From 6515374ce92ed1fdd764b60179a22e722aabce0c Mon Sep 17 00:00:00 2001 From: Michael Clayton Date: Fri, 21 Feb 2025 08:31:44 +0000 Subject: [PATCH] Ready for Review - [Mouse Without Borders] - refactoring "Common" classes (Part 3) - #35155 (#36950) * [MWB] - refactoring MachineInf from Common.MachineStuff.cs into MachineInf.cs - #35155 * [MWB] - fixing references to MachineInf - #35155 * [MWB] - cleaning up MachineInf.cs - #35155 * [MWB] - moving MyRectangle from Common.MachineStuff.cs into MyRectangle.cs - #35155 * [MWB] - cleaning up MyRectangle.cs - #35155 * [MWB] - moving Common.MachineStuff.cs to MachineStuff.cs - #35155 * [MWB] - fixing references to MachineStuff - #35155 * [MWB] - cleaning up MachineStuff.cs - #35155 * [MWB] - cleaning up MachineStuff.cs - #35155 * [MWB] - moving Common.DragDrop.cs to DragDrop.cs - #35155 * [MWB] - fixing references to DragDrop - #35155 * [MWB] - fixing unit test - #35155 * [MWB] - cleaning up DragDrop.cs - #35155 * [MWB] - cleaning up DragDrop.cs - #35155 --- .../App/Class/Common.Clipboard.cs | 4 +- .../App/Class/Common.DragDrop.cs | 409 ------ .../App/Class/Common.Event.cs | 60 +- .../App/Class/Common.Helper.cs | 30 +- .../App/Class/Common.InitAndCleanup.cs | 18 +- .../App/Class/Common.MachineStuff.cs | 1136 ----------------- .../App/Class/Common.WinAPI.cs | 22 +- .../MouseWithoutBorders/App/Class/Common.cs | 74 +- .../App/Class/IClipboardHelper.cs | 2 +- .../App/Class/InputHook.cs | 52 +- .../App/Class/InputSimulation.cs | 18 +- .../App/Class/MachinePool.cs | 20 +- .../App/Class/MachinePoolHelpers.cs | 10 +- .../MouseWithoutBorders/App/Class/Program.cs | 21 +- .../MouseWithoutBorders/App/Class/Setting.cs | 4 +- .../App/Class/SocketStuff.cs | 38 +- .../MouseWithoutBorders/App/Core/DragDrop.cs | 404 ++++++ .../MouseWithoutBorders/App/Core/Logger.cs | 5 +- .../App/Core/MachineInf.cs | 20 + .../App/Core/MachineStuff.cs | 1122 ++++++++++++++++ .../App/Core/MyRectangle.cs | 21 + .../MouseWithoutBorders/App/Core/Receiver.cs | 38 +- .../App/Form/Settings/SettingsForm.cs | 2 +- .../App/Form/Settings/SettingsFormPage.cs | 5 +- .../App/Form/Settings/SetupPage1.cs | 4 +- .../App/Form/Settings/SetupPage2a.cs | 9 +- .../App/Form/Settings/SetupPage3a.cs | 2 +- .../App/Form/Settings/SetupPage5.cs | 6 +- .../MouseWithoutBorders/App/Form/frmMatrix.cs | 36 +- .../MouseWithoutBorders/App/Form/frmScreen.cs | 56 +- .../Core/Logger.PrivateDump.expected.txt | 82 +- .../Core/LoggerTests.cs | 4 + 32 files changed, 1889 insertions(+), 1845 deletions(-) delete mode 100644 src/modules/MouseWithoutBorders/App/Class/Common.DragDrop.cs delete mode 100644 src/modules/MouseWithoutBorders/App/Class/Common.MachineStuff.cs create mode 100644 src/modules/MouseWithoutBorders/App/Core/DragDrop.cs create mode 100644 src/modules/MouseWithoutBorders/App/Core/MachineInf.cs create mode 100644 src/modules/MouseWithoutBorders/App/Core/MachineStuff.cs create mode 100644 src/modules/MouseWithoutBorders/App/Core/MyRectangle.cs diff --git a/src/modules/MouseWithoutBorders/App/Class/Common.Clipboard.cs b/src/modules/MouseWithoutBorders/App/Class/Common.Clipboard.cs index 3f5ace6900..9ab3238894 100644 --- a/src/modules/MouseWithoutBorders/App/Class/Common.Clipboard.cs +++ b/src/modules/MouseWithoutBorders/App/Class/Common.Clipboard.cs @@ -431,7 +431,7 @@ namespace MouseWithoutBorders if (!IsConnectedByAClientSocketTo(remoteMachine)) { Logger.Log($"No potential inbound connection from {MachineName} to {remoteMachine}, ask for a push back instead."); - ID machineId = MachinePool.ResolveID(remoteMachine); + ID machineId = MachineStuff.MachinePool.ResolveID(remoteMachine); if (machineId != ID.NONE) { @@ -840,7 +840,7 @@ namespace MouseWithoutBorders Logger.LogDebug($"{nameof(ShakeHand)}: Connection from {name}:{package.Src}"); - if (Common.MachinePool.ResolveID(name) == package.Src && Common.IsConnectedTo(package.Src)) + if (MachineStuff.MachinePool.ResolveID(name) == package.Src && Common.IsConnectedTo(package.Src)) { clientPushData = package.Type == PackageType.ClipboardPush; postAction = package.PostAction; diff --git a/src/modules/MouseWithoutBorders/App/Class/Common.DragDrop.cs b/src/modules/MouseWithoutBorders/App/Class/Common.DragDrop.cs deleted file mode 100644 index 5426f93db0..0000000000 --- a/src/modules/MouseWithoutBorders/App/Class/Common.DragDrop.cs +++ /dev/null @@ -1,409 +0,0 @@ -// Copyright (c) Microsoft Corporation -// The Microsoft Corporation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Drawing; -using System.Globalization; -using System.IO; -using System.Threading; -using System.Windows.Forms; - -using Microsoft.PowerToys.Telemetry; - -// -// Drag/Drop implementation. -// -// -// 2008 created by Truong Do (ductdo). -// 2009-... modified by Truong Do (TruongDo). -// 2023- Included in PowerToys. -// -using MouseWithoutBorders.Class; -using MouseWithoutBorders.Core; - -using Thread = MouseWithoutBorders.Core.Thread; - -namespace MouseWithoutBorders -{ - /* Common.DragDrop.cs - * Drag&Drop is one complicated implementation of the tool with some tricks. - * - * SEQUENCE OF EVENTS: - * DragDropStep01: MachineX: Remember mouse down state since it could be a start of a dragging - * DragDropStep02: MachineY: Send an message to the MachineX to ask it to check if it is - * doing drag/drop - * DragDropStep03: MachineX: Got explorerDragDrop, send WM_CHECK_EXPLORER_DRAG_DROP to its mainForm - * DragDropStep04: MachineX: Show Mouse Without Borders Helper form at mouse cursor to get DragEnter event. - * DragDropStepXX: MachineX: Mouse Without Borders Helper: Called by DragEnter, check if dragging a single file, - * remember the file (set as its window caption) - * DragDropStep05: MachineX: Get the file name from Mouse Without Borders Helper, hide Mouse Without Borders Helper window - * DragDropStep06: MachineX: Broadcast a message saying that it has some drag file. - * DragDropStep08: MachineY: Got ClipboardDragDrop, isDropping set, get the MachineX name from the package. - * DragDropStep09: MachineY: Since isDropping is true, show up the drop form (looks like an icon). - * DragDropStep10: MachineY: MouseUp, set isDropping to false, hide the drop "icon" and get data. - * DragDropStep11: MachineX: Mouse move back without drop event, cancelling drag/dop - * SendClipboardBeatDragDropEnd - * DragDropStep12: MachineY: Hide the drop "icon" when received ClipboardDragDropEnd. - * - * FROM VERSION 1.6.3: Drag/Drop is temporary removed, Drop action cannot be done from a lower integrity app to a higher one. - * We have to run a helper process... - * http://forums.microsoft.com/MSDN/ShowPost.aspx?PageIndex=1&SiteID=1&PageID=1&PostID=736086 - * - * 2008.10.28: Trying to restore the Drag/Drop feature by adding the drag/drop helper process. Coming in version - * 1.6.5 - * */ - - internal partial class Common - { - private static bool isDragging; - - internal static bool IsDragging - { - get => Common.isDragging; - set => Common.isDragging = value; - } - - internal static void DragDropStep01(int wParam) - { - if (!Setting.Values.TransferFile) - { - return; - } - - if (wParam == WM_LBUTTONDOWN) - { - MouseDown = true; - DragMachine = desMachineID; - dropMachineID = ID.NONE; - Logger.LogDebug("DragDropStep01: MouseDown"); - } - else if (wParam == WM_LBUTTONUP) - { - MouseDown = false; - Logger.LogDebug("DragDropStep01: MouseUp"); - } - - if (wParam == WM_RBUTTONUP && IsDropping) - { - IsDropping = false; - LastIDWithClipboardData = ID.NONE; - } - } - - internal static void DragDropStep02() - { - if (desMachineID == MachineID) - { - Logger.LogDebug("DragDropStep02: SendCheckExplorerDragDrop sent to myself"); - DoSomethingInUIThread(() => - { - _ = NativeMethods.PostMessage(MainForm.Handle, NativeMethods.WM_CHECK_EXPLORER_DRAG_DROP, (IntPtr)0, (IntPtr)0); - }); - } - else - { - SendCheckExplorerDragDrop(); - Logger.LogDebug("DragDropStep02: SendCheckExplorerDragDrop sent"); - } - } - - internal static void DragDropStep03(DATA package) - { - if (RunOnLogonDesktop || RunOnScrSaverDesktop) - { - return; - } - - if (package.Des == MachineID || package.Des == ID.ALL) - { - Logger.LogDebug("DragDropStep03: ExplorerDragDrop Received."); - dropMachineID = package.Src; // Drop machine is the machine that sent ExplorerDragDrop - if (MouseDown || IsDropping) - { - Logger.LogDebug("DragDropStep03: Mouse is down, check if dragging...sending WM_CHECK_EXPLORER_DRAG_DROP to myself..."); - DoSomethingInUIThread(() => - { - _ = NativeMethods.PostMessage(MainForm.Handle, NativeMethods.WM_CHECK_EXPLORER_DRAG_DROP, (IntPtr)0, (IntPtr)0); - }); - } - } - } - - private static int dragDropStep05ExCalledByIpc; - - internal static void DragDropStep04() - { - if (!IsDropping) - { - IntPtr h = (IntPtr)NativeMethods.FindWindow(null, Common.HELPER_FORM_TEXT); - if (h.ToInt32() > 0) - { - _ = Interlocked.Exchange(ref dragDropStep05ExCalledByIpc, 0); - - MainForm.Hide(); - MainFormVisible = false; - - Point p = default; - - // NativeMethods.SetWindowText(h, ""); - _ = NativeMethods.SetWindowPos(h, NativeMethods.HWND_TOPMOST, 0, 0, 0, 0, NativeMethods.SWP_SHOWWINDOW); - - for (int i = -10; i < 10; i++) - { - if (dragDropStep05ExCalledByIpc > 0) - { - Logger.LogDebug("DragDropStep04: DragDropStep05ExCalledByIpc."); - break; - } - - _ = NativeMethods.GetCursorPos(ref p); - Logger.LogDebug("DragDropStep04: Moving Mouse Without Borders Helper to (" + p.X.ToString(CultureInfo.CurrentCulture) + ", " + p.Y.ToString(CultureInfo.CurrentCulture) + ")"); - _ = NativeMethods.SetWindowPos(h, NativeMethods.HWND_TOPMOST, p.X - 100 + i, p.Y - 100 + i, 200, 200, 0); - _ = NativeMethods.SendMessage(h, 0x000F, IntPtr.Zero, IntPtr.Zero); // WM_PAINT - Thread.Sleep(20); - Application.DoEvents(); - - // if (GetText(h).Length > 1) break; - } - } - else - { - Logger.LogDebug("DragDropStep04: Mouse without Borders Helper not found!"); - } - } - else - { - Logger.LogDebug("DragDropStep04: IsDropping == true, skip checking"); - } - - Logger.LogDebug("DragDropStep04: Got WM_CHECK_EXPLORER_DRAG_DROP, done with processing jump to DragDropStep05..."); - } - - internal static void DragDropStep05Ex(string dragFileName) - { - Logger.LogDebug("DragDropStep05 called."); - - _ = Interlocked.Exchange(ref dragDropStep05ExCalledByIpc, 1); - - if (RunOnLogonDesktop || RunOnScrSaverDesktop) - { - return; - } - - if (!IsDropping) - { - _ = Common.ImpersonateLoggedOnUserAndDoSomething(() => - { - if (!string.IsNullOrEmpty(dragFileName) && (File.Exists(dragFileName) || Directory.Exists(dragFileName))) - { - Common.LastDragDropFile = dragFileName; - /* - * possibleDropMachineID is used as desID sent in DragDropStep06(); - * */ - if (dropMachineID == ID.NONE) - { - dropMachineID = newDesMachineID; - } - - DragDropStep06(); - Logger.LogDebug("DragDropStep05: File dragging: " + dragFileName); - _ = NativeMethods.PostMessage(MainForm.Handle, NativeMethods.WM_HIDE_DD_HELPER, (IntPtr)1, (IntPtr)0); - } - else - { - Logger.LogDebug("DragDropStep05: File not found: [" + dragFileName + "]"); - _ = NativeMethods.PostMessage(MainForm.Handle, NativeMethods.WM_HIDE_DD_HELPER, (IntPtr)0, (IntPtr)0); - } - - Logger.LogDebug("DragDropStep05: WM_HIDE_DDHelper sent"); - }); - } - else - { - Logger.LogDebug("DragDropStep05: IsDropping == true, change drop machine..."); - IsDropping = false; - MainFormVisible = true; // WM_HIDE_DRAG_DROP - SendDropBegin(); // To dropMachineID set in DragDropStep03 - } - - MouseDown = false; - } - - internal static void DragDropStep06() - { - IsDragging = true; - Logger.LogDebug("DragDropStep06: SendClipboardBeatDragDrop"); - SendClipboardBeatDragDrop(); - SendDropBegin(); - } - - internal static void DragDropStep08(DATA package) - { - Receiver.GetNameOfMachineWithClipboardData(package); - Logger.LogDebug("DragDropStep08: ClipboardDragDrop Received. machine with drag file was set"); - } - - internal static void DragDropStep08_2(DATA package) - { - if (package.Des == MachineID && !RunOnLogonDesktop && !RunOnScrSaverDesktop) - { - IsDropping = true; - dropMachineID = MachineID; - Logger.LogDebug("DragDropStep08_2: ClipboardDragDropOperation Received. IsDropping set"); - } - } - - internal static void DragDropStep09(int wParam) - { - if (wParam == WM_MOUSEMOVE && IsDropping) - { - // Show/Move form - DoSomethingInUIThread(() => - { - _ = NativeMethods.PostMessage(MainForm.Handle, NativeMethods.WM_SHOW_DRAG_DROP, (IntPtr)0, (IntPtr)0); - }); - } - else if (wParam == WM_LBUTTONUP && (IsDropping || IsDragging)) - { - if (IsDropping) - { - // Hide form, get data - DragDropStep10(); - } - else - { - IsDragging = false; - LastIDWithClipboardData = ID.NONE; - } - } - } - - internal static void DragDropStep10() - { - Logger.LogDebug("DragDropStep10: Hide the form and get data..."); - IsDropping = false; - IsDragging = false; - LastIDWithClipboardData = ID.NONE; - - DoSomethingInUIThread(() => - { - _ = NativeMethods.PostMessage(MainForm.Handle, NativeMethods.WM_HIDE_DRAG_DROP, (IntPtr)0, (IntPtr)0); - }); - - PowerToysTelemetry.Log.WriteEvent(new MouseWithoutBorders.Telemetry.MouseWithoutBordersDragAndDropEvent()); - GetRemoteClipboard("desktop"); - } - - internal static void DragDropStep11() - { - Logger.LogDebug("DragDropStep11: Mouse drag coming back, canceling drag/drop"); - SendClipboardBeatDragDropEnd(); - IsDropping = false; - IsDragging = false; - DragMachine = (ID)1; - LastIDWithClipboardData = ID.NONE; - LastDragDropFile = null; - MouseDown = false; - } - - internal static void DragDropStep12() - { - Logger.LogDebug("DragDropStep12: ClipboardDragDropEnd received"); - IsDropping = false; - LastIDWithClipboardData = ID.NONE; - - DoSomethingInUIThread(() => - { - _ = NativeMethods.PostMessage(MainForm.Handle, NativeMethods.WM_HIDE_DRAG_DROP, (IntPtr)0, (IntPtr)0); - }); - } - - internal static void SendCheckExplorerDragDrop() - { - DATA package = new(); - package.Type = PackageType.ExplorerDragDrop; - - /* - * package.src = newDesMachineID: - * sent from the master machine but the src must be the - * new des machine since the previous des machine will get this and set - * to possibleDropMachineID in DragDropStep3() - * */ - package.Src = newDesMachineID; - - package.Des = desMachineID; - package.MachineName = MachineName; - - SkSend(package, null, false); - } - - private static void ChangeDropMachine() - { - // desMachineID = current drop machine - // newDesMachineID = new drop machine - - // 1. Cancelling dropping in current drop machine - if (dropMachineID == MachineID) - { - // Drag/Drop coming through me - IsDropping = false; - } - else - { - // Drag/Drop coming back - SendClipboardBeatDragDropEnd(); - } - - // 2. SendClipboardBeatDragDrop to new drop machine - // new drop machine is not me - if (newDesMachineID != MachineID) - { - dropMachineID = newDesMachineID; - SendDropBegin(); - } - - // New drop machine is me - else - { - IsDropping = true; - } - } - - internal static void SendClipboardBeatDragDrop() - { - SendPackage(ID.ALL, PackageType.ClipboardDragDrop); - } - - internal static void SendDropBegin() - { - Logger.LogDebug("SendDropBegin..."); - SendPackage(dropMachineID, PackageType.ClipboardDragDropOperation); - } - - internal static void SendClipboardBeatDragDropEnd() - { - if (desMachineID != MachineID) - { - SendPackage(desMachineID, PackageType.ClipboardDragDropEnd); - } - } - - private static bool isDropping; - private static ID dragMachine; - - internal static ID DragMachine - { - get => Common.dragMachine; - set => Common.dragMachine = value; - } - - internal static bool IsDropping - { - get => Common.isDropping; - set => Common.isDropping = value; - } - - internal static bool MouseDown { get; set; } - } -} diff --git a/src/modules/MouseWithoutBorders/App/Class/Common.Event.cs b/src/modules/MouseWithoutBorders/App/Class/Common.Event.cs index fc581a3de2..92122bcc8f 100644 --- a/src/modules/MouseWithoutBorders/App/Class/Common.Event.cs +++ b/src/modules/MouseWithoutBorders/App/Class/Common.Event.cs @@ -72,7 +72,7 @@ namespace MouseWithoutBorders if (switchByMouseEnabled && Sk != null && (DesMachineID == MachineID || !Setting.Values.MoveMouseRelatively) && e.dwFlags == WM_MOUSEMOVE) { - Point p = MoveToMyNeighbourIfNeeded(e.X, e.Y, desMachineID); + Point p = MachineStuff.MoveToMyNeighbourIfNeeded(e.X, e.Y, MachineStuff.desMachineID); if (!p.IsEmpty) { @@ -81,20 +81,20 @@ namespace MouseWithoutBorders Logger.LogDebug(string.Format( CultureInfo.CurrentCulture, "***** Host Machine: newDesMachineIdEx set = [{0}]. Mouse is now at ({1},{2})", - newDesMachineIdEx, + MachineStuff.newDesMachineIdEx, e.X, e.Y)); myLastX = e.X; myLastY = e.Y; - PrepareToSwitchToMachine(newDesMachineIdEx, p); + PrepareToSwitchToMachine(MachineStuff.newDesMachineIdEx, p); } } - if (desMachineID != MachineID && SwitchLocation.Count <= 0) + if (MachineStuff.desMachineID != MachineID && MachineStuff.SwitchLocation.Count <= 0) { - MousePackage.Des = desMachineID; + MousePackage.Des = MachineStuff.desMachineID; MousePackage.Type = PackageType.Mouse; MousePackage.Md.dwFlags = e.dwFlags; MousePackage.Md.WheelDelta = e.WheelDelta; @@ -107,8 +107,8 @@ namespace MouseWithoutBorders } else { - MousePackage.Md.X = (e.X - primaryScreenBounds.Left) * 65535 / screenWidth; - MousePackage.Md.Y = (e.Y - primaryScreenBounds.Top) * 65535 / screenHeight; + MousePackage.Md.X = (e.X - MachineStuff.primaryScreenBounds.Left) * 65535 / screenWidth; + MousePackage.Md.Y = (e.Y - MachineStuff.primaryScreenBounds.Top) * 65535 / screenHeight; } SkSend(MousePackage, null, false); @@ -156,15 +156,15 @@ namespace MouseWithoutBorders { Logger.LogDebug($"PrepareToSwitchToMachine: newDesMachineID = {newDesMachineID}, desMachineXY = {desMachineXY}"); - if (((GetTick() - lastJump < 100) && (GetTick() - lastJump > 0)) || desMachineID == ID.ALL) + if (((GetTick() - MachineStuff.lastJump < 100) && (GetTick() - MachineStuff.lastJump > 0)) || MachineStuff.desMachineID == ID.ALL) { Logger.LogDebug("PrepareToSwitchToMachine: lastJump"); return; } - lastJump = GetTick(); + MachineStuff.lastJump = GetTick(); - string newDesMachineName = NameFromID(newDesMachineID); + string newDesMachineName = MachineStuff.NameFromID(newDesMachineID); if (!IsConnectedTo(newDesMachineID)) {// Connection lost, cancel switching @@ -174,46 +174,46 @@ namespace MouseWithoutBorders } else { - Common.newDesMachineID = newDesMachineID; - SwitchLocation.X = desMachineXY.X; - SwitchLocation.Y = desMachineXY.Y; - SwitchLocation.ResetCount(); + MachineStuff.newDesMachineID = newDesMachineID; + MachineStuff.SwitchLocation.X = desMachineXY.X; + MachineStuff.SwitchLocation.Y = desMachineXY.Y; + MachineStuff.SwitchLocation.ResetCount(); _ = EvSwitch.Set(); // PostMessage(mainForm.Handle, WM_SWITCH, IntPtr.Zero, IntPtr.Zero); - if (newDesMachineID != DragMachine) + if (newDesMachineID != DragDrop.DragMachine) { - if (!IsDragging && !IsDropping) + if (!DragDrop.IsDragging && !DragDrop.IsDropping) { - if (MouseDown && !RunOnLogonDesktop && !RunOnScrSaverDesktop) + if (DragDrop.MouseDown && !RunOnLogonDesktop && !RunOnScrSaverDesktop) { - DragDropStep02(); + DragDrop.DragDropStep02(); } } - else if (DragMachine != (ID)1) + else if (DragDrop.DragMachine != (ID)1) { - ChangeDropMachine(); + DragDrop.ChangeDropMachine(); } } else { - DragDropStep11(); + DragDrop.DragDropStep11(); } // Change des machine - if (desMachineID != newDesMachineID) + if (MachineStuff.desMachineID != newDesMachineID) { Logger.LogDebug("MouseEvent: Switching to new machine:" + newDesMachineName); // Ask current machine to hide the Mouse cursor - if (newDesMachineID != ID.ALL && desMachineID != MachineID) + if (newDesMachineID != ID.ALL && MachineStuff.desMachineID != MachineID) { - SendPackage(desMachineID, PackageType.HideMouse); + SendPackage(MachineStuff.desMachineID, PackageType.HideMouse); } DesMachineID = newDesMachineID; - if (desMachineID == MachineID) + if (MachineStuff.desMachineID == MachineID) { if (GetTick() - clipboardCopiedTime < BIG_CLIPBOARD_DATA_TIMEOUT) { @@ -224,7 +224,7 @@ namespace MouseWithoutBorders else { // Ask the new active machine to get clipboard data (if the data is too big) - SendPackage(desMachineID, PackageType.MachineSwitched); + SendPackage(MachineStuff.desMachineID, PackageType.MachineSwitched); } _ = Interlocked.Increment(ref switchCount); @@ -249,15 +249,15 @@ namespace MouseWithoutBorders try { PaintCount = 0; - if (desMachineID != newDesMachineID) + if (MachineStuff.desMachineID != MachineStuff.newDesMachineID) { Logger.LogDebug("KeybdEvent: Switching to new machine..."); - DesMachineID = newDesMachineID; + DesMachineID = MachineStuff.newDesMachineID; } - if (desMachineID != MachineID) + if (MachineStuff.desMachineID != MachineID) { - KeybdPackage.Des = desMachineID; + KeybdPackage.Des = MachineStuff.desMachineID; KeybdPackage.Type = PackageType.Keyboard; KeybdPackage.Kd = e; KeybdPackage.DateTime = GetTick(); diff --git a/src/modules/MouseWithoutBorders/App/Class/Common.Helper.cs b/src/modules/MouseWithoutBorders/App/Class/Common.Helper.cs index d6bd73b7eb..b741f95256 100644 --- a/src/modules/MouseWithoutBorders/App/Class/Common.Helper.cs +++ b/src/modules/MouseWithoutBorders/App/Class/Common.Helper.cs @@ -88,35 +88,35 @@ namespace MouseWithoutBorders break; } - if (Common.NewDesMachineID != Common.MachineID && Common.NewDesMachineID != ID.ALL) + if (MachineStuff.NewDesMachineID != Common.MachineID && MachineStuff.NewDesMachineID != ID.ALL) { HideMouseCursor(false); Common.MainFormDotEx(true); } else { - if (Common.SwitchLocation.Count > 0) + if (MachineStuff.SwitchLocation.Count > 0) { - Common.SwitchLocation.Count--; + MachineStuff.SwitchLocation.Count--; // When we want to move mouse by pixels, we add 300k to x and y (search for XY_BY_PIXEL for other related code). - Logger.LogDebug($"+++++ Moving mouse to {Common.SwitchLocation.X}, {Common.SwitchLocation.Y}"); + Logger.LogDebug($"+++++ Moving mouse to {MachineStuff.SwitchLocation.X}, {MachineStuff.SwitchLocation.Y}"); // MaxXY = 65535 so 100k is safe. - if (Common.SwitchLocation.X > XY_BY_PIXEL - 100000 || Common.SwitchLocation.Y > XY_BY_PIXEL - 100000) + if (MachineStuff.SwitchLocation.X > XY_BY_PIXEL - 100000 || MachineStuff.SwitchLocation.Y > XY_BY_PIXEL - 100000) { - InputSimulation.MoveMouse(Common.SwitchLocation.X - XY_BY_PIXEL, Common.SwitchLocation.Y - XY_BY_PIXEL); + InputSimulation.MoveMouse(MachineStuff.SwitchLocation.X - XY_BY_PIXEL, MachineStuff.SwitchLocation.Y - XY_BY_PIXEL); } else { - InputSimulation.MoveMouseEx(Common.SwitchLocation.X, Common.SwitchLocation.Y); + InputSimulation.MoveMouseEx(MachineStuff.SwitchLocation.X, MachineStuff.SwitchLocation.Y); } Common.MainFormDot(); } } - if (Common.NewDesMachineID == Common.MachineID) + if (MachineStuff.NewDesMachineID == Common.MachineID) { ReleaseAllKeys(); } @@ -137,8 +137,8 @@ namespace MouseWithoutBorders if (!Common.RunOnLogonDesktop && !Common.RunOnScrSaverDesktop) { - int left = Common.PrimaryScreenBounds.Left + ((Common.PrimaryScreenBounds.Right - Common.PrimaryScreenBounds.Left) / 2) - 1; - int top = Setting.Values.HideMouse ? 3 : Common.PrimaryScreenBounds.Top + ((Common.PrimaryScreenBounds.Bottom - Common.PrimaryScreenBounds.Top) / 2); + int left = MachineStuff.PrimaryScreenBounds.Left + ((MachineStuff.PrimaryScreenBounds.Right - MachineStuff.PrimaryScreenBounds.Left) / 2) - 1; + int top = Setting.Values.HideMouse ? 3 : MachineStuff.PrimaryScreenBounds.Top + ((MachineStuff.PrimaryScreenBounds.Bottom - MachineStuff.PrimaryScreenBounds.Top) / 2); Common.MainFormVisible = true; @@ -198,8 +198,8 @@ namespace MouseWithoutBorders DoSomethingInUIThread( () => { - MainForm.Left = Common.PrimaryScreenBounds.Left + ((Common.PrimaryScreenBounds.Right - Common.PrimaryScreenBounds.Left) / 2) - 2; - MainForm.Top = Setting.Values.HideMouse ? 3 : Common.PrimaryScreenBounds.Top + ((Common.PrimaryScreenBounds.Bottom - Common.PrimaryScreenBounds.Top) / 2) - 1; + MainForm.Left = MachineStuff.PrimaryScreenBounds.Left + ((MachineStuff.PrimaryScreenBounds.Right - MachineStuff.PrimaryScreenBounds.Left) / 2) - 2; + MainForm.Top = Setting.Values.HideMouse ? 3 : MachineStuff.PrimaryScreenBounds.Top + ((MachineStuff.PrimaryScreenBounds.Bottom - MachineStuff.PrimaryScreenBounds.Top) / 2) - 1; MainForm.Width = 3; MainForm.Height = 3; MainForm.Opacity = 0.11D; @@ -230,8 +230,8 @@ namespace MouseWithoutBorders { _ = Common.SendMessageToHelper(0x408, IntPtr.Zero, IntPtr.Zero, false); - MainForm.Left = Common.PrimaryScreenBounds.Left + ((Common.PrimaryScreenBounds.Right - Common.PrimaryScreenBounds.Left) / 2) - 1; - MainForm.Top = Setting.Values.HideMouse ? 3 : Common.PrimaryScreenBounds.Top + ((Common.PrimaryScreenBounds.Bottom - Common.PrimaryScreenBounds.Top) / 2); + MainForm.Left = MachineStuff.PrimaryScreenBounds.Left + ((MachineStuff.PrimaryScreenBounds.Right - MachineStuff.PrimaryScreenBounds.Left) / 2) - 1; + MainForm.Top = Setting.Values.HideMouse ? 3 : MachineStuff.PrimaryScreenBounds.Top + ((MachineStuff.PrimaryScreenBounds.Bottom - MachineStuff.PrimaryScreenBounds.Top) / 2); MainForm.Width = 1; MainForm.Height = 1; MainForm.Opacity = 0.15; @@ -381,7 +381,7 @@ namespace MouseWithoutBorders log += $"{Setting.Values.Username}/{GetDebugInfo(MyKey)}\r\n"; log += $"{MachineName}/{MachineID}/{DesMachineID}\r\n"; log += $"Id: {Setting.Values.DeviceId}\r\n"; - log += $"Matrix: {string.Join(",", MachineMatrix)}\r\n"; + log += $"Matrix: {string.Join(",", MachineStuff.MachineMatrix)}\r\n"; log += $"McPool: {Setting.Values.MachinePoolString}\r\n"; log += "\r\nOPTIONS:\r\n"; diff --git a/src/modules/MouseWithoutBorders/App/Class/Common.InitAndCleanup.cs b/src/modules/MouseWithoutBorders/App/Class/Common.InitAndCleanup.cs index b733e17830..0b2b651060 100644 --- a/src/modules/MouseWithoutBorders/App/Class/Common.InitAndCleanup.cs +++ b/src/modules/MouseWithoutBorders/App/Class/Common.InitAndCleanup.cs @@ -46,7 +46,7 @@ namespace MouseWithoutBorders internal static void UpdateMachineTimeAndID() { Common.MachineName = Common.MachineName.Trim(); - _ = Common.MachinePool.TryUpdateMachineID(Common.MachineName, Common.MachineID, true); + _ = MachineStuff.MachinePool.TryUpdateMachineID(Common.MachineName, Common.MachineID, true); } private static void InitializeMachinePoolFromSettings() @@ -59,13 +59,13 @@ namespace MouseWithoutBorders info[i].Name = info[i].Name.Trim(); } - Common.MachinePool.Initialize(info); - Common.MachinePool.ResetIPAddressesForDeadMachines(true); + MachineStuff.MachinePool.Initialize(info); + MachineStuff.MachinePool.ResetIPAddressesForDeadMachines(true); } catch (Exception ex) { Logger.Log(ex); - Common.MachinePool.Clear(); + MachineStuff.MachinePool.Clear(); } } @@ -74,16 +74,16 @@ namespace MouseWithoutBorders try { GetMachineName(); - DesMachineID = NewDesMachineID = MachineID; + DesMachineID = MachineStuff.NewDesMachineID = MachineID; // MessageBox.Show(machineID.ToString(CultureInfo.CurrentCulture)); // For test InitializeMachinePoolFromSettings(); Common.MachineName = Common.MachineName.Trim(); - _ = Common.MachinePool.LearnMachine(Common.MachineName); - _ = Common.MachinePool.TryUpdateMachineID(Common.MachineName, Common.MachineID, true); + _ = MachineStuff.MachinePool.LearnMachine(Common.MachineName); + _ = MachineStuff.MachinePool.TryUpdateMachineID(Common.MachineName, Common.MachineID, true); - Common.UpdateMachinePoolStringSetting(); + MachineStuff.UpdateMachinePoolStringSetting(); } catch (Exception e) { @@ -154,7 +154,7 @@ namespace MouseWithoutBorders { Logger.TelemetryLogTrace($"{nameof(SystemEvents_PowerModeChanged)}: {e.Mode}", SeverityLevel.Information); LastResumeSuspendTime = DateTime.UtcNow; - SwitchToMultipleMode(false, true); + MachineStuff.SwitchToMultipleMode(false, true); } } diff --git a/src/modules/MouseWithoutBorders/App/Class/Common.MachineStuff.cs b/src/modules/MouseWithoutBorders/App/Class/Common.MachineStuff.cs deleted file mode 100644 index cbf11ca16e..0000000000 --- a/src/modules/MouseWithoutBorders/App/Class/Common.MachineStuff.cs +++ /dev/null @@ -1,1136 +0,0 @@ -// Copyright (c) Microsoft Corporation -// The Microsoft Corporation licenses this file to you under the MIT license. -// See the LICENSE file in the project root for more information. - -using System; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; -using System.Drawing; -using System.Globalization; -using System.Linq; -using System.Threading; -using System.Windows.Forms; - -using Microsoft.PowerToys.Telemetry; - -// -// Machine setup/switching implementation. -// -// -// 2008 created by Truong Do (ductdo). -// 2009-... modified by Truong Do (TruongDo). -// 2023- Included in PowerToys. -// -using MouseWithoutBorders.Class; -using MouseWithoutBorders.Core; - -namespace MouseWithoutBorders -{ - internal struct MachineInf - { - internal string Name; - internal ID Id; - internal long Time; - } - - internal class MyRectangle - { - internal int Left; - internal int Top; - internal int Right; - internal int Bottom; - } - - internal partial class Common - { - private static readonly Lock McMatrixLock = new(); - - internal const byte MAX_MACHINE = 4; - internal const byte MAX_SOCKET = MAX_MACHINE * 2; - internal const long HEARTBEAT_TIMEOUT = 1500000; // 30 Mins - private const int SKIP_PIXELS = 1; - private const int JUMP_PIXELS = 2; - -#pragma warning disable SA1307 // Accessible fields should begin with upper-case letter - internal static ID desMachineID; -#pragma warning restore SA1307 - internal static string DesMachineName = string.Empty; - private static ID newDesMachineID; -#pragma warning disable SA1307 // Accessible fields should begin with upper-case letter - internal static ID newDesMachineIdEx; -#pragma warning restore SA1307 - private static ID dropMachineID; - - private static long lastJump = Common.GetTick(); - private static MyRectangle desktopBounds = new(); - private static MyRectangle primaryScreenBounds = new(); - private static MachinePool _machinePool; - - internal static MachinePool MachinePool - { - get - { - _machinePool ??= new MachinePool(); - return _machinePool; - } - } - - internal static MyRectangle PrimaryScreenBounds => Common.primaryScreenBounds; - - internal static MouseLocation SwitchLocation = new(); - - internal static ID NewDesMachineID - { - get => Common.newDesMachineID; - set => Common.newDesMachineID = value; - } - - internal static MyRectangle DesktopBounds => Common.desktopBounds; - -#if OLD_VERSION - static bool MoveToMyNeighbourIfNeeded(int x, int y) - { - if (Math.Abs(x) > 10) LastX = x; - if (Math.Abs(y) > 10) LastY = y; - if (GetTick() - lastJump < 500 || desMachineID == IP.ALL) return false; - if (desMachineID == machineID) - { - if (x < desktopBounds.Left + skipPixels) return MoveLeft(x, y, x - desktopBounds.Left, 0); - } - else - { - if (x < primaryScreenBounds.Left + skipPixels) - { - if (MoveLeft(x, y, x - primaryScreenBounds.Left, 0)) - { - return true; - } - else - { - if (desktopBounds.Left < primaryScreenBounds.Left) - { - RequestedX_Ex = primaryScreenBounds.Left; - RequestedY_Ex = y; - return true; - } - } - } - } - - if (desMachineID == machineID) - { - if (x > desktopBounds.Right - skipPixels) return MoveRight(x, y, x - desktopBounds.Right, 0); - } - else - { - if (x > primaryScreenBounds.Right - skipPixels) - { - if (MoveRight(x, y, x - primaryScreenBounds.Right, 0)) - { - return true; - } - else - { - if (desktopBounds.Right > primaryScreenBounds.Right) - { - RequestedX_Ex = primaryScreenBounds.Right; - RequestedY_Ex = y; - return true; - } - } - } - } - - if (desMachineID == machineID) - { - if (y < desktopBounds.Top + skipPixels) return MoveUp(x, y, 0, y - desktopBounds.Top); - } - else - { - if (y < primaryScreenBounds.Top + skipPixels) - { - if (MoveUp(x, y, 0, y - primaryScreenBounds.Top)) - { - return true; - } - else - { - if (desktopBounds.Top < primaryScreenBounds.Top) - { - RequestedX_Ex = x; - RequestedY_Ex = primaryScreenBounds.Top; - return true; - } - } - } - } - - if (desMachineID == machineID) - { - if (y > desktopBounds.Bottom - skipPixels) return MoveDown(x, y, 0, y - desktopBounds.Bottom); - } - else - { - if (y > primaryScreenBounds.Bottom - skipPixels) - { - if (MoveDown(x, y, 0, y - primaryScreenBounds.Bottom)) - { - return true; - } - else - { - if (desktopBounds.Bottom > primaryScreenBounds.Bottom) - { - RequestedX_Ex = x; - RequestedY_Ex = primaryScreenBounds.Bottom; - return true; - } - } - } - } - - return false; - } -#else - - private static Point ConvertToUniversalValue(Point p, MyRectangle r) - { - if (!p.IsEmpty) - { - p.X = (p.X - r.Left) * 65535 / (r.Right - r.Left); - p.Y = (p.Y - r.Top) * 65535 / (r.Bottom - r.Top); - } - - return p; - } - - /* Let's say we have 3 machines A, B, and C. A is the controller machine. - * (x, y) is the current Mouse position in pixel. - * If Setting.Values.MoveMouseRelatively then (x, y) can be from any machine having the value bounded by desktopBounds (can be negative) - * Else (x, y) is from the controller machine which is bounded by ONLY primaryScreenBounds (>=0); - * - * The return point is from 0 to 65535 which is then mapped to the desktop of the new controlled machine by the SendInput method. - * Let's say user is switching from machine B to machine C: - * If Setting.Values.MoveMouseRelatively the this method is called by B and the return point is calculated by B and sent back to A, A will use it to move Mouse to the right position when switching to C. - * Else this method is called by A and the return point is calculated by A. - * */ - - internal static Point MoveToMyNeighbourIfNeeded(int x, int y, ID desMachineID) - { - newDesMachineIdEx = desMachineID; - - if (Math.Abs(x) > 10) - { - LastX = x; - } - - if (Math.Abs(y) > 10) - { - LastY = y; - } - - if ((GetTick() - lastJump < 100) || desMachineID == ID.ALL) - { - return Point.Empty; - } - - if (Setting.Values.BlockMouseAtCorners) - { - lock (SensitivePoints) - { - foreach (Point p in SensitivePoints) - { - if (Math.Abs(p.X - x) < 100 && Math.Abs(p.Y - y) < 100) - { - return Point.Empty; - } - } - } - } - - /* If Mouse is moving in the controller machine and this method is called by the controller machine. - * Or if Mouse is moving in the controlled machine and this method is called by the controlled machine and Setting.Values.MoveMouseRelative. - * */ - if (desMachineID == MachineID) - { - if (x < desktopBounds.Left + SKIP_PIXELS) - { - return MoveLeft(x, y); - } - else if (x >= desktopBounds.Right - SKIP_PIXELS) - { - return MoveRight(x, y); - } - else if (y < desktopBounds.Top + SKIP_PIXELS) - { - return MoveUp(x, y); - } - else if (y >= desktopBounds.Bottom - SKIP_PIXELS) - { - return MoveDown(x, y); - } - } - - /* If Mouse is moving in the controlled machine and this method is called by the controller machine and !Setting.Values.MoveMouseRelative. - * Mouse location is scaled from the primary screen bound of the controller machine regardless of how many monitors the controlled machine may have. - * */ - else - { - if (x < primaryScreenBounds.Left + SKIP_PIXELS) - { - return MoveLeft(x, y); - } - else if (x >= primaryScreenBounds.Right - SKIP_PIXELS) - { - return MoveRight(x, y); - } - else if (y < primaryScreenBounds.Top + SKIP_PIXELS) - { - return MoveUp(x, y); - } - else if (y >= primaryScreenBounds.Bottom - SKIP_PIXELS) - { - return MoveDown(x, y); - } - } - - return Point.Empty; - } - -#endif - - [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "Dotnet port with style preservation")] - private static Point MoveRight(int x, int y) - { - string[] mc = LiveMachineMatrix; - if (mc == null) - { - return Point.Empty; - } - - bool oneRow = Setting.Values.MatrixOneRow; - - string currentMachine = NameFromID(desMachineID); - if (currentMachine == null) - { - return Point.Empty; - } - - ID newID; - if (oneRow) - { - bool found = false; - for (int i = 0; i < MAX_MACHINE; i++) - { - if (currentMachine.Trim().Equals(mc[i], StringComparison.OrdinalIgnoreCase)) - { - for (int j = i; j < MAX_MACHINE - 1; j++) - { - if (mc[j + 1] != null && mc[j + 1].Length > 0) - { - if ((newID = IdFromName(mc[j + 1])) > 0) - { - newDesMachineIdEx = newID; - found = true; - break; - } - } - } - - if (!found && Setting.Values.MatrixCircle) - { - for (int j = 0; j < i; j++) - { - if (mc[j] != null && mc[j].Length > 0) - { - if ((newID = IdFromName(mc[j])) > 0) - { - newDesMachineIdEx = newID; - break; - } - } - } - } - - break; - } - } - } - else - { - if (currentMachine.Trim().Equals(mc[0], StringComparison.OrdinalIgnoreCase) && (mc[1] != null) - && (mc[1].Length > 0)) - { - if ((newID = IdFromName(mc[1])) > 0) - { - newDesMachineIdEx = newID; - } - } - else if (currentMachine.Trim().Equals(mc[2], StringComparison.OrdinalIgnoreCase) && (mc[3] != null) - && (mc[3].Length > 0)) - { - if ((newID = IdFromName(mc[3])) > 0) - { - newDesMachineIdEx = newID; - } - } - else if (Setting.Values.MatrixCircle && currentMachine.Trim().Equals(mc[1], StringComparison.OrdinalIgnoreCase) && (mc[0] != null) - && (mc[0].Length > 0)) - { - if ((newID = IdFromName(mc[0])) > 0) - { - newDesMachineIdEx = newID; - } - } - else if (Setting.Values.MatrixCircle && currentMachine.Trim().Equals(mc[3], StringComparison.OrdinalIgnoreCase) && (mc[2] != null) - && (mc[2].Length > 0)) - { - if ((newID = IdFromName(mc[2])) > 0) - { - newDesMachineIdEx = newID; - } - } - } - - // THIS LOGIC IS THE SAME FOR Move*(int x, int y) METHODS. - if (newDesMachineIdEx != desMachineID) - { - Logger.LogDebug("Move Right"); - - if (!Setting.Values.MoveMouseRelatively) - { - if (newDesMachineIdEx == MachineID) - { - /* Switching back to the controller machine, we need to scale up to the desktopBounds from primaryScreenBounds (sine !Setting.Values.MoveMouseRelatively). - * primaryScreenBounds => 65535 => desktopBounds, so that the Mouse position is mapped to the right position when the controller machine has multiple monitors. - * */ - return ConvertToUniversalValue(new Point(primaryScreenBounds.Left + JUMP_PIXELS, y), primaryScreenBounds); - } - else - { - if (desMachineID == MachineID) - { - /* Switching FROM the controller machine, since Mouse was not bounded/locked to the primary screen, - * Mouse position can just be mapped from desktopBounds to desktopBounds - * desktopBounds => 65535 => desktopBounds. - * */ - return ConvertToUniversalValue(new Point(desktopBounds.Left + JUMP_PIXELS, y), desktopBounds); - } - else - { - /* Switching between two machines where non of them is the controller machine. - * Since the current Mouse position is "mapped" from the primary monitor of the controller machine, - * new Mouse position for the new controlled machine needs to be calculated from this as well. - * primaryScreenBounds => 65535 => desktopBounds - * */ - return ConvertToUniversalValue(new Point(primaryScreenBounds.Left + JUMP_PIXELS, y), primaryScreenBounds); - } - } - } - else - { - /* In the case where Mouse is moved relatively, Mouse position is simply mapped from desktopBounds to desktopBounds. - * desktopBounds => 65535 => desktopBounds. - * */ - return ConvertToUniversalValue(new Point(desktopBounds.Left + JUMP_PIXELS, y), desktopBounds); - } - } - - return Point.Empty; - } - - [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "Dotnet port with style preservation")] - private static Point MoveLeft(int x, int y) - { - string[] mc = LiveMachineMatrix; - if (mc == null) - { - return Point.Empty; - } - - bool oneRow = Setting.Values.MatrixOneRow; - - string currentMachine = NameFromID(desMachineID); - if (currentMachine == null) - { - return Point.Empty; - } - - ID newID; - if (oneRow) - { - bool found = false; - for (int i = MAX_MACHINE - 1; i >= 0; i--) - { - if (currentMachine.Trim().Equals(mc[i], StringComparison.OrdinalIgnoreCase)) - { - for (int j = i; j > 0; j--) - { - if (mc[j - 1] != null && mc[j - 1].Length > 0) - { - if ((newID = IdFromName(mc[j - 1])) != ID.NONE) - { - newDesMachineIdEx = newID; - found = true; - break; - } - } - } - - if (!found && Setting.Values.MatrixCircle) - { - for (int j = MAX_MACHINE - 1; j > i; j--) - { - if (mc[j] != null && mc[j].Length > 0) - { - if ((newID = IdFromName(mc[j])) != ID.NONE) - { - newDesMachineIdEx = newID; - break; - } - } - } - } - - break; - } - } - } - else - { - if (currentMachine.Trim().Equals(mc[1], StringComparison.OrdinalIgnoreCase) && (mc[0] != null) - && (mc[0].Length > 0)) - { - if ((newID = IdFromName(mc[0])) != ID.NONE) - { - newDesMachineIdEx = newID; - } - } - else if (currentMachine.Trim().Equals(mc[3], StringComparison.OrdinalIgnoreCase) && (mc[2] != null) - && (mc[2].Length > 0)) - { - if ((newID = IdFromName(mc[2])) != ID.NONE) - { - newDesMachineIdEx = newID; - } - } - else if (Setting.Values.MatrixCircle && currentMachine.Trim().Equals(mc[0], StringComparison.OrdinalIgnoreCase) && (mc[1] != null) - && (mc[1].Length > 0)) - { - if ((newID = IdFromName(mc[1])) != ID.NONE) - { - newDesMachineIdEx = newID; - } - } - else if (Setting.Values.MatrixCircle && currentMachine.Trim().Equals(mc[2], StringComparison.OrdinalIgnoreCase) && (mc[3] != null) - && (mc[3].Length > 0)) - { - if ((newID = IdFromName(mc[3])) != ID.NONE) - { - newDesMachineIdEx = newID; - } - } - } - - if (newDesMachineIdEx != desMachineID) - { - Logger.LogDebug("Move Left"); - - return !Setting.Values.MoveMouseRelatively - ? newDesMachineIdEx == MachineID - ? ConvertToUniversalValue(new Point(primaryScreenBounds.Right - JUMP_PIXELS, y), primaryScreenBounds) - : desMachineID == MachineID - ? ConvertToUniversalValue(new Point(desktopBounds.Right - JUMP_PIXELS, y), desktopBounds) - : ConvertToUniversalValue(new Point(primaryScreenBounds.Right - JUMP_PIXELS, y), primaryScreenBounds) - : ConvertToUniversalValue(new Point(desktopBounds.Right - JUMP_PIXELS, y), desktopBounds); - } - - return Point.Empty; - } - - private static Point MoveUp(int x, int y) - { - if (Setting.Values.MatrixOneRow) - { - return Point.Empty; - } - - string[] mc = LiveMachineMatrix; - if (mc == null) - { - return Point.Empty; - } - - string currentMachine = NameFromID(desMachineID); - if (currentMachine == null) - { - return Point.Empty; - } - - ID newID; - if (currentMachine.Trim().Equals(mc[2], StringComparison.OrdinalIgnoreCase) && (mc[0] != null) - && (mc[0].Length > 0)) - { - if ((newID = IdFromName(mc[0])) != ID.NONE) - { - newDesMachineIdEx = newID; - } - } - else if (currentMachine.Trim().Equals(mc[3], StringComparison.OrdinalIgnoreCase) && (mc[1] != null) - && (mc[1].Length > 0)) - { - if ((newID = IdFromName(mc[1])) != ID.NONE) - { - newDesMachineIdEx = newID; - } - } - else if (Setting.Values.MatrixCircle && currentMachine.Trim().Equals(mc[0], StringComparison.OrdinalIgnoreCase) && (mc[2] != null) - && (mc[2].Length > 0)) - { - if ((newID = IdFromName(mc[2])) != ID.NONE) - { - newDesMachineIdEx = newID; - } - } - else if (Setting.Values.MatrixCircle && currentMachine.Trim().Equals(mc[1], StringComparison.OrdinalIgnoreCase) && (mc[3] != null) - && (mc[3].Length > 0)) - { - if ((newID = IdFromName(mc[3])) != ID.NONE) - { - newDesMachineIdEx = newID; - } - } - - if (newDesMachineIdEx != desMachineID) - { - Logger.LogDebug("Move Up"); - - return !Setting.Values.MoveMouseRelatively - ? newDesMachineIdEx == MachineID - ? ConvertToUniversalValue(new Point(x, primaryScreenBounds.Bottom - JUMP_PIXELS), primaryScreenBounds) - : desMachineID == MachineID - ? ConvertToUniversalValue(new Point(x, desktopBounds.Bottom - JUMP_PIXELS), desktopBounds) - : ConvertToUniversalValue(new Point(x, primaryScreenBounds.Bottom - JUMP_PIXELS), primaryScreenBounds) - : ConvertToUniversalValue(new Point(x, desktopBounds.Bottom - JUMP_PIXELS), desktopBounds); - } - - return Point.Empty; - } - - private static Point MoveDown(int x, int y) - { - if (Setting.Values.MatrixOneRow) - { - return Point.Empty; - } - - string[] mc = LiveMachineMatrix; - if (mc == null) - { - return Point.Empty; - } - - string currentMachine = NameFromID(desMachineID); - if (currentMachine == null) - { - return Point.Empty; - } - - ID newID; - if (currentMachine.Trim().Equals(mc[0], StringComparison.OrdinalIgnoreCase) && (mc[2] != null) - && (mc[2].Length > 0)) - { - if ((newID = IdFromName(mc[2])) != ID.NONE) - { - newDesMachineIdEx = newID; - } - } - else if (currentMachine.Trim().Equals(mc[1], StringComparison.OrdinalIgnoreCase) && (mc[3] != null) - && (mc[3].Length > 0)) - { - if ((newID = IdFromName(mc[3])) != ID.NONE) - { - newDesMachineIdEx = newID; - } - } - - if (Setting.Values.MatrixCircle && currentMachine.Trim().Equals(mc[2], StringComparison.OrdinalIgnoreCase) && (mc[0] != null) - && (mc[0].Length > 0)) - { - if ((newID = IdFromName(mc[0])) != ID.NONE) - { - newDesMachineIdEx = newID; - } - } - else if (Setting.Values.MatrixCircle && currentMachine.Trim().Equals(mc[3], StringComparison.OrdinalIgnoreCase) && (mc[1] != null) - && (mc[1].Length > 0)) - { - if ((newID = IdFromName(mc[1])) != ID.NONE) - { - newDesMachineIdEx = newID; - } - } - - if (newDesMachineIdEx != desMachineID) - { - Logger.LogDebug("Move Down"); - - return !Setting.Values.MoveMouseRelatively - ? newDesMachineIdEx == MachineID - ? ConvertToUniversalValue(new Point(x, primaryScreenBounds.Top + JUMP_PIXELS), primaryScreenBounds) - : desMachineID == MachineID - ? ConvertToUniversalValue(new Point(x, desktopBounds.Top + JUMP_PIXELS), desktopBounds) - : ConvertToUniversalValue(new Point(x, primaryScreenBounds.Top + JUMP_PIXELS), primaryScreenBounds) - : ConvertToUniversalValue(new Point(x, desktopBounds.Top + JUMP_PIXELS), desktopBounds); - } - - return Point.Empty; - } - - internal static bool RemoveDeadMachines(ID ip) - { - bool rv = false; - - // Here we are removing a dead machine by IP. - foreach (MachineInf inf in Common.MachinePool.ListAllMachines()) - { - if (inf.Id == ip) - { - if (MachinePool.SetMachineDisconnected(inf.Name)) - { - rv = true; - } - - Logger.LogDebug("<><><><><>>><><><<><><><><><><><><><><>><><><><><><><><><><><" + inf.Name); - } - } - - return rv; - } - - internal static void RemoveDeadMachines() - { - // list of live/dead machines is now automatically up-to-date - // if it changed we need to update the UI. - // for now assume it changed. - // Common.MachinePool.ResetIPAddressesForDeadMachines(); - // DoSomethingInUIThread(UpdateMenu); - Common.UpdateMachinePoolStringSetting(); - - // Make sure MachinePool still holds this machine. - if (Common.MachinePool.LearnMachine(MachineName)) - { - _ = Common.MachinePool.TryUpdateMachineID(MachineName, MachineID, false); - } - } - - internal static string AddToMachinePool(DATA package) - { - // Log("********** AddToMachinePool called: " + package.src.ToString(CultureInfo.InvariantCulture)); - - // There should be no duplicates in machine pool. - string name = package.MachineName; - - // a few things happening here: - // 1) find a matching machine (by name) - // 2) update its ID and time - // 3) logging - // 4) updating some variables - desMachineID/newDesMachineID - // 5) return the matched name (trimmed) - only in the event of a match - if (Common.MachinePool.TryFindMachineByName(name, out MachineInf machineInfo)) - { - _ = Common.MachinePool.TryUpdateMachineID(machineInfo.Name, machineInfo.Id, true); - - _ = Common.MachinePool.TryUpdateMachineID(machineInfo.Name, package.Src, true); - - if (machineInfo.Name.Equals(DesMachineName, StringComparison.OrdinalIgnoreCase)) - { - Logger.LogDebug("AddToMachinePool: Des ID updated: " + DesMachineID.ToString() + "/" + package.Src.ToString()); - newDesMachineID = desMachineID = package.Src; - } - - return machineInfo.Name; - } - else - { - if (Common.MachinePool.LearnMachine(name)) - { - _ = Common.MachinePool.TryUpdateMachineID(name, package.Src, true); - } - else - { - Logger.LogDebug("AddToMachinePool: could not add a new machine: " + name); - return "The 5th machine"; - } - } - - // if (machineCount != saved) - { - // DoSomethingInUIThread(UpdateMenu); - Common.UpdateMachinePoolStringSetting(); - } - - // NOTE(yuyoyuppe): automatically active "bidirectional" control between the machines. - string[] st = new string[Common.MAX_MACHINE]; - Array.Fill(st, string.Empty); - var machines = Common.MachinePool.ListAllMachines(); - for (int i = 0; i < machines.Count; ++i) - { - if (machines[i].Id != ID.NONE && machines[i].Id != ID.ALL) - { - st[i] = machines[i].Name; - } - } - - Common.MachineMatrix = st; - Common.ReopenSockets(true); - Common.SendMachineMatrix(); - - Logger.LogDebug("Machine added: " + name + "/" + package.Src.ToString()); - UpdateClientSockets("AddToMachinePool"); - return name; - } - - internal static void UpdateClientSockets(string logHeader) - { - Logger.LogDebug("UpdateClientSockets: " + logHeader); - Sk?.UpdateTCPClients(); - } - - private static SettingsForm settings; - - internal static SettingsForm Settings - { - get => Common.settings; - set => Common.settings = value; - } - - internal static void ShowSetupForm(bool reopenSockets = false) - { - Logger.LogDebug("========== BEGIN THE SETUP EXPERIENCE ==========", true); - Setting.Values.MyKey = Common.MyKey = Common.CreateRandomKey(); - Common.GeneratedKey = true; - - if (Process.GetCurrentProcess().SessionId != NativeMethods.WTSGetActiveConsoleSessionId()) - { - Logger.Log("Not physical console session."); - _ = MessageBox.Show( - "Please run the program in the physical console session.\r\nThe program does not work in a remote desktop or virtual machine session.", - Application.ProductName, - MessageBoxButtons.OK, - MessageBoxIcon.Stop); - return; - } - - if (settings == null) - { - settings = new SettingsForm(); - settings.Show(); - } - else - { - settings.Close(); - Common.MMSleep(0.3); - settings = new SettingsForm(); - settings.Show(); - } - - if (reopenSockets) - { - Common.ReopenSockets(true); - } - } - - internal static void CloseSetupForm() - { - if (settings != null) - { - settings.Close(); - settings = null; - } - } - - internal static void ShowMachineMatrix() - { - if (!Setting.Values.ShowOriginalUI) - { - return; - } - - if (Process.GetCurrentProcess().SessionId != NativeMethods.WTSGetActiveConsoleSessionId()) - { - Common.ShowToolTip(Application.ProductName + " cannot be used in a remote desktop or virtual machine session.", 5000); - } - -#if NEW_SETTINGS_FORM - Common.ShowSetupForm(); -#else - if (Setting.Values.FirstRun && !Common.AtLeastOneSocketConnected()) - { - Common.ShowSetupForm(); - } - else - { - PowerToysTelemetry.Log.WriteEvent(new MouseWithoutBorders.Telemetry.MouseWithoutBordersOldUIOpenedEvent()); - - if (MatrixForm == null) - { - MatrixForm = new FrmMatrix(); - MatrixForm.Show(); - - if (MainForm != null) - { - MainForm.NotifyIcon.Visible = false; - MainForm.NotifyIcon.Visible = Setting.Values.ShowOriginalUI; - } - } - else - { - MatrixForm.WindowState = FormWindowState.Normal; - MatrixForm.Activate(); - } - } -#endif - } - - private static string[] mcMatrix; - - internal static string[] MachineMatrix - { - get - { - lock (McMatrixLock) - { - if (mcMatrix == null) - { - string s = Setting.Values.MachineMatrixString; - - if (!string.IsNullOrEmpty(s)) - { - mcMatrix = s.Split(new char[] { ',' }); - - if (mcMatrix == null || mcMatrix.Length != MAX_MACHINE) - { - mcMatrix = new string[MAX_MACHINE] { string.Empty, string.Empty, string.Empty, string.Empty }; - } - } - else - { - mcMatrix = new string[MAX_MACHINE] { string.Empty, string.Empty, string.Empty, string.Empty }; - } - } - - return mcMatrix; - } - } - - set - { - lock (McMatrixLock) - { - if (value == null) - { - mcMatrix = null; // Force read from registry next time. - return; - } - else - { - Setting.Values.MachineMatrixString = string.Join(",", mcMatrix = value); - } - } - - DoSomethingInUIThread(() => - { - MainForm.ChangeIcon(-1); - MainForm.UpdateNotifyIcon(); - }); - } - } - - private static string[] LiveMachineMatrix - { - get - { - bool twoRow = !Setting.Values.MatrixOneRow; - string[] connectedMachines = twoRow ? MachineMatrix : MachineMatrix.Select(m => IsConnectedTo(IdFromName(m)) ? m : string.Empty).ToArray(); - Logger.LogDebug($"Matrix: {string.Join(",", MachineMatrix)}, Connected: {string.Join(",", connectedMachines)}"); - - return connectedMachines; - } - } - - internal static void UpdateMachinePoolStringSetting() - { - Setting.Values.MachinePoolString = Common.MachinePool.SerializedAsString(); - } - - internal static void SendMachineMatrix() - { - if (MachineMatrix == null) - { - return; - } - - DATA package = new(); - - for (int i = 0; i < MachineMatrix.Length; i++) - { - package.MachineName = MachineMatrix[i]; - - package.Type = PackageType.Matrix - | (Setting.Values.MatrixCircle ? PackageType.MatrixSwapFlag : 0) - | (Setting.Values.MatrixOneRow ? 0 : PackageType.MatrixTwoRowFlag); - - package.Src = (ID)(i + 1); - package.Des = ID.ALL; - - SkSend(package, null, false); - - Logger.LogDebug($"matrixIncludedMachine sent: [{i + 1}]:[{MachineMatrix[i]}]"); - } - } - - internal static void UpdateMachineMatrix(DATA package) - { - uint i = (uint)package.Src; - string matrixIncludedMachine = package.MachineName; - - if (i is > 0 and <= MAX_MACHINE) - { - Logger.LogDebug($"matrixIncludedMachine: [{i}]:[{matrixIncludedMachine}]"); - - MachineMatrix[i - 1] = matrixIncludedMachine; - - if (i == MAX_MACHINE) - { - Setting.Values.MatrixCircle = (package.Type & PackageType.MatrixSwapFlag) == PackageType.MatrixSwapFlag; - Setting.Values.MatrixOneRow = !((package.Type & PackageType.MatrixTwoRowFlag) == PackageType.MatrixTwoRowFlag); - MachineMatrix = MachineMatrix; // Save - - Common.ReopenSocketDueToReadError = true; - - UpdateClientSockets("UpdateMachineMatrix"); - - Setting.Values.Changed = true; - } - } - else - { - Logger.LogDebug("Invalid machine Matrix package!"); - } - } - - internal static void SwitchToMachine(string name) - { - ID id = Common.MachinePool.ResolveID(name); - - if (id != ID.NONE) - { - // Ask current machine to hide the Mouse cursor - if (desMachineID != MachineID) - { - SendPackage(desMachineID, PackageType.HideMouse); - } - - NewDesMachineID = DesMachineID = id; - SwitchLocation.X = XY_BY_PIXEL + primaryScreenBounds.Left + ((primaryScreenBounds.Right - primaryScreenBounds.Left) / 2); - SwitchLocation.Y = XY_BY_PIXEL + primaryScreenBounds.Top + ((primaryScreenBounds.Bottom - primaryScreenBounds.Top) / 2); - SwitchLocation.ResetCount(); - Common.UpdateMultipleModeIconAndMenu(); - HideMouseCursor(false); - _ = EvSwitch.Set(); - } - } - - internal static void SwitchToMultipleMode(bool multipleMode, bool centerScreen) - { - if (multipleMode) - { - PowerToysTelemetry.Log.WriteEvent(new MouseWithoutBorders.Telemetry.MouseWithoutBordersMultipleModeEvent()); - NewDesMachineID = DesMachineID = ID.ALL; - } - else - { - NewDesMachineID = DesMachineID = MachineID; - } - - if (centerScreen) - { - MoveMouseToCenter(); - } - - ReleaseAllKeys(); - - Common.UpdateMultipleModeIconAndMenu(); - } - - internal static bool CheckSecondInstance(bool sendMessage = false) - { - int h; - - if ((h = NativeMethods.FindWindow(null, Setting.Values.MyID)) > 0) - { - return true; - } - - return false; - } - - private static EventWaitHandle oneInstanceCheck; - - internal static void AssertOneInstancePerDesktopSession() - { - string eventName = $"Global\\{Application.ProductName}-{FrmAbout.AssemblyVersion}-{GetMyDesktop()}-{CurrentProcess.SessionId}"; - oneInstanceCheck = new EventWaitHandle(false, EventResetMode.ManualReset, eventName, out bool created); - - if (!created) - { - Logger.TelemetryLogTrace($"Second instance found: {eventName}.", SeverityLevel.Warning, true); - CurrentProcess.KillProcess(true); - } - } - - internal static ID IdFromName(string name) - { - return Common.MachinePool.ResolveID(name); - } - - internal static string NameFromID(ID id) - { - foreach (MachineInf inf in Common.MachinePool.TryFindMachineByID(id)) - { - if (!string.IsNullOrEmpty(inf.Name)) - { - return inf.Name; - } - } - - return null; - } - - internal static bool InMachineMatrix(string name) - { - if (MachineMatrix == null || string.IsNullOrWhiteSpace(name)) - { - return false; - } - - foreach (string st in MachineMatrix) - { - if (!string.IsNullOrWhiteSpace(st) && st.Trim().Equals(name.Trim(), StringComparison.OrdinalIgnoreCase)) - { - return true; - } - } - - return false; - } - - internal static void ClearComputerMatrix() - { - Common.MachineMatrix = new string[Common.MAX_MACHINE] { Common.MachineName.Trim(), string.Empty, string.Empty, string.Empty }; - Common.MachinePool.Initialize(new string[] { Common.MachineName }); - Common.UpdateMachinePoolStringSetting(); - } - } -} diff --git a/src/modules/MouseWithoutBorders/App/Class/Common.WinAPI.cs b/src/modules/MouseWithoutBorders/App/Class/Common.WinAPI.cs index 006c5d862c..f1190a7cc7 100644 --- a/src/modules/MouseWithoutBorders/App/Class/Common.WinAPI.cs +++ b/src/modules/MouseWithoutBorders/App/Class/Common.WinAPI.cs @@ -41,7 +41,7 @@ namespace MouseWithoutBorders GetScreenConfig(); } - private static readonly List SensitivePoints = new(); + internal static readonly List SensitivePoints = new(); private static bool MonitorEnumProc(IntPtr hMonitor, IntPtr hdcMonitor, ref NativeMethods.RECT lprcMonitor, IntPtr dwData) { @@ -162,21 +162,21 @@ namespace MouseWithoutBorders // 1000 calls to EnumDisplayMonitors cost a dozen of milliseconds #endif - Interlocked.Exchange(ref desktopBounds, newDesktopBounds); - Interlocked.Exchange(ref primaryScreenBounds, newPrimaryScreenBounds); + Interlocked.Exchange(ref MachineStuff.desktopBounds, newDesktopBounds); + Interlocked.Exchange(ref MachineStuff.primaryScreenBounds, newPrimaryScreenBounds); Logger.Log(string.Format( CultureInfo.CurrentCulture, "logon = {0} PrimaryScreenBounds = {1},{2},{3},{4} desktopBounds = {5},{6},{7},{8}", Common.RunOnLogonDesktop, - Common.PrimaryScreenBounds.Left, - Common.PrimaryScreenBounds.Top, - Common.PrimaryScreenBounds.Right, - Common.PrimaryScreenBounds.Bottom, - Common.DesktopBounds.Left, - Common.DesktopBounds.Top, - Common.DesktopBounds.Right, - Common.DesktopBounds.Bottom)); + MachineStuff.PrimaryScreenBounds.Left, + MachineStuff.PrimaryScreenBounds.Top, + MachineStuff.PrimaryScreenBounds.Right, + MachineStuff.PrimaryScreenBounds.Bottom, + MachineStuff.DesktopBounds.Left, + MachineStuff.DesktopBounds.Top, + MachineStuff.DesktopBounds.Right, + MachineStuff.DesktopBounds.Bottom)); Logger.Log("==================== GetScreenConfig ended"); } diff --git a/src/modules/MouseWithoutBorders/App/Class/Common.cs b/src/modules/MouseWithoutBorders/App/Class/Common.cs index 1131893ec4..40699b355b 100644 --- a/src/modules/MouseWithoutBorders/App/Class/Common.cs +++ b/src/modules/MouseWithoutBorders/App/Class/Common.cs @@ -112,7 +112,7 @@ namespace MouseWithoutBorders internal const int JUST_GOT_BACK_FROM_SCREEN_SAVER = 9999; internal const int NETWORK_STREAM_BUF_SIZE = 1024 * 1024; - private static readonly EventWaitHandle EvSwitch = new(false, EventResetMode.AutoReset); + internal static readonly EventWaitHandle EvSwitch = new(false, EventResetMode.AutoReset); private static Point lastPos; private static int switchCount; private static long lastReconnectByHotKeyTime; @@ -236,12 +236,12 @@ namespace MouseWithoutBorders internal static ID DesMachineID { - get => Common.desMachineID; + get => MachineStuff.desMachineID; set { - Common.desMachineID = value; - Common.DesMachineName = Common.NameFromID(Common.desMachineID); + MachineStuff.desMachineID = value; + MachineStuff.DesMachineName = MachineStuff.NameFromID(MachineStuff.desMachineID); } } @@ -351,7 +351,7 @@ namespace MouseWithoutBorders Logger.TelemetryLogTrace($"[{actionName}] took more than {(long)timeout.TotalSeconds}, restarting the process.", SeverityLevel.Warning, true); string desktop = Common.GetMyDesktop(); - oneInstanceCheck?.Close(); + MachineStuff.oneInstanceCheck?.Close(); _ = Process.Start(Application.ExecutablePath, desktop); Logger.LogDebug($"Started on desktop {desktop}"); @@ -619,12 +619,12 @@ namespace MouseWithoutBorders internal static void ProcessByeByeMessage(DATA package) { - if (package.Src == desMachineID) + if (package.Src == MachineStuff.desMachineID) { - SwitchToMachine(MachineName.Trim()); + MachineStuff.SwitchToMachine(MachineName.Trim()); } - _ = RemoveDeadMachines(package.Src); + _ = MachineStuff.RemoveDeadMachines(package.Src); } internal static long GetTick() // ms @@ -644,12 +644,12 @@ namespace MouseWithoutBorders try { string fileName = GetMyStorageDir() + @"ScreenCaptureByMouseWithoutBorders.png"; - int w = desktopBounds.Right - desktopBounds.Left; - int h = desktopBounds.Bottom - desktopBounds.Top; + int w = MachineStuff.desktopBounds.Right - MachineStuff.desktopBounds.Left; + int h = MachineStuff.desktopBounds.Bottom - MachineStuff.desktopBounds.Top; Bitmap bm = new(w, h); Graphics g = Graphics.FromImage(bm); Size s = new(w, h); - g.CopyFromScreen(desktopBounds.Left, desktopBounds.Top, 0, 0, s); + g.CopyFromScreen(MachineStuff.desktopBounds.Left, MachineStuff.desktopBounds.Top, 0, 0, s); bm.Save(fileName, ImageFormat.Png); bm.Dispose(); return fileName; @@ -665,7 +665,7 @@ namespace MouseWithoutBorders { Common.DoSomethingInUIThread(() => { - if (!MouseDown && Common.SendMessageToHelper(0x401, IntPtr.Zero, IntPtr.Zero) > 0) + if (!DragDrop.MouseDown && Common.SendMessageToHelper(0x401, IntPtr.Zero, IntPtr.Zero) > 0) { Common.MMSleep(0.2); InputSimulation.SendKey(new KEYBDDATA() { wVk = (int)VK.SNAPSHOT }); @@ -675,10 +675,10 @@ namespace MouseWithoutBorders _ = NativeMethods.MoveWindow( (IntPtr)NativeMethods.FindWindow(null, Common.HELPER_FORM_TEXT), - Common.DesktopBounds.Left, - Common.DesktopBounds.Top, - Common.DesktopBounds.Right - Common.DesktopBounds.Left, - Common.DesktopBounds.Bottom - Common.DesktopBounds.Top, + MachineStuff.DesktopBounds.Left, + MachineStuff.DesktopBounds.Top, + MachineStuff.DesktopBounds.Right - MachineStuff.DesktopBounds.Left, + MachineStuff.DesktopBounds.Bottom - MachineStuff.DesktopBounds.Top, false); _ = Common.SendMessageToHelper(0x406, IntPtr.Zero, IntPtr.Zero, false); @@ -729,7 +729,7 @@ namespace MouseWithoutBorders } else { - ID id = Common.MachinePool.ResolveID(machine); + ID id = MachineStuff.MachinePool.ResolveID(machine); if (id != ID.NONE) { SendPackage(id, PackageType.ClipboardCapture); @@ -753,7 +753,7 @@ namespace MouseWithoutBorders { if (Setting.Values.FirstRun) { - Common.Settings?.ShowTip(icon, tip, timeOutInMilliseconds); + MachineStuff.Settings?.ShowTip(icon, tip, timeOutInMilliseconds); } Common.MatrixForm?.ShowTip(icon, tip, timeOutInMilliseconds); @@ -882,7 +882,7 @@ namespace MouseWithoutBorders if (updateClientSockets) { - UpdateClientSockets(nameof(IsConnectedTo)); + MachineStuff.UpdateClientSockets(nameof(IsConnectedTo)); } return false; @@ -921,7 +921,7 @@ namespace MouseWithoutBorders { if (t != null && t.BackingSocket != null && (t.Status == SocketStatus.Connected || (t.Status == SocketStatus.Handshaking && includeHandShakingSockets))) { - if (t.MachineId == (uint)data.Des || (data.Des == ID.ALL && t.MachineId != exceptDes && InMachineMatrix(t.MachineName))) + if (t.MachineId == (uint)data.Des || (data.Des == ID.ALL && t.MachineId != exceptDes && MachineStuff.InMachineMatrix(t.MachineName))) { try { @@ -952,20 +952,20 @@ namespace MouseWithoutBorders { Logger.LogDebug("********** No active connection found for the remote machine! **********" + data.Des.ToString()); - if (data.Des == ID.NONE || RemoveDeadMachines(data.Des)) + if (data.Des == ID.NONE || MachineStuff.RemoveDeadMachines(data.Des)) { // SwitchToMachine(MachineName.Trim()); - NewDesMachineID = DesMachineID = MachineID; - SwitchLocation.X = XY_BY_PIXEL + myLastX; - SwitchLocation.Y = XY_BY_PIXEL + myLastY; - SwitchLocation.ResetCount(); + MachineStuff.NewDesMachineID = DesMachineID = MachineID; + MachineStuff.SwitchLocation.X = XY_BY_PIXEL + myLastX; + MachineStuff.SwitchLocation.Y = XY_BY_PIXEL + myLastY; + MachineStuff.SwitchLocation.ResetCount(); EvSwitch.Set(); } } if (updateClientSockets) { - UpdateClientSockets("SkSend"); + MachineStuff.UpdateClientSockets("SkSend"); } } catch (Exception e) @@ -1203,7 +1203,7 @@ namespace MouseWithoutBorders { int machineCt = 0; - foreach (string m in Common.MachineMatrix) + foreach (string m in MachineStuff.MachineMatrix) { if (!string.IsNullOrEmpty(m.Trim())) { @@ -1211,15 +1211,15 @@ namespace MouseWithoutBorders } } - if (machineCt < 2 && Common.Settings != null && (Common.Settings.GetCurrentPage() is SetupPage1 || Common.Settings.GetCurrentPage() is SetupPage2b)) + if (machineCt < 2 && MachineStuff.Settings != null && (MachineStuff.Settings.GetCurrentPage() is SetupPage1 || MachineStuff.Settings.GetCurrentPage() is SetupPage2b)) { - Common.MachineMatrix = new string[Common.MAX_MACHINE] { Common.MachineName.Trim(), desMachine, string.Empty, string.Empty }; - Logger.LogDebug("UpdateSetupMachineMatrix: " + string.Join(",", Common.MachineMatrix)); + MachineStuff.MachineMatrix = new string[MachineStuff.MAX_MACHINE] { Common.MachineName.Trim(), desMachine, string.Empty, string.Empty }; + Logger.LogDebug("UpdateSetupMachineMatrix: " + string.Join(",", MachineStuff.MachineMatrix)); Common.DoSomethingInUIThread( () => { - Common.Settings.SetControlPage(new SetupPage4()); + MachineStuff.Settings.SetControlPage(new SetupPage4()); }, true); } @@ -1255,7 +1255,7 @@ namespace MouseWithoutBorders SocketStuff.ClearBadIPs(); } - UpdateClientSockets("ReopenSockets"); + MachineStuff.UpdateClientSockets("ReopenSockets"); } }, true); @@ -1473,17 +1473,17 @@ namespace MouseWithoutBorders { Logger.LogDebug("+++++ MoveMouseToCenter"); InputSimulation.MoveMouse( - Common.PrimaryScreenBounds.Left + ((Common.PrimaryScreenBounds.Right - Common.PrimaryScreenBounds.Left) / 2), - Common.PrimaryScreenBounds.Top + ((Common.PrimaryScreenBounds.Bottom - Common.PrimaryScreenBounds.Top) / 2)); + MachineStuff.PrimaryScreenBounds.Left + ((MachineStuff.PrimaryScreenBounds.Right - MachineStuff.PrimaryScreenBounds.Left) / 2), + MachineStuff.PrimaryScreenBounds.Top + ((MachineStuff.PrimaryScreenBounds.Bottom - MachineStuff.PrimaryScreenBounds.Top) / 2)); } internal static void HideMouseCursor(bool byHideMouseMessage) { Common.LastPos = new Point( - Common.PrimaryScreenBounds.Left + ((Common.PrimaryScreenBounds.Right - Common.PrimaryScreenBounds.Left) / 2), - Setting.Values.HideMouse ? 4 : Common.PrimaryScreenBounds.Top + ((Common.PrimaryScreenBounds.Bottom - Common.PrimaryScreenBounds.Top) / 2)); + MachineStuff.PrimaryScreenBounds.Left + ((MachineStuff.PrimaryScreenBounds.Right - MachineStuff.PrimaryScreenBounds.Left) / 2), + Setting.Values.HideMouse ? 4 : MachineStuff.PrimaryScreenBounds.Top + ((MachineStuff.PrimaryScreenBounds.Bottom - MachineStuff.PrimaryScreenBounds.Top) / 2)); - if ((desMachineID != MachineID && desMachineID != ID.ALL) || byHideMouseMessage) + if ((MachineStuff.desMachineID != MachineID && MachineStuff.desMachineID != ID.ALL) || byHideMouseMessage) { _ = NativeMethods.SetCursorPos(Common.LastPos.X, Common.LastPos.Y); _ = NativeMethods.GetCursorPos(ref Common.lastPos); diff --git a/src/modules/MouseWithoutBorders/App/Class/IClipboardHelper.cs b/src/modules/MouseWithoutBorders/App/Class/IClipboardHelper.cs index 9621c54bc4..9a52f69529 100644 --- a/src/modules/MouseWithoutBorders/App/Class/IClipboardHelper.cs +++ b/src/modules/MouseWithoutBorders/App/Class/IClipboardHelper.cs @@ -154,7 +154,7 @@ namespace MouseWithoutBorders public void SendDragFile(string fileName) { - Common.DragDropStep05Ex(fileName); + DragDrop.DragDropStep05Ex(fileName); } public void SendClipboardData(ByteArrayOrString data, bool isFilePath) diff --git a/src/modules/MouseWithoutBorders/App/Class/InputHook.cs b/src/modules/MouseWithoutBorders/App/Class/InputHook.cs index 59b5974a80..9bd7b5c4bf 100644 --- a/src/modules/MouseWithoutBorders/App/Class/InputHook.cs +++ b/src/modules/MouseWithoutBorders/App/Class/InputHook.cs @@ -222,10 +222,10 @@ namespace MouseWithoutBorders.Class { Common.RealInputEventCount++; - if (Common.NewDesMachineID == Common.MachineID || Common.NewDesMachineID == ID.ALL) + if (MachineStuff.NewDesMachineID == Common.MachineID || MachineStuff.NewDesMachineID == ID.ALL) { local = true; - if (Common.MainFormVisible && !Common.IsDropping) + if (Common.MainFormVisible && !DragDrop.IsDropping) { Common.MainFormDot(); } @@ -265,19 +265,19 @@ namespace MouseWithoutBorders.Class } else { - if (Common.SwitchLocation.Count > 0 && Common.NewDesMachineID != Common.MachineID && Common.NewDesMachineID != ID.ALL) + if (MachineStuff.SwitchLocation.Count > 0 && MachineStuff.NewDesMachineID != Common.MachineID && MachineStuff.NewDesMachineID != ID.ALL) { - Common.SwitchLocation.Count--; + MachineStuff.SwitchLocation.Count--; - if (Common.SwitchLocation.X > Common.XY_BY_PIXEL - 100000 || Common.SwitchLocation.Y > Common.XY_BY_PIXEL - 100000) + if (MachineStuff.SwitchLocation.X > Common.XY_BY_PIXEL - 100000 || MachineStuff.SwitchLocation.Y > Common.XY_BY_PIXEL - 100000) { - hookCallbackMouseData.X = Common.SwitchLocation.X - Common.XY_BY_PIXEL; - hookCallbackMouseData.Y = Common.SwitchLocation.Y - Common.XY_BY_PIXEL; + hookCallbackMouseData.X = MachineStuff.SwitchLocation.X - Common.XY_BY_PIXEL; + hookCallbackMouseData.Y = MachineStuff.SwitchLocation.Y - Common.XY_BY_PIXEL; } else { - hookCallbackMouseData.X = (Common.SwitchLocation.X * Common.ScreenWidth / 65535) + Common.PrimaryScreenBounds.Left; - hookCallbackMouseData.Y = (Common.SwitchLocation.Y * Common.ScreenHeight / 65535) + Common.PrimaryScreenBounds.Top; + hookCallbackMouseData.X = (MachineStuff.SwitchLocation.X * Common.ScreenWidth / 65535) + MachineStuff.PrimaryScreenBounds.Left; + hookCallbackMouseData.Y = (MachineStuff.SwitchLocation.Y * Common.ScreenHeight / 65535) + MachineStuff.PrimaryScreenBounds.Top; } Common.HideMouseCursor(false); @@ -290,22 +290,22 @@ namespace MouseWithoutBorders.Class hookCallbackMouseData.X += dx; hookCallbackMouseData.Y += dy; - if (hookCallbackMouseData.X < Common.PrimaryScreenBounds.Left) + if (hookCallbackMouseData.X < MachineStuff.PrimaryScreenBounds.Left) { - hookCallbackMouseData.X = Common.PrimaryScreenBounds.Left - 1; + hookCallbackMouseData.X = MachineStuff.PrimaryScreenBounds.Left - 1; } - else if (hookCallbackMouseData.X > Common.PrimaryScreenBounds.Right) + else if (hookCallbackMouseData.X > MachineStuff.PrimaryScreenBounds.Right) { - hookCallbackMouseData.X = Common.PrimaryScreenBounds.Right + 1; + hookCallbackMouseData.X = MachineStuff.PrimaryScreenBounds.Right + 1; } - if (hookCallbackMouseData.Y < Common.PrimaryScreenBounds.Top) + if (hookCallbackMouseData.Y < MachineStuff.PrimaryScreenBounds.Top) { - hookCallbackMouseData.Y = Common.PrimaryScreenBounds.Top - 1; + hookCallbackMouseData.Y = MachineStuff.PrimaryScreenBounds.Top - 1; } - else if (hookCallbackMouseData.Y > Common.PrimaryScreenBounds.Bottom) + else if (hookCallbackMouseData.Y > MachineStuff.PrimaryScreenBounds.Bottom) { - hookCallbackMouseData.Y = Common.PrimaryScreenBounds.Bottom + 1; + hookCallbackMouseData.Y = MachineStuff.PrimaryScreenBounds.Bottom + 1; } dx += dx < 0 ? -Common.MOVE_MOUSE_RELATIVE : Common.MOVE_MOUSE_RELATIVE; @@ -315,8 +315,8 @@ namespace MouseWithoutBorders.Class MouseEvent(hookCallbackMouseData, dx, dy); - Common.DragDropStep01(wParam); - Common.DragDropStep09(wParam); + DragDrop.DragDropStep01(wParam); + DragDrop.DragDropStep09(wParam); } if (local) @@ -432,7 +432,7 @@ namespace MouseWithoutBorders.Class if (Common.DesMachineID != ID.ALL) { - Common.SwitchToMachine(Common.MachineName.Trim()); + MachineStuff.SwitchToMachine(Common.MachineName.Trim()); } /* @@ -518,7 +518,7 @@ namespace MouseWithoutBorders.Class if (Common.HotkeyMatched(vkCode, winDown, CtrlDown, altDown, shiftDown, Setting.Values.HotKeySwitch2AllPC)) { ResetLastSwitchKeys(); - Common.SwitchToMultipleMode(Common.DesMachineID != ID.ALL, true); + MachineStuff.SwitchToMultipleMode(Common.DesMachineID != ID.ALL, true); } if (Common.HotkeyMatched(vkCode, winDown, CtrlDown, altDown, shiftDown, Setting.Values.HotKeyToggleEasyMouse)) @@ -543,7 +543,7 @@ namespace MouseWithoutBorders.Class { if (Common.GetTick() - lastHotKeyLockMachine < 500) { - Common.SwitchToMultipleMode(true, true); + MachineStuff.SwitchToMultipleMode(true, true); var codes = GetVkCodesList(Setting.Values.HotKeyLockMachine); @@ -561,7 +561,7 @@ namespace MouseWithoutBorders.Class KeyboardEvent(hookCallbackKeybdData); } - Common.SwitchToMultipleMode(false, true); + MachineStuff.SwitchToMultipleMode(false, true); _ = NativeMethods.LockWorkStation(); } @@ -625,9 +625,9 @@ namespace MouseWithoutBorders.Class private static bool Switch2(int index) { - if (Common.MachineMatrix != null && Common.MachineMatrix.Length > index) + if (MachineStuff.MachineMatrix != null && MachineStuff.MachineMatrix.Length > index) { - string mcName = Common.MachineMatrix[index].Trim(); + string mcName = MachineStuff.MachineMatrix[index].Trim(); if (!string.IsNullOrEmpty(mcName)) { // Common.DoSomethingInUIThread(delegate() @@ -636,7 +636,7 @@ namespace MouseWithoutBorders.Class } // ); - Common.SwitchToMachine(mcName); + MachineStuff.SwitchToMachine(mcName); if (!Common.RunOnLogonDesktop && !Common.RunOnScrSaverDesktop) { diff --git a/src/modules/MouseWithoutBorders/App/Class/InputSimulation.cs b/src/modules/MouseWithoutBorders/App/Class/InputSimulation.cs index bca6e4b28f..6641655ad4 100644 --- a/src/modules/MouseWithoutBorders/App/Class/InputSimulation.cs +++ b/src/modules/MouseWithoutBorders/App/Class/InputSimulation.cs @@ -162,10 +162,10 @@ namespace MouseWithoutBorders.Class uint rv = 0; NativeMethods.INPUT mouse_input = default; - long w65535 = (Common.DesktopBounds.Right - Common.DesktopBounds.Left) * 65535 / Common.ScreenWidth; - long h65535 = (Common.DesktopBounds.Bottom - Common.DesktopBounds.Top) * 65535 / Common.ScreenHeight; - long l65535 = Common.DesktopBounds.Left * 65535 / Common.ScreenWidth; - long t65535 = Common.DesktopBounds.Top * 65535 / Common.ScreenHeight; + long w65535 = (MachineStuff.DesktopBounds.Right - MachineStuff.DesktopBounds.Left) * 65535 / Common.ScreenWidth; + long h65535 = (MachineStuff.DesktopBounds.Bottom - MachineStuff.DesktopBounds.Top) * 65535 / Common.ScreenHeight; + long l65535 = MachineStuff.DesktopBounds.Left * 65535 / Common.ScreenWidth; + long t65535 = MachineStuff.DesktopBounds.Top * 65535 / Common.ScreenHeight; mouse_input.type = 0; long dx = (md.X * w65535 / 65535) + l65535; long dy = (md.Y * h65535 / 65535) + t65535; @@ -221,7 +221,7 @@ namespace MouseWithoutBorders.Class rv = SendInputEx(mouse_input); }); - if (Common.MainFormVisible && !Common.IsDropping) + if (Common.MainFormVisible && !DragDrop.IsDropping) { Common.MainFormDot(); } @@ -233,10 +233,10 @@ namespace MouseWithoutBorders.Class { NativeMethods.INPUT mouse_input = default; - long w65535 = (Common.DesktopBounds.Right - Common.DesktopBounds.Left) * 65535 / Common.ScreenWidth; - long h65535 = (Common.DesktopBounds.Bottom - Common.DesktopBounds.Top) * 65535 / Common.ScreenHeight; - long l65535 = Common.DesktopBounds.Left * 65535 / Common.ScreenWidth; - long t65535 = Common.DesktopBounds.Top * 65535 / Common.ScreenHeight; + long w65535 = (MachineStuff.DesktopBounds.Right - MachineStuff.DesktopBounds.Left) * 65535 / Common.ScreenWidth; + long h65535 = (MachineStuff.DesktopBounds.Bottom - MachineStuff.DesktopBounds.Top) * 65535 / Common.ScreenHeight; + long l65535 = MachineStuff.DesktopBounds.Left * 65535 / Common.ScreenWidth; + long t65535 = MachineStuff.DesktopBounds.Top * 65535 / Common.ScreenHeight; mouse_input.type = 0; long dx = (x * w65535 / 65535) + l65535; long dy = (y * h65535 / 65535) + t65535; diff --git a/src/modules/MouseWithoutBorders/App/Class/MachinePool.cs b/src/modules/MouseWithoutBorders/App/Class/MachinePool.cs index bfbdc3d1d2..e07ca4c4cb 100644 --- a/src/modules/MouseWithoutBorders/App/Class/MachinePool.cs +++ b/src/modules/MouseWithoutBorders/App/Class/MachinePool.cs @@ -12,6 +12,8 @@ using System.Diagnostics; using System.Linq; using System.Threading; +using MouseWithoutBorders.Core; + namespace MouseWithoutBorders.Class { /// @@ -113,10 +115,10 @@ namespace MouseWithoutBorders.Class { Name = list[i].Name, Id = list[i].Id, - Time = list[i].Time > Common.GetTick() - Common.HEARTBEAT_TIMEOUT + 10000 ? Common.GetTick() - Common.HEARTBEAT_TIMEOUT + 10000 : list[i].Time, + Time = list[i].Time > Common.GetTick() - MachineStuff.HEARTBEAT_TIMEOUT + 10000 ? Common.GetTick() - MachineStuff.HEARTBEAT_TIMEOUT + 10000 : list[i].Time, }; - foundAndTimedOut = list[i].Time < Common.GetTick() - Common.HEARTBEAT_TIMEOUT + 10000 - 5000; + foundAndTimedOut = list[i].Time < Common.GetTick() - MachineStuff.HEARTBEAT_TIMEOUT + 10000 - 5000; } } @@ -157,7 +159,7 @@ namespace MouseWithoutBorders.Class } else if (list.Count >= 4) { - throw new ArgumentException($"The number of machines exceeded the maximum allowed limit of {Common.MAX_MACHINE}. Actual count: {list.Count}."); + throw new ArgumentException($"The number of machines exceeded the maximum allowed limit of {MachineStuff.MAX_MACHINE}. Actual count: {list.Count}."); } _ = LearnMachine(name); @@ -179,7 +181,7 @@ namespace MouseWithoutBorders.Class } else if (list.Count >= 4) { - throw new ArgumentException($"The number of machines exceeded the maximum allowed limit of {Common.MAX_MACHINE}. Actual count: {list.Count}."); + throw new ArgumentException($"The number of machines exceeded the maximum allowed limit of {MachineStuff.MAX_MACHINE}. Actual count: {list.Count}."); } _ = LearnMachine(inf.Name); @@ -212,13 +214,13 @@ namespace MouseWithoutBorders.Class } } - if (list.Count >= Common.MAX_MACHINE) + if (list.Count >= MachineStuff.MAX_MACHINE) { int slotFound = -1; for (int i = 0; i < list.Count; i++) { - if (!Common.InMachineMatrix(list[i].Name)) + if (!MachineStuff.InMachineMatrix(list[i].Name)) { slotFound = i; break; @@ -289,7 +291,7 @@ namespace MouseWithoutBorders.Class List machinePool = ListAllMachines(); string rv = string.Join(",", machinePool.Select(m => $"{m.Name}:{m.Id}")); - for (int j = machinePool.Count; j < Common.MAX_MACHINE; j++) + for (int j = machinePool.Count; j < MachineStuff.MAX_MACHINE; j++) { rv += ",:"; } @@ -301,7 +303,7 @@ namespace MouseWithoutBorders.Class /// When doing unit tests it's nice to be able to fudge with the clock time, adding milliseconds, instead of sleeping. internal static bool IsAlive(MachineInf inf, int clockSkewInMS_forTesting = 0) { - return inf.Id != ID.NONE && (Common.GetTick() + clockSkewInMS_forTesting - inf.Time <= Common.HEARTBEAT_TIMEOUT || Common.IsConnectedTo(inf.Id)); + return inf.Id != ID.NONE && (Common.GetTick() + clockSkewInMS_forTesting - inf.Time <= MachineStuff.HEARTBEAT_TIMEOUT || Common.IsConnectedTo(inf.Id)); } private static bool NamesAreEqual(string name1, string name2) @@ -326,7 +328,7 @@ namespace MouseWithoutBorders.Class continue; } - if ((firstLoaded && !Common.InMachineMatrix(list[i].Name)) || (!firstLoaded && (!Common.InMachineMatrix(list[i].Name) || !IsAlive(list[i])))) + if ((firstLoaded && !MachineStuff.InMachineMatrix(list[i].Name)) || (!firstLoaded && (!MachineStuff.InMachineMatrix(list[i].Name) || !IsAlive(list[i])))) { list[i] = new MachineInf diff --git a/src/modules/MouseWithoutBorders/App/Class/MachinePoolHelpers.cs b/src/modules/MouseWithoutBorders/App/Class/MachinePoolHelpers.cs index d2162273fb..bbb20bcc17 100644 --- a/src/modules/MouseWithoutBorders/App/Class/MachinePoolHelpers.cs +++ b/src/modules/MouseWithoutBorders/App/Class/MachinePoolHelpers.cs @@ -4,6 +4,8 @@ using System; +using MouseWithoutBorders.Core; + namespace MouseWithoutBorders.Class { internal static class MachinePoolHelpers @@ -20,20 +22,20 @@ namespace MouseWithoutBorders.Class string[] st = s.Split(Comma); - if (st.Length < Common.MAX_MACHINE) + if (st.Length < MachineStuff.MAX_MACHINE) { throw new ArgumentException("Not enough elements in encoded MachinePool string"); } - MachineInf[] rv = new MachineInf[Common.MAX_MACHINE]; - for (int i = 0; i < Common.MAX_MACHINE; i++) + MachineInf[] rv = new MachineInf[MachineStuff.MAX_MACHINE]; + for (int i = 0; i < MachineStuff.MAX_MACHINE; i++) { string[] mc = st[i].Split(Colon); if (mc.Length == 2) { rv[i].Name = mc[0]; rv[i].Id = uint.TryParse(mc[1], out uint ip) ? (ID)ip : ID.NONE; - rv[i].Time = rv[i].Id == ID.NONE ? Common.GetTick() - Common.HEARTBEAT_TIMEOUT : Common.GetTick(); + rv[i].Time = rv[i].Id == ID.NONE ? Common.GetTick() - MachineStuff.HEARTBEAT_TIMEOUT : Common.GetTick(); } } diff --git a/src/modules/MouseWithoutBorders/App/Class/Program.cs b/src/modules/MouseWithoutBorders/App/Class/Program.cs index 7a6b3a37ed..203f5f277d 100644 --- a/src/modules/MouseWithoutBorders/App/Class/Program.cs +++ b/src/modules/MouseWithoutBorders/App/Class/Program.cs @@ -31,6 +31,7 @@ using System.Xml.Linq; using ManagedCommon; using Microsoft.PowerToys.Settings.UI.Library.Utilities; using Microsoft.PowerToys.Telemetry; +using MouseWithoutBorders.Core; using Newtonsoft.Json; using StreamJsonRpc; @@ -135,7 +136,7 @@ namespace MouseWithoutBorders.Class if (firstArg != string.Empty) { - if (Common.CheckSecondInstance(Common.RunWithNoAdminRight)) + if (MachineStuff.CheckSecondInstance(Common.RunWithNoAdminRight)) { Logger.Log("*** Second instance, exiting..."); return; @@ -165,7 +166,7 @@ namespace MouseWithoutBorders.Class } else { - if (Common.CheckSecondInstance(true)) + if (MachineStuff.CheckSecondInstance(true)) { Logger.Log("*** Second instance, exiting..."); return; @@ -301,20 +302,20 @@ namespace MouseWithoutBorders.Class { Setting.Values.PauseInstantSaving = true; - Common.ClearComputerMatrix(); + MachineStuff.ClearComputerMatrix(); Setting.Values.MyKey = securityKey; Common.MyKey = securityKey; Common.MagicNumber = Common.Get24BitHash(Common.MyKey); - Common.MachineMatrix = new string[Common.MAX_MACHINE] { pcName.Trim().ToUpper(CultureInfo.CurrentCulture), Common.MachineName.Trim(), string.Empty, string.Empty }; + MachineStuff.MachineMatrix = new string[MachineStuff.MAX_MACHINE] { pcName.Trim().ToUpper(CultureInfo.CurrentCulture), Common.MachineName.Trim(), string.Empty, string.Empty }; - string[] machines = Common.MachineMatrix; - Common.MachinePool.Initialize(machines); - Common.UpdateMachinePoolStringSetting(); + string[] machines = MachineStuff.MachineMatrix; + MachineStuff.MachinePool.Initialize(machines); + MachineStuff.UpdateMachinePoolStringSetting(); SocketStuff.InvalidKeyFound = false; Common.ReopenSocketDueToReadError = true; Common.ReopenSockets(true); - Common.SendMachineMatrix(); + MachineStuff.SendMachineMatrix(); Setting.Values.PauseInstantSaving = false; Setting.Values.SaveSettings(); @@ -325,7 +326,7 @@ namespace MouseWithoutBorders.Class Setting.Values.PauseInstantSaving = true; Setting.Values.EasyMouse = (int)EasyMouseOption.Enable; - Common.ClearComputerMatrix(); + MachineStuff.ClearComputerMatrix(); Setting.Values.MyKey = Common.MyKey = Common.CreateRandomKey(); Common.GeneratedKey = true; @@ -352,7 +353,7 @@ namespace MouseWithoutBorders.Class Common.MMSleep(0.2); } - Common.SendMachineMatrix(); + MachineStuff.SendMachineMatrix(); } public void Shutdown() diff --git a/src/modules/MouseWithoutBorders/App/Class/Setting.cs b/src/modules/MouseWithoutBorders/App/Class/Setting.cs index 8d2270424d..31d9a50049 100644 --- a/src/modules/MouseWithoutBorders/App/Class/Setting.cs +++ b/src/modules/MouseWithoutBorders/App/Class/Setting.cs @@ -102,7 +102,7 @@ namespace MouseWithoutBorders.Class if (!Enumerable.SequenceEqual(last_properties.MachineMatrixString, _settings.Properties.MachineMatrixString)) { _properties.MachineMatrixString = _settings.Properties.MachineMatrixString; - Common.MachineMatrix = null; // Forces read next time it's needed. + MachineStuff.MachineMatrix = null; // Forces read next time it's needed. shouldSendMachineMatrix = true; } @@ -123,7 +123,7 @@ namespace MouseWithoutBorders.Class if (shouldSendMachineMatrix) { - Common.SendMachineMatrix(); + MachineStuff.SendMachineMatrix(); shouldSaveNewSettingsValues = true; } diff --git a/src/modules/MouseWithoutBorders/App/Class/SocketStuff.cs b/src/modules/MouseWithoutBorders/App/Class/SocketStuff.cs index d7ff395ce9..3f848edf76 100644 --- a/src/modules/MouseWithoutBorders/App/Class/SocketStuff.cs +++ b/src/modules/MouseWithoutBorders/App/Class/SocketStuff.cs @@ -188,7 +188,7 @@ namespace MouseWithoutBorders.Class { if (Common.DesMachineID != Common.MachineID) { - Common.SwitchToMultipleMode(false, true); + MachineStuff.SwitchToMultipleMode(false, true); } if (!Common.RunOnLogonDesktop && !Common.RunOnScrSaverDesktop) @@ -253,7 +253,7 @@ namespace MouseWithoutBorders.Class { if (Setting.Values.LastX == Common.JUST_GOT_BACK_FROM_SCREEN_SAVER) { - Common.NewDesMachineID = Common.DesMachineID = Common.MachineID; + MachineStuff.NewDesMachineID = Common.DesMachineID = Common.MachineID; } else { @@ -263,11 +263,11 @@ namespace MouseWithoutBorders.Class if (Common.RunOnLogonDesktop && Setting.Values.DesMachineID == (uint)ID.ALL) { - Common.SwitchToMultipleMode(true, false); + MachineStuff.SwitchToMultipleMode(true, false); } else { - Common.SwitchToMultipleMode(false, false); + MachineStuff.SwitchToMultipleMode(false, false); } } } @@ -804,11 +804,11 @@ namespace MouseWithoutBorders.Class try { - if (Common.MachineMatrix != null) + if (MachineStuff.MachineMatrix != null) { - Logger.LogDebug("MachineMatrix = " + string.Join(", ", Common.MachineMatrix)); + Logger.LogDebug("MachineMatrix = " + string.Join(", ", MachineStuff.MachineMatrix)); - foreach (string st in Common.MachineMatrix) + foreach (string st in MachineStuff.MachineMatrix) { string machineName = st.Trim(); if (!string.IsNullOrEmpty(machineName) && @@ -961,7 +961,7 @@ namespace MouseWithoutBorders.Class UpdateTcpSockets(dummyTcp, SocketStatus.NA); - if (!Common.InMachineMatrix(machineName)) + if (!MachineStuff.InMachineMatrix(machineName)) { // While Resolving from name to IP, user may have changed the machine name and clicked on Apply. return; @@ -1449,19 +1449,19 @@ namespace MouseWithoutBorders.Class Common.SendHeartBeat(initial: true); - if (Common.MachinePool.TryFindMachineByName(remoteMachine, out MachineInf machineInfo)) + if (MachineStuff.MachinePool.TryFindMachineByName(remoteMachine, out MachineInf machineInfo)) { Logger.LogDebug("Machine updated: " + remoteMachine + "/" + remoteID.ToString()); - if (machineInfo.Name.Equals(Common.DesMachineName, StringComparison.OrdinalIgnoreCase)) + if (machineInfo.Name.Equals(MachineStuff.DesMachineName, StringComparison.OrdinalIgnoreCase)) { Logger.LogDebug("Des ID updated: " + Common.DesMachineID.ToString() + "/" + remoteID.ToString()); - Common.NewDesMachineID = Common.DesMachineID = remoteID; + MachineStuff.NewDesMachineID = Common.DesMachineID = remoteID; } - _ = Common.MachinePool.TryUpdateMachineID(remoteMachine, remoteID, true); - Common.UpdateMachinePoolStringSetting(); + _ = MachineStuff.MachinePool.TryUpdateMachineID(remoteMachine, remoteID, true); + MachineStuff.UpdateMachinePoolStringSetting(); } else { @@ -1475,7 +1475,7 @@ namespace MouseWithoutBorders.Class if (!isClient) { - Common.UpdateClientSockets("MainTCPRoutine"); + MachineStuff.UpdateClientSockets("MainTCPRoutine"); } } else @@ -1559,7 +1559,7 @@ namespace MouseWithoutBorders.Class if (remoteID != ID.NONE) { - _ = Common.RemoveDeadMachines(remoteID); + _ = MachineStuff.RemoveDeadMachines(remoteID); } } @@ -1635,9 +1635,9 @@ namespace MouseWithoutBorders.Class { string remoteEndPoint = s.RemoteEndPoint.ToString(); Logger.LogDebug("SendClipboardData: Request accepted: " + s.LocalEndPoint.ToString() + "/" + remoteEndPoint); - Common.IsDropping = false; - Common.IsDragging = false; - Common.DragMachine = (ID)1; + DragDrop.IsDropping = false; + DragDrop.IsDragging = false; + DragDrop.DragMachine = (ID)1; bool clientPushData = true; ClipboardPostAction postAction = ClipboardPostAction.Other; @@ -2064,7 +2064,7 @@ namespace MouseWithoutBorders.Class if (string.IsNullOrEmpty(tcp.MachineName) || tcp.MachineName.Contains('.') || tcp.MachineName.Contains(':')) { - tcp.MachineName = Common.NameFromID((ID)tcp.MachineId); + tcp.MachineName = MachineStuff.NameFromID((ID)tcp.MachineId); } if (string.IsNullOrEmpty(tcp.MachineName) || tcp.MachineName.Contains('.') || tcp.MachineName.Contains(':')) diff --git a/src/modules/MouseWithoutBorders/App/Core/DragDrop.cs b/src/modules/MouseWithoutBorders/App/Core/DragDrop.cs new file mode 100644 index 0000000000..bf52717dfb --- /dev/null +++ b/src/modules/MouseWithoutBorders/App/Core/DragDrop.cs @@ -0,0 +1,404 @@ +// Copyright (c) Microsoft Corporation +// The Microsoft Corporation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Drawing; +using System.Globalization; +using System.IO; +using System.Threading; +using System.Windows.Forms; + +using Microsoft.PowerToys.Telemetry; +using MouseWithoutBorders.Class; + +// +// Drag/Drop implementation. +// +// +// 2008 created by Truong Do (ductdo). +// 2009-... modified by Truong Do (TruongDo). +// 2023- Included in PowerToys. +// +namespace MouseWithoutBorders.Core; + +/* Common.DragDrop.cs + * Drag&Drop is one complicated implementation of the tool with some tricks. + * + * SEQUENCE OF EVENTS: + * DragDropStep01: MachineX: Remember mouse down state since it could be a start of a dragging + * DragDropStep02: MachineY: Send an message to the MachineX to ask it to check if it is + * doing drag/drop + * DragDropStep03: MachineX: Got explorerDragDrop, send WM_CHECK_EXPLORER_DRAG_DROP to its mainForm + * DragDropStep04: MachineX: Show Mouse Without Borders Helper form at mouse cursor to get DragEnter event. + * DragDropStepXX: MachineX: Mouse Without Borders Helper: Called by DragEnter, check if dragging a single file, + * remember the file (set as its window caption) + * DragDropStep05: MachineX: Get the file name from Mouse Without Borders Helper, hide Mouse Without Borders Helper window + * DragDropStep06: MachineX: Broadcast a message saying that it has some drag file. + * DragDropStep08: MachineY: Got ClipboardDragDrop, isDropping set, get the MachineX name from the package. + * DragDropStep09: MachineY: Since isDropping is true, show up the drop form (looks like an icon). + * DragDropStep10: MachineY: MouseUp, set isDropping to false, hide the drop "icon" and get data. + * DragDropStep11: MachineX: Mouse move back without drop event, cancelling drag/dop + * SendClipboardBeatDragDropEnd + * DragDropStep12: MachineY: Hide the drop "icon" when received ClipboardDragDropEnd. + * + * FROM VERSION 1.6.3: Drag/Drop is temporary removed, Drop action cannot be done from a lower integrity app to a higher one. + * We have to run a helper process... + * http://forums.microsoft.com/MSDN/ShowPost.aspx?PageIndex=1&SiteID=1&PageID=1&PostID=736086 + * + * 2008.10.28: Trying to restore the Drag/Drop feature by adding the drag/drop helper process. Coming in version + * 1.6.5 + * */ + +internal static class DragDrop +{ + private static bool isDragging; + + internal static bool IsDragging + { + get => DragDrop.isDragging; + set => DragDrop.isDragging = value; + } + + internal static void DragDropStep01(int wParam) + { + if (!Setting.Values.TransferFile) + { + return; + } + + if (wParam == Common.WM_LBUTTONDOWN) + { + MouseDown = true; + DragMachine = MachineStuff.desMachineID; + MachineStuff.dropMachineID = ID.NONE; + Logger.LogDebug("DragDropStep01: MouseDown"); + } + else if (wParam == Common.WM_LBUTTONUP) + { + MouseDown = false; + Logger.LogDebug("DragDropStep01: MouseUp"); + } + + if (wParam == Common.WM_RBUTTONUP && IsDropping) + { + IsDropping = false; + Common.LastIDWithClipboardData = ID.NONE; + } + } + + internal static void DragDropStep02() + { + if (MachineStuff.desMachineID == Common.MachineID) + { + Logger.LogDebug("DragDropStep02: SendCheckExplorerDragDrop sent to myself"); + Common.DoSomethingInUIThread(() => + { + _ = NativeMethods.PostMessage(Common.MainForm.Handle, NativeMethods.WM_CHECK_EXPLORER_DRAG_DROP, (IntPtr)0, (IntPtr)0); + }); + } + else + { + SendCheckExplorerDragDrop(); + Logger.LogDebug("DragDropStep02: SendCheckExplorerDragDrop sent"); + } + } + + internal static void DragDropStep03(DATA package) + { + if (Common.RunOnLogonDesktop || Common.RunOnScrSaverDesktop) + { + return; + } + + if (package.Des == Common.MachineID || package.Des == ID.ALL) + { + Logger.LogDebug("DragDropStep03: ExplorerDragDrop Received."); + MachineStuff.dropMachineID = package.Src; // Drop machine is the machine that sent ExplorerDragDrop + if (MouseDown || IsDropping) + { + Logger.LogDebug("DragDropStep03: Mouse is down, check if dragging...sending WM_CHECK_EXPLORER_DRAG_DROP to myself..."); + Common.DoSomethingInUIThread(() => + { + _ = NativeMethods.PostMessage(Common.MainForm.Handle, NativeMethods.WM_CHECK_EXPLORER_DRAG_DROP, (IntPtr)0, (IntPtr)0); + }); + } + } + } + + private static int dragDropStep05ExCalledByIpc; + + internal static void DragDropStep04() + { + if (!IsDropping) + { + IntPtr h = (IntPtr)NativeMethods.FindWindow(null, Common.HELPER_FORM_TEXT); + if (h.ToInt32() > 0) + { + _ = Interlocked.Exchange(ref dragDropStep05ExCalledByIpc, 0); + + Common.MainForm.Hide(); + Common.MainFormVisible = false; + + Point p = default; + + // NativeMethods.SetWindowText(h, ""); + _ = NativeMethods.SetWindowPos(h, NativeMethods.HWND_TOPMOST, 0, 0, 0, 0, NativeMethods.SWP_SHOWWINDOW); + + for (int i = -10; i < 10; i++) + { + if (dragDropStep05ExCalledByIpc > 0) + { + Logger.LogDebug("DragDropStep04: DragDropStep05ExCalledByIpc."); + break; + } + + _ = NativeMethods.GetCursorPos(ref p); + Logger.LogDebug("DragDropStep04: Moving Mouse Without Borders Helper to (" + p.X.ToString(CultureInfo.CurrentCulture) + ", " + p.Y.ToString(CultureInfo.CurrentCulture) + ")"); + _ = NativeMethods.SetWindowPos(h, NativeMethods.HWND_TOPMOST, p.X - 100 + i, p.Y - 100 + i, 200, 200, 0); + _ = NativeMethods.SendMessage(h, 0x000F, IntPtr.Zero, IntPtr.Zero); // WM_PAINT + Thread.Sleep(20); + Application.DoEvents(); + + // if (GetText(h).Length > 1) break; + } + } + else + { + Logger.LogDebug("DragDropStep04: Mouse without Borders Helper not found!"); + } + } + else + { + Logger.LogDebug("DragDropStep04: IsDropping == true, skip checking"); + } + + Logger.LogDebug("DragDropStep04: Got WM_CHECK_EXPLORER_DRAG_DROP, done with processing jump to DragDropStep05..."); + } + + internal static void DragDropStep05Ex(string dragFileName) + { + Logger.LogDebug("DragDropStep05 called."); + + _ = Interlocked.Exchange(ref dragDropStep05ExCalledByIpc, 1); + + if (Common.RunOnLogonDesktop || Common.RunOnScrSaverDesktop) + { + return; + } + + if (!IsDropping) + { + _ = Common.ImpersonateLoggedOnUserAndDoSomething(() => + { + if (!string.IsNullOrEmpty(dragFileName) && (File.Exists(dragFileName) || Directory.Exists(dragFileName))) + { + Common.LastDragDropFile = dragFileName; + /* + * possibleDropMachineID is used as desID sent in DragDropStep06(); + * */ + if (MachineStuff.dropMachineID == ID.NONE) + { + MachineStuff.dropMachineID = MachineStuff.newDesMachineID; + } + + DragDropStep06(); + Logger.LogDebug("DragDropStep05: File dragging: " + dragFileName); + _ = NativeMethods.PostMessage(Common.MainForm.Handle, NativeMethods.WM_HIDE_DD_HELPER, (IntPtr)1, (IntPtr)0); + } + else + { + Logger.LogDebug("DragDropStep05: File not found: [" + dragFileName + "]"); + _ = NativeMethods.PostMessage(Common.MainForm.Handle, NativeMethods.WM_HIDE_DD_HELPER, (IntPtr)0, (IntPtr)0); + } + + Logger.LogDebug("DragDropStep05: WM_HIDE_DDHelper sent"); + }); + } + else + { + Logger.LogDebug("DragDropStep05: IsDropping == true, change drop machine..."); + IsDropping = false; + Common.MainFormVisible = true; // WM_HIDE_DRAG_DROP + SendDropBegin(); // To dropMachineID set in DragDropStep03 + } + + MouseDown = false; + } + + private static void DragDropStep06() + { + IsDragging = true; + Logger.LogDebug("DragDropStep06: SendClipboardBeatDragDrop"); + SendClipboardBeatDragDrop(); + SendDropBegin(); + } + + internal static void DragDropStep08(DATA package) + { + Receiver.GetNameOfMachineWithClipboardData(package); + Logger.LogDebug("DragDropStep08: ClipboardDragDrop Received. machine with drag file was set"); + } + + internal static void DragDropStep08_2(DATA package) + { + if (package.Des == Common.MachineID && !Common.RunOnLogonDesktop && !Common.RunOnScrSaverDesktop) + { + IsDropping = true; + MachineStuff.dropMachineID = Common.MachineID; + Logger.LogDebug("DragDropStep08_2: ClipboardDragDropOperation Received. IsDropping set"); + } + } + + internal static void DragDropStep09(int wParam) + { + if (wParam == Common.WM_MOUSEMOVE && IsDropping) + { + // Show/Move form + Common.DoSomethingInUIThread(() => + { + _ = NativeMethods.PostMessage(Common.MainForm.Handle, NativeMethods.WM_SHOW_DRAG_DROP, (IntPtr)0, (IntPtr)0); + }); + } + else if (wParam == Common.WM_LBUTTONUP && (IsDropping || IsDragging)) + { + if (IsDropping) + { + // Hide form, get data + DragDropStep10(); + } + else + { + IsDragging = false; + Common.LastIDWithClipboardData = ID.NONE; + } + } + } + + private static void DragDropStep10() + { + Logger.LogDebug("DragDropStep10: Hide the form and get data..."); + IsDropping = false; + IsDragging = false; + Common.LastIDWithClipboardData = ID.NONE; + + Common.DoSomethingInUIThread(() => + { + _ = NativeMethods.PostMessage(Common.MainForm.Handle, NativeMethods.WM_HIDE_DRAG_DROP, (IntPtr)0, (IntPtr)0); + }); + + PowerToysTelemetry.Log.WriteEvent(new MouseWithoutBorders.Telemetry.MouseWithoutBordersDragAndDropEvent()); + Common.GetRemoteClipboard("desktop"); + } + + internal static void DragDropStep11() + { + Logger.LogDebug("DragDropStep11: Mouse drag coming back, canceling drag/drop"); + SendClipboardBeatDragDropEnd(); + IsDropping = false; + IsDragging = false; + DragMachine = (ID)1; + Common.LastIDWithClipboardData = ID.NONE; + Common.LastDragDropFile = null; + MouseDown = false; + } + + internal static void DragDropStep12() + { + Logger.LogDebug("DragDropStep12: ClipboardDragDropEnd received"); + IsDropping = false; + Common.LastIDWithClipboardData = ID.NONE; + + Common.DoSomethingInUIThread(() => + { + _ = NativeMethods.PostMessage(Common.MainForm.Handle, NativeMethods.WM_HIDE_DRAG_DROP, (IntPtr)0, (IntPtr)0); + }); + } + + private static void SendCheckExplorerDragDrop() + { + DATA package = new(); + package.Type = PackageType.ExplorerDragDrop; + + /* + * package.src = newDesMachineID: + * sent from the master machine but the src must be the + * new des machine since the previous des machine will get this and set + * to possibleDropMachineID in DragDropStep3() + * */ + package.Src = MachineStuff.newDesMachineID; + + package.Des = MachineStuff.desMachineID; + package.MachineName = Common.MachineName; + + Common.SkSend(package, null, false); + } + + internal static void ChangeDropMachine() + { + // desMachineID = current drop machine + // newDesMachineID = new drop machine + + // 1. Cancelling dropping in current drop machine + if (MachineStuff.dropMachineID == Common.MachineID) + { + // Drag/Drop coming through me + IsDropping = false; + } + else + { + // Drag/Drop coming back + SendClipboardBeatDragDropEnd(); + } + + // 2. SendClipboardBeatDragDrop to new drop machine + // new drop machine is not me + if (MachineStuff.newDesMachineID != Common.MachineID) + { + MachineStuff.dropMachineID = MachineStuff.newDesMachineID; + SendDropBegin(); + } + + // New drop machine is me + else + { + IsDropping = true; + } + } + + private static void SendClipboardBeatDragDrop() + { + Common.SendPackage(ID.ALL, PackageType.ClipboardDragDrop); + } + + private static void SendDropBegin() + { + Logger.LogDebug("SendDropBegin..."); + Common.SendPackage(MachineStuff.dropMachineID, PackageType.ClipboardDragDropOperation); + } + + private static void SendClipboardBeatDragDropEnd() + { + if (MachineStuff.desMachineID != Common.MachineID) + { + Common.SendPackage(MachineStuff.desMachineID, PackageType.ClipboardDragDropEnd); + } + } + + private static bool isDropping; + private static ID dragMachine; + + internal static ID DragMachine + { + get => DragDrop.dragMachine; + set => DragDrop.dragMachine = value; + } + + internal static bool IsDropping + { + get => DragDrop.isDropping; + set => DragDrop.isDropping = value; + } + + internal static bool MouseDown { get; set; } +} diff --git a/src/modules/MouseWithoutBorders/App/Core/Logger.cs b/src/modules/MouseWithoutBorders/App/Core/Logger.cs index c561d5ff42..520f1671e3 100644 --- a/src/modules/MouseWithoutBorders/App/Core/Logger.cs +++ b/src/modules/MouseWithoutBorders/App/Core/Logger.cs @@ -199,8 +199,11 @@ internal static class Logger _ = Logger.PrivateDump(sb, AllLogs, "[Program logs]\r\n===============\r\n", 0, level, false); _ = Logger.PrivateDump(sb, new Common(), "[Other Logs]\r\n===============\r\n", 0, level, false); - sb.AppendLine("[Logger]\r\n==============="); Logger.DumpType(sb, typeof(Logger), 0, level); + sb.AppendLine("[DragDrop]\r\n==============="); + Logger.DumpType(sb, typeof(DragDrop), 0, level); + sb.AppendLine("[MachineStuff]\r\n==============="); + Logger.DumpType(sb, typeof(MachineStuff), 0, level); sb.AppendLine("[Receiver]\r\n==============="); Logger.DumpType(sb, typeof(Receiver), 0, level); diff --git a/src/modules/MouseWithoutBorders/App/Core/MachineInf.cs b/src/modules/MouseWithoutBorders/App/Core/MachineInf.cs new file mode 100644 index 0000000000..8cf807d3bd --- /dev/null +++ b/src/modules/MouseWithoutBorders/App/Core/MachineInf.cs @@ -0,0 +1,20 @@ +// Copyright (c) Microsoft Corporation +// The Microsoft Corporation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +// +// Machine setup/switching implementation. +// +// +// 2008 created by Truong Do (ductdo). +// 2009-... modified by Truong Do (TruongDo). +// 2023- Included in PowerToys. +// +namespace MouseWithoutBorders.Core; + +internal struct MachineInf +{ + internal string Name; + internal ID Id; + internal long Time; +} diff --git a/src/modules/MouseWithoutBorders/App/Core/MachineStuff.cs b/src/modules/MouseWithoutBorders/App/Core/MachineStuff.cs new file mode 100644 index 0000000000..b835ce3420 --- /dev/null +++ b/src/modules/MouseWithoutBorders/App/Core/MachineStuff.cs @@ -0,0 +1,1122 @@ +// Copyright (c) Microsoft Corporation +// The Microsoft Corporation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Drawing; +using System.Linq; +using System.Threading; +using System.Windows.Forms; + +using Microsoft.PowerToys.Telemetry; +using MouseWithoutBorders.Class; + +// +// Machine setup/switching implementation. +// +// +// 2008 created by Truong Do (ductdo). +// 2009-... modified by Truong Do (TruongDo). +// 2023- Included in PowerToys. +// +namespace MouseWithoutBorders.Core; + +internal static class MachineStuff +{ + private static readonly Lock McMatrixLock = new(); + + internal const byte MAX_MACHINE = 4; + private const byte MAX_SOCKET = MAX_MACHINE * 2; + internal const long HEARTBEAT_TIMEOUT = 1500000; // 30 Mins + private const int SKIP_PIXELS = 1; + private const int JUMP_PIXELS = 2; + +#pragma warning disable SA1307 // Accessible fields should begin with upper-case letter + internal static ID desMachineID; +#pragma warning restore SA1307 +#pragma warning disable SA1306 // Field should begin with a lower-case letter + internal static string DesMachineName = string.Empty; +#pragma warning restore SA1306 +#pragma warning disable SA1307 // Accessible fields should begin with upper-case letter + internal static ID newDesMachineID; + internal static ID newDesMachineIdEx; + internal static ID dropMachineID; + internal static long lastJump = Common.GetTick(); + internal static MyRectangle desktopBounds = new(); + internal static MyRectangle primaryScreenBounds = new(); +#pragma warning restore SA1307 + private static MachinePool _machinePool; + + internal static MachinePool MachinePool + { + get + { + _machinePool ??= new MachinePool(); + return _machinePool; + } + } + + internal static MyRectangle PrimaryScreenBounds => MachineStuff.primaryScreenBounds; + +#pragma warning disable SA1306 // Field should begin with a lower-case letter + internal static MouseLocation SwitchLocation = new(); +#pragma warning restore SA1306 + + internal static ID NewDesMachineID + { + get => MachineStuff.newDesMachineID; + set => MachineStuff.newDesMachineID = value; + } + + internal static MyRectangle DesktopBounds => MachineStuff.desktopBounds; + +#if OLD_VERSION + static bool MoveToMyNeighbourIfNeeded(int x, int y) + { + if (Math.Abs(x) > 10) LastX = x; + if (Math.Abs(y) > 10) LastY = y; + if (GetTick() - lastJump < 500 || desMachineID == IP.ALL) return false; + if (desMachineID == machineID) + { + if (x < desktopBounds.Left + skipPixels) return MoveLeft(x, y, x - desktopBounds.Left, 0); + } + else + { + if (x < primaryScreenBounds.Left + skipPixels) + { + if (MoveLeft(x, y, x - primaryScreenBounds.Left, 0)) + { + return true; + } + else + { + if (desktopBounds.Left < primaryScreenBounds.Left) + { + RequestedX_Ex = primaryScreenBounds.Left; + RequestedY_Ex = y; + return true; + } + } + } + } + + if (desMachineID == machineID) + { + if (x > desktopBounds.Right - skipPixels) return MoveRight(x, y, x - desktopBounds.Right, 0); + } + else + { + if (x > primaryScreenBounds.Right - skipPixels) + { + if (MoveRight(x, y, x - primaryScreenBounds.Right, 0)) + { + return true; + } + else + { + if (desktopBounds.Right > primaryScreenBounds.Right) + { + RequestedX_Ex = primaryScreenBounds.Right; + RequestedY_Ex = y; + return true; + } + } + } + } + + if (desMachineID == machineID) + { + if (y < desktopBounds.Top + skipPixels) return MoveUp(x, y, 0, y - desktopBounds.Top); + } + else + { + if (y < primaryScreenBounds.Top + skipPixels) + { + if (MoveUp(x, y, 0, y - primaryScreenBounds.Top)) + { + return true; + } + else + { + if (desktopBounds.Top < primaryScreenBounds.Top) + { + RequestedX_Ex = x; + RequestedY_Ex = primaryScreenBounds.Top; + return true; + } + } + } + } + + if (desMachineID == machineID) + { + if (y > desktopBounds.Bottom - skipPixels) return MoveDown(x, y, 0, y - desktopBounds.Bottom); + } + else + { + if (y > primaryScreenBounds.Bottom - skipPixels) + { + if (MoveDown(x, y, 0, y - primaryScreenBounds.Bottom)) + { + return true; + } + else + { + if (desktopBounds.Bottom > primaryScreenBounds.Bottom) + { + RequestedX_Ex = x; + RequestedY_Ex = primaryScreenBounds.Bottom; + return true; + } + } + } + } + + return false; + } +#else + + private static Point ConvertToUniversalValue(Point p, MyRectangle r) + { + if (!p.IsEmpty) + { + p.X = (p.X - r.Left) * 65535 / (r.Right - r.Left); + p.Y = (p.Y - r.Top) * 65535 / (r.Bottom - r.Top); + } + + return p; + } + + /* Let's say we have 3 machines A, B, and C. A is the controller machine. + * (x, y) is the current Mouse position in pixel. + * If Setting.Values.MoveMouseRelatively then (x, y) can be from any machine having the value bounded by desktopBounds (can be negative) + * Else (x, y) is from the controller machine which is bounded by ONLY primaryScreenBounds (>=0); + * + * The return point is from 0 to 65535 which is then mapped to the desktop of the new controlled machine by the SendInput method. + * Let's say user is switching from machine B to machine C: + * If Setting.Values.MoveMouseRelatively the this method is called by B and the return point is calculated by B and sent back to A, A will use it to move Mouse to the right position when switching to C. + * Else this method is called by A and the return point is calculated by A. + * */ + + internal static Point MoveToMyNeighbourIfNeeded(int x, int y, ID desMachineID) + { + newDesMachineIdEx = desMachineID; + + if (Math.Abs(x) > 10) + { + Common.LastX = x; + } + + if (Math.Abs(y) > 10) + { + Common.LastY = y; + } + + if ((Common.GetTick() - lastJump < 100) || desMachineID == ID.ALL) + { + return Point.Empty; + } + + if (Setting.Values.BlockMouseAtCorners) + { + lock (Common.SensitivePoints) + { + foreach (Point p in Common.SensitivePoints) + { + if (Math.Abs(p.X - x) < 100 && Math.Abs(p.Y - y) < 100) + { + return Point.Empty; + } + } + } + } + + /* If Mouse is moving in the controller machine and this method is called by the controller machine. + * Or if Mouse is moving in the controlled machine and this method is called by the controlled machine and Setting.Values.MoveMouseRelative. + * */ + if (desMachineID == Common.MachineID) + { + if (x < desktopBounds.Left + SKIP_PIXELS) + { + return MoveLeft(x, y); + } + else if (x >= desktopBounds.Right - SKIP_PIXELS) + { + return MoveRight(x, y); + } + else if (y < desktopBounds.Top + SKIP_PIXELS) + { + return MoveUp(x, y); + } + else if (y >= desktopBounds.Bottom - SKIP_PIXELS) + { + return MoveDown(x, y); + } + } + + /* If Mouse is moving in the controlled machine and this method is called by the controller machine and !Setting.Values.MoveMouseRelative. + * Mouse location is scaled from the primary screen bound of the controller machine regardless of how many monitors the controlled machine may have. + * */ + else + { + if (x < primaryScreenBounds.Left + SKIP_PIXELS) + { + return MoveLeft(x, y); + } + else if (x >= primaryScreenBounds.Right - SKIP_PIXELS) + { + return MoveRight(x, y); + } + else if (y < primaryScreenBounds.Top + SKIP_PIXELS) + { + return MoveUp(x, y); + } + else if (y >= primaryScreenBounds.Bottom - SKIP_PIXELS) + { + return MoveDown(x, y); + } + } + + return Point.Empty; + } + +#endif + + [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "Dotnet port with style preservation")] + private static Point MoveRight(int x, int y) + { + string[] mc = LiveMachineMatrix; + if (mc == null) + { + return Point.Empty; + } + + bool oneRow = Setting.Values.MatrixOneRow; + + string currentMachine = NameFromID(desMachineID); + if (currentMachine == null) + { + return Point.Empty; + } + + ID newID; + if (oneRow) + { + bool found = false; + for (int i = 0; i < MAX_MACHINE; i++) + { + if (currentMachine.Trim().Equals(mc[i], StringComparison.OrdinalIgnoreCase)) + { + for (int j = i; j < MAX_MACHINE - 1; j++) + { + if (mc[j + 1] != null && mc[j + 1].Length > 0) + { + if ((newID = IdFromName(mc[j + 1])) > 0) + { + newDesMachineIdEx = newID; + found = true; + break; + } + } + } + + if (!found && Setting.Values.MatrixCircle) + { + for (int j = 0; j < i; j++) + { + if (mc[j] != null && mc[j].Length > 0) + { + if ((newID = IdFromName(mc[j])) > 0) + { + newDesMachineIdEx = newID; + break; + } + } + } + } + + break; + } + } + } + else + { + if (currentMachine.Trim().Equals(mc[0], StringComparison.OrdinalIgnoreCase) && (mc[1] != null) + && (mc[1].Length > 0)) + { + if ((newID = IdFromName(mc[1])) > 0) + { + newDesMachineIdEx = newID; + } + } + else if (currentMachine.Trim().Equals(mc[2], StringComparison.OrdinalIgnoreCase) && (mc[3] != null) + && (mc[3].Length > 0)) + { + if ((newID = IdFromName(mc[3])) > 0) + { + newDesMachineIdEx = newID; + } + } + else if (Setting.Values.MatrixCircle && currentMachine.Trim().Equals(mc[1], StringComparison.OrdinalIgnoreCase) && (mc[0] != null) + && (mc[0].Length > 0)) + { + if ((newID = IdFromName(mc[0])) > 0) + { + newDesMachineIdEx = newID; + } + } + else if (Setting.Values.MatrixCircle && currentMachine.Trim().Equals(mc[3], StringComparison.OrdinalIgnoreCase) && (mc[2] != null) + && (mc[2].Length > 0)) + { + if ((newID = IdFromName(mc[2])) > 0) + { + newDesMachineIdEx = newID; + } + } + } + + // THIS LOGIC IS THE SAME FOR Move*(int x, int y) METHODS. + if (newDesMachineIdEx != desMachineID) + { + Logger.LogDebug("Move Right"); + + if (!Setting.Values.MoveMouseRelatively) + { + if (newDesMachineIdEx == Common.MachineID) + { + /* Switching back to the controller machine, we need to scale up to the desktopBounds from primaryScreenBounds (sine !Setting.Values.MoveMouseRelatively). + * primaryScreenBounds => 65535 => desktopBounds, so that the Mouse position is mapped to the right position when the controller machine has multiple monitors. + * */ + return ConvertToUniversalValue(new Point(primaryScreenBounds.Left + JUMP_PIXELS, y), primaryScreenBounds); + } + else + { + if (desMachineID == Common.MachineID) + { + /* Switching FROM the controller machine, since Mouse was not bounded/locked to the primary screen, + * Mouse position can just be mapped from desktopBounds to desktopBounds + * desktopBounds => 65535 => desktopBounds. + * */ + return ConvertToUniversalValue(new Point(desktopBounds.Left + JUMP_PIXELS, y), desktopBounds); + } + else + { + /* Switching between two machines where non of them is the controller machine. + * Since the current Mouse position is "mapped" from the primary monitor of the controller machine, + * new Mouse position for the new controlled machine needs to be calculated from this as well. + * primaryScreenBounds => 65535 => desktopBounds + * */ + return ConvertToUniversalValue(new Point(primaryScreenBounds.Left + JUMP_PIXELS, y), primaryScreenBounds); + } + } + } + else + { + /* In the case where Mouse is moved relatively, Mouse position is simply mapped from desktopBounds to desktopBounds. + * desktopBounds => 65535 => desktopBounds. + * */ + return ConvertToUniversalValue(new Point(desktopBounds.Left + JUMP_PIXELS, y), desktopBounds); + } + } + + return Point.Empty; + } + + [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "Dotnet port with style preservation")] + private static Point MoveLeft(int x, int y) + { + string[] mc = LiveMachineMatrix; + if (mc == null) + { + return Point.Empty; + } + + bool oneRow = Setting.Values.MatrixOneRow; + + string currentMachine = NameFromID(desMachineID); + if (currentMachine == null) + { + return Point.Empty; + } + + ID newID; + if (oneRow) + { + bool found = false; + for (int i = MAX_MACHINE - 1; i >= 0; i--) + { + if (currentMachine.Trim().Equals(mc[i], StringComparison.OrdinalIgnoreCase)) + { + for (int j = i; j > 0; j--) + { + if (mc[j - 1] != null && mc[j - 1].Length > 0) + { + if ((newID = IdFromName(mc[j - 1])) != ID.NONE) + { + newDesMachineIdEx = newID; + found = true; + break; + } + } + } + + if (!found && Setting.Values.MatrixCircle) + { + for (int j = MAX_MACHINE - 1; j > i; j--) + { + if (mc[j] != null && mc[j].Length > 0) + { + if ((newID = IdFromName(mc[j])) != ID.NONE) + { + newDesMachineIdEx = newID; + break; + } + } + } + } + + break; + } + } + } + else + { + if (currentMachine.Trim().Equals(mc[1], StringComparison.OrdinalIgnoreCase) && (mc[0] != null) + && (mc[0].Length > 0)) + { + if ((newID = IdFromName(mc[0])) != ID.NONE) + { + newDesMachineIdEx = newID; + } + } + else if (currentMachine.Trim().Equals(mc[3], StringComparison.OrdinalIgnoreCase) && (mc[2] != null) + && (mc[2].Length > 0)) + { + if ((newID = IdFromName(mc[2])) != ID.NONE) + { + newDesMachineIdEx = newID; + } + } + else if (Setting.Values.MatrixCircle && currentMachine.Trim().Equals(mc[0], StringComparison.OrdinalIgnoreCase) && (mc[1] != null) + && (mc[1].Length > 0)) + { + if ((newID = IdFromName(mc[1])) != ID.NONE) + { + newDesMachineIdEx = newID; + } + } + else if (Setting.Values.MatrixCircle && currentMachine.Trim().Equals(mc[2], StringComparison.OrdinalIgnoreCase) && (mc[3] != null) + && (mc[3].Length > 0)) + { + if ((newID = IdFromName(mc[3])) != ID.NONE) + { + newDesMachineIdEx = newID; + } + } + } + + if (newDesMachineIdEx != desMachineID) + { + Logger.LogDebug("Move Left"); + + return !Setting.Values.MoveMouseRelatively + ? newDesMachineIdEx == Common.MachineID + ? ConvertToUniversalValue(new Point(primaryScreenBounds.Right - JUMP_PIXELS, y), primaryScreenBounds) + : desMachineID == Common.MachineID + ? ConvertToUniversalValue(new Point(desktopBounds.Right - JUMP_PIXELS, y), desktopBounds) + : ConvertToUniversalValue(new Point(primaryScreenBounds.Right - JUMP_PIXELS, y), primaryScreenBounds) + : ConvertToUniversalValue(new Point(desktopBounds.Right - JUMP_PIXELS, y), desktopBounds); + } + + return Point.Empty; + } + + private static Point MoveUp(int x, int y) + { + if (Setting.Values.MatrixOneRow) + { + return Point.Empty; + } + + string[] mc = LiveMachineMatrix; + if (mc == null) + { + return Point.Empty; + } + + string currentMachine = NameFromID(desMachineID); + if (currentMachine == null) + { + return Point.Empty; + } + + ID newID; + if (currentMachine.Trim().Equals(mc[2], StringComparison.OrdinalIgnoreCase) && (mc[0] != null) + && (mc[0].Length > 0)) + { + if ((newID = IdFromName(mc[0])) != ID.NONE) + { + newDesMachineIdEx = newID; + } + } + else if (currentMachine.Trim().Equals(mc[3], StringComparison.OrdinalIgnoreCase) && (mc[1] != null) + && (mc[1].Length > 0)) + { + if ((newID = IdFromName(mc[1])) != ID.NONE) + { + newDesMachineIdEx = newID; + } + } + else if (Setting.Values.MatrixCircle && currentMachine.Trim().Equals(mc[0], StringComparison.OrdinalIgnoreCase) && (mc[2] != null) + && (mc[2].Length > 0)) + { + if ((newID = IdFromName(mc[2])) != ID.NONE) + { + newDesMachineIdEx = newID; + } + } + else if (Setting.Values.MatrixCircle && currentMachine.Trim().Equals(mc[1], StringComparison.OrdinalIgnoreCase) && (mc[3] != null) + && (mc[3].Length > 0)) + { + if ((newID = IdFromName(mc[3])) != ID.NONE) + { + newDesMachineIdEx = newID; + } + } + + if (newDesMachineIdEx != desMachineID) + { + Logger.LogDebug("Move Up"); + + return !Setting.Values.MoveMouseRelatively + ? newDesMachineIdEx == Common.MachineID + ? ConvertToUniversalValue(new Point(x, primaryScreenBounds.Bottom - JUMP_PIXELS), primaryScreenBounds) + : desMachineID == Common.MachineID + ? ConvertToUniversalValue(new Point(x, desktopBounds.Bottom - JUMP_PIXELS), desktopBounds) + : ConvertToUniversalValue(new Point(x, primaryScreenBounds.Bottom - JUMP_PIXELS), primaryScreenBounds) + : ConvertToUniversalValue(new Point(x, desktopBounds.Bottom - JUMP_PIXELS), desktopBounds); + } + + return Point.Empty; + } + + private static Point MoveDown(int x, int y) + { + if (Setting.Values.MatrixOneRow) + { + return Point.Empty; + } + + string[] mc = LiveMachineMatrix; + if (mc == null) + { + return Point.Empty; + } + + string currentMachine = NameFromID(desMachineID); + if (currentMachine == null) + { + return Point.Empty; + } + + ID newID; + if (currentMachine.Trim().Equals(mc[0], StringComparison.OrdinalIgnoreCase) && (mc[2] != null) + && (mc[2].Length > 0)) + { + if ((newID = IdFromName(mc[2])) != ID.NONE) + { + newDesMachineIdEx = newID; + } + } + else if (currentMachine.Trim().Equals(mc[1], StringComparison.OrdinalIgnoreCase) && (mc[3] != null) + && (mc[3].Length > 0)) + { + if ((newID = IdFromName(mc[3])) != ID.NONE) + { + newDesMachineIdEx = newID; + } + } + + if (Setting.Values.MatrixCircle && currentMachine.Trim().Equals(mc[2], StringComparison.OrdinalIgnoreCase) && (mc[0] != null) + && (mc[0].Length > 0)) + { + if ((newID = IdFromName(mc[0])) != ID.NONE) + { + newDesMachineIdEx = newID; + } + } + else if (Setting.Values.MatrixCircle && currentMachine.Trim().Equals(mc[3], StringComparison.OrdinalIgnoreCase) && (mc[1] != null) + && (mc[1].Length > 0)) + { + if ((newID = IdFromName(mc[1])) != ID.NONE) + { + newDesMachineIdEx = newID; + } + } + + if (newDesMachineIdEx != desMachineID) + { + Logger.LogDebug("Move Down"); + + return !Setting.Values.MoveMouseRelatively + ? newDesMachineIdEx == Common.MachineID + ? ConvertToUniversalValue(new Point(x, primaryScreenBounds.Top + JUMP_PIXELS), primaryScreenBounds) + : desMachineID == Common.MachineID + ? ConvertToUniversalValue(new Point(x, desktopBounds.Top + JUMP_PIXELS), desktopBounds) + : ConvertToUniversalValue(new Point(x, primaryScreenBounds.Top + JUMP_PIXELS), primaryScreenBounds) + : ConvertToUniversalValue(new Point(x, desktopBounds.Top + JUMP_PIXELS), desktopBounds); + } + + return Point.Empty; + } + + internal static bool RemoveDeadMachines(ID ip) + { + bool rv = false; + + // Here we are removing a dead machine by IP. + foreach (MachineInf inf in MachineStuff.MachinePool.ListAllMachines()) + { + if (inf.Id == ip) + { + if (MachinePool.SetMachineDisconnected(inf.Name)) + { + rv = true; + } + + Logger.LogDebug("<><><><><>>><><><<><><><><><><><><><><>><><><><><><><><><><><" + inf.Name); + } + } + + return rv; + } + + internal static void RemoveDeadMachines() + { + // list of live/dead machines is now automatically up-to-date + // if it changed we need to update the UI. + // for now assume it changed. + // Common.MachinePool.ResetIPAddressesForDeadMachines(); + // DoSomethingInUIThread(UpdateMenu); + MachineStuff.UpdateMachinePoolStringSetting(); + + // Make sure MachinePool still holds this machine. + if (MachineStuff.MachinePool.LearnMachine(Common.MachineName)) + { + _ = MachineStuff.MachinePool.TryUpdateMachineID(Common.MachineName, Common.MachineID, false); + } + } + + internal static string AddToMachinePool(DATA package) + { + // Log("********** AddToMachinePool called: " + package.src.ToString(CultureInfo.InvariantCulture)); + + // There should be no duplicates in machine pool. + string name = package.MachineName; + + // a few things happening here: + // 1) find a matching machine (by name) + // 2) update its ID and time + // 3) logging + // 4) updating some variables - desMachineID/newDesMachineID + // 5) return the matched name (trimmed) - only in the event of a match + if (MachineStuff.MachinePool.TryFindMachineByName(name, out MachineInf machineInfo)) + { + _ = MachineStuff.MachinePool.TryUpdateMachineID(machineInfo.Name, machineInfo.Id, true); + + _ = MachineStuff.MachinePool.TryUpdateMachineID(machineInfo.Name, package.Src, true); + + if (machineInfo.Name.Equals(DesMachineName, StringComparison.OrdinalIgnoreCase)) + { + Logger.LogDebug("AddToMachinePool: Des ID updated: " + Common.DesMachineID.ToString() + "/" + package.Src.ToString()); + newDesMachineID = desMachineID = package.Src; + } + + return machineInfo.Name; + } + else + { + if (MachineStuff.MachinePool.LearnMachine(name)) + { + _ = MachineStuff.MachinePool.TryUpdateMachineID(name, package.Src, true); + } + else + { + Logger.LogDebug("AddToMachinePool: could not add a new machine: " + name); + return "The 5th machine"; + } + } + + // if (machineCount != saved) + { + // DoSomethingInUIThread(UpdateMenu); + MachineStuff.UpdateMachinePoolStringSetting(); + } + + // NOTE(yuyoyuppe): automatically active "bidirectional" control between the machines. + string[] st = new string[MachineStuff.MAX_MACHINE]; + Array.Fill(st, string.Empty); + var machines = MachineStuff.MachinePool.ListAllMachines(); + for (int i = 0; i < machines.Count; ++i) + { + if (machines[i].Id != ID.NONE && machines[i].Id != ID.ALL) + { + st[i] = machines[i].Name; + } + } + + MachineStuff.MachineMatrix = st; + Common.ReopenSockets(true); + MachineStuff.SendMachineMatrix(); + + Logger.LogDebug("Machine added: " + name + "/" + package.Src.ToString()); + UpdateClientSockets("AddToMachinePool"); + return name; + } + + internal static void UpdateClientSockets(string logHeader) + { + Logger.LogDebug("UpdateClientSockets: " + logHeader); + Common.Sk?.UpdateTCPClients(); + } + + private static SettingsForm settings; + + internal static SettingsForm Settings + { + get => MachineStuff.settings; + set => MachineStuff.settings = value; + } + + internal static void ShowSetupForm(bool reopenSockets = false) + { + Logger.LogDebug("========== BEGIN THE SETUP EXPERIENCE ==========", true); + Setting.Values.MyKey = Common.MyKey = Common.CreateRandomKey(); + Common.GeneratedKey = true; + + if (Process.GetCurrentProcess().SessionId != NativeMethods.WTSGetActiveConsoleSessionId()) + { + Logger.Log("Not physical console session."); + _ = MessageBox.Show( + "Please run the program in the physical console session.\r\nThe program does not work in a remote desktop or virtual machine session.", + Application.ProductName, + MessageBoxButtons.OK, + MessageBoxIcon.Stop); + return; + } + + if (settings == null) + { + settings = new SettingsForm(); + settings.Show(); + } + else + { + settings.Close(); + Common.MMSleep(0.3); + settings = new SettingsForm(); + settings.Show(); + } + + if (reopenSockets) + { + Common.ReopenSockets(true); + } + } + + internal static void CloseSetupForm() + { + if (settings != null) + { + settings.Close(); + settings = null; + } + } + + internal static void ShowMachineMatrix() + { + if (!Setting.Values.ShowOriginalUI) + { + return; + } + + if (Process.GetCurrentProcess().SessionId != NativeMethods.WTSGetActiveConsoleSessionId()) + { + Common.ShowToolTip(Application.ProductName + " cannot be used in a remote desktop or virtual machine session.", 5000); + } + +#if NEW_SETTINGS_FORM + Common.ShowSetupForm(); +#else + if (Setting.Values.FirstRun && !Common.AtLeastOneSocketConnected()) + { + MachineStuff.ShowSetupForm(); + } + else + { + PowerToysTelemetry.Log.WriteEvent(new MouseWithoutBorders.Telemetry.MouseWithoutBordersOldUIOpenedEvent()); + + if (Common.MatrixForm == null) + { + Common.MatrixForm = new FrmMatrix(); + Common.MatrixForm.Show(); + + if (Common.MainForm != null) + { + Common.MainForm.NotifyIcon.Visible = false; + Common.MainForm.NotifyIcon.Visible = Setting.Values.ShowOriginalUI; + } + } + else + { + Common.MatrixForm.WindowState = FormWindowState.Normal; + Common.MatrixForm.Activate(); + } + } +#endif + } + + private static string[] mcMatrix; + + internal static string[] MachineMatrix + { + get + { + lock (McMatrixLock) + { + if (mcMatrix == null) + { + string s = Setting.Values.MachineMatrixString; + + if (!string.IsNullOrEmpty(s)) + { + mcMatrix = s.Split(new char[] { ',' }); + + if (mcMatrix == null || mcMatrix.Length != MAX_MACHINE) + { + mcMatrix = new string[MAX_MACHINE] { string.Empty, string.Empty, string.Empty, string.Empty }; + } + } + else + { + mcMatrix = new string[MAX_MACHINE] { string.Empty, string.Empty, string.Empty, string.Empty }; + } + } + + return mcMatrix; + } + } + + set + { + lock (McMatrixLock) + { + if (value == null) + { + mcMatrix = null; // Force read from registry next time. + return; + } + else + { + Setting.Values.MachineMatrixString = string.Join(",", mcMatrix = value); + } + } + + Common.DoSomethingInUIThread(() => + { + Common.MainForm.ChangeIcon(-1); + Common.MainForm.UpdateNotifyIcon(); + }); + } + } + + private static string[] LiveMachineMatrix + { + get + { + bool twoRow = !Setting.Values.MatrixOneRow; + string[] connectedMachines = twoRow ? MachineMatrix : MachineMatrix.Select(m => Common.IsConnectedTo(IdFromName(m)) ? m : string.Empty).ToArray(); + Logger.LogDebug($"Matrix: {string.Join(",", MachineMatrix)}, Connected: {string.Join(",", connectedMachines)}"); + + return connectedMachines; + } + } + + internal static void UpdateMachinePoolStringSetting() + { + Setting.Values.MachinePoolString = MachineStuff.MachinePool.SerializedAsString(); + } + + internal static void SendMachineMatrix() + { + if (MachineMatrix == null) + { + return; + } + + DATA package = new(); + + for (int i = 0; i < MachineMatrix.Length; i++) + { + package.MachineName = MachineMatrix[i]; + + package.Type = PackageType.Matrix + | (Setting.Values.MatrixCircle ? PackageType.MatrixSwapFlag : 0) + | (Setting.Values.MatrixOneRow ? 0 : PackageType.MatrixTwoRowFlag); + + package.Src = (ID)(i + 1); + package.Des = ID.ALL; + + Common.SkSend(package, null, false); + + Logger.LogDebug($"matrixIncludedMachine sent: [{i + 1}]:[{MachineMatrix[i]}]"); + } + } + + internal static void UpdateMachineMatrix(DATA package) + { + uint i = (uint)package.Src; + string matrixIncludedMachine = package.MachineName; + + if (i is > 0 and <= MAX_MACHINE) + { + Logger.LogDebug($"matrixIncludedMachine: [{i}]:[{matrixIncludedMachine}]"); + + MachineMatrix[i - 1] = matrixIncludedMachine; + + if (i == MAX_MACHINE) + { + Setting.Values.MatrixCircle = (package.Type & PackageType.MatrixSwapFlag) == PackageType.MatrixSwapFlag; + Setting.Values.MatrixOneRow = !((package.Type & PackageType.MatrixTwoRowFlag) == PackageType.MatrixTwoRowFlag); + MachineMatrix = MachineMatrix; // Save + + Common.ReopenSocketDueToReadError = true; + + UpdateClientSockets("UpdateMachineMatrix"); + + Setting.Values.Changed = true; + } + } + else + { + Logger.LogDebug("Invalid machine Matrix package!"); + } + } + + internal static void SwitchToMachine(string name) + { + ID id = MachineStuff.MachinePool.ResolveID(name); + + if (id != ID.NONE) + { + // Ask current machine to hide the Mouse cursor + if (desMachineID != Common.MachineID) + { + Common.SendPackage(desMachineID, PackageType.HideMouse); + } + + NewDesMachineID = Common.DesMachineID = id; + SwitchLocation.X = Common.XY_BY_PIXEL + primaryScreenBounds.Left + ((primaryScreenBounds.Right - primaryScreenBounds.Left) / 2); + SwitchLocation.Y = Common.XY_BY_PIXEL + primaryScreenBounds.Top + ((primaryScreenBounds.Bottom - primaryScreenBounds.Top) / 2); + SwitchLocation.ResetCount(); + Common.UpdateMultipleModeIconAndMenu(); + Common.HideMouseCursor(false); + _ = Common.EvSwitch.Set(); + } + } + + internal static void SwitchToMultipleMode(bool multipleMode, bool centerScreen) + { + if (multipleMode) + { + PowerToysTelemetry.Log.WriteEvent(new MouseWithoutBorders.Telemetry.MouseWithoutBordersMultipleModeEvent()); + NewDesMachineID = Common.DesMachineID = ID.ALL; + } + else + { + NewDesMachineID = Common.DesMachineID = Common.MachineID; + } + + if (centerScreen) + { + Common.MoveMouseToCenter(); + } + + Common.ReleaseAllKeys(); + + Common.UpdateMultipleModeIconAndMenu(); + } + + internal static bool CheckSecondInstance(bool sendMessage = false) + { + int h; + + if ((h = NativeMethods.FindWindow(null, Setting.Values.MyID)) > 0) + { + return true; + } + + return false; + } + +#pragma warning disable SA1307 // Accessible fields should begin with upper-case letter + internal static EventWaitHandle oneInstanceCheck; +#pragma warning restore SA1307 + + internal static void AssertOneInstancePerDesktopSession() + { + string eventName = $"Global\\{Application.ProductName}-{FrmAbout.AssemblyVersion}-{Common.GetMyDesktop()}-{Common.CurrentProcess.SessionId}"; + oneInstanceCheck = new EventWaitHandle(false, EventResetMode.ManualReset, eventName, out bool created); + + if (!created) + { + Logger.TelemetryLogTrace($"Second instance found: {eventName}.", SeverityLevel.Warning, true); + Common.CurrentProcess.KillProcess(true); + } + } + + internal static ID IdFromName(string name) + { + return MachineStuff.MachinePool.ResolveID(name); + } + + internal static string NameFromID(ID id) + { + foreach (MachineInf inf in MachineStuff.MachinePool.TryFindMachineByID(id)) + { + if (!string.IsNullOrEmpty(inf.Name)) + { + return inf.Name; + } + } + + return null; + } + + internal static bool InMachineMatrix(string name) + { + if (MachineMatrix == null || string.IsNullOrWhiteSpace(name)) + { + return false; + } + + foreach (string st in MachineMatrix) + { + if (!string.IsNullOrWhiteSpace(st) && st.Trim().Equals(name.Trim(), StringComparison.OrdinalIgnoreCase)) + { + return true; + } + } + + return false; + } + + internal static void ClearComputerMatrix() + { + MachineStuff.MachineMatrix = new string[MachineStuff.MAX_MACHINE] { Common.MachineName.Trim(), string.Empty, string.Empty, string.Empty }; + MachineStuff.MachinePool.Initialize(new string[] { Common.MachineName }); + MachineStuff.UpdateMachinePoolStringSetting(); + } +} diff --git a/src/modules/MouseWithoutBorders/App/Core/MyRectangle.cs b/src/modules/MouseWithoutBorders/App/Core/MyRectangle.cs new file mode 100644 index 0000000000..82d408b2ee --- /dev/null +++ b/src/modules/MouseWithoutBorders/App/Core/MyRectangle.cs @@ -0,0 +1,21 @@ +// Copyright (c) Microsoft Corporation +// The Microsoft Corporation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +// +// Machine setup/switching implementation. +// +// +// 2008 created by Truong Do (ductdo). +// 2009-... modified by Truong Do (TruongDo). +// 2023- Included in PowerToys. +// +namespace MouseWithoutBorders.Core; + +internal sealed class MyRectangle +{ + internal int Left; + internal int Top; + internal int Right; + internal int Bottom; +} diff --git a/src/modules/MouseWithoutBorders/App/Core/Receiver.cs b/src/modules/MouseWithoutBorders/App/Core/Receiver.cs index 4ef8a8ccdc..787c9a5a9e 100644 --- a/src/modules/MouseWithoutBorders/App/Core/Receiver.cs +++ b/src/modules/MouseWithoutBorders/App/Core/Receiver.cs @@ -120,16 +120,16 @@ internal static class Receiver if (package.Des == Common.MachineID || package.Des == ID.ALL) { - if (Common.desMachineID != Common.MachineID) + if (MachineStuff.desMachineID != Common.MachineID) { - Common.NewDesMachineID = Common.DesMachineID = Common.MachineID; + MachineStuff.NewDesMachineID = Common.DesMachineID = Common.MachineID; } // NOTE(@yuyoyuppe): disabled to drop elevation requirement bool nonElevated = Common.RunWithNoAdminRight && false; if (nonElevated && Setting.Values.OneWayControlMode && package.Md.dwFlags != Common.WM_MOUSEMOVE) { - if (!Common.IsDropping) + if (!DragDrop.IsDropping) { if (package.Md.dwFlags is Common.WM_LBUTTONDOWN or Common.WM_RBUTTONDOWN) { @@ -138,7 +138,7 @@ internal static class Receiver } else if (package.Md.dwFlags is Common.WM_LBUTTONUP or Common.WM_RBUTTONUP) { - Common.IsDropping = false; + DragDrop.IsDropping = false; } return; @@ -153,7 +153,7 @@ internal static class Receiver package.Md.Y < 0 ? package.Md.Y + Common.MOVE_MOUSE_RELATIVE : package.Md.Y - Common.MOVE_MOUSE_RELATIVE); _ = NativeMethods.GetCursorPos(ref lastXY); - Point p = Common.MoveToMyNeighbourIfNeeded(lastXY.X, lastXY.Y, Common.MachineID); + Point p = MachineStuff.MoveToMyNeighbourIfNeeded(lastXY.X, lastXY.Y, Common.MachineID); if (!p.IsEmpty) { @@ -162,11 +162,11 @@ internal static class Receiver Logger.LogDebug(string.Format( CultureInfo.CurrentCulture, "***** Controlled Machine: newDesMachineIdEx set = [{0}]. Mouse is now at ({1},{2})", - Common.newDesMachineIdEx, + MachineStuff.newDesMachineIdEx, lastXY.X, lastXY.Y)); - Common.SendNextMachine(package.Src, Common.newDesMachineIdEx, p); + Common.SendNextMachine(package.Src, MachineStuff.newDesMachineIdEx, p); } } else @@ -188,8 +188,8 @@ internal static class Receiver CustomCursor.ShowFakeMouseCursor(Common.LastX, Common.LastY); } - Common.DragDropStep01(package.Md.dwFlags); - Common.DragDropStep09(package.Md.dwFlags); + DragDrop.DragDropStep01(package.Md.dwFlags); + DragDrop.DragDropStep09(package.Md.dwFlags); break; case PackageType.NextMachine: @@ -204,7 +204,7 @@ internal static class Receiver case PackageType.ExplorerDragDrop: Common.PackageReceived.ExplorerDragDrop++; - Common.DragDropStep03(package); + DragDrop.DragDropStep03(package); break; case PackageType.Heartbeat: @@ -219,12 +219,12 @@ internal static class Receiver Common.SendPackage(ID.ALL, PackageType.Heartbeat_ex_l2); } - string desMachine = Common.AddToMachinePool(package); + string desMachine = MachineStuff.AddToMachinePool(package); if (Setting.Values.FirstRun && !string.IsNullOrEmpty(desMachine)) { Common.UpdateSetupMachineMatrix(desMachine); - Common.UpdateClientSockets("UpdateSetupMachineMatrix"); + MachineStuff.UpdateClientSockets("UpdateSetupMachineMatrix"); } break; @@ -244,14 +244,14 @@ internal static class Receiver case PackageType.Awake: Common.PackageReceived.Heartbeat++; - _ = Common.AddToMachinePool(package); + _ = MachineStuff.AddToMachinePool(package); Common.HumanBeingDetected(); break; case PackageType.Hello: Common.PackageReceived.Hello++; Common.SendHeartBeat(); - string newMachine = Common.AddToMachinePool(package); + string newMachine = MachineStuff.AddToMachinePool(package); if (Setting.Values.MachineMatrixString == null) { string tip = newMachine + " saying Hello!"; @@ -345,17 +345,17 @@ internal static class Receiver case PackageType.ClipboardDragDrop: Common.PackageReceived.ClipboardDragDrop++; - Common.DragDropStep08(package); + DragDrop.DragDropStep08(package); break; case PackageType.ClipboardDragDropOperation: Common.PackageReceived.ClipboardDragDrop++; - Common.DragDropStep08_2(package); + DragDrop.DragDropStep08_2(package); break; case PackageType.ClipboardDragDropEnd: Common.PackageReceived.ClipboardDragDropEnd++; - Common.DragDropStep12(); + DragDrop.DragDropStep12(); break; case PackageType.ClipboardText: @@ -391,7 +391,7 @@ internal static class Receiver if ((package.Type & PackageType.Matrix) == PackageType.Matrix) { Common.PackageReceived.Matrix++; - Common.UpdateMachineMatrix(package); + MachineStuff.UpdateMachineMatrix(package); break; } else @@ -406,7 +406,7 @@ internal static class Receiver internal static void GetNameOfMachineWithClipboardData(DATA package) { Common.LastIDWithClipboardData = package.Src; - List matchingMachines = Common.MachinePool.TryFindMachineByID(Common.LastIDWithClipboardData); + List matchingMachines = MachineStuff.MachinePool.TryFindMachineByID(Common.LastIDWithClipboardData); if (matchingMachines.Count >= 1) { Common.LastMachineWithClipboardData = matchingMachines[0].Name.Trim(); diff --git a/src/modules/MouseWithoutBorders/App/Form/Settings/SettingsForm.cs b/src/modules/MouseWithoutBorders/App/Form/Settings/SettingsForm.cs index 768e0bdadc..ac6ec8c311 100644 --- a/src/modules/MouseWithoutBorders/App/Form/Settings/SettingsForm.cs +++ b/src/modules/MouseWithoutBorders/App/Form/Settings/SettingsForm.cs @@ -39,7 +39,7 @@ namespace MouseWithoutBorders protected override void OnClosing(System.ComponentModel.CancelEventArgs e) { - Common.Settings = null; + MachineStuff.Settings = null; if (_currentPage != null) { diff --git a/src/modules/MouseWithoutBorders/App/Form/Settings/SettingsFormPage.cs b/src/modules/MouseWithoutBorders/App/Form/Settings/SettingsFormPage.cs index af4361a33c..39574ac8fe 100644 --- a/src/modules/MouseWithoutBorders/App/Form/Settings/SettingsFormPage.cs +++ b/src/modules/MouseWithoutBorders/App/Form/Settings/SettingsFormPage.cs @@ -6,6 +6,7 @@ using System; using System.Windows.Forms; using MouseWithoutBorders.Class; +using MouseWithoutBorders.Core; using MouseWithoutBorders.Form.Settings; namespace MouseWithoutBorders @@ -59,8 +60,8 @@ namespace MouseWithoutBorders MessageBoxDefaultButton.Button2) == DialogResult.Yes) { Setting.Values.FirstRun = false; - Common.CloseSetupForm(); - Common.ShowMachineMatrix(); + MachineStuff.CloseSetupForm(); + MachineStuff.ShowMachineMatrix(); } } } diff --git a/src/modules/MouseWithoutBorders/App/Form/Settings/SetupPage1.cs b/src/modules/MouseWithoutBorders/App/Form/Settings/SetupPage1.cs index 2020e2f9f5..ae50f78231 100644 --- a/src/modules/MouseWithoutBorders/App/Form/Settings/SetupPage1.cs +++ b/src/modules/MouseWithoutBorders/App/Form/Settings/SetupPage1.cs @@ -4,6 +4,8 @@ using System; +using MouseWithoutBorders.Core; + namespace MouseWithoutBorders { public partial class SetupPage1 : SettingsFormPage @@ -12,7 +14,7 @@ namespace MouseWithoutBorders { InitializeComponent(); - Common.ClearComputerMatrix(); + MachineStuff.ClearComputerMatrix(); } private void NoButtonClick(object sender, EventArgs e) diff --git a/src/modules/MouseWithoutBorders/App/Form/Settings/SetupPage2a.cs b/src/modules/MouseWithoutBorders/App/Form/Settings/SetupPage2a.cs index 40adf62b6c..c86df58143 100644 --- a/src/modules/MouseWithoutBorders/App/Form/Settings/SetupPage2a.cs +++ b/src/modules/MouseWithoutBorders/App/Form/Settings/SetupPage2a.cs @@ -6,6 +6,7 @@ using System.Globalization; using System.Text.RegularExpressions; using MouseWithoutBorders.Class; +using MouseWithoutBorders.Core; namespace MouseWithoutBorders { @@ -92,12 +93,12 @@ namespace MouseWithoutBorders SecurityCode = Common.MyKey; } - Common.MachineMatrix = new string[Common.MAX_MACHINE] { ComputerNameField.Text.Trim().ToUpper(CultureInfo.CurrentCulture), Common.MachineName.Trim(), string.Empty, string.Empty }; + MachineStuff.MachineMatrix = new string[MachineStuff.MAX_MACHINE] { ComputerNameField.Text.Trim().ToUpper(CultureInfo.CurrentCulture), Common.MachineName.Trim(), string.Empty, string.Empty }; - string[] machines = Common.MachineMatrix; - Common.MachinePool.Initialize(machines); + string[] machines = MachineStuff.MachineMatrix; + MachineStuff.MachinePool.Initialize(machines); - Common.UpdateMachinePoolStringSetting(); + MachineStuff.UpdateMachinePoolStringSetting(); SendNextPage(new SetupPage3a { ReturnToSettings = !Setting.Values.FirstRun }); } diff --git a/src/modules/MouseWithoutBorders/App/Form/Settings/SetupPage3a.cs b/src/modules/MouseWithoutBorders/App/Form/Settings/SetupPage3a.cs index ea5334f3a5..84d464d33d 100644 --- a/src/modules/MouseWithoutBorders/App/Form/Settings/SetupPage3a.cs +++ b/src/modules/MouseWithoutBorders/App/Form/Settings/SetupPage3a.cs @@ -70,7 +70,7 @@ namespace MouseWithoutBorders ShowStatus($"Connecting..."); - Common.SwitchToMultipleMode(false, false); + MachineStuff.SwitchToMultipleMode(false, false); Common.ReopenSockets(true); int timeOut = 0; diff --git a/src/modules/MouseWithoutBorders/App/Form/Settings/SetupPage5.cs b/src/modules/MouseWithoutBorders/App/Form/Settings/SetupPage5.cs index fdcde4edda..0463419bcc 100644 --- a/src/modules/MouseWithoutBorders/App/Form/Settings/SetupPage5.cs +++ b/src/modules/MouseWithoutBorders/App/Form/Settings/SetupPage5.cs @@ -4,6 +4,8 @@ using System; +using MouseWithoutBorders.Core; + namespace MouseWithoutBorders { public partial class SetupPage5 : SettingsFormPage @@ -16,8 +18,8 @@ namespace MouseWithoutBorders private void DoneButtonClick(object sender, EventArgs e) { // SendNextPage(new SettingsPage1()); - Common.CloseSetupForm(); - Common.ShowMachineMatrix(); + MachineStuff.CloseSetupForm(); + MachineStuff.ShowMachineMatrix(); } } } diff --git a/src/modules/MouseWithoutBorders/App/Form/frmMatrix.cs b/src/modules/MouseWithoutBorders/App/Form/frmMatrix.cs index 7d4e2da3fa..8f23dba1a2 100644 --- a/src/modules/MouseWithoutBorders/App/Form/frmMatrix.cs +++ b/src/modules/MouseWithoutBorders/App/Form/frmMatrix.cs @@ -76,8 +76,8 @@ namespace MouseWithoutBorders return; } - string[] st = new string[Common.MAX_MACHINE]; - for (int i = 0; i < Common.MAX_MACHINE; i++) + string[] st = new string[MachineStuff.MAX_MACHINE]; + for (int i = 0; i < MachineStuff.MAX_MACHINE; i++) { if (machines[i].MachineEnabled) { @@ -98,7 +98,7 @@ namespace MouseWithoutBorders } } - Common.MachineMatrix = st; + MachineStuff.MachineMatrix = st; Setting.Values.MatrixOneRow = matrixOneRow = !checkBoxTwoRow.Checked; if (Process.GetCurrentProcess().SessionId != NativeMethods.WTSGetActiveConsoleSessionId()) @@ -124,7 +124,7 @@ namespace MouseWithoutBorders Common.MMSleep(0.2); } - Common.SendMachineMatrix(); + MachineStuff.SendMachineMatrix(); } buttonOK.Enabled = true; @@ -150,13 +150,13 @@ namespace MouseWithoutBorders bool meAdded = false; string machineName; - if (Common.MachineMatrix != null && Common.MachineMatrix.Length == Common.MAX_MACHINE) + if (MachineStuff.MachineMatrix != null && MachineStuff.MachineMatrix.Length == MachineStuff.MAX_MACHINE) { Logger.LogDebug("LoadMachines: Machine Matrix: " + Setting.Values.MachineMatrixString); - for (int i = 0; i < Common.MAX_MACHINE; i++) + for (int i = 0; i < MachineStuff.MAX_MACHINE; i++) { - machineName = Common.MachineMatrix[i].Trim(); + machineName = MachineStuff.MachineMatrix[i].Trim(); machines[i].MachineName = machineName; if (string.IsNullOrEmpty(machineName)) @@ -168,7 +168,7 @@ namespace MouseWithoutBorders machines[i].MachineEnabled = true; } - bool found = Common.MachinePool.TryFindMachineByName(machineName, out MachineInf machineInfo); + bool found = MachineStuff.MachinePool.TryFindMachineByName(machineName, out MachineInf machineInfo); if (found) { if (machineInfo.Id == Common.MachineID) @@ -340,7 +340,7 @@ namespace MouseWithoutBorders string newMachine; Machine unUsedMachine; - foreach (MachineInf inf in Common.MachinePool.ListAllMachines()) + foreach (MachineInf inf in MachineStuff.MachinePool.ListAllMachines()) { bool found = false; unUsedMachine = null; @@ -519,7 +519,7 @@ namespace MouseWithoutBorders return true; } - private readonly Machine[] machines = new Machine[Common.MAX_MACHINE]; + private readonly Machine[] machines = new Machine[MachineStuff.MAX_MACHINE]; private Machine dragDropMachine; private Machine desMachine; private Machine desMachineX; @@ -530,7 +530,7 @@ namespace MouseWithoutBorders private void CreateMachines() { - for (int i = 0; i < Common.MAX_MACHINE; i++) + for (int i = 0; i < MachineStuff.MAX_MACHINE; i++) { Machine m = new(); m.MouseDown += Machine_MouseDown; @@ -550,7 +550,7 @@ namespace MouseWithoutBorders int dx = (groupBoxMachineMatrix.Width - 40) / 4; int yOffset = groupBoxMachineMatrix.Height / 3; - for (int i = 0; i < Common.MAX_MACHINE; i++) + for (int i = 0; i < MachineStuff.MAX_MACHINE; i++) { machines[i].Left = matrixOneRow ? 22 + (i * dx) : 22 + dx + ((i % 2) * dx); machines[i].Top = matrixOneRow ? yOffset : (yOffset / 2) + (i / 2 * (machines[i].Width + 2)); @@ -649,7 +649,7 @@ namespace MouseWithoutBorders desMachineX = desMachineY = desMachine; - for (int i = 0; i < Common.MAX_MACHINE; i++) + for (int i = 0; i < MachineStuff.MAX_MACHINE; i++) { if (machines[i] == dragDropMachine) { @@ -703,9 +703,9 @@ namespace MouseWithoutBorders dragDropMachine.Top = desMachinePos.Y; Machine tmp; - for (int i = 0; i < Common.MAX_MACHINE - 1; i++) + for (int i = 0; i < MachineStuff.MAX_MACHINE - 1; i++) { - for (int j = 0; j < Common.MAX_MACHINE - 1 - i; j++) + for (int j = 0; j < MachineStuff.MAX_MACHINE - 1 - i; j++) { if (machines[j + 1].Top < machines[j].Top || (machines[j + 1].Top == machines[j].Top && machines[j + 1].Left < machines[j].Left)) { @@ -1041,7 +1041,7 @@ namespace MouseWithoutBorders { Setting.Values.MatrixCircle = checkBoxCircle.Checked; ShowUpdateMessage(); - Common.SendMachineMatrix(); + MachineStuff.SendMachineMatrix(); } } @@ -1187,8 +1187,8 @@ namespace MouseWithoutBorders ButtonCancel_Click(this, new EventArgs()); Setting.Values.FirstRun = true; Setting.Values.EasyMouse = (int)EasyMouseOption.Enable; - Common.ClearComputerMatrix(); - Common.ShowSetupForm(true); + MachineStuff.ClearComputerMatrix(); + MachineStuff.ShowSetupForm(true); } } diff --git a/src/modules/MouseWithoutBorders/App/Form/frmScreen.cs b/src/modules/MouseWithoutBorders/App/Form/frmScreen.cs index 027844315d..7963a75721 100644 --- a/src/modules/MouseWithoutBorders/App/Form/frmScreen.cs +++ b/src/modules/MouseWithoutBorders/App/Form/frmScreen.cs @@ -171,7 +171,7 @@ namespace MouseWithoutBorders internal void MenuOnClick(object sender, EventArgs e) { string name = (sender as ToolStripMenuItem).Text; - Common.SwitchToMachine(name); + MachineStuff.SwitchToMachine(name); } internal void UpdateMenu() @@ -199,11 +199,11 @@ namespace MouseWithoutBorders menuGetScreenCapture.DropDown.Items.Count - 1]); } - for (int i = 0; i < Common.MAX_MACHINE; i++) + for (int i = 0; i < MachineStuff.MAX_MACHINE; i++) { - string newMachine = Common.MachineMatrix[i].Trim(); + string newMachine = MachineStuff.MachineMatrix[i].Trim(); - if (Common.MachinePool.TryFindMachineByName(newMachine, out MachineInf inf) && MachinePool.IsAlive(inf)) + if (MachineStuff.MachinePool.TryFindMachineByName(newMachine, out MachineInf inf) && MachinePool.IsAlive(inf)) { ToolStripMenuItem newItem = new( newMachine, @@ -372,14 +372,14 @@ namespace MouseWithoutBorders Common.MyKey = Setting.Values.MyKey; } - Common.UpdateMachinePoolStringSetting(); + MachineStuff.UpdateMachinePoolStringSetting(); if (!Common.RunOnLogonDesktop && !Common.RunOnScrSaverDesktop && (Setting.Values.FirstRun || Common.KeyCorrupted)) { if (!shownSetupFormOneTime) { shownSetupFormOneTime = true; - Common.ShowMachineMatrix(); + MachineStuff.ShowMachineMatrix(); if (Common.KeyCorrupted && !Setting.Values.FirstRun) { @@ -439,7 +439,7 @@ namespace MouseWithoutBorders Common.GetMachineName(); Logger.LogDebug("Common.pleaseReopenSocket: " + Common.PleaseReopenSocket.ToString(CultureInfo.InvariantCulture)); Common.ReopenSockets(false); - Common.NewDesMachineID = Common.DesMachineID = Common.MachineID; + MachineStuff.NewDesMachineID = Common.DesMachineID = Common.MachineID; } } else @@ -457,7 +457,7 @@ namespace MouseWithoutBorders { Common.PleaseReopenSocket = 0; Thread.Sleep(1000); - Common.UpdateClientSockets("REOPEN_WHEN_WSAECONNRESET"); + MachineStuff.UpdateClientSockets("REOPEN_WHEN_WSAECONNRESET"); } if (Common.RunOnLogonDesktop) @@ -496,7 +496,7 @@ namespace MouseWithoutBorders if (!Common.RunOnLogonDesktop && !Common.RunOnScrSaverDesktop) { - Common.ShowMachineMatrix(); + MachineStuff.ShowMachineMatrix(); Common.MatrixForm?.UpdateKeyTextBox(); @@ -511,7 +511,7 @@ namespace MouseWithoutBorders if (myKeyDaysToExpire <= 0) { - Common.ShowMachineMatrix(); + MachineStuff.ShowMachineMatrix(); Common.Sk?.Close(false); @@ -532,7 +532,7 @@ namespace MouseWithoutBorders // if (Common.RunOnLogonDesktop) ShowMouseWithoutBordersUiOnWinLogonDesktop(false); #endif Common.CheckForDesktopSwitchEvent(true); - Common.UpdateClientSockets("helperTimer_Tick"); // Sockets may be closed by the remote host when both machines switch desktop at the same time. + MachineStuff.UpdateClientSockets("helperTimer_Tick"); // Sockets may be closed by the remote host when both machines switch desktop at the same time. } count++; @@ -553,11 +553,11 @@ namespace MouseWithoutBorders Logger.LogAll(); // Need to review this code on why it is needed (moved from MoveToMyNeighbourIfNeeded(...)) - for (int i = 0; i < Common.MachineMatrix.Length; i++) + for (int i = 0; i < MachineStuff.MachineMatrix.Length; i++) { - if (string.IsNullOrEmpty(Common.MachineMatrix[i]) && !Common.InMachineMatrix(Common.MachineName)) + if (string.IsNullOrEmpty(MachineStuff.MachineMatrix[i]) && !MachineStuff.InMachineMatrix(Common.MachineName)) { - Common.MachineMatrix[i] = Common.MachineName; + MachineStuff.MachineMatrix[i] = Common.MachineName; } } @@ -567,7 +567,7 @@ namespace MouseWithoutBorders if (Setting.Values.BlockScreenSaver || count % 3000 == 0) { Common.SendAwakeBeat(); - Common.RemoveDeadMachines(); + MachineStuff.RemoveDeadMachines(); // GC.Collect(); // GC.WaitForPendingFinalizers(); @@ -601,12 +601,12 @@ namespace MouseWithoutBorders private void MenuMachineMatrix_Click(object sender, EventArgs e) { - Common.ShowMachineMatrix(); + MachineStuff.ShowMachineMatrix(); } private void FrmScreen_MouseMove(object sender, MouseEventArgs e) { - if (!Common.IsDropping) + if (!Core.DragDrop.IsDropping) { if (Cursor != dotCur) { @@ -702,7 +702,7 @@ namespace MouseWithoutBorders internal void MenuAllPC_Click(object sender, EventArgs e) { Logger.LogDebug("menuAllPC_Click"); - Common.SwitchToMultipleMode(MenuAllPC.Checked, true); + MachineStuff.SwitchToMultipleMode(MenuAllPC.Checked, true); CurIcon = MenuAllPC.Checked ? Common.ICON_ALL : Common.ICON_ONE; ChangeIcon(CurIcon); } @@ -711,7 +711,7 @@ namespace MouseWithoutBorders { Common.DoSomethingInUIThread(() => { - MenuAllPC.Checked = Common.NewDesMachineID == ID.ALL; + MenuAllPC.Checked = MachineStuff.NewDesMachineID == ID.ALL; CurIcon = MenuAllPC.Checked ? Common.ICON_ALL : Common.ICON_ONE; ChangeIcon(CurIcon); }); @@ -819,7 +819,7 @@ namespace MouseWithoutBorders case NativeMethods.WM_CHECK_EXPLORER_DRAG_DROP: Logger.LogDebug("Got WM_CHECK_EXPLORER_DRAG_DROP!"); - Common.DragDropStep04(); + Core.DragDrop.DragDropStep04(); break; case NativeMethods.WM_QUIT: @@ -841,7 +841,7 @@ namespace MouseWithoutBorders case NativeMethods.WM_SHOW_SETTINGS_FORM: if (!Common.RunOnLogonDesktop && !Common.RunOnScrSaverDesktop) { - Common.ShowMachineMatrix(); + MachineStuff.ShowMachineMatrix(); } break; @@ -856,7 +856,7 @@ namespace MouseWithoutBorders { if (e.Button == MouseButtons.Left) { - Common.ShowMachineMatrix(); + MachineStuff.ShowMachineMatrix(); } } @@ -872,7 +872,7 @@ namespace MouseWithoutBorders internal void UpdateNotifyIcon() { - string[] x = Common.MachineMatrix; + string[] x = MachineStuff.MachineMatrix; string iconText; if (x != null && (x[0].Length > 0 || x[1].Length > 0 || x[2].Length > 0 || x[3].Length > 0)) { @@ -943,13 +943,13 @@ namespace MouseWithoutBorders string menuCaption = (sender as ToolStripMenuItem).Text; // Send CaptureScreenCommand - ID des = menuCaption.Equals("All", StringComparison.OrdinalIgnoreCase) ? ID.ALL : Common.IdFromName(menuCaption); + ID des = menuCaption.Equals("All", StringComparison.OrdinalIgnoreCase) ? ID.ALL : MachineStuff.IdFromName(menuCaption); Common.SendPackage(des, PackageType.CaptureScreenCommand); } private void FrmScreen_Shown(object sender, EventArgs e) { - Common.AssertOneInstancePerDesktopSession(); + MachineStuff.AssertOneInstancePerDesktopSession(); Common.MainForm = this; Hide(); @@ -1057,11 +1057,11 @@ namespace MouseWithoutBorders r.Right = Common.ScreenWidth - (Common.ScreenWidth / 5); r.Bottom = 20; - for (int i = 0; i < Common.MAX_MACHINE; i++) + for (int i = 0; i < MachineStuff.MAX_MACHINE; i++) { - string newMachine = Common.MachineMatrix[i].Trim(); + string newMachine = MachineStuff.MachineMatrix[i].Trim(); - if (Common.MachinePool.TryFindMachineByName(newMachine, out MachineInf inf) && MachinePool.IsAlive(inf)) + if (MachineStuff.MachinePool.TryFindMachineByName(newMachine, out MachineInf inf) && MachinePool.IsAlive(inf)) { machineMatrix += "[" + inf.Name.Trim() + "]"; } diff --git a/src/modules/MouseWithoutBorders/MouseWithoutBorders.UnitTests/Core/Logger.PrivateDump.expected.txt b/src/modules/MouseWithoutBorders/MouseWithoutBorders.UnitTests/Core/Logger.PrivateDump.expected.txt index dddef136c4..d4cc369a9f 100644 --- a/src/modules/MouseWithoutBorders/MouseWithoutBorders.UnitTests/Core/Logger.PrivateDump.expected.txt +++ b/src/modules/MouseWithoutBorders/MouseWithoutBorders.UnitTests/Core/Logger.PrivateDump.expected.txt @@ -68,11 +68,6 @@ avgSendTime = 0 maxSendTime = 0 totalSendCount = 0 totalSendTime = 0 -isDragging = False -dragDropStep05ExCalledByIpc = 0 -isDropping = False -dragMachine = NONE -k__BackingField = False magicNumber = 0 ran = System.Random --_impl = System.Random+XoshiroImpl @@ -163,35 +158,6 @@ ReopenSocketDueToReadError = False --MaxValue = 31/12/9999 23:59:59 --UnixEpoch = 01/01/1970 00:00:00 lastReleaseAllKeysCall = 0 -McMatrixLock = Lock ---_owningThreadId = 0 ---_state = 0 ---_recursionCount = 0 ---_spinCount = 22 ---_waiterStartTimeMs = 0 ---s_contentionCount = 0 ---s_maxSpinCount = 22 ---s_minSpinCountForAdaptiveSpin = -100 -desMachineID = NONE -DesMachineName = -newDesMachineID = NONE -newDesMachineIdEx = NONE -dropMachineID = NONE -lastJump = ???????????? -desktopBounds = MouseWithoutBorders.MyRectangle ---Left = 0 ---Top = 0 ---Right = 0 ---Bottom = 0 -primaryScreenBounds = MouseWithoutBorders.MyRectangle ---Left = 0 ---Top = 0 ---Right = 0 ---Bottom = 0 -SwitchLocation = MouseWithoutBorders.Class.MouseLocation ---k__BackingField = 0 ---k__BackingField = 0 ---k__BackingField = 0 PackageSent = MouseWithoutBorders.PackageMonitor --Keyboard = 0 --Mouse = 0 @@ -259,11 +225,6 @@ SymAlBlockSize = 16 PW_LENGTH = 16 HELPER_FORM_TEXT = Mouse without Borders Helper HelperProcessName = PowerToys.MouseWithoutBordersHelper -MAX_MACHINE = 4 -MAX_SOCKET = 8 -HEARTBEAT_TIMEOUT = 1500000 -SKIP_PIXELS = 1 -JUMP_PIXELS = 2 PACKAGE_SIZE = 32 PACKAGE_SIZE_EX = 64 WP_PACKAGE_SIZE = 6 @@ -358,6 +319,49 @@ MAX_LOG = 10000 MaxLogExceptionPerHour = 1000 HeaderSENT = Be{0},Ke{1},Mo{2},He{3},Mx{4},Tx{5},Im{6},By{7},Cl{8},Dr{9},De{10},Ed{11},Ie{12},Ni{13} HeaderRECEIVED = Be{0},Ke{1},Mo{2},He{3},Mx{4},Tx{5},Im{6},By{7},Cl{8},Dr{9},De{10},Ed{11},In{12},Ni{13},Pc{14}/{15} +[DragDrop] +=============== +isDragging = False +dragDropStep05ExCalledByIpc = 0 +isDropping = False +dragMachine = NONE +k__BackingField = False +[MachineStuff] +=============== +McMatrixLock = Lock +--_owningThreadId = 0 +--_state = 0 +--_recursionCount = 0 +--_spinCount = 22 +--_waiterStartTimeMs = 0 +--s_contentionCount = 0 +--s_maxSpinCount = 22 +--s_minSpinCountForAdaptiveSpin = -100 +desMachineID = NONE +DesMachineName = +newDesMachineID = NONE +newDesMachineIdEx = NONE +dropMachineID = NONE +lastJump = ???????????? +desktopBounds = MouseWithoutBorders.Core.MyRectangle +--Left = 0 +--Top = 0 +--Right = 0 +--Bottom = 0 +primaryScreenBounds = MouseWithoutBorders.Core.MyRectangle +--Left = 0 +--Top = 0 +--Right = 0 +--Bottom = 0 +SwitchLocation = MouseWithoutBorders.Class.MouseLocation +--k__BackingField = 0 +--k__BackingField = 0 +--k__BackingField = 0 +MAX_MACHINE = 4 +MAX_SOCKET = 8 +HEARTBEAT_TIMEOUT = 1500000 +SKIP_PIXELS = 1 +JUMP_PIXELS = 2 [Receiver] =============== QUEUE_SIZE = 50 diff --git a/src/modules/MouseWithoutBorders/MouseWithoutBorders.UnitTests/Core/LoggerTests.cs b/src/modules/MouseWithoutBorders/MouseWithoutBorders.UnitTests/Core/LoggerTests.cs index a3d3a173f1..2ef14453a0 100644 --- a/src/modules/MouseWithoutBorders/MouseWithoutBorders.UnitTests/Core/LoggerTests.cs +++ b/src/modules/MouseWithoutBorders/MouseWithoutBorders.UnitTests/Core/LoggerTests.cs @@ -120,6 +120,10 @@ public static class LoggerTests _ = Logger.PrivateDump(sb, new Common(), "[Other Logs]\r\n===============\r\n", 0, settingsDumpObjectsLevel, false); sb.AppendLine("[Logger]\r\n==============="); Logger.DumpType(sb, typeof(Logger), 0, settingsDumpObjectsLevel); + sb.AppendLine("[DragDrop]\r\n==============="); + Logger.DumpType(sb, typeof(DragDrop), 0, settingsDumpObjectsLevel); + sb.AppendLine("[MachineStuff]\r\n==============="); + Logger.DumpType(sb, typeof(MachineStuff), 0, settingsDumpObjectsLevel); sb.AppendLine("[Receiver]\r\n==============="); Logger.DumpType(sb, typeof(Receiver), 0, settingsDumpObjectsLevel); var actual = sb.ToString();