├── .gitignore ├── AutoRaise.dmg ├── AutoRaise.icns ├── AutoRaise.mm ├── Info.plist ├── LICENSE.md ├── Makefile ├── README.md └── create-app-bundle.sh /.gitignore: -------------------------------------------------------------------------------- 1 | AutoRaise 2 | AutoRaise.out 3 | AutoRaise.app 4 | *~ 5 | -------------------------------------------------------------------------------- /AutoRaise.dmg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sbmpost/AutoRaise/ce3ef0579017ba797207e19f9327ffbf1d12ffef/AutoRaise.dmg -------------------------------------------------------------------------------- /AutoRaise.icns: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sbmpost/AutoRaise/ce3ef0579017ba797207e19f9327ffbf1d12ffef/AutoRaise.icns -------------------------------------------------------------------------------- /AutoRaise.mm: -------------------------------------------------------------------------------- 1 | /* 2 | * AutoRaise - Copyright (C) 2024 sbmpost 3 | * Some pieces of the code are based on 4 | * metamove by jmgao as part of XFree86 5 | * 6 | * This program is free software; you can redistribute it and/or modify 7 | * it under the terms of the GNU General Public License as published by 8 | * the Free Software Foundation; either version 2 of the License, or 9 | * (at your option) any later version. 10 | * 11 | * This program is distributed in the hope that it will be useful, 12 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details. 15 | * 16 | * You should have received a copy of the GNU General Public License along 17 | * with this program; if not, write to the Free Software Foundation, Inc., 18 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 19 | */ 20 | 21 | // g++ -O2 -Wall -fobjc-arc -D"NS_FORMAT_ARGUMENT(A)=" -o AutoRaise AutoRaise.mm \ 22 | // -framework AppKit && ./AutoRaise 23 | 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | 31 | #define AUTORAISE_VERSION "5.3" 32 | #define STACK_THRESHOLD 20 33 | 34 | #ifdef EXPERIMENTAL_FOCUS_FIRST 35 | #if SKYLIGHT_AVAILABLE 36 | // Focus first is an experimental feature that can break easily across different OSX 37 | // versions. It relies on the private Skylight api. As such, there are absolutely no 38 | // guarantees that this feature will keep on working in future versions of AutoRaise. 39 | #define FOCUS_FIRST 40 | #else 41 | #pragma message "Skylight api is unavailable, Focus First is disabled" 42 | #endif 43 | #endif 44 | 45 | // It seems OSX Monterey introduced a transparent 3 pixel border around each window. This 46 | // means that when two windows are visually precisely connected and not overlapping, in 47 | // reality they are. Consequently one has to move the mouse 3 pixels further out of the 48 | // visual area to make the connected window raise. This new OSX 'feature' also introduces 49 | // unwanted raising of windows when visually connected to the top menu bar. To solve this 50 | // we correct the mouse position before determining which window is underneath the mouse. 51 | #define WINDOW_CORRECTION 3 52 | #define MENUBAR_CORRECTION 8 53 | static CGPoint oldCorrectedPoint = {0, 0}; 54 | 55 | // An activate delay of about 10 microseconds is just high enough to ensure we always 56 | // find the latest focused (main)window. This value should be kept as low as possible. 57 | #define ACTIVATE_DELAY_MS 10 58 | 59 | #define SCALE_DELAY_MS 400 // The moment the mouse scaling should start, feel free to modify. 60 | #define SCALE_DURATION_MS (SCALE_DELAY_MS+600) // Mouse scale duration, feel free to modify. 61 | 62 | #ifdef FOCUS_FIRST 63 | #define kCPSUserGenerated 0x200 64 | extern "C" CGError SLPSPostEventRecordTo(ProcessSerialNumber *psn, uint8_t *bytes); 65 | extern "C" CGError _SLPSSetFrontProcessWithOptions( 66 | ProcessSerialNumber *psn, uint32_t wid, uint32_t mode); 67 | 68 | /* -----------Could these be a replacement for GetProcessForPID?----------- 69 | extern "C" int SLSMainConnectionID(void); 70 | extern "C" CGError SLSGetWindowOwner(int cid, uint32_t wid, int *wcid); 71 | extern "C" CGError SLSGetConnectionPSN(int cid, ProcessSerialNumber *psn); 72 | int element_connection; 73 | SLSGetWindowOwner(SLSMainConnectionID(), window_id, &element_connection); 74 | SLSGetConnectionPSN(element_connection, &window_psn); 75 | -------------------------------------------------------------------------*/ 76 | #endif 77 | 78 | typedef int CGSConnectionID; 79 | extern "C" CGSConnectionID CGSMainConnectionID(void); 80 | extern "C" CGError CGSSetCursorScale(CGSConnectionID connectionId, float scale); 81 | extern "C" CGError CGSGetCursorScale(CGSConnectionID connectionId, float *scale); 82 | extern "C" AXError _AXUIElementGetWindow(AXUIElementRef, CGWindowID *out); 83 | // Above methods are undocumented and subjective to incompatible changes 84 | 85 | #ifdef FOCUS_FIRST 86 | static int raiseDelayCount = 0; 87 | static pid_t lastFocusedWindow_pid; 88 | static AXUIElementRef _lastFocusedWindow = NULL; 89 | #endif 90 | 91 | CFMachPortRef eventTap = NULL; 92 | static char pathBuffer[PROC_PIDPATHINFO_MAXSIZE]; 93 | static bool activated_by_task_switcher = false; 94 | static AXUIElementRef _accessibility_object = AXUIElementCreateSystemWide(); 95 | static AXUIElementRef _previousFinderWindow = NULL; 96 | static AXUIElementRef _dock_app = NULL; 97 | static NSArray * ignoreApps = NULL; 98 | static NSArray * ignoreTitles = NULL; 99 | static NSArray * stayFocusedBundleIds = NULL; 100 | static NSArray * const mainWindowAppsWithoutTitle = @[@"Photos", @"Calculator", @"Podcasts", @"Stickies Pro", @"Reeder"]; 101 | static NSString * const DockBundleId = @"com.apple.dock"; 102 | static NSString * const FinderBundleId = @"com.apple.finder"; 103 | static NSString * const LittleSnitchBundleId = @"at.obdev.littlesnitch"; 104 | static NSString * const AssistiveControl = @"AssistiveControl"; 105 | static NSString * const MissionControl = @"Mission Control"; 106 | static NSString * const BartenderBar = @"Bartender Bar"; 107 | static NSString * const AppStoreSearchResults = @"Search results"; 108 | static NSString * const Untitled = @"Untitled"; // OSX Email search 109 | static NSString * const Zim = @"Zim"; 110 | static NSString * const XQuartz = @"XQuartz"; 111 | static NSString * const Finder = @"Finder"; 112 | static NSString * const NoTitle = @""; 113 | static CGPoint desktopOrigin = {0, 0}; 114 | static CGPoint oldPoint = {0, 0}; 115 | static bool propagateMouseMoved = false; 116 | static bool ignoreSpaceChanged = false; 117 | static bool invertIgnoreApps = false; 118 | static bool spaceHasChanged = false; 119 | static bool appWasActivated = false; 120 | static bool altTaskSwitcher = false; 121 | static bool warpMouse = false; 122 | static bool verbose = false; 123 | static float warpX = 0.5; 124 | static float warpY = 0.5; 125 | static float oldScale = 1; 126 | static float cursorScale = 2; 127 | static float mouseDelta = 0; 128 | static int ignoreTimes = 0; 129 | static int raiseTimes = 0; 130 | static int delayTicks = 0; 131 | static int delayCount = 0; 132 | static int pollMillis = 0; 133 | static int disableKey = 0; 134 | 135 | //----------------------------------------yabai focus only methods------------------------------------------ 136 | 137 | #ifdef FOCUS_FIRST 138 | // The two methods below, starting with "window_manager" were copied from 139 | // https://github.com/koekeishiya/yabai and slightly modified. See also: 140 | // https://github.com/Hammerspoon/hammerspoon/issues/370#issuecomment-545545468 141 | void window_manager_make_key_window(ProcessSerialNumber * _window_psn, uint32_t window_id) { 142 | uint8_t * bytes = (uint8_t *) malloc(0xf8); 143 | memset(bytes, 0, 0xf8); 144 | 145 | bytes[0x04] = 0xf8; 146 | bytes[0x3a] = 0x10; 147 | 148 | memcpy(bytes + 0x3c, &window_id, sizeof(uint32_t)); 149 | memset(bytes + 0x20, 0xFF, 0x10); 150 | 151 | bytes[0x08] = 0x01; 152 | SLPSPostEventRecordTo(_window_psn, bytes); 153 | 154 | bytes[0x08] = 0x02; 155 | SLPSPostEventRecordTo(_window_psn, bytes); 156 | free(bytes); 157 | } 158 | 159 | void window_manager_focus_window_without_raise( 160 | ProcessSerialNumber * _window_psn, uint32_t window_id, 161 | ProcessSerialNumber * _focused_window_psn, uint32_t focused_window_id 162 | ) { 163 | if (verbose) { NSLog(@"Focus"); } 164 | if (_focused_window_psn) { 165 | Boolean same_process; 166 | SameProcess(_window_psn, _focused_window_psn, &same_process); 167 | if (same_process) { 168 | if (verbose) { NSLog(@"Same process"); } 169 | uint8_t * bytes = (uint8_t *) malloc(0xf8); 170 | memset(bytes, 0, 0xf8); 171 | 172 | bytes[0x04] = 0xf8; 173 | bytes[0x08] = 0x0d; 174 | memcpy(bytes + 0x3c, &focused_window_id, sizeof(uint32_t)); 175 | memcpy(bytes + 0x3c, &window_id, sizeof(uint32_t)); 176 | 177 | bytes[0x8a] = 0x02; 178 | SLPSPostEventRecordTo(_focused_window_psn, bytes); 179 | 180 | // @hack 181 | // Artificially delay the activation by 1ms. This is necessary 182 | // because some applications appear to be confused if both of 183 | // the events appear instantaneously. 184 | usleep(10000); 185 | 186 | bytes[0x8a] = 0x01; 187 | SLPSPostEventRecordTo(_window_psn, bytes); 188 | free(bytes); 189 | } 190 | } 191 | 192 | _SLPSSetFrontProcessWithOptions(_window_psn, window_id, kCPSUserGenerated); 193 | window_manager_make_key_window(_window_psn, window_id); 194 | } 195 | #endif 196 | 197 | //---------------------------------------------helper methods----------------------------------------------- 198 | 199 | inline void activate(pid_t pid) { 200 | if (verbose) { NSLog(@"Activate"); } 201 | #ifdef OLD_ACTIVATION_METHOD 202 | ProcessSerialNumber process; 203 | OSStatus error = GetProcessForPID(pid, &process); 204 | if (!error) { SetFrontProcessWithOptions(&process, kSetFrontProcessFrontWindowOnly); } 205 | #else 206 | // Note activateWithOptions does not work properly on OSX 11.1 207 | [[NSRunningApplication runningApplicationWithProcessIdentifier: pid] 208 | activateWithOptions: NSApplicationActivateIgnoringOtherApps]; 209 | #endif 210 | } 211 | 212 | inline void raiseAndActivate(AXUIElementRef _window, pid_t window_pid) { 213 | if (verbose) { NSLog(@"Raise"); } 214 | if (AXUIElementPerformAction(_window, kAXRaiseAction) == kAXErrorSuccess) { 215 | activate(window_pid); 216 | } 217 | } 218 | 219 | // TODO: does not take into account different languages 220 | inline bool titleEquals(AXUIElementRef _element, NSArray * _titles, NSArray * _patterns = NULL, bool logTitle = false) { 221 | bool equal = false; 222 | CFStringRef _elementTitle = NULL; 223 | AXUIElementCopyAttributeValue(_element, kAXTitleAttribute, (CFTypeRef *) &_elementTitle); 224 | if (logTitle) { NSLog(@"element title: %@", _elementTitle); } 225 | if (_elementTitle) { 226 | NSString * _title = (__bridge NSString *) _elementTitle; 227 | equal = [_titles containsObject: _title]; 228 | if (!equal && _patterns) { 229 | for (NSString * _pattern in _patterns) { 230 | equal = [_title rangeOfString:_pattern options:NSRegularExpressionSearch].location != NSNotFound; 231 | if (equal) { break; } 232 | } 233 | } 234 | CFRelease(_elementTitle); 235 | } else { equal = [_titles containsObject: NoTitle]; } 236 | return equal; 237 | } 238 | 239 | inline bool dock_active() { 240 | bool active = false; 241 | AXUIElementRef _focusedUIElement = NULL; 242 | AXUIElementCopyAttributeValue(_dock_app, kAXFocusedUIElementAttribute, (CFTypeRef *) &_focusedUIElement); 243 | if (_focusedUIElement) { 244 | active = true; 245 | if (verbose) { NSLog(@"Dock is active"); } 246 | CFRelease(_focusedUIElement); 247 | } 248 | return active; 249 | } 250 | 251 | inline bool mc_active() { 252 | bool active = false; 253 | CFArrayRef _children = NULL; 254 | AXUIElementCopyAttributeValue(_dock_app, kAXChildrenAttribute, (CFTypeRef *) &_children); 255 | if (_children) { 256 | CFIndex count = CFArrayGetCount(_children); 257 | for (CFIndex i=0;!active && i != count;i++) { 258 | CFStringRef _element_role = NULL; 259 | AXUIElementRef _element = (AXUIElementRef) CFArrayGetValueAtIndex(_children, i); 260 | AXUIElementCopyAttributeValue(_element, kAXRoleAttribute, (CFTypeRef *) &_element_role); 261 | if (_element_role) { 262 | active = CFEqual(_element_role, kAXGroupRole) && titleEquals(_element, @[MissionControl]); 263 | CFRelease(_element_role); 264 | } 265 | } 266 | CFRelease(_children); 267 | } 268 | 269 | if (verbose && active) { NSLog(@"Mission Control is active"); } 270 | return active; 271 | } 272 | 273 | NSDictionary * topwindow(CGPoint point) { 274 | NSDictionary * top_window = NULL; 275 | NSArray * window_list = (NSArray *) CFBridgingRelease(CGWindowListCopyWindowInfo( 276 | kCGWindowListOptionOnScreenOnly | kCGWindowListExcludeDesktopElements, 277 | kCGNullWindowID)); 278 | 279 | for (NSDictionary * window in window_list) { 280 | NSDictionary * window_bounds_dict = window[(NSString *) CFBridgingRelease(kCGWindowBounds)]; 281 | 282 | if (![window[(__bridge id) kCGWindowLayer] isEqual: @0]) { continue; } 283 | 284 | NSRect window_bounds = NSMakeRect( 285 | [window_bounds_dict[@"X"] intValue], 286 | [window_bounds_dict[@"Y"] intValue], 287 | [window_bounds_dict[@"Width"] intValue], 288 | [window_bounds_dict[@"Height"] intValue]); 289 | 290 | if (NSPointInRect(NSPointFromCGPoint(point), window_bounds)) { 291 | top_window = window; 292 | break; 293 | } 294 | } 295 | 296 | return top_window; 297 | } 298 | 299 | AXUIElementRef fallback(CGPoint point) { 300 | if (verbose) { NSLog(@"Fallback"); } 301 | AXUIElementRef _window = NULL; 302 | NSDictionary * top_window = topwindow(point); 303 | if (top_window) { 304 | CFTypeRef _windows_cf = NULL; 305 | pid_t pid = [top_window[(__bridge id) kCGWindowOwnerPID] intValue]; 306 | AXUIElementRef _window_owner = AXUIElementCreateApplication(pid); 307 | AXUIElementCopyAttributeValue(_window_owner, kAXWindowsAttribute, &_windows_cf); 308 | CFRelease(_window_owner); 309 | if (_windows_cf) { 310 | NSArray * application_windows = (NSArray *) CFBridgingRelease(_windows_cf); 311 | CGWindowID top_window_id = [top_window[(__bridge id) kCGWindowNumber] intValue]; 312 | if (top_window_id) { 313 | for (id application_window in application_windows) { 314 | CGWindowID application_window_id; 315 | AXUIElementRef application_window_ax = 316 | (__bridge AXUIElementRef) application_window; 317 | if (_AXUIElementGetWindow( 318 | application_window_ax, 319 | &application_window_id) == kAXErrorSuccess) { 320 | if (application_window_id == top_window_id) { 321 | _window = application_window_ax; 322 | CFRetain(_window); 323 | break; 324 | } 325 | } 326 | } 327 | } 328 | } else { 329 | activate(pid); 330 | } 331 | } 332 | 333 | return _window; 334 | } 335 | 336 | AXUIElementRef get_raisable_window(AXUIElementRef _element, CGPoint point, int count) { 337 | AXUIElementRef _window = NULL; 338 | if (_element) { 339 | if (count >= STACK_THRESHOLD) { 340 | if (verbose) { 341 | NSLog(@"Stack threshold reached"); 342 | pid_t application_pid; 343 | if (AXUIElementGetPid(_element, &application_pid) == kAXErrorSuccess) { 344 | proc_pidpath(application_pid, pathBuffer, sizeof(pathBuffer)); 345 | NSLog(@"Application path: %s", pathBuffer); 346 | } 347 | } 348 | CFRelease(_element); 349 | } else { 350 | CFStringRef _element_role = NULL; 351 | AXUIElementCopyAttributeValue(_element, kAXRoleAttribute, (CFTypeRef *) &_element_role); 352 | bool check_attributes = !_element_role; 353 | if (_element_role) { 354 | if (CFEqual(_element_role, kAXDockItemRole) || 355 | CFEqual(_element_role, kAXMenuItemRole) || 356 | CFEqual(_element_role, kAXMenuRole) || 357 | CFEqual(_element_role, kAXMenuBarRole) || 358 | CFEqual(_element_role, kAXMenuBarItemRole)) { 359 | CFRelease(_element_role); 360 | CFRelease(_element); 361 | } else if ( 362 | CFEqual(_element_role, kAXWindowRole) || 363 | CFEqual(_element_role, kAXSheetRole) || 364 | CFEqual(_element_role, kAXDrawerRole)) { 365 | CFRelease(_element_role); 366 | _window = _element; 367 | } else if (CFEqual(_element_role, kAXApplicationRole)) { 368 | CFRelease(_element_role); 369 | if (titleEquals(_element, @[XQuartz])) { 370 | pid_t application_pid; 371 | if (AXUIElementGetPid(_element, &application_pid) == kAXErrorSuccess) { 372 | pid_t frontmost_pid = [[[NSWorkspace sharedWorkspace] 373 | frontmostApplication] processIdentifier]; 374 | if (application_pid != frontmost_pid) { 375 | // Focus and/or raising is the responsibility of XQuartz. 376 | // As such AutoRaise features (delay/warp) do not apply. 377 | activate(application_pid); 378 | } 379 | } 380 | CFRelease(_element); 381 | } else { check_attributes = true; } 382 | } else { 383 | CFRelease(_element_role); 384 | check_attributes = true; 385 | } 386 | } 387 | 388 | if (check_attributes) { 389 | AXUIElementCopyAttributeValue(_element, kAXParentAttribute, (CFTypeRef *) &_window); 390 | bool no_parent = !_window; 391 | _window = get_raisable_window(_window, point, ++count); 392 | if (!_window) { 393 | AXUIElementCopyAttributeValue(_element, kAXWindowAttribute, (CFTypeRef *) &_window); 394 | if (!_window && no_parent) { _window = fallback(point); } 395 | } 396 | CFRelease(_element); 397 | } 398 | } 399 | } 400 | 401 | return _window; 402 | } 403 | 404 | AXUIElementRef get_mousewindow(CGPoint point) { 405 | AXUIElementRef _element = NULL; 406 | AXError error = AXUIElementCopyElementAtPosition(_accessibility_object, point.x, point.y, &_element); 407 | 408 | AXUIElementRef _window = NULL; 409 | if (_element) { 410 | _window = get_raisable_window(_element, point, 0); 411 | } else if (error == kAXErrorCannotComplete || error == kAXErrorNotImplemented) { 412 | // fallback, happens for apps that do not support the Accessibility API 413 | if (verbose) { NSLog(@"Copy element: no accessibility support"); } 414 | _window = fallback(point); 415 | } else if (error == kAXErrorNoValue) { 416 | // fallback, happens sometimes when switching to another app (with cmd-tab) 417 | if (verbose) { NSLog(@"Copy element: no value"); } 418 | _window = fallback(point); 419 | } else if (error == kAXErrorAttributeUnsupported) { 420 | // no fallback, happens when hovering into volume/wifi menubar window 421 | if (verbose) { NSLog(@"Copy element: attribute unsupported"); } 422 | } else if (error == kAXErrorFailure) { 423 | // no fallback, happens when hovering over the menubar itself 424 | if (verbose) { NSLog(@"Copy element: failure"); } 425 | } else if (error == kAXErrorIllegalArgument) { 426 | // no fallback, happens in (Open, Save) dialogs 427 | if (verbose) { NSLog(@"Copy element: illegal argument"); } 428 | } else if (verbose) { 429 | NSLog(@"Copy element: AXError %d", error); 430 | } 431 | 432 | if (verbose) { 433 | if (_window) { 434 | CFStringRef _windowTitle = NULL; 435 | AXUIElementCopyAttributeValue(_window, kAXTitleAttribute, (CFTypeRef *) &_windowTitle); 436 | NSLog(@"Mouse window: %@", _windowTitle); 437 | if (_windowTitle) { CFRelease(_windowTitle); } 438 | } else { NSLog(@"No raisable window"); } 439 | } 440 | 441 | return _window; 442 | } 443 | 444 | CGPoint get_mousepoint(AXUIElementRef _window) { 445 | CGPoint mousepoint = {0, 0}; 446 | AXValueRef _size = NULL; 447 | AXValueRef _pos = NULL; 448 | AXUIElementCopyAttributeValue(_window, kAXSizeAttribute, (CFTypeRef *) &_size); 449 | if (_size) { 450 | AXUIElementCopyAttributeValue(_window, kAXPositionAttribute, (CFTypeRef *) &_pos); 451 | if (_pos) { 452 | CGSize cg_size; 453 | CGPoint cg_pos; 454 | if (AXValueGetValue(_size, kAXValueTypeCGSize, &cg_size) && 455 | AXValueGetValue(_pos, kAXValueTypeCGPoint, &cg_pos)) { 456 | mousepoint.x = cg_pos.x + (cg_size.width * warpX); 457 | mousepoint.y = cg_pos.y + (cg_size.height * warpY); 458 | } 459 | CFRelease(_pos); 460 | } 461 | CFRelease(_size); 462 | } 463 | 464 | return mousepoint; 465 | } 466 | 467 | bool contained_within(AXUIElementRef _window1, AXUIElementRef _window2) { 468 | bool contained = false; 469 | AXValueRef _size1 = NULL; 470 | AXValueRef _size2 = NULL; 471 | AXValueRef _pos1 = NULL; 472 | AXValueRef _pos2 = NULL; 473 | 474 | AXUIElementCopyAttributeValue(_window1, kAXSizeAttribute, (CFTypeRef *) &_size1); 475 | if (_size1) { 476 | AXUIElementCopyAttributeValue(_window1, kAXPositionAttribute, (CFTypeRef *) &_pos1); 477 | if (_pos1) { 478 | AXUIElementCopyAttributeValue(_window2, kAXSizeAttribute, (CFTypeRef *) &_size2); 479 | if (_size2) { 480 | AXUIElementCopyAttributeValue(_window2, kAXPositionAttribute, (CFTypeRef *) &_pos2); 481 | if (_pos2) { 482 | CGSize cg_size1; 483 | CGSize cg_size2; 484 | CGPoint cg_pos1; 485 | CGPoint cg_pos2; 486 | if (AXValueGetValue(_size1, kAXValueTypeCGSize, &cg_size1) && 487 | AXValueGetValue(_pos1, kAXValueTypeCGPoint, &cg_pos1) && 488 | AXValueGetValue(_size2, kAXValueTypeCGSize, &cg_size2) && 489 | AXValueGetValue(_pos2, kAXValueTypeCGPoint, &cg_pos2)) { 490 | contained = cg_pos1.x > cg_pos2.x && cg_pos1.y > cg_pos2.y && 491 | cg_pos1.x + cg_size1.width < cg_pos2.x + cg_size2.width && 492 | cg_pos1.y + cg_size1.height < cg_pos2.y + cg_size2.height; 493 | } 494 | CFRelease(_pos2); 495 | } 496 | CFRelease(_size2); 497 | } 498 | CFRelease(_pos1); 499 | } 500 | CFRelease(_size1); 501 | } 502 | 503 | return contained; 504 | } 505 | 506 | void findDockApplication() { 507 | NSArray * _apps = [[NSWorkspace sharedWorkspace] runningApplications]; 508 | for (NSRunningApplication * app in _apps) { 509 | if ([app.bundleIdentifier isEqual: DockBundleId]) { 510 | _dock_app = AXUIElementCreateApplication(app.processIdentifier); 511 | break; 512 | } 513 | } 514 | 515 | if (verbose && !_dock_app) { NSLog(@"Dock application isn't running"); } 516 | } 517 | 518 | void findDesktopOrigin() { 519 | NSScreen * main_screen = NSScreen.screens[0]; 520 | float mainScreenTop = NSMaxY(main_screen.frame); 521 | for (NSScreen * screen in [NSScreen screens]) { 522 | float screenOriginY = mainScreenTop - NSMaxY(screen.frame); 523 | if (screenOriginY < desktopOrigin.y) { desktopOrigin.y = screenOriginY; } 524 | if (screen.frame.origin.x < desktopOrigin.x) { desktopOrigin.x = screen.frame.origin.x; } 525 | } 526 | 527 | if (verbose) { NSLog(@"Desktop origin (%f, %f)", desktopOrigin.x, desktopOrigin.y); } 528 | } 529 | 530 | inline NSScreen * findScreen(CGPoint point) { 531 | NSScreen * main_screen = NSScreen.screens[0]; 532 | point.y = NSMaxY(main_screen.frame) - point.y; 533 | for (NSScreen * screen in [NSScreen screens]) { 534 | NSRect screen_bounds = NSMakeRect( 535 | screen.frame.origin.x, 536 | screen.frame.origin.y, 537 | NSWidth(screen.frame) + 1, 538 | NSHeight(screen.frame) + 1 539 | ); 540 | if (NSPointInRect(NSPointFromCGPoint(point), screen_bounds)) { 541 | return screen; 542 | } 543 | } 544 | return NULL; 545 | } 546 | 547 | inline bool is_desktop_window(AXUIElementRef _window) { 548 | bool desktop_window = false; 549 | AXValueRef _pos = NULL; 550 | AXUIElementCopyAttributeValue(_window, kAXPositionAttribute, (CFTypeRef *) &_pos); 551 | if (_pos) { 552 | CGPoint cg_pos; 553 | desktop_window = AXValueGetValue(_pos, kAXValueTypeCGPoint, &cg_pos) && 554 | NSEqualPoints(NSPointFromCGPoint(cg_pos), NSPointFromCGPoint(desktopOrigin)); 555 | CFRelease(_pos); 556 | } 557 | 558 | if (verbose && desktop_window) { NSLog(@"Desktop window"); } 559 | return desktop_window; 560 | } 561 | 562 | inline bool is_full_screen(AXUIElementRef _window) { 563 | bool full_screen = false; 564 | AXValueRef _pos = NULL; 565 | AXUIElementCopyAttributeValue(_window, kAXPositionAttribute, (CFTypeRef *) &_pos); 566 | if (_pos) { 567 | CGPoint cg_pos; 568 | if (AXValueGetValue(_pos, kAXValueTypeCGPoint, &cg_pos)) { 569 | NSScreen * screen = findScreen(cg_pos); 570 | if (screen) { 571 | AXValueRef _size = NULL; 572 | AXUIElementCopyAttributeValue(_window, kAXSizeAttribute, (CFTypeRef *) &_size); 573 | if (_size) { 574 | CGSize cg_size; 575 | if (AXValueGetValue(_size, kAXValueTypeCGSize, &cg_size)) { 576 | float menuBarHeight = 577 | fmax(0, NSMaxY(screen.frame) - NSMaxY(screen.visibleFrame) - 1); 578 | NSScreen * main_screen = NSScreen.screens[0]; 579 | float screenOriginY = NSMaxY(main_screen.frame) - NSMaxY(screen.frame); 580 | full_screen = cg_pos.x == NSMinX(screen.frame) && 581 | cg_pos.y == screenOriginY + menuBarHeight && 582 | cg_size.width == NSWidth(screen.frame) && 583 | cg_size.height == NSHeight(screen.frame) - menuBarHeight; 584 | } 585 | CFRelease(_size); 586 | } 587 | } 588 | } 589 | CFRelease(_pos); 590 | } 591 | 592 | if (verbose && full_screen) { NSLog(@"Full screen window"); } 593 | return full_screen; 594 | } 595 | 596 | inline bool is_main_window(AXUIElementRef _app, AXUIElementRef _window, bool chrome_app) { 597 | bool main_window = false; 598 | CFBooleanRef _result = NULL; 599 | AXUIElementCopyAttributeValue(_window, kAXMainAttribute, (CFTypeRef *) &_result); 600 | if (_result) { 601 | main_window = CFEqual(_result, kCFBooleanTrue); 602 | if (main_window) { 603 | CFStringRef _element_sub_role = NULL; 604 | AXUIElementCopyAttributeValue(_window, kAXSubroleAttribute, (CFTypeRef *) &_element_sub_role); 605 | if (_element_sub_role) { 606 | main_window = !CFEqual(_element_sub_role, kAXDialogSubrole); 607 | if (verbose && !main_window) { NSLog(@"Dialog window"); } 608 | CFRelease(_element_sub_role); 609 | } 610 | } 611 | CFRelease(_result); 612 | } 613 | 614 | bool finder_app = titleEquals(_app, @[Finder]); 615 | main_window = main_window && (chrome_app || finder_app || 616 | !titleEquals(_window, @[NoTitle]) || 617 | titleEquals(_app, mainWindowAppsWithoutTitle)); 618 | 619 | main_window = main_window || (!finder_app && is_full_screen(_window)); 620 | 621 | if (verbose && !main_window) { NSLog(@"Not a main window"); } 622 | return main_window; 623 | } 624 | 625 | inline bool is_chrome_app(NSString * bundleIdentifier) { 626 | NSArray * components = [bundleIdentifier componentsSeparatedByString: @"."]; 627 | return components.count > 4 && [components[2] isEqual: @"Chrome"] && [components[3] isEqual: @"app"]; 628 | } 629 | 630 | //-----------------------------------------------notifications---------------------------------------------- 631 | 632 | void spaceChanged(); 633 | bool appActivated(); 634 | void onTick(); 635 | 636 | @interface MDWorkspaceWatcher:NSObject {} 637 | - (id)init; 638 | @end 639 | 640 | static MDWorkspaceWatcher * workspaceWatcher = NULL; 641 | 642 | @implementation MDWorkspaceWatcher 643 | - (id)init { 644 | if ((self = [super init])) { 645 | NSNotificationCenter * center = 646 | [[NSWorkspace sharedWorkspace] notificationCenter]; 647 | [center 648 | addObserver: self 649 | selector: @selector(spaceChanged:) 650 | name: NSWorkspaceActiveSpaceDidChangeNotification 651 | object: nil]; 652 | if (warpMouse) { 653 | [center 654 | addObserver: self 655 | selector: @selector(appActivated:) 656 | name: NSWorkspaceDidActivateApplicationNotification 657 | object: nil]; 658 | if (verbose) { NSLog(@"Registered app activated selector"); } 659 | } 660 | } 661 | return self; 662 | } 663 | 664 | - (void)dealloc { 665 | [[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver: self]; 666 | } 667 | 668 | - (void)spaceChanged:(NSNotification *)notification { 669 | if (verbose) { NSLog(@"Space changed"); } 670 | spaceChanged(); 671 | } 672 | 673 | - (void)appActivated:(NSNotification *)notification { 674 | if (verbose) { NSLog(@"App activated, waiting %0.3fs", ACTIVATE_DELAY_MS/1000.0); } 675 | [self performSelector: @selector(onAppActivated) withObject: nil afterDelay: ACTIVATE_DELAY_MS/1000.0]; 676 | } 677 | 678 | - (void)onAppActivated { 679 | if (appActivated() && cursorScale != oldScale) { 680 | if (verbose) { NSLog(@"Set cursor scale after %0.3fs", SCALE_DELAY_MS/1000.0); } 681 | [self performSelector: @selector(onSetCursorScale:) 682 | withObject: [NSNumber numberWithFloat: cursorScale] 683 | afterDelay: SCALE_DELAY_MS/1000.0]; 684 | 685 | [self performSelector: @selector(onSetCursorScale:) 686 | withObject: [NSNumber numberWithFloat: oldScale] 687 | afterDelay: SCALE_DURATION_MS/1000.0]; 688 | } 689 | } 690 | 691 | - (void)onSetCursorScale:(NSNumber *)scale { 692 | if (verbose) { NSLog(@"Set cursor scale: %@", scale); } 693 | CGSSetCursorScale(CGSMainConnectionID(), scale.floatValue); 694 | } 695 | 696 | - (void)onTick:(NSNumber *)timerInterval { 697 | [self performSelector: @selector(onTick:) 698 | withObject: timerInterval 699 | afterDelay: timerInterval.floatValue]; 700 | onTick(); 701 | } 702 | 703 | #ifdef FOCUS_FIRST 704 | - (void)windowFocused:(AXUIElementRef)_window { 705 | if (verbose) { NSLog(@"Window focused, waiting %0.3fs", raiseDelayCount*pollMillis/1000.0); } 706 | [self performSelector: @selector(onWindowFocused:) 707 | withObject: [NSNumber numberWithUnsignedLong: (uint64_t) _window] 708 | afterDelay: raiseDelayCount*pollMillis/1000.0]; 709 | } 710 | 711 | - (void)onWindowFocused:(NSNumber *)_window { 712 | if (_window.unsignedLongValue == (uint64_t) _lastFocusedWindow) { 713 | raiseAndActivate(_lastFocusedWindow, lastFocusedWindow_pid); 714 | } else if (verbose) { NSLog(@"Ignoring window focused event"); } 715 | } 716 | #endif 717 | @end // MDWorkspaceWatcher 718 | 719 | //----------------------------------------------configuration----------------------------------------------- 720 | 721 | const NSString *kDelay = @"delay"; 722 | const NSString *kWarpX = @"warpX"; 723 | const NSString *kWarpY = @"warpY"; 724 | const NSString *kScale = @"scale"; 725 | const NSString *kVerbose = @"verbose"; 726 | const NSString *kAltTaskSwitcher = @"altTaskSwitcher"; 727 | const NSString *kIgnoreSpaceChanged = @"ignoreSpaceChanged"; 728 | const NSString *kStayFocusedBundleIds = @"stayFocusedBundleIds"; 729 | const NSString *kInvertIgnoreApps = @"invertIgnoreApps"; 730 | const NSString *kIgnoreApps = @"ignoreApps"; 731 | const NSString *kIgnoreTitles = @"ignoreTitles"; 732 | const NSString *kMouseDelta = @"mouseDelta"; 733 | const NSString *kPollMillis = @"pollMillis"; 734 | const NSString *kDisableKey = @"disableKey"; 735 | #ifdef FOCUS_FIRST 736 | const NSString *kFocusDelay = @"focusDelay"; 737 | NSArray *parametersDictionary = @[kDelay, kWarpX, kWarpY, kScale, kVerbose, kAltTaskSwitcher, 738 | kFocusDelay, kIgnoreSpaceChanged, kInvertIgnoreApps, kIgnoreApps, kIgnoreTitles, 739 | kStayFocusedBundleIds, kDisableKey, kMouseDelta, kPollMillis]; 740 | #else 741 | NSArray *parametersDictionary = @[kDelay, kWarpX, kWarpY, kScale, kVerbose, kAltTaskSwitcher, 742 | kIgnoreSpaceChanged, kInvertIgnoreApps, kIgnoreApps, kIgnoreTitles, kStayFocusedBundleIds, 743 | kDisableKey, kMouseDelta, kPollMillis]; 744 | #endif 745 | NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init]; 746 | 747 | @interface ConfigClass:NSObject 748 | - (NSString *) getFilePath:(NSString *) filename; 749 | - (void) readConfig:(int) argc; 750 | - (void) readOriginalConfig; 751 | - (void) readHiddenConfig; 752 | - (void) validateParameters; 753 | @end 754 | 755 | @implementation ConfigClass 756 | - (NSString *) getFilePath:(NSString *) filename { 757 | filename = [NSString stringWithFormat: @"%@/%@", NSHomeDirectory(), filename]; 758 | if (not [[NSFileManager defaultManager] fileExistsAtPath: filename]) { filename = NULL; } 759 | return filename; 760 | } 761 | 762 | - (void) readConfig:(int) argc { 763 | if (argc > 1) { 764 | // read NSArgumentDomain 765 | NSUserDefaults *arguments = [NSUserDefaults standardUserDefaults]; 766 | 767 | for (id key in parametersDictionary) { 768 | id arg = [arguments objectForKey: key]; 769 | if (arg != NULL) { parameters[key] = arg; } 770 | } 771 | } else { 772 | [self readHiddenConfig]; 773 | } 774 | return; 775 | } 776 | 777 | - (void) readOriginalConfig { 778 | // original config files: 779 | NSString *delayFilePath = [self getFilePath: @"AutoRaise.delay"]; 780 | NSString *warpFilePath = [self getFilePath: @"AutoRaise.warp"]; 781 | 782 | if (delayFilePath || warpFilePath) { 783 | NSFileHandle *hDelayFile = [NSFileHandle fileHandleForReadingAtPath: delayFilePath]; 784 | if (hDelayFile) { 785 | parameters[kDelay] = @(abs([[[NSString alloc] 786 | initWithData: [hDelayFile readDataOfLength: 2] 787 | encoding: NSUTF8StringEncoding] intValue])); 788 | [hDelayFile closeFile]; 789 | } 790 | 791 | NSFileHandle *hWarpFile = [NSFileHandle fileHandleForReadingAtPath: warpFilePath]; 792 | if (hWarpFile) { 793 | NSString *line = [[NSString alloc] 794 | initWithData: [hWarpFile readDataOfLength:11] 795 | encoding: NSUTF8StringEncoding]; 796 | NSArray *components = [line componentsSeparatedByString: @" "]; 797 | if (components.count >= 1) { parameters[kWarpX] = @([[components objectAtIndex:0] floatValue]); } 798 | if (components.count >= 2) { parameters[kWarpY] = @([[components objectAtIndex:1] floatValue]); } 799 | if (components.count >= 3) { parameters[kScale] = @([[components objectAtIndex:2] floatValue]); } 800 | [hWarpFile closeFile]; 801 | } 802 | } 803 | return; 804 | } 805 | 806 | - (void) readHiddenConfig { 807 | // search for dotfiles 808 | NSString *hiddenConfigFilePath = [self getFilePath: @".AutoRaise"]; 809 | if (!hiddenConfigFilePath) { hiddenConfigFilePath = [self getFilePath: @".config/AutoRaise/config"]; } 810 | 811 | if (hiddenConfigFilePath) { 812 | NSError *error; 813 | NSString *configContent = [[NSString alloc] 814 | initWithContentsOfFile: hiddenConfigFilePath 815 | encoding: NSUTF8StringEncoding error: &error]; 816 | 817 | NSArray *configLines = [configContent componentsSeparatedByString:@"\n"]; 818 | NSString *trimmedLine, *trimmedKey, *trimmedValue, *noQuotesValue; 819 | NSArray *components; 820 | for (NSString *line in configLines) { 821 | trimmedLine = [line stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]]; 822 | if (not [trimmedLine hasPrefix:@"#"]) { 823 | components = [trimmedLine componentsSeparatedByString:@"="]; 824 | if ([components count] == 2) { 825 | for (id key in parametersDictionary) { 826 | trimmedKey = [components[0] stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]]; 827 | trimmedValue = [components[1] stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]]; 828 | noQuotesValue = [trimmedValue stringByReplacingOccurrencesOfString:@"\"" withString:@""]; 829 | if ([trimmedKey isEqual: key]) { parameters[key] = noQuotesValue; } 830 | } 831 | } 832 | } 833 | } 834 | } else { 835 | [self readOriginalConfig]; 836 | } 837 | return; 838 | } 839 | 840 | - (void) validateParameters { 841 | // validate and fix wrong/absent parameters 842 | #ifdef FOCUS_FIRST 843 | if (!parameters[kFocusDelay] && !parameters[kDelay]) { 844 | #else 845 | if (!parameters[kDelay]) { 846 | #endif 847 | parameters[kDelay] = @"1"; 848 | } 849 | if ([parameters[kPollMillis] intValue] < 20) { parameters[kPollMillis] = @"50"; } 850 | if ([parameters[kMouseDelta] floatValue] < 0) { parameters[kMouseDelta] = @"0"; } 851 | if ([parameters[kScale] floatValue] < 1) { parameters[kScale] = @"2.0"; } 852 | if (!parameters[kDisableKey]) { parameters[kDisableKey] = @"control"; } 853 | warpMouse = 854 | parameters[kWarpX] && [parameters[kWarpX] floatValue] >= 0 && [parameters[kWarpX] floatValue] <= 1 && 855 | parameters[kWarpY] && [parameters[kWarpY] floatValue] >= 0 && [parameters[kWarpY] floatValue] <= 1; 856 | #ifdef ALTERNATIVE_TASK_SWITCHER 857 | if (!parameters[kAltTaskSwitcher]) { parameters[kAltTaskSwitcher] = @"true"; } 858 | #endif 859 | #ifdef FOCUS_FIRST 860 | if (![parameters[kDelay] intValue] && !parameters[kFocusDelay]) { parameters[kFocusDelay] = @"1"; } 861 | if (!parameters[kDelay] && ![parameters[kFocusDelay] intValue]) { parameters[kDelay] = @"1"; } 862 | #endif 863 | return; 864 | } 865 | @end // ConfigClass 866 | 867 | //------------------------------------------where it all happens-------------------------------------------- 868 | 869 | void spaceChanged() { 870 | spaceHasChanged = true; 871 | oldPoint.x = oldPoint.y = 0; 872 | } 873 | 874 | bool appActivated() { 875 | if (verbose) { NSLog(@"App activated"); } 876 | if (!altTaskSwitcher) { 877 | if (!activated_by_task_switcher) { return false; } 878 | activated_by_task_switcher = false; 879 | } 880 | appWasActivated = true; 881 | 882 | NSRunningApplication *frontmostApp = [[NSWorkspace sharedWorkspace] frontmostApplication]; 883 | pid_t frontmost_pid = frontmostApp.processIdentifier; 884 | 885 | AXUIElementRef _activatedWindow = NULL; 886 | AXUIElementRef _frontmostApp = AXUIElementCreateApplication(frontmost_pid); 887 | AXUIElementCopyAttributeValue(_frontmostApp, 888 | kAXMainWindowAttribute, (CFTypeRef *) &_activatedWindow); 889 | if (!_activatedWindow) { 890 | if (verbose) { NSLog(@"No main window, trying focused window"); } 891 | AXUIElementCopyAttributeValue(_frontmostApp, 892 | kAXFocusedWindowAttribute, (CFTypeRef *) &_activatedWindow); 893 | } 894 | CFRelease(_frontmostApp); 895 | 896 | if (verbose) { NSLog(@"BundleIdentifier: %@", frontmostApp.bundleIdentifier); } 897 | bool finder_app = [frontmostApp.bundleIdentifier isEqual: FinderBundleId]; 898 | if (finder_app) { 899 | if (_activatedWindow) { 900 | if (is_desktop_window(_activatedWindow)) { 901 | CFRelease(_activatedWindow); 902 | _activatedWindow = _previousFinderWindow; 903 | } else { 904 | if (_previousFinderWindow) { CFRelease(_previousFinderWindow); } 905 | _previousFinderWindow = _activatedWindow; 906 | } 907 | } else { _activatedWindow = _previousFinderWindow; } 908 | } 909 | 910 | if (altTaskSwitcher) { 911 | CGEventRef _event = CGEventCreate(NULL); 912 | CGPoint mousePoint = CGEventGetLocation(_event); 913 | if (_event) { CFRelease(_event); } 914 | 915 | bool ignoreActivated = false; 916 | // TODO: is the uncorrected mousePoint good enough? 917 | AXUIElementRef _mouseWindow = get_mousewindow(mousePoint); 918 | if (_mouseWindow) { 919 | if (!activated_by_task_switcher) { 920 | pid_t mouseWindow_pid; 921 | // Checking for mouse movement reduces the problem of the mouse being warped 922 | // when changing spaces and simultaneously moving the mouse to another screen 923 | ignoreActivated = fabs(mousePoint.x-oldPoint.x) > 0; 924 | ignoreActivated = ignoreActivated || fabs(mousePoint.y-oldPoint.y) > 0; 925 | // Check if the mouse is already hovering above the frontmost app. If 926 | // for example we only change spaces, we don't want the mouse to warp 927 | ignoreActivated = ignoreActivated || (AXUIElementGetPid(_mouseWindow, 928 | &mouseWindow_pid) == kAXErrorSuccess && mouseWindow_pid == frontmost_pid); 929 | } 930 | CFRelease(_mouseWindow); 931 | } else { // dock or top menu 932 | // Comment the line below if clicking the dock icons should also 933 | // warp the mouse. Note this may introduce some unexpected warps 934 | ignoreActivated = true; 935 | } 936 | 937 | activated_by_task_switcher = false; // used in the previous code block 938 | 939 | if (ignoreActivated) { 940 | if (verbose) { NSLog(@"Ignoring app activated"); } 941 | if (!finder_app && _activatedWindow) { CFRelease(_activatedWindow); } 942 | return false; 943 | } 944 | } 945 | 946 | if (_activatedWindow) { 947 | if (verbose) { NSLog(@"Warp mouse"); } 948 | CGWarpMouseCursorPosition(get_mousepoint(_activatedWindow)); 949 | if (!finder_app) { CFRelease(_activatedWindow); } 950 | } 951 | 952 | return true; 953 | } 954 | 955 | void onTick() { 956 | // determine if mouseMoved 957 | CGEventRef _event = CGEventCreate(NULL); 958 | CGPoint mousePoint = CGEventGetLocation(_event); 959 | if (_event) { CFRelease(_event); } 960 | 961 | float mouse_x_diff = mousePoint.x-oldPoint.x; 962 | float mouse_y_diff = mousePoint.y-oldPoint.y; 963 | oldPoint = mousePoint; 964 | 965 | bool mouseMoved = fabs(mouse_x_diff) > mouseDelta; 966 | mouseMoved = mouseMoved || fabs(mouse_y_diff) > mouseDelta; 967 | mouseMoved = mouseMoved || propagateMouseMoved; 968 | propagateMouseMoved = false; 969 | 970 | // delayCount = 0 -> warp only 971 | #ifdef FOCUS_FIRST 972 | if (altTaskSwitcher && !delayCount && !raiseDelayCount) { return; } 973 | #else 974 | if (altTaskSwitcher && !delayCount) { return; } 975 | #endif 976 | 977 | // delayTicks = 0 -> delay disabled 978 | // delayTicks = 1 -> delay finished 979 | // delayTicks = n -> delay started 980 | if (delayTicks > 1) { delayTicks--; } 981 | 982 | #ifdef FOCUS_FIRST 983 | if (!delayCount || raiseDelayCount == 1) { 984 | #endif 985 | if (@available(macOS 12.00, *)) { 986 | // the correction should be applied before we return 987 | // under certain conditions in the code after it. This 988 | // ensures oldCorrectedPoint always has a recent value. 989 | if (mouseMoved) { 990 | NSScreen * screen = findScreen(mousePoint); 991 | mousePoint.x += mouse_x_diff > 0 ? WINDOW_CORRECTION : -WINDOW_CORRECTION; 992 | mousePoint.y += mouse_y_diff > 0 ? WINDOW_CORRECTION : -WINDOW_CORRECTION; 993 | if (screen) { 994 | NSScreen * main_screen = NSScreen.screens[0]; 995 | float screenOriginX = NSMinX(screen.frame) - NSMinX(main_screen.frame); 996 | float screenOriginY = NSMaxY(main_screen.frame) - NSMaxY(screen.frame); 997 | 998 | if (oldPoint.x > screenOriginX + NSWidth(screen.frame) - WINDOW_CORRECTION) { 999 | if (verbose) { NSLog(@"Screen edge correction"); } 1000 | mousePoint.x = screenOriginX + NSWidth(screen.frame) - 1; 1001 | } else if (oldPoint.x < screenOriginX + WINDOW_CORRECTION - 1) { 1002 | if (verbose) { NSLog(@"Screen edge correction"); } 1003 | mousePoint.x = screenOriginX + 1; 1004 | } 1005 | 1006 | if (oldPoint.y > screenOriginY + NSHeight(screen.frame) - WINDOW_CORRECTION) { 1007 | if (verbose) { NSLog(@"Screen edge correction"); } 1008 | mousePoint.y = screenOriginY + NSHeight(screen.frame) - 1; 1009 | } else { 1010 | float menuBarHeight = 1011 | fmax(0, NSMaxY(screen.frame) - NSMaxY(screen.visibleFrame) - 1); 1012 | if (mousePoint.y < screenOriginY + menuBarHeight + MENUBAR_CORRECTION) { 1013 | if (verbose) { NSLog(@"Menu bar correction"); } 1014 | mousePoint.y = screenOriginY; 1015 | } 1016 | } 1017 | } 1018 | oldCorrectedPoint = mousePoint; 1019 | } else { 1020 | mousePoint = oldCorrectedPoint; 1021 | } 1022 | } 1023 | #ifdef FOCUS_FIRST 1024 | } 1025 | #endif 1026 | 1027 | if (ignoreTimes) { 1028 | ignoreTimes--; 1029 | return; 1030 | } else if (appWasActivated) { 1031 | appWasActivated = false; 1032 | return; 1033 | } else if (spaceHasChanged) { 1034 | // spaceHasChanged has priority 1035 | // over waiting for the delay 1036 | if (mouseMoved) { return; } 1037 | else if (!ignoreSpaceChanged) { 1038 | raiseTimes = 3; 1039 | delayTicks = 0; 1040 | } 1041 | spaceHasChanged = false; 1042 | } else if (delayTicks && mouseMoved) { 1043 | delayTicks = 0; 1044 | // propagate the mouseMoved event 1045 | // to restart the delay if needed 1046 | propagateMouseMoved = true; 1047 | return; 1048 | } 1049 | 1050 | // mouseMoved: we have to decide if the window needs raising 1051 | // delayTicks: count down as long as the mouse doesn't move 1052 | // raiseTimes: the window needs raising a couple of times. 1053 | if (mouseMoved || delayTicks || raiseTimes) { 1054 | // don't raise for as long as something is being dragged (resizing a window for instance) 1055 | bool abort = CGEventSourceButtonState(kCGEventSourceStateCombinedSessionState, kCGMouseButtonLeft) || 1056 | CGEventSourceButtonState(kCGEventSourceStateCombinedSessionState, kCGMouseButtonRight) || 1057 | dock_active() || 1058 | mc_active(); 1059 | 1060 | if (!abort && disableKey) { 1061 | CGEventRef _keyDownEvent = CGEventCreateKeyboardEvent(NULL, 0, true); 1062 | CGEventFlags flags = CGEventGetFlags(_keyDownEvent); 1063 | if (_keyDownEvent) { CFRelease(_keyDownEvent); } 1064 | abort = (flags & disableKey) == disableKey; 1065 | } 1066 | 1067 | NSRunningApplication *frontmostApp = [[NSWorkspace sharedWorkspace] frontmostApplication]; 1068 | abort = abort || [stayFocusedBundleIds containsObject: frontmostApp.bundleIdentifier]; 1069 | 1070 | if (abort) { 1071 | if (verbose) { NSLog(@"Abort focus/raise"); } 1072 | raiseTimes = 0; 1073 | delayTicks = 0; 1074 | return; 1075 | } 1076 | 1077 | AXUIElementRef _mouseWindow = get_mousewindow(mousePoint); 1078 | if (_mouseWindow) { 1079 | pid_t mouseWindow_pid; 1080 | if (AXUIElementGetPid(_mouseWindow, &mouseWindow_pid) == kAXErrorSuccess) { 1081 | bool needs_raise = !invertIgnoreApps; 1082 | AXUIElementRef _mouseWindowApp = AXUIElementCreateApplication(mouseWindow_pid); 1083 | if (needs_raise && titleEquals(_mouseWindow, @[NoTitle, Untitled])) { 1084 | needs_raise = is_main_window(_mouseWindowApp, _mouseWindow, is_chrome_app( 1085 | [NSRunningApplication runningApplicationWithProcessIdentifier: 1086 | mouseWindow_pid].bundleIdentifier)); 1087 | if (verbose && !needs_raise) { NSLog(@"Excluding window"); } 1088 | } else if (needs_raise && 1089 | titleEquals(_mouseWindow, @[BartenderBar, Zim, AppStoreSearchResults], ignoreTitles)) { 1090 | // TODO: make these window title exceptions an ignoreWindowTitles setting. 1091 | needs_raise = false; 1092 | if (verbose) { NSLog(@"Excluding window"); } 1093 | } else { 1094 | if (titleEquals(_mouseWindowApp, ignoreApps)) { 1095 | needs_raise = invertIgnoreApps; 1096 | if (verbose) { 1097 | if (invertIgnoreApps) { 1098 | NSLog(@"Including app"); 1099 | } else { 1100 | NSLog(@"Excluding app"); 1101 | } 1102 | } 1103 | } 1104 | } 1105 | CFRelease(_mouseWindowApp); 1106 | CGWindowID mouseWindow_id; 1107 | CGWindowID focusedWindow_id; 1108 | #ifdef FOCUS_FIRST 1109 | ProcessSerialNumber mouseWindow_psn; 1110 | ProcessSerialNumber focusedWindow_psn; 1111 | ProcessSerialNumber * _focusedWindow_psn = NULL; 1112 | #endif 1113 | if (needs_raise) { 1114 | _AXUIElementGetWindow(_mouseWindow, &mouseWindow_id); 1115 | pid_t frontmost_pid = frontmostApp.processIdentifier; 1116 | AXUIElementRef _frontmostApp = AXUIElementCreateApplication(frontmost_pid); 1117 | AXUIElementRef _focusedWindow = NULL; 1118 | AXUIElementCopyAttributeValue( 1119 | _frontmostApp, 1120 | kAXFocusedWindowAttribute, 1121 | (CFTypeRef *) &_focusedWindow); 1122 | if (_focusedWindow) { 1123 | if (verbose) { 1124 | CFStringRef _windowTitle = NULL; 1125 | AXUIElementCopyAttributeValue(_focusedWindow, 1126 | kAXTitleAttribute, (CFTypeRef *) &_windowTitle); 1127 | NSLog(@"Focused window: %@", _windowTitle); 1128 | if (_windowTitle) { CFRelease(_windowTitle); } 1129 | } 1130 | _AXUIElementGetWindow(_focusedWindow, &focusedWindow_id); 1131 | needs_raise = mouseWindow_id != focusedWindow_id; 1132 | #ifdef FOCUS_FIRST 1133 | if (raiseDelayCount) { 1134 | #endif 1135 | needs_raise = needs_raise && !contained_within(_focusedWindow, _mouseWindow); 1136 | #ifdef FOCUS_FIRST 1137 | } else { 1138 | needs_raise = needs_raise && is_main_window(_frontmostApp, _focusedWindow, 1139 | is_chrome_app(frontmostApp.bundleIdentifier)) && ( 1140 | mouseWindow_pid != frontmost_pid || 1141 | !contained_within(_focusedWindow, _mouseWindow)); 1142 | } 1143 | if (needs_raise && delayCount && raiseDelayCount != 1) { 1144 | OSStatus error = GetProcessForPID(frontmost_pid, &focusedWindow_psn); 1145 | if (!error) { _focusedWindow_psn = &focusedWindow_psn; } 1146 | } 1147 | #endif 1148 | CFRelease(_focusedWindow); 1149 | } else { 1150 | if (verbose) { NSLog(@"No focused window"); } 1151 | AXUIElementRef _activatedWindow = NULL; 1152 | AXUIElementCopyAttributeValue(_frontmostApp, 1153 | kAXMainWindowAttribute, (CFTypeRef *) &_activatedWindow); 1154 | if (_activatedWindow) { 1155 | needs_raise = false; 1156 | CFRelease(_activatedWindow); 1157 | } 1158 | } 1159 | CFRelease(_frontmostApp); 1160 | } 1161 | 1162 | if (needs_raise) { 1163 | if (!delayTicks) { 1164 | // start the delay 1165 | delayTicks = delayCount; 1166 | } 1167 | if (raiseTimes || delayTicks == 1) { 1168 | delayTicks = 0; // disable delay 1169 | 1170 | if (raiseTimes) { raiseTimes--; } 1171 | else { raiseTimes = 3; } 1172 | #ifdef FOCUS_FIRST 1173 | if (delayCount && raiseDelayCount != 1) { 1174 | OSStatus error = GetProcessForPID(mouseWindow_pid, &mouseWindow_psn); 1175 | if (!error) { 1176 | bool floating_window = false; 1177 | CFStringRef _element_sub_role = NULL; 1178 | AXUIElementCopyAttributeValue( 1179 | _mouseWindow, 1180 | kAXSubroleAttribute, 1181 | (CFTypeRef *) &_element_sub_role); 1182 | if (_element_sub_role) { 1183 | floating_window = 1184 | CFEqual(_element_sub_role, kAXFloatingWindowSubrole) || 1185 | CFEqual(_element_sub_role, kAXSystemFloatingWindowSubrole) || 1186 | CFEqual(_element_sub_role, kAXUnknownSubrole); 1187 | CFRelease(_element_sub_role); 1188 | } 1189 | if (!floating_window) { 1190 | // TODO: method below seems unable to focus floating windows 1191 | window_manager_focus_window_without_raise(&mouseWindow_psn, 1192 | mouseWindow_id, _focusedWindow_psn, focusedWindow_id); 1193 | } else if (verbose) { NSLog(@"Unable to focus floating window"); } 1194 | if (_lastFocusedWindow) { CFRelease(_lastFocusedWindow); } 1195 | _lastFocusedWindow = _mouseWindow; 1196 | lastFocusedWindow_pid = mouseWindow_pid; 1197 | if (raiseDelayCount) { [workspaceWatcher windowFocused: _lastFocusedWindow]; } 1198 | } 1199 | } else { 1200 | #endif 1201 | raiseAndActivate(_mouseWindow, mouseWindow_pid); 1202 | #ifdef FOCUS_FIRST 1203 | } 1204 | #endif 1205 | } 1206 | } else { 1207 | raiseTimes = 0; 1208 | delayTicks = 0; 1209 | } 1210 | } 1211 | #ifdef FOCUS_FIRST 1212 | if (_mouseWindow != _lastFocusedWindow) { 1213 | #endif 1214 | CFRelease(_mouseWindow); 1215 | #ifdef FOCUS_FIRST 1216 | } 1217 | #endif 1218 | } else { 1219 | raiseTimes = 0; 1220 | delayTicks = 0; 1221 | } 1222 | } 1223 | } 1224 | 1225 | CGEventRef eventTapHandler(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *userInfo) { 1226 | static bool commandTabPressed = false; 1227 | if (type == kCGEventFlagsChanged && commandTabPressed) { 1228 | if (!activated_by_task_switcher) { 1229 | activated_by_task_switcher = true; 1230 | ignoreTimes = 3; 1231 | } 1232 | } 1233 | 1234 | static bool commandGravePressed = false; 1235 | if (type == kCGEventFlagsChanged && commandGravePressed) { 1236 | if (!activated_by_task_switcher) { 1237 | activated_by_task_switcher = true; 1238 | ignoreTimes = 3; 1239 | [workspaceWatcher onAppActivated]; 1240 | } 1241 | } 1242 | 1243 | commandTabPressed = false; 1244 | commandGravePressed = false; 1245 | if (type == kCGEventKeyDown) { 1246 | CGKeyCode keycode = (CGKeyCode) CGEventGetIntegerValueField(event, kCGKeyboardEventKeycode); 1247 | if (keycode == kVK_Tab) { 1248 | CGEventFlags flags = CGEventGetFlags(event); 1249 | commandTabPressed = (flags & kCGEventFlagMaskCommand) == kCGEventFlagMaskCommand; 1250 | } else if (warpMouse && keycode == kVK_ANSI_Grave) { 1251 | CGEventFlags flags = CGEventGetFlags(event); 1252 | commandGravePressed = (flags & kCGEventFlagMaskCommand) == kCGEventFlagMaskCommand; 1253 | } 1254 | } else if (type == kCGEventTapDisabledByTimeout || type == kCGEventTapDisabledByUserInput) { 1255 | if (verbose) { NSLog(@"Got event tap disabled event, re-enabling..."); } 1256 | CGEventTapEnable(eventTap, true); 1257 | } 1258 | 1259 | return event; 1260 | } 1261 | 1262 | int main(int argc, const char * argv[]) { 1263 | @autoreleasepool { 1264 | ConfigClass * config = [[ConfigClass alloc] init]; 1265 | [config readConfig: argc]; 1266 | [config validateParameters]; 1267 | 1268 | delayCount = [parameters[kDelay] intValue]; 1269 | warpX = [parameters[kWarpX] floatValue]; 1270 | warpY = [parameters[kWarpY] floatValue]; 1271 | cursorScale = [parameters[kScale] floatValue]; 1272 | verbose = [parameters[kVerbose] boolValue]; 1273 | altTaskSwitcher = [parameters[kAltTaskSwitcher] boolValue]; 1274 | mouseDelta = [parameters[kMouseDelta] floatValue]; 1275 | pollMillis = [parameters[kPollMillis] intValue]; 1276 | ignoreSpaceChanged = [parameters[kIgnoreSpaceChanged] boolValue]; 1277 | invertIgnoreApps = [parameters[kInvertIgnoreApps] boolValue]; 1278 | 1279 | printf("\nv%s by sbmpost(c) 2024, usage:\n\nAutoRaise\n", AUTORAISE_VERSION); 1280 | printf(" -pollMillis <20, 30, 40, 50, ...>\n"); 1281 | printf(" -delay <0=no-raise, 1=no-delay, 2=%dms, 3=%dms, ...>\n", pollMillis, pollMillis*2); 1282 | #ifdef FOCUS_FIRST 1283 | printf(" -focusDelay <0=no-focus, 1=no-delay, 2=%dms, 3=%dms, ...>\n", pollMillis, pollMillis*2); 1284 | #endif 1285 | printf(" -warpX <0.5> -warpY <0.5> -scale <2.0>\n"); 1286 | printf(" -altTaskSwitcher \n"); 1287 | printf(" -ignoreSpaceChanged \n"); 1288 | printf(" -invertIgnoreApps \n"); 1289 | printf(" -ignoreApps \"\"\n"); 1290 | printf(" -ignoreTitles \"\"\n"); 1291 | printf(" -stayFocusedBundleIds \"\"\n"); 1292 | printf(" -disableKey \n"); 1293 | printf(" -mouseDelta <0.1>\n"); 1294 | printf(" -verbose \n\n"); 1295 | 1296 | printf("Started with:\n"); 1297 | printf(" * pollMillis: %dms\n", pollMillis); 1298 | if (delayCount) { 1299 | printf(" * delay: %dms\n", (delayCount-1)*pollMillis); 1300 | } else { 1301 | printf(" * delay: disabled\n"); 1302 | } 1303 | #ifdef FOCUS_FIRST 1304 | if ([parameters[kFocusDelay] intValue]) { 1305 | raiseDelayCount = delayCount; 1306 | delayCount = [parameters[kFocusDelay] intValue]; 1307 | printf(" * focusDelay: %dms\n", (delayCount-1)*pollMillis); 1308 | } else { 1309 | raiseDelayCount = 1; 1310 | printf(" * focusDelay: disabled\n"); 1311 | } 1312 | #endif 1313 | 1314 | if (warpMouse) { 1315 | printf(" * warpX: %.1f, warpY: %.1f, scale: %.1f\n", warpX, warpY, cursorScale); 1316 | printf(" * altTaskSwitcher: %s\n", altTaskSwitcher ? "true" : "false"); 1317 | } 1318 | 1319 | printf(" * ignoreSpaceChanged: %s\n", ignoreSpaceChanged ? "true" : "false"); 1320 | printf(" * invertIgnoreApps: %s\n", invertIgnoreApps ? "true" : "false"); 1321 | 1322 | NSMutableArray * ignoreA; 1323 | if (parameters[kIgnoreApps]) { 1324 | ignoreA = [[NSMutableArray alloc] initWithArray: 1325 | [parameters[kIgnoreApps] componentsSeparatedByString:@","]]; 1326 | } else { ignoreA = [[NSMutableArray alloc] init]; } 1327 | 1328 | for (id ignoreApp in ignoreA) { 1329 | printf(" * ignoreApp: %s\n", [ignoreApp UTF8String]); 1330 | } 1331 | [ignoreA addObject: AssistiveControl]; 1332 | ignoreApps = [ignoreA copy]; 1333 | 1334 | NSMutableArray * ignoreT; 1335 | if (parameters[kIgnoreTitles]) { 1336 | ignoreT = [[NSMutableArray alloc] initWithArray: 1337 | [parameters[kIgnoreTitles] componentsSeparatedByString:@","]]; 1338 | } else { ignoreT = [[NSMutableArray alloc] init]; } 1339 | 1340 | for (id ignoreTitle in ignoreT) { 1341 | printf(" * ignoreTitle: %s\n", [ignoreTitle UTF8String]); 1342 | } 1343 | ignoreTitles = [ignoreT copy]; 1344 | 1345 | NSMutableArray * stayFocused; 1346 | if (parameters[kStayFocusedBundleIds]) { 1347 | stayFocused = [[NSMutableArray alloc] initWithArray: 1348 | [parameters[kStayFocusedBundleIds] componentsSeparatedByString:@","]]; 1349 | } else { stayFocused = [[NSMutableArray alloc] init]; } 1350 | 1351 | for (id stayFocusedBundleId in stayFocused) { 1352 | printf(" * stayFocusedBundleId: %s\n", [stayFocusedBundleId UTF8String]); 1353 | } 1354 | stayFocusedBundleIds = [stayFocused copy]; 1355 | 1356 | if ([parameters[kDisableKey] isEqualToString: @"control"]) { 1357 | printf(" * disableKey: control\n"); 1358 | disableKey = kCGEventFlagMaskControl; 1359 | } else if ([parameters[kDisableKey] isEqualToString: @"option"]) { 1360 | printf(" * disableKey: option\n"); 1361 | disableKey = kCGEventFlagMaskAlternate; 1362 | } else { printf(" * disableKey: disabled\n"); } 1363 | 1364 | if (mouseDelta) { printf(" * mouseDelta: %.1f\n", mouseDelta); } 1365 | 1366 | printf(" * verbose: %s\n", verbose ? "true" : "false"); 1367 | #if defined OLD_ACTIVATION_METHOD or defined FOCUS_FIRST or defined ALTERNATIVE_TASK_SWITCHER 1368 | printf("\nCompiled with:\n"); 1369 | #ifdef OLD_ACTIVATION_METHOD 1370 | printf(" * OLD_ACTIVATION_METHOD\n"); 1371 | #endif 1372 | #ifdef FOCUS_FIRST 1373 | printf(" * EXPERIMENTAL_FOCUS_FIRST\n"); 1374 | #endif 1375 | #ifdef ALTERNATIVE_TASK_SWITCHER 1376 | printf(" * ALTERNATIVE_TASK_SWITCHER\n"); 1377 | #endif 1378 | #endif 1379 | printf("\n"); 1380 | 1381 | NSDictionary * options = @{(id) CFBridgingRelease(kAXTrustedCheckOptionPrompt): @YES}; 1382 | bool trusted = AXIsProcessTrustedWithOptions((__bridge CFDictionaryRef) options); 1383 | if (verbose) { NSLog(@"AXIsProcessTrusted: %s", trusted ? "YES" : "NO"); } 1384 | 1385 | CGSGetCursorScale(CGSMainConnectionID(), &oldScale); 1386 | if (verbose) { NSLog(@"System cursor scale: %f", oldScale); } 1387 | 1388 | CFRunLoopSourceRef runLoopSource = NULL; 1389 | eventTap = CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap, kCGEventTapOptionDefault, 1390 | CGEventMaskBit(kCGEventKeyDown) | CGEventMaskBit(kCGEventFlagsChanged), 1391 | eventTapHandler, NULL); 1392 | if (eventTap) { 1393 | runLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventTap, 0); 1394 | if (runLoopSource) { 1395 | CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopCommonModes); 1396 | CGEventTapEnable(eventTap, true); 1397 | } 1398 | } 1399 | if (verbose) { NSLog(@"Got run loop source: %s", runLoopSource ? "YES" : "NO"); } 1400 | 1401 | workspaceWatcher = [[MDWorkspaceWatcher alloc] init]; 1402 | #ifdef FOCUS_FIRST 1403 | if (altTaskSwitcher || raiseDelayCount || delayCount) { 1404 | #else 1405 | if (altTaskSwitcher || delayCount) { 1406 | #endif 1407 | [workspaceWatcher onTick: [NSNumber numberWithFloat: pollMillis/1000.0]]; 1408 | } 1409 | 1410 | findDockApplication(); 1411 | findDesktopOrigin(); 1412 | [[NSApplication sharedApplication] run]; 1413 | } 1414 | return 0; 1415 | } 1416 | -------------------------------------------------------------------------------- /Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleExecutable 6 | AutoRaise 7 | CFBundleIdentifier 8 | nl.postware.autoraise 9 | CFBundleGetInfoString 10 | Copyright © 2024 sbmpost 11 | CFBundleShortVersionString 12 | 5.3 13 | CFBundleIconFile 14 | AutoRaise 15 | CFBundleName 16 | AutoRaise 17 | CFBundlePackageType 18 | APPL 19 | CFBundleSupportedPlatforms 20 | 21 | MacOSX 22 | 23 | LSUIElement 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | ### GNU GENERAL PUBLIC LICENSE 2 | 3 | Version 3, 29 June 2007 4 | 5 | Copyright (C) 2007 Free Software Foundation, Inc. 6 | 7 | 8 | Everyone is permitted to copy and distribute verbatim copies of this 9 | license document, but changing it is not allowed. 10 | 11 | ### Preamble 12 | 13 | The GNU General Public License is a free, copyleft license for 14 | software and other kinds of works. 15 | 16 | The licenses for most software and other practical works are designed 17 | to take away your freedom to share and change the works. By contrast, 18 | the GNU General Public License is intended to guarantee your freedom 19 | to share and change all versions of a program--to make sure it remains 20 | free software for all its users. We, the Free Software Foundation, use 21 | the GNU General Public License for most of our software; it applies 22 | also to any other work released this way by its authors. You can apply 23 | it to your programs, too. 24 | 25 | When we speak of free software, we are referring to freedom, not 26 | price. Our General Public Licenses are designed to make sure that you 27 | have the freedom to distribute copies of free software (and charge for 28 | them if you wish), that you receive source code or can get it if you 29 | want it, that you can change the software or use pieces of it in new 30 | free programs, and that you know you can do these things. 31 | 32 | To protect your rights, we need to prevent others from denying you 33 | these rights or asking you to surrender the rights. Therefore, you 34 | have certain responsibilities if you distribute copies of the 35 | software, or if you modify it: responsibilities to respect the freedom 36 | of others. 37 | 38 | For example, if you distribute copies of such a program, whether 39 | gratis or for a fee, you must pass on to the recipients the same 40 | freedoms that you received. You must make sure that they, too, receive 41 | or can get the source code. And you must show them these terms so they 42 | know their rights. 43 | 44 | Developers that use the GNU GPL protect your rights with two steps: 45 | (1) assert copyright on the software, and (2) offer you this License 46 | giving you legal permission to copy, distribute and/or modify it. 47 | 48 | For the developers' and authors' protection, the GPL clearly explains 49 | that there is no warranty for this free software. For both users' and 50 | authors' sake, the GPL requires that modified versions be marked as 51 | changed, so that their problems will not be attributed erroneously to 52 | authors of previous versions. 53 | 54 | Some devices are designed to deny users access to install or run 55 | modified versions of the software inside them, although the 56 | manufacturer can do so. This is fundamentally incompatible with the 57 | aim of protecting users' freedom to change the software. The 58 | systematic pattern of such abuse occurs in the area of products for 59 | individuals to use, which is precisely where it is most unacceptable. 60 | Therefore, we have designed this version of the GPL to prohibit the 61 | practice for those products. If such problems arise substantially in 62 | other domains, we stand ready to extend this provision to those 63 | domains in future versions of the GPL, as needed to protect the 64 | freedom of users. 65 | 66 | Finally, every program is threatened constantly by software patents. 67 | States should not allow patents to restrict development and use of 68 | software on general-purpose computers, but in those that do, we wish 69 | to avoid the special danger that patents applied to a free program 70 | could make it effectively proprietary. To prevent this, the GPL 71 | assures that patents cannot be used to render the program non-free. 72 | 73 | The precise terms and conditions for copying, distribution and 74 | modification follow. 75 | 76 | ### TERMS AND CONDITIONS 77 | 78 | #### 0. Definitions. 79 | 80 | "This License" refers to version 3 of the GNU General Public License. 81 | 82 | "Copyright" also means copyright-like laws that apply to other kinds 83 | of works, such as semiconductor masks. 84 | 85 | "The Program" refers to any copyrightable work licensed under this 86 | License. Each licensee is addressed as "you". "Licensees" and 87 | "recipients" may be individuals or organizations. 88 | 89 | To "modify" a work means to copy from or adapt all or part of the work 90 | in a fashion requiring copyright permission, other than the making of 91 | an exact copy. The resulting work is called a "modified version" of 92 | the earlier work or a work "based on" the earlier work. 93 | 94 | A "covered work" means either the unmodified Program or a work based 95 | on the Program. 96 | 97 | To "propagate" a work means to do anything with it that, without 98 | permission, would make you directly or secondarily liable for 99 | infringement under applicable copyright law, except executing it on a 100 | computer or modifying a private copy. Propagation includes copying, 101 | distribution (with or without modification), making available to the 102 | public, and in some countries other activities as well. 103 | 104 | To "convey" a work means any kind of propagation that enables other 105 | parties to make or receive copies. Mere interaction with a user 106 | through a computer network, with no transfer of a copy, is not 107 | conveying. 108 | 109 | An interactive user interface displays "Appropriate Legal Notices" to 110 | the extent that it includes a convenient and prominently visible 111 | feature that (1) displays an appropriate copyright notice, and (2) 112 | tells the user that there is no warranty for the work (except to the 113 | extent that warranties are provided), that licensees may convey the 114 | work under this License, and how to view a copy of this License. If 115 | the interface presents a list of user commands or options, such as a 116 | menu, a prominent item in the list meets this criterion. 117 | 118 | #### 1. Source Code. 119 | 120 | The "source code" for a work means the preferred form of the work for 121 | making modifications to it. "Object code" means any non-source form of 122 | a work. 123 | 124 | A "Standard Interface" means an interface that either is an official 125 | standard defined by a recognized standards body, or, in the case of 126 | interfaces specified for a particular programming language, one that 127 | is widely used among developers working in that language. 128 | 129 | The "System Libraries" of an executable work include anything, other 130 | than the work as a whole, that (a) is included in the normal form of 131 | packaging a Major Component, but which is not part of that Major 132 | Component, and (b) serves only to enable use of the work with that 133 | Major Component, or to implement a Standard Interface for which an 134 | implementation is available to the public in source code form. A 135 | "Major Component", in this context, means a major essential component 136 | (kernel, window system, and so on) of the specific operating system 137 | (if any) on which the executable work runs, or a compiler used to 138 | produce the work, or an object code interpreter used to run it. 139 | 140 | The "Corresponding Source" for a work in object code form means all 141 | the source code needed to generate, install, and (for an executable 142 | work) run the object code and to modify the work, including scripts to 143 | control those activities. However, it does not include the work's 144 | System Libraries, or general-purpose tools or generally available free 145 | programs which are used unmodified in performing those activities but 146 | which are not part of the work. For example, Corresponding Source 147 | includes interface definition files associated with source files for 148 | the work, and the source code for shared libraries and dynamically 149 | linked subprograms that the work is specifically designed to require, 150 | such as by intimate data communication or control flow between those 151 | subprograms and other parts of the work. 152 | 153 | The Corresponding Source need not include anything that users can 154 | regenerate automatically from other parts of the Corresponding Source. 155 | 156 | The Corresponding Source for a work in source code form is that same 157 | work. 158 | 159 | #### 2. Basic Permissions. 160 | 161 | All rights granted under this License are granted for the term of 162 | copyright on the Program, and are irrevocable provided the stated 163 | conditions are met. This License explicitly affirms your unlimited 164 | permission to run the unmodified Program. The output from running a 165 | covered work is covered by this License only if the output, given its 166 | content, constitutes a covered work. This License acknowledges your 167 | rights of fair use or other equivalent, as provided by copyright law. 168 | 169 | You may make, run and propagate covered works that you do not convey, 170 | without conditions so long as your license otherwise remains in force. 171 | You may convey covered works to others for the sole purpose of having 172 | them make modifications exclusively for you, or provide you with 173 | facilities for running those works, provided that you comply with the 174 | terms of this License in conveying all material for which you do not 175 | control copyright. Those thus making or running the covered works for 176 | you must do so exclusively on your behalf, under your direction and 177 | control, on terms that prohibit them from making any copies of your 178 | copyrighted material outside their relationship with you. 179 | 180 | Conveying under any other circumstances is permitted solely under the 181 | conditions stated below. Sublicensing is not allowed; section 10 makes 182 | it unnecessary. 183 | 184 | #### 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 185 | 186 | No covered work shall be deemed part of an effective technological 187 | measure under any applicable law fulfilling obligations under article 188 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 189 | similar laws prohibiting or restricting circumvention of such 190 | measures. 191 | 192 | When you convey a covered work, you waive any legal power to forbid 193 | circumvention of technological measures to the extent such 194 | circumvention is effected by exercising rights under this License with 195 | respect to the covered work, and you disclaim any intention to limit 196 | operation or modification of the work as a means of enforcing, against 197 | the work's users, your or third parties' legal rights to forbid 198 | circumvention of technological measures. 199 | 200 | #### 4. Conveying Verbatim Copies. 201 | 202 | You may convey verbatim copies of the Program's source code as you 203 | receive it, in any medium, provided that you conspicuously and 204 | appropriately publish on each copy an appropriate copyright notice; 205 | keep intact all notices stating that this License and any 206 | non-permissive terms added in accord with section 7 apply to the code; 207 | keep intact all notices of the absence of any warranty; and give all 208 | recipients a copy of this License along with the Program. 209 | 210 | You may charge any price or no price for each copy that you convey, 211 | and you may offer support or warranty protection for a fee. 212 | 213 | #### 5. Conveying Modified Source Versions. 214 | 215 | You may convey a work based on the Program, or the modifications to 216 | produce it from the Program, in the form of source code under the 217 | terms of section 4, provided that you also meet all of these 218 | conditions: 219 | 220 | - a) The work must carry prominent notices stating that you modified 221 | it, and giving a relevant date. 222 | - b) The work must carry prominent notices stating that it is 223 | released under this License and any conditions added under 224 | section 7. This requirement modifies the requirement in section 4 225 | to "keep intact all notices". 226 | - c) You must license the entire work, as a whole, under this 227 | License to anyone who comes into possession of a copy. This 228 | License will therefore apply, along with any applicable section 7 229 | additional terms, to the whole of the work, and all its parts, 230 | regardless of how they are packaged. This License gives no 231 | permission to license the work in any other way, but it does not 232 | invalidate such permission if you have separately received it. 233 | - d) If the work has interactive user interfaces, each must display 234 | Appropriate Legal Notices; however, if the Program has interactive 235 | interfaces that do not display Appropriate Legal Notices, your 236 | work need not make them do so. 237 | 238 | A compilation of a covered work with other separate and independent 239 | works, which are not by their nature extensions of the covered work, 240 | and which are not combined with it such as to form a larger program, 241 | in or on a volume of a storage or distribution medium, is called an 242 | "aggregate" if the compilation and its resulting copyright are not 243 | used to limit the access or legal rights of the compilation's users 244 | beyond what the individual works permit. Inclusion of a covered work 245 | in an aggregate does not cause this License to apply to the other 246 | parts of the aggregate. 247 | 248 | #### 6. Conveying Non-Source Forms. 249 | 250 | You may convey a covered work in object code form under the terms of 251 | sections 4 and 5, provided that you also convey the machine-readable 252 | Corresponding Source under the terms of this License, in one of these 253 | ways: 254 | 255 | - a) Convey the object code in, or embodied in, a physical product 256 | (including a physical distribution medium), accompanied by the 257 | Corresponding Source fixed on a durable physical medium 258 | customarily used for software interchange. 259 | - b) Convey the object code in, or embodied in, a physical product 260 | (including a physical distribution medium), accompanied by a 261 | written offer, valid for at least three years and valid for as 262 | long as you offer spare parts or customer support for that product 263 | model, to give anyone who possesses the object code either (1) a 264 | copy of the Corresponding Source for all the software in the 265 | product that is covered by this License, on a durable physical 266 | medium customarily used for software interchange, for a price no 267 | more than your reasonable cost of physically performing this 268 | conveying of source, or (2) access to copy the Corresponding 269 | Source from a network server at no charge. 270 | - c) Convey individual copies of the object code with a copy of the 271 | written offer to provide the Corresponding Source. This 272 | alternative is allowed only occasionally and noncommercially, and 273 | only if you received the object code with such an offer, in accord 274 | with subsection 6b. 275 | - d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | - e) Convey the object code using peer-to-peer transmission, 288 | provided you inform other peers where the object code and 289 | Corresponding Source of the work are being offered to the general 290 | public at no charge under subsection 6d. 291 | 292 | A separable portion of the object code, whose source code is excluded 293 | from the Corresponding Source as a System Library, need not be 294 | included in conveying the object code work. 295 | 296 | A "User Product" is either (1) a "consumer product", which means any 297 | tangible personal property which is normally used for personal, 298 | family, or household purposes, or (2) anything designed or sold for 299 | incorporation into a dwelling. In determining whether a product is a 300 | consumer product, doubtful cases shall be resolved in favor of 301 | coverage. For a particular product received by a particular user, 302 | "normally used" refers to a typical or common use of that class of 303 | product, regardless of the status of the particular user or of the way 304 | in which the particular user actually uses, or expects or is expected 305 | to use, the product. A product is a consumer product regardless of 306 | whether the product has substantial commercial, industrial or 307 | non-consumer uses, unless such uses represent the only significant 308 | mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to 312 | install and execute modified versions of a covered work in that User 313 | Product from a modified version of its Corresponding Source. The 314 | information must suffice to ensure that the continued functioning of 315 | the modified object code is in no case prevented or interfered with 316 | solely because modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or 331 | updates for a work that has been modified or installed by the 332 | recipient, or for the User Product in which it has been modified or 333 | installed. Access to a network may be denied when the modification 334 | itself materially and adversely affects the operation of the network 335 | or violates the rules and protocols for communication across the 336 | network. 337 | 338 | Corresponding Source conveyed, and Installation Information provided, 339 | in accord with this section must be in a format that is publicly 340 | documented (and with an implementation available to the public in 341 | source code form), and must require no special password or key for 342 | unpacking, reading or copying. 343 | 344 | #### 7. Additional Terms. 345 | 346 | "Additional permissions" are terms that supplement the terms of this 347 | License by making exceptions from one or more of its conditions. 348 | Additional permissions that are applicable to the entire Program shall 349 | be treated as though they were included in this License, to the extent 350 | that they are valid under applicable law. If additional permissions 351 | apply only to part of the Program, that part may be used separately 352 | under those permissions, but the entire Program remains governed by 353 | this License without regard to the additional permissions. 354 | 355 | When you convey a copy of a covered work, you may at your option 356 | remove any additional permissions from that copy, or from any part of 357 | it. (Additional permissions may be written to require their own 358 | removal in certain cases when you modify the work.) You may place 359 | additional permissions on material, added by you to a covered work, 360 | for which you have or can give appropriate copyright permission. 361 | 362 | Notwithstanding any other provision of this License, for material you 363 | add to a covered work, you may (if authorized by the copyright holders 364 | of that material) supplement the terms of this License with terms: 365 | 366 | - a) Disclaiming warranty or limiting liability differently from the 367 | terms of sections 15 and 16 of this License; or 368 | - b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | - c) Prohibiting misrepresentation of the origin of that material, 372 | or requiring that modified versions of such material be marked in 373 | reasonable ways as different from the original version; or 374 | - d) Limiting the use for publicity purposes of names of licensors 375 | or authors of the material; or 376 | - e) Declining to grant rights under trademark law for use of some 377 | trade names, trademarks, or service marks; or 378 | - f) Requiring indemnification of licensors and authors of that 379 | material by anyone who conveys the material (or modified versions 380 | of it) with contractual assumptions of liability to the recipient, 381 | for any liability that these contractual assumptions directly 382 | impose on those licensors and authors. 383 | 384 | All other non-permissive additional terms are considered "further 385 | restrictions" within the meaning of section 10. If the Program as you 386 | received it, or any part of it, contains a notice stating that it is 387 | governed by this License along with a term that is a further 388 | restriction, you may remove that term. If a license document contains 389 | a further restriction but permits relicensing or conveying under this 390 | License, you may add to a covered work material governed by the terms 391 | of that license document, provided that the further restriction does 392 | not survive such relicensing or conveying. 393 | 394 | If you add terms to a covered work in accord with this section, you 395 | must place, in the relevant source files, a statement of the 396 | additional terms that apply to those files, or a notice indicating 397 | where to find the applicable terms. 398 | 399 | Additional terms, permissive or non-permissive, may be stated in the 400 | form of a separately written license, or stated as exceptions; the 401 | above requirements apply either way. 402 | 403 | #### 8. Termination. 404 | 405 | You may not propagate or modify a covered work except as expressly 406 | provided under this License. Any attempt otherwise to propagate or 407 | modify it is void, and will automatically terminate your rights under 408 | this License (including any patent licenses granted under the third 409 | paragraph of section 11). 410 | 411 | However, if you cease all violation of this License, then your license 412 | from a particular copyright holder is reinstated (a) provisionally, 413 | unless and until the copyright holder explicitly and finally 414 | terminates your license, and (b) permanently, if the copyright holder 415 | fails to notify you of the violation by some reasonable means prior to 416 | 60 days after the cessation. 417 | 418 | Moreover, your license from a particular copyright holder is 419 | reinstated permanently if the copyright holder notifies you of the 420 | violation by some reasonable means, this is the first time you have 421 | received notice of violation of this License (for any work) from that 422 | copyright holder, and you cure the violation prior to 30 days after 423 | your receipt of the notice. 424 | 425 | Termination of your rights under this section does not terminate the 426 | licenses of parties who have received copies or rights from you under 427 | this License. If your rights have been terminated and not permanently 428 | reinstated, you do not qualify to receive new licenses for the same 429 | material under section 10. 430 | 431 | #### 9. Acceptance Not Required for Having Copies. 432 | 433 | You are not required to accept this License in order to receive or run 434 | a copy of the Program. Ancillary propagation of a covered work 435 | occurring solely as a consequence of using peer-to-peer transmission 436 | to receive a copy likewise does not require acceptance. However, 437 | nothing other than this License grants you permission to propagate or 438 | modify any covered work. These actions infringe copyright if you do 439 | not accept this License. Therefore, by modifying or propagating a 440 | covered work, you indicate your acceptance of this License to do so. 441 | 442 | #### 10. Automatic Licensing of Downstream Recipients. 443 | 444 | Each time you convey a covered work, the recipient automatically 445 | receives a license from the original licensors, to run, modify and 446 | propagate that work, subject to this License. You are not responsible 447 | for enforcing compliance by third parties with this License. 448 | 449 | An "entity transaction" is a transaction transferring control of an 450 | organization, or substantially all assets of one, or subdividing an 451 | organization, or merging organizations. If propagation of a covered 452 | work results from an entity transaction, each party to that 453 | transaction who receives a copy of the work also receives whatever 454 | licenses to the work the party's predecessor in interest had or could 455 | give under the previous paragraph, plus a right to possession of the 456 | Corresponding Source of the work from the predecessor in interest, if 457 | the predecessor has it or can get it with reasonable efforts. 458 | 459 | You may not impose any further restrictions on the exercise of the 460 | rights granted or affirmed under this License. For example, you may 461 | not impose a license fee, royalty, or other charge for exercise of 462 | rights granted under this License, and you may not initiate litigation 463 | (including a cross-claim or counterclaim in a lawsuit) alleging that 464 | any patent claim is infringed by making, using, selling, offering for 465 | sale, or importing the Program or any portion of it. 466 | 467 | #### 11. Patents. 468 | 469 | A "contributor" is a copyright holder who authorizes use under this 470 | License of the Program or a work on which the Program is based. The 471 | work thus licensed is called the contributor's "contributor version". 472 | 473 | A contributor's "essential patent claims" are all patent claims owned 474 | or controlled by the contributor, whether already acquired or 475 | hereafter acquired, that would be infringed by some manner, permitted 476 | by this License, of making, using, or selling its contributor version, 477 | but do not include claims that would be infringed only as a 478 | consequence of further modification of the contributor version. For 479 | purposes of this definition, "control" includes the right to grant 480 | patent sublicenses in a manner consistent with the requirements of 481 | this License. 482 | 483 | Each contributor grants you a non-exclusive, worldwide, royalty-free 484 | patent license under the contributor's essential patent claims, to 485 | make, use, sell, offer for sale, import and otherwise run, modify and 486 | propagate the contents of its contributor version. 487 | 488 | In the following three paragraphs, a "patent license" is any express 489 | agreement or commitment, however denominated, not to enforce a patent 490 | (such as an express permission to practice a patent or covenant not to 491 | sue for patent infringement). To "grant" such a patent license to a 492 | party means to make such an agreement or commitment not to enforce a 493 | patent against the party. 494 | 495 | If you convey a covered work, knowingly relying on a patent license, 496 | and the Corresponding Source of the work is not available for anyone 497 | to copy, free of charge and under the terms of this License, through a 498 | publicly available network server or other readily accessible means, 499 | then you must either (1) cause the Corresponding Source to be so 500 | available, or (2) arrange to deprive yourself of the benefit of the 501 | patent license for this particular work, or (3) arrange, in a manner 502 | consistent with the requirements of this License, to extend the patent 503 | license to downstream recipients. "Knowingly relying" means you have 504 | actual knowledge that, but for the patent license, your conveying the 505 | covered work in a country, or your recipient's use of the covered work 506 | in a country, would infringe one or more identifiable patents in that 507 | country that you have reason to believe are valid. 508 | 509 | If, pursuant to or in connection with a single transaction or 510 | arrangement, you convey, or propagate by procuring conveyance of, a 511 | covered work, and grant a patent license to some of the parties 512 | receiving the covered work authorizing them to use, propagate, modify 513 | or convey a specific copy of the covered work, then the patent license 514 | you grant is automatically extended to all recipients of the covered 515 | work and works based on it. 516 | 517 | A patent license is "discriminatory" if it does not include within the 518 | scope of its coverage, prohibits the exercise of, or is conditioned on 519 | the non-exercise of one or more of the rights that are specifically 520 | granted under this License. You may not convey a covered work if you 521 | are a party to an arrangement with a third party that is in the 522 | business of distributing software, under which you make payment to the 523 | third party based on the extent of your activity of conveying the 524 | work, and under which the third party grants, to any of the parties 525 | who would receive the covered work from you, a discriminatory patent 526 | license (a) in connection with copies of the covered work conveyed by 527 | you (or copies made from those copies), or (b) primarily for and in 528 | connection with specific products or compilations that contain the 529 | covered work, unless you entered into that arrangement, or that patent 530 | license was granted, prior to 28 March 2007. 531 | 532 | Nothing in this License shall be construed as excluding or limiting 533 | any implied license or other defenses to infringement that may 534 | otherwise be available to you under applicable patent law. 535 | 536 | #### 12. No Surrender of Others' Freedom. 537 | 538 | If conditions are imposed on you (whether by court order, agreement or 539 | otherwise) that contradict the conditions of this License, they do not 540 | excuse you from the conditions of this License. If you cannot convey a 541 | covered work so as to satisfy simultaneously your obligations under 542 | this License and any other pertinent obligations, then as a 543 | consequence you may not convey it at all. For example, if you agree to 544 | terms that obligate you to collect a royalty for further conveying 545 | from those to whom you convey the Program, the only way you could 546 | satisfy both those terms and this License would be to refrain entirely 547 | from conveying the Program. 548 | 549 | #### 13. Use with the GNU Affero General Public License. 550 | 551 | Notwithstanding any other provision of this License, you have 552 | permission to link or combine any covered work with a work licensed 553 | under version 3 of the GNU Affero General Public License into a single 554 | combined work, and to convey the resulting work. The terms of this 555 | License will continue to apply to the part which is the covered work, 556 | but the special requirements of the GNU Affero General Public License, 557 | section 13, concerning interaction through a network will apply to the 558 | combination as such. 559 | 560 | #### 14. Revised Versions of this License. 561 | 562 | The Free Software Foundation may publish revised and/or new versions 563 | of the GNU General Public License from time to time. Such new versions 564 | will be similar in spirit to the present version, but may differ in 565 | detail to address new problems or concerns. 566 | 567 | Each version is given a distinguishing version number. If the Program 568 | specifies that a certain numbered version of the GNU General Public 569 | License "or any later version" applies to it, you have the option of 570 | following the terms and conditions either of that numbered version or 571 | of any later version published by the Free Software Foundation. If the 572 | Program does not specify a version number of the GNU General Public 573 | License, you may choose any version ever published by the Free 574 | Software Foundation. 575 | 576 | If the Program specifies that a proxy can decide which future versions 577 | of the GNU General Public License can be used, that proxy's public 578 | statement of acceptance of a version permanently authorizes you to 579 | choose that version for the Program. 580 | 581 | Later license versions may give you additional or different 582 | permissions. However, no additional obligations are imposed on any 583 | author or copyright holder as a result of your choosing to follow a 584 | later version. 585 | 586 | #### 15. Disclaimer of Warranty. 587 | 588 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 589 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 590 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT 591 | WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT 592 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 593 | A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND 594 | PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE 595 | DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR 596 | CORRECTION. 597 | 598 | #### 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR 602 | CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 603 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES 604 | ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT 605 | NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR 606 | LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM 607 | TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER 608 | PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 609 | 610 | #### 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | ### How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these 626 | terms. 627 | 628 | To do so, attach the following notices to the program. It is safest to 629 | attach them to the start of each source file to most effectively state 630 | the exclusion of warranty; and each file should have at least the 631 | "copyright" line and a pointer to where the full notice is found. 632 | 633 | 634 | Copyright (C) 635 | 636 | This program is free software: you can redistribute it and/or modify 637 | it under the terms of the GNU General Public License as published by 638 | the Free Software Foundation, either version 3 of the License, or 639 | (at your option) any later version. 640 | 641 | This program is distributed in the hope that it will be useful, 642 | but WITHOUT ANY WARRANTY; without even the implied warranty of 643 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 644 | GNU General Public License for more details. 645 | 646 | You should have received a copy of the GNU General Public License 647 | along with this program. If not, see . 648 | 649 | Also add information on how to contact you by electronic and paper 650 | mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands \`show w' and \`show c' should show the 661 | appropriate parts of the General Public License. Of course, your 662 | program's commands might be different; for a GUI interface, you would 663 | use an "about box". 664 | 665 | You should also get your employer (if you work as a programmer) or 666 | school, if any, to sign a "copyright disclaimer" for the program, if 667 | necessary. For more information on this, and how to apply and follow 668 | the GNU GPL, see . 669 | 670 | The GNU General Public License does not permit incorporating your 671 | program into proprietary programs. If your program is a subroutine 672 | library, you may consider it more useful to permit linking proprietary 673 | applications with the library. If this is what you want to do, use the 674 | GNU Lesser General Public License instead of this License. But first, 675 | please read . 676 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | SKYLIGHT_AVAILABLE := $(shell test -d /System/Library/PrivateFrameworks/SkyLight.framework && echo 1 || echo 0) 2 | override CXXFLAGS += -O2 -Wall -fobjc-arc -D"NS_FORMAT_ARGUMENT(A)=" -D"SKYLIGHT_AVAILABLE=$(SKYLIGHT_AVAILABLE)" 3 | 4 | .PHONY: all clean install 5 | 6 | all: AutoRaise AutoRaise.app 7 | 8 | clean: 9 | rm -f AutoRaise 10 | rm -rf AutoRaise.app 11 | 12 | install: AutoRaise.app 13 | rm -rf /Applications/AutoRaise.app 14 | cp -r AutoRaise.app /Applications/ 15 | 16 | AutoRaise: AutoRaise.mm 17 | ifeq ($(SKYLIGHT_AVAILABLE), 1) 18 | g++ $(CXXFLAGS) -o $@ $^ -framework AppKit -F /System/Library/PrivateFrameworks -framework SkyLight 19 | else 20 | g++ $(CXXFLAGS) -o $@ $^ -framework AppKit 21 | endif 22 | 23 | AutoRaise.app: AutoRaise Info.plist AutoRaise.icns 24 | ./create-app-bundle.sh 25 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | **AutoRaise** 2 | 3 | When you hover a window it will be raised to the front (with a delay of your choosing) and gets the focus. There is also an option to warp 4 | the mouse to the center of the activated window when using the cmd-tab or cmd-grave (backtick) key combination. 5 | See also [on stackoverflow](https://stackoverflow.com/questions/98310/focus-follows-mouse-plus-auto-raise-on-mac-os-x) 6 | 7 | **Quick start** 8 | 9 | 1. Download the [disk image](https://github.com/sbmpost/AutoRaise/blob/master/AutoRaise.dmg) 10 | 2. Double click the downloaded .dmg in Finder. 11 | 3. In finder, look for mounted disk image on side bar at left. 12 | 4. Drag the AutoRaise.app into the Applications folder. 13 | 5. Then open AutoRaise from Applications. 14 | 6. Left click the menu bar balloon at top to give permissions to AutoRaise in System/Accessibility. 15 | 7. Right click the menu bar balloon at top, then select preferences. 16 | 17 | *Important*: When you enable Accessibility in System Preferences, if you see an older AutoRaise item with balloon icon in the 18 | Accessibility pane, first remove it **completely** (clicking the minus). Then stop and start AutoRaise by left clicking the balloon 19 | icon, and the item should re-appear so that you can properly enable Accessibility. 20 | 21 | **Compiling AutoRaise** 22 | 23 | To compile AutoRaise yourself, download the master branch from [here](https://github.com/sbmpost/AutoRaise/archive/refs/heads/master.zip) 24 | and use the following commands: 25 | 26 | unzip -d ~ ~/Downloads/AutoRaise-master.zip 27 | cd ~/AutoRaise-master && make clean && make && make install 28 | 29 | **Advanced compilation options** 30 | 31 | * ALTERNATIVE_TASK_SWITCHER: The warp feature works accurately with the default OSX task switcher. Enable the alternative 32 | task switcher flag if you use an alternative task switcher and are willing to accept that in some cases you may encounter 33 | an unexpected mouse warp. 34 | 35 | * OLD_ACTIVATION_METHOD: Enable this flag if one of your applications is not raising properly. This can happen if the 36 | application uses a non native graphic technology like GTK or SDL. It could also be a [wine](https://www.winehq.org) application. 37 | Note this will introduce a deprecation warning. 38 | 39 | * EXPERIMENTAL_FOCUS_FIRST: Enabling this flag adds support for first focusing the hovered window before actually raising it. 40 | Or not raising at all if the -delay setting equals 0. This is an experimental feature. It relies on undocumented private API 41 | calls. *As such there is absolutely no guarantee it will be supported in future OSX versions*. 42 | 43 | Example advanced compilation command: 44 | 45 | make CXXFLAGS="-DOLD_ACTIVATION_METHOD -DEXPERIMENTAL_FOCUS_FIRST" && make install 46 | 47 | **Running AutoRaise** 48 | 49 | After making the project, you end up with these two files: 50 | 51 | AutoRaise (command line version) 52 | AutoRaise.app (version without GUI) 53 | 54 | The first binary is to be used directly from the command line and accepts parameters. The second binary, AutoRaise.app, can 55 | be used without a terminal window and relies on the presence of a configuration file. AutoRaise.app runs on the background and 56 | can only be stopped via "Activity Monitor" or the AppleScript provided near the bottom of this README. 57 | 58 | **Command line usage:** 59 | 60 | ./AutoRaise -pollMillis 50 -delay 1 -focusDelay 0 -warpX 0.5 -warpY 0.1 -scale 2.5 -altTaskSwitcher false -ignoreSpaceChanged false -ignoreApps "App1,App2" -stayFocusedBundleIds "Id1,Id2" -disableKey control -mouseDelta 0.1 61 | 62 | *Note*: focusDelay is only supported when compiled with the "EXPERIMENTAL_FOCUS_FIRST" flag. 63 | 64 | - pollMillis: How often to poll the mouse position and consider a raise/focus. Lower values increase responsiveness but also CPU load. Minimum = 20 and default = 50. 65 | 66 | - delay: Raise delay, specified in units of pollMillis. Disabled if 0. A delay > 1 requires the mouse to stop for a moment before raising. 67 | 68 | - focusDelay: Focus delay, specified in units of pollMillis. Disabled if 0. A delay > 1 requires the mouse to stop for a moment before focusing. 69 | 70 | - warpX: A Factor between 0 and 1. Makes the mouse jump horizontally to the activated window. By default disabled. 71 | 72 | - warpY: A Factor between 0 and 1. Makes the mouse jump vertically to the activated window. By default disabled. 73 | 74 | - scale: Enlarge the mouse for a short period of time after warping it. The default is 2.0. To disable set it to 1.0. 75 | 76 | - altTaskSwitcher: Set to true if you use 3rd party tools to switch between applications (other than standard command-tab). 77 | 78 | - ignoreSpaceChanged: Do not immediately raise/focus after a space change. The default is false. 79 | 80 | - invertIgnoreApps: Turns the ignoreApps parameter into an includeApps parameter. The default is false. 81 | 82 | - ignoreApps: Comma separated list of apps for which you would like to disable focus/raise. 83 | 84 | - ignoreTitles: Comma separated list of window titles (a title can be an ICU regular expression) for which you would like to disable focus/raise. 85 | 86 | - stayFocusedBundleIds: Comma separated list of app bundle identifiers that shouldn't lose focus even when hovering the mouse over another window. 87 | 88 | - disableKey: Set to control, option or disabled. This will temporarily disable AutoRaise while holding the specified key. The default is control. 89 | 90 | - mouseDelta: Requires the mouse to move a certain distance. 0.0 = most sensitive whereas higher values decrease sensitivity. 91 | 92 | - verbose: Set to true to make AutoRaise show a log of events when started in a terminal. 93 | 94 | AutoRaise can read these parameters from a configuration file. To make this happen, create a **~/.AutoRaise** file or a 95 | **~/.config/AutoRaise/config** file. The format is as follows: 96 | 97 | #AutoRaise config file 98 | pollMillis=50 99 | delay=1 100 | focusDelay=0 101 | warpX=0.5 102 | warpY=0.1 103 | scale=2.5 104 | altTaskSwitcher=false 105 | ignoreSpaceChanged=false 106 | invertIgnoreApps=false 107 | ignoreApps="IntelliJ IDEA,WebStorm" 108 | ignoreTitles="\\s\\| Microsoft Teams,..." 109 | stayFocusedBundleIds="com.apple.SecurityAgent,..." 110 | disableKey="control" 111 | mouseDelta=0.1 112 | 113 | **AutoRaise.app usage:** 114 | 115 | a) setup configuration file, see above ^ 116 | b) open /Applications/AutoRaise.app (allow Accessibility if asked for) 117 | c) either stop AutoRaise via "Activity Monitor" or read on: 118 | 119 | To toggle AutoRaise on/off with a keyboard shortcut, paste the AppleScript below into an automator service workflow. Then 120 | bind the created service to a keyboard shortcut via System Preferences|Keyboard|Shortcuts. This also works for AutoRaise.app 121 | in which case "/Applications/AutoRaise" should be replaced with "/Applications/AutoRaise.app" 122 | 123 | Applescript: 124 | 125 | on run {input, parameters} 126 | tell application "Finder" 127 | if exists of application process "AutoRaise" then 128 | quit application "/Applications/AutoRaise" 129 | display notification "AutoRaise Stopped" 130 | else 131 | launch application "/Applications/AutoRaise" 132 | display notification "AutoRaise Started" 133 | end if 134 | end tell 135 | return input 136 | end run 137 | 138 | **Troubleshooting & Verbose logging** 139 | 140 | If you experience any issues, it is suggested to first check these points: 141 | 142 | - Are you using the latest version? 143 | - Does it work with the command line version? 144 | - Are you running other mouse tools that might intervene with AutoRaise? 145 | - Are you running two AutoRaise instances at the same time? Use "Activity Monitor" to check this. 146 | - Is Accessibility properly enabled? To be absolutely sure, remove any previous AutoRaise items 147 | that may be present in the System Preferences|Security & Privacy|Privacy|Accessibility pane. Then 148 | start AutoRaise and enable accessibility again. 149 | 150 | If after checking the above you still experience the problem, I encourage you to create an issue 151 | in github. It will be helpful to provide (a small part of) the verbose log, which can be enabled 152 | like so: 153 | 154 | ./AutoRaise -verbose true 155 | 156 | The output should look something like this: 157 | 158 | v5.3 by sbmpost(c) 2024, usage: 159 | 160 | AutoRaise 161 | -pollMillis <20, 30, 40, 50, ...> 162 | -delay <0=no-raise, 1=no-delay, 2=50ms, 3=100ms, ...> 163 | -focusDelay <0=no-focus, 1=no-delay, 2=50ms, 3=100ms, ...> 164 | -warpX <0.5> -warpY <0.5> -scale <2.0> 165 | -altTaskSwitcher 166 | -ignoreSpaceChanged 167 | -invertIgnoreApps 168 | -ignoreApps "" 169 | -ignoreTitles "" 170 | -stayFocusedBundleIds "" 171 | -disableKey 172 | -mouseDelta <0.1> 173 | -verbose 174 | 175 | Started with: 176 | * pollMillis: 50ms 177 | * delay: 0ms 178 | * focusDelay: disabled 179 | * warpX: 0.5, warpY: 0.1, scale: 2.5 180 | * altTaskSwitcher: false 181 | * ignoreSpaceChanged: false 182 | * invertIgnoreApps: false 183 | * ignoreApp: App1 184 | * ignoreApp: App2 185 | * ignoreTitle: Regex1 186 | * ignoreTitle: Regex2 187 | * stayFocusedBundleId: Id1 188 | * stayFocusedBundleId: Id2 189 | * disableKey: control 190 | * mouseDelta: 2.0 191 | * verbose: true 192 | 193 | Compiled with: 194 | * OLD_ACTIVATION_METHOD 195 | * EXPERIMENTAL_FOCUS_FIRST 196 | 197 | 2024-04-09 10:55:27.903 AutoRaise[40260:3886758] AXIsProcessTrusted: YES 198 | 2024-04-09 10:55:27.922 AutoRaise[40260:3886758] System cursor scale: 1.000000 199 | 2024-04-09 10:55:27.936 AutoRaise[40260:3886758] Got run loop source: YES 200 | 2024-04-09 10:55:27.975 AutoRaise[40260:3886758] Registered app activated selector 201 | 2024-04-09 10:55:27.995 AutoRaise[40260:3886758] Desktop origin (-1920.000000, -360.000000) 202 | ... 203 | ... 204 | 205 | *Note*: Dimentium created a homebrew formula for this tool which can be found here: 206 | 207 | https://github.com/Dimentium/homebrew-autoraise 208 | -------------------------------------------------------------------------------- /create-app-bundle.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | rm -rf AutoRaise.app && \ 4 | mkdir -p AutoRaise.app/Contents/MacOS && \ 5 | mkdir AutoRaise.app/Contents/Resources && \ 6 | cp AutoRaise AutoRaise.app/Contents/MacOS && \ 7 | cp Info.plist AutoRaise.app/Contents && \ 8 | cp AutoRaise.icns AutoRaise.app/Contents/Resources && \ 9 | chmod 755 AutoRaise.app && echo "Successfully created AutoRaise.app" 10 | --------------------------------------------------------------------------------