-
-
Notifications
You must be signed in to change notification settings - Fork 346
/
ManageMods.cs
1431 lines (1260 loc) · 57.2 KB
/
ManageMods.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
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.Linq;
using System.Drawing;
using System.Diagnostics;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using log4net;
using CKAN.Versioning;
namespace CKAN
{
public partial class ManageMods : UserControl
{
public ManageMods()
{
InitializeComponent();
mainModList = new ModList(source => UpdateFilters());
FilterToolButton.MouseHover += (sender, args) => FilterToolButton.ShowDropDown();
launchKSPToolStripMenuItem.MouseHover += (sender, args) => launchKSPToolStripMenuItem.ShowDropDown();
ApplyToolButton.MouseHover += (sender, args) => ApplyToolButton.ShowDropDown();
ApplyToolButton.Enabled = false;
// History is read-only until the UI is started. We switch
// out of it at the end of OnLoad() when we call NavInit().
navHistory = new NavigationHistory<GUIMod> { IsReadOnly = true };
// Initialize navigation. This should be called as late as
// possible, once the UI is "settled" from its initial load.
NavInit();
if (Platform.IsMono)
{
menuStrip2.Renderer = new FlatToolStripRenderer();
FilterToolButton.DropDown.Renderer = new FlatToolStripRenderer();
FilterTagsToolButton.DropDown.Renderer = new FlatToolStripRenderer();
FilterLabelsToolButton.DropDown.Renderer = new FlatToolStripRenderer();
ModListContextMenuStrip.Renderer = new FlatToolStripRenderer();
ModListHeaderContextMenuStrip.Renderer = new FlatToolStripRenderer();
LabelsContextMenuStrip.Renderer = new FlatToolStripRenderer();
}
}
private static readonly ILog log = LogManager.GetLogger(typeof(ManageMods));
private DateTime lastSearchTime;
private string lastSearchKey;
private NavigationHistory<GUIMod> navHistory;
private IEnumerable<ModChange> currentChangeSet;
private Dictionary<GUIMod, string> conflicts;
public readonly ModList mainModList;
public event Action<GUIMod> OnSelectedModuleChanged;
public event Action<IEnumerable<ModChange>> OnChangeSetChanged;
public event Action OnRegistryChanged;
public event Action<List<ModChange>> StartChangeSet;
public event Action OpenProgressTab;
public event Action CloseProgressTab;
public event Action<IEnumerable<GUIMod>> LabelsAfterUpdate;
private IEnumerable<ModChange> ChangeSet
{
get { return currentChangeSet; }
set
{
var orig = currentChangeSet;
currentChangeSet = value;
if (!ReferenceEquals(orig, value))
ChangeSetUpdated();
}
}
private void ChangeSetUpdated()
{
if (ChangeSet != null && ChangeSet.Any())
{
ApplyToolButton.Enabled = true;
}
else
{
ApplyToolButton.Enabled = false;
InstallAllCheckbox.Checked = true;
}
if (OnChangeSetChanged != null)
{
OnChangeSetChanged(ChangeSet);
}
}
private Dictionary<GUIMod, string> Conflicts
{
get { return conflicts; }
set
{
var orig = conflicts;
conflicts = value;
if (orig != value)
ConflictsUpdated(orig);
}
}
private void ConflictsUpdated(Dictionary<GUIMod, string> prevConflicts)
{
if (Conflicts == null)
{
// Clear status bar if no conflicts
Main.Instance.AddStatusMessage("");
}
if (prevConflicts != null)
{
// Mark old conflicts as non-conflicted
// (rows that are _still_ conflicted will be marked as such in the next loop)
foreach (GUIMod guiMod in prevConflicts.Keys)
{
DataGridViewRow row = mainModList.full_list_of_mod_rows[guiMod.Identifier];
foreach (DataGridViewCell cell in row.Cells)
{
cell.ToolTipText = null;
}
mainModList.ReapplyLabels(guiMod, false, Main.Instance.CurrentInstance.Name);
if (row.Visible)
{
ModGrid.InvalidateRow(row.Index);
}
}
}
if (Conflicts != null)
{
// Mark current conflicts as conflicted
foreach (var kvp in Conflicts)
{
GUIMod guiMod = kvp.Key;
DataGridViewRow row = mainModList.full_list_of_mod_rows[guiMod.Identifier];
string conflict_text = kvp.Value;
foreach (DataGridViewCell cell in row.Cells)
{
cell.ToolTipText = conflict_text;
}
row.DefaultCellStyle.BackColor = mainModList.GetRowBackground(guiMod, true, Main.Instance.CurrentInstance.Name);
if (row.Visible)
{
ModGrid.InvalidateRow(row.Index);
}
}
}
}
private void RefreshToolButton_Click(object sender, EventArgs e)
{
Main.Instance.UpdateRepo();
}
#region Filter dropdown
private void FilterToolButton_DropDown_Opening(object sender, System.ComponentModel.CancelEventArgs e)
{
// The menu items' dropdowns can't be accessed if they're empty
FilterTagsToolButton_DropDown_Opening(null, null);
FilterLabelsToolButton_DropDown_Opening(null, null);
}
private void FilterTagsToolButton_DropDown_Opening(object sender, System.ComponentModel.CancelEventArgs e)
{
FilterTagsToolButton.DropDownItems.Clear();
foreach (var kvp in mainModList.ModuleTags.Tags.OrderBy(kvp => kvp.Key))
{
FilterTagsToolButton.DropDownItems.Add(new ToolStripMenuItem(
$"{kvp.Key} ({kvp.Value.ModuleIdentifiers.Count})",
null, tagFilterButton_Click
)
{
Tag = kvp.Value
});
}
FilterTagsToolButton.DropDownItems.Add(untaggedFilterToolStripSeparator);
FilterTagsToolButton.DropDownItems.Add(new ToolStripMenuItem(
string.Format(Properties.Resources.MainLabelsUntagged, mainModList.ModuleTags.Untagged.Count),
null, tagFilterButton_Click
)
{
Tag = null
});
}
private void FilterLabelsToolButton_DropDown_Opening(object sender, System.ComponentModel.CancelEventArgs e)
{
FilterLabelsToolButton.DropDownItems.Clear();
foreach (ModuleLabel mlbl in mainModList.ModuleLabels.LabelsFor(Main.Instance.CurrentInstance.Name))
{
FilterLabelsToolButton.DropDownItems.Add(new ToolStripMenuItem(
$"{mlbl.Name} ({mlbl.ModuleIdentifiers.Count})",
null, customFilterButton_Click
)
{
Tag = mlbl
});
}
}
private void tagFilterButton_Click(object sender, EventArgs e)
{
var clicked = sender as ToolStripMenuItem;
Filter(GUIModFilter.Tag, clicked.Tag as ModuleTag, null);
}
private void customFilterButton_Click(object sender, EventArgs e)
{
var clicked = sender as ToolStripMenuItem;
Filter(GUIModFilter.CustomLabel, null, clicked.Tag as ModuleLabel);
}
#endregion
#region Filter right click menu
private void LabelsContextMenuStrip_Opening(object sender, System.ComponentModel.CancelEventArgs e)
{
LabelsContextMenuStrip.Items.Clear();
var module = SelectedModule;
foreach (ModuleLabel mlbl in mainModList.ModuleLabels.LabelsFor(Main.Instance.CurrentInstance.Name))
{
LabelsContextMenuStrip.Items.Add(
new ToolStripMenuItem(mlbl.Name, null, labelMenuItem_Click)
{
Checked = mlbl.ModuleIdentifiers.Contains(module.Identifier),
CheckOnClick = true,
Tag = mlbl,
}
);
}
LabelsContextMenuStrip.Items.Add(labelToolStripSeparator);
LabelsContextMenuStrip.Items.Add(editLabelsToolStripMenuItem);
e.Cancel = false;
}
private void labelMenuItem_Click(object sender, EventArgs e)
{
var item = sender as ToolStripMenuItem;
var mlbl = item.Tag as ModuleLabel;
var module = SelectedModule;
if (item.Checked)
{
mlbl.Add(module.Identifier);
}
else
{
mlbl.Remove(module.Identifier);
}
mainModList.ReapplyLabels(module, Conflicts?.ContainsKey(module) ?? false, Main.Instance.CurrentInstance.Name);
mainModList.ModuleLabels.Save(ModuleLabelList.DefaultPath);
}
private void editLabelsToolStripMenuItem_Click(object sender, EventArgs e)
{
EditLabelsDialog eld = new EditLabelsDialog(Main.Instance.currentUser, Main.Instance.Manager, mainModList.ModuleLabels);
eld.ShowDialog(this);
eld.Dispose();
mainModList.ModuleLabels.Save(ModuleLabelList.DefaultPath);
foreach (GUIMod module in mainModList.Modules)
{
mainModList.ReapplyLabels(module, Conflicts?.ContainsKey(module) ?? false, Main.Instance.CurrentInstance.Name);
}
}
#endregion
private void FilterCompatibleButton_Click(object sender, EventArgs e)
{
Filter(GUIModFilter.Compatible);
}
private void FilterInstalledButton_Click(object sender, EventArgs e)
{
Filter(GUIModFilter.Installed);
}
private void FilterInstalledUpdateButton_Click(object sender, EventArgs e)
{
Filter(GUIModFilter.InstalledUpdateAvailable);
}
private void FilterReplaceableButton_Click(object sender, EventArgs e)
{
Filter(GUIModFilter.Replaceable);
}
private void FilterCachedButton_Click(object sender, EventArgs e)
{
Filter(GUIModFilter.Cached);
}
private void FilterUncachedButton_Click(object sender, EventArgs e)
{
Filter(GUIModFilter.Uncached);
}
private void FilterNewButton_Click(object sender, EventArgs e)
{
Filter(GUIModFilter.NewInRepository);
}
private void FilterNotInstalledButton_Click(object sender, EventArgs e)
{
Filter(GUIModFilter.NotInstalled);
}
private void FilterIncompatibleButton_Click(object sender, EventArgs e)
{
Filter(GUIModFilter.Incompatible);
}
private void FilterAllButton_Click(object sender, EventArgs e)
{
Filter(GUIModFilter.All);
}
/// <summary>
/// Called when the ModGrid filter (all, compatible, incompatible...) is changed.
/// </summary>
/// <param name="filter">Filter.</param>
public void Filter(GUIModFilter filter, ModuleTag tag = null, ModuleLabel label = null)
{
// Triggers mainModList.ModFiltersUpdated()
mainModList.TagFilter = tag;
mainModList.CustomLabelFilter = label;
mainModList.ModFilter = filter;
// Save new filter to the configuration.
Main.Instance.configuration.ActiveFilter = (int)mainModList.ModFilter;
Main.Instance.configuration.CustomLabelFilter = label?.Name;
Main.Instance.configuration.TagFilter = tag?.Name;
Main.Instance.configuration.Save();
// Ask the configuration which columns to show.
foreach (DataGridViewColumn col in ModGrid.Columns)
{
// Some columns are always shown, and others are handled by UpdateModsList()
if (col.Name != "Installed" && col.Name != "UpdateCol" && col.Name != "ReplaceCol")
{
col.Visible = !Main.Instance.configuration.HiddenColumnNames.Contains(col.Name);
}
}
switch (filter)
{
// Some columns really do / don't make sense to be visible on certain filter settings.
// Hide / Show them, without writing to config, so once the user changes tab again,
// they are shown / hidden again, as before.
case GUIModFilter.All: FilterToolButton.Text = Properties.Resources.MainFilterAll; break;
case GUIModFilter.Incompatible: FilterToolButton.Text = Properties.Resources.MainFilterIncompatible; break;
case GUIModFilter.Installed: FilterToolButton.Text = Properties.Resources.MainFilterInstalled; break;
case GUIModFilter.InstalledUpdateAvailable: FilterToolButton.Text = Properties.Resources.MainFilterUpgradeable; break;
case GUIModFilter.Replaceable: FilterToolButton.Text = Properties.Resources.MainFilterReplaceable; break;
case GUIModFilter.Cached: FilterToolButton.Text = Properties.Resources.MainFilterCached; break;
case GUIModFilter.Uncached: FilterToolButton.Text = Properties.Resources.MainFilterUncached; break;
case GUIModFilter.NewInRepository: FilterToolButton.Text = Properties.Resources.MainFilterNew; break;
case GUIModFilter.NotInstalled: ModGrid.Columns["InstalledVersion"].Visible = false;
ModGrid.Columns["InstallDate"].Visible = false;
ModGrid.Columns["AutoInstalled"].Visible = false;
FilterToolButton.Text = Properties.Resources.MainFilterNotInstalled; break;
case GUIModFilter.CustomLabel: FilterToolButton.Text = string.Format(Properties.Resources.MainFilterLabel, label?.Name ?? "CUSTOM"); break;
case GUIModFilter.Tag:
FilterToolButton.Text = tag == null
? Properties.Resources.MainFilterUntagged
: string.Format(Properties.Resources.MainFilterTag, tag.Name);
break;
default: FilterToolButton.Text = Properties.Resources.MainFilterCompatible; break;
}
}
public void MarkAllUpdates()
{
foreach (DataGridViewRow row in ModGrid.Rows)
{
var mod = (GUIMod)row.Tag;
if (mod.HasUpdate)
{
MarkModForUpdate(mod.Identifier, true);
}
}
// only sort by Update column if checkbox in settings checked
if (Main.Instance.configuration.AutoSortByUpdate)
{
// set new sort column
var new_sort_column = ModGrid.Columns[UpdateCol.Index];
var current_sort_column = ModGrid.Columns[Main.Instance.configuration.SortByColumnIndex];
// Reset the glyph.
current_sort_column.HeaderCell.SortGlyphDirection = SortOrder.None;
Main.Instance.configuration.SortByColumnIndex = new_sort_column.Index;
UpdateFilters();
// Select the top row and scroll the list to it.
ModGrid.CurrentCell = ModGrid.Rows[0].Cells[SelectableColumnIndex()];
}
ModGrid.Refresh();
}
private void MarkAllUpdatesToolButton_Click(object sender, EventArgs e)
{
MarkAllUpdates();
}
private void ApplyToolButton_Click(object sender, EventArgs e)
{
Main.Instance.tabController.ShowTab("ChangesetTabPage", 1);
}
public void MarkModForUpdate(string identifier, bool value)
{
Util.Invoke(this, () => _MarkModForUpdate(identifier, value));
}
private void _MarkModForUpdate(string identifier, bool value)
{
DataGridViewRow row = mainModList.full_list_of_mod_rows[identifier];
var mod = (GUIMod)row.Tag;
mod.SetUpgradeChecked(row, UpdateCol, value);
}
private void launchKSPToolStripMenuItem_Click(object sender, EventArgs e)
{
Main.Instance.LaunchKSP();
}
private void NavBackwardToolButton_Click(object sender, EventArgs e)
{
NavGoBackward();
}
private void NavForwardToolButton_Click(object sender, EventArgs e)
{
NavGoForward();
}
private void ModList_SelectedIndexChanged(object sender, EventArgs e)
{
// Skip if already disposed (i.e. after the form has been closed).
// Needed for TransparentTextBoxes
if (IsDisposed)
{
return;
}
var module = SelectedModule;
if (OnSelectedModuleChanged != null)
{
OnSelectedModuleChanged(module);
}
if (module != null)
{
NavSelectMod(module);
}
}
/// <summary>
/// Called when there's a click on the ModGrid header row.
/// Handles sorting and the header right click context menu.
/// </summary>
private void ModList_HeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
// Left click -> sort by new column / change sorting direction.
if (e.Button == MouseButtons.Left)
{
var new_sort_column = ModGrid.Columns [e.ColumnIndex];
var current_sort_column = ModGrid.Columns [Main.Instance.configuration.SortByColumnIndex];
// Reverse the sort order if the current sorting column is clicked again.
Main.Instance.configuration.SortDescending = new_sort_column == current_sort_column && !Main.Instance.configuration.SortDescending;
// Reset the glyph.
current_sort_column.HeaderCell.SortGlyphDirection = SortOrder.None;
Main.Instance.configuration.SortByColumnIndex = new_sort_column.Index;
UpdateFilters();
}
// Right click -> Bring up context menu to change visibility of columns.
else if (e.Button == MouseButtons.Right)
{
// Start from scrap: clear the entire item list, then add all options again.
ModListHeaderContextMenuStrip.Items.Clear();
// Add columns
ModListHeaderContextMenuStrip.Items.AddRange(
ModGrid.Columns.Cast<DataGridViewColumn>()
.Where(col => col.Name != "Installed" && col.Name != "UpdateCol" && col.Name != "ReplaceCol")
.Select(col => new ToolStripMenuItem()
{
Name = col.Name,
Text = col.HeaderText,
Checked = col.Visible,
Tag = col
})
.ToArray()
);
// Separator
ModListHeaderContextMenuStrip.Items.Add(new ToolStripSeparator());
// Add tags
ModListHeaderContextMenuStrip.Items.AddRange(
mainModList.ModuleTags.Tags.OrderBy(kvp => kvp.Key)
.Select(kvp => new ToolStripMenuItem()
{
Name = kvp.Key,
Text = kvp.Key,
Checked = kvp.Value.Visible,
Tag = kvp.Value,
})
.ToArray()
);
// Show the context menu on cursor position.
ModListHeaderContextMenuStrip.Show(Cursor.Position);
}
}
/// <summary>
/// Called if a ToolStripButton of the header context menu is pressed.
/// </summary>
private void ModListHeaderContextMenuStrip_ItemClicked(object sender, System.Windows.Forms.ToolStripItemClickedEventArgs e)
{
// ClickedItem is of type ToolStripItem, we need ToolStripButton.
ToolStripMenuItem clickedItem = e.ClickedItem as ToolStripMenuItem;
DataGridViewColumn col = clickedItem?.Tag as DataGridViewColumn;
ModuleTag tag = clickedItem?.Tag as ModuleTag;
if (col != null)
{
col.Visible = !clickedItem.Checked;
Main.Instance.configuration.SetColumnVisibility(col.Name, !clickedItem.Checked);
if (col.Index == 0)
{
InstallAllCheckbox.Visible = col.Visible;
}
}
else if (tag != null)
{
tag.Visible = !clickedItem.Checked;
if (tag.Visible)
{
mainModList.ModuleTags.HiddenTags.Remove(tag.Name);
}
else
{
mainModList.ModuleTags.HiddenTags.Add(tag.Name);
}
mainModList.ModuleTags.Save(ModuleTagList.DefaultPath);
UpdateFilters();
}
}
/// <summary>
/// Called on key down when the mod list is focused.
/// Makes the Home/End keys go to the top/bottom of the list respectively.
/// </summary>
private void ModList_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.Home:
// First row.
ModGrid.CurrentCell = ModGrid.Rows[0].Cells[SelectableColumnIndex()];
e.Handled = true;
break;
case Keys.End:
// Last row.
ModGrid.CurrentCell = ModGrid.Rows[ModGrid.Rows.Count - 1].Cells[SelectableColumnIndex()];
e.Handled = true;
break;
case Keys.Space:
// If they've focused one of the checkbox columns, don't intercept
if (ModGrid.CurrentCell.ColumnIndex > 3)
{
DataGridViewRow row = ModGrid.CurrentRow;
// Toggle Update column if enabled, otherwise Install
for (int colIndex = 2; colIndex >= 0; --colIndex)
{
if (row?.Cells[colIndex] is DataGridViewCheckBoxCell)
{
// Need to change the state here, because the user hasn't clicked on a checkbox
row.Cells[colIndex].Value = !(bool)row.Cells[colIndex].Value;
ModGrid.CommitEdit(DataGridViewDataErrorContexts.Commit);
e.Handled = true;
break;
}
}
}
break;
}
}
/// <summary>
/// Called on key press when the mod is focused. Scrolls to the first mod with name
/// beginning with the key pressed. If more than one unique keys are pressed in under
/// a second, it searches for the combination of the keys pressed. If the same key is
/// being pressed repeatedly, it cycles through mods names beginning with that key.
/// If space is pressed, the checkbox at the current row is toggled.
/// </summary>
private void ModList_KeyPress(object sender, KeyPressEventArgs e)
{
// Don't search for spaces or newlines
if (e.KeyChar == (char)Keys.Space || e.KeyChar == (char)Keys.Enter)
{
return;
}
var key = e.KeyChar.ToString();
// Determine time passed since last key press.
TimeSpan interval = DateTime.Now - lastSearchTime;
if (interval.TotalSeconds < 1)
{
// Last keypress was < 1 sec ago, so combine the last and current keys.
key = lastSearchKey + key;
}
// Remember the current time and key.
lastSearchTime = DateTime.Now;
lastSearchKey = key;
if (key.Distinct().Count() == 1)
{
// Treat repeating and single keypresses the same.
key = key.Substring(0, 1);
}
FocusMod(key, false);
e.Handled = true;
}
/// <summary>
/// I'm pretty sure this is what gets called when the user clicks on a ticky in the mod list.
/// </summary>
private void ModList_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
ModGrid.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
private void ModList_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.Button != MouseButtons.Left)
return;
if (e.RowIndex < 0)
return;
DataGridViewRow row = ModGrid.Rows[e.RowIndex];
if (!(row.Cells[0] is DataGridViewCheckBoxCell))
return;
// Need to change the state here, because the user hasn't clicked on a checkbox.
row.Cells[0].Value = !(bool)row.Cells[0].Value;
ModGrid.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
private async void ModList_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
int row_index = e.RowIndex;
int column_index = e.ColumnIndex;
if (row_index < 0 || column_index < 0)
return;
DataGridView grid = sender as DataGridView;
DataGridViewRow row = grid?.Rows[row_index];
DataGridViewCell gridCell = row?.Cells[column_index];
if (gridCell is DataGridViewLinkCell)
{
// Launch URLs if found in grid
DataGridViewLinkCell cell = gridCell as DataGridViewLinkCell;
string cmd = cell?.Value.ToString();
if (!string.IsNullOrEmpty(cmd))
Utilities.ProcessStartURL(cmd);
}
else
{
GUIMod gui_mod = row?.Tag as GUIMod;
if (gui_mod != null)
{
switch (ModGrid.Columns[column_index].Name)
{
case "Installed":
gui_mod.SetInstallChecked(row, Installed);
// The above will call UpdateChangeSetAndConflicts, so we don't need to.
return;
case "AutoInstalled":
gui_mod.SetAutoInstallChecked(row, AutoInstalled);
if (OnRegistryChanged != null)
{
OnRegistryChanged();
}
break;
case "UpdateCol":
gui_mod.SetUpgradeChecked(row, UpdateCol);
break;
case "ReplaceCol":
gui_mod.SetReplaceChecked(row, ReplaceCol);
break;
}
await UpdateChangeSetAndConflicts(
Main.Instance.CurrentInstance,
RegistryManager.Instance(Main.Instance.CurrentInstance).registry
);
}
}
}
private void ModList_GotFocus(object sender, EventArgs e)
{
Util.Invoke(this, () =>
{
// Give the selected row the standard highlight color
ModGrid.RowsDefaultCellStyle.SelectionBackColor = SystemColors.Highlight;
ModGrid.RowsDefaultCellStyle.SelectionForeColor = SystemColors.HighlightText;
});
}
private void ModList_LostFocus(object sender, EventArgs e)
{
Util.Invoke(this, () =>
{
// Gray out the selected row so you can tell the mod list is not focused
ModGrid.RowsDefaultCellStyle.SelectionBackColor = SystemColors.Control;
ModGrid.RowsDefaultCellStyle.SelectionForeColor = SystemColors.ControlText;
});
}
private void InstallAllCheckbox_CheckChanged(object sender, EventArgs e)
{
if (InstallAllCheckbox.Checked)
{
// Reset changeset
ClearChangeSet();
}
else
{
// Uninstall all
foreach (DataGridViewRow row in mainModList.full_list_of_mod_rows.Values)
{
GUIMod mod = row.Tag as GUIMod;
if (mod.IsInstallChecked)
{
mod.SetInstallChecked(row, Installed, false);
}
}
}
}
public void ClearChangeSet()
{
foreach (DataGridViewRow row in mainModList.full_list_of_mod_rows.Values)
{
GUIMod mod = row.Tag as GUIMod;
if (mod.IsInstallChecked != mod.IsInstalled)
{
mod.SetInstallChecked(row, Installed, mod.IsInstalled);
}
mod.SetUpgradeChecked(row, UpdateCol, false);
mod.SetReplaceChecked(row, ReplaceCol, false);
}
}
/// <summary>
/// Find a column of the grid that can contain the CurrentCell.
/// Can't be hidden or an exception is thrown.
/// Shouldn't be a checkbox because we don't want the space bar to toggle.
/// </summary>
/// <returns>
/// Index of the column to use.
/// </returns>
private int SelectableColumnIndex()
{
// First try the currently active cell's column
return ModGrid.CurrentCell?.ColumnIndex
// If there's no currently active cell, use the first visible non-checkbox column
?? ModGrid.Columns.Cast<DataGridViewColumn>()
.FirstOrDefault(c => c is DataGridViewTextBoxColumn && c.Visible)?.Index
// Otherwise use the Installed checkbox column since it can't be hidden
?? Installed.Index;
}
public void FocusMod(string key, bool exactMatch, bool showAsFirst = false)
{
DataGridViewRow current_row = ModGrid.CurrentRow;
int currentIndex = current_row?.Index ?? 0;
DataGridViewRow first_match = null;
var does_name_begin_with_key = new Func<DataGridViewRow, bool>(row =>
{
GUIMod mod = row.Tag as GUIMod;
bool row_match;
if (exactMatch)
row_match = mod.Name == key || mod.Identifier == key;
else
row_match = mod.Name.StartsWith(key, StringComparison.OrdinalIgnoreCase) ||
mod.Abbrevation.StartsWith(key, StringComparison.OrdinalIgnoreCase) ||
mod.Identifier.StartsWith(key, StringComparison.OrdinalIgnoreCase);
if (row_match && first_match == null)
{
// Remember the first match to allow cycling back to it if necessary.
first_match = row;
}
if (key.Length == 1 && row_match && row.Index <= currentIndex)
{
// Keep going forward if it's a single key match and not ahead of the current row.
return false;
}
return row_match;
});
ModGrid.ClearSelection();
var rows = ModGrid.Rows.Cast<DataGridViewRow>().Where(row => row.Visible);
DataGridViewRow match = rows.FirstOrDefault(does_name_begin_with_key);
if (match == null && first_match != null)
{
// If there were no matches after the first match, cycle over to the beginning.
match = first_match;
}
if (match != null)
{
match.Selected = true;
ModGrid.CurrentCell = match.Cells[SelectableColumnIndex()];
if (showAsFirst)
ModGrid.FirstDisplayedScrollingRowIndex = match.Index;
}
else
{
Main.Instance.AddStatusMessage(Properties.Resources.MainNotFound);
}
}
private void ModList_MouseDown(object sender, MouseEventArgs e)
{
var rowIndex = ModGrid.HitTest(e.X, e.Y).RowIndex;
// Ignore header column to prevent errors.
if (rowIndex != -1 && e.Button == MouseButtons.Right)
{
// Detect the clicked cell and select the row.
ModGrid.ClearSelection();
ModGrid.Rows[rowIndex].Selected = true;
// Show the context menu.
ModListContextMenuStrip.Show(ModGrid, new Point(e.X, e.Y));
// Set the menu options.
var guiMod = (GUIMod)ModGrid.Rows[rowIndex].Tag;
downloadContentsToolStripMenuItem.Enabled = !guiMod.IsCached;
purgeContentsToolStripMenuItem.Enabled = guiMod.IsCached;
reinstallToolStripMenuItem.Enabled = guiMod.IsInstalled && !guiMod.IsAutodetected;
}
}
private void reinstallToolStripMenuItem_Click(object sender, EventArgs e)
{
GUIMod module = SelectedModule;
if (module == null || !module.IsCKAN)
return;
YesNoDialog reinstallDialog = new YesNoDialog();
string confirmationText = string.Format(Properties.Resources.MainReinstallConfirm, module.Name);
if (reinstallDialog.ShowYesNoDialog(Main.Instance, confirmationText) == DialogResult.No)
return;
IRegistryQuerier registry = RegistryManager.Instance(Main.Instance.CurrentInstance).registry;
// Build the list of changes, first the mod to remove:
List<ModChange> toReinstall = new List<ModChange>()
{
new ModChange(module.ToModule(), GUIModChangeType.Remove, null)
};
// Then everything we need to re-install:
var revdep = registry.FindReverseDependencies(new List<string>() { module.Identifier });
var goners = revdep.Union(
registry.FindRemovableAutoInstalled(
registry.InstalledModules.Where(im => !revdep.Contains(im.identifier))
).Select(im => im.Module.identifier)
);
foreach (string id in goners)
{
toReinstall.Add(new ModChange(
(mainModList.full_list_of_mod_rows[id]?.Tag as GUIMod).ToModule(),
GUIModChangeType.Install,
null
));
}
if (StartChangeSet != null)
{
StartChangeSet(toReinstall);
}
}
private void purgeContentsToolStripMenuItem_Click(object sender, EventArgs e)
{
// Purge other versions as well since the user is likely to want that
// and has no other way to achieve it
var selected = SelectedModule;
if (selected != null)
{
IRegistryQuerier registry = RegistryManager.Instance(Main.Instance.CurrentInstance).registry;
var allAvail = registry.AvailableByIdentifier(selected.Identifier);
foreach (CkanModule mod in allAvail)
{
Main.Instance.Manager.Cache.Purge(mod);
}
selected.UpdateIsCached();
Main.Instance.UpdateModContentsTree(selected.ToCkanModule(), true);
}
}
private void downloadContentsToolStripMenuItem_Click(object sender, EventArgs e)
{
Main.Instance.StartDownload(SelectedModule);
}
private void EditModSearch_ApplySearch(ModSearch search)
{
mainModList.SetSearch(search);
}
private void EditModSearch_SurrenderFocus()
{
Util.Invoke(this, () => ModGrid.Focus());
}
private void UpdateFilters()
{
Util.Invoke(this, _UpdateFilters);
}
private void _UpdateFilters()
{
if (ModGrid == null || mainModList?.full_list_of_mod_rows == null)
return;
// Each time a row in DataGridViewRow is changed, DataGridViewRow updates the view. Which is slow.
// To make the filtering process faster, Copy the list of rows. Filter out the hidden and replace the
// rows in DataGridView.
var rows = new DataGridViewRow[mainModList.full_list_of_mod_rows.Count];
mainModList.full_list_of_mod_rows.Values.CopyTo(rows, 0);
// Try to remember the current scroll position and selected mod
var scroll_col = Math.Max(0, ModGrid.FirstDisplayedScrollingColumnIndex);
GUIMod selected_mod = null;
if (ModGrid.CurrentRow != null)
{
selected_mod = (GUIMod) ModGrid.CurrentRow.Tag;
}
ModGrid.Rows.Clear();
foreach (var row in rows)
{
var mod = ((GUIMod) row.Tag);
row.Visible = mainModList.IsVisible(mod, Main.Instance.CurrentInstance.Name);
}
var sorted = this._SortRowsByColumn(rows.Where(row => row.Visible));
ModGrid.Rows.AddRange(sorted.ToArray());
// Find and select the previously selected row
if (selected_mod != null)
{
var selected_row = ModGrid.Rows.Cast<DataGridViewRow>()
.FirstOrDefault(row => selected_mod.Identifier.Equals(((GUIMod)row.Tag).Identifier));
if (selected_row != null)
{
ModGrid.CurrentCell = selected_row.Cells[scroll_col];
}
}
}
public async void UpdateModsList(Dictionary<string, bool> old_modules = null)
{
// Run the update in the background so the UI thread can appear alive
// Await it so potential (fatal) errors are thrown, not swallowed.
// Need to be on the GUI thread to get the translated strings
Main.Instance.tabController.RenameTab("WaitTabPage", Properties.Resources.MainModListWaitTitle);
await Task.Factory.StartNew(() =>
_UpdateModsList(old_modules)