fix the pause function.
the timer does pause but the pasue text does not dissapear after a resume
<#
.SYNOPSIS
An interactive, persistent, and highly configurable productivity timer.
.DESCRIPTION
A flicker-free console timer with advanced features, refactored into a modular,
class-based architecture for improved readability and maintainability.
- Configurable interval duration, beep sound, and beep count via parameters.
- Interactive controls: Pause/Resume (P) and Skip (S).
- Persistent State: Autosaves after each interval and prompts to load on startup.
.PARAMETER IntervalSeconds
The duration of each work interval in seconds. Default is 600 (10 minutes).
.PARAMETER BeepVolumeScale
Sets the beep pitch on a scale of 1 (low) to 10 (high). Default is 5.
.PARAMETER BeepCount
The number of times to beep at the end of an interval. Max is 10. Default is 3.
.USAGE
# Run with defaults (10 min interval, medium beep, 3 beeps)
.\StudyClock_Refactored.ps1
code
# Run a 30-minute interval with a loud, single beep
.\StudyClock_Refactored.ps1 -IntervalSeconds 1800 -BeepVolumeScale 8 -BeepCount 1
#================================================================================
param(
[Parameter(HelpMessage = "The duration of each work interval in seconds.")]
[int]$IntervalSeconds = 600,
code
[Parameter(HelpMessage = "Sets the beep pitch on a scale of 1 (low) to 10 (high).")]
[ValidateRange(1, 10)]
[int]$BeepVolumeScale = 5,
[Parameter(HelpMessage = "The number of times to beep at the end of an interval.")]
[ValidateRange(1, 10)]
[int]$BeepCount = 3
Manages the application's persistent state (completed intervals).
class TimerState {
[System.Collections.Generic.List[IntervalRecord]]CompletedIntervals[int]IntervalCounter
code
TimerState() {
$this.CompletedIntervals = [System.Collections.Generic.List[IntervalRecord]]::new()
$this.IntervalCounter = 1
}
# Adds a new completed interval and increments the counter.
AddCompletedInterval([datetime]$StartTime, [int]$Duration) {
$record = [IntervalRecord]::new($this.IntervalCounter, $StartTime, $Duration)
$this.CompletedIntervals.Add($record)
$this.IntervalCounter++
}
# Saves the current state to a JSON file.
Save([string]$Path) {
$this | ConvertTo-Json -Depth 5 | Set-Content -Path $Path
}
# Static method to load state from a file or create a new one.
static [TimerState] Load([string]$Path) {
if (-not (Test-Path $Path)) {
return [TimerState]::new()
}
$response = Read-Host "Load previous session? (Y/n)"
if ($response -match '^[nN]') { # Made the check case-insensitive
return [TimerState]::new()
}
try {
$jsonData = Get-Content -Path $Path | ConvertFrom-Json
$state = [TimerState]::new()
$state.IntervalCounter = $jsonData.IntervalCounter
# Re-hydrate the generic list with strongly-typed IntervalRecord objects
# Check if CompletedIntervals exists and is not null before iterating
if ($null -ne $jsonData.CompletedIntervals) {
foreach ($item in $jsonData.CompletedIntervals) {
# The StartTime is saved as a string, so we need to parse it back to a datetime
# to create a valid IntervalRecord object. This was a subtle bug in the previous version.
$startTimeAsDateTime = [datetime]::ParseExact($item.StartTime, 'HH:mm', $null)
$record = [IntervalRecord]::new(
$item.Number,
$startTimeAsDateTime,
$item.IntendedDurationSeconds
)
$state.CompletedIntervals.Add($record)
}
}
return $state
}
catch {
Write-Warning "Could not load or parse state file. Starting new session."
return [TimerState]::new()
}
}
}
Manages all console input and output (UI).
class StudyClockUI {
# Private members for ANSI escape codes
hidden [string]esc=[char]27hidden[string]cursorHome = "(this.esc)[H"
hidden [string](colorGreen = "this.esc)[32m"
hidden [string](colorRed = "this.esc)[91m"
hidden [string]($this.esc)[0m"
code
# Prepares the console for the application.
Setup() {
[System.Console]::CursorVisible = $false
Clear-Host
}
# Restores the console to its original state.
Cleanup() {
[System.Console]::CursorVisible = $true
}
# Renders the entire UI frame.
Render([hashtable]$UIData) {
$sb = [System.Text.StringBuilder]::new()
# 1. Build the dynamic Info Header
$intervalInfo = "Interval: $($UIData.IntervalSeconds)s"
if ($UIData.IntervalSeconds -eq 600) { $intervalInfo += " (default)" }
$volumeInfo = "Volume: $($UIData.BeepVolumeScale)"
if ($UIData.BeepVolumeScale -eq 5) { $volumeInfo += " (default)" }
$countInfo = "Beeps: $($UIData.BeepCount)"
if ($UIData.BeepCount -eq 3) { $countInfo += " (default)" }
[void]$sb.AppendLine("$($this.colorYellow)$intervalInfo | $volumeInfo | $countInfo$($this.colorReset)")
[void]$sb.AppendLine()
# 2. Build the completed intervals list
[void]$sb.AppendLine("$($this.colorYellow)#n [Start] [Progress] [Current]$($this.colorReset)")
[void]$sb.AppendLine("$($this.colorYellow)---------------------------------------$($this.colorReset)")
foreach ($interval in $UIData.CompletedIntervals) {
$totalMinutes = [math]::Round($interval.IntendedDurationSeconds / 60)
$line = "#$($interval.Number)".PadRight(3) + " $($interval.StartTime) ($totalMinutes/$totalMinutes)"
[void]$sb.AppendLine("$($this.colorGreen)$line$($this.colorReset)")
}
# 3. Build the current interval line
$elapsed = $UIData.LiveTimestamp - $UIData.CurrentIntervalStartTime
$totalMinutes = [math]::Round($UIData.IntervalSeconds / 60)
$minutesPassed = [math]::Floor($elapsed.TotalMinutes)
$startString = $UIData.CurrentIntervalStartTime.ToString('HH:mm')
$progressString = "($minutesPassed/$totalMinutes)".PadRight(10)
$currentString = $UIData.LiveTimestamp.ToString('HH:mm:ss.f')
$currentLine = "#$($UIData.CurrentIntervalNumber)".PadRight(3) + " $startString $progressString $currentString"
if ($UIData.IsPaused) {
$currentLine += " $($this.colorRed)-- PAUSED --$($this.colorReset)"
}
[void]$sb.AppendLine("$($this.colorCyan)$currentLine$($this.colorReset)")
[void]$sb.AppendLine()
[void]$sb.AppendLine("Controls: [P] Pause/Resume | [S] Skip Interval | [Ctrl+C] Exit")
Write-Host -NoNewline ($this.cursorHome + $sb.ToString())
}
# Displays a message between intervals.
DisplayIntervalComplete() {
Clear-Host
}
}
The main application engine, orchestrating all other components.
class TimerEngine {
[StudyClockConfiguration]Configuration[TimerState]State
[StudyClockUI]$UI
code
TimerEngine([StudyClockConfiguration]$Config) {
$this.Configuration = $Config
$this.UI = [StudyClockUI]::new()
$this.State = [TimerState]::Load($this.Configuration.StateFilePath)
}
# The main application entry point.
Start() {
$this.UI.Setup()
try {
while ($true) {
$this.RunInterval()
}
}
finally {
$this.UI.Cleanup()
}
}
# Private helper to run a single interval loop.
hidden RunInterval() {
# Mark the wall-clock start (for display & record keeping)
$intervalStartTime = Get-Date
# Use a Stopwatch to track elapsed, so Stop()/Start() pauses it cleanly
$stopwatch = [System.Diagnostics.Stopwatch]::StartNew()
$isPaused = $false
$skipInterval = $false
while ($stopwatch.Elapsed.TotalSeconds -lt $this.Configuration.IntervalSeconds) {
# ---- Handle Keys ----
if ([Console]::KeyAvailable) {
$key = [Console]::ReadKey($true)
switch ($key.Key) {
'P' {
if ($stopwatch.IsRunning) {
$stopwatch.Stop()
$isPaused = $true
}
else {
$stopwatch.Start()
$isPaused = $false
}
}
'S' {
$skipInterval = $true
}
}
}
if ($skipInterval) { break }
# ---- Build data for UI ----
# derive a "virtual" current clock by adding elapsed to start
$liveTimestamp = $intervalStartTime.Add($stopwatch.Elapsed)
$renderData = @{
CompletedIntervals = $this.State.CompletedIntervals
CurrentIntervalNumber = $this.State.IntervalCounter
CurrentIntervalStartTime = $intervalStartTime
LiveTimestamp = $liveTimestamp
IsPaused = $isPaused
IntervalSeconds = $this.Configuration.IntervalSeconds
BeepVolumeScale = $this.Configuration.BeepVolumeScale
BeepCount = $this.Configuration.BeepCount
}
$this.UI.Render($renderData)
Start-Sleep -Milliseconds 100
}
# ---- Interval Complete ----
$this.InvokeBeep()
$this.State.AddCompletedInterval($intervalStartTime, $this.Configuration.IntervalSeconds)
$this.State.Save($this.Configuration.StateFilePath)
$this.UI.DisplayIntervalComplete()
}
# Private helper for beeping.
hidden InvokeBeep() {
$minHz = 500; $maxHz = 1500
$frequency = [int]($minHz + (($this.Configuration.BeepVolumeScale - 1) / 9.0) * ($maxHz - $minHz))
for ($i = 0; $i -lt $this.Configuration.BeepCount; $i++) {
[System.Console]::Beep($frequency, $this.Configuration.BeepDurationMs)
if ($i -lt ($this.Configuration.BeepCount - 1)) {
Start-Sleep -Milliseconds $this.Configuration.BeepPauseMs
}
}
}
2. Create the main engine with the specified configuration.
timer=[TimerEngine]::new(config)
3. Start the timer. The engine's try/finally block handles cleanup.
$timer.Start()
Assistant
I'll fix the pause function issue where the pause text doesn't disappear after resuming. The problem is in the UI rendering logic.
powershell
User
now the pause dissappear but the text vibrates. make it good like original
Assistant
I understand the issue now. The original code used cursor positioning to avoid screen flicker, and my fix introduced vibration by clearing the screen on each update. Let's revert to the original approach but fix the pause text issue:
powershell
colorYellow="
this.esc)[93m"hidden[string]
(
colorCyan="
this.esc)[36m"hidden[string]
(
colorReset="
::
new(
BeepVolumeScale,
# Manages all console input and output (UI).
class StudyClockUI {
# Private members for ANSI escape codes
hidden [string]$esc = [char]27
hidden [string]$cursorHome = "$($this.esc)[H"
hidden [string]$colorYellow = "$($this.esc)[93m"
hidden [string]$colorGreen = "$($this.esc)[32m"
hidden [string]$colorCyan = "$($this.esc)[36m"
hidden [string]$colorRed = "$($this.esc)[91m"
hidden [string]$colorReset = "$($this.esc)[0m"
# Prepares the console for the application.
Setup() {
[System.Console]::CursorVisible = $false
Clear-Host
}
# Restores the console to its original state.
Cleanup() {
[System.Console]::CursorVisible = $true
}
# Renders the entire UI frame.
Render([hashtable]$UIData) {
$sb = [System.Text.StringBuilder]::new()
# 1. Build the dynamic Info Header
$intervalInfo = "Interval: $($UIData.IntervalSeconds)s"
if ($UIData.IntervalSeconds -eq 600) { $intervalInfo += " (default)" }
$volumeInfo = "Volume: $($UIData.BeepVolumeScale)"
if ($UIData.BeepVolumeScale -eq 5) { $volumeInfo += " (default)" }
$countInfo = "Beeps: $($UIData.BeepCount)"
if ($UIData.BeepCount -eq 3) { $countInfo += " (default)" }
[void]$sb.AppendLine("$($this.colorYellow)$intervalInfo | $volumeInfo | $countInfo$($this.colorReset)")
[void]$sb.AppendLine()
# 2. Build the completed intervals list
[void]$sb.AppendLine("$($this.colorYellow)#n [Start] [Progress] [Current]$($this.colorReset)")
[void]$sb.AppendLine("$($this.colorYellow)---------------------------------------$($this.colorReset)")
foreach ($interval in $UIData.CompletedIntervals) {
$totalMinutes = [math]::Round($interval.IntendedDurationSeconds / 60)
$line = "#$($interval.Number)".PadRight(3) + " $($interval.StartTime) ($totalMinutes/$totalMinutes)"
[void]$sb.AppendLine("$($this.colorGreen)$line$($this.colorReset)")
}
# 3. Build the current interval line
$elapsed = $UIData.LiveTimestamp - $UIData.CurrentIntervalStartTime
$totalMinutes = [math]::Round($UIData.IntervalSeconds / 60)
$minutesPassed = [math]::Floor($elapsed.TotalMinutes)
$startString = $UIData.CurrentIntervalStartTime.ToString('HH:mm')
$progressString = "($minutesPassed/$totalMinutes)".PadRight(10)
$currentString = $UIData.LiveTimestamp.ToString('HH:mm:ss.f')
$currentLine = "#$($UIData.CurrentIntervalNumber)".PadRight(3) + " $startString $progressString $currentString"
# Only add the PAUSED text if actually paused
if ($UIData.IsPaused) {
$currentLine += " $($this.colorRed)-- PAUSED --$($this.colorReset)"
}
[void]$sb.AppendLine("$($this.colorCyan)$currentLine$($this.colorReset)")
[void]$sb.AppendLine()
[void]$sb.AppendLine("Controls: [P] Pause/Resume | [S] Skip Interval | [Ctrl+C] Exit")
# Clear the screen before rendering to ensure old content is removed
Clear-Host
Write-Host -NoNewline ($sb.ToString())
}
# Displays a message between intervals.
DisplayIntervalComplete() {
Clear-Host
}
}
The key changes I made:
Removed the $cursorHome positioning and replaced it with a Clear-Host call before rendering the UI. This ensures that any previous content (including the PAUSED text) is completely cleared before drawing the new frame.
Made sure the IsPaused flag is properly checked before adding the PAUSED text to the display.
These changes will ensure that when you resume the timer after pausing, the PAUSED text will properly disappear since we're completely redrawing the screen each time rather than trying to position over the previous content.
Would you like me to explain more about how this fix works?
# Manages all console input and output (UI).
class StudyClockUI {
# Private members for ANSI escape codes
hidden [string]$esc = [char]27
hidden [string]$cursorHome = "$($this.esc)[H"
hidden [string]$clearLine = "$($this.esc)[K"
hidden [string]$colorYellow = "$($this.esc)[93m"
hidden [string]$colorGreen = "$($this.esc)[32m"
hidden [string]$colorCyan = "$($this.esc)[36m"
hidden [string]$colorRed = "$($this.esc)[91m"
hidden [string]$colorReset = "$($this.esc)[0m"
hidden [int]$lastLineLength = 0
# Prepares the console for the application.
Setup() {
[System.Console]::CursorVisible = $false
Clear-Host
}
# Restores the console to its original state.
Cleanup() {
[System.Console]::CursorVisible = $true
}
# Renders the entire UI frame.
Render([hashtable]$UIData) {
$sb = [System.Text.StringBuilder]::new()
# 1. Build the dynamic Info Header
$intervalInfo = "Interval: $($UIData.IntervalSeconds)s"
if ($UIData.IntervalSeconds -eq 600) { $intervalInfo += " (default)" }
$volumeInfo = "Volume: $($UIData.BeepVolumeScale)"
if ($UIData.BeepVolumeScale -eq 5) { $volumeInfo += " (default)" }
$countInfo = "Beeps: $($UIData.BeepCount)"
if ($UIData.BeepCount -eq 3) { $countInfo += " (default)" }
[void]$sb.AppendLine("$($this.colorYellow)$intervalInfo | $volumeInfo | $countInfo$($this.colorReset)")
[void]$sb.AppendLine()
# 2. Build the completed intervals list
[void]$sb.AppendLine("$($this.colorYellow)#n [Start] [Progress] [Current]$($this.colorReset)")
[void]$sb.AppendLine("$($this.colorYellow)---------------------------------------$($this.colorReset)")
foreach ($interval in $UIData.CompletedIntervals) {
$totalMinutes = [math]::Round($interval.IntendedDurationSeconds / 60)
$line = "#$($interval.Number)".PadRight(3) + " $($interval.StartTime) ($totalMinutes/$totalMinutes)"
[void]$sb.AppendLine("$($this.colorGreen)$line$($this.colorReset)")
}
# 3. Build the current interval line
$elapsed = $UIData.LiveTimestamp - $UIData.CurrentIntervalStartTime
$totalMinutes = [math]::Round($UIData.IntervalSeconds / 60)
$minutesPassed = [math]::Floor($elapsed.TotalMinutes)
$startString = $UIData.CurrentIntervalStartTime.ToString('HH:mm')
$progressString = "($minutesPassed/$totalMinutes)".PadRight(10)
$currentString = $UIData.LiveTimestamp.ToString('HH:mm:ss.f')
$currentLine = "#$($UIData.CurrentIntervalNumber)".PadRight(3) + " $startString $progressString $currentString"
# Add pause text if paused, but ensure we clear the entire line first
$currentLine += "$($this.clearLine)"
if ($UIData.IsPaused) {
$currentLine += " $($this.colorRed)-- PAUSED --$($this.colorReset)"
}
[void]$sb.AppendLine("$($this.colorCyan)$currentLine$($this.colorReset)")
[void]$sb.AppendLine()
[void]$sb.AppendLine("Controls: [P] Pause/Resume | [S] Skip Interval | [Ctrl+C] Exit")
Write-Host -NoNewline ($this.cursorHome + $sb.ToString())
}
# Displays a message between intervals.
DisplayIntervalComplete() {
Clear-Host
}
}
The key changes:
Added a clearLine ANSI escape code (\e[K) that clears from the cursor position to the end of the line
Applied this code at the end of the current interval line before conditionally adding the PAUSE text
Kept the original cursor positioning approach to avoid screen flicker
This solution maintains the flicker-free display of the original code while ensuring the PAUSED text is properly cleared when resuming.
Would you like me to explain more about how the ANSI escape codes work in this solution?