-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathComponent.cs
More file actions
643 lines (558 loc) · 24.4 KB
/
Copy pathComponent.cs
File metadata and controls
643 lines (558 loc) · 24.4 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
using LiveSplit.Model;
using LiveSplit.UI;
using LiveSplit.UI.Components;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace LiveSplit.TimerSync
{
public class Component : IComponent
{
private readonly LiveSplitState state;
private readonly Settings settings;
// Synchronization Variables
private SyncMode currentActiveMode = SyncMode.Off;
private string currentActiveIP = "";
private int currentActivePort = 0;
private TcpListener tcpListener;
private TcpClient tcpClient;
private bool stopNetworkThreads = false;
private Thread hostListenerThread;
private Thread clientConnectionThread;
private readonly object clientsLock = new object();
private readonly List<TcpClient> connectedClients = new List<TcpClient>();
private readonly ConcurrentQueue<string> incomingMessages = new ConcurrentQueue<string>();
private DateTime lastSyncTime = DateTime.MinValue;
private DateTime lastLayoutSyncTime = DateTime.MinValue;
private volatile bool isClientConnected = false;
// Caching variables for zero-allocation Text Component sync
private readonly Dictionary<string, string> hostTextComponentCache = new Dictionary<string, string>();
private readonly Dictionary<string, string> currentTextComponents = new Dictionary<string, string>();
private readonly List<string> removedKeys = new List<string>();
private Type cachedTextComponentType = null;
public string ComponentName => "Timer Sync";
// Fake Text Component
public float VerticalHeight => 0f;
public float HorizontalWidth => 0f;
public float MinimumWidth => 0f;
public float MinimumHeight => 0f;
public float PaddingTop => 0; public float PaddingBottom => 0; public float PaddingLeft => 0; public float PaddingRight => 0;
public IDictionary<string, Action> ContextMenuControls => null;
public Component(LiveSplitState state)
{
this.state = state;
this.settings = new Settings();
// Register Host Timer Event Listeners
state.OnStart += State_OnStart;
state.OnSplit += State_OnSplit;
state.OnUndoSplit += State_OnUndoSplit;
state.OnSkipSplit += State_OnSkipSplit;
state.OnReset += State_OnReset;
state.OnPause += State_OnPause;
state.OnResume += State_OnResume;
}
public void Update(IInvalidator invalidator, LiveSplitState state, float width, float height, LayoutMode mode)
{
// Check P2P Sync State
CheckNetwork();
// Update status string and colors in the Settings GUI
if (settings.SyncMode == SyncMode.Off)
{
settings.SetStatusText("", "Disabled", Color.Crimson);
}
else if (settings.SyncMode == SyncMode.Host)
{
lock (clientsLock)
{
int count = connectedClients.Count;
Color color = count > 0 ? Color.ForestGreen : Color.Crimson;
settings.SetStatusText("Hosting ", $"({count} Client{(count == 1 ? "" : "s")})", color);
}
}
else if (settings.SyncMode == SyncMode.Client)
{
if (isClientConnected)
{
settings.SetStatusText("", "Connected to Host", Color.ForestGreen);
}
else
{
settings.SetStatusText("", "Connecting to Host...", Color.Crimson);
}
}
// CLIENT: Process received messages on UI thread
while (incomingMessages.TryDequeue(out string message))
{
ProcessMessage(message);
}
// HOST: Send timer, text components to clients
if (settings.SyncMode == SyncMode.Host)
{
if (state.CurrentPhase == TimerPhase.Running)
{
if ((DateTime.Now - lastSyncTime).TotalMilliseconds >= 20)
{
lastSyncTime = DateTime.Now;
TimeSpan? rTime = state.CurrentTime.RealTime;
TimeSpan? gTime = state.CurrentTime.GameTime;
if (rTime == null) rTime = TimeStamp.Now - state.StartTimeWithOffset;
if (gTime == null) gTime = (TimeStamp.Now - state.StartTimeWithOffset) - state.LoadingTimes;
long rTicks = rTime?.Ticks ?? 0;
long gTicks = gTime?.Ticks ?? 0;
SendToAllClients($"SYNC;{state.CurrentSplitIndex};{rTicks};{gTicks}");
}
}
if ((DateTime.Now - lastLayoutSyncTime).TotalMilliseconds >= 40)
{
lastLayoutSyncTime = DateTime.Now;
SyncTextComponents();
}
}
// CLIENT: Force comparison to Game Time
if (settings.SyncMode == SyncMode.Client)
{
if (state.CurrentTimingMethod != TimingMethod.GameTime)
{
state.CurrentTimingMethod = TimingMethod.GameTime;
}
}
}
// Required by IComponent
public void DrawVertical(Graphics g, LiveSplitState state, float width, Region clipRegion) { }
public void DrawHorizontal(Graphics g, LiveSplitState state, float height, Region clipRegion) { }
public System.Windows.Forms.Control GetSettingsControl(LayoutMode mode) => settings;
public System.Xml.XmlNode GetSettings(System.Xml.XmlDocument doc) => settings.GetSettings(doc);
public void SetSettings(System.Xml.XmlNode node) => settings.SetSettings(node);
public void Dispose()
{
if (state != null)
{
state.OnStart -= State_OnStart;
state.OnSplit -= State_OnSplit;
state.OnUndoSplit -= State_OnUndoSplit;
state.OnSkipSplit -= State_OnSkipSplit;
state.OnReset -= State_OnReset;
state.OnPause -= State_OnPause;
state.OnResume -= State_OnResume;
}
StopAllNetwork();
}
private void CheckNetwork()
{
if (settings.SyncMode != currentActiveMode ||
settings.SyncIP != currentActiveIP ||
settings.SyncPort != currentActivePort)
{
StopAllNetwork();
currentActiveMode = settings.SyncMode;
currentActiveIP = settings.SyncIP;
currentActivePort = settings.SyncPort;
if (currentActiveMode == SyncMode.Host)
{
StartHost();
}
else if (currentActiveMode == SyncMode.Client)
{
StartClient();
}
}
}
private void StartHost()
{
stopNetworkThreads = false;
hostListenerThread = new Thread(ListenForClients) { IsBackground = true, Name = "P2PSyncHost" };
hostListenerThread.Start();
}
private void StartClient()
{
stopNetworkThreads = false;
clientConnectionThread = new Thread(ListenForHost) { IsBackground = true, Name = "P2PSyncClient" };
clientConnectionThread.Start();
}
private void StopAllNetwork()
{
stopNetworkThreads = true;
isClientConnected = false;
try { tcpListener?.Stop(); } catch { }
try { tcpClient?.Close(); } catch { }
lock (clientsLock)
{
foreach (var client in connectedClients)
{
try { client.Close(); } catch { }
}
connectedClients.Clear();
}
if (hostListenerThread != null && hostListenerThread.IsAlive) hostListenerThread.Join(200);
if (clientConnectionThread != null && clientConnectionThread.IsAlive) clientConnectionThread.Join(200);
tcpListener = null;
tcpClient = null;
hostListenerThread = null;
clientConnectionThread = null;
hostTextComponentCache.Clear();
}
private void ListenForClients()
{
try
{
tcpListener = new TcpListener(IPAddress.Any, currentActivePort);
tcpListener.Start();
while (!stopNetworkThreads)
{
TcpClient client = tcpListener.AcceptTcpClient();
lock (clientsLock)
{
connectedClients.Add(client);
}
var monitorThread = new Thread(() => MonitorClient(client)) { IsBackground = true };
monitorThread.Start();
}
}
catch { }
}
private void MonitorClient(TcpClient client)
{
try
{
var stream = client.GetStream();
byte[] buffer = new byte[128];
while (!stopNetworkThreads && client.Connected)
{
int readBytes = stream.Read(buffer, 0, buffer.Length);
if (readBytes == 0) break;
}
}
catch { }
finally
{
lock (clientsLock) { connectedClients.Remove(client); }
try { client.Close(); } catch { }
}
}
private void ListenForHost()
{
while (!stopNetworkThreads)
{
try
{
isClientConnected = false;
tcpClient = new TcpClient();
var result = tcpClient.BeginConnect(currentActiveIP, currentActivePort, null, null);
bool completed = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(3));
if (!completed || !tcpClient.Connected)
{
tcpClient.Close();
tcpClient = null;
Thread.Sleep(3000);
continue;
}
isClientConnected = true;
using (var stream = tcpClient.GetStream())
using (var reader = new StreamReader(stream))
{
while (!stopNetworkThreads && isClientConnected)
{
string line = reader.ReadLine();
if (line == null) break;
if (!string.IsNullOrEmpty(line))
{
incomingMessages.Enqueue(line);
}
}
}
}
catch { }
finally
{
isClientConnected = false;
try { tcpClient?.Close(); } catch { }
tcpClient = null;
}
if (!stopNetworkThreads) Thread.Sleep(3000);
}
}
private void SendToAllClients(string message)
{
byte[] data = Encoding.UTF8.GetBytes(message + "\n");
lock (clientsLock)
{
for (int i = connectedClients.Count - 1; i >= 0; i--)
{
var client = connectedClients[i];
if (client == null || !client.Connected)
{
connectedClients.RemoveAt(i);
continue;
}
try
{
var stream = client.GetStream();
stream.Write(data, 0, data.Length);
}
catch
{
try { client.Close(); } catch { }
connectedClients.RemoveAt(i);
}
}
}
}
// Host Side: Layout Text Components
private void SyncTextComponents()
{
if (settings.SyncMode != SyncMode.Host) return;
currentTextComponents.Clear();
foreach (var component in state.Layout.Components)
{
if (component.GetType().Name == "TextComponent")
{
try
{
var settingsObj = component.GetType().GetProperty("Settings")?.GetValue(component, null);
if (settingsObj != null)
{
string text1 = settingsObj.GetType().GetProperty("Text1")?.GetValue(settingsObj, null) as string;
string text2 = settingsObj.GetType().GetProperty("Text2")?.GetValue(settingsObj, null) as string;
if (!string.IsNullOrEmpty(text1))
{
currentTextComponents[text1] = text2 ?? "";
}
}
}
catch { }
}
}
foreach (var kvp in currentTextComponents)
{
if (!hostTextComponentCache.TryGetValue(kvp.Key, out string cachedVal) || cachedVal != kvp.Value)
{
SendToAllClients($"TXT_SET;{kvp.Key};{kvp.Value}");
hostTextComponentCache[kvp.Key] = kvp.Value;
}
}
removedKeys.Clear();
foreach (var key in hostTextComponentCache.Keys)
{
if (!currentTextComponents.ContainsKey(key))
{
removedKeys.Add(key);
}
}
foreach (var key in removedKeys)
{
SendToAllClients($"TXT_REM;{key}");
hostTextComponentCache.Remove(key);
}
}
// Host Side: Game Timer
private void State_OnStart(object sender, EventArgs e)
{
if (settings.SyncMode == SyncMode.Host)
{
TimeSpan? rTime = state.CurrentTime.RealTime;
TimeSpan? gTime = state.CurrentTime.GameTime;
if (rTime == null && state.CurrentPhase == TimerPhase.Running) rTime = TimeStamp.Now - state.StartTimeWithOffset;
if (gTime == null && state.CurrentPhase == TimerPhase.Running) gTime = (TimeStamp.Now - state.StartTimeWithOffset) - state.LoadingTimes;
SendToAllClients($"START;0;{rTime?.Ticks ?? 0};{gTime?.Ticks ?? 0}");
}
}
private void State_OnSplit(object sender, EventArgs e)
{
if (settings.SyncMode == SyncMode.Host)
{
int lastSplitIndex = state.CurrentSplitIndex - 1;
long realTimeTicks = 0;
long gameTimeTicks = 0;
if (lastSplitIndex >= 0 && lastSplitIndex < state.Run.Count)
{
var time = state.Run[lastSplitIndex].SplitTime;
realTimeTicks = time.RealTime?.Ticks ?? 0;
gameTimeTicks = time.GameTime?.Ticks ?? 0;
}
SendToAllClients($"SPLIT;{state.CurrentSplitIndex};{realTimeTicks};{gameTimeTicks}");
}
}
private void State_OnUndoSplit(object sender, EventArgs e) => SendToAllClients($"UNDOSPLIT;{state.CurrentSplitIndex};0;0");
private void State_OnSkipSplit(object sender, EventArgs e) => SendToAllClients($"SKIPSPLIT;{state.CurrentSplitIndex};0;0");
private void State_OnReset(object sender, TimerPhase value) => SendToAllClients($"RESET;0;0;0");
private void State_OnPause(object sender, EventArgs e) => SendToAllClients($"PAUSE;{state.CurrentSplitIndex};{state.CurrentTime.RealTime?.Ticks ?? 0};{state.CurrentTime.GameTime?.Ticks ?? 0}");
private void State_OnResume(object sender, EventArgs e) => SendToAllClients($"RESUME;{state.CurrentSplitIndex};{state.CurrentTime.RealTime?.Ticks ?? 0};{state.CurrentTime.GameTime?.Ticks ?? 0}");
// Client Side: Sync Timer, Splits...
private void ProcessMessage(string message)
{
try
{
var parts = message.Split(';');
if (parts.Length < 2) return;
string action = parts[0];
if (action == "TXT_SET")
{
if (parts.Length >= 3) ClientSetText(parts[1], parts[2]);
return;
}
else if (action == "TXT_REM")
{
if (parts.Length >= 2) ClientRemoveText(parts[1]);
return;
}
if (parts.Length < 4) return;
int splitIndex = int.Parse(parts[1]);
long realTimeTicks = long.Parse(parts[2]);
long gameTimeTicks = long.Parse(parts[3]);
var model = new TimerModel() { CurrentState = state };
switch (action)
{
case "START":
if (state.CurrentPhase == TimerPhase.NotRunning) model.Start();
state.StartTimeWithOffset = TimeStamp.Now - TimeSpan.FromTicks(realTimeTicks);
state.LoadingTimes = TimeSpan.FromTicks(realTimeTicks) - TimeSpan.FromTicks(gameTimeTicks);
break;
case "SPLIT":
if (state.CurrentPhase == TimerPhase.Running)
{
while (state.CurrentSplitIndex < splitIndex) model.Split();
int completedIndex = splitIndex - 1;
if (completedIndex >= 0 && completedIndex < state.Run.Count)
{
state.Run[completedIndex].SplitTime = new Time(
realTimeTicks > 0 ? (TimeSpan?)TimeSpan.FromTicks(realTimeTicks) : null,
gameTimeTicks > 0 ? (TimeSpan?)TimeSpan.FromTicks(gameTimeTicks) : null
);
}
}
break;
case "UNDOSPLIT":
if (state.CurrentPhase == TimerPhase.Running || state.CurrentPhase == TimerPhase.Ended) model.UndoSplit();
break;
case "SKIPSPLIT":
if (state.CurrentPhase == TimerPhase.Running) model.SkipSplit();
break;
case "PAUSE":
if (state.CurrentPhase == TimerPhase.Running) model.Pause();
break;
case "RESUME":
if (state.CurrentPhase == TimerPhase.Paused) model.Pause();
break;
case "RESET":
if (state.CurrentPhase != TimerPhase.NotRunning) model.Reset();
break;
case "SYNC":
if (state.CurrentPhase == TimerPhase.NotRunning) model.Start();
if (state.CurrentPhase == TimerPhase.Running)
{
if (state.CurrentSplitIndex < splitIndex)
{
while (state.CurrentSplitIndex < splitIndex) model.Split();
}
else if (state.CurrentSplitIndex > splitIndex)
{
while (state.CurrentSplitIndex > splitIndex) model.UndoSplit();
}
if (state.CurrentTimingMethod != TimingMethod.GameTime)
{
state.CurrentTimingMethod = TimingMethod.GameTime;
}
state.IsGameTimePaused = true;
state.SetGameTime(TimeSpan.FromTicks(gameTimeTicks));
state.StartTimeWithOffset = TimeStamp.Now - TimeSpan.FromTicks(realTimeTicks);
}
break;
}
}
catch { }
}
// Client Side Layout Components
private void ClientSetText(string text1, string text2)
{
try
{
object textSetting = null;
foreach (var comp in state.Layout.Components)
{
if (comp.GetType().Name == "TextComponent")
{
var settingsObj = comp.GetType().GetProperty("Settings")?.GetValue(comp, null);
if (settingsObj != null)
{
string t1 = settingsObj.GetType().GetProperty("Text1")?.GetValue(settingsObj, null) as string;
if (t1 == text1)
{
textSetting = settingsObj;
break;
}
}
}
}
if (textSetting != null)
{
textSetting.GetType().GetProperty("Text2")?.SetValue(textSetting, text2, null);
}
else if (!string.IsNullOrEmpty(text2))
{
if (cachedTextComponentType == null)
{
var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Components", "LiveSplit.Text.dll");
if (File.Exists(path))
{
var asm = System.Reflection.Assembly.LoadFrom(path);
cachedTextComponentType = asm.GetType("LiveSplit.UI.Components.TextComponent");
}
}
if (cachedTextComponentType != null)
{
var textComponent = Activator.CreateInstance(cachedTextComponentType, state);
state.Layout.LayoutComponents.Add(new LayoutComponent("LiveSplit.Text.dll", textComponent as IComponent));
var settingsObj = textComponent.GetType().GetProperty("Settings")?.GetValue(textComponent, null);
if (settingsObj != null)
{
settingsObj.GetType().GetProperty("Text1")?.SetValue(settingsObj, text1, null);
settingsObj.GetType().GetProperty("Text2")?.SetValue(settingsObj, text2, null);
}
}
}
}
catch { }
}
private void ClientRemoveText(string text1)
{
try
{
IComponent componentToRemove = null;
foreach (var comp in state.Layout.Components)
{
if (comp.GetType().Name == "TextComponent")
{
var settingsObj = comp.GetType().GetProperty("Settings")?.GetValue(comp, null);
if (settingsObj != null)
{
string t1 = settingsObj.GetType().GetProperty("Text1")?.GetValue(settingsObj, null) as string;
if (t1 == text1)
{
componentToRemove = comp;
break;
}
}
}
}
if (componentToRemove != null)
{
for (int i = state.Layout.LayoutComponents.Count - 1; i >= 0; i--)
{
if (state.Layout.LayoutComponents[i].Component == componentToRemove)
{
state.Layout.LayoutComponents.RemoveAt(i);
}
}
}
}
catch { }
}
}
}