1use chrono::{Datelike, Local, NaiveTime, Timelike};
2use editor::scroll::Autoscroll;
3use editor::{Editor, SelectionEffects};
4use gpui::{App, AppContext as _, Context, Window, actions};
5pub use settings::HourFormat;
6use settings::Settings;
7use std::{
8 fs::OpenOptions,
9 path::{Path, PathBuf},
10 sync::Arc,
11};
12use workspace::{AppState, OpenVisible, Workspace};
13
14actions!(
15 journal,
16 [
17 /// Creates a new journal entry for today.
18 NewJournalEntry
19 ]
20);
21
22/// Settings specific to journaling
23#[derive(Clone, Debug)]
24pub struct JournalSettings {
25 /// The path of the directory where journal entries are stored.
26 ///
27 /// Default: `~`
28 pub path: String,
29 /// What format to display the hours in.
30 ///
31 /// Default: hour12
32 pub hour_format: HourFormat,
33}
34
35impl settings::Settings for JournalSettings {
36 fn from_settings(content: &settings::SettingsContent, _cx: &mut App) -> Self {
37 let journal = content.journal.clone().unwrap();
38
39 Self {
40 path: journal.path.unwrap(),
41 hour_format: journal.hour_format.unwrap(),
42 }
43 }
44}
45
46pub fn init(_: Arc<AppState>, cx: &mut App) {
47 JournalSettings::register(cx);
48
49 cx.observe_new(
50 |workspace: &mut Workspace, _window, _cx: &mut Context<Workspace>| {
51 workspace.register_action(|workspace, _: &NewJournalEntry, window, cx| {
52 new_journal_entry(workspace, window, cx);
53 });
54 },
55 )
56 .detach();
57}
58
59pub fn new_journal_entry(workspace: &Workspace, window: &mut Window, cx: &mut App) {
60 let settings = JournalSettings::get_global(cx);
61 let journal_dir = match journal_dir(&settings.path) {
62 Some(journal_dir) => journal_dir,
63 None => {
64 log::error!("Can't determine journal directory");
65 return;
66 }
67 };
68 let journal_dir_clone = journal_dir.clone();
69
70 let now = Local::now();
71 let month_dir = journal_dir
72 .join(format!("{:02}", now.year()))
73 .join(format!("{:02}", now.month()));
74 let entry_path = month_dir.join(format!("{:02}.md", now.day()));
75 let now = now.time();
76 let entry_heading = heading_entry(now, &settings.hour_format);
77
78 let create_entry = cx.background_spawn(async move {
79 std::fs::create_dir_all(month_dir)?;
80 OpenOptions::new()
81 .create(true)
82 .truncate(false)
83 .write(true)
84 .open(&entry_path)?;
85 Ok::<_, std::io::Error>((journal_dir, entry_path))
86 });
87
88 let worktrees = workspace.visible_worktrees(cx).collect::<Vec<_>>();
89 let mut open_new_workspace = true;
90 'outer: for worktree in worktrees.iter() {
91 let worktree_root = worktree.read(cx).abs_path();
92 if *worktree_root == journal_dir_clone {
93 open_new_workspace = false;
94 break;
95 }
96 for directory in worktree.read(cx).directories(true, 1) {
97 let full_directory_path = worktree_root.join(&directory.path);
98 if full_directory_path.ends_with(&journal_dir_clone) {
99 open_new_workspace = false;
100 break 'outer;
101 }
102 }
103 }
104
105 let app_state = workspace.app_state().clone();
106 let view_snapshot = workspace.weak_handle();
107
108 window
109 .spawn(cx, async move |cx| {
110 let (journal_dir, entry_path) = create_entry.await?;
111 let opened = if open_new_workspace {
112 let (new_workspace, _) = cx
113 .update(|_window, cx| {
114 workspace::open_paths(
115 &[journal_dir],
116 app_state,
117 workspace::OpenOptions::default(),
118 cx,
119 )
120 })?
121 .await?;
122 new_workspace
123 .update(cx, |workspace, window, cx| {
124 workspace.open_paths(
125 vec![entry_path],
126 workspace::OpenOptions {
127 visible: Some(OpenVisible::All),
128 ..Default::default()
129 },
130 None,
131 window,
132 cx,
133 )
134 })?
135 .await
136 } else {
137 view_snapshot
138 .update_in(cx, |workspace, window, cx| {
139 workspace.open_paths(
140 vec![entry_path],
141 workspace::OpenOptions {
142 visible: Some(OpenVisible::All),
143 ..Default::default()
144 },
145 None,
146 window,
147 cx,
148 )
149 })?
150 .await
151 };
152
153 if let Some(Some(Ok(item))) = opened.first()
154 && let Some(editor) = item.downcast::<Editor>().map(|editor| editor.downgrade())
155 {
156 editor.update_in(cx, |editor, window, cx| {
157 let len = editor.buffer().read(cx).len(cx);
158 editor.change_selections(
159 SelectionEffects::scroll(Autoscroll::center()),
160 window,
161 cx,
162 |s| s.select_ranges([len..len]),
163 );
164 if len > 0 {
165 editor.insert("\n\n", window, cx);
166 }
167 editor.insert(&entry_heading, window, cx);
168 editor.insert("\n\n", window, cx);
169 })?;
170 }
171
172 anyhow::Ok(())
173 })
174 .detach_and_log_err(cx);
175}
176
177fn journal_dir(path: &str) -> Option<PathBuf> {
178 shellexpand::full(path) //TODO handle this better
179 .ok()
180 .map(|dir| Path::new(&dir.to_string()).to_path_buf().join("journal"))
181}
182
183fn heading_entry(now: NaiveTime, hour_format: &HourFormat) -> String {
184 match hour_format {
185 HourFormat::Hour24 => {
186 let hour = now.hour();
187 format!("# {}:{:02}", hour, now.minute())
188 }
189 HourFormat::Hour12 => {
190 let (pm, hour) = now.hour12();
191 let am_or_pm = if pm { "PM" } else { "AM" };
192 format!("# {}:{:02} {}", hour, now.minute(), am_or_pm)
193 }
194 }
195}
196
197#[cfg(test)]
198mod tests {
199 mod heading_entry_tests {
200 use super::super::*;
201
202 #[test]
203 fn test_heading_entry_defaults_to_hour_12() {
204 let naive_time = NaiveTime::from_hms_milli_opt(15, 0, 0, 0).unwrap();
205 let actual_heading_entry = heading_entry(naive_time, &HourFormat::Hour12);
206 let expected_heading_entry = "# 3:00 PM";
207
208 assert_eq!(actual_heading_entry, expected_heading_entry);
209 }
210
211 #[test]
212 fn test_heading_entry_is_hour_12() {
213 let naive_time = NaiveTime::from_hms_milli_opt(15, 0, 0, 0).unwrap();
214 let actual_heading_entry = heading_entry(naive_time, &HourFormat::Hour12);
215 let expected_heading_entry = "# 3:00 PM";
216
217 assert_eq!(actual_heading_entry, expected_heading_entry);
218 }
219
220 #[test]
221 fn test_heading_entry_is_hour_24() {
222 let naive_time = NaiveTime::from_hms_milli_opt(15, 0, 0, 0).unwrap();
223 let actual_heading_entry = heading_entry(naive_time, &HourFormat::Hour24);
224 let expected_heading_entry = "# 15:00";
225
226 assert_eq!(actual_heading_entry, expected_heading_entry);
227 }
228 }
229}