Skip to content

Commit

Permalink
Improve #59
Browse files Browse the repository at this point in the history
  • Loading branch information
sindresorhus committed Nov 13, 2019
1 parent 9479d1b commit 25b3734
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 7 deletions.
19 changes: 14 additions & 5 deletions Sources/active-win/main.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,18 @@
import AppKit

// This shows 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
}

func toJson<T>(_ data: T) throws -> String {
let json = try JSONSerialization.data(withJSONObject: data)
return String(data: json, encoding: .utf8)!
Expand All @@ -15,11 +28,7 @@ let frontmostAppPID = NSWorkspace.shared.frontmostApplication!.processIdentifier
let windows = CGWindowListCopyWindowInfo([.optionOnScreenOnly, .excludeDesktopElements], kCGNullWindowID) as! [[String: Any]]

// Show screen recording permission prompt if needed. Required to get the complete window title.
if
let firstWindow = windows.first,
let windowNumber = firstWindow[kCGWindowNumber as String] as? CGWindowID,
CGWindowListCreateImage(.null, .optionIncludingWindow, windowNumber, [.boundsIgnoreFraming, .bestResolution]) == nil
{
if !hasScreenRecordingPermission() {
print("active-win requires the screen recording permission in “System Preferences › Security & Privacy › Privacy › Screen Recording”.")
exit(1)
}
Expand Down
4 changes: 2 additions & 2 deletions index.test-d.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {expectType, expectError} from 'tsd';
import activeWin = require('.');
import { Result, LinuxResult, MacOSResult, WindowsResult } from '.';
import {Result, LinuxResult, MacOSResult, WindowsResult} from '.';

expectType<Promise<Result | undefined>>(activeWin());

Expand All @@ -9,7 +9,7 @@ const result = activeWin.sync();
expectType<Result | undefined>(result);

if (result) {
expectType<string>(result.platform);
expectType<'macos' | 'linux' | 'windows'>(result.platform);
expectType<string>(result.title);
expectType<number>(result.id);
expectType<number>(result.bounds.x);
Expand Down

0 comments on commit 25b3734

Please sign in to comment.