Advertisement
egor230

punto switcher for linux.py

Oct 16th, 2023 (edited)
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.94 KB | None | 0 0
  1. from pynput.keyboard import Key, Controller
  2. from pynput import *
  3. from tkinter import *
  4. import time, json, threading, subprocess, os, re
  5.  
  6. data = "dictionary of substitutions.json" # файл список замен.
  7.  
  8. if os.path.exists(data): # есть ли этот файл.
  9. with open(data) as json_file: # загрузка настроек из файла.
  10. d = json.load(json_file, encoding="UTF-8")
  11. longest_key_length = len(max(d.keys(), key=len))# Максимальная длина строки
  12. list_words_ab=sorted(list(d.keys())) # упорядочить список
  13. class save_key:
  14. def __init__(self):
  15. self.key = ""
  16. self.swit=False
  17. self.list_words_ab=[]
  18. def update(self, key1):
  19. self.key =str(self.key)+str(key1).replace("'","")
  20.  
  21. def clean(self):
  22. self.key=''
  23. def return_key(self):
  24. return self.key
  25.  
  26. def backspace(self):
  27. self.key = str(self.key[1:])
  28. return self.key
  29. def save(self, list_words_ab):# сохранить вводное слово.
  30. self.list_words_ab =list_words_ab
  31.  
  32. def get(self):# сохранить вводное слово.
  33. return self.list_words_ab
  34. k=save_key()# Создать объект класса
  35.  
  36. def get_current_keyboard_layout(): # Определить текущую расскладку
  37. result = subprocess.run(['xset', 'q'], capture_output=True, text=True) # Проверка успешного выполнения команды
  38. if result.returncode == 0:
  39. output = result.stdout # Получение вывода команды
  40. lines = output.split('\n') # Разделение вывода на строки
  41. for line in lines:
  42. if 'LED mask' in line:# Получение значения LED mask
  43. # print(line)
  44. pattern = r"LED mask:\s+(\d+)"
  45. match = re.search(pattern, line)
  46. if match:
  47. number = match.group(1)
  48. # print(number)
  49. if '00001002' in str(number): # print("en")
  50. return "en"
  51. else: # print("ru")
  52. return "ru"
  53.  
  54. l = {'й': 'q', 'ц': 'w', 'у': 'e', 'к': 'r', 'е': 't', 'н': 'y', 'г': 'u', 'ш': 'i', 'щ': 'o', 'з': 'p', 'х': '[', 'ъ': ']', 'ф': 'a', 'ы': 's',
  55. 'в': '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',
  56. 'Б': '<', 'Ю': '>', ',': '?', 'Ё': '~'}
  57. def show_tooltip(self, event): # Показать подсказку.
  58. x, y, _, _ = self.widget.bbox("insert")
  59. x += self.widget.winfo_rootx() + 25
  60. y += self.widget.winfo_rooty() + 25
  61.  
  62. self.tooltip = root.Toplevel(self.widget)
  63. self.tooltip.wm_overrideredirect(True)
  64. self.tooltip.wm_geometry(f"+{x}+{y}")
  65.  
  66. label = root.Label(self.tooltip, text=self.text, background="#ffffe0", relief="solid", borderwidth=1)
  67. label.pack()
  68. # всплывающая подсказка
  69. class ToolTip(object):
  70. def __init__(self, widget):
  71. self.widget = widget
  72. self.tipwindow = None
  73. self.id = None
  74. self.x = self.y = 0
  75.  
  76. def showtip(self, text):
  77. "Display text in tooltip window"
  78. self.text = text
  79. if self.tipwindow or not self.text:
  80. return
  81. x, y, cx, cy = self.widget.bbox("insert")
  82. x = x + self.widget.winfo_rootx() + 22
  83. y = y + cy + self.widget.winfo_rooty() +7
  84. self.tipwindow = tw = Toplevel(self.widget)
  85. tw.wm_overrideredirect(1)
  86. tw.wm_geometry("+%d+%d" % (x, y))
  87. label = Label(tw, text=self.text, justify=LEFT,
  88. background="#ffffe0", relief=SOLID, borderwidth=1,
  89. font=("tahoma", "12", "normal"))
  90. label.pack(ipadx=1)
  91.  
  92. def hidetip(self):
  93. tw = self.tipwindow
  94. self.tipwindow = None
  95. if tw:
  96. tw.destroy()
  97.  
  98. def CreateToolTip(widget, text):# Показать подсказку
  99. toolTip = ToolTip(widget)
  100. toolTip.showtip(text)
  101.  
  102. def on_release(key):
  103. pass
  104.  
  105. def typing_text( char1):# Это функция печатает буквы
  106. for char in char1:
  107. delay = 0.008 # Задайте здесь нужную задержку в секундах
  108. script = f'''#!/bin/bash
  109. word="{char}" # Задайте здесь нужное слово
  110. delay={delay} # Задайте здесь нужную задержку в секундах
  111. if [[ -z "$word" ]]; then
  112. xte "key space"
  113. else
  114.  
  115. xdotool type "$word"
  116. sleep $delay # Пауза в секундах
  117. fi
  118. '''
  119. subprocess.call(['bash', '-c', script, '_'])
  120.  
  121. Backspace = f'''#!/bin/bash
  122. xte 'keydown BackSpace' 'keyup BackSpace'
  123. '''
  124. global listener1
  125. def replacing_words(word, res):# удалить абв и написать новое слово
  126. len_word=len(word)+1 # длинна написаного слово для удаления.
  127. for i in range(len_word):# Удаляем слово.
  128. subprocess.call(['bash', '-c', Backspace, '_'])
  129.  
  130. time.sleep(0.5)
  131. typing_text(res)
  132. def on_press2(key, root, word, res, listener1):
  133. key = str(key).replace(" ", "") # print(key)
  134. res1 = res.lstrip().rsplit()
  135. res = ' '.join(res1)
  136. listener1.stop()# остановить обработчик клави.
  137. k.swit=False
  138. if key == "Key.space":
  139. t3 = threading.Thread(target=replacing_words, args=(word, res,))
  140. t3.start()
  141. root.destroy()
  142. sys.exit()
  143. return False
  144. if key != "Key.space":
  145. root.destroy()
  146. sys.exit()
  147.  
  148. return False
  149. def start1(root, word, res):
  150. # print(res)
  151. while 1:
  152. with keyboard.Listener(
  153. on_press=lambda key: on_press2(key, root, word, res, listener1),
  154. on_release=on_release
  155. ) as listener1:
  156. listener1.join()
  157. if k.swit== False:
  158. root.destroy()
  159. break
  160.  
  161. def press_key1(word, res): # print("??????????????????????")
  162. root = Tk()
  163. root.withdraw()
  164. CreateToolTip(root, text=res)
  165. t2 = threading.Thread(target=start1, args=(root,word, res,))
  166. t2.start()
  167. root.mainloop()
  168. def update_word(liter, list_words_ab):# обновить слово
  169. # print(get_current_keyboard_layout())
  170. if "en" == get_current_keyboard_layout():
  171. # print("en")
  172. liter=str(liter[1])
  173. liter = l[liter]
  174. k.update(str(liter))# сложить слово
  175. else:
  176. k.update(str(liter))# сложить слово
  177.  
  178. key = k.return_key()# вернуть слово
  179. # print("press ") # print(key)
  180. if len(key)>longest_key_length:# если оно больше максимальной длинны.
  181. key = k.backspace()# Удалить первую букву в начале слове
  182. for word in list_words_ab:
  183. if len(key)>=len(word):
  184. d1=len(word)*-1
  185. if key[d1:]==word:
  186. res =d[word] # print(key) # print(word) # print(res)
  187. k.clean()
  188. k.swit = True
  189. t1 = threading.Thread(target=press_key1, args=(word, res,))
  190. t1.start()
  191. break
  192. # return False
  193. # return True
  194.  
  195. timestamp = time.time()
  196. def on_press(key):#обработчик клави.
  197. key=str(key).replace(" ","") # print(key)
  198. global timestamp # print(time.time()- timestamp )
  199. if time.time() - timestamp < 0.3 or k.swit==True:
  200. timestamp = time.time() # root.withdraw() # свернуть панель подсказок.
  201. return True
  202. timestamp = time.time()
  203. try:
  204. if key=='Key.ctrl_l' or key=='\' \'' or key=='Key.shift_l'or key=='.' or key==',' or key=='Key.shift_r'\
  205. or key=='\'\'' or key =="Key.ctrl_r" or key == "Key.delete"or key =="Key.right"or key =="Key.left"\
  206. or key =="Key.down" or key =="Key.up" or key =="Key.delete" or key == "Key.space"or key=='\'.\''\
  207. or key=='\',\''or key=='\\\\' or key != 'Key.ctrl_l' and key !="Key.caps_lock" and key !="Key.tab" and key !="Key.alt_l"\
  208. and key !="Key.ctrl_r"and key !="Key.alt_r" and key != "Key.shift_r" and key !="Key.shift" \
  209. and key !="Key.shift" and key != "Key.tab" and key !="Key.backspace"and key !="Key.down"\
  210. and key !="Key.up" and key !="Key.left" and key !="Key.right" and key !="Key.enter"\
  211. and key !="Key.space" and key !="Key.backspace" and key !="Key.cmd"and key !="Key.delete"\
  212. and key !="/" and key != "Key.num_lock" and key !="Key.page_down"and key != "Key.page_up" \
  213. and key != "Key.end" and key != "Key.home" and key !="Key.delete" and key !="Key.insert"\
  214. and key !='\'/\'' and key !='\'\ \'' and key !='\'.\'' : # print(key)
  215. update_word(key, list_words_ab)# обновить слово
  216. # print("upd")
  217. return True
  218. except Exception as ex: # print(ex)
  219. pass
  220.  
  221. listener = keyboard.Listener( on_press= on_press, on_release=on_release)
  222. listener.start()
  223.  
  224. while 1:
  225. pass
  226.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement