Merge branch 'main' into gpui-events

This commit is contained in:
Mikayla Maki 2022-10-17 15:43:41 -07:00 committed by GitHub
commit 5ef5147780
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
13 changed files with 346 additions and 201 deletions

2
Cargo.lock generated
View file

@ -2946,6 +2946,8 @@ dependencies = [
"editor", "editor",
"gpui", "gpui",
"log", "log",
"settings",
"shellexpand",
"util", "util",
"workspace", "workspace",
] ]

View file

@ -83,6 +83,16 @@
// "git_gutter": "hide" // "git_gutter": "hide"
"git_gutter": "tracked_files" "git_gutter": "tracked_files"
}, },
// Settings specific to journaling
"journal": {
// The path of the directory where journal entries are stored
"path": "~",
// What format to display the hours in
// May take 2 values:
// 1. hour12
// 2. hour24
"hour_format": "hour12"
},
// Settings specific to the terminal // Settings specific to the terminal
"terminal": { "terminal": {
// What shell to use when opening a terminal. May take 3 values: // What shell to use when opening a terminal. May take 3 values:

View file

@ -46,6 +46,7 @@ impl ActivityIndicator {
cx: &mut ViewContext<Workspace>, cx: &mut ViewContext<Workspace>,
) -> ViewHandle<ActivityIndicator> { ) -> ViewHandle<ActivityIndicator> {
let project = workspace.project().clone(); let project = workspace.project().clone();
let auto_updater = AutoUpdater::get(cx);
let this = cx.add_view(|cx: &mut ViewContext<Self>| { let this = cx.add_view(|cx: &mut ViewContext<Self>| {
let mut status_events = languages.language_server_binary_statuses(); let mut status_events = languages.language_server_binary_statuses();
cx.spawn_weak(|this, mut cx| async move { cx.spawn_weak(|this, mut cx| async move {
@ -66,11 +67,14 @@ impl ActivityIndicator {
}) })
.detach(); .detach();
cx.observe(&project, |_, _, cx| cx.notify()).detach(); cx.observe(&project, |_, _, cx| cx.notify()).detach();
if let Some(auto_updater) = auto_updater.as_ref() {
cx.observe(auto_updater, |_, _, cx| cx.notify()).detach();
}
Self { Self {
statuses: Default::default(), statuses: Default::default(),
project: project.clone(), project: project.clone(),
auto_updater: AutoUpdater::get(cx), auto_updater,
} }
}); });
cx.subscribe(&this, move |workspace, _, event, cx| match event { cx.subscribe(&this, move |workspace, _, event, cx| match event {

View file

@ -157,6 +157,7 @@ pub struct BlockChunks<'a> {
max_output_row: u32, max_output_row: u32,
} }
#[derive(Clone)]
pub struct BlockBufferRows<'a> { pub struct BlockBufferRows<'a> {
transforms: sum_tree::Cursor<'a, Transform, (BlockRow, WrapRow)>, transforms: sum_tree::Cursor<'a, Transform, (BlockRow, WrapRow)>,
input_buffer_rows: wrap_map::WrapBufferRows<'a>, input_buffer_rows: wrap_map::WrapBufferRows<'a>,

View file

@ -987,6 +987,7 @@ impl<'a> sum_tree::Dimension<'a, FoldSummary> for usize {
} }
} }
#[derive(Clone)]
pub struct FoldBufferRows<'a> { pub struct FoldBufferRows<'a> {
cursor: Cursor<'a, Transform, (FoldPoint, Point)>, cursor: Cursor<'a, Transform, (FoldPoint, Point)>,
input_buffer_rows: MultiBufferRows<'a>, input_buffer_rows: MultiBufferRows<'a>,

View file

@ -62,6 +62,7 @@ pub struct WrapChunks<'a> {
transforms: Cursor<'a, Transform, (WrapPoint, TabPoint)>, transforms: Cursor<'a, Transform, (WrapPoint, TabPoint)>,
} }
#[derive(Clone)]
pub struct WrapBufferRows<'a> { pub struct WrapBufferRows<'a> {
input_buffer_rows: fold_map::FoldBufferRows<'a>, input_buffer_rows: fold_map::FoldBufferRows<'a>,
input_buffer_row: Option<u32>, input_buffer_row: Option<u32>,

View file

@ -12,11 +12,11 @@ use crate::{
GoToFetchedDefinition, GoToFetchedTypeDefinition, UpdateGoToDefinitionLink, GoToFetchedDefinition, GoToFetchedTypeDefinition, UpdateGoToDefinitionLink,
}, },
mouse_context_menu::DeployMouseContextMenu, mouse_context_menu::DeployMouseContextMenu,
EditorStyle, AnchorRangeExt, EditorStyle,
}; };
use clock::ReplicaId; use clock::ReplicaId;
use collections::{BTreeMap, HashMap}; use collections::{BTreeMap, HashMap};
use git::diff::{DiffHunk, DiffHunkStatus}; use git::diff::DiffHunkStatus;
use gpui::{ use gpui::{
color::Color, color::Color,
elements::*, elements::*,
@ -34,7 +34,7 @@ use gpui::{
Quad, Scene, SizeConstraint, ViewContext, WeakViewHandle, Quad, Scene, SizeConstraint, ViewContext, WeakViewHandle,
}; };
use json::json; use json::json;
use language::{Bias, DiagnosticSeverity, OffsetUtf16, Selection}; use language::{Bias, DiagnosticSeverity, OffsetUtf16, Point, Selection};
use project::ProjectPath; use project::ProjectPath;
use settings::{GitGutter, Settings}; use settings::{GitGutter, Settings};
use smallvec::SmallVec; use smallvec::SmallVec;
@ -45,7 +45,13 @@ use std::{
ops::{DerefMut, Range}, ops::{DerefMut, Range},
sync::Arc, sync::Arc,
}; };
use theme::DiffStyle;
#[derive(Debug)]
struct DiffHunkLayout {
visual_range: Range<u32>,
status: DiffHunkStatus,
is_folded: bool,
}
struct SelectionLayout { struct SelectionLayout {
head: DisplayPoint, head: DisplayPoint,
@ -516,85 +522,11 @@ impl EditorElement {
layout: &mut LayoutState, layout: &mut LayoutState,
cx: &mut PaintContext, cx: &mut PaintContext,
) { ) {
struct GutterLayout { let line_height = layout.position_map.line_height;
line_height: f32,
// scroll_position: Vector2F,
scroll_top: f32,
bounds: RectF,
}
struct DiffLayout<'a> {
buffer_row: u32,
last_diff: Option<&'a DiffHunk<u32>>,
}
fn diff_quad(
hunk: &DiffHunk<u32>,
gutter_layout: &GutterLayout,
diff_style: &DiffStyle,
) -> Quad {
let color = match hunk.status() {
DiffHunkStatus::Added => diff_style.inserted,
DiffHunkStatus::Modified => diff_style.modified,
//TODO: This rendering is entirely a horrible hack
DiffHunkStatus::Removed => {
let row = hunk.buffer_range.start;
let offset = gutter_layout.line_height / 2.;
let start_y =
row as f32 * gutter_layout.line_height + offset - gutter_layout.scroll_top;
let end_y = start_y + gutter_layout.line_height;
let width = diff_style.removed_width_em * gutter_layout.line_height;
let highlight_origin = gutter_layout.bounds.origin() + vec2f(-width, start_y);
let highlight_size = vec2f(width * 2., end_y - start_y);
let highlight_bounds = RectF::new(highlight_origin, highlight_size);
return Quad {
bounds: highlight_bounds,
background: Some(diff_style.deleted),
border: Border::new(0., Color::transparent_black()),
corner_radius: 1. * gutter_layout.line_height,
};
}
};
let start_row = hunk.buffer_range.start;
let end_row = hunk.buffer_range.end;
let start_y = start_row as f32 * gutter_layout.line_height - gutter_layout.scroll_top;
let end_y = end_row as f32 * gutter_layout.line_height - gutter_layout.scroll_top;
let width = diff_style.width_em * gutter_layout.line_height;
let highlight_origin = gutter_layout.bounds.origin() + vec2f(-width, start_y);
let highlight_size = vec2f(width * 2., end_y - start_y);
let highlight_bounds = RectF::new(highlight_origin, highlight_size);
Quad {
bounds: highlight_bounds,
background: Some(color),
border: Border::new(0., Color::transparent_black()),
corner_radius: diff_style.corner_radius * gutter_layout.line_height,
}
}
let scroll_position = layout.position_map.snapshot.scroll_position(); let scroll_position = layout.position_map.snapshot.scroll_position();
let gutter_layout = { let scroll_top = scroll_position.y() * line_height;
let line_height = layout.position_map.line_height;
GutterLayout {
scroll_top: scroll_position.y() * line_height,
line_height,
bounds,
}
};
let mut diff_layout = DiffLayout {
buffer_row: scroll_position.y() as u32,
last_diff: None,
};
let diff_style = &cx.global::<Settings>().theme.editor.diff.clone();
let show_gutter = matches!( let show_gutter = matches!(
&cx.global::<Settings>() &cx.global::<Settings>()
.git_overrides .git_overrides
@ -603,58 +535,107 @@ impl EditorElement {
GitGutter::TrackedFiles GitGutter::TrackedFiles
); );
// line is `None` when there's a line wrap if show_gutter {
Self::paint_diff_hunks(bounds, layout, cx);
}
for (ix, line) in layout.line_number_layouts.iter().enumerate() { for (ix, line) in layout.line_number_layouts.iter().enumerate() {
if let Some(line) = line { if let Some(line) = line {
let line_origin = bounds.origin() let line_origin = bounds.origin()
+ vec2f( + vec2f(
bounds.width() - line.width() - layout.gutter_padding, bounds.width() - line.width() - layout.gutter_padding,
ix as f32 * gutter_layout.line_height ix as f32 * line_height - (scroll_top % line_height),
- (gutter_layout.scroll_top % gutter_layout.line_height),
); );
line.paint(line_origin, visible_bounds, gutter_layout.line_height, cx); line.paint(line_origin, visible_bounds, line_height, cx);
if show_gutter {
//This line starts a buffer line, so let's do the diff calculation
let new_hunk = get_hunk(diff_layout.buffer_row, &layout.diff_hunks);
let (is_ending, is_starting) = match (diff_layout.last_diff, new_hunk) {
(Some(old_hunk), Some(new_hunk)) if new_hunk == old_hunk => (false, false),
(a, b) => (a.is_some(), b.is_some()),
};
if is_ending {
let last_hunk = diff_layout.last_diff.take().unwrap();
cx.scene
.push_quad(diff_quad(last_hunk, &gutter_layout, diff_style));
}
if is_starting {
let new_hunk = new_hunk.unwrap();
diff_layout.last_diff = Some(new_hunk);
};
diff_layout.buffer_row += 1;
}
} }
} }
// If we ran out with a diff hunk still being prepped, paint it now
if let Some(last_hunk) = diff_layout.last_diff {
cx.scene
.push_quad(diff_quad(last_hunk, &gutter_layout, diff_style))
}
if let Some((row, indicator)) = layout.code_actions_indicator.as_mut() { if let Some((row, indicator)) = layout.code_actions_indicator.as_mut() {
let mut x = bounds.width() - layout.gutter_padding; let mut x = bounds.width() - layout.gutter_padding;
let mut y = *row as f32 * gutter_layout.line_height - gutter_layout.scroll_top; let mut y = *row as f32 * line_height - scroll_top;
x += ((layout.gutter_padding + layout.gutter_margin) - indicator.size().x()) / 2.; x += ((layout.gutter_padding + layout.gutter_margin) - indicator.size().x()) / 2.;
y += (gutter_layout.line_height - indicator.size().y()) / 2.; y += (line_height - indicator.size().y()) / 2.;
indicator.paint(bounds.origin() + vec2f(x, y), visible_bounds, cx); indicator.paint(bounds.origin() + vec2f(x, y), visible_bounds, cx);
} }
} }
fn paint_diff_hunks(bounds: RectF, layout: &mut LayoutState, cx: &mut PaintContext) {
let diff_style = &cx.global::<Settings>().theme.editor.diff.clone();
let line_height = layout.position_map.line_height;
let scroll_position = layout.position_map.snapshot.scroll_position();
let scroll_top = scroll_position.y() * line_height;
for hunk in &layout.hunk_layouts {
let color = match (hunk.status, hunk.is_folded) {
(DiffHunkStatus::Added, false) => diff_style.inserted,
(DiffHunkStatus::Modified, false) => diff_style.modified,
//TODO: This rendering is entirely a horrible hack
(DiffHunkStatus::Removed, false) => {
let row = hunk.visual_range.start;
let offset = line_height / 2.;
let start_y = row as f32 * line_height - offset - scroll_top;
let end_y = start_y + line_height;
let width = diff_style.removed_width_em * line_height;
let highlight_origin = bounds.origin() + vec2f(-width, start_y);
let highlight_size = vec2f(width * 2., end_y - start_y);
let highlight_bounds = RectF::new(highlight_origin, highlight_size);
cx.scene.push_quad(Quad {
bounds: highlight_bounds,
background: Some(diff_style.deleted),
border: Border::new(0., Color::transparent_black()),
corner_radius: 1. * line_height,
});
continue;
}
(_, true) => {
let row = hunk.visual_range.start;
let start_y = row as f32 * line_height - scroll_top;
let end_y = start_y + line_height;
let width = diff_style.removed_width_em * line_height;
let highlight_origin = bounds.origin() + vec2f(-width, start_y);
let highlight_size = vec2f(width * 2., end_y - start_y);
let highlight_bounds = RectF::new(highlight_origin, highlight_size);
cx.scene.push_quad(Quad {
bounds: highlight_bounds,
background: Some(diff_style.modified),
border: Border::new(0., Color::transparent_black()),
corner_radius: 1. * line_height,
});
continue;
}
};
let start_row = hunk.visual_range.start;
let end_row = hunk.visual_range.end;
let start_y = start_row as f32 * line_height - scroll_top;
let end_y = end_row as f32 * line_height - scroll_top;
let width = diff_style.width_em * line_height;
let highlight_origin = bounds.origin() + vec2f(-width, start_y);
let highlight_size = vec2f(width * 2., end_y - start_y);
let highlight_bounds = RectF::new(highlight_origin, highlight_size);
cx.scene.push_quad(Quad {
bounds: highlight_bounds,
background: Some(color),
border: Border::new(0., Color::transparent_black()),
corner_radius: diff_style.corner_radius * line_height,
});
}
}
fn paint_text( fn paint_text(
&mut self, &mut self,
bounds: RectF, bounds: RectF,
@ -1113,6 +1094,75 @@ impl EditorElement {
.width() .width()
} }
//Folds contained in a hunk are ignored apart from shrinking visual size
//If a fold contains any hunks then that fold line is marked as modified
fn layout_git_gutters(
&self,
rows: Range<u32>,
snapshot: &EditorSnapshot,
) -> Vec<DiffHunkLayout> {
let buffer_snapshot = &snapshot.buffer_snapshot;
let visual_start = DisplayPoint::new(rows.start, 0).to_point(snapshot).row;
let visual_end = DisplayPoint::new(rows.end, 0).to_point(snapshot).row;
let hunks = buffer_snapshot.git_diff_hunks_in_range(visual_start..visual_end);
let mut layouts = Vec::<DiffHunkLayout>::new();
for hunk in hunks {
let hunk_start_point = Point::new(hunk.buffer_range.start, 0);
let hunk_end_point = Point::new(hunk.buffer_range.end, 0);
let hunk_start_point_sub = Point::new(hunk.buffer_range.start.saturating_sub(1), 0);
let hunk_end_point_sub = Point::new(
hunk.buffer_range
.end
.saturating_sub(1)
.max(hunk.buffer_range.start),
0,
);
let is_removal = hunk.status() == DiffHunkStatus::Removed;
let folds_start = Point::new(hunk.buffer_range.start.saturating_sub(1), 0);
let folds_end = Point::new(hunk.buffer_range.end + 1, 0);
let folds_range = folds_start..folds_end;
let containing_fold = snapshot.folds_in_range(folds_range).find(|fold_range| {
let fold_point_range = fold_range.to_point(buffer_snapshot);
let fold_point_range = fold_point_range.start..=fold_point_range.end;
let folded_start = fold_point_range.contains(&hunk_start_point);
let folded_end = fold_point_range.contains(&hunk_end_point_sub);
let folded_start_sub = fold_point_range.contains(&hunk_start_point_sub);
(folded_start && folded_end) || (is_removal && folded_start_sub)
});
let visual_range = if let Some(fold) = containing_fold {
let row = fold.start.to_display_point(snapshot).row();
row..row
} else {
let start = hunk_start_point.to_display_point(snapshot).row();
let end = hunk_end_point.to_display_point(snapshot).row();
start..end
};
let has_existing_layout = match layouts.last() {
Some(e) => visual_range == e.visual_range && e.status == hunk.status(),
None => false,
};
if !has_existing_layout {
layouts.push(DiffHunkLayout {
visual_range,
status: hunk.status(),
is_folded: containing_fold.is_some(),
});
}
}
layouts
}
fn layout_line_numbers( fn layout_line_numbers(
&self, &self,
rows: Range<u32>, rows: Range<u32>,
@ -1465,27 +1515,6 @@ impl EditorElement {
} }
} }
/// Get the hunk that contains buffer_line, starting from start_idx
/// Returns none if there is none found, and
fn get_hunk(buffer_line: u32, hunks: &[DiffHunk<u32>]) -> Option<&DiffHunk<u32>> {
for i in 0..hunks.len() {
// Safety: Index out of bounds is handled by the check above
let hunk = hunks.get(i).unwrap();
if hunk.buffer_range.contains(&(buffer_line as u32)) {
return Some(hunk);
} else if hunk.status() == DiffHunkStatus::Removed && buffer_line == hunk.buffer_range.start
{
return Some(hunk);
} else if hunk.buffer_range.start > buffer_line as u32 {
// If we've passed the buffer_line, just stop
return None;
}
}
// We reached the end of the array without finding a hunk, just return none.
return None;
}
impl Element for EditorElement { impl Element for EditorElement {
type LayoutState = LayoutState; type LayoutState = LayoutState;
type PaintState = (); type PaintState = ();
@ -1665,10 +1694,7 @@ impl Element for EditorElement {
let line_number_layouts = let line_number_layouts =
self.layout_line_numbers(start_row..end_row, &active_rows, &snapshot, cx); self.layout_line_numbers(start_row..end_row, &active_rows, &snapshot, cx);
let diff_hunks = snapshot let hunk_layouts = self.layout_git_gutters(start_row..end_row, &snapshot);
.buffer_snapshot
.git_diff_hunks_in_range(start_row..end_row)
.collect();
let scrollbar_row_range = scroll_position.y()..(scroll_position.y() + height_in_lines); let scrollbar_row_range = scroll_position.y()..(scroll_position.y() + height_in_lines);
@ -1826,7 +1852,7 @@ impl Element for EditorElement {
highlighted_rows, highlighted_rows,
highlighted_ranges, highlighted_ranges,
line_number_layouts, line_number_layouts,
diff_hunks, hunk_layouts,
blocks, blocks,
selections, selections,
context_menu, context_menu,
@ -1948,6 +1974,7 @@ pub struct LayoutState {
active_rows: BTreeMap<u32, bool>, active_rows: BTreeMap<u32, bool>,
highlighted_rows: Option<Range<u32>>, highlighted_rows: Option<Range<u32>>,
line_number_layouts: Vec<Option<text_layout::Line>>, line_number_layouts: Vec<Option<text_layout::Line>>,
hunk_layouts: Vec<DiffHunkLayout>,
blocks: Vec<BlockLayout>, blocks: Vec<BlockLayout>,
highlighted_ranges: Vec<(Range<DisplayPoint>, Color)>, highlighted_ranges: Vec<(Range<DisplayPoint>, Color)>,
selections: Vec<(ReplicaId, Vec<SelectionLayout>)>, selections: Vec<(ReplicaId, Vec<SelectionLayout>)>,
@ -1955,7 +1982,6 @@ pub struct LayoutState {
show_scrollbars: bool, show_scrollbars: bool,
max_row: u32, max_row: u32,
context_menu: Option<(DisplayPoint, ElementBox)>, context_menu: Option<(DisplayPoint, ElementBox)>,
diff_hunks: Vec<DiffHunk<u32>>,
code_actions_indicator: Option<(u32, ElementBox)>, code_actions_indicator: Option<(u32, ElementBox)>,
hover_popovers: Option<(DisplayPoint, Vec<ElementBox>)>, hover_popovers: Option<(DisplayPoint, Vec<ElementBox>)>,
} }

View file

@ -143,6 +143,7 @@ struct ExcerptSummary {
text: TextSummary, text: TextSummary,
} }
#[derive(Clone)]
pub struct MultiBufferRows<'a> { pub struct MultiBufferRows<'a> {
buffer_row_range: Range<u32>, buffer_row_range: Range<u32>,
excerpts: Cursor<'a, Excerpt, Point>, excerpts: Cursor<'a, Excerpt, Point>,

View file

@ -190,7 +190,6 @@ impl BufferDiff {
} }
if kind == GitDiffLineType::Deletion { if kind == GitDiffLineType::Deletion {
*buffer_row_divergence -= 1;
let end = content_offset + content_len; let end = content_offset + content_len;
match &mut head_byte_range { match &mut head_byte_range {
@ -203,6 +202,8 @@ impl BufferDiff {
let row = old_row as i64 + *buffer_row_divergence; let row = old_row as i64 + *buffer_row_divergence;
first_deletion_buffer_row = Some(row as u32); first_deletion_buffer_row = Some(row as u32);
} }
*buffer_row_divergence -= 1;
} }
} }

View file

@ -15,3 +15,5 @@ workspace = { path = "../workspace" }
chrono = "0.4" chrono = "0.4"
dirs = "4.0" dirs = "4.0"
log = { version = "0.4.16", features = ["kv_unstable_serde"] } log = { version = "0.4.16", features = ["kv_unstable_serde"] }
settings = { path = "../settings" }
shellexpand = "2.1.0"

View file

@ -1,7 +1,12 @@
use chrono::{Datelike, Local, Timelike}; use chrono::{Datelike, Local, NaiveTime, Timelike};
use editor::{Autoscroll, Editor}; use editor::{Autoscroll, Editor};
use gpui::{actions, MutableAppContext}; use gpui::{actions, MutableAppContext};
use std::{fs::OpenOptions, sync::Arc}; use settings::{HourFormat, Settings};
use std::{
fs::OpenOptions,
path::{Path, PathBuf},
sync::Arc,
};
use util::TryFutureExt as _; use util::TryFutureExt as _;
use workspace::AppState; use workspace::AppState;
@ -12,24 +17,23 @@ pub fn init(app_state: Arc<AppState>, cx: &mut MutableAppContext) {
} }
pub fn new_journal_entry(app_state: Arc<AppState>, cx: &mut MutableAppContext) { pub fn new_journal_entry(app_state: Arc<AppState>, cx: &mut MutableAppContext) {
let now = Local::now(); let settings = cx.global::<Settings>();
let home_dir = match dirs::home_dir() { let journal_dir = match journal_dir(&settings) {
Some(home_dir) => home_dir, Some(journal_dir) => journal_dir,
None => { None => {
log::error!("can't determine home directory"); log::error!("Can't determine journal directory");
return; return;
} }
}; };
let journal_dir = home_dir.join("journal"); let now = Local::now();
let month_dir = journal_dir let month_dir = journal_dir
.join(format!("{:02}", now.year())) .join(format!("{:02}", now.year()))
.join(format!("{:02}", now.month())); .join(format!("{:02}", now.month()));
let entry_path = month_dir.join(format!("{:02}.md", now.day())); let entry_path = month_dir.join(format!("{:02}.md", now.day()));
let now = now.time(); let now = now.time();
let (pm, hour) = now.hour12(); let hour_format = &settings.journal_overrides.hour_format;
let am_or_pm = if pm { "PM" } else { "AM" }; let entry_heading = heading_entry(now, &hour_format);
let entry_heading = format!("# {}:{:02} {}\n\n", hour, now.minute(), am_or_pm);
let create_entry = cx.background().spawn(async move { let create_entry = cx.background().spawn(async move {
std::fs::create_dir_all(month_dir)?; std::fs::create_dir_all(month_dir)?;
@ -64,6 +68,7 @@ pub fn new_journal_entry(app_state: Arc<AppState>, cx: &mut MutableAppContext) {
editor.insert("\n\n", cx); editor.insert("\n\n", cx);
} }
editor.insert(&entry_heading, cx); editor.insert(&entry_heading, cx);
editor.insert("\n\n", cx);
}); });
} }
} }
@ -74,3 +79,65 @@ pub fn new_journal_entry(app_state: Arc<AppState>, cx: &mut MutableAppContext) {
}) })
.detach(); .detach();
} }
fn journal_dir(settings: &Settings) -> Option<PathBuf> {
let journal_dir = settings
.journal_overrides
.path
.as_ref()
.unwrap_or(settings.journal_defaults.path.as_ref()?);
let expanded_journal_dir = shellexpand::full(&journal_dir) //TODO handle this better
.ok()
.map(|dir| Path::new(&dir.to_string()).to_path_buf().join("journal"));
return expanded_journal_dir;
}
fn heading_entry(now: NaiveTime, hour_format: &Option<HourFormat>) -> String {
match hour_format {
Some(HourFormat::Hour24) => {
let hour = now.hour();
format!("# {}:{:02}", hour, now.minute())
}
_ => {
let (pm, hour) = now.hour12();
let am_or_pm = if pm { "PM" } else { "AM" };
format!("# {}:{:02} {}", hour, now.minute(), am_or_pm)
}
}
}
#[cfg(test)]
mod tests {
mod heading_entry_tests {
use super::super::*;
#[test]
fn test_heading_entry_defaults_to_hour_12() {
let naive_time = NaiveTime::from_hms_milli(15, 0, 0, 0);
let actual_heading_entry = heading_entry(naive_time, &None);
let expected_heading_entry = "# 3:00 PM";
assert_eq!(actual_heading_entry, expected_heading_entry);
}
#[test]
fn test_heading_entry_is_hour_12() {
let naive_time = NaiveTime::from_hms_milli(15, 0, 0, 0);
let actual_heading_entry = heading_entry(naive_time, &Some(HourFormat::Hour12));
let expected_heading_entry = "# 3:00 PM";
assert_eq!(actual_heading_entry, expected_heading_entry);
}
#[test]
fn test_heading_entry_is_hour_24() {
let naive_time = NaiveTime::from_hms_milli(15, 0, 0, 0);
let actual_heading_entry = heading_entry(naive_time, &Some(HourFormat::Hour24));
let expected_heading_entry = "# 15:00";
assert_eq!(actual_heading_entry, expected_heading_entry);
}
}
}

