Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from pynput.keyboard import Key, Controller
- from pynput import *
- from tkinter import *
- import time, json, threading, subprocess, os, re
- data = "dictionary of substitutions.json" # файл список замен.
- if os.path.exists(data): # есть ли этот файл.
- with open(data) as json_file: # загрузка настроек из файла.
- d = json.load(json_file, encoding="UTF-8")
- longest_key_length = len(max(d.keys(), key=len))# Максимальная длина строки
- list_words_ab=sorted(list(d.keys())) # упорядочить список
- class save_key:
- def __init__(self):
- self.key = ""
- self.swit=False
- self.list_words_ab=[]
- def update(self, key1):
- self.key =str(self.key)+str(key1).replace("'","")
- def clean(self):
- self.key=''
- def return_key(self):
- return self.key
- def backspace(self):
- self.key = str(self.key[1:])
- return self.key
- def save(self, list_words_ab):# сохранить вводное слово.
- self.list_words_ab =list_words_ab
- def get(self):# сохранить вводное слово.
- return self.list_words_ab
- k=save_key()# Создать объект класса
- def get_current_keyboard_layout(): # Определить текущую расскладку
- result = subprocess.run(['xset', 'q'], capture_output=True, text=True) # Проверка успешного выполнения команды
- if result.returncode == 0:
- output = result.stdout # Получение вывода команды
- lines = output.split('\n') # Разделение вывода на строки
- for line in lines:
- if 'LED mask' in line:# Получение значения LED mask
- # print(line)
- pattern = r"LED mask:\s+(\d+)"
- match = re.search(pattern, line)
- if match:
- number = match.group(1)
- # print(number)
- if '00001002' in str(number): # print("en")
- return "en"
- else: # print("ru")
- return "ru"
- l = {'й': 'q', 'ц': 'w', 'у': 'e', 'к': 'r', 'е': 't', 'н': 'y', 'г': 'u', 'ш': 'i', 'щ': 'o', 'з': 'p', 'х': '[', 'ъ': ']', 'ф': 'a', 'ы': 's',
- 'в': 'd', 'а': 'f', 'п': 'g', 'р': 'h', 'о': 'j', 'л': 'k', 'д': 'l', 'ж': ';', 'э': "'", 'я': 'z', 'ч': 'x', 'с': 'c', 'м': 'v', 'и': 'b', 'т': 'n', 'ь': 'm', 'б': ',', 'ю': '.', '.': '/', 'ё': '`', 'Й': 'Q', 'Ц': 'W', 'У': 'E', 'К': 'R', 'Е': 'T', 'Н': 'Y', 'Г': 'U', 'Ш': 'I', 'Щ': 'O', 'З': 'P', 'Х': '{', 'Ъ': '}', 'Ф': 'A', 'Ы': 'S', 'В': 'D', 'А': 'F', 'П': 'G', 'Р': 'H', 'О': 'J', 'Л': 'K', 'Д': 'L', 'Ж': ':', 'Э': '"', 'Я': 'Z', 'Ч': 'X', 'С': 'C', 'М': 'V', 'И': 'B', 'Т': 'N', 'Ь': 'M',
- 'Б': '<', 'Ю': '>', ',': '?', 'Ё': '~'}
- def show_tooltip(self, event): # Показать подсказку.
- x, y, _, _ = self.widget.bbox("insert")
- x += self.widget.winfo_rootx() + 25
- y += self.widget.winfo_rooty() + 25
- self.tooltip = root.Toplevel(self.widget)
- self.tooltip.wm_overrideredirect(True)
- self.tooltip.wm_geometry(f"+{x}+{y}")
- label = root.Label(self.tooltip, text=self.text, background="#ffffe0", relief="solid", borderwidth=1)
- label.pack()
- # всплывающая подсказка
- class ToolTip(object):
- def __init__(self, widget):
- self.widget = widget
- self.tipwindow = None
- self.id = None
- self.x = self.y = 0
- def showtip(self, text):
- "Display text in tooltip window"
- self.text = text
- if self.tipwindow or not self.text:
- return
- x, y, cx, cy = self.widget.bbox("insert")
- x = x + self.widget.winfo_rootx() + 22
- y = y + cy + self.widget.winfo_rooty() +7
- self.tipwindow = tw = Toplevel(self.widget)
- tw.wm_overrideredirect(1)
- tw.wm_geometry("+%d+%d" % (x, y))
- label = Label(tw, text=self.text, justify=LEFT,
- background="#ffffe0", relief=SOLID, borderwidth=1,
- font=("tahoma", "12", "normal"))
- label.pack(ipadx=1)
- def hidetip(self):
- tw = self.tipwindow
- self.tipwindow = None
- if tw:
- tw.destroy()
- def CreateToolTip(widget, text):# Показать подсказку
- toolTip = ToolTip(widget)
- toolTip.showtip(text)
- def on_release(key):
- pass
- def typing_text( char1):# Это функция печатает буквы
- for char in char1:
- delay = 0.008 # Задайте здесь нужную задержку в секундах
- script = f'''#!/bin/bash
- word="{char}" # Задайте здесь нужное слово
- delay={delay} # Задайте здесь нужную задержку в секундах
- if [[ -z "$word" ]]; then
- xte "key space"
- else
- xdotool type "$word"
- sleep $delay # Пауза в секундах
- fi
- '''
- subprocess.call(['bash', '-c', script, '_'])
- Backspace = f'''#!/bin/bash
- xte 'keydown BackSpace' 'keyup BackSpace'
- '''
- global listener1
- def replacing_words(word, res):# удалить абв и написать новое слово
- len_word=len(word)+1 # длинна написаного слово для удаления.
- for i in range(len_word):# Удаляем слово.
- subprocess.call(['bash', '-c', Backspace, '_'])
- time.sleep(0.5)
- typing_text(res)
- def on_press2(key, root, word, res, listener1):
- key = str(key).replace(" ", "") # print(key)
- res1 = res.lstrip().rsplit()
- res = ' '.join(res1)
- listener1.stop()# остановить обработчик клави.
- k.swit=False
- if key == "Key.space":
- t3 = threading.Thread(target=replacing_words, args=(word, res,))
- t3.start()
- root.destroy()
- sys.exit()
- return False
- if key != "Key.space":
- root.destroy()
- sys.exit()
- return False
- def start1(root, word, res):
- # print(res)
- while 1:
- with keyboard.Listener(
- on_press=lambda key: on_press2(key, root, word, res, listener1),
- on_release=on_release
- ) as listener1:
- listener1.join()
- if k.swit== False:
- root.destroy()
- break
- def press_key1(word, res): # print("??????????????????????")
- root = Tk()
- root.withdraw()
- CreateToolTip(root, text=res)
- t2 = threading.Thread(target=start1, args=(root,word, res,))
- t2.start()
- root.mainloop()
- def update_word(liter, list_words_ab):# обновить слово
- # print(get_current_keyboard_layout())
- if "en" == get_current_keyboard_layout():
- # print("en")
- liter=str(liter[1])
- liter = l[liter]
- k.update(str(liter))# сложить слово
- else:
- k.update(str(liter))# сложить слово
- key = k.return_key()# вернуть слово
- # print("press ") # print(key)
- if len(key)>longest_key_length:# если оно больше максимальной длинны.
- key = k.backspace()# Удалить первую букву в начале слове
- for word in list_words_ab:
- if len(key)>=len(word):
- d1=len(word)*-1
- if key[d1:]==word:
- res =d[word] # print(key) # print(word) # print(res)
- k.clean()
- k.swit = True
- t1 = threading.Thread(target=press_key1, args=(word, res,))
- t1.start()
- break
- # return False
- # return True
- timestamp = time.time()
- def on_press(key):#обработчик клави.
- key=str(key).replace(" ","") # print(key)
- global timestamp # print(time.time()- timestamp )
- if time.time() - timestamp < 0.3 or k.swit==True:
- timestamp = time.time() # root.withdraw() # свернуть панель подсказок.
- return True
- timestamp = time.time()
- try:
- if key=='Key.ctrl_l' or key=='\' \'' or key=='Key.shift_l'or key=='.' or key==',' or key=='Key.shift_r'\
- or key=='\'\'' or key =="Key.ctrl_r" or key == "Key.delete"or key =="Key.right"or key =="Key.left"\
- or key =="Key.down" or key =="Key.up" or key =="Key.delete" or key == "Key.space"or key=='\'.\''\
- or key=='\',\''or key=='\\\\' or key != 'Key.ctrl_l' and key !="Key.caps_lock" and key !="Key.tab" and key !="Key.alt_l"\
- and key !="Key.ctrl_r"and key !="Key.alt_r" and key != "Key.shift_r" and key !="Key.shift" \
- and key !="Key.shift" and key != "Key.tab" and key !="Key.backspace"and key !="Key.down"\
- and key !="Key.up" and key !="Key.left" and key !="Key.right" and key !="Key.enter"\
- and key !="Key.space" and key !="Key.backspace" and key !="Key.cmd"and key !="Key.delete"\
- and key !="/" and key != "Key.num_lock" and key !="Key.page_down"and key != "Key.page_up" \
- and key != "Key.end" and key != "Key.home" and key !="Key.delete" and key !="Key.insert"\
- and key !='\'/\'' and key !='\'\ \'' and key !='\'.\'' : # print(key)
- update_word(key, list_words_ab)# обновить слово
- # print("upd")
- return True
- except Exception as ex: # print(ex)
- pass
- listener = keyboard.Listener( on_press= on_press, on_release=on_release)
- listener.start()
- while 1:
- pass
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement