Skip to content
Open
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
11 changes: 0 additions & 11 deletions Normal/App/AppContainer.swift
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import SwiftData
import SwiftUI

struct AppContainer: View {
@Query private var allSettings: [Settings]
@State private var screenTimeService: ScreenTimeService
@State private var timedUnblockService: TimedUnblockService
@State private var nfcService = NFCService.shared
Expand Down Expand Up @@ -40,14 +38,5 @@ struct AppContainer: View {
.environment(donationService)
.environment(usageLimitService)
.environment(unlockInbox)
.task { mirrorCustomDomainsEnabled() }
.onChange(of: allSettings.first?.enableCustomDomains ?? false) { _, enabled in
scheduleService.mirrorCustomDomainsEnabled(enabled)
screenTimeService.reconcile()
}
}

private func mirrorCustomDomainsEnabled() {
scheduleService.mirrorCustomDomainsEnabled(allSettings.first?.enableCustomDomains ?? false)
}
}
4 changes: 2 additions & 2 deletions Normal/App/AppServices.swift
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ final class AppServices {
timedUnblock = TimedUnblockService(
activityCenter: center,
sharedStore: store,
onExpiration: { screenTime.reconcile() }
onExpirationAt: { screenTime.reconcile(at: $0) }
)
schedule = ScheduleService(activityCenter: center, sharedStore: store)
appReview = AppReviewService(
Expand All @@ -50,7 +50,7 @@ final class AppServices {
} else {
let screenTime = ScreenTimeService()
self.screenTime = screenTime
timedUnblock = TimedUnblockService(onExpiration: { screenTime.reconcile() })
timedUnblock = TimedUnblockService(onExpirationAt: { screenTime.reconcile(at: $0) })
schedule = ScheduleService()
appReview = AppReviewService()
emergencyUnblock = EmergencyUnblockService(ledger: KeychainEmergencyUnblockLedger())
Expand Down
12 changes: 11 additions & 1 deletion Normal/App/ContentView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ struct ContentView: View {
@Query private var allSettings: [Settings]
@Query private var schedules: [BlockSchedule]
@Query private var usageLimits: [UsageLimit]
@Query private var selectedApps: [SelectedApps]

@State private var navigationCoordinator = NavigationCoordinator()

Expand Down Expand Up @@ -56,6 +57,7 @@ struct ContentView: View {
private func onAppear() {
if let settings {
emergencyUnblockService.reconcile(into: settings)
scheduleService.mirrorCustomDomainsEnabled(settings.enableCustomDomains)
}

timedUnblockService.reconcile(screenTimeService: screenTimeService)
Expand All @@ -73,12 +75,20 @@ struct ContentView: View {
}
}

private var mainSelectionConstraint: SelectionConstraint? {
selectedApps.first?.effectiveConstraint(customDomainsEnabled: settings?.enableCustomDomains ?? false)
}

/// Re-registers every `DeviceActivity` we depend on. Usage limits ride along
/// with schedules: their threshold events use `includesPastActivity`, so
/// re-registering mid-day cannot hand back an allowance already spent.
private func reregisterActivities() {
guard settings?.hasCompletedOnboarding == true else { return }
scheduleService.registerAll(schedules, screenTimeService: screenTimeService)
scheduleService.registerAll(
schedules,
screenTimeService: screenTimeService,
constrainedTo: mainSelectionConstraint
)
reregisterUsageLimits()
}

Expand Down
84 changes: 78 additions & 6 deletions Normal/Models/BlockSchedule.swift
Original file line number Diff line number Diff line change
Expand Up @@ -115,19 +115,91 @@ final class BlockSchedule: Identifiable {
)
}

func hasSameRules(as dto: ScheduleDTO) -> Bool {
func latestStart(atOrBefore date: Date, calendar: Calendar = .current) -> Date? {
ScheduleWindow.latestStart(
atOrBefore: date,
startHour: startHour,
startMinute: startMinute,
weekdays: weekdays,
calendar: calendar
)
}

struct Snapshot {
let name: String
let selection: FamilyActivitySelection
let startHour: Int
let startMinute: Int
let durationMinutes: Int
let weekdays: Set<Int>
let shouldBlock: Bool
let isTimed: Bool
let isEnabled: Bool
let customDomains: [String]

init(_ schedule: BlockSchedule) {
name = schedule.name
selection = schedule.selection
startHour = schedule.startHour
startMinute = schedule.startMinute
durationMinutes = schedule.durationMinutes
weekdays = schedule.weekdays
shouldBlock = schedule.shouldBlock
isTimed = schedule.isTimed
isEnabled = schedule.isEnabled
customDomains = schedule.customDomains
}

func restore(to schedule: BlockSchedule) {
schedule.name = name
schedule.selection = selection
schedule.startHour = startHour
schedule.startMinute = startMinute
schedule.durationMinutes = durationMinutes
schedule.weekdays = weekdays
schedule.shouldBlock = shouldBlock
schedule.isTimed = isTimed
schedule.isEnabled = isEnabled
schedule.customDomains = customDomains
}
}

func hasSameTimingAndMode(as dto: ScheduleDTO) -> Bool {
startHour == dto.startHour
&& startMinute == dto.startMinute
&& effectiveDurationMinutes == dto.durationMinutes
&& weekdays == dto.weekdays
&& shouldBlock == dto.shouldBlock
&& isTimed == dto.isTimed
&& customDomains == dto.customDomains
&& (try? FamilyActivitySelection.fromData(dto.selectionData)) == selection
}

func toDTO(activatedAt: Date? = nil) -> ScheduleDTO? {
guard let data = try? selection.toData() else { return nil }
func hasSameRules(
as dto: ScheduleDTO,
constrainedTo main: SelectionConstraint? = nil
) -> Bool {
let previousSelection = try? FamilyActivitySelection.fromData(dto.selectionData)
let effectiveSelection = main?.constrain(selection, previous: previousSelection) ?? selection
let effectiveDomains = main?.intersect(customDomains) ?? customDomains
return hasSameTimingAndMode(as: dto)
&& Set(effectiveDomains.compactMap(DomainNormalizer.normalize))
== Set(dto.customDomains.compactMap(DomainNormalizer.normalize))
&& previousSelection == effectiveSelection
}

func toDTO(
activatedAt: Date? = nil,
constrainedTo main: SelectionConstraint? = nil,
previousSelection: FamilyActivitySelection? = nil,
confirmedRemovals: FamilyActivitySelection? = nil
) -> ScheduleDTO? {
let effectiveSelection =
main?.constrain(
selection,
previous: previousSelection,
confirmedRemovals: confirmedRemovals
) ?? selection
let effectiveDomains = main?.intersect(customDomains) ?? customDomains
guard let data = try? effectiveSelection.toData() else { return nil }
return ScheduleDTO(
id: id,
name: name,
Expand All @@ -138,7 +210,7 @@ final class BlockSchedule: Identifiable {
weekdays: weekdays,
shouldBlock: shouldBlock,
isTimed: isTimed,
customDomains: customDomains,
customDomains: effectiveDomains,
isEnabled: isEnabled,
activatedAt: activatedAt
)
Expand Down
75 changes: 75 additions & 0 deletions Normal/Models/SelectionConstraint.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import FamilyControls
import Foundation

struct SelectionConstraint {
let selection: FamilyActivitySelection
let customDomains: [String]
let customDomainsEnabled: Bool

var effectiveCustomDomains: [String] {
customDomainsEnabled ? customDomains : []
}

func constrain(
_ otherSelection: FamilyActivitySelection,
previous: FamilyActivitySelection? = nil,
confirmedRemovals: FamilyActivitySelection? = nil
) -> FamilyActivitySelection {
var result = otherSelection
result.applicationTokens = Self.constrain(
otherSelection.applicationTokens,
main: selection.applicationTokens,
previous: previous?.applicationTokens,
confirmedRemovals: confirmedRemovals?.applicationTokens
)
result.webDomainTokens = Self.constrain(
otherSelection.webDomainTokens,
main: selection.webDomainTokens,
previous: previous?.webDomainTokens,
confirmedRemovals: confirmedRemovals?.webDomainTokens
)
result.categoryTokens = Self.constrain(
otherSelection.categoryTokens,
main: selection.categoryTokens,
previous: previous?.categoryTokens,
confirmedRemovals: confirmedRemovals?.categoryTokens
)
return result
}

func intersect(_ otherDomains: [String]) -> [String] {
CustomDomains.subset(otherDomains, of: effectiveCustomDomains)
}

func needsSync(selection otherSelection: FamilyActivitySelection, customDomains otherDomains: [String]) -> Bool {
if !otherSelection.isSubset(of: selection) {
return true
}
if customDomainsEnabled, CustomDomains.needsResync(otherDomains, main: customDomains) {
return true
}
return false
}

private static func constrain<T: Hashable>(
_ scheduleTokens: Set<T>,
main: Set<T>,
previous: Set<T>?,
confirmedRemovals: Set<T>?
) -> Set<T> {
guard !main.isEmpty else { return [] }
let baseline = previous.map { $0.intersection(scheduleTokens) } ?? []
let retained = confirmedRemovals.map { baseline.subtracting($0) } ?? baseline
return retained.union(scheduleTokens.intersection(main))
}
}

extension SelectedApps {
func effectiveConstraint(customDomainsEnabled: Bool) -> SelectionConstraint {
SelectionConstraint(
selection: selection,
customDomains: customDomains,
customDomainsEnabled: customDomainsEnabled
)
}
}
10 changes: 10 additions & 0 deletions Normal/Modifiers/LiveActivitySync.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,23 @@ private struct LiveActivitySyncModifier: ViewModifier {
@Query(sort: [SortDescriptor(\AppGroup.sortIndex)]) private var groups: [AppGroup]
@Query private var settingsRows: [Settings]

private struct GroupTitle: Equatable {
let id: UUID
let name: String
}

private var liveActivityEnabled: Bool {
settingsRows.first?.showTimedUnblockLiveActivity ?? true
}

private var groupTitles: [GroupTitle] {
groups.map { GroupTitle(id: $0.id, name: $0.name) }
}

func body(content: Content) -> some View {
content
.onChange(of: timedUnblockService.activeUnblocks) { _, _ in reconcile() }
.onChange(of: groupTitles) { _, _ in reconcile() }
.onChange(of: liveActivityEnabled) { _, _ in reconcile() }
.onAppear { reconcile() }
}
Expand Down
18 changes: 17 additions & 1 deletion Normal/Modifiers/WidgetActionResponder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,25 @@ private struct WidgetActionResponder: ViewModifier {
let keyType: KeyType?
}

private struct GroupSnapshot: Equatable {
let id: UUID
let name: String
let sortIndex: Int
let lastUpdated: Date
}

private var unblockDurations: [TimedUnblockDuration] {
allSettings.first?.unblockDurations ?? TimedUnblockDuration.presets
}

private var groupsFingerprint: [GroupSnapshot] {
groups.map { GroupSnapshot(id: $0.id, name: $0.name, sortIndex: $0.sortIndex, lastUpdated: $0.lastUpdated) }
}

private var customDomainsEnabled: Bool {
allSettings.first?.enableCustomDomains ?? false
}

func body(content: Content) -> some View {
content
.protectedAction(
Expand All @@ -47,7 +62,8 @@ private struct WidgetActionResponder: ViewModifier {
.onChange(of: unlockInbox.pending, initial: true) { _, _ in takeInboxRequest() }
.onChange(of: scenePhase) { _, _ in takeInboxRequest() }
.onChange(of: screenTimeService.authorizationState) { _, _ in takeInboxRequest() }
.onChange(of: groups) { _, _ in syncGroups() }
.onChange(of: groupsFingerprint) { _, _ in syncGroups() }
.onChange(of: customDomainsEnabled) { _, _ in syncGroups() }
.onChange(of: keys) { _, _ in syncWidget() }
.onChange(of: screenTimeService.lastUpdate) { _, _ in syncWidget() }
.onChange(of: unblockDurations) { _, _ in syncWidget() }
Expand Down
18 changes: 18 additions & 0 deletions Normal/Resources/Localizable.xcstrings
Original file line number Diff line number Diff line change
Expand Up @@ -587,6 +587,9 @@
"Couldn't confirm your location. Open Normal to check it?" : {
"comment" : "Text displayed in a notification when a timed unblock is already running for all apps.",
"isCommentAutoGenerated" : true
},
"Couldn't Save Selection" : {

},
"Couldn't start the unblock. Open Normal and try again." : {
"comment" : "Error when unblocking an app fails.",
Expand All @@ -595,6 +598,15 @@
"Couldn't Unblock" : {
"comment" : "Title of an alert shown when an unblock with the default duration fails.",
"isCommentAutoGenerated" : true
},
"Couldn't update blocking state right now. Please try again." : {

},
"Couldn't update this schedule right now. Please try again." : {

},
"Couldn't update your selection right now. Please try again." : {

},
"Create a schedule to automatically block or unblock apps at set times." : {
"comment" : "A footer message in the Schedules view that instructs the user on how to create schedules.",
Expand Down Expand Up @@ -826,6 +838,9 @@
"Getting one" : {
"comment" : "A subheading within the \"Where to place them\" card, explaining how to get a QR code or barcode.",
"isCommentAutoGenerated" : true
},
"Global keys can be deleted in the Keys tab." : {

},
"Go to App Select to choose which apps to manage before creating schedules." : {

Expand Down Expand Up @@ -1386,6 +1401,9 @@
"Schedule" : {
"comment" : "The title of the view that lists schedules.",
"isCommentAutoGenerated" : true
},
"Schedule Notice" : {

},
"Schedules" : {
"comment" : "The title of the screen where users can view and manage their schedules.",
Expand Down
Loading