journal.rs

  1use anyhow::Result;
  2use chrono::{Datelike, Local, NaiveTime, Timelike};
  3use editor::Editor;
  4use editor::scroll::Autoscroll;
  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(Some(Autoscroll::center()), window, cx, |s| {
172                            s.select_ranges([len..len])
173                        });
174                        if len > 0 {
175                            editor.insert("\n\n", window, cx);
176                        }
177                        editor.insert(&entry_heading, window, cx);
178                        editor.insert("\n\n", window, cx);
179                    })?;
180                }
181            }
182
183            anyhow::Ok(())
184        })
185        .detach_and_log_err(cx);
186}
187
188fn journal_dir(path: &str) -> Option<PathBuf> {
189    let expanded_journal_dir = shellexpand::full(path) //TODO handle this better
190        .ok()
191        .map(|dir| Path::new(&dir.to_string()).to_path_buf().join("journal"));
192
193    expanded_journal_dir
194}
195
196fn heading_entry(now: NaiveTime, hour_format: &Option<HourFormat>) -> String {
197    match hour_format {
198        Some(HourFormat::Hour24) => {
199            let hour = now.hour();
200            format!("# {}:{:02}", hour, now.minute())
201        }
202        _ => {
203            let (pm, hour) = now.hour12();
204            let am_or_pm = if pm { "PM" } else { "AM" };
205            format!("# {}:{:02} {}", hour, now.minute(), am_or_pm)
206        }
207    }
208}
209
210#[cfg(test)]
211mod tests {
212    mod heading_entry_tests {
213        use super::super::*;
214
215        #[test]
216        fn test_heading_entry_defaults_to_hour_12() {
217            let naive_time = NaiveTime::from_hms_milli_opt(15, 0, 0, 0).unwrap();
218            let actual_heading_entry = heading_entry(naive_time, &None);
219            let expected_heading_entry = "# 3:00 PM";
220
221            assert_eq!(actual_heading_entry, expected_heading_entry);
222        }
223
224        #[test]
225        fn test_heading_entry_is_hour_12() {
226            let naive_time = NaiveTime::from_hms_milli_opt(15, 0, 0, 0).unwrap();
227            let actual_heading_entry = heading_entry(naive_time, &Some(HourFormat::Hour12));
228            let expected_heading_entry = "# 3:00 PM";
229
230            assert_eq!(actual_heading_entry, expected_heading_entry);
231        }
232
233        #[test]
234        fn test_heading_entry_is_hour_24() {
235            let naive_time = NaiveTime::from_hms_milli_opt(15, 0, 0, 0).unwrap();
236            let actual_heading_entry = heading_entry(naive_time, &Some(HourFormat::Hour24));
237            let expected_heading_entry = "# 15:00";
238
239            assert_eq!(actual_heading_entry, expected_heading_entry);
240        }
241    }
242}