コード例 #1
0
def show_notification(title, message):
    '''
    Show a notification using libnotify/gobject

    Positional arguments:
    title - notification title
    message - notification message

    Raises:
    RuntimeError - failed to show the notification

    Note:
    This function is designed to be called a few times in a row so
    make sure to call Notify.uninit() afterwards
    '''
    if Notify.is_initted() is False:
        Notify.init('TwitchNotifier')

    if Notify.is_initted() is False:
        raise RuntimeError('Failed to init notify')

    notif = Notify.Notification.new(title, message)

    if not notif.show():
        raise RuntimeError('Failed to show a notification')
コード例 #2
0
ファイル: notify.py プロジェクト: Nek-/Solaar
	def init():
		"""Init the notifications system."""
		global available
		if available:
			if not Notify.is_initted():
				logging.info("starting desktop notifications")
				try:
					return Notify.init(_NAMESPACE)
				except:
					logging.exception("initializing desktop notifications")
					available = False
		return available and Notify.is_initted()
コード例 #3
0
	def init():
		"""Init the notifications system."""
		global available
		if available:
			if not Notify.is_initted():
				if _log.isEnabledFor(_INFO):
					_log.info("starting desktop notifications")
				try:
					return Notify.init(NAME)
				except:
					_log.exception("initializing desktop notifications")
					available = False
		return available and Notify.is_initted()
コード例 #4
0
def notify_process():
    global notifications, notifying, last_notify

    if len(notifications) == 0:
        return


#    if notifying == True:
#        #See Bug #622021 on gnome
#        diff = datetime.now() - last_notify
#        if diff.seconds > 30:
#            logger.debug("30 seconds from the last notification, reactivating")
#            notifying = False
#        else:
#            return

    if not Notify.is_initted():
        logger.warn('The notification library has not been initialized yet')
        return

    while len(notifications) > 0:
        n = notifications.pop(0)
        #n.connect("closed", notify_closed_cb)
        n.show()

    notifying = True
    last_notify = datetime.now()
    #TODO Do it better and configuable
    sound = Sound()
    sound.play(config.add_data_prefix("drip.ogg"))
コード例 #5
0
	def show(dev, reason=None, icon=None):
		"""Show a notification with title and text."""
		if available and Notify.is_initted():
			summary = dev.name

			# if a notification with same name is already visible, reuse it to avoid spamming
			n = _notifications.get(summary)
			if n is None:
				n = _notifications[summary] = Notify.Notification()

			if reason:
				message = reason
			elif dev.status is None:
				message = _("unpaired")
			elif bool(dev.status):
				message = dev.status.to_string() or _("connected")
			else:
				message = _("offline")

			# we need to use the filename here because the notifications daemon
			# is an external application that does not know about our icon sets
			icon_file = _icons.device_icon_file(dev.name, dev.kind) if icon is None \
						else _icons.icon_file(icon)

			n.update(summary, message, icon_file)
			urgency = Notify.Urgency.LOW if dev.status else Notify.Urgency.NORMAL
			n.set_urgency(urgency)

			try:
				# if _log.isEnabledFor(_DEBUG):
				# 	_log.debug("showing %s", n)
				n.show()
			except Exception:
				_log.exception("showing %s", n)
コード例 #6
0
ファイル: __init__.py プロジェクト: remcohaszing/exaile
    def __init_notify(self):
        can_continue = True
        caps = None
        if not Notify.is_initted():
            can_continue = Notify.init('Exaile')
        if not can_continue:
            LOGGER.error("Notify.init() returned false.")

        if can_continue:
            # This is the first synchronous call to the Notify server.
            # This call might fail if no server is present or it is broken.
            # Test it on window manager sessions (e.g. Weston) without
            # libnotify support, not on a Desktop Environment (such as
            # GNOME, KDE) to reproduce.
            available, name, vendor, version, spec_version = \
                Notify.get_server_info()
            if available:
                LOGGER.info(
                    "Connected with notify server %s (version %s) by %s", name,
                    version, vendor)
                LOGGER.info("Supported spec version: %s", spec_version)
                # This is another synchronous, blocking call:
                caps = Notify.get_server_caps()
                # Example from Fedora 26 Linux with GNOME on Wayland:
                # ['actions', 'body', 'body-markup', 'icon-static', 'persistence', 'sound']
                LOGGER.debug("Notify server caps: %s", caps)
                if not caps or not isinstance(caps, list):
                    can_continue = False
            else:
                LOGGER.error(
                    "Failed to retrieve capabilities from notify server. "
                    "This may happen if the desktop environment does not support "
                    "the org.freedesktop.Notifications DBus interface.")
                can_continue = False
        self.__handle_init(can_continue, caps)
