make punctuation configurable, add emoticons

This commit is contained in:
chrys
2016-10-16 22:02:42 +02:00
118 changed files with 3595 additions and 93 deletions

View File

@@ -0,0 +1,26 @@
#!/bin/python
# -*- coding: utf-8 -*-
# Fenrir TTY screen reader
# By Chrys, Storm Dragon, and contributers.
from core import debug
class command():
def __init__(self):
pass
def initialize(self, environment):
self.env = environment
def shutdown(self):
pass
def getDescription(self):
return 'enables or disables announcement of emoticons insteed of chars'
def run(self):
self.env['runtime']['settingsManager'].setSetting('general', 'emoticons', str(not self.env['runtime']['settingsManager'].getSettingAsBool('general', 'emoticons')))
if self.env['runtime']['settingsManager'].getSettingAsBool('general', 'emoticons'):
self.env['runtime']['outputManager'].presentText("emoticons enabled", soundIcon='', interrupt=True)
else:
self.env['runtime']['outputManager'].presentText("emoticons disabled", soundIcon='', interrupt=True)
def setCallback(self, callback):
pass

View File

@@ -34,10 +34,9 @@ class commandManager():
commandList = glob.glob(commandFolder+'*')
for command in commandList:
try:
print(command)
fileName, fileExtension = os.path.splitext(command)
fileName = fileName.split('/')[-1]
if fileName in ['__init__','__pycache__']:
if fileName.startswith('__'):
continue
if fileExtension.lower() == '.py':
spec = importlib.util.spec_from_file_location(fileName, command)
@@ -46,7 +45,7 @@ class commandManager():
self.env['commands'][section][fileName.upper()] = command_mod.command()
self.env['commandsIgnore'][section][fileName.upper()[fileName.upper().find('-')+1:]+'_IGNORE'] = False
self.env['commands'][section][fileName.upper()].initialize(self.env)
self.env['runtime']['debug'].writeDebugOut("Load command:" + section + "." + fileName.upper() ,debug.debugLevel.INFO)
self.env['runtime']['debug'].writeDebugOut("Load command:" + section + "." + fileName.upper() ,debug.debugLevel.INFO, onAnyLevel=True)
except Exception as e:
print(e)
self.env['runtime']['debug'].writeDebugOut("Loading command:" + command ,debug.debugLevel.ERROR)

View File

