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