Initial (automated) port to Python3.

This commit is contained in:
Bill Dengler 2017-06-16 21:25:01 +00:00
parent e85c9b5af0
commit 9677d996d1
58 changed files with 2208 additions and 2146 deletions

View File

@ -1,18 +1,18 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
name = 'TWBlue' name = 'TWBlue'
snapshot = False snapshot = False
if snapshot == False: if snapshot == False:
version = "0.92" version = "0.92"
update_url = 'https://twblue.es/updates/stable.php' update_url = 'https://twblue.es/updates/stable.php'
mirror_update_url = 'https://raw.githubusercontent.com/manuelcortez/TWBlue/next-gen/updates/stable.json' mirror_update_url = 'https://raw.githubusercontent.com/manuelcortez/TWBlue/next-gen/updates/stable.json'
else: else:
version = "1" version = "1"
update_url = 'https://twblue.es/updates/snapshot.php' update_url = 'https://twblue.es/updates/snapshot.php'
mirror_update_url = 'https://raw.githubusercontent.com/manuelcortez/TWBlue/next-gen/updates/snapshots.json' mirror_update_url = 'https://raw.githubusercontent.com/manuelcortez/TWBlue/next-gen/updates/snapshots.json'
authors = [u"Manuel Cortéz", u"José Manuel Delicado"] authors = ["Manuel Cortéz", "José Manuel Delicado"]
authorEmail = "manuel@manuelcortez.net" authorEmail = "manuel@manuelcortez.net"
copyright = u"Copyright (C) 2013-2017, Manuel cortéz." copyright = "Copyright (C) 2013-2017, Manuel cortéz."
description = unicode(name+" is an app designed to use Twitter simply and efficiently while using minimal system resources. This app provides access to most Twitter features.") description = str(name+" is an app designed to use Twitter simply and efficiently while using minimal system resources. This app provides access to most Twitter features.")
translators = [u"Manuel Cortéz (English)", u"Mohammed Al Shara, Hatoun Felemban (Arabic)", u"Francisco Torres (Catalan)", u"Manuel cortéz (Spanish)", u"Sukil Etxenike Arizaleta (Basque)", u"Jani Kinnunen (finnish)", u"Rémy Ruiz (French)", u"Juan Buño (Galician)", u"Steffen Schultz (German)", u"Zvonimir Stanečić (Croatian)", u"Robert Osztolykan (Hungarian)", u"Christian Leo Mameli (Italian)", u"Riku (Japanese)", u"Paweł Masarczyk (Polish)", u"Odenilton Júnior Santos (Portuguese)", u"Florian Ionașcu, Nicușor Untilă (Romanian)", u"Natalia Hedlund, Valeria Kuznetsova (Russian)", u"Aleksandar Đurić (Serbian)", u"Burak Yüksek (Turkish)"] translators = ["Manuel Cortéz (English)", "Mohammed Al Shara, Hatoun Felemban (Arabic)", "Francisco Torres (Catalan)", "Manuel cortéz (Spanish)", "Sukil Etxenike Arizaleta (Basque)", "Jani Kinnunen (finnish)", "Rémy Ruiz (French)", "Juan Buño (Galician)", "Steffen Schultz (German)", "Zvonimir Stanečić (Croatian)", "Robert Osztolykan (Hungarian)", "Christian Leo Mameli (Italian)", "Riku (Japanese)", "Paweł Masarczyk (Polish)", "Odenilton Júnior Santos (Portuguese)", "Florian Ionașcu, Nicușor Untilă (Romanian)", "Natalia Hedlund, Valeria Kuznetsova (Russian)", "Aleksandar Đurić (Serbian)", "Burak Yüksek (Turkish)"]
url = u"https://twblue.es" url = "https://twblue.es"
report_bugs_url = "https://github.com/manuelcortez/twblue/issues" report_bugs_url = "https://github.com/manuelcortez/twblue/issues"

View File

@ -1,32 +1,32 @@
from audio_services import matches_url from audio_services import matches_url
import json import json
import re import re
import urllib import urllib.request, urllib.parse, urllib.error
@matches_url('https://audioboom.com') @matches_url('https://audioboom.com')
def convert_audioboom(url): def convert_audioboom(url):
if "audioboom.com" not in url.lower(): if "audioboom.com" not in url.lower():
raise TypeError('%r is not a valid URL' % url) raise TypeError('%r is not a valid URL' % url)
audio_id = url.split('.com/')[-1] audio_id = url.split('.com/')[-1]
return 'https://audioboom.com/%s.mp3' % audio_id return 'https://audioboom.com/%s.mp3' % audio_id
@matches_url ('https://soundcloud.com/') @matches_url ('https://soundcloud.com/')
def convert_soundcloud (url): def convert_soundcloud (url):
client_id = "df8113ca95c157b6c9731f54b105b473" client_id = "df8113ca95c157b6c9731f54b105b473"
permalink = urllib.urlopen ('http://api.soundcloud.com/resolve.json?client_id=%s&url=%s' %(client_id, url)) permalink = urllib.request.urlopen ('http://api.soundcloud.com/resolve.json?client_id=%s&url=%s' %(client_id, url))
if permalink.getcode () == 404: if permalink.getcode () == 404:
permalink.close () permalink.close ()
raise TypeError('%r is not a valid URL' % url) raise TypeError('%r is not a valid URL' % url)
else: else:
resolved_url = permalink.geturl () resolved_url = permalink.geturl ()
permalink.close () permalink.close ()
track_url = urllib.urlopen (resolved_url) track_url = urllib.request.urlopen (resolved_url)
track_data = json.loads (track_url.read ()) track_data = json.loads (track_url.read ())
track_url.close () track_url.close ()
if track_data ['streamable']: if track_data ['streamable']:
return track_data ['stream_url'] + "?client_id=%s" %client_id return track_data ['stream_url'] + "?client_id=%s" %client_id
else: else:
raise TypeError('%r is not streamable' % url) raise TypeError('%r is not streamable' % url)
def convert_generic_audio(url): def convert_generic_audio(url):
return url return url

View File

@ -1,79 +1,79 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from configobj import ConfigObj, ParseError from configobj import ConfigObj, ParseError
from validate import Validator, ValidateError from validate import Validator, ValidateError
import os import os
import string import string
from logging import getLogger from logging import getLogger
log = getLogger("config_utils") log = getLogger("config_utils")
class ConfigLoadError(Exception): pass class ConfigLoadError(Exception): pass
def load_config(config_path, configspec_path=None, copy=True, *args, **kwargs): def load_config(config_path, configspec_path=None, copy=True, *args, **kwargs):
if os.path.exists(config_path): if os.path.exists(config_path):
clean_config(config_path) clean_config(config_path)
spec = ConfigObj(configspec_path, encoding='UTF8', list_values=False, _inspec=True) spec = ConfigObj(configspec_path, encoding='UTF8', list_values=False, _inspec=True)
try: try:
config = ConfigObj(infile=config_path, configspec=spec, create_empty=True, encoding='UTF8', *args, **kwargs) config = ConfigObj(infile=config_path, configspec=spec, create_empty=True, encoding='UTF8', *args, **kwargs)
except ParseError: except ParseError:
raise ConfigLoadError("Unable to load %r" % config_path) raise ConfigLoadError("Unable to load %r" % config_path)
validator = Validator() validator = Validator()
validated = config.validate(validator, preserve_errors=False, copy=copy) validated = config.validate(validator, preserve_errors=False, copy=copy)
if validated == True: if validated == True:
config.write() config.write()
return config return config
else: else:
log.exception("Error in config file: {0}".format(validated,)) log.exception("Error in config file: {0}".format(validated,))
def is_blank(arg): def is_blank(arg):
"Check if a line is blank." "Check if a line is blank."
for c in arg: for c in arg:
if c not in string.whitespace: if c not in string.whitespace:
return False return False
return True return True
def get_keys(path): def get_keys(path):
"Gets the keys of a configobj config file." "Gets the keys of a configobj config file."
res=[] res=[]
fin=open(path) fin=open(path)
for line in fin: for line in fin:
if not is_blank(line): if not is_blank(line):
res.append(line[0:line.find('=')].strip()) res.append(line[0:line.find('=')].strip())
fin.close() fin.close()
return res return res
def hist(keys): def hist(keys):
"Generates a histogram of an iterable." "Generates a histogram of an iterable."
res={} res={}
for k in keys: for k in keys:
res[k]=res.setdefault(k,0)+1 res[k]=res.setdefault(k,0)+1
return res return res
def find_problems(hist): def find_problems(hist):
"Takes a histogram and returns a list of items occurring more than once." "Takes a histogram and returns a list of items occurring more than once."
res=[] res=[]
for k,v in hist.items(): for k,v in list(hist.items()):
if v>1: if v>1:
res.append(k) res.append(k)
return res return res
def clean_config(path): def clean_config(path):
"Cleans a config file. If duplicate values are found, delete all of them and just use the default." "Cleans a config file. If duplicate values are found, delete all of them and just use the default."
orig=[] orig=[]
cleaned=[] cleaned=[]
fin=open(path) fin=open(path)
for line in fin: for line in fin:
orig.append(line) orig.append(line)
fin.close() fin.close()
for p in find_problems(hist(get_keys(path))): for p in find_problems(hist(get_keys(path))):
for o in orig: for o in orig:
o.strip() o.strip()
if p not in o: if p not in o:
cleaned.append(o) cleaned.append(o)
if len(cleaned) != 0: if len(cleaned) != 0:
cam=open(path,'w') cam=open(path,'w')
for c in cleaned: for c in cleaned:
cam.write(c) cam.write(c)
cam.close() cam.close()
return True return True
else: else:
return False return False

View File

@ -1,38 +1,39 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import os from builtins import object
import widgetUtils import os
import logging import widgetUtils
from wxUI.dialogs import attach as gui import logging
log = logging.getLogger("controller.attach") from wxUI.dialogs import attach as gui
log = logging.getLogger("controller.attach")
class attach(object):
def __init__(self): class attach(object):
self.attachments = list() def __init__(self):
self.dialog = gui.attachDialog() self.attachments = list()
widgetUtils.connect_event(self.dialog.photo, widgetUtils.BUTTON_PRESSED, self.upload_image) self.dialog = gui.attachDialog()
widgetUtils.connect_event(self.dialog.remove, widgetUtils.BUTTON_PRESSED, self.remove_attachment) widgetUtils.connect_event(self.dialog.photo, widgetUtils.BUTTON_PRESSED, self.upload_image)
self.dialog.get_response() widgetUtils.connect_event(self.dialog.remove, widgetUtils.BUTTON_PRESSED, self.remove_attachment)
log.debug("Attachments controller started.") self.dialog.get_response()
log.debug("Attachments controller started.")
def upload_image(self, *args, **kwargs):
image, description = self.dialog.get_image() def upload_image(self, *args, **kwargs):
if image != None: image, description = self.dialog.get_image()
imageInfo = {"type": "photo", "file": image, "description": description} if image != None:
log.debug("Image data to upload: %r" % (imageInfo,)) imageInfo = {"type": "photo", "file": image, "description": description}
self.attachments.append(imageInfo) log.debug("Image data to upload: %r" % (imageInfo,))
info = [_(u"Photo"), description] self.attachments.append(imageInfo)
self.dialog.attachments.insert_item(False, *info) info = [_(u"Photo"), description]
self.dialog.remove.Enable(True) self.dialog.attachments.insert_item(False, *info)
self.dialog.remove.Enable(True)
def remove_attachment(self, *args, **kwargs):
current_item = self.dialog.attachments.get_selected() def remove_attachment(self, *args, **kwargs):
log.debug("Removing item %d" % (current_item,)) current_item = self.dialog.attachments.get_selected()
if current_item == -1: current_item = 0 log.debug("Removing item %d" % (current_item,))
self.attachments.pop(current_item) if current_item == -1: current_item = 0
self.dialog.attachments.remove_item(current_item) self.attachments.pop(current_item)
self.check_remove_status() self.dialog.attachments.remove_item(current_item)
log.debug("Removed") self.check_remove_status()
log.debug("Removed")
def check_remove_status(self):
if len(self.attachments) == 0 and self.dialog.attachments.get_count() == 0: def check_remove_status(self):
self.dialog.remove.Enable(False) if len(self.attachments) == 0 and self.dialog.attachments.get_count() == 0:
self.dialog.remove.Enable(False)

View File

@ -1,7 +1,8 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from wxUI.dialogs import filters from builtins import object
from wxUI.dialogs import filters
class filterController(object):
def __init__(self): class filterController(object):
self.dialog = filters.filterDialog() def __init__(self):
self.dialog = filters.filterDialog()
self.dialog.get_response() self.dialog.get_response()

View File

@ -1,106 +1,107 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import widgetUtils from builtins import object
import output import widgetUtils
from wxUI.dialogs import lists import output
from twython import TwythonError from wxUI.dialogs import lists
from twitter import compose, utils from twython import TwythonError
from pubsub import pub from twitter import compose, utils
from pubsub import pub
class listsController(object):
def __init__(self, session, user=None): class listsController(object):
super(listsController, self).__init__() def __init__(self, session, user=None):
self.session = session super(listsController, self).__init__()
if user == None: self.session = session
self.dialog = lists.listViewer() if user == None:
self.dialog.populate_list(self.get_all_lists()) self.dialog = lists.listViewer()
widgetUtils.connect_event(self.dialog.createBtn, widgetUtils.BUTTON_PRESSED, self.create_list) self.dialog.populate_list(self.get_all_lists())
widgetUtils.connect_event(self.dialog.editBtn, widgetUtils.BUTTON_PRESSED, self.edit_list) widgetUtils.connect_event(self.dialog.createBtn, widgetUtils.BUTTON_PRESSED, self.create_list)
widgetUtils.connect_event(self.dialog.deleteBtn, widgetUtils.BUTTON_PRESSED, self.remove_list) widgetUtils.connect_event(self.dialog.editBtn, widgetUtils.BUTTON_PRESSED, self.edit_list)
widgetUtils.connect_event(self.dialog.view, widgetUtils.BUTTON_PRESSED, self.open_list_as_buffer) widgetUtils.connect_event(self.dialog.deleteBtn, widgetUtils.BUTTON_PRESSED, self.remove_list)
widgetUtils.connect_event(self.dialog.deleteBtn, widgetUtils.BUTTON_PRESSED, self.remove_list) widgetUtils.connect_event(self.dialog.view, widgetUtils.BUTTON_PRESSED, self.open_list_as_buffer)
else: widgetUtils.connect_event(self.dialog.deleteBtn, widgetUtils.BUTTON_PRESSED, self.remove_list)
self.dialog = lists.userListViewer(user) else:
self.dialog.populate_list(self.get_user_lists(user)) self.dialog = lists.userListViewer(user)
widgetUtils.connect_event(self.dialog.createBtn, widgetUtils.BUTTON_PRESSED, self.subscribe) self.dialog.populate_list(self.get_user_lists(user))
widgetUtils.connect_event(self.dialog.deleteBtn, widgetUtils.BUTTON_PRESSED, self.unsubscribe) widgetUtils.connect_event(self.dialog.createBtn, widgetUtils.BUTTON_PRESSED, self.subscribe)
self.dialog.get_response() widgetUtils.connect_event(self.dialog.deleteBtn, widgetUtils.BUTTON_PRESSED, self.unsubscribe)
self.dialog.get_response()
def get_all_lists(self):
return [compose.compose_list(item) for item in self.session.db["lists"]] def get_all_lists(self):
return [compose.compose_list(item) for item in self.session.db["lists"]]
def get_user_lists(self, user):
self.lists = self.session.twitter.twitter.show_lists(reverse=True, screen_name=user) def get_user_lists(self, user):
return [compose.compose_list(item) for item in self.lists] self.lists = self.session.twitter.twitter.show_lists(reverse=True, screen_name=user)
return [compose.compose_list(item) for item in self.lists]
def create_list(self, *args, **kwargs):
dialog = lists.createListDialog() def create_list(self, *args, **kwargs):
if dialog.get_response() == widgetUtils.OK: dialog = lists.createListDialog()
name = dialog.get("name") if dialog.get_response() == widgetUtils.OK:
description = dialog.get("description") name = dialog.get("name")
p = dialog.get("public") description = dialog.get("description")
if p == True: p = dialog.get("public")
mode = "public" if p == True:
else: mode = "public"
mode = "private" else:
try: mode = "private"
new_list = self.session.twitter.twitter.create_list(name=name, description=description, mode=mode) try:
self.session.db["lists"].append(new_list) new_list = self.session.twitter.twitter.create_list(name=name, description=description, mode=mode)
self.dialog.lista.insert_item(False, *compose.compose_list(new_list)) self.session.db["lists"].append(new_list)
except TwythonError as e: self.dialog.lista.insert_item(False, *compose.compose_list(new_list))
output.speak("error %s: %s" % (e.status_code, e.msg)) except TwythonError as e:
dialog.destroy() output.speak("error %s: %s" % (e.status_code, e.msg))
dialog.destroy()
def edit_list(self, *args, **kwargs):
if self.dialog.lista.get_count() == 0: return def edit_list(self, *args, **kwargs):
list = self.session.db["lists"][self.dialog.get_item()] if self.dialog.lista.get_count() == 0: return
dialog = lists.editListDialog(list) list = self.session.db["lists"][self.dialog.get_item()]
if dialog.get_response() == widgetUtils.OK: dialog = lists.editListDialog(list)
name = dialog.get("name") if dialog.get_response() == widgetUtils.OK:
description = dialog.get("description") name = dialog.get("name")
p = dialog.get("public") description = dialog.get("description")
if p == True: p = dialog.get("public")
mode = "public" if p == True:
else: mode = "public"
mode = "private" else:
try: mode = "private"
self.session.twitter.twitter.update_list(list_id=list["id"], name=name, description=description, mode=mode) try:
self.session.get_lists() self.session.twitter.twitter.update_list(list_id=list["id"], name=name, description=description, mode=mode)
self.dialog.populate_list(self.get_all_lists(), True) self.session.get_lists()
except TwythonError as e: self.dialog.populate_list(self.get_all_lists(), True)
output.speak("error %s: %s" % (e.error_code, e.msg)) except TwythonError as e:
dialog.destroy() output.speak("error %s: %s" % (e.error_code, e.msg))
dialog.destroy()
def remove_list(self, *args, **kwargs):
if self.dialog.lista.get_count() == 0: return def remove_list(self, *args, **kwargs):
list = self.session.db["lists"][self.dialog.get_item()]["id"] if self.dialog.lista.get_count() == 0: return
if lists.remove_list() == widgetUtils.YES: list = self.session.db["lists"][self.dialog.get_item()]["id"]
try: if lists.remove_list() == widgetUtils.YES:
self.session.twitter.twitter.delete_list(list_id=list) try:
self.session.db["lists"].pop(self.dialog.get_item()) self.session.twitter.twitter.delete_list(list_id=list)
self.dialog.lista.remove_item(self.dialog.get_item()) self.session.db["lists"].pop(self.dialog.get_item())
except TwythonError as e: self.dialog.lista.remove_item(self.dialog.get_item())
output.speak("error %s: %s" % (e.error_code, e.msg)) except TwythonError as e:
output.speak("error %s: %s" % (e.error_code, e.msg))
def open_list_as_buffer(self, *args, **kwargs):
if self.dialog.lista.get_count() == 0: return def open_list_as_buffer(self, *args, **kwargs):
list = self.session.db["lists"][self.dialog.get_item()] if self.dialog.lista.get_count() == 0: return
pub.sendMessage("create-new-buffer", buffer="list", account=self.session.db["user_name"], create=list["name"]) list = self.session.db["lists"][self.dialog.get_item()]
pub.sendMessage("create-new-buffer", buffer="list", account=self.session.db["user_name"], create=list["name"])
def subscribe(self, *args, **kwargs):
if self.dialog.lista.get_count() == 0: return def subscribe(self, *args, **kwargs):
list_id = self.lists[self.dialog.get_item()]["id"] if self.dialog.lista.get_count() == 0: return
try: list_id = self.lists[self.dialog.get_item()]["id"]
list = self.session.twitter.twitter.subscribe_to_list(list_id=list_id) try:
item = utils.find_item(list["id"], self.session.db["lists"]) list = self.session.twitter.twitter.subscribe_to_list(list_id=list_id)
self.session.db["lists"].append(list) item = utils.find_item(list["id"], self.session.db["lists"])
except TwythonError as e: self.session.db["lists"].append(list)
output.speak("error %s: %s" % (e.status_code, e.msg)) except TwythonError as e:
output.speak("error %s: %s" % (e.status_code, e.msg))
def unsubscribe(self, *args, **kwargs):
if self.dialog.lista.get_count() == 0: return def unsubscribe(self, *args, **kwargs):
list_id = self.lists[self.dialog.get_item()]["id"] if self.dialog.lista.get_count() == 0: return
try: list_id = self.lists[self.dialog.get_item()]["id"]
list = self.session.twitter.twitter.unsubscribe_from_list(list_id=list_id) try:
self.session.db["lists"].remove(list) list = self.session.twitter.twitter.unsubscribe_from_list(list_id=list_id)
except TwythonError as e: self.session.db["lists"].remove(list)
output.speak("error %s: %s" % (e.status_code, e.msg)) except TwythonError as e:
output.speak("error %s: %s" % (e.status_code, e.msg))

View File

