diff --git a/src/font/mod.rs b/src/font/mod.rs index e198350aa..6d25b351a 100644 --- a/src/font/mod.rs +++ b/src/font/mod.rs @@ -131,18 +131,6 @@ impl FontConfiguration { } } - /// Used when spawning a window to start with an unscaled font configuration - pub fn clone_unscaled(&self) -> Rc { - Rc::new(Self { - config: Rc::clone(&self.config), - fonts: RefCell::new(HashMap::new()), - system: Rc::clone(&self.system), - metrics: RefCell::new(None), - font_scale: RefCell::new(1.0), - dpi_scale: RefCell::new(1.0), - }) - } - /// Given a text style, load (with caching) the font that best /// matches according to the fontconfig pattern. pub fn cached_font(&self, style: &TextStyle) -> Result>>, Error> { diff --git a/src/gliumwindows.rs b/src/gliumwindows.rs index 976fe6ede..26ae6d3f1 100644 --- a/src/gliumwindows.rs +++ b/src/gliumwindows.rs @@ -9,15 +9,14 @@ use crate::guicommon::window::{Dimensions, TerminalWindow}; use crate::guiloop::glutinloop::GuiEventLoop; use crate::guiloop::SessionTerminated; use crate::opengl::render::Renderer; -use crate::{spawn_window_impl, Child, MasterPty}; use glium; use glium::glutin::dpi::{LogicalPosition, LogicalSize, PhysicalPosition, PhysicalSize}; use glium::glutin::{self, ElementState, MouseCursor}; use std::cell::RefMut; use std::rc::Rc; +use term; use term::KeyCode; use term::KeyModifiers; -use term::{self, Terminal}; use term::{MouseButton, MouseEventKind}; #[cfg(target_os = "macos")] use winit::os::macos::WindowExt; @@ -38,22 +37,6 @@ impl HostHelper for Host { GuiEventLoop::with_window(&self.event_loop, self.display.gl_window().id(), func); } - fn new_window(&mut self) { - let event_loop = Rc::clone(&self.event_loop); - let config = Rc::clone(&self.config); - let fonts = Rc::clone(&self.fonts); - self.event_loop.spawn_fn(move || { - let (terminal, master, child, fonts) = spawn_window_impl(None, &config, &fonts)?; - let window = - GliumTerminalWindow::new(&event_loop, terminal, master, child, &fonts, &config)?; - - event_loop.add_window(window) - }); - } - fn new_tab(&mut self) { - self.with_window(|win| win.spawn_tab().map(|_| ())); - } - fn toggle_full_screen(&mut self) { if let Some(pos) = self.is_fullscreen.take() { let window = self.display.gl_window(); @@ -133,14 +116,9 @@ impl TerminalWindow for GliumTerminalWindow { self.tabs.get_active().unwrap().terminal(), ) } - fn tab_was_created(&mut self, tab_id: TabId) -> Result<(), Error> { - match self.tabs.get_by_id(tab_id) { - Ok(tab) => { - self.event_loop - .schedule_read_pty(tab.pty().try_clone()?, self.window_id(), tab_id) - } - _ => Ok(()), - } + + fn tab_was_created(&mut self, tab: &Rc) -> Result<(), Error> { + self.event_loop.register_tab(tab) } fn deregister_tab(&mut self, _tab_id: TabId) -> Result<(), Error> { Ok(()) @@ -187,11 +165,9 @@ impl TerminalWindow for GliumTerminalWindow { impl GliumTerminalWindow { pub fn new( event_loop: &Rc, - terminal: Terminal, - pty: MasterPty, - process: Child, fonts: &Rc, config: &Rc, + tab: &Rc, ) -> Result { let palette = config .colors @@ -199,13 +175,19 @@ impl GliumTerminalWindow { .map(|p| p.clone().into()) .unwrap_or_else(term::color::ColorPalette::default); - let metrics = fonts.default_font_metrics()?; - let (cell_height, cell_width) = (metrics.cell_height, metrics.cell_width); + let terminal = tab.terminal(); + let screen = terminal.screen(); - let size = pty.get_size()?; - let width = size.ws_xpixel; - let height = size.ws_ypixel; - let logical_size = LogicalSize::new(width.into(), height.into()); + 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 * screen.physical_cols; + let height = cell_height * screen.physical_rows; + + let logical_size = LogicalSize::new(width as f64, height as f64); eprintln!("make window with {}x{}", width, height); let display = { @@ -234,11 +216,9 @@ impl GliumTerminalWindow { host.display.gl_window().set_cursor(MouseCursor::Text); + let width = width as u16; + let height = height as u16; let renderer = Renderer::new(&host.display, width, height, fonts, palette)?; - let cell_height = cell_height.ceil() as usize; - let cell_width = cell_width.ceil() as usize; - - let tab = Tab::new(terminal, process, pty); Ok(GliumTerminalWindow { host, @@ -257,34 +237,10 @@ impl GliumTerminalWindow { }) } - pub fn get_tab_id_by_idx(&self, tab_idx: usize) -> usize { - self.tabs - .get_by_idx(tab_idx) - .expect("invalid tab_idx") - .tab_id() - } - pub fn window_id(&self) -> glutin::WindowId { self.host.display.gl_window().id() } - pub fn clone_current_pty(&self) -> Result { - self.tabs - .get_active() - .ok_or_else(|| format_err!("no active tab"))? - .pty() - .try_clone() - } - - pub fn process_data_read_from_pty(&mut self, data: &[u8], tab_id: usize) -> Result<(), Error> { - let tab = self.tabs.get_by_id(tab_id)?; - - tab.terminal() - .advance_bytes(data, &mut TabHost::new(&mut tab.pty(), &mut self.host)); - - Ok(()) - } - fn resize_surfaces_logical(&mut self, size: LogicalSize) -> Result { let dpi_scale = self.host.display.gl_window().get_hidpi_factor(); let (width, height): (u32, u32) = size.to_physical(dpi_scale).into(); @@ -649,11 +605,29 @@ impl GliumTerminalWindow { if let Some(key) = Self::keycode_from_input(&event) { // debug!("event {:?} -> {:?}", event, key); match event.state { - ElementState::Pressed => tab.terminal().key_down( - key, - mods, - &mut TabHost::new(&mut tab.pty(), &mut self.host), - )?, + ElementState::Pressed => { + if mods == KeyModifiers::SUPER && key == KeyCode::Char('n') { + GuiEventLoop::schedule_spawn_new_window( + &self.event_loop, + &self.host.config, + &self.host.fonts, + ); + return Ok(()); + } + + if mods == KeyModifiers::SUPER && key == KeyCode::Char('t') { + GuiEventLoop::with_window(&self.event_loop, self.window_id(), |win| { + win.spawn_tab().map(|_| ()) + }); + return Ok(()); + } + + tab.terminal().key_down( + key, + mods, + &mut TabHost::new(&mut tab.pty(), &mut self.host), + )? + } ElementState::Released => tab.terminal().key_up( key, diff --git a/src/guicommon/host.rs b/src/guicommon/host.rs index ce9916954..b108efd0a 100644 --- a/src/guicommon/host.rs +++ b/src/guicommon/host.rs @@ -8,8 +8,6 @@ use termwiz::hyperlink::Hyperlink; pub trait HostHelper { fn with_window Result<(), Error>>(&self, func: F); - fn new_tab(&mut self); - fn new_window(&mut self); fn toggle_full_screen(&mut self); } @@ -105,13 +103,6 @@ impl<'a, H: HostHelper> term::TerminalHost for TabHost<'a, H> { }) } - fn new_window(&mut self) { - self.host.new_window(); - } - fn new_tab(&mut self) { - self.host.new_tab(); - } - fn activate_tab(&mut self, tab: usize) { self.host.with_window(move |win| win.activate_tab(tab)) } diff --git a/src/guicommon/tabs.rs b/src/guicommon/tabs.rs index 39a795085..3f71ccb22 100644 --- a/src/guicommon/tabs.rs +++ b/src/guicommon/tabs.rs @@ -1,6 +1,6 @@ use crate::{Child, MasterPty}; -use failure::Error; use std::cell::{RefCell, RefMut}; +use std::rc::Rc; use term::Terminal; static TAB_ID: ::std::sync::atomic::AtomicUsize = ::std::sync::atomic::ATOMIC_USIZE_INIT; @@ -51,20 +51,20 @@ impl Drop for Tab { } pub struct Tabs { - tabs: Vec, + tabs: Vec>, active: usize, } impl Tabs { - pub fn new(tab: Tab) -> Self { + pub fn new(tab: &Rc) -> Self { Self { - tabs: vec![tab], + tabs: vec![Rc::clone(tab)], active: 0, } } - pub fn push(&mut self, tab: Tab) { - self.tabs.push(tab); + pub fn push(&mut self, tab: &Rc) { + self.tabs.push(Rc::clone(tab)) } pub fn is_empty(&self) -> bool { @@ -75,22 +75,13 @@ impl Tabs { self.tabs.len() } - pub fn get_by_idx(&self, idx: usize) -> Option<&Tab> { + pub fn get_by_idx(&self, idx: usize) -> Option<&Rc> { self.tabs.get(idx) } - pub fn get_by_id(&self, id: TabId) -> Result<&Tab, Error> { - for t in &self.tabs { - if t.tab_id == id { - return Ok(t); - } - } - bail!("no such tab id {}", id) - } - pub fn idx_by_id(&self, id: TabId) -> Option { for (idx, t) in self.tabs.iter().enumerate() { - if t.tab_id == id { + if t.tab_id() == id { return Some(idx); } } @@ -107,8 +98,8 @@ impl Tabs { } } - pub fn get_active(&self) -> Option<&Tab> { - self.tabs.get(self.active) + pub fn get_active(&self) -> Option<&Rc> { + self.get_by_idx(self.active) } #[inline] @@ -119,10 +110,14 @@ impl Tabs { pub fn set_active(&mut self, idx: usize) { assert!(idx < self.tabs.len()); self.active = idx; - self.tabs[idx].terminal.borrow_mut().make_all_lines_dirty(); + self.get_by_idx(idx) + .unwrap() + .terminal + .borrow_mut() + .make_all_lines_dirty(); } - pub fn iter(&self) -> impl Iterator { + pub fn iter(&self) -> impl Iterator> { self.tabs.iter() } } diff --git a/src/guicommon/window.rs b/src/guicommon/window.rs index 1a5b363eb..3a539c0fa 100644 --- a/src/guicommon/window.rs +++ b/src/guicommon/window.rs @@ -3,7 +3,7 @@ use crate::font::FontConfiguration; use crate::guicommon::tabs::{Tab, TabId, Tabs}; use crate::opengl::render::Renderer; use crate::opengl::textureatlas::OutOfTextureSpace; -use crate::pty::unix::openpty; +use crate::openpty; use failure::Error; use glium; use std::cell::RefMut; @@ -37,7 +37,7 @@ pub trait TerminalWindow { cell_height: usize, ) -> Result<(), Error>; fn advise_renderer_of_resize(&mut self, width: u16, height: u16) -> Result<(), Error>; - fn tab_was_created(&mut self, tab_id: TabId) -> Result<(), Error>; + fn tab_was_created(&mut self, tab: &Rc) -> Result<(), Error>; fn deregister_tab(&mut self, tab_id: TabId) -> Result<(), Error>; fn config(&self) -> &Rc; fn fonts(&self) -> &Rc; @@ -90,6 +90,7 @@ pub trait TerminalWindow { if tab.terminal().has_dirty_lines() { self.paint()?; } + self.update_title(); Ok(()) } @@ -150,14 +151,14 @@ pub trait TerminalWindow { config.hyperlink_rules.clone(), ); - let tab = Tab::new(terminal, process, pty); + let tab = Rc::new(Tab::new(terminal, process, pty)); let tab_id = tab.tab_id(); - self.get_tabs_mut().push(tab); + self.get_tabs_mut().push(&tab); let len = self.get_tabs().len(); self.activate_tab(len - 1)?; - self.tab_was_created(tab_id)?; + self.tab_was_created(&tab)?; Ok(tab_id) } @@ -177,7 +178,8 @@ pub trait TerminalWindow { let rows = ((height as usize + 1) / dims.cell_height) as u16; let cols = ((width as usize + 1) / dims.cell_width) as u16; - for tab in self.get_tabs().iter() { + let tabs = self.get_tabs(); + for tab in tabs.iter() { tab.pty().resize(rows, cols, width as u16, height as u16)?; tab.terminal().resize(rows as usize, cols as usize); } @@ -235,24 +237,26 @@ pub trait TerminalWindow { fn tab_did_terminate(&mut self, tab_id: TabId) { self.get_tabs_mut().remove_by_id(tab_id); - if let Some(tab) = self.get_tabs().get_active() { - tab.terminal().make_all_lines_dirty(); + if let Some(active) = self.get_tabs().get_active() { + active.terminal().make_all_lines_dirty(); self.update_title(); } - self.deregister_tab(tab_id).ok(); } fn test_for_child_exit(&mut self) -> bool { - let dead_tabs: Vec = self - .get_tabs() + let tabs = self.get_tabs(); + let dead_tabs: Vec> = tabs .iter() - .filter_map(|tab| match tab.process().try_wait() { - Ok(None) => None, - _ => Some(tab.tab_id()), + .filter_map(|tab| { + if let Ok(None) = tab.process().try_wait() { + None + } else { + Some(Rc::clone(tab)) + } }) .collect(); - for tab_id in dead_tabs { - self.tab_did_terminate(tab_id); + for tab in dead_tabs { + self.tab_did_terminate(tab.tab_id()); } self.get_tabs().is_empty() } diff --git a/src/guiloop/glutinloop.rs b/src/guiloop/glutinloop.rs index 1c0c46c5d..7a2e207c1 100644 --- a/src/guiloop/glutinloop.rs +++ b/src/guiloop/glutinloop.rs @@ -1,10 +1,14 @@ use super::GuiSystem; +use crate::config::Config; +use crate::font::FontConfiguration; use crate::futurecore; use crate::gliumwindows; pub use crate::gliumwindows::GliumTerminalWindow; +use crate::guicommon::tabs::Tab; use crate::guicommon::window::TerminalWindow; use crate::guiloop::SessionTerminated; -use crate::{Child, MasterPty}; +use crate::mux::{Mux, PtyEvent, PtyEventSender}; +use crate::spawn_tab; use failure::Error; use futures::future; use glium; @@ -12,7 +16,6 @@ use glium::glutin::EventsLoopProxy; pub use glium::glutin::WindowId; use std::cell::RefCell; use std::collections::HashMap; -use std::io::Read; use std::rc::Rc; use std::sync::mpsc::{self, Receiver, SyncSender, TryRecvError}; use std::thread; @@ -41,6 +44,12 @@ impl futurecore::CoreSender for GuiSender { } } +impl PtyEventSender for GuiSender { + fn send(&self, event: PtyEvent) -> Result<(), Error> { + GuiSender::send(self, event) + } +} + impl futurecore::CoreReceiver for Receiver { fn try_recv(&self) -> Result { Receiver::try_recv(self) @@ -55,19 +64,6 @@ pub fn channel(proxy: EventsLoopProxy) -> (GuiSender, Receiver) { (GuiSender { tx, proxy }, rx) } -#[derive(Clone)] -pub enum IOEvent { - Data { - window_id: WindowId, - tab_id: usize, - data: Vec, - }, - Terminated { - window_id: WindowId, - tab_id: usize, - }, -} - /// This struct holds references to Windows. /// The primary mapping is from `WindowId` -> `GliumTerminalWindow`. #[derive(Default)] @@ -82,9 +78,10 @@ pub struct GuiEventLoop { pub event_loop: RefCell, windows: Rc>, core: futurecore::Core, - poll_tx: GuiSender, - poll_rx: Receiver, + poll_tx: GuiSender, + poll_rx: Receiver, tick_rx: Receiver<()>, + mux: Rc, } const TICK_INTERVAL: Duration = Duration::from_millis(50); @@ -95,8 +92,8 @@ pub struct GlutinGuiSystem { } impl GlutinGuiSystem { - pub fn try_new() -> Result, Error> { - let event_loop = Rc::new(GuiEventLoop::new()?); + pub fn try_new(mux: &Rc) -> Result, Error> { + let event_loop = Rc::new(GuiEventLoop::new(mux)?); Ok(Rc::new(Self { event_loop })) } @@ -113,6 +110,10 @@ impl GlutinGuiSystem { } impl GuiSystem for GlutinGuiSystem { + fn pty_sender(&self) -> Box { + Box::new(self.event_loop.poll_tx.clone()) + } + fn run_forever(&self) -> Result<(), Error> { // This convoluted run() signature is present because of this issue: // https://github.com/tomaka/winit/issues/413 @@ -138,19 +139,15 @@ impl GuiSystem for GlutinGuiSystem { fn spawn_new_window( &self, - terminal: term::Terminal, - master: MasterPty, - child: Child, config: &Rc, fontconfig: &Rc, + tab: &Rc, ) -> Result<(), Error> { let window = GliumTerminalWindow::new( &self.event_loop, - terminal, - master, - child, fontconfig, config, + tab, )?; self.event_loop.add_window(window) @@ -158,7 +155,7 @@ impl GuiSystem for GlutinGuiSystem { } impl GuiEventLoop { - pub fn new() -> Result { + pub fn new(mux: &Rc) -> Result { let event_loop = glium::glutin::EventsLoop::new(); let (fut_tx, fut_rx) = channel(event_loop.create_proxy()); @@ -184,9 +181,42 @@ impl GuiEventLoop { tick_rx, event_loop: RefCell::new(event_loop), windows: Rc::new(RefCell::new(Default::default())), + mux: Rc::clone(mux), }) } + pub fn register_tab(&self, tab: &Rc) -> Result<(), Error> { + self.mux.add_tab(Box::new(self.poll_tx.clone()), tab) + } + + fn do_spawn_new_window( + events: &Rc, + config: &Rc, + fonts: &Rc, + ) -> Result<(), Error> { + let tab = spawn_tab(&config, None)?; + let sender = Box::new(events.poll_tx.clone()); + events.mux.add_tab(sender, &tab)?; + let window = GliumTerminalWindow::new( &events, &fonts, &config, &tab)?; + + events.add_window(window) + } + + pub fn schedule_spawn_new_window( + events: &Rc, + config: &Rc, + fonts: &Rc, + ) { + let myself = Rc::clone(events); + let config = Rc::clone(config); + let fonts = Rc::clone(fonts); + events.core.spawn(futures::future::poll_fn(move || { + Self::do_spawn_new_window(&myself, &config, &fonts) + .map(futures::Async::Ready) + .map_err(|_| ()) + })); + } + pub fn with_window Result<(), Error>>( events: &Rc, window_id: WindowId, @@ -203,63 +233,9 @@ impl GuiEventLoop { })); } - pub fn spawn_fn Result<(), Error>>(&self, func: F) { - self.core.spawn(futures::future::poll_fn(move || { - func().map(futures::Async::Ready).map_err(|_| ()) - })) - } - - pub fn schedule_read_pty( - &self, - mut pty: MasterPty, - window_id: WindowId, - tab_id: usize, - ) -> Result<(), Error> { - pty.clear_nonblocking()?; - let tx = self.poll_tx.clone(); - - thread::spawn(move || { - const BUFSIZE: usize = 32 * 1024; - let mut buf = [0; BUFSIZE]; - loop { - match pty.read(&mut buf) { - Ok(size) if size == 0 => { - eprintln!("read_pty EOF: window {:?} {}", window_id, tab_id); - tx.send(IOEvent::Terminated { window_id, tab_id }).ok(); - return; - } - Ok(size) => { - if tx - .send(IOEvent::Data { - window_id, - tab_id, - data: buf[0..size].to_vec(), - }) - .is_err() - { - return; - } - } - Err(err) => { - eprintln!( - "read_pty failed: window {:?} {} {:?}", - window_id, tab_id, err - ); - tx.send(IOEvent::Terminated { window_id, tab_id }).ok(); - return; - } - } - } - }); - - Ok(()) - } - /// Add a window to the event loop and run it. pub fn add_window(&self, window: gliumwindows::GliumTerminalWindow) -> Result<(), Error> { let window_id = window.window_id(); - let pty = window.clone_current_pty()?; - self.schedule_read_pty(pty, window_id, window.get_tab_id_by_idx(0))?; let mut windows = self.windows.borrow_mut(); windows.by_id.insert(window_id, window); Ok(()) @@ -334,25 +310,7 @@ impl GuiEventLoop { _ => {} } match self.poll_rx.try_recv() { - Ok(IOEvent::Data { - window_id, - tab_id, - data, - }) => { - let mut windows = self.windows.borrow_mut(); - windows.by_id.get_mut(&window_id).map(|window| { - window.process_data_read_from_pty(&data, tab_id).ok(); - Some(()) - }); - } - Ok(IOEvent::Terminated { window_id, tab_id }) => { - eprintln!("window {:?} tab {} terminated", window_id, tab_id); - let mut windows = self.windows.borrow_mut(); - windows.by_id.get_mut(&window_id).map(|window| { - window.tab_did_terminate(tab_id); - Some(()) - }); - } + Ok(event) => self.mux.process_pty_event(event)?, Err(TryRecvError::Empty) => return Ok(()), Err(err) => bail!("poll_rx disconnected {:?}", err), } diff --git a/src/guiloop/mod.rs b/src/guiloop/mod.rs index a368fb459..5ad6f1757 100644 --- a/src/guiloop/mod.rs +++ b/src/guiloop/mod.rs @@ -1,7 +1,8 @@ use super::ExitStatus; use crate::config::Config; use crate::font::FontConfiguration; -use crate::{Child, MasterPty}; +use crate::guicommon::tabs::Tab; +use crate::mux::{Mux, PtyEventSender}; use failure::Error; use std::rc::Rc; @@ -24,12 +25,12 @@ impl Default for GuiSelection { } impl GuiSelection { - pub fn try_new(self) -> Result, Error> { + pub fn try_new(self, mux: &Rc) -> Result, Error> { match self { - GuiSelection::Glutin => glutinloop::GlutinGuiSystem::try_new(), + GuiSelection::Glutin => glutinloop::GlutinGuiSystem::try_new(mux), GuiSelection::X11 => { #[cfg(all(unix, not(target_os = "macos")))] - return x11::X11GuiSystem::try_new(); + return x11::X11GuiSystem::try_new(mux); #[cfg(not(all(unix, not(target_os = "macos"))))] bail!("X11 not compiled in"); } @@ -64,12 +65,12 @@ pub trait GuiSystem { fn spawn_new_window( &self, - terminal: term::Terminal, - master: MasterPty, - child: Child, config: &Rc, fontconfig: &Rc, + tab: &Rc, ) -> Result<(), Error>; + + fn pty_sender(&self) -> Box; } pub mod glutinloop; diff --git a/src/guiloop/x11.rs b/src/guiloop/x11.rs index 7a5a4800e..dc565336f 100644 --- a/src/guiloop/x11.rs +++ b/src/guiloop/x11.rs @@ -1,21 +1,18 @@ -use super::{GuiSystem, SessionTerminated}; use crate::config::Config; use crate::font::FontConfiguration; use crate::futurecore; -use crate::guicommon::tabs::TabId; +use crate::guicommon::tabs::{Tab }; use crate::guicommon::window::TerminalWindow; +use crate::guiloop::GuiSystem; +use crate::mux::{Mux, PtyEvent, PtyEventSender}; +use crate::spawn_tab; use crate::xwindows::xwin::X11TerminalWindow; use crate::xwindows::Connection; -use crate::{spawn_window_impl, Child, MasterPty}; use failure::Error; -use mio::unix::EventedFd; -use mio::{Event, Evented, Events, Poll, PollOpt, Ready, Token}; +use mio::{Events, Poll, PollOpt, Ready, Token}; use mio_extras::channel::{channel, Receiver as GuiReceiver, Sender as GuiSender}; use std::cell::RefCell; use std::collections::HashMap; -use std::io; -use std::os::unix::io::AsRawFd; -use std::os::unix::io::RawFd; use std::rc::Rc; use std::sync::mpsc::TryRecvError; use std::time::{Duration, Instant}; @@ -30,48 +27,21 @@ impl futurecore::CoreSender for GuiSender { } } +impl PtyEventSender for GuiSender { + fn send(&self, event: PtyEvent) -> Result<(), Error> { + GuiSender::send(self, event).map_err(|e| format_err!("send: {}", e)) + } +} + impl futurecore::CoreReceiver for GuiReceiver { fn try_recv(&self) -> Result { GuiReceiver::try_recv(self) } } -struct TabEntry { - tab_id: TabId, - fd: RawFd, - window_id: WindowId, -} - -impl Evented for TabEntry { - fn register( - &self, - poll: &Poll, - token: Token, - interest: Ready, - opts: PollOpt, - ) -> io::Result<()> { - EventedFd(&self.fd).register(poll, token, interest, opts) - } - - fn reregister( - &self, - poll: &Poll, - token: Token, - interest: Ready, - opts: PollOpt, - ) -> io::Result<()> { - EventedFd(&self.fd).reregister(poll, token, interest, opts) - } - - fn deregister(&self, poll: &Poll) -> io::Result<()> { - EventedFd(&self.fd).deregister(poll) - } -} - #[derive(Default)] struct Windows { by_id: HashMap, - tab_by_id: HashMap>, } pub struct GuiEventLoop { @@ -80,40 +50,43 @@ pub struct GuiEventLoop { pub core: futurecore::Core, windows: Rc>, interval: Duration, + pty_rx: GuiReceiver, + pty_tx: GuiSender, + mux: Rc, } const TOK_CORE: usize = 0xffff_ffff; +const TOK_PTY: usize = 0xffff_fffe; const TOK_XCB: usize = 0xffff_fffc; pub struct X11GuiSystem { event_loop: Rc, } impl X11GuiSystem { - pub fn try_new() -> Result, Error> { - let event_loop = Rc::new(GuiEventLoop::new()?); + pub fn try_new(mux: &Rc) -> Result, Error> { + let event_loop = Rc::new(GuiEventLoop::new(mux)?); Ok(Rc::new(Self { event_loop })) } } impl super::GuiSystem for X11GuiSystem { + fn pty_sender(&self) -> Box { + Box::new(self.event_loop.pty_tx.clone()) + } fn run_forever(&self) -> Result<(), Error> { self.event_loop.run() } fn spawn_new_window( &self, - terminal: term::Terminal, - master: MasterPty, - child: Child, config: &Rc, fontconfig: &Rc, + tab: &Rc, ) -> Result<(), Error> { let window = X11TerminalWindow::new( &self.event_loop, - terminal, - master, - child, fontconfig, config, + tab, )?; self.event_loop.add_window(window) @@ -121,7 +94,7 @@ impl super::GuiSystem for X11GuiSystem { } impl GuiEventLoop { - pub fn new() -> Result { + pub fn new(mux: &Rc) -> Result { let poll = Poll::new()?; let conn = Rc::new(Connection::new()?); @@ -138,20 +111,31 @@ impl GuiEventLoop { let fut_tx2 = fut_tx.clone(); let core = futurecore::Core::new(Box::new(fut_tx), Box::new(fut_tx2), Box::new(fut_rx)); + let (pty_tx, pty_rx) = channel(); + poll.register(&pty_rx, Token(TOK_PTY), Ready::readable(), PollOpt::level())?; + Ok(Self { conn, poll, core, + pty_rx, + pty_tx, interval: Duration::from_millis(50), windows: Rc::new(RefCell::new(Default::default())), + mux: Rc::clone(mux), }) } + pub fn register_tab(&self, tab: &Rc) -> Result<(), Error> { + self.mux.add_tab(Box::new(self.pty_tx.clone()), tab) + } + fn run(&self) -> Result<(), Error> { let mut events = Events::with_capacity(8); let tok_core = Token(TOK_CORE); let tok_xcb = Token(TOK_XCB); + let tok_pty = Token(TOK_PTY); self.conn.flush(); let mut last_interval = Instant::now(); @@ -175,19 +159,17 @@ impl GuiEventLoop { self.process_futures(); } else if t == tok_xcb { self.process_queued_xcb()?; + } else if t == tok_pty { + self.process_pty_event()?; } else { - self.process_pty_event(event)?; } } self.process_sigchld(); // Check the window count; if after processing the futures there // are no windows left, then we are done. - { - let windows = self.windows.borrow(); - if windows.by_id.is_empty() && windows.tab_by_id.is_empty() { - debug!("No more windows; done!"); - return Ok(()); - } + if self.mux.is_empty() { + debug!("No more windows; done!"); + return Ok(()); } } @@ -215,58 +197,32 @@ impl GuiEventLoop { func(window) } - /// Spawn a new tab in the specified window. This method registers - /// the returned pty fd as a TabEntry so that events are wired up. - pub fn spawn_tab(&self, window_id: WindowId) -> Result<(), Error> { - let mut windows = self.windows.borrow_mut(); + fn do_spawn_new_window( + events: &Rc, + config: &Rc, + fonts: &Rc, + ) -> Result<(), Error> { + let tab = spawn_tab(&config, None)?; + let sender = Box::new(events.pty_tx.clone()); + events.mux.add_tab(sender, &tab)?; + let window = X11TerminalWindow::new(&events, &fonts, &config, &tab)?; - let (tab_id, fd) = { - let window = windows.by_id.get_mut(&window_id).ok_or_else(|| { - format_err!("no window_id {:?} in the windows_by_id map", window_id) - })?; - - let tab_id = window.spawn_tab()?; - - let fd = window - .get_tabs() - .get_by_id(tab_id) - .unwrap() - .pty() - .as_raw_fd(); - - (tab_id, fd) - }; - - eprintln!("spawned new tab with fd = {}", fd); - - let entry = Rc::new(TabEntry { - fd, - tab_id, - window_id, - }); - windows.tab_by_id.insert(tab_id, Rc::clone(&entry)); - self.poll.register( - &*entry, - Token(tab_id as usize), - Ready::readable(), - PollOpt::edge(), - )?; - - Ok(()) + events.add_window(window) } - pub fn spawn_window( - &self, - event_loop: &Rc, + pub fn schedule_spawn_new_window( + events: &Rc, config: &Rc, - fontconfig: &Rc, - ) -> Result<(), Error> { - let (terminal, master, child, fontconfig) = spawn_window_impl(None, config, fontconfig)?; - - let window = - X11TerminalWindow::new(event_loop, terminal, master, child, &fontconfig, config)?; - - self.add_window(window) + fonts: &Rc, + ) { + let myself = Rc::clone(events); + let config = Rc::clone(config); + let fonts = Rc::clone(fonts); + events.core.spawn(futures::future::poll_fn(move || { + Self::do_spawn_new_window(&myself, &config, &fonts) + .map(futures::Async::Ready) + .map_err(|_| ()) + })); } pub fn add_window(&self, window: X11TerminalWindow) -> Result<(), Error> { @@ -274,22 +230,6 @@ impl GuiEventLoop { let mut windows = self.windows.borrow_mut(); - for tab in window.get_tabs().iter() { - let fd = tab.pty().as_raw_fd(); - let tab_id = tab.tab_id(); - let entry = Rc::new(TabEntry { - fd, - tab_id, - window_id, - }); - windows.tab_by_id.insert(tab_id, Rc::clone(&entry)); - self.poll.register( - &*entry, - Token(tab_id as usize), - Ready::readable(), - PollOpt::edge(), - )?; - } windows.by_id.insert(window_id, window); Ok(()) } @@ -308,95 +248,20 @@ impl GuiEventLoop { /// Process an even from the remote mio instance. /// At this time, all such events correspond to readable events /// for the pty associated with a window. - fn process_pty_event(&self, event: Event) -> Result<(), Error> { - // The token is the tab_id - let tab_id = event.token().0 as TabId; - - let (window_id, tab_id, result) = { - let mut windows = self.windows.borrow_mut(); - - let entry = windows - .tab_by_id - .get(&tab_id) - .ok_or_else(|| { - format_err!( - "tab_id {} has no associated window in windows_tab_by_id map", - tab_id - ) - }) - .map(Rc::clone)?; - - let window = windows.by_id.get_mut(&entry.window_id).ok_or_else(|| { - format_err!( - "tab {} -> window_id {:?} but no associated window is in the windows_tab_by_id map", - tab_id, - entry.window_id - ) - })?; - ( - entry.window_id, - entry.tab_id, - window.try_read_pty(entry.tab_id), - ) - }; - - if let Err(err) = result { - if err.downcast_ref::().is_some() { - self.windows - .borrow_mut() - .by_id - .get_mut(&window_id) - .map(|window| { - window.tab_did_terminate(tab_id); - Some(()) - }); - } else { - bail!("{:?}", err); - } + fn process_pty_event(&self) -> Result<(), Error> { + match self.pty_rx.try_recv() { + Ok(event) => self.mux.process_pty_event(event)?, + Err(TryRecvError::Empty) => return Ok(()), + Err(err) => bail!("poll_rx disconnected {:?}", err), } Ok(()) } - pub fn deregister_tab(&self, tab_id: TabId) -> Result<(), Error> { - let mut windows = self.windows.borrow_mut(); - if let Some(entry) = windows.tab_by_id.get_mut(&tab_id) { - self.poll.deregister(&**entry).ok(); - } - windows.tab_by_id.remove(&tab_id); - Ok(()) - } - fn schedule_window_close(&self, window_id: WindowId) -> Result<(), Error> { eprintln!("schedule_window_close {:?}", window_id); let mut windows = self.windows.borrow_mut(); - - let tab_ids: Vec = windows - .tab_by_id - .iter() - .filter_map(|(tab_id, entry)| { - if entry.window_id == window_id { - Some(*tab_id) - } else { - None - } - }) - .collect(); - - for tab_id in &tab_ids { - if let Some(entry) = windows.tab_by_id.get_mut(&tab_id) { - self.poll.deregister(&**entry).ok(); - } - windows.tab_by_id.remove(&tab_id); - } - windows.by_id.remove(&window_id); - eprintln!( - "deregistered tabs {:?}. Remaining counts {} {}", - tab_ids, - windows.tab_by_id.len(), - windows.by_id.len() - ); Ok(()) } diff --git a/src/main.rs b/src/main.rs index f11930b69..7a55b0164 100644 --- a/src/main.rs +++ b/src/main.rs @@ -20,9 +20,12 @@ mod futurecore; mod gliumwindows; mod guicommon; mod guiloop; +mod mux; mod opengl; +use crate::guicommon::tabs::Tab; use crate::guiloop::GuiSelection; use crate::guiloop::GuiSystem; +use crate::mux::Mux; mod font; use crate::font::{FontConfiguration, FontSystemSelection}; @@ -117,33 +120,25 @@ fn main() -> Result<(), Error> { None }; - let gui_system = opts.gui_system.unwrap_or(config.gui_system); - let gui = gui_system.try_new()?; + let mux = Rc::new(mux::Mux::default()); - spawn_window(&*gui, cmd, &config, &fontconfig)?; + let gui_system = opts.gui_system.unwrap_or(config.gui_system); + let gui = gui_system.try_new(&mux)?; + + spawn_window(&mux, &*gui, cmd, &config, &fontconfig)?; gui.run_forever() } -fn spawn_window_impl( - cmd: Option>, +fn spawn_tab( config: &Rc, - fontconfig: &Rc, -) -> Result<(term::Terminal, MasterPty, Child, Rc), Error> { + cmd: Option>, +) -> Result, Error> { let cmd = config.build_prog(cmd)?; - let fontconfig = fontconfig.clone_unscaled(); - - // First step is to figure out the font metrics so that we know how - // big things are going to be. - // we always load the cell_height for font 0, - // regardless of which font we are shaping here, - // so that we can scale glyphs appropriately - let metrics = fontconfig.default_font_metrics()?; - let initial_cols = 80u16; let initial_rows = 24u16; - let initial_pixel_width = initial_cols * metrics.cell_width.ceil() as u16; - let initial_pixel_height = initial_rows * metrics.cell_height.ceil() as u16; + let initial_pixel_width = 0; + let initial_pixel_height = 0; let (master, slave) = openpty( initial_rows, @@ -162,16 +157,18 @@ fn spawn_window_impl( config.hyperlink_rules.clone(), ); - Ok((terminal, master, child, fontconfig)) + Ok(Rc::new(Tab::new(terminal, child, master))) } fn spawn_window( + mux: &Rc, gui: &GuiSystem, cmd: Option>, config: &Rc, fontconfig: &Rc, ) -> Result<(), Error> { - let (terminal, master, child, fontconfig) = spawn_window_impl(cmd, config, fontconfig)?; + let tab = spawn_tab(config, cmd)?; + mux.add_tab(gui.pty_sender(), &tab)?; - gui.spawn_new_window(terminal, master, child, config, &fontconfig) + gui.spawn_new_window(config, &fontconfig, &tab) } diff --git a/src/mux/mod.rs b/src/mux/mod.rs new file mode 100644 index 000000000..0579efc66 --- /dev/null +++ b/src/mux/mod.rs @@ -0,0 +1,131 @@ +use crate::guicommon::tabs::{Tab, TabId}; +use crate::MasterPty; +use failure::Error; +use std::cell::RefCell; +use std::collections::HashMap; +use std::io::Read; +use std::rc::Rc; +use std::thread; +use term::TerminalHost; +use termwiz::hyperlink::Hyperlink; + +#[derive(Default)] +pub struct Mux { + tabs: RefCell>>, +} + +#[derive(Clone)] +pub enum PtyEvent { + Data { tab_id: TabId, data: Vec }, + Terminated { tab_id: TabId }, +} + +pub trait PtyEventSender: Send { + fn send(&self, event: PtyEvent) -> Result<(), Error>; +} + +fn read_from_tab_pty(sender: Box, tab_id: TabId, mut pty: MasterPty) { + const BUFSIZE: usize = 32 * 1024; + let mut buf = [0; BUFSIZE]; + loop { + match pty.read(&mut buf) { + Ok(size) if size == 0 => { + eprintln!("read_pty EOF: tab_id {}", tab_id); + sender.send(PtyEvent::Terminated { tab_id }).ok(); + return; + } + Ok(size) => { + if sender + .send(PtyEvent::Data { + tab_id, + data: buf[0..size].to_vec(), + }) + .is_err() + { + return; + } + } + Err(err) => { + eprintln!("read_pty failed: tab {} {:?}", tab_id, err); + sender.send(PtyEvent::Terminated { tab_id }).ok(); + return; + } + } + } +} + +/// This is just a stub impl of TerminalHost; it really only exists +/// in order to parse data sent by the peer (so, just to parse output). +/// As such it only really has Host::writer get called. +/// The GUI driven flows provide their own impl of TerminalHost. +struct Host<'a> { + pty: &'a mut MasterPty, +} + +impl<'a> TerminalHost for Host<'a> { + fn writer(&mut self) -> &mut std::io::Write { + &mut self.pty + } + + fn click_link(&mut self, link: &Rc) { + match open::that(link.uri()) { + Ok(_) => {} + Err(err) => eprintln!("failed to open {}: {:?}", link.uri(), err), + } + } + + fn get_clipboard(&mut self) -> Result { + eprintln!("peer requested clipboard; ignoring"); + Ok("".into()) + } + + fn set_clipboard(&mut self, _clip: Option) -> Result<(), Error> { + Ok(()) + } + + fn set_title(&mut self, _title: &str) { + } +} + +impl Mux { + pub fn get_tab(&self, tab_id: TabId) -> Option> { + self.tabs.borrow().get(&tab_id).map(Rc::clone) + } + + pub fn add_tab(&self, sender: Box, tab: &Rc) -> Result<(), Error> { + self.tabs.borrow_mut().insert(tab.tab_id(), Rc::clone(tab)); + + let pty = tab.pty().try_clone()?; + pty.clear_nonblocking()?; + let tab_id = tab.tab_id(); + thread::spawn(move || read_from_tab_pty(sender, tab_id, pty)); + + Ok(()) + } + + pub fn process_pty_event(&self, event: PtyEvent) -> Result<(), Error> { + match event { + PtyEvent::Data { tab_id, data } => { + if let Some(tab) = self.get_tab(tab_id) { + tab.terminal().advance_bytes( + data, + &mut Host { + pty: &mut tab.pty(), + }, + ); + } + } + PtyEvent::Terminated { tab_id } => { + // The fact that we woke up is enough to trigger each + // window to check for termination + eprintln!("tab {} terminated", tab_id); + self.tabs.borrow_mut().remove(&tab_id); + } + } + Ok(()) + } + + pub fn is_empty(&self) -> bool { + self.tabs.borrow().is_empty() + } +} diff --git a/src/xwindows/xwin.rs b/src/xwindows/xwin.rs index 30b3c051c..f5ebc26a6 100644 --- a/src/xwindows/xwin.rs +++ b/src/xwindows/xwin.rs @@ -1,5 +1,4 @@ use super::super::opengl::render::Renderer; -use super::super::Child; use super::xkeysyms; use super::{Connection, Window}; use crate::config::Config; @@ -9,11 +8,9 @@ use crate::guicommon::tabs::{Tab, TabId, Tabs}; use crate::guicommon::window::{Dimensions, TerminalWindow}; use crate::guiloop::x11::{GuiEventLoop, WindowId}; use crate::guiloop::SessionTerminated; -use crate::MasterPty; use failure::Error; use futures; use std::cell::RefMut; -use std::io::{self, Read}; use std::rc::Rc; use term::{self, KeyCode, KeyModifiers, MouseButton, MouseEvent, MouseEventKind}; use xcb; @@ -40,35 +37,6 @@ impl HostHelper for Host { .map_err(|_| ()) })); } - fn new_window(&mut self) { - let event_loop = Rc::clone(&self.event_loop); - let events = Rc::clone(&self.event_loop); - let config = Rc::clone(&self.config); - let fonts = Rc::clone(&self.fonts); - - self.event_loop - .core - .spawn(futures::future::poll_fn(move || { - events - .spawn_window(&event_loop, &config, &fonts) - .map(futures::Async::Ready) - .map_err(|_| ()) - })); - } - - fn new_tab(&mut self) { - let events = Rc::clone(&self.event_loop); - let window_id = self.window.window.window_id; - - self.event_loop - .core - .spawn(futures::future::poll_fn(move || { - events - .spawn_tab(window_id) - .map(futures::Async::Ready) - .map_err(|_| ()) - })); - } fn toggle_full_screen(&mut self) {} } @@ -118,20 +86,10 @@ impl TerminalWindow for X11TerminalWindow { self.tabs.get_active().unwrap().terminal(), ) } - fn tab_was_created(&mut self, _tab_id: TabId) -> Result<(), Error> { - Ok(()) + fn tab_was_created(&mut self, tab: &Rc) -> Result<(), Error> { + self.host.event_loop.register_tab(tab) } - fn deregister_tab(&mut self, tab_id: TabId) -> Result<(), Error> { - let events = Rc::clone(&self.host.event_loop); - self.host - .event_loop - .core - .spawn(futures::future::poll_fn(move || { - events - .deregister_tab(tab_id) - .map(futures::Async::Ready) - .map_err(|_| ()) - })); + fn deregister_tab(&mut self, _tab_id: TabId) -> Result<(), Error> { Ok(()) } fn get_dimensions(&self) -> Dimensions { @@ -167,11 +125,9 @@ impl TerminalWindow for X11TerminalWindow { impl X11TerminalWindow { pub fn new( event_loop: &Rc, - terminal: term::Terminal, - pty: MasterPty, - process: Child, fonts: &Rc, config: &Rc, + tab: &Rc, ) -> Result { let palette = config .colors @@ -179,13 +135,20 @@ impl X11TerminalWindow { .map(|p| p.clone().into()) .unwrap_or_else(term::color::ColorPalette::default); + let terminal = tab.terminal(); + let screen = terminal.screen(); + let metrics = fonts.default_font_metrics()?; - let (cell_height, cell_width) = (metrics.cell_height, metrics.cell_width); + let (cell_height, cell_width) = ( + metrics.cell_height.ceil() as usize, + metrics.cell_width.ceil() as usize, + ); - let size = pty.get_size()?; - let width = size.ws_xpixel; - let height = size.ws_ypixel; + let width = cell_width * screen.physical_cols; + let height = cell_height * screen.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"); @@ -197,13 +160,9 @@ impl X11TerminalWindow { }); let renderer = Renderer::new(&host.window, width, height, fonts, palette)?; - let cell_height = cell_height.ceil() as usize; - let cell_width = cell_width.ceil() as usize; host.window.show(); - let tab = Tab::new(terminal, process, pty); - Ok(X11TerminalWindow { host, renderer, @@ -224,30 +183,6 @@ impl X11TerminalWindow { self.paint() } - pub fn try_read_pty(&mut self, tab_id: TabId) -> Result<(), Error> { - const BUFSIZE: usize = 8192; - let mut buf = [0; BUFSIZE]; - - let tab = self.tabs.get_by_id(tab_id)?; - - let result = tab.pty().read(&mut buf); - match result { - Ok(size) => { - tab.terminal().advance_bytes( - &buf[0..size], - &mut TabHost::new(&mut tab.pty(), &mut self.host), - ); - } - Err(err) => { - if err.kind() != io::ErrorKind::WouldBlock { - return Err(SessionTerminated::Error { err: err.into() }.into()); - } - } - } - - Ok(()) - } - fn decode_key(&self, event: &xcb::KeyPressEvent) -> Option<(KeyCode, KeyModifiers)> { self.conn.xkb_lookup_keysym(event) } @@ -280,6 +215,18 @@ impl X11TerminalWindow { None => return Ok(()), }; if let Some((code, mods)) = self.decode_key(key_press) { + if mods == KeyModifiers::SUPER && code == KeyCode::Char('n') { + GuiEventLoop::schedule_spawn_new_window( + &self.host.event_loop, + &self.host.config, + &self.host.fonts, + ); + return Ok(()); + } + if mods == KeyModifiers::SUPER && code == KeyCode::Char('t') { + self.host.with_window(|win| win.spawn_tab().map(|_| ())); + return Ok(()); + } tab.terminal().key_down( code, mods, diff --git a/term/src/terminal.rs b/term/src/terminal.rs index 3a1afc34c..d60f87f76 100644 --- a/term/src/terminal.rs +++ b/term/src/terminal.rs @@ -22,12 +22,6 @@ pub trait TerminalHost { /// Called when a URL is clicked fn click_link(&mut self, link: &Rc); - /// Create a new Window - fn new_window(&mut self) {} - - /// Create a new tab in the current window - fn new_tab(&mut self) {} - /// Switch to a specific tab fn activate_tab(&mut self, _tab: usize) {} diff --git a/term/src/terminalstate.rs b/term/src/terminalstate.rs index cd0d3ba79..73c12a14a 100644 --- a/term/src/terminalstate.rs +++ b/term/src/terminalstate.rs @@ -696,14 +696,6 @@ impl TerminalState { // TODO: also respect self.application_keypad - if mods == KeyModifiers::SUPER && key == KeyCode::Char('n') { - host.new_window(); - return Ok(()); - } - if mods == KeyModifiers::SUPER && key == KeyCode::Char('t') { - host.new_tab(); - return Ok(()); - } if mods == (KeyModifiers::SUPER | KeyModifiers::SHIFT) && (key == KeyCode::Char('[') || key == KeyCode::Char('{')) {