Skip to content

Commit

Permalink
Meta tweaks
Browse files Browse the repository at this point in the history
  • Loading branch information
sindresorhus committed Feb 19, 2020
1 parent 47e6e44 commit 1ec222c
Show file tree
Hide file tree
Showing 6 changed files with 43 additions and 39 deletions.
33 changes: 4 additions & 29 deletions Sources/active-win/main.swift
Original file line number Diff line number Diff line change
@@ -1,11 +1,5 @@
import AppKit

@discardableResult
func runAppleScript(source: String) -> String? {
NSAppleScript(source: source)?.executeAndReturnError(nil).stringValue
}

// Format the AppleScript command for Chrome, Safari, Brave, and Edge
func getActiveBrowserTabURLAppleScriptCommand(_ appName: String) -> String? {
switch appName {
case "Google Chrome", "Brave Browser", "Microsoft Edge":
Expand All @@ -17,25 +11,6 @@ func getActiveBrowserTabURLAppleScriptCommand(_ appName: String) -> String? {
}
}

// Show the system prompt if there's no permission.
func hasScreenRecordingPermission() -> Bool {
CGDisplayStream(
dispatchQueueDisplay: CGMainDisplayID(),
outputWidth: 1,
outputHeight: 1,
pixelFormat: Int32(kCVPixelFormatType_32BGRA),
properties: nil,
queue: DispatchQueue.global(),
handler: { _, _, _, _ in }
) != nil
}

// Serialize data dict to JSON
func toJson<T>(_ data: T) throws -> String {
let json = try JSONSerialization.data(withJSONObject: data)
return String(data: json, encoding: .utf8)!
}

// Show accessibility permission prompt if needed. Required to get the complete window title.
if !AXIsProcessTrustedWithOptions(["AXTrustedCheckOptionPrompt": true] as CFDictionary) {
print("active-win requires the accessibility permission in “System Preferences › Security & Privacy › Privacy › Accessibility”.")
Expand All @@ -58,22 +33,22 @@ for window in windows {
continue
}

// Skip transparent windows, like with Chrome
// Skip transparent windows, like with Chrome.
if (window[kCGWindowAlpha as String] as! Double) == 0 {
continue
}

let bounds = CGRect(dictionaryRepresentation: window[kCGWindowBounds as String] as! CFDictionary)!

// Skip tiny windows, like the Chrome link hover statusbar
// Skip tiny windows, like the Chrome link hover statusbar.
let minWinSize: CGFloat = 50
if bounds.width < minWinSize || bounds.height < minWinSize {
continue
}

let appPid = window[kCGWindowOwnerPID as String] as! pid_t

// This can't fail as we're only dealing with apps
// This can't fail as we're only dealing with apps.
let app = NSRunningApplication(processIdentifier: appPid)!

let appName = window[kCGWindowOwnerName as String] as! String
Expand All @@ -96,7 +71,7 @@ for window in windows {
"memoryUsage": window[kCGWindowMemoryUsage as String] as! Int
]

// Only run the AppleScript if active window is a compatible browser
// Only run the AppleScript if active window is a compatible browser.
if
let script = getActiveBrowserTabURLAppleScriptCommand(appName),
let url = runAppleScript(source: script)
Expand Down
27 changes: 27 additions & 0 deletions Sources/active-win/utilities.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import AppKit


@discardableResult
func runAppleScript(source: String) -> String? {
NSAppleScript(source: source)?.executeAndReturnError(nil).stringValue
}


func toJson<T>(_ data: T) throws -> String {
let json = try JSONSerialization.data(withJSONObject: data)
return String(data: json, encoding: .utf8)!
}


// Show the system prompt if there's no permission.
func hasScreenRecordingPermission() -> Bool {
CGDisplayStream(
dispatchQueueDisplay: CGMainDisplayID(),
outputWidth: 1,
outputHeight: 1,
pixelFormat: Int32(kCVPixelFormatType_32BGRA),
properties: nil,
queue: DispatchQueue.global(),
handler: { _, _, _, _ in }
) != nil
}
1 change: 1 addition & 0 deletions index.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ if (result) {
expectType<number>(result.owner.processId);
expectType<string>(result.owner.path);
expectType<number>(result.memoryUsage);

if (result.platform === 'macos') {
expectType<MacOSResult>(result);
expectType<number>(result.owner.bundleId);
Expand Down
2 changes: 1 addition & 1 deletion license
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
MIT License

Copyright (c) Sindre Sorhus <[email protected]> (sindresorhus.com)
Copyright (c) Sindre Sorhus <[email protected]> (https://sindresorhus.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

Expand Down
13 changes: 10 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
{
"name": "active-win",
"version": "6.0.0",
"description": "Get metadata about the active window (title, id, bounds, owner, etc). Works on macOS, Linux, Windows.",
"description": "Get metadata about the active window (title, id, bounds, owner, URL, etc). Works on macOS, Linux, Windows.",
"license": "MIT",
"repository": "sindresorhus/active-win",
"funding": "https://github.com/sponsors/sindresorhus",
"author": {
"name": "Sindre Sorhus",
"email": "[email protected]",
"url": "sindresorhus.com"
"url": "https://sindresorhus.com"
},
"engines": {
"node": ">=8"
Expand Down Expand Up @@ -44,7 +45,13 @@
"bounds",
"memory",
"usage",
"bundleid"
"bundleid",
"browser",
"url",
"chrome",
"safari",
"edge",
"brave"
],
"devDependencies": {
"ava": "^2.4.0",
Expand Down
6 changes: 0 additions & 6 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,12 @@ Works on macOS, Linux, Windows.

Users on macOS 10.13 or earlier needs to download the [Swift runtime support libraries](https://support.apple.com/kb/DL1998).


## Install

```
$ npm install active-win
```


## Usage

```js
Expand Down Expand Up @@ -55,7 +53,6 @@ Returns a `Promise<Object>` with the result, or `Promise<undefined>` if there is

Returns an `Object` with the result, or `undefined` if there is no active window.


## Result

- `platform` *(string)* - `'macos'` | `'linux'` | `'windows'`
Expand All @@ -74,20 +71,17 @@ Returns an `Object` with the result, or `undefined` if there is no active window
- `url` *(string?)* - URL of the active browser tab if the active window is Safari, Chrome, Edge, or Brave *(macOS only)*
- `memoryUsage` *(number)* - Memory usage by the window owner process


## OS support

It works on macOS, Linux, and Windows 7+.

**Note**: On Windows, there isn't a clear notion of a "Window ID". Instead it returns the memory address of the window "handle" in the `id` property. That "handle" is unique per window, so it can be used to identify them. [Read more…](https://msdn.microsoft.com/en-us/library/windows/desktop/ms632597(v=vs.85).aspx#window_handle).


## Related

- [active-win-cli](https://github.com/sindresorhus/active-win-cli) - CLI for this module
- [active-win-log](https://github.com/uglow/active-win-log) - Window-usage logging CLI using this module


## Maintainers

- [Sindre Sorhus](https://github.com/sindresorhus)
Expand Down

0 comments on commit 1ec222c

Please sign in to comment.