pp-games-lib 20.2 KB
Newer Older
fidel's avatar
fidel committed
1 2 3 4 5 6
#!/usr/bin/env python3

import os
import re
import shlex
import shutil
Mikhail Tergoev's avatar
Mikhail Tergoev committed
7
import logging
fidel's avatar
fidel committed
8
from configparser import RawConfigParser
fidel's avatar
fidel committed
9 10 11 12 13 14 15 16
from pathlib import Path
from subprocess import run
from types import SimpleNamespace
try:
    from PyQt6.QtCore import * # type: ignore
    from PyQt6.QtGui import * # type: ignore
    from PyQt6.QtWidgets import * # type: ignore
except ModuleNotFoundError:
fidel's avatar
fidel committed
17 18 19
    from PyQt5.QtCore import * # type: ignore
    from PyQt5.QtGui import * # type: ignore
    from PyQt5.QtWidgets import * # type: ignore
fidel's avatar
fidel committed
20 21

settings = QSettings('PPGL', 'PortProtonGamesLib')
Castro_Fidel's avatar
Castro_Fidel committed
22
g = SimpleNamespace(locale = '')
fidel's avatar
fidel committed
23 24 25 26 27 28 29 30 31 32

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()

        self.resize(QSize(800, 600))
        geometry = settings.value('geometry_main')
        if geometry:
            self.restoreGeometry(geometry)

fidel's avatar
fidel committed
33
        shortcut = RawConfigParser()
fidel's avatar
fidel committed
34 35 36 37 38 39
        shortcut.read(os.getenv('HOME') + '/.local/share/applications/PortProton.desktop')
        scripts_dir = shortcut.get('Desktop Entry', 'Path', fallback=os.getenv('HOME') + '/.local/share/PortWINE/PortProton/data/scripts')
        if not scripts_dir or not Path(scripts_dir).is_dir():
            QMessageBox.critical(self, 'Error', 'Can not find installed PortProton')
            exit(1)
        g.scripts_dir = scripts_dir.rstrip('/')
Mikhail Tergoev's avatar
Mikhail Tergoev committed
40 41 42
        g.pp_icon = shortcut.get('Desktop Entry', 'Icon', fallback='/usr/share/pixmaps/portproton.png')
        pp_icon = QIcon(g.pp_icon)
        self.setWindowIcon(pp_icon)
fidel's avatar
fidel committed
43 44 45 46 47 48 49
        self.setWindowTitle('PortProton games library')

        g.base_dir = str(Path(scripts_dir + '/../..').resolve())
        g.install_pfx = g.base_dir + '/data/prefixes/INSTALL'
        g.shortcuts_dir = g.base_dir + '/shortcuts'
        g.games_dir = g.base_dir + '/games'

Castro_Fidel's avatar
Castro_Fidel committed
50 51 52 53
        loc_path = Path(g.base_dir + '/data/tmp/PortProton_loc')
        if loc_path.exists():
            g.locale = loc_path.read_text().strip()

fidel's avatar
fidel committed
54 55 56 57 58 59 60 61
        Path(g.shortcuts_dir).mkdir(parents=True, exist_ok=True)
        Path(g.games_dir).mkdir(parents=True, exist_ok=True)

        sep = QFrame(self)
        sep.setFrameShape(QFrame.Shape.VLine)
        sep.setFrameShadow(QFrame.Shadow.Sunken)
        self._status_size = QLabel(self)
        self._status_dir = QLabel(self)
Mikhail Tergoev's avatar
Mikhail Tergoev committed
62
        self._status_wine = QLabel(self)
fidel's avatar
fidel committed
63 64
        self.statusBar().setVisible(False)
        self.statusBar().addWidget(self._status_dir, 1)
Mikhail Tergoev's avatar
Mikhail Tergoev committed
65
        self.statusBar().addWidget(self._status_wine)
