1
0
mirror of https://github.com/chylex/TweetDuck.git synced 2025-05-25 17:34:06 +02:00

Fix IDE warnings (dispose, lang features) & nullability settings

This commit is contained in:
chylex 2020-04-24 23:14:22 +02:00
parent fc89744238
commit 1091b6d232
38 changed files with 230 additions and 221 deletions

View File

@ -38,9 +38,7 @@ public void OpenProfileImport(){
} }
public void OnIntroductionClosed(bool showGuide, bool allowDataCollection){ public void OnIntroductionClosed(bool showGuide, bool allowDataCollection){
form.InvokeAsyncSafe(() => { form.InvokeAsyncSafe(() => form.OnIntroductionClosed(showGuide, allowDataCollection));
form.OnIntroductionClosed(showGuide, allowDataCollection);
});
} }
public void LoadNotificationLayout(string fontSize, string headLayout){ public void LoadNotificationLayout(string fontSize, string headLayout){

View File

@ -5,17 +5,6 @@ sealed partial class FormBrowser {
/// </summary> /// </summary>
private System.ComponentModel.IContainer components = null; private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing) {
if (disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code #region Windows Form Designer generated code
/// <summary> /// <summary>

View File

@ -90,14 +90,6 @@ public FormBrowser(){
Disposed += (sender, args) => { Disposed += (sender, args) => {
Config.MuteToggled -= Config_MuteToggled; Config.MuteToggled -= Config_MuteToggled;
Config.TrayBehaviorChanged -= Config_TrayBehaviorChanged; Config.TrayBehaviorChanged -= Config_TrayBehaviorChanged;
browser.Dispose();
updates.Dispose();
contextMenu.Dispose();
notificationScreenshotManager?.Dispose();
videoPlayer?.Dispose();
analytics?.Dispose();
}; };
Config.MuteToggled += Config_MuteToggled; Config.MuteToggled += Config_MuteToggled;
@ -119,6 +111,23 @@ public FormBrowser(){
RestoreWindow(); RestoreWindow();
} }
protected override void Dispose(bool disposing){
if (disposing){
components?.Dispose();
browser.Dispose();
updates.Dispose();
notification.Dispose();
contextMenu.Dispose();
notificationScreenshotManager?.Dispose();
videoPlayer?.Dispose();
analytics?.Dispose();
}
base.Dispose(disposing);
}
private void ShowChildForm(Form form){ private void ShowChildForm(Form form){
form.VisibleChanged += (sender, args) => form.MoveToCenter(this); form.VisibleChanged += (sender, args) => form.MoveToCenter(this);
form.Show(this); form.Show(this);
@ -152,7 +161,9 @@ private void timerResize_Tick(object sender, EventArgs e){
} }
private void FormBrowser_Activated(object sender, EventArgs e){ private void FormBrowser_Activated(object sender, EventArgs e){
if (!isLoaded)return; if (!isLoaded){
return;
}
trayIcon.HasNotifications = false; trayIcon.HasNotifications = false;
@ -162,14 +173,18 @@ private void FormBrowser_Activated(object sender, EventArgs e){
} }
private void FormBrowser_LocationChanged(object sender, EventArgs e){ private void FormBrowser_LocationChanged(object sender, EventArgs e){
if (!isLoaded)return; if (!isLoaded){
return;
}
timerResize.Stop(); timerResize.Stop();
timerResize.Start(); timerResize.Start();
} }
private void FormBrowser_Resize(object sender, EventArgs e){ private void FormBrowser_Resize(object sender, EventArgs e){
if (!isLoaded)return; if (!isLoaded){
return;
}
if (WindowState != prevState){ if (WindowState != prevState){
prevState = WindowState; prevState = WindowState;
@ -190,7 +205,9 @@ private void FormBrowser_Resize(object sender, EventArgs e){
} }
private void FormBrowser_ResizeEnd(object sender, EventArgs e){ // also triggers when the window moves private void FormBrowser_ResizeEnd(object sender, EventArgs e){ // also triggers when the window moves
if (!isLoaded)return; if (!isLoaded){
return;
}
timerResize.Stop(); timerResize.Stop();
@ -201,7 +218,9 @@ private void FormBrowser_ResizeEnd(object sender, EventArgs e){ // also triggers
} }
private void FormBrowser_FormClosing(object sender, FormClosingEventArgs e){ private void FormBrowser_FormClosing(object sender, FormClosingEventArgs e){
if (!isLoaded)return; if (!isLoaded){
return;
}
if (Config.TrayBehavior.ShouldHideOnClose() && trayIcon.Visible && e.CloseReason == CloseReason.UserClosing){ if (Config.TrayBehavior.ShouldHideOnClose() && trayIcon.Visible && e.CloseReason == CloseReason.UserClosing){
Hide(); // hides taskbar too?! welp that works I guess Hide(); // hides taskbar too?! welp that works I guess
@ -491,12 +510,12 @@ public void OpenPlugins(){
public void OpenProfileImport(){ public void OpenProfileImport(){
FormManager.TryFind<FormSettings>()?.Close(); FormManager.TryFind<FormSettings>()?.Close();
using(DialogSettingsManage dialog = new DialogSettingsManage(plugins, true)){ using DialogSettingsManage dialog = new DialogSettingsManage(plugins, true);
if (!dialog.IsDisposed && dialog.ShowDialog() == DialogResult.OK && !dialog.IsRestarting){ // needs disposal check because the dialog may be closed in constructor
BrowserProcessHandler.UpdatePrefs(); if (!dialog.IsDisposed && dialog.ShowDialog() == DialogResult.OK && !dialog.IsRestarting){ // needs disposal check because the dialog may be closed in constructor
FormManager.TryFind<FormPlugins>()?.Close(); BrowserProcessHandler.UpdatePrefs();
plugins.Reload(); // also reloads the browser FormManager.TryFind<FormPlugins>()?.Close();
} plugins.Reload(); // also reloads the browser
} }
} }
@ -516,10 +535,7 @@ public void PlayVideo(string videoUrl, string tweetUrl, string username, IJavasc
if (playerPath == null || !File.Exists(playerPath)){ if (playerPath == null || !File.Exists(playerPath)){
if (videoPlayer == null){ if (videoPlayer == null){
videoPlayer = new VideoPlayer(this); videoPlayer = new VideoPlayer(this);
videoPlayer.ProcessExited += (sender, args) => browser.HideVideoOverlay(true);
videoPlayer.ProcessExited += (sender, args) => {
browser.HideVideoOverlay(true);
};
} }
callShowOverlay.ExecuteAsync(); callShowOverlay.ExecuteAsync();

View File

@ -14,7 +14,9 @@ public static bool TryBringToFront<T>() where T : Form{
form.BringToFront(); form.BringToFront();
return true; return true;
} }
else return false; else{
return false;
}
} }
public static void CloseAllDialogs(){ public static void CloseAllDialogs(){

View File

@ -5,17 +5,6 @@ partial class FormNotificationBase {
/// </summary> /// </summary>
private System.ComponentModel.IContainer components = null; private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing) {
if (disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code #region Windows Form Designer generated code
/// <summary> /// <summary>

View File

@ -144,11 +144,7 @@ protected FormNotificationBase(FormBrowser owner, bool enableContextMenu){
this.browser.SetupZoomEvents(); this.browser.SetupZoomEvents();
Controls.Add(browser); Controls.Add(browser);
Disposed += (sender, args) => this.owner.FormClosed -= owner_FormClosed;
Disposed += (sender, args) => {
this.browser.Dispose();
this.owner.FormClosed -= owner_FormClosed;
};
DpiScale = this.GetDPIScale(); DpiScale = this.GetDPIScale();
@ -156,6 +152,16 @@ protected FormNotificationBase(FormBrowser owner, bool enableContextMenu){
UpdateTitle(); UpdateTitle();
} }
protected override void Dispose(bool disposing){
if (disposing){
components?.Dispose();
browser.Dispose();
resourceHandler.Dispose();
}
base.Dispose(disposing);
}
protected override void WndProc(ref Message m){ protected override void WndProc(ref Message m){
if (m.Msg == 0x0112 && (m.WParam.ToInt32() & 0xFFF0) == 0xF010 && !CanDragWindow){ // WM_SYSCOMMAND, SC_MOVE if (m.Msg == 0x0112 && (m.WParam.ToInt32() & 0xFFF0) == 0xF010 && !CanDragWindow){ // WM_SYSCOMMAND, SC_MOVE
return; return;

View File

@ -82,16 +82,16 @@ public bool TakeScreenshot(bool ignoreHeightError = false){
return false; return false;
} }
else{ else{
using(Bitmap bmp = new Bitmap(ClientSize.Width, Math.Max(1, height), PixelFormat.Format32bppRgb)){ using Bitmap bmp = new Bitmap(ClientSize.Width, Math.Max(1, height), PixelFormat.Format32bppRgb);
try{
NativeMethods.RenderSourceIntoBitmap(context, bmp);
}finally{
NativeMethods.ReleaseDC(this.Handle, context);
}
Clipboard.SetImage(bmp); try{
return true; NativeMethods.RenderSourceIntoBitmap(context, bmp);
}finally{
NativeMethods.ReleaseDC(this.Handle, context);
} }
Clipboard.SetImage(bmp);
return true;
} }
} }
} }

View File

@ -28,16 +28,15 @@ public static IResourceHandler CreateFileHandler(string path){
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);
form.AddButton(FormMessage.Ignore, ControlType.Cancel | ControlType.Focused); form.AddButton(FormMessage.Ignore, ControlType.Cancel | ControlType.Focused);
Button btnViewOptions = form.AddButton("View Options"); Button btnViewOptions = form.AddButton("View Options");
btnViewOptions.Width += 16; btnViewOptions.Width += 16;
btnViewOptions.Location = new Point(btnViewOptions.Location.X - 16, btnViewOptions.Location.Y); btnViewOptions.Location = new Point(btnViewOptions.Location.X - 16, btnViewOptions.Location.Y);
if (form.ShowDialog() == DialogResult.OK && form.ClickedButton == btnViewOptions){ if (form.ShowDialog() == DialogResult.OK && form.ClickedButton == btnViewOptions){
browser.OpenSettings(typeof(TabSettingsSounds)); browser.OpenSettings(typeof(TabSettingsSounds));
}
} }
}); });

View File

@ -138,8 +138,7 @@ private void SendReport(){
break; break;
case WebExceptionStatus.ProtocolError: case WebExceptionStatus.ProtocolError:
HttpWebResponse response = e.Response as HttpWebResponse; message = "HTTP Error " + (e.Response is HttpWebResponse response ? $"{(int)response.StatusCode} ({response.StatusDescription})" : "(unknown code)");
message = "HTTP Error " + (response != null ? $"{(int)response.StatusCode} ({response.StatusDescription})" : "(unknown code)");
break; break;
} }

View File

@ -5,17 +5,6 @@ partial class FormGuide {
/// </summary> /// </summary>
private System.ComponentModel.IContainer components = null; private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing) {
if (disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code #region Windows Form Designer generated code
/// <summary> /// <summary>

View File

@ -85,10 +85,15 @@ private FormGuide(string url, FormBrowser owner){
browser.SetupZoomEvents(); browser.SetupZoomEvents();
Controls.Add(browser); Controls.Add(browser);
}
Disposed += (sender, args) => { protected override void Dispose(bool disposing){
if (disposing){
components?.Dispose();
browser.Dispose(); browser.Dispose();
}; }
base.Dispose(disposing);
} }
private void Reload(string url){ private void Reload(string url){

View File

@ -43,17 +43,17 @@ public static bool Show(string caption, string text, MessageBoxIcon icon, string
} }
public static bool Show(string caption, string text, MessageBoxIcon icon, string buttonAccept, string buttonCancel){ public static bool Show(string caption, string text, MessageBoxIcon icon, string buttonAccept, string buttonCancel){
using(FormMessage message = new FormMessage(caption, text, icon)){ using FormMessage message = new FormMessage(caption, text, icon);
if (buttonCancel == null){
message.AddButton(buttonAccept, DialogResult.OK, ControlType.Cancel | ControlType.Focused);
}
else{
message.AddButton(buttonCancel, DialogResult.Cancel, ControlType.Cancel);
message.AddButton(buttonAccept, DialogResult.OK, ControlType.Accept | ControlType.Focused);
}
return message.ShowDialog() == DialogResult.OK; if (buttonCancel == null){
message.AddButton(buttonAccept, DialogResult.OK, ControlType.Cancel | ControlType.Focused);
} }
else{
message.AddButton(buttonCancel, DialogResult.Cancel, ControlType.Cancel);
message.AddButton(buttonAccept, DialogResult.OK, ControlType.Accept | ControlType.Focused);
}
return message.ShowDialog() == DialogResult.OK;
} }
// Instance // Instance

View File

@ -80,25 +80,24 @@ private void FormSettings_FormClosing(object sender, FormClosingEventArgs e){
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);
FormClosing -= FormSettings_FormClosing; FormClosing -= FormSettings_FormClosing;
if (dialog.ShowDialog() == DialogResult.OK){ if (dialog.ShowDialog() == DialogResult.OK){
if (!dialog.IsRestarting){ if (!dialog.IsRestarting){
browser.ResumeNotification(); browser.ResumeNotification();
if (dialog.ShouldReloadBrowser){ if (dialog.ShouldReloadBrowser){
BrowserProcessHandler.UpdatePrefs(); BrowserProcessHandler.UpdatePrefs();
ShouldReloadBrowser = true; ShouldReloadBrowser = true;
}
} }
}
Close(); Close();
} }
else{ else{
FormClosing += FormSettings_FormClosing; FormClosing += FormSettings_FormClosing;
PrepareLoad(); PrepareLoad();
}
} }
} }

View File

@ -91,10 +91,10 @@ private void btnRestart_Click(object sender, EventArgs e){
} }
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){
Program.RestartWithArgs(dialog.Args); if (dialog.ShowDialog() == DialogResult.OK){
} Program.RestartWithArgs(dialog.Args);
} }
} }

View File

@ -50,9 +50,8 @@ private void labelDataCollectionLink_LinkClicked(object sender, LinkLabelLinkCli
} }
private void btnViewReport_Click(object sender, EventArgs e){ private void btnViewReport_Click(object sender, EventArgs e){
using(DialogSettingsAnalytics dialog = new DialogSettingsAnalytics(AnalyticsReportGenerator.Create(analyticsFile, analyticsInfo, plugins))){ using DialogSettingsAnalytics dialog = new DialogSettingsAnalytics(AnalyticsReportGenerator.Create(analyticsFile, analyticsInfo, plugins));
dialog.ShowDialog(); dialog.ShowDialog();
}
} }
#endregion #endregion

View File

@ -219,10 +219,18 @@ 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)Config.NotificationPosition = DesktopNotification.Position.TopLeft; if (radioLocTL.Checked){
else if (radioLocTR.Checked)Config.NotificationPosition = DesktopNotification.Position.TopRight; Config.NotificationPosition = DesktopNotification.Position.TopLeft;
else if (radioLocBL.Checked)Config.NotificationPosition = DesktopNotification.Position.BottomLeft; }
else if (radioLocBR.Checked)Config.NotificationPosition = DesktopNotification.Position.BottomRight; else if (radioLocTR.Checked){
Config.NotificationPosition = DesktopNotification.Position.TopRight;
}
else if (radioLocBL.Checked){
Config.NotificationPosition = DesktopNotification.Position.BottomLeft;
}
else if (radioLocBR.Checked){
Config.NotificationPosition = DesktopNotification.Position.BottomRight;
}
comboBoxDisplay.Enabled = trackBarEdgeDistance.Enabled = true; comboBoxDisplay.Enabled = trackBarEdgeDistance.Enabled = true;
notification.ShowExampleNotification(false); notification.ShowExampleNotification(false);

View File

@ -64,15 +64,15 @@ 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,
Title = "Custom Notification Sound", Title = "Custom Notification Sound",
Filter = $"Sound file ({SoundNotification.SupportedFormats})|{SoundNotification.SupportedFormats}|All files (*.*)|*.*" Filter = $"Sound file ({SoundNotification.SupportedFormats})|{SoundNotification.SupportedFormats}|All files (*.*)|*.*"
}){ };
if (dialog.ShowDialog() == DialogResult.OK){
tbCustomSound.Text = dialog.FileName; if (dialog.ShowDialog() == DialogResult.OK){
} tbCustomSound.Text = dialog.FileName;
} }
} }

