forked from fdorg/flashdevelop
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainForm.cs
More file actions
1325 lines (1248 loc) · 49.5 KB
/
Copy pathMainForm.cs
File metadata and controls
1325 lines (1248 loc) · 49.5 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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.IO;
using System.Net;
using System.Data;
using System.Text;
using System.Drawing;
using System.Threading;
using System.Reflection;
using System.Diagnostics;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Xml.Serialization;
using System.ComponentModel;
using AppMan.Utilities;
namespace AppMan
{
public partial class MainForm : Form, IMessageFilter
{
private String curFile;
private String tempFile;
private String localeId;
private Boolean isLoading;
private DepEntry curEntry;
private String entriesFile;
private WebClient webClient;
private DepEntries depEntries;
private DepEntries instEntries;
private BackgroundWorker bgWorker;
private Dictionary<String, String> entryStates;
private Dictionary<String, ListViewGroup> appGroups;
private Queue<DepEntry> downloadQueue;
private Queue<String> fileQueue;
private LocaleData localeData;
private Boolean localeOverride;
private String[] notifyPaths;
private Boolean shouldNotify;
private Boolean haveUpdates;
private Boolean checkOnly;
public MainForm(String[] args)
{
this.CheckArgs(args);
this.isLoading = false;
this.haveUpdates = false;
this.shouldNotify = false;
this.InitializeSettings();
this.InitializeLocalization();
this.InitializeComponent();
this.InitializeGraphics();
this.InitializeContextMenu();
this.ApplyLocalizationStrings();
this.Font = SystemFonts.MenuFont;
Application.AddMessageFilter(this);
}
#region WIN32 Stuff
#if WIN32
[DllImport("user32.dll")]
public static extern IntPtr WindowFromPoint(Point pt);
[DllImport("user32.dll")]
public static extern IntPtr SendMessage(IntPtr hWnd, Int32 msg, IntPtr wp, IntPtr lp);
#endif
#endregion
#region Initialization
/// <summary>
/// Processes command line args.
/// </summary>
private void CheckArgs(String[] args)
{
this.checkOnly = false;
this.localeId = "en_US";
this.localeOverride = false;
foreach (String arg in args)
{
// Handle minimized mode
if (arg.Trim() == "-minimized")
{
this.WindowState = FormWindowState.Minimized;
this.checkOnly = true;
}
// Handle locale id values
if (arg.Trim().Contains("-locale="))
{
this.localeId = arg.Trim().Substring("-locale=".Length);
this.localeOverride = true;
}
}
}
/// <summary>
/// Initializes the graphics of the app.
/// </summary>
private void InitializeGraphics()
{
Assembly assembly = Assembly.GetExecutingAssembly();
this.cancelButton.Image = Image.FromStream(assembly.GetManifestResourceStream("AppMan.Resources.Cancel.png"));
this.Icon = new Icon(assembly.GetManifestResourceStream("AppMan.Resources.AppMan.ico"));
}
/// <summary>
/// Initializes the web client used for item downloads.
/// </summary>
private void InitializeWebClient()
{
this.webClient = new WebClient();
this.webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(this.DownloadProgressChanged);
this.webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(this.DownloadFileCompleted);
}
/// <summary>
/// Initializes the localization of the app.
/// </summary>
private void InitializeLocalization()
{
this.localeData = new LocaleData();
String localeDir = Path.Combine(PathHelper.GetExeDirectory(), "Locales");
String localeFile = Path.Combine(PathHelper.GetExeDirectory(), this.localeId + ".xml");
if (File.Exists(localeFile))
{
this.localeData = ObjectSerializer.Deserialize(localeFile, this.localeData) as LocaleData;
}
}
/// <summary>
/// Applies the localization string to controls.
/// </summary>
private void ApplyLocalizationStrings()
{
this.Text = this.localeData.MainFormTitle;
this.exploreButton.Text = this.localeData.ExploreLabel;
this.nameHeader.Text = this.localeData.NameHeader;
this.descHeader.Text = this.localeData.DescHeader;
this.statusHeader.Text = this.localeData.StatusHeader;
this.versionHeader.Text = this.localeData.VersionHeader;
this.typeHeader.Text = this.localeData.TypeHeader;
this.allLinkLabel.Text = this.localeData.LinkAll;
this.newLinkLabel.Text = this.localeData.LinkNew;
this.noneLinkLabel.Text = this.localeData.LinkNone;
this.instLinkLabel.Text = this.localeData.LinkInstalled;
this.updateLinkLabel.Text = this.localeData.LinkUpdates;
this.statusLabel.Text = this.localeData.NoItemsSelected;
this.pathLabel.Text = this.localeData.InstallPathLabel;
this.selectLabel.Text = this.localeData.SelectLabel;
this.installButton.Text = String.Format(this.localeData.InstallSelectedLabel, "0");
this.deleteButton.Text = String.Format(this.localeData.DeleteSelectedLabel, "0");
}
/// <summary>
/// Initializes the settings of the app.
/// </summary>
private void InitializeSettings()
{
try
{
Settings settings = new Settings();
String file = Path.Combine(PathHelper.GetExeDirectory(), "Config.xml");
if (File.Exists(file))
{
settings = ObjectSerializer.Deserialize(file, settings) as Settings;
PathHelper.APPS_DIR = ArgProcessor.ProcessArguments(settings.Archive);
PathHelper.CONFIG_ADR = ArgProcessor.ProcessArguments(settings.Config);
PathHelper.HELP_ADR = ArgProcessor.ProcessArguments(settings.Help);
if (!this.localeOverride) this.localeId = settings.Locale;
this.notifyPaths = settings.Paths;
}
#if FLASHDEVELOP
else /* Defaults for FlashDevelop */
{
PathHelper.HELP_ADR = "http://www.flashdevelop.org/wikidocs/";
PathHelper.CONFIG_ADR = "http://www.flashdevelop.org/appman.xml";
String local = Path.Combine(PathHelper.GetExeDirectory(), @"..\..\.local");
local = Path.GetFullPath(local); /* Fix weird path */
if (!File.Exists(local))
{
String userAppDir = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
String fdUserPath = Path.Combine(userAppDir, "FlashDevelop");
String appManDataDir = Path.Combine(fdUserPath, @"Data\AppMan");
this.notifyPaths = new String[1] { fdUserPath };
PathHelper.APPS_DIR = Path.Combine(fdUserPath, "Apps");
PathHelper.LOG_DIR = appManDataDir;
}
else
{
String fdPath = Path.Combine(PathHelper.GetExeDirectory(), @"..\..\");
fdPath = Path.GetFullPath(fdPath); /* Fix weird path */
PathHelper.APPS_DIR = Path.Combine(fdPath, "Apps");
PathHelper.LOG_DIR = Path.Combine(fdPath, @"Data\AppMan");
this.notifyPaths = new String[1] { fdPath };
}
}
#endif
if (!Directory.Exists(PathHelper.LOG_DIR))
{
Directory.CreateDirectory(PathHelper.LOG_DIR);
}
if (!Directory.Exists(PathHelper.APPS_DIR))
{
Directory.CreateDirectory(PathHelper.APPS_DIR);
}
}
catch (Exception ex)
{
DialogHelper.ShowError(ex.ToString());
}
}
/// <summary>
/// Initializes the list view context menu.
/// </summary>
private void InitializeContextMenu()
{
ContextMenuStrip cms = new ContextMenuStrip();
cms.Items.Add(this.localeData.ShowInfoLabel, null, new EventHandler(this.OnViewInfoClick));
cms.Items.Add(this.localeData.ToggleCheckedLabel, null, new EventHandler(this.OnCheckToggleClick));
this.listView.ContextMenuStrip = cms;
}
#endregion
#region Key Handling
/// <summary>
/// Closes the application when pressing Escape.
/// </summary>
protected override Boolean ProcessCmdKey(ref Message msg, Keys k)
{
if (k == Keys.Escape)
{
this.Close();
return true;
}
return base.ProcessCmdKey(ref msg, k);
}
#endregion
#region Event Handlers
/// <summary>
/// On MainForm show, initializes the UI and the props.
/// </summary>
private void MainFormLoad(Object sender, EventArgs e)
{
this.InitializeWebClient();
this.depEntries = new DepEntries();
this.entryStates = new Dictionary<String, String>();
this.appGroups = new Dictionary<String, ListViewGroup>();
this.downloadQueue = new Queue<DepEntry>();
this.TryDeleteOldTempFiles();
this.listView.Items.Clear();
this.LoadInstalledEntries();
this.LoadEntriesFile();
}
/// <summary>
/// Opens the help when pressing help button or F1.
/// </summary>
private void MainFormHelpRequested(Object sender, HelpEventArgs e)
{
try
{
Process.Start(PathHelper.HELP_ADR);
}
catch (Exception ex)
{
DialogHelper.ShowError(ex.ToString());
}
}
private void MainFormHelpButtonClicked(Object sender, CancelEventArgs e)
{
e.Cancel = true;
this.MainFormHelpRequested(null, null);
}
/// <summary>
/// Save notification files to the notify paths
/// </summary>
private void MainFormClosed(Object sender, FormClosedEventArgs e)
{
try
{
if (!this.shouldNotify || this.notifyPaths == null) return;
foreach (String nPath in this.notifyPaths)
{
try
{
String path = Path.GetFullPath(ArgProcessor.ProcessArguments(nPath));
if (Directory.Exists(path))
{
String amFile = Path.Combine(path, ".appman");
File.WriteAllText(amFile, "");
}
}
catch { /* NO ERRORS */ }
}
}
catch (Exception ex)
{
DialogHelper.ShowError(ex.ToString());
}
}
/// <summary>
/// Open info file or url when clicked.
/// </summary>
private void OnViewInfoClick(Object sender, EventArgs e)
{
if (this.listView.SelectedItems.Count > 0)
{
ListViewItem item = this.listView.SelectedItems[0];
if (item != null)
{
DepEntry entry = item.Tag as DepEntry;
if (entry != null && !String.IsNullOrEmpty(entry.Info))
{
this.RunExecutableProcess(entry.Info);
}
}
}
}
/// <summary>
/// Toggles the check state of the item.
/// </summary>
private void OnCheckToggleClick(Object sender, EventArgs e)
{
if (this.listView.SelectedItems.Count > 0)
{
ListViewItem item = this.listView.SelectedItems[0];
if (item != null) item.Checked = !item.Checked;
}
}
/// <summary>
/// Cancels the item download process.
/// </summary>
private void CancelButtonClick(Object sender, EventArgs e)
{
try
{
this.webClient.CancelAsync();
}
catch (Exception ex)
{
DialogHelper.ShowError(ex.ToString());
}
}
/// <summary>
/// Starts the download queue based on the user selections.
/// </summary>
private void InstallButtonClick(Object sender, EventArgs e)
{
this.isLoading = true;
this.cancelButton.Enabled = true;
this.installButton.Enabled = false;
this.deleteButton.Enabled = false;
this.AddEntriesToQueue();
this.DownloadNextFromQueue();
}
/// <summary>
/// Deletes the selected items from the archive.
/// </summary>
private void DeleteButtonClick(Object sender, EventArgs e)
{
try
{
this.shouldNotify = true;
String title = this.localeData.ConfirmTitle;
String message = this.localeData.DeleteSelectedConfirm;
if (MessageBox.Show(message, title, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
foreach (ListViewItem item in this.listView.CheckedItems)
{
DepEntry entry = item.Tag as DepEntry;
String state = this.entryStates[entry.Id];
if (state == this.localeData.StateInstalled || state == this.localeData.StateUpdate)
{
#if FLASHDEVELOP
if (entry.Urls[0].ToLower().EndsWith(".fdz"))
{
String fileName = Path.GetFileName(entry.Urls[0]);
String delFile = Path.ChangeExtension(fileName, ".delete.fdz");
String tempFile = this.GetTempFileName(delFile, true);
String entryDir = Path.Combine(PathHelper.APPS_DIR, entry.Id);
String versionDir = Path.Combine(entryDir, entry.Version.ToLower());
String entryFile = Path.Combine(versionDir, fileName);
File.Copy(entryFile, tempFile, true);
this.RunExecutableProcess(tempFile);
}
#endif
String folder = Path.Combine(PathHelper.APPS_DIR, entry.Id);
// Sometimes we might get "dir not empty" error, try 10 times...
for (Int32 attempts = 0; attempts < 10; attempts++)
{
try
{
if (Directory.Exists(folder)) Directory.Delete(folder, true);
return;
}
catch (IOException) { Thread.Sleep(50); }
}
throw new Exception("Could not delete the directory:\n" + folder);
}
}
}
}
catch (Exception ex)
{
DialogHelper.ShowError(ex.ToString());
}
finally
{
Thread.Sleep(100); // Wait for files...
this.NoneLinkLabelLinkClicked(null, null);
this.LoadInstalledEntries();
this.UpdateEntryStates();
this.UpdateButtonLabels();
}
}
/// <summary>
/// Browses the archive with windows explorer.
/// </summary>
private void ExploreButtonClick(Object sender, EventArgs e)
{
try
{
Process.Start("explorer.exe", PathHelper.APPS_DIR);
}
catch (Exception ex)
{
DialogHelper.ShowError(ex.ToString());
}
}
/// <summary>
/// On All link click, selects the all items.
/// </summary>
private void AllLinkLabelLinkClicked(Object sender, LinkLabelLinkClickedEventArgs e)
{
if (this.isLoading) return;
this.listView.BeginUpdate();
foreach (ListViewItem item in this.listView.Items)
{
item.Checked = true;
}
this.listView.EndUpdate();
}
/// <summary>
/// On None link click, deselects all items.
/// </summary>
private void NoneLinkLabelLinkClicked(Object sender, LinkLabelLinkClickedEventArgs e)
{
if (this.isLoading) return;
this.listView.BeginUpdate();
foreach (ListViewItem item in this.listView.Items)
{
item.Checked = false;
}
this.listView.EndUpdate();
}
/// <summary>
/// On New link click, selects all new items.
/// </summary>
private void NewLinkLabelLinkClicked(Object sender, LinkLabelLinkClickedEventArgs e)
{
try
{
if (this.isLoading) return;
this.listView.BeginUpdate();
foreach (ListViewItem item in this.listView.Items)
{
DepEntry entry = item.Tag as DepEntry;
String state = this.entryStates[entry.Id];
if (state == this.localeData.StateNew) item.Checked = true;
else item.Checked = false;
}
this.listView.EndUpdate();
}
catch (Exception ex)
{
DialogHelper.ShowError(ex.ToString());
}
}
/// <summary>
/// On Installed link click, selects all installed items.
/// </summary>
private void InstLinkLabelLinkClicked(Object sender, LinkLabelLinkClickedEventArgs e)
{
try
{
if (this.isLoading) return;
this.listView.BeginUpdate();
foreach (ListViewItem item in this.listView.Items)
{
DepEntry entry = item.Tag as DepEntry;
String state = this.entryStates[entry.Id];
if (state == this.localeData.StateInstalled) item.Checked = true;
else item.Checked = false;
}
this.listView.EndUpdate();
}
catch (Exception ex)
{
DialogHelper.ShowError(ex.ToString());
}
}
/// <summary>
/// On Updates link click, selects all updatable items.
/// </summary>
private void UpdatesLinkLabelLinkClicked(Object sender, LinkLabelLinkClickedEventArgs e)
{
try
{
if (this.isLoading) return;
this.listView.BeginUpdate();
foreach (ListViewItem item in this.listView.Items)
{
DepEntry entry = item.Tag as DepEntry;
String state = this.entryStates[entry.Id];
if (state == this.localeData.StateUpdate) item.Checked = true;
else item.Checked = false;
}
this.listView.EndUpdate();
}
catch (Exception ex)
{
DialogHelper.ShowError(ex.ToString());
}
}
/// <summary>
/// Disables the item checking when downloading.
/// </summary>
private void ListViewItemCheck(Object sender, ItemCheckEventArgs e)
{
if (this.isLoading) e.NewValue = e.CurrentValue;
}
/// <summary>
/// Updates the button labels when item is checked.
/// </summary>
private void ListViewItemChecked(Object sender, ItemCheckedEventArgs e)
{
if (this.isLoading) return;
this.UpdateButtonLabels();
}
/// <summary>
/// Handles the mouse wheel on hover
/// </summary>
public Boolean PreFilterMessage(ref Message m)
{
#if WIN32
if (m.Msg == 0x20a) // WM_MOUSEWHEEL
{
Point pos = new Point(m.LParam.ToInt32() & 0xffff, m.LParam.ToInt32() >> 16);
IntPtr hWnd = WindowFromPoint(pos);
if (hWnd != IntPtr.Zero)
{
if (Control.FromHandle(hWnd) != null)
{
SendMessage(hWnd, m.Msg, m.WParam, m.LParam);
return true;
}
else if (this.listView != null && hWnd == this.listView.Handle)
{
SendMessage(hWnd, m.Msg, m.WParam, m.LParam);
return true;
}
}
}
#endif
return false;
}
#endregion
#region Utility Methods
/// <summary>
/// Completes the minimized update process.
/// </summary>
private void CompleteMinimizedProcess()
{
if (this.checkOnly)
{
if (this.haveUpdates)
{
this.WindowState = FormWindowState.Normal;
this.Activate();
}
else Application.Exit();
}
}
/// <summary>
/// Updates the buttons labels.
/// </summary>
private void UpdateButtonLabels()
{
try
{
Int32 inst = 0;
Int32 dele = 0;
if (this.isLoading) return;
foreach (ListViewItem item in this.listView.CheckedItems)
{
DepEntry entry = item.Tag as DepEntry;
if (this.entryStates.ContainsKey(entry.Id))
{
String state = this.entryStates[entry.Id];
if (state == this.localeData.StateInstalled || state == this.localeData.StateUpdate) dele++;
if (state == this.localeData.StateNew || state == this.localeData.StateUpdate) inst++;
}
}
this.installButton.Text = String.Format(this.localeData.InstallSelectedLabel, inst);
this.deleteButton.Text = String.Format(this.localeData.DeleteSelectedLabel, dele);
this.deleteButton.Enabled = dele > 0;
this.installButton.Enabled = inst > 0;
}
catch (Exception ex)
{
DialogHelper.ShowError(ex.ToString());
}
}
/// <summary>
/// Populates the list view with current entries.
/// </summary>
private void PopulateListView()
{
try
{
this.listView.BeginUpdate();
this.pathTextBox.Text = PathHelper.APPS_DIR;
foreach (DepEntry entry in this.depEntries)
{
ListViewItem item = new ListViewItem(entry.Name);
item.Tag = entry; /* Store for later */
item.SubItems.Add(entry.Version);
item.SubItems.Add(entry.Desc);
item.SubItems.Add(this.localeData.StateNew);
item.SubItems.Add(this.IsExecutable(entry) ? this.localeData.ExecutableType : this.localeData.ArchiveType);
this.listView.Items.Add(item);
this.AddToGroup(item);
}
if (this.appGroups.Count > 1) this.listView.ShowGroups = true;
else this.listView.ShowGroups = false;
this.UpdateEntryStates();
this.listView.EndUpdate();
}
catch (Exception ex)
{
DialogHelper.ShowError(ex.ToString());
}
}
/// <summary>
/// Adds the entry into a new or existing group.
/// </summary>
private void AddToGroup(ListViewItem item)
{
try
{
DepEntry entry = item.Tag as DepEntry;
if (this.appGroups.ContainsKey(entry.Group))
{
ListViewGroup lvg = this.appGroups[entry.Group];
item.Group = lvg;
}
else
{
ListViewGroup lvg = new ListViewGroup(entry.Group);
this.appGroups[entry.Group] = lvg;
this.listView.Groups.Add(lvg);
item.Group = lvg;
}
}
catch (Exception ex)
{
DialogHelper.ShowError(ex.ToString());
}
}
/// <summary>
/// Creates a temporary file with the given extension.
/// </summary>
private String GetTempFileName(String file, Boolean unique)
{
try
{
Int32 counter = 0;
String tempDir = Path.GetTempPath();
String fileName = Path.GetFileName(file);
String tempFile = Path.Combine(tempDir, "appman_" + fileName);
if (!unique) return tempFile;
while (File.Exists(tempFile))
{
counter++;
tempFile = Path.Combine(tempDir, "appman_" + counter + "_" + fileName);
}
return tempFile;
}
catch (Exception ex)
{
DialogHelper.ShowError(ex.ToString());
return null;
}
}
/// <summary>
/// Tries to delete old temp files.
/// </summary>
private void TryDeleteOldTempFiles()
{
String path = Path.GetTempPath();
String[] oldFiles = Directory.GetFiles(path, "appman_*.*");
foreach (String file in oldFiles)
{
try { File.Delete(file); }
catch { /* NO ERRORS */ }
}
}
/// <summary>
/// Runs an executable process.
/// </summary>
private void RunExecutableProcess(String file)
{
try
{
#if FLASHDEVELOP
if (file.ToLower().EndsWith(".fdz"))
{
String fd = Path.Combine(PathHelper.GetExeDirectory(), @"..\..\FlashDevelop.exe");
Process.Start(Path.GetFullPath(fd), file + " -silent -reuse");
return;
}
#endif
Process.Start(file);
}
catch (Exception ex)
{
DialogHelper.ShowError(ex.ToString());
}
}
/// <summary>
/// Checks if entry is an executable.
/// </summary>
private Boolean IsExecutable(DepEntry entry)
{
return entry.Type == this.localeData.ExecutableType;
}
#endregion
#region Entry Management
/// <summary>
/// Downloads the entry config file.
/// </summary>
private void LoadEntriesFile()
{
try
{
if (PathHelper.CONFIG_ADR.StartsWith("http"))
{
WebClient client = new WebClient();
this.entriesFile = Path.GetTempFileName();
client.DownloadFileCompleted += new AsyncCompletedEventHandler(this.EntriesDownloadCompleted);
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(this.DownloadProgressChanged);
client.DownloadFileAsync(new Uri(PathHelper.CONFIG_ADR), this.entriesFile);
this.statusLabel.Text = this.localeData.DownloadingItemList;
}
else
{
this.entriesFile = PathHelper.CONFIG_ADR;
Object data = ObjectSerializer.Deserialize(this.entriesFile, this.depEntries);
this.statusLabel.Text = this.localeData.ItemListOpened;
this.depEntries = data as DepEntries;
this.PopulateListView();
}
}
catch (Exception ex)
{
DialogHelper.ShowError(ex.ToString());
}
finally
{
this.CompleteMinimizedProcess();
}
}
/// <summary>
/// When entry config is loaded, populates the list view.
/// </summary>
private void EntriesDownloadCompleted(Object sender, AsyncCompletedEventArgs e)
{
try
{
Boolean fileExists = File.Exists(this.entriesFile);
Boolean fileIsValid = File.ReadAllText(this.entriesFile).Length > 0;
if (e.Error == null && fileExists && fileIsValid)
{
this.statusLabel.Text = this.localeData.DownloadedItemList;
Object data = ObjectSerializer.Deserialize(this.entriesFile, this.depEntries);
this.depEntries = data as DepEntries;
this.PopulateListView();
}
else this.statusLabel.Text = this.localeData.ItemListDownloadFailed;
this.progressBar.Value = 0;
}
catch (Exception ex)
{
DialogHelper.ShowError(ex.ToString());
}
finally
{
this.CompleteMinimizedProcess();
try { File.Delete(this.entriesFile); }
catch { /* NO ERRORS*/ }
}
}
/// <summary>
/// Adds the currently selected entries to download queue.
/// </summary>
private void AddEntriesToQueue()
{
try
{
this.downloadQueue.Clear();
foreach (ListViewItem item in this.listView.CheckedItems)
{
DepEntry entry = item.Tag as DepEntry;
String state = this.entryStates[entry.Id];
if (state == this.localeData.StateNew || state == this.localeData.StateUpdate)
{
this.downloadQueue.Enqueue(entry);
}
}
}
catch (Exception ex)
{
DialogHelper.ShowError(ex.ToString());
}
}
/// <summary>
/// Downloads next item from the queue.
/// </summary>
private void DownloadNextFromQueue()
{
try
{
this.fileQueue = new Queue<String>();
this.curEntry = this.downloadQueue.Dequeue();
foreach (String file in this.curEntry.Urls)
{
this.fileQueue.Enqueue(file);
}
this.curFile = this.fileQueue.Dequeue();
this.tempFile = this.GetTempFileName(this.curFile, false);
this.curEntry.Temps[this.curFile] = this.tempFile; // Save for cmd
if (File.Exists(this.tempFile)) // Use already downloaded temp...
{
String idPath = Path.Combine(PathHelper.APPS_DIR, this.curEntry.Id);
String vnPath = Path.Combine(idPath, this.curEntry.Version.ToLower());
this.ExtractFile(this.tempFile, vnPath);
return;
}
this.tempFile = this.GetTempFileName(this.curFile, true);
this.curEntry.Temps[this.curFile] = this.tempFile; // Save for cmd
this.webClient.DownloadFileAsync(new Uri(this.curFile), this.tempFile);
this.statusLabel.Text = this.localeData.DownloadingFile + this.curFile;
}
catch (Exception ex)
{
DialogHelper.ShowError(ex.ToString());
}
}
/// <summary>
/// Updates the progress bar for individual downloads.
/// </summary>
private void DownloadProgressChanged(Object sender, DownloadProgressChangedEventArgs e)
{
this.progressBar.Value = e.ProgressPercentage;
}
/// <summary>
/// When file is downloaded, check for errors and extract the file.
/// </summary>
private void DownloadFileCompleted(Object sender, AsyncCompletedEventArgs e)
{
try
{
if (e.Cancelled)
{
this.isLoading = false;
this.cancelButton.Enabled = false;
this.statusLabel.Text = this.localeData.ItemListDownloadCancelled;
this.TryDeleteOldTempFiles();
this.progressBar.Value = 0;
this.UpdateButtonLabels();
}
else if (e.Error == null)
{
String idPath = Path.Combine(PathHelper.APPS_DIR, this.curEntry.Id);
String vnPath = Path.Combine(idPath, this.curEntry.Version.ToLower());
this.ExtractFile(this.tempFile, vnPath);
}
else
{
String message = this.localeData.DownloadingError + this.curFile + ".\n";
if (this.downloadQueue.Count > 1) message += this.localeData.ContinueWithNextItem;
DialogHelper.ShowError(message); // Show message first...
if (this.downloadQueue.Count > 1) this.DownloadNextFromQueue();
else
{
this.isLoading = false;
this.cancelButton.Enabled = false;
this.TryDeleteOldTempFiles();
this.progressBar.Value = 0;
this.UpdateButtonLabels();
}
}
}
catch (Exception ex)
{
DialogHelper.ShowError(ex.ToString());
}
}
/// <summary>
/// Starts the extraction work in a background thread.
/// </summary>
private void ExtractFile(String file, String path)
{
try
{
this.bgWorker = new BackgroundWorker();
this.bgWorker.DoWork += new DoWorkEventHandler(this.WorkerDoWork);
this.bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(this.WorkerDoCompleted);
this.bgWorker.RunWorkerAsync(new BgArg(file, path));
this.statusLabel.Text = this.localeData.ExtractingFile + this.curFile;
this.progressBar.Style = ProgressBarStyle.Marquee;
}
catch
{
String message = this.localeData.ExtractingError + this.curFile + ".\n";
if (this.downloadQueue.Count > 1) message += this.localeData.ContinueWithNextItem;
DialogHelper.ShowError(message);
this.DownloadNextFromQueue();
}
}
/// <summary>
/// Completes the actual extraction or file manipulation.
/// </summary>
private void WorkerDoWork(Object sender, DoWorkEventArgs e)
{
try
{
BgArg args = e.Argument as BgArg;
String url = new Uri(this.curFile).LocalPath;
Boolean shouldExecute = this.IsExecutable(this.curEntry);
if (!Directory.Exists(args.Path) && !shouldExecute) Directory.CreateDirectory(args.Path);
if (Path.GetExtension(url) == ".zip") ZipHelper.ExtractZip(args.File, args.Path);
else if (!shouldExecute)
{
String fileName = Path.GetFileName(url);
File.Copy(this.tempFile, Path.Combine(args.Path, fileName), true);
}
}
catch
{
DialogHelper.ShowError(this.localeData.ExtractingError + this.curFile + ".\n" + this.localeData.ContinueWithNextItem);
this.DownloadNextFromQueue();
}
}
/// <summary>
/// When file hasd been handled, continues to next file or download next item.
/// </summary>
private void WorkerDoCompleted(Object sender, RunWorkerCompletedEventArgs e)