fidel's avatar
fidel committed
66 67 68 69 70 71 72 73 74 75 76
        self.statusBar().addWidget(sep)
        self.statusBar().addWidget(self._status_size)


        self.game_list = GameList(self)
        self.setCentralWidget(self.game_list)

        self.toolbar = self.addToolBar('Main')
        self.toolbar.setIconSize(QSize(32, 32))
        self.toolbar.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon)
        self.toolbar.setMovable(False)
Castro_Fidel's avatar
Castro_Fidel committed
77
        action = QAction(self.style().standardIcon(QStyle.StandardPixmap.SP_FileDialogNewFolder), _tr('Install new game'), self)
fidel's avatar
fidel committed
78 79
        action.triggered.connect(self.install_game)
        self.toolbar.addAction(action)
Castro_Fidel's avatar
Castro_Fidel committed
80
        action = QAction(self.style().standardIcon(QStyle.StandardPixmap.SP_FileLinkIcon), _tr('Add game entry'), self)
fidel's avatar
fidel committed
81 82
        action.triggered.connect(self.add_game)
        self.toolbar.addAction(action)
Castro_Fidel's avatar
Castro_Fidel committed
83
        action = QAction(self.style().standardIcon(QStyle.StandardPixmap.SP_BrowserReload), _tr('Reload list'), self)
fidel's avatar
fidel committed
84 85
        action.triggered.connect(self.reload_list)
        self.toolbar.addAction(action)
Castro_Fidel's avatar
Castro_Fidel committed
86
        action = QAction(self.style().standardIcon(QStyle.StandardPixmap.SP_TrashIcon), _tr('Drop install prefix'), self)
fidel's avatar
fidel committed
87 88 89 90 91
        action.triggered.connect(self.drop_prefix)
        self.toolbar.addAction(action)
        spacer = QWidget(self)
        spacer.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Preferred)
        self.toolbar.addWidget(spacer)
Mikhail Tergoev's avatar
Mikhail Tergoev committed
92
        action = QAction(pp_icon, 'PortProton', self)
fidel's avatar
fidel committed
93 94 95 96 97 98 99 100 101 102 103 104 105
        action.triggered.connect(self.run_pp)
        self.toolbar.addAction(action)

    def install_game(self):
        InstallGame(self)

    def add_game(self):
        InstallGame(self, False)

    def reload_list(self):
        self.game_list.reload()

    def drop_prefix(self):
Mikhail Tergoev's avatar
Mikhail Tergoev committed
106
        res = QMessageBox.question(self, _tr('Are you sure ?'), _tr('Do you really want to remove<br/><b>{0}</b> ?', g.install_pfx))
fidel's avatar
fidel committed
107 108 109 110 111 112 113 114 115 116 117 118 119 120
        if res == QMessageBox.StandardButton.Yes:
            shutil.rmtree(g.install_pfx, True)

    def run_pp(self):
        self.setDisabled(True)
        app.processEvents()
        run([g.scripts_dir + '/start.sh'])
        self.setDisabled(False)

    def set_status(self, item):
        self.statusBar().setVisible(bool(item))
        if item:
            self._status_size.setText('Size: ' + item.dir_size_human)
            self._status_dir.setText(' ' + item.game_dir)
Mikhail Tergoev's avatar
Mikhail Tergoev committed
121
            self._status_wine.setText(item.wine_use)
fidel's avatar
fidel committed
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157

    def closeEvent(self, event):
        geometry = self.saveGeometry()
        settings.setValue('geometry_main', geometry)
        super().closeEvent(event)

class LoadListThread(QThread):
    completed = pyqtSignal(list)
    def __init__(self, parent, install_dir):
        super().__init__(parent)
        self.install_dir = install_dir
    def run(self):
        exe_list = list(Path(self.install_dir).glob('**/*.exe'))
        self.completed.emit(exe_list)