@ -1,317 +1,321 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import os from __future__ import division
import webbrowser from builtins import str
import sound_lib from past.utils import old_div
import paths from builtins import object
import widgetUtils import os
import config import webbrowser
import languageHandler import sound_lib
import output import paths
import application import widgetUtils
from wxUI.dialogs import configuration import config
from wxUI import commonMessageDialogs import languageHandler
from extra.autocompletionUsers import settings import output
from extra.ocr import OCRSpace import application
from pubsub import pub from wxUI.dialogs import configuration
import logging from wxUI import commonMessageDialogs
import config_utils from extra.autocompletionUsers import settings
log = logging.getLogger("Settings") from extra.ocr import OCRSpace
import keys from pubsub import pub
from collections import OrderedDict import logging
from platform_utils.autostart import windows as autostart_windows import config_utils
log = logging.getLogger("Settings")
class globalSettingsController(object): import keys
def __init__(self): from collections import OrderedDict
super(globalSettingsController, self).__init__() from platform_utils.autostart import windows as autostart_windows
self.dialog = configuration.configurationDialog()
self.create_config() class globalSettingsController(object):
self.needs_restart = False def __init__(self):
self.is_started = True super(globalSettingsController, self).__init__()
self.dialog = configuration.configurationDialog()
def make_kmmap(self): self.create_config()
res={} self.needs_restart = False
for i in os.listdir(paths.app_path('keymaps')): self.is_started = True
if ".keymap" not in i:
continue def make_kmmap(self):
try: res={}
res[i[:-7]] =i for i in os.listdir(paths.app_path('keymaps')):
except: if ".keymap" not in i:
log.exception("Exception while loading keymap " + i) continue
return res try:
res[i[:-7]] =i
def create_config(self): except:
self.kmmap=self.make_kmmap() log.exception("Exception while loading keymap " + i)
self.langs = languageHandler.getAvailableLanguages() return res
langs = []
[langs.append(i[1]) for i in self.langs] def create_config(self):
self.codes = [] self.kmmap=self.make_kmmap()
[self.codes.append(i[0]) for i in self.langs] self.langs = languageHandler.getAvailableLanguages()
id = self.codes.index(config.app["app-settings"]["language"]) langs = []
self.kmfriendlies=[] [langs.append(i[1]) for i in self.langs]
self.kmnames=[] self.codes = []
for k,v in self.kmmap.items(): [self.codes.append(i[0]) for i in self.langs]
self.kmfriendlies.append(k) id = self.codes.index(config.app["app-settings"]["language"])
self.kmnames.append(v) self.kmfriendlies=[]
self.kmid=self.kmnames.index(config.app['app-settings']['load_keymap']) self.kmnames=[]
self.dialog.create_general(langs,self.kmfriendlies) for k,v in list(self.kmmap.items()):
self.dialog.general.language.SetSelection(id) self.kmfriendlies.append(k)
self.dialog.general.km.SetSelection(self.kmid) self.kmnames.append(v)
if paths.mode == "installed": self.kmid=self.kmnames.index(config.app['app-settings']['load_keymap'])
self.dialog.set_value("general", "autostart", config.app["app-settings"]["autostart"]) self.dialog.create_general(langs,self.kmfriendlies)
else: self.dialog.general.language.SetSelection(id)
self.dialog.general.autostart.Enable(False) self.dialog.general.km.SetSelection(self.kmid)
self.dialog.set_value("general", "ask_at_exit", config.app["app-settings"]["ask_at_exit"]) if paths.mode == "installed":
self.dialog.set_value("general", "play_ready_sound", config.app["app-settings"]["play_ready_sound"]) self.dialog.set_value("general", "autostart", config.app["app-settings"]["autostart"])
self.dialog.set_value("general", "speak_ready_msg", config.app["app-settings"]["speak_ready_msg"]) else:
self.dialog.set_value("general", "handle_longtweets", config.app["app-settings"]["handle_longtweets"]) self.dialog.general.autostart.Enable(False)
self.dialog.set_value("general", "use_invisible_shorcuts", config.app["app-settings"]["use_invisible_keyboard_shorcuts"]) self.dialog.set_value("general", "ask_at_exit", config.app["app-settings"]["ask_at_exit"])
self.dialog.set_value("general", "disable_sapi5", config.app["app-settings"]["voice_enabled"]) self.dialog.set_value("general", "play_ready_sound", config.app["app-settings"]["play_ready_sound"])
self.dialog.set_value("general", "hide_gui", config.app["app-settings"]["hide_gui"]) self.dialog.set_value("general", "speak_ready_msg", config.app["app-settings"]["speak_ready_msg"])
self.dialog.set_value("general", "check_for_updates", config.app["app-settings"]["check_for_updates"]) self.dialog.set_value("general", "handle_longtweets", config.app["app-settings"]["handle_longtweets"])
proxyTypes=config.proxyTypes self.dialog.set_value("general", "use_invisible_shorcuts", config.app["app-settings"]["use_invisible_keyboard_shorcuts"])
self.dialog.create_proxy([_(u"Direct connection")]+proxyTypes) self.dialog.set_value("general", "disable_sapi5", config.app["app-settings"]["voice_enabled"])
if config.app["proxy"]["type"] not in proxyTypes: self.dialog.set_value("general", "hide_gui", config.app["app-settings"]["hide_gui"])
self.dialog.proxy.type.SetSelection(0) self.dialog.set_value("general", "check_for_updates", config.app["app-settings"]["check_for_updates"])
else: proxyTypes=config.proxyTypes
self.dialog.proxy.type.SetSelection(proxyTypes.index(config.app["proxy"]["type"])+1) self.dialog.create_proxy([_(u"Direct connection")]+proxyTypes)
self.dialog.set_value("proxy", "server", config.app["proxy"]["server"]) if config.app["proxy"]["type"] not in proxyTypes:
self.dialog.set_value("proxy", "port", config.app["proxy"]["port"]) self.dialog.proxy.type.SetSelection(0)
self.dialog.set_value("proxy", "user", config.app["proxy"]["user"]) else:
self.dialog.set_value("proxy", "password", config.app["proxy"]["password"]) self.dialog.proxy.type.SetSelection(proxyTypes.index(config.app["proxy"]["type"])+1)
self.dialog.set_value("proxy", "server", config.app["proxy"]["server"])
self.dialog.realize() self.dialog.set_value("proxy", "port", config.app["proxy"]["port"])
self.response = self.dialog.get_response() self.dialog.set_value("proxy", "user", config.app["proxy"]["user"])
self.dialog.set_value("proxy", "password", config.app["proxy"]["password"])
def save_configuration(self):
if self.codes[self.dialog.general.language.GetSelection()] != config.app["app-settings"]["language"]: self.dialog.realize()
config.app["app-settings"]["language"] = self.codes[self.dialog.general.language.GetSelection()] self.response = self.dialog.get_response()
languageHandler.setLanguage(config.app["app-settings"]["language"])
self.needs_restart = True def save_configuration(self):
if self.kmnames[self.dialog.general.km.GetSelection()] != config.app["app-settings"]["load_keymap"]: if self.codes[self.dialog.general.language.GetSelection()] != config.app["app-settings"]["language"]:
config.app["app-settings"]["load_keymap"] =self.kmnames[self.dialog.general.km.GetSelection()] config.app["app-settings"]["language"] = self.codes[self.dialog.general.language.GetSelection()]
kmFile = open(paths.config_path("keymap.keymap"), "w") languageHandler.setLanguage(config.app["app-settings"]["language"])
kmFile.close() self.needs_restart = True
self.needs_restart = True if self.kmnames[self.dialog.general.km.GetSelection()] != config.app["app-settings"]["load_keymap"]:
config.app["app-settings"]["load_keymap"] =self.kmnames[self.dialog.general.km.GetSelection()]
if config.app["app-settings"]["autostart"] != self.dialog.get_value("general", "autostart") and paths.mode == "installed": kmFile = open(paths.config_path("keymap.keymap"), "w")
config.app["app-settings"]["autostart"] = self.dialog.get_value("general", "autostart") kmFile.close()
autostart_windows.setAutoStart(application.name, enable=self.dialog.get_value("general", "autostart")) self.needs_restart = True
if config.app["app-settings"]["use_invisible_keyboard_shorcuts"] != self.dialog.get_value("general", "use_invisible_shorcuts"):
config.app["app-settings"]["use_invisible_keyboard_shorcuts"] = self.dialog.get_value("general", "use_invisible_shorcuts") if config.app["app-settings"]["autostart"] != self.dialog.get_value("general", "autostart") and paths.mode == "installed":
pub.sendMessage("invisible-shorcuts-changed", registered=self.dialog.get_value("general", "use_invisible_shorcuts")) config.app["app-settings"]["autostart"] = self.dialog.get_value("general", "autostart")
config.app["app-settings"]["voice_enabled"] = self.dialog.get_value("general", "disable_sapi5") autostart_windows.setAutoStart(application.name, enable=self.dialog.get_value("general", "autostart"))
config.app["app-settings"]["hide_gui"] = self.dialog.get_value("general", "hide_gui") if config.app["app-settings"]["use_invisible_keyboard_shorcuts"] != self.dialog.get_value("general", "use_invisible_shorcuts"):
config.app["app-settings"]["ask_at_exit"] = self.dialog.get_value("general", "ask_at_exit") config.app["app-settings"]["use_invisible_keyboard_shorcuts"] = self.dialog.get_value("general", "use_invisible_shorcuts")
config.app["app-settings"]["handle_longtweets"] = self.dialog.get_value("general", "handle_longtweets") pub.sendMessage("invisible-shorcuts-changed", registered=self.dialog.get_value("general", "use_invisible_shorcuts"))
config.app["app-settings"]["play_ready_sound"] = self.dialog.get_value("general", "play_ready_sound") config.app["app-settings"]["voice_enabled"] = self.dialog.get_value("general", "disable_sapi5")
config.app["app-settings"]["speak_ready_msg"] = self.dialog.get_value("general", "speak_ready_msg") config.app["app-settings"]["hide_gui"] = self.dialog.get_value("general", "hide_gui")
config.app["app-settings"]["check_for_updates"] = self.dialog.get_value("general", "check_for_updates") config.app["app-settings"]["ask_at_exit"] = self.dialog.get_value("general", "ask_at_exit")
if config.app["proxy"]["type"]!=self.dialog.get_value("proxy", "type") or config.app["proxy"]["server"] != self.dialog.get_value("proxy", "server") or config.app["proxy"]["port"] != self.dialog.get_value("proxy", "port") or config.app["proxy"]["user"] != self.dialog.get_value("proxy", "user") or config.app["proxy"]["password"] != self.dialog.get_value("proxy", "password"): config.app["app-settings"]["handle_longtweets"] = self.dialog.get_value("general", "handle_longtweets")
if self.is_started == True: config.app["app-settings"]["play_ready_sound"] = self.dialog.get_value("general", "play_ready_sound")
self.needs_restart = True config.app["app-settings"]["speak_ready_msg"] = self.dialog.get_value("general", "speak_ready_msg")
config.app["proxy"]["type"]=self.dialog.get_value("proxy", "type") config.app["app-settings"]["check_for_updates"] = self.dialog.get_value("general", "check_for_updates")
config.app["proxy"]["server"] = self.dialog.get_value("proxy", "server") if config.app["proxy"]["type"]!=self.dialog.get_value("proxy", "type") or config.app["proxy"]["server"] != self.dialog.get_value("proxy", "server") or config.app["proxy"]["port"] != self.dialog.get_value("proxy", "port") or config.app["proxy"]["user"] != self.dialog.get_value("proxy", "user") or config.app["proxy"]["password"] != self.dialog.get_value("proxy", "password"):
config.app["proxy"]["port"] = self.dialog.get_value("proxy", "port") if self.is_started == True:
config.app["proxy"]["user"] = self.dialog.get_value("proxy", "user") self.needs_restart = True
config.app["proxy"]["password"] = self.dialog.get_value("proxy", "password") config.app["proxy"]["type"]=self.dialog.get_value("proxy", "type")
config.app.write() config.app["proxy"]["server"] = self.dialog.get_value("proxy", "server")
config.app["proxy"]["port"] = self.dialog.get_value("proxy", "port")
class accountSettingsController(globalSettingsController): config.app["proxy"]["user"] = self.dialog.get_value("proxy", "user")
def __init__(self, buffer, window): config.app["proxy"]["password"] = self.dialog.get_value("proxy", "password")
self.user = buffer.session.db["user_name"] config.app.write()
self.buffer = buffer
self.window = window class accountSettingsController(globalSettingsController):
self.config = buffer.session.settings def __init__(self, buffer, window):
super(accountSettingsController, self).__init__() self.user = buffer.session.db["user_name"]
self.buffer = buffer
def create_config(self): self.window = window
self.dialog.create_general_account() self.config = buffer.session.settings
widgetUtils.connect_event(self.dialog.general.au, widgetUtils.BUTTON_PRESSED, self.manage_autocomplete) super(accountSettingsController, self).__init__()
self.dialog.set_value("general", "relative_time", self.config["general"]["relative_times"])
self.dialog.set_value("general", "show_screen_names", self.config["general"]["show_screen_names"]) def create_config(self):
self.dialog.set_value("general", "apiCalls", self.config["general"]["max_api_calls"]) self.dialog.create_general_account()
self.dialog.set_value("general", "itemsPerApiCall", self.config["general"]["max_tweets_per_call"]) widgetUtils.connect_event(self.dialog.general.au, widgetUtils.BUTTON_PRESSED, self.manage_autocomplete)
self.dialog.set_value("general", "reverse_timelines", self.config["general"]["reverse_timelines"]) self.dialog.set_value("general", "relative_time", self.config["general"]["relative_times"])
rt = self.config["general"]["retweet_mode"] self.dialog.set_value("general", "show_screen_names", self.config["general"]["show_screen_names"])
if rt == "ask": self.dialog.set_value("general", "apiCalls", self.config["general"]["max_api_calls"])
self.dialog.set_value("general", "retweet_mode", _(u"Ask")) self.dialog.set_value("general", "itemsPerApiCall", self.config["general"]["max_tweets_per_call"])
elif rt == "direct": self.dialog.set_value("general", "reverse_timelines", self.config["general"]["reverse_timelines"])
self.dialog.set_value("general", "retweet_mode", _(u"Retweet without comments")) rt = self.config["general"]["retweet_mode"]
else: if rt == "ask":
self.dialog.set_value("general", "retweet_mode", _(u"Retweet with comments")) self.dialog.set_value("general", "retweet_mode", _(u"Ask"))
self.dialog.set_value("general", "persist_size", str(self.config["general"]["persist_size"])) elif rt == "direct":
self.dialog.create_other_buffers() self.dialog.set_value("general", "retweet_mode", _(u"Retweet without comments"))
buffer_values = self.get_buffers_list() else:
self.dialog.buffers.insert_buffers(buffer_values) self.dialog.set_value("general", "retweet_mode", _(u"Retweet with comments"))
self.dialog.buffers.connect_hook_func(self.toggle_buffer_active) self.dialog.set_value("general", "persist_size", str(self.config["general"]["persist_size"]))
widgetUtils.connect_event(self.dialog.buffers.toggle_state, widgetUtils.BUTTON_PRESSED, self.toggle_state) self.dialog.create_other_buffers()
widgetUtils.connect_event(self.dialog.buffers.up, widgetUtils.BUTTON_PRESSED, self.dialog.buffers.move_up) buffer_values = self.get_buffers_list()
widgetUtils.connect_event(self.dialog.buffers.down, widgetUtils.BUTTON_PRESSED, self.dialog.buffers.move_down) self.dialog.buffers.insert_buffers(buffer_values)
self.dialog.buffers.connect_hook_func(self.toggle_buffer_active)
widgetUtils.connect_event(self.dialog.buffers.toggle_state, widgetUtils.BUTTON_PRESSED, self.toggle_state)
self.dialog.create_ignored_clients(self.config["twitter"]["ignored_clients"]) widgetUtils.connect_event(self.dialog.buffers.up, widgetUtils.BUTTON_PRESSED, self.dialog.buffers.move_up)
widgetUtils.connect_event(self.dialog.ignored_clients.add, widgetUtils.BUTTON_PRESSED, self.add_ignored_client) widgetUtils.connect_event(self.dialog.buffers.down, widgetUtils.BUTTON_PRESSED, self.dialog.buffers.move_down)
widgetUtils.connect_event(self.dialog.ignored_clients.remove, widgetUtils.BUTTON_PRESSED, self.remove_ignored_client)
self.input_devices = sound_lib.input.Input.get_device_names()
self.output_devices = sound_lib.output.Output.get_device_names() self.dialog.create_ignored_clients(self.config["twitter"]["ignored_clients"])
self.soundpacks = [] widgetUtils.connect_event(self.dialog.ignored_clients.add, widgetUtils.BUTTON_PRESSED, self.add_ignored_client)
[self.soundpacks.append(i) for i in os.listdir(paths.sound_path()) if os.path.isdir(paths.sound_path(i)) == True ] widgetUtils.connect_event(self.dialog.ignored_clients.remove, widgetUtils.BUTTON_PRESSED, self.remove_ignored_client)
self.dialog.create_sound(self.input_devices, self.output_devices, self.soundpacks) self.input_devices = sound_lib.input.Input.get_device_names()
self.dialog.set_value("sound", "volumeCtrl", self.config["sound"]["volume"]*100) self.output_devices = sound_lib.output.Output.get_device_names()
self.dialog.set_value("sound", "input", self.config["sound"]["input_device"]) self.soundpacks = []
self.dialog.set_value("sound", "output", self.config["sound"]["output_device"]) [self.soundpacks.append(i) for i in os.listdir(paths.sound_path()) if os.path.isdir(paths.sound_path(i)) == True ]
self.dialog.set_value("sound", "session_mute", self.config["sound"]["session_mute"]) self.dialog.create_sound(self.input_devices, self.output_devices, self.soundpacks)
self.dialog.set_value("sound", "soundpack", self.config["sound"]["current_soundpack"]) self.dialog.set_value("sound", "volumeCtrl", self.config["sound"]["volume"]*100)
self.dialog.set_value("sound", "indicate_audio", self.config["sound"]["indicate_audio"]) self.dialog.set_value("sound", "input", self.config["sound"]["input_device"])
self.dialog.set_value("sound", "indicate_geo", self.config["sound"]["indicate_geo"]) self.dialog.set_value("sound", "output", self.config["sound"]["output_device"])
self.dialog.set_value("sound", "indicate_img", self.config["sound"]["indicate_img"]) self.dialog.set_value("sound", "session_mute", self.config["sound"]["session_mute"])
self.dialog.create_extras(OCRSpace.translatable_langs) self.dialog.set_value("sound", "soundpack", self.config["sound"]["current_soundpack"])
self.dialog.set_value("extras", "sndup_apiKey", self.config["sound"]["sndup_api_key"]) self.dialog.set_value("sound", "indicate_audio", self.config["sound"]["indicate_audio"])
language_index = OCRSpace.OcrLangs.index(self.config["mysc"]["ocr_language"]) self.dialog.set_value("sound", "indicate_geo", self.config["sound"]["indicate_geo"])
self.dialog.extras.ocr_lang.SetSelection(language_index) self.dialog.set_value("sound", "indicate_img", self.config["sound"]["indicate_img"])
self.dialog.realize() self.dialog.create_extras(OCRSpace.translatable_langs)
self.dialog.set_title(_(u"Account settings for %s") % (self.user,)) self.dialog.set_value("extras", "sndup_apiKey", self.config["sound"]["sndup_api_key"])
self.response = self.dialog.get_response() language_index = OCRSpace.OcrLangs.index(self.config["mysc"]["ocr_language"])
self.dialog.extras.ocr_lang.SetSelection(language_index)
def save_configuration(self): self.dialog.realize()
if self.config["general"]["relative_times"] != self.dialog.get_value("general", "relative_time"): self.dialog.set_title(_(u"Account settings for %s") % (self.user,))
self.needs_restart = True self.response = self.dialog.get_response()
self.config["general"]["relative_times"] = self.dialog.get_value("general", "relative_time")
self.config["general"]["show_screen_names"] = self.dialog.get_value("general", "show_screen_names") def save_configuration(self):
self.config["general"]["max_api_calls"] = self.dialog.get_value("general", "apiCalls") if self.config["general"]["relative_times"] != self.dialog.get_value("general", "relative_time"):
self.config["general"]["max_tweets_per_call"] = self.dialog.get_value("general", "itemsPerApiCall") self.needs_restart = True
if self.config["general"]["persist_size"] != self.dialog.get_value("general", "persist_size"): self.config["general"]["relative_times"] = self.dialog.get_value("general", "relative_time")
if self.dialog.get_value("general", "persist_size") == '': self.config["general"]["show_screen_names"] = self.dialog.get_value("general", "show_screen_names")
self.config["general"]["persist_size"] =-1 self.config["general"]["max_api_calls"] = self.dialog.get_value("general", "apiCalls")
else: self.config["general"]["max_tweets_per_call"] = self.dialog.get_value("general", "itemsPerApiCall")
try: if self.config["general"]["persist_size"] != self.dialog.get_value("general", "persist_size"):
self.config["general"]["persist_size"] = int(self.dialog.get_value("general", "persist_size")) if self.dialog.get_value("general", "persist_size") == '':
except ValueError: self.config["general"]["persist_size"] =-1
output.speak("Invalid cache size, setting to default.",True) else:
self.config["general"]["persist_size"] =1764 try:
self.config["general"]["persist_size"] = int(self.dialog.get_value("general", "persist_size"))
if self.config["general"]["reverse_timelines"] != self.dialog.get_value("general", "reverse_timelines"): except ValueError:
self.needs_restart = True output.speak("Invalid cache size, setting to default.",True)
self.config["general"]["reverse_timelines"] = self.dialog.get_value("general", "reverse_timelines") self.config["general"]["persist_size"] =1764
rt = self.dialog.get_value("general", "retweet_mode")
if rt == _(u"Ask"): if self.config["general"]["reverse_timelines"] != self.dialog.get_value("general", "reverse_timelines"):
self.config["general"]["retweet_mode"] = "ask" self.needs_restart = True
elif rt == _(u"Retweet without comments"): self.config["general"]["reverse_timelines"] = self.dialog.get_value("general", "reverse_timelines")
self.config["general"]["retweet_mode"] = "direct" rt = self.dialog.get_value("general", "retweet_mode")
else: if rt == _(u"Ask"):
self.config["general"]["retweet_mode"] = "comment" self.config["general"]["retweet_mode"] = "ask"
buffers_list = self.dialog.buffers.get_list() elif rt == _(u"Retweet without comments"):
if set(self.config["general"]["buffer_order"]) != set(buffers_list) or buffers_list != self.config["general"]["buffer_order"]: self.config["general"]["retweet_mode"] = "direct"
self.needs_restart = True else:
self.config["general"]["buffer_order"] = buffers_list self.config["general"]["retweet_mode"] = "comment"
self.config["mysc"]["ocr_language"] = OCRSpace.OcrLangs[self.dialog.extras.ocr_lang.GetSelection()] buffers_list = self.dialog.buffers.get_list()
# if self.config["other_buffers"]["show_followers"] != self.dialog.get_value("buffers", "followers"): if set(self.config["general"]["buffer_order"]) != set(buffers_list) or buffers_list != self.config["general"]["buffer_order"]:
# self.config["other_buffers"]["show_followers"] = self.dialog.get_value("buffers", "followers") self.needs_restart = True
# pub.sendMessage("create-new-buffer", buffer="followers", account=self.user, create=self.config["other_buffers"]["show_followers"]) self.config["general"]["buffer_order"] = buffers_list
# if self.config["other_buffers"]["show_friends"] != self.dialog.get_value("buffers", "friends"): self.config["mysc"]["ocr_language"] = OCRSpace.OcrLangs[self.dialog.extras.ocr_lang.GetSelection()]
# self.config["other_buffers"]["show_friends"] = self.dialog.get_value("buffers", "friends") # if self.config["other_buffers"]["show_followers"] != self.dialog.get_value("buffers", "followers"):
# pub.sendMessage("create-new-buffer", buffer="friends", account=self.user, create=self.config["other_buffers"]["show_friends"]) # self.config["other_buffers"]["show_followers"] = self.dialog.get_value("buffers", "followers")
# if self.config["other_buffers"]["show_favourites"] != self.dialog.get_value("buffers", "favs"): # pub.sendMessage("create-new-buffer", buffer="followers", account=self.user, create=self.config["other_buffers"]["show_followers"])
# self.config["other_buffers"]["show_favourites"] = self.dialog.get_value("buffers", "favs") # if self.config["other_buffers"]["show_friends"] != self.dialog.get_value("buffers", "friends"):
# pub.sendMessage("create-new-buffer", buffer="favourites", account=self.user, create=self.config["other_buffers"]["show_favourites"]) # self.config["other_buffers"]["show_friends"] = self.dialog.get_value("buffers", "friends")
# if self.config["other_buffers"]["show_blocks"] != self.dialog.get_value("buffers", "blocks"): # pub.sendMessage("create-new-buffer", buffer="friends", account=self.user, create=self.config["other_buffers"]["show_friends"])
# self.config["other_buffers"]["show_blocks"] = self.dialog.get_value("buffers", "blocks") # if self.config["other_buffers"]["show_favourites"] != self.dialog.get_value("buffers", "favs"):
# pub.sendMessage("create-new-buffer", buffer="blocked", account=self.user, create=self.config["other_buffers"]["show_blocks"]) # self.config["other_buffers"]["show_favourites"] = self.dialog.get_value("buffers", "favs")
# if self.config["other_buffers"]["show_muted_users"] != self.dialog.get_value("buffers", "mutes"): # pub.sendMessage("create-new-buffer", buffer="favourites", account=self.user, create=self.config["other_buffers"]["show_favourites"])
# self.config["other_buffers"]["show_muted_users"] = self.dialog.get_value("buffers", "mutes") # if self.config["other_buffers"]["show_blocks"] != self.dialog.get_value("buffers", "blocks"):
# pub.sendMessage("create-new-buffer", buffer="muted", account=self.user, create=self.config["other_buffers"]["show_muted_users"]) # self.config["other_buffers"]["show_blocks"] = self.dialog.get_value("buffers", "blocks")
# if self.config["other_buffers"]["show_events"] != self.dialog.get_value("buffers", "events"): # pub.sendMessage("create-new-buffer", buffer="blocked", account=self.user, create=self.config["other_buffers"]["show_blocks"])
# self.config["other_buffers"]["show_events"] = self.dialog.get_value("buffers", "events") # if self.config["other_buffers"]["show_muted_users"] != self.dialog.get_value("buffers", "mutes"):
# pub.sendMessage("create-new-buffer", buffer="events", account=self.user, create=self.config["other_buffers"]["show_events"]) # self.config["other_buffers"]["show_muted_users"] = self.dialog.get_value("buffers", "mutes")
if self.config["sound"]["input_device"] != self.dialog.sound.get("input"): # pub.sendMessage("create-new-buffer", buffer="muted", account=self.user, create=self.config["other_buffers"]["show_muted_users"])
self.config["sound"]["input_device"] = self.dialog.sound.get("input") # if self.config["other_buffers"]["show_events"] != self.dialog.get_value("buffers", "events"):
try: # self.config["other_buffers"]["show_events"] = self.dialog.get_value("buffers", "events")
self.buffer.session.sound.input.set_device(self.buffer.session.sound.input.find_device_by_name(self.config["sound"]["input_device"])) # pub.sendMessage("create-new-buffer", buffer="events", account=self.user, create=self.config["other_buffers"]["show_events"])
except: if self.config["sound"]["input_device"] != self.dialog.sound.get("input"):
self.config["sound"]["input_device"] = "default" self.config["sound"]["input_device"] = self.dialog.sound.get("input")
if self.config["sound"]["output_device"] != self.dialog.sound.get("output"): try:
self.config["sound"]["output_device"] = self.dialog.sound.get("output") self.buffer.session.sound.input.set_device(self.buffer.session.sound.input.find_device_by_name(self.config["sound"]["input_device"]))
try: except:
self.buffer.session.sound.output.set_device(self.buffer.session.sound.output.find_device_by_name(self.config["sound"]["output_device"])) self.config["sound"]["input_device"] = "default"
except: if self.config["sound"]["output_device"] != self.dialog.sound.get("output"):
self.config["sound"]["output_device"] = "default" self.config["sound"]["output_device"] = self.dialog.sound.get("output")
self.config["sound"]["volume"] = self.dialog.get_value("sound", "volumeCtrl")/100.0 try:
self.config["sound"]["session_mute"] = self.dialog.get_value("sound", "session_mute") self.buffer.session.sound.output.set_device(self.buffer.session.sound.output.find_device_by_name(self.config["sound"]["output_device"]))
self.config["sound"]["current_soundpack"] = self.dialog.sound.get("soundpack") except:
self.config["sound"]["indicate_audio"] = self.dialog.get_value("sound", "indicate_audio") self.config["sound"]["output_device"] = "default"
self.config["sound"]["indicate_geo"] = self.dialog.get_value("sound", "indicate_geo") self.config["sound"]["volume"] = old_div(self.dialog.get_value("sound", "volumeCtrl"),100.0)
self.config["sound"]["indicate_img"] = self.dialog.get_value("sound", "indicate_img") self.config["sound"]["session_mute"] = self.dialog.get_value("sound", "session_mute")
self.config["sound"]["sndup_api_key"] = self.dialog.get_value("extras", "sndup_apiKey") self.config["sound"]["current_soundpack"] = self.dialog.sound.get("soundpack")
self.buffer.session.sound.config = self.config["sound"] self.config["sound"]["indicate_audio"] = self.dialog.get_value("sound", "indicate_audio")
self.buffer.session.sound.check_soundpack() self.config["sound"]["indicate_geo"] = self.dialog.get_value("sound", "indicate_geo")
self.config.write() self.config["sound"]["indicate_img"] = self.dialog.get_value("sound", "indicate_img")
self.config["sound"]["sndup_api_key"] = self.dialog.get_value("extras", "sndup_apiKey")
def toggle_state(self,*args,**kwargs): self.buffer.session.sound.config = self.config["sound"]
return self.dialog.buffers.change_selected_item() self.buffer.session.sound.check_soundpack()
self.config.write()
def manage_autocomplete(self, *args, **kwargs):
configuration = settings.autocompletionSettings(self.buffer.session.settings, self.buffer, self.window) def toggle_state(self,*args,**kwargs):
return self.dialog.buffers.change_selected_item()
def add_ignored_client(self, *args, **kwargs):
client = commonMessageDialogs.get_ignored_client() def manage_autocomplete(self, *args, **kwargs):
if client == None: return configuration = settings.autocompletionSettings(self.buffer.session.settings, self.buffer, self.window)
if client not in self.config["twitter"]["ignored_clients"]:
self.config["twitter"]["ignored_clients"].append(client) def add_ignored_client(self, *args, **kwargs):
self.dialog.ignored_clients.append(client) client = commonMessageDialogs.get_ignored_client()
if client == None: return
def remove_ignored_client(self, *args, **kwargs): if client not in self.config["twitter"]["ignored_clients"]:
if self.dialog.ignored_clients.get_clients() == 0: return self.config["twitter"]["ignored_clients"].append(client)
id = self.dialog.ignored_clients.get_client_id() self.dialog.ignored_clients.append(client)
self.config["twitter"]["ignored_clients"].pop(id)
self.dialog.ignored_clients.remove_(id) def remove_ignored_client(self, *args, **kwargs):
if self.dialog.ignored_clients.get_clients() == 0: return
def get_buffers_list(self): id = self.dialog.ignored_clients.get_client_id()
all_buffers=OrderedDict() self.config["twitter"]["ignored_clients"].pop(id)
all_buffers['home']=_(u"Home") self.dialog.ignored_clients.remove_(id)
all_buffers['mentions']=_(u"Mentions")
all_buffers['dm']=_(u"Direct Messages") def get_buffers_list(self):
all_buffers['sent_dm']=_(u"Sent direct messages") all_buffers=OrderedDict()
all_buffers['sent_tweets']=_(u"Sent tweets") all_buffers['home']=_(u"Home")
all_buffers['favorites']=_(u"Likes") all_buffers['mentions']=_(u"Mentions")
all_buffers['followers']=_(u"Followers") all_buffers['dm']=_(u"Direct Messages")
all_buffers['friends']=_(u"Friends") all_buffers['sent_dm']=_(u"Sent direct messages")
all_buffers['blocks']=_(u"Blocked users") all_buffers['sent_tweets']=_(u"Sent tweets")
all_buffers['muted']=_(u"Muted users") all_buffers['favorites']=_(u"Likes")
all_buffers['events']=_(u"Events") all_buffers['followers']=_(u"Followers")
list_buffers = [] all_buffers['friends']=_(u"Friends")
hidden_buffers=[] all_buffers['blocks']=_(u"Blocked users")
for i in all_buffers.keys(): all_buffers['muted']=_(u"Muted users")
if i in self.config["general"]["buffer_order"]: all_buffers['events']=_(u"Events")
list_buffers.append((i, all_buffers[i], True)) list_buffers = []
else: hidden_buffers=[]
hidden_buffers.append((i, all_buffers[i], False)) for i in list(all_buffers.keys()):
list_buffers.extend(hidden_buffers) if i in self.config["general"]["buffer_order"]:
return list_buffers list_buffers.append((i, all_buffers[i], True))
else:
def toggle_buffer_active(self, ev): hidden_buffers.append((i, all_buffers[i], False))
change = self.dialog.buffers.get_event(ev) list_buffers.extend(hidden_buffers)
if change == True: return list_buffers
self.dialog.buffers.change_selected_item()
def toggle_buffer_active(self, ev):
# def manage_pocket(self, *args, **kwargs): change = self.dialog.buffers.get_event(ev)
# if self.dialog.services.get_pocket_status() == _(u"Connect your Pocket account"): if change == True:
# self.connect_pocket() self.dialog.buffers.change_selected_item()
# else:
# self.disconnect_pocket() # def manage_pocket(self, *args, **kwargs):
# if self.dialog.services.get_pocket_status() == _(u"Connect your Pocket account"):
# def connect_pocket(self): # self.connect_pocket()
# dlg = self.dialog.services.show_pocket_dialog() # else:
# if dlg == widgetUtils.YES: # self.disconnect_pocket()
# request_token = pocket.Pocket.get_request_token(consumer_key=keys.keyring.get("pocket_consumer_key"), redirect_uri="http://127.0.0.1:8080")
# auth_url = pocket.Pocket.get_auth_url(code=request_token, redirect_uri="http://127.0.0.1:8080") # def connect_pocket(self):
# webbrowser.open_new_tab(auth_url) # dlg = self.dialog.services.show_pocket_dialog()
# httpd = BaseHTTPServer.HTTPServer(('127.0.0.1', 8080), authorisationHandler.handler) # if dlg == widgetUtils.YES:
# while authorisationHandler.logged == False: # request_token = pocket.Pocket.get_request_token(consumer_key=keys.keyring.get("pocket_consumer_key"), redirect_uri="http://127.0.0.1:8080")
# httpd.handle_request() # auth_url = pocket.Pocket.get_auth_url(code=request_token, redirect_uri="http://127.0.0.1:8080")
# user_credentials = pocket.Pocket.get_credentials(consumer_key=keys.keyring.get("pocket_consumer_key"), code=request_token) # webbrowser.open_new_tab(auth_url)
# self.dialog.services.set_pocket(True) # httpd = BaseHTTPServer.HTTPServer(('127.0.0.1', 8080), authorisationHandler.handler)
# self.config["services"]["pocket_access_token"] = user_credentials["access_token"] # while authorisationHandler.logged == False:
# httpd.handle_request()
def disconnect_dropbox(self): # user_credentials = pocket.Pocket.get_credentials(consumer_key=keys.keyring.get("pocket_consumer_key"), code=request_token)
self.config["services"]["pocket_access_token"] = "" # self.dialog.services.set_pocket(True)
self.dialog.services.set_pocket(False) # self.config["services"]["pocket_access_token"] = user_credentials["access_token"]
def disconnect_dropbox(self):
self.config["services"]["pocket_access_token"] = ""
self.dialog.services.set_pocket(False)