@@ -37,16 +37,21 @@ class debug():
self._file = open(self._fileName,'a')
self._fileOpened = True
def writeDebugOut(self, text, level = debugLevel.DEACTIVE):
if self.env['runtime']['settingsManager'].getSettingAsInt('general','debugLevel') < int(level):
def writeDebugOut(self, text, level = debugLevel.DEACTIVE, onAnyLevel=False):
if (self.env['runtime']['settingsManager'].getSettingAsInt('general','debugLevel') < int(level)) or \
not (onAnyLevel and self.env['runtime']['settingsManager'].getSettingAsInt('general','debugLevel') > int(debugLevel.DEACTIVE)) :
if self._fileOpened:
self.closeDebugFile()
return
else:
if not self._fileOpened:
self.openDebugFile()
msg = str(level) +' ' + str(datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')
) + ': ' + text
if onAnyLevel:
msg = 'INFO ' + str(datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f'))
else:
msg = str(level) +' ' + str(datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f')
)
msg += ': ' + text
print(msg)
self._file.write(msg + '\n')

View File

@@ -11,6 +11,7 @@ from core import screenData
from core import generalInformation
from core import commands
from core import inputEvent
from core import punctuation
environment = {
'screenData': screenData.screenData,
@@ -22,6 +23,7 @@ environment = {
'commandInfo': commands.commandInfo,
'commandBuffer': commands.commandBuffer,
'input': inputEvent.input,
'punctuation': punctuation.punctuation,
'soundIcons': {},
'bindings': {},
}

View File

@@ -41,7 +41,8 @@ class inputManager():
self.env['input']['currInput'] = sorted(self.env['input']['currInput'])
if len(self.env['input']['currInput']) == 0:
self.env['input']['prevDeepestInput'] = []
self.env['input']['shortcutRepeat'] = 1
self.env['input']['shortcutRepeat'] = 1
self.env['input']['lastInputTime'] = time.time()
elif mEvent['EventState'] == 1:
if not mEvent['EventName'] in self.env['input']['currInput']:
self.env['input']['currInput'].append(mEvent['EventName'])
@@ -50,8 +51,11 @@ class inputManager():
if len(self.env['input']['prevDeepestInput']) < len(self.env['input']['currInput']):
self.env['input']['prevDeepestInput'] = self.env['input']['currInput'].copy()
elif self.env['input']['prevDeepestInput'] == self.env['input']['currInput']:
self.env['input']['shortcutRepeat'] += 1
if time.time() - self.env['input']['lastInputTime'] <= self.env['runtime']['settingsManager'].getSettingAsFloat('keyboard','doubleTapTimeout'):
self.env['input']['shortcutRepeat'] += 1
else:
self.env['input']['shortcutRepeat'] = 1
self.env['input']['lastInputTime'] = time.time()
elif mEvent['EventState'] == 2:
pass
else:
@@ -62,7 +66,7 @@ class inputManager():
self.env['input']['newCapsLock'] = self.env['runtime']['inputDriver'].getCapslock()
self.env['input']['oldScrollLock'] = self.env['input']['newScrollLock']
self.env['input']['newScrollLock'] = self.env['runtime']['inputDriver'].getScrollLock()
self.env['input']['lastInputTime'] = time.time()
return eventReceived
def grabDevices(self):

View File

@@ -0,0 +1,61 @@
#!/bin/python
# -*- coding: utf-8 -*-
# Fenrir TTY screen reader
# By Chrys, Storm Dragon, and contributers.
from core import debug
import string
punctuation = {
'LEVELDICT':{
'none': '',
'some': '#-$~+*-/\\@',
'most': '.,:-$~+*-/\\@!#%^&*()[]}{<>;',
'all': string.punctuation,
},
'PUNCTDICT':{
'&':'and',
"'":"apostrophe",
'@':'at',
'\\':'backslash',
'|':'bar',
'!':'bang',
'^':'carrot',
':':'colon',
',':'comma',
'-':'dash',
'$':'dollar',
'.':'dot',
'>':'greater',
'`':'grave',
'#':'hash',
'{':'left brace',
'[':'left bracket',
'(':'left paren',
'<':'less',
'%':'percent',
'+':'plus',
'?':'question',
'"':'quote',
')':'right paren',
'}':'right brace',
']':'right bracket',
';':'semicolon',
'/':'slash',
'*':'star',
'~':'tilde',
'_':'line',
'=':'equals',
},
'CUSTOMDICT':{
'chrys': 'nice chrys'
},
'EMOTICONDICT':{
':)':'smiley',
';)':'winking face',
'XD':'loool',
':@':'angry face',
':D':'lought'
},
}

View File

@@ -17,62 +17,7 @@ class punctuationManager():
# dot, comma, grave, apostrophe
for char in [ord('.'),ord(','),ord('`'),ord("'")]:
self.allPunctNone[char] = None
self.punctuation = {
'levels':{
'none': '',
'some': '#-$~+*-/\\@',
'most': '.,:-$~+*-/\\@!#%^&*()[]}{<>;',
'all': string.punctuation,
},
'punctuationDict':{
'&':'and',
"'":"apostrophe",
'@':'at',
'\\':'backslash',
'|':'bar',
'!':'bang',
'^':'carrot',
':':'colon',
',':'comma',
'-':'dash',
'$':'dollar',
'.':'dot',
'>':'greater',
'`':'grave',
'#':'hash',
'{':'left brace',
'[':'left bracket',
'(':'left paren',
'<':'less',
'%':'percent',
'+':'plus',
'?':'question',
'"':'quote',
')':'right paren',
'}':'right brace',
']':'right bracket',
';':'semicolon',
'/':'slash',
'*':'star',
'~':'tilde',
'_':'line',
'=':'equals',
},
'customDict':{
'>:)':'evil smiley',
'>:-)':'evil smiley',
'>:)}':'evil beerded smiley',
'>:-)}':'evil beerded smiley',
':)':'smiley',
':-)':'smiley',
':)}':'beerded smiley',
':-)}':'beerded smiley',
';)':'winking face',
'XD':'loool',
':@':'angry face',
':D':'lought'
}
}
def shutdown(self):
pass
def removeUnused(self, text):
@@ -94,18 +39,21 @@ class punctuationManager():
return resultText
def proceedPunctuation(self, text, ignorePunctuation=False):
resultText = self.useCustomDict(text, self.punctuation['customDict'])
resultText = text
resultText = self.useCustomDict(resultText, self.env['punctuation']['CUSTOMDICT'])
if self.env['runtime']['settingsManager'].getSetting('general', 'emoticons'):
resultText = self.useCustomDict(resultText, self.env['punctuation']['EMOTICONDICT'])
currPunctLevel = ''
if not ignorePunctuation and self.env['runtime']['settingsManager'].getSetting('general', 'punctuationLevel').lower() in self.punctuation['levels']:
currPunctLevel = self.punctuation['levels'][self.env['runtime']['settingsManager'].getSetting('general', 'punctuationLevel').lower()]
if not ignorePunctuation and self.env['runtime']['settingsManager'].getSetting('general', 'punctuationLevel').lower() in self.env['punctuation']['LEVELDICT']:
currPunctLevel = self.env['punctuation']['LEVELDICT'][self.env['runtime']['settingsManager'].getSetting('general', 'punctuationLevel').lower()]
else:
currPunctLevel = string.punctuation
resultText = self.usePunctuationDict(resultText, self.punctuation['punctuationDict'], currPunctLevel)
resultText = self.usePunctuationDict(resultText, self.env['punctuation']['PUNCTDICT'], currPunctLevel)
resultText = self.removeUnused(resultText)
return resultText
def cyclePunctuation(self):
punctList = list(self.punctuation['levels'].keys())
punctList = list(self.env['punctuation']['LEVELDICT'].keys())
try:
currIndex = punctList.index(self.env['runtime']['settingsManager'].getSetting('general', 'punctuationLevel').lower()) # curr punctuation
except:

View File

@@ -41,8 +41,10 @@ settings = {
},
'general':{
'debugLevel': debug.debugLevel.DEACTIVE,
'punctuationProfile':'default',
'punctuationLevel': 1,
'numberOfClipboards': 10,
'emoticons': True,
'fenrirKeys': ['KEY_KP0'],
'timeFormat': '%I:%M%P',
'dateFormat': '%A, %B %d, %Y',
@@ -64,6 +66,6 @@ settings = {
'charDeleteEcho': True,
'wordEcho': True,
'interruptOnKeyPress': True,
'doubleTapDelay': 0.2,
'doubleTapTimeout': 0.2,
}
}

View File

@@ -33,6 +33,8 @@ class settingsManager():
if not line:
break
line = line.replace('\n','')
if line.replace(" ","") == '':
continue
if line.replace(" ","").startswith("#"):
continue
if line.count("=") != 1:
@@ -53,7 +55,7 @@ class settingsManager():
shortcutKeys.append(key.upper())
shortcut.append(shortcutRepeat)
shortcut.append(sorted(shortcutKeys))
self.env['runtime']['debug'].writeDebugOut("Shortcut: "+ str(shortcut) + ' command:' +commandName ,debug.debugLevel.INFO)
self.env['runtime']['debug'].writeDebugOut("Shortcut: "+ str(shortcut) + ' command:' +commandName ,debug.debugLevel.INFO, onAnyLevel=True)
self.env['bindings'][str(shortcut)] = commandName
kbConfig.close()
@@ -64,6 +66,8 @@ class settingsManager():
if not line:
break
line = line.replace('\n','')
if line.replace(" ","") == '':
continue
if line.replace(" ","").startswith("#"):
continue
if line.count("=") != 1:
@@ -81,8 +85,40 @@ class settingsManager():
if os.path.exists(soundIconPath + Values[1]):
soundIconFile = soundIconPath + Values[1]
self.env['soundIcons'][soundIcon] = soundIconFile
self.env['runtime']['debug'].writeDebugOut("SoundIcon: " + soundIcon + '.' + soundIconFile, debug.debugLevel.INFO, onAnyLevel=True)
siConfig.close()
def loadDicts(self, dictConfigPath=os.path.dirname(os.path.realpath(__main__.__file__)) + '/../../config/punctuation/default.conf'):
dictConfig = open(dictConfigPath,"r")
currDictName = ''
while(True):
line = dictConfig.readline()
if not line:
break
line = line.replace('\n','')
if line.replace(" ","") == '':
continue
if line.replace(" ","").startswith("#"):
continue
if line.replace(" ","").upper().startswith("[") and \
line.replace(" ","").upper().endswith("DICT]"):
currDictName = line[line.find('[') + 1 :line.upper().find('DICT]') + 4].upper()
else:
if currDictName == '':
continue
if not ":===:" in line:
continue
sepLine = line.split(':===:')
if len(sepLine) == 1:
sepLine.append('')
elif len(sepLine) < 1:
continue
elif len(sepLine) > 2:
sepLine[1] = ':===:'
self.env['punctuation'][currDictName][sepLine[0]] = sepLine[1]
self.env['runtime']['debug'].writeDebugOut("Punctuation: " + currDictName + '.' + str(sepLine[0]) + ' :' + sepLine[1] ,debug.debugLevel.INFO, onAnyLevel=True)
dictConfig.close()
def loadSettings(self, settingConfigPath):
if not os.path.exists(settingConfigPath):
return False
@@ -189,6 +225,16 @@ class settingsManager():
else:
environment['runtime']['settingsManager'].loadSoundIcons(self.getSetting('sound','theme'))
if not os.path.exists(self.getSetting('general','punctuationProfile')):
if os.path.exists(settingsRoot + 'punctuation/' + self.getSetting('general','punctuationProfile')):
self.setSetting('general', 'punctuationProfile', settingsRoot + 'punctuation/' + self.getSetting('general','punctuationProfile'))
environment['runtime']['settingsManager'].loadDicts(self.getSetting('general','punctuationProfile'))
if os.path.exists(settingsRoot + 'punctuation/' + self.getSetting('general','punctuationProfile') + '.conf'):
self.setSetting('general', 'punctuationProfile', settingsRoot + 'punctuation/' + self.getSetting('general','punctuationProfile') + '.conf')
environment['runtime']['settingsManager'].loadDicts(self.getSetting('general','punctuationProfile'))
else:
environment['runtime']['settingsManager'].loadDicts(self.getSetting('general','punctuationProfile'))
environment['runtime']['inputManager'] = inputManager.inputManager()
environment['runtime']['inputManager'].initialize(environment)
environment['runtime']['outputManager'] = outputManager.outputManager()
@@ -206,10 +252,10 @@ class settingsManager():
environment['runtime']['screenManager'] = screenManager.screenManager()
environment['runtime']['screenManager'].initialize(environment)
environment['runtime']['debug'].writeDebugOut('\/-------environment-------\/',debug.debugLevel.ERROR)
environment['runtime']['debug'].writeDebugOut(str(environment),debug.debugLevel.ERROR)
environment['runtime']['debug'].writeDebugOut('\/-------settings.conf-------\/',debug.debugLevel.ERROR)
environment['runtime']['debug'].writeDebugOut('\/-------environment-------\/',debug.debugLevel.INFO, onAnyLevel=True)
environment['runtime']['debug'].writeDebugOut(str(environment),debug.debugLevel.INFO, onAnyLevel=True)
environment['runtime']['debug'].writeDebugOut('\/-------settings.conf-------\/',debug.debugLevel.INFO, onAnyLevel=True)
environment['runtime']['debug'].writeDebugOut(str(environment['settings']._sections
),debug.debugLevel.ERROR)
),debug.debugLevel.INFO, onAnyLevel=True)
return environment

View File

@@ -117,20 +117,24 @@ class driver():
return False
def grabDevices(self):
# leve the old code until the new one is better tested
# for fd in self.iDevices:
# dev = self.iDevices[fd]
# cap = dev.capabilities()
# del cap[0]
# self.uDevices[fd] = UInput(
# cap,
# dev.name,
# #dev.info.vendor,
# #dev.info.product,
# #dev.version,
# #dev.info.bustype,
# #'/dev/uinput'
# )
# dev.grab()
for fd in self.iDevices:
dev = self.iDevices[fd]
cap = dev.capabilities()
del cap[0]
self.uDevices[fd] = UInput(
cap,
dev.name,
#dev.info.vendor,
#dev.info.product,
#dev.version,
#dev.info.bustype,
#'/dev/uinput'
)
dev.grab()
self.uDevices[fd] = UInput.from_device(self.iDevices[fd].fn)
self.iDevices[fd].grab()
def releaseDevices(self):
for fd in self.iDevices: