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, 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    fn import_from_vscode(_vscode: &settings::VsCodeSettings, _current: &mut Self::FileContent) {}
 58}
 59
 60pub fn init(_: Arc<AppState>, cx: &mut App) {
 61    JournalSettings::register(cx);
 62
 63    cx.observe_new(
 64        |workspace: &mut Workspace, _window, _cx: &mut Context<Workspace>| {
 65            workspace.register_action(|workspace, _: &NewJournalEntry, window, cx| {
 66                new_journal_entry(workspace, window, cx);
 67            });
 68        },
 69    )
 70    .detach();
 71}
 72
 73pub fn new_journal_entry(workspace: &Workspace, window: &mut Window, cx: &mut App) {
 74    let settings = JournalSettings::get_global(cx);
 75    let journal_dir = match journal_dir(settings.path.as_ref().unwrap()) {
 76        Some(journal_dir) => journal_dir,
 77        None => {
 78            log::error!("Can't determine journal directory");
 79            return;
 80        }
 81    };
 82    let journal_dir_clone = journal_dir.clone();
 83
 84    let now = Local::now();
 85    let month_dir = journal_dir
 86        .join(format!("{:02}", now.year()))
 87        .join(format!("{:02}", now.month()));
 88    let entry_path = month_dir.join(format!("{:02}.md", now.day()));
 89    let now = now.time();
 90    let entry_heading = heading_entry(now, &settings.hour_format);
 91
 92    let create_entry = cx.background_spawn(async move {
 93        std::fs::create_dir_all(month_dir)?;
 94        OpenOptions::new()
 95            .create(true)
 96            .truncate(false)
 97            .write(true)
 98            .open(&entry_path)?;
 99        Ok::<_, std::io::Error>((journal_dir, entry_path))
100    });
101
102    let worktrees = workspace.visible_worktrees(cx).collect::<Vec<_>>();
103    let mut open_new_workspace = true;
104    'outer: for worktree in worktrees.iter() {
105        let worktree_root = worktree.read(cx).abs_path();
106        if *worktree_root == journal_dir_clone {
107            open_new_workspace = false;
108            break;
109        }
110        for directory in worktree.read(cx).directories(true, 1) {
111            let full_directory_path = worktree_root.join(&directory.path);
112            if full_directory_path.ends_with(&journal_dir_clone) {
113                open_new_workspace = false;
114                break 'outer;
115            }
116        }
117    }
118
119    let app_state = workspace.app_state().clone();
120    let view_snapshot = workspace.weak_handle().clone();
121
122    window
123        .spawn(cx, async move |cx| {
124            let (journal_dir, entry_path) = create_entry.await?;
125            let opened = if open_new_workspace {
126                let (new_workspace, _) = cx
127                    .update(|_window, cx| {
128                        workspace::open_paths(
129                            &[journal_dir],
130                            app_state,
131                            workspace::OpenOptions::default(),
132                            cx,
133                        )
134                    })?
135                    .await?;
136                new_workspace
137                    .update(cx, |workspace, window, cx| {
138                        workspace.open_paths(
139                            vec![entry_path],
140                            workspace::OpenOptions {
141                                visible: Some(OpenVisible::All),
142                                ..Default::default()
143                            },
144                            None,
145                            window,
146                            cx,
147                        )
148                    })?
149                    .await
150            } else {
151                view_snapshot
152                    .update_in(cx, |workspace, window, cx| {
153                        workspace.open_paths(
154                            vec![entry_path],
155                            workspace::OpenOptions {
156                                visible: Some(OpenVisible::All),
157                                ..Default::default()
158                            },
159                            None,
160                            window,
161                            cx,
162                        )
163                    })?
164                    .await
165            };
166
167            if let Some(Some(Ok(item))) = opened.first() {
168                if let Some(editor) = item.downcast::<Editor>().map(|editor| editor.downgrade()) {
169                    editor.update_in(cx, |editor, window, cx| {
170                        let len = editor.buffer().read(cx).len(cx);
171                        editor.change_selections(
172                            SelectionEffects::scroll(Autoscroll::center()),
173                            window,
174                            cx,
175                            |s| s.select_ranges([len..len]),
176                        );
177                        if len > 0 {
178                            editor.insert("\n\n", window, cx);
179                        }
180                        editor.insert(&entry_heading, window, cx);
181                        editor.insert("\n\n", window, cx);
182                    })?;
183                }
184            }
185
186            anyhow::Ok(())
187        })
188        .detach_and_log_err(cx);
189}
190
191fn journal_dir(path: &str) -> Option<PathBuf> {
192    let expanded_journal_dir = shellexpand::full(path) //TODO handle this better
193        .ok()
194        .map(|dir| Path::new(&dir.to_string()).to_path_buf().join("journal"));
195
196    expanded_journal_dir
197}
198
199fn heading_entry(now: NaiveTime, hour_format: &Option<HourFormat>) -> String {
200    match hour_format {
201        Some(HourFormat::Hour24) => {
202            let hour = now.hour();
203            format!("# {}:{:02}", hour, now.minute())
204        }
205        _ => {
206            let (pm, hour) = now.hour12();
207            let am_or_pm = if pm { "PM" } else { "AM" };
208            format!("# {}:{:02} {}", hour, now.minute(), am_or_pm)
209        }
210    }
211}
212
213#[cfg(test)]
214mod tests {
215    mod heading_entry_tests {
216        use super::super::*;
217
218        #[test]
219        fn test_heading_entry_defaults_to_hour_12() {
220            let naive_time = NaiveTime::from_hms_milli_opt(15, 0, 0, 0).unwrap();
221            let actual_heading_entry = heading_entry(naive_time, &None);
222            let expected_heading_entry = "# 3:00 PM";
223
224            assert_eq!(actual_heading_entry, expected_heading_entry);
225        }
226
227        #[test]
228        fn test_heading_entry_is_hour_12() {
229            let naive_time = NaiveTime::from_hms_milli_opt(15, 0, 0, 0).unwrap();
230            let actual_heading_entry = heading_entry(naive_time, &Some(HourFormat::Hour12));
231            let expected_heading_entry = "# 3:00 PM";
232
233            assert_eq!(actual_heading_entry, expected_heading_entry);
234        }
235
236        #[test]
237        fn test_heading_entry_is_hour_24() {
238            let naive_time = NaiveTime::from_hms_milli_opt(15, 0, 0, 0).unwrap();
239            let actual_heading_entry = heading_entry(naive_time, &Some(HourFormat::Hour24));
240            let expected_heading_entry = "# 15:00";
241
242            assert_eq!(actual_heading_entry, expected_heading_entry);
243        }
244    }
245}