View File

@ -1,45 +1,46 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from wxUI.dialogs import trends from builtins import object
import widgetUtils from wxUI.dialogs import trends
import widgetUtils
class trendingTopicsController(object):
def __init__(self, session): class trendingTopicsController(object):
super(trendingTopicsController, self).__init__() def __init__(self, session):
self.countries = {} super(trendingTopicsController, self).__init__()
self.cities = {} self.countries = {}
self.dialog = trends.trendingTopicsDialog() self.cities = {}
self.information = session.twitter.twitter.get_available_trends() self.dialog = trends.trendingTopicsDialog()
self.split_information() self.information = session.twitter.twitter.get_available_trends()
widgetUtils.connect_event(self.dialog.country, widgetUtils.RADIOBUTTON, self.get_places) self.split_information()
widgetUtils.connect_event(self.dialog.city, widgetUtils.RADIOBUTTON, self.get_places) widgetUtils.connect_event(self.dialog.country, widgetUtils.RADIOBUTTON, self.get_places)
self.get_places() widgetUtils.connect_event(self.dialog.city, widgetUtils.RADIOBUTTON, self.get_places)
self.get_places()
def split_information(self):
for i in self.information: def split_information(self):
if i["placeType"]["name"] == "Country": for i in self.information:
self.countries[i["name"]] = i["woeid"] if i["placeType"]["name"] == "Country":
else: self.countries[i["name"]] = i["woeid"]
self.cities[i["name"]] = i["woeid"] else:
self.cities[i["name"]] = i["woeid"]
def get_places(self, event=None):
values = [] def get_places(self, event=None):
if self.dialog.get_active() == "country": values = []
for i in self.information: if self.dialog.get_active() == "country":
if i["placeType"]["name"] == "Country": for i in self.information:
values.append(i["name"]) if i["placeType"]["name"] == "Country":
elif self.dialog.get_active() == "city": values.append(i["name"])
for i in self.information: elif self.dialog.get_active() == "city":
if i["placeType"]["name"] != "Country": for i in self.information:
values.append(i["name"]) if i["placeType"]["name"] != "Country":
self.dialog.set(values) values.append(i["name"])
self.dialog.set(values)
def get_woeid(self):
selected = self.dialog.get_item() def get_woeid(self):
if self.dialog.get_active() == "country": selected = self.dialog.get_item()
woeid = self.countries[selected] if self.dialog.get_active() == "country":
else: woeid = self.countries[selected]
woeid = self.cities[selected] else:
return woeid woeid = self.cities[selected]
return woeid
def get_string(self):
def get_string(self):
return self.dialog.get_item() return self.dialog.get_item()

View File

@ -1,4 +1,5 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from builtins import object
import wx import wx
import webbrowser import webbrowser
import widgetUtils import widgetUtils

View File

@ -1,4 +1,5 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from builtins import object
import re import re
import widgetUtils import widgetUtils
import output import output

View File

@ -17,6 +17,8 @@
# #
############################################################ ############################################################
from __future__ import absolute_import from __future__ import absolute_import
from builtins import str
from builtins import object
import widgetUtils import widgetUtils
from . import wx_ui from . import wx_ui
from . import wx_transfer_dialogs from . import wx_transfer_dialogs
@ -132,7 +134,7 @@ class audioUploader(object):
def _play(self): def _play(self):
output.speak(_(u"Playing...")) output.speak(_(u"Playing..."))
# try: # try:
self.playing = sound_lib.stream.FileStream(file=unicode(self.file), flags=sound_lib.stream.BASS_UNICODE) self.playing = sound_lib.stream.FileStream(file=str(self.file), flags=sound_lib.stream.BASS_UNICODE)
self.playing.play() self.playing.play()
self.dialog.set("play", _(u"&Stop")) self.dialog.set("play", _(u"&Stop"))
try: try:

View File

@ -1,5 +1,8 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import absolute_import from __future__ import absolute_import
from __future__ import division
from builtins import object
from past.utils import old_div
import sys import sys
import threading import threading
import time import time
@ -21,7 +24,7 @@ class Upload(object):
self.background_thread = None self.background_thread = None
self.transfer_rate = 0 self.transfer_rate = 0
self.local_filename=os.path.basename(self.filename) self.local_filename=os.path.basename(self.filename)
if isinstance(self.local_filename, unicode): if isinstance(self.local_filename, str):
self.local_filename=self.local_filename.encode(sys.getfilesystemencoding()) self.local_filename=self.local_filename.encode(sys.getfilesystemencoding())
self.fin=open(self.filename, 'rb') self.fin=open(self.filename, 'rb')
self.m = MultipartEncoder(fields={field:(self.local_filename, self.fin, "application/octet-stream")}) self.m = MultipartEncoder(fields={field:(self.local_filename, self.fin, "application/octet-stream")})
@ -44,11 +47,11 @@ class Upload(object):
progress["percent"] = 0 progress["percent"] = 0
self.transfer_rate = 0 self.transfer_rate = 0
else: else:
progress["percent"] = int((float(progress["current"]) / progress["total"]) * 100) progress["percent"] = int((old_div(float(progress["current"]), progress["total"])) * 100)
self.transfer_rate = progress["current"] / self.elapsed_time() self.transfer_rate = old_div(progress["current"], self.elapsed_time())
progress["speed"] = '%s/s' % convert_bytes(self.transfer_rate) progress["speed"] = '%s/s' % convert_bytes(self.transfer_rate)
if self.transfer_rate: if self.transfer_rate:
progress["eta"] = (progress["total"] - progress["current"]) / self.transfer_rate progress["eta"] = old_div((progress["total"] - progress["current"]), self.transfer_rate)
else: else:
progress["eta"] = 0 progress["eta"] = 0
pub.sendMessage("uploading", data=progress) pub.sendMessage("uploading", data=progress)

View File

