Skip to content

Commit

Permalink
rename APIs which have winit/tao specific names
Browse files Browse the repository at this point in the history
- `UserEvent*` -> `Event*`
- `IpcMessage` -> `RendererMessage`
  • Loading branch information
rhysd committed Feb 4, 2024
1 parent b5d1524 commit 997ab8d
Show file tree
Hide file tree
Showing 9 changed files with 48 additions and 47 deletions.
3 changes: 2 additions & 1 deletion v2/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ Features:
- Sections outline in side navigation bar. The current section is automatically focused
- Both CLI and GUI friendly; Available as a single binary executable as well as a desktop application installed to your system
- Performance critical part (parsing Markdown text, searching Markdown AST, calculating the last modified position, ...) and
core application logic are written in [Rust][rust]. View logic is written in [TypeScript][ts] and [React][react]
core application logic are written in [Rust][rust]. View logic written in [TypeScript][ts] and [React][react] runs on
platform-specific WebView
- Cross platform; macOS, Windows, Linux are supported
- Customizable with [a YAML config file](./src/assets/default_config.yml) (color theme, keyboard shortcuts, custom CSS, ...)
- Dogs are respected :dog2:
Expand Down
16 changes: 8 additions & 8 deletions v2/src/renderer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,8 @@ pub enum MessageFromRenderer {
}

