Advertisement
egor230

Mouse setting control for buttons python linux

Dec 13th, 2022 (edited)
977
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 40.09 KB | Source Code | 0 0
  1. from Mouse_libs import *
  2. def run_scrypt(i):
  3.   res= dict_save.return_jnson()
  4.   if "script_mouse" not in res:
  5.     res.setdefault("script_mouse", {})
  6.   if res["script_mouse"].get(dict_save.get_cur_app()) is None:
  7.       res["script_mouse"].setdefault(dict_save.get_cur_app(), {})
  8.  
  9.   if res["script_mouse"][dict_save.get_cur_app()].get(defaut_list_mouse_buttons[i]) is None:
  10.       res["script_mouse"][dict_save.get_cur_app()].setdefault(defaut_list_mouse_buttons[i], "#!/bin/bash\n")
  11.  
  12.   root.title("Скрипт")
  13.   notebook = ttk.Notebook(root)
  14.   notebook.grid(row=0, column=0, sticky="nsew")
  15.  
  16.   tab1 = ttk.Frame(notebook)  # Создаем одну вкладку для текста
  17.   notebook.add(tab1, text="Редактор")
  18.  
  19.   # Добавляем виджет Text на вкладку для ввода текста
  20.   text_widget = Text(tab1, wrap='word')
  21.   text_widget.grid(row=0, column=0, sticky="nsew")
  22.   key_mouse_scrypt = res["script_mouse"][dict_save.get_cur_app()].get(defaut_list_mouse_buttons[i])
  23.   # Вставляем текст только если он не равен "#!/bin/bash\n"
  24.   if key_mouse_scrypt and key_mouse_scrypt != "#!/bin/bash\n":
  25.       text_widget.insert("end", key_mouse_scrypt)
  26.   else:
  27.       text_widget.insert("end", "#!/bin/bash\n")
  28.     # Функция для закрытия окна
  29.   def close_window(i, key_mouse_scrypt, win):
  30.     text_content = text_widget.get("1.0", "end-1c")  # Извлекаем текст из text_widget
  31.     res["script_mouse"][dict_save.get_cur_app()][defaut_list_mouse_buttons[i]]=text_content
  32.     dict_save.save_jnson(res)
  33.     notebook.destroy()  # Создаем вкладку с кнопкой "Закрыть"
  34.     win.destroy()
  35.  
  36.   # Создаем окно клавиатуры
  37.   win = keyboard_scrypt(root, text_widget)
  38.  
  39.   # Установка обработчика закрытия окна
  40.   win.protocol("WM_DELETE_WINDOW", lambda: close_window(i, key_mouse_scrypt, win))
  41.  
  42. creat = 0  # Глобальная переменная для контроля создания кнопок
  43. a_scrypt = []  # Список для хранения созданных кнопок
  44.  
  45. def create_scrypt_buttons():
  46.   global creat
  47.   y_place = 23  # Начальная координата для кнопок
  48.   res = dict_save.return_jnson()  # Получение данных из dict_saveуу
  49.   for i in range(7):
  50.     if creat == 0:    # Проверяем, нужно ли создавать кнопки
  51.       scrypt_button = Button( text=str(LIST_MOUSE_BUTTONS[i]),     # Создание кнопки
  52.         font=("Arial", 9),  width=10, height=1, command=lambda i1=i: run_scrypt(i1)     )
  53.       scrypt_button.place(x=520, y=y_place)  # Размещение кнопки
  54.       a_scrypt.append(scrypt_button)  # Добавление кнопки в список
  55.  
  56.     # Проверяем состояние кнопки и устанавливаем стиль
  57.     if i < len(a_scrypt) and check_mouse_script(res, dict_save, defaut_list_mouse_buttons, i):      # print("Кнопка активирована")
  58.       a_scrypt[i].config(relief=SUNKEN)  # Изменение стиля кнопки
  59.     else:
  60.       a_scrypt[i].config(relief=RAISED)
  61.     y_place += 31  # Увеличение координаты по вертикали
  62.  
  63.   creat = 1  # Обновляем флаг, чтобы кнопки не создавались повторно
  64. def update_buttons(event=0):# Изменение назначения кнопок.
  65.   # dict_save.set_current_path_game(dict_save.get_cur_app())
  66.   # input()
  67.   dict_save.set_default_id_value()
  68.   res=dict_save.return_jnson()
  69.   # print(res["current_app"])
  70.   # print(dict_save.get_cur_app())
  71.   box_value = dict_save.return_box_values() # Получить значения выпадающего списка
  72.   box_values=[box_value[0].get(), box_value[1].get(), box_value[2].get(),
  73.               box_value[3].get(),box_value[4].get(),box_value[5].get(),box_value[6].get()]
  74.   res["key_value"][str(dict_save.get_cur_app())]=box_values
  75.   dict_save.set_id(id_value.get())
  76.  
  77.   res["current_app"]=str(dict_save.get_cur_app())  # add_button_start["state"] = "normal"
  78.   res["id"]=id_value.get()
  79.   dict_save.save_jnson(res)  # Сохранить новые настройки.  # print("change color label")
  80.  
  81. def run_in_thread(dict_save, game, event):
  82.  dict_save.set_prev_game(dict_save.get_cur_app())  # Сохранить предыдущую игру
  83.  dict_save.set_current_path_game(dict_save.get_cur_app())
  84.  
  85.  while game != dict_save.get_cur_app():  # Получить значение текущей активной строки.
  86.   dict_save.set_cur_app(game)
  87.   time.sleep(1)  # Добавьте задержку, чтобы избежать чрезмерного использования процессора
  88.  
  89.  update_buttons(event)  # Изменение назначения кнопок.
  90.  
  91.  dict_save.set_box_values()
  92.  dict_save.set_values_box()  # Установить знач
  93. def check_label_changed(event, labels, count, var_list):# Когда мы переключаем вкладку актив текущей игры изменение цвета label
  94.  res=dict_save.return_jnson()
  95.  game=list(res['paths'].keys())[count]
  96.  if game== dict_save.get_cur_app():# Если нажата активная вкладка
  97.    return 0 # Выход
  98.  while game!=dict_save.get_cur_app(): # получить значение текущей активной строки.
  99.   dict_save.set_cur_app(game)
  100.  
  101.  dict_save.set_prev_game(game)# Сохранить предыдущую игру
  102.  res['current_app'] = game# Выбранная игра.
  103.  set_colol_white_label_changed(labels)  # Установить белый цвет для всех label print(count)
  104.  if count != dict_save.get_count() :
  105.   dict_save.set_count(count)
  106.   res = labels[count].cget("background")
  107.   for i in range(len(labels)):
  108.    if i != count:
  109.     labels[i].config(background="white")
  110.    if str(res) =="white":
  111.      labels[count].config(background="#06c")
  112.      var_list[count].set(True)
  113.  else:
  114.      if "white" == labels[count].cget("background"):
  115.       labels[count].config(background="#06c")
  116.      else: # в белый
  117.       labels[count].config(background="white")
  118.  
  119.  dict_save.set_box_values()
  120.  update_buttons(event)# Изменение назначения кнопок.
  121.  mouse_check_button(dict_save) # флаг для удержания кнопки мыши.
  122.  create_scrypt_buttons()
  123.  
  124. def checkbutton_changed(event, var_list, count, name_games, labels, curr_app):  # галочки
  125.   dict_save.set_cur_app(curr_app)# Установить текущий путь к игре напротив галочки
  126.   dict_save.set_count(count)
  127.   res = dict_save.return_jnson()
  128.   if var_list[count].get() == False:
  129.     labels[count].config(background="#06c")  # текстовое поле и кнопка для добавления в список
  130.     res["games_checkmark"][str(dict_save.get_cur_app())] = True
  131.   else:
  132.     labels[count].config(background="white")  # текстовое поле и кнопка для добавления в список
  133.     res["games_checkmark"][str(dict_save.get_cur_app())] = False
  134.   for i in range(len(labels)):
  135.     if i != count:
  136.       labels[i].config(background="white")
  137.   dict_save.save_jnson(res)
  138.   update_buttons(event)# Обновить кнопки.
  139.  
  140. def update_mouse_check_button(count):# сохранение после установки флажков.  print(count)
  141.   res=dict_save.return_jnson()
  142.   curr_name=dict_save.get_cur_app()#  print(count)  print(len(res["mouse_press"][curr_name]))
  143.   # Проверка наличия ключа перед его обновлением
  144.   if curr_name in res["mouse_press"]:    # Изменение значения на противоположное
  145.     res["mouse_press"][curr_name][count] = not res["mouse_press"][curr_name][count]
  146.     list_mouse_button_press = res["mouse_press"][curr_name]  # print(list_mouse_button_press)  # Обновить список флажков.
  147.     dict_save.set_default_id_value()
  148.     dict_save.save_jnson(res)
  149. def mouse_check_button(dict_save):
  150.   curr_name=dict_save.get_cur_app()#
  151.   res=dict_save.return_jnson()
  152.   # print(res["mouse_press"][curr_name])
  153.   list_mouse_button_press = list(res["mouse_press"][curr_name])#  print(d)
  154.   mouse_press_button = []# список нажатых кнопок.
  155.   cd1_y = 30
  156.   for count, i in enumerate(list_mouse_button_press):
  157.     mouse_press_button.append(BooleanVar())
  158.     mouse_press_button[count].set(i)
  159.     cb1 = Checkbutton(root, variable=mouse_press_button[count],  # создания галочек
  160.                       onvalue=1, offvalue=0, state=NORMAL,  command=lambda c=count: update_mouse_check_button(c))  # Исправление здесь
  161.     cb1.place(x=490, y=cd1_y)
  162.     cd1_y = cd1_y + 30
  163.     CreateToolTip(cb1, text='Держать нажатой')  # вывод надписи
  164.   dict_save.save_mouse_button_press(list_mouse_button_press, mouse_press_button)
  165.  
  166. def set_colol_white_label_changed(labels):# Установить белый цвет для всех label
  167.   for i in range(len(labels)):
  168.     labels[i].config(background="white")  # у всех надписей снять выделения
  169.  
  170. def change(event, window, new_name, old_name, res, count, labels):# Окно изменение названия игры
  171.   new_name = new_name.get()  # print(new_name, old_name, end=" , ")
  172.   if new_name != "" and new_name != old_name:
  173.     res["paths"][list(res["paths"])[count]]=new_name
  174.     labels[count].config(text=new_name)#  res["paths"][dict_save.get_cur_app()] = new_name.get()
  175.   window.destroy()  # Закрытие окна после сохранения изменений
  176. def change_name_label(event, count): #Изменить название игры
  177.   window = Toplevel(root)  # основа
  178.   window.title("change_name")  # заголовок
  179.   window.geometry("350x150+750+400")  # Первые 2 определяют ширину высоту. Пос 2 x и y координаты на экране.
  180.   window.configure(bg='DimGray')  # Цвет фона окна
  181.   labels = dict_save.return_labels()
  182.   res = dict_save.return_jnson()
  183.   old_name=res["paths"][list(res["paths"])[count]]# Получить прежнее название игры
  184.   new_name = StringVar()
  185.   e = Entry(window, width=25, textvariable=new_name)
  186.   e.grid(column=2, row=0, padx=50, pady=5)
  187.   e.focus()  # Фокусируемся на текстовом поле
  188.   new_name.set(old_name)
  189.   # Кнопка теперь является частью нового диалогового окна `window`, а не исходного `root`
  190.   Button(window, text="Ok", command=lambda: change(None, window, new_name, old_name, res, count,  labels)) \
  191.     .grid(column=2, row=1, padx=50, pady=30)  # кнопка, откроется новое окно.
  192.   e.bind('<Return>', lambda event: change(event, window, new_name, old_name, res, count,labels))
  193.  
  194. def add_file(dict_save):# Добавить новые игры
  195.  res=dict_save.return_jnson() # получаем настройки
  196.  keys_values =res["key_value"][dict_save.get_cur_app()]# конфигурация кнопок от предыдущего профиля.
  197.  mouse_press_old =res["mouse_press"][dict_save.get_cur_app()]# какие кнопки имеют залипания.
  198.  
  199.  # print(dict_save.get_current_app_path())
  200.  cmd = ['zenity', '--file-selection', '--file-filter=EXE files | *.exe | *.EXE'] # Zenity команда для выбора одного exe файла
  201.  # Вызов zenity и получение выбранного пути
  202.  result = subprocess.run(cmd, check=True, stdout=subprocess.PIPE, text=True)
  203.  path_to_file = result.stdout.strip()# новый путь к игре
  204.  name_with_expansion = path.basename(path_to_file)# Получение базового имени файла с расширением из полного пути к файлу
  205.  name = path.splitext(name_with_expansion)[0] # Отделение имени файла без расширения путем разбиения строки.
  206.  li= list(res["paths"].keys())
  207.  if path_to_file in li:
  208.    return 0
  209.  res["paths"][str(path_to_file)]=str(name)
  210.  res["games_checkmark"][str(path_to_file)]=True
  211.  res["key_value"][str(path_to_file)]=keys_values # сохранить пред значения
  212.  res["mouse_press"][str(path_to_file)]= list(mouse_press_old)
  213.  res1= res["key_value"]
  214.  if path_to_file in res1:
  215.      pass
  216.  else:
  217.      res["key_value"][path_to_file]=["LBUTTON","RBUTTON",  "WHEEL_MOUSE_BUTTON",
  218.       "WHEEL_MOUSE_UP", "WHEEL_MOUSE_DOWN", 'XBUTTON1', 'XBUTTON2']
  219.  
  220.  labels=dict_save.return_labels()
  221.  for i in range(len(labels)):
  222.    labels[i].destroy()
  223.  
  224.  labels.clear()
  225.  name_games = dict_save.return_name_games()
  226.  name_games.clear()
  227.  var_list = dict_save.return_var_list()
  228.  var_list.clear()
  229.  labels_with_checkmark = dict_save.return_labels_with_checkmark()
  230.  labels_with_checkmark.clear()
  231.  labels=dict_save.return_labels()
  232.  dict_save.count=+1
  233.  res['current_app'] = path_to_file# Выбранная игра.
  234.  dict_save.set_cur_app(path_to_file)
  235.  dict_save.set_current_path_game(path_to_file)
  236.  dict_save.save_jnson(res)
  237.  set_colol_white_label_changed(labels)  # Установить белый цвет для всех label
  238.  res = dict_save.return_jnson()
  239. # update_buttons()
  240.  filling_in_fields(res)
  241.  
  242.  # keys_values= dict_save.return_box_values()
  243.  # old_keys_values=[]
  244.  # for i in range(len(keys_values)):
  245.  #     old_keys_values.append(keys_values[i].get())
  246.  #
  247.  labels[len(labels)-1].config(background="#06c")  # текстовое поле и кнопка для добавления в список
  248. checkbutton_list=[]
  249. def fill_labes(res, name_games,labels,var_list, labels_with_checkmark):# Заполнение полей надписи и галочки.
  250.   check_mark = res["games_checkmark"]
  251.   d=res["paths"]
  252.   for count, i in enumerate(d):    # print(count)
  253.     name_game = StringVar()    # i это пути к играм
  254.     name_game = d[i] # называния игр.
  255.     box_key = StringVar()    # dict_save.set_cur_app(i)
  256.     name_games.append(name_game)
  257.     labels.append(Label(root, background="white", text=name_games[count], width=28, relief=GROOVE, justify="left"))
  258.     y1 = (count + 1) * 25 + 1
  259.  
  260.     # галочки
  261.     var_list.append(BooleanVar())
  262.     check_mark = res["games_checkmark"]
  263.     bool_check_mark = check_mark[i]
  264.     var_list[count].set(bool_check_mark)
  265.     labels_with_checkmark[labels[count]] = var_list[count]
  266.     cb = Checkbutton(root, variable=var_list[count],  # создания галочек
  267.                      onvalue=1, offvalue=0, state=ACTIVE)
  268.     cb.bind("<Button-1>", lambda event, agr=var_list, agr1=count, agr2=name_games, agr3=labels, agr4=i:
  269.     checkbutton_changed(event, agr, agr1, agr2, agr3, agr4))
  270.     cb.place(x=7, y=y1 - 2)
  271.     checkbutton_list.append(cb)
  272.     # надписи
  273.     labels[count].bind("<Button-1>", lambda event, agr=labels, agr1=count, agr2=var_list:
  274.     check_label_changed(event, agr, agr1, agr2))
  275.     labels[count].bind('<Button-3>', lambda event, agr=count: change_name_label(event, agr))
  276.     labels[count].place(x=10, y=y1)  # текстовое поле и кнопка для добавления в список
  277.  
  278.   keys = list(res['paths'].keys())# Получить все пути игр.
  279.   index = keys.index(res['current_app'])# Узнать индекс текущей игры.
  280.  
  281.   #активное приложение.
  282.   labels[index].config(background="#06c") # Установить cиний цвет.  print(index)
  283.   dict_save.set_count(index)# Установить  индекс текущей игры.
  284.   dict_save.set_box_values()  # Установить значения выпадающего списка.
  285.   dict_save.set_values_box()
  286. def filling_in_fields(res):# заполнения всех полей.
  287.     labels=dict_save.return_labels()
  288.     name_games=dict_save.return_name_games()# имя игр
  289.     var_list=dict_save.return_var_list()
  290.     labels_with_checkmark= dict_save.return_labels_with_checkmark()
  291.     boxs = dict_save.return_box_values()
  292.     fill_labes(res, name_games, labels, var_list, labels_with_checkmark)    # if dict_save.get_count()==0:    #    print("ok")    #  labels[dict_save.get_count()].config(background="#06c")
  293.     dict_save.set_box_values()  # Установить значения выпадающего списка.
  294.     dict_save.set_values_box()
  295. def start(root, dict_save):# запуск всего.
  296.  data = dict_save.data  # файл настроек. print(data)
  297.  if os.path.exists(data):  # есть ли этот файл.
  298.    with open(data) as json_file:# загрузка настроек из файла.
  299.     res = json.load(json_file)
  300.  else:  # Если нет файла создать настройки.
  301.     res ={ 'games_checkmark': {'C:/Windows/explorer.exe': True},
  302.    'paths': {'C:/Windows/explorer.exe': 'По умолчанию'        },
  303.    'key_value': {'C:/Windows/explorer.exe': ['LBUTTON', 'RBUTTON', 'WHEEL_MOUSE_BUTTON', 'SCROLL_UP',
  304.                  'SCROLL_DOWN', 'SCROLL_UP', 'SCROLL_DOWN']   },
  305.    "mouse_press": {  "C:/Windows/explorer.exe": [ False, False,
  306.      False, False, False, False, False ] },
  307.    "id": 0, # Какой id устройства
  308.    "current_app" : 'C:/Windows/explorer.exe'}
  309.  
  310.     know_id = f'''#!/bin/bash
  311.     input_list=$(xinput list)  # Получаем список устройств ввода
  312.     # Исключаем линию с 'Consumer Control' и выбираем первую подходящую строку
  313.     mouse_line=$(echo "$input_list" | head -n 1)
  314.  
  315.     if [ -n "$mouse_line" ]; then  # Если строка найдена, извлекаем ID
  316.          mouse_id=$(echo "$mouse_line" | grep -o "id=[0-9]*" | cut -d "=" -f 2)
  317.          echo "$mouse_id"
  318.     fi
  319.     '''  # Запускаем скрипт нахождения id мыши.
  320.     res["id"] = int(subprocess.run(['bash', '-c', know_id], capture_output=True, text=True).stdout.strip())# print(type(res["id"])) print(res["id"])
  321.  
  322.  d = list(res["paths"].keys()) # получить словарь путей и имен файлов.
  323.  dict_save.save_old_data(res) # сохранить значения настроек из файла.
  324.  dict_save.set_cur_app(res["current_app"])  # установить текущую активную строку.
  325.  
  326.  dict_save.set_prev_game(res["current_app"])
  327.  dict_save.set_current_app_path(res['current_app'])# установит текущий путь к игре.
  328.  box_values = dict_save.return_box_values()  # получить список значения боксов.
  329.  curr_name=dict_save.get_cur_app() # получить значение текущей активной строки.
  330.  key_values = res["key_value"] # получить значения настроек для каждой кнопки мыши.
  331.  
  332.  box_values.clear()# Очистить значения кнопок.
  333.  id_value.set(res["id"])# Установить id устройства в списке.
  334.  dict_save.set_id(res["id"]) #сохранить текущий id устройства
  335.  for i in range(len(LIST_MOUSE_BUTTONS)):  # создания выпадающих списков.
  336.   y1 = (i + 1) * 30 + 1
  337.   box_value = StringVar()
  338.   Label(root, background="#ededed", text=LIST_MOUSE_BUTTONS[i]).place(x=250, y=y1 - 2)
  339.   box = Combobox(root, width=12, textvariable=box_value, values=LIST_KEYS, state='readonly') #
  340.   box.place(x=380, y=y1)
  341.   box_values.append(box_value)
  342.   box.bind('<<ComboboxSelected>>', update_buttons)# Если изменяется значения кнопок
  343.  
  344.  filling_in_fields(res) # заполнения всех полей.
  345.  mouse_check_button(dict_save) # флаг для удержания кнопки мыши.
  346.  start_startup_now(dict_save, root)
  347.  create_scrypt_buttons()# создание углубление кнопок скрипта.
  348.  # print("fill")
  349. def move_last_key_to_front(d):# Рекурсивно перемещает последний ключ словаря в начало.
  350.    #Если значение является словарём, функция применяется и к нему.
  351.  
  352.    # Если d не словарь – возвращаем как есть
  353.    if not isinstance(d, dict):
  354.      return d
  355.  
  356.    keys = list(d.keys())
  357.    if not keys:
  358.      return d
  359.  
  360.    # Сначала обрабатываем последний ключ
  361.    new_d = {keys[-1]: move_last_key_to_front(d[keys[-1]])}
  362.    # Затем остальные ключи в исходном порядке
  363.    for key in keys[:-1]:
  364.      new_d[key] = move_last_key_to_front(d[key])
  365.    return new_d
  366.  
  367. def scrolling_list(event):# прокрутка списка игр.
  368.  a =[]
  369.  labels=dict_save.return_labels()
  370.  for i in range(len(labels)):
  371.    info = labels[i].place_info()
  372.    a.append(int(info["y"]))
  373.  
  374.  var_list = dict_save.return_var_list()
  375.  a = a[1:] + a[:1]  # Перемещаем первый элемент в конец
  376.  for i in range(len(labels)):
  377.    labels[i].place(x=labels[i].winfo_x(), y=a[i])  # Используем winfo_x для получения текущей координаты x
  378.    cb = Checkbutton(root, variable=var_list[i],  # создания галочек
  379.                      onvalue=1, offvalue=0, state=ACTIVE)
  380.    cb.place(x=7, y=a[i] - 2)
  381.  res=dict_save.return_jnson()
  382.  res = move_last_key_to_front(res) #print(res["games_checkmark"])
  383.  dict_save.save_jnson(res)
  384. def add_buttons_keyboard(buttons, window):
  385.  mouse_key_left_button = ttk.Button(window, text="\n\nЛевая\n\n", width=6, style='TButton')
  386.  mouse_key_left_button.place(x=1340, y=100)
  387.  buttons[mouse_key_left_button] = "Левая"
  388.  
  389.  mouse_wheel_up = ttk.Button(window, text="wheel_up", width=11, style='TButton')
  390.  mouse_wheel_up.place(x=1410, y=50)
  391.  buttons[mouse_wheel_up] = "wheel_up" #
  392.  mouse_key_middie_button = ttk.Button(window, text="mouse_middie", width=11, style='TButton')
  393.  mouse_key_middie_button.place(x=1410, y=140)
  394.  buttons[mouse_key_middie_button] = "mouse_middie"
  395.  
  396.  mouse_wheel_down = ttk.Button(window, text="wheel_down", width=11, style='TButton')
  397.  mouse_wheel_down.place(x=1410, y=220)
  398.  buttons[mouse_wheel_down] = "wheel_down"
  399.  
  400.  mouse_key_right_button = ttk.Button(window, text="\n\nПравая\n\n", width=6, style='TButton')
  401.  mouse_key_right_button.place(x=1530, y=100)
  402.  buttons[mouse_key_right_button] = "Правая"
  403. def on_close():# Функция закрытия программы.  # print("exit")
  404.   dict_save.set_default_id_value()
  405.   old_data = dict_save.return_old_data()  # старые значения настроек.
  406.   new_data = dict_save.return_jnson()  # новые значения настроек.
  407.   # print(new_data["key_value"]["C:/Windows/explorer.exe"])  #print(new_data["games_checkmark"])
  408.   if new_data != old_data or list(old_data["games_checkmark"].keys())[0] != list(new_data["games_checkmark"].keys())[0]:# Если ли какие-то изменения
  409.    if (messagebox.askokcancel("Quit", "Do you want to save the changes?")):
  410.         dict_save.write_to_file(new_data)  # записать настройки в файл.
  411.   dict_save.reset_id_value()
  412.   target = "Mouse_setting_control_for_buttons_python_for_linux.py"
  413.   for p in psutil.process_iter(['pid', 'cmdline']):
  414.    if p.info['cmdline'] and target in ' '.join(p.info['cmdline']):
  415.     os.kill(p.info['pid'], signal.SIGTERM)
  416.     break
  417.  
  418.   root.destroy()
  419.   exit()
  420.   sys.exit()
  421.  
  422. def create_virtial_keyboard():# создать виртуальную клавиатуру
  423.   window = Toplevel(root)  # основа
  424.   window.geometry("1350x340+240+580")  # Используем geometry вместо setGeometry
  425.   keyboard_layout = [
  426.    ['Esc', 'F1', 'F2', 'F3', 'F4', 'F5', 'F6', 'F7', 'F8', 'F9', 'F10', 'F11', 'F12', 'Insert', 'Delete', 'Home',
  427.     'End', 'PgUp', 'PgDn']
  428.    , ['~\n`', '!\n1', '@\n2', '#\n3', '$\n4', '%\n5', '^\n6', '&\n7', '*\n8', '(\n9', ')\n0', '_\n-', '+\n=',
  429.       'Backspace', 'Num Lock', '/', '*', '-']
  430.    , ['Tab', 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', '{\n[', '}\n]', '|\n\\', ' 7\nHome', '8\n↑', '9\nPgUp',
  431.       '+']
  432.    , ['Caps Lock', 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ':\n;', '"\n\'', '\nEnter\n', '4\n←', '5\n', '6\n→']
  433.    , ['Shift_L', 'Z', 'X', 'C', 'V', 'B', 'N', 'M', '<\n,', '>\n.', '?\n/', 'Shift', '1\nEnd', '2\n↓', '3\nPgDn', 'KEnter']
  434.    , ['Ctrl', 'Windows', 'Alt_L', 'Space', 'Alt_r', 'Fn', 'Menu', 'Ctrl_r', 'up', '0\nIns', ' . ']
  435.    , ['Left', 'Down', 'Right']
  436.   ]
  437.   buttons={}
  438.   style = ttk.Style()  # При нажатии кнопка меняет свой цвет.
  439.   style.configure('TButton', background='lightgray')
  440.   style.map('TButton', background=[('active', 'blue')])
  441.   for i, row in enumerate(keyboard_layout):  # Создаем клавиатуру.
  442.    for j, key in enumerate(row):
  443.     x1 = 70 * j + 6
  444.     y1 = 50 * i + 6
  445.     button = ttk.Button(window, text=key, width=5, style='TButton')
  446.     buttons[button]=key
  447.     if key == 'Backspace':  # Условие только для Backspace
  448.      button = ttk.Button(window, text=key, width=10, style='TButton')
  449.      buttons[button]=key
  450.      button.place(x=x1, y=y1)
  451.     elif i == 1 and j > 13:  # Смещение кнопок NumPad после Backspace
  452.      button.place(x=x1 + 69, y=y1)  # Сдвигаем вправо на 80 пикселей
  453.     else:
  454.      button.place(x=x1, y=y1)
  455.     if key in [' 7\nHome', '8\n↑', '9\nPgUp', '+']:
  456.      x2 = x1 + 69
  457.      button.place(x=x2, y=y1)
  458.      if key == "+":
  459.       button.config(text="\n\n" + key + "\n")
  460.     if key in ['4\n←', '5\n', '6\n→']:
  461.      x2 = x1 + 140
  462.      button.place(x=x2, y=y1)
  463.     if key in ['1\nEnd', '2\n↓', '3\nPgDn', 'KEnter']:
  464.      x2 = x1 + 210
  465.      button.place(x=x2, y=y1)
  466.      if key == "KEnter":
  467.       button.config(text="\n\n" + key + "\n")
  468.     if i == 5:
  469.      if key in ['Ctrl', 'Windows', 'Alt']:
  470.       button.place(x=x1, y=y1)
  471.      if key == "Space":
  472.       button = ttk.Button(window, text=key, width=30, style='TButton')
  473.       button.place(x=x1, y=y1)
  474.       buttons[button] = key
  475.      elif key in ['Alt_r', 'Fn', 'Menu', 'Ctrl_r']:
  476.       x2 = x1 + 210
  477.       button.config(width=5)  # Устанавливаем ширину 15 для "0\nIns"
  478.       button.place(x=x2, y=y1)
  479.      elif key == 'up':
  480.       x2 = x1 + 280
  481.       button.config(width=5)
  482.       button.place(x=x2, y=y1)
  483.      elif key == "0\nIns":
  484.       x2 = x1 + 420
  485.       button.config(width=15)  # Устанавливаем ширину 15 для "0\nIns"
  486.       button.place(x=x2, y=y1)
  487.      elif key == ' . ':
  488.       x2 = x1 + 490
  489.       button.config(width=5)
  490.       button.place(x=x2, y=y1)
  491.     if i == 6:
  492.      if key in ['Left', 'Down', 'Right']:
  493.       x2 = x1 + 770
  494.       button.config(width=5)
  495.       button.place(x=x2, y=y1 - 9)
  496.   return window, buttons
  497.  
  498. def add_key_text(key, text_widget):
  499.   sc=add_text(key, text_widget)
  500.  
  501.   text_widget.insert(text_widget.index("insert"), sc)
  502.   current_app = dict_save.get_cur_app()  # Получаем текущую игру
  503.   res = dict_save.return_jnson()  # Получение настроек.
  504.   curr_key=dict_save.get_last_key_keyboard_script()
  505.   keyboard_script = res["keyboard_script"][current_app]["keys"]
  506.   if text_widget.get("1.0", "end-1c"):
  507.    keyboard_script[curr_key]=text_widget.get("1.0", "end-1c")  # Извлекаем текст из text_widget""
  508.   dict_save.save_jnson(res)
  509. def kill_notebook(w, n, text_widget):
  510.   current_app = dict_save.get_cur_app()  # Получаем текущую игру
  511.   res = dict_save.return_jnson()  # Получение настроек.
  512.   curr_key=dict_save.get_last_key_keyboard_script()
  513.  
  514.   keyboard_script = res["keyboard_script"][current_app]["keys"]
  515.   sc = text_widget.get("1.0", "end-1c")
  516.   if sc =="": # Удаляем ключ, если он существует
  517.    if curr_key in keyboard_script:
  518.     del keyboard_script[curr_key]
  519.   w.destroy()  # Закрываем предыдущую клавиатуру.
  520.   n.destroy()
  521.   create_keyboard()# Создаем виртуальную клавиатуру
  522. def kill_keyboard(w, n, text_widget):
  523.  kill_notebook(w, n, text_widget)
  524.  
  525. def record_marcross(key,w):# здесь мы записываем макрос
  526.  w.destroy()  # Закрываем предыдущую клавиатуру.
  527.  dict_save.set_last_key_keyboard_script(key)#  сохранить кнопку, которая нажата
  528.  current_app = dict_save.get_cur_app()  # Получаем текущую игру
  529.  res= dict_save.return_jnson()# Получение настроек.
  530.  
  531.  res.setdefault("keyboard_script", {}).setdefault(current_app, {}).setdefault("keys", {})
  532.  keys_active = list(res["keyboard_script"][current_app]["keys"].keys())
  533.  
  534.  window, buttons = create_virtial_keyboard()# Создаем виртуальную клавиатуру
  535.  window.title(f"Запись макроса для клавиши {key}")  # Устанавливаем заголовок окна
  536.  window.geometry("1610x340+140+480")  # Используем geometry вместо setGeometry
  537.  add_buttons_keyboard(buttons, window) # это меняет клавиатуру до записи макросов
  538.  note = Toplevel(window)  # основа
  539.  note.title("Скрипт")# Заголовок блокнота
  540.  
  541.  notebook = ttk.Notebook(note)
  542.  notebook.grid(row=0, column=0, sticky="nsew")
  543.  
  544.  tab1 = ttk.Frame(notebook)
  545.  notebook.add(tab1, text="Окно редактора скрипта")
  546.  keyboard_script=dict_save.return_jnson()["keyboard_script"]
  547.  text_widget = Text(tab1, wrap='word') # Текстовый редактор
  548.  text_widget.grid(row=0, column=0, sticky="nsew")
  549.  note.protocol("WM_DELETE_WINDOW", lambda: kill_notebook(window, note, text_widget))# Если мы закрываем блокнот
  550.  if key in keys_active:# Если кнопку которую мы нажали уже имеет какую-то привязку
  551.   text_content =keyboard_script[current_app]["keys"][key]
  552.   text_widget.insert('end', text_content)
  553.  window.protocol("WM_DELETE_WINDOW", lambda: kill_keyboard(window, note, text_widget))
  554.  for button, key in buttons.items():# каждой клавише присваиваем свою функци.
  555.   button.configure(command=lambda k=key, t=text_widget: add_key_text(k, t))
  556.  
  557. def create_keyboard():# Функция создания клавиатуры.
  558.   res= dict_save.return_jnson()# Получение настроек.
  559.   current_app = dict_save.get_cur_app()  # Получаем текущую игру
  560.   if res.get("keyboard_script") is None:
  561.     res["keyboard_script"] = {}# если нет ключа для клавиатуры
  562.   if current_app not in res.get("keyboard_script", {}):  # Проверяем наличие ключа
  563.    res["keyboard_script"][current_app] = {}  # Если ключ отсутствует, создаем его] = {}  # Если ключ отсутствует, создаем его
  564.   key = dict_save.get_last_key_keyboard_script()
  565.   keys_active = list(res["keyboard_script"][current_app]["keys"].keys())  # Список кнопок из файла которые надо обозначить синим.
  566.   window, buttons = create_virtial_keyboard() # создаем окно с клавиатурой. Надо нажать 1 кнопку
  567.   window.title("Выбор клавиш")# на которой мы запишем макро
  568.   for button, key in buttons.items():  # Прикрепляем функцию record_marcross к каждой кнопке
  569.    button.configure(command=lambda k=key, w=window: record_marcross(k, w))  # при нажатии любой кнопка выходит новая клавиатура с редактором
  570.    if key !="" and key in keys_active:# какие кнопка уже назаченные.
  571.      style = ttk.Style() # Меняем цвет тех кнопок которые уже были назначены.
  572.      style.configure("Custom.TButton", background="blue", foreground="white")
  573.      button.configure(style="Custom.TButton")
  574.  
  575.   dict_save.save_jnson(res)
  576.   # print(res["keyboard_script"])
  577. def delete(dict_save, root):# Удалить профиль.
  578.  if dict_save.get_cur_app()=="C:/Windows/explorer.exe":# # получить id устройства.Если id устройство не выбрали.
  579.      messagebox.showinfo("Ошибка", "Вы выбрали профиль по умолчанию")
  580.      ok_button = Button(root, text="Ок")
  581.      return
  582.  else:
  583.    profile = dict_save.get_cur_app()# Текущая директория активной игры.
  584.    res = dict_save.return_jnson()   # print(profile)
  585.    list_paths=list(res["paths"].keys())
  586.    del_index=(list_paths.index(profile))
  587.    labels = dict_save.return_labels()
  588.    var_list = dict_save.return_var_list()
  589.    for i in range(len(labels)):
  590.      if i == del_index: # индекс какой нужно удалить
  591.       info = labels[i].place_info()
  592.       info2= checkbutton_list[i].place_info()
  593.       old_y = int(info["y"])
  594.  
  595.       old_y2 = int(info2["y"])
  596.      if i > del_index:# индекс больше удалённого
  597.        info = labels[i].place_info()
  598.        new_y = int(info["y"])
  599.        labels[i].place(x=labels[i].winfo_x(), y=old_y)
  600.        old_y=new_y
  601.  
  602.        info2 = checkbutton_list[i].place_info()
  603.        new_y2 = int(info2["y"])
  604.        checkbutton_list[i].place(x=checkbutton_list[i].winfo_x(), y=old_y2)
  605.        old_y2 = new_y2
  606.  
  607.    labels.pop()
  608.    checkbutton_list.pop()
  609.    remove_profile_keys(res, profile)
  610.    del_index= del_index-1
  611.    dict_save.save_jnson(res)  # Сохранить новые настройки.
  612.    check_label_changed(0, labels, del_index, var_list)  # изменение цвета label
  613.    #current_app   # print(dict_save.return_jnson())
  614.  
  615. def reorder_keys_in_dict(res, index, direction='up'):
  616.   lst = list(res["paths"].keys())
  617.   if direction == 'up' and 0 < index < len(lst):
  618.     lst[index], lst[index - 1] = lst[index - 1], lst[index]
  619.   elif direction == 'down' and 0 <= index < len(lst) - 1:
  620.     lst[index], lst[index + 1] = lst[index + 1], lst[index]
  621.   else:
  622.     return res
  623.   updated_paths = {key: res["paths"][key] for key in lst}
  624.   res["paths"] = updated_paths
  625.   return res
  626. def move_element(dict_save, root, direction='up'):  # Перемещает текущий элемент (определяемый dict_save.get_cur_app())
  627.   # вверх или вниз в списке, меняя положение виджетов и порядок ключей в JSON.
  628.   # :param dict_save: Объект для работы с настройками (с методами get_cur_app, return_jnson, return_labels, set_cur_app, save_jnson)
  629.   # :param root: Корневой виджет Tkinter (используется, если требуется)
  630.   # :param direction: 'up' для перемещения вверх, 'down' для перемещения вниз
  631.   # Получаем текущий профиль и конфигурацию
  632.   res = dict_save.return_jnson()
  633.   profile = dict_save.get_cur_app()  # Текущая директория/приложение
  634.   list_paths = list(res["paths"].keys())
  635.  
  636.   try:
  637.     index = list_paths.index(profile)
  638.   except ValueError:
  639.     # Если профиль не найден, выходим
  640.     return
  641.   labels = dict_save.return_labels()
  642.  
  643.   # Проверяем границы для перемещения
  644.   if direction == 'up':
  645.     if index == 0:
  646.       return  # Нельзя двигать вверх первый элемент
  647.     new_index = index - 1
  648.   elif direction == 'down':
  649.     if index == len(labels) - 1:
  650.       return  # Нельзя двигать вниз последний элемент
  651.     new_index = index + 1
  652.   else:
  653.     raise ValueError("direction должен быть 'up' или 'down'")
  654.   # Получаем текущие позиции элементов (предполагается, что используется .place())
  655.   info_current = labels[index].place_info()
  656.   info_neighbor = labels[new_index].place_info()
  657.   y_current = int(info_current.get("y", 0))
  658.   y_neighbor = int(info_neighbor.get("y", 0))
  659.   # Меняем местами y-координаты для labels
  660.   labels[index].place(x=labels[index].winfo_x(), y=y_neighbor)
  661.   labels[new_index].place(x=labels[new_index].winfo_x(), y=y_current)
  662.  
  663.   # Меняем порядок элементов в списке labels
  664.   element = labels.pop(index)
  665.   labels.insert(new_index, element)
  666.  
  667.  
  668.   info_current = checkbutton_list[index].place_info()
  669.   info_neighbor = checkbutton_list[new_index].place_info()
  670.   y_current = int(info_current.get("y", 0))
  671.   y_neighbor = int(info_neighbor.get("y", 0))
  672.   # Меняем местами y-координаты для labels
  673.   checkbutton_list[index].place(x=checkbutton_list[index].winfo_x(), y=y_neighbor)
  674.   checkbutton_list[new_index].place(x=checkbutton_list[new_index].winfo_x(), y=y_current)
  675.  
  676.   # Меняем порядок элементов в списке labels
  677.   element = checkbutton_list.pop(index)
  678.   checkbutton_list.insert(new_index, element)
  679.   res =reorder_keys_in_dict(res, index, direction)  # Меняем порядок в списке
  680.   # Обновляем текущий профиль в соответствии с новым порядком
  681.  
  682.   list_paths = list(res["paths"].keys())
  683.   dict_save.set_cur_app(list_paths[new_index])
  684.   # Обновляем цвета: сначала сбрасываем, затем выделяем перемещённый элемент
  685.   set_colol_white_label_changed(labels)
  686.   labels[new_index].config(background="#06c")
  687.   dict_save.save_jnson(res)
  688.  
  689. dict_save=save_dict()
  690. root = Tk()
  691. id_value =  IntVar()
  692. f1 = Frame()
  693. root.title("Mouse setting control for buttons python")  # заголовок
  694. root.geometry("940x346+440+280")  # Первые 2 определяют ширину высоту. Пос 2 x и y координаты на экране.
  695. root.configure(bg='DimGray')  # Цвет фона окна
  696. root.resizable(width=False, height=False)
  697. f1.grid(column=0, row=0, padx=10, pady=10)
  698. container = Frame(root)
  699. canvas = Canvas(container,width=700, height=480)
  700. canvas.create_window((0, 0), window=f1, anchor="n")
  701. container.grid()
  702. canvas.grid(sticky=N+W)
  703. scrollbar = Scrollbar(container, orient="vertical", command=canvas.yview)
  704. scrollable_frame = Frame(canvas)
  705. scrollable_frame.bind( "<Configure>",  lambda e: canvas.configure( scrollregion=canvas.bbox("all")    ))
  706. canvas.configure(yscrollcommand=scrollbar.set)
  707. scrollbar.grid(column=0, row=0,sticky=N+S+E)# полоса прокрутки.
  708. scrollbar.bind("<ButtonRelease-1>", lambda event : scrolling_list(event))
  709. add_button_add = Button(text=" Добавить", command= lambda:add_file(dict_save)).grid(column=1, row=0, padx=25, pady=5,sticky=N)
  710. up_button = Button(text=" Вверх",  command= lambda:move_element(dict_save, root, 'up'))
  711. up_button.place(x=520, y=250)
  712. down_button = Button(text=" Вниз",  command= lambda:move_element(dict_save, root, 'down'))
  713. down_button.place(x=520, y=300)
  714. id_list =dict_save.get_list_ids()
  715. add_button_start = Button(text=" Удалить",  command= lambda:delete(dict_save, root))
  716. add_button_start.place(x=770, y=120)
  717. add_button_create_keyboard = Button(text="Клавиатура",  command= lambda:create_keyboard())# Создаем  клавиатуру
  718. add_button_create_keyboard.place(x=760, y=200)
  719. root.protocol("WM_DELETE_WINDOW", on_close)
  720. Button(root, text="Показать список устройств", command=show_list_id_callback).place(x=710, y=280)
  721. start(root, dict_save) # Запуск всего
  722. if os.getgid() != 0:# if os.getgid() == 0:# start1() с root правами"
  723.  box = Combobox(root, width=12, textvariable=id_value, values=id_list, state='readonly')  #
  724.  box.grid(column=1, row=0, padx=10, pady=60,sticky=N)
  725.  box.bind('<<ComboboxSelected>>', update_buttons)# Если изменяется значения id.
  726.  CreateToolTip(box, text='Выбор id устройства')  # вывод надписи
  727.  root.iconify()  # Свернуть окно
  728.   # root.withdraw()# свернуть панель подсказок.
  729. create_keyboard()
  730. root.mainloop()
  731. main_window_id = root.winfo_id()# Get the ID of the main window
  732.  
  733.  
  734.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement