Exemplo n.º 1
0
    def run(self, **options):
        """Performs various setup tasks including creating the underlying Objective-C application, starting the timers,
        and registering callback functions for click events. Then starts the application run loop.

        .. versionchanged:: 0.2.1
            Accepts `debug` keyword argument.

        :param debug: determines if application should log information useful for debugging. Same effect as calling
                      :func:`rumps.debug_mode`.

        """
        dont_change = object()
        debug = options.get('debug', dont_change)
        if debug is not dont_change:
            debug_mode(debug)

        nsapplication = NSApplication.sharedApplication()
        nsapplication.activateIgnoringOtherApps_(True)  # NSAlerts in front
        self._nsapp = NSApp.alloc().init()
        self._nsapp._app = self.__dict__  # allow for dynamic modification based on this App instance
        nsapplication.setDelegate_(self._nsapp)
        if _NOTIFICATIONS:
            NSUserNotificationCenter.defaultUserNotificationCenter().setDelegate_(self._nsapp)

        setattr(App, '*app_instance', self)  # class level ref to running instance (for passing self to App subclasses)
        t = b = None
        for t in getattr(timer, '*timers', []):
            t.start()
        for b in getattr(clicked, '*buttons', []):
            b(self)  # we waited on registering clicks so we could pass self to access _menu attribute
        del t, b

        self._nsapp.initializeStatusBar()

        AppHelper.runEventLoop()
Exemplo n.º 2
0
            def _pyobjc_notify(message, title=None, subtitle=None, appIcon=None, contentImage=None, open_URL=None, delay=0, sound=False):

                swizzle(objc.lookUpClass('NSBundle'),
                        b'bundleIdentifier',
                        swizzled_bundleIdentifier)
                notification = NSUserNotification.alloc().init()
                notification.setInformativeText_(message)
                if title:
                    notification.setTitle_(title)
                if subtitle:
                    notification.setSubtitle_(subtitle)
                if appIcon:
                    url = NSURL.alloc().initWithString_(appIcon)
                    image = NSImage.alloc().initWithContentsOfURL_(url)
                    notification.set_identityImage_(image)
                if contentImage:
                    url = NSURL.alloc().initWithString_(contentImage)
                    image = NSImage.alloc().initWithContentsOfURL_(url)
                    notification.setContentImage_(image)

                if sound:
                    notification.setSoundName_(
                        "NSUserNotificationDefaultSoundName")
                notification.setDeliveryDate_(
                    NSDate.dateWithTimeInterval_sinceDate_(delay, NSDate.date()))
                NSUserNotificationCenter.defaultUserNotificationCenter().scheduleNotification_(
                    notification)
Exemplo n.º 3
0
def notification(title, subtitle, message, data=None, sound=True, image=None):
    """Send a notification to Notification Center (Mac OS X 10.8+). If running on a version of Mac OS X that does not
    support notifications, a ``RuntimeError`` will be raised. Apple says,

        "The userInfo content must be of reasonable serialized size (less than 1k) or an exception will be thrown."

    So don't do that!

    :param title: text in a larger font.
    :param subtitle: text in a smaller font below the `title`.
    :param message: text representing the body of the notification below the `subtitle`.
    :param data: will be passed to the application's "notification center" (see :func:`rumps.notifications`) when this
                 notification is clicked.
    :param sound: whether the notification should make a noise when it arrives.
    """
    if not _NOTIFICATIONS:
        raise RuntimeError('Mac OS X 10.8+ is required to send notifications')
    if data is not None and not isinstance(data, Mapping):
        raise TypeError('notification data must be a mapping')
    _require_string_or_none(title, subtitle, message)
    notification = NSUserNotification.alloc().init()
    notification.setTitle_(title)
    notification.setSubtitle_(subtitle)
    notification.setInformativeText_(message)
    notification.setUserInfo_({} if data is None else data)
    if sound:
        notification.setSoundName_("NSUserNotificationDefaultSoundName")
    if image != None:
        notification.setContentImage_(image)
    notification.setDeliveryDate_(NSDate.dateWithTimeInterval_sinceDate_(0, NSDate.date()))
    NSUserNotificationCenter.defaultUserNotificationCenter().scheduleNotification_(notification)
Exemplo n.º 4
0
    def run(self, **options):
        """Performs various setup tasks including creating the underlying Objective-C application, starting the timers,
        and registering callback functions for click events. Then starts the application run loop.

        .. versionchanged:: 0.2.1
            Accepts `debug` keyword argument.

        :param debug: determines if application should log information useful for debugging. Same effect as calling
                      :func:`rumps.debug_mode`.

        """
        dont_change = object()
        debug = options.get('debug', dont_change)
        if debug is not dont_change:
            debug_mode(debug)

        nsapplication = NSApplication.sharedApplication()
        nsapplication.activateIgnoringOtherApps_(True)  # NSAlerts in front
        self._nsapp = NSApp.alloc().init()
        self._nsapp._app = self.__dict__  # allow for dynamic modification based on this App instance
        nsapplication.setDelegate_(self._nsapp)
        if _NOTIFICATIONS:
            NSUserNotificationCenter.defaultUserNotificationCenter().setDelegate_(self._nsapp)

        setattr(App, '*app_instance', self)  # class level ref to running instance (for passing self to App subclasses)
        t = b = None
        for t in getattr(timer, '*timers', []):
            t.start()
        for b in getattr(clicked, '*buttons', []):
            b(self)  # we waited on registering clicks so we could pass self to access _menu attribute
        del t, b

        self._nsapp.initializeStatusBar()

        AppHelper.runEventLoop()