@ -1,42 +1,45 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
def convert_bytes(n): from __future__ import division
K, M, G, T, P = 1 << 10, 1 << 20, 1 << 30, 1 << 40, 1 << 50 from builtins import str
if n >= P: from past.utils import old_div
return '%.2fPb' % (float(n) / T) def convert_bytes(n):
elif n >= T: K, M, G, T, P = 1 << 10, 1 << 20, 1 << 30, 1 << 40, 1 << 50
return '%.2fTb' % (float(n) / T) if n >= P:
elif n >= G: return '%.2fPb' % (old_div(float(n), T))
return '%.2fGb' % (float(n) / G) elif n >= T:
elif n >= M: return '%.2fTb' % (old_div(float(n), T))
return '%.2fMb' % (float(n) / M) elif n >= G:
elif n >= K: return '%.2fGb' % (old_div(float(n), G))
return '%.2fKb' % (float(n) / K) elif n >= M:
else: return '%.2fMb' % (old_div(float(n), M))
return '%d' % n elif n >= K:
return '%.2fKb' % (old_div(float(n), K))
def seconds_to_string(seconds, precision=0): else:
day = seconds // 86400 return '%d' % n
hour = seconds // 3600
min = (seconds // 60) % 60 def seconds_to_string(seconds, precision=0):
sec = seconds - (hour * 3600) - (min * 60) day = seconds // 86400
sec_spec = "." + str(precision) + "f" hour = seconds // 3600
sec_string = sec.__format__(sec_spec) min = (seconds // 60) % 60
string = "" sec = seconds - (hour * 3600) - (min * 60)
if day == 1: sec_spec = "." + str(precision) + "f"
string += _(u"%d day, ") % day sec_string = sec.__format__(sec_spec)
elif day >= 2: string = ""
string += _(u"%d days, ") % day if day == 1:
if (hour == 1): string += _(u"%d day, ") % day
string += _(u"%d hour, ") % hour elif day >= 2:
elif (hour >= 2): string += _(u"%d days, ") % day
string += _("%d hours, ") % hour if (hour == 1):
if (min == 1): string += _(u"%d hour, ") % hour
string += _(u"%d minute, ") % min elif (hour >= 2):
elif (min >= 2): string += _("%d hours, ") % hour
string += _(u"%d minutes, ") % min if (min == 1):
if sec >= 0 and sec <= 2: string += _(u"%d minute, ") % min
string += _(u"%s second") % sec_string elif (min >= 2):
else: string += _(u"%d minutes, ") % min
string += _(u"%s seconds") % sec_string if sec >= 0 and sec <= 2:
string += _(u"%s second") % sec_string
else:
string += _(u"%s seconds") % sec_string
return string return string

View File

@ -1,5 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import absolute_import from __future__ import absolute_import
from builtins import object
import platform import platform
import widgetUtils import widgetUtils
import os import os

View File

@ -1,5 +1,7 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import absolute_import from __future__ import absolute_import
from builtins import next
from builtins import object
import logging import logging
log = logging.getLogger("extra.SpellChecker.spellChecker") log = logging.getLogger("extra.SpellChecker.spellChecker")
from . import wx_ui from . import wx_ui

View File

@ -1,5 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import absolute_import from __future__ import absolute_import
from builtins import object
import output import output
from . import storage from . import storage
from . import wx_menu from . import wx_menu

View File

@ -1,6 +1,7 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import absolute_import from __future__ import absolute_import
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from builtins import object
from . import storage from . import storage
import widgetUtils import widgetUtils
from . import wx_manage from . import wx_manage

View File

@ -1,6 +1,7 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import absolute_import from __future__ import absolute_import
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from builtins import object
from . import storage from . import storage
import widgetUtils import widgetUtils
from . import wx_settings from . import wx_settings

View File

@ -1,52 +1,53 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import sqlite3, paths from builtins import object
import sqlite3, paths
class storage(object):
def __init__(self, session_id): class storage(object):
self.connection = sqlite3.connect(paths.config_path("%s/autocompletionUsers.dat" % (session_id))) def __init__(self, session_id):
self.cursor = self.connection.cursor() self.connection = sqlite3.connect(paths.config_path("%s/autocompletionUsers.dat" % (session_id)))
if self.table_exist("users") == False: self.cursor = self.connection.cursor()
self.create_table() if self.table_exist("users") == False:
self.create_table()
def table_exist(self, table):
ask = self.cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='%s'" % (table)) def table_exist(self, table):
answer = ask.fetchone() ask = self.cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='%s'" % (table))
if answer == None: answer = ask.fetchone()
return False if answer == None:
else: return False
return True else:
return True
def get_all_users(self):
self.cursor.execute("""select * from users""") def get_all_users(self):
return self.cursor.fetchall() self.cursor.execute("""select * from users""")
return self.cursor.fetchall()
def get_users(self, term):
self.cursor.execute("""SELECT * FROM users WHERE user LIKE ?""", ('{}%'.format(term),)) def get_users(self, term):
return self.cursor.fetchall() self.cursor.execute("""SELECT * FROM users WHERE user LIKE ?""", ('{}%'.format(term),))
return self.cursor.fetchall()
def set_user(self, screen_name, user_name, from_a_buffer):
self.cursor.execute("""insert or ignore into users values(?, ?, ?)""", (screen_name, user_name, from_a_buffer)) def set_user(self, screen_name, user_name, from_a_buffer):
self.connection.commit() self.cursor.execute("""insert or ignore into users values(?, ?, ?)""", (screen_name, user_name, from_a_buffer))
self.connection.commit()
def remove_user(self, user):
self.cursor.execute("""DELETE FROM users WHERE user = ?""", (user,)) def remove_user(self, user):
self.connection.commit() self.cursor.execute("""DELETE FROM users WHERE user = ?""", (user,))
return self.cursor.fetchone() self.connection.commit()
return self.cursor.fetchone()
def remove_by_buffer(self, bufferType):
""" Removes all users saved on a buffer. BufferType is 0 for no buffer, 1 for friends and 2 for followers""" def remove_by_buffer(self, bufferType):
self.cursor.execute("""DELETE FROM users WHERE from_a_buffer = ?""", (bufferType,)) """ Removes all users saved on a buffer. BufferType is 0 for no buffer, 1 for friends and 2 for followers"""
self.connection.commit() self.cursor.execute("""DELETE FROM users WHERE from_a_buffer = ?""", (bufferType,))
return self.cursor.fetchone() self.connection.commit()
return self.cursor.fetchone()
def create_table(self):
self.cursor.execute(""" def create_table(self):
create table users( self.cursor.execute("""
user TEXT UNIQUE, create table users(
name TEXT, user TEXT UNIQUE,
from_a_buffer INTEGER name TEXT,
)""") from_a_buffer INTEGER
)""")
def __del__(self):
self.cursor.close() def __del__(self):
self.cursor.close()
self.connection.close() self.connection.close()

View File

@ -1,43 +1,44 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
""" original module taken and modified from https://github.com/ctoth/cloudOCR""" """ original module taken and modified from https://github.com/ctoth/cloudOCR"""
import requests from builtins import object
import requests
translatable_langs = [_(u"Detect automatically"), _(u"Danish"), _(u"Dutch"), _(u"English"), _(u"Finnish"), _(u"French"), _(u"German"), _(u"Hungarian"), _(u"Korean"), _(u"Italian"), _(u"Japanese"), _(u"Polish"), _(u"Portuguese"), _(u"Russian"), _(u"Spanish"), _(u"Turkish")]
short_langs = ["", "da", "du", "en", "fi", "fr", "de", "hu", "ko", "it", "ja", "pl", "pt", "ru", "es", "tr"] translatable_langs = [_(u"Detect automatically"), _(u"Danish"), _(u"Dutch"), _(u"English"), _(u"Finnish"), _(u"French"), _(u"German"), _(u"Hungarian"), _(u"Korean"), _(u"Italian"), _(u"Japanese"), _(u"Polish"), _(u"Portuguese"), _(u"Russian"), _(u"Spanish"), _(u"Turkish")]
OcrLangs = ["", "dan", "dut", "eng", "fin", "fre", "ger", "hun", "kor", "ita", "jpn", "pol", "por", "rus", "spa", "tur"] short_langs = ["", "da", "du", "en", "fi", "fr", "de", "hu", "ko", "it", "ja", "pl", "pt", "ru", "es", "tr"]
OcrLangs = ["", "dan", "dut", "eng", "fin", "fre", "ger", "hun", "kor", "ita", "jpn", "pol", "por", "rus", "spa", "tur"]
class APIError(Exception):
pass class APIError(Exception):
pass
class OCRSpaceAPI(object):
class OCRSpaceAPI(object):
def __init__(self, key="4e72ae996f88957", url='https://api.ocr.space/parse/image'):
self.key = key def __init__(self, key="4e72ae996f88957", url='https://api.ocr.space/parse/image'):
self.url = url self.key = key
self.url = url
def OCR_URL(self, url, overlay=False, lang=None):
payload = { def OCR_URL(self, url, overlay=False, lang=None):
'url': url, payload = {
'isOverlayRequired': overlay, 'url': url,
'apikey': self.key, 'isOverlayRequired': overlay,
} 'apikey': self.key,
if lang != None: }
payload.update(language=lang) if lang != None:
r = requests.post(self.url, data=payload) payload.update(language=lang)
result = r.json()['ParsedResults'][0] r = requests.post(self.url, data=payload)
if result['ErrorMessage']: result = r.json()['ParsedResults'][0]
raise APIError(result['ErrorMessage']) if result['ErrorMessage']:
return result raise APIError(result['ErrorMessage'])
return result
def OCR_file(self, fileobj, overlay=False):
payload = { def OCR_file(self, fileobj, overlay=False):
'isOverlayRequired': overlay, payload = {
'apikey': self.key, 'isOverlayRequired': overlay,
'lang': 'es', 'apikey': self.key,
} 'lang': 'es',
r = requests.post(self.url, data=payload, files={'file': fileobj}) }
results = r.json()['ParsedResults'] r = requests.post(self.url, data=payload, files={'file': fileobj})
if results[0]['ErrorMessage']: results = r.json()['ParsedResults']
raise APIError(results[0]['ErrorMessage']) if results[0]['ErrorMessage']:
return results raise APIError(results[0]['ErrorMessage'])
return results

View File

@ -1,13 +1,12 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from builtins import zip
from yandex_translate import YandexTranslate from yandex_translate import YandexTranslate
def translate(text="", target="en"): def translate(text="", source="auto", target="en"):
t = YandexTranslate("trnsl.1.1.20161012T134532Z.d01b9c75fc39aa74.7d1be75a5166a80583eeb020e10f584168da6bf7") t = YandexTranslate("trnsl.1.1.20161012T134532Z.d01b9c75fc39aa74.7d1be75a5166a80583eeb020e10f584168da6bf7")
vars = dict(text=text, lang=target) return t.translate(text, target)["text"][0]
return t.translate(**vars)["text"][0]
supported_langs = None
d = None
languages = { languages = {
"af": _("Afrikaans"), "af": _("Afrikaans"),
"sq": _("Albanian"), "sq": _("Albanian"),
@ -73,7 +72,7 @@ languages = {
"ps": _("Pashto"), "ps": _("Pashto"),
"fa": _("Persian"), "fa": _("Persian"),
"pl": _("Polish"), "pl": _("Polish"),
"pt": _("Portuguese"), "pt-PT": _("Portuguese"),
"pa": _("Punjabi"), "pa": _("Punjabi"),
"ro": _("Romanian"), "ro": _("Romanian"),
"ru": _("Russian"), "ru": _("Russian"),
@ -103,11 +102,8 @@ languages = {
} }
def available_languages(): def available_languages():
global supported_langs, d l = list(languages.keys())
if supported_langs == None and d == None: d = list(languages.values())
t = YandexTranslate("trnsl.1.1.20161012T134532Z.d01b9c75fc39aa74.7d1be75a5166a80583eeb020e10f584168da6bf7") l.insert(0, '')
supported_langs = t.langs d.insert(0, _("autodetect"))
d = [] return sorted(zip(l, d))
for i in supported_langs:
d.append(languages[i])
return sorted(zip(supported_langs, d))

View File

@ -1,24 +1,26 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from requests.packages import urllib3 from future import standard_library
from requests.packages.urllib3 import fields standard_library.install_aliases()
import six from requests.packages import urllib3
import urllib from requests.packages.urllib3 import fields
import six
def fix(): import urllib.request, urllib.parse, urllib.error
urllib3.disable_warnings()
fields.format_header_param=patched_format_header_param def fix():
urllib3.disable_warnings()
def patched_format_header_param(name, value): fields.format_header_param=patched_format_header_param
if not any(ch in value for ch in '"\\\r\n'):
result = '%s="%s"' % (name, value) def patched_format_header_param(name, value):
try: if not any(ch in value for ch in '"\\\r\n'):
result.encode('ascii') result = '%s="%s"' % (name, value)
except (UnicodeEncodeError, UnicodeDecodeError): try:
pass result.encode('ascii')
else: except (UnicodeEncodeError, UnicodeDecodeError):
return result pass
if not six.PY3 and isinstance(value, six.text_type): # Python 2: else:
value = value.encode('utf-8') return result
value=urllib.quote(value, safe='') if not six.PY3 and isinstance(value, six.text_type): # Python 2:
value = '%s=%s' % (name, value) value = value.encode('utf-8')
return value value=urllib.parse.quote(value, safe='')
value = '%s=%s' % (name, value)
return value

View File

@ -17,6 +17,7 @@
# #
############################################################ ############################################################
from __future__ import absolute_import from __future__ import absolute_import
from builtins import object
import keys import keys
import wx import wx
from . import wx_ui from . import wx_ui

View File

@ -1,7 +1,10 @@
from __future__ import absolute_import from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import chr
from .main import KeyboardHandler from .main import KeyboardHandler
import threading import threading
import thread import _thread
import pyatspi import pyatspi
def parse(s): def parse(s):
"""parse a string like control+f into (modifier, key). """parse a string like control+f into (modifier, key).
@ -37,7 +40,7 @@ def handler(e):
if (not e.is_text) and e.id >= 97 <= 126: if (not e.is_text) and e.id >= 97 <= 126:
k = chr(e.id) k = chr(e.id)
if (m,k) not in keys: return False if (m,k) not in keys: return False
thread.start_new(keys[(m,k)], ()) _thread.start_new(keys[(m,k)], ())
return True #don't pass it on return True #don't pass it on
class LinuxKeyboardHandler(KeyboardHandler): class LinuxKeyboardHandler(KeyboardHandler):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):

View File

@ -1,3 +1,4 @@
from builtins import object
import platform import platform
import time import time

View File

@ -1,4 +1,5 @@
from __future__ import absolute_import from __future__ import absolute_import
from builtins import str
from AppKit import * from AppKit import *
from PyObjCTools import AppHelper from PyObjCTools import AppHelper
from Carbon.CarbonEvt import RegisterEventHotKey, GetApplicationEventTarget from Carbon.CarbonEvt import RegisterEventHotKey, GetApplicationEventTarget

View File

@ -1,4 +1,5 @@
from __future__ import absolute_import from __future__ import absolute_import
from builtins import str
import win32api import win32api
import win32con import win32con

View File

@ -1,5 +1,6 @@
from __future__ import print_function from __future__ import print_function
from __future__ import absolute_import from __future__ import absolute_import
from builtins import chr
import functools import functools
import wx import wx
import platform import platform
@ -84,7 +85,7 @@ class WXKeyboardHandler(keyboard_handler):
def process_key (self, evt, id): def process_key (self, evt, id):
evt.Skip() evt.Skip()
key_ids = self.key_ids.keys() key_ids = list(self.key_ids.keys())
for i in key_ids: for i in key_ids:
if self.key_ids.get(i) == id: if self.key_ids.get(i) == id:
self.handle_key(i) self.handle_key(i)

View File

@ -1,41 +1,41 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import application from builtins import object
import platform import application
import exceptions import platform
from ctypes import c_char_p from ctypes import c_char_p
from libloader import load_library from libloader import load_library
import paths import paths
#if application.snapshot == True: #if application.snapshot == True:
# if platform.architecture()[0][:2] == "32": # if platform.architecture()[0][:2] == "32":
# lib = load_library("snapshot_api_keys32", x86_path=paths.app_path("keys/lib")) # lib = load_library("snapshot_api_keys32", x86_path=paths.app_path("keys/lib"))
# else: # else:
# lib = load_library("snapshot_api_keys64", x64_path=paths.app_path("keys/lib")) # lib = load_library("snapshot_api_keys64", x64_path=paths.app_path("keys/lib"))
#else: #else:
if platform.architecture()[0][:2] == "32": if platform.architecture()[0][:2] == "32":
lib = load_library("stable_api_keys32", x86_path=paths.app_path("keys/lib")) lib = load_library("stable_api_keys32", x86_path=paths.app_path("keys/lib"))
else: else:
lib = load_library("stable_api_keys64", x64_path=paths.app_path("keys/lib")) lib = load_library("stable_api_keys64", x64_path=paths.app_path("keys/lib"))
# import linuxKeys # import linuxKeys
# lib = linuxKeys # lib = linuxKeys
keyring = None keyring = None
def setup(): def setup():
global keyring global keyring
if keyring == None: if keyring == None:
keyring = Keyring() keyring = Keyring()
class Keyring(object): class Keyring(object):
def __init__(self): def __init__(self):
super(Keyring, self).__init__() super(Keyring, self).__init__()
def _call_method(self, function): def _call_method(self, function):
result = getattr(lib, function) result = getattr(lib, function)
result = c_char_p(result.__call__()) result = c_char_p(result.__call__())
return result.value return result.value
def get(self, func): def get(self, func):
if hasattr(application,func+"_override"): if hasattr(application,func+"_override"):
return getattr(application,func+'_override') return getattr(application,func+'_override')
return getattr(self, "_call_method")("get_"+func) return getattr(self, "_call_method")("get_"+func)

View File

@ -1,5 +1,6 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import absolute_import from __future__ import absolute_import
from builtins import object
import widgetUtils import widgetUtils
import config import config
from . import wx_ui from . import wx_ui

View File

@ -1,212 +1,212 @@
import __builtin__ import builtins
import os import os
import sys import sys
import ctypes import ctypes
import locale import locale
# add mapping for Serbian (latin) language # add mapping for Serbian (latin) language
locale.windows_locale[9242]='sr_RS' locale.windows_locale[9242]='sr_RS'
import gettext import gettext
import paths import paths
import platform import platform
# A fix for the mac locales # A fix for the mac locales
#if platform.system() == 'Darwin': #if platform.system() == 'Darwin':
#a few Windows locale constants #a few Windows locale constants
LOCALE_SLANGUAGE=0x2 LOCALE_SLANGUAGE=0x2
LOCALE_SLANGDISPLAYNAME=0x6f LOCALE_SLANGDISPLAYNAME=0x6f
curLang="en" curLang="en"
def localeNameToWindowsLCID(localeName): def localeNameToWindowsLCID(localeName):
"""Retreave the Windows locale identifier (LCID) for the given locale name """Retreave the Windows locale identifier (LCID) for the given locale name
@param localeName: a string of 2letterLanguage_2letterCountry or or just 2letterLanguage @param localeName: a string of 2letterLanguage_2letterCountry or or just 2letterLanguage
@type localeName: string @type localeName: string
@returns: a Windows LCID @returns: a Windows LCID
@rtype: integer @rtype: integer
""" """
#Windows Vista is able to convert locale names to LCIDs #Windows Vista is able to convert locale names to LCIDs
func_LocaleNameToLCID=getattr(ctypes.windll.kernel32,'LocaleNameToLCID',None) func_LocaleNameToLCID=getattr(ctypes.windll.kernel32,'LocaleNameToLCID',None)
if func_LocaleNameToLCID is not None: if func_LocaleNameToLCID is not None:
localeName=localeName.replace('_','-') localeName=localeName.replace('_','-')
LCID=func_LocaleNameToLCID(unicode(localeName),0) LCID=func_LocaleNameToLCID(str(localeName),0)
else: #Windows doesn't have this functionality, manually search Python's windows_locale dictionary for the LCID else: #Windows doesn't have this functionality, manually search Python's windows_locale dictionary for the LCID
localeName=locale.normalize(localeName) localeName=locale.normalize(localeName)
if '.' in localeName: if '.' in localeName:
localeName=localeName.split('.')[0] localeName=localeName.split('.')[0]
LCList=[x[0] for x in locale.windows_locale.iteritems() if x[1]==localeName] LCList=[x[0] for x in locale.windows_locale.items() if x[1]==localeName]
if len(LCList)>0: if len(LCList)>0:
LCID=LCList[0] LCID=LCList[0]
else: else:
LCID=0 LCID=0
return LCID return LCID
def getLanguageDescription(language): def getLanguageDescription(language):
"""Finds out the description (localized full name) of a given local name""" """Finds out the description (localized full name) of a given local name"""
desc=None desc=None
if platform.system() == "Windows": if platform.system() == "Windows":
LCID=localeNameToWindowsLCID(language) LCID=localeNameToWindowsLCID(language)
if LCID!=0: if LCID!=0:
buf=ctypes.create_unicode_buffer(1024) buf=ctypes.create_unicode_buffer(1024)
if '_' not in language: if '_' not in language:
res=ctypes.windll.kernel32.GetLocaleInfoW(LCID,LOCALE_SLANGDISPLAYNAME,buf,1024) res=ctypes.windll.kernel32.GetLocaleInfoW(LCID,LOCALE_SLANGDISPLAYNAME,buf,1024)
else: else:
res=0 res=0
if res==0: if res==0:
res=ctypes.windll.kernel32.GetLocaleInfoW(LCID,LOCALE_SLANGUAGE,buf,1024) res=ctypes.windll.kernel32.GetLocaleInfoW(LCID,LOCALE_SLANGUAGE,buf,1024)
desc=buf.value desc=buf.value
elif platform.system() == "Linux" or not desc: elif platform.system() == "Linux" or not desc:
desc={ desc={
"am":pgettext("languageName","Amharic"), "am":pgettext("languageName","Amharic"),
"an":pgettext("languageName","Aragonese"), "an":pgettext("languageName","Aragonese"),
"es":pgettext("languageName","Spanish"), "es":pgettext("languageName","Spanish"),
"pt":pgettext("languageName","Portuguese"), "pt":pgettext("languageName","Portuguese"),
"ru":pgettext("languageName","Russian"), "ru":pgettext("languageName","Russian"),
"it":pgettext("languageName","italian"), "it":pgettext("languageName","italian"),
"tr":pgettext("languageName","Turkey"), "tr":pgettext("languageName","Turkey"),
"gl":pgettext("languageName","Galician"), "gl":pgettext("languageName","Galician"),
"ca":pgettext("languageName","Catala"), "ca":pgettext("languageName","Catala"),
"eu":pgettext("languageName","Vasque"), "eu":pgettext("languageName","Vasque"),
"pl":pgettext("languageName","polish"), "pl":pgettext("languageName","polish"),
"ar":pgettext("languageName","Arabic"), "ar":pgettext("languageName","Arabic"),
"ne":pgettext("languageName","Nepali"), "ne":pgettext("languageName","Nepali"),
"sr":pgettext("languageName","Serbian (Latin)"), "sr":pgettext("languageName","Serbian (Latin)"),
"ja":pgettext("languageName","Japanese"), "ja":pgettext("languageName","Japanese"),
"ro":pgettext("languageName","Romanian"), "ro":pgettext("languageName","Romanian"),
}.get(language,None) }.get(language,None)
return desc return desc
def getAvailableLanguages(): def getAvailableLanguages():
"""generates a list of locale names, plus their full localized language and country names. """generates a list of locale names, plus their full localized language and country names.
@rtype: list of tuples @rtype: list of tuples
""" """
#Make a list of all the locales found in NVDA's locale dir #Make a list of all the locales found in NVDA's locale dir
l=[x for x in os.listdir(paths.locale_path()) if not x.startswith('.')] l=[x for x in os.listdir(paths.locale_path()) if not x.startswith('.')]
l=[x for x in l if os.path.isfile(paths.locale_path('%s/LC_MESSAGES/twblue.mo' % x))] l=[x for x in l if os.path.isfile(paths.locale_path('%s/LC_MESSAGES/twblue.mo' % x))]
#Make sure that en (english) is in the list as it may not have any locale files, but is default #Make sure that en (english) is in the list as it may not have any locale files, but is default
if 'en' not in l: if 'en' not in l:
l.append('en') l.append('en')
l.sort() l.sort()
#For each locale, ask Windows for its human readable display name #For each locale, ask Windows for its human readable display name
d=[] d=[]
for i in l: for i in l:
desc=getLanguageDescription(i) desc=getLanguageDescription(i)
label="%s, %s"%(desc,i) if desc else i label="%s, %s"%(desc,i) if desc else i
d.append(label) d.append(label)
#include a 'user default, windows' language, which just represents the default language for this user account #include a 'user default, windows' language, which just represents the default language for this user account
l.append("system") l.append("system")
# Translators: the label for the Windows default NVDA interface language. # Translators: the label for the Windows default NVDA interface language.
d.append(_("User default")) d.append(_("User default"))
#return a zipped up version of both the lists (a list with tuples of locale,label) #return a zipped up version of both the lists (a list with tuples of locale,label)
return zip(l,d) return list(zip(l,d))
def makePgettext(translations): def makePgettext(translations):
"""Obtaina pgettext function for use with a gettext translations instance. """Obtaina pgettext function for use with a gettext translations instance.
pgettext is used to support message contexts, pgettext is used to support message contexts,
but Python 2.7's gettext module doesn't support this, but Python 2.7's gettext module doesn't support this,
so NVDA must provide its own implementation. so NVDA must provide its own implementation.
""" """
if isinstance(translations, gettext.GNUTranslations): if isinstance(translations, gettext.GNUTranslations):
def pgettext(context, message): def pgettext(context, message):
message = unicode(message) message = str(message)
try: try:
# Look up the message with its context. # Look up the message with its context.
return translations._catalog[u"%s\x04%s" % (context, message)] return translations._catalog["%s\x04%s" % (context, message)]
except KeyError: except KeyError:
return message return message
else: else:
def pgettext(context, message): def pgettext(context, message):
return unicode(message) return str(message)
return pgettext return pgettext
def setLanguage(lang): def setLanguage(lang):
system = platform.system() system = platform.system()
global curLang global curLang
try: try:
if lang=="system": if lang=="system":
if system == "Windows": if system == "Windows":
windowsLCID=ctypes.windll.kernel32.GetUserDefaultUILanguage() windowsLCID=ctypes.windll.kernel32.GetUserDefaultUILanguage()
localeName=locale.windows_locale[windowsLCID] localeName=locale.windows_locale[windowsLCID]
elif system == "Darwin": elif system == "Darwin":
import Foundation import Foundation
localeName = Foundation.NSLocale.currentLocale().identifier() localeName = Foundation.NSLocale.currentLocale().identifier()
elif system == "Linux": elif system == "Linux":
localeName = locale.getdefaultlocale()[0] localeName = locale.getdefaultlocale()[0]
trans=gettext.translation('twblue', localedir=paths.locale_path(), languages=[localeName]) trans=gettext.translation('twblue', localedir=paths.locale_path(), languages=[localeName])
curLang=localeName curLang=localeName
# else: # else:
# localeName=locale.getdefaultlocale()[0] # localeName=locale.getdefaultlocale()[0]
# trans=gettext.translation('twblue', localedir=paths.locale_path(), languages=[localeName]) # trans=gettext.translation('twblue', localedir=paths.locale_path(), languages=[localeName])
# curLang=localeName # curLang=localeName
else: else:
trans=gettext.translation("twblue", localedir=paths.locale_path(), languages=[lang]) trans=gettext.translation("twblue", localedir=paths.locale_path(), languages=[lang])
curLang=lang curLang=lang
localeChanged=False localeChanged=False
#Try setting Python's locale to lang #Try setting Python's locale to lang
# try: # try:
if system == "Windows": if system == "Windows":
locale.setlocale(locale.LC_ALL, langToWindowsLocale(lang)) locale.setlocale(locale.LC_ALL, langToWindowsLocale(lang))
localeChanged=True localeChanged=True
else: else:
locale.setlocale(locale.LC_ALL, lang) locale.setlocale(locale.LC_ALL, lang)
localeChanged=True localeChanged=True
# except: # except:
# pass # pass
if not localeChanged and '_' in lang: if not localeChanged and '_' in lang:
#Python couldn'tsupport the language_country locale, just try language. #Python couldn'tsupport the language_country locale, just try language.
try: try:
locale.setlocale(locale.LC_ALL, lang.split('_')[0]) locale.setlocale(locale.LC_ALL, lang.split('_')[0])
except: except:
pass pass
#Set the windows locale for this thread (NVDA core) to this locale. #Set the windows locale for this thread (NVDA core) to this locale.
if system == "Windows": if system == "Windows":
LCID=localeNameToWindowsLCID(lang) LCID=localeNameToWindowsLCID(lang)
ctypes.windll.kernel32.SetThreadLocale(LCID) ctypes.windll.kernel32.SetThreadLocale(LCID)
except IOError: except IOError:
trans=gettext.translation("twblue",fallback=True) trans=gettext.translation("twblue",fallback=True)
curLang="en" curLang="en"
trans.install(unicode=True) trans.install()
# Install our pgettext function. # Install our pgettext function.
# __builtin__.__dict__["pgettext"] = makePgettext(trans) # __builtin__.__dict__["pgettext"] = makePgettext(trans)
def getLanguage(): def getLanguage():
return curLang return curLang
def normalizeLanguage(lang): def normalizeLanguage(lang):
""" """
Normalizes a language-dialect string in to a standard form we can deal with. Normalizes a language-dialect string in to a standard form we can deal with.
Converts any dash to underline, and makes sure that language is lowercase and dialect is upercase. Converts any dash to underline, and makes sure that language is lowercase and dialect is upercase.
""" """
lang=lang.replace('-','_') lang=lang.replace('-','_')
ld=lang.split('_') ld=lang.split('_')
ld[0]=ld[0].lower() ld[0]=ld[0].lower()
#Filter out meta languages such as x-western #Filter out meta languages such as x-western
if ld[0]=='x': if ld[0]=='x':
return None return None
if len(ld)>=2: if len(ld)>=2:
ld[1]=ld[1].upper() ld[1]=ld[1].upper()
return "_".join(ld) return "_".join(ld)
def langToWindowsLocale(lang): def langToWindowsLocale(lang):
languages = {"en": "eng", languages = {"en": "eng",
"ar": "ara", "ar": "ara",
"ca": "cat", "ca": "cat",
"de": "deu", "de": "deu",
"es": "esp", "es": "esp",
"fi": "fin", "fi": "fin",
"fr": "fre_FRA", "fr": "fre_FRA",
"gl": "glc", "gl": "glc",
"eu": "euq", "eu": "euq",
"hu": "hun", "hu": "hun",
"hr": "hrv", "hr": "hrv",
"it": "ita", "it": "ita",
"ja": "jpn", "ja": "jpn",
"pl": "plk", "pl": "plk",
"pt": "ptb", "pt": "ptb",
"ro": "rom", "ro": "rom",
"ru": "rus", "ru": "rus",
"tr": "trk", "tr": "trk",
"sr": "eng", "sr": "eng",
} }
return languages[lang] return languages[lang]

View File

@ -1,56 +1,57 @@
import ctypes from builtins import str
import collections import ctypes
import platform import collections
import os import platform
import os
TYPES = {
'Linux': { TYPES = {
'loader': ctypes.CDLL, 'Linux': {
'functype': ctypes.CFUNCTYPE, 'loader': ctypes.CDLL,
'prefix': 'lib', 'functype': ctypes.CFUNCTYPE,
'extension': '.so' 'prefix': 'lib',
}, 'extension': '.so'
'Darwin': { },
'loader': ctypes.CDLL, 'Darwin': {
'functype': ctypes.CFUNCTYPE, 'loader': ctypes.CDLL,
'prefix': 'lib', 'functype': ctypes.CFUNCTYPE,
'extension': '.dylib' 'prefix': 'lib',
}, 'extension': '.dylib'
} },
if platform.system() == 'Windows': }
TYPES['Windows'] = { if platform.system() == 'Windows':
'loader': ctypes.WinDLL, TYPES['Windows'] = {
'functype': ctypes.WINFUNCTYPE, 'loader': ctypes.WinDLL,
'prefix': "", 'functype': ctypes.WINFUNCTYPE,
'extension': '.dll' 'prefix': "",
} 'extension': '.dll'
}
class LibraryLoadError(OSError): pass
class LibraryLoadError(OSError): pass
def load_library(library, x86_path='.', x64_path='.', *args, **kwargs):
lib = find_library_path(library, x86_path=x86_path, x64_path=x64_path) def load_library(library, x86_path='.', x64_path='.', *args, **kwargs):
loaded = _do_load(str(lib), *args, **kwargs) lib = find_library_path(library, x86_path=x86_path, x64_path=x64_path)
if loaded is not None: loaded = _do_load(str(lib), *args, **kwargs)
return loaded if loaded is not None:
raise LibraryLoadError('unable to load %r. Provided library path: %r' % (library, lib)) return loaded
raise LibraryLoadError('unable to load %r. Provided library path: %r' % (library, lib))
def _do_load(file, *args, **kwargs):
loader = TYPES[platform.system()]['loader'] def _do_load(file, *args, **kwargs):
return loader(file, *args, **kwargs) loader = TYPES[platform.system()]['loader']
return loader(file, *args, **kwargs)
def find_library_path(libname, x86_path='.', x64_path='.'):
libname = '%s%s' % (TYPES[platform.system()]['prefix'], libname) def find_library_path(libname, x86_path='.', x64_path='.'):
if platform.architecture()[0] == '64bit': libname = '%s%s' % (TYPES[platform.system()]['prefix'], libname)
path = os.path.join(x64_path, libname) if platform.architecture()[0] == '64bit':
else: path = os.path.join(x64_path, libname)
path = os.path.join(x86_path, libname) else:
ext = get_library_extension() path = os.path.join(x86_path, libname)
path = '%s%s' % (path, ext) ext = get_library_extension()
return os.path.abspath(path) path = '%s%s' % (path, ext)
return os.path.abspath(path)
def get_functype():
return TYPES[platform.system()]['functype'] def get_functype():
return TYPES[platform.system()]['functype']
def get_library_extension():
return TYPES[platform.system()]['extension'] def get_library_extension():
return TYPES[platform.system()]['extension']

View File

@ -9,7 +9,7 @@ ERROR_LOG_FILE = "error.log"
MESSAGE_FORMAT = "%(asctime)s %(name)s %(levelname)s: %(message)s" MESSAGE_FORMAT = "%(asctime)s %(name)s %(levelname)s: %(message)s"
DATE_FORMAT = u"%d/%m/%Y %H:%M:%S" DATE_FORMAT = u"%d/%m/%Y %H:%M:%S"
formatter = logging.Formatter(MESSAGE_FORMAT.decode("utf-8"), datefmt=DATE_FORMAT) formatter = logging.Formatter(MESSAGE_FORMAT, datefmt=DATE_FORMAT)
requests_log = logging.getLogger("requests") requests_log = logging.getLogger("requests")
requests_log.setLevel(logging.WARNING) requests_log.setLevel(logging.WARNING)

View File

@ -17,6 +17,7 @@
# #
############################################################ ############################################################
from __future__ import print_function from __future__ import print_function
from builtins import range
import requests import requests
import keys import keys
import logging import logging
@ -42,7 +43,7 @@ def is_long(tweet):
# see https://github.com/manuelcortez/TWBlue/issues/103 # see https://github.com/manuelcortez/TWBlue/issues/103
except TypeError: except TypeError:
pass pass
if long == False and "retweeted_status" in tweet: if int == False and "retweeted_status" in tweet:
for url in range(0, len(tweet["retweeted_status"]["entities"]["urls"])): for url in range(0, len(tweet["retweeted_status"]["entities"]["urls"])):
try: try:
if tweet["retweeted_status"]["entities"]["urls"][url] != None and "twishort.com" in tweet["retweeted_status"]["entities"]["urls"][url]["expanded_url"]: if tweet["retweeted_status"]["entities"]["urls"][url] != None and "twishort.com" in tweet["retweeted_status"]["entities"]["urls"][url]["expanded_url"]:
@ -51,7 +52,7 @@ def is_long(tweet):
pass pass
except TypeError: except TypeError:
pass pass
return long return int
def get_full_text(uri): def get_full_text(uri):
try: try:

View File

@ -1,89 +1,92 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import wx from builtins import str
import platform from builtins import range
import logging from builtins import object
log = logging.getLogger("multiplatform_widgets.widgets") import wx
import platform
class list(object): import logging
def __init__(self, parent, *columns, **listArguments): log = logging.getLogger("multiplatform_widgets.widgets")
self.system = platform.system()
self.columns = columns class list(object):
self.listArguments = listArguments def __init__(self, parent, *columns, **listArguments):
log.debug("Creating list: Columns: %s, arguments: %s" % (self.columns, self.listArguments)) self.system = platform.system()
self.create_list(parent) self.columns = columns
# self.set_size() self.listArguments = listArguments
log.debug("Creating list: Columns: %s, arguments: %s" % (self.columns, self.listArguments))
def set_windows_size(self, column, characters_max): self.create_list(parent)
# it = wx.ListItem() # self.set_size()
# dc = wx.WindowDC(self.list)
# dc.SetFont(it.GetFont()) def set_windows_size(self, column, characters_max):
# (x, y) = dc.GetTextExtent("r"*characters_max) # it = wx.ListItem()
self.list.SetColumnWidth(column, characters_max*2) # dc = wx.WindowDC(self.list)
# dc.SetFont(it.GetFont())
def set_size(self): # (x, y) = dc.GetTextExtent("r"*characters_max)
self.list.SetSize((self.list.GetBestSize()[0], 728)) self.list.SetColumnWidth(column, characters_max*2)
# self.list.SetSize((1439, 1000))
def set_size(self):
def create_list(self, parent): self.list.SetSize((self.list.GetBestSize()[0], 728))
if self.system == "Windows": # self.list.SetSize((1439, 1000))
self.list = wx.ListCtrl(parent, -1, **self.listArguments)
for i in xrange(0, len(self.columns)): def create_list(self, parent):
self.list.InsertColumn(i, u"%s" % (self.columns[i])) if self.system == "Windows":
else: self.list = wx.ListCtrl(parent, -1, **self.listArguments)
self.list = wx.ListBox(parent, -1, choices=[]) for i in range(0, len(self.columns)):
self.list.InsertColumn(i, u"%s" % (self.columns[i]))
def insert_item(self, reversed, *item): else:
""" Inserts an item on the list, depending on the OS.""" self.list = wx.ListBox(parent, -1, choices=[])
if self.system == "Windows":
if reversed == False: items = self.list.GetItemCount() def insert_item(self, reversed, *item):
else: items = 0 """ Inserts an item on the list, depending on the OS."""
self.list.InsertItem(items, unicode(item[0])) if self.system == "Windows":
for i in xrange(1, len(self.columns)): if reversed == False: items = self.list.GetItemCount()
self.list.SetItem(items, i, unicode(item[i])) else: items = 0
else: self.list.InsertItem(items, str(item[0]))
self.list.Append(" ".join(item)) for i in range(1, len(self.columns)):
self.list.SetItem(items, i, str(item[i]))
def remove_item(self, pos): else:
""" Deletes an item from the list.""" self.list.Append(" ".join(item))
if self.system == "Windows":
if pos > 0: self.list.Focus(pos-1) def remove_item(self, pos):
self.list.DeleteItem(pos) """ Deletes an item from the list."""
else: if self.system == "Windows":
if pos > 0: self.list.SetSelection(pos-1) if pos > 0: self.list.Focus(pos-1)
self.list.Delete(pos) self.list.DeleteItem(pos)
else:
def clear(self): if pos > 0: self.list.SetSelection(pos-1)
if self.system == "Windows": self.list.Delete(pos)
self.list.DeleteAllItems()
else: def clear(self):
self.list.Clear() if self.system == "Windows":
self.list.DeleteAllItems()
def get_selected(self): else:
if self.system == "Windows": self.list.Clear()
return self.list.GetFocusedItem()
else: def get_selected(self):
return self.list.GetSelection() if self.system == "Windows":
return self.list.GetFocusedItem()
def select_item(self, pos): else:
if self.system == "Windows": return self.list.GetSelection()
self.list.Focus(pos)
else: def select_item(self, pos):
self.list.SetSelection(pos) if self.system == "Windows":
self.list.Focus(pos)
def get_count(self): else:
if self.system == "Windows": self.list.SetSelection(pos)
selected = self.list.GetItemCount()
else: def get_count(self):
selected = self.list.GetCount() if self.system == "Windows":
if selected == -1: selected = self.list.GetItemCount()
return 0 else:
else: selected = self.list.GetCount()
return selected if selected == -1:
return 0
def get_text_column(self, indexId, column): else:
item = self.list.GetItem(indexId, column) return selected
return item.GetText()
def get_text_column(self, indexId, column):
def set_text_column(self, indexId, column, text): item = self.list.GetItem(indexId, column)
item = self.list.SetItem(indexId, column, unicode(text)) return item.GetText()
def set_text_column(self, indexId, column, text):
item = self.list.SetItem(indexId, column, str(text))
return item return item

View File

@ -1,37 +1,39 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import logging from future import standard_library
log = logging.getLogger("mysc.thread_utils") standard_library.install_aliases()
import threading import logging
import wx log = logging.getLogger("mysc.thread_utils")
from pubsub import pub import threading
from twython import TwythonRateLimitError import wx
import time from pubsub import pub
from twython import TwythonRateLimitError
def call_threaded(func, *args, **kwargs): import time
#Call the given function in a daemonized thread and return the thread.
def new_func(*a, **k): def call_threaded(func, *args, **kwargs):
try: #Call the given function in a daemonized thread and return the thread.
func(*a, **k) def new_func(*a, **k):
except TwythonRateLimitError: try:
pass func(*a, **k)
except: except TwythonRateLimitError:
log.exception("Thread %d with function %r, args of %r, and kwargs of %r failed to run." % (threading.current_thread().ident, func, a, k)) pass
# pass except:
thread = threading.Thread(target=new_func, args=args, kwargs=kwargs) log.exception("Thread %d with function %r, args of %r, and kwargs of %r failed to run." % (threading.current_thread().ident, func, a, k))
thread.daemon = True # pass
thread.start() thread = threading.Thread(target=new_func, args=args, kwargs=kwargs)
return thread thread.daemon = True
thread.start()
def stream_threaded(func, *args, **kwargs): return thread
def new_func(*a, **k):
try: def stream_threaded(func, *args, **kwargs):
func(**k) def new_func(*a, **k):
except Exception as msg: try:
log.error("Error in stream with args: %r" % (a,)) func(**k)
log.error(msg.message) except Exception as msg:
pub.sendMessage("stream-error", session=a[0]) log.error("Error in stream with args: %r" % (a,))
log.error(msg.message)
thread = threading.Thread(target=new_func, args=args, kwargs=kwargs) pub.sendMessage("stream-error", session=a[0])
thread.daemon = True
thread.start() thread = threading.Thread(target=new_func, args=args, kwargs=kwargs)
thread.daemon = True
thread.start()
return thread return thread

View File

@ -1,25 +1,26 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import dbus from builtins import object
import application import dbus
import application
class notifications(object):
"""Supports notifications on Linux. class notifications(object):
""" """Supports notifications on Linux.
"""
def __init__(self):
super(notifications, self).__init__() def __init__(self):
self.item = "org.freedesktop.Notifications" super(notifications, self).__init__()
self.path = "/org/freedesktop/Notifications" self.item = "org.freedesktop.Notifications"
self.interface = "org.freedesktop.Notifications" self.path = "/org/freedesktop/Notifications"
self.app_name = application.name self.interface = "org.freedesktop.Notifications"
self.id_num_to_replace = 0 self.app_name = application.name
self.icon = "/usr/share/icons/Tango/32x32/status/sunny.png" self.id_num_to_replace = 0
self.icon = "/usr/share/icons/Tango/32x32/status/sunny.png"
def notify(self, title="", text=""):
actions_list = '' def notify(self, title="", text=""):
hint = '' actions_list = ''
time = 5000 # Use seconds x 1000 hint = ''
bus = dbus.SessionBus() time = 5000 # Use seconds x 1000
notif = bus.get_object(self.item, self.path) bus = dbus.SessionBus()
notify = dbus.Interface(notif, self.interface) notif = bus.get_object(self.item, self.path)
notify = dbus.Interface(notif, self.interface)
notify.Notify(self.app_name, self.id_num_to_replace, self.icon, title, text, actions_list, hint, time) notify.Notify(self.app_name, self.id_num_to_replace, self.icon, title, text, actions_list, hint, time)

View File

@ -1,7 +1,8 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import wx from builtins import object
import wx
class notification(object):
class notification(object):
def notify(self, title, text):
def notify(self, title, text):
wx.NotificationMessage(title, text).Show() wx.NotificationMessage(title, text).Show()

View File

@ -1,85 +1,86 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import platform from builtins import str
import os import platform
import sys import os
import logging import sys
from platform_utils import paths as paths_ import logging
from platform_utils import paths as paths_
from functools import wraps
from functools import wraps
mode = "portable"
directory = None mode = "portable"
directory = None
log = logging.getLogger("paths")
log = logging.getLogger("paths")
def merge_paths(func):
@wraps(func) def merge_paths(func):
def merge_paths_wrapper(*a): @wraps(func)
return unicode(os.path.join(func(), *a)) def merge_paths_wrapper(*a):
return merge_paths_wrapper return str(os.path.join(func(), *a))
return merge_paths_wrapper
@merge_paths
def app_path(): @merge_paths
return paths_.app_path() def app_path():
return paths_.app_path()
@merge_paths
def config_path(): @merge_paths
global mode, directory def config_path():
if mode == "portable": global mode, directory
if directory != None: path = os.path.join(directory, "config") if mode == "portable":
elif directory == None: path = app_path(u"config") if directory != None: path = os.path.join(directory, "config")
elif mode == "installed": elif directory == None: path = app_path(u"config")
path = data_path(u"config") elif mode == "installed":
if not os.path.exists(path): path = data_path(u"config")
log.debug("%s path does not exist, creating..." % (path,)) if not os.path.exists(path):
os.mkdir(path) log.debug("%s path does not exist, creating..." % (path,))
return path os.mkdir(path)
return path
@merge_paths
def logs_path(): @merge_paths
global mode, directory def logs_path():
if mode == "portable": global mode, directory
if directory != None: path = os.path.join(directory, "logs") if mode == "portable":
elif directory == None: path = app_path(u"logs") if directory != None: path = os.path.join(directory, "logs")
elif mode == "installed": elif directory == None: path = app_path(u"logs")
path = data_path(u"logs") elif mode == "installed":
if not os.path.exists(path): path = data_path(u"logs")
log.debug("%s path does not exist, creating..." % (path,)) if not os.path.exists(path):
os.mkdir(path) log.debug("%s path does not exist, creating..." % (path,))
return path os.mkdir(path)
return path
@merge_paths
def data_path(app_name='TW blue'): @merge_paths
# if platform.system() == "Windows": def data_path(app_name='TW blue'):
# import shlobj # if platform.system() == "Windows":
# data_path = os.path.join(shlobj.SHGetFolderPath(0, shlobj.CSIDL_APPDATA), app_name) # import shlobj
# else: # data_path = os.path.join(shlobj.SHGetFolderPath(0, shlobj.CSIDL_APPDATA), app_name)
if platform.system() == "Windows": # else:
import winpaths if platform.system() == "Windows":
data_path = os.path.join(winpaths.get_appdata(), app_name) import winpaths
else: data_path = os.path.join(winpaths.get_appdata(), app_name)
data_path = os.path.join(os.environ['HOME'], ".%s" % app_name) else:
if not os.path.exists(data_path): data_path = os.path.join(os.environ['HOME'], ".%s" % app_name)
os.mkdir(data_path) if not os.path.exists(data_path):
return data_path os.mkdir(data_path)
return data_path
@merge_paths
def locale_path(): @merge_paths
return app_path(u"locales") def locale_path():
return app_path(u"locales")
@merge_paths
def sound_path(): @merge_paths
return app_path(u"sounds") def sound_path():
return app_path(u"sounds")
@merge_paths
def com_path(): @merge_paths
global mode, directory def com_path():
if mode == "portable": global mode, directory
if directory != None: path = os.path.join(directory, "com_cache") if mode == "portable":
elif directory == None: path = app_path(u"com_cache") if directory != None: path = os.path.join(directory, "com_cache")
elif mode == "installed": elif directory == None: path = app_path(u"com_cache")
path = data_path(u"com_cache") elif mode == "installed":
if not os.path.exists(path): path = data_path(u"com_cache")
log.debug("%s path does not exist, creating..." % (path,)) if not os.path.exists(path):
os.mkdir(path) log.debug("%s path does not exist, creating..." % (path,))
return path os.mkdir(path)
return path

View File

@ -1,20 +1,21 @@
from __future__ import print_function from __future__ import print_function
import _winreg from builtins import str
import winreg
import os import os
import sys import sys
from platform_utils import paths from platform_utils import paths
RUN_REGKEY = ur"SOFTWARE\Microsoft\Windows\CurrentVersion\Run" RUN_REGKEY = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run"
def is_installed(app_subkey): def is_installed(app_subkey):
"""Checks if the currently running copy is installed or portable variant. Requires the name of the application subkey found under the uninstall section in Windows registry.""" """Checks if the currently running copy is installed or portable variant. Requires the name of the application subkey found under the uninstall section in Windows registry."""
try: try:
key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\%s" % app_subkey) key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\%s" % app_subkey)
inst_dir = _winreg.QueryValueEx(key,"InstallLocation")[0] inst_dir = winreg.QueryValueEx(key,"InstallLocation")[0]
except WindowsError: except WindowsError:
return False return False
_winreg.CloseKey(key) winreg.CloseKey(key)
try: try:
return os.stat(inst_dir) == os.stat(paths.app_path()) return os.stat(inst_dir) == os.stat(paths.app_path())
except WindowsError: except WindowsError:
@ -24,8 +25,8 @@ def getAutoStart(app_name):
"""Queries if the automatic startup should be set for the application or not, depending on it's current state.""" """Queries if the automatic startup should be set for the application or not, depending on it's current state."""
try: try:
key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, RUN_REGKEY) key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, RUN_REGKEY)
val = _winreg.QueryValueEx(key, unicode(app_name))[0] val = winreg.QueryValueEx(key, str(app_name))[0]
return os.stat(val) == os.stat(sys.argv[0]) return os.stat(val) == os.stat(sys.argv[0])
except (WindowsError, OSError): except (WindowsError, OSError):
return False return False
@ -35,8 +36,8 @@ def setAutoStart(app_name, enable=True):
print(paths.get_executable()) print(paths.get_executable())
if getAutoStart(app_name) == enable: if getAutoStart(app_name) == enable:
return return
key = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, RUN_REGKEY, 0, _winreg.KEY_WRITE) key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, RUN_REGKEY, 0, winreg.KEY_WRITE)
if enable: if enable:
_winreg.SetValueEx(key, unicode(app_name), None, _winreg.REG_SZ, paths.get_executable()) winreg.SetValueEx(key, str(app_name), None, winreg.REG_SZ, paths.get_executable())
else: else:
_winreg.DeleteValue(key, unicode(app_name)) winreg.DeleteValue(key, str(app_name))

