Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Resources/pl.lproj/Localizable.strings
Original file line number Diff line number Diff line change
Expand Up @@ -104,3 +104,5 @@
"Close the tasks" = "Zamknij zadania";
"done" = "zrobione";
"not done" = "do zrobienia";
"stopped" = "zatrzymano";
"round %lld of %lld" = "runda %lld z %lld";
47 changes: 45 additions & 2 deletions Sources/FocusCore/SessionClock.swift
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,12 @@ public enum Phase: Equatable, Sendable {
case done

public var isStudy: Bool { if case .study = self { true } else { false } }
public var round: Int? {
switch self {
case .study(let round), .rest(let round): round
case .idle, .done: nil
}
}
public var isRunning: Bool {
switch self {
case .study, .rest: true
Expand All @@ -41,10 +47,23 @@ public struct SessionClock: Sendable {
public private(set) var phaseDuration: TimeInterval = 0
private var phaseEnd: Date?
private var pausedRemaining: TimeInterval?
/// Study time of the study phases already over.
private var studiedBefore: TimeInterval = 0
/// Where a session ended with stop was, so its summary can take it back.
private var stopped: (phase: Phase, remaining: TimeInterval)?

public init() {}

public var isPaused: Bool { pausedRemaining != nil }
/// The phase a stopped session was in; nil when it ran to the end.
public var stoppedIn: Phase? { stopped?.phase }

/// Time actually spent in study phases, pauses excluded.
public func studied(at now: Date) -> TimeInterval {
let current = stopped.map { $0.phase.isStudy ? phaseDuration - $0.remaining : 0 }
?? (phase.isStudy ? phaseDuration - remaining(at: now) : 0)
return studiedBefore + current
}

/// Every 4th break is three times as long, capped at 30 minutes.
public func breakMinutes(after round: Int) -> Int {
Expand All @@ -66,15 +85,37 @@ public struct SessionClock: Sendable {
self.config = SessionConfig(studyMinutes: max(1, config.studyMinutes),
breakMinutes: max(1, config.breakMinutes),
rounds: max(1, config.rounds))
pausedRemaining = nil
reset()
enter(.study(round: 1), at: now)
}

public mutating func stop() {
/// Back to idle, forgetting the session.
public mutating func reset() {
phase = .idle
phaseEnd = nil
pausedRemaining = nil
phaseDuration = 0
studiedBefore = 0
stopped = nil
}

/// Ends a running session early, on its summary. Stopped within its first seconds, it just goes back to idle.
public mutating func stop(at now: Date) {
tick(at: now)
guard phase.isRunning else { return }
if studied(at: now) < 10 { return reset() }
stopped = (phase, remaining(at: now))
phase = .done
phaseEnd = nil
pausedRemaining = nil
}

/// Takes a stop back: the session carries on where it was stopped.
public mutating func undoStop(at now: Date) {
guard let stopped else { return }
phase = stopped.phase
phaseEnd = now.addingTimeInterval(stopped.remaining)
self.stopped = nil
}

public mutating func pause(at now: Date) {
Expand Down Expand Up @@ -104,9 +145,11 @@ public struct SessionClock: Sendable {
private mutating func advance(at time: Date) {
switch phase {
case .study(let round) where round >= config.rounds:
studiedBefore += phaseDuration
phase = .done
phaseEnd = nil
case .study(let round):
studiedBefore += phaseDuration
enter(.rest(round: round), at: time)
case .rest(let round):
enter(.study(round: round + 1), at: time)
Expand Down
29 changes: 23 additions & 6 deletions Sources/FocusGuard/AppModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -171,8 +171,9 @@ final class AppModel: ObservableObject {
let s = Int(remaining.rounded(.up))
return String(format: "%d:%02d", s / 60, s % 60)
}
/// Minutes actually studied: study phases only, pauses left out.
var studiedMinutes: Int { Int((clock.studied(at: monoNow) / 60).rounded()) }
/// nil without camera data: no figure is better than a made-up one.
var studiedMinutes: Int { clock.config.studyMinutes * clock.config.rounds }
var averageFocus: Int? { history.isEmpty ? nil : Int(history.reduce(0, +) / Double(history.count)) }
/// Focus figures need a running camera that has finished calibrating on a real face.
var showsFocus: Bool { !timerOnly && camera == .running && !calibrating && !focusStale }
Expand Down Expand Up @@ -217,15 +218,27 @@ final class AppModel: ObservableObject {
cardHidden = false
phaseStart = Date()
clock.start(config, at: monoNow)
// Keeps App Nap from throttling the timer without blocking idle sleep.
activity = ProcessInfo.processInfo.beginActivity(options: .userInitiatedAllowingIdleSystemSleep,
reason: "Study session timer")
phaseChanged()
}

/// Ends the session on its summary, which can take the stop back.
func stop() {
clock.stop()
clock.stop(at: monoNow)
pausedBySleep = false
cardHidden = false
phaseChanged()
}

/// "resume" on the summary of a stopped session.
func undoStop() {
clock.undoStop(at: monoNow)
phaseStart = Date()
phaseChanged()
}

/// From the summary back to the idle card and its settings.
func reset() {
clock.reset()
phaseChanged()
}

Expand Down Expand Up @@ -370,7 +383,11 @@ final class AppModel: ObservableObject {
camera = .off
calibrating = false
}
if !clock.phase.isRunning, let activity {
if clock.phase.isRunning, activity == nil {
// Keeps App Nap from throttling the timer without blocking idle sleep.
activity = ProcessInfo.processInfo.beginActivity(options: .userInitiatedAllowingIdleSystemSleep,
reason: "Study session timer")
} else if !clock.phase.isRunning, let activity {
ProcessInfo.processInfo.endActivity(activity)
self.activity = nil
}
Expand Down
12 changes: 8 additions & 4 deletions Sources/FocusGuard/Card.swift
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ private struct CardContent: View {
case "done":
RuledRow(height: 18) {
HStack(alignment: .lastTextBaseline) {
Text("done!").font(Ink.hand(13))
Text(model.clock.stoppedIn == nil ? "done!" : "stopped").font(Ink.hand(13))
Spacer(minLength: 4)
if !model.history.isEmpty { Text("nudges: \(model.nudges)").font(Ink.hand(11)) }
}
Expand All @@ -174,15 +174,19 @@ private struct CardContent: View {
Sparkline(values: model.history).frame(width: 60, height: 16)
Num(text: "\(average)%", size: 16)
}
} else if let round = model.clock.stoppedIn?.round {
Text("round \(round) of \(model.clock.config.rounds)").font(Ink.hand(12))
} else {
Text("\(model.clock.config.rounds) rounds").font(Ink.hand(12))
}
}
RuledRow(height: 18, seed: 3) {
HStack {
WordLink(title: "adjust", size: 12, action: model.stop) // back to the idle card and its settings
HStack(spacing: 0) {
// A stop is one click away from pause, so its summary can take it back.
if model.clock.stoppedIn != nil { WordLink(title: "resume", size: 12, action: model.undoStop) }
Spacer(minLength: 4)
WordLink(title: "new session", size: 12, underlined: true, action: model.requestStart)
WordLink(title: "adjust", size: 12, action: model.reset) // back to the idle card and its settings
WordLink(title: "new session", size: 12, underlined: true, action: model.requestStart).padding(.leading, 9)
}
}
default: // idle: the session's settings right on the card, and start
Expand Down
5 changes: 3 additions & 2 deletions Sources/FocusGuard/Debug.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import SwiftUI
enum DebugWindow {
static var window: NSWindow?

/// States: idle (default), hint, why, study, paused, sleep, settings, break, done, bubble, music, nomusic, nudge, todos.
/// States: idle (default), hint, why, study, paused, sleep, settings, break, done, stopped, bubble, music, nomusic, nudge, todos.
/// `--large` draws the bigger panel.
static func configure(_ model: AppModel) {
model.persists = false // fixtures never touch the user's settings
Expand All @@ -30,7 +30,7 @@ enum DebugWindow {
if state == "nomusic" { model.showMusic = true }
model.showPreview = false
if state == "why" { model.cameraExplained = false; model.showCameraWhy = true }
if ["study", "paused", "sleep", "settings", "break", "done", "nudge"].contains(state) {
if ["study", "paused", "sleep", "settings", "break", "done", "stopped", "nudge"].contains(state) {
model.start(withCamera: false) // no capture and no permission prompt; the card is told the camera runs
model.timerOnly = false
model.camera = .running
Expand All @@ -49,6 +49,7 @@ enum DebugWindow {
if state == "nudge" { model.nudgeText = Lines.random(for: .lowFocus) }
if state == "break" { model.clock.tick(at: t0.addingTimeInterval(25 * 60 + 1)); model.timeShift = 27 * 60 }
if state == "done" { model.clock.tick(at: t0.addingTimeInterval(24 * 3600)); model.nudges = 2 }
if state == "stopped" { model.stop(); model.nudges = 1 }
if state == "bubble" {
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
Bubble.show(Lines.random(for: .lowFocus), cat: model.timeOfDay.art.catFace)
Expand Down
59 changes: 59 additions & 0 deletions Sources/focus-check/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,60 @@ func zeroConfigIsClamped() {
check(clock.phase == .done)
}

func stopShowsRealStudiedTime() {
var clock = SessionClock()
let t0 = Date(timeIntervalSinceReferenceDate: 0)
clock.start(SessionConfig(studyMinutes: 25, breakMinutes: 5, rounds: 4), at: t0)
clock.pause(at: t0 + 5 * 60)
clock.resume(at: t0 + 15 * 60) // the 10 paused minutes do not count
clock.stop(at: t0 + 17 * 60)
check(clock.phase == .done && clock.stoppedIn == .study(round: 1))
check(clock.studied(at: t0 + 99 * 60) == 7 * 60)
check(!clock.isPaused && clock.remaining(at: t0 + 99 * 60) == 0)
}

func stopDuringBreakCountsOnlyStudy() {
var clock = SessionClock()
let t0 = Date(timeIntervalSinceReferenceDate: 0)
clock.start(SessionConfig(studyMinutes: 25, breakMinutes: 5, rounds: 4), at: t0)
clock.stop(at: t0 + 28 * 60)
check(clock.phase == .done && clock.stoppedIn == .rest(round: 1))
check(clock.studied(at: t0 + 28 * 60) == 25 * 60)
}

func fullSessionStudiedExcludesBreaks() {
var clock = SessionClock()
let t0 = Date(timeIntervalSinceReferenceDate: 0)
clock.start(SessionConfig(studyMinutes: 25, breakMinutes: 5, rounds: 2), at: t0)
check(clock.studied(at: t0 + 10 * 60) == 10 * 60)
clock.tick(at: t0 + 3 * 3600)
check(clock.phase == .done && clock.stoppedIn == nil)
check(clock.studied(at: t0 + 3 * 3600) == 50 * 60)
}

func stopRightAfterStartGoesIdle() {
var clock = SessionClock()
let t0 = Date(timeIntervalSinceReferenceDate: 0)
clock.start(SessionConfig(studyMinutes: 25, breakMinutes: 5, rounds: 4), at: t0)
clock.stop(at: t0 + 5)
check(clock.phase == .idle && clock.stoppedIn == nil && clock.studied(at: t0 + 5) == 0)
}

func undoStopCarriesOn() {
var clock = SessionClock()
let t0 = Date(timeIntervalSinceReferenceDate: 0)
clock.start(SessionConfig(studyMinutes: 25, breakMinutes: 5, rounds: 4), at: t0)
clock.stop(at: t0 + 17 * 60)
clock.undoStop(at: t0 + 30 * 60)
check(clock.phase == .study(round: 1) && clock.stoppedIn == nil)
check(clock.remaining(at: t0 + 30 * 60) == 8 * 60)
check(clock.studied(at: t0 + 32 * 60) == 19 * 60)
clock.tick(at: t0 + 38 * 60)
check(clock.phase == .rest(round: 1))
clock.reset()
check(clock.phase == .idle && clock.studied(at: t0 + 40 * 60) == 0)
}

func lcdDigitsAndText() {
check(SevenSegment.mask(8) == 0b1111111)
check(SevenSegment.mask(1) == 0b0000110)
Expand Down Expand Up @@ -340,6 +394,11 @@ let checks: [(String, () -> Void)] = [
("everyFourthBreakIsLong", everyFourthBreakIsLong),
("absenceRespectsCooldown", absenceRespectsCooldown),
("absentIsNotCountedBeforeFirstFace", absentIsNotCountedBeforeFirstFace),
("stopShowsRealStudiedTime", stopShowsRealStudiedTime),
("stopDuringBreakCountsOnlyStudy", stopDuringBreakCountsOnlyStudy),
("fullSessionStudiedExcludesBreaks", fullSessionStudiedExcludesBreaks),
("stopRightAfterStartGoesIdle", stopRightAfterStartGoesIdle),
("undoStopCarriesOn", undoStopCarriesOn),
]
for (name, body) in checks {
current = name
Expand Down
Loading