Exemplo n.º 5
0
def send_OS_X_notify(title, content, img_path):
    '''发送Mac桌面通知'''
    def swizzle(cls, SEL, func):
        old_IMP = cls.instanceMethodForSelector_(SEL)

        def wrapper(self, *args, **kwargs):
            return func(self, old_IMP, *args, **kwargs)
        new_IMP = objc.selector(wrapper, selector=old_IMP.selector,
                                signature=old_IMP.signature)
        objc.classAddMethod(cls, SEL, new_IMP)

    def swizzled_bundleIdentifier(self, original):
        # Use iTunes icon for notification
        return 'com.apple.itunes'

    swizzle(objc.lookUpClass('NSBundle'),
            b'bundleIdentifier',
            swizzled_bundleIdentifier)
    notification = NSUserNotification.alloc().init()
    notification.setInformativeText_('')
    notification.setTitle_(title.decode('utf-8'))
    notification.setSubtitle_(content.decode('utf-8'))

    notification.setInformativeText_('')
    notification.setUserInfo_({})
    if img_path is not None:
        image = NSImage.alloc().initWithContentsOfFile_(img_path)
        # notification.setContentImage_(image)
        notification.set_identityImage_(image)
    notification.setDeliveryDate_(
            NSDate.dateWithTimeInterval_sinceDate_(0, NSDate.date())
    )
    NSUserNotificationCenter.defaultUserNotificationCenter().\
        scheduleNotification_(notification)
Exemplo n.º 6
0
    def run(self):
        """
        Perform various setup tasks then start application run loop.
        """
        nsapplication = NSApplication.sharedApplication()
        nsapplication.activateIgnoringOtherApps_(True)  # NSAlerts in front
        self._nsapp = NSApp.alloc().init()
        self._nsapp._app = self.__dict__  # allow for dynamic modification based on this App instance
        self._nsapp.initializeStatusBar()
        nsapplication.setDelegate_(self._nsapp)
        NSUserNotificationCenter.defaultUserNotificationCenter().setDelegate_(
            self._nsapp)

        setattr(
            App, '*app_instance', self
        )  # class level ref to running instance (for passing self to App subclasses)
        t = b = None
        for t in getattr(timer, '*timers', []):
            t.start()
        for b in getattr(clicked, '*buttons', []):
            b(
                self
            )  # we waited on registering clicks so we could pass self to access _menu attribute
        del t, b

        AppHelper.runEventLoop()
        sys.exit(0)
Exemplo n.º 7
0
def send_OS_X_notify(title, content, img_path):
    '''发送Mac桌面通知'''
    def swizzle(cls, SEL, func):
        old_IMP = cls.instanceMethodForSelector_(SEL)

        def wrapper(self, *args, **kwargs):
            return func(self, old_IMP, *args, **kwargs)

        new_IMP = objc.selector(wrapper,
                                selector=old_IMP.selector,
                                signature=old_IMP.signature)
        objc.classAddMethod(cls, SEL, new_IMP)

    def swizzled_bundleIdentifier(self, original):
        # Use iTunes icon for notification
        return 'com.apple.itunes'

    swizzle(objc.lookUpClass('NSBundle'), b'bundleIdentifier',
            swizzled_bundleIdentifier)
    notification = NSUserNotification.alloc().init()
    notification.setInformativeText_('')
    notification.setTitle_(title.decode('utf-8'))
    notification.setSubtitle_(content.decode('utf-8'))

    notification.setInformativeText_('')
    notification.setUserInfo_({})
    if img_path is not None:
        image = NSImage.alloc().initWithContentsOfFile_(img_path)
        # notification.setContentImage_(image)
        notification.set_identityImage_(image)
    notification.setDeliveryDate_(
        NSDate.dateWithTimeInterval_sinceDate_(0, NSDate.date()))
    NSUserNotificationCenter.defaultUserNotificationCenter().\
        scheduleNotification_(notification)
Exemplo n.º 8
0
        def notify(self, title, subtitle, text):
            """Create a user notification and display it."""

             # if appImage:
             #    source_img = AppKit.NSImage.alloc().initByReferencingFile_(appImage)
             #    notification.set_identityImage_(source_img)
             # if contentImage:
             #    source_img = AppKit.NSImage.alloc().initBy
            #     notification.setContentImage_(source_img)

            notification = NSUserNotification.alloc().init()
            notification.setTitle_(str(title))
            notification.setSubtitle_(str(subtitle))
            notification.setInformativeText_(str(text))
            notification.setSoundName_("NSUserNotificationDefaultSoundName")

            # notification.set_showsButtons_(True)
            # notification.setHasActionButton_(True)
            # notification.setHasReplyButton_ (True) # this will allow the user to enter text to "reply"
            # notification.setActionButtonTitle_("View")
            # notification.setUserInfo_({"action":"open_url", "value":url})

            NSUserNotificationCenter.defaultUserNotificationCenter().setDelegate_(self)
            NSUserNotificationCenter.defaultUserNotificationCenter().scheduleNotification_(notification)

            # Note that the notification center saves a *copy* of our object.
            AppHelper.runConsoleEventLoop()
def notify(title, subtitle, text):
    notification = NSUserNotification.alloc().init()
    notification.setTitle_(str(title))
    notification.setSubtitle_(str(subtitle))
    notification.setInformativeText_(str(text))
    notification.setSoundName_("NSUserNotificationDefaultSoundName")
    NSUserNotificationCenter.defaultUserNotificationCenter().scheduleNotification_(notification)
