Initial (automated) port to Python3.

This commit is contained in:
Bill Dengler 2017-06-16 21:25:01 +00:00
parent 4bdc2b2a6a
commit b9ce127bc1
71 changed files with 2958 additions and 2837 deletions

View File

@ -1,18 +1,19 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
name = 'TWBlue' from builtins import str
snapshot = False name = 'TWBlue'
if snapshot == False: snapshot = False
version = "0.90" if snapshot == False:
update_url = 'http://twblue.es/updates/twblue_ngen.json' version = "0.90"
mirror_update_url = 'https://raw.githubusercontent.com/manuelcortez/TWBlue/next-gen/updates/stable.json' update_url = 'http://twblue.es/updates/twblue_ngen.json'
else: mirror_update_url = 'https://raw.githubusercontent.com/manuelcortez/TWBlue/next-gen/updates/stable.json'
version = "10.99" else:
update_url = 'http://twblue.es/updates/snapshots_ngen.json' version = "10.99"
mirror_update_url = 'https://raw.githubusercontent.com/manuelcortez/TWBlue/next-gen/updates/snapshots.json' update_url = 'http://twblue.es/updates/snapshots_ngen.json'
authors = [u"Manuel Cortéz", u"José Manuel Delicado"] mirror_update_url = 'https://raw.githubusercontent.com/manuelcortez/TWBlue/next-gen/updates/snapshots.json'
authorEmail = "manuel@manuelcortez.net" authors = [u"Manuel Cortéz", u"José Manuel Delicado"]
copyright = u"Copyright (C) 2013-2017, Manuel cortéz." authorEmail = "manuel@manuelcortez.net"
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.") copyright = u"Copyright (C) 2013-2017, Manuel cortéz."
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)"] 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.")
url = u"http://twblue.es" 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)"]
url = u"http://twblue.es"
report_bugs_url = "http://twblue.es/bugs/api/soap/mantisconnect.php?wsdl" report_bugs_url = "http://twblue.es/bugs/api/soap/mantisconnect.php?wsdl"

View File