class InstallGame(QDialog):
    def __init__(self, parent, installing=True):
        super().__init__(parent)
        self._installing = installing
        self.install_dir = g.install_pfx + '/drive_c/Games' if installing else g.games_dir
        self._exe_list_widget = QListWidget(self)
        self._exe_list_widget.setIconSize(QSize(16, 16))
        self._exe_list_widget.itemDoubleClicked.connect(self._handleDoubleClick)
        layout = QVBoxLayout()
        layout.addWidget(self._exe_list_widget)

        self._pbar = QProgressBar(self)
        self._pbar.setMaximum(0)
        layout.addWidget(self._pbar)
        thread = LoadListThread(self, self.install_dir)
        thread.completed.connect(self.load)
        thread.start()

        if self._installing:
            setup_btn = QPushButton(self)
            setup_btn.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_FileDialogStart))
Castro_Fidel's avatar
Castro_Fidel committed
158
            setup_btn.setText(_tr('Run another setup'))
fidel's avatar
fidel committed
159 160 161 162 163
            setup_btn.clicked.connect(self._runSetup)
            layout.addWidget(setup_btn)
        self.setLayout(layout)
        self.resize(400, 300)
        self.setModal(True)
Castro_Fidel's avatar
Castro_Fidel committed
164
        self.setWindowTitle(_tr('Select game exe file'))
fidel's avatar
fidel committed
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
        geometry = settings.value('geometry_install')
        if geometry:
            self.restoreGeometry(geometry)
        self.show()

    def load(self, exe_list):
        if self._installing and len(exe_list) == 0:
            self._runSetup()
            exe_list = list(Path(self.install_dir).glob('**/*.exe'))
        if len(exe_list) == 0:
            return self.close()
        def render_list():
            pixmap = QPixmap(16, 16)
            pixmap.fill(Qt.GlobalColor.transparent)
            empty_icon = QIcon(pixmap)
            for exe in sorted(exe_list):
                ico_file = str(exe) + '.ico'
                item = QListWidgetItem(self._exe_list_widget)
                item.setText(str(exe)[len(self.install_dir)+1:])
                try:
                    if not Path(ico_file).exists():
                        run(['wrestool', '-x', '-t14', '-o', ico_file, exe], capture_output=True)
                    item.setIcon(QIcon(ico_file))
                except Exception:
                    pass
                if item.icon().pixmap(16, 16).isNull():
                    item.setIcon(empty_icon)
                self._exe_list_widget.addItem(item)
            self._pbar.setVisible(False)
        thread = QThread(self)
        thread.run = render_list
        thread.start()

    def _runSetup(self):
        downloads_dir = QStandardPaths.writableLocation(QStandardPaths.StandardLocation.DownloadLocation)
Castro_Fidel's avatar
Castro_Fidel committed
200
        exe_file, _ = QFileDialog.getOpenFileName(self, caption=_tr('Choose setup file'), filter='Exe files (*.exe)', directory=downloads_dir)
fidel's avatar
fidel committed
201 202 203 204 205 206
        if not exe_file:
            return
        ppdb = shlex.quote(exe_file + '.ppdb')
        script = f"""
            mkdir -p {shlex.quote(g.install_pfx + '/drive_c/Games')}
            echo '
castro-fidel's avatar
castro-fidel committed
207 208 209 210
                export PW_VULKAN_USE=1
                export PW_GUI_DISABLED_CS=1
                export PW_PREFIX_NAME=INSTALL
                export PW_DLL_INSTALL=mfc42
fidel's avatar
fidel committed
211 212 213 214 215 216 217 218 219 220 221 222
            ' > {ppdb}
            {shlex.quote(g.scripts_dir + '/start.sh')} {shlex.quote(exe_file)}
            rm -f {ppdb}
        """
        self.setDisabled(True)
        app.processEvents()
        run(['bash', '-c', script])
        self.setDisabled(False)

    def _handleDoubleClick(self, item):
        game_dir = item.text().split('/')[0]
        dlg = QInputDialog(self)
Castro_Fidel's avatar
Castro_Fidel committed
223 224
        dlg.setWindowTitle(_tr('Please enter game entry name'))
        dlg.setLabelText(_tr('New game entry'))