View file

@ -37,6 +37,8 @@ pub struct Settings {
pub editor_overrides: EditorSettings, pub editor_overrides: EditorSettings,
pub git: GitSettings, pub git: GitSettings,
pub git_overrides: GitSettings, pub git_overrides: GitSettings,
pub journal_defaults: JournalSettings,
pub journal_overrides: JournalSettings,
pub terminal_defaults: TerminalSettings, pub terminal_defaults: TerminalSettings,
pub terminal_overrides: TerminalSettings, pub terminal_overrides: TerminalSettings,
pub language_defaults: HashMap<Arc<str>, EditorSettings>, pub language_defaults: HashMap<Arc<str>, EditorSettings>,
@ -122,6 +124,34 @@ pub enum Autosave {
OnWindowChange, OnWindowChange,
} }
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
pub struct JournalSettings {
pub path: Option<String>,
pub hour_format: Option<HourFormat>,
}
impl Default for JournalSettings {
fn default() -> Self {
Self {
path: Some("~".into()),
hour_format: Some(Default::default()),
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum HourFormat {
Hour12,
Hour24,
}
impl Default for HourFormat {
fn default() -> Self {
Self::Hour12
}
}
#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)] #[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
pub struct TerminalSettings { pub struct TerminalSettings {
pub shell: Option<Shell>, pub shell: Option<Shell>,
@ -216,6 +246,8 @@ pub struct SettingsFileContent {
#[serde(flatten)] #[serde(flatten)]
pub editor: EditorSettings, pub editor: EditorSettings,
#[serde(default)] #[serde(default)]
pub journal: JournalSettings,
#[serde(default)]
pub terminal: TerminalSettings, pub terminal: TerminalSettings,
#[serde(default)] #[serde(default)]
pub git: Option<GitSettings>, pub git: Option<GitSettings>,
@ -278,6 +310,8 @@ impl Settings {
editor_overrides: Default::default(), editor_overrides: Default::default(),
git: defaults.git.unwrap(), git: defaults.git.unwrap(),
git_overrides: Default::default(), git_overrides: Default::default(),
journal_defaults: defaults.journal,
journal_overrides: Default::default(),
terminal_defaults: defaults.terminal, terminal_defaults: defaults.terminal,
terminal_overrides: Default::default(), terminal_overrides: Default::default(),
language_defaults: defaults.languages, language_defaults: defaults.languages,
@ -330,6 +364,7 @@ impl Settings {
self.editor_overrides = data.editor; self.editor_overrides = data.editor;
self.git_overrides = data.git.unwrap_or_default(); self.git_overrides = data.git.unwrap_or_default();
self.journal_overrides = data.journal;
self.terminal_defaults.font_size = data.terminal.font_size; self.terminal_defaults.font_size = data.terminal.font_size;
self.terminal_overrides.copy_on_select = data.terminal.copy_on_select; self.terminal_overrides.copy_on_select = data.terminal.copy_on_select;
self.terminal_overrides = data.terminal; self.terminal_overrides = data.terminal;
@ -416,6 +451,8 @@ impl Settings {
enable_language_server: Some(true), enable_language_server: Some(true),
}, },
editor_overrides: Default::default(), editor_overrides: Default::default(),
journal_defaults: Default::default(),
journal_overrides: Default::default(),
terminal_defaults: Default::default(), terminal_defaults: Default::default(),
terminal_overrides: Default::default(), terminal_overrides: Default::default(),
git: Default::default(), git: Default::default(),

View file

@ -1018,55 +1018,34 @@ impl Terminal {
self.last_content.size, self.last_content.size,
self.last_content.display_offset, self.last_content.display_offset,
); );
// let side = mouse_side(position, self.last_content.size);
if self.mouse_mode(e.shift) { if self.mouse_mode(e.shift) {
if let Some(bytes) = mouse_button_report(point, e, true, self.last_content.mode) { if let Some(bytes) = mouse_button_report(point, e, true, self.last_content.mode) {
self.pty_tx.notify(bytes); self.pty_tx.notify(bytes);
} }
} else if e.button == MouseButton::Left { } else if e.button == MouseButton::Left {
self.left_click(e, origin) let position = e.position.sub(origin);
} let point = grid_point(
} position,
self.last_content.size,
self.last_content.display_offset,
);
let side = mouse_side(position, self.last_content.size);
pub fn left_click(&mut self, e: &MouseDown, origin: Vector2F) { let selection_type = match e.click_count {
let position = e.position.sub(origin); 0 => return, //This is a release
if !self.mouse_mode(e.shift) { 1 => Some(SelectionType::Simple),
//Hyperlinks 2 => Some(SelectionType::Semantic),
{ 3 => Some(SelectionType::Lines),
let mouse_cell_index = content_index_for_mouse(position, &self.last_content); _ => None,
if let Some(link) = self.last_content.cells[mouse_cell_index].hyperlink() { };
open_uri(link.uri()).log_err();
} else {
self.events
.push_back(InternalEvent::FindHyperlink(position, true));
}
}
// Selections let selection =
{ selection_type.map(|selection_type| Selection::new(selection_type, point, side));
let point = grid_point(
position,
self.last_content.size,
self.last_content.display_offset,
);
let side = mouse_side(position, self.last_content.size);
let selection_type = match e.click_count { if let Some(sel) = selection {
0 => return, //This is a release self.events
1 => Some(SelectionType::Simple), .push_back(InternalEvent::SetSelection(Some((sel, point))));
2 => Some(SelectionType::Semantic),
3 => Some(SelectionType::Lines),
_ => None,
};
let selection = selection_type
.map(|selection_type| Selection::new(selection_type, point, side));
if let Some(sel) = selection {
self.events
.push_back(InternalEvent::SetSelection(Some((sel, point))));
}
} }
} }
} }
@ -1094,8 +1073,21 @@ impl Terminal {
if let Some(bytes) = mouse_button_report(point, e, false, self.last_content.mode) { if let Some(bytes) = mouse_button_report(point, e, false, self.last_content.mode) {
self.pty_tx.notify(bytes); self.pty_tx.notify(bytes);
} }
} else if e.button == MouseButton::Left && copy_on_select { } else {
self.copy(); if e.button == MouseButton::Left && copy_on_select {
self.copy();
}
//Hyperlinks
if self.selection_phase == SelectionPhase::Ended {
let mouse_cell_index = content_index_for_mouse(position, &self.last_content);
if let Some(link) = self.last_content.cells[mouse_cell_index].hyperlink() {
open_uri(link.uri()).log_err();
} else {
self.events
.push_back(InternalEvent::FindHyperlink(position, true));
}
}
} }
self.selection_phase = SelectionPhase::Ended; self.selection_phase = SelectionPhase::Ended;