journal.rs

  1use anyhow::Result;
  2use chrono::{Datelike, Local, NaiveTime, Timelike};
  3use editor::scroll::Autoscroll;
  4use editor::Editor;
  5use gpui::{actions, App, AppContext as _, Context, Window};
  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 App) -> Result<Self> {
 54        sources.json_merge()
 55    }
 56}
 57
 58pub fn init(_: Arc<AppState>, cx: &mut App) {
 59    JournalSettings::register(cx);
 60
 61    cx.observe_new(
 62        |workspace: &mut Workspace, _window, _cx: &mut Context<Workspace>| {
 63            workspace.register_action(|workspace, _: &NewJournalEntry, window, cx| {
 64                new_journal_entry(workspace, window, cx);
 65            });
 66        },
 67    )
 68    .detach();
 69}
 70
 71pub fn new_journal_entry(workspace: &Workspace, window: &mut Window, cx: &mut App) {
 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_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    window
121        .spawn(cx, |mut cx| async move {
122            let (journal_dir, entry_path) = create_entry.await?;
123            let opened = if open_new_workspace {
124                let (new_workspace, _) = cx
125                    .update(|_window, cx| {
126                        workspace::open_paths(
127                            &[journal_dir],
128                            app_state,
129                            workspace::OpenOptions::default(),
130                            cx,
131                        )
132                    })?
133                    .await?;
134                new_workspace
135                    .update(&mut cx, |workspace, window, cx| {
136                        workspace.open_paths(vec![entry_path], OpenVisible::All, None, window, cx)
137                    })?
138                    .await
139            } else {
140                view_snapshot
141                    .update_in(&mut cx, |workspace, window, cx| {
142                        workspace.open_paths(vec![entry_path], OpenVisible::All, None, window, cx)
143                    })?
144                    .await
145            };
146
147            if let Some(Some(Ok(item))) = opened.first() {
148                if let Some(editor) = item.downcast::<Editor>().map(|editor| editor.downgrade()) {
149                    editor.update_in(&mut cx, |editor, window, cx| {
150                        let len = editor.buffer().read(cx).len(cx);
151                        editor.change_selections(Some(Autoscroll::center()), window, cx, |s| {
152                            s.select_ranges([len..len])
153                        });
154                        if len > 0 {
155                            editor.insert("\n\n", window, cx);
156                        }
157                        editor.insert(&entry_heading, window, cx);
158                        editor.insert("\n\n", window, cx);
159                    })?;
160                }
161            }
162
163            anyhow::Ok(())
164        })
165        .detach_and_log_err(cx);
166}
167
168fn journal_dir(path: &str) -> Option<PathBuf> {
169    let expanded_journal_dir = shellexpand::full(path) //TODO handle this better
170        .ok()
171        .map(|dir| Path::new(&dir.to_string()).to_path_buf().join("journal"));
172
173    expanded_journal_dir
174}
175
176fn heading_entry(now: NaiveTime, hour_format: &Option<HourFormat>) -> String {
177    match hour_format {
178        Some(HourFormat::Hour24) => {
179            let hour = now.hour();
180            format!("# {}:{:02}", hour, now.minute())
181        }
182        _ => {
183            let (pm, hour) = now.hour12();
184            let am_or_pm = if pm { "PM" } else { "AM" };
185            format!("# {}:{:02} {}", hour, now.minute(), am_or_pm)
186        }
187    }
188}
189
190#[cfg(test)]
191mod tests {
192    mod heading_entry_tests {
193        use super::super::*;
194
195        #[test]
196        fn test_heading_entry_defaults_to_hour_12() {
197            let naive_time = NaiveTime::from_hms_milli_opt(15, 0, 0, 0).unwrap();
198            let actual_heading_entry = heading_entry(naive_time, &None);
199            let expected_heading_entry = "# 3:00 PM";
200
201            assert_eq!(actual_heading_entry, expected_heading_entry);
202        }
203
204        #[test]
205        fn test_heading_entry_is_hour_12() {
206            let naive_time = NaiveTime::from_hms_milli_opt(15, 0, 0, 0).unwrap();
207            let actual_heading_entry = heading_entry(naive_time, &Some(HourFormat::Hour12));
208            let expected_heading_entry = "# 3:00 PM";
209
210            assert_eq!(actual_heading_entry, expected_heading_entry);
211        }
212
213        #[test]
214        fn test_heading_entry_is_hour_24() {
215            let naive_time = NaiveTime::from_hms_milli_opt(15, 0, 0, 0).unwrap();
216            let actual_heading_entry = heading_entry(naive_time, &Some(HourFormat::Hour24));
217            let expected_heading_entry = "# 15:00";
218
219            assert_eq!(actual_heading_entry, expected_heading_entry);
220        }
221    }
222}