1
0
mirror of https://github.com/chylex/TweetDuck.git synced 2025-05-01 08:34:11 +02:00

Fix compiler and IDE warnings for .NET 6

This commit is contained in:
chylex 2022-06-09 00:41:43 +02:00
parent 96d2e7cc7c
commit bee894bfbb
Signed by: chylex
GPG Key ID: 4DE42C8F19A80548
102 changed files with 461 additions and 460 deletions
lib
windows

View File

@ -2,7 +2,7 @@
using System.Collections.Generic; using System.Collections.Generic;
namespace TweetLib.Browser.CEF.Data { namespace TweetLib.Browser.CEF.Data {
abstract class ContextMenuActionRegistry<T> { abstract class ContextMenuActionRegistry<T> where T : notnull {
private readonly Dictionary<T, Action> actions = new (); private readonly Dictionary<T, Action> actions = new ();
protected abstract T NextId(int n); protected abstract T NextId(int n);

View File

@ -21,7 +21,7 @@ internal bool HasHandler(string url) {
} }
private void Register(string url, Func<TResourceHandler> factory) { 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!"); throw new ArgumentException("Resource handler URL must be absolute!");
} }

View File

@ -9,7 +9,7 @@ private static (MessageDialogType, string) GetMessageDialogProperties(string tex
int pipe = text.IndexOf('|'); int pipe = text.IndexOf('|');
if (pipe != -1) { if (pipe != -1) {
type = text.Substring(0, pipe) switch { type = text[..pipe] switch {
"error" => MessageDialogType.Error, "error" => MessageDialogType.Error,
"warning" => MessageDialogType.Warning, "warning" => MessageDialogType.Warning,
"info" => MessageDialogType.Information, "info" => MessageDialogType.Information,
@ -18,7 +18,7 @@ private static (MessageDialogType, string) GetMessageDialogProperties(string tex
}; };
if (type != MessageDialogType.None) { if (type != MessageDialogType.None) {
text = text.Substring(pipe + 1); text = text[(pipe + 1)..];
} }
} }

View File

@ -8,7 +8,7 @@ public static string GetCacheFolder(string storagePath) {
return Path.Combine(storagePath, "Cache"); return Path.Combine(storagePath, "Cache");
} }
public static CommandLineArgs ParseCommandLineArguments(string argumentString) { public static CommandLineArgs ParseCommandLineArguments(string? argumentString) {
CommandLineArgs args = new CommandLineArgs(); CommandLineArgs args = new CommandLineArgs();
if (string.IsNullOrWhiteSpace(argumentString)) { if (string.IsNullOrWhiteSpace(argumentString)) {
@ -26,8 +26,8 @@ public static CommandLineArgs ParseCommandLineArguments(string argumentString) {
value = "1"; value = "1";
} }
else { else {
key = matchValue.Substring(0, indexEquals).TrimStart('-'); key = matchValue[..indexEquals].TrimStart('-');
value = matchValue.Substring(indexEquals + 1).Trim('"'); value = matchValue[(indexEquals + 1)..].Trim('"');
} }
if (key.Length != 0) { if (key.Length != 0) {

View File

@ -1,9 +1,9 @@
namespace TweetLib.Browser.Contexts { namespace TweetLib.Browser.Contexts {
public struct Notification { public struct Notification {
public string TweetUrl { get; } public string? TweetUrl { get; }
public string? QuoteUrl { get; } public string? QuoteUrl { get; }
public Notification(string tweetUrl, string? quoteUrl) { public Notification(string? tweetUrl, string? quoteUrl) {
TweetUrl = tweetUrl; TweetUrl = tweetUrl;
QuoteUrl = quoteUrl; QuoteUrl = quoteUrl;
} }

View File

@ -13,13 +13,11 @@ public static Server CreateServer() {
public static Client CreateClient(string token) { public static Client CreateClient(string token) {
int space = token.IndexOf(' '); 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 pipeIn;
private readonly PipeStream pipeOut; private readonly PipeStream pipeOut;
private readonly Thread readerThread;
private readonly StreamWriter writerStream; private readonly StreamWriter writerStream;
public event EventHandler<PipeReadEventArgs>? DataIn; public event EventHandler<PipeReadEventArgs>? DataIn;
@ -27,13 +25,9 @@ public static Client CreateClient(string token) {
private DuplexPipe(PipeStream pipeIn, PipeStream pipeOut) { private DuplexPipe(PipeStream pipeIn, PipeStream pipeOut) {
this.pipeIn = pipeIn; this.pipeIn = pipeIn;
this.pipeOut = pipeOut; this.pipeOut = pipeOut;
this.readerThread = new Thread(ReaderThread) {
IsBackground = true
};
this.readerThread.Start();
this.writerStream = new StreamWriter(this.pipeOut); this.writerStream = new StreamWriter(this.pipeOut);
new Thread(ReaderThread) { IsBackground = true }.Start();
} }
private void ReaderThread() { private void ReaderThread() {
@ -95,8 +89,8 @@ internal PipeReadEventArgs(string line) {
Data = string.Empty; Data = string.Empty;
} }
else { else {
Key = line.Substring(0, separatorIndex); Key = line[..separatorIndex];
Data = line.Substring(separatorIndex + 1); Data = line[(separatorIndex + 1)..];
} }
} }
} }

View File

@ -34,7 +34,7 @@ public static void LoadResourceRewriteRules(string rules) {
if (resourceType is ResourceType.Script or ResourceType.Stylesheet && TweetDeckHashes.Count > 0) { if (resourceType is ResourceType.Script or ResourceType.Stylesheet && TweetDeckHashes.Count > 0) {
Match match = TweetDeckResourceUrl.Match(url); 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) { if (match.Groups[2].Value == hash) {
App.Logger.Debug("[RequestHandlerBase] Accepting " + url); App.Logger.Debug("[RequestHandlerBase] Accepting " + url);
} }

View File

@ -84,7 +84,7 @@ public void SaveImages(string[] urls, string? author) {
var settings = new SaveFileDialogSettings { var settings = new SaveFileDialogSettings {
DialogTitle = oneImage ? "Save Image" : "Save Images", DialogTitle = oneImage ? "Save Image" : "Save Images",
OverwritePrompt = oneImage, 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 }) } Filters = new [] { new FileDialogFilter(oneImage ? "Image" : "Images", string.IsNullOrEmpty(ext) ? Array.Empty<string>() : new [] { ext }) }
}; };

View File

@ -56,7 +56,9 @@ public override void Show(IContextMenuBuilder menu, Context context) {
menu.AddSeparator(); menu.AddSeparator();
if (context.Notification is {} notification) { 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)) { if (!string.IsNullOrEmpty(notification.QuoteUrl)) {
AddCopyAction(menu, "Copy quoted tweet address", notification.QuoteUrl!); AddCopyAction(menu, "Copy quoted tweet address", notification.QuoteUrl!);
@ -72,7 +74,7 @@ public override void Dispose() {
this.browserComponent.PageLoadEnd -= BrowserComponentOnPageLoadEnd; this.browserComponent.PageLoadEnd -= BrowserComponentOnPageLoadEnd;
} }
private void BrowserComponentOnPageLoadEnd(object sender, PageLoadEventArgs e) { private void BrowserComponentOnPageLoadEnd(object? sender, PageLoadEventArgs e) {
string url = e.Url; string url = e.Url;
if (TwitterUrls.IsTweetDeck(url) && url != BlankURL) { if (TwitterUrls.IsTweetDeck(url) && url != BlankURL) {

View File

@ -93,7 +93,7 @@ public override int GetHashCode() {
return Identifier.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); return obj is Plugin plugin && plugin.Identifier.Equals(Identifier);
} }

View File

@ -48,17 +48,17 @@ internal int GetTokenFromPlugin(Plugin plugin) {
} }
internal Plugin? GetPluginFromToken(int token) { 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 // Event handlers
private void manager_Reloaded(object sender, PluginErrorEventArgs e) { private void manager_Reloaded(object? sender, PluginErrorEventArgs e) {
tokens.Clear(); tokens.Clear();
fileCache.Clear(); fileCache.Clear();
} }
private void Config_PluginChangedState(object sender, PluginChangedStateEventArgs e) { private void Config_PluginChangedState(object? sender, PluginChangedStateEventArgs e) {
if (!e.IsEnabled) { if (!e.IsEnabled) {
int token = GetTokenFromPlugin(e.Plugin); 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) { private string ReadFileUnsafe(int token, PluginFolder folder, string path, bool readCached) {
string fullPath = GetFullPathOrThrow(token, folder, path); 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; return cachedContents;
} }
@ -161,7 +161,7 @@ public void Clear() {
cache.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); return cache.TryGetValue(token, Key(folder, path), out contents);
} }

View File

@ -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) { private static Plugin FromFolder(string name, string pathRoot, string pathData, PluginGroup group) {
Plugin.Builder builder = new Plugin.Builder(group, name, pathRoot, pathData); 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); builder.AddEnvironment(environment);
} }
@ -55,7 +55,7 @@ private static Plugin FromFolder(string name, string pathRoot, string pathData,
string currentContents = string.Empty; 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)) { 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) { if (currentTag != null) {
SetProperty(builder, currentTag, currentContents); SetProperty(builder, currentTag, currentContents);
} }
@ -106,7 +106,7 @@ private static void SetProperty(Plugin.Builder builder, string tag, string value
builder.ConfigDefault = value; builder.ConfigDefault = value;
break; break;
case "REQUIRES": 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; break;
default: default:
throw new FormatException($"Invalid metadata tag: {tag}"); throw new FormatException($"Invalid metadata tag: {tag}");

View File

@ -102,7 +102,7 @@ internal void Execute(PluginEnvironment environment, IScriptExecutor executor) {
Executed?.Invoke(this, new PluginErrorEventArgs(errors)); 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); browserExecutor?.RunFunction("TDPF_setPluginState", e.Plugin, e.IsEnabled);
} }

View File

@ -71,12 +71,12 @@ public override void Dispose() {
App.UserConfiguration.SoundNotificationChanged -= UserConfiguration_SoundNotificationChanged; 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"); e.AddDictionaryWords("tweetdeck", "TweetDeck", "tweetduck", "TweetDuck", "TD");
isBrowserReady = true; isBrowserReady = true;
} }
private void browserComponent_PageLoadStart(object sender, PageLoadEventArgs e) { private void browserComponent_PageLoadStart(object? sender, PageLoadEventArgs e) {
string url = e.Url; string url = e.Url;
if (TwitterUrls.IsTweetDeck(url) || (TwitterUrls.IsTwitter(url) && !TwitterUrls.IsTwitterLogin2Factor(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; string url = e.Url;
if (TwitterUrls.IsTweetDeck(url)) { if (TwitterUrls.IsTweetDeck(url)) {
@ -105,7 +105,7 @@ private void browserComponent_PageLoadEnd(object sender, PageLoadEventArgs e) {
browserComponent.RunBootstrap("update"); browserComponent.RunBootstrap("update");
} }
private void pluginManager_Reloaded(object sender, PluginErrorEventArgs e) { private void pluginManager_Reloaded(object? sender, PluginErrorEventArgs e) {
if (e.HasErrors) { 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)); 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) { if (e.HasErrors) {
App.MessageDialogs.Error("Error Executing Plugins", "Failed to execute the following plugins:\n\n" + string.Join("\n\n", e.Errors)); 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) { private void updateChecker_CheckFinished(object? sender, UpdateCheckEventArgs e) {
var updateChecker = (UpdateChecker) sender; var updateChecker = (UpdateChecker) sender!;
e.Result.Handle(update => { e.Result.Handle(update => {
string tag = update.VersionTag; string tag = update.VersionTag;
@ -144,7 +144,7 @@ private void updateChecker_CheckFinished(object sender, UpdateCheckEventArgs e)
ignoreUpdateCheckError = true; ignoreUpdateCheckError = true;
} }
private void UserConfiguration_GeneralEventHandler(object sender, EventArgs e) { private void UserConfiguration_GeneralEventHandler(object? sender, EventArgs e) {
UpdatePropertyObject(); UpdatePropertyObject();
} }

View File

@ -24,15 +24,15 @@ public void SetLink(string type, string? url) {
switch (type) { switch (type) {
case "link": case "link":
Link = new Link(url!, url!); Link = new Link(url, url);
break; break;
case "image": 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; break;
case "video": case "video":
Media = new Media(Type.Video, url!); Media = new Media(Type.Video, url);
break; break;
} }
} }

View File

@ -57,7 +57,7 @@ public static bool TryParse(string url, out ImageUrl obj) {
return false; return false;
} }
string originalUrl = url.Substring(0, question); string originalUrl = url[..question];
obj = new ImageUrl(Path.HasExtension(originalUrl) ? originalUrl : originalUrl + imageExtension, imageQuality); obj = new ImageUrl(Path.HasExtension(originalUrl) ? originalUrl : originalUrl + imageExtension, imageQuality);
return true; return true;

View File

@ -49,11 +49,11 @@ public enum UrlType {
} }
public static UrlType Check(string url) { public static UrlType Check(string url) {
if (url.Contains("\"")) { if (url.Contains('"')) {
return UrlType.Invalid; 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; string scheme = uri.Scheme;
if (scheme == Uri.UriSchemeHttps || scheme == Uri.UriSchemeHttp || scheme == Uri.UriSchemeFtp || scheme == Uri.UriSchemeMailto) { if (scheme == Uri.UriSchemeHttps || scheme == Uri.UriSchemeHttp || scheme == Uri.UriSchemeFtp || scheme == Uri.UriSchemeMailto) {

View File

@ -16,7 +16,7 @@ static ConfigManager() {
ConverterRegistry.Register(typeof(WindowState), new BasicTypeConverter<WindowState> { 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}", ConvertToString = static value => $"{(value.IsMaximized ? 'M' : '_')}{value.Bounds.X} {value.Bounds.Y} {value.Bounds.Width} {value.Bounds.Height}",
ConvertToObject = static value => { ConvertToObject = static value => {
int[] elements = StringUtils.ParseInts(value.Substring(1), ' '); int[] elements = StringUtils.ParseInts(value[1..], ' ');
return new WindowState { return new WindowState {
Bounds = new Rectangle(elements[0], elements[1], elements[2], elements[3]), Bounds = new Rectangle(elements[0], elements[1], elements[2], elements[3]),

View File

@ -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("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"); build.Append(message).Append("\r\n\r\n");
try { try {

View File

@ -37,7 +37,7 @@ public void Dispose() {
InteractionManager.Dispose(); InteractionManager.Dispose();
} }
private void timer_Elapsed(object sender, ElapsedEventArgs e) { private void timer_Elapsed(object? sender, ElapsedEventArgs e) {
Check(false); Check(false);
} }

View File

@ -26,7 +26,7 @@ public void ClearUpdate() {
nextUpdate = null; 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; UpdateInfo? foundUpdate = e.Result.HasValue ? e.Result.Value : null;
if (nextUpdate != null && !nextUpdate.Equals(foundUpdate)) { if (nextUpdate != null && !nextUpdate.Equals(foundUpdate)) {

View File

@ -57,7 +57,7 @@ public void SetValue(string key, string value) {
} }
public string? GetValue(string key) { 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) { public void RemoveValue(string key) {

View File

@ -11,7 +11,7 @@ namespace TweetLib.Utils.Collections {
/// <typeparam name="V">The type of the values.</typeparam> /// <typeparam name="V">The type of the values.</typeparam>
[SuppressMessage("ReSharper", "UnusedMethodReturnValue.Global")] [SuppressMessage("ReSharper", "UnusedMethodReturnValue.Global")]
[SuppressMessage("ReSharper", "UnusedMember.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 Dictionary<K1, Dictionary<K2, V>> dict;
private readonly int innerCapacity; private readonly int innerCapacity;
@ -41,7 +41,7 @@ public TwoKeyDictionary(int outerCapacity, int innerCapacity) {
} }
set { 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)); dict.Add(outerKey, innerDict = new Dictionary<K2, V>(innerCapacity));
} }
@ -67,7 +67,7 @@ public IEnumerable<V> InnerValues {
/// Throws if the key pair already exists. /// Throws if the key pair already exists.
/// </summary> /// </summary>
public void Add(K1 outerKey, K2 innerKey, V value) { 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)); 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. /// Determines whether the dictionary contains the key pair.
/// </summary> /// </summary>
public bool Contains(K1 outerKey, K2 innerKey) { 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> /// <summary>
@ -122,8 +122,8 @@ public int Count(K1 outerKey) {
/// Gets the value associated with the key pair. /// Gets the value associated with the key pair.
/// Returns true if the key pair was present. /// Returns true if the key pair was present.
/// </summary> /// </summary>
public bool TryGetValue(K1 outerKey, K2 innerKey, out V value) { public bool TryGetValue(K1 outerKey, K2 innerKey, [MaybeNullWhen(false)] out V value) {
if (dict.TryGetValue(outerKey, out Dictionary<K2, V> innerDict)) { if (dict.TryGetValue(outerKey, out Dictionary<K2, V>? innerDict)) {
return innerDict.TryGetValue(innerKey, out value); return innerDict.TryGetValue(innerKey, out value);
} }
else { else {
@ -145,7 +145,7 @@ public bool Remove(K1 outerKey) {
/// Returns true if the key pair was present. /// Returns true if the key pair was present.
/// </summary> /// </summary>
public bool Remove(K1 outerKey, K2 innerKey) { 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) { if (innerDict.Count == 0) {
dict.Remove(outerKey); dict.Remove(outerKey);
} }

View File

@ -2,9 +2,9 @@
namespace TweetLib.Utils.Dialogs { namespace TweetLib.Utils.Dialogs {
public sealed class SaveFileDialogSettings { public sealed class SaveFileDialogSettings {
public string DialogTitle { get; set; } = "Save File"; public string DialogTitle { get; init; } = "Save File";
public bool OverwritePrompt { get; set; } = true; public bool OverwritePrompt { get; init; } = true;
public string? FileName { get; set; } public string? FileName { get; init; }
public IReadOnlyList<FileDialogFilter>? Filters { get; set; } public IReadOnlyList<FileDialogFilter>? Filters { get; init; }
} }
} }

View File

@ -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); 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}"; return cultureInfo.DisplayName == cultureInfo.NativeName ? capitalizedName : $"{capitalizedName}, {cultureInfo.DisplayName}";
} }
public int CompareTo(Language other) { public int CompareTo(Language? other) {
return string.Compare(Name, other.Name, false, CultureInfo.InvariantCulture); return string.Compare(Name, other?.Name, false, CultureInfo.InvariantCulture);
} }
} }
} }

View File

@ -134,7 +134,7 @@ public sealed class Entry {
public string[] KeyValue { public string[] KeyValue {
get { get {
int index = Identifier.IndexOf(KeySeparator); 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);
} }
} }

View File

@ -2,12 +2,12 @@
namespace TweetLib.Utils.Serialization.Converters { namespace TweetLib.Utils.Serialization.Converters {
public sealed class BasicTypeConverter<T> : ITypeConverter { public sealed class BasicTypeConverter<T> : ITypeConverter {
public Func<T, string>? ConvertToString { get; set; } public Func<T, string>? ConvertToString { get; init; }
public Func<string, T>? ConvertToObject { get; set; } 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 { try {
converted = ConvertToString!((T) value); converted = ConvertToString!((T) value!);
return true; return true;
} catch { } catch {
converted = null; converted = null;

View File

@ -6,18 +6,17 @@ sealed class ClrTypeConverter : ITypeConverter {
private ClrTypeConverter() {} 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)) { switch (Type.GetTypeCode(type)) {
case TypeCode.Boolean: case TypeCode.Boolean:
converted = value.ToString(); converted = value!.ToString();
return true; return true;
case TypeCode.Int32: case TypeCode.Int32:
converted = ((int) value).ToString(); // cast required for enums converted = ((int) value!).ToString(); // cast required for enums
return true; return true;
case TypeCode.String: case TypeCode.String:
// ReSharper disable once ConstantConditionalAccessQualifier
converted = value?.ToString(); converted = value?.ToString();
return true; return true;

View File

@ -2,7 +2,7 @@
namespace TweetLib.Utils.Serialization { namespace TweetLib.Utils.Serialization {
public interface ITypeConverter { 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); bool TryReadType(Type type, string value, out object? converted);
} }
} }

View File

@ -28,7 +28,7 @@ private static string UnescapeStream(StreamReader reader) {
break; break;
} }
else { else {
build.Append(data.Substring(index, nextIndex - index)); build.Append(data[index..nextIndex]);
char next = data[nextIndex + 1]; 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; private readonly TypeConverterRegistry converterRegistry;
@ -114,7 +114,7 @@ public void Read(string file, T obj) {
int nextPos = contents.IndexOf(NewLineReal, currentPos); int nextPos = contents.IndexOf(NewLineReal, currentPos);
if (nextPos == -1) { if (nextPos == -1) {
line = contents.Substring(currentPos); line = contents[currentPos..];
currentPos = -1; currentPos = -1;
if (string.IsNullOrEmpty(line)) { if (string.IsNullOrEmpty(line)) {
@ -133,10 +133,10 @@ public void Read(string file, T obj) {
continue; continue;
} }
string property = line.Substring(0, space); string property = line[..space];
string value = UnescapeLine(line.Substring(space + 1)); 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 type = info.PropertyType;
var converter = converterRegistry.TryGet(type) ?? ClrTypeConverter.Instance; var converter = converterRegistry.TryGet(type) ?? ClrTypeConverter.Instance;

View File

@ -1,6 +1,5 @@
using System; using System;
using System.Diagnostics; using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO; using System.IO;
using System.Threading; using System.Threading;
using TweetLib.Utils.Static; using TweetLib.Utils.Static;
@ -91,7 +90,6 @@ public UnlockResult Unlock() {
return UnlockResult.Success; return UnlockResult.Success;
} }
[SuppressMessage("ReSharper", "PossibleNullReferenceException")]
private LockResult DetermineLockingProcessOrFail(Exception originalException) { private LockResult DetermineLockingProcessOrFail(Exception originalException) {
try { try {
int pid; int pid;
@ -110,7 +108,7 @@ private LockResult DetermineLockingProcessOrFail(Exception originalException) {
var foundProcess = Process.GetProcessById(pid); var foundProcess = Process.GetProcessById(pid);
using var currentProcess = Process.GetCurrentProcess(); 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); return new LockResult.HasProcess(foundProcess);
} }
else { else {

View File

@ -40,7 +40,7 @@ public static (string before, string after)? SplitInTwo(string str, char search,
return null; return null;
} }
return (str.Substring(0, index), str.Substring(index + 1)); return (str[..index], str[(index + 1)..]);
} }
/// <summary> /// <summary>
@ -49,7 +49,7 @@ public static (string before, string after)? SplitInTwo(string str, char search,
/// </summary> /// </summary>
public static string ExtractBefore(string str, char search, int startIndex = 0) { public static string ExtractBefore(string str, char search, int startIndex = 0) {
int index = str.IndexOf(search, startIndex); int index = str.IndexOf(search, startIndex);
return index == -1 ? str : str.Substring(0, index); return index == -1 ? str : str[..index];
} }
/// <summary> /// <summary>

View File

@ -12,8 +12,10 @@ public static class WebUtils {
private static void EnsureTLS12() { private static void EnsureTLS12() {
if (!hasMicrosoftBeenBroughtTo2008Yet) { if (!hasMicrosoftBeenBroughtTo2008Yet) {
#pragma warning disable CS0618
ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12; ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;
ServicePointManager.SecurityProtocol &= ~(SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11); ServicePointManager.SecurityProtocol &= ~(SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11);
#pragma warning restore CS0618
hasMicrosoftBeenBroughtTo2008Yet = true; hasMicrosoftBeenBroughtTo2008Yet = true;
} }
} }

View File

@ -47,7 +47,7 @@ module RegexAccount =
Assert.True(isMatch("https://twitter.com/" + name)) Assert.True(isMatch("https://twitter.com/" + name))
module Match = module Match =
let extract str = TwitterUrls.RegexAccount.Match(str).Groups.[1].Value let extract str = TwitterUrls.RegexAccount.Match(str).Groups[1].Value
[<Fact>] [<Fact>]
let ``extracts account name from simple URL`` () = let ``extracts account name from simple URL`` () =

View File

@ -276,11 +276,11 @@ module ToDictionary =
TestData.mixed.ToDictionary(dict) TestData.mixed.ToDictionary(dict)
Assert.Equal(5, dict.Count) Assert.Equal(5, dict.Count)
Assert.Equal("1", dict.["flag1"]) Assert.Equal("1", dict["flag1"])
Assert.Equal("1", dict.["flag2"]) Assert.Equal("1", dict["flag2"])
Assert.Equal("1", dict.["flag3"]) Assert.Equal("1", dict["flag3"])
Assert.Equal("hello", dict.["val1"]) Assert.Equal("hello", dict["val1"])
Assert.Equal("world", dict.["val2"]) Assert.Equal("world", dict["val2"])
[<Fact>] [<Fact>]
let ``prefers value if the same name is used for a flag and value`` () = let ``prefers value if the same name is used for a flag and value`` () =
@ -288,7 +288,7 @@ module ToDictionary =
TestData.duplicate.ToDictionary(dict) TestData.duplicate.ToDictionary(dict)
Assert.Equal(1, dict.Count) Assert.Equal(1, dict.Count)
Assert.Equal("value", dict.["duplicate"]) Assert.Equal("value", dict["duplicate"])
module ToString = module ToString =

View File

@ -38,36 +38,36 @@ module Indexer =
[<InlineData("second", 2, 200.0)>] [<InlineData("second", 2, 200.0)>]
[<InlineData("third", 1, 1000.0)>] [<InlineData("third", 1, 1000.0)>]
let ``get returns correct value`` (outerKey: string, innerKey: int, value: float) = 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>] [<Fact>]
let ``get throws if outer key is missing`` () = 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>] [<Fact>]
let ``get throws if inner key is missing`` () = 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>] [<Fact>]
let ``set modifies existing value`` () = let ``set modifies existing value`` () =
let copy = TestData.uniquevals 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>] [<Fact>]
let ``set creates new inner key`` () = let ``set creates new inner key`` () =
let copy = TestData.uniquevals 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>] [<Fact>]
let ``set creates new outer key`` () = let ``set creates new outer key`` () =
let copy = TestData.uniquevals 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 = module InnerValues =
@ -93,14 +93,14 @@ module Add =
let copy = TestData.uniquevals let copy = TestData.uniquevals
copy.Add("first", 4, 40.0) copy.Add("first", 4, 40.0)
Assert.Equal(40.0, copy.["first", 4]) Assert.Equal(40.0, copy["first", 4])
[<Fact>] [<Fact>]
let ``creates new outer key`` () = let ``creates new outer key`` () =
let copy = TestData.uniquevals let copy = TestData.uniquevals
copy.Add("fourth", 1, 10000.0) copy.Add("fourth", 1, 10000.0)
Assert.Equal(10000.0, copy.["fourth", 1]) Assert.Equal(10000.0, copy["fourth", 1])
[<Fact>] [<Fact>]
let ``throw on duplicate key`` () = let ``throw on duplicate key`` () =

View File

@ -83,7 +83,7 @@ module ReadFile =
[<InlineData("singleFile")>] [<InlineData("singleFile")>]
[<InlineData("singleFileWithMultiIdentifier")>] [<InlineData("singleFileWithMultiIdentifier")>]
let ``reading first file from single file stream returns an entry`` (stream: string) = 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()) Assert.NotNull(f.ReadFile())
) )
@ -91,7 +91,7 @@ module ReadFile =
[<InlineData("singleFile")>] [<InlineData("singleFile")>]
[<InlineData("singleFileWithMultiIdentifier")>] [<InlineData("singleFileWithMultiIdentifier")>]
let ``reading second file from single file stream returns null`` (stream: string) = 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 f.ReadFile() |> ignore
Assert.Null(f.ReadFile()) Assert.Null(f.ReadFile())
) )
@ -197,7 +197,7 @@ module Entry =
[<InlineData("singleFile")>] [<InlineData("singleFile")>]
[<InlineData("singleFileWithMultiIdentifier")>] [<InlineData("singleFileWithMultiIdentifier")>]
let ``contents of single file stream with are correct`` (stream: string) = 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)) Assert.Equal("test file\n123", Encoding.UTF8.GetString(f.ReadFile().Contents))
) )

View File

@ -25,7 +25,7 @@ private static int Main(string[] args) {
private static async void KillWhenHung(int parentId) { private static async void KillWhenHung(int parentId) {
try { try {
using Process process = Process.GetProcessById(parentId); using Process process = Process.GetProcessById(parentId);
process.WaitForExit(); await process.WaitForExitAsync();
} catch { } catch {
// ded // ded
} }

View File

@ -30,7 +30,7 @@ public void AttachTooltip(Control control, bool followCursor, Func<MouseEventArg
Text = text; 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.X = Math.Max(0, Math.Min(form.Width - Width, loc.X - Width / 2));
loc.Y -= Height - Margin.Top + Margin.Bottom; loc.Y -= Height - Margin.Top + Margin.Bottom;
Location = loc; Location = loc;
@ -42,7 +42,7 @@ public void AttachTooltip(Control control, bool followCursor, Func<MouseEventArg
control.MouseLeave += control_MouseLeave; control.MouseLeave += control_MouseLeave;
} }
private void control_MouseLeave(object sender, EventArgs e) { private void control_MouseLeave(object? sender, EventArgs e) {
Visible = false; Visible = false;
} }
} }

View File

@ -153,12 +153,12 @@ static void Disable(TableLayoutPanel panel) {
// Events // Events
private void FormPlayer_Load(object sender, EventArgs e) { private void FormPlayer_Load(object? sender, EventArgs e) {
Player.URL = videoUrl; Player.URL = videoUrl;
} }
private void pipe_DataIn(object sender, DuplexPipe.PipeReadEventArgs e) { private void pipe_DataIn(object? sender, DuplexPipe.PipeReadEventArgs e) {
Invoke(new Action(() => { Invoke(() => {
switch (e.Key) { switch (e.Key) {
case "key": case "key":
HandleKey((Keys) int.Parse(e.Data, NumberStyles.Integer)); HandleKey((Keys) int.Parse(e.Data, NumberStyles.Integer));
@ -168,7 +168,7 @@ private void pipe_DataIn(object sender, DuplexPipe.PipeReadEventArgs e) {
StopVideo(); StopVideo();
break; break;
} }
})); });
} }
private void player_PlayStateChange(int newState) { private void player_PlayStateChange(int newState) {
@ -215,7 +215,7 @@ private void timerUI_Tick(object? sender, EventArgs e) {
Marshal.ReleaseComObject(controls); 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)) { if (NativeMethods.GetWindowRect(ownerHandle, out NativeMethods.RECT rect)) {
IWMPMedia media = Player.currentMedia; IWMPMedia media = Player.currentMedia;
IWMPControls controls = Player.controls; 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(); timerData.Stop();
pipe.Write("vol", trackBarVolume.Value.ToString()); 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) { if (e.Button == MouseButtons.Left) {
IWMPMedia media = Player.currentMedia; IWMPMedia media = Player.currentMedia;
IWMPControls controls = Player.controls; 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; IWMPSettings settings = Player.settings;
settings.volume = trackBarVolume.Value; 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; isDragging = true;
} }
private void trackBarVolume_MouseUp(object sender, MouseEventArgs e) { private void trackBarVolume_MouseUp(object? sender, MouseEventArgs e) {
isDragging = false; isDragging = false;
} }
private void imageClose_Click(object sender, EventArgs e) { private void imageClose_Click(object? sender, EventArgs e) {
StopVideo(); StopVideo();
} }
private void imageDownload_Click(object sender, EventArgs e) { private void imageDownload_Click(object? sender, EventArgs e) {
pipe.Write("download"); pipe.Write("download");
} }
private void imageResize_Click(object sender, EventArgs e) { private void imageResize_Click(object? sender, EventArgs e) {
Player.fullScreen = true; Player.fullScreen = true;
} }

View File

@ -18,7 +18,7 @@ public void SaveFile(SaveFileDialogSettings settings, Action<string> onAccepted)
}; };
if (dialog.ShowDialog() == DialogResult.OK) { if (dialog.ShowDialog() == DialogResult.OK) {
onAccepted(dialog.FileName); onAccepted(dialog.FileName!);
} }
}); });
} }

View File

@ -13,7 +13,7 @@
namespace TweetDuck.Application { namespace TweetDuck.Application {
sealed class SystemHandler : IAppSystemHandler { sealed class SystemHandler : IAppSystemHandler {
public void OpenBrowser(string url) { public void OpenBrowser(string? url) {
if (string.IsNullOrWhiteSpace(url)) { if (string.IsNullOrWhiteSpace(url)) {
return; return;
} }
@ -23,7 +23,7 @@ public void OpenBrowser(string url) {
switch (TwitterUrls.Check(url)) { switch (TwitterUrls.Check(url)) {
case TwitterUrls.UrlType.Fine: case TwitterUrls.UrlType.Fine:
string browserPath = config.BrowserPath; string? browserPath = config.BrowserPath;
if (browserPath == null || !File.Exists(browserPath)) { if (browserPath == null || !File.Exists(browserPath)) {
OpenAssociatedProgram(url); OpenAssociatedProgram(url);
@ -120,7 +120,7 @@ public void OpenFileExplorer(string path) {
void PerformSearch() { void PerformSearch() {
var config = Program.Config.User; var config = Program.Config.User;
string searchUrl = config.SearchEngineUrl; string? searchUrl = config.SearchEngineUrl;
if (string.IsNullOrEmpty(searchUrl)) { 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)) { 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; return;
} }
FormSettings settings = FormManager.TryFind<FormSettings>(); FormSettings? settings = FormManager.TryFind<FormSettings>();
if (settings == null) { if (settings == null) {
return; return;
@ -146,7 +146,7 @@ void PerformSearch() {
} }
} }
else { else {
App.SystemHandler.OpenBrowser(searchUrl + Uri.EscapeUriString(text)); App.SystemHandler.OpenBrowser(searchUrl + Uri.EscapeDataString(text));
} }
} }

View File

@ -10,7 +10,7 @@ sealed class CefBrowserComponent : BrowserComponentBase {
public override string CacheFolder => CefUtils.GetCacheFolder(App.StoragePath); 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(); browser.SetupZoomEvents();
} }
} }

View File

@ -14,7 +14,7 @@ class ContextMenuBase : CefContextMenuHandler {
protected static UserConfig Config => Program.Config.User; 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) { protected override Context CreateContext(IContextMenuParams parameters) {
return CreateContext(parameters, null, Config.TwitterImageQuality); 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 context = new Context();
var flags = parameters.TypeFlags; var flags = parameters.TypeFlags;
@ -74,7 +74,7 @@ protected static Context CreateContext(IContextMenuParams parameters, TweetDeckE
return context; return context;
} }
private static Link? GetLink(IContextMenuParams parameters, TweetDeckExtraContext extraContext) { private static Link? GetLink(IContextMenuParams parameters, TweetDeckExtraContext? extraContext) {
var link = extraContext?.Link; var link = extraContext?.Link;
if (link != null) { if (link != null) {
return link; return link;
@ -87,7 +87,7 @@ protected static Context CreateContext(IContextMenuParams parameters, TweetDeckE
return null; 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; var media = extraContext?.Media;
if (media != null) { if (media != null) {
return media; return media;

View File

@ -24,7 +24,7 @@ sealed class ContextMenuBrowser : ContextMenuBase {
private readonly FormBrowser form; private readonly FormBrowser form;
private readonly TweetDeckExtraContext extraContext; 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.form = form;
this.extraContext = extraContext; this.extraContext = extraContext;
} }

View File

@ -8,7 +8,7 @@ namespace TweetDuck.Browser.Base {
sealed class ContextMenuNotification : ContextMenuBase { sealed class ContextMenuNotification : ContextMenuBase {
private readonly FormNotificationBase form; private readonly FormNotificationBase form;
public ContextMenuNotification(FormNotificationBase form, IContextMenuHandler handler) : base(handler) { public ContextMenuNotification(FormNotificationBase form, IContextMenuHandler? handler) : base(handler) {
this.form = form; this.form = form;
} }

View File

@ -5,9 +5,9 @@
namespace TweetDuck.Browser.Base { namespace TweetDuck.Browser.Base {
sealed class CustomKeyboardHandler : IKeyboardHandler { sealed class CustomKeyboardHandler : IKeyboardHandler {
private readonly IBrowserKeyHandler handler; private readonly IBrowserKeyHandler? handler;
public CustomKeyboardHandler(IBrowserKeyHandler handler) { public CustomKeyboardHandler(IBrowserKeyHandler? handler) {
this.handler = handler; this.handler = handler;
} }

View File

@ -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 ResourceCache resourceCache;
private readonly TweetDeckBrowser browser; private readonly TweetDeckBrowser browser;
@ -63,8 +63,8 @@ public bool IsWaiting {
private bool isLoaded; private bool isLoaded;
private FormWindowState prevState; private FormWindowState prevState;
private TweetScreenshotManager notificationScreenshotManager; private TweetScreenshotManager? notificationScreenshotManager;
private VideoPlayer videoPlayer; private VideoPlayer? videoPlayer;
public FormBrowser(ResourceCache resourceCache, PluginManager pluginManager, IUpdateCheckClient updateCheckClient, uint windowRestoreMessage) { public FormBrowser(ResourceCache resourceCache, PluginManager pluginManager, IUpdateCheckClient updateCheckClient, uint windowRestoreMessage) {
InitializeComponent(); InitializeComponent();
@ -156,11 +156,11 @@ private void UpdateTray() {
// event handlers // 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 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) { if (!isLoaded) {
return; return;
} }
@ -172,7 +172,7 @@ private void FormBrowser_Activated(object sender, EventArgs e) {
} // the window, enable the browser again } // the window, enable the browser again
} }
private void FormBrowser_LocationChanged(object sender, EventArgs e) { private void FormBrowser_LocationChanged(object? sender, EventArgs e) {
if (!isLoaded) { if (!isLoaded) {
return; return;
} }
@ -181,7 +181,7 @@ private void FormBrowser_LocationChanged(object sender, EventArgs e) {
timerResize.Start(); timerResize.Start();
} }
private void FormBrowser_Resize(object sender, EventArgs e) { private void FormBrowser_Resize(object? sender, EventArgs e) {
if (!isLoaded) { if (!isLoaded) {
return; 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) { if (!isLoaded) {
return; 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) { if (!isLoaded) {
return; 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) { if (isLoaded && UpdateInstaller == null) {
updates.InteractionManager.ClearUpdate(); updates.InteractionManager.ClearUpdate();
updates.InteractionManager.Dispose(); updates.InteractionManager.Dispose();
} }
} }
private void Config_MuteToggled(object sender, EventArgs e) { private void Config_MuteToggled(object? sender, EventArgs e) {
UpdateFormIcon(); UpdateFormIcon();
} }
private void Config_TrayBehaviorChanged(object sender, EventArgs e) { private void Config_TrayBehaviorChanged(object? sender, EventArgs e) {
UpdateTray(); UpdateTray();
} }
private void trayIcon_ClickRestore(object sender, EventArgs e) { private void trayIcon_ClickRestore(object? sender, EventArgs e) {
Show(); Show();
RestoreWindow(); RestoreWindow();
Activate(); Activate();
UpdateTray(); UpdateTray();
} }
private void trayIcon_ClickClose(object sender, EventArgs e) { private void trayIcon_ClickClose(object? sender, EventArgs e) {
ForceClose(); ForceClose();
} }
private void updateInteractionManager_UpdateAccepted(object sender, UpdateInfo update) { private void updateInteractionManager_UpdateAccepted(object? sender, UpdateInfo update) {
this.InvokeAsyncSafe(() => { this.InvokeAsyncSafe(() => {
FormManager.CloseAllDialogs(); 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(() => { this.InvokeAsyncSafe(() => {
Config.DismissedUpdate = update.VersionTag; Config.DismissedUpdate = update.VersionTag;
Config.Save(); Config.Save();
@ -385,7 +385,7 @@ public void OpenSettings() {
OpenSettings(null); OpenSettings(null);
} }
public void OpenSettings(Type startTab) { public void OpenSettings(Type? startTab) {
if (!FormManager.TryBringToFront<FormSettings>()) { if (!FormManager.TryBringToFront<FormSettings>()) {
bool prevEnableUpdateCheck = Config.EnableUpdateCheck; bool prevEnableUpdateCheck = Config.EnableUpdateCheck;
@ -464,7 +464,7 @@ private void PlayVideo(string videoUrl, string tweetUrl, string username, IJavas
videoUrl = Regex.Replace(videoUrl, "^https://", "http://"); videoUrl = Regex.Replace(videoUrl, "^https://", "http://");
} }
string playerPath = Config.VideoPlayerPath; string? playerPath = Config.VideoPlayerPath;
if (playerPath == null || !File.Exists(playerPath)) { if (playerPath == null || !File.Exists(playerPath)) {
if (videoPlayer == null) { if (videoPlayer == null) {
@ -512,7 +512,7 @@ private void OnTweetScreenshotReady(string html, int width) {
notificationScreenshotManager.Trigger(html, width); notificationScreenshotManager.Trigger(html, width);
} }
private void DisplayTooltip(string text) { private void DisplayTooltip(string? text) {
if (string.IsNullOrEmpty(text)) { if (string.IsNullOrEmpty(text)) {
toolTip.Hide(this); toolTip.Hide(this);
} }
@ -554,7 +554,7 @@ public void Alert(string type, string contents) {
FormMessage.Show("TweetDuck Browser Message", contents, icon, FormMessage.OK); FormMessage.Show("TweetDuck Browser Message", contents, icon, FormMessage.OK);
} }
public void DisplayTooltip(string text) { public void DisplayTooltip(string? text) {
form.InvokeAsyncSafe(() => form.DisplayTooltip(text)); form.InvokeAsyncSafe(() => form.DisplayTooltip(text));
} }

View File

@ -97,11 +97,11 @@ protected virtual FormBorderStyle NotificationBorderStyle {
private readonly CefByteArrayResourceHandler resourceHandler = new CefByteArrayResourceHandler(); private readonly CefByteArrayResourceHandler resourceHandler = new CefByteArrayResourceHandler();
private DesktopNotification currentNotification; private DesktopNotification? currentNotification;
private readonly HashSet<NotificationPauseReason> pauseReasons = new HashSet<NotificationPauseReason>(); private readonly HashSet<NotificationPauseReason> pauseReasons = new HashSet<NotificationPauseReason>();
public string CurrentTweetUrl => currentNotification?.TweetUrl; public string? CurrentTweetUrl => currentNotification?.TweetUrl;
public string CurrentQuoteUrl => currentNotification?.QuoteUrl; public string? CurrentQuoteUrl => currentNotification?.QuoteUrl;
protected bool IsPaused => pauseReasons.Count > 0; protected bool IsPaused => pauseReasons.Count > 0;
protected internal bool IsCursorOverBrowser => browser.Bounds.Contains(PointToClient(Cursor.Position)); protected internal bool IsCursorOverBrowser => browser.Bounds.Contains(PointToClient(Cursor.Position));
@ -156,7 +156,7 @@ protected override void WndProc(ref Message m) {
// event handlers // event handlers
private void owner_FormClosed(object sender, FormClosedEventArgs e) { private void owner_FormClosed(object? sender, FormClosedEventArgs e) {
Close(); Close();
} }
@ -195,7 +195,7 @@ protected virtual void SetNotificationSize(int width, int height) {
} }
protected virtual void UpdateTitle() { protected virtual void UpdateTitle() {
string title = currentNotification?.ColumnTitle; string? title = currentNotification?.ColumnTitle;
Text = string.IsNullOrEmpty(title) || !Config.DisplayNotificationColumn ? Program.BrandName : $"{Program.BrandName} - {title}"; 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)) { if (string.IsNullOrEmpty(text)) {
toolTip.Hide(this); toolTip.Hide(this);
} }

View File

@ -32,7 +32,7 @@ protected override FormBorderStyle NotificationBorderStyle {
} }
} }
public event EventHandler Ready; public event EventHandler? Ready;
private readonly DesktopNotification exampleNotification; private readonly DesktopNotification exampleNotification;

View File

@ -23,7 +23,7 @@ public NotificationInterfaceImpl(FormNotificationBase notification) {
this.notification = notification; this.notification = notification;
} }
public void DisplayTooltip(string text) { public void DisplayTooltip(string? text) {
notification.InvokeAsyncSafe(() => notification.DisplayTooltip(text)); notification.InvokeAsyncSafe(() => notification.DisplayTooltip(text));
} }
@ -175,14 +175,14 @@ private IntPtr MouseHookProc(int nCode, IntPtr wParam, IntPtr lParam) {
// event handlers // event handlers
private void FormNotification_FormClosing(object sender, FormClosingEventArgs e) { private void FormNotification_FormClosing(object? sender, FormClosingEventArgs e) {
if (e.CloseReason == CloseReason.UserClosing) { if (e.CloseReason == CloseReason.UserClosing) {
HideNotification(); HideNotification();
e.Cancel = true; 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) { if (!e.IsLoading && browser.Address != NotificationBrowser.BlankURL) {
this.InvokeSafe(() => { this.InvokeSafe(() => {
Visible = true; // ensures repaint before moving the window to a visible location 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(); OnNotificationReady();
timerDisplayDelay.Stop(); timerDisplayDelay.Stop();
} }
private void timerHideProgress_Tick(object sender, EventArgs e) { private void timerHideProgress_Tick(object? sender, EventArgs e) {
bool isCursorInside = Bounds.Contains(Cursor.Position); bool isCursorInside = Bounds.Contains(Cursor.Position);
if (isCursorInside) { if (isCursorInside) {

View File

@ -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) { if (WindowsSessionManager.IsLocked) {
PauseNotification(NotificationPauseReason.WindowsSessionLocked); PauseNotification(NotificationPauseReason.WindowsSessionLocked);
} }
@ -78,7 +78,7 @@ protected override void WndProc(ref Message m) {
// event handlers // event handlers
private void Config_MuteToggled(object sender, EventArgs e) { private void Config_MuteToggled(object? sender, EventArgs e) {
if (Config.MuteNotifications) { if (Config.MuteNotifications) {
PauseNotification(NotificationPauseReason.UserConfiguration); 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) { if (!IsCursorOverNotificationArea) {
ResumeNotification(NotificationPauseReason.CursorOverNotificationArea); ResumeNotification(NotificationPauseReason.CursorOverNotificationArea);
timerCursorCheck.Stop(); timerCursorCheck.Stop();
} }
} }
private void timerIdlePauseCheck_Tick(object sender, EventArgs e) { private void timerIdlePauseCheck_Tick(object? sender, EventArgs e) {
if (NativeMethods.GetIdleSeconds() < Config.NotificationIdlePauseSeconds) { if (NativeMethods.GetIdleSeconds() < Config.NotificationIdlePauseSeconds) {
ResumeNotification(NotificationPauseReason.SystemIdle); ResumeNotification(NotificationPauseReason.SystemIdle);
timerIdlePauseCheck.Stop(); timerIdlePauseCheck.Stop();

View File

@ -28,7 +28,7 @@ public FormNotificationScreenshotable(Action callback, FormBrowser owner, Plugin
browserComponent.AttachBridgeObject("$TD_NotificationScreenshot", new ScreenshotBridge(this, SetScreenshotHeight, callback)); browserComponent.AttachBridgeObject("$TD_NotificationScreenshot", new ScreenshotBridge(this, SetScreenshotHeight, callback));
browserComponent.BrowserLoaded += (sender, args) => { browserComponent.BrowserLoaded += (sender, args) => {
string script = ResourceUtils.ReadFileOrNull("notification/screenshot/screenshot.js"); string? script = ResourceUtils.ReadFileOrNull("notification/screenshot/screenshot.js");
if (script == null) { if (script == null) {
this.InvokeAsyncSafe(callback); this.InvokeAsyncSafe(callback);
@ -47,29 +47,27 @@ private void SetScreenshotHeight(int browserHeight) {
this.height = BrowserUtils.Scale(browserHeight, SizeScale); this.height = BrowserUtils.Scale(browserHeight, SizeScale);
} }
public Task<Image> TakeScreenshot(bool ignoreHeightError = false) { public Task<Image>? TakeScreenshot() {
if (!ignoreHeightError) { if (height == 0) {
if (height == 0) { FormMessage.Error("Screenshot Failed", "Could not detect screenshot size.", FormMessage.OK);
FormMessage.Error("Screenshot Failed", "Could not detect screenshot size.", FormMessage.OK); return null;
return null; }
} else if (height > ClientSize.Height) {
else if (height > ClientSize.Height) { FormMessage.Error("Screenshot Failed", $"Screenshot is too large: {height}px > {ClientSize.Height}px", FormMessage.OK);
FormMessage.Error("Screenshot Failed", $"Screenshot is too large: {height}px > {ClientSize.Height}px", FormMessage.OK); return null;
return null;
}
} }
return Task.Run(TakeScreenshotImpl); return Task.Run(TakeScreenshotImpl);
} }
private async Task<Image> TakeScreenshotImpl() { private async Task<Image> TakeScreenshotImpl() {
if (this.height == 0) { if (height == 0) {
return null; throw new InvalidOperationException("Screenshot height must not be zero!");
} }
Viewport viewport = new Viewport { Viewport viewport = new Viewport {
Width = this.ClientSize.Width, Width = ClientSize.Width,
Height = this.height, Height = height,
Scale = 1 Scale = 1
}; };

View File

@ -35,7 +35,7 @@ sealed class TweetScreenshotManager : IDisposable {
public const int WaitFrames = 5; public const int WaitFrames = 5;
#endif #endif
private FormNotificationScreenshotable screenshot; private FormNotificationScreenshotable? screenshot;
public TweetScreenshotManager(FormBrowser owner, PluginManager pluginManager) { public TweetScreenshotManager(FormBrowser owner, PluginManager pluginManager) {
this.owner = owner; this.owner = owner;
@ -53,14 +53,14 @@ public TweetScreenshotManager(FormBrowser owner, PluginManager pluginManager) {
#endif #endif
} }
private void timeout_Tick(object sender, EventArgs e) { private void timeout_Tick(object? sender, EventArgs e) {
timeout.Stop(); timeout.Stop();
OnFinished(); OnFinished();
} }
private void disposer_Tick(object sender, EventArgs e) { private void disposer_Tick(object? sender, EventArgs e) {
disposer.Stop(); disposer.Stop();
screenshot.Dispose(); screenshot?.Dispose();
screenshot = null; screenshot = null;
} }
@ -88,12 +88,12 @@ private void Callback() {
} }
timeout.Stop(); timeout.Stop();
screenshot.TakeScreenshot().ContinueWith(HandleResult, TaskScheduler.FromCurrentSynchronizationContext()); screenshot?.TakeScreenshot()?.ContinueWith(HandleResult, TaskScheduler.FromCurrentSynchronizationContext());
} }
private void HandleResult(Task<Image> task) { private void HandleResult(Task<Image> task) {
if (task.IsFaulted) { 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) { else if (task.IsCompleted) {
Clipboard.SetImage(task.Result); Clipboard.SetImage(task.Result);
@ -111,7 +111,10 @@ private void OnFinished() {
debugger.Stop(); debugger.Stop();
#endif #endif
screenshot.Location = ControlExtensions.InvisibleLocation; if (screenshot != null) {
screenshot.Location = ControlExtensions.InvisibleLocation;
}
owner.IsWaiting = false; owner.IsWaiting = false;
disposer.Start(); disposer.Start();
} }
@ -141,7 +144,7 @@ private void StartDebugger() {
debugger.Start(); debugger.Start();
} }
private void debugger_Tick(object sender, EventArgs e) { private void debugger_Tick(object? sender, EventArgs e) {
if (frameCounter < 63) { if (frameCounter < 63) {
int frame = ++frameCounter; int frame = ++frameCounter;
screenshot.TakeScreenshot(true).ContinueWith(task => SaveDebugFrame(task, frame), TaskScheduler.FromCurrentSynchronizationContext()); screenshot.TakeScreenshot(true).ContinueWith(task => SaveDebugFrame(task, frame), TaskScheduler.FromCurrentSynchronizationContext());

View File

@ -40,13 +40,13 @@ private static (byte[] data, string mimeType)? CreateFileHandler(string path) {
".mp3" => "audio/mp3", ".mp3" => "audio/mp3",
".flac" => "audio/flac", ".flac" => "audio/flac",
".opus" => "audio/ogg; codecs=opus", ".opus" => "audio/ogg; codecs=opus",
_ => null _ => "application/octet-stream"
}; };
try { try {
return (File.ReadAllBytes(path), mimeType); return (File.ReadAllBytes(path), mimeType);
} catch { } catch {
FormBrowser browser = FormManager.TryFind<FormBrowser>(); FormBrowser? browser = FormManager.TryFind<FormBrowser>();
browser?.InvokeAsyncSafe(() => { browser?.InvokeAsyncSafe(() => {
using FormMessage form = new FormMessage("Sound Notification Error", "Could not find custom notification sound file:\n" + path, MessageBoxIcon.Error); using FormMessage form = new FormMessage("Sound Notification Error", "Could not find custom notification sound file:\n" + path, MessageBoxIcon.Error);

View File

@ -17,8 +17,8 @@ public enum Behavior { // keep order
private static UserConfig Config => Program.Config.User; private static UserConfig Config => Program.Config.User;
public event EventHandler ClickRestore; public event EventHandler? ClickRestore;
public event EventHandler ClickClose; public event EventHandler? ClickClose;
public bool Visible { public bool Visible {
get { get {
@ -85,30 +85,30 @@ private void UpdateIcon() {
// event handlers // event handlers
private void Config_MuteToggled(object sender, EventArgs e) { private void Config_MuteToggled(object? sender, EventArgs e) {
UpdateIcon(); UpdateIcon();
} }
private void trayIcon_MouseClick(object sender, MouseEventArgs e) { private void trayIcon_MouseClick(object? sender, MouseEventArgs e) {
if (e.Button == MouseButtons.Left) { if (e.Button == MouseButtons.Left) {
menuItemRestore_Click(sender, e); 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; ((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); 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.MuteNotifications = !((ToolStripMenuItem) contextMenu.Items[1]).Checked;
Config.Save(); Config.Save();
} }
private void menuItemClose_Click(object sender, EventArgs e) { private void menuItemClose_Click(object? sender, EventArgs e) {
ClickClose?.Invoke(this, e); ClickClose?.Invoke(this, e);
} }
} }

View File

@ -21,7 +21,7 @@ public static bool HasFlag(string flag) {
return Current.HasFlag(flag); return Current.HasFlag(flag);
} }
public static string GetValue(string key) { public static string? GetValue(string key) {
return Current.GetValue(key); return Current.GetValue(key);
} }

View File

@ -29,18 +29,18 @@ sealed class UserConfig : BaseConfig<UserConfig>, IAppUserConfiguration {
public bool EnableAnimatedImages { get; set; } = true; public bool EnableAnimatedImages { get; set; } = true;
public bool HideTweetsByNftUsers { get; set; } = false; public bool HideTweetsByNftUsers { get; set; } = false;
private bool _enableSmoothScrolling = true; private bool _enableSmoothScrolling = true;
private string _customCefArgs = null; private string? _customCefArgs = null;
public string BrowserPath { get; set; } = null; public string? BrowserPath { get; set; } = null;
public string BrowserPathArgs { get; set; } = null; public string? BrowserPathArgs { get; set; } = null;
public bool IgnoreTrackingUrlWarning { get; set; } = false; public bool IgnoreTrackingUrlWarning { get; set; } = false;
public string SearchEngineUrl { get; set; } = null; public string? SearchEngineUrl { get; set; } = null;
private int _zoomLevel = 100; private int _zoomLevel = 100;
public string VideoPlayerPath { get; set; } = null; public string? VideoPlayerPath { get; set; } = null;
public string VideoPlayerPathArgs { get; set; } = null; public string? VideoPlayerPathArgs { get; set; } = null;
public int VideoPlayerVolume { get; set; } = 50; public int VideoPlayerVolume { get; set; } = 50;
public bool EnableSpellCheck { get; set; } = false; public bool EnableSpellCheck { get; set; } = false;
private string _spellCheckLanguage = "en-US"; private string _spellCheckLanguage = "en-US";
@ -51,8 +51,8 @@ sealed class UserConfig : BaseConfig<UserConfig>, IAppUserConfiguration {
private TrayIcon.Behavior _trayBehavior = TrayIcon.Behavior.Disabled; private TrayIcon.Behavior _trayBehavior = TrayIcon.Behavior.Disabled;
public bool EnableTrayHighlight { get; set; } = true; public bool EnableTrayHighlight { get; set; } = true;
public bool EnableUpdateCheck { get; set; } = true; public bool EnableUpdateCheck { get; set; } = true;
public string DismissedUpdate { get; set; } = null; public string? DismissedUpdate { get; set; } = null;
public bool DisplayNotificationColumn { get; set; } = false; public bool DisplayNotificationColumn { get; set; } = false;
public bool NotificationMediaPreviews { get; set; } = true; public bool NotificationMediaPreviews { get; set; } = true;
@ -74,13 +74,13 @@ sealed class UserConfig : BaseConfig<UserConfig>, IAppUserConfiguration {
public Size CustomNotificationSize { get; set; } = Size.Empty; public Size CustomNotificationSize { get; set; } = Size.Empty;
public int NotificationScrollSpeed { get; set; } = 100; public int NotificationScrollSpeed { get; set; } = 100;
private string _notificationSoundPath; private string? _notificationSoundPath;
private int _notificationSoundVolume = 100; private int _notificationSoundVolume = 100;
private bool _muteNotifications; private bool _muteNotifications;
public string CustomBrowserCSS { get; set; } = null; public string? CustomBrowserCSS { get; set; } = null;
public string CustomNotificationCSS { get; set; } = null; public string? CustomNotificationCSS { get; set; } = null;
public bool DevToolsInContextMenu { get; set; } = false; public bool DevToolsInContextMenu { get; set; } = false;
public bool DevToolsWindowOnTop { get; set; } = true; public bool DevToolsWindowOnTop { get; set; } = true;
@ -123,7 +123,7 @@ public bool EnableSmoothScrolling {
set => UpdatePropertyWithCallback(ref _enableSmoothScrolling, value, App.ConfigManager.TriggerProgramRestartRequested); set => UpdatePropertyWithCallback(ref _enableSmoothScrolling, value, App.ConfigManager.TriggerProgramRestartRequested);
} }
public string CustomCefArgs { public string? CustomCefArgs {
get => _customCefArgs; get => _customCefArgs;
set => UpdatePropertyWithCallback(ref _customCefArgs, value, App.ConfigManager.TriggerProgramRestartRequested); set => UpdatePropertyWithCallback(ref _customCefArgs, value, App.ConfigManager.TriggerProgramRestartRequested);
} }
@ -149,11 +149,11 @@ public string SpellCheckLanguage {
// EVENTS // EVENTS
public event EventHandler MuteToggled; public event EventHandler? MuteToggled;
public event EventHandler ZoomLevelChanged; public event EventHandler? ZoomLevelChanged;
public event EventHandler TrayBehaviorChanged; public event EventHandler? TrayBehaviorChanged;
public event EventHandler SoundNotificationChanged; public event EventHandler? SoundNotificationChanged;
public event EventHandler OptionsDialogClosed; public event EventHandler? OptionsDialogClosed;
public void TriggerOptionsDialogClosed() { public void TriggerOptionsDialogClosed() {
OptionsDialogClosed?.Invoke(this, EventArgs.Empty); OptionsDialogClosed?.Invoke(this, EventArgs.Empty);

View File

@ -74,8 +74,8 @@ public static bool AlignValueToTick(this TrackBar trackBar) {
public static void EnableMultilineShortcuts(this TextBox textBox) { public static void EnableMultilineShortcuts(this TextBox textBox) {
textBox.KeyDown += (sender, args) => { textBox.KeyDown += (sender, args) => {
if (args.Control && args.KeyCode == Keys.A) { if (args.Control && args.KeyCode == Keys.A && sender is TextBox tb) {
((TextBox) sender).SelectAll(); tb.SelectAll();
args.SuppressKeyPress = true; args.SuppressKeyPress = true;
args.Handled = true; args.Handled = true;
} }

View File

@ -9,7 +9,7 @@ public FlatButton() {
GotFocus += FlatButton_GotFocus; 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); NotifyDefault(false);
} }
} }

View File

@ -3,7 +3,7 @@
namespace TweetDuck.Controls { namespace TweetDuck.Controls {
sealed class NumericUpDownEx : NumericUpDown { sealed class NumericUpDownEx : NumericUpDown {
public string TextSuffix { get; set ; } public string? TextSuffix { get; set; }
protected override void UpdateEditText() { protected override void UpdateEditText() {
base.UpdateEditText(); base.UpdateEditText();

View File

@ -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); 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(); ShowGuide();
} }
private void FormAbout_HelpButtonClicked(object sender, CancelEventArgs e) { private void FormAbout_HelpButtonClicked(object? sender, CancelEventArgs e) {
e.Cancel = true; e.Cancel = true;
ShowGuide(); ShowGuide();
} }

View File

@ -12,12 +12,12 @@ namespace TweetDuck.Dialogs {
sealed partial class FormGuide : Form, FormManager.IAppDialog { sealed partial class FormGuide : Form, FormManager.IAppDialog {
private const string GuideUrl = "td://guide/index.html"; 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); string url = GuideUrl + (string.IsNullOrEmpty(hash) ? string.Empty : "#" + hash);
FormGuide guide = FormManager.TryFind<FormGuide>(); FormGuide? guide = FormManager.TryFind<FormGuide>();
if (guide == null) { if (guide == null) {
FormBrowser owner = FormManager.TryFind<FormBrowser>(); FormBrowser? owner = FormManager.TryFind<FormBrowser>();
if (owner != null) { if (owner != null) {
new FormGuide(url, owner).Show(owner); new FormGuide(url, owner).Show(owner);

View File

@ -22,23 +22,23 @@ sealed partial class FormMessage : Form {
public const string Ignore = "Ignore"; public const string Ignore = "Ignore";
public const string Exit = "Exit"; 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); 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); 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); 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); 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); using FormMessage message = new FormMessage(caption, text, icon);
if (buttonCancel == null) { if (buttonCancel == null) {
@ -54,7 +54,7 @@ public static bool Show(string caption, string text, MessageBoxIcon icon, string
// Instance // Instance
public Button ClickedButton { get; private set; } public Button? ClickedButton { get; private set; }
public bool HasIcon => icon != null; public bool HasIcon => icon != null;
public int ActionPanelY => panelActions.Location.Y; public int ActionPanelY => panelActions.Location.Y;
@ -68,7 +68,7 @@ private int ButtonDistance {
get => BrowserUtils.Scale(96, dpiScale); get => BrowserUtils.Scale(96, dpiScale);
} }
private readonly Icon icon; private readonly Icon? icon;
private readonly bool isReady; private readonly bool isReady;
private readonly float dpiScale; 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); 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(); RecalculateButtonLocation();
} }
@ -135,7 +135,7 @@ public Button AddButton(string title, DialogResult result = DialogResult.OK, Con
}; };
button.Click += (sender, args) => { button.Click += (sender, args) => {
ClickedButton = (Button) sender; ClickedButton = button;
DialogResult = result; DialogResult = result;
Close(); 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) { if (!isReady) {
return; return;
} }

View File

@ -16,11 +16,12 @@ sealed partial class FormPlugins : Form, FormManager.IAppDialog {
private readonly PluginManager pluginManager; private readonly PluginManager pluginManager;
#pragma warning disable CS8618
private FormPlugins() { private FormPlugins() {
InitializeComponent(); InitializeComponent();
Text = Program.BrandName + " Plugins"; Text = Program.BrandName + " Plugins";
} }
#pragma warning restore CS8618
public FormPlugins(PluginManager pluginManager) : this() { public FormPlugins(PluginManager pluginManager) : this() {
this.pluginManager = pluginManager; this.pluginManager = pluginManager;
@ -68,7 +69,7 @@ private void ReloadPluginList() {
timerLayout.Start(); timerLayout.Start();
} }
private void timerLayout_Tick(object sender, EventArgs e) { private void timerLayout_Tick(object? sender, EventArgs e) {
timerLayout.Stop(); timerLayout.Stop();
// stupid WinForms scrollbars and panels // 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); Padding = new Padding(Padding.Left, Padding.Top, Padding.Right - 1, Padding.Bottom - 1);
} }
private void flowLayoutPlugins_Resize(object sender, EventArgs e) { private void flowLayoutPlugins_Resize(object? sender, EventArgs e) {
Control lastPlugin = flowLayoutPlugins.Controls.OfType<PluginControl>().LastOrDefault(); Control? lastPlugin = flowLayoutPlugins.Controls.OfType<PluginControl>().LastOrDefault();
if (lastPlugin == null) { if (lastPlugin == null) {
return; return;
@ -93,22 +94,22 @@ private void flowLayoutPlugins_Resize(object sender, EventArgs e) {
control.Width = flowLayoutPlugins.Width - control.Margin.Horizontal - horizontalOffset; control.Width = flowLayoutPlugins.Width - control.Margin.Horizontal - horizontalOffset;
} }
flowLayoutPlugins.Controls[flowLayoutPlugins.Controls.Count - 1].Visible = !showScrollBar; flowLayoutPlugins.Controls[^1].Visible = !showScrollBar;
flowLayoutPlugins.Focus(); 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)); 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)) { if (FormMessage.Warning("Reloading Plugins", "This will also reload the browser window. Do you want to proceed?", FormMessage.Yes, FormMessage.No)) {
pluginManager.Reload(); pluginManager.Reload();
ReloadPluginList(); ReloadPluginList();
} }
} }
private void btnClose_Click(object sender, EventArgs e) { private void btnClose_Click(object? sender, EventArgs e) {
Close(); Close();
} }
} }

View File

@ -25,9 +25,9 @@ sealed partial class FormSettings : Form, FormManager.IAppDialog {
private readonly int buttonHeight; private readonly int buttonHeight;
private readonly Dictionary<Type, SettingsTab> tabs = new Dictionary<Type, SettingsTab>(8); 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(); InitializeComponent();
Text = Program.BrandName + " Options"; Text = Program.BrandName + " Options";
@ -56,19 +56,19 @@ private void PrepareLoad() {
} }
private void PrepareUnload() { // TODO refactor this further later private void PrepareUnload() { // TODO refactor this further later
currentTab.Control.OnClosing(); currentTab?.Control.OnClosing();
App.ConfigManager.ProgramRestartRequested -= Config_ProgramRestartRequested; App.ConfigManager.ProgramRestartRequested -= Config_ProgramRestartRequested;
App.ConfigManager.SaveAll(); 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)) { 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(); Program.Restart();
} }
} }
private void FormSettings_FormClosing(object sender, FormClosingEventArgs e) { private void FormSettings_FormClosing(object? sender, FormClosingEventArgs e) {
PrepareUnload(); PrepareUnload();
foreach (SettingsTab tab in tabs.Values) { foreach (SettingsTab tab in tabs.Values) {
@ -80,7 +80,7 @@ private void FormSettings_FormClosing(object sender, FormClosingEventArgs e) {
browser.ResumeNotification(NotificationPauseReason.SettingsDialogOpen); browser.ResumeNotification(NotificationPauseReason.SettingsDialogOpen);
} }
private void btnManageOptions_Click(object sender, EventArgs e) { private void btnManageOptions_Click(object? sender, EventArgs e) {
PrepareUnload(); PrepareUnload();
using DialogSettingsManage dialog = new DialogSettingsManage(plugins); 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(); Close();
} }
@ -128,7 +128,7 @@ private void AddButton<T>(string title, Func<T> constructor) where T : BaseTab {
panelButtons.Controls.Add(new Panel { panelButtons.Controls.Add(new Panel {
BackColor = Color.DimGray, 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), Margin = new Padding(0),
Size = new Size(panelButtons.Width, 1) Size = new Size(panelButtons.Width, 1)
}); });
@ -182,7 +182,7 @@ private void SelectTab(SettingsTab tab) {
currentTab = 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 } ) { if (sender is ComboBox { DroppedDown: true } ) {
return; // prevents comboboxes from closing when MouseLeave event triggers during opening animation 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(); panelContents.Focus();
} }
private void control_MouseWheel(object sender, MouseEventArgs e) { private void control_MouseWheel(object? sender, MouseEventArgs e) {
((HandledMouseEventArgs) e).Handled = true; ((HandledMouseEventArgs) e).Handled = true;
panelContents.Focus(); panelContents.Focus();
} }
@ -202,7 +202,7 @@ private sealed class SettingsTab {
public bool IsInitialized => control != null; public bool IsInitialized => control != null;
private readonly Func<BaseTab> constructor; private readonly Func<BaseTab> constructor;
private BaseTab control; private BaseTab? control;
public SettingsTab(Button button, Func<BaseTab> constructor) { public SettingsTab(Button button, Func<BaseTab> constructor) {
this.Button = button; this.Button = button;

View File

@ -12,7 +12,7 @@ sealed partial class DialogSettingsCSS : Form {
private readonly Action<string> reinjectBrowserCSS; private readonly Action<string> reinjectBrowserCSS;
private readonly Action openDevTools; 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(); InitializeComponent();
Text = Program.BrandName + " Options - CSS"; Text = Program.BrandName + " Options - CSS";
@ -30,8 +30,8 @@ public DialogSettingsCSS(string browserCSS, string notificationCSS, Action<strin
textBoxBrowserCSS.Select(textBoxBrowserCSS.TextLength, 0); textBoxBrowserCSS.Select(textBoxBrowserCSS.TextLength, 0);
} }
private void tabPanel_SelectedIndexChanged(object sender, EventArgs e) { private void tabPanel_SelectedIndexChanged(object? sender, EventArgs e) {
TextBox tb = tabPanel.SelectedTab.Controls.OfType<TextBox>().FirstOrDefault(); TextBox? tb = tabPanel.SelectedTab.Controls.OfType<TextBox>().FirstOrDefault();
if (tb != null) { if (tb != null) {
tb.Focus(); tb.Focus();
@ -39,8 +39,8 @@ private void tabPanel_SelectedIndexChanged(object sender, EventArgs e) {
} }
} }
private void textBoxCSS_KeyDown(object sender, KeyEventArgs e) { private void textBoxCSS_KeyDown(object? sender, KeyEventArgs e) {
TextBox tb = (TextBox) sender; TextBox tb = (TextBox) sender!;
string text = tb.Text; string text = tb.Text;
if (e.KeyCode == Keys.Back && e.Modifiers == Keys.Control) { 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) { else if (e.KeyCode == Keys.Enter && e.Modifiers == Keys.None && tb.SelectionLength == 0) {
int insertAt = tb.SelectionStart, cursorOffset = 0; int insertAt = tb.SelectionStart, cursorOffset = 0;
string insertText; string? insertText;
if (insertAt == 0) { if (insertAt == 0) {
return; return;
@ -97,8 +97,9 @@ private void textBoxCSS_KeyDown(object sender, KeyEventArgs e) {
} }
else { else {
int lineStart = text.LastIndexOf('\n', tb.SelectionStart - 1); int lineStart = text.LastIndexOf('\n', tb.SelectionStart - 1);
var firstIndex = (lineStart == -1 ? 0 : lineStart + 1);
Match match = Regex.Match(text.Substring(lineStart == -1 ? 0 : lineStart + 1), "^([ \t]+)");
Match match = Regex.Match(text[firstIndex..], "^([ \t]+)");
insertText = match.Success ? Environment.NewLine + match.Groups[1].Value : null; 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.Stop();
timerTestBrowser.Start(); timerTestBrowser.Start();
} }
private void timerTestBrowser_Tick(object sender, EventArgs e) { private void timerTestBrowser_Tick(object? sender, EventArgs e) {
reinjectBrowserCSS(textBoxBrowserCSS.Text); reinjectBrowserCSS(textBoxBrowserCSS.Text);
timerTestBrowser.Stop(); timerTestBrowser.Stop();
} }
private void btnOpenDevTools_Click(object sender, EventArgs e) { private void btnOpenDevTools_Click(object? sender, EventArgs e) {
openDevTools(); openDevTools();
} }
private void btnApply_Click(object sender, EventArgs e) { private void btnApply_Click(object? sender, EventArgs e) {
DialogResult = DialogResult.OK; DialogResult = DialogResult.OK;
Close(); Close();
} }
private void btnCancel_Click(object sender, EventArgs e) { private void btnCancel_Click(object? sender, EventArgs e) {
DialogResult = DialogResult.Cancel; DialogResult = DialogResult.Cancel;
Close(); Close();
} }

View File

@ -10,7 +10,7 @@ sealed partial class DialogSettingsCefArgs : Form {
private readonly string initialArgs; private readonly string initialArgs;
public DialogSettingsCefArgs(string args) { public DialogSettingsCefArgs(string? args) {
InitializeComponent(); InitializeComponent();
Text = Program.BrandName + " Options - CEF Arguments"; Text = Program.BrandName + " Options - CEF Arguments";
@ -20,11 +20,11 @@ public DialogSettingsCefArgs(string args) {
textBoxArgs.Select(textBoxArgs.Text.Length, 0); 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/"); 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) { if (CefArgs == initialArgs) {
DialogResult = DialogResult.Cancel; DialogResult = DialogResult.Cancel;
Close(); 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; DialogResult = DialogResult.Cancel;
Close(); Close();
} }

View File

@ -5,12 +5,12 @@
namespace TweetDuck.Dialogs.Settings { namespace TweetDuck.Dialogs.Settings {
sealed partial class DialogSettingsExternalProgram : Form { sealed partial class DialogSettingsExternalProgram : Form {
public string Path { public string? Path {
get => StringUtils.NullIfEmpty(textBoxPath.Text); get => StringUtils.NullIfEmpty(textBoxPath.Text);
set => textBoxPath.Text = value ?? string.Empty; set => textBoxPath.Text = value ?? string.Empty;
} }
public string Args { public string? Args {
get => StringUtils.NullIfEmpty(textBoxArgs.Text); get => StringUtils.NullIfEmpty(textBoxArgs.Text);
set => textBoxArgs.Text = value ?? string.Empty; set => textBoxArgs.Text = value ?? string.Empty;
} }
@ -27,7 +27,7 @@ public DialogSettingsExternalProgram(string windowTitle, string fileDialogTitle)
this.fileDialogTitle = 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 { using OpenFileDialog dialog = new OpenFileDialog {
AutoUpgradeEnabled = true, AutoUpgradeEnabled = true,
DereferenceLinks = 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; DialogResult = DialogResult.OK;
Close(); Close();
} }
private void btnCancel_Click(object sender, EventArgs e) { private void btnCancel_Click(object? sender, EventArgs e) {
DialogResult = DialogResult.Cancel; DialogResult = DialogResult.Cancel;
Close(); Close();
} }

View File

@ -35,7 +35,7 @@ private ProfileManager.Items SelectedItems {
private readonly bool openImportImmediately; private readonly bool openImportImmediately;
private State currentState; private State currentState;
private ProfileManager importManager; private ProfileManager? importManager;
private bool requestedRestartFromConfig; private bool requestedRestartFromConfig;
private ProfileManager.Items _selectedItems = ProfileManager.Items.None; 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; btnContinue.Enabled = true;
} }
private void checkBoxSelection_CheckedChanged(object sender, EventArgs e) { private void checkBoxSelection_CheckedChanged(object? sender, EventArgs e) {
CheckBox cb = (CheckBox) sender; CheckBox cb = (CheckBox) sender!;
SetFlag(checkBoxMap[cb], cb.Checked); SetFlag(checkBoxMap[cb], cb.Checked);
} }
private void btnContinue_Click(object sender, EventArgs e) { private void btnContinue_Click(object? sender, EventArgs e) {
string file; string file;
switch (currentState) { switch (currentState) {
@ -167,7 +167,7 @@ private void btnContinue_Click(object sender, EventArgs e) {
break; break;
case State.Import: case State.Import:
if (importManager.Import(SelectedItems)) { if (importManager!.Import(SelectedItems)) {
App.ConfigManager.ProgramRestartRequested += Config_ProgramRestartRequested; App.ConfigManager.ProgramRestartRequested += Config_ProgramRestartRequested;
App.ConfigManager.ReloadAll(); App.ConfigManager.ReloadAll();
App.ConfigManager.SaveAll(); 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; DialogResult = DialogResult.Cancel;
Close(); Close();
} }
private void Config_ProgramRestartRequested(object sender, EventArgs e) { private void Config_ProgramRestartRequested(object? sender, EventArgs e) {
requestedRestartFromConfig = true; requestedRestartFromConfig = true;
} }

View File

@ -6,7 +6,7 @@
namespace TweetDuck.Dialogs.Settings { namespace TweetDuck.Dialogs.Settings {
sealed partial class DialogSettingsRestart : Form { sealed partial class DialogSettingsRestart : Form {
public CommandLineArgs Args { get; private set; } public CommandLineArgs Args { get; private set; } = null!;
public DialogSettingsRestart(CommandLineArgs currentArgs) { public DialogSettingsRestart(CommandLineArgs currentArgs) {
InitializeComponent(); InitializeComponent();
@ -28,7 +28,7 @@ public DialogSettingsRestart(CommandLineArgs currentArgs) {
Text = Program.BrandName + " Arguments"; Text = Program.BrandName + " Arguments";
} }
private void control_Change(object sender, EventArgs e) { private void control_Change(object? sender, EventArgs e) {
Args = new CommandLineArgs(); Args = new CommandLineArgs();
if (cbLogging.Checked) { if (cbLogging.Checked) {
@ -43,18 +43,18 @@ private void control_Change(object sender, EventArgs e) {
tbShortcutTarget.Select(tbShortcutTarget.Text.Length, 0); 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) { if (tbShortcutTarget.SelectionLength == 0) {
tbShortcutTarget.SelectAll(); tbShortcutTarget.SelectAll();
} }
} }
private void btnRestart_Click(object sender, EventArgs e) { private void btnRestart_Click(object? sender, EventArgs e) {
DialogResult = DialogResult.OK; DialogResult = DialogResult.OK;
Close(); Close();
} }
private void btnCancel_Click(object sender, EventArgs e) { private void btnCancel_Click(object? sender, EventArgs e) {
DialogResult = DialogResult.Cancel; DialogResult = DialogResult.Cancel;
Close(); Close();
} }

View File

@ -14,12 +14,12 @@ public DialogSettingsSearchEngine() {
textBoxUrl.Select(textBoxUrl.Text.Length, 0); 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; DialogResult = DialogResult.OK;
Close(); Close();
} }
private void btnCancel_Click(object sender, EventArgs e) { private void btnCancel_Click(object? sender, EventArgs e) {
DialogResult = DialogResult.Cancel; DialogResult = DialogResult.Cancel;
Close(); Close();
} }

View File

@ -9,10 +9,10 @@
namespace TweetDuck.Dialogs.Settings { namespace TweetDuck.Dialogs.Settings {
sealed partial class TabSettingsAdvanced : FormSettings.BaseTab { sealed partial class TabSettingsAdvanced : FormSettings.BaseTab {
private readonly Action<string> reinjectBrowserCSS; private readonly Action<string?> reinjectBrowserCSS;
private readonly Action openDevTools; private readonly Action openDevTools;
public TabSettingsAdvanced(Action<string> reinjectBrowserCSS, Action openDevTools) { public TabSettingsAdvanced(Action<string?> reinjectBrowserCSS, Action openDevTools) {
InitializeComponent(); InitializeComponent();
this.reinjectBrowserCSS = reinjectBrowserCSS; this.reinjectBrowserCSS = reinjectBrowserCSS;
@ -98,19 +98,19 @@ public override void OnClosing() {
#region Application #region Application
private void btnOpenAppFolder_Click(object sender, EventArgs e) { private void btnOpenAppFolder_Click(object? sender, EventArgs e) {
App.SystemHandler.OpenFileExplorer(App.ProgramPath); 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); App.SystemHandler.OpenFileExplorer(App.StoragePath);
} }
private void btnRestart_Click(object sender, EventArgs e) { private void btnRestart_Click(object? sender, EventArgs e) {
Program.Restart(); 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()); using DialogSettingsRestart dialog = new DialogSettingsRestart(Arguments.GetCurrentClean());
if (dialog.ShowDialog() == DialogResult.OK) { if (dialog.ShowDialog() == DialogResult.OK) {
@ -122,15 +122,15 @@ private void btnRestartArgs_Click(object sender, EventArgs e) {
#region Browser Settings #region Browser Settings
private void checkTouchAdjustment_CheckedChanged(object sender, EventArgs e) { private void checkTouchAdjustment_CheckedChanged(object? sender, EventArgs e) {
SysConfig.EnableTouchAdjustment = checkTouchAdjustment.Checked; SysConfig.EnableTouchAdjustment = checkTouchAdjustment.Checked;
} }
private void checkAutomaticallyDetectColorProfile_CheckedChanged(object sender, EventArgs e) { private void checkAutomaticallyDetectColorProfile_CheckedChanged(object? sender, EventArgs e) {
SysConfig.EnableColorProfileDetection = checkAutomaticallyDetectColorProfile.Checked; SysConfig.EnableColorProfileDetection = checkAutomaticallyDetectColorProfile.Checked;
} }
private void checkHardwareAcceleration_CheckedChanged(object sender, EventArgs e) { private void checkHardwareAcceleration_CheckedChanged(object? sender, EventArgs e) {
SysConfig.HardwareAcceleration = checkHardwareAcceleration.Checked; SysConfig.HardwareAcceleration = checkHardwareAcceleration.Checked;
} }
@ -138,13 +138,13 @@ private void checkHardwareAcceleration_CheckedChanged(object sender, EventArgs e
#region Browser Cache #region Browser Cache
private void btnClearCache_Click(object sender, EventArgs e) { private void btnClearCache_Click(object? sender, EventArgs e) {
btnClearCache.Enabled = false; btnClearCache.Enabled = false;
BrowserCache.SetClearOnExit(); BrowserCache.SetClearOnExit();
FormMessage.Information("Clear Cache", "Cache will be automatically cleared when TweetDuck exits.", FormMessage.OK); 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; numClearCacheThreshold.Enabled = checkClearCacheAuto.Checked;
} }
@ -152,11 +152,12 @@ private void checkClearCacheAuto_CheckedChanged(object sender, EventArgs e) {
#region Configuration #region Configuration
private void btnEditCefArgs_Click(object sender, EventArgs e) { private void btnEditCefArgs_Click(object? sender, EventArgs e) {
DialogSettingsCefArgs form = new DialogSettingsCefArgs(Config.CustomCefArgs); var parentForm = ParentForm ?? throw new InvalidOperationException("Dialog does not have a parent form!");
var form = new DialogSettingsCefArgs(Config.CustomCefArgs);
form.VisibleChanged += (sender2, args2) => { form.VisibleChanged += (sender2, args2) => {
form.MoveToCenter(ParentForm); form.MoveToCenter(parentForm);
}; };
form.FormClosed += (sender2, args2) => { form.FormClosed += (sender2, args2) => {
@ -169,15 +170,16 @@ private void btnEditCefArgs_Click(object sender, EventArgs e) {
form.Dispose(); form.Dispose();
}; };
form.Show(ParentForm); form.Show(parentForm);
NativeMethods.SetFormDisabled(ParentForm, true); NativeMethods.SetFormDisabled(parentForm, true);
} }
private void btnEditCSS_Click(object sender, EventArgs e) { private void btnEditCSS_Click(object? sender, EventArgs e) {
DialogSettingsCSS form = new DialogSettingsCSS(Config.CustomBrowserCSS, Config.CustomNotificationCSS, reinjectBrowserCSS, openDevTools); 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.VisibleChanged += (sender2, args2) => {
form.MoveToCenter(ParentForm); form.MoveToCenter(parentForm);
}; };
form.FormClosed += (sender2, args2) => { form.FormClosed += (sender2, args2) => {
@ -192,8 +194,8 @@ private void btnEditCSS_Click(object sender, EventArgs e) {
form.Dispose(); form.Dispose();
}; };
form.Show(ParentForm); form.Show(parentForm);
NativeMethods.SetFormDisabled(ParentForm, true); NativeMethods.SetFormDisabled(parentForm, true);
} }
private void RestoreParentForm() { private void RestoreParentForm() {
@ -206,7 +208,7 @@ private void RestoreParentForm() {
#region Proxy #region Proxy
private void checkUseSystemProxyForAllConnections_CheckedChanged(object sender, EventArgs e) { private void checkUseSystemProxyForAllConnections_CheckedChanged(object? sender, EventArgs e) {
SysConfig.UseSystemProxyForAllConnections = checkUseSystemProxyForAllConnections.Checked; SysConfig.UseSystemProxyForAllConnections = checkUseSystemProxyForAllConnections.Checked;
} }
@ -214,11 +216,11 @@ private void checkUseSystemProxyForAllConnections_CheckedChanged(object sender,
#region Development Tools #region Development Tools
private void checkDevToolsInContextMenuOnCheckedChanged(object sender, EventArgs e) { private void checkDevToolsInContextMenuOnCheckedChanged(object? sender, EventArgs e) {
Config.DevToolsInContextMenu = checkDevToolsInContextMenu.Checked; Config.DevToolsInContextMenu = checkDevToolsInContextMenu.Checked;
} }
private void checkDevToolsWindowOnTop_CheckedChanged(object sender, EventArgs e) { private void checkDevToolsWindowOnTop_CheckedChanged(object? sender, EventArgs e) {
Config.DevToolsWindowOnTop = checkDevToolsWindowOnTop.Checked; Config.DevToolsWindowOnTop = checkDevToolsWindowOnTop.Checked;
} }

View File

@ -13,7 +13,7 @@ public override void OnReady() {
#region Feedback #region Feedback
private void btnSendFeedback_Click(object sender, EventArgs e) { private void btnSendFeedback_Click(object? sender, EventArgs e) {
App.SystemHandler.OpenBrowser(Lib.IssueTrackerUrl + "/new"); App.SystemHandler.OpenBrowser(Lib.IssueTrackerUrl + "/new");
} }

View File

@ -171,27 +171,27 @@ public override void OnClosing() {
#region User Interface #region User Interface
private void checkExpandLinks_CheckedChanged(object sender, EventArgs e) { private void checkExpandLinks_CheckedChanged(object? sender, EventArgs e) {
Config.ExpandLinksOnHover = checkExpandLinks.Checked; Config.ExpandLinksOnHover = checkExpandLinks.Checked;
} }
private void checkFocusDmInput_CheckedChanged(object sender, EventArgs e) { private void checkFocusDmInput_CheckedChanged(object? sender, EventArgs e) {
Config.FocusDmInput = checkFocusDmInput.Checked; Config.FocusDmInput = checkFocusDmInput.Checked;
} }
private void checkOpenSearchInFirstColumn_CheckedChanged(object sender, EventArgs e) { private void checkOpenSearchInFirstColumn_CheckedChanged(object? sender, EventArgs e) {
Config.OpenSearchInFirstColumn = checkOpenSearchInFirstColumn.Checked; Config.OpenSearchInFirstColumn = checkOpenSearchInFirstColumn.Checked;
} }
private void checkKeepLikeFollowDialogsOpen_CheckedChanged(object sender, EventArgs e) { private void checkKeepLikeFollowDialogsOpen_CheckedChanged(object? sender, EventArgs e) {
Config.KeepLikeFollowDialogsOpen = checkKeepLikeFollowDialogsOpen.Checked; Config.KeepLikeFollowDialogsOpen = checkKeepLikeFollowDialogsOpen.Checked;
} }
private void checkSmoothScrolling_CheckedChanged(object sender, EventArgs e) { private void checkSmoothScrolling_CheckedChanged(object? sender, EventArgs e) {
Config.EnableSmoothScrolling = checkSmoothScrolling.Checked; Config.EnableSmoothScrolling = checkSmoothScrolling.Checked;
} }
private void trackBarZoom_ValueChanged(object sender, EventArgs e) { private void trackBarZoom_ValueChanged(object? sender, EventArgs e) {
if (trackBarZoom.AlignValueToTick()) { if (trackBarZoom.AlignValueToTick()) {
zoomUpdateTimer.Stop(); zoomUpdateTimer.Stop();
zoomUpdateTimer.Start(); 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; Config.ZoomLevel = trackBarZoom.Value;
zoomUpdateTimer.Stop(); zoomUpdateTimer.Stop();
} }
@ -208,16 +208,16 @@ private void zoomUpdateTimer_Tick(object sender, EventArgs e) {
#region Twitter #region Twitter
private void checkBestImageQuality_CheckedChanged(object sender, EventArgs e) { private void checkBestImageQuality_CheckedChanged(object? sender, EventArgs e) {
Config.BestImageQuality = checkBestImageQuality.Checked; Config.BestImageQuality = checkBestImageQuality.Checked;
} }
private void checkHideTweetsByNftUsers_CheckedChanged(object sender, EventArgs e) { private void checkHideTweetsByNftUsers_CheckedChanged(object? sender, EventArgs e) {
Config.HideTweetsByNftUsers = checkHideTweetsByNftUsers.Checked; Config.HideTweetsByNftUsers = checkHideTweetsByNftUsers.Checked;
BeginInvoke(reloadTweetDeck); BeginInvoke(reloadTweetDeck);
} }
private void checkAnimatedAvatars_CheckedChanged(object sender, EventArgs e) { private void checkAnimatedAvatars_CheckedChanged(object? sender, EventArgs e) {
Config.EnableAnimatedImages = checkAnimatedAvatars.Checked; Config.EnableAnimatedImages = checkAnimatedAvatars.Checked;
BrowserProcessHandler.UpdatePrefs().ContinueWith(task => reloadColumns()); BrowserProcessHandler.UpdatePrefs().ContinueWith(task => reloadColumns());
} }
@ -226,18 +226,18 @@ private void checkAnimatedAvatars_CheckedChanged(object sender, EventArgs e) {
#region Updates #region Updates
private void checkUpdateNotifications_CheckedChanged(object sender, EventArgs e) { private void checkUpdateNotifications_CheckedChanged(object? sender, EventArgs e) {
Config.EnableUpdateCheck = checkUpdateNotifications.Checked; Config.EnableUpdateCheck = checkUpdateNotifications.Checked;
} }
private void btnCheckUpdates_Click(object sender, EventArgs e) { private void btnCheckUpdates_Click(object? sender, EventArgs e) {
Config.DismissedUpdate = null; Config.DismissedUpdate = null;
btnCheckUpdates.Enabled = false; btnCheckUpdates.Enabled = false;
updateCheckEventId = updates.Check(true); updateCheckEventId = updates.Check(true);
} }
private void updates_CheckFinished(object sender, UpdateCheckEventArgs e) { private void updates_CheckFinished(object? sender, UpdateCheckEventArgs e) {
if (e.EventId == updateCheckEventId) { if (e.EventId == updateCheckEventId) {
btnCheckUpdates.Enabled = true; btnCheckUpdates.Enabled = true;
@ -264,7 +264,7 @@ private void UpdateBrowserPathSelection() {
comboBoxCustomBrowser.SelectedIndex = browserListIndexDefault; comboBoxCustomBrowser.SelectedIndex = browserListIndexDefault;
} }
else { 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) { if (browserInfo == null || Config.BrowserPathArgs != null) {
comboBoxCustomBrowser.SelectedIndex = browserListIndexCustom; comboBoxCustomBrowser.SelectedIndex = browserListIndexCustom;
@ -277,7 +277,7 @@ private void UpdateBrowserPathSelection() {
UpdateBrowserChangeButton(); UpdateBrowserChangeButton();
} }
private void comboBoxCustomBrowser_SelectedIndexChanged(object sender, EventArgs e) { private void comboBoxCustomBrowser_SelectedIndexChanged(object? sender, EventArgs e) {
if (comboBoxCustomBrowser.SelectedIndex == browserListIndexCustom) { if (comboBoxCustomBrowser.SelectedIndex == browserListIndexCustom) {
btnCustomBrowserChange_Click(sender, e); 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...") { using (DialogSettingsExternalProgram dialog = new DialogSettingsExternalProgram("External Browser", "Open Links With...") {
Path = Config.BrowserPath, Path = Config.BrowserPath,
Args = Config.BrowserPathArgs Args = Config.BrowserPathArgs
@ -319,7 +319,7 @@ private void UpdateVideoPlayerPathSelection() {
UpdateVideoPlayerChangeButton(); UpdateVideoPlayerChangeButton();
} }
private void comboBoxCustomVideoPlayer_SelectedIndexChanged(object sender, EventArgs e) { private void comboBoxCustomVideoPlayer_SelectedIndexChanged(object? sender, EventArgs e) {
if (comboBoxCustomVideoPlayer.SelectedIndex == videoPlayerListIndexCustom) { if (comboBoxCustomVideoPlayer.SelectedIndex == videoPlayerListIndexCustom) {
btnCustomVideoPlayerChange_Click(sender, e); 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...") { using (DialogSettingsExternalProgram dialog = new DialogSettingsExternalProgram("External Video Player", "Play Videos With...") {
Path = Config.VideoPlayerPath, Path = Config.VideoPlayerPath,
Args = Config.VideoPlayerPathArgs Args = Config.VideoPlayerPathArgs
@ -346,7 +346,7 @@ private void btnCustomVideoPlayerChange_Click(object sender, EventArgs e) {
comboBoxCustomVideoPlayer.SelectedIndexChanged += comboBoxCustomVideoPlayer_SelectedIndexChanged; comboBoxCustomVideoPlayer.SelectedIndexChanged += comboBoxCustomVideoPlayer_SelectedIndexChanged;
} }
private void comboBoxSearchEngine_SelectedIndexChanged(object sender, EventArgs e) { private void comboBoxSearchEngine_SelectedIndexChanged(object? sender, EventArgs e) {
if (comboBoxSearchEngine.SelectedIndex == searchEngineIndexCustom) { if (comboBoxSearchEngine.SelectedIndex == searchEngineIndexCustom) {
using (DialogSettingsSearchEngine dialog = new DialogSettingsSearchEngine()) { using (DialogSettingsSearchEngine dialog = new DialogSettingsSearchEngine()) {
if (dialog.ShowDialog() == DialogResult.OK) { if (dialog.ShowDialog() == DialogResult.OK) {
@ -368,7 +368,7 @@ private void UpdateSearchEngineSelection() {
comboBoxSearchEngine.SelectedIndex = searchEngineIndexDefault; comboBoxSearchEngine.SelectedIndex = searchEngineIndexDefault;
} }
else { 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) { if (engineInfo == null) {
comboBoxSearchEngine.SelectedIndex = searchEngineIndexCustom; comboBoxSearchEngine.SelectedIndex = searchEngineIndexCustom;
@ -389,7 +389,7 @@ public SearchEngine(string name, string url) {
} }
public override int GetHashCode() => Name.GetHashCode(); 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; public override string ToString() => Name;
} }
@ -397,20 +397,20 @@ public SearchEngine(string name, string url) {
#region Locales #region Locales
private void checkSpellCheck_CheckedChanged(object sender, EventArgs e) { private void checkSpellCheck_CheckedChanged(object? sender, EventArgs e) {
Config.EnableSpellCheck = checkSpellCheck.Checked; Config.EnableSpellCheck = checkSpellCheck.Checked;
BrowserProcessHandler.UpdatePrefs(); 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"; 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"; 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; 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 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; public override string ToString() => Name;
} }

View File

@ -143,7 +143,7 @@ public override void OnReady() {
trackBarScrollSpeed.ValueChanged += trackBarScrollSpeed_ValueChanged; trackBarScrollSpeed.ValueChanged += trackBarScrollSpeed_ValueChanged;
} }
private void TabSettingsNotifications_ParentChanged(object sender, EventArgs e) { private void TabSettingsNotifications_ParentChanged(object? sender, EventArgs e) {
if (Parent == null) { if (Parent == null) {
notification.HideNotification(); 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) { if (radioLocCustom.Checked && notification.Location != ControlExtensions.InvisibleLocation) {
Config.CustomNotificationPosition = notification.Location; Config.CustomNotificationPosition = notification.Location;
} }
} }
private void notification_ResizeEnd(object sender, EventArgs e) { private void notification_ResizeEnd(object? sender, EventArgs e) {
if (radioSizeCustom.Checked) { if (radioSizeCustom.Checked) {
Config.CustomNotificationSize = notification.BrowserSize; Config.CustomNotificationSize = notification.BrowserSize;
notification.ShowExampleNotification(false); notification.ShowExampleNotification(false);
@ -167,28 +167,28 @@ private void notification_ResizeEnd(object sender, EventArgs e) {
#region General #region General
private void checkColumnName_CheckedChanged(object sender, EventArgs e) { private void checkColumnName_CheckedChanged(object? sender, EventArgs e) {
Config.DisplayNotificationColumn = checkColumnName.Checked; Config.DisplayNotificationColumn = checkColumnName.Checked;
notification.ShowExampleNotification(false); notification.ShowExampleNotification(false);
} }
private void checkMediaPreviews_CheckedChanged(object sender, EventArgs e) { private void checkMediaPreviews_CheckedChanged(object? sender, EventArgs e) {
Config.NotificationMediaPreviews = checkMediaPreviews.Checked; Config.NotificationMediaPreviews = checkMediaPreviews.Checked;
} }
private void checkSkipOnLinkClick_CheckedChanged(object sender, EventArgs e) { private void checkSkipOnLinkClick_CheckedChanged(object? sender, EventArgs e) {
Config.NotificationSkipOnLinkClick = checkSkipOnLinkClick.Checked; Config.NotificationSkipOnLinkClick = checkSkipOnLinkClick.Checked;
} }
private void checkNonIntrusive_CheckedChanged(object sender, EventArgs e) { private void checkNonIntrusive_CheckedChanged(object? sender, EventArgs e) {
Config.NotificationNonIntrusiveMode = checkNonIntrusive.Checked; 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]; Config.NotificationIdlePauseSeconds = IdlePauseSeconds[comboBoxIdlePause.SelectedIndex];
} }
private void trackBarOpacity_ValueChanged(object sender, EventArgs e) { private void trackBarOpacity_ValueChanged(object? sender, EventArgs e) {
if (trackBarOpacity.AlignValueToTick()) { if (trackBarOpacity.AlignValueToTick()) {
Config.NotificationWindowOpacity = trackBarOpacity.Value; Config.NotificationWindowOpacity = trackBarOpacity.Value;
labelOpacityValue.Text = Config.NotificationWindowOpacity + "%"; labelOpacityValue.Text = Config.NotificationWindowOpacity + "%";
@ -199,18 +199,18 @@ private void trackBarOpacity_ValueChanged(object sender, EventArgs e) {
#region Timer #region Timer
private void checkNotificationTimer_CheckedChanged(object sender, EventArgs e) { private void checkNotificationTimer_CheckedChanged(object? sender, EventArgs e) {
Config.DisplayNotificationTimer = checkNotificationTimer.Checked; Config.DisplayNotificationTimer = checkNotificationTimer.Checked;
checkTimerCountDown.Enabled = checkNotificationTimer.Checked; checkTimerCountDown.Enabled = checkNotificationTimer.Checked;
notification.ShowExampleNotification(true); notification.ShowExampleNotification(true);
} }
private void checkTimerCountDown_CheckedChanged(object sender, EventArgs e) { private void checkTimerCountDown_CheckedChanged(object? sender, EventArgs e) {
Config.NotificationTimerCountDown = checkTimerCountDown.Checked; Config.NotificationTimerCountDown = checkTimerCountDown.Checked;
notification.ShowExampleNotification(true); notification.ShowExampleNotification(true);
} }
private void trackBarDuration_ValueChanged(object sender, EventArgs e) { private void trackBarDuration_ValueChanged(object? sender, EventArgs e) {
durationUpdateTimer.Stop(); durationUpdateTimer.Stop();
durationUpdateTimer.Start(); durationUpdateTimer.Start();
@ -218,19 +218,19 @@ private void trackBarDuration_ValueChanged(object sender, EventArgs e) {
labelDurationValue.Text = Config.NotificationDurationValue + " ms/c"; 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; trackBarDuration.Value = 15;
} }
private void btnDurationMedium_Click(object sender, EventArgs e) { private void btnDurationMedium_Click(object? sender, EventArgs e) {
trackBarDuration.Value = 25; trackBarDuration.Value = 25;
} }
private void btnDurationLong_Click(object sender, EventArgs e) { private void btnDurationLong_Click(object? sender, EventArgs e) {
trackBarDuration.Value = 35; trackBarDuration.Value = 35;
} }
private void durationUpdateTimer_Tick(object sender, EventArgs e) { private void durationUpdateTimer_Tick(object? sender, EventArgs e) {
notification.ShowExampleNotification(true); notification.ShowExampleNotification(true);
durationUpdateTimer.Stop(); durationUpdateTimer.Stop();
} }
@ -239,7 +239,7 @@ private void durationUpdateTimer_Tick(object sender, EventArgs e) {
#region Location #region Location
private void radioLoc_CheckedChanged(object sender, EventArgs e) { private void radioLoc_CheckedChanged(object? sender, EventArgs e) {
if (radioLocTL.Checked) { if (radioLocTL.Checked) {
Config.NotificationPosition = DesktopNotification.Position.TopLeft; Config.NotificationPosition = DesktopNotification.Position.TopLeft;
} }
@ -257,7 +257,7 @@ private void radioLoc_CheckedChanged(object sender, EventArgs e) {
notification.ShowExampleNotification(false); notification.ShowExampleNotification(false);
} }
private void radioLocCustom_Click(object sender, EventArgs e) { private void radioLocCustom_Click(object? sender, EventArgs e) {
if (!Config.IsCustomNotificationPositionSet) { if (!Config.IsCustomNotificationPositionSet) {
Config.CustomNotificationPosition = notification.Location; 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; Config.NotificationDisplay = comboBoxDisplay.SelectedIndex;
notification.ShowExampleNotification(false); notification.ShowExampleNotification(false);
} }
private void trackBarEdgeDistance_ValueChanged(object sender, EventArgs e) { private void trackBarEdgeDistance_ValueChanged(object? sender, EventArgs e) {
labelEdgeDistanceValue.Text = trackBarEdgeDistance.Value + " px"; labelEdgeDistanceValue.Text = trackBarEdgeDistance.Value + " px";
Config.NotificationEdgeDistance = trackBarEdgeDistance.Value; Config.NotificationEdgeDistance = trackBarEdgeDistance.Value;
notification.ShowExampleNotification(false); notification.ShowExampleNotification(false);
@ -293,7 +293,7 @@ private void trackBarEdgeDistance_ValueChanged(object sender, EventArgs e) {
#region Size #region Size
private void radioSize_CheckedChanged(object sender, EventArgs e) { private void radioSize_CheckedChanged(object? sender, EventArgs e) {
if (radioSizeAuto.Checked) { if (radioSizeAuto.Checked) {
Config.NotificationSize = DesktopNotification.Size.Auto; Config.NotificationSize = DesktopNotification.Size.Auto;
} }
@ -301,7 +301,7 @@ private void radioSize_CheckedChanged(object sender, EventArgs e) {
notification.ShowExampleNotification(false); notification.ShowExampleNotification(false);
} }
private void radioSizeCustom_Click(object sender, EventArgs e) { private void radioSizeCustom_Click(object? sender, EventArgs e) {
if (!Config.IsCustomNotificationSizeSet) { if (!Config.IsCustomNotificationSizeSet) {
Config.CustomNotificationSize = notification.BrowserSize; Config.CustomNotificationSize = notification.BrowserSize;
} }
@ -310,7 +310,7 @@ private void radioSizeCustom_Click(object sender, EventArgs e) {
notification.ShowExampleNotification(false); notification.ShowExampleNotification(false);
} }
private void trackBarScrollSpeed_ValueChanged(object sender, EventArgs e) { private void trackBarScrollSpeed_ValueChanged(object? sender, EventArgs e) {
if (trackBarScrollSpeed.AlignValueToTick()) { if (trackBarScrollSpeed.AlignValueToTick()) {
labelScrollSpeedValue.Text = trackBarScrollSpeed.Value + "%"; labelScrollSpeedValue.Text = trackBarScrollSpeed.Value + "%";
Config.NotificationScrollSpeed = trackBarScrollSpeed.Value; Config.NotificationScrollSpeed = trackBarScrollSpeed.Value;

View File

@ -51,11 +51,11 @@ private bool RefreshCanPlay() {
return canPlay; return canPlay;
} }
private void tbCustomSound_TextChanged(object sender, EventArgs e) { private void tbCustomSound_TextChanged(object? sender, EventArgs e) {
RefreshCanPlay(); RefreshCanPlay();
} }
private void btnPlaySound_Click(object sender, EventArgs e) { private void btnPlaySound_Click(object? sender, EventArgs e) {
if (RefreshCanPlay()) { if (RefreshCanPlay()) {
Config.NotificationSoundPath = tbCustomSound.Text; Config.NotificationSoundPath = tbCustomSound.Text;
Config.NotificationSoundVolume = trackBarVolume.Value; 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 { using OpenFileDialog dialog = new OpenFileDialog {
AutoUpgradeEnabled = true, AutoUpgradeEnabled = true,
DereferenceLinks = 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; tbCustomSound.Text = string.Empty;
} }
private void trackBarVolume_ValueChanged(object sender, EventArgs e) { private void trackBarVolume_ValueChanged(object? sender, EventArgs e) {
volumeUpdateTimer.Stop(); volumeUpdateTimer.Stop();
volumeUpdateTimer.Start(); volumeUpdateTimer.Start();
labelVolumeValue.Text = trackBarVolume.Value + "%"; labelVolumeValue.Text = trackBarVolume.Value + "%";
} }
private void volumeUpdateTimer_Tick(object sender, EventArgs e) { private void volumeUpdateTimer_Tick(object? sender, EventArgs e) {
Config.NotificationSoundVolume = trackBarVolume.Value; Config.NotificationSoundVolume = trackBarVolume.Value;
volumeUpdateTimer.Stop(); volumeUpdateTimer.Stop();
} }

View File

@ -29,12 +29,12 @@ public override void OnReady() {
#region System Tray #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; Config.TrayBehavior = (TrayIcon.Behavior) comboBoxTrayType.SelectedIndex;
checkTrayHighlight.Enabled = Config.TrayBehavior.ShouldDisplayIcon(); 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; Config.EnableTrayHighlight = checkTrayHighlight.Checked;
} }

View File

@ -11,7 +11,7 @@ static class BrowserCache {
private static string CacheFolder => CefUtils.GetCacheFolder(App.StoragePath); private static string CacheFolder => CefUtils.GetCacheFolder(App.StoragePath);
private static bool clearOnExit; private static bool clearOnExit;
private static Timer autoClearTimer; private static Timer? autoClearTimer;
private static long CalculateCacheSize() { private static long CalculateCacheSize() {
return new DirectoryInfo(CacheFolder).EnumerateFiles().Select(file => { return new DirectoryInfo(CacheFolder).EnumerateFiles().Select(file => {

View File

@ -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(); return OpenForms.OfType<T>().FirstOrDefault();
} }
public static bool TryBringToFront<T>() where T : Form { public static bool TryBringToFront<T>() where T : Form {
T form = TryFind<T>(); T? form = TryFind<T>();
if (form != null) { if (form != null) {
form.BringToFront(); form.BringToFront();

View File

@ -61,7 +61,7 @@ public bool Export(Items items) {
} }
if (items.HasFlag(Items.Session)) { if (items.HasFlag(Items.Session)) {
string authToken = ReadAuthCookie(); string? authToken = ReadAuthCookie();
if (authToken != null) { if (authToken != null) {
stream.WriteString("cookie.auth", authToken); stream.WriteString("cookie.auth", authToken);
@ -84,9 +84,8 @@ public Items FindImportItems() {
try { try {
using CombinedFileStream stream = new CombinedFileStream(new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.None)); 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) { switch (key) {
case "config": case "config":
items |= Items.UserConfig; items |= Items.UserConfig;
@ -121,9 +120,7 @@ public bool Import(Items items) {
bool oldCookies = false; bool oldCookies = false;
using (CombinedFileStream stream = new CombinedFileStream(new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.None))) { using (CombinedFileStream stream = new CombinedFileStream(new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.None))) {
CombinedFileStream.Entry entry; while (stream.ReadFile() is {} entry) {
while ((entry = stream.ReadFile()) != null) {
switch (entry.KeyName) { switch (entry.KeyName) {
case "config": case "config":
if (items.HasFlag(Items.UserConfig)) { if (items.HasFlag(Items.UserConfig)) {
@ -223,11 +220,11 @@ private sealed class PathInfo {
public PathInfo(string fullPath, int rootLength) { public PathInfo(string fullPath, int rootLength) {
this.Full = fullPath; 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(); using var cookieManager = Cef.GetGlobalCookieManager();
foreach (var cookie in cookieManager.VisitUrlCookiesAsync(AuthCookieUrl, true).Result) { foreach (var cookie in cookieManager.VisitUrlCookiesAsync(AuthCookieUrl, true).Result) {

View File

@ -16,11 +16,11 @@ sealed class VideoPlayer : IDisposable {
public bool Running => currentInstance is { Running: true }; public bool Running => currentInstance is { Running: true };
public event EventHandler ProcessExited; public event EventHandler? ProcessExited;
private readonly FormBrowser owner; private readonly FormBrowser owner;
private Instance currentInstance; private Instance? currentInstance;
private bool isClosing; private bool isClosing;
public VideoPlayer(FormBrowser owner) { public VideoPlayer(FormBrowser owner) {
@ -44,7 +44,7 @@ public void Launch(string videoUrl, string tweetUrl, string username) {
RedirectStandardOutput = true RedirectStandardOutput = true
}; };
Process process; Process? process;
if ((process = Process.Start(startInfo)) != null) { if ((process = Process.Start(startInfo)) != null) {
currentInstance = new Instance(process, pipe, videoUrl, tweetUrl, username); currentInstance = new Instance(process, pipe, videoUrl, tweetUrl, username);
@ -69,7 +69,7 @@ public void SendKeyEvent(Keys key) {
currentInstance?.Pipe.Write("key", ((int) key).ToString()); 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(() => { owner.InvokeSafe(() => {
switch (e.Key) { switch (e.Key) {
case "vol": 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) { if (currentInstance != null) {
currentInstance.Process.Exited -= process_Exited; 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)) { if (!string.IsNullOrEmpty(e.Data)) {
App.Logger.Debug("[VideoPlayer] " + 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) { if (currentInstance == null) {
return; return;
} }

View File

@ -5,18 +5,18 @@
namespace TweetDuck.Management { namespace TweetDuck.Management {
static class WindowsSessionManager { static class WindowsSessionManager {
public static bool IsLocked { get; private set; } = false; public static bool IsLocked { get; private set; } = false;
public static event EventHandler LockStateChanged; public static event EventHandler? LockStateChanged;
public static void Register() { public static void Register() {
Win.Application.ApplicationExit += OnApplicationExit; Win.Application.ApplicationExit += OnApplicationExit;
SystemEvents.SessionSwitch += OnSessionSwitch; SystemEvents.SessionSwitch += OnSessionSwitch;
} }
private static void OnApplicationExit(object sender, EventArgs e) { private static void OnApplicationExit(object? sender, EventArgs e) {
SystemEvents.SessionSwitch -= OnSessionSwitch; SystemEvents.SessionSwitch -= OnSessionSwitch;
} }
private static void OnSessionSwitch(object sender, SessionSwitchEventArgs e) { private static void OnSessionSwitch(object? sender, SessionSwitchEventArgs e) {
var reason = e.Reason; var reason = e.Reason;
if (reason == SessionSwitchReason.SessionLock) { if (reason == SessionSwitchReason.SessionLock) {
SetLocked(true); SetLocked(true);

View File

@ -16,9 +16,11 @@ sealed partial class PluginControl : UserControl {
private int nextHeight; private int nextHeight;
#pragma warning disable CS8618
private PluginControl() { private PluginControl() {
InitializeComponent(); InitializeComponent();
} }
#pragma warning restore CS8618
public PluginControl(PluginManager pluginManager, Plugin plugin) : this() { public PluginControl(PluginManager pluginManager, Plugin plugin) : this() {
this.pluginManager = pluginManager; this.pluginManager = pluginManager;
@ -49,13 +51,13 @@ public PluginControl(PluginManager pluginManager, Plugin plugin) : this() {
panelDescription_Resize(panelDescription, EventArgs.Empty); panelDescription_Resize(panelDescription, EventArgs.Empty);
} }
private void timerLayout_Tick(object sender, EventArgs e) { private void timerLayout_Tick(object? sender, EventArgs e) {
timerLayout.Stop(); timerLayout.Stop();
Height = nextHeight; Height = nextHeight;
ResumeLayout(); ResumeLayout();
} }
private void panelDescription_Resize(object sender, EventArgs e) { private void panelDescription_Resize(object? sender, EventArgs e) {
SuspendLayout(); SuspendLayout();
int maxWidth = panelDescription.Width - (panelDescription.VerticalScroll.Visible ? SystemInformation.VerticalScrollBarWidth : 0); 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) { if (labelWebsite.Text.Length > 0) {
App.SystemHandler.OpenBrowser(labelWebsite.Text); App.SystemHandler.OpenBrowser(labelWebsite.Text);
} }
} }
private void btnConfigure_Click(object sender, EventArgs e) { private void btnConfigure_Click(object? sender, EventArgs e) {
pluginManager.ConfigurePlugin(plugin); pluginManager.ConfigurePlugin(plugin);
ParentForm?.Close(); 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.SetEnabled(plugin, !pluginManager.Config.IsEnabled(plugin));
pluginManager.Config.Save(); pluginManager.Config.Save();
UpdatePluginState(); UpdatePluginState();

View File

@ -36,11 +36,11 @@ static class Program {
public static string ExecutablePath => Win.Application.ExecutablePath; public static string ExecutablePath => Win.Application.ExecutablePath;
private static Reporter errorReporter; private static Reporter? errorReporter;
private static LockManager lockManager; private static LockManager lockManager = null!;
private static bool hasCleanedUp; 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() { internal static void SetupWinForms() {
Win.Application.EnableVisualStyles(); Win.Application.EnableVisualStyles();
@ -85,8 +85,8 @@ private static void Main() {
private sealed class Setup : IAppSetup { private sealed class Setup : IAppSetup {
public bool IsPortable => File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "makeportable")); public bool IsPortable => File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "makeportable"));
public bool IsDebugLogging => Arguments.HasFlag(Arguments.ArgLogging); public bool IsDebugLogging => Arguments.HasFlag(Arguments.ArgLogging);
public string CustomDataFolder => Arguments.GetValue(Arguments.ArgDataFolder); public string? CustomDataFolder => Arguments.GetValue(Arguments.ArgDataFolder);
public string ResourceRewriteRules => Arguments.GetValue(Arguments.ArgFreeze); public string? ResourceRewriteRules => Arguments.GetValue(Arguments.ArgFreeze);
public ConfigManager CreateConfigManager(string storagePath) { public ConfigManager CreateConfigManager(string storagePath) {
return new ConfigManager<UserConfig, SystemConfig>(storagePath, Config); 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) { if (e.ExceptionObject is Exception ex) {
const string title = "TweetDuck Has Failed :("; const string title = "TweetDuck Has Failed :(";
string message = "An unhandled exception has occurred: " + ex.Message; string message = "An unhandled exception has occurred: " + ex.Message;
@ -173,7 +173,7 @@ public static void Restart() {
} }
public static void RestartWithArgs(CommandLineArgs args) { public static void RestartWithArgs(CommandLineArgs args) {
FormBrowser browserForm = FormManager.TryFind<FormBrowser>(); FormBrowser? browserForm = FormManager.TryFind<FormBrowser>();
if (browserForm != null) { if (browserForm != null) {
browserForm.ForceClose(); browserForm.ForceClose();

View File

@ -9,7 +9,7 @@
namespace TweetDuck { namespace TweetDuck {
sealed class Reporter : IAppErrorHandler { sealed class Reporter : IAppErrorHandler {
private static void Exit(string message, Exception ex = null) { private static void Exit(string message, Exception? ex = null) {
try { try {
Process.GetCurrentProcess().Kill(); Process.GetCurrentProcess().Kill();
} catch { } catch {

View File

@ -16,11 +16,11 @@ public FormUpdateDownload(UpdateInfo info) {
timerDownloadCheck.Start(); timerDownloadCheck.Start();
} }
private void btnCancel_Click(object sender, EventArgs e) { private void btnCancel_Click(object? sender, EventArgs e) {
Close(); Close();
} }
private void timerDownloadCheck_Tick(object sender, EventArgs e) { private void timerDownloadCheck_Tick(object? sender, EventArgs e) {
if (updateInfo.DownloadStatus.IsFinished(false)) { if (updateInfo.DownloadStatus.IsFinished(false)) {
timerDownloadCheck.Stop(); timerDownloadCheck.Stop();
DialogResult = DialogResult.OK; DialogResult = DialogResult.OK;

View File

@ -33,7 +33,7 @@ Task<UpdateInfo> IUpdateCheckClient.Check() {
result.SetCanceled(); result.SetCanceled();
} }
else if (task.IsFaulted) { else if (task.IsFaulted) {
result.SetException(ExpandWebException(task.Exception.InnerException)); result.SetException(ExpandWebException(task.Exception!.InnerException));
} }
else { else {
try { try {
@ -65,7 +65,7 @@ static string AssetDownloadUrl(JsonElement obj) {
return new UpdateInfo(versionTag, releaseNotes, downloadUrl, installerFolder); 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 } ) { if (e is WebException { Response: HttpWebResponse response } ) {
try { try {
using var stream = response.GetResponseStream(); using var stream = response.GetResponseStream();
@ -76,7 +76,7 @@ private static Exception ExpandWebException(Exception e) {
} }
} }
return e; return e!;
} }
} }
} }

View File

@ -38,7 +38,7 @@ public static void SetupCefArgs(IDictionary<string, string> args) {
args["disable-plugins-discovery"] = "1"; args["disable-plugins-discovery"] = "1";
args["enable-system-flash"] = "0"; 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; args["js-flags"] = "--expose-gc " + jsFlags;
} }
else { else {
@ -63,7 +63,7 @@ static void SetZoomLevel(IBrowserHost host, int percentage) {
host.SetZoomLevel(Math.Log(percentage / 100.0, 1.2)); 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); SetZoomLevel(browser.GetBrowserHost(), Config.ZoomLevel);
} }

View File

@ -62,7 +62,7 @@ private struct MSLLHOOKSTRUCT {
[DllImport("user32.dll")] [DllImport("user32.dll")]
private static extern bool PostMessage(IntPtr hWnd, uint msg, UIntPtr wParam, IntPtr lParam); 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); public static extern uint RegisterWindowMessage(string messageName);
[DllImport("user32.dll")] [DllImport("user32.dll")]

View File

@ -43,28 +43,28 @@ public static void TryDeleteFolderWhenAble(string path, int timeout) {
public static IEnumerable<Browser> FindInstalledBrowsers() { public static IEnumerable<Browser> FindInstalledBrowsers() {
static IEnumerable<Browser> ReadBrowsersFromKey(RegistryHive hive) { static IEnumerable<Browser> ReadBrowsersFromKey(RegistryHive hive) {
using RegistryKey root = RegistryKey.OpenBaseKey(hive, RegistryView.Default); 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) { if (browserList == null) {
yield break; yield break;
} }
foreach (string sub in browserList.GetSubKeyNames()) { foreach (string sub in browserList.GetSubKeyNames()) {
using RegistryKey browserKey = browserList.OpenSubKey(sub, false); using RegistryKey? browserKey = browserList.OpenSubKey(sub, false);
using RegistryKey shellKey = browserKey?.OpenSubKey(@"shell\open\command"); using RegistryKey? shellKey = browserKey?.OpenSubKey(@"shell\open\command");
if (shellKey == null) { if (browserKey == null || shellKey == null) {
continue; continue;
} }
string browserName = browserKey.GetValue(null) as string; string? browserName = browserKey.GetValue(null) as string;
string browserPath = shellKey.GetValue(null) as string; string? browserPath = shellKey.GetValue(null) as string;
if (string.IsNullOrEmpty(browserName) || string.IsNullOrEmpty(browserPath)) { if (string.IsNullOrEmpty(browserName) || string.IsNullOrEmpty(browserPath)) {
continue; continue;
} }
if (browserPath[0] == '"' && browserPath[browserPath.Length - 1] == '"') { if (browserPath[0] == '"' && browserPath[^1] == '"') {
browserPath = browserPath.Substring(1, browserPath.Length - 2); 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 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; public override string ToString() => Name;
} }
} }

View File

@ -12,7 +12,7 @@ public bool IsAborted(CefErrorCode errorCode) {
return errorCode == CefErrorCode.Aborted; return errorCode == CefErrorCode.Aborted;
} }
public string GetName(CefErrorCode errorCode) { public string? GetName(CefErrorCode errorCode) {
return Enum.GetName(typeof(CefErrorCode), errorCode); return Enum.GetName(typeof(CefErrorCode), errorCode);
} }
} }

View File

@ -7,7 +7,7 @@ sealed class CefJsDialogCallbackAdapter : IJsDialogCallbackAdapter<IJsDialogCall
private CefJsDialogCallbackAdapter() {} 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) { if (userInput == null) {
callback.Continue(success); callback.Continue(success);
} }

View File

@ -24,7 +24,7 @@ public void SetHeader(IResponse response, string header, string value) {
response.SetHeaderByName(header, value, overwrite: true); response.SetHeaderByName(header, value, overwrite: true);
} }
public string GetHeader(IResponse response, string header) { public string? GetHeader(IResponse response, string header) {
return response.Headers[header]; return response.Headers[header];
} }
} }

View File

@ -10,7 +10,7 @@
namespace TweetImpl.CefSharp.Component { namespace TweetImpl.CefSharp.Component {
public abstract class BrowserComponentBase : BrowserComponent<IFrame, IRequest> { 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); 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); browser.JavascriptObjectRepository.Register(name, bridge);
} }
private void OnLoadingStateChanged(object sender, LoadingStateChangedEventArgs e) { private void OnLoadingStateChanged(object? sender, LoadingStateChangedEventArgs e) {
base.OnLoadingStateChanged(e.IsLoading); 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); 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); 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); base.OnFrameLoadEnd(e.Url, e.Frame);
} }
} }

View File

@ -12,25 +12,27 @@ public sealed class CefByteArrayResourceHandler : IResourceHandler {
dataOut.Write(dataIn, position, length); dataOut.Write(dataIn, position, length);
}; };
private ByteArrayResourceHandlerLogic<IResponse> logic; private static ByteArrayResourceHandlerLogic<IResponse> CreateLogic(ByteArrayResource resource) {
return new ByteArrayResourceHandlerLogic<IResponse>(resource, CefResponseAdapter.Instance);
public CefByteArrayResourceHandler() {
SetResource(new ByteArrayResource(Array.Empty<byte>()));
} }
private ByteArrayResourceHandlerLogic<IResponse> logic;
public CefByteArrayResourceHandler() : this(new ByteArrayResource(Array.Empty<byte>())) {}
internal CefByteArrayResourceHandler(ByteArrayResource resource) { internal CefByteArrayResourceHandler(ByteArrayResource resource) {
SetResource(resource); this.logic = CreateLogic(resource);
} }
public void SetResource(ByteArrayResource 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) { bool IResourceHandler.Open(IRequest request, out bool handleRequest, ICallback callback) {
return logic.Open(out handleRequest); 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); logic.GetResponseHeaders(response, out responseLength, out redirectUrl);
} }

View File

@ -7,7 +7,7 @@ namespace TweetImpl.CefSharp.Handlers {
public abstract class CefContextMenuHandler : IContextMenuHandler { public abstract class CefContextMenuHandler : IContextMenuHandler {
private readonly ContextMenuLogic<IMenuModel> logic; 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); this.logic = new ContextMenuLogic<IMenuModel>(handler, CefMenuModelAdapter.Instance);
} }

View File

@ -12,7 +12,7 @@ public CefLifeSpanHandler(IPopupHandler popupHandler) {
this.Logic = new LifeSpanHandlerLogic(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; newBrowser = null;
return Logic.OnBeforePopup(targetUrl, ConvertTargetDisposition(targetDisposition)); return Logic.OnBeforePopup(targetUrl, ConvertTargetDisposition(targetDisposition));
} }

View File

@ -9,7 +9,7 @@ namespace TweetImpl.CefSharp.Handlers {
sealed class CefResourceRequestHandler : ResourceRequestHandler { sealed class CefResourceRequestHandler : ResourceRequestHandler {
private readonly ResourceRequestHandlerLogic<IRequest, IResponse, IResourceHandler> logic; 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); 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; 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); 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)); return CefResponseFilter.Create(logic.GetResourceResponseFilter(request, response));
} }

View File

@ -11,7 +11,7 @@ sealed class CefResourceRequestHandlerFactory : IResourceRequestHandlerFactory {
private readonly ResourceRequestHandlerFactoryLogic<CefResourceRequestHandler, IResourceHandler, IRequest> logic; 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); this.logic = new ResourceRequestHandlerFactoryLogic<CefResourceRequestHandler, IResourceHandler, IRequest>(CefRequestAdapter.Instance, new CefResourceRequestHandler(registry, resourceRequestHandler), registry);
} }

Some files were not shown because too many files have changed in this diff Show More