fidel's avatar
fidel committed
225 226 227 228 229 230 231 232 233
        dlg.setTextValue(game_dir)
        dlg.resize(300, 0)
        ok = dlg.exec()
        shortcut_name = dlg.textValue()
        if not ok or not shortcut_name:
            return
        file_name = re.sub(r'[<>:/\\|?*]', '_', shortcut_name)
        shortcut = f"{g.shortcuts_dir}/{file_name}.desktop"
        if Path(shortcut).exists():
Castro_Fidel's avatar
Castro_Fidel committed
234
            res = QMessageBox.question(self, _tr('Shortcut already exists'), _tr('Shortcut <b>{0}</b> already exists. Overwrite ?', file_name))
fidel's avatar
fidel committed
235 236 237 238 239
            if res != QMessageBox.StandardButton.Yes:
                return
        src_dir = self.install_dir + '/' + game_dir
        dst_dir = g.games_dir + '/' + game_dir
        exe_file = shlex.quote(g.games_dir + '/' + item.text())
Mikhail Tergoev's avatar
Mikhail Tergoev committed
240
        ppdb = shlex.quote(g.games_dir + '/' + item.text() + '.ppdb')
fidel's avatar
fidel committed
241 242
        self.setDisabled(True)
        if self._installing and Path(dst_dir).exists():
Castro_Fidel's avatar
Castro_Fidel committed
243
            res = QMessageBox.question(self, _tr('Dir already exists'), _tr('Dir <b>{0}</b> already exists. Overwrite ?', game_dir))
fidel's avatar
fidel committed
244 245 246 247 248 249 250 251 252
            if res != QMessageBox.StandardButton.Yes:
                return
        if self._installing:
            os.rename(src_dir, dst_dir)
        script = f"""
            export INSTALLING_PORT=1
            export portwine_exe={exe_file}
            cd {shlex.quote(g.scripts_dir)}
            . {shlex.quote(g.scripts_dir + '/runlib')}
castro-fidel's avatar
castro-fidel committed
253
            pw_init_db
fidel's avatar
fidel committed
254
            [ -f {ppdb} ] && . {ppdb}
castro-fidel's avatar
castro-fidel committed
255
            echo -e "export PW_VULKAN_USE=${{PW_VULKAN_USE:-1}}\nexport PW_GUI_DISABLED_CS=1" >> {ppdb}
fidel's avatar
fidel committed
256 257
        """
        run(['bash', '-c', script])
Mikhail Tergoev's avatar
Mikhail Tergoev committed
258
        icon_path = g.games_dir + '/' + item.text() + '.ico'
fidel's avatar
fidel committed
259
        if not Path(icon_path).exists():
Mikhail Tergoev's avatar
Mikhail Tergoev committed
260
            icon_path = g.pp_icon
fidel's avatar
fidel committed
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
        Path(shortcut).write_text(f"""[Desktop Entry]
Name={shortcut_name}
Exec=env {shlex.quote(g.scripts_dir + '/start.sh')} {exe_file}
Type=Application
Categories=Game
StartupNotify=true
Path={shlex.quote(g.scripts_dir)}
Icon={icon_path}
""", encoding='utf-8')
        os.chmod(shortcut, 0o755)
        win.reload_list()
        self.close()

    def closeEvent(self, event):
        geometry = self.saveGeometry()
        settings.setValue('geometry_install', geometry)
        super().closeEvent(event)


class GameList(QListWidget):
    def __init__(self, parent):
        super().__init__(parent)
        self.itemActivated.connect(self.runGame)
        self.currentItemChanged.connect(self.selectItem)
        self.setViewMode(QListWidget.ViewMode.IconMode)
        self.setResizeMode(QListWidget.ResizeMode.Adjust)
        self.setIconSize(QSize(64, 64))
        self.setWordWrap(True)
        self.setSpacing(3)
        self.reload()

    def reload(self):
        self.clear()
        shortcuts = list(Path(g.shortcuts_dir).glob('*.desktop'))
