Skip to content

Commit

Permalink
Merge branch 'main' into launch-apps-3350
Browse files Browse the repository at this point in the history
  • Loading branch information
jefflord committed Dec 31, 2023
2 parents 61bdabd + a94b3ee commit bca4723
Show file tree
Hide file tree
Showing 130 changed files with 736 additions and 387 deletions.
47 changes: 1 addition & 46 deletions src/.editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -96,49 +96,4 @@ end_of_line = crlf
dotnet_diagnostic.IDE0065.severity = none

# IDE0009: Add this or Me qualification
dotnet_diagnostic.IDE0009.severity = none

# CA1859: Change type for improved performance
dotnet_diagnostic.CA1859.severity = none

# CA1716: Identifiers should not match keywords
dotnet_diagnostic.CA1716.severity = none

# SYSLIB1096: Convert to 'GeneratedComInterface'
dotnet_diagnostic.SYSLIB1096.severity = silent

# CA1309: Use ordinal StringComparison
dotnet_diagnostic.CA1309.severity = suggestion

# CS1615: Argument may not be passed with the ref keyword
dotnet_diagnostic.CS1615.severity = none

# CA1854: Prefer a 'TryGetValue' call over a Dictionary indexer access guarded by a 'ContainsKey' check to avoid double lookup
dotnet_diagnostic.CA1854.severity = suggestion

# CA1860: Avoid using 'Enumerable.Any()' extension method
dotnet_diagnostic.CA1860.severity = suggestion

# CA1861: Prefer 'static readonly' fields over constant array arguments if the called method is called repeatedly and is not mutating the passed array
dotnet_diagnostic.CA1861.severity = suggestion

# CA1862: Prefer using 'StringComparer'/'StringComparison' to perform case-insensitive string comparisons
dotnet_diagnostic.CA1862.severity = suggestion

# CA1863: Cache a CompositeFormat for repeated use in this formatting operation
dotnet_diagnostic.CA1863.severity = none

# CA1864: Prefer the 'IDictionary.TryAdd(TKey, TValue)' method
dotnet_diagnostic.CA1864.severity = suggestion

# CA1865: Use 'string.Method(char)' instead of 'string.Method(string)' for string with single char
dotnet_diagnostic.CA1865.severity = suggestion

# CA1869: Cache and reuse 'JsonSerializerOptions' instances
dotnet_diagnostic.CA1869.severity = none

# CA2208: Instantiate argument exceptions correctly
dotnet_diagnostic.CA2208.severity = none

# CS9191: The 'ref' modifier for argument corresponding to 'in' is equivalent to 'in'. Consider using 'in' instead.
dotnet_diagnostic.CS9191.severity = none
dotnet_diagnostic.IDE0009.severity = none
2 changes: 1 addition & 1 deletion src/common/AllExperiments/Experiments.cs
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ private async Task VariantAssignmentProvider_Initialize()

private string? AssignmentUnit { get; set; }

private IVariantAssignmentRequest GetVariantAssignmentRequest()
private VariantAssignmentRequest GetVariantAssignmentRequest()
{
var jsonFilePath = CreateFilePath();
try
Expand Down
12 changes: 7 additions & 5 deletions src/common/FilePreviewCommon/Formatters/JsonFormatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@ public class JsonFormatter : IFormatter
/// <inheritdoc/>
public string LangSet => "json";

private static readonly JsonSerializerOptions _serializerOptions = new JsonSerializerOptions
{
WriteIndented = true,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
};

/// <inheritdoc/>
public string Format(string value)
{
Expand All @@ -22,11 +28,7 @@ public string Format(string value)

using (var jDocument = JsonDocument.Parse(value, new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip }))
{
return JsonSerializer.Serialize(jDocument, new JsonSerializerOptions
{
WriteIndented = true,
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
});
return JsonSerializer.Serialize(jDocument, _serializerOptions);
}
}
}
Expand Down
36 changes: 36 additions & 0 deletions src/common/notifications/NotificationUtil.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
#pragma once

#include <common/notifications/notifications.h>
#include <common/notifications/dont_show_again.h>
#include <common/utils/resources.h>

#include "Generated Files/resource.h"

