596 lines
31 KiB
C++
596 lines
31 KiB
C++
// Uses the resident service; the configurator never opens a discovery socket.
|
|
struct LanView
|
|
{
|
|
HWND owner{};
|
|
App *app{};
|
|
nlohmann::json snapshot=nlohmann::json::object();
|
|
nlohmann::json saved, draft = nlohmann::json::object();
|
|
std::vector<std::string> ids;
|
|
std::wstring error;
|
|
std::wstring layoutError;
|
|
std::string dragPeer;POINT dragStart{},dragPoint{};bool dragMoved{};
|
|
std::string gridState;
|
|
std::vector<std::wstring> rows;
|
|
std::string logRequest;
|
|
std::filesystem::path logDestination;
|
|
std::wstring logMessage;
|
|
};
|
|
nlohmann::json lanRequest(App &app,const nlohmann::json &request)
|
|
{
|
|
auto text=request.dump(); auto reply=app.lanCommand(Bytes(text.begin(),text.end()));
|
|
return nlohmann::json::parse(reply);
|
|
}
|
|
void stageLanValue(LanView &v, const char *key, const nlohmann::json &value)
|
|
{
|
|
if (value == v.saved.at(key)) v.draft.erase(key);
|
|
else v.draft[key] = value;
|
|
}
|
|
void refreshLanFooter(LanView &v)
|
|
{
|
|
updateSettingsState(v.owner, reinterpret_cast<SettingsView *>(GetWindowLongPtrW(v.owner, GWLP_USERDATA)));
|
|
}
|
|
std::string selectedLan(HWND w,LanView &v)
|
|
{
|
|
auto index=SendDlgItemMessageW(w,702,LB_GETCURSEL,0,0);
|
|
return index>=0 && size_t(index)<v.ids.size() ? v.ids[size_t(index)] : "";
|
|
}
|
|
std::filesystem::path pickLanFile(HWND owner, bool save, const wchar_t *suggestion=L"",
|
|
const wchar_t *filter=L"All files\0*.*\0")
|
|
{
|
|
wchar_t path[32768]{};
|
|
wcsncpy_s(path,suggestion,_TRUNCATE);
|
|
OPENFILENAMEW dialog{sizeof(dialog)};
|
|
dialog.hwndOwner=owner;
|
|
dialog.lpstrFilter=filter;
|
|
dialog.lpstrFile=path;
|
|
dialog.nMaxFile=std::size(path);
|
|
dialog.Flags=OFN_EXPLORER|OFN_NOCHANGEDIR|OFN_PATHMUSTEXIST|(save?OFN_OVERWRITEPROMPT:OFN_FILEMUSTEXIST);
|
|
if(save?GetSaveFileNameW(&dialog):GetOpenFileNameW(&dialog))return path;
|
|
return {};
|
|
}
|
|
|
|
struct LanClientsView
|
|
{
|
|
LanView *lan{};
|
|
nlohmann::json entries, saved;
|
|
};
|
|
void selectLanClient(HWND window, const LanClientsView &view, LRESULT index)
|
|
{
|
|
const bool selected = index >= 0 && size_t(index) < view.entries.size();
|
|
EnableWindow(GetDlgItem(window, 734), selected);
|
|
EnableWindow(GetDlgItem(window, 736), selected);
|
|
EnableWindow(GetDlgItem(window, 737), selected);
|
|
for (const auto &[id, key] : {std::pair{736, "writeFiles"}, std::pair{737, "deleteFiles"}})
|
|
SendDlgItemMessageW(window, id, BM_SETCHECK,
|
|
selected && view.entries[size_t(index)].value(key, false) ? BST_CHECKED : BST_UNCHECKED, 0);
|
|
}
|
|
void refreshLanClients(HWND window, LanClientsView &view)
|
|
{
|
|
view.entries = view.saved;
|
|
for (const auto &change : view.lan->draft.value("clients", nlohmann::json::object()))
|
|
{
|
|
const auto &path = change.at("path");
|
|
std::erase_if(view.entries.get_ref<nlohmann::json::array_t &>(),
|
|
[&](const auto &entry) { return entry.at("path") == path; });
|
|
if (change.at("action") == "trustClient") view.entries.push_back(change);
|
|
}
|
|
SendDlgItemMessageW(window, 732, LB_RESETCONTENT, 0, 0);
|
|
for (const auto &entry : view.entries)
|
|
{
|
|
auto path = wide(entry.at("path").get<std::string>());
|
|
if (path.starts_with(L"\\\\?\\UNC\\")) path = L"\\\\" + path.substr(8);
|
|
else if (path.starts_with(L"\\\\?\\")) path.erase(0, 4);
|
|
SendDlgItemMessageW(window, 732, LB_ADDSTRING, 0, reinterpret_cast<LPARAM>(path.c_str()));
|
|
const auto width = scale(window, int(path.size()) * 9);
|
|
if (width > SendDlgItemMessageW(window, 732, LB_GETHORIZONTALEXTENT, 0, 0))
|
|
SendDlgItemMessageW(window, 732, LB_SETHORIZONTALEXTENT, width, 0);
|
|
}
|
|
selectLanClient(window, view, LB_ERR);
|
|
}
|
|
LRESULT CALLBACK lanClientsProc(HWND window, UINT msg, WPARAM wp, LPARAM lp)
|
|
{
|
|
auto *view = reinterpret_cast<LanClientsView *>(GetWindowLongPtrW(window, GWLP_USERDATA));
|
|
if (msg == WM_DPICHANGED) { resizeForDpi(window, wp, lp); return 0; }
|
|
if (msg == WM_CLOSE || (msg == WM_COMMAND && LOWORD(wp) == IDCANCEL))
|
|
{
|
|
DestroyWindow(window);
|
|
return 0;
|
|
}
|
|
if (msg == WM_DESTROY)
|
|
{
|
|
const auto parent = GetWindow(window, GW_OWNER);
|
|
EnableWindow(parent, TRUE);
|
|
SetForegroundWindow(parent);
|
|
delete view;
|
|
return 0;
|
|
}
|
|
if (view && msg == WM_COMMAND)
|
|
{
|
|
const auto id = LOWORD(wp);
|
|
const auto index = SendDlgItemMessageW(window, 732, LB_GETCURSEL, 0, 0);
|
|
if (id == 732 && HIWORD(wp) == LBN_SELCHANGE)
|
|
{
|
|
selectLanClient(window, *view, index);
|
|
return 0;
|
|
}
|
|
try
|
|
{
|
|
if (id == 733)
|
|
{
|
|
const auto path = pickLanFile(window, false, L"", L"Windows executables (*.exe)\0*.exe\0");
|
|
if (!path.empty() && MessageBoxW(window,
|
|
(L"Allow this application to browse and download files from paired computers?\n\n" + path.wstring()).c_str(),
|
|
L"Trust a LAN client", MB_YESNO | MB_DEFBUTTON2 | MB_ICONQUESTION) == IDYES)
|
|
{
|
|
const auto entry = lanRequest(*view->lan->app, {{"action", "inspectClient"}, {"path", utf8(path.wstring())}});
|
|
const auto canonical = entry.at("path").get<std::string>();
|
|
const auto key = utf8(lower(wide(canonical)));
|
|
auto &changes = view->lan->draft["clients"];
|
|
if (std::none_of(view->saved.begin(), view->saved.end(), [&](const auto &saved) {
|
|
return saved.at("path") == entry.at("path") && saved.at("sha256") == entry.at("sha256");
|
|
}))
|
|
changes[key] = {{"action", "trustClient"}, {"path", canonical}, {"sha256", entry.at("sha256")}};
|
|
else if (changes.is_object()) changes.erase(key);
|
|
if (changes.empty()) view->lan->draft.erase("clients");
|
|
refreshLanFooter(*view->lan);
|
|
refreshLanClients(window, *view);
|
|
}
|
|
return 0;
|
|
}
|
|
if ((id == 736 || id == 737) && index >= 0 && size_t(index) < view->entries.size())
|
|
{
|
|
auto entry = view->entries[size_t(index)];
|
|
const auto *permission = id == 736 ? "writeFiles" : "deleteFiles";
|
|
const auto checked = SendDlgItemMessageW(window, id, BM_GETCHECK, 0, 0) == BST_CHECKED;
|
|
if (checked && MessageBoxW(window, id == 736 ?
|
|
L"Allow this executable to create, rename, copy and overwrite files on paired computers?" :
|
|
L"Allow this executable to recycle and permanently delete files on paired computers?",
|
|
L"Change trusted client permissions", MB_YESNO | MB_DEFBUTTON2 | MB_ICONQUESTION) != IDYES)
|
|
{
|
|
selectLanClient(window, *view, index);
|
|
return 0;
|
|
}
|
|
entry["action"] = "trustClient";
|
|
entry[permission] = checked;
|
|
const auto key = utf8(lower(wide(entry.at("path").get<std::string>())));
|
|
view->lan->draft["clients"][key] = entry;
|
|
view->entries[size_t(index)] = std::move(entry);
|
|
refreshLanFooter(*view->lan);
|
|
return 0;
|
|
}
|
|
if (id == 734 && index >= 0 && size_t(index) < view->entries.size())
|
|
{
|
|
const auto path = view->entries[size_t(index)].at("path").get<std::string>();
|
|
const auto key = utf8(lower(wide(path)));
|
|
auto &changes = view->lan->draft["clients"];
|
|
if (std::any_of(view->saved.begin(), view->saved.end(), [&](const auto &entry) { return entry.at("path") == path; }))
|
|
changes[key] = {{"action", "removeClient"}, {"path", path}};
|
|
else changes.erase(key);
|
|
if (changes.empty()) view->lan->draft.erase("clients");
|
|
refreshLanFooter(*view->lan);
|
|
refreshLanClients(window, *view);
|
|
return 0;
|
|
}
|
|
}
|
|
catch (const std::exception &error)
|
|
{
|
|
MessageBoxW(window, wide(error.what()).c_str(), L"Trusted clients", MB_OK | MB_ICONERROR);
|
|
return 0;
|
|
}
|
|
}
|
|
return DefWindowProcW(window, msg, wp, lp);
|
|
}
|
|
void showLanClients(HWND parent, LanView &lan)
|
|
{
|
|
auto window = makeWindow(*lan.app, L"KSwitcher.LAN.Clients", L"Trusted clients", lanClientsProc, 610, 318, 0, false);
|
|
SetWindowLongPtrW(window, GWLP_HWNDPARENT, reinterpret_cast<LONG_PTR>(parent));
|
|
auto view = new LanClientsView{&lan};
|
|
SetWindowLongPtrW(window, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(view));
|
|
label(window, L"Trusted executables can browse and download files from paired computers.", 16, 14, 578);
|
|
control(window, L"LISTBOX", L"", WS_TABSTOP | WS_VSCROLL | WS_HSCROLL | WS_BORDER | LBS_NOTIFY |
|
|
LBS_NOINTEGRALHEIGHT, 732, 16, 42, 578, 152);
|
|
control(window, L"BUTTON", L"Allow &write", WS_TABSTOP | BS_AUTOCHECKBOX, 736, 16, 200, 150, 26);
|
|
control(window, L"BUTTON", L"Allow &delete", WS_TABSTOP | BS_AUTOCHECKBOX, 737, 182, 200, 150, 26);
|
|
label(window, L"Move requires both permissions. Click Apply or Save in Settings.", 16, 232, 578);
|
|
button(window, L"&Add client…", 733, 16, 271, 126);
|
|
button(window, L"&Remove", 734, 150, 271, 110);
|
|
button(window, L"&Close", IDCANCEL, 494, 271, 100);
|
|
try
|
|
{
|
|
view->saved = lanRequest(*lan.app, {{"action", "trustedClients"}});
|
|
refreshLanClients(window, *view);
|
|
}
|
|
catch (...) { DestroyWindow(window); throw; }
|
|
EnableWindow(parent, FALSE);
|
|
showRequestedWindow(window);
|
|
SetForegroundWindow(window);
|
|
}
|
|
LRESULT CALLBACK lanHelpProc(HWND w,UINT msg,WPARAM wp,LPARAM lp)
|
|
{
|
|
if(msg==WM_DPICHANGED){resizeForDpi(w,wp,lp);return 0;}
|
|
if(msg==WM_COMMAND&&LOWORD(wp)==724){SendDlgItemMessageW(w,723,EM_SETSEL,0,-1);SendDlgItemMessageW(w,723,WM_COPY,0,0);value(w,724,L"Copied");return 0;}
|
|
if(msg==WM_CLOSE||(msg==WM_COMMAND&&LOWORD(wp)==IDCANCEL)){DestroyWindow(w);return 0;}
|
|
if(msg==WM_DESTROY){auto parent=GetWindow(w,GW_OWNER);EnableWindow(parent,TRUE);SetForegroundWindow(parent);return 0;}
|
|
return DefWindowProcW(w,msg,wp,lp);
|
|
}
|
|
void showLanHelp(HWND parent,App &app)
|
|
{
|
|
auto script=wide(lanRequest(app,{{"action","connectionHelp"}}).at("script").get<std::string>());
|
|
auto w=makeWindow(app,L"KSwitcher.LAN.Help",L"KSwitcher — connection help",lanHelpProc,740,430,0,false);
|
|
SetWindowLongPtrW(w,GWLP_HWNDPARENT,(LONG_PTR)parent);
|
|
control(w,L"STATIC",L"First enable input sharing on both PCs. KSwitcher tries direct TCP, reverse TCP, then encrypted UDP automatically. Both PCs need an updated version for all three methods.",0,725,18,16,700,60);
|
|
control(w,L"STATIC",L"Still disconnected? A firewall may be blocking the app. On EACH PC, open this help and run its own command in PowerShell as administrator. This allows only local-network connections to that PC's current KSwitcher executable. No restart or new pairing is needed.",0,726,18,88,700,80);
|
|
auto field=edit(w,723,18,180,700,180,ES_MULTILINE|ES_READONLY|ES_AUTOVSCROLL|WS_VSCROLL);
|
|
SetWindowTextW(field,script.c_str());
|
|
button(w,L"&Copy command",724,18,380,180);button(w,L"&Close",IDCANCEL,618,380,100);
|
|
EnableWindow(parent,FALSE);showRequestedWindow(w);SetForegroundWindow(w);
|
|
}
|
|
void refreshLan(HWND w,LanView &v)
|
|
{
|
|
if(!v.logRequest.empty())
|
|
{
|
|
auto reply=lanRequest(*v.app,{{"action","takeLog"},{"request",v.logRequest}});
|
|
auto state=reply.at("state").get<std::string>();
|
|
if(state!="waiting")
|
|
{
|
|
if(state=="ready")
|
|
{
|
|
v.logRequest.clear();
|
|
v.logMessage.clear();
|
|
atomicWrite(v.logDestination,decodeLanLog(reply.at("logHex")));
|
|
v.logMessage=L"Diagnostic log saved.";
|
|
}
|
|
else if(state=="denied")v.logMessage=L"Remote diagnostic downloads are disabled on that PC.";
|
|
else if(state=="unavailable")v.logMessage=L"The selected log is unavailable on that PC.";
|
|
else v.logMessage=L"The remote log download timed out.";
|
|
v.logRequest.clear();
|
|
}
|
|
}
|
|
auto selected=selectedLan(w,v);
|
|
auto next=lanRequest(*v.app,{{"action","status"}});
|
|
v.saved = next;
|
|
for (const auto *key : {"enabled", "shareInput", "shareLogs"})
|
|
if (v.draft.contains(key)) next[key] = v.draft.at(key);
|
|
next["positions"].update(v.draft.value("positions", nlohmann::json::object()));
|
|
const auto forgotten = v.draft.value("forget", nlohmann::json::object());
|
|
for (const auto &[peer, ignored] : forgotten.items())
|
|
{
|
|
next["positions"].erase(peer);
|
|
for (auto &entry : next["peers"])
|
|
if (entry.at("id") == peer) entry["paired"] = false;
|
|
}
|
|
if (next["positions"].empty()) next["shareInput"] = false;
|
|
if(selected.empty())
|
|
{
|
|
std::string onlyPaired;size_t pairedCount=0;
|
|
for(const auto &peer:next["peers"])if(peer.value("paired",false))
|
|
{onlyPaired=peer.at("id").get<std::string>();++pairedCount;}
|
|
if(pairedCount==1)selected=onlyPaired;
|
|
}
|
|
std::vector<std::string> ids;
|
|
std::vector<std::wstring> rows;
|
|
for(const auto &peer:next["peers"])
|
|
{
|
|
auto id=peer.at("id").get<std::string>();ids.push_back(id);
|
|
const bool online = peer.value("online", false);
|
|
const bool paired = peer.value("paired", false);
|
|
const auto state = paired ? (online ? L"Paired · online" : L"Paired · offline") :
|
|
(online ? L"Available to pair" : L"Offline");
|
|
rows.push_back(wide(peer.at("name").get<std::string>()) + L" [" + wide(id.substr(0,8)) + L"] — " + state);
|
|
}
|
|
// Presence/challenge refreshes must not repaint or reset the pairing list.
|
|
if(v.ids!=ids||v.rows!=rows)
|
|
{
|
|
SendDlgItemMessageW(w,702,WM_SETREDRAW,FALSE,0);
|
|
SendDlgItemMessageW(w,702,LB_RESETCONTENT,0,0); v.ids=std::move(ids);v.rows=std::move(rows);
|
|
for(size_t i=0;i<v.ids.size();++i)
|
|
{
|
|
auto row=SendDlgItemMessageW(w,702,LB_ADDSTRING,0,(LPARAM)v.rows[i].c_str());
|
|
if(v.ids[i]==selected) SendDlgItemMessageW(w,702,LB_SETCURSEL,row,0);
|
|
}
|
|
SendDlgItemMessageW(w,702,WM_SETREDRAW,TRUE,0); InvalidateRect(GetDlgItem(w,702),nullptr,TRUE);
|
|
}
|
|
for(size_t i=0;i<v.ids.size();++i)if(v.ids[i]==selected)
|
|
SendDlgItemMessageW(w,702,LB_SETCURSEL,i,0);
|
|
selected=selectedLan(w,v);
|
|
// Keep the code available while the user enters it on the other PC, and
|
|
// after cancellation/timeout for retry. Clear it only after trust is saved.
|
|
if(v.snapshot.value("pending",false))
|
|
for(const auto &peer:next["peers"])
|
|
if(peer.at("id")==v.snapshot.value("pendingPeer",std::string{})&&peer.value("paired",false))value(w,703,L"");
|
|
v.snapshot=std::move(next);
|
|
bool enabled=v.snapshot.at("enabled"), pending=v.snapshot.at("pending"), online=false, paired=false;
|
|
for(const auto &peer:v.snapshot["peers"]) if(peer.at("id")==selected) {online=peer.at("online");paired=peer.at("paired");}
|
|
bool reflow = false;
|
|
auto setStatus = [&](int id, const std::wstring &text)
|
|
{
|
|
if (value(w, id) == text) return;
|
|
value(w, id, text);
|
|
reflow = true;
|
|
};
|
|
setStatus(701,enabled ? L"&Disable discovery" : L"&Enable discovery");
|
|
setStatus(709,L"This PC: "+wide(v.snapshot.at("name").get<std::string>())+L" ["+wide(v.snapshot.at("id").get<std::string>().substr(0,8))+L"]");
|
|
auto pairingStatus=wide(v.snapshot.at("status").get<std::string>());
|
|
if(pending)
|
|
{
|
|
std::wstring peerName;
|
|
for(const auto &peer:v.snapshot["peers"])
|
|
if(peer.at("id")==v.snapshot.value("pendingPeer",std::string{}))peerName=wide(peer.at("name").get<std::string>());
|
|
pairingStatus=L"Waiting for "+peerName+L" ("+std::to_wstring(v.snapshot.value("pairSecondsRemaining",0))+L" s).\nEnter the same code and click Pair, then Apply or Save on the other PC.";
|
|
}
|
|
if (v.draft.contains("enabled"))
|
|
pairingStatus = enabled ? L"Click Apply or Save to enable discovery." : L"Click Apply or Save to disable discovery.";
|
|
if (v.draft.contains("pair")) pairingStatus = L"Click Apply or Save to start pairing on this PC.";
|
|
setStatus(708,v.error.empty() ? pairingStatus : v.error);
|
|
setStatus(705,pending ? L"Waiting..." : L"&Pair");
|
|
const wchar_t *peerStatus=L"Select the name and ID shown on the other PC.";
|
|
if(v.ids.empty()) peerStatus=enabled?L"No computers found. Enable discovery on both PCs and allow UDP 45883.":
|
|
L"Discovery is disabled on this computer.";
|
|
else if(paired)
|
|
{
|
|
const bool connected=v.snapshot.value("inputReady",nlohmann::json::object()).contains(selected);
|
|
peerStatus=connected?L"Pair saved — input connected":
|
|
!v.snapshot.value("shareInput",false)?L"Pair saved — input disabled here":
|
|
!online?L"Pair saved — computer offline":L"Pair saved — input not connected";
|
|
}
|
|
setStatus(710,forgotten.contains(selected) ? L"Click Apply or Save to remove this pair." : peerStatus);
|
|
EnableWindow(GetDlgItem(w,705),v.saved.at("enabled").get<bool>()&&enabled&&online&&!pending&&!v.draft.contains("pair")&&!forgotten.contains(selected)&&!paired);
|
|
EnableWindow(GetDlgItem(w,706),pending || v.draft.contains("pair"));
|
|
EnableWindow(GetDlgItem(w,707),paired);
|
|
bool canDownloadLogs=false;
|
|
for(const auto &peer:v.snapshot["peers"])
|
|
if(peer.at("id")==selected)canDownloadLogs=paired&&peer.value("verified",false)&&peer.value("fileTransfer",false);
|
|
EnableWindow(GetDlgItem(w,727),canDownloadLogs&&v.logRequest.empty());
|
|
EnableWindow(GetDlgItem(w,728),canDownloadLogs&&v.logRequest.empty());
|
|
CheckDlgButton(w,729,v.snapshot.value("shareLogs",false)?BST_CHECKED:BST_UNCHECKED);
|
|
if (value(w, 731) != v.logMessage)
|
|
{
|
|
value(w, 731, v.logMessage);
|
|
ShowWindow(GetDlgItem(w, 731), v.logMessage.empty() ? SW_HIDE : SW_SHOWNA);
|
|
reflow = true;
|
|
}
|
|
for(int id:{703,704}) EnableWindow(GetDlgItem(w,id),v.saved.at("enabled").get<bool>()&&enabled&&!pending&&!v.draft.contains("pair")&&!paired);
|
|
auto positions=v.snapshot.value("positions",nlohmann::json::object());
|
|
EnableWindow(GetDlgItem(w,715),enabled&&!positions.empty()&&!v.snapshot.value("shareInput",false));
|
|
EnableWindow(GetDlgItem(w,716),v.snapshot.value("shareInput",false));
|
|
auto gridState=positions.dump()+v.snapshot["peers"].dump()+selected+v.snapshot.value("controlPeer",std::string{})+v.snapshot.value("inputReady",nlohmann::json::object()).dump()+(v.snapshot.value("shareInput",false)?"1":"0");
|
|
if(gridState!=v.gridState){v.gridState=std::move(gridState);InvalidateRect(GetDlgItem(w,721),nullptr,FALSE);}
|
|
auto inputStatus=wide(v.snapshot.value("inputStatus",std::string("Input sharing disabled.")));
|
|
if(!v.snapshot.value("shareInput",false))
|
|
inputStatus=!enabled ? L"Enable discovery to set up mouse and keyboard sharing." :
|
|
selected.empty() ? L"Select a computer in the pairing list to enable input." :
|
|
!paired ? L"Pair the selected computer first." :
|
|
L"Arrange the monitors, then enable input sharing on all PCs.";
|
|
auto mode=v.snapshot.value("controlMode",0);
|
|
if(mode==2)inputStatus=L"Mouse and keyboard control the OTHER PC. Ctrl+Alt+Esc returns here.";
|
|
else if(mode==3)inputStatus=L"This PC is controlled remotely. Local physical input takes control back.";
|
|
if (v.draft.contains("shareInput"))
|
|
inputStatus = L"Click Apply or Save to apply input sharing changes.";
|
|
setStatus(718,v.layoutError.empty() ? inputStatus : v.layoutError);
|
|
setStatus(722,v.snapshot.value("inputNeedsHelp",false)?L"Connection failed — &help":L"Connection &help");
|
|
if (reflow && IsWindowVisible(w))
|
|
{
|
|
arrangeWindow(GetParent(w));
|
|
arrangeWindow(w);
|
|
}
|
|
}
|
|
#include "ui_lan_layout.inl"
|
|
LRESULT CALLBACK lanProc(HWND w,UINT msg,WPARAM wp,LPARAM lp)
|
|
{
|
|
if (msg == WM_SIZE) arrangeWindow(w);
|
|
auto v=(LanView*)GetWindowLongPtrW(w,GWLP_USERDATA);
|
|
if(!v) return DefWindowProcW(w,msg,wp,lp);
|
|
if (msg == WM_NCDESTROY)
|
|
{
|
|
KillTimer(w, 1);
|
|
delete windowLayoutState(w);
|
|
RemovePropW(w, L"WindowLayout");
|
|
delete v;
|
|
SetWindowLongPtrW(w, GWLP_USERDATA, 0);
|
|
return DefWindowProcW(w, msg, wp, lp);
|
|
}
|
|
if (msg == WM_CTLCOLORSTATIC)
|
|
return SendMessageW(GetParent(w), msg, wp, lp);
|
|
if (msg == WM_PAINT)
|
|
{
|
|
paintSettingsMatches(w);
|
|
return 0;
|
|
}
|
|
try
|
|
{
|
|
if (msg == WM_SHOWWINDOW)
|
|
{
|
|
if (wp)
|
|
{
|
|
SetTimer(w, 1, 1000, nullptr);
|
|
refreshLan(w, *v);
|
|
}
|
|
else if (v->logRequest.empty()) KillTimer(w, 1);
|
|
return 0;
|
|
}
|
|
if (msg == WM_TIMER && wp == 1)
|
|
{
|
|
if (IsWindowVisible(w) || !v->logRequest.empty()) refreshLan(w, *v);
|
|
else KillTimer(w, 1);
|
|
return 0;
|
|
}
|
|
if(msg==WM_COMMAND)
|
|
{
|
|
int id=LOWORD(wp); auto peer=selectedLan(w,*v);
|
|
if(id==702&&HIWORD(wp)==LBN_SELCHANGE) {refreshLan(w,*v);return 0;}
|
|
if(HIWORD(wp)!=BN_CLICKED) return DefWindowProcW(w,msg,wp,lp);
|
|
if(!IsWindowEnabled(GetDlgItem(w,id)))return 0;
|
|
v->error.clear();
|
|
v->layoutError.clear();
|
|
if(id==722){showLanHelp(v->owner,*v->app);return 0;}
|
|
if(id==735){showLanClients(v->owner,*v);return 0;}
|
|
if(id==701) stageLanValue(*v,"enabled",!v->snapshot.value("enabled",false));
|
|
if(id==704)
|
|
{
|
|
auto code=lanRequest(*v->app,{{"action","code"}}).at("code").get<std::string>();
|
|
std::string grouped; for(size_t i=0;i<code.size();++i) {if(i&&i%4==0) grouped+='-';grouped+=code[i];}
|
|
value(w,703,wide(grouped)); SetFocus(GetDlgItem(w,703)); SendDlgItemMessageW(w,703,EM_SETSEL,0,-1);
|
|
}
|
|
if(id==705) v->draft["pair"] = {{"peer",peer},{"code",lan::normalizeCode(utf8(value(w,703)))}};
|
|
if(id==701 && v->snapshot.value("enabled",false))
|
|
{
|
|
v->draft.erase("pair");
|
|
if (v->draft.value("shareInput", false)) v->draft.erase("shareInput");
|
|
}
|
|
if(id==706 && !v->draft.erase("pair")) lanRequest(*v->app,{{"action","cancel"}});
|
|
if(id==707)
|
|
{
|
|
v->draft["forget"][peer] = true;
|
|
if (v->draft.contains("positions"))
|
|
{
|
|
v->draft["positions"].erase(peer);
|
|
if (v->draft["positions"].empty()) v->draft.erase("positions");
|
|
}
|
|
if (v->snapshot["positions"].size() == 1) v->draft.erase("shareInput");
|
|
}
|
|
if(id==727||id==728)
|
|
{
|
|
auto destination=pickLanFile(v->owner,true,id==728?L"kswitcher-previous.log":L"kswitcher-remote.log");
|
|
if(!destination.empty())
|
|
{
|
|
auto reply=lanRequest(*v->app,{{"action","requestLog"},{"peer",peer},{"previous",id==728}});
|
|
v->logDestination=std::move(destination);
|
|
v->logRequest=reply.at("request").get<std::string>();
|
|
v->logMessage=L"Downloading diagnostic log...";
|
|
}
|
|
}
|
|
if(id==729)stageLanValue(*v,"shareLogs",checked(w,729));
|
|
if(id==715 || id==716) stageLanValue(*v,"shareInput",id==715);
|
|
refreshLanFooter(*v);
|
|
refreshLan(w,*v); return 0;
|
|
}
|
|
}
|
|
catch(const std::exception &e) {v->error=wide(e.what());value(w,708,v->error);}
|
|
return DefWindowProcW(w,msg,wp,lp);
|
|
}
|
|
constexpr int LanPadding = 16, LanPairingWidth = 341, LanLayoutLeft = 375, LanLayoutWidth = 341;
|
|
constexpr int LanEditorsTop = 98, LanEditorsHeight = 134, LanEditorsBottom = LanEditorsTop + LanEditorsHeight;
|
|
constexpr int LanActionHeight = 28, LanCodeTop = LanEditorsBottom + 66, LanActionsTop = LanCodeTop + LanActionHeight + 8;
|
|
constexpr int LanDiagnosticsTop = 420, LanStackWidth = 640;
|
|
constexpr int LanSettingsWidth = LanLayoutLeft + LanLayoutWidth + LanPadding, LanSettingsHeight = 540;
|
|
HWND createLanSettings(HWND pane, App &app)
|
|
{
|
|
WNDCLASSW panel{};
|
|
panel.hInstance = app.instance;
|
|
panel.lpfnWndProc = lanProc;
|
|
panel.lpszClassName = L"KSwitcher.LAN.Settings";
|
|
panel.hCursor = LoadCursorW(nullptr, IDC_ARROW);
|
|
panel.hbrBackground = GetSysColorBrush(COLOR_WINDOW);
|
|
RegisterClassW(&panel);
|
|
HWND w = CreateWindowExW(WS_EX_CONTROLPARENT, panel.lpszClassName, L"",
|
|
WS_CHILD | WS_CLIPCHILDREN, 0, 0, scale(pane, LanSettingsWidth),
|
|
scale(pane, LanSettingsHeight), pane, reinterpret_cast<HMENU>(262), app.instance, nullptr);
|
|
if (!w) throw std::runtime_error("Cannot create computer settings.");
|
|
auto v = new LanView{GetAncestor(pane, GA_ROOT), &app};
|
|
SetWindowLongPtrW(w, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(v));
|
|
SetPropW(w, L"Font", GetPropW(pane, L"Font"));
|
|
auto layout = new WindowLayout{LanSettingsWidth, LanSettingsHeight, 0, 0, true, true};
|
|
SetPropW(w, L"WindowLayout", layout);
|
|
constexpr int left = LanPadding, pairingWidth = LanPairingWidth, right = LanLayoutLeft, rightWidth = LanLayoutWidth;
|
|
constexpr int gap = 10, rowHeight = LanActionHeight;
|
|
constexpr int discoveryWidth = (pairingWidth - gap) / 2;
|
|
settingsGroupLabel(w, L"Computers and pairing", left, 14, pairingWidth);
|
|
control(w, L"STATIC", L"", 0, 709, left, 39, pairingWidth, 22);
|
|
button(w, L"&Enable discovery", 701, left, 65, discoveryWidth);
|
|
button(w, L"&Trusted clients…", 735, left + discoveryWidth + gap, 65, discoveryWidth);
|
|
control(w, L"LISTBOX", L"Discovered and paired computers", WS_TABSTOP | WS_VSCROLL | WS_BORDER | LBS_NOTIFY | LBS_NOINTEGRALHEIGHT,
|
|
702, left, LanEditorsTop, pairingWidth, LanEditorsHeight);
|
|
control(w, L"STATIC", L"", 0, 710, left, LanEditorsBottom + 8, pairingWidth, 33);
|
|
constexpr int codeTop = LanCodeTop, actionTop = LanActionsTop;
|
|
constexpr int generateWidth = 135, codeWidth = pairingWidth - gap - generateWidth;
|
|
constexpr int actionWidth = (pairingWidth - 2 * gap) / 3, actionStep = actionWidth + gap;
|
|
label(w, L"Same pairing c&ode on both PCs", left, codeTop - 24, pairingWidth);
|
|
edit(w, 703, left, codeTop, codeWidth, rowHeight);
|
|
SendDlgItemMessageW(w,703,EM_SETLIMITTEXT,80,0);
|
|
button(w, L"&Generate code", 704, left + codeWidth + gap, codeTop, generateWidth);
|
|
button(w, L"&Pair", 705, left, actionTop, actionWidth);
|
|
button(w, L"Ca&ncel", 706, left + actionStep, actionTop, actionWidth);
|
|
button(w, L"&Forget pair", 707, left + 2 * actionStep, actionTop, actionWidth);
|
|
control(w, L"STATIC", L"", 0, 708, left, actionTop + rowHeight + 5, pairingWidth, 42);
|
|
|
|
constexpr int inputButtonWidth = (rightWidth - gap) / 2;
|
|
settingsGroupLabel(w, L"Monitor layout and input sharing", right, 14, rightWidth);
|
|
control(w, L"STATIC", L"Drag monitors or use arrow keys. The pointer crosses shared edges.", 0, 719, right, 39, rightWidth, 50);
|
|
WNDCLASSW gridClass{};gridClass.lpfnWndProc=lanGridProc;gridClass.hInstance=app.instance;gridClass.hCursor=LoadCursorW(nullptr,IDC_ARROW);gridClass.lpszClassName=L"KSwitcher.LAN.Layout";RegisterClassW(&gridClass);
|
|
auto grid=CreateWindowExW(0,gridClass.lpszClassName,L"Computer layout. Select a computer in the list, then drag its monitor or use arrow keys.",WS_CHILD|WS_VISIBLE|WS_TABSTOP|WS_BORDER,
|
|
scale(w,right),scale(w,LanEditorsTop),scale(w,rightWidth),scale(w,LanEditorsHeight),w,reinterpret_cast<HMENU>(721),app.instance,v);
|
|
windowLayoutState(w)->controls.push_back({grid,{right,LanEditorsTop,right+rightWidth,LanEditorsBottom}});
|
|
control(w, L"STATIC", L"", 0, 718, right, LanEditorsBottom + 8, rightWidth, 42);
|
|
button(w, L"Enable &input sharing", 715, right, codeTop, inputButtonWidth);
|
|
button(w, L"&Stop input sharing", 716, right + inputButtonWidth + gap, codeTop, inputButtonWidth);
|
|
button(w, L"Connection &help", 722, right, actionTop, 232);
|
|
|
|
constexpr int fullWidth = right + rightWidth - left;
|
|
constexpr int logButtonWidth = (fullWidth - gap) / 2;
|
|
settingsGroupLabel(w, L"Diagnostic logs", left, LanDiagnosticsTop, fullWidth);
|
|
checkbox(w, L"Allow paired computers to download logs", 729, left, LanDiagnosticsTop + 28, fullWidth);
|
|
button(w, L"Current log…", 727, left, LanDiagnosticsTop + 62, logButtonWidth);
|
|
button(w, L"Previous log…", 728, left + logButtonWidth + gap, LanDiagnosticsTop + 62, logButtonWidth);
|
|
ShowWindow(control(w, L"STATIC", L"", 0, 731, left, LanDiagnosticsTop + 96, fullWidth, 22), SW_HIDE);
|
|
SetWindowSubclass(grid, scrollChildProc, 2, 0);
|
|
captureSettingsGeometry(*layout, 0, w);
|
|
layout->arranging = false;
|
|
return w;
|
|
}
|
|
|
|
void alignLanActionRows(WindowLayout &layout, size_t footer, size_t end)
|
|
{
|
|
for (int row : {LanCodeTop, LanActionsTop})
|
|
{
|
|
LONG top = 0, height = 0;
|
|
std::array<LONG, 2> previousBottom{};
|
|
for (size_t i = 0; i < footer; ++i)
|
|
{
|
|
const auto &original = layout.originalControls[i].bounds;
|
|
if (original.top != row) continue;
|
|
const auto &bounds = layout.controls[i].second;
|
|
const int column = original.left >= LanLayoutLeft;
|
|
top = std::max(top, bounds.top);
|
|
height = std::max(height, bounds.bottom - bounds.top);
|
|
previousBottom[column] = std::max(previousBottom[column], bounds.bottom);
|
|
}
|
|
const LONG bottom = top + height;
|
|
for (size_t i = 0; i < footer; ++i)
|
|
{
|
|
const auto &original = layout.originalControls[i].bounds;
|
|
auto &bounds = layout.controls[i].second;
|
|
if (original.top == row)
|
|
{
|
|
bounds.top = top;
|
|
bounds.bottom = bottom;
|
|
}
|
|
else if (original.top > row)
|
|
OffsetRect(&bounds, 0, bottom - previousBottom[original.left >= LanLayoutLeft]);
|
|
}
|
|
}
|
|
LONG contentBottom = 0;
|
|
for (size_t i = 0; i < footer; ++i) contentBottom = std::max(contentBottom, layout.controls[i].second.bottom);
|
|
const LONG footerShift = std::max(0L, contentBottom + 12 - layout.controls[footer].second.top);
|
|
for (size_t i = footer; i < end; ++i) OffsetRect(&layout.controls[i].second, 0, footerShift);
|
|
layout.height += footerShift;
|
|
}
|
|
|
|
int fitLanSettings(HWND panel, int width, int height)
|
|
{
|
|
auto &layout = *windowLayoutState(panel);
|
|
layout.width = 1;
|
|
// The final control is feedback for the diagnostic log actions.
|
|
const auto end = layout.controls.size() - (GetWindowTextLengthW(GetDlgItem(panel, 731)) ? 0 : 1);
|
|
layout.height = fitSettingsColumns(layout, 0, end, width,
|
|
{LanPadding, LanLayoutLeft + LanLayoutWidth, LanLayoutLeft, LanPadding + LanPairingWidth,
|
|
LanDiagnosticsTop, LanStackWidth, 0, 0, true});
|
|
const auto footer = std::find_if(layout.originalControls.begin(), layout.originalControls.end(),
|
|
[](const auto &item) { return item.bounds.top >= LanDiagnosticsTop; }) - layout.originalControls.begin();
|
|
const bool stacked = width < LanStackWidth;
|
|
if (!stacked) alignLanActionRows(layout, footer, end);
|
|
const int extra = std::max(0, height - layout.height);
|
|
stretchSettingsEditors(layout, 0, footer, extra, {702, 721}, stacked);
|
|
for (size_t i = footer; i < end; ++i) OffsetRect(&layout.controls[i].second, 0, extra);
|
|
return layout.height;
|
|
}
|