Skip to content

Commit

Permalink
fix: fixed import in main, moved macos permission prompt into seperat…
Browse files Browse the repository at this point in the history
…e file
  • Loading branch information
ErikBjare committed Jun 6, 2021
1 parent b8eb8e3 commit c683671
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 46 deletions.
34 changes: 0 additions & 34 deletions aw_watcher_window/macos_jxa.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,40 +54,6 @@ def getInfo() -> Dict[str, str]:
return json.loads(result.stringValue())


def background_ensure_permissions() -> None:
from multiprocessing import Process

permission_process = Process(target=ensure_permissions, args=(()))
permission_process.start()
return


def ensure_permissions() -> None:
from ApplicationServices import AXIsProcessTrusted
from AppKit import NSAlert, NSAlertFirstButtonReturn, NSWorkspace, NSURL

accessibility_permissions = AXIsProcessTrusted()
if not accessibility_permissions:
title = "Missing accessibility permissions"
info = "To let ActivityWatch capture window titles grant it accessibility permissions. \n If you've already given ActivityWatch accessibility permissions and are still seeing this dialog, try removing and re-adding them."

alert = NSAlert.new()
alert.setMessageText_(title)
alert.setInformativeText_(info)

ok_button = alert.addButtonWithTitle_("Open accessibility settings")

alert.addButtonWithTitle_("Close")
choice = alert.runModal()
print(choice)
if choice == NSAlertFirstButtonReturn:
NSWorkspace.sharedWorkspace().openURL_(
NSURL.URLWithString_(
"x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility"
)
)


if __name__ == "__main__":
print(getInfo())
print("Waiting 5 seconds...")
Expand Down
37 changes: 37 additions & 0 deletions aw_watcher_window/macos_permissions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import logging

logger = logging.getLogger(__name__)


def background_ensure_permissions() -> None:
from multiprocessing import Process

permission_process = Process(target=ensure_permissions, args=(()))
permission_process.start()
return


def ensure_permissions() -> None:
from ApplicationServices import AXIsProcessTrusted
from AppKit import NSAlert, NSAlertFirstButtonReturn, NSWorkspace, NSURL

accessibility_permissions = AXIsProcessTrusted()
if not accessibility_permissions:
logger.info("No accessibility permissions, prompting user")
title = "Missing accessibility permissions"
info = "To let ActivityWatch capture window titles grant it accessibility permissions. \n If you've already given ActivityWatch accessibility permissions and are still seeing this dialog, try removing and re-adding them."

alert = NSAlert.new()
alert.setMessageText_(title)
alert.setInformativeText_(info)

ok_button = alert.addButtonWithTitle_("Open accessibility settings")

alert.addButtonWithTitle_("Close")
choice = alert.runModal()
if choice == NSAlertFirstButtonReturn:
NSWorkspace.sharedWorkspace().openURL_(
NSURL.URLWithString_(
"x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility"
)
)
43 changes: 31 additions & 12 deletions aw_watcher_window/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,26 +11,35 @@

from .lib import get_current_window
from .config import parse_args
from .macos_permissions import background_ensure_permissions


logger = logging.getLogger(__name__)

# run with LOG_LEVEL=DEBUG
log_level = os.environ.get('LOG_LEVEL')
log_level = os.environ.get("LOG_LEVEL")
if log_level:
logger.setLevel(logging.__getattribute__(log_level.upper()))


def main():
args = parse_args()

if sys.platform.startswith("linux") and ("DISPLAY" not in os.environ or not os.environ["DISPLAY"]):
if sys.platform.startswith("linux") and (
"DISPLAY" not in os.environ or not os.environ["DISPLAY"]
):
raise Exception("DISPLAY environment variable not set")

setup_logging(name="aw-watcher-window", testing=args.testing, verbose=args.verbose,
log_stderr=True, log_file=True)
setup_logging(
name="aw-watcher-window",
testing=args.testing,
verbose=args.verbose,
log_stderr=True,
log_file=True,
)

if sys.platform == "darwin":
from . import macos
macos.background_ensure_permissions()
background_ensure_permissions()

client = ActivityWatchClient("aw-watcher-window", testing=args.testing)

Expand All @@ -43,7 +52,14 @@ def main():

sleep(1) # wait for server to start
with client:
heartbeat_loop(client, bucket_id, poll_time=args.poll_time, strategy=args.strategy, exclude_title=args.exclude_title)
heartbeat_loop(
client,
bucket_id,
poll_time=args.poll_time,
strategy=args.strategy,
exclude_title=args.exclude_title,
)


def heartbeat_loop(client, bucket_id, poll_time, strategy, exclude_title=False):
while True:
Expand All @@ -55,23 +71,26 @@ def heartbeat_loop(client, bucket_id, poll_time, strategy, exclude_title=False):
current_window = get_current_window(strategy)
logger.debug(current_window)
except Exception as e:
logger.error("Exception thrown while trying to get active window: {}".format(e))
logger.error(
"Exception thrown while trying to get active window: {}".format(e)
)
traceback.print_exc()
current_window = {"app": "unknown", "title": "unknown"}

now = datetime.now(timezone.utc)
if current_window is None:
logger.debug('Unable to fetch window, trying again on next poll')
logger.debug("Unable to fetch window, trying again on next poll")
else:
if exclude_title:
current_window["title"] = "excluded"
current_window["title"] = "excluded"

current_window_event = Event(timestamp=now, data=current_window)

# Set pulsetime to 1 second more than the poll_time
# This since the loop takes more time than poll_time
# due to sleep(poll_time).
client.heartbeat(bucket_id, current_window_event,
pulsetime=poll_time + 1.0, queued=True)
client.heartbeat(
bucket_id, current_window_event, pulsetime=poll_time + 1.0, queued=True
)

sleep(poll_time)

0 comments on commit c683671

Please sign in to comment.