Repository navigation
Expand file tree
/
Copy pathFormMain.cs
More file actions
1062 lines (894 loc) · 40.3 KB
/
Copy pathFormMain.cs
File metadata and controls
1062 lines (894 loc) · 40.3 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.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Sockets;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Rug.Osc;
using System.Diagnostics;
using Newtonsoft.Json;
using VRC.OSCQuery;
namespace VRCDebug
{
public partial class FormMain : Form
{
public FormMain()
{
InitializeComponent();
}
// Networking
static HttpClient _client = new HttpClient();
OSCQueryServiceProfile VRChatClient;
UdpClient udpClient = new UdpClient();
IPEndPoint vrChatEndpoint;
bool FindVRC = true;
// Data
BindingSource bindingSource = new BindingSource();
DataTable dataTable;
Dictionary<string, string> OSCValues = new Dictionary<string, string>();
Dictionary<string, ListSortDirection> columnSortDirections = new Dictionary<string, ListSortDirection>();
bool ShowBuiltins = true;
string avatarID = "";
string previousAvatarID = "";
int intParamCount = 0;
int floatParamCount = 0;
int boolParamCount = 0;
int unknownParamCount = 0;
// UI
bool isDragging = false;
Point dragCursorPoint = new Point(0, 0);
Point dragFormPoint = new Point(0, 0);
bool isNightMode = false;
int RefreshDelayInMs = 1000;
bool StopRefreshing = false;
bool PauseRefresh = false;
private Stopwatch stopwatch = new Stopwatch();
private Thread monitoringThread;
private bool uiResponsive;
EditedCell editedCell;
struct EditedCell
{
public string Name;
public string PreviousValue;
public string Type;
public DataGridViewCell CellReference;
}
private void FormMain_Load(object sender, EventArgs e)
{
// Default to . as the decimal separator
CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture;
CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.InvariantCulture;
// Load config values
Size WindowSize = ConfigManager.LoadWindowSize();
Width = WindowSize.Width;
Height = WindowSize.Height;
isNightMode = ConfigManager.LoadIsNightMode();
if (isNightMode)
ThemeManager.ApplyNightMode(Controls);
else
ThemeManager.ApplyDefaultMode(Controls);
// Form dragging extension
foreach (Control c in Controls)
{
if (c is Panel || c is Label && !(c is LinkLabel))
AddFormDraggingEvent(c);
}
AddFormDraggingEvent(labelRefreshRateGuide);
AddFormDraggingEvent(labelRefreshRate);
// Initial data setup
dataTable = new DataTable();
dataTable.Columns.Add("Name", typeof(string));
dataTable.Columns.Add("Type", typeof(string));
dataTable.Columns.Add("Value", typeof(string));
// Auto incrementing ID field
DataColumn idColumn = new DataColumn("ID", typeof(int));
idColumn.AutoIncrement = true;
idColumn.AutoIncrementSeed = 1;
idColumn.AutoIncrementStep = 1;
dataTable.Columns.Add(idColumn);
dataTable.PrimaryKey = new DataColumn[] { dataTable.Columns["ID"] };
bindingSource.DataSource = dataTable;
dataGridViewAvatarParameters.DataSource = bindingSource;
dataGridViewAvatarParameters.Columns["ID"].Visible = false;
// Allow only the "Value" column to be editable
foreach (DataGridViewColumn column in dataGridViewAvatarParameters.Columns)
{
if (column.Name != "Value")
column.ReadOnly = true;
}
// Start the UI responsiveness testing thread
monitoringThread = new Thread(MonitorUIThread);
monitoringThread.IsBackground = true;
monitoringThread.Start();
if (!backgroundWorkerRefresh.IsBusy)
backgroundWorkerRefresh.RunWorkerAsync();
}
// Find VRChat
public void RunOSCQuery()
{
try
{
int tcpPort = Extensions.GetAvailableTcpPort();
int udpPort = Extensions.GetAvailableUdpPort();
OSCQueryService oscQuery = new OSCQueryServiceBuilder()
.WithTcpPort(tcpPort)
.WithUdpPort(udpPort)
.WithServiceName("VRChat Debug+")
.AdvertiseOSC()
.AdvertiseOSCQuery()
.StartHttpServer()
.Build();
List<OSCQueryServiceProfile> oscQueryServiceProfiles = oscQuery.GetOSCQueryServices().ToList();
if (oscQueryServiceProfiles != null)
{
OSCQueryServiceProfile oscQueryServiceProfile = oscQueryServiceProfiles.FirstOrDefault(x => x.name.Contains("VRChat-Client"));
if (oscQueryServiceProfile != null)
{
VRChatClient = oscQueryServiceProfile;
vrChatEndpoint = new IPEndPoint(VRChatClient.address, 9000);
FindVRC = false;
Invoke(new Action(() => linkLabelOscLink.Text = "http://127.0.0.1:" + VRChatClient.port.ToString()));
Invoke(new Action(() => linkLabelOscLink.Visible = true));
Invoke(new Action(() => linkLabelOscLink.Left = panelRefreshRate.Left + panelRefreshRate.Width / 2 - linkLabelOscLink.Width / 2));
}
}
}
catch (Exception) { }
}
#region Data reading
// Read values from VRChat
private async void ReadValues()
{
if (VRChatClient == null)
{
FindVRC = true;
Invoke(new Action(() =>
{
labelParameterCount.Visible = false;
linkLabelOscLink.Visible = false;
labelAvatarID.Visible = false;
}));
return;
}
if (StopRefreshing)
return;
Dictionary<string, OSCQueryNode> oscQueryNodes = await GetParameterNodes(VRChatClient.address, VRChatClient.port);
if (oscQueryNodes == null)
return;
try
{
if (!StopRefreshing)
Invoke(new Action(() => DisplayData(oscQueryNodes, avatarID)));
}
catch (Exception) { }
}
// Reading parameters
public async Task<Dictionary<string, OSCQueryNode>> GetParameterNodes(IPAddress ip, int port)
{
OSCQueryRootNode rootNode = await GetTree(ip, port);
if (rootNode == null || rootNode.Contents == null) return null;
if (!rootNode.Contents.TryGetValue("avatar", out OSCQueryNode avatarNode)) return null;
if (!avatarNode.Contents.TryGetValue("parameters", out OSCQueryNode parametersNode)) return null;
Dictionary<string, OSCQueryNode> avatarQueryNodes = new Dictionary<string, OSCQueryNode>(avatarNode.Contents.Count);
Stack<OSCQueryNode> todoStack = new Stack<OSCQueryNode>(avatarNode.Contents.Count);
todoStack.Push(avatarNode);
// /avatar reading
while (todoStack.Count > 0)
{
OSCQueryNode oSCQueryNode = todoStack.Pop();
if (oSCQueryNode != avatarNode)
avatarQueryNodes.Add(oSCQueryNode.FullPath.Remove(0, "/avatar".Length), oSCQueryNode);
if (oSCQueryNode.Contents == null) continue;
foreach (var kvp in oSCQueryNode.Contents)
{
todoStack.Push(kvp.Value);
// Getting AvatarID
if (kvp.Key.Contains("change"))
avatarID = kvp.Value.Value.Length > 0 ? kvp.Value.Value[0].ToString() : "";
}
}
// /avatar/parameter reading
Dictionary<string, OSCQueryNode> oscQueryNodes = new Dictionary<string, OSCQueryNode>(parametersNode.Contents.Count);
todoStack.Push(parametersNode);
while (todoStack.Count > 0)
{
OSCQueryNode oscQueryNode = todoStack.Pop();
// Collect nodes without their full path
if (oscQueryNode != parametersNode)
oscQueryNodes.Add(oscQueryNode.FullPath.Remove(0, "/avatar/parameters/".Length), oscQueryNode);
if (oscQueryNode.Contents == null) continue;
foreach (KeyValuePair<string, OSCQueryNode> kvp in oscQueryNode.Contents)
{
todoStack.Push(kvp.Value);
}
}
// Collect data from /input, /tracking, and /chatbox into separate nodes
string[] rootPaths = new string[] { "input", "tracking", "chatbox" };
Dictionary<string, OSCQueryNode> inputNodes = new Dictionary<string, OSCQueryNode>();
Dictionary<string, OSCQueryNode> trackingNodes = new Dictionary<string, OSCQueryNode>();
Dictionary<string, OSCQueryNode> chatboxNodes = new Dictionary<string, OSCQueryNode>();
foreach (string rootPath in rootPaths)
{
if (!rootNode.Contents.TryGetValue(rootPath, out OSCQueryNode baseNode)) continue;
Dictionary<string, OSCQueryNode> queryNodes = new Dictionary<string, OSCQueryNode>(baseNode.Contents.Count);
todoStack.Push(baseNode);
// Collecting nodes for each root path
while (todoStack.Count > 0)
{
OSCQueryNode oscQueryNode = todoStack.Pop();
if (oscQueryNode != baseNode)
queryNodes.Add(oscQueryNode.FullPath.Remove(0, $"/{rootPath}/".Length), oscQueryNode);
if (oscQueryNode.Contents == null) continue;
foreach (KeyValuePair<string, OSCQueryNode> kvp in oscQueryNode.Contents)
{
todoStack.Push(kvp.Value);
}
}
switch (rootPath)
{
case "input":
inputNodes = queryNodes;
break;
case "tracking":
trackingNodes = queryNodes;
break;
case "chatbox":
chatboxNodes = queryNodes;
break;
}
}
return oscQueryNodes;
}
// Get root node
public static async Task<OSCQueryRootNode> GetTree(IPAddress ip, int port)
{
try
{
return await GetOSCTree(ip, port);
}
catch (Exception e)
{
Console.Write(e.StackTrace);
return null;
}
}
// Taken from the Extension class, to be able to add exception handling
public static async Task<OSCQueryRootNode> GetOSCTree(IPAddress ip, int port)
{
try
{
HttpResponseMessage response = await _client.GetAsync($"http://{ip}:{port}/");
if (!response.IsSuccessStatusCode)
return new OSCQueryRootNode();
string oscTreeString = await response.Content.ReadAsStringAsync();
OSCQueryRootNode oscTree = new OSCQueryRootNode();
try
{
JsonConvert.DeserializeObject<object>(oscTreeString);
}
catch (JsonException)
{
return new OSCQueryRootNode();
}
oscTree = OSCQueryRootNode.FromString(oscTreeString);
if (oscTree == null)
return new OSCQueryRootNode();
return oscTree;
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace);
return new OSCQueryRootNode();
}
}
private void backgroundWorkerRefresh_DoWork(object sender, DoWorkEventArgs e)
{
// StopRefreshing true --> Closing form
while (!StopRefreshing)
{
if (FindVRC)
{
while (VRChatClient == null)
{
if (!StopRefreshing)
{
Invoke(new Action(() =>
{
labelParameterCount.Visible = false;
linkLabelOscLink.Visible = false;
labelAvatarID.Visible = false;
}));
// Try to connect to VRC
RunOSCQuery();
Thread.Sleep(2000);
}
}
}
// Keep refreshing data while
// not paused, and connected to VRC
if (!PauseRefresh && !FindVRC)
{
if (!StopRefreshing)
{
ReadValues();
Thread.Sleep(RefreshDelayInMs);
}
}
}
}
private void trackBarRefreshRate_ValueChanged(object sender, EventArgs e)
{
if (trackBarRefreshRate.Value == trackBarRefreshRate.Minimum)
{
RefreshDelayInMs = 1000;
labelRefreshRate.Text = "Paused";
PauseRefresh = true;
}
else
{
RefreshDelayInMs = trackBarRefreshRate.Value * 100;
labelRefreshRate.Text = RefreshDelayInMs + " ms";
PauseRefresh = false;
}
labelRefreshRate.Left = panelRefreshRate.Width / 2 - labelRefreshRate.Width / 2;
}
#endregion Data reading
#region Data sending
private void dataGridViewAvatarParameters_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
// Don't update while editing
PauseRefresh = true;
// Set editing cell forecolor
dataGridViewAvatarParameters.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.ForeColor = isNightMode ? ThemeManager.NightGridHeaderForegroundColor : ThemeManager.DefaultGridHeaderForegroundColor;
// Save data about the current row
DataGridViewRow currentRow = dataGridViewAvatarParameters.Rows[dataGridViewAvatarParameters.CurrentCell.RowIndex];
editedCell = new EditedCell()
{
Name = currentRow.Cells["Name"].Value.ToString(),
PreviousValue = currentRow.Cells["Value"].Value.ToString().Trim().ToLower(),
Type = currentRow.Cells["Type"].Value.ToString(),
CellReference = dataGridViewAvatarParameters.Rows[e.RowIndex].Cells[e.ColumnIndex]
};
// If value is bool, toggle it and stop editing
if (editedCell.Type == "Bool")
{
if (editedCell.PreviousValue.ToLower() == "false")
dataGridViewAvatarParameters.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "True";
else
dataGridViewAvatarParameters.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "False";
e.Cancel = true;
dataGridViewAvatarParameters_CellEndEdit(sender, new DataGridViewCellEventArgs(e.ColumnIndex, e.RowIndex));
}
}
private void dataGridViewAvatarParameters_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
// Resume updating
PauseRefresh = false;
if (VRChatClient == null)
{
Invoke(new Action(() =>
{
labelParameterCount.Visible = false;
linkLabelOscLink.Visible = false;
labelAvatarID.Visible = false;
}));
return;
}
if (StopRefreshing)
return;
// Mark parameter as changed
DataGridViewCell nameCell = dataGridViewAvatarParameters.Rows[e.RowIndex].Cells["Name"];
DataGridViewCell valueCell = dataGridViewAvatarParameters.Rows[e.RowIndex].Cells["Value"];
string key = nameCell.Value.ToString();
string newValue = valueCell.Value.ToString();
if (OSCValues.ContainsKey(key))
OSCValues[key] = newValue;
else
OSCValues.Add(key, newValue);
// OSC Data sending
string valueToSend = editedCell.CellReference.Value.ToString().Trim().ToLower();
// Not sending, as the value didn't change
if (editedCell.PreviousValue.Trim().ToLower() == valueToSend)
return;
bool regexMatch = false;
byte[] messageBytes;
switch (editedCell.Type)
{
case "Bool":
if (valueToSend == "t" || valueToSend == "true" || valueToSend == "1" || valueToSend == "1.0")
messageBytes = new OscMessage("/avatar/parameters/" + editedCell.Name, new object[] { true }).ToByteArray();
else
messageBytes = new OscMessage("/avatar/parameters/" + editedCell.Name, new object[] { false }).ToByteArray();
break;
case "Float":
regexMatch = Regex.IsMatch(valueToSend, @"^[\d,.\-]+$");
if (!regexMatch)
messageBytes = new OscMessage("/avatar/parameters/" + editedCell.Name, new object[] { 0.0f }).ToByteArray();
else
messageBytes = new OscMessage("/avatar/parameters/" + editedCell.Name, new object[] { float.Parse(valueToSend.Replace(',', '.')) }).ToByteArray();
break;
case "Integer":
regexMatch = Regex.IsMatch(valueToSend, @"^[\d]+$");
if (!regexMatch)
messageBytes = new OscMessage("/avatar/parameters/" + editedCell.Name, new object[] { 0 }).ToByteArray();
else
messageBytes = new OscMessage("/avatar/parameters/" + editedCell.Name, new object[] { int.Parse(valueToSend) }).ToByteArray();
break;
default:
// Unknown type
messageBytes = new OscMessage("/avatar/parameters/" + editedCell.Name, new object[] { valueToSend }).ToByteArray();
break;
}
udpClient.Send(messageBytes, messageBytes.Length, vrChatEndpoint);
// Refresh data after sending OSC packet
ReadValues();
}
#endregion Data sending
#region Link labels
private void linkLabelOscLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
Process.Start(linkLabelOscLink.Text);
}
private void labelAvatarID_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
Process.Start("https://vrchat.com/home/avatar/" + labelAvatarID.Text);
}
#endregion Link labels
#region Sorting
private void SortDataGridView(string primaryColumn, ListSortDirection primaryDirection, string secondaryColumn)
{
DataView dataView = dataTable.DefaultView;
string primaryDirectionStr = primaryDirection == ListSortDirection.Ascending ? "ASC" : "DESC";
dataView.Sort = $"{primaryColumn} {primaryDirectionStr}, {secondaryColumn} ASC";
}
private void ResetSorting()
{
DataView dataView = dataTable.DefaultView;
dataView.Sort = "";
columnSortDirections.Clear();
foreach (DataGridViewColumn column in dataGridViewAvatarParameters.Columns)
{
column.HeaderCell.SortGlyphDirection = SortOrder.None;
}
}
private void dataGridViewAvatarParameters_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
DataGridViewColumn clickedColumn = dataGridViewAvatarParameters.Columns[e.ColumnIndex];
string columnName = clickedColumn.Name;
if (e.Button == MouseButtons.Right || e.Button == MouseButtons.Middle)
{
ResetSorting();
ReadValues();
return;
}
// Determine the new sort direction
if (!columnSortDirections.TryGetValue(columnName, out ListSortDirection sortDirection))
sortDirection = ListSortDirection.Ascending;
else
sortDirection = sortDirection == ListSortDirection.Ascending ? ListSortDirection.Descending : ListSortDirection.Ascending;
// Update the dictionary with the new sort direction
columnSortDirections[columnName] = sortDirection;
// Update the sort glyph
clickedColumn.HeaderCell.SortGlyphDirection = sortDirection == ListSortDirection.Ascending ? SortOrder.Ascending : SortOrder.Descending;
// Sort
SortDataGridView(columnName, sortDirection, "Name");
ReadValues();
}
#endregion Sorting
#region Form moving events
private void FormMain_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
isDragging = true;
dragCursorPoint = Cursor.Position;
dragFormPoint = Location;
}
if (e.Button == MouseButtons.Middle)
{
Size = new Size(1216, 606);
}
}
private void AddFormDraggingEvent(Control control)
{
control.MouseDown += FormMain_MouseDown;
control.MouseMove += FormMain_MouseMove;
control.MouseUp += FormMain_MouseUp;
}
private void FormMain_MouseMove(object sender, MouseEventArgs e)
{
if (isDragging)
{
Point dif = Point.Subtract(Cursor.Position, new Size(dragCursorPoint));
Location = Point.Add(dragFormPoint, new Size(dif));
}
}
private void FormMain_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
isDragging = false;
}
#endregion Form moving events
#region Night mode toggle
private void buttonToggleTheme_Click(object sender, EventArgs e) { ToggleNightMode(); }
private void ToggleNightMode()
{
isNightMode = !isNightMode;
ConfigManager.SaveIsNightMode(isNightMode);
if (isNightMode)
ThemeManager.ApplyNightMode(Controls);
else
ThemeManager.ApplyDefaultMode(Controls);
// Refresh data to reflect theme change
ReadValues();
}
#endregion Night mode toggle
#region Other
private void checkBoxBuiltInParams_CheckedChanged(object sender, EventArgs e)
{
ShowBuiltins = checkBoxBuiltInParams.Checked;
// Refresh data to add the builtins back into the list
ReadValues();
}
private void buttonReloadList_Click(object sender, EventArgs e)
{
dataTable.Clear();
labelParameterCount.Text = "0 Parameters";
labelAvatarID.Text = "";
}
private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
{
StopRefreshing = true;
try
{
if (monitoringThread != null && monitoringThread.IsAlive)
monitoringThread.Abort();
ConfigManager.SaveWindowSize(Width, Height);
udpClient?.Dispose();
}
catch (Exception) { }
}
private void textBoxSearchParameter_TextChanged(object sender, EventArgs e)
{
string searchValue = textBoxSearchParameter.Text;
if (string.IsNullOrWhiteSpace(searchValue))
{
if (dataGridViewAvatarParameters.DataSource is BindingSource bindingSourceLocal)
bindingSourceLocal.RemoveFilter();
return;
}
// Split the search terms by space or comma
string[] searchTerms = searchValue.Split(new char[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries);
List<string> filterParts = new List<string>();
foreach (string term in searchTerms)
{
// Make \ and / interchangeable
string normalizedSearchValue = term.Replace("\\", "/").Replace("'", "''");
string normalizedSearchValueWithBackslash = normalizedSearchValue.Replace("/", "\\");
if ((term.StartsWith("\"") && term.EndsWith("\"")) || (term.StartsWith("'") && term.EndsWith("'")))
{
// Exact search
string exactValue = normalizedSearchValue.Trim('"', '\'');
string exactValueWithBackslash = normalizedSearchValueWithBackslash.Trim('"', '\'');
filterParts.Add($"Name = '{exactValue}' OR Type = '{exactValue}' OR Value = '{exactValue}' OR " +
$"Name = '{exactValueWithBackslash}' OR Type = '{exactValueWithBackslash}' OR Value = '{exactValueWithBackslash}'");
}
else
{
// Partial search
filterParts.Add($"Name LIKE '%{normalizedSearchValue}%' OR Type LIKE '%{normalizedSearchValue}%' OR Value LIKE '%{normalizedSearchValue}%' OR " +
$"Name LIKE '%{normalizedSearchValueWithBackslash}%' OR Type LIKE '%{normalizedSearchValueWithBackslash}%' OR Value LIKE '%{normalizedSearchValueWithBackslash}%'");
}
}
string filterExpression = string.Join(" AND ", filterParts);
if (dataGridViewAvatarParameters.DataSource is BindingSource bindingSource)
bindingSource.Filter = filterExpression;
// Refresh data to have proper colors immediately
ReadValues();
}
// Get info about name cell
private void dataGridViewAvatarParameters_CellMouseEnter(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0 && e.ColumnIndex == 0)
{
DataGridViewCell cell = ((DataGridView)sender)[e.ColumnIndex, e.RowIndex];
textBoxGuide.Text = GetBuiltinParameterDescription(cell);
}
}
private void dataGridViewAvatarParameters_CellMouseLeave(object sender, DataGridViewCellEventArgs e)
{
textBoxGuide.Text = "";
}
// Get info about built-in parameters
private string GetBuiltinParameterDescription(DataGridViewCell cell)
{
if (cell.Value != null)
{
string helperText = "";
if (!BuiltinParams.List.ContainsKey(cell.Value.ToString()))
helperText = "\r\n\r\nThis is a custom parameter";
if (BuiltinParams.List.ContainsKey(cell.Value.ToString()))
helperText += "\r\n\r\nThis is a built-in parameter that can't be changed";
if (BuiltinParams.List.ContainsKey(cell.Value.ToString()))
return BuiltinParams.List[cell.Value.ToString()] + helperText;
return cell.Value.ToString() + helperText;
}
return "";
}
// Display parameter count by type
private void labelParameterCount_MouseEnter(object sender, EventArgs e)
{
if (unknownParamCount == 0)
{
textBoxGuide.Text = intParamCount.ToString() + " Int\r\n" +
floatParamCount.ToString() + " Float\r\n" +
boolParamCount.ToString() + " Bool";
}
else
{
textBoxGuide.Text = intParamCount.ToString() + " Int\r\n" +
floatParamCount.ToString() + " Float\r\n" +
boolParamCount.ToString() + " Bool\r\n" +
unknownParamCount.ToString() + " Unknown";
}
}
private void labelParameterCount_MouseLeave(object sender, EventArgs e)
{
textBoxGuide.Text = "";
}
// Debug logging
private void Log(string text)
{
Debug.WriteLine(text);
}
#endregion Other
public void DisplayData(Dictionary<string, OSCQueryNode> keyValuePairs, string AvatarID)
{
if (InvokeRequired)
{
try
{
if (!StopRefreshing)
Invoke(new Action(() => DisplayData(keyValuePairs, AvatarID)));
}
catch (Exception) { }
return;
}
// Check if AvatarID has changed
bool isAvatarIDChanged = AvatarID != previousAvatarID;
if (isAvatarIDChanged)
{
// Clear the data table and value change tracker
dataTable.Clear();
OSCValues.Clear();
previousAvatarID = AvatarID;
}
// Save the current scroll position and selected rows
int firstDisplayedScrollingRowIndex = dataGridViewAvatarParameters.FirstDisplayedScrollingRowIndex;
List<int> selectedRows = dataGridViewAvatarParameters.SelectedRows.Cast<DataGridViewRow>().Select(r => r.Index).ToList();
// Suspend updates to the DataGridView
dataGridViewAvatarParameters.SuspendLayout();
dataTable.BeginLoadData();
// Create a copy of the dictionary for safe iteration
Dictionary<string, OSCQueryNode> keyValuePairsCopy = new Dictionary<string, OSCQueryNode>(keyValuePairs);
// Create dictionaries for fast lookups
Dictionary<string, DataRow> existingRows = dataTable.AsEnumerable().ToDictionary(row => row.Field<string>("Name"));
Dictionary<string, DataGridViewRow> dataGridViewRowDict = dataGridViewAvatarParameters.Rows.Cast<DataGridViewRow>()
.ToDictionary(r => r.Cells["Name"].Value.ToString());
intParamCount = 0;
floatParamCount = 0;
boolParamCount = 0;
unknownParamCount = 0;
// Update existing rows and add new rows
foreach (var kvp in keyValuePairsCopy)
{
if (kvp.Key != null && kvp.Value != null && kvp.Value.OscType != null && kvp.Value.Value != null)
{
string name = kvp.Key;
string type = kvp.Value.OscType.ToLower();
string value = "";
switch (type)
{
case "i":
type = "Integer";
value = kvp.Value.Value[0].ToString();
if (!BuiltinParams.List.ContainsKey(name))
intParamCount++;
else
{
if (ShowBuiltins)
intParamCount++;
}
break;
case "f":
type = "Float";
value = Math.Round(Convert.ToDecimal(kvp.Value.Value[0]), 4).ToString("F4");
if (!BuiltinParams.List.ContainsKey(name))
floatParamCount++;
else
{
if (ShowBuiltins)
floatParamCount++;
}
break;
case "t":
type = "Bool";
value = kvp.Value.Value[0].ToString();
if (!BuiltinParams.List.ContainsKey(name))
boolParamCount++;
else
{
if (ShowBuiltins)
boolParamCount++;
}
break;
default:
value = kvp.Value.Value[0].ToString();
if (!BuiltinParams.List.ContainsKey(name))
unknownParamCount++;
else
{
if (ShowBuiltins)
unknownParamCount++;
}
break;
}
if (existingRows.TryGetValue(name, out DataRow row))
{
// Check for changes in values
if (!OSCValues.ContainsKey(name))
OSCValues[name] = row["Value"].ToString();
// Update existing row and track value changes
row["Type"] = type;
row["Value"] = value;
existingRows.Remove(name); // Mark this parameter as handled
}
else
{
if (!BuiltinParams.List.ContainsKey(name) || ShowBuiltins)
{
dataTable.Rows.Add(name, type, value);
OSCValues[name] = value;
}
}
// Set up ReadOnly values
if (dataGridViewRowDict.TryGetValue(name, out DataGridViewRow dataGridViewRow))
{
bool isReadOnly = (kvp.Value.Access == Attributes.AccessValues.ReadOnly);
dataGridViewRow.ReadOnly = isReadOnly;
if (isReadOnly)
{
if (isNightMode)
dataGridViewRow.Cells["Value"].Style.BackColor = Color.FromArgb(90, 90, 90);
else
dataGridViewRow.Cells["Value"].Style.BackColor = Color.LightGray;
}
}
}
}
// Rows that were not updated and are in BuiltinParams.List are removed if ShowBuiltins is false
if (!ShowBuiltins)
{
List<DataRow> rowsToRemove = dataTable.AsEnumerable()
.Where(row => BuiltinParams.List.ContainsKey(row.Field<string>("Name")))
.ToList();
foreach (var row in rowsToRemove)
{
dataTable.Rows.Remove(row);
}
}
// Catch any bad data
try
{
// Display data changes on the UI
dataTable.EndLoadData();
}
catch (Exception) { }
dataGridViewAvatarParameters.ResumeLayout();
// Refresh once to update the selected cell's value
dataGridViewAvatarParameters.Refresh();
// Cell colors
foreach (DataGridViewRow row in dataGridViewAvatarParameters.Rows)
{
string name = row.Cells["Name"].Value.ToString();
row.Cells["Name"].Style.ForeColor = isNightMode ? Color.White : Color.Black;
// Bools
if (row.Cells["Type"].Value.ToString() == "Bool")
{
if (row.Cells["Value"].Value.ToString() == "True")
{
// True color
if (isNightMode)
row.Cells["Value"].Style.ForeColor = Color.LimeGreen;
else
row.Cells["Value"].Style.ForeColor = Color.FromArgb(0, 190, 0);
}
else
{
// False color
if (isNightMode)
row.Cells["Value"].Style.ForeColor = Color.FromArgb(255, 80, 80);
else
row.Cells["Value"].Style.ForeColor = Color.Red;
}
}
else
{
// Every other type
if (isNightMode)
row.Cells["Value"].Style.ForeColor = Color.White;
else
row.Cells["Value"].Style.ForeColor = Color.Black;
}
// Types
if (isNightMode)
row.Cells["Type"].Style.ForeColor = Color.White;
else
row.Cells["Type"].Style.ForeColor = Color.Black;
}
// Parameter count
labelParameterCount.Text = dataGridViewAvatarParameters.RowCount.ToString() + " Parameters";
labelParameterCount.Left = panelRefreshRate.Left + panelRefreshRate.Width / 2 - labelParameterCount.Width / 2;
labelParameterCount.Visible = true;
// AvatarID