-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
404 lines (360 loc) · 15.7 KB
/
Copy pathMainWindow.xaml.cs
File metadata and controls
404 lines (360 loc) · 15.7 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
using MahApps.Metro.Controls;
using MahApps.Metro.Controls.Dialogs;
using ServiceStack.Text;
using SourceChord.Lighty;
using System;
using System.ComponentModel;
using System.Globalization;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
using WPFLocalizeExtension.Engine;
namespace PSO2ModManager
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : MetroWindow, INotifyPropertyChanged {
#region INotifyPropertyChanged Implementation
/// <summary>
/// Occurs when a property value changes.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Raises a new <see cref="E:INotifyPropertyChanged.PropertyChanged"/> event.
/// </summary>
/// <param name="propertyName">The name of the property that changed.</param>
protected void RaisePropertyChanged (string propertyName) {
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
public ModManager Mods { get; set; }
public ModPresenter SelectedPresenter { get; set; } = new ModPresenter();
private DispatcherTimer updatesTimer;
private InlineDialog d;
private string CurrentPageTitle;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "System.Windows.MessageBox.Show(System.String,System.String)")]
public MainWindow() {
// Initilalize Inline Dialog
d = InlineDialog.Instance();
LocalizeDictionary.Instance.Culture = new CultureInfo(App.locale);
// Initialize Mod Manager
if (ModManager.CheckForSettings()) {
Mods = new ModManager();
} else {
MessageBox.Show(Helpers._("Dialog.Welcome"),
Helpers._("Dialog.WelcomeTitle"));
Mods = new ModManager (GetPSO2Dir());
}
InitializeComponent();
Mods.OnSelectionChanged += ModChanged;
ValidateUrlInput();
// For some reason RegisterJsObject doesn't work so we're stream a json object
// to the page title, once we have a new download action.
Browser.TitleChanged += Browser_TitleChanged;
Browser.BrowserSettings.AcceptLanguageList = App.locale;
Browser.Address = String.Format(CultureInfo.InvariantCulture, "http://pso2mod.com/?app={0}&lang={1}", "true", App.locale.Substring (0, 2));
}
/// <summary>
/// Callback to update the Download progressbar.
/// </summary>
public void DownloadProgress(object sender, System.Net.DownloadProgressChangedEventArgs e) {
d.UpdateProgressDialogValue (Convert.ToDouble(e.ProgressPercentage * 0.01));
}
/// <summary>
/// Starts a mod download.
/// </summary>
private async Task DownloadMod (string url) {
if (Mods.Downloading) {
await d.PromptAsync (Helpers._ ("Error.Title"), Helpers._ ("Error.MultipleDownloadProcess"));
return;
}
// Add Event handler
Mods.OnDownloadStart += DownloadStart;
Mods.OnDownloadPercentPercentChanged += DownloadProgress;
Mods.OnDownloadComplete += DownloadComplete;
// Download progress
await Mods.DownloadMod (url);
// Remove Event Handler
Mods.OnDownloadPercentPercentChanged -= DownloadProgress;
Mods.OnDownloadComplete -= DownloadComplete;
Mods.OnDownloadStart -= DownloadStart;
}
private async void DownloadStart (object sender, EventArgs e) {
await d.OpenProgressDialog (Helpers._ ("Dialog.WaitTitle"), Helpers._ ("Dialog.Downloading"));
}
/// <summary>
/// Updates a mod
/// </summary>
private async void UpdateSelectedMod() {
await Mods.UpdateMod();
}
/// <summary>
/// Callback when the download progress
/// </summary>
private async void DownloadComplete(object sender, EventArgs e)
{
dynamic u = (ModManager.OnDownloadCompleteArgs)e;
bool Success = false;
string ErrorMessage = null;
if (u != null) {
Success = u.Success;
ErrorMessage = u.ErrorMessage;
} else {
return;
}
if (!Success) {
await d.PromptAsync (Helpers._("Error.DownloadingTitle"), ErrorMessage);
} else {
InstalledModsTab.Focus();
}
DownloadUrlTextbox.Text = "";
ValidateUrlInput();
await d.CloseProgressDialog();
}
/// <summary>
/// Kinda validates the url.
/// </summary>
private void ValidateUrlInput() {
if (String.IsNullOrEmpty(DownloadUrlTextbox.Text) || !DownloadUrlTextbox.Text.ToUpperInvariant().StartsWith("http://", StringComparison.Ordinal)) {
DownloadModBtn.IsEnabled = false;
} else {
DownloadModBtn.IsEnabled = true;
}
}
/// <summary>
/// Shows a Folderbrowser dialog and gets PSO2 Directory, if it fails it closes the application.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "System.Windows.Forms.FolderBrowserDialog.set_SelectedPath(System.String)")]
public string GetPSO2Dir() {
string folderPath = "";
while (!Helpers.ValidatePSO2Dir (folderPath)) {
dynamic fbd = new System.Windows.Forms.FolderBrowserDialog
{
Description = Helpers._("Select the pso2 data/win32 directory"),
RootFolder = Environment.SpecialFolder.MyComputer,
SelectedPath = Helpers.DetectPSODir() + "\\data\\win32",
ShowNewFolderButton = false
};
if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
folderPath = fbd.SelectedPath;
} else {
Environment.Exit (1);
}
if (!Helpers.ValidatePSO2Dir (folderPath)) {
MessageBox.Show(Helpers._("This doesn't looks like the pso2 data/win32 folder. Try again"), Helpers._("Error"));
}
}
return folderPath;
}
/// <summary>
/// Updates the mod presenter when the selected mod changes.
/// </summary>
public void ModChanged(object sender, EventArgs e)
{
SelectedPresenter.Setup (Mods.SelectedMod, Mods.IsInstalled (Mods.SelectedMod));
}
/// <summary>
/// Event hook that enables the updates button after
/// certain time passes, and stops the time.
/// </summary>
private void ReenableUpdates (object sender, EventArgs e) {
updatesTimer.Stop();
CheckForUpdatesBtn.IsEnabled = true;
}
/// <summary>
/// Asks the mod manager to check for updates
/// </summary>
private async void CheckForUpdates() {
await d.OpenProgressDialog (Helpers._ ("Dialog.WaitTitle"), Helpers._ ("Dialog.CheckingUpdate"));
Mods.OnError += UpdateCheckError;
bool success = await Mods.CheckForUpdates();
Mods.OnError -= UpdateCheckError;
if (success) {
CheckForUpdatesBtn.IsEnabled = false;
updatesTimer = new System.Windows.Threading.DispatcherTimer();
updatesTimer.Tick += new EventHandler (ReenableUpdates);
updatesTimer.Interval = new TimeSpan (0, 5, 0);
updatesTimer.Start();
await d.CloseProgressDialog();
}
}
private async void UpdateCheckError(object sender, EventArgs e)
{
dynamic u = (ModManager.OnErrorArgs)e;
String Message = "";
if (u != null)
{
Message = u.Message;
}
await d.PromptAsync (Helpers._ ("Error.CheckingUpdate"), Message);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "System.Windows.Forms.FileDialog.set_Filter(System.String)")]
private void FindAndInstallMod() {
System.Windows.Forms.OpenFileDialog fd = new System.Windows.Forms.OpenFileDialog
{
// Set filter options and filter index.
Filter = Helpers._("FileDialog.Filter") + " (.zip)|*.zip",
FilterIndex = 1,
Multiselect = true
};
// Process input if the user clicked OK.
if (fd.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
Mods.AddLocalMod (fd.FileName);
InstalledModsTab.Focus();
}
}
#region Input Events
private void DownloadUrlTextbox_TextChanged (object sender, TextChangedEventArgs e) {
ValidateUrlInput();
}
private async void DownloadModBtn_Click (object sender, RoutedEventArgs e) {
await DownloadMod (DownloadUrlTextbox.Text);
}
private void CheckForUpdatesBtn_Click (object sender, RoutedEventArgs e) {
CheckForUpdates();
}
private void InstallUninstallBtn_Click (object sender, RoutedEventArgs e) {
Mods.ToggleMod();
}
private void AvailableModsList_SelectionChanged (object sender, SelectionChangedEventArgs e) {
if (e.AddedItems.Count > 0) {
Mods.SelectedMod = (Mod) e.AddedItems[0];
}
}
private void InstalledModsList_SelectionChanged (object sender, SelectionChangedEventArgs e) {
if (e.AddedItems.Count > 0) {
Mods.SelectedMod = (Mod) e.AddedItems[0];
}
}
private void DeleteBtn_Click (object sender, RoutedEventArgs e) {
Mods.Delete();
}
private void UpdateBtn_Click (object sender, RoutedEventArgs e) {
UpdateSelectedMod();
}
private void ViewSiteBtn_Click (object sender, RoutedEventArgs e) {
//string url = "http://pso2mod.com/?lang={1}&p={0}";
string url = "http://pso2mod.com/?p={0}";
System.Diagnostics.Process.Start(String.Format(CultureInfo.InvariantCulture, url, SelectedPresenter.Id));
}
private async void Browser_TitleChanged (object sender, DependencyPropertyChangedEventArgs e) {
if (CurrentPageTitle == e.NewValue.ToString()) return;
CurrentPageTitle = e.NewValue.ToString();
DownloadAction duh = new DownloadAction
{
Url = "http://google.com"
};
try {
JsonSerializer.SerializeToString<DownloadAction> (duh);
DownloadAction da = JsonSerializer.DeserializeFromString<DownloadAction> (CurrentPageTitle);
if (da.Url != null) {
await DownloadMod (da.Url);
}
} catch {
// Not valid json: Note it would be better to just run a json validation method,
// but there doesn't seem to be anything on servicestack.text for that
}
}
private void InstallLocalModBtn_Click (object sender, RoutedEventArgs e) {
FindAndInstallMod();
}
/// <summary>
/// Toggle Setting Flyout
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void SettingBtn_Click (object sender, RoutedEventArgs e) {
settingsFlyout.IsOpen = !settingsFlyout.IsOpen;
}
#endregion Input Events
/// <summary>
/// Show Thumnail
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ModImage_MouseDown (object sender, System.Windows.Input.MouseButtonEventArgs e) {
// show FrameworkElement.
var image = new Image
{
Source = ModImage.Source
};
LightBox.Show (this, image);
}
/// <summary>
/// Show ProgressRing and URL in Build-in WebBrowser
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Browser_LoadingStateChanged (object sender, CefSharp.LoadingStateChangedEventArgs e) {
if (e.IsLoading) {
this.Dispatcher.Invoke (() => {
ProgressRing.Visibility = Visibility.Visible;
StatusBarText.Content = "Now Loading...";
});
} else {
this.Dispatcher.Invoke (() => {
ProgressRing.Visibility = Visibility.Hidden;
StatusBarText.Content = Browser.Address;
});
}
}
#region DialogTask
private sealed class InlineDialog {
// Singleton
private static readonly InlineDialog _singleInstance = new InlineDialog();
// Progress Dialog Object
public ProgressDialogController ProgressDlgCtl;
// Parent Window
private MainWindow w;
// Check Multiple Dialog
private bool multiple;
/// <summary>
/// Constructor
/// </summary>
private InlineDialog() {
w = (MainWindow) App.Current.MainWindow;
}
/// <summary>
/// Get Instance
/// </summary>
/// <returns></returns>
public static InlineDialog Instance() {
return _singleInstance;
}
/// <summary>
/// Show Message Box
/// </summary>
/// <param name="title"></param>
/// <param name="message"></param>
/// <param name="style"></param>
/// <param name="settings"></param>
/// <returns></returns>
public async Task<MessageDialogResult> PromptAsync (string title, string message, MessageDialogStyle style = MessageDialogStyle.Affirmative, MetroDialogSettings settings = null) {
return await w.ShowMessageAsync (title, message, style, settings);
}
public async Task OpenProgressDialog (string title, string message, bool isCancellable = false) {
Console.WriteLine ("Open Progress Dialog.");
if (multiple) return;
ProgressDlgCtl = await w.ShowProgressAsync (title, message, isCancellable) as ProgressDialogController;
ProgressDlgCtl.SetIndeterminate();
multiple = true;
}
public async Task CloseProgressDialog (bool continueOnCaptureContext = false) {
await ProgressDlgCtl.CloseAsync().ConfigureAwait (continueOnCaptureContext);
multiple = false;
Console.WriteLine ("Close Progress Dialog.");
}
public void UpdateProgressDialogValue (double value) {
ProgressDlgCtl.SetProgress (value);
}
}
#endregion
private void MainTab_SelectionChanged (object sender, SelectionChangedEventArgs e) {
if (MainTab.SelectedIndex == 0) {
StatusBarText.Content = "PSO2 Mod Manager";
}
}
}
}