コード例 #7
0
def notify_process ():
    global notifications, notifying, last_notify

    if len(notifications) == 0:
        return;

#    if notifying == True:
#        #See Bug #622021 on gnome
#        diff = datetime.now() - last_notify
#        if diff.seconds > 30:
#            logger.debug("30 seconds from the last notification, reactivating")
#            notifying = False
#        else:
#            return

    if not Notify.is_initted():
        logger.warn('The notification library has not been initialized yet')
        return

    while len(notifications) > 0:
        n = notifications.pop(0)
        #n.connect("closed", notify_closed_cb)
        n.show()

    notifying= True
    last_notify = datetime.now()
    #TODO Do it better and configuable
    sound = Sound()
    sound.play(config.add_data_prefix("drip.ogg"))
コード例 #8
0
ファイル: imaging.py プロジェクト: awacha/SAXSCtrl
 def do_imaging_fail(self, message):
     logger.error('Imaging failure: ' + message)
     if Notify.is_initted():
         n = Notify.Notification.new('Imaging failure',
                                     'Reason: ' + message,
                                     'dialog-error')
         n.show()
         del n
コード例 #9
0
ファイル: genix.py プロジェクト: awacha/SAXSCtrl
 def do_notify(self, prop):
     Instrument_ModbusTCP.do_notify(self, prop)
     logger.info('GeniX status changed to: ' + self.status)
     if Notify.is_initted():
         n = Notify.Notification.new(
             'GeniX status change', 'New status: ' + self.status, 'dialog-information')
         n.show()
         del n
コード例 #10
0
ファイル: notifier.py プロジェクト: david-xie/mate-applets
 def __init__(self, app_name, icon, attach):
     self._icon = icon
     self._attach = attach
     self._notify = None
     self._handler_id = None
     self._timeout_id = None
     if not Notify.is_initted():
         Notify.init(app_name)
コード例 #11
0
ファイル: utils.py プロジェクト: DarkSouL11/gnome-tweak-tool
 def __init__(self, summary, body):
     if Notify.is_initted() or Notify.init("GNOME Tweak Tool"):
         self.notification = Notify.Notification.new(
             summary, body, 'gnome-tweak-tool')
         self.notification.set_hint("desktop-entry",
                                    GLib.Variant('s', 'gnome-tweak-tool'))
         self.notification.show()
     else:
         raise Exception("Not Supported")
コード例 #12
0
def init(icon_path):
    '''
    Initialize the module Notification system.
    '''
    # initialize icon
    global icon
    icon = GdkPixbuf.Pixbuf.new_from_file(icon_path)

    # initialize Notify
    if not Notify.is_initted():
        Notify.init("Rhythmbox")
コード例 #13
0
def init(icon_path):
    # inicializa los threads de gobject
    GObject.threads_init()

    # inicializa el icono para notificaciones
    global icon
    icon = GdkPixbuf.Pixbuf.new_from_file(icon_path)

    # inicializamos libnotify
    if not Notify.is_initted():
        Notify.init("Rhythmbox")
コード例 #14
0
    def run(self):
        self.show_all()
        self._check_default_browser()

        Notify.init('uroute')
        Gtk.main()

        if Notify.is_initted():
            Notify.uninit()

        return self.command
コード例 #15
0
ファイル: Timer.py プロジェクト: Ulauncher/ulauncher-timer
 def _show_notification(self, title, body, on_close):
     if not Notify.is_initted():
         Notify.init("TimerExtension")
     icon = get_icon_path()
     if self.notification is None:
         self.notification = Notify.Notification.new(title, body, icon)
     else:
         self.notification.update(title, body, icon)
     if on_close is not None:
         self.notification.connect("closed", on_close)
     self.notification.show()