namespace notifications
{
// Non-Localizable strings
namespace NonLocalizable
{
const wchar_t RunAsAdminInfoPage[] = L"https://aka.ms/powertoysDetectedElevatedHelp";
const wchar_t ToastNotificationButtonUrl[] = L"powertoys://cant_drag_elevated_disable/";
}

inline void WarnIfElevationIsRequired(std::wstring title, std::wstring message, std::wstring button1, std::wstring button2)
{
using namespace NonLocalizable;

static bool warning_shown = false;
if (!warning_shown && !is_toast_disabled(ElevatedDontShowAgainRegistryPath, ElevatedDisableIntervalInDays))
{
std::vector<action_t> actions = {
link_button{ button1, RunAsAdminInfoPage },
link_button{ button2, ToastNotificationButtonUrl }
};
show_toast_with_activations(message,
title,
{},
std::move(actions));
warning_shown = true;
}
}
}
4 changes: 2 additions & 2 deletions src/common/notifications/dont_show_again.h
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@

namespace notifications
{
const inline wchar_t CantDragElevatedDontShowAgainRegistryPath[] = LR"(SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\DontShowMeThisDialogAgain\{e16ea82f-6d94-4f30-bb02-d6d911588afd})";
const inline int64_t CantDragElevatedDisableIntervalInDays = 30;
const inline wchar_t ElevatedDontShowAgainRegistryPath[] = LR"(SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\DontShowMeThisDialogAgain\{e16ea82f-6d94-4f30-bb02-d6d911588afd})";
const inline int64_t ElevatedDisableIntervalInDays = 30;

const inline wchar_t PreviewModulesDontShowAgainRegistryPath[] = LR"(SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\DontShowMeThisDialogAgain\{7e29e2b2-b31c-4dcd-b7b0-79c078b02430})";
const inline int64_t PreviewModulesDisableIntervalInDays = 30;
Expand Down
1 change: 1 addition & 0 deletions src/common/notifications/notifications.vcxproj
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
</ItemDefinitionGroup>
<ItemGroup>
<ClInclude Include="notifications.h" />
<ClInclude Include="NotificationUtil.h" />
<ClInclude Include="dont_show_again.h" />
<ClInclude Include="pch.h" />
</ItemGroup>
Expand Down
27 changes: 27 additions & 0 deletions src/common/utils/elevation.h
Original file line number Diff line number Diff line change
Expand Up @@ -537,3 +537,30 @@ inline bool check_user_is_admin()
freeMemory(pSID, pGroupInfo);
return false;
}

inline bool IsProcessOfWindowElevated(HWND window)
{
DWORD pid = 0;
GetWindowThreadProcessId(window, &pid);
if (!pid)
{
return false;
}

wil::unique_handle hProcess{ OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION,
FALSE,
pid) };

wil::unique_handle token;

if (OpenProcessToken(hProcess.get(), TOKEN_QUERY, &token))
{
TOKEN_ELEVATION elevation;
DWORD size;
if (GetTokenInformation(token.get(), TokenElevation, &elevation, sizeof(elevation), &size))
{
return elevation.TokenIsElevated != 0;
}
}
return false;
}
2 changes: 1 addition & 1 deletion src/modules/Hosts/Hosts/Settings/UserSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public class UserSettings : IUserSettings
private const string HostsModuleName = "Hosts";
private const int MaxNumberOfRetry = 5;

private readonly ISettingsUtils _settingsUtils;
private readonly SettingsUtils _settingsUtils;
private readonly IFileSystemWatcher _watcher;
private readonly object _loadingSettingsLock = new object();

Expand Down
10 changes: 7 additions & 3 deletions src/modules/MouseWithoutBorders/App/Class/Common.Clipboard.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ internal partial class Common
private static string lastDragDropFile;
private static long clipboardCopiedTime;

internal static readonly char[] Comma = new char[] { ',' };
internal static readonly char[] Star = new char[] { '*' };
internal static readonly char[] NullSeparator = new char[] { '\0' };

internal static ID LastIDWithClipboardData { get; set; }

internal static string LastDragDropFile
Expand Down Expand Up @@ -406,7 +410,7 @@ private static void ConnectAndGetData(object postAction)

