From 992372a19b7bce4ae112821187cdbe3e31af7d97 Mon Sep 17 00:00:00 2001 From: YuriXbr Date: Tue, 30 Apr 2024 14:26:26 -0300 Subject: [PATCH] commit --- LeagueClicker.code-workspace | 11 ++ configExample.json | 4 + index.js | 184 ++++-------------- package-lock.json | 4 +- package.json | 2 +- src/locales/en-US.json | 32 +++ src/locales/es-ES.json | 32 +++ src/locales/pt-BR.json | 33 ++++ src/locales/ru-RU.json | 32 +++ src/modals/defaultConfig.js | 4 +- src/pages/configPage/index.html | 37 ---- src/pages/configPage/index.js | 0 src/pages/configPage/styles.css | 107 ---------- src/pages/settings/index.html | 42 ++++ src/pages/settings/index.js | 30 +++ .../{configPage => settings}/keyRegister.js | 44 ++--- src/pages/settings/styles.css | 89 +++++++++ src/utils/configManager.js | 60 ++++++ src/utils/keyManager.js | 61 ++++++ src/utils/trayManager.js | 91 +++++++++ src/utils/windowManager.js | 64 ++++++ 21 files changed, 641 insertions(+), 322 deletions(-) create mode 100644 LeagueClicker.code-workspace create mode 100644 src/locales/en-US.json create mode 100644 src/locales/es-ES.json create mode 100644 src/locales/pt-BR.json create mode 100644 src/locales/ru-RU.json delete mode 100644 src/pages/configPage/index.js create mode 100644 src/pages/settings/index.html create mode 100644 src/pages/settings/index.js rename src/pages/{configPage => settings}/keyRegister.js (90%) create mode 100644 src/pages/settings/styles.css create mode 100644 src/utils/configManager.js create mode 100644 src/utils/keyManager.js create mode 100644 src/utils/trayManager.js create mode 100644 src/utils/windowManager.js diff --git a/LeagueClicker.code-workspace b/LeagueClicker.code-workspace new file mode 100644 index 0000000..a13bded --- /dev/null +++ b/LeagueClicker.code-workspace @@ -0,0 +1,11 @@ +{ + "folders": [ + { + "path": "." + }, + { + "path": "../../../../../../LeagueClicker" + } + ], + "settings": {} +} \ No newline at end of file diff --git a/configExample.json b/configExample.json index 18ad477..073df78 100644 --- a/configExample.json +++ b/configExample.json @@ -1,4 +1,8 @@ { + "__DevComments": { + "textENUS": "Use this file to change the AutoClicker configurations, tutorial: https://github.com/YuriXbr/LeagueClicker/", + "textPTBR": "Utilize esse arquivo para configurar o autoclicker, tutorial: https://github.com/YuriXbr/LeagueClicker/" + }, "keybinds": { "RecordMousePosition": "CommandOrControl+R", "ShowPositions": "CommandOrControl+F11", diff --git a/index.js b/index.js index bd62dff..1d0dbac 100644 --- a/index.js +++ b/index.js @@ -1,21 +1,28 @@ const { app, Menu, Tray, globalShortcut, dialog } = require('electron'); +const { ipcMain, ipcRenderer } = require('electron'); +if (require('electron-squirrel-startup')) app.quit(); + const { mouse } = require("@nut-tree/nut-js"); const fs = require('fs'); const path = require('path'); -if (require('electron-squirrel-startup')) app.quit(); -let tray = null; -let pauseMacro = true; -let pauseReading = true; -let recordedPositions = new Array(50).fill(null).map(() => new Array(2)); // Inicializa o array bidimensional -let recordedindex = 0; +const localeManager = require('./src/utils/localeManager.js'); +const configManager = require('./src/utils/configManager.js'); +const keyManager = require('./src/utils/keyManager.js'); +const mouseManager = require('./src/utils/mouseManager.js'); +const windowManager = require('./src/utils/windowManager.js'); +const cache = require('./src/configs/cache.js') -const configFolderPath = 'C:/LeagueClicker/'; -const configPath = path.join(configFolderPath, 'config.json'); +app.on('ready', () => { + setup(); + loop(); +}); -function setup() { - setupKeybinds(); - createTrayIcon(); +async function setup() { + await configManager.setupConfig(); + localeManager.setupLocales(); + await keyManager.setupKeybinds(); + require('./src/utils/trayManager.js').createTrayIcon(); } function loop() { @@ -27,141 +34,6 @@ function loop() { } -async function executeMacro() { - for (const position in config.clickPositions) { - if (pauseMacro) { - console.log('Macro paused'); - return; - } - - if (config.clickPositions.hasOwnProperty(position)) { - const { x, y, button } = config.clickPositions[position]; - if (x !== null && y !== null) { - console.log(`Moving mouse to position: (${x}, ${y})`); - await mouse.move({ x, y }); - console.log(`Clicking at position: (${x}, ${y}) with button ${button}`); - await mouse.click(button); - await delay(config.config.MacroSleepTime); // Espera o tempo especificado entre os cliques - } - } - } - - if(!pauseMacro) return executeMacro(); -} - -function delay(ms) { - return new Promise(resolve => setTimeout(resolve, ms)); -} - -let config = require('./src/modals/defaultConfig').defaultconfig; - -function setupKeybinds() { - // Verifica se o diretório de configuração existe, se não, cria - if (!fs.existsSync(configFolderPath)) { - fs.mkdirSync(configFolderPath); - } - - // Verifica se o arquivo de configurações existe - if (fs.existsSync(configPath)) { - // Se existe, lê o arquivo e atualiza as configurações - const configFile = fs.readFileSync(configPath, 'utf-8'); - config = JSON.parse(configFile); - } else { - // Se não existe, cria o arquivo com as configurações padrão - fs.writeFileSync(configPath, JSON.stringify(config, null, 4), 'utf-8'); - } - - // Definindo os atalhos de teclado - globalShortcut.register(config.keybinds.RecordMousePosition, () => { - showMousePositionDialog(); - console.log('RecordMousePosition shortcut triggered'); - }); - - globalShortcut.register(config.keybinds.ShowPositions, () => { - // TODO Lógica para mostrar posições - console.log('ShowPositions shortcut triggered'); - }); - - globalShortcut.register(config.keybinds.PauseResumeMacro, () => { - // Lógica para pausar/resumir macro - pauseMacro = !pauseMacro; - if(!pauseMacro) { - executeMacro(); - } - console.log(" " + (pauseMacro ? "pausado" : "despausado") + "\n\n"); - console.log('PauseResumeMacro shortcut triggered'); - }); - - globalShortcut.register(config.keybinds.PauseResumeMouseReading, () => { - pauseReading = !pauseReading; - console.log(" " + (pauseReading ? "pausado" : "despausado") + "\n\n"); - }); - - globalShortcut.register(config.keybinds.Exit, () => { - quit(); - }); -} - -function createTrayIcon() { - tray = new Tray(path.join(__dirname, "src", "assets", "app.ico")); - - const contextMenu = Menu.buildFromTemplate([ - { label: `TECLAS DE ATALHO:`, type: 'normal' }, - { type: 'separator' }, - { label: `RecordMousePosition: ${config.keybinds.RecordMousePosition}`, type: 'normal' }, - { label: `ShowPositions: ${config.keybinds.ShowPositions}`, type: 'normal' }, - { label: `PauseResumeMacro: ${config.keybinds.PauseResumeMacro}`, type: 'normal' }, - { label: `PauseResumeMouseReading: ${config.keybinds.PauseResumeMouseReading}`, type: 'normal' }, - { label: `Exit: ${config.keybinds.Exit}`, type: 'normal' }, - { type: 'separator' }, - { label: 'PreviewClicks', type: 'submenu', submenu: [ - { label: `IniciarFila X ${config.clickPositions.IniciarFila.x} : Y ${config.clickPositions.IniciarFila.y}`, type: 'normal', }, - { label: `AceitarPartida X ${config.clickPositions.AceitarPartida.x} : Y ${config.clickPositions.AceitarPartida.y}`, type: 'normal', }, - { label: `FecharErro1 X ${config.clickPositions.FecharErro1.x} : Y ${config.clickPositions.FecharErro1.y}`, type: 'normal', }, - { label: `FecharErro2 X ${config.clickPositions.FecharErro2.x} : Y ${config.clickPositions.FecharErro2.y}`, type: 'normal', }, - { label: `ComprarLoja1 X ${config.clickPositions.ComprarLoja1.x} : Y ${config.clickPositions.ComprarLoja1.y}`, type: 'normal', }, - { label: `ComprarLoja2 X ${config.clickPositions.ComprarLoja2.x} : Y ${config.clickPositions.ComprarLoja2.y}`, type: 'normal', }, - { label: `AndarParaCentro X ${config.clickPositions.AndarParaCentro.x} : Y ${config.clickPositions.AndarParaCentro.y}`, type: 'normal', }, - { label: `SairDaPartida X ${config.clickPositions.SairDaPartida.x} : Y ${config.clickPositions.SairDaPartida.y}`, type: 'normal', }, - { label: `JogarNovamente X ${config.clickPositions.JogarNovamente.x} : Y ${config.clickPositions.JogarNovamente.y}`, type: 'normal', } - ] }, - { label: 'Update KeyBinds', type: 'normal', click: () => { setupKeybinds(); } }, - { type: 'separator' }, - { label: 'Quit', type: 'normal', click: () => { quit(); } } - ]); - tray.setToolTip('Macro'); - tray.setContextMenu(contextMenu); -} - -async function getMousePosition(print) { - const pos = await mouse.getPosition(); - if (print) { - console.log(pos); - } - return pos; -} - -function showMousePositionDialog() { - getMousePosition(true).then((pos) => { - saveCachePosition(pos.x, pos.y); - - const message = `A posição do mouse é: ${pos.x}, ${pos.y}`; - dialog.showMessageBox(null, { - type: 'info', - title: 'Posição do Mouse', - message: message, - buttons: ['FECHAR'] - }); - }).catch((error) => { - console.error('Erro ao obter a posição do mouse:', error); - }); -} - -function saveCachePosition(x, y) { - recordedPositions[recordedindex][0] = x; - recordedPositions[recordedindex][1] = y; - recordedindex++; -} async function quit() { if(recordedPositions[0][0] == undefined) return app.quit(); @@ -185,15 +57,25 @@ async function quit() { app.quit(); } -app.on('ready', () => { - setup(); - loop(); -}); - app.on('before-quit', (event) => { + require('./src/utils/trayManager.js').closeTray(); console.log("\n\n\nRecorded Positions:\n"); recordedPositions.forEach((pos, index) => { if(pos[0] != undefined) console.log(`index: ${index} ; X: ${pos[0]} Y: ${pos[1]}`); }); + windowManager.closeAllWindows(); }); + +ipcMain.on('request-config', (event) => { + const keybinds = configManager.getConfig().keybinds; + console.log("enviando", {keybinds}) + event.reply('config-response', {keybinds}); + }); + +ipcMain.on('update-keybinds', (event, newKeybinds) => { + console.log({newKeybinds}); + configManager.updateToFile('keybinds', newKeybinds); + setup(); + +}) diff --git a/package-lock.json b/package-lock.json index b7fa2c3..e35f932 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "LeagueClicker", - "version": "1.0.0", + "version": "1.2.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "LeagueClicker", - "version": "1.0.0", + "version": "1.2.0", "license": "ISC", "dependencies": { "@nut-tree/nut-js": "^3.1.2", diff --git a/package.json b/package.json index 78a696c..a827c7d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "LeagueClicker", - "version": "1.0.0", + "version": "1.2.0", "description": "League Auto Clicker", "main": "index.js", "scripts": { diff --git a/src/locales/en-US.json b/src/locales/en-US.json new file mode 100644 index 0000000..a6185fb --- /dev/null +++ b/src/locales/en-US.json @@ -0,0 +1,32 @@ +{ + "code": "en-US", + "tray": { + "header": "KEYBINDS:", + "recordMousePosition": "Record Mouse Position:", + "showPositions": "Show Positions", + "pauseResumeMacro": "Pause/Resume Macro:", + "pauseResumeMouseReading": "Pause/Resume Mouse Reading:", + "exit": "Exit:", + + "previewClicks": "Preview Clicks", + "startQueue": "Start Queue:", + "acceptMatch": "Accept Match:", + "closeError1": "Close Error (1):", + "closeError2": "Close Error (2):", + "buyChampion1": "Buy Champion (1):", + "buyChampion2": "Buy Champion (2):", + "buyChampion3": "Buy Champion (3):", + "buyChampion4": "Buy Champion (4):", + "buyChampion5": "Buy Champion (5):", + "walkToCenter": "Walk to Center:", + "selectCard": "Select Card:", + "quitMatch": "Quit Match:", + "playAgain": "Play Again:", + "extra1": "Extra Position (1):", + "extra2": "Extra Position (2):", + "extra3": "Extra Position (3):", + + "updateKeybinds": "Update Keybinds", + "quit": "Quit" + } +} diff --git a/src/locales/es-ES.json b/src/locales/es-ES.json new file mode 100644 index 0000000..dadc6c2 --- /dev/null +++ b/src/locales/es-ES.json @@ -0,0 +1,32 @@ +{ + "code": "es-ES", + "tray": { + "header": "ATAJOS DE TECLADO:", + "recordMousePosition": "Grabar posición del ratón:", + "showPositions": "Mostrar posiciones", + "pauseResumeMacro": "Pausar/Reanudar Macro:", + "pauseResumeMouseReading": "Pausar/Reanudar Lectura del Ratón:", + "exit": "Salir:", + + "previewClicks": "Previsualizar Clicks", + "startQueue": "Iniciar Cola:", + "acceptMatch": "Aceptar Partida:", + "closeError1": "Cerrar Error (1):", + "closeError2": "Cerrar Error (2):", + "buyChampion1": "Comprar Campeón (1):", + "buyChampion2": "Comprar Campeón (2):", + "buyChampion3": "Comprar Campeón (3):", + "buyChampion4": "Comprar Campeón (4):", + "buyChampion5": "Comprar Campeón (5):", + "walkToCenter": "Caminar al Centro:", + "selectCard": "Seleccionar Carta:", + "quitMatch": "Salir de la Partida:", + "playAgain": "Jugar de Nuevo:", + "extra1": "Posición Extra (1):", + "extra2": "Posición Extra (2):", + "extra3": "Posición Extra (3):", + + "updateKeybinds": "Actualizar Atajos", + "quit": "Salir" + } +} diff --git a/src/locales/pt-BR.json b/src/locales/pt-BR.json new file mode 100644 index 0000000..194c65f --- /dev/null +++ b/src/locales/pt-BR.json @@ -0,0 +1,33 @@ +{ + "code": "pt-BR" , + "tray": { + "header": "TECLAS DE ATALHO:", + "recordMousePosition": "Gravar posição do mouse", + "showPositions": "Mostrar posições", + "pauseResumeMacro": "Pausar/Resumir Macro", + "pauseResumeMouseReading": "Pausar/Resumir Leitura do mouse", + "exit": "Sair", + + "previewClicks": "Testar Cliques", + "startQueue": "Iniciar Fila:", + "acceptMatch": "Aceitar Partida:", + "closeError1": "Fechar Erro (1):", + "closeError2": "Fechar Erro (2):", + "buyChampion1": "Comprar Campeão (1):", + "buyChampion2": "Comprar Campeão (2):", + "buyChampion3": "Comprar Campeão (3):", + "buyChampion4": "Comprar Campeão (4):", + "buyChampion5": "Comprar Campeão (5):", + "walkToCenter": "Andar Para o Centro:", + "selectCard": "Selecionar Carta:", + "quitMatch": "sair da Partida:", + "playAgain": "Jogar Novamente:", + "extra1": "Posição Extra (1):", + "extra2": "Posição Extra (2):", + "extra3": "Posição Extra (3):", + + "updateKeybinds": "Atualizar atalhos", + "quit": "Sair" + } + +} \ No newline at end of file diff --git a/src/locales/ru-RU.json b/src/locales/ru-RU.json new file mode 100644 index 0000000..35a2a9c --- /dev/null +++ b/src/locales/ru-RU.json @@ -0,0 +1,32 @@ +{ + "code": "ru-RU", + "tray": { + "header": "ГОРЯЧИЕ КЛАВИШИ:", + "recordMousePosition": "Записать положение мыши:", + "showPositions": "Показать позиции", + "pauseResumeMacro": "Приостановить/Возобновить макрос:", + "pauseResumeMouseReading": "Приостановить/Возобновить чтение мыши:", + "exit": "Выйти:", + + "previewClicks": "Предварительный просмотр кликов", + "startQueue": "Начать очередь:", + "acceptMatch": "Принять матч:", + "closeError1": "Закрыть ошибку (1):", + "closeError2": "Закрыть ошибку (2):", + "buyChampion1": "Купить чемпиона (1):", + "buyChampion2": "Купить чемпиона (2):", + "buyChampion3": "Купить чемпиона (3):", + "buyChampion4": "Купить чемпиона (4):", + "buyChampion5": "Купить чемпиона (5):", + "walkToCenter": "Идти в центр:", + "selectCard": "Выбрать карту:", + "quitMatch": "Выйти из матча:", + "playAgain": "Играть снова:", + "extra1": "Дополнительное положение (1):", + "extra2": "Дополнительное положение (2):", + "extra3": "Дополнительное положение (3):", + + "updateKeybinds": "Обновить горячие клавиши", + "quit": "Выйти" + } +} diff --git a/src/modals/defaultConfig.js b/src/modals/defaultConfig.js index 76213ce..da65c34 100644 --- a/src/modals/defaultConfig.js +++ b/src/modals/defaultConfig.js @@ -1,7 +1,7 @@ defaultconfig = { __DevComments: { - textEN: "Use this file to change the AutoClicker configurations, tutorial: https://github.com/YuriXbr/LeagueClicker/blob/BETA-1.0.0/README.md", - textPTBR: "Utilize esse arquivo para configurar o autoclicker, tutorial: https://github.com/YuriXbr/LeagueClicker/blob/BETA-1.0.0/README.md" + textENUS: "Use this file to change the AutoClicker configurations, tutorial: https://github.com/YuriXbr/LeagueClicker/", + textPTBR: "Utilize esse arquivo para configurar o autoclicker, tutorial: https://github.com/YuriXbr/LeagueClicker/" }, keybinds: { RecordMousePosition: 'CommandOrControl+R', diff --git a/src/pages/configPage/index.html b/src/pages/configPage/index.html index 2aab06e..e69de29 100644 --- a/src/pages/configPage/index.html +++ b/src/pages/configPage/index.html @@ -1,37 +0,0 @@ - - - - - - - - Configuration - - -

CONFIG:

-
-
  • - Record Position: - - - Show Positions: - - - Pause/Resume Macro: - - - Pause/Resume MouseReading: - - - Exit: - - -
  • -
    -
    - -
    - - - - \ No newline at end of file diff --git a/src/pages/configPage/index.js b/src/pages/configPage/index.js deleted file mode 100644 index e69de29..0000000 diff --git a/src/pages/configPage/styles.css b/src/pages/configPage/styles.css index d883146..e69de29 100644 --- a/src/pages/configPage/styles.css +++ b/src/pages/configPage/styles.css @@ -1,107 +0,0 @@ -* { - font-family: arial; - text-decoration: none; - - } - - body { - background-color: #181818; - } - - .title { - text-align: center; - color: white; - } - - a { - display: flex; - flex-direction: row; - align-items: center; - padding-top: 10px; - } - - .inputs { - display: flex; - flex-direction: column; /* Alterado para coluna */ - align-items: flex-start; /* Adicionado */ - text-align: center; /* Alterado para direita */ - background-color: #181818; - color: white; - overflow: hidden; - padding-top: 5px; - } - - a { - justify-content: flex-end; /* Adicionado */ - } - - li { - list-style-type: none; - text-align: center; - padding-right: 10px; - } - - .input-section { - color: cyan; - width: 70px; - height: 30px; - border: hidden; - border-radius: 5px; - background-color: #22303C; - } - - .input-section::placeholder { - padding-left: 5px - } - - /* CSS */ - .buttons { - appearance: none; - background-color: #2ea44f; - border: 1px solid rgba(27, 31, 35, .15); - border-radius: 6px; - box-shadow: rgba(27, 31, 35, .1) 0 1px 0; - box-sizing: border-box; - color: #fff; - cursor: pointer; - display: inline-block; - font-family: -apple-system,system-ui,"Segoe UI",Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji"; - font-size: 14px; - font-weight: 600; - line-height: 20px; - padding: 6px 16px; - position: relative; - text-align: center; - text-decoration: none; - user-select: none; - -webkit-user-select: none; - touch-action: manipulation; - vertical-align: middle; - white-space: nowrap; - } - - .buttons:focus:not(:focus-visible):not(.focus-visible) { - box-shadow: none; - outline: none; - } - - .buttons:hover { - background-color: #2c974b; - } - - .buttons:focus { - box-shadow: rgba(46, 164, 79, .4) 0 0 0 3px; - outline: none; - } - - .buttons:disabled { - background-color: #94d3a2; - border-color: rgba(27, 31, 35, .1); - color: rgba(255, 255, 255, .8); - cursor: default; - } - - .buttons:active { - background-color: #298e46; - box-shadow: rgba(20, 70, 32, .2) 0 1px 0 inset; - } \ No newline at end of file diff --git a/src/pages/settings/index.html b/src/pages/settings/index.html new file mode 100644 index 0000000..03b5d89 --- /dev/null +++ b/src/pages/settings/index.html @@ -0,0 +1,42 @@ + + + + + + + + Settings + + +

    Settings

    +
    + +
    +
    + +
    + + + + diff --git a/src/pages/settings/index.js b/src/pages/settings/index.js new file mode 100644 index 0000000..025b211 --- /dev/null +++ b/src/pages/settings/index.js @@ -0,0 +1,30 @@ +const { ipcRenderer } = require("electron"); + +window.addEventListener('DOMContentLoaded', () => { + // Enviar mensagem IPC para o processo principal + ipcRenderer.send('request-config'); +}); + +ipcRenderer.on('config-response', (event, keybinds) => { + // Atualizar os valores dos campos de entrada com os keybinds recebidos + console.log({keybinds}) + document.querySelectorAll('.input-section').forEach((input) => { + const fieldName = input.id; + input.value = keybinds.keybinds[fieldName] || ''; // Definir valor padrão se não houver keybind para o campo + }); +}); + +document.querySelector('.save-button').addEventListener('click', () => { + // Criar um objeto com as novas teclas a partir dos valores dos campos de entrada + const keybinds = { + recordMousePosition: document.getElementById('recordMousePosition').value, + showPositions: document.getElementById('showPositions').value, + pauseResumeMacro: document.getElementById('pauseResumeMacro').value, + pauseResumeMouseReading: document.getElementById('pauseResumeMouseReading').value, + exit: document.getElementById('exit').value + }; + + ipcRenderer.send('update-keybinds', keybinds); + window.close(); + + }); \ No newline at end of file diff --git a/src/pages/configPage/keyRegister.js b/src/pages/settings/keyRegister.js similarity index 90% rename from src/pages/configPage/keyRegister.js rename to src/pages/settings/keyRegister.js index 171588c..cc5a267 100644 --- a/src/pages/configPage/keyRegister.js +++ b/src/pages/settings/keyRegister.js @@ -1,23 +1,23 @@ -document.querySelectorAll('.input-section').forEach(function(input) { - input.addEventListener('keydown', function(event) { - const keyCombination = []; - - if (event.ctrlKey) { - keyCombination.push('Ctrl'); - } - if (event.altKey) { - keyCombination.push('Alt'); - } - if (event.shiftKey) { - keyCombination.push('Shift'); - } - - const key = event.key.toUpperCase(); - if (!['CONTROL', 'ALT', 'SHIFT'].includes(key)) { - keyCombination.push(key); - } - - this.value = keyCombination.join('+'); - event.preventDefault(); - }); +document.querySelectorAll('.input-section').forEach(function(input) { + input.addEventListener('keydown', function(event) { + const keyCombination = []; + + if (event.ctrlKey) { + keyCombination.push('CommandOrControl'); + } + if (event.altKey) { + keyCombination.push('Alt'); + } + if (event.shiftKey) { + keyCombination.push('Shift'); + } + + const key = event.key.toUpperCase(); + if (!['CONTROL', 'ALT', 'SHIFT'].includes(key)) { + keyCombination.push(key); + } + + this.value = keyCombination.join('+'); + event.preventDefault(); + }); }); \ No newline at end of file diff --git a/src/pages/settings/styles.css b/src/pages/settings/styles.css new file mode 100644 index 0000000..207bc69 --- /dev/null +++ b/src/pages/settings/styles.css @@ -0,0 +1,89 @@ +* { + font-family: Arial, sans-serif; + text-decoration: none; +} + +body { + background-color: #181818; +} + +li { + padding-top: 10px; +} + +.title { + text-align: center; + color: white; + margin-top: 20px; +} + +.inputs { + margin-top: 20px; + padding: 0; + list-style: none; +} + +.keytext { + color: white; + width: 200px; + display: inline-block; +} + +.input-section { + color: cyan; + width: 200px; /* Aumentar a largura do campo de entrada */ + min-width: 200px; /* Definir uma largura mínima */ + height: 30px; + border: hidden; + border-radius: 5px; + background-color: #22303C; + white-space: nowrap; /* Evitar quebras de linha */ + overflow: hidden; /* Ocultar o conteúdo que ultrapassa o limite */ + text-overflow: ellipsis; /* Exibir reticências (...) para indicar texto truncado */ +} + +.input-section::placeholder { + padding-left: 5px; +} + +.buttons { + text-align: center; + margin-top: 20px; +} + +.save-button { + appearance: none; + background-color: #2ea44f; + border: 1px solid rgba(27, 31, 35, .15); + border-radius: 6px; + box-shadow: rgba(27, 31, 35, .1) 0 1px 0; + color: #fff; + cursor: pointer; + font-size: 14px; + font-weight: 600; + line-height: 20px; + padding: 6px 16px; + text-align: center; + text-decoration: none; +} + +.save-button:hover { + background-color: #2c974b; +} + +.save-button:focus { + box-shadow: rgba(46, 164, 79, .4) 0 0 0 3px; + outline: none; +} + +.save-button:active { + background-color: #298e46; + box-shadow: rgba(20, 70, 32, .2) 0 1px 0 inset; +} + +.save-button:disabled { + background-color: #94d3a2; + border-color: rgba(27, 31, 35, .1); + color: rgba(255, 255, 255, .8); + cursor: default; +} diff --git a/src/utils/configManager.js b/src/utils/configManager.js new file mode 100644 index 0000000..e159fb7 --- /dev/null +++ b/src/utils/configManager.js @@ -0,0 +1,60 @@ +const fs = require('fs'); +const path = require('path') + +const configFolderPath = 'C:/LeagueClicker/'; +const configPath = path.join(configFolderPath, 'config.json'); +let config = require('../modals/defaultConfig').defaultconfig; + +function setupConfig(){ + // Verifica se o diretório de configuração existe, se não, cria + if (!fs.existsSync(configFolderPath)) { + fs.mkdirSync(configFolderPath); + } + + // Verifica se o arquivo de configurações existe + if (fs.existsSync(configPath)) { + // Se existe, lê o arquivo e atualiza as configurações + const configFile = fs.readFileSync(configPath, 'utf-8'); + console.log("[configManager > setupConfig]: Versao do arquivo de configuracoes:", config.fileVersion,); + console.log("[configManager > setupConfig]: Versao do arquivo default:", require(configPath).fileVersion) + if(config.fileVersion == require(configPath).fileVersion) { + config = JSON.parse(configFile); + console.log({config}) + return console.log("[configManager > setupConfig]: Configuracoes atualizadas."); + } else { + fs.writeFileSync(configPath, JSON.stringify(config, null, 4), 'utf-8'); + return console.log("[configManager > setupConfig]: Configuracoes desatualizadas, redefinindo."); + } + } else { + // Se não existe, cria o arquivo com as configurações padrão + fs.writeFileSync(configPath, JSON.stringify(config, null, 4), 'utf-8'); + return console.log("[configManager > setupConfig]: Configurações não encontradas, redefinindo."); + } +} + +function getConfig() { + config = require('c:/LeagueClicker/config.json'); + return config; +} + +async function updateToFile(local, parametros, value) { + config = getConfig(); + if (local === 'keybinds') { + config[local] = parametros; + } else { + if(value == null || value == undefined) return console.log("Valor invalido"); + config[local][parametros] = value; + } + + fs.writeFileSync(configPath, JSON.stringify(config, null, 4), 'utf-8'); +} + + +module.exports = { + setupConfig, + updateToFile, + config, + configPath, + configFolderPath, + getConfig +} \ No newline at end of file diff --git a/src/utils/keyManager.js b/src/utils/keyManager.js new file mode 100644 index 0000000..b7ab4fd --- /dev/null +++ b/src/utils/keyManager.js @@ -0,0 +1,61 @@ +const {globalShortcut} = require('electron'); +const cache = require('../configs/cache') +const click = require('./mouseManager'); +const dialogManager = require('./dialogManager'); +const configManager = require('./configManager'); + +function removeAllKeybinds() { + globalShortcut.unregisterAll(); + console.log("[KeyManager > removeAllKeybinds]: TODOS atalhos removidos.") +} + +function setupKeybinds() { + removeAllKeybinds(); + try{ + config = configManager.getConfig(); + keybinds = config.keybinds; + + globalShortcut.register(keybinds.recordMousePosition, () => { + dialogManager.showMousePositionDialog(); + console.log("[KeyManager > setupKeybinds]: ", 'RecordMousePosition shortcut triggered'); + }); + console.log("[KeyManager > setupKeybinds]: ", 'RecordMousePosition configurado em', keybinds.recordMousePosition); + + globalShortcut.register(keybinds.showPositions, () => { + // TODO Lógica para mostrar posições + console.log("[KeyManager > setupKeybinds]: ", 'ShowPositions shortcut triggered'); + }); + console.log("[KeyManager > setupKeybinds]: ", 'ShowPositions configurado em', keybinds.showPositions); + + globalShortcut.register(keybinds.pauseResumeMacro, () => { + // Lógica para pausar/resumir macro + cache.pauseMacro("toggle"); + if (!cache.pauseMacro()) { + click.executeMacro(); + } + console.log("[KeyManager > setupKeybinds]: ", 'PauseResumeMacro shortcut triggered'); + console.log("[KeyManager > setupKeybinds]: ", " " + (cache.pauseMacro() ? "pausado" : "despausado") + "\n\n"); + }); + console.log("[KeyManager > setupKeybinds]: ", 'PauseResumeMacro configurado em', keybinds.pauseResumeMacro); + + globalShortcut.register(keybinds.pauseResumeMouseReading, () => { + cache.pauseReading("toggle"); + console.log("[KeyManager > setupKeybinds]: ", 'PauseResumeMouseReading shortcut triggered'); + console.log("[KeyManager > setupKeybinds]: ", " " + (cache.pauseReading() ? "pausado" : "despausado") + "\n\n"); + }); + console.log("[KeyManager > setupKeybinds]: ", 'PauseResumeMouseReading configurado em', keybinds.pauseResumeMouseReading); + + globalShortcut.register(keybinds.exit, () => { + require('../../index').quit(); + console.log("[KeyManager > setupKeybinds]: ", 'Exit shortcut triggered'); + }); + console.log("[KeyManager > setupKeybinds]: ", 'Exit configurado em', keybinds.exit); + } catch(err) { + console.log(err); + } +} + +module.exports = { + setupKeybinds, + removeAllKeybinds, +} \ No newline at end of file diff --git a/src/utils/trayManager.js b/src/utils/trayManager.js new file mode 100644 index 0000000..3b98115 --- /dev/null +++ b/src/utils/trayManager.js @@ -0,0 +1,91 @@ +const {Menu, Tray} = require("electron"); +const fs = require('fs'); +const path = require('path'); +const main = require(path.join(__dirname, "../", "../", "index.js")); +const mouseManager = require('./mouseManager.js'); +const windowManager = require('./windowManager.js'); +const configManager = require('./configManager.js'); + +let tray; +let contextMenu; + +let config = configManager.getConfig(); + +const langFolder = path.join(__dirname, "../", "locales"); +let langPath = path.join(langFolder, `${config.config.language}.json`); +let lang = require(langPath); + +function getLocaleMenuItens() { + const availableLanguages = fs.readdirSync(langFolder); + const languageMenuItems = availableLanguages.map(languageFile => { + const languageCode = path.basename(languageFile, '.json'); + return { + label: languageCode, + type: 'normal', + click: () => { + config.config.language = languageCode; + fs.writeFileSync('c:/LeagueClicker/config.json', JSON.stringify(config, null, 4), 'utf-8'); + return createTrayIcon(); + } + }; + }); + return languageMenuItems; +} + +function getClickPositionsMenuItem(){ + config = require("c:/LeagueClicker/config.json") + const clickPositionsItems = Object.entries(config.clickPositions).map(([position, { x, y, button }]) => ({ + label: `${lang.tray[position]} X ${x} : Y ${y}`, + type: 'normal', + click: () => mouseManager.singleClick(x, y, button) + })); + return clickPositionsItems; +} + +function updateContextMenu() { + config = require("c:/LeagueClicker/config.json") + langPath = path.join(langFolder, `${config.config.language}.json`); + lang = require(langPath); + + contextMenu = Menu.buildFromTemplate([ + { label: lang.tray.header, type: 'normal' }, + { type: 'separator' }, + { label: `${lang.tray.recordMousePosition}: ${config.keybinds.recordMousePosition}`, type: 'normal' }, + { label: `${lang.tray.showPositions}: ${config.keybinds.showPositions}`, type: 'normal' }, + { label: `${lang.tray.pauseResumeMacro}: ${config.keybinds.pauseResumeMacro}`, type: 'normal' }, + { label: `${lang.tray.pauseResumeMouseReading}: ${config.keybinds.pauseResumeMouseReading}`, type: 'normal' }, + { label: `${lang.tray.exit}: ${config.keybinds.exit}`, type: 'normal' }, + { type: 'separator' }, + { label: lang.tray.previewClicks, type: 'submenu', submenu: getClickPositionsMenuItem() }, + { label: "Languages", type: 'submenu', submenu: getLocaleMenuItens() }, + { label: `Settings`, type: 'normal', click: () => { windowManager.invoke("settings") } }, + { type: 'separator' }, + { label: lang.tray.quit, type: 'normal', click: () => { main.quit(); } } + ]); + return contextMenu; +} + + + +function createTrayIcon() { + if (tray && !tray.isDestroyed()) { + console.log("[Tray.js > createTrayIcon] Tray ja existe, recriando") + tray.destroy(); + } + console.log("[Tray.js > createTrayIcon] Criando Tray") + + tray = new Tray(path.join(__dirname, "../", "assets", "app.ico")); + tray.setToolTip('Macro'); + tray.setContextMenu(updateContextMenu()); +} + +function closeTray() { + tray.destroy(); + return; +} + +module.exports = { + createTrayIcon, + updateContextMenu, + closeTray +} \ No newline at end of file diff --git a/src/utils/windowManager.js b/src/utils/windowManager.js new file mode 100644 index 0000000..0245d58 --- /dev/null +++ b/src/utils/windowManager.js @@ -0,0 +1,64 @@ +const { BrowserWindow } = require('electron'); +const path = require('path'); + +let settingsWindow; + +function createSettingsWindow() { + settingsWindow = new BrowserWindow({ + width: 500, + height: 500, + resizable: true, // Define a janela como não redimensionável + x: 0, // Define a posição inicial X da janela para o canto esquerdo + y: 0, // Define a posição inicial Y da janela para o topo + autoHideMenuBar: true, // Oculta a barra de menu + icon: '../assets/app.ico', + webPreferences: { + nodeIntegration: true, + contextIsolation: false, + enableRemoteModule: true, + webSecurity: false, + allowRunningInsecureContent: true, + scrollBounce: true, + } + }); + + settingsWindow.loadFile(path.join(__dirname, '../pages/settings/index.html')); + + // Abrir o DevTools se estiver em ambiente de desenvolvimento + if (process.env.NODE_ENV === 'development') { + settingsWindow.webContents.openDevTools(); + } + + // Manipulador de evento para ocultar a janela ao fechá-la + settingsWindow.on('close', (event) => { + event.preventDefault(); + try{ + settingsWindow.hide(); + } catch { + console.log("[windowManager > invoke]: Erro ao fechar a janela. de configurações."); + } + }); +} + +function invoke(page) { + if (page === 'settings') { + if (!settingsWindow) { + createSettingsWindow(); + } else { + settingsWindow.show(); + } + } +} + +function closeAllWindows() { + if (settingsWindow) { + settingsWindow.close(); + settingsWindow = null; + } + // Adicione mais janelas aqui, se necessário +} + +module.exports = { + invoke, + closeAllWindows +}; \ No newline at end of file