View File

@ -5,17 +5,6 @@ partial class TrayIcon {
/// </summary> /// </summary>
private System.ComponentModel.IContainer components = null; private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing) {
if (disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code #region Component Designer generated code
/// <summary> /// <summary>

View File

@ -63,6 +63,15 @@ public TrayIcon(IContainer container) : this(){
container.Add(this); container.Add(this);
} }
protected override void Dispose(bool disposing){
if (disposing){
components?.Dispose();
contextMenu.Dispose();
}
base.Dispose(disposing);
}
private void UpdateIcon(){ private void UpdateIcon(){
if (Visible){ if (Visible){
notifyIcon.Icon = hasNotifications ? Res.icon_tray_new : Config.MuteNotifications ? Res.icon_tray_muted : Res.icon_tray; notifyIcon.Icon = hasNotifications ? Res.icon_tray_new : Config.MuteNotifications ? Res.icon_tray_muted : Res.icon_tray;

View File

@ -161,10 +161,16 @@ public static void OpenExternalSearch(string query){
bool wereSettingsOpen = FormManager.TryFind<FormSettings>() != null; bool wereSettingsOpen = FormManager.TryFind<FormSettings>() != null;
FormManager.TryFind<FormBrowser>()?.OpenSettings(); FormManager.TryFind<FormBrowser>()?.OpenSettings();
if (wereSettingsOpen)return;
if (wereSettingsOpen){
return;
}
FormSettings settings = FormManager.TryFind<FormSettings>(); FormSettings settings = FormManager.TryFind<FormSettings>();
if (settings == null)return;
if (settings == null){
return;
}
settings.FormClosed += (sender, args) => { settings.FormClosed += (sender, args) => {
if (args.CloseReason == CloseReason.UserClosing && Config.SearchEngineUrl != searchUrl){ if (args.CloseReason == CloseReason.UserClosing && Config.SearchEngineUrl != searchUrl){

View File

@ -138,14 +138,13 @@ public static int GetIdleSeconds(){
} }
public static void RenderSourceIntoBitmap(IntPtr source, Bitmap target){ public static void RenderSourceIntoBitmap(IntPtr source, Bitmap target){
using(Graphics graphics = Graphics.FromImage(target)){ using Graphics graphics = Graphics.FromImage(target);
IntPtr graphicsHandle = graphics.GetHdc(); IntPtr graphicsHandle = graphics.GetHdc();
try{ try{
BitBlt(graphicsHandle, 0, 0, target.Width, target.Height, source, 0, 0, 0x00CC0020); BitBlt(graphicsHandle, 0, 0, target.Width, target.Height, source, 0, 0, 0x00CC0020);
}finally{ }finally{
graphics.ReleaseHdc(graphicsHandle); graphics.ReleaseHdc(graphicsHandle);
}
} }
} }
} }

View File

@ -64,29 +64,29 @@ public static void DownloadImages(string[] urls, string username, ImageQuality q
string filename = TwitterUrls.GetImageFileName(firstImageLink); string filename = TwitterUrls.GetImageFileName(firstImageLink);
string ext = Path.GetExtension(filename); // includes dot string ext = Path.GetExtension(filename); // includes dot
using(SaveFileDialog dialog = new SaveFileDialog{ using SaveFileDialog dialog = new SaveFileDialog{
AutoUpgradeEnabled = true, AutoUpgradeEnabled = true,
OverwritePrompt = urls.Length == 1, OverwritePrompt = urls.Length == 1,
Title = "Save Image", Title = "Save Image",
FileName = qualityIndex == -1 ? filename : $"{username} {Path.ChangeExtension(filename, null)} {firstImageLink.Substring(qualityIndex + 1)}".Trim() + ext, FileName = qualityIndex == -1 ? filename : $"{username} {Path.ChangeExtension(filename, null)} {firstImageLink.Substring(qualityIndex + 1)}".Trim() + ext,
Filter = (urls.Length == 1 ? "Image" : "Images") + (string.IsNullOrEmpty(ext) ? " (unknown)|*.*" : $" (*{ext})|*{ext}") Filter = (urls.Length == 1 ? "Image" : "Images") + (string.IsNullOrEmpty(ext) ? " (unknown)|*.*" : $" (*{ext})|*{ext}")
}){ };
if (dialog.ShowDialog() == DialogResult.OK){
static void OnFailure(Exception ex){
FormMessage.Error("Image Download", "An error occurred while downloading the image: " + ex.Message, FormMessage.OK);
}
if (urls.Length == 1){ if (dialog.ShowDialog() == DialogResult.OK){
DownloadFileAuth(firstImageLink, dialog.FileName, null, OnFailure); static void OnFailure(Exception ex){
} FormMessage.Error("Image Download", "An error occurred while downloading the image: " + ex.Message, FormMessage.OK);
else{ }
string pathBase = Path.ChangeExtension(dialog.FileName, null);
string pathExt = Path.GetExtension(dialog.FileName);
for(int index = 0; index < urls.Length; index++){ if (urls.Length == 1){
DownloadFileAuth(TwitterUrls.GetMediaLink(urls[index], quality), $"{pathBase} {index + 1}{pathExt}", null, OnFailure); DownloadFileAuth(firstImageLink, dialog.FileName, null, OnFailure);
} }
else{
string pathBase = Path.ChangeExtension(dialog.FileName, null);
string pathExt = Path.GetExtension(dialog.FileName);
for(int index = 0; index < urls.Length; index++){
DownloadFileAuth(TwitterUrls.GetMediaLink(urls[index], quality), $"{pathBase} {index + 1}{pathExt}", null, OnFailure);
} }
} }
} }
@ -96,18 +96,18 @@ public static void DownloadVideo(string url, string username){
string filename = TwitterUrls.GetFileNameFromUrl(url); string filename = TwitterUrls.GetFileNameFromUrl(url);
string ext = Path.GetExtension(filename); string ext = Path.GetExtension(filename);
using(SaveFileDialog dialog = new SaveFileDialog{ using SaveFileDialog dialog = new SaveFileDialog{
AutoUpgradeEnabled = true, AutoUpgradeEnabled = true,
OverwritePrompt = true, OverwritePrompt = true,
Title = "Save Video", Title = "Save Video",
FileName = string.IsNullOrEmpty(username) ? filename : $"{username} {filename}".TrimStart(), FileName = string.IsNullOrEmpty(username) ? filename : $"{username} {filename}".TrimStart(),
Filter = "Video" + (string.IsNullOrEmpty(ext) ? " (unknown)|*.*" : $" (*{ext})|*{ext}") Filter = "Video" + (string.IsNullOrEmpty(ext) ? " (unknown)|*.*" : $" (*{ext})|*{ext}")
}){ };
if (dialog.ShowDialog() == DialogResult.OK){
DownloadFileAuth(url, dialog.FileName, null, ex => { if (dialog.ShowDialog() == DialogResult.OK){
FormMessage.Error("Video Download", "An error occurred while downloading the video: " + ex.Message, FormMessage.OK); DownloadFileAuth(url, dialog.FileName, null, ex => {
}); FormMessage.Error("Video Download", "An error occurred while downloading the video: " + ex.Message, FormMessage.OK);
} });
} }
} }
@ -115,25 +115,24 @@ private static void DownloadFileAuth(string url, string target, Action onSuccess
const string AuthCookieName = "auth_token"; const string AuthCookieName = "auth_token";
TaskScheduler scheduler = TaskScheduler.FromCurrentSynchronizationContext(); TaskScheduler scheduler = TaskScheduler.FromCurrentSynchronizationContext();
using ICookieManager cookies = Cef.GetGlobalCookieManager();
using(ICookieManager cookies = Cef.GetGlobalCookieManager()){ cookies.VisitUrlCookiesAsync(url, true).ContinueWith(task => {
cookies.VisitUrlCookiesAsync(url, true).ContinueWith(task => { string cookieStr = null;
string cookieStr = null;
if (task.Status == TaskStatus.RanToCompletion){ if (task.Status == TaskStatus.RanToCompletion){
Cookie found = task.Result?.Find(cookie => cookie.Name == AuthCookieName); // the list may be null Cookie found = task.Result?.Find(cookie => cookie.Name == AuthCookieName); // the list may be null
if (found != null){ if (found != null){
cookieStr = $"{found.Name}={found.Value}"; cookieStr = $"{found.Name}={found.Value}";
}
} }
}
WebClient client = WebUtils.NewClient(BrowserUtils.UserAgentChrome); WebClient client = WebUtils.NewClient(BrowserUtils.UserAgentChrome);
client.Headers[HttpRequestHeader.Cookie] = cookieStr; client.Headers[HttpRequestHeader.Cookie] = cookieStr;
client.DownloadFileCompleted += WebUtils.FileDownloadCallback(target, onSuccess, onFailure); client.DownloadFileCompleted += WebUtils.FileDownloadCallback(target, onSuccess, onFailure);
client.DownloadFileAsync(new Uri(url), target); client.DownloadFileAsync(new Uri(url), target);
}, scheduler); }, scheduler);
}
} }
} }
} }

View File

@ -232,7 +232,9 @@ private static void RestartWithArgsInternal(CommandLineArgs args){
} }
private static void ExitCleanup(){ private static void ExitCleanup(){
if (HasCleanedUp)return; if (HasCleanedUp){
return;
}
Config.SaveAll(); Config.SaveAll();

View File

@ -37,12 +37,11 @@ protected DuplexPipe(PipeStream pipeIn, PipeStream pipeOut){
} }
private void ReaderThread(){ private void ReaderThread(){
using(StreamReader read = new StreamReader(pipeIn)){ using StreamReader read = new StreamReader(pipeIn);
string data; string data;
while((data = read.ReadLine()) != null){ while((data = read.ReadLine()) != null){
DataIn?.Invoke(this, new PipeReadEventArgs(data)); DataIn?.Invoke(this, new PipeReadEventArgs(data));
}
} }
} }

View File

@ -12,6 +12,7 @@
<AssemblyName>TweetLib.Communication</AssemblyName> <AssemblyName>TweetLib.Communication</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion> <TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<LangVersion>8.0</LangVersion> <LangVersion>8.0</LangVersion>
<Nullable>enable</Nullable>
<FileAlignment>512</FileAlignment> <FileAlignment>512</FileAlignment>
<NuGetPackageImportStamp> <NuGetPackageImportStamp>
</NuGetPackageImportStamp> </NuGetPackageImportStamp>

View File

@ -3,10 +3,12 @@
namespace TweetLib.Core{ namespace TweetLib.Core{
public sealed class App{ public sealed class App{
#pragma warning disable CS8618 // Non-nullable field is uninitialized. Consider declaring as nullable.
public static IAppErrorHandler ErrorHandler { get; private set; } public static IAppErrorHandler ErrorHandler { get; private set; }
public static IAppLockHandler LockHandler { get; private set; } public static IAppLockHandler LockHandler { get; private set; }
public static IAppSystemHandler SystemHandler { get; private set; } public static IAppSystemHandler SystemHandler { get; private set; }
public static IAppResourceHandler ResourceHandler { get; private set; } public static IAppResourceHandler ResourceHandler { get; private set; }
#pragma warning restore CS8618 // Non-nullable field is uninitialized. Consider declaring as nullable.
// Builder // Builder

View File

@ -74,11 +74,11 @@ private string GetFullPathOrThrow(int token, PluginFolder folder, string path){
string fullPath = plugin == null ? string.Empty : plugin.GetFullPathIfSafe(folder, path); string fullPath = plugin == null ? string.Empty : plugin.GetFullPathIfSafe(folder, path);
if (fullPath.Length == 0){ if (fullPath.Length == 0){
switch(folder){ throw folder switch{
case PluginFolder.Data: throw new ArgumentException("File path has to be relative to the plugin data folder."); PluginFolder.Data => new ArgumentException("File path has to be relative to the plugin data folder."),
case PluginFolder.Root: throw new ArgumentException("File path has to be relative to the plugin root folder."); PluginFolder.Root => new ArgumentException("File path has to be relative to the plugin root folder."),
default: throw new ArgumentException($"Invalid folder type {folder}, this is a TweetDuck error."); _ => new ArgumentException($"Invalid folder type {folder}, this is a TweetDuck error.")
} };
} }
else{ else{
return fullPath; return fullPath;

View File

@ -17,8 +17,8 @@ public sealed class PluginManager{
public IPluginConfig Config { get; } public IPluginConfig Config { get; }
public event EventHandler<PluginErrorEventArgs> Reloaded; public event EventHandler<PluginErrorEventArgs>? Reloaded;
public event EventHandler<PluginErrorEventArgs> Executed; public event EventHandler<PluginErrorEventArgs>? Executed;
private readonly string pluginFolder; private readonly string pluginFolder;
private readonly string pluginDataFolder; private readonly string pluginDataFolder;

View File

@ -13,7 +13,7 @@ public sealed class UpdateHandler : IDisposable{
private readonly TaskScheduler scheduler; private readonly TaskScheduler scheduler;
private readonly Timer timer; private readonly Timer timer;
public event EventHandler<UpdateCheckEventArgs> CheckFinished; public event EventHandler<UpdateCheckEventArgs>? CheckFinished;
private ushort lastEventId; private ushort lastEventId;
public UpdateHandler(IUpdateCheckClient client, TaskScheduler scheduler){ public UpdateHandler(IUpdateCheckClient client, TaskScheduler scheduler){

View File

@ -6,7 +6,9 @@ public static class Lib{
public const string BrandName = "TweetDuck"; public const string BrandName = "TweetDuck";
public const string VersionTag = "1.18.3"; public const string VersionTag = "1.18.3";
#pragma warning disable CS8618 // Non-nullable field is uninitialized. Consider declaring as nullable.
public static CultureInfo Culture { get; private set; } public static CultureInfo Culture { get; private set; }
#pragma warning restore CS8618 // Non-nullable field is uninitialized. Consider declaring as nullable.
public static void Initialize(App.Builder app){ public static void Initialize(App.Builder app){
Culture = CultureInfo.CurrentCulture; Culture = CultureInfo.CurrentCulture;

View File

@ -33,14 +33,18 @@ bool ITypeConverter.TryReadType(Type type, string value, out object? converted){
converted = b; converted = b;
return true; return true;
} }
else goto default; else{
goto default;
}
case TypeCode.Int32: case TypeCode.Int32:
if (int.TryParse(value, out int i)){ if (int.TryParse(value, out int i)){
converted = i; converted = i;
return true; return true;
} }
else goto default; else{
goto default;
}
case TypeCode.String: case TypeCode.String:
converted = value; converted = value;

View File

@ -2,12 +2,12 @@
namespace TweetLib.Core.Serialization.Converters{ namespace TweetLib.Core.Serialization.Converters{
public sealed class SingleTypeConverter<T> : ITypeConverter{ public sealed class SingleTypeConverter<T> : ITypeConverter{
public Func<T, string> ConvertToString { get; set; } public Func<T, string>? ConvertToString { get; set; }
public Func<string, T> ConvertToObject { get; set; } public Func<string, T>? ConvertToObject { get; set; }
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;
@ -17,7 +17,7 @@ bool ITypeConverter.TryWriteType(Type type, object value, out string? converted)
bool ITypeConverter.TryReadType(Type type, string value, out object? converted){ bool ITypeConverter.TryReadType(Type type, string value, out object? converted){
try{ try{
converted = ConvertToObject(value); converted = ConvertToObject!(value);
return true; return true;
}catch{ }catch{
converted = null; converted = null;

View File

@ -4,7 +4,7 @@
<TargetFramework>netstandard2.0</TargetFramework> <TargetFramework>netstandard2.0</TargetFramework>
<Platforms>x86</Platforms> <Platforms>x86</Platforms>
<LangVersion>8.0</LangVersion> <LangVersion>8.0</LangVersion>
<NullableContextOptions>enable</NullableContextOptions> <Nullable>enable</Nullable>
</PropertyGroup> </PropertyGroup>
</Project> </Project>

View File

@ -24,9 +24,8 @@ string FindArg(string key){
Task.Factory.StartNew(() => KillWhenHung(parentId), TaskCreationOptions.LongRunning); Task.Factory.StartNew(() => KillWhenHung(parentId), TaskCreationOptions.LongRunning);
if (FindArg(typePrefix) == "renderer"){ if (FindArg(typePrefix) == "renderer"){
using(SubProcess subProcess = new SubProcess(args)){ using SubProcess subProcess = new SubProcess(args);
return subProcess.Run(); return subProcess.Run();
}
} }
else{ else{
return SubProcess.ExecuteProcess(); return SubProcess.ExecuteProcess();
@ -35,9 +34,8 @@ string FindArg(string key){
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(); process.WaitForExit();
}
}catch{ }catch{
// ded // ded
} }

View File

@ -11,6 +11,7 @@
<AssemblyName>TweetDuck.Browser</AssemblyName> <AssemblyName>TweetDuck.Browser</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion> <TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<LangVersion>8.0</LangVersion> <LangVersion>8.0</LangVersion>
<Nullable>enable</Nullable>
<FileAlignment>512</FileAlignment> <FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects> <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<NuGetPackageImportStamp> <NuGetPackageImportStamp>

View File

@ -5,17 +5,6 @@ partial class FormPlayer {
/// </summary> /// </summary>
private System.ComponentModel.IContainer components = null; private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing) {
if (disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code #region Windows Form Designer generated code
/// <summary> /// <summary>

View File

@ -88,6 +88,16 @@ public FormPlayer(IntPtr handle, int dpi, int volume, string url, string token){
Application.AddMessageFilter(new MessageFilter(this)); Application.AddMessageFilter(new MessageFilter(this));
} }
protected override void Dispose(bool disposing){
if (disposing){
components.Dispose();
player.Dispose();
pipe.Dispose();
}
base.Dispose(disposing);
}
// Layout // Layout
private int DpiScaled(int value){ private int DpiScaled(int value){

View File

@ -11,6 +11,7 @@
<AssemblyName>TweetDuck.Video</AssemblyName> <AssemblyName>TweetDuck.Video</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion> <TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<LangVersion>8.0</LangVersion> <LangVersion>8.0</LangVersion>
<Nullable>enable</Nullable>
<FileAlignment>512</FileAlignment> <FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects> <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<ResolveComReferenceSilent>True</ResolveComReferenceSilent> <ResolveComReferenceSilent>True</ResolveComReferenceSilent>