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 .write(true)
98 .open(&entry_path)?;
99 Ok::<_, std::io::Error>((journal_dir, entry_path))
100 });
101
102 cx.spawn(|mut cx| async move {
103 let (journal_dir, entry_path) = create_entry.await?;
104 let (workspace, _) = cx
105 .update(|cx| {
106 workspace::open_paths(
107 &[journal_dir],
108 app_state,
109 workspace::OpenOptions::default(),
110 cx,
111 )
112 })?
113 .await?;
114
115 let opened = workspace
116 .update(&mut cx, |workspace, cx| {
117 workspace.open_paths(vec![entry_path], OpenVisible::All, None, cx)
118 })?
119 .await;
120
121 if let Some(Some(Ok(item))) = opened.first() {
122 if let Some(editor) = item.downcast::<Editor>().map(|editor| editor.downgrade()) {
123 editor.update(&mut cx, |editor, cx| {
124 let len = editor.buffer().read(cx).len(cx);
125 editor.change_selections(Some(Autoscroll::center()), cx, |s| {
126 s.select_ranges([len..len])
127 });
128 if len > 0 {
129 editor.insert("\n\n", cx);
130 }
131 editor.insert(&entry_heading, cx);
132 editor.insert("\n\n", cx);
133 })?;
134 }
135 }
136
137 anyhow::Ok(())
138 })
139 .detach_and_log_err(cx);
140}
141
142fn journal_dir(path: &str) -> Option<PathBuf> {
143 let expanded_journal_dir = shellexpand::full(path) //TODO handle this better
144 .ok()
145 .map(|dir| Path::new(&dir.to_string()).to_path_buf().join("journal"));
146
147 return expanded_journal_dir;
148}
149
150fn heading_entry(now: NaiveTime, hour_format: &Option<HourFormat>) -> String {
151 match hour_format {
152 Some(HourFormat::Hour24) => {
153 let hour = now.hour();
154 format!("# {}:{:02}", hour, now.minute())
155 }
156 _ => {
157 let (pm, hour) = now.hour12();
158 let am_or_pm = if pm { "PM" } else { "AM" };
159 format!("# {}:{:02} {}", hour, now.minute(), am_or_pm)
160 }
161 }
162}
163
164#[cfg(test)]
165mod tests {
166 mod heading_entry_tests {
167 use super::super::*;
168
169 #[test]
170 fn test_heading_entry_defaults_to_hour_12() {
171 let naive_time = NaiveTime::from_hms_milli_opt(15, 0, 0, 0).unwrap();
172 let actual_heading_entry = heading_entry(naive_time, &None);
173 let expected_heading_entry = "# 3:00 PM";
174
175 assert_eq!(actual_heading_entry, expected_heading_entry);
176 }
177
178 #[test]
179 fn test_heading_entry_is_hour_12() {
180 let naive_time = NaiveTime::from_hms_milli_opt(15, 0, 0, 0).unwrap();
181 let actual_heading_entry = heading_entry(naive_time, &Some(HourFormat::Hour12));
182 let expected_heading_entry = "# 3:00 PM";
183
184 assert_eq!(actual_heading_entry, expected_heading_entry);
185 }
186
187 #[test]
188 fn test_heading_entry_is_hour_24() {
189 let naive_time = NaiveTime::from_hms_milli_opt(15, 0, 0, 0).unwrap();
190 let actual_heading_entry = heading_entry(naive_time, &Some(HourFormat::Hour24));
191 let expected_heading_entry = "# 15:00";
192
193 assert_eq!(actual_heading_entry, expected_heading_entry);
194 }
195 }
196}