Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement a macOS listener #30

Merged
merged 10 commits into from
Dec 8, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,13 @@ pip install darkdetect

Alternatively, you are free to vendor directly a copy of Darkdetect in your app. Further information on vendoring can be found [here](https://medium.com/underdog-io-engineering/vendoring-python-dependencies-with-pip-b9eb6078b9c0).

## Optional Installs

To enable the macOS listener, additional components are required, these can be installed via:
```bash
pip install darkdetect[macos-listener]
```

## Notes

- This software is licensed under the terms of the 3-clause BSD License.
Expand Down
56 changes: 53 additions & 3 deletions darkdetect/_mac_detect.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,19 @@

import ctypes
import ctypes.util
import subprocess
import sys
import os
zwimer marked this conversation as resolved.
Show resolved Hide resolved
from pathlib import Path
from typing import Callable

try:
from Foundation import NSObject, NSKeyValueObservingOptionNew, NSKeyValueChangeNewKey, NSUserDefaults
from PyObjCTools import AppHelper
_can_listen = True
except ModuleNotFoundError:
_can_listen = False


try:
# macOS Big Sur+ use "a built-in dynamic linker cache of all system-provided libraries"
Expand Down Expand Up @@ -69,6 +82,43 @@ def isDark():
def isLight():
return theme() == 'Light'

#def listener(callback: typing.Callable[[str], None]) -> None:
def listener(callback):
raise NotImplementedError()

def _listen_child():
"""
Run by a child process, install an observer and print theme on change
"""
import signal
signal.signal(signal.SIGINT, signal.SIG_IGN)

OBSERVED_KEY = "AppleInterfaceStyle"

class Observer(NSObject):
def observeValueForKeyPath_ofObject_change_context_(
self, path, object, changeDescription, context
):
result = changeDescription[NSKeyValueChangeNewKey]
try:
print(f"{'Light' if result is None else result}", flush=True)
except IOError:
os._exit(1)

observer = Observer.new() # Keep a reference alive after installing
defaults = NSUserDefaults.standardUserDefaults()
defaults.addObserver_forKeyPath_options_context_(
observer, OBSERVED_KEY, NSKeyValueObservingOptionNew, 0
)

AppHelper.runConsoleEventLoop()


def listener(callback: Callable[[str], None]) -> None:
if not _can_listen:
raise NotImplementedError()
with subprocess.Popen(
(sys.executable, "-c", "import _mac_detect as m; m._listen_child()"),
stdout=subprocess.PIPE,
universal_newlines=True,
cwd=Path(__file__).parent,
) as p:
for line in p.stdout:
callback(line.strip())
6 changes: 4 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,14 @@ build-backend = "setuptools.build_meta"
name = "darkdetect"
description = "Detect OS Dark Mode from Python"
readme = "README.md"
requires-python = ">=3"
requires-python = ">=3.6"
dynamic = [ "version" ]
classifiers = [
"License :: OSI Approved :: BSD License",
"Operating System :: MacOS :: MacOS X",
"Operating System :: Microsoft :: Windows :: Windows 10",
"Operating System :: POSIX :: Linux",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
Expand All @@ -35,6 +34,9 @@ email = "asottile@gmail.com"
homepage = "http://github.com/albertosottile/darkdetect"
download = "http://github.com/albertosottile/darkdetect/releases"

[project.optional-dependencies]
macos-listener = [ "pyobjc-framework-Cocoa; platform_system == 'Darwin'" ]

# Tool Config

[tool.setuptools]
Expand Down