Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Replace winapi with windows crate bindings shared with WRY #206

Merged
merged 31 commits into from
Sep 22, 2021
Merged
Show file tree
Hide file tree
Changes from 27 commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
9da2f15
fix(deps): update rust crate libayatana-appindicator to 0.1.6 (#190)
renovate[bot] Sep 1, 2021
610d02f
Add Windows crate and webview2-com-sys bindings
wravery Sep 10, 2021
ea091b9
Initial port to webview2-com-sys
wravery Sep 11, 2021
45737c4
Finish conversion and remove winapi
wravery Sep 11, 2021
3756145
Fix renamed lint warning
wravery Sep 12, 2021
bf63503
Fix all match arms referencing const variables
wravery Sep 12, 2021
df22a8e
Put back the assert instead of expect
wravery Sep 12, 2021
7e3f657
Point to the published version of webview2-com-sys
wravery Sep 13, 2021
00ddbe1
Cleanup slightly weird BOOL handling
wravery Sep 13, 2021
0fb8aba
Replace mem::zeroed with Default::default
wravery Sep 13, 2021
118710b
Add a summary in .changes
wravery Sep 13, 2021
d23e144
Remove extra projects not in config.json
wravery Sep 13, 2021
009f060
Fix clippy warnings
wravery Sep 13, 2021
bc7f7c1
Update to 32-bit compatible webview2-com-sys
wravery Sep 13, 2021
5485032
Merge branch 'next' into webview2-com
wravery Sep 13, 2021
0c3ecb8
Better fix for merge conflict
wravery Sep 13, 2021
05ff95b
Fix clippy errors on Windows
wravery Sep 14, 2021
7d3eb0b
Use path prefix to prevent variable shadowing
wravery Sep 14, 2021
e940d6e
Fix Windows clippy warnings with nightly toolchain
wravery Sep 14, 2021
70e8f3f
Fix Linux nightly/stable clippy warnings
wravery Sep 14, 2021
b353fa5
Fix macOS nightly/stable clippy warnings
wravery Sep 14, 2021
8a0f806
Put back public *mut libc::c_void for consistency
wravery Sep 20, 2021
46b2c78
Re-run cargo fmt
wravery Sep 20, 2021
442761f
Move call_default_window_proc to util mod
wravery Sep 20, 2021
653be92
Remove unnecessary util::to_wstring calls
wravery Sep 20, 2021
7bfe37e
Don't repeat LRESULT expression in match arms
wravery Sep 20, 2021
3c0d0ec
Replace bitwise operations with util functions
wravery Sep 20, 2021
0355b02
Cleanup more bit mask & shift with util fns
wravery Sep 21, 2021
0c7a9a2
Prefer from conversions instead of as cast
wravery Sep 21, 2021
e2b9697
Implement get_xbutton_wparam
wravery Sep 21, 2021
30ce98c
Use *mut libc::c_void for return types
wravery Sep 21, 2021
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changes/webview2-com-sys.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"tao": patch
---

Replace all of the `winapi` crate references with the `windows` crate. The generated bindings are in the `webview2-com-sys` crate to share types with WRY later.
31 changes: 3 additions & 28 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -71,33 +71,8 @@ cc = "1"
[target."cfg(target_os = \"windows\")".dependencies]
parking_lot = "0.11"
unicode-segmentation = "1.8.0"

[target."cfg(target_os = \"windows\")".dependencies.winapi]
version = "0.3"
features = [
"combaseapi",
"commctrl",
"dwmapi",
"errhandlingapi",
"imm",
"hidusage",
"libloaderapi",
"objbase",
"ole2",
"processthreadsapi",
"shellapi",
"shellscalingapi",
"shobjidl_core",
"unknwnbase",
"winbase",
"windowsx",
"winerror",
"wingdi",
"winnt",
"winnls",
"winuser",
"impl-default"
]
webview2-com-sys = "0.4.0"
windows = "0.19.0"

[target."cfg(any(target_os = \"linux\", target_os = \"dragonfly\", target_os = \"freebsd\", target_os = \"openbsd\", target_os = \"netbsd\"))".dependencies]
cairo-rs = "0.14"
Expand All @@ -108,6 +83,6 @@ gtk = { version = "0.14", features = [ "v3_22" ] }
gdk = { version = "0.14", features = [ "v3_22" ] }
gdk-sys = "0.14"
gdk-pixbuf = { version = "0.14", features = [ "v2_36_8" ] }
libayatana-appindicator = { version = "0.1.4", optional = true }
libayatana-appindicator = { version = "0.1.6", optional = true }
tauri-libappindicator = { version = "0.1.2", optional = true }
x11-dl = "2.18"
4 changes: 2 additions & 2 deletions examples/parentwindow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ fn main() {
window::WindowBuilder,
};
#[cfg(target_os = "windows")]
use winapi::shared::windef::HWND;
use webview2_com_sys::Windows::Win32::Foundation::HWND;
SimpleLogger::new().init().unwrap();
let event_loop = EventLoop::new();
let mut windows = HashMap::new();
Expand All @@ -25,7 +25,7 @@ fn main() {
#[cfg(target_os = "macos")]
let parent_window = main_window.ns_window();
#[cfg(target_os = "windows")]
let parent_window = main_window.hwnd() as HWND;
let parent_window = HWND(main_window.hwnd() as _);

let child_window = WindowBuilder::new()
.with_parent_window(parent_window)
Expand Down
1 change: 1 addition & 0 deletions src/clipboard.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ pub(crate) type FormatId = &'static str;

/// Object that allows you to access the `ClipboardFormat`.
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub(crate) struct ClipboardFormat {
pub(crate) identifier: FormatId,
pub(crate) data: Vec<u8>,
Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@
clippy::wrong_self_convention
)]
#![deny(rust_2018_idioms)]
#![deny(broken_intra_doc_links)]
#![deny(rustdoc::broken_intra_doc_links)]

#[allow(unused_imports)]
#[macro_use]
Expand Down
47 changes: 23 additions & 24 deletions src/platform/windows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

#![cfg(target_os = "windows")]

use std::{os::raw::c_void, path::Path};
use std::path::Path;

pub use crate::platform_impl::hit_test;
use crate::{
Expand All @@ -15,12 +15,10 @@ use crate::{
window::{BadIcon, Icon, Theme, Window, WindowBuilder},
};
use libc;
use winapi::{
shared::{
minwindef::{self, WORD},
windef::{HMENU, HWND, POINT},
},
um::winuser,
use webview2_com_sys::Windows::Win32::{
Foundation::{HWND, LPARAM, WPARAM},
Graphics::Gdi::HMONITOR,
UI::{KeyboardAndMouseInput::*, WindowsAndMessaging::*},
};

/// Additional methods on `EventLoop` that are specific to Windows.
Expand Down Expand Up @@ -123,18 +121,18 @@ pub trait WindowExtWindows {
impl WindowExtWindows for Window {
#[inline]
fn hinstance(&self) -> *mut libc::c_void {
self.window.hinstance() as *mut _
self.window.hinstance().0 as _
}

#[inline]
fn hwnd(&self) -> *mut libc::c_void {
self.window.hwnd() as *mut _
self.window.hwnd().0 as _
}

#[inline]
fn set_enable(&self, enabled: bool) {
unsafe {
winapi::um::winuser::EnableWindow(self.hwnd() as _, enabled as _);
EnableWindow(self.window.hwnd(), enabled);
}
}

Expand All @@ -156,14 +154,14 @@ impl WindowExtWindows for Window {
#[inline]
fn begin_resize_drag(&self, edge: isize, button: u32, x: i32, y: i32) {
unsafe {
let point = POINT { x, y };
winuser::ReleaseCapture();
winuser::PostMessageW(
self.hwnd() as _,
button as minwindef::UINT,
edge as minwindef::WPARAM,
&point as *const _ as minwindef::LPARAM,
);
let w_param = WPARAM(edge as usize);

let low_word = x as u32 & 0xFFFF;
let high_word = (y as u32 & 0xFFFF) << 16;
wravery marked this conversation as resolved.
Show resolved Hide resolved
let l_param = LPARAM((low_word | high_word) as isize);

ReleaseCapture();
PostMessageW(self.window.hwnd(), button, w_param, l_param);
}
}

Expand Down Expand Up @@ -198,7 +196,8 @@ pub trait WindowBuilderExtWindows {
///
/// Parent and menu are mutually exclusive; a child window cannot have a menu!
///
/// The menu must have been manually created beforehand with [`winapi::um::winuser::CreateMenu`] or similar.
/// The menu must have been manually created beforehand with [`webview2_com_sys::Windows::Win32::UI::WindowsAndMessaging::CreateMenu`]
/// or similar.
///
/// Note: Dark mode cannot be supported for win32 menus, it's simply not possible to change how the menus look.
/// If you use this, it is recommended that you combine it with `with_theme(Some(Theme::Light))` to avoid a jarring effect.
Expand Down Expand Up @@ -281,7 +280,7 @@ pub trait MonitorHandleExtWindows {
fn native_id(&self) -> String;

/// Returns the handle of the monitor - `HMONITOR`.
fn hmonitor(&self) -> *mut c_void;
fn hmonitor(&self) -> HMONITOR;
wravery marked this conversation as resolved.
Show resolved Hide resolved
}

impl MonitorHandleExtWindows for MonitorHandle {
Expand All @@ -291,8 +290,8 @@ impl MonitorHandleExtWindows for MonitorHandle {
}

#[inline]
fn hmonitor(&self) -> *mut c_void {
self.inner.hmonitor() as *mut _
fn hmonitor(&self) -> HMONITOR {
self.inner.hmonitor()
}
}

Expand Down Expand Up @@ -329,7 +328,7 @@ pub trait IconExtWindows: Sized {
///
/// In cases where the specified size does not exist in the file, Windows may perform scaling
/// to get an icon of the desired size.
fn from_resource(ordinal: WORD, size: Option<PhysicalSize<u32>>) -> Result<Self, BadIcon>;
fn from_resource(ordinal: u16, size: Option<PhysicalSize<u32>>) -> Result<Self, BadIcon>;
}

impl IconExtWindows for Icon {
Expand All @@ -338,7 +337,7 @@ impl IconExtWindows for Icon {
Ok(Icon { inner: win_icon })
}

fn from_resource(ordinal: WORD, size: Option<PhysicalSize<u32>>) -> Result<Self, BadIcon> {
fn from_resource(ordinal: u16, size: Option<PhysicalSize<u32>>) -> Result<Self, BadIcon> {
let win_icon = WinIcon::from_resource(ordinal, size)?;
Ok(Icon { inner: win_icon })
}
Expand Down
29 changes: 13 additions & 16 deletions src/platform_impl/linux/event_loop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ use gtk::{prelude::*, AboutDialog, ApplicationWindow, Inhibit};
use crate::{
accelerator::AcceleratorId,
dpi::{PhysicalPosition, PhysicalSize},
event::{DeviceId as RootDeviceId, ElementState, Event, MouseButton, StartCause, WindowEvent},
event::{ElementState, Event, MouseButton, StartCause, WindowEvent},
event_loop::{ControlFlow, EventLoopClosed, EventLoopWindowTarget as RootELW},
keyboard::ModifiersState,
menu::{MenuItem, MenuType},
Expand All @@ -32,7 +32,6 @@ use super::{
keyboard,
monitor::MonitorHandle,
window::{WindowId, WindowRequest},
DeviceId,
};

pub struct EventLoopWindowTarget<T> {
Expand All @@ -55,7 +54,7 @@ impl<T> EventLoopWindowTarget<T> {
let numbers = display.n_monitors();

for i in 0..numbers {
let monitor = MonitorHandle::new(&display, i);
let monitor = MonitorHandle::new(display, i);
handles.push_back(monitor);
}

Expand Down Expand Up @@ -351,19 +350,17 @@ impl<T: 'static> EventLoop<T> {
Inhibit(false)
});
window.connect_button_press_event(|window, event| {
if !window.is_decorated() && window.is_resizable() {
if event.button() == 1 {
if let Some(window) = window.window() {
let (cx, cy) = event.root();
let result = hit_test(&window, cx, cy);

// Ignore the `__Unknown` variant so the window receives the click correctly if it is not on the edges.
match result {
WindowEdge::__Unknown(_) => (),
_ => {
// FIXME: calling `window.begin_resize_drag` uses the default cursor, it should show a resizing cursor instead
window.begin_resize_drag(result, 1, cx as i32, cy as i32, event.time())
}
if !window.is_decorated() && window.is_resizable() && event.button() == 1 {
if let Some(window) = window.window() {
let (cx, cy) = event.root();
let result = hit_test(&window, cx, cy);

// Ignore the `__Unknown` variant so the window receives the click correctly if it is not on the edges.
match result {
WindowEdge::__Unknown(_) => (),
_ => {
// FIXME: calling `window.begin_resize_drag` uses the default cursor, it should show a resizing cursor instead
window.begin_resize_drag(result, 1, cx as i32, cy as i32, event.time())
}
}
}
Expand Down
3 changes: 2 additions & 1 deletion src/platform_impl/linux/menu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ unsafe impl Send for Menu {}
unsafe impl Sync for Menu {}

#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct MenuItemAttributes {
id: MenuId,
key: Option<Accelerator>,
Expand Down Expand Up @@ -113,7 +114,7 @@ impl Menu {
menu_type: MenuType,
) -> CustomMenuItem {
let gtk_item = if selected {
let item = CheckMenuItem::with_label(&title);
let item = CheckMenuItem::with_label(title);
item.set_active(true);
item.upcast::<GtkMenuItem>()
} else {
Expand Down
10 changes: 1 addition & 9 deletions src/platform_impl/linux/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,19 +40,11 @@ pub struct KeyEventExtra {
pub key_without_modifiers: Key<'static>,
}

#[derive(Clone)]
#[derive(Clone, Default)]
pub struct PlatformSpecificWindowBuilderAttributes {
pub skip_taskbar: bool,
}

impl Default for PlatformSpecificWindowBuilderAttributes {
fn default() -> Self {
Self {
skip_taskbar: false,
}
}
}

unsafe impl Send for PlatformSpecificWindowBuilderAttributes {}
unsafe impl Sync for PlatformSpecificWindowBuilderAttributes {}

Expand Down
1 change: 1 addition & 0 deletions src/platform_impl/macos/monitor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,7 @@ impl fmt::Debug for MonitorHandle {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// TODO: Do this using the proper fmt API
#[derive(Debug)]
#[allow(dead_code)] // none of the member reads in Debug::fmt are detected
struct MonitorHandle {
name: Option<String>,
native_identifier: u32,
Expand Down
20 changes: 10 additions & 10 deletions src/platform_impl/windows/accelerator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,20 @@ use std::{
};

use lazy_static::lazy_static;
use winapi::{ctypes::c_int, shared::windef::*, um::winuser::*};

use webview2_com_sys::Windows::Win32::{Foundation::HWND, UI::WindowsAndMessaging::*};

// NOTE:
// https://docs.microsoft.com/en-us/windows/win32/wsw/thread-safety
// All handles you obtain from functions in Kernel32 are thread-safe,
// unless the MSDN Library article for the function explicitly mentions it is not.

#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
struct WindowHandle(HWND);
struct WindowHandle(isize);
amrbashir marked this conversation as resolved.
Show resolved Hide resolved
unsafe impl Send for WindowHandle {}

#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
struct AccelHandle(HACCEL);
struct AccelHandle(isize);
amrbashir marked this conversation as resolved.
Show resolved Hide resolved
unsafe impl Send for AccelHandle {}
unsafe impl Sync for AccelHandle {}

Expand All @@ -36,32 +37,31 @@ pub(crate) struct AccelTable {

impl AccelTable {
fn new(accel: &[ACCEL]) -> AccelTable {
let accel =
unsafe { CreateAcceleratorTableW(accel as *const _ as *mut _, accel.len() as c_int) };
let accel = unsafe { CreateAcceleratorTableW(accel as *const _ as *mut _, accel.len() as i32) };
AccelTable {
accel: AccelHandle(accel),
accel: AccelHandle(accel.0),
}
}

pub(crate) fn handle(&self) -> HACCEL {
self.accel.0
HACCEL(self.accel.0)
}
}

pub(crate) fn register_accel(hwnd: HWND, accel: &[ACCEL]) {
let mut table = ACCEL_TABLES.lock().unwrap();
table.insert(WindowHandle(hwnd), Arc::new(AccelTable::new(accel)));
table.insert(WindowHandle(hwnd.0), Arc::new(AccelTable::new(accel)));
}

impl Drop for AccelTable {
fn drop(&mut self) {
unsafe {
DestroyAcceleratorTable(self.accel.0);
DestroyAcceleratorTable(self.handle());
}
}
}

pub(crate) fn find_accels(hwnd: HWND) -> Option<Arc<AccelTable>> {
let table = ACCEL_TABLES.lock().unwrap();
table.get(&WindowHandle(hwnd)).cloned()
table.get(&WindowHandle(hwnd.0)).cloned()
}
Loading