diff --git a/Cargo.toml b/Cargo.toml index 2ceb18b8b..e30380bf7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -56,8 +56,6 @@ window = { path = "window", features=["opengl"]} zstd = "0.4" [target.'cfg(unix)'.dependencies] -mio = {version="0.6", optional=true} -mio-extras = {version="2.0", optional=true} daemonize = "0.4" [dependencies.fontconfig] @@ -83,14 +81,9 @@ winapi = { version = "0.3", features = [ ]} [target.'cfg(any(target_os = "android", all(unix, not(target_os = "macos"))))'.dependencies] -egli = "0.4" fontconfig = { path = "deps/fontconfig" } -x11 = {version ="2.18", features = ["xlib_xcb"]} [target.'cfg(all(unix, not(target_os = "macos")))'.dependencies] -xcb = "0.8" -xcb-util = { features = [ "icccm", "ewmh", "keysyms", ], version = "0.2" } -xkbcommon = { version = "0.4", features = ["x11"] } openssl = "0.10" [target.'cfg(target_os = "macos")'.dependencies] @@ -102,7 +95,7 @@ core-text = "13.2" [features] default = ["enable-winit"] force-fontconfig = ["fontconfig"] -enable-winit = ["winit", "glium", "mio", "mio-extras"] +enable-winit = ["winit", "glium"] [workspace] diff --git a/src/frontend/mod.rs b/src/frontend/mod.rs index 367ff10b8..43111e662 100644 --- a/src/frontend/mod.rs +++ b/src/frontend/mod.rs @@ -17,13 +17,10 @@ pub mod glium; pub mod guicommon; pub mod muxserver; pub mod software; -#[cfg(all(unix, feature = "enable-winit", not(target_os = "macos")))] -pub mod xwindows; #[derive(Debug, Deserialize, Clone, Copy, PartialEq, Eq)] pub enum FrontEndSelection { Glutin, - X11, MuxServer, Null, Software, @@ -32,12 +29,8 @@ pub enum FrontEndSelection { impl Default for FrontEndSelection { fn default() -> Self { - if cfg!(all( - unix, - feature = "enable-winit", - not(target_os = "macos") - )) { - FrontEndSelection::X11 + if cfg!(all(unix, not(target_os = "macos"))) { + FrontEndSelection::OpenGL } else if cfg!(feature = "enable-winit") { FrontEndSelection::Glutin } else { @@ -78,10 +71,6 @@ impl FrontEndSelection { FrontEndSelection::Glutin => glium::glutinloop::GlutinFrontEnd::try_new(mux), #[cfg(not(feature = "enable-winit"))] FrontEndSelection::Glutin => failure::bail!("Glutin not compiled in"), - #[cfg(all(unix, feature = "enable-winit", not(target_os = "macos")))] - FrontEndSelection::X11 => xwindows::x11loop::X11FrontEnd::try_new(mux), - #[cfg(not(all(unix, feature = "enable-winit", not(target_os = "macos"))))] - FrontEndSelection::X11 => failure::bail!("X11 not compiled in"), FrontEndSelection::MuxServer => muxserver::MuxServerFrontEnd::try_new(mux), FrontEndSelection::Null => muxserver::MuxServerFrontEnd::new_null(mux), FrontEndSelection::Software => software::SoftwareFrontEnd::try_new_no_opengl(mux), @@ -96,7 +85,7 @@ impl FrontEndSelection { // TODO: find or build a proc macro for this pub fn variants() -> Vec<&'static str> { - vec!["Glutin", "X11", "MuxServer", "Null", "Software", "OpenGL"] + vec!["Glutin", "MuxServer", "Null", "Software", "OpenGL"] } } @@ -105,7 +94,6 @@ impl std::str::FromStr for FrontEndSelection { fn from_str(s: &str) -> Result { match s.to_lowercase().as_ref() { "glutin" => Ok(FrontEndSelection::Glutin), - "x11" => Ok(FrontEndSelection::X11), "muxserver" => Ok(FrontEndSelection::MuxServer), "null" => Ok(FrontEndSelection::Null), "software" => Ok(FrontEndSelection::Software), diff --git a/src/frontend/xwindows/keyboard.rs b/src/frontend/xwindows/keyboard.rs deleted file mode 100644 index 3be66d09d..000000000 --- a/src/frontend/xwindows/keyboard.rs +++ /dev/null @@ -1,274 +0,0 @@ -use super::xkeysyms::keysym_to_keycode; -use super::Error; -use super::{KeyCode, KeyModifiers}; -use failure::{ensure, format_err}; -use libc; -use log::debug; -use std::cell::RefCell; -use std::ffi::CStr; -use xkb::compose::Status as ComposeStatus; -use xkbcommon::xkb; - -pub struct Keyboard { - context: xkb::Context, - keymap: RefCell, - device_id: i32, - - state: RefCell, - compose_state: RefCell, -} - -impl Keyboard { - pub fn new(connection: &xcb::Connection) -> Result<(Keyboard, u8), Error> { - connection.prefetch_extension_data(xcb::xkb::id()); - - let first_ev = connection - .get_extension_data(xcb::xkb::id()) - .map(|r| r.first_event()) - .ok_or_else(|| format_err!("could not get xkb extension data"))?; - - { - let cookie = xcb::xkb::use_extension( - &connection, - xkb::x11::MIN_MAJOR_XKB_VERSION, - xkb::x11::MIN_MINOR_XKB_VERSION, - ); - let r = cookie.get_reply()?; - - ensure!( - r.supported(), - "required xcb-xkb-{}-{} is not supported", - xkb::x11::MIN_MAJOR_XKB_VERSION, - xkb::x11::MIN_MINOR_XKB_VERSION - ); - } - - let context = xkb::Context::new(xkb::CONTEXT_NO_FLAGS); - let device_id = xkb::x11::get_core_keyboard_device_id(&connection); - ensure!(device_id != -1, "Couldn't find core keyboard device"); - - let keymap = xkb::x11::keymap_new_from_device( - &context, - &connection, - device_id, - xkb::KEYMAP_COMPILE_NO_FLAGS, - ); - let state = xkb::x11::state_new_from_device(&keymap, &connection, device_id); - - let locale = query_lc_ctype()?; - - let table = xkb::compose::Table::new_from_locale( - &context, - locale.to_str()?, - xkb::compose::COMPILE_NO_FLAGS, - ) - .map_err(|()| format_err!("Failed to acquire compose table from locale"))?; - let compose_state = xkb::compose::State::new(&table, xkb::compose::STATE_NO_FLAGS); - - { - let map_parts = xcb::xkb::MAP_PART_KEY_TYPES - | xcb::xkb::MAP_PART_KEY_SYMS - | xcb::xkb::MAP_PART_MODIFIER_MAP - | xcb::xkb::MAP_PART_EXPLICIT_COMPONENTS - | xcb::xkb::MAP_PART_KEY_ACTIONS - | xcb::xkb::MAP_PART_KEY_BEHAVIORS - | xcb::xkb::MAP_PART_VIRTUAL_MODS - | xcb::xkb::MAP_PART_VIRTUAL_MOD_MAP; - - let events = xcb::xkb::EVENT_TYPE_NEW_KEYBOARD_NOTIFY - | xcb::xkb::EVENT_TYPE_MAP_NOTIFY - | xcb::xkb::EVENT_TYPE_STATE_NOTIFY; - - let cookie = xcb::xkb::select_events_checked( - &connection, - device_id as u16, - events as u16, - 0, - events as u16, - map_parts as u16, - map_parts as u16, - None, - ); - - cookie.request_check()?; - } - - let kbd = Keyboard { - context, - device_id, - keymap: RefCell::new(keymap), - state: RefCell::new(state), - compose_state: RefCell::new(compose_state), - }; - - Ok((kbd, first_ev)) - } - - pub fn process_key_event( - &self, - xcb_ev: &xcb::KeyPressEvent, - ) -> Option<(KeyCode, KeyModifiers)> { - let pressed = (xcb_ev.response_type() & !0x80) == xcb::KEY_PRESS; - - if !pressed { - return None; - } - - let xcode = xkb::Keycode::from(xcb_ev.detail()); - let xsym = self.state.borrow().key_get_one_sym(xcode); - self.compose_state.borrow_mut().feed(xsym); - - let cstate = self.compose_state.borrow().status(); - let ksym = match cstate { - ComposeStatus::Composing => { - // eat - return None; - } - ComposeStatus::Composed => { - let res = self.compose_state.borrow().keysym(); - self.compose_state.borrow_mut().reset(); - res.unwrap_or(xsym) - } - ComposeStatus::Nothing => xsym, - ComposeStatus::Cancelled => { - self.compose_state.borrow_mut().reset(); - return None; - } - }; - - // could be from_u32_unchecked - let ks_char = std::char::from_u32(xkb::keysym_to_utf32(ksym)); - - let kc = match ks_char { - Some(c) if (c as u32) >= 0x20 && (c as u32) != 0x7f => KeyCode::Char(c), - _ => { - if let Some(key) = keysym_to_keycode(xsym) { - key - } else { - debug!("xkbc:Missing xcb keysym {} definition", xsym); - return None; - } - } - }; - - Some((kc, self.get_key_modifiers())) - } - - fn mod_is_active(&self, modifier: &str) -> bool { - // [TODO] consider state Depressed & consumed mods - self.state - .borrow() - .mod_name_is_active(modifier, xkb::STATE_MODS_EFFECTIVE) - } - - pub fn get_key_modifiers(&self) -> KeyModifiers { - let mut res = KeyModifiers::default(); - - if self.mod_is_active(xkb::MOD_NAME_SHIFT) { - res |= KeyModifiers::SHIFT; - } - if self.mod_is_active(xkb::MOD_NAME_CTRL) { - res |= KeyModifiers::CTRL; - } - if self.mod_is_active(xkb::MOD_NAME_ALT) { - // Mod1 - res |= KeyModifiers::ALT; - } - if self.mod_is_active(xkb::MOD_NAME_LOGO) { - // Mod4 - res |= KeyModifiers::SUPER; - } - if self.mod_is_active("Mod3") { - res |= KeyModifiers::SUPER; - } - //Mod2 is numlock - res - } - - pub fn process_xkb_event( - &self, - connection: &xcb::Connection, - event: &xcb::GenericEvent, - ) -> Result<(), Error> { - let xkb_ev: &XkbGenericEvent = unsafe { xcb::cast_event(&event) }; - - if xkb_ev.device_id() == self.get_device_id() as u8 { - match xkb_ev.xkb_type() { - xcb::xkb::STATE_NOTIFY => { - self.update_state(unsafe { xcb::cast_event(&event) }); - } - xcb::xkb::MAP_NOTIFY | xcb::xkb::NEW_KEYBOARD_NOTIFY => { - self.update_keymap(connection)?; - } - _ => {} - } - } - Ok(()) - } - // for convenience, this fn takes &self, not &mut self - pub fn update_state(&self, ev: &xcb::xkb::StateNotifyEvent) { - self.state.borrow_mut().update_mask( - xkb::ModMask::from(ev.base_mods()), - xkb::ModMask::from(ev.latched_mods()), - xkb::ModMask::from(ev.locked_mods()), - ev.base_group() as xkb::LayoutIndex, - ev.latched_group() as xkb::LayoutIndex, - xkb::LayoutIndex::from(ev.locked_group()), - ); - } - - pub fn update_keymap(&self, connection: &xcb::Connection) -> Result<(), Error> { - let new_keymap = xkb::x11::keymap_new_from_device( - &self.context, - &connection, - self.get_device_id(), - xkb::KEYMAP_COMPILE_NO_FLAGS, - ); - ensure!( - !new_keymap.get_raw_ptr().is_null(), - "problem with new keymap" - ); - - let new_state = xkb::x11::state_new_from_device(&new_keymap, &connection, self.device_id); - ensure!(!new_state.get_raw_ptr().is_null(), "problem with new state"); - - self.state.replace(new_state); - self.keymap.replace(new_keymap); - Ok(()) - } - - pub fn get_device_id(&self) -> i32 { - self.device_id - } -} - -fn query_lc_ctype() -> Result<&'static CStr, Error> { - let ptr = unsafe { libc::setlocale(libc::LC_CTYPE, std::ptr::null()) }; - ensure!(!ptr.is_null(), "failed to query locale"); - unsafe { Ok(CStr::from_ptr(ptr)) } -} - -/// struct that has fields common to the 3 different xkb events -/// (StateNotify, NewKeyboardNotify, MapNotify) -#[repr(C)] -struct xcb_xkb_generic_event_t { - response_type: u8, - xkb_type: u8, - sequence: u16, - time: xcb::Timestamp, - device_id: u8, -} - -struct XkbGenericEvent { - base: xcb::Event, -} - -impl XkbGenericEvent { - pub fn xkb_type(&self) -> u8 { - unsafe { (*self.base.ptr).xkb_type } - } - - pub fn device_id(&self) -> u8 { - unsafe { (*self.base.ptr).device_id } - } -} diff --git a/src/frontend/xwindows/mod.rs b/src/frontend/xwindows/mod.rs deleted file mode 100644 index cd53f9ff2..000000000 --- a/src/frontend/xwindows/mod.rs +++ /dev/null @@ -1,395 +0,0 @@ -use log::debug; -use term::{KeyCode, KeyModifiers}; -mod keyboard; -use egli; -use failure::{bail, err_msg, format_err, Error}; -use glium; -use glium::backend::Backend; -use keyboard::Keyboard; -use mio::unix::EventedFd; -use mio::{Evented, Poll, PollOpt, Ready, Token}; -use std::cell::RefCell; -use std::io; -use std::mem; -use std::ops::Deref; -use std::os; -use std::os::unix::io::AsRawFd; -use std::ptr; -use std::rc::Rc; -use std::result; -use x11; -use xcb; -use xcb_util; -use xcb_util::ffi::keysyms::{xcb_key_symbols_alloc, xcb_key_symbols_free, xcb_key_symbols_t}; - -pub type Result = result::Result; - -mod xkeysyms; -pub use self::xkeysyms::*; -pub mod x11loop; -pub mod xwin; - -pub struct Connection { - pub display: *mut x11::xlib::Display, - conn: xcb::Connection, - screen_num: i32, - pub keyboard: Keyboard, - pub kbd_ev: u8, - pub atom_protocols: xcb::Atom, - pub atom_delete: xcb::Atom, - pub atom_utf8_string: xcb::Atom, - pub atom_xsel_data: xcb::Atom, - pub atom_targets: xcb::Atom, - pub atom_clipboard: xcb::Atom, - keysyms: *mut xcb_key_symbols_t, - egl_display: Rc, - egl_config: egli::FrameBufferConfigRef, -} - -impl Deref for Connection { - type Target = xcb::Connection; - - fn deref(&self) -> &xcb::Connection { - &self.conn - } -} - -impl Evented for Connection { - fn register( - &self, - poll: &Poll, - token: Token, - interest: Ready, - opts: PollOpt, - ) -> io::Result<()> { - EventedFd(&self.conn.as_raw_fd()).register(poll, token, interest, opts) - } - - fn reregister( - &self, - poll: &Poll, - token: Token, - interest: Ready, - opts: PollOpt, - ) -> io::Result<()> { - EventedFd(&self.conn.as_raw_fd()).reregister(poll, token, interest, opts) - } - - fn deregister(&self, poll: &Poll) -> io::Result<()> { - EventedFd(&self.conn.as_raw_fd()).deregister(poll) - } -} - -#[link(name = "X11-xcb")] -extern "C" { - fn XGetXCBConnection(display: *mut x11::xlib::Display) -> *mut xcb::ffi::xcb_connection_t; - fn XSetEventQueueOwner(display: *mut x11::xlib::Display, owner: i32); -} - -fn egli_err(err: egli::error::Error) -> Error { - format_err!("egli error: {:?}", err) -} - -impl Connection { - pub fn new() -> Result { - let display = unsafe { x11::xlib::XOpenDisplay(ptr::null()) }; - if display.is_null() { - bail!("failed to open display"); - } - let screen_num = unsafe { x11::xlib::XDefaultScreen(display) }; - let conn = unsafe { xcb::Connection::from_raw_conn(XGetXCBConnection(display)) }; - unsafe { XSetEventQueueOwner(display, 1) }; - - let atom_protocols = xcb::intern_atom(&conn, false, "WM_PROTOCOLS") - .get_reply()? - .atom(); - let atom_delete = xcb::intern_atom(&conn, false, "WM_DELETE_WINDOW") - .get_reply()? - .atom(); - let atom_utf8_string = xcb::intern_atom(&conn, false, "UTF8_STRING") - .get_reply()? - .atom(); - let atom_xsel_data = xcb::intern_atom(&conn, false, "XSEL_DATA") - .get_reply()? - .atom(); - let atom_targets = xcb::intern_atom(&conn, false, "TARGETS") - .get_reply()? - .atom(); - let atom_clipboard = xcb::intern_atom(&conn, false, "CLIPBOARD") - .get_reply()? - .atom(); - - let keysyms = unsafe { xcb_key_symbols_alloc(conn.get_raw_conn()) }; - - let egl_display = egli::Display::from_display_id(display as *mut _).map_err(egli_err)?; - - let egl_version = egl_display.initialize_and_get_version().map_err(egli_err)?; - debug!("Using EGL {}", egl_version); - - let configs = egl_display - .config_filter() - .with_red_size(8) - .with_green_size(8) - .with_blue_size(8) - .with_depth_size(24) - .with_surface_type( - egli::SurfaceType::WINDOW | egli::SurfaceType::PBUFFER | egli::SurfaceType::PIXMAP, - ) - .with_renderable_type(egli::RenderableType::OPENGL_ES2) - .with_conformant(egli::RenderableType::OPENGL_ES2) - .choose_configs() - .map_err(|e| format_err!("failed to get EGL config: {:?}", e))?; - - let first_config = *configs - .first() - .ok_or_else(|| err_msg("no compatible EGL configuration was found"))?; - - let (keyboard, kbd_ev) = Keyboard::new(&conn)?; - Ok(Connection { - display, - conn, - screen_num, - keyboard, - kbd_ev, - atom_protocols, - atom_clipboard, - atom_delete, - keysyms, - atom_utf8_string, - atom_xsel_data, - atom_targets, - egl_display: Rc::new(egl_display), - egl_config: first_config, - }) - } - - pub fn conn(&self) -> &xcb::Connection { - &self.conn - } - - pub fn screen_num(&self) -> i32 { - self.screen_num - } - - pub fn atom_delete(&self) -> xcb::Atom { - self.atom_delete - } - - pub fn xkb_lookup_keysym(&self, event: &xcb::KeyPressEvent) -> Option<(KeyCode, KeyModifiers)> { - self.keyboard.process_key_event(event) - } -} - -impl Drop for Connection { - fn drop(&mut self) { - unsafe { - xcb_key_symbols_free(self.keysyms); - } - } -} - -struct WindowHolder { - window_id: xcb::xproto::Window, - conn: Rc, -} - -impl Drop for WindowHolder { - fn drop(&mut self) { - xcb::destroy_window(self.conn.conn(), self.window_id); - } -} - -struct GlState { - display: Rc, - surface: egli::Surface, - egl_context: egli::Context, - _window: Rc, -} - -/// A Window! -pub struct Window { - window: Rc, - conn: Rc, - gl: Rc, - glium_context: Rc, -} - -impl Window { - /// Create a new window on the specified screen with the specified - /// dimensions - pub fn new(conn: &Rc, width: u16, height: u16) -> Result { - let window = { - let setup = conn.conn().get_setup(); - let screen = setup - .roots() - .nth(conn.screen_num() as usize) - .ok_or_else(|| err_msg("no screen?"))?; - - let window_id = conn.conn().generate_id(); - - xcb::create_window_checked( - conn.conn(), - xcb::COPY_FROM_PARENT as u8, - window_id, - screen.root(), - // x, y - 0, - 0, - // width, height - width, - height, - // border width - 0, - xcb::WINDOW_CLASS_INPUT_OUTPUT as u16, - screen.root_visual(), - &[( - xcb::CW_EVENT_MASK, - xcb::EVENT_MASK_EXPOSURE - | xcb::EVENT_MASK_KEY_PRESS - | xcb::EVENT_MASK_BUTTON_PRESS - | xcb::EVENT_MASK_BUTTON_RELEASE - | xcb::EVENT_MASK_POINTER_MOTION - | xcb::EVENT_MASK_BUTTON_MOTION - | xcb::EVENT_MASK_KEY_RELEASE - | xcb::EVENT_MASK_STRUCTURE_NOTIFY, - )], - ) - .request_check()?; - Rc::new(WindowHolder { - window_id, - conn: Rc::clone(conn), - }) - }; - - xcb::change_property( - &*conn, - xcb::PROP_MODE_REPLACE as u8, - window.window_id, - conn.atom_protocols, - 4, - 32, - &[conn.atom_delete], - ); - - let surface = conn - .egl_display - .create_window_surface(conn.egl_config, window.window_id as *mut _) - .map_err(egli_err)?; - - let egl_context = conn - .egl_display - .create_context_with_client_version( - conn.egl_config, - egli::ContextClientVersion::OpenGlEs2, - ) - .map_err(egli_err)?; - - conn.egl_display - .make_current(&surface, &surface, &egl_context) - .map_err(egli_err)?; - - let gl_state = Rc::new(GlState { - display: Rc::clone(&conn.egl_display), - egl_context, - surface, - _window: Rc::clone(&window), - }); - - let glium_context = unsafe { - glium::backend::Context::new( - Rc::clone(&gl_state), - true, - if cfg!(debug_assertions) { - //glium::debug::DebugCallbackBehavior::PrintAll - glium::debug::DebugCallbackBehavior::DebugMessageOnError - } else { - glium::debug::DebugCallbackBehavior::Ignore - }, - )? - }; - - Ok(Window { - conn: Rc::clone(conn), - window, - gl: gl_state, - glium_context, - }) - } - - /// Change the title for the window manager - pub fn set_title(&self, title: &str) { - xcb_util::icccm::set_wm_name(self.conn.conn(), self.window.window_id, title); - } - - /// Display the window - pub fn show(&self) { - xcb::map_window(self.conn.conn(), self.window.window_id); - } - - pub fn draw(&self) -> glium::Frame { - glium::Frame::new( - self.glium_context.clone(), - self.gl.get_framebuffer_dimensions(), - ) - } -} - -impl glium::backend::Facade for Window { - fn get_context(&self) -> &Rc { - &self.glium_context - } -} - -// We need to remember which context is current in a multi-window -// application, and OpenGL cares about this on a per-thread basis. -// Even though we're largely single threaded, it's worth making sure -// that we're tracking this for each thread. -thread_local!(static CURRENT: RefCell<*const GlState> = RefCell::new(ptr::null())); - -impl Drop for GlState { - fn drop(&mut self) { - // On drop, make sure that the current context doesn't refer - // to our dead, possibly recycled address. - CURRENT.with(|id| { - if *id.borrow_mut() == self as *const _ { - *id.borrow_mut() = ptr::null(); - } - }); - } -} - -unsafe impl glium::backend::Backend for GlState { - fn swap_buffers(&self) -> result::Result<(), glium::SwapBuffersError> { - self.display.swap_buffers(&self.surface).map_err(|_| { - // We're guessing that this is the case as the other option - // that glium recognizes is threading related and we're - // single threaded. - glium::SwapBuffersError::AlreadySwapped - }) - } - - unsafe fn get_proc_address(&self, symbol: &str) -> *const os::raw::c_void { - mem::transmute(egli::egl::get_proc_address(symbol)) - } - - fn get_framebuffer_dimensions(&self) -> (u32, u32) { - unsafe { - self.make_current(); - } - ( - self.surface.query_width().unwrap() as u32, - self.surface.query_height().unwrap() as u32, - ) - } - - fn is_current(&self) -> bool { - CURRENT.with(|id| *id.borrow() == self as *const _) - } - - unsafe fn make_current(&self) { - self.display - .make_current(&self.surface, &self.surface, &self.egl_context) - .expect("make_current failed"); - CURRENT.with(|id| *id.borrow_mut() = self as *const _); - } -} diff --git a/src/frontend/xwindows/x11loop.rs b/src/frontend/xwindows/x11loop.rs deleted file mode 100644 index c2593fd54..000000000 --- a/src/frontend/xwindows/x11loop.rs +++ /dev/null @@ -1,350 +0,0 @@ -use crate::config::Config; -use crate::font::FontConfiguration; -use crate::frontend::guicommon::window::TerminalWindow; -use crate::frontend::xwindows::xwin::X11TerminalWindow; -use crate::frontend::xwindows::Connection; -use crate::frontend::FrontEnd; -use crate::mux::tab::Tab; -use crate::mux::window::WindowId as MuxWindowId; -use crate::mux::Mux; -use failure::{bail, Error, Fallible}; -use log::debug; -use mio::{Events, Poll, PollOpt, Ready, Token}; -use mio_extras::channel::{channel, Receiver as GuiReceiver, Sender as GuiSender}; -use promise::{BasicExecutor, Executor, Future, SpawnFunc}; -use std::cell::RefCell; -use std::collections::HashMap; -use std::rc::Rc; -use std::sync::mpsc::TryRecvError; -use std::sync::Arc; -use std::time::{Duration, Instant}; -use xcb; - -#[cfg(all(unix, not(target_os = "macos")))] -pub use xcb::xproto::Window as WindowId; - -#[derive(Default)] -struct Windows { - by_id: HashMap, -} - -pub struct X11GuiExecutor { - tx: GuiSender, -} - -impl BasicExecutor for X11GuiExecutor { - fn execute(&self, f: SpawnFunc) { - self.tx.send(f).expect("X11GuiExecutor execute failed"); - } -} -impl Executor for X11GuiExecutor { - fn clone_executor(&self) -> Box { - Box::new(X11GuiExecutor { - tx: self.tx.clone(), - }) - } -} - -pub struct GuiEventLoop { - poll: Poll, - pub conn: Rc, - windows: Rc>, - interval: Duration, - gui_rx: GuiReceiver, - gui_tx: GuiSender, - mux: Rc, -} - -const TOK_XCB: usize = 0xffff_fffc; -const TOK_GUI_EXEC: usize = 0xffff_fffd; - -pub struct X11FrontEnd { - event_loop: Rc, -} -impl X11FrontEnd { - pub fn try_new(mux: &Rc) -> Result, Error> { - let event_loop = Rc::new(GuiEventLoop::new(mux)?); - X11_EVENT_LOOP.with(|f| *f.borrow_mut() = Some(Rc::clone(&event_loop))); - Ok(Rc::new(Self { event_loop })) - } -} - -thread_local! { - static X11_EVENT_LOOP: RefCell>> = RefCell::new(None); -} - -impl FrontEnd for X11FrontEnd { - fn gui_executor(&self) -> Box { - self.event_loop.gui_executor() - } - - fn run_forever(&self) -> Result<(), Error> { - self.event_loop.run() - } - - fn spawn_new_window( - &self, - config: &Arc, - fontconfig: &Rc, - tab: &Rc, - window_id: MuxWindowId, - ) -> Fallible<()> { - let window = X11TerminalWindow::new(&self.event_loop, fontconfig, config, tab, window_id)?; - self.event_loop.add_window(window) - } -} - -impl GuiEventLoop { - pub fn new(mux: &Rc) -> Result { - let poll = Poll::new()?; - - let conn = Rc::new(Connection::new()?); - - poll.register(&*conn, Token(TOK_XCB), Ready::readable(), PollOpt::level())?; - - let (gui_tx, gui_rx) = channel(); - poll.register( - &gui_rx, - Token(TOK_GUI_EXEC), - Ready::readable(), - PollOpt::level(), - )?; - - Ok(Self { - conn, - poll, - gui_tx, - gui_rx, - interval: Duration::from_millis(50), - windows: Rc::new(RefCell::new(Default::default())), - mux: Rc::clone(mux), - }) - } - - pub fn get() -> Option> { - let mut res = None; - X11_EVENT_LOOP.with(|f| { - if let Some(me) = &*f.borrow() { - res = Some(Rc::clone(me)); - } - }); - res - } - - fn gui_executor(&self) -> Box { - Box::new(X11GuiExecutor { - tx: self.gui_tx.clone(), - }) - } - - fn run(&self) -> Result<(), Error> { - let mut events = Events::with_capacity(8); - - let tok_xcb = Token(TOK_XCB); - let tok_gui = Token(TOK_GUI_EXEC); - - self.conn.flush(); - let mut last_interval = Instant::now(); - - loop { - let now = Instant::now(); - let diff = now - last_interval; - let period = if diff >= self.interval { - self.do_paint(); - last_interval = now; - self.interval - } else { - self.interval - diff - }; - - match self.poll.poll(&mut events, Some(period)) { - Ok(_) => { - for event in &events { - let t = event.token(); - if t == tok_xcb { - self.process_queued_xcb()?; - } else if t == tok_gui { - self.process_gui_exec()?; - } else { - } - } - self.process_sigchld(); - // Check the window count; if after processing the futures there - // are no windows left, then we are done. - if self.mux.is_empty() { - debug!("No more windows; done!"); - return Ok(()); - } - } - - Err(err) => { - bail!("polling for events: {:?}", err); - } - } - } - } - - /// Run a function with access to the mutable version of the window with - /// the specified window id - pub fn with_window Result<(), Error>>( - &self, - window_id: WindowId, - func: F, - ) -> Result<(), Error> { - Future::with_executor( - X11GuiExecutor { - tx: self.gui_tx.clone(), - }, - move || { - let myself = Self::get().expect("to be called on gui thread"); - let mut windows = myself.windows.borrow_mut(); - if let Some(window) = windows.by_id.get_mut(&window_id) { - func(window) - } else { - bail!("no such window {:?}", window_id); - } - }, - ); - Ok(()) - } - - pub fn add_window(&self, window: X11TerminalWindow) -> Result<(), Error> { - let window_id = window.window_id(); - - let mut windows = self.windows.borrow_mut(); - - windows.by_id.insert(window_id, window); - Ok(()) - } - - fn process_gui_exec(&self) -> Result<(), Error> { - match self.gui_rx.try_recv() { - Ok(func) => func(), - Err(TryRecvError::Empty) => return Ok(()), - Err(err) => bail!("poll_rx disconnected {:?}", err), - } - Ok(()) - } - - fn schedule_window_close(&self, window_id: WindowId) -> Result<(), Error> { - debug!("schedule_window_close {:?}", window_id); - - let mut windows = self.windows.borrow_mut(); - windows.by_id.remove(&window_id); - - Ok(()) - } - - fn process_window_event( - &self, - window_id: WindowId, - event: &xcb::GenericEvent, - ) -> Result<(), Error> { - let mut windows = self.windows.borrow_mut(); - if let Some(window) = windows.by_id.get_mut(&window_id) { - window.dispatch_event(event)?; - } - Ok(()) - } - - fn window_id_from_event(event: &xcb::GenericEvent) -> Option { - match event.response_type() & 0x7f { - xcb::EXPOSE => { - let expose: &xcb::ExposeEvent = unsafe { xcb::cast_event(event) }; - Some(expose.window()) - } - xcb::CONFIGURE_NOTIFY => { - let cfg: &xcb::ConfigureNotifyEvent = unsafe { xcb::cast_event(event) }; - Some(cfg.window()) - } - xcb::KEY_PRESS | xcb::KEY_RELEASE => { - let key_press: &xcb::KeyPressEvent = unsafe { xcb::cast_event(event) }; - Some(key_press.event()) - } - xcb::MOTION_NOTIFY => { - let motion: &xcb::MotionNotifyEvent = unsafe { xcb::cast_event(event) }; - Some(motion.event()) - } - xcb::BUTTON_PRESS | xcb::BUTTON_RELEASE => { - let button_press: &xcb::ButtonPressEvent = unsafe { xcb::cast_event(event) }; - Some(button_press.event()) - } - xcb::CLIENT_MESSAGE => { - let msg: &xcb::ClientMessageEvent = unsafe { xcb::cast_event(event) }; - Some(msg.window()) - } - _ => None, - } - } - - fn process_xcb_event(&self, event: &xcb::GenericEvent) -> Result<(), Error> { - if let Some(window_id) = Self::window_id_from_event(event) { - self.process_window_event(window_id, event)?; - } else { - let r = event.response_type() & 0x7f; - if r == self.conn.kbd_ev { - // key press/release are not processed here. - // xkbcommon depends on those events in order to: - // - update modifiers state - // - update keymap/state on keyboard changes - self.conn.keyboard.process_xkb_event(&self.conn, event)?; - } - } - Ok(()) - } - - fn process_queued_xcb(&self) -> Result<(), Error> { - match self.conn.poll_for_event() { - None => match self.conn.has_error() { - Ok(_) => (), - Err(err) => { - bail!("clipboard window connection is broken: {:?}", err); - } - }, - Some(event) => match self.process_xcb_event(&event) { - Ok(_) => (), - Err(err) => return Err(err), - }, - } - self.conn.flush(); - - loop { - match self.conn.poll_for_queued_event() { - None => return Ok(()), - Some(event) => self.process_xcb_event(&event)?, - } - self.conn.flush(); - } - } - - /// Run through all of the windows and cause them to paint if they need it. - /// This happens ~50ms or so. - fn do_paint(&self) { - for window in &mut self.windows.borrow_mut().by_id.values_mut() { - window.paint_if_needed().unwrap(); - } - self.conn.flush(); - } - - /// If we were signalled by a child process completion, zip through - /// the windows and have then notice and prepare to close. - fn process_sigchld(&self) { - let window_ids: Vec = self - .windows - .borrow_mut() - .by_id - .iter_mut() - .filter_map(|(window_id, window)| { - if window.test_for_child_exit() { - Some(*window_id) - } else { - None - } - }) - .collect(); - - for window_id in window_ids { - self.schedule_window_close(window_id).ok(); - } - } -} diff --git a/src/frontend/xwindows/xkeysyms.rs b/src/frontend/xwindows/xkeysyms.rs deleted file mode 100644 index 64aa90a68..000000000 --- a/src/frontend/xwindows/xkeysyms.rs +++ /dev/null @@ -1,121 +0,0 @@ -use term::KeyCode; -use term::KeyModifiers; - -pub fn modifiers_from_state(state: u16) -> KeyModifiers { - use xcb::xproto::*; - - let mut mods = KeyModifiers::default(); - let state = u32::from(state); - - if state & MOD_MASK_SHIFT != 0 { - mods |= KeyModifiers::SHIFT; - } - if state & MOD_MASK_CONTROL != 0 { - mods |= KeyModifiers::CTRL; - } - if state & MOD_MASK_1 != 0 { - mods |= KeyModifiers::ALT; - } - if state & MOD_MASK_4 != 0 { - mods |= KeyModifiers::SUPER; - } - - mods -} - -/// Translates non-printable X11 keysym to termwiz::KeyCode -/// for missing keys, look into ```/usr/include/X11/keysymdef.h``` and/or define them in KeyCode. -/// If we can find a unicode representation of the input key then this function is skipped. -pub fn keysym_to_keycode(keysym: u32) -> Option { - use xkbcommon::xkb::keysyms::*; - #[allow(non_upper_case_globals)] - let res = match keysym { - KEY_Escape => KeyCode::Escape, - KEY_Tab => KeyCode::Tab, - - KEY_BackSpace => KeyCode::Backspace, - KEY_Return => KeyCode::Char(0xdu8 as char), - KEY_Insert => KeyCode::Insert, - KEY_Delete => KeyCode::Delete, - KEY_Clear => KeyCode::Delete, - KEY_Pause => KeyCode::Pause, - KEY_Print => KeyCode::Print, - - // cursor movement - KEY_Home => KeyCode::Home, - KEY_End => KeyCode::End, - KEY_Left => KeyCode::LeftArrow, - KEY_Up => KeyCode::UpArrow, - KEY_Right => KeyCode::RightArrow, - KEY_Down => KeyCode::DownArrow, - KEY_Page_Up => KeyCode::PageUp, - KEY_Page_Down => KeyCode::PageDown, - - // modifiers - KEY_Shift_L => KeyCode::Shift, - KEY_Shift_R => KeyCode::Shift, - - KEY_Control_L => KeyCode::Control, - KEY_Control_R => KeyCode::Control, - KEY_Alt_L => KeyCode::Alt, - KEY_Alt_R => KeyCode::Alt, - KEY_Caps_Lock => KeyCode::CapsLock, - KEY_Num_Lock => KeyCode::NumLock, - KEY_Scroll_Lock => KeyCode::ScrollLock, - KEY_Super_L => KeyCode::Super, - KEY_Super_R => KeyCode::Super, - KEY_Menu => KeyCode::Menu, - KEY_Help => KeyCode::Help, - - KEY_F1 => KeyCode::Function(1), - KEY_F2 => KeyCode::Function(2), - KEY_F3 => KeyCode::Function(3), - KEY_F4 => KeyCode::Function(4), - KEY_F5 => KeyCode::Function(5), - KEY_F6 => KeyCode::Function(6), - KEY_F7 => KeyCode::Function(7), - KEY_F8 => KeyCode::Function(8), - KEY_F9 => KeyCode::Function(9), - KEY_F10 => KeyCode::Function(10), - KEY_F11 => KeyCode::Function(11), - KEY_F12 => KeyCode::Function(12), - - // numeric and function keypad keys - KEY_KP_Enter => KeyCode::Char(0xdu8 as char), - KEY_KP_Delete => KeyCode::Delete, - KEY_KP_Home => KeyCode::Home, - KEY_KP_Page_Up => KeyCode::PageUp, - KEY_KP_Page_Down => KeyCode::PageDown, - KEY_KP_Multiply => KeyCode::Multiply, - KEY_KP_Add => KeyCode::Add, - KEY_KP_Divide => KeyCode::Divide, - KEY_KP_Subtract => KeyCode::Subtract, - KEY_KP_Decimal => KeyCode::Decimal, - KEY_KP_Separator => KeyCode::Separator, - - KEY_KP_0 => KeyCode::Numpad0, - KEY_KP_1 => KeyCode::Numpad1, - KEY_KP_2 => KeyCode::Numpad2, - KEY_KP_3 => KeyCode::Numpad3, - KEY_KP_4 => KeyCode::Numpad4, - KEY_KP_6 => KeyCode::Numpad6, - KEY_KP_7 => KeyCode::Numpad7, - KEY_KP_8 => KeyCode::Numpad8, - KEY_KP_9 => KeyCode::Numpad9, - - KEY_XF86Back => KeyCode::BrowserBack, - KEY_XF86Forward => KeyCode::BrowserForward, - KEY_XF86Stop => KeyCode::BrowserStop, - KEY_XF86Refresh => KeyCode::BrowserRefresh, - KEY_XF86Favorites => KeyCode::BrowserFavorites, - KEY_XF86HomePage => KeyCode::BrowserHome, - - KEY_XF86AudioLowerVolume => KeyCode::VolumeDown, - KEY_XF86AudioMute => KeyCode::VolumeMute, - KEY_XF86AudioRaiseVolume => KeyCode::VolumeUp, - _ => { - return None; - } - }; - Some(res) -} diff --git a/src/frontend/xwindows/xwin.rs b/src/frontend/xwindows/xwin.rs deleted file mode 100644 index 409b25612..000000000 --- a/src/frontend/xwindows/xwin.rs +++ /dev/null @@ -1,262 +0,0 @@ -use super::xkeysyms; -use super::{Connection, Window}; -use crate::config::Config; -use crate::font::FontConfiguration; -use crate::frontend::guicommon::host::{HostHelper, HostImpl, TabHost}; -use crate::frontend::guicommon::window::{Dimensions, TerminalWindow}; -use crate::frontend::xwindows::x11loop::{GuiEventLoop, WindowId as X11WindowId}; -use crate::mux::tab::Tab; -use crate::mux::window::WindowId; -use crate::mux::{Mux, SessionTerminated}; -use crate::opengl::render::Renderer; -use failure::Error; -use log::{debug, error}; -use std::rc::Rc; -use std::sync::Arc; -use term::{self, KeyCode, KeyModifiers, MouseButton, MouseEvent, MouseEventKind}; -use xcb; - -/// Holds most of the information we need to implement `TerminalHost` -struct Host { - window: Window, - event_loop: Rc, - fonts: Rc, - config: Arc, -} - -impl HostHelper for Host { - fn with_window Result<(), Error>>( - &self, - func: F, - ) { - let window_id = self.window.window.window_id; - self.event_loop.with_window(window_id, func).ok(); - } - - fn toggle_full_screen(&mut self) {} -} - -pub struct X11TerminalWindow { - host: HostImpl, - conn: Rc, - renderer: Renderer, - width: u16, - height: u16, - cell_height: usize, - cell_width: usize, - have_pending_resize: Option<(u16, u16)>, - mux_window_id: WindowId, -} - -impl TerminalWindow for X11TerminalWindow { - fn get_mux_window_id(&self) -> WindowId { - self.mux_window_id - } - fn config(&self) -> &Arc { - &self.host.config - } - fn fonts(&self) -> &Rc { - &self.host.fonts - } - - fn set_window_title(&mut self, title: &str) -> Result<(), Error> { - self.host.window.set_title(title); - Ok(()) - } - fn frame(&self) -> glium::Frame { - self.host.window.draw() - } - - fn renderer(&mut self) -> &mut Renderer { - &mut self.renderer - } - fn recreate_texture_atlas(&mut self, size: u32) -> Result<(), Error> { - self.renderer.recreate_atlas(&self.host.window, size) - } - fn get_dimensions(&self) -> Dimensions { - Dimensions { - width: self.width, - height: self.height, - cell_height: self.cell_height, - cell_width: self.cell_width, - } - } - fn advise_renderer_that_scaling_has_changed( - &mut self, - cell_width: usize, - cell_height: usize, - ) -> Result<(), Error> { - self.cell_width = cell_width; - self.cell_height = cell_height; - self.renderer.scaling_changed(&self.host.window) - } - fn advise_renderer_of_resize(&mut self, width: u16, height: u16) -> Result<(), Error> { - self.width = width; - self.height = height; - self.renderer.resize(&self.host.window, width, height) - } - fn resize_if_not_full_screen(&mut self, _width: u16, _height: u16) -> Result { - // FIXME: it would be nice to implement this! - // It requires some plumbing to allow sending xcb_configure_window with - // XCB_CONFIG_WINDOW_WIDTH and XCB_CONFIG_WINDOW_HEIGHT set. - Ok(false) - } - - fn check_for_resize(&mut self) -> Result<(), Error> { - if let Some((width, height)) = self.have_pending_resize.take() { - self.resize_surfaces(width, height, false)?; - } - Ok(()) - } -} - -impl X11TerminalWindow { - pub fn new( - event_loop: &Rc, - fonts: &Rc, - config: &Arc, - tab: &Rc, - mux_window_id: WindowId, - ) -> Result { - let (physical_rows, physical_cols) = tab.renderer().physical_dimensions(); - - let metrics = fonts.default_font_metrics()?; - let (cell_height, cell_width) = ( - metrics.cell_height.ceil() as usize, - metrics.cell_width.ceil() as usize, - ); - - let width = cell_width * physical_cols; - let height = cell_height * physical_rows; - - let width = width as u16; - let height = height as u16; - let window = Window::new(&event_loop.conn, width, height)?; - window.set_title("wezterm"); - - let host = HostImpl::new(Host { - window, - event_loop: Rc::clone(event_loop), - config: Arc::clone(config), - fonts: Rc::clone(fonts), - }); - - let renderer = Renderer::new(&host.window, width, height, fonts)?; - host.window.show(); - - Ok(X11TerminalWindow { - host, - renderer, - conn: Rc::clone(&event_loop.conn), - width, - height, - cell_height, - cell_width, - have_pending_resize: None, - mux_window_id, - }) - } - - pub fn window_id(&self) -> X11WindowId { - self.host.window.window.window_id - } - - pub fn expose(&mut self, _x: u16, _y: u16, _width: u16, _height: u16) -> Result<(), Error> { - self.paint() - } - - fn decode_key(&self, event: &xcb::KeyPressEvent) -> Option<(KeyCode, KeyModifiers)> { - self.conn.xkb_lookup_keysym(event) - } - - fn mouse_event(&mut self, event: MouseEvent) -> Result<(), Error> { - let mux = Mux::get().unwrap(); - let tab = match mux.get_active_tab_for_window(self.get_mux_window_id()) { - Some(tab) => tab, - None => return Ok(()), - }; - tab.mouse_event(event, &mut TabHost::new(&mut *tab.writer(), &mut self.host))?; - Ok(()) - } - - pub fn dispatch_event(&mut self, event: &xcb::GenericEvent) -> Result<(), Error> { - let r = event.response_type() & 0x7f; - match r { - xcb::EXPOSE => { - let expose: &xcb::ExposeEvent = unsafe { xcb::cast_event(event) }; - self.expose(expose.x(), expose.y(), expose.width(), expose.height())?; - } - xcb::CONFIGURE_NOTIFY => { - let cfg: &xcb::ConfigureNotifyEvent = unsafe { xcb::cast_event(event) }; - let schedule = self.have_pending_resize.is_none(); - self.have_pending_resize = Some((cfg.width(), cfg.height())); - if schedule { - self.host.with_window(|win| win.check_for_resize()); - } - } - xcb::KEY_PRESS => { - let key_press: &xcb::KeyPressEvent = unsafe { xcb::cast_event(event) }; - let mux = Mux::get().unwrap(); - let tab = match mux.get_active_tab_for_window(self.get_mux_window_id()) { - Some(tab) => tab, - None => return Ok(()), - }; - if let Some((code, mods)) = self.decode_key(key_press) { - if self.host.process_gui_shortcuts(&*tab, mods, code)? { - return Ok(()); - } - - tab.key_down(code, mods)?; - } - } - xcb::MOTION_NOTIFY => { - let motion: &xcb::MotionNotifyEvent = unsafe { xcb::cast_event(event) }; - - let event = MouseEvent { - kind: MouseEventKind::Move, - button: MouseButton::None, - x: (motion.event_x() as usize / self.cell_width) as usize, - y: (motion.event_y() as usize / self.cell_height) as i64, - modifiers: xkeysyms::modifiers_from_state(motion.state()), - }; - self.mouse_event(event)?; - } - xcb::BUTTON_PRESS | xcb::BUTTON_RELEASE => { - let button_press: &xcb::ButtonPressEvent = unsafe { xcb::cast_event(event) }; - - let event = MouseEvent { - kind: match r { - xcb::BUTTON_PRESS => MouseEventKind::Press, - xcb::BUTTON_RELEASE => MouseEventKind::Release, - _ => unreachable!("button event mismatch"), - }, - x: (button_press.event_x() as usize / self.cell_width) as usize, - y: (button_press.event_y() as usize / self.cell_height) as i64, - button: match button_press.detail() { - 1 => MouseButton::Left, - 2 => MouseButton::Middle, - 3 => MouseButton::Right, - 4 => MouseButton::WheelUp(1), - 5 => MouseButton::WheelDown(1), - _ => { - error!("button {} is not implemented", button_press.detail()); - return Ok(()); - } - }, - modifiers: xkeysyms::modifiers_from_state(button_press.state()), - }; - - self.mouse_event(event)?; - } - xcb::CLIENT_MESSAGE => { - let msg: &xcb::ClientMessageEvent = unsafe { xcb::cast_event(event) }; - debug!("CLIENT_MESSAGE {:?}", msg.data().data32()); - if msg.data().data32()[0] == self.conn.atom_delete() { - return Err(SessionTerminated::WindowClosed.into()); - } - } - _ => {} - } - Ok(()) - } -}