Пример #1
0
def main_app(base_path, file, file_config):
    """Run the GUI of xBan

    The function initiates and resize the application
    """
    app = QApplication(sys.argv)

    if hasattr(QStyleFactory, "AA_UseHighDpiPixmaps"):
        app.setAttribute(Qt.AA_UseHighDpiPixmaps)

    with open(os.path.join(base_path, "xBanStyle.css"), "r") as style_sheet:
        style = style_sheet.read()

    app.setWindowIcon(QIcon(os.path.join(base_path, "xBanUI.png")))
    xBanApp = xBanWindow(base_path, file, file_config)

    xBanApp.setStyleSheet(style)

    # resize and move screen to center

    primary_screen = QGuiApplication.primaryScreen()
    if primary_screen:
        screen_size = primary_screen.availableSize()

        xBanApp.resize(screen_size.width() / 3, screen_size.height() / 2)
        xBanApp.move(
            (screen_size.width() - xBanApp.width()) / 2,
            (screen_size.height() - xBanApp.height()) / 2,
        )

        app.setStyle("Fusion")
        sys.exit(app.exec_())

    else:
        main_logger.error("Primary screen not found")
Пример #2
0
def main():
    mp.set_start_method("spawn", force=True)  # required for Linux
    app_name = "MNELAB"
    if sys.platform.startswith("darwin"):
        # set bundle name on macOS (app name shown in the menu bar)
        from Foundation import NSBundle
        bundle = NSBundle.mainBundle()
        info = bundle.localizedInfoDictionary() or bundle.infoDictionary()
        info["CFBundleName"] = app_name

    matplotlib.use("QtAgg")
    app = QApplication(sys.argv)
    app.setApplicationName(app_name)
    app.setOrganizationName("cbrnr")
    if sys.platform.startswith("darwin"):
        app.setAttribute(Qt.ApplicationAttribute.AA_DontShowIconsInMenus, True)
    app.setAttribute(Qt.ApplicationAttribute.AA_UseHighDpiPixmaps)
    model = Model()
    model.view = MainWindow(model)
    if len(sys.argv) > 1:  # open files from command line arguments
        for f in sys.argv[1:]:
            model.load(f)
    model.view.show()
    sys.exit(app.exec())
Пример #3
0
    def getInputDir(self):
        dir = QFileDialog.getExistingDirectory(None, "Select folder",
                                               self.userDesktop)

        if dir:
            path = dir.replace("/", "\\")
            self.InputLineEdit.setText(path)

    def getOuputDir(self):
        dir = QFileDialog.getExistingDirectory(None,
                                               "Select save folder location",
                                               self.userDesktop)

        if dir:
            path = dir.replace("/", "\\")
            self.OutputLineEdit.setText(path)


if __name__ == "__main__":
    os.environ["QT_AUTO_SCREEN_SCALE_FACTOR"] = "1"  # For High DPI Displays
    app = QApplication(sys.argv)  # Create the Qt Application
    app.setAttribute(
        QtCore.Qt.AA_EnableHighDpiScaling)  # For High DPI Displays
    MainWindow = QMainWindow()

    # Create an instance
    ui = TheApp(MainWindow)

    # Show the window and start the app
    MainWindow.show()
    app.exec()