Exemplo n.º 10
0
def notify(title, subtitle, text):
    notification = NSUserNotification.alloc().init()
    notification.setTitle_(str(title))
    notification.setSubtitle_(str(subtitle))
    notification.setInformativeText_(str(text))
    notification.setSoundName_("NSUserNotificationDefaultSoundName")
    NSUserNotificationCenter.defaultUserNotificationCenter().scheduleNotification_(notification)
Exemplo n.º 11
0
def notification(title, subtitle, message, data=None, sound=True):
    """Send a notification to Notification Center (Mac OS X 10.8+). If running on a version of Mac OS X that does not
    support notifications, a ``RuntimeError`` will be raised. Apple says,

        "The userInfo content must be of reasonable serialized size (less than 1k) or an exception will be thrown."

    So don't do that!

    :param title: text in a larger font.
    :param subtitle: text in a smaller font below the `title`.
    :param message: text representing the body of the notification below the `subtitle`.
    :param data: will be passed to the application's "notification center" (see :func:`rumps.notifications`) when this
                 notification is clicked.
    :param sound: whether the notification should make a noise when it arrives.
    """
    if not _NOTIFICATIONS:
        raise RuntimeError('Mac OS X 10.8+ is required to send notifications')
    if data is not None and not isinstance(data, Mapping):
        raise TypeError('notification data must be a mapping')
    _require_string_or_none(title, subtitle, message)
    notification = NSUserNotification.alloc().init()
    notification.setTitle_(title)
    notification.setSubtitle_(subtitle)
    notification.setInformativeText_(message)
    notification.setUserInfo_({} if data is None else data)
    if sound:
        notification.setSoundName_("NSUserNotificationDefaultSoundName")
    notification.setDeliveryDate_(
        NSDate.dateWithTimeInterval_sinceDate_(0, NSDate.date()))
    NSUserNotificationCenter.defaultUserNotificationCenter(
    ).scheduleNotification_(notification)
Exemplo n.º 12
0
            def _pyobjc_notify(message,
                               title=None,
                               subtitle=None,
                               appIcon=None,
                               contentImage=None,
                               open_URL=None,
                               delay=0,
                               sound=False):

                swizzle(objc.lookUpClass('NSBundle'), b'bundleIdentifier',
                        swizzled_bundleIdentifier)
                notification = NSUserNotification.alloc().init()
                notification.setInformativeText_(message)
                if title:
                    notification.setTitle_(title)
                if subtitle:
                    notification.setSubtitle_(subtitle)
                if appIcon:
                    url = NSURL.alloc().initWithString_(appIcon)
                    image = NSImage.alloc().initWithContentsOfURL_(url)
                    notification.set_identityImage_(image)
                if contentImage:
                    url = NSURL.alloc().initWithString_(contentImage)
                    image = NSImage.alloc().initWithContentsOfURL_(url)
                    notification.setContentImage_(image)

                if sound:
                    notification.setSoundName_(
                        "NSUserNotificationDefaultSoundName")
                notification.setDeliveryDate_(
                    NSDate.dateWithTimeInterval_sinceDate_(
                        delay, NSDate.date()))
                NSUserNotificationCenter.defaultUserNotificationCenter(
                ).scheduleNotification_(notification)
Exemplo n.º 13
0
 def notify(self, title, subtitle, text, url):
     notification = NSUserNotification.alloc().init()
     notification.setTitle_(str(title))
     notification.setSubtitle_(str(subtitle))
     notification.setInformativeText_(str(text))
     notification.setSoundName_("NSUserNotificationDefaultSoundName")
     notification.setUserInfo_({"action":"open_url", "value":url})
     NSUserNotificationCenter.defaultUserNotificationCenter().setDelegate_(self)
     NSUserNotificationCenter.defaultUserNotificationCenter().scheduleNotification_(notification)
Exemplo n.º 14
0
 def notify(self, title, subtitle, text, url):
     notification = NSUserNotification.alloc().init()
     notification.setTitle_(str(title))
     notification.setSubtitle_(str(subtitle))
     notification.setInformativeText_(str(text))
     notification.setSoundName_("NSUserNotificationDefaultSoundName")
     notification.setUserInfo_({"action": "open_url", "value": url})
     NSUserNotificationCenter.defaultUserNotificationCenter().setDelegate_(self)
     NSUserNotificationCenter.defaultUserNotificationCenter().scheduleNotification_(notification)
Exemplo n.º 15
0
 def notify(self, title, subtitle, text):
     notification = NSUserNotification.alloc().init()
     notification.setTitle_(title)
     notification.setSubtitle_(subtitle)
     notification.setInformativeText_(text)
     NSUserNotificationCenter.defaultUserNotificationCenter().\
         setDelegate_(self)
     NSUserNotificationCenter.defaultUserNotificationCenter().\
         scheduleNotification_(notification)
Exemplo n.º 16
0
    def alert(self, title, subtitle, message, delay=0, sound=False, userInfo={}):
        self.notification.setTitle_(title)
        self.notification.setSubtitle_(subtitle)
        self.notification.setInformativeText_(message)
        self.notification.setDeliveryDate_(NSDate.dateWithTimeInterval_sinceDate_(delay, NSDate.date()))
#        self.notification.setUserInfo_(userInfo)
        if sound:
            self.notification.setSoundName_("NSUserNotificationDefaultSoundName")
        NSUserNotificationCenter.defaultUserNotificationCenter().scheduleNotification_(self.notification)
