예제 #1
0
##########################################################################
# System/Library/Frameworks/WebKit.framework
##########################################################################

from rubicon.objc import ObjCClass
from rubicon.objc.runtime import load_library

######################################################################
webkit = load_library('WebKit')
######################################################################

######################################################################
# WebView.h
WebView = ObjCClass('WebView')

######################################################################
# WKWebView.h
WKWebView = ObjCClass('WKWebView')
예제 #2
0
from typing import Optional, cast

# external imports
from packaging.version import Version
from rubicon.objc import NSObject, ObjCClass, objc_method, py_from_ns  # type: ignore
from rubicon.objc.runtime import load_library, objc_id, objc_block  # type: ignore

# local imports
from .base import Notification, DesktopNotifierBase, AuthorisationError, Urgency
from .macos_support import macos_version

__all__ = ["CocoaNotificationCenter"]

logger = logging.getLogger(__name__)

foundation = load_library("Foundation")
uns = load_library("UserNotifications")

UNUserNotificationCenter = ObjCClass("UNUserNotificationCenter")
UNMutableNotificationContent = ObjCClass("UNMutableNotificationContent")
UNNotificationRequest = ObjCClass("UNNotificationRequest")
UNNotificationAction = ObjCClass("UNNotificationAction")
UNTextInputNotificationAction = ObjCClass("UNTextInputNotificationAction")
UNNotificationCategory = ObjCClass("UNNotificationCategory")
UNNotificationSound = ObjCClass("UNNotificationSound")
UNNotificationAttachment = ObjCClass("UNNotificationAttachment")

NSURL = ObjCClass("NSURL")
NSSet = ObjCClass("NSSet")

# UserNotifications.h
import cmd
import os
import pickle
import site
import subprocess
import sys
import tempfile

site.addsitedir(
    os.path.join(os.path.dirname(os.path.realpath(__file__)), 'third_party'))
from rubicon.objc import ObjCClass
from rubicon.objc import objc_const
from rubicon.objc.eventloop import EventLoopPolicy
from rubicon.objc.runtime import load_library

AppKit = load_library('AppKit')
CoreServices = load_library('CoreServices')
NSURL = ObjCClass('NSURL')  # Framework: Foundation
NSPasteboard = ObjCClass('NSPasteboard')  # Framework: AppKit
kUTTypeUTF8PlainText = objc_const(CoreServices, 'kUTTypeUTF8PlainText')

parser = argparse.ArgumentParser(
    description='write_to_pasteboard: write to the pasteboard')
parser.add_argument('-i',
                    '--interactive',
                    action='store_true',
                    help='starts an interactive prompt')
parser.add_argument('-p', '--pasteboard', help='pasteboard to write to')

args = None
loop = None
예제 #4
0
def get_ac_state() -> ACState:
    """
    Checks if the current device has AC power or is running on battery.

    :returns: ``True`` if the device has AC power, ``False`` otherwise.
    """

    if platform.system() == "Darwin":

        from ctypes import c_double
        from rubicon.objc.runtime import load_library

        iokit = load_library("IOKit")
        kIOPSTimeRemainingUnlimited = -2.0

        iokit.IOPSGetTimeRemainingEstimate.restype = c_double

        remaining_time = iokit.IOPSGetTimeRemainingEstimate()

        if remaining_time == kIOPSTimeRemainingUnlimited:
            return ACState.Connected
        else:
            return ACState.Disconnected

    elif platform.system() == "Linux":

        # taken from https://github.com/giampaolo/psutil

        supply_entry = list(os.scandir(LINUX_POWER_SUPPLY_PATH))

        ac_paths = [
            Path(entry.path) for entry in supply_entry
            if entry.name.startswith("A") or "ac" in entry.name.lower()
        ]

        battery_paths = [
            Path(entry.path) for entry in supply_entry
            if entry.name.startswith("B") or "battery" in entry.name.lower()
        ]

        online = multi_cat(*iter(path / "online" for path in ac_paths))

        if online is not None:
            if online == 1:
                return ACState.Connected
            else:
                return ACState.Disconnected

        elif len(battery_paths) > 0:

            # Get the first available battery. Usually this is "BAT0", except
            # some rare exceptions:
            # https://github.com/giampaolo/psutil/issues/1238
            bat0 = sorted(battery_paths)[0]

            try:
                status = (bat0 / "status").read_text().strip().lower()
            except OSError:
                status = ""

            if status == "discharging":
                return ACState.Disconnected
            elif status in ("charging", "full"):
                return ACState.Connected

    return ACState.Undetermined
예제 #5
0
from rubicon.objc import *
from rubicon.objc.runtime import load_library, send_super

load_library('UIKit')
load_library('SceneKit')
load_library('ARKit')

ARSessionObserver = ObjCProtocol('ARSessionObserver')

ARSession = ObjCClass('ARSession')
ARPositionalTrackingConfiguration = ObjCClass(
    'ARPositionalTrackingConfiguration')
UIApplication = ObjCClass('UIApplication')

ARSessionRunOptionResetTracking = (1 << 0)

ARTrackingStateNotAvailable = 0
ARTrackingStateLimited = 1
ARTrackingStateNormal = 2