#[derive(Debug)]
pub enum UserEvent {
IpcMessage(MessageFromRenderer),
pub enum Event {
RendererMessage(MessageFromRenderer),
FileDrop(PathBuf),
WatchedFilesChanged(Vec<PathBuf>),
OpenLocalPath(PathBuf),
Expand Down Expand Up @@ -154,10 +154,10 @@ pub enum RenderingFlow {
Exit,
}

/// Sender to send [`UserEvent`] accross threads. It is used to send the user events to the main thread
/// Sender to send [`Event`] accross threads. It is used to send the user events to the main thread
/// from another worker thread.
pub trait UserEventSender: 'static + Send {
fn send(&self, event: UserEvent);
pub trait EventSender: 'static + Send {
fn send(&self, event: Event);
}

/// Renderer is responsible for rendering the actual UI in the rendering context.
Expand Down Expand Up @@ -185,19 +185,19 @@ pub trait Renderer {

/// Context to execute rendering.
pub trait Rendering: Sized {
type UserEventSender: UserEventSender;
type EventSender: EventSender;
type Renderer: Renderer;

fn new() -> Result<Self>;
fn create_sender(&self) -> Self::UserEventSender;
fn create_sender(&self) -> Self::EventSender;
fn create_renderer(&mut self, config: &Config) -> Result<Self::Renderer>;
/// Starts the rendering execution and runs until the process exits.
fn start<H: EventHandler + 'static>(self, handler: H) -> !;
}

/// Event handler which listens several rendering events.
pub trait EventHandler {
fn handle_user_event(&mut self, event: UserEvent) -> Result<RenderingFlow>;
fn handle_event(&mut self, event: Event) -> Result<RenderingFlow>;
fn handle_menu_event(&mut self, item: MenuItem) -> Result<RenderingFlow>;
fn handle_minimized(&mut self, is_active: bool);
fn handle_exit(&mut self) -> Result<()>;
Expand Down
6 changes: 3 additions & 3 deletions v2/src/sanity.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
use crate::renderer::{MessageFromRenderer, UserEvent, UserEventSender};
use crate::renderer::{Event, EventSender, MessageFromRenderer};
use std::thread::{sleep, spawn};
use std::time::Duration;

pub struct SanityTest<S> {
sender: Option<S>,
}

impl<S: UserEventSender> SanityTest<S> {
impl<S: EventSender> SanityTest<S> {
pub fn new(sender: S) -> Self {
Self { sender: Some(sender) }
}
Expand Down Expand Up @@ -39,7 +39,7 @@ impl<S: UserEventSender> SanityTest<S> {
for msg in messages {
sleep(Duration::from_millis(1000));
log::debug!("Sanity test case is about to send message: {msg:?}");
sender.send(UserEvent::IpcMessage(msg));
sender.send(Event::RendererMessage(msg));
}
});
}
Expand Down
22 changes: 11 additions & 11 deletions v2/src/shiba.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ use crate::dialog::Dialog;
use crate::markdown::{DisplayText, MarkdownContent, MarkdownParser};
use crate::opener::Opener;
use crate::renderer::{
EventHandler, MenuItem, MessageFromRenderer, MessageToRenderer, Renderer, Rendering,
RenderingFlow, UserEvent,
Event, EventHandler, MenuItem, MessageFromRenderer, MessageToRenderer, Renderer, Rendering,
RenderingFlow,
};
#[cfg(feature = "__sanity")]
use crate::sanity::SanityTest;
Expand Down Expand Up @@ -201,7 +201,7 @@ pub struct Shiba<R: Rendering, O, W, D> {
init_file: Option<PathBuf>,
_dialog: PhantomData<D>,
#[cfg(feature = "__sanity")]
sanity: SanityTest<R::UserEventSender>,
sanity: SanityTest<R::EventSender>,
}

impl<R, O, W, D> Shiba<R, O, W, D>
Expand Down Expand Up @@ -368,7 +368,7 @@ where
self.opener.open(&path)
}

fn handle_ipc_message(&mut self, message: MessageFromRenderer) -> Result<RenderingFlow> {
fn handle_renderer_message(&mut self, message: MessageFromRenderer) -> Result<RenderingFlow> {
use MessageFromRenderer::*;
match message {
Init => {
Expand Down Expand Up @@ -431,18 +431,18 @@ where
W: Watcher,
D: Dialog,
{
fn handle_user_event(&mut self, event: UserEvent) -> Result<RenderingFlow> {
fn handle_event(&mut self, event: Event) -> Result<RenderingFlow> {
log::debug!("Handling user event {:?}", event);
match event {
UserEvent::IpcMessage(msg) => return self.handle_ipc_message(msg),
UserEvent::FileDrop(mut path) => {
Event::RendererMessage(msg) => return self.handle_renderer_message(msg),
Event::FileDrop(mut path) => {
log::debug!("Previewing file dropped into window: {:?}", path);
if !path.is_absolute() {
path = path.canonicalize()?;
}
self.preview_new(path)?;
}
UserEvent::WatchedFilesChanged(mut paths) => {
Event::WatchedFilesChanged(mut paths) => {
log::debug!("Files changed: {:?}", paths);
if let Some(current) = self.history.current() {
if paths.contains(current) {
Expand All @@ -460,7 +460,7 @@ where
}
}
}
UserEvent::OpenLocalPath(mut path) => {
Event::OpenLocalPath(mut path) => {
if path.is_relative() {
if let Some(current_file) = self.history.current() {
if let Some(dir) = current_file.parent() {
Expand All @@ -478,11 +478,11 @@ where
self.opener.open(&path).with_context(|| format!("opening path {:?}", &path))?;
}
}
UserEvent::OpenExternalLink(link) => {
Event::OpenExternalLink(link) => {
log::debug!("Opening external link item clicked in WebView: {:?}", link);
self.opener.open(&link).with_context(|| format!("opening link {:?}", &link))?;
}
UserEvent::Error(err) => return Err(err),
Event::Error(err) => return Err(err),
}
Ok(RenderingFlow::Continue)
}
Expand Down
6 changes: 3 additions & 3 deletions v2/src/watcher/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ pub use system::SystemWatcher;
pub use system_linux::SystemWatcher;

use crate::config::{FileExtensions, Watch as Config};
use crate::renderer::UserEventSender;
use crate::renderer::EventSender;
use anyhow::Result;
use notify::event::{CreateKind, DataChange, EventKind, ModifyKind};
use std::collections::HashMap;
Expand Down Expand Up @@ -82,14 +82,14 @@ impl PathFilter {
}

pub trait Watcher: Sized {
fn new<S: UserEventSender>(sender: S, filter: PathFilter) -> Result<Self>;
fn new<S: EventSender>(sender: S, filter: PathFilter) -> Result<Self>;
fn watch(&mut self, path: &Path) -> Result<()>;
}

pub struct NopWatcher;

impl Watcher for NopWatcher {
fn new<S: UserEventSender>(_sender: S, _filter: PathFilter) -> Result<Self> {
fn new<S: EventSender>(_sender: S, _filter: PathFilter) -> Result<Self> {
Ok(Self)
}
fn watch(&mut self, _path: &Path) -> Result<()> {
Expand Down
8 changes: 4 additions & 4 deletions v2/src/watcher/system.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
use super::{find_watch_path_fallback, should_watch_event, PathFilter, Watcher};
use crate::renderer::{UserEvent, UserEventSender};
use crate::renderer::{Event, EventSender};
use anyhow::{Context as _, Result};
use notify::{recommended_watcher, RecommendedWatcher, RecursiveMode, Watcher as NotifyWatcher};
use std::path::Path;

impl Watcher for RecommendedWatcher {
fn new<S: UserEventSender>(sender: S, mut filter: PathFilter) -> Result<Self> {
fn new<S: EventSender>(sender: S, mut filter: PathFilter) -> Result<Self> {
let watcher = recommended_watcher(move |res: notify::Result<notify::Event>| match res {
Ok(event) if should_watch_event(event.kind) => {
log::debug!("Caught filesystem event: {:?}", event);
Expand All @@ -15,15 +15,15 @@ impl Watcher for RecommendedWatcher {

if !paths.is_empty() {
log::debug!("Files change event from watcher: {:?}", paths);
sender.send(UserEvent::WatchedFilesChanged(paths));
sender.send(Event::WatchedFilesChanged(paths));
}

filter.cleanup_debouncer();
}
Ok(event) => log::debug!("Ignored filesystem event: {:?}", event),
Err(err) => {
log::error!("Error on watching file changes: {}", err);
sender.send(UserEvent::Error(err.into()));
sender.send(Event::Error(err.into()));
}
})?;
Ok(watcher)
Expand Down
8 changes: 4 additions & 4 deletions v2/src/watcher/system_linux.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use super::{find_watch_path_fallback, should_watch_event, PathFilter, Watcher};
use crate::renderer::{UserEvent, UserEventSender};
use crate::renderer::{Event, EventSender};
use anyhow::{Context as _, Result};
use notify::{recommended_watcher, RecommendedWatcher, RecursiveMode, Watcher as NotifyWatcher};
use std::collections::{HashMap, HashSet};
Expand Down Expand Up @@ -66,7 +66,7 @@ pub struct SystemWatcher {
}

impl Watcher for SystemWatcher {
fn new<S: UserEventSender>(sender: S, mut filter: PathFilter) -> Result<Self> {
fn new<S: EventSender>(sender: S, mut filter: PathFilter) -> Result<Self> {
let watching = Arc::new(Mutex::new(WatchingPaths::default()));
let inner = {
let watching = watching.clone();
Expand All @@ -82,15 +82,15 @@ impl Watcher for SystemWatcher {

if !paths.is_empty() {
log::debug!("Files change event from watcher: {:?}", paths);
sender.send(UserEvent::WatchedFilesChanged(paths));
sender.send(Event::WatchedFilesChanged(paths));
}

filter.cleanup_debouncer();
}
Ok(event) => log::debug!("Ignored filesystem event: {:?}", event),
Err(err) => {
log::error!("Error on watching file changes: {}", err);
sender.send(UserEvent::Error(err.into()));
sender.send(Event::Error(err.into()));
}
})?
};
Expand Down
12 changes: 6 additions & 6 deletions v2/src/wry/event_loop.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::config::Config;
use crate::renderer::{EventHandler, Rendering, RenderingFlow, UserEvent, UserEventSender};
use crate::renderer::{Event as AppEvent, EventHandler, EventSender, Rendering, RenderingFlow};
use crate::wry::menu::{Menu, MenuEvents};
use crate::wry::webview::{EventLoop, WebViewRenderer};
use anyhow::Result;
Expand All @@ -13,16 +13,16 @@ pub struct Wry {
menu: Menu, // On Windows, Menu instance needs to be created before creating the event loop
}

impl UserEventSender for EventLoopProxy<UserEvent> {
fn send(&self, event: UserEvent) {
impl EventSender for EventLoopProxy<AppEvent> {
fn send(&self, event: AppEvent) {
if let Err(err) = self.send_event(event) {
log::error!("Could not send user event for message from WebView: {}", err);
}
}
}

impl Rendering for Wry {
type UserEventSender = EventLoopProxy<UserEvent>;
type EventSender = EventLoopProxy<AppEvent>;
type Renderer = WebViewRenderer;

#[cfg(not(target_os = "windows"))]
Expand Down Expand Up @@ -57,7 +57,7 @@ impl Rendering for Wry {
Ok(Self { event_loop, menu_events, menu })
}

fn create_sender(&self) -> Self::UserEventSender {
fn create_sender(&self) -> Self::EventSender {
self.event_loop.create_proxy()
}

Expand All @@ -84,7 +84,7 @@ impl Rendering for Wry {
log::debug!("Closing window was requested");
RenderingFlow::Exit
}
Event::UserEvent(event) => handler.handle_user_event(event).unwrap_or_else(|err| {
Event::UserEvent(event) => handler.handle_event(event).unwrap_or_else(|err| {
handler.handle_error(err.context("Could not handle user event"))
}),
Event::WindowEvent { event: WindowEvent::Resized(size), .. } => {
Expand Down
14 changes: 7 additions & 7 deletions v2/src/wry/webview.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ use crate::assets::Assets;
use crate::config::{Config, WindowTheme as ThemeConfig};
use crate::persistent::WindowState;
use crate::renderer::{
MessageFromRenderer, MessageToRenderer, RawMessageWriter, Renderer, Theme as RendererTheme,
UserEvent, WindowAppearance, ZoomLevel,
Event, MessageFromRenderer, MessageToRenderer, RawMessageWriter, Renderer,
Theme as RendererTheme, WindowAppearance, ZoomLevel,
};
use crate::wry::menu::Menu;
use anyhow::{Context as _, Result};
Expand All @@ -21,7 +21,7 @@ use wry::{FileDropEvent, WebContext, WebView, WebViewBuilder};
#[cfg(target_os = "windows")]
use wry::{MemoryUsageLevel, WebViewBuilderExtWindows, WebViewExtWindows};

pub type EventLoop = tao::event_loop::EventLoop<UserEvent>;
pub type EventLoop = tao::event_loop::EventLoop<Event>;

#[cfg(not(target_os = "macos"))]
const ICON_RGBA: &[u8] = include_bytes!("../assets/icon_32x32.rgba");
Expand Down Expand Up @@ -57,15 +57,15 @@ fn create_webview(window: &Window, event_loop: &EventLoop, config: &Config) -> R
.with_ipc_handler(move |msg| {
let msg: MessageFromRenderer = serde_json::from_str(&msg).unwrap();
log::debug!("Message from WebView: {msg:?}");
if let Err(err) = ipc_proxy.send_event(UserEvent::IpcMessage(msg)) {
if let Err(err) = ipc_proxy.send_event(Event::RendererMessage(msg)) {
log::error!("Could not send user event for message from WebView: {err}");
}
})
.with_file_drop_handler(move |event| {
if let FileDropEvent::Dropped { paths, .. } = event {
log::debug!("Files were dropped (the first one will be opened): {paths:?}",);
if let Some(path) = paths.into_iter().next() {
if let Err(err) = file_drop_proxy.send_event(UserEvent::FileDrop(path)) {
if let Err(err) = file_drop_proxy.send_event(Event::FileDrop(path)) {
log::error!("Could not send user event for file drop: {err}");
}
}
Expand Down Expand Up @@ -104,10 +104,10 @@ fn create_webview(window: &Window, event_loop: &EventLoop, config: &Config) -> R
let path = url.replace('/', "\\").into();

log::debug!("Opening local path {:?}", path);
UserEvent::OpenLocalPath(path)
Event::OpenLocalPath(path)
} else {
log::debug!("Navigating to external URL {:?}", url);
UserEvent::OpenExternalLink(url)
Event::OpenExternalLink(url)
};

if let Err(e) = navigation_proxy.send_event(event) {
Expand Down

0 comments on commit 997ab8d

Please sign in to comment.