Exemplo n.º 17
0
def notify(title, subtitle, text, fileType = None):
    notification = NSUserNotification.alloc().init()
    notification.setTitle_(str(title))
    notification.setSubtitle_(str(subtitle))
    notification.setInformativeText_(str(text))
    notification.setSoundName_("NSUserNotificationDefaultSoundName")
    if fileType is not None:
        file_icon = NSWorkspace.sharedWorkspace().iconForFileType_(fileType)
        notification.setContentImage_(file_icon)
    NSUserNotificationCenter.defaultUserNotificationCenter().scheduleNotification_(notification)
Exemplo n.º 18
0
def notify(title, subtitle, text, fileType=None):
    notification = NSUserNotification.alloc().init()
    notification.setTitle_(str(title))
    notification.setSubtitle_(str(subtitle))
    notification.setInformativeText_(str(text))
    notification.setSoundName_("NSUserNotificationDefaultSoundName")
    if fileType is not None:
        file_icon = NSWorkspace.sharedWorkspace().iconForFileType_(fileType)
        notification.setContentImage_(file_icon)
    NSUserNotificationCenter.defaultUserNotificationCenter(
    ).scheduleNotification_(notification)
Exemplo n.º 19
0
	def writeFont_error_(self, font, error):
		"""
		EXPORT dialog

		This method is called when the Next button is pressed in the Export dialog,
		and should ask the user for the place to store the font (not necessarily, you could choose to hard-wire the destination in the code).

		Parameters:
		- font: The font object to export
		- error: PyObjc-Requirement. It is required here in order to return the error object upon export failure. Ignore its existence here.

		return (True, None) if the export was successful
		return (False, NSError) if the export failed
		"""
		try:

			returnStatus, returnMessage = [False, 'export() is not implemented in the plugin.']
			if hasattr(self, 'export'):
				returnStatus, returnMessage = self.export(font)

			# Export successful
			# Change the condition (True) to your own assessment on whether or not the export succeeded
			if returnStatus:
				# Use Mac Notification Center
				notification = NSUserNotification.alloc().init()
				notification.setTitle_(self.title())
				notification.setInformativeText_(returnMessage)
				NSUserNotificationCenter.defaultUserNotificationCenter().scheduleNotification_(notification)

				return (True, None)

			# Export failed, give reason
			else:
				error = NSError.errorWithDomain_code_userInfo_(self.title(), -57, {
					NSLocalizedDescriptionKey: NSLocalizedString('Export failed', None),
					NSLocalizedRecoverySuggestionErrorKey: returnMessage
				})
				return (False, error)

		# Python exception, return error message
		except Exception as e:
			self.logError(traceback.format_exc())
			error = NSError.errorWithDomain_code_userInfo_(self.title(), -57, {
				NSLocalizedDescriptionKey: NSLocalizedString('Python exception', None),
				NSLocalizedRecoverySuggestionErrorKey: str(e) + '\nCheck Macro window output.'
			})
			return (False, error)
		return True
Exemplo n.º 20
0
def notification(title, subtitle, message, data=None, sound=True):
    """
    Notification sender. Apple says, "The userInfo content must be of reasonable serialized size (less than 1k) or an
    exception will be thrown." So don't do that!
    """
    if data is not None and not isinstance(data, Mapping):
        raise TypeError('notification data must be a mapping')
    notification = NSUserNotification.alloc().init()
    notification.setTitle_(title)
    notification.setSubtitle_(subtitle)
    notification.setInformativeText_(message)
    notification.setUserInfo_({} if data is None else data)
    if sound:
        notification.setSoundName_("NSUserNotificationDefaultSoundName")
    notification.setDeliveryDate_(NSDate.dateWithTimeInterval_sinceDate_(0, NSDate.date()))
    NSUserNotificationCenter.defaultUserNotificationCenter().scheduleNotification_(notification)
Exemplo n.º 21
0
def notify(text):

    notification = NSUserNotification.alloc().init()
    notification.setTitle_('Clipbox')
    notification.setInformativeText_(text)
    center = NSUserNotificationCenter.defaultUserNotificationCenter()
    center.deliverNotification_(notification)
Exemplo n.º 22
0
Arquivo: gui.py Projeto: dochench/xpra
 def __init__(self, closed_cb=None, action_cb=None):
     super().__init__(closed_cb, action_cb)
     self.gtk_notifier = None
     self.gtk_notifications = set()
     self.notifications = {}
     self.notification_center = NSUserNotificationCenter.defaultUserNotificationCenter()
     assert self.notification_center
Exemplo n.º 23
0
def notification(title, subtitle, message, data=None, sound=True):
    """
    Notification sender. Apple says, "The userInfo content must be of reasonable serialized size (less than 1k) or an
    exception will be thrown." So don't do that!
    """
    if data is not None and not isinstance(data, Mapping):
        raise TypeError('notification data must be a mapping')
    notification = NSUserNotification.alloc().init()
    notification.setTitle_(title)
    notification.setSubtitle_(subtitle)
    notification.setInformativeText_(message)
    notification.setUserInfo_({} if data is None else data)
    if sound:
        notification.setSoundName_("NSUserNotificationDefaultSoundName")
    notification.setDeliveryDate_(NSDate.dateWithTimeInterval_sinceDate_(0, NSDate.date()))
    NSUserNotificationCenter.defaultUserNotificationCenter().scheduleNotification_(notification)
