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    shellexpand::full(path) //TODO handle this better
177        .ok()
178        .map(|dir| Path::new(&dir.to_string()).to_path_buf().join("journal"))
179}
180
181fn heading_entry(now: NaiveTime, hour_format: &HourFormat) -> String {
182    match hour_format {
183        HourFormat::Hour24 => {
184            let hour = now.hour();
185            format!("# {}:{:02}", hour, now.minute())
186        }
187        HourFormat::Hour12 => {
188            let (pm, hour) = now.hour12();
189            let am_or_pm = if pm { "PM" } else { "AM" };
190            format!("# {}:{:02} {}", hour, now.minute(), am_or_pm)
191        }
192    }
193}
194
195#[cfg(test)]
196mod tests {
197    mod heading_entry_tests {
198        use super::super::*;
199
200        #[test]
201        fn test_heading_entry_defaults_to_hour_12() {
202            let naive_time = NaiveTime::from_hms_milli_opt(15, 0, 0, 0).unwrap();
203            let actual_heading_entry = heading_entry(naive_time, &HourFormat::Hour12);
204            let expected_heading_entry = "# 3:00 PM";
205
206            assert_eq!(actual_heading_entry, expected_heading_entry);
207        }
208
209        #[test]
210        fn test_heading_entry_is_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_24() {
220            let naive_time = NaiveTime::from_hms_milli_opt(15, 0, 0, 0).unwrap();
221            let actual_heading_entry = heading_entry(naive_time, &HourFormat::Hour24);
222            let expected_heading_entry = "# 15:00";
223
224            assert_eq!(actual_heading_entry, expected_heading_entry);
225        }
226    }
227}