-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
488 lines (434 loc) · 14.2 KB
/
Copy pathMainWindow.xaml.cs
File metadata and controls
488 lines (434 loc) · 14.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
using FileFox.Helpers;
using FileFox.Models;
using FileFox.Services;
using FileFox.Views;
using H.NotifyIcon;
using Microsoft.UI.Windowing;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Controls.Primitives;
using Microsoft.UI.Xaml.Media;
using Microsoft.UI.Xaml.Media.Imaging;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
using Windows.Graphics;
using WinRT.Interop;
namespace FileFox;
public sealed partial class MainWindow : Window
{
private const string CloseToTraySetting = "CloseToTray";
private const nuint SubclassId = 101;
private readonly SiteManagerService _siteManager = new();
private readonly StartupManager _startupManager = new();
private TaskbarIcon? _taskbarIcon;
private Win32Window.SubclassProc? _subclassProc;
private uint _restoreMessageId;
private IntPtr _windowHandle;
private bool _isExiting;
private bool _closeToTray = true;
public MainWindow()
{
TrayOpenCommand = new SimpleCommand(RestoreAndActivateWindow);
TrayExitCommand = new SimpleCommand(RequestExit);
InitializeComponent();
Title = App.WindowTitle;
LoadWindowSettings();
ConfigureWindow();
InitializeSubclassing();
InitializeTrayIcon();
RootGrid.Loaded += RootGrid_Loaded;
AppWindow.Closing += AppWindow_Closing;
}
public ICommand TrayOpenCommand { get; }
public ICommand TrayExitCommand { get; }
public void HideToTray()
{
try
{
AppWindow.Hide();
}
catch (Exception ex)
{
AppLogger.LogException(ex, "HideToTray");
}
}
public void RestoreAndActivateWindow()
{
try
{
AppWindow.Show();
if (AppWindow.Presenter is OverlappedPresenter presenter)
{
presenter.Maximize();
}
Activate();
if (_windowHandle != IntPtr.Zero)
{
Win32Window.ShowWindow(_windowHandle, Win32Window.SwMaximize);
Win32Window.ShowWindow(_windowHandle, Win32Window.SwShow);
Win32Window.SetForegroundWindow(_windowHandle);
}
AppLogger.LogAction("Window_Restored");
}
catch (Exception ex)
{
AppLogger.LogException(ex, "RestoreAndActivateWindow");
}
}
private void RootGrid_Loaded(object sender, RoutedEventArgs e)
{
RootGrid.Loaded -= RootGrid_Loaded;
ThemeService.ApplyTheme(RootGrid, ThemeService.CurrentTheme);
DashboardViewControl.UpdateThemeButtonState(ThemeService.CurrentTheme);
AppLogger.LogAction("MainWindow_Loaded");
}
private void ConfigureWindow()
{
try
{
AppWindow.SetIcon(Path.Combine(AppContext.BaseDirectory, "Assets", "AppIcon.ico"));
if (AppWindow.Presenter is OverlappedPresenter presenter)
{
presenter.Maximize();
}
}
catch (Exception ex)
{
AppLogger.LogException(ex, "ConfigureWindow");
}
}
private void LoadWindowSettings()
{
try
{
_closeToTray = AppStorageService.GetSetting<bool>(CloseToTraySetting, true);
}
catch (Exception ex)
{
AppLogger.LogException(ex, "LoadWindowSettings");
}
}
private async void MainTabView_AddTabButtonClick(TabView sender, object args)
{
try
{
var savedSites = await _siteManager.LoadAsync();
if (savedSites.Count == 0)
{
MainTabView.SelectedItem = DashboardTab;
var dialog = new ContentDialog
{
Title = "No Saved Connections",
Content = "You do not have any saved connection profiles yet. Please create and save a connection profile on the Dashboard first.",
CloseButtonText = "OK",
XamlRoot = RootGrid.XamlRoot
};
await dialog.ShowAsync();
return;
}
var menu = new MenuFlyout();
var newConnectionItem = new MenuFlyoutItem
{
Text = "Dashboard (New connection)",
Icon = new FontIcon { Glyph = "\uF246" }
};
newConnectionItem.Click += (_, _) =>
{
MainTabView.SelectedItem = DashboardTab;
};
menu.Items.Add(newConnectionItem);
menu.Items.Add(new MenuFlyoutSeparator());
foreach (var site in savedSites)
{
var siteItem = new MenuFlyoutItem
{
Text = $"{site.DisplayName} ({site.Protocol} • {site.Host}:{site.Port})",
Icon = new FontIcon { Glyph = "\uE8AF" }
};
var capturedSite = site;
siteItem.Click += (_, _) =>
{
OpenConnectionTab(capturedSite);
};
menu.Items.Add(siteItem);
}
menu.ShowAt(sender, new FlyoutShowOptions
{
Placement = FlyoutPlacementMode.BottomEdgeAlignedRight
});
}
catch (Exception ex)
{
AppLogger.LogException(ex, "AddTabButtonClick");
MainTabView.SelectedItem = DashboardTab;
}
}
private async void MainTabView_TabCloseRequested(TabView sender, TabViewTabCloseRequestedEventArgs args)
{
if (args.Item is TabViewItem tabItem)
{
if (tabItem.Content is ConnectionSessionView sessionView)
{
await sessionView.DisconnectInternalAsync(false);
}
sender.TabItems.Remove(tabItem);
}
}
private void DashboardView_ConnectRequested(object? sender, ConnectionProfile profile)
{
OpenConnectionTab(profile);
}
private void OpenConnectionTab(ConnectionProfile profile)
{
var sessionView = new ConnectionSessionView(profile, _windowHandle);
string tabTitle = string.IsNullOrWhiteSpace(profile.Name) || string.Equals(profile.Name, profile.Host, StringComparison.OrdinalIgnoreCase)
? profile.Host
: $"{profile.Name} ({profile.Host})";
IconSource iconSource;
try
{
var faviconUrl = $"https://www.google.com/s2/favicons?domain={Uri.EscapeDataString(profile.Host)}&sz=32";
iconSource = new BitmapIconSource
{
UriSource = new Uri(faviconUrl),
ShowAsMonochrome = false
};
}
catch
{
iconSource = new FontIconSource { Glyph = "\uE8AF" };
}
var tabItem = new TabViewItem
{
Header = tabTitle,
Content = sessionView,
IsClosable = true,
IconSource = iconSource
};
sessionView.TitleChanged += (s, newTitle) =>
{
tabItem.Header = newTitle;
};
sessionView.EditFileRequested += async (s, args) =>
{
await OpenFileEditorTabAsync(args.FileItem, args.RemoteSystem);
};
MainTabView.TabItems.Add(tabItem);
MainTabView.SelectedItem = tabItem;
}
private async Task OpenFileEditorTabAsync(RemoteFileItem fileItem, IRemoteFileSystem remote)
{
try
{
var tempDir = Path.Combine(AppStorageService.TempFolder, "FileFoxEditors");
Directory.CreateDirectory(tempDir);
var tempFilePath = Path.Combine(tempDir, $"{Guid.NewGuid():N}_{fileItem.Name}");
var progress = new Progress<TransferProgressInfo>();
await remote.DownloadFileAsync(fileItem.FullPath, tempFilePath, progress, CancellationToken.None);
var editorView = new FileEditorView(tempFilePath, fileItem.FullPath, remote);
var tabItem = new TabViewItem
{
Header = fileItem.Name,
Content = editorView,
IsClosable = true,
IconSource = new FontIconSource { Glyph = "\uE70F" }
};
editorView.CloseRequested += (_, _) =>
{
MainTabView.TabItems.Remove(tabItem);
try
{
if (File.Exists(tempFilePath))
{
File.Delete(tempFilePath);
}
}
catch { }
};
MainTabView.TabItems.Add(tabItem);
MainTabView.SelectedItem = tabItem;
}
catch (Exception ex)
{
AppLogger.LogException(ex, "OpenFileEditorTab");
await ShowErrorAsync("Error opening file", ex.Message);
}
}
private async void DashboardView_DeleteSiteRequested(object? sender, ConnectionProfile profile)
{
try
{
await _siteManager.DeleteAsync(profile);
await DashboardViewControl.LoadSavedSitesAsync();
}
catch (Exception ex)
{
AppLogger.LogException(ex, "DeleteSiteRequested");
await ShowErrorAsync("Could not delete site", ex.Message);
}
}
private void DashboardView_ThemeToggleRequested(object? sender, EventArgs e)
{
var newTheme = ThemeService.ToggleTheme(RootGrid);
DashboardViewControl.UpdateThemeButtonState(newTheme);
}
private void RequestExit() => _ = ExitApplicationAsync();
private async Task ExitApplicationAsync()
{
if (_isExiting)
{
return;
}
_isExiting = true;
foreach (var item in MainTabView.TabItems.OfType<TabViewItem>())
{
if (item.Content is ConnectionSessionView sessionView)
{
await sessionView.DisconnectInternalAsync(false);
}
}
DisposeSubclassing();
try
{
_taskbarIcon?.Dispose();
}
catch (Exception ex)
{
AppLogger.LogException(ex, "TrayIcon_Dispose");
}
AppLogger.LogAction("Application_Exit");
Close();
Application.Current.Exit();
}
private void AppWindow_Closing(AppWindow sender, AppWindowClosingEventArgs args)
{
if (_isExiting)
{
return;
}
if (_closeToTray)
{
args.Cancel = true;
sender.Hide();
AppLogger.LogAction("Window_Hidden_To_Tray");
return;
}
_isExiting = true;
foreach (var item in MainTabView.TabItems.OfType<TabViewItem>())
{
if (item.Content is ConnectionSessionView sessionView)
{
_ = sessionView.DisconnectInternalAsync(false);
}
}
DisposeSubclassing();
try
{
_taskbarIcon?.Dispose();
}
catch
{
}
}
private void InitializeTrayIcon()
{
try
{
_taskbarIcon = new TaskbarIcon
{
ToolTipText = App.AppName,
ContextMenuMode = ContextMenuMode.ActiveWindow,
IconSource = new BitmapImage(new Uri(Path.Combine(AppContext.BaseDirectory, "Assets", "AppIcon.ico"))),
LeftClickCommand = TrayOpenCommand,
NoLeftClickDelay = true
};
var menu = new MenuFlyout { AreOpenCloseAnimationsEnabled = false };
var openItem = new MenuFlyoutItem
{
Text = $"Open {App.AppName}",
FontFamily = new FontFamily("Segoe UI"),
Icon = new FontIcon { Glyph = "\uE8A7" }
};
openItem.Click += (_, _) => RestoreAndActivateWindow();
menu.Items.Add(openItem);
var exitItem = new MenuFlyoutItem
{
Text = "Exit",
FontFamily = new FontFamily("Segoe UI"),
Icon = new FontIcon { Glyph = "\uE711" }
};
exitItem.Click += (_, _) => RequestExit();
menu.Items.Add(exitItem);
_taskbarIcon.ContextFlyout = menu;
RootGrid.Children.Add(_taskbarIcon);
}
catch (Exception ex)
{
AppLogger.LogException(ex, "TrayIcon_Initialize");
}
}
private void InitializeSubclassing()
{
try
{
_windowHandle = WindowNative.GetWindowHandle(this);
_restoreMessageId = Win32Window.RegisterWindowMessage(App.RestoreMessageName);
if (_windowHandle == IntPtr.Zero || _restoreMessageId == 0)
{
return;
}
_subclassProc = WindowSubclassCallback;
Win32Window.SetWindowSubclass(_windowHandle, _subclassProc, SubclassId, IntPtr.Zero);
}
catch (Exception ex)
{
AppLogger.LogException(ex, "WindowSubclass_Initialize");
}
}
private IntPtr WindowSubclassCallback(
IntPtr hWnd,
uint message,
IntPtr wParam,
IntPtr lParam,
nuint subclassId,
IntPtr referenceData)
{
if (_restoreMessageId != 0 && message == _restoreMessageId)
{
DispatcherQueue.TryEnqueue(RestoreAndActivateWindow);
return IntPtr.Zero;
}
return Win32Window.DefSubclassProc(hWnd, message, wParam, lParam);
}
private void DisposeSubclassing()
{
try
{
if (_subclassProc != null && _windowHandle != IntPtr.Zero)
{
Win32Window.RemoveWindowSubclass(_windowHandle, _subclassProc, SubclassId);
_subclassProc = null;
}
}
catch (Exception ex)
{
AppLogger.LogException(ex, "WindowSubclass_Dispose");
}
}
private async Task ShowErrorAsync(string title, string message)
{
var dialog = new ContentDialog
{
Title = title,
Content = message,
CloseButtonText = "Close",
XamlRoot = RootGrid.XamlRoot
};
await dialog.ShowAsync();
}
}