journal.rs

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