Castro_Fidel's avatar
Castro_Fidel committed
295
        shortcuts += list(Path(g.base_dir).glob('*.desktop'))
fidel's avatar
fidel committed
296
        for shortcut in shortcuts:
fidel's avatar
fidel committed
297
            try:
Castro_Fidel's avatar
Castro_Fidel committed
298 299
                item = GameItem(self, shortcut)
                self.addItem(item)
Mikhail Tergoev's avatar
Mikhail Tergoev committed
300
            except ValueError:
fidel's avatar
fidel committed
301
                pass
Mikhail Tergoev's avatar
Mikhail Tergoev committed
302 303
            except:
                logging.exception('Error while parse "%s"', shortcut)
fidel's avatar
fidel committed
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
        self.sortItems()
        self.setCurrentIndex(QModelIndex())

    def runGame(self, item):
        win.setDisabled(True)
        app.processEvents()
        run(['bash', '-c', item.get('Exec')])
        win.setDisabled(False)

    def selectItem(self, item):
        win.set_status(item)

    def contextMenuEvent(self, event):
        selected = self.selectedItems()
        if len(selected) == 0:
            return
        selected = selected[0]
        menu = QMenu(self)
Castro_Fidel's avatar
Castro_Fidel committed
322 323
        desktop = menu.addAction(self.style().standardIcon(QStyle.StandardPixmap.SP_DesktopIcon), _tr('Add to desktop'))
        restore_gui = menu.addAction(self.style().standardIcon(QStyle.StandardPixmap.SP_DialogResetButton), _tr('Restore PortProton GUI'))
Mikhail Tergoev's avatar
Mikhail Tergoev committed
324
        default_wine = menu.addAction(self.style().standardIcon(QStyle.StandardPixmap.SP_DialogOkButton), _tr('Set default wine'))
Castro_Fidel's avatar
Castro_Fidel committed
325 326
        remove = menu.addAction(self.style().standardIcon(QStyle.StandardPixmap.SP_TrashIcon), _tr('Remove game entry'))
        uninstall = menu.addAction(self.style().standardIcon(QStyle.StandardPixmap.SP_DialogCloseButton), _tr('Uninstall game'))
Mikhail Tergoev's avatar
Mikhail Tergoev committed
327 328 329 330
        if not selected.pp_gui_disabled:
            restore_gui.setVisible(False)
        if not selected.wine_use:
            default_wine.setVisible(False)
fidel's avatar
fidel committed
331 332 333 334 335 336
        if not selected.game_dir.startswith(g.games_dir):
            uninstall.setVisible(False)
        action = menu.exec(self.mapToGlobal(event.pos()))
        desktop_shortcut = QStandardPaths.writableLocation(QStandardPaths.StandardLocation.DesktopLocation) + '/' + Path(selected.desktop_file).name
        if action == desktop:
            if Path(desktop_shortcut).exists():
Castro_Fidel's avatar
Castro_Fidel committed
337
                res = QMessageBox.question(self, _tr('Shortcut already exists'), _tr('Shortcut <b>{0}</b> already exists. Overwrite ?', desktop_shortcut))
fidel's avatar
fidel committed
338 339 340
                if res != QMessageBox.StandardButton.Yes:
                    return
            shutil.copy(selected.desktop_file, desktop_shortcut)
Mikhail Tergoev's avatar
Mikhail Tergoev committed
341 342
        if action == restore_gui or action == default_wine:
            ignore_line = 'PW_GUI_DISABLED_CS' if action == restore_gui else 'PW_WINE_USE'
fidel's avatar
fidel committed
343 344 345 346 347 348
            ppdb = shlex.split(selected.get('Exec'))[-1] + '.ppdb'
            if not Path(ppdb).exists():
                return
            with open(ppdb, 'r') as read:
                with open(ppdb + '.new', 'w') as write:
                    while (line := read.readline()):
Mikhail Tergoev's avatar
Mikhail Tergoev committed
349
                        if ignore_line not in line:
fidel's avatar
fidel committed
350 351
                            write.write(line)
            os.rename(ppdb + '.new', ppdb)
