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
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, async move |cx| {
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(cx, |workspace, window, cx| {
136 workspace.open_paths(
137 vec![entry_path],
138 workspace::OpenOptions {
139 visible: Some(OpenVisible::All),
140 ..Default::default()
141 },
142 None,
143 window,
144 cx,
145 )
146 })?
147 .await
148 } else {
149 view_snapshot
150 .update_in(cx, |workspace, window, cx| {
151 workspace.open_paths(
152 vec![entry_path],
153 workspace::OpenOptions {
154 visible: Some(OpenVisible::All),
155 ..Default::default()
156 },
157 None,
158 window,
159 cx,
160 )
161 })?
162 .await
163 };
164
165 if let Some(Some(Ok(item))) = opened.first() {
166 if let Some(editor) = item.downcast::<Editor>().map(|editor| editor.downgrade()) {
167 editor.update_in(cx, |editor, window, cx| {
168 let len = editor.buffer().read(cx).len(cx);
169 editor.change_selections(Some(Autoscroll::center()), window, cx, |s| {
170 s.select_ranges([len..len])
171 });
172 if len > 0 {
173 editor.insert("\n\n", window, cx);
174 }
175 editor.insert(&entry_heading, window, cx);
176 editor.insert("\n\n", window, cx);
177 })?;
178 }
179 }
180
181 anyhow::Ok(())
182 })
183 .detach_and_log_err(cx);
184}
185
186fn journal_dir(path: &str) -> Option<PathBuf> {
187 let expanded_journal_dir = shellexpand::full(path) //TODO handle this better
188 .ok()
189 .map(|dir| Path::new(&dir.to_string()).to_path_buf().join("journal"));
190
191 expanded_journal_dir
192}
193
194fn heading_entry(now: NaiveTime, hour_format: &Option<HourFormat>) -> String {
195 match hour_format {
196 Some(HourFormat::Hour24) => {
197 let hour = now.hour();
198 format!("# {}:{:02}", hour, now.minute())
199 }
200 _ => {
201 let (pm, hour) = now.hour12();
202 let am_or_pm = if pm { "PM" } else { "AM" };
203 format!("# {}:{:02} {}", hour, now.minute(), am_or_pm)
204 }
205 }
206}
207
208#[cfg(test)]
209mod tests {
210 mod heading_entry_tests {
211 use super::super::*;
212
213 #[test]
214 fn test_heading_entry_defaults_to_hour_12() {
215 let naive_time = NaiveTime::from_hms_milli_opt(15, 0, 0, 0).unwrap();
216 let actual_heading_entry = heading_entry(naive_time, &None);
217 let expected_heading_entry = "# 3:00 PM";
218
219 assert_eq!(actual_heading_entry, expected_heading_entry);
220 }
221
222 #[test]
223 fn test_heading_entry_is_hour_12() {
224 let naive_time = NaiveTime::from_hms_milli_opt(15, 0, 0, 0).unwrap();
225 let actual_heading_entry = heading_entry(naive_time, &Some(HourFormat::Hour12));
226 let expected_heading_entry = "# 3:00 PM";
227
228 assert_eq!(actual_heading_entry, expected_heading_entry);
229 }
230
231 #[test]
232 fn test_heading_entry_is_hour_24() {
233 let naive_time = NaiveTime::from_hms_milli_opt(15, 0, 0, 0).unwrap();
234 let actual_heading_entry = heading_entry(naive_time, &Some(HourFormat::Hour24));
235 let expected_heading_entry = "# 15:00";
236
237 assert_eq!(actual_heading_entry, expected_heading_entry);
238 }
239 }
240}