refactor: break more stuff out of termwindow

This commit is contained in:
Wez Furlong committed 2021-02-27 18:21:36 -08:00
1 parent 840173af61
commit 452c76ea89
5 files changed
+1034 -991

No files matched your search

@@ -1,3 +1,9 @@
use crate::gui::TermWindow;
use config::keyassignment::{ClipboardCopyDestination, ClipboardPasteSource};
use mux::pane::Pane;
use mux::window::WindowId as MuxWindowId;
use mux::Mux;
use std::rc::Rc;
use std::sync::{Arc, Mutex};
use wezterm_term::ClipboardSelection;
use window::{Clipboard, Window, WindowOps};
@@ -43,3 +49,75 @@ impl wezterm_term::Clipboard for ClipboardHelper {
Ok(())
}
}
impl TermWindow {
pub fn setup_clipboard(
window: &Window,
mux_window_id: MuxWindowId,
clipboard_contents: Arc<Mutex<Option<String>>>,
) {
let clipboard: Arc<dyn wezterm_term::Clipboard> = Arc::new(ClipboardHelper {
window: window.clone(),
clipboard_contents,
});
let mux = Mux::get().unwrap();
let mut mux_window = mux.get_window_mut(mux_window_id).unwrap();
mux_window.set_clipboard(&clipboard);
for tab in mux_window.iter() {
for pane in tab.get_active_pane() {
pane.set_clipboard(&clipboard);
}
}
}
pub fn copy_to_clipboard(&self, clipboard: ClipboardCopyDestination, text: String) {
let clipboard = match clipboard {
ClipboardCopyDestination::Clipboard => [Some(Clipboard::Clipboard), None],
ClipboardCopyDestination::PrimarySelection => [Some(Clipboard::PrimarySelection), None],
ClipboardCopyDestination::ClipboardAndPrimarySelection => [
Some(Clipboard::Clipboard),
Some(Clipboard::PrimarySelection),
],
};
for &c in &clipboard {
if let Some(c) = c {
self.window.as_ref().unwrap().set_clipboard(c, text.clone());
}
}
}
pub fn paste_from_clipboard(&mut self, pane: &Rc<dyn Pane>, clipboard: ClipboardPasteSource) {
let pane_id = pane.pane_id();
let window = self.window.as_ref().unwrap().clone();
let clipboard = match clipboard {
ClipboardPasteSource::Clipboard => Clipboard::Clipboard,
ClipboardPasteSource::PrimarySelection => Clipboard::PrimarySelection,
};
let future = window.get_clipboard(clipboard);
promise::spawn::spawn(async move {
if let Ok(clip) = future.await {
window
.apply(move |term_window, _window| {
let clip = clip.clone();
if let Some(term_window) = term_window.downcast_mut::<TermWindow>() {
if let Some(pane) =
term_window.pane_state(pane_id).overlay.clone().or_else(|| {
let mux = Mux::get().unwrap();
mux.get_pane(pane_id)
})
{
pane.trickle_paste(clip).ok();
}
}
Ok(())
})
.await?;
};
Ok::<(), anyhow::Error>(())
})
.detach();
}
}
+350
View File
@@ -0,0 +1,350 @@
use ::window::{KeyCode, KeyEvent, Modifiers, WindowOps};
pub fn window_mods_to_termwiz_mods(modifiers: ::window::Modifiers) -> termwiz::input::Modifiers {
let mut result = termwiz::input::Modifiers::NONE;
if modifiers.contains(::window::Modifiers::SHIFT) {
result.insert(termwiz::input::Modifiers::SHIFT);
}
if modifiers.contains(::window::Modifiers::LEFT_ALT) {
result.insert(termwiz::input::Modifiers::ALT);
}
if modifiers.contains(::window::Modifiers::RIGHT_ALT) {
result.insert(termwiz::input::Modifiers::ALT);
}
if modifiers.contains(::window::Modifiers::ALT) {
result.insert(termwiz::input::Modifiers::ALT);
}
if modifiers.contains(::window::Modifiers::CTRL) {
result.insert(termwiz::input::Modifiers::CTRL);
}
if modifiers.contains(::window::Modifiers::SUPER) {
result.insert(termwiz::input::Modifiers::SUPER);
}
if modifiers.contains(::window::Modifiers::LEADER) {
result.insert(termwiz::input::Modifiers::LEADER);
}
result
}
#[derive(Debug)]
pub enum Key {
Code(::termwiz::input::KeyCode),
Composed(String),
None,
}
impl super::TermWindow {
pub fn key_event_impl(&mut self, window_key: &KeyEvent, context: &dyn WindowOps) -> bool {
if !window_key.key_is_down {
return false;
}
if self.config.debug_key_events {
log::info!("key_event {:?}", window_key);
} else {
log::trace!("key_event {:?}", window_key);
}
let pane = match self.get_active_pane_or_overlay() {
Some(pane) => pane,
None => return false,
};
// The leader key is a kind of modal modifier key.
// It is allowed to be active for up to the leader timeout duration,
// after which it auto-deactivates.
let (leader_active, leader_mod) = match self.leader_is_down.as_ref() {
Some(expiry) if *expiry > std::time::Instant::now() => {
// Currently active
(true, Modifiers::LEADER)
}
Some(_) => {
// Expired; clear out the old expiration time
self.leader_is_down.take();
(false, Modifiers::NONE)
}
_ => (false, Modifiers::NONE),
};
let modifiers = window_mods_to_termwiz_mods(window_key.modifiers);
let raw_modifiers = window_mods_to_termwiz_mods(window_key.raw_modifiers);
// If we know the underlying raw code, let's first try any mappings
// defined for those. By their nature, we don't know anything useful
// about their position or meaning in code here, so we don't have
// any built-in mappings defined with raw_codes.
// That means that we only need check for user-defined values in
// this block.
if let Some(raw_code) = window_key.raw_code {
let raw_code_key = KeyCode::RawCode(raw_code);
if !leader_active {
// Check to see if this key-press is the leader activating
if let Some(duration) = self
.input_map
.is_leader(&raw_code_key, window_key.raw_modifiers)
{
// Yes; record its expiration
self.leader_is_down
.replace(std::time::Instant::now() + duration);
return true;
}
}
if let Some(assignment) = self
.input_map
.lookup_key(&raw_code_key, window_key.raw_modifiers | leader_mod)
{
self.perform_key_assignment(&pane, &assignment).ok();
context.invalidate();
if leader_active {
// A successful leader key-lookup cancels the leader
// virtual modifier state
self.leader_is_down.take();
}
return true;
}
}
// We may know the decoded platform key, but prior to any composition
// defined by the system (eg: prior to dead key expansion).
if let Some(key) = &window_key.raw_key {
if !leader_active {
// Check to see if this key-press is the leader activating
if let Some(duration) = self.input_map.is_leader(key, window_key.raw_modifiers) {
// Yes; record its expiration
self.leader_is_down
.replace(std::time::Instant::now() + duration);
return true;
}
}
if let Some(assignment) = self
.input_map
.lookup_key(key, window_key.raw_modifiers | leader_mod)
{
self.perform_key_assignment(&pane, &assignment).ok();
context.invalidate();
if leader_active {
// A successful leader key-lookup cancels the leader
// virtual modifier state
self.leader_is_down.take();
}
return true;
}
// While the leader modifier is active, only registered
// keybindings are recognized.
if !leader_active {
let config = &self.config;
// This is a bit ugly.
// Not all of our platforms report LEFT|RIGHT ALT; most report just ALT.
// For those that do distinguish between them we want to respect the left vs.
// right settings for the compose behavior.
// Otherwise, if the event didn't include left vs. right then we want to
// respect the generic compose behavior.
let bypass_compose =
// Left ALT and they disabled compose
(window_key.raw_modifiers.contains(Modifiers::LEFT_ALT)
&& !config.send_composed_key_when_left_alt_is_pressed)
// Right ALT and they disabled compose
|| (window_key.raw_modifiers.contains(Modifiers::RIGHT_ALT)
&& !config.send_composed_key_when_right_alt_is_pressed)
// Generic ALT and they disabled generic compose
|| (!window_key.raw_modifiers.contains(Modifiers::RIGHT_ALT)
&& !window_key.raw_modifiers.contains(Modifiers::LEFT_ALT)
&& window_key.raw_modifiers.contains(Modifiers::ALT)
&& !config.send_composed_key_when_alt_is_pressed);
if let Key::Code(term_key) = self.win_key_code_to_termwiz_key_code(&key) {
if bypass_compose && pane.key_down(term_key, raw_modifiers).is_ok() {
if !key.is_modifier() && self.pane_state(pane.pane_id()).overlay.is_none() {
self.maybe_scroll_to_bottom_for_input(&pane);
}
context.invalidate();
return true;
}
}
}
}
if !leader_active {
// Check to see if this key-press is the leader activating
if let Some(duration) = self
.input_map
.is_leader(&window_key.key, window_key.modifiers)
{
// Yes; record its expiration
self.leader_is_down
.replace(std::time::Instant::now() + duration);
return true;
}
}
if let Some(assignment) = self
.input_map
.lookup_key(&window_key.key, window_key.modifiers | leader_mod)
{
self.perform_key_assignment(&pane, &assignment).ok();
context.invalidate();
if leader_active {
// A successful leader key-lookup cancels the leader
// virtual modifier state
self.leader_is_down.take();
}
true
} else if leader_active {
if !window_key.key.is_modifier() {
// Leader was pressed and this non-modifier keypress isn't
// a registered key binding; swallow this event and cancel
// the leader modifier
self.leader_is_down.take();
}
true
} else {
let key = self.win_key_code_to_termwiz_key_code(&window_key.key);
match key {
Key::Code(key) => {
if pane.key_down(key, modifiers).is_ok() {
if !key.is_modifier() && self.pane_state(pane.pane_id()).overlay.is_none() {
self.maybe_scroll_to_bottom_for_input(&pane);
}
context.invalidate();
true
} else {
false
}
}
Key::Composed(s) => {
if leader_active {
// Leader was pressed and this non-modifier keypress isn't
// a registered key binding; swallow this event and cancel
// the leader modifier.
self.leader_is_down.take();
} else {
pane.writer().write_all(s.as_bytes()).ok();
self.maybe_scroll_to_bottom_for_input(&pane);
context.invalidate();
}
true
}
Key::None => false,
}
}
}
fn win_key_code_to_termwiz_key_code(&self, key: &::window::KeyCode) -> Key {
use ::termwiz::input::KeyCode as KC;
use ::window::KeyCode as WK;
let code = match key {
// TODO: consider eliminating these codes from termwiz::input::KeyCode
WK::Char('\r') => KC::Enter,
WK::Char('\t') => KC::Tab,
WK::Char('\u{08}') => {
if self.config.swap_backspace_and_delete {
KC::Delete
} else {
KC::Backspace
}
}
WK::Char('\u{7f}') => {
if self.config.swap_backspace_and_delete {
KC::Backspace
} else {
KC::Delete
}
}
WK::Char('\u{1b}') => KC::Escape,
WK::RawCode(_) => return Key::None,
WK::Char(c) => KC::Char(*c),
WK::Composed(ref s) => {
let mut chars = s.chars();
if let Some(first_char) = chars.next() {
if chars.next().is_none() {
// Was just a single char after all
return self.win_key_code_to_termwiz_key_code(&WK::Char(first_char));
}
}
return Key::Composed(s.to_owned());
}
WK::Function(f) => KC::Function(*f),
WK::LeftArrow => KC::LeftArrow,
WK::RightArrow => KC::RightArrow,
WK::UpArrow => KC::UpArrow,
WK::DownArrow => KC::DownArrow,
WK::Home => KC::Home,
WK::End => KC::End,
WK::PageUp => KC::PageUp,
WK::PageDown => KC::PageDown,
WK::Insert => KC::Insert,
WK::Hyper => KC::Hyper,
WK::Super => KC::Super,
WK::Meta => KC::Meta,
WK::Cancel => KC::Cancel,
WK::Clear => KC::Clear,
WK::Shift => KC::Shift,
WK::LeftShift => KC::LeftShift,
WK::RightShift => KC::RightShift,
WK::Control => KC::Control,
WK::LeftControl => KC::LeftControl,
WK::RightControl => KC::RightControl,
WK::Alt => KC::Alt,
WK::LeftAlt => KC::LeftAlt,
WK::RightAlt => KC::RightAlt,
WK::Pause => KC::Pause,
WK::CapsLock => KC::CapsLock,
WK::Select => KC::Select,
WK::Print => KC::Print,
WK::Execute => KC::Execute,
WK::PrintScreen => KC::PrintScreen,
WK::Help => KC::Help,
WK::LeftWindows => KC::LeftWindows,
WK::RightWindows => KC::RightWindows,
WK::Sleep => KC::Sleep,
WK::Multiply => KC::Multiply,
WK::Applications => KC::Applications,
WK::Add => KC::Add,
WK::Numpad(0) => KC::Numpad0,
WK::Numpad(1) => KC::Numpad1,
WK::Numpad(2) => KC::Numpad2,
WK::Numpad(3) => KC::Numpad3,
WK::Numpad(4) => KC::Numpad4,
WK::Numpad(5) => KC::Numpad5,
WK::Numpad(6) => KC::Numpad6,
WK::Numpad(7) => KC::Numpad7,
WK::Numpad(8) => KC::Numpad8,
WK::Numpad(9) => KC::Numpad9,
WK::Numpad(_) => return Key::None,
WK::Separator => KC::Separator,
WK::Subtract => KC::Subtract,
WK::Decimal => KC::Decimal,
WK::Divide => KC::Divide,
WK::NumLock => KC::NumLock,
WK::ScrollLock => KC::ScrollLock,
WK::BrowserBack => KC::BrowserBack,
WK::BrowserForward => KC::BrowserForward,
WK::BrowserRefresh => KC::BrowserRefresh,
WK::BrowserStop => KC::BrowserStop,
WK::BrowserSearch => KC::BrowserSearch,
WK::BrowserFavorites => KC::BrowserFavorites,
WK::BrowserHome => KC::BrowserHome,
WK::VolumeMute => KC::VolumeMute,
WK::VolumeDown => KC::VolumeDown,
WK::VolumeUp => KC::VolumeUp,
WK::MediaNextTrack => KC::MediaNextTrack,
WK::MediaPrevTrack => KC::MediaPrevTrack,
WK::MediaStop => KC::MediaStop,
WK::MediaPlayPause => KC::MediaPlayPause,
WK::ApplicationLeftArrow => KC::ApplicationLeftArrow,
WK::ApplicationRightArrow => KC::ApplicationRightArrow,
WK::ApplicationUpArrow => KC::ApplicationUpArrow,
WK::ApplicationDownArrow => KC::ApplicationDownArrow,
};
Key::Code(code)
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,482 @@
use crate::gui::tabbar::TabBarItem;
use crate::gui::termwindow::keyevent::window_mods_to_termwiz_mods;
use crate::gui::termwindow::{mouse_press_to_tmb, ScrollHit, TMB};
use ::window::{
Modifiers, MouseButtons as WMB, MouseCursor, MouseEvent, MouseEventKind as WMEK, MousePress,
WindowOps,
};
use config::keyassignment::{MouseEventTrigger, SpawnTabDomain};
use mux::pane::Pane;
use mux::tab::SplitDirection;
use mux::Mux;
use std::convert::TryInto;
use std::ops::Sub;
use std::rc::Rc;
use std::sync::Arc;
use std::time::Duration;
use wezterm_term::input::MouseEventKind as TMEK;
use wezterm_term::{LastMouseClick, StableRowIndex};
impl super::TermWindow {
pub fn mouse_event_impl(&mut self, event: &MouseEvent, context: &dyn WindowOps) {
let pane = match self.get_active_pane_or_overlay() {
Some(pane) => pane,
None => return,
};
let config = &self.config;
// Round the x coordinate so that we're a bit more forgiving of
// the horizontal position when selecting cells
let x = ((event
.coords
.x
.sub(config.window_padding.left as isize)
.max(0) as f32)
/ self.render_metrics.cell_size.width as f32)
.round()
.trunc() as usize;
// But don't round the y coordinate as that is more annoying
let y = (event
.coords
.y
.sub(config.window_padding.top as isize)
.max(0)
/ self.render_metrics.cell_size.height) as i64;
let first_line_offset = if self.show_tab_bar { 1 } else { 0 };
self.last_mouse_coords = (x, y);
let in_tab_bar = self.show_tab_bar && y == 0 && event.coords.y >= 0;
let in_scroll_bar = self.show_scroll_bar && x >= self.terminal_size.cols as usize;
// y position relative to top of viewport (not including tab bar)
let term_y = y.saturating_sub(first_line_offset);
match event.kind {
WMEK::Release(ref press) => {
self.current_mouse_button = None;
if press == &MousePress::Left && self.scroll_drag_start.take().is_some() {
// Completed a scrollbar drag
return;
}
if press == &MousePress::Left && self.split_drag_start.take().is_some() {
// Completed a split drag
return;
}
}
WMEK::Press(ref press) => {
if let Some(focused) = self.focused.as_ref() {
if focused.elapsed() <= Duration::from_millis(200) {
log::trace!("discard mouse click because it focused the window");
return;
}
}
// Perform click counting
let button = mouse_press_to_tmb(press);
let click = match self.last_mouse_click.take() {
None => LastMouseClick::new(button),
Some(click) => click.add(button),
};
self.last_mouse_click = Some(click);
self.current_mouse_button = Some(press.clone());
}
WMEK::VertWheel(amount) if !pane.is_mouse_grabbed() && !pane.is_alt_screen_active() => {
// adjust viewport
let dims = pane.get_dimensions();
let position = self
.get_viewport(pane.pane_id())
.unwrap_or(dims.physical_top)
.saturating_sub(amount.into());
self.set_viewport(pane.pane_id(), Some(position), dims);
context.invalidate();
return;
}
WMEK::Move => {
let current_viewport = self.get_viewport(pane.pane_id());
if let Some(from_top) = self.scroll_drag_start.as_ref() {
// Dragging the scroll bar
let pane = match self.get_active_pane_or_overlay() {
Some(pane) => pane,
None => return,
};
let dims = pane.get_dimensions();
let effective_thumb_top =
event.coords.y.saturating_sub(*from_top).max(0) as usize;
// Convert thumb top into a row index by reversing the math
// in ScrollHit::thumb
let row = ScrollHit::thumb_top_to_scroll_top(
effective_thumb_top,
&*pane,
current_viewport,
self.terminal_size,
&self.dimensions,
);
self.set_viewport(pane.pane_id(), Some(row), dims);
context.invalidate();
return;
}
if let Some(split) = self.split_drag_start.take() {
let mux = Mux::get().unwrap();
let tab = match mux.get_active_tab_for_window(self.mux_window_id) {
Some(tab) => tab,
None => return,
};
let delta = match split.direction {
SplitDirection::Horizontal => {
(x as isize).saturating_sub(split.left as isize)
}
SplitDirection::Vertical => {
(term_y as isize).saturating_sub(split.top as isize)
}
};
if delta != 0 {
tab.resize_split_by(split.index, delta);
self.split_drag_start = tab.iter_splits().into_iter().nth(split.index);
context.invalidate();
} else {
self.split_drag_start.replace(split);
}
return;
}
}
_ => {}
}
if in_tab_bar {
self.mouse_event_tab_bar(x, event, context);
} else if in_scroll_bar {
self.mouse_event_scroll_bar(pane, event, context);
} else {
self.mouse_event_terminal(pane, x, term_y, event, context);
}
}
pub fn mouse_event_tab_bar(&mut self, x: usize, event: &MouseEvent, context: &dyn WindowOps) {
match event.kind {
WMEK::Press(MousePress::Left) => match self.tab_bar.hit_test(x) {
TabBarItem::Tab(tab_idx) => {
self.activate_tab(tab_idx as isize).ok();
}
TabBarItem::NewTabButton => {
self.spawn_tab(&SpawnTabDomain::CurrentPaneDomain);
}
TabBarItem::None => {}
},
WMEK::Press(MousePress::Middle) => match self.tab_bar.hit_test(x) {
TabBarItem::Tab(tab_idx) => {
self.close_tab_idx(tab_idx).ok();
}
TabBarItem::NewTabButton | TabBarItem::None => {}
},
WMEK::Press(MousePress::Right) => match self.tab_bar.hit_test(x) {
TabBarItem::Tab(_) => {
self.show_tab_navigator();
}
TabBarItem::NewTabButton => {
self.show_launcher();
}
TabBarItem::None => {}
},
_ => {}
}
self.update_title();
context.set_cursor(Some(MouseCursor::Arrow));
}
pub fn mouse_event_scroll_bar(
&mut self,
pane: Rc<dyn Pane>,
event: &MouseEvent,
context: &dyn WindowOps,
) {
if let WMEK::Press(MousePress::Left) = event.kind {
let dims = pane.get_dimensions();
let current_viewport = self.get_viewport(pane.pane_id());
let hit_result = ScrollHit::test(
event.coords.y,
&*pane,
current_viewport,
self.terminal_size,
&self.dimensions,
);
match hit_result {
ScrollHit::Above => {
// Page up
self.set_viewport(
pane.pane_id(),
Some(
current_viewport
.unwrap_or(dims.physical_top)
.saturating_sub(self.terminal_size.rows.try_into().unwrap()),
),
dims,
);
context.invalidate();
}
ScrollHit::Below => {
// Page down
self.set_viewport(
pane.pane_id(),
Some(
current_viewport
.unwrap_or(dims.physical_top)
.saturating_add(self.terminal_size.rows.try_into().unwrap()),
),
dims,
);
context.invalidate();
}
ScrollHit::OnThumb(from_top) => {
// Start a scroll drag
self.scroll_drag_start = Some(from_top);
}
};
}
context.set_cursor(Some(MouseCursor::Arrow));
}
pub fn mouse_event_terminal(
&mut self,
mut pane: Rc<dyn Pane>,
mut x: usize,
mut y: i64,
event: &MouseEvent,
context: &dyn WindowOps,
) {
let mut on_split = None;
if y >= 0 {
let y = y as usize;
for split in self.get_splits() {
on_split = match split.direction {
SplitDirection::Horizontal => {
if x == split.left && y >= split.top && y <= split.top + split.size {
Some(SplitDirection::Horizontal)
} else {
None
}
}
SplitDirection::Vertical => {
if y == split.top && x >= split.left && x <= split.left + split.size {
Some(SplitDirection::Vertical)
} else {
None
}
}
};
if on_split.is_some() {
if event.kind == WMEK::Press(MousePress::Left) {
context.set_cursor(on_split.map(|d| match d {
SplitDirection::Horizontal => MouseCursor::SizeLeftRight,
SplitDirection::Vertical => MouseCursor::SizeUpDown,
}));
self.split_drag_start.replace(split);
return;
}
break;
}
}
}
for pos in self.get_panes_to_render() {
if y >= pos.top as i64
&& y <= (pos.top + pos.height) as i64
&& x >= pos.left
&& x <= pos.left + pos.width
{
if pane.pane_id() != pos.pane.pane_id() {
// We're over a pane that isn't active
match &event.kind {
WMEK::Press(_) => {
let mux = Mux::get().unwrap();
mux.get_active_tab_for_window(self.mux_window_id)
.map(|tab| tab.set_active_idx(pos.index));
pane = Rc::clone(&pos.pane);
}
WMEK::Move => {}
WMEK::Release(_) => {}
WMEK::VertWheel(_) => {}
WMEK::HorzWheel(_) => {}
}
}
x = x.saturating_sub(pos.left);
y = y.saturating_sub(pos.top as i64);
break;
}
}
let dims = pane.get_dimensions();
let stable_row = self
.get_viewport(pane.pane_id())
.unwrap_or(dims.physical_top)
+ y as StableRowIndex;
self.last_mouse_terminal_coords = (x, stable_row); // FIXME: per-pane
let (top, mut lines) = pane.get_lines(stable_row..stable_row + 1);
let new_highlight = if top == stable_row {
if let Some(line) = lines.get_mut(0) {
if let Some(cell) = line.cells().get(x) {
cell.attrs().hyperlink().cloned()
} else {
None
}
} else {
None
}
} else {
None
};
match (self.current_highlight.as_ref(), new_highlight) {
(Some(old_link), Some(new_link)) if Arc::ptr_eq(&old_link, &new_link) => {
// Unchanged
}
(None, None) => {
// Unchanged
}
(_, rhs) => {
// We're hovering over a different URL, so invalidate and repaint
// so that we render the underline correctly
self.current_highlight = rhs;
context.invalidate();
}
};
context.set_cursor(Some(match on_split {
Some(SplitDirection::Horizontal) => MouseCursor::SizeLeftRight,
Some(SplitDirection::Vertical) => MouseCursor::SizeUpDown,
None => {
if self.current_highlight.is_some() {
// When hovering over a hyperlink, show an appropriate
// mouse cursor to give the cue that it is clickable
MouseCursor::Hand
} else {
MouseCursor::Text
}
}
}));
let event_trigger_type = match &event.kind {
WMEK::Press(press) => {
let press = mouse_press_to_tmb(press);
match self.last_mouse_click.as_ref() {
Some(LastMouseClick { streak, button, .. }) if *button == press => {
Some(MouseEventTrigger::Down {
streak: *streak,
button: press,
})
}
_ => None,
}
}
WMEK::Release(press) => {
let press = mouse_press_to_tmb(press);
match self.last_mouse_click.as_ref() {
Some(LastMouseClick { streak, button, .. }) if *button == press => {
Some(MouseEventTrigger::Up {
streak: *streak,
button: press,
})
}
_ => None,
}
}
WMEK::Move => {
if let Some(LastMouseClick { streak, button, .. }) = self.last_mouse_click.as_ref()
{
if Some(*button) == self.current_mouse_button.as_ref().map(mouse_press_to_tmb) {
Some(MouseEventTrigger::Drag {
streak: *streak,
button: *button,
})
} else {
None
}
} else {
None
}
}
WMEK::VertWheel(_) | WMEK::HorzWheel(_) => None,
};
let ignore_grab_modifier = Modifiers::SHIFT;
if !pane.is_mouse_grabbed() || event.modifiers.contains(ignore_grab_modifier) {
if let Some(event_trigger_type) = event_trigger_type {
let mut modifiers = event.modifiers;
// Since we use shift to force assessing the mouse bindings, pretend
// that shift is not one of the mods when the mouse is grabbed.
if pane.is_mouse_grabbed() {
modifiers -= ignore_grab_modifier;
}
if let Some(action) = self
.input_map
.lookup_mouse(event_trigger_type.clone(), modifiers)
{
self.perform_key_assignment(&pane, &action).ok();
return;
}
}
}
let mouse_event = wezterm_term::MouseEvent {
kind: match event.kind {
WMEK::Move => TMEK::Move,
WMEK::VertWheel(_) | WMEK::HorzWheel(_) | WMEK::Press(_) => TMEK::Press,
WMEK::Release(_) => TMEK::Release,
},
button: match event.kind {
WMEK::Release(ref press) | WMEK::Press(ref press) => mouse_press_to_tmb(press),
WMEK::Move => {
if event.mouse_buttons == WMB::LEFT {
TMB::Left
} else if event.mouse_buttons == WMB::RIGHT {
TMB::Right
} else if event.mouse_buttons == WMB::MIDDLE {
TMB::Middle
} else {
TMB::None
}
}
WMEK::VertWheel(amount) => {
if amount > 0 {
TMB::WheelUp(amount as usize)
} else {
TMB::WheelDown((-amount) as usize)
}
}
WMEK::HorzWheel(_) => TMB::None,
},
x,
y,
modifiers: window_mods_to_termwiz_mods(event.modifiers),
};
pane.mouse_event(mouse_event).ok();
match event.kind {
WMEK::Move => {}
_ => {
context.invalidate();
}
}
}
}
+113 -2
View File
@@ -1,8 +1,12 @@
use crate::gui::glium::texture::SrgbTexture2d;
use crate::gui::glyphcache::{CachedGlyph, GlyphCache};
use crate::gui::shapecache::*;
use crate::gui::termwindow::{
rgbcolor_alpha_to_window_color, rgbcolor_to_window_color, BorrowedShapeCacheKey, MappedQuads,
BorrowedShapeCacheKey, MappedQuads,
RenderState, ScrollHit, ShapedInfo,
};
use ::window::bitmaps::{Texture2d, TextureCoord, TextureRect, TextureSize};
use ::window::bitmaps::atlas::OutOfTextureSpace;
use ::window::bitmaps::{TextureCoord, TextureRect, TextureSize};
use ::window::glium;
use ::window::glium::uniforms::{
MagnifySamplerFilter, MinifySamplerFilter, Sampler, SamplerWrapFunction,
@@ -10,17 +14,21 @@ use ::window::glium::uniforms::{
use ::window::glium::{uniform, BlendingFunction, LinearBlendingFactor, Surface};
use anyhow::anyhow;
use config::ConfigHandle;
use config::TextStyle;
use mux::pane::Pane;
use mux::renderable::{RenderableDimensions, StableCursorPosition};
use mux::tab::{PositionedPane, PositionedSplit, SplitDirection};
use std::ops::Range;
use std::rc::Rc;
use std::sync::Arc;
use termwiz::cellcluster::CellCluster;
use termwiz::surface::{CursorShape, CursorVisibility};
use wezterm_font::units::PixelLength;
use wezterm_font::GlyphInfo;
use wezterm_term::color::{ColorAttribute, ColorPalette, RgbColor};
use wezterm_term::{CellAttributes, Line, StableRowIndex};
use window::bitmaps::atlas::SpriteSlice;
use window::bitmaps::Texture2d;
use window::Color;
pub struct RenderScreenLineOpenGLParams<'a> {
@@ -58,6 +66,60 @@ pub struct ComputeCellFgBgResult {
}
impl super::TermWindow {
pub fn paint_impl(&mut self, frame: &mut glium::Frame) {
self.check_for_config_reload();
let start = std::time::Instant::now();
{
let background_alpha = (self.config.window_background_opacity * 255.0) as u8;
let palette = self.palette();
let background = rgbcolor_alpha_to_window_color(palette.background, background_alpha);
let (r, g, b, a) = background.to_tuple_rgba();
frame.clear_color_srgb(r, g, b, a);
}
for pass in 0.. {
match self.paint_opengl_pass() {
Ok(_) => break,
Err(err) => {
if let Some(&OutOfTextureSpace { size: Some(size) }) =
err.downcast_ref::<OutOfTextureSpace>()
{
let result = if pass == 0 {
// Let's try clearing out the atlas and trying again
self.shape_cache.borrow_mut().clear();
self.render_state
.as_mut()
.unwrap()
.clear_texture_atlas(&self.render_metrics)
} else {
log::trace!("grow texture atlas to {}", size);
self.recreate_texture_atlas(Some(size))
};
if let Err(err) = result {
log::error!(
"Failed to {} texture: {}",
if pass == 0 { "clear" } else { "resize" },
err
);
break;
}
} else {
log::error!("paint_opengl_pass failed: {:#}", err);
break;
}
}
}
}
self.call_draw(frame).ok();
log::debug!("paint_pane_opengl elapsed={:?}", start.elapsed());
metrics::histogram!("gui.paint.opengl", start.elapsed());
self.update_title();
}
pub fn paint_pane_opengl(&mut self, pos: &PositionedPane) -> anyhow::Result<()> {
let config = &self.config;
let palette = pos.pane.palette();
@@ -988,4 +1050,53 @@ impl super::TermWindow {
},
}
}
fn glyph_infos_to_glyphs(
&self,
cluster: &CellCluster,
line: &Line,
style: &TextStyle,
glyph_cache: &mut GlyphCache<SrgbTexture2d>,
infos: &[GlyphInfo],
) -> anyhow::Result<Vec<Rc<CachedGlyph<SrgbTexture2d>>>> {
let mut glyphs = vec![];
for info in infos {
let cell_idx = cluster.byte_to_cell_idx[info.cluster as usize];
let followed_by_space = match line.cells().get(cell_idx + 1) {
Some(cell) => cell.str() == " ",
None => false,
};
glyphs.push(glyph_cache.cached_glyph(info, &style, followed_by_space)?);
}
Ok(glyphs)
}
fn lookup_cached_shape(
&self,
key: &dyn ShapeCacheKeyTrait,
) -> Option<anyhow::Result<Rc<Vec<ShapedInfo<SrgbTexture2d>>>>> {
match self.shape_cache.borrow_mut().get(key) {
Some(Ok(info)) => Some(Ok(Rc::clone(info))),
Some(Err(err)) => Some(Err(anyhow!("cached shaper error: {}", err))),
None => None,
}
}
fn recreate_texture_atlas(&mut self, size: Option<usize>) -> anyhow::Result<()> {
self.shape_cache.borrow_mut().clear();
self.render_state.as_mut().unwrap().recreate_texture_atlas(
&self.fonts,
&self.render_metrics,
size,
)
}
}
fn rgbcolor_to_window_color(color: RgbColor) -> Color {
rgbcolor_alpha_to_window_color(color, 0xff)
}
fn rgbcolor_alpha_to_window_color(color: RgbColor, alpha: u8) -> Color {
Color::rgba(color.red, color.green, color.blue, alpha)
}