Mikhail Tergoev's avatar
Mikhail Tergoev committed
352 353 354 355 356 357
            if action == restore_gui:
                selected.pp_gui_disabled = False
            if action == default_wine:
                selected.wine_use = None
                self.selectItem(selected)
        def remove_shortcut():
fidel's avatar
fidel committed
358 359
            Path(desktop_shortcut).unlink(True)
            Path(selected.desktop_file).unlink(True)
Mikhail Tergoev's avatar
Mikhail Tergoev committed
360 361 362 363
            def_icon_path = g.base_dir + '/data/img/' + Path(shlex.split(selected.get('Exec'))[-1]).stem + '.png'
            Path(def_icon_path).unlink(True)
        if action == remove:
            remove_shortcut()
fidel's avatar
fidel committed
364 365 366
            self.reload()
        if action == uninstall:
            res = QMessageBox.question(self,
Mikhail Tergoev's avatar
Mikhail Tergoev committed
367
                _tr('Are you sure ?'),
Castro_Fidel's avatar
Castro_Fidel committed
368
                _tr('Do you really want to uninstall <b>{0}</b><br/>located in "<b>{1}</b>" ?', selected.get('Name'), selected.game_dir)
fidel's avatar
fidel committed
369 370 371
            )
            if res != QMessageBox.StandardButton.Yes:
                return
Mikhail Tergoev's avatar
Mikhail Tergoev committed
372
            remove_shortcut()
fidel's avatar
fidel committed
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
            if selected.game_dir.startswith(g.games_dir):
                shutil.rmtree(selected.game_dir, True)
            self.reload()


