Created
February 10, 2015 08:53
-
-
Save xdqi/e0d20d8bc5a6dee5472d to your computer and use it in GitHub Desktop.
Implement minimum python-notify2 API using pync
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 | |
# WeCase -- This file implemented Notify. | |
# Copyright (C) 2013, 2014, 2015 The WeCase Developers. | |
# License: GPL v3 or later. | |
from PyQt4 import QtCore | |
import path | |
try: | |
import notify2 as pynotify | |
from dbus.exceptions import DBusException | |
pynotify.init("WeCase") | |
except ImportError: | |
from OSXNotify import os_x_notify_is_available | |
if os_x_notify_is_available(): | |
import OSXNotify as pynotify | |
from OSXNotify import DBusException | |
else: | |
import nullNotify as pynotify | |
except DBusException: | |
import nullNotify as pynotify | |
class Notify(QtCore.QObject): | |
image = path.icon_path | |
def __init__(self, appname=QtCore.QObject().tr("WeCase"), timeout=5): | |
super(Notify, self).__init__() | |
pynotify.init(appname) | |
self.timeout = timeout | |
self.n = pynotify.Notification(appname) | |
def showMessage(self, title, text): | |
try: | |
self.n.update(title, text, self.image) | |
self.n.set_timeout(self.timeout * 1000) | |
self.n.show() | |
except DBusException: | |
return False | |
return True |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 | |
# WeCase -- This model implemented a simple notification interface for | |
# Mac OS X (v10.8+). | |
# Copyright (C) 2013, 2014, 2015 The WeCase Developers. | |
# License: GPL v3 or later. | |
try: | |
from pync import Notifier | |
except ImportError: | |
class Notifier(): | |
def notify(self, *args, **kwargs): | |
pass | |
def init(self, *args): | |
pass | |
class Notification: | |
def __init__(self, appname): | |
self.appname = appname | |
def update(self, title, text, imagepath): | |
self.title = title | |
self.text = text | |
self.image_path = imagepath | |
def set_timeout(self, *args): | |
pass | |
def show(self): | |
try: | |
Notifier.notify(self.text, | |
title=self.title, | |
appIcon=self.image_path, | |
sender='org.python.PythonLauncher', | |
activate='org.python.PythonLauncher') | |
except Exception as e: | |
raise DBusException(e) | |
class DBusException(Exception): | |
def __init__(self, value): | |
self.value = value | |
def __str__(self): | |
return repr(self.value) | |
def os_x_notify_is_available(): | |
try: | |
from pync import Notifier | |
return True | |
except Exception: | |
return False |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 | |
# WeCase -- Linux Sina Weibo Client, since Feb 4th, 2013. | |
# This is the entry point of WeCase. | |
# Copyright (C) 2013, 2014 The WeCase Developers. | |
# License: GPL v3 or later. | |
import sys | |
sys.path.append("@PYTHONDIR@") | |
sys.path.append("@DATADIR@/wecase") | |
import os | |
import sip | |
from PyQt4 import QtCore, QtGui | |
import traceback | |
import signal | |
import logging | |
import path | |
import version | |
from LoginWindow import LoginWindow | |
import WeHack | |
from WeHack import UNUSED | |
def mkconfig(): | |
try: | |
os.makedirs(path.config_path.replace("/config_db", "")) | |
except OSError: | |
pass | |
try: | |
os.makedirs(path.cache_path) | |
except OSError: | |
pass | |
class ErrorWindow(QtCore.QObject): | |
raiseException = QtCore.pyqtSignal(str) | |
def __init__(self, parent=None): | |
super(ErrorWindow, self).__init__(parent) | |
self.raiseException.connect(self.showError) | |
@QtCore.pyqtSlot(str) | |
def showError(self, traceback): | |
messageBox = QtGui.QMessageBox(QtGui.QMessageBox.Critical, self.tr("Unknown Error"), "") | |
layout = messageBox.layout() | |
if layout: | |
textEdit = QtGui.QPlainTextEdit(traceback) | |
textEdit.setReadOnly(True) | |
textEdit.setFixedHeight(250) | |
textEdit.setFixedWidth(600) | |
layout.addWidget(textEdit, 0, 1) | |
messageBox.exec() | |
def my_excepthook(type, value, tback): | |
if "last_error" not in globals().keys(): | |
global last_error | |
last_error = None | |
exception = "".join(traceback.format_exception(type, value, tback)) | |
line1 = App.translate("main", "Oops, there is an unexpected error,\n") | |
line2 = App.translate("main", "Please report it to %s\n") | |
line3 = "------------[ cut here ]------------\n\n" | |
line4 = "Version: WeCase %s\n\n" | |
last_line = "---[ end trace %s ]---" | |
error_info = (line1 + line2 % version.bug_report_url + line3 + line4 % version.pkgversion + "%s" % exception + last_line % hex(id(value))) | |
if type != last_error: | |
last_error = type | |
logging.error(error_info) | |
errorWindow.raiseException.emit(error_info) | |
else: | |
logging.error("Same error...") | |
# Call the default handler | |
sys.__excepthook__(type, value, tback) | |
def import_warning(): | |
try: | |
import notify2 | |
import dbus | |
from dbus.exceptions import DBusException | |
notify2.init("WeCase") | |
UNUSED(dbus) | |
except ImportError: | |
from OSXNotify import os_x_notify_is_available | |
if not os_x_notify_is_available: | |
QtGui.QMessageBox.warning( | |
None, | |
App.translate("main", "Notification disabled"), | |
App.translate("main", "dbus-python, notify2 or pync is not found. Notification will disable.")) | |
notify2.init("WeCase") | |
except DBusException: | |
QtGui.QMessageBox.warning( | |
None, | |
App.translate("main", "Notification disabled"), | |
App.translate("main", "Notification Daemon not exist. Notification will disable.")) | |
def setup_logger(): | |
loglevel = str(os.getenv("WECASELOG")).upper() | |
if loglevel in ("WARNING", "WARN"): | |
loglevel = logging.WARN | |
elif loglevel in ("DEBUG", "VERBOSE"): | |
loglevel = logging.DEBUG | |
else: | |
loglevel = logging.ERROR | |
logging.basicConfig(level=loglevel, | |
format='%(asctime)s %(name)-12s %(levelname)-8s %(' | |
'message)s', | |
datefmt='%m-%d %H:%M', | |
filename=path.cache_path + "log") | |
console = logging.StreamHandler() | |
console.setLevel(logging.DEBUG) | |
formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s') | |
console.setFormatter(formatter) | |
logging.getLogger('').addHandler(console) | |
if __name__ == "__main__": | |
mkconfig() | |
setup_logger() | |
# Issue 50. Disable automatic destruction of C/C++. | |
try: | |
sip.setdestroyonexit(False) | |
safe_to_exit = True | |
except AttributeError: | |
logging.warn("Old SIP detect.") | |
safe_to_exit = False | |
App = QtGui.QApplication(sys.argv) | |
App.setApplicationName("WeCase") | |
QtCore.QTextCodec.setCodecForTr(QtCore.QTextCodec. codecForName("UTF-8")) | |
# Exceptions may happen in other threads. | |
# So, use signal/slot to avoid threads' issue. | |
sys.excepthook = my_excepthook | |
WeHack.workaround_excepthook_bug() | |
errorWindow = ErrorWindow() | |
signal.signal(signal.SIGINT, signal.SIG_DFL) | |
# Qt's built-in string translator | |
qt_translator = QtCore.QTranslator(App) | |
qt_translator.load("qt_" + QtCore.QLocale.system().name(), | |
QtCore.QLibraryInfo.location( | |
QtCore.QLibraryInfo.TranslationsPath)) | |
App.installTranslator(qt_translator) | |
# WeCase's own string translator | |
my_translator = QtCore.QTranslator(App) | |
my_translator.load("WeCase_" + QtCore.QLocale.system().name(), | |
path.locale_path) | |
App.installTranslator(my_translator) | |
import_warning() | |
wecase_login = LoginWindow() | |
exit_status = App.exec_() | |
# Cleanup code here. | |
App.deleteLater() | |
logging.info("Exited") | |
sys.excepthook = sys.__excepthook__ | |
if safe_to_exit: | |
exit(exit_status) | |
else: | |
os._exit(exit_status) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment