diff --git a/lib/TweetLib.Browser.CEF/Data/ContextMenuActionRegistry.cs b/lib/TweetLib.Browser.CEF/Data/ContextMenuActionRegistry.cs index 48279266..e8952677 100644 --- a/lib/TweetLib.Browser.CEF/Data/ContextMenuActionRegistry.cs +++ b/lib/TweetLib.Browser.CEF/Data/ContextMenuActionRegistry.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; namespace TweetLib.Browser.CEF.Data { - abstract class ContextMenuActionRegistry<T> { + abstract class ContextMenuActionRegistry<T> where T : notnull { private readonly Dictionary<T, Action> actions = new (); protected abstract T NextId(int n); diff --git a/lib/TweetLib.Browser.CEF/Data/ResourceHandlerRegistry.cs b/lib/TweetLib.Browser.CEF/Data/ResourceHandlerRegistry.cs index d761d367..ed6368d1 100644 --- a/lib/TweetLib.Browser.CEF/Data/ResourceHandlerRegistry.cs +++ b/lib/TweetLib.Browser.CEF/Data/ResourceHandlerRegistry.cs @@ -21,7 +21,7 @@ internal bool HasHandler(string url) { } private void Register(string url, Func<TResourceHandler> factory) { - if (!Uri.TryCreate(url, UriKind.Absolute, out Uri uri)) { + if (!Uri.TryCreate(url, UriKind.Absolute, out var uri)) { throw new ArgumentException("Resource handler URL must be absolute!"); } diff --git a/lib/TweetLib.Browser.CEF/Logic/JsDialogHandlerLogic.cs b/lib/TweetLib.Browser.CEF/Logic/JsDialogHandlerLogic.cs index 3309fffc..9fd84fba 100644 --- a/lib/TweetLib.Browser.CEF/Logic/JsDialogHandlerLogic.cs +++ b/lib/TweetLib.Browser.CEF/Logic/JsDialogHandlerLogic.cs @@ -9,7 +9,7 @@ private static (MessageDialogType, string) GetMessageDialogProperties(string tex int pipe = text.IndexOf('|'); if (pipe != -1) { - type = text.Substring(0, pipe) switch { + type = text[..pipe] switch { "error" => MessageDialogType.Error, "warning" => MessageDialogType.Warning, "info" => MessageDialogType.Information, @@ -18,7 +18,7 @@ private static (MessageDialogType, string) GetMessageDialogProperties(string tex }; if (type != MessageDialogType.None) { - text = text.Substring(pipe + 1); + text = text[(pipe + 1)..]; } } diff --git a/lib/TweetLib.Browser.CEF/Utils/CefUtils.cs b/lib/TweetLib.Browser.CEF/Utils/CefUtils.cs index e2c7f14f..db503a41 100644 --- a/lib/TweetLib.Browser.CEF/Utils/CefUtils.cs +++ b/lib/TweetLib.Browser.CEF/Utils/CefUtils.cs @@ -8,7 +8,7 @@ public static string GetCacheFolder(string storagePath) { return Path.Combine(storagePath, "Cache"); } - public static CommandLineArgs ParseCommandLineArguments(string argumentString) { + public static CommandLineArgs ParseCommandLineArguments(string? argumentString) { CommandLineArgs args = new CommandLineArgs(); if (string.IsNullOrWhiteSpace(argumentString)) { @@ -26,8 +26,8 @@ public static CommandLineArgs ParseCommandLineArguments(string argumentString) { value = "1"; } else { - key = matchValue.Substring(0, indexEquals).TrimStart('-'); - value = matchValue.Substring(indexEquals + 1).Trim('"'); + key = matchValue[..indexEquals].TrimStart('-'); + value = matchValue[(indexEquals + 1)..].Trim('"'); } if (key.Length != 0) { diff --git a/lib/TweetLib.Browser/Contexts/Notification.cs b/lib/TweetLib.Browser/Contexts/Notification.cs index 502f6af6..30672d96 100644 --- a/lib/TweetLib.Browser/Contexts/Notification.cs +++ b/lib/TweetLib.Browser/Contexts/Notification.cs @@ -1,9 +1,9 @@ namespace TweetLib.Browser.Contexts { public struct Notification { - public string TweetUrl { get; } + public string? TweetUrl { get; } public string? QuoteUrl { get; } - public Notification(string tweetUrl, string? quoteUrl) { + public Notification(string? tweetUrl, string? quoteUrl) { TweetUrl = tweetUrl; QuoteUrl = quoteUrl; } diff --git a/lib/TweetLib.Communication/Pipe/DuplexPipe.cs b/lib/TweetLib.Communication/Pipe/DuplexPipe.cs index aa9de305..fcd0c96f 100644 --- a/lib/TweetLib.Communication/Pipe/DuplexPipe.cs +++ b/lib/TweetLib.Communication/Pipe/DuplexPipe.cs @@ -13,13 +13,11 @@ public static Server CreateServer() { public static Client CreateClient(string token) { int space = token.IndexOf(' '); - return new Client(token.Substring(0, space), token.Substring(space + 1)); + return new Client(token[..space], token[(space + 1)..]); } private readonly PipeStream pipeIn; private readonly PipeStream pipeOut; - - private readonly Thread readerThread; private readonly StreamWriter writerStream; public event EventHandler<PipeReadEventArgs>? DataIn; @@ -27,13 +25,9 @@ public static Client CreateClient(string token) { private DuplexPipe(PipeStream pipeIn, PipeStream pipeOut) { this.pipeIn = pipeIn; this.pipeOut = pipeOut; - - this.readerThread = new Thread(ReaderThread) { - IsBackground = true - }; - - this.readerThread.Start(); this.writerStream = new StreamWriter(this.pipeOut); + + new Thread(ReaderThread) { IsBackground = true }.Start(); } private void ReaderThread() { @@ -95,8 +89,8 @@ internal PipeReadEventArgs(string line) { Data = string.Empty; } else { - Key = line.Substring(0, separatorIndex); - Data = line.Substring(separatorIndex + 1); + Key = line[..separatorIndex]; + Data = line[(separatorIndex + 1)..]; } } } diff --git a/lib/TweetLib.Core/Features/BaseResourceRequestHandler.cs b/lib/TweetLib.Core/Features/BaseResourceRequestHandler.cs index 116774b2..95a2e242 100644 --- a/lib/TweetLib.Core/Features/BaseResourceRequestHandler.cs +++ b/lib/TweetLib.Core/Features/BaseResourceRequestHandler.cs @@ -34,7 +34,7 @@ public static void LoadResourceRewriteRules(string rules) { if (resourceType is ResourceType.Script or ResourceType.Stylesheet && TweetDeckHashes.Count > 0) { Match match = TweetDeckResourceUrl.Match(url); - if (match.Success && TweetDeckHashes.TryGetValue($"{match.Groups[1]}.{match.Groups[3]}", out string hash)) { + if (match.Success && TweetDeckHashes.TryGetValue($"{match.Groups[1]}.{match.Groups[3]}", out var hash)) { if (match.Groups[2].Value == hash) { App.Logger.Debug("[RequestHandlerBase] Accepting " + url); } diff --git a/lib/TweetLib.Core/Features/FileDownloadManager.cs b/lib/TweetLib.Core/Features/FileDownloadManager.cs index 8d609fde..1e59ecf5 100644 --- a/lib/TweetLib.Core/Features/FileDownloadManager.cs +++ b/lib/TweetLib.Core/Features/FileDownloadManager.cs @@ -84,7 +84,7 @@ public void SaveImages(string[] urls, string? author) { var settings = new SaveFileDialogSettings { DialogTitle = oneImage ? "Save Image" : "Save Images", OverwritePrompt = oneImage, - FileName = qualityIndex == -1 ? filename : $"{author} {Path.ChangeExtension(filename, null)} {firstImageLink.Substring(qualityIndex + 1)}".Trim() + ext, + FileName = qualityIndex == -1 ? filename : $"{author} {Path.ChangeExtension(filename, null)} {firstImageLink[(qualityIndex + 1)..]}".Trim() + ext, Filters = new [] { new FileDialogFilter(oneImage ? "Image" : "Images", string.IsNullOrEmpty(ext) ? Array.Empty<string>() : new [] { ext }) } }; diff --git a/lib/TweetLib.Core/Features/Notifications/NotificationBrowser.Tweet.cs b/lib/TweetLib.Core/Features/Notifications/NotificationBrowser.Tweet.cs index e7c4fdfe..09bfc96b 100644 --- a/lib/TweetLib.Core/Features/Notifications/NotificationBrowser.Tweet.cs +++ b/lib/TweetLib.Core/Features/Notifications/NotificationBrowser.Tweet.cs @@ -56,7 +56,9 @@ public override void Show(IContextMenuBuilder menu, Context context) { menu.AddSeparator(); if (context.Notification is {} notification) { - AddCopyAction(menu, "Copy tweet address", notification.TweetUrl); + if (!string.IsNullOrEmpty(notification.TweetUrl)) { + AddCopyAction(menu, "Copy tweet address", notification.TweetUrl); + } if (!string.IsNullOrEmpty(notification.QuoteUrl)) { AddCopyAction(menu, "Copy quoted tweet address", notification.QuoteUrl!); @@ -72,7 +74,7 @@ public override void Dispose() { this.browserComponent.PageLoadEnd -= BrowserComponentOnPageLoadEnd; } - private void BrowserComponentOnPageLoadEnd(object sender, PageLoadEventArgs e) { + private void BrowserComponentOnPageLoadEnd(object? sender, PageLoadEventArgs e) { string url = e.Url; if (TwitterUrls.IsTweetDeck(url) && url != BlankURL) { diff --git a/lib/TweetLib.Core/Features/Plugins/Plugin.cs b/lib/TweetLib.Core/Features/Plugins/Plugin.cs index 4f440a55..aea26ffe 100644 --- a/lib/TweetLib.Core/Features/Plugins/Plugin.cs +++ b/lib/TweetLib.Core/Features/Plugins/Plugin.cs @@ -93,7 +93,7 @@ public override int GetHashCode() { return Identifier.GetHashCode(); } - public override bool Equals(object obj) { + public override bool Equals(object? obj) { return obj is Plugin plugin && plugin.Identifier.Equals(Identifier); } diff --git a/lib/TweetLib.Core/Features/Plugins/PluginBridge.cs b/lib/TweetLib.Core/Features/Plugins/PluginBridge.cs index 7921e070..a5b11851 100644 --- a/lib/TweetLib.Core/Features/Plugins/PluginBridge.cs +++ b/lib/TweetLib.Core/Features/Plugins/PluginBridge.cs @@ -48,17 +48,17 @@ internal int GetTokenFromPlugin(Plugin plugin) { } internal Plugin? GetPluginFromToken(int token) { - return tokens.TryGetValue(token, out Plugin plugin) ? plugin : null; + return tokens.TryGetValue(token, out var plugin) ? plugin : null; } // Event handlers - private void manager_Reloaded(object sender, PluginErrorEventArgs e) { + private void manager_Reloaded(object? sender, PluginErrorEventArgs e) { tokens.Clear(); fileCache.Clear(); } - private void Config_PluginChangedState(object sender, PluginChangedStateEventArgs e) { + private void Config_PluginChangedState(object? sender, PluginChangedStateEventArgs e) { if (!e.IsEnabled) { int token = GetTokenFromPlugin(e.Plugin); @@ -88,7 +88,7 @@ private string GetFullPathOrThrow(int token, PluginFolder folder, string path) { private string ReadFileUnsafe(int token, PluginFolder folder, string path, bool readCached) { string fullPath = GetFullPathOrThrow(token, folder, path); - if (readCached && fileCache.TryGetValue(token, folder, path, out string cachedContents)) { + if (readCached && fileCache.TryGetValue(token, folder, path, out var cachedContents)) { return cachedContents; } @@ -161,7 +161,7 @@ public void Clear() { cache.Clear(); } - public bool TryGetValue(int token, PluginFolder folder, string path, out string contents) { + public bool TryGetValue(int token, PluginFolder folder, string path, [MaybeNullWhen(false)] out string contents) { return cache.TryGetValue(token, Key(folder, path), out contents); } diff --git a/lib/TweetLib.Core/Features/Plugins/PluginLoader.cs b/lib/TweetLib.Core/Features/Plugins/PluginLoader.cs index d8faf0dc..eabb3efc 100644 --- a/lib/TweetLib.Core/Features/Plugins/PluginLoader.cs +++ b/lib/TweetLib.Core/Features/Plugins/PluginLoader.cs @@ -41,7 +41,7 @@ public static IEnumerable<Result<Plugin>> AllInFolder(string pluginFolder, strin private static Plugin FromFolder(string name, string pathRoot, string pathData, PluginGroup group) { Plugin.Builder builder = new Plugin.Builder(group, name, pathRoot, pathData); - foreach (var environment in Directory.EnumerateFiles(pathRoot, "*.js", SearchOption.TopDirectoryOnly).Select(Path.GetFileName).Select(EnvironmentFromFileName)) { + foreach (var environment in Directory.EnumerateFiles(pathRoot, "*.js", SearchOption.TopDirectoryOnly).Select(Path.GetFileName).Select(EnvironmentFromFileName!)) { builder.AddEnvironment(environment); } @@ -55,7 +55,7 @@ private static Plugin FromFolder(string name, string pathRoot, string pathData, string currentContents = string.Empty; foreach (string line in File.ReadAllLines(metaFile, Encoding.UTF8).Concat(EndTag).Select(static line => line.TrimEnd()).Where(static line => line.Length > 0)) { - if (line[0] == '[' && line[line.Length - 1] == ']') { + if (line[0] == '[' && line[^1] == ']') { if (currentTag != null) { SetProperty(builder, currentTag, currentContents); } @@ -106,7 +106,7 @@ private static void SetProperty(Plugin.Builder builder, string tag, string value builder.ConfigDefault = value; break; case "REQUIRES": - builder.RequiredVersion = Version.TryParse(value, out Version version) ? version : throw new FormatException($"Invalid required minimum version: {value}"); + builder.RequiredVersion = Version.TryParse(value, out var version) ? version : throw new FormatException($"Invalid required minimum version: {value}"); break; default: throw new FormatException($"Invalid metadata tag: {tag}"); diff --git a/lib/TweetLib.Core/Features/Plugins/PluginManager.cs b/lib/TweetLib.Core/Features/Plugins/PluginManager.cs index 12cb7495..4618dbf3 100644 --- a/lib/TweetLib.Core/Features/Plugins/PluginManager.cs +++ b/lib/TweetLib.Core/Features/Plugins/PluginManager.cs @@ -102,7 +102,7 @@ internal void Execute(PluginEnvironment environment, IScriptExecutor executor) { Executed?.Invoke(this, new PluginErrorEventArgs(errors)); } - private void Config_PluginChangedState(object sender, PluginChangedStateEventArgs e) { + private void Config_PluginChangedState(object? sender, PluginChangedStateEventArgs e) { browserExecutor?.RunFunction("TDPF_setPluginState", e.Plugin, e.IsEnabled); } diff --git a/lib/TweetLib.Core/Features/TweetDeck/TweetDeckBrowser.cs b/lib/TweetLib.Core/Features/TweetDeck/TweetDeckBrowser.cs index 6c968fe1..aed35bbb 100644 --- a/lib/TweetLib.Core/Features/TweetDeck/TweetDeckBrowser.cs +++ b/lib/TweetLib.Core/Features/TweetDeck/TweetDeckBrowser.cs @@ -71,12 +71,12 @@ public override void Dispose() { App.UserConfiguration.SoundNotificationChanged -= UserConfiguration_SoundNotificationChanged; } - private void browserComponent_BrowserLoaded(object sender, BrowserLoadedEventArgs e) { + private void browserComponent_BrowserLoaded(object? sender, BrowserLoadedEventArgs e) { e.AddDictionaryWords("tweetdeck", "TweetDeck", "tweetduck", "TweetDuck", "TD"); isBrowserReady = true; } - private void browserComponent_PageLoadStart(object sender, PageLoadEventArgs e) { + private void browserComponent_PageLoadStart(object? sender, PageLoadEventArgs e) { string url = e.Url; if (TwitterUrls.IsTweetDeck(url) || (TwitterUrls.IsTwitter(url) && !TwitterUrls.IsTwitterLogin2Factor(url))) { @@ -84,7 +84,7 @@ private void browserComponent_PageLoadStart(object sender, PageLoadEventArgs e) } } - private void browserComponent_PageLoadEnd(object sender, PageLoadEventArgs e) { + private void browserComponent_PageLoadEnd(object? sender, PageLoadEventArgs e) { string url = e.Url; if (TwitterUrls.IsTweetDeck(url)) { @@ -105,7 +105,7 @@ private void browserComponent_PageLoadEnd(object sender, PageLoadEventArgs e) { browserComponent.RunBootstrap("update"); } - private void pluginManager_Reloaded(object sender, PluginErrorEventArgs e) { + private void pluginManager_Reloaded(object? sender, PluginErrorEventArgs e) { if (e.HasErrors) { App.MessageDialogs.Error("Error Loading Plugins", "The following plugins will not be available until the issues are resolved:\n\n" + string.Join("\n\n", e.Errors)); } @@ -115,14 +115,14 @@ private void pluginManager_Reloaded(object sender, PluginErrorEventArgs e) { } } - private void pluginManager_Executed(object sender, PluginErrorEventArgs e) { + private void pluginManager_Executed(object? sender, PluginErrorEventArgs e) { if (e.HasErrors) { App.MessageDialogs.Error("Error Executing Plugins", "Failed to execute the following plugins:\n\n" + string.Join("\n\n", e.Errors)); } } - private void updateChecker_CheckFinished(object sender, UpdateCheckEventArgs e) { - var updateChecker = (UpdateChecker) sender; + private void updateChecker_CheckFinished(object? sender, UpdateCheckEventArgs e) { + var updateChecker = (UpdateChecker) sender!; e.Result.Handle(update => { string tag = update.VersionTag; @@ -144,7 +144,7 @@ private void updateChecker_CheckFinished(object sender, UpdateCheckEventArgs e) ignoreUpdateCheckError = true; } - private void UserConfiguration_GeneralEventHandler(object sender, EventArgs e) { + private void UserConfiguration_GeneralEventHandler(object? sender, EventArgs e) { UpdatePropertyObject(); } diff --git a/lib/TweetLib.Core/Features/TweetDeck/TweetDeckExtraContext.cs b/lib/TweetLib.Core/Features/TweetDeck/TweetDeckExtraContext.cs index d4f2bc9b..222254ae 100644 --- a/lib/TweetLib.Core/Features/TweetDeck/TweetDeckExtraContext.cs +++ b/lib/TweetLib.Core/Features/TweetDeck/TweetDeckExtraContext.cs @@ -24,15 +24,15 @@ public void SetLink(string type, string? url) { switch (type) { case "link": - Link = new Link(url!, url!); + Link = new Link(url, url); break; case "image": - Media = new Media(Type.Image, TwitterUrls.GetMediaLink(url!, App.UserConfiguration.TwitterImageQuality)); + Media = new Media(Type.Image, TwitterUrls.GetMediaLink(url, App.UserConfiguration.TwitterImageQuality)); break; case "video": - Media = new Media(Type.Video, url!); + Media = new Media(Type.Video, url); break; } } diff --git a/lib/TweetLib.Core/Features/Twitter/ImageUrl.cs b/lib/TweetLib.Core/Features/Twitter/ImageUrl.cs index 3e1d59ca..0318a14d 100644 --- a/lib/TweetLib.Core/Features/Twitter/ImageUrl.cs +++ b/lib/TweetLib.Core/Features/Twitter/ImageUrl.cs @@ -57,7 +57,7 @@ public static bool TryParse(string url, out ImageUrl obj) { return false; } - string originalUrl = url.Substring(0, question); + string originalUrl = url[..question]; obj = new ImageUrl(Path.HasExtension(originalUrl) ? originalUrl : originalUrl + imageExtension, imageQuality); return true; diff --git a/lib/TweetLib.Core/Features/Twitter/TwitterUrls.cs b/lib/TweetLib.Core/Features/Twitter/TwitterUrls.cs index 47f75ab3..60551b97 100644 --- a/lib/TweetLib.Core/Features/Twitter/TwitterUrls.cs +++ b/lib/TweetLib.Core/Features/Twitter/TwitterUrls.cs @@ -49,11 +49,11 @@ public enum UrlType { } public static UrlType Check(string url) { - if (url.Contains("\"")) { + if (url.Contains('"')) { return UrlType.Invalid; } - if (Uri.TryCreate(url, UriKind.Absolute, out Uri uri)) { + if (Uri.TryCreate(url, UriKind.Absolute, out var uri)) { string scheme = uri.Scheme; if (scheme == Uri.UriSchemeHttps || scheme == Uri.UriSchemeHttp || scheme == Uri.UriSchemeFtp || scheme == Uri.UriSchemeMailto) { diff --git a/lib/TweetLib.Core/Systems/Configuration/ConfigManager.cs b/lib/TweetLib.Core/Systems/Configuration/ConfigManager.cs index 5deae85c..9dc885db 100644 --- a/lib/TweetLib.Core/Systems/Configuration/ConfigManager.cs +++ b/lib/TweetLib.Core/Systems/Configuration/ConfigManager.cs @@ -16,7 +16,7 @@ static ConfigManager() { ConverterRegistry.Register(typeof(WindowState), new BasicTypeConverter<WindowState> { ConvertToString = static value => $"{(value.IsMaximized ? 'M' : '_')}{value.Bounds.X} {value.Bounds.Y} {value.Bounds.Width} {value.Bounds.Height}", ConvertToObject = static value => { - int[] elements = StringUtils.ParseInts(value.Substring(1), ' '); + int[] elements = StringUtils.ParseInts(value[1..], ' '); return new WindowState { Bounds = new Rectangle(elements[0], elements[1], elements[2], elements[3]), diff --git a/lib/TweetLib.Core/Systems/Logging/Logger.cs b/lib/TweetLib.Core/Systems/Logging/Logger.cs index 53221d3c..b834a508 100644 --- a/lib/TweetLib.Core/Systems/Logging/Logger.cs +++ b/lib/TweetLib.Core/Systems/Logging/Logger.cs @@ -43,7 +43,7 @@ private bool Log(string level, string message) { build.Append("Please, report all issues to: ").Append(Lib.IssueTrackerUrl).Append("\r\n\r\n"); } - build.Append("[").Append(DateTime.Now.ToString("G", Lib.Culture)).Append("] ").Append(level).Append("\r\n"); + build.Append('[').Append(DateTime.Now.ToString("G", Lib.Culture)).Append("] ").Append(level).Append("\r\n"); build.Append(message).Append("\r\n\r\n"); try { diff --git a/lib/TweetLib.Core/Systems/Updates/UpdateChecker.cs b/lib/TweetLib.Core/Systems/Updates/UpdateChecker.cs index 5b2d0fa5..a3b78800 100644 --- a/lib/TweetLib.Core/Systems/Updates/UpdateChecker.cs +++ b/lib/TweetLib.Core/Systems/Updates/UpdateChecker.cs @@ -37,7 +37,7 @@ public void Dispose() { InteractionManager.Dispose(); } - private void timer_Elapsed(object sender, ElapsedEventArgs e) { + private void timer_Elapsed(object? sender, ElapsedEventArgs e) { Check(false); } diff --git a/lib/TweetLib.Core/Systems/Updates/UpdateInteractionManager.cs b/lib/TweetLib.Core/Systems/Updates/UpdateInteractionManager.cs index 041ee2c3..431cfc49 100644 --- a/lib/TweetLib.Core/Systems/Updates/UpdateInteractionManager.cs +++ b/lib/TweetLib.Core/Systems/Updates/UpdateInteractionManager.cs @@ -26,7 +26,7 @@ public void ClearUpdate() { nextUpdate = null; } - private void updates_CheckFinished(object sender, UpdateCheckEventArgs e) { + private void updates_CheckFinished(object? sender, UpdateCheckEventArgs e) { UpdateInfo? foundUpdate = e.Result.HasValue ? e.Result.Value : null; if (nextUpdate != null && !nextUpdate.Equals(foundUpdate)) { diff --git a/lib/TweetLib.Utils/Collections/CommandLineArgs.cs b/lib/TweetLib.Utils/Collections/CommandLineArgs.cs index 4bf1ac9f..d7ffed3b 100644 --- a/lib/TweetLib.Utils/Collections/CommandLineArgs.cs +++ b/lib/TweetLib.Utils/Collections/CommandLineArgs.cs @@ -57,7 +57,7 @@ public void SetValue(string key, string value) { } public string? GetValue(string key) { - return values.TryGetValue(key.ToLower(), out string val) ? val : null; + return values.TryGetValue(key.ToLower(), out var val) ? val : null; } public void RemoveValue(string key) { diff --git a/lib/TweetLib.Utils/Collections/TwoKeyDictionary.cs b/lib/TweetLib.Utils/Collections/TwoKeyDictionary.cs index 92757f47..3e63bba6 100644 --- a/lib/TweetLib.Utils/Collections/TwoKeyDictionary.cs +++ b/lib/TweetLib.Utils/Collections/TwoKeyDictionary.cs @@ -11,7 +11,7 @@ namespace TweetLib.Utils.Collections { /// <typeparam name="V">The type of the values.</typeparam> [SuppressMessage("ReSharper", "UnusedMethodReturnValue.Global")] [SuppressMessage("ReSharper", "UnusedMember.Global")] - public sealed class TwoKeyDictionary<K1, K2, V> { + public sealed class TwoKeyDictionary<K1, K2, V> where K1 : notnull where K2 : notnull { private readonly Dictionary<K1, Dictionary<K2, V>> dict; private readonly int innerCapacity; @@ -41,7 +41,7 @@ public TwoKeyDictionary(int outerCapacity, int innerCapacity) { } set { - if (!dict.TryGetValue(outerKey, out Dictionary<K2, V> innerDict)) { + if (!dict.TryGetValue(outerKey, out Dictionary<K2, V>? innerDict)) { dict.Add(outerKey, innerDict = new Dictionary<K2, V>(innerCapacity)); } @@ -67,7 +67,7 @@ public IEnumerable<V> InnerValues { /// Throws if the key pair already exists. /// </summary> public void Add(K1 outerKey, K2 innerKey, V value) { - if (!dict.TryGetValue(outerKey, out Dictionary<K2, V> innerDict)) { + if (!dict.TryGetValue(outerKey, out Dictionary<K2, V>? innerDict)) { dict.Add(outerKey, innerDict = new Dictionary<K2, V>(innerCapacity)); } @@ -100,7 +100,7 @@ public bool Contains(K1 outerKey) { /// Determines whether the dictionary contains the key pair. /// </summary> public bool Contains(K1 outerKey, K2 innerKey) { - return dict.TryGetValue(outerKey, out Dictionary<K2, V> innerDict) && innerDict.ContainsKey(innerKey); + return dict.TryGetValue(outerKey, out Dictionary<K2, V>? innerDict) && innerDict.ContainsKey(innerKey); } /// <summary> @@ -122,8 +122,8 @@ public int Count(K1 outerKey) { /// Gets the value associated with the key pair. /// Returns true if the key pair was present. /// </summary> - public bool TryGetValue(K1 outerKey, K2 innerKey, out V value) { - if (dict.TryGetValue(outerKey, out Dictionary<K2, V> innerDict)) { + public bool TryGetValue(K1 outerKey, K2 innerKey, [MaybeNullWhen(false)] out V value) { + if (dict.TryGetValue(outerKey, out Dictionary<K2, V>? innerDict)) { return innerDict.TryGetValue(innerKey, out value); } else { @@ -145,7 +145,7 @@ public bool Remove(K1 outerKey) { /// Returns true if the key pair was present. /// </summary> public bool Remove(K1 outerKey, K2 innerKey) { - if (dict.TryGetValue(outerKey, out Dictionary<K2, V> innerDict) && innerDict.Remove(innerKey)) { + if (dict.TryGetValue(outerKey, out Dictionary<K2, V>? innerDict) && innerDict.Remove(innerKey)) { if (innerDict.Count == 0) { dict.Remove(outerKey); } diff --git a/lib/TweetLib.Utils/Dialogs/SaveFileDialogSettings.cs b/lib/TweetLib.Utils/Dialogs/SaveFileDialogSettings.cs index 82945f1d..08c42634 100644 --- a/lib/TweetLib.Utils/Dialogs/SaveFileDialogSettings.cs +++ b/lib/TweetLib.Utils/Dialogs/SaveFileDialogSettings.cs @@ -2,9 +2,9 @@ namespace TweetLib.Utils.Dialogs { public sealed class SaveFileDialogSettings { - public string DialogTitle { get; set; } = "Save File"; - public bool OverwritePrompt { get; set; } = true; - public string? FileName { get; set; } - public IReadOnlyList<FileDialogFilter>? Filters { get; set; } + public string DialogTitle { get; init; } = "Save File"; + public bool OverwritePrompt { get; init; } = true; + public string? FileName { get; init; } + public IReadOnlyList<FileDialogFilter>? Filters { get; init; } } } diff --git a/lib/TweetLib.Utils/Globalization/Language.cs b/lib/TweetLib.Utils/Globalization/Language.cs index 5089a88c..314cfadb 100644 --- a/lib/TweetLib.Utils/Globalization/Language.cs +++ b/lib/TweetLib.Utils/Globalization/Language.cs @@ -21,7 +21,7 @@ public Language(string code, string? alt = null) { } } - public override bool Equals(object obj) { + public override bool Equals(object? obj) { return obj is Language other && Code.Equals(other.Code, StringComparison.OrdinalIgnoreCase); } @@ -38,8 +38,8 @@ public override string ToString() { return cultureInfo.DisplayName == cultureInfo.NativeName ? capitalizedName : $"{capitalizedName}, {cultureInfo.DisplayName}"; } - public int CompareTo(Language other) { - return string.Compare(Name, other.Name, false, CultureInfo.InvariantCulture); + public int CompareTo(Language? other) { + return string.Compare(Name, other?.Name, false, CultureInfo.InvariantCulture); } } } diff --git a/lib/TweetLib.Utils/IO/CombinedFileStream.cs b/lib/TweetLib.Utils/IO/CombinedFileStream.cs index 41bb6932..766985e4 100644 --- a/lib/TweetLib.Utils/IO/CombinedFileStream.cs +++ b/lib/TweetLib.Utils/IO/CombinedFileStream.cs @@ -134,7 +134,7 @@ public sealed class Entry { public string[] KeyValue { get { int index = Identifier.IndexOf(KeySeparator); - return index == -1 ? StringUtils.EmptyArray : Identifier.Substring(index + 1).Split(KeySeparator); + return index == -1 ? StringUtils.EmptyArray : Identifier[(index + 1)..].Split(KeySeparator); } } diff --git a/lib/TweetLib.Utils/Serialization/Converters/BasicTypeConverter.cs b/lib/TweetLib.Utils/Serialization/Converters/BasicTypeConverter.cs index 9faca1e5..dc72b903 100644 --- a/lib/TweetLib.Utils/Serialization/Converters/BasicTypeConverter.cs +++ b/lib/TweetLib.Utils/Serialization/Converters/BasicTypeConverter.cs @@ -2,12 +2,12 @@ namespace TweetLib.Utils.Serialization.Converters { public sealed class BasicTypeConverter<T> : ITypeConverter { - public Func<T, string>? ConvertToString { get; set; } - public Func<string, T>? ConvertToObject { get; set; } + public Func<T, string>? ConvertToString { get; init; } + public Func<string, T>? ConvertToObject { get; init; } - bool ITypeConverter.TryWriteType(Type type, object value, out string? converted) { + bool ITypeConverter.TryWriteType(Type type, object? value, out string? converted) { try { - converted = ConvertToString!((T) value); + converted = ConvertToString!((T) value!); return true; } catch { converted = null; diff --git a/lib/TweetLib.Utils/Serialization/Converters/ClrTypeConverter.cs b/lib/TweetLib.Utils/Serialization/Converters/ClrTypeConverter.cs index 249c68bc..6e2aa7e2 100644 --- a/lib/TweetLib.Utils/Serialization/Converters/ClrTypeConverter.cs +++ b/lib/TweetLib.Utils/Serialization/Converters/ClrTypeConverter.cs @@ -6,18 +6,17 @@ sealed class ClrTypeConverter : ITypeConverter { private ClrTypeConverter() {} - bool ITypeConverter.TryWriteType(Type type, object value, out string? converted) { + bool ITypeConverter.TryWriteType(Type type, object? value, out string? converted) { switch (Type.GetTypeCode(type)) { case TypeCode.Boolean: - converted = value.ToString(); + converted = value!.ToString(); return true; case TypeCode.Int32: - converted = ((int) value).ToString(); // cast required for enums + converted = ((int) value!).ToString(); // cast required for enums return true; case TypeCode.String: - // ReSharper disable once ConstantConditionalAccessQualifier converted = value?.ToString(); return true; diff --git a/lib/TweetLib.Utils/Serialization/ITypeConverter.cs b/lib/TweetLib.Utils/Serialization/ITypeConverter.cs index 77cba01f..55b8a0b6 100644 --- a/lib/TweetLib.Utils/Serialization/ITypeConverter.cs +++ b/lib/TweetLib.Utils/Serialization/ITypeConverter.cs @@ -2,7 +2,7 @@ namespace TweetLib.Utils.Serialization { public interface ITypeConverter { - bool TryWriteType(Type type, object value, out string? converted); + bool TryWriteType(Type type, object? value, out string? converted); bool TryReadType(Type type, string value, out object? converted); } } diff --git a/lib/TweetLib.Utils/Serialization/SimpleObjectSerializer.cs b/lib/TweetLib.Utils/Serialization/SimpleObjectSerializer.cs index 4608c8ac..ce419b11 100644 --- a/lib/TweetLib.Utils/Serialization/SimpleObjectSerializer.cs +++ b/lib/TweetLib.Utils/Serialization/SimpleObjectSerializer.cs @@ -28,7 +28,7 @@ private static string UnescapeStream(StreamReader reader) { break; } else { - build.Append(data.Substring(index, nextIndex - index)); + build.Append(data[index..nextIndex]); char next = data[nextIndex + 1]; @@ -47,7 +47,7 @@ private static string UnescapeStream(StreamReader reader) { } } - return build.Append(data.Substring(index)).ToString(); + return build.Append(data[index..]).ToString(); } private readonly TypeConverterRegistry converterRegistry; @@ -114,7 +114,7 @@ public void Read(string file, T obj) { int nextPos = contents.IndexOf(NewLineReal, currentPos); if (nextPos == -1) { - line = contents.Substring(currentPos); + line = contents[currentPos..]; currentPos = -1; if (string.IsNullOrEmpty(line)) { @@ -133,10 +133,10 @@ public void Read(string file, T obj) { continue; } - string property = line.Substring(0, space); - string value = UnescapeLine(line.Substring(space + 1)); + string property = line[..space]; + string value = UnescapeLine(line[(space + 1)..]); - if (props.TryGetValue(property, out PropertyInfo info)) { + if (props.TryGetValue(property, out var info)) { var type = info.PropertyType; var converter = converterRegistry.TryGet(type) ?? ClrTypeConverter.Instance; diff --git a/lib/TweetLib.Utils/Startup/LockFile.cs b/lib/TweetLib.Utils/Startup/LockFile.cs index 25e17543..6f2e05ba 100644 --- a/lib/TweetLib.Utils/Startup/LockFile.cs +++ b/lib/TweetLib.Utils/Startup/LockFile.cs @@ -1,6 +1,5 @@ using System; using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; using System.IO; using System.Threading; using TweetLib.Utils.Static; @@ -91,7 +90,6 @@ public UnlockResult Unlock() { return UnlockResult.Success; } - [SuppressMessage("ReSharper", "PossibleNullReferenceException")] private LockResult DetermineLockingProcessOrFail(Exception originalException) { try { int pid; @@ -110,7 +108,7 @@ private LockResult DetermineLockingProcessOrFail(Exception originalException) { var foundProcess = Process.GetProcessById(pid); using var currentProcess = Process.GetCurrentProcess(); - if (currentProcess.MainModule.FileVersionInfo.InternalName == foundProcess.MainModule.FileVersionInfo.InternalName) { + if (currentProcess.MainModule!.FileVersionInfo.InternalName == foundProcess.MainModule!.FileVersionInfo.InternalName) { return new LockResult.HasProcess(foundProcess); } else { diff --git a/lib/TweetLib.Utils/Static/StringUtils.cs b/lib/TweetLib.Utils/Static/StringUtils.cs index bff10b66..394f91d5 100644 --- a/lib/TweetLib.Utils/Static/StringUtils.cs +++ b/lib/TweetLib.Utils/Static/StringUtils.cs @@ -40,7 +40,7 @@ public static (string before, string after)? SplitInTwo(string str, char search, return null; } - return (str.Substring(0, index), str.Substring(index + 1)); + return (str[..index], str[(index + 1)..]); } /// <summary> @@ -49,7 +49,7 @@ public static (string before, string after)? SplitInTwo(string str, char search, /// </summary> public static string ExtractBefore(string str, char search, int startIndex = 0) { int index = str.IndexOf(search, startIndex); - return index == -1 ? str : str.Substring(0, index); + return index == -1 ? str : str[..index]; } /// <summary> diff --git a/lib/TweetLib.Utils/Static/WebUtils.cs b/lib/TweetLib.Utils/Static/WebUtils.cs index d98049ba..1dd56b27 100644 --- a/lib/TweetLib.Utils/Static/WebUtils.cs +++ b/lib/TweetLib.Utils/Static/WebUtils.cs @@ -12,8 +12,10 @@ public static class WebUtils { private static void EnsureTLS12() { if (!hasMicrosoftBeenBroughtTo2008Yet) { + #pragma warning disable CS0618 ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12; ServicePointManager.SecurityProtocol &= ~(SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11); + #pragma warning restore CS0618 hasMicrosoftBeenBroughtTo2008Yet = true; } } diff --git a/lib/TweetTest.Core/Features/Twitter/TestTwitterUrls.fs b/lib/TweetTest.Core/Features/Twitter/TestTwitterUrls.fs index b4231f0a..a79769e4 100644 --- a/lib/TweetTest.Core/Features/Twitter/TestTwitterUrls.fs +++ b/lib/TweetTest.Core/Features/Twitter/TestTwitterUrls.fs @@ -47,7 +47,7 @@ module RegexAccount = Assert.True(isMatch("https://twitter.com/" + name)) module Match = - let extract str = TwitterUrls.RegexAccount.Match(str).Groups.[1].Value + let extract str = TwitterUrls.RegexAccount.Match(str).Groups[1].Value [<Fact>] let ``extracts account name from simple URL`` () = diff --git a/lib/TweetTest.Utils/Collections/TestCommandLineArgs.fs b/lib/TweetTest.Utils/Collections/TestCommandLineArgs.fs index bd8ebae1..0cbc5233 100644 --- a/lib/TweetTest.Utils/Collections/TestCommandLineArgs.fs +++ b/lib/TweetTest.Utils/Collections/TestCommandLineArgs.fs @@ -276,11 +276,11 @@ module ToDictionary = TestData.mixed.ToDictionary(dict) Assert.Equal(5, dict.Count) - Assert.Equal("1", dict.["flag1"]) - Assert.Equal("1", dict.["flag2"]) - Assert.Equal("1", dict.["flag3"]) - Assert.Equal("hello", dict.["val1"]) - Assert.Equal("world", dict.["val2"]) + Assert.Equal("1", dict["flag1"]) + Assert.Equal("1", dict["flag2"]) + Assert.Equal("1", dict["flag3"]) + Assert.Equal("hello", dict["val1"]) + Assert.Equal("world", dict["val2"]) [<Fact>] let ``prefers value if the same name is used for a flag and value`` () = @@ -288,7 +288,7 @@ module ToDictionary = TestData.duplicate.ToDictionary(dict) Assert.Equal(1, dict.Count) - Assert.Equal("value", dict.["duplicate"]) + Assert.Equal("value", dict["duplicate"]) module ToString = diff --git a/lib/TweetTest.Utils/Collections/TestTwoKeyDictionary.fs b/lib/TweetTest.Utils/Collections/TestTwoKeyDictionary.fs index d2bcc1d7..227cf022 100644 --- a/lib/TweetTest.Utils/Collections/TestTwoKeyDictionary.fs +++ b/lib/TweetTest.Utils/Collections/TestTwoKeyDictionary.fs @@ -38,36 +38,36 @@ module Indexer = [<InlineData("second", 2, 200.0)>] [<InlineData("third", 1, 1000.0)>] let ``get returns correct value`` (outerKey: string, innerKey: int, value: float) = - Assert.Equal(value, TestData.uniquevals.[outerKey, innerKey]) + Assert.Equal(value, TestData.uniquevals[outerKey, innerKey]) [<Fact>] let ``get throws if outer key is missing`` () = - Assert.Throws<KeyNotFoundException>(fun () -> TestData.uniquevals.["missing", 1] |> ignore) + Assert.Throws<KeyNotFoundException>(fun () -> TestData.uniquevals["missing", 1] |> ignore) [<Fact>] let ``get throws if inner key is missing`` () = - Assert.Throws<KeyNotFoundException>(fun () -> TestData.uniquevals.["first", 0] |> ignore) + Assert.Throws<KeyNotFoundException>(fun () -> TestData.uniquevals["first", 0] |> ignore) [<Fact>] let ``set modifies existing value`` () = let copy = TestData.uniquevals - copy.["first", 1] <- 50.0 + copy["first", 1] <- 50.0 - Assert.Equal(50.0, copy.["first", 1]) + Assert.Equal(50.0, copy["first", 1]) [<Fact>] let ``set creates new inner key`` () = let copy = TestData.uniquevals - copy.["second", 3] <- 300.0 + copy["second", 3] <- 300.0 - Assert.Equal(300.0, copy.["second", 3]) + Assert.Equal(300.0, copy["second", 3]) [<Fact>] let ``set creates new outer key`` () = let copy = TestData.uniquevals - copy.["fourth", 1] <- 10000.0 + copy["fourth", 1] <- 10000.0 - Assert.Equal(10000.0, copy.["fourth", 1]) + Assert.Equal(10000.0, copy["fourth", 1]) module InnerValues = @@ -93,14 +93,14 @@ module Add = let copy = TestData.uniquevals copy.Add("first", 4, 40.0) - Assert.Equal(40.0, copy.["first", 4]) + Assert.Equal(40.0, copy["first", 4]) [<Fact>] let ``creates new outer key`` () = let copy = TestData.uniquevals copy.Add("fourth", 1, 10000.0) - Assert.Equal(10000.0, copy.["fourth", 1]) + Assert.Equal(10000.0, copy["fourth", 1]) [<Fact>] let ``throw on duplicate key`` () = diff --git a/lib/TweetTest.Utils/IO/TestCombinedFileStream.fs b/lib/TweetTest.Utils/IO/TestCombinedFileStream.fs index e18b7253..9a252eb6 100644 --- a/lib/TweetTest.Utils/IO/TestCombinedFileStream.fs +++ b/lib/TweetTest.Utils/IO/TestCombinedFileStream.fs @@ -83,7 +83,7 @@ module ReadFile = [<InlineData("singleFile")>] [<InlineData("singleFileWithMultiIdentifier")>] let ``reading first file from single file stream returns an entry`` (stream: string) = - using TestData.singleFileStreams.[stream] (fun f -> + using TestData.singleFileStreams[stream] (fun f -> Assert.NotNull(f.ReadFile()) ) @@ -91,7 +91,7 @@ module ReadFile = [<InlineData("singleFile")>] [<InlineData("singleFileWithMultiIdentifier")>] let ``reading second file from single file stream returns null`` (stream: string) = - using TestData.singleFileStreams.[stream] (fun f -> + using TestData.singleFileStreams[stream] (fun f -> f.ReadFile() |> ignore Assert.Null(f.ReadFile()) ) @@ -197,7 +197,7 @@ module Entry = [<InlineData("singleFile")>] [<InlineData("singleFileWithMultiIdentifier")>] let ``contents of single file stream with are correct`` (stream: string) = - using TestData.singleFileStreams.[stream] (fun f -> + using TestData.singleFileStreams[stream] (fun f -> Assert.Equal("test file\n123", Encoding.UTF8.GetString(f.ReadFile().Contents)) ) diff --git a/windows/TweetDuck.Browser/Program.cs b/windows/TweetDuck.Browser/Program.cs index df25e075..bb49ffe5 100644 --- a/windows/TweetDuck.Browser/Program.cs +++ b/windows/TweetDuck.Browser/Program.cs @@ -25,7 +25,7 @@ private static int Main(string[] args) { private static async void KillWhenHung(int parentId) { try { using Process process = Process.GetProcessById(parentId); - process.WaitForExit(); + await process.WaitForExitAsync(); } catch { // ded } diff --git a/windows/TweetDuck.Video/Controls/LabelTooltip.cs b/windows/TweetDuck.Video/Controls/LabelTooltip.cs index 56383c1c..25bc8e76 100644 --- a/windows/TweetDuck.Video/Controls/LabelTooltip.cs +++ b/windows/TweetDuck.Video/Controls/LabelTooltip.cs @@ -30,7 +30,7 @@ public void AttachTooltip(Control control, bool followCursor, Func<MouseEventArg Text = text; - Point loc = form!.PointToClient(control.Parent.PointToScreen(new Point(control.Location.X + (followCursor ? args.X : control.Width / 2), 0))); + Point loc = form.PointToClient(control.Parent.PointToScreen(new Point(control.Location.X + (followCursor ? args.X : control.Width / 2), 0))); loc.X = Math.Max(0, Math.Min(form.Width - Width, loc.X - Width / 2)); loc.Y -= Height - Margin.Top + Margin.Bottom; Location = loc; @@ -42,7 +42,7 @@ public void AttachTooltip(Control control, bool followCursor, Func<MouseEventArg control.MouseLeave += control_MouseLeave; } - private void control_MouseLeave(object sender, EventArgs e) { + private void control_MouseLeave(object? sender, EventArgs e) { Visible = false; } } diff --git a/windows/TweetDuck.Video/FormPlayer.cs b/windows/TweetDuck.Video/FormPlayer.cs index 3882b482..cdd4e1e9 100644 --- a/windows/TweetDuck.Video/FormPlayer.cs +++ b/windows/TweetDuck.Video/FormPlayer.cs @@ -153,12 +153,12 @@ static void Disable(TableLayoutPanel panel) { // Events - private void FormPlayer_Load(object sender, EventArgs e) { + private void FormPlayer_Load(object? sender, EventArgs e) { Player.URL = videoUrl; } - private void pipe_DataIn(object sender, DuplexPipe.PipeReadEventArgs e) { - Invoke(new Action(() => { + private void pipe_DataIn(object? sender, DuplexPipe.PipeReadEventArgs e) { + Invoke(() => { switch (e.Key) { case "key": HandleKey((Keys) int.Parse(e.Data, NumberStyles.Integer)); @@ -168,7 +168,7 @@ private void pipe_DataIn(object sender, DuplexPipe.PipeReadEventArgs e) { StopVideo(); break; } - })); + }); } private void player_PlayStateChange(int newState) { @@ -215,7 +215,7 @@ private void timerUI_Tick(object? sender, EventArgs e) { Marshal.ReleaseComObject(controls); } - private void timerSync_Tick(object sender, EventArgs e) { + private void timerSync_Tick(object? sender, EventArgs e) { if (NativeMethods.GetWindowRect(ownerHandle, out NativeMethods.RECT rect)) { IWMPMedia media = Player.currentMedia; IWMPControls controls = Player.controls; @@ -312,12 +312,12 @@ private void timerSync_Tick(object sender, EventArgs e) { } } - private void timerData_Tick(object sender, EventArgs e) { + private void timerData_Tick(object? sender, EventArgs e) { timerData.Stop(); pipe.Write("vol", trackBarVolume.Value.ToString()); } - private void progressSeek_MouseDown(object sender, MouseEventArgs e) { + private void progressSeek_MouseDown(object? sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { IWMPMedia media = Player.currentMedia; IWMPControls controls = Player.controls; @@ -329,7 +329,7 @@ private void progressSeek_MouseDown(object sender, MouseEventArgs e) { } } - private void trackBarVolume_ValueChanged(object sender, EventArgs e) { + private void trackBarVolume_ValueChanged(object? sender, EventArgs e) { IWMPSettings settings = Player.settings; settings.volume = trackBarVolume.Value; @@ -341,23 +341,23 @@ private void trackBarVolume_ValueChanged(object sender, EventArgs e) { } } - private void trackBarVolume_MouseDown(object sender, MouseEventArgs e) { + private void trackBarVolume_MouseDown(object? sender, MouseEventArgs e) { isDragging = true; } - private void trackBarVolume_MouseUp(object sender, MouseEventArgs e) { + private void trackBarVolume_MouseUp(object? sender, MouseEventArgs e) { isDragging = false; } - private void imageClose_Click(object sender, EventArgs e) { + private void imageClose_Click(object? sender, EventArgs e) { StopVideo(); } - private void imageDownload_Click(object sender, EventArgs e) { + private void imageDownload_Click(object? sender, EventArgs e) { pipe.Write("download"); } - private void imageResize_Click(object sender, EventArgs e) { + private void imageResize_Click(object? sender, EventArgs e) { Player.fullScreen = true; } diff --git a/windows/TweetDuck/Application/FileDialogs.cs b/windows/TweetDuck/Application/FileDialogs.cs index eecfa9fe..0a5fcf8d 100644 --- a/windows/TweetDuck/Application/FileDialogs.cs +++ b/windows/TweetDuck/Application/FileDialogs.cs @@ -18,7 +18,7 @@ public void SaveFile(SaveFileDialogSettings settings, Action<string> onAccepted) }; if (dialog.ShowDialog() == DialogResult.OK) { - onAccepted(dialog.FileName); + onAccepted(dialog.FileName!); } }); } diff --git a/windows/TweetDuck/Application/SystemHandler.cs b/windows/TweetDuck/Application/SystemHandler.cs index fd5a870a..0217854c 100644 --- a/windows/TweetDuck/Application/SystemHandler.cs +++ b/windows/TweetDuck/Application/SystemHandler.cs @@ -13,7 +13,7 @@ namespace TweetDuck.Application { sealed class SystemHandler : IAppSystemHandler { - public void OpenBrowser(string url) { + public void OpenBrowser(string? url) { if (string.IsNullOrWhiteSpace(url)) { return; } @@ -23,7 +23,7 @@ public void OpenBrowser(string url) { switch (TwitterUrls.Check(url)) { case TwitterUrls.UrlType.Fine: - string browserPath = config.BrowserPath; + string? browserPath = config.BrowserPath; if (browserPath == null || !File.Exists(browserPath)) { OpenAssociatedProgram(url); @@ -120,7 +120,7 @@ public void OpenFileExplorer(string path) { void PerformSearch() { var config = Program.Config.User; - string searchUrl = config.SearchEngineUrl; + string? searchUrl = config.SearchEngineUrl; if (string.IsNullOrEmpty(searchUrl)) { if (FormMessage.Question("Search Options", "You have not configured a default search engine yet, would you like to do it now?", FormMessage.Yes, FormMessage.No)) { @@ -132,7 +132,7 @@ void PerformSearch() { return; } - FormSettings settings = FormManager.TryFind<FormSettings>(); + FormSettings? settings = FormManager.TryFind<FormSettings>(); if (settings == null) { return; @@ -146,7 +146,7 @@ void PerformSearch() { } } else { - App.SystemHandler.OpenBrowser(searchUrl + Uri.EscapeUriString(text)); + App.SystemHandler.OpenBrowser(searchUrl + Uri.EscapeDataString(text)); } } diff --git a/windows/TweetDuck/Browser/Base/CefBrowserComponent.cs b/windows/TweetDuck/Browser/Base/CefBrowserComponent.cs index 9a059ddf..a0bbfba2 100644 --- a/windows/TweetDuck/Browser/Base/CefBrowserComponent.cs +++ b/windows/TweetDuck/Browser/Base/CefBrowserComponent.cs @@ -10,7 +10,7 @@ sealed class CefBrowserComponent : BrowserComponentBase { public override string CacheFolder => CefUtils.GetCacheFolder(App.StoragePath); - public CefBrowserComponent(ChromiumWebBrowser browser, CreateContextMenu createContextMenu = null, bool autoReload = true) : base(browser, createContextMenu ?? DefaultContextMenuFactory, new JsDialogOpener(browser), PopupHandler.Instance, autoReload) { + public CefBrowserComponent(ChromiumWebBrowser browser, CreateContextMenu? createContextMenu = null, bool autoReload = true) : base(browser, createContextMenu ?? DefaultContextMenuFactory, new JsDialogOpener(browser), PopupHandler.Instance, autoReload) { browser.SetupZoomEvents(); } } diff --git a/windows/TweetDuck/Browser/Base/ContextMenuBase.cs b/windows/TweetDuck/Browser/Base/ContextMenuBase.cs index 96446da8..f78a952e 100644 --- a/windows/TweetDuck/Browser/Base/ContextMenuBase.cs +++ b/windows/TweetDuck/Browser/Base/ContextMenuBase.cs @@ -14,7 +14,7 @@ class ContextMenuBase : CefContextMenuHandler { protected static UserConfig Config => Program.Config.User; - public ContextMenuBase(IContextMenuHandler handler) : base(handler) {} + public ContextMenuBase(IContextMenuHandler? handler) : base(handler) {} protected override Context CreateContext(IContextMenuParams parameters) { return CreateContext(parameters, null, Config.TwitterImageQuality); @@ -55,7 +55,7 @@ protected static void AddSeparator(IMenuModel model) { } } - protected static Context CreateContext(IContextMenuParams parameters, TweetDeckExtraContext extraContext, ImageQuality imageQuality) { + protected static Context CreateContext(IContextMenuParams parameters, TweetDeckExtraContext? extraContext, ImageQuality imageQuality) { var context = new Context(); var flags = parameters.TypeFlags; @@ -74,7 +74,7 @@ protected static Context CreateContext(IContextMenuParams parameters, TweetDeckE return context; } - private static Link? GetLink(IContextMenuParams parameters, TweetDeckExtraContext extraContext) { + private static Link? GetLink(IContextMenuParams parameters, TweetDeckExtraContext? extraContext) { var link = extraContext?.Link; if (link != null) { return link; @@ -87,7 +87,7 @@ protected static Context CreateContext(IContextMenuParams parameters, TweetDeckE return null; } - private static Media? GetMedia(IContextMenuParams parameters, TweetDeckExtraContext extraContext, ImageQuality imageQuality) { + private static Media? GetMedia(IContextMenuParams parameters, TweetDeckExtraContext? extraContext, ImageQuality imageQuality) { var media = extraContext?.Media; if (media != null) { return media; diff --git a/windows/TweetDuck/Browser/Base/ContextMenuBrowser.cs b/windows/TweetDuck/Browser/Base/ContextMenuBrowser.cs index 598e3bcb..17fc9e8e 100644 --- a/windows/TweetDuck/Browser/Base/ContextMenuBrowser.cs +++ b/windows/TweetDuck/Browser/Base/ContextMenuBrowser.cs @@ -24,7 +24,7 @@ sealed class ContextMenuBrowser : ContextMenuBase { private readonly FormBrowser form; private readonly TweetDeckExtraContext extraContext; - public ContextMenuBrowser(FormBrowser form, IContextMenuHandler handler, TweetDeckExtraContext extraContext) : base(handler) { + public ContextMenuBrowser(FormBrowser form, IContextMenuHandler? handler, TweetDeckExtraContext extraContext) : base(handler) { this.form = form; this.extraContext = extraContext; } diff --git a/windows/TweetDuck/Browser/Base/ContextMenuNotification.cs b/windows/TweetDuck/Browser/Base/ContextMenuNotification.cs index 53f7aec2..3965f83a 100644 --- a/windows/TweetDuck/Browser/Base/ContextMenuNotification.cs +++ b/windows/TweetDuck/Browser/Base/ContextMenuNotification.cs @@ -8,7 +8,7 @@ namespace TweetDuck.Browser.Base { sealed class ContextMenuNotification : ContextMenuBase { private readonly FormNotificationBase form; - public ContextMenuNotification(FormNotificationBase form, IContextMenuHandler handler) : base(handler) { + public ContextMenuNotification(FormNotificationBase form, IContextMenuHandler? handler) : base(handler) { this.form = form; } diff --git a/windows/TweetDuck/Browser/Base/CustomKeyboardHandler.cs b/windows/TweetDuck/Browser/Base/CustomKeyboardHandler.cs index 6dd5b98e..15253a59 100644 --- a/windows/TweetDuck/Browser/Base/CustomKeyboardHandler.cs +++ b/windows/TweetDuck/Browser/Base/CustomKeyboardHandler.cs @@ -5,9 +5,9 @@ namespace TweetDuck.Browser.Base { sealed class CustomKeyboardHandler : IKeyboardHandler { - private readonly IBrowserKeyHandler handler; + private readonly IBrowserKeyHandler? handler; - public CustomKeyboardHandler(IBrowserKeyHandler handler) { + public CustomKeyboardHandler(IBrowserKeyHandler? handler) { this.handler = handler; } diff --git a/windows/TweetDuck/Browser/FormBrowser.cs b/windows/TweetDuck/Browser/FormBrowser.cs index d14674b9..41cda1af 100644 --- a/windows/TweetDuck/Browser/FormBrowser.cs +++ b/windows/TweetDuck/Browser/FormBrowser.cs @@ -49,7 +49,7 @@ public bool IsWaiting { } } - public UpdateInstaller UpdateInstaller { get; private set; } + public UpdateInstaller? UpdateInstaller { get; private set; } private readonly ResourceCache resourceCache; private readonly TweetDeckBrowser browser; @@ -63,8 +63,8 @@ public bool IsWaiting { private bool isLoaded; private FormWindowState prevState; - private TweetScreenshotManager notificationScreenshotManager; - private VideoPlayer videoPlayer; + private TweetScreenshotManager? notificationScreenshotManager; + private VideoPlayer? videoPlayer; public FormBrowser(ResourceCache resourceCache, PluginManager pluginManager, IUpdateCheckClient updateCheckClient, uint windowRestoreMessage) { InitializeComponent(); @@ -156,11 +156,11 @@ private void UpdateTray() { // event handlers - private void timerResize_Tick(object sender, EventArgs e) { + private void timerResize_Tick(object? sender, EventArgs e) { FormBrowser_ResizeEnd(this, e); // also stops timer } - private void FormBrowser_Activated(object sender, EventArgs e) { + private void FormBrowser_Activated(object? sender, EventArgs e) { if (!isLoaded) { return; } @@ -172,7 +172,7 @@ private void FormBrowser_Activated(object sender, EventArgs e) { } // the window, enable the browser again } - private void FormBrowser_LocationChanged(object sender, EventArgs e) { + private void FormBrowser_LocationChanged(object? sender, EventArgs e) { if (!isLoaded) { return; } @@ -181,7 +181,7 @@ private void FormBrowser_LocationChanged(object sender, EventArgs e) { timerResize.Start(); } - private void FormBrowser_Resize(object sender, EventArgs e) { + private void FormBrowser_Resize(object? sender, EventArgs e) { if (!isLoaded) { return; } @@ -204,7 +204,7 @@ private void FormBrowser_Resize(object sender, EventArgs e) { } } - private void FormBrowser_ResizeEnd(object sender, EventArgs e) { // also triggers when the window moves + private void FormBrowser_ResizeEnd(object? sender, EventArgs e) { // also triggers when the window moves if (!isLoaded) { return; } @@ -218,7 +218,7 @@ private void FormBrowser_ResizeEnd(object sender, EventArgs e) { // also trigger } } - private void FormBrowser_FormClosing(object sender, FormClosingEventArgs e) { + private void FormBrowser_FormClosing(object? sender, FormClosingEventArgs e) { if (!isLoaded) { return; } @@ -229,33 +229,33 @@ private void FormBrowser_FormClosing(object sender, FormClosingEventArgs e) { } } - private void FormBrowser_FormClosed(object sender, FormClosedEventArgs e) { + private void FormBrowser_FormClosed(object? sender, FormClosedEventArgs e) { if (isLoaded && UpdateInstaller == null) { updates.InteractionManager.ClearUpdate(); updates.InteractionManager.Dispose(); } } - private void Config_MuteToggled(object sender, EventArgs e) { + private void Config_MuteToggled(object? sender, EventArgs e) { UpdateFormIcon(); } - private void Config_TrayBehaviorChanged(object sender, EventArgs e) { + private void Config_TrayBehaviorChanged(object? sender, EventArgs e) { UpdateTray(); } - private void trayIcon_ClickRestore(object sender, EventArgs e) { + private void trayIcon_ClickRestore(object? sender, EventArgs e) { Show(); RestoreWindow(); Activate(); UpdateTray(); } - private void trayIcon_ClickClose(object sender, EventArgs e) { + private void trayIcon_ClickClose(object? sender, EventArgs e) { ForceClose(); } - private void updateInteractionManager_UpdateAccepted(object sender, UpdateInfo update) { + private void updateInteractionManager_UpdateAccepted(object? sender, UpdateInfo update) { this.InvokeAsyncSafe(() => { FormManager.CloseAllDialogs(); @@ -305,7 +305,7 @@ void OnFinished() { }); } - private void updateInteractionManager_UpdateDismissed(object sender, UpdateInfo update) { + private void updateInteractionManager_UpdateDismissed(object? sender, UpdateInfo update) { this.InvokeAsyncSafe(() => { Config.DismissedUpdate = update.VersionTag; Config.Save(); @@ -385,7 +385,7 @@ public void OpenSettings() { OpenSettings(null); } - public void OpenSettings(Type startTab) { + public void OpenSettings(Type? startTab) { if (!FormManager.TryBringToFront<FormSettings>()) { bool prevEnableUpdateCheck = Config.EnableUpdateCheck; @@ -464,7 +464,7 @@ private void PlayVideo(string videoUrl, string tweetUrl, string username, IJavas videoUrl = Regex.Replace(videoUrl, "^https://", "http://"); } - string playerPath = Config.VideoPlayerPath; + string? playerPath = Config.VideoPlayerPath; if (playerPath == null || !File.Exists(playerPath)) { if (videoPlayer == null) { @@ -512,7 +512,7 @@ private void OnTweetScreenshotReady(string html, int width) { notificationScreenshotManager.Trigger(html, width); } - private void DisplayTooltip(string text) { + private void DisplayTooltip(string? text) { if (string.IsNullOrEmpty(text)) { toolTip.Hide(this); } @@ -554,7 +554,7 @@ public void Alert(string type, string contents) { FormMessage.Show("TweetDuck Browser Message", contents, icon, FormMessage.OK); } - public void DisplayTooltip(string text) { + public void DisplayTooltip(string? text) { form.InvokeAsyncSafe(() => form.DisplayTooltip(text)); } diff --git a/windows/TweetDuck/Browser/Notification/FormNotificationBase.cs b/windows/TweetDuck/Browser/Notification/FormNotificationBase.cs index 188dd5b7..b1558dff 100644 --- a/windows/TweetDuck/Browser/Notification/FormNotificationBase.cs +++ b/windows/TweetDuck/Browser/Notification/FormNotificationBase.cs @@ -97,11 +97,11 @@ protected virtual FormBorderStyle NotificationBorderStyle { private readonly CefByteArrayResourceHandler resourceHandler = new CefByteArrayResourceHandler(); - private DesktopNotification currentNotification; + private DesktopNotification? currentNotification; private readonly HashSet<NotificationPauseReason> pauseReasons = new HashSet<NotificationPauseReason>(); - public string CurrentTweetUrl => currentNotification?.TweetUrl; - public string CurrentQuoteUrl => currentNotification?.QuoteUrl; + public string? CurrentTweetUrl => currentNotification?.TweetUrl; + public string? CurrentQuoteUrl => currentNotification?.QuoteUrl; protected bool IsPaused => pauseReasons.Count > 0; protected internal bool IsCursorOverBrowser => browser.Bounds.Contains(PointToClient(Cursor.Position)); @@ -156,7 +156,7 @@ protected override void WndProc(ref Message m) { // event handlers - private void owner_FormClosed(object sender, FormClosedEventArgs e) { + private void owner_FormClosed(object? sender, FormClosedEventArgs e) { Close(); } @@ -195,7 +195,7 @@ protected virtual void SetNotificationSize(int width, int height) { } protected virtual void UpdateTitle() { - string title = currentNotification?.ColumnTitle; + string? title = currentNotification?.ColumnTitle; Text = string.IsNullOrEmpty(title) || !Config.DisplayNotificationColumn ? Program.BrandName : $"{Program.BrandName} - {title}"; } @@ -214,7 +214,7 @@ public void MoveToVisibleLocation() { } } - public void DisplayTooltip(string text) { + public void DisplayTooltip(string? text) { if (string.IsNullOrEmpty(text)) { toolTip.Hide(this); } diff --git a/windows/TweetDuck/Browser/Notification/FormNotificationExample.cs b/windows/TweetDuck/Browser/Notification/FormNotificationExample.cs index 23efde65..866557ec 100644 --- a/windows/TweetDuck/Browser/Notification/FormNotificationExample.cs +++ b/windows/TweetDuck/Browser/Notification/FormNotificationExample.cs @@ -32,7 +32,7 @@ protected override FormBorderStyle NotificationBorderStyle { } } - public event EventHandler Ready; + public event EventHandler? Ready; private readonly DesktopNotification exampleNotification; diff --git a/windows/TweetDuck/Browser/Notification/FormNotificationMain.cs b/windows/TweetDuck/Browser/Notification/FormNotificationMain.cs index 386bb1ea..51ebb92c 100644 --- a/windows/TweetDuck/Browser/Notification/FormNotificationMain.cs +++ b/windows/TweetDuck/Browser/Notification/FormNotificationMain.cs @@ -23,7 +23,7 @@ public NotificationInterfaceImpl(FormNotificationBase notification) { this.notification = notification; } - public void DisplayTooltip(string text) { + public void DisplayTooltip(string? text) { notification.InvokeAsyncSafe(() => notification.DisplayTooltip(text)); } @@ -175,14 +175,14 @@ private IntPtr MouseHookProc(int nCode, IntPtr wParam, IntPtr lParam) { // event handlers - private void FormNotification_FormClosing(object sender, FormClosingEventArgs e) { + private void FormNotification_FormClosing(object? sender, FormClosingEventArgs e) { if (e.CloseReason == CloseReason.UserClosing) { HideNotification(); e.Cancel = true; } } - private void Browser_LoadingStateChanged(object sender, LoadingStateChangedEventArgs e) { + private void Browser_LoadingStateChanged(object? sender, LoadingStateChangedEventArgs e) { if (!e.IsLoading && browser.Address != NotificationBrowser.BlankURL) { this.InvokeSafe(() => { Visible = true; // ensures repaint before moving the window to a visible location @@ -191,12 +191,12 @@ private void Browser_LoadingStateChanged(object sender, LoadingStateChangedEvent } } - private void timerDisplayDelay_Tick(object sender, EventArgs e) { + private void timerDisplayDelay_Tick(object? sender, EventArgs e) { OnNotificationReady(); timerDisplayDelay.Stop(); } - private void timerHideProgress_Tick(object sender, EventArgs e) { + private void timerHideProgress_Tick(object? sender, EventArgs e) { bool isCursorInside = Bounds.Contains(Cursor.Position); if (isCursorInside) { diff --git a/windows/TweetDuck/Browser/Notification/FormNotificationTweet.cs b/windows/TweetDuck/Browser/Notification/FormNotificationTweet.cs index 95f8e157..2bb998b5 100644 --- a/windows/TweetDuck/Browser/Notification/FormNotificationTweet.cs +++ b/windows/TweetDuck/Browser/Notification/FormNotificationTweet.cs @@ -53,7 +53,7 @@ protected override bool CanDragWindow { } } - private void WindowsSessionManager_LockStateChanged(object sender, EventArgs e) { + private void WindowsSessionManager_LockStateChanged(object? sender, EventArgs e) { if (WindowsSessionManager.IsLocked) { PauseNotification(NotificationPauseReason.WindowsSessionLocked); } @@ -78,7 +78,7 @@ protected override void WndProc(ref Message m) { // event handlers - private void Config_MuteToggled(object sender, EventArgs e) { + private void Config_MuteToggled(object? sender, EventArgs e) { if (Config.MuteNotifications) { PauseNotification(NotificationPauseReason.UserConfiguration); } @@ -87,14 +87,14 @@ private void Config_MuteToggled(object sender, EventArgs e) { } } - private void timerCursorCheck_Tick(object sender, EventArgs e) { + private void timerCursorCheck_Tick(object? sender, EventArgs e) { if (!IsCursorOverNotificationArea) { ResumeNotification(NotificationPauseReason.CursorOverNotificationArea); timerCursorCheck.Stop(); } } - private void timerIdlePauseCheck_Tick(object sender, EventArgs e) { + private void timerIdlePauseCheck_Tick(object? sender, EventArgs e) { if (NativeMethods.GetIdleSeconds() < Config.NotificationIdlePauseSeconds) { ResumeNotification(NotificationPauseReason.SystemIdle); timerIdlePauseCheck.Stop(); diff --git a/windows/TweetDuck/Browser/Notification/Screenshot/FormNotificationScreenshotable.cs b/windows/TweetDuck/Browser/Notification/Screenshot/FormNotificationScreenshotable.cs index ae350d1b..b082a9fc 100644 --- a/windows/TweetDuck/Browser/Notification/Screenshot/FormNotificationScreenshotable.cs +++ b/windows/TweetDuck/Browser/Notification/Screenshot/FormNotificationScreenshotable.cs @@ -28,7 +28,7 @@ public FormNotificationScreenshotable(Action callback, FormBrowser owner, Plugin browserComponent.AttachBridgeObject("$TD_NotificationScreenshot", new ScreenshotBridge(this, SetScreenshotHeight, callback)); browserComponent.BrowserLoaded += (sender, args) => { - string script = ResourceUtils.ReadFileOrNull("notification/screenshot/screenshot.js"); + string? script = ResourceUtils.ReadFileOrNull("notification/screenshot/screenshot.js"); if (script == null) { this.InvokeAsyncSafe(callback); @@ -47,29 +47,27 @@ private void SetScreenshotHeight(int browserHeight) { this.height = BrowserUtils.Scale(browserHeight, SizeScale); } - public Task<Image> TakeScreenshot(bool ignoreHeightError = false) { - if (!ignoreHeightError) { - if (height == 0) { - FormMessage.Error("Screenshot Failed", "Could not detect screenshot size.", FormMessage.OK); - return null; - } - else if (height > ClientSize.Height) { - FormMessage.Error("Screenshot Failed", $"Screenshot is too large: {height}px > {ClientSize.Height}px", FormMessage.OK); - return null; - } + public Task<Image>? TakeScreenshot() { + if (height == 0) { + FormMessage.Error("Screenshot Failed", "Could not detect screenshot size.", FormMessage.OK); + return null; + } + else if (height > ClientSize.Height) { + FormMessage.Error("Screenshot Failed", $"Screenshot is too large: {height}px > {ClientSize.Height}px", FormMessage.OK); + return null; } return Task.Run(TakeScreenshotImpl); } private async Task<Image> TakeScreenshotImpl() { - if (this.height == 0) { - return null; + if (height == 0) { + throw new InvalidOperationException("Screenshot height must not be zero!"); } Viewport viewport = new Viewport { - Width = this.ClientSize.Width, - Height = this.height, + Width = ClientSize.Width, + Height = height, Scale = 1 }; diff --git a/windows/TweetDuck/Browser/Notification/Screenshot/TweetScreenshotManager.cs b/windows/TweetDuck/Browser/Notification/Screenshot/TweetScreenshotManager.cs index 736f24e1..5bd98e05 100644 --- a/windows/TweetDuck/Browser/Notification/Screenshot/TweetScreenshotManager.cs +++ b/windows/TweetDuck/Browser/Notification/Screenshot/TweetScreenshotManager.cs @@ -35,7 +35,7 @@ sealed class TweetScreenshotManager : IDisposable { public const int WaitFrames = 5; #endif - private FormNotificationScreenshotable screenshot; + private FormNotificationScreenshotable? screenshot; public TweetScreenshotManager(FormBrowser owner, PluginManager pluginManager) { this.owner = owner; @@ -53,14 +53,14 @@ public TweetScreenshotManager(FormBrowser owner, PluginManager pluginManager) { #endif } - private void timeout_Tick(object sender, EventArgs e) { + private void timeout_Tick(object? sender, EventArgs e) { timeout.Stop(); OnFinished(); } - private void disposer_Tick(object sender, EventArgs e) { + private void disposer_Tick(object? sender, EventArgs e) { disposer.Stop(); - screenshot.Dispose(); + screenshot?.Dispose(); screenshot = null; } @@ -88,12 +88,12 @@ private void Callback() { } timeout.Stop(); - screenshot.TakeScreenshot().ContinueWith(HandleResult, TaskScheduler.FromCurrentSynchronizationContext()); + screenshot?.TakeScreenshot()?.ContinueWith(HandleResult, TaskScheduler.FromCurrentSynchronizationContext()); } private void HandleResult(Task<Image> task) { if (task.IsFaulted) { - App.ErrorHandler.HandleException("Screenshot Failed", "An error occurred while taking a screenshot.", true, task.Exception!.InnerException); + App.ErrorHandler.HandleException("Screenshot Failed", "An error occurred while taking a screenshot.", true, task.Exception!.InnerException!); } else if (task.IsCompleted) { Clipboard.SetImage(task.Result); @@ -111,7 +111,10 @@ private void OnFinished() { debugger.Stop(); #endif - screenshot.Location = ControlExtensions.InvisibleLocation; + if (screenshot != null) { + screenshot.Location = ControlExtensions.InvisibleLocation; + } + owner.IsWaiting = false; disposer.Start(); } @@ -141,7 +144,7 @@ private void StartDebugger() { debugger.Start(); } - private void debugger_Tick(object sender, EventArgs e) { + private void debugger_Tick(object? sender, EventArgs e) { if (frameCounter < 63) { int frame = ++frameCounter; screenshot.TakeScreenshot(true).ContinueWith(task => SaveDebugFrame(task, frame), TaskScheduler.FromCurrentSynchronizationContext()); diff --git a/windows/TweetDuck/Browser/Notification/SoundNotification.cs b/windows/TweetDuck/Browser/Notification/SoundNotification.cs index cbbb79c5..b8b22313 100644 --- a/windows/TweetDuck/Browser/Notification/SoundNotification.cs +++ b/windows/TweetDuck/Browser/Notification/SoundNotification.cs @@ -40,13 +40,13 @@ private static (byte[] data, string mimeType)? CreateFileHandler(string path) { ".mp3" => "audio/mp3", ".flac" => "audio/flac", ".opus" => "audio/ogg; codecs=opus", - _ => null + _ => "application/octet-stream" }; try { return (File.ReadAllBytes(path), mimeType); } catch { - FormBrowser browser = FormManager.TryFind<FormBrowser>(); + FormBrowser? browser = FormManager.TryFind<FormBrowser>(); browser?.InvokeAsyncSafe(() => { using FormMessage form = new FormMessage("Sound Notification Error", "Could not find custom notification sound file:\n" + path, MessageBoxIcon.Error); diff --git a/windows/TweetDuck/Browser/TrayIcon.cs b/windows/TweetDuck/Browser/TrayIcon.cs index e0547393..0af203c5 100644 --- a/windows/TweetDuck/Browser/TrayIcon.cs +++ b/windows/TweetDuck/Browser/TrayIcon.cs @@ -17,8 +17,8 @@ public enum Behavior { // keep order private static UserConfig Config => Program.Config.User; - public event EventHandler ClickRestore; - public event EventHandler ClickClose; + public event EventHandler? ClickRestore; + public event EventHandler? ClickClose; public bool Visible { get { @@ -85,30 +85,30 @@ private void UpdateIcon() { // event handlers - private void Config_MuteToggled(object sender, EventArgs e) { + private void Config_MuteToggled(object? sender, EventArgs e) { UpdateIcon(); } - private void trayIcon_MouseClick(object sender, MouseEventArgs e) { + private void trayIcon_MouseClick(object? sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) { menuItemRestore_Click(sender, e); } } - private void contextMenu_Popup(object sender, EventArgs e) { + private void contextMenu_Popup(object? sender, EventArgs e) { ((ToolStripMenuItem) contextMenu.Items[1]).Checked = Config.MuteNotifications; } - private void menuItemRestore_Click(object sender, EventArgs e) { + private void menuItemRestore_Click(object? sender, EventArgs e) { ClickRestore?.Invoke(this, e); } - private void menuItemMuteNotifications_Click(object sender, EventArgs e) { + private void menuItemMuteNotifications_Click(object? sender, EventArgs e) { Config.MuteNotifications = !((ToolStripMenuItem) contextMenu.Items[1]).Checked; Config.Save(); } - private void menuItemClose_Click(object sender, EventArgs e) { + private void menuItemClose_Click(object? sender, EventArgs e) { ClickClose?.Invoke(this, e); } } diff --git a/windows/TweetDuck/Configuration/Arguments.cs b/windows/TweetDuck/Configuration/Arguments.cs index 157ed314..e3c8137c 100644 --- a/windows/TweetDuck/Configuration/Arguments.cs +++ b/windows/TweetDuck/Configuration/Arguments.cs @@ -21,7 +21,7 @@ public static bool HasFlag(string flag) { return Current.HasFlag(flag); } - public static string GetValue(string key) { + public static string? GetValue(string key) { return Current.GetValue(key); } diff --git a/windows/TweetDuck/Configuration/UserConfig.cs b/windows/TweetDuck/Configuration/UserConfig.cs index 26a3fcda..4dbd3791 100644 --- a/windows/TweetDuck/Configuration/UserConfig.cs +++ b/windows/TweetDuck/Configuration/UserConfig.cs @@ -29,18 +29,18 @@ sealed class UserConfig : BaseConfig<UserConfig>, IAppUserConfiguration { public bool EnableAnimatedImages { get; set; } = true; public bool HideTweetsByNftUsers { get; set; } = false; - private bool _enableSmoothScrolling = true; - private string _customCefArgs = null; + private bool _enableSmoothScrolling = true; + private string? _customCefArgs = null; - public string BrowserPath { get; set; } = null; - public string BrowserPathArgs { get; set; } = null; + public string? BrowserPath { get; set; } = null; + public string? BrowserPathArgs { get; set; } = null; public bool IgnoreTrackingUrlWarning { get; set; } = false; - public string SearchEngineUrl { get; set; } = null; + public string? SearchEngineUrl { get; set; } = null; private int _zoomLevel = 100; - public string VideoPlayerPath { get; set; } = null; - public string VideoPlayerPathArgs { get; set; } = null; - public int VideoPlayerVolume { get; set; } = 50; + public string? VideoPlayerPath { get; set; } = null; + public string? VideoPlayerPathArgs { get; set; } = null; + public int VideoPlayerVolume { get; set; } = 50; public bool EnableSpellCheck { get; set; } = false; private string _spellCheckLanguage = "en-US"; @@ -51,8 +51,8 @@ sealed class UserConfig : BaseConfig<UserConfig>, IAppUserConfiguration { private TrayIcon.Behavior _trayBehavior = TrayIcon.Behavior.Disabled; public bool EnableTrayHighlight { get; set; } = true; - public bool EnableUpdateCheck { get; set; } = true; - public string DismissedUpdate { get; set; } = null; + public bool EnableUpdateCheck { get; set; } = true; + public string? DismissedUpdate { get; set; } = null; public bool DisplayNotificationColumn { get; set; } = false; public bool NotificationMediaPreviews { get; set; } = true; @@ -74,13 +74,13 @@ sealed class UserConfig : BaseConfig<UserConfig>, IAppUserConfiguration { public Size CustomNotificationSize { get; set; } = Size.Empty; public int NotificationScrollSpeed { get; set; } = 100; - private string _notificationSoundPath; + private string? _notificationSoundPath; private int _notificationSoundVolume = 100; private bool _muteNotifications; - public string CustomBrowserCSS { get; set; } = null; - public string CustomNotificationCSS { get; set; } = null; + public string? CustomBrowserCSS { get; set; } = null; + public string? CustomNotificationCSS { get; set; } = null; public bool DevToolsInContextMenu { get; set; } = false; public bool DevToolsWindowOnTop { get; set; } = true; @@ -123,7 +123,7 @@ public bool EnableSmoothScrolling { set => UpdatePropertyWithCallback(ref _enableSmoothScrolling, value, App.ConfigManager.TriggerProgramRestartRequested); } - public string CustomCefArgs { + public string? CustomCefArgs { get => _customCefArgs; set => UpdatePropertyWithCallback(ref _customCefArgs, value, App.ConfigManager.TriggerProgramRestartRequested); } @@ -149,11 +149,11 @@ public string SpellCheckLanguage { // EVENTS - public event EventHandler MuteToggled; - public event EventHandler ZoomLevelChanged; - public event EventHandler TrayBehaviorChanged; - public event EventHandler SoundNotificationChanged; - public event EventHandler OptionsDialogClosed; + public event EventHandler? MuteToggled; + public event EventHandler? ZoomLevelChanged; + public event EventHandler? TrayBehaviorChanged; + public event EventHandler? SoundNotificationChanged; + public event EventHandler? OptionsDialogClosed; public void TriggerOptionsDialogClosed() { OptionsDialogClosed?.Invoke(this, EventArgs.Empty); diff --git a/windows/TweetDuck/Controls/ControlExtensions.cs b/windows/TweetDuck/Controls/ControlExtensions.cs index abbcbb89..16a69515 100644 --- a/windows/TweetDuck/Controls/ControlExtensions.cs +++ b/windows/TweetDuck/Controls/ControlExtensions.cs @@ -74,8 +74,8 @@ public static bool AlignValueToTick(this TrackBar trackBar) { public static void EnableMultilineShortcuts(this TextBox textBox) { textBox.KeyDown += (sender, args) => { - if (args.Control && args.KeyCode == Keys.A) { - ((TextBox) sender).SelectAll(); + if (args.Control && args.KeyCode == Keys.A && sender is TextBox tb) { + tb.SelectAll(); args.SuppressKeyPress = true; args.Handled = true; } diff --git a/windows/TweetDuck/Controls/FlatButton.cs b/windows/TweetDuck/Controls/FlatButton.cs index bd6b7256..b20e4198 100644 --- a/windows/TweetDuck/Controls/FlatButton.cs +++ b/windows/TweetDuck/Controls/FlatButton.cs @@ -9,7 +9,7 @@ public FlatButton() { GotFocus += FlatButton_GotFocus; } - private void FlatButton_GotFocus(object sender, EventArgs e) { // removes extra border when focused + private void FlatButton_GotFocus(object? sender, EventArgs e) { // removes extra border when focused NotifyDefault(false); } } diff --git a/windows/TweetDuck/Controls/NumericUpDownEx.cs b/windows/TweetDuck/Controls/NumericUpDownEx.cs index cce00691..4a2f5fdc 100644 --- a/windows/TweetDuck/Controls/NumericUpDownEx.cs +++ b/windows/TweetDuck/Controls/NumericUpDownEx.cs @@ -3,7 +3,7 @@ namespace TweetDuck.Controls { sealed class NumericUpDownEx : NumericUpDown { - public string TextSuffix { get; set ; } + public string? TextSuffix { get; set; } protected override void UpdateEditText() { base.UpdateEditText(); diff --git a/windows/TweetDuck/Dialogs/FormAbout.cs b/windows/TweetDuck/Dialogs/FormAbout.cs index 0ea02c3e..56610882 100644 --- a/windows/TweetDuck/Dialogs/FormAbout.cs +++ b/windows/TweetDuck/Dialogs/FormAbout.cs @@ -27,15 +27,15 @@ public FormAbout() { } } - private void OnLinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { + private void OnLinkClicked(object? sender, LinkLabelLinkClickedEventArgs e) { App.SystemHandler.OpenBrowser(e.Link.LinkData as string); } - private void FormAbout_HelpRequested(object sender, HelpEventArgs hlpevent) { + private void FormAbout_HelpRequested(object? sender, HelpEventArgs hlpevent) { ShowGuide(); } - private void FormAbout_HelpButtonClicked(object sender, CancelEventArgs e) { + private void FormAbout_HelpButtonClicked(object? sender, CancelEventArgs e) { e.Cancel = true; ShowGuide(); } diff --git a/windows/TweetDuck/Dialogs/FormGuide.cs b/windows/TweetDuck/Dialogs/FormGuide.cs index 49c1baa6..48de8dd5 100644 --- a/windows/TweetDuck/Dialogs/FormGuide.cs +++ b/windows/TweetDuck/Dialogs/FormGuide.cs @@ -12,12 +12,12 @@ namespace TweetDuck.Dialogs { sealed partial class FormGuide : Form, FormManager.IAppDialog { private const string GuideUrl = "td://guide/index.html"; - public static void Show(string hash = null) { + public static void Show(string? hash = null) { string url = GuideUrl + (string.IsNullOrEmpty(hash) ? string.Empty : "#" + hash); - FormGuide guide = FormManager.TryFind<FormGuide>(); + FormGuide? guide = FormManager.TryFind<FormGuide>(); if (guide == null) { - FormBrowser owner = FormManager.TryFind<FormBrowser>(); + FormBrowser? owner = FormManager.TryFind<FormBrowser>(); if (owner != null) { new FormGuide(url, owner).Show(owner); diff --git a/windows/TweetDuck/Dialogs/FormMessage.cs b/windows/TweetDuck/Dialogs/FormMessage.cs index 3b2bf2c7..ad9c6e96 100644 --- a/windows/TweetDuck/Dialogs/FormMessage.cs +++ b/windows/TweetDuck/Dialogs/FormMessage.cs @@ -22,23 +22,23 @@ sealed partial class FormMessage : Form { public const string Ignore = "Ignore"; public const string Exit = "Exit"; - public static bool Information(string caption, string text, string buttonAccept, string buttonCancel = null) { + public static bool Information(string caption, string text, string buttonAccept, string? buttonCancel = null) { return Show(caption, text, MessageBoxIcon.Information, buttonAccept, buttonCancel); } - public static bool Warning(string caption, string text, string buttonAccept, string buttonCancel = null) { + public static bool Warning(string caption, string text, string buttonAccept, string? buttonCancel = null) { return Show(caption, text, MessageBoxIcon.Warning, buttonAccept, buttonCancel); } - public static bool Error(string caption, string text, string buttonAccept, string buttonCancel = null) { + public static bool Error(string caption, string text, string buttonAccept, string? buttonCancel = null) { return Show(caption, text, MessageBoxIcon.Error, buttonAccept, buttonCancel); } - public static bool Question(string caption, string text, string buttonAccept, string buttonCancel = null) { + public static bool Question(string caption, string text, string buttonAccept, string? buttonCancel = null) { return Show(caption, text, MessageBoxIcon.Question, buttonAccept, buttonCancel); } - public static bool Show(string caption, string text, MessageBoxIcon icon, string buttonAccept, string buttonCancel = null) { + public static bool Show(string caption, string text, MessageBoxIcon icon, string buttonAccept, string? buttonCancel = null) { using FormMessage message = new FormMessage(caption, text, icon); if (buttonCancel == null) { @@ -54,7 +54,7 @@ public static bool Show(string caption, string text, MessageBoxIcon icon, string // Instance - public Button ClickedButton { get; private set; } + public Button? ClickedButton { get; private set; } public bool HasIcon => icon != null; public int ActionPanelY => panelActions.Location.Y; @@ -68,7 +68,7 @@ private int ButtonDistance { get => BrowserUtils.Scale(96, dpiScale); } - private readonly Icon icon; + private readonly Icon? icon; private readonly bool isReady; private readonly float dpiScale; @@ -115,7 +115,7 @@ public FormMessage(string caption, string text, MessageBoxIcon messageIcon) { this.labelMessage.Text = text.Replace("\r", "").Replace("\n", Environment.NewLine); } - private void FormMessage_SizeChanged(object sender, EventArgs e) { + private void FormMessage_SizeChanged(object? sender, EventArgs e) { RecalculateButtonLocation(); } @@ -135,7 +135,7 @@ public Button AddButton(string title, DialogResult result = DialogResult.OK, Con }; button.Click += (sender, args) => { - ClickedButton = (Button) sender; + ClickedButton = button; DialogResult = result; Close(); }; @@ -181,7 +181,7 @@ private void RecalculateButtonLocation() { } } - private void labelMessage_SizeChanged(object sender, EventArgs e) { + private void labelMessage_SizeChanged(object? sender, EventArgs e) { if (!isReady) { return; } diff --git a/windows/TweetDuck/Dialogs/FormPlugins.cs b/windows/TweetDuck/Dialogs/FormPlugins.cs index 216be1eb..1ffe9e7a 100644 --- a/windows/TweetDuck/Dialogs/FormPlugins.cs +++ b/windows/TweetDuck/Dialogs/FormPlugins.cs @@ -16,11 +16,12 @@ sealed partial class FormPlugins : Form, FormManager.IAppDialog { private readonly PluginManager pluginManager; + #pragma warning disable CS8618 private FormPlugins() { InitializeComponent(); - Text = Program.BrandName + " Plugins"; } + #pragma warning restore CS8618 public FormPlugins(PluginManager pluginManager) : this() { this.pluginManager = pluginManager; @@ -68,7 +69,7 @@ private void ReloadPluginList() { timerLayout.Start(); } - private void timerLayout_Tick(object sender, EventArgs e) { + private void timerLayout_Tick(object? sender, EventArgs e) { timerLayout.Stop(); // stupid WinForms scrollbars and panels @@ -76,8 +77,8 @@ private void timerLayout_Tick(object sender, EventArgs e) { Padding = new Padding(Padding.Left, Padding.Top, Padding.Right - 1, Padding.Bottom - 1); } - private void flowLayoutPlugins_Resize(object sender, EventArgs e) { - Control lastPlugin = flowLayoutPlugins.Controls.OfType<PluginControl>().LastOrDefault(); + private void flowLayoutPlugins_Resize(object? sender, EventArgs e) { + Control? lastPlugin = flowLayoutPlugins.Controls.OfType<PluginControl>().LastOrDefault(); if (lastPlugin == null) { return; @@ -93,22 +94,22 @@ private void flowLayoutPlugins_Resize(object sender, EventArgs e) { control.Width = flowLayoutPlugins.Width - control.Margin.Horizontal - horizontalOffset; } - flowLayoutPlugins.Controls[flowLayoutPlugins.Controls.Count - 1].Visible = !showScrollBar; + flowLayoutPlugins.Controls[^1].Visible = !showScrollBar; flowLayoutPlugins.Focus(); } - private void btnOpenFolder_Click(object sender, EventArgs e) { + private void btnOpenFolder_Click(object? sender, EventArgs e) { App.SystemHandler.OpenFileExplorer(pluginManager.GetPluginFolder(PluginGroup.Custom)); } - private void btnReload_Click(object sender, EventArgs e) { + private void btnReload_Click(object? sender, EventArgs e) { if (FormMessage.Warning("Reloading Plugins", "This will also reload the browser window. Do you want to proceed?", FormMessage.Yes, FormMessage.No)) { pluginManager.Reload(); ReloadPluginList(); } } - private void btnClose_Click(object sender, EventArgs e) { + private void btnClose_Click(object? sender, EventArgs e) { Close(); } } diff --git a/windows/TweetDuck/Dialogs/FormSettings.cs b/windows/TweetDuck/Dialogs/FormSettings.cs index 463e2fe9..c8e002b0 100644 --- a/windows/TweetDuck/Dialogs/FormSettings.cs +++ b/windows/TweetDuck/Dialogs/FormSettings.cs @@ -25,9 +25,9 @@ sealed partial class FormSettings : Form, FormManager.IAppDialog { private readonly int buttonHeight; private readonly Dictionary<Type, SettingsTab> tabs = new Dictionary<Type, SettingsTab>(8); - private SettingsTab currentTab; + private SettingsTab? currentTab; - public FormSettings(FormBrowser browser, PluginManager plugins, UpdateChecker updates, TweetDeckFunctions tweetDeckFunctions, Type startTab) { + public FormSettings(FormBrowser browser, PluginManager plugins, UpdateChecker updates, TweetDeckFunctions tweetDeckFunctions, Type? startTab) { InitializeComponent(); Text = Program.BrandName + " Options"; @@ -56,19 +56,19 @@ private void PrepareLoad() { } private void PrepareUnload() { // TODO refactor this further later - currentTab.Control.OnClosing(); + currentTab?.Control.OnClosing(); App.ConfigManager.ProgramRestartRequested -= Config_ProgramRestartRequested; App.ConfigManager.SaveAll(); } - private void Config_ProgramRestartRequested(object sender, EventArgs e) { + private void Config_ProgramRestartRequested(object? sender, EventArgs e) { if (FormMessage.Information("TweetDuck Options", "The application must restart for the option to take place. Do you want to restart now?", FormMessage.Yes, FormMessage.No)) { Program.Restart(); } } - private void FormSettings_FormClosing(object sender, FormClosingEventArgs e) { + private void FormSettings_FormClosing(object? sender, FormClosingEventArgs e) { PrepareUnload(); foreach (SettingsTab tab in tabs.Values) { @@ -80,7 +80,7 @@ private void FormSettings_FormClosing(object sender, FormClosingEventArgs e) { browser.ResumeNotification(NotificationPauseReason.SettingsDialogOpen); } - private void btnManageOptions_Click(object sender, EventArgs e) { + private void btnManageOptions_Click(object? sender, EventArgs e) { PrepareUnload(); using DialogSettingsManage dialog = new DialogSettingsManage(plugins); @@ -104,7 +104,7 @@ private void btnManageOptions_Click(object sender, EventArgs e) { } } - private void btnClose_Click(object sender, EventArgs e) { + private void btnClose_Click(object? sender, EventArgs e) { Close(); } @@ -128,7 +128,7 @@ private void AddButton<T>(string title, Func<T> constructor) where T : BaseTab { panelButtons.Controls.Add(new Panel { BackColor = Color.DimGray, - Location = new Point(0, panelButtons.Controls[panelButtons.Controls.Count - 1].Location.Y + buttonHeight), + Location = new Point(0, panelButtons.Controls[^1].Location.Y + buttonHeight), Margin = new Padding(0), Size = new Size(panelButtons.Width, 1) }); @@ -182,7 +182,7 @@ private void SelectTab(SettingsTab tab) { currentTab = tab; } - private void control_MouseLeave(object sender, EventArgs e) { + private void control_MouseLeave(object? sender, EventArgs e) { if (sender is ComboBox { DroppedDown: true } ) { return; // prevents comboboxes from closing when MouseLeave event triggers during opening animation } @@ -190,7 +190,7 @@ private void control_MouseLeave(object sender, EventArgs e) { panelContents.Focus(); } - private void control_MouseWheel(object sender, MouseEventArgs e) { + private void control_MouseWheel(object? sender, MouseEventArgs e) { ((HandledMouseEventArgs) e).Handled = true; panelContents.Focus(); } @@ -202,7 +202,7 @@ private sealed class SettingsTab { public bool IsInitialized => control != null; private readonly Func<BaseTab> constructor; - private BaseTab control; + private BaseTab? control; public SettingsTab(Button button, Func<BaseTab> constructor) { this.Button = button; diff --git a/windows/TweetDuck/Dialogs/Settings/DialogSettingsCSS.cs b/windows/TweetDuck/Dialogs/Settings/DialogSettingsCSS.cs index 2bf50f24..ca2fed52 100644 --- a/windows/TweetDuck/Dialogs/Settings/DialogSettingsCSS.cs +++ b/windows/TweetDuck/Dialogs/Settings/DialogSettingsCSS.cs @@ -12,7 +12,7 @@ sealed partial class DialogSettingsCSS : Form { private readonly Action<string> reinjectBrowserCSS; private readonly Action openDevTools; - public DialogSettingsCSS(string browserCSS, string notificationCSS, Action<string> reinjectBrowserCSS, Action openDevTools) { + public DialogSettingsCSS(string? browserCSS, string? notificationCSS, Action<string> reinjectBrowserCSS, Action openDevTools) { InitializeComponent(); Text = Program.BrandName + " Options - CSS"; @@ -30,8 +30,8 @@ public DialogSettingsCSS(string browserCSS, string notificationCSS, Action<strin textBoxBrowserCSS.Select(textBoxBrowserCSS.TextLength, 0); } - private void tabPanel_SelectedIndexChanged(object sender, EventArgs e) { - TextBox tb = tabPanel.SelectedTab.Controls.OfType<TextBox>().FirstOrDefault(); + private void tabPanel_SelectedIndexChanged(object? sender, EventArgs e) { + TextBox? tb = tabPanel.SelectedTab.Controls.OfType<TextBox>().FirstOrDefault(); if (tb != null) { tb.Focus(); @@ -39,8 +39,8 @@ private void tabPanel_SelectedIndexChanged(object sender, EventArgs e) { } } - private void textBoxCSS_KeyDown(object sender, KeyEventArgs e) { - TextBox tb = (TextBox) sender; + private void textBoxCSS_KeyDown(object? sender, KeyEventArgs e) { + TextBox tb = (TextBox) sender!; string text = tb.Text; if (e.KeyCode == Keys.Back && e.Modifiers == Keys.Control) { @@ -79,7 +79,7 @@ private void textBoxCSS_KeyDown(object sender, KeyEventArgs e) { } else if (e.KeyCode == Keys.Enter && e.Modifiers == Keys.None && tb.SelectionLength == 0) { int insertAt = tb.SelectionStart, cursorOffset = 0; - string insertText; + string? insertText; if (insertAt == 0) { return; @@ -97,8 +97,9 @@ private void textBoxCSS_KeyDown(object sender, KeyEventArgs e) { } else { int lineStart = text.LastIndexOf('\n', tb.SelectionStart - 1); - - Match match = Regex.Match(text.Substring(lineStart == -1 ? 0 : lineStart + 1), "^([ \t]+)"); + var firstIndex = (lineStart == -1 ? 0 : lineStart + 1); + + Match match = Regex.Match(text[firstIndex..], "^([ \t]+)"); insertText = match.Success ? Environment.NewLine + match.Groups[1].Value : null; } @@ -110,26 +111,26 @@ private void textBoxCSS_KeyDown(object sender, KeyEventArgs e) { } } - private void textBoxBrowserCSS_KeyUp(object sender, KeyEventArgs e) { + private void textBoxBrowserCSS_KeyUp(object? sender, KeyEventArgs e) { timerTestBrowser.Stop(); timerTestBrowser.Start(); } - private void timerTestBrowser_Tick(object sender, EventArgs e) { + private void timerTestBrowser_Tick(object? sender, EventArgs e) { reinjectBrowserCSS(textBoxBrowserCSS.Text); timerTestBrowser.Stop(); } - private void btnOpenDevTools_Click(object sender, EventArgs e) { + private void btnOpenDevTools_Click(object? sender, EventArgs e) { openDevTools(); } - private void btnApply_Click(object sender, EventArgs e) { + private void btnApply_Click(object? sender, EventArgs e) { DialogResult = DialogResult.OK; Close(); } - private void btnCancel_Click(object sender, EventArgs e) { + private void btnCancel_Click(object? sender, EventArgs e) { DialogResult = DialogResult.Cancel; Close(); } diff --git a/windows/TweetDuck/Dialogs/Settings/DialogSettingsCefArgs.cs b/windows/TweetDuck/Dialogs/Settings/DialogSettingsCefArgs.cs index 987f6142..c6c1dfd1 100644 --- a/windows/TweetDuck/Dialogs/Settings/DialogSettingsCefArgs.cs +++ b/windows/TweetDuck/Dialogs/Settings/DialogSettingsCefArgs.cs @@ -10,7 +10,7 @@ sealed partial class DialogSettingsCefArgs : Form { private readonly string initialArgs; - public DialogSettingsCefArgs(string args) { + public DialogSettingsCefArgs(string? args) { InitializeComponent(); Text = Program.BrandName + " Options - CEF Arguments"; @@ -20,11 +20,11 @@ public DialogSettingsCefArgs(string args) { textBoxArgs.Select(textBoxArgs.Text.Length, 0); } - private void btnHelp_Click(object sender, EventArgs e) { + private void btnHelp_Click(object? sender, EventArgs e) { App.SystemHandler.OpenBrowser("http://peter.sh/experiments/chromium-command-line-switches/"); } - private void btnApply_Click(object sender, EventArgs e) { + private void btnApply_Click(object? sender, EventArgs e) { if (CefArgs == initialArgs) { DialogResult = DialogResult.Cancel; Close(); @@ -40,7 +40,7 @@ private void btnApply_Click(object sender, EventArgs e) { } } - private void btnCancel_Click(object sender, EventArgs e) { + private void btnCancel_Click(object? sender, EventArgs e) { DialogResult = DialogResult.Cancel; Close(); } diff --git a/windows/TweetDuck/Dialogs/Settings/DialogSettingsExternalProgram.cs b/windows/TweetDuck/Dialogs/Settings/DialogSettingsExternalProgram.cs index 6a3183e8..123d0226 100644 --- a/windows/TweetDuck/Dialogs/Settings/DialogSettingsExternalProgram.cs +++ b/windows/TweetDuck/Dialogs/Settings/DialogSettingsExternalProgram.cs @@ -5,12 +5,12 @@ namespace TweetDuck.Dialogs.Settings { sealed partial class DialogSettingsExternalProgram : Form { - public string Path { + public string? Path { get => StringUtils.NullIfEmpty(textBoxPath.Text); set => textBoxPath.Text = value ?? string.Empty; } - public string Args { + public string? Args { get => StringUtils.NullIfEmpty(textBoxArgs.Text); set => textBoxArgs.Text = value ?? string.Empty; } @@ -27,7 +27,7 @@ public DialogSettingsExternalProgram(string windowTitle, string fileDialogTitle) this.fileDialogTitle = fileDialogTitle; } - private void btnBrowse_Click(object sender, EventArgs e) { + private void btnBrowse_Click(object? sender, EventArgs e) { using OpenFileDialog dialog = new OpenFileDialog { AutoUpgradeEnabled = true, DereferenceLinks = true, @@ -42,12 +42,12 @@ private void btnBrowse_Click(object sender, EventArgs e) { } } - private void btnApply_Click(object sender, EventArgs e) { + private void btnApply_Click(object? sender, EventArgs e) { DialogResult = DialogResult.OK; Close(); } - private void btnCancel_Click(object sender, EventArgs e) { + private void btnCancel_Click(object? sender, EventArgs e) { DialogResult = DialogResult.Cancel; Close(); } diff --git a/windows/TweetDuck/Dialogs/Settings/DialogSettingsManage.cs b/windows/TweetDuck/Dialogs/Settings/DialogSettingsManage.cs index 9053c024..6480db53 100644 --- a/windows/TweetDuck/Dialogs/Settings/DialogSettingsManage.cs +++ b/windows/TweetDuck/Dialogs/Settings/DialogSettingsManage.cs @@ -35,7 +35,7 @@ private ProfileManager.Items SelectedItems { private readonly bool openImportImmediately; private State currentState; - private ProfileManager importManager; + private ProfileManager? importManager; private bool requestedRestartFromConfig; private ProfileManager.Items _selectedItems = ProfileManager.Items.None; @@ -59,16 +59,16 @@ public DialogSettingsManage(PluginManager plugins, bool openImportImmediately = } } - private void radioDecision_CheckedChanged(object sender, EventArgs e) { + private void radioDecision_CheckedChanged(object? sender, EventArgs e) { btnContinue.Enabled = true; } - private void checkBoxSelection_CheckedChanged(object sender, EventArgs e) { - CheckBox cb = (CheckBox) sender; + private void checkBoxSelection_CheckedChanged(object? sender, EventArgs e) { + CheckBox cb = (CheckBox) sender!; SetFlag(checkBoxMap[cb], cb.Checked); } - private void btnContinue_Click(object sender, EventArgs e) { + private void btnContinue_Click(object? sender, EventArgs e) { string file; switch (currentState) { @@ -167,7 +167,7 @@ private void btnContinue_Click(object sender, EventArgs e) { break; case State.Import: - if (importManager.Import(SelectedItems)) { + if (importManager!.Import(SelectedItems)) { App.ConfigManager.ProgramRestartRequested += Config_ProgramRestartRequested; App.ConfigManager.ReloadAll(); App.ConfigManager.SaveAll(); @@ -209,12 +209,12 @@ private void btnContinue_Click(object sender, EventArgs e) { } } - private void btnCancel_Click(object sender, EventArgs e) { + private void btnCancel_Click(object? sender, EventArgs e) { DialogResult = DialogResult.Cancel; Close(); } - private void Config_ProgramRestartRequested(object sender, EventArgs e) { + private void Config_ProgramRestartRequested(object? sender, EventArgs e) { requestedRestartFromConfig = true; } diff --git a/windows/TweetDuck/Dialogs/Settings/DialogSettingsRestart.cs b/windows/TweetDuck/Dialogs/Settings/DialogSettingsRestart.cs index 43955d0f..f7438090 100644 --- a/windows/TweetDuck/Dialogs/Settings/DialogSettingsRestart.cs +++ b/windows/TweetDuck/Dialogs/Settings/DialogSettingsRestart.cs @@ -6,7 +6,7 @@ namespace TweetDuck.Dialogs.Settings { sealed partial class DialogSettingsRestart : Form { - public CommandLineArgs Args { get; private set; } + public CommandLineArgs Args { get; private set; } = null!; public DialogSettingsRestart(CommandLineArgs currentArgs) { InitializeComponent(); @@ -28,7 +28,7 @@ public DialogSettingsRestart(CommandLineArgs currentArgs) { Text = Program.BrandName + " Arguments"; } - private void control_Change(object sender, EventArgs e) { + private void control_Change(object? sender, EventArgs e) { Args = new CommandLineArgs(); if (cbLogging.Checked) { @@ -43,18 +43,18 @@ private void control_Change(object sender, EventArgs e) { tbShortcutTarget.Select(tbShortcutTarget.Text.Length, 0); } - private void tbShortcutTarget_Click(object sender, EventArgs e) { + private void tbShortcutTarget_Click(object? sender, EventArgs e) { if (tbShortcutTarget.SelectionLength == 0) { tbShortcutTarget.SelectAll(); } } - private void btnRestart_Click(object sender, EventArgs e) { + private void btnRestart_Click(object? sender, EventArgs e) { DialogResult = DialogResult.OK; Close(); } - private void btnCancel_Click(object sender, EventArgs e) { + private void btnCancel_Click(object? sender, EventArgs e) { DialogResult = DialogResult.Cancel; Close(); } diff --git a/windows/TweetDuck/Dialogs/Settings/DialogSettingsSearchEngine.cs b/windows/TweetDuck/Dialogs/Settings/DialogSettingsSearchEngine.cs index 072a5d85..5af07172 100644 --- a/windows/TweetDuck/Dialogs/Settings/DialogSettingsSearchEngine.cs +++ b/windows/TweetDuck/Dialogs/Settings/DialogSettingsSearchEngine.cs @@ -14,12 +14,12 @@ public DialogSettingsSearchEngine() { textBoxUrl.Select(textBoxUrl.Text.Length, 0); } - private void btnApply_Click(object sender, EventArgs e) { + private void btnApply_Click(object? sender, EventArgs e) { DialogResult = DialogResult.OK; Close(); } - private void btnCancel_Click(object sender, EventArgs e) { + private void btnCancel_Click(object? sender, EventArgs e) { DialogResult = DialogResult.Cancel; Close(); } diff --git a/windows/TweetDuck/Dialogs/Settings/TabSettingsAdvanced.cs b/windows/TweetDuck/Dialogs/Settings/TabSettingsAdvanced.cs index 1e43fa2c..3a8d34cb 100644 --- a/windows/TweetDuck/Dialogs/Settings/TabSettingsAdvanced.cs +++ b/windows/TweetDuck/Dialogs/Settings/TabSettingsAdvanced.cs @@ -9,10 +9,10 @@ namespace TweetDuck.Dialogs.Settings { sealed partial class TabSettingsAdvanced : FormSettings.BaseTab { - private readonly Action<string> reinjectBrowserCSS; + private readonly Action<string?> reinjectBrowserCSS; private readonly Action openDevTools; - public TabSettingsAdvanced(Action<string> reinjectBrowserCSS, Action openDevTools) { + public TabSettingsAdvanced(Action<string?> reinjectBrowserCSS, Action openDevTools) { InitializeComponent(); this.reinjectBrowserCSS = reinjectBrowserCSS; @@ -98,19 +98,19 @@ public override void OnClosing() { #region Application - private void btnOpenAppFolder_Click(object sender, EventArgs e) { + private void btnOpenAppFolder_Click(object? sender, EventArgs e) { App.SystemHandler.OpenFileExplorer(App.ProgramPath); } - private void btnOpenDataFolder_Click(object sender, EventArgs e) { + private void btnOpenDataFolder_Click(object? sender, EventArgs e) { App.SystemHandler.OpenFileExplorer(App.StoragePath); } - private void btnRestart_Click(object sender, EventArgs e) { + private void btnRestart_Click(object? sender, EventArgs e) { Program.Restart(); } - private void btnRestartArgs_Click(object sender, EventArgs e) { + private void btnRestartArgs_Click(object? sender, EventArgs e) { using DialogSettingsRestart dialog = new DialogSettingsRestart(Arguments.GetCurrentClean()); if (dialog.ShowDialog() == DialogResult.OK) { @@ -122,15 +122,15 @@ private void btnRestartArgs_Click(object sender, EventArgs e) { #region Browser Settings - private void checkTouchAdjustment_CheckedChanged(object sender, EventArgs e) { + private void checkTouchAdjustment_CheckedChanged(object? sender, EventArgs e) { SysConfig.EnableTouchAdjustment = checkTouchAdjustment.Checked; } - private void checkAutomaticallyDetectColorProfile_CheckedChanged(object sender, EventArgs e) { + private void checkAutomaticallyDetectColorProfile_CheckedChanged(object? sender, EventArgs e) { SysConfig.EnableColorProfileDetection = checkAutomaticallyDetectColorProfile.Checked; } - private void checkHardwareAcceleration_CheckedChanged(object sender, EventArgs e) { + private void checkHardwareAcceleration_CheckedChanged(object? sender, EventArgs e) { SysConfig.HardwareAcceleration = checkHardwareAcceleration.Checked; } @@ -138,13 +138,13 @@ private void checkHardwareAcceleration_CheckedChanged(object sender, EventArgs e #region Browser Cache - private void btnClearCache_Click(object sender, EventArgs e) { + private void btnClearCache_Click(object? sender, EventArgs e) { btnClearCache.Enabled = false; BrowserCache.SetClearOnExit(); FormMessage.Information("Clear Cache", "Cache will be automatically cleared when TweetDuck exits.", FormMessage.OK); } - private void checkClearCacheAuto_CheckedChanged(object sender, EventArgs e) { + private void checkClearCacheAuto_CheckedChanged(object? sender, EventArgs e) { numClearCacheThreshold.Enabled = checkClearCacheAuto.Checked; } @@ -152,11 +152,12 @@ private void checkClearCacheAuto_CheckedChanged(object sender, EventArgs e) { #region Configuration - private void btnEditCefArgs_Click(object sender, EventArgs e) { - DialogSettingsCefArgs form = new DialogSettingsCefArgs(Config.CustomCefArgs); + private void btnEditCefArgs_Click(object? sender, EventArgs e) { + var parentForm = ParentForm ?? throw new InvalidOperationException("Dialog does not have a parent form!"); + var form = new DialogSettingsCefArgs(Config.CustomCefArgs); form.VisibleChanged += (sender2, args2) => { - form.MoveToCenter(ParentForm); + form.MoveToCenter(parentForm); }; form.FormClosed += (sender2, args2) => { @@ -169,15 +170,16 @@ private void btnEditCefArgs_Click(object sender, EventArgs e) { form.Dispose(); }; - form.Show(ParentForm); - NativeMethods.SetFormDisabled(ParentForm, true); + form.Show(parentForm); + NativeMethods.SetFormDisabled(parentForm, true); } - private void btnEditCSS_Click(object sender, EventArgs e) { - DialogSettingsCSS form = new DialogSettingsCSS(Config.CustomBrowserCSS, Config.CustomNotificationCSS, reinjectBrowserCSS, openDevTools); + private void btnEditCSS_Click(object? sender, EventArgs e) { + var parentForm = ParentForm ?? throw new InvalidOperationException("Dialog does not have a parent form!"); + var form = new DialogSettingsCSS(Config.CustomBrowserCSS, Config.CustomNotificationCSS, reinjectBrowserCSS, openDevTools); form.VisibleChanged += (sender2, args2) => { - form.MoveToCenter(ParentForm); + form.MoveToCenter(parentForm); }; form.FormClosed += (sender2, args2) => { @@ -192,8 +194,8 @@ private void btnEditCSS_Click(object sender, EventArgs e) { form.Dispose(); }; - form.Show(ParentForm); - NativeMethods.SetFormDisabled(ParentForm, true); + form.Show(parentForm); + NativeMethods.SetFormDisabled(parentForm, true); } private void RestoreParentForm() { @@ -206,7 +208,7 @@ private void RestoreParentForm() { #region Proxy - private void checkUseSystemProxyForAllConnections_CheckedChanged(object sender, EventArgs e) { + private void checkUseSystemProxyForAllConnections_CheckedChanged(object? sender, EventArgs e) { SysConfig.UseSystemProxyForAllConnections = checkUseSystemProxyForAllConnections.Checked; } @@ -214,11 +216,11 @@ private void checkUseSystemProxyForAllConnections_CheckedChanged(object sender, #region Development Tools - private void checkDevToolsInContextMenuOnCheckedChanged(object sender, EventArgs e) { + private void checkDevToolsInContextMenuOnCheckedChanged(object? sender, EventArgs e) { Config.DevToolsInContextMenu = checkDevToolsInContextMenu.Checked; } - private void checkDevToolsWindowOnTop_CheckedChanged(object sender, EventArgs e) { + private void checkDevToolsWindowOnTop_CheckedChanged(object? sender, EventArgs e) { Config.DevToolsWindowOnTop = checkDevToolsWindowOnTop.Checked; } diff --git a/windows/TweetDuck/Dialogs/Settings/TabSettingsFeedback.cs b/windows/TweetDuck/Dialogs/Settings/TabSettingsFeedback.cs index 8b333bea..f472cfc5 100644 --- a/windows/TweetDuck/Dialogs/Settings/TabSettingsFeedback.cs +++ b/windows/TweetDuck/Dialogs/Settings/TabSettingsFeedback.cs @@ -13,7 +13,7 @@ public override void OnReady() { #region Feedback - private void btnSendFeedback_Click(object sender, EventArgs e) { + private void btnSendFeedback_Click(object? sender, EventArgs e) { App.SystemHandler.OpenBrowser(Lib.IssueTrackerUrl + "/new"); } diff --git a/windows/TweetDuck/Dialogs/Settings/TabSettingsGeneral.cs b/windows/TweetDuck/Dialogs/Settings/TabSettingsGeneral.cs index a747faae..89356100 100644 --- a/windows/TweetDuck/Dialogs/Settings/TabSettingsGeneral.cs +++ b/windows/TweetDuck/Dialogs/Settings/TabSettingsGeneral.cs @@ -171,27 +171,27 @@ public override void OnClosing() { #region User Interface - private void checkExpandLinks_CheckedChanged(object sender, EventArgs e) { + private void checkExpandLinks_CheckedChanged(object? sender, EventArgs e) { Config.ExpandLinksOnHover = checkExpandLinks.Checked; } - private void checkFocusDmInput_CheckedChanged(object sender, EventArgs e) { + private void checkFocusDmInput_CheckedChanged(object? sender, EventArgs e) { Config.FocusDmInput = checkFocusDmInput.Checked; } - private void checkOpenSearchInFirstColumn_CheckedChanged(object sender, EventArgs e) { + private void checkOpenSearchInFirstColumn_CheckedChanged(object? sender, EventArgs e) { Config.OpenSearchInFirstColumn = checkOpenSearchInFirstColumn.Checked; } - private void checkKeepLikeFollowDialogsOpen_CheckedChanged(object sender, EventArgs e) { + private void checkKeepLikeFollowDialogsOpen_CheckedChanged(object? sender, EventArgs e) { Config.KeepLikeFollowDialogsOpen = checkKeepLikeFollowDialogsOpen.Checked; } - private void checkSmoothScrolling_CheckedChanged(object sender, EventArgs e) { + private void checkSmoothScrolling_CheckedChanged(object? sender, EventArgs e) { Config.EnableSmoothScrolling = checkSmoothScrolling.Checked; } - private void trackBarZoom_ValueChanged(object sender, EventArgs e) { + private void trackBarZoom_ValueChanged(object? sender, EventArgs e) { if (trackBarZoom.AlignValueToTick()) { zoomUpdateTimer.Stop(); zoomUpdateTimer.Start(); @@ -199,7 +199,7 @@ private void trackBarZoom_ValueChanged(object sender, EventArgs e) { } } - private void zoomUpdateTimer_Tick(object sender, EventArgs e) { + private void zoomUpdateTimer_Tick(object? sender, EventArgs e) { Config.ZoomLevel = trackBarZoom.Value; zoomUpdateTimer.Stop(); } @@ -208,16 +208,16 @@ private void zoomUpdateTimer_Tick(object sender, EventArgs e) { #region Twitter - private void checkBestImageQuality_CheckedChanged(object sender, EventArgs e) { + private void checkBestImageQuality_CheckedChanged(object? sender, EventArgs e) { Config.BestImageQuality = checkBestImageQuality.Checked; } - private void checkHideTweetsByNftUsers_CheckedChanged(object sender, EventArgs e) { + private void checkHideTweetsByNftUsers_CheckedChanged(object? sender, EventArgs e) { Config.HideTweetsByNftUsers = checkHideTweetsByNftUsers.Checked; BeginInvoke(reloadTweetDeck); } - private void checkAnimatedAvatars_CheckedChanged(object sender, EventArgs e) { + private void checkAnimatedAvatars_CheckedChanged(object? sender, EventArgs e) { Config.EnableAnimatedImages = checkAnimatedAvatars.Checked; BrowserProcessHandler.UpdatePrefs().ContinueWith(task => reloadColumns()); } @@ -226,18 +226,18 @@ private void checkAnimatedAvatars_CheckedChanged(object sender, EventArgs e) { #region Updates - private void checkUpdateNotifications_CheckedChanged(object sender, EventArgs e) { + private void checkUpdateNotifications_CheckedChanged(object? sender, EventArgs e) { Config.EnableUpdateCheck = checkUpdateNotifications.Checked; } - private void btnCheckUpdates_Click(object sender, EventArgs e) { + private void btnCheckUpdates_Click(object? sender, EventArgs e) { Config.DismissedUpdate = null; btnCheckUpdates.Enabled = false; updateCheckEventId = updates.Check(true); } - private void updates_CheckFinished(object sender, UpdateCheckEventArgs e) { + private void updates_CheckFinished(object? sender, UpdateCheckEventArgs e) { if (e.EventId == updateCheckEventId) { btnCheckUpdates.Enabled = true; @@ -264,7 +264,7 @@ private void UpdateBrowserPathSelection() { comboBoxCustomBrowser.SelectedIndex = browserListIndexDefault; } else { - WindowsUtils.Browser browserInfo = comboBoxCustomBrowser.Items.OfType<WindowsUtils.Browser>().FirstOrDefault(browser => browser.Path == Config.BrowserPath); + WindowsUtils.Browser? browserInfo = comboBoxCustomBrowser.Items.OfType<WindowsUtils.Browser>().FirstOrDefault(browser => browser.Path == Config.BrowserPath); if (browserInfo == null || Config.BrowserPathArgs != null) { comboBoxCustomBrowser.SelectedIndex = browserListIndexCustom; @@ -277,7 +277,7 @@ private void UpdateBrowserPathSelection() { UpdateBrowserChangeButton(); } - private void comboBoxCustomBrowser_SelectedIndexChanged(object sender, EventArgs e) { + private void comboBoxCustomBrowser_SelectedIndexChanged(object? sender, EventArgs e) { if (comboBoxCustomBrowser.SelectedIndex == browserListIndexCustom) { btnCustomBrowserChange_Click(sender, e); } @@ -288,7 +288,7 @@ private void comboBoxCustomBrowser_SelectedIndexChanged(object sender, EventArgs } } - private void btnCustomBrowserChange_Click(object sender, EventArgs e) { + private void btnCustomBrowserChange_Click(object? sender, EventArgs e) { using (DialogSettingsExternalProgram dialog = new DialogSettingsExternalProgram("External Browser", "Open Links With...") { Path = Config.BrowserPath, Args = Config.BrowserPathArgs @@ -319,7 +319,7 @@ private void UpdateVideoPlayerPathSelection() { UpdateVideoPlayerChangeButton(); } - private void comboBoxCustomVideoPlayer_SelectedIndexChanged(object sender, EventArgs e) { + private void comboBoxCustomVideoPlayer_SelectedIndexChanged(object? sender, EventArgs e) { if (comboBoxCustomVideoPlayer.SelectedIndex == videoPlayerListIndexCustom) { btnCustomVideoPlayerChange_Click(sender, e); } @@ -330,7 +330,7 @@ private void comboBoxCustomVideoPlayer_SelectedIndexChanged(object sender, Event } } - private void btnCustomVideoPlayerChange_Click(object sender, EventArgs e) { + private void btnCustomVideoPlayerChange_Click(object? sender, EventArgs e) { using (DialogSettingsExternalProgram dialog = new DialogSettingsExternalProgram("External Video Player", "Play Videos With...") { Path = Config.VideoPlayerPath, Args = Config.VideoPlayerPathArgs @@ -346,7 +346,7 @@ private void btnCustomVideoPlayerChange_Click(object sender, EventArgs e) { comboBoxCustomVideoPlayer.SelectedIndexChanged += comboBoxCustomVideoPlayer_SelectedIndexChanged; } - private void comboBoxSearchEngine_SelectedIndexChanged(object sender, EventArgs e) { + private void comboBoxSearchEngine_SelectedIndexChanged(object? sender, EventArgs e) { if (comboBoxSearchEngine.SelectedIndex == searchEngineIndexCustom) { using (DialogSettingsSearchEngine dialog = new DialogSettingsSearchEngine()) { if (dialog.ShowDialog() == DialogResult.OK) { @@ -368,7 +368,7 @@ private void UpdateSearchEngineSelection() { comboBoxSearchEngine.SelectedIndex = searchEngineIndexDefault; } else { - SearchEngine engineInfo = comboBoxSearchEngine.Items.OfType<SearchEngine>().FirstOrDefault(engine => engine.Url == Config.SearchEngineUrl); + SearchEngine? engineInfo = comboBoxSearchEngine.Items.OfType<SearchEngine>().FirstOrDefault(engine => engine.Url == Config.SearchEngineUrl); if (engineInfo == null) { comboBoxSearchEngine.SelectedIndex = searchEngineIndexCustom; @@ -389,7 +389,7 @@ public SearchEngine(string name, string url) { } public override int GetHashCode() => Name.GetHashCode(); - public override bool Equals(object obj) => obj is SearchEngine other && Name == other.Name; + public override bool Equals(object? obj) => obj is SearchEngine other && Name == other.Name; public override string ToString() => Name; } @@ -397,20 +397,20 @@ public SearchEngine(string name, string url) { #region Locales - private void checkSpellCheck_CheckedChanged(object sender, EventArgs e) { + private void checkSpellCheck_CheckedChanged(object? sender, EventArgs e) { Config.EnableSpellCheck = checkSpellCheck.Checked; BrowserProcessHandler.UpdatePrefs(); } - private void comboBoxSpellCheckLanguage_SelectedValueChanged(object sender, EventArgs e) { + private void comboBoxSpellCheckLanguage_SelectedValueChanged(object? sender, EventArgs e) { Config.SpellCheckLanguage = (comboBoxSpellCheckLanguage.SelectedItem as Language)?.Code ?? "en-US"; } - private void comboBoxTranslationTarget_SelectedValueChanged(object sender, EventArgs e) { + private void comboBoxTranslationTarget_SelectedValueChanged(object? sender, EventArgs e) { Config.TranslationTarget = (comboBoxTranslationTarget.SelectedItem as Language)?.Code ?? "en"; } - private void comboBoxFirstDayOfWeek_SelectedValueChanged(object sender, EventArgs e) { + private void comboBoxFirstDayOfWeek_SelectedValueChanged(object? sender, EventArgs e) { Config.CalendarFirstDay = (comboBoxFirstDayOfWeek.SelectedItem as DayOfWeekItem)?.Id ?? -1; } @@ -424,7 +424,7 @@ public DayOfWeekItem(string name, DayOfWeek dow) { } public override int GetHashCode() => Name.GetHashCode(); - public override bool Equals(object obj) => obj is DayOfWeekItem other && Name == other.Name; + public override bool Equals(object? obj) => obj is DayOfWeekItem other && Name == other.Name; public override string ToString() => Name; } diff --git a/windows/TweetDuck/Dialogs/Settings/TabSettingsNotifications.cs b/windows/TweetDuck/Dialogs/Settings/TabSettingsNotifications.cs index cd472f18..94e95d13 100644 --- a/windows/TweetDuck/Dialogs/Settings/TabSettingsNotifications.cs +++ b/windows/TweetDuck/Dialogs/Settings/TabSettingsNotifications.cs @@ -143,7 +143,7 @@ public override void OnReady() { trackBarScrollSpeed.ValueChanged += trackBarScrollSpeed_ValueChanged; } - private void TabSettingsNotifications_ParentChanged(object sender, EventArgs e) { + private void TabSettingsNotifications_ParentChanged(object? sender, EventArgs e) { if (Parent == null) { notification.HideNotification(); } @@ -152,13 +152,13 @@ private void TabSettingsNotifications_ParentChanged(object sender, EventArgs e) } } - private void notification_Move(object sender, EventArgs e) { + private void notification_Move(object? sender, EventArgs e) { if (radioLocCustom.Checked && notification.Location != ControlExtensions.InvisibleLocation) { Config.CustomNotificationPosition = notification.Location; } } - private void notification_ResizeEnd(object sender, EventArgs e) { + private void notification_ResizeEnd(object? sender, EventArgs e) { if (radioSizeCustom.Checked) { Config.CustomNotificationSize = notification.BrowserSize; notification.ShowExampleNotification(false); @@ -167,28 +167,28 @@ private void notification_ResizeEnd(object sender, EventArgs e) { #region General - private void checkColumnName_CheckedChanged(object sender, EventArgs e) { + private void checkColumnName_CheckedChanged(object? sender, EventArgs e) { Config.DisplayNotificationColumn = checkColumnName.Checked; notification.ShowExampleNotification(false); } - private void checkMediaPreviews_CheckedChanged(object sender, EventArgs e) { + private void checkMediaPreviews_CheckedChanged(object? sender, EventArgs e) { Config.NotificationMediaPreviews = checkMediaPreviews.Checked; } - private void checkSkipOnLinkClick_CheckedChanged(object sender, EventArgs e) { + private void checkSkipOnLinkClick_CheckedChanged(object? sender, EventArgs e) { Config.NotificationSkipOnLinkClick = checkSkipOnLinkClick.Checked; } - private void checkNonIntrusive_CheckedChanged(object sender, EventArgs e) { + private void checkNonIntrusive_CheckedChanged(object? sender, EventArgs e) { Config.NotificationNonIntrusiveMode = checkNonIntrusive.Checked; } - private void comboBoxIdlePause_SelectedValueChanged(object sender, EventArgs e) { + private void comboBoxIdlePause_SelectedValueChanged(object? sender, EventArgs e) { Config.NotificationIdlePauseSeconds = IdlePauseSeconds[comboBoxIdlePause.SelectedIndex]; } - private void trackBarOpacity_ValueChanged(object sender, EventArgs e) { + private void trackBarOpacity_ValueChanged(object? sender, EventArgs e) { if (trackBarOpacity.AlignValueToTick()) { Config.NotificationWindowOpacity = trackBarOpacity.Value; labelOpacityValue.Text = Config.NotificationWindowOpacity + "%"; @@ -199,18 +199,18 @@ private void trackBarOpacity_ValueChanged(object sender, EventArgs e) { #region Timer - private void checkNotificationTimer_CheckedChanged(object sender, EventArgs e) { + private void checkNotificationTimer_CheckedChanged(object? sender, EventArgs e) { Config.DisplayNotificationTimer = checkNotificationTimer.Checked; checkTimerCountDown.Enabled = checkNotificationTimer.Checked; notification.ShowExampleNotification(true); } - private void checkTimerCountDown_CheckedChanged(object sender, EventArgs e) { + private void checkTimerCountDown_CheckedChanged(object? sender, EventArgs e) { Config.NotificationTimerCountDown = checkTimerCountDown.Checked; notification.ShowExampleNotification(true); } - private void trackBarDuration_ValueChanged(object sender, EventArgs e) { + private void trackBarDuration_ValueChanged(object? sender, EventArgs e) { durationUpdateTimer.Stop(); durationUpdateTimer.Start(); @@ -218,19 +218,19 @@ private void trackBarDuration_ValueChanged(object sender, EventArgs e) { labelDurationValue.Text = Config.NotificationDurationValue + " ms/c"; } - private void btnDurationShort_Click(object sender, EventArgs e) { + private void btnDurationShort_Click(object? sender, EventArgs e) { trackBarDuration.Value = 15; } - private void btnDurationMedium_Click(object sender, EventArgs e) { + private void btnDurationMedium_Click(object? sender, EventArgs e) { trackBarDuration.Value = 25; } - private void btnDurationLong_Click(object sender, EventArgs e) { + private void btnDurationLong_Click(object? sender, EventArgs e) { trackBarDuration.Value = 35; } - private void durationUpdateTimer_Tick(object sender, EventArgs e) { + private void durationUpdateTimer_Tick(object? sender, EventArgs e) { notification.ShowExampleNotification(true); durationUpdateTimer.Stop(); } @@ -239,7 +239,7 @@ private void durationUpdateTimer_Tick(object sender, EventArgs e) { #region Location - private void radioLoc_CheckedChanged(object sender, EventArgs e) { + private void radioLoc_CheckedChanged(object? sender, EventArgs e) { if (radioLocTL.Checked) { Config.NotificationPosition = DesktopNotification.Position.TopLeft; } @@ -257,7 +257,7 @@ private void radioLoc_CheckedChanged(object sender, EventArgs e) { notification.ShowExampleNotification(false); } - private void radioLocCustom_Click(object sender, EventArgs e) { + private void radioLocCustom_Click(object? sender, EventArgs e) { if (!Config.IsCustomNotificationPositionSet) { Config.CustomNotificationPosition = notification.Location; } @@ -278,12 +278,12 @@ private void radioLocCustom_Click(object sender, EventArgs e) { } } - private void comboBoxDisplay_SelectedValueChanged(object sender, EventArgs e) { + private void comboBoxDisplay_SelectedValueChanged(object? sender, EventArgs e) { Config.NotificationDisplay = comboBoxDisplay.SelectedIndex; notification.ShowExampleNotification(false); } - private void trackBarEdgeDistance_ValueChanged(object sender, EventArgs e) { + private void trackBarEdgeDistance_ValueChanged(object? sender, EventArgs e) { labelEdgeDistanceValue.Text = trackBarEdgeDistance.Value + " px"; Config.NotificationEdgeDistance = trackBarEdgeDistance.Value; notification.ShowExampleNotification(false); @@ -293,7 +293,7 @@ private void trackBarEdgeDistance_ValueChanged(object sender, EventArgs e) { #region Size - private void radioSize_CheckedChanged(object sender, EventArgs e) { + private void radioSize_CheckedChanged(object? sender, EventArgs e) { if (radioSizeAuto.Checked) { Config.NotificationSize = DesktopNotification.Size.Auto; } @@ -301,7 +301,7 @@ private void radioSize_CheckedChanged(object sender, EventArgs e) { notification.ShowExampleNotification(false); } - private void radioSizeCustom_Click(object sender, EventArgs e) { + private void radioSizeCustom_Click(object? sender, EventArgs e) { if (!Config.IsCustomNotificationSizeSet) { Config.CustomNotificationSize = notification.BrowserSize; } @@ -310,7 +310,7 @@ private void radioSizeCustom_Click(object sender, EventArgs e) { notification.ShowExampleNotification(false); } - private void trackBarScrollSpeed_ValueChanged(object sender, EventArgs e) { + private void trackBarScrollSpeed_ValueChanged(object? sender, EventArgs e) { if (trackBarScrollSpeed.AlignValueToTick()) { labelScrollSpeedValue.Text = trackBarScrollSpeed.Value + "%"; Config.NotificationScrollSpeed = trackBarScrollSpeed.Value; diff --git a/windows/TweetDuck/Dialogs/Settings/TabSettingsSounds.cs b/windows/TweetDuck/Dialogs/Settings/TabSettingsSounds.cs index 46459845..64d0ed91 100644 --- a/windows/TweetDuck/Dialogs/Settings/TabSettingsSounds.cs +++ b/windows/TweetDuck/Dialogs/Settings/TabSettingsSounds.cs @@ -51,11 +51,11 @@ private bool RefreshCanPlay() { return canPlay; } - private void tbCustomSound_TextChanged(object sender, EventArgs e) { + private void tbCustomSound_TextChanged(object? sender, EventArgs e) { RefreshCanPlay(); } - private void btnPlaySound_Click(object sender, EventArgs e) { + private void btnPlaySound_Click(object? sender, EventArgs e) { if (RefreshCanPlay()) { Config.NotificationSoundPath = tbCustomSound.Text; Config.NotificationSoundVolume = trackBarVolume.Value; @@ -63,7 +63,7 @@ private void btnPlaySound_Click(object sender, EventArgs e) { } } - private void btnBrowseSound_Click(object sender, EventArgs e) { + private void btnBrowseSound_Click(object? sender, EventArgs e) { using OpenFileDialog dialog = new OpenFileDialog { AutoUpgradeEnabled = true, DereferenceLinks = true, @@ -84,17 +84,17 @@ private void btnBrowseSound_Click(object sender, EventArgs e) { } } - private void btnResetSound_Click(object sender, EventArgs e) { + private void btnResetSound_Click(object? sender, EventArgs e) { tbCustomSound.Text = string.Empty; } - private void trackBarVolume_ValueChanged(object sender, EventArgs e) { + private void trackBarVolume_ValueChanged(object? sender, EventArgs e) { volumeUpdateTimer.Stop(); volumeUpdateTimer.Start(); labelVolumeValue.Text = trackBarVolume.Value + "%"; } - private void volumeUpdateTimer_Tick(object sender, EventArgs e) { + private void volumeUpdateTimer_Tick(object? sender, EventArgs e) { Config.NotificationSoundVolume = trackBarVolume.Value; volumeUpdateTimer.Stop(); } diff --git a/windows/TweetDuck/Dialogs/Settings/TabSettingsTray.cs b/windows/TweetDuck/Dialogs/Settings/TabSettingsTray.cs index 9d4e92bd..1f173419 100644 --- a/windows/TweetDuck/Dialogs/Settings/TabSettingsTray.cs +++ b/windows/TweetDuck/Dialogs/Settings/TabSettingsTray.cs @@ -29,12 +29,12 @@ public override void OnReady() { #region System Tray - private void comboBoxTrayType_SelectedIndexChanged(object sender, EventArgs e) { + private void comboBoxTrayType_SelectedIndexChanged(object? sender, EventArgs e) { Config.TrayBehavior = (TrayIcon.Behavior) comboBoxTrayType.SelectedIndex; checkTrayHighlight.Enabled = Config.TrayBehavior.ShouldDisplayIcon(); } - private void checkTrayHighlight_CheckedChanged(object sender, EventArgs e) { + private void checkTrayHighlight_CheckedChanged(object? sender, EventArgs e) { Config.EnableTrayHighlight = checkTrayHighlight.Checked; } diff --git a/windows/TweetDuck/Management/BrowserCache.cs b/windows/TweetDuck/Management/BrowserCache.cs index da082fc3..26597084 100644 --- a/windows/TweetDuck/Management/BrowserCache.cs +++ b/windows/TweetDuck/Management/BrowserCache.cs @@ -11,7 +11,7 @@ static class BrowserCache { private static string CacheFolder => CefUtils.GetCacheFolder(App.StoragePath); private static bool clearOnExit; - private static Timer autoClearTimer; + private static Timer? autoClearTimer; private static long CalculateCacheSize() { return new DirectoryInfo(CacheFolder).EnumerateFiles().Select(file => { diff --git a/windows/TweetDuck/Management/FormManager.cs b/windows/TweetDuck/Management/FormManager.cs index 3e927548..0ed89c0c 100644 --- a/windows/TweetDuck/Management/FormManager.cs +++ b/windows/TweetDuck/Management/FormManager.cs @@ -28,12 +28,12 @@ public static void RunOnUIThreadAsync(Action action) { } } - public static T TryFind<T>() where T : Form { + public static T? TryFind<T>() where T : Form { return OpenForms.OfType<T>().FirstOrDefault(); } public static bool TryBringToFront<T>() where T : Form { - T form = TryFind<T>(); + T? form = TryFind<T>(); if (form != null) { form.BringToFront(); diff --git a/windows/TweetDuck/Management/ProfileManager.cs b/windows/TweetDuck/Management/ProfileManager.cs index 7fe49ab0..7713fbe6 100644 --- a/windows/TweetDuck/Management/ProfileManager.cs +++ b/windows/TweetDuck/Management/ProfileManager.cs @@ -61,7 +61,7 @@ public bool Export(Items items) { } if (items.HasFlag(Items.Session)) { - string authToken = ReadAuthCookie(); + string? authToken = ReadAuthCookie(); if (authToken != null) { stream.WriteString("cookie.auth", authToken); @@ -84,9 +84,8 @@ public Items FindImportItems() { try { using CombinedFileStream stream = new CombinedFileStream(new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.None)); - string key; - while ((key = stream.SkipFile()) != null) { + while (stream.SkipFile() is {} key) { switch (key) { case "config": items |= Items.UserConfig; @@ -121,9 +120,7 @@ public bool Import(Items items) { bool oldCookies = false; using (CombinedFileStream stream = new CombinedFileStream(new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.None))) { - CombinedFileStream.Entry entry; - - while ((entry = stream.ReadFile()) != null) { + while (stream.ReadFile() is {} entry) { switch (entry.KeyName) { case "config": if (items.HasFlag(Items.UserConfig)) { @@ -223,11 +220,11 @@ private sealed class PathInfo { public PathInfo(string fullPath, int rootLength) { this.Full = fullPath; - this.Relative = fullPath.Substring(rootLength).TrimStart(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); // strip leading separator character + this.Relative = fullPath[rootLength..].TrimStart(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); // strip leading separator character } } - private static string ReadAuthCookie() { + private static string? ReadAuthCookie() { using var cookieManager = Cef.GetGlobalCookieManager(); foreach (var cookie in cookieManager.VisitUrlCookiesAsync(AuthCookieUrl, true).Result) { diff --git a/windows/TweetDuck/Management/VideoPlayer.cs b/windows/TweetDuck/Management/VideoPlayer.cs index f4a2bfa0..609bf81e 100644 --- a/windows/TweetDuck/Management/VideoPlayer.cs +++ b/windows/TweetDuck/Management/VideoPlayer.cs @@ -16,11 +16,11 @@ sealed class VideoPlayer : IDisposable { public bool Running => currentInstance is { Running: true }; - public event EventHandler ProcessExited; + public event EventHandler? ProcessExited; private readonly FormBrowser owner; - private Instance currentInstance; + private Instance? currentInstance; private bool isClosing; public VideoPlayer(FormBrowser owner) { @@ -44,7 +44,7 @@ public void Launch(string videoUrl, string tweetUrl, string username) { RedirectStandardOutput = true }; - Process process; + Process? process; if ((process = Process.Start(startInfo)) != null) { currentInstance = new Instance(process, pipe, videoUrl, tweetUrl, username); @@ -69,7 +69,7 @@ public void SendKeyEvent(Keys key) { currentInstance?.Pipe.Write("key", ((int) key).ToString()); } - private void pipe_DataIn(object sender, DuplexPipe.PipeReadEventArgs e) { + private void pipe_DataIn(object? sender, DuplexPipe.PipeReadEventArgs e) { owner.InvokeSafe(() => { switch (e.Key) { case "vol": @@ -128,19 +128,19 @@ private void Destroy() { } } - private void owner_FormClosing(object sender, FormClosingEventArgs e) { + private void owner_FormClosing(object? sender, FormClosingEventArgs e) { if (currentInstance != null) { currentInstance.Process.Exited -= process_Exited; } } - private void process_OutputDataReceived(object sender, DataReceivedEventArgs e) { + private void process_OutputDataReceived(object? sender, DataReceivedEventArgs e) { if (!string.IsNullOrEmpty(e.Data)) { App.Logger.Debug("[VideoPlayer] " + e.Data); } } - private void process_Exited(object sender, EventArgs e) { + private void process_Exited(object? sender, EventArgs e) { if (currentInstance == null) { return; } diff --git a/windows/TweetDuck/Management/WindowsSessionManager.cs b/windows/TweetDuck/Management/WindowsSessionManager.cs index 61336305..2272fb6e 100644 --- a/windows/TweetDuck/Management/WindowsSessionManager.cs +++ b/windows/TweetDuck/Management/WindowsSessionManager.cs @@ -5,18 +5,18 @@ namespace TweetDuck.Management { static class WindowsSessionManager { public static bool IsLocked { get; private set; } = false; - public static event EventHandler LockStateChanged; + public static event EventHandler? LockStateChanged; public static void Register() { Win.Application.ApplicationExit += OnApplicationExit; SystemEvents.SessionSwitch += OnSessionSwitch; } - private static void OnApplicationExit(object sender, EventArgs e) { + private static void OnApplicationExit(object? sender, EventArgs e) { SystemEvents.SessionSwitch -= OnSessionSwitch; } - private static void OnSessionSwitch(object sender, SessionSwitchEventArgs e) { + private static void OnSessionSwitch(object? sender, SessionSwitchEventArgs e) { var reason = e.Reason; if (reason == SessionSwitchReason.SessionLock) { SetLocked(true); diff --git a/windows/TweetDuck/Plugins/PluginControl.cs b/windows/TweetDuck/Plugins/PluginControl.cs index 17071d0f..6d0b8b6a 100644 --- a/windows/TweetDuck/Plugins/PluginControl.cs +++ b/windows/TweetDuck/Plugins/PluginControl.cs @@ -16,9 +16,11 @@ sealed partial class PluginControl : UserControl { private int nextHeight; + #pragma warning disable CS8618 private PluginControl() { InitializeComponent(); } + #pragma warning restore CS8618 public PluginControl(PluginManager pluginManager, Plugin plugin) : this() { this.pluginManager = pluginManager; @@ -49,13 +51,13 @@ public PluginControl(PluginManager pluginManager, Plugin plugin) : this() { panelDescription_Resize(panelDescription, EventArgs.Empty); } - private void timerLayout_Tick(object sender, EventArgs e) { + private void timerLayout_Tick(object? sender, EventArgs e) { timerLayout.Stop(); Height = nextHeight; ResumeLayout(); } - private void panelDescription_Resize(object sender, EventArgs e) { + private void panelDescription_Resize(object? sender, EventArgs e) { SuspendLayout(); int maxWidth = panelDescription.Width - (panelDescription.VerticalScroll.Visible ? SystemInformation.VerticalScrollBarWidth : 0); @@ -80,18 +82,18 @@ private void panelDescription_Resize(object sender, EventArgs e) { } } - private void labelWebsite_Click(object sender, EventArgs e) { + private void labelWebsite_Click(object? sender, EventArgs e) { if (labelWebsite.Text.Length > 0) { App.SystemHandler.OpenBrowser(labelWebsite.Text); } } - private void btnConfigure_Click(object sender, EventArgs e) { + private void btnConfigure_Click(object? sender, EventArgs e) { pluginManager.ConfigurePlugin(plugin); ParentForm?.Close(); } - private void btnToggleState_Click(object sender, EventArgs e) { + private void btnToggleState_Click(object? sender, EventArgs e) { pluginManager.Config.SetEnabled(plugin, !pluginManager.Config.IsEnabled(plugin)); pluginManager.Config.Save(); UpdatePluginState(); diff --git a/windows/TweetDuck/Program.cs b/windows/TweetDuck/Program.cs index c1a3a4a2..867ceb3d 100644 --- a/windows/TweetDuck/Program.cs +++ b/windows/TweetDuck/Program.cs @@ -36,11 +36,11 @@ static class Program { public static string ExecutablePath => Win.Application.ExecutablePath; - private static Reporter errorReporter; - private static LockManager lockManager; + private static Reporter? errorReporter; + private static LockManager lockManager = null!; private static bool hasCleanedUp; - public static ConfigObjects<UserConfig, SystemConfig> Config { get; private set; } + public static ConfigObjects<UserConfig, SystemConfig> Config { get; private set; } = null!; internal static void SetupWinForms() { Win.Application.EnableVisualStyles(); @@ -85,8 +85,8 @@ private static void Main() { private sealed class Setup : IAppSetup { public bool IsPortable => File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "makeportable")); public bool IsDebugLogging => Arguments.HasFlag(Arguments.ArgLogging); - public string CustomDataFolder => Arguments.GetValue(Arguments.ArgDataFolder); - public string ResourceRewriteRules => Arguments.GetValue(Arguments.ArgFreeze); + public string? CustomDataFolder => Arguments.GetValue(Arguments.ArgDataFolder); + public string? ResourceRewriteRules => Arguments.GetValue(Arguments.ArgFreeze); public ConfigManager CreateConfigManager(string storagePath) { return new ConfigManager<UserConfig, SystemConfig>(storagePath, Config); @@ -153,7 +153,7 @@ public void Launch(ResourceCache resourceCache, PluginManager pluginManager) { } } - private static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e) { + private static void OnUnhandledException(object? sender, UnhandledExceptionEventArgs e) { if (e.ExceptionObject is Exception ex) { const string title = "TweetDuck Has Failed :("; string message = "An unhandled exception has occurred: " + ex.Message; @@ -173,7 +173,7 @@ public static void Restart() { } public static void RestartWithArgs(CommandLineArgs args) { - FormBrowser browserForm = FormManager.TryFind<FormBrowser>(); + FormBrowser? browserForm = FormManager.TryFind<FormBrowser>(); if (browserForm != null) { browserForm.ForceClose(); diff --git a/windows/TweetDuck/Reporter.cs b/windows/TweetDuck/Reporter.cs index d30d3364..25bd9f88 100644 --- a/windows/TweetDuck/Reporter.cs +++ b/windows/TweetDuck/Reporter.cs @@ -9,7 +9,7 @@ namespace TweetDuck { sealed class Reporter : IAppErrorHandler { - private static void Exit(string message, Exception ex = null) { + private static void Exit(string message, Exception? ex = null) { try { Process.GetCurrentProcess().Kill(); } catch { diff --git a/windows/TweetDuck/Updates/FormUpdateDownload.cs b/windows/TweetDuck/Updates/FormUpdateDownload.cs index f48f0161..46baee13 100644 --- a/windows/TweetDuck/Updates/FormUpdateDownload.cs +++ b/windows/TweetDuck/Updates/FormUpdateDownload.cs @@ -16,11 +16,11 @@ public FormUpdateDownload(UpdateInfo info) { timerDownloadCheck.Start(); } - private void btnCancel_Click(object sender, EventArgs e) { + private void btnCancel_Click(object? sender, EventArgs e) { Close(); } - private void timerDownloadCheck_Tick(object sender, EventArgs e) { + private void timerDownloadCheck_Tick(object? sender, EventArgs e) { if (updateInfo.DownloadStatus.IsFinished(false)) { timerDownloadCheck.Stop(); DialogResult = DialogResult.OK; diff --git a/windows/TweetDuck/Updates/UpdateCheckClient.cs b/windows/TweetDuck/Updates/UpdateCheckClient.cs index e6903a31..711d1389 100644 --- a/windows/TweetDuck/Updates/UpdateCheckClient.cs +++ b/windows/TweetDuck/Updates/UpdateCheckClient.cs @@ -33,7 +33,7 @@ Task<UpdateInfo> IUpdateCheckClient.Check() { result.SetCanceled(); } else if (task.IsFaulted) { - result.SetException(ExpandWebException(task.Exception.InnerException)); + result.SetException(ExpandWebException(task.Exception!.InnerException)); } else { try { @@ -65,7 +65,7 @@ static string AssetDownloadUrl(JsonElement obj) { return new UpdateInfo(versionTag, releaseNotes, downloadUrl, installerFolder); } - private static Exception ExpandWebException(Exception e) { + private static Exception ExpandWebException(Exception? e) { if (e is WebException { Response: HttpWebResponse response } ) { try { using var stream = response.GetResponseStream(); @@ -76,7 +76,7 @@ private static Exception ExpandWebException(Exception e) { } } - return e; + return e!; } } } diff --git a/windows/TweetDuck/Utils/BrowserUtils.cs b/windows/TweetDuck/Utils/BrowserUtils.cs index 9dfcaa83..92c778f6 100644 --- a/windows/TweetDuck/Utils/BrowserUtils.cs +++ b/windows/TweetDuck/Utils/BrowserUtils.cs @@ -38,7 +38,7 @@ public static void SetupCefArgs(IDictionary<string, string> args) { args["disable-plugins-discovery"] = "1"; args["enable-system-flash"] = "0"; - if (args.TryGetValue("js-flags", out string jsFlags)) { + if (args.TryGetValue("js-flags", out var jsFlags)) { args["js-flags"] = "--expose-gc " + jsFlags; } else { @@ -63,7 +63,7 @@ static void SetZoomLevel(IBrowserHost host, int percentage) { host.SetZoomLevel(Math.Log(percentage / 100.0, 1.2)); } - void UpdateZoomLevel(object sender, EventArgs args) { + void UpdateZoomLevel(object? sender, EventArgs args) { SetZoomLevel(browser.GetBrowserHost(), Config.ZoomLevel); } diff --git a/windows/TweetDuck/Utils/NativeMethods.cs b/windows/TweetDuck/Utils/NativeMethods.cs index a1e938d3..2315a358 100644 --- a/windows/TweetDuck/Utils/NativeMethods.cs +++ b/windows/TweetDuck/Utils/NativeMethods.cs @@ -62,7 +62,7 @@ private struct MSLLHOOKSTRUCT { [DllImport("user32.dll")] private static extern bool PostMessage(IntPtr hWnd, uint msg, UIntPtr wParam, IntPtr lParam); - [DllImport("user32.dll")] + [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern uint RegisterWindowMessage(string messageName); [DllImport("user32.dll")] diff --git a/windows/TweetDuck/Utils/WindowsUtils.cs b/windows/TweetDuck/Utils/WindowsUtils.cs index aa954e4e..4ed5b066 100644 --- a/windows/TweetDuck/Utils/WindowsUtils.cs +++ b/windows/TweetDuck/Utils/WindowsUtils.cs @@ -43,28 +43,28 @@ public static void TryDeleteFolderWhenAble(string path, int timeout) { public static IEnumerable<Browser> FindInstalledBrowsers() { static IEnumerable<Browser> ReadBrowsersFromKey(RegistryHive hive) { using RegistryKey root = RegistryKey.OpenBaseKey(hive, RegistryView.Default); - using RegistryKey browserList = root.OpenSubKey(@"SOFTWARE\Clients\StartMenuInternet", false); + using RegistryKey? browserList = root.OpenSubKey(@"SOFTWARE\Clients\StartMenuInternet", false); if (browserList == null) { yield break; } foreach (string sub in browserList.GetSubKeyNames()) { - using RegistryKey browserKey = browserList.OpenSubKey(sub, false); - using RegistryKey shellKey = browserKey?.OpenSubKey(@"shell\open\command"); + using RegistryKey? browserKey = browserList.OpenSubKey(sub, false); + using RegistryKey? shellKey = browserKey?.OpenSubKey(@"shell\open\command"); - if (shellKey == null) { + if (browserKey == null || shellKey == null) { continue; } - string browserName = browserKey.GetValue(null) as string; - string browserPath = shellKey.GetValue(null) as string; + string? browserName = browserKey.GetValue(null) as string; + string? browserPath = shellKey.GetValue(null) as string; if (string.IsNullOrEmpty(browserName) || string.IsNullOrEmpty(browserPath)) { continue; } - if (browserPath[0] == '"' && browserPath[browserPath.Length - 1] == '"') { + if (browserPath[0] == '"' && browserPath[^1] == '"') { browserPath = browserPath.Substring(1, browserPath.Length - 2); } @@ -94,7 +94,7 @@ public Browser(string name, string path) { } public override int GetHashCode() => Name.GetHashCode(); - public override bool Equals(object obj) => obj is Browser other && Name == other.Name; + public override bool Equals(object? obj) => obj is Browser other && Name == other.Name; public override string ToString() => Name; } } diff --git a/windows/TweetImpl.CefSharp/Adapters/CefErrorCodeAdapter.cs b/windows/TweetImpl.CefSharp/Adapters/CefErrorCodeAdapter.cs index 39a35494..f63ff5d6 100644 --- a/windows/TweetImpl.CefSharp/Adapters/CefErrorCodeAdapter.cs +++ b/windows/TweetImpl.CefSharp/Adapters/CefErrorCodeAdapter.cs @@ -12,7 +12,7 @@ public bool IsAborted(CefErrorCode errorCode) { return errorCode == CefErrorCode.Aborted; } - public string GetName(CefErrorCode errorCode) { + public string? GetName(CefErrorCode errorCode) { return Enum.GetName(typeof(CefErrorCode), errorCode); } } diff --git a/windows/TweetImpl.CefSharp/Adapters/CefJsDialogCallbackAdapter.cs b/windows/TweetImpl.CefSharp/Adapters/CefJsDialogCallbackAdapter.cs index 61e1c04d..c0fbec2f 100644 --- a/windows/TweetImpl.CefSharp/Adapters/CefJsDialogCallbackAdapter.cs +++ b/windows/TweetImpl.CefSharp/Adapters/CefJsDialogCallbackAdapter.cs @@ -7,7 +7,7 @@ sealed class CefJsDialogCallbackAdapter : IJsDialogCallbackAdapter<IJsDialogCall private CefJsDialogCallbackAdapter() {} - public void Continue(IJsDialogCallback callback, bool success, string userInput = null) { + public void Continue(IJsDialogCallback callback, bool success, string? userInput = null) { if (userInput == null) { callback.Continue(success); } diff --git a/windows/TweetImpl.CefSharp/Adapters/CefResponseAdapter.cs b/windows/TweetImpl.CefSharp/Adapters/CefResponseAdapter.cs index ce54f7f4..a655dd71 100644 --- a/windows/TweetImpl.CefSharp/Adapters/CefResponseAdapter.cs +++ b/windows/TweetImpl.CefSharp/Adapters/CefResponseAdapter.cs @@ -24,7 +24,7 @@ public void SetHeader(IResponse response, string header, string value) { response.SetHeaderByName(header, value, overwrite: true); } - public string GetHeader(IResponse response, string header) { + public string? GetHeader(IResponse response, string header) { return response.Headers[header]; } } diff --git a/windows/TweetImpl.CefSharp/Component/BrowserComponentBase.cs b/windows/TweetImpl.CefSharp/Component/BrowserComponentBase.cs index 44ba67f2..ac69f118 100644 --- a/windows/TweetImpl.CefSharp/Component/BrowserComponentBase.cs +++ b/windows/TweetImpl.CefSharp/Component/BrowserComponentBase.cs @@ -10,7 +10,7 @@ namespace TweetImpl.CefSharp.Component { public abstract class BrowserComponentBase : BrowserComponent<IFrame, IRequest> { - public delegate CefContextMenuHandler CreateContextMenu(IContextMenuHandler handler); + public delegate CefContextMenuHandler CreateContextMenu(IContextMenuHandler? handler); public ResourceHandlerRegistry<IResourceHandler> ResourceHandlerRegistry { get; } = new ResourceHandlerRegistry<IResourceHandler>(CefResourceHandlerFactory.Instance); @@ -50,19 +50,19 @@ public override void AttachBridgeObject(string name, object bridge) { browser.JavascriptObjectRepository.Register(name, bridge); } - private void OnLoadingStateChanged(object sender, LoadingStateChangedEventArgs e) { + private void OnLoadingStateChanged(object? sender, LoadingStateChangedEventArgs e) { base.OnLoadingStateChanged(e.IsLoading); } - private void OnLoadError(object sender, LoadErrorEventArgs e) { + private void OnLoadError(object? sender, LoadErrorEventArgs e) { base.OnLoadError(e.FailedUrl, e.ErrorCode, CefErrorCodeAdapter.Instance); } - private void OnFrameLoadStart(object sender, FrameLoadStartEventArgs e) { + private void OnFrameLoadStart(object? sender, FrameLoadStartEventArgs e) { base.OnFrameLoadStart(e.Url, e.Frame); } - private void OnFrameLoadEnd(object sender, FrameLoadEndEventArgs e) { + private void OnFrameLoadEnd(object? sender, FrameLoadEndEventArgs e) { base.OnFrameLoadEnd(e.Url, e.Frame); } } diff --git a/windows/TweetImpl.CefSharp/Handlers/CefByteArrayResourceHandler.cs b/windows/TweetImpl.CefSharp/Handlers/CefByteArrayResourceHandler.cs index 4e84ac86..79a28fd0 100644 --- a/windows/TweetImpl.CefSharp/Handlers/CefByteArrayResourceHandler.cs +++ b/windows/TweetImpl.CefSharp/Handlers/CefByteArrayResourceHandler.cs @@ -12,25 +12,27 @@ public sealed class CefByteArrayResourceHandler : IResourceHandler { dataOut.Write(dataIn, position, length); }; - private ByteArrayResourceHandlerLogic<IResponse> logic; - - public CefByteArrayResourceHandler() { - SetResource(new ByteArrayResource(Array.Empty<byte>())); + private static ByteArrayResourceHandlerLogic<IResponse> CreateLogic(ByteArrayResource resource) { + return new ByteArrayResourceHandlerLogic<IResponse>(resource, CefResponseAdapter.Instance); } + private ByteArrayResourceHandlerLogic<IResponse> logic; + + public CefByteArrayResourceHandler() : this(new ByteArrayResource(Array.Empty<byte>())) {} + internal CefByteArrayResourceHandler(ByteArrayResource resource) { - SetResource(resource); + this.logic = CreateLogic(resource); } public void SetResource(ByteArrayResource resource) { - this.logic = new ByteArrayResourceHandlerLogic<IResponse>(resource, CefResponseAdapter.Instance); + this.logic = CreateLogic(resource); } bool IResourceHandler.Open(IRequest request, out bool handleRequest, ICallback callback) { return logic.Open(out handleRequest); } - void IResourceHandler.GetResponseHeaders(IResponse response, out long responseLength, out string redirectUrl) { + void IResourceHandler.GetResponseHeaders(IResponse response, out long responseLength, out string? redirectUrl) { logic.GetResponseHeaders(response, out responseLength, out redirectUrl); } diff --git a/windows/TweetImpl.CefSharp/Handlers/CefContextMenuHandler.cs b/windows/TweetImpl.CefSharp/Handlers/CefContextMenuHandler.cs index b1cb7927..a1ccc64d 100644 --- a/windows/TweetImpl.CefSharp/Handlers/CefContextMenuHandler.cs +++ b/windows/TweetImpl.CefSharp/Handlers/CefContextMenuHandler.cs @@ -7,7 +7,7 @@ namespace TweetImpl.CefSharp.Handlers { public abstract class CefContextMenuHandler : IContextMenuHandler { private readonly ContextMenuLogic<IMenuModel> logic; - protected CefContextMenuHandler(TweetLib.Browser.Interfaces.IContextMenuHandler handler) { + protected CefContextMenuHandler(TweetLib.Browser.Interfaces.IContextMenuHandler? handler) { this.logic = new ContextMenuLogic<IMenuModel>(handler, CefMenuModelAdapter.Instance); } diff --git a/windows/TweetImpl.CefSharp/Handlers/CefLifeSpanHandler.cs b/windows/TweetImpl.CefSharp/Handlers/CefLifeSpanHandler.cs index 35f7f2eb..f89ec04a 100644 --- a/windows/TweetImpl.CefSharp/Handlers/CefLifeSpanHandler.cs +++ b/windows/TweetImpl.CefSharp/Handlers/CefLifeSpanHandler.cs @@ -12,7 +12,7 @@ public CefLifeSpanHandler(IPopupHandler popupHandler) { this.Logic = new LifeSpanHandlerLogic(popupHandler); } - protected override bool OnBeforePopup(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, string targetUrl, string targetFrameName, WindowOpenDisposition targetDisposition, bool userGesture, IPopupFeatures popupFeatures, IWindowInfo windowInfo, IBrowserSettings browserSettings, ref bool noJavascriptAccess, out IWebBrowser newBrowser) { + protected override bool OnBeforePopup(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, string targetUrl, string targetFrameName, WindowOpenDisposition targetDisposition, bool userGesture, IPopupFeatures popupFeatures, IWindowInfo windowInfo, IBrowserSettings browserSettings, ref bool noJavascriptAccess, out IWebBrowser? newBrowser) { newBrowser = null; return Logic.OnBeforePopup(targetUrl, ConvertTargetDisposition(targetDisposition)); } diff --git a/windows/TweetImpl.CefSharp/Handlers/CefResourceRequestHandler.cs b/windows/TweetImpl.CefSharp/Handlers/CefResourceRequestHandler.cs index 15d9212f..8a973505 100644 --- a/windows/TweetImpl.CefSharp/Handlers/CefResourceRequestHandler.cs +++ b/windows/TweetImpl.CefSharp/Handlers/CefResourceRequestHandler.cs @@ -9,7 +9,7 @@ namespace TweetImpl.CefSharp.Handlers { sealed class CefResourceRequestHandler : ResourceRequestHandler { private readonly ResourceRequestHandlerLogic<IRequest, IResponse, IResourceHandler> logic; - public CefResourceRequestHandler(ResourceHandlerRegistry<IResourceHandler> resourceHandlerRegistry, IResourceRequestHandler resourceRequestHandler) { + public CefResourceRequestHandler(ResourceHandlerRegistry<IResourceHandler> resourceHandlerRegistry, IResourceRequestHandler? resourceRequestHandler) { this.logic = new ResourceRequestHandlerLogic<IRequest, IResponse, IResourceHandler>(CefRequestAdapter.Instance, CefResponseAdapter.Instance, resourceHandlerRegistry, resourceRequestHandler); } @@ -17,11 +17,11 @@ protected override CefReturnValue OnBeforeResourceLoad(IWebBrowser chromiumWebBr return logic.OnBeforeResourceLoad(request, callback) ? CefReturnValue.Continue : CefReturnValue.Cancel; } - protected override IResourceHandler GetResourceHandler(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request) { + protected override IResourceHandler? GetResourceHandler(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request) { return logic.GetResourceHandler(request); } - protected override IResponseFilter GetResourceResponseFilter(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response) { + protected override IResponseFilter? GetResourceResponseFilter(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response) { return CefResponseFilter.Create(logic.GetResourceResponseFilter(request, response)); } diff --git a/windows/TweetImpl.CefSharp/Handlers/CefResourceRequestHandlerFactory.cs b/windows/TweetImpl.CefSharp/Handlers/CefResourceRequestHandlerFactory.cs index 11701a8a..007d82de 100644 --- a/windows/TweetImpl.CefSharp/Handlers/CefResourceRequestHandlerFactory.cs +++ b/windows/TweetImpl.CefSharp/Handlers/CefResourceRequestHandlerFactory.cs @@ -11,7 +11,7 @@ sealed class CefResourceRequestHandlerFactory : IResourceRequestHandlerFactory { private readonly ResourceRequestHandlerFactoryLogic<CefResourceRequestHandler, IResourceHandler, IRequest> logic; - public CefResourceRequestHandlerFactory(IResourceRequestHandler resourceRequestHandler, ResourceHandlerRegistry<IResourceHandler> registry) { + public CefResourceRequestHandlerFactory(IResourceRequestHandler? resourceRequestHandler, ResourceHandlerRegistry<IResourceHandler> registry) { this.logic = new ResourceRequestHandlerFactoryLogic<CefResourceRequestHandler, IResourceHandler, IRequest>(CefRequestAdapter.Instance, new CefResourceRequestHandler(registry, resourceRequestHandler), registry); } diff --git a/windows/TweetImpl.CefSharp/Handlers/CefResponseFilter.cs b/windows/TweetImpl.CefSharp/Handlers/CefResponseFilter.cs index fc6f2c24..da62854e 100644 --- a/windows/TweetImpl.CefSharp/Handlers/CefResponseFilter.cs +++ b/windows/TweetImpl.CefSharp/Handlers/CefResponseFilter.cs @@ -5,7 +5,7 @@ namespace TweetImpl.CefSharp.Handlers { sealed class CefResponseFilter : IResponseFilter { - public static CefResponseFilter Create(ResponseFilterLogic logic) { + public static CefResponseFilter? Create(ResponseFilterLogic? logic) { return logic == null ? null : new CefResponseFilter(logic); } diff --git a/windows/TweetImpl.CefSharp/Handlers/CefSchemeHandlerFactory.cs b/windows/TweetImpl.CefSharp/Handlers/CefSchemeHandlerFactory.cs index 5010efc8..5b7fa0c5 100644 --- a/windows/TweetImpl.CefSharp/Handlers/CefSchemeHandlerFactory.cs +++ b/windows/TweetImpl.CefSharp/Handlers/CefSchemeHandlerFactory.cs @@ -23,7 +23,7 @@ private CefSchemeHandlerFactory(ICustomSchemeHandler handler) { this.logic = new SchemeHandlerFactoryLogic<IRequest, IResourceHandler>(handler, CefRequestAdapter.Instance, CefResourceHandlerFactory.Instance); } - IResourceHandler ISchemeHandlerFactory.Create(IBrowser browser, IFrame frame, string schemeName, IRequest request) { + IResourceHandler? ISchemeHandlerFactory.Create(IBrowser browser, IFrame frame, string schemeName, IRequest request) { return logic.Create(request); } }