journal.rs

  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, OpenResult, 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 OpenResult {
111                    window: new_workspace,
112                    ..
113                } = cx
114                    .update(|_window, cx| {
115                        workspace::open_paths(
116                            &[journal_dir],
117                            app_state,
118                            workspace::OpenOptions::default(),
119                            cx,
120                        )
121                    })?
122                    .await?;
123                new_workspace
124                    .update(cx, |multi_workspace, window, cx| {
125                        let workspace = multi_workspace.workspace().clone();
126                        workspace.update(cx, |workspace, cx| {
127                            workspace.open_paths(
128                                vec![entry_path],
129                                workspace::OpenOptions {
130                                    visible: Some(OpenVisible::All),
131                                    ..Default::default()
132                                },
133                                None,
134                                window,
135                                cx,
136                            )
137                        })
138                    })?
139                    .await
140            } else {
141                view_snapshot
142                    .update_in(cx, |workspace, window, cx| {
143                        workspace.open_paths(
144                            vec![entry_path],
145                            workspace::OpenOptions {
146                                visible: Some(OpenVisible::All),
147                                ..Default::default()
148                            },
149                            None,
150                            window,
151                            cx,
152                        )
153                    })?
154                    .await
155            };
156
157            if let Some(Some(Ok(item))) = opened.first()
158                && let Some(editor) = item.downcast::<Editor>().map(|editor| editor.downgrade())
159            {
160                editor.update_in(cx, |editor, window, cx| {
161                    let len = editor.buffer().read(cx).len(cx);
162                    editor.change_selections(
163                        SelectionEffects::scroll(Autoscroll::center()),
164                        window,
165                        cx,
166                        |s| s.select_ranges([len..len]),
167                    );
168                    if len.0 > 0 {
169                        editor.insert("\n\n", window, cx);
170                    }
171                    editor.insert(&entry_heading, window, cx);
172                    editor.insert("\n\n", window, cx);
173                })?;
174            }
175
176            anyhow::Ok(())
177        })
178        .detach_and_log_err(cx);
179}
180
181fn journal_dir(path: &str) -> Option<PathBuf> {
182    let expanded = shellexpand::full(path).ok()?;
183    let base_path = Path::new(expanded.as_ref());
184    let absolute_path = if base_path.is_absolute() {
185        base_path.to_path_buf()
186    } else {
187        log::warn!("Invalid journal path {path:?} (not absolute), falling back to home directory",);
188        std::env::home_dir()?
189    };
190    Some(absolute_path.join("journal"))
191}
192
193fn heading_entry(now: NaiveTime, hour_format: &HourFormat) -> String {
194    match hour_format {
195        HourFormat::Hour24 => {
196            let hour = now.hour();
197            format!("# {}:{:02}", hour, now.minute())
198        }
199        HourFormat::Hour12 => {
200            let (pm, hour) = now.hour12();
201            let am_or_pm = if pm { "PM" } else { "AM" };
202            format!("# {}:{:02} {}", hour, now.minute(), am_or_pm)
203        }
204    }
205}
206
207#[cfg(test)]
208mod tests {
209    mod heading_entry_tests {
210        use super::super::*;
211
212        #[test]
213        fn test_heading_entry_defaults_to_hour_12() {
214            let naive_time = NaiveTime::from_hms_milli_opt(15, 0, 0, 0).unwrap();
215            let actual_heading_entry = heading_entry(naive_time, &HourFormat::Hour12);
216            let expected_heading_entry = "# 3:00 PM";
217
218            assert_eq!(actual_heading_entry, expected_heading_entry);
219        }
220
221        #[test]
222        fn test_heading_entry_is_hour_12() {
223            let naive_time = NaiveTime::from_hms_milli_opt(15, 0, 0, 0).unwrap();
224            let actual_heading_entry = heading_entry(naive_time, &HourFormat::Hour12);
225            let expected_heading_entry = "# 3:00 PM";
226
227            assert_eq!(actual_heading_entry, expected_heading_entry);
228        }
229
230        #[test]
231        fn test_heading_entry_is_hour_24() {
232            let naive_time = NaiveTime::from_hms_milli_opt(15, 0, 0, 0).unwrap();
233            let actual_heading_entry = heading_entry(naive_time, &HourFormat::Hour24);
234            let expected_heading_entry = "# 15:00";
235
236            assert_eq!(actual_heading_entry, expected_heading_entry);
237        }
238    }
239
240    mod journal_dir_tests {
241        use super::super::*;
242
243        #[test]
244        #[cfg(target_family = "unix")]
245        fn test_absolute_unix_path() {
246            let result = journal_dir("/home/user");
247            assert!(result.is_some());
248            let path = result.unwrap();
249            assert!(path.is_absolute());
250            assert_eq!(path, PathBuf::from("/home/user/journal"));
251        }
252
253        #[test]
254        fn test_tilde_expansion() {
255            let result = journal_dir("~/documents");
256            assert!(result.is_some());
257            let path = result.unwrap();
258
259            assert!(path.is_absolute(), "Tilde should expand to absolute path");
260
261            if let Some(home) = std::env::home_dir() {
262                assert_eq!(path, home.join("documents").join("journal"));
263            }
264        }
265
266        #[test]
267        fn test_relative_path_falls_back_to_home() {
268            for relative_path in ["relative/path", "NONEXT/some/path", "../some/path"] {
269                let result = journal_dir(relative_path);
270                assert!(result.is_some(), "Failed for path: {}", relative_path);
271                let path = result.unwrap();
272
273                assert!(
274                    path.is_absolute(),
275                    "Path should be absolute for input '{}', got: {:?}",
276                    relative_path,
277                    path
278                );
279
280                if let Some(home) = std::env::home_dir() {
281                    assert_eq!(
282                        path,
283                        home.join("journal"),
284                        "Should fall back to home directory for input '{}'",
285                        relative_path
286                    );
287                }
288            }
289        }
290
291        #[test]
292        #[cfg(target_os = "windows")]
293        fn test_absolute_path_windows_style() {
294            let result = journal_dir("C:\\Users\\user\\Documents");
295            assert!(result.is_some());
296            let path = result.unwrap();
297            assert_eq!(path, PathBuf::from("C:\\Users\\user\\Documents\\journal"));
298        }
299    }
300}