-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsession_pulse.lua
More file actions
executable file
·3938 lines (3470 loc) · 152 KB
/
session_pulse.lua
File metadata and controls
executable file
·3938 lines (3470 loc) · 152 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
--[[
SessionPulse v6.0.0
Session automation engine for OBS Studio.
Wallclock-based timing, WebSocket dock control, scene/source/filter/volume
automation, warning alerts, time adjustment, session labeling, daily goal
tracking, session logging, chapter markers, "ends at" time display, and
state persistence with atomic writes.
https://github.com/bhaskarjha-com/sbobs
License: MIT
]]
local obs = obslua
if not obs then
print("[SessionPulse] Error: This script must be run within OBS Studio.")
return
end
local VERSION = "6.0.0"
------------------------------------------------------------------------
-- 1. State Variables
--
-- Defines all runtime state (timers, flags, counters).
-- Functions: None (variable declarations only)
--
-- State Machine (valid combinations only):
-- IDLE: is_running=false, is_paused=false, is_overtime=false
-- RUNNING: is_running=true, is_paused=false, is_overtime=false
-- PAUSED: is_running=true, is_paused=true, is_overtime=false
-- OVERTIME: is_running=true, is_paused=false, is_overtime=true
-- TRANSITIONING: is_running=true, show_transition=true
--
-- All other boolean combinations are invalid.
------------------------------------------------------------------------
local current_time = 0
local cycle_count = 0
local completed_focus_sessions = 0
local total_focus_seconds = 0
local is_running = false
local is_paused = false
local session_type = "Focus"
local show_transition = false
local transition_timer = 0
local transition_message = ""
local has_pending_resume = false
local suggestion_index = 0
local custom_segments = {}
local custom_segment_index = 1
local overtime_seconds = 0
local overtime_epoch = 0 -- os.time() when overtime began (drift-proof)
local is_overtime = false
local stream_start_time = 0
local session_label = "" -- user-defined label for current work
local daily_focus_seconds_today = 0 -- computed from CSV on load
local focus_streak = 0 -- consecutive completed focus sessions
-- Wallclock timing (drift-proof)
local session_epoch = 0 -- os.time() when current segment counting started
local session_pause_total = 0 -- accumulated seconds paused in current segment
local pause_epoch = 0 -- os.time() when current pause began
local session_target_duration = 0 -- target seconds for current segment (adjustable)
-- File I/O optimization
local state_dirty = false
local last_save_time = 0
-- Time adjustment
local time_adjust_increment = 5 -- minutes to add/subtract per hotkey press
-- Warning alerts
local warning_5min_fired = false
local warning_1min_fired = false
local warning_break_end_fired = false
-- Volume fade state
local fade_active = false
local fade_source_name = ""
local fade_from = 1.0
local fade_to = 1.0
local fade_elapsed = 0
local fade_duration = 3 -- will be set from volume_fade_duration config
------------------------------------------------------------------------
-- 2. Configuration
--
-- Variables loaded from OBS properties (durations, toggles, paths).
-- Updated during `script_update()`.
-- Debugging: If a setting change isn't applied, check `script_update`.
------------------------------------------------------------------------
local timer_mode = "pomodoro"
local focus_duration = 1500
local short_break_duration = 300
local long_break_duration = 900
local long_break_interval = 4
local goal_sessions = 6
local transition_display_time = 2
local show_progress_bar = true
local auto_start_next = true
local progress_bar_length = 100
-- Countdown mode
local countdown_duration = 1500
-- Custom intervals mode
local custom_intervals_text = ""
-- Session offset
local starting_session_offset = 0
-- Negative timer / overtime
local enable_overtime = false
-- Warning alert settings
local enable_warning_alerts = false
local warning_5min_enabled = true
local warning_1min_enabled = true
local warning_break_end_enabled = true
local warning_break_end_seconds = 30
-- Session history logging
local enable_session_log = false
-- Stream integration toggles
local enable_chapter_markers = true
local enable_mic_control = false
local auto_start_on_stream = false
local auto_stop_on_stream_end = false
-- Mic source
local mic_source_name = ""
local mute_mic_during_focus = true
-- Source visibility
local hide_during_focus_source = ""
-- Volume ducking
local volume_source_name = ""
local focus_volume = 0.3
local break_volume = 0.8
local enable_volume_fade = true
local volume_fade_duration = 3 -- seconds, user-configurable
-- Daily goal
local daily_goal_minutes = 0 -- 0 = disabled
-- Filter toggle
local filter_source_name = ""
local focus_filters_enable = ""
local focus_filters_disable = ""
-- Break suggestions
local break_suggestions_text = "Stretch!,Hydrate!,Look away from screen,Take a walk,Deep breaths,Roll your shoulders,Stand up,Rest your eyes"
local parsed_suggestions = {}
-- Source names
local focus_count_source = ""
local message_source = ""
local time_source = ""
local progress_bar_source = ""
local background_media_source = ""
local background_music_source_name = ""
local alert_source_name = ""
local pending_background_refit = nil -- { source_name, epoch } deferred canvas fit
local status_state = {
source_name = "",
control_source_name = "SP Control",
control_scene_name = "SP Internal",
message_input = "",
duration_minutes = 0,
current_message = "",
active = false,
until_epoch = 0,
last_overlay_command_nonce = ""
}
-- Session messages
local focus_message = "Focus Time"
local short_break_message = "Short Break"
local long_break_message = "Long Break"
local paused_message = "Paused"
local transition_to_short_break_message = "Time for a short break!"
local transition_to_focus_message = "Back to focus time!"
local transition_to_long_break_message = "Time for a long break!"
-- Asset paths
local legacy_background_media_paths = {
Focus = "",
["Short Break"] = "",
["Long Break"] = ""
}
local background_image_paths = {
Focus = "",
["Short Break"] = "",
["Long Break"] = ""
}
local background_video_paths = {
Focus = "",
["Short Break"] = "",
["Long Break"] = ""
}
local background_music_track_path = ""
local alert_sound_paths = {
Focus = "",
["Short Break"] = "",
["Long Break"] = ""
}
------------------------------------------------------------------------
-- 3. Hotkey IDs
--
-- Storage for OBS frontend hotkey handles.
------------------------------------------------------------------------
local hotkey_start_pause = obs.OBS_INVALID_HOTKEY_ID
local hotkey_stop = obs.OBS_INVALID_HOTKEY_ID
local hotkey_skip = obs.OBS_INVALID_HOTKEY_ID
local hotkey_add_time = obs.OBS_INVALID_HOTKEY_ID
local hotkey_sub_time = obs.OBS_INVALID_HOTKEY_ID
local hotkey_reset = obs.OBS_INVALID_HOTKEY_ID
hotkey_resume_previous = obs.OBS_INVALID_HOTKEY_ID
-- Queued control actions
local pending_control_actions = {}
local pending_runtime_effects = {}
local scene_switching_deprecation_logged = false
local quick_setup_settings = nil
local function get_effective_completed_focus_sessions()
if timer_mode == "pomodoro" and not is_running and completed_focus_sessions == 0 and starting_session_offset > 0 then
return starting_session_offset
end
return completed_focus_sessions
end
------------------------------------------------------------------------
-- 4. Helpers
--
-- Utility routines for time math, formatting, string parsing, and paths.
-- Functions: log, mark_dirty, json_escape, get_session_elapsed,
-- compute_current_time, get_duration_for_session, format_time,
-- format_overtime, format_duration_human, get_state_file_path,
-- get_log_file_path, parse_suggestions, parse_custom_intervals,
-- get_break_suggestion
-- Debugging: Check `get_session_elapsed` if drift or timer math is off.
------------------------------------------------------------------------
local function log(msg)
print("[SessionPulse] " .. msg)
end
local function mark_dirty()
state_dirty = true
end
local function queue_control_action(action, origin)
if not action or action == "" then return end
pending_control_actions[#pending_control_actions + 1] = {
action = action,
origin = origin or "unknown"
}
log("Control queued (" .. (origin or "unknown") .. "): " .. action)
end
local function has_pending_control_action(action)
for i = 1, #pending_control_actions do
if pending_control_actions[i].action == action then
return true
end
end
return false
end
local function queue_runtime_effect(effect, origin)
if not effect or effect == "" then return end
pending_runtime_effects[#pending_runtime_effects + 1] = {
effect = effect,
origin = origin or "unknown"
}
log("Runtime effect queued (" .. (origin or "unknown") .. "): " .. effect)
end
local function json_escape(str)
if not str then return "" end
str = str:gsub('\\', '\\\\')
str = str:gsub('"', '\\"')
str = str:gsub('\n', '\\n')
str = str:gsub('\r', '\\r')
str = str:gsub('\t', '\\t')
-- Escape remaining control characters (0x00-0x1F) that weren't handled above.
-- Exclude \n (0x0A), \r (0x0D), \t (0x09) since they've already been replaced.
str = str:gsub('[%z\1-\8\11\12\14-\31]', function(c)
return string.format('\\u%04x', string.byte(c))
end)
return str
end
local function get_session_elapsed()
if session_epoch == 0 then return 0 end
local now = os.time()
local paused = session_pause_total
if is_paused and pause_epoch > 0 then
paused = paused + (now - pause_epoch)
end
return math.max(0, now - session_epoch - paused)
end
local function compute_current_time()
if not is_running then return current_time end
local elapsed = get_session_elapsed()
if timer_mode == "stopwatch" then
return elapsed
else
return math.max(0, session_target_duration - elapsed)
end
end
local function get_duration_for_session(stype)
if timer_mode == "custom" then
if custom_segments[custom_segment_index] then
return custom_segments[custom_segment_index].duration
end
return 0
end
if timer_mode == "countdown" then return countdown_duration end
if timer_mode == "stopwatch" then return 0 end
if stype == "Focus" then return focus_duration end
if stype == "Short Break" then return short_break_duration end
return long_break_duration
end
local function format_time(seconds)
if seconds < 0 then seconds = 0 end
if seconds >= 3600 then
return string.format("%d:%02d:%02d",
math.floor(seconds / 3600),
math.floor((seconds % 3600) / 60),
seconds % 60)
end
return string.format("%02d:%02d", math.floor(seconds / 60), seconds % 60)
end
local function format_overtime(seconds)
return "+" .. format_time(seconds)
end
local function format_duration_human(seconds)
if seconds < 60 then return seconds .. "s" end
local mins = math.floor(seconds / 60)
if mins < 60 then return mins .. "m" end
local hours = math.floor(mins / 60)
local rem_mins = mins % 60
if rem_mins == 0 then return hours .. "h" end
return hours .. "h " .. rem_mins .. "m"
end
local function get_state_file_path()
return script_path() .. "session_state.json"
end
function get_resume_state_file_path()
return script_path() .. "session_resume.json"
end
local function get_log_file_path()
return script_path() .. "session_history.csv"
end
local function parse_suggestions(text)
local result = {}
if not text or text == "" then return result end
for item in text:gmatch("([^,]+)") do
local trimmed = item:match("^%s*(.-)%s*$")
if trimmed and trimmed ~= "" then
result[#result + 1] = trimmed
end
end
return result
end
local function parse_custom_intervals(text)
local result = {}
if not text or text == "" then return result end
for segment in text:gmatch("([^,]+)") do
local name, mins = segment:match("^%s*(.-)%s*:%s*(%d+)%s*$")
if name and mins then
local dur = tonumber(mins) * 60
if dur > 0 then
result[#result + 1] = { name = name, duration = dur }
else
log("Custom interval '" .. name .. "' skipped: duration must be > 0")
end
end
end
-- Validation feedback in log
if #result > 0 then
local parts = {}
for _, seg in ipairs(result) do
parts[#parts + 1] = seg.name .. ":" .. (seg.duration / 60) .. "m"
end
log("Custom intervals parsed: " .. #result .. " segments → " .. table.concat(parts, ", "))
end
return result
end
local function get_break_suggestion()
if #parsed_suggestions == 0 then return nil end
suggestion_index = suggestion_index + 1
if suggestion_index > #parsed_suggestions then
suggestion_index = 1
end
return parsed_suggestions[suggestion_index]
end
------------------------------------------------------------------------
-- 5. Session History Log
--
-- CSV file read/write operations for tracking daily progress.
-- Functions: log_session, compute_daily_focus
-- Debugging: If session goals aren't updating, verify CSV headers.
------------------------------------------------------------------------
local function log_session(stype, duration, completed)
if not enable_session_log then return end
local path = get_log_file_path()
-- Write header if file doesn't exist
local check = io.open(path, "r")
local needs_header = (check == nil)
if check then check:close() end
local file = io.open(path, "a")
if not file then return end
if needs_header then
file:write("date,time,session_type,duration_seconds,completed,mode,total_focus,label\n")
end
-- CSV-escape label: wrap in quotes, double any internal quotes
local csv_label = session_label or ""
csv_label = csv_label:gsub('"', '""')
file:write(string.format("\"%s\",\"%s\",\"%s\",%d,%s,\"%s\",%d,\"%s\"\n",
os.date("%Y-%m-%d"),
os.date("%H:%M:%S"),
stype,
duration,
tostring(completed),
timer_mode,
total_focus_seconds,
csv_label
))
file:close()
end
-- Read CSV to compute today's total focus seconds (for daily goal tracking)
local function compute_daily_focus()
local path = get_log_file_path()
local file = io.open(path, "r")
if not file then
daily_focus_seconds_today = 0
return
end
local today = os.date("%Y-%m-%d")
local total = 0
local first_line = true
for line in file:lines() do
if first_line then
first_line = false -- skip header
else
-- log_session wraps fields in quotes: "date","time","type",duration,...
-- Strip optional surrounding quotes from each field before matching
local date, _, stype, dur = line:match('^"?([^",]+)"?,([^,]+),"?([^",]+)"?,(%d+)')
if date == today and stype == "Focus" then
total = total + (tonumber(dur) or 0)
end
end
end
file:close()
daily_focus_seconds_today = total
log("Daily focus loaded from CSV: " .. format_duration_human(total))
end
------------------------------------------------------------------------
-- 6. Session Persistence
--
-- JSON state saving, loading, migration, and application.
-- Functions: get_next_session_type, save_state, load_state,
-- delete_state_file, apply_saved_state
-- Debugging: Check `state_dirty` if files aren't writing, or JSON parser if corrupt.
------------------------------------------------------------------------
update_control_bridge_state = nil
write_json_to_path = function(path, json)
local tmp_path = path .. ".tmp"
local file = io.open(tmp_path, "w")
if not file then return false end
local ok = file:write(json)
if ok == false then
file:close()
os.remove(tmp_path)
return false
end
local closed = file:close()
if closed == false then
os.remove(tmp_path)
return false
end
if os.rename(tmp_path, path) then
return true
end
os.remove(path)
if os.rename(tmp_path, path) then
return true
end
os.remove(tmp_path)
return false
end
local function get_next_session_type()
if timer_mode ~= "pomodoro" then return "" end
if session_type == "Focus" then
if (cycle_count + 1) % long_break_interval == 0 then
return "Long Break"
end
return "Short Break"
end
return "Focus"
end
local function save_state(force)
-- Throttle: only write when dirty or forced, max once per second
if not force and not state_dirty then return end
local now = os.time()
if not force and now == last_save_time then return end
local display_time = compute_current_time()
local total = session_target_duration
if not is_running or total == 0 then
total = get_duration_for_session(session_type)
end
local seg_name = ""
if timer_mode == "custom" and custom_segments[custom_segment_index] then
seg_name = custom_segments[custom_segment_index].name
end
local completed_for_display = get_effective_completed_focus_sessions()
local next_type = get_next_session_type()
local sessions_remaining = math.max(0, goal_sessions - completed_for_display)
local next_in = display_time
if is_overtime then next_in = 0 end
local stream_dur = 0
if stream_start_time > 0 then
stream_dur = now - stream_start_time
end
local suggestion_text = ""
if suggestion_index > 0 and suggestion_index <= #parsed_suggestions then
suggestion_text = parsed_suggestions[suggestion_index]
end
-- Build chat-ready status line
local chat_status = ""
if is_running then
if is_overtime then
chat_status = string.format("%s +%s", session_type, format_time(overtime_seconds))
elseif timer_mode == "stopwatch" then
chat_status = "Stopwatch " .. format_time(display_time)
elseif timer_mode == "pomodoro" then
chat_status = string.format("%s %s (%d/%d)",
session_type, format_time(display_time),
completed_for_display, goal_sessions)
elseif timer_mode == "custom" and seg_name ~= "" then
chat_status = string.format("%s %s (%d/%d)",
seg_name, format_time(display_time),
custom_segment_index, #custom_segments)
else
chat_status = string.format("%s %s", session_type, format_time(display_time))
end
if is_paused then chat_status = chat_status .. " [Paused]" end
end
-- Compute derived fields for external consumption
local elapsed_seconds = get_session_elapsed()
local progress_pct = 0
if total > 0 then
progress_pct = math.min(100, math.floor(((total - display_time) / total) * 100))
end
if is_overtime then progress_pct = 100 end
-- "Ends at" local time string (e.g., "15:45")
local ends_at = ""
if is_running and not is_paused and not is_overtime and timer_mode ~= "stopwatch" then
ends_at = os.date("%H:%M", now + display_time)
end
local active_status_message = ""
if status_state.active and status_state.current_message ~= "" then
active_status_message = status_state.current_message
end
local json = string.format(
'{\n' ..
' "version": "%s",\n' ..
' "timer_mode": "%s",\n' ..
' "is_running": %s,\n' ..
' "is_paused": %s,\n' ..
' "session_type": "%s",\n' ..
' "current_time": %d,\n' ..
' "total_time": %d,\n' ..
' "elapsed_seconds": %d,\n' ..
' "progress_percent": %d,\n' ..
' "ends_at": "%s",\n' ..
' "cycle_count": %d,\n' ..
' "completed_focus_sessions": %d,\n' ..
' "goal_sessions": %d,\n' ..
' "total_focus_seconds": %d,\n' ..
' "show_transition": %s,\n' ..
' "transition_message": "%s",\n' ..
' "custom_segment_name": "%s",\n' ..
' "custom_segment_index": %d,\n' ..
' "custom_segment_count": %d,\n' ..
' "is_overtime": %s,\n' ..
' "overtime_seconds": %d,\n' ..
' "next_session_type": "%s",\n' ..
' "next_session_in": %d,\n' ..
' "sessions_remaining": %d,\n' ..
' "break_suggestion": "%s",\n' ..
' "stream_duration": %d,\n' ..
' "chat_status_line": "%s",\n' ..
' "session_label": "%s",\n' ..
' "status_active": %s,\n' ..
' "status_message": "%s",\n' ..
' "status_until_epoch": %d,\n' ..
' "daily_focus_seconds": %d,\n' ..
' "daily_goal_seconds": %d,\n' ..
' "focus_streak": %d,\n' ..
' "session_epoch": %d,\n' ..
' "session_pause_total": %d,\n' ..
' "session_target_duration": %d,\n' ..
' "resume_available": %s,\n' ..
' "timestamp": %d\n' ..
'}',
json_escape(VERSION),
json_escape(timer_mode),
tostring(is_running),
tostring(is_paused),
json_escape(session_type),
display_time,
total,
elapsed_seconds,
progress_pct,
json_escape(ends_at),
cycle_count,
completed_for_display,
goal_sessions,
total_focus_seconds,
tostring(show_transition),
json_escape(transition_message),
json_escape(seg_name),
custom_segment_index,
#custom_segments,
tostring(is_overtime),
overtime_seconds,
json_escape(next_type),
next_in,
sessions_remaining,
json_escape(suggestion_text),
stream_dur,
json_escape(chat_status),
json_escape(session_label),
tostring(status_state.active and active_status_message ~= ""),
json_escape(active_status_message),
status_state.until_epoch,
daily_focus_seconds_today + total_focus_seconds,
daily_goal_minutes * 60,
focus_streak,
session_epoch,
session_pause_total,
session_target_duration,
tostring(has_pending_resume),
now
)
local state_saved = write_json_to_path(get_state_file_path(), json)
if state_saved then
if is_running then
write_json_to_path(get_resume_state_file_path(), json)
elseif not has_pending_resume then
os.remove(get_resume_state_file_path())
os.remove(get_resume_state_file_path() .. ".tmp")
end
state_dirty = false
last_save_time = now
end
if update_control_bridge_state then
update_control_bridge_state(true)
end
end
load_state_from_path = function(path)
local file = io.open(path, "r")
if not file then return nil end
local content = file:read("*all")
file:close()
if not content or content == "" then return nil end
local function get_string(key)
local _, value_start = content:find('"' .. key .. '":%s*"', 1)
if not value_start then return nil end
local chars = {}
local escaped = false
local i = value_start + 1
while i <= #content do
local ch = content:sub(i, i)
if escaped then
if ch == "n" then
chars[#chars + 1] = "\n"
elseif ch == "r" then
chars[#chars + 1] = "\r"
elseif ch == "t" then
chars[#chars + 1] = "\t"
else
chars[#chars + 1] = ch
end
escaped = false
elseif ch == "\\" then
escaped = true
elseif ch == '"' then
break
else
chars[#chars + 1] = ch
end
i = i + 1
end
return table.concat(chars)
end
local function get_number(key)
local val = content:match('"' .. key .. '":%s*(%d+)')
return val and tonumber(val) or nil
end
local function get_bool(key)
local val = content:match('"' .. key .. '":%s*(%a+)')
return val == "true"
end
local state = {
version = get_string("version"),
timer_mode = get_string("timer_mode"),
is_running = get_bool("is_running"),
is_paused = get_bool("is_paused"),
session_type = get_string("session_type"),
current_time = get_number("current_time"),
cycle_count = get_number("cycle_count"),
completed_focus_sessions = get_number("completed_focus_sessions"),
total_focus_seconds = get_number("total_focus_seconds"),
custom_segment_index = get_number("custom_segment_index"),
status_active = get_bool("status_active"),
status_message = get_string("status_message"),
status_until_epoch = get_number("status_until_epoch"),
timestamp = get_number("timestamp"),
-- v5.0 wallclock fields
session_epoch = get_number("session_epoch"),
session_pause_total = get_number("session_pause_total"),
session_target_duration = get_number("session_target_duration"),
}
if not state.current_time then
log("State file corrupt — ignoring")
return nil
end
if (not state.timer_mode or state.timer_mode == "pomodoro") and state.session_type then
if state.session_type ~= "Focus" and
state.session_type ~= "Short Break" and
state.session_type ~= "Long Break" then
log("Unknown session type in state: " .. state.session_type)
return nil
end
end
-- Detect v4.x state files (no wallclock fields) — migrate gracefully
if state.session_epoch == nil or state.session_epoch == 0 then
state.is_v4_migration = true
log("Migrating v4.x state — wallclock will be freshly initialized")
end
return state
end
local function load_state()
return load_state_from_path(get_state_file_path())
end
load_resume_state = function()
return load_state_from_path(get_resume_state_file_path())
end
local function refresh_pending_resume_state()
local state = load_resume_state()
if not state or not state.is_running then
-- Backward compatibility for older installs that only had session_state.json.
local legacy_state = load_state()
if legacy_state and legacy_state.is_running then
local live_path = get_state_file_path()
local live_file = io.open(live_path, "r")
if live_file then
local live_content = live_file:read("*all")
live_file:close()
if live_content and live_content ~= "" then
write_json_to_path(get_resume_state_file_path(), live_content)
end
end
state = legacy_state
end
end
has_pending_resume = state ~= nil and state.is_running == true
return state
end
local function delete_state_file()
os.remove(get_state_file_path())
-- Clean up temp file if it exists
os.remove(get_state_file_path() .. ".tmp")
os.remove(get_resume_state_file_path())
os.remove(get_resume_state_file_path() .. ".tmp")
end
-- Forward declarations (referenced by apply_saved_state before definition)
local update_display_texts
local update_background_media
local update_background_music
local update_mic_state
local update_source_visibility
local update_volume
local update_filters
local function apply_saved_state(state)
session_type = state.session_type or "Focus"
current_time = state.current_time
cycle_count = state.cycle_count or 0
completed_focus_sessions = state.completed_focus_sessions or 0
total_focus_seconds = state.total_focus_seconds or 0
is_overtime = false
overtime_seconds = 0
overtime_epoch = 0
if state.custom_segment_index and state.timer_mode == "custom" then
custom_segment_index = state.custom_segment_index
end
status_state.active = state.status_active == true
status_state.current_message = state.status_message or status_state.current_message or status_state.message_input or ""
status_state.until_epoch = state.status_until_epoch or 0
if status_state.active and status_state.until_epoch > 0 and os.time() >= status_state.until_epoch then
status_state.active = false
status_state.until_epoch = 0
status_state.current_message = ""
end
-- Initialize wallclock state for resume
if state.is_running then
is_running = true
is_paused = state.is_paused or false
-- Resume should continue from the exact saved timer state, not consume time
-- while OBS was closed or the machine was offline.
if timer_mode == "stopwatch" then
session_epoch = os.time() - (state.current_time or 0)
session_pause_total = 0
session_target_duration = 0
else
local saved_total = state.session_target_duration or get_duration_for_session(session_type)
local saved_remaining = state.current_time or saved_total
local saved_elapsed = math.max(0, saved_total - saved_remaining)
session_epoch = os.time() - saved_elapsed
session_pause_total = 0
session_target_duration = saved_total
local current_setting = get_duration_for_session(session_type)
if saved_total ~= current_setting and current_setting > 0 then
log("Note: Resumed session uses saved duration (" ..
format_duration_human(saved_total) .. "), current setting is " ..
format_duration_human(current_setting))
end
end
if is_paused then
pause_epoch = os.time()
current_time = state.current_time or current_time
else
pause_epoch = 0
current_time = compute_current_time()
end
log("Resumed from saved state — " .. session_type .. " at " .. format_time(current_time) ..
" (" .. (is_paused and "paused" or "running") .. ")")
else
is_running = false
is_paused = false
session_epoch = 0
session_pause_total = 0
pause_epoch = 0
session_target_duration = 0
end
-- Reset warning flags
warning_5min_fired = false
warning_1min_fired = false
warning_break_end_fired = false
has_pending_resume = false
update_display_texts()
update_background_media()
update_background_music(true)
update_mic_state()
update_source_visibility()
update_volume()
update_filters()
mark_dirty()
save_state(true)
end
------------------------------------------------------------------------
-- 7. OBS Source Interaction
--
-- Text, background media, and alert sound updates via OBS data API.
-- Functions: update_obs_source_text, update_background_media, play_alert_sound
-- Debugging: Ensure sources exist exactly as named if they don't update.
------------------------------------------------------------------------
local function update_obs_source_text(source_name, text)
if not source_name or source_name == "" then return end
local source = obs.obs_get_source_by_name(source_name)
if source then
local settings = obs.obs_data_create()
obs.obs_data_set_string(settings, "text", text)
obs.obs_source_update(source, settings)
obs.obs_data_release(settings)
obs.obs_source_release(source)
end
end
function get_obs_source_text(source_name)
if not source_name or source_name == "" then return "" end
local source = obs.obs_get_source_by_name(source_name)
if not source then return "" end
local text = ""
local ok, settings = pcall(function()
return obs.obs_source_get_settings(source)
end)
if ok and settings then
text = obs.obs_data_get_string(settings, "text") or ""
obs.obs_data_release(settings)
end
obs.obs_source_release(source)
return text
end
local function set_source_enabled_by_name(source_name, enabled)
if not source_name or source_name == "" then return false end
local source = obs.obs_get_source_by_name(source_name)
if not source then return false end
obs.obs_source_set_enabled(source, enabled)
obs.obs_source_release(source)
return true
end
local function get_background_source_mode(source_name)
if not source_name or source_name == "" then return "unknown" end
local source = obs.obs_get_source_by_name(source_name)
if not source then return "unknown" end
local source_id = obs.obs_source_get_id(source)
obs.obs_source_release(source)
if source_id == "image_source" then
return "image"
end
if source_id == "ffmpeg_source" then
return "video"
end
return "unknown"
end