Exemplo n.º 24
0
def notify(
    title: str,
    subtitle: str,
    info_text: str,
    delay: int = 0,
    sound: bool = False,
    user_info: Dict[str, str] = None,
) -> None:
    """ Python method to show a desktop notification on Mountain Lion. Where:
        title: Title of notification
        subtitle: Subtitle of notification
        info_text: Informative text of notification
        delay: Delay (in seconds) before showing the notification
        sound: Play the default notification sound
        userInfo: a dictionary that can be used to handle clicks in your
                  app's applicationDidFinishLaunching:aNotification method
    """
    notification = NSUserNotification.alloc().init()
    notification.setTitle_(title)
    notification.setSubtitle_(subtitle)
    notification.setInformativeText_(info_text)
    user_info = user_info or {}
    notification.setUserInfo_(user_info)
    if sound:
        notification.setSoundName_("NSUserNotificationDefaultSoundName")
    center = NSUserNotificationCenter.defaultUserNotificationCenter()
    if center is not None:
        center.deliverNotification_(notification)
Exemplo n.º 25
0
def notify(
    title: str,
    subtitle: str,
    info_text: str,
    delay: int = 0,
    sound: bool = False,
    user_info: Dict[str, str] = None,
) -> None:
    """ Python method to show a desktop notification on Mountain Lion. Where:
        title: Title of notification
        subtitle: Subtitle of notification
        info_text: Informative text of notification
        delay: Delay (in seconds) before showing the notification
        sound: Play the default notification sound
        userInfo: a dictionary that can be used to handle clicks in your
                  app's applicationDidFinishLaunching:aNotification method
    """
    notification = NSUserNotification.alloc().init()
    notification.setTitle_(title)
    notification.setSubtitle_(subtitle)
    notification.setInformativeText_(info_text)
    user_info = user_info or {}
    notification.setUserInfo_(user_info)
    if sound:
        notification.setSoundName_("NSUserNotificationDefaultSoundName")
    center = NSUserNotificationCenter.defaultUserNotificationCenter()
    if center is not None:
        center.deliverNotification_(notification)
Exemplo n.º 26
0
def notify(title, subtitle, text, bundleid=None):
    if bundleid:
        # fake our bundleid
        set_fake_bundleid(bundleid)

    # create a new user notification
    notification = NSUserNotification.alloc().init()
    notification.setTitle_(title)
    notification.setSubtitle_(subtitle)
    notification.setInformativeText_(text)

    # get the default User Notification Center
    nc = NSUserNotificationCenter.defaultUserNotificationCenter()

    # create a delegate object that implements our delegate methods
    my_delegate = NotificationCenterDelegate.alloc().init()
    nc.setDelegate_(my_delegate)

    # deliver the notification
    nc.deliverNotification_(notification)

    # keep running until the notification is activated
    while (my_delegate.keepRunning):
        NSRunLoop.currentRunLoop().runUntilDate_(
            NSDate.dateWithTimeIntervalSinceNow_(0.1))
Exemplo n.º 27
0
Arquivo: gui.py Projeto: chewi/xpra
def get_native_notifier_classes():
    v = []
    if NATIVE_NOTIFIER and NSUserNotificationCenter.defaultUserNotificationCenter(
    ):
        v.append(OSX_Notifier)
    notifylog("get_native_notifier_classes()=%s", v)
    return v
Exemplo n.º 28
0
def notify(title, subtitle, text, bundleid=None, url=None):
    if bundleid:
        # fake our bundleid
        set_fake_bundleid(bundleid)

    # create a new user notification
    notification = NSUserNotification.alloc().init()
    notification.setTitle_(title)
    notification.setSubtitle_(subtitle)
    notification.setInformativeText_(text)
    if url:
        userInfo = NSDictionary.dictionaryWithDictionary_({
            'action': u'open_url',
            'value': unicode(url)
        })
        notification.setUserInfo_(userInfo)
    notification.setHasActionButton_(True)
    notification.setActionButtonTitle_('Details')

    # get the default User Notification Center
    nc = NSUserNotificationCenter.defaultUserNotificationCenter()

    # create a delegate object that implements our delegate methods
    my_delegate = NotificationCenterDelegate.alloc().init()
    nc.setDelegate_(my_delegate)

    nc.removeAllDeliveredNotifications()
    # deliver the notification
    nc.deliverNotification_(notification)

    # keep running until the notification is activated
    while (my_delegate.keepRunning):
        NSRunLoop.currentRunLoop().runUntilDate_(
            NSDate.dateWithTimeIntervalSinceNow_(0.1))
Exemplo n.º 29
0
 def alert(content="", title="SECURITY ALERT", icon=None, sound=None):
     if content:
         log("[>] secalert[%s]: %s" % (title, content))
         notification = NSUserNotification.alloc().init()
         notification.setTitle_(title)
         notification.setInformativeText_(content)
         center = NSUserNotificationCenter.defaultUserNotificationCenter()
         center.deliverNotification_(notification)
