-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMainWindowViewModel.cs
More file actions
1504 lines (1265 loc) · 53.9 KB
/
MainWindowViewModel.cs
File metadata and controls
1504 lines (1265 loc) · 53.9 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.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Reactive;
using System.Reactive.Linq;
using System.Security.Principal;
using System.Text.Json;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Controls.Documents;
using Avalonia.Input;
using Avalonia.Input.Platform;
using Avalonia.Media;
using Avalonia.Threading;
using CliWrap;
using DynamicData;
using MsBox.Avalonia;
using ReactiveUI;
using ScriptRunner.GUI.BackgroundTasks;
using ScriptRunner.GUI.Infrastructure;
using ScriptRunner.GUI.Infrastructure.DataProtection;
using ScriptRunner.GUI.ScriptConfigs;
using ScriptRunner.GUI.ScriptReader;
using ScriptRunner.GUI.Settings;
using ScriptRunner.GUI.Views;
namespace ScriptRunner.GUI.ViewModels;
public class MainWindowViewModel : ReactiveObject
{
private static readonly SolidColorBrush ParameterBrush = new SolidColorBrush(new Color(255, 52, 215, 153));
public bool IsScriptListVisible
{
get => _isScriptListVisible;
set => this.RaiseAndSetIfChanged(ref _isScriptListVisible, value);
}
private bool _isScriptListVisible;
public bool IsRecentListVisible
{
get => _isRecentListVisible;
set => this.RaiseAndSetIfChanged(ref _isRecentListVisible, value);
}
private bool _isRecentListVisible;
public bool IsStatisticsVisible
{
get => _isStatisticsVisible;
set => this.RaiseAndSetIfChanged(ref _isStatisticsVisible, value);
}
private bool _isStatisticsVisible;
public bool IsLoadingConfig
{
get => _isLoadingConfig;
set
{
this.RaiseAndSetIfChanged(ref _isLoadingConfig, value);
UpdateIsAnyRefreshInProgress();
}
}
private bool _isLoadingConfig;
public bool IsRefreshingAppUpdates
{
get => _isRefreshingAppUpdates;
set
{
this.RaiseAndSetIfChanged(ref _isRefreshingAppUpdates, value);
UpdateIsAnyRefreshInProgress();
}
}
private bool _isRefreshingAppUpdates;
public bool IsRefreshingRepositories
{
get => _isRefreshingRepositories;
set
{
this.RaiseAndSetIfChanged(ref _isRefreshingRepositories, value);
UpdateIsAnyRefreshInProgress();
}
}
private bool _isRefreshingRepositories;
public bool IsAnyRefreshInProgress
{
get => _isAnyRefreshInProgress;
private set => this.RaiseAndSetIfChanged(ref _isAnyRefreshInProgress, value);
}
private bool _isAnyRefreshInProgress;
private void UpdateIsAnyRefreshInProgress()
{
IsAnyRefreshInProgress = IsRefreshingAppUpdates || IsRefreshingRepositories || IsLoadingConfig;
}
public StatisticsViewModel Statistics { get; private set; }
public bool IsSideBoxVisible => _isSideBoxVisible.Value;
private readonly ObservableAsPropertyHelper<bool> _isSideBoxVisible;
public IReactiveCommand SaveAsPredefinedCommand { get; set; }
public ReactiveCommand<TaggedScriptConfig, Unit> SelectActionCommand { get; set; }
private readonly ParamsPanelFactory _paramsPanelFactory;
private readonly VaultProvider _vaultProvider;
/// <summary>
/// Contains panels with generated controls for every defined action
/// </summary>
private ObservableCollection<Panel> _actionParametersPanel;
public ObservableCollection<Panel> ActionParametersPanel
{
get => _actionParametersPanel;
private set => this.RaiseAndSetIfChanged(ref _actionParametersPanel, value);
}
/// <summary>
/// Contains list of actions defined in json file
/// </summary>
public List<ScriptConfig> Actions
{
get => _actions;
set => this.RaiseAndSetIfChanged(ref _actions, value);
}
public string ActionFilter
{
get => _actionFilter;
set => this.RaiseAndSetIfChanged(ref _actionFilter, value);
}
private string _actionFilter;
public string SelectedCategoryFilter
{
get => _selectedCategoryFilter;
set => this.RaiseAndSetIfChanged(ref _selectedCategoryFilter, value);
}
private string _selectedCategoryFilter = "All";
private readonly ObservableAsPropertyHelper<IEnumerable<string>> _availableCategories;
public IEnumerable<string> AvailableCategories => _availableCategories.Value;
public bool IsTreeViewMode
{
get => _isTreeViewMode;
set => this.RaiseAndSetIfChanged(ref _isTreeViewMode, value);
}
private bool _isTreeViewMode = false;
private readonly ObservableAsPropertyHelper<IEnumerable<ScriptConfigGroupWrapper>> _filteredActionList;
public IEnumerable<ScriptConfigGroupWrapper> FilteredActionList => _filteredActionList.Value;
private readonly ObservableAsPropertyHelper<int> _actionCount;
public int ActionCount => _actionCount.Value;
public ObservableCollection<RunningJobViewModel> RunningJobs { get; set; } = new();
public RunningJobViewModel SelectedRunningJob
{
get => _selectedRunningJob;
set => this.RaiseAndSetIfChanged(ref _selectedRunningJob, value);
}
private bool _isActionSelected;
public bool IsActionSelected
{
get => _isActionSelected;
set => this.RaiseAndSetIfChanged(ref _isActionSelected, value);
}
private bool _installAvailable;
public bool InstallAvailable
{
get => _installAvailable;
set => this.RaiseAndSetIfChanged(ref _installAvailable, value);
}
private bool _hasParams;
public bool HasParams
{
get => _hasParams;
private set => this.RaiseAndSetIfChanged(ref _hasParams, value);
}
private object? _selectedActionOrGroup;
public object? SelectedActionOrGroup
{
get => _selectedActionOrGroup;
set
{
this.RaiseAndSetIfChanged(ref _selectedActionOrGroup, value);
if (value is TaggedScriptConfig {Config: var scriptConfig, ArgumentSet: var argumentSet})
{
SelectedAction = scriptConfig;
if (argumentSet != null)
{
SelectedArgumentSet = argumentSet;
}
}
}
}
public ScriptConfig? SelectedAction
{
get => _selectedAction;
set
{
if (value == null || _selectedAction == value)
{
return;
}
this.RaiseAndSetIfChanged(ref _selectedAction, value);
SelectedArgumentSet = value.PredefinedArgumentSets.FirstOrDefault();
InstallAvailable = string.IsNullOrWhiteSpace(value.InstallCommand) == false;
SelectedActionInstalled = InstallAvailable == false || IsActionInstalled(value.Name);
IsActionSelected = true;
HasParams = value.Params.Any();
}
}
public KeyGesture SearchBoxHotKey
{
get
{
if (OperatingSystem.IsMacOS())
{
// Cmd+P
return new KeyGesture(Key.P, KeyModifiers.Meta);
}
// Ctrl+P
return new KeyGesture(Key.P, KeyModifiers.Control);
}
}
private bool IsActionInstalled(string valueName)
{
if (AppSettingsService.Load().InstalledActions is { } installedActions && installedActions.TryGetValue(valueName, out var installInfo))
{
return installInfo.IsInstalled;
}
return false;
}
public bool ShowNewVersionAvailable
{
get => _showNewVersionAvailable;
set => this.RaiseAndSetIfChanged(ref _showNewVersionAvailable, value);
}
private bool _showNewVersionAvailable;
public ObservableCollection<OutdatedRepositoryModel> OutOfDateConfigRepositories { get; } = new();
public MainWindowViewModel() : this(new ParamsPanelFactory(new VaultProvider(new NullDataProtector())), new VaultProvider(new NullDataProtector()))
{
}
public MainWindowViewModel(ParamsPanelFactory paramsPanelFactory, VaultProvider vaultProvider)
{
CompactedHistoryForCurrent = true;
this._configRepositoryUpdater = new ConfigRepositoryUpdater(new CliRepositoryClient(command =>
{
var tcs = new TaskCompletionSource<CliCommandOutputs>();
Dispatcher.UIThread.Post(() =>
{
var job = new RunningJobViewModel
{
Tile = $"Update repository",
ExecutedCommand = $"{command.Command} {command.Parameters}",
};
job.ExecutedCommandFormatted.AddRange(CreateSimpleFormattedCommand($"{command.Command} {command.Parameters}"));
this.RunningJobs.Add(job);
SelectedRunningJob = job;
job.ExecutionCompleted += (sender, args) =>
{
tcs.SetResult(new(job.RawOutput, job.RawErrorOutput));
};
job.RunJob(command.Command, command.Parameters, command.WorkingDirectory, Array.Empty<InteractiveInputDescription>(), Array.Empty<TroubleshootingItem>());
});
return tcs.Task;
}));
IsScriptListVisible = true;
SaveAsPredefinedCommand = ReactiveCommand.Create(() => { });
SelectActionCommand = ReactiveCommand.Create<TaggedScriptConfig, Unit>(taggedScriptConfig =>
{
if (taggedScriptConfig.Config is { } scriptConfig)
{
SelectedAction = scriptConfig;
}
return Unit.Default;
});
_paramsPanelFactory = paramsPanelFactory;
_vaultProvider = vaultProvider;
this.appUpdater = new GithubUpdater();
// Initialize Statistics ViewModel
Statistics = new StatisticsViewModel(ExecutionLog);
ExecutionLogAction? lastSelected = null;
this.WhenAnyValue(x=>x.SelectedRecentExecution)
.Where(x=>x is not null && x != lastSelected)
.ObserveOn(RxApp.MainThreadScheduler)
.Subscribe(b =>
{
lastSelected = b;
if (Actions.FirstOrDefault(x => x.Name == b.Name && x.SourceName == b.Source) is { } selected)
{
SelectedAction = selected;
RenderParameterForm(selected, b.Parameters);
}
});
this.WhenAnyValue(x => x.IsScriptListVisible, x => x.IsRecentListVisible, x => x.IsStatisticsVisible)
.Select(t => (t.Item1 || t.Item2 || t.Item3))
.ObserveOn(RxApp.MainThreadScheduler)
.ToProperty(this, x => x.IsSideBoxVisible, out _isSideBoxVisible);
this.WhenAnyValue(x => x.IsScriptListVisible)
.Where(x => x)
.ObserveOn(RxApp.MainThreadScheduler)
.Subscribe(b => { IsRecentListVisible = false; IsStatisticsVisible = false; });
this.WhenAnyValue(x => x.IsRecentListVisible)
.Where(x => x)
.ObserveOn(RxApp.MainThreadScheduler)
.Subscribe(b => { IsScriptListVisible = false; IsStatisticsVisible = false; });
this.WhenAnyValue(x => x.IsStatisticsVisible)
.Where(x => x)
.ObserveOn(RxApp.MainThreadScheduler)
.Subscribe(b =>
{
IsScriptListVisible = false;
IsRecentListVisible = false;
Statistics.RefreshStatistics();
});
// Build available categories list
this.WhenAnyValue(x => x.Actions)
.Select(actions =>
{
var categories = new List<string> { "All" };
var allCategories = actions
.SelectMany(a => a.Categories ?? Enumerable.Empty<string>())
.Where(c => !string.IsNullOrWhiteSpace(c))
.Distinct()
.OrderBy(c => c);
categories.AddRange(allCategories);
if (actions.Any(a => a.Categories == null || a.Categories.Count == 0))
{
categories.Add("(No Category)");
}
return categories.AsEnumerable();
})
.ObserveOn(RxApp.MainThreadScheduler)
.ToProperty(this, x => x.AvailableCategories, out _availableCategories);
this.WhenAnyValue(x => x.ActionFilter, x => x.SelectedCategoryFilter, x => x.Actions)
.Throttle(TimeSpan.FromMilliseconds(200))
.DistinctUntilChanged()
.Select((tuple, cancellationToken) =>
{
var (textFilter, categoryFilter, actions) = tuple;
// Apply category filter first
IEnumerable<ScriptConfig> configs = actions;
if (!string.IsNullOrWhiteSpace(categoryFilter) && categoryFilter != "All")
{
if (categoryFilter == "(No Category)")
{
configs = configs.Where(x => x.Categories == null || x.Categories.Count == 0);
}
else
{
configs = configs.Where(x => x.Categories != null && x.Categories.Contains(categoryFilter));
}
}
IEnumerable<ScriptConfigGroupWrapper> scriptConfigGroupWrappers;
// When a specific category is filtered, show each action only once under that category
if (!string.IsNullOrWhiteSpace(categoryFilter) && categoryFilter != "All")
{
var expandedEntries = configs.SelectMany(c =>
c.PredefinedArgumentSets.Select(p => new TaggedScriptConfig(
categoryFilter,
p.Description == "<default>" ? c.Name : $"{c.Name} - {p.Description}",
c,
p
))
);
// Apply text filter to expanded entries
if (!string.IsNullOrWhiteSpace(textFilter))
{
expandedEntries = expandedEntries.Where(x => x.Name.Contains(textFilter, StringComparison.InvariantCultureIgnoreCase));
}
var children = expandedEntries.OrderBy(x => x.Name).ToList();
// Only create group if it has children
scriptConfigGroupWrappers = children.Any()
? new[]
{
new ScriptConfigGroupWrapper
{
Name = categoryFilter,
Children = children
}
}
: Enumerable.Empty<ScriptConfigGroupWrapper>();
}
else
{
// When no filter or "All" is selected, show actions grouped by all their categories
var groupedConfigs = configs.SelectMany(c =>
{
if (c.Categories is {Count: > 0})
{
return c.Categories.DistinctBy(x=>x).Select((cat) => (category: cat, script: c));
}
return new[] {(category: "(No Category)", script: c)};
}).GroupBy(x => x.category).OrderBy(x=>x.Key);
scriptConfigGroupWrappers = groupedConfigs.Select(x =>
{
var expandedEntries = x.SelectMany(p =>
p.script.PredefinedArgumentSets.Select(argSet => new TaggedScriptConfig(
x.Key,
argSet.Description == "<default>" ? p.script.Name : $"{p.script.Name} - {argSet.Description}",
p.script,
argSet
))
);
// Apply text filter to expanded entries
if (!string.IsNullOrWhiteSpace(textFilter))
{
expandedEntries = expandedEntries.Where(e => e.Name.Contains(textFilter, StringComparison.InvariantCultureIgnoreCase));
}
return new ScriptConfigGroupWrapper
{
Name = x.Key,
Children = expandedEntries.OrderBy(e => e.Name)
};
}).Where(group => group.Children.Any()); // Filter out empty groups
}
return scriptConfigGroupWrappers;
})
.ObserveOn(RxApp.MainThreadScheduler)
.ToProperty(this, x => x.FilteredActionList, out _filteredActionList);
this.WhenAnyValue(x => x.Actions)
.Select(list => list?.Count ?? 0)
.ObserveOn(RxApp.MainThreadScheduler)
.ToProperty(this, x => x.ActionCount, out _actionCount);
Observable
.FromEventPattern<NotifyCollectionChangedEventHandler, NotifyCollectionChangedEventArgs>(
h => this.ExecutionLog.CollectionChanged += h,
h => this.ExecutionLog.CollectionChanged -= h)
.Throttle(TimeSpan.FromMilliseconds(500))
.Select(_ => Unit.Default) // We don't care about the event args; we just want to know something changed.
.StartWith(Unit.Default) // To ensure initial population.
.CombineLatest(
this.WhenAnyValue(
x => x.SelectedAction,
x=>x.CompactedHistoryForCurrent,
x=>x.TermForCurrentHistoryFilter
).Where(x => x.Item1 != null).Throttle(TimeSpan.FromMilliseconds(200)),
(_, selectedAction) => selectedAction)
.Select(data =>
{
var (selectedAction, compacted, term) = data;
var filtered = this.ExecutionLog.Where(y => y.Source == selectedAction!.SourceName && y.Name == selectedAction.Name);
if (compacted)
{
filtered = filtered.GroupBy(x => x.ParametersDescriptionString(), (key, group) => group.First());
}
if (string.IsNullOrWhiteSpace(term) == false)
{
filtered = filtered.Where(x => x.Parameters.Values.Any(p => p?.Contains(term, StringComparison.InvariantCultureIgnoreCase) == true));
}
return filtered;
})
.ObserveOn(RxApp.MainThreadScheduler)
.ToProperty(this, x => x.ExecutionLogForCurrent, out _executionLogForCurrent);
// Create grouped execution log with date dividers
Observable
.FromEventPattern<NotifyCollectionChangedEventHandler, NotifyCollectionChangedEventArgs>(
h => this.ExecutionLog.CollectionChanged += h,
h => this.ExecutionLog.CollectionChanged -= h)
.Throttle(TimeSpan.FromMilliseconds(500))
.Select(_ => Unit.Default)
.StartWith(Unit.Default)
.Select(_ =>
{
var items = new List<ExecutionLogItemBase>();
DateTime? lastDate = null;
foreach (var action in ExecutionLog)
{
var actionDate = action.Timestamp.Date;
// Add date header if the date changed
if (lastDate == null || lastDate != actionDate)
{
items.Add(new ExecutionLogDateHeader(actionDate));
lastDate = actionDate;
}
items.Add(new ExecutionLogItemAction(action));
}
return items.AsEnumerable();
})
.ObserveOn(RxApp.MainThreadScheduler)
.ToProperty(this, x => x.ExecutionLogGrouped, out _executionLogGrouped);
// Create available dates list for date picker
Observable
.FromEventPattern<NotifyCollectionChangedEventHandler, NotifyCollectionChangedEventArgs>(
h => this.ExecutionLog.CollectionChanged += h,
h => this.ExecutionLog.CollectionChanged -= h)
.Throttle(TimeSpan.FromMilliseconds(500))
.Select(_ => Unit.Default)
.StartWith(Unit.Default)
.Select(_ =>
{
// Group by date and count items
var dateGroups = ExecutionLog
.GroupBy(x => x.Timestamp.Date)
.OrderByDescending(g => g.Key)
.Select(g => new DateGroupInfo(g.Key, g.Count()))
.ToList();
return dateGroups.AsEnumerable();
})
.ObserveOn(RxApp.MainThreadScheduler)
.ToProperty(this, x => x.AvailableDates, out _availableDates);
this.WhenAnyValue(x => x.SelectedAction)
.ObserveOn(RxApp.MainThreadScheduler)
.Subscribe(s =>
{
TermForCurrentHistoryFilter = "";
});
_appUpdateScheduler = new RealTimeScheduler(TimeSpan.FromDays(1), TimeSpan.FromHours(1), async () =>
{
await RefreshInfoAbouAppUpdates();
});
_appUpdateScheduler.Run();
_outdatedRepoCheckingScheduler = new RealTimeScheduler(TimeSpan.FromHours(4), TimeSpan.FromHours(1), async () =>
{
await RefreshInfoAboutRepositories();
});
_outdatedRepoCheckingScheduler.Run();
ActionParametersPanel = new ObservableCollection<Panel>();
BuildUi();
}
private bool _compactedHistoryForCurrent;
public bool CompactedHistoryForCurrent
{
get => _compactedHistoryForCurrent;
set => this.RaiseAndSetIfChanged(ref _compactedHistoryForCurrent, value);
}
private string _termForCurrentHistoryFilter;
public string TermForCurrentHistoryFilter
{
get => _termForCurrentHistoryFilter;
set => this.RaiseAndSetIfChanged(ref _termForCurrentHistoryFilter, value);
}
private async Task RefreshInfoAbouAppUpdates()
{
IsRefreshingAppUpdates = true;
try
{
var isNewerVersion = await appUpdater.CheckIsNewerVersionAvailable();
if (isNewerVersion)
{
Dispatcher.UIThread.Post(() =>
{
ShowNewVersionAvailable = true;
});
}
}
finally
{
IsRefreshingAppUpdates = false;
}
}
private async Task RefreshInfoAboutRepositories()
{
IsRefreshingRepositories = true;
try
{
var outOfDateRepos = await _configRepositoryUpdater.CheckAllRepositories();
Dispatcher.UIThread.Post(() =>
{
OutOfDateConfigRepositories.Clear();
OutOfDateConfigRepositories.AddRange(outOfDateRepos);
});
}
finally
{
IsRefreshingRepositories = false;
}
}
public void CheckForUpdates()
{
appUpdater.OpenLatestReleaseLog();
}
public void InstallUpdate()
{
appUpdater.InstallLatestVersion();
}
public void DismissNewVersionAvailable()
{
ShowNewVersionAvailable = false;
}
public void DismissOutdatedRepositories()
{
OutOfDateConfigRepositories.Clear();
}
private IEnumerable<IControlRecord> _controlRecords;
//private ActionsConfig config;
private ScriptConfig _selectedAction;
private ArgumentSet _selectedArgumentSet;
private void BuildUi()
{
IsLoadingConfig = true;
Task.Run(() =>
{
var selectedActionName = SelectedAction?.Name;
var appSettings = AppSettingsService.Load();
var sources = appSettings.ConfigScripts == null || appSettings.ConfigScripts.Count == 0
? SampleScripts
: appSettings.ConfigScripts;
var actions = new List<ScriptConfig>();
var allCorruptedFiles = new List<string>();
var results = sources.Select(source => ScriptConfigReader.LoadWithErrorTracking(source, appSettings)).ToList();
var el = AppSettingsService.LoadExecutionLog();
Dispatcher.UIThread.Post(() =>
{
foreach (var result in results)
{
actions.AddRange(result.Configs.OrderBy(x => x.SourceName).ThenBy(x => x.Name));
allCorruptedFiles.AddRange(result.CorruptedFiles);
}
foreach (var action in actions)
{
var withMarkers = action.Params.Aggregate
(
seed: action.Command,
func: (string accumulate, ScriptParam source) =>
accumulate.Replace("{" + source.Name + "}", "[!@#]{" + source.Name + "}[!@#]")
);
action.CommandFormatted.AddRange(withMarkers.Split("[!@#]").Select(x =>
{
var inline = new Run(x);
if (x.StartsWith("{"))
{
inline.Foreground = ParameterBrush;
}
return inline;
}));
// Format InstallCommand if it exists
if (!string.IsNullOrWhiteSpace(action.InstallCommand))
{
var installWithMarkers = action.Params.Aggregate
(
seed: action.InstallCommand,
func: (string accumulate, ScriptParam source) =>
accumulate.Replace("{" + source.Name + "}", "[!@#]{" + source.Name + "}[!@#]")
);
action.InstallCommandFormatted.AddRange(installWithMarkers.Split("[!@#]").Select(x =>
{
var inline = new Run(x);
if (x.StartsWith("{"))
{
inline.Foreground = ParameterBrush;
}
return inline;
}));
}
}
Actions = actions;
if (string.IsNullOrWhiteSpace(selectedActionName) == false && Actions.FirstOrDefault(x => x.Name == selectedActionName) is { } previouslySelected)
{
SelectedAction = previouslySelected;
}
else if (appSettings.Recent?.OrderByDescending(x => x.Value.Timestamp).FirstOrDefault() is { } recent && Actions.FirstOrDefault(a =>
a.Name == recent.Value?.ActionId.ActionName &&
a.SourceName == recent.Value.ActionId.SourceName) is
{ } existingRecent)
{
SelectedAction = existingRecent;
if (existingRecent.PredefinedArgumentSets.FirstOrDefault(p =>
p.Description == recent.Value.ActionId.ParameterSet) is { } ps)
{
SelectedArgumentSet = ps;
}
}
else if(Actions.FirstOrDefault() is { } firstAction)
{
SelectedAction = firstAction;
}
ExecutionLog.Clear();
ExecutionLog.AddRange(el);
IsLoadingConfig = false;
if (allCorruptedFiles.Count > 0)
{
ShowCorruptedFilesDialog(allCorruptedFiles);
}
});
});
}
private async void ShowCorruptedFilesDialog(List<string> corruptedFiles)
{
var fileList = string.Join("\n", corruptedFiles.Select(f => $"• {f}"));
var message = $"The following configuration files are corrupted and were skipped:\n\n{fileList}\n\nPlease check these files for JSON syntax errors.";
var messageBox = MessageBoxManager.GetMessageBoxStandard(
"Corrupted Configuration Files",
message,
icon: MsBox.Avalonia.Enums.Icon.Warning,
windowStartupLocation: WindowStartupLocation.CenterOwner);
if (Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
await messageBox.ShowWindowDialogAsync(desktop.MainWindow);
}
}
private static List<ConfigScriptEntry> SampleScripts => new()
{
new ConfigScriptEntry
{
Name = "Samples",
Path = Path.Combine(AppContext.BaseDirectory,"Scripts/TextInputScript.json"),
Type = ConfigScriptType.File
}
};
public ArgumentSet? SelectedArgumentSet
{
get => _selectedArgumentSet;
set
{
this.RaiseAndSetIfChanged(ref _selectedArgumentSet, value);
if (SelectedAction is { } selectedAction && _selectedArgumentSet is { Arguments: {} arguments, Description: var setName})
{
if (setName == DefaultParameterSetName)
{
if (AppSettingsService.TryGetDefaultOverrides(selectedAction.Name) is { } overrides)
{
arguments = new Dictionary<string, string>(arguments);
foreach (var (argName, argValue) in overrides)
{
arguments[argName] = argValue;
}
}
}
// Handle fallbackToExisting: preserve current values when new set has empty values
if (_selectedArgumentSet.FallbackToExisting && _controlRecords != null)
{
// Harvest current parameter values from UI controls
var currentValues = new Dictionary<string, string>();
foreach (var controlRecord in _controlRecords)
{
var controlValue = controlRecord.GetFormattedValue()?.Trim();
if (!string.IsNullOrEmpty(controlValue))
{
currentValues[controlRecord.Name] = controlValue;
}
}
// Merge: use new set's values if non-empty, otherwise preserve current values
arguments = new Dictionary<string, string>(arguments);
foreach (var param in selectedAction.Params)
{
// If the new set doesn't have this parameter or has an empty value
if ((!arguments.ContainsKey(param.Name) || string.IsNullOrEmpty(arguments[param.Name]))
&& currentValues.ContainsKey(param.Name))
{
// Preserve the current value
arguments[param.Name] = currentValues[param.Name];
}
}
}
RenderParameterForm(selectedAction, arguments);
}
}
}
private void RenderParameterForm(ScriptConfig action, Dictionary<string, string> parameterValues)
{
ActionParametersPanel.Clear();
// Action panel could be used by creating custom user control with Description, description etc.
// Just ParamsPanel should be generated dynamically
//var actionPanel = new StackPanel();
// Create IPanel with controls for all parameters
var paramsPanel = _paramsPanelFactory.Create(action, parameterValues, (title, command) =>
{
if (SelectedAction != null)
{
var taskCompletionSource = new TaskCompletionSource<string>();
try
{
ExecuteCommand(command, this.SelectedAction, useSystemShell:false, title, s =>
{
taskCompletionSource.SetResult(s);
});
}
catch (Exception e)
{
taskCompletionSource.SetException(e);
}
return taskCompletionSource.Task;
}
return Task.FromResult("");
});
// Add panel with param controls to action panel
//actionPanel.Children.Add(paramsPanel.Panel);
// Add action panel to root container with all action panels
ActionParametersPanel.Add(paramsPanel.Panel);
// Write down param controls to read easier later - TODO: figure out better way, support multiple actions
_controlRecords = paramsPanel.ControlRecords;
}
private int jobCounter;
private RunningJobViewModel _selectedRunningJob;
private bool _selectedActionInstalled;
private readonly GithubUpdater appUpdater;
private readonly RealTimeScheduler _appUpdateScheduler;
private readonly RealTimeScheduler _outdatedRepoCheckingScheduler;
private List<ScriptConfig> _actions = new ();
public void ResetDefaults()
{
if (SelectedAction is not null)
{
AppSettingsService.UpdateDefaultOverrides(new ActionDefaultOverrides
{
ActionName = SelectedAction.Name,
Defaults = new Dictionary<string, string>()
});
BuildUi();
}
}
public void InstallScript()
{
if (SelectedAction is { InstallCommand: {} installCommand } selectedAction )
{
if (selectedAction.RunInstallCommandAsAdmin && IsAdministrator() == false)
{
NotifyAboutMissingAdminRights();
return;
}
var (commandPath, args) = SplitCommandAndArgs(installCommand);
var job = new RunningJobViewModel
{
Tile = $"#{jobCounter++} Install {selectedAction.Name}",
ExecutedCommand = installCommand,
EnvironmentVariables = new Dictionary<string, string?>()
};
job.ExecutedCommandFormatted.AddRange(CreateSimpleFormattedCommand(installCommand));
job.ExecutionCompleted += (sender, eventArgs) =>
{
SelectedActionInstalled = true;
AppSettingsService.MarkActionAsInstalled(selectedAction.Name);
};
this.RunningJobs.Add(job);
SelectedRunningJob = job;
job.RunJob(commandPath, args, selectedAction.InstallCommandWorkingDirectory, Array.Empty<InteractiveInputDescription>(), selectedAction.InstallTroubleshooting);
}
}
private static void NotifyAboutMissingAdminRights()
{
var messageBoxStandardWindow = MessageBoxManager.GetMessageBoxStandard("Missing permissions", "This scripts requires administrator rights.\r\n\r\nPlease restart the app as administrator. ", icon: MsBox.Avalonia.Enums.Icon.Forbidden);
messageBoxStandardWindow.ShowAsync();
}
public static bool IsAdministrator()
{
if (OperatingSystem.IsWindows())
{
var identity = WindowsIdentity.GetCurrent();
var principal = new WindowsPrincipal(identity);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
return true;
}
public void OpenSettingsWindow()
{
if (Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime {MainWindow: {} mainWindow})
{
var window = new SettingsWindow();
window.Closed += (sender, args) =>
{
RefreshSettings();
};
window.Show(mainWindow);
}
}