-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Copy pathMavFTPUI.cs
635 lines (555 loc) · 23.7 KB
/
MavFTPUI.cs
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
using Ionic.Zip;
using log4net;
using MissionPlanner.ArduPilot.Mavlink;
using MissionPlanner.Utilities;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MissionPlanner.Controls
{
public partial class MavFTPUI : UserControl
{
private static readonly ILog log =
LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
private MAVLinkInterface _mav;
private MAVFtp _mavftp;
public MavFTPUI() : this(MainV2.comPort)
{
}
public MavFTPUI(MAVLinkInterface mav)
{
_mav = mav;
_mavftp = new MAVFtp(_mav, (byte)_mav.sysidcurrent, (byte)mav.compidcurrent);
_mavftp.Progress += (message, percent) =>
{
try
{
if (toolStripProgressBar1.Value == percent)
return;
if (this.IsDisposed)
{
_mavftp = null;
return;
}
this.BeginInvokeIfRequired(() =>
{
try
{
toolStripProgressBar1.Value = percent;
toolStripStatusLabel1.Text = message;
statusStrip1.Refresh();
}
catch (Exception ex)
{
log.Error(ex);
}
});
}
catch (Exception ex)
{
log.Error(ex);
}
};
InitializeComponent();
ThemeManager.ApplyThemeTo(this);
treeView1.PathSeparator = "/";
}
private async void PopulateTreeView()
{
toolStripStatusLabel1.Text = "Updating Folders";
toolStripProgressBar1.ProgressBar.Style = ProgressBarStyle.Marquee;
treeView1.BeginUpdate();
treeView1.Enabled = false;
treeView1.Nodes.Clear();
TreeNode rootNode = null;
DirectoryInfo info = new DirectoryInfo(@"/", _mavftp);
if (info.Exists)
{
rootNode = new TreeNode(info.Name, 0, 0);
rootNode.Tag = info;
await PopulateDirectories(await info.GetDirectories().ConfigureAwait(true), rootNode).ConfigureAwait(true);
treeView1.Nodes.Add(rootNode);
}
/*
info = new DirectoryInfo(@"@ROMFS/", _mavftp);
if (info.Exists)
{
rootNode = new TreeNode("@ROMFS", 0, 0);
rootNode.Tag = info;
await PopulateDirectories(await info.GetDirectories().ConfigureAwait(true), rootNode).ConfigureAwait(true);
treeView1.Nodes.Add(rootNode);
}
*/
info = new DirectoryInfo(@"@SYS/", _mavftp);
if (info.Exists)
{
rootNode = new TreeNode("@SYS", 0, 0);
rootNode.Tag = info;
await PopulateDirectories(await info.GetDirectories().ConfigureAwait(true), rootNode).ConfigureAwait(true);
treeView1.Nodes.Add(rootNode);
}
toolStripStatusLabel1.Text = "Ready";
treeView1.Enabled = true;
treeView1.EndUpdate();
toolStripProgressBar1.ProgressBar.Style = ProgressBarStyle.Blocks;
treeView1.SelectedNode = rootNode;
TreeView1_NodeMouseClick(this, new TreeNodeMouseClickEventArgs(rootNode, MouseButtons.Left, 1, 1, 1));
}
private async Task PopulateDirectories(DirectoryInfo[] subDirs,
TreeNode nodeToAddTo)
{
List<TreeNode> info = new List<TreeNode>();
TreeNode aNode;
foreach (DirectoryInfo subDir in subDirs)
{
aNode = new TreeNode(subDir.Name, 0, 0);
aNode.Tag = subDir;
aNode.ImageKey = "folder";
nodeToAddTo.Nodes.Add(aNode);
info.Add(aNode);
}
}
private async void TreeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
if (e.Node == null)
return;
TreeNode newSelected = e.Node;
listView1.Items.Clear();
DirectoryInfo nodeDirInfo = (DirectoryInfo)newSelected.Tag;
ListViewItem.ListViewSubItem[] subItems;
ListViewItem item = null;
var dirs = await nodeDirInfo.GetDirectories().ConfigureAwait(true);
newSelected.Nodes.Clear();
await PopulateDirectories(dirs, newSelected).ConfigureAwait(true);
foreach (DirectoryInfo dir in dirs)
{
item = new ListViewItem(dir.Name, 0);
subItems = new ListViewItem.ListViewSubItem[]
{
new ListViewItem.ListViewSubItem(item, "Directory"),
new ListViewItem.ListViewSubItem(item, "".ToString())
};
item.Tag = nodeDirInfo;
item.SubItems.AddRange(subItems);
listView1.Items.Add(item);
}
foreach (var file in await nodeDirInfo.GetFiles())
{
item = new ListViewItem(file.Name, 1);
subItems = new ListViewItem.ListViewSubItem[]
{
new ListViewItem.ListViewSubItem(item, "File"),
new ListViewItem.ListViewSubItem(item, file.Size.ToString())
};
item.Tag = nodeDirInfo;
item.SubItems.AddRange(subItems);
listView1.Items.Add(item);
}
try
{
listView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
}
catch
{
}
}
[Serializable]
public class DirectoryInfo : FileSystemInfo
{
private readonly MAVFtp _mavftp;
private List<MAVFtp.FtpFileInfo> cache;
public DirectoryInfo(string dir, MAVFtp mavftp)
{
_mavftp = mavftp;
FullPath = dir;
}
public override string Name
{
get { return Path.GetFileName(FullPath); }
}
public override bool Exists {
get { return true; }
}
public override void Delete()
{
_mavftp.kCmdRemoveDirectory(FullPath, new CancellationTokenSource());
}
public async Task<DirectoryInfo[]> GetDirectories()
{
try
{
// rerequest every time
await Task.Run(() =>
{
lock (_mavftp)
{
cache = _mavftp.kCmdListDirectory(FullPath, new CancellationTokenSource());
}
}).ConfigureAwait(true);
return cache.Where(a => a.isDirectory && a.Name != "." && a.Name != "..")
.Select(a => new DirectoryInfo(a.FullName, _mavftp)).ToArray();
}
catch (Exception e)
{
log.Error(e);
}
return new DirectoryInfo[] { };
}
public async Task<IEnumerable<MAVFtp.FtpFileInfo>> GetFiles()
{
try
{
if (cache == null)
await GetDirectories().ConfigureAwait(true);
// rerequest every time
return cache.Where(a => !a.isDirectory);
}
catch (Exception e)
{
log.Error(e);
}
return new List<MAVFtp.FtpFileInfo>();
}
}
private async void ListView1_DragDrop(object sender, DragEventArgs e)
{
var files = e.Data.GetData(DataFormats.FileDrop) as string[];
foreach (var file in files)
{
try
{
await UploadFile(file).ConfigureAwait(true);
}
catch (Exception exception)
{
log.Error(exception);
CustomMessageBox.Show(exception.Message);
}
}
TreeView1_NodeMouseClick(null,
new TreeNodeMouseClickEventArgs(treeView1.SelectedNode, MouseButtons.Left, 1, 1, 1));
}
private void ListView1_ColumnClick(object sender, ColumnClickEventArgs e)
{
if (listView1.Sorting == null || listView1.Sorting == SortOrder.Descending)
listView1.Sorting = SortOrder.Ascending;
else
listView1.Sorting = SortOrder.Descending;
listView1.ListViewItemSorter = Comparer<ListViewItem>.Create(((o, o1) =>
{
var v1 = o.SubItems[e.Column].Text;
var v2 = o1.SubItems[e.Column].Text;
if (v1.All(a => a >= '0' && a <= '9') && v2.All(a => a >= '0' && a <= '9'))
{
if (listView1.Sorting == SortOrder.Descending)
return double.Parse("0" + v1).CompareTo(double.Parse("0" + v2)) * -1;
return double.Parse("0" + v1).CompareTo(double.Parse("0" + v2));
}
if (listView1.Sorting == SortOrder.Descending)
return v1.CompareTo(v2) * -1;
return v1.CompareTo(v2);
}));
}
private async void DownloadToolStripMenuItem_Click(object sender, EventArgs e)
{
foreach (ListViewItem listView1SelectedItem in listView1.SelectedItems)
{
toolStripStatusLabel1.Text = "Download " + listView1SelectedItem.Text;
SaveFileDialog sfd = new SaveFileDialog();
sfd.FileName = listView1SelectedItem.Text;
sfd.RestoreDirectory = true;
sfd.OverwritePrompt = true;
var dr = sfd.ShowDialog();
if (dr == DialogResult.OK)
{
var path = treeView1.SelectedNode.FullPath + "/" + listView1SelectedItem.Text;
ProgressReporterDialogue prd = new ProgressReporterDialogue();
CancellationTokenSource cancel = new CancellationTokenSource();
prd.doWorkArgs.CancelRequestChanged += (o, args) =>
{
prd.doWorkArgs.ErrorMessage = "User Cancel";
cancel.Cancel();
_mavftp.kCmdResetSessions();
};
prd.doWorkArgs.ForceExit = false;
Action<string, int> progress = delegate (string message, int i)
{
prd.UpdateProgressAndStatus(i, toolStripStatusLabel1.Text);
};
_mavftp.Progress += progress;
prd.DoWork += (iprd) =>
{
var ms = _mavftp.GetFile(path, cancel, false);
if (cancel.IsCancellationRequested)
{
iprd.doWorkArgs.CancelAcknowledged = true;
iprd.doWorkArgs.CancelRequested = true;
return;
}
File.WriteAllBytes(sfd.FileName, ms.ToArray());
};
prd.RunBackgroundOperationAsync();
_mavftp.Progress -= progress;
}
else if (dr == DialogResult.Cancel)
{
return;
}
}
toolStripStatusLabel1.Text = "Ready";
}
private async void UploadToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Multiselect = true;
var dr = ofd.ShowDialog();
if (dr == DialogResult.OK)
{
foreach (var ofdFileName in ofd.FileNames)
{
try
{
await UploadFile(ofdFileName).ConfigureAwait(true);
}
catch (Exception exception)
{
log.Error(exception);
CustomMessageBox.Show(exception.Message);
}
}
}
TreeView1_NodeMouseClick(null,
new TreeNodeMouseClickEventArgs(treeView1.SelectedNode, MouseButtons.Left, 1, 1, 1));
}
private async Task UploadFile(string ofdFileName)
{
toolStripStatusLabel1.Text = "Upload " + Path.GetFileName(ofdFileName);
var fn = treeView1.SelectedNode.FullPath + "/" + Path.GetFileName(ofdFileName);
ProgressReporterDialogue prd = new ProgressReporterDialogue();
CancellationTokenSource cancel = new CancellationTokenSource();
prd.doWorkArgs.CancelRequestChanged += (o, args) =>
{
prd.doWorkArgs.ErrorMessage = "User Cancel";
cancel.Cancel();
_mavftp.kCmdResetSessions();
};
prd.doWorkArgs.ForceExit = false;
Action<string, int> progress = delegate (string message, int i)
{
prd.UpdateProgressAndStatus(i, toolStripStatusLabel1.Text);
};
_mavftp.Progress += progress;
prd.DoWork += (iprd) =>
{
_mavftp.UploadFile(fn, ofdFileName, cancel);
if (cancel.IsCancellationRequested)
{
iprd.doWorkArgs.CancelAcknowledged = true;
iprd.doWorkArgs.CancelRequested = true;
return;
}
prd.UpdateProgressAndStatus(-1, "Calc CRC");
uint crc = 0;
_mavftp.kCmdCalcFileCRC32(fn, ref crc, cancel);
var crc32a = MAVFtp.crc_crc32(0, File.ReadAllBytes(ofdFileName));
if (crc32a != crc)
{
throw new BadCrcException();
}
};
prd.RunBackgroundOperationAsync();
_mavftp.Progress -= progress;
toolStripStatusLabel1.Text = "Ready";
}
private void DeleteToolStripMenuItem_Click(object sender, EventArgs e)
{
foreach (ListViewItem listView1SelectedItem in listView1.SelectedItems)
{
toolStripStatusLabel1.Text = "Delete " + listView1SelectedItem.Text;
ProgressReporterDialogue prd = new ProgressReporterDialogue();
CancellationTokenSource cancel = new CancellationTokenSource();
prd.doWorkArgs.CancelRequestChanged += (o, args) =>
{
prd.doWorkArgs.ErrorMessage = "User Cancel";
cancel.Cancel();
_mavftp.kCmdResetSessions();
};
prd.doWorkArgs.ForceExit = false;
prd.DoWork += (iprd) =>
{
var success = _mavftp.kCmdRemoveFile(((DirectoryInfo) listView1SelectedItem.Tag).FullName + "/" +
listView1SelectedItem.Text, cancel);
if (!success)
CustomMessageBox.Show("Failed to delete file", listView1SelectedItem.Text);
};
prd.RunBackgroundOperationAsync();
}
TreeView1_NodeMouseClick(null,
new TreeNodeMouseClickEventArgs(treeView1.SelectedNode, MouseButtons.Left, 1, 1, 1));
toolStripStatusLabel1.Text = "Ready";
}
private void RenameToolStripMenuItem_Click(object sender, EventArgs e)
{
listView1.SelectedItems[0].BeginEdit();
}
private void ListView1_AfterLabelEdit(object sender, LabelEditEventArgs e)
{
if (e.Label == null)
return;
ProgressReporterDialogue prd = new ProgressReporterDialogue();
CancellationTokenSource cancel = new CancellationTokenSource();
prd.doWorkArgs.CancelRequestChanged += (o, args) =>
{
prd.doWorkArgs.ErrorMessage = "User Cancel";
cancel.Cancel();
_mavftp.kCmdResetSessions();
};
prd.doWorkArgs.ForceExit = false;
var selectedNodeFullPath = treeView1.SelectedNode.FullPath;
var text = listView1.SelectedItems[0].Text;
prd.DoWork += (iprd) =>
{
_mavftp.kCmdRename(selectedNodeFullPath + "/" + text,
selectedNodeFullPath + "/" + e.Label, cancel);
};
prd.RunBackgroundOperationAsync();
TreeView1_NodeMouseClick(null,
new TreeNodeMouseClickEventArgs(treeView1.SelectedNode, MouseButtons.Left, 1, 1, 1));
toolStripStatusLabel1.Text = "Ready";
}
private void NewFolderToolStripMenuItem_Click(object sender, EventArgs e)
{
string folder = "";
var dr = InputBox.Show("Folder Name", "Enter folder name", ref folder);
if (dr == DialogResult.OK)
{
ProgressReporterDialogue prd = new ProgressReporterDialogue();
CancellationTokenSource cancel = new CancellationTokenSource();
prd.doWorkArgs.CancelRequestChanged += (o, args) =>
{
prd.doWorkArgs.ErrorMessage = "User Cancel";
cancel.Cancel();
_mavftp.kCmdResetSessions();
};
prd.doWorkArgs.ForceExit = false;
prd.DoWork += (iprd) =>
{
if (!_mavftp.kCmdCreateDirectory(treeView1.SelectedNode.FullPath + "/" + folder,
cancel))
{
CustomMessageBox.Show("Failed to create directory", Strings.ERROR);
}
};
prd.RunBackgroundOperationAsync();
}
TreeView1_NodeMouseClick(null,
new TreeNodeMouseClickEventArgs(treeView1.SelectedNode, MouseButtons.Left, 1, 1, 1));
toolStripStatusLabel1.Text = "Ready";
}
private void GetCRC32ToolStripMenuItem_Click(object sender, EventArgs e)
{
ProgressReporterDialogue prd = new ProgressReporterDialogue();
CancellationTokenSource cancel = new CancellationTokenSource();
prd.doWorkArgs.CancelRequestChanged += (o, args) =>
{
prd.doWorkArgs.ErrorMessage = "User Cancel";
cancel.Cancel();
_mavftp.kCmdResetSessions();
};
prd.doWorkArgs.ForceExit = false;
var crc = 0u;
prd.DoWork += (iprd) =>
{
_mavftp.kCmdCalcFileCRC32(treeView1.SelectedNode.FullPath + "/" + listView1.SelectedItems[0].Text,
ref crc, cancel);
};
prd.RunBackgroundOperationAsync();
CustomMessageBox.Show(listView1.SelectedItems[0].Text + ": 0x" + crc.ToString("X"));
}
private void ListView1_MouseDown(object sender, MouseEventArgs e)
{
}
private void ListView1_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
e.Effect = DragDropEffects.Copy;
else
e.Effect = DragDropEffects.None;
}
private void ListView1_MouseDoubleClick(object sender, MouseEventArgs e)
{
if (listView1.SelectedItems.Count > 0)
{
treeView1.SelectedNode?.Expand();
// find child node with name
foreach (TreeNode node in treeView1.SelectedNode?.Nodes)
{
if (node.Text == listView1.SelectedItems[0].Text)
{
treeView1.SelectedNode = node;
TreeView1_NodeMouseClick(null,
new TreeNodeMouseClickEventArgs(treeView1.SelectedNode, MouseButtons.Left, 1, 1, 1));
break;
}
}
}
}
private void DownloadBurstToolStripMenuItem_Click(object sender, EventArgs e)
{
foreach (ListViewItem listView1SelectedItem in listView1.SelectedItems)
{
toolStripStatusLabel1.Text = "Download " + listView1SelectedItem.Text;
SaveFileDialog sfd = new SaveFileDialog();
sfd.FileName = listView1SelectedItem.Text;
sfd.RestoreDirectory = true;
sfd.OverwritePrompt = true;
var dr = sfd.ShowDialog();
if (dr == DialogResult.OK)
{
var path = treeView1.SelectedNode.FullPath + "/" + listView1SelectedItem.Text;
ProgressReporterDialogue prd = new ProgressReporterDialogue();
CancellationTokenSource cancel = new CancellationTokenSource();
prd.doWorkArgs.CancelRequestChanged += (o, args) =>
{
prd.doWorkArgs.ErrorMessage = "User Cancel";
cancel.Cancel();
_mavftp.kCmdResetSessions();
};
prd.doWorkArgs.ForceExit = false;
Action<string, int> progress = delegate (string message, int i)
{
prd.UpdateProgressAndStatus(i, toolStripStatusLabel1.Text);
};
_mavftp.Progress += progress;
prd.DoWork += (iprd) =>
{
var ms = _mavftp.GetFile(path, cancel);
if (cancel.IsCancellationRequested)
{
iprd.doWorkArgs.CancelAcknowledged = true;
iprd.doWorkArgs.CancelRequested = true;
return;
}
File.WriteAllBytes(sfd.FileName, ms.ToArray());
};
prd.RunBackgroundOperationAsync();
_mavftp.Progress -= progress;
}
else if (dr == DialogResult.Cancel)
{
return;
}
}
toolStripStatusLabel1.Text = "Ready";
}
private void MavFTPUI_Load(object sender, EventArgs e)
{
PopulateTreeView();
}
}
}