Commit Settings drafts through Apply or Save and make Close and Cancel reflect the pending state.
4074 lines
173 KiB
C++
4074 lines
173 KiB
C++
#include "lan_layout.h"
|
||
#include "../resources/resource.h"
|
||
#include "app.h"
|
||
#include "lan_log.h"
|
||
#include "history_preview.h"
|
||
#include "ui_scroll.h"
|
||
#include "configuration.h"
|
||
#include "ocr.h"
|
||
#include "richtext.h"
|
||
#include "ui_geometry.h"
|
||
#include "diagnostics.h"
|
||
#include <algorithm>
|
||
#include <array>
|
||
#include <commctrl.h>
|
||
#include <commdlg.h>
|
||
#include <dwmapi.h>
|
||
#include <map>
|
||
#include <richedit.h>
|
||
#include <set>
|
||
#include <shellapi.h>
|
||
#include <shlobj.h>
|
||
#include <sstream>
|
||
#include <wrl/client.h>
|
||
|
||
namespace ks
|
||
{
|
||
namespace
|
||
{
|
||
constexpr UINT ResultsMessage = WM_APP + 40, PreviewMessage = WM_APP + 41;
|
||
int scale(HWND w, int n)
|
||
{
|
||
return MulDiv(n, (int)GetDpiForWindow(w), 96);
|
||
}
|
||
HFONT font(HWND w, int size = 14, int weight = FW_NORMAL)
|
||
{
|
||
return CreateFontW(-scale(w, size), 0, 0, 0, weight, FALSE, FALSE, FALSE, DEFAULT_CHARSET,
|
||
OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, CLEARTYPE_QUALITY, DEFAULT_PITCH,
|
||
L"Segoe UI");
|
||
}
|
||
struct WindowLayout
|
||
{
|
||
int width{}, height{}, x{}, y{};
|
||
bool scrolling{}, arranging{}, history{};
|
||
int wheelRemainder{}, horizontalWheelRemainder{};
|
||
std::vector<std::pair<HWND, RECT>> controls; // Original 96-DPI geometry; never rescale rounded pixels.
|
||
HWND stretch{}, bottomLeft{}, bottomRight{}, details{};
|
||
bool fixedClient{}, childViewport{}, settingsShell{};
|
||
HWND rowCombo{};
|
||
void (*reflow)(HWND, WindowLayout &, int, int){};
|
||
struct ControlGeometry { RECT bounds; int visibleHeight; };
|
||
std::vector<ControlGeometry> originalControls;
|
||
};
|
||
#ifndef KS_RESIDENT_APP
|
||
void resizeSettingsForDpi(HWND w, int previousDpi, int nextDpi);
|
||
#endif
|
||
WindowLayout *windowLayoutState(HWND w)
|
||
{
|
||
return reinterpret_cast<WindowLayout *>(GetPropW(w, L"WindowLayout"));
|
||
}
|
||
RECT workArea(RECT rect)
|
||
{
|
||
MONITORINFO monitor{sizeof(monitor)};
|
||
GetMonitorInfoW(MonitorFromRect(&rect, MONITOR_DEFAULTTONEAREST), &monitor);
|
||
return monitor.rcWork;
|
||
}
|
||
void fitToMonitor(HWND w, RECT rect)
|
||
{
|
||
rect = fitWindowRect(rect, workArea(rect));
|
||
SetWindowPos(w, nullptr, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top,
|
||
SWP_NOACTIVATE | SWP_NOZORDER);
|
||
}
|
||
void fitFixedClient(HWND w, WindowLayout &layout, RECT frame)
|
||
{
|
||
RECT current{}, client{};
|
||
GetWindowRect(w, ¤t);
|
||
GetClientRect(w, &client);
|
||
const auto style = GetWindowLongPtrW(w, GWL_STYLE);
|
||
const UINT dpi = GetDpiForWindow(w);
|
||
const int vertical = (style & WS_VSCROLL) ? GetSystemMetricsForDpi(SM_CXVSCROLL, dpi) : 0;
|
||
const int horizontal = (style & WS_HSCROLL) ? GetSystemMetricsForDpi(SM_CYHSCROLL, dpi) : 0;
|
||
frame.right = frame.left + scale(w, layout.width) + current.right - current.left - client.right - vertical;
|
||
frame.bottom = frame.top + scale(w, layout.height) + current.bottom - current.top - client.bottom - horizontal;
|
||
fitToMonitor(w, frame);
|
||
}
|
||
struct WindowMove { HWND child; RECT rect; };
|
||
void applyWindowMoves(const std::vector<WindowMove> &moves, UINT flags = 0)
|
||
{
|
||
if (moves.empty()) return;
|
||
flags |= SWP_NOACTIVATE | SWP_NOZORDER;
|
||
auto batch = BeginDeferWindowPos(static_cast<int>(moves.size()));
|
||
for (const auto &[child, rect] : moves)
|
||
{
|
||
if (!batch) break;
|
||
batch = DeferWindowPos(batch, child, nullptr, rect.left, rect.top,
|
||
rect.right - rect.left, rect.bottom - rect.top, flags);
|
||
}
|
||
if (!batch || !EndDeferWindowPos(batch))
|
||
for (const auto &[child, rect] : moves)
|
||
SetWindowPos(child, nullptr, rect.left, rect.top, rect.right - rect.left,
|
||
rect.bottom - rect.top, flags);
|
||
}
|
||
void arrangeWindow(HWND w)
|
||
{
|
||
auto *layout = windowLayoutState(w);
|
||
if (!layout || !layout->scrolling || layout->arranging) return;
|
||
layout->arranging = true;
|
||
RECT client{};
|
||
GetClientRect(w, &client);
|
||
const auto style = GetWindowLongPtrW(w, GWL_STYLE);
|
||
const UINT dpi = GetDpiForWindow(w);
|
||
const int verticalBar = GetSystemMetricsForDpi(SM_CXVSCROLL, dpi);
|
||
const int horizontalBar = GetSystemMetricsForDpi(SM_CYHSCROLL, dpi);
|
||
// Start from the full client area so two obsolete bars cannot keep each other visible.
|
||
const int fullWidth = client.right + ((style & WS_VSCROLL) ? verticalBar : 0);
|
||
const int fullHeight = client.bottom + ((style & WS_HSCROLL) ? horizontalBar : 0);
|
||
if (layout->reflow) layout->reflow(w, *layout, fullWidth, fullHeight);
|
||
const int width = layout->reflow ? 1 : scale(w, layout->width);
|
||
const int height = scale(w, layout->height);
|
||
const bool needsHorizontal = width > fullWidth || (height > fullHeight && width > fullWidth - verticalBar);
|
||
const bool needsVertical = height > fullHeight - (needsHorizontal ? horizontalBar : 0);
|
||
SCROLLINFO horizontal{sizeof(horizontal), SIF_RANGE | SIF_PAGE | SIF_POS, 0, width - 1,
|
||
(UINT)std::max(1, fullWidth - (needsVertical ? verticalBar : 0)), layout->x};
|
||
SCROLLINFO vertical{sizeof(vertical), SIF_RANGE | SIF_PAGE | SIF_POS, 0, height - 1,
|
||
(UINT)std::max(1, fullHeight - (needsHorizontal ? horizontalBar : 0)), layout->y};
|
||
layout->x = SetScrollInfo(w, SB_HORZ, &horizontal, TRUE);
|
||
layout->y = SetScrollInfo(w, SB_VERT, &vertical, TRUE);
|
||
GetClientRect(w, &client);
|
||
bool expandable = layout->history || layout->stretch;
|
||
int extraWidth = expandable ? std::max(0, int(client.right) - scale(w, layout->width)) : 0;
|
||
int extraHeight = expandable ? std::max(0, int(client.bottom) - scale(w, layout->height)) : 0;
|
||
std::vector<WindowMove> moves;
|
||
for (const auto &[child, r] : layout->controls)
|
||
{
|
||
int id = GetDlgCtrlID(child);
|
||
RECT next{scale(w, r.left) - layout->x,
|
||
scale(w, r.top) - layout->y + ((id >= 110 && id <= 114) || id == 116 ? extraHeight : 0)};
|
||
next.right = next.left + scale(w, r.right - r.left) + (id == 101 || id == 102 ? extraWidth : 0);
|
||
next.bottom = next.top + scale(w, r.bottom - r.top) + (id == 102 ? extraHeight : 0);
|
||
if (child == layout->stretch)
|
||
{
|
||
next.right += extraWidth;
|
||
next.bottom += extraHeight;
|
||
}
|
||
if (child == layout->details)
|
||
{
|
||
next.right += extraWidth;
|
||
OffsetRect(&next, 0, extraHeight);
|
||
}
|
||
if (child == layout->bottomLeft || child == layout->bottomRight)
|
||
OffsetRect(&next, child == layout->bottomRight ? extraWidth : 0, extraHeight);
|
||
RECT current{}; GetWindowRect(child, ¤t);
|
||
MapWindowPoints(nullptr, w, reinterpret_cast<POINT *>(¤t), 2);
|
||
if (!EqualRect(¤t, &next)) moves.push_back({child, next});
|
||
}
|
||
if (!moves.empty())
|
||
{
|
||
applyWindowMoves(moves);
|
||
if (layout->childViewport) InvalidateRect(w, nullptr, TRUE);
|
||
}
|
||
if (layout->rowCombo)
|
||
{
|
||
RECT bounds{};
|
||
GetWindowRect(layout->rowCombo, &bounds);
|
||
const int difference = scale(w, 25) - (bounds.bottom - bounds.top);
|
||
const auto itemHeight = SendMessageW(layout->rowCombo, CB_GETITEMHEIGHT, static_cast<WPARAM>(-1), 0);
|
||
if (difference && itemHeight != CB_ERR && itemHeight + difference > 0)
|
||
SendMessageW(layout->rowCombo, CB_SETITEMHEIGHT, static_cast<WPARAM>(-1), itemHeight + difference);
|
||
}
|
||
layout->arranging = false;
|
||
}
|
||
void scrollWindow(HWND w, WindowLayout *layout, bool horizontal, int requested)
|
||
{
|
||
SCROLLINFO info{sizeof(info), SIF_RANGE | SIF_PAGE};
|
||
GetScrollInfo(w, horizontal ? SB_HORZ : SB_VERT, &info);
|
||
int next = std::clamp(requested, info.nMin, std::max(info.nMin, info.nMax - std::max(0, (int)info.nPage - 1)));
|
||
int &position = horizontal ? layout->x : layout->y;
|
||
if (position == next) return;
|
||
position = next;
|
||
arrangeWindow(w);
|
||
}
|
||
void revealControl(HWND child)
|
||
{
|
||
for (HWND parent = GetParent(child); parent; parent = GetAncestor(parent, GA_PARENT))
|
||
{
|
||
auto *layout = windowLayoutState(parent);
|
||
if (!layout || !layout->scrolling) continue;
|
||
RECT r{}, client{};
|
||
GetWindowRect(child, &r);
|
||
MapWindowPoints(nullptr, parent, reinterpret_cast<POINT *>(&r), 2);
|
||
GetClientRect(parent, &client);
|
||
if (r.left < 0) layout->x += r.left;
|
||
else if (r.right > client.right) layout->x += r.right - client.right;
|
||
if (r.top < 0) layout->y += r.top;
|
||
else if (r.bottom > client.bottom) layout->y += r.bottom - client.bottom;
|
||
arrangeWindow(parent);
|
||
}
|
||
}
|
||
LRESULT CALLBACK scrollChildProc(HWND w, UINT msg, WPARAM wp, LPARAM lp, UINT_PTR, DWORD_PTR)
|
||
{
|
||
if (msg == WM_SETFOCUS) revealControl(w);
|
||
if (msg == WM_NCDESTROY) RemoveWindowSubclass(w, scrollChildProc, 2);
|
||
return DefSubclassProc(w, msg, wp, lp);
|
||
}
|
||
void resizeForDpi(HWND, WPARAM, LPARAM);
|
||
LRESULT CALLBACK layoutProc(HWND w, UINT msg, WPARAM wp, LPARAM lp, UINT_PTR, DWORD_PTR)
|
||
{
|
||
auto *layout = windowLayoutState(w);
|
||
if (!layout) return DefSubclassProc(w, msg, wp, lp);
|
||
if (msg == WM_DPICHANGED)
|
||
{
|
||
resizeForDpi(w, wp, lp);
|
||
return 0;
|
||
}
|
||
if (msg == WM_SIZE) arrangeWindow(w);
|
||
if (!layout->childViewport && (msg == WM_DISPLAYCHANGE || msg == WM_SETTINGCHANGE || (msg == WM_SHOWWINDOW && wp)))
|
||
{
|
||
RECT rect{};
|
||
GetWindowRect(w, &rect);
|
||
if (layout->fixedClient) fitFixedClient(w, *layout, rect);
|
||
else fitToMonitor(w, rect);
|
||
arrangeWindow(w);
|
||
}
|
||
if (layout->scrolling && (msg == WM_VSCROLL || msg == WM_HSCROLL))
|
||
{
|
||
bool vertical = msg == WM_VSCROLL;
|
||
SCROLLINFO info{sizeof(info), SIF_ALL};
|
||
GetScrollInfo(w, vertical ? SB_VERT : SB_HORZ, &info);
|
||
int position = vertical ? layout->y : layout->x;
|
||
switch (LOWORD(wp))
|
||
{
|
||
case SB_LINEUP: position -= scale(w, 32); break;
|
||
case SB_LINEDOWN: position += scale(w, 32); break;
|
||
case SB_PAGEUP: position -= (int)info.nPage; break;
|
||
case SB_PAGEDOWN: position += (int)info.nPage; break;
|
||
case SB_TOP: position = 0; break;
|
||
case SB_BOTTOM: position = info.nMax; break;
|
||
case SB_THUMBTRACK: case SB_THUMBPOSITION: position = info.nTrackPos; break;
|
||
}
|
||
scrollWindow(w, layout, !vertical, position);
|
||
return 0;
|
||
}
|
||
if (layout->scrolling && (msg == WM_MOUSEWHEEL || msg == WM_MOUSEHWHEEL))
|
||
{
|
||
bool horizontal = msg == WM_MOUSEHWHEEL || (GET_KEYSTATE_WPARAM(wp) & MK_SHIFT);
|
||
int &remainder = horizontal ? layout->horizontalWheelRemainder : layout->wheelRemainder;
|
||
remainder += GET_WHEEL_DELTA_WPARAM(wp);
|
||
int steps = remainder / WHEEL_DELTA;
|
||
remainder %= WHEEL_DELTA;
|
||
if (steps)
|
||
scrollWindow(w, layout, horizontal, (horizontal ? layout->x : layout->y) +
|
||
steps * scale(w, 48) * (msg == WM_MOUSEHWHEEL ? 1 : -1));
|
||
return 0;
|
||
}
|
||
if (msg == WM_NCDESTROY)
|
||
{
|
||
RemovePropW(w, L"WindowLayout");
|
||
RemoveWindowSubclass(w, layoutProc, 2);
|
||
delete layout;
|
||
}
|
||
return DefSubclassProc(w, msg, wp, lp);
|
||
}
|
||
LRESULT CALLBACK listHeaderDraw(HWND list, UINT message, WPARAM wp, LPARAM lp, UINT_PTR, DWORD_PTR)
|
||
{
|
||
if (message != WM_NOTIFY) return DefSubclassProc(list, message, wp, lp);
|
||
const auto *notice = reinterpret_cast<const NMHDR *>(lp);
|
||
auto header = ListView_GetHeader(list);
|
||
if (notice->hwndFrom != header || notice->code != NM_CUSTOMDRAW)
|
||
return DefSubclassProc(list, message, wp, lp);
|
||
const auto &draw = *reinterpret_cast<const NMCUSTOMDRAW *>(lp);
|
||
auto background = GetSysColorBrush(COLOR_3DFACE);
|
||
auto border = GetSysColorBrush(COLOR_3DSHADOW);
|
||
if (draw.dwDrawStage == CDDS_PREPAINT)
|
||
{
|
||
FillRect(draw.hdc, &draw.rc, background);
|
||
return CDRF_NOTIFYITEMDRAW | CDRF_NOTIFYPOSTPAINT;
|
||
}
|
||
if (draw.dwDrawStage == CDDS_ITEMPREPAINT)
|
||
{
|
||
RECT cell = draw.rc;
|
||
FillRect(draw.hdc, &cell, background);
|
||
RECT divider{cell.right - 1, cell.top, cell.right, cell.bottom};
|
||
FillRect(draw.hdc, ÷r, border);
|
||
wchar_t title[64]{};
|
||
HDITEMW item{HDI_TEXT | HDI_FORMAT};
|
||
item.pszText = title;
|
||
item.cchTextMax = std::size(title);
|
||
Header_GetItem(header, static_cast<int>(draw.dwItemSpec), &item);
|
||
cell.left += scale(list, 5);
|
||
cell.right -= scale(list, 5);
|
||
int dc = SaveDC(draw.hdc);
|
||
auto font = SendMessageW(header, WM_GETFONT, 0, 0);
|
||
if (font) SelectObject(draw.hdc, reinterpret_cast<HFONT>(font));
|
||
SetTextColor(draw.hdc, GetSysColor(COLOR_BTNTEXT));
|
||
SetBkMode(draw.hdc, TRANSPARENT);
|
||
UINT alignment = (item.fmt & HDF_RIGHT) ? DT_RIGHT : (item.fmt & HDF_CENTER) ? DT_CENTER : DT_LEFT;
|
||
DrawTextW(draw.hdc, title, -1, &cell, alignment | DT_SINGLELINE | DT_VCENTER | DT_END_ELLIPSIS | DT_NOPREFIX);
|
||
RestoreDC(draw.hdc, dc);
|
||
return CDRF_SKIPDEFAULT;
|
||
}
|
||
if (draw.dwDrawStage == CDDS_POSTPAINT)
|
||
{
|
||
RECT line{};
|
||
GetClientRect(header, &line);
|
||
line.top = line.bottom - 1;
|
||
FillRect(draw.hdc, &line, border);
|
||
}
|
||
return CDRF_DODEFAULT;
|
||
}
|
||
HWND control(HWND parent, const wchar_t *cls, const wchar_t *title, DWORD style, int id, int x, int y,
|
||
int width, int height)
|
||
{
|
||
HWND w = CreateWindowExW(wcscmp(cls, L"EDIT") == 0 ? WS_EX_CLIENTEDGE : 0, cls, title,
|
||
WS_CHILD | WS_VISIBLE | style, scale(parent, x), scale(parent, y),
|
||
scale(parent, width), scale(parent, height), parent, (HMENU)(INT_PTR)id,
|
||
GetModuleHandleW(nullptr), nullptr);
|
||
SendMessageW(w, WM_SETFONT, (WPARAM)GetPropW(parent, L"Font"), TRUE);
|
||
if (wcscmp(cls, WC_LISTVIEWW) == 0 && (style & LVS_TYPEMASK) == LVS_REPORT && !(style & LVS_NOCOLUMNHEADER))
|
||
SetWindowSubclass(w, listHeaderDraw, 3, 0);
|
||
if(wcscmp(cls,L"LISTBOX")==0 || wcscmp(cls,WC_LISTVIEWW)==0 ||
|
||
wcscmp(cls,L"COMBOBOX")==0 || (wcscmp(cls,L"EDIT")==0 && (style&ES_MULTILINE)))
|
||
enableWheelBatching(w,wcscmp(cls,L"LISTBOX")==0);
|
||
if (auto *layout = windowLayoutState(parent); layout && layout->scrolling)
|
||
{
|
||
layout->controls.push_back({w, {x, y, x + width, y + height}});
|
||
SetWindowSubclass(w, scrollChildProc, 2, 0);
|
||
arrangeWindow(parent);
|
||
}
|
||
return w;
|
||
}
|
||
void label(HWND w, const wchar_t *text, int x, int y, int width = 200)
|
||
{
|
||
control(w, L"STATIC", text, 0, 0, x, y, width, 22);
|
||
}
|
||
void button(HWND w, const wchar_t *text, int id, int x, int y, int width = 100)
|
||
{
|
||
control(w, L"BUTTON", text, WS_TABSTOP | BS_PUSHBUTTON, id, x, y, width, 28);
|
||
}
|
||
HWND edit(HWND w, int id, int x, int y, int width, int height = 25, DWORD style = ES_AUTOHSCROLL)
|
||
{
|
||
auto c = control(w, L"EDIT", L"", WS_TABSTOP | style, id, x, y, width, height);
|
||
SendMessageW(c, EM_SETLIMITTEXT, 1024 * 1024, 0);
|
||
return c;
|
||
}
|
||
LRESULT CALLBACK hotkeyProc(HWND w, UINT msg, WPARAM wp, LPARAM lp, UINT_PTR, DWORD_PTR data)
|
||
{
|
||
auto *app = (App *)data;
|
||
if (msg == WM_SETFOCUS)
|
||
{
|
||
app->setHotkeyCapture(w);
|
||
SendMessageW(w, EM_SETSEL, 0, -1);
|
||
}
|
||
if (msg == WM_KILLFOCUS || msg == WM_NCDESTROY)
|
||
{
|
||
if (app->hotkeyCapture == w)
|
||
app->setHotkeyCapture(nullptr);
|
||
}
|
||
if (msg == CaptureHotkeyMessage)
|
||
{
|
||
UINT mods = (UINT)lp;
|
||
if ((wp == VK_TAB && (mods == 0 || mods == MOD_SHIFT)) || (wp == VK_ESCAPE && mods == 0))
|
||
{
|
||
SetFocus(GetNextDlgTabItem(GetAncestor(w, GA_ROOT), w, mods == MOD_SHIFT));
|
||
return 0;
|
||
}
|
||
if ((wp == VK_BACK || wp == VK_DELETE) && mods == 0)
|
||
{
|
||
SetWindowTextW(w, L"");
|
||
return 0;
|
||
}
|
||
auto text = Hotkey{mods, (UINT)wp}.format();
|
||
if (!text.empty())
|
||
{
|
||
SetWindowTextW(w, text.c_str());
|
||
SendMessageW(w, EM_SETSEL, 0, -1);
|
||
}
|
||
return 0;
|
||
}
|
||
if (msg == WM_CHAR || msg == WM_SYSCHAR || msg == WM_PASTE || msg == WM_CUT)
|
||
return 0;
|
||
return DefSubclassProc(w, msg, wp, lp);
|
||
}
|
||
[[maybe_unused]] void hotkeyEdit(App &app, HWND w, int id, int x, int y, int width)
|
||
{
|
||
HWND field = edit(w, id, x, y, width, 25, ES_AUTOHSCROLL | ES_READONLY);
|
||
SendMessageW(field, EM_SETCUEBANNER, FALSE, (LPARAM)L"Click, then press a shortcut");
|
||
SetWindowSubclass(field, hotkeyProc, 1, (DWORD_PTR)&app);
|
||
}
|
||
[[maybe_unused]] void checkbox(HWND w, const wchar_t *text, int id, int x, int y, int width = 300)
|
||
{
|
||
control(w, L"BUTTON", text, WS_TABSTOP | BS_AUTOCHECKBOX, id, x, y, width, 24);
|
||
}
|
||
std::wstring value(HWND w, int id)
|
||
{
|
||
HWND c = GetDlgItem(w, id);
|
||
int n = GetWindowTextLengthW(c);
|
||
std::wstring text(n + 1, L'\0');
|
||
GetWindowTextW(c, text.data(), n + 1);
|
||
text.resize(n);
|
||
return text;
|
||
}
|
||
[[maybe_unused]] void value(HWND w, int id, const std::wstring &text)
|
||
{
|
||
SetDlgItemTextW(w, id, text.c_str());
|
||
}
|
||
[[maybe_unused]] bool checked(HWND w, int id)
|
||
{
|
||
return IsDlgButtonChecked(w, id) == BST_CHECKED;
|
||
}
|
||
[[maybe_unused]] void check(HWND w, int id, bool yes)
|
||
{
|
||
CheckDlgButton(w, id, yes ? BST_CHECKED : BST_UNCHECKED);
|
||
}
|
||
void error(HWND w, const std::exception &e)
|
||
{
|
||
MessageBoxW(w, wide(e.what()).c_str(), L"KSwitcher", MB_OK | MB_ICONWARNING);
|
||
}
|
||
HWND makeWindow(App &app, const wchar_t *cls, const wchar_t *title, WNDPROC proc, int width, int height,
|
||
DWORD extra = 0, bool resizable = true, HWND owner = nullptr)
|
||
{
|
||
WNDCLASSW wc{};
|
||
wc.hInstance = app.instance;
|
||
wc.lpfnWndProc = proc;
|
||
wc.lpszClassName = cls;
|
||
wc.hCursor = LoadCursorW(nullptr, IDC_ARROW);
|
||
wc.hbrBackground = (HBRUSH)(COLOR_BTNFACE + 1);
|
||
wc.hIcon = LoadIconW(app.instance, MAKEINTRESOURCEW(IDI_KSWITCHER));
|
||
RegisterClassW(&wc);
|
||
UINT dpi = GetDpiForSystem();
|
||
RECT rect{0, 0, MulDiv(width, dpi, 96), MulDiv(height, dpi, 96)};
|
||
DWORD style = WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_CLIPCHILDREN | extra;
|
||
if (resizable) style |= WS_THICKFRAME | WS_MAXIMIZEBOX;
|
||
const DWORD exStyle = owner ? WS_EX_DLGMODALFRAME : WS_EX_APPWINDOW;
|
||
AdjustWindowRectExForDpi(&rect, style, FALSE, exStyle, dpi);
|
||
POINT cursor{};
|
||
GetCursorPos(&cursor);
|
||
MONITORINFO monitor{sizeof(monitor)};
|
||
GetMonitorInfoW(MonitorFromPoint(cursor, MONITOR_DEFAULTTONEAREST), &monitor);
|
||
HWND w =
|
||
CreateWindowExW(exStyle, cls, title, style, monitor.rcWork.left, monitor.rcWork.top,
|
||
rect.right - rect.left, rect.bottom - rect.top, owner, nullptr, app.instance, &app);
|
||
if (!w)
|
||
throw std::runtime_error(utf8(lastError(L"Cannot create native window")));
|
||
// The system DPI may still describe the old primary display. The HWND tells
|
||
// us the actual destination DPI, and must size the frame AND its controls.
|
||
dpi = GetDpiForWindow(w);
|
||
RECT frame{}, client{};
|
||
GetWindowRect(w, &frame);
|
||
GetClientRect(w, &client);
|
||
int outerWidth = scale(w, width) + (frame.right - frame.left) - client.right;
|
||
int outerHeight = scale(w, height) + (frame.bottom - frame.top) - client.bottom;
|
||
int left = monitor.rcWork.left + std::max(0L, (monitor.rcWork.right - monitor.rcWork.left - outerWidth) / 2);
|
||
int top = monitor.rcWork.top + std::max(0L, (monitor.rcWork.bottom - monitor.rcWork.top - outerHeight) / 2);
|
||
SetPropW(w, L"WindowLayout", new WindowLayout{width, height, 0, 0, !(extra & WS_THICKFRAME)});
|
||
SetWindowSubclass(w, layoutProc, 2, 0);
|
||
if(windowLayoutState(w)->scrolling) enableWheelBatching(w);
|
||
RECT initial = fitWindowRect({left, top, left + outerWidth, top + outerHeight}, monitor.rcWork);
|
||
SetWindowPos(w, nullptr, initial.left, initial.top, initial.right - initial.left, initial.bottom - initial.top,
|
||
SWP_NOACTIVATE | SWP_NOZORDER);
|
||
arrangeWindow(w);
|
||
SetWindowTextW(w, localBuildTitle(title).c_str());
|
||
auto smallIcon = (HICON)LoadImageW(app.instance, MAKEINTRESOURCEW(IDI_KSWITCHER), IMAGE_ICON,
|
||
GetSystemMetricsForDpi(SM_CXSMICON, dpi),
|
||
GetSystemMetricsForDpi(SM_CYSMICON, dpi), LR_SHARED);
|
||
SendMessageW(w, WM_SETICON, ICON_SMALL, (LPARAM)smallIcon);
|
||
SetPropW(w, L"Font", font(w));
|
||
SetPropW(w, L"Dpi", (HANDLE)(UINT_PTR)GetDpiForWindow(w));
|
||
return w;
|
||
}
|
||
void resizeForDpi(HWND w, WPARAM wp, LPARAM lp)
|
||
{
|
||
// Creation may send WM_DPICHANGED before controls and the original font exist.
|
||
if (!GetPropW(w, L"Dpi"))
|
||
{
|
||
fitToMonitor(w, *(RECT *)lp);
|
||
return;
|
||
}
|
||
int previous = (int)(UINT_PTR)GetPropW(w, L"Dpi");
|
||
int next = LOWORD(wp);
|
||
if (!previous)
|
||
previous = 96;
|
||
HFONT old = (HFONT)GetPropW(w, L"Font");
|
||
HFONT replacement = font(w);
|
||
struct State
|
||
{
|
||
HWND parent;
|
||
int previous, next;
|
||
HFONT font;
|
||
} state{w, previous, next, replacement};
|
||
auto *layout = windowLayoutState(w);
|
||
if (!layout || !layout->scrolling) EnumChildWindows(
|
||
w,
|
||
[](HWND child, LPARAM data) -> BOOL
|
||
{
|
||
auto &s = *(State *)data;
|
||
if (GetParent(child) != s.parent)
|
||
return TRUE;
|
||
RECT r;
|
||
GetWindowRect(child, &r);
|
||
MapWindowPoints(nullptr, s.parent, (POINT *)&r, 2);
|
||
SetWindowPos(child, nullptr, MulDiv(r.left, s.next, s.previous),
|
||
MulDiv(r.top, s.next, s.previous), MulDiv(r.right - r.left, s.next, s.previous),
|
||
MulDiv(r.bottom - r.top, s.next, s.previous), SWP_NOZORDER);
|
||
SendMessageW(child, WM_SETFONT, (WPARAM)s.font, TRUE);
|
||
return TRUE;
|
||
},
|
||
(LPARAM)&state);
|
||
else
|
||
{
|
||
layout->x = MulDiv(layout->x, next, previous);
|
||
layout->y = MulDiv(layout->y, next, previous);
|
||
for (auto &[child, rect] : layout->controls)
|
||
SendMessageW(child, WM_SETFONT, (WPARAM)replacement, TRUE);
|
||
}
|
||
SetPropW(w, L"Font", replacement);
|
||
SetPropW(w, L"Dpi", (HANDLE)(UINT_PTR)next);
|
||
if (old)
|
||
DeleteObject(old);
|
||
// layoutProc consumes WM_DPICHANGED, so owner-drawn rows must be resized here.
|
||
if (layout && layout->history)
|
||
SendDlgItemMessageW(w, 102, LB_SETITEMHEIGHT, 0, scale(w, 88));
|
||
fitToMonitor(w, *(RECT *)lp);
|
||
if (layout && layout->fixedClient)
|
||
{
|
||
RECT frame{};
|
||
GetWindowRect(w, &frame);
|
||
fitFixedClient(w, *layout, frame);
|
||
}
|
||
arrangeWindow(w);
|
||
#ifndef KS_RESIDENT_APP
|
||
if (layout && layout->settingsShell)
|
||
resizeSettingsForDpi(w, previous, next);
|
||
#endif
|
||
}
|
||
[[maybe_unused]] std::filesystem::path pickFile(HWND owner, bool save)
|
||
{
|
||
wchar_t path[32768]{};
|
||
OPENFILENAMEW ofn{sizeof(ofn)};
|
||
ofn.hwndOwner = owner;
|
||
ofn.lpstrFilter = L"Settings (*.json)\0*.json\0All files\0*.*\0";
|
||
ofn.lpstrFile = path;
|
||
ofn.nMaxFile = 32768;
|
||
ofn.lpstrDefExt = L"json";
|
||
ofn.Flags = OFN_EXPLORER | OFN_NOCHANGEDIR | (save ? OFN_OVERWRITEPROMPT : OFN_FILEMUSTEXIST);
|
||
return (save ? GetSaveFileNameW(&ofn) : GetOpenFileNameW(&ofn)) ? std::filesystem::path(path)
|
||
: std::filesystem::path();
|
||
}
|
||
void disposeFont(HWND w)
|
||
{
|
||
auto h = (HFONT)RemovePropW(w, L"Font");
|
||
if (h)
|
||
DeleteObject(h);
|
||
}
|
||
|
||
#ifndef KS_CONFIG_APP
|
||
struct SearchResult
|
||
{
|
||
uint64_t generation;
|
||
std::vector<Entry> items;
|
||
};
|
||
struct TextPreview
|
||
{
|
||
std::string rtf;
|
||
std::wstring plain;
|
||
};
|
||
struct PreviewResult
|
||
{
|
||
uint64_t generation;
|
||
std::wstring id;
|
||
Pixels pixels;
|
||
TextPreview text;
|
||
};
|
||
struct HistoryView
|
||
{
|
||
App *app{};
|
||
std::vector<Entry> items;
|
||
std::wstring rememberedSelection, rememberedTop;
|
||
uint64_t generation{};
|
||
std::shared_ptr<std::atomic<bool>> previewActive = std::make_shared<std::atomic<bool>>(true);
|
||
std::map<std::wstring, Pixels> thumbnails;
|
||
std::map<std::wstring, TextPreview> richTexts;
|
||
HWND rich{};
|
||
std::set<std::wstring> pending;
|
||
bool scrolling{};
|
||
bool closed{};
|
||
bool selectFirstOnResults{};
|
||
};
|
||
bool selectedImage(HWND w, HistoryView *v)
|
||
{
|
||
int i=(int)SendDlgItemMessageW(w,102,LB_GETCURSEL,0,0);
|
||
return i>=0 && i<(int)v->items.size() && v->items[i].image;
|
||
}
|
||
void updateHistoryActions(HWND w, HistoryView *v)
|
||
{
|
||
SetDlgItemTextW(w,114,selectedImage(w,v)?L"&Edit image":L"&Open item");
|
||
}
|
||
std::wstring selected(HWND w, HistoryView *v)
|
||
{
|
||
int i = (int)SendDlgItemMessageW(w, 102, LB_GETCURSEL, 0, 0);
|
||
return i >= 0 && i < (int)v->items.size() ? v->items[i].id : L"";
|
||
}
|
||
void search(HWND w, HistoryView *v)
|
||
{
|
||
v->previewActive->store(false);
|
||
v->previewActive = std::make_shared<std::atomic<bool>>(true);
|
||
v->closed = false;
|
||
auto q = value(w, 101);
|
||
const bool pinnedOnly = SendDlgItemMessageW(w, 117, BM_GETCHECK, 0, 0) == BST_CHECKED;
|
||
auto generation = ++v->generation;
|
||
v->pending.clear();
|
||
auto *app = v->app;
|
||
app->enqueueHistorySearch(
|
||
[w, app, q, generation, pinnedOnly, computers=app->historyComputers]
|
||
{
|
||
try
|
||
{
|
||
auto result = new SearchResult{generation, app->history->search(q, pinnedOnly)};
|
||
if(!computers.empty())std::erase_if(result->items,[&](const Entry &e){return
|
||
std::find(computers.begin(),computers.end(),e.computer)==computers.end();});
|
||
if (!PostMessageW(w, ResultsMessage, 0, (LPARAM)result))
|
||
delete result;
|
||
}
|
||
catch (const std::exception &e)
|
||
{
|
||
app->report(wide(e.what()));
|
||
}
|
||
});
|
||
}
|
||
struct ComputerFilter
|
||
{
|
||
HWND owner{},list{};HistoryView *view{};bool filling{};
|
||
std::vector<std::pair<std::string,std::wstring>> computers;
|
||
};
|
||
LRESULT CALLBACK filterKeys(HWND w,UINT msg,WPARAM wp,LPARAM lp,UINT_PTR,DWORD_PTR)
|
||
{
|
||
if(msg==WM_KEYDOWN&&wp==VK_ESCAPE){DestroyWindow(GetParent(w));return 0;}
|
||
if(msg==WM_NCDESTROY)RemoveWindowSubclass(w,filterKeys,1);
|
||
return DefSubclassProc(w,msg,wp,lp);
|
||
}
|
||
LRESULT CALLBACK computerFilterProc(HWND w,UINT msg,WPARAM wp,LPARAM lp)
|
||
{
|
||
auto *f=reinterpret_cast<ComputerFilter*>(GetWindowLongPtrW(w,GWLP_USERDATA));
|
||
if(msg==WM_NCCREATE){f=static_cast<ComputerFilter*>(reinterpret_cast<CREATESTRUCTW*>(lp)->lpCreateParams);SetWindowLongPtrW(w,GWLP_USERDATA,reinterpret_cast<LONG_PTR>(f));}
|
||
if(f&&msg==WM_NOTIFY&&!f->filling&&reinterpret_cast<NMHDR*>(lp)->code==LVN_ITEMCHANGED){
|
||
auto *change=reinterpret_cast<NMLISTVIEW*>(lp);
|
||
if(change->iItem>=0&&(change->uChanged&LVIF_STATE)&&((change->uOldState^change->uNewState)&LVIS_STATEIMAGEMASK)){
|
||
f->filling=true;
|
||
bool checked=ListView_GetCheckState(f->list,change->iItem)!=0;
|
||
if(change->iItem==0)for(int i=1;i<=int(f->computers.size());++i)ListView_SetCheckState(f->list,i,checked);
|
||
bool all=true;auto &chosen=f->view->app->historyComputers;chosen.clear();
|
||
for(int i=0;i<int(f->computers.size());++i){if(ListView_GetCheckState(f->list,i+1))chosen.push_back(f->computers[i].first);else all=false;}
|
||
ListView_SetCheckState(f->list,0,all);
|
||
if(all)chosen.clear();else if(chosen.empty())chosen.push_back("__none");
|
||
f->filling=false;
|
||
SetDlgItemTextW(f->owner,118,all?L" Computers: All ▾":L" Computers: Selected ▾");
|
||
search(f->owner,f->view);
|
||
f->view->app->saveHistoryView(f->view->rememberedSelection,f->view->rememberedTop,value(f->owner,101),SendDlgItemMessageW(f->owner,117,BM_GETCHECK,0,0)==BST_CHECKED);
|
||
}
|
||
return 0;
|
||
}
|
||
if(msg==WM_ACTIVATE&&LOWORD(wp)==WA_INACTIVE){DestroyWindow(w);return 0;}
|
||
if(msg==WM_CLOSE){DestroyWindow(w);return 0;}
|
||
if(msg==WM_NCDESTROY){SetWindowLongPtrW(w,GWLP_USERDATA,0);delete f;}
|
||
return DefWindowProcW(w,msg,wp,lp);
|
||
}
|
||
void showComputerFilter(HWND owner,HistoryView *v)
|
||
{
|
||
std::map<std::string,std::wstring> names{{"",L"This computer"}};
|
||
for(auto &entry:v->app->history->entries())if(!entry.computer.empty())names[entry.computer]=entry.computerName;
|
||
try{
|
||
auto path=v->app->data/L"lan-pairing.bin";
|
||
if(std::filesystem::exists(path)){
|
||
auto config=nlohmann::json::parse(unprotect(readFile(path,256*1024)));
|
||
for(auto &[id,peer]:config.at("trusted").items())names[id]=wide(peer.at("name").get<std::string>());
|
||
}
|
||
}catch(...){}
|
||
auto *f=new ComputerFilter{owner,nullptr,v,true,{}};
|
||
for(auto &[id,name]:names)f->computers.push_back({id,name});
|
||
WNDCLASSW cls{};cls.lpfnWndProc=computerFilterProc;cls.hInstance=v->app->instance;cls.hCursor=LoadCursorW(nullptr,IDC_ARROW);cls.hbrBackground=(HBRUSH)(COLOR_WINDOW+1);cls.lpszClassName=L"KSwitcher.ComputerFilter";RegisterClassW(&cls);
|
||
RECT r{};GetWindowRect(GetDlgItem(owner,118),&r);
|
||
int width=scale(owner,300),height=scale(owner,std::min(280,32+int(names.size()+1)*26));
|
||
MONITORINFO monitor{sizeof(monitor)};GetMonitorInfoW(MonitorFromWindow(owner,MONITOR_DEFAULTTONEAREST),&monitor);
|
||
int x=std::clamp(int(r.left),int(monitor.rcWork.left),std::max(int(monitor.rcWork.left),int(monitor.rcWork.right)-width));
|
||
int y=r.bottom+height>monitor.rcWork.bottom?std::max(int(monitor.rcWork.top),int(r.top)-height):int(r.bottom);
|
||
auto popup=CreateWindowExW(WS_EX_TOOLWINDOW,cls.lpszClassName,L"Computers",WS_POPUP|WS_BORDER,x,y,width,height,owner,nullptr,v->app->instance,f);
|
||
if(!popup){delete f;return;}
|
||
RECT client{};GetClientRect(popup,&client);
|
||
f->list=CreateWindowExW(0,WC_LISTVIEWW,L"Computers",WS_CHILD|WS_VISIBLE|WS_TABSTOP|LVS_REPORT|LVS_NOCOLUMNHEADER|LVS_SINGLESEL,0,0,client.right,client.bottom,popup,nullptr,v->app->instance,nullptr);
|
||
SendMessageW(f->list,WM_SETFONT,SendDlgItemMessageW(owner,118,WM_GETFONT,0,0),TRUE);
|
||
ListView_SetExtendedListViewStyle(f->list,LVS_EX_CHECKBOXES|LVS_EX_FULLROWSELECT|LVS_EX_DOUBLEBUFFER);
|
||
LVCOLUMNW column{LVCF_WIDTH};column.cx=client.right-scale(owner,24);ListView_InsertColumn(f->list,0,&column);
|
||
auto &chosen=v->app->historyComputers;
|
||
for(int i=0;i<=int(f->computers.size());++i){
|
||
std::wstring label=i?f->computers[i-1].second:L"All computers";
|
||
LVITEMW item{LVIF_TEXT};item.iItem=i;item.pszText=label.data();ListView_InsertItem(f->list,&item);
|
||
bool checked=chosen.empty()||(i&&std::find(chosen.begin(),chosen.end(),f->computers[i-1].first)!=chosen.end());
|
||
ListView_SetCheckState(f->list,i,checked);
|
||
}
|
||
f->filling=false;SetWindowSubclass(f->list,filterKeys,1,0);
|
||
ShowWindow(popup,SW_SHOW);SetFocus(f->list);
|
||
}
|
||
void requestPreview(HWND w, HistoryView *v, const Entry &entry)
|
||
{
|
||
if(v->scrolling) return;
|
||
const auto id = entry.id;
|
||
const bool image = entry.image;
|
||
if (v->thumbnails.contains(id) || v->richTexts.contains(id) || !v->pending.insert(id).second)
|
||
return;
|
||
auto generation = v->generation;
|
||
auto active = v->previewActive;
|
||
auto *app = v->app;
|
||
app->enqueue(
|
||
[w, app, id, generation, image, active]
|
||
{
|
||
if (!active->load()) return;
|
||
auto result = new PreviewResult{generation, id, {}, {}};
|
||
try
|
||
{
|
||
if (image)
|
||
result->pixels = app->history->thumbnail(id, [active] { return !active->load(); });
|
||
else {
|
||
auto clip = app->history->load(id);
|
||
if (!active->load()) { delete result; return; }
|
||
result->text.rtf = richPreview(clip, false);
|
||
if (result->text.rtf.empty()) {
|
||
result->text.plain = clip.text();
|
||
if (result->text.plain.size() > 4096) result->text.plain.resize(4096);
|
||
}
|
||
}
|
||
}
|
||
catch (const std::exception &)
|
||
{
|
||
}
|
||
if (!active->load() || !PostMessageW(w, PreviewMessage, 0, (LPARAM)result))
|
||
delete result;
|
||
});
|
||
}
|
||
void drawHistoryRow(HWND w, HistoryView *v, const DRAWITEMSTRUCT &draw)
|
||
{
|
||
if (draw.itemID >= v->items.size())
|
||
return;
|
||
const auto &entry = v->items[draw.itemID];
|
||
const bool selected = (draw.itemState & ODS_SELECTED) != 0;
|
||
HDC dc = draw.hDC;
|
||
int saved = SaveDC(dc);
|
||
auto box = draw.rcItem;
|
||
FillRect(dc, &box, GetSysColorBrush(selected ? COLOR_HIGHLIGHT : COLOR_WINDOW));
|
||
SetBkMode(dc, TRANSPARENT);
|
||
SetTextColor(dc, GetSysColor(selected ? COLOR_HIGHLIGHTTEXT : COLOR_WINDOWTEXT));
|
||
SelectObject(dc, GetPropW(w, L"Font"));
|
||
RECT icon{box.left + scale(w, 12), box.top + scale(w, 10), box.left + scale(w, 116),
|
||
box.bottom - scale(w, 10)};
|
||
auto thumbnail = v->thumbnails.find(entry.id);
|
||
if (entry.image && thumbnail != v->thumbnails.end() && !thumbnail->second.bgra.empty())
|
||
{
|
||
auto &p = thumbnail->second;
|
||
double ratio =
|
||
std::min(double(icon.right - icon.left) / p.width, double(icon.bottom - icon.top) / p.height);
|
||
int width = int(p.width * ratio), height = int(p.height * ratio);
|
||
BITMAPINFO info{};
|
||
info.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
|
||
info.bmiHeader.biWidth = p.width;
|
||
info.bmiHeader.biHeight = -(LONG)p.height;
|
||
info.bmiHeader.biPlanes = 1;
|
||
info.bmiHeader.biBitCount = 32;
|
||
SetStretchBltMode(dc, HALFTONE);
|
||
StretchDIBits(dc, icon.left + (icon.right - icon.left - width) / 2,
|
||
icon.top + (icon.bottom - icon.top - height) / 2, width, height, 0, 0, p.width,
|
||
p.height, p.bgra.data(), &info, DIB_RGB_COLORS, SRCCOPY);
|
||
}
|
||
else
|
||
{
|
||
FrameRect(dc, &icon, GetSysColorBrush(selected ? COLOR_HIGHLIGHTTEXT : COLOR_3DSHADOW));
|
||
const wchar_t *glyph = entry.image ? L"▧" : entry.files ? L"≡" : L"Aa";
|
||
DrawTextW(dc, glyph, -1, &icon, DT_CENTER | DT_VCENTER | DT_SINGLELINE);
|
||
if (entry.image)
|
||
requestPreview(w, v, entry);
|
||
}
|
||
RECT title{icon.right + scale(w, 14), box.top + scale(w, 10), box.right - scale(w, 14),
|
||
box.bottom - scale(w, 30)};
|
||
auto text = (entry.pinned ? L"★ " : L"") + (entry.image ? L"Image"
|
||
: entry.files ? L"Files"
|
||
: entry.preview);
|
||
bool formatted = false;
|
||
if (!entry.image && !entry.files)
|
||
{
|
||
auto rich = v->richTexts.find(entry.id);
|
||
if (rich != v->richTexts.end() && rich->second.rtf.empty())
|
||
text = (entry.pinned ? L"★ " : L"") + rich->second.plain;
|
||
if (rich != v->richTexts.end() && !rich->second.rtf.empty() && !v->rich)
|
||
v->rich = createRichText(w, 105, false);
|
||
if (rich != v->richTexts.end() && v->rich && !rich->second.rtf.empty())
|
||
{
|
||
setRichText(v->rich, rich->second.rtf);
|
||
CHARFORMAT2W format{};
|
||
format.cbSize = sizeof(format);
|
||
format.dwMask = CFM_COLOR;
|
||
format.crTextColor = GetSysColor(selected ? COLOR_HIGHLIGHTTEXT : COLOR_WINDOWTEXT);
|
||
SendMessageW(v->rich, EM_SETCHARFORMAT, SCF_ALL, (LPARAM)&format);
|
||
SendMessageW(v->rich, EM_SETBKGNDCOLOR, 0,
|
||
GetSysColor(selected ? COLOR_HIGHLIGHT : COLOR_WINDOW));
|
||
FORMATRANGE range{};
|
||
range.hdc = range.hdcTarget = dc;
|
||
range.rc = {MulDiv(title.left, 1440, GetDeviceCaps(dc, LOGPIXELSX)),
|
||
MulDiv(title.top, 1440, GetDeviceCaps(dc, LOGPIXELSY)),
|
||
MulDiv(title.right, 1440, GetDeviceCaps(dc, LOGPIXELSX)),
|
||
MulDiv(title.bottom, 1440, GetDeviceCaps(dc, LOGPIXELSY))};
|
||
range.rcPage = range.rc;
|
||
range.chrg = {0, -1};
|
||
IntersectClipRect(dc, title.left, title.top, title.right, title.bottom);
|
||
SendMessageW(v->rich, EM_FORMATRANGE, TRUE, (LPARAM)&range);
|
||
SendMessageW(v->rich, EM_FORMATRANGE, FALSE, 0);
|
||
// Restore the row clipping before drawing its source label.
|
||
RestoreDC(dc, saved);
|
||
saved = SaveDC(dc);
|
||
SetBkMode(dc, TRANSPARENT);
|
||
SelectObject(dc, GetPropW(w, L"Font"));
|
||
formatted = true;
|
||
}
|
||
else
|
||
requestPreview(w, v, entry);
|
||
}
|
||
if (!formatted)
|
||
DrawTextW(dc, text.c_str(), -1, &title, DT_WORDBREAK | DT_END_ELLIPSIS | DT_NOPREFIX);
|
||
RECT detail{title.left, box.bottom - scale(w, 26), title.right, box.bottom - scale(w, 8)};
|
||
SetTextColor(dc, GetSysColor(selected ? COLOR_HIGHLIGHTTEXT : COLOR_GRAYTEXT));
|
||
auto subtitle = (entry.pinned ? L"★ " : L"") + std::to_wstring(draw.itemID + 1) + L" · " + entry.app + L" · " + (entry.computer.empty()?L"This computer":entry.computerName);
|
||
DrawTextW(dc, subtitle.c_str(), -1, &detail, DT_SINGLELINE | DT_END_ELLIPSIS | DT_NOPREFIX);
|
||
if (draw.itemState & ODS_FOCUS)
|
||
{
|
||
InflateRect(&box, -2, -2);
|
||
DrawFocusRect(dc, &box);
|
||
}
|
||
RestoreDC(dc, saved);
|
||
}
|
||
LRESULT CALLBACK historyKey(HWND w, UINT msg, WPARAM wp, LPARAM lp, UINT_PTR, DWORD_PTR data)
|
||
{
|
||
HWND parent = (HWND)data;
|
||
if (msg == WM_KEYDOWN)
|
||
{
|
||
if (wp == VK_ESCAPE)
|
||
{
|
||
SendMessageW(parent, WM_CLOSE, 0, 0);
|
||
return 0;
|
||
}
|
||
if (wp == VK_RETURN)
|
||
{
|
||
SendMessageW(parent, WM_COMMAND, (GetKeyState(VK_SHIFT) & 0x8000) ? 111 : 110, 0);
|
||
return 0;
|
||
}
|
||
if (GetKeyState(VK_CONTROL) & 0x8000)
|
||
{
|
||
if (wp >= L'1' && wp <= L'9')
|
||
{
|
||
SendDlgItemMessageW(parent, 102, LB_SETCURSEL, wp - L'1', 0);
|
||
SendMessageW(parent, WM_COMMAND, 110, 0);
|
||
return 0;
|
||
}
|
||
if (wp == L'P')
|
||
{
|
||
SendMessageW(parent, WM_COMMAND, 112, 0);
|
||
return 0;
|
||
}
|
||
if (wp == L'O')
|
||
{
|
||
SendMessageW(parent, WM_COMMAND, 114, 0);
|
||
return 0;
|
||
}
|
||
}
|
||
if (GetDlgCtrlID(w) == 102 && wp == VK_DELETE)
|
||
{
|
||
SendMessageW(parent, WM_COMMAND, 113, 0);
|
||
return 0;
|
||
}
|
||
if (GetDlgCtrlID(w) == 101 && wp == VK_DOWN)
|
||
{
|
||
SetFocus(GetDlgItem(parent, 102));
|
||
return 0;
|
||
}
|
||
}
|
||
return DefSubclassProc(w, msg, wp, lp);
|
||
}
|
||
LRESULT CALLBACK historyProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||
{
|
||
auto *v = (HistoryView *)GetWindowLongPtrW(w, GWLP_USERDATA);
|
||
if (msg == WM_NCCREATE)
|
||
{
|
||
auto *app = (App *)((CREATESTRUCTW *)lp)->lpCreateParams;
|
||
v = new HistoryView;
|
||
v->app = app;
|
||
SetWindowLongPtrW(w, GWLP_USERDATA, (LONG_PTR)v);
|
||
return TRUE;
|
||
}
|
||
if (!v)
|
||
return DefWindowProcW(w, msg, wp, lp);
|
||
try
|
||
{
|
||
switch (msg)
|
||
{
|
||
case ScrollActivity:
|
||
if((HWND)wp==GetDlgItem(w,102)) {
|
||
v->scrolling=lp!=0;
|
||
if(!v->scrolling) InvalidateRect((HWND)wp,nullptr,FALSE);
|
||
}
|
||
return 0;
|
||
case WM_COMMAND:
|
||
{
|
||
int id = LOWORD(wp);
|
||
if(id==118&&HIWORD(wp)==BN_CLICKED){showComputerFilter(w,v);return 0;}
|
||
if (id == 117 && HIWORD(wp) == BN_CLICKED)
|
||
{
|
||
KillTimer(w, 1);
|
||
search(w, v);
|
||
return 0;
|
||
}
|
||
if (id == 101 && HIWORD(wp) == EN_CHANGE)
|
||
{
|
||
// Reject an older result even during the debounce interval.
|
||
++v->generation;
|
||
SetTimer(w, 1, 180, nullptr);
|
||
return 0;
|
||
}
|
||
if (id == 102 && HIWORD(wp) == LBN_SELCHANGE)
|
||
{
|
||
updateHistoryActions(w,v);
|
||
return 0;
|
||
}
|
||
if (id == 102 && HIWORD(wp) == LBN_DBLCLK)
|
||
id = 110;
|
||
if (id == 116)
|
||
{
|
||
if (MessageBoxW(w, L"Delete all clipboard history, including pinned items? This also deletes items hidden by the current search.",
|
||
L"Clear history", MB_YESNO | MB_ICONWARNING | MB_DEFBUTTON2) == IDYES)
|
||
v->app->clearHistory();
|
||
return 0;
|
||
}
|
||
auto entry = selected(w, v);
|
||
if (id == 110 || id == 111)
|
||
{
|
||
if (!entry.empty())
|
||
v->app->pasteEntry(entry, id == 111);
|
||
return 0;
|
||
}
|
||
if (id == 112 || id == 113)
|
||
{
|
||
if (!entry.empty())
|
||
{
|
||
if (v->app->historyService) {
|
||
v->app->remoteHistory(id == 112 ? "pin" : "remove", entry);
|
||
v->app->history->reload();
|
||
} else if (id == 112)
|
||
v->app->history->pin(entry);
|
||
else
|
||
v->app->history->remove(entry);
|
||
search(w, v);
|
||
}
|
||
return 0;
|
||
}
|
||
if (id == 115 && !entry.empty())
|
||
{
|
||
v->app->recognizeEntry(entry);
|
||
return 0;
|
||
}
|
||
if (id == 114 && !entry.empty())
|
||
{
|
||
showEntry(*v->app, entry);
|
||
return 0;
|
||
}
|
||
return 0;
|
||
}
|
||
case WM_TIMER:
|
||
KillTimer(w, 1);
|
||
if (v->closed) return 0;
|
||
search(w, v);
|
||
return 0;
|
||
case ResultsMessage:
|
||
{
|
||
std::unique_ptr<SearchResult> result((SearchResult *)lp);
|
||
if (result->generation != v->generation)
|
||
return 0;
|
||
auto old = selected(w, v);
|
||
if (old.empty()) old = v->rememberedSelection;
|
||
int top=(int)SendDlgItemMessageW(w,102,LB_GETTOPINDEX,0,0);
|
||
auto topId=top>=0 && top<(int)v->items.size()?v->items[top].id:L"";
|
||
if (topId.empty()) topId = v->rememberedTop;
|
||
if (v->selectFirstOnResults)
|
||
{
|
||
old.clear();
|
||
topId.clear();
|
||
v->rememberedSelection.clear();
|
||
v->rememberedTop.clear();
|
||
v->selectFirstOnResults = false;
|
||
}
|
||
v->items = std::move(result->items);
|
||
SendDlgItemMessageW(w, 102, WM_SETREDRAW, FALSE, 0);
|
||
SendDlgItemMessageW(w, 102, LB_RESETCONTENT, 0, 0);
|
||
int select = 0;
|
||
int restoreTop=0;
|
||
for (size_t i = 0; i < v->items.size(); ++i)
|
||
{
|
||
auto &e = v->items[i];
|
||
auto text = (e.pinned ? L"★ " : L"") + e.preview + L" — " + e.app;
|
||
SendDlgItemMessageW(w, 102, LB_ADDSTRING, 0, (LPARAM)text.c_str());
|
||
if (e.id == old)
|
||
select = (int)i;
|
||
if(e.id==topId) restoreTop=(int)i;
|
||
}
|
||
SendDlgItemMessageW(w, 102, LB_SETCURSEL, select, 0);
|
||
SendDlgItemMessageW(w,102,LB_SETTOPINDEX,restoreTop,0);
|
||
updateHistoryActions(w,v);
|
||
SendDlgItemMessageW(w, 102, WM_SETREDRAW, TRUE, 0);
|
||
InvalidateRect(GetDlgItem(w, 102), nullptr, TRUE);
|
||
return 0;
|
||
}
|
||
case PreviewMessage:
|
||
{
|
||
std::unique_ptr<PreviewResult> result((PreviewResult *)lp);
|
||
if (result->generation != v->generation || !IsWindowVisible(w))
|
||
return 0;
|
||
v->pending.erase(result->id);
|
||
auto list=GetDlgItem(w,102);
|
||
RECT client{}; GetClientRect(list,&client);
|
||
std::set<std::wstring> visible;
|
||
RECT changed{}; bool repaint=false;
|
||
int top=(int)SendMessageW(list,LB_GETTOPINDEX,0,0);
|
||
for(int i=std::max(0,top);i<(int)v->items.size();++i) {
|
||
RECT row{}, intersection{};
|
||
if(SendMessageW(list,LB_GETITEMRECT,i,(LPARAM)&row)==LB_ERR || row.top>=client.bottom) break;
|
||
if(!IntersectRect(&intersection,&row,&client)) continue;
|
||
visible.insert(v->items[i].id);
|
||
if(v->items[i].id==result->id) { changed=intersection; repaint=true; }
|
||
}
|
||
if (!result->text.rtf.empty() || !result->text.plain.empty())
|
||
v->richTexts[result->id] = std::move(result->text);
|
||
else
|
||
v->thumbnails[result->id] = std::move(result->pixels);
|
||
trimHistoryPreviews(v->thumbnails,visible,32,HistoryThumbnailBudget,
|
||
[](const Pixels &p) { return p.bgra.capacity(); });
|
||
trimHistoryPreviews(v->richTexts,visible,32,HistoryRichTextBudget,
|
||
[](const TextPreview &s) { return s.rtf.capacity() + s.plain.capacity() * sizeof(wchar_t); });
|
||
if(repaint) InvalidateRect(list,&changed,FALSE);
|
||
return 0;
|
||
}
|
||
case WM_MEASUREITEM:
|
||
if (((MEASUREITEMSTRUCT *)lp)->CtlID == 102)
|
||
{
|
||
((MEASUREITEMSTRUCT *)lp)->itemHeight = scale(w, 88);
|
||
return TRUE;
|
||
}
|
||
break;
|
||
case WM_DRAWITEM:
|
||
if (((DRAWITEMSTRUCT *)lp)->CtlID == 102)
|
||
{
|
||
drawHistoryRow(w, v, *(DRAWITEMSTRUCT *)lp);
|
||
return TRUE;
|
||
}
|
||
break;
|
||
case WM_CONTEXTMENU:
|
||
{
|
||
auto list=GetDlgItem(w,102);
|
||
if((HWND)wp!=list) break;
|
||
POINT p{(short)LOWORD(lp),(short)HIWORD(lp)};
|
||
if(lp!=-1) {
|
||
POINT hit=p; ScreenToClient(list,&hit);
|
||
auto item=SendMessageW(list,LB_ITEMFROMPOINT,0,MAKELPARAM(hit.x,hit.y));
|
||
if(HIWORD(item)) return 0;
|
||
SendMessageW(list,LB_SETCURSEL,LOWORD(item),0);
|
||
updateHistoryActions(w,v);
|
||
} else {
|
||
RECT row{};
|
||
auto index=SendMessageW(list,LB_GETCURSEL,0,0);
|
||
if(index==LB_ERR) return 0;
|
||
SendMessageW(list,LB_GETITEMRECT,index,(LPARAM)&row);
|
||
p={row.left,row.top}; ClientToScreen(list,&p);
|
||
}
|
||
HMENU menu = CreatePopupMenu();
|
||
AppendMenuW(menu, MF_STRING, 110, L"&Paste");
|
||
AppendMenuW(menu, MF_STRING, 111, L"Paste plain &text");
|
||
AppendMenuW(menu, MF_STRING, 112, L"P&in / unpin");
|
||
AppendMenuW(menu, MF_STRING, 113, L"&Delete");
|
||
AppendMenuW(menu, MF_STRING, 114, selectedImage(w,v)?L"&Edit image in screenshot editor":L"&Open full item");
|
||
AppendMenuW(menu, MF_STRING, 115, L"&Copy text from image (OCR)");
|
||
showMenuAccessKeys(menu);
|
||
int cmd = TrackPopupMenu(menu, TPM_RETURNCMD, p.x, p.y, 0, w, nullptr);
|
||
DestroyMenu(menu);
|
||
if (cmd)
|
||
SendMessageW(w, WM_COMMAND, cmd, 0);
|
||
return 0;
|
||
}
|
||
case WM_CLOSE:
|
||
{
|
||
v->rememberedSelection = selected(w, v);
|
||
int top = (int)SendDlgItemMessageW(w,102,LB_GETTOPINDEX,0,0);
|
||
v->rememberedTop = top >= 0 && top < (int)v->items.size() ? v->items[top].id : L"";
|
||
v->app->saveHistoryView(v->rememberedSelection, v->rememberedTop, value(w, 101),
|
||
SendDlgItemMessageW(w, 117, BM_GETCHECK, 0, 0) == BST_CHECKED);
|
||
KillTimer(w, 1);
|
||
v->closed = true;
|
||
v->previewActive->store(false);
|
||
++v->generation; // Discard search/preview results queued before closing.
|
||
ShowWindow(w, SW_HIDE);
|
||
SendDlgItemMessageW(w,102,LB_RESETCONTENT,0,0);
|
||
std::vector<Entry>().swap(v->items);
|
||
v->thumbnails.clear();
|
||
v->richTexts.clear();
|
||
if (v->rich) SetWindowTextW(v->rich, L"");
|
||
v->pending.clear();
|
||
if (v->app->historyService && !v->app->historyEntryWindows)
|
||
PostMessageW(v->app->window, WM_CLOSE, 0, 0);
|
||
return 0;
|
||
}
|
||
case WM_NCDESTROY:
|
||
v->previewActive->store(false);
|
||
disposeFont(w);
|
||
v->app->historyWindow = nullptr;
|
||
delete v;
|
||
return DefWindowProcW(w, msg, wp, lp);
|
||
}
|
||
}
|
||
catch (const std::exception &e)
|
||
{
|
||
error(w, e);
|
||
}
|
||
return DefWindowProcW(w, msg, wp, lp);
|
||
}
|
||
|
||
#endif
|
||
#ifndef KS_RESIDENT_APP
|
||
constexpr int LanguagesPage = 1, ShortcutsPage = 2, ClipboardPage = 3, SnippetsPage = 4, MousePage = 5;
|
||
constexpr int ExceptionsPage = 13, PersonalDictionariesPage = 14, WordBoundariesPage = 15, SnippetMacros = 320;
|
||
constexpr UINT AppWindowPicked = WM_APP + 78;
|
||
constexpr int SettingsNavigation = 260, SettingsStatus = 261, SettingsViewport = 264, SettingsApply = 272;
|
||
constexpr int SettingsBrand = 265, SettingsHeading = 266, SettingsDescription = 267, SettingsGroup = 268;
|
||
constexpr int SettingsSearch = 269, GeneralPage = 0, ComputersPage = 7, ManageComputersPage = 10, CorrectionPage = 11;
|
||
constexpr int SyncPage = 6, OpenBaoPage = 17, SettingsSyncPanel = 271;
|
||
constexpr UINT CollapseSettingsGroupMessage = WM_APP + 188;
|
||
constexpr int SettingsSidebarWidth = 214, SettingsHeaderHeight = 82, SettingsFooterHeight = 76;
|
||
constexpr int SettingsNavigationIndent = 16;
|
||
constexpr int SettingsSplitter = 270, SettingsSplitterWidth = 8;
|
||
constexpr int SettingsSidebarMin = 164, SettingsSidebarMax = 420, SettingsPaneMin = 320;
|
||
constexpr int SettingsContentWidth = 738;
|
||
constexpr int SettingsMinWidth = 620, SettingsMinHeight = 418;
|
||
constexpr struct SettingsSection
|
||
{
|
||
const char *key;
|
||
const wchar_t *name, *description;
|
||
int parent = -1;
|
||
} settingsSections[] = {
|
||
{"general", L"General", L"Configure text conversion and how KSwitcher runs on Windows."},
|
||
{"languages", L"Languages", L"Order layouts from top to bottom and override the cycle for individual chats or apps."},
|
||
{"shortcuts", L"Shortcuts", L"Click a shortcut field and press the desired keys. Backspace or Delete clears it."},
|
||
{"clipboard", L"Clipboard", L"Configure clipboard history, storage limits and text recognition."},
|
||
{"snippets", L"Snippets", L"Create text expansions and choose which applications can use them."},
|
||
{"mouse", L"Mouse", L"Manage profiles, assign actions and test your mouse buttons."},
|
||
{"sync", L"Sync", L"Back up and synchronize settings through OpenBao."},
|
||
{"computers", L"Computers", L"Share mouse and keyboard with paired computers."},
|
||
{"diagnostics", L"Diagnostics", L"Manage diagnostic logging and view recent operations."},
|
||
{"mcp", L"MCP", L"Connect Codex to KSwitcher to read diagnostic logs."},
|
||
{"manage-computers", L"Manage computers", L"Pair computers, arrange their screens and manage input sharing.", ComputersPage},
|
||
{"correction", L"Correction options", L"Choose a subsection to configure automatic correction.", GeneralPage},
|
||
{"offline-dictionaries", L"Offline dictionaries", L"Choose dictionary languages and set limits for automatic correction.", CorrectionPage},
|
||
{"correction-exceptions", L"Exceptions", L"Exclude applications and words from automatic correction.", CorrectionPage},
|
||
{"personal-dictionaries", L"Personal dictionaries", L"Separate words with commas or new lines. Internal hyphens are allowed.", CorrectionPage},
|
||
{"word-boundaries", L"Word boundaries", L"Choose which punctuation KSwitcher keeps before and after a corrected word.", CorrectionPage},
|
||
{"custom-replacements", L"Custom replacements", L"Define your own corrections, which take priority over dictionary suggestions.", CorrectionPage},
|
||
{"openbao", L"OpenBao", L"Connect to OpenBao and synchronize your saved settings.", SyncPage},
|
||
};
|
||
constexpr wchar_t SettingsWindowFile[] = L"configurator-window.json";
|
||
struct SettingsWindowState
|
||
{
|
||
std::optional<RECT> frame;
|
||
UINT dpi = 96;
|
||
int page = GeneralPage;
|
||
int sidebar = SettingsSidebarWidth;
|
||
bool maximized{};
|
||
};
|
||
SettingsWindowState loadSettingsWindowState(const App &app)
|
||
{
|
||
SettingsWindowState state;
|
||
try
|
||
{
|
||
const auto file = app.data / SettingsWindowFile;
|
||
if (!std::filesystem::exists(file)) return state;
|
||
const auto bytes = readFile(file, 8192);
|
||
const auto data = nlohmann::json::parse(bytes);
|
||
if (!data.is_object()) return state;
|
||
const auto key = data.value("page", std::string{});
|
||
for (int index = 0; index < static_cast<int>(std::size(settingsSections)); ++index)
|
||
if (key == settingsSections[index].key) state.page = index;
|
||
state.sidebar = std::clamp(data.value("sidebar", SettingsSidebarWidth), SettingsSidebarMin, SettingsSidebarMax);
|
||
state.maximized = data.value("maximized", false);
|
||
state.dpi = std::clamp(data.value("dpi", 96), 48, 960);
|
||
const auto bounds = data.value("frame", std::vector<int>{});
|
||
if (bounds.size() == 4 &&
|
||
std::all_of(bounds.begin(), bounds.end(), [](int value) { return value >= -100000 && value <= 100000; }) &&
|
||
bounds[2] > bounds[0] && bounds[3] > bounds[1])
|
||
state.frame = RECT{bounds[0], bounds[1], bounds[2], bounds[3]};
|
||
}
|
||
catch (const std::exception &)
|
||
{
|
||
return {};
|
||
}
|
||
return state;
|
||
}
|
||
void restoreSettingsWindowFrame(HWND w, const SettingsWindowState &state)
|
||
{
|
||
if (!state.frame) return;
|
||
auto frame = *state.frame;
|
||
const auto monitor = MonitorFromRect(&frame, MONITOR_DEFAULTTONEAREST);
|
||
if (monitor != MonitorFromWindow(w, MONITOR_DEFAULTTONEAREST)) fitToMonitor(w, frame);
|
||
const UINT dpi = GetDpiForWindow(w);
|
||
frame.right = frame.left + MulDiv(frame.right - frame.left, dpi, state.dpi);
|
||
frame.bottom = frame.top + MulDiv(frame.bottom - frame.top, dpi, state.dpi);
|
||
fitToMonitor(w, frame);
|
||
}
|
||
HWND settingsPage(HWND w)
|
||
{
|
||
if (HWND pane = GetDlgItem(w, SettingsViewport)) return pane;
|
||
return w;
|
||
}
|
||
void settingsGroupLabel(HWND pane, const wchar_t *name, int x, int y, int width = 660)
|
||
{
|
||
control(pane, L"STATIC", name, 0, SettingsGroup, x, y, width, 22);
|
||
}
|
||
struct SnippetView
|
||
{
|
||
App *app{};
|
||
std::vector<Snippet> snippets, saved;
|
||
int selection = -1;
|
||
HWND pickerOutline{};
|
||
bool filling{};
|
||
};
|
||
class WindowPalette
|
||
{
|
||
public:
|
||
WindowPalette() = default;
|
||
WindowPalette(const WindowPalette &) = delete;
|
||
WindowPalette &operator=(const WindowPalette &) = delete;
|
||
~WindowPalette() { if (brush_) DeleteObject(brush_); }
|
||
|
||
void refresh(std::optional<DWORD> colorization = std::nullopt)
|
||
{
|
||
HIGHCONTRASTW contrast{sizeof(contrast)};
|
||
highContrast = SystemParametersInfoW(SPI_GETHIGHCONTRAST, sizeof(contrast), &contrast, 0) &&
|
||
(contrast.dwFlags & HCF_HIGHCONTRASTON);
|
||
const auto background = GetSysColor(COLOR_WINDOW);
|
||
if (brush_) DeleteObject(brush_);
|
||
brush_ = nullptr;
|
||
if (highContrast) return;
|
||
|
||
DWORD argb{};
|
||
BOOL opaque{};
|
||
if (!colorization && SUCCEEDED(DwmGetColorizationColor(&argb, &opaque)))
|
||
colorization = argb;
|
||
const auto accent = colorization ? RGB(*colorization >> 16, *colorization >> 8, *colorization)
|
||
: GetSysColor(COLOR_HIGHLIGHT);
|
||
// Keep system window text readable even with a saturated accent.
|
||
const auto tint = [](int base, int accentChannel) { return (base * 92 + accentChannel * 8 + 50) / 100; };
|
||
color_ = RGB(tint(GetRValue(background), GetRValue(accent)),
|
||
tint(GetGValue(background), GetGValue(accent)),
|
||
tint(GetBValue(background), GetBValue(accent)));
|
||
brush_ = CreateSolidBrush(color_);
|
||
}
|
||
|
||
COLORREF color() const { return brush_ ? color_ : GetSysColor(COLOR_WINDOW); }
|
||
HBRUSH brush() const { return brush_ ? brush_ : GetSysColorBrush(COLOR_WINDOW); }
|
||
bool highContrast{};
|
||
|
||
private:
|
||
COLORREF color_{};
|
||
HBRUSH brush_{};
|
||
};
|
||
struct SettingsView
|
||
{
|
||
App *app{};
|
||
Settings draft;
|
||
std::vector<int> order;
|
||
int selection = -1;
|
||
bool filling{};
|
||
struct Page
|
||
{
|
||
size_t first{}, end{};
|
||
int height{};
|
||
int x{}, y{};
|
||
};
|
||
std::array<Page, std::size(settingsSections)> pages;
|
||
int selectedPage = -1;
|
||
HWND viewport{}, navigation{}, search{}, heading{}, description{}, brand{}, lan{}, sync{}, splitter{};
|
||
int sidebarWidth = SettingsSidebarWidth;
|
||
std::optional<int> splitterDragOffset;
|
||
bool splitterHovered{};
|
||
std::array<HTREEITEM, std::size(settingsSections)> navigationItems{};
|
||
struct SearchEntry { int page; HWND caption, target; std::wstring title, aliases; bool matched{}; };
|
||
std::vector<SearchEntry> searchEntries;
|
||
std::optional<size_t> activeSearchEntry;
|
||
std::vector<std::wstring> searchTerms;
|
||
bool rebuildingNavigation{}, searching{};
|
||
HFONT headingFont{}, brandFont{}, groupFont{}, fieldFont{};
|
||
WindowPalette palette;
|
||
bool ready{}, refreshing{}, wasShown{};
|
||
std::vector<std::wstring> mouseProfiles;
|
||
std::array<HICON, 2> mouseProfileChecks{};
|
||
SIZE mouseProfileCheckSize{};
|
||
unsigned mouseEvents{}, rawMouseEvents{};
|
||
bool rawMouseRegistered{};
|
||
SnippetView snippets;
|
||
};
|
||
void saveSettingsWindowState(HWND w, const SettingsView &v)
|
||
{
|
||
if (!v.ready || !v.wasShown || v.selectedPage < 0) return;
|
||
WINDOWPLACEMENT placement{sizeof(placement)};
|
||
if (!GetWindowPlacement(w, &placement)) return;
|
||
const bool minimized = IsIconic(w) != FALSE;
|
||
const bool maximized = IsZoomed(w) || (minimized && (placement.flags & WPF_RESTORETOMAXIMIZED));
|
||
RECT frame{};
|
||
if (minimized || maximized)
|
||
{
|
||
MONITORINFO monitor{sizeof(monitor)};
|
||
if (!GetMonitorInfoW(MonitorFromWindow(w, MONITOR_DEFAULTTONEAREST), &monitor)) return;
|
||
frame = placement.rcNormalPosition;
|
||
// WINDOWPLACEMENT uses workspace coordinates for ordinary top-level windows.
|
||
OffsetRect(&frame, monitor.rcWork.left - monitor.rcMonitor.left, monitor.rcWork.top - monitor.rcMonitor.top);
|
||
}
|
||
else if (!GetWindowRect(w, &frame)) return;
|
||
|
||
try
|
||
{
|
||
const nlohmann::json data{{"frame", {frame.left, frame.top, frame.right, frame.bottom}},
|
||
{"dpi", GetDpiForWindow(w)}, {"maximized", maximized}, {"page", settingsSections[v.selectedPage].key},
|
||
{"sidebar", v.sidebarWidth}};
|
||
const auto text = data.dump();
|
||
atomicWrite(v.app->data / SettingsWindowFile, Bytes(text.begin(), text.end()));
|
||
}
|
||
catch (const std::exception &e)
|
||
{
|
||
log(L"Could not save configurator window state: " + wide(e.what()));
|
||
}
|
||
}
|
||
bool snippetCommand(HWND, SnippetView *, WPARAM);
|
||
void snippetWindowPicked(HWND w, WPARAM target, LPARAM phase);
|
||
bool snippetDraftChanged(HWND, SnippetView *);
|
||
bool mergeSnippetDraft(HWND, SnippetView *, Settings &);
|
||
void refreshSnippetDraft(HWND, SnippetView *);
|
||
void updateSettingsState(HWND w, SettingsView *v);
|
||
bool matchesSettingsSearch(const SettingsView &v, const std::wstring &text)
|
||
{
|
||
if (!v.searching) return false;
|
||
const auto candidate = lower(text);
|
||
return std::all_of(v.searchTerms.begin(), v.searchTerms.end(), [&](const auto &term)
|
||
{
|
||
return candidate.find(term) != std::wstring::npos;
|
||
});
|
||
}
|
||
void paintSettingsMatches(HWND pane)
|
||
{
|
||
HWND root = GetAncestor(pane, GA_ROOT);
|
||
auto *v = reinterpret_cast<SettingsView *>(GetWindowLongPtrW(root, GWLP_USERDATA));
|
||
PAINTSTRUCT paint{};
|
||
HDC dc = BeginPaint(pane, &paint);
|
||
if (v && v->searching)
|
||
{
|
||
auto brush = reinterpret_cast<HBRUSH>(GetStockObject(DC_BRUSH));
|
||
const int padding = scale(pane, 3);
|
||
auto drawMatch = [&](const SettingsView::SearchEntry &entry, bool active)
|
||
{
|
||
if (!entry.matched || entry.page != v->selectedPage) return;
|
||
SetDCBrushColor(dc, v->palette.highContrast ? GetSysColor(COLOR_HIGHLIGHT) :
|
||
active ? RGB(7, 97, 83) : RGB(157, 111, 21));
|
||
const int stroke = scale(pane, active ? 2 : 1);
|
||
for (HWND mark : {entry.caption, entry.target == entry.caption ? nullptr : entry.target})
|
||
{
|
||
if (!mark || GetParent(mark) != pane || !IsWindowVisible(mark)) continue;
|
||
RECT bounds{};
|
||
GetWindowRect(mark, &bounds);
|
||
MapWindowPoints(nullptr, pane, reinterpret_cast<POINT *>(&bounds), 2);
|
||
InflateRect(&bounds, padding, padding);
|
||
for (int line = 0; line < stroke; ++line)
|
||
{
|
||
FrameRect(dc, &bounds, brush);
|
||
InflateRect(&bounds, -1, -1);
|
||
}
|
||
}
|
||
};
|
||
for (size_t index = 0; index < v->searchEntries.size(); ++index)
|
||
if (index != v->activeSearchEntry) drawMatch(v->searchEntries[index], false);
|
||
if (v->activeSearchEntry) drawMatch(v->searchEntries[*v->activeSearchEntry], true);
|
||
}
|
||
EndPaint(pane, &paint);
|
||
}
|
||
void repaintSettingsMatches(const SettingsView &v)
|
||
{
|
||
InvalidateRect(v.viewport, nullptr, TRUE);
|
||
if (v.lan) InvalidateRect(v.lan, nullptr, TRUE);
|
||
if (v.sync) InvalidateRect(v.sync, nullptr, TRUE);
|
||
}
|
||
LRESULT CALLBACK settingsViewportProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||
{
|
||
switch (msg)
|
||
{
|
||
case WM_COMMAND: case WM_NOTIFY: case WM_DRAWITEM: case WM_CTLCOLORSTATIC:
|
||
return SendMessageW(GetParent(w), msg, wp, lp);
|
||
case WM_PAINT:
|
||
paintSettingsMatches(w);
|
||
return 0;
|
||
}
|
||
return DefWindowProcW(w, msg, wp, lp);
|
||
}
|
||
int clampSettingsSidebar(HWND w, int available, int requested)
|
||
{
|
||
const int maximum = std::clamp(available - scale(w, SettingsPaneMin + SettingsSplitterWidth),
|
||
0, scale(w, SettingsSidebarMax));
|
||
return std::clamp(requested, std::min(maximum, scale(w, SettingsSidebarMin)), maximum);
|
||
}
|
||
int settingsCaptionHeight(HWND caption, int width);
|
||
void layoutSettings(HWND w, const SettingsView &v)
|
||
{
|
||
if (!v.viewport) return;
|
||
RECT bounds{};
|
||
GetClientRect(w, &bounds);
|
||
const int width = bounds.right, height = bounds.bottom;
|
||
const int sidebar = clampSettingsSidebar(w, width, scale(w, v.sidebarWidth));
|
||
const int split = scale(w, SettingsSplitterWidth);
|
||
const int paneLeft = sidebar + split, footer = height - scale(w, SettingsFooterHeight);
|
||
const int left = paneLeft + scale(w, 24);
|
||
const int titleWidth = std::max(1, width - left - scale(w, 18));
|
||
const int descriptionHeight = settingsCaptionHeight(v.description,
|
||
std::max(1, MulDiv(titleWidth, 96, GetDpiForWindow(w))));
|
||
const int header = scale(w, std::max(SettingsHeaderHeight, 60 + descriptionHeight));
|
||
const int margin = scale(w, 18), gap = scale(w, 10);
|
||
const int slot = std::max(0, (width - 2 * margin - 4 * gap) / 5);
|
||
const int transferWidth = std::min(scale(w, 112), slot), commitWidth = std::min(scale(w, 100), slot);
|
||
const int actionTop = footer + scale(w, 34), actionHeight = scale(w, 30);
|
||
std::vector<WindowMove> moves;
|
||
auto move = [&](HWND child, int x, int y, int cx, int cy)
|
||
{
|
||
if (!child) return;
|
||
RECT current{};
|
||
GetWindowRect(child, ¤t);
|
||
MapWindowPoints(nullptr, w, reinterpret_cast<POINT *>(¤t), 2);
|
||
RECT next{x, y, x + std::max(0, cx), y + std::max(0, cy)};
|
||
if (!EqualRect(¤t, &next)) moves.push_back({child, next});
|
||
};
|
||
move(v.brand, scale(w, 54), scale(w, 20), std::min(scale(w, 118), sidebar - scale(w, 60)), scale(w, 28));
|
||
move(v.search, scale(w, 12), scale(w, 58), sidebar - scale(w, 24), scale(w, 29));
|
||
move(v.navigation, scale(w, 10), scale(w, 97), sidebar - scale(w, 20), footer - scale(w, 105));
|
||
move(v.splitter, sidebar, 0, split, footer);
|
||
move(v.heading, left, scale(w, 13), titleWidth, scale(w, 37));
|
||
move(v.description, left, scale(w, 53), titleWidth, scale(w, descriptionHeight));
|
||
move(v.viewport, paneLeft, header, width - paneLeft, footer - header);
|
||
move(GetDlgItem(w, SettingsStatus), margin, footer + scale(w, 9), width - 2 * margin, scale(w, 20));
|
||
move(GetDlgItem(w, 250), margin, actionTop, transferWidth, actionHeight);
|
||
move(GetDlgItem(w, 251), margin + transferWidth + gap, actionTop, transferWidth, actionHeight);
|
||
move(GetDlgItem(w, SettingsApply), width - margin - 3 * commitWidth - 2 * gap, actionTop, commitWidth, actionHeight);
|
||
move(GetDlgItem(w, IDOK), width - margin - 2 * commitWidth - gap, actionTop, commitWidth, actionHeight);
|
||
move(GetDlgItem(w, IDCANCEL), width - margin - commitWidth, actionTop, commitWidth, actionHeight);
|
||
if (moves.empty()) return;
|
||
// Repaint after the final positions are in place. Copying old window bits
|
||
// during the move can leave splitter pixels in the heading or in a sibling.
|
||
applyWindowMoves(moves, SWP_NOREDRAW | SWP_NOCOPYBITS);
|
||
RedrawWindow(w, nullptr, nullptr, RDW_INVALIDATE | RDW_ERASE | RDW_ALLCHILDREN);
|
||
}
|
||
void moveSettingsSplitter(HWND w, SettingsView &v, int position)
|
||
{
|
||
RECT client{};
|
||
GetClientRect(w, &client);
|
||
const int pixels = clampSettingsSidebar(w, client.right, position);
|
||
const int width = MulDiv(pixels, 96, GetDpiForWindow(w));
|
||
if (width == v.sidebarWidth) return;
|
||
v.sidebarWidth = width;
|
||
layoutSettings(w, v);
|
||
}
|
||
LRESULT CALLBACK settingsSplitterProc(HWND splitter, UINT message, WPARAM wp, LPARAM lp,
|
||
UINT_PTR id, DWORD_PTR data)
|
||
{
|
||
auto &v = *reinterpret_cast<SettingsView *>(data);
|
||
HWND root = GetParent(splitter);
|
||
switch (message)
|
||
{
|
||
case WM_SETCURSOR:
|
||
SetCursor(LoadCursorW(nullptr, IDC_SIZEWE));
|
||
return TRUE;
|
||
case WM_GETDLGCODE:
|
||
return DLGC_WANTARROWS;
|
||
case WM_LBUTTONDOWN:
|
||
SetFocus(splitter);
|
||
SetCapture(splitter);
|
||
if (GetCapture() == splitter) v.splitterDragOffset = GET_X_LPARAM(lp);
|
||
InvalidateRect(splitter, nullptr, FALSE);
|
||
return 0;
|
||
case WM_LBUTTONDBLCLK:
|
||
moveSettingsSplitter(root, v, scale(root, SettingsSidebarWidth));
|
||
return 0;
|
||
case WM_MOUSEMOVE:
|
||
if (v.splitterDragOffset)
|
||
{
|
||
POINT pt{GET_X_LPARAM(lp), GET_Y_LPARAM(lp)};
|
||
MapWindowPoints(splitter, root, &pt, 1);
|
||
moveSettingsSplitter(root, v, pt.x - *v.splitterDragOffset);
|
||
}
|
||
else if (!v.splitterHovered)
|
||
{
|
||
TRACKMOUSEEVENT track{sizeof(track), TME_LEAVE, splitter};
|
||
v.splitterHovered = TrackMouseEvent(&track) != FALSE;
|
||
InvalidateRect(splitter, nullptr, FALSE);
|
||
}
|
||
return 0;
|
||
case WM_MOUSELEAVE:
|
||
v.splitterHovered = false;
|
||
InvalidateRect(splitter, nullptr, FALSE);
|
||
return 0;
|
||
case WM_LBUTTONUP: case WM_CANCELMODE:
|
||
if (GetCapture() == splitter) ReleaseCapture();
|
||
return 0;
|
||
case WM_CAPTURECHANGED:
|
||
v.splitterDragOffset.reset();
|
||
InvalidateRect(splitter, nullptr, FALSE);
|
||
return 0;
|
||
case WM_KEYDOWN:
|
||
if (wp == VK_LEFT || wp == VK_RIGHT)
|
||
{
|
||
RECT bounds{};
|
||
GetWindowRect(splitter, &bounds);
|
||
MapWindowPoints(nullptr, root, reinterpret_cast<POINT *>(&bounds), 2);
|
||
moveSettingsSplitter(root, v, bounds.left + scale(root, wp == VK_LEFT ? -12 : 12));
|
||
return 0;
|
||
}
|
||
break;
|
||
case WM_SETFOCUS: case WM_KILLFOCUS:
|
||
InvalidateRect(splitter, nullptr, FALSE);
|
||
break;
|
||
case WM_PAINT:
|
||
{
|
||
PAINTSTRUCT paint{};
|
||
HDC dc = BeginPaint(splitter, &paint);
|
||
RECT client{};
|
||
GetClientRect(splitter, &client);
|
||
FillRect(dc, &client, GetSysColorBrush(COLOR_WINDOW));
|
||
const bool focused = GetFocus() == splitter;
|
||
const bool active = v.splitterHovered || v.splitterDragOffset || focused;
|
||
SetDCBrushColor(dc, v.palette.highContrast ? GetSysColor(active ? COLOR_HIGHLIGHT : COLOR_WINDOWTEXT)
|
||
: active ? RGB(7, 97, 83) : RGB(200, 213, 222));
|
||
auto brush = reinterpret_cast<HBRUSH>(GetStockObject(DC_BRUSH));
|
||
const int x = (client.right - 1) / 2, y = client.bottom / 2;
|
||
RECT line{x, 0, x + 1, client.bottom};
|
||
RECT grip{x - 1, y - scale(root, 11), x + 2, y + scale(root, 11)};
|
||
FillRect(dc, &line, brush);
|
||
FillRect(dc, &grip, brush);
|
||
if (focused) DrawFocusRect(dc, &grip);
|
||
EndPaint(splitter, &paint);
|
||
return 0;
|
||
}
|
||
case WM_NCDESTROY:
|
||
RemoveWindowSubclass(splitter, settingsSplitterProc, id);
|
||
break;
|
||
}
|
||
return DefSubclassProc(splitter, message, wp, lp);
|
||
}
|
||
void setSettingsFonts(HWND w, SettingsView &v, UINT dpi)
|
||
{
|
||
auto assign = [](HWND target, HFONT replacement, HFONT &old)
|
||
{
|
||
SendMessageW(target, WM_SETFONT, reinterpret_cast<WPARAM>(replacement), TRUE);
|
||
if (old) DeleteObject(old);
|
||
old = replacement;
|
||
};
|
||
assign(v.heading, font(w, 27, FW_SEMIBOLD), v.headingFont);
|
||
assign(v.brand, font(w, 18, FW_SEMIBOLD), v.brandFont);
|
||
HFONT group = font(w, 15, FW_SEMIBOLD);
|
||
HFONT field = font(w, 14, FW_SEMIBOLD);
|
||
for (HWND pane : {v.viewport, v.lan, v.sync})
|
||
if (pane)
|
||
{
|
||
SetPropW(pane, L"Font", GetPropW(w, L"Font"));
|
||
for (const auto &[child, bounds] : windowLayoutState(pane)->controls)
|
||
SendMessageW(child, WM_SETFONT, reinterpret_cast<WPARAM>(
|
||
GetDlgCtrlID(child) == SettingsGroup ? group : GetPropW(pane, L"Font")), TRUE);
|
||
}
|
||
for (const auto &entry : v.searchEntries)
|
||
if (entry.caption != entry.target)
|
||
SendMessageW(entry.caption, WM_SETFONT, reinterpret_cast<WPARAM>(field), TRUE);
|
||
if (v.groupFont) DeleteObject(v.groupFont);
|
||
if (v.fieldFont) DeleteObject(v.fieldFont);
|
||
v.groupFont = group;
|
||
v.fieldFont = field;
|
||
TreeView_SetIndent(v.navigation, MulDiv(SettingsNavigationIndent, dpi, USER_DEFAULT_SCREEN_DPI));
|
||
TreeView_SetItemHeight(v.navigation, MulDiv(30, dpi, USER_DEFAULT_SCREEN_DPI));
|
||
}
|
||
constexpr const wchar_t *shortcutNames[] = {
|
||
L"Next layout", L"Change case", L"Transliterate", L"Undo", L"Clipboard history",
|
||
L"Screen capture", L"Open KSwitcher Files",
|
||
};
|
||
constexpr int SettingsFormMargin = 24;
|
||
constexpr int ShortcutFieldLeft = 230;
|
||
constexpr int ShortcutFirstRow = 64, ShortcutRowHeight = 40, ShortcutStackedRowHeight = 62;
|
||
constexpr int ShortcutFieldHeight = 25, ShortcutStackedFieldOffset = 24;
|
||
constexpr int ShortcutCheckboxTop = 352, ShortcutRight = 684;
|
||
void reflowShortcuts(HWND pane, WindowLayout &layout, int width, int height)
|
||
{
|
||
const auto &v = *reinterpret_cast<SettingsView *>(GetWindowLongPtrW(GetParent(pane), GWLP_USERDATA));
|
||
const auto &page = v.pages[ShortcutsPage];
|
||
const int rows = static_cast<int>(std::size(shortcutNames));
|
||
const int minColumnsWidth = scale(pane, 440);
|
||
auto pageHeight = [&](bool stacked)
|
||
{
|
||
return page.height + (stacked ? rows * (ShortcutStackedRowHeight - ShortcutRowHeight) : 0);
|
||
};
|
||
if (scale(pane, pageHeight(width < minColumnsWidth)) > height)
|
||
width -= GetSystemMetricsForDpi(SM_CXVSCROLL, GetDpiForWindow(pane));
|
||
const bool stacked = width < minColumnsWidth;
|
||
const int right = std::clamp(MulDiv(width, 96, GetDpiForWindow(pane)) - SettingsFormMargin,
|
||
SettingsFormMargin + 1, ShortcutRight);
|
||
const int fieldLeft = stacked ? SettingsFormMargin : ShortcutFieldLeft;
|
||
layout.height = pageHeight(stacked);
|
||
layout.controls[page.first].second.right = right;
|
||
for (int row = 0; row < rows; ++row)
|
||
{
|
||
const int top = ShortcutFirstRow + row * (stacked ? ShortcutStackedRowHeight : ShortcutRowHeight);
|
||
const int fieldTop = top + (stacked ? ShortcutStackedFieldOffset : 0);
|
||
const int captionTop = top + (stacked ? 0 : 4);
|
||
layout.controls[page.first + 1 + row * 2].second =
|
||
{SettingsFormMargin, captionTop, stacked ? right : SettingsFormMargin + 180, captionTop + 22};
|
||
layout.controls[page.first + 2 + row * 2].second =
|
||
{fieldLeft, fieldTop, right, fieldTop + ShortcutFieldHeight};
|
||
}
|
||
auto &checkbox = layout.controls[page.end - 1].second;
|
||
OffsetRect(&checkbox, 0, ShortcutCheckboxTop + layout.height - page.height - checkbox.top);
|
||
checkbox.right = right;
|
||
}
|
||
int settingsCaptionHeight(HWND caption, int width)
|
||
{
|
||
wchar_t value[256]{};
|
||
GetWindowTextW(caption, value, std::size(value));
|
||
HDC dc = GetDC(caption);
|
||
if (!dc) return 22;
|
||
const auto face = reinterpret_cast<HFONT>(SendMessageW(caption, WM_GETFONT, 0, 0));
|
||
const auto previous = face ? SelectObject(dc, face) : nullptr;
|
||
RECT bounds{0, 0, scale(caption, width), 0};
|
||
DrawTextW(dc, value, -1, &bounds, DT_CALCRECT | DT_WORDBREAK);
|
||
if (previous) SelectObject(dc, previous);
|
||
ReleaseDC(caption, dc);
|
||
return std::max(22, MulDiv(bounds.bottom, 96, GetDpiForWindow(caption)) + 2);
|
||
}
|
||
void captureSettingsGeometry(WindowLayout &layout, size_t first, HWND pane)
|
||
{
|
||
for (size_t i = first; i < layout.controls.size(); ++i)
|
||
{
|
||
const auto &[child, bounds] = layout.controls[i];
|
||
RECT actual{};
|
||
GetWindowRect(child, &actual);
|
||
layout.originalControls.push_back({bounds, MulDiv(actual.bottom - actual.top, 96, GetDpiForWindow(pane))});
|
||
}
|
||
}
|
||
struct SettingsColumns
|
||
{
|
||
int left, right;
|
||
int secondLeft = 0, firstRight = 0, footerTop = 0, wrapAt = 0;
|
||
int compactListHeight = 0;
|
||
int sharedHeaderEnd = 0;
|
||
};
|
||
int fitSettingsColumns(WindowLayout &layout, size_t first, size_t end, int width, SettingsColumns grid)
|
||
{
|
||
// Work from the design coordinates on every pass. Resizing back or changing DPI
|
||
// must not reuse rounded or already-wrapped geometry.
|
||
const int right = std::max(grid.left + 1, width - grid.left);
|
||
const bool stacked = grid.secondLeft && width < grid.wrapAt;
|
||
std::array<std::vector<size_t>, 3> columns;
|
||
for (size_t i = first; i < end; ++i)
|
||
{
|
||
const auto &bounds = layout.originalControls[i].bounds;
|
||
const int column = grid.footerTop && bounds.top >= grid.footerTop ? 2 :
|
||
grid.secondLeft && bounds.left >= grid.secondLeft ? 1 : 0;
|
||
columns[column].push_back(i);
|
||
}
|
||
int bottom = 0;
|
||
for (int column = 0; column < static_cast<int>(columns.size()); ++column)
|
||
{
|
||
auto &items = columns[column];
|
||
if (items.empty()) continue;
|
||
const bool twoColumns = grid.secondLeft && column != 2;
|
||
const int sourceLeft = column == 1 ? grid.secondLeft : grid.left;
|
||
const int sourceRight = twoColumns && column == 0 ? grid.firstRight : grid.right;
|
||
const auto fitX = [&](int x, bool sharedHeader)
|
||
{
|
||
const int available = right - grid.left;
|
||
const int size = grid.right - grid.left;
|
||
if (!stacked || !twoColumns || sharedHeader)
|
||
return grid.left + MulDiv(x - grid.left, std::min(size, available), size);
|
||
return grid.left + MulDiv(x - sourceLeft, available, sourceRight - sourceLeft);
|
||
};
|
||
std::stable_sort(items.begin(), items.end(), [&](size_t left, size_t right)
|
||
{
|
||
return layout.originalControls[left].bounds.top < layout.originalControls[right].bounds.top;
|
||
});
|
||
const int initialTop = layout.originalControls[items.front()].bounds.top;
|
||
int shift = stacked && column == 1 ? bottom + 18 - initialTop :
|
||
column == 2 ? std::max(0, bottom + 12 - initialTop) : 0;
|
||
int columnBottom = 0, rowBottom = 0, rowExtra = 0;
|
||
for (size_t i : items)
|
||
{
|
||
const auto &[bounds, visibleHeight] = layout.originalControls[i];
|
||
if (bounds.top >= rowBottom)
|
||
{
|
||
shift += rowExtra;
|
||
rowExtra = 0;
|
||
rowBottom = bounds.top;
|
||
}
|
||
rowBottom = std::max(rowBottom, static_cast<int>(bounds.top) + visibleHeight);
|
||
auto &[child, next] = layout.controls[i];
|
||
next = bounds;
|
||
const bool sharedHeader = grid.sharedHeaderEnd && bounds.top < grid.sharedHeaderEnd;
|
||
next.left = fitX(bounds.left, sharedHeader);
|
||
next.right = std::max<LONG>(next.left + 1, fitX(bounds.right, sharedHeader));
|
||
if (!grid.secondLeft && bounds.left == grid.left &&
|
||
std::none_of(items.begin(), items.end(), [&](size_t other)
|
||
{
|
||
const auto &[neighbor, neighborHeight] = layout.originalControls[other];
|
||
return other != i && neighbor.top < bounds.top + visibleHeight &&
|
||
neighbor.top + neighborHeight > bounds.top;
|
||
}))
|
||
next.right = std::min<LONG>(right, next.left + bounds.right - bounds.left);
|
||
OffsetRect(&next, 0, shift);
|
||
wchar_t cls[32]{};
|
||
GetClassNameW(child, cls, std::size(cls));
|
||
int extra = 0;
|
||
if (!_wcsicmp(cls, L"STATIC"))
|
||
extra = std::max(0, settingsCaptionHeight(child, next.right - next.left) - visibleHeight);
|
||
if (!_wcsicmp(cls, L"BUTTON"))
|
||
{
|
||
const auto style = GetWindowLongPtrW(child, GWL_STYLE);
|
||
const auto type = style & BS_TYPEMASK;
|
||
if (type == BS_AUTOCHECKBOX || type == BS_PUSHBUTTON)
|
||
{
|
||
const int inset = type == BS_AUTOCHECKBOX ? 18 : 8;
|
||
extra = std::max(0, settingsCaptionHeight(child, std::max(1L, next.right - next.left - inset)) +
|
||
(type == BS_PUSHBUTTON ? 4 : 0) - visibleHeight);
|
||
if (!(style & BS_MULTILINE)) SetWindowLongPtrW(child, GWL_STYLE, style | BS_MULTILINE);
|
||
}
|
||
}
|
||
if (stacked && column == 0 && grid.compactListHeight && !_wcsicmp(cls, L"LISTBOX"))
|
||
{
|
||
extra = std::min(0, grid.compactListHeight - visibleHeight);
|
||
shift += extra;
|
||
rowBottom += extra;
|
||
}
|
||
next.bottom += extra;
|
||
rowExtra = std::max(rowExtra, extra);
|
||
columnBottom = std::max(columnBottom, static_cast<int>(next.top) + visibleHeight + extra);
|
||
}
|
||
bottom = std::max(bottom, columnBottom);
|
||
}
|
||
return bottom + 20;
|
||
}
|
||
int fitLanSettings(HWND panel, int width);
|
||
int fitSyncSettings(HWND panel, int width);
|
||
void reflowSettingsPage(HWND pane, WindowLayout &layout, int width, int height)
|
||
{
|
||
const auto &v = *reinterpret_cast<SettingsView *>(GetWindowLongPtrW(GetParent(pane), GWLP_USERDATA));
|
||
const auto &page = v.pages[v.selectedPage];
|
||
const UINT dpi = GetDpiForWindow(pane);
|
||
auto fit = [&](int pixels)
|
||
{
|
||
const int available = std::max(1, pixels * 96 / static_cast<int>(dpi));
|
||
if (v.selectedPage == ManageComputersPage || v.selectedPage == OpenBaoPage)
|
||
{
|
||
const int panelWidth = std::max(1, available - 16);
|
||
const int panelHeight = v.selectedPage == ManageComputersPage ? fitLanSettings(v.lan, panelWidth) :
|
||
fitSyncSettings(v.sync, panelWidth);
|
||
layout.controls[page.first].second = {8, 7, 8 + panelWidth, 7 + panelHeight};
|
||
layout.height = panelHeight + 15;
|
||
return;
|
||
}
|
||
SettingsColumns grid{24, 684};
|
||
switch (v.selectedPage)
|
||
{
|
||
case LanguagesPage: grid = {24, 684, 454, 434, 330, 670, 140, 60}; break;
|
||
case SnippetsPage: grid = {24, 684, 232, 210, 0, 625, 140}; break;
|
||
case MousePage: grid = {18, 702, 369, 351, 0, 650}; break;
|
||
case WordBoundariesPage: grid = {24, 684, 362, 346, 90, 500}; break;
|
||
}
|
||
layout.height = fitSettingsColumns(layout, page.first, page.end, available, grid);
|
||
};
|
||
fit(width);
|
||
if (scale(pane, layout.height) > height)
|
||
fit(width - GetSystemMetricsForDpi(SM_CXVSCROLL, dpi));
|
||
}
|
||
void reflowMultilineSettings(HWND pane, WindowLayout &layout, int width, int height)
|
||
{
|
||
const auto &v = *reinterpret_cast<SettingsView *>(GetWindowLongPtrW(GetParent(pane), GWLP_USERDATA));
|
||
const auto &page = v.pages[v.selectedPage];
|
||
const int rows = static_cast<int>((page.end - page.first) / 2);
|
||
const int dpi = GetDpiForWindow(pane);
|
||
constexpr int top = 20, bottom = 24, gap = 22, captionGap = 4, minimumFieldHeight = 72;
|
||
auto fit = [&](int pixels)
|
||
{
|
||
const int right = std::max(SettingsFormMargin + 1, MulDiv(pixels, 96, dpi) - SettingsFormMargin);
|
||
std::vector<int> captionHeights;
|
||
int overhead = top + bottom + gap * (rows - 1) + captionGap * rows;
|
||
for (size_t i = page.first; i < page.end; i += 2)
|
||
{
|
||
const int captionHeight = settingsCaptionHeight(layout.controls[i].first, right - SettingsFormMargin);
|
||
captionHeights.push_back(captionHeight);
|
||
overhead += captionHeight;
|
||
}
|
||
const int available = std::max(rows * minimumFieldHeight, height * 96 / dpi - overhead);
|
||
int y = top;
|
||
for (int row = 0; row < rows; ++row)
|
||
{
|
||
const int captionHeight = captionHeights[row];
|
||
const int fieldHeight = available / rows + (row < available % rows ? 1 : 0);
|
||
layout.controls[page.first + row * 2].second = {SettingsFormMargin, y, right, y + captionHeight};
|
||
y += captionHeight + captionGap;
|
||
layout.controls[page.first + row * 2 + 1].second = {SettingsFormMargin, y, right, y + fieldHeight};
|
||
y += fieldHeight + gap;
|
||
}
|
||
layout.height = overhead + available;
|
||
};
|
||
fit(width);
|
||
if (scale(pane, layout.height) > height)
|
||
fit(width - GetSystemMetricsForDpi(SM_CXVSCROLL, dpi));
|
||
}
|
||
void reflowClipboard(HWND pane, WindowLayout &layout, int width, int height)
|
||
{
|
||
const auto &v = *reinterpret_cast<SettingsView *>(GetWindowLongPtrW(GetParent(pane), GWLP_USERDATA));
|
||
const auto first = v.pages[ClipboardPage].first;
|
||
const int dpi = GetDpiForWindow(pane);
|
||
constexpr int left = SettingsFormMargin, gap = 14;
|
||
auto fit = [&](int pixels)
|
||
{
|
||
const int right = std::max(left + 1, MulDiv(pixels, 96, dpi) - left);
|
||
const int contentWidth = right - left;
|
||
const bool stacked = contentWidth < 278;
|
||
layout.controls[first].second.right = right;
|
||
layout.controls[first + 1].second.right = right;
|
||
int y = 112;
|
||
for (int field = 0; field < 3; ++field)
|
||
{
|
||
const int column = stacked ? 0 : field;
|
||
const int columnWidth = stacked ? contentWidth : (contentWidth - gap * 2) / 3;
|
||
const int x = left + column * (columnWidth + gap);
|
||
const int end = stacked || column == 2 ? right : x + columnWidth;
|
||
layout.controls[first + 2 + field * 2].second = {x, y, end, y + 22};
|
||
layout.controls[first + 3 + field * 2].second = {x, y + 26, end, y + 51};
|
||
if (stacked) y += 62;
|
||
}
|
||
if (!stacked) y += 62;
|
||
const int actionRight = std::min(right, left + 200);
|
||
layout.controls[first + 8].second = {left, y, actionRight, y + 28};
|
||
y += 52;
|
||
const int captionHeight = settingsCaptionHeight(layout.controls[first + 9].first, contentWidth);
|
||
layout.controls[first + 9].second = {left, y, right, y + captionHeight};
|
||
y += captionHeight + 4;
|
||
layout.controls[first + 10].second = {left, y, right, y + 25};
|
||
y += 35;
|
||
layout.controls[first + 11].second = {left, y, actionRight, y + 28};
|
||
layout.height = y + 48;
|
||
};
|
||
fit(width);
|
||
if (scale(pane, layout.height) > height)
|
||
fit(width - GetSystemMetricsForDpi(SM_CXVSCROLL, dpi));
|
||
}
|
||
void selectSettingsPage(SettingsView &v, int selected)
|
||
{
|
||
if (selected < 0 || selected >= (int)v.pages.size() || selected == v.selectedPage) return;
|
||
auto &layout = *windowLayoutState(v.viewport);
|
||
if (v.selectedPage >= 0)
|
||
{
|
||
auto &previous = v.pages[v.selectedPage];
|
||
previous.x = layout.x;
|
||
previous.y = layout.y;
|
||
if (IsChild(v.viewport, GetFocus())) SetFocus(v.navigation);
|
||
for (size_t i = previous.first; i < previous.end; ++i)
|
||
ShowWindow(layout.controls[i].first, SW_HIDE);
|
||
}
|
||
v.selectedPage = selected;
|
||
SetWindowTextW(v.heading, settingsSections[selected].name);
|
||
SetWindowTextW(v.description, settingsSections[selected].description);
|
||
const auto &page = v.pages[selected];
|
||
switch (selected)
|
||
{
|
||
case ShortcutsPage: layout.reflow = reflowShortcuts; break;
|
||
case ClipboardPage: layout.reflow = reflowClipboard; break;
|
||
case ExceptionsPage:
|
||
case PersonalDictionariesPage: layout.reflow = reflowMultilineSettings; break;
|
||
default: layout.reflow = reflowSettingsPage; break;
|
||
}
|
||
layout.height = std::max(1, page.height);
|
||
layout.x = page.x;
|
||
layout.y = page.y;
|
||
layout.wheelRemainder = layout.horizontalWheelRemainder = 0;
|
||
layoutSettings(GetParent(v.viewport), v);
|
||
arrangeWindow(v.viewport);
|
||
for (size_t i = page.first; i < page.end; ++i) ShowWindow(layout.controls[i].first, SW_SHOWNA);
|
||
InvalidateRect(v.viewport, nullptr, TRUE);
|
||
}
|
||
void refreshSettingsColors(HWND w, SettingsView &v, std::optional<DWORD> colorization = std::nullopt)
|
||
{
|
||
v.palette.refresh(colorization);
|
||
TreeView_SetBkColor(v.navigation, v.palette.color());
|
||
TreeView_SetTextColor(v.navigation, GetSysColor(COLOR_WINDOWTEXT));
|
||
RedrawWindow(w, nullptr, nullptr, RDW_INVALIDATE | RDW_ERASE | RDW_ALLCHILDREN);
|
||
}
|
||
void paintSettings(HWND w, const SettingsView &v)
|
||
{
|
||
PAINTSTRUCT paint{};
|
||
HDC dc = BeginPaint(w, &paint);
|
||
RECT client{};
|
||
GetClientRect(w, &client);
|
||
FillRect(dc, &paint.rcPaint, GetSysColorBrush(COLOR_WINDOW));
|
||
const int footer = client.bottom - scale(w, SettingsFooterHeight);
|
||
const int sidebar = clampSettingsSidebar(w, client.right, scale(w, v.sidebarWidth));
|
||
RECT viewport{};
|
||
if (v.viewport && GetWindowRect(v.viewport, &viewport))
|
||
MapWindowPoints(nullptr, w, reinterpret_cast<POINT *>(&viewport), 2);
|
||
const int header = viewport.top;
|
||
RECT rail{0, 0, sidebar, footer}, actions{0, footer, client.right, client.bottom};
|
||
FillRect(dc, &rail, v.palette.brush());
|
||
FillRect(dc, &actions, v.palette.brush());
|
||
SetDCBrushColor(dc, v.palette.highContrast ? GetSysColor(COLOR_WINDOWTEXT) : RGB(200, 213, 222));
|
||
auto border = reinterpret_cast<HBRUSH>(GetStockObject(DC_BRUSH));
|
||
RECT footerEdge{0, footer, client.right, footer + 1};
|
||
RECT headingEdge{sidebar + scale(w, SettingsSplitterWidth), header - 1, client.right, header};
|
||
FillRect(dc, &footerEdge, border);
|
||
FillRect(dc, &headingEdge, border);
|
||
auto icon = LoadIconW(v.app->instance, MAKEINTRESOURCEW(IDI_KSWITCHER));
|
||
DrawIconEx(dc, scale(w, 17), scale(w, 18), icon, scale(w, 28), scale(w, 28), 0, nullptr, DI_NORMAL);
|
||
EndPaint(w, &paint);
|
||
}
|
||
HTREEITEM addSettingsNode(HWND tree, HTREEITEM parent, const wchar_t *title, LPARAM data)
|
||
{
|
||
TVINSERTSTRUCTW node{};
|
||
node.hParent = parent;
|
||
node.hInsertAfter = TVI_LAST;
|
||
node.item.mask = TVIF_TEXT | TVIF_PARAM;
|
||
node.item.pszText = const_cast<wchar_t *>(title);
|
||
node.item.lParam = data;
|
||
return TreeView_InsertItem(tree, &node);
|
||
}
|
||
int settingsContentPage(const SettingsView &v, int page)
|
||
{
|
||
while (v.pages[page].first == v.pages[page].end)
|
||
{
|
||
const auto child = std::find_if(std::begin(settingsSections), std::end(settingsSections),
|
||
[page](const auto §ion) { return section.parent == page; });
|
||
if (child == std::end(settingsSections)) break;
|
||
page = static_cast<int>(child - std::begin(settingsSections));
|
||
}
|
||
return page;
|
||
}
|
||
bool isSettingsGroup(const SettingsView &v, HTREEITEM item)
|
||
{
|
||
const auto found = std::find(v.navigationItems.begin(), v.navigationItems.end(), item);
|
||
if (!item || found == v.navigationItems.end()) return false;
|
||
const int page = static_cast<int>(found - v.navigationItems.begin());
|
||
return settingsContentPage(v, page) != page;
|
||
}
|
||
void collapseSettingsGroup(const SettingsView &v, HTREEITEM group)
|
||
{
|
||
const auto tree = v.navigation;
|
||
auto target = TreeView_GetParent(tree, group);
|
||
while (isSettingsGroup(v, target)) target = TreeView_GetParent(tree, target);
|
||
if (!target) target = TreeView_GetPrevSibling(tree, group);
|
||
if (!target) target = TreeView_GetNextSibling(tree, group);
|
||
if (!target) return;
|
||
TreeView_SelectItem(tree, target);
|
||
TreeView_Expand(tree, group, TVE_COLLAPSE);
|
||
}
|
||
void rebuildSettingsNavigation(HWND w, SettingsView &v)
|
||
{
|
||
std::wistringstream input(lower(value(w, SettingsSearch)));
|
||
v.searchTerms.clear();
|
||
for (std::wstring term; input >> term;) v.searchTerms.push_back(term);
|
||
v.searching = !v.searchTerms.empty();
|
||
v.activeSearchEntry.reset();
|
||
for (auto &entry : v.searchEntries) entry.matched = false;
|
||
v.rebuildingNavigation = true;
|
||
SendMessageW(v.navigation, WM_SETREDRAW, FALSE, 0);
|
||
TreeView_DeleteAllItems(v.navigation);
|
||
v.navigationItems.fill(nullptr);
|
||
|
||
if (!v.searching)
|
||
{
|
||
for (int page = 0; page < static_cast<int>(v.pages.size()); ++page)
|
||
{
|
||
const auto §ion = settingsSections[page];
|
||
const auto parent = section.parent < 0 ? TVI_ROOT : v.navigationItems[section.parent];
|
||
v.navigationItems[page] = addSettingsNode(v.navigation, parent, section.name, page);
|
||
if (section.parent >= 0 && settingsSections[section.parent].parent < 0)
|
||
TreeView_Expand(v.navigation, parent, TVE_EXPAND);
|
||
}
|
||
if (v.selectedPage >= 0)
|
||
{
|
||
const auto selected = v.navigationItems[v.selectedPage];
|
||
TreeView_EnsureVisible(v.navigation, selected);
|
||
TreeView_SelectItem(v.navigation, selected);
|
||
}
|
||
}
|
||
else
|
||
{
|
||
for (int page = 0; page < static_cast<int>(v.pages.size()); ++page)
|
||
{
|
||
if (settingsContentPage(v, page) != page) continue;
|
||
const auto &definition = settingsSections[page];
|
||
const auto name = definition.name;
|
||
std::wstring context = name;
|
||
for (int ancestor = definition.parent; ancestor >= 0; ancestor = settingsSections[ancestor].parent)
|
||
context = std::wstring(settingsSections[ancestor].name) + L" " + context;
|
||
const bool sectionMatch = matchesSettingsSearch(v, context) ||
|
||
matchesSettingsSearch(v, settingsSections[page].description);
|
||
HTREEITEM section = sectionMatch ? addSettingsNode(v.navigation, TVI_ROOT, name, page) : nullptr;
|
||
for (size_t i = 0; i < v.searchEntries.size(); ++i)
|
||
{
|
||
auto &entry = v.searchEntries[i];
|
||
if (entry.page != page || !matchesSettingsSearch(v, context + L" " + entry.title + L" " + entry.aliases)) continue;
|
||
entry.matched = true;
|
||
if (!section) section = addSettingsNode(v.navigation, TVI_ROOT, name, page);
|
||
addSettingsNode(v.navigation, section, entry.title.c_str(), static_cast<LPARAM>(v.pages.size() + i));
|
||
}
|
||
if (section) TreeView_Expand(v.navigation, section, TVE_EXPAND);
|
||
}
|
||
if (!TreeView_GetRoot(v.navigation)) addSettingsNode(v.navigation, TVI_ROOT, L"No matching settings", -1);
|
||
}
|
||
SendMessageW(v.navigation, WM_SETREDRAW, TRUE, 0);
|
||
InvalidateRect(v.navigation, nullptr, TRUE);
|
||
repaintSettingsMatches(v);
|
||
v.rebuildingNavigation = false;
|
||
}
|
||
void navigateSettings(SettingsView &v, int page);
|
||
void openSettingsNode(HWND w, SettingsView &v, LPARAM data, bool focus)
|
||
{
|
||
if (data < 0) return;
|
||
const auto previousMatch = v.activeSearchEntry;
|
||
v.activeSearchEntry.reset();
|
||
if (data < static_cast<LPARAM>(v.pages.size()))
|
||
{
|
||
const int page = static_cast<int>(data);
|
||
const int content = settingsContentPage(v, page);
|
||
if (!v.searching && content != page)
|
||
{
|
||
navigateSettings(v, content);
|
||
return;
|
||
}
|
||
selectSettingsPage(v, page);
|
||
}
|
||
else
|
||
{
|
||
v.activeSearchEntry = static_cast<size_t>(data) - v.pages.size();
|
||
const auto &entry = v.searchEntries[*v.activeSearchEntry];
|
||
selectSettingsPage(v, entry.page);
|
||
revealControl(entry.target);
|
||
if (focus && IsWindowEnabled(entry.target) &&
|
||
(GetWindowLongPtrW(entry.target, GWL_STYLE) & WS_TABSTOP))
|
||
SetFocus(entry.target);
|
||
}
|
||
if (previousMatch != v.activeSearchEntry) repaintSettingsMatches(v);
|
||
updateSettingsState(w, &v);
|
||
}
|
||
LRESULT CALLBACK settingsTreeProc(HWND tree, UINT msg, WPARAM wp, LPARAM lp, UINT_PTR id, DWORD_PTR data)
|
||
{
|
||
auto &v = *reinterpret_cast<SettingsView *>(data);
|
||
if (msg == CollapseSettingsGroupMessage)
|
||
{
|
||
auto group = reinterpret_cast<HTREEITEM>(lp);
|
||
if (!v.searching && isSettingsGroup(v, group)) collapseSettingsGroup(v, group);
|
||
return 0;
|
||
}
|
||
if (!v.searching && msg == WM_KEYDOWN && (wp == VK_UP || wp == VK_LEFT))
|
||
{
|
||
const auto selected = TreeView_GetSelection(tree);
|
||
if (wp == VK_UP)
|
||
{
|
||
auto previous = TreeView_GetPrevVisible(tree, selected);
|
||
if (isSettingsGroup(v, previous) && TreeView_GetChild(tree, previous) == selected)
|
||
{
|
||
do previous = TreeView_GetPrevVisible(tree, previous);
|
||
while (isSettingsGroup(v, previous));
|
||
if (previous) TreeView_SelectItem(tree, previous);
|
||
return 0;
|
||
}
|
||
}
|
||
else if (!TreeView_GetChild(tree, selected) ||
|
||
!(TreeView_GetItemState(tree, selected, TVIS_EXPANDED) & TVIS_EXPANDED))
|
||
{
|
||
auto parent = TreeView_GetParent(tree, selected);
|
||
if (isSettingsGroup(v, parent))
|
||
{
|
||
collapseSettingsGroup(v, parent);
|
||
return 0;
|
||
}
|
||
}
|
||
}
|
||
if (v.searching && msg == WM_GETDLGCODE && wp == VK_RETURN) return DLGC_WANTMESSAGE;
|
||
if (v.searching && msg == WM_KEYDOWN && wp == VK_RETURN)
|
||
{
|
||
TVITEMW item{};
|
||
item.mask = TVIF_PARAM;
|
||
item.hItem = TreeView_GetSelection(tree);
|
||
if (item.hItem && TreeView_GetItem(tree, &item)) openSettingsNode(GetParent(tree), v, item.lParam, true);
|
||
return 0;
|
||
}
|
||
if (msg == WM_NCDESTROY) RemoveWindowSubclass(tree, settingsTreeProc, id);
|
||
return DefSubclassProc(tree, msg, wp, lp);
|
||
}
|
||
LRESULT CALLBACK settingsSearchProc(HWND field, UINT msg, WPARAM wp, LPARAM lp, UINT_PTR id, DWORD_PTR data)
|
||
{
|
||
auto &v = *reinterpret_cast<SettingsView *>(data);
|
||
if (msg == WM_GETDLGCODE && (wp == VK_RETURN || (wp == VK_ESCAPE && v.searching)))
|
||
return DLGC_WANTMESSAGE;
|
||
if (msg == WM_KEYDOWN && wp == VK_RETURN)
|
||
{
|
||
if (!TreeView_GetSelection(v.navigation))
|
||
{
|
||
auto first = TreeView_GetRoot(v.navigation);
|
||
auto child = TreeView_GetChild(v.navigation, first);
|
||
TreeView_SelectItem(v.navigation, child ? child : first);
|
||
}
|
||
SetFocus(v.navigation);
|
||
return 0;
|
||
}
|
||
if (msg == WM_KEYDOWN && wp == VK_ESCAPE && v.searching)
|
||
{
|
||
SetWindowTextW(field, L"");
|
||
return 0;
|
||
}
|
||
if (msg == WM_NCDESTROY) RemoveWindowSubclass(field, settingsSearchProc, id);
|
||
return DefSubclassProc(field, msg, wp, lp);
|
||
}
|
||
void navigateSettings(SettingsView &v, int page)
|
||
{
|
||
if (v.searching) SetWindowTextW(v.search, L"");
|
||
page = settingsContentPage(v, page);
|
||
const auto node = v.navigationItems[page];
|
||
TreeView_EnsureVisible(v.navigation, node);
|
||
TreeView_SelectItem(v.navigation, node);
|
||
if (v.selectedPage != page) openSettingsNode(GetParent(v.navigation), v, page, false);
|
||
}
|
||
HWND settingsFieldForLabel(HWND label)
|
||
{
|
||
RECT caption{};
|
||
GetWindowRect(label, &caption);
|
||
const int rowTolerance = scale(label, 6), fieldGap = scale(label, 18);
|
||
for (HWND next = GetWindow(label, GW_HWNDNEXT); next; next = GetWindow(next, GW_HWNDNEXT))
|
||
{
|
||
wchar_t cls[24]{};
|
||
GetClassNameW(next, cls, std::size(cls));
|
||
if (_wcsicmp(cls, L"EDIT") && _wcsicmp(cls, L"COMBOBOX")) continue;
|
||
RECT field{};
|
||
GetWindowRect(next, &field);
|
||
const bool onSameRow = std::abs(field.top - caption.top) <= rowTolerance && field.left >= caption.right;
|
||
const bool below = field.left == caption.left && field.top >= caption.bottom &&
|
||
field.top - caption.bottom <= fieldGap;
|
||
if (onSameRow || below) return next;
|
||
}
|
||
return label;
|
||
}
|
||
void indexSettingsControl(SettingsView &v, int page, HWND child)
|
||
{
|
||
wchar_t cls[24]{};
|
||
GetClassNameW(child, cls, std::size(cls));
|
||
const bool staticText = _wcsicmp(cls, L"STATIC") == 0;
|
||
if (!staticText && _wcsicmp(cls, L"BUTTON")) return;
|
||
const int length = GetWindowTextLengthW(child);
|
||
if (!length) return;
|
||
std::wstring text(length + 1, L'\0');
|
||
GetWindowTextW(child, text.data(), length + 1);
|
||
text.resize(length);
|
||
std::erase(text, L'&');
|
||
HWND target = staticText && GetDlgCtrlID(child) == 0 ? settingsFieldForLabel(child) : child;
|
||
const wchar_t *aliases = L"";
|
||
switch (GetDlgCtrlID(target))
|
||
{
|
||
case 204: case 206: aliases = L"autostart startup login"; break;
|
||
case 205: aliases = L"sleep prevent power"; break;
|
||
case 210: case 211: case 212: case 213: case 214: case 215: case 216:
|
||
case 231: aliases = L"hotkey keyboard shortcut"; break;
|
||
case 240: aliases = L"max maximum count history limit"; break;
|
||
case 241: case 242: aliases = L"size storage history limit"; break;
|
||
case 257: aliases = L"text recognition Tesseract"; break;
|
||
case 411: case 412: case 413: aliases = L"personal dictionary words"; break;
|
||
case 701: aliases = L"LAN network discover devices computers"; break;
|
||
case 704: aliases = L"pairing connection code"; break;
|
||
case 706: aliases = L"cancel pairing"; break;
|
||
}
|
||
v.searchEntries.push_back({page, child, target, std::move(text), aliases});
|
||
}
|
||
struct ChatLanguagesView
|
||
{
|
||
HWND parent{};
|
||
SettingsView *settings{};
|
||
std::vector<std::wstring> keys;
|
||
Settings draft;
|
||
int selection = -1;
|
||
bool dirty{};
|
||
bool updatingList{};
|
||
std::wstring search;
|
||
};
|
||
void collectChatLanguages(HWND w, ChatLanguagesView *v)
|
||
{
|
||
if (!v->dirty || v->selection < 0) return;
|
||
std::vector<std::wstring> cycle;
|
||
for (size_t i = 0; i < v->settings->order.size(); ++i)
|
||
if (SendDlgItemMessageW(w, 711, LB_GETSEL, i, 0) > 0)
|
||
cycle.push_back(v->settings->app->layouts[v->settings->order[i]].id);
|
||
if (cycle.empty()) throw std::runtime_error("Select at least one language.");
|
||
v->draft.chatCycles[v->keys[v->selection]] = std::move(cycle);
|
||
v->dirty = false;
|
||
}
|
||
void fillChatLanguages(HWND w, ChatLanguagesView *v)
|
||
{
|
||
int index = v->selection;
|
||
EnableWindow(GetDlgItem(w, 711), index >= 0);
|
||
EnableWindow(GetDlgItem(w, IDOK), index >= 0);
|
||
if (index < 0)
|
||
{
|
||
SendDlgItemMessageW(w, 711, LB_SETSEL, FALSE, -1);
|
||
EnableWindow(GetDlgItem(w, 713), FALSE);
|
||
value(w, 712, v->keys.empty() ? L"Open a chat, then reopen this dialog to add it." :
|
||
L"No contacts match your search.");
|
||
return;
|
||
}
|
||
const auto &draft = v->draft;
|
||
auto saved = draft.chatCycles.find(v->keys[index]);
|
||
const auto &cycle = saved == draft.chatCycles.end() ? draft.cycle : saved->second;
|
||
for (size_t i = 0; i < v->settings->order.size(); ++i)
|
||
{
|
||
auto &layout = v->settings->app->layouts[v->settings->order[i]];
|
||
SendDlgItemMessageW(w, 711, LB_SETSEL,
|
||
std::find(cycle.begin(), cycle.end(), layout.id) != cycle.end(), i);
|
||
}
|
||
value(w, 712, saved == draft.chatCycles.end() ? L"No profile yet. Select the languages for this chat." :
|
||
L"Chat profile. Select languages, or remove it to use the defaults.");
|
||
EnableWindow(GetDlgItem(w, 713), saved != draft.chatCycles.end());
|
||
}
|
||
void selectChatRow(HWND list, int index)
|
||
{
|
||
int row = -1;
|
||
if (index >= 0)
|
||
{
|
||
LVFINDINFOW find{LVFI_PARAM};
|
||
find.lParam = index;
|
||
row = ListView_FindItem(list, -1, &find);
|
||
}
|
||
ListView_SetItemState(list, -1, 0, LVIS_SELECTED | LVIS_FOCUSED);
|
||
if (row >= 0)
|
||
{
|
||
ListView_SetItemState(list, row, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
|
||
ListView_EnsureVisible(list, row, FALSE);
|
||
}
|
||
}
|
||
void filterChatRows(HWND w, ChatLanguagesView *v)
|
||
{
|
||
auto list = GetDlgItem(w, 710);
|
||
auto search = lower(v->search);
|
||
int selection = -1;
|
||
v->updatingList = true;
|
||
SendMessageW(list, WM_SETREDRAW, FALSE, 0);
|
||
ListView_DeleteAllItems(list);
|
||
for (size_t i = 0; i < v->keys.size(); ++i)
|
||
{
|
||
const auto &key = v->keys[i];
|
||
auto contact = key.substr(key.find(L'\n') + 1);
|
||
if (lower(contact).find(search) == std::wstring::npos) continue;
|
||
auto app = key.starts_with(L"telegram\n") ? L"Telegram" :
|
||
key.starts_with(L"telegram-web\n") ? L"Telegram Web" :
|
||
key.starts_with(L"viber\n") ? L"Viber (inactive)" : L"Teams";
|
||
LVITEMW item{LVIF_TEXT | LVIF_PARAM};
|
||
item.iItem = ListView_GetItemCount(list);
|
||
item.pszText = contact.data();
|
||
item.lParam = static_cast<LPARAM>(i);
|
||
int row = ListView_InsertItem(list, &item);
|
||
if (row < 0) continue;
|
||
ListView_SetItemText(list, row, 1, const_cast<wchar_t *>(app));
|
||
if (selection < 0 || static_cast<int>(i) == v->selection) selection = static_cast<int>(i);
|
||
}
|
||
selectChatRow(list, selection);
|
||
SendMessageW(list, WM_SETREDRAW, TRUE, 0);
|
||
InvalidateRect(list, nullptr, TRUE);
|
||
v->updatingList = false;
|
||
v->selection = selection;
|
||
fillChatLanguages(w, v);
|
||
}
|
||
LRESULT CALLBACK chatLanguagesProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||
{
|
||
auto *v = (ChatLanguagesView *)GetWindowLongPtrW(w, GWLP_USERDATA);
|
||
if (!v) return DefWindowProcW(w, msg, wp, lp);
|
||
try
|
||
{
|
||
if (msg == WM_NOTIFY && !v->updatingList)
|
||
{
|
||
auto *change = reinterpret_cast<const NMLISTVIEW *>(lp);
|
||
if (change->hdr.idFrom == 710 && change->hdr.code == LVN_ITEMCHANGED &&
|
||
(change->uNewState & LVIS_SELECTED) && !(change->uOldState & LVIS_SELECTED))
|
||
{
|
||
int selected = static_cast<int>(change->lParam);
|
||
if (selected == v->selection) return 0;
|
||
try { collectChatLanguages(w, v); }
|
||
catch (...)
|
||
{
|
||
v->updatingList = true;
|
||
selectChatRow(change->hdr.hwndFrom, v->selection);
|
||
v->updatingList = false;
|
||
throw;
|
||
}
|
||
v->selection = selected;
|
||
fillChatLanguages(w, v);
|
||
return 0;
|
||
}
|
||
}
|
||
if (msg == WM_COMMAND)
|
||
{
|
||
int id = LOWORD(wp);
|
||
if (id == 711 && HIWORD(wp) == LBN_SELCHANGE) { v->dirty = true; return 0; }
|
||
if (id == 714 && HIWORD(wp) == EN_CHANGE && !v->updatingList)
|
||
{
|
||
try { collectChatLanguages(w, v); }
|
||
catch (...)
|
||
{
|
||
v->updatingList = true;
|
||
value(w, 714, v->search);
|
||
v->updatingList = false;
|
||
throw;
|
||
}
|
||
v->search = value(w, 714);
|
||
filterChatRows(w, v);
|
||
return 0;
|
||
}
|
||
if (id == IDOK || id == 713)
|
||
{
|
||
int selected = v->selection;
|
||
if (id == IDOK && selected < 0) return 0;
|
||
if (selected < 0 || selected >= (int)v->keys.size())
|
||
throw std::runtime_error("Open a Telegram or Teams chat, then reopen this dialog.");
|
||
if (id == 713)
|
||
{
|
||
v->draft.chatCycles.erase(v->keys[selected]);
|
||
v->dirty = false;
|
||
fillChatLanguages(w, v);
|
||
return 0;
|
||
}
|
||
collectChatLanguages(w, v);
|
||
validateSettings(v->draft);
|
||
v->settings->draft.chatCycles = std::move(v->draft.chatCycles);
|
||
DestroyWindow(w);
|
||
return 0;
|
||
}
|
||
if (id == IDCANCEL) { DestroyWindow(w); return 0; }
|
||
}
|
||
if (msg == WM_CLOSE) { DestroyWindow(w); return 0; }
|
||
if (msg == WM_DPICHANGED)
|
||
{
|
||
resizeForDpi(w, wp, lp);
|
||
auto list = GetDlgItem(w, 710);
|
||
ListView_SetColumnWidth(list, 0, scale(w, 442));
|
||
ListView_SetColumnWidth(list, 1, scale(w, 140));
|
||
return 0;
|
||
}
|
||
if (msg == WM_NCDESTROY)
|
||
{
|
||
EnableWindow(v->parent, TRUE);
|
||
SetForegroundWindow(v->parent);
|
||
disposeFont(w);
|
||
delete v;
|
||
SetWindowLongPtrW(w, GWLP_USERDATA, 0);
|
||
}
|
||
}
|
||
catch (const std::exception &e) { error(w, e); }
|
||
return DefWindowProcW(w, msg, wp, lp);
|
||
}
|
||
void showChatLanguages(HWND parent, SettingsView *settings)
|
||
{
|
||
std::set<std::wstring> keys;
|
||
for (const auto &[key, cycle] : settings->draft.chatCycles) keys.insert(key);
|
||
struct Context { std::set<std::wstring> &keys; const Settings &settings; } context{keys, settings->draft};
|
||
EnumWindows([](HWND candidate, LPARAM context) -> BOOL
|
||
{
|
||
if (!IsWindowVisible(candidate)) return TRUE;
|
||
auto &data = *(Context *)context;
|
||
auto key = lower(processName(candidate)) == L"chrome" ? readChromeChat(candidate) : windowChatKey(candidate);
|
||
if (!key.empty()) data.keys.insert(std::move(key));
|
||
return TRUE;
|
||
}, (LPARAM)&context);
|
||
INITCOMMONCONTROLSEX controls{sizeof(controls), ICC_LISTVIEW_CLASSES};
|
||
InitCommonControlsEx(&controls);
|
||
HWND w = makeWindow(*settings->app, L"KSwitcher.ChatLanguages", L"Languages for a chat", chatLanguagesProc, 640, 524);
|
||
auto *v = new ChatLanguagesView{parent, settings, {keys.begin(), keys.end()}};
|
||
v->draft = settings->draft;
|
||
v->updatingList = true;
|
||
SetWindowLongPtrW(w, GWLP_HWNDPARENT, (LONG_PTR)parent);
|
||
SetWindowLongPtrW(w, GWLP_USERDATA, (LONG_PTR)v);
|
||
label(w, L"&Find contact", 18, 19, 106);
|
||
edit(w, 714, 130, 14, 492);
|
||
auto list = control(w, WC_LISTVIEWW, L"", WS_TABSTOP | WS_BORDER | LVS_REPORT | LVS_SINGLESEL |
|
||
LVS_SHOWSELALWAYS | LVS_NOSORTHEADER, 710, 18, 48, 604, 136);
|
||
ListView_SetExtendedListViewStyle(list, LVS_EX_FULLROWSELECT | LVS_EX_DOUBLEBUFFER | LVS_EX_LABELTIP);
|
||
for (const auto &[title, width] : {std::pair{L"Contact", 442}, std::pair{L"App", 140}})
|
||
{
|
||
LVCOLUMNW column{LVCF_TEXT | LVCF_WIDTH};
|
||
column.pszText = const_cast<wchar_t *>(title);
|
||
column.cx = scale(w, width);
|
||
ListView_InsertColumn(list, Header_GetItemCount(ListView_GetHeader(list)), &column);
|
||
}
|
||
control(w, L"STATIC", L"Open a chat, then reopen this dialog to add it.", 0, 712, 18, 194, 604, 26);
|
||
label(w, L"Click languages to include (saved in the order shown)", 18, 228, 604);
|
||
control(w, L"LISTBOX", L"", WS_TABSTOP | WS_VSCROLL | LBS_NOTIFY | LBS_MULTIPLESEL | LBS_NOINTEGRALHEIGHT | WS_BORDER,
|
||
711, 18, 256, 604, 132);
|
||
for (int i : settings->order)
|
||
SendDlgItemMessageW(w, 711, LB_ADDSTRING, 0, (LPARAM)settings->app->layouts[i].name.c_str());
|
||
label(w, L"Applies to Alt+Shift, Win+Space and KSwitcher Next layout.", 18, 402, 604);
|
||
label(w, L"Switch chats freely. Use languages, then Save settings.", 18, 430, 604);
|
||
button(w, L"&Remove profile", 713, 18, 476, 170);
|
||
button(w, L"&Use languages", IDOK, 300, 476, 170);
|
||
button(w, L"&Cancel", IDCANCEL, 486, 476, 136);
|
||
filterChatRows(w, v);
|
||
EnableWindow(parent, FALSE);
|
||
showRequestedWindow(w);
|
||
SetFocus(GetDlgItem(w, 714));
|
||
}
|
||
#include "ui_app_languages.inl"
|
||
#include "ui_mouse_buttons.inl"
|
||
void resizeSettingsForDpi(HWND w, int previousDpi, int nextDpi)
|
||
{
|
||
auto &v = *reinterpret_cast<SettingsView *>(GetWindowLongPtrW(w, GWLP_USERDATA));
|
||
if (!v.ready) return;
|
||
setSettingsFonts(w, v, nextDpi);
|
||
auto &layout = *windowLayoutState(v.viewport);
|
||
layout.x = MulDiv(layout.x, nextDpi, previousDpi);
|
||
layout.y = MulDiv(layout.y, nextDpi, previousDpi);
|
||
for (auto &page : v.pages)
|
||
{
|
||
page.x = MulDiv(page.x, nextDpi, previousDpi);
|
||
page.y = MulDiv(page.y, nextDpi, previousDpi);
|
||
}
|
||
layoutSettings(w, v);
|
||
arrangeWindow(v.viewport);
|
||
if (v.lan) arrangeWindow(v.lan);
|
||
if (v.sync) arrangeWindow(v.sync);
|
||
if (previousDpi != nextDpi) scaleMouseTableColumns(w, previousDpi, nextDpi);
|
||
}
|
||
void collectLayout(SettingsView *v)
|
||
{
|
||
HWND w = v->viewport;
|
||
if (v->selection < 0 || v->selection >= (int)v->order.size())
|
||
return;
|
||
int index = v->order[v->selection];
|
||
auto id = v->app->layouts[index].id;
|
||
auto &cycle = v->draft.cycle;
|
||
std::erase(cycle, id);
|
||
if (checked(w, 230))
|
||
cycle.push_back(id);
|
||
if (v->draft.direct.size() < v->app->layouts.size())
|
||
v->draft.direct.resize(v->app->layouts.size());
|
||
v->draft.direct[index] = value(w, 231);
|
||
}
|
||
void layoutSelection(SettingsView *v)
|
||
{
|
||
HWND w = v->viewport;
|
||
v->selection = (int)SendDlgItemMessageW(w, 220, LB_GETCURSEL, 0, 0);
|
||
if (v->selection < 0)
|
||
return;
|
||
int i = v->order[v->selection];
|
||
auto &l = v->app->layouts[i];
|
||
check(w, 230, std::find(v->draft.cycle.begin(), v->draft.cycle.end(), l.id) != v->draft.cycle.end());
|
||
EnableWindow(GetDlgItem(w, 230), l.convertible);
|
||
value(w, 231, i < (int)v->draft.direct.size() ? v->draft.direct[i] : L"");
|
||
}
|
||
void fillLayouts(SettingsView *v)
|
||
{
|
||
HWND w = v->viewport;
|
||
SendDlgItemMessageW(w, 220, LB_RESETCONTENT, 0, 0);
|
||
for (int i : v->order)
|
||
{
|
||
auto &l = v->app->layouts[i];
|
||
bool on = std::find(v->draft.cycle.begin(), v->draft.cycle.end(), l.id) != v->draft.cycle.end();
|
||
auto title = (on ? L"[✓] " : L"[ ] ") + l.name + (l.convertible ? L"" : L" — switch only");
|
||
SendDlgItemMessageW(w, 220, LB_ADDSTRING, 0, (LPARAM)title.c_str());
|
||
}
|
||
SendDlgItemMessageW(w, 220, LB_SETCURSEL, std::max(0, v->selection), 0);
|
||
layoutSelection(v);
|
||
}
|
||
void fillCorrectionOptions(HWND w, const Settings &draft);
|
||
void collectCorrectionOptions(HWND w, Settings &draft);
|
||
void fillSettings(HWND root, SettingsView *v)
|
||
{
|
||
HWND w = v->viewport;
|
||
v->filling = true;
|
||
auto &s = v->draft;
|
||
check(w, 201, s.recent);
|
||
check(w, 202, s.switchLayout);
|
||
check(w, 208, s.writeLog);
|
||
check(w, 209, s.screenshotAutoOpenEditor);
|
||
check(w, 203, s.history);
|
||
check(w, 204, s.autostart);
|
||
check(w, 206, s.elevatedAutostart);
|
||
check(w, 205, s.awake);
|
||
check(w, 207, s.autoCorrect);
|
||
value(w, 210, s.toggle);
|
||
value(w, 211, s.casing);
|
||
value(w, 212, s.translit);
|
||
value(w, 213, s.undo);
|
||
value(w, 214, s.clipboard);
|
||
value(w, 215, s.screenshot);
|
||
value(w, 216, s.filesHotkey.value_or(L""));
|
||
value(w, 240, std::to_wstring(s.maxItems));
|
||
value(w, 241, std::to_wstring(s.maxMiB));
|
||
value(w, 242, std::to_wstring(s.maxImageMiB));
|
||
std::wstring excluded;
|
||
for (auto &name : s.excluded)
|
||
{
|
||
if (!excluded.empty())
|
||
excluded += L", ";
|
||
excluded += name;
|
||
}
|
||
value(w, 243, excluded);
|
||
v->order.clear();
|
||
for (auto &id : s.cycle)
|
||
for (int i = 0; i < (int)v->app->layouts.size(); ++i)
|
||
if (v->app->layouts[i].id == id)
|
||
v->order.push_back(i);
|
||
for (int i = 0; i < (int)v->app->layouts.size(); ++i)
|
||
if (std::find(v->order.begin(), v->order.end(), i) == v->order.end())
|
||
v->order.push_back(i);
|
||
v->selection = 0;
|
||
fillLayouts(v);
|
||
fillMouseProfiles(root, *v);
|
||
fillCorrectionOptions(w, s);
|
||
v->filling = false;
|
||
updateSettingsState(root, v);
|
||
}
|
||
int integer(HWND w, int id)
|
||
{
|
||
auto s = value(w, id);
|
||
size_t n{};
|
||
int v = std::stoi(s, &n);
|
||
if (n != s.size())
|
||
throw std::runtime_error("Enter a whole number for history limits");
|
||
return v;
|
||
}
|
||
Settings collectSettings(SettingsView *v)
|
||
{
|
||
HWND w = v->viewport;
|
||
collectLayout(v);
|
||
auto s = v->draft;
|
||
s.recent = checked(w, 201);
|
||
s.switchLayout = checked(w, 202);
|
||
s.writeLog = checked(w, 208);
|
||
s.screenshotAutoOpenEditor = checked(w, 209);
|
||
s.history = checked(w, 203);
|
||
s.autostart = checked(w, 204);
|
||
s.elevatedAutostart = checked(w, 206);
|
||
s.awake = checked(w, 205);
|
||
s.autoCorrect = checked(w, 207);
|
||
s.toggle = value(w, 210);
|
||
s.casing = value(w, 211);
|
||
s.translit = value(w, 212);
|
||
s.undo = value(w, 213);
|
||
s.clipboard = value(w, 214);
|
||
s.screenshot = value(w, 215);
|
||
auto filesHotkey = value(w, 216);
|
||
if (s.filesHotkey || !filesHotkey.empty())
|
||
s.filesHotkey = std::move(filesHotkey);
|
||
s.maxItems = integer(w, 240);
|
||
s.maxMiB = integer(w, 241);
|
||
s.maxImageMiB = integer(w, 242);
|
||
s.excluded.clear();
|
||
std::wistringstream input(value(w, 243));
|
||
std::wstring item;
|
||
while (std::getline(input, item, L','))
|
||
{
|
||
auto first = item.find_first_not_of(L" \t"), last = item.find_last_not_of(L" \t");
|
||
if (first != item.npos)
|
||
s.excluded.push_back(item.substr(first, last - first + 1));
|
||
}
|
||
std::vector<std::wstring> cycle;
|
||
for (int i : v->order)
|
||
{
|
||
auto id = v->app->layouts[i].id;
|
||
if (std::find(s.cycle.begin(), s.cycle.end(), id) != s.cycle.end())
|
||
cycle.push_back(id);
|
||
}
|
||
s.cycle = cycle;
|
||
collectCorrectionOptions(w, s);
|
||
validateSettings(s);
|
||
return s;
|
||
}
|
||
std::wstring commaList(const std::vector<std::wstring> &items)
|
||
{
|
||
std::wstring text;
|
||
for (auto &item : items)
|
||
{
|
||
if (!text.empty())
|
||
text += L", ";
|
||
text += item;
|
||
}
|
||
return text;
|
||
}
|
||
std::vector<std::wstring> parseCommaList(const std::wstring &text)
|
||
{
|
||
std::vector<std::wstring> items;
|
||
std::wistringstream input(text);
|
||
std::wstring item;
|
||
while (std::getline(input, item, L','))
|
||
{
|
||
auto first = item.find_first_not_of(L" \t\r\n"), last = item.find_last_not_of(L" \t\r\n");
|
||
if (first != item.npos)
|
||
items.push_back(item.substr(first, last - first + 1));
|
||
}
|
||
return items;
|
||
}
|
||
std::wstring correctionPairs(const Settings &draft)
|
||
{
|
||
std::wstring pairs;
|
||
for (const auto &[from, to] : draft.autoReplacements) pairs += from + L"=" + to + L"\r\n";
|
||
return pairs;
|
||
}
|
||
void collectCorrectionOptions(HWND w, Settings &draft)
|
||
{
|
||
auto lengthText = value(w, 410);
|
||
if (lengthText.empty() || lengthText.size() > 2 ||
|
||
lengthText.find_first_not_of(L"0123456789") != lengthText.npos)
|
||
throw std::runtime_error("Minimum word length must be between 1 and 32 letters");
|
||
draft.autoMinLength = std::stoi(lengthText);
|
||
auto rankText = value(w, 406);
|
||
if (rankText.empty() || rankText.find_first_not_of(L"0123456789") != rankText.npos)
|
||
throw std::runtime_error("Enter a non-negative whole number for the frequency rank limit");
|
||
try
|
||
{
|
||
draft.autoMaxRank = std::stoi(rankText);
|
||
}
|
||
catch (...)
|
||
{
|
||
throw std::runtime_error("Frequency rank limit is too large");
|
||
}
|
||
std::vector<std::wstring> languages;
|
||
for (auto [id, language] : {std::pair{401, L"en"}, {402, L"uk"}, {403, L"ru"}})
|
||
if (checked(w, id)) languages.push_back(language);
|
||
if (!std::is_permutation(languages.begin(), languages.end(), draft.autoLanguages.begin(), draft.autoLanguages.end()))
|
||
{
|
||
if (languages.size() < 2) throw std::runtime_error("Select at least two languages");
|
||
draft.autoLanguages = std::move(languages);
|
||
}
|
||
auto readList = [&](int id, std::vector<std::wstring> &items)
|
||
{
|
||
const auto text = value(w, id);
|
||
if (text != commaList(items)) items = parseCommaList(text);
|
||
};
|
||
readList(405, draft.autoNever);
|
||
readList(404, draft.autoExcluded);
|
||
for (auto [id, language] : {std::pair{411, L"en"}, {412, L"uk"}, {413, L"ru"}})
|
||
{
|
||
auto text = value(w, id);
|
||
const auto existing = draft.autoWords.find(language);
|
||
if (text == (existing == draft.autoWords.end() ? L"" : commaList(existing->second))) continue;
|
||
text = lower(std::move(text));
|
||
std::replace(text.begin(), text.end(), L'\n', L',');
|
||
auto words = parseCommaList(text);
|
||
std::sort(words.begin(), words.end());
|
||
words.erase(std::unique(words.begin(), words.end()), words.end());
|
||
// Opening and accepting an untouched empty dictionary must not
|
||
// introduce a new entry and mark Settings as changed.
|
||
if (!words.empty() || draft.autoWords.contains(language))
|
||
draft.autoWords[language] = std::move(words);
|
||
}
|
||
draft.autoPrefixChars = value(w, 408);
|
||
draft.autoSuffixChars = value(w, 409);
|
||
draft.autoReplace = checked(w, 414);
|
||
draft.autoTypos = checked(w, 415);
|
||
const auto pairs = value(w, 416);
|
||
if (pairs == correctionPairs(draft)) return;
|
||
draft.autoReplacements.clear();
|
||
std::wistringstream replacements(lower(pairs));
|
||
std::wstring line;
|
||
auto trim = [](std::wstring text)
|
||
{
|
||
auto first = text.find_first_not_of(L" \t\r\n");
|
||
return first == text.npos ? std::wstring{} : text.substr(first, text.find_last_not_of(L" \t\r\n") - first + 1);
|
||
};
|
||
while (std::getline(replacements, line))
|
||
{
|
||
if (trim(line).empty()) continue;
|
||
auto equals = line.find(L'=');
|
||
if (equals == line.npos)
|
||
throw std::runtime_error("Enter one replacement per line: typo=correction");
|
||
if (!draft.autoReplacements.emplace(trim(line.substr(0, equals)), trim(line.substr(equals + 1))).second)
|
||
throw std::runtime_error("Each replacement typo must occur only once");
|
||
}
|
||
}
|
||
void fillCorrectionOptions(HWND w, const Settings &draft)
|
||
{
|
||
for (auto [id, language] : {std::pair{401, L"en"}, {402, L"uk"}, {403, L"ru"}})
|
||
check(w, id, std::find(draft.autoLanguages.begin(), draft.autoLanguages.end(), language) != draft.autoLanguages.end());
|
||
for (auto [id, language] : {std::pair{411, L"en"}, {412, L"uk"}, {413, L"ru"}})
|
||
{
|
||
auto words = draft.autoWords.find(language);
|
||
value(w, id, words == draft.autoWords.end() ? L"" : commaList(words->second));
|
||
}
|
||
value(w, 404, commaList(draft.autoExcluded));
|
||
value(w, 405, commaList(draft.autoNever));
|
||
value(w, 406, std::to_wstring(draft.autoMaxRank));
|
||
value(w, 410, std::to_wstring(draft.autoMinLength));
|
||
value(w, 408, draft.autoPrefixChars);
|
||
value(w, 409, draft.autoSuffixChars);
|
||
check(w, 414, draft.autoReplace);
|
||
check(w, 415, draft.autoTypos);
|
||
value(w, 416, correctionPairs(draft));
|
||
}
|
||
struct OcrOptionsView { HWND parent; SettingsView *settings; };
|
||
Settings ocrDraft(HWND w, OcrOptionsView *v)
|
||
{
|
||
auto draft = v->settings->draft;
|
||
draft.useTesseract = checked(w, 501);
|
||
draft.tesseractPath = value(w, 502);
|
||
draft.tesseractLanguages = value(w, 503);
|
||
validateSettings(draft);
|
||
return draft;
|
||
}
|
||
LRESULT CALLBACK ocrOptionsProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||
{
|
||
auto *v = reinterpret_cast<OcrOptionsView *>(GetWindowLongPtrW(w, GWLP_USERDATA));
|
||
if (!v) return DefWindowProcW(w, msg, wp, lp);
|
||
if (msg == WM_COMMAND)
|
||
{
|
||
int id = LOWORD(wp);
|
||
try
|
||
{
|
||
if (id == 507)
|
||
{
|
||
if ((INT_PTR)ShellExecuteW(w, L"open", L"https://github.com/UB-Mannheim/tesseract/wiki#tesseract-installer-for-windows",
|
||
nullptr, nullptr, SW_SHOWNORMAL) <= 32)
|
||
throw std::runtime_error("Could not open the Tesseract download page in your browser");
|
||
return 0;
|
||
}
|
||
if (id == 504)
|
||
{
|
||
wchar_t path[32768]{};
|
||
OPENFILENAMEW picker{sizeof(picker)};
|
||
picker.hwndOwner = w; picker.lpstrFile = path; picker.nMaxFile = std::size(path);
|
||
picker.lpstrFilter = L"Tesseract executable (tesseract.exe)\0tesseract.exe\0Executables\0*.exe\0";
|
||
picker.Flags = OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR;
|
||
if (GetOpenFileNameW(&picker)) value(w, 502, path);
|
||
return 0;
|
||
}
|
||
if (id == 505 || id == IDOK)
|
||
{
|
||
auto draft = ocrDraft(w, v);
|
||
if (id == 505)
|
||
{
|
||
draft.useTesseract = true;
|
||
validateTesseract(draft);
|
||
SetDlgItemTextW(w, 506, (L"Ready: " + draft.tesseractLanguages).c_str());
|
||
return 0;
|
||
}
|
||
validateTesseract(draft);
|
||
v->settings->draft.useTesseract = draft.useTesseract;
|
||
v->settings->draft.tesseractPath = draft.tesseractPath;
|
||
v->settings->draft.tesseractLanguages = draft.tesseractLanguages;
|
||
DestroyWindow(w);
|
||
return 0;
|
||
}
|
||
if (id == IDCANCEL) { DestroyWindow(w); return 0; }
|
||
}
|
||
catch (const std::exception &e) { error(w, e); return 0; }
|
||
}
|
||
if (msg == WM_CLOSE) { DestroyWindow(w); return 0; }
|
||
if (msg == WM_NCDESTROY)
|
||
{
|
||
EnableWindow(v->parent, TRUE);
|
||
SetForegroundWindow(v->parent);
|
||
disposeFont(w); delete v;
|
||
SetWindowLongPtrW(w, GWLP_USERDATA, 0);
|
||
}
|
||
return DefWindowProcW(w, msg, wp, lp);
|
||
}
|
||
void showOcrOptions(HWND parent, SettingsView *v)
|
||
{
|
||
HWND w = makeWindow(*v->app, L"KSwitcher.OcrOptions", L"Image text recognition", ocrOptionsProc, 640, 450);
|
||
SetWindowLongPtrW(w, GWLP_HWNDPARENT, (LONG_PTR)parent);
|
||
SetWindowLongPtrW(w, GWLP_USERDATA, (LONG_PTR)new OcrOptionsView{parent, v});
|
||
label(w, L"Windows OCR is used by default. Recognition stays on this computer.", 18, 16, 600);
|
||
checkbox(w, L"&Use optional Tesseract 5 instead of Windows OCR", 501, 18, 48, 600);
|
||
check(w, 501, v->draft.useTesseract);
|
||
label(w, L"Tesseract executable (blank = detect installed location)", 18, 90, 600);
|
||
edit(w, 502, 18, 118, 484);
|
||
value(w, 502, v->draft.tesseractPath);
|
||
button(w, L"&Browse…", 504, 514, 117, 106);
|
||
label(w, L"Languages used together (for example ukr+eng+rus)", 18, 160, 600);
|
||
edit(w, 503, 18, 188, 602);
|
||
value(w, 503, v->draft.tesseractLanguages);
|
||
button(w, L"Check &installation", 505, 18, 228, 180);
|
||
control(w, L"STATIC", L"", 0, 506, 212, 232, 408, 24);
|
||
button(w, L"&Download Tesseract…", 507, 18, 266, 180);
|
||
label(w, L"Opens the Windows installer page in your browser.", 212, 270, 408);
|
||
label(w, L"Changing the engine or languages reprocesses saved images in the background.", 18, 314, 602);
|
||
label(w, L"Click OK here, then Save in Settings to apply. No downloads are automatic.", 18, 344, 602);
|
||
button(w, L"&OK", IDOK, 406, 390, 100);
|
||
button(w, L"&Cancel", IDCANCEL, 520, 390, 100);
|
||
EnableWindow(parent, FALSE);
|
||
showRequestedWindow(w); SetForegroundWindow(w);
|
||
}
|
||
#include "ui_sync.inl"
|
||
#include "ui_lan.inl"
|
||
bool settingsChanged(SettingsView *v)
|
||
{
|
||
try
|
||
{
|
||
return encodeSettings(collectSettings(v)) != encodeSettings(v->app->settings);
|
||
}
|
||
catch (const std::exception &)
|
||
{
|
||
// Invalid edits are unsaved changes too. Allow discarding them without
|
||
// requiring the user to repair the fields first.
|
||
return true;
|
||
}
|
||
}
|
||
LanView *settingsLanView(SettingsView *v)
|
||
{
|
||
return v->lan ? reinterpret_cast<LanView *>(GetWindowLongPtrW(v->lan, GWLP_USERDATA)) : nullptr;
|
||
}
|
||
bool settingsFieldsChanged(SettingsView *v)
|
||
{
|
||
const auto *lan = settingsLanView(v);
|
||
return (lan && !lan->draft.empty()) || syncDraftChanged(v->sync) || settingsChanged(v);
|
||
}
|
||
void updateSettingsState(HWND w, SettingsView *v)
|
||
{
|
||
if (!v || !v->ready || v->filling || v->snippets.filling || v->refreshing) return;
|
||
v->refreshing = true;
|
||
const bool changed = settingsFieldsChanged(v);
|
||
const bool snippetsChanged = snippetDraftChanged(v->viewport, &v->snippets);
|
||
const bool dirty = changed || snippetsChanged;
|
||
EnableWindow(GetDlgItem(w, SettingsApply), dirty);
|
||
const auto closeLabel = dirty ? L"&Cancel" : L"&Close";
|
||
if (value(w, IDCANCEL) != closeLabel) value(w, IDCANCEL, closeLabel);
|
||
EnableWindow(GetDlgItem(w, IDOK), dirty || (v->app->settings.autostart && !isLocalBuild()));
|
||
const wchar_t *text = changed ? L"Unsaved settings — click Apply or Save." :
|
||
snippetsChanged ? L"Unsaved snippets — click Apply or Save." : L"No unsaved settings.";
|
||
if (value(w, SettingsStatus) != text) value(w, SettingsStatus, text);
|
||
v->refreshing = false;
|
||
}
|
||
// Refresh after commands have updated controls/drafts, including early returns.
|
||
// Saving can destroy Settings, so retrieve its state only if it still exists.
|
||
struct SettingsStateRefresh
|
||
{
|
||
HWND window;
|
||
~SettingsStateRefresh()
|
||
{
|
||
if (IsWindow(window))
|
||
updateSettingsState(window, reinterpret_cast<SettingsView *>(GetWindowLongPtrW(window, GWLP_USERDATA)));
|
||
}
|
||
};
|
||
void applySettingsDraft(HWND w, SettingsView *v, bool keepOpen)
|
||
{
|
||
if (v->app->busy)
|
||
throw std::runtime_error("Wait for the current text operation to finish");
|
||
auto settings = collectSettings(v);
|
||
mergeSnippetDraft(v->viewport, &v->snippets, settings);
|
||
nlohmann::json draft = nlohmann::json::object();
|
||
auto *lan = settingsLanView(v);
|
||
if (lan && !lan->draft.empty()) draft["lan"] = lan->draft;
|
||
if (syncDraftChanged(v->sync)) draft["sync"] = collectSyncDraft(v->sync);
|
||
const bool syncEdited = draft.contains("sync");
|
||
const bool lanEdited = draft.contains("lan");
|
||
const auto payload = draft.empty() ? std::string{} : draft.dump();
|
||
v->app->applySettings(settings, Bytes(payload.begin(), payload.end()));
|
||
if (!keepOpen)
|
||
{
|
||
DestroyWindow(w);
|
||
return;
|
||
}
|
||
|
||
if (lanEdited) lan->draft.clear();
|
||
v->draft = v->app->settings;
|
||
fillSettings(w, v);
|
||
refreshSnippetDraft(v->viewport, &v->snippets);
|
||
if (syncEdited) reloadSyncEditor(v->sync);
|
||
if (lanEdited) refreshLan(v->lan, *lan);
|
||
}
|
||
void closeSettings(HWND w, SettingsView *v)
|
||
{
|
||
if ((settingsFieldsChanged(v) || snippetDraftChanged(v->viewport, &v->snippets)) &&
|
||
MessageBoxW(w, L"Discard your unsaved changes? Choose No to keep editing and use Apply or Save.",
|
||
L"KSwitcher — Unsaved settings", MB_YESNO | MB_ICONWARNING | MB_DEFBUTTON2) != IDYES)
|
||
return;
|
||
DestroyWindow(w);
|
||
}
|
||
LRESULT CALLBACK settingsProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||
{
|
||
if (msg == WM_DPICHANGED)
|
||
{
|
||
resizeForDpi(w, wp, lp);
|
||
return 0;
|
||
}
|
||
auto *v = (SettingsView *)GetWindowLongPtrW(w, GWLP_USERDATA);
|
||
if (msg == WM_NCCREATE)
|
||
{
|
||
auto *app = (App *)((CREATESTRUCTW *)lp)->lpCreateParams;
|
||
v = new SettingsView{app, app->settings};
|
||
SetWindowLongPtrW(w, GWLP_USERDATA, (LONG_PTR)v);
|
||
return TRUE;
|
||
}
|
||
if (!v)
|
||
return DefWindowProcW(w, msg, wp, lp);
|
||
try
|
||
{
|
||
switch (msg)
|
||
{
|
||
case WM_SIZE:
|
||
if (wp != SIZE_MINIMIZED) layoutSettings(w, *v);
|
||
return 0;
|
||
case WM_SHOWWINDOW:
|
||
if (wp) v->wasShown = true;
|
||
break;
|
||
case WM_GETMINMAXINFO:
|
||
{
|
||
auto &limits = *reinterpret_cast<MINMAXINFO *>(lp);
|
||
RECT window{}, client{};
|
||
GetWindowRect(w, &window);
|
||
GetClientRect(w, &client);
|
||
const auto work = workArea(window);
|
||
limits.ptMinTrackSize.x = std::min(work.right - work.left, scale(w, SettingsMinWidth) +
|
||
(window.right - window.left - client.right));
|
||
limits.ptMinTrackSize.y = std::min(work.bottom - work.top,
|
||
scale(w, SettingsMinHeight) + (window.bottom - window.top - client.bottom));
|
||
return 0;
|
||
}
|
||
case WM_SETTINGCHANGE: case WM_SYSCOLORCHANGE:
|
||
refreshSettingsColors(w, *v);
|
||
break;
|
||
case WM_DWMCOLORIZATIONCOLORCHANGED:
|
||
refreshSettingsColors(w, *v, static_cast<DWORD>(wp));
|
||
return 0;
|
||
case WM_ERASEBKGND:
|
||
return 1;
|
||
case WM_PAINT:
|
||
paintSettings(w, *v);
|
||
return 0;
|
||
case AppWindowPicked:
|
||
snippetWindowPicked(v->viewport, wp, lp);
|
||
return 0;
|
||
case WM_DRAWITEM:
|
||
if (wp == AppWindowPickerIcon || wp == AddMouseProfile || wp == RenameMouseProfile || wp == DeleteMouseProfile || wp == AddMouseEvent)
|
||
{
|
||
drawActionApplicationIcon(w, *reinterpret_cast<const DRAWITEMSTRUCT *>(lp));
|
||
return TRUE;
|
||
}
|
||
break;
|
||
case WM_CTLCOLORSTATIC:
|
||
{
|
||
HWND child = reinterpret_cast<HWND>(lp);
|
||
auto dc = reinterpret_cast<HDC>(wp);
|
||
if (child == GetDlgItem(v->viewport, 281))
|
||
{
|
||
SetTextColor(dc, GetSysColor(COLOR_WINDOWTEXT));
|
||
SetBkColor(dc, GetSysColor(COLOR_WINDOW));
|
||
return reinterpret_cast<LRESULT>(GetSysColorBrush(COLOR_WINDOW));
|
||
}
|
||
SetTextColor(dc, !v->palette.highContrast && (child == v->description || GetDlgCtrlID(child) == SettingsStatus)
|
||
? RGB(70, 91, 112) : GetSysColor(COLOR_WINDOWTEXT));
|
||
SetBkMode(dc, TRANSPARENT);
|
||
return reinterpret_cast<LRESULT>(child == v->brand || GetDlgCtrlID(child) == SettingsStatus
|
||
? v->palette.brush() : GetSysColorBrush(COLOR_WINDOW));
|
||
}
|
||
case WM_INPUT:
|
||
readMouseTestInput(w, *v, reinterpret_cast<HRAWINPUT>(lp));
|
||
return DefWindowProcW(w, msg, wp, lp);
|
||
case ConfigSettingsDownloaded:
|
||
v->draft = v->app->settings;
|
||
fillSettings(w, v);
|
||
refreshSnippetDraft(v->viewport, &v->snippets);
|
||
updateSettingsState(w, v);
|
||
return 0;
|
||
case WM_ENABLE:
|
||
if (wp) updateSettingsState(w, v);
|
||
break;
|
||
case WM_ACTIVATE:
|
||
if (LOWORD(wp) != WA_INACTIVE) updateSettingsState(w, v);
|
||
break;
|
||
case WM_NOTIFY:
|
||
if (reinterpret_cast<const NMHDR *>(lp)->idFrom == SettingsNavigation)
|
||
{
|
||
const auto code = reinterpret_cast<const NMHDR *>(lp)->code;
|
||
if (v->searching && code == NM_CUSTOMDRAW)
|
||
{
|
||
auto &draw = *reinterpret_cast<NMTVCUSTOMDRAW *>(lp);
|
||
if (draw.nmcd.dwDrawStage == CDDS_PREPAINT) return CDRF_NOTIFYITEMDRAW;
|
||
if (draw.nmcd.dwDrawStage == CDDS_ITEMPREPAINT)
|
||
{
|
||
const auto data = draw.nmcd.lItemlParam;
|
||
if (reinterpret_cast<HTREEITEM>(draw.nmcd.dwItemSpec) != TreeView_GetSelection(v->navigation) &&
|
||
(data >= static_cast<LPARAM>(v->pages.size()) ||
|
||
(data >= 0 && matchesSettingsSearch(*v, settingsSections[data].name))))
|
||
{
|
||
draw.clrTextBk = v->palette.highContrast ? GetSysColor(COLOR_HIGHLIGHT) : RGB(255, 235, 174);
|
||
draw.clrText = v->palette.highContrast ? GetSysColor(COLOR_HIGHLIGHTTEXT) : RGB(83, 52, 8);
|
||
}
|
||
}
|
||
return CDRF_DODEFAULT;
|
||
}
|
||
if (v->ready && !v->rebuildingNavigation && code == TVN_SELCHANGEDW)
|
||
openSettingsNode(w, *v, reinterpret_cast<const NMTREEVIEWW *>(lp)->itemNew.lParam, false);
|
||
if (v->ready && !v->searching && code == TVN_ITEMEXPANDINGW)
|
||
{
|
||
const auto ¬ice = *reinterpret_cast<const NMTREEVIEWW *>(lp);
|
||
const auto group = notice.itemNew.hItem;
|
||
if ((notice.action & TVE_COLLAPSE) && isSettingsGroup(*v, group))
|
||
{
|
||
for (auto item = TreeView_GetSelection(v->navigation); item;
|
||
item = TreeView_GetParent(v->navigation, item))
|
||
{
|
||
if (item != group) continue;
|
||
// Change the caret outside the native collapse notification.
|
||
PostMessageW(v->navigation, CollapseSettingsGroupMessage, 0, reinterpret_cast<LPARAM>(group));
|
||
return TRUE;
|
||
}
|
||
}
|
||
}
|
||
if (v->ready && v->searching && code == NM_DBLCLK)
|
||
{
|
||
TVITEMW item{};
|
||
item.mask = TVIF_PARAM;
|
||
item.hItem = TreeView_GetSelection(v->navigation);
|
||
if (item.hItem && TreeView_GetItem(v->navigation, &item)) openSettingsNode(w, *v, item.lParam, true);
|
||
}
|
||
return 0;
|
||
}
|
||
if (((NMHDR *)lp)->idFrom == 731)
|
||
{
|
||
if (((NMHDR *)lp)->code == NM_CUSTOMDRAW)
|
||
return drawMouseProfileChecks(*v, *reinterpret_cast<const NMLVCUSTOMDRAW *>(lp));
|
||
if (((NMHDR *)lp)->code == LVN_ITEMCHANGING)
|
||
return blockMouseProfileStateChange(w, *v, *reinterpret_cast<const NMLISTVIEW *>(lp));
|
||
if (((NMHDR *)lp)->code == LVN_ITEMCHANGED)
|
||
{
|
||
const auto &change = *reinterpret_cast<const NMLISTVIEW *>(lp);
|
||
if (!(change.uOldState & LVIS_SELECTED) && (change.uNewState & LVIS_SELECTED))
|
||
fillMouseEvents(w, *v);
|
||
}
|
||
return 0;
|
||
}
|
||
if (((NMHDR *)lp)->idFrom == 733 && ((NMHDR *)lp)->code == NM_DBLCLK)
|
||
{
|
||
const auto &click = *reinterpret_cast<const NMITEMACTIVATE *>(lp);
|
||
showMouseActionEditor(w, *v, mouseEventAtRow(click.hdr.hwndFrom, click.iItem));
|
||
return 0;
|
||
}
|
||
break;
|
||
case WM_COMMAND:
|
||
{
|
||
int id = LOWORD(wp);
|
||
if (id == SettingsSearch && HIWORD(wp) == EN_CHANGE)
|
||
{
|
||
if (v->ready) rebuildSettingsNavigation(w, *v);
|
||
return 0;
|
||
}
|
||
SettingsStateRefresh refresh{w};
|
||
HWND pane = v->viewport;
|
||
if (id == 282 && HIWORD(wp) == BN_CLICKED)
|
||
{
|
||
writeClipboard(w, textClip(value(pane, 281)));
|
||
value(pane, 283, L"Copied to clipboard.");
|
||
return 0;
|
||
}
|
||
if (((id >= 301 && id <= 317) || id == SnippetMacros) &&
|
||
snippetCommand(w, &v->snippets, wp))
|
||
return 0;
|
||
if (id == 220 && HIWORD(wp) == LBN_SELCHANGE && !v->filling)
|
||
{
|
||
collectLayout(v);
|
||
layoutSelection(v);
|
||
return 0;
|
||
}
|
||
if (id == 256)
|
||
{
|
||
showLogs(*v->app);
|
||
return 0;
|
||
}
|
||
if (id == 257) { showOcrOptions(w, v); return 0; }
|
||
if (id == 263) { collectLayout(v); showAppLanguages(w, v); return 0; }
|
||
if (handleMouseBindings(w, *v, wp)) return 0;
|
||
if (id == 259) { collectLayout(v); showChatLanguages(w, v); return 0; }
|
||
if (id == 230)
|
||
{
|
||
collectLayout(v);
|
||
fillLayouts(v);
|
||
return 0;
|
||
}
|
||
if (id == 232 || id == 233)
|
||
{
|
||
collectLayout(v);
|
||
int next = v->selection + (id == 232 ? -1 : 1);
|
||
if (next >= 0 && next < (int)v->order.size())
|
||
{
|
||
std::swap(v->order[next], v->order[v->selection]);
|
||
v->selection = next;
|
||
fillLayouts(v);
|
||
}
|
||
return 0;
|
||
}
|
||
if (id == SettingsApply || id == IDOK)
|
||
{
|
||
if (!IsWindowEnabled(GetDlgItem(w, id))) return 0;
|
||
applySettingsDraft(w, v, id == SettingsApply);
|
||
return 0;
|
||
}
|
||
if (id == IDCANCEL)
|
||
{
|
||
closeSettings(w, v);
|
||
return 0;
|
||
}
|
||
if (id == 250)
|
||
{
|
||
auto path = pickFile(w, false);
|
||
if (!path.empty())
|
||
{
|
||
v->draft = loadSettings(path, v->app->layouts);
|
||
fillSettings(w, v);
|
||
}
|
||
return 0;
|
||
}
|
||
if (id == 251)
|
||
{
|
||
auto s = collectSettings(v);
|
||
auto path = pickFile(w, true);
|
||
if (!path.empty())
|
||
saveSettings(path, s);
|
||
return 0;
|
||
}
|
||
if (id == 407)
|
||
{
|
||
auto folder = std::filesystem::path(executable()).parent_path() / L"dictionaries";
|
||
if ((INT_PTR)ShellExecuteW(w, L"open", folder.c_str(), nullptr, nullptr, SW_SHOWNORMAL) <= 32)
|
||
throw std::runtime_error("Could not open the dictionary folder.");
|
||
return 0;
|
||
}
|
||
if (id == 253)
|
||
{
|
||
if (v->app->busy)
|
||
throw std::runtime_error("Wait for the current operation");
|
||
v->draft = collectSettings(v);
|
||
v->app->reloadLayouts();
|
||
v->draft.direct = v->app->settings.direct;
|
||
fillSettings(w, v);
|
||
return 0;
|
||
}
|
||
if (id == 254)
|
||
{
|
||
if (MessageBoxW(w, L"Delete all clipboard history, including pinned items?", L"Clear history",
|
||
MB_YESNO | MB_ICONWARNING) == IDYES)
|
||
v->app->clearHistory();
|
||
return 0;
|
||
}
|
||
break;
|
||
}
|
||
case WM_CLOSE:
|
||
closeSettings(w, v);
|
||
return 0;
|
||
case WM_ENDSESSION:
|
||
if (wp) saveSettingsWindowState(w, *v);
|
||
break;
|
||
case WM_DESTROY:
|
||
saveSettingsWindowState(w, *v);
|
||
break;
|
||
case WM_NCDESTROY:
|
||
if (v->rawMouseRegistered) registerMouseTestInput(nullptr);
|
||
for (HICON icon : v->mouseProfileChecks)
|
||
if (icon) DestroyIcon(icon);
|
||
for (HFONT face : {v->headingFont, v->brandFont, v->groupFont, v->fieldFont})
|
||
if (face) DeleteObject(face);
|
||
disposeFont(w);
|
||
v->app->settingsWindow = nullptr;
|
||
delete v;
|
||
return DefWindowProcW(w, msg, wp, lp);
|
||
}
|
||
}
|
||
catch (const std::exception &e)
|
||
{
|
||
error(w, e);
|
||
}
|
||
return DefWindowProcW(w, msg, wp, lp);
|
||
}
|
||
void enableSnippetScopeControls(HWND w, bool enabled)
|
||
{
|
||
for (int id : {315, 316, 317, AppWindowPickerIcon}) EnableWindow(GetDlgItem(w, id), enabled);
|
||
}
|
||
void updateSnippetEditor(HWND w, SnippetView *v)
|
||
{
|
||
v->filling = true;
|
||
bool selected = v->selection >= 0 && v->selection < (int)v->snippets.size();
|
||
value(w, 302, selected ? v->snippets[v->selection].trigger : L"");
|
||
value(w, 303, selected ? v->snippets[v->selection].text : L"");
|
||
std::wstring apps;
|
||
if (selected) for (const auto &app : v->snippets[v->selection].apps)
|
||
{
|
||
if (!apps.empty()) apps += L", ";
|
||
if (!app.empty()) apps += app + L".exe";
|
||
}
|
||
value(w, 315, apps);
|
||
bool restricted = selected && !v->snippets[v->selection].apps.empty();
|
||
CheckDlgButton(w, 314, restricted ? BST_CHECKED : BST_UNCHECKED);
|
||
for (int id : {302, 303, 311, 314, SnippetMacros})
|
||
EnableWindow(GetDlgItem(w, id), selected);
|
||
enableSnippetScopeControls(w, restricted);
|
||
v->filling = false;
|
||
}
|
||
void fillSnippets(HWND w, SnippetView *v)
|
||
{
|
||
SendDlgItemMessageW(w, 301, LB_RESETCONTENT, 0, 0);
|
||
for (auto &sn : v->snippets)
|
||
{
|
||
auto label = sn.trigger + (sn.apps.empty() ? L" [All apps]" : L" [" + sn.apps.front() + (sn.apps.size() > 1 ? L", ...]" : L"]"));
|
||
SendDlgItemMessageW(w, 301, LB_ADDSTRING, 0, (LPARAM)label.c_str());
|
||
}
|
||
if (v->selection >= 0)
|
||
SendDlgItemMessageW(w, 301, LB_SETCURSEL, v->selection, 0);
|
||
updateSnippetEditor(w, v);
|
||
}
|
||
void collectSnippet(HWND w, SnippetView *v)
|
||
{
|
||
if (v->selection >= 0 && v->selection < (int)v->snippets.size())
|
||
{
|
||
auto &snippet = v->snippets[v->selection];
|
||
if (snippet.id.empty()) snippet.id = snippetId(snippet);
|
||
snippet.trigger = value(w, 302);
|
||
snippet.text = value(w, 303);
|
||
snippet.apps.clear();
|
||
if (IsDlgButtonChecked(w, 314) == BST_CHECKED)
|
||
{
|
||
std::wistringstream input(value(w, 315)); std::wstring item;
|
||
while (std::getline(input, item, L','))
|
||
{
|
||
auto app = snippetAppName(item);
|
||
if (!app.empty()) snippet.apps.push_back(app);
|
||
}
|
||
// An explicitly restricted but empty list must not become global.
|
||
if (snippet.apps.empty()) snippet.apps.push_back(L"");
|
||
}
|
||
}
|
||
}
|
||
bool sameSnippets(const std::vector<Snippet> &left, const std::vector<Snippet> &right)
|
||
{
|
||
return std::equal(left.begin(), left.end(), right.begin(), right.end(), [](const Snippet &a, const Snippet &b) {
|
||
return a.id == b.id && a.trigger == b.trigger && a.text == b.text && a.apps == b.apps;
|
||
});
|
||
}
|
||
bool snippetDraftChanged(HWND w, SnippetView *v)
|
||
{
|
||
collectSnippet(w, v);
|
||
return !sameSnippets(v->snippets, v->saved);
|
||
}
|
||
void refreshSnippetDraft(HWND w, SnippetView *v)
|
||
{
|
||
if (snippetDraftChanged(w, v) || sameSnippets(v->saved, v->app->settings.snippets))
|
||
return;
|
||
v->snippets = v->saved = v->app->settings.snippets;
|
||
v->selection = -1;
|
||
fillSnippets(w, v);
|
||
}
|
||
bool mergeSnippetDraft(HWND w, SnippetView *v, Settings &settings)
|
||
{
|
||
if (!snippetDraftChanged(w, v)) return false;
|
||
const auto ¤t = v->app->settings.snippets;
|
||
if (!sameSnippets(current, v->saved) && !sameSnippets(current, v->snippets))
|
||
throw std::runtime_error("Snippets changed elsewhere. Reopen Settings to load the current snippets.");
|
||
settings.snippets = v->snippets;
|
||
return true;
|
||
}
|
||
std::wstring snippetWindowExecutable(HWND window)
|
||
{
|
||
auto process = lower(processName(window));
|
||
return process.empty() ? L"" : process + L".exe";
|
||
}
|
||
void addSnippetApplication(HWND w, const std::wstring &app)
|
||
{
|
||
auto name = snippetAppName(app);
|
||
if (name.empty()) return;
|
||
auto current = value(w, 315);
|
||
std::wistringstream input(current);
|
||
std::wstring entry;
|
||
while (std::getline(input, entry, L','))
|
||
if (snippetAppName(entry) == name) return;
|
||
value(w, 315, current.empty() ? app : current + L", " + app);
|
||
}
|
||
void snippetWindowPicked(HWND w, WPARAM target, LPARAM phase)
|
||
{
|
||
if (phase == 1 && target)
|
||
addSnippetApplication(w, snippetWindowExecutable(reinterpret_cast<HWND>(target)));
|
||
}
|
||
constexpr struct SnippetInsertionOption
|
||
{
|
||
const wchar_t *name, *parameter, *initial;
|
||
} snippetInsertions[] = {
|
||
{L"Place cursor", L"", L""},
|
||
{L"Press Enter", L"", L""},
|
||
{L"Pause", L"&Milliseconds (0–10000)", L"50"},
|
||
{L"Tap a key", L"Record &key", L""},
|
||
{L"Press keys together", L"Record &keys", L""}
|
||
};
|
||
constexpr int InsertionType = 321, InsertionLabel = 322, InsertionParameter = 323, InsertionPreview = 324;
|
||
constexpr int NumericParameterWidth = 62, TextParameterWidth = 210;
|
||
constexpr UINT SnippetKeyEvent = WM_APP + 160;
|
||
struct SnippetKeyCapture
|
||
{
|
||
HWND window;
|
||
HHOOK hook{};
|
||
std::vector<WORD> keys, held;
|
||
bool releasing{};
|
||
};
|
||
thread_local SnippetKeyCapture *activeSnippetCapture{};
|
||
SnippetInsertion selectedSnippetInsertion(HWND w)
|
||
{
|
||
return static_cast<SnippetInsertion>(static_cast<int>(SendDlgItemMessageW(w, InsertionType, CB_GETCURSEL, 0, 0)));
|
||
}
|
||
bool recordsSnippetKeys(SnippetInsertion type)
|
||
{
|
||
return type == SnippetInsertion::Key || type == SnippetInsertion::Chord;
|
||
}
|
||
void stopSnippetCapture(SnippetKeyCapture &capture)
|
||
{
|
||
if (!capture.hook) return;
|
||
activeSnippetCapture = nullptr;
|
||
UnhookWindowsHookEx(capture.hook);
|
||
capture.hook = nullptr;
|
||
}
|
||
LRESULT CALLBACK snippetCaptureHook(int code, WPARAM message, LPARAM data)
|
||
{
|
||
auto *capture = activeSnippetCapture;
|
||
if (code == HC_ACTION && capture && GetForegroundWindow() == capture->window &&
|
||
GetFocus() == GetDlgItem(capture->window, InsertionParameter))
|
||
{
|
||
const auto &event = *reinterpret_cast<const KBDLLHOOKSTRUCT *>(data);
|
||
PostMessageW(capture->window, SnippetKeyEvent, event.vkCode, message == WM_KEYDOWN || message == WM_SYSKEYDOWN);
|
||
return 1;
|
||
}
|
||
return CallNextHookEx(nullptr, code, message, data);
|
||
}
|
||
std::wstring snippetInsertionText(HWND w)
|
||
{
|
||
return formatSnippetInsertion(selectedSnippetInsertion(w), value(w, InsertionParameter));
|
||
}
|
||
void updateSnippetInsertion(HWND w, bool changedType)
|
||
{
|
||
if (changedType)
|
||
{
|
||
const auto type = selectedSnippetInsertion(w);
|
||
const auto &option = snippetInsertions[static_cast<size_t>(type)];
|
||
const bool hasParameter = *option.parameter != L'\0';
|
||
const bool textParameter = recordsSnippetKeys(type);
|
||
const auto parameter = GetDlgItem(w, InsertionParameter);
|
||
SendMessageW(parameter, EM_SETREADONLY, textParameter, 0);
|
||
SendMessageW(parameter, EM_SETCUEBANNER, TRUE,
|
||
reinterpret_cast<LPARAM>(textParameter ? L"Click or press Space to record" : L""));
|
||
auto &controls = windowLayoutState(w)->controls;
|
||
const auto bounds = std::find_if(controls.begin(), controls.end(),
|
||
[parameter](const auto &control) { return control.first == parameter; });
|
||
if (bounds != controls.end())
|
||
{
|
||
auto &rect = bounds->second;
|
||
rect.right = rect.left + (textParameter ? TextParameterWidth : NumericParameterWidth);
|
||
arrangeWindow(w);
|
||
}
|
||
SendMessageW(parameter, EM_SETLIMITTEXT, textParameter ? 96 : 5, 0);
|
||
value(w, InsertionLabel, hasParameter ? option.parameter : L"Parameter");
|
||
value(w, InsertionParameter, option.initial);
|
||
EnableWindow(parameter, hasParameter);
|
||
}
|
||
const auto text = snippetInsertionText(w);
|
||
const auto *capture = reinterpret_cast<SnippetKeyCapture *>(GetWindowLongPtrW(w, GWLP_USERDATA));
|
||
const bool recording = capture && capture->hook;
|
||
const wchar_t *hint = recording ? L"Press the keys you want to record." :
|
||
recordsSnippetKeys(selectedSnippetInsertion(w)) ? L"" : L"Enter a valid duration (0–10000).";
|
||
value(w, InsertionPreview, text.empty() ? hint : text);
|
||
EnableWindow(GetDlgItem(w, IDOK), !recording && !text.empty());
|
||
}
|
||
void showRecordedSnippetKeys(const SnippetKeyCapture &capture)
|
||
{
|
||
std::wstring text;
|
||
for (auto recorded : capture.keys)
|
||
{
|
||
auto name = snippetKeyName(recorded);
|
||
if (name.empty()) { text.clear(); break; }
|
||
if (!text.empty()) text += L'+';
|
||
text += name;
|
||
}
|
||
value(capture.window, InsertionParameter, text);
|
||
updateSnippetInsertion(capture.window, false);
|
||
}
|
||
void recordSnippetKey(SnippetKeyCapture &capture, WORD key, bool down)
|
||
{
|
||
if (!capture.hook) return;
|
||
auto &held = capture.held;
|
||
auto position = std::find(held.begin(), held.end(), key);
|
||
if (down)
|
||
{
|
||
if (position != held.end()) return;
|
||
held.push_back(key);
|
||
if (!capture.releasing)
|
||
{
|
||
capture.keys.push_back(key);
|
||
showRecordedSnippetKeys(capture);
|
||
}
|
||
return;
|
||
}
|
||
if (position == held.end()) return;
|
||
held.erase(position);
|
||
capture.releasing = true;
|
||
if (!held.empty()) return;
|
||
stopSnippetCapture(capture);
|
||
|
||
updateSnippetInsertion(capture.window, false);
|
||
if (snippetInsertionText(capture.window).empty())
|
||
value(capture.window, InsertionPreview,
|
||
selectedSnippetInsertion(capture.window) == SnippetInsertion::Chord ?
|
||
L"Record at least two supported keys held together." : L"Record one supported key.");
|
||
}
|
||
LRESULT CALLBACK snippetParameterProc(HWND field, UINT msg, WPARAM wp, LPARAM lp, UINT_PTR, DWORD_PTR ref)
|
||
{
|
||
auto &capture = *reinterpret_cast<SnippetKeyCapture *>(ref);
|
||
const bool recordKeys = recordsSnippetKeys(selectedSnippetInsertion(capture.window));
|
||
if (recordKeys && ((msg == WM_LBUTTONUP) || (msg == WM_KEYUP && wp == VK_SPACE)))
|
||
{
|
||
if (msg == WM_LBUTTONUP) DefSubclassProc(field, msg, wp, lp);
|
||
if (!capture.hook)
|
||
{
|
||
capture.held.clear();
|
||
capture.keys.clear();
|
||
capture.releasing = false;
|
||
capture.hook = SetWindowsHookExW(WH_KEYBOARD_LL, snippetCaptureHook, GetModuleHandleW(nullptr), 0);
|
||
if (capture.hook)
|
||
{
|
||
activeSnippetCapture = &capture;
|
||
value(capture.window, InsertionParameter, L"");
|
||
updateSnippetInsertion(capture.window, false);
|
||
}
|
||
else value(capture.window, InsertionPreview, L"Could not start key recording. Try again.");
|
||
}
|
||
return 0;
|
||
}
|
||
if (msg == WM_KILLFOCUS && capture.hook)
|
||
{
|
||
stopSnippetCapture(capture);
|
||
value(capture.window, InsertionParameter, L"");
|
||
updateSnippetInsertion(capture.window, false);
|
||
}
|
||
return DefSubclassProc(field, msg, wp, lp);
|
||
}
|
||
LRESULT CALLBACK snippetInsertionProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||
{
|
||
HWND parent = GetWindow(w, GW_OWNER);
|
||
auto *capture = reinterpret_cast<SnippetKeyCapture *>(GetWindowLongPtrW(w, GWLP_USERDATA));
|
||
if (msg == WM_DPICHANGED) { resizeForDpi(w, wp, lp); return 0; }
|
||
if (msg == SnippetKeyEvent && capture)
|
||
{
|
||
recordSnippetKey(*capture, static_cast<WORD>(wp), lp != 0);
|
||
return 0;
|
||
}
|
||
if (msg == WM_COMMAND)
|
||
{
|
||
const int id = LOWORD(wp);
|
||
if (id == InsertionType && HIWORD(wp) == CBN_SELCHANGE) updateSnippetInsertion(w, true);
|
||
if (id == InsertionParameter && HIWORD(wp) == EN_CHANGE) updateSnippetInsertion(w, false);
|
||
if (id == IDOK && IsWindowEnabled(GetDlgItem(w, IDOK)))
|
||
{
|
||
const auto text = snippetInsertionText(w);
|
||
DestroyWindow(w);
|
||
SendDlgItemMessageW(settingsPage(parent), 303, EM_REPLACESEL, TRUE, reinterpret_cast<LPARAM>(text.c_str()));
|
||
}
|
||
if (id == IDCANCEL) DestroyWindow(w);
|
||
return 0;
|
||
}
|
||
if (msg == WM_CLOSE) { DestroyWindow(w); return 0; }
|
||
if (msg == WM_NCDESTROY)
|
||
{
|
||
if (capture)
|
||
{
|
||
stopSnippetCapture(*capture);
|
||
delete capture;
|
||
SetWindowLongPtrW(w, GWLP_USERDATA, 0);
|
||
}
|
||
EnableWindow(parent, TRUE);
|
||
SetForegroundWindow(parent);
|
||
SetFocus(GetDlgItem(settingsPage(parent), 303));
|
||
disposeFont(w);
|
||
}
|
||
return DefWindowProcW(w, msg, wp, lp);
|
||
}
|
||
void showSnippetInsertion(HWND parent, App &app)
|
||
{
|
||
HWND w = makeWindow(app, L"KSwitcher.SnippetInsertion", L"Insert macro or marker", snippetInsertionProc,
|
||
426, 150, 0, false, parent);
|
||
label(w, L"&Action", 18, 14, 166);
|
||
auto list = control(w, L"COMBOBOX", L"", WS_TABSTOP | CBS_DROPDOWNLIST | WS_VSCROLL,
|
||
InsertionType, 18, 38, 166, 174);
|
||
for (const auto &option : snippetInsertions)
|
||
SendMessageW(list, CB_ADDSTRING, 0, reinterpret_cast<LPARAM>(option.name));
|
||
SendMessageW(list, CB_SETCURSEL, 0, 0);
|
||
control(w, L"STATIC", L"", 0, InsertionLabel, 198, 14, 210, 22);
|
||
auto parameter = edit(w, InsertionParameter, 198, 38, NumericParameterWidth);
|
||
auto *capture = new SnippetKeyCapture{w};
|
||
SetWindowLongPtrW(w, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(capture));
|
||
SetWindowSubclass(parameter, snippetParameterProc, 1, reinterpret_cast<DWORD_PTR>(capture));
|
||
label(w, L"Inserts", 18, 75, 59);
|
||
control(w, L"STATIC", L"", SS_ENDELLIPSIS, InsertionPreview, 78, 75, 330, 22);
|
||
button(w, L"&Insert", IDOK, 200, 105);
|
||
button(w, L"&Cancel", IDCANCEL, 308, 105);
|
||
updateSnippetInsertion(w, true);
|
||
EnableWindow(parent, FALSE);
|
||
showRequestedWindow(w);
|
||
SetFocus(list);
|
||
}
|
||
bool snippetCommand(HWND root, SnippetView *v, WPARAM wp)
|
||
{
|
||
HWND w = settingsPage(root);
|
||
if (v->filling) return true;
|
||
const int id = LOWORD(wp);
|
||
if (id == 314)
|
||
{
|
||
bool restricted = IsDlgButtonChecked(w, 314) == BST_CHECKED;
|
||
enableSnippetScopeControls(w, restricted);
|
||
return true;
|
||
}
|
||
if (id == 317)
|
||
{
|
||
addSnippetApplication(w, value(w, 316));
|
||
return true;
|
||
}
|
||
if (id == 301 && HIWORD(wp) == LBN_SELCHANGE)
|
||
{
|
||
collectSnippet(w, v);
|
||
v->selection = (int)SendDlgItemMessageW(w, 301, LB_GETCURSEL, 0, 0);
|
||
updateSnippetEditor(w, v);
|
||
return true;
|
||
}
|
||
if (id == 310)
|
||
{
|
||
collectSnippet(w, v);
|
||
v->snippets.push_back({L";new", L"", newSnippetId()});
|
||
v->selection = (int)v->snippets.size() - 1;
|
||
fillSnippets(w, v);
|
||
SetFocus(GetDlgItem(w, 302));
|
||
return true;
|
||
}
|
||
if (id == 311)
|
||
{
|
||
if (v->selection >= 0)
|
||
{
|
||
v->snippets.erase(v->snippets.begin() + v->selection);
|
||
v->selection = -1;
|
||
fillSnippets(w, v);
|
||
SetFocus(GetDlgItem(w, 301));
|
||
}
|
||
return true;
|
||
}
|
||
if (id == SnippetMacros)
|
||
{
|
||
if (v->selection >= 0 && v->selection < (int)v->snippets.size()) showSnippetInsertion(root, *v->app);
|
||
return true;
|
||
}
|
||
return false;
|
||
}
|
||
void createSnippetEditor(HWND w, SnippetView *view, bool embedded)
|
||
{
|
||
const int top = embedded ? 60 : 16;
|
||
const int textHeight = embedded ? 106 : 240;
|
||
const int actions = top + 201 + textHeight;
|
||
if (embedded) settingsGroupLabel(w, L"Triggers", 24, top, 186);
|
||
else label(w, L"Triggers", 24, top, 186);
|
||
control(w, L"LISTBOX", L"", WS_TABSTOP | WS_VSCROLL | LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_BORDER,
|
||
301, 24, top + 24, 186, 170 + textHeight);
|
||
button(w, L"&Add", 310, 24, actions, 88);
|
||
button(w, L"&Delete", 311, 122, actions, 88);
|
||
label(w, L"&Trigger (for example ;addr)", 232, top, 452);
|
||
edit(w, 302, 232, top + 24, 452);
|
||
checkbox(w, L"Only in these &applications (unchecked: everywhere)", 314, 232, top + 55, 452);
|
||
edit(w, 315, 232, top + 83, 452);
|
||
control(w, L"COMBOBOX", L"", WS_TABSTOP | CBS_DROPDOWNLIST | WS_VSCROLL, 316, 232, top + 113, 296, 200);
|
||
button(w, L"Add a&pp", 317, 536, top + 110, 108);
|
||
createAppWindowPicker(w, AppWindowPickerIcon, 652, top + 110, 32, view->pickerOutline, createButtonTooltips(w));
|
||
label(w, L"Process names, comma-separated (for example chrome.exe)", 232, top + 144, 452);
|
||
label(w, L"&Replacement text", 232, top + 170, 452);
|
||
edit(w, 303, 232, top + 194, 452, textHeight, ES_MULTILINE | ES_WANTRETURN | ES_AUTOVSCROLL | WS_VSCROLL);
|
||
button(w, L"Insert ¯o or marker…", SnippetMacros, 232, actions, 202);
|
||
if (!embedded)
|
||
{
|
||
button(w, L"&Save", IDOK, 474, actions + 44, 100);
|
||
button(w, L"&Cancel", IDCANCEL, 584, actions + 44, 100);
|
||
}
|
||
std::set<std::wstring> apps;
|
||
EnumWindows([](HWND candidate, LPARAM context)->BOOL {
|
||
if (IsWindowVisible(candidate))
|
||
{
|
||
auto name = snippetWindowExecutable(candidate);
|
||
if (!name.empty()) reinterpret_cast<std::set<std::wstring> *>(context)->insert(name);
|
||
}
|
||
return TRUE;
|
||
}, (LPARAM)&apps);
|
||
for (const auto &name : apps) SendDlgItemMessageW(w, 316, CB_ADDSTRING, 0, (LPARAM)name.c_str());
|
||
SendDlgItemMessageW(w, 316, CB_SETCURSEL, 0, 0);
|
||
fillSnippets(w, view);
|
||
}
|
||
LRESULT CALLBACK snippetProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||
{
|
||
if (msg == WM_DPICHANGED)
|
||
{
|
||
resizeForDpi(w, wp, lp);
|
||
return 0;
|
||
}
|
||
auto *v = (SnippetView *)GetWindowLongPtrW(w, GWLP_USERDATA);
|
||
if (msg == WM_NCCREATE)
|
||
{
|
||
auto *app = (App *)((CREATESTRUCTW *)lp)->lpCreateParams;
|
||
v = new SnippetView{app, app->settings.snippets, app->settings.snippets};
|
||
SetWindowLongPtrW(w, GWLP_USERDATA, (LONG_PTR)v);
|
||
return TRUE;
|
||
}
|
||
if (!v) return DefWindowProcW(w, msg, wp, lp);
|
||
try
|
||
{
|
||
if (msg == AppWindowPicked) { snippetWindowPicked(w, wp, lp); return 0; }
|
||
if (msg == WM_DRAWITEM && wp == AppWindowPickerIcon)
|
||
{
|
||
drawActionApplicationIcon(w, *reinterpret_cast<const DRAWITEMSTRUCT *>(lp));
|
||
return TRUE;
|
||
}
|
||
if (msg == WM_COMMAND)
|
||
{
|
||
if (LOWORD(wp) == IDOK)
|
||
{
|
||
auto settings = v->app->settings;
|
||
if (mergeSnippetDraft(w, v, settings))
|
||
{
|
||
if (v->app->busy) throw std::runtime_error("Wait for the current operation");
|
||
v->app->applySettings(settings);
|
||
}
|
||
DestroyWindow(w);
|
||
return 0;
|
||
}
|
||
if (LOWORD(wp) == IDCANCEL) { DestroyWindow(w); return 0; }
|
||
if (snippetCommand(w, v, wp)) return 0;
|
||
}
|
||
if (msg == WM_CLOSE)
|
||
{
|
||
DestroyWindow(w);
|
||
return 0;
|
||
}
|
||
if (msg == WM_NCDESTROY)
|
||
{
|
||
disposeFont(w);
|
||
v->app->snippetsWindow = nullptr;
|
||
delete v;
|
||
}
|
||
}
|
||
catch (const std::exception &e)
|
||
{
|
||
error(w, e);
|
||
}
|
||
return DefWindowProcW(w, msg, wp, lp);
|
||
}
|
||
#endif
|
||
#ifndef KS_CONFIG_APP
|
||
LRESULT CALLBACK entryProc(HWND w, UINT msg, WPARAM wp, LPARAM lp)
|
||
{
|
||
if (msg == WM_NCCREATE)
|
||
SetWindowLongPtrW(w, GWLP_USERDATA, (LONG_PTR)((CREATESTRUCTW *)lp)->lpCreateParams);
|
||
if (msg == WM_SIZE)
|
||
{
|
||
MoveWindow(GetDlgItem(w, 1), 10, 10, LOWORD(lp) - 20, HIWORD(lp) - 20, TRUE);
|
||
return 0;
|
||
}
|
||
if (msg == WM_NCDESTROY) {
|
||
disposeFont(w);
|
||
auto *app = (App *)GetWindowLongPtrW(w, GWLP_USERDATA);
|
||
if (app && app->historyService && app->historyEntryWindows && !--app->historyEntryWindows &&
|
||
!IsWindowVisible(app->historyWindow)) PostMessageW(app->window, WM_CLOSE, 0, 0);
|
||
}
|
||
return DefWindowProcW(w, msg, wp, lp);
|
||
}
|
||
#endif
|
||
} // namespace
|
||
#ifndef KS_CONFIG_APP
|
||
void refreshHistory(App &app)
|
||
{
|
||
if (app.isolateHistory) { app.refreshHistoryProcess(); return; }
|
||
if (app.historyWindow)
|
||
{
|
||
auto *v = (HistoryView *)GetWindowLongPtrW(app.historyWindow, GWLP_USERDATA);
|
||
search(app.historyWindow, v);
|
||
}
|
||
}
|
||
void showHistory(App &app, bool visible)
|
||
{
|
||
if (app.isolateHistory) { if (visible) app.openHistoryProcess(); return; }
|
||
if (!app.history)
|
||
{
|
||
app.report(L"Clipboard history is unavailable. See the log in the data folder.");
|
||
return;
|
||
}
|
||
HWND foreground = GetForegroundWindow();
|
||
if (visible && app.historyWindow && IsWindowVisible(app.historyWindow) && foreground == app.historyWindow)
|
||
{
|
||
auto *v = (HistoryView *)GetWindowLongPtrW(app.historyWindow, GWLP_USERDATA);
|
||
if (v->items.size() > 1)
|
||
app.pasteEntry(v->items[1].id, false);
|
||
return;
|
||
}
|
||
if (foreground != app.window && foreground != app.historyWindow)
|
||
app.pasteTarget = foreground;
|
||
if (!app.historyWindow)
|
||
{
|
||
HWND w = makeWindow(app, L"KSwitcher.History", L"Clipboard history", historyProc, 760, 500);
|
||
app.historyWindow = w;
|
||
windowLayoutState(w)->history = true;
|
||
auto filter = control(w, L"BUTTON", L"★ Pinned only", WS_TABSTOP | BS_AUTOCHECKBOX,
|
||
117, 16, 38, 112, 25);
|
||
SendMessageW(filter, BM_SETCHECK, app.historyPinnedOnly ? BST_CHECKED : BST_UNCHECKED, 0);
|
||
auto computers = control(w,L"BUTTON",app.historyComputers.empty()?L" Computers: All ▾":L" Computers: Selected ▾",
|
||
WS_TABSTOP | BS_PUSHBUTTON | BS_LEFT,118,136,36,180,28);
|
||
(void)computers;
|
||
label(w, L"&Search clipboard history", 328, 12, 400);
|
||
edit(w, 101, 328, 38, 416);
|
||
auto list = control(w, L"LISTBOX", L"",
|
||
WS_TABSTOP | WS_VSCROLL | LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_BORDER |
|
||
LBS_OWNERDRAWFIXED | LBS_HASSTRINGS,
|
||
102, 16, 76, 728, 360);
|
||
SendMessageW(list, LB_SETITEMHEIGHT, 0, scale(w, 88));
|
||
button(w, L"&Paste", 110, 16, 452, 90);
|
||
button(w, L"Plain &text", 111, 114, 452, 100);
|
||
button(w, L"P&in / unpin", 112, 222, 452, 110);
|
||
button(w, L"&Delete", 113, 340, 452, 90);
|
||
button(w, L"&Open item", 114, 438, 452, 100);
|
||
button(w, L"Clear &history…", 116, 546, 452, 150);
|
||
SetWindowSubclass(list, historyKey, 1, (DWORD_PTR)w);
|
||
SetWindowSubclass(GetDlgItem(w, 101), historyKey, 1, (DWORD_PTR)w);
|
||
if (app.historyService) {
|
||
auto *v = (HistoryView *)GetWindowLongPtrW(w, GWLP_USERDATA);
|
||
v->rememberedSelection = app.historySelection;
|
||
v->rememberedTop = app.historyTop;
|
||
SetDlgItemTextW(w, 101, app.historyQuery.c_str());
|
||
}
|
||
}
|
||
if (!visible) return;
|
||
// A fresh invocation starts at the newest matching item. Background search
|
||
// and OCR refreshes still preserve the user's selection while browsing.
|
||
auto *view = (HistoryView *)GetWindowLongPtrW(app.historyWindow, GWLP_USERDATA);
|
||
view->selectFirstOnResults = true;
|
||
POINT cursor;
|
||
GetCursorPos(&cursor);
|
||
MONITORINFO monitor{sizeof(monitor)};
|
||
GetMonitorInfoW(MonitorFromPoint(cursor, MONITOR_DEFAULTTONEAREST), &monitor);
|
||
RECT r;
|
||
GetWindowRect(app.historyWindow, &r);
|
||
int x = std::max(monitor.rcWork.left, std::min(cursor.x, monitor.rcWork.right - (r.right - r.left)));
|
||
int y = std::max(monitor.rcWork.top, std::min(cursor.y, monitor.rcWork.bottom - (r.bottom - r.top)));
|
||
SetWindowPos(app.historyWindow, HWND_TOP, x, y, 0, 0, SWP_NOSIZE | SWP_SHOWWINDOW);
|
||
SetForegroundWindow(app.historyWindow);
|
||
SetFocus(GetDlgItem(app.historyWindow, 101));
|
||
refreshHistory(app);
|
||
}
|
||
#endif
|
||
#ifndef KS_RESIDENT_APP
|
||
#include "ui_log.inl"
|
||
#else
|
||
void showLogs(App &app) { launchConfiguration(app, false, true); }
|
||
#endif
|
||
#ifndef KS_RESIDENT_APP
|
||
void showSettings(App &app, bool visible)
|
||
{
|
||
if (app.settingsWindow)
|
||
{
|
||
if (IsIconic(app.settingsWindow)) ShowWindow(app.settingsWindow, SW_RESTORE);
|
||
else showRequestedWindow(app.settingsWindow);
|
||
HWND target = app.settingsWindow;
|
||
if (!IsWindowEnabled(target))
|
||
target = GetLastActivePopup(target);
|
||
activateWindow(target);
|
||
return;
|
||
}
|
||
HWND w = makeWindow(app, L"KSwitcher.Settings", L"KSwitcher settings", settingsProc,
|
||
SettingsSidebarWidth + SettingsSplitterWidth + SettingsContentWidth + 20, 540);
|
||
auto &shell = *windowLayoutState(w);
|
||
shell.scrolling = false;
|
||
shell.settingsShell = true;
|
||
app.settingsWindow = w;
|
||
auto *v = (SettingsView *)GetWindowLongPtrW(w, GWLP_USERDATA);
|
||
const auto savedWindow = loadSettingsWindowState(app);
|
||
v->sidebarWidth = savedWindow.sidebar;
|
||
restoreSettingsWindowFrame(w, savedWindow);
|
||
v->brand = control(w, L"STATIC", L"KSwitcher", SS_CENTERIMAGE | SS_ENDELLIPSIS, SettingsBrand, 0, 0, 0, 0);
|
||
INITCOMMONCONTROLSEX treeControls{sizeof(treeControls), ICC_TREEVIEW_CLASSES};
|
||
InitCommonControlsEx(&treeControls);
|
||
v->search = edit(w, SettingsSearch, 0, 0, 0);
|
||
SendMessageW(v->search, EM_SETLIMITTEXT, 180, 0);
|
||
SendMessageW(v->search, EM_SETCUEBANNER, TRUE, reinterpret_cast<LPARAM>(L"Search settings"));
|
||
SetWindowSubclass(v->search, settingsSearchProc, 1, reinterpret_cast<DWORD_PTR>(v));
|
||
v->navigation = control(w, WC_TREEVIEWW, L"Settings sections",
|
||
WS_TABSTOP | TVS_HASBUTTONS | TVS_LINESATROOT | TVS_FULLROWSELECT | TVS_SHOWSELALWAYS,
|
||
SettingsNavigation, 0, 0, 0, 0);
|
||
SetWindowSubclass(v->navigation, settingsTreeProc, 1, reinterpret_cast<DWORD_PTR>(v));
|
||
v->heading = control(w, L"STATIC", L"", SS_CENTERIMAGE | SS_ENDELLIPSIS, SettingsHeading, 0, 0, 0, 0);
|
||
v->description = control(w, L"STATIC", L"", 0, SettingsDescription, 0, 0, 0, 0);
|
||
|
||
WNDCLASSW canvas{};
|
||
canvas.hInstance = app.instance;
|
||
canvas.lpfnWndProc = settingsViewportProc;
|
||
canvas.lpszClassName = L"KSwitcher.Settings.Viewport";
|
||
canvas.hCursor = LoadCursorW(nullptr, IDC_ARROW);
|
||
canvas.hbrBackground = GetSysColorBrush(COLOR_WINDOW);
|
||
RegisterClassW(&canvas);
|
||
HWND pane = CreateWindowExW(WS_EX_CONTROLPARENT, canvas.lpszClassName, L"",
|
||
WS_CHILD | WS_VISIBLE | WS_CLIPCHILDREN, 0, 0, 0, 0, w,
|
||
reinterpret_cast<HMENU>(SettingsViewport), app.instance, nullptr);
|
||
if (!pane)
|
||
{
|
||
DestroyWindow(w);
|
||
throw std::runtime_error("Cannot create settings viewport.");
|
||
}
|
||
v->viewport = pane;
|
||
SetPropW(pane, L"Font", GetPropW(w, L"Font"));
|
||
auto *layout = new WindowLayout{SettingsContentWidth, 0, 0, 0, true};
|
||
layout->childViewport = true;
|
||
layout->arranging = true;
|
||
SetPropW(pane, L"WindowLayout", layout);
|
||
SetWindowSubclass(pane, layoutProc, 2, 0);
|
||
enableWheelBatching(pane);
|
||
|
||
size_t first = 0, pageIndex = 0;
|
||
auto page = [&]
|
||
{
|
||
auto §ion = v->pages[pageIndex++];
|
||
section.first = first;
|
||
section.end = layout->controls.size();
|
||
for (size_t i = first; i < section.end; ++i)
|
||
{
|
||
auto &[child, bounds] = layout->controls[i];
|
||
ShowWindow(child, SW_HIDE);
|
||
OffsetRect(&bounds, 0, -48);
|
||
indexSettingsControl(*v, static_cast<int>(pageIndex - 1), child);
|
||
RECT actual{};
|
||
GetWindowRect(child, &actual); // Drop-down height does not count towards page height.
|
||
section.height = std::max(section.height, static_cast<int>(bounds.top) +
|
||
MulDiv(actual.bottom - actual.top, 96, GetDpiForWindow(pane)) + 20);
|
||
}
|
||
captureSettingsGeometry(*layout, first, pane);
|
||
first = section.end;
|
||
};
|
||
settingsGroupLabel(pane, L"Text conversion", 24, 68);
|
||
checkbox(pane, L"Con&vert recently typed text when nothing is selected", 201, 24, 110, 660);
|
||
checkbox(pane, L"Switch Windows input &layout after conversion", 202, 24, 146, 660);
|
||
checkbox(pane, L"Automatic correction (e&xperimental)", 207, 24, 182, 390);
|
||
settingsGroupLabel(pane, L"Windows integration", 24, 238);
|
||
checkbox(pane, L"Start with &Windows", 204, 24, 288, 660);
|
||
checkbox(pane, L"Start with Windows as ad&ministrator", 206, 24, 324, 660);
|
||
checkbox(pane, L"&Keep screen awake", 205, 24, 360, 660);
|
||
page();
|
||
|
||
settingsGroupLabel(pane, L"Default language cycle", 24, 68);
|
||
control(pane, L"LISTBOX", L"", WS_TABSTOP | WS_VSCROLL | LBS_NOTIFY | LBS_NOINTEGRALHEIGHT | WS_BORDER,
|
||
220, 24, 108, 410, 240);
|
||
button(pane, L"Move u&p", 232, 454, 108, 110);
|
||
button(pane, L"Move &down", 233, 574, 108, 110);
|
||
checkbox(pane, L"&Include in cycle", 230, 454, 154, 230);
|
||
label(pane, L"Direct layout shortcut", 454, 206, 230);
|
||
hotkeyEdit(app, pane, 231, 454, 234, 230);
|
||
label(pane, L"Backspace / Delete clears it", 454, 270, 230);
|
||
button(pane, L"Re&fresh layouts", 253, 454, 322, 230);
|
||
button(pane, L"Languages for a &chat...", 259, 24, 378, 230);
|
||
button(pane, L"Languages for &applications...", 263, 272, 378, 300);
|
||
page();
|
||
|
||
settingsGroupLabel(pane, L"Keyboard shortcuts", 24, 68);
|
||
for (int i = 0; i < static_cast<int>(std::size(shortcutNames)); ++i)
|
||
{
|
||
const int y = 48 + ShortcutFirstRow + i * ShortcutRowHeight;
|
||
label(pane, shortcutNames[i], SettingsFormMargin, y + 4, 180);
|
||
hotkeyEdit(app, pane, 210 + i, ShortcutFieldLeft, y, ShortcutRight - ShortcutFieldLeft);
|
||
}
|
||
checkbox(pane, L"Open editor after screen capt&ure", 209, SettingsFormMargin, ShortcutCheckboxTop + 48,
|
||
ShortcutRight - SettingsFormMargin);
|
||
page();
|
||
|
||
checkbox(pane, L"Record clip&board history", 203, 24, 80, 660);
|
||
settingsGroupLabel(pane, L"History limits", 24, 126);
|
||
label(pane, L"Items", 24, 176, 180);
|
||
edit(pane, 240, 24, 204, 200);
|
||
label(pane, L"Total MiB", 254, 176, 180);
|
||
edit(pane, 241, 254, 204, 200);
|
||
label(pane, L"Per item MiB", 484, 176, 180);
|
||
edit(pane, 242, 484, 204, 200);
|
||
button(pane, L"Clear &history...", 254, 24, 258, 200);
|
||
label(pane, L"Exclude applications (process names, comma-separated)", 24, 330, 660);
|
||
edit(pane, 243, 24, 362, 660);
|
||
button(pane, L"OCR op&tions...", 257, 24, 394, 200);
|
||
page();
|
||
|
||
v->snippets = {&app, app.settings.snippets, app.settings.snippets};
|
||
createSnippetEditor(pane, &v->snippets, true);
|
||
page();
|
||
|
||
createMousePage(w, *v);
|
||
page();
|
||
|
||
page();
|
||
|
||
label(pane, L"Use the same pairing code on both computers.", 24, 68, 660);
|
||
page();
|
||
|
||
settingsGroupLabel(pane, L"Diagnostic log", 24, 68);
|
||
checkbox(pane, L"Write lo&g", 208, 24, 104, 210);
|
||
button(pane, L"View l&og...", 256, 24, 142, 210);
|
||
page();
|
||
|
||
settingsGroupLabel(pane, L"Codex configuration", 24, 68);
|
||
label(pane, L"Paste this block into ~/.codex/config.toml to connect Codex to KSwitcher.", 24, 108, 660);
|
||
edit(pane, 281, 24, 140, 660, 108, ES_MULTILINE | ES_READONLY | ES_AUTOHSCROLL | WS_HSCROLL | WS_BORDER);
|
||
const auto server = std::filesystem::path(executable()).parent_path() / L"KSwitcher.Config.exe";
|
||
value(pane, 281, L"[mcp_servers.kswitcher]\r\ncommand = " +
|
||
wide(nlohmann::json(utf8(server.wstring())).dump()) + L"\r\nargs = [\"--mcp\"]\r\n");
|
||
label(pane, L"Select text and press Ctrl+C, or copy the entire block below.", 24, 258, 660);
|
||
button(pane, L"&Copy configuration", 282, 24, 288, 190);
|
||
control(pane, L"STATIC", L"", 0, 283, 24, 322, 660, 24);
|
||
label(pane, L"For remote logs, enable diagnostic log downloads on the paired computer.", 24, 354, 660);
|
||
page();
|
||
|
||
v->lan = createLanSettings(pane, app);
|
||
layout->controls.push_back({v->lan, {8, 55, 8 + LanSettingsWidth, 55 + LanSettingsHeight}});
|
||
for (HWND child = GetWindow(v->lan, GW_CHILD); child; child = GetWindow(child, GW_HWNDNEXT))
|
||
indexSettingsControl(*v, ManageComputersPage, child);
|
||
page();
|
||
|
||
page(); // Correction options groups the five child pages.
|
||
|
||
checkbox(pane, L"E&nglish", 401, 24, 68, 212);
|
||
checkbox(pane, L"&Ukrainian", 402, 244, 68, 212);
|
||
checkbox(pane, L"Russ&ian", 403, 464, 68, 212);
|
||
label(pane, L"Only languages in your layout cycle are used.", 24, 104, 660);
|
||
label(pane, L"Frequency rank limit (0 = entire dictionary)", 24, 156, 390);
|
||
edit(pane, 406, 420, 152, 122, 26, ES_NUMBER);
|
||
label(pane, L"Minimum word length (1–32 letters)", 24, 196, 390);
|
||
edit(pane, 410, 420, 192, 122, 26, ES_NUMBER);
|
||
checkbox(pane, L"Correct spelling &typos using dictionaries (experimental)", 415, 24, 246, 660);
|
||
label(pane, L"Single edits, 4+ letters; ambiguous words are left unchanged.", 24, 276, 660);
|
||
button(pane, L"Open dictionary &folder", 407, 24, 326, 220);
|
||
page();
|
||
|
||
constexpr DWORD multiline = ES_MULTILINE | WS_VSCROLL | ES_AUTOVSCROLL;
|
||
label(pane, L"Excluded applications (process names, comma-separated)", 24, 68, 660);
|
||
edit(pane, 404, 24, 94, 660, 132, multiline);
|
||
label(pane, L"Never correct these words (comma-separated)", 24, 248, 660);
|
||
edit(pane, 405, 24, 274, 660, 132, multiline);
|
||
page();
|
||
|
||
for (const auto &[id, language] : {std::pair{411, L"English"}, {412, L"Ukrainian"}, {413, L"Russian"}})
|
||
{
|
||
const int y = 68 + (id - 411) * 138;
|
||
label(pane, language, 24, y, 660);
|
||
edit(pane, id, 24, y + 26, 660, 100, multiline | ES_WANTRETURN);
|
||
}
|
||
page();
|
||
|
||
label(pane, L"Characters before a word", 24, 68, 322);
|
||
label(pane, L"Characters after a word", 362, 68, 322);
|
||
edit(pane, 408, 24, 94, 322);
|
||
edit(pane, 409, 362, 94, 322);
|
||
label(pane, L"Enter punctuation without spaces or separators.", 24, 138, 660);
|
||
page();
|
||
|
||
checkbox(pane, L"Use custom re&placements", 414, 24, 68, 660);
|
||
label(pane, L"One pair per line: typo=correction (same language; correction may contain spaces)", 24, 106, 660);
|
||
edit(pane, 416, 24, 132, 660, 248, multiline | ES_WANTRETURN);
|
||
page();
|
||
|
||
v->sync = createSyncSettings(pane, app);
|
||
layout->controls.push_back({v->sync, {8, 55, 8 + SyncSettingsWidth, 55 + SyncSettingsHeight}});
|
||
for (HWND child = GetWindow(v->sync, GW_CHILD); child; child = GetWindow(child, GW_HWNDNEXT))
|
||
indexSettingsControl(*v, OpenBaoPage, child);
|
||
page();
|
||
|
||
v->splitter = control(w, L"STATIC", L"Resize navigation pane", SS_NOTIFY | WS_TABSTOP,
|
||
SettingsSplitter, 0, 0, 0, 0);
|
||
SetWindowSubclass(v->splitter, settingsSplitterProc, 1, reinterpret_cast<DWORD_PTR>(v));
|
||
control(w, L"STATIC", L"No unsaved settings.", SS_ENDELLIPSIS, SettingsStatus, 0, 0, 0, 0);
|
||
button(w, L"Impo&rt...", 250, 0, 0);
|
||
button(w, L"&Export...", 251, 0, 0);
|
||
button(w, L"&Apply", SettingsApply, 0, 0);
|
||
button(w, L"&Save", IDOK, 0, 0);
|
||
button(w, L"&Close", IDCANCEL, 0, 0);
|
||
|
||
layout->arranging = false;
|
||
setSettingsFonts(w, *v, GetDpiForWindow(w));
|
||
refreshSettingsColors(w, *v);
|
||
layoutSettings(w, *v);
|
||
fillSettings(w, v);
|
||
v->ready = true;
|
||
updateSettingsState(w, v);
|
||
rebuildSettingsNavigation(w, *v);
|
||
navigateSettings(*v, savedWindow.page);
|
||
if (visible)
|
||
{
|
||
showRequestedWindow(w);
|
||
if (savedWindow.maximized) ShowWindow(w, SW_MAXIMIZE);
|
||
activateWindow(w);
|
||
SetFocus(v->navigation);
|
||
}
|
||
}
|
||
void showSnippets(App &app)
|
||
{
|
||
if (app.settingsWindow)
|
||
{
|
||
HWND w = app.settingsWindow;
|
||
HWND target = IsWindowEnabled(w) ? w : GetLastActivePopup(w);
|
||
navigateSettings(*reinterpret_cast<SettingsView *>(GetWindowLongPtrW(w, GWLP_USERDATA)), SnippetsPage);
|
||
activateWindow(target);
|
||
return;
|
||
}
|
||
if (app.snippetsWindow)
|
||
{
|
||
SetForegroundWindow(app.snippetsWindow);
|
||
return;
|
||
}
|
||
HWND w = makeWindow(app, L"KSwitcher.Snippets", L"Text snippets", snippetProc, 720, 565);
|
||
app.snippetsWindow = w;
|
||
createSnippetEditor(w, reinterpret_cast<SnippetView *>(GetWindowLongPtrW(w, GWLP_USERDATA)), false);
|
||
showRequestedWindow(w);
|
||
SetForegroundWindow(w);
|
||
}
|
||
#else
|
||
void showSettings(App &app, bool) { launchConfiguration(app); }
|
||
void showSnippets(App &app) { launchConfiguration(app, true); }
|
||
#endif
|
||
#ifndef KS_CONFIG_APP
|
||
void showShortcuts(App &app)
|
||
{
|
||
auto &s = app.settings;
|
||
std::wstring text = L"Next layout: " + s.toggle + L"\nChange case: " + s.casing + L"\nTransliterate: " +
|
||
s.translit + L"\nUndo: " + s.undo + L"\nClipboard history: " + s.clipboard +
|
||
L"\nScreen capture: " + s.screenshot + L"\nOpen KSwitcher Files: " + s.filesHotkey.value_or(L"") + L"\n";
|
||
for (size_t i = 0; i < std::min(app.layouts.size(), s.direct.size()); ++i)
|
||
if (!s.direct[i].empty())
|
||
text += L"\n" + app.layouts[i].name + L": " + s.direct[i];
|
||
text += L"\n\nHistory: Enter to paste, Shift+Enter for plain text,\nCtrl+1…9 to paste, Ctrl+P to pin, "
|
||
L"Delete to remove,\nCtrl+O to open the full item, Escape to close.";
|
||
MessageBoxW(app.window, text.c_str(), L"Keyboard shortcuts", MB_OK);
|
||
}
|
||
void showEntry(App &app, const std::wstring &id)
|
||
{
|
||
try
|
||
{
|
||
auto clip = app.history->load(id);
|
||
if(std::any_of(clip.formats.begin(),clip.formats.end(),[](const auto &format) {
|
||
return format.id==CF_DIB || format.id==CF_DIBV5 || format.name==L"PNG";
|
||
})) {
|
||
launchScreenshotEditor(app,clip);
|
||
return;
|
||
}
|
||
auto text = clip.text();
|
||
if (text.empty())
|
||
{
|
||
MessageBoxW(app.historyWindow,
|
||
L"This item contains files. Paste it into the "
|
||
L"destination application.",
|
||
L"Clipboard item", MB_OK);
|
||
return;
|
||
}
|
||
HWND w = makeWindow(app, L"KSwitcher.Entry", L"Clipboard item", entryProc, 720, 500,
|
||
WS_THICKFRAME | WS_MAXIMIZEBOX);
|
||
if (app.historyService) ++app.historyEntryWindows;
|
||
auto field = edit(w, 1, 10, 10, 700, 480, ES_MULTILINE | ES_READONLY | ES_AUTOVSCROLL | WS_VSCROLL);
|
||
SetWindowTextW(field, text.c_str());
|
||
showRequestedWindow(w);
|
||
}
|
||
catch (const std::exception &e)
|
||
{
|
||
error(app.historyWindow, e);
|
||
}
|
||
}
|
||
#endif
|
||
} // namespace ks
|