Пример #4
0
def main(gamePath: Optional[str] = None,
         configPath: Optional[str] = None,
         startupMode: StartupMode = StartupMode.Main) -> NoReturn:

    from w3modmanager.util.util import getRuntimePath
    from w3modmanager.core.model import Model
    from w3modmanager.core.errors import OtherInstanceError, InvalidGamePath, InvalidConfigPath
    from w3modmanager.ui.graphical.mainwindow import MainWindow
    from w3modmanager.domain.web.nexus import closeSession
    from w3modmanager.domain.system.permissions import \
        getWritePermissions, setWritePermissions

    from PySide6.QtCore import Qt, QSettings
    from PySide6.QtWidgets import QApplication, QMessageBox
    from PySide6.QtGui import QIcon, QPalette, QFont

    from qasync import QEventLoop

    QApplication.setOrganizationName(w3modmanager.ORG_NAME)
    QApplication.setOrganizationDomain(w3modmanager.ORG_URL)
    QApplication.setApplicationName(w3modmanager.TITLE)
    QApplication.setApplicationVersion(w3modmanager.VERSION)
    QApplication.setApplicationDisplayName('')
    QApplication.setAttribute(Qt.AA_NativeWindows)

    app = QApplication(sys.argv)
    app.setStyleSheet('''
        Link { text-decoration: none; }
    ''')

    eventloop = QEventLoop(app)
    asyncio.set_event_loop(eventloop)

    palette = QPalette(QApplication.palette())
    palette.setColor(QPalette.Link, Qt.red)
    palette.setColor(QPalette.LinkVisited, Qt.red)
    palette.setColor(QPalette.PlaceholderText, Qt.gray)
    app.setPalette(palette)

    font = QFont('Segoe UI')
    font.setStyleHint(QFont.System)
    font.setWeight(QFont.Normal)
    font.setStyleStrategy(QFont.PreferDevice)
    font.setPointSize(9)
    app.setFont(font)

    icon = QIcon()
    icon.addFile(str(getRuntimePath('resources/icons/w3b.ico')))
    app.setWindowIcon(icon)

    pool = ThreadPoolExecutor()
    asyncio.get_running_loop().set_default_executor(pool)

    # configure startup overrides
    settings = QSettings()
    if gamePath:
        settings.setValue('gamePath', gamePath)
    if configPath:
        settings.setValue('configPath', configPath)
    if startupMode == StartupMode.About:
        MainWindow.showAboutDialog(None).exec_()
        sys.exit()
    if startupMode == StartupMode.Settings:
        MainWindow.showSettingsDialog(None).exec_()
        sys.exit()

    exception_hook_set = False

    def createModel(ignorelock: bool = False) -> Model:
        nonlocal settings
        return Model(
            Path(str(settings.value('gamePath'))),
            Path(str(settings.value('configPath'))),
            Path(
                appdirs.user_data_dir(w3modmanager.NAME,
                                      w3modmanager.ORG_NAME)), ignorelock)

    try:
        # try to initialize the mod management model
        try:
            model = createModel()
        # if another instance is already open, inform and ask to open anyway
        except OtherInstanceError as e:
            if MainWindow.showOtherInstanceDialog(
                    None).exec_() == QMessageBox.Yes:
                model = createModel(True)
            else:
                raise e
        # if game path or config path is invalid or not set,
        # show a special settings dialog and retry
        except (InvalidGamePath, InvalidConfigPath):
            MainWindow.showSettingsDialog(None, True).exec_()
            model = createModel()

        # check for write access to the game and config directories
        for path in (
                model.gamepath,
                model.configpath,
                model.cachepath,
        ):
            if not getWritePermissions(path):
                if MainWindow.showInvalidPermissionsDialog(None, path).exec_() != QMessageBox.Yes \
                or not setWritePermissions(path):
                    raise PermissionError(f'Not enough permissions for {path}')

        window = MainWindow(model)
        app.setActiveWindow(window)

        def show_exception_hook(exctype, value, tb) -> None:  # noqa
            nonlocal window
            MainWindow.showCritcalErrorDialog(
                window, value,
                ''.join(traceback.format_exception(exctype, value,
                                                   tb))).exec_()
            exception_hook(exctype, value, tb)

        sys.excepthook = show_exception_hook
        exception_hook_set = True

        with eventloop:
            status = eventloop.run_forever()
            eventloop.run_until_complete(closeSession())
            sys.exit(status)

    except OtherInstanceError as e:
        sys.exit(f'error: {str(e)}')

    except (InvalidGamePath, InvalidConfigPath) as e:
        MainWindow.showInvalidConfigErrorDialog(None).exec_()
        sys.exit(f'error: {str(e)}')

    except PermissionError as e:
        MainWindow.showInvalidPermissionsErrorDialog(None).exec_()
        sys.exit(f'error: {str(e)}')

    except Exception as e:
        if not exception_hook_set:
            MainWindow.showCritcalErrorDialog(None, str(e)).exec_()
        raise e

    sys.exit()
Пример #5
0
        si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        x = subprocess.Popen([
            "powershell",
            f'try {{Get-AppxPackage {package_name} -OutVariable app | Remove-AppPackage -ea stop;[bool]$app}} catch {{$false}}'
        ],
                             stdin=subprocess.PIPE,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.STDOUT,
                             shell=False,
                             startupinfo=si)
        x.communicate()[0]
        self.signals.progress_signal.emit(self.i)


if __name__ == '__main__':
    QApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True)
    QApplication.setHighDpiScaleFactorRoundingPolicy(
        Qt.HighDpiScaleFactorRoundingPolicy.PassThrough)
    app = QApplication(sys.argv)
    app.setFont(QFont("Tahoma"))
    locale = QLocale()
    trans = QTranslator()
    if trans.load(locale, "", "", resource_path("Language"), ".qm"):
        app.installTranslator(trans)
    about = Ui_AboutWindow()
    about.setupUi()
    ui = Ui_MainWindow()
    ui.setupUi()
    ui.show()
    logic = Logic()
    sys.exit(app.exec_())
Пример #6
0
    QWidget,
    QWidgetItem,
)

import natsort  # type: ignore

from .. import core, iso639, models
from ..sources.base import Parser
from ..utils import CONFIG

from ..__version__ import __version__

from . import common, resources, template, utils

_app = QApplication([])
_app.setAttribute(Qt.AA_UseHighDpiPixmaps)

QStyle = _app.style()

LOGO = QPixmap(":/logo.jpg")

HOME = pathlib.Path.home()

CACHE = core.Cache()