コード例 #16
0
 def __init__(self, summary, body):
     if Notify.is_initted() or Notify.init('Mattermost'):
         self.notification = Notify.Notification.new(
             summary, body, 'user-available')
         self.notification.set_hint('desktop-entry',
                                    GLib.Variant('s', 'mattermost'))
         self.notification.set_hint('category',
                                    GLib.Variant('s', 'im.received'))
         self.notification.set_category('im.received')
         self.notification.show()
     else:
         raise Exception('Not Supported')
コード例 #17
0
ファイル: thetool.py プロジェクト: izderadicka/thetool
 def send_notification(self, message):
     if not self.settings.get_unpacked('enable-notifications'):
         return
     if not Notify.is_initted ():
         Notify.init(self.NAME)
     notification = Notify.Notification.new(
     self.NAME,
     message,
     None# 'dialog-information'
     )
     notification.set_image_from_pixbuf(self.icon_normal)
     notification.show()
コード例 #18
0
ファイル: utils.py プロジェクト: pombredanne/linuxtrail
 def __init__(self, summary, body):
     if Notify.is_initted() or Notify.init("GNOME Tweak Tool"):
         self.notification = Notify.Notification.new(
                                 summary,
                                 body,
                                 'gnome-tweak-tool'
         )
         self.notification.set_hint(
                             "desktop-entry",
                             GLib.Variant('s', 'gnome-tweak-tool'))
         self.notification.show()
     else:
         raise Exception("Not Supported")
コード例 #19
0
ファイル: utils.py プロジェクト: DarkSouL11/gnome-tweak-tool
 def __init__(self):
     if Notify.is_initted() or Notify.init(_("GNOME Tweak Tool")):
         self.notification = Notify.Notification.new(
             _("Configuration changes require restart"),
             _("Your session needs to be restarted for settings to take effect"
               ), 'gnome-tweak-tool')
         self.notification.add_action("restart", _("Restart Session"),
                                      self._logout, None, None)
         self.notification.set_hint("desktop-entry",
                                    GLib.Variant('s', 'gnome-tweak-tool'))
         self.notification.show()
     else:
         raise Exception("Not Supported")
コード例 #20
0
ファイル: screenshot.py プロジェクト: fernzi/dotfiles
async def _run(command: list, save: Path) -> bool:
    save.parent.mkdir(parents=True, exist_ok=True)
    proc = await aio.create_subprocess_exec(*command)
    await proc.wait()
    if save.exists():
        audio.play('screen-capture')
        if Notify.is_initted():
            Notify.Notification.new(
                'Screen captured!',
                str(save),
                str(save),
            ).show()
        return True
    return False
コード例 #21
0
ファイル: __init__.py プロジェクト: jinhkim/AutomaThemely
def notify(message):
    import gi
    gi.require_version('Notify', '0.7')
    from gi.repository import Notify, GLib

    if not Notify.is_initted():
        Notify.init('AutomaThemely')

    n = Notify.Notification.new('AutomaThemely', message,
                                get_resource('automathemely.svg'))
    try:  # I don't even know... https://bugzilla.redhat.com/show_bug.cgi?id=1582833
        n.show()
    except GLib.GError as e:
        if str(e) != 'g-dbus-error-quark: Unexpected reply type (16)':
            raise e
コード例 #22
0
ファイル: utils.py プロジェクト: pombredanne/linuxtrail
 def __init__(self):
     if Notify.is_initted() or Notify.init("GNOME Tweak Tool"):
         self.notification = Notify.Notification.new(
                             "Configuration changes requiere restart",
                             "Your session needs to be restarted for settings to take effect",
                             'gnome-tweak-tool')
         self.notification.add_action(
                             "restart",
                             "Restart Session",
                             self._logout, None, None)
         self.notification.set_hint(
                             "desktop-entry",
                             GLib.Variant('s', 'gnome-tweak-tool'))
         self.notification.show()
     else:
         raise Exception("Not Supported")
