Compare commits
3
Commits
main
..
1d01c501ca
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1d01c501ca
|
||
|
|
619ca9e33e
|
||
|
|
b2603d74ee
|
@@ -65,6 +65,24 @@ cargo tauri build
|
||||
|
||||
`src-tauri/target/release/` 以下に配布用バイナリが生成されます。
|
||||
|
||||
### 日付時刻ライブラリと依存監査
|
||||
|
||||
日時処理は、RUSTSEC-2026-0543で保守停止が告知されたChronoではなくJiff 1.xを使用します。
|
||||
日常のローカル時刻、UTC表示、アラームの暦日計算はJiffが担当します。互換性維持のため、
|
||||
夏時間の重複時刻は早い方を選び、存在しない時刻は従来どおりcivil timeをUTCとして解釈する
|
||||
fallbackを使います。保存済みアラームJSONの形式は変更しません。
|
||||
|
||||
```bash
|
||||
cd src-tauri
|
||||
cargo tree --locked -i chrono # active dependencyは表示されないこと
|
||||
cargo audit --deny warnings
|
||||
```
|
||||
|
||||
Tauriが利用するcrateの非有効なoptional dependencyとして、`Cargo.lock`にChronoが残る場合があります。
|
||||
`cargo tree`でactive dependencyではないことを確認してください。`cargo audit`はlockfile単位で検査するため、
|
||||
この非有効なentryもRUSTSEC-2026-0543として報告します。Tauri/Linux GUI由来のその他の
|
||||
warning-class advisoryは [Issue #9](https://git.rumginger.org/kamat/tauclock/issues/9) で追跡します。
|
||||
|
||||
## ライセンス
|
||||
|
||||
MIT License. 詳細は `LICENSE` を参照してください。
|
||||
|
||||
Generated
+1186
-1632
File diff suppressed because it is too large
Load Diff
@@ -22,7 +22,7 @@ tauri = { version = "2", features = [] }
|
||||
tauri-plugin-opener = "2"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
chrono = "0.4.42"
|
||||
jiff = "1"
|
||||
tauri-plugin-log = "2"
|
||||
uuid = { version = "1", features = ["v4"] }
|
||||
dirs = "5"
|
||||
|
||||
+166
-40
@@ -1,6 +1,6 @@
|
||||
use chrono::{
|
||||
DateTime, Datelike, Days, Local, LocalResult, NaiveDate, NaiveDateTime, NaiveTime, TimeZone,
|
||||
Timelike, Utc,
|
||||
use jiff::{
|
||||
tz::{AmbiguousOffset, TimeZone},
|
||||
Timestamp, ZonedDateTime,
|
||||
};
|
||||
use log::{debug, error, info, trace, warn};
|
||||
use serde::{Deserialize, Serialize};
|
||||
@@ -24,14 +24,21 @@ const TIMER_MIN_MS: u64 = 1000;
|
||||
pub struct AppState {
|
||||
inner: Mutex<StateInner>,
|
||||
storage_path: PathBuf,
|
||||
time_zone: TimeZone,
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
/// Constructs a new state container and eagerly loads persisted alarms.
|
||||
pub fn new(storage_path: PathBuf) -> Self {
|
||||
Self::with_time_zone(storage_path, TimeZone::system())
|
||||
}
|
||||
|
||||
/// Constructs state using an explicit time zone. Production passes the
|
||||
/// operating system zone; tests can provide a named IANA zone.
|
||||
fn with_time_zone(storage_path: PathBuf, time_zone: TimeZone) -> Self {
|
||||
let mut inner = StateInner::default();
|
||||
if let Some(list) = load_alarms(&storage_path) {
|
||||
let now = Local::now();
|
||||
let now = now_in_time_zone(&time_zone);
|
||||
inner.alarms = list
|
||||
.into_iter()
|
||||
.map(|alarm| Alarm {
|
||||
@@ -48,6 +55,7 @@ impl AppState {
|
||||
Self {
|
||||
inner: Mutex::new(inner),
|
||||
storage_path,
|
||||
time_zone,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -116,15 +124,15 @@ impl AppState {
|
||||
/// snapshot generation, and persistence side effects.
|
||||
fn apply<F>(&self, mutator: F) -> FrontendState
|
||||
where
|
||||
F: FnOnce(&mut StateInner, i64, &DateTime<Local>),
|
||||
F: FnOnce(&mut StateInner, i64, &ZonedDateTime),
|
||||
{
|
||||
let now_local = Local::now();
|
||||
let now_ms = now_local.timestamp_millis();
|
||||
let now_local = now_in_time_zone(&self.time_zone);
|
||||
let now_ms = now_local.timestamp().as_millisecond();
|
||||
let mut guard = self.inner.lock().expect("state mutex poisoned");
|
||||
trace!("Running state mutation (now_ms={})", now_ms);
|
||||
mutator(&mut guard, now_ms, &now_local);
|
||||
guard.refresh(now_ms, &now_local);
|
||||
let snapshot = guard.to_frontend(&now_local);
|
||||
let snapshot = guard.build_frontend(&now_local);
|
||||
let persisted = if guard.alarms_dirty {
|
||||
Some(
|
||||
guard
|
||||
@@ -194,16 +202,16 @@ struct StateInner {
|
||||
|
||||
impl StateInner {
|
||||
/// Executes periodic tasks that should run on every mutation or tick.
|
||||
fn refresh(&mut self, now_ms: i64, now_local: &DateTime<Local>) {
|
||||
fn refresh(&mut self, now_ms: i64, now_local: &ZonedDateTime) {
|
||||
self.process_alarms(now_ms, now_local);
|
||||
self.update_timer(now_ms);
|
||||
self.expire_status(now_ms);
|
||||
}
|
||||
|
||||
/// Builds a full [`FrontendState`] representation of the current data.
|
||||
fn to_frontend(&mut self, now_local: &DateTime<Local>) -> FrontendState {
|
||||
let now_ms = now_local.timestamp_millis();
|
||||
let now_utc = now_local.with_timezone(&Utc);
|
||||
fn build_frontend(&mut self, now_local: &ZonedDateTime) -> FrontendState {
|
||||
let now_ms = now_local.timestamp().as_millisecond();
|
||||
let now_utc = now_local.timestamp().to_zoned_datetime(TimeZone::UTC);
|
||||
let clock = ClockState {
|
||||
local_time: format_time(now_local.hour(), now_local.minute(), now_local.second()),
|
||||
local_date: format_date(now_local.year(), now_local.month(), now_local.day()),
|
||||
@@ -231,7 +239,7 @@ impl StateInner {
|
||||
raw_time: &str,
|
||||
label: Option<&str>,
|
||||
now_ms: i64,
|
||||
now_local: &DateTime<Local>,
|
||||
now_local: &ZonedDateTime,
|
||||
) {
|
||||
let Some((hour, minute)) = parse_alarm_time(raw_time) else {
|
||||
warn!("Invalid alarm time input: {}", raw_time);
|
||||
@@ -261,7 +269,7 @@ impl StateInner {
|
||||
}
|
||||
|
||||
/// Toggles an alarm's active state and recalculates its next trigger.
|
||||
fn toggle_alarm(&mut self, id: &str, now_local: &DateTime<Local>) {
|
||||
fn toggle_alarm(&mut self, id: &str, now_local: &ZonedDateTime) {
|
||||
if let Some(alarm) = self.alarms.iter_mut().find(|alarm| alarm.id == id) {
|
||||
alarm.active = !alarm.active;
|
||||
alarm.ringing_until = None;
|
||||
@@ -412,7 +420,7 @@ impl StateInner {
|
||||
|
||||
/// Iterates configured alarms, triggering those scheduled for the current
|
||||
/// tick and scheduling their next activation.
|
||||
fn process_alarms(&mut self, now_ms: i64, now_local: &DateTime<Local>) {
|
||||
fn process_alarms(&mut self, now_ms: i64, now_local: &ZonedDateTime) {
|
||||
let mut triggered_labels = Vec::new();
|
||||
for alarm in &mut self.alarms {
|
||||
if let Some(until) = alarm.ringing_until {
|
||||
@@ -512,9 +520,7 @@ impl StateInner {
|
||||
|
||||
/// Builds the timer view model by formatting durations and button labels.
|
||||
fn build_timer_view(&self) -> TimerView {
|
||||
let display_ms = if self.timer.running {
|
||||
self.timer.remaining_ms
|
||||
} else if self.timer.remaining_ms > 0 {
|
||||
let display_ms = if self.timer.remaining_ms > 0 {
|
||||
self.timer.remaining_ms
|
||||
} else {
|
||||
self.timer.initial_ms
|
||||
@@ -733,12 +739,12 @@ fn load_alarms(path: &Path) -> Option<Vec<PersistedAlarm>> {
|
||||
}
|
||||
|
||||
/// Formats a timestamp as HH:MM:SS.
|
||||
fn format_time(hour: u32, minute: u32, second: u32) -> String {
|
||||
fn format_time(hour: i8, minute: i8, second: i8) -> String {
|
||||
format!("{:02}:{:02}:{:02}", hour, minute, second)
|
||||
}
|
||||
|
||||
/// Formats a date as YYYY-MM-DD.
|
||||
fn format_date(year: i32, month: u32, day: u32) -> String {
|
||||
fn format_date(year: i16, month: i8, day: i8) -> String {
|
||||
format!("{year:04}-{month:02}-{day:02}")
|
||||
}
|
||||
|
||||
@@ -768,7 +774,7 @@ fn format_relative(target_ms: i64, now_ms: i64) -> String {
|
||||
|
||||
/// Formats a duration for timer display, switching to HH:MM:SS when needed.
|
||||
fn format_duration(ms: u64) -> String {
|
||||
let total_seconds = (ms / 1000) as u64;
|
||||
let total_seconds = ms / 1000;
|
||||
let minutes = total_seconds / 60;
|
||||
let seconds = total_seconds % 60;
|
||||
let hundredths = (ms % 1000) / 10;
|
||||
@@ -870,27 +876,147 @@ fn parse_unit_duration(value: &str) -> Option<u64> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Calculates the next trigger timestamp in milliseconds for an alarm.
|
||||
fn resolve_next_trigger(hour: u8, minute: u8, now_local: &DateTime<Local>) -> i64 {
|
||||
let naive_time = NaiveTime::from_hms_opt(hour as u32, minute as u32, 0)
|
||||
.unwrap_or_else(|| NaiveTime::from_hms_opt(0, 0, 0).unwrap());
|
||||
let mut candidate = combine_local(now_local.date_naive(), naive_time);
|
||||
if candidate.timestamp_millis() <= now_local.timestamp_millis() {
|
||||
let next_day = now_local.date_naive() + Days::new(1);
|
||||
candidate = combine_local(next_day, naive_time);
|
||||
}
|
||||
candidate.timestamp_millis()
|
||||
/// Returns the current system instant expressed in the requested zone.
|
||||
fn now_in_time_zone(time_zone: &TimeZone) -> ZonedDateTime {
|
||||
Timestamp::now().to_zoned_datetime(time_zone.clone())
|
||||
}
|
||||
|
||||
/// Safely combines a date and time within the Local timezone, falling back to
|
||||
/// UTC if the local conversion is ambiguous or invalid.
|
||||
fn combine_local(date: NaiveDate, time: NaiveTime) -> DateTime<Local> {
|
||||
let naive = NaiveDateTime::new(date, time);
|
||||
match Local.from_local_datetime(&naive) {
|
||||
LocalResult::Single(value) => value,
|
||||
LocalResult::Ambiguous(first, _second) => first,
|
||||
LocalResult::None => {
|
||||
DateTime::<Utc>::from_naive_utc_and_offset(naive, Utc).with_timezone(&Local)
|
||||
/// Calculates the next trigger timestamp in milliseconds for an alarm while
|
||||
/// preserving the legacy local-time ambiguity policy. A fold selects the
|
||||
/// earlier occurrence. A gap interprets the nonexistent civil time as UTC
|
||||
/// before converting it back to the local zone.
|
||||
fn resolve_next_trigger(hour: u8, minute: u8, now_local: &ZonedDateTime) -> i64 {
|
||||
let time_zone = now_local.time_zone().clone();
|
||||
let mut candidate = combine_local(now_local.date(), hour, minute, &time_zone);
|
||||
if candidate.timestamp().as_millisecond() <= now_local.timestamp().as_millisecond() {
|
||||
candidate = combine_local(
|
||||
now_local
|
||||
.date()
|
||||
.tomorrow()
|
||||
.expect("tomorrow is representable"),
|
||||
hour,
|
||||
minute,
|
||||
&time_zone,
|
||||
);
|
||||
}
|
||||
candidate.timestamp().as_millisecond()
|
||||
}
|
||||
|
||||
fn combine_local(
|
||||
date: jiff::civil::Date,
|
||||
hour: u8,
|
||||
minute: u8,
|
||||
time_zone: &TimeZone,
|
||||
) -> ZonedDateTime {
|
||||
let civil = date.at(hour as i8, minute as i8, 0, 0);
|
||||
let ambiguous = time_zone.to_ambiguous_zoned_datetime(civil);
|
||||
if matches!(ambiguous.offset(), AmbiguousOffset::Gap { .. }) {
|
||||
return civil
|
||||
.to_zoned_datetime(TimeZone::UTC)
|
||||
.expect("alarm date is representable in UTC")
|
||||
.timestamp()
|
||||
.to_zoned_datetime(time_zone.clone());
|
||||
}
|
||||
ambiguous.compatible().expect("alarm date is representable")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn named_zone(name: &str) -> TimeZone {
|
||||
TimeZone::get(name).expect("named test time zone is available")
|
||||
}
|
||||
|
||||
fn zoned(instant: &str, time_zone: TimeZone) -> ZonedDateTime {
|
||||
instant
|
||||
.parse::<Timestamp>()
|
||||
.expect("valid test instant")
|
||||
.to_zoned_datetime(time_zone)
|
||||
}
|
||||
|
||||
fn milliseconds(instant: &str) -> i64 {
|
||||
instant
|
||||
.parse::<Timestamp>()
|
||||
.expect("valid expected instant")
|
||||
.as_millisecond()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn formats_clock_labels_without_changing_the_ui_contract() {
|
||||
assert_eq!(format_date(2026, 11, 20), "2026-11-20");
|
||||
assert_eq!(format_time(7, 5, 9), "07:05:09");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn production_state_can_be_configured_with_a_named_test_zone() {
|
||||
let app = AppState::with_time_zone(
|
||||
PathBuf::from("missing-test-alarms.json"),
|
||||
named_zone("Asia/Tokyo"),
|
||||
);
|
||||
assert_eq!(app.time_zone.iana_name(), Some("Asia/Tokyo"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn schedules_later_today_and_equal_time_tomorrow() {
|
||||
let utc = named_zone("UTC");
|
||||
let now = zoned("2024-01-15T09:30:00Z", utc.clone());
|
||||
assert_eq!(
|
||||
resolve_next_trigger(9, 31, &now),
|
||||
milliseconds("2024-01-15T09:31:00Z")
|
||||
);
|
||||
assert_eq!(
|
||||
resolve_next_trigger(9, 30, &now),
|
||||
milliseconds("2024-01-16T09:30:00Z")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_york_fold_uses_the_earlier_occurrence() {
|
||||
let new_york = named_zone("America/New_York");
|
||||
let now = zoned("2024-11-03T00:00:00Z", new_york);
|
||||
assert_eq!(
|
||||
resolve_next_trigger(1, 30, &now),
|
||||
milliseconds("2024-11-03T05:30:00Z")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_york_gap_preserves_the_legacy_utc_fallback() {
|
||||
let new_york = named_zone("America/New_York");
|
||||
let gap_date: jiff::civil::Date = "2024-03-10".parse().expect("valid date");
|
||||
assert_eq!(
|
||||
combine_local(gap_date, 2, 30, &new_york)
|
||||
.timestamp()
|
||||
.as_millisecond(),
|
||||
milliseconds("2024-03-10T02:30:00Z")
|
||||
);
|
||||
|
||||
let now = zoned("2024-03-10T05:00:00Z", new_york);
|
||||
assert_eq!(
|
||||
resolve_next_trigger(2, 30, &now),
|
||||
milliseconds("2024-03-11T06:30:00Z")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn next_alarm_advances_by_calendar_day_across_dst() {
|
||||
let new_york = named_zone("America/New_York");
|
||||
let now = zoned("2024-03-09T08:30:01Z", new_york);
|
||||
let trigger = resolve_next_trigger(3, 30, &now);
|
||||
assert_eq!(trigger, milliseconds("2024-03-10T07:30:00Z"));
|
||||
assert_eq!(trigger - now.timestamp().as_millisecond(), 82_799_000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn persisted_alarm_json_round_trips_without_schedule_fields() {
|
||||
let json =
|
||||
r#"{"alarms":[{"id":"wake","hour":7,"minute":30,"label":"Wake up","active":true}]}"#;
|
||||
let store: AlarmStore = serde_json::from_str(json).expect("stored alarm JSON parses");
|
||||
assert_eq!(store.alarms.len(), 1);
|
||||
assert_eq!(store.alarms[0].id, "wake");
|
||||
assert_eq!(store.alarms[0].hour, 7);
|
||||
assert_eq!(store.alarms[0].minute, 30);
|
||||
assert_eq!(serde_json::to_string(&store).unwrap(), json);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user