-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfrmDigitalSlate.vb
More file actions
1443 lines (1182 loc) · 47.4 KB
/
frmDigitalSlate.vb
File metadata and controls
1443 lines (1182 loc) · 47.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
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
Imports System.IO
Imports System.Diagnostics
Imports System.Media
Imports System.Reflection.Emit
Imports System.Windows.Forms
Imports System.Collections.Generic
Imports System.Linq
Imports System.Drawing.Drawing2D
Imports System.Drawing.Text
Imports System.Drawing.Imaging
Imports digitalSlate.World.Functions
Imports digitalSlate.World.mainClass
Imports digitalSlate.World.Vars.vDefaults
Partial Public Class frmDigitalSlate
Private ReadOnly _ltcOut As New LtcAudioOutputService()
Private _targetValue As Integer = 1
Private _timecodeFreezeUntilUtc As DateTime = DateTime.MinValue
Private _frozenTimecodeText As String = zeroTC
Private _timecodeOverlayUntilUtc As DateTime = DateTime.MinValue
Private _timecodeOverlayText As String = String.Empty
Private _timecodeLabelBaseFont As Font
Private _logoOverlay As PictureBox
Private _currentLogoImage As Image
Private _ltcCurrentDeviceId As Integer = Integer.MinValue
Private _ltcCurrentFpsMode As LtcFpsMode = CType(-1, LtcFpsMode)
Private _ltcLastError As String = String.Empty
Private _isPlayingCalibrationTone As Boolean = False
Private WithEvents _ltcHealthTimer As New Windows.Forms.Timer With {.Interval = 1500}
Private _resolveLogFilePathCache As String = String.Empty
Private ReadOnly _resolveSessionToken As String = Date.Now.ToString("yyyyMMdd_HHmmss")
Private _slateScaleInitialized As Boolean = False
Private _slateDesignSize As Size = Size.Empty
Private ReadOnly _slateControlBounds As New Dictionary(Of Control, Rectangle)
Private ReadOnly _slateControlFonts As New Dictionary(Of Control, Font)
Private Const LogoMaxWidthPx As Integer = 430
Private Const LogoMaxHeightPx As Integer = 115
Private Const ShowLogoDiagnostics As Boolean = False
Private Shared ReadOnly DefaultLogoBounds As New Rectangle(16, 126, 88, 96)
Private Shared Function GetCustomLogoPersistPath() As String
Dim baseFolder As String = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "digitalSlate")
Return Path.Combine(baseFolder, "custom-logo.png")
End Function
Private Sub EnsureLogoOverlayControl()
If _logoOverlay IsNot Nothing Then Return
Dim logoBounds As Rectangle = If(pbLogoSlot IsNot Nothing, pbLogoSlot.Bounds, DefaultLogoBounds)
Dim overlayParent As Control = plPrimary
Dim overlayLocation As Point = logoBounds.Location
If pbSlateBody IsNot Nothing AndAlso pbSlateBody.Bounds.Contains(logoBounds) Then
overlayParent = pbSlateBody
overlayLocation = New Point(logoBounds.X - pbSlateBody.Left, logoBounds.Y - pbSlateBody.Top)
ElseIf pbClapper IsNot Nothing AndAlso pbClapper.Bounds.Contains(logoBounds) Then
overlayParent = pbClapper
overlayLocation = New Point(logoBounds.X - pbClapper.Left, logoBounds.Y - pbClapper.Top)
End If
_logoOverlay = New PictureBox With {
.Name = "pbCustomLogoOverlay",
.Location = overlayLocation,
.Size = New Size(logoBounds.Width, logoBounds.Height),
.SizeMode = PictureBoxSizeMode.Zoom,
.BackColor = Color.Transparent,
.Visible = False,
.TabStop = False
}
overlayParent.Controls.Add(_logoOverlay)
_logoOverlay.BringToFront()
End Sub
Private Function GetDesiredLtcFpsMode() As LtcFpsMode
Return CType(Math.Max(0, Math.Min(3, World.vMain.ltcFpsMode)), LtcFpsMode)
End Function
Private Function GetLtcDeviceName(deviceId As Integer) As String
If deviceId < 0 Then Return "Default"
Try
For Each d In LtcAudioOutputService.GetOutputDevices()
If d.Item1 = deviceId Then Return d.Item2
Next
Catch
End Try
Return $"Device {deviceId}"
End Function
Private Sub EnsureSessionMetadataDefaults()
ApplySessionMetadataPolicy()
End Sub
Private Sub SyncLtcOutputState()
If _isPlayingCalibrationTone Then Return
If World.vMain.ltcEnabled <> 1 Then
_ltcOut.Stop()
_ltcCurrentDeviceId = Integer.MinValue
_ltcCurrentFpsMode = CType(-1, LtcFpsMode)
_ltcLastError = String.Empty
UpdateLtcIndicator()
Return
End If
Try
Dim desiredDeviceId As Integer = World.vMain.ltcOutputDeviceId
Dim desiredFpsMode As LtcFpsMode = GetDesiredLtcFpsMode()
If (Not _ltcOut.IsRunning) OrElse _ltcCurrentDeviceId <> desiredDeviceId OrElse _ltcCurrentFpsMode <> desiredFpsMode Then
_ltcOut.Stop()
_ltcOut.Start(desiredDeviceId, desiredFpsMode)
_ltcCurrentDeviceId = desiredDeviceId
_ltcCurrentFpsMode = desiredFpsMode
End If
_ltcOut.SetMuted(World.vMain.ltcUnmute <> 1)
_ltcLastError = String.Empty
Catch ex As Exception
_ltcOut.Stop()
_ltcCurrentDeviceId = Integer.MinValue
_ltcCurrentFpsMode = CType(-1, LtcFpsMode)
_ltcLastError = ex.Message
End Try
UpdateLtcIndicator()
End Sub
Private Sub SetLogoImage(image As Image)
If _currentLogoImage IsNot Nothing Then
_currentLogoImage.Dispose()
_currentLogoImage = Nothing
End If
If image Is Nothing Then
If _logoOverlay IsNot Nothing Then
_logoOverlay.Image = Nothing
_logoOverlay.Visible = False
End If
Return
End If
_currentLogoImage = CType(image.Clone(), Image)
_logoOverlay.Image = _currentLogoImage
_logoOverlay.Visible = True
End Sub
Private Function LoadImageUnlocked(filePath As String) As Image
Using fs As New FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read)
Using img As Image = Image.FromStream(fs)
Return CType(img.Clone(), Image)
End Using
End Using
End Function
Private Async Function runVisualCountDown(count As Integer) As Task
If Timer1.Enabled Then Return
If count <= 0 Then Return
Dim cadenceClock As Stopwatch = Stopwatch.StartNew()
Const CountdownCadenceMs As Integer = 1000
For i As Integer = 1 To count
Await WaitUntilElapsedMsAsync(cadenceClock, (i - 1) * CountdownCadenceMs)
Await HandleBeepVisualsAsync(i, count, True)
Next
Await WaitUntilElapsedMsAsync(cadenceClock, count * CountdownCadenceMs)
End Function
Private Sub TryLoadPersistedLogo()
Try
EnsureLogoOverlayControl()
Dim logoPath As String = GetCustomLogoPersistPath()
If File.Exists(logoPath) Then
Using loaded As Image = LoadImageUnlocked(logoPath)
SetLogoImage(loaded)
If ShowLogoDiagnostics Then
MessageBox.Show($"Logo loaded from saved file: {loaded.Width}x{loaded.Height}", "Logo Diagnostic", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Using
Return
End If
If pbLogoSlot IsNot Nothing AndAlso pbLogoSlot.Image IsNot Nothing Then
Using fallback As Image = CType(pbLogoSlot.Image.Clone(), Image)
SetLogoImage(fallback)
If ShowLogoDiagnostics Then
MessageBox.Show($"Logo loaded from designer fallback: {fallback.Width}x{fallback.Height}", "Logo Diagnostic", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Using
Else
SetLogoImage(Nothing)
If ShowLogoDiagnostics Then
MessageBox.Show("No persisted logo and no designer fallback image found.", "Logo Diagnostic", MessageBoxButtons.OK, MessageBoxIcon.Warning)
End If
End If
Catch ex As Exception
SetLogoImage(Nothing)
If ShowLogoDiagnostics Then
MessageBox.Show("Logo load failed: " & ex.Message, "Logo Diagnostic", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
End Try
End Sub
Private Function ValidateLogoDimensions(candidate As Image) As Boolean
Return candidate.Width <= LogoMaxWidthPx AndAlso candidate.Height <= LogoMaxHeightPx
End Function
Private Sub SaveSelectedLogo(selectedPath As String)
Dim persistPath As String = GetCustomLogoPersistPath()
Dim persistDirectory As String = Path.GetDirectoryName(persistPath)
If Not Directory.Exists(persistDirectory) Then
Directory.CreateDirectory(persistDirectory)
End If
Using img As Image = LoadImageUnlocked(selectedPath)
If Not ValidateLogoDimensions(img) Then
MessageBox.Show($"Logo is too large ({img.Width}x{img.Height}). Max allowed is {LogoMaxWidthPx}x{LogoMaxHeightPx}.", "Invalid logo size", MessageBoxButtons.OK, MessageBoxIcon.Warning)
Return
End If
If File.Exists(persistPath) Then
File.Delete(persistPath)
End If
img.Save(persistPath, ImageFormat.Png)
SetLogoImage(img)
If ShowLogoDiagnostics Then
MessageBox.Show($"Logo saved and applied: {img.Width}x{img.Height}", "Logo Diagnostic", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Using
End Sub
Private Sub UpdateLtcIndicator()
If lblLtcStatus Is Nothing Then Return
If World.vMain.ltcEnabled <> 1 Then
lblLtcStatus.Text = "LTC: OFF"
lblLtcStatus.ForeColor = Color.Gray
Return
End If
Dim fpsLabel As String = GetDesiredLtcFpsMode().ToString()
Dim deviceLabel As String = GetLtcDeviceName(World.vMain.ltcOutputDeviceId)
Dim muteLabel As String = If(World.vMain.ltcUnmute = 1, "AUD", "MUT")
Dim baseText As String = $"LTC {fpsLabel} | {deviceLabel} | {muteLabel}"
If Timer1 IsNot Nothing AndAlso Timer1.Enabled Then
If World.vMain.ltcUnmute = 1 Then
lblLtcStatus.Text = "LTC: LIVE | " & baseText
lblLtcStatus.ForeColor = Color.Lime
Else
lblLtcStatus.Text = "LTC: MUTED | " & baseText
lblLtcStatus.ForeColor = Color.Gold
End If
ElseIf _ltcOut IsNot Nothing AndAlso _ltcOut.IsRunning Then
lblLtcStatus.Text = "LTC: READY | " & baseText
lblLtcStatus.ForeColor = Color.Green
Else
lblLtcStatus.Text = "LTC: RECOVERING | " & baseText
lblLtcStatus.ForeColor = Color.Orange
End If
If Not String.IsNullOrWhiteSpace(_ltcLastError) Then
lblLtcStatus.Text &= " | ERR"
lblLtcStatus.ForeColor = Color.OrangeRed
End If
End Sub
Private Sub frmDigitalSlate_Load(sender As Object, e As EventArgs) Handles MyBase.Load
loadFromSettings()
EnsureSessionMetadataDefaults()
framesPerSecond = If(World.vMain.fps > 0, World.vMain.fps, World.vDefaults.fps)
loadToForm(Me)
If pbLogoSlot IsNot Nothing Then pbLogoSlot.Visible = False
TryLoadPersistedLogo()
InitializeSlateScaling()
_timecodeLabelBaseFont = New Font(lblTimecode.Font.FontFamily, lblTimecode.Font.Size, lblTimecode.Font.Style)
SyncLtcOutputState()
_ltcHealthTimer.Start()
' Ensure save/load menu items reflect current timer state
Try
tsiSaveProfile.Enabled = Not Timer1.Enabled
tsiLoadProfile.Enabled = Not Timer1.Enabled
Catch ex As Exception
' Ignore if menu items are not present in designer yet
End Try
nudTakes.Value = _targetValue
RefreshTargetLabel()
cbLock.Text = "LOCK SLATE"
ApplySlateLockState()
TryHandlePendingExternalSlateFile()
End Sub
Private Async Sub TryHandlePendingExternalSlateFile()
Dim pendingPath As String = World.Functions.PendingExternalSlateFilePath
If String.IsNullOrWhiteSpace(pendingPath) Then Return
World.Functions.PendingExternalSlateFilePath = String.Empty
Await World.Functions.LoadSlateFromFilePath(pendingPath, False)
End Sub
Private Sub RefreshTargetLabel()
lblTake.Text = _targetValue.ToString()
End Sub
Private framesPerSecond As Double = World.vDefaults.fps 'default is 24 fps
Private Sub frmDigitalSlate_Shown(sender As Object, e As EventArgs) Handles Me.Shown
loadFromSettings()
EnsureSessionMetadataDefaults()
framesPerSecond = If(World.vMain.fps > 0, World.vMain.fps, World.vDefaults.fps)
loadToForm(Me)
If pbLogoSlot IsNot Nothing Then pbLogoSlot.Visible = False
TryLoadPersistedLogo()
ApplySlateScaleLayout()
SyncLtcOutputState()
If Not _ltcHealthTimer.Enabled Then _ltcHealthTimer.Start()
Try
tsiSaveProfile.Enabled = Not Timer1.Enabled
tsiLoadProfile.Enabled = Not Timer1.Enabled
Catch ex As Exception
' Ignore if menu items are not present in designer yet
End Try
ApplySlateLockState()
End Sub
Private Function IsSlateLocked() As Boolean
Return cbLock IsNot Nothing AndAlso cbLock.Checked
End Function
Private Sub ApplySlateLockState()
Dim locked As Boolean = IsSlateLocked()
Dim timerRunning As Boolean = (Timer1 IsNot Nothing AndAlso Timer1.Enabled)
If cbLock IsNot Nothing Then
cbLock.Text = If(locked, "🔒SLATE LOCKED", "LOCK SLATE")
EnsureLockCheckboxFitsText()
End If
If butSwIntExt IsNot Nothing Then butSwIntExt.Enabled = Not locked
If butSwDayNit IsNot Nothing Then butSwDayNit.Enabled = Not locked
If butSwAudio IsNot Nothing Then butSwAudio.Enabled = Not locked
If butEdit IsNot Nothing Then butEdit.Enabled = Not locked
If cbTakeInc IsNot Nothing Then cbTakeInc.Enabled = Not locked
If nudTakes IsNot Nothing Then nudTakes.Enabled = Not locked
If tsiEdit IsNot Nothing Then tsiEdit.Enabled = Not locked
If tsiOptions IsNot Nothing Then tsiOptions.Enabled = Not locked
If tsiChangeLogo IsNot Nothing Then tsiChangeLogo.Enabled = Not locked
If tsiReset IsNot Nothing Then tsiReset.Enabled = Not locked
If tsiZeroTC IsNot Nothing Then tsiZeroTC.Enabled = (Not locked) AndAlso (Not timerRunning)
If tsiSaveProfile IsNot Nothing Then tsiSaveProfile.Enabled = (Not locked) AndAlso (Not timerRunning)
If tsiLoadProfile IsNot Nothing Then tsiLoadProfile.Enabled = (Not locked) AndAlso (Not timerRunning)
End Sub
Private Sub EnsureLockCheckboxFitsText()
If cbLock Is Nothing Then Return
Dim currentRight As Integer = cbLock.Right
Dim measured As Size = TextRenderer.MeasureText(cbLock.Text, cbLock.Font)
Dim desiredWidth As Integer = Math.Max(185, measured.Width + 34)
cbLock.Width = desiredWidth
cbLock.Left = currentRight - cbLock.Width
End Sub
Private Function BlockWhenSlateLocked() As Boolean
If Not IsSlateLocked() Then Return False
SystemSounds.Asterisk.Play()
Return True
End Function
Protected Overrides Function ProcessCmdKey(ByRef msg As Message, keyData As Keys) As Boolean
If IsSlateLocked() Then
Select Case keyData
Case (Keys.Alt Or Keys.Shift Or Keys.E),
(Keys.Alt Or Keys.Shift Or Keys.O),
(Keys.Alt Or Keys.Shift Or Keys.S)
SystemSounds.Asterisk.Play()
Return True
End Select
End If
Return MyBase.ProcessCmdKey(msg, keyData)
End Function
Public Sub CenterPanel()
If plPrimary IsNot Nothing Then
plPrimary.Left = (Me.ClientSize.Width - plPrimary.Width) \ 2
plPrimary.Top = (Me.ClientSize.Height - plPrimary.Height) \ 2
End If
End Sub
Private Sub InitializeSlateScaling()
If _slateScaleInitialized Then Return
If plPrimary Is Nothing Then Return
ClearControlSizeConstraintsRecursive(plPrimary)
_slateDesignSize = plPrimary.Size
_slateControlBounds.Clear()
_slateControlFonts.Clear()
CaptureSlateControlMetrics(plPrimary)
_slateScaleInitialized = True
ApplySlateScaleLayout()
End Sub
Private Sub ClearControlSizeConstraintsRecursive(parent As Control)
parent.MinimumSize = Size.Empty
parent.MaximumSize = Size.Empty
For Each child As Control In parent.Controls
ClearControlSizeConstraintsRecursive(child)
Next
End Sub
Private Sub CaptureSlateControlMetrics(parent As Control)
For Each child As Control In parent.Controls
_slateControlBounds(child) = child.Bounds
If child.Font IsNot Nothing Then
_slateControlFonts(child) = CType(child.Font.Clone(), Font)
End If
If child.HasChildren Then
CaptureSlateControlMetrics(child)
End If
Next
End Sub
Private Sub ApplySlateScaleLayout()
If Not _slateScaleInitialized Then Return
If _slateDesignSize.Width <= 0 OrElse _slateDesignSize.Height <= 0 Then Return
If Me.ClientSize.Width <= 0 OrElse Me.ClientSize.Height <= 0 Then Return
Dim fitScaleX As Double = Me.ClientSize.Width / CDbl(_slateDesignSize.Width)
Dim fitScaleY As Double = Me.ClientSize.Height / CDbl(_slateDesignSize.Height)
Dim fitScale As Double = Math.Min(fitScaleX, fitScaleY)
Dim userScale As Double = If(World.vMain.slateScaleMultiplier > 0, World.vMain.slateScaleMultiplier, 1.0)
Dim finalScale As Single = CSng(Math.Max(0.1, Math.Min(fitScale, fitScale * userScale)))
Dim scaledWidth As Integer = Math.Max(1, CInt(Math.Round(_slateDesignSize.Width * finalScale)))
Dim scaledHeight As Integer = Math.Max(1, CInt(Math.Round(_slateDesignSize.Height * finalScale)))
plPrimary.SuspendLayout()
plPrimary.Size = New Size(scaledWidth, scaledHeight)
For Each kvp In _slateControlBounds
Dim ctl As Control = kvp.Key
Dim baseBounds As Rectangle = kvp.Value
ctl.Bounds = New Rectangle(
CInt(Math.Round(baseBounds.X * finalScale)),
CInt(Math.Round(baseBounds.Y * finalScale)),
Math.Max(1, CInt(Math.Round(baseBounds.Width * finalScale))),
Math.Max(1, CInt(Math.Round(baseBounds.Height * finalScale))))
Dim baseFont As Font = Nothing
If _slateControlFonts.TryGetValue(ctl, baseFont) AndAlso baseFont IsNot Nothing Then
Dim scaledFontSize As Single = Math.Max(1.0F, CSng(baseFont.Size * finalScale))
ctl.Font = New Font(baseFont.FontFamily, scaledFontSize, baseFont.Style, baseFont.Unit)
End If
Next
plPrimary.ResumeLayout()
CenterPanel()
EnsureLockCheckboxFitsText()
If lblTimecode IsNot Nothing AndAlso DateTime.UtcNow >= _timecodeOverlayUntilUtc Then
_timecodeLabelBaseFont = New Font(lblTimecode.Font.FontFamily, lblTimecode.Font.Size, lblTimecode.Font.Style)
End If
End Sub
Private Sub frmDigitalSlate_Resize(sender As Object, e As EventArgs) Handles MyBase.Resize
ApplySlateScaleLayout()
End Sub
Public Sub ApplyCurrentSlateScale()
ApplySlateScaleLayout()
End Sub
Public Function GetLtcDiagnosticsSummary() As String
Dim enabled As Boolean = (World.vMain.ltcEnabled = 1)
Dim running As Boolean = (_ltcOut IsNot Nothing AndAlso _ltcOut.IsRunning)
Dim deviceLabel As String = GetLtcDeviceName(World.vMain.ltcOutputDeviceId)
Dim fpsLabel As String = GetDesiredLtcFpsMode().ToString()
Dim muteLabel As String = If(World.vMain.ltcUnmute = 1, "Unmuted", "Muted")
Dim stateLabel As String
If Not enabled Then
stateLabel = "OFF"
ElseIf running Then
stateLabel = "RUNNING"
Else
stateLabel = "RECOVERING"
End If
Dim summary As String = $"State: {stateLabel} | FPS: {fpsLabel} | Device: {deviceLabel} | Audio: {muteLabel}"
If Not String.IsNullOrWhiteSpace(_ltcLastError) Then
summary &= $" | Last error: {_ltcLastError}"
End If
Return summary
End Function
Private Shared Function GetAudioPath(relativeFile As String) As String
Return Path.Combine(Application.StartupPath, "audio", relativeFile)
End Function
Private Function GetFrameDurationMs(frameCount As Integer) As Integer
Dim safeFps As Double = If(framesPerSecond > 0, framesPerSecond, World.vDefaults.fps)
Return Math.Max(1, CInt(Math.Round((frameCount * 1000.0) / safeFps)))
End Function
Private Sub BeginTimecodeFreeze(frames As Integer)
_frozenTimecodeText = TimecodeGenerator.GenerateTimecode(Date.Now, framesPerSecond).ToString()
_timecodeFreezeUntilUtc = DateTime.UtcNow.AddMilliseconds(GetFrameDurationMs(frames))
End Sub
Private Function GetSlateDateForOverlay() As String
Dim applyCaps As Func(Of String, String) = Function(value As String)
If World.vMain.displayCaps = 1 Then
Return If(value, String.Empty).ToUpperInvariant()
End If
Return If(value, String.Empty)
End Function
If Not String.IsNullOrWhiteSpace(World.vMain.custDate) Then
Return applyCaps(World.vMain.custDate)
End If
If Not String.IsNullOrWhiteSpace(World.vMain.currentDate) Then
Return applyCaps(World.vMain.currentDate)
End If
Return applyCaps(Date.Now.ToString("dd MMM yyyy"))
End Function
Private Function GetMetadataItems() As List(Of String)
Dim items As New List(Of String)
If World.vMain.metadataFlashFpsEnabled = 1 Then
items.Add($"FPS {framesPerSecond:0.###}")
End If
If World.vMain.metadataFlashDateEnabled = 1 Then
items.Add(GetSlateDateForOverlay())
End If
Return items
End Function
Private Sub SaveClapTimecodeToSessionLog()
Dim clapTc As String = TimecodeGenerator.GenerateTimecode(Date.Now, framesPerSecond).ToString()
World.vMain.clapTimecodeLog.Add(clapTc)
WriteResolveInMarkerLog(clapTc)
End Sub
Private Shared Function SanitizeFilePart(value As String) As String
If String.IsNullOrWhiteSpace(value) Then Return "UNTITLED"
Dim cleaned As String = value.Trim()
For Each ch In Path.GetInvalidFileNameChars()
cleaned = cleaned.Replace(ch, "_"c)
Next
Return cleaned
End Function
Private Shared Function EscapeCsv(value As String) As String
If value Is Nothing Then Return """"""
Return """" & value.Replace("""", """""") & """"
End Function
Private Function NormalizeTimecode(tc As String) As String
If String.IsNullOrWhiteSpace(tc) Then Return "00:00:00:00"
Return tc.Replace(" ", String.Empty)
End Function
Private Function GetResolveLogFilePath() As String
If Not String.IsNullOrWhiteSpace(_resolveLogFilePathCache) Then Return _resolveLogFilePathCache
If String.IsNullOrWhiteSpace(World.vMain.logOutputFolder) Then Return String.Empty
Dim productionPart As String = SanitizeFilePart(World.vMain.production)
Dim scenePart As String = SanitizeFilePart(World.vMain.scene)
Dim rollPart As String = SanitizeFilePart(World.vMain.roll)
Dim sessionPart As String = If(IsSessionMetadataEnabled(), SanitizeFilePart(World.vMain.sessionId), "NOSESSION")
Dim baseName As String
If World.vMain.markerAppendDaily = 1 Then
Dim dayPart As String = Date.Now.ToString("yyyyMMdd")
baseName = $"{productionPart}_{dayPart}_SlateMarkers"
Else
baseName = $"{productionPart}_{scenePart}_{rollPart}_{sessionPart}_SlateMarkers_{_resolveSessionToken}"
End If
Dim candidatePath As String = Path.Combine(World.vMain.logOutputFolder, baseName & ".csv")
Dim suffix As Integer = 1
Do While World.vMain.markerAppendDaily <> 1 AndAlso File.Exists(candidatePath)
candidatePath = Path.Combine(World.vMain.logOutputFolder, $"{baseName}_{suffix:00}.csv")
suffix += 1
Loop
_resolveLogFilePathCache = candidatePath
Return _resolveLogFilePathCache
End Function
Private Sub ResetResolveLogFilePathCache()
_resolveLogFilePathCache = String.Empty
End Sub
Private Function EnsureLogFolderWritable() As Boolean
Try
If String.IsNullOrWhiteSpace(World.vMain.logOutputFolder) Then Return False
If Not Directory.Exists(World.vMain.logOutputFolder) Then
Directory.CreateDirectory(World.vMain.logOutputFolder)
End If
Dim probePath As String = Path.Combine(World.vMain.logOutputFolder, ".write-test.tmp")
File.WriteAllText(probePath, Date.Now.ToString("O"))
File.Delete(probePath)
Return True
Catch
Return False
End Try
End Function
Private Sub ExportResolveMarkerLogFromSession()
If World.vMain.logOutToFile <> 1 Then
MessageBox.Show("Marker log export is disabled in Settings.", "Export markers", MessageBoxButtons.OK, MessageBoxIcon.Information)
Return
End If
If Not EnsureLogFolderWritable() Then
MessageBox.Show("Marker log folder is not writable. Check Settings.", "Export markers", MessageBoxButtons.OK, MessageBoxIcon.Warning)
Return
End If
Try
Dim filePath As String = GetResolveLogFilePath()
If String.IsNullOrWhiteSpace(filePath) Then
MessageBox.Show("No marker log output path is configured.", "Export markers", MessageBoxButtons.OK, MessageBoxIcon.Warning)
Return
End If
Dim lines As New List(Of String) From {
"Marker Name,Description,In,Out,Duration,Marker Color,Marker Type"
}
For i As Integer = 0 To World.vMain.clapTimecodeLog.Count - 1
Dim inTc As String = NormalizeTimecode(World.vMain.clapTimecodeLog(i))
Dim markerName As String = $"{World.vMain.scene}_T{i + 1}"
Dim description As String = $"Roll {World.vMain.roll}; FPS {framesPerSecond:0.###}"
Dim row As String = String.Join(",", New String() {
EscapeCsv(markerName),
EscapeCsv(description),
EscapeCsv(inTc),
EscapeCsv(inTc),
EscapeCsv("00:00:00:01"),
EscapeCsv("Blue"),
EscapeCsv("Comment")
})
lines.Add(row)
Next
File.WriteAllLines(filePath, lines)
MessageBox.Show($"Exported {World.vMain.clapTimecodeLog.Count} marker(s) to:`n{filePath}", "Export markers", MessageBoxButtons.OK, MessageBoxIcon.Information)
Catch ex As Exception
MessageBox.Show("Error exporting Resolve marker log: " & ex.Message, "Export markers", MessageBoxButtons.OK, MessageBoxIcon.Warning)
End Try
End Sub
Private Sub WriteResolveInMarkerLog(inTcRaw As String)
If World.vMain.logOutToFile <> 1 Then Return
If Not EnsureLogFolderWritable() Then Return
Try
Dim filePath As String = GetResolveLogFilePath()
If String.IsNullOrWhiteSpace(filePath) Then Return
Dim folder As String = Path.GetDirectoryName(filePath)
If String.IsNullOrWhiteSpace(folder) Then Return
If Not Directory.Exists(folder) Then
Directory.CreateDirectory(folder)
End If
Dim inTc As String = NormalizeTimecode(inTcRaw)
Dim markerName As String = $"{World.vMain.scene}_T{World.vMain.take}"
Dim description As String = $"Roll {World.vMain.roll}; FPS {framesPerSecond:0.###}"
If IsSessionMetadataEnabled() Then
description &= $"; Unit {World.vMain.unitName}; Op {World.vMain.operatorName}; Session {World.vMain.sessionId}"
End If
If Not File.Exists(filePath) Then
Dim header As String = "Marker Name,Description,In,Out,Duration,Marker Color,Marker Type"
File.WriteAllLines(filePath, New String() {header})
End If
Dim row As String = String.Join(",", New String() {
EscapeCsv(markerName),
EscapeCsv(description),
EscapeCsv(inTc),
EscapeCsv(inTc),
EscapeCsv("00:00:00:01"),
EscapeCsv("Blue"),
EscapeCsv("Comment")
})
File.AppendAllLines(filePath, New String() {row})
Catch ex As Exception
MessageBox.Show("Error writing Resolve log: " & ex.Message, "Log output error", MessageBoxButtons.OK, MessageBoxIcon.Warning)
End Try
End Sub
Private Async Sub StartClapPulse()
Try
Await TriggerVisualPulseAsync(1, True)
Catch
End Try
End Sub
Private Sub StartTakeAtSyncPoint()
If Timer1.Enabled Then Return
SyncLtcOutputState()
SaveClapTimecodeToSessionLog()
BeginTimecodeFreeze(5)
StartClapPulse()
Timer1.Start()
tsiZeroTC.Enabled = False
UpdateLtcIndicator()
Try
tsiSaveProfile.Enabled = False
tsiLoadProfile.Enabled = False
Catch ex As Exception
End Try
ApplySlateLockState()
End Sub
Private Async Function ShowTimecodeOverlayAsync(text As String, durationMs As Integer, Optional useLargeFont As Boolean = False) As Task
_timecodeOverlayText = text
_timecodeOverlayUntilUtc = DateTime.UtcNow.AddMilliseconds(Math.Max(1, durationMs))
If useLargeFont Then
lblTimecode.Font = New Font(lblTimecode.Font.FontFamily, 88.0F, FontStyle.Bold)
ElseIf _timecodeLabelBaseFont IsNot Nothing Then
lblTimecode.Font = _timecodeLabelBaseFont
End If
lblTimecode.Text = text
Await Task.Delay(Math.Max(1, durationMs))
If DateTime.UtcNow >= _timecodeOverlayUntilUtc AndAlso _timecodeLabelBaseFont IsNot Nothing Then
lblTimecode.Font = _timecodeLabelBaseFont
End If
End Function
Private Async Function ShowCountdownNumberOverlayAsync(number As Integer, durationMs As Integer) As Task
Using overlay As New Form()
overlay.FormBorderStyle = FormBorderStyle.None
overlay.StartPosition = FormStartPosition.Manual
overlay.Bounds = Screen.FromControl(Me).Bounds
overlay.ShowInTaskbar = False
overlay.TopMost = True
overlay.BackColor = Color.Magenta
overlay.TransparencyKey = Color.Magenta
AddHandler overlay.Paint,
Sub(sender As Object, e As PaintEventArgs)
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias
e.Graphics.TextRenderingHint = TextRenderingHint.AntiAliasGridFit
Dim sf As New StringFormat With {
.Alignment = StringAlignment.Center,
.LineAlignment = StringAlignment.Center
}
Dim textValue As String = number.ToString()
Dim textRect As New Rectangle(0, 0, overlay.ClientSize.Width, overlay.ClientSize.Height)
Dim emSize As Single = CSng(Math.Min(overlay.ClientSize.Width, overlay.ClientSize.Height) * 0.55)
Using path As New GraphicsPath()
Using arialFamily As New FontFamily("Arial")
path.AddString(textValue,
arialFamily,
CInt(FontStyle.Bold),
emSize,
textRect,
sf)
End Using
Using strokePen As New Pen(Color.Black, 5.0F)
strokePen.LineJoin = LineJoin.Round
e.Graphics.DrawPath(strokePen, path)
End Using
Using fillBrush As New SolidBrush(Color.Yellow)
e.Graphics.FillPath(fillBrush, path)
End Using
End Using
End Sub
overlay.Show()
overlay.Refresh()
Await Task.Delay(Math.Max(1, durationMs))
overlay.Close()
End Using
End Function
Private Async Function playVisualSyncBeep(count As Integer, Optional onFinalBeepStart As Action = Nothing) As Task
If Timer1.Enabled Then Return
If count <= 0 Then
If onFinalBeepStart IsNot Nothing Then onFinalBeepStart()
Return
End If
For i As Integer = 1 To count
Await HandleBeepVisualsAsync(i, count, False)
If i = count AndAlso onFinalBeepStart IsNot Nothing Then
onFinalBeepStart()
End If
Await Task.Delay(250)
Next
End Function
Private Function GetMetadataFlashDurationMs() As Integer
Return GetFrameDurationMs(3)
End Function
Private Async Function ShowMetadataFlashSequenceAsync() As Task
Dim items As List(Of String) = GetMetadataItems()
If items.Count = 0 Then Return
For Each item In items
Await ShowTimecodeOverlayAsync(item, GetMetadataFlashDurationMs())
Next
End Function
Private Async Sub StartMetadataFlashSequence()
Try
Await ShowMetadataFlashSequenceAsync()
Catch
End Try
End Sub
Private Async Sub StartCountdownMetadataFlash(index As Integer, total As Integer)
Try
Dim items As List(Of String) = GetMetadataItems()
If items.Count = 0 Then Return
If total < items.Count Then Return
If index < 1 OrElse index > items.Count Then Return
Await ShowTimecodeOverlayAsync(items(index - 1), GetMetadataFlashDurationMs())
Catch
End Try
End Sub
Private Async Function TriggerVisualPulseAsync(frameCount As Integer, Optional forceWhite As Boolean = False) As Task
Dim pulseColor As Color = Color.White
Using pulseForm As New Form()
pulseForm.FormBorderStyle = FormBorderStyle.None
pulseForm.StartPosition = FormStartPosition.Manual
pulseForm.Bounds = Screen.FromControl(Me).Bounds
pulseForm.ShowInTaskbar = False
pulseForm.TopMost = True
pulseForm.BackColor = pulseColor
pulseForm.Opacity = 1.0
pulseForm.Show()
Await Task.Delay(GetFrameDurationMs(frameCount))
pulseForm.Close()
End Using
End Function
Private Async Function HandleBeepVisualsAsync(index As Integer, total As Integer, isCountdown As Boolean) As Task
Dim pulseTask As Task = TriggerVisualPulseAsync(1)
If isCountdown AndAlso World.vMain.showCountdownNumbers <> 1 Then
StartCountdownMetadataFlash(index, total)
End If
If isCountdown AndAlso total >= 2 AndAlso World.vMain.showCountdownNumbers = 1 Then
Dim countNumber As Integer = Math.Max(0, total - index + 1)
Await ShowCountdownNumberOverlayAsync(countNumber, 350)
End If
Await pulseTask
End Function
Private Async Function WaitUntilElapsedMsAsync(clock As Stopwatch, targetMs As Integer) As Task
Dim remainingMs As Integer = targetMs - CInt(clock.ElapsedMilliseconds)
If remainingMs > 1 Then
Await Task.Delay(remainingMs)
End If
Do While clock.ElapsedMilliseconds < targetMs
Await Task.Yield()
Loop
End Function
Private Async Function runCountDown(count As Integer) As Task
If Timer1.Enabled Then Return
If count <= 0 Then Return
Dim filePath = GetAudioPath("countdown.wav")
If Not File.Exists(filePath) Then
MessageBox.Show("Missing audio file: " & filePath)
Return
End If
Using cdPlayer As New SoundPlayer(filePath)
Try
Await Task.Run(Sub() cdPlayer.Load())
Dim cadenceClock As Stopwatch = Stopwatch.StartNew()
Const CountdownCadenceMs As Integer = 1000
For i As Integer = 1 To count
Await WaitUntilElapsedMsAsync(cadenceClock, (i - 1) * CountdownCadenceMs)
Dim visualsTask As Task = HandleBeepVisualsAsync(i, count, True)
Await Task.Run(Sub() cdPlayer.PlaySync())
Await visualsTask
Next
Await WaitUntilElapsedMsAsync(cadenceClock, count * CountdownCadenceMs)
Catch ex As Exception
MessageBox.Show("Error playing countdown: " & ex.Message)
End Try
End Using
End Function
Private Async Function TryCreateLoadedPlayer(relativeFile As String, missingFileMessagePrefix As String, loadErrorMessagePrefix As String) As Task(Of SoundPlayer)
Dim filePath = GetAudioPath(relativeFile)
If Not File.Exists(filePath) Then
MessageBox.Show(missingFileMessagePrefix & filePath)
Return Nothing
End If
Dim player As New SoundPlayer(filePath)
Try
Await Task.Run(Sub() player.Load())
Return player
Catch ex As Exception
player.Dispose()
MessageBox.Show(loadErrorMessagePrefix & ex.Message)
Return Nothing
End Try
End Function
Private Async Function playSyncBeep(count As Integer, Optional onFinalBeepStart As Action = Nothing, Optional preloadedPlayer As SoundPlayer = Nothing) As Task
If Timer1.Enabled Then Return
If preloadedPlayer IsNot Nothing Then
Try
For i As Integer = 1 To count
Dim visualsTask As Task = HandleBeepVisualsAsync(i, count, False)
If i = count AndAlso onFinalBeepStart IsNot Nothing Then
onFinalBeepStart()
End If
Await Task.Run(Sub() preloadedPlayer.PlaySync())
Await visualsTask
Next
Catch ex As Exception
MessageBox.Show("Error playing sync beep: " & ex.Message)
End Try
Return
End If
Using beepPlayer As SoundPlayer = Await TryCreateLoadedPlayer("syncBeep.wav", "Missing audio file: ", "Error loading sync beep: ")
If beepPlayer Is Nothing Then Return
Try
For i As Integer = 1 To count
Dim visualsTask As Task = HandleBeepVisualsAsync(i, count, False)
If i = count AndAlso onFinalBeepStart IsNot Nothing Then
onFinalBeepStart()
End If
Await Task.Run(Sub() beepPlayer.PlaySync())
Await visualsTask
Next
Catch ex As Exception
MessageBox.Show("Error playing sync beep: " & ex.Message)
End Try
End Using