ARTrackingStateReasonNone = 0
ARTrackingStateReasonInitializing = 1
ARTrackingStateReasonRelocalizing = 2
ARTrackingStateReasonExcessiveMotion = 3
ARTrackingStateReasonInsufficientFeatures = 4


class ARSessionHandler(NSObject, protocols=[ARSessionObserver]):
    @objc_method
    def init(self):
        self = ObjCInstance(send_super(__class__, self, 'init'))
예제 #6
0
import platform
from ctypes import Structure, c_void_p
from enum import Enum, IntEnum

from rubicon.objc import CGFloat, ObjCClass, objc_const
from rubicon.objc.api import NSString
from rubicon.objc.runtime import load_library

from travertino.colors import (BLACK, BLUE, BROWN, CYAN, DARKGRAY, GRAY, GREEN,
                               LIGHTGRAY, MAGENTA, ORANGE, PURPLE, RED, WHITE,
                               YELLOW)

from toga.constants import CENTER, JUSTIFY, LEFT, RIGHT

######################################################################
appkit = load_library('AppKit')
######################################################################

######################################################################
# NSAffineTransform.h
NSAffineTransform = ObjCClass('NSAffineTransform')

######################################################################
# NSAlert.h
NSAlert = ObjCClass('NSAlert')


class NSAlertStyle(Enum):
    Warning = 0  # NSAlertStyleWarning
    Informational = 1  # NSAlertStyleInformational
    Critical = 2  # NSAlertStyleCritical
예제 #7
0
    POINTER,
    Structure,
    c_int,
    c_int32,
    c_size_t,
    c_uint32,
    c_void_p,
    c_wchar_p,
)

from rubicon.objc import CGFloat, CGRect
from rubicon.objc.types import register_preferred_encoding
from rubicon.objc.runtime import load_library

######################################################################
core_graphics = load_library('CoreGraphics')
######################################################################

######################################################################
# CGAffineTransform.h


class CGAffineTransform(Structure):
    _fields_ = [
        ("a", CGFloat),
        ("b", CGFloat),
        ("c", CGFloat),
        ("d", CGFloat),
        ("tx", CGFloat),
        ("ty", CGFloat),
    ]
예제 #8
0
import logging
from typing import Optional, cast

# external imports
from rubicon.objc import NSObject, ObjCClass, objc_method, py_from_ns  # type: ignore
from rubicon.objc.runtime import load_library  # type: ignore

# local imports
from .base import Notification, DesktopNotifierBase

__all__ = ["CocoaNotificationCenterLegacy"]

logger = logging.getLogger(__name__)
macos_version, *_ = platform.mac_ver()

foundation = load_library("Foundation")

NSUserNotification = ObjCClass("NSUserNotification")
NSUserNotificationCenter = ObjCClass("NSUserNotificationCenter")
NSDate = ObjCClass("NSDate")

NSUserNotificationActivationTypeContentsClicked = 1
NSUserNotificationActivationTypeActionButtonClicked = 2
NSUserNotificationActivationTypeAdditionalActionClicked = 4

NSUserNotificationDefaultSoundName = "DefaultSoundName"


class NotificationCenterDelegate(NSObject):  # type: ignore
    """Delegate to handle user interactions with notifications"""
    @objc_method
예제 #9
0
##########################################################################
# System/Library/Frameworks/Foundation.framework
##########################################################################
from ctypes import c_bool

from rubicon.objc import NSPoint, NSRect, ObjCClass
from rubicon.objc.runtime import load_library

######################################################################
foundation = load_library('Foundation')
######################################################################

foundation.NSMouseInRect.restype = c_bool
foundation.NSMouseInRect.argtypes = [NSPoint, NSRect, c_bool]

######################################################################
# NSBundle.h
NSBundle = ObjCClass('NSBundle')
NSBundle.declare_class_property('mainBundle')
NSBundle.declare_property('bundlePath')

######################################################################
# NSFileWrapper.h
NSFileWrapper = ObjCClass('NSFileWrapper')

######################################################################
# NSNotification.h
NSNotificationCenter = ObjCClass('NSNotificationCenter')

######################################################################
NSNotification = ObjCClass('NSNotification')
예제 #10
0
import faulthandler
import os

from rubicon.objc.runtime import load_library

try:
    import platform
    OSX_VERSION = tuple(int(v) for v in platform.mac_ver()[0].split('.')[:2])
except Exception:
    OSX_VERSION = None

try:
    rubiconharness = load_library(
        os.path.abspath('tests/objc/build/librubiconharness.dylib'))
except ValueError:
    raise ValueError(
        "Couldn't load Rubicon test harness library. Did you remember to run make?"
    )

faulthandler.enable()
예제 #11
0
import faulthandler

from rubicon.objc.runtime import load_library

try:
    import platform
    OSX_VERSION = tuple(int(v) for v in platform.mac_ver()[0].split('.')[:2])
except Exception:
    OSX_VERSION = None

try:
    rubiconharness = load_library('rubiconharness')
except ValueError:
    raise ValueError(
        "Couldn't load Rubicon test harness library. Have you set DYLD_LIBRARY_PATH?"
    )

faulthandler.enable()