1use anyhow::Result;
2use chrono::{Datelike, Local, NaiveTime, Timelike};
3use editor::scroll::Autoscroll;
4use editor::Editor;
5use gpui::{actions, AppContext, ViewContext, WindowContext};
6use schemars::JsonSchema;
7use serde::{Deserialize, Serialize};
8use settings::Settings;
9use std::{
10 fs::OpenOptions,
11 path::{Path, PathBuf},
12 sync::Arc,
13};
14use workspace::{AppState, OpenVisible, Workspace};
15
16actions!(journal, [NewJournalEntry]);
17
18/// Settings specific to journaling
19#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
20pub struct JournalSettings {
21 /// The path of the directory where journal entries are stored.
22 ///
23 /// Default: `~`
24 pub path: Option<String>,
25 /// What format to display the hours in.
26 ///
27 /// Default: hour12
28 pub hour_format: Option<HourFormat>,
29}
30
31impl Default for JournalSettings {
32 fn default() -> Self {
33 Self {
34 path: Some("~".into()),
35 hour_format: Some(Default::default()),
36 }
37 }
38}
39
40#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
41#[serde(rename_all = "snake_case")]
42pub enum HourFormat {
43 #[default]
44 Hour12,
45 Hour24,
46}
47
48impl settings::Settings for JournalSettings {
49 const KEY: Option<&'static str> = Some("journal");
50
51 type FileContent = Self;
52
53 fn load(
54 defaults: &Self::FileContent,
55 user_values: &[&Self::FileContent],
56 _: &mut AppContext,
57 ) -> Result<Self> {
58 Self::load_via_json_merge(defaults, user_values)
59 }
60}
61
62pub fn init(_: Arc<AppState>, cx: &mut AppContext) {
63 JournalSettings::register(cx);
64
65 cx.observe_new_views(
66 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
67 workspace.register_action(|workspace, _: &NewJournalEntry, cx| {
68 new_journal_entry(workspace.app_state().clone(), cx);
69 });
70 },
71 )
72 .detach();
73}
74
75pub fn new_journal_entry(app_state: Arc<AppState>, cx: &mut WindowContext) {
76 let settings = JournalSettings::get_global(cx);
77 let journal_dir = match journal_dir(settings.path.as_ref().unwrap()) {
78 Some(journal_dir) => journal_dir,
79 None => {
80 log::error!("Can't determine journal directory");
81 return;
82 }
83 };
84
85 let now = Local::now();
86 let month_dir = journal_dir
87 .join(format!("{:02}", now.year()))
88 .join(format!("{:02}", now.month()));
89 let entry_path = month_dir.join(format!("{:02}.md", now.day()));
90 let now = now.time();
91 let entry_heading = heading_entry(now, &settings.hour_format);
92
93 let create_entry = cx.background_executor().spawn(async move {
94 std::fs::create_dir_all(month_dir)?;
95 OpenOptions::new()
96 .create(true)
97 .write(true)
98 .open(&entry_path)?;
99 Ok::<_, std::io::Error>((journal_dir, entry_path))
100 });
101
102 cx.spawn(|mut cx| async move {
103 let (journal_dir, entry_path) = create_entry.await?;
104 let (workspace, _) = cx
105 .update(|cx| workspace::open_paths(&[journal_dir], app_state, None, cx))?
106 .await?;
107
108 let opened = workspace
109 .update(&mut cx, |workspace, cx| {
110 workspace.open_paths(vec![entry_path], OpenVisible::All, None, cx)
111 })?
112 .await;
113
114 if let Some(Some(Ok(item))) = opened.first() {
115 if let Some(editor) = item.downcast::<Editor>().map(|editor| editor.downgrade()) {
116 editor.update(&mut cx, |editor, cx| {
117 let len = editor.buffer().read(cx).len(cx);
118 editor.change_selections(Some(Autoscroll::center()), cx, |s| {
119 s.select_ranges([len..len])
120 });
121 if len > 0 {
122 editor.insert("\n\n", cx);
123 }
124 editor.insert(&entry_heading, cx);
125 editor.insert("\n\n", cx);
126 })?;
127 }
128 }
129
130 anyhow::Ok(())
131 })
132 .detach_and_log_err(cx);
133}
134
135fn journal_dir(path: &str) -> Option<PathBuf> {
136 let expanded_journal_dir = shellexpand::full(path) //TODO handle this better
137 .ok()
138 .map(|dir| Path::new(&dir.to_string()).to_path_buf().join("journal"));
139
140 return expanded_journal_dir;
141}
142
143fn heading_entry(now: NaiveTime, hour_format: &Option<HourFormat>) -> String {
144 match hour_format {
145 Some(HourFormat::Hour24) => {
146 let hour = now.hour();
147 format!("# {}:{:02}", hour, now.minute())
148 }
149 _ => {
150 let (pm, hour) = now.hour12();
151 let am_or_pm = if pm { "PM" } else { "AM" };
152 format!("# {}:{:02} {}", hour, now.minute(), am_or_pm)
153 }
154 }
155}
156
157#[cfg(test)]
158mod tests {
159 mod heading_entry_tests {
160 use super::super::*;
161
162 #[test]
163 fn test_heading_entry_defaults_to_hour_12() {
164 let naive_time = NaiveTime::from_hms_milli_opt(15, 0, 0, 0).unwrap();
165 let actual_heading_entry = heading_entry(naive_time, &None);
166 let expected_heading_entry = "# 3:00 PM";
167
168 assert_eq!(actual_heading_entry, expected_heading_entry);
169 }
170
171 #[test]
172 fn test_heading_entry_is_hour_12() {
173 let naive_time = NaiveTime::from_hms_milli_opt(15, 0, 0, 0).unwrap();
174 let actual_heading_entry = heading_entry(naive_time, &Some(HourFormat::Hour12));
175 let expected_heading_entry = "# 3:00 PM";
176
177 assert_eq!(actual_heading_entry, expected_heading_entry);
178 }
179
180 #[test]
181 fn test_heading_entry_is_hour_24() {
182 let naive_time = NaiveTime::from_hms_milli_opt(15, 0, 0, 0).unwrap();
183 let actual_heading_entry = heading_entry(naive_time, &Some(HourFormat::Hour24));
184 let expected_heading_entry = "# 15:00";
185
186 assert_eq!(actual_heading_entry, expected_heading_entry);
187 }
188 }
189}