コード例 #23
0
ファイル: utils.py プロジェクト: danigm/gnome-clocks
    def __init__(self, soundid, title, msg):
        try:
            self.canberra = pycanberra.Canberra()
        except Exception as e:
            print("Sound will not be available: ", e)
            self.canberra = None

        self.soundtheme = Alert.settings.get_string('theme-name')
        self.soundid = soundid

        self.notification = None
        if Notify.is_initted() or Notify.init("GNOME Clocks"):
            self.notification = Notify.Notification.new(title, msg, "gnome-clocks")
            self.notification.set_hint_string("desktop-entry", "gnome-clocks")
        else:
            print("Error: Could not trigger Alert")
コード例 #24
0
ファイル: utils.py プロジェクト: wroldwiedbwe/AutomaThemely
def notify(message, title='AutomaThemely'):
    import gi
    gi.require_version('Notify', '0.7')
    from gi.repository import Notify, GLib

    if not Notify.is_initted():
        Notify.init('AutomaThemely')

    n = Notify.Notification.new(title, message, get_resource('automathemely.svg'))
    try:  # I don't even know... https://bugzilla.redhat.com/show_bug.cgi?id=1582833
        n.show()
    except GLib.GError as e:
        if str(e) != 'g-dbus-error-quark: Unexpected reply type (16)' \
                and str(e) != 'g-dbus-error-quark: GDBus.Error:org.freedesktop.DBus.Error.NoReply: Message recipient ' \
                              'disconnected from message bus without replying (4)':
            raise e
コード例 #25
0
ファイル: timetracker.py プロジェクト: Artimi/waktu
    def askUser(self, _activity, _categories):
        """Creates a notification and asks a user where the activity belongs to"""
        if not Notify.is_initted():
            Notify.init('Waktu')
            
        self.n.clear_hints()
        self.n.clear_actions()
        self.n.set_property('summary','Kam patří aktivita %s?' % _activity.getName())
        self.n.set_property('body', 'Zdá se, že tuto aktivitu máte zvolenou ve více kategoriích. Zvolte, prosím, níže jednu, do které spadá tato aktivita práve teď.')
        self.n.set_property('icon_name','dialog-question')
        self.n.set_urgency(Notify.Urgency.NORMAL)
        self.n.set_timeout(Notify.EXPIRES_NEVER)
        self.n.set_hint("resident", GLib.Variant('b',True))
        
        for cat in _categories:
            self.n.add_action(cat.name, cat.name, self.getUserAnswer, _activity, None)

        self.n.add_action("OTHER", "Jinam", self.getUserAnswer, _activity, None)
        
        self.n.show()
コード例 #26
0
ファイル: scan.py プロジェクト: awacha/SAXSCtrl
 def do_scan_end(self, status):
     if self._ex_conn is not None:
         for c in self._ex_conn:
             self.credo().subsystems['Exposure'].disconnect(c)
         self._ex_conn = None
     if self.autoreturn:
         logger.info('Auto-returning...')
         try:
             self.scandevice.moveto(self._autoreturn_to)
         except ScanDeviceError:
             self.emit(
                 'scan-fail', 'Error on auto-return: ' + traceback.format_exc())
     self._firsttime = None
     self._where = None
     self.currentscan.stop_record_mode()
     if self.credo().subsystems['Exposure'].operate_shutter != self._original_shuttermode:
         self.credo().subsystems[
             'Exposure'].operate_shutter = self._original_shuttermode
     if self.credo().subsystems['Exposure'].operate_shutter:
         try:
             if self.credo().get_equipment('genix').shutter_state():
                 logger.warning(
                     'Shutter left open at the end of scan, closing.')
                 self.credo().get_equipment('genix').shutter_close()
         except GenixError:
             logger.warning(
                 'Error closing shutter: ' + traceback.format_exc())
     logger.info('Scan #%d finished.' % self.currentscan.fsn)
     if Notify.is_initted():
         if status:
             n = Notify.Notification.new(
                 'Scan #%d finished' % self.currentscan.fsn,
                 'Sequence ended normally.',
                 'dialog-information')
         else:
             n = Notify.Notification.new(
                 'Scan #%d finished' % self.currentscan.fsn,
                 'Abnormal termination.',
                 'dialog-warning')
         n.show()
         del n
