Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b07c35e879 | ||
|
|
0baa84dbed | ||
|
|
f1821b40ff | ||
|
|
608faea597 | ||
|
|
827395a0ed | ||
|
|
3fdfe0fffc | ||
|
|
f9be296cac | ||
|
|
b2e79a3571 | ||
|
|
2d808ae555 | ||
|
|
732c688e3a | ||
|
|
7611dc16c6 | ||
|
|
010f757589 | ||
|
|
55d591ac4f | ||
|
|
95ad8bdedc | ||
|
|
7fe5208333 | ||
|
|
c2e24ff327 | ||
|
|
1b63f2dd0c | ||
|
|
7cf76aaf97 | ||
|
|
b126910229 | ||
|
|
96e29eb528 | ||
|
|
3ec7b756de | ||
|
|
f640aaf6af | ||
|
|
93b9e2f638 | ||
|
|
2030cea983 | ||
|
|
793d960b65 | ||
|
|
ef74003283 | ||
|
|
81a43ca9bd | ||
|
|
f10921840e | ||
|
|
425268ade2 | ||
|
|
743ab69455 | ||
|
|
502c5e4b1b | ||
|
|
44881267cf | ||
|
|
0433ff6cee | ||
|
|
8c984f1b15 | ||
|
|
319c4453fd | ||
|
|
9ec692833e | ||
|
|
1a9297e3e5 | ||
|
|
625ee0a223 | ||
|
|
991a03b829 | ||
|
|
8eba7d21d0 | ||
|
|
eed297a226 | ||
|
|
9017aaac25 | ||
|
|
18f35ed08b | ||
|
|
f5b62e9ec2 | ||
|
|
ae55e69700 | ||
|
|
723cfdcc4c | ||
|
|
fb2f2cf020 | ||
|
|
a7d2ea994e | ||
|
|
572ce2a08a | ||
|
|
d48e50a0b4 | ||
|
|
7321bde951 | ||
|
|
f5e10a8b0d | ||
|
|
61e659ea2e | ||
|
|
728266cdb3 | ||
|
|
055dc04bb1 | ||
|
|
3b5432ecdd | ||
|
|
415ed948ad | ||
|
|
b6e99d01af | ||
|
|
6b53afa238 | ||
|
|
b27d5f31ae | ||
|
|
e62cd1463a | ||
|
|
3bab2d12c7 | ||
|
|
a14ad4ff70 | ||
|
|
39fd02d358 | ||
|
|
d7d0ef4516 | ||
|
|
4b540302dc | ||
|
|
ff7c36208d | ||
|
|
4f3355e633 | ||
|
|
bb637f48f6 |
No files matched your search
@@ -0,0 +1,2 @@
|
||||
seh
|
||||
testser
|
||||
+16
-5
@@ -40,9 +40,20 @@ env/
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# Logs
|
||||
*.log
|
||||
.ruff_cache/
|
||||
.mypy_cache/
|
||||
.pytest_cache/
|
||||
.tox/
|
||||
|
||||
# Temporary files
|
||||
*.tmp
|
||||
*.bak
|
||||
# Test and coverage
|
||||
.coverage
|
||||
htmlcov/
|
||||
|
||||
# RPM / package build artifacts
|
||||
*.rpm
|
||||
*.src.rpm
|
||||
RPMS/
|
||||
SRPMS/
|
||||
BUILD/
|
||||
BUILDROOT/
|
||||
*.spec~
|
||||
@@ -0,0 +1,111 @@
|
||||
default_language_version:
|
||||
python: python3
|
||||
|
||||
exclude: |
|
||||
(?x)(
|
||||
^\.git/|
|
||||
^__pycache__/|
|
||||
.*\.pyc$
|
||||
)
|
||||
|
||||
repos:
|
||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||
rev: v5.0.0
|
||||
hooks:
|
||||
- id: trailing-whitespace
|
||||
- id: end-of-file-fixer
|
||||
- id: check-yaml
|
||||
- id: check-json
|
||||
- id: check-toml
|
||||
- id: check-added-large-files
|
||||
args: ["--maxkb=1024"]
|
||||
- id: check-merge-conflict
|
||||
- id: check-symlinks
|
||||
- id: check-executables-have-shebangs
|
||||
- id: check-shebang-scripts-are-executable
|
||||
- id: mixed-line-ending
|
||||
args: ["--fix=lf"]
|
||||
- id: check-case-conflict
|
||||
- id: check-ast
|
||||
- id: debug-statements
|
||||
- id: detect-private-key
|
||||
|
||||
- repo: local
|
||||
hooks:
|
||||
- id: bash-syntax-check
|
||||
name: bash syntax check
|
||||
entry: bash -n
|
||||
language: system
|
||||
files: |
|
||||
(?x)(
|
||||
^winehelper$|
|
||||
^dependencies\.sh$|
|
||||
^autoinstall/|
|
||||
^manualinstall/|
|
||||
^testinstall/|
|
||||
^hiden_scripts/|
|
||||
^database/.*\.whdb$
|
||||
)
|
||||
types: [shell]
|
||||
|
||||
- id: py-compile
|
||||
name: python compile
|
||||
entry: python3 -m py_compile
|
||||
language: system
|
||||
types: [python]
|
||||
|
||||
- id: shellcheck
|
||||
name: shellcheck
|
||||
entry: shellcheck
|
||||
args: ["--severity=error", "--exclude=SC2068,SC2145,SC2199"]
|
||||
language: system
|
||||
files: |
|
||||
(?x)(
|
||||
^winehelper$|
|
||||
^dependencies\.sh$|
|
||||
^autoinstall/|
|
||||
^manualinstall/|
|
||||
^testinstall/|
|
||||
^hiden_scripts/|
|
||||
^database/.*\.whdb$
|
||||
)
|
||||
types: [shell]
|
||||
|
||||
- repo: https://github.com/scop/pre-commit-shfmt
|
||||
rev: v3.10.0-1
|
||||
hooks:
|
||||
- id: shfmt
|
||||
args: ["--write", "--indent", "4", "--case-indent", "--space-redirects"]
|
||||
files: |
|
||||
(?x)(
|
||||
^winehelper$|
|
||||
^dependencies\.sh$|
|
||||
^autoinstall/|
|
||||
^manualinstall/|
|
||||
^testinstall/|
|
||||
^hiden_scripts/|
|
||||
^database/.*\.whdb$
|
||||
)
|
||||
types: [shell]
|
||||
|
||||
- repo: https://github.com/astral-sh/ruff-pre-commit
|
||||
rev: v0.11.4
|
||||
hooks:
|
||||
- id: ruff
|
||||
args: ["--fix", "--show-fixes"]
|
||||
- id: ruff-format
|
||||
|
||||
- repo: https://github.com/codespell-project/codespell
|
||||
rev: v2.3.0
|
||||
hooks:
|
||||
- id: codespell
|
||||
args: ["--ignore-words", ".codespell-ignorewords"]
|
||||
|
||||
- repo: local
|
||||
hooks:
|
||||
- id: sha256sum-list-check
|
||||
name: sha256sum.list format check
|
||||
entry: scripts/check_sha256sum_list.sh
|
||||
language: script
|
||||
files: ^sha256sum\.list$
|
||||
pass_filenames: false
|
||||
@@ -15,8 +15,8 @@ WineHelper — инструмент для упрощения установки
|
||||
## Технологический стек
|
||||
|
||||
### Основные технологии
|
||||
- **Bash** — основной язык для CLI-интерфейса (~2692 строк в главном скрипте)
|
||||
- **Python 3** — графический интерфейс с использованием PyQt5
|
||||
- **Bash** — основной язык для CLI-интерфейса (~3075 строк в главном скрипте)
|
||||
- **Python 3** — графический интерфейс с использованием PyQt5 (~3413 строк в `winehelper_gui.py` и модули `winehelperqt/`)
|
||||
- **Wine** — запуск Windows-приложений (поддерживаются различные версии: vanilla, staging, Proton, tkg, crossover)
|
||||
- **DXVK/VKD3D** — трансляция DirectX → Vulkan
|
||||
|
||||
@@ -39,12 +39,15 @@ winehelper/
|
||||
├── winehelper_gui.py # GUI на PyQt5 (точка входа)
|
||||
├── winehelperqt/ # Python-модуль GUI
|
||||
│ ├── __init__.py # Экспорты основных классов
|
||||
│ ├── logger.py # Единый логгер (get_logger/setup_logger), вывод в консоль
|
||||
│ ├── dialogs/ # Диалоговые окна
|
||||
│ │ ├── base_version_dialog.py
|
||||
│ │ ├── component_version.py
|
||||
│ │ ├── create_prefix.py # Создание префикса
|
||||
│ │ ├── file_associations.py
|
||||
│ │ ├── settings.py # Настройки
|
||||
│ │ ├── noexec_warning.py # Предупреждение о noexec
|
||||
│ │ ├── settings.py # Настройки префикса
|
||||
│ │ ├── windows_version.py # Выбор версии Windows
|
||||
│ │ ├── wine_version.py # Выбор версии Wine
|
||||
│ │ └── winetricks_manager.py
|
||||
│ ├── parsers/ # Парсеры
|
||||
@@ -52,14 +55,26 @@ winehelper/
|
||||
│ │ ├── sha256_parser.py # Парсинг sha256sum.list
|
||||
│ │ └── winetricks_parser.py
|
||||
│ ├── services/ # Бизнес-логика
|
||||
│ │ ├── application_installer.py
|
||||
│ │ ├── app_launcher.py # Запуск приложений
|
||||
│ │ ├── desktop_file_manager.py
|
||||
│ │ ├── prefix_manager.py # Управление префиксами
|
||||
│ │ ├── process_handler.py
|
||||
│ │ ├── script_manager.py
|
||||
│ │ ├── settings_manager.py
|
||||
│ │ └── winetricks_service.py
|
||||
│ ├── utils/ # Утилиты
|
||||
│ │ └── log_handler.py # Обработка логов
|
||||
│ │ ├── cache_service.py
|
||||
│ │ ├── desktop_entry.py
|
||||
│ │ ├── dialog_utils.py
|
||||
│ │ ├── environment.py
|
||||
│ │ ├── export_utils.py
|
||||
│ │ ├── grid_utils.py
|
||||
│ │ ├── log_handler.py # Обработка логов
|
||||
│ │ ├── prefix_info.py # Построение HTML с информацией о префиксе
|
||||
│ │ ├── process_utils.py
|
||||
│ │ └── version_utils.py
|
||||
│ └── widgets/ # Кастомные виджеты
|
||||
│ ├── icon_manager.py
|
||||
│ └── __init__.py
|
||||
├── autoinstall/ # Скрипты автоматической установки (43 приложения)
|
||||
├── manualinstall/ # Скрипты ручной установки (9 приложений)
|
||||
├── testinstall/ # Тестовые скрипты установки
|
||||
@@ -68,9 +83,14 @@ winehelper/
|
||||
│ ├── gui/ # Иконки приложения (SVG)
|
||||
│ └── handbook/ # Скриншоты для документации
|
||||
├── hiden_scripts/ # Скрытые/вспомогательные скрипты
|
||||
├── scripts/ # Вспомогательные скрипты
|
||||
│ └── check_sha256sum_list.sh # Проверка формата sha256sum.list
|
||||
├── auto_completion/ # Автодополнение для bash
|
||||
├── dependencies.sh # Установка системных зависимостей
|
||||
├── sha256sum.list # SHA256 хеши загружаемых файлов
|
||||
├── .pre-commit-config.yaml # Настройки pre-commit
|
||||
├── pyproject.toml # Настройки ruff
|
||||
├── .codespell-ignorewords # Исключения для codespell
|
||||
└── winehelper.desktop # Desktop-файл для запуска GUI
|
||||
```
|
||||
|
||||
@@ -92,11 +112,16 @@ winehelper/
|
||||
|
||||
Модульная архитектура PyQt5:
|
||||
|
||||
- **WineHelperGUI** — главное окно, управление вкладками
|
||||
- **PrefixManager** — CRUD операции с префиксами
|
||||
- **ApplicationInstaller** — установка приложений
|
||||
- **WineHelperGUI** — главное окно приложения (`winehelper_gui.py`)
|
||||
- **ScriptManager** — загрузка и обработка скриптов установки
|
||||
- **ScriptParser** — парсинг информации из скриптов установки
|
||||
- **Диалоги** — модальные окна для настроек и выбора
|
||||
- **PrefixManager** — CRUD операции с префиксами
|
||||
- **DesktopFileManager** — работа с .desktop файлами
|
||||
- **AppLauncher** — запуск и мониторинг установленных приложений
|
||||
- **SettingsManager** — чтение/запись настроек префиксов
|
||||
- **WinetricksService** — работа с компонентами Winetricks
|
||||
- **Диалоги** — модальные окна для настроек и выбора (Wine, Windows, компоненты, ассоциации файлов, предупреждение noexec)
|
||||
- **Утилиты** — логирование, работа с окружением, экспорт, сеточные макеты, управление иконками
|
||||
|
||||
### Скрипты установки
|
||||
|
||||
@@ -168,7 +193,6 @@ winehelper change-wine [version] # Сменить версию Wine
|
||||
winehelper clear-winetricks-cache # Очистить кэш Winetricks
|
||||
|
||||
# Другое
|
||||
winehelper --debug <command> # Режим отладки
|
||||
winehelper --changelog # История изменений
|
||||
winehelper gui # Запустить GUI
|
||||
```
|
||||
@@ -186,6 +210,74 @@ winehelper gui # Запустить GUI
|
||||
./winehelper -i alta-expert
|
||||
```
|
||||
|
||||
### Pre-commit
|
||||
|
||||
Проект использует [pre-commit](https://pre-commit.com/) для автоматической проверки кода перед коммитом.
|
||||
|
||||
#### Установка
|
||||
|
||||
```bash
|
||||
# Установить pre-commit
|
||||
pip install --user pre-commit
|
||||
|
||||
# Установить git-хуки
|
||||
pre-commit install
|
||||
```
|
||||
|
||||
#### Использование
|
||||
|
||||
Проверка запускается автоматически при обычном `git commit`:
|
||||
|
||||
```bash
|
||||
git add some-file.py
|
||||
git commit -m "feat: описание изменения"
|
||||
```
|
||||
|
||||
Если хуки проходят — коммит создаётся. Если падают — коммит отменяется, а в терминале выводится список ошибок.
|
||||
|
||||
Проверить все файлы вручную:
|
||||
|
||||
```bash
|
||||
pre-commit run --all-files
|
||||
```
|
||||
|
||||
Проверить только staged-файлы:
|
||||
|
||||
```bash
|
||||
pre-commit run
|
||||
```
|
||||
|
||||
Обновить версии хуков:
|
||||
|
||||
```bash
|
||||
pre-commit autoupdate
|
||||
```
|
||||
|
||||
#### Включённые проверки
|
||||
|
||||
- `trailing-whitespace`, `end-of-file-fixer`, `mixed-line-ending` — форматирование файлов
|
||||
- `check-ast` — синтаксис Python
|
||||
- `debug-statements` — отладочные вызовы (`breakpoint()`, `pdb`)
|
||||
- `detect-private-key` — случайно закоммиченные ключи
|
||||
- `bash-syntax-check` — синтаксис bash-скриптов
|
||||
- `py-compile` — компиляция Python-файлов (`python3 -m py_compile`)
|
||||
- `shellcheck` — линтинг bash-скриптов
|
||||
- `shfmt` — форматирование bash-скриптов
|
||||
- `ruff` — линтинг Python (импорты, отступы, line-length=120)
|
||||
- `ruff-format` — автоформатирование Python
|
||||
- `codespell` — проверка орфографии
|
||||
- `sha256sum.list format check` — валидация формата `sha256sum.list`
|
||||
|
||||
#### Важные нюансы
|
||||
|
||||
- Хук проверяет только файлы из индекса (`git add`).
|
||||
- Чтобы пропустить проверку (не рекомендуется):
|
||||
```bash
|
||||
git commit --no-verify
|
||||
```
|
||||
- `pyproject.toml` содержит настройки `ruff` (line-length=120, select правил).
|
||||
- Слова, которые `codespell` считает опечатками, но которые являются корректными для проекта, перечислены в `.codespell-ignorewords`.
|
||||
|
||||
### Добавление нового скрипта установки
|
||||
|
||||
1. Создать файл в `autoinstall/` (для автоматической установки) или `manualinstall/` (требуется дистрибутив)
|
||||
@@ -204,9 +296,19 @@ winehelper gui # Запустить GUI
|
||||
|
||||
**Python:**
|
||||
- Импортировать из `winehelperqt` относительно
|
||||
- Использовать type hints где возможно
|
||||
- Документация на русском языке
|
||||
- Классы должны наследоваться от соответствующих QWidget
|
||||
- Код проходит проверки `ruff` и `ruff-format` (см. раздел Pre-commit)
|
||||
- Желательно добавлять type hints для новых функций и методов
|
||||
- Для вывода сообщений использовать логгер, а не `print()`:
|
||||
```python
|
||||
from winehelperqt.logger import get_logger
|
||||
logger = get_logger(__name__)
|
||||
```
|
||||
Логгер настраивается один раз в `main()` (`winehelper_gui.py`) через `setup_logger()`.
|
||||
Уровень задаётся переменной окружения `WH_LOG_LEVEL` (debug/info/warning/error, по умолчанию info)
|
||||
либо во вкладке «Настройки» GUI.
|
||||
Вывод идёт в stdout — виден при запуске GUI из терминала (`./winehelper gui`).
|
||||
|
||||
## Безопасность
|
||||
|
||||
|
||||
@@ -55,7 +55,7 @@ modified by someone else and passed on, the recipients should know
|
||||
that what they have is not the original version, so that the original
|
||||
author's reputation will not be affected by problems that might be
|
||||
introduced by others.
|
||||
|
||||
|
||||
Finally, software patents pose a constant threat to the existence of
|
||||
any free program. We wish to make sure that a company cannot
|
||||
effectively restrict the users of a free program by obtaining a
|
||||
@@ -111,7 +111,7 @@ modification follow. Pay close attention to the difference between a
|
||||
"work based on the library" and a "work that uses the library". The
|
||||
former contains code derived from the library, whereas the latter must
|
||||
be combined with the library in order to run.
|
||||
|
||||
|
||||
GNU LESSER GENERAL PUBLIC LICENSE
|
||||
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
||||
|
||||
@@ -158,7 +158,7 @@ Library.
|
||||
You may charge a fee for the physical act of transferring a copy,
|
||||
and you may at your option offer warranty protection in exchange for a
|
||||
fee.
|
||||
|
||||
|
||||
2. You may modify your copy or copies of the Library or any portion
|
||||
of it, thus forming a work based on the Library, and copy and
|
||||
distribute such modifications or work under the terms of Section 1
|
||||
@@ -216,7 +216,7 @@ instead of to this License. (If a newer version than version 2 of the
|
||||
ordinary GNU General Public License has appeared, then you can specify
|
||||
that version instead if you wish.) Do not make any other change in
|
||||
these notices.
|
||||
|
||||
|
||||
Once this change is made in a given copy, it is irreversible for
|
||||
that copy, so the ordinary GNU General Public License applies to all
|
||||
subsequent copies and derivative works made from that copy.
|
||||
@@ -267,7 +267,7 @@ Library will still fall under Section 6.)
|
||||
distribute the object code for the work under the terms of Section 6.
|
||||
Any executables containing that work also fall under Section 6,
|
||||
whether or not they are linked directly with the Library itself.
|
||||
|
||||
|
||||
6. As an exception to the Sections above, you may also combine or
|
||||
link a "work that uses the Library" with the Library to produce a
|
||||
work containing portions of the Library, and distribute that work
|
||||
@@ -329,7 +329,7 @@ restrictions of other proprietary libraries that do not normally
|
||||
accompany the operating system. Such a contradiction means you cannot
|
||||
use both them and the Library together in an executable that you
|
||||
distribute.
|
||||
|
||||
|
||||
7. You may place library facilities that are a work based on the
|
||||
Library side-by-side in a single library together with other library
|
||||
facilities not covered by this License, and distribute such a combined
|
||||
@@ -370,7 +370,7 @@ subject to these terms and conditions. You may not impose any further
|
||||
restrictions on the recipients' exercise of the rights granted herein.
|
||||
You are not responsible for enforcing compliance by third parties with
|
||||
this License.
|
||||
|
||||
|
||||
11. If, as a consequence of a court judgment or allegation of patent
|
||||
infringement or for any other reason (not limited to patent issues),
|
||||
conditions are imposed on you (whether by court order, agreement or
|
||||
@@ -422,7 +422,7 @@ conditions either of that version or of any later version published by
|
||||
the Free Software Foundation. If the Library does not specify a
|
||||
license version number, you may choose any version ever published by
|
||||
the Free Software Foundation.
|
||||
|
||||
|
||||
14. If you wish to incorporate parts of the Library into other free
|
||||
programs whose distribution conditions are incompatible with these,
|
||||
write to the author to ask for permission. For software which is
|
||||
@@ -456,7 +456,7 @@ SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
|
||||
DAMAGES.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
|
||||
How to Apply These Terms to Your New Libraries
|
||||
|
||||
If you develop a new library, and you want it to be of the greatest
|
||||
|
||||
@@ -148,7 +148,7 @@ $ winehelper "/путь/до/установочного_файла.exe"
|
||||
2 - Префикс2
|
||||
Выберите префикс (0-2):
|
||||
```
|
||||
Необходимо указать номер удаляемого префикса и нажать клавишу **Enter**.
|
||||
Необходимо указать номер удаляемого префикса и нажать клавишу **Enter**.
|
||||
После выбора префикса автоматически:
|
||||
- Создаётся копия префикса.
|
||||
- Внутри префикса сохраняется используемая версия WINE.
|
||||
@@ -258,7 +258,6 @@ WineHelper предоставляет доступ к основным инст
|
||||
--help показать эту справку и выйти
|
||||
--version показать информацию о пакете и его версии
|
||||
--changelog показать историю изменений
|
||||
--debug [команда] включить режим логирования работы WINE
|
||||
</pre>
|
||||
|
||||
</details>
|
||||
|
||||
@@ -4,7 +4,7 @@ _winehelper_completions() {
|
||||
COMPREPLY=()
|
||||
cur="${COMP_WORDS[COMP_CWORD]}"
|
||||
prev="${COMP_WORDS[COMP_CWORD-1]}"
|
||||
opts="--help --version --debug install installed install-dxvk install-vkd3d -r -i remove-all killall remove-prefix backup-prefix restore-prefix create-prefix change-wine clear-winetricks-cache gui data-path version help --changelog changelog create-base-pfx init-prefix run-in-prefix debug"
|
||||
opts="--help --version install installed install-dxvk install-vkd3d -r -i remove-all killall remove-prefix backup-prefix restore-prefix create-prefix change-wine change-windows-ver clear-winetricks-cache gui data-path version help --changelog changelog create-base-pfx init-prefix run-in-prefix debug"
|
||||
wine_cmd="winecfg winereg winefile wineconsole winetricks desktop regedit explorer cmd run uninstaller control"
|
||||
|
||||
case "${prev}" in
|
||||
@@ -12,16 +12,12 @@ _winehelper_completions() {
|
||||
COMPREPLY=( $(compgen -W "${opts} ${wine_cmd}" -- "${cur}") )
|
||||
return 0
|
||||
;;
|
||||
--debug)
|
||||
COMPREPLY=( $(compgen -W "${wine_cmd}" -- "${cur}") )
|
||||
return 0
|
||||
;;
|
||||
install|-i)
|
||||
local scripts="$(ls -1 /usr/share/winehelper/autoinstall 2>/dev/null) $(ls -1 /usr/share/winehelper/manualinstall 2>/dev/null) $(ls -1 /usr/share/winehelper/testinstall 2>/dev/null)"
|
||||
COMPREPLY=( $(compgen -W "list --clear-pfx ${scripts}" -- "${cur}") )
|
||||
return 0
|
||||
;;
|
||||
run|installed|debug)
|
||||
run|installed)
|
||||
local installed=$(ls -1 ~/.local/share/winehelper/ 2>/dev/null | grep ".desktop" | sed 's/.desktop//')
|
||||
COMPREPLY=( $(compgen -W "${installed}" -- "${cur}") )
|
||||
return 0
|
||||
@@ -58,6 +54,10 @@ _winehelper_completions() {
|
||||
COMPREPLY=( $(compgen -W "system ${wine_versions}" -- "${cur}") )
|
||||
return 0
|
||||
;;
|
||||
change-windows-ver)
|
||||
COMPREPLY=( $(compgen -W "2k xp xp64 2k3 vista 7 8 81 10 11" -- "${cur}") )
|
||||
return 0
|
||||
;;
|
||||
*)
|
||||
if [[ "${COMP_WORDS[COMP_CWORD-2]}" == "run-in-prefix" ]] ; then
|
||||
COMPREPLY=( $(compgen -f -- "${cur}") )
|
||||
|
||||
@@ -8,7 +8,6 @@ _winehelper() {
|
||||
'help[Вывести справку]'
|
||||
'--version[Показать информацию о пакете и его версии]'
|
||||
'version[Показать информацию о пакете и его версии]'
|
||||
'--debug[Режим отладки]'
|
||||
'install[Запустить скрипт установки программы]'
|
||||
'install-dxvk[Установить/удалить DXVK]'
|
||||
'install-vkd3d[Установить/удалить VKD3D]'
|
||||
@@ -22,6 +21,7 @@ _winehelper() {
|
||||
'backup-prefix[Создать резервную копию префикса]'
|
||||
'restore-prefix[Восстановить префикс из резервной копии "путь/до/whpack"]'
|
||||
'change-wine[Изменить версию Wine для префикса]'
|
||||
'change-windows-ver[Изменить версию Windows для префикса]'
|
||||
'clear-winetricks-cache[Очистить кэш Winetricks]'
|
||||
'gui[Запустить графический интерфейс]'
|
||||
'data-path[Изменить рабочий каталог WineHelper]'
|
||||
@@ -64,9 +64,6 @@ _winehelper() {
|
||||
fi
|
||||
|
||||
case $words[2] in
|
||||
--debug)
|
||||
_values 'wine commands' "${wine_cmd[@]}"
|
||||
;;
|
||||
install|-i)
|
||||
_get_list_for_install
|
||||
;;
|
||||
@@ -93,6 +90,9 @@ _winehelper() {
|
||||
change-wine)
|
||||
_get_wine_versions
|
||||
;;
|
||||
change-windows-ver)
|
||||
_values 'windows versions' 2k xp xp64 2k3 vista 7 8 81 10 11
|
||||
;;
|
||||
winecfg|winereg|winefile|wineconsole|winetricks|desktop|regedit|explorer|cmd|uninstaller|control)
|
||||
;;
|
||||
*)
|
||||
|
||||
@@ -24,5 +24,3 @@ if try_download "$AUTOINSTALL_URL" "$AUTOINSTALL_EXE" ; then
|
||||
|
||||
create_desktop "$PROG_NAME" "$DRIVE_C/Program Files/A'PROPOS-Z/Apropos-Z.exe" "$PROG_ICON"
|
||||
fi
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
export PROG_URL="https://www.tflexcad.ru"
|
||||
export PROG_NAME="T-FLEX CAD Учебная Версия 17"
|
||||
export PROG_ICON="tflexcad17"
|
||||
export WH_WINE_USE="wine-11.0-alt-tflex-wow64"
|
||||
export WH_WINE_USE="wine-10.9-alt-tflex-wow64"
|
||||
export BASE_PFX="tflex_pfx_x64_v03"
|
||||
export WINEARCH="win64"
|
||||
export WH_WINDOWS_VER="10"
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
export PROG_URL="https://www.tflexcad.ru"
|
||||
export PROG_NAME="T-FLEX CAD 17"
|
||||
export PROG_ICON="tflexcad17"
|
||||
export WH_WINE_USE="wine-11.0-alt-tflex-wow64"
|
||||
export WH_WINE_USE="wine-10.9-alt-tflex-wow64"
|
||||
export BASE_PFX="tflex_pfx_x64_v03"
|
||||
export WINEARCH="win64"
|
||||
export WH_WINDOWS_VER="10"
|
||||
|
||||
@@ -5,7 +5,7 @@ export PROG_URL="https://www.tflexcad.ru"
|
||||
export PROG_NAME="Приложения для T-FLEX CAD 17"
|
||||
export PROG_ICON="tflexcad17"
|
||||
export WH_WINDOWS_VER="10"
|
||||
export WH_WINE_USE="wine-11.0-alt-tflex-wow64"
|
||||
export WH_WINE_USE="wine-10.9-alt-tflex-wow64"
|
||||
export BASE_PFX="tflex_pfx_x64_v03"
|
||||
export WINEARCH="win64"
|
||||
export WINEPREFIX="tflex"
|
||||
|
||||
@@ -5,7 +5,7 @@ export PROG_URL="https://www.tflexcad.ru"
|
||||
export PROG_NAME="Ресурсы для T-FLEX CAD 17"
|
||||
export PROG_ICON="tflexcad17"
|
||||
export WH_WINDOWS_VER="10"
|
||||
export WH_WINE_USE="wine-11.0-alt-tflex-wow64"
|
||||
export WH_WINE_USE="wine-10.9-alt-tflex-wow64"
|
||||
export BASE_PFX="tflex_pfx_x64_v03"
|
||||
export WINEARCH="win64"
|
||||
export WINEPREFIX="tflex"
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
export PROG_URL="https://www.tflexcad.ru"
|
||||
export PROG_NAME="T-FLEX CAD 18"
|
||||
export PROG_ICON="tflexcad18"
|
||||
export WH_WINE_USE="wine-11.0-alt-tflex-wow64"
|
||||
export WH_WINE_USE="wine-10.9-alt-tflex-wow64"
|
||||
export BASE_PFX="tflex_pfx_x64_v03"
|
||||
export WINEARCH="win64"
|
||||
export WH_WINDOWS_VER="10"
|
||||
|
||||
@@ -5,7 +5,7 @@ export PROG_URL="https://www.tflexcad.ru"
|
||||
export PROG_NAME="Приложения для T-FLEX CAD 18"
|
||||
export PROG_ICON="tflexcad18"
|
||||
export WH_WINDOWS_VER="10"
|
||||
export WH_WINE_USE="wine-11.0-alt-tflex-wow64"
|
||||
export WH_WINE_USE="wine-10.9-alt-tflex-wow64"
|
||||
export BASE_PFX="tflex_pfx_x64_v03"
|
||||
export WINEARCH="win64"
|
||||
export WINEPREFIX="tflex"
|
||||
|
||||
@@ -5,7 +5,7 @@ export PROG_URL="https://www.tflexcad.ru"
|
||||
export PROG_NAME="Ресурсы для T-FLEX CAD 18"
|
||||
export PROG_ICON="tflexcad18"
|
||||
export WH_WINDOWS_VER="10"
|
||||
export WH_WINE_USE="wine-11.0-alt-tflex-wow64"
|
||||
export WH_WINE_USE="wine-10.9-alt-tflex-wow64"
|
||||
export BASE_PFX="tflex_pfx_x64_v03"
|
||||
export WINEARCH="win64"
|
||||
export WINEPREFIX="tflex"
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
export PROG_URL="https://www.tflexcad.ru"
|
||||
export PROG_NAME="T-FLEX CAD 2D+ 17"
|
||||
export PROG_ICON="tflexcad17"
|
||||
export WH_WINE_USE="wine-11.0-alt-tflex-wow64"
|
||||
export WH_WINE_USE="wine-10.9-alt-tflex-wow64"
|
||||
export BASE_PFX="tflex_pfx_x64_v03"
|
||||
export WINEARCH="win64"
|
||||
export WH_WINDOWS_VER="10"
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
export PROG_URL="https://www.tflexcad.ru"
|
||||
export PROG_NAME="T-FLEX CAD 2D+ 18"
|
||||
export PROG_ICON="tflexcad18"
|
||||
export WH_WINE_USE="wine-11.0-alt-tflex-wow64"
|
||||
export WH_WINE_USE="wine-10.9-alt-tflex-wow64"
|
||||
export BASE_PFX="tflex_pfx_x64_v03"
|
||||
export WINEARCH="win64"
|
||||
export WH_WINDOWS_VER="10"
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
export PROG_URL="https://www.tflexcad.ru"
|
||||
export PROG_NAME="T-FLEX DOCs 17"
|
||||
export PROG_ICON="tflexdoc17"
|
||||
export WH_WINE_USE="wine-11.0-alt-tflex-wow64"
|
||||
export WH_WINE_USE="wine-10.9-alt-tflex-wow64"
|
||||
export BASE_PFX="tflex_pfx_x64_v03"
|
||||
export WINEARCH="win64"
|
||||
export WH_WINDOWS_VER="10"
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
export PROG_URL="https://www.tflexcad.ru"
|
||||
export PROG_NAME="T-FLEX Viewer 17"
|
||||
export PROG_ICON="tflexcad17"
|
||||
export WH_WINE_USE="wine-11.0-alt-tflex-wow64"
|
||||
export WH_WINE_USE="wine-10.9-alt-tflex-wow64"
|
||||
export BASE_PFX="tflex_pfx_x64_v03"
|
||||
export WINEARCH="win64"
|
||||
export WH_WINDOWS_VER="10"
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
export PROG_URL="https://www.tflexcad.ru"
|
||||
export PROG_NAME="T-FLEX Viewer 18"
|
||||
export PROG_ICON="tflexcad18"
|
||||
export WH_WINE_USE="wine-11.0-alt-tflex-wow64"
|
||||
export WH_WINE_USE="wine-10.9-alt-tflex-wow64"
|
||||
export BASE_PFX="tflex_pfx_x64_v03"
|
||||
export WINEARCH="win64"
|
||||
export WH_WINDOWS_VER="10"
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
# info_ru: Компоненты сервисов поддержки T-FLEX 17 и 18
|
||||
########################################################################
|
||||
export WH_WINDOWS_VER="10"
|
||||
export WH_WINE_USE="wine-11.0-alt-tflex-wow64"
|
||||
export WH_WINE_USE="wine-10.9-alt-tflex-wow64"
|
||||
export BASE_PFX="tflex_pfx_x64_v03"
|
||||
export WINEARCH="win64"
|
||||
export PROG_VERSION=""
|
||||
|
||||
+6
-9
@@ -1,19 +1,19 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
##### CHECK ROOT #####
|
||||
if [[ $(id -u) -ne 0 ]] ; then
|
||||
if [[ $(id -u) -ne 0 ]]; then
|
||||
echo "Перезапустите скрипт $0 от root пользователя!"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
##### MESSAGES FUNCTIONS #####
|
||||
if [[ -t 0 ]] ; then
|
||||
print_error () { printf "\E[31m%s Ошибка: $* %s\e[0m\n" ;}
|
||||
if [[ -t 0 ]]; then
|
||||
print_error() { printf "\E[31m%s Ошибка: $* %s\e[0m\n"; }
|
||||
else
|
||||
print_error () { echo -e "Ошибка: $*" ;}
|
||||
print_error() { echo -e "Ошибка: $*"; }
|
||||
fi
|
||||
|
||||
fatal () {
|
||||
fatal() {
|
||||
print_error "$@ Аварийное завершение работы WineHelper!"
|
||||
exit 1
|
||||
}
|
||||
@@ -29,7 +29,4 @@ apt-get update || fatal "Не удалось обновить список до
|
||||
##### INSTALL DEPENDENCIES #####
|
||||
# fonts-ttf-ms
|
||||
|
||||
apt-get install -y i586-{wine,glibc-core,libstdc++6,glibc-pthread,glibc-nss,\
|
||||
libnm,libnss,libnss-mdns,libnsl1,libunwind,libunixODBC2,ocl-icd,libfreetype,\
|
||||
libcups,libfontconfig1,libgnutls30,libGL,libEGL,libvulkan1,xorg-dri-swrast,\
|
||||
xorg-dri-intel,xorg-dri-radeon} || fatal "Не удалось установить зависимости."
|
||||
apt-get install -y i586-{wine,glibc-core,libstdc++6,glibc-pthread,glibc-nss,libnm,libnss,libnss-mdns,libnsl1,libunwind,libunixODBC2,ocl-icd,libfreetype,libcups,libfontconfig1,libgnutls30,libGL,libEGL,libvulkan1,xorg-dri-swrast,xorg-dri-intel,xorg-dri-radeon} || fatal "Не удалось установить зависимости."
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
# info_ru: Установщик "ЕМИАС" - Единая медицинская информационно-аналитическая система
|
||||
########################################################################
|
||||
export PROG_URL="https://emias.info/"
|
||||
export WH_WINE_USE="wine-11.0-alt-tkg-wow64"
|
||||
export WH_WINE_USE="wine-11.0-alt-emias-wow64"
|
||||
export WINEPREFIX="emias"
|
||||
export PROG_NAME="КИС ЕМИАС"
|
||||
export BASE_PFX="none"
|
||||
|
||||
@@ -33,7 +33,3 @@ else
|
||||
fatal "Не найден файл архива для $PROG_NAME. Перезапустите по примеру:
|
||||
winehelper install $1 \"/путь/до/архива\""
|
||||
fi
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
[tool.ruff]
|
||||
line-length = 120
|
||||
|
||||
[tool.ruff.lint]
|
||||
select = ["E", "W", "F", "I"]
|
||||
|
||||
[tool.ruff.format]
|
||||
quote-style = "double"
|
||||
indent-style = "space"
|
||||
Executable
+17
@@ -0,0 +1,17 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
file="sha256sum.list"
|
||||
|
||||
if [[ ! -f "$file" ]]; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
awk '
|
||||
/^#/ { next }
|
||||
NF == 0 { next }
|
||||
$1 !~ /^[a-f0-9]{64}$/ {
|
||||
print "Invalid hash line: " NR ": " $0
|
||||
exit 1
|
||||
}
|
||||
' "$file"
|
||||
+5
-2
@@ -1,17 +1,20 @@
|
||||
##### WINE WOW64 #####
|
||||
e99a44d9f302869287cbe699c2800e3ab4b3e1f9501f20fa3b0491c9cfaae1e7 wine-11.12-alt-tkg-wow64.tar.xz
|
||||
90676579fc97b0bdd0cc265b5c728683f8ce8d8998b020ac39d7c26ebf8783d9 wine-11.0-alt-tkg-wow64.tar.xz
|
||||
f8763bc54a4e1f1407cec8401e9ccb166b7d1aad064dd8875143717f19796bb8 wine-11.0-alt-tflex-wow64.tar.xz
|
||||
d8275a94f7538e600b4c82b0693a9ab1ebf0d5f141ea7ec3bc2a0e230b15676b wine-11.0-alt-emias-wow64.tar.xz
|
||||
d86724bd1b3a7a798f221a6a84430d37a3f531014756b7de49c0d8444d748bd7 wine-10.9-alt-tflex-wow64.tar.xz
|
||||
df5509e1f04424d41d734a255acd3695ac1167b73e52189b97b8acc9084f7fa6 wine-10.0-alt-scadoffice-wow64.tar.xz
|
||||
1f5214b5070066e6868da4f8961506e1d80a00470e5a135945386421a4ca02df wine-10.0.2-alt-scadoffice-wow64.tar.xz
|
||||
714687110724f4772d4028fb340ac1c8f9a32f0454c76822c967af9ef06844eb wine-10.0-alt-tkg-wow64.tar.xz
|
||||
4826028ddd49cc6ec2760be8dbb8ff2353a58323a87c846a8667e41e90851ea1 wine-9.0-alt-tkg-wow64.tar.xz
|
||||
|
||||
##### WINE AMD64 #####
|
||||
d1bfda024138f6e83ee531df513e6ebebb7aee1e40ce3f5cd3a4d0631107e482 wine-11.12-alt-tkg-amd64.tar.xz
|
||||
7a735f1e00173d8d3e3727aab927c4eb86aca018f39a4e8dfc1936909b8b9654 wine-11.0-alt-tkg-amd64.tar.xz
|
||||
2f3aa24fcb52a12bac35a77bf088aa8308e2e0ac3bf89f9b3f9e8e3c7090bbe8 wine-10.0-alt-tkg-amd64.tar.xz
|
||||
4251e75b410268fca9dabc168f838a56f5f02b970c6d4250763da8e791e8880d wine-9.0-alt-tkg-amd64.tar.xz
|
||||
|
||||
##### WINE I586 #####
|
||||
b660de1ce16fc90f54997e6cf30d9cf92daa932f5ef14ba8bd7cd5d7a4fa25af wine-11.12-alt-tkg-i586.tar.xz
|
||||
b082dc92c0ed96366353b8a9f62b126276d2476be85d2b37d47a886771a808b6 wine-11.0-alt-tkg-i586.tar.xz
|
||||
d63ae109e2495d3817172146107d9ddfd0b63a0f76b4d575279ae6b642522795 wine-10.0-alt-tkg-i586.tar.xz
|
||||
9a3160ae815b2dd008f67bf230b4e440c6b341d770b7c2a4b1a2c50283c7a895 wine-9.0-alt-tkg-i586.tar.xz
|
||||
|
||||
+2
-2
@@ -95,7 +95,7 @@ if [[ -n "$UPDATE_VER" ]]; then
|
||||
if try_download "https://data.nalog.ru/files/nalul/${UPDATE_URL_PATH}/NalogUL${UPDATE_VER}.msi" "${AUTOINSTALL_UPDATE}"; then
|
||||
wine_run_install "${AUTOINSTALL_UPDATE}" /quiet /norestart
|
||||
try_remove_file "${AUTOINSTALL_UPDATE}"
|
||||
|
||||
|
||||
# После обновления может появиться новая версия печати
|
||||
PRINT_INSTALLER="$(find "$DRIVE_C/npul/INPUTDOC" -name "Печать НД с PDF417*.msi" | tail -n 1)"
|
||||
if [[ -n "$PRINT_INSTALLER" ]]; then
|
||||
@@ -106,7 +106,7 @@ if [[ -n "$UPDATE_VER" ]]; then
|
||||
if try_download "https://data.nalog.ru/files/nalul/${UPDATE_URL_PATH}/NalogUL${UPDATE_VER}.exe" "${AUTOINSTALL_UPDATE}"; then
|
||||
wine_run_install "${AUTOINSTALL_UPDATE}" /VERYSILENT /NORESTART
|
||||
try_remove_file "${AUTOINSTALL_UPDATE}"
|
||||
|
||||
|
||||
# После обновления может появиться новая версия печати
|
||||
PRINT_INSTALLER="$(find "$DRIVE_C/npul/INPUTDOC" -name "Печать НД с PDF417*.msi" | tail -n 1)"
|
||||
if [[ -n "$PRINT_INSTALLER" ]]; then
|
||||
|
||||
+10
-8
@@ -2,7 +2,7 @@
|
||||
# info_ru: SCAD Office — это программный комплекс для расчёта строительных конструкций.
|
||||
########################################################################
|
||||
export PROG_URL="https://scadoffice.ru"
|
||||
export WH_WINE_USE="wine-10.0-alt-scadoffice-wow64"
|
||||
export WH_WINE_USE="wine-10.0.2-alt-scadoffice-wow64"
|
||||
export WINEPREFIX="scadoffice"
|
||||
export PROG_NAME="SCAD Office"
|
||||
export PROG_ICON="scadoffice"
|
||||
@@ -33,13 +33,6 @@ if [[ -n $2 ]] ; then
|
||||
fi
|
||||
fi
|
||||
|
||||
if try_download "https://scadhelp.ru/files/10/download" "${AUTOINSTALL_EXE}" ; then
|
||||
create_new_dir "$DRIVE_C/SDATA"
|
||||
create_new_dir "$DRIVE_C/SWORK"
|
||||
wine_run_install "$AUTOINSTALL_EXE"
|
||||
# try_remove_file "$AUTOINSTALL_EXE"
|
||||
fi
|
||||
|
||||
print_info "Установка дополнительных компонентов..."
|
||||
|
||||
ADDONS_PACK="${WH_TMP_DIR}/$(basename "$SCADOFFICE_ADDONS_URL")"
|
||||
@@ -65,6 +58,15 @@ if try_download "$SCADOFFICE_ADDONS_URL" "$ADDONS_PACK" ; then
|
||||
try_remove_dir "$ADDONS_PATH"
|
||||
fi
|
||||
|
||||
|
||||
if try_download "https://scadhelp.ru/files/10/download" "${AUTOINSTALL_EXE}" ; then
|
||||
create_new_dir "$DRIVE_C/SDATA"
|
||||
create_new_dir "$DRIVE_C/SWORK"
|
||||
wine_run_install "$AUTOINSTALL_EXE"
|
||||
"$WINESERVER" -k
|
||||
# try_remove_file "$AUTOINSTALL_EXE"
|
||||
fi
|
||||
|
||||
# Определение всех программ, значков и исполняемых файлов
|
||||
declare -a PROG_NAME_All=("Арбат" "Вест" "Глобальные настройки" "Декор" "Дискретная арматура" "Запрос" "Камин" "КоКон" "Комета" "Конструктор сечений" "Консул" "Конфигуратор лицензий" "Кристалл" "Кросс" "Куст" "Магнум" "Монолит" "Откос" "Пастернак" "Преобразование ед. измерений" "Cортамент металлопроката" "Расчет по формуле" "Редактор акселерограмм" "Редактор динамичности" "Редактор материалов" "Тонус" "Эквивалентное сечение" "SCAD++")
|
||||
|
||||
|
||||
+879
-691
File diff suppressed because it is too large.
Load diff
+1082
-856
File diff suppressed because it is too large.
Load diff
+32
-44
@@ -10,63 +10,51 @@ GUI пакет для winehelper.
|
||||
"""
|
||||
|
||||
# Parsers
|
||||
from winehelperqt.dialogs.noexec_warning import NoExecWarningDialog
|
||||
|
||||
# Dialogs
|
||||
from winehelperqt.dialogs.winetricks_manager import WinetricksManagerDialog
|
||||
from winehelperqt.parsers.script_parser import ScriptParser
|
||||
from winehelperqt.parsers.sha256_parser import Sha256Parser
|
||||
from winehelperqt.parsers.winetricks_parser import WinetricksOutputParser
|
||||
from winehelperqt.parsers.script_parser import ScriptParser
|
||||
from winehelperqt.services.app_launcher import AppLauncher
|
||||
from winehelperqt.services.desktop_file_manager import DesktopFileManager
|
||||
from winehelperqt.services.prefix_manager import PrefixManager
|
||||
from winehelperqt.services.script_manager import ScriptInfo, ScriptManager
|
||||
from winehelperqt.services.settings_manager import SettingsManager
|
||||
|
||||
# Services
|
||||
from winehelperqt.services.winetricks_service import WinetricksCacheService, WinetricksLogReader
|
||||
from winehelperqt.utils.cache_service import CacheService, FileCacheService
|
||||
|
||||
# Utils
|
||||
from winehelperqt.utils.log_handler import LogProgressHandler, MultiLogHandler
|
||||
from winehelperqt.utils.cache_service import CacheService, FileCacheService
|
||||
|
||||
# Services
|
||||
from winehelperqt.services.winetricks_service import WinetricksCacheService
|
||||
from winehelperqt.services.winetricks_service import WinetricksLogReader
|
||||
from winehelperqt.services.prefix_manager import PrefixManager
|
||||
from winehelperqt.services.process_handler import ProcessHandler
|
||||
from winehelperqt.services.process_handler import CommandRunner
|
||||
from winehelperqt.services.desktop_file_manager import DesktopFileManager
|
||||
from winehelperqt.services.script_manager import ScriptManager
|
||||
from winehelperqt.services.script_manager import ScriptInfo
|
||||
from winehelperqt.services.installation_manager import InstallationManager
|
||||
from winehelperqt.services.app_launcher import AppLauncher
|
||||
from winehelperqt.services.settings_manager import SettingsManager
|
||||
|
||||
# Widgets
|
||||
from winehelperqt.widgets.icon_manager import IconManager
|
||||
|
||||
# Dialogs
|
||||
from winehelperqt.dialogs.winetricks_manager import WinetricksManagerDialog
|
||||
from winehelperqt.dialogs.noexec_warning import NoExecWarningDialog
|
||||
|
||||
__all__ = [
|
||||
# Parsers
|
||||
'Sha256Parser',
|
||||
'WinetricksOutputParser',
|
||||
'ScriptParser',
|
||||
|
||||
"Sha256Parser",
|
||||
"WinetricksOutputParser",
|
||||
"ScriptParser",
|
||||
# Utils
|
||||
'LogProgressHandler',
|
||||
'MultiLogHandler',
|
||||
'CacheService',
|
||||
'FileCacheService',
|
||||
|
||||
"LogProgressHandler",
|
||||
"MultiLogHandler",
|
||||
"CacheService",
|
||||
"FileCacheService",
|
||||
# Services
|
||||
'WinetricksCacheService',
|
||||
'WinetricksLogReader',
|
||||
'PrefixManager',
|
||||
'ProcessHandler',
|
||||
'CommandRunner',
|
||||
'DesktopFileManager',
|
||||
'ScriptManager',
|
||||
'ScriptInfo',
|
||||
'InstallationManager',
|
||||
'AppLauncher',
|
||||
'SettingsManager',
|
||||
|
||||
"WinetricksCacheService",
|
||||
"WinetricksLogReader",
|
||||
"PrefixManager",
|
||||
"DesktopFileManager",
|
||||
"ScriptManager",
|
||||
"ScriptInfo",
|
||||
"AppLauncher",
|
||||
"SettingsManager",
|
||||
# Widgets
|
||||
'IconManager',
|
||||
|
||||
"IconManager",
|
||||
# Dialogs
|
||||
'WinetricksManagerDialog',
|
||||
'NoExecWarningDialog',
|
||||
"WinetricksManagerDialog",
|
||||
"NoExecWarningDialog",
|
||||
]
|
||||
@@ -1,32 +1,38 @@
|
||||
"""
|
||||
Диалоги для winehelper GUI.
|
||||
"""
|
||||
|
||||
from winehelperqt.dialogs.base_version_dialog import (
|
||||
BaseVersionSelectionDialog,
|
||||
WineVersionSelectionDialogBase,
|
||||
ComponentVersionSelectionDialogBase,
|
||||
WineVersionSelectionDialogBase,
|
||||
)
|
||||
from winehelperqt.dialogs.winetricks_manager import WinetricksManagerDialog
|
||||
from winehelperqt.dialogs.wine_version import WineVersionSelectionDialog
|
||||
from winehelperqt.dialogs.command_dialog import CommandDialog
|
||||
from winehelperqt.dialogs.component_version import ComponentVersionSelectionDialog
|
||||
from winehelperqt.dialogs.create_log import CreateLogDialog
|
||||
from winehelperqt.dialogs.create_prefix import CreatePrefixDialog
|
||||
from winehelperqt.dialogs.file_associations import FileAssociationsDialog
|
||||
from winehelperqt.dialogs.settings import AdditionalSettingsDialog, AppAdditionalSettingsDialog
|
||||
from winehelperqt.dialogs.noexec_warning import NoExecWarningDialog
|
||||
from winehelperqt.dialogs.settings import AdditionalSettingsDialog, AppAdditionalSettingsDialog
|
||||
from winehelperqt.dialogs.windows_version import WindowsVersionSelectionDialog
|
||||
from winehelperqt.dialogs.wine_version import WineVersionSelectionDialog
|
||||
from winehelperqt.dialogs.winetricks_manager import WinetricksManagerDialog
|
||||
|
||||
__all__ = [
|
||||
# Base classes
|
||||
'BaseVersionSelectionDialog',
|
||||
'WineVersionSelectionDialogBase',
|
||||
'ComponentVersionSelectionDialogBase',
|
||||
|
||||
"BaseVersionSelectionDialog",
|
||||
"WineVersionSelectionDialogBase",
|
||||
"ComponentVersionSelectionDialogBase",
|
||||
# Dialogs
|
||||
'WinetricksManagerDialog',
|
||||
'WineVersionSelectionDialog',
|
||||
'ComponentVersionSelectionDialog',
|
||||
'CreatePrefixDialog',
|
||||
'FileAssociationsDialog',
|
||||
'AdditionalSettingsDialog',
|
||||
'AppAdditionalSettingsDialog',
|
||||
'NoExecWarningDialog',
|
||||
"CommandDialog",
|
||||
"WinetricksManagerDialog",
|
||||
"WineVersionSelectionDialog",
|
||||
"ComponentVersionSelectionDialog",
|
||||
"CreatePrefixDialog",
|
||||
"FileAssociationsDialog",
|
||||
"AdditionalSettingsDialog",
|
||||
"AppAdditionalSettingsDialog",
|
||||
"WindowsVersionSelectionDialog",
|
||||
"NoExecWarningDialog",
|
||||
"CreateLogDialog",
|
||||
]
|
||||
@@ -2,21 +2,34 @@
|
||||
Базовые классы для диалогов выбора версий.
|
||||
Устраняет дублирование кода между WineVersionSelectionDialog и ComponentVersionSelectionDialog.
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
from PyQt5.QtWidgets import (
|
||||
QDialog, QVBoxLayout, QHBoxLayout, QGridLayout, QScrollArea,
|
||||
QTabWidget, QLineEdit, QPushButton, QLabel, QWidget, QMessageBox
|
||||
)
|
||||
from PyQt5.QtCore import Qt, pyqtSignal
|
||||
from PyQt5.QtWidgets import (
|
||||
QDialog,
|
||||
QGridLayout,
|
||||
QHBoxLayout,
|
||||
QLabel,
|
||||
QLineEdit,
|
||||
QMessageBox,
|
||||
QPushButton,
|
||||
QScrollArea,
|
||||
QTabWidget,
|
||||
QVBoxLayout,
|
||||
QWidget,
|
||||
)
|
||||
|
||||
from winehelperqt.logger import get_logger
|
||||
from winehelperqt.parsers.sha256_parser import Sha256Parser
|
||||
from winehelperqt.utils.environment import EnvironmentConfig
|
||||
from winehelperqt.utils.grid_utils import GridUtils
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class BaseVersionSelectionDialog(QDialog):
|
||||
"""
|
||||
@@ -30,6 +43,9 @@ class BaseVersionSelectionDialog(QDialog):
|
||||
|
||||
NUM_COLUMNS = 3
|
||||
|
||||
# Кэш версии системного Wine на время сессии (не меняется между открытиями диалога)
|
||||
_system_wine_version_cache = None
|
||||
|
||||
version_selected = pyqtSignal(str)
|
||||
|
||||
def __init__(self, title, parent=None, min_width=600, min_height=400):
|
||||
@@ -55,9 +71,7 @@ class BaseVersionSelectionDialog(QDialog):
|
||||
if data_path:
|
||||
return os.path.join(data_path, "sha256sum.list")
|
||||
# Фолбэк: явно разрешаем путь из расположения пакета
|
||||
return os.path.abspath(
|
||||
os.path.join(os.path.dirname(__file__), '..', '..', 'sha256sum.list')
|
||||
)
|
||||
return os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "sha256sum.list"))
|
||||
|
||||
def _setup_ui(self):
|
||||
"""Создает базовый UI диалога."""
|
||||
@@ -80,10 +94,8 @@ class BaseVersionSelectionDialog(QDialog):
|
||||
|
||||
def filter_versions(self):
|
||||
"""Фильтрует версии по тексту поиска."""
|
||||
grid_layout = getattr(self, 'grid_layout', None)
|
||||
GridUtils.filter_buttons(
|
||||
self.buttons, self.search_edit.text(), grid_layout, self.NUM_COLUMNS
|
||||
)
|
||||
grid_layout = getattr(self, "grid_layout", None)
|
||||
GridUtils.filter_buttons(self.buttons, self.search_edit.text(), grid_layout, self.NUM_COLUMNS)
|
||||
|
||||
def on_version_selected(self, version_name):
|
||||
"""Обрабатывает выбор версии."""
|
||||
@@ -103,7 +115,7 @@ class BaseVersionSelectionDialog(QDialog):
|
||||
start_row=0,
|
||||
num_columns=3,
|
||||
is_download_tab=False,
|
||||
version_filter=None
|
||||
version_filter=None,
|
||||
):
|
||||
"""Создает сетку кнопок для версий."""
|
||||
buttons = []
|
||||
@@ -150,10 +162,7 @@ class WineVersionSelectionDialogBase(BaseVersionSelectionDialog):
|
||||
self.selected_display_text = None
|
||||
|
||||
super().__init__(
|
||||
title=f"Выбор версии Wine для {architecture} префикса",
|
||||
parent=parent,
|
||||
min_width=900,
|
||||
min_height=500
|
||||
title=f"Выбор версии Wine для {architecture} префикса", parent=parent, min_width=900, min_height=500
|
||||
)
|
||||
|
||||
def _create_version_container(self):
|
||||
@@ -185,11 +194,7 @@ class WineVersionSelectionDialogBase(BaseVersionSelectionDialog):
|
||||
self.wine_versions_data = Sha256Parser.parse_wine_versions(sha256_path)
|
||||
|
||||
if not self.wine_versions_data:
|
||||
QMessageBox.warning(
|
||||
self,
|
||||
"Ошибка",
|
||||
f"Файл с версиями не найден или пуст:\n{sha256_path}"
|
||||
)
|
||||
QMessageBox.warning(self, "Ошибка", f"Файл с версиями не найден или пуст:\n{sha256_path}")
|
||||
|
||||
def _get_installed_versions(self):
|
||||
"""Возвращает список локально установленных версий Wine."""
|
||||
@@ -199,32 +204,35 @@ class WineVersionSelectionDialogBase(BaseVersionSelectionDialog):
|
||||
return Sha256Parser.get_installed_versions(dist_path)
|
||||
|
||||
def _get_system_wine_version(self):
|
||||
"""Получает версию системного Wine."""
|
||||
if shutil.which('wine'):
|
||||
"""Получает версию системного Wine (с кэшированием на время сессии)."""
|
||||
if BaseVersionSelectionDialog._system_wine_version_cache is not None:
|
||||
return BaseVersionSelectionDialog._system_wine_version_cache
|
||||
|
||||
version = "Системная версия"
|
||||
if shutil.which("wine"):
|
||||
try:
|
||||
result = subprocess.run(
|
||||
['wine', '--version'],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=True,
|
||||
encoding='utf-8'
|
||||
["wine", "--version"], capture_output=True, text=True, check=True, encoding="utf-8"
|
||||
)
|
||||
return result.stdout.strip()
|
||||
version = result.stdout.strip()
|
||||
logger.debug("Системный wine: %s", version)
|
||||
except (FileNotFoundError, subprocess.CalledProcessError) as e:
|
||||
print(f"Не удалось получить версию системного wine: {e}")
|
||||
return "Системная версия"
|
||||
logger.warning("Не удалось получить версию системного wine: %s", e)
|
||||
|
||||
BaseVersionSelectionDialog._system_wine_version_cache = version
|
||||
return version
|
||||
|
||||
def _is_version_compatible(self, version_name):
|
||||
"""Проверяет совместимость версии с выбранной архитектурой."""
|
||||
is_win64_prefix = self.architecture == "win64"
|
||||
is_win32_prefix = self.architecture == "win32"
|
||||
re_32bit_version = re.compile(r'i[3-6]86|i586')
|
||||
re_32bit_version = re.compile(r"i[3-6]86|i586")
|
||||
|
||||
if is_win64_prefix and re_32bit_version.search(version_name):
|
||||
return False
|
||||
|
||||
if is_win32_prefix:
|
||||
if version_name == "system" or 'wow64' in version_name:
|
||||
if version_name == "system" or "wow64" in version_name:
|
||||
return False
|
||||
|
||||
return True
|
||||
@@ -239,13 +247,7 @@ class ComponentVersionSelectionDialogBase(BaseVersionSelectionDialog):
|
||||
Базовый класс для диалога выбора версии компонента (DXVK, VKD3D).
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
component_group,
|
||||
title,
|
||||
parent=None,
|
||||
add_extra_options=True
|
||||
):
|
||||
def __init__(self, component_group, title, parent=None, add_extra_options=True):
|
||||
"""
|
||||
Инициализирует диалог выбора версии компонента.
|
||||
"""
|
||||
@@ -253,12 +255,7 @@ class ComponentVersionSelectionDialogBase(BaseVersionSelectionDialog):
|
||||
self.versions_data = []
|
||||
self.add_extra_options = add_extra_options
|
||||
|
||||
super().__init__(
|
||||
title=title,
|
||||
parent=parent,
|
||||
min_width=700,
|
||||
min_height=400
|
||||
)
|
||||
super().__init__(title=title, parent=parent, min_width=700, min_height=400)
|
||||
|
||||
def _create_version_container(self):
|
||||
"""Создает контейнер для версий компонента."""
|
||||
@@ -303,10 +300,7 @@ class ComponentVersionSelectionDialogBase(BaseVersionSelectionDialog):
|
||||
def _parse_sha256_list(self):
|
||||
"""Парсит sha256sum.list для получения списка версий компонента."""
|
||||
sha256_path = self._get_sha256_path()
|
||||
self.versions_data = Sha256Parser.parse_component_versions(
|
||||
sha256_path,
|
||||
self.component_group
|
||||
)
|
||||
self.versions_data = Sha256Parser.parse_component_versions(sha256_path, self.component_group)
|
||||
|
||||
def populate_ui(self, start_row):
|
||||
"""Заполняет UI версиями компонента."""
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
from PyQt5.QtCore import QProcess
|
||||
from PyQt5.QtWidgets import QDialog
|
||||
|
||||
from winehelperqt.utils.dialog_utils import DialogUtils
|
||||
|
||||
|
||||
class CommandDialog(QDialog):
|
||||
"""Модальный диалог для выполнения команд winehelper с защитой от случайного закрытия."""
|
||||
|
||||
def __init__(self, parent=None):
|
||||
super().__init__(parent)
|
||||
self._process = None
|
||||
|
||||
def set_process(self, process):
|
||||
self._process = process
|
||||
|
||||
def closeEvent(self, event):
|
||||
running = False
|
||||
if self._process is not None:
|
||||
try:
|
||||
running = self._process.state() == QProcess.Running
|
||||
except RuntimeError:
|
||||
running = False
|
||||
if running:
|
||||
proc = self._process
|
||||
if not DialogUtils.confirm(
|
||||
self,
|
||||
"Прервать выполнение?",
|
||||
"Процесс ещё выполняется.\nВы действительно хотите прервать его?",
|
||||
yes_text="Да, прервать",
|
||||
no_text="Нет",
|
||||
):
|
||||
event.ignore()
|
||||
return
|
||||
if proc is None:
|
||||
event.accept()
|
||||
return
|
||||
try:
|
||||
proc.terminate()
|
||||
if not proc.waitForFinished(10000):
|
||||
proc.kill()
|
||||
proc.waitForFinished(5000)
|
||||
except RuntimeError:
|
||||
pass
|
||||
event.accept()
|
||||
else:
|
||||
event.accept()
|
||||
@@ -2,6 +2,7 @@
|
||||
Диалог для выбора версии компонента (DXVK, VKD3D).
|
||||
|
||||
"""
|
||||
|
||||
from functools import partial
|
||||
|
||||
from winehelperqt.dialogs.base_version_dialog import ComponentVersionSelectionDialogBase
|
||||
@@ -25,10 +26,7 @@ class ComponentVersionSelectionDialog(ComponentVersionSelectionDialogBase):
|
||||
"""
|
||||
self.installed_version = installed_version
|
||||
super().__init__(
|
||||
component_group=component_group,
|
||||
title=title,
|
||||
parent=parent,
|
||||
add_extra_options=add_extra_options
|
||||
component_group=component_group, title=title, parent=parent, add_extra_options=add_extra_options
|
||||
)
|
||||
|
||||
def populate_ui(self, start_row):
|
||||
@@ -37,10 +35,7 @@ class ComponentVersionSelectionDialog(ComponentVersionSelectionDialogBase):
|
||||
row, col = start_row, 0
|
||||
for version_name in versions:
|
||||
is_installed = version_name == self.installed_version
|
||||
btn = VersionButtonWidget(
|
||||
version_name, version_name,
|
||||
is_installed=is_installed, show_icon=True
|
||||
)
|
||||
btn = VersionButtonWidget(version_name, version_name, is_installed=is_installed, show_icon=True)
|
||||
btn.clicked.connect(partial(self.on_version_selected, version_name))
|
||||
self.grid_layout.addWidget(btn, row, col)
|
||||
self.buttons.append(btn)
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
"""
|
||||
Диалог создания лога запуска программы с выбором каналов WINEDEBUG.
|
||||
"""
|
||||
|
||||
from PyQt5.QtCore import QSettings
|
||||
from PyQt5.QtWidgets import (
|
||||
QCheckBox,
|
||||
QDialog,
|
||||
QHBoxLayout,
|
||||
QLabel,
|
||||
QLineEdit,
|
||||
QPushButton,
|
||||
QVBoxLayout,
|
||||
)
|
||||
|
||||
DEFAULT_WINEDEBUG = "+loaddll,+seh"
|
||||
SETTINGS_KEY = "winedebug_channels"
|
||||
|
||||
|
||||
class CreateLogDialog(QDialog):
|
||||
"""Диалог для запуска приложения с созданием лога."""
|
||||
|
||||
def __init__(self, parent=None):
|
||||
super().__init__(parent)
|
||||
self.setWindowTitle("Создание лога")
|
||||
self.setMinimumSize(520, 240)
|
||||
self.setModal(True)
|
||||
|
||||
self._settings = QSettings("winehelper", "winedebug_run")
|
||||
|
||||
layout = QVBoxLayout(self)
|
||||
|
||||
desc_label = QLabel(
|
||||
"Приложение будет запущено в режиме отладки.\n\n"
|
||||
"После закрытия приложения лог будет сохранен в папке 'winehelper_backup_log' "
|
||||
"в вашем домашнем каталоге под именем (пример: prefix_program.log).\n\n"
|
||||
"Укажите каналы отладки WINEDEBUG:"
|
||||
)
|
||||
desc_label.setWordWrap(True)
|
||||
layout.addWidget(desc_label)
|
||||
|
||||
winedebug_layout = QHBoxLayout()
|
||||
winedebug_layout.addWidget(QLabel("<b>WINEDEBUG:</b>"))
|
||||
self.winedebug_edit = QLineEdit()
|
||||
self.winedebug_edit.setPlaceholderText("Например: +loaddll,+seh")
|
||||
winedebug_layout.addWidget(self.winedebug_edit)
|
||||
layout.addLayout(winedebug_layout)
|
||||
|
||||
hint_label = QLabel("Пример: +loaddll,-seh,fixme-all,+tid")
|
||||
hint_label.setStyleSheet("color: gray; font-size: 13px;")
|
||||
layout.addWidget(hint_label)
|
||||
|
||||
self.remember_cb = QCheckBox("Запомнить каналы")
|
||||
layout.addWidget(self.remember_cb)
|
||||
|
||||
self._restore_state()
|
||||
|
||||
layout.addStretch()
|
||||
|
||||
button_layout = QHBoxLayout()
|
||||
ok_button = QPushButton("Запустить")
|
||||
ok_button.clicked.connect(self.accept)
|
||||
cancel_button = QPushButton("Отмена")
|
||||
cancel_button.clicked.connect(self.reject)
|
||||
button_layout.addStretch()
|
||||
button_layout.addWidget(ok_button)
|
||||
button_layout.addWidget(cancel_button)
|
||||
layout.addLayout(button_layout)
|
||||
|
||||
def _restore_state(self):
|
||||
saved = self._settings.value(SETTINGS_KEY, "")
|
||||
if saved:
|
||||
self.winedebug_edit.setText(saved)
|
||||
self.remember_cb.setChecked(True)
|
||||
else:
|
||||
self.winedebug_edit.setText(DEFAULT_WINEDEBUG)
|
||||
self.remember_cb.setChecked(False)
|
||||
|
||||
def accept(self):
|
||||
if self.remember_cb.isChecked():
|
||||
value = self.winedebug_edit.text().strip()
|
||||
if value:
|
||||
self._settings.setValue(SETTINGS_KEY, value)
|
||||
else:
|
||||
self._settings.remove(SETTINGS_KEY)
|
||||
super().accept()
|
||||
|
||||
@property
|
||||
def winedebug_value(self) -> str:
|
||||
value = self.winedebug_edit.text().strip()
|
||||
return value or DEFAULT_WINEDEBUG
|
||||
@@ -1,25 +1,36 @@
|
||||
"""
|
||||
Диалог для создания нового префикса.
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
|
||||
from PyQt5.QtWidgets import (
|
||||
QDialog, QVBoxLayout, QHBoxLayout, QFormLayout, QPushButton,
|
||||
QLabel, QLineEdit, QRadioButton, QComboBox, QMessageBox, QWidget
|
||||
)
|
||||
from PyQt5.QtGui import QFont
|
||||
from PyQt5.QtWidgets import (
|
||||
QComboBox,
|
||||
QDialog,
|
||||
QFormLayout,
|
||||
QHBoxLayout,
|
||||
QLabel,
|
||||
QLineEdit,
|
||||
QMessageBox,
|
||||
QPushButton,
|
||||
QRadioButton,
|
||||
QVBoxLayout,
|
||||
QWidget,
|
||||
)
|
||||
|
||||
from winehelperqt.parsers.sha256_parser import Sha256Parser
|
||||
from winehelperqt.dialogs.windows_version import WindowsVersionSelectionDialog
|
||||
from winehelperqt.dialogs.wine_version import WineVersionSelectionDialog
|
||||
from winehelperqt.parsers.sha256_parser import Sha256Parser
|
||||
from winehelperqt.utils.environment import EnvironmentConfig
|
||||
|
||||
|
||||
class CreatePrefixDialog(QDialog):
|
||||
"""Диалог для создания нового префикса."""
|
||||
|
||||
PREFIX_NAME_PATTERN = r'^[a-zA-Z0-9_-]+$'
|
||||
PREFIX_NAME_CHARS = r'[^a-zA-Z0-9_-]'
|
||||
PREFIX_NAME_PATTERN = r"^[a-zA-Z0-9_-]+$"
|
||||
PREFIX_NAME_CHARS = r"[^a-zA-Z0-9_-]"
|
||||
|
||||
def __init__(self, parent=None):
|
||||
super().__init__(parent)
|
||||
@@ -34,6 +45,7 @@ class CreatePrefixDialog(QDialog):
|
||||
self.prepared_prefixes = {}
|
||||
self.selected_wine_version_value = None
|
||||
self.selected_wine_version_display = None
|
||||
self.selected_windows_version = "10"
|
||||
|
||||
layout = QVBoxLayout(self)
|
||||
form_layout = QFormLayout()
|
||||
@@ -68,6 +80,7 @@ class CreatePrefixDialog(QDialog):
|
||||
form_layout.addRow("<b>Разрядность:</b>", arch_widget)
|
||||
|
||||
self.prefix_template_selector = QComboBox()
|
||||
self.prefix_template_selector.setFixedWidth(170)
|
||||
self.prefix_template_selector.setToolTip("Выберите шаблон для создания префикса.")
|
||||
form_layout.addRow("<b>Шаблон префикса:</b>", self.prefix_template_selector)
|
||||
|
||||
@@ -83,11 +96,18 @@ class CreatePrefixDialog(QDialog):
|
||||
version_layout.addWidget(select_version_button)
|
||||
form_layout.addRow("<b>Версия Wine:</b>", version_layout)
|
||||
|
||||
self.windows_version_combo = QComboBox()
|
||||
self.windows_version_combo.setFixedWidth(170)
|
||||
for display_name, value in WindowsVersionSelectionDialog.WINDOWS_VERSIONS:
|
||||
self.windows_version_combo.addItem(display_name, value)
|
||||
self.windows_version_combo.setCurrentIndex(self.windows_version_combo.findData(self.selected_windows_version))
|
||||
form_layout.addRow("<b>Версия Windows:</b>", self.windows_version_combo)
|
||||
|
||||
layout.addLayout(form_layout)
|
||||
|
||||
button_layout = QHBoxLayout()
|
||||
self.create_button = QPushButton("Создать")
|
||||
self.create_button.setFont(QFont('Arial', 11, QFont.Bold))
|
||||
self.create_button.setFont(QFont("Arial", 11, QFont.Bold))
|
||||
self.create_button.setStyleSheet("background-color: #0078d7; color: white;")
|
||||
self.create_button.setEnabled(False)
|
||||
self.create_button.clicked.connect(self.accept_creation)
|
||||
@@ -109,7 +129,7 @@ class CreatePrefixDialog(QDialog):
|
||||
|
||||
def _load_prepared_prefixes(self):
|
||||
"""Загружает и парсит шаблоны префиксов из sha256sum.list."""
|
||||
self.prepared_prefixes = {'win32': [], 'win64': []}
|
||||
self.prepared_prefixes = {"win32": [], "win64": []}
|
||||
data_path = EnvironmentConfig.DATA_PATH
|
||||
if not data_path:
|
||||
QMessageBox.warning(self, "Ошибка", "Переменная окружения DATA_PATH не установлена.")
|
||||
@@ -143,22 +163,20 @@ class CreatePrefixDialog(QDialog):
|
||||
|
||||
for value, description in templates:
|
||||
display_name = "Чистый префикс" if value == "none" else value
|
||||
self.prefix_template_selector.addItem(display_name, userData={'value': value, 'tooltip': description})
|
||||
self.prefix_template_selector.addItem(display_name, userData={"value": value, "tooltip": description})
|
||||
|
||||
self.prefix_template_selector.blockSignals(False)
|
||||
self.prefix_template_selector.currentIndexChanged.connect(
|
||||
lambda i: self.prefix_template_selector.setToolTip(
|
||||
self.prefix_template_selector.itemData(i)['tooltip']
|
||||
)
|
||||
lambda i: self.prefix_template_selector.setToolTip(self.prefix_template_selector.itemData(i)["tooltip"])
|
||||
)
|
||||
self.prefix_template_selector.setToolTip(self.prefix_template_selector.itemData(0)['tooltip'])
|
||||
self.prefix_template_selector.setToolTip(self.prefix_template_selector.itemData(0)["tooltip"])
|
||||
|
||||
def validate_prefix_name(self, text):
|
||||
"""Проверяет имя префикса в реальном времени."""
|
||||
if re.match(self.PREFIX_NAME_PATTERN, text):
|
||||
self.name_warning_label.setVisible(False)
|
||||
else:
|
||||
cleaned_text = re.sub(self.PREFIX_NAME_CHARS, '', text)
|
||||
cleaned_text = re.sub(self.PREFIX_NAME_CHARS, "", text)
|
||||
self.prefix_name_edit.blockSignals(True)
|
||||
self.prefix_name_edit.setText(cleaned_text)
|
||||
self.prefix_name_edit.blockSignals(False)
|
||||
@@ -170,9 +188,7 @@ class CreatePrefixDialog(QDialog):
|
||||
"""Включает или выключает кнопку 'Создать'."""
|
||||
name_ok = bool(self.prefix_name_edit.text().strip())
|
||||
version_ok = bool(self.wine_version_edit.text().strip())
|
||||
self.create_button.setEnabled(
|
||||
name_ok and version_ok and not self.name_warning_label.isVisible()
|
||||
)
|
||||
self.create_button.setEnabled(name_ok and version_ok and not self.name_warning_label.isVisible())
|
||||
|
||||
def accept_creation(self):
|
||||
"""Валидирует данные, сохраняет их и закрывает диалог с успехом."""
|
||||
@@ -184,8 +200,9 @@ class CreatePrefixDialog(QDialog):
|
||||
|
||||
if not re.match(self.PREFIX_NAME_PATTERN, prefix_name):
|
||||
QMessageBox.warning(
|
||||
self, "Ошибка",
|
||||
"Имя префикса может содержать только латинские буквы, цифры, дефисы и знаки подчеркивания."
|
||||
self,
|
||||
"Ошибка",
|
||||
"Имя префикса может содержать только латинские буквы, цифры, дефисы и знаки подчеркивания.",
|
||||
)
|
||||
return
|
||||
|
||||
@@ -198,7 +215,8 @@ class CreatePrefixDialog(QDialog):
|
||||
self.wine_arch = "win32" if self.arch_win32_radio.isChecked() else "win64"
|
||||
|
||||
current_index = self.prefix_template_selector.currentIndex()
|
||||
self.base_pfx = self.prefix_template_selector.itemData(current_index)['value']
|
||||
self.base_pfx = self.prefix_template_selector.itemData(current_index)["value"]
|
||||
self.selected_wine_version_display = self.wine_version_edit.text()
|
||||
self.selected_windows_version = self.windows_version_combo.currentData()
|
||||
|
||||
self.accept()
|
||||
@@ -1,10 +1,9 @@
|
||||
"""
|
||||
Диалог для управления ассоциациями файлов (WH_XDG_OPEN).
|
||||
"""
|
||||
from PyQt5.QtWidgets import (
|
||||
QDialog, QVBoxLayout, QLineEdit, QLabel, QDialogButtonBox, QMessageBox
|
||||
)
|
||||
|
||||
from PyQt5.QtCore import Qt
|
||||
from PyQt5.QtWidgets import QDialog, QDialogButtonBox, QLabel, QLineEdit, QMessageBox, QVBoxLayout
|
||||
|
||||
|
||||
class FileAssociationsDialog(QDialog):
|
||||
@@ -37,9 +36,7 @@ class FileAssociationsDialog(QDialog):
|
||||
self.associations_edit.setPlaceholderText("Введите расширения через пробел...")
|
||||
layout.addWidget(self.associations_edit)
|
||||
|
||||
forbidden_label = QLabel(
|
||||
"<small><b>Запрещено использовать:</b> cpl, dll, exe, lnk, msi</small>"
|
||||
)
|
||||
forbidden_label = QLabel("<small><b>Запрещено использовать:</b> cpl, dll, exe, lnk, msi</small>")
|
||||
forbidden_label.setTextFormat(Qt.RichText)
|
||||
layout.addWidget(forbidden_label)
|
||||
|
||||
@@ -53,9 +50,7 @@ class FileAssociationsDialog(QDialog):
|
||||
forbidden_extensions = {"cpl", "dll", "exe", "lnk", "msi"}
|
||||
|
||||
input_text = self.associations_edit.text().lower().strip()
|
||||
entered_extensions = {
|
||||
ext.strip() for ext in input_text.split() if ext.strip()
|
||||
}
|
||||
entered_extensions = {ext.strip() for ext in input_text.split() if ext.strip()}
|
||||
|
||||
found_forbidden = entered_extensions.intersection(forbidden_extensions)
|
||||
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
"""
|
||||
Диалог/виджет глобальных настроек WineHelper GUI.
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from PyQt5.QtCore import Qt
|
||||
from PyQt5.QtWidgets import (
|
||||
QComboBox,
|
||||
QDialog,
|
||||
QFileDialog,
|
||||
QFormLayout,
|
||||
QHBoxLayout,
|
||||
QLabel,
|
||||
QLineEdit,
|
||||
QMessageBox,
|
||||
QPushButton,
|
||||
QVBoxLayout,
|
||||
QWidget,
|
||||
)
|
||||
|
||||
from winehelperqt.logger import get_logger, setup_logger
|
||||
from winehelperqt.services.global_settings_service import GlobalSettingsService
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class GlobalSettingsWidget(QWidget):
|
||||
"""Виджет с глобальными настройками приложения."""
|
||||
|
||||
def __init__(self, parent=None):
|
||||
super().__init__(parent)
|
||||
self.settings_service = GlobalSettingsService()
|
||||
self._setup_ui()
|
||||
self._load_settings()
|
||||
|
||||
def _setup_ui(self):
|
||||
"""Создаёт элементы управления."""
|
||||
layout = QVBoxLayout(self)
|
||||
layout.setContentsMargins(20, 20, 20, 20)
|
||||
layout.setSpacing(15)
|
||||
|
||||
form_layout = QFormLayout()
|
||||
form_layout.setSpacing(10)
|
||||
|
||||
self.log_level_label = QLabel("Уровень логирования:")
|
||||
self.log_level_label.setToolTip(
|
||||
"debug — максимально подробный вывод\n"
|
||||
"info — обычный вывод\n"
|
||||
"warning — только предупреждения и ошибки\n"
|
||||
"error — только ошибки"
|
||||
)
|
||||
|
||||
self.log_level_combo = QComboBox()
|
||||
self.log_level_combo.setMinimumWidth(200)
|
||||
self.log_level_combo.addItem("Отладка (debug)", "debug")
|
||||
self.log_level_combo.addItem("Информация (info)", "info")
|
||||
self.log_level_combo.addItem("Предупреждения (warning)", "warning")
|
||||
self.log_level_combo.addItem("Ошибки (error)", "error")
|
||||
|
||||
form_layout.addRow(self.log_level_label, self.log_level_combo)
|
||||
|
||||
self.work_path_label = QLabel("Рабочий каталог:")
|
||||
self.work_path_label.setToolTip(
|
||||
"Каталог, в котором хранятся префиксы, версии Wine и загруженные файлы.\n"
|
||||
"Аналог команды: winehelper data-path /путь/к/каталогу\n"
|
||||
"Данные из текущего каталога не переносятся автоматически.\n"
|
||||
"Изменение применяется после перезапуска WineHelper."
|
||||
)
|
||||
|
||||
self.work_path_edit = QLineEdit()
|
||||
self.work_path_edit.setMinimumWidth(200)
|
||||
self.work_path_edit.setPlaceholderText("/путь/к/каталогу")
|
||||
|
||||
self.work_path_browse_button = QPushButton("Обзор...")
|
||||
self.work_path_browse_button.clicked.connect(self._browse_work_path)
|
||||
self.work_path_browse_button.setFocusPolicy(Qt.NoFocus)
|
||||
|
||||
work_path_layout = QHBoxLayout()
|
||||
work_path_layout.addWidget(self.work_path_edit, 1)
|
||||
work_path_layout.addWidget(self.work_path_browse_button)
|
||||
|
||||
if not self.settings_service.is_work_path_changeable():
|
||||
self.work_path_edit.setEnabled(False)
|
||||
self.work_path_browse_button.setEnabled(False)
|
||||
self.work_path_edit.setToolTip(
|
||||
"Изменение рабочего каталога доступно только для установленной версии WineHelper."
|
||||
)
|
||||
|
||||
form_layout.addRow(self.work_path_label, work_path_layout)
|
||||
|
||||
layout.addLayout(form_layout)
|
||||
|
||||
layout.addStretch()
|
||||
|
||||
button_layout = QHBoxLayout()
|
||||
button_layout.addStretch()
|
||||
|
||||
self.save_button = QPushButton("Сохранить")
|
||||
self.save_button.setMinimumHeight(32)
|
||||
self.save_button.clicked.connect(self._save_settings)
|
||||
self.save_button.setFocusPolicy(Qt.NoFocus)
|
||||
button_layout.addWidget(self.save_button)
|
||||
|
||||
layout.addLayout(button_layout)
|
||||
|
||||
def _load_settings(self):
|
||||
"""Загружает текущие настройки в интерфейс."""
|
||||
current_level = self.settings_service.get_log_level()
|
||||
index = self.log_level_combo.findData(current_level)
|
||||
if index >= 0:
|
||||
self.log_level_combo.setCurrentIndex(index)
|
||||
|
||||
self.work_path_edit.setText(self.settings_service.get_work_path())
|
||||
|
||||
def _browse_work_path(self):
|
||||
"""Открывает диалог выбора рабочего каталога."""
|
||||
current_path = self.work_path_edit.text().strip()
|
||||
directory = QFileDialog.getExistingDirectory(self, "Выбор рабочего каталога", current_path or str(Path.home()))
|
||||
if directory:
|
||||
self.work_path_edit.setText(directory)
|
||||
|
||||
def _save_work_path(self):
|
||||
"""
|
||||
Сохраняет рабочий каталог при его изменении.
|
||||
|
||||
Returns:
|
||||
bool: False если сохранение не удалось (сообщение уже показано).
|
||||
"""
|
||||
new_path = self.work_path_edit.text().strip()
|
||||
if not self.settings_service.is_work_path_changeable() or new_path == self.settings_service.get_work_path():
|
||||
return True
|
||||
|
||||
answer = QMessageBox.question(
|
||||
self,
|
||||
"Изменение рабочего каталога",
|
||||
f"Рабочий каталог будет изменён на:\n{new_path}\n\n"
|
||||
"Данные из текущего каталога (префиксы, версии Wine) не переносятся автоматически.\n"
|
||||
"Изменение вступит в силу после перезапуска WineHelper.\n\nПродолжить?",
|
||||
QMessageBox.Yes | QMessageBox.No,
|
||||
QMessageBox.No,
|
||||
)
|
||||
if answer != QMessageBox.Yes:
|
||||
return False
|
||||
|
||||
success, error = self.settings_service.set_work_path(new_path)
|
||||
if not success:
|
||||
QMessageBox.warning(self, "Ошибка", error)
|
||||
return False
|
||||
return True
|
||||
|
||||
def _save_settings(self):
|
||||
"""Сохраняет настройки и применяет уровень логирования."""
|
||||
if not self._save_work_path():
|
||||
return
|
||||
|
||||
new_level = self.log_level_combo.currentData()
|
||||
if self.settings_service.set_log_level(new_level):
|
||||
setup_logger(new_level)
|
||||
logger.info("Уровень логирования изменён на '%s'", new_level)
|
||||
QMessageBox.information(self, "Сохранено", f"Уровень логирования изменён на '{new_level}'.")
|
||||
else:
|
||||
QMessageBox.warning(self, "Ошибка", "Не удалось сохранить уровень логирования.")
|
||||
|
||||
|
||||
class GlobalSettingsDialog(QDialog):
|
||||
"""Модальный диалог глобальных настроек."""
|
||||
|
||||
def __init__(self, parent=None):
|
||||
super().__init__(parent)
|
||||
self.setWindowTitle("Настройки WineHelper")
|
||||
self.setMinimumWidth(400)
|
||||
self.setModal(True)
|
||||
|
||||
layout = QVBoxLayout(self)
|
||||
layout.setContentsMargins(0, 0, 0, 0)
|
||||
|
||||
self.settings_widget = GlobalSettingsWidget(self)
|
||||
layout.addWidget(self.settings_widget)
|
||||
@@ -5,6 +5,7 @@
|
||||
Выводит информационное окно с инструкциями по устранению проблемы,
|
||||
когда /home примонтирован с флагом noexec и запуск Wine невозможен.
|
||||
"""
|
||||
|
||||
import getpass
|
||||
import sys
|
||||
|
||||
@@ -45,13 +46,9 @@ class NoExecWarningDialog(QDialog):
|
||||
username = getpass.getuser()
|
||||
|
||||
body_style = (
|
||||
"font-family: 'Segoe UI', 'Noto Sans', sans-serif; "
|
||||
"font-size: 14px; color: #e4e4e4; line-height: 1.55;"
|
||||
)
|
||||
warning_style = (
|
||||
"background-color: #3d351f; border-left: 4px solid #ffcc00; "
|
||||
"padding: 12px 14px; margin: 0;"
|
||||
"font-family: 'Segoe UI', 'Noto Sans', sans-serif; font-size: 14px; color: #e4e4e4; line-height: 1.55;"
|
||||
)
|
||||
warning_style = "background-color: #3d351f; border-left: 4px solid #ffcc00; padding: 12px 14px; margin: 0;"
|
||||
warning_text_style = "color: #ffd700; font-weight: bold; text-align: center; margin: 0 0 6px 0;"
|
||||
card_style = "padding: 14px; margin: 0;"
|
||||
title_style = "font-size: 15px; font-weight: bold; color: #ffffff; margin: 0 0 10px 0;"
|
||||
|
||||
@@ -1,19 +1,31 @@
|
||||
"""
|
||||
Диалоги для дополнительных настроек префикса и приложений.
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
from PyQt5.QtWidgets import (
|
||||
QDialog, QVBoxLayout, QHBoxLayout, QGridLayout, QPushButton,
|
||||
QLabel, QCheckBox, QComboBox, QMessageBox, QSizePolicy
|
||||
)
|
||||
from PyQt5.QtCore import Qt
|
||||
from PyQt5.QtWidgets import (
|
||||
QCheckBox,
|
||||
QComboBox,
|
||||
QDialog,
|
||||
QGridLayout,
|
||||
QHBoxLayout,
|
||||
QLabel,
|
||||
QMessageBox,
|
||||
QPushButton,
|
||||
QSizePolicy,
|
||||
QVBoxLayout,
|
||||
)
|
||||
|
||||
from winehelperqt.logger import get_logger
|
||||
from winehelperqt.utils.export_utils import ExportUtils
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class AdditionalSettingsDialog(QDialog):
|
||||
"""Диалог для дополнительных настроек префикса (ESync, FSync, DXVK, VKD3D)."""
|
||||
"""Диалог для дополнительных настроек префикса (ESync, FSync, DXVK, VKD3D, Windows)."""
|
||||
|
||||
def __init__(self, prefix_name, parent=None):
|
||||
super().__init__(parent)
|
||||
@@ -65,17 +77,13 @@ class AdditionalSettingsDialog(QDialog):
|
||||
# DXVK/VKD3D
|
||||
self.dxvk_manage_button = QPushButton("Управление DXVK")
|
||||
self.dxvk_manage_button.setMinimumHeight(32)
|
||||
self.dxvk_manage_button.clicked.connect(
|
||||
lambda: self._open_component_manager('dxvk')
|
||||
)
|
||||
self.dxvk_manage_button.clicked.connect(lambda: self._open_component_manager("dxvk"))
|
||||
self.dxvk_manage_button.setToolTip("Установка или удаление определенной версии DXVK в префиксе.")
|
||||
grid_layout.addWidget(self.dxvk_manage_button, 1, 0)
|
||||
|
||||
self.vkd3d_manage_button = QPushButton("Управление VKD3D")
|
||||
self.vkd3d_manage_button.setMinimumHeight(32)
|
||||
self.vkd3d_manage_button.clicked.connect(
|
||||
lambda: self._open_component_manager('vkd3d-proton')
|
||||
)
|
||||
self.vkd3d_manage_button.clicked.connect(lambda: self._open_component_manager("vkd3d-proton"))
|
||||
self.vkd3d_manage_button.setToolTip("Установка или удаление определенной версии vkd3d-proton в префиксе.")
|
||||
grid_layout.addWidget(self.vkd3d_manage_button, 1, 1)
|
||||
|
||||
@@ -109,6 +117,14 @@ class AdditionalSettingsDialog(QDialog):
|
||||
grid_layout.addWidget(self.cpcsp_proxy_button, 2, 1)
|
||||
self.cpcsp_proxy_button.setFocusPolicy(Qt.NoFocus)
|
||||
|
||||
# Версия Windows
|
||||
self.windows_version_button = QPushButton("Версия Windows")
|
||||
self.windows_version_button.setMinimumHeight(32)
|
||||
self.windows_version_button.clicked.connect(self.parent_gui.open_windows_version_manager)
|
||||
self.windows_version_button.setToolTip("Изменить версию Windows, которую Wine сообщает приложениям в префиксе.")
|
||||
grid_layout.addWidget(self.windows_version_button, 3, 0)
|
||||
self.windows_version_button.setFocusPolicy(Qt.NoFocus)
|
||||
|
||||
layout.addLayout(grid_layout)
|
||||
|
||||
self.close_button = QPushButton("Закрыть")
|
||||
@@ -124,16 +140,11 @@ class AdditionalSettingsDialog(QDialog):
|
||||
self.parent_gui.update_sync_option(option_name, is_checked)
|
||||
|
||||
def _toggle_cpcsp_proxy(self, is_checked, button):
|
||||
"""Обновляет опцию CPCSP_PROXY и запускает установку при включении."""
|
||||
"""Включает/выключает CPCSP_PROXY через winehelper cpcsp-proxy enable/disable."""
|
||||
if is_checked:
|
||||
# Сначала сохраняем WH_USE_CPCSP_PROXY="1" в last.conf,
|
||||
# чтобы winehelper init-prefix прочитал его при запуске
|
||||
self.parent_gui.update_sync_option("WH_USE_CPCSP_PROXY", True)
|
||||
|
||||
def on_install_finished(success):
|
||||
if not success:
|
||||
# При ошибке откатываем значение в last.conf и сбрасываем кнопку
|
||||
self.parent_gui.update_sync_option("WH_USE_CPCSP_PROXY", False)
|
||||
button.blockSignals(True)
|
||||
button.setChecked(False)
|
||||
self._update_button_text(button, "CPCSP_PROXY", False)
|
||||
@@ -141,7 +152,7 @@ class AdditionalSettingsDialog(QDialog):
|
||||
|
||||
self.parent_gui.run_cpcsp_proxy_install(self.prefix_name, on_install_finished)
|
||||
else:
|
||||
self.parent_gui.update_sync_option("WH_USE_CPCSP_PROXY", False)
|
||||
self.parent_gui.run_cpcsp_proxy_disable(self.prefix_name)
|
||||
|
||||
def _update_button_text(self, button, base_text, is_checked):
|
||||
"""Обновляет текст кнопки, добавляя или убирая галочку."""
|
||||
@@ -156,15 +167,11 @@ class AdditionalSettingsDialog(QDialog):
|
||||
|
||||
def update_button_states(self):
|
||||
"""Обновляет состояние кнопок на основе данных из last.conf."""
|
||||
esync_enabled = self.parent_gui._get_prefix_component_version(
|
||||
self.prefix_name, "WINEESYNC"
|
||||
) == "1"
|
||||
fsync_enabled = self.parent_gui._get_prefix_component_version(
|
||||
self.prefix_name, "WINEFSYNC"
|
||||
) == "1"
|
||||
cpcsp_proxy_enabled = self.parent_gui._get_prefix_component_version(
|
||||
self.prefix_name, "WH_USE_CPCSP_PROXY"
|
||||
) == "1"
|
||||
esync_enabled = self.parent_gui._get_prefix_component_version(self.prefix_name, "WINEESYNC") == "1"
|
||||
fsync_enabled = self.parent_gui._get_prefix_component_version(self.prefix_name, "WINEFSYNC") == "1"
|
||||
cpcsp_proxy_enabled = (
|
||||
self.parent_gui._get_prefix_component_version(self.prefix_name, "WH_USE_CPCSP_PROXY") == "1"
|
||||
)
|
||||
|
||||
self.esync_button.blockSignals(True)
|
||||
self.fsync_button.blockSignals(True)
|
||||
@@ -190,14 +197,14 @@ class AppAdditionalSettingsDialog(QDialog):
|
||||
super().__init__(parent)
|
||||
self.parent_gui = parent
|
||||
self.exe_path = os.path.abspath(exe_path)
|
||||
self.whdb_path = self.exe_path + '.whdb'
|
||||
self.whdb_path = self.exe_path + ".whdb"
|
||||
|
||||
self.settings = {
|
||||
'WH_MAIN_DECORATED': 'default',
|
||||
'WH_VIRTUAL_DESKTOP': 'default',
|
||||
'WH_FONT_SMOOTHING': '0',
|
||||
'WH_FONT_MSS_REPLACE': '0',
|
||||
'WINE_D3D_CONFIG': ''
|
||||
"WH_MAIN_DECORATED": "default",
|
||||
"WH_VIRTUAL_DESKTOP": "default",
|
||||
"WH_FONT_SMOOTHING": "0",
|
||||
"WH_FONT_MSS_REPLACE": "0",
|
||||
"WINE_D3D_CONFIG": "",
|
||||
}
|
||||
|
||||
self.setWindowTitle("Дополнительные настройки приложения")
|
||||
@@ -242,9 +249,7 @@ class AppAdditionalSettingsDialog(QDialog):
|
||||
|
||||
self.wine_d3d_config_combo = QComboBox()
|
||||
self.wine_d3d_config_combo.setMinimumWidth(250)
|
||||
self.wine_d3d_config_combo.setSizePolicy(
|
||||
QSizePolicy.Preferred, QSizePolicy.Preferred
|
||||
)
|
||||
self.wine_d3d_config_combo.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
|
||||
self.wine_d3d_config_combo.addItem("Не задано", "")
|
||||
self.wine_d3d_config_combo.addItem("renderer=vulkan", "renderer=vulkan")
|
||||
self.wine_d3d_config_combo.addItem("renderer=gdi", "renderer=gdi")
|
||||
@@ -282,10 +287,10 @@ class AppAdditionalSettingsDialog(QDialog):
|
||||
return
|
||||
|
||||
try:
|
||||
with open(self.whdb_path, 'r', encoding='utf-8') as f:
|
||||
with open(self.whdb_path, "r", encoding="utf-8") as f:
|
||||
content = f.read()
|
||||
|
||||
for line in content.split('\n'):
|
||||
for line in content.split("\n"):
|
||||
var_name, var_value = self._parse_export_line(line)
|
||||
if var_name and var_name in self.settings:
|
||||
self.settings[var_name] = var_value
|
||||
@@ -293,29 +298,21 @@ class AppAdditionalSettingsDialog(QDialog):
|
||||
self._update_ui_from_settings()
|
||||
|
||||
except Exception as e:
|
||||
QMessageBox.warning(
|
||||
self, "Ошибка",
|
||||
f"Не удалось прочитать файл настроек:\n{self.whdb_path}\n\nОшибка: {e}"
|
||||
)
|
||||
logger.warning("Не удалось прочитать файл настроек %s: %s", self.whdb_path, e)
|
||||
QMessageBox.warning(self, "Ошибка", f"Не удалось прочитать файл настроек:\n{self.whdb_path}\n\nОшибка: {e}")
|
||||
self._update_ui_from_settings()
|
||||
|
||||
def _update_ui_from_settings(self):
|
||||
"""Обновляет элементы управления на основе загруженных настроек."""
|
||||
self.wh_main_decorated_checkbox.setChecked(
|
||||
self.settings.get('WH_MAIN_DECORATED') == '1'
|
||||
)
|
||||
wh_virtual_desktop = self.settings.get('WH_VIRTUAL_DESKTOP', '')
|
||||
self.wh_main_decorated_checkbox.setChecked(self.settings.get("WH_MAIN_DECORATED") == "1")
|
||||
wh_virtual_desktop = self.settings.get("WH_VIRTUAL_DESKTOP", "")
|
||||
self.wh_virtual_desktop_checkbox.setChecked(
|
||||
wh_virtual_desktop == '1' or wh_virtual_desktop.lower() not in ('0', 'default', '')
|
||||
)
|
||||
self.wh_font_smoothing_checkbox.setChecked(
|
||||
self.settings.get('WH_FONT_SMOOTHING') == '1'
|
||||
)
|
||||
self.wh_font_mss_replace_checkbox.setChecked(
|
||||
self.settings.get('WH_FONT_MSS_REPLACE') == '1'
|
||||
wh_virtual_desktop == "1" or wh_virtual_desktop.lower() not in ("0", "default", "")
|
||||
)
|
||||
self.wh_font_smoothing_checkbox.setChecked(self.settings.get("WH_FONT_SMOOTHING") == "1")
|
||||
self.wh_font_mss_replace_checkbox.setChecked(self.settings.get("WH_FONT_MSS_REPLACE") == "1")
|
||||
|
||||
d3d_value = self.settings.get('WINE_D3D_CONFIG', '')
|
||||
d3d_value = self.settings.get("WINE_D3D_CONFIG", "")
|
||||
index = self.wine_d3d_config_combo.findData(d3d_value)
|
||||
if index >= 0:
|
||||
self.wine_d3d_config_combo.setCurrentIndex(index)
|
||||
@@ -327,36 +324,34 @@ class AppAdditionalSettingsDialog(QDialog):
|
||||
try:
|
||||
existing_lines = []
|
||||
if os.path.exists(self.whdb_path):
|
||||
with open(self.whdb_path, 'r', encoding='utf-8') as f:
|
||||
with open(self.whdb_path, "r", encoding="utf-8") as f:
|
||||
existing_lines = f.readlines()
|
||||
|
||||
settings_values = {
|
||||
var_name: self._get_setting_value(var_name)
|
||||
for var_name in self.settings
|
||||
}
|
||||
settings_values = {var_name: self._get_setting_value(var_name) for var_name in self.settings}
|
||||
new_lines = ExportUtils.update_lines(existing_lines, settings_values)
|
||||
|
||||
with open(self.whdb_path, 'w', encoding='utf-8') as f:
|
||||
with open(self.whdb_path, "w", encoding="utf-8") as f:
|
||||
f.writelines(new_lines)
|
||||
|
||||
self.accept()
|
||||
|
||||
except Exception as e:
|
||||
logger.error("Не удалось сохранить файл настроек %s: %s", self.whdb_path, e)
|
||||
QMessageBox.critical(self, "Ошибка", f"Не удалось сохранить настройки:\n{e}")
|
||||
|
||||
def _get_setting_value(self, var_name):
|
||||
"""Возвращает текущее значение переменной из UI."""
|
||||
if var_name == 'WINE_D3D_CONFIG':
|
||||
if var_name == "WINE_D3D_CONFIG":
|
||||
return self.wine_d3d_config_combo.currentData()
|
||||
if var_name == 'WH_MAIN_DECORATED':
|
||||
return '1' if self.wh_main_decorated_checkbox.isChecked() else 'default'
|
||||
if var_name == 'WH_VIRTUAL_DESKTOP':
|
||||
return '1' if self.wh_virtual_desktop_checkbox.isChecked() else 'default'
|
||||
if var_name == 'WH_FONT_SMOOTHING':
|
||||
return '1' if self.wh_font_smoothing_checkbox.isChecked() else '0'
|
||||
if var_name == 'WH_FONT_MSS_REPLACE':
|
||||
return '1' if self.wh_font_mss_replace_checkbox.isChecked() else '0'
|
||||
return ''
|
||||
if var_name == "WH_MAIN_DECORATED":
|
||||
return "1" if self.wh_main_decorated_checkbox.isChecked() else "default"
|
||||
if var_name == "WH_VIRTUAL_DESKTOP":
|
||||
return "1" if self.wh_virtual_desktop_checkbox.isChecked() else "default"
|
||||
if var_name == "WH_FONT_SMOOTHING":
|
||||
return "1" if self.wh_font_smoothing_checkbox.isChecked() else "0"
|
||||
if var_name == "WH_FONT_MSS_REPLACE":
|
||||
return "1" if self.wh_font_mss_replace_checkbox.isChecked() else "0"
|
||||
return ""
|
||||
|
||||
@staticmethod
|
||||
def _parse_export_line(line):
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
"""
|
||||
Диалог для выбора версии Windows в префиксе Wine.
|
||||
"""
|
||||
|
||||
from PyQt5.QtWidgets import QComboBox, QDialog, QHBoxLayout, QLabel, QPushButton, QVBoxLayout
|
||||
|
||||
|
||||
class WindowsVersionSelectionDialog(QDialog):
|
||||
"""Диалог выбора версии Windows, сообщаемой приложениям в префиксе."""
|
||||
|
||||
WINDOWS_VERSIONS = [
|
||||
("Windows 2000", "2k"),
|
||||
("Windows XP", "xp"),
|
||||
("Windows XP 64-bit", "xp64"),
|
||||
("Windows Server 2003", "2k3"),
|
||||
("Windows Vista", "vista"),
|
||||
("Windows 7", "7"),
|
||||
("Windows 8", "8"),
|
||||
("Windows 8.1", "81"),
|
||||
("Windows 10", "10"),
|
||||
("Windows 11", "11"),
|
||||
]
|
||||
|
||||
def __init__(self, current_version="10", parent=None):
|
||||
"""
|
||||
Инициализирует диалог выбора версии Windows.
|
||||
|
||||
Args:
|
||||
current_version: Текущая версия Windows из last.conf (по умолчанию "10")
|
||||
parent: Родительский виджет
|
||||
"""
|
||||
super().__init__(parent)
|
||||
self.setWindowTitle("Выбор версии Windows")
|
||||
self.setMinimumWidth(380)
|
||||
self.setModal(True)
|
||||
|
||||
self.selected_version = None
|
||||
|
||||
layout = QVBoxLayout(self)
|
||||
layout.setSpacing(10)
|
||||
|
||||
info_label = QLabel("Выберите версию Windows, которую Wine будет сообщать приложениям в префиксе.")
|
||||
info_label.setWordWrap(True)
|
||||
layout.addWidget(info_label)
|
||||
|
||||
self.version_combo = QComboBox()
|
||||
self.version_combo.setMinimumHeight(32)
|
||||
for display_name, value in self.WINDOWS_VERSIONS:
|
||||
self.version_combo.addItem(display_name, value)
|
||||
|
||||
index = self.version_combo.findData(current_version)
|
||||
if index >= 0:
|
||||
self.version_combo.setCurrentIndex(index)
|
||||
|
||||
layout.addWidget(self.version_combo)
|
||||
|
||||
button_layout = QHBoxLayout()
|
||||
button_layout.addStretch()
|
||||
|
||||
self.ok_button = QPushButton("Применить")
|
||||
self.ok_button.setMinimumHeight(32)
|
||||
self.ok_button.clicked.connect(self._accept)
|
||||
self.ok_button.setDefault(True)
|
||||
button_layout.addWidget(self.ok_button)
|
||||
|
||||
self.cancel_button = QPushButton("Отмена")
|
||||
self.cancel_button.setMinimumHeight(32)
|
||||
self.cancel_button.clicked.connect(self.reject)
|
||||
button_layout.addWidget(self.cancel_button)
|
||||
|
||||
layout.addLayout(button_layout)
|
||||
|
||||
def _accept(self):
|
||||
"""Сохраняет выбранную версию и закрывает диалог."""
|
||||
self.selected_version = self.version_combo.currentData()
|
||||
self.accept()
|
||||
@@ -1,18 +1,16 @@
|
||||
"""
|
||||
Диалог для выбора версии Wine с группировкой.
|
||||
"""
|
||||
|
||||
import re
|
||||
from functools import partial
|
||||
|
||||
from PyQt5.QtWidgets import (
|
||||
QGridLayout, QScrollArea, QTabWidget, QPushButton, QLabel, QWidget, QVBoxLayout,
|
||||
QHBoxLayout
|
||||
)
|
||||
from PyQt5.QtCore import Qt
|
||||
from PyQt5.QtWidgets import QGridLayout, QHBoxLayout, QLabel, QPushButton, QScrollArea, QTabWidget, QVBoxLayout, QWidget
|
||||
|
||||
from winehelperqt.dialogs.base_version_dialog import WineVersionSelectionDialogBase
|
||||
from winehelperqt.utils.version_utils import sort_versions
|
||||
from winehelperqt.utils.grid_utils import GridUtils
|
||||
from winehelperqt.utils.version_utils import sort_versions
|
||||
|
||||
|
||||
class VersionButtonWidget(QPushButton):
|
||||
@@ -93,7 +91,7 @@ class VersionButtonWidget(QPushButton):
|
||||
def setText(self, text):
|
||||
"""Устанавливает текст метки названия версии."""
|
||||
self.display_name = text
|
||||
if hasattr(self, 'name_label'):
|
||||
if hasattr(self, "name_label"):
|
||||
self.name_label.setText(text)
|
||||
|
||||
|
||||
@@ -179,23 +177,14 @@ class WineVersionSelectionDialog(WineVersionSelectionDialogBase):
|
||||
if is_win64:
|
||||
allowed_groups_for_arch = {"WINE AMD64", "WINE WOW64"}
|
||||
tab_order = ["WINE WOW64", "WINE AMD64"]
|
||||
display_names = {
|
||||
"WINE WOW64": "Загрузить wine-wow64",
|
||||
"WINE AMD64": "Загрузить wine-amd64"
|
||||
}
|
||||
display_names = {"WINE WOW64": "Загрузить wine-wow64", "WINE AMD64": "Загрузить wine-amd64"}
|
||||
else:
|
||||
allowed_groups_for_arch = {"WINE I586", "WINE AMD64"}
|
||||
tab_order = ["WINE I586", "WINE AMD64"]
|
||||
display_names = {
|
||||
"WINE I586": "Загрузить wine-i586",
|
||||
"WINE AMD64": "Загрузить wine-amd64"
|
||||
}
|
||||
display_names = {"WINE I586": "Загрузить wine-i586", "WINE AMD64": "Загрузить wine-amd64"}
|
||||
|
||||
available_keys = [
|
||||
key for key in self.wine_versions_data.keys()
|
||||
if key in allowed_groups_for_arch
|
||||
]
|
||||
group_keys = sorted(available_keys, key=lambda k: tab_order.index(k))
|
||||
available_keys = [key for key in self.wine_versions_data if key in allowed_groups_for_arch]
|
||||
group_keys = sorted(available_keys, key=tab_order.index)
|
||||
|
||||
for key in group_keys:
|
||||
versions = self.wine_versions_data.get(key, [])
|
||||
@@ -230,7 +219,7 @@ class WineVersionSelectionDialog(WineVersionSelectionDialogBase):
|
||||
"""Создает кнопки для версий в сетке."""
|
||||
is_win64_prefix = self.architecture == "win64"
|
||||
is_win32_prefix = self.architecture == "win32"
|
||||
re_32bit_version = re.compile(r'i[3-6]86|i586')
|
||||
re_32bit_version = re.compile(r"i[3-6]86|i586")
|
||||
|
||||
row, col = 0, 0
|
||||
for version_data in versions_list:
|
||||
@@ -268,7 +257,7 @@ class WineVersionSelectionDialog(WineVersionSelectionDialogBase):
|
||||
|
||||
# Отключение 64-битных версий для 32-битного префикса
|
||||
if not is_download_tab and is_win32_prefix:
|
||||
if value_name == "system" or 'wow64' in value_name:
|
||||
if value_name == "system" or "wow64" in value_name:
|
||||
btn.setEnabled(False)
|
||||
btn.setToolTip("Эта 64-битная версия Wine несовместима с 32-битным префиксом.")
|
||||
|
||||
@@ -288,11 +277,8 @@ class WineVersionSelectionDialog(WineVersionSelectionDialogBase):
|
||||
search_text = self.search_edit.text()
|
||||
|
||||
# Фильтр для вкладки "Установленные"
|
||||
if hasattr(self, 'installed_grid_layout'):
|
||||
GridUtils.filter_buttons(
|
||||
self.installed_buttons, search_text,
|
||||
self.installed_grid_layout, self.NUM_COLUMNS
|
||||
)
|
||||
if hasattr(self, "installed_grid_layout"):
|
||||
GridUtils.filter_buttons(self.installed_buttons, search_text, self.installed_grid_layout, self.NUM_COLUMNS)
|
||||
|
||||
# Фильтр для вкладок с версиями (теперь напрямую в main_tabs)
|
||||
# Пропускаем первую вкладку "Установленные" (индекс 0)
|
||||
@@ -300,9 +286,7 @@ class WineVersionSelectionDialog(WineVersionSelectionDialogBase):
|
||||
tab_widget = self.main_tabs.widget(i)
|
||||
grid_layout, buttons = self._get_grid_layout_and_buttons(tab_widget)
|
||||
if grid_layout:
|
||||
visible = GridUtils.filter_buttons(
|
||||
buttons, search_text, grid_layout, self.NUM_COLUMNS
|
||||
)
|
||||
visible = GridUtils.filter_buttons(buttons, search_text, grid_layout, self.NUM_COLUMNS)
|
||||
self.main_tabs.setTabEnabled(i, bool(visible))
|
||||
|
||||
def _get_grid_layout_and_buttons(self, tab_widget):
|
||||
|
||||
@@ -1,21 +1,37 @@
|
||||
"""
|
||||
Диалог для управления компонентами Winetricks.
|
||||
"""
|
||||
|
||||
import os
|
||||
import shlex
|
||||
from functools import partial
|
||||
|
||||
from PyQt5.QtCore import QProcess, QProcessEnvironment, Qt, QTimer, pyqtSignal
|
||||
from PyQt5.QtGui import QFont, QTextCharFormat, QTextCursor
|
||||
from PyQt5.QtWidgets import (
|
||||
QDialog, QVBoxLayout, QHBoxLayout, QPushButton, QTabWidget,
|
||||
QTextEdit, QListWidget, QListWidgetItem, QMessageBox, QLineEdit, QWidget
|
||||
QDialog,
|
||||
QHBoxLayout,
|
||||
QLineEdit,
|
||||
QListWidget,
|
||||
QListWidgetItem,
|
||||
QMessageBox,
|
||||
QPushButton,
|
||||
QTabWidget,
|
||||
QTextEdit,
|
||||
QVBoxLayout,
|
||||
QWidget,
|
||||
)
|
||||
from PyQt5.QtCore import Qt, QProcess, QTimer, QProcessEnvironment, pyqtSignal
|
||||
from PyQt5.QtGui import QTextCursor, QTextCharFormat, QFont
|
||||
|
||||
from winehelperqt.logger import get_logger
|
||||
from winehelperqt.parsers.winetricks_parser import WinetricksOutputParser
|
||||
from winehelperqt.services.winetricks_service import WinetricksLogReader, WinetricksCacheService
|
||||
from winehelperqt.utils.environment import EnvironmentConfig
|
||||
from winehelperqt.services.winetricks_service import WinetricksCacheService, WinetricksLogReader
|
||||
from winehelperqt.utils.dialog_utils import DialogUtils
|
||||
from winehelperqt.utils.environment import EnvironmentConfig
|
||||
|
||||
logger = get_logger(__name__)
|
||||
# Отдельный логгер для вывода внешних процессов (bash, winetricks),
|
||||
# чтобы в консоли отличать его от событий самого GUI
|
||||
process_logger = get_logger("process")
|
||||
|
||||
|
||||
class NoAutoScrollListWidget(QListWidget):
|
||||
@@ -55,8 +71,8 @@ class WinetricksManagerDialog(QDialog):
|
||||
super().__init__(parent)
|
||||
self.prefix_path = prefix_path
|
||||
self.winetricks_path = winetricks_path
|
||||
self.wine_executable = wine_executable or 'wine'
|
||||
self.winehelper_path = winehelper_path or 'winehelper'
|
||||
self.wine_executable = wine_executable or "wine"
|
||||
self.winehelper_path = winehelper_path or "winehelper"
|
||||
self.initial_states = {}
|
||||
self.apply_process = None
|
||||
self.installation_finished = False
|
||||
@@ -77,11 +93,7 @@ class WinetricksManagerDialog(QDialog):
|
||||
self.tabs = QTabWidget()
|
||||
main_layout.addWidget(self.tabs)
|
||||
|
||||
self.categories = {
|
||||
"Библиотеки": "dlls",
|
||||
"Шрифты": "fonts",
|
||||
"Настройки": "settings"
|
||||
}
|
||||
self.categories = {"Библиотеки": "dlls", "Шрифты": "fonts", "Настройки": "settings"}
|
||||
self.list_widgets = {}
|
||||
self.search_edits = {}
|
||||
for display_name, internal_name in self.categories.items():
|
||||
@@ -91,7 +103,7 @@ class WinetricksManagerDialog(QDialog):
|
||||
|
||||
self.log_output = QTextEdit()
|
||||
self.log_output.setReadOnly(True)
|
||||
self.log_output.setFont(QFont('DejaVu Sans Mono', 10))
|
||||
self.log_output.setFont(QFont("DejaVu Sans Mono", 10))
|
||||
self.log_output.setMaximumHeight(150)
|
||||
self.log_output.setText(self.INFO_TEXT)
|
||||
main_layout.addWidget(self.log_output)
|
||||
@@ -151,7 +163,8 @@ class WinetricksManagerDialog(QDialog):
|
||||
layout.addWidget(search_edit)
|
||||
|
||||
list_widget = NoAutoScrollListWidget()
|
||||
list_widget.setAutoScroll(False) # Отключаем автопрокрутку
|
||||
list_widget.setAutoScroll(False)
|
||||
list_widget.setTextElideMode(Qt.ElideNone)
|
||||
list_widget.itemChanged.connect(self._on_item_changed)
|
||||
list_widget.currentItemChanged.connect(self._update_ui_state)
|
||||
layout.addWidget(list_widget)
|
||||
@@ -195,9 +208,9 @@ class WinetricksManagerDialog(QDialog):
|
||||
"""Запускает QProcess для получения списка компонентов, используя кэш."""
|
||||
cached_output = self.cache_service.get_cached_data(category, self.winetricks_path)
|
||||
if cached_output is not None:
|
||||
QTimer.singleShot(0, lambda: self._on_load_finished(
|
||||
category, 0, QProcess.NormalExit, from_cache=cached_output
|
||||
))
|
||||
QTimer.singleShot(
|
||||
0, lambda: self._on_load_finished(category, 0, QProcess.NormalExit, from_cache=cached_output)
|
||||
)
|
||||
return
|
||||
|
||||
process = QProcess(self)
|
||||
@@ -209,6 +222,11 @@ class WinetricksManagerDialog(QDialog):
|
||||
process.setProcessEnvironment(env)
|
||||
|
||||
process.finished.connect(partial(self._on_load_finished, category))
|
||||
logger.debug(
|
||||
"Запуск загрузки списка winetricks: %s %s",
|
||||
shlex.quote(self.winehelper_path),
|
||||
["winetricks", category, "list"],
|
||||
)
|
||||
process.start(self.winehelper_path, ["winetricks", category, "list"])
|
||||
|
||||
def _parse_winetricks_log(self):
|
||||
@@ -239,16 +257,13 @@ class WinetricksManagerDialog(QDialog):
|
||||
process = None
|
||||
else:
|
||||
process = self.processes[category]
|
||||
output = process.readAllStandardOutput().data().decode('utf-8', 'ignore')
|
||||
output = process.readAllStandardOutput().data().decode("utf-8", "ignore")
|
||||
|
||||
list_widget = self.list_widgets.get(category)
|
||||
if list_widget is None:
|
||||
return
|
||||
|
||||
category_display_name = next(
|
||||
(k for k, v in self.categories.items() if v == category),
|
||||
category
|
||||
)
|
||||
category_display_name = next((k for k, v in self.categories.items() if v == category), category)
|
||||
|
||||
list_widget.clear()
|
||||
|
||||
@@ -273,7 +288,7 @@ class WinetricksManagerDialog(QDialog):
|
||||
self._log(output)
|
||||
self._log("--------------------------------------------------")
|
||||
|
||||
has_errors = any(status == 'error' for status in self.category_statuses.values())
|
||||
has_errors = any(status == "error" for status in self.category_statuses.values())
|
||||
|
||||
self.loading_count -= 1
|
||||
if self.loading_count == 0:
|
||||
@@ -441,8 +456,8 @@ class WinetricksManagerDialog(QDialog):
|
||||
try:
|
||||
self.apply_process.readyReadStandardOutput.disconnect()
|
||||
self.apply_process.finished.disconnect(self.on_apply_finished)
|
||||
except TypeError:
|
||||
pass
|
||||
except TypeError as e:
|
||||
logger.debug("Отсутствуют подключенные обработчики процесса winetricks: %s", e)
|
||||
|
||||
self.apply_process = QProcess(self)
|
||||
self.apply_process.setProcessChannelMode(QProcess.MergedChannels)
|
||||
@@ -451,8 +466,8 @@ class WinetricksManagerDialog(QDialog):
|
||||
env.insert("WINEPREFIX", self.prefix_path)
|
||||
self.apply_process.setProcessEnvironment(env)
|
||||
self.apply_process.readyReadStandardOutput.connect(
|
||||
lambda: self.log_output.append(
|
||||
self.apply_process.readAllStandardOutput().data().decode('utf-8', 'ignore').strip()
|
||||
lambda: self._log(
|
||||
self.apply_process.readAllStandardOutput().data().decode("utf-8", "ignore").strip(), process=True
|
||||
)
|
||||
)
|
||||
self.apply_process.finished.connect(self.on_apply_finished)
|
||||
@@ -474,7 +489,7 @@ class WinetricksManagerDialog(QDialog):
|
||||
"Ошибка",
|
||||
"Произошла ошибка во время выполнения операций.\nПодробности смотрите в логе.",
|
||||
QMessageBox.Warning,
|
||||
{"buttons": {"OK": QMessageBox.AcceptRole}}
|
||||
{"buttons": {"OK": QMessageBox.AcceptRole}},
|
||||
)
|
||||
self.log_output.setCurrentCharFormat(QTextCharFormat())
|
||||
self.apply_button.setEnabled(True)
|
||||
@@ -506,7 +521,7 @@ class WinetricksManagerDialog(QDialog):
|
||||
"Вы собираетесь удалить все скачанные установщики и списки компонентов Winetricks.\n\n"
|
||||
"Это действие может потребоваться, если у вас возникают проблемы "
|
||||
"со скачиванием или установкой компонентов.\n\n"
|
||||
"Продолжить?"
|
||||
"Продолжить?",
|
||||
):
|
||||
return
|
||||
|
||||
@@ -522,7 +537,7 @@ class WinetricksManagerDialog(QDialog):
|
||||
self.cache_clear_process.setProcessChannelMode(QProcess.MergedChannels)
|
||||
|
||||
def handle_output():
|
||||
output = self.cache_clear_process.readAll().data().decode('utf-8', 'ignore').strip()
|
||||
output = self.cache_clear_process.readAll().data().decode("utf-8", "ignore").strip()
|
||||
if output:
|
||||
self._log(output)
|
||||
|
||||
@@ -530,7 +545,7 @@ class WinetricksManagerDialog(QDialog):
|
||||
if exit_code == 0:
|
||||
self.is_reloading_after_cache_clear = True
|
||||
self.category_statuses.clear()
|
||||
self.cache_service._ensure_cache_dir()
|
||||
self.cache_service.ensure_cache_dir()
|
||||
self._log("Обновление списков...")
|
||||
self.initial_states.clear()
|
||||
self.load_all_categories()
|
||||
@@ -545,7 +560,7 @@ class WinetricksManagerDialog(QDialog):
|
||||
self.cache_clear_process.readyRead.connect(handle_output)
|
||||
self.cache_clear_process.finished.connect(handle_finish)
|
||||
|
||||
if self.parent() and hasattr(self.parent(), 'winehelper_path'):
|
||||
if self.parent() and hasattr(self.parent(), "winehelper_path"):
|
||||
winehelper_path = self.parent().winehelper_path
|
||||
else:
|
||||
winehelper_path = EnvironmentConfig.RUN_SCRIPT
|
||||
@@ -558,22 +573,39 @@ class WinetricksManagerDialog(QDialog):
|
||||
"""Обрабатывает закрытие окна."""
|
||||
if self.apply_process and self.apply_process.state() == QProcess.Running:
|
||||
if DialogUtils.confirm(
|
||||
self,
|
||||
'Подтверждение',
|
||||
"Процесс установки еще не завершен. Вы уверены, что хотите прервать его?"
|
||||
self, "Подтверждение", "Процесс установки еще не завершен. Вы уверены, что хотите прервать его?"
|
||||
):
|
||||
self.user_cancelled = True
|
||||
self.log_output.append("\n=== Прерывание установки... Ожидание завершения процесса... ===")
|
||||
self.apply_process.terminate()
|
||||
event.ignore()
|
||||
else:
|
||||
# Корректно завершаем фоновые процессы (загрузка категорий, очистка кэша)
|
||||
for process in list(self.processes.values()):
|
||||
if process.state() == QProcess.Running:
|
||||
process.terminate()
|
||||
if self.cache_clear_process and self.cache_clear_process.state() == QProcess.Running:
|
||||
self.cache_clear_process.terminate()
|
||||
event.accept()
|
||||
|
||||
def _log(self, message, color=None):
|
||||
"""Добавляет сообщение в лог с возможностью указания цвета."""
|
||||
def _log(self, message, color=None, process=False):
|
||||
"""
|
||||
Добавляет сообщение в лог с возможностью указания цвета.
|
||||
|
||||
Args:
|
||||
message: Текст сообщения
|
||||
color: Цвет текста (например, "red")
|
||||
process: True если это вывод внешнего процесса (bash, winetricks)
|
||||
"""
|
||||
if color:
|
||||
self.log_output.append(f'<span style="color:{color};">{message}</span>')
|
||||
self.log_output.setCurrentCharFormat(QTextCharFormat())
|
||||
else:
|
||||
self.log_output.append(message)
|
||||
self.log_output.moveCursor(QTextCursor.End)
|
||||
if message.strip():
|
||||
target_logger = process_logger if process else logger
|
||||
if color == "red":
|
||||
target_logger.error("%s", message)
|
||||
else:
|
||||
target_logger.info("%s", message)
|
||||
@@ -0,0 +1,51 @@
|
||||
"""
|
||||
Единый логгер приложения.
|
||||
|
||||
По умолчанию пишет в stdout — виден при запуске GUI из терминала
|
||||
(``./winehelper gui``). При запуске из меню терминала нет, вывод
|
||||
просто уходит в никуда, ничего не ломая.
|
||||
|
||||
Уровень задаётся переменной окружения ``WH_LOG_LEVEL``
|
||||
(debug/info/warning/error, по умолчанию info).
|
||||
|
||||
Использование в модулях::
|
||||
|
||||
from winehelperqt.logger import get_logger
|
||||
logger = get_logger(__name__)
|
||||
"""
|
||||
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
|
||||
DEFAULT_LEVEL = "INFO"
|
||||
|
||||
|
||||
def setup_logger(level: str | None = None) -> None:
|
||||
"""
|
||||
Настраивает корневой логгер приложения.
|
||||
|
||||
Args:
|
||||
level: Уровень логирования (debug/info/warning/error).
|
||||
Если не задан, берётся из WH_LOG_LEVEL, иначе info.
|
||||
"""
|
||||
if level is None:
|
||||
level = os.environ.get("WH_LOG_LEVEL", DEFAULT_LEVEL)
|
||||
|
||||
log_level = getattr(logging, level.upper(), logging.INFO)
|
||||
|
||||
root_logger = logging.getLogger()
|
||||
for handler in root_logger.handlers[:]:
|
||||
root_logger.removeHandler(handler)
|
||||
|
||||
logging.basicConfig(
|
||||
level=log_level,
|
||||
format="[%(asctime)s] [%(levelname)s] [%(name)s] %(message)s",
|
||||
datefmt="%H:%M:%S",
|
||||
handlers=[logging.StreamHandler(sys.stdout)],
|
||||
)
|
||||
|
||||
|
||||
def get_logger(name: str) -> logging.Logger:
|
||||
"""Возвращает логгер для модуля."""
|
||||
return logging.getLogger(name)
|
||||
@@ -1,13 +1,14 @@
|
||||
"""
|
||||
Парсеры для winehelper.
|
||||
"""
|
||||
from winehelperqt.parsers.sha256_parser import Sha256Parser
|
||||
from winehelperqt.parsers.winetricks_parser import WinetricksOutputParser, WinetricksItem
|
||||
|
||||
from winehelperqt.parsers.script_parser import ScriptParser
|
||||
from winehelperqt.parsers.sha256_parser import Sha256Parser
|
||||
from winehelperqt.parsers.winetricks_parser import WinetricksItem, WinetricksOutputParser
|
||||
|
||||
__all__ = [
|
||||
'Sha256Parser',
|
||||
'WinetricksOutputParser',
|
||||
'WinetricksItem',
|
||||
'ScriptParser',
|
||||
"Sha256Parser",
|
||||
"WinetricksOutputParser",
|
||||
"WinetricksItem",
|
||||
"ScriptParser",
|
||||
]
|
||||
@@ -1,10 +1,14 @@
|
||||
"""
|
||||
Парсер для извлечения информации из скриптов установки.
|
||||
"""
|
||||
|
||||
import shlex
|
||||
|
||||
from winehelperqt.logger import get_logger
|
||||
from winehelperqt.utils.export_utils import ExportUtils
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class ScriptParser:
|
||||
"""Утилитарный класс для парсинга информации из скриптов установки."""
|
||||
@@ -20,78 +24,89 @@ class ScriptParser:
|
||||
Returns:
|
||||
Список имен иконок
|
||||
"""
|
||||
logger.debug("Извлекаем иконки из скрипта: %s", script_path)
|
||||
try:
|
||||
with open(script_path, 'r', encoding='utf-8') as f:
|
||||
with open(script_path, "r", encoding="utf-8") as f:
|
||||
lines = f.readlines()
|
||||
|
||||
# Приоритет у ICONS_BUTTON_GUI
|
||||
for line in lines:
|
||||
if line.strip().startswith('export ICONS_BUTTON_GUI='):
|
||||
icon_names_str = line.split('=', 1)[1].strip().strip('"\'')
|
||||
if line.strip().startswith("export ICONS_BUTTON_GUI="):
|
||||
icon_names_str = line.split("=", 1)[1].strip().strip("\"'")
|
||||
if icon_names_str:
|
||||
return icon_names_str.split()
|
||||
icons = icon_names_str.split()
|
||||
logger.debug("Найдены иконки %s в %s", icons, script_path)
|
||||
return icons
|
||||
|
||||
for line in lines:
|
||||
if line.strip().startswith('export PROG_ICON='):
|
||||
icon_names_str = line.split('=', 1)[1].strip().strip('"\'')
|
||||
if line.strip().startswith("export PROG_ICON="):
|
||||
icon_names_str = line.split("=", 1)[1].strip().strip("\"'")
|
||||
if icon_names_str:
|
||||
return icon_names_str.split()
|
||||
icons = icon_names_str.split()
|
||||
logger.debug("Найдены иконки %s в %s", icons, script_path)
|
||||
return icons
|
||||
|
||||
# Поиск в create_desktop
|
||||
icon_names = []
|
||||
for line in lines:
|
||||
line = line.strip()
|
||||
if not line or line.startswith('#'):
|
||||
if not line or line.startswith("#"):
|
||||
continue
|
||||
|
||||
if 'create_desktop' in line:
|
||||
if "create_desktop" in line:
|
||||
try:
|
||||
parts = shlex.split(line)
|
||||
for i, part in enumerate(parts):
|
||||
if part == 'create_desktop':
|
||||
if part == "create_desktop":
|
||||
if len(parts) > i + 3:
|
||||
icon_name = parts[i + 3]
|
||||
if icon_name and icon_name.lower() not in ('auto', 'nocopy'):
|
||||
if icon_name and icon_name.lower() not in ("auto", "nocopy"):
|
||||
icon_names.append(icon_name)
|
||||
except (ValueError, IndexError):
|
||||
except (ValueError, IndexError) as e:
|
||||
logger.debug("Пропущена строка create_desktop в %s: %s", script_path, e)
|
||||
continue
|
||||
logger.debug("Иконки из create_desktop в %s: %s", script_path, icon_names)
|
||||
return icon_names
|
||||
except Exception as e:
|
||||
print(f"Ошибка чтения файла для извлечения иконки: {str(e)}")
|
||||
logger.warning("Не удалось извлечь иконки из %s: %s", script_path, e)
|
||||
return []
|
||||
|
||||
@staticmethod
|
||||
def _extract_variable(script_path, var_name):
|
||||
"""Извлекает значение переменной из скрипта установки."""
|
||||
logger.debug("Извлекаем переменную %s из скрипта: %s", var_name, script_path)
|
||||
try:
|
||||
with open(script_path, 'r', encoding='utf-8') as f:
|
||||
with open(script_path, "r", encoding="utf-8") as f:
|
||||
for line in f:
|
||||
parsed_name, parsed_value = ExportUtils.parse_line(line)
|
||||
if parsed_name == var_name:
|
||||
logger.debug("Найдена %s=%s в %s", var_name, parsed_value, script_path)
|
||||
return parsed_value if parsed_value else None
|
||||
logger.debug("Переменная %s не найдена в %s", var_name, script_path)
|
||||
return None
|
||||
except Exception as e:
|
||||
print(f"Ошибка чтения файла для извлечения {var_name}: {e}")
|
||||
logger.warning("Не удалось извлечь переменную %s из %s: %s", var_name, script_path, e)
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def extract_prog_name_from_script(script_path):
|
||||
"""Извлекает имя программы из строки PROG_NAME= в скрипте."""
|
||||
return ScriptParser._extract_variable(script_path, 'PROG_NAME')
|
||||
return ScriptParser._extract_variable(script_path, "PROG_NAME")
|
||||
|
||||
@staticmethod
|
||||
def extract_prog_url_from_script(script_path):
|
||||
"""Извлекает URL из строки PROG_URL= в скрипте."""
|
||||
return ScriptParser._extract_variable(script_path, 'PROG_URL')
|
||||
return ScriptParser._extract_variable(script_path, "PROG_URL")
|
||||
|
||||
@staticmethod
|
||||
def extract_info_ru(script_path):
|
||||
"""Извлекает информацию из строки # info_ru: в скрипте"""
|
||||
try:
|
||||
with open(script_path, 'r', encoding='utf-8') as f:
|
||||
with open(script_path, "r", encoding="utf-8") as f:
|
||||
for line in f:
|
||||
if line.startswith('# info_ru:'):
|
||||
return line.replace('# info_ru:', '').strip()
|
||||
if line.startswith("# info_ru:"):
|
||||
return line.replace("# info_ru:", "").strip()
|
||||
return "Описание отсутствует"
|
||||
except Exception as e:
|
||||
logger.warning("Не удалось извлечь описание из %s: %s", script_path, e)
|
||||
return f"Ошибка чтения файла: {str(e)}"
|
||||
@@ -2,21 +2,25 @@
|
||||
Парсер для файла sha256sum.list.
|
||||
Извлекает версии Wine и компонентов из файла хешей.
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
|
||||
from winehelperqt.logger import get_logger
|
||||
from winehelperqt.utils.version_utils import sort_versions
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class Sha256Parser:
|
||||
"""Парсер файла sha256sum.list для извлечения версий пакетов."""
|
||||
|
||||
WINE_ALLOWED_GROUPS = {"WINE WOW64", "WINE AMD64", "WINE I586"}
|
||||
GROUP_HEADER_PATTERN = re.compile(r'^#+\s*(.*?)\s*#*$')
|
||||
HASH_PATTERN = re.compile(r'^[a-f0-9]{64}')
|
||||
PREFIX_SECTION_START = re.compile(r'^#####\s*PREFIX\s*#####$')
|
||||
SECTION_END_PATTERN = re.compile(r'^#####')
|
||||
ARCHIVE_EXTENSION = '.tar.xz'
|
||||
GROUP_HEADER_PATTERN = re.compile(r"^#+\s*(.*?)\s*#*$")
|
||||
HASH_PATTERN = re.compile(r"^[a-f0-9]{64}")
|
||||
PREFIX_SECTION_START = re.compile(r"^#####\s*PREFIX\s*#####$")
|
||||
SECTION_END_PATTERN = re.compile(r"^#####")
|
||||
ARCHIVE_EXTENSION = ".tar.xz"
|
||||
|
||||
@classmethod
|
||||
def parse_wine_versions(cls, sha256_path):
|
||||
@@ -38,7 +42,7 @@ class Sha256Parser:
|
||||
current_group = None
|
||||
|
||||
try:
|
||||
with open(sha256_path, 'r', encoding='utf-8') as f:
|
||||
with open(sha256_path, "r", encoding="utf-8") as f:
|
||||
for line in f:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
@@ -60,12 +64,14 @@ class Sha256Parser:
|
||||
if len(parts) == 2:
|
||||
filename = parts[1]
|
||||
if filename.endswith(cls.ARCHIVE_EXTENSION):
|
||||
version_name = filename[:-len(cls.ARCHIVE_EXTENSION)]
|
||||
version_name = filename[: -len(cls.ARCHIVE_EXTENSION)]
|
||||
versions_data[current_group].append(version_name)
|
||||
|
||||
except IOError:
|
||||
except IOError as e:
|
||||
logger.warning("Не удалось прочитать файл версий %s: %s", sha256_path, e)
|
||||
return {}
|
||||
|
||||
logger.debug("Версии Wine из %s: %s", sha256_path, versions_data)
|
||||
return versions_data
|
||||
|
||||
@classmethod
|
||||
@@ -88,7 +94,7 @@ class Sha256Parser:
|
||||
current_group = None
|
||||
|
||||
try:
|
||||
with open(sha256_path, 'r', encoding='utf-8') as f:
|
||||
with open(sha256_path, "r", encoding="utf-8") as f:
|
||||
for line in f:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
@@ -104,12 +110,14 @@ class Sha256Parser:
|
||||
if len(parts) == 2:
|
||||
filename = parts[1]
|
||||
if filename.endswith(cls.ARCHIVE_EXTENSION):
|
||||
version_name = filename[:-len(cls.ARCHIVE_EXTENSION)]
|
||||
version_name = filename[: -len(cls.ARCHIVE_EXTENSION)]
|
||||
versions_data.append(version_name)
|
||||
|
||||
except IOError:
|
||||
except IOError as e:
|
||||
logger.warning("Не удалось прочитать файл версий %s: %s", sha256_path, e)
|
||||
return []
|
||||
|
||||
logger.debug("Версии компонента %s из %s: %s", component_group, sha256_path, versions_data)
|
||||
return versions_data
|
||||
|
||||
@classmethod
|
||||
@@ -124,7 +132,7 @@ class Sha256Parser:
|
||||
Словарь {архитектура: [(имя_префикса, описание)]}, например:
|
||||
{'win32': [('prefix_x86_v1', 'Описание')], 'win64': [...]}
|
||||
"""
|
||||
prepared_prefixes = {'win32': [], 'win64': []}
|
||||
prepared_prefixes = {"win32": [], "win64": []}
|
||||
|
||||
if not os.path.exists(sha256_path):
|
||||
return prepared_prefixes
|
||||
@@ -134,20 +142,16 @@ class Sha256Parser:
|
||||
current_prefix_name = None
|
||||
|
||||
try:
|
||||
with open(sha256_path, 'r', encoding='utf-8') as f:
|
||||
with open(sha256_path, "r", encoding="utf-8") as f:
|
||||
for line in f:
|
||||
line = line.strip()
|
||||
|
||||
if cls.PREFIX_SECTION_START.match(line):
|
||||
in_prefix_section = True
|
||||
continue
|
||||
elif cls.SECTION_END_PATTERN.match(line):
|
||||
if cls.SECTION_END_PATTERN.match(line):
|
||||
if current_prefix_name and current_description:
|
||||
cls._add_prefix_to_list(
|
||||
prepared_prefixes,
|
||||
current_prefix_name,
|
||||
current_description
|
||||
)
|
||||
cls._add_prefix_to_list(prepared_prefixes, current_prefix_name, current_description)
|
||||
in_prefix_section = False
|
||||
current_description = ""
|
||||
current_prefix_name = None
|
||||
@@ -158,21 +162,17 @@ class Sha256Parser:
|
||||
|
||||
if cls.HASH_PATTERN.match(line):
|
||||
if current_prefix_name and current_description:
|
||||
cls._add_prefix_to_list(
|
||||
prepared_prefixes,
|
||||
current_prefix_name,
|
||||
current_description
|
||||
)
|
||||
cls._add_prefix_to_list(prepared_prefixes, current_prefix_name, current_description)
|
||||
|
||||
current_description = ""
|
||||
|
||||
parts = line.split(maxsplit=1)
|
||||
if len(parts) == 2:
|
||||
current_prefix_name = parts[1].replace('.tar.xz', '')
|
||||
current_prefix_name = parts[1].replace(".tar.xz", "")
|
||||
else:
|
||||
current_prefix_name = None
|
||||
|
||||
elif line.startswith('# '):
|
||||
elif line.startswith("# "):
|
||||
comment_line = line[2:].strip()
|
||||
if current_description:
|
||||
current_description += "\n" + comment_line
|
||||
@@ -180,17 +180,15 @@ class Sha256Parser:
|
||||
current_description = comment_line
|
||||
|
||||
if current_prefix_name and current_description:
|
||||
cls._add_prefix_to_list(
|
||||
prepared_prefixes,
|
||||
current_prefix_name,
|
||||
current_description
|
||||
)
|
||||
cls._add_prefix_to_list(prepared_prefixes, current_prefix_name, current_description)
|
||||
|
||||
except IOError:
|
||||
return {'win32': [], 'win64': []}
|
||||
except IOError as e:
|
||||
logger.warning("Не удалось прочитать префиксы из %s: %s", sha256_path, e)
|
||||
return {"win32": [], "win64": []}
|
||||
|
||||
cls._add_clean_prefix_option(prepared_prefixes)
|
||||
|
||||
logger.debug("Подготовленные префиксы из %s: %s", sha256_path, prepared_prefixes)
|
||||
return prepared_prefixes
|
||||
|
||||
@classmethod
|
||||
@@ -198,21 +196,19 @@ class Sha256Parser:
|
||||
"""Добавляет префикс в список с определением архитектуры."""
|
||||
arch = None
|
||||
if "_x86_" in prefix_name or "_i586_" in prefix_name:
|
||||
arch = 'win32'
|
||||
arch = "win32"
|
||||
elif "_x64_" in prefix_name or "_amd64_" in prefix_name:
|
||||
arch = 'win64'
|
||||
arch = "win64"
|
||||
|
||||
if arch:
|
||||
prepared_prefixes[arch].append(
|
||||
(prefix_name, description.strip().replace('\\n', '\n'))
|
||||
)
|
||||
prepared_prefixes[arch].append((prefix_name, description.strip().replace("\\n", "\n")))
|
||||
|
||||
@classmethod
|
||||
def _add_clean_prefix_option(cls, prepared_prefixes):
|
||||
"""Добавляет опцию 'Чистый префикс' для обеих архитектур."""
|
||||
clean_prefix_description = 'Создать чистый префикс без дополнительных библиотек'
|
||||
prepared_prefixes['win32'].insert(0, ('none', clean_prefix_description))
|
||||
prepared_prefixes['win64'].insert(0, ('none', clean_prefix_description))
|
||||
clean_prefix_description = "Создать чистый префикс без дополнительных библиотек"
|
||||
prepared_prefixes["win32"].insert(0, ("none", clean_prefix_description))
|
||||
prepared_prefixes["win64"].insert(0, ("none", clean_prefix_description))
|
||||
|
||||
@classmethod
|
||||
def get_installed_versions(cls, dist_path):
|
||||
@@ -229,10 +225,10 @@ class Sha256Parser:
|
||||
return []
|
||||
|
||||
try:
|
||||
versions = [
|
||||
name for name in os.listdir(dist_path)
|
||||
if os.path.isdir(os.path.join(dist_path, name))
|
||||
]
|
||||
return sort_versions(versions, reverse=True)
|
||||
except OSError:
|
||||
versions = [name for name in os.listdir(dist_path) if os.path.isdir(os.path.join(dist_path, name))]
|
||||
sorted_versions = sort_versions(versions, reverse=True)
|
||||
logger.debug("Установленные версии в %s: %s", dist_path, sorted_versions)
|
||||
return sorted_versions
|
||||
except OSError as e:
|
||||
logger.warning("Не удалось прочитать директорию dist %s: %s", dist_path, e)
|
||||
return []
|
||||
@@ -2,9 +2,14 @@
|
||||
Парсер для вывода утилиты Winetricks.
|
||||
Извлекает списки компонентов и информацию об установленных пакетах.
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
|
||||
from winehelperqt.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class WinetricksItem:
|
||||
"""Элемент списка компонентов Winetricks."""
|
||||
@@ -21,23 +26,16 @@ class WinetricksOutputParser:
|
||||
|
||||
LINE_PATTERN = re.compile(r"^\s*(?:\[(.)]\s+)?([^\s]+)\s*(.*)")
|
||||
|
||||
DLLS_BLACKLIST_PATTERN = re.compile(
|
||||
r'^(dont_use|dxvk|vkd3d|galliumnine|faudio|foundation)',
|
||||
re.IGNORECASE
|
||||
)
|
||||
FONTS_BLACKLIST_PATTERN = re.compile(
|
||||
r'^(dont_use)',
|
||||
re.IGNORECASE
|
||||
)
|
||||
DLLS_BLACKLIST_PATTERN = re.compile(r"^(dont_use|dxvk|vkd3d|galliumnine|faudio|foundation)", re.IGNORECASE)
|
||||
FONTS_BLACKLIST_PATTERN = re.compile(r"^(dont_use)", re.IGNORECASE)
|
||||
SETTINGS_BLACKLIST_PATTERN = re.compile(
|
||||
r'^(vista|alldlls|autostart_|bad|good|win|videomemory|vd=|isolate_home)',
|
||||
re.IGNORECASE
|
||||
r"^(vista|alldlls|autostart_|bad|good|win|videomemory|vd=|isolate_home)", re.IGNORECASE
|
||||
)
|
||||
|
||||
DOWNLOAD_AVAILABLE_PATTERN = re.compile(r'\[\s*доступно для скачивания[^]]*\]')
|
||||
IN_CACHE_PATTERN = re.compile(r'\[\s*в кэше\s*\]')
|
||||
DOWNLOAD_AVAILABLE_PATTERN = re.compile(r"\[\s*доступно для скачивания[^]]*\]")
|
||||
IN_CACHE_PATTERN = re.compile(r"\[\s*в кэше\s*\]")
|
||||
|
||||
SERVICE_WORDS = {'executing', 'using', 'warning:', '#', 'export'}
|
||||
SERVICE_WORDS = {"executing", "using", "warning:", "#", "export"}
|
||||
|
||||
@classmethod
|
||||
def parse_installed_verbs(cls, log_path):
|
||||
@@ -56,15 +54,15 @@ class WinetricksOutputParser:
|
||||
return installed_verbs
|
||||
|
||||
try:
|
||||
with open(log_path, 'r', encoding='utf-8') as f:
|
||||
with open(log_path, "r", encoding="utf-8") as f:
|
||||
for line in f:
|
||||
# Учитываем экранированный #: разделяем только по неэкранированному #
|
||||
parts = re.split(r'(?<!\\)#', line)
|
||||
verb = parts[0].replace('\\#', '#').strip()
|
||||
parts = re.split(r"(?<!\\)#", line)
|
||||
verb = parts[0].replace("\\#", "#").strip()
|
||||
if verb:
|
||||
installed_verbs.add(verb)
|
||||
except Exception as e:
|
||||
print(f"Предупреждение: не удалось прочитать {log_path}: {e}")
|
||||
logger.warning("Не удалось прочитать %s: %s", log_path, e)
|
||||
|
||||
return installed_verbs
|
||||
|
||||
@@ -98,14 +96,11 @@ class WinetricksOutputParser:
|
||||
description = cls._clean_description(description)
|
||||
|
||||
is_checked = name in installed_verbs
|
||||
item_text = f"{name.ljust(27)}{description.strip()}"
|
||||
item_text = f"{name.ljust(24)}{description.strip()}"
|
||||
|
||||
items.append(WinetricksItem(
|
||||
name=name,
|
||||
description=description.strip(),
|
||||
is_installed=is_checked,
|
||||
item_text=item_text
|
||||
))
|
||||
items.append(
|
||||
WinetricksItem(name=name, description=description.strip(), is_installed=is_checked, item_text=item_text)
|
||||
)
|
||||
|
||||
return items, found_items
|
||||
|
||||
@@ -113,9 +108,9 @@ class WinetricksOutputParser:
|
||||
def _get_blacklist_pattern(cls, category):
|
||||
"""Возвращает шаблон blacklist для указанной категории."""
|
||||
patterns = {
|
||||
'dlls': cls.DLLS_BLACKLIST_PATTERN,
|
||||
'fonts': cls.FONTS_BLACKLIST_PATTERN,
|
||||
'settings': cls.SETTINGS_BLACKLIST_PATTERN
|
||||
"dlls": cls.DLLS_BLACKLIST_PATTERN,
|
||||
"fonts": cls.FONTS_BLACKLIST_PATTERN,
|
||||
"settings": cls.SETTINGS_BLACKLIST_PATTERN,
|
||||
}
|
||||
return patterns.get(category)
|
||||
|
||||
@@ -131,10 +126,10 @@ class WinetricksOutputParser:
|
||||
Returns:
|
||||
True если компонент допустим, False иначе
|
||||
"""
|
||||
if '/' in name or '\\' in name:
|
||||
if "/" in name or "\\" in name:
|
||||
return False
|
||||
|
||||
if name.lower() in cls.SERVICE_WORDS or name.endswith(':'):
|
||||
if name.lower() in cls.SERVICE_WORDS or name.endswith(":"):
|
||||
return False
|
||||
|
||||
blacklist_pattern = cls._get_blacklist_pattern(category)
|
||||
@@ -154,8 +149,8 @@ class WinetricksOutputParser:
|
||||
Returns:
|
||||
Очищенное описание
|
||||
"""
|
||||
description = cls.DOWNLOAD_AVAILABLE_PATTERN.sub('', description)
|
||||
description = cls.IN_CACHE_PATTERN.sub('', description)
|
||||
description = cls.DOWNLOAD_AVAILABLE_PATTERN.sub("", description)
|
||||
description = cls.IN_CACHE_PATTERN.sub("", description)
|
||||
return description.strip()
|
||||
|
||||
@classmethod
|
||||
@@ -171,8 +166,8 @@ class WinetricksOutputParser:
|
||||
Строковое представление паттерна или None
|
||||
"""
|
||||
patterns = {
|
||||
'dlls': cls.DLLS_BLACKLIST_PATTERN.pattern,
|
||||
'fonts': cls.FONTS_BLACKLIST_PATTERN.pattern,
|
||||
'settings': cls.SETTINGS_BLACKLIST_PATTERN.pattern
|
||||
"dlls": cls.DLLS_BLACKLIST_PATTERN.pattern,
|
||||
"fonts": cls.FONTS_BLACKLIST_PATTERN.pattern,
|
||||
"settings": cls.SETTINGS_BLACKLIST_PATTERN.pattern,
|
||||
}
|
||||
return patterns.get(category)
|
||||
@@ -1,25 +1,21 @@
|
||||
"""
|
||||
Сервисы для winehelper GUI.
|
||||
"""
|
||||
from winehelperqt.services.winetricks_service import WinetricksCacheService, WinetricksLogReader
|
||||
from winehelperqt.services.prefix_manager import PrefixManager
|
||||
from winehelperqt.services.process_handler import ProcessHandler, CommandRunner
|
||||
from winehelperqt.services.desktop_file_manager import DesktopFileManager
|
||||
from winehelperqt.services.script_manager import ScriptManager, ScriptInfo
|
||||
from winehelperqt.services.installation_manager import InstallationManager
|
||||
|
||||
from winehelperqt.services.app_launcher import AppLauncher
|
||||
from winehelperqt.services.desktop_file_manager import DesktopFileManager
|
||||
from winehelperqt.services.prefix_manager import PrefixManager
|
||||
from winehelperqt.services.script_manager import ScriptInfo, ScriptManager
|
||||
from winehelperqt.services.settings_manager import SettingsManager
|
||||
from winehelperqt.services.winetricks_service import WinetricksCacheService, WinetricksLogReader
|
||||
|
||||
__all__ = [
|
||||
'WinetricksCacheService',
|
||||
'WinetricksLogReader',
|
||||
'PrefixManager',
|
||||
'ProcessHandler',
|
||||
'CommandRunner',
|
||||
'DesktopFileManager',
|
||||
'ScriptManager',
|
||||
'ScriptInfo',
|
||||
'InstallationManager',
|
||||
'AppLauncher',
|
||||
'SettingsManager',
|
||||
"WinetricksCacheService",
|
||||
"WinetricksLogReader",
|
||||
"PrefixManager",
|
||||
"DesktopFileManager",
|
||||
"ScriptManager",
|
||||
"ScriptInfo",
|
||||
"AppLauncher",
|
||||
"SettingsManager",
|
||||
]
|
||||
@@ -5,18 +5,21 @@
|
||||
- Запуск приложений из .desktop файлов
|
||||
- Остановка приложений
|
||||
- Мониторинг запущенных приложений
|
||||
- Создание логов запуска (в обычном и debug режиме)
|
||||
- Запуск в debug-режиме (WINEDEBUG)
|
||||
"""
|
||||
|
||||
import os
|
||||
import shlex
|
||||
from typing import Dict, Optional
|
||||
from datetime import datetime
|
||||
|
||||
from PyQt5.QtCore import QProcess, QProcessEnvironment
|
||||
|
||||
from winehelperqt.logger import get_logger
|
||||
from winehelperqt.utils.desktop_entry import DesktopEntry
|
||||
from winehelperqt.utils.process_utils import ProcessUtils
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class AppLauncher:
|
||||
"""Сервис для запуска и управления приложениями Wine."""
|
||||
@@ -55,30 +58,7 @@ class AppLauncher:
|
||||
raise ValueError(f"Не удалось получить команду запуска из: {desktop_path}")
|
||||
|
||||
args = shlex.split(exec_command)
|
||||
return self._start_process(
|
||||
desktop_path, args,
|
||||
debug=debug,
|
||||
connect_finished=True
|
||||
)
|
||||
|
||||
def launch_app_with_log(self, desktop_path: str, debug: bool = False) -> QProcess:
|
||||
"""
|
||||
Запускает приложение с созданием лога.
|
||||
|
||||
Args:
|
||||
desktop_path: Путь к .desktop файлу
|
||||
debug: Создать debug лог
|
||||
|
||||
Returns:
|
||||
QProcess запущенного приложения
|
||||
"""
|
||||
process = self.launch_app(desktop_path, debug)
|
||||
|
||||
# Создаём лог если в debug режиме
|
||||
if debug:
|
||||
self._create_debug_log(desktop_path, process)
|
||||
|
||||
return process
|
||||
return self._start_process(desktop_path, args, debug=debug, connect_finished=True)
|
||||
|
||||
def _validate_desktop_origin(self, desktop_path: str) -> None:
|
||||
"""
|
||||
@@ -99,16 +79,13 @@ class AppLauncher:
|
||||
try:
|
||||
if os.path.commonpath([desktop_dir, allowed_dir]) == allowed_dir:
|
||||
return
|
||||
except ValueError:
|
||||
except ValueError as e:
|
||||
logger.debug("Путь %s не относится к разрешённому %s: %s", desktop_dir, allowed_dir, e)
|
||||
continue
|
||||
raise ValueError(
|
||||
f"Desktop файл из недоверенного расположения: {desktop_path}"
|
||||
)
|
||||
raise ValueError(f"Desktop файл из недоверенного расположения: {desktop_path}")
|
||||
|
||||
def launch_app_by_command(
|
||||
self, desktop_path: str, command: list,
|
||||
env_vars: Optional[Dict[str, str]] = None,
|
||||
debug: bool = False
|
||||
self, desktop_path: str, command: list, env_vars: Optional[Dict[str, str]] = None, debug: bool = False
|
||||
) -> QProcess:
|
||||
"""
|
||||
Запускает приложение по команде (для сложных случаев с env).
|
||||
@@ -128,12 +105,7 @@ class AppLauncher:
|
||||
if not command:
|
||||
raise ValueError("Команда запуска не может быть пустой")
|
||||
|
||||
return self._start_process(
|
||||
desktop_path, command,
|
||||
env_vars=env_vars,
|
||||
debug=debug,
|
||||
connect_finished=False
|
||||
)
|
||||
return self._start_process(desktop_path, command, env_vars=env_vars, debug=debug, connect_finished=False)
|
||||
|
||||
def _start_process(
|
||||
self,
|
||||
@@ -141,7 +113,7 @@ class AppLauncher:
|
||||
command: list,
|
||||
env_vars: Optional[Dict[str, str]] = None,
|
||||
debug: bool = False,
|
||||
connect_finished: bool = True
|
||||
connect_finished: bool = True,
|
||||
) -> QProcess:
|
||||
"""
|
||||
Запускает QProcess для приложения и регистрирует его.
|
||||
@@ -168,16 +140,26 @@ class AppLauncher:
|
||||
process.setProcessEnvironment(env)
|
||||
|
||||
executable = command[0]
|
||||
logged_env = {key: env_vars[key] for key in (env_vars or {})}
|
||||
if debug:
|
||||
logged_env["WINEDEBUG"] = "+loaddll,+seh"
|
||||
logger.debug(
|
||||
"Запуск процесса: %s %s (env=%s)",
|
||||
shlex.quote(executable),
|
||||
" ".join(shlex.quote(a) for a in command[1:]),
|
||||
logged_env,
|
||||
)
|
||||
process.start(executable, command[1:])
|
||||
|
||||
if not process.waitForStarted():
|
||||
if not process.waitForStarted(5000):
|
||||
logger.error("Не удалось дождаться старта приложения: %s", desktop_path)
|
||||
raise RuntimeError(f"Не удалось запустить приложение: {desktop_path}")
|
||||
|
||||
self._active_processes[desktop_path] = process
|
||||
|
||||
if connect_finished:
|
||||
process.finished.connect(
|
||||
lambda: self._on_app_finished(desktop_path, process)
|
||||
lambda exit_code, exit_status: self._on_app_finished(desktop_path, process, exit_code)
|
||||
)
|
||||
|
||||
return process
|
||||
@@ -225,10 +207,7 @@ class AppLauncher:
|
||||
Returns:
|
||||
Словарь {desktop_path: QProcess}
|
||||
"""
|
||||
return {
|
||||
path: proc for path, proc in self._active_processes.items()
|
||||
if proc.state() == QProcess.Running
|
||||
}
|
||||
return {path: proc for path, proc in self._active_processes.items() if proc.state() == QProcess.Running}
|
||||
|
||||
def get_process_for_app(self, desktop_path: str) -> Optional[QProcess]:
|
||||
"""
|
||||
@@ -242,9 +221,7 @@ class AppLauncher:
|
||||
"""
|
||||
return self._active_processes.get(desktop_path)
|
||||
|
||||
def connect_output_callback(
|
||||
self, desktop_path: str, callback
|
||||
) -> None:
|
||||
def connect_output_callback(self, desktop_path: str, callback) -> None:
|
||||
"""
|
||||
Подключает callback для обработки вывода приложения.
|
||||
|
||||
@@ -254,8 +231,9 @@ class AppLauncher:
|
||||
"""
|
||||
process = self._active_processes.get(desktop_path)
|
||||
if process:
|
||||
|
||||
def read_output():
|
||||
output = process.readAllStandardOutput().data().decode('utf-8', 'ignore')
|
||||
output = process.readAllStandardOutput().data().decode("utf-8", "ignore")
|
||||
if output:
|
||||
callback(output)
|
||||
|
||||
@@ -266,9 +244,11 @@ class AppLauncher:
|
||||
for desktop_path in list(self._active_processes.keys()):
|
||||
self.stop_app(desktop_path)
|
||||
|
||||
def _on_app_finished(self, desktop_path: str, process: QProcess) -> None:
|
||||
def _on_app_finished(self, desktop_path: str, process: QProcess, exit_code: int = 0) -> None:
|
||||
"""Обработчик завершения приложения."""
|
||||
self._active_processes.pop(desktop_path, None)
|
||||
if exit_code != 0:
|
||||
logger.warning("Приложение %s завершилось с кодом %d", desktop_path, exit_code)
|
||||
|
||||
def _get_exec_from_desktop(self, desktop_path: str) -> Optional[str]:
|
||||
"""
|
||||
@@ -283,69 +263,15 @@ class AppLauncher:
|
||||
try:
|
||||
entry = DesktopEntry(desktop_path)
|
||||
entry.load()
|
||||
exec_cmd = entry.get('Desktop Entry', 'Exec')
|
||||
exec_cmd = entry.get("Desktop Entry", "Exec")
|
||||
if not exec_cmd:
|
||||
return None
|
||||
|
||||
# Убираем %F, %f, %U, %u (параметры desktop-файла)
|
||||
exec_cmd = exec_cmd.replace('%F', '').replace('%f', '')
|
||||
exec_cmd = exec_cmd.replace('%U', '').replace('%u', '')
|
||||
exec_cmd = exec_cmd.replace("%F", "").replace("%f", "")
|
||||
exec_cmd = exec_cmd.replace("%U", "").replace("%u", "")
|
||||
return exec_cmd.strip()
|
||||
except (IOError, OSError) as e:
|
||||
print(f"Ошибка чтения {desktop_path}: {e}")
|
||||
logger.error("Ошибка чтения %s: %s", desktop_path, e)
|
||||
|
||||
return None
|
||||
|
||||
def _create_debug_log(self, desktop_path: str, process: QProcess) -> Optional[str]:
|
||||
"""
|
||||
Создаёт debug лог для приложения, стримя вывод процесса.
|
||||
|
||||
Args:
|
||||
desktop_path: Путь к .desktop файлу
|
||||
process: QProcess приложения
|
||||
|
||||
Returns:
|
||||
Путь к файлу лога или None
|
||||
"""
|
||||
try:
|
||||
# Создаём директорию для логов
|
||||
log_dir = os.path.join(self.user_work_path, "logs")
|
||||
os.makedirs(log_dir, exist_ok=True)
|
||||
|
||||
# Формируем имя файла
|
||||
app_name = os.path.splitext(os.path.basename(desktop_path))[0]
|
||||
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
log_filename = f"{app_name}_{timestamp}.log"
|
||||
log_path = os.path.join(log_dir, log_filename)
|
||||
|
||||
log_file = open(log_path, 'w', encoding='utf-8')
|
||||
log_file.write(f"Debug лог для: {desktop_path}\n")
|
||||
log_file.write(f"Время запуска: {timestamp}\n")
|
||||
log_file.write("=" * 80 + "\n\n")
|
||||
log_file.flush()
|
||||
|
||||
def _write_output():
|
||||
try:
|
||||
output = process.readAllStandardOutput().data().decode('utf-8', 'ignore')
|
||||
if output:
|
||||
log_file.write(output)
|
||||
log_file.flush()
|
||||
except (IOError, OSError, RuntimeError) as e:
|
||||
print(f"Ошибка записи debug лога: {e}")
|
||||
|
||||
def _close_log():
|
||||
try:
|
||||
_write_output()
|
||||
log_file.close()
|
||||
print(f"Debug лог создан: {log_path}")
|
||||
except (IOError, OSError) as e:
|
||||
print(f"Ошибка закрытия debug лога: {e}")
|
||||
|
||||
process.readyReadStandardOutput.connect(_write_output)
|
||||
process.finished.connect(_close_log)
|
||||
|
||||
return log_path
|
||||
|
||||
except (IOError, OSError) as e:
|
||||
print(f"Ошибка создания debug лога: {e}")
|
||||
return None
|
||||
@@ -1,12 +1,16 @@
|
||||
"""
|
||||
Сервис для управления .desktop файлами.
|
||||
"""
|
||||
|
||||
import os
|
||||
import shlex
|
||||
import shutil
|
||||
|
||||
from winehelperqt.logger import get_logger
|
||||
from winehelperqt.utils.desktop_entry import DesktopEntry
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class DesktopFileManager:
|
||||
"""
|
||||
@@ -53,11 +57,12 @@ class DesktopFileManager:
|
||||
return []
|
||||
|
||||
try:
|
||||
return [
|
||||
f.replace('.desktop', '') for f in os.listdir(self.desktop_dir)
|
||||
if f.endswith('.desktop')
|
||||
]
|
||||
except OSError:
|
||||
return sorted(
|
||||
(f.replace(".desktop", "") for f in os.listdir(self.desktop_dir) if f.endswith(".desktop")),
|
||||
key=str.lower,
|
||||
)
|
||||
except OSError as e:
|
||||
logger.warning("Не удалось прочитать директорию .desktop файлов %s: %s", self.desktop_dir, e)
|
||||
return []
|
||||
|
||||
def read_desktop_file(self, app_name):
|
||||
@@ -78,8 +83,11 @@ class DesktopFileManager:
|
||||
try:
|
||||
entry = DesktopEntry(desktop_path)
|
||||
entry.load()
|
||||
return dict(entry.section('Desktop Entry'))
|
||||
except (IOError, OSError):
|
||||
data = dict(entry.section("Desktop Entry"))
|
||||
logger.debug("Прочитан .desktop файл %s", desktop_path)
|
||||
return data
|
||||
except (IOError, OSError) as e:
|
||||
logger.warning("Не удалось прочитать .desktop файл %s: %s", desktop_path, e)
|
||||
return {}
|
||||
|
||||
def get_app_name_from_desktop(self, app_name):
|
||||
@@ -93,7 +101,7 @@ class DesktopFileManager:
|
||||
Отображаемое имя приложения
|
||||
"""
|
||||
data = self.read_desktop_file(app_name)
|
||||
return data.get('Name', app_name)
|
||||
return data.get("Name", app_name)
|
||||
|
||||
def get_app_icon_from_desktop(self, app_name):
|
||||
"""
|
||||
@@ -106,7 +114,7 @@ class DesktopFileManager:
|
||||
Путь к иконке или None
|
||||
"""
|
||||
data = self.read_desktop_file(app_name)
|
||||
return data.get('Icon')
|
||||
return data.get("Icon")
|
||||
|
||||
def delete_desktop_file(self, app_name):
|
||||
"""
|
||||
@@ -125,8 +133,10 @@ class DesktopFileManager:
|
||||
|
||||
try:
|
||||
os.remove(desktop_path)
|
||||
logger.debug("Удалён .desktop файл %s", desktop_path)
|
||||
return True, "Файл удален"
|
||||
except OSError as e:
|
||||
logger.error("Не удалось удалить .desktop файл %s: %s", desktop_path, e)
|
||||
return False, f"Ошибка удаления: {e}"
|
||||
|
||||
def desktop_file_exists(self, app_name):
|
||||
@@ -142,7 +152,7 @@ class DesktopFileManager:
|
||||
return os.path.exists(self.get_desktop_file_path(app_name))
|
||||
|
||||
@staticmethod
|
||||
def _get_exe_path_from_exec(exec_line, base_dir=None):
|
||||
def get_exe_path_from_exec(exec_line, base_dir=None):
|
||||
"""
|
||||
Извлекает путь к .exe файлу из строки Exec.
|
||||
|
||||
@@ -156,16 +166,17 @@ class DesktopFileManager:
|
||||
if not exec_line:
|
||||
return None
|
||||
|
||||
exec_line = exec_line.split('%')[0].strip()
|
||||
exec_line = exec_line.split("%")[0].strip()
|
||||
|
||||
try:
|
||||
parts = shlex.split(exec_line)
|
||||
except ValueError:
|
||||
except ValueError as e:
|
||||
logger.debug("Не удалось распарсить строку Exec (%s): %s", exec_line, e)
|
||||
parts = exec_line.split()
|
||||
|
||||
for part in parts:
|
||||
part_clean = part.strip('"\'')
|
||||
if not part_clean.lower().endswith('.exe'):
|
||||
part_clean = part.strip("\"'")
|
||||
if not part_clean.lower().endswith(".exe"):
|
||||
continue
|
||||
|
||||
if os.path.exists(part_clean):
|
||||
@@ -189,17 +200,21 @@ class DesktopFileManager:
|
||||
apps = []
|
||||
for app_name in self.list_desktop_files():
|
||||
data = self.read_desktop_file(app_name)
|
||||
exec_line = data.get('Exec', '')
|
||||
exe_path = self._get_exe_path_from_exec(exec_line)
|
||||
exec_line = data.get("Exec", "")
|
||||
exe_path = self.get_exe_path_from_exec(exec_line)
|
||||
if exe_path is None:
|
||||
continue
|
||||
apps.append({
|
||||
'name': app_name,
|
||||
'display_name': data.get('Name', app_name),
|
||||
'icon': data.get('Icon'),
|
||||
'exec': exec_line,
|
||||
'path': self.get_desktop_file_path(app_name)
|
||||
})
|
||||
apps.append(
|
||||
{
|
||||
"name": app_name,
|
||||
"display_name": data.get("Name", app_name),
|
||||
"icon": data.get("Icon"),
|
||||
"exec": exec_line,
|
||||
"path": self.get_desktop_file_path(app_name),
|
||||
}
|
||||
)
|
||||
# Сортируем по отображаемому имени, чтобы порядок кнопок был стабильным
|
||||
apps.sort(key=lambda app: app["display_name"].lower())
|
||||
return apps
|
||||
|
||||
def copy_desktop_file(self, source_path, dest_name):
|
||||
@@ -221,6 +236,8 @@ class DesktopFileManager:
|
||||
|
||||
try:
|
||||
shutil.copy2(source_path, dest_path)
|
||||
logger.debug("Скопирован .desktop файл %s -> %s", source_path, dest_path)
|
||||
return True, "Файл скопирован"
|
||||
except (IOError, OSError) as e:
|
||||
logger.error("Не удалось скопировать .desktop файл %s -> %s: %s", source_path, dest_path, e)
|
||||
return False, f"Ошибка копирования: {e}"
|
||||
@@ -0,0 +1,164 @@
|
||||
"""
|
||||
Сервис для управления глобальными настройками WineHelper GUI.
|
||||
|
||||
Хранит настройки в ~/.config/winehelper/logging.conf
|
||||
(или в директории, заданной XDG_CONFIG_HOME).
|
||||
"""
|
||||
|
||||
import configparser
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from winehelperqt.logger import get_logger
|
||||
from winehelperqt.utils.environment import EnvironmentConfig
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class GlobalSettingsService:
|
||||
"""Сервис для чтения/записи глобальных настроек приложения."""
|
||||
|
||||
CONFIG_DIR = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")) / "winehelper"
|
||||
CONFIG_PATH = CONFIG_DIR / "logging.conf"
|
||||
|
||||
DEFAULT_LOG_LEVEL = "info"
|
||||
VALID_LOG_LEVELS = ("debug", "info", "warning", "error")
|
||||
|
||||
def __init__(self, config_path=None):
|
||||
"""
|
||||
Инициализирует сервис настроек.
|
||||
|
||||
Args:
|
||||
config_path: Путь к файлу конфигурации (опционально).
|
||||
"""
|
||||
self.config_path = Path(config_path) if config_path else self.CONFIG_PATH
|
||||
self._ensure_config_dir()
|
||||
|
||||
def _ensure_config_dir(self):
|
||||
"""Создаёт директорию конфигурации, если она отсутствует."""
|
||||
try:
|
||||
self.config_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
except OSError as e:
|
||||
logger.warning("Не удалось создать директорию конфигурации %s: %s", self.config_path.parent, e)
|
||||
|
||||
def _load_config(self):
|
||||
"""Загружает конфигурацию из файла."""
|
||||
config = configparser.ConfigParser()
|
||||
if self.config_path.exists():
|
||||
try:
|
||||
config.read(self.config_path, encoding="utf-8")
|
||||
except (configparser.Error, OSError) as e:
|
||||
logger.warning("Не удалось прочитать конфиг %s: %s", self.config_path, e)
|
||||
if "gui" not in config:
|
||||
config["gui"] = {}
|
||||
return config
|
||||
|
||||
def _save_config(self, config):
|
||||
"""Сохраняет конфигурацию в файл."""
|
||||
try:
|
||||
self._ensure_config_dir()
|
||||
with open(self.config_path, "w", encoding="utf-8") as f:
|
||||
config.write(f)
|
||||
except OSError as e:
|
||||
logger.error("Не удалось сохранить конфиг %s: %s", self.config_path, e)
|
||||
|
||||
def get_log_level(self):
|
||||
"""
|
||||
Возвращает уровень логирования из конфигурации.
|
||||
|
||||
Returns:
|
||||
str: один из debug/info/warning/error.
|
||||
"""
|
||||
config = self._load_config()
|
||||
level = config["gui"].get("log_level", self.DEFAULT_LOG_LEVEL).lower().strip()
|
||||
if level not in self.VALID_LOG_LEVELS:
|
||||
logger.warning("Неизвестный уровень логирования '%s', используется '%s'", level, self.DEFAULT_LOG_LEVEL)
|
||||
return self.DEFAULT_LOG_LEVEL
|
||||
return level
|
||||
|
||||
def set_log_level(self, level):
|
||||
"""
|
||||
Сохраняет уровень логирования в конфигурации.
|
||||
|
||||
Args:
|
||||
level: debug/info/warning/error.
|
||||
|
||||
Returns:
|
||||
bool: True если значение корректно и сохранено.
|
||||
"""
|
||||
level = level.lower().strip()
|
||||
if level not in self.VALID_LOG_LEVELS:
|
||||
logger.error("Попытка сохранить некорректный уровень логирования: %s", level)
|
||||
return False
|
||||
|
||||
config = self._load_config()
|
||||
config["gui"]["log_level"] = level
|
||||
self._save_config(config)
|
||||
logger.debug("Уровень логирования сохранён: %s", level)
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
def is_work_path_changeable():
|
||||
"""
|
||||
Проверяет, можно ли изменить рабочий каталог.
|
||||
|
||||
Рабочий каталог меняется только для установленного в систему
|
||||
WineHelper (CLI экспортирует WH_CONFIG); в режиме разработки
|
||||
путь фиксирован скриптом winehelper.
|
||||
|
||||
Returns:
|
||||
bool: True если изменение поддерживается.
|
||||
"""
|
||||
return bool(os.environ.get("WH_CONFIG"))
|
||||
|
||||
def get_work_path(self):
|
||||
"""
|
||||
Возвращает текущий рабочий каталог WineHelper.
|
||||
|
||||
Returns:
|
||||
str: путь из окружения (USER_WORK_PATH) или пустая строка.
|
||||
"""
|
||||
return EnvironmentConfig.USER_WORK_PATH or ""
|
||||
|
||||
def set_work_path(self, path):
|
||||
"""
|
||||
Сохраняет новый рабочий каталог в конфиг CLI (~/.config/winehelper/winehelper.conf).
|
||||
|
||||
Аналог команды `winehelper data-path /путь/к/каталогу`.
|
||||
Проверяет доступность каталога на чтение-запись (создаёт его при
|
||||
необходимости), затем записывает export USER_WORK_PATH в WH_CONFIG.
|
||||
Изменение применяется при следующем запуске WineHelper.
|
||||
|
||||
Args:
|
||||
path: новый рабочий каталог.
|
||||
|
||||
Returns:
|
||||
tuple: (bool, str) — успех и сообщение об ошибке (пустая строка при успехе).
|
||||
"""
|
||||
path = str(path).strip()
|
||||
if not path:
|
||||
return False, "Укажите путь к рабочему каталогу."
|
||||
|
||||
wh_config = os.environ.get("WH_CONFIG")
|
||||
if not wh_config:
|
||||
return False, "Изменение рабочего каталога доступно только для установленной версии WineHelper."
|
||||
|
||||
try:
|
||||
os.makedirs(path, exist_ok=True)
|
||||
except OSError as e:
|
||||
logger.error("Не удалось создать рабочий каталог %s: %s", path, e)
|
||||
return False, f"Не удалось создать каталог: {e}"
|
||||
|
||||
if not (os.access(path, os.R_OK) and os.access(path, os.W_OK)):
|
||||
return False, f"Нет доступа на чтение-запись в каталог: {path}"
|
||||
|
||||
try:
|
||||
os.makedirs(os.path.dirname(wh_config), exist_ok=True)
|
||||
with open(wh_config, "w", encoding="utf-8") as f:
|
||||
f.write(f'export USER_WORK_PATH="{path}"\n')
|
||||
except OSError as e:
|
||||
logger.error("Не удалось записать конфиг %s: %s", wh_config, e)
|
||||
return False, f"Не удалось сохранить настройку: {e}"
|
||||
|
||||
logger.info("Рабочий каталог изменён на: %s (применится после перезапуска)", path)
|
||||
return True, ""
|
||||
@@ -1,210 +0,0 @@
|
||||
"""
|
||||
Сервис для управления процессом установки приложений WineHelper.
|
||||
|
||||
Предоставляет функциональность:
|
||||
- Запуск процесса установки
|
||||
- Мониторинг прогресса установки
|
||||
- Обработка логов (stdout/stderr)
|
||||
- Управление процессами (остановка, завершение)
|
||||
- Отмена установки
|
||||
"""
|
||||
import os
|
||||
from typing import Dict, Optional, Callable
|
||||
|
||||
from PyQt5.QtCore import QProcess, QProcessEnvironment
|
||||
|
||||
from winehelperqt.utils.process_utils import ProcessUtils
|
||||
|
||||
|
||||
class InstallationManager:
|
||||
"""Сервис для управления процессом установки приложений."""
|
||||
|
||||
def __init__(self, winehelper_path: str):
|
||||
"""
|
||||
Инициализирует менеджер установки.
|
||||
|
||||
Args:
|
||||
winehelper_path: Путь к скрипту winehelper
|
||||
"""
|
||||
self.winehelper_path = winehelper_path
|
||||
self._active_processes: Dict[str, QProcess] = {}
|
||||
|
||||
def start_install(self, script_path: str,
|
||||
work_path: Optional[str] = None,
|
||||
env_vars: Optional[Dict[str, str]] = None,
|
||||
installer_file: Optional[str] = None) -> QProcess:
|
||||
"""
|
||||
Запускает процесс установки приложения через CLI winehelper.
|
||||
|
||||
Args:
|
||||
script_path: Путь к скрипту установки (install.sh)
|
||||
work_path: Рабочая директория (по умолчанию директория скрипта)
|
||||
env_vars: Дополнительные переменные окружения
|
||||
installer_file: Путь к файлу установщика для ручной установки
|
||||
|
||||
Returns:
|
||||
QProcess запущенного процесса
|
||||
"""
|
||||
if not os.path.exists(script_path):
|
||||
raise FileNotFoundError(f"Скрипт установки не найден: {script_path}")
|
||||
|
||||
process = QProcess()
|
||||
process.setProcessChannelMode(QProcess.MergedChannels)
|
||||
|
||||
# Настраиваем окружение
|
||||
env = QProcessEnvironment.systemEnvironment()
|
||||
|
||||
# Добавляем пользовательские переменные окружения
|
||||
if env_vars:
|
||||
for key, value in env_vars.items():
|
||||
env.insert(key, value)
|
||||
|
||||
process.setProcessEnvironment(env)
|
||||
|
||||
# Устанавливаем рабочую директорию
|
||||
if work_path:
|
||||
process.setWorkingDirectory(work_path)
|
||||
|
||||
# Запускаем установку через CLI winehelper
|
||||
args = ["install", script_path]
|
||||
if installer_file:
|
||||
args.append(installer_file)
|
||||
|
||||
process.start(self.winehelper_path, args)
|
||||
|
||||
if not process.waitForStarted():
|
||||
raise RuntimeError(f"Не удалось запустить процесс установки: {script_path}")
|
||||
|
||||
# Регистрируем процесс и подключаем очистку по завершении
|
||||
self._active_processes[script_path] = process
|
||||
process.finished.connect(self._on_install_finished)
|
||||
|
||||
return process
|
||||
|
||||
def _on_install_finished(self):
|
||||
"""Удаляет завершившиеся процессы из реестра активных установок."""
|
||||
self._cleanup_finished_processes()
|
||||
|
||||
def _cleanup_finished_processes(self) -> None:
|
||||
"""Очищает словарь активных процессов от завершившихся установок."""
|
||||
finished = [
|
||||
path for path, proc in self._active_processes.items()
|
||||
if proc.state() == QProcess.NotRunning
|
||||
]
|
||||
for path in finished:
|
||||
del self._active_processes[path]
|
||||
|
||||
def start_manual_install(self, script_path: str,
|
||||
installer_file: str,
|
||||
env_vars: Optional[Dict[str, str]] = None) -> QProcess:
|
||||
"""
|
||||
Запускает ручную установку с указанием файла установщика.
|
||||
|
||||
Args:
|
||||
script_path: Путь к скрипту установки
|
||||
installer_file: Путь к файлу установщика (.exe или .msi)
|
||||
env_vars: Дополнительные переменные окружения
|
||||
|
||||
Returns:
|
||||
QProcess запущенного процесса
|
||||
"""
|
||||
return self.start_install(
|
||||
script_path, env_vars=env_vars, installer_file=installer_file
|
||||
)
|
||||
|
||||
def stop_install(self, process: QProcess) -> None:
|
||||
"""
|
||||
Останавливает процесс установки.
|
||||
|
||||
Args:
|
||||
process: Процесс установки для остановки
|
||||
"""
|
||||
ProcessUtils.stop_process(process)
|
||||
self._remove_process(process)
|
||||
|
||||
def _remove_process(self, process: QProcess) -> None:
|
||||
"""Удаляет процесс из реестра активных установок."""
|
||||
for path, proc in list(self._active_processes.items()):
|
||||
if proc is process:
|
||||
del self._active_processes[path]
|
||||
break
|
||||
|
||||
def is_running(self, process: QProcess) -> bool:
|
||||
"""
|
||||
Проверяет, запущен ли процесс установки.
|
||||
|
||||
Args:
|
||||
process: Процесс для проверки
|
||||
|
||||
Returns:
|
||||
True если процесс запущен
|
||||
"""
|
||||
return process and process.state() == QProcess.Running
|
||||
|
||||
def connect_output_callback(
|
||||
self, process: QProcess, callback: Callable[[str], None]
|
||||
) -> None:
|
||||
"""
|
||||
Подключает callback для обработки вывода процесса.
|
||||
|
||||
Args:
|
||||
process: Процесс установки
|
||||
callback: Функция для обработки вывода (принимает строку)
|
||||
"""
|
||||
def read_output():
|
||||
output = process.readAllStandardOutput().data().decode('utf-8', 'ignore')
|
||||
if output:
|
||||
callback(output)
|
||||
|
||||
process.readyReadStandardOutput.connect(read_output)
|
||||
|
||||
def connect_error_callback(
|
||||
self, process: QProcess, callback: Callable[[str], None]
|
||||
) -> None:
|
||||
"""
|
||||
Подключает callback для обработки ошибок.
|
||||
|
||||
Args:
|
||||
process: Процесс установки
|
||||
callback: Функция для обработки ошибок (принимает строку)
|
||||
"""
|
||||
def read_error():
|
||||
error = process.readAllStandardError().data().decode('utf-8', 'ignore')
|
||||
if error:
|
||||
callback(error)
|
||||
|
||||
process.readyReadStandardError.connect(read_error)
|
||||
|
||||
def get_install_script_for_folder(self, folder_path: str) -> Optional[str]:
|
||||
"""
|
||||
Возвращает путь к скрипту установки для папки.
|
||||
|
||||
Args:
|
||||
folder_path: Путь к папке скрипта
|
||||
|
||||
Returns:
|
||||
Путь к install.sh или None
|
||||
"""
|
||||
script_path = os.path.join(folder_path, 'install.sh')
|
||||
if os.path.exists(script_path):
|
||||
return script_path
|
||||
return None
|
||||
|
||||
def get_active_installations(self) -> Dict[str, QProcess]:
|
||||
"""
|
||||
Возвращает список активных процессов установки.
|
||||
|
||||
Returns:
|
||||
Словарь {script_path: QProcess}
|
||||
"""
|
||||
return {
|
||||
path: proc for path, proc in self._active_processes.items()
|
||||
if self.is_running(proc)
|
||||
}
|
||||
|
||||
def cancel_all(self) -> None:
|
||||
"""Отменяет все активные процессы установки."""
|
||||
for path, process in list(self._active_processes.items()):
|
||||
if self.is_running(process):
|
||||
self.stop_install(process)
|
||||
self._cleanup_finished_processes()
|
||||
@@ -1,13 +1,17 @@
|
||||
"""
|
||||
Сервис для управления префиксами Wine.
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
from winehelperqt.logger import get_logger
|
||||
from winehelperqt.utils.export_utils import ExportUtils
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class PrefixManager:
|
||||
"""
|
||||
@@ -79,14 +83,20 @@ class PrefixManager:
|
||||
return []
|
||||
|
||||
try:
|
||||
return sorted([
|
||||
name for name in os.listdir(self.prefixes_path)
|
||||
if os.path.isdir(os.path.join(self.prefixes_path, name))
|
||||
])
|
||||
except OSError:
|
||||
prefixes = sorted(
|
||||
[
|
||||
name
|
||||
for name in os.listdir(self.prefixes_path)
|
||||
if os.path.isdir(os.path.join(self.prefixes_path, name))
|
||||
]
|
||||
)
|
||||
logger.debug("Найдено префиксов: %d (%s)", len(prefixes), self.prefixes_path)
|
||||
return prefixes
|
||||
except OSError as e:
|
||||
logger.warning("Не удалось прочитать директорию префиксов %s: %s", self.prefixes_path, e)
|
||||
return []
|
||||
|
||||
def create_prefix(self, prefix_name, wine_arch="win64", base_pfx="none"):
|
||||
def create_prefix(self, prefix_name, wine_arch="win64", base_pfx="none", windows_version="10"):
|
||||
"""
|
||||
Создает новый префикс.
|
||||
|
||||
@@ -94,6 +104,7 @@ class PrefixManager:
|
||||
prefix_name: Имя префикса
|
||||
wine_arch: Архитектура ("win32" или "win64")
|
||||
base_pfx: Базовый шаблон префикса
|
||||
windows_version: Версия Windows, сообщаемая приложениям
|
||||
|
||||
Returns:
|
||||
True если создание успешно, False иначе
|
||||
@@ -101,7 +112,7 @@ class PrefixManager:
|
||||
if not prefix_name:
|
||||
return False, "Имя префикса не может быть пустым"
|
||||
|
||||
if not re.match(r'^[a-zA-Z0-9_-]+$', prefix_name):
|
||||
if not re.match(r"^[a-zA-Z0-9_-]+$", prefix_name):
|
||||
return False, "Имя префикса может содержать только латинские буквы, цифры, дефисы и знаки подчеркивания"
|
||||
|
||||
prefix_path = self.get_prefix_path(prefix_name)
|
||||
@@ -111,6 +122,7 @@ class PrefixManager:
|
||||
# Создаем директорию префикса
|
||||
try:
|
||||
os.makedirs(prefix_path, exist_ok=True)
|
||||
logger.debug("Создан префикс: %s", prefix_path)
|
||||
return True, "Префикс создан"
|
||||
except OSError as e:
|
||||
return False, f"Ошибка создания префикса: {e}"
|
||||
@@ -132,6 +144,7 @@ class PrefixManager:
|
||||
|
||||
try:
|
||||
shutil.rmtree(prefix_path)
|
||||
logger.debug("Удалён префикс: %s", prefix_path)
|
||||
return True, "Префикс удален"
|
||||
except OSError as e:
|
||||
return False, f"Ошибка удаления префикса: {e}"
|
||||
@@ -154,12 +167,13 @@ class PrefixManager:
|
||||
|
||||
all_vars = {}
|
||||
try:
|
||||
with open(config_path, 'r', encoding='utf-8') as f:
|
||||
with open(config_path, "r", encoding="utf-8") as f:
|
||||
for line in f:
|
||||
var_name, var_value = ExportUtils.parse_line(line)
|
||||
if var_name is not None:
|
||||
all_vars[var_name] = var_value
|
||||
except (IOError, OSError):
|
||||
except (IOError, OSError) as e:
|
||||
logger.warning("Не удалось прочитать конфиг префикса %s: %s", config_path, e)
|
||||
return {}
|
||||
|
||||
return all_vars
|
||||
@@ -184,17 +198,18 @@ class PrefixManager:
|
||||
|
||||
existing_lines = []
|
||||
if os.path.exists(config_path):
|
||||
with open(config_path, 'r', encoding='utf-8') as f:
|
||||
with open(config_path, "r", encoding="utf-8") as f:
|
||||
existing_lines = f.readlines()
|
||||
|
||||
new_lines = ExportUtils.update_lines(existing_lines, variables)
|
||||
|
||||
with open(config_path, 'w', encoding='utf-8') as f:
|
||||
with open(config_path, "w", encoding="utf-8") as f:
|
||||
f.writelines(new_lines)
|
||||
|
||||
logger.debug("Записана конфигурация префикса: %s", config_path)
|
||||
return True
|
||||
except (IOError, OSError) as e:
|
||||
print(f"Ошибка записи конфигурации: {e}")
|
||||
logger.error("Ошибка записи конфигурации: %s", e)
|
||||
return False
|
||||
|
||||
def get_prefix_component_version(self, prefix_name, component):
|
||||
@@ -227,9 +242,11 @@ class PrefixManager:
|
||||
return False, f"Директория префикса не найдена: {prefix_path}"
|
||||
|
||||
try:
|
||||
subprocess.Popen(['xdg-open', prefix_path])
|
||||
subprocess.Popen(["xdg-open", prefix_path])
|
||||
logger.debug("Открыта папка префикса: %s", prefix_path)
|
||||
return True, "Папка открыта"
|
||||
except Exception as e:
|
||||
logger.error("Не удалось открыть папку префикса %s: %s", prefix_path, e)
|
||||
return False, f"Ошибка открытия папки: {e}"
|
||||
|
||||
def get_prefixes_with_arch(self):
|
||||
@@ -244,7 +261,8 @@ class PrefixManager:
|
||||
|
||||
for prefix_name in prefixes:
|
||||
config = self.read_prefix_config(prefix_name)
|
||||
arch = config.get('WINEARCH', 'unknown')
|
||||
arch = config.get("WINEARCH", "unknown")
|
||||
result.append((prefix_name, arch))
|
||||
|
||||
logger.debug("Префиксы с архитектурой: %s", result)
|
||||
return result
|
||||
@@ -1,164 +0,0 @@
|
||||
"""
|
||||
Сервис для выполнения и обработки процессов.
|
||||
"""
|
||||
import shlex
|
||||
from PyQt5.QtCore import QProcess, QProcessEnvironment
|
||||
|
||||
from winehelperqt.utils.process_utils import ProcessUtils
|
||||
|
||||
|
||||
class ProcessHandler:
|
||||
"""
|
||||
Сервис для выполнения процессов с обработкой вывода.
|
||||
|
||||
Предоставляет функциональность:
|
||||
- Запуск процессов
|
||||
- Обработка вывода (stdout/stderr)
|
||||
- Обработка завершения процесса
|
||||
"""
|
||||
|
||||
def __init__(self, parent=None):
|
||||
"""
|
||||
Инициализирует обработчик процессов.
|
||||
|
||||
Args:
|
||||
parent: Родительский QObject
|
||||
"""
|
||||
self.parent = parent
|
||||
self.process = None
|
||||
self.output_buffer = ""
|
||||
self.log_widget = None
|
||||
|
||||
def set_log_widget(self, log_widget):
|
||||
"""
|
||||
Устанавливает виджет для вывода логов.
|
||||
|
||||
Args:
|
||||
log_widget: QTextEdit для вывода
|
||||
"""
|
||||
self.log_widget = log_widget
|
||||
|
||||
def run_command(self, executable, arguments, log_widget=None):
|
||||
"""
|
||||
Запускает команду и выводит лог.
|
||||
|
||||
Args:
|
||||
executable: Путь к исполняемому файлу
|
||||
arguments: Список аргументов
|
||||
log_widget: QTextEdit для вывода (опционально)
|
||||
"""
|
||||
if log_widget:
|
||||
self.log_widget = log_widget
|
||||
|
||||
self.process = QProcess(self.parent)
|
||||
self.process.setProcessChannelMode(QProcess.MergedChannels)
|
||||
self.process.setProcessEnvironment(QProcessEnvironment.systemEnvironment())
|
||||
|
||||
# Логирование команды
|
||||
if self.log_widget:
|
||||
cmd_line = f"Выполнение: {shlex.quote(executable)} {' '.join(shlex.quote(a) for a in arguments)}"
|
||||
self._append_to_log(cmd_line)
|
||||
|
||||
self.process.errorOccurred.connect(self._on_error_occurred)
|
||||
self.process.start(executable, arguments)
|
||||
|
||||
if not self.process.waitForStarted(5000):
|
||||
self._append_to_log(
|
||||
f"Не удалось запустить процесс: {self.process.errorString()}",
|
||||
is_error=True
|
||||
)
|
||||
|
||||
return self.process
|
||||
|
||||
def _on_error_occurred(self, error):
|
||||
"""Обрабатывает ошибки запуска процесса."""
|
||||
if self.process:
|
||||
self._append_to_log(
|
||||
f"Ошибка процесса: {self.process.errorString()}",
|
||||
is_error=True
|
||||
)
|
||||
|
||||
def _append_to_log(self, text, is_error=False):
|
||||
"""Добавляет текст в лог."""
|
||||
if not self.log_widget:
|
||||
return
|
||||
|
||||
if is_error:
|
||||
self.log_widget.append(f'<span style="color:red;">{text}</span>')
|
||||
else:
|
||||
self.log_widget.append(text)
|
||||
|
||||
def get_process(self):
|
||||
"""Возвращает текущий процесс."""
|
||||
return self.process
|
||||
|
||||
def is_running(self):
|
||||
"""Проверяет, запущен ли процесс."""
|
||||
return self.process and self.process.state() == QProcess.Running
|
||||
|
||||
def terminate(self):
|
||||
"""Завершает процесс."""
|
||||
ProcessUtils.stop_process(self.process)
|
||||
|
||||
def kill(self):
|
||||
"""Убивает процесс."""
|
||||
ProcessUtils.stop_process(self.process)
|
||||
|
||||
|
||||
class CommandRunner:
|
||||
"""
|
||||
Утилита для запуска команд winehelper.
|
||||
"""
|
||||
|
||||
def __init__(self, winehelper_path):
|
||||
"""
|
||||
Инициализирует исполнитель команд.
|
||||
|
||||
Args:
|
||||
winehelper_path: Путь к скрипту winehelper
|
||||
"""
|
||||
self.winehelper_path = winehelper_path
|
||||
|
||||
def run(self, command, arguments, log_widget=None):
|
||||
"""
|
||||
Запускает команду winehelper.
|
||||
|
||||
Args:
|
||||
command: Имя команды
|
||||
arguments: Дополнительные аргументы
|
||||
log_widget: QTextEdit для вывода (опционально)
|
||||
"""
|
||||
process_handler = ProcessHandler()
|
||||
process_handler.set_log_widget(log_widget)
|
||||
|
||||
args = [command] + arguments
|
||||
return process_handler.run_command(self.winehelper_path, args, log_widget)
|
||||
|
||||
def remove_prefix(self, prefix_name, log_widget=None):
|
||||
"""
|
||||
Удаляет префикс.
|
||||
|
||||
Args:
|
||||
prefix_name: Имя префикса
|
||||
log_widget: QTextEdit для вывода (опционально)
|
||||
"""
|
||||
return self.run("remove-prefix", [prefix_name, "--force"], log_widget)
|
||||
|
||||
def create_base_prefix(self, prefix_name, log_widget=None):
|
||||
"""
|
||||
Создает базовый префикс.
|
||||
|
||||
Args:
|
||||
prefix_name: Имя префикса
|
||||
log_widget: QTextEdit для вывода (опционально)
|
||||
"""
|
||||
return self.run("create-base-pfx", [prefix_name], log_widget)
|
||||
|
||||
def clear_winetricks_cache(self, log_widget=None):
|
||||
"""
|
||||
Очищает кеш winetricks.
|
||||
|
||||
Args:
|
||||
log_widget: QTextEdit для вывода (опционально)
|
||||
"""
|
||||
return self.run("clear-winetricks-cache", ["--force"], log_widget)
|
||||
@@ -8,17 +8,22 @@
|
||||
- Управление тестовыми скриптами
|
||||
- Кэширование информации о скриптах
|
||||
"""
|
||||
import os
|
||||
from typing import List, Optional
|
||||
from dataclasses import dataclass
|
||||
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
from typing import List, Optional
|
||||
|
||||
from winehelperqt.logger import get_logger
|
||||
from winehelperqt.parsers.script_parser import ScriptParser
|
||||
from winehelperqt.utils.cache_service import CacheService
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
@dataclass
|
||||
class ScriptInfo:
|
||||
"""Информация о скрипте установки."""
|
||||
|
||||
name: str # Имя программы
|
||||
folder: str # Путь к папке скрипта
|
||||
script_path: str # Путь к install.sh
|
||||
@@ -70,11 +75,15 @@ class ScriptManager:
|
||||
return []
|
||||
|
||||
try:
|
||||
return sorted([
|
||||
os.path.join(folder_path, d) for d in os.listdir(folder_path)
|
||||
if os.path.isdir(os.path.join(folder_path, d))
|
||||
])
|
||||
except OSError:
|
||||
return sorted(
|
||||
[
|
||||
os.path.join(folder_path, d)
|
||||
for d in os.listdir(folder_path)
|
||||
if os.path.isdir(os.path.join(folder_path, d))
|
||||
]
|
||||
)
|
||||
except OSError as e:
|
||||
logger.warning("Не удалось прочитать папку со скриптами %s: %s", folder_path, e)
|
||||
return []
|
||||
|
||||
def get_script_files(self, folder_name: str) -> List[str]:
|
||||
@@ -93,26 +102,28 @@ class ScriptManager:
|
||||
folder_path = os.path.join(self.data_path, folder_name)
|
||||
|
||||
if not os.path.isdir(folder_path):
|
||||
logger.debug("Папка со скриптами не найдена: %s", folder_path)
|
||||
return []
|
||||
|
||||
try:
|
||||
entries = [
|
||||
os.path.join(folder_path, entry)
|
||||
for entry in os.listdir(folder_path)
|
||||
]
|
||||
entries = [os.path.join(folder_path, entry) for entry in os.listdir(folder_path)]
|
||||
logger.debug("Найдено %d записей в %s", len(entries), folder_path)
|
||||
|
||||
def _is_valid_script(path: str) -> bool:
|
||||
if not os.path.isfile(path):
|
||||
return False
|
||||
basename = os.path.basename(path)
|
||||
if basename.startswith('.'):
|
||||
if basename.startswith("."):
|
||||
return False
|
||||
if basename.endswith('.swp') or basename.endswith('~'):
|
||||
if basename.endswith(".swp") or basename.endswith("~"):
|
||||
return False
|
||||
return True
|
||||
|
||||
return sorted([entry for entry in entries if _is_valid_script(entry)])
|
||||
except OSError:
|
||||
scripts = sorted([entry for entry in entries if _is_valid_script(entry)])
|
||||
logger.debug("Отфильтровано скриптов в %s: %d", folder_path, len(scripts))
|
||||
return scripts
|
||||
except OSError as e:
|
||||
logger.warning("Не удалось прочитать папку со скриптами %s: %s", folder_path, e)
|
||||
return []
|
||||
|
||||
def get_script_info(self, script_path: str) -> Optional[ScriptInfo]:
|
||||
@@ -131,10 +142,14 @@ class ScriptManager:
|
||||
# Проверяем кэш
|
||||
cached = self.cache_service.get(cache_key)
|
||||
if cached is not None:
|
||||
logger.debug("Информация о скрипте взята из кэша: %s", script_path)
|
||||
return cached
|
||||
|
||||
logger.debug("Парсим информацию из скрипта: %s", script_path)
|
||||
|
||||
# Проверяем существование файла
|
||||
if not os.path.exists(script_path):
|
||||
logger.debug("Файл скрипта не найден: %s", script_path)
|
||||
return None
|
||||
|
||||
# Парсим информацию из скрипта
|
||||
@@ -149,6 +164,7 @@ class ScriptManager:
|
||||
# Если имя программы не найдено, используем имя папки как fallback
|
||||
if not prog_name:
|
||||
prog_name = os.path.basename(script_folder)
|
||||
logger.debug("Имя программы не найдено в %s, используем имя папки: %s", script_path, prog_name)
|
||||
|
||||
script_info = ScriptInfo(
|
||||
name=prog_name,
|
||||
@@ -156,12 +172,14 @@ class ScriptManager:
|
||||
script_path=script_path,
|
||||
description=description or "",
|
||||
icons=icons or [],
|
||||
url=url or ""
|
||||
url=url or "",
|
||||
)
|
||||
|
||||
# Сохраняем в кэш
|
||||
self.cache_service.set(cache_key, script_info)
|
||||
|
||||
logger.debug("Информация о скрипте сохранена в кэш: %s -> %s", script_path, prog_name)
|
||||
|
||||
return script_info
|
||||
|
||||
def list_available_apps(self, folder_name: str) -> List[ScriptInfo]:
|
||||
@@ -175,6 +193,7 @@ class ScriptManager:
|
||||
Список ScriptInfo
|
||||
"""
|
||||
script_files = self.get_script_files(folder_name)
|
||||
logger.debug("Загружаем скрипты из %s: найдено файлов %d", folder_name, len(script_files))
|
||||
apps = []
|
||||
|
||||
for script_file in script_files:
|
||||
@@ -182,6 +201,7 @@ class ScriptManager:
|
||||
if info:
|
||||
apps.append(info)
|
||||
|
||||
logger.debug("Загружено приложений из %s: %d", folder_name, len(apps))
|
||||
return apps
|
||||
|
||||
def get_autoinstall_scripts(self) -> List[ScriptInfo]:
|
||||
@@ -266,5 +286,6 @@ class ScriptManager:
|
||||
try:
|
||||
mtime = os.path.getmtime(script_path)
|
||||
return f"script_info:{script_path}:{mtime}"
|
||||
except OSError:
|
||||
except OSError as e:
|
||||
logger.warning("Не удалось получить время модификации %s: %s", script_path, e)
|
||||
return f"script_info:{script_path}"
|
||||
@@ -7,13 +7,17 @@
|
||||
- Backup/restore настроек
|
||||
- Загрузка настроек по умолчанию
|
||||
"""
|
||||
|
||||
import os
|
||||
import shutil
|
||||
from typing import Dict, Optional
|
||||
from datetime import datetime
|
||||
from typing import Dict, Optional
|
||||
|
||||
from winehelperqt.logger import get_logger
|
||||
from winehelperqt.utils.desktop_entry import DesktopEntry
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class SettingsManager:
|
||||
"""
|
||||
@@ -45,7 +49,9 @@ class SettingsManager:
|
||||
Returns:
|
||||
Словарь с настройками
|
||||
"""
|
||||
return self.prefix_manager.read_prefix_config(prefix_name)
|
||||
settings = self.prefix_manager.read_prefix_config(prefix_name)
|
||||
logger.debug("Загружены настройки префикса %s: %s", prefix_name, settings)
|
||||
return settings
|
||||
|
||||
def save_prefix_settings(self, prefix_name: str, settings: Dict[str, str]) -> bool:
|
||||
"""
|
||||
@@ -58,6 +64,7 @@ class SettingsManager:
|
||||
Returns:
|
||||
True если сохранение успешно
|
||||
"""
|
||||
logger.debug("Сохраняем настройки префикса %s: %s", prefix_name, settings)
|
||||
return self.prefix_manager.write_prefix_config(prefix_name, settings)
|
||||
|
||||
def load_app_settings(self, desktop_path: str) -> Dict[str, str]:
|
||||
@@ -76,8 +83,11 @@ class SettingsManager:
|
||||
try:
|
||||
entry = DesktopEntry(desktop_path)
|
||||
entry.load()
|
||||
return dict(entry.section('Desktop Entry'))
|
||||
except (IOError, OSError):
|
||||
settings = dict(entry.section("Desktop Entry"))
|
||||
logger.debug("Загружены настройки приложения %s: %s", desktop_path, settings)
|
||||
return settings
|
||||
except (IOError, OSError) as e:
|
||||
logger.warning("Не удалось прочитать настройки приложения %s: %s", desktop_path, e)
|
||||
return {}
|
||||
|
||||
def save_app_settings(self, desktop_path: str, settings: Dict[str, str]) -> bool:
|
||||
@@ -98,13 +108,13 @@ class SettingsManager:
|
||||
entry = DesktopEntry(desktop_path)
|
||||
entry.load()
|
||||
|
||||
desktop_section = entry.section('Desktop Entry')
|
||||
desktop_section = entry.section("Desktop Entry")
|
||||
desktop_section.update(settings)
|
||||
|
||||
return entry.save()
|
||||
|
||||
except (IOError, OSError) as e:
|
||||
print(f"Ошибка сохранения настроек: {e}")
|
||||
logger.error("Ошибка сохранения настроек: %s", e)
|
||||
return False
|
||||
|
||||
def backup_settings(self, source_path: str, backup_dir: Optional[str] = None) -> Optional[str]:
|
||||
@@ -124,10 +134,7 @@ class SettingsManager:
|
||||
try:
|
||||
# Определяем директорию для бэкапа
|
||||
if backup_dir is None:
|
||||
backup_dir = os.path.join(
|
||||
os.path.dirname(source_path),
|
||||
"backups"
|
||||
)
|
||||
backup_dir = os.path.join(os.path.dirname(source_path), "backups")
|
||||
|
||||
os.makedirs(backup_dir, exist_ok=True)
|
||||
|
||||
@@ -139,10 +146,11 @@ class SettingsManager:
|
||||
|
||||
# Копируем файл
|
||||
shutil.copy2(source_path, backup_path)
|
||||
logger.debug("Создан бэкап настроек: %s -> %s", source_path, backup_path)
|
||||
return backup_path
|
||||
|
||||
except (IOError, OSError) as e:
|
||||
print(f"Ошибка создания бэкапа: {e}")
|
||||
logger.error("Ошибка создания бэкапа: %s", e)
|
||||
return None
|
||||
|
||||
def restore_settings(self, backup_path: str, target_path: str) -> bool:
|
||||
@@ -156,6 +164,7 @@ class SettingsManager:
|
||||
Returns:
|
||||
True если восстановление успешно
|
||||
"""
|
||||
logger.debug("Восстановление настроек из бэкапа: %s -> %s", backup_path, target_path)
|
||||
if not os.path.exists(backup_path):
|
||||
return False
|
||||
|
||||
@@ -170,7 +179,7 @@ class SettingsManager:
|
||||
return True
|
||||
|
||||
except (IOError, OSError) as e:
|
||||
print(f"Ошибка восстановления настроек: {e}")
|
||||
logger.error("Ошибка восстановления настроек: %s", e)
|
||||
return False
|
||||
|
||||
def get_default_settings(self, prefix_name: str) -> Dict[str, str]:
|
||||
@@ -183,21 +192,21 @@ class SettingsManager:
|
||||
Returns:
|
||||
Словарь с настройками по умолчанию
|
||||
"""
|
||||
return {
|
||||
'WINE_ARCH': 'win64',
|
||||
'WINEESYNC': '0',
|
||||
'WINEFSYNC': '0',
|
||||
'WH_WINDOWS_VER': '10',
|
||||
'WH_USE_SHADER_CACHE': '1',
|
||||
'WH_USE_MESA_GL_OVERRIDE': '0',
|
||||
'WH_USE_WINE_DXGI': '0',
|
||||
'WINE_LARGE_ADDRESS_AWARE': '1',
|
||||
'WINE_FULLSCREEN_FSR': '1',
|
||||
defaults = {
|
||||
"WINE_ARCH": "win64",
|
||||
"WINEESYNC": "0",
|
||||
"WINEFSYNC": "0",
|
||||
"WH_WINDOWS_VER": "10",
|
||||
"WH_USE_SHADER_CACHE": "1",
|
||||
"WH_USE_MESA_GL_OVERRIDE": "0",
|
||||
"WH_USE_WINE_DXGI": "0",
|
||||
"WINE_LARGE_ADDRESS_AWARE": "1",
|
||||
"WINE_FULLSCREEN_FSR": "1",
|
||||
}
|
||||
logger.debug("Настройки по умолчанию для %s: %s", prefix_name, defaults)
|
||||
return defaults
|
||||
|
||||
def merge_settings(
|
||||
self, base: Dict[str, str], override: Dict[str, str]
|
||||
) -> Dict[str, str]:
|
||||
def merge_settings(self, base: Dict[str, str], override: Dict[str, str]) -> Dict[str, str]:
|
||||
"""
|
||||
Объединяет две конфигурации настроек.
|
||||
|
||||
@@ -210,4 +219,5 @@ class SettingsManager:
|
||||
"""
|
||||
result = base.copy()
|
||||
result.update(override)
|
||||
logger.debug("Объединение настроек: база=%s, переопределения=%s, результат=%s", base, override, result)
|
||||
return result
|
||||
@@ -1,13 +1,22 @@
|
||||
"""
|
||||
Сервисы для управления кэшем и компонентами Winetricks.
|
||||
"""
|
||||
import os
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from winehelperqt.logger import get_logger
|
||||
from winehelperqt.parsers.winetricks_parser import WinetricksOutputParser
|
||||
from winehelperqt.utils.cache_service import FileCacheService
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class NamedFileCacheService(FileCacheService):
|
||||
def _get_cache_path(self, key: str) -> Path:
|
||||
return self.cache_dir / f"{key}.cache"
|
||||
|
||||
|
||||
class WinetricksCacheService:
|
||||
"""
|
||||
@@ -29,10 +38,10 @@ class WinetricksCacheService:
|
||||
"""
|
||||
self.cache_dir = Path(cache_dir) if cache_dir else self.CACHE_DIR
|
||||
self.cache_ttl = cache_ttl if cache_ttl is not None else self.DEFAULT_CACHE_TTL_SECONDS
|
||||
self._ensure_cache_dir()
|
||||
self._file_cache = FileCacheService(cache_dir=str(self.cache_dir), cache_ttl=self.cache_ttl)
|
||||
self.ensure_cache_dir()
|
||||
self._file_cache = NamedFileCacheService(cache_dir=str(self.cache_dir), cache_ttl=self.cache_ttl)
|
||||
|
||||
def _ensure_cache_dir(self):
|
||||
def ensure_cache_dir(self):
|
||||
"""Создает директорию кэша если она не существует."""
|
||||
self.cache_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
@@ -45,11 +54,12 @@ class WinetricksCacheService:
|
||||
"""
|
||||
try:
|
||||
hasher = hashlib.sha256()
|
||||
with open(winetricks_path, 'rb') as f:
|
||||
with open(winetricks_path, "rb") as f:
|
||||
while chunk := f.read(4096):
|
||||
hasher.update(chunk)
|
||||
return hasher.hexdigest()
|
||||
except (IOError, OSError):
|
||||
except (IOError, OSError) as e:
|
||||
logger.warning("Не удалось вычислить хэш winetricks (%s): %s", winetricks_path, e)
|
||||
return None
|
||||
|
||||
def get_cached_data(self, category, winetricks_path):
|
||||
@@ -62,13 +72,20 @@ class WinetricksCacheService:
|
||||
"""
|
||||
cached = self._file_cache.get_json(category)
|
||||
if cached is None:
|
||||
logger.debug("Кэш категории winetricks '%s' отсутствует", category)
|
||||
return None
|
||||
|
||||
winetricks_hash = self._get_winetricks_hash(winetricks_path)
|
||||
if cached.get("hash") != winetricks_hash:
|
||||
logger.debug("Кэш категории winetricks '%s' устарел (изменился winetricks)", category)
|
||||
return None
|
||||
|
||||
return cached.get("output")
|
||||
output = cached.get("output")
|
||||
if isinstance(output, list):
|
||||
logger.debug("Кэш категории winetricks '%s': попадание (%d компонентов)", category, len(output))
|
||||
else:
|
||||
logger.debug("Кэш категории winetricks '%s': попадание", category)
|
||||
return output
|
||||
|
||||
def save_to_cache(self, category, output, winetricks_path):
|
||||
"""
|
||||
@@ -84,12 +101,14 @@ class WinetricksCacheService:
|
||||
if not winetricks_hash:
|
||||
return False
|
||||
|
||||
cache_data = {
|
||||
"hash": winetricks_hash,
|
||||
"output": output
|
||||
}
|
||||
|
||||
return self._file_cache.set_json(category, cache_data)
|
||||
cache_data = {"hash": winetricks_hash, "output": output}
|
||||
saved = self._file_cache.set_json(category, cache_data)
|
||||
if saved:
|
||||
if isinstance(output, list):
|
||||
logger.debug("Кэш категории winetricks '%s' сохранён (%d компонентов)", category, len(output))
|
||||
else:
|
||||
logger.debug("Кэш категории winetricks '%s' сохранён", category)
|
||||
return saved
|
||||
|
||||
def clear_cache(self):
|
||||
"""
|
||||
@@ -129,7 +148,9 @@ class WinetricksLogReader:
|
||||
"""
|
||||
Читает winetricks.log и возвращает множество установленных компонентов.
|
||||
"""
|
||||
return WinetricksOutputParser.parse_installed_verbs(self.log_path)
|
||||
verbs = WinetricksOutputParser.parse_installed_verbs(self.log_path)
|
||||
logger.debug("Установленные компоненты winetricks (%s): %d шт.", self.log_path, len(verbs))
|
||||
return verbs
|
||||
|
||||
def is_verb_installed(self, verb):
|
||||
"""
|
||||
|
||||
@@ -1,20 +1,21 @@
|
||||
"""
|
||||
Утилиты для winehelper GUI.
|
||||
"""
|
||||
from winehelperqt.utils.log_handler import LogProgressHandler, MultiLogHandler
|
||||
|
||||
from winehelperqt.utils.cache_service import CacheService, FileCacheService
|
||||
from winehelperqt.utils.version_utils import sort_versions
|
||||
from winehelperqt.utils.export_utils import ExportUtils
|
||||
from winehelperqt.utils.dialog_utils import DialogUtils
|
||||
from winehelperqt.utils.export_utils import ExportUtils
|
||||
from winehelperqt.utils.grid_utils import GridUtils
|
||||
from winehelperqt.utils.log_handler import LogProgressHandler, MultiLogHandler
|
||||
from winehelperqt.utils.version_utils import sort_versions
|
||||
|
||||
__all__ = [
|
||||
'LogProgressHandler',
|
||||
'MultiLogHandler',
|
||||
'CacheService',
|
||||
'FileCacheService',
|
||||
'sort_versions',
|
||||
'ExportUtils',
|
||||
'DialogUtils',
|
||||
'GridUtils',
|
||||
"LogProgressHandler",
|
||||
"MultiLogHandler",
|
||||
"CacheService",
|
||||
"FileCacheService",
|
||||
"sort_versions",
|
||||
"ExportUtils",
|
||||
"DialogUtils",
|
||||
"GridUtils",
|
||||
]
|
||||
@@ -7,12 +7,17 @@
|
||||
- File-based кэш для постоянных данных
|
||||
- Автоматическая очистка устаревших записей
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
from typing import Any, Optional, Dict
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
from winehelperqt.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class CacheEntry:
|
||||
@@ -69,12 +74,15 @@ class CacheService:
|
||||
"""
|
||||
entry = self._cache.get(key)
|
||||
if entry is None:
|
||||
logger.debug("Кэш '%s': промах (в памяти)", key)
|
||||
return default
|
||||
|
||||
if entry.is_expired():
|
||||
logger.debug("Кэш '%s': истёк (возраст %.0fс)", key, entry.age())
|
||||
self._cache.pop(key, None)
|
||||
return default
|
||||
|
||||
logger.debug("Кэш '%s': попадание (возраст %.0fс)", key, entry.age())
|
||||
return entry.data
|
||||
|
||||
def set(self, key: str, value: Any, ttl: Optional[float] = None) -> None:
|
||||
@@ -96,6 +104,7 @@ class CacheService:
|
||||
|
||||
effective_ttl = ttl if ttl is not None else self._default_ttl
|
||||
self._cache[key] = CacheEntry(value, effective_ttl)
|
||||
logger.debug("Кэш '%s': сохранено (TTL %s)", key, effective_ttl)
|
||||
|
||||
def delete(self, key: str) -> bool:
|
||||
"""
|
||||
@@ -139,10 +148,7 @@ class CacheService:
|
||||
|
||||
def _evict_expired(self) -> None:
|
||||
"""Удаляет все истекшие записи."""
|
||||
expired_keys = [
|
||||
key for key, entry in self._cache.items()
|
||||
if entry.is_expired()
|
||||
]
|
||||
expired_keys = [key for key, entry in self._cache.items() if entry.is_expired()]
|
||||
for key in expired_keys:
|
||||
del self._cache[key]
|
||||
|
||||
@@ -151,10 +157,7 @@ class CacheService:
|
||||
if not self._cache:
|
||||
return
|
||||
|
||||
oldest_key = min(
|
||||
self._cache.keys(),
|
||||
key=lambda k: self._cache[k].timestamp
|
||||
)
|
||||
oldest_key = min(self._cache.keys(), key=lambda k: self._cache[k].timestamp)
|
||||
del self._cache[oldest_key]
|
||||
|
||||
def cleanup(self) -> int:
|
||||
@@ -184,13 +187,13 @@ class FileCacheService:
|
||||
"""
|
||||
self.cache_dir = Path(cache_dir) if cache_dir else self._default_cache_dir()
|
||||
self.cache_ttl = cache_ttl if cache_ttl is not None else self.DEFAULT_CACHE_TTL_SECONDS
|
||||
self._ensure_cache_dir()
|
||||
self.ensure_cache_dir()
|
||||
|
||||
def _default_cache_dir(self) -> Path:
|
||||
"""Возвращает директорию кэша по умолчанию."""
|
||||
return Path.home() / ".cache" / "winehelper"
|
||||
|
||||
def _ensure_cache_dir(self) -> None:
|
||||
def ensure_cache_dir(self) -> None:
|
||||
"""Создаёт директорию кэша, если она не существует."""
|
||||
self.cache_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
@@ -222,23 +225,26 @@ class FileCacheService:
|
||||
cache_path = self._get_cache_path(key)
|
||||
|
||||
if not cache_path.exists():
|
||||
logger.debug("Файловый кэш '%s': промах", key)
|
||||
return default
|
||||
|
||||
try:
|
||||
with open(cache_path, 'r', encoding='utf-8') as f:
|
||||
with open(cache_path, "r", encoding="utf-8") as f:
|
||||
cache_data = json.load(f)
|
||||
|
||||
# Проверяем возраст кэша
|
||||
cache_age = time.time() - cache_data.get("timestamp", 0)
|
||||
if cache_age < self.cache_ttl:
|
||||
logger.debug("Файловый кэш '%s': попадание (возраст %.0fс)", key, cache_age)
|
||||
return cache_data.get("data")
|
||||
else:
|
||||
# Кэш устарел, удаляем
|
||||
cache_path.unlink(missing_ok=True)
|
||||
return default
|
||||
|
||||
# Кэш устарел, удаляем
|
||||
logger.debug("Файловый кэш '%s': устарел (возраст %.0fс)", key, cache_age)
|
||||
cache_path.unlink(missing_ok=True)
|
||||
return default
|
||||
|
||||
except (json.JSONDecodeError, IOError, KeyError) as e:
|
||||
print(f"Кэш '{key}' повреждён: {e}")
|
||||
logger.warning("Кэш '%s' повреждён: %s", key, e)
|
||||
return default
|
||||
|
||||
def set_json(self, key: str, data: Any) -> bool:
|
||||
@@ -254,24 +260,18 @@ class FileCacheService:
|
||||
"""
|
||||
cache_path = self._get_cache_path(key)
|
||||
|
||||
cache_data = {
|
||||
"timestamp": time.time(),
|
||||
"data": data
|
||||
}
|
||||
cache_data = {"timestamp": time.time(), "data": data}
|
||||
|
||||
try:
|
||||
# Создаём файл с правами 0o600, чтобы другие пользователи
|
||||
# не могли читать чувствительные данные кэша.
|
||||
fd = os.open(
|
||||
cache_path,
|
||||
os.O_WRONLY | os.O_CREAT | os.O_TRUNC,
|
||||
0o600
|
||||
)
|
||||
with os.fdopen(fd, 'w', encoding='utf-8') as f:
|
||||
fd = os.open(cache_path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
||||
json.dump(cache_data, f, ensure_ascii=False, indent=2)
|
||||
logger.debug("Файловый кэш '%s': сохранён в %s", key, cache_path)
|
||||
return True
|
||||
except (IOError, OSError) as e:
|
||||
print(f"Не удалось сохранить кэш '{key}': {e}")
|
||||
logger.error("Не удалось сохранить кэш '%s': %s", key, e)
|
||||
return False
|
||||
|
||||
def delete(self, key: str) -> bool:
|
||||
@@ -287,8 +287,10 @@ class FileCacheService:
|
||||
cache_path = self._get_cache_path(key)
|
||||
try:
|
||||
cache_path.unlink(missing_ok=True)
|
||||
logger.debug("Файловый кэш '%s': удалён", key)
|
||||
return True
|
||||
except OSError:
|
||||
except OSError as e:
|
||||
logger.warning("Не удалось удалить файловый кэш '%s': %s", key, e)
|
||||
return False
|
||||
|
||||
def clear(self) -> bool:
|
||||
@@ -300,11 +302,14 @@ class FileCacheService:
|
||||
"""
|
||||
try:
|
||||
if self.cache_dir.exists():
|
||||
count = 0
|
||||
for file_path in self.cache_dir.glob("*.cache"):
|
||||
file_path.unlink()
|
||||
count += 1
|
||||
logger.debug("Файловый кэш очищен: удалено %d файлов", count)
|
||||
return True
|
||||
except (IOError, OSError) as e:
|
||||
print(f"Ошибка очистки кэша: {e}")
|
||||
logger.error("Ошибка очистки кэша: %s", e)
|
||||
return False
|
||||
|
||||
def get_cache_age(self, key: str) -> Optional[float]:
|
||||
@@ -323,10 +328,11 @@ class FileCacheService:
|
||||
return None
|
||||
|
||||
try:
|
||||
with open(cache_path, 'r', encoding='utf-8') as f:
|
||||
with open(cache_path, "r", encoding="utf-8") as f:
|
||||
cache_data = json.load(f)
|
||||
return time.time() - cache_data.get("timestamp", 0)
|
||||
except (json.JSONDecodeError, IOError, KeyError):
|
||||
except (json.JSONDecodeError, IOError, KeyError) as e:
|
||||
logger.debug("Не удалось определить возраст кэша '%s': %s", key, e)
|
||||
return None
|
||||
|
||||
def is_valid(self, key: str) -> bool:
|
||||
|
||||
@@ -7,27 +7,32 @@
|
||||
- многострочных значений (продолжение строки с отступом)
|
||||
- сохранения регистра ключей (Name, Exec, Icon, Name[ru] и т.д.)
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
from collections import OrderedDict
|
||||
from typing import Dict
|
||||
|
||||
from winehelperqt.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class DesktopEntry:
|
||||
"""Простой reader/writer для .desktop файлов по спецификации XDG."""
|
||||
|
||||
_ESCAPE_MAP = {
|
||||
'\\s': ' ',
|
||||
'\\n': '\n',
|
||||
'\\t': '\t',
|
||||
'\\r': '\r',
|
||||
'\\\\': '\\',
|
||||
"\\s": " ",
|
||||
"\\n": "\n",
|
||||
"\\t": "\t",
|
||||
"\\r": "\r",
|
||||
"\\\\": "\\",
|
||||
}
|
||||
_REVERSE_ESCAPE_MAP = {
|
||||
'\n': '\\n',
|
||||
'\t': '\\t',
|
||||
'\r': '\\r',
|
||||
'\\': '\\\\',
|
||||
"\n": "\\n",
|
||||
"\t": "\\t",
|
||||
"\r": "\\r",
|
||||
"\\": "\\\\",
|
||||
}
|
||||
|
||||
def __init__(self, path: str):
|
||||
@@ -36,9 +41,9 @@ class DesktopEntry:
|
||||
path: Путь к .desktop файлу.
|
||||
"""
|
||||
self.path = path
|
||||
self.sections: Dict[str, 'OrderedDict[str, str]'] = OrderedDict()
|
||||
self.sections: Dict[str, "OrderedDict[str, str]"] = OrderedDict()
|
||||
|
||||
def load(self) -> 'DesktopEntry':
|
||||
def load(self) -> "DesktopEntry":
|
||||
"""Загружает .desktop файл."""
|
||||
self.sections = OrderedDict()
|
||||
|
||||
@@ -48,35 +53,35 @@ class DesktopEntry:
|
||||
current_section = None
|
||||
current_key = None
|
||||
|
||||
with open(self.path, 'r', encoding='utf-8') as f:
|
||||
with open(self.path, "r", encoding="utf-8") as f:
|
||||
for raw_line in f:
|
||||
line = raw_line.rstrip('\n').rstrip('\r')
|
||||
line = raw_line.rstrip("\n").rstrip("\r")
|
||||
|
||||
stripped = line.strip()
|
||||
if not stripped or stripped.startswith('#'):
|
||||
if not stripped or stripped.startswith("#"):
|
||||
continue
|
||||
|
||||
section_match = re.match(r'^\[([^\]]+)\]\s*$', stripped)
|
||||
section_match = re.match(r"^\[([^\]]+)\]\s*$", stripped)
|
||||
if section_match:
|
||||
current_section = section_match.group(1)
|
||||
self.sections.setdefault(current_section, OrderedDict())
|
||||
current_key = None
|
||||
continue
|
||||
|
||||
if line[0] in ' \t' and current_key is not None and current_section is not None:
|
||||
if line[0] in " \t" and current_key is not None and current_section is not None:
|
||||
# продолжение многострочного значения
|
||||
continuation = self._unescape(stripped)
|
||||
current_value = self.sections[current_section][current_key]
|
||||
self.sections[current_section][current_key] = current_value + '\n' + continuation
|
||||
self.sections[current_section][current_key] = current_value + "\n" + continuation
|
||||
continue
|
||||
|
||||
if '=' in stripped:
|
||||
key, value = stripped.split('=', 1)
|
||||
if "=" in stripped:
|
||||
key, value = stripped.split("=", 1)
|
||||
key = key.strip()
|
||||
value = self._unescape(value.strip())
|
||||
|
||||
if current_section is None:
|
||||
current_section = 'Desktop Entry'
|
||||
current_section = "Desktop Entry"
|
||||
self.sections.setdefault(current_section, OrderedDict())
|
||||
|
||||
self.sections[current_section][key] = value
|
||||
@@ -87,16 +92,16 @@ class DesktopEntry:
|
||||
def save(self) -> bool:
|
||||
"""Сохраняет .desktop файл."""
|
||||
try:
|
||||
os.makedirs(os.path.dirname(self.path) or '.', exist_ok=True)
|
||||
with open(self.path, 'w', encoding='utf-8') as f:
|
||||
os.makedirs(os.path.dirname(self.path) or ".", exist_ok=True)
|
||||
with open(self.path, "w", encoding="utf-8") as f:
|
||||
for section_name, entries in self.sections.items():
|
||||
f.write(f"[{section_name}]\n")
|
||||
for key, value in entries.items():
|
||||
f.write(f"{key}={self._escape(value)}\n")
|
||||
f.write('\n')
|
||||
f.write("\n")
|
||||
return True
|
||||
except (IOError, OSError) as e:
|
||||
print(f"Ошибка записи .desktop файла {self.path}: {e}")
|
||||
logger.error("Ошибка записи .desktop файла %s: %s", self.path, e)
|
||||
return False
|
||||
|
||||
def get(self, section: str, key: str, default=None):
|
||||
@@ -109,7 +114,7 @@ class DesktopEntry:
|
||||
self.sections[section] = OrderedDict()
|
||||
self.sections[section][key] = value
|
||||
|
||||
def section(self, section: str) -> 'OrderedDict[str, str]':
|
||||
def section(self, section: str) -> "OrderedDict[str, str]":
|
||||
"""Возвращает секцию как OrderedDict."""
|
||||
return self.sections.setdefault(section, OrderedDict())
|
||||
|
||||
@@ -119,15 +124,15 @@ class DesktopEntry:
|
||||
result = []
|
||||
i = 0
|
||||
while i < len(value):
|
||||
if value[i] == '\\' and i + 1 < len(value):
|
||||
seq = value[i:i + 2]
|
||||
if value[i] == "\\" and i + 1 < len(value):
|
||||
seq = value[i : i + 2]
|
||||
if seq in cls._ESCAPE_MAP:
|
||||
result.append(cls._ESCAPE_MAP[seq])
|
||||
i += 2
|
||||
continue
|
||||
result.append(value[i])
|
||||
i += 1
|
||||
return ''.join(result)
|
||||
return "".join(result)
|
||||
|
||||
@classmethod
|
||||
def _escape(cls, value: str) -> str:
|
||||
@@ -138,4 +143,4 @@ class DesktopEntry:
|
||||
result.append(cls._REVERSE_ESCAPE_MAP[char])
|
||||
else:
|
||||
result.append(char)
|
||||
return ''.join(result)
|
||||
return "".join(result)
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
Устраняет дублирование кода подтверждающих QMessageBox в GUI.
|
||||
"""
|
||||
|
||||
from PyQt5.QtWidgets import QMessageBox, QPushButton, QWidget
|
||||
|
||||
|
||||
@@ -17,7 +18,7 @@ class DialogUtils:
|
||||
yes_text: str = "Да",
|
||||
no_text: str = "Нет",
|
||||
default_no: bool = True,
|
||||
icon: QMessageBox.Icon = QMessageBox.Question
|
||||
icon: QMessageBox.Icon = QMessageBox.Question,
|
||||
) -> bool:
|
||||
"""
|
||||
Показывает подтверждающий диалог с двумя кнопками.
|
||||
|
||||
@@ -3,11 +3,13 @@
|
||||
|
||||
Устраняет дублирование класса Var в нескольких файлах.
|
||||
"""
|
||||
|
||||
import os
|
||||
|
||||
|
||||
class EnvironmentConfig:
|
||||
"""Полная конфигурация приложения из переменных окружения."""
|
||||
|
||||
# Переменные определяемые в скрипте winehelper
|
||||
SCRIPT_NAME = os.environ.get("SCRIPT_NAME")
|
||||
USER_WORK_PATH = os.environ.get("USER_WORK_PATH")
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
Устраняет дублирование парсинга и форматирования конфигурационных строк
|
||||
в prefix_manager, script_parser и диалогах настроек.
|
||||
"""
|
||||
|
||||
import re
|
||||
import shlex
|
||||
from typing import Optional, Tuple
|
||||
@@ -12,7 +13,7 @@ from typing import Optional, Tuple
|
||||
class ExportUtils:
|
||||
"""Утилиты для парсинга и форматирования export-строк."""
|
||||
|
||||
EXPORT_PATTERN = re.compile(r'^(?:export\s+)?(\w+)=(.*)$')
|
||||
EXPORT_PATTERN = re.compile(r"^(?:export\s+)?(\w+)=(.*)$")
|
||||
|
||||
@classmethod
|
||||
def parse_line(cls, line: str) -> Tuple[Optional[str], Optional[str]]:
|
||||
@@ -26,7 +27,7 @@ class ExportUtils:
|
||||
Кортеж (имя_переменной, значение) или (None, None)
|
||||
"""
|
||||
stripped = line.strip()
|
||||
if not stripped or stripped.startswith('#') or stripped.startswith('['):
|
||||
if not stripped or stripped.startswith("#") or stripped.startswith("["):
|
||||
return None, None
|
||||
|
||||
match = cls.EXPORT_PATTERN.match(stripped)
|
||||
@@ -37,9 +38,9 @@ class ExportUtils:
|
||||
raw_value = match.group(2).strip()
|
||||
try:
|
||||
parsed = shlex.split(raw_value)
|
||||
var_value = parsed[0] if parsed else ''
|
||||
var_value = parsed[0] if parsed else ""
|
||||
except ValueError:
|
||||
var_value = raw_value.strip('"\'')
|
||||
var_value = raw_value.strip("\"'")
|
||||
|
||||
return var_name, var_value
|
||||
|
||||
@@ -48,6 +49,9 @@ class ExportUtils:
|
||||
"""
|
||||
Форматирует строку export VAR=value с экранированием.
|
||||
|
||||
Всегда использует двойные кавычки для совместимости с bash-функцией
|
||||
update_last_conf_var(), которая также пишет с двойными кавычками.
|
||||
|
||||
Args:
|
||||
var_name: Имя переменной
|
||||
value: Значение переменной
|
||||
@@ -56,8 +60,10 @@ class ExportUtils:
|
||||
Returns:
|
||||
Отформатированная строка
|
||||
"""
|
||||
prefix = 'export ' if with_export else ''
|
||||
return f'{prefix}{var_name}={shlex.quote(value)}\n'
|
||||
prefix = "export " if with_export else ""
|
||||
# Экранируем двойные кавычки внутри значения
|
||||
escaped = value.replace('"', '\\"')
|
||||
return f'{prefix}{var_name}="{escaped}"\n'
|
||||
|
||||
@classmethod
|
||||
def update_lines(cls, lines: list, variables: dict, with_export: bool = True) -> list:
|
||||
|
||||
@@ -4,9 +4,10 @@
|
||||
Устраняет дублирование кода фильтрации и перестроения QGridLayout
|
||||
в списках приложений и диалогах выбора версий.
|
||||
"""
|
||||
|
||||
from typing import Iterable, Optional
|
||||
|
||||
from PyQt5.QtWidgets import QGridLayout, QFrame, QAbstractButton, QWidget
|
||||
from PyQt5.QtWidgets import QAbstractButton, QFrame, QGridLayout, QWidget
|
||||
|
||||
|
||||
class GridUtils:
|
||||
@@ -21,7 +22,7 @@ class GridUtils:
|
||||
search_text: str,
|
||||
grid_layout: Optional[QGridLayout] = None,
|
||||
num_columns: int = DEFAULT_NUM_COLUMNS,
|
||||
text_getter=None
|
||||
text_getter=None,
|
||||
) -> list:
|
||||
"""
|
||||
Фильтрует виджеты по тексту и перестраивает сетку.
|
||||
@@ -41,8 +42,9 @@ class GridUtils:
|
||||
visible_buttons = []
|
||||
|
||||
if text_getter is None:
|
||||
|
||||
def text_getter(btn):
|
||||
return btn.text() if hasattr(btn, 'text') else ''
|
||||
return btn.text() if hasattr(btn, "text") else ""
|
||||
|
||||
for btn in buttons:
|
||||
is_match = search_text_lower in text_getter(btn).lower()
|
||||
@@ -63,7 +65,8 @@ class GridUtils:
|
||||
buttons: Iterable[QAbstractButton],
|
||||
search_text: str,
|
||||
grid_layout: QGridLayout,
|
||||
num_columns: int = DEFAULT_NUM_COLUMNS
|
||||
num_columns: int = DEFAULT_NUM_COLUMNS,
|
||||
text_getter=None,
|
||||
) -> list:
|
||||
"""
|
||||
Фильтрует кнопки, обернутые в QFrame, по тексту и перестраивает сетку.
|
||||
@@ -73,6 +76,8 @@ class GridUtils:
|
||||
search_text: Текст для поиска
|
||||
grid_layout: QGridLayout для перестроения
|
||||
num_columns: Количество колонок в сетке
|
||||
text_getter: Функция для получения текста кнопки
|
||||
(по умолчанию используется text())
|
||||
|
||||
Returns:
|
||||
Список видимых фреймов
|
||||
@@ -80,12 +85,17 @@ class GridUtils:
|
||||
search_text_lower = search_text.lower()
|
||||
visible_frames = []
|
||||
|
||||
if text_getter is None:
|
||||
|
||||
def text_getter(btn):
|
||||
return btn.text()
|
||||
|
||||
for btn in buttons:
|
||||
frame = btn.parent()
|
||||
if not isinstance(frame, QFrame):
|
||||
frame = btn
|
||||
|
||||
is_match = search_text_lower in btn.text().lower()
|
||||
is_match = search_text_lower in text_getter(btn).lower()
|
||||
frame.setVisible(is_match)
|
||||
if is_match:
|
||||
visible_frames.append(frame)
|
||||
|
||||
@@ -2,9 +2,18 @@
|
||||
Обработчик логов с поддержкой прогресс-баров.
|
||||
Обрабатывает вывод процессов с корректным отображением однострочного прогресса.
|
||||
"""
|
||||
|
||||
import re
|
||||
|
||||
from PyQt5.QtGui import QTextCursor
|
||||
|
||||
from winehelperqt.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
# Отдельный логгер для вывода внешних процессов (bash, wine),
|
||||
# чтобы в консоли отличать его от событий самого GUI
|
||||
process_logger = get_logger("process")
|
||||
|
||||
|
||||
class LogProgressHandler:
|
||||
"""
|
||||
@@ -14,7 +23,7 @@ class LogProgressHandler:
|
||||
заменяя предыдущие строки прогресса новыми, вместо добавления новых строк.
|
||||
"""
|
||||
|
||||
PROGRESS_PERCENT_PATTERN = re.compile(r'\d\s*%')
|
||||
PROGRESS_PERCENT_PATTERN = re.compile(r"\d\s*%")
|
||||
|
||||
def __init__(self, log_widget=None):
|
||||
"""
|
||||
@@ -44,15 +53,15 @@ class LogProgressHandler:
|
||||
self.output_buffer += raw_output
|
||||
|
||||
while True:
|
||||
idx_n = self.output_buffer.find('\n')
|
||||
idx_r = self.output_buffer.find('\r')
|
||||
idx_n = self.output_buffer.find("\n")
|
||||
idx_r = self.output_buffer.find("\r")
|
||||
|
||||
if idx_n == -1 and idx_r == -1:
|
||||
break
|
||||
|
||||
split_idx = min(idx for idx in [idx_n, idx_r] if idx != -1)
|
||||
line = self.output_buffer[:split_idx + 1]
|
||||
self.output_buffer = self.output_buffer[split_idx + 1:]
|
||||
line = self.output_buffer[: split_idx + 1]
|
||||
self.output_buffer = self.output_buffer[split_idx + 1 :]
|
||||
|
||||
self._process_log_line(line)
|
||||
|
||||
@@ -84,7 +93,7 @@ class LogProgressHandler:
|
||||
cursor.movePosition(QTextCursor.End)
|
||||
cursor.insertText("\n")
|
||||
|
||||
self._reset_state()
|
||||
self.reset_state()
|
||||
|
||||
def _process_log_line(self, line_with_delimiter):
|
||||
"""
|
||||
@@ -93,13 +102,13 @@ class LogProgressHandler:
|
||||
Args:
|
||||
line_with_delimiter: Строка с разделителем (\n или \r)
|
||||
"""
|
||||
is_progress_line = '\r' in line_with_delimiter
|
||||
is_progress_line = "\r" in line_with_delimiter
|
||||
|
||||
if is_progress_line:
|
||||
if not self.PROGRESS_PERCENT_PATTERN.search(line_with_delimiter):
|
||||
return
|
||||
|
||||
clean_line = line_with_delimiter.replace('\r', '').replace('\n', '').strip()
|
||||
clean_line = line_with_delimiter.replace("\r", "").replace("\n", "").strip()
|
||||
|
||||
if not clean_line:
|
||||
return
|
||||
@@ -118,6 +127,10 @@ class LogProgressHandler:
|
||||
add_newline = not is_progress_line
|
||||
self._append_to_log(clean_line, is_error=False, add_newline=add_newline)
|
||||
|
||||
# Дублируем в консоль (строки прогресса пропускаем, чтобы не спамить процентами)
|
||||
if not is_progress_line:
|
||||
process_logger.info("%s", clean_line)
|
||||
|
||||
self.last_line_was_progress = is_progress_line
|
||||
|
||||
def _append_to_log(self, text, is_error=False, add_newline=True):
|
||||
@@ -152,7 +165,7 @@ class LogProgressHandler:
|
||||
|
||||
self.log_widget.ensureCursorVisible()
|
||||
|
||||
def _reset_state(self):
|
||||
def reset_state(self):
|
||||
"""Сбрасывает состояние обработчика."""
|
||||
self.last_line_was_progress = False
|
||||
self.output_buffer = ""
|
||||
@@ -161,7 +174,7 @@ class LogProgressHandler:
|
||||
"""Очищает лог и сбрасывает состояние."""
|
||||
if self.log_widget:
|
||||
self.log_widget.clear()
|
||||
self._reset_state()
|
||||
self.reset_state()
|
||||
|
||||
def append_error(self, text):
|
||||
"""
|
||||
@@ -171,6 +184,7 @@ class LogProgressHandler:
|
||||
text: Текст ошибки
|
||||
"""
|
||||
self._append_to_log(text, is_error=True, add_newline=True)
|
||||
logger.error("%s", text)
|
||||
|
||||
def append_info(self, text, add_newline=True):
|
||||
"""
|
||||
@@ -181,6 +195,7 @@ class LogProgressHandler:
|
||||
add_newline: True если добавить перенос строки
|
||||
"""
|
||||
self._append_to_log(text, is_error=False, add_newline=add_newline)
|
||||
logger.info("%s", text)
|
||||
|
||||
|
||||
class MultiLogHandler:
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
"""
|
||||
Построение HTML с информацией о префиксе для панели менеджера префиксов.
|
||||
|
||||
Вынесено из WineHelperGUI для уменьшения главного класса.
|
||||
"""
|
||||
|
||||
import html
|
||||
import os
|
||||
|
||||
from winehelperqt.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# Служебные компоненты winetricks, которые не показываем пользователю
|
||||
VERBS_TO_IGNORE = {
|
||||
"isolate_home",
|
||||
"winxp",
|
||||
"win7",
|
||||
"win10",
|
||||
"win11",
|
||||
"vista",
|
||||
"win2k",
|
||||
"win2k3",
|
||||
"win2k8",
|
||||
"win8",
|
||||
"win81",
|
||||
"workaround",
|
||||
"internal",
|
||||
}
|
||||
|
||||
# Карта для красивого отображения известных переменных префикса
|
||||
DISPLAY_MAP = {
|
||||
"WINEPREFIX": ("Путь", lambda v: v),
|
||||
"WINEARCH": ("Архитектура", lambda v: "64-bit" if v == "win64" else "32-bit"),
|
||||
"WH_WINE_USE": ("Версия Wine", lambda v: "Системная" if v == "system" else v),
|
||||
"BASE_PFX": ("Шаблон префикса", lambda v: "Не задан" if not v or v.lower() == "none" else v),
|
||||
"DXVK_VER": ("Версия DXVK", lambda v: "Не задана" if not v or v.lower() == "none" else v),
|
||||
"VKD3D_VER": ("Версия VKD3D", lambda v: "Не задана" if not v or v.lower() == "none" else v),
|
||||
"WINEESYNC": ("ESync", lambda v: "Включен" if v == "1" else "Выключен"),
|
||||
"WINEFSYNC": ("FSync", lambda v: "Включен" if v == "1" else "Выключен"),
|
||||
"WH_USE_CPCSP_PROXY": ("CPCSP_PROXY", lambda v: "Включен" if v == "1" else "Выключен"),
|
||||
"WH_XDG_OPEN": ("Ассоциации файлов", lambda v: v if v and v not in ("0", "default") else "Не заданы"),
|
||||
"WH_WINDOWS_VER": ("Версия Windows", lambda v: f"Windows {v}" if v else "Не задана"),
|
||||
}
|
||||
|
||||
# Порядок отображения известных переменных
|
||||
DISPLAY_ORDER = [
|
||||
"WINEPREFIX",
|
||||
"WINEARCH",
|
||||
"WH_WINE_USE",
|
||||
"BASE_PFX",
|
||||
"DXVK_VER",
|
||||
"VKD3D_VER",
|
||||
"WINEESYNC",
|
||||
"WINEFSYNC",
|
||||
"WH_USE_CPCSP_PROXY",
|
||||
"WH_WINDOWS_VER",
|
||||
"WH_XDG_OPEN",
|
||||
]
|
||||
|
||||
|
||||
def _read_winetricks_verbs(prefix_dir):
|
||||
"""
|
||||
Читает список установленных компонентов из winetricks.log префикса.
|
||||
|
||||
Args:
|
||||
prefix_dir: Путь к директории префикса
|
||||
|
||||
Returns:
|
||||
Отсортированный список компонентов для отображения
|
||||
"""
|
||||
log_path = os.path.join(prefix_dir, "winetricks.log")
|
||||
installed_verbs = []
|
||||
if os.path.exists(log_path):
|
||||
try:
|
||||
with open(log_path, "r", encoding="utf-8") as f:
|
||||
for line in f:
|
||||
verb = line.split("#", 1)[0].strip()
|
||||
if verb:
|
||||
installed_verbs.append(verb)
|
||||
except IOError as e:
|
||||
logger.error("Ошибка чтения winetricks.log: %s", e)
|
||||
|
||||
return sorted([v for v in installed_verbs if v not in VERBS_TO_IGNORE])
|
||||
|
||||
|
||||
def build_prefix_info_html(prefix_name, all_vars, prefixes_dir):
|
||||
"""
|
||||
Строит HTML с информацией о префиксе для информационного блока.
|
||||
|
||||
Args:
|
||||
prefix_name: Имя префикса
|
||||
all_vars: Словарь переменных из last.conf (может быть пустым)
|
||||
prefixes_dir: Путь к директории с префиксами (для чтения winetricks.log)
|
||||
|
||||
Returns:
|
||||
HTML-строка для отображения
|
||||
"""
|
||||
if not all_vars:
|
||||
return f"<p>Файл конфигурации last.conf не найден или пуст для префикса '{html.escape(prefix_name)}'.</p>"
|
||||
|
||||
display_verbs = _read_winetricks_verbs(os.path.join(prefixes_dir, prefix_name))
|
||||
|
||||
html_content = '<p style="line-height: 1.3; font-size: 9pt;">'
|
||||
html_content += f"<b>Имя префикса:</b> {html.escape(prefix_name)}<br>"
|
||||
|
||||
# Отображаем известные переменные в заданном порядке
|
||||
for key in DISPLAY_ORDER:
|
||||
if key in all_vars:
|
||||
label, formatter = DISPLAY_MAP[key]
|
||||
value = formatter(all_vars[key])
|
||||
html_content += f"<b>{html.escape(label)}:</b> {html.escape(value)}<br>"
|
||||
|
||||
# Отображаем остальные (неизвестные) переменные
|
||||
other_vars_html = ""
|
||||
for key, value in sorted(all_vars.items()):
|
||||
if key not in DISPLAY_MAP:
|
||||
other_vars_html += f" <b>{html.escape(key)}:</b> {html.escape(value)}<br>"
|
||||
|
||||
if other_vars_html:
|
||||
html_content += "<br><b>Дополнительные параметры:</b><br>"
|
||||
html_content += other_vars_html
|
||||
|
||||
html_content += "<br><b>Компоненты (Winetricks):</b> "
|
||||
if display_verbs:
|
||||
# Используем span вместо div, чтобы избежать лишних отступов
|
||||
html_content += '<span style="max-height: 120px; overflow-y: auto;">'
|
||||
html_content += ", ".join(html.escape(v) for v in display_verbs)
|
||||
html_content += "</span>"
|
||||
else:
|
||||
html_content += "Не установлены"
|
||||
|
||||
html_content += "</p>"
|
||||
return html_content
|
||||
@@ -3,7 +3,8 @@
|
||||
|
||||
Устраняет дублирование кода остановки процессов в разных частях приложения.
|
||||
"""
|
||||
from PyQt5.QtCore import QProcess
|
||||
|
||||
from PyQt5.QtCore import QProcess, QTimer
|
||||
|
||||
|
||||
class ProcessUtils:
|
||||
@@ -15,7 +16,8 @@ class ProcessUtils:
|
||||
@staticmethod
|
||||
def stop_process(process: QProcess, timeout: int = DEFAULT_TERMINATE_TIMEOUT) -> None:
|
||||
"""
|
||||
Останавливает QProcess: сначала terminate, потом kill если не завершился.
|
||||
Останавливает QProcess без блокировки UI-потока:
|
||||
сразу terminate, затем kill по таймауту, если процесс ещё жив.
|
||||
|
||||
Args:
|
||||
process: Процесс для остановки
|
||||
@@ -26,8 +28,16 @@ class ProcessUtils:
|
||||
|
||||
if process.state() == QProcess.Running:
|
||||
process.terminate()
|
||||
if not process.waitForFinished(timeout):
|
||||
QTimer.singleShot(timeout, lambda p=process: ProcessUtils._kill_if_running(p))
|
||||
|
||||
@staticmethod
|
||||
def _kill_if_running(process: QProcess) -> None:
|
||||
"""Убивает процесс, если он не завершился после terminate."""
|
||||
try:
|
||||
if process and process.state() == QProcess.Running:
|
||||
process.kill()
|
||||
except RuntimeError:
|
||||
pass # объект QProcess уже удалён
|
||||
|
||||
@staticmethod
|
||||
def is_running(process: QProcess) -> bool:
|
||||
|
||||
@@ -4,11 +4,11 @@
|
||||
Исправляет проблему лексикографической сортировки строк версий,
|
||||
где 'wine-9.0...' считалось больше чем 'wine-11.0...'.
|
||||
"""
|
||||
|
||||
import re
|
||||
|
||||
|
||||
# Регулярное выражение для извлечения числовых частей версии
|
||||
_VERSION_PART_RE = re.compile(r'(\d+)')
|
||||
_VERSION_PART_RE = re.compile(r"(\d+)")
|
||||
|
||||
|
||||
def _version_key(version_string):
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
"""
|
||||
Виджеты для winehelper GUI.
|
||||
"""
|
||||
|
||||
from winehelperqt.widgets.icon_manager import IconManager
|
||||
|
||||
__all__ = [
|
||||
'IconManager',
|
||||
"IconManager",
|
||||
]
|
||||
@@ -8,12 +8,13 @@
|
||||
- Кэширование иконок
|
||||
- Извлечение иконок из .exe файлов
|
||||
"""
|
||||
import os
|
||||
from typing import List, Optional, Dict, Tuple
|
||||
|
||||
from PyQt5.QtCore import Qt, QObject, QTimer, QSize, QPropertyAnimation, QEasingCurve
|
||||
from PyQt5.QtGui import QIcon, QPixmap, QPainter, QColor
|
||||
from PyQt5.QtWidgets import QToolButton, QSizePolicy, QFrame, QVBoxLayout
|
||||
import os
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
|
||||
from PyQt5.QtCore import QEasingCurve, QObject, QPropertyAnimation, QSize, Qt, QTimer
|
||||
from PyQt5.QtGui import QColor, QIcon, QPainter, QPixmap
|
||||
from PyQt5.QtWidgets import QFrame, QSizePolicy, QToolButton, QVBoxLayout
|
||||
|
||||
|
||||
class IconManager(QObject):
|
||||
@@ -34,6 +35,14 @@ class IconManager(QObject):
|
||||
# Длительность анимации fade (мс)
|
||||
FADE_DURATION = 700
|
||||
|
||||
# Стили рамок выделения кнопок (единый источник для GUI и виджетов)
|
||||
SELECTION_FRAME_DEFAULT = (
|
||||
"QFrame { border: 2px solid transparent; border-radius: 8px; padding: 0px; background-color: palette(window); }"
|
||||
)
|
||||
SELECTION_FRAME_ACTIVE = (
|
||||
"QFrame { border: 2px solid #0078d7; border-radius: 8px; padding: 0px; background-color: palette(window); }"
|
||||
)
|
||||
|
||||
def __init__(self, parent: Optional[QObject] = None):
|
||||
"""
|
||||
Инициализирует менеджер иконок.
|
||||
@@ -46,12 +55,13 @@ class IconManager(QObject):
|
||||
self._icon_cache: Dict[str, QIcon] = {}
|
||||
|
||||
def create_animated_button(
|
||||
self, text: str,
|
||||
self,
|
||||
text: str,
|
||||
icon_paths: List[str],
|
||||
style_sheet: str,
|
||||
icon_size: int = 32,
|
||||
min_width: int = 250,
|
||||
height: int = 70
|
||||
height: int = 70,
|
||||
) -> QToolButton:
|
||||
"""
|
||||
Создает кнопку с анимацией смены иконок.
|
||||
@@ -89,14 +99,12 @@ class IconManager(QObject):
|
||||
# Создаём таймер для смены иконок
|
||||
main_timer = QTimer(btn)
|
||||
self._icon_animators[btn] = {
|
||||
'main_timer': main_timer,
|
||||
'icons': existing_paths,
|
||||
'current_index': 0,
|
||||
'animation': None
|
||||
"main_timer": main_timer,
|
||||
"icons": existing_paths,
|
||||
"current_index": 0,
|
||||
"animation": None,
|
||||
}
|
||||
main_timer.timeout.connect(
|
||||
lambda b=btn: self._start_fade_animation(b)
|
||||
)
|
||||
main_timer.timeout.connect(lambda b=btn: self._start_fade_animation(b))
|
||||
main_timer.start(self.DEFAULT_ICON_INTERVAL)
|
||||
else:
|
||||
# Одна иконка без анимации
|
||||
@@ -108,10 +116,7 @@ class IconManager(QObject):
|
||||
return btn
|
||||
|
||||
def create_button_with_frame(
|
||||
self, text: str,
|
||||
icon_paths: List[str],
|
||||
style_sheet: str,
|
||||
frame_style: str
|
||||
self, text: str, icon_paths: List[str], style_sheet: str, frame_style: str
|
||||
) -> Tuple[QFrame, QToolButton]:
|
||||
"""
|
||||
Создает кнопку в рамке для выделения.
|
||||
@@ -192,15 +197,9 @@ class IconManager(QObject):
|
||||
selected: True для выделения
|
||||
"""
|
||||
if selected:
|
||||
frame.setStyleSheet(
|
||||
"QFrame { border: 2px solid #0078d7; border-radius: 8px; "
|
||||
"padding: 0px; background-color: palette(window); }"
|
||||
)
|
||||
frame.setStyleSheet(self.SELECTION_FRAME_ACTIVE)
|
||||
else:
|
||||
frame.setStyleSheet(
|
||||
"QFrame { border: 2px solid transparent; border-radius: 8px; "
|
||||
"padding: 0px; background-color: palette(window); }"
|
||||
)
|
||||
frame.setStyleSheet(self.SELECTION_FRAME_DEFAULT)
|
||||
|
||||
def stop_button_animation(self, button: QToolButton) -> None:
|
||||
"""
|
||||
@@ -211,10 +210,10 @@ class IconManager(QObject):
|
||||
"""
|
||||
if button in self._icon_animators:
|
||||
anim_data = self._icon_animators.pop(button)
|
||||
if 'main_timer' in anim_data:
|
||||
anim_data['main_timer'].stop()
|
||||
if 'animation' in anim_data and anim_data['animation']:
|
||||
anim_data['animation'].stop()
|
||||
if "main_timer" in anim_data:
|
||||
anim_data["main_timer"].stop()
|
||||
if "animation" in anim_data and anim_data["animation"]:
|
||||
anim_data["animation"].stop()
|
||||
|
||||
def cleanup(self) -> None:
|
||||
"""Останавливает все анимации и очищает ресурсы."""
|
||||
@@ -232,35 +231,35 @@ class IconManager(QObject):
|
||||
if button not in self._icon_animators:
|
||||
return
|
||||
|
||||
# Не тратим ресурсы на анимацию скрытых кнопок (неактивная вкладка, фильтр поиска, свёрнутое окно)
|
||||
if not button.isVisible():
|
||||
return
|
||||
|
||||
anim_data = self._icon_animators[button]
|
||||
|
||||
# Получаем или создаём объект анимации
|
||||
animation = anim_data.get('animation')
|
||||
animation = anim_data.get("animation")
|
||||
if not animation:
|
||||
button.setProperty("fadeProgress", 0.0)
|
||||
animation = QPropertyAnimation(button, b"fadeProgress", self)
|
||||
animation.setDuration(self.FADE_DURATION)
|
||||
animation.setEasingCurve(QEasingCurve.InOutQuad)
|
||||
|
||||
animation.valueChanged.connect(
|
||||
lambda value, b=button: self._update_icon_blend(b, value)
|
||||
)
|
||||
animation.finished.connect(
|
||||
lambda b=button: self._on_animation_finished(b)
|
||||
)
|
||||
anim_data['animation'] = animation
|
||||
animation.valueChanged.connect(lambda value, b=button: self._update_icon_blend(b, value))
|
||||
animation.finished.connect(lambda b=button: self._on_animation_finished(b))
|
||||
anim_data["animation"] = animation
|
||||
|
||||
# Останавливаем предыдущую анимацию
|
||||
if animation.state() == QPropertyAnimation.Running:
|
||||
animation.stop()
|
||||
|
||||
# Определяем текущую и следующую иконки
|
||||
current_icon_path = anim_data['icons'][anim_data['current_index']]
|
||||
next_icon_index = (anim_data['current_index'] + 1) % len(anim_data['icons'])
|
||||
next_icon_path = anim_data['icons'][next_icon_index]
|
||||
current_icon_path = anim_data["icons"][anim_data["current_index"]]
|
||||
next_icon_index = (anim_data["current_index"] + 1) % len(anim_data["icons"])
|
||||
next_icon_path = anim_data["icons"][next_icon_index]
|
||||
|
||||
# Сохраняем QPixmap для использования в функции обновления
|
||||
anim_data['pixmaps'] = (QPixmap(current_icon_path), QPixmap(next_icon_path))
|
||||
anim_data["pixmaps"] = (QPixmap(current_icon_path), QPixmap(next_icon_path))
|
||||
|
||||
# Запускаем анимацию
|
||||
animation.setStartValue(0.0)
|
||||
@@ -271,7 +270,7 @@ class IconManager(QObject):
|
||||
"""Обработчик завершения анимации."""
|
||||
if button in self._icon_animators:
|
||||
anim_data = self._icon_animators[button]
|
||||
anim_data['current_index'] = (anim_data['current_index'] + 1) % len(anim_data['icons'])
|
||||
anim_data["current_index"] = (anim_data["current_index"] + 1) % len(anim_data["icons"])
|
||||
|
||||
def _update_icon_blend(self, button: QToolButton, progress: float) -> None:
|
||||
"""
|
||||
@@ -282,10 +281,10 @@ class IconManager(QObject):
|
||||
progress: Прогресс от 0.0 до 1.0
|
||||
"""
|
||||
anim_data = self._icon_animators.get(button)
|
||||
if not anim_data or 'pixmaps' not in anim_data:
|
||||
if not anim_data or "pixmaps" not in anim_data:
|
||||
return
|
||||
|
||||
old_pixmap, new_pixmap = anim_data['pixmaps']
|
||||
old_pixmap, new_pixmap = anim_data["pixmaps"]
|
||||
|
||||
# На последнем кадре устанавливаем новую иконку
|
||||
if progress >= 1.0:
|
||||
|
||||
Reference in new issue
Block a user