def human_size(num):
    if not num:
        return "-"
    for unit in ["", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"]:
        if abs(num) < 1024.0:
            return f"{num:.2f} {unit}B"
        num /= 1024.0
    return f"{num:.2f} YiB"

class GameItem(QListWidgetItem):
    def __init__(self, parent, desktop_file):
        self.desktop_file = desktop_file
fidel's avatar
fidel committed
390
        self.config = RawConfigParser()
fidel's avatar
fidel committed
391 392
        self.config.read(desktop_file)
        text = self.get('Name', Path(desktop_file).stem)
fidel's avatar
fidel committed
393
        if not self.get('Exec') or text == 'PortProton':
Mikhail Tergoev's avatar
Mikhail Tergoev committed
394 395 396 397
            raise ValueError('Validation fail')
        exe_file = shlex.split(self.get('Exec'))[-1]
        if exe_file.startswith(g.games_dir):
            self.game_dir = g.games_dir + '/' + exe_file[len(g.games_dir)+1:].split('/')[0]
fidel's avatar
fidel committed
398
        else:
Mikhail Tergoev's avatar
Mikhail Tergoev committed
399
            self.game_dir = str(Path(exe_file).parent)
fidel's avatar
fidel committed
400
        if self.game_dir == '.':
Mikhail Tergoev's avatar
Mikhail Tergoev committed
401 402 403 404 405 406 407 408 409 410 411 412 413
            raise ValueError('Can not determine game dir')
        self.pp_gui_disabled = False
        self.wine_use = None
        ppdb = exe_file + '.ppdb'
        if Path(ppdb).exists():
            ppdb_conf = RawConfigParser(strict=False)
            with open(ppdb) as f:
                ppdb_conf.read_string('[dummy]\n' + f.read())
            pp_gui_disabled = ppdb_conf.get('dummy', 'export PW_GUI_DISABLED_CS', fallback='').strip('"')
            try: self.pp_gui_disabled = bool(int(pp_gui_disabled))
            except: self.pp_gui_disabled = bool(pp_gui_disabled)
            self.wine_use = ppdb_conf.get('dummy', 'export PW_WINE_USE', fallback='').strip('"')

fidel's avatar
fidel committed
414 415
        super().__init__(parent)

fidel's avatar
fidel committed
416 417
        self.setToolTip(text)
        self.setText(text)
Mikhail Tergoev's avatar
Mikhail Tergoev committed
418
        icon_path = self.get('Icon') if Path(self.get('Icon')).exists() else g.pp_icon
fidel's avatar
fidel committed
419 420 421 422
        qicon = QIcon(icon_path)
        self.setIcon(qicon)
        self.setTextAlignment(Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignTop)
        self.setSizeHint(QSize(100, 105))
fidel's avatar
fidel committed
423

fidel's avatar
fidel committed
424 425 426 427 428 429 430 431
        self._set_dir_size(None)
        dir_size_cache = self.game_dir + '/.size'
        if Path(dir_size_cache).exists():
            self._set_dir_size(int(Path(dir_size_cache).read_text()))
        else:
            def calc_dir_size():
                if not Path(self.game_dir).exists():
                    return
fidel's avatar
fidel committed
432
                dir_size = sum(p.stat(follow_symlinks=False).st_size for p in Path(self.game_dir).rglob('*'))
fidel's avatar
fidel committed
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
                self._set_dir_size(dir_size)
                Path(dir_size_cache).write_text(str(dir_size))
            thread = QThread(parent)
            thread.run = calc_dir_size
            thread.start()

    def get(self, name, fallback=None):
        return self.config.get('Desktop Entry', name, fallback=fallback)

    def _set_dir_size(self, size):
        self.dir_size = size
        self.dir_size_human = human_size(size)

import signal
signal.signal(signal.SIGINT, signal.SIG_DFL)

Castro_Fidel's avatar
Castro_Fidel committed
449 450 451 452 453 454
lang = {
    'RUS': {
        'Install new game': 'Установить игру',
        'Add game entry': 'Добавить в список',
        'Reload list': 'Обновить список',
        'Drop install prefix': 'Удалить установочный префикс',
Mikhail Tergoev's avatar
Mikhail Tergoev committed
455
        'Are you sure ?': 'Вы уверены ?',
Castro_Fidel's avatar
Castro_Fidel committed
456 457 458 459 460 461 462 463 464 465 466 467
        'Do you really want to remove<br/><b>{0}</b> ?': 'Вы действительно хотите удалить<br/><b>{0}</b> ?',
        'Run another setup': 'Запустить установку',
        'Select game exe file': 'Выберите exe файл игры',
        'Choose setup file': 'Выберите установочный файл',
        'Please enter game entry name': 'Введите название игры',
        'New game entry': 'Название игры',
        'Shortcut already exists': 'Ярлык уже существует',
        'Shortcut <b>{0}</b> already exists. Overwrite ?': 'Ярлык <b>{0}</b> уже существует. Перезаписать ?',
        'Dir already exists': 'Директория уже существует',
        'Dir <b>{0}</b> already exists. Overwrite ?': 'Директория <b>{0}</b> уже существует. Перезаписать ?',
        'Add to desktop': 'Добавить на рабочий стол',
        'Restore PortProton GUI': 'Восстановить PortProton GUI',
Mikhail Tergoev's avatar
Mikhail Tergoev committed
468
        'Set default wine': 'Выбрать дефолтный wine',
Castro_Fidel's avatar
Castro_Fidel committed
469 470 471 472 473 474 475 476 477 478 479
        'Remove game entry': 'Убрать из списка',
        'Uninstall game': 'Удалить игру',
        'Do you really want to uninstall <b>{0}</b><br/>located in "<b>{1}</b>" ?': 'Вы действительно хотите удалить <b>{0}</b><br/>расположеную в "<b>{1}</b>" ?'
    }
}
def _tr(text, *fmt):
    res = lang.get(g.locale, {}).get(text, text)
    if fmt:
        res = res.format(*fmt)
    return res

fidel's avatar
fidel committed
480
app = QApplication([])
Mikhail Tergoev's avatar
Mikhail Tergoev committed
481
app.setDesktopFileName('PortProton')
fidel's avatar
fidel committed
482 483 484
win = MainWindow()
win.show()
app.exec()