コード例 #27
0
def notify(
    title, msg, icon='dialog-information', timeout=Notify.EXPIRES_DEFAULT,
    actions=None, transient=False, urgency=Notify.Urgency.NORMAL,
):
    if not Notify.is_initted():
        Notify.init('uroute')

    notification = Notify.Notification.new(title, msg, icon=icon)
    notification.set_timeout(timeout)
    notification.set_urgency(urgency)

    if transient:
        notification.set_hint_byte('transient', 1)

    for action in listify(actions):
        notification.add_action(
            action.id, action.label, action.callback, action.user_data,
        )

    notification.show()
    return notification
コード例 #28
0
ファイル: notify.py プロジェクト: yunpub/Solaar
    def show(dev, reason=None, icon=None, progress=None):
        """Show a notification with title and text.
        Optionally displays the `progress` integer value
        in [0, 100] as a progress bar."""
        if available and Notify.is_initted():
            summary = dev.name

            # if a notification with same name is already visible, reuse it to avoid spamming
            n = _notifications.get(summary)
            if n is None:
                n = _notifications[summary] = Notify.Notification()

            if reason:
                message = reason
            elif dev.status is None:
                message = _('unpaired')
            elif bool(dev.status):
                message = dev.status.to_string() or _('connected')
            else:
                message = _('offline')

            # we need to use the filename here because the notifications daemon
            # is an external application that does not know about our icon sets
            icon_file = _icons.device_icon_file(
                dev.name, dev.kind) if icon is None else _icons.icon_file(icon)

            n.update(summary, message, icon_file)
            urgency = Notify.Urgency.LOW if dev.status else Notify.Urgency.NORMAL
            n.set_urgency(urgency)
            n.set_hint('desktop-entry', GLib.Variant('s', NAME.lower()))
            if progress:
                n.set_hint('value', GLib.Variant('i', progress))

            try:
                # if _log.isEnabledFor(_DEBUG):
                #     _log.debug("showing %s", n)
                n.show()
            except Exception:
                _log.exception('showing %s', n)
コード例 #29
0
	def alert(reason, icon=None):
		assert reason

		if available and Notify.is_initted():
			n = _notifications.get(NAME)
			if n is None:
				n = _notifications[NAME] = Notify.Notification()

			# we need to use the filename here because the notifications daemon
			# is an external application that does not know about our icon sets
			icon_file = _icons.icon_file(NAME.lower()) if icon is None \
						else _icons.icon_file(icon)

			n.update(NAME, reason, icon_file)
			n.set_urgency(Notify.Urgency.NORMAL)

			try:
				# if _log.isEnabledFor(_DEBUG):
				# 	_log.debug("showing %s", n)
				n.show()
			except Exception:
				_log.exception("showing %s", n)
コード例 #30
0
ファイル: __init__.py プロジェクト: exaile/exaile
    def __init_notify(self):
        can_continue = True
        caps = None
        if not Notify.is_initted():
            can_continue = Notify.init('Exaile')
        if not can_continue:
            LOGGER.error("Notify.init() returned false.")

        if can_continue:
            # This is the first synchronous call to the Notify server.
            # This call might fail if no server is present or it is broken.
            # Test it on window manager sessions (e.g. Weston) without
            # libnotify support, not on a Desktop Environment (such as
            # GNOME, KDE) to reproduce.
            available, name, vendor, version, spec_version = Notify.get_server_info()
            if available:
                LOGGER.info(
                    "Connected with notify server %s (version %s) by %s",
                    name,
                    version,
                    vendor,
                )
                LOGGER.info("Supported spec version: %s", spec_version)
                # This is another synchronous, blocking call:
                caps = Notify.get_server_caps()
                # Example from Fedora 26 Linux with GNOME on Wayland:
                # ['actions', 'body', 'body-markup', 'icon-static', 'persistence', 'sound']
                LOGGER.debug("Notify server caps: %s", caps)
                if not caps or not isinstance(caps, list):
                    can_continue = False
            else:
                LOGGER.error(
                    "Failed to retrieve capabilities from notify server. "
                    "This may happen if the desktop environment does not support "
                    "the org.freedesktop.Notifications DBus interface."
                )
                can_continue = False
        self.__handle_init(can_continue, caps)
