0% found this document useful (0 votes)
10 views4 pages

Mac Auto-Window Resizer Script

The document is a Python script for a Mac Window Auto-Resizer that automatically resizes application windows that exceed a specified size after exiting full-screen mode. It uses AppleScript to gather window information, resize windows, and monitor the current frontmost application. The script can be run in two modes: to resize the current window or to continuously monitor and resize windows that are too large.

Uploaded by

gamingkheeda
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views4 pages

Mac Auto-Window Resizer Script

The document is a Python script for a Mac Window Auto-Resizer that automatically resizes application windows that exceed a specified size after exiting full-screen mode. It uses AppleScript to gather window information, resize windows, and monitor the current frontmost application. The script can be run in two modes: to resize the current window or to continuously monitor and resize windows that are too large.

Uploaded by

gamingkheeda
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

#!

/usr/bin/env python3
"""
Mac Window Auto-Resizer
Automatically resizes windows when they become too large after exiting full-screen
"""

import subprocess
import json
import time
import sys

def get_window_info():
"""Get information about all windows using yabai-like approach"""
try:
# Using AppleScript to get window information
script = '''
tell application "System Events"
set windowList to {}
repeat with proc in (every process whose background only is false)
try
repeat with win in (every window of proc)
if exists win then
set winInfo to {name of proc, name of win, position of
win, size of win}
set end of windowList to winInfo
end if
end repeat
end try
end repeat
return windowList
end tell
'''

result = [Link](['osascript', '-e', script],


capture_output=True, text=True, check=True)
return [Link]()
except [Link] as e:
print(f"Error getting window info: {e}")
return None

def resize_window(app_name, window_name, new_width=1200, new_height=800):


"""Resize a specific window"""
script = f'''
tell application "System Events"
tell process "{app_name}"
try
set frontmost to true
tell window "{window_name}"
set position to {{100, 100}}
set size to {{{new_width}, {new_height}}}
end tell
return "success"
on error errMsg
return "error: " & errMsg
end try
end tell
end tell
'''
try:
result = [Link](['osascript', '-e', script],
capture_output=True, text=True, check=True)
return [Link]()
except [Link] as e:
return f"Error: {e}"

def get_screen_size():
"""Get screen dimensions"""
script = '''
tell application "Finder"
set screenBounds to bounds of window of desktop
return {item 3 of screenBounds, item 4 of screenBounds}
end tell
'''