View File

@ -1,16 +1,17 @@
# Replacement for py2exe distributed module # Replacement for py2exe distributed module
# Avoids the use of the standard py2exe console. # Avoids the use of the standard py2exe console.
# Just import this file and it should go away # Just import this file and it should go away
import sys from builtins import object
if hasattr(sys,"frozen"): # true only if we are running as a py2exe app import sys
class Blackhole(object): if hasattr(sys,"frozen"): # true only if we are running as a py2exe app
def write(self,text): class Blackhole(object):
pass def write(self,text):
def flush(self): pass
pass def flush(self):
sys.stdout = Blackhole() pass
sys.stderr = Blackhole() sys.stdout = Blackhole()
del Blackhole sys.stderr = Blackhole()
del sys del Blackhole
del sys

View File

@ -1,114 +1,115 @@
import inspect from builtins import str
import platform import inspect
import os import platform
import subprocess import os
import sys import subprocess
import string import sys
import unicodedata import string
import unicodedata
def app_data_path(app_name=None):
"""Cross-platform method for determining where to put application data.""" def app_data_path(app_name=None):
"""Requires the name of the application""" """Cross-platform method for determining where to put application data."""
plat = platform.system() """Requires the name of the application"""
if plat == 'Windows': plat = platform.system()
import winpaths if plat == 'Windows':
path = winpaths.get_appdata() import winpaths
elif plat == 'Darwin': path = winpaths.get_appdata()
path = os.path.join(os.path.expanduser('~'), 'Library', 'Application Support') elif plat == 'Darwin':
elif plat == 'Linux': path = os.path.join(os.path.expanduser('~'), 'Library', 'Application Support')
path = os.path.expanduser('~') elif plat == 'Linux':
app_name = '.%s' % app_name.replace(' ', '_') path = os.path.expanduser('~')
return os.path.join(path, app_name) app_name = '.%s' % app_name.replace(' ', '_')
return os.path.join(path, app_name)
def prepare_app_data_path(app_name):
"""Creates the application's data directory, given its name.""" def prepare_app_data_path(app_name):
dir = app_data_path(app_name) """Creates the application's data directory, given its name."""
return ensure_path(dir) dir = app_data_path(app_name)
return ensure_path(dir)
def embedded_data_path():
if platform.system() == 'Darwin' and is_frozen(): def embedded_data_path():
return os.path.abspath(os.path.join(executable_directory(), '..', 'Resources')) if platform.system() == 'Darwin' and is_frozen():
return app_path() return os.path.abspath(os.path.join(executable_directory(), '..', 'Resources'))
return app_path()
def is_frozen():
"""Return a bool indicating if application is compressed""" def is_frozen():
import imp """Return a bool indicating if application is compressed"""
return hasattr(sys, 'frozen') or imp.is_frozen("__main__") import imp
return hasattr(sys, 'frozen') or imp.is_frozen("__main__")
def get_executable():
"""Returns the full executable path/name if frozen, or the full path/name of the main module if not.""" def get_executable():
if is_frozen(): """Returns the full executable path/name if frozen, or the full path/name of the main module if not."""
if platform.system() != 'Darwin': if is_frozen():
return sys.executable if platform.system() != 'Darwin':
#On darwin, sys.executable points to python. We want the full path to the exe we ran. return sys.executable
exedir = os.path.abspath(os.path.dirname(sys.executable)) #On darwin, sys.executable points to python. We want the full path to the exe we ran.
items = os.listdir(exedir) exedir = os.path.abspath(os.path.dirname(sys.executable))
items.remove('python') items = os.listdir(exedir)
return os.path.join(exedir, items[0]) items.remove('python')
#Not frozen return os.path.join(exedir, items[0])
try: #Not frozen
import __main__ try:
return os.path.abspath(__main__.__file__) import __main__
except AttributeError: return os.path.abspath(__main__.__file__)
return sys.argv[0] except AttributeError:
return sys.argv[0]
def get_module(level=2):
"""Hacky method for deriving the caller of this function's module.""" def get_module(level=2):
return inspect.getmodule(inspect.stack()[level][0]).__file__ """Hacky method for deriving the caller of this function's module."""
return inspect.getmodule(inspect.stack()[level][0]).__file__
def executable_directory():
"""Always determine the directory of the executable, even when run with py2exe or otherwise frozen""" def executable_directory():
executable = get_executable() """Always determine the directory of the executable, even when run with py2exe or otherwise frozen"""
path = os.path.abspath(os.path.dirname(executable)) executable = get_executable()
return path path = os.path.abspath(os.path.dirname(executable))
return path
def app_path():
"""Return the root of the application's directory""" def app_path():
path = executable_directory() """Return the root of the application's directory"""
if is_frozen() and platform.system() == 'Darwin': path = executable_directory()
path = os.path.abspath(os.path.join(path, '..', '..')) if is_frozen() and platform.system() == 'Darwin':
return path path = os.path.abspath(os.path.join(path, '..', '..'))
return path
def module_path(level=2):
return os.path.abspath(os.path.dirname(get_module(level))) def module_path(level=2):
return os.path.abspath(os.path.dirname(get_module(level)))
def documents_path():
"""On windows, returns the path to My Documents. On OSX, returns the user's Documents folder. For anything else, returns the user's home directory.""" def documents_path():
plat = platform.system() """On windows, returns the path to My Documents. On OSX, returns the user's Documents folder. For anything else, returns the user's home directory."""
if plat == 'Windows': plat = platform.system()
import winpaths if plat == 'Windows':
path = winpaths.get_my_documents() import winpaths
elif plat == 'Darwin': path = winpaths.get_my_documents()
path = os.path.join(os.path.expanduser('~'), 'Documents') elif plat == 'Darwin':
else: path = os.path.join(os.path.expanduser('~'), 'Documents')
path = os.path.expanduser('~') else:
return path path = os.path.expanduser('~')
return path
def safe_filename(filename):
"""Given a filename, returns a safe version with no characters that would not work on different platforms.""" def safe_filename(filename):
SAFE_FILE_CHARS = "'-_.()[]{}!@#$%^&+=`~ " """Given a filename, returns a safe version with no characters that would not work on different platforms."""
filename = unicode(filename) SAFE_FILE_CHARS = "'-_.()[]{}!@#$%^&+=`~ "
new_filename = ''.join(c for c in filename if c in SAFE_FILE_CHARS or c.isalnum()) filename = str(filename)
#Windows doesn't like directory names ending in space, macs consider filenames beginning with a dot as hidden, and windows removes dots at the ends of filenames. new_filename = ''.join(c for c in filename if c in SAFE_FILE_CHARS or c.isalnum())
return new_filename.strip(' .') #Windows doesn't like directory names ending in space, macs consider filenames beginning with a dot as hidden, and windows removes dots at the ends of filenames.
return new_filename.strip(' .')
def ensure_path(path):
if not os.path.exists(path): def ensure_path(path):
os.makedirs(path) if not os.path.exists(path):
return path os.makedirs(path)
return path
def start_file(path):
if platform.system() == 'Windows': def start_file(path):
os.startfile(path) if platform.system() == 'Windows':
else: os.startfile(path)
subprocess.Popen(['open', path]) else:
subprocess.Popen(['open', path])
def get_applications_path():
"""Return the directory where applications are commonly installed on the system.""" def get_applications_path():
plat = platform.system() """Return the directory where applications are commonly installed on the system."""
if plat == 'Windows': plat = platform.system()
import winpaths if plat == 'Windows':
return winpaths.get_program_files() import winpaths
elif plat == 'Darwin': return winpaths.get_program_files()
return '/Applications' elif plat == 'Darwin':
return '/Applications'