Exemplo n.º 30
0
def send_OS_X_notify(title, content, img_path):
    '''发送Mac桌面通知'''
    try:
        from Foundation import (
            NSDate, NSUserNotification, NSUserNotificationCenter)
        from AppKit import NSImage
        import objc
    except ImportError:
        logger.info('failed to init OSX notify!')
        return

    def swizzle(cls, SEL, func):
        old_IMP = getattr(cls, SEL, None)

        if old_IMP is None:
            old_IMP = cls.instanceMethodForSelector_(SEL)

        def wrapper(self, *args, **kwargs):
            return func(self, old_IMP, *args, **kwargs)
        new_IMP = objc.selector(wrapper, selector=old_IMP.selector,
                                signature=old_IMP.signature)
        objc.classAddMethod(cls, SEL.encode(), new_IMP)

    def swizzled_bundleIdentifier(self, original):
        # Use iTunes icon for notification
        return 'com.apple.itunes'

    swizzle(objc.lookUpClass('NSBundle'),
            'bundleIdentifier',
            swizzled_bundleIdentifier)
    notification = NSUserNotification.alloc().init()

    notification.setTitle_(title)
    notification.setSubtitle_(content)
    notification.setInformativeText_('')
    notification.setUserInfo_({})
    if img_path is not None:
        image = NSImage.alloc().initWithContentsOfFile_(img_path)
        # notification.setContentImage_(image)
        notification.set_identityImage_(image)
    notification.setDeliveryDate_(
        NSDate.dateWithTimeInterval_sinceDate_(0, NSDate.date())
    )
    NSUserNotificationCenter.defaultUserNotificationCenter().\
        scheduleNotification_(notification)
    logger.info('send notify success!')
Exemplo n.º 31
0
def show_notification(title, message):
    notification = NSUserNotification.alloc().init()
    notification.setTitle_(title)
    notification.setInformativeText_(message)
    notification.setSoundName_(NSUserNotificationDefaultSoundName)

    center = NSUserNotificationCenter.defaultUserNotificationCenter()
    center.deliverNotification_(notification)
Exemplo n.º 32
0
 def notify(content="", title="Security Notification", icon=None, sound=None):
     if content:
         log("[>] secnotify[%s]: %s" % (title, content))
         notification = NSUserNotification.alloc().init()
         notification.setTitle_(title)
         notification.setInformativeText_(content)
         center = NSUserNotificationCenter.defaultUserNotificationCenter()
         center.deliverNotification_(notification)
Exemplo n.º 33
0
def notify(_title, _message, _sound = False):
    notification = NSUserNotification.alloc().init()
    notification.setTitle_(_title)
    notification.setInformativeText_(_message)
    if _sound == True:
        notification.setSoundName_(NSUserNotificationDefaultSoundName)

    center = NSUserNotificationCenter.defaultUserNotificationCenter()
    center.deliverNotification_(notification)
Exemplo n.º 34
0
 def sendNotification(self, title, body):
     """
     Notification pop-up when IP address change detected
     """
     notification = NSUserNotification.alloc().init()
     center = NSUserNotificationCenter.defaultUserNotificationCenter()
     notification.setTitle_(title)
     notification.setInformativeText_(body)
     center.deliverNotification_(notification)
Exemplo n.º 35
0
    def osx_message(self, title, message):
        # based on:
        # https://gist.github.com/baliw/4020619
        # http://stackoverflow.com/questions/17651017/python-post-osx-notification
        notification = NSUserNotification.alloc().init()
        notification.setTitle_(title)
        notification.setInformativeText_(message)

        center = NSUserNotificationCenter.defaultUserNotificationCenter()
        center.deliverNotification_(notification)
Exemplo n.º 36
0
def alert(title, message):
    ''' Send the desktop notification. '''

    notification = NSUserNotification.alloc().init()
    notification.setTitle_(title)
    notification.setInformativeText_(message)
    notification.setSoundName_(NSUserNotificationDefaultSoundName)

    center = NSUserNotificationCenter.defaultUserNotificationCenter()
    center.deliverNotification_(notification)
Exemplo n.º 37
0
def alert(title,message):
    ''' Send the desktop notification. '''

    notification = NSUserNotification.alloc().init()
    notification.setTitle_(title)
    notification.setInformativeText_(message)
    notification.setSoundName_(NSUserNotificationDefaultSoundName)

    center = NSUserNotificationCenter.defaultUserNotificationCenter()
    center.deliverNotification_(notification)
Exemplo n.º 38
0
    def osx_message(self, title, message):
        # based on:
        # https://gist.github.com/baliw/4020619
        # http://stackoverflow.com/questions/17651017/python-post-osx-notification
        notification = NSUserNotification.alloc().init()
        notification.setTitle_(title)
        notification.setInformativeText_(message)

        center = NSUserNotificationCenter.defaultUserNotificationCenter()
        center.deliverNotification_(notification)
    def notify(self, title, message, sound):

        notification = NSUserNotification.alloc().init()
        notification.setTitle_(title)
        notification.setInformativeText_(message)
        if sound:
            notification.setSoundName_(NSUserNotificationDefaultSoundName)

        center = NSUserNotificationCenter.defaultUserNotificationCenter()
        center.deliverNotification_(notification)
Exemplo n.º 40
0
 def alert(content="", title="SECURITY ALERT", icon=False, sound=False):
     if content:
         print "[>] secalert[%s]: %s" % (title, content)
         notification = NSUserNotification.alloc().init()
         notification.setTitle_(title)
         notification.setInformativeText_(content)
         if sound:
             notification.setSoundName_(NSUserNotificationDefaultSoundName)
         center = NSUserNotificationCenter.defaultUserNotificationCenter()
         center.deliverNotification_(notification)
Exemplo n.º 41
0
    def deliver(self, title, text):
        from Foundation import NSUserNotification
        from Foundation import NSUserNotificationCenter

        notification = NSUserNotification.alloc().init()
        notification.setTitle_(title)
        notification.setInformativeText_(text)
        center = NSUserNotificationCenter.defaultUserNotificationCenter()
        if center is not None:  # Only works when run from app bundle.
            center.deliverNotification_(notification)