try:
result = [Link](['osascript', '-e', script],
capture_output=True, text=True, check=True)
# Parse the result to get width and height
bounds = [Link]().replace('{', '').replace('}', '').split(',
')
return int(bounds[0]), int(bounds[1])
except:
return 1920, 1080 # Default fallback

def auto_resize_large_windows(threshold_percentage=0.8):
"""Automatically resize windows that are too large"""
screen_width, screen_height = get_screen_size()
threshold_width = screen_width * threshold_percentage
threshold_height = screen_height * threshold_percentage

print(f"Screen size: {screen_width}x{screen_height}")


print(f"Will resize windows larger than:
{int(threshold_width)}x{int(threshold_height)}")

# Get current frontmost application


get_frontmost_script = '''
tell application "System Events"
set frontApp to name of first application process whose frontmost is true
set frontWindow to ""
try
set frontWindow to name of front window of process frontApp
end try
return frontApp & "|" & frontWindow
end tell
'''

try:
result = [Link](['osascript', '-e', get_frontmost_script],
capture_output=True, text=True, check=True)
app_info = [Link]().split('|')
app_name = app_info[0]
window_name = app_info[1] if len(app_info) > 1 else ""

if not window_name:
print(f"No window found for {app_name}")
return
# Get window size
get_size_script = f'''
tell application "System Events"
tell process "{app_name}"
try
tell window "{window_name}"
return size
end tell
end try
end tell
end tell
'''

result = [Link](['osascript', '-e', get_size_script],


capture_output=True, text=True, check=True)
size_str = [Link]().replace('{', '').replace('}', '')
current_width, current_height = map(int, size_str.split(', '))

print(f"Current window: {app_name} - {window_name}")


print(f"Current size: {current_width}x{current_height}")

# Check if window is too large


if current_width > threshold_width or current_height > threshold_height:
new_width = min(1400, int(screen_width * 0.7))
new_height = min(900, int(screen_height * 0.7))

print(f"Window is too large! Resizing to {new_width}x{new_height}")


result = resize_window(app_name, window_name, new_width, new_height)
print(f"Resize result: {result}")
else:
print("Window size is acceptable")

except [Link] as e:
print(f"Error getting frontmost window: {e}")

def main():
if len([Link]) > 1:
if [Link][1] == "monitor":
print("Starting window monitor mode...")
print("Press Ctrl+C to stop")
try:
while True:
auto_resize_large_windows()
[Link](2) # Check every 2 seconds
except KeyboardInterrupt:
print("\nStopped monitoring")
elif [Link][1] == "resize-current":
print("Resizing current window...")
auto_resize_large_windows()
else:
print("Mac Window Auto-Resizer")
print("Usage:")
print(" python3 window_resizer.py resize-current # Resize current window
if too large")
print(" python3 window_resizer.py monitor # Monitor and auto-
resize continuously")
print("\nNote: You may need to grant accessibility permissions to
Terminal")
print("Go to: System Settings > Privacy & Security > Accessibility")
if __name__ == "__main__":
main()

Common questions

Powered by AI

The script resizes windows by setting a new size and position for a specific window using an AppleScript command. This command adjusts windows to a pre-defined maximum of 1400x900 pixels or 70% of the screen dimensions if the window exceeds a threshold size relative to the screen's dimensions. This method is implemented using the 'resize_window' function executed via subprocess .

The script identifies the frontmost application by utilizing AppleScript to communicate with 'System Events'. It retrieves the name of the first application process that is currently frontmost, along with the name of its front window. If a window is found, the script proceeds to gather its size; otherwise, it handles the case with a fallback message .

Accessibility permissions are crucial for the script to execute successfully because it relies on AppleScript commands to interact with other applications' windows. These commands, executed via Python's subprocess, require permission to control the computer. Users must grant these permissions through System Preferences under 'Privacy & Security' to allow the script to get window information and resize them effectively, highlighting the intersection of system security and automation accessibility .

The script ensures proportional resizing by calculating the new window dimensions based on a fixed proportion (70%) of the screen size limits rather than arbitrary values. This proportional approach allows resized windows to maintain relative size consistency across different screen dimensions, providing a logical and visually coherent resizing mechanism .

The script triggers a window resize when it detects that the current window's width or height exceeds 80% of the screen's respective dimensions. When resizing is required, the script calculates new dimensions by taking the lesser of 1400 pixels or 70% of the screen's width for the new width, and the lesser of 900 pixels or 70% of the screen's height for the new height, ensuring the new size is within bounds .

The script is designed primarily for users who require an automated way to manage window sizes on Mac systems, especially when exiting full-screen mode. Its reliance on AppleScript and requirement for terminal accessibility permissions suggest it is intended for users comfortable with technical setups. The script also includes command-line instructions, further indicating an audience familiar with basic command-line operations and system configurations .

The script uses AppleScript to obtain information about all windows by querying 'System Events' to list all processes with foreground windows. It then compiles a list of each window's process name, window name, position, and size. This is accomplished with an AppleScript command executed through Python's subprocess module .

The script can be run in a continuous monitoring mode where it periodically checks and resizes windows every two seconds. While this enables real-time management of window sizes, it also implies a constant use of system resources due to repeated subprocess calls and scripting operations, which could affect system performance depending on the script's execution frequency and the system's processing capabilities .

The script's approach to error handling involves try-except blocks to catch and report subprocess execution errors when OS commands fail during window information retrieval or resizing. While this prevents abrupt crashes, the script could benefit from more sophisticated error mitigation strategies, such as retry mechanisms or user notifications to guide corrective actions, which are partially addressed via informative error prints .

If the default screen dimensions of 1920x1080 are used due to a failure in retrieving actual screen size, the script might make inaccurate resizing decisions. Windows could potentially be resized based on incorrect thresholds if the screen is actually smaller, leading to portions of windows being obscured or off-screen. Thus, ensuring accurate screen dimension retrieval is critical for optimal functionality .

You might also like