View File

@ -1,10 +1,12 @@
import _winreg from future import standard_library
standard_library.install_aliases()
SHELL_REGKEY = ur"Directory\shell" import winreg
def context_menu_integrate(item_key_name, item_display_text, item_command): SHELL_REGKEY = ur"Directory\shell"
app_menu_key = _winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT, SHELL_REGKEY, 0, _winreg.KEY_WRITE)
menu_item_key = _winreg.CreateKey(app_menu_key, item_key_name) def context_menu_integrate(item_key_name, item_display_text, item_command):
_winreg.SetValueEx(menu_item_key, None, None, _winreg.REG_SZ, item_display_text) app_menu_key = winreg.OpenKey(winreg.HKEY_CLASSES_ROOT, SHELL_REGKEY, 0, winreg.KEY_WRITE)
item_command_key = _winreg.CreateKey(menu_item_key, 'command') menu_item_key = winreg.CreateKey(app_menu_key, item_key_name)
_winreg.SetValueEx(item_command_key, None, None, _winreg.REG_SZ, item_command) winreg.SetValueEx(menu_item_key, None, None, winreg.REG_SZ, item_display_text)
item_command_key = winreg.CreateKey(menu_item_key, 'command')
winreg.SetValueEx(item_command_key, None, None, winreg.REG_SZ, item_command)

View File

@ -1,15 +1,17 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import BaseHTTPServer, application from future import standard_library
standard_library.install_aliases()
logged = False import http.server, application
class handler(BaseHTTPServer.BaseHTTPRequestHandler): logged = False
def do_GET(self): class handler(http.server.BaseHTTPRequestHandler):
global logged
self.send_response(200) def do_GET(self):
self.send_header("Content-type", "text/html") global logged
self.end_headers() self.send_response(200)
logged = True self.send_header("Content-type", "text/html")
self.wfile.write("You have successfully logged into Pocket with" + application.name + ". " self.end_headers()
logged = True
self.wfile.write("You have successfully logged into Pocket with" + application.name + ". "
"You can close this window now.") "You can close this window now.")

View File

@ -1,6 +1,7 @@
# -*- coding: cp1252 -*- # -*- coding: cp1252 -*-
#from config_utils import Configuration, ConfigurationResetException #from config_utils import Configuration, ConfigurationResetException
from __future__ import absolute_import from __future__ import absolute_import
from builtins import object
import config import config
import paths import paths
import os import os

View File

@ -499,7 +499,12 @@ class Session(object):
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
""" The main session object. Here are the twitter functions to interact with the "model" of TWBlue.""" """ The main session object. Here are the twitter functions to interact with the "model" of TWBlue."""
from __future__ import absolute_import from __future__ import absolute_import
import urllib2 from future import standard_library
standard_library.install_aliases()
from builtins import str
from builtins import range
from builtins import object
import urllib.request, urllib.error, urllib.parse
import config import config
import twitter import twitter
from keys import keyring from keys import keyring
@ -906,8 +911,8 @@ class Session(object):
if not os.path.exists(shelfname): if not os.path.exists(shelfname):
output.speak("Generating database, this might take a while.",True) output.speak("Generating database, this might take a while.",True)
shelf=shelve.open(paths.config_path(shelfname),'c') shelf=shelve.open(paths.config_path(shelfname),'c')
for key,value in self.db.items(): for key,value in list(self.db.items()):
if type(key) != str and type(key) != unicode: if type(key) != str and type(key) != str:
output.speak("Uh oh, while shelving the database, a key of type " + str(type(key)) + " has been found. It will be converted to type str, but this will cause all sorts of problems on deshelve. Please bring this to the attention of the " + application.name + " developers immediately. More information about the error will be written to the error log.",True) output.speak("Uh oh, while shelving the database, a key of type " + str(type(key)) + " has been found. It will be converted to type str, but this will cause all sorts of problems on deshelve. Please bring this to the attention of the " + application.name + " developers immediately. More information about the error will be written to the error log.",True)
log.error("Uh oh, " + str(key) + " is of type " + str(type(key)) + "!") log.error("Uh oh, " + str(key) + " is of type " + str(type(key)) + "!")
# Convert unicode objects to UTF-8 strings before shelve these objects. # Convert unicode objects to UTF-8 strings before shelve these objects.
@ -930,7 +935,7 @@ class Session(object):
return return
try: try:
shelf=shelve.open(paths.config_path(shelfname),'c') shelf=shelve.open(paths.config_path(shelfname),'c')
for key,value in shelf.items(): for key,value in list(shelf.items()):
self.db[key]=value self.db[key]=value
shelf.close() shelf.close()
except: except:
@ -969,8 +974,8 @@ class Session(object):
def check_long_tweet(self, tweet): def check_long_tweet(self, tweet):
long = twishort.is_long(tweet) long = twishort.is_long(tweet)
if long != False and config.app["app-settings"]["handle_longtweets"]: if int != False and config.app["app-settings"]["handle_longtweets"]:
tweet["message"] = twishort.get_full_text(long) tweet["message"] = twishort.get_full_text(int)
if tweet["message"] == False: return False if tweet["message"] == False: return False
tweet["twishort"] = True tweet["twishort"] = True
for i in tweet["entities"]["user_mentions"]: for i in tweet["entities"]["user_mentions"]:

View File

@ -1,5 +1,7 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import absolute_import from __future__ import absolute_import
from builtins import str
from builtins import object
import shutil import shutil
import widgetUtils import widgetUtils
import platform import platform

View File

@ -1,9 +1,8 @@
# -*- coding: cp1252 -*- # -*- coding: cp1252 -*-
import exceptions
class InvalidSessionError(exceptions.Exception): pass class InvalidSessionError(Exception): pass
class NonExistentSessionError(exceptions.Exception): pass class NonExistentSessionError(Exception): pass
class NotLoggedSessionError(exceptions.BaseException): pass class NotLoggedSessionError(BaseException): pass
class NotConfiguredSessionError(exceptions.BaseException): pass class NotConfiguredSessionError(BaseException): pass
class RequireCredentialsSessionError(exceptions.BaseException): pass class RequireCredentialsSessionError(BaseException): pass
class AlreadyAuthorisedError(exceptions.BaseException): pass class AlreadyAuthorisedError(BaseException): pass

View File