@ -1,48 +1,50 @@
from audio_services import matches_url from future import standard_library
import json standard_library.install_aliases()
import re from audio_services import matches_url
import urllib import json
import re
@matches_url('https://audioboom.com') import urllib.request, urllib.parse, urllib.error
def convert_audioboom(url):
if "audioboom.com" not in url.lower(): @matches_url('https://audioboom.com')
raise TypeError('%r is not a valid URL' % url) def convert_audioboom(url):
audio_id = url.split('.com/')[-1] if "audioboom.com" not in url.lower():
return 'https://audioboom.com/%s.mp3' % audio_id raise TypeError('%r is not a valid URL' % url)
audio_id = url.split('.com/')[-1]
@matches_url ('https://soundcloud.com/') return 'https://audioboom.com/%s.mp3' % audio_id
def convert_soundcloud (url):
client_id = "df8113ca95c157b6c9731f54b105b473" @matches_url ('https://soundcloud.com/')
permalink = urllib.urlopen ('http://api.soundcloud.com/resolve.json?client_id=%s&url=%s' %(client_id, url)) def convert_soundcloud (url):
if permalink.getcode () == 404: client_id = "df8113ca95c157b6c9731f54b105b473"
permalink.close () permalink = urllib.request.urlopen ('http://api.soundcloud.com/resolve.json?client_id=%s&url=%s' %(client_id, url))
raise TypeError('%r is not a valid URL' % url) if permalink.getcode () == 404:
else: permalink.close ()
resolved_url = permalink.geturl () raise TypeError('%r is not a valid URL' % url)
permalink.close () else:
track_url = urllib.urlopen (resolved_url) resolved_url = permalink.geturl ()
track_data = json.loads (track_url.read ()) permalink.close ()
track_url.close () track_url = urllib.request.urlopen (resolved_url)
if track_data ['streamable']: track_data = json.loads (track_url.read ())
return track_data ['stream_url'] + "?client_id=%s" %client_id track_url.close ()
else: if track_data ['streamable']:
raise TypeError('%r is not streamable' % url) return track_data ['stream_url'] + "?client_id=%s" %client_id
else:
@matches_url('http://twup.me') raise TypeError('%r is not streamable' % url)
def convert_twup(url):
result = re.match("^http://twup.me/(?P<audio_id>[A-Za-z0-9]+/?)$", url, re.I) @matches_url('http://twup.me')
if not result or result.group("audio_id") is None: def convert_twup(url):
raise TypeError('%r is not a valid URL' % url) result = re.match("^http://twup.me/(?P<audio_id>[A-Za-z0-9]+/?)$", url, re.I)
audio_id = result.group("audio_id") if not result or result.group("audio_id") is None:
return 'http://twup.me/%s' % audio_id raise TypeError('%r is not a valid URL' % url)
audio_id = result.group("audio_id")
#@matches_url('http://sndup.net') return 'http://twup.me/%s' % audio_id
#def convert_sndup(url):
# result = re.match("^http://sndup.net/(?P<audio_id>[a-z0-9]+/?)(|d|l|a)/?$", url, re.I) #@matches_url('http://sndup.net')
# if not result or result.group("audio_id") is None: #def convert_sndup(url):
# raise TypeError('%r is not a valid URL' % url) # result = re.match("^http://sndup.net/(?P<audio_id>[a-z0-9]+/?)(|d|l|a)/?$", url, re.I)
# audio_id = result.group("audio_id") # if not result or result.group("audio_id") is None:
# return 'http://sndup.net/%s/a' % audio_id # raise TypeError('%r is not a valid URL' % url)
# audio_id = result.group("audio_id")
def convert_generic_audio(url): # return 'http://sndup.net/%s/a' % audio_id
return url
def convert_generic_audio(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,5 +1,8 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import absolute_import from __future__ import absolute_import
from builtins import str
from builtins import range
from builtins import object
import time import time
import platform import platform
if platform.system() == "Windows": if platform.system() == "Windows":
@ -389,7 +392,7 @@ class baseBufferController(bufferController):
def remove_tweet(self, id): def remove_tweet(self, id):
if type(self.session.db[self.name]) == dict: return if type(self.session.db[self.name]) == dict: return
for i in xrange(0, len(self.session.db[self.name])): for i in range(0, len(self.session.db[self.name])):
if self.session.db[self.name][i]["id"] == id: if self.session.db[self.name][i]["id"] == id:
self.session.db[self.name].pop(i) self.session.db[self.name].pop(i)
self.remove_item(i) self.remove_item(i)
@ -606,7 +609,7 @@ class baseBufferController(bufferController):
# fix this: # fix this:
original_date = arrow.get(self.session.db[self.name][self.buffer.list.get_selected()]["created_at"], "ddd MMM D H:m:s Z YYYY", locale="en") original_date = arrow.get(self.session.db[self.name][self.buffer.list.get_selected()]["created_at"], "ddd MMM D H:m:s Z YYYY", locale="en")
ts = original_date.humanize(locale=languageHandler.getLanguage()) ts = original_date.humanize(locale=languageHandler.getLanguage())
self.buffer.list.list.SetItem(self.buffer.list.get_selected(), 2, unicode(ts)) self.buffer.list.list.SetItem(self.buffer.list.get_selected(), 2, str(ts))
if self.session.settings['sound']['indicate_audio'] and utils.is_audio(tweet): if self.session.settings['sound']['indicate_audio'] and utils.is_audio(tweet):
self.session.sound.play("audio.ogg") self.session.sound.play("audio.ogg")
if self.session.settings['sound']['indicate_geo'] and utils.is_geocoded(tweet): if self.session.settings['sound']['indicate_geo'] and utils.is_geocoded(tweet):

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,5 +1,8 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import absolute_import from __future__ import absolute_import
from builtins import str
from builtins import range
from builtins import object
import platform import platform
system = platform.system() system = platform.system()
import application import application
@ -264,7 +267,7 @@ class Controller(object):
self.start_buffers(session_.sessions[i]) self.start_buffers(session_.sessions[i])
self.set_buffer_positions(session_.sessions[i]) self.set_buffer_positions(session_.sessions[i])
if config.app["app-settings"]["play_ready_sound"] == True: if config.app["app-settings"]["play_ready_sound"] == True:
session_.sessions[session_.sessions.keys()[0]].sound.play("ready.ogg") session_.sessions[list(session_.sessions.keys())[0]].sound.play("ready.ogg")
if config.app["app-settings"]["speak_ready_msg"] == True: if config.app["app-settings"]["speak_ready_msg"] == True:
output.speak(_(u"Ready")) output.speak(_(u"Ready"))
self.started = True self.started = True
@ -478,7 +481,7 @@ class Controller(object):
output.speak(_(u"Empty buffer."), True) output.speak(_(u"Empty buffer."), True)
return return
start = page.buffer.list.get_selected() start = page.buffer.list.get_selected()
for i in xrange(start,count): for i in range(start,count):
page.buffer.list.select_item(i) page.buffer.list.select_item(i)
if string.lower() in page.get_message().lower(): if string.lower() in page.get_message().lower():
return output.speak(page.get_message(), True) return output.speak(page.get_message(), True)
@ -1595,7 +1598,7 @@ class Controller(object):
output.speak(_(u"This tweet doesn't contain images")) output.speak(_(u"This tweet doesn't contain images"))
return return
if len(tweet["entities"]["media"]) > 1: if len(tweet["entities"]["media"]) > 1:
image_list = [_(u"Picture {0}").format(i,) for i in xrange(0, len(tweet["entities"]["media"]))] image_list = [_(u"Picture {0}").format(i,) for i in range(0, len(tweet["entities"]["media"]))]
dialog = dialogs.urlList.urlList(title=_(u"Select the picture")) dialog = dialogs.urlList.urlList(title=_(u"Select the picture"))
if dialog.get_response() == widgetUtils.OK: if dialog.get_response() == widgetUtils.OK:
img = tweet["entities"]["media"][dialog.get_item()] img = tweet["entities"]["media"][dialog.get_item()]

View File

@ -1,5 +1,8 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import absolute_import from __future__ import absolute_import
from builtins import str
from builtins import range
from builtins import object
import re import re
import platform import platform
from . import attach from . import attach
@ -172,14 +175,14 @@ class reply(tweet):
def get_ids(self): def get_ids(self):
excluded_ids = "" excluded_ids = ""
for i in xrange(0, len(self.message.checkboxes)): for i in range(0, len(self.message.checkboxes)):
if self.message.checkboxes[i].GetValue() == False: if self.message.checkboxes[i].GetValue() == False:
excluded_ids = excluded_ids + "{0},".format(self.ids[i],) excluded_ids = excluded_ids + "{0},".format(self.ids[i],)
return excluded_ids return excluded_ids
def get_people(self): def get_people(self):
people = "" people = ""
for i in xrange(0, len(self.message.checkboxes)): for i in range(0, len(self.message.checkboxes)):
if self.message.checkboxes[i].GetValue() == True: if self.message.checkboxes[i].GetValue() == True:
people = people + "{0} ".format(self.message.checkboxes[i].GetLabel(),) people = people + "{0} ".format(self.message.checkboxes[i].GetLabel(),)
return people return people
@ -203,7 +206,7 @@ class viewTweet(basicTweet):
if is_tweet == True: if is_tweet == True:
image_description = [] image_description = []
text = "" text = ""
for i in xrange(0, len(tweetList)): for i in range(0, len(tweetList)):
# tweets with message keys are longer tweets, the message value is the full messaje taken from twishort. # tweets with message keys are longer tweets, the message value is the full messaje taken from twishort.
if "message" in tweetList[i] and tweetList[i]["is_quote_status"] == False: if "message" in tweetList[i] and tweetList[i]["is_quote_status"] == False:
value = "message" value = "message"

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,126 +1,127 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import wx from builtins import object
import webbrowser import wx
import widgetUtils import webbrowser
import output import widgetUtils
from wxUI.dialogs import update_profile, show_user import output
import logging from wxUI.dialogs import update_profile, show_user
log = logging.getLogger("controller.user") import logging
from twython import TwythonError log = logging.getLogger("controller.user")
from twython import TwythonError
class profileController(object):
def __init__(self, session, user=None): class profileController(object):
super(profileController, self).__init__() def __init__(self, session, user=None):
self.file = None super(profileController, self).__init__()
self.session = session self.file = None
self.user = user self.session = session
if user == None: self.user = user
self.get_data(screen_name=self.session.db["user_name"]) if user == None:
self.dialog = update_profile.updateProfileDialog() self.get_data(screen_name=self.session.db["user_name"])
self.fill_profile_fields() self.dialog = update_profile.updateProfileDialog()
self.uploaded = False self.fill_profile_fields()
widgetUtils.connect_event(self.dialog.upload_image, widgetUtils.BUTTON_PRESSED, self.upload_image) self.uploaded = False
else: widgetUtils.connect_event(self.dialog.upload_image, widgetUtils.BUTTON_PRESSED, self.upload_image)
try: else:
self.get_data(screen_name=self.user) try:
except TwythonError as err: self.get_data(screen_name=self.user)
if err.error_code == 404: except TwythonError as err:
wx.MessageDialog(None, _(u"That user does not exist"), _(u"Error"), wx.ICON_ERROR).ShowModal() if err.error_code == 404:
if err.error_code == 403: wx.MessageDialog(None, _(u"That user does not exist"), _(u"Error"), wx.ICON_ERROR).ShowModal()
wx.MessageDialog(None, _(u"User has been suspended"), _(u"Error"), wx.ICON_ERROR).ShowModal() if err.error_code == 403:
log.error("error %d: %s" % (err.error_code, err.msg)) wx.MessageDialog(None, _(u"User has been suspended"), _(u"Error"), wx.ICON_ERROR).ShowModal()
return log.error("error %d: %s" % (err.error_code, err.msg))
self.dialog = show_user.showUserProfile() return
string = self.get_user_info() self.dialog = show_user.showUserProfile()
self.dialog.set("text", string) string = self.get_user_info()
self.dialog.set_title(_(u"Information for %s") % (self.data["screen_name"])) self.dialog.set("text", string)
if self.data["url"] != None: self.dialog.set_title(_(u"Information for %s") % (self.data["screen_name"]))
self.dialog.enable_url() if self.data["url"] != None:
widgetUtils.connect_event(self.dialog.url, widgetUtils.BUTTON_PRESSED, self.visit_url) self.dialog.enable_url()
if self.dialog.get_response() == widgetUtils.OK and self.user == None: widgetUtils.connect_event(self.dialog.url, widgetUtils.BUTTON_PRESSED, self.visit_url)
self.do_update() if self.dialog.get_response() == widgetUtils.OK and self.user == None:
self.do_update()
def get_data(self, screen_name):
self.data = self.session.twitter.twitter.show_user(screen_name=screen_name) def get_data(self, screen_name):
if screen_name != self.session.db["user_name"]: self.data = self.session.twitter.twitter.show_user(screen_name=screen_name)
self.friendship_status = self.session.twitter.twitter.show_friendship(source_screen_name=self.session.db["user_name"], target_screen_name=screen_name) if screen_name != self.session.db["user_name"]:
self.friendship_status = self.session.twitter.twitter.show_friendship(source_screen_name=self.session.db["user_name"], target_screen_name=screen_name)
def fill_profile_fields(self):
self.dialog.set_name(self.data["name"]) def fill_profile_fields(self):
if self.data["url"] != None: self.dialog.set_name(self.data["name"])
self.dialog.set_url(self.data["url"]) if self.data["url"] != None:
if len(self.data["location"]) > 0: self.dialog.set_url(self.data["url"])
self.dialog.set_location(self.data["location"]) if len(self.data["location"]) > 0:
if len(self.data["description"]) > 0: self.dialog.set_location(self.data["location"])
self.dialog.set_description(self.data["description"]) if len(self.data["description"]) > 0:
self.dialog.set_description(self.data["description"])
def get_image(self):
file = self.dialog.upload_picture() def get_image(self):
if file != None: file = self.dialog.upload_picture()
self.file = open(file, "rb") if file != None:
self.uploaded = True self.file = open(file, "rb")
self.dialog.change_upload_button(self.uploaded) self.uploaded = True
self.dialog.change_upload_button(self.uploaded)
def discard_image(self):
self.file = None def discard_image(self):
output.speak(_(u"Discarded")) self.file = None
self.uploaded = False output.speak(_(u"Discarded"))
self.dialog.change_upload_button(self.uploaded) self.uploaded = False
self.dialog.change_upload_button(self.uploaded)
def upload_image(self, *args, **kwargs):
if self.uploaded == False: def upload_image(self, *args, **kwargs):
self.get_image() if self.uploaded == False:
elif self.uploaded == True: self.get_image()
self.discard_image() elif self.uploaded == True:
self.discard_image()
def do_update(self):
if self.user != None: return def do_update(self):
name = self.dialog.get("name") if self.user != None: return
description = self.dialog.get("description") name = self.dialog.get("name")
location = self.dialog.get("location") description = self.dialog.get("description")
url = self.dialog.get("url") location = self.dialog.get("location")
if self.file != None: url = self.dialog.get("url")
try: if self.file != None:
self.session.twitter.twitter.update_profile_image(image=self.file) try:
except TwythonError as e: self.session.twitter.twitter.update_profile_image(image=self.file)
output.speak(u"Error %s. %s" % (e.error_code, e.msg)) except TwythonError as e:
try: output.speak(u"Error %s. %s" % (e.error_code, e.msg))
self.session.twitter.twitter.update_profile(name=name, description=description, location=location, url=url) try:
except TwythonError as e: self.session.twitter.twitter.update_profile(name=name, description=description, location=location, url=url)
output.speak(u"Error %s. %s" % (e.error_code, e.msg)) except TwythonError as e:
output.speak(u"Error %s. %s" % (e.error_code, e.msg))
def get_user_info(self):
def get_user_info(self):
string = u""
string = string + _(u"Username: @%s\n") % (self.data["screen_name"]) string = u""
string = string + _(u"Name: %s\n") % (self.data["name"]) string = string + _(u"Username: @%s\n") % (self.data["screen_name"])
if self.data["location"] != "": string = string + _(u"Name: %s\n") % (self.data["name"])
string = string + _(u"Location: %s\n") % (self.data["location"]) if self.data["location"] != "":
if self.data["url"] != None: string = string + _(u"Location: %s\n") % (self.data["location"])
string = string+ _(u"URL: %s\n") % (self.data["url"]) if self.data["url"] != None:
if self.data["description"] != "": string = string+ _(u"URL: %s\n") % (self.data["url"])
string = string+ _(u"Bio: %s\n") % (self.data["description"]) if self.data["description"] != "":
if self.data["protected"] == True: protected = _(u"Yes") string = string+ _(u"Bio: %s\n") % (self.data["description"])
else: protected = _(u"No") if self.data["protected"] == True: protected = _(u"Yes")
string = string+ _(u"Protected: %s\n") % (protected) else: protected = _(u"No")
if hasattr(self, "friendship_status"): string = string+ _(u"Protected: %s\n") % (protected)
relation = False if hasattr(self, "friendship_status"):
friendship = "Relationship: " relation = False
if self.friendship_status["relationship"]["target"]["followed_by"]: friendship = "Relationship: "
friendship += _(u"You follow {0}. ").format(self.data["name"],) if self.friendship_status["relationship"]["target"]["followed_by"]:
relation = True friendship += _(u"You follow {0}. ").format(self.data["name"],)
if self.friendship_status["relationship"]["target"]["following"]: relation = True
friendship += _(u"{0} is following you.").format(self.data["name"],) if self.friendship_status["relationship"]["target"]["following"]:
relation = True friendship += _(u"{0} is following you.").format(self.data["name"],)
if relation == True: relation = True
string = string+friendship+"\n" if relation == True:
string = string+_(u"Followers: %s\n Friends: %s\n") % (self.data["followers_count"], self.data["friends_count"]) string = string+friendship+"\n"
if self.data["verified"] == True: verified = _(u"Yes") string = string+_(u"Followers: %s\n Friends: %s\n") % (self.data["followers_count"], self.data["friends_count"])
else: verified = _(u"No") if self.data["verified"] == True: verified = _(u"Yes")
string = string+ _(u"Verified: %s\n") % (verified) else: verified = _(u"No")
string = string+ _(u"Tweets: %s\n") % (self.data["statuses_count"]) string = string+ _(u"Verified: %s\n") % (verified)
string = string+ _(u"Likes: %s") % (self.data["favourites_count"]) string = string+ _(u"Tweets: %s\n") % (self.data["statuses_count"])
return string string = string+ _(u"Likes: %s") % (self.data["favourites_count"])
return string
def visit_url(self, *args, **kwargs):
def visit_url(self, *args, **kwargs):
webbrowser.open_new_tab(self.data["url"]) webbrowser.open_new_tab(self.data["url"])

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,108 +1,109 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from yandex_translate import YandexTranslate from builtins import zip
from yandex_translate import YandexTranslate
def translate(text="", source="auto", target="en"):
t = YandexTranslate("trnsl.1.1.20161012T134532Z.d01b9c75fc39aa74.7d1be75a5166a80583eeb020e10f584168da6bf7") def translate(text="", source="auto", target="en"):
return t.translate(text, target)["text"][0] t = YandexTranslate("trnsl.1.1.20161012T134532Z.d01b9c75fc39aa74.7d1be75a5166a80583eeb020e10f584168da6bf7")
return t.translate(text, target)["text"][0]
languages = {
"af": _(u"Afrikaans"), languages = {
"sq": _(u"Albanian"), "af": _(u"Afrikaans"),
"am": _(u"Amharic"), "sq": _(u"Albanian"),
"ar": _(u"Arabic"), "am": _(u"Amharic"),
"hy": _(u"Armenian"), "ar": _(u"Arabic"),
"az": _(u"Azerbaijani"), "hy": _(u"Armenian"),
"eu": _(u"Basque"), "az": _(u"Azerbaijani"),
"be": _(u"Belarusian"), "eu": _(u"Basque"),
"bn": _(u"Bengali"), "be": _(u"Belarusian"),
"bh": _(u"Bihari"), "bn": _(u"Bengali"),
"bg": _(u"Bulgarian"), "bh": _(u"Bihari"),
"my": _(u"Burmese"), "bg": _(u"Bulgarian"),
"ca": _(u"Catalan"), "my": _(u"Burmese"),
"chr": _(u"Cherokee"), "ca": _(u"Catalan"),
"zh": _(u"Chinese"), "chr": _(u"Cherokee"),
"zh-CN": _(u"Chinese_simplified"), "zh": _(u"Chinese"),
"zh-TW": _(u"Chinese_traditional"), "zh-CN": _(u"Chinese_simplified"),
"hr": _(u"Croatian"), "zh-TW": _(u"Chinese_traditional"),
"cs": _(u"Czech"), "hr": _(u"Croatian"),
"da": _(u"Danish"), "cs": _(u"Czech"),
"dv": _(u"Dhivehi"), "da": _(u"Danish"),
"nl": _(u"Dutch"), "dv": _(u"Dhivehi"),
"en": _(u"English"), "nl": _(u"Dutch"),
"eo": _(u"Esperanto"), "en": _(u"English"),
"et": _(u"Estonian"), "eo": _(u"Esperanto"),
"tl": _(u"Filipino"), "et": _(u"Estonian"),
"fi": _(u"Finnish"), "tl": _(u"Filipino"),
"fr": _(u"French"), "fi": _(u"Finnish"),
"gl": _(u"Galician"), "fr": _(u"French"),
"ka": _(u"Georgian"), "gl": _(u"Galician"),
"de": _(u"German"), "ka": _(u"Georgian"),
"el": _(u"Greek"), "de": _(u"German"),
"gn": _(u"Guarani"), "el": _(u"Greek"),
"gu": _(u"Gujarati"), "gn": _(u"Guarani"),
"iw": _(u"Hebrew"), "gu": _(u"Gujarati"),
"hi": _(u"Hindi"), "iw": _(u"Hebrew"),
"hu": _(u"Hungarian"), "hi": _(u"Hindi"),
"is": _(u"Icelandic"), "hu": _(u"Hungarian"),
"id": _(u"Indonesian"), "is": _(u"Icelandic"),
"iu": _(u"Inuktitut"), "id": _(u"Indonesian"),
"ga": _(u"Irish"), "iu": _(u"Inuktitut"),
"it": _(u"Italian"), "ga": _(u"Irish"),
"ja": _(u"Japanese"), "it": _(u"Italian"),
"kn": _(u"Kannada"), "ja": _(u"Japanese"),
"kk": _(u"Kazakh"), "kn": _(u"Kannada"),
"km": _(u"Khmer"), "kk": _(u"Kazakh"),
"ko": _(u"Korean"), "km": _(u"Khmer"),
"ku": _(u"Kurdish"), "ko": _(u"Korean"),
"ky": _(u"Kyrgyz"), "ku": _(u"Kurdish"),
"lo": _(u"Laothian"), "ky": _(u"Kyrgyz"),
"lv": _(u"Latvian"), "lo": _(u"Laothian"),
"lt": _(u"Lithuanian"), "lv": _(u"Latvian"),
"mk": _(u"Macedonian"), "lt": _(u"Lithuanian"),
"ms": _(u"Malay"), "mk": _(u"Macedonian"),
"ml": _(u"Malayalam"), "ms": _(u"Malay"),
"mt": _(u"Maltese"), "ml": _(u"Malayalam"),
"mr": _(u"Marathi"), "mt": _(u"Maltese"),
"mn": _(u"Mongolian"), "mr": _(u"Marathi"),
"ne": _(u"Nepali"), "mn": _(u"Mongolian"),
"no": _(u"Norwegian"), "ne": _(u"Nepali"),
"or": _(u"Oriya"), "no": _(u"Norwegian"),
"ps": _(u"Pashto"), "or": _(u"Oriya"),
"fa": _(u"Persian"), "ps": _(u"Pashto"),
"pl": _(u"Polish"), "fa": _(u"Persian"),
"pt-PT": _(u"Portuguese"), "pl": _(u"Polish"),
"pa": _(u"Punjabi"), "pt-PT": _(u"Portuguese"),
"ro": _(u"Romanian"), "pa": _(u"Punjabi"),
"ru": _(u"Russian"), "ro": _(u"Romanian"),
"sa": _(u"Sanskrit"), "ru": _(u"Russian"),
"sr": _(u"Serbian"), "sa": _(u"Sanskrit"),
"sd": _(u"Sindhi"), "sr": _(u"Serbian"),
"si": _(u"Sinhalese"), "sd": _(u"Sindhi"),
"sk": _(u"Slovak"), "si": _(u"Sinhalese"),
"sl": _(u"Slovenian"), "sk": _(u"Slovak"),
"es": _(u"Spanish"), "sl": _(u"Slovenian"),
"sw": _(u"Swahili"), "es": _(u"Spanish"),
"sv": _(u"Swedish"), "sw": _(u"Swahili"),
"tg": _(u"Tajik"), "sv": _(u"Swedish"),
"ta": _(u"Tamil"), "tg": _(u"Tajik"),
"tl": _(u"Tagalog"), "ta": _(u"Tamil"),
"te": _(u"Telugu"), "tl": _(u"Tagalog"),
"th": _(u"Thai"), "te": _(u"Telugu"),
"bo": _(u"Tibetan"), "th": _(u"Thai"),
"tr": _(u"Turkish"), "bo": _(u"Tibetan"),
"uk": _(u"Ukrainian"), "tr": _(u"Turkish"),
"ur": _(u"Urdu"), "uk": _(u"Ukrainian"),
"uz": _(u"Uzbek"), "ur": _(u"Urdu"),
"ug": _(u"Uighur"), "uz": _(u"Uzbek"),
"vi": _(u"Vietnamese"), "ug": _(u"Uighur"),
"cy": _(u"Welsh"), "vi": _(u"Vietnamese"),
"yi": _(u"Yiddish") "cy": _(u"Welsh"),
} "yi": _(u"Yiddish")
}
def available_languages():
l = languages.keys() def available_languages():
d = languages.values() l = list(languages.keys())
l.insert(0, '') d = list(languages.values())
d.insert(0, _(u"autodetect")) l.insert(0, '')
return sorted(zip(l, d)) d.insert(0, _(u"autodetect"))
return sorted(zip(l, 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,210 +1,214 @@
import __builtin__ from future import standard_library
import os standard_library.install_aliases()
import sys from builtins import zip
import ctypes from builtins import str
import locale import builtins
import gettext import os
import paths import sys
import platform import ctypes
import locale
# A fix for the mac locales import gettext
#if platform.system() == 'Darwin': import paths
import platform
#a few Windows locale constants
LOCALE_SLANGUAGE=0x2 # A fix for the mac locales
LOCALE_SLANGDISPLAYNAME=0x6f #if platform.system() == 'Darwin':
curLang="en" #a few Windows locale constants
LOCALE_SLANGUAGE=0x2
def localeNameToWindowsLCID(localeName): LOCALE_SLANGDISPLAYNAME=0x6f
"""Retreave the Windows locale identifier (LCID) for the given locale name
@param localeName: a string of 2letterLanguage_2letterCountry or or just 2letterLanguage curLang="en"
@type localeName: string
@returns: a Windows LCID def localeNameToWindowsLCID(localeName):
@rtype: integer """Retreave the Windows locale identifier (LCID) for the given locale name
""" @param localeName: a string of 2letterLanguage_2letterCountry or or just 2letterLanguage
#Windows Vista is able to convert locale names to LCIDs @type localeName: string
func_LocaleNameToLCID=getattr(ctypes.windll.kernel32,'LocaleNameToLCID',None) @returns: a Windows LCID
if func_LocaleNameToLCID is not None: @rtype: integer
localeName=localeName.replace('_','-') """
LCID=func_LocaleNameToLCID(unicode(localeName),0) #Windows Vista is able to convert locale names to LCIDs
else: #Windows doesn't have this functionality, manually search Python's windows_locale dictionary for the LCID func_LocaleNameToLCID=getattr(ctypes.windll.kernel32,'LocaleNameToLCID',None)
localeName=locale.normalize(localeName) if func_LocaleNameToLCID is not None:
if '.' in localeName: localeName=localeName.replace('_','-')
localeName=localeName.split('.')[0] LCID=func_LocaleNameToLCID(str(localeName),0)
LCList=[x[0] for x in locale.windows_locale.iteritems() if x[1]==localeName] else: #Windows doesn't have this functionality, manually search Python's windows_locale dictionary for the LCID
if len(LCList)>0: localeName=locale.normalize(localeName)
LCID=LCList[0] if '.' in localeName:
else: localeName=localeName.split('.')[0]
LCID=0 LCList=[x[0] for x in locale.windows_locale.items() if x[1]==localeName]
return LCID if len(LCList)>0:
LCID=LCList[0]
def getLanguageDescription(language): else:
"""Finds out the description (localized full name) of a given local name""" LCID=0
desc=None return LCID
if platform.system() == "Windows":
LCID=localeNameToWindowsLCID(language) def getLanguageDescription(language):
if LCID!=0: """Finds out the description (localized full name) of a given local name"""
buf=ctypes.create_unicode_buffer(1024) desc=None
if '_' not in language: if platform.system() == "Windows":
res=ctypes.windll.kernel32.GetLocaleInfoW(LCID,LOCALE_SLANGDISPLAYNAME,buf,1024) LCID=localeNameToWindowsLCID(language)
else: if LCID!=0:
res=0 buf=ctypes.create_unicode_buffer(1024)
if res==0: if '_' not in language:
res=ctypes.windll.kernel32.GetLocaleInfoW(LCID,LOCALE_SLANGUAGE,buf,1024) res=ctypes.windll.kernel32.GetLocaleInfoW(LCID,LOCALE_SLANGDISPLAYNAME,buf,1024)
desc=buf.value else:
elif platform.system() == "Linux" or not desc: res=0
desc={ if res==0:
"am":pgettext("languageName","Amharic"), res=ctypes.windll.kernel32.GetLocaleInfoW(LCID,LOCALE_SLANGUAGE,buf,1024)
"an":pgettext("languageName","Aragonese"), desc=buf.value
"es":pgettext("languageName","Spanish"), elif platform.system() == "Linux" or not desc:
"pt":pgettext("languageName","Portuguese"), desc={
"ru":pgettext("languageName","Russian"), "am":pgettext("languageName","Amharic"),
"it":pgettext("languageName","italian"), "an":pgettext("languageName","Aragonese"),
"tr":pgettext("languageName","Turkey"), "es":pgettext("languageName","Spanish"),
"gl":pgettext("languageName","Galician"), "pt":pgettext("languageName","Portuguese"),
"ca":pgettext("languageName","Catala"), "ru":pgettext("languageName","Russian"),
"eu":pgettext("languageName","Vasque"), "it":pgettext("languageName","italian"),
"pl":pgettext("languageName","polish"), "tr":pgettext("languageName","Turkey"),
"ar":pgettext("languageName","Arabic"), "gl":pgettext("languageName","Galician"),
"ne":pgettext("languageName","Nepali"), "ca":pgettext("languageName","Catala"),
"sr":pgettext("languageName","Serbian (Latin)"), "eu":pgettext("languageName","Vasque"),
"ja":pgettext("languageName","Japanese"), "pl":pgettext("languageName","polish"),
"ro":pgettext("languageName","Romanian"), "ar":pgettext("languageName","Arabic"),
}.get(language,None) "ne":pgettext("languageName","Nepali"),
return desc "sr":pgettext("languageName","Serbian (Latin)"),
"ja":pgettext("languageName","Japanese"),
def getAvailableLanguages(): "ro":pgettext("languageName","Romanian"),
"""generates a list of locale names, plus their full localized language and country names. }.get(language,None)
@rtype: list of tuples return desc
"""
#Make a list of all the locales found in NVDA's locale dir def getAvailableLanguages():
l=[x for x in os.listdir(paths.locale_path()) if not x.startswith('.')] """generates a list of locale names, plus their full localized language and country names.
l=[x for x in l if os.path.isfile(paths.locale_path('%s/LC_MESSAGES/twblue.mo' % x))] @rtype: list of tuples
#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: #Make a list of all the locales found in NVDA's locale dir
l.append('en') l=[x for x in os.listdir(paths.locale_path()) if not x.startswith('.')]
l.sort() l=[x for x in l if os.path.isfile(paths.locale_path('%s/LC_MESSAGES/twblue.mo' % x))]
#For each locale, ask Windows for its human readable display name #Make sure that en (english) is in the list as it may not have any locale files, but is default
d=[] if 'en' not in l:
for i in l: l.append('en')
desc=getLanguageDescription(i) l.sort()
label="%s, %s"%(desc,i) if desc else i #For each locale, ask Windows for its human readable display name
d.append(label) d=[]
#include a 'user default, windows' language, which just represents the default language for this user account for i in l:
l.append("system") desc=getLanguageDescription(i)
# Translators: the label for the Windows default NVDA interface language. label="%s, %s"%(desc,i) if desc else i
d.append(_("User default")) d.append(label)
#return a zipped up version of both the lists (a list with tuples of locale,label) #include a 'user default, windows' language, which just represents the default language for this user account
return zip(l,d) l.append("system")
# Translators: the label for the Windows default NVDA interface language.
def makePgettext(translations): d.append(_("User default"))
"""Obtaina pgettext function for use with a gettext translations instance. #return a zipped up version of both the lists (a list with tuples of locale,label)
pgettext is used to support message contexts, return list(zip(l,d))
but Python 2.7's gettext module doesn't support this,
so NVDA must provide its own implementation. def makePgettext(translations):
""" """Obtaina pgettext function for use with a gettext translations instance.
if isinstance(translations, gettext.GNUTranslations): pgettext is used to support message contexts,
def pgettext(context, message): but Python 2.7's gettext module doesn't support this,
message = unicode(message) so NVDA must provide its own implementation.
try: """
# Look up the message with its context. if isinstance(translations, gettext.GNUTranslations):
return translations._catalog[u"%s\x04%s" % (context, message)] def pgettext(context, message):
except KeyError: message = str(message)
return message try:
else: # Look up the message with its context.
def pgettext(context, message): return translations._catalog[u"%s\x04%s" % (context, message)]
return unicode(message) except KeyError:
return pgettext return message
else:
def setLanguage(lang): def pgettext(context, message):
system = platform.system() return str(message)
global curLang return pgettext
try:
if lang=="system": def setLanguage(lang):
if system == "Windows": system = platform.system()
windowsLCID=ctypes.windll.kernel32.GetUserDefaultUILanguage() global curLang
localeName=locale.windows_locale[windowsLCID] try:
elif system == "Darwin": if lang=="system":
import Foundation if system == "Windows":
localeName = Foundation.NSLocale.currentLocale().identifier() windowsLCID=ctypes.windll.kernel32.GetUserDefaultUILanguage()
elif system == "Linux": localeName=locale.windows_locale[windowsLCID]
localeName = locale.getdefaultlocale()[0] elif system == "Darwin":
trans=gettext.translation('twblue', localedir=paths.locale_path(), languages=[localeName]) import Foundation
curLang=localeName localeName = Foundation.NSLocale.currentLocale().identifier()
# else: 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]
trans=gettext.translation("twblue", localedir=paths.locale_path(), languages=[lang]) # trans=gettext.translation('twblue', localedir=paths.locale_path(), languages=[localeName])
curLang=lang # curLang=localeName
localeChanged=False
#Try setting Python's locale to lang else:
# try: trans=gettext.translation("twblue", localedir=paths.locale_path(), languages=[lang])
if system == "Windows": curLang=lang
locale.setlocale(locale.LC_ALL, langToWindowsLocale(lang)) localeChanged=False
localeChanged=True #Try setting Python's locale to lang
else: # try:
locale.setlocale(locale.LC_ALL, lang) if system == "Windows":
localeChanged=True locale.setlocale(locale.LC_ALL, langToWindowsLocale(lang))
# except: localeChanged=True
# pass else:
if not localeChanged and '_' in lang: locale.setlocale(locale.LC_ALL, lang)
#Python couldn'tsupport the language_country locale, just try language. localeChanged=True
try: # except:
locale.setlocale(locale.LC_ALL, lang.split('_')[0]) # pass
except: if not localeChanged and '_' in lang:
pass #Python couldn'tsupport the language_country locale, just try language.
#Set the windows locale for this thread (NVDA core) to this locale. try:
if system == "Windows": locale.setlocale(locale.LC_ALL, lang.split('_')[0])
LCID=localeNameToWindowsLCID(lang) except:
ctypes.windll.kernel32.SetThreadLocale(LCID) pass
except IOError: #Set the windows locale for this thread (NVDA core) to this locale.
trans=gettext.translation("twblue",fallback=True) if system == "Windows":
curLang="en" LCID=localeNameToWindowsLCID(lang)
trans.install(unicode=True) ctypes.windll.kernel32.SetThreadLocale(LCID)
# Install our pgettext function. except IOError:
# __builtin__.__dict__["pgettext"] = makePgettext(trans) trans=gettext.translation("twblue",fallback=True)
curLang="en"
def getLanguage(): trans.install()
return curLang # Install our pgettext function.
# __builtin__.__dict__["pgettext"] = makePgettext(trans)
def normalizeLanguage(lang):
""" def getLanguage():
Normalizes a language-dialect string in to a standard form we can deal with. return curLang
Converts any dash to underline, and makes sure that language is lowercase and dialect is upercase.
""" def normalizeLanguage(lang):
lang=lang.replace('-','_') """
ld=lang.split('_') Normalizes a language-dialect string in to a standard form we can deal with.
ld[0]=ld[0].lower() Converts any dash to underline, and makes sure that language is lowercase and dialect is upercase.
#Filter out meta languages such as x-western """
if ld[0]=='x': lang=lang.replace('-','_')
return None ld=lang.split('_')
if len(ld)>=2: ld[0]=ld[0].lower()
ld[1]=ld[1].upper() #Filter out meta languages such as x-western
return "_".join(ld) if ld[0]=='x':
return None
def langToWindowsLocale(lang): if len(ld)>=2:
languages = {"en": "eng", ld[1]=ld[1].upper()
"ar": "ara", return "_".join(ld)
"ca": "cat",
"de": "deu", def langToWindowsLocale(lang):
"es": "esp", languages = {"en": "eng",
"fi": "fin", "ar": "ara",
"fr": "fre_FRA", "ca": "cat",
"gl": "glc", "de": "deu",
"eu": "euq", "es": "esp",
"hu": "hun", "fi": "fin",
"hr": "hrv", "fr": "fre_FRA",
"it": "ita", "gl": "glc",
"ja": "jpn", "eu": "euq",
"pl": "plk", "hu": "hun",
"pt": "ptb", "hr": "hrv",
"ro": "rom", "it": "ita",
"ru": "rus", "ja": "jpn",
"tr": "trk", "pl": "plk",
"sr": "eng", "pt": "ptb",
} "ro": "rom",
return languages[lang] "ru": "rus",
"tr": "trk",
"sr": "eng",
}
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

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

View File

@ -1,21 +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
import application
logged = False from urllib.parse import urlparse, parse_qs
verifier = None
logged = False
class handler(BaseHTTPServer.BaseHTTPRequestHandler): verifier = None
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")
params = parse_qs(urlparse(self.path).query) self.end_headers()
global verifier logged = True
verifier = params.get('oauth_verifier', [None])[0] params = parse_qs(urlparse(self.path).query)
self.wfile.write(u"You have successfully logged into Twitter with {0}. You can close this window now.".format(application.name)) global verifier
self.finish() verifier = params.get('oauth_verifier', [None])[0]
self.wfile.write(u"You have successfully logged into Twitter with {0}. You can close this window now.".format(application.name))
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,10 +1,15 @@
# -*- 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 str
from builtins import chr
from builtins import range
import platform import platform
system = platform.system() system = platform.system()
from . import utils from . import utils
import re import re
import htmlentitydefs import html.entities
import time import time
import output import output
import languageHandler import languageHandler
@ -22,10 +27,10 @@ def StripChars(s):
If we match &blah; and it's not found, &blah; will be returned. If we match &blah; and it's not found, &blah; will be returned.
if we match #\d+, unichr(digits) will be returned. if we match #\d+, unichr(digits) will be returned.
Else, a unicode string will be returned.""" Else, a unicode string will be returned."""
if match.group(1).startswith('#'): return unichr(int(match.group(1)[1:])) if match.group(1).startswith('#'): return chr(int(match.group(1)[1:]))
replacement = htmlentitydefs.entitydefs.get(match.group(1), "&%s;" % match.group(1)) replacement = html.entities.entitydefs.get(match.group(1), "&%s;" % match.group(1))
return replacement.decode('iso-8859-1') return replacement.decode('iso-8859-1')
return unicode(entity_re.sub(matchFunc, s)) return str(entity_re.sub(matchFunc, s))
chars = "abcdefghijklmnopqrstuvwxyz" chars = "abcdefghijklmnopqrstuvwxyz"

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

@ -1,5 +1,7 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import print_function from __future__ import print_function
from builtins import str
from builtins import range
import url_shortener, re import url_shortener, re
import output import output
from twython import TwythonError from twython import TwythonError

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,5 +1,7 @@
from __future__ import absolute_import from __future__ import absolute_import
import urllib from future import standard_library
standard_library.install_aliases()
import urllib.request, urllib.parse, urllib.error
from .url_shortener import URLShortener from .url_shortener import URLShortener
@ -11,7 +13,7 @@ class ClckruShortener (URLShortener):
def _shorten (self, url): def _shorten (self, url):
answer = url answer = url
api = urllib.urlopen ("http://clck.ru/--?url=" + urllib.quote(url)) api = urllib.request.urlopen ("http://clck.ru/--?url=" + urllib.parse.quote(url))
if api.getcode() == 200: if api.getcode() == 200:
answer = api.read() answer = api.read()
api.close() api.close()

View File

@ -1,5 +1,7 @@
from __future__ import absolute_import from __future__ import absolute_import
import urllib from future import standard_library
standard_library.install_aliases()
import urllib.request, urllib.parse, urllib.error
from .url_shortener import URLShortener from .url_shortener import URLShortener
@ -10,7 +12,7 @@ class HKCShortener (URLShortener):
def _shorten (self, url): def _shorten (self, url):
answer = url answer = url
api = urllib.urlopen ("http://hkc.im/yourls-api.php?action=shorturl&format=simple&url=" + urllib.quote(url)) api = urllib.request.urlopen ("http://hkc.im/yourls-api.php?action=shorturl&format=simple&url=" + urllib.parse.quote(url))
if api.getcode() == 200: if api.getcode() == 200:
answer = api.read() answer = api.read()
api.close() api.close()

View File

@ -1,5 +1,7 @@
from __future__ import absolute_import from __future__ import absolute_import
import urllib from future import standard_library
standard_library.install_aliases()
import urllib.request, urllib.parse, urllib.error
from .url_shortener import URLShortener from .url_shortener import URLShortener
@ -11,7 +13,7 @@ class IsgdShortener (URLShortener):
def _shorten (self, url): def _shorten (self, url):
answer = url answer = url
api = urllib.urlopen ("http://is.gd/api.php?longurl=" + urllib.quote(url)) api = urllib.request.urlopen ("http://is.gd/api.php?longurl=" + urllib.parse.quote(url))
if api.getcode() == 200: if api.getcode() == 200:
answer = api.read() answer = api.read()
api.close() api.close()

View File

@ -1,5 +1,7 @@
from __future__ import absolute_import from __future__ import absolute_import
import urllib from future import standard_library
standard_library.install_aliases()
import urllib.request, urllib.parse, urllib.error
from .url_shortener import URLShortener from .url_shortener import URLShortener
@ -10,7 +12,7 @@ class OnjmeShortener (URLShortener):
def _shorten (self, url): def _shorten (self, url):
answer = url answer = url
api = urllib.urlopen ("http://onj.me/yourls-api.php?action=shorturl&format=simple&url=" + urllib.quote(url)) api = urllib.request.urlopen ("http://onj.me/yourls-api.php?action=shorturl&format=simple&url=" + urllib.parse.quote(url))
if api.getcode() == 200: if api.getcode() == 200:
answer = api.read() answer = api.read()
api.close() api.close()

View File

@ -1,5 +1,7 @@
from __future__ import absolute_import from __future__ import absolute_import
import urllib from future import standard_library
standard_library.install_aliases()
import urllib.request, urllib.parse, urllib.error
from .url_shortener import URLShortener from .url_shortener import URLShortener
@ -10,7 +12,7 @@ class TinyArrowsShortener (URLShortener):
def _shorten (self, url): def _shorten (self, url):
answer = url answer = url
answer = urllib.urlopen("http://tinyarro.ws/api-create.php?utfpure=1&url=%s" % urllib.quote(url)).read() answer = urllib.request.urlopen("http://tinyarro.ws/api-create.php?utfpure=1&url=%s" % urllib.parse.quote(url)).read()
return answer.decode('UTF-8') return answer.decode('UTF-8')
def created_url(self, url): def created_url(self, url):

View File

@ -1,6 +1,8 @@
from __future__ import absolute_import from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
from .url_shortener import URLShortener from .url_shortener import URLShortener
import urllib import urllib.request, urllib.parse, urllib.error
class TinyurlShortener (URLShortener): class TinyurlShortener (URLShortener):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
self.name = "TinyURL.com" self.name = "TinyURL.com"
@ -9,7 +11,7 @@ class TinyurlShortener (URLShortener):
def _shorten (self, url): def _shorten (self, url):
answer = url answer = url
api = urllib.urlopen ("http://tinyurl.com/api-create.php?url=" + urllib.quote(url)) api = urllib.request.urlopen ("http://tinyurl.com/api-create.php?url=" + urllib.parse.quote(url))
if api.getcode() == 200: if api.getcode() == 200:
answer = api.read() answer = api.read()
api.close() api.close()

View File

@ -1,5 +1,8 @@
from httplib import HTTPConnection from future import standard_library
from urlparse import urlparse standard_library.install_aliases()
from builtins import object
from http.client import HTTPConnection
from urllib.parse import urlparse
class URLShortener (object): class URLShortener (object):

View File

@ -1,5 +1,7 @@
from __future__ import absolute_import from __future__ import absolute_import
import urllib from future import standard_library
standard_library.install_aliases()
import urllib.request, urllib.parse, urllib.error
from .url_shortener import URLShortener from .url_shortener import URLShortener
@ -10,7 +12,7 @@ class XedccShortener (URLShortener):
def _shorten (self, url): def _shorten (self, url):
answer = url answer = url
api = urllib.urlopen ("http://xed.cc/yourls-api.php?action=shorturl&format=simple&url=" + urllib.quote(url)) api = urllib.request.urlopen ("http://xed.cc/yourls-api.php?action=shorturl&format=simple&url=" + urllib.parse.quote(url))
if api.getcode() == 200: if api.getcode() == 200:
answer = api.read() answer = api.read()
api.close() api.close()

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,446 +1,447 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
import wx from builtins import str
import widgetUtils import wx
import widgetUtils
class textLimited(widgetUtils.BaseDialog):
def __init__(self, *args, **kwargs): class textLimited(widgetUtils.BaseDialog):
super(textLimited, self).__init__(parent=None, *args, **kwargs) def __init__(self, *args, **kwargs):
super(textLimited, self).__init__(parent=None, *args, **kwargs)
def createTextArea(self, message="", text=""):
if not hasattr(self, "panel"): def createTextArea(self, message="", text=""):
self.panel = wx.Panel(self) if not hasattr(self, "panel"):
self.label = wx.StaticText(self.panel, -1, message) self.panel = wx.Panel(self)
self.SetTitle(str(len(text))) self.label = wx.StaticText(self.panel, -1, message)
self.text = wx.TextCtrl(self.panel, -1, text, size=(439, -1),style=wx.TE_MULTILINE|wx.TE_PROCESS_ENTER) self.SetTitle(str(len(text)))
# font = self.text.GetFont() self.text = wx.TextCtrl(self.panel, -1, text, size=(439, -1),style=wx.TE_MULTILINE|wx.TE_PROCESS_ENTER)
# dc = wx.WindowDC(self.text) # font = self.text.GetFont()
# dc.SetFont(font) # dc = wx.WindowDC(self.text)
# x, y = dc.GetTextExtent("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000") # dc.SetFont(font)
# self.text.SetSize((x, y)) # x, y = dc.GetTextExtent("00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000")
self.Bind(wx.EVT_CHAR_HOOK, self.handle_keys, self.text) # self.text.SetSize((x, y))
self.text.SetFocus() self.Bind(wx.EVT_CHAR_HOOK, self.handle_keys, self.text)
self.textBox = wx.BoxSizer(wx.HORIZONTAL) self.text.SetFocus()
self.textBox.Add(self.label, 0, wx.ALL, 5) self.textBox = wx.BoxSizer(wx.HORIZONTAL)
self.textBox.Add(self.text, 0, wx.ALL, 5) self.textBox.Add(self.label, 0, wx.ALL, 5)
self.textBox.Add(self.text, 0, wx.ALL, 5)
def text_focus(self):
self.text.SetFocus() def text_focus(self):
self.text.SetFocus()
def get_text(self):
return self.text.GetValue() def get_text(self):
return self.text.GetValue()
def set_text(self, text):
return self.text.ChangeValue(text) def set_text(self, text):
return self.text.ChangeValue(text)
def set_title(self, new_title):
return self.SetTitle(new_title) def set_title(self, new_title):
return self.SetTitle(new_title)
def enable_button(self, buttonName):
if hasattr(self, buttonName): def enable_button(self, buttonName):
return getattr(self, buttonName).Enable() if hasattr(self, buttonName):
return getattr(self, buttonName).Enable()
def disable_button(self, buttonName):
if hasattr(self, buttonName): def disable_button(self, buttonName):
return getattr(self, buttonName).Disable() if hasattr(self, buttonName):
return getattr(self, buttonName).Disable()
def onSelect(self, ev):
self.text.SelectAll() def onSelect(self, ev):
self.text.SelectAll()
def handle_keys(self, event):
shift=event.ShiftDown() def handle_keys(self, event):
if event.GetKeyCode() == wx.WXK_RETURN and shift==False and hasattr(self,'okButton'): shift=event.ShiftDown()
wx.PostEvent(self.okButton.GetEventHandler(), wx.PyCommandEvent(wx.EVT_BUTTON.typeId,wx.ID_OK)) if event.GetKeyCode() == wx.WXK_RETURN and shift==False and hasattr(self,'okButton'):
else: wx.PostEvent(self.okButton.GetEventHandler(), wx.PyCommandEvent(wx.EVT_BUTTON.typeId,wx.ID_OK))
event.Skip() else:
event.Skip()
def set_cursor_at_end(self):
self.text.SetInsertionPoint(len(self.text.GetValue())) def set_cursor_at_end(self):
self.text.SetInsertionPoint(len(self.text.GetValue()))
def set_cursor_at_position(self, position):
self.text.SetInsertionPoint(position) def set_cursor_at_position(self, position):
self.text.SetInsertionPoint(position)
def get_position(self):
return self.text.GetInsertionPoint() def get_position(self):
return self.text.GetInsertionPoint()
def popup_menu(self, menu):
self.PopupMenu(menu, self.text.GetPosition()) def popup_menu(self, menu):
self.PopupMenu(menu, self.text.GetPosition())
class tweet(textLimited):
def createControls(self, title, message, text): class tweet(textLimited):
self.mainBox = wx.BoxSizer(wx.VERTICAL) def createControls(self, title, message, text):
self.createTextArea(message, text) self.mainBox = wx.BoxSizer(wx.VERTICAL)
self.mainBox.Add(self.textBox, 0, wx.ALL, 5) self.createTextArea(message, text)
self.long_tweet = wx.CheckBox(self.panel, -1, _(u"&Long tweet")) self.mainBox.Add(self.textBox, 0, wx.ALL, 5)
self.long_tweet.SetValue(True) self.long_tweet = wx.CheckBox(self.panel, -1, _(u"&Long tweet"))
self.upload_image = wx.Button(self.panel, -1, _(u"&Upload image..."), size=wx.DefaultSize) self.long_tweet.SetValue(True)
self.spellcheck = wx.Button(self.panel, -1, _("Check &spelling..."), size=wx.DefaultSize) self.upload_image = wx.Button(self.panel, -1, _(u"&Upload image..."), size=wx.DefaultSize)
self.attach = wx.Button(self.panel, -1, _(u"&Attach audio..."), size=wx.DefaultSize) self.spellcheck = wx.Button(self.panel, -1, _("Check &spelling..."), size=wx.DefaultSize)
self.shortenButton = wx.Button(self.panel, -1, _(u"Sh&orten URL"), size=wx.DefaultSize) self.attach = wx.Button(self.panel, -1, _(u"&Attach audio..."), size=wx.DefaultSize)
self.unshortenButton = wx.Button(self.panel, -1, _(u"&Expand URL"), size=wx.DefaultSize) self.shortenButton = wx.Button(self.panel, -1, _(u"Sh&orten URL"), size=wx.DefaultSize)
self.shortenButton.Disable() self.unshortenButton = wx.Button(self.panel, -1, _(u"&Expand URL"), size=wx.DefaultSize)
self.unshortenButton.Disable() self.shortenButton.Disable()
self.translateButton = wx.Button(self.panel, -1, _(u"&Translate..."), size=wx.DefaultSize) self.unshortenButton.Disable()
self.autocompletionButton = wx.Button(self.panel, -1, _(u"Auto&complete users")) self.translateButton = wx.Button(self.panel, -1, _(u"&Translate..."), size=wx.DefaultSize)
self.okButton = wx.Button(self.panel, wx.ID_OK, _(u"Sen&d"), size=wx.DefaultSize) self.autocompletionButton = wx.Button(self.panel, -1, _(u"Auto&complete users"))
self.okButton.SetDefault() self.okButton = wx.Button(self.panel, wx.ID_OK, _(u"Sen&d"), size=wx.DefaultSize)
cancelButton = wx.Button(self.panel, wx.ID_CANCEL, _(u"C&lose"), size=wx.DefaultSize) self.okButton.SetDefault()
self.buttonsBox1 = wx.BoxSizer(wx.HORIZONTAL) cancelButton = wx.Button(self.panel, wx.ID_CANCEL, _(u"C&lose"), size=wx.DefaultSize)
self.buttonsBox1.Add(self.upload_image, 0, wx.ALL, 10) self.buttonsBox1 = wx.BoxSizer(wx.HORIZONTAL)
self.buttonsBox1.Add(self.spellcheck, 0, wx.ALL, 10) self.buttonsBox1.Add(self.upload_image, 0, wx.ALL, 10)
self.buttonsBox1.Add(self.attach, 0, wx.ALL, 10) self.buttonsBox1.Add(self.spellcheck, 0, wx.ALL, 10)
self.mainBox.Add(self.buttonsBox1, 0, wx.ALL, 10) self.buttonsBox1.Add(self.attach, 0, wx.ALL, 10)
self.buttonsBox2 = wx.BoxSizer(wx.HORIZONTAL) self.mainBox.Add(self.buttonsBox1, 0, wx.ALL, 10)
self.buttonsBox2.Add(self.shortenButton, 0, wx.ALL, 10) self.buttonsBox2 = wx.BoxSizer(wx.HORIZONTAL)
self.buttonsBox2.Add(self.unshortenButton, 0, wx.ALL, 10) self.buttonsBox2.Add(self.shortenButton, 0, wx.ALL, 10)
self.buttonsBox2.Add(self.translateButton, 0, wx.ALL, 10) self.buttonsBox2.Add(self.unshortenButton, 0, wx.ALL, 10)
self.mainBox.Add(self.buttonsBox2, 0, wx.ALL, 10) self.buttonsBox2.Add(self.translateButton, 0, wx.ALL, 10)
self.ok_cancelSizer = wx.BoxSizer(wx.HORIZONTAL) self.mainBox.Add(self.buttonsBox2, 0, wx.ALL, 10)
self.ok_cancelSizer.Add(self.autocompletionButton, 0, wx.ALL, 10) self.ok_cancelSizer = wx.BoxSizer(wx.HORIZONTAL)
self.ok_cancelSizer.Add(self.okButton, 0, wx.ALL, 10) self.ok_cancelSizer.Add(self.autocompletionButton, 0, wx.ALL, 10)
self.ok_cancelSizer.Add(cancelButton, 0, wx.ALL, 10) self.ok_cancelSizer.Add(self.okButton, 0, wx.ALL, 10)
self.mainBox.Add(self.ok_cancelSizer) self.ok_cancelSizer.Add(cancelButton, 0, wx.ALL, 10)
selectId = wx.NewId() self.mainBox.Add(self.ok_cancelSizer)
self.Bind(wx.EVT_MENU, self.onSelect, id=selectId) selectId = wx.NewId()
self.accel_tbl = wx.AcceleratorTable([ self.Bind(wx.EVT_MENU, self.onSelect, id=selectId)
(wx.ACCEL_CTRL, ord('A'), selectId), self.accel_tbl = wx.AcceleratorTable([
]) (wx.ACCEL_CTRL, ord('A'), selectId),
self.SetAcceleratorTable(self.accel_tbl) ])
self.panel.SetSizer(self.mainBox) self.SetAcceleratorTable(self.accel_tbl)
self.panel.SetSizer(self.mainBox)
def __init__(self, title, message, text, *args, **kwargs):
super(tweet, self).__init__() def __init__(self, title, message, text, *args, **kwargs):
self.shift=False super(tweet, self).__init__()
self.createControls(message, title, text) self.shift=False
self.SetClientSize(self.mainBox.CalcMin()) self.createControls(message, title, text)
self.SetClientSize(self.mainBox.CalcMin())
def get_image(self):
openFileDialog = wx.FileDialog(self, _(u"Select the picture to be uploaded"), "", "", _("Image files (*.png, *.jpg, *.gif)|*.png; *.jpg; *.gif"), wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) def get_image(self):
if openFileDialog.ShowModal() == wx.ID_CANCEL: openFileDialog = wx.FileDialog(self, _(u"Select the picture to be uploaded"), "", "", _("Image files (*.png, *.jpg, *.gif)|*.png; *.jpg; *.gif"), wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)
return None if openFileDialog.ShowModal() == wx.ID_CANCEL:
return open(openFileDialog.GetPath(), "rb") return None
return open(openFileDialog.GetPath(), "rb")
class retweet(tweet):
def createControls(self, title, message, text): class retweet(tweet):
self.mainBox = wx.BoxSizer(wx.VERTICAL) def createControls(self, title, message, text):
self.createTextArea(message, "") self.mainBox = wx.BoxSizer(wx.VERTICAL)
label = wx.StaticText(self.panel, -1, _(u"Retweet")) self.createTextArea(message, "")
self.text2 = wx.TextCtrl(self.panel, -1, text, size=(439, -1), style=wx.TE_MULTILINE|wx.TE_READONLY) label = wx.StaticText(self.panel, -1, _(u"Retweet"))
self.retweetBox = wx.BoxSizer(wx.HORIZONTAL) self.text2 = wx.TextCtrl(self.panel, -1, text, size=(439, -1), style=wx.TE_MULTILINE|wx.TE_READONLY)
self.retweetBox.Add(label, 0, wx.ALL, 5) self.retweetBox = wx.BoxSizer(wx.HORIZONTAL)
self.retweetBox.Add(self.text2, 0, wx.ALL, 5) self.retweetBox.Add(label, 0, wx.ALL, 5)
self.mainBox.Add(self.textBox, 0, wx.ALL, 5) self.retweetBox.Add(self.text2, 0, wx.ALL, 5)
self.mainBox.Add(self.retweetBox, 0, wx.ALL, 5) self.mainBox.Add(self.textBox, 0, wx.ALL, 5)
self.upload_image = wx.Button(self.panel, -1, _(u"&Upload image..."), size=wx.DefaultSize) self.mainBox.Add(self.retweetBox, 0, wx.ALL, 5)
self.spellcheck = wx.Button(self.panel, -1, _("Check &spelling..."), size=wx.DefaultSize) self.upload_image = wx.Button(self.panel, -1, _(u"&Upload image..."), size=wx.DefaultSize)
self.attach = wx.Button(self.panel, -1, _(u"&Attach audio..."), size=wx.DefaultSize) self.spellcheck = wx.Button(self.panel, -1, _("Check &spelling..."), size=wx.DefaultSize)
self.shortenButton = wx.Button(self.panel, -1, _(u"Sh&orten URL"), size=wx.DefaultSize) self.attach = wx.Button(self.panel, -1, _(u"&Attach audio..."), size=wx.DefaultSize)
self.unshortenButton = wx.Button(self.panel, -1, _(u"&Expand URL"), size=wx.DefaultSize) self.shortenButton = wx.Button(self.panel, -1, _(u"Sh&orten URL"), size=wx.DefaultSize)
self.shortenButton.Disable() self.unshortenButton = wx.Button(self.panel, -1, _(u"&Expand URL"), size=wx.DefaultSize)
self.unshortenButton.Disable() self.shortenButton.Disable()
self.translateButton = wx.Button(self.panel, -1, _(u"&Translate..."), size=wx.DefaultSize) self.unshortenButton.Disable()
self.autocompletionButton = wx.Button(self.panel, -1, _(u"Auto&complete users")) self.translateButton = wx.Button(self.panel, -1, _(u"&Translate..."), size=wx.DefaultSize)
self.okButton = wx.Button(self.panel, wx.ID_OK, _(u"Sen&d"), size=wx.DefaultSize) self.autocompletionButton = wx.Button(self.panel, -1, _(u"Auto&complete users"))
self.okButton.SetDefault() self.okButton = wx.Button(self.panel, wx.ID_OK, _(u"Sen&d"), size=wx.DefaultSize)
cancelButton = wx.Button(self.panel, wx.ID_CANCEL, _(u"C&lose"), size=wx.DefaultSize) self.okButton.SetDefault()
self.buttonsBox1 = wx.BoxSizer(wx.HORIZONTAL) cancelButton = wx.Button(self.panel, wx.ID_CANCEL, _(u"C&lose"), size=wx.DefaultSize)
self.buttonsBox1.Add(self.upload_image, 0, wx.ALL, 10) self.buttonsBox1 = wx.BoxSizer(wx.HORIZONTAL)
self.buttonsBox1.Add(self.spellcheck, 0, wx.ALL, 10) self.buttonsBox1.Add(self.upload_image, 0, wx.ALL, 10)
self.buttonsBox1.Add(self.attach, 0, wx.ALL, 10) self.buttonsBox1.Add(self.spellcheck, 0, wx.ALL, 10)
self.mainBox.Add(self.buttonsBox1, 0, wx.ALL, 10) self.buttonsBox1.Add(self.attach, 0, wx.ALL, 10)
self.buttonsBox2 = wx.BoxSizer(wx.HORIZONTAL) self.mainBox.Add(self.buttonsBox1, 0, wx.ALL, 10)
self.buttonsBox2.Add(self.shortenButton, 0, wx.ALL, 10) self.buttonsBox2 = wx.BoxSizer(wx.HORIZONTAL)
self.buttonsBox2.Add(self.unshortenButton, 0, wx.ALL, 10) self.buttonsBox2.Add(self.shortenButton, 0, wx.ALL, 10)
self.buttonsBox2.Add(self.translateButton, 0, wx.ALL, 10) self.buttonsBox2.Add(self.unshortenButton, 0, wx.ALL, 10)
self.mainBox.Add(self.buttonsBox2, 0, wx.ALL, 10) self.buttonsBox2.Add(self.translateButton, 0, wx.ALL, 10)
self.ok_cancelSizer = wx.BoxSizer(wx.HORIZONTAL) self.mainBox.Add(self.buttonsBox2, 0, wx.ALL, 10)
self.ok_cancelSizer.Add(self.autocompletionButton, 0, wx.ALL, 10) self.ok_cancelSizer = wx.BoxSizer(wx.HORIZONTAL)
self.ok_cancelSizer.Add(self.okButton, 0, wx.ALL, 10) self.ok_cancelSizer.Add(self.autocompletionButton, 0, wx.ALL, 10)
self.ok_cancelSizer.Add(cancelButton, 0, wx.ALL, 10) self.ok_cancelSizer.Add(self.okButton, 0, wx.ALL, 10)
self.mainBox.Add(self.ok_cancelSizer) self.ok_cancelSizer.Add(cancelButton, 0, wx.ALL, 10)
selectId = wx.NewId() self.mainBox.Add(self.ok_cancelSizer)
self.Bind(wx.EVT_MENU, self.onSelect, id=selectId) selectId = wx.NewId()
self.accel_tbl = wx.AcceleratorTable([ self.Bind(wx.EVT_MENU, self.onSelect, id=selectId)
(wx.ACCEL_CTRL, ord('A'), selectId), self.accel_tbl = wx.AcceleratorTable([
]) (wx.ACCEL_CTRL, ord('A'), selectId),
self.SetAcceleratorTable(self.accel_tbl) ])
self.panel.SetSizer(self.mainBox) self.SetAcceleratorTable(self.accel_tbl)
self.panel.SetSizer(self.mainBox)
def __init__(self, title, message, text, *args, **kwargs):
super(tweet, self).__init__() def __init__(self, title, message, text, *args, **kwargs):
self.createControls(message, title, text) super(tweet, self).__init__()
# self.onTimer(wx.EVT_CHAR_HOOK) self.createControls(message, title, text)
self.SetClientSize(self.mainBox.CalcMin()) # self.onTimer(wx.EVT_CHAR_HOOK)
self.SetClientSize(self.mainBox.CalcMin())
def get_image(self):
openFileDialog = wx.FileDialog(self, _(u"Select the picture to be uploaded"), "", "", _("Image files (*.png, *.jpg, *.gif)|*.png; *.jpg; *.gif"), wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) def get_image(self):
if openFileDialog.ShowModal() == wx.ID_CANCEL: openFileDialog = wx.FileDialog(self, _(u"Select the picture to be uploaded"), "", "", _("Image files (*.png, *.jpg, *.gif)|*.png; *.jpg; *.gif"), wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)
return None if openFileDialog.ShowModal() == wx.ID_CANCEL:
return open(openFileDialog.GetPath(), "rb") return None
return open(openFileDialog.GetPath(), "rb")
class dm(textLimited):
def createControls(self, title, message, users): class dm(textLimited):
self.panel = wx.Panel(self) def createControls(self, title, message, users):
self.mainBox = wx.BoxSizer(wx.VERTICAL) self.panel = wx.Panel(self)
label = wx.StaticText(self.panel, -1, _(u"&Recipient")) self.mainBox = wx.BoxSizer(wx.VERTICAL)
self.cb = wx.ComboBox(self.panel, -1, choices=users, value=users[0], size=wx.DefaultSize) label = wx.StaticText(self.panel, -1, _(u"&Recipient"))
self.autocompletionButton = wx.Button(self.panel, -1, _(u"Auto&complete users")) self.cb = wx.ComboBox(self.panel, -1, choices=users, value=users[0], size=wx.DefaultSize)
self.createTextArea(message, text="") self.autocompletionButton = wx.Button(self.panel, -1, _(u"Auto&complete users"))
userBox = wx.BoxSizer(wx.HORIZONTAL) self.createTextArea(message, text="")
userBox.Add(label, 0, wx.ALL, 5) userBox = wx.BoxSizer(wx.HORIZONTAL)
userBox.Add(self.cb, 0, wx.ALL, 5) userBox.Add(label, 0, wx.ALL, 5)
userBox.Add(self.autocompletionButton, 0, wx.ALL, 5) userBox.Add(self.cb, 0, wx.ALL, 5)
self.mainBox.Add(userBox, 0, wx.ALL, 5) userBox.Add(self.autocompletionButton, 0, wx.ALL, 5)
self.mainBox.Add(self.textBox, 0, wx.ALL, 5) self.mainBox.Add(userBox, 0, wx.ALL, 5)
self.spellcheck = wx.Button(self.panel, -1, _("Check &spelling..."), size=wx.DefaultSize) self.mainBox.Add(self.textBox, 0, wx.ALL, 5)
self.attach = wx.Button(self.panel, -1, _(u"&Attach audio..."), size=wx.DefaultSize) self.spellcheck = wx.Button(self.panel, -1, _("Check &spelling..."), size=wx.DefaultSize)
self.shortenButton = wx.Button(self.panel, -1, _(u"Sh&orten URL"), size=wx.DefaultSize) self.attach = wx.Button(self.panel, -1, _(u"&Attach audio..."), size=wx.DefaultSize)
self.unshortenButton = wx.Button(self.panel, -1, _(u"&Expand URL"), size=wx.DefaultSize) self.shortenButton = wx.Button(self.panel, -1, _(u"Sh&orten URL"), size=wx.DefaultSize)
self.shortenButton.Disable() self.unshortenButton = wx.Button(self.panel, -1, _(u"&Expand URL"), size=wx.DefaultSize)
self.unshortenButton.Disable() self.shortenButton.Disable()
self.translateButton = wx.Button(self.panel, -1, _(u"&Translate..."), size=wx.DefaultSize) self.unshortenButton.Disable()
self.okButton = wx.Button(self.panel, wx.ID_OK, _(u"Sen&d"), size=wx.DefaultSize) self.translateButton = wx.Button(self.panel, -1, _(u"&Translate..."), size=wx.DefaultSize)
self.okButton.SetDefault() self.okButton = wx.Button(self.panel, wx.ID_OK, _(u"Sen&d"), size=wx.DefaultSize)
cancelButton = wx.Button(self.panel, wx.ID_CANCEL, _(u"C&lose"), size=wx.DefaultSize) self.okButton.SetDefault()
self.buttonsBox = wx.BoxSizer(wx.HORIZONTAL) cancelButton = wx.Button(self.panel, wx.ID_CANCEL, _(u"C&lose"), size=wx.DefaultSize)
self.buttonsBox.Add(self.spellcheck, 0, wx.ALL, 5) self.buttonsBox = wx.BoxSizer(wx.HORIZONTAL)
self.buttonsBox.Add(self.attach, 0, wx.ALL, 5) self.buttonsBox.Add(self.spellcheck, 0, wx.ALL, 5)
self.mainBox.Add(self.buttonsBox, 0, wx.ALL, 5) self.buttonsBox.Add(self.attach, 0, wx.ALL, 5)
self.buttonsBox1 = wx.BoxSizer(wx.HORIZONTAL) self.mainBox.Add(self.buttonsBox, 0, wx.ALL, 5)
self.buttonsBox1.Add(self.shortenButton, 0, wx.ALL, 5) self.buttonsBox1 = wx.BoxSizer(wx.HORIZONTAL)
self.buttonsBox1.Add(self.unshortenButton, 0, wx.ALL, 5) self.buttonsBox1.Add(self.shortenButton, 0, wx.ALL, 5)
self.buttonsBox1.Add(self.translateButton, 0, wx.ALL, 5) self.buttonsBox1.Add(self.unshortenButton, 0, wx.ALL, 5)
self.mainBox.Add(self.buttonsBox1, 0, wx.ALL, 5) self.buttonsBox1.Add(self.translateButton, 0, wx.ALL, 5)
self.buttonsBox3 = wx.BoxSizer(wx.HORIZONTAL) self.mainBox.Add(self.buttonsBox1, 0, wx.ALL, 5)
self.buttonsBox3.Add(self.okButton, 0, wx.ALL, 5) self.buttonsBox3 = wx.BoxSizer(wx.HORIZONTAL)
self.buttonsBox3.Add(cancelButton, 0, wx.ALL, 5) self.buttonsBox3.Add(self.okButton, 0, wx.ALL, 5)
self.mainBox.Add(self.buttonsBox3, 0, wx.ALL, 5) self.buttonsBox3.Add(cancelButton, 0, wx.ALL, 5)
self.panel.SetSizer(self.mainBox) self.mainBox.Add(self.buttonsBox3, 0, wx.ALL, 5)
self.SetClientSize(self.mainBox.CalcMin()) self.panel.SetSizer(self.mainBox)
self.SetClientSize(self.mainBox.CalcMin())
def __init__(self, title, message, users, *args, **kwargs):
super(dm, self).__init__() def __init__(self, title, message, users, *args, **kwargs):
self.createControls(message, title, users) super(dm, self).__init__()
# self.onTimer(wx.EVT_CHAR_HOOK) self.createControls(message, title, users)
# self.SetClientSize(self.mainBox.CalcMin()) # self.onTimer(wx.EVT_CHAR_HOOK)
# self.SetClientSize(self.mainBox.CalcMin())
def get_user(self):
return self.cb.GetValue() def get_user(self):
return self.cb.GetValue()
def set_user(self, user):
return self.cb.SetValue(user) def set_user(self, user):
return self.cb.SetValue(user)
class reply(textLimited):
class reply(textLimited):
def get_image(self):
openFileDialog = wx.FileDialog(self, _(u"Select the picture to be uploaded"), "", "", _("Image files (*.png, *.jpg, *.gif)|*.png; *.jpg; *.gif"), wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) def get_image(self):
if openFileDialog.ShowModal() == wx.ID_CANCEL: openFileDialog = wx.FileDialog(self, _(u"Select the picture to be uploaded"), "", "", _("Image files (*.png, *.jpg, *.gif)|*.png; *.jpg; *.gif"), wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)
return None if openFileDialog.ShowModal() == wx.ID_CANCEL:
return open(openFileDialog.GetPath(), "rb") return None
return open(openFileDialog.GetPath(), "rb")
def createControls(self, title, message, text):
self.mainBox = wx.BoxSizer(wx.VERTICAL) def createControls(self, title, message, text):
self.createTextArea(message, text) self.mainBox = wx.BoxSizer(wx.VERTICAL)
self.mainBox.Add(self.textBox, 0, wx.ALL, 5) self.createTextArea(message, text)
self.usersbox = wx.BoxSizer(wx.VERTICAL) self.mainBox.Add(self.textBox, 0, wx.ALL, 5)
self.mentionAll = wx.CheckBox(self.panel, -1, _(u"&Mention to all"), size=wx.DefaultSize) self.usersbox = wx.BoxSizer(wx.VERTICAL)
self.mentionAll.Disable() self.mentionAll = wx.CheckBox(self.panel, -1, _(u"&Mention to all"), size=wx.DefaultSize)
self.usersbox.Add(self.mentionAll, 0, wx.ALL, 5) self.mentionAll.Disable()
self.checkboxes = [] self.usersbox.Add(self.mentionAll, 0, wx.ALL, 5)
for i in self.users: self.checkboxes = []
user_checkbox = wx.CheckBox(self.panel, -1, "@"+i, size=wx.DefaultSize) for i in self.users:
self.checkboxes.append(user_checkbox) user_checkbox = wx.CheckBox(self.panel, -1, "@"+i, size=wx.DefaultSize)
self.usersbox.Add(self.checkboxes[-1], 0, wx.ALL, 5) self.checkboxes.append(user_checkbox)
self.mainBox.Add(self.usersbox, 0, wx.ALL, 10) self.usersbox.Add(self.checkboxes[-1], 0, wx.ALL, 5)
self.long_tweet = wx.CheckBox(self.panel, -1, _(u"&Long tweet")) self.mainBox.Add(self.usersbox, 0, wx.ALL, 10)
self.long_tweet.SetValue(True) self.long_tweet = wx.CheckBox(self.panel, -1, _(u"&Long tweet"))
self.upload_image = wx.Button(self.panel, -1, _(u"&Upload image..."), size=wx.DefaultSize) self.long_tweet.SetValue(True)
self.spellcheck = wx.Button(self.panel, -1, _("Check &spelling..."), size=wx.DefaultSize) self.upload_image = wx.Button(self.panel, -1, _(u"&Upload image..."), size=wx.DefaultSize)
self.attach = wx.Button(self.panel, -1, _(u"&Attach audio..."), size=wx.DefaultSize) self.spellcheck = wx.Button(self.panel, -1, _("Check &spelling..."), size=wx.DefaultSize)
self.shortenButton = wx.Button(self.panel, -1, _(u"Sh&orten URL"), size=wx.DefaultSize) self.attach = wx.Button(self.panel, -1, _(u"&Attach audio..."), size=wx.DefaultSize)
self.unshortenButton = wx.Button(self.panel, -1, _(u"&Expand URL"), size=wx.DefaultSize) self.shortenButton = wx.Button(self.panel, -1, _(u"Sh&orten URL"), size=wx.DefaultSize)
self.shortenButton.Disable() self.unshortenButton = wx.Button(self.panel, -1, _(u"&Expand URL"), size=wx.DefaultSize)
self.unshortenButton.Disable() self.shortenButton.Disable()
self.translateButton = wx.Button(self.panel, -1, _(u"&Translate..."), size=wx.DefaultSize) self.unshortenButton.Disable()
self.autocompletionButton = wx.Button(self.panel, -1, _(u"Auto&complete users")) self.translateButton = wx.Button(self.panel, -1, _(u"&Translate..."), size=wx.DefaultSize)
self.okButton = wx.Button(self.panel, wx.ID_OK, _(u"Sen&d"), size=wx.DefaultSize) self.autocompletionButton = wx.Button(self.panel, -1, _(u"Auto&complete users"))
self.okButton.SetDefault() self.okButton = wx.Button(self.panel, wx.ID_OK, _(u"Sen&d"), size=wx.DefaultSize)
cancelButton = wx.Button(self.panel, wx.ID_CANCEL, _(u"C&lose"), size=wx.DefaultSize) self.okButton.SetDefault()
self.buttonsBox1 = wx.BoxSizer(wx.HORIZONTAL) cancelButton = wx.Button(self.panel, wx.ID_CANCEL, _(u"C&lose"), size=wx.DefaultSize)
self.buttonsBox1.Add(self.upload_image, 0, wx.ALL, 10) self.buttonsBox1 = wx.BoxSizer(wx.HORIZONTAL)
self.buttonsBox1.Add(self.spellcheck, 0, wx.ALL, 10) self.buttonsBox1.Add(self.upload_image, 0, wx.ALL, 10)
self.buttonsBox1.Add(self.attach, 0, wx.ALL, 10) self.buttonsBox1.Add(self.spellcheck, 0, wx.ALL, 10)
self.mainBox.Add(self.buttonsBox1, 0, wx.ALL, 10) self.buttonsBox1.Add(self.attach, 0, wx.ALL, 10)
self.buttonsBox2 = wx.BoxSizer(wx.HORIZONTAL) self.mainBox.Add(self.buttonsBox1, 0, wx.ALL, 10)
self.buttonsBox2.Add(self.shortenButton, 0, wx.ALL, 10) self.buttonsBox2 = wx.BoxSizer(wx.HORIZONTAL)
self.buttonsBox2.Add(self.unshortenButton, 0, wx.ALL, 10) self.buttonsBox2.Add(self.shortenButton, 0, wx.ALL, 10)
self.buttonsBox2.Add(self.translateButton, 0, wx.ALL, 10) self.buttonsBox2.Add(self.unshortenButton, 0, wx.ALL, 10)
self.mainBox.Add(self.buttonsBox2, 0, wx.ALL, 10) self.buttonsBox2.Add(self.translateButton, 0, wx.ALL, 10)
self.ok_cancelSizer = wx.BoxSizer(wx.HORIZONTAL) self.mainBox.Add(self.buttonsBox2, 0, wx.ALL, 10)
self.ok_cancelSizer.Add(self.autocompletionButton, 0, wx.ALL, 10) self.ok_cancelSizer = wx.BoxSizer(wx.HORIZONTAL)
self.ok_cancelSizer.Add(self.okButton, 0, wx.ALL, 10) self.ok_cancelSizer.Add(self.autocompletionButton, 0, wx.ALL, 10)
self.ok_cancelSizer.Add(cancelButton, 0, wx.ALL, 10) self.ok_cancelSizer.Add(self.okButton, 0, wx.ALL, 10)
self.mainBox.Add(self.ok_cancelSizer, 0, wx.ALL, 10) self.ok_cancelSizer.Add(cancelButton, 0, wx.ALL, 10)
selectId = wx.NewId() self.mainBox.Add(self.ok_cancelSizer, 0, wx.ALL, 10)
self.Bind(wx.EVT_MENU, self.onSelect, id=selectId) selectId = wx.NewId()
self.accel_tbl = wx.AcceleratorTable([ self.Bind(wx.EVT_MENU, self.onSelect, id=selectId)
(wx.ACCEL_CTRL, ord('A'), selectId), self.accel_tbl = wx.AcceleratorTable([
]) (wx.ACCEL_CTRL, ord('A'), selectId),
self.SetAcceleratorTable(self.accel_tbl) ])
self.panel.SetSizer(self.mainBox) self.SetAcceleratorTable(self.accel_tbl)
self.panel.SetSizer(self.mainBox)
def __init__(self, title, message, text, users=[], *args, **kwargs):
self.users = users def __init__(self, title, message, text, users=[], *args, **kwargs):
super(reply, self).__init__() self.users = users
self.shift=False super(reply, self).__init__()
self.createControls(message, title, text) self.shift=False
self.SetClientSize(self.mainBox.CalcMin()) self.createControls(message, title, text)
self.SetClientSize(self.mainBox.CalcMin())
class viewTweet(widgetUtils.BaseDialog):
def set_title(self, lenght): class viewTweet(widgetUtils.BaseDialog):
self.SetTitle(_(u"Tweet - %i characters ") % (lenght,)) def set_title(self, lenght):
self.SetTitle(_(u"Tweet - %i characters ") % (lenght,))
def __init__(self, text, rt_count, favs_count,source, *args, **kwargs):
super(viewTweet, self).__init__(None, size=(850,850)) def __init__(self, text, rt_count, favs_count,source, *args, **kwargs):
panel = wx.Panel(self) super(viewTweet, self).__init__(None, size=(850,850))
label = wx.StaticText(panel, -1, _(u"Tweet")) panel = wx.Panel(self)
self.text = wx.TextCtrl(panel, -1, text, style=wx.TE_READONLY|wx.TE_MULTILINE, size=(250, 180)) label = wx.StaticText(panel, -1, _(u"Tweet"))
dc = wx.WindowDC(self.text) self.text = wx.TextCtrl(panel, -1, text, style=wx.TE_READONLY|wx.TE_MULTILINE, size=(250, 180))
dc.SetFont(self.text.GetFont()) dc = wx.WindowDC(self.text)
(x, y) = dc.GetMultiLineTextExtent("0"*140) dc.SetFont(self.text.GetFont())
self.text.SetSize((x, y)) (x, y) = dc.GetMultiLineTextExtent("0"*140)
self.text.SetFocus() self.text.SetSize((x, y))
textBox = wx.BoxSizer(wx.HORIZONTAL) self.text.SetFocus()
textBox.Add(label, 0, wx.ALL, 5) textBox = wx.BoxSizer(wx.HORIZONTAL)
textBox.Add(self.text, 1, wx.EXPAND, 5) textBox.Add(label, 0, wx.ALL, 5)
mainBox = wx.BoxSizer(wx.VERTICAL) textBox.Add(self.text, 1, wx.EXPAND, 5)
mainBox.Add(textBox, 0, wx.ALL, 5) mainBox = wx.BoxSizer(wx.VERTICAL)
label2 = wx.StaticText(panel, -1, _(u"Image description")) mainBox.Add(textBox, 0, wx.ALL, 5)
self.image_description = wx.TextCtrl(panel, -1, style=wx.TE_READONLY|wx.TE_MULTILINE, size=(250, 180)) label2 = wx.StaticText(panel, -1, _(u"Image description"))
dc = wx.WindowDC(self.image_description) self.image_description = wx.TextCtrl(panel, -1, style=wx.TE_READONLY|wx.TE_MULTILINE, size=(250, 180))
dc.SetFont(self.image_description.GetFont()) dc = wx.WindowDC(self.image_description)
(x, y) = dc.GetMultiLineTextExtent("0"*450) dc.SetFont(self.image_description.GetFont())
self.image_description.SetSize((x, y)) (x, y) = dc.GetMultiLineTextExtent("0"*450)
self.image_description.Enable(False) self.image_description.SetSize((x, y))
iBox = wx.BoxSizer(wx.HORIZONTAL) self.image_description.Enable(False)
iBox.Add(label2, 0, wx.ALL, 5) iBox = wx.BoxSizer(wx.HORIZONTAL)
iBox.Add(self.image_description, 1, wx.EXPAND, 5) iBox.Add(label2, 0, wx.ALL, 5)
mainBox.Add(iBox, 0, wx.ALL, 5) iBox.Add(self.image_description, 1, wx.EXPAND, 5)
rtCountLabel = wx.StaticText(panel, -1, _(u"Retweets: ")) mainBox.Add(iBox, 0, wx.ALL, 5)
rtCount = wx.TextCtrl(panel, -1, rt_count, size=wx.DefaultSize, style=wx.TE_READONLY|wx.TE_MULTILINE) rtCountLabel = wx.StaticText(panel, -1, _(u"Retweets: "))
rtBox = wx.BoxSizer(wx.HORIZONTAL) rtCount = wx.TextCtrl(panel, -1, rt_count, size=wx.DefaultSize, style=wx.TE_READONLY|wx.TE_MULTILINE)
rtBox.Add(rtCountLabel, 0, wx.ALL, 5) rtBox = wx.BoxSizer(wx.HORIZONTAL)
rtBox.Add(rtCount, 0, wx.ALL, 5) rtBox.Add(rtCountLabel, 0, wx.ALL, 5)
favsCountLabel = wx.StaticText(panel, -1, _(u"Likes: ")) rtBox.Add(rtCount, 0, wx.ALL, 5)
favsCount = wx.TextCtrl(panel, -1, favs_count, size=wx.DefaultSize, style=wx.TE_READONLY|wx.TE_MULTILINE) favsCountLabel = wx.StaticText(panel, -1, _(u"Likes: "))
favsBox = wx.BoxSizer(wx.HORIZONTAL) favsCount = wx.TextCtrl(panel, -1, favs_count, size=wx.DefaultSize, style=wx.TE_READONLY|wx.TE_MULTILINE)
favsBox.Add(favsCountLabel, 0, wx.ALL, 5) favsBox = wx.BoxSizer(wx.HORIZONTAL)
favsBox.Add(favsCount, 0, wx.ALL, 5) favsBox.Add(favsCountLabel, 0, wx.ALL, 5)
sourceLabel = wx.StaticText(panel, -1, _(u"Source: ")) favsBox.Add(favsCount, 0, wx.ALL, 5)
sourceTweet = wx.TextCtrl(panel, -1, source, size=wx.DefaultSize, style=wx.TE_READONLY|wx.TE_MULTILINE) sourceLabel = wx.StaticText(panel, -1, _(u"Source: "))
sourceBox = wx.BoxSizer(wx.HORIZONTAL) sourceTweet = wx.TextCtrl(panel, -1, source, size=wx.DefaultSize, style=wx.TE_READONLY|wx.TE_MULTILINE)
sourceBox.Add(sourceLabel, 0, wx.ALL, 5) sourceBox = wx.BoxSizer(wx.HORIZONTAL)
sourceBox.Add(sourceTweet, 0, wx.ALL, 5) sourceBox.Add(sourceLabel, 0, wx.ALL, 5)
infoBox = wx.BoxSizer(wx.HORIZONTAL) sourceBox.Add(sourceTweet, 0, wx.ALL, 5)
infoBox.Add(rtBox, 0, wx.ALL, 5) infoBox = wx.BoxSizer(wx.HORIZONTAL)
infoBox.Add(favsBox, 0, wx.ALL, 5) infoBox.Add(rtBox, 0, wx.ALL, 5)
infoBox.Add(sourceBox, 0, wx.ALL, 5) infoBox.Add(favsBox, 0, wx.ALL, 5)
mainBox.Add(infoBox, 0, wx.ALL, 5) infoBox.Add(sourceBox, 0, wx.ALL, 5)
self.spellcheck = wx.Button(panel, -1, _("Check &spelling..."), size=wx.DefaultSize) mainBox.Add(infoBox, 0, wx.ALL, 5)
self.unshortenButton = wx.Button(panel, -1, _(u"&Expand URL"), size=wx.DefaultSize) self.spellcheck = wx.Button(panel, -1, _("Check &spelling..."), size=wx.DefaultSize)
self.unshortenButton.Disable() self.unshortenButton = wx.Button(panel, -1, _(u"&Expand URL"), size=wx.DefaultSize)
self.translateButton = wx.Button(panel, -1, _(u"&Translate..."), size=wx.DefaultSize) self.unshortenButton.Disable()
cancelButton = wx.Button(panel, wx.ID_CANCEL, _(u"C&lose"), size=wx.DefaultSize) self.translateButton = wx.Button(panel, -1, _(u"&Translate..."), size=wx.DefaultSize)
cancelButton.SetDefault() cancelButton = wx.Button(panel, wx.ID_CANCEL, _(u"C&lose"), size=wx.DefaultSize)
buttonsBox = wx.BoxSizer(wx.HORIZONTAL) cancelButton.SetDefault()
buttonsBox.Add(self.spellcheck, 0, wx.ALL, 5) buttonsBox = wx.BoxSizer(wx.HORIZONTAL)
buttonsBox.Add(self.unshortenButton, 0, wx.ALL, 5) buttonsBox.Add(self.spellcheck, 0, wx.ALL, 5)
buttonsBox.Add(self.translateButton, 0, wx.ALL, 5) buttonsBox.Add(self.unshortenButton, 0, wx.ALL, 5)
buttonsBox.Add(cancelButton, 0, wx.ALL, 5) buttonsBox.Add(self.translateButton, 0, wx.ALL, 5)
mainBox.Add(buttonsBox, 0, wx.ALL, 5) buttonsBox.Add(cancelButton, 0, wx.ALL, 5)
selectId = wx.NewId() mainBox.Add(buttonsBox, 0, wx.ALL, 5)
self.Bind(wx.EVT_MENU, self.onSelect, id=selectId) selectId = wx.NewId()
self.accel_tbl = wx.AcceleratorTable([ self.Bind(wx.EVT_MENU, self.onSelect, id=selectId)
(wx.ACCEL_CTRL, ord('A'), selectId), self.accel_tbl = wx.AcceleratorTable([
]) (wx.ACCEL_CTRL, ord('A'), selectId),
self.SetAcceleratorTable(self.accel_tbl) ])
panel.SetSizer(mainBox) self.SetAcceleratorTable(self.accel_tbl)
self.SetClientSize(mainBox.CalcMin()) panel.SetSizer(mainBox)
self.SetClientSize(mainBox.CalcMin())
def set_text(self, text):
self.text.ChangeValue(text) def set_text(self, text):
self.text.ChangeValue(text)
def get_text(self):
return self.text.GetValue() def get_text(self):
return self.text.GetValue()
def set_image_description(self, desc):
self.image_description.Enable(True) def set_image_description(self, desc):
if len(self.image_description.GetValue()) == 0: self.image_description.Enable(True)
self.image_description.SetValue(desc) if len(self.image_description.GetValue()) == 0:
else: self.image_description.SetValue(desc)
self.image_description.SetValue(self.image_description.GetValue()+"\n"+desc) else:
self.image_description.SetValue(self.image_description.GetValue()+"\n"+desc)
def text_focus(self):
self.text.SetFocus() def text_focus(self):
self.text.SetFocus()
def onSelect(self, ev):
self.text.SelectAll() def onSelect(self, ev):
self.text.SelectAll()
def enable_button(self, buttonName):
if hasattr(self, buttonName): def enable_button(self, buttonName):
return getattr(self, buttonName).Enable() if hasattr(self, buttonName):
return getattr(self, buttonName).Enable()
class viewNonTweet(widgetUtils.BaseDialog):
class viewNonTweet(widgetUtils.BaseDialog):
def __init__(self, text, *args, **kwargs):
super(viewNonTweet, self).__init__(None, size=(850,850)) def __init__(self, text, *args, **kwargs):
self.SetTitle(_(u"View")) super(viewNonTweet, self).__init__(None, size=(850,850))
panel = wx.Panel(self) self.SetTitle(_(u"View"))
label = wx.StaticText(panel, -1, _(u"Item")) panel = wx.Panel(self)
self.text = wx.TextCtrl(parent=panel, id=-1, value=text, style=wx.TE_READONLY|wx.TE_MULTILINE, size=(250, 180)) label = wx.StaticText(panel, -1, _(u"Item"))
dc = wx.WindowDC(self.text) self.text = wx.TextCtrl(parent=panel, id=-1, value=text, style=wx.TE_READONLY|wx.TE_MULTILINE, size=(250, 180))
dc.SetFont(self.text.GetFont()) dc = wx.WindowDC(self.text)
(x, y) = dc.GetMultiLineTextExtent("0"*140) dc.SetFont(self.text.GetFont())
self.text.SetSize((x, y)) (x, y) = dc.GetMultiLineTextExtent("0"*140)
self.text.SetFocus() self.text.SetSize((x, y))
textBox = wx.BoxSizer(wx.HORIZONTAL) self.text.SetFocus()
textBox.Add(label, 0, wx.ALL, 5) textBox = wx.BoxSizer(wx.HORIZONTAL)
textBox.Add(self.text, 1, wx.EXPAND, 5) textBox.Add(label, 0, wx.ALL, 5)
mainBox = wx.BoxSizer(wx.VERTICAL) textBox.Add(self.text, 1, wx.EXPAND, 5)
mainBox.Add(textBox, 0, wx.ALL, 5) mainBox = wx.BoxSizer(wx.VERTICAL)
self.spellcheck = wx.Button(panel, -1, _("Check &spelling..."), size=wx.DefaultSize) mainBox.Add(textBox, 0, wx.ALL, 5)
self.unshortenButton = wx.Button(panel, -1, _(u"&Expand URL"), size=wx.DefaultSize) self.spellcheck = wx.Button(panel, -1, _("Check &spelling..."), size=wx.DefaultSize)
self.unshortenButton.Disable() self.unshortenButton = wx.Button(panel, -1, _(u"&Expand URL"), size=wx.DefaultSize)
self.translateButton = wx.Button(panel, -1, _(u"&Translate..."), size=wx.DefaultSize) self.unshortenButton.Disable()
cancelButton = wx.Button(panel, wx.ID_CANCEL, _(u"C&lose"), size=wx.DefaultSize) self.translateButton = wx.Button(panel, -1, _(u"&Translate..."), size=wx.DefaultSize)
cancelButton.SetDefault() cancelButton = wx.Button(panel, wx.ID_CANCEL, _(u"C&lose"), size=wx.DefaultSize)
buttonsBox = wx.BoxSizer(wx.HORIZONTAL) cancelButton.SetDefault()
buttonsBox.Add(self.spellcheck, 0, wx.ALL, 5) buttonsBox = wx.BoxSizer(wx.HORIZONTAL)
buttonsBox.Add(self.unshortenButton, 0, wx.ALL, 5) buttonsBox.Add(self.spellcheck, 0, wx.ALL, 5)
buttonsBox.Add(self.translateButton, 0, wx.ALL, 5) buttonsBox.Add(self.unshortenButton, 0, wx.ALL, 5)
buttonsBox.Add(cancelButton, 0, wx.ALL, 5) buttonsBox.Add(self.translateButton, 0, wx.ALL, 5)
mainBox.Add(buttonsBox, 0, wx.ALL, 5) buttonsBox.Add(cancelButton, 0, wx.ALL, 5)
selectId = wx.NewId() mainBox.Add(buttonsBox, 0, wx.ALL, 5)
self.Bind(wx.EVT_MENU, self.onSelect, id=selectId) selectId = wx.NewId()
self.accel_tbl = wx.AcceleratorTable([ self.Bind(wx.EVT_MENU, self.onSelect, id=selectId)
(wx.ACCEL_CTRL, ord('A'), selectId), self.accel_tbl = wx.AcceleratorTable([
]) (wx.ACCEL_CTRL, ord('A'), selectId),
self.SetAcceleratorTable(self.accel_tbl) ])
panel.SetSizer(mainBox) self.SetAcceleratorTable(self.accel_tbl)
self.SetClientSize(mainBox.CalcMin()) panel.SetSizer(mainBox)
self.SetClientSize(mainBox.CalcMin())
def onSelect(self, ev):
self.text.SelectAll() def onSelect(self, ev):
self.text.SelectAll()
def set_text(self, text):
self.text.ChangeValue(text) def set_text(self, text):
self.text.ChangeValue(text)
def get_text(self):
return self.text.GetValue() def get_text(self):
return self.text.GetValue()
def text_focus(self):
self.text.SetFocus() def text_focus(self):
self.text.SetFocus()
def enable_button(self, buttonName):
if getattr(self, buttonName): def enable_button(self, buttonName):
return getattr(self, buttonName).Enable() if getattr(self, buttonName):
return getattr(self, buttonName).Enable()

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()