Exemplo n.º 42
0
    def deliver(self, title, text, level='info'):
        if self.notifications_suppressed(level):
            return

        from Foundation import NSUserNotification, NSUserNotificationCenter
        notification = NSUserNotification.alloc().init()
        notification.setTitle_(title)
        notification.setInformativeText_(text)
        center = NSUserNotificationCenter.defaultUserNotificationCenter()
        if center is not None:  # Only works when run from app bundle.
            return center.deliverNotification_(notification)
Exemplo n.º 43
0
    def run(self):
        """
        Perform various setup tasks then start application run loop.
        """
        nsapplication = NSApplication.sharedApplication()
        nsapplication.activateIgnoringOtherApps_(True)  # NSAlerts in front
        self._nsapp = NSApp.alloc().init()
        self._nsapp._app = self.__dict__  # allow for dynamic modification based on this App instance
        self._nsapp.initializeStatusBar()
        nsapplication.setDelegate_(self._nsapp)
        NSUserNotificationCenter.defaultUserNotificationCenter().setDelegate_(self._nsapp)

        setattr(App, '*app_instance', self)  # class level ref to running instance (for passing self to App subclasses)
        for t in getattr(timer, '*timers', []):
            t.start()
        for b in getattr(clicked, '*buttons', []):
            b(self)  # we waited on registering clicks so we could pass self to access _menu attribute

        AppHelper.runEventLoop()
        sys.exit(0)
Exemplo n.º 44
0
def send_notification(title, text, wantSound=True):
    # Use NSUserNotification to construct our notification:
    notification = NSUserNotification.alloc().init()
    notification.setTitle_(title)
    notification.setInformativeText_(text)
    if wantSound:
        notification.setSoundName_(NSUserNotificationDefaultSoundName)

    # Now, deliver that notification to the default macOS notification center:
    center = NSUserNotificationCenter.defaultUserNotificationCenter()
    center.deliverNotification_(notification)
Exemplo n.º 45
0
 def alert(content="", title="SECURITY ALERT", icon=False, sound=False):
     if content:
         print "[>] secalert[%s]: %s" % (title, content)
         notification = NSUserNotification.alloc().init()
         notification.setTitle_(title)
         notification.setInformativeText_(content)
         if sound:
             notification.setSoundName_(
                 NSUserNotificationDefaultSoundName)
         center = NSUserNotificationCenter.defaultUserNotificationCenter(
         )
         center.deliverNotification_(notification)
Exemplo n.º 46
0
def notify_mac(summary, body='', app_name='', app_icon='',
               timeout=5000, actions=[], hints=[], replaces_id=0):
  from Foundation import NSUserNotification
  from Foundation import NSUserNotificationCenter
  from Foundation import NSUserNotificationDefaultSoundName
  notification = NSUserNotification.alloc().init()
  notification.setTitle_(summary)
  notification.setInformativeText_(body)
  notification.setSoundName_(NSUserNotificationDefaultSoundName)
  #notification.setImage("svd.jpg")
  center = NSUserNotificationCenter.defaultUserNotificationCenter()
  center.deliverNotification_(notification)
Exemplo n.º 47
0
def notify(title, subtitle, text):
    # create a user notification
    notification = NSUserNotification.alloc().init()
    notification.setTitle_(title)
    notification.setSubtitle_(subtitle)
    notification.setInformativeText_(text)

    # get the default User Notification Center
    nc = NSUserNotificationCenter.defaultUserNotificationCenter()

    # tell the notification center to deliver the user notification
    nc.deliverNotification_(notification)
Exemplo n.º 48
0
    def notify(self, _title, _message, _sound=False):
        self._title = _title
        self._message = _message
        self._sound = _sound

        self.notification = NSUserNotification.alloc().init()
        self.notification.setTitle_(self._title)
        self.notification.setInformativeText_(self._message)
        if self._sound == True:
            self.notification.setSoundName_(NSUserNotificationDefaultSoundName)

        center = NSUserNotificationCenter.defaultUserNotificationCenter()
        center.deliverNotification_(self.notification)
Exemplo n.º 49
0
def main():
    parser = OptionParser(usage='%prog -t TITLE -m MESSAGE')
    parser.add_option('-t', '--title', action='store', default='A title')
    parser.add_option('-m', '--message', action='store', default='...')

    options, args = parser.parse_args()
 
    notification = NSUserNotification.alloc().init()
    notification.setTitle_(options.title)
    notification.setInformativeText_(options.message)

    center = NSUserNotificationCenter.defaultUserNotificationCenter()
    center.deliverNotification_(notification)
Exemplo n.º 50
0
def _default_user_notification_center():
    notification_center = NSUserNotificationCenter.defaultUserNotificationCenter()
    if notification_center is None:
        info = (
            'Failed to setup the notification center. This issue occurs when the "Info.plist" file '
            'cannot be found or is missing "CFBundleIdentifier".'
        )
        try:
            info += _gather_info_issue_9()
        except Exception:
            pass
        raise RuntimeError(info)
    else:
        return notification_center