@ -1,180 +1,180 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import sys import sys
import url_shortener import url_shortener
import audio_services import audio_services
import os import os
import logging as original_logger import logging as original_logger
log = original_logger.getLogger("sound") log = original_logger.getLogger("sound")
import paths import paths
from sound_lib.output import Output from sound_lib.output import Output
from sound_lib.input import Input from sound_lib.input import Input
from sound_lib.recording import WaveRecording from sound_lib.recording import WaveRecording
from sound_lib.stream import FileStream from sound_lib.stream import FileStream
from sound_lib.stream import URLStream as SoundlibURLStream from sound_lib.stream import URLStream as SoundlibURLStream
import subprocess import subprocess
import platform import platform
import output import output
system = platform.system() system = platform.system()
from mysc.repeating_timer import RepeatingTimer from mysc.repeating_timer import RepeatingTimer
from mysc.thread_utils import call_threaded from mysc.thread_utils import call_threaded
import application import application
import tempfile import tempfile
import glob import glob
URLPlayer = None URLPlayer = None
is_created = False is_created = False
def setup(): def setup():
global URLPlayer global URLPlayer
if not URLPlayer: if not URLPlayer:
log.debug("creating stream URL player...") log.debug("creating stream URL player...")
URLPlayer = URLStream() URLPlayer = URLStream()
def recode_audio(filename, quality=4.5): def recode_audio(filename, quality=4.5):
global system global system
if system == "Windows": subprocess.call(r'"%s" -q %r "%s"' % (paths.app_path('oggenc2.exe'), quality, filename)) if system == "Windows": subprocess.call(r'"%s" -q %r "%s"' % (paths.app_path('oggenc2.exe'), quality, filename))
def recording(filename): def recording(filename):
# try: # try:
val = WaveRecording(filename=filename) val = WaveRecording(filename=filename)
# except sound_lib.main.BassError: # except sound_lib.main.BassError:
# sound_lib.input.Input() # sound_lib.input.Input()
# val = sound_lib.recording.WaveRecording(filename=filename) # val = sound_lib.recording.WaveRecording(filename=filename)
return val return val
class soundSystem(object): class soundSystem(object):
def check_soundpack(self): def check_soundpack(self):
""" Checks if the folder where live the current soundpack exists.""" """ Checks if the folder where live the current soundpack exists."""
self.soundpack_OK = False self.soundpack_OK = False
if os.path.exists(paths.sound_path(self.config["current_soundpack"])): if os.path.exists(paths.sound_path(self.config["current_soundpack"])):
self.path = paths.sound_path(self.config["current_soundpack"]) self.path = paths.sound_path(self.config["current_soundpack"])
self.soundpack_OK = True self.soundpack_OK = True
elif os.path.exists(paths.sound_path("default")): elif os.path.exists(paths.sound_path("default")):
log.error("The soundpack does not exist, using default...") log.error("The soundpack does not exist, using default...")
self.path = paths.sound_path("default") self.path = paths.sound_path("default")
self.soundpack_OK = True self.soundpack_OK = True
else: else:
log.error("The current soundpack could not be found and the default soundpack has been deleted, " + application.name + " will not play sounds.") log.error("The current soundpack could not be found and the default soundpack has been deleted, " + application.name + " will not play sounds.")
self.soundpack_OK = False self.soundpack_OK = False
def __init__(self, soundConfig): def __init__(self, soundConfig):
""" Sound Player.""" """ Sound Player."""
global is_created global is_created
self.config = soundConfig self.config = soundConfig
# Set the output and input default devices. # Set the output and input default devices.
if is_created == False: if is_created == False:
try: try:
self.output = Output() self.output = Output()
self.input = Input() self.input = Input()
except IOError: except IOError:
pass pass
# Try to use the selected device from the configuration. It can fail if the machine does not has a mic. # Try to use the selected device from the configuration. It can fail if the machine does not has a mic.
if is_created == False: if is_created == False:
try: try:
log.debug("Setting input and output devices...") log.debug("Setting input and output devices...")
self.output.set_device(self.output.find_device_by_name(self.config["output_device"])) self.output.set_device(self.output.find_device_by_name(self.config["output_device"]))
self.input.set_device(self.input.find_device_by_name(self.config["input_device"])) self.input.set_device(self.input.find_device_by_name(self.config["input_device"]))
except: except:
log.exception("Error in input or output devices, using defaults...") log.exception("Error in input or output devices, using defaults...")
self.config["output_device"] = "Default" self.config["output_device"] = "Default"
self.config["input_device"] = "Default" self.config["input_device"] = "Default"
is_created = True is_created = True
self.files = [] self.files = []
self.cleaner = RepeatingTimer(60, self.clear_list) self.cleaner = RepeatingTimer(60, self.clear_list)
self.cleaner.start() self.cleaner.start()
self.check_soundpack() self.check_soundpack()
def clear_list(self): def clear_list(self):
if len(self.files) == 0: return if len(self.files) == 0: return
try: try:
for i in range(0, len(self.files)): for i in range(0, len(self.files)):
if self.files[i].is_playing == False: if self.files[i].is_playing == False:
self.files[i].free() self.files[i].free()
self.files.pop(i) self.files.pop(i)
except IndexError: except IndexError:
pass pass
def play(self, sound, argument=False): def play(self, sound, argument=False):
if self.soundpack_OK == False: return if self.soundpack_OK == False: return
if self.config["session_mute"] == True: return if self.config["session_mute"] == True: return
sound_object = FileStream(file="%s/%s" % (self.path, sound)) sound_object = FileStream(file="%s/%s" % (self.path, sound))
sound_object.volume = float(self.config["volume"]) sound_object.volume = float(self.config["volume"])
self.files.append(sound_object) self.files.append(sound_object)
sound_object.play() sound_object.play()
class URLStream(object): class URLStream(object):
def __init__(self, url=None): def __init__(self, url=None):
self.url = url self.url = url
self.prepared = False self.prepared = False
log.debug("URL Player initialized") log.debug("URL Player initialized")
def prepare(self, url): def prepare(self, url):
log.debug("Preparing URL: %s" % (url,)) log.debug("Preparing URL: %s" % (url,))
self.prepared = False self.prepared = False
self.url = url_shortener.unshorten(url) self.url = url_shortener.unshorten(url)
log.debug("Expanded URL: %s" % (self.url,)) log.debug("Expanded URL: %s" % (self.url,))
if self.url != None: if self.url != None:
transformer = audio_services.find_url_transformer(self.url) transformer = audio_services.find_url_transformer(self.url)
self.url = transformer(self.url) self.url = transformer(self.url)
log.debug("Transformed URL: %s. Prepared" % (self.url,)) log.debug("Transformed URL: %s. Prepared" % (self.url,))
else: else:
self.url = url self.url = url
log.debug("Transformed URL: %s. Prepared" % (self.url,)) log.debug("Transformed URL: %s. Prepared" % (self.url,))
self.prepared = True self.prepared = True
def seek(self,step): def seek(self,step):
pos=self.stream.get_position() pos=self.stream.get_position()
pos=self.stream.bytes_to_seconds(pos) pos=self.stream.bytes_to_seconds(pos)
pos+=step pos+=step
pos=self.stream.seconds_to_bytes(pos) pos=self.stream.seconds_to_bytes(pos)
if pos<0: if pos<0:
pos=0 pos=0
self.stream.set_position(pos) self.stream.set_position(pos)
def playpause(self): def playpause(self):
if self.stream.is_playing==True: if self.stream.is_playing==True:
self.stream.pause() self.stream.pause()
else: else:
self.stream.play() self.stream.play()
def play(self, url=None, volume=1.0, stream=None,announce=True): def play(self, url=None, volume=1.0, stream=None,announce=True):
if announce: if announce:
output.speak(_(u"Playing...")) output.speak(_("Playing..."))
log.debug("Attempting to play an URL...") log.debug("Attempting to play an URL...")
if url != None: if url != None:
self.prepare(url) self.prepare(url)
elif stream != None: elif stream != None:
self.stream=stream self.stream=stream
if self.prepared == True: if self.prepared == True:
self.stream = SoundlibURLStream(url=self.url) self.stream = SoundlibURLStream(url=self.url)
if hasattr(self,'stream'): if hasattr(self,'stream'):
self.stream.volume = float(volume) self.stream.volume = float(volume)
self.stream.play() self.stream.play()
log.debug("played") log.debug("played")
self.prepared=False self.prepared=False
def stop_audio(self,delete=False): def stop_audio(self,delete=False):
if hasattr(self, "stream"): if hasattr(self, "stream"):
output.speak(_(u"Stopped."), True) output.speak(_("Stopped."), True)
try: try:
self.stream.stop() self.stream.stop()
log.debug("Stopped audio stream.") log.debug("Stopped audio stream.")
except: except:
log.exception("Exception while stopping stream.") log.exception("Exception while stopping stream.")
if delete: if delete:
del self.stream del self.stream
log.debug("Deleted audio stream.") log.debug("Deleted audio stream.")
self.prepared=False self.prepared=False
return True return True
else: else:
return False return False
@staticmethod @staticmethod
def delete_old_tempfiles(): def delete_old_tempfiles():
for f in glob(os.path.join(tempfile.gettempdir(), 'tmp*.wav')): for f in glob(os.path.join(tempfile.gettempdir(), 'tmp*.wav')):
try: try:
os.remove(f) os.remove(f)
except: except:
pass pass

View File

@ -1,32 +1,23 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import BaseHTTPServer from future import standard_library
import application standard_library.install_aliases()
from urlparse import urlparse, parse_qs import http.server
from pubsub import pub import application
from urllib.parse import urlparse, parse_qs
logged = False
verifier = None logged = False
verifier = None
class handler(BaseHTTPServer.BaseHTTPRequestHandler, object):
class handler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
global logged def do_GET(self):
self.send_response(200) global logged
self.send_header("Content-type", "text/html") self.send_response(200)
self.end_headers() self.send_header("Content-type", "text/html")
logged = True self.end_headers()
params = parse_qs(urlparse(self.path).query) logged = True
global verifier params = parse_qs(urlparse(self.path).query)
verifier = params.get('oauth_verifier', [None])[0] global verifier
self.wfile.write(u"You have successfully logged into Twitter with {0}. You can close this window now.".format(application.name)) verifier = params.get('oauth_verifier', [None])[0]
pub.sendMessage("authorisation-accepted") self.wfile.write("You have successfully logged into Twitter with {0}. You can close this window now.".format(application.name))
pub.unsubscribe(self.cancelled, "authorisation-cancelled") self.finish()
self.finish()
def __init__(self, *args, **kwargs):
pub.subscribe(self.cancelled, "authorisation-cancelled")
super(handler, self).__init__(*args, **kwargs)
def cancelled(self):
pub.unsubscribe(self.cancelled, "authorisation-cancelled")
self.finish()

View File

@ -1,4 +1,5 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from builtins import str
import config import config
from requests.auth import HTTPProxyAuth from requests.auth import HTTPProxyAuth
from twitter import utils from twitter import utils

View File

@ -1,8 +1,11 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import absolute_import from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from builtins import object
import config import config
import random import random
import BaseHTTPServer import http.server
import webbrowser import webbrowser
from twython import Twython, TwythonError from twython import Twython, TwythonError
from keys import keyring from keys import keyring
@ -21,7 +24,7 @@ class twitter(object):
def authorise(self, settings): def authorise(self, settings):
authorisationHandler.logged = False authorisationHandler.logged = False
port = random.randint(30000, 65535) port = random.randint(30000, 65535)
httpd = BaseHTTPServer.HTTPServer(('127.0.0.1', port), authorisationHandler.handler) httpd = http.server.HTTPServer(('127.0.0.1', port), authorisationHandler.handler)
twitter = Twython(keyring.get("api_key"), keyring.get("api_secret"), auth_endpoint='authorize') twitter = Twython(keyring.get("api_key"), keyring.get("api_secret"), auth_endpoint='authorize')
auth = twitter.get_authentication_tokens("http://127.0.0.1:{0}".format(port,)) auth = twitter.get_authentication_tokens("http://127.0.0.1:{0}".format(port,))
webbrowser.open_new_tab(auth['auth_url']) webbrowser.open_new_tab(auth['auth_url'])

View File

@ -64,7 +64,7 @@ def is_audio(tweet):
if i["text"] == "audio": if i["text"] == "audio":
return True return True
except: except:
print(tweet["entities"]["hashtags"]) print((tweet["entities"]["hashtags"]))
log.exception("Exception while executing is_audio hashtag algorithm") log.exception("Exception while executing is_audio hashtag algorithm")
def is_geocoded(tweet): def is_geocoded(tweet):

View File

