1use chrono::{Datelike, Local, NaiveTime, Timelike};
2use editor::scroll::Autoscroll;
3use editor::{Editor, SelectionEffects};
4use gpui::{App, AppContext as _, Context, Window, actions};
5pub use settings::HourFormat;
6use settings::{RegisterSetting, Settings};
7use std::{
8 fs::OpenOptions,
9 path::{Path, PathBuf},
10 sync::Arc,
11};
12use workspace::{AppState, OpenVisible, Workspace};
13
14actions!(
15 journal,
16 [
17 /// Creates a new journal entry for today.
18 NewJournalEntry
19 ]
20);
21
22/// Settings specific to journaling
23#[derive(Clone, Debug, RegisterSetting)]
24pub struct JournalSettings {
25 /// The path of the directory where journal entries are stored.
26 ///
27 /// Default: `~`
28 pub path: String,
29 /// What format to display the hours in.
30 ///
31 /// Default: hour12
32 pub hour_format: HourFormat,
33}
34
35impl settings::Settings for JournalSettings {
36 fn from_settings(content: &settings::SettingsContent) -> Self {
37 let journal = content.journal.clone().unwrap();
38
39 Self {
40 path: journal.path.unwrap(),
41 hour_format: journal.hour_format.unwrap(),
42 }
43 }
44}
45
46pub fn init(_: Arc<AppState>, cx: &mut App) {
47 cx.observe_new(
48 |workspace: &mut Workspace, _window, _cx: &mut Context<Workspace>| {
49 workspace.register_action(|workspace, _: &NewJournalEntry, window, cx| {
50 new_journal_entry(workspace, window, cx);
51 });
52 },
53 )
54 .detach();
55}
56
57pub fn new_journal_entry(workspace: &Workspace, window: &mut Window, cx: &mut App) {
58 let settings = JournalSettings::get_global(cx);
59 let journal_dir = match journal_dir(&settings.path) {
60 Some(journal_dir) => journal_dir,
61 None => {
62 log::error!("Can't determine journal directory");
63 return;
64 }
65 };
66 let journal_dir_clone = journal_dir.clone();
67
68 let now = Local::now();
69 let month_dir = journal_dir
70 .join(format!("{:02}", now.year()))
71 .join(format!("{:02}", now.month()));
72 let entry_path = month_dir.join(format!("{:02}.md", now.day()));
73 let now = now.time();
74 let entry_heading = heading_entry(now, &settings.hour_format);
75
76 let create_entry = cx.background_spawn(async move {
77 std::fs::create_dir_all(month_dir)?;
78 OpenOptions::new()
79 .create(true)
80 .truncate(false)
81 .write(true)
82 .open(&entry_path)?;
83 Ok::<_, std::io::Error>((journal_dir, entry_path))
84 });
85
86 let worktrees = workspace.visible_worktrees(cx).collect::<Vec<_>>();
87 let mut open_new_workspace = true;
88 'outer: for worktree in worktrees.iter() {
89 let worktree_root = worktree.read(cx).abs_path();
90 if *worktree_root == journal_dir_clone {
91 open_new_workspace = false;
92 break;
93 }
94 for directory in worktree.read(cx).directories(true, 1) {
95 let full_directory_path = worktree_root.join(directory.path.as_std_path());
96 if full_directory_path.ends_with(&journal_dir_clone) {
97 open_new_workspace = false;
98 break 'outer;
99 }
100 }
101 }
102
103 let app_state = workspace.app_state().clone();
104 let view_snapshot = workspace.weak_handle();
105
106 window
107 .spawn(cx, async move |cx| {
108 let (journal_dir, entry_path) = create_entry.await?;
109 let opened = if open_new_workspace {
110 let (new_workspace, _) = cx
111 .update(|_window, cx| {
112 workspace::open_paths(
113 &[journal_dir],
114 app_state,
115 workspace::OpenOptions::default(),
116 cx,
117 )
118 })?
119 .await?;
120 new_workspace
121 .update(cx, |multi_workspace, window, cx| {
122 let workspace = multi_workspace.workspace().clone();
123 workspace.update(cx, |workspace, cx| {
124 workspace.open_paths(
125 vec![entry_path],
126 workspace::OpenOptions {
127 visible: Some(OpenVisible::All),
128 ..Default::default()
129 },
130 None,
131 window,
132 cx,
133 )
134 })
135 })?
136 .await
137 } else {
138 view_snapshot
139 .update_in(cx, |workspace, window, cx| {
140 workspace.open_paths(
141 vec![entry_path],
142 workspace::OpenOptions {
143 visible: Some(OpenVisible::All),
144 ..Default::default()
145 },
146 None,
147 window,
148 cx,
149 )
150 })?
151 .await
152 };
153
154 if let Some(Some(Ok(item))) = opened.first()
155 && let Some(editor) = item.downcast::<Editor>().map(|editor| editor.downgrade())
156 {
157 editor.update_in(cx, |editor, window, cx| {
158 let len = editor.buffer().read(cx).len(cx);
159 editor.change_selections(
160 SelectionEffects::scroll(Autoscroll::center()),
161 window,
162 cx,
163 |s| s.select_ranges([len..len]),
164 );
165 if len.0 > 0 {
166 editor.insert("\n\n", window, cx);
167 }
168 editor.insert(&entry_heading, window, cx);
169 editor.insert("\n\n", window, cx);
170 })?;
171 }
172
173 anyhow::Ok(())
174 })
175 .detach_and_log_err(cx);
176}
177
178fn journal_dir(path: &str) -> Option<PathBuf> {
179 let expanded = shellexpand::full(path).ok()?;
180 let base_path = Path::new(expanded.as_ref());
181 let absolute_path = if base_path.is_absolute() {
182 base_path.to_path_buf()
183 } else {
184 log::warn!("Invalid journal path {path:?} (not absolute), falling back to home directory",);
185 std::env::home_dir()?
186 };
187 Some(absolute_path.join("journal"))
188}
189
190fn heading_entry(now: NaiveTime, hour_format: &HourFormat) -> String {
191 match hour_format {
192 HourFormat::Hour24 => {
193 let hour = now.hour();
194 format!("# {}:{:02}", hour, now.minute())
195 }
196 HourFormat::Hour12 => {
197 let (pm, hour) = now.hour12();
198 let am_or_pm = if pm { "PM" } else { "AM" };
199 format!("# {}:{:02} {}", hour, now.minute(), am_or_pm)
200 }
201 }
202}
203
204#[cfg(test)]
205mod tests {
206 mod heading_entry_tests {
207 use super::super::*;
208
209 #[test]
210 fn test_heading_entry_defaults_to_hour_12() {
211 let naive_time = NaiveTime::from_hms_milli_opt(15, 0, 0, 0).unwrap();
212 let actual_heading_entry = heading_entry(naive_time, &HourFormat::Hour12);
213 let expected_heading_entry = "# 3:00 PM";
214
215 assert_eq!(actual_heading_entry, expected_heading_entry);
216 }
217
218 #[test]
219 fn test_heading_entry_is_hour_12() {
220 let naive_time = NaiveTime::from_hms_milli_opt(15, 0, 0, 0).unwrap();
221 let actual_heading_entry = heading_entry(naive_time, &HourFormat::Hour12);
222 let expected_heading_entry = "# 3:00 PM";
223
224 assert_eq!(actual_heading_entry, expected_heading_entry);
225 }
226
227 #[test]
228 fn test_heading_entry_is_hour_24() {
229 let naive_time = NaiveTime::from_hms_milli_opt(15, 0, 0, 0).unwrap();
230 let actual_heading_entry = heading_entry(naive_time, &HourFormat::Hour24);
231 let expected_heading_entry = "# 15:00";
232
233 assert_eq!(actual_heading_entry, expected_heading_entry);
234 }
235 }
236
237 mod journal_dir_tests {
238 use super::super::*;
239
240 #[test]
241 #[cfg(target_family = "unix")]
242 fn test_absolute_unix_path() {
243 let result = journal_dir("/home/user");
244 assert!(result.is_some());
245 let path = result.unwrap();
246 assert!(path.is_absolute());
247 assert_eq!(path, PathBuf::from("/home/user/journal"));
248 }
249
250 #[test]
251 fn test_tilde_expansion() {
252 let result = journal_dir("~/documents");
253 assert!(result.is_some());
254 let path = result.unwrap();
255
256 assert!(path.is_absolute(), "Tilde should expand to absolute path");
257
258 if let Some(home) = std::env::home_dir() {
259 assert_eq!(path, home.join("documents").join("journal"));
260 }
261 }
262
263 #[test]
264 fn test_relative_path_falls_back_to_home() {
265 for relative_path in ["relative/path", "NONEXT/some/path", "../some/path"] {
266 let result = journal_dir(relative_path);
267 assert!(result.is_some(), "Failed for path: {}", relative_path);
268 let path = result.unwrap();
269
270 assert!(
271 path.is_absolute(),
272 "Path should be absolute for input '{}', got: {:?}",
273 relative_path,
274 path
275 );
276
277 if let Some(home) = std::env::home_dir() {
278 assert_eq!(
279 path,
280 home.join("journal"),
281 "Should fall back to home directory for input '{}'",
282 relative_path
283 );
284 }
285 }
286 }
287
288 #[test]
289 #[cfg(target_os = "windows")]
290 fn test_absolute_path_windows_style() {
291 let result = journal_dir("C:\\Users\\user\\Documents");
292 assert!(result.is_some());
293 let path = result.unwrap();
294 assert_eq!(path, PathBuf::from("C:\\Users\\user\\Documents\\journal"));
295 }
296 }
297}