journal.rs

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