From 8fe826c1ceb5536fbb8c89346f297d8bc9c69554 Mon Sep 17 00:00:00 2001 From: "METANEOCORTEX\\Kotti" Date: Mon, 16 Nov 2026 11:51:41 +0100 Subject: [PATCH 1/3] chore: agent-trail insights --- agent-trail/architecture/codebase-and-conventions.md | 2 ++ agent-trail/playbooks/maintenance.md | 2 ++ 2 files changed, 4 insertions(+) diff --git a/agent-trail/architecture/codebase-and-conventions.md b/agent-trail/architecture/codebase-and-conventions.md index f5b93c2ba..176c2cf31 100644 --- a/agent-trail/architecture/codebase-and-conventions.md +++ b/agent-trail/architecture/codebase-and-conventions.md @@ -85,6 +85,8 @@ Before an approved vendored-library change, consult the [Lexilla patch registry] ### Dynamic string/path buffer lifetime +`StrgCreate(NULL)` can return a valid handle without allocating its text buffer; `StrgGet(h) == NULL` before initialization is normal, not proof of allocation failure. Initialize the fresh handle with `StrgReset(h, text)` and check its result (`> 0`) before using the text ([source](../../src/DynStrg.c#L432-L473): `StrgCreate`, `StrgReset`, `StrgGet`). + Never use a pointer returned by `Path_WriteAccessBuf()` / `StrgWriteAccessBuf()` after an operation that may reallocate or swap the same handle's buffer. Examples include `Path_CanonicalizeEx`, `Path_Swap` / `StrgSwap`, `Path_ExpandEnvStrings` / `ExpandEnvironmentStrgs`, `Path_Append` / `Path_Reset`, `StrgCat` / `StrgInsert` / `StrgFormat` / `StrgReset`, and `Path_NormalizeEx` / `Path_AbsoluteFromApp` / `Path_RelativeToApp`. - For read-only access afterward, use `Path_Get(h)` / `StrgGet(h)`. diff --git a/agent-trail/playbooks/maintenance.md b/agent-trail/playbooks/maintenance.md index 876e4d251..672a5a732 100644 --- a/agent-trail/playbooks/maintenance.md +++ b/agent-trail/playbooks/maintenance.md @@ -36,6 +36,8 @@ Output: implemented behavior, extension points, evidence, and explicit exclusion 4. Run against unchanged production source first; record stub/integration boundaries. 5. Change the expectation only as part of the requested behavior change. +Prefer linking self-contained production helpers where practical. Test doubles must preserve observable allocation/lifecycle and return-value contracts; a more permissive double can hide a regression. The [WebTemplate runner](../../test/TestWebTemplates.ps1) links production `DynStrg.c` to exercise the real [lazy-string initialization contract](../architecture/codebase-and-conventions.md#dynamic-stringpath-buffer-lifetime). + Stop if isolation requires product refactoring or desktop interaction could disturb another user. Recommend a manual reproduction record or separately approved test seam. Output: characterized boundary, cases, stubs, baseline outcome, and uncovered integration. From 531af3edf4c76e1ad30bfe1ded734edb851b413b Mon Sep 17 00:00:00 2001 From: "METANEOCORTEX\\Kotti" Date: Mon, 16 Nov 2026 11:53:45 +0100 Subject: [PATCH 2/3] chore: add agent test helpers --- test/TestLexerDialogSorting.cpp | 115 ++++++ test/TestLexerDialogSorting.ps1 | 28 ++ test/TestWebTemplates.cpp | 654 ++++++++++++++++++++++++++++++++ test/TestWebTemplates.ps1 | 59 +++ 4 files changed, 856 insertions(+) create mode 100644 test/TestLexerDialogSorting.cpp create mode 100644 test/TestLexerDialogSorting.ps1 create mode 100644 test/TestWebTemplates.cpp create mode 100644 test/TestWebTemplates.ps1 diff --git a/test/TestLexerDialogSorting.cpp b/test/TestLexerDialogSorting.cpp new file mode 100644 index 000000000..5de7a394f --- /dev/null +++ b/test/TestLexerDialogSorting.cpp @@ -0,0 +1,115 @@ +#include +#include +#include +#include +#include + +#define COUNTOF(a) static_cast(sizeof(a) / sizeof((a)[0])) +#define MIDSZ_BUFFER 256 + +struct EDITLEXER { + int resID; + LPCWSTR pszName; +}; +using PEDITLEXER = EDITLEXER*; + +static EDITLEXER lexStandard = { 0, L"Standard" }; +static EDITLEXER lexStandard2nd = { 0, L"Standard2nd" }; +static EDITLEXER lexTEXT = { 0, L"Text" }; +static EDITLEXER lexZulu = { 1, L"Zulu" }; +static EDITLEXER lexBravo = { 0, L"Bravo" }; +static EDITLEXER lexBravo2 = { 0, L"bravo" }; +static EDITLEXER lexAPDL = { 0, L"ANSYS APDL" }; +static PEDITLEXER g_pLexArray[] = { + &lexStandard, &lexStandard2nd, &lexTEXT, &lexZulu, &lexBravo, &lexBravo2, &lexAPDL +}; + +static bool GetLngString(int resID, LPWSTR name, int capacity) +{ + return resID == 1 && SUCCEEDED(StringCchCopyW(name, capacity, L"Alpha")); +} + +#include "LexerDialogSorting.inc" + +static int failures = 0; + +static void Check(bool condition, const char* message) +{ + if (!condition) { + std::printf("FAIL: %s\n", message); + ++failures; + } +} + +int main() +{ + INITCOMMONCONTROLSEX controls = { sizeof(controls), ICC_TREEVIEW_CLASSES | ICC_LISTVIEW_CLASSES }; + if (!InitCommonControlsEx(&controls)) { + return 1; + } + HWND parent = CreateWindowExW(0, L"STATIC", L"", 0, 0, 0, 100, 100, nullptr, nullptr, nullptr, nullptr); + HWND tree = CreateWindowExW(0, WC_TREEVIEWW, L"", WS_CHILD, 0, 0, 100, 100, parent, nullptr, nullptr, nullptr); + HWND list = CreateWindowExW(0, WC_LISTVIEWW, L"", WS_CHILD | LVS_REPORT, 0, 0, 100, 100, parent, nullptr, nullptr, nullptr); + if (!parent || !tree || !list) { + if (parent) { DestroyWindow(parent); } + return 1; + } + + for (PEDITLEXER lexer : g_pLexArray) { + WCHAR name[MIDSZ_BUFFER] = {}; + Style_GetLexerDisplayName(lexer, name, COUNTOF(name)); + TVINSERTSTRUCT root = {}; + root.hInsertAfter = TVI_LAST; + root.item.mask = TVIF_PARAM | TVIF_TEXT; + root.item.lParam = reinterpret_cast(lexer); + root.item.pszText = name; + HTREEITEM node = TreeView_InsertItem(tree, &root); + LPCWSTR styleNames[] = { L"Zulu style", L"Alpha style" }; + for (LPCWSTR style : styleNames) { + TVINSERTSTRUCT child = {}; + child.hParent = node; + child.hInsertAfter = TVI_LAST; + child.item.mask = TVIF_TEXT; + child.item.pszText = const_cast(style); + TreeView_InsertItem(tree, &child); + } + LVITEM item = {}; + item.mask = LVIF_PARAM | LVIF_TEXT; + item.iItem = ListView_GetItemCount(list); + item.lParam = reinterpret_cast(lexer); + item.pszText = name; + ListView_InsertItem(list, &item); + } + + HTREEITEM current = _FindLexerTreeItem(tree, &lexAPDL); + TreeView_SelectItem(tree, current); + TV_SORTCB sort = { nullptr, _CompareLexersByDisplayName, 0 }; + Check(TreeView_SortChildrenCB(tree, &sort, FALSE), "tree sorting succeeds"); + Check(ListView_SortItems(list, _CompareLexersByDisplayName, 0), "list sorting succeeds"); + PEDITLEXER expected[] = { + &lexStandard, &lexStandard2nd, &lexTEXT, &lexZulu, &lexAPDL, &lexBravo, &lexBravo2 + }; + HTREEITEM node = TreeView_GetRoot(tree); + for (int i = 0; i < COUNTOF(expected); ++i) { + Check(node == _FindLexerTreeItem(tree, expected[i]), "tree order pins first three and sorts localized names"); + Check(_GetListViewLexer(list, i) == expected[i], "list order matches tree order"); + WCHAR styleName[MIDSZ_BUFFER] = {}; + TVITEM child = {}; + child.mask = TVIF_TEXT; + child.hItem = TreeView_GetChild(tree, node); + child.pszText = styleName; + child.cchTextMax = COUNTOF(styleName); + TreeView_GetItem(tree, &child); + Check(lstrcmpW(styleName, L"Zulu style") == 0, "style children retain their original order"); + node = TreeView_GetNextSibling(tree, node); + } + Check(TreeView_GetSelection(tree) == current, "tree preserves current selection"); + Check(_FindLexerTreeItem(tree, &lexAPDL) == current, "current-lexer lookup ignores sorted position"); + Check(_FindLexerTreeItem(tree, nullptr) == nullptr, "missing tree lexer returns null"); + Check(_GetListViewLexer(list, -1) == nullptr, "no list selection returns null"); + Check(_GetLexerIndex(_GetListViewLexer(list, 4)) == 6, "APDL default retains its original index, not display index"); + Check(g_pLexArray[6] == &lexAPDL && g_pLexArray[3] == &lexZulu, "sorting does not reorder registration array"); + DestroyWindow(parent); + std::printf("Lexer sorting: %s\n", failures ? "FAILED" : "PASS"); + return failures ? 1 : 0; +} diff --git a/test/TestLexerDialogSorting.ps1 b/test/TestLexerDialogSorting.ps1 new file mode 100644 index 000000000..a332ed0a1 --- /dev/null +++ b/test/TestLexerDialogSorting.ps1 @@ -0,0 +1,28 @@ +$ErrorActionPreference = 'Stop' +$root = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path +$temp = Join-Path ([IO.Path]::GetTempPath()) ('np3-lexer-sorting-' + [guid]::NewGuid()) +[void](New-Item -ItemType Directory $temp) +try { + $source = Get-Content (Join-Path $root 'src\Styles.c') -Raw + $functions = foreach ($name in @('Style_GetLexerDisplayName', '_GetLexerIndex', '_CompareLexersByDisplayName', '_FindLexerTreeItem', '_GetListViewLexer')) { + $start = [regex]::Match($source, "(?m)^(?:static )?[^\r\n]+ \b$name\(") + if (!$start.Success) { throw "Missing $name" } + $body = $source.IndexOf('{', $start.Index) + $end = [regex]::Match($source.Substring($body), '(?m)^}') + if (!$end.Success) { throw "Missing $name end" } + $source.Substring($start.Index, $body + $end.Index + 1 - $start.Index) + } + Set-Content (Join-Path $temp 'LexerDialogSorting.inc') ($functions -join "`n") -Encoding ascii + $vswhere = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe" + $vs = & $vswhere -latest -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath + if (!$vs) { throw 'Visual C++ build tools not found' } + $vcvars = Join-Path $vs 'VC\Auxiliary\Build\vcvars64.bat' + $test = Join-Path $PSScriptRoot 'TestLexerDialogSorting.cpp' + & $env:ComSpec /d /c "call `"$vcvars`" >nul && cd /d `"$temp`" && cl /nologo /EHsc /std:c++20 /W4 /WX /DUNICODE /D_UNICODE /I`"$temp`" `"$test`" /Fe:TestLexerDialogSorting.exe /link comctl32.lib shlwapi.lib user32.lib" + if ($LASTEXITCODE -ne 0) { throw 'Lexer-sorting test build failed' } + & (Join-Path $temp 'TestLexerDialogSorting.exe') + if ($LASTEXITCODE -ne 0) { throw 'Lexer-sorting tests failed' } +} finally { + Get-ChildItem $temp -File | Remove-Item + Remove-Item $temp +} diff --git a/test/TestWebTemplates.cpp b/test/TestWebTemplates.cpp new file mode 100644 index 000000000..89380215f --- /dev/null +++ b/test/TestWebTemplates.cpp @@ -0,0 +1,654 @@ +#include +#include +#include +#include +#include "..\language\common_res.h" +#include "..\src\TypeDefs.h" +extern "C" { +#include "..\src\DynStrg.h" +} +#include +#include +#include +#include + +// Production DynStrg and extracted settings/commands; INI, editor, paths, saves and launches are stubbed. +struct TestPath { + std::wstring value; +}; +constexpr size_t PATHLONG_MAX_CCH = 0x8000; +#define COUNTOF(value) _countof(value) + +PATHS_T Paths{}; +SETTINGS_T Settings{}; +SETTINGS2_T Settings2{}; +GLOBALS_T Globals{}; +std::wstring selection; +std::wstring savedPath; +bool saveResult = true; +bool fileExists = true; +bool launchResult = true; +HRESULT conversionError = S_OK; +HRESULT associationError = S_OK; +bool associationFailureOnRead = false; +bool browserQueriesOnly = true; +int associationQueries = 0; +bool bufferGrowthFails = false; +size_t writableCapacity = 0; +int oversizedBufferCalls = 0; +int conversionCalls = 0; +std::wstring defaultBrowserClass; +int saves = 0; +DWORD reportedError = 0; +int reportedErrors = 0; +bool enabled[CMD_WEBACTION3 + 1]{}; +std::map iniValues; +struct Launch { + std::wstring file; + std::wstring arguments; + std::wstring directory; + std::wstring className; + ULONG mask; +}; +std::vector launches; + +bool StrIsNotEmpty(LPCWSTR value) { return value && *value; } +LPWSTR TestStrgWriteAccessBuf(HSTRINGW value, size_t count) { + LPWSTR buffer = bufferGrowthFails ? nullptr : StrgWriteAccessBuf(value, count); + writableCapacity = buffer ? StrgGetAllocLength(value) : 0; + return buffer; +} +#define StrgWriteAccessBuf TestStrgWriteAccessBuf +void ExpandEnvironmentStrgs(HSTRINGW value, bool) { + const DWORD count = ExpandEnvironmentStringsW(StrgGet(value), nullptr, 0); + std::vector buffer(count); + ExpandEnvironmentStringsW(StrgGet(value), buffer.data(), count); + StrgReset(value, buffer.data()); +} +std::wstring& PathValue(HPATHL value) { return reinterpret_cast(value)->value; } +LPCWSTR Path_Get(HPATHL value) { return PathValue(value).c_str(); } +bool Path_IsEmpty(HPATHL value) { return PathValue(value).empty(); } +bool Path_IsNotEmpty(HPATHL value) { return !Path_IsEmpty(value); } +size_t Path_GetLength(HPATHL value) { return PathValue(value).size(); } +bool Path_IsExistingFile(HPATHL) { return fileExists; } +HPATHL Path_Copy(HPATHL value) { return reinterpret_cast(new TestPath{ PathValue(value) }); } +void Path_Release(HPATHL value) { delete reinterpret_cast(value); } +void Path_RemoveFileSpec(HPATHL value) { + std::wstring& path = PathValue(value); + const size_t at = path.find_last_of(L'\\'); + path.resize(at == 2 ? 3 : at); +} +size_t EditGetSelectedText(LPWSTR buffer, size_t count) { + if (selection.size() >= count) { buffer[0] = L'\0'; return 0; } + wcscpy_s(buffer, count, selection.c_str()); + return selection.size() + 1; +} +bool FileSave(int) { + ++saves; + if (saveResult && !savedPath.empty()) { PathValue(Paths.CurrentFile) = savedPath; } + return saveResult; +} +DWORD InfoBoxLastError(LPCWSTR, DWORD error) { + ++reportedErrors; + reportedError = error ? error : GetLastError(); + return reportedError; +} +BOOL TestShellExecuteExW(SHELLEXECUTEINFOW* info) { + launches.push_back({ info->lpFile, info->lpParameters ? info->lpParameters : L"", + info->lpDirectory ? info->lpDirectory : L"", + info->lpClass ? info->lpClass : L"", info->fMask }); + if (!launchResult) { SetLastError(ERROR_FILE_NOT_FOUND); } + return launchResult; +} +#define ShellExecuteExW TestShellExecuteExW +HRESULT TestUrlCreateFromPathW(PCWSTR path, PWSTR url, DWORD* count, DWORD flags) { + ++conversionCalls; + if (*count > writableCapacity) { ++oversizedBufferCalls; return E_OUTOFMEMORY; } + return FAILED(conversionError) ? conversionError : UrlCreateFromPathW(path, url, count, flags); +} +#define UrlCreateFromPathW TestUrlCreateFromPathW +HRESULT TestAssocQueryStringW(ASSOCF flags, ASSOCSTR kind, LPCWSTR association, + LPCWSTR extra, LPWSTR output, DWORD* count) { + ++associationQueries; + browserQueriesOnly = browserQueriesOnly && (flags & ASSOCF_IS_PROTOCOL) != 0 + && kind == ASSOCSTR_PROGID && std::wstring(association) == L"https" && !extra; + if (FAILED(associationError) && (!associationFailureOnRead || output)) { + return associationError; + } + const DWORD required = static_cast(defaultBrowserClass.size() + 1); + if (!output) { *count = required; return S_FALSE; } + if (*count > writableCapacity) { ++oversizedBufferCalls; return E_OUTOFMEMORY; } + if (*count < required) { *count = required; return E_POINTER; } + wcscpy_s(output, *count, defaultBrowserClass.c_str()); + *count = required; + return S_OK; +} +#define AssocQueryStringW TestAssocQueryStringW +void EnableCmd(HMENU menu, int id, bool state) { + enabled[id] = state; + EnableMenuItem(menu, id, MF_BYCOMMAND | (state ? MF_ENABLED : MF_GRAYED)); +} +void IniSectionGetStringNoQuotes(int, LPCWSTR key, LPCWSTR fallback, LPWSTR output, size_t count) { + const auto value = iniValues.find(key); + wcscpy_s(output, count, value == iniValues.end() ? fallback : value->second.c_str()); +} +void LoadWebTemplateSettings() { + const int IniSecSettings2 = 0; + WCHAR pPathBuffer[PATHLONG_MAX_CCH]{}; +#include "WebTemplateSettings.inc" +} + +#include "WebTemplateHelpers.inc" + +void RunAction(int iLoWParam = CMD_WEBACTION1) { + switch (iLoWParam) { +#include "WebTemplateCommands.inc" + } +} +void UpdateMenuOn(HMENU hmenu, bool se, bool mrs, bool bPosInSel, bool bIsHLink) { +#include "WebTemplateMenu.inc" +} +void UpdateMenu(bool se, bool mrs, bool bPosInSel, bool bIsHLink) { + UpdateMenuOn(Globals.hMainMenu, se, mrs, bPosInSel, bIsHLink); +} +HMENU CreateActionMenu(bool mainMenu) { + HMENU actions = CreatePopupMenu(); + AppendMenuW(actions, MF_STRING, CMD_WEBACTION1, + mainMenu ? L"Web Template &1\tCtrl+Shift+1" : L"Open Web Action 1"); + AppendMenuW(actions, MF_STRING, CMD_WEBACTION2, + mainMenu ? L"Web Template &2\tCtrl+Shift+2" : L"Open Web Action 2"); + AppendMenuW(actions, MF_STRING, CMD_WEBACTION3, + mainMenu ? L"Preview current file &3\tCtrl+Shift+3" : L"Preview current file"); + if (!mainMenu) { return actions; } + HMENU file = CreatePopupMenu(); + HMENU root = CreateMenu(); + AppendMenuW(file, MF_POPUP, reinterpret_cast(actions), L"Launch"); + AppendMenuW(root, MF_POPUP, reinterpret_cast(file), L"File"); + return root; +} +std::wstring MenuText(HMENU menu, UINT id) { + WCHAR text[SMALL_BUFFER]{}; + GetMenuStringW(menu, id, text, COUNTOF(text), MF_BYCOMMAND); + return text; +} + +int wmain() { + TestPath current{}; + HSTRINGW first = StrgCreate(nullptr), second = StrgCreate(nullptr), third = StrgCreate(nullptr); + HSTRINGW app = StrgCreate(nullptr), arguments = StrgCreate(nullptr); + Paths.CurrentFile = reinterpret_cast(¤t); + Settings2.WebTemplate1 = first; + Settings2.WebTemplate2 = second; + Settings2.WebTemplate3 = third; + Settings2.HyperlinkShellExURLWithApp = app; + Settings2.HyperlinkShellExURLCmdLnArgs = arguments; + Globals.hMainMenu = CreateActionMenu(true); + const auto reset = [&] { + current.value = L"C:\\Notes\\readme.md"; + StrgReset(first, L"https://example.test/?q=%s"); + StrgReset(second, L"https://example.test/second/%s"); + StrgReset(third, L"${FILE_URL}"); + StrgReset(app, L""); + StrgReset(arguments, L"\"${URL}\""); + Settings2.WebTmpl1MenuName[0] = Settings2.WebTmpl2MenuName[0] = Settings2.WebTmpl3MenuName[0] = L'\0'; + iniValues.clear(); + Settings.SaveBeforeRunningTools = false; + selection = L"selected text"; + savedPath.clear(); + saveResult = fileExists = launchResult = true; + conversionError = S_OK; + associationError = S_OK; + associationFailureOnRead = false; + browserQueriesOnly = true; + associationQueries = 0; + bufferGrowthFails = false; + writableCapacity = 0; + oversizedBufferCalls = 0; + conversionCalls = 0; + defaultBrowserClass = L"NP3.TestHttpsBrowser"; + saves = 0; + reportedError = 0; + reportedErrors = 0; + launches.clear(); + }; + int failures = 0; + int checks = 0; + const auto check = [&](const char* name, bool result) { + ++checks; + if (!result) { std::cerr << "FAIL: " << name << '\n'; ++failures; } + }; + reset(); + RunAction(); + check("legacy selection URL and shell fallback", launches.size() == 1 + && launches[0].file == L"https://example.test/?q=selected text" + && launches[0].directory == L"C:\\Notes" && launches[0].arguments.empty() + && launches[0].className.empty() && associationQueries == 0 + && launches[0].mask == SEE_MASK_NOZONECHECKS); + reset(); + selection = L"x"; + RunAction(); + check("legacy single-character selection", launches.size() == 1 + && launches[0].file == L"https://example.test/?q=x"); + reset(); + selection.clear(); + RunAction(); + check("legacy empty selection", launches.empty()); + for (const WCHAR delimiter : { L'\r', L'\n', L'\t' }) { + reset(); + selection = std::wstring(L"first") + delimiter + L"second"; + RunAction(); + check("legacy selection delimiter truncation", launches.size() == 1 + && launches[0].file == L"https://example.test/?q=first"); + } + reset(); + StrgReset(app, L"C:\\Browser\\browser.exe"); + StrgReset(arguments, L"--new-window \"${URL}\""); + Settings.SaveBeforeRunningTools = true; + RunAction(CMD_WEBACTION2); + check("second slot and shared browser arguments", launches.size() == 1 + && launches[0].file == StrgGet(app) + && launches[0].arguments == L"--new-window \"https://example.test/second/selected text\"" + && launches[0].mask == SEE_MASK_DEFAULT); + check("legacy templates do not save", saves == 0); + StrgReset(arguments, L""); + launches.clear(); + RunAction(); + check("legacy empty arguments remain unchanged", launches.size() == 1 + && launches[0].arguments.empty() && reportedError == 0); + StrgReset(arguments, L"--new-window"); + launches.clear(); + RunAction(); + check("legacy arguments without URL token remain unchanged", launches.size() == 1 + && launches[0].arguments == L"--new-window" && reportedError == 0 && saves == 0); + UpdateMenu(false, false, true, false); + check("legacy menu selection available", enabled[CMD_WEBACTION1] && enabled[CMD_WEBACTION2]); + UpdateMenu(true, false, false, false); + check("legacy menu selection required", !enabled[CMD_WEBACTION1] && !enabled[CMD_WEBACTION2]); + UpdateMenu(false, false, true, true); + check("legacy hyperlink context unavailable", !enabled[CMD_WEBACTION1] && !enabled[CMD_WEBACTION2]); + + const auto preview = [&] { + reset(); + StrgReset(first, L"${FILE_URL}"); + StrgReset(app, L"C:\\Browser\\browser.exe"); + selection.clear(); + }; + preview(); + RunAction(); + check("file preview without selection", launches.size() == 1 + && launches[0].file == StrgGet(app) + && launches[0].arguments == L"\"file:///C:/Notes/readme.md\"" + && launches[0].directory == L"C:\\Notes" && saves == 0 + && launches[0].className.empty() && associationQueries == 0); + preview(); + StrgReset(arguments, L""); + RunAction(); + check("empty browser arguments still pass the file URL", launches.size() == 1 + && launches[0].arguments == L"file:///C:/Notes/readme.md"); + preview(); + StrgReset(arguments, L"--new-window"); + Settings.SaveBeforeRunningTools = true; + RunAction(); + check("browser arguments without URL token rejected before saving", + launches.empty() && saves == 0 && reportedError == ERROR_INVALID_PARAMETER); + preview(); + selection = L"unrelated selected text"; + RunAction(); + check("file preview ignores selection", launches.size() == 1 + && launches[0].arguments == L"\"file:///C:/Notes/readme.md\""); + UpdateMenu(true, true, false, true); + check("file menu ignores selection and hyperlink context", enabled[CMD_WEBACTION1] && !enabled[CMD_WEBACTION2]); + StrgReset(first, L"https://example.test/?q=%s"); + StrgReset(second, L"${FILE_URL}"); + UpdateMenu(true, false, false, false); + RunAction(CMD_WEBACTION2); + check("second slot has independent file mode", !enabled[CMD_WEBACTION1] && enabled[CMD_WEBACTION2] + && launches.size() == 2 && launches[1].arguments == L"\"file:///C:/Notes/readme.md\""); + preview(); + current.value.clear(); + Settings.SaveBeforeRunningTools = true; + UpdateMenu(true, false, false, false); + RunAction(); + check("untitled is disabled and never saves or launches", !enabled[CMD_WEBACTION1] && saves == 0 && launches.empty()); + preview(); + StrgReset(app, L""); + UpdateMenu(true, true, false, true); + RunAction(); + check("default browser receives file URL without using its extension association", + enabled[CMD_WEBACTION1] && launches.size() == 1 && associationQueries == 2 && browserQueriesOnly + && launches[0].file == L"file:///C:/Notes/readme.md" + && launches[0].arguments.empty() && launches[0].directory == L"C:\\Notes" + && launches[0].className == defaultBrowserClass + && (launches[0].mask & SEE_MASK_CLASSNAME) != 0); + preview(); + StrgReset(app, L""); + StrgReset(arguments, L"--ignored-explicit-browser-arguments"); + StrgReset(first, L"https://example.test/?q=%s"); + StrgReset(second, L"${FILE_URL}"); + current.value = L"C:\\Notes\\a b#100%.md"; + Settings.SaveBeforeRunningTools = true; + RunAction(CMD_WEBACTION2); + check("second slot defaults to browser and ignores explicit-app arguments", + launches.size() == 1 && saves == 1 && reportedError == 0 + && launches[0].file == L"file:///C:/Notes/a%20b%23100%25.md" + && launches[0].arguments.empty() && launches[0].className == defaultBrowserClass); + preview(); + StrgReset(app, L""); + current.value.clear(); + Settings.SaveBeforeRunningTools = true; + UpdateMenu(true, false, false, false); + RunAction(); + check("untitled default-browser preview is disabled without querying or saving", + !enabled[CMD_WEBACTION1] && associationQueries == 0 && saves == 0 && launches.empty()); + for (const bool failOnRead : { false, true }) { + preview(); + StrgReset(app, L""); + associationError = HRESULT_FROM_WIN32(ERROR_NO_ASSOCIATION); + associationFailureOnRead = failOnRead; + Settings.SaveBeforeRunningTools = true; + RunAction(); + check("failed browser lookup reports error without save or extension fallback", + launches.empty() && saves == 0 && reportedError == ERROR_NO_ASSOCIATION + && associationQueries == (failOnRead ? 2 : 1)); + } + preview(); + StrgReset(app, L""); + associationError = E_POINTER; + associationFailureOnRead = true; + Settings.SaveBeforeRunningTools = true; + RunAction(); + check("undersized browser-query buffer reports a buffer error, not invalid pointer", + launches.empty() && saves == 0 && reportedError == ERROR_INSUFFICIENT_BUFFER + && associationQueries == 2); + reset(); + bufferGrowthFails = true; + Settings.SaveBeforeRunningTools = true; + RunAction(CMD_WEBACTION3); + check("failed browser buffer allocation aborts before saving or calling Windows", + launches.empty() && saves == 0 && associationQueries == 1 && oversizedBufferCalls == 0 + && reportedError == ERROR_OUTOFMEMORY && reportedErrors == 1); + preview(); + Settings.SaveBeforeRunningTools = true; + check("unallocated file-preview target reports failure before saving or conversion", + !_PrepareWebTemplate(StrgGet(first), nullptr) && saves == 0 && conversionCalls == 0 + && reportedError == ERROR_OUTOFMEMORY && reportedErrors == 1); + preview(); + Settings.SaveBeforeRunningTools = true; + HSTRINGW freshTarget = StrgCreate(nullptr); + const bool lazyTarget = freshTarget && !StrgGet(freshTarget); + const bool preparedTarget = _PrepareWebTemplate(StrgGet(first), freshTarget); + check("fresh production string initializes before allocation is checked", + lazyTarget && preparedTarget && std::wstring(StrgGet(freshTarget)) == L"file:///C:/Notes/readme.md" + && saves == 1 && conversionCalls == 1 && reportedErrors == 0); + StrgDestroy(freshTarget); + preview(); + StrgReset(app, L""); + defaultBrowserClass.clear(); + RunAction(); + check("empty default browser class never uses file association", + launches.empty() && reportedError == ERROR_NO_ASSOCIATION); + preview(); + StrgReset(app, L""); + launchResult = false; + RunAction(); + check("default browser launch failure reports once without shell error UI or association retry", + launches.size() == 1 && launches[0].className == defaultBrowserClass + && reportedError == ERROR_FILE_NOT_FOUND && reportedErrors == 1 + && (launches[0].mask & SEE_MASK_FLAG_NO_UI) != 0); + preview(); + associationError = HRESULT_FROM_WIN32(ERROR_NO_ASSOCIATION); + RunAction(); + check("explicit browser overrides missing default browser", + launches.size() == 1 && launches[0].file == StrgGet(app) && associationQueries == 0 + && reportedError == 0); + preview(); + StrgReset(first, L""); + UpdateMenu(false, false, true, false); + RunAction(); + check("empty template is disabled", !enabled[CMD_WEBACTION1] && launches.empty()); + preview(); + Settings.SaveBeforeRunningTools = true; + RunAction(); + check("save accepted or declined previews disk version", saves == 1 && launches.size() == 1 + && launches[0].arguments == L"\"file:///C:/Notes/readme.md\""); + preview(); + Settings.SaveBeforeRunningTools = true; + savedPath = L"D:\\Moved\\new name.md"; + RunAction(); + check("path and working directory reacquired after save", saves == 1 && launches.size() == 1 + && launches[0].arguments == L"\"file:///D:/Moved/new%20name.md\"" + && launches[0].directory == L"D:\\Moved"); + preview(); + Settings.SaveBeforeRunningTools = true; + saveResult = false; + RunAction(); + check("save cancellation or failure aborts", saves == 1 && launches.empty()); + preview(); + fileExists = false; + RunAction(); + check("missing disk file reports error without launch", + launches.empty() && reportedError == ERROR_FILE_NOT_FOUND); + preview(); + bufferGrowthFails = true; + RunAction(CMD_WEBACTION3); + check("failed URL buffer growth never passes its requested size to Windows", + launches.empty() && conversionCalls == 0 && oversizedBufferCalls == 0 + && reportedError == ERROR_OUTOFMEMORY && reportedErrors == 1); + + for (const auto* path : { L"C:\\Notes\\a b#100%.md", L"C:\\Notes\\\u00E4\u4E2D.md", + L"\\\\server\\share\\a b#100%.md", L"C:\\Notes\\%TEMP%.md", + L"C:\\Notes\\${FILE_URL}-${URL}.md" }) { + preview(); + current.value = path; + RunAction(); + bool matches = false; + if (launches.size() == 1 && launches[0].arguments.size() > 2) { + const std::wstring url = launches[0].arguments.substr(1, launches[0].arguments.size() - 2); + WCHAR decoded[INTERNET_MAX_URL_LENGTH]{}; + DWORD count = COUNTOF(decoded); + matches = SUCCEEDED(PathCreateFromUrlW(url.c_str(), decoded, &count, 0)) + && current.value == decoded; + if (current.value.find(L'#') != std::wstring::npos) { + matches = matches && url.find(L"%23") != std::wstring::npos; + } + if (current.value.find(L'%') != std::wstring::npos) { + matches = matches && url.find(L"%25") != std::wstring::npos; + } + } + check("file URL preserves special characters and UNC identity", matches); + } + preview(); + StrgReset(first, L"${FILE_URL}#again=${FILE_URL}"); + RunAction(); + check("all file tokens replaced", launches.size() == 1 + && launches[0].arguments == L"\"file:///C:/Notes/readme.md#again=file:///C:/Notes/readme.md\""); + preview(); + SetEnvironmentVariableW(L"NP3_WEBTEMPLATE_TEST", L"prefix%20/"); + StrgReset(first, L"%NP3_WEBTEMPLATE_TEST%${FILE_URL}"); + current.value = L"C:\\Notes\\%NP3_WEBTEMPLATE_TEST%.md"; + RunAction(); + check("environment expansion precedes literal URL insertion", launches.size() == 1 + && launches[0].arguments == L"\"prefix%20/file:///C:/Notes/%25NP3_WEBTEMPLATE_TEST%25.md\""); + SetEnvironmentVariableW(L"NP3_WEBTEMPLATE_TEST", nullptr); + preview(); + StrgReset(first, L"${FILE_URL}?selection=%s"); + Settings.SaveBeforeRunningTools = true; + RunAction(); + check("mixed file and selection templates rejected before save", + launches.empty() && saves == 0 && reportedError == ERROR_INVALID_PARAMETER); + for (const auto& path : { std::wstring(L"\\\\?\\C:\\Notes\\readme.md"), + std::wstring(L"\\\\?\\UNC\\server\\share\\readme.md"), + std::wstring(L"C:\\") + std::wstring(INTERNET_MAX_URL_LENGTH, L'x') }) { + preview(); + current.value = path; + RunAction(); + check("unsupported path fails without truncated launch", launches.empty() && reportedError != 0); + } + preview(); + conversionError = E_POINTER; + RunAction(); + check("conversion failure reports error without launch", + launches.empty() && reportedError == ERROR_INSUFFICIENT_BUFFER); + preview(); + conversionError = E_FAIL; + RunAction(); + WCHAR errorMessage[512]{}; + check("generic conversion error remains displayable", launches.empty() && reportedError != 0 + && FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, + reportedError, 0, errorMessage, COUNTOF(errorMessage), nullptr) != 0); + preview(); + launchResult = false; + RunAction(); + check("explicit browser launch failure reports once without shell error UI or fallback", + launches.size() == 1 && reportedError == ERROR_FILE_NOT_FOUND && reportedErrors == 1 + && (launches[0].mask & SEE_MASK_FLAG_NO_UI) != 0); + + preview(); + wcscpy_s(Settings2.WebTmpl1MenuName, L"Preview current file"); + wcscpy_s(Settings2.WebTmpl2MenuName, L"Search selected text"); + UpdateMenu(true, false, false, false); + check("main Launch menu uses configured labels and shortcuts", + MenuText(Globals.hMainMenu, CMD_WEBACTION1) == L"Preview current file\tCtrl+Shift+1" + && MenuText(Globals.hMainMenu, CMD_WEBACTION2) == L"Search selected text\tCtrl+Shift+2"); + HMENU context = CreateActionMenu(false); + EnableMenuItem(context, CMD_WEBACTION1, MF_BYCOMMAND | MF_GRAYED); + EnableMenuItem(context, CMD_WEBACTION2, MF_BYCOMMAND | MF_GRAYED); + UpdateMenuOn(context, true, true, false, true); + check("context menu uses configured labels and shortcuts", + MenuText(context, CMD_WEBACTION1) == L"Preview current file\tCtrl+Shift+1" + && MenuText(context, CMD_WEBACTION2) == L"Search selected text\tCtrl+Shift+2"); + check("real popup enables file mode without selection and keeps selection mode disabled", + GetMenuState(context, CMD_WEBACTION1, MF_BYCOMMAND) == MF_ENABLED + && (GetMenuState(context, CMD_WEBACTION2, MF_BYCOMMAND) & MF_GRAYED) != 0); + UpdateMenuOn(context, true, false, false, false); + check("repeated popup initialization does not duplicate shortcuts", + MenuText(context, CMD_WEBACTION1) == L"Preview current file\tCtrl+Shift+1"); + StrgReset(first, L"https://example.test/?q=%s"); + StrgReset(second, L"${FILE_URL}"); + UpdateMenuOn(context, true, false, false, false); + check("second popup slot independently enables file mode without selection", + (GetMenuState(context, CMD_WEBACTION1, MF_BYCOMMAND) & MF_GRAYED) != 0 + && GetMenuState(context, CMD_WEBACTION2, MF_BYCOMMAND) == MF_ENABLED); + StrgReset(app, L""); + UpdateMenuOn(context, true, false, false, false); + check("popup enables default-browser file preview without selection or association queries", + GetMenuState(context, CMD_WEBACTION2, MF_BYCOMMAND) == MF_ENABLED && associationQueries == 0); + DestroyMenu(context); + + preview(); + HMENU originalMain = Globals.hMainMenu; + Globals.hMainMenu = CreateActionMenu(true); + ModifyMenuW(Globals.hMainMenu, CMD_WEBACTION1, MF_BYCOMMAND | MF_STRING, + CMD_WEBACTION1, L"Webvorlage &1\tStrg+Umschalt+1"); + context = CreateActionMenu(false); + ModifyMenuW(context, CMD_WEBACTION1, MF_BYCOMMAND | MF_STRING, CMD_WEBACTION1, L"Webaktion 1"); + UpdateMenu(true, false, false, false); + UpdateMenuOn(context, true, false, false, false); + check("default labels and localized shortcut suffixes are preserved", + MenuText(Globals.hMainMenu, CMD_WEBACTION1) == L"Webvorlage &1\tStrg+Umschalt+1" + && MenuText(context, CMD_WEBACTION1) == L"Webaktion 1\tStrg+Umschalt+1"); + DestroyMenu(context); + DestroyMenu(Globals.hMainMenu); + Globals.hMainMenu = originalMain; + + reset(); + LoadWebTemplateSettings(); + selection.clear(); + UpdateMenu(true, true, false, true); + RunAction(CMD_WEBACTION3); + check("third slot defaults to browser file preview without changing search availability", + !enabled[CMD_WEBACTION1] && !enabled[CMD_WEBACTION2] && enabled[CMD_WEBACTION3] + && launches.size() == 1 && launches[0].file == L"file:///C:/Notes/readme.md" + && launches[0].className == defaultBrowserClass && launches[0].arguments.empty()); + launches.clear(); + selection = L"needle"; + RunAction(CMD_WEBACTION1); + RunAction(CMD_WEBACTION2); + check("configuration keeps the original first and second search defaults", + launches.size() == 2 && launches[0].file == L"https://google.com/search?q=needle" + && launches[1].file == L"https://en.wikipedia.org/w/index.php?search=needle" && saves == 0); + reset(); + iniValues[L"WebTemplate1"] = L"${FILE_URL}"; + iniValues[L"WebTmpl1MenuName"] = L"Existing preview"; + iniValues[L"WebTemplate2"] = L"https://custom.test/%s"; + LoadWebTemplateSettings(); + selection.clear(); + RunAction(CMD_WEBACTION1); + RunAction(CMD_WEBACTION3); + check("existing first-slot preview is preserved rather than migrated", + std::wstring(StrgGet(first)) == L"${FILE_URL}" && std::wstring(Settings2.WebTmpl1MenuName) == L"Existing preview" + && std::wstring(StrgGet(second)) == L"https://custom.test/%s" && launches.size() == 2 + && launches[0].file == launches[1].file && launches[1].className == defaultBrowserClass); + reset(); + iniValues[L"WebTemplate3"] = L"https://example.test/third/%s"; + LoadWebTemplateSettings(); + Settings.SaveBeforeRunningTools = true; + selection = L"third"; + UpdateMenu(false, false, true, false); + RunAction(CMD_WEBACTION3); + check("third slot can be configured as a selection template without acquiring save behavior", + enabled[CMD_WEBACTION3] && launches.size() == 1 + && launches[0].file == L"https://example.test/third/third" && saves == 0 && associationQueries == 0); + reset(); + current.value.clear(); + Settings.SaveBeforeRunningTools = true; + UpdateMenu(true, false, false, false); + RunAction(CMD_WEBACTION3); + check("untitled third-slot preview never saves, queries or launches", + !enabled[CMD_WEBACTION3] && saves == 0 && associationQueries == 0 && launches.empty()); + reset(); + iniValues[L"WebTemplate3"] = L""; + LoadWebTemplateSettings(); + UpdateMenu(false, false, true, false); + RunAction(CMD_WEBACTION3); + check("explicitly empty third template stays disabled", + !enabled[CMD_WEBACTION3] && launches.empty() && associationQueries == 0); + reset(); + StrgReset(app, L"C:\\Browser\\browser.exe"); + RunAction(CMD_WEBACTION3); + check("third slot honors the shared explicit browser override", + launches.size() == 1 && launches[0].file == StrgGet(app) + && launches[0].arguments == L"\"file:///C:/Notes/readme.md\"" && associationQueries == 0); + + reset(); + LoadWebTemplateSettings(); + selection.clear(); + originalMain = Globals.hMainMenu; + Globals.hMainMenu = LoadMenuW(GetModuleHandleW(nullptr), MAKEINTRESOURCEW(IDR_MUI_MAINMENU)); + context = LoadMenuW(GetModuleHandleW(nullptr), MAKEINTRESOURCEW(IDR_MUI_POPUPMENU)); + UpdateMenu(true, false, false, false); + UpdateMenuOn(context, true, false, false, false); + check("production main and context menus expose default preview with its shortcut", + MenuText(Globals.hMainMenu, CMD_WEBACTION3) == L"Preview current file &3\tCtrl+Shift+3" + && MenuText(context, CMD_WEBACTION3) == L"Preview current file\tCtrl+Shift+3" + && GetMenuState(Globals.hMainMenu, CMD_WEBACTION3, MF_BYCOMMAND) == MF_ENABLED + && GetMenuState(context, CMD_WEBACTION3, MF_BYCOMMAND) == MF_ENABLED); + HACCEL accelerators = LoadAcceleratorsW(GetModuleHandleW(nullptr), MAKEINTRESOURCEW(IDR_MAINWND)); + const int acceleratorCount = CopyAcceleratorTableW(accelerators, nullptr, 0); + std::vector keys(acceleratorCount); + CopyAcceleratorTableW(accelerators, keys.data(), acceleratorCount); + int previewShortcuts = 0; + for (const auto& key : keys) { + if (key.key == L'3' && (key.fVirt & (FVIRTKEY | FCONTROL | FSHIFT | FALT)) == (FVIRTKEY | FCONTROL | FSHIFT)) { + ++previewShortcuts; + RunAction(key.cmd); + } + } + check("production Ctrl+Shift+3 accelerator dispatches preview without a conflicting binding", + previewShortcuts == 1 && launches.size() == 1 && launches[0].file == L"file:///C:/Notes/readme.md" + && launches[0].className == defaultBrowserClass); + iniValues[L"WebTmpl3MenuName"] = L"My Markdown preview"; + LoadWebTemplateSettings(); + UpdateMenu(true, false, false, false); + UpdateMenuOn(context, true, false, false, false); + check("third-slot configured name and shortcut reach both production menus", + MenuText(Globals.hMainMenu, CMD_WEBACTION3) == L"My Markdown preview\tCtrl+Shift+3" + && MenuText(context, CMD_WEBACTION3) == L"My Markdown preview\tCtrl+Shift+3"); + DestroyMenu(context); + DestroyMenu(Globals.hMainMenu); + Globals.hMainMenu = originalMain; + DestroyMenu(Globals.hMainMenu); + for (const auto handle : { first, second, third, app, arguments }) { StrgDestroy(handle); } + std::cout << checks << " WebTemplate checks, " << failures << " failures\n"; + return failures ? 1 : 0; +} diff --git a/test/TestWebTemplates.ps1 b/test/TestWebTemplates.ps1 new file mode 100644 index 000000000..c148d1344 --- /dev/null +++ b/test/TestWebTemplates.ps1 @@ -0,0 +1,59 @@ +param( + [string]$Notepad3Source +) + +$ErrorActionPreference = 'Stop' +$root = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path +if (!$Notepad3Source) { $Notepad3Source = Join-Path $root 'src\Notepad3.c' } +$temp = Join-Path ([IO.Path]::GetTempPath()) ('np3-webtemplates-' + [guid]::NewGuid()) +[void](New-Item -ItemType Directory $temp) +try { + $source = Get-Content $Notepad3Source -Raw + $helpers = foreach ($signature in @('static bool _IsFileWebTemplate(', 'static bool _CanRunWebTemplate(', 'static void _UpdateWebTemplateMenu(', 'static HRESULT _GetDefaultBrowserClass(', 'static bool _PrepareWebTemplate(')) { + $start = $source.IndexOf($signature, [StringComparison]::Ordinal) + if ($start -lt 0) { continue } + $body = $source.IndexOf('{', $start) + $end = [regex]::Match($source.Substring($body), '(?m)^}') + if (!$end.Success) { throw "Missing end of $signature" } + $source.Substring($start, $body + $end.Index + 1 - $start) + } + Set-Content (Join-Path $temp 'WebTemplateHelpers.inc') ($helpers -join "`n") -Encoding utf8 + + $start = $source.IndexOf(' case CMD_WEBACTION1:', [StringComparison]::Ordinal) + if ($start -lt 0) { throw 'Missing WebTemplate command cases' } + $commands = $source.Substring($start) + $end = [regex]::Match($commands, '(?m)^ break;') + if (!$end.Success) { throw 'Missing WebTemplate command end' } + Set-Content (Join-Path $temp 'WebTemplateCommands.inc') $commands.Substring(0, $end.Index + $end.Length) -Encoding utf8 + $menu = [regex]::Matches($source, '(?m)^ _UpdateWebTemplateMenu\(hmenu,[^\r\n]*') + if ($menu.Count -ne 1) { throw 'Missing shared WebTemplate menu update' } + Set-Content (Join-Path $temp 'WebTemplateMenu.inc') ($menu.Value -join "`n") -Encoding utf8 + $config = Get-Content (Join-Path $root 'src\Config\Config.cpp') -Raw + $start = $config.IndexOf(' IniSectionGetStringNoQuotes(IniSecSettings2, L"WebTemplate1"', [StringComparison]::Ordinal) + if ($start -lt 0) { throw 'Missing WebTemplate settings block' } + $end = $config.IndexOf(' Settings2.LexerSQLNumberSignAsComment', $start, [StringComparison]::Ordinal) + if ($end -lt 0) { throw 'Missing WebTemplate settings block end' } + Set-Content (Join-Path $temp 'WebTemplateSettings.inc') $config.Substring($start, $end - $start) -Encoding utf8 + $resource = Get-Content (Join-Path $root 'src\Notepad3.rc') -Raw + $accelerators = [regex]::Match($resource, '(?ms)^IDR_MAINWND ACCELERATORS\r?\nBEGIN.*?^END') + if (!$accelerators.Success) { throw 'Missing main accelerator table' } + $menuResource = Join-Path $root 'language\np3_en_us\menu_en_us.rc' + Set-Content (Join-Path $temp 'WebTemplateResources.rc') @( + '#include "resource.h"' + "#include `"$($menuResource.Replace('\', '\\'))`"" + $accelerators.Value + ) -Encoding utf8 + + $vswhere = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe" + $vs = & $vswhere -latest -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath + if (!$vs) { throw 'Visual C++ build tools not found' } + $vcvars = Join-Path $vs 'VC\Auxiliary\Build\vcvars64.bat' + $test = Join-Path $PSScriptRoot 'TestWebTemplates.cpp' + & $env:ComSpec /d /c "call `"$vcvars`" >nul && cd /d `"$temp`" && rc /nologo /I`"$root\src`" /fo WebTemplateResources.res WebTemplateResources.rc && cl /nologo /c /utf-8 /W4 /WX /DUNICODE /D_UNICODE /I`"$root\scintilla\include`" `"$root\src\DynStrg.c`" /Fo:DynStrg.obj && cl /nologo /EHsc /std:c++20 /utf-8 /W4 /WX /DUNICODE /D_UNICODE /I`"$temp`" /I`"$root\scintilla\include`" `"$test`" DynStrg.obj WebTemplateResources.res /Fe:TestWebTemplates.exe /link shlwapi.lib user32.lib" + if ($LASTEXITCODE -ne 0) { throw 'WebTemplate test build failed' } + & (Join-Path $temp 'TestWebTemplates.exe') + if ($LASTEXITCODE -ne 0) { throw 'WebTemplate tests failed' } +} finally { + Get-ChildItem $temp -File | Remove-Item + Remove-Item $temp +} From 5eb21320820c94b2b5afda3b958f13faad33a47a Mon Sep 17 00:00:00 2001 From: "METANEOCORTEX\\Kotti" Date: Mon, 16 Nov 2026 13:39:34 +0100 Subject: [PATCH 3/3] Add configurable zoom tooltip positioning Support corner, caret, and pixel-based mouse modes with safe fallbacks. Add regression tests and configuration/agent documentation. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- Build/Notepad3.ini | 1 + .../architecture/scintilla-api-usage.md | 12 +- agent-trail/index.md | 2 +- readme/config/Configuration.md | 10 + src/Config/Config.cpp | 5 + src/Notepad3.c | 157 ++++++- src/TypeDefs.h | 8 + test/TestZoomTooltipPosition.cpp | 393 ++++++++++++++++++ test/TestZoomTooltipPosition.ps1 | 37 ++ 9 files changed, 609 insertions(+), 16 deletions(-) create mode 100644 test/TestZoomTooltipPosition.cpp create mode 100644 test/TestZoomTooltipPosition.ps1 diff --git a/Build/Notepad3.ini b/Build/Notepad3.ini index 5412b20bd..b51dbf385 100644 --- a/Build/Notepad3.ini +++ b/Build/Notepad3.ini @@ -97,6 +97,7 @@ SettingsVersion=5 ;AtomicFileSave=true ;ExitOnESCSkipLevel=2 ;ZoomTooltipTimeout=3200 ;in [msec] +;ZoomTooltipPosition=0 ;(0=upper-left, 1=upper-right, 2=near caret, 3=near mouse) ;WrapAroundTooltipTimeout=2000 ;in [msec] ;LargeIconScalePrecent=150 ;DarkModeBkgColor=0x1F1F1F diff --git a/agent-trail/architecture/scintilla-api-usage.md b/agent-trail/architecture/scintilla-api-usage.md index e4adcaabb..62a48e72a 100644 --- a/agent-trail/architecture/scintilla-api-usage.md +++ b/agent-trail/architecture/scintilla-api-usage.md @@ -1,8 +1,8 @@ # Scintilla API Usage Notes -When to read: Replacing home-grown `Edit.c` code with Scintilla messages +When to read: Scintilla message replacements, zoom call-tip positioning, or Scintilla upgrades -Verified constraints to check before replacing home-grown `src\Edit.c` code with a Scintilla message. Wrapper rules are in [Codebase and conventions](codebase-and-conventions.md). +Constraints for first-party Scintilla calls and native zoom call-tip positioning. Wrapper rules are in [Codebase and conventions](codebase-and-conventions.md). ## Reading document text @@ -18,6 +18,14 @@ Verified constraints to check before replacing home-grown `src\Edit.c` code with | `SCI_REPLACETARGETMINIMAL` | `Sci_ReplaceTargetTestChgHist` (`src\SciCall.h`) uses it only when change history is enabled; otherwise a full `SCI_REPLACETARGET`. | | `SCI_MARKERNEXT` / `SCI_MARKERPREVIOUS` | Do not see change-history markers (21-24); `_MarkerNext` / `_MarkerPrevious` in `src\Edit.c` scan linearly for them. | +## Native zoom call-tip discovery + +- Preserve the combined discovery checks in `_FindZoomCallTip` / `_PositionZoomCallTip`: enumerate the current thread's windows, match the editor's top-level owner (`GA_ROOT`), require class `CallTip`, and compare window extra bytes at offset zero with the nonzero `SciCall_GetDirectPointer()`. Windows promotes the child editor's popup owner to its top-level window; owner matching alone cannot distinguish editors sharing that window ([implementation](../../src/Notepad3.c#L13665-L13692)). +- Never cache the popup HWND across cancellation. `CallTip::CallTipCancel` destroys the native window; rediscover it after showing the next tip ([lifetime](../../scintilla/src/CallTip.cxx#L312-L317)). +- Revalidate this contract when upgrading Scintilla: the class and instance-pointer storage are vendored Win32 internals, not a public popup-HWND API. `ScintillaWin::CTWndProc` stores the instance via `SetWindowPointer`, whose offset-zero storage must still agree with `SCI_GETDIRECTPOINTER` ([creation](../../scintilla/win32/ScintillaWin.cxx#L4134-L4147), [storage](../../scintilla/win32/PlatWin.cxx#L78-L84), [direct pointer](../../scintilla/win32/ScintillaWin.cxx#L2278-L2279)). + +Ownership isolation and popup recreation are exercised by `test\TestZoomTooltipPosition.cpp` using hidden Win32 windows. Those checks do not establish visible rendering or physical monitor-DPI behavior. + ## Wrapped but unused `SciCall_IsRangeWord` exists in `src\SciCall.h` but has no caller. See [open questions](../open-questions.md) before using it to replace delimiter scans. diff --git a/agent-trail/index.md b/agent-trail/index.md index 2bec1791e..22c27f7e0 100644 --- a/agent-trail/index.md +++ b/agent-trail/index.md @@ -52,7 +52,7 @@ The checker rejects broken/escaping links, undeclared topic folders, mismatched | Bug fix, small feature, characterization test, focused check, or doc proposal | [Maintenance playbooks](playbooks/maintenance.md) (read only the relevant procedure) | | Instructions, routing, adapters, skills, or the docs checker | [Review the agent docs](playbooks/docs-review.md) | | Menus, commands, source layout, coding conventions, buffers | [Codebase and conventions](architecture/codebase-and-conventions.md) | -| Replacing home-grown `Edit.c` code with Scintilla messages | [Scintilla API usage](architecture/scintilla-api-usage.md) | +| Scintilla message replacements, zoom call-tip positioning, or Scintilla upgrades | [Scintilla API usage](architecture/scintilla-api-usage.md) | | Build, MSBuild, CI, test scripts, Python scripting | [Windows build and test](build-and-test/windows-build-and-test.md) | | `Edit.c` load/save, atomic save, file watching, Open/MRU dialogs | [File I/O](domain/file-io.md) | | Any Win32 file/path call on `HPATHL` | [PathLib](domain/pathlib.md) | diff --git a/readme/config/Configuration.md b/readme/config/Configuration.md index 450b67d0a..3a9f1f18b 100644 --- a/readme/config/Configuration.md +++ b/readme/config/Configuration.md @@ -552,6 +552,16 @@ Controls ESC key behavior: Zoom tooltip display duration in milliseconds. Set to `0` to disable. +#### `ZoomTooltipPosition=0` + +Selects where the temporary zoom tooltip appears: +- **0** (default): Existing upper-left placement. +- **1**: Upper-right of the editor text area, constrained to the monitor work area. +- **2**: Near the caret, if it is visible; otherwise upper-left. +- **3**: Near the mouse pointer inside the editor text area, including space beyond line endings and empty editor space. If the pointer is outside that area or its coordinates cannot be obtained, use the visible caret, then upper-left. + +Caret mode is text-anchored. Mouse mode uses pixel coordinates and does not require virtual-space selection to be enabled. It offsets the tooltip from the sampled pointer, flips to the other side near right/bottom edges, and constrains placement to the editor text area and monitor work area where the tooltip fits. The pointer is sampled when the tooltip appears; the tooltip does not follow later mouse movement. Missing or unsupported values use `0`. `ZoomTooltipTimeout` still controls the display duration. + #### `WrapAroundTooltipTimeout=2000` Search wrap-around tooltip duration in milliseconds. Set to `0` to disable. diff --git a/src/Config/Config.cpp b/src/Config/Config.cpp index 18f20d663..01fff457a 100644 --- a/src/Config/Config.cpp +++ b/src/Config/Config.cpp @@ -1499,6 +1499,11 @@ void LoadSettings() Settings2.ZoomTooltipTimeout = clampi(IniSectionGetInt(IniSecSettings2, L"ZoomTooltipTimeout", 3200), 0, 10000); + Settings2.ZoomTooltipPosition = IniSectionGetInt(IniSecSettings2, L"ZoomTooltipPosition", ZOOM_TOOLTIP_UPPER_LEFT); + if (Settings2.ZoomTooltipPosition < ZOOM_TOOLTIP_UPPER_LEFT || Settings2.ZoomTooltipPosition > ZOOM_TOOLTIP_MOUSE) { + Settings2.ZoomTooltipPosition = ZOOM_TOOLTIP_UPPER_LEFT; + } + Settings2.WrapAroundTooltipTimeout = clampi(IniSectionGetInt(IniSecSettings2, L"WrapAroundTooltipTimeout", 2000), 0, 10000); Settings2.LargeIconScalePrecent = clampi(IniSectionGetInt(IniSecSettings2, L"LargeIconScalePrecent", 150), 100, 1000); diff --git a/src/Notepad3.c b/src/Notepad3.c index f4939ed34..d1f72cd86 100644 --- a/src/Notepad3.c +++ b/src/Notepad3.c @@ -13624,6 +13624,113 @@ int NP3_GetZoomPercent() return Globals.iZoomPercent; } +//============================================================================= +// +// _GetZoomCallTipViewport() +// +static bool _GetZoomCallTipViewport(RECT* rcViewport) +{ + if (!GetClientRect(Globals.hwndEdit, rcViewport)) { + return false; + } + rcViewport->left += SciCall_GetMarginLeft(); + int const margins = SciCall_GetMargins(); + for (int i = 0; i < margins; ++i) { + rcViewport->left += SciCall_GetMarginWidthN(i); + } + rcViewport->right -= SciCall_GetMarginRight(); + return !IsRectEmpty(rcViewport); +} + + +//============================================================================= +// +// _GetZoomCallTipCaret() +// +static DocPos _GetZoomCallTipCaret(const RECT* rcViewport) +{ + DocPos const pos = SciCall_GetCurrentPos(); + if (!SciCall_GetLineVisible(SciCall_LineFromPosition(pos))) { + return -1; + } + POINT const pt = { (LONG)SciCall_PointXFromPosition(pos), (LONG)SciCall_PointYFromPosition(pos) }; + return PtInRect(rcViewport, pt) ? pos : -1; +} + + +//============================================================================= +// +// _FindZoomCallTip() +// +static BOOL CALLBACK _FindZoomCallTip(HWND hwnd, LPARAM lParam) +{ + if (GetWindow(hwnd, GW_OWNER) != GetAncestor(Globals.hwndEdit, GA_ROOT)) { + return TRUE; + } + WCHAR className[32] = { L'\0' }; + if (!GetClassName(hwnd, className, COUNTOF(className)) || lstrcmp(className, L"CallTip") != 0) { + return TRUE; + } + // Scintilla's CTWndProc stores the editor's direct pointer in window extra bytes. + LONG_PTR const sci = (LONG_PTR)SciCall_GetDirectPointer(); + if (!sci || GetWindowLongPtr(hwnd, 0) != sci) { + return TRUE; + } + + *(HWND*)lParam = hwnd; + return FALSE; +} + + +//============================================================================= +// +// _PositionZoomCallTip() +// +static void _PositionZoomCallTip(const RECT* rcViewport, const POINT* mouse) +{ + HWND hwnd = NULL; + EnumThreadWindows(GetCurrentThreadId(), _FindZoomCallTip, (LPARAM)&hwnd); + + RECT rcTip; + if (!hwnd || !GetWindowRect(hwnd, &rcTip)) { + return; + } + + LONG const width = rcTip.right - rcTip.left; + LONG const height = rcTip.bottom - rcTip.top; + int const gap = ScaleIntToDPI(Globals.hwndEdit, 4); + LONG x = max_l(rcViewport->left, rcViewport->right - width - gap); + LONG y = min_l(rcViewport->top + gap, max_l(rcViewport->top, rcViewport->bottom - height)); + RECT rcPosition = { x, y, x + width, y + height }; + if (mouse) { + SetRect(&rcPosition, mouse->x, mouse->y, mouse->x + 1, mouse->y + 1); + } + MONITORINFO mi = { sizeof(mi) }; + bool const hasMonitor = GetMonitorInfo(MonitorFromRect(&rcPosition, MONITOR_DEFAULTTONEAREST), &mi); + if (mouse) { + RECT bounds = *rcViewport; + if (hasMonitor && !IntersectRect(&bounds, rcViewport, &mi.rcWork)) { + bounds = mi.rcWork; + } + x = mouse->x + gap; + y = mouse->y + gap; + if (x + width > bounds.right) { + x = mouse->x - width - gap; + } + if (y + height > bounds.bottom) { + y = mouse->y - height - gap; + } + x = max_l(bounds.left, min_l(x, bounds.right - width)); + y = max_l(bounds.top, min_l(y, bounds.bottom - height)); + } + if (hasMonitor) { + x = max_l(mi.rcWork.left, min_l(x, mi.rcWork.right - width)); + y = max_l(mi.rcWork.top, min_l(y, mi.rcWork.bottom - height)); + } + SetWindowPos(hwnd, NULL, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOOWNERZORDER); +} + + //============================================================================= // // ShowZoomCallTip() @@ -13632,23 +13739,47 @@ void ShowZoomCallTip() { static char chToolTip[64] = { '\0' }; int const delayClr = Settings2.ZoomTooltipTimeout; - if (delayClr >= (_MQ_TIMER_CYCLE << 3)) { - - StringCchPrintfA(chToolTip, COUNTOF(chToolTip), "Zoom: %i%%", NP3_GetZoomPercent()); - - DocPos const iPos = SciCall_PositionFromLine(SciCall_GetFirstVisibleLine()); + if (delayClr < (_MQ_TIMER_CYCLE << 3)) { + Sci_CallTipCancelEx(); + return; + } - int const iXOff = SciCall_GetXOffset(); + StringCchPrintfA(chToolTip, COUNTOF(chToolTip), "Zoom: %i%%", NP3_GetZoomPercent()); + + RECT rcViewport; + bool const hasViewport = Settings2.ZoomTooltipPosition != ZOOM_TOOLTIP_UPPER_LEFT && _GetZoomCallTipViewport(&rcViewport); + POINT origin = { 0, 0 }; + bool const hasScreenViewport = hasViewport && ClientToScreen(Globals.hwndEdit, &origin); + POINT mouse = { 0, 0 }; + bool const atMouse = hasScreenViewport && Settings2.ZoomTooltipPosition == ZOOM_TOOLTIP_MOUSE + && GetCursorPos(&mouse) && ScreenToClient(Globals.hwndEdit, &mouse) && PtInRect(&rcViewport, mouse); + DocPos pos = -1; + if (atMouse) { + pos = SciCall_GetCurrentPos(); // Only used to create and measure the popup. + } else if (hasViewport && (Settings2.ZoomTooltipPosition == ZOOM_TOOLTIP_CARET || Settings2.ZoomTooltipPosition == ZOOM_TOOLTIP_MOUSE)) { + pos = _GetZoomCallTipCaret(&rcViewport); + } + bool const useLegacyAnchor = pos < 0; + int const iXOff = SciCall_GetXOffset(); + if (useLegacyAnchor) { + pos = SciCall_PositionFromLine(SciCall_GetFirstVisibleLine()); SciCall_SetXOffset(-4); // move away from margin - - SciCall_CallTipSetPosition(true); // show above - SciCall_CallTipShow(iPos, chToolTip); - + } + SciCall_CallTipSetPosition(useLegacyAnchor); + SciCall_CallTipShow(pos, chToolTip); + if (useLegacyAnchor) { SciCall_SetXOffset(iXOff); - _DelayClearCallTip(delayClr); - } else { - Sci_CallTipCancelEx(); } + + if (hasScreenViewport && (Settings2.ZoomTooltipPosition == ZOOM_TOOLTIP_UPPER_RIGHT || atMouse)) { + OffsetRect(&rcViewport, origin.x, origin.y); + if (atMouse) { + mouse.x += origin.x; + mouse.y += origin.y; + } + _PositionZoomCallTip(&rcViewport, atMouse ? &mouse : NULL); + } + _DelayClearCallTip(delayClr); } diff --git a/src/TypeDefs.h b/src/TypeDefs.h index 6de8cbcea..0c1c8f5ca 100644 --- a/src/TypeDefs.h +++ b/src/TypeDefs.h @@ -232,6 +232,13 @@ typedef enum FR_STATES { FND_NOP = 0, NXT_NOT_FND, NXT_FND, NXT_WRP_FND, PRV_NOT typedef enum FR_UPD_MODES { FRMOD_IGNORE = 0, FRMOD_NORM, FRMOD_WRAPED } FR_UPD_MODES; typedef enum WIN_DISPL_MODE { WINDSPMOD_AUTO = 0, WINDSPMOD_DARK, WINDSPMOD_LIGHT } WIN_DISPL_MODE; +typedef enum ZOOM_TOOLTIP_POSITION { + ZOOM_TOOLTIP_UPPER_LEFT = 0, + ZOOM_TOOLTIP_UPPER_RIGHT = 1, + ZOOM_TOOLTIP_CARET = 2, + ZOOM_TOOLTIP_MOUSE = 3 +} ZOOM_TOOLTIP_POSITION; + //==== Statusbar ============================================================== typedef WCHAR prefix_t[MICRO_BUFFER]; @@ -834,6 +841,7 @@ typedef struct SETTINGS2_T { bool DiscardOnClosingUntitledPasteBoard; int ExitOnESCSkipLevel; int ZoomTooltipTimeout; + int ZoomTooltipPosition; int WrapAroundTooltipTimeout; int LargeIconScalePrecent; int DarkModeHiglightContrast; diff --git a/test/TestZoomTooltipPosition.cpp b/test/TestZoomTooltipPosition.cpp new file mode 100644 index 000000000..5e97bc2c0 --- /dev/null +++ b/test/TestZoomTooltipPosition.cpp @@ -0,0 +1,393 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#define COUNTOF(a) static_cast(sizeof(a) / sizeof((a)[0])) + +#include "ZoomTooltipPositionTypes.inc" + +using DocPos = ptrdiff_t; +using DocLn = ptrdiff_t; + +static struct { + HWND hwndEdit; +} Globals; +static struct { + int ZoomTooltipTimeout = 3200; + int ZoomTooltipPosition = ZOOM_TOOLTIP_UPPER_LEFT; +} Settings2; +static char editorInstance; +static UINT testDpi = 96; +static DocPos currentPos = 400; +static POINT caretPoint = { 100, 100 }; +static bool caretLineVisible = true; +static POINT mouseScreen = {}; +static bool cursorValid = true; +static int cursorQueries = 0; +static bool conversionValid = true; +static int xOffset = 120; +static int offsetChanges = 0; +static int tipShows = 0; +static int tipCancels = 0; +static DocPos shownPos = -1; +static int shownXOffset = 0; +static bool tipAbove = false; +static char shownText[64] = {}; +static int delayCalls = 0; +static LONG64 scheduledDelay = 0; +static HWND simulatedTip = nullptr; +static bool hasIniValue = false; +static int iniValue = 0; +static RECT monitorWorkArea = { -32000, -32000, 32000, 32000 }; +static bool monitorInfoValid = true; + +static const char* SciCall_GetDirectPointer() +{ + return &editorInstance; +} + +static long max_l(long x, long y) +{ + return x > y ? x : y; +} + +static long min_l(long x, long y) +{ + return x < y ? x : y; +} + +static int ScaleIntToDPI(HWND, int value) { return MulDiv(value, testDpi, USER_DEFAULT_SCREEN_DPI); } +static int SciCall_GetMarginLeft() { return 6; } +static int SciCall_GetMarginRight() { return 8; } +static int SciCall_GetMargins() { return 2; } +static int SciCall_GetMarginWidthN(int index) { return index == 0 ? 20 : 12; } +static DocPos SciCall_GetCurrentPos() { return currentPos; } +static DocLn SciCall_LineFromPosition(DocPos pos) { return pos / 10; } +static bool SciCall_GetLineVisible(DocLn) { return caretLineVisible; } +static int SciCall_PointXFromPosition(DocPos) { return caretPoint.x; } +static int SciCall_PointYFromPosition(DocPos) { return caretPoint.y; } +static DocLn SciCall_GetFirstVisibleLine() { return 10; } +static DocPos SciCall_PositionFromLine(DocLn line) { return line * 10; } +static int SciCall_GetXOffset() { return xOffset; } +static void SciCall_SetXOffset(int offset) { xOffset = offset; ++offsetChanges; } +static int NP3_GetZoomPercent() { return 125; } +static void SciCall_CallTipSetPosition(bool above) { tipAbove = above; } +static void SciCall_CallTipCancel() { ++tipCancels; } +#define Sci_CallTipCancelEx() { SciCall_CallTipCancel(); SciCall_CallTipSetPosition(false); } + +static void SciCall_CallTipShow(DocPos pos, const char* text) +{ + ++tipShows; + shownPos = pos; + shownXOffset = xOffset; + StringCchCopyA(shownText, COUNTOF(shownText), text); + if (simulatedTip) { + SetWindowPos(simulatedTip, nullptr, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE); + } +} + +static void _DelayClearCallTip(LONG64 delay) +{ + ++delayCalls; + scheduledDelay = delay; +} + +static BOOL TestGetCursorPos(LPPOINT point) +{ + ++cursorQueries; + *point = mouseScreen; + return cursorValid; +} + +static BOOL TestScreenToClient(HWND hwnd, LPPOINT point) +{ + return conversionValid && ScreenToClient(hwnd, point); +} + +static HMONITOR TestMonitorFromRect(const RECT*, DWORD) +{ + return reinterpret_cast(1); +} + +static BOOL TestGetMonitorInfo(HMONITOR, LPMONITORINFO info) +{ + info->rcWork = monitorWorkArea; + return monitorInfoValid; +} + +static constexpr LPCWSTR IniSecSettings2 = L"Settings2"; +static int IniSectionGetInt(LPCWSTR section, LPCWSTR key, int fallback) +{ + return hasIniValue && std::wcscmp(section, L"Settings2") == 0 && std::wcscmp(key, L"ZoomTooltipPosition") == 0 + ? iniValue : fallback; +} + +#define GetCursorPos TestGetCursorPos +#define ScreenToClient TestScreenToClient +#define MonitorFromRect TestMonitorFromRect +#define GetMonitorInfoW TestGetMonitorInfo +#include "ZoomTooltipPosition.inc" +#undef GetMonitorInfoW +#undef MonitorFromRect +#undef ScreenToClient +#undef GetCursorPos + +static int failures = 0; +static int checks = 0; + +static void Check(bool condition, const char* message) +{ + ++checks; + if (!condition) { + std::printf("FAIL: %s\n", message); + ++failures; + } +} + +static bool HasRect(HWND hwnd, LONG x, LONG y, LONG width, LONG height) +{ + RECT rc = {}; + return GetWindowRect(hwnd, &rc) && rc.left == x && rc.top == y + && rc.right - rc.left == width && rc.bottom - rc.top == height; +} + +static void ResetObservation() +{ + cursorQueries = 0; + offsetChanges = 0; + tipShows = 0; + tipCancels = 0; + delayCalls = 0; + shownPos = -1; +} + +static void CheckShown(DocPos pos, bool above, int expectedOffsetChanges, const char* message) +{ + Check(tipShows == 1 && tipCancels == 0 && shownPos == pos && tipAbove == above + && xOffset == 120 && offsetChanges == expectedOffsetChanges && currentPos == 400 + && delayCalls == 1 && scheduledDelay == Settings2.ZoomTooltipTimeout, message); +} + +static void SetMouseClient(LONG x, LONG y) +{ + mouseScreen = { x, y }; + ClientToScreen(Globals.hwndEdit, &mouseScreen); +} + +int main() +{ + WNDCLASSEXW wc = { sizeof(wc) }; + wc.lpfnWndProc = DefWindowProcW; + wc.cbWndExtra = sizeof(LONG_PTR); + wc.hInstance = GetModuleHandleW(nullptr); + wc.lpszClassName = L"CallTip"; + if (!RegisterClassExW(&wc)) { + return 1; + } + + HWND owner = CreateWindowExW(0, L"STATIC", L"", WS_POPUP, 100, 100, 640, 480, nullptr, nullptr, wc.hInstance, nullptr); + Globals.hwndEdit = CreateWindowExW(0, L"STATIC", L"", WS_CHILD, 0, 0, 640, 480, owner, nullptr, wc.hInstance, nullptr); + HWND tip = CreateWindowExW(0, L"CallTip", L"", WS_POPUP, 0, 0, 96, 24, Globals.hwndEdit, nullptr, wc.hInstance, nullptr); + HWND otherTip = CreateWindowExW(0, L"CallTip", L"", WS_POPUP, 10, 20, 96, 24, Globals.hwndEdit, nullptr, wc.hInstance, nullptr); + HWND otherOwner = CreateWindowExW(0, L"STATIC", L"", WS_POPUP, 0, 0, 100, 100, nullptr, nullptr, wc.hInstance, nullptr); + HWND foreignTip = CreateWindowExW(0, L"CallTip", L"", WS_POPUP, 30, 40, 96, 24, otherOwner, nullptr, wc.hInstance, nullptr); + if (!owner || !Globals.hwndEdit || !tip || !otherTip || !otherOwner || !foreignTip) { + return 1; + } + SetWindowLongPtrW(tip, 0, reinterpret_cast(&editorInstance)); + SetWindowLongPtrW(foreignTip, 0, reinterpret_cast(&editorInstance)); + + Check(GetWindow(tip, GW_OWNER) == owner, "child editor's popup is owned by its top-level window"); + HWND const active = GetActiveWindow(); + HWND const focus = GetFocus(); + RECT bounds = { 150, 110, 730, 560 }; + _PositionZoomCallTip(&bounds, nullptr); + Check(HasRect(tip, 630, 114, 96, 24), "positions measured popup at upper-right in screen coordinates"); + Check(HasRect(otherTip, 10, 20, 96, 24), "does not move another editor's call-tip"); + Check(HasRect(foreignTip, 30, 40, 96, 24), "does not move a call-tip with another owner"); + Check(!IsWindowVisible(tip), "positioning does not show a hidden popup"); + Check(GetActiveWindow() == active && GetFocus() == focus, "positioning does not activate or focus"); + + bounds = { -500, 60, -450, 80 }; + _PositionZoomCallTip(&bounds, nullptr); + Check(HasRect(tip, -500, 60, 96, 24), "oversized popup clamps to viewport left without resizing"); + DestroyWindow(tip); + tip = CreateWindowExW(0, L"CallTip", L"", WS_POPUP, 0, 0, 120, 32, Globals.hwndEdit, nullptr, wc.hInstance, nullptr); + SetWindowLongPtrW(tip, 0, reinterpret_cast(&editorInstance)); + bounds = { 150, 110, 730, 560 }; + testDpi = 192; + _PositionZoomCallTip(&bounds, nullptr); + Check(HasRect(tip, 602, 118, 120, 32), "finds recreated popup and scales inset for new DPI and dimensions"); + testDpi = 96; + + monitorWorkArea = { 0, 0, 700, 500 }; + bounds = { 150, -20, 850, 560 }; + _PositionZoomCallTip(&bounds, nullptr); + Check(HasRect(tip, 580, 0, 120, 32), "upper-right remains in monitor work area when editor extends off-screen"); + monitorInfoValid = false; + _PositionZoomCallTip(&bounds, nullptr); + Check(HasRect(tip, 726, -16, 120, 32), "failed monitor query retains viewport placement"); + monitorInfoValid = true; + monitorWorkArea = { -32000, -32000, 32000, 32000 }; + + LoadZoomTooltipPosition(); + Check(Settings2.ZoomTooltipPosition == ZOOM_TOOLTIP_UPPER_LEFT, "missing INI value preserves upper-left default"); + hasIniValue = true; + for (int value : { -1, 0, 1, 2, 3, 4, INT_MAX }) { + iniValue = value; + LoadZoomTooltipPosition(); + Check(Settings2.ZoomTooltipPosition == (value >= 0 && value <= 3 ? value : 0), "loads supported modes and rejects invalid INI values"); + } + + RECT viewport = {}; + Check(_GetZoomCallTipViewport(&viewport) && viewport.left == 38 && viewport.right == 632 + && viewport.top == 0 && viewport.bottom == 480, "text viewport excludes all margins"); + Settings2.ZoomTooltipPosition = ZOOM_TOOLTIP_UPPER_LEFT; + ResetObservation(); + ShowZoomCallTip(); + CheckShown(100, true, 2, "default retains legacy anchor, offset workaround, restored scrolling, and timer"); + Check(shownXOffset == -4 && std::strcmp(shownText, "Zoom: 125%") == 0, "legacy offset at display and percentage formatting are unchanged"); + + Settings2.ZoomTooltipPosition = ZOOM_TOOLTIP_CARET; + ResetObservation(); + ShowZoomCallTip(); + CheckShown(400, false, 0, "visible caret anchors below text without modifying horizontal scrolling"); + caretPoint.y = -1; + ResetObservation(); + ShowZoomCallTip(); + CheckShown(100, true, 2, "caret vertically off-screen falls back to upper-left"); + caretPoint = { 37, 100 }; + ResetObservation(); + ShowZoomCallTip(); + CheckShown(100, true, 2, "caret horizontally scrolled out of text area falls back"); + caretPoint = { 632, 100 }; + ResetObservation(); + ShowZoomCallTip(); + CheckShown(100, true, 2, "caret at right clipping edge falls back"); + caretPoint = { 100, 480 }; + ResetObservation(); + ShowZoomCallTip(); + CheckShown(100, true, 2, "caret below bottom clipping edge falls back"); + caretPoint = { 100, 100 }; + caretLineVisible = false; + ResetObservation(); + ShowZoomCallTip(); + CheckShown(100, true, 2, "folded caret line falls back even if coordinate query looks visible"); + caretLineVisible = true; + + Settings2.ZoomTooltipPosition = ZOOM_TOOLTIP_MOUSE; + simulatedTip = tip; + POINT origin = { 0, 0 }; + ClientToScreen(Globals.hwndEdit, &origin); + SetMouseClient(300, 240); + ResetObservation(); + ShowZoomCallTip(); + CheckShown(400, false, 0, "mouse mode measures popup without changing caret or horizontal scrolling"); + Check(HasRect(tip, origin.x + 304, origin.y + 244, 120, 32), "mouse mode uses sampled pixel coordinates with an inset"); + Check(cursorQueries == 1, "mouse positioning samples the pointer only once"); + caretPoint.x = -100; + ResetObservation(); + ShowZoomCallTip(); + Check(HasRect(tip, origin.x + 304, origin.y + 244, 120, 32), "mouse mode includes virtual space beyond a horizontally scrolled line ending"); + caretPoint.y = -1; + ResetObservation(); + ShowZoomCallTip(); + CheckShown(400, false, 0, "mouse pixel placement works even when caret and nearest text are off-screen"); + Check(HasRect(tip, origin.x + 304, origin.y + 244, 120, 32), "off-screen caret does not change pixel placement"); + caretPoint = { 100, 100 }; + caretLineVisible = false; + ResetObservation(); + ShowZoomCallTip(); + Check(HasRect(tip, origin.x + 304, origin.y + 244, 120, 32), "mouse pixel placement does not depend on folded caret line visibility"); + caretLineVisible = true; + currentPos = 0; + SetMouseClient(500, 400); + ResetObservation(); + ShowZoomCallTip(); + Check(shownPos == 0 && HasRect(tip, origin.x + 504, origin.y + 404, 120, 32), "empty document stays near pointer instead of snapping to position zero"); + currentPos = 400; + SetMouseClient(630, 478); + ResetObservation(); + ShowZoomCallTip(); + Check(HasRect(tip, origin.x + 506, origin.y + 442, 120, 32), "mouse popup flips left and above near viewport edges"); + SetMouseClient(300, 240); + testDpi = 192; + ResetObservation(); + ShowZoomCallTip(); + Check(HasRect(tip, origin.x + 308, origin.y + 248, 120, 32), "mouse offset scales with editor DPI"); + testDpi = 96; + monitorWorkArea = { origin.x, origin.y, origin.x + 400, origin.y + 480 }; + SetMouseClient(398, 478); + ResetObservation(); + ShowZoomCallTip(); + Check(HasRect(tip, origin.x + 274, origin.y + 442, 120, 32), "mouse popup flips before clamping to monitor work-area edges"); + monitorWorkArea = { -32000, -32000, 32000, 32000 }; + SetMouseClient(700, 240); + ResetObservation(); + ShowZoomCallTip(); + CheckShown(400, false, 0, "mouse outside editor falls back to visible caret"); + Check(HasRect(tip, 0, 0, 120, 32), "outside mouse does not trigger native mouse placement"); + SetMouseClient(10, 100); + ResetObservation(); + ShowZoomCallTip(); + CheckShown(400, false, 0, "mouse over gutter uses visible caret instead of gutter text mapping"); + caretPoint.y = -1; + ResetObservation(); + ShowZoomCallTip(); + CheckShown(100, true, 2, "outside mouse and invisible caret fall back to upper-left"); + caretPoint.y = 100; + SetMouseClient(300, 240); + cursorValid = false; + ResetObservation(); + ShowZoomCallTip(); + CheckShown(400, false, 0, "failed pointer query uses visible caret"); + cursorValid = true; + conversionValid = false; + ResetObservation(); + ShowZoomCallTip(); + CheckShown(400, false, 0, "failed coordinate conversion uses visible caret"); + conversionValid = true; + + Settings2.ZoomTooltipPosition = ZOOM_TOOLTIP_UPPER_RIGHT; + simulatedTip = tip; + ResetObservation(); + ShowZoomCallTip(); + CheckShown(100, true, 2, "upper-right reuses existing display and timeout lifecycle"); + Check(HasRect(tip, origin.x + 632 - 120 - 4, origin.y + 4, 120, 32), "upper-right translates text viewport to screen and uses actual popup dimensions"); + ResetObservation(); + ShowZoomCallTip(); + Check(HasRect(tip, origin.x + 632 - 120 - 4, origin.y + 4, 120, 32), "repeated zoom repositions after Scintilla resets popup placement"); + simulatedTip = nullptr; + + SetWindowPos(Globals.hwndEdit, nullptr, 0, 0, 20, 20, SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE); + Settings2.ZoomTooltipPosition = ZOOM_TOOLTIP_CARET; + ResetObservation(); + ShowZoomCallTip(); + CheckShown(100, true, 2, "empty text viewport safely uses legacy placement"); + + for (int timeout : { 0, (_MQ_TIMER_CYCLE << 3) - 1 }) { + Settings2.ZoomTooltipTimeout = timeout; + ResetObservation(); + ShowZoomCallTip(); + Check(tipShows == 0 && tipCancels == 1 && !tipAbove && delayCalls == 0 && offsetChanges == 0, + "disabled or below-threshold timeout only cancels and resets call-tip orientation"); + } + Settings2.ZoomTooltipTimeout = _MQ_TIMER_CYCLE << 3; + ResetObservation(); + ShowZoomCallTip(); + CheckShown(100, true, 2, "existing timer threshold still displays the indicator"); + + DestroyWindow(tip); + DestroyWindow(otherTip); + DestroyWindow(foreignTip); + DestroyWindow(otherOwner); + DestroyWindow(owner); + UnregisterClassW(wc.lpszClassName, wc.hInstance); + std::printf("Zoom tooltip position: %s (%d checks)\n", failures ? "FAILED" : "PASS", checks); + return failures ? 1 : 0; +} diff --git a/test/TestZoomTooltipPosition.ps1 b/test/TestZoomTooltipPosition.ps1 new file mode 100644 index 000000000..6fdfa2aa1 --- /dev/null +++ b/test/TestZoomTooltipPosition.ps1 @@ -0,0 +1,37 @@ +$ErrorActionPreference = 'Stop' +$root = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path +$temp = Join-Path ([IO.Path]::GetTempPath()) ('np3-zoom-position-' + [guid]::NewGuid()) +[void](New-Item -ItemType Directory $temp) +try { + $source = Get-Content (Join-Path $root 'src\Notepad3.c') -Raw + $types = Get-Content (Join-Path $root 'src\TypeDefs.h') -Raw + $enum = [regex]::Match($types, '(?ms)^typedef enum ZOOM_TOOLTIP_POSITION \{.*?^\} ZOOM_TOOLTIP_POSITION;') + $cycle = [regex]::Match($source, '(?m)^#define _MQ_TIMER_CYCLE [^\r\n]+') + if (!$enum.Success -or !$cycle.Success) { throw 'Missing zoom position enum or timer cycle' } + Set-Content (Join-Path $temp 'ZoomTooltipPositionTypes.inc') ($enum.Value + "`n" + $cycle.Value) -Encoding ascii + $functions = foreach ($name in @('_GetZoomCallTipViewport', '_GetZoomCallTipCaret', '_FindZoomCallTip', '_PositionZoomCallTip', 'ShowZoomCallTip')) { + $start = [regex]::Match($source, "(?m)^(?:static )?\w+(?: CALLBACK)? $name\([^\r\n;]*\)\r?$") + if (!$start.Success) { throw "Missing $name" } + $body = $source.IndexOf('{', $start.Index) + $end = [regex]::Match($source.Substring($body), '(?m)^}') + if (!$end.Success) { throw "Missing $name end" } + $source.Substring($start.Index, $body + $end.Index + 1 - $start.Index) + } + $config = Get-Content (Join-Path $root 'src\Config\Config.cpp') -Raw + $load = [regex]::Match($config, '(?ms)^ Settings2\.ZoomTooltipPosition =.*?^ \}') + if (!$load.Success) { throw 'Missing zoom position settings load' } + $functions += "static void LoadZoomTooltipPosition()`n{`n" + $load.Value + "`n}" + Set-Content (Join-Path $temp 'ZoomTooltipPosition.inc') ($functions -join "`n") -Encoding ascii + $vswhere = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe" + $vs = & $vswhere -latest -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath + if (!$vs) { throw 'Visual C++ build tools not found' } + $vcvars = Join-Path $vs 'VC\Auxiliary\Build\vcvars64.bat' + $test = Join-Path $PSScriptRoot 'TestZoomTooltipPosition.cpp' + & $env:ComSpec /d /c "call `"$vcvars`" >nul && cd /d `"$temp`" && cl /nologo /EHsc /std:c++20 /W4 /WX /DUNICODE /D_UNICODE /DNOMINMAX /I`"$temp`" `"$test`" /Fe:TestZoomTooltipPosition.exe /link user32.lib" + if ($LASTEXITCODE -ne 0) { throw 'Zoom-position test build failed' } + & (Join-Path $temp 'TestZoomTooltipPosition.exe') + if ($LASTEXITCODE -ne 0) { throw 'Zoom-position tests failed' } +} finally { + Get-ChildItem $temp -File | Remove-Item + Remove-Item $temp +}