T_ADD = "Add Manga"
T_DELETE = "Delete Manga"
T_DOWNLOAD = "Download Manga"

MANGA = {}
MANGA_LOCK = threading.Lock()
Пример #7
0
            
    def mouseReleaseEvent(self, QMouseEvent):
        self.m_flag = False
        self.setCursor(QtGui.QCursor(QtGui.Qt.ArrowCursor))

    def refresh_page1(self):
        self.ui.massterpw_entry.setText('')
    
    def refresh_page2(self):
        self.ui.masterpw2_entry.setText('')
        self.ui.confirmmasterpw2_entry.setText('')
    
    def refresh_page4(self):
        self.ui.username_entry.setText('')
        self.ui.pw_entry.setText('')
        self.ui.confrimpw_entry.setText('')
        self.ui.url_entry.setText('')

    def closeEvent(self, event):
        if self.filepath:
            directory = os.path.dirname(self.filepath)
            temp.writer(directory)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    app.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, True)
    window = SplashScreen()
    # window = MainApplication()
    window.show()

    sys.exit(app.exec())
Пример #8
0
def main():
    # if lock_file is existed , it means persepolis is still running!
    if lock_file_validation and (not (
        (args.parent_window or unknownargs) and browser_url == False) or
                                 ((args.parent_window or unknownargs)
                                  and start_persepolis_if_browser_executed)):

        # set QT_AUTO_SCREEN_SCALE_FACTOR to 1 for "high DPI displays"
        os.environ['QT_AUTO_SCREEN_SCALE_FACTOR'] = '1'

        # run mainwindow

        # set color_scheme and style
        # see palettes.py and setting.py

        # this line is added fot fixing persepolis view in HighDpi displays
        # more information at: https://doc.qt.io/qt-5/highdpi.html
        try:
            QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
        except:
            from persepolis.scripts import logger

            # write error_message in log file.
            logger.sendToLog('Qt.AA_EnableHighDpiScaling is not available!',
                             "ERROR")

        # create QApplication
        persepolis_download_manager = PersepolisApplication(sys.argv)

        # setQuitOnLastWindowClosed(False) is needed to prevent persepolis exiting,
        # when it's minimized in system tray.
        persepolis_download_manager.setQuitOnLastWindowClosed(False)

        # Enable High DPI display
        try:
            if hasattr(QStyleFactory, 'AA_UseHighDpiPixmaps'):
                persepolis_download_manager.setAttribute(
                    Qt.AA_UseHighDpiPixmaps)
        except:
            from persepolis.scripts import logger

            # write error_message in log file.
            logger.sendToLog('Qt.AA_UseHighDpiPixmaps is not available!',
                             "ERROR")

        # set organization name and domain and application name
        QCoreApplication.setOrganizationName('persepolis_download_manager')
        QCoreApplication.setApplicationName('persepolis')

        # Persepolis setting
        persepolis_download_manager.setting = QSettings()

        # get user's desired font and style , ... from setting
        custom_font = persepolis_download_manager.setting.value(
            'settings/custom-font')
        font = persepolis_download_manager.setting.value('settings/font')
        font_size = int(
            persepolis_download_manager.setting.value('settings/font-size'))
        style = persepolis_download_manager.setting.value('settings/style')
        color_scheme = persepolis_download_manager.setting.value(
            'settings/color-scheme')
        ui_direction = persepolis_download_manager.setting.value(
            'ui_direction')

        # set style
        persepolis_download_manager.setPersepolisStyle(style)

        # set font
        persepolis_download_manager.setPersepolisFont(font, font_size,
                                                      custom_font)

        # set color_scheme
        persepolis_download_manager.setPersepolisColorScheme(color_scheme)

        # set ui direction
        if ui_direction == 'rtl':
            persepolis_download_manager.setLayoutDirection(Qt.RightToLeft)

        elif ui_direction in 'ltr':
            persepolis_download_manager.setLayoutDirection(Qt.LeftToRight)

        # run mainwindow
        try:
            mainwindow = MainWindow(start_in_tray, persepolis_download_manager,
                                    persepolis_download_manager.setting)
            if start_in_tray:
                mainwindow.hide()
            else:
                mainwindow.show()

        except Exception:
            from persepolis.scripts import logger
            error_message = str(traceback.format_exc())

            # write error_message in log file.
            logger.sendToLog(error_message, "ERROR")

            # Reset persepolis
            error_window = ErrorWindow(error_message)
            error_window.show()

        sys.exit(persepolis_download_manager.exec_())

    elif not ((args.parent_window or unknownargs)):

        # this section warns user that program is still running and no need to run it again
        # and creating a file to notify mainwindow for showing itself!
        # (see CheckingThread in mainwindow.py for more information)
        if len(plugin_list) == 0:

            show_window_file = os.path.join(persepolis_tmp, 'show-window')
            f = open(show_window_file, 'w')
            f.close()

        sys.exit(0)