コード例 #31
0
ファイル: notify.py プロジェクト: Nek-/Solaar
	def show(dev, reason=None):
		"""Show a notification with title and text."""
		if available and Notify.is_initted():
			summary = dev.name

			# if a notification with same name is already visible, reuse it to avoid spamming
			n = _notifications.get(summary)
			if n is None:
				n = _notifications[summary] = Notify.Notification()

			message = reason or ('unpaired' if dev.status is None else
						(str(dev.status) or ('connected' if dev.status else 'inactive')))

			# we need to use the filename here because the notifications daemon
			# is an external application that does not know about our icon sets
			n.update(summary, message, _icons.device_icon_file(dev.name, dev.kind))
			urgency = Notify.Urgency.LOW if dev.status else Notify.Urgency.NORMAL
			n.set_urgency(urgency)

			try:
				# logging.debug("showing %s", n)
				n.show()
			except Exception:
				logging.exception("showing %s", n)
コード例 #32
0
ファイル: notify.py プロジェクト: Nek-/Solaar
	def uninit():
		if available and Notify.is_initted():
			logging.info("stopping desktop notifications")
			_notifications.clear()
			Notify.uninit()
コード例 #33
0
ファイル: test-gir.py プロジェクト: Distrotech/libnotify
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA  02111-1307, USA.

import os

# use our local typelib
os.environ['GI_TYPELIB_PATH'] = 'libnotify:' + os.environ.get('GI_TYPELIB_PATH', '')

from gi.repository import Notify

assert Notify.is_initted() == False
Notify.init('test')
assert Notify.is_initted() == True

print 'server info:', Notify.get_server_info()
print 'server capabilities:', Notify.get_server_caps()

n = Notify.Notification.new('title', None, None)
n.show()
n = Notify.Notification.new('title', 'text', None)
n.show()
n = Notify.Notification.new('title', 'text', 'gtk-ok')
n.show()

n.update('New Title', None, None)
n.show()
コード例 #34
0
    def __on_mainnotification_closed(self, notification):
        """When the last notification is closed, quit."""
        if Notify.is_initted():
            Notify.uninit()

        Gtk.main_quit()
コード例 #35
0
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA  02111-1307, USA.

import os

# use our local typelib
os.environ['GI_TYPELIB_PATH'] = 'libnotify:' + os.environ.get(
    'GI_TYPELIB_PATH', '')

from gi.repository import Notify

assert Notify.is_initted() == False
Notify.init('test')
assert Notify.is_initted() == True

print 'server info:', Notify.get_server_info()
print 'server capabilities:', Notify.get_server_caps()

n = Notify.Notification.new('title', None, None)
n.show()
n = Notify.Notification.new('title', 'text', None)
n.show()
n = Notify.Notification.new('title', 'text', 'gtk-ok')
n.show()

n.update('New Title', None, None)
n.show()
コード例 #36
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     if not Notify.is_initted():
         Notify.init(sys.argv[0])
コード例 #37
0
 def __init__(self):
     """ Make sure Notify is initted """
     if not Notify.is_initted():
         Notify.init("Pomidor")
コード例 #38
0
	def uninit():
		if available and Notify.is_initted():
			if _log.isEnabledFor(_INFO):
				_log.info("stopping desktop notifications")
			_notifications.clear()
			Notify.uninit()
コード例 #39
0
 def __init__(self, title):
     """ Initialize notification engine """
     if not Notify.is_initted():
         Notify.init(APPNAME)
     self.title = title
     self.note = None
コード例 #40
0
ファイル: guiclient.py プロジェクト: Boquete/imgur-shot
    def __on_mainnotification_closed(self, notification):
        """When the last notification is closed, quit."""
        if Notify.is_initted():
            Notify.uninit()

        Gtk.main_quit()
コード例 #41
0
ファイル: extensions.py プロジェクト: nathan-hoad/roland
 def setup(self):
     from gi.repository import Notify
     if not Notify.is_initted():
         Notify.init('roland')
コード例 #42
0
ファイル: notifylib.py プロジェクト: ES-Devel/GLMPlayer
 def notify(title, msg, icon=None):
     if not pynotify.is_initted():
         pynotify.init(title)
         note = pynotify.Notification.new(title, msg, icon)
     note.show()