def main(): parser = ArgumentParser() parser.add_argument('-c', '--config', help='A path to config file', default="~/.pyvpn") args = parser.parse_args() Notify.init('SofToken') try: config = get_config(expanduser(args.config)) token = SoftToken(config['tuser'], config['consoleui'], config['wine']) password = token.get_password(config['tpassword']) copy_to_clipboard(password) notification = Notify.Notification.new( "SoftToken", "VPN password copied to clipboard", "dialog-information" ) notification.show() except Exception as e: notification = Notify.Notification.new( "SoftToken", str(e), "dialog-information" ) notification.show()
def notifiersystem(last_comm): Notify.init("Football score") notification = Notify.Notification.new(last_comm) notification.show()
def main(argv): reload(sys); sys.setdefaultencoding('utf-8'); #ķź² ģ¤ė¹ targets = argv[1:] #ģė¦¼ ė©ģģ§ ģ“źø°ķ Notify.init("make_comic_book") title = u'ź·øė¦¼ģ± ė§ė¤źø°' if not targets: msg = u'ėģģ ģ ķķ“ ģ£¼ģøģ!' Notify.Notification.new(title, msg, '').show() sys.exit(1) #ė³ķ for target in targets: try: cbz = MakeCbz().make(target, u'.') except Exception, err: Notify.Notification.new(title, unicode(err), '').show() raise SystemExit() ufp.trashPut(target) #ė©ģģ§ ģģ± msg = u"<b>%(target)s</b>ė„¼ <b>%(cbz)s</b>ė” ė¬¶ģģµėė¤." % locals() #ģė¦¼ ė©ģģ§ ė³“ģ“źø° Notify.Notification.new(title, msg, '').show()
def __init__(self, app, daemon): Notify.init("Syncthing GTK") # Prepare stuff self.app = app self.daemon = daemon self.notify_folders = {} self.notify_devices = {} # Make deep connection with daemon self.signals = [ self.daemon.connect("connected", self.cb_syncthing_connected) ] if self.app.config["notification_for_error"]: self.signals += [ self.daemon.connect("error", self.cb_syncthing_error), self.daemon.connect("folder-rejected", self.cb_syncthing_folder_rejected), self.daemon.connect("device-rejected", self.cb_syncthing_device_rejected) ] log.verbose("Error notifications enabled") if self.app.config["notification_for_update"]: self.signals += [ self.daemon.connect('item-started', self.cb_syncthing_item_started), self.daemon.connect('item-updated', self.cb_syncthing_item_updated), ] log.verbose("File update notifications enabled") if self.app.config["notification_for_folder"]: self.signals += [ self.daemon.connect('folder-sync-progress', self.cb_syncthing_folder_progress), self.daemon.connect('folder-sync-finished', self.cb_syncthing_folder_finished) ] log.verbose("Folder notifications enabled")
def __init__(self, controls): FControl.__init__(self, controls) Gtk.Window.__init__(self, Gtk.WindowType.POPUP) self.set_position(Gtk.WindowPosition.MOUSE) self.connect("leave-notify-event", self.on_leave_window) Notify.init('Foobnix')
def func(): #Enter your Twilio accountSid and authToken accountSid = "" authToken = "" #Parser for the Cricbuzz XML Page in cricbuzz library cric = CricbuzzParser() #Connecting to the Twilio API twilioClient = TwilioRestClient(accountSid, authToken) myTwilioNumber = "" destCellPhone = "" #Getting the XML File and extracting the matches from it match = cric.getXml() details = cric.handleMatches(match) #Filtering out the NoneType Objects in 'details' details = filter(None,details) message = 'No Match Available' for i in details: #Traversing the list if 'Match State' in i: #If the match state key is present in the dict if i['Match State'] == 'inprogress': #If the match is in progress message = i['Team']+ " "+ i['Match Format'] + ' Match at ' + i['Venue']+ "\n" +i['Batting team'] + ' ' + i['Batting Team Runs'] + '/'+i['Batting Team Wickets'] + ' Overs: ' + i['Batting Team Overs'] #Generates the message Notify.init("Live Scores") #Shows Notification on the desktop Notify.Notification.new("Match currently in progress:",message).show() #Sends message to the phone number myMessage = twilioClient.messages.create(body = "Match Currently in progress: " + message, from_=myTwilioNumber, to=destCellPhone) #Defines an interval of 60 seconds time.sleep(60)
def _main(): parser = ArgumentParser() parser.add_argument( '-n','--name', help='name', default="notify-pipe") parser.add_argument( '-i','--icon', help='icon ', default="") args = parser.parse_args() Notify.init("notify-pipe") name = args.name Hello = Notify.Notification.new (name) Hello.show() lines_iterator = iter(sys.stdin.readline, b"") try: for line in lines_iterator: if line: print(line,end="") sys.stdout.flush() Hello.update(name, line, args.icon) Hello.show() else: break except KeyboardInterrupt: sys.exit(0)
def enable(self): self._max_mails = int(self.get_config()['max_visible_mails']) self._notification_server_wait_event.clear() self._notification_server_ready = False self._notifications = {} # initialize Notification if not self._initialized: Notify.init("Mailnag") self._is_gnome = os.environ.has_key('GDMSESSION') and \ (os.environ['GDMSESSION'] == 'gnome') self._initialized = True def mails_added_hook(new_mails, all_mails): self._notify_async(new_mails, all_mails) def mails_removed_hook(remaining_mails): if remaining_mails == 0: # no mails (e.g. email client has been launched) -> close notifications self._close_notifications() self._mails_added_hook = mails_added_hook self._mails_removed_hook = mails_removed_hook controller = self.get_mailnag_controller() hooks = controller.get_hooks() hooks.register_hook_func(HookTypes.MAILS_ADDED, self._mails_added_hook) hooks.register_hook_func(HookTypes.MAILS_REMOVED, self._mails_removed_hook)
def __init__(self): Notify.init("cricket score indicator") self.notification = Notify.Notification.new("") self.notification.set_app_name("Cricket Score") """ Initialize appindicator and other menus """ self.indicator = appindicator.Indicator.new("cricket-indicator", ICON_PREFIX + DEFAULT_ICON+ ICON_SUFFIX , appindicator.IndicatorCategory.APPLICATION_STATUS) # if DEBUG: # self.indicator.set_icon_theme_path(DARK_ICONS) self.indicator.set_status(appindicator.IndicatorStatus.ACTIVE) self.indicator.set_label("Loading", "") self.indicator.connect("scroll-event", self.scroll_event_cb) self.menu_setup() # the 'id' of match selected for display as indicator label self.label_match_id = None self.open_scorecard = set() self.intl_menu = [] self.dom_menu = []
def notification(self): while(True): live_scores, valid = Fixtures().fixture() for score in live_scores: match_time = score['time'] status = score['status'] team = score['team'] score = score['score'] score_time = score + ' (Time:' + match_time + ')' if status != 1: if status == 3: score_time = score + ' (FT)' elif status == 4: score_time = score + ' (HT)' Notify.init("Live Score") send_notification = Notify.Notification.new(team, score_time, ) send_notification.set_icon_from_pixbuf(self._icon) send_notification.show() time.sleep(3) send_notification.close() Notify.uninit() if not valid: break time.sleep(300)
def status(project, args): try: import gi gi.require_version('Notify','0.7') from gi.repository import Notify from gi.repository import GLib except: return global inited if not inited: Notify.init("sgmake") inited = True try: #if not "step" in args and not "start" in args: if "success" == args: Notify.Notification.new( "sgmake", "Build Complete", 'dialog-information' ).show() if "failure" == args: Notify.Notification.new( "sgmake", "Build Failure", 'dialog-error' ).show() except GLib.Error: pass # notifications disabled
def main(): setup_logging() logging.info('Starting 60 min notifier') Notify.init('Check Tasks') notify_body = "eventually this will pull from org agenda" # Hello = Notify.Notification.new('Task Check', notify_body, 'alert.xpm') # show for 5 minutes # Hello.set_timeout(100000) while True: logging.info('Start of while true loop') to_sleep = 3600 - time.time() % 3600 logging.debug('Sleep time is ' + str(to_sleep)) # sleep for the remaining seconds until the half hour time.sleep(to_sleep) logging.info('Showing notification') args = ['uclock'] out_bytes = subprocess.check_output(args) out_text = out_bytes.decode('utf-8') logging.debug(out_text) # alert_window() # Hello.show() logging.error('Somehow left while true loop')
def __init__(self): Notify.init("A3KTorrent") self.filename = 'path' self.filepath = 'folder' #default values to check! self.builder = Gtk.Builder() self.builder.add_from_file("layout.glade") self.builder.get_object('window1').connect('delete-event',Gtk.main_quit) self.dialog=self.builder.get_object('dialog1') self.dialog.get_style_context().add_class(Gtk.STYLE_CLASS_PRIMARY_TOOLBAR) self.dialog2=self.builder.get_object('dialog2') self.dialog2.get_style_context().add_class(Gtk.STYLE_CLASS_PRIMARY_TOOLBAR) self.dialog3 = self.builder.get_object("dialog3") self.dialog3.get_style_context().add_class(Gtk.STYLE_CLASS_PRIMARY_TOOLBAR) self.window = self.builder.get_object("window1") self.window.get_style_context().add_class(Gtk.STYLE_CLASS_PRIMARY_TOOLBAR) self.progressbar= self.builder.get_object("progressbar1") #PROGRESSBAR self.progressbar.get_style_context().add_class(Gtk.STYLE_CLASS_PRIMARY_TOOLBAR) self.aboutdialog = self.builder.get_object("aboutdialog1") self.aboutdialog.get_style_context().add_class(Gtk.STYLE_CLASS_PRIMARY_TOOLBAR) self.label = self.builder.get_object("label1") self.builder.get_object("filechooserbutton2").set_action(Gtk.FileChooserAction.SELECT_FOLDER) #filechooser 2 self.search_field = self.builder.get_object("search_field") self.search_field.get_style_context().add_class(Gtk.STYLE_CLASS_PRIMARY_TOOLBAR) self.dow_label = self.builder.get_object("dow_speed")
def on_module_selected(self): if self.loaded: return print("Loading Notifications module") Notify.init("cinnamon-settings-notifications-test") page = SettingsPage() self.sidePage.add_widget(page) settings = page.add_section(_("Notification settings")) switch = GSettingsSwitch(_("Enable notifications"), "org.cinnamon.desktop.notifications", "display-notifications") settings.add_row(switch) switch = GSettingsSwitch(_("Remove notifications after their timeout is reached"), "org.cinnamon.desktop.notifications", "remove-old") settings.add_reveal_row(switch, "org.cinnamon.desktop.notifications", "display-notifications") switch = GSettingsSwitch(_("Show notifications on the bottom side of the screen"), "org.cinnamon.desktop.notifications", "bottom-notifications") settings.add_reveal_row(switch, "org.cinnamon.desktop.notifications", "display-notifications") button = Button(_("Display a test notification"), self.send_test) settings.add_row(button) settings = page.add_section(_("Media keys OSD")) combo = GSettingsComboBox(_("Media keys OSD size"), "org.cinnamon", "show-media-keys-osd", MEDIA_KEYS_OSD_SIZES) settings.add_row(combo)
def get_cpu_speeds(self): message = '' try: r = requests.post('https://www-wohnheim.uni-regensburg.de/utils/login.py/checkAuthentication', data=payload) soup = BeautifulSoup(r.text) title = soup.findAll('title')[0].get_text() login_page = title.find('Login')>0 if(login_page): notify.init('indicator-cpuspeed') notify.Notification.new("<b>Login failed</b>", "<b>Change password?</b>", None).show() notify.uninit() rzdatatable = soup.find("table", {"id": "rzdatatable"}) data = rzdatatable.findAll('tr')[1] wohnheim = data.findAll('td')[0].get_text() zimmer = data.findAll('td')[1].get_text() status = data.findAll('td')[2].span.get_text() empfangen = data.findAll('td')[3].get_text() gesendet = data.findAll('td')[4].get_text() summe = data.findAll('td')[5].get_text() limit = data.findAll('td')[6].get_text() # print(wohnheim + "(" + zimmer + "), status: " + status) # print("Volumen: " + str(summe) + "mb von " + str(limit) + "mb (" + str(round(100*float(summe)/float(limit),2)) + "%), davon " + gesendet + "mb gesendet und " + empfangen + "mb empfangen.") message = str(summe) except requests.ConnectionError: message = 'No Connection' return message
def __init__(self, colors): super().__init__() # Save config self.__colors = colors # Start lemonbar in a subprocess self.__bar = subprocess.Popen(['lemonbar', '-B', colors['bg'], '-F', colors['fg'], '-f', "Terminesspowerline-8", '-f', "Ionicons-10", '-f', 'Icons-8', '-f', 'FontAwesome-10', '-f', "Serif-9", '-a', '30' ], stdin=subprocess.PIPE, stdout=subprocess.PIPE) # Init notifier for displaying volume stats with dunst Notify.init('bar') # Panel variables to save intermediate states self.__calendar = None self.__volume = None self.__vpn = None self.__state = None self.__spotify = None self.spotify_callback_value = None self.keyboard_callback_value = None self.status = {'date':'', 'spotify':'', 'vol':'', 'wlan':'', 'eth':'', 'vpn':'', 'bat':''} self.workspaces = '' self.title = '' self.current_power = '' self.old_power = '' # Status toggles self.__show_eth = False self.__show_wlan = False self.__show_battery = False self.__show_spotify = False self.__run = True
def prepare_notify(self): try: from gi.repository import Notify self.has_notifications = True except ImportError: logging.warning ("libnotify not found.") return "libnotify not found" # Work-around Ubuntu's incompatible workaround for Gnome's API breaking mistake. # https://bugzilla.gnome.org/show_bug.cgi?id=702390 old_add_action = Notify.Notification.add_action def new_add_action(*args): try: old_add_action(*args) except TypeError: old_add_action(*(args + (None,))) Notify.Notification.add_action = new_add_action Notify.init('Pithos') self.notification = Notify.Notification() self.notification.set_category('x-gnome.music') self.notification.set_hint_string('desktop-icon', 'pithos') caps = Notify.get_server_caps() if 'actions' in caps: logging.info('Notify supports actions') self.supports_actions = True if 'body-markup' in caps: self.escape_markup = True if 'action-icons' in caps: self.notification.set_hint('action-icons', GLib.Variant.new_boolean(True))
def abort_refresh(self, message, description): """Updates menu with failure state message.""" # Remove previous message if already exists if (len(self.menuItems) > 4): self.menuItems.pop(2) self.menuItems.pop(1) self.menuItems.insert(2, gtk.MenuItem(message)) self.menuItems.insert(3, gtk.SeparatorMenuItem()) self.menuItems[2].set_sensitive(False) # Re-enable "Check now" button self.menuItems[0].set_sensitive(True) self.menuItems[0].set_label("Check now") # Refresh all menu items for i in self.menu.get_children(): self.menu.remove(i) for i in self.menuItems: self.menu.append(i) self.menu.show_all() # Push notification Notify.init("image") self.n = Notify.Notification.new(message, description, "error" ).show()
def somethingFinished(self, subject, body, soundfile): timerSound = os.path.join(os.path.dirname(__file__), soundfile) Notify.init("Timer finished") notification = Notify.Notification.new (subject, body, NOTIFICATION_ICON) notification.set_urgency(Notify.Urgency.CRITICAL) notification.show() subprocess.Popen(["paplay", timerSound])
def notify_bat_low(): print '\nBattery is at ' + str(bat_percentage()) + '%\n' Notify.init('Battery low!') message=Notify.Notification.new('Battery low!', 'Battery is at ' + str(bat_percentage()) + '%', '/usr/share/icons/gnome/32x32/status/battery-empty.png') message.show()
def __init__(self): dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) self.bus = dbus.SessionBus() self.bus.add_signal_receiver( self.notify, signal_name="IrssiNotify", dbus_interface="org.irssi.Irssi", path="/org/irssi/Irssi" ) Notify.init("irssi")
def process_selection(self, filelist): self.conf.read(self.configfile) # Run in Preview Mode if self.conf.get(c, "preview_mode") == "True": if filelist != []: prelist = os.getenv('HOME') + '/.fileorganizer-preview.log' FILE = open(prelist, "w") FILE.close() damlist = os.getenv('HOME') + '/.fileorganizer-damaged.log' FILE = open(damlist, "w") FILE.close() for item in filelist: item = fileops.MusicFile(self, item) item.preview() Notify.init('Fileorganizer') title = 'Fileorganizer' note = 'Preview Has Completed' notification = Notify.Notification.new(title, note, None) Notify.Notification.show(notification) # Show Results of preview self.results(prelist, damlist) else: # Run Normally self.organize(filelist) Notify.init('Fileorganizer') title = 'Fileorganizer' note = 'Your selection is organised' notification = Notify.Notification.new(title, note, None) Notify.Notification.show(notification)
def fire_notify(self, msg="", title="GitPushNotify", add_callback=None, path=None): # raise Exception(999) Notify.init("New commit") self.log.info("Called fireNotify()") try: # n = notify2.Notification(title, msg, '') n = Notify.Notification.new(title, msg) if len(self.nn) > 10: self.nn = [] self.nn.append(n) self.log.info("append data") n.set_urgency(1) self.log.info("set_urgency") if add_callback: self.log.info("add callback ") n.connect("closed", self.empty_cb) n.add_action("clicked", " pull all branches ", self.call_back_fire, path) self.log.info("show") try: n.show() except Exception as e: self.log.info("error while show: %s" % e) else: self.log.info("showed") finally: self.log.info("end show") except Exception as e: self.log.info("error in firenotify: %s" % e) traceback.print_exc() else: self.log.info("ok firenotify")
def time_manager(work_seconds, sleep_seconds): mm = MouseManager() km = KeyboardManager() Notify.init("time manager") while True: time.sleep(work_seconds) mm.disable_mouse() km.disable_keyboard() message = Notify.Notification.new("äø»ä»»ļ¼ čÆ„ä¼ęÆäŗļ¼", 'Time to sleep!!!', 'dialog-information') message.show() # There's a bug in disabling mouse delta = 5 m_sleep_seconds = sleep_seconds while m_sleep_seconds > 0: mm.disable_mouse() if m_sleep_seconds >= delta: time.sleep(delta) m_sleep_seconds -= delta else: time.sleep(m_sleep_seconds) break mm.enable_mouse() km.enable_keyboard()
def __init__(self, token=None): self.indicator = AppIndicator3.Indicator.new( 'digitalocean-indicator', '', AppIndicator3.IndicatorCategory.APPLICATION_STATUS) self.indicator.set_status(AppIndicator3.IndicatorStatus.ACTIVE) icon_uri = get_media_file("digitalocean-indicator.svg") icon_path = icon_uri.replace("file:///", '') self.indicator.set_icon(icon_path) Notify.init('DigitalOcean Indicator') self.PreferencesDialog = DoPreferencesDialog self.settings = Gio.Settings( "com.andrewsomething.digitalocean-indicator") self.settings.connect('changed', self.on_preferences_changed) self.preferences_dialog = None self.preferences_changed = False if token: self.do_api_token = token else: self.do_api_token = self.settings.get_string("do-api-token") self.menu = Gtk.Menu() # Add items to Menu and connect signals. self.build_menu() # Refresh menu every 10 min by default self.change_timeout = False self.interval = self.settings.get_int("refresh-interval") GLib.timeout_add_seconds(self.interval * 60, self.timeout_set)
def autoSuspender(self, minPercent=5): # update even full capacity in case the battery has been changed self.full = int(cat("/sys/class/power_supply/BAT0/energy_full")) self.update() # hibernate only if battery is discharging if self.state != "Discharging": return {} # return empty dict, main loop expects it # test if everything is OK for var in (self.full, self.now, self.state, self.percent): if var is None: return {} # return empty dict, main loop expects it # test battery level if self.percent <= minPercent: Notify.init("Hibernation") battLevel = Notify.Notification.new("Warning:", "Battery level at " + str(self.percent) + "%.", "") battLevel.set_urgency(Notify.Urgency.CRITICAL) battLevel.show() warning = Notify.Notification.new("Warning:", "Hibernation in 10 seconds...", "") warning.set_urgency(Notify.Urgency.CRITICAL) warning.show() time.sleep(10) battLevel.close() warning.close() Notify.uninit() subprocess.call("systemctl hibernate", shell=True) return {} # return empty dict, main loop expects it
def __init__(self): # Create variables # See how to define this in a better way # (But for now 0 - ReadyToWork, 1 - Working, 2 - ReadyToBreak, 3 - InBreak) self.state = 0 self.work_value = 0 self.break_value = 0 self.timer_value = 0 self.read_options_file() self.counter_timeout_id = 0 # Define icons and notifications by state self.icon_by_state = {0: 'work_gray', 1: 'work_red', 2: 'break_gray', 3: 'break_green'} self.notification_by_state = {1: 'Your work time is over. You should take a break!', 3: 'Your break is over. Ready to get back to work?'} self.icons_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'icons/') # Create the Indicator instance self.ind = appindicator.Indicator.new_with_path( "pTimer", "work_gray", appindicator.IndicatorCategory.APPLICATION_STATUS, self.icons_path) self.ind.set_status(appindicator.IndicatorStatus.ACTIVE) self.ind.set_label(self.get_time_string(), "00:00:00") # Init notifications notify.init('pTimer') # Init menu class self.menu = PMenu(self) self.options_window = None
def __init__(self): cfg = fedmsg.config.load_config(None, []) moksha_options = { self.config_key: True, "zmq_subscribe_endpoints": ','.join( ','.join(bunch) for bunch in cfg['endpoints'].values() ), } cfg.update(moksha_options) moksha.hub.setup_logger(verbose=True) # Despite what fedmsg.config might say about what consumers are enabled # and which are not, we're only going to let the central moksha hub know # about *our* consumer. By specifying this here, it won't even check # the entry-points list. consumers, prods = [self], [] moksha.hub._hub = moksha.hub.CentralMokshaHub(cfg, consumers, prods) fedmsg.consumers.FedmsgConsumer.__init__(self, moksha.hub._hub) self.session_bus = dbus.SessionBus() bus_name = dbus.service.BusName(self.bus_name, bus=self.session_bus) dbus.service.Object.__init__(self, bus_name, self._object_path) Notify.init("fedmsg") Notify.Notification.new("fedmsg", "activated", "").show()
def __init__(self, title=""): Gtk.Window.__init__(self, title=title) self.connect('delete-event', Gtk.main_quit) DBusGMainLoop(set_as_default=True) self._bus = dbus.SessionBus() self._daemon = self._bus.get_object(DBUS_BUS_NAME, DBUS_DAEMON_PATH) self._daemon_i = dbus.Interface(self._daemon, DBUS_BUS_NAME) self._daemon.connect_to_signal('state_changed', self._state_changed_handler) Notify.init("Pymodoro") self.status_icon = Gtk.StatusIcon.new_from_file(self.get_icon()) self.status_icon.connect("popup-menu", self._right_click_handler) self.menu = Gtk.Menu() self.mi_start = Gtk.MenuItem() self.mi_start.set_label("Start") self.mi_stop = Gtk.MenuItem() self.mi_stop.set_label("Interrupt") self.mi_quit = Gtk.MenuItem() self.mi_quit.set_label("Quit") self.mi_start.connect("activate", self._daemon_i.start_pomodoro) self.mi_stop.connect("activate", self._daemon_i.reset_pomodoro) self.mi_quit.connect("activate", Gtk.main_quit) self.menu.append(self.mi_start) self.menu.append(self.mi_stop) self.menu.append(self.mi_quit) self._menu_setup()
def let_it_rain(): GObject.threads_init() Gst.init(None) signal.signal(signal.SIGINT, signal.SIG_DFL) Notify.init("silver-rain") # Create system directories if not os.path.exists(IMG_DIR): os.makedirs(IMG_DIR) # Initialize config config.setup() # Create directory for recordings if not os.path.exists(config.recs_dir): os.makedirs(config.recs_dir) # Load css css_load() # Init translation set_translation() # Init application silver_app = SilverApp() # Setup dbus service service = SilverService(silver_app) # Run loop Gtk.main() # Cleanup silver_app.clean() Notify.uninit()
def OnInit(self): Notify.init(Constants.APP_NAME)
from gi.repository import Notify import os Notify.init("SMS") Hello = Notify.Notification.new("BaÅlık", "Mesaj", os.path.dirname(os.path.realpath(__file__))+ "/icon.png") Hello.show()
def main(self): notify.init(self.indicator_id) self.init_clipboard() Gtk.main()
# TODO add command line options for wallpaper directory, stack location, max # stack size import os import sys import pickle import collections import random import subprocess import pathlib import shutil import gi gi.require_version('Notify', '0.7') from gi.repository import Notify Notify.init("backgrounds") WALLPAPERS = pathlib.Path.home() / "Pictures" / "wallpapers" if os.getenv("XDG_CACHE_HOME"): CACHE_HOME = pathlib.Path(os.getenv("XDG_CACHE_HOME")) else: CACHE_HOME = pathlib.Path.home() / ".cache" STACK = CACHE_HOME / "randombg" / "stack.pickle" MAX_STACK = 100 def ensure_cache(): """ Ensure an appropriate directory to write the cache file to exists. """ if not STACK.exists():
class BottlesWindow(Gtk.ApplicationWindow): __gtype_name__ = 'BottlesWindow' ''' Get and assign widgets to variables from template childs ''' grid_main = Gtk.Template.Child() stack_main = Gtk.Template.Child() btn_back = Gtk.Template.Child() btn_add = Gtk.Template.Child() btn_list = Gtk.Template.Child() btn_preferences = Gtk.Template.Child() btn_download_preferences = Gtk.Template.Child() btn_about = Gtk.Template.Child() btn_downloads = Gtk.Template.Child() btn_menu = Gtk.Template.Child() btn_translate = Gtk.Template.Child() btn_support = Gtk.Template.Child() btn_noconnection = Gtk.Template.Child() switch_dark = Gtk.Template.Child() box_downloads = Gtk.Template.Child() pop_downloads = Gtk.Template.Child() ''' Define environments and select the first by default ''' envs = ['Gaming', 'Software', 'Custom'] env_active = envs[0] ''' Common variables ''' previous_page = "" default_settings = Gtk.Settings.get_default() settings = Gio.Settings.new(APP_ID) ''' Initializing Notify ''' Notify.init(APP_ID) def __init__(self, **kwargs): super().__init__(**kwargs) ''' Initialize template ''' self.init_template() self.default_settings.set_property("gtk-application-prefer-dark-theme", THEME_DARK) self.utils_conn = UtilsConnection(self) ''' Create a runner instance ''' self.runner = BottlesRunner(self) ''' Get and assign pages to variables ''' page_add = BottlesAdd(self) page_add_details = BottlesAddDetails(self) page_details = BottlesDetails(self) page_list = BottlesList(self) page_create = BottlesCreate(self) page_preferences = BottlesPreferences(self) ''' Set reusable variables ''' self.page_add_details = page_add_details self.page_create = page_create self.page_preferences = page_preferences self.page_list = page_list self.page_details = page_details ''' Add pages to stack and set options ''' self.stack_main.set_transition_type(Gtk.StackTransitionType.CROSSFADE) self.stack_main.set_transition_duration(ANIM_DURATION) self.stack_main.add_titled(page_add, "page_add", "New Bottle") self.stack_main.add_titled(page_create, "page_create", "Create Bottle") self.stack_main.add_titled(page_add_details, "page_add_details", "New Bottle details") self.stack_main.add_titled(page_details, "page_details", "Bottle details") self.stack_main.add_titled(page_list, "page_list", "Bottles") self.stack_main.add_titled(page_preferences, "page_preferences", "Preferences") ''' Add widgets to main grid ''' self.grid_main.attach(self.stack_main, 0, 1, 1, 1) ''' Connect signals to widgets ''' self.btn_back.connect('pressed', self.go_back) self.btn_add.connect('pressed', self.show_add_view) self.btn_list.connect('pressed', self.show_list_view) self.btn_about.connect('pressed', self.show_about_dialog) self.btn_support.connect('pressed', self.open_support_url) self.btn_translate.connect('pressed', self.open_translate_url) self.btn_preferences.connect('pressed', self.show_preferences_view) self.btn_download_preferences.connect( 'pressed', self.show_download_preferences_view) self.btn_noconnection.connect('pressed', self.check_for_connection) self.switch_dark.connect('state-set', self.toggle_dark) ''' Set widgets status from user settings ''' self.switch_dark.set_active(self.settings.get_boolean("dark-theme")) ''' Load startup view from user settings ''' self.stack_main.set_visible_child_name( self.settings.get_string("startup-view")) ''' This method sould be executed as last ''' self.on_start() def check_for_connection(self, status): if self.utils_conn.check_connection(): self.runner.checks() ''' Toggle btn_noconnection visibility for display connection issues ''' def toggle_btn_noconnection(self, status): self.btn_noconnection.set_visible(status) ''' This method should be called after window shown ''' def on_start(self): ''' Check if there is at least 1 runner in the system ''' if len(self.runner.runners_available) == 0: message = "There are no Runners in the system. " if self.utils_conn.check_connection(): message += "Proceed with the installation of the latest version?" else: message += "But you don't seem to be connected to the internet and you won't be able to download a runner. Connect to the internet and confirm this message to begin the download." dialog_checks = BottlesDialog(parent=self, title="No runners found", message=message) response = dialog_checks.run() if response == Gtk.ResponseType.OK: logging.info("OK status received") ''' Performs runner checks ''' self.runner.checks() else: logging.info("Cancel status received") dialog_checks.destroy() ''' TODO: Else check for updates ''' ''' Toggle UI usability, this method should be used when performing delicate operations, like new bottle creation ''' def set_usable_ui(self, status): for widget in [ self.btn_back, self.btn_add, self.btn_list, self.btn_download_preferences, self.btn_menu ]: widget.set_sensitive(status) ''' Request a new notification to the Notify instance ''' def send_notification(self, title, text, image=""): notification = Notify.Notification.new(title, text, image) notification.show() ''' Save the previous page to allow the user to go back ''' def set_previous_page_status(self): current_page = self.stack_main.get_visible_child_name() if current_page in ["page_add_details", "page_create"]: current_page = "page_add" if self.previous_page != current_page: self.previous_page = current_page self.btn_back.set_visible(True) ''' Open URLs ''' def open_translate_url(self, widget): webbrowser.open_new_tab( "https://github.com/bottlesdevs/Bottles/tree/develop") def open_support_url(self, widget): webbrowser.open_new_tab( "https://github.com/bottlesdevs/Bottles/issues") ''' Return to previous page ''' def go_back(self, widget): self.btn_back.set_visible(False) self.stack_main.set_visible_child_name(self.previous_page) def show_add_view(self, widget): self.stack_main.set_visible_child_name("page_add") def show_list_view(self, widget): self.stack_main.set_visible_child_name("page_list") def show_preferences_view(self, widget, view=0): self.set_previous_page_status() self.page_preferences.notebook_preferences.set_current_page(view) self.stack_main.set_visible_child_name("page_preferences") def show_download_preferences_view(self, widget=False): self.show_preferences_view(widget, view=1) def show_runners_preferences_view(self, widget=False): self.show_preferences_view(widget, view=2) def show_about_dialog(self, widget): BottlesAboutDialog().show_all() ''' Toggle dark mode and store status in settings ''' def toggle_dark(self, widget, state): self.settings.set_boolean("dark-theme", state) self.default_settings.set_property("gtk-application-prefer-dark-theme", state)
import os import re import sys import subprocess import gi gi.require_version('Notify', '0.7') from gi.repository import Gio from gi.repository import Gdk from gi.repository import Notify from gi.repository import GdkPixbuf from draobpilc import get_data_path from draobpilc.version import APP_NAME Notify.init(APP_NAME) simple_url_re = re.compile(r'^https?://\[?\w', re.IGNORECASE) simple_url_2_re = re.compile( r'^www\.|^(?!http)\w[^@]+\.(com|edu|gov|int|mil|net|org)($|/.*)$', re.IGNORECASE) class SettingsSchemaNotFound(Exception): """ """ class NotifyAction(): def __init__(self, id_, label, user_data=None, callback=None): if not isinstance(id_, str): raise ValueError('id_ must be a string')
import gi gi.require_version('Notify', '0.7') from gi.repository import Notify import sys sys.path.insert(0, '/home/akshat/Desktop/Task_manager/DB_Manipulation') import DB_Manipulation Notify.init("Task Notifier") notificationHeading = "Tasks for today are: " notification = Notify.Notification.new( notificationHeading, "", ) def showTasks(day=""): notificationHeading = "Tasks for today are: " if day == "": task_list = DB_Manipulation.getTasks() else: task_list = DB_Manipulation.getTasks(day) if len(task_list) <= 0: return tasks = "" for i, task in zip(range(1, len(task_list) + 1), task_list): tasks = tasks + str(i) + ". " + str(task) + "\n" if day == "": notification.update(notificationHeading, tasks)
import logging import subprocess import sys import gi import os gi.require_version('Gdk', '3.0') gi.require_version('Gtk', '3.0') gi.require_version('Notify', '0.7') from gi.repository import Gdk, Gtk, Notify, GObject from time import sleep from distutils.spawn import find_executable as findExec logger = logging.getLogger('ulauncher-clipboard') Notify.init('ulauncher-clipboard-extension') def execGet(*args): return subprocess.check_output(list(args)).rstrip().decode('utf-8') def tryOr(function, args, fallback=None): try: return function(*args) except Exception: return fallback def tryInt(string, fallback=0): return tryOr(int, [string, 10], fallback)
def cast_list(self): self.set_icon_idle() if len(self.available_devices) == 0: self.menu.clear() self.search_menu() self.separator_menu() self.NodevAction = self.menu.addAction("No Streaming Devices Found.") self.set_icon_nodev() self.separator_menu() self.stop_menu() self.volume_menu() self.resetaudio_menu() self.reboot_menu() self.separator_menu() self.preferences_menu() self.update_menu() self.about_menu() self.exit_menu() else: self.read_config() if platform == "Darwin" and self.notifications == "enabled": if ( os.path.exists("images/" + self.google[self.colors] + ".icns") is True ): noticon = "images/" + self.google[self.colors] + ".icns" else: noticon = self.google[self.colors] + ".icns" found = [ "./notifier/terminal-notifier.app/Contents/MacOS/terminal-notifier", "-group", "cast", "-contentImage", noticon, "-title", "Mkchromecast", "-message", "Media Streaming Devices Found!", ] subprocess.Popen(found) if debug is True: print(":::systray:::", found) elif platform == "Linux" and self.notifications == "enabled": try: import gi gi.require_version("Notify", "0.7") from gi.repository import Notify Notify.init("Mkchromecast") found = Notify.Notification.new( "Mkchromecast", "Media Streaming Devices Found!", "dialog-information", ) found.show() except ImportError: print( "If you want to receive notifications in Linux, " "install libnotify and python-gobject" ) self.menu.clear() self.search_menu() self.separator_menu() print("Available Media Streaming Devices", self.available_devices) for index, menuentry in enumerate(self.available_devices): try: a = self.ag.addAction( (QtWidgets.QAction(str(menuentry[1]), self, checkable=True)) ) self.menuentry = self.menu.addAction(a) except UnicodeEncodeError: a = self.menuentry = self.menu.addAction( str(unicode(menuentry[1]).encode("utf-8")) ) # The receiver is a lambda function that passes clicked as # a boolean, and the clicked_item as an argument to the # self.clicked_cc() method. This last method, sets the correct # index and name of the chromecast to be used by # self.play_cast(). Credits to this question in stackoverflow: # # http://stackoverflow.com/questions/1464548/pyqt-qmenu-dynamically-populated-and-clicked receiver = lambda clicked, clicked_item=menuentry: self.clicked_cc( clicked_item ) a.triggered.connect(receiver) self.separator_menu() self.stop_menu() self.volume_menu() self.resetaudio_menu() self.reboot_menu() self.separator_menu() self.preferences_menu() self.update_menu() self.about_menu() self.exit_menu()
def __init__(self, function_restart, function_pause, function_quit, update_sleep_length=0.2, icon_paused="", icon_default=""): self.appindicator = AppIndicator3.Indicator.new_with_path( "unison-indicator", "sync-default", AppIndicator3.IndicatorCategory.SYSTEM_SERVICES, os.path.dirname(os.path.realpath(__file__)) + "/icons") self.appindicator.set_status(AppIndicator3.IndicatorStatus.ACTIVE) Notify.init("unison-indicator") self.notification = Notify.Notification.new( "<b>Unison</b>", "", None) # balloon notification # settings: self.update_sleep_length = update_sleep_length self.icon_paused = icon_paused self.icon_default = icon_default # internal data: self.status_list = collections.deque(maxlen=20) self.error_list = collections.deque(maxlen=10) self.file_list = collections.deque(maxlen=30) self.status_list_lock = threading.Lock() self.file_list_lock = threading.Lock() self.error_list_lock = threading.Lock() self.icon = "" self.notifytext = "" self.notifyheading = "" self.notifyicon = "" # Menu self.menu = Gtk.Menu() self.menu_file_list = Gtk.Menu() self.menu_error_list = Gtk.Menu() self.item_start = Gtk.MenuItem('Restart') self.item_pause = Gtk.MenuItem('Pause/abort') self.item_quit = Gtk.MenuItem('Quit') self.item_file_list = Gtk.MenuItem('Recently changed files') self.item_error_list = Gtk.MenuItem('Error log') self.menu_file_list.append(Gtk.MenuItem('--')) self.menu_error_list.append(Gtk.MenuItem('--')) self.item_status = Gtk.MenuItem('') self.item_status.connect('activate', self.show_status_in_dialog) self.item_start.connect('activate', function_restart) self.item_pause.connect('activate', function_pause) self.item_quit.connect('activate', function_quit) self.item_file_list.set_submenu(self.menu_file_list) self.item_error_list.set_submenu(self.menu_error_list) menu_items = [ self.item_status, self.item_file_list, self.item_error_list, Gtk.SeparatorMenuItem(), self.item_start, self.item_pause, self.item_quit ] for item in menu_items: self.menu.append(item) self.appindicator.set_menu(self.menu) self.menu.show_all() # Auxiliary variables: self.icon_blink_counter = 0 self.update_event = threading.Event() self.update_thread = threading.Thread(target=self.__wait_for_updates) self.update_thread.daemon = True self.update_thread.start() self.new_status("Initializing ...") self.__set_state(Indicator.STATE_RUNNING)
def cast_list(self): self.set_icon_idle() if len(self.availablecc) == 0: self.menu.clear() self.search_menu() self.separator_menu() self.NodevAction = self.menu.addAction( 'No Streaming Devices Found.') self.set_icon_nodev() self.separator_menu() self.stop_menu() self.volume_menu() self.resetaudio_menu() self.reboot_menu() self.separator_menu() self.preferences_menu() self.update_menu() self.about_menu() self.exit_menu() else: self.read_config() if platform == 'Darwin' and self.notifications == 'enabled': if os.path.exists('images/' + self.google[self.colors]+'.icns') is True: noticon = 'images/'+self.google[self.colors]+'.icns' else: noticon = self.google[self.colors]+'.icns' found = [ './notifier/terminal-notifier.app/Contents/MacOS/terminal-notifier', '-group', 'cast', '-contentImage', noticon, '-title', 'Mkchromecast', '-message', 'Media Streaming Devices Found!' ] subprocess.Popen(found) if debug is True: print(':::systray:::', found) elif platform == 'Linux' and self.notifications == 'enabled': try: import gi gi.require_version('Notify', '0.7') from gi.repository import Notify Notify.init('Mkchromecast') found = Notify.Notification.new( 'Mkchromecast', 'Media Streaming Devices Found!', 'dialog-information' ) found.show() except ImportError: print('If you want to receive notifications in Linux, ' 'install libnotify and python-gobject') self.menu.clear() self.search_menu() self.separator_menu() print('Available Media Streaming Devices', self.availablecc) for index, menuentry in enumerate(self.availablecc): try: a = self.ag.addAction( (QtWidgets.QAction( str(menuentry[1]), self, checkable=True))) self.menuentry = self.menu.addAction(a) except UnicodeEncodeError: a = self.menuentry = self.menu.addAction(str( unicode(menuentry[1]).encode("utf-8"))) # The receiver is a lambda function that passes clicked as # a boolean, and the clicked_item as an argument to the # self.clicked_cc() method. This last method, sets the correct # index and name of the chromecast to be used by # self.play_cast(). Credits to this question in stackoverflow: # # http://stackoverflow.com/questions/1464548/pyqt-qmenu-dynamically-populated-and-clicked receiver = lambda clicked, clicked_item=menuentry: self.clicked_cc(clicked_item) a.triggered.connect(receiver) self.separator_menu() self.stop_menu() self.volume_menu() self.resetaudio_menu() self.reboot_menu() self.separator_menu() self.preferences_menu() self.update_menu() self.about_menu() self.exit_menu()
def stop_cast(self): if self.stopped is False: pass if self.cast is not None or self.stopped is True or self.pcastfailed is True: try: self.cast.quit_app() except AttributeError: # This is for sonos. The thing is that if we are at this point, # user requested an stop or cast failed. self.cast.stop() self.reset_audio() try: self.kill_child() except psutil.NoSuchProcess: pass checkmktmp() self.search_cast() # This is to retry when stopping and # pychromecast.error.NotConnected raises. if chromecast: while True: try: self.cast.quit_app() except pychromecast.error.NotConnected: continue except AttributeError: # This is for sonos. The thing is that if we are at this # point, user requested an stop or cast failed. self.cast.stop() break self.stopped = True self.read_config() if platform == "Darwin" and self.notifications == "enabled": if self.pcastfailed is True: stop = [ "./notifier/terminal-notifier.app/Contents/MacOS/terminal-notifier", "-group", "cast", "-title", "Mkchromecast", "-message", "Streaming Process Failed. Try Again...", ] else: stop = [ "./notifier/terminal-notifier.app/Contents/MacOS/terminal-notifier", "-group", "cast", "-title", "Mkchromecast", "-message", "Streaming Stopped!", ] subprocess.Popen(stop) if debug is True: print(":::systray::: stop", stop) elif platform == "Linux" and self.notifications == "enabled": try: import gi gi.require_version("Notify", "0.7") from gi.repository import Notify Notify.init("Mkchromecast") if self.pcastfailed is True: stop = Notify.Notification.new( "Mkchromecast", "Streaming Process Failed. Try Again...", "dialog-information", ) else: stop = Notify.Notification.new( "Mkchromecast", "Streaming Stopped!", "dialog-information" ) stop.show() except ImportError: print( "If you want to receive notifications in Linux, " "install libnotify and python-gobject" )
team_name = team.get_text() print(team.get_text()) curr_score = team.get_text() curr_score = curr_score + ' ' while (True): page = urllib2.urlopen(url) soup = BeautifulSoup(page.read(), 'html.parser') f = 0 for score in soup.find_all(class_='scr'): print("current live score derived from yahoo cricket is :") curr_score = curr_score + score.get_text() f = 1 #print(score.get_text()) # check to bring parser to 0 if (f == 1): curr_score = str(curr_score) else: curr_score = str(0) Notify.init("Score") Hello = Notify.Notification.new("The score is ", curr_score, "dialog-notification") Hello.show() #change the time for pop up notifications below time.sleep(25.0) curr_score = team.get_text() curr_score = curr_score + ' '
def stop_cast(self): if self.stopped is False: pass if (self.cast is not None or self.stopped is True or self.pcastfailed is True): try: self.cast.quit_app() except AttributeError: # This is for sonos. The thing is that if we are at this point, # user requested an stop or cast failed. self.cast.stop() self.reset_audio() try: self.kill_child() except psutil.NoSuchProcess: pass checkmktmp() self.search_cast() # This is to retry when stopping and # pychromecast.error.NotConnected raises. while True: try: self.cast.quit_app() except pychromecast.error.NotConnected: continue except AttributeError: # This is for sonos. The thing is that if we are at this # point, user requested an stop or cast failed. self.cast.stop() break self.stopped = True self.read_config() if platform == 'Darwin' and self.notifications == 'enabled': if self.pcastfailed is True: stop = [ './notifier/terminal-notifier.app/Contents/MacOS/terminal-notifier', '-group', 'cast', '-title', 'Mkchromecast', '-message', 'Streaming Process Failed. Try Again...' ] else: stop = [ './notifier/terminal-notifier.app/Contents/MacOS/terminal-notifier', '-group', 'cast', '-title', 'Mkchromecast', '-message', 'Streaming Stopped!' ] subprocess.Popen(stop) if debug is True: print(':::systray::: stop', stop) elif platform == 'Linux' and self.notifications == 'enabled': try: import gi gi.require_version('Notify', '0.7') from gi.repository import Notify Notify.init('Mkchromecast') if self.pcastfailed is True: stop = Notify.Notification.new( 'Mkchromecast', 'Streaming Process Failed. Try Again...', 'dialog-information' ) else: stop = Notify.Notification.new( 'Mkchromecast', 'Streaming Stopped!', 'dialog-information' ) stop.show() except ImportError: print('If you want to receive notifications in Linux, ' 'install libnotify and python-gobject')
def notification(conversation, author, message): Notify.init("Bla Chat") MsgNotification = Notify.Notification.new("Bla - " + conversation, "(" + author + ") " + message, "dialog-information") MsgNotification.show()
from gi.repository import Notify Notify.init('ulauncher') def show_notification(summary, body, icon='ulauncher'): """ :rtype: :class:`Notify.Notification` """ Notify.Notification.new(summary, body, icon).show()
import util gi.require_version('Champlain', '0.12') gi.require_version('Gtk', "3.0") gi.require_version('GtkChamplain', '0.12') gi.require_version('GtkClutter', '1.0') gi.require_version('Notify', '0.7') from gi.repository import Gtk from gi.repository import Gio from gi.repository import Notify from gi.repository import GtkClutter, Clutter from gi.repository import Champlain, GtkChamplain GtkClutter.init([]) Notify.init("Geocaching App") # Cache 1000000 tiles in ~/.cache CACHE_SIZE = 1000000 # Cache 200 tiles in memory MEMORY_CACHE_SIZE = 200 ICON_FILE = "/usr/share/pixmaps/geocachingapp.png" class LoginScreen(Gtk.ApplicationWindow): def __init__(self, app): Gtk.ApplicationWindow.__init__(self, title="GeoCaching Login", application=app) self.set_title('GeoCaching Login')
def show(): sleep(1) detected_os = sys.platform if detected_os == "linux": Notify.init("openpyn") while True: try: s = socket_connect('localhost', 7015) except ConnectionRefusedError: sleep(3) continue break try: # Create the notification object and show once summary = "Openpyn" body = "Initiating connection (If stuck here, try again)" if detected_os == "linux": notification = Notify.Notification.new(summary, body) notification.show() elif detected_os == "darwin": os.system( """osascript -e 'display notification "{}" with title "{}"'""". format(body, summary)) server_name = "" last_status_UP = False while True: data = s.recv(1024) data_str = repr(data) # print(data_str) # if 'UPDOWN:DOWN' or 'UPDOWN:UP' or 'INFO' in data_str: if 'UPDOWN:UP' in data_str: last_status_UP = True # print ('Received AN UP') if 'UPDOWN:DOWN' in data_str: last_status_UP = False # print ('Received A DOWN', data_str) body = "Connection Down, Disconnected." if detected_os == "linux": notification.update(summary, body) # Show again notification.show() elif detected_os == "darwin": os.system( """osascript -e 'display notification "{}" with title "{}"'""" .format(body, summary)) server_name_location = data_str.find("common_name=") # print(server_name_location) if server_name_location != -1 and last_status_UP is True: server_name_start = data_str[server_name_location + 12:] server_name = server_name_start[:server_name_start.find(".com" ) + 4] # print("Both True and server_name", server_name) body = "Connected! to " + server_name if detected_os == "linux": notification.update(summary, body) # Show again notification.show() elif detected_os == "darwin": os.system( """osascript -e 'display notification "{}" with title "{}"'""" .format(body, summary)) # break of data stream is empty if not data: break except (KeyboardInterrupt) as err: body = "Disconnected, Bye." if detected_os == "linux": notification.update(summary, body) notification.show() elif detected_os == "darwin": os.system( """osascript -e 'display notification "{}" with title "{}"'""". format(body, summary)) print('\nShutting down safely, please wait until process exits\n') except ConnectionResetError: body = "Disconnected, Bye. (ConnectionReset)" if detected_os == "linux": notification.update(summary, body) notification.show() elif detected_os == "darwin": os.system( """osascript -e 'display notification "{}" with title "{}"'""". format(body, summary)) sys.exit() s.close() return
import logging import gi from safeeyes.model import BreakType gi.require_version('Notify', '0.7') from gi.repository import Notify """ Safe Eyes Notification plugin """ APPINDICATOR_ID = 'safeeyes' notification = None context = None Notify.init(APPINDICATOR_ID) def init(ctx, safeeyes_config, plugin_config): """ Initialize the plugin. """ global context logging.debug('Initialize Notification plugin') context = ctx def on_pre_break(break_obj): """ Show the notification """
def __enter__(self): Notify.init('blue-audio-con') return self
def show_notification(self, title, text=None, icon=ext_icon): logger.debug('Show notification: %s' % text) icon_full_path = os.path.join(os.path.dirname(__file__), icon) Notify.init("KillerExtension") Notify.Notification.new(title, text, icon_full_path).show()
import os import os.path from functools import partial import subprocess import shlex import pyudev import gi from pulsectl import Pulse gi.require_version('Gtk', '3.0') from gi.repository import Gtk, Gdk, Notify # TODO: fix fullscreen # TODO: MTP # TODO: no skype in systray Notify.init("qtile") def notify(title, content): Notify.Notification.new(title, content).show() class MyPrompt(widget.Prompt): pass class ProcessTrackerWidget2(widget_base.ThreadPoolText): orientations = widget_base.ORIENTATION_HORIZONTAL defaults = [('name', 'NAME', 'Title of widget'), ('cmd_start', 'CMD', 'Command to run'), ('cmd_stop', 'CMD_STOP', 'Command to run to stop'),
def __init__(self, **kwargs): super().__init__(**kwargs) self.app = kwargs['application'] """Initialize app""" self.app_name = "Coulr" self.set_border_width(15) self.set_size_request(600, -1) self.set_resizable(False) self.set_position(Gtk.WindowPosition.CENTER) self.connect('delete-event', self.quit_app) # Enable notifications Notify.init(self.app_name) # Main vars self.rgb_color = None self.clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD) # Header bar header_bar = Gtk.HeaderBar() header_bar.set_show_close_button(True) header_bar.props.title = self.app_name header_bar.set_subtitle(_("Enjoy colors and feel happy!")) self.set_titlebar(header_bar) # About button button_about = Gtk.Button() button_about.set_tooltip_text(_("About")) icon_about = Gio.ThemedIcon(name="help-about-symbolic") image_about = Gtk.Image.new_from_gicon(icon_about, Gtk.IconSize.BUTTON) button_about.add(image_about) button_about.connect("clicked", self.about_dialog) header_bar.pack_end(button_about) # Copy button button_copy = Gtk.Button() button_copy.set_tooltip_text(_("Copy color")) icon_copy = Gio.ThemedIcon(name="edit-copy-symbolic") image_copy = Gtk.Image.new_from_gicon(icon_copy, Gtk.IconSize.BUTTON) button_copy.add(image_copy) button_copy.connect("clicked", self.copy_output) header_bar.pack_end(button_copy) # Random button self.button_random = Gtk.Button() self.button_random.set_tooltip_text(_("Generate random color")) icon_random = Gio.ThemedIcon(name="media-playlist-shuffle-symbolic") image_random = Gtk.Image.new_from_gicon(icon_random, Gtk.IconSize.BUTTON) self.button_random.add(image_random) self.button_random.connect("clicked", self.random_button_clicked) header_bar.pack_end(self.button_random) # Main wrappers main_box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=10) layout1 = Gtk.Grid(row_spacing=30, column_spacing=10, valign=Gtk.Align.CENTER) layout2 = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=5, valign=Gtk.Align.CENTER) main_box.add(layout1) main_box.add(layout2) self.add(main_box) # RGB # Red label label = Gtk.Label(_("R")) layout1.attach(label, 0, 1, 1, 1) # Red spinner adj = Gtk.Adjustment(0, 0, 255, 1, 10, 0) self.spinbutton_r = Gtk.SpinButton(adjustment=adj) self.red_sb_id = self.spinbutton_r.connect("value-changed", self.rgb_spin_changed) layout1.attach(self.spinbutton_r, 1, 1, 1, 1) # Red slider adj = Gtk.Adjustment(0, 0, 255, 2, 10, 0) self.slider_r = Gtk.Scale(adjustment=adj, draw_value=False) self.slider_r.set_hexpand(True) self.red_s_id = self.slider_r.connect("value-changed", self.rgb_slider_moved) layout1.attach(self.slider_r, 2, 1, 2, 1) # Green label label = Gtk.Label(_("G")) layout1.attach(label, 0, 2, 1, 1) # Green spinner adj = Gtk.Adjustment(0, 0, 255, 1, 10, 0) self.spinbutton_g = Gtk.SpinButton(adjustment=adj) self.green_sb_id = self.spinbutton_g.connect("value-changed", self.rgb_spin_changed) layout1.attach(self.spinbutton_g, 1, 2, 1, 1) # Green slider adj = Gtk.Adjustment(0, 0, 255, 2, 10, 0) self.slider_g = Gtk.Scale(adjustment=adj, draw_value=False) self.slider_g.set_hexpand(True) self.green_s_id = self.slider_g.connect("value-changed", self.rgb_slider_moved) layout1.attach(self.slider_g, 2, 2, 2, 1) # Blue label label = Gtk.Label(_("B")) layout1.attach(label, 0, 3, 1, 1) # Blue spinner adj = Gtk.Adjustment(0, 0, 255, 1, 10, 0) self.spinbutton_b = Gtk.SpinButton(adjustment=adj) self.blue_sb_id = self.spinbutton_b.connect("value-changed", self.rgb_spin_changed) layout1.attach(self.spinbutton_b, 1, 3, 1, 1) # Blue slider adj = Gtk.Adjustment(0, 0, 255, 2, 10, 0) self.slider_b = Gtk.Scale(adjustment=adj, draw_value=False) self.slider_b.set_hexpand(True) self.blue_s_id = self.slider_b.connect("value-changed", self.rgb_slider_moved) layout1.attach(self.slider_b, 2, 3, 2, 1) # Layout 2 # Output mode self.combo_output = Gtk.ComboBoxText() self.combo_output.append("hex", _("Hexadecimal")) self.combo_output.append("rgb", _("RGB")) self.combo_output.set_active(0) self.combo_output.connect("changed", self.change_output) # Output entry self.output = Gtk.Entry() self.output_id = self.output.connect("changed", self.output_entry_changed) # Preview color with square self.square = Gtk.Frame() self.square.set_size_request(150, 150) layout2.add(self.square) layout2.add(self.combo_output) layout2.add(self.output) if self._settings.get_string("last-color"): color = hex_to_rgb( self._settings.get_string("last-color").lstrip("#")) else: color = random_rgb() self.change_color(color) self.show_all()
from blueman.main.Config import Config import gi gi.require_version("Gtk", "3.0") gi.require_version("Gdk", "3.0") gi.require_version('Notify', '0.7') from gi.repository import Notify from gi.repository import Gtk from gi.repository import Gdk from gi.repository import GLib from blueman.Functions import dprint from blueman.gui.GtkAnimation import AnimBase Notify.init("blueman") OPACITY_START = 0.7 class Fade(AnimBase): def __init__(self, window): AnimBase.__init__(self, state=OPACITY_START) self.window = window def state_changed(self, state): self.window.props.opacity = state class _NotificationDialog(Gtk.MessageDialog): def __init__(self,
def do_startup(self): Gtk.Application.do_startup(self) Notify.init(_("Music")) self.build_app_menu()
def _notify_linux(title: str, body: str): Notify.init(title) n = Notify.Notification.new("", body) n.set_urgency(Notify.Urgency.CRITICAL) n.show()
obj.main_func() def Quit_app(): #global quit_variable config.quit_variable = True QApplication.instance().quit() if __name__ == "__main__": smeet_ = QApplication(sys.argv) smeet_.setStyle('Oxygen') palette = QPalette() palette.setColor(QPalette.Window, QColor(f"{Colour_pallete[0]}")) smeet_.setPalette(palette) notify.init("Smeet") main_window = Smeet() login_window = Login_Page() calendar_window = Calendar_window() about_window = About_Page() settings_window = Settings_Page() create_event_window = Create_Event() main_window.Launch_appindicator_button.clicked.connect(Launch_AppIndicator) w = QStackedWidget() w.addWidget(main_window) w.addWidget(login_window) w.addWidget(calendar_window)
def exit(): Notify.init('Time_OFF_Notification') pop_up=Notify.Notification.new("Thanks You " +uname+ " !" ,"We will remind you after 5 Minutes",'/usr/share/icons/ubuntu-mobile/apps/240/amazon.png') pop_up.show() pop_up.set_urgency(2) root.quit()
""" Module Docstring """ import os import re import cv2 import imghdr from wand.image import Image from pathlib import Path from rofi import Rofi import gi.repository gi.require_version('Notify', '0.7') from gi.repository import Notify ROFI = Rofi() Notify.init("Palette") app_icon = "applications-graphics" __author__ = "Njiall" __version__ = "0.1.0" __license__ = "MIT" def ask_user(options, names, prompt): index, key = ROFI.select(prompt, names) if index >= 0: return options[index], names[index] return '', '' def sort_names_options(names, options):
def main(): Notify.init(APP_NAME) urlToHandle = None # check parameter for arg in sys.argv: if(arg.startswith(PROTOCOL_SCHEME)): urlToHandle = arg if(urlToHandle == None): log("[MAIN] Error: no valid '"+PROTOCOL_SCHEME+"' scheme parameter given.") exit(1) # create temporary directory os.makedirs(DOWNLOAD_DIR, exist_ok=True) # parse given companion URL log("[HANDLE URL] "+urlToHandle) protocolPayload = unquote(urlToHandle).replace(PROTOCOL_SCHEME, "") protocolPayloadData = json.loads(protocolPayload) log("[METADATA-LINK] "+protocolPayloadData["link"]) # download metadata from provided link try: metadataString = urllib.request.urlopen(protocolPayloadData["link"]).read() metadata = json.loads(metadataString) except Exception as e: log("[GET METADATA ERROR] "+str(e)) exit(1) log("[METADATA] "+str(metadata)) # start file download try: filePath = DOWNLOAD_DIR + "/" + metadata["fileName"] log("[START DOWNLOAD TO] "+filePath) urllib.request.urlretrieve(metadata["downloadUrl"], filePath) log("[DOWNLOAD FINISHED] "+filePath) except Exception as e: log("[DOWNLOAD ERROR] "+str(e)) exit(1) # start application log("[LAUNCH] "+filePath) subprocess.call(["xdg-open", filePath]) # set up file watcher log("[SETUP FILE WATCHER] " + DOWNLOAD_DIR) wm = pyinotify.WatchManager() wm.add_watch(DOWNLOAD_DIR, pyinotify.IN_MODIFY | pyinotify.IN_CLOSE_WRITE) notifier = pyinotify.ThreadedNotifier(wm, FileChangedHandler( dict={ "fileId": metadata["fileId"], "fileName": metadata["fileName"], "filePath": filePath, "mimeType": metadata["mimeType"], "downloadUrl": metadata["downloadUrl"], "companionActionCallbackUrl": metadata["companionActionCallbackUrl"], "uploadUrl": metadata["uploadUrl"], "fileMd5": md5(filePath) }) ) notifier.start() # show GUI log("[SHOW GUI]") app = wx.App() window = CompanionWindow(metadata["fileName"]) window.Show() app.MainLoop() # kill file watcher after window closed log("[EXIT]") notifier.stop() exit(0)