from __future__ import annotations import importlib.util import subprocess import sys PACKAGES = {'PIL': 'Pillow>=12.3.0,<13', 'brotli': 'brotli>=1.1,<2', 'certifi': 'certifi>=2026.5.20', 'customtkinter': 'customtkinter==6.0.0'} def install_missing_packages(): missing = [spec for name, spec in PACKAGES.items() if importlib.util.find_spec(name) is None] if not missing: return print('Installing the libraries the launcher needs: ' + ', '.join(missing), flush=True) if subprocess.run([sys.executable, '-m', 'pip', '--version'], capture_output=True).returncode != 0: subprocess.run([sys.executable, '-m', 'ensurepip', '--upgrade'], check=False) result = subprocess.run([sys.executable, '-m', 'pip', 'install', *missing]) import site if site.ENABLE_USER_SITE and site.getusersitepackages() not in sys.path: site.addsitedir(site.getusersitepackages()) importlib.invalidate_caches() still = [spec for name, spec in PACKAGES.items() if importlib.util.find_spec(name) is None] if result.returncode != 0 or still: raise SystemExit('Could not install: ' + ', '.join(still or missing) + '\nInstall them by hand with:\n python -m pip install ' + ' '.join(still or missing)) install_missing_packages() import logging import logging.handlers import os from pathlib import Path import platform import subprocess import sys import tempfile import threading import ctypes import json import locale import re import bz2 from functools import lru_cache import struct from urllib.parse import urlparse import brotli from collections.abc import Iterable from contextlib import contextmanager from datetime import datetime, timezone import hashlib from http.client import HTTPException import shutil import ssl from urllib.error import HTTPError, URLError from urllib.request import urlopen, Request import uuid import certifi from PIL import Image import tkinter as tk import time from PIL import Image, ImageOps, ImageTk import customtkinter as ctk from PIL import Image, ImageTk import math from PIL import Image, ImageDraw, ImageTk import argparse import queue from tkinter import filedialog PATCH_SOURCE = {'game_hosts': ['game.arinar.net'], 'newer_clients': 'newest', 'releases': [{'generation': '13.4', 'pak_version': 6, 'base_timestamp': '2026-06-04', 'url': 'https://patch.arinar.net/diffs/arinar-13.4-warspear.pak.1', 'sha256': '01becc775a95d5aceaea3f5d4bf5704fe13cf543a355e37513ef519af69512df', 'size': 11570, 'copy_manifest_url': 'https://patch.arinar.net/diffs/arinar-13.4-content.json'}, {'generation': '13.5', 'pak_version': 6, 'base_timestamp': '2026-09-30', 'url': 'https://patch.arinar.net/diffs/arinar-13.5-warspear.pak.1', 'sha256': '8146b55a856d17f8a479ea5f0ba8a9771e8d824ac69509c2d166d502c0ffdbf1', 'size': 11567, 'copy_manifest_url': 'https://patch.arinar.net/diffs/arinar-13.5-content.json'}, {'generation': '13.6', 'pak_version': 6, 'base_timestamp': '2026-10-22', 'url': 'https://patch.arinar.net/diffs/arinar-13.6-warspear.pak.1', 'sha256': 'ead5686fbc4082af1b9a132cef2a361bdf876fd3e3a49bfb75df9099702f27f8', 'size': 11567, 'copy_manifest_url': 'https://patch.arinar.net/diffs/arinar-13.6-content.json'}, {'generation': '13.6.1', 'pak_version': 6, 'base_timestamp': '2026-12-01', 'url': 'https://patch.arinar.net/diffs/arinar-13.6.1-warspear.pak.1', 'sha256': 'fa2be56083dcdd700dcc0932e27195ea5b0bbecd96570b708f7145473bdcad0d', 'size': 11567, 'copy_manifest_url': 'https://patch.arinar.net/diffs/arinar-13.6.1-content.json'}]} LOCALES = {'ru': {'Automatic': 'Автоматически', 'GAME LAUNCHER': 'ИГРОВОЙ ЛАУНЧЕР', 'Language': 'Язык', 'Choose your realm': 'Выберите сервер', 'Original server': 'Официальный сервер', 'Official Warspear servers': 'Официальные серверы Warspear', 'Arinar Reborn': 'Arinar Reborn', 'Independent community realm': 'Независимый сервер сообщества', 'Game folder': 'Папка игры', 'Change folder': 'Выбрать папку', 'Play': 'Играть', 'Play applies your selected server. Close the game before switching.': 'Сервер подключается при ' 'запуске. Закройте игру перед ' 'сменой сервера.', 'Looking for your installed game...': 'Поиск установленной игры...', 'Choose a game folder to get started.': 'Выберите папку игры для начала.', 'Game found. Ready to play.': 'Игра найдена. Можно играть.', 'Game not found. Choose its folder to continue.': 'Игра не найдена. Укажите её папку.', 'Folder selected. Ready to play.': 'Папка выбрана. Можно играть.', 'Choose your Warspear game folder': 'Выберите папку игры Warspear', 'Checking the client...': 'Проверка клиента...', 'Could not start the game': 'Не удалось запустить игру', 'Wait for the current operation to finish before closing.': 'Дождитесь завершения операции перед ' 'закрытием.', 'Game started for {server}.': 'Игра запущена: {server}.', 'Choose the game folder containing warspear.exe and warspear.pak.': 'Выберите папку с warspear.exe и ' 'warspear.pak.', 'Language changed for this session. Could not save preference.': 'Язык изменён для этого сеанса. Не ' 'удалось сохранить выбор.', 'Checking client and existing overlays...': 'Проверка клиента и установленных патчей...', 'Building connection-only overlay...': 'Создание патча подключения...', 'Arinar connection overlay installed. Original game files are unchanged.': 'Патч подключения Arinar ' 'установлен. Исходные ' 'файлы игры не изменены.', 'Original server is already selected.': 'Официальный сервер уже выбран.', 'Original routing restored. No Arinar overlay remains.': 'Исходное подключение восстановлено. Патч ' 'Arinar удалён.', 'Choose the installed Windows client folder containing warspear.pak.': 'Выберите папку ' 'установленного ' 'Windows-клиента с ' 'warspear.pak.', 'Client and managed patch files must not be links or junctions.': 'Клиент и файлы патча не должны ' 'быть ссылками или точками ' 'соединения.', 'Another routing overlay exists ({file}). Use a clean client / remove it with its owning tool first.': 'Найден ' 'другой ' 'патч ' 'подключения ' '({file}). ' 'Используйте ' 'чистый ' 'клиент ' 'или ' 'удалите ' 'патч ' 'создавшим ' 'его ' 'инструментом.', 'An unmanaged file occupies the patcher overlay name. Nothing was changed.': 'Имя патча занято ' 'неизвестным файлом. ' 'Ничего не изменено.', 'The base client changed since patching. Restore the original client version before switching.': 'Основной ' 'клиент ' 'изменился ' 'после ' 'установки ' 'патча. ' 'Перед ' 'сменой ' 'сервера ' 'восстановите ' 'исходную ' 'версию.', 'The managed overlay is missing or changed. Nothing was overwritten or removed.': 'Установленный ' 'патч отсутствует ' 'или изменён. ' 'Ничего не ' 'перезаписано и не ' 'удалено.', 'The patch manifest is invalid. Nothing was changed.': 'Файл учёта патча повреждён. Ничего не ' 'изменено.', 'This client has no supported connection configurations.': 'В клиенте нет поддерживаемых настроек ' 'подключения.', 'PAK format {version} is not supported by this prototype.': 'Формат PAK {version} не поддерживается ' 'этим прототипом.', 'The baseline already has custom routing. Select an unmodified official client copy.': 'Исходный ' 'клиент уже ' 'имеет ' 'изменённое ' 'подключение. ' 'Выберите ' 'неизменённую ' 'копию ' 'официального ' 'клиента.', 'Arinar is already applied. Switch to Original server before changing its endpoint.': 'Патч Arinar ' 'уже ' 'установлен. ' 'Перед сменой ' 'адреса ' 'переключитесь ' 'на ' 'официальный ' 'сервер.', 'Select a valid RSA PUBLIC key PEM for the Arinar master. Private keys are not accepted.': 'Нужен ' 'действительный ' 'ОТКРЫТЫЙ ' 'RSA-ключ ' 'PEM ' 'сервера ' 'Arinar. ' 'Закрытые ' 'ключи не ' 'принимаются.', 'This client has no supported login-key entry. Nothing was changed.': 'В клиенте нет поддерживаемого ' 'ключа входа. Ничего не ' 'изменено.', 'Overlay verification failed. Nothing was installed.': 'Проверка патча не пройдена. Ничего не ' 'установлено.', 'Overlay appeared during patching. Nothing was overwritten.': 'Во время установки появился другой ' 'патч. Ничего не перезаписано.', 'Enter a hostname or IP address, without a URL or path.': 'Введите имя узла или IP-адрес без URL и ' 'пути.', 'Port must be between 1 and 65535.': 'Порт должен быть от 1 до 65535.', 'This development prototype needs the sibling pak_explorer.py and wsserver tools.': 'Этому прототипу ' 'нужны соседний ' 'pak_explorer.py ' 'и инструменты ' 'wsserver.', 'Install requirements: python -m pip install -r arinar-patcher/requirements.txt': 'Установите ' 'зависимости: ' 'python -m pip ' 'install -r ' 'arinar-patcher/requirements.txt', 'Error': 'Ошибка', 'Attention': 'Внимание', 'Ready': 'Готово', 'Working': 'Выполняется', 'Information': 'Информация', 'Important': 'Важно', 'OK': 'ОК', 'The server patch download URL has not been configured yet.': 'Адрес загрузки серверного патча ещё ' 'не настроен.', 'The selected game client has an invalid base PAK.': 'Основной PAK выбранного клиента ' 'недействителен.', 'No server patch is available for this client version. Choose a supported client.': 'Для этой версии ' 'клиента нет ' 'серверного ' 'патча. Выберите ' 'поддерживаемую ' 'версию.', 'The server patch download configuration is invalid.': 'Настройки загрузки серверного патча ' 'недействительны.', 'The downloaded patch checksum does not match. Existing patches were not changed.': 'Контрольная ' 'сумма ' 'загруженного ' 'патча не ' 'совпадает. ' 'Установленные ' 'патчи не ' 'изменены.', 'The download is not a valid PAK patch. Existing patches were not changed.': 'Загруженный файл не ' 'является PAK-патчем. ' 'Установленные патчи не ' 'изменены.', 'The downloaded PAK format is not supported.': 'Формат загруженного PAK не поддерживается.', 'The downloaded patch is incomplete. Existing patches were not changed.': 'Загруженный патч ' 'повреждён или неполон. ' 'Установленные патчи не ' 'изменены.', 'The downloaded patch has no merge manifest. Existing patches were not changed.': 'В патче нет ' 'манифеста ' 'слияния. ' 'Установленные ' 'патчи не ' 'изменены.', 'Downloading the server patch...': 'Загрузка серверного патча...', 'The patch server returned an invalid download address.': 'Сервер вернул недействительный адрес ' 'загрузки.', 'The patch download size is invalid.': 'Размер загружаемого патча недействителен.', 'The patch download is too large.': 'Загружаемый патч слишком большой.', 'The patch download was interrupted. Existing patches were not changed.': 'Загрузка патча прервана. ' 'Установленные патчи не ' 'изменены.', 'Could not download the server patch. Check your connection and try again.': 'Не удалось загрузить ' 'серверный патч. ' 'Проверьте подключение ' 'и повторите попытку.', 'Verifying the downloaded patch...': 'Проверка загруженного патча...', 'Patch and backup locations must not be links or junctions.': 'Папки патчей и резервных копий не ' 'должны быть ссылками или точками ' 'соединения.', 'Windows LocalAppData could not be located.': 'Не удалось найти папку Windows LocalAppData.', 'A patch path is not a regular file. Nothing was changed.': 'Путь патча не является обычным файлом. ' 'Ничего не изменено.', 'The saved patch backup record is invalid. No patches were changed.': 'Запись резервной копии патчей ' 'недействительна. Патчи не ' 'изменены.', 'Another patcher operation is running. Wait for it to finish.': 'Уже выполняется другая операция ' 'патчера. Дождитесь её завершения.', 'A game patch changed during backup. Close the game and try again.': 'Патч изменился во время ' 'резервного копирования. ' 'Закройте игру и повторите ' 'попытку.', 'Recovering the previous patch switch...': 'Восстановление после прерванного переключения...', 'An interrupted switch could not be recovered. Your patch backups are in ArinarRebornBackups.': 'Не ' 'удалось ' 'восстановить ' 'прерванное ' 'переключение. ' 'Резервные ' 'копии ' 'находятся ' 'в ' 'ArinarRebornBackups.', 'The switch failed. Close the game and run the patcher again to recover your backed-up patches.': 'Переключение ' 'не ' 'удалось. ' 'Закройте ' 'игру ' 'и ' 'снова ' 'запустите ' 'патчер ' 'для ' 'восстановления ' 'из ' 'резервной ' 'копии.', 'The switch failed. Your previous patches were restored from backup.': 'Переключение не удалось. ' 'Предыдущие патчи ' 'восстановлены из резервной ' 'копии.', 'The server patch is already up to date.': 'Серверный патч уже обновлён.', 'Backing up existing game patches...': 'Резервное копирование установленных патчей...', 'Server patch installed in LocalAppData. Previous patches are backed up.': 'Серверный патч ' 'установлен в ' 'LocalAppData. Предыдущие ' 'патчи сохранены в ' 'резервной копии.', 'Backing up Arinar patches and restoring the original set...': 'Резервное копирование патчей Arinar ' 'и восстановление исходных патчей...', 'Your original game patches have been restored.': 'Исходные игровые патчи восстановлены.', 'Close the game before changing its server.': 'Закройте игру перед сменой сервера.', 'Could not check whether the game is running.': 'Не удалось проверить, запущена ли игра.', 'Current mode: {server}': 'Текущий режим: {server}', 'Unknown': 'Неизвестно', 'Separate Arinar copy (play both at once)': 'Отдельная копия Arinar (обе игры одновременно)', 'Checking the separate Arinar copy...': 'Проверка отдельной копии Arinar...', 'The Arinar copy is up to date.': 'Копия Arinar актуальна.', 'Close the Arinar game before it is updated.': 'Закройте игру Arinar перед её обновлением.', 'Copying the game for Arinar (the official game is not changed)...': 'Копирование игры для Arinar ' '(официальная игра не ' 'изменяется)...', 'Adding the Arinar content to the copy...': 'Добавление контента Arinar в копию...', 'The Arinar copy could not be prepared.': 'Не удалось подготовить копию Arinar.', 'The Arinar copy is ready.': 'Копия Arinar готова.', 'No separate Arinar copy is available for this client version.': 'Для этой версии клиента отдельная ' 'копия Arinar недоступна.', 'Choose the official game folder, not the Arinar copy.': 'Выберите папку официальной игры, а не ' 'копии Arinar.', 'The merged game PAK would be too large.': 'Объединённый PAK игры получился бы слишком большим.', "Close the game before switching servers, so your saved login is kept. Switch anyway puts this server's saved login in place now; the open game may save its own login over it when it closes.": 'Закройте ' 'игру ' 'перед ' 'сменой ' 'сервера, ' 'чтобы ' 'сохранённый ' 'вход ' 'не ' 'потерялся. ' '«Всё ' 'равно ' 'сменить» ' 'сразу ' 'подставит ' 'сохранённый ' 'вход ' 'этого ' 'сервера; ' 'открытая ' 'игра ' 'при ' 'закрытии ' 'может ' 'записать ' 'поверх ' 'него ' 'свой ' 'вход.', 'Switch anyway': 'Всё равно сменить', 'Separate login per server': 'Отдельный вход для каждого сервера', 'Your saved game login could not be backed up. Nothing was changed.': 'Не удалось сохранить ' 'резервную копию вашего входа. ' 'Ничего не изменено.', 'Arinar login selected.': 'Выбран вход Arinar.', 'Official game login selected.': 'Выбран вход официальной игры.', 'No separate Arinar copy is available for this client version ({version}).': 'Для этой версии ' 'клиента отдельная ' 'копия Arinar ' 'недоступна ' '({version}).', 'Open log folder': 'Открыть папку с логами'}, 'pt': {'Automatic': 'Automático', 'GAME LAUNCHER': 'INICIADOR DO JOGO', 'Language': 'Idioma', 'Choose your realm': 'Escolha seu reino', 'Original server': 'Servidor original', 'Official Warspear servers': 'Servidores oficiais de Warspear', 'Arinar Reborn': 'Arinar Reborn', 'Independent community realm': 'Reino independente da comunidade', 'Game folder': 'Pasta do jogo', 'Change folder': 'Alterar pasta', 'Play': 'Jogar', 'Play applies your selected server. Close the game before switching.': 'O servidor escolhido é ' 'aplicado ao jogar. Feche o ' 'jogo antes de trocar.', 'Looking for your installed game...': 'Procurando o jogo instalado...', 'Choose a game folder to get started.': 'Escolha a pasta do jogo para começar.', 'Game found. Ready to play.': 'Jogo encontrado. Pronto para jogar.', 'Game not found. Choose its folder to continue.': 'Jogo não encontrado. Escolha a pasta para ' 'continuar.', 'Folder selected. Ready to play.': 'Pasta selecionada. Pronto para jogar.', 'Choose your Warspear game folder': 'Escolha a pasta do jogo Warspear', 'Checking the client...': 'Verificando o cliente...', 'Could not start the game': 'Não foi possível iniciar o jogo', 'Wait for the current operation to finish before closing.': 'Aguarde a operação terminar antes de ' 'fechar.', 'Game started for {server}.': 'Jogo iniciado: {server}.', 'Choose the game folder containing warspear.exe and warspear.pak.': 'Escolha a pasta com ' 'warspear.exe e warspear.pak.', 'Language changed for this session. Could not save preference.': 'Idioma alterado nesta sessão. Não ' 'foi possível salvar a preferência.', 'Checking client and existing overlays...': 'Verificando o cliente e os patches existentes...', 'Building connection-only overlay...': 'Criando o patch de conexão...', 'Arinar connection overlay installed. Original game files are unchanged.': 'Patch de conexão Arinar ' 'instalado. Os arquivos ' 'originais não foram ' 'alterados.', 'Original server is already selected.': 'O servidor original já está selecionado.', 'Original routing restored. No Arinar overlay remains.': 'Conexão original restaurada. O patch ' 'Arinar foi removido.', 'Choose the installed Windows client folder containing warspear.pak.': 'Escolha a pasta do cliente ' 'Windows com warspear.pak.', 'Client and managed patch files must not be links or junctions.': 'O cliente e os arquivos do patch ' 'não podem ser links ou junções.', 'Another routing overlay exists ({file}). Use a clean client / remove it with its owning tool first.': 'Há ' 'outro ' 'patch ' 'de ' 'conexão ' '({file}). ' 'Use ' 'um ' 'cliente ' 'limpo ' 'ou ' 'remova-o ' 'com ' 'a ' 'ferramenta ' 'que ' 'o ' 'criou.', 'An unmanaged file occupies the patcher overlay name. Nothing was changed.': 'Um arquivo não ' 'gerenciado ocupa o ' 'nome do patch. Nada ' 'foi alterado.', 'The base client changed since patching. Restore the original client version before switching.': 'O ' 'cliente ' 'base ' 'mudou ' 'após ' 'o ' 'patch. ' 'Restaure ' 'a ' 'versão ' 'original ' 'antes ' 'de ' 'trocar.', 'The managed overlay is missing or changed. Nothing was overwritten or removed.': 'O patch está ' 'ausente ou foi ' 'alterado. Nada ' 'foi sobrescrito ' 'ou removido.', 'The patch manifest is invalid. Nothing was changed.': 'O registro do patch é inválido. Nada foi ' 'alterado.', 'This client has no supported connection configurations.': 'Este cliente não tem configurações de ' 'conexão compatíveis.', 'PAK format {version} is not supported by this prototype.': 'O formato PAK {version} não é ' 'compatível com este protótipo.', 'The baseline already has custom routing. Select an unmodified official client copy.': 'O cliente já ' 'tem uma ' 'conexão ' 'modificada. ' 'Escolha uma ' 'cópia ' 'oficial sem ' 'modificações.', 'Arinar is already applied. Switch to Original server before changing its endpoint.': 'O patch ' 'Arinar já ' 'está ' 'aplicado. ' 'Troque para o ' 'servidor ' 'original ' 'antes de ' 'alterar o ' 'endereço.', 'Select a valid RSA PUBLIC key PEM for the Arinar master. Private keys are not accepted.': 'É ' 'necessária ' 'uma ' 'chave ' 'RSA ' 'PÚBLICA ' 'PEM ' 'válida ' 'do ' 'servidor ' 'Arinar. ' 'Chaves ' 'privadas ' 'não são ' 'aceitas.', 'This client has no supported login-key entry. Nothing was changed.': 'Este cliente não tem uma ' 'chave de login compatível. ' 'Nada foi alterado.', 'Overlay verification failed. Nothing was installed.': 'A verificação do patch falhou. Nada foi ' 'instalado.', 'Overlay appeared during patching. Nothing was overwritten.': 'Outro patch apareceu durante a ' 'operação. Nada foi sobrescrito.', 'Enter a hostname or IP address, without a URL or path.': 'Informe um nome de host ou IP, sem URL ou ' 'caminho.', 'Port must be between 1 and 65535.': 'A porta deve estar entre 1 e 65535.', 'This development prototype needs the sibling pak_explorer.py and wsserver tools.': 'Este protótipo ' 'precisa de ' 'pak_explorer.py ' 'e das ' 'ferramentas ' 'wsserver no ' 'repositório.', 'Install requirements: python -m pip install -r arinar-patcher/requirements.txt': 'Instale as ' 'dependências: ' 'python -m pip ' 'install -r ' 'arinar-patcher/requirements.txt', 'Error': 'Erro', 'Attention': 'Atenção', 'Ready': 'Pronto', 'Working': 'Em andamento', 'Information': 'Informação', 'Important': 'Importante', 'OK': 'OK', 'The server patch download URL has not been configured yet.': 'O endereço de download do patch ainda ' 'não foi configurado.', 'The selected game client has an invalid base PAK.': 'O PAK base do cliente selecionado é inválido.', 'No server patch is available for this client version. Choose a supported client.': 'Não há patch ' 'para esta ' 'versão do ' 'cliente. ' 'Escolha uma ' 'versão ' 'compatível.', 'The server patch download configuration is invalid.': 'A configuração de download do patch é ' 'inválida.', 'The downloaded patch checksum does not match. Existing patches were not changed.': 'A soma de ' 'verificação do ' 'patch não ' 'confere. Os ' 'patches ' 'existentes não ' 'foram ' 'alterados.', 'The download is not a valid PAK patch. Existing patches were not changed.': 'O arquivo baixado não ' 'é um patch PAK válido. ' 'Os patches existentes ' 'não foram alterados.', 'The downloaded PAK format is not supported.': 'O formato PAK baixado não é compatível.', 'The downloaded patch is incomplete. Existing patches were not changed.': 'O patch baixado está ' 'incompleto. Os patches ' 'existentes não foram ' 'alterados.', 'The downloaded patch has no merge manifest. Existing patches were not changed.': 'O patch não tem ' 'um manifesto de ' 'mesclagem. Os ' 'patches ' 'existentes não ' 'foram alterados.', 'Downloading the server patch...': 'Baixando o patch do servidor...', 'The patch server returned an invalid download address.': 'O servidor retornou um endereço de ' 'download inválido.', 'The patch download size is invalid.': 'O tamanho do download do patch é inválido.', 'The patch download is too large.': 'O download do patch é grande demais.', 'The patch download was interrupted. Existing patches were not changed.': 'O download do patch foi ' 'interrompido. Os patches ' 'existentes não foram ' 'alterados.', 'Could not download the server patch. Check your connection and try again.': 'Não foi possível ' 'baixar o patch. ' 'Verifique a conexão e ' 'tente novamente.', 'Verifying the downloaded patch...': 'Verificando o patch baixado...', 'Patch and backup locations must not be links or junctions.': 'Os locais de patches e backups não ' 'podem ser links ou junções.', 'Windows LocalAppData could not be located.': 'Não foi possível localizar a pasta LocalAppData do ' 'Windows.', 'A patch path is not a regular file. Nothing was changed.': 'Um caminho de patch não é um arquivo ' 'comum. Nada foi alterado.', 'The saved patch backup record is invalid. No patches were changed.': 'O registro do backup é ' 'inválido. Nenhum patch foi ' 'alterado.', 'Another patcher operation is running. Wait for it to finish.': 'Outra operação do patcher está em ' 'andamento. Aguarde a conclusão.', 'A game patch changed during backup. Close the game and try again.': 'Um patch mudou durante o ' 'backup. Feche o jogo e tente ' 'novamente.', 'Recovering the previous patch switch...': 'Recuperando a troca de patches anterior...', 'An interrupted switch could not be recovered. Your patch backups are in ArinarRebornBackups.': 'Não ' 'foi ' 'possível ' 'recuperar ' 'a ' 'troca ' 'interrompida. ' 'Os ' 'backups ' 'estão ' 'em ' 'ArinarRebornBackups.', 'The switch failed. Close the game and run the patcher again to recover your backed-up patches.': 'A ' 'troca ' 'falhou. ' 'Feche ' 'o ' 'jogo ' 'e ' 'execute ' 'o ' 'patcher ' 'novamente ' 'para ' 'recuperar ' 'os ' 'backups.', 'The switch failed. Your previous patches were restored from backup.': 'A troca falhou. Seus patches ' 'anteriores foram restaurados ' 'do backup.', 'The server patch is already up to date.': 'O patch do servidor já está atualizado.', 'Backing up existing game patches...': 'Fazendo backup dos patches existentes...', 'Server patch installed in LocalAppData. Previous patches are backed up.': 'Patch instalado em ' 'LocalAppData. Os patches ' 'anteriores estão salvos ' 'em backup.', 'Backing up Arinar patches and restoring the original set...': 'Salvando patches Arinar e ' 'restaurando os patches originais...', 'Your original game patches have been restored.': 'Seus patches originais foram restaurados.', 'Close the game before changing its server.': 'Feche o jogo antes de trocar o servidor.', 'Could not check whether the game is running.': 'Não foi possível verificar se o jogo está aberto.', 'Current mode: {server}': 'Modo atual: {server}', 'Unknown': 'Desconhecido', 'Separate Arinar copy (play both at once)': 'Cópia separada do Arinar (jogar os dois ao mesmo tempo)', 'Checking the separate Arinar copy...': 'Verificando a cópia separada do Arinar...', 'The Arinar copy is up to date.': 'A cópia do Arinar está atualizada.', 'Close the Arinar game before it is updated.': 'Feche o jogo do Arinar antes de atualizá-lo.', 'Copying the game for Arinar (the official game is not changed)...': 'Copiando o jogo para o Arinar ' '(o jogo oficial não é ' 'alterado)...', 'Adding the Arinar content to the copy...': 'Adicionando o conteúdo do Arinar à cópia...', 'The Arinar copy could not be prepared.': 'Não foi possível preparar a cópia do Arinar.', 'The Arinar copy is ready.': 'A cópia do Arinar está pronta.', 'No separate Arinar copy is available for this client version.': 'Não há cópia separada do Arinar ' 'para esta versão do cliente.', 'Choose the official game folder, not the Arinar copy.': 'Escolha a pasta do jogo oficial, não a ' 'cópia do Arinar.', 'The merged game PAK would be too large.': 'O PAK combinado do jogo ficaria grande demais.', "Close the game before switching servers, so your saved login is kept. Switch anyway puts this server's saved login in place now; the open game may save its own login over it when it closes.": 'Feche ' 'o ' 'jogo ' 'antes ' 'de ' 'trocar ' 'de ' 'servidor, ' 'para ' 'que ' 'seu ' 'login ' 'salvo ' 'seja ' 'mantido. ' 'Trocar ' 'mesmo ' 'assim ' 'coloca ' 'agora ' 'o ' 'login ' 'salvo ' 'deste ' 'servidor; ' 'o ' 'jogo ' 'aberto ' 'pode ' 'salvar ' 'o ' 'próprio ' 'login ' 'por ' 'cima ' 'dele ' 'ao ' 'fechar.', 'Switch anyway': 'Trocar mesmo assim', 'Separate login per server': 'Login separado por servidor', 'Your saved game login could not be backed up. Nothing was changed.': 'Não foi possível fazer backup ' 'do seu login salvo. Nada foi ' 'alterado.', 'Arinar login selected.': 'Login do Arinar selecionado.', 'Official game login selected.': 'Login do jogo oficial selecionado.', 'No separate Arinar copy is available for this client version ({version}).': 'Não há cópia separada ' 'do Arinar para esta ' 'versão do cliente ' '({version}).', 'Open log folder': 'Abrir pasta de logs'}, 'zh': {'Automatic': '自动', 'GAME LAUNCHER': '游戏启动器', 'Language': '语言', 'Choose your realm': '选择服务器', 'Original server': '官方服务器', 'Official Warspear servers': 'Warspear 官方服务器', 'Arinar Reborn': 'Arinar Reborn', 'Independent community realm': '独立社区服务器', 'Game folder': '游戏文件夹', 'Change folder': '更改文件夹', 'Play': '开始游戏', 'Play applies your selected server. Close the game before switching.': '启动时会应用所选服务器。切换前请先关闭游戏。', 'Looking for your installed game...': '正在查找已安装的游戏…', 'Choose a game folder to get started.': '请选择游戏文件夹以开始。', 'Game found. Ready to play.': '已找到游戏,可以开始。', 'Game not found. Choose its folder to continue.': '未找到游戏。请选择游戏文件夹以继续。', 'Folder selected. Ready to play.': '已选择文件夹,可以开始。', 'Choose your Warspear game folder': '选择 Warspear 游戏文件夹', 'Checking the client...': '正在检查客户端…', 'Could not start the game': '无法启动游戏', 'Wait for the current operation to finish before closing.': '请等待当前操作完成后再关闭。', 'Game started for {server}.': '游戏已启动:{server}。', 'Choose the game folder containing warspear.exe and warspear.pak.': '请选择包含 warspear.exe 和 ' 'warspear.pak 的文件夹。', 'Language changed for this session. Could not save preference.': '已更改本次会话的语言,但无法保存偏好设置。', 'Checking client and existing overlays...': '正在检查客户端和现有补丁…', 'Building connection-only overlay...': '正在生成连接补丁…', 'Arinar connection overlay installed. Original game files are unchanged.': 'Arinar ' '连接补丁已安装,原始游戏文件未改动。', 'Original server is already selected.': '当前已选择官方服务器。', 'Original routing restored. No Arinar overlay remains.': '已恢复官方连接,Arinar 补丁已移除。', 'Choose the installed Windows client folder containing warspear.pak.': '请选择包含 warspear.pak 的 Windows ' '客户端文件夹。', 'Client and managed patch files must not be links or junctions.': '客户端和补丁文件不能是符号链接或目录联接。', 'Another routing overlay exists ({file}). Use a clean client / remove it with its owning tool first.': '存在其他连接补丁({file})。请使用干净客户端,或先用原工具移除该补丁。', 'An unmanaged file occupies the patcher overlay name. Nothing was changed.': '补丁文件名已被未知文件占用,未作任何改动。', 'The base client changed since patching. Restore the original client version before switching.': '基础客户端在打补丁后已更改。切换前请恢复原始版本。', 'The managed overlay is missing or changed. Nothing was overwritten or removed.': '补丁已丢失或被更改,未覆盖或删除任何文件。', 'The patch manifest is invalid. Nothing was changed.': '补丁清单无效,未作任何改动。', 'This client has no supported connection configurations.': '此客户端没有受支持的连接配置。', 'PAK format {version} is not supported by this prototype.': '此原型不支持 PAK 格式 {version}。', 'The baseline already has custom routing. Select an unmodified official client copy.': '客户端已使用自定义连接。请选择未经修改的官方客户端副本。', 'Arinar is already applied. Switch to Original server before changing its endpoint.': '已应用 Arinar ' '补丁。更改连接地址前请先切回官方服务器。', 'Select a valid RSA PUBLIC key PEM for the Arinar master. Private keys are not accepted.': '需要有效的 ' 'Arinar ' '服务器 RSA ' '公钥 ' 'PEM,不接受私钥。', 'This client has no supported login-key entry. Nothing was changed.': '此客户端没有受支持的登录密钥项,未作任何改动。', 'Overlay verification failed. Nothing was installed.': '补丁验证失败,未安装任何内容。', 'Overlay appeared during patching. Nothing was overwritten.': '操作期间出现了其他补丁,未覆盖任何文件。', 'Enter a hostname or IP address, without a URL or path.': '请输入主机名或 IP 地址,不要包含 URL 或路径。', 'Port must be between 1 and 65535.': '端口必须在 1 到 65535 之间。', 'This development prototype needs the sibling pak_explorer.py and wsserver tools.': '此原型需要仓库中的 ' 'pak_explorer.py ' '和 wsserver 工具。', 'Install requirements: python -m pip install -r arinar-patcher/requirements.txt': '请安装依赖:python -m ' 'pip install -r ' 'arinar-patcher/requirements.txt', 'Error': '错误', 'Attention': '注意', 'Ready': '就绪', 'Working': '处理中', 'Information': '信息', 'Important': '重要提示', 'OK': '确定', 'The server patch download URL has not been configured yet.': '尚未配置服务器补丁下载地址。', 'The selected game client has an invalid base PAK.': '所选客户端的基础 PAK 无效。', 'No server patch is available for this client version. Choose a supported client.': '此客户端版本暂无服务器补丁,请选择受支持的客户端。', 'The server patch download configuration is invalid.': '服务器补丁下载配置无效。', 'The downloaded patch checksum does not match. Existing patches were not changed.': '下载的补丁校验和不匹配,现有补丁未改动。', 'The download is not a valid PAK patch. Existing patches were not changed.': '下载内容不是有效的 PAK ' '补丁,现有补丁未改动。', 'The downloaded PAK format is not supported.': '不支持下载的 PAK 格式。', 'The downloaded patch is incomplete. Existing patches were not changed.': '下载的补丁不完整,现有补丁未改动。', 'The downloaded patch has no merge manifest. Existing patches were not changed.': '下载的补丁缺少合并清单,现有补丁未改动。', 'Downloading the server patch...': '正在下载服务器补丁…', 'The patch server returned an invalid download address.': '补丁服务器返回了无效下载地址。', 'The patch download size is invalid.': '补丁下载大小无效。', 'The patch download is too large.': '补丁下载过大。', 'The patch download was interrupted. Existing patches were not changed.': '补丁下载已中断,现有补丁未改动。', 'Could not download the server patch. Check your connection and try again.': '无法下载服务器补丁,请检查网络后重试。', 'Verifying the downloaded patch...': '正在验证下载的补丁…', 'Patch and backup locations must not be links or junctions.': '补丁和备份位置不能是符号链接或目录联接。', 'Windows LocalAppData could not be located.': '无法定位 Windows LocalAppData 文件夹。', 'A patch path is not a regular file. Nothing was changed.': '补丁路径不是普通文件,未作任何改动。', 'The saved patch backup record is invalid. No patches were changed.': '补丁备份记录无效,未改动任何补丁。', 'Another patcher operation is running. Wait for it to finish.': '另一个补丁操作正在运行,请等待其完成。', 'A game patch changed during backup. Close the game and try again.': '游戏补丁在备份期间发生变化,请关闭游戏后重试。', 'Recovering the previous patch switch...': '正在恢复上次补丁切换…', 'An interrupted switch could not be recovered. Your patch backups are in ArinarRebornBackups.': '无法恢复中断的切换,补丁备份位于 ' 'ArinarRebornBackups。', 'The switch failed. Close the game and run the patcher again to recover your backed-up patches.': '切换失败,请关闭游戏并重新运行补丁程序以恢复备份。', 'The switch failed. Your previous patches were restored from backup.': '切换失败,已从备份恢复原有补丁。', 'The server patch is already up to date.': '服务器补丁已是最新版本。', 'Backing up existing game patches...': '正在备份现有游戏补丁…', 'Server patch installed in LocalAppData. Previous patches are backed up.': '服务器补丁已安装到 ' 'LocalAppData,原有补丁已备份。', 'Backing up Arinar patches and restoring the original set...': '正在备份 Arinar 补丁并恢复原有补丁…', 'Your original game patches have been restored.': '原有游戏补丁已恢复。', 'Close the game before changing its server.': '更改服务器前请先关闭游戏。', 'Could not check whether the game is running.': '无法检查游戏是否正在运行。', 'Current mode: {server}': '当前模式:{server}', 'Unknown': '未知', 'Separate Arinar copy (play both at once)': '独立的 Arinar 副本(可同时运行两者)', 'Checking the separate Arinar copy...': '正在检查独立的 Arinar 副本...', 'The Arinar copy is up to date.': 'Arinar 副本已是最新。', 'Close the Arinar game before it is updated.': '请在更新前关闭 Arinar 游戏。', 'Copying the game for Arinar (the official game is not changed)...': '正在为 Arinar 复制游戏(官方游戏不会被修改)...', 'Adding the Arinar content to the copy...': '正在向副本添加 Arinar 内容...', 'The Arinar copy could not be prepared.': '无法准备 Arinar 副本。', 'The Arinar copy is ready.': 'Arinar 副本已就绪。', 'No separate Arinar copy is available for this client version.': '此客户端版本没有可用的独立 Arinar 副本。', 'Choose the official game folder, not the Arinar copy.': '请选择官方游戏文件夹,而不是 Arinar 副本。', 'The merged game PAK would be too large.': '合并后的游戏 PAK 过大。', "Close the game before switching servers, so your saved login is kept. Switch anyway puts this server's saved login in place now; the open game may save its own login over it when it closes.": '切换服务器前请先关闭游戏,以保留您保存的登录信息。“仍然切换”会立即换上此服务器保存的登录信息;已打开的游戏在关闭时可能会用自己的登录信息将其覆盖。', 'Switch anyway': '仍然切换', 'Separate login per server': '每个服务器单独保存登录', 'Your saved game login could not be backed up. Nothing was changed.': '无法备份您保存的游戏登录信息。未做任何更改。', 'Arinar login selected.': '已切换到 Arinar 登录。', 'Official game login selected.': '已切换到官方游戏登录。', 'No separate Arinar copy is available for this client version ({version}).': '此客户端版本没有可用的独立 Arinar ' '副本({version})。', 'Open log folder': '打开日志文件夹'}} PYTHON_LAUNCHER_DATE = '2026-12-03' ART = {'arinar-wordmark-v1.webp': 'c1f21455107d302afc75ec8b64d58403c1ff18d8669381fb38efdc0e2d9a1a15', 'blue-steel-panel-plain-top.png': '100642521ba7b5133ae83cc7680e04b89cd1903eb0487c70425d892ab3cf51c3', 'blue-steel-panel.png': '950858482e6d8e1115a5f2ad60fbfaf6df1a450b895734a431f8f35789e8c7b4', 'kingdom-panorama.png': 'c2561de96b318b15419a480d2b2d2e4aaa3af7f6e67f9fa64d0d21761122da34', 'patcher-icon-v1.ico': '828c45b553adbc0c1f498d7328d7249737fe921cf86982ebd7cd28f22353572f', 'patcher-icon-v1.png': '12423c6a860c21524254f115f7e8651ac1c41064fc6a0503890be8d11d16b800'} ART_URL = 'https://patch.arinar.net/diffs/launcher-' def asset(name): folder = Path(os.environ.get('LOCALAPPDATA') or Path.home()) / 'ArinarReborn' / 'launcher-art' path = folder / name if path.is_file() and digest(path) == ART[name]: return path folder.mkdir(parents=True, exist_ok=True) request = Request(ART_URL + name, headers={'User-Agent': 'ArinarReborn-Patcher/1'}) with urlopen(request, timeout=30, context=ssl.create_default_context(cafile=certifi.where())) as response: data = response.read(32 * 1024 * 1024) if hashlib.sha256(data).hexdigest() != ART[name]: raise SystemExit(f'The downloaded launcher artwork {name} does not match its checksum.') temporary = path.with_name(path.name + '.tmp') temporary.write_bytes(data) os.replace(temporary, path) return path log = logging.getLogger('arinar') LOG_NAME = 'launcher.log' _state = {'file': None} def launcher_version(): try: return 'python ' + PYTHON_LAUNCHER_DATE except OSError: return 'dev' def log_dir(): location = os.environ.get('LOCALAPPDATA') return Path(location) / 'ArinarReborn' / 'logs' if location else Path(tempfile.gettempdir()) / 'ArinarReborn-logs' def log_file(): return _state['file'] or log_dir() / LOG_NAME def setup(): if _state['file'] is not None: return _state['file'] log.setLevel(logging.INFO) for folder in (log_dir(), Path(tempfile.gettempdir()) / 'ArinarReborn-logs'): try: folder.mkdir(parents=True, exist_ok=True) handler = logging.handlers.RotatingFileHandler(folder / LOG_NAME, maxBytes=1000000, backupCount=3, encoding='utf-8') except OSError: continue handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s')) log.addHandler(handler) _state['file'] = folder / LOG_NAME break else: log.addHandler(logging.NullHandler()) log.info('---- Arinar Reborn launcher %s started (%s, %s; Python %s %s; Windows %s)', launcher_version(), 'exe' if getattr(sys, 'frozen', False) else 'source', platform.machine(), platform.python_version(), platform.architecture()[0], platform.platform()) def unhandled(kind, value, trace): log.error('unhandled error', exc_info=(kind, value, trace)) sys.__excepthook__(kind, value, trace) sys.excepthook = unhandled if hasattr(threading, 'excepthook'): threading.excepthook = lambda args: log.error('unhandled error in a worker thread', exc_info=(args.exc_type, args.exc_value, args.exc_traceback)) return _state['file'] def open_log_folder(): path = log_file() try: if os.name == 'nt': if path.is_file(): subprocess.Popen(['explorer', '/select,', str(path)]) else: os.startfile(str(path.parent)) else: subprocess.Popen(['xdg-open', str(path.parent)]) except OSError: log.exception('could not open the log folder') def mix(first, second, amount): channels = [round(int(first[index:index + 2], 16) * (1 - amount) + int(second[index:index + 2], 16) * amount) for index in (1, 3, 5)] return '#' + ''.join((f'{channel:02x}' for channel in channels)) SURFACE = '#162737' FRAME = '#526779' TEXT = '#d1dbe3' SEVERITIES = {'error': ('Error', '!', '#d38c7d'), 'warning': ('Attention', '!', '#d0b477'), 'success': ('Ready', '✓', '#9fc5af'), 'working': ('Working', '…', '#a1c0d8'), 'info': ('Information', 'i', '#a1c0d8')} def frame_points(left, top, right, bottom, cut=5): return (left + cut, top, right - cut, top, right, top + cut, right, bottom - cut, right - cut, bottom, left + cut, bottom, left, bottom - cut, left, top + cut) LABELS = {'en': 'English', 'ru': 'Русский', 'pt': 'Português', 'zh': '简体中文'} CATALOGS = LOCALES def normalize(value): language = str(value or '').replace('-', '_').split('_')[0].split('.')[0].lower() return language if language in LABELS else None def system_language(): for key in ('LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG'): for value in os.environ.get(key, '').split(':'): if (language := normalize(value)): return language if os.name == 'nt': try: code = ctypes.windll.kernel32.GetUserDefaultUILanguage() if (language := normalize(locale.windows_locale.get(code))): return language except (AttributeError, OSError): pass try: return normalize(locale.getlocale()[0]) or 'en' except (ValueError, TypeError): return 'en' def preference_path(): base = Path(os.environ['LOCALAPPDATA']) if os.environ.get('LOCALAPPDATA') else Path.home() / '.config' return base / 'ArinarReborn' / 'launcher-preferences.json' def load_preference(path): try: value = json.loads(Path(path).read_text(encoding='utf-8')).get('language') return value if value in LABELS else 'auto' except (OSError, ValueError, TypeError, AttributeError): return 'auto' def save_preference(path, language): if language not in (*LABELS, 'auto'): raise ValueError('Unsupported language preference') path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) temporary = None try: with tempfile.NamedTemporaryFile(mode='w', encoding='utf-8', dir=path.parent, delete=False) as file: temporary = Path(file.name) json.dump({'language': language}, file) temporary.replace(path) finally: if temporary is not None: temporary.unlink(missing_ok=True) def translate(text, language): catalog = CATALOGS.get(language, {}) if text in catalog: return catalog[text] for source, translated in catalog.items(): if '{' not in source: continue names = re.findall('\\{(\\w+)\\}', source) pattern = re.escape(source) for name in names: pattern = pattern.replace(re.escape('{' + name + '}'), '(?P<' + name + '>.+?)') if (match := re.fullmatch(pattern, text)): values = match.groupdict() if 'server' in values: values['server'] = translate(values['server'], language) return translated.format(**values) return text def font_family(language): return 'Microsoft YaHei UI' if language == 'zh' else 'Bahnschrift' UNKNOWN = 'Unknown' @lru_cache(maxsize=32) def _settings(path, modified, size): result = {} with Path(path).open('rb') as file: header = file.read(26) if len(header) < 26 or header[:4] != b'MDPK': raise ValueError('Invalid PAK') version = struct.unpack_from(' 300000 or start + count * 68 > size: raise ValueError('Invalid PAK index') file.seek(start) table = file.read(count * 68) for index in range(count): offset, packed, unpacked, method, raw = struct.unpack_from(' 1024 * 1024 or unpacked > 1024 * 1024 or (offset < start + count * 68) or (offset + packed > size): raise ValueError('Invalid connection entry') file.seek(offset) data = file.read(packed) if method == 1: data = bz2.decompress(data) elif method == 2: data = brotli.decompress(data) if len(data) != unpacked: raise ValueError('Invalid connection entry size') result[name] = data.decode('utf-8-sig') return (revision, result) def detect_mode(base, patches, arinar_hosts): settings, revisions = ({}, {}) try: for index, path in enumerate([Path(base), *sorted(patches, key=lambda p: int(p.name.rsplit('.', 1)[1]))]): stat = path.stat() revision, entries = _settings(str(path), stat.st_mtime_ns, stat.st_size) if index == 0: base_revision = revision elif revision <= base_revision: continue for name, text in entries.items(): if name not in revisions or revision > revisions[name]: settings[name], revisions[name] = (text, revision) modes = set() for text in settings.values(): key = '(?:host(?:_tls)?|(?:tls_)?master_server_address(?:es_list)?)' if text.lstrip().startswith('[master]') else '(?:tls_)?master_server_address(?:es_list)?' for match in re.finditer('^\\s*' + key + '\\s*=\\s*([^\\r\\n;]+)', text, re.M): value = match[1].strip().strip('"\'') for host in re.split('[,\\s|]+', value): host = host.strip().strip('"\'').lower().rstrip('.') if not host: continue if host in arinar_hosts: modes.add('Arinar Reborn') elif any((host == domain or host.endswith('.' + domain) for domain in ('warspear-online.com', 'warspear.com', 'aigrind.com', 'warspear.online', 'warspear.ru', 'warspear-online.ru', 'warspearonline.ru'))): modes.add('Original server') else: modes.add(UNKNOWN) return modes.pop() if len(modes) == 1 else UNKNOWN except (OSError, ValueError, UnicodeError, struct.error, brotli.error): return UNKNOWN def configured_hosts(manifest): hosts = {urlparse(release['url']).hostname.lower() for release in manifest['releases']} hosts.update((host.lower().rstrip('.') for host in manifest.get('game_hosts', []))) return hosts OFFICIAL_KEY = 'SOFTWARE\\Warspear Online' LAUNCHER_KEY = 'Software\\ArinarReborn\\Patcher' FOLDER_VALUE = 'GameFolder' def load_game_folder(registry=None) -> Path | None: if registry is None: if os.name != 'nt': return None import winreg as registry try: with registry.OpenKey(registry.HKEY_CURRENT_USER, LAUNCHER_KEY) as key: value, _kind = registry.QueryValueEx(key, FOLDER_VALUE) return find_client([Path(value)]) if isinstance(value, str) and value.strip() else None except (OSError, ValueError): return None def save_game_folder(folder, registry=None) -> None: if registry is None: if os.name != 'nt': return import winreg as registry with registry.CreateKeyEx(registry.HKEY_CURRENT_USER, LAUNCHER_KEY, 0, registry.KEY_SET_VALUE) as key: registry.SetValueEx(key, FOLDER_VALUE, 0, registry.REG_SZ, str(Path(folder).resolve())) def official_registry_locations(registry) -> list[Path]: locations = [] for hive in (registry.HKEY_CURRENT_USER, registry.HKEY_LOCAL_MACHINE): for view in (registry.KEY_WOW64_64KEY, registry.KEY_WOW64_32KEY): try: with registry.OpenKey(hive, OFFICIAL_KEY, 0, registry.KEY_READ | view) as key: value = registry.QueryValueEx(key, 'Path')[0] if isinstance(value, str) and value.strip(): path = Path(os.path.expandvars(value.strip().strip('"'))) if path not in locations: locations.append(path) except OSError: continue return locations def registry_locations() -> list[Path]: if os.name != 'nt': return [] import winreg locations = official_registry_locations(winreg) for hive in (winreg.HKEY_CURRENT_USER, winreg.HKEY_LOCAL_MACHINE): for view in (winreg.KEY_WOW64_64KEY, winreg.KEY_WOW64_32KEY): try: with winreg.OpenKey(hive, 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall', 0, winreg.KEY_READ | view) as root: for index in range(winreg.QueryInfoKey(root)[0]): try: with winreg.OpenKey(root, winreg.EnumKey(root, index)) as key: name = str(winreg.QueryValueEx(key, 'DisplayName')[0]) if 'warspear' in name.casefold(): locations.append(Path(os.path.expandvars(str(winreg.QueryValueEx(key, 'InstallLocation')[0])))) except OSError: continue except OSError: continue for hive, key, value in ((winreg.HKEY_CURRENT_USER, 'Software\\Valve\\Steam', 'SteamPath'), (winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Valve\\Steam', 'InstallPath')): try: with winreg.OpenKey(hive, key) as item: locations.append(Path(winreg.QueryValueEx(item, value)[0])) except OSError: pass return locations def candidate_locations(nearby: Iterable[Path]=()) -> list[Path]: bases = registry_locations() + list(nearby) home = Path.home() bases += [home / 'Games', home / 'Downloads', home / 'Desktop', Path('C:/Games')] bases += [Path(os.environ[key]) for key in ('ProgramFiles', 'ProgramFiles(x86)', 'LOCALAPPDATA', 'APPDATA') if os.environ.get(key)] bases = [path for path in bases if not str(path).startswith(('\\\\', '//'))] steam_roots = [Path(os.environ[key]) / 'Steam' for key in ('ProgramFiles(x86)', 'ProgramFiles') if os.environ.get(key)] steam_roots += [path for path in bases if (path / 'steamapps').is_dir()] steam_roots = [path for path in steam_roots if not str(path).startswith(('\\\\', '//'))] for steam in list(steam_roots): try: vdf = (steam / 'steamapps' / 'libraryfolders.vdf').read_text(encoding='utf-8') steam_roots += [Path(value.replace('\\\\', '\\')) for value in re.findall('"path"\\s*"([^"\\n]+)"', vdf)] except (OSError, UnicodeError): pass bases += [path / 'steamapps' / 'common' for path in steam_roots] names = ('Warspear Online', 'WarspearOnline', 'Warspear', 'warspear', 'client', 'AIGRIND/Warspear Online', 'AIGRIND/WarspearOnline') return [candidate for base in bases for candidate in (base, *(base / name for name in names))] def find_client(candidates: Iterable[Path]) -> Path | None: seen = set() for candidate in candidates: try: if str(candidate).startswith(('\\\\', '//')): continue folder = candidate.expanduser().resolve() identity = str(folder).casefold() if identity in seen: continue seen.add(identity) files = (folder / 'warspear.exe', folder / 'warspear.pak') if all((path.is_file() and (not path.is_symlink()) for path in files)): return folder except (OSError, ValueError): continue return None log = logging.getLogger('arinar') OVERLAY = 'warspear.pak.1' STATE = '.arinar-patcher.json' BACKUPS = 'ArinarRebornBackups' MAX_PATCH_BYTES = 64 * 1024 * 1024 PATCH_NAME = re.compile('warspear\\.pak\\.\\d+$') class PatcherError(Exception): def __init__(self, message, kind='error'): super().__init__(message) self.kind = kind def digest(path): with Path(path).open('rb') as file: if hasattr(hashlib, 'file_digest'): return hashlib.file_digest(file, 'sha256').hexdigest() hasher = hashlib.sha256() for chunk in iter(lambda: file.read(1024 * 1024), b''): hasher.update(chunk) return hasher.hexdigest() def base_identity(path): with Path(path).open('rb') as file: data = file.read(26) if len(data) < 26 or data[:4] != b'MDPK': raise PatcherError('The selected game client has an invalid base PAK.') version = struct.unpack_from(' same[-1]['base_timestamp'] and manifest.get('newer_clients', 'newest') != 'newest': return None chosen = [r for r in same if r['base_timestamp'] <= timestamp][-1] log.info('client %s/%s is not listed: using the closest release, %s', version, timestamp, chosen['generation']) return chosen def client_version(base): try: version, timestamp = base_identity(base) return f'format {version}, {timestamp or 'no date'}' except (OSError, PatcherError, ValueError, UnicodeDecodeError): return '?' def load_source(base): try: source = find_release(base) if source is None: raise PatcherError('No server patch is available for this client version. Choose a supported client.') url = source.get('url') if not isinstance(url, str) or not url.strip(): raise PatcherError('The server patch download URL has not been configured yet.') parsed = urlparse(url) if parsed.scheme not in ('http', 'https') or not parsed.hostname or parsed.username or parsed.password: raise ValueError('Invalid patch URL') checksum = source.get('sha256') if not isinstance(checksum, str) or not re.fullmatch('[0-9a-fA-F]{64}', checksum): raise ValueError('Invalid SHA-256') return {'url': url, 'sha256': checksum} except (OSError, ValueError, TypeError, AttributeError, KeyError) as exc: raise PatcherError('The server patch download configuration is invalid.') from exc def validate_patch(path, expected=None, manifest_required=True): data = Path(path).read_bytes() if expected and hashlib.sha256(data).hexdigest().lower() != expected.lower(): raise PatcherError('The downloaded patch checksum does not match. Existing patches were not changed.') if len(data) < 26 or data[:4] != b'MDPK': raise PatcherError('The download is not a valid PAK patch. Existing patches were not changed.') version = struct.unpack_from(' len(data): raise PatcherError('The downloaded patch is incomplete. Existing patches were not changed.') names = set() for index in range(count): offset, packed, unpacked, method, raw = struct.unpack_from(' len(data)): raise PatcherError('The downloaded patch is incomplete. Existing patches were not changed.') names.add(name) if manifest_required and b'deleted' not in names: raise PatcherError('The downloaded patch has no merge manifest. Existing patches were not changed.') DIRECT_DIFFS_ORIGIN = 'http://game.arinar.net:15180' def _download_urls(url): urls = [url] parsed = urlparse(url) if parsed.scheme == 'https' and (parsed.hostname or '').lower() == 'patch.arinar.net' and parsed.path.startswith('/diffs/') and (not parsed.query) and (not parsed.fragment): urls.append(DIRECT_DIFFS_ORIGIN + parsed.path) return urls def download_patch(source, destination, progress): progress('Downloading the server patch...') urls = _download_urls(source['url']) context = ssl.create_default_context(cafile=certifi.where()) last_error = None for index, url in enumerate(urls): has_fallback = index + 1 < len(urls) request = Request(url, headers={'User-Agent': 'ArinarReborn-Patcher/1'}) timeout = 10 if has_fallback else 20 try: kwargs = {'timeout': timeout} if urlparse(url).scheme == 'https': kwargs['context'] = context with urlopen(request, **kwargs) as response, Path(destination).open('wb') as output: if urlparse(response.geturl()).scheme not in ('http', 'https'): raise PatcherError('The patch server returned an invalid download address.') length = response.headers.get('Content-Length') expected_size = int(length) if length else None if expected_size is not None and (not 0 < expected_size <= MAX_PATCH_BYTES): raise PatcherError('The patch download size is invalid.') size = 0 while (block := response.read(64 * 1024)): size += len(block) if size > MAX_PATCH_BYTES: raise PatcherError('The patch download is too large.') output.write(block) if expected_size is not None and size != expected_size: if has_fallback: last_error = PatcherError('The patch download was interrupted. Existing patches were not changed.') continue raise PatcherError('The patch download was interrupted. Existing patches were not changed.') last_error = None break except (HTTPError, URLError, TimeoutError, OSError, ValueError, HTTPException) as exc: last_error = exc if not has_fallback: raise PatcherError('Could not download the server patch. Check your connection and try again.') from exc if last_error is not None: if isinstance(last_error, PatcherError): raise last_error raise PatcherError('Could not download the server patch. Check your connection and try again.') from last_error progress('Verifying the downloaded patch...') validate_patch(destination, source.get('sha256'), source.get('manifest_required', True)) def atomic_json(path, value): Path(path).parent.mkdir(parents=True, exist_ok=True) temporary = Path(path).with_name('.arinar-' + uuid.uuid4().hex + '.tmp') try: temporary.write_text(json.dumps(value, indent=2), encoding='utf-8') os.replace(temporary, path) finally: temporary.unlink(missing_ok=True) def _is_junction(path): if hasattr(path, 'is_junction'): return path.is_junction() if os.name != 'nt': return False try: return getattr(os.lstat(path), 'st_reparse_tag', 0) == 2684354563 except OSError: return False def reject_link(path): path = Path(path) if path.is_symlink() or _is_junction(path): raise PatcherError('Patch and backup locations must not be links or junctions.') def process_alive(pid): if pid <= 0: return True if os.name == 'nt': import ctypes kernel = ctypes.WinDLL('kernel32', use_last_error=True) kernel.OpenProcess.restype = ctypes.c_void_p kernel.CloseHandle.argtypes = [ctypes.c_void_p] handle = kernel.OpenProcess(4096, False, pid) if handle: kernel.CloseHandle(handle) return True return ctypes.get_last_error() != 87 try: os.kill(pid, 0) return True except ProcessLookupError: return False except PermissionError: return True def game_running(): if os.name != 'nt': return False try: result = subprocess.run(['tasklist', '/FI', 'IMAGENAME eq warspear.exe', '/FO', 'CSV', '/NH'], capture_output=True, text=True, errors='replace', check=True, timeout=10, creationflags=subprocess.CREATE_NO_WINDOW) except (OSError, subprocess.SubprocessError) as exc: raise PatcherError('Could not check whether the game is running.') from exc return any((line.lower().startswith('"warspear.exe",') for line in result.stdout.splitlines())) def ensure_game_closed(): if game_running(): raise PatcherError('Close the game before changing its server.', kind='warning') class Client: def __init__(self, folder, *, appdata=None, source=None, downloader=download_patch): self.folder = Path(folder).expanduser().resolve() location = appdata if appdata is not None else os.environ.get('LOCALAPPDATA') self.root = Path(location) / 'Warspear Online' if location else None self.source, self.downloader = (source, downloader) def _validate(self): if not self.root: raise PatcherError('Windows LocalAppData could not be located.') for path in (self.folder / 'warspear.exe', self.folder / 'warspear.pak'): reject_link(path) if not path.is_file(): raise PatcherError('Choose the game folder containing warspear.exe and warspear.pak.') for path in (self.root, self.root / BACKUPS, self.root / STATE, self.root / '.arinar-switch.json'): reject_link(path) def _patches(self): paths = sorted((path for path in self.root.glob('warspear.pak.*') if PATCH_NAME.fullmatch(path.name))) for path in paths: reject_link(path) if not path.is_file(): raise PatcherError('A patch path is not a regular file. Nothing was changed.') return paths def _record(self): path = self.root / STATE if not path.exists(): return None try: record = json.loads(path.read_text(encoding='utf-8')) if record['schema'] != 2 or not isinstance(record['original_files'], dict): raise ValueError('Invalid state') self._saved_files(record['original_backup'], record['original_files']) return record except (OSError, ValueError, KeyError, TypeError) as exc: raise PatcherError('The saved patch backup record is invalid. No patches were changed.') from exc def _saved_files(self, name, hashes): if not isinstance(name, str) or not re.fullmatch('[a-zA-Z0-9_-]+', name): raise ValueError('Invalid backup name') directory = self.root / BACKUPS / name reject_link(directory) reject_link(directory / 'files') if not (directory / 'files').is_dir(): raise ValueError('Missing backup') paths = {} for filename, checksum in hashes.items(): if not isinstance(filename, str) or not PATCH_NAME.fullmatch(filename): raise ValueError('Invalid saved filename') path = directory / 'files' / filename reject_link(path) if not path.is_file() or digest(path) != checksum: raise ValueError('Backup checksum mismatch') paths[filename] = path return paths def inspect(self): self._validate() record = self._record() pending = (self.root / '.arinar-switch.json').exists() return {'mode': self.current_mode(), 'patch_directory': str(self.root), 'patches': [p.name for p in self._patches()], 'backup': record['original_backup'] if record else None, 'recovery_pending': pending} def current_mode(self): if not self.root or (self.root / '.arinar-switch.json').exists(): return 'Unknown' try: manifest = load_manifest(network=False) hosts = configured_hosts(manifest) base = self.folder / 'warspear.pak' if not base.is_file(): base = self.root / 'warspear.pak' return detect_mode(base, self._patches(), hosts) except (OSError, ValueError, KeyError, TypeError, AttributeError, PatcherError): return 'Unknown' @contextmanager def _lock(self): self.root.mkdir(parents=True, exist_ok=True) lock = self.root / '.arinar-patcher.lock' reject_link(lock) try: file = lock.open('x', encoding='ascii') except FileExistsError as exc: try: contents = lock.read_text(encoding='ascii') if not process_alive(int(contents)): lock.unlink() file = lock.open('x', encoding='ascii') else: raise ValueError('Active operation') except (OSError, ValueError): raise PatcherError('Another patcher operation is running. Wait for it to finish.') from exc try: with file: file.write(str(os.getpid())) yield finally: lock.unlink(missing_ok=True) def _snapshot(self, action): name = datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S') + '-' + action + '-' + uuid.uuid4().hex[:8] directory = self.root / BACKUPS / name files = directory / 'files' files.mkdir(parents=True) hashes = {} for path in self._patches(): before = digest(path) shutil.copy2(path, files / path.name) if before != digest(files / path.name) or before != digest(path): raise PatcherError('A game patch changed during backup. Close the game and try again.') hashes[path.name] = before state = self.root / STATE if state.exists(): shutil.copy2(state, directory / 'previous-state.json') atomic_json(directory / 'snapshot.json', {'files': hashes, 'action': action}) return (name, hashes) def _replace_files(self, desired): for path in self._patches(): path.unlink() for name, source in desired.items(): temporary = self.root / ('.arinar-' + uuid.uuid4().hex + '.tmp') try: shutil.copy2(source, temporary) os.replace(temporary, self.root / name) finally: temporary.unlink(missing_ok=True) def _restore_snapshot(self, name, hashes): desired = self._saved_files(name, hashes) self._replace_files(desired) old_state = self.root / BACKUPS / name / 'previous-state.json' reject_link(old_state) if old_state.exists(): atomic_json(self.root / STATE, json.loads(old_state.read_text(encoding='utf-8'))) else: (self.root / STATE).unlink(missing_ok=True) def _recover(self, progress): pending = self.root / '.arinar-switch.json' if not pending.exists(): return try: record = json.loads(pending.read_text(encoding='utf-8')) self._saved_files(record['backup'], record['files']) progress('Recovering the previous patch switch...') self._snapshot('interrupted') self._restore_snapshot(record['backup'], record['files']) pending.unlink() except Exception as exc: raise PatcherError('An interrupted switch could not be recovered. Your patch backups are in ArinarRebornBackups.') from exc def _switch(self, desired, new_record, name, hashes): pending = self.root / '.arinar-switch.json' atomic_json(pending, {'backup': name, 'files': hashes}) if {p.name: digest(p) for p in self._patches()} != hashes: pending.unlink() raise PatcherError('A game patch changed during backup. Close the game and try again.') try: self._replace_files(desired) if new_record is None: (self.root / STATE).unlink(missing_ok=True) else: atomic_json(self.root / STATE, new_record) pending.unlink() except Exception as exc: try: self._snapshot('failed-switch') self._restore_snapshot(name, hashes) pending.unlink(missing_ok=True) except Exception: raise PatcherError('The switch failed. Close the game and run the patcher again to recover your backed-up patches.') from exc raise PatcherError('The switch failed. Your previous patches were restored from backup.') from exc def apply(self, progress=lambda _: None): self._validate() ensure_game_closed() source = self.source if self.source is not None else load_source(self.folder / 'warspear.pak') with tempfile.TemporaryDirectory(prefix='arinar-download-') as folder: downloaded = Path(folder) / OVERLAY self.downloader(source, downloaded, progress) validate_patch(downloaded, source.get('sha256')) with self._lock(): ensure_game_closed() self._recover(progress) record = self._record() current = self.root / OVERLAY if record and current.is_file() and (digest(current) == digest(downloaded)): progress('The server patch is already up to date.') return progress('Backing up existing game patches...') name, hashes = self._snapshot('before-arinar') baseline, original = (record['original_backup'], record['original_files']) if record else (name, hashes) new_record = {'schema': 2, 'original_backup': baseline, 'original_files': original, 'installed_sha256': digest(downloaded), 'source_url': source['url']} self._switch({OVERLAY: downloaded}, new_record, name, hashes) progress('Server patch installed in LocalAppData. Previous patches are backed up.') def restore(self, progress=lambda _: None): self._validate() ensure_game_closed() if not self.root.exists(): progress('Original server is already selected.') return with self._lock(): self._recover(progress) record = self._record() if not record: progress('Original server is already selected.') return desired = self._saved_files(record['original_backup'], record['original_files']) progress('Backing up Arinar patches and restoring the original set...') name, hashes = self._snapshot('before-original') self._switch(desired, None, name, hashes) progress('Your original game patches have been restored.') COPY_DIR = 'Arinar client' COPY_STATE = '.arinar-copy.json' COPY_SKIP = shutil.ignore_patterns('*.dmp', '*.log', 'temp', 'warspear.pak.bak*', 'patches') ARINAR_REVISION = re.compile('\\d{4}-\\d{2}-\\d{2}-\\d+') def _is_arinar_overlay(path): try: return bool(ARINAR_REVISION.fullmatch(base_identity(path)[1])) except (OSError, PatcherError, UnicodeDecodeError, struct.error): return False def move_arinar_overlays(appdata=None, progress=lambda _: None): location = appdata if appdata is not None else os.environ.get('LOCALAPPDATA') if not location: return [] folder = Path(location) / 'Warspear Online' paks = sorted(((int(p.name.rsplit('.', 1)[1]), p) for p in folder.glob('warspear.pak.*') if p.name.rsplit('.', 1)[1].isdigit() and p.is_file())) ours = [p for _, p in paks if _is_arinar_overlay(p)] if not ours: return [] backup = Path(location) / 'ArinarReborn' / 'removed-overlays' / datetime.now().strftime('%Y%m%d-%H%M%S') backup.mkdir(parents=True, exist_ok=True) try: for path in ours: os.replace(path, backup / path.name) rest = [p for _, p in paks if p not in ours] for index, path in enumerate(rest, 1): target = folder / f'warspear.pak.{index}' if path != target: os.replace(path, target) except OSError as exc: raise PatcherError('Close the official game, then try again.', kind='warning') from exc progress('Moved Arinar patches out of the official game folder.') return [p.name for p in ours] def _pak_index(file): header = file.read(26) if len(header) < 26 or header[:4] != b'MDPK' or struct.unpack_from(' 4294967295: raise PatcherError('The merged game PAK would be too large.') out.write(b'MDPK' + struct.pack('', self._draw) self.bind('', self._enter) self.bind('', self._leave) self.bind('', self._press) self.bind('', self._release) self.bind('', self._draw) self.bind('', self._cancel) self.bind('', self._press) self.bind('', self._release) self.bind('', self._activate) def configure(self, cnf=None, **kwargs): if cnf is not None: kwargs.update(cnf) if kwargs.get('state') == 'disabled': self.pressed = self.hovered = False self._stop_hover() self.hover_amount = 0.0 result = super().configure(**kwargs) self._draw() return result config = configure def _enter(self, _event): self.hovered = self.cget('state') != 'disabled' self._animate_hover() def _leave(self, _event): self.hovered = self.pressed = False self._animate_hover() def _stop_hover(self): if self.hover_job is not None: self.after_cancel(self.hover_job) self.hover_job = None def _animate_hover(self): self._stop_hover() start, target, began = (self.hover_amount, float(self.hovered), time.monotonic()) def frame(): self.hover_job = None progress = min(1.0, (time.monotonic() - began) / 0.16) eased = 1 - (1 - progress) ** 3 self.hover_amount = start + (target - start) * eased self._draw() if progress < 1: self.hover_job = self.after(16, frame) frame() def destroy(self): self._stop_hover() super().destroy() def _cancel(self, _event): self.pressed = False self._draw() def _press(self, _event): if self.cget('state') != 'disabled': self.focus_set() self.pressed = True self._draw() return 'break' def _release(self, event): activate = self.pressed self.pressed = False self._draw() if activate and (getattr(event, 'keysym', '') == 'space' or (0 <= event.x < self.winfo_width() and 0 <= event.y < self.winfo_height())): self._activate() return 'break' def _activate(self, _event=None): if self.cget('state') != 'disabled': self.command() return 'break' def _draw(self, _event=None): self.delete('all') width, height = (self.winfo_width(), self.winfo_height()) if width < 10 or height < 10: return if self.backdrop is not None: self.create_image(0, 0, image=self.backdrop, anchor='nw') disabled = self.cget('state') == 'disabled' self.configure_cursor(disabled) highlight = max(self.hover_amount, float(self.focus_get() == self)) rim = '#7c7a68' if disabled else mix('#c6a460', '#f0d28d', highlight) face = '#2b3b4b' if disabled else '#183756' if self.pressed else mix('#254d7a', '#386b9f', self.hover_amount) light = '#465563' if disabled else '#142a43' if self.pressed else '#6595bd' shade = '#1c2833' if disabled else '#456b90' if self.pressed else '#112a45' def octagon(inset, cut, fill): x, y, r, b = (inset, inset, width - inset - 1, height - inset - 3) self.create_polygon(x + cut, y, r - cut, y, r, y + cut, r, b - cut, r - cut, b, x + cut, b, x, b - cut, x, y + cut, fill=fill, outline='') octagon(0, 7, '#080e17') octagon(1, 6, rim) octagon(3, 5, '#101e2e') octagon(4, 4, light) self.create_polygon(5, height - 10, width - 9, height - 10, width - 5, 8, width - 5, height - 10, width - 9, height - 7, 9, height - 7, fill=shade, outline='') octagon(7, 2, face) if not disabled: self.create_line(8, 2, width - 9, 2, fill='#f4dba2') self.create_line(8, height - 5, width - 9, height - 5, fill='#77572d') offset = 1 if self.pressed else 0 font = (self.typeface, 12 if self.primary else 10, 'bold') x, y = (width / 2 + offset, (height - 2) / 2 + offset) self.create_text(x + 1, y + 1, text=self.text, font=font, fill='#0b1725') self.create_text(x, y, text=self.text, font=font, fill='#84909a' if disabled else '#f4e3b9') def configure_cursor(self, disabled): super().configure(cursor='arrow' if disabled else 'hand2') class RealmCard(GameButton): def __init__(self, parent, *, name, detail, artwork, command): self.detail, self.artwork = (detail, artwork) self.colors = {'fg_color': '#1b2d40', 'border_color': '#526578', 'border_width': 1} self.art_size = None self.art_photo = None super().__init__(parent, text=name, command=command, width=300) def configure(self, cnf=None, **kwargs): if cnf: kwargs.update(cnf) for key in self.colors: if key in kwargs: self.colors[key] = kwargs.pop(key) return super().configure(**kwargs) config = configure def cget(self, key): return self.colors[key] if key in self.colors else super().cget(key) def _draw(self, _event=None): self.delete('all') width, height = (self.winfo_width(), self.winfo_height()) if width < 20 or height < 20: return disabled = self.cget('state') == 'disabled' self.configure_cursor(disabled) if self.backdrop is not None: self.create_image(0, 0, image=self.backdrop, anchor='nw') selected = self.colors['border_width'] == 2 hover = max(self.hover_amount, float(self.focus_get() == self)) if not disabled else 0 rim = mix(self.colors['border_color'], '#f6d997', hover) points = (7, 1, width - 8, 1, width - 2, 7, width - 2, height - 8, width - 8, height - 2, 7, height - 2, 1, height - 8, 1, 7) self.create_polygon(points, fill=self.colors['fg_color'], outline=rim, width=2 if selected else 1) size = (width - 12, 52) if size != self.art_size: self.art_size = size self.art_photo = ImageTk.PhotoImage(ImageOps.fit(self.artwork, size, method=Image.Resampling.NEAREST, centering=(0.5, 0.38))) self.create_image(6, 6, image=self.art_photo, anchor='nw') self.create_line(6, 58, width - 7, 58, fill=rim) self.create_line(9, 3, width - 10, 3, fill='#c4a86e' if selected else '#6c7e8c') self.create_line(9, height - 4, width - 10, height - 4, fill='#0c1927') offset = 1 if self.pressed else 0 x, y = (22 + offset, 80 + offset) self.create_polygon(x, y - 7, x + 7, y, x, y + 7, x - 7, y, fill='#d2b16c' if selected else '#122334', outline=rim) if selected: self.create_polygon(x, y - 3, x + 3, y, x, y + 3, x - 3, y, fill='#fff0be') self.create_text(39 + offset, 79 + offset, text=self.text, anchor='w', font=(self.typeface, 13, 'bold'), fill='#8d9aa6' if disabled else '#f1dfb2') self.create_text(18, 103, text=self.detail, anchor='w', font=(self.typeface, 9), fill='#81919e' if disabled else '#b6c6d4') ACTION_WIDTH = 190 class NoticeDialog(ctk.CTkToplevel): def __init__(self, parent, kind, text, action=None): super().__init__(parent, fg_color='#111d29') self.owner = parent height = 220 if len(text) < 240 else 330 self.geometry(f'580x{height}') self.minsize(520, 220) self.transient(parent) self.title(parent.t('Error' if kind == 'error' else 'Attention')) self.iconbitmap(str(asset('patcher-icon-v1.ico'))) self.color = SEVERITIES[kind][2] self.caption = parent.t('Error' if kind == 'error' else 'Attention') self.family = font_family(parent.locale) self.canvas = tk.Canvas(self, background='#111d29', borderwidth=0, highlightthickness=0) self.canvas.pack(fill='both', expand=True) self.message = tk.Text(self.canvas, background=SURFACE, foreground=TEXT, relief='flat', borderwidth=0, highlightthickness=0, font=(self.family, 10), wrap='word', padx=0, pady=0, selectbackground='#35516b', selectforeground='#ffffff') self.message.insert('1.0', parent.t(text)) self.message.configure(state='disabled') self.message_window = self.canvas.create_window(32, 74, window=self.message, anchor='nw') self.scrollbar = ctk.CTkScrollbar(self.canvas, command=self.message.yview, fg_color=SURFACE, button_color='#35516b', button_hover_color='#59758e', width=8) self.scroll_window = self.canvas.create_window(0, 74, window=self.scrollbar, anchor='nw', width=8, state='hidden') self.message.configure(yscrollcommand=self._scroll_position) self.ok = GameButton(self.canvas, text=parent.t('OK'), command=self.destroy, width=122) self.ok.typeface = self.family self.ok_window = self.canvas.create_window(0, 0, window=self.ok, anchor='ne') self.action = self.action_window = None if action is not None: label, callback = action def choose(): self.destroy() callback() self.action = GameButton(self.canvas, text=parent.t(label), command=choose, width=ACTION_WIDTH) self.action.typeface = self.family self.action_window = self.canvas.create_window(0, 0, window=self.action, anchor='ne') self.canvas.bind('', self._resize) self.bind('', lambda _: self.destroy()) self.bind('', lambda _: self.destroy()) self.update_idletasks() self._resize() self.update_idletasks() self.geometry(f'+{parent.winfo_rootx() + max(0, (parent.winfo_width() - 580) // 2)}+{parent.winfo_rooty() + max(0, (parent.winfo_height() - height) // 2)}') self.grab_set() self.ok.focus_set() def _resize(self, event=None): width, height = (max(520, self.canvas.winfo_width()), max(220, self.canvas.winfo_height())) panel = self.owner.dialog_renderer.render(width, height) self.art = ImageTk.PhotoImage(panel) self.canvas.delete('decoration') image = self.canvas.create_image(0, 0, image=self.art, anchor='nw', tags='decoration') self.canvas.tag_lower(image) self.canvas.create_polygon(50, 21, 61, 32, 50, 43, 39, 32, fill='#263b4c', outline=self.color, tags='decoration') self.canvas.create_text(50, 32, text='!', fill=self.color, font=(self.family, 10, 'bold'), tags='decoration') self.canvas.create_text(72, 32, text=self.caption, fill=self.color, font=(self.family, 15, 'bold'), anchor='w', tags='decoration') self.canvas.create_polygon(frame_points(24, 66, width - 24, height - 72), fill=SURFACE, outline=FRAME, tags='decoration') self.canvas.itemconfigure(self.message_window, width=width - 64, height=height - 150) self.canvas.coords(self.scroll_window, width - 36, 74) self.canvas.itemconfigure(self.scroll_window, height=height - 150) self.canvas.coords(self.ok_window, width - 32, height - 60) self.ok.backdrop = ImageTk.PhotoImage(panel.crop((width - 154, height - 60, width - 32, height - 18))) self.ok._draw() if self.action is not None: right = width - 32 - 122 - 12 self.canvas.coords(self.action_window, right, height - 60) self.action.backdrop = ImageTk.PhotoImage(panel.crop((right - ACTION_WIDTH, height - 60, right, height - 18))) self.action._draw() def _scroll_position(self, first, last): self.scrollbar.set(first, last) state = 'hidden' if float(last) - float(first) >= 0.9999 else 'normal' self.canvas.itemconfigure(self.scroll_window, state=state) def language_icon(code): scale = 3 image = Image.new('RGBA', (24 * scale, 16 * scale)) draw = ImageDraw.Draw(image) def polygon(points, fill): draw.polygon([(round(x * scale), round(y * scale)) for x, y in points], fill=fill) def rectangle(box, fill): draw.rectangle(tuple((round(value * scale) for value in box)), fill=fill) def star(x, y, radius, angle=-math.pi / 2): return [(x + math.cos(angle + n * math.pi / 5) * radius * (1 if n % 2 == 0 else 0.4), y + math.sin(angle + n * math.pi / 5) * radius * (1 if n % 2 == 0 else 0.4)) for n in range(10)] if code == 'en': rectangle((0, 0, 24, 16), '#193b75') for a, b in (((0, 0), (24, 16)), ((0, 16), (24, 0))): draw.line(tuple((round(v * scale) for point in (a, b) for v in point)), fill='white', width=4 * scale) draw.line(tuple((round(v * scale) for point in (a, b) for v in point)), fill='#c92c3a', width=scale) rectangle((9, 0, 15, 16), 'white') rectangle((0, 5, 24, 11), 'white') rectangle((10, 0, 14, 16), '#c92c3a') rectangle((0, 6, 24, 10), '#c92c3a') elif code == 'ru': rectangle((0, 0, 24, 5), '#ffffff') rectangle((0, 5, 24, 11), '#2459ba') rectangle((0, 11, 24, 16), '#d53843') elif code == 'pt': rectangle((0, 0, 24, 16), '#168449') polygon([(2, 8), (12, 1), (22, 8), (12, 15)], '#f4d248') draw.ellipse((8 * scale, 4 * scale, 16 * scale, 12 * scale), fill='#254a93') draw.line((8 * scale, 7 * scale, 16 * scale, 9 * scale), fill='white', width=scale) elif code == 'zh': rectangle((0, 0, 24, 16), '#d73735') polygon(star(5, 5, 3), '#ffdd58') for x, y in ((10, 2), (12, 5), (12, 8), (10, 11)): polygon(star(x, y, 1.2), '#ffdd58') else: draw.ellipse((3 * scale, 0, 20 * scale, 15 * scale), outline='#b9d4e4', width=scale) draw.ellipse((8 * scale, 0, 15 * scale, 15 * scale), outline='#b9d4e4', width=scale) draw.line((4 * scale, 7 * scale, 19 * scale, 7 * scale), fill='#b9d4e4', width=scale) return image.resize((24, 16), Image.Resampling.LANCZOS) class LanguageMenu(ctk.CTkOptionMenu): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.flag_images = {code: ImageTk.PhotoImage(language_icon(code), master=self) for code in ('auto', 'en', 'ru', 'pt', 'zh')} def refresh_flags(self, choices, selected): for index, code in enumerate(choices.values()): self._dropdown_menu.entryconfigure(index, image=self.flag_images[code], compound='left') self._text_label.configure(image=self.flag_images[selected], compound='left', padx=6) BG, PANEL, INK, MUTED = ('#111d29', '#1b2d40', '#f1dfb2', '#aab9c7') ACCENT, BORDER = ('#d2b16c', '#526578') COPY_LABEL = 'Separate Arinar copy (play both at once)' def copy_preference_path(preferences): return Path(preferences).with_name('copy-preference.json') def load_copy_preference(preferences): try: return bool(json.loads(copy_preference_path(preferences).read_text(encoding='utf-8'))['separate']) except (OSError, ValueError, KeyError, TypeError): return True def save_copy_preference(preferences, separate): path = copy_preference_path(preferences) path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps({'separate': bool(separate)}), encoding='utf-8') LOGINS_LABEL = 'Separate login per server' REGISTRY_KEY = 'Software\\ArinarReborn\\Launcher' LOGINS_VALUE = 'SeparateLogins' def load_logins_preference(key=REGISTRY_KEY): if os.name != 'nt': return True import winreg try: with winreg.OpenKey(winreg.HKEY_CURRENT_USER, key) as handle: value, kind = winreg.QueryValueEx(handle, LOGINS_VALUE) return bool(value) if kind == winreg.REG_DWORD else True except OSError: return True def save_logins_preference(enabled, key=REGISTRY_KEY): if os.name != 'nt': return import winreg with winreg.CreateKeyEx(winreg.HKEY_CURRENT_USER, key, 0, winreg.KEY_SET_VALUE) as handle: winreg.SetValueEx(handle, LOGINS_VALUE, 0, winreg.REG_DWORD, 1 if enabled else 0) def prepare_and_launch(client, selected, emit, *, start=subprocess.Popen, separate=False, copy_factory=ArinarCopy, accounts=None, force_login=False, separate_logins=True): executable = client.folder / 'warspear.exe' if not executable.is_file() or executable.is_symlink(): raise PatcherError('Choose the game folder containing warspear.exe and warspear.pak.') accounts = accounts or AccountConfigs side = 'arinar' if selected == 'Arinar Reborn' else 'official' def swap_login(): if separate_logins: accounts().use(side, emit, force=force_login) else: accounts().forget() if selected == 'Arinar Reborn' and separate: copy = copy_factory(client.folder).prepare(emit) swap_login() start([str(copy)], cwd=copy.parent) return f'Game started for {selected}.' if selected == 'Arinar Reborn': client.apply(emit) elif not separate or (client.root and ((client.root / STATE).exists() or (client.root / '.arinar-switch.json').exists())): client.restore(emit) swap_login() start([str(executable)], cwd=client.folder) return f'Game started for {selected}.' class Patcher(ctk.CTk): def __init__(self, detect=True, preferences=None): ctk.set_appearance_mode('dark') if os.name == 'nt': import ctypes ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID('ArinarReborn.Patcher') super().__init__(fg_color=BG) self.preferences = preferences if preferences is not None else preference_path() self.language_mode = load_preference(self.preferences) self.locale = system_language() if self.language_mode == 'auto' else self.language_mode self.language_label = tk.StringVar() if os.name == 'nt': self.iconbitmap(str(asset('patcher-icon-v1.ico'))) else: self.app_icon = ImageTk.PhotoImage(Image.open(asset('patcher-icon-v1.png'))) self.iconphoto(True, self.app_icon) self.title('Arinar Reborn | Launcher') self.geometry('860x590') self.minsize(780, 570) self.jobs = queue.Queue() self.busy = False self.controls = [] self.card_jobs = {} self.intro_job = None self.notice_window = None self.logo_offset = 6.0 self.manual_folder = False self.current_mode = 'Unknown' self.mode_checking = False self.next_mode_check = 0 self.mode_detection_enabled = detect self.selection_touched = False self.initial_mode_selected = False self.client_path = tk.StringVar() self.server = tk.StringVar(value='Arinar Reborn') self.separate_copy = tk.BooleanVar(value=load_copy_preference(self.preferences)) self.separate_logins = tk.BooleanVar(value=load_logins_preference()) self.status_kind = 'working' if detect else 'info' self.status = tk.StringVar(value='Looking for your installed game...' if detect else 'Choose a game folder to get started.') self.protocol('WM_DELETE_WINDOW', self.close) self._build() self._refresh_text() self.server.trace_add('write', self._selection_changed) self._selection_changed() self.after_idle(self._animate_logo) self.after(100, self._drain) if detect: threading.Thread(target=self._detect, daemon=True).start() def _label(self, parent, text, size=13, color=INK, **kwargs): return ctk.CTkLabel(parent, text=text, text_color=color, anchor='w', font=('Bahnschrift', size), **kwargs) def t(self, text): return translate(text, self.locale) def _language_choices(self): return {self.t('Automatic'): 'auto', **{label: code for code, label in LABELS.items()}} def _change_language(self, label): self.language_mode = self._language_choices()[label] self.locale = system_language() if self.language_mode == 'auto' else self.language_mode self._refresh_text() try: save_preference(self.preferences, self.language_mode) except OSError: self._set_status('Language changed for this session. Could not save preference.', 'warning') def _refresh_text(self): family = font_family(self.locale) version = launcher_version() self.title('Arinar Reborn | ' + self.t('GAME LAUNCHER') + ('' if version == 'dev' else ' ' + version)) self.language_label.set(self.t('Automatic') if self.language_mode == 'auto' else LABELS[self.locale]) self.language_menu.configure(values=list(self._language_choices()), font=(family, 12), dropdown_font=(family, 13)) self.language_menu.refresh_flags(self._language_choices(), self.language_mode) for item, text, size, weight in ((self.heading_item, 'Choose your realm', 16, 'bold'), (self.folder_label_item, 'Game folder', 10, 'normal'), (self.reminder_item, 'Play applies your selected server. Close the game before switching.', 9, 'normal'), (self.important_title, 'Important', 10, 'bold')): self.main.itemconfigure(item, text=self.t(text), font=(family, size, weight)) self.main.itemconfigure(self.status_item, font=(family, 10)) self._status_changed() self.folder_entry.configure(font=(family, 12)) self.copy_check.configure(text=self.t(COPY_LABEL), font=(family, 10)) self.logins_check.configure(text=self.t(LOGINS_LABEL), font=(family, 10)) self._place_checks() for button, text in ((self.folder_button, 'Change folder'), (self.play_button, 'Play')): button.text, button.typeface = (self.t(text), family) button._draw() for name, card in self.server_cards.items(): card.text, card.typeface = (self.t(name), family) card.detail = self.t('Official Warspear servers' if name == 'Original server' else 'Independent community realm') card._draw() self._resize_header(type('Size', (), {'width': max(780, self.winfo_width())})()) def _button(self, parent, text, command, primary=False, **kwargs): button = GameButton(parent, text=text, command=command, primary=primary, **kwargs) self.controls.append(button) return button def _build(self): self.grid_columnconfigure(0, weight=1) self.grid_rowconfigure(1, weight=1) with Image.open(asset('blue-steel-panel.png')) as artwork: self.panel_source = artwork.copy() with Image.open(asset('blue-steel-panel-plain-top.png')) as artwork: self.main_panel_source = artwork.copy() self.header_renderer = PanelRenderer(self.panel_source) self.main_renderer = PanelRenderer(self.main_panel_source) self.dialog_renderer = PanelRenderer(self.panel_source, scale=0.3) with Image.open(asset('arinar-wordmark-v1.webp')) as artwork: self.logo_art = ImageTk.PhotoImage(artwork.resize((252, 84), Image.Resampling.LANCZOS)) self.header = tk.Canvas(self, height=104, background=BG, highlightthickness=0, borderwidth=0) self.header.grid(row=0, column=0, sticky='ew') self.header.bind('', self._resize_header) self.language_menu = LanguageMenu(self.header, variable=self.language_label, values=list(self._language_choices()), command=self._change_language, width=182, height=28, corner_radius=3, fg_color='#20374d', button_color='#304d65', button_hover_color='#41617c', text_color=INK, dropdown_fg_color=BG, dropdown_hover_color='#304d65', dropdown_text_color=INK) with Image.open(asset('kingdom-panorama.png')) as artwork: self.realm_art_source = artwork.copy() self.main = tk.Canvas(self, background=BG, highlightthickness=0, borderwidth=0) self.main.grid(row=1, column=0, sticky='nsew') self.panel_item = self.main.create_image(0, 0, anchor='nw') self.heading_item = self.main.create_text(28, 28, text='Choose your realm', fill=INK, font=('Bahnschrift', 16, 'bold'), anchor='w') self.server_cards = {} self.card_windows = [] for column, (name, detail) in enumerate([('Original server', 'Official Warspear servers'), ('Arinar Reborn', 'Independent community realm')]): half = self.realm_art_source.width // 2 artwork = self.realm_art_source.crop((column * half, 0, (column + 1) * half, self.realm_art_source.height)) card = RealmCard(self.main, name=name, detail=detail, artwork=artwork, command=lambda value=name: self._choose_server(value)) self.controls.append(card) self.server_cards[name] = card self.card_windows.append(self.main.create_window(0, 0, window=card, anchor='nw', height=120)) self.folder_label_item = self.main.create_text(28, 194, text='Game folder', fill=MUTED, font=('Bahnschrift', 10), anchor='w') self.copy_check = ctk.CTkCheckBox(self.main, text=COPY_LABEL, variable=self.separate_copy, command=self._copy_choice_changed, font=('Bahnschrift', 10), text_color=MUTED, fg_color=ACCENT, hover_color='#e0c27f', border_color=BORDER, checkmark_color=BG, checkbox_width=16, checkbox_height=16, border_width=1, corner_radius=2, bg_color=BG) self.controls.append(self.copy_check) self.copy_window = self.main.create_window(0, 194, window=self.copy_check, anchor='e') self.logins_check = ctk.CTkCheckBox(self.main, text=LOGINS_LABEL, variable=self.separate_logins, command=self._logins_choice_changed, font=('Bahnschrift', 10), text_color=MUTED, fg_color=ACCENT, hover_color='#e0c27f', border_color=BORDER, checkmark_color=BG, checkbox_width=16, checkbox_height=16, border_width=1, corner_radius=2, bg_color=BG) self.controls.append(self.logins_check) self.logins_window = self.main.create_window(0, 194, window=self.logins_check, anchor='e') self.folder_entry = ctk.CTkEntry(self.main, textvariable=self.client_path, height=38, corner_radius=2, fg_color='#101b27', bg_color=BG, border_color=BORDER, text_color=MUTED, font=('Bahnschrift', 12), state='readonly') self.folder_window = self.main.create_window(28, 214, window=self.folder_entry, anchor='nw', height=38) self.folder_button = self._button(self.main, 'Change folder', self.browse, width=132) self.folder_button_window = self.main.create_window(0, 212, window=self.folder_button, anchor='ne') self.progress = ctk.CTkProgressBar(self.main, height=2, corner_radius=0, fg_color=BORDER, bg_color=BG, progress_color=ACCENT) self.progress_window = self.main.create_window(28, 276, window=self.progress, anchor='nw', height=2) self.progress.set(0) self.status_panel = self.main.create_polygon(frame_points(28, 292, 606, 378), width=1) self.status_edge = self.main.create_line(29, 302, 29, 368, width=2) self.status_icon = self.main.create_polygon(49, 301, 58, 310, 49, 319, 40, 310, width=1) self.status_symbol = self.main.create_text(49, 310, font=('Bahnschrift', 9, 'bold')) self.status_title = self.main.create_text(66, 310, anchor='w', font=('Bahnschrift', 10, 'bold')) self.status_item = self.main.create_text(42, 330, text=self.status.get(), fill=MUTED, font=('Bahnschrift', 10), anchor='nw', justify='left') self.status.trace_add('write', self._status_changed) self.play_button = self._button(self.main, 'Play', self.play, primary=True, width=170) self.play_window = self.main.create_window(0, 310, window=self.play_button, anchor='ne') self.important_panel = self.main.create_polygon(frame_points(28, 390, 832, 444), fill=SURFACE, outline=FRAME) self.main.create_line(29, 400, 29, 434, fill='#c4aa73', width=2) self.main.create_polygon(49, 399, 58, 408, 49, 417, 40, 408, fill='#263b4c', outline='#b7a074') self.main.create_text(49, 408, text='i', fill='#e3cd9e', font=('Bahnschrift', 9, 'bold')) self.important_title = self.main.create_text(66, 408, text='Important', anchor='w', fill='#f1d596') self.reminder_item = self.main.create_text(42, 423, text='Play applies your selected server. Close the game before switching.', fill=TEXT, font=('Bahnschrift', 9), anchor='nw') self.main.bind('', self._resize_main) def _status_changed(self, *_): self._render_notices() def _set_status(self, text, kind): self.status_kind = kind self.status.set(text) def _render_notices(self): width = max(780, self.main.winfo_width()) title, symbol, accent = SEVERITIES[self.status_kind] family = font_family(self.locale) self.main.coords(self.status_panel, *frame_points(28, 292, width - 226, 378)) self.main.itemconfigure(self.status_panel, fill=SURFACE, outline=FRAME) self.main.itemconfigure(self.status_edge, fill=accent) self.main.itemconfigure(self.status_icon, fill='#263b4c', outline=accent) self.main.itemconfigure(self.status_symbol, text=symbol, fill=accent, font=(family, 9, 'bold')) self.main.itemconfigure(self.status_title, text=self.t(title), fill=accent, font=(family, 10, 'bold')) self.main.itemconfigure(self.status_item, text=self.t(self.status.get()), fill=TEXT, width=width - 282) text = self.t(self.status.get()) while self.main.bbox(self.status_item)[3] > 371 and text: text = text[:-8] self.main.itemconfigure(self.status_item, text=text.rstrip() + '…') self.main.coords(self.important_panel, *frame_points(28, 390, width - 28, 444)) self.main.itemconfigure(self.reminder_item, width=width - 84) def _resize_header(self, event): width = max(1, event.width) self.header_art = ImageTk.PhotoImage(self.header_renderer.header(width)) self.header.delete('all') self.header.create_image(0, 0, image=self.header_art, anchor='nw') self.header.create_image(28, 52 + self.logo_offset, image=self.logo_art, anchor='w', tags='wordmark') family = font_family(self.locale) self.header.create_text(width - 228, 52, text=self.t('Language'), fill=MUTED, font=(family, 9), anchor='e') self.header.create_window(width - 30, 52, window=self.language_menu, anchor='e', width=182, height=28) def _animate_logo(self): began = time.monotonic() def frame(): self.intro_job = None progress = min(1.0, (time.monotonic() - began) / 0.32) self.logo_offset = 6 * (1 - progress) ** 3 self.header.coords('wordmark', 28, 52 + self.logo_offset) if progress < 1: self.intro_job = self.after(16, frame) frame() def _resize_main(self, event): width, height = (max(1, event.width), max(1, event.height)) panel = self.main_renderer.render(width, height) self.panel_art = ImageTk.PhotoImage(panel) self.main.itemconfigure(self.panel_item, image=self.panel_art) card_width = (width - 68) // 2 for column, item in enumerate(self.card_windows): self.main.coords(item, 28 + column * (card_width + 12), 54) self.main.itemconfigure(item, width=card_width) for column, card in enumerate(self.server_cards.values()): x = 28 + column * (card_width + 12) card.backdrop = ImageTk.PhotoImage(panel.crop((x, 54, x + card_width, 174))) card._draw() self.main.itemconfigure(self.folder_window, width=width - 228) self.main.coords(self.copy_window, width - 28, 194) self._place_checks(width) self.main.coords(self.folder_button_window, width - 28, 212) self.main.itemconfigure(self.progress_window, width=width - 56) self.main.coords(self.play_window, width - 28, 310) self._render_notices() for button, x, y, button_width, button_height in ((self.folder_button, width - 160, 212, 132, 42), (self.play_button, width - 198, 310, 170, 50)): button.backdrop = ImageTk.PhotoImage(panel.crop((x, y, x + button_width, y + button_height))) button._draw() def _selection_changed(self, *_): for name, card in self.server_cards.items(): selected = name == self.server.get() if name in self.card_jobs: self.after_cancel(self.card_jobs.pop(name)) start, target = (card.cget('fg_color'), '#233f5b' if selected else PANEL) card.configure(border_color=ACCENT if selected else BORDER, border_width=2 if selected else 1) self._animate_card(name, card, start, target) self.play_button.configure(state='normal' if self.client_path.get() and (not self.busy) else 'disabled') def _place_checks(self, width=None): width = width or self.main.winfo_width() self.update_idletasks() self.main.coords(self.logins_window, width - 28 - self.copy_check.winfo_reqwidth() - 18, 194) def _logins_choice_changed(self): try: save_logins_preference(self.separate_logins.get()) except OSError: pass def _copy_choice_changed(self): try: save_copy_preference(self.preferences, self.separate_copy.get()) except OSError: pass def _choose_server(self, value): if not self.busy: self.selection_touched = True self.server.set(value) def _check_mode(self): if self.busy or self.mode_checking: return self.mode_checking = True folder = self.client_path.get() def work(): mode = Client(folder or Path.cwd()).current_mode() self.jobs.put(('mode', (folder, mode))) threading.Thread(target=work, daemon=True).start() def _animate_card(self, name, card, start, target): began = time.monotonic() def frame(): self.card_jobs.pop(name, None) progress = min(1.0, (time.monotonic() - began) / 0.18) card.configure(fg_color=mix(start, target, 1 - (1 - progress) ** 3)) if progress < 1: self.card_jobs[name] = self.after(16, frame) frame() def destroy(self): for job in self.card_jobs.values(): self.after_cancel(job) if self.intro_job is not None: self.after_cancel(self.intro_job) super().destroy() def _detect(self): try: folder = load_game_folder() if folder is None: folder = find_client(candidate_locations((Path(__file__).parent, Path.cwd()))) log.info('game folder found: %s', folder) self.jobs.put(('detected', folder)) except Exception: log.exception('game folder detection failed') self.jobs.put(('detected', None)) def browse(self): folder = filedialog.askdirectory(title=self.t('Choose your Warspear game folder'), initialdir=self.client_path.get() or None) if folder: self.manual_folder = True log.info('game folder chosen: %s (client %s)', folder, client_version(Path(folder) / 'warspear.pak')) self.client_path.set(folder) self._set_status('Folder selected. Ready to play.', 'success') try: save_game_folder(folder) except OSError: self._set_status('Could not save game folder preference.', 'warning') self._selection_changed() def play(self, force_login=False): if self.busy or not self.client_path.get(): return client, selected = (Client(self.client_path.get()), self.server.get()) separate = self.separate_copy.get() separate_logins = self.separate_logins.get() self.busy = True self._set_status('Checking the client...', 'working') for widget in self.controls: widget.configure(state='disabled') self.progress.configure(mode='indeterminate') self.progress.start() def step(text): log.info(' %s', text) self.jobs.put(('progress', text)) def work(): try: log.info('Play: %s | folder %s | client %s | separate copy %s | separate logins %s%s', selected, client.folder, client_version(client.folder / 'warspear.pak'), separate, separate_logins, ' | switch anyway' if force_login else '') result = prepare_and_launch(client, selected, step, separate=separate, force_login=force_login, separate_logins=separate_logins) log.info(' %s', result) self.jobs.put(('done', result)) except LoginSwapBlocked as exc: log.warning(' login swap blocked: %s', exc) self.jobs.put(('login_blocked', str(exc))) except PatcherError as exc: log.error(' %s', exc, exc_info=True) self.jobs.put((exc.kind, str(exc))) except Exception as exc: log.exception(' unexpected error') self.jobs.put(('error', str(exc))) threading.Thread(target=work, daemon=True).start() def _drain(self): while not self.jobs.empty(): kind, text = self.jobs.get_nowait() if kind == 'mode': self.mode_checking = False folder, mode = text if not self.busy and folder == self.client_path.get(): self.current_mode = mode if not self.initial_mode_selected and mode != 'Unknown': self.initial_mode_selected = True if not self.selection_touched: self.server.set(mode) continue if kind == 'detected': if not self.manual_folder: self.client_path.set(str(text) if text else '') self._set_status('Game found. Ready to play.' if text else 'Game not found. Choose its folder to continue.', 'success' if text else 'error') self._selection_changed() continue self._set_status(text, 'warning' if kind in ('warning', 'login_blocked') else 'error' if kind == 'error' else 'success' if kind == 'done' else 'working') if kind != 'progress': self.next_mode_check = 0 self.busy = False self.progress.stop() self.progress.configure(mode='determinate') self.progress.set(0) for widget in self.controls: widget.configure(state='normal') self._selection_changed() if kind == 'login_blocked': self._show_dialog('warning', text, action=('Switch anyway', lambda: self.play(force_login=True))) elif kind in ('error', 'warning'): self._show_dialog(kind, text, action=('Open log folder', open_log_folder)) if self.mode_detection_enabled and time.monotonic() >= self.next_mode_check: self.next_mode_check = time.monotonic() + 3 self._check_mode() self.after(100, self._drain) def close(self): if self.busy: self._set_status('Wait for the current operation to finish before closing.', 'warning') self._show_dialog('warning', 'Wait for the current operation to finish before closing.') return self.destroy() def _show_dialog(self, kind, text, action=None): if self.notice_window is not None and self.notice_window.winfo_exists(): self.notice_window.destroy() self.notice_window = NoticeDialog(self, kind, text, action=action) return self.notice_window def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--inspect', type=Path, help='Inspect a client without changing files') parser.add_argument('--smoke-test', action='store_true', help='Build widgets without touching a client') args = parser.parse_args() if args.inspect: print(json.dumps(Client(args.inspect).inspect(), indent=2)) return if not args.smoke_test: start_log() app = Patcher(detect=not args.smoke_test) if args.smoke_test: app.update() activations = [] app.play_button.command = lambda: activations.append('play') assert app.play_button.cget('state') == 'disabled' app.play_button.event_generate('', x=20, y=20) app.play_button.event_generate('', x=20, y=20) assert not activations app.jobs.put(('detected', None)) app._drain() assert app.status_kind == 'error' and app.play_button.cget('state') == 'disabled' app.jobs.put(('detected', Path('C:/Games/Warspear'))) app._drain() assert app.play_button.cget('state') == 'normal' assert app.status_kind == 'success' app.play_button.event_generate('', x=20, y=20) app.play_button.event_generate('', x=20, y=20) assert activations == ['play'] app.play_button.focus_force() app.update() app.play_button.event_generate('') app.play_button.event_generate('') app.play_button.event_generate('') assert activations == ['play', 'play', 'play'] app.play_button.event_generate('', x=20, y=20) app.play_button.event_generate('') app.play_button.event_generate('', x=20, y=20) assert activations == ['play', 'play', 'play'] app.manual_folder = True app.client_path.set('C:/Manual') app.jobs.put(('detected', Path('C:/Other'))) app._drain() assert app.client_path.get() == 'C:/Manual' original_card = app.server_cards['Original server'] original_card.configure(state='disabled') original_card.event_generate('', x=20, y=20) original_card.event_generate('', x=20, y=20) assert app.server.get() == 'Arinar Reborn' original_card.configure(state='normal') original_card.event_generate('', x=20, y=20) original_card.event_generate('', x=20, y=20) assert app.server.get() == 'Original server' arinar_card = app.server_cards['Arinar Reborn'] arinar_card.focus_force() app.update() arinar_card.event_generate('') assert app.server.get() == 'Arinar Reborn' app.server.set('Original server') assert app.server_cards['Original server'].cget('border_color') == ACCENT for width, height in ((860, 590), (780, 570)): app.geometry(f'{width}x{height}') app.update_idletasks() assert app.play_button.winfo_rooty() + app.play_button.winfo_height() <= app.winfo_rooty() + app.winfo_height() app.update() app.play_button.event_generate('') app.after(380, app.quit) app.mainloop() assert app.play_button.hover_amount == 1.0 assert app.play_button.hover_job is None assert not app.card_jobs and app.intro_job is None assert app.logo_offset == 0.0 app.play_button.event_generate('') app.play_button.configure(state='disabled') assert app.play_button.hover_job is None and app.play_button.hover_amount == 0.0 import tempfile with tempfile.TemporaryDirectory() as folder: app.preferences = Path(folder) / 'preferences.json' selected_server, selected_folder = (app.server.get(), app.client_path.get()) for language, label in LABELS.items(): menu = app.language_menu._dropdown_menu index = list(app._language_choices().values()).index(language) assert menu.entrycget(index, 'image') menu.invoke(index) app.update_idletasks() assert app.language_menu._text_label.cget('image') == str(app.language_menu.flag_images[language]) assert app.locale == language and load_preference(app.preferences) == language assert app.play_button.text == app.t('Play') assert app.main.itemcget(app.status_item, 'text') == app.t(app.status.get()) assert app.server.get() == selected_server and app.client_path.get() == selected_folder for kind, title in (('error', 'Error'), ('success', 'Ready'), ('working', 'Working'), ('warning', 'Attention'), ('info', 'Information')): app._set_status('Game not found. Choose its folder to continue.', kind) assert app.main.itemcget(app.status_title, 'text') == app.t(title) assert app.main.itemcget(app.important_title, 'text') == app.t('Important') assert app.main.bbox(app.reminder_item)[3] <= 444 app.update_idletasks() logins, copy = (app.main.bbox(app.logins_window), app.main.bbox(app.copy_window)) assert logins[2] <= copy[0], language assert logins[0] >= app.main.bbox(app.folder_label_item)[2], language for kind in ('error', 'warning'): message = 'Could not download the server patch. Check your connection and try again.' dialog = app._show_dialog(kind, message) app.update_idletasks() assert dialog.message.get('1.0', 'end-1c') == app.t(message) assert len(dialog.canvas.find_withtag('decoration')) == 5 assert float(dialog.canvas.itemcget(dialog.message_window, 'width')) >= 440 assert dialog.grab_current() == dialog assert dialog.title() == app.t('Error' if kind == 'error' else 'Attention') dialog.ok._activate() assert not dialog.winfo_exists() chosen = [] dialog = app._show_dialog('warning', 'Close the game before switching servers, so your saved login is kept.', action=('Switch anyway', lambda: chosen.append(True))) app.update_idletasks() ok_left = dialog.canvas.bbox(dialog.ok_window)[0] assert dialog.canvas.bbox(dialog.action_window)[2] <= ok_left assert dialog.canvas.bbox(dialog.action_window)[0] >= 24 dialog.action._activate() assert chosen == [True] and (not dialog.winfo_exists()) for card in app.server_cards.values(): for item in card.find_all(): if card.type(item) == 'text': bounds = card.bbox(item) assert bounds[0] >= 0 and bounds[2] <= card.winfo_width(), (language, card.text) app._change_language(app.t('Automatic')) assert load_preference(app.preferences) == 'auto' app._set_status('Long diagnostic ' * 100, 'error') assert app.main.bbox(app.status_item)[3] <= 371 assert app.main.itemcget(app.status_item, 'text').endswith('…') app.selection_touched = False app.initial_mode_selected = False app.jobs.put(('mode', (app.client_path.get(), 'Original server'))) app._drain() assert app.current_mode == 'Original server' and app.server.get() == 'Original server' app._choose_server('Arinar Reborn') app.jobs.put(('mode', (app.client_path.get(), 'Original server'))) app._drain() assert app.current_mode == 'Original server' and app.server.get() == 'Arinar Reborn' print('Launcher branding, layout, input and finite animations passed; no client changed.') app.destroy() else: app.mainloop() if __name__ == '__main__': main()