try
{
remoteMachine = postAct.Contains("mspaint,") ? postAct.Split(new char[] { ',' })[1] : Common.LastMachineWithClipboardData;
remoteMachine = postAct.Contains("mspaint,") ? postAct.Split(Comma)[1] : Common.LastMachineWithClipboardData;

remoteMachine = remoteMachine.Trim();

Expand Down Expand Up @@ -518,7 +522,7 @@ internal static void ReceiveAndProcessClipboardData(string remoteMachine, Socket

fileName = Common.GetStringU(header).Replace("\0", string.Empty);
Common.LogDebug("Header: " + fileName);
string[] headers = fileName.Split(new char[] { '*' });
string[] headers = fileName.Split(Star);

if (headers.Length < 2 || !long.TryParse(headers[0], out long dataSize))
{
Expand Down Expand Up @@ -973,7 +977,7 @@ internal static void SetClipboardData(byte[] data)

foreach (string txt in texts)
{
if (string.IsNullOrEmpty(txt.Trim(new char[] { '\0' })))
if (string.IsNullOrEmpty(txt.Trim(NullSeparator)))
{
continue;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@ namespace MouseWithoutBorders
{
internal partial class Common
{
private static SymmetricAlgorithm symAl;
#pragma warning disable SYSLIB0021
private static AesCryptoServiceProvider symAl;
#pragma warning restore SYSLIB0021
private static string myKey;
private static uint magicNumber;
private static Random ran = new(); // Used for non encryption related functionality.
Expand Down
8 changes: 5 additions & 3 deletions src/modules/MouseWithoutBorders/App/Class/Common.Helper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -313,7 +313,8 @@ internal static void RunDDHelper(bool cleanUp = false)
HasSwitchedMachineSinceLastCopy = true;

// Common.CreateLowIntegrityProcess("\"" + Path.GetDirectoryName(Application.ExecutablePath) + "\\MouseWithoutBordersHelper.exe\"", string.Empty, 0, false, 0);
if (Process.GetProcessesByName(HelperProcessName)?.Any() != true)
var processes = Process.GetProcessesByName(HelperProcessName);
if (processes?.Length == 0)
{
Log("Unable to start helper process.");
Common.ShowToolTip("Error starting Mouse Without Borders Helper, clipboard sharing will not work!", 5000, ToolTipIcon.Error);
Expand All @@ -325,7 +326,8 @@ internal static void RunDDHelper(bool cleanUp = false)
}
else
{
if (Process.GetProcessesByName(HelperProcessName)?.Any() == true)
var processes = Process.GetProcessesByName(HelperProcessName);
if (processes?.Length > 0)
{
Log("Helper process found running.");
}
Expand Down Expand Up @@ -432,7 +434,7 @@ internal static bool GetUserName()
{
if (string.IsNullOrEmpty(Setting.Values.Username) && !Common.RunOnLogonDesktop)
{
if (Program.User.ToLower(CultureInfo.CurrentCulture).Contains("system"))
if (Program.User.Contains("system", StringComparison.CurrentCultureIgnoreCase))
{
_ = Common.ImpersonateLoggedOnUserAndDoSomething(() =>
{
Expand Down
3 changes: 1 addition & 2 deletions src/modules/MouseWithoutBorders/App/Class/Common.Launch.cs
Original file line number Diff line number Diff line change
Expand Up @@ -84,12 +84,11 @@ internal static bool ImpersonateLoggedOnUserAndDoSomething(Action targetFunc)
}
}

[SuppressMessage("Microsoft.Globalization", "CA1304:SpecifyCultureInfo", MessageId = "System.String.ToLower", Justification = "Dotnet port with style preservation")]
internal static int CreateProcessInInputDesktopSession(string commandLine, string arg, string desktop, short wShowWindow, bool lowIntegrity = false)

// As user who runs explorer.exe
{
if (!Program.User.ToLower(CultureInfo.InvariantCulture).Contains("system"))
if (!Program.User.Contains("system", StringComparison.InvariantCultureIgnoreCase))
{
ProcessStartInfo s = new(commandLine, arg);
s.WindowStyle = wShowWindow != 0 ? ProcessWindowStyle.Normal : ProcessWindowStyle.Hidden;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ internal static void StartMouseWithoutBordersService(string desktopToRunMouseWit
{
Process[] ps = Process.GetProcessesByName("MouseWithoutBordersSvc");
if (ps.Any())
if (ps.Length != 0)
{
if (DateTime.UtcNow - lastStartServiceTime < TimeSpan.FromSeconds(5))
{
Expand Down
3 changes: 2 additions & 1 deletion src/modules/MouseWithoutBorders/App/Class/InputSimulation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,7 @@ internal static void MouseClickDotForm(int x, int y)
private static bool ctrlDown;
private static bool altDown;
private static bool shiftDown;
internal static readonly string[] Args = new string[] { "CAD" };

private static void ResetModifiersState(HotkeySettings matchingHotkey)
{
Expand Down Expand Up @@ -456,7 +457,7 @@ private static void InputProcessKeyEx(int vkCode, int flags, out bool eatKey)
if (ctrlDown && altDown)
{
ctrlDown = altDown = false;
new ServiceController("MouseWithoutBordersSvc").Start(new string[] { "CAD" });
new ServiceController("MouseWithoutBordersSvc").Start(Args);
}

break;
Expand Down
4 changes: 2 additions & 2 deletions src/modules/MouseWithoutBorders/App/Class/MachinePool.cs
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ public void Initialize(IEnumerable<string> machineNames)
}
else if (list.Count >= 4)
{
throw new ArgumentException("machineNames.Length > Common.MAX_MACHINE");
throw new ArgumentException($"The number of machines exceeded the maximum allowed limit of {Common.MAX_MACHINE}. Actual count: {list.Count}.");
}

_ = LearnMachine(name);
Expand All @@ -178,7 +178,7 @@ public void Initialize(IEnumerable<MachineInf> infos)
}
else if (list.Count >= 4)
{
throw new ArgumentException("infos.Length > Common.MAX_MACHINE");
throw new ArgumentException($"The number of machines exceeded the maximum allowed limit of {Common.MAX_MACHINE}. Actual count: {list.Count}.");
}

_ = LearnMachine(inf.Name);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,17 @@ namespace MouseWithoutBorders.Class
{
internal static class MachinePoolHelpers
{
internal static readonly char[] Comma = new char[] { ',' };
internal static readonly char[] Colon = new char[] { ':' };

internal static MachineInf[] LoadMachineInfoFromMachinePoolStringSetting(string s)
{
if (s == null)
{
throw new ArgumentNullException(s);
}

string[] st = s.Split(new char[] { ',' });
string[] st = s.Split(Comma);

if (st.Length < Common.MAX_MACHINE)
{
Expand All @@ -25,7 +28,7 @@ internal static MachineInf[] LoadMachineInfoFromMachinePoolStringSetting(string
MachineInf[] rv = new MachineInf[Common.MAX_MACHINE];
for (int i = 0; i < Common.MAX_MACHINE; i++)
{
string[] mc = st[i].Split(new char[] { ':' });
string[] mc = st[i].Split(Colon);
if (mc.Length == 2)
{
rv[i].Name = mc[0];
Expand Down
2 changes: 1 addition & 1 deletion src/modules/MouseWithoutBorders/App/Class/Setting.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ internal class Settings
{
internal bool Changed;

private readonly ISettingsUtils _settingsUtils;
private readonly SettingsUtils _settingsUtils;
private readonly object _loadingSettingsLock = new object();
private readonly IFileSystemWatcher _watcher;

Expand Down
8 changes: 5 additions & 3 deletions src/modules/MouseWithoutBorders/App/Class/SocketStuff.cs
Original file line number Diff line number Diff line change
Expand Up @@ -887,14 +887,14 @@ void ClientThread(object obj)

if (!string.IsNullOrEmpty(Setting.Values.Name2IP))
{
string[] name2ip = Setting.Values.Name2IP.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
string[] name2ip = Setting.Values.Name2IP.Split(Separator, StringSplitOptions.RemoveEmptyEntries);
string[] nameNip;

if (name2ip != null)
{
foreach (string st in name2ip)
{
nameNip = st.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
nameNip = st.Split(BlankSeparator, StringSplitOptions.RemoveEmptyEntries);

if (nameNip != null && nameNip.Length >= 2 && nameNip[0].Trim().Equals(machineName, StringComparison.OrdinalIgnoreCase)
&& IPAddress.TryParse(nameNip[1].Trim(), out IPAddress ip) && !validAddressesSt.Contains("[" + ip.ToString() + "]")
Expand Down Expand Up @@ -1063,7 +1063,7 @@ private bool CheckForSameSubNet(List<IPAddress> validatedAddresses, string machi

List<IPAddress> localIPv4Addresses = GetMyIPv4Addresses().ToList();

if (!localIPv4Addresses.Any())
if (localIPv4Addresses.Count == 0)
{
Common.Log($"No IPv4 resolved from the local machine: {Common.MachineName}");
return true;
Expand Down Expand Up @@ -1234,6 +1234,8 @@ private void FlagReopenSocketIfNeeded(Exception e)
}

private long lastRemoteMachineID;
internal static readonly string[] Separator = new string[] { "\r\n" };
internal static readonly char[] BlankSeparator = new char[] { ' ' };

private void MainTCPRoutine(TcpSk tcp, string machineName, bool isClient)
{
Expand Down
Loading

1 comment on commit bca4723

@github-actions
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@check-spelling-bot Report

🔴 Please review

See the 📜action log or 📝 job summary for details.

Unrecognized words (43)
actio
ALLOWCHORDS
ALREADYRUNNINGCLOSE
ALREADYRUNNINGCLOSEANDTERMINATE
ALREADYRUNNINGDONOTHING
ALREADYRUNNINGSHOWWINDOW
ALREADYRUNNINGSTARTANOTHER
ALREADYRUNNINGTERMINATE
ARGSFORPROGRAM
BIF
BROWSEINFO
CKBH
CLOSE'ing
cmdow
commdlg
CRTL
EDITSINGLESHORTCUT
EDITTHISSHORTCUT
ELEVATIONTYPEDIFFERENTUSER
ELEVATIONTYPEELEVATED
ELEVATIONTYPENORMAL
FILEMUSTEXIST
Lencode
LPITEMIDLIST
lpstr
NEWDIALOGSTYLE
ofn
OPENFILENAME
PATHMUSTEXIST
PATHTOPROGRAM
pids
PROCESSENTRY
Procses
RETURNONLYFSDIRS
ritchielawrence
runasuser
SNAPPROCESS
STARTINDIRFORPROGRAM
tlhelp
Toolhelp
URIOr
urlmon
wcsicmp
Previously acknowledged words that are now absent applicationframehost CHT constexpr DEU hashcode HEB JPN LAlt Lambson langword nodiscard pcs qps roundf RUS RValue SVE TKey tonos TValue weakme wifi 🫥
To accept these unrecognized words as correct and remove the previously acknowledged and now absent words, you could run the following commands

... in a clone of the git@github.com:jefflord/PowerToys.git repository
on the launch-apps-3350 branch (ℹ️ how do I use this?):

curl -s -S -L 'https://raw.githubusercontent.com/check-spelling/check-spelling/v0.0.22/apply.pl' |
perl - 'https://github.com/jefflord/PowerToys/actions/runs/7370798993/attempts/1'
Available 📚 dictionaries could cover words (expected and unrecognized) not in the 📘 dictionary

This includes both expected items (1859) from .github/actions/spell-check/expect.txt and unrecognized words (43)

Dictionary Entries Covers Uniquely
cspell:r/src/r.txt 543 1 1
cspell:cpp/src/people.txt 23 1
cspell:cpp/src/ecosystem.txt 51 1

Consider adding them (in .github/workflows/spelling2.yml) for uses: check-spelling/check-spelling@v0.0.22 in its with:

      with:
        extra_dictionaries:
          cspell:r/src/r.txt
          cspell:cpp/src/people.txt
          cspell:cpp/src/ecosystem.txt

To stop checking additional dictionaries, add (in .github/workflows/spelling2.yml) for uses: check-spelling/check-spelling@v0.0.22 in its with:

check_extra_dictionaries: ''
If the flagged items are 🤯 false positives

If items relate to a ...

  • binary file (or some other file you wouldn't want to check at all).

    Please add a file path to the excludes.txt file matching the containing file.

    File paths are Perl 5 Regular Expressions - you can test yours before committing to verify it will match your files.

    ^ refers to the file's path from the root of the repository, so ^README\.md$ would exclude README.md (on whichever branch you're using).

  • well-formed pattern.

    If you can write a pattern that would match it,
    try adding it to the patterns.txt file.

    Patterns are Perl 5 Regular Expressions - you can test yours before committing to verify it will match your lines.

    Note that patterns can't match multiline strings.

Please sign in to comment.