@ -1,42 +1,45 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
def convert_bytes(n): from __future__ import division
K, M, G, T, P = 1 << 10, 1 << 20, 1 << 30, 1 << 40, 1 << 50 from builtins import str
if n >= P: from past.utils import old_div
return '%.2fPb' % (float(n) / T) def convert_bytes(n):
elif n >= T: K, M, G, T, P = 1 << 10, 1 << 20, 1 << 30, 1 << 40, 1 << 50
return '%.2fTb' % (float(n) / T) if n >= P:
elif n >= G: return '%.2fPb' % (old_div(float(n), T))
return '%.2fGb' % (float(n) / G) elif n >= T:
elif n >= M: return '%.2fTb' % (old_div(float(n), T))
return '%.2fMb' % (float(n) / M) elif n >= G:
elif n >= K: return '%.2fGb' % (old_div(float(n), G))
return '%.2fKb' % (float(n) / K) elif n >= M:
else: return '%.2fMb' % (old_div(float(n), M))
return '%d' % n elif n >= K:
return '%.2fKb' % (old_div(float(n), K))
def seconds_to_string(seconds, precision=0): else:
day = seconds // 86400 return '%d' % n
hour = seconds // 3600
min = (seconds // 60) % 60 def seconds_to_string(seconds, precision=0):
sec = seconds - (hour * 3600) - (min * 60) day = seconds // 86400
sec_spec = "." + str(precision) + "f" hour = seconds // 3600
sec_string = sec.__format__(sec_spec) min = (seconds // 60) % 60
string = "" sec = seconds - (hour * 3600) - (min * 60)
if day == 1: sec_spec = "." + str(precision) + "f"
string += _(u"%d day, ") % day sec_string = sec.__format__(sec_spec)
elif day >= 2: string = ""
string += _(u"%d days, ") % day if day == 1:
if (hour == 1): string += _(u"%d day, ") % day
string += _(u"%d hour, ") % hour elif day >= 2:
elif (hour >= 2): string += _(u"%d days, ") % day
string += _("%d hours, ") % hour if (hour == 1):
if (min == 1): string += _(u"%d hour, ") % hour
string += _(u"%d minute, ") % min elif (hour >= 2):
elif (min >= 2): string += _("%d hours, ") % hour
string += _(u"%d minutes, ") % min if (min == 1):
if sec >= 0 and sec <= 2: string += _(u"%d minute, ") % min
string += _(u"%s second") % sec_string elif (min >= 2):
else: string += _(u"%d minutes, ") % min
string += _(u"%s seconds") % sec_string if sec >= 0 and sec <= 2:
string += _(u"%s second") % sec_string
else:
string += _(u"%s seconds") % sec_string
return string return string

View File

@ -1,5 +1,8 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import absolute_import from __future__ import absolute_import
from __future__ import division
from builtins import str
from past.utils import old_div
import wx import wx
import application import application
from . import utils from . import utils
@ -25,7 +28,7 @@ def progress_callback(total_downloaded, total_size):
if total_downloaded == total_size: if total_downloaded == total_size:
progress_dialog.Destroy() progress_dialog.Destroy()
else: else:
progress_dialog.Update((total_downloaded*100)/total_size, _(u"Updating... %s of %s") % (str(utils.convert_bytes(total_downloaded)), str(utils.convert_bytes(total_size)))) progress_dialog.Update(old_div((total_downloaded*100),total_size), _(u"Updating... %s of %s") % (str(utils.convert_bytes(total_downloaded)), str(utils.convert_bytes(total_size))))
def update_finished(): def update_finished():
ms = wx.MessageDialog(None, _(u"The update has been downloaded and installed successfully. Press OK to continue."), _(u"Done!")).ShowModal() ms = wx.MessageDialog(None, _(u"The update has been downloaded and installed successfully. Press OK to continue."), _(u"Done!")).ShowModal()

View File

@ -1,143 +1,145 @@
from gi.repository import Gtk, Gdk from builtins import range
from gi.repository import GObject from builtins import object
from gi.repository import Gtk, Gdk
toolkit = "gtk" from gi.repository import GObject
# Code responses for GTK +3 dialogs.
# this is when an user presses OK on a dialogue. toolkit = "gtk"
OK = Gtk.ResponseType.OK # Code responses for GTK +3 dialogs.
# This is when an user presses cancel on a dialogue. # this is when an user presses OK on a dialogue.
CANCEL = Gtk.ResponseType.CANCEL OK = Gtk.ResponseType.OK
# This is when an user closes the dialogue or an id to create the close button. # This is when an user presses cancel on a dialogue.
CLOSE = Gtk.ResponseType.CLOSE CANCEL = Gtk.ResponseType.CANCEL
# The response for a "yes" Button pressed on a dialogue. # This is when an user closes the dialogue or an id to create the close button.
YES = Gtk.ResponseType.YES CLOSE = Gtk.ResponseType.CLOSE
# This is when the user presses No on a default dialogue. # The response for a "yes" Button pressed on a dialogue.
NO = Gtk.ResponseType.NO YES = Gtk.ResponseType.YES
# This is when the user presses No on a default dialogue.
#events NO = Gtk.ResponseType.NO
# This is raised when the application must be closed.
CLOSE_EVENT = "delete-event" #events
# This is activated when a button is pressed. # This is raised when the application must be closed.
BUTTON_PRESSED = "clicked" CLOSE_EVENT = "delete-event"
# This is activated when an user enter text on an edit box. # This is activated when a button is pressed.
ENTERED_TEXT = "changed" BUTTON_PRESSED = "clicked"
MENU = "activate" # This is activated when an user enter text on an edit box.
ENTERED_TEXT = "changed"
#KEYPRESS = wx.EVT_CHAR_HOOK MENU = "activate"
#NOTEBOOK_PAGE_CHANGED = wx.EVT_NOTEBOOK_PAGE_CHANGED
CHECKBOX = "toggled" #KEYPRESS = wx.EVT_CHAR_HOOK
#NOTEBOOK_PAGE_CHANGED = wx.EVT_NOTEBOOK_PAGE_CHANGED
def exit_application(): CHECKBOX = "toggled"
""" Closes the current window cleanly. """
Gtk.main_quit() def exit_application():
""" Closes the current window cleanly. """
def connect_event(parent, event, func, menuitem=None, *args, **kwargs): Gtk.main_quit()
""" Connects an event to a function.
parent Gtk.widget: The widget that will listen for the event. def connect_event(parent, event, func, menuitem=None, *args, **kwargs):
event widgetUtils.event: The event that will be listened for the parent. The event should be one of the widgetUtils events. """ Connects an event to a function.
function func: The function that will be connected to the event.""" parent Gtk.widget: The widget that will listen for the event.
if menuitem == None: event widgetUtils.event: The event that will be listened for the parent. The event should be one of the widgetUtils events.
return getattr(parent, "connect")(event, func, *args, **kwargs) function func: The function that will be connected to the event."""
else: if menuitem == None:
return getattr(menuitem, "connect")(event, func, *args, **kwargs) return getattr(parent, "connect")(event, func, *args, **kwargs)
else:
class list(object): return getattr(menuitem, "connect")(event, func, *args, **kwargs)
def __init__(self, *columns, **listArguments):
self.columns = columns class list(object):
self.list_arguments = listArguments def __init__(self, *columns, **listArguments):
self.create_list() self.columns = columns
self.list_arguments = listArguments
def create_list(self): self.create_list()
columns = []
[columns.append(str) for i in self.columns] def create_list(self):
self.store = Gtk.ListStore(*columns) columns = []
self.list = Gtk.TreeView(model=self.store) [columns.append(str) for i in self.columns]
renderer = Gtk.CellRendererText() self.store = Gtk.ListStore(*columns)
for i in range(0, len(self.columns)): self.list = Gtk.TreeView(model=self.store)
column = Gtk.TreeViewColumn(self.columns[i], renderer, text=i) renderer = Gtk.CellRendererText()
# column.set_sort_column_id(i) for i in range(0, len(self.columns)):
self.list.append_column(column) column = Gtk.TreeViewColumn(self.columns[i], renderer, text=i)
# column.set_sort_column_id(i)
def insert_item(self, reversed=False, *item): self.list.append_column(column)
if reversed == False:
self.store.append(row=item) def insert_item(self, reversed=False, *item):
else: if reversed == False:
self.store.insert(position=0, row=item) self.store.append(row=item)
else:
def get_selected(self): self.store.insert(position=0, row=item)
tree_selection = self.list.get_selection()
(model, pathlist) = tree_selection.get_selected_rows() def get_selected(self):
return int(pathlist[0].to_string() ) tree_selection = self.list.get_selection()
(model, pathlist) = tree_selection.get_selected_rows()
def select_item(self, item): return int(pathlist[0].to_string() )
tree_selection = self.list.get_selection()
tree_selection.select_path(item) def select_item(self, item):
tree_selection = self.list.get_selection()
def remove_item(self, item): tree_selection.select_path(item)
self.store.remove(self.store.get_iter(item))
def remove_item(self, item):
def get_count(self): self.store.remove(self.store.get_iter(item))
return len(self.store)
def get_count(self):
class baseDialog(Gtk.Dialog): return len(self.store)
def __init__(self, *args, **kwargs):
super(baseDialog, self).__init__(*args, **kwargs) class baseDialog(Gtk.Dialog):
self.box = self.get_content_area() def __init__(self, *args, **kwargs):
super(baseDialog, self).__init__(*args, **kwargs)
def get_response(self): self.box = self.get_content_area()
answer = self.run()
return answer def get_response(self):
answer = self.run()
class buffer(GObject.GObject): return answer
name = GObject.property(type=str)
class buffer(GObject.GObject):
def __init__(self, obj): name = GObject.property(type=str)
super(buffer, self).__init__()
self.buffer = obj def __init__(self, obj):
super(buffer, self).__init__()
class notebook(object): self.buffer = obj
def __init__(self): class notebook(object):
self.store = Gtk.TreeStore(buffer.__gtype__)
self.view = Gtk.TreeView() def __init__(self):
self.view.set_model(self.store) self.store = Gtk.TreeStore(buffer.__gtype__)
self.view = Gtk.TreeView()
column = Gtk.TreeViewColumn("Buffer") self.view.set_model(self.store)
cell = Gtk.CellRendererText()
column.pack_start(cell, True) column = Gtk.TreeViewColumn("Buffer")
column.set_cell_data_func(cell, self.get_buffer) cell = Gtk.CellRendererText()
self.view.append_column(column) column.pack_start(cell, True)
column.set_cell_data_func(cell, self.get_buffer)
def get_current_page(self): self.view.append_column(column)
tree_selection = self.view.get_selection()
(model, pathlist) = tree_selection.get_selected_rows() def get_current_page(self):
iter = pathlist[0] tree_selection = self.view.get_selection()
return self.store[iter][0].buffer (model, pathlist) = tree_selection.get_selected_rows()
iter = pathlist[0]
def get_buffer(self, column, cell, model, iter, data): return self.store[iter][0].buffer
cell.set_property('text', self.store.get_value(iter, 0).name)
def get_buffer(self, column, cell, model, iter, data):
def match_func(self, row, name_, account): cell.set_property('text', self.store.get_value(iter, 0).name)
name = name_
account = account def match_func(self, row, name_, account):
iter = self.store.get_iter(row.path) name = name_
if self.store[iter][0].buffer.name == name and self.store[iter][0].buffer.account == account: account = account
return (row.path, iter) iter = self.store.get_iter(row.path)
else: if self.store[iter][0].buffer.name == name and self.store[iter][0].buffer.account == account:
return (None, None) return (row.path, iter)
else:
def search(self, rows, name_, account): return (None, None)
if not rows: return None
for row in rows: def search(self, rows, name_, account):
(path, iter) = self.match_func(row, name_, account) if not rows: return None
if iter != None: for row in rows:
return (path, iter) (path, iter) = self.match_func(row, name_, account)
(result_path, result_iter) = self.search(row.iterchildren(), name_, account) if iter != None:
if result_path: return (result_path, result_iter) return (path, iter)
return (None, None) (result_path, result_iter) = self.search(row.iterchildren(), name_, account)
if result_path: return (result_path, result_iter)
class mainLoopObject(object): return (None, None)
def run(self): class mainLoopObject(object):
GObject.type_register(buffer)
Gtk.main() def run(self):
GObject.type_register(buffer)
Gtk.main()

View File

@ -1,6 +1,7 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import absolute_import from __future__ import absolute_import
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from builtins import range
from . import baseDialog from . import baseDialog
import wx import wx
import logging as original_logger import logging as original_logger
@ -214,7 +215,7 @@ class other_buffers(wx.Panel):
output.speak(self.buffers.get_text_column(current, 2),True) output.speak(self.buffers.get_text_column(current, 2),True)
def get_list(self): def get_list(self):
buffers_list = [] buffers_list = []
for i in xrange(0, self.buffers.get_count()): for i in range(0, self.buffers.get_count()):
if self.buffers.get_text_column(i, 2) == _(u"Show"): if self.buffers.get_text_column(i, 2) == _(u"Show"):
buffers_list.append(self.buffers.get_text_column(i, 0)) buffers_list.append(self.buffers.get_text_column(i, 0))
return buffers_list return buffers_list

View File

@ -1,198 +1,199 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import wx from builtins import range
import application import wx
import application
class mainFrame(wx.Frame):
""" Main class of the Frame. This is the Main Window.""" class mainFrame(wx.Frame):
""" Main class of the Frame. This is the Main Window."""
### MENU
def makeMenus(self): ### MENU
""" Creates, bind and returns the menu bar for the application. Also in this function, the accel table is created.""" def makeMenus(self):
menuBar = wx.MenuBar() """ Creates, bind and returns the menu bar for the application. Also in this function, the accel table is created."""
menuBar = wx.MenuBar()
# Application menu
app = wx.Menu() # Application menu
self.manage_accounts = app.Append(wx.NewId(), _(u"&Manage accounts")) app = wx.Menu()
self.updateProfile = app.Append(wx.NewId(), _(u"&Update profile")) self.manage_accounts = app.Append(wx.NewId(), _(u"&Manage accounts"))
self.show_hide = app.Append(wx.NewId(), _(u"&Hide window")) self.updateProfile = app.Append(wx.NewId(), _(u"&Update profile"))
self.menuitem_search = app.Append(wx.NewId(), _(u"&Search")) self.show_hide = app.Append(wx.NewId(), _(u"&Hide window"))
self.lists = app.Append(wx.NewId(), _(u"&Lists manager")) self.menuitem_search = app.Append(wx.NewId(), _(u"&Search"))
self.keystroke_editor = app.Append(wx.NewId(), _(u"&Edit keystrokes")) self.lists = app.Append(wx.NewId(), _(u"&Lists manager"))
self.account_settings = app.Append(wx.NewId(), _(u"Account se&ttings")) self.keystroke_editor = app.Append(wx.NewId(), _(u"&Edit keystrokes"))
self.prefs = app.Append(wx.ID_PREFERENCES, _(u"&Global settings")) self.account_settings = app.Append(wx.NewId(), _(u"Account se&ttings"))
self.close = app.Append(wx.ID_EXIT, _(u"E&xit")) self.prefs = app.Append(wx.ID_PREFERENCES, _(u"&Global settings"))
self.close = app.Append(wx.ID_EXIT, _(u"E&xit"))
# Tweet menu
tweet = wx.Menu() # Tweet menu
self.compose = tweet.Append(wx.NewId(), _(u"&Tweet")) tweet = wx.Menu()
self.reply = tweet.Append(wx.NewId(), _(u"Re&ply")) self.compose = tweet.Append(wx.NewId(), _(u"&Tweet"))
self.retweet = tweet.Append(wx.NewId(), _(u"&Retweet")) self.reply = tweet.Append(wx.NewId(), _(u"Re&ply"))
self.fav = tweet.Append(wx.NewId(), _(u"&Like")) self.retweet = tweet.Append(wx.NewId(), _(u"&Retweet"))
self.unfav = tweet.Append(wx.NewId(), _(u"&Unlike")) self.fav = tweet.Append(wx.NewId(), _(u"&Like"))
self.view = tweet.Append(wx.NewId(), _(u"&Show tweet")) self.unfav = tweet.Append(wx.NewId(), _(u"&Unlike"))
self.view_coordinates = tweet.Append(wx.NewId(), _(u"View &address")) self.view = tweet.Append(wx.NewId(), _(u"&Show tweet"))
self.view_conversation = tweet.Append(wx.NewId(), _(u"View conversa&tion")) self.view_coordinates = tweet.Append(wx.NewId(), _(u"View &address"))
self.ocr = tweet.Append(wx.NewId(), _(u"Read text in picture")) self.view_conversation = tweet.Append(wx.NewId(), _(u"View conversa&tion"))
self.delete = tweet.Append(wx.NewId(), _(u"&Delete")) self.ocr = tweet.Append(wx.NewId(), _(u"Read text in picture"))
self.delete = tweet.Append(wx.NewId(), _(u"&Delete"))
# User menu
user = wx.Menu() # User menu
self.follow = user.Append(wx.NewId(), _(u"&Actions...")) user = wx.Menu()
self.timeline = user.Append(wx.NewId(), _(u"&View timeline...")) self.follow = user.Append(wx.NewId(), _(u"&Actions..."))
self.dm = user.Append(wx.NewId(), _(u"Direct me&ssage")) self.timeline = user.Append(wx.NewId(), _(u"&View timeline..."))
self.addToList = user.Append(wx.NewId(), _(u"&Add to list")) self.dm = user.Append(wx.NewId(), _(u"Direct me&ssage"))
self.removeFromList = user.Append(wx.NewId(), _(u"R&emove from list")) self.addToList = user.Append(wx.NewId(), _(u"&Add to list"))
self.viewLists = user.Append(wx.NewId(), _(u"&View lists")) self.removeFromList = user.Append(wx.NewId(), _(u"R&emove from list"))
self.details = user.Append(wx.NewId(), _(u"Show user &profile")) self.viewLists = user.Append(wx.NewId(), _(u"&View lists"))
self.favs = user.Append(wx.NewId(), _(u"V&iew likes")) self.details = user.Append(wx.NewId(), _(u"Show user &profile"))
self.favs = user.Append(wx.NewId(), _(u"V&iew likes"))
# buffer menu
buffer = wx.Menu() # buffer menu
self.update_buffer = buffer.Append(wx.NewId(), _(u"&Update buffer")) buffer = wx.Menu()
self.trends = buffer.Append(wx.NewId(), _(u"New &trending topics buffer...")) self.update_buffer = buffer.Append(wx.NewId(), _(u"&Update buffer"))
self.find = buffer.Append(wx.NewId(), _(u"Find a string in the currently focused buffer...")) self.trends = buffer.Append(wx.NewId(), _(u"New &trending topics buffer..."))
self.load_previous_items = buffer.Append(wx.NewId(), _(u"&Load previous items")) self.find = buffer.Append(wx.NewId(), _(u"Find a string in the currently focused buffer..."))
buffer.AppendSeparator() self.load_previous_items = buffer.Append(wx.NewId(), _(u"&Load previous items"))
self.mute_buffer = buffer.AppendCheckItem(wx.NewId(), _(u"&Mute")) buffer.AppendSeparator()
self.autoread = buffer.AppendCheckItem(wx.NewId(), _(u"&Autoread")) self.mute_buffer = buffer.AppendCheckItem(wx.NewId(), _(u"&Mute"))
self.clear = buffer.Append(wx.NewId(), _(u"&Clear buffer")) self.autoread = buffer.AppendCheckItem(wx.NewId(), _(u"&Autoread"))
self.deleteTl = buffer.Append(wx.NewId(), _(u"&Destroy")) self.clear = buffer.Append(wx.NewId(), _(u"&Clear buffer"))
self.deleteTl = buffer.Append(wx.NewId(), _(u"&Destroy"))
# audio menu
audio = wx.Menu() # audio menu
self.seekLeft = audio.Append(wx.NewId(), _(u"&Seek back 5 seconds")) audio = wx.Menu()
self.seekRight = audio.Append(wx.NewId(), _(u"&Seek forward 5 seconds")) self.seekLeft = audio.Append(wx.NewId(), _(u"&Seek back 5 seconds"))
self.seekRight = audio.Append(wx.NewId(), _(u"&Seek forward 5 seconds"))
# Help Menu
help = wx.Menu() # Help Menu
self.doc = help.Append(-1, _(u"&Documentation")) help = wx.Menu()
self.sounds_tutorial = help.Append(wx.NewId(), _(u"Sounds &tutorial")) self.doc = help.Append(-1, _(u"&Documentation"))
self.changelog = help.Append(wx.NewId(), _(u"&What's new in this version?")) self.sounds_tutorial = help.Append(wx.NewId(), _(u"Sounds &tutorial"))
self.check_for_updates = help.Append(wx.NewId(), _(u"&Check for updates")) self.changelog = help.Append(wx.NewId(), _(u"&What's new in this version?"))
self.reportError = help.Append(wx.NewId(), _(u"&Report an error")) self.check_for_updates = help.Append(wx.NewId(), _(u"&Check for updates"))
self.visit_website = help.Append(-1, _(u"{0}'s &website").format(application.name,)) self.reportError = help.Append(wx.NewId(), _(u"&Report an error"))
self.about = help.Append(-1, _(u"About &{0}").format(application.name,)) self.visit_website = help.Append(-1, _(u"{0}'s &website").format(application.name,))
self.about = help.Append(-1, _(u"About &{0}").format(application.name,))
# Add all to the menu Bar
menuBar.Append(app, _(u"&Application")) # Add all to the menu Bar
menuBar.Append(tweet, _(u"&Tweet")) menuBar.Append(app, _(u"&Application"))
menuBar.Append(user, _(u"&User")) menuBar.Append(tweet, _(u"&Tweet"))
menuBar.Append(buffer, _(u"&Buffer")) menuBar.Append(user, _(u"&User"))
menuBar.Append(audio, _(u"&Audio")) menuBar.Append(buffer, _(u"&Buffer"))
menuBar.Append(help, _(u"&Help")) menuBar.Append(audio, _(u"&Audio"))
menuBar.Append(help, _(u"&Help"))
self.accel_tbl = wx.AcceleratorTable([
(wx.ACCEL_CTRL, ord('N'), self.compose.GetId()), self.accel_tbl = wx.AcceleratorTable([
(wx.ACCEL_CTRL, ord('R'), self.reply.GetId()), (wx.ACCEL_CTRL, ord('N'), self.compose.GetId()),
(wx.ACCEL_CTRL|wx.ACCEL_SHIFT, ord('R'), self.retweet.GetId()), (wx.ACCEL_CTRL, ord('R'), self.reply.GetId()),
(wx.ACCEL_CTRL, ord('F'), self.fav.GetId()), (wx.ACCEL_CTRL|wx.ACCEL_SHIFT, ord('R'), self.retweet.GetId()),
(wx.ACCEL_CTRL|wx.ACCEL_SHIFT, ord('F'), self.unfav.GetId()), (wx.ACCEL_CTRL, ord('F'), self.fav.GetId()),
(wx.ACCEL_CTRL|wx.ACCEL_SHIFT, ord('V'), self.view.GetId()), (wx.ACCEL_CTRL|wx.ACCEL_SHIFT, ord('F'), self.unfav.GetId()),
(wx.ACCEL_CTRL, ord('D'), self.dm.GetId()), (wx.ACCEL_CTRL|wx.ACCEL_SHIFT, ord('V'), self.view.GetId()),
(wx.ACCEL_CTRL, ord('D'), self.dm.GetId()),
(wx.ACCEL_CTRL, ord('Q'), self.close.GetId()),
(wx.ACCEL_CTRL, ord('S'), self.follow.GetId()), (wx.ACCEL_CTRL, ord('Q'), self.close.GetId()),
(wx.ACCEL_CTRL, ord('I'), self.timeline.GetId()), (wx.ACCEL_CTRL, ord('S'), self.follow.GetId()),
(wx.ACCEL_CTRL|wx.ACCEL_SHIFT, ord('I'), self.deleteTl.GetId()), (wx.ACCEL_CTRL, ord('I'), self.timeline.GetId()),
(wx.ACCEL_CTRL, ord('M'), self.show_hide.GetId()), (wx.ACCEL_CTRL|wx.ACCEL_SHIFT, ord('I'), self.deleteTl.GetId()),
(wx.ACCEL_CTRL, wx.WXK_LEFT, self.seekLeft.GetId()), (wx.ACCEL_CTRL, ord('M'), self.show_hide.GetId()),
(wx.ACCEL_CTRL, ord('P'), self.updateProfile.GetId()), (wx.ACCEL_CTRL, wx.WXK_LEFT, self.seekLeft.GetId()),
(wx.ACCEL_CTRL, wx.WXK_RIGHT, self.seekRight.GetId()), (wx.ACCEL_CTRL, ord('P'), self.updateProfile.GetId()),
(wx.ACCEL_CTRL, ord(' '), self.seekLeft.GetId()), (wx.ACCEL_CTRL, wx.WXK_RIGHT, self.seekRight.GetId()),
]) (wx.ACCEL_CTRL, ord(' '), self.seekLeft.GetId()),
])
self.SetAcceleratorTable(self.accel_tbl)
return menuBar self.SetAcceleratorTable(self.accel_tbl)
return menuBar
### MAIN
def __init__(self): ### MAIN
""" Main function of this class.""" def __init__(self):
super(mainFrame, self).__init__(None, -1, application.name, size=(1600, 1600)) """ Main function of this class."""
self.panel = wx.Panel(self) super(mainFrame, self).__init__(None, -1, application.name, size=(1600, 1600))
self.sizer = wx.BoxSizer(wx.VERTICAL) self.panel = wx.Panel(self)
self.SetTitle(application.name) self.sizer = wx.BoxSizer(wx.VERTICAL)
self.SetMenuBar(self.makeMenus()) self.SetTitle(application.name)
self.nb = wx.Treebook(self.panel, wx.NewId()) self.SetMenuBar(self.makeMenus())
self.buffers = {} self.nb = wx.Treebook(self.panel, wx.NewId())
self.buffers = {}
def get_buffer_count(self):
return self.nb.GetPageCount() def get_buffer_count(self):
return self.nb.GetPageCount()
def add_buffer(self, buffer, name):
self.nb.AddPage(buffer, name) def add_buffer(self, buffer, name):
self.buffers[name] = buffer.GetId() self.nb.AddPage(buffer, name)
self.buffers[name] = buffer.GetId()
def insert_buffer(self, buffer, name, pos):
self.nb.InsertSubPage(pos, buffer, name) def insert_buffer(self, buffer, name, pos):
self.buffers[name] = buffer.GetId() self.nb.InsertSubPage(pos, buffer, name)
self.buffers[name] = buffer.GetId()
def prepare(self):
self.sizer.Add(self.nb, 0, wx.ALL, 5) def prepare(self):
self.panel.SetSizer(self.sizer) self.sizer.Add(self.nb, 0, wx.ALL, 5)
# self.Maximize() self.panel.SetSizer(self.sizer)
self.sizer.Layout() # self.Maximize()
self.SetClientSize(self.sizer.CalcMin()) self.sizer.Layout()
# print self.GetSize() self.SetClientSize(self.sizer.CalcMin())
# print self.GetSize()
def get_buffers(self):
return [self.nb.GetPage(i) for i in range(0, self.nb.GetPageCount())] def get_buffers(self):
return [self.nb.GetPage(i) for i in range(0, self.nb.GetPageCount())]
def search(self, name_, account):
for i in range(0, self.nb.GetPageCount()): def search(self, name_, account):
if self.nb.GetPage(i).name == name_ and self.nb.GetPage(i).account == account: return i for i in range(0, self.nb.GetPageCount()):
if self.nb.GetPage(i).name == name_ and self.nb.GetPage(i).account == account: return i
def get_current_buffer(self):
return self.nb.GetCurrentPage() def get_current_buffer(self):
return self.nb.GetCurrentPage()
def get_current_buffer_pos(self):
return self.nb.GetSelection() def get_current_buffer_pos(self):
return self.nb.GetSelection()
def get_buffer(self, pos):
return self.GetPage(pos) def get_buffer(self, pos):
return self.GetPage(pos)
def change_buffer(self, position):
self.nb.ChangeSelection(position) def change_buffer(self, position):
self.nb.ChangeSelection(position)
def get_buffer_text(self):
return self.nb.GetPageText(self.nb.GetSelection()) def get_buffer_text(self):
return self.nb.GetPageText(self.nb.GetSelection())
def get_buffer_by_id(self, id):
return self.nb.FindWindowById(id) def get_buffer_by_id(self, id):
def advance_selection(self, forward): return self.nb.FindWindowById(id)
self.nb.AdvanceSelection(forward) def advance_selection(self, forward):
self.nb.AdvanceSelection(forward)
def show(self):
self.Show() def show(self):
self.Show()
def show_address(self, address):
wx.MessageDialog(self, address, _(u"Address"), wx.OK).ShowModal() def show_address(self, address):
wx.MessageDialog(self, address, _(u"Address"), wx.OK).ShowModal()
def delete_buffer(self, pos):
self.nb.DeletePage(pos) def delete_buffer(self, pos):
self.nb.DeletePage(pos)
def about_dialog(self):
info = wx.AboutDialogInfo() def about_dialog(self):
info.SetName(application.name) info = wx.AboutDialogInfo()
info.SetVersion(application.version) info.SetName(application.name)
info.SetDescription(application.description) info.SetVersion(application.version)
info.SetCopyright(application.copyright) info.SetDescription(application.description)
info.SetTranslators(application.translators) info.SetCopyright(application.copyright)
# info.SetLicence(application.licence) info.SetTranslators(application.translators)
for i in application.authors: # info.SetLicence(application.licence)
info.AddDeveloper(i) for i in application.authors:
wx.AboutBox(info) info.AddDeveloper(i)
def set_focus(self): wx.AboutBox(info)
self.SetFocus() def set_focus(self):
self.SetFocus()
def check_menuitem(self, menuitem, check=True):
if hasattr(self, menuitem): def check_menuitem(self, menuitem, check=True):
getattr(self, menuitem).Check(check) if hasattr(self, menuitem):
getattr(self, menuitem).Check(check)
def set_page_title(self, page, title):
return self.nb.SetPageText(page, title) def set_page_title(self, page, title):
return self.nb.SetPageText(page, title)
def get_page_title(self, page):
return self.nb.GetPageText(page) def get_page_title(self, page):
return self.nb.GetPageText(page)
def no_update_available():
wx.MessageDialog(None, _(u"Your {0} version is up to date").format(application.name,), _(u"Update"), style=wx.OK).ShowModal() def no_update_available():
wx.MessageDialog(None, _(u"Your {0} version is up to date").format(application.name,), _(u"Update"), style=wx.OK).ShowModal()