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;
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(
54 defaults: &Self::FileContent,
55 user_values: &[&Self::FileContent],
56 _: &mut AppContext,
57 ) -> Result<Self> {
58 Self::load_via_json_merge(defaults, user_values)
59 }
60}
61
62pub fn init(_: Arc<AppState>, cx: &mut AppContext) {
63 JournalSettings::register(cx);
64
65 cx.observe_new_views(
66 |workspace: &mut Workspace, _cx: &mut ViewContext<Workspace>| {
67 workspace.register_action(|workspace, _: &NewJournalEntry, cx| {
68 new_journal_entry(workspace.app_state().clone(), cx);
69 });
70 },
71 )
72 .detach();
73}
74
75pub fn new_journal_entry(app_state: Arc<AppState>, cx: &mut WindowContext) {
76 let settings = JournalSettings::get_global(cx);
77 let journal_dir = match journal_dir(settings.path.as_ref().unwrap()) {
78 Some(journal_dir) => journal_dir,
79 None => {
80 log::error!("Can't determine journal directory");
81 return;
82 }
83 };
84
85 let now = Local::now();
86 let month_dir = journal_dir
87 .join(format!("{:02}", now.year()))
88 .join(format!("{:02}", now.month()));
89 let entry_path = month_dir.join(format!("{:02}.md", now.day()));
90 let now = now.time();
91 let entry_heading = heading_entry(now, &settings.hour_format);
92
93 let create_entry = cx.background_executor().spawn(async move {
94 std::fs::create_dir_all(month_dir)?;
95 OpenOptions::new()
96 .create(true)
97 .truncate(false)
98 .write(true)
99 .open(&entry_path)?;
100 Ok::<_, std::io::Error>((journal_dir, entry_path))
101 });
102
103 cx.spawn(|mut cx| async move {
104 let (journal_dir, entry_path) = create_entry.await?;
105 let (workspace, _) = cx
106 .update(|cx| {
107 workspace::open_paths(
108 &[journal_dir],
109 app_state,
110 workspace::OpenOptions::default(),
111 cx,
112 )
113 })?
114 .await?;
115
116 let opened = workspace
117 .update(&mut cx, |workspace, cx| {
118 workspace.open_paths(vec![entry_path], OpenVisible::All, None, cx)
119 })?
120 .await;
121
122 if let Some(Some(Ok(item))) = opened.first() {
123 if let Some(editor) = item.downcast::<Editor>().map(|editor| editor.downgrade()) {
124 editor.update(&mut cx, |editor, cx| {
125 let len = editor.buffer().read(cx).len(cx);
126 editor.change_selections(Some(Autoscroll::center()), cx, |s| {
127 s.select_ranges([len..len])
128 });
129 if len > 0 {
130 editor.insert("\n\n", cx);
131 }
132 editor.insert(&entry_heading, cx);
133 editor.insert("\n\n", cx);
134 })?;
135 }
136 }
137
138 anyhow::Ok(())
139 })
140 .detach_and_log_err(cx);
141}
142
143fn journal_dir(path: &str) -> Option<PathBuf> {
144 let expanded_journal_dir = shellexpand::full(path) //TODO handle this better
145 .ok()
146 .map(|dir| Path::new(&dir.to_string()).to_path_buf().join("journal"));
147
148 return expanded_journal_dir;
149}
150
151fn heading_entry(now: NaiveTime, hour_format: &Option<HourFormat>) -> String {
152 match hour_format {
153 Some(HourFormat::Hour24) => {
154 let hour = now.hour();
155 format!("# {}:{:02}", hour, now.minute())
156 }
157 _ => {
158 let (pm, hour) = now.hour12();
159 let am_or_pm = if pm { "PM" } else { "AM" };
160 format!("# {}:{:02} {}", hour, now.minute(), am_or_pm)
161 }
162 }
163}
164
165#[cfg(test)]
166mod tests {
167 mod heading_entry_tests {
168 use super::super::*;
169
170 #[test]
171 fn test_heading_entry_defaults_to_hour_12() {
172 let naive_time = NaiveTime::from_hms_milli_opt(15, 0, 0, 0).unwrap();
173 let actual_heading_entry = heading_entry(naive_time, &None);
174 let expected_heading_entry = "# 3:00 PM";
175
176 assert_eq!(actual_heading_entry, expected_heading_entry);
177 }
178
179 #[test]
180 fn test_heading_entry_is_hour_12() {
181 let naive_time = NaiveTime::from_hms_milli_opt(15, 0, 0, 0).unwrap();
182 let actual_heading_entry = heading_entry(naive_time, &Some(HourFormat::Hour12));
183 let expected_heading_entry = "# 3:00 PM";
184
185 assert_eq!(actual_heading_entry, expected_heading_entry);
186 }
187
188 #[test]
189 fn test_heading_entry_is_hour_24() {
190 let naive_time = NaiveTime::from_hms_milli_opt(15, 0, 0, 0).unwrap();
191 let actual_heading_entry = heading_entry(naive_time, &Some(HourFormat::Hour24));
192 let expected_heading_entry = "# 15:00";
193
194 assert_eq!(actual_heading_entry, expected_heading_entry);
195 }
196 }
197}