refactor(rust): remove lots of unsafe blocks

This commit is contained in:
LGUG2Z committed 2025-10-06 16:50:10 -07:00
1 parent 0789ed0136
commit 05e4222a23
9 files changed
+120 -157

No files matched your search

+5 -8
View File
@@ -118,14 +118,11 @@ Licenses [can be found here](https://lgug2z.com/software/komorebi).
_komorebi for Mac_ is currently not accepting contributions.
[//]: # (If you would like to contribute to `komorebi` please take the time to carefully)
[//]: # (read the guidelines below.)
[//]: # ()
[//]: # (Please see [CONTRIBUTING.md](./CONTRIBUTING.md) for more information about how)
[//]: # (code contributions to `komorebi` are licensed.)
[//]: # "If you would like to contribute to `komorebi` please take the time to carefully"
[//]: # "read the guidelines below."
[//]: #
[//]: # "Please see [CONTRIBUTING.md](./CONTRIBUTING.md) for more information about how"
[//]: # "code contributions to `komorebi` are licensed."
## Commit hygiene
@@ -69,7 +69,7 @@ impl TryFrom<NSNotification> for AppKitWorkspaceNotification {
type Error = strum::ParseError;
fn try_from(value: NSNotification) -> Result<Self, Self::Error> {
let name = unsafe { value.name().to_string() };
let name = value.name().to_string();
AppKitWorkspaceNotification::from_str(&name)
}
+1 -3
View File
@@ -101,9 +101,7 @@ impl Border {
let rect = MacosApi::window_rect(&element).unwrap_or_default();
let frame = Rect::from(CoreGraphicsApi::display_bounds(unsafe {
CGMainDisplayID()
}));
let frame = Rect::from(CoreGraphicsApi::display_bounds(CGMainDisplayID()));
let ns_rect = NSRect::new(
NSPoint::new(
rect.origin.x,
+14 -22
View File
@@ -64,37 +64,31 @@ impl NsWindow {
};
// Make transparent
unsafe {
window.setBackgroundColor(Some(&NSColor::clearColor()));
window.setAnimationBehavior(NSWindowAnimationBehavior::None);
window.disableSnapshotRestoration();
window.setPreservesContentDuringLiveResize(false);
window.setRestorable(false);
}
window.setBackgroundColor(Some(&NSColor::clearColor()));
window.setAnimationBehavior(NSWindowAnimationBehavior::None);
window.disableSnapshotRestoration();
window.setPreservesContentDuringLiveResize(false);
window.setRestorable(false);
window.setHasShadow(false);
window.setOpaque(false);
window.setLevel(NSNormalWindowLevel);
window.setIgnoresMouseEvents(true);
unsafe {
window.setCollectionBehavior(
NSWindowCollectionBehavior::CanJoinAllSpaces |
NSWindowCollectionBehavior::Stationary |
NSWindowCollectionBehavior::IgnoresCycle |
NSWindowCollectionBehavior::Transient
);
}
window.setCollectionBehavior(
NSWindowCollectionBehavior::CanJoinAllSpaces |
NSWindowCollectionBehavior::Stationary |
NSWindowCollectionBehavior::IgnoresCycle |
NSWindowCollectionBehavior::Transient
);
let content_view = {
let view = NSView::alloc(mtm);
unsafe { NSView::initWithFrame(view, window_frame) }
NSView::initWithFrame(view, window_frame)
};
content_view.setWantsLayer(true);
unsafe {
content_view.setAutoresizesSubviews(false);
}
content_view.setAutoresizesSubviews(false);
// Create and configure the layer for the border
let layer = {
@@ -120,9 +114,7 @@ impl NsWindow {
}
};
unsafe {
content_view.setLayer(Some(&layer));
}
content_view.setLayer(Some(&layer));
window.setContentView(Some(&content_view));
window.setMovableByWindowBackground(false);
+13 -17
View File
@@ -20,19 +20,17 @@ pub struct CoreGraphicsApi;
impl CoreGraphicsApi {
pub fn warp_mouse_cursor_position(x: i32, y: i32) -> Result<(), CoreGraphicsError> {
match unsafe {
CoreGraphicsError::from(CGWarpMouseCursorPosition(CGPoint::new(
x as CGFloat,
y as CGFloat,
)))
} {
match CoreGraphicsError::from(CGWarpMouseCursorPosition(CGPoint::new(
x as CGFloat,
y as CGFloat,
))) {
CoreGraphicsError::Success => Ok(()),
error => Err(error),
}
}
pub fn contains_rect(smaller: CGRect, bigger: CGRect) -> bool {
unsafe { CGRectIntersectsRect(smaller, bigger) }
CGRectIntersectsRect(smaller, bigger)
}
pub fn connected_display_ids() -> Result<Vec<u32>, CoreGraphicsError> {
@@ -55,11 +53,11 @@ impl CoreGraphicsApi {
}
pub fn display_bounds(display_id: u32) -> CGRect {
unsafe { CGDisplayBounds(display_id) }
CGDisplayBounds(display_id)
}
pub fn display_serial_number(display_id: u32) -> u32 {
unsafe { CGDisplaySerialNumber(display_id) }
CGDisplaySerialNumber(display_id)
}
pub fn display_bounds_for_window_rect(window_rect: CGRect) -> Option<CGRect> {
@@ -113,13 +111,11 @@ impl CoreGraphicsApi {
}
pub fn window_list_info() -> Option<CFRetained<CFArray>> {
unsafe {
CGWindowListCopyWindowInfo(
// this is still way too many bogus windows
CGWindowListOption::OptionOnScreenOnly | CGWindowListOption::ExcludeDesktopElements,
// required when using OnScreenOnly
kCGNullWindowID,
)
}
CGWindowListCopyWindowInfo(
// this is still way too many bogus windows
CGWindowListOption::OptionOnScreenOnly | CGWindowListOption::ExcludeDesktopElements,
// required when using OnScreenOnly
kCGNullWindowID,
)
}
}
+1 -3
View File
@@ -92,8 +92,6 @@ impl InputEventListener {
impl Drop for InputEventListener {
fn drop(&mut self) {
CFMachPort::invalidate(&self.port);
unsafe {
CGEvent::tap_enable(&self.port, false);
}
CGEvent::tap_enable(&self.port, false);
}
}
+8 -10
View File
@@ -60,7 +60,7 @@ impl MacosApi {
DispatchQueue::main().exec_async(move || {
let ns_path = NSString::from_str(&path_str);
let url = unsafe { NSURL::fileURLWithPath(&ns_path) };
let url = NSURL::fileURLWithPath(&ns_path);
let mtm = unsafe { MainThreadMarker::new_unchecked() };
let screens = NSScreen::screens(mtm);
@@ -72,7 +72,7 @@ impl MacosApi {
&& let Ok(did) = did.downcast::<NSNumber>()
&& did.as_u32() == display_id
{
let workspace = unsafe { NSWorkspace::sharedWorkspace() };
let workspace = NSWorkspace::sharedWorkspace();
unsafe {
if let Err(error) = workspace.setDesktopImageURL_forScreen_options_error(
&url,
@@ -235,7 +235,7 @@ impl MacosApi {
MonitorInfo {
alphanumeric_serial_number: serial_number.to_string(),
manufacturer_id: "".to_string(),
product_name: unsafe { screen.localizedName() }.to_string(),
product_name: screen.localizedName().to_string(),
legacy_manufacturer_id: "".to_string(),
product_id: "".to_string(),
serial_number,
@@ -265,7 +265,7 @@ impl MacosApi {
let visible_frame = screen.visibleFrame();
let primary_display_height =
CoreGraphicsApi::display_bounds(unsafe { CGMainDisplayID() })
CoreGraphicsApi::display_bounds(CGMainDisplayID())
.size
.height;
@@ -446,11 +446,9 @@ impl MacosApi {
}
pub fn cursor_pos() -> CGPoint {
unsafe {
let source = CGEventSource::new(CGEventSourceStateID::HIDSystemState);
let event = CGEvent::new(source.as_deref());
CGEvent::location(event.as_deref())
}
let source = CGEventSource::new(CGEventSourceStateID::HIDSystemState);
let event = CGEvent::new(source.as_deref());
CGEvent::location(event.as_deref())
}
pub fn monitor_from_point(point: CGPoint) -> Option<u32> {
@@ -458,6 +456,6 @@ impl MacosApi {
}
pub fn left_mouse_button_is_pressed() -> bool {
(unsafe { NSEvent::pressedMouseButtons() } & 0x1 != 0)
NSEvent::pressedMouseButtons() & 0x1 != 0
}
}
+45 -47
View File
@@ -32,60 +32,58 @@ define_class! {
impl NotificationCenterListenerNsObject {
#[unsafe(method(handleNotification:))]
fn handle_notification(&self, notif: &NSNotification) {
unsafe {
let mut process_id = None;
let mut window_id = None;
let mut valid_keys = vec![];
let mut process_id = None;
let mut window_id = None;
let mut valid_keys = vec![];
if let Some(user_info) = notif.userInfo() {
let all_keys = user_info.allKeys();
for k in all_keys {
if let Some(key) = k.downcast_ref::<NSString>() {
valid_keys.push(key.to_string());
}
}
if let Some(application_key) =
user_info.valueForKey(&NSString::from_str("NSWorkspaceApplicationKey"))
&& let Some(application) = application_key.downcast_ref::<NSRunningApplication>()
{
process_id = Some(application.processIdentifier());
if let Ok(application) = Application::new(application.processIdentifier()) {
window_id = application.main_window_id();
}
if let Some(user_info) = notif.userInfo() {
let all_keys = user_info.allKeys();
for k in all_keys {
if let Some(key) = k.downcast_ref::<NSString>() {
valid_keys.push(key.to_string());
}
}
tracing::trace!("received {} with keys {}", notif.name(), valid_keys.join(", "));
if let Some(application_key) =
user_info.valueForKey(&NSString::from_str("NSWorkspaceApplicationKey"))
&& let Some(application) = application_key.downcast_ref::<NSRunningApplication>()
{
process_id = Some(application.processIdentifier());
if let Ok(application) = Application::new(application.processIdentifier()) {
window_id = application.main_window_id();
}
}
}
match process_id {
None => {
if let Ok(notification) =
AppKitWorkspaceNotification::from_str(&notif.name().to_string()) {
if matches!(notification, AppKitWorkspaceNotification::NSWorkspaceActiveSpaceDidChangeNotification) {
// TODO: this is really, really stupid
window_manager_event_listener::send_notification(WindowManagerEvent::SpaceChange(SystemNotification::AppKitWorkspace(notification), 0));
}
} else {
tracing::debug!(
"notification: {}, skipping as there is no associated process id",
notif.name()
);
tracing::trace!("received {} with keys {}", notif.name(), valid_keys.join(", "));
match process_id {
None => {
if let Ok(notification) =
AppKitWorkspaceNotification::from_str(&notif.name().to_string()) {
if matches!(notification, AppKitWorkspaceNotification::NSWorkspaceActiveSpaceDidChangeNotification) {
// TODO: this is really, really stupid
window_manager_event_listener::send_notification(WindowManagerEvent::SpaceChange(SystemNotification::AppKitWorkspace(notification), 0));
}
} else {
tracing::debug!(
"notification: {}, skipping as there is no associated process id",
notif.name()
);
}
Some(process_id) => {
tracing::debug!("notification: {}, process: {process_id}", notif.name());
if let Ok(notification) =
AppKitWorkspaceNotification::from_str(&notif.name().to_string())
&& let Some(event) = WindowManagerEvent::from_system_notification(
SystemNotification::AppKitWorkspace(notification),
process_id,
window_id,
)
{
window_manager_event_listener::send_notification(event);
};
}
}
Some(process_id) => {
tracing::debug!("notification: {}, process: {process_id}", notif.name());
if let Ok(notification) =
AppKitWorkspaceNotification::from_str(&notif.name().to_string())
&& let Some(event) = WindowManagerEvent::from_system_notification(
SystemNotification::AppKitWorkspace(notification),
process_id,
window_id,
)
{
window_manager_event_listener::send_notification(event);
};
}
}
}
+32 -46
View File
@@ -414,10 +414,7 @@ impl Window {
}
pub fn bundle_identifier(&self) -> Option<String> {
if let Ok(Some(identifier)) = self
.running_application()
.map(|app| unsafe { app.bundleIdentifier() })
{
if let Ok(Some(identifier)) = self.running_application().map(|app| app.bundleIdentifier()) {
Some(identifier.to_string())
} else {
None
@@ -427,7 +424,7 @@ impl Window {
pub fn bundle_path(&self) -> Option<PathBuf> {
if let Ok(Some(path)) = self
.running_application()
.map(|app| unsafe { app.bundleURL() })
.map(|app| app.bundleURL())
.map(|url| url.map(|url| url.to_file_path()))
{
path
@@ -439,7 +436,7 @@ impl Window {
pub fn path(&self) -> Option<PathBuf> {
if let Ok(Some(path)) = self
.running_application()
.map(|app| unsafe { app.executableURL() })
.map(|app| app.executableURL())
.map(|ns_url| ns_url.map(|url| url.to_file_path()))
{
path
@@ -449,27 +446,23 @@ impl Window {
}
pub fn icon_path(&self) -> Option<PathBuf> {
if let Some(path) = self.bundle_path() {
unsafe {
if let Some(bundle) =
NSBundle::bundleWithPath(&NSString::from_str(&path.to_string_lossy()))
&& let Some(icon_file) =
bundle.objectForInfoDictionaryKey(&NSString::from_str("CFBundleIconFile"))
&& let Ok(icon_name) = icon_file.downcast::<NSString>()
{
let mut icon_path =
format!("{}/Contents/Resources/{}", path.display(), icon_name);
if let Some(path) = self.bundle_path()
&& let Some(bundle) =
NSBundle::bundleWithPath(&NSString::from_str(&path.to_string_lossy()))
&& let Some(icon_file) =
bundle.objectForInfoDictionaryKey(&NSString::from_str("CFBundleIconFile"))
&& let Ok(icon_name) = icon_file.downcast::<NSString>()
{
let mut icon_path = format!("{}/Contents/Resources/{}", path.display(), icon_name);
if !icon_path.ends_with(".icns") {
icon_path.push_str(".icns");
}
if !icon_path.ends_with(".icns") {
icon_path.push_str(".icns");
}
let path = Path::new(&icon_path);
let path = Path::new(&icon_path);
if path.exists() {
return Some(PathBuf::from(path));
}
}
if path.exists() {
return Some(PathBuf::from(path));
}
}
@@ -487,14 +480,10 @@ impl Window {
}
fn running_application(&self) -> Result<Retained<NSRunningApplication>, AccessibilityError> {
unsafe {
NSRunningApplication::runningApplicationWithProcessIdentifier(
self.application.process_id,
)
NSRunningApplication::runningApplicationWithProcessIdentifier(self.application.process_id)
.ok_or(AccessibilityError::Custom(
AccessibilityCustomError::NSRunningApplication(self.application.process_id),
))
}
}
pub fn set_position(&self, rect: &Rect) -> Result<(), AccessibilityError> {
@@ -509,26 +498,23 @@ impl Window {
}
pub fn focus(&self, mouse_follows_focus: bool) -> Result<(), LibraryError> {
unsafe {
match self.running_application() {
Ok(running_application) => {
running_application
.activateWithOptions(NSApplicationActivationOptions::empty());
}
Err(error) => {
tracing::warn!(
"failed to get running application for {} ({:?}): {error}",
self.application.process_id,
self.application.name()
);
}
match self.running_application() {
Ok(running_application) => {
running_application.activateWithOptions(NSApplicationActivationOptions::empty());
}
Err(error) => {
tracing::warn!(
"failed to get running application for {} ({:?}): {error}",
self.application.process_id,
self.application.name()
);
}
let cf_boolean = CFBoolean::new(true);
let value = &**cf_boolean;
AccessibilityApi::set_attribute_cf_value(&self.element, kAXMainAttribute, value)?;
}
let cf_boolean = CFBoolean::new(true);
let value = &**cf_boolean;
AccessibilityApi::set_attribute_cf_value(&self.element, kAXMainAttribute, value)?;
if mouse_follows_focus {
MacosApi::center_cursor_in_rect(&MacosApi::window_rect(&self.element)?.into())?
}