Exemplo n.º 51
0
Arquivo: rumps.py Projeto: ixc/rumps
    def run(self):
        """Performs various setup tasks including creating the underlying Objective-C application, starting the timers,
        and registering callback functions for click events. Then starts the application run loop.
        """
        nsapplication = NSApplication.sharedApplication()
        nsapplication.activateIgnoringOtherApps_(True)  # NSAlerts in front
        self._nsapp = NSApp.alloc().init()
        self._nsapp._app = self.__dict__  # allow for dynamic modification based on this App instance
        self._nsapp.initializeStatusBar()
        nsapplication.setDelegate_(self._nsapp)
        if _NOTIFICATIONS:
            NSUserNotificationCenter.defaultUserNotificationCenter().setDelegate_(self._nsapp)

        setattr(App, '*app_instance', self)  # class level ref to running instance (for passing self to App subclasses)
        t = b = None
        for t in getattr(timer, '*timers', []):
            t.start()
        for b in getattr(clicked, '*buttons', []):
            b(self)  # we waited on registering clicks so we could pass self to access _menu attribute
        del t, b

        AppHelper.runEventLoop()
        sys.exit(0)
Exemplo n.º 52
0
def _default_user_notification_center():
    notification_center = NSUserNotificationCenter.defaultUserNotificationCenter(
    )
    if notification_center is None:
        info = (
            'Failed to setup the notification center. This issue occurs when the "Info.plist" file '
            'cannot be found or is missing "CFBundleIdentifier".')
        try:
            info += _gather_info_issue_9()
        except Exception:
            pass
        raise RuntimeError(info)
    else:
        return notification_center
Exemplo n.º 53
0
def main():
    if len(sys.argv)<4:
        print("Error: not enough arguments")
        return 1
    global notification_center
    notification_center = NSUserNotificationCenter.defaultUserNotificationCenter()
    if not notification_center:
        print("Error: cannot access notification center")
        return 2
    nid = sys.argv[1]
    summary = sys.argv[2]
    body = sys.argv[3]
    show_notify(nid, summary, body)
    return 0
Exemplo n.º 54
0
def notify_osx(reports):
    from AppKit import NSImage
    from Foundation import NSUserNotification
    from Foundation import NSUserNotificationCenter
    from Foundation import NSUserNotificationDefaultSoundName

    for report in reports:
        notification = NSUserNotification.alloc().init()
        notification.setTitle_("%s %s changes" % (report["status"].title(), report["vcs"].lower()))
        notification.setInformativeText_(report["path"])
        image = NSImage.alloc().initByReferencingFile_(here("logo.png"))
        # See http://stackoverflow.com/questions/24923979/nsusernotification-customisable-app-icon
        # Unfortunately I can't seem to get it to work with PyObjC
        # notification.setValue_forKey_(image, "_identityImage")
        notification.setIdentifier_(report["path"])
        notification.setSoundName_(NSUserNotificationDefaultSoundName)
        center = NSUserNotificationCenter.defaultUserNotificationCenter()
        center.deliverNotification_(notification)
Exemplo n.º 55
0
    def _run(self):
        NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(1, self, 'doIdle:', "", True)
        self.app = NSApplication.sharedApplication()
        self.app.activateIgnoringOtherApps_(True)
        self.delegate = AppDelegate.alloc().init()
        self.delegate.shell = self
        self.delegate.app = self.app
        self.app.setDelegate_(self.delegate)

        if _NOTIFICATIONS:
            nc = NSUserNotificationCenter.defaultUserNotificationCenter()
            if nc is not None:
                nc.setDelegate_(self.app)
            else:
                logger.warning("No notification center object found!")
        else:
            logger.debug("Platform notification is not enabled.")

        self.app.run()
Exemplo n.º 56
0
def mac_notifications():
    parser = OptionParser(usage='%prog -t TITLE -m MESSAGE')
    parser.add_option('-t', '--title', action='store', default='Link Copied')
    parser.add_option('-m', '--message', action='store', default="""A Link has been Successfully Copied to Your Clipboard. Kindly Paste and Save it.""")
    parser.add_option('--no-sound', action='store_false', default=True, dest='sound')

    options, args = parser.parse_args()
                      
    pool = NSAutoreleasePool.alloc().init()
    notification = NSUserNotification.alloc().init()
    notification.setTitle_(options.title)
    notification.setInformativeText_(options.message)
    if options.sound:
        notification.setSoundName_(NSUserNotificationDefaultSoundName)
                      
    center = NSUserNotificationCenter.defaultUserNotificationCenter()
    center.deliverNotification_(notification)
                      
    del notification
    del pool
Exemplo n.º 57
0
    def show(self, title, subtitle, message, cover):
        center = NSUserNotificationCenter.defaultUserNotificationCenter()
        notification = NSUserNotification.alloc().init()

        notification.setTitle_(title)
        notification.setSubtitle_(subtitle.decode('utf-8'))
        notification.setInformativeText_(message.decode('utf-8'))

        if cover: # the song has an embedded cover image
            img = AppKit.NSImage.alloc().initByReferencingFile_(cover)
            notification.setContentImage_(img)
        elif ALBUMART_PATH: # song has no cover image, show an icon
            img = AppKit.NSImage.alloc().initByReferencingFile_(DEFAULT_LOCAL_ICON)
            notification.setContentImage_(img)

        if DISPLAY_MODE == 1:
            notification.setIdentifier_('cmus')
        elif DISPLAY_MODE == 2:
            center.removeAllDeliveredNotifications()

        center.deliverNotification_(notification)
Exemplo n.º 58
0
def setup_delegator(delegator: NotificationDelegator = None) -> None:
    center = NSUserNotificationCenter.defaultUserNotificationCenter()
    if delegator is not None and center is not None:
        center.setDelegate_(delegator)