Beispiel #1
0
def main():
    if not os.getenv('PYTHONUNBUFFERED'):
        os.environ['PYTHONUNBUFFERED'] = '1'

    urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

    args = app_args.read()

    logger = logs.new_logger(__app_name__, bool(args.logs))

    local_config = config.read_config(update_file=True)

    if local_config['ui']['auto_scale']:
        os.environ['QT_AUTO_SCREEN_SCALE_FACTOR'] = '1'
        logger.info("Auto screen scale factor activated")

    if local_config['ui']['hdpi']:
        logger.info("HDPI settings activated")
        QCoreApplication.setAttribute(Qt.AA_UseHighDpiPixmaps)
        QCoreApplication.setAttribute(Qt.AA_EnableHighDpiScaling)

    i18n_key, current_i18n = translation.get_locale_keys(
        local_config['locale'])
    default_i18n = translation.get_locale_keys(
        DEFAULT_I18N_KEY)[1] if i18n_key != DEFAULT_I18N_KEY else {}
    i18n = I18n(i18n_key, current_i18n, DEFAULT_I18N_KEY, default_i18n)

    cache_cleaner = CacheCleaner()
    cache_factory = DefaultMemoryCacheFactory(expiration_time=int(
        local_config['memory_cache']['data_expiration']),
                                              cleaner=cache_cleaner)
    icon_cache = cache_factory.new(
        int(local_config['memory_cache']['icon_expiration']))

    http_client = HttpClient(logger)

    context = ApplicationContext(
        i18n=i18n,
        http_client=http_client,
        disk_cache=bool(local_config['disk_cache']['enabled']),
        download_icons=bool(local_config['download']['icons']),
        app_root_dir=ROOT_DIR,
        cache_factory=cache_factory,
        disk_loader_factory=DefaultDiskCacheLoaderFactory(
            disk_cache_enabled=bool(local_config['disk_cache']['enabled']),
            logger=logger),
        logger=logger,
        distro=util.get_distro(),
        file_downloader=AdaptableFileDownloader(
            logger, bool(local_config['download']['multithreaded']), i18n,
            http_client),
        app_name=__app_name__)

    managers = gems.load_managers(context=context,
                                  locale=i18n_key,
                                  config=local_config,
                                  default_locale=DEFAULT_I18N_KEY)

    if args.reset:
        util.clean_app_files(managers)
        exit(0)

    manager = GenericSoftwareManager(managers,
                                     context=context,
                                     config=local_config)
    manager.prepare()

    app = QApplication(sys.argv)
    app.setQuitOnLastWindowClosed(
        False
    )  # otherwise windows opened through the tray icon kill the aplication when closed
    app.setApplicationName(__app_name__)
    app.setApplicationVersion(__version__)
    app_icon = util.get_default_icon()[1]
    app.setWindowIcon(app_icon)

    if local_config['ui']['style']:
        app.setStyle(str(local_config['ui']['style']))
    else:
        if app.style().objectName().lower() not in {'fusion', 'breeze'}:
            app.setStyle('Fusion')

    manage_window = ManageWindow(i18n=i18n,
                                 manager=manager,
                                 icon_cache=icon_cache,
                                 screen_size=app.primaryScreen().size(),
                                 config=local_config,
                                 context=context,
                                 http_client=http_client,
                                 icon=app_icon,
                                 logger=logger)

    if args.tray:
        tray_icon = TrayIcon(i18n=i18n,
                             manager=manager,
                             manage_window=manage_window,
                             screen_size=app.primaryScreen().size(),
                             config=local_config)
        manage_window.set_tray_icon(tray_icon)
        tray_icon.show()

        if args.show_panel:
            tray_icon.show_manage_window()
    else:
        manage_window.refresh_apps()
        manage_window.show()

    cache_cleaner.start()
    Thread(target=config.remove_old_config, args=(logger, ),
           daemon=True).start()
    sys.exit(app.exec_())
Beispiel #2
0
def get_type_label(type_: str, gem: str, i18n: I18n) -> str:
    type_label = 'gem.{}.type.{}.label'.format(gem, type_.lower())
    return i18n.get(type_label, type_.capitalize()).strip()
Beispiel #3
0
    def __init__(self,
                 window: QWidget,
                 manager: GenericSoftwareManager,
                 i18n: I18n,
                 config: dict,
                 show_panel_after_restart: bool = False):
        super(GemSelectorPanel, self).__init__()
        self.window = window
        self.manager = manager
        self.config = config
        self.setLayout(QGridLayout())
        self.setWindowIcon(QIcon(resource.get_path('img/logo.svg')))
        self.setWindowTitle(i18n['gem_selector.title'])
        self.resize(400, 400)
        self.show_panel_after_restart = show_panel_after_restart

        self.label_question = QLabel(i18n['gem_selector.question'])
        self.label_question.setStyleSheet('QLabel { font-weight: bold}')
        self.layout().addWidget(self.label_question, 0, 1, Qt.AlignHCenter)

        self.bt_proceed = QPushButton(i18n['change'].capitalize())
        self.bt_proceed.setStyleSheet(css.OK_BUTTON)
        self.bt_proceed.clicked.connect(self.save)

        self.bt_exit = QPushButton(i18n['close'].capitalize())
        self.bt_exit.clicked.connect(self.exit)

        self.gem_map = {}
        gem_options = []
        default = set()

        managers = [*manager.managers]
        managers.sort(key=lambda c: c.__class__.__name__)

        for m in managers:
            if m.can_work():
                modname = m.__module__.split('.')[-2]
                op = InputOption(
                    label=i18n.get('gem.{}.label'.format(modname),
                                   modname.capitalize()),
                    tooltip=i18n.get('gem.{}.info'.format(modname)),
                    value=modname,
                    icon_path='{r}/gems/{n}/resources/img/{n}.svg'.format(
                        r=ROOT_DIR, n=modname))

                gem_options.append(op)
                self.gem_map[modname] = m

                if m.is_enabled() and m in manager.working_managers:
                    default.add(op)

        if self.config['gems']:
            default_ops = {
                o
                for o in gem_options if o.value in self.config['gems']
            }
        else:
            default_ops = default

        self.bt_proceed.setEnabled(bool(default_ops))

        self.gem_select_model = MultipleSelectComponent(
            label='',
            options=gem_options,
            default_options=default_ops,
            max_per_line=1)

        self.gem_select = MultipleSelectQt(self.gem_select_model,
                                           self.check_state)
        self.layout().addWidget(self.gem_select, 1, 1)

        self.layout().addWidget(new_spacer(), 2, 1)

        self.layout().addWidget(self.bt_proceed, 3, 1, Qt.AlignRight)
        self.layout().addWidget(self.bt_exit, 3, 1, Qt.AlignLeft)

        self.adjustSize()
        self.setFixedSize(self.size())
        qt_utils.centralize(self)
Beispiel #4
0
    def __init__(self, pkg_info: dict, icon_cache: MemoryCache, i18n: I18n,
                 screen_size: QSize):
        super(InfoDialog, self).__init__()
        self.setWindowTitle(str(pkg_info['__app__']))
        self.screen_size = screen_size
        self.i18n = i18n
        layout = QVBoxLayout()
        self.setLayout(layout)

        scroll = QScrollArea(self)
        scroll.setFrameShape(QFrame.NoFrame)
        scroll.setWidgetResizable(True)
        comps_container = QWidget()
        comps_container.setObjectName('root_container')
        comps_container.setLayout(QVBoxLayout())
        scroll.setWidget(comps_container)

        # shows complete field string
        self.text_field = QPlainTextEdit()
        self.text_field.setObjectName('full_field')
        self.text_field.setReadOnly(True)
        comps_container.layout().addWidget(self.text_field)
        self.text_field.hide()

        self.gbox_info = QGroupBox()
        self.gbox_info.setObjectName('fields')
        self.gbox_info.setLayout(QGridLayout())

        comps_container.layout().addWidget(self.gbox_info)

        # THERE ARE CRASHES WITH SOME RARE ICONS ( like insomnia ). IT CAN BE A QT BUG. IN THE MEANTIME, ONLY THE TYPE ICON WILL BE RENDERED
        #
        # icon_data = icon_cache.get(app['__app__'].model.icon_url)
        #
        # if icon_data and icon_data.get('icon'):
        #     self.setWindowIcon(icon_data.get('icon'))
        self.setWindowIcon(
            QIcon(pkg_info['__app__'].model.get_type_icon_path()))

        for idx, attr in enumerate(sorted(pkg_info.keys())):
            if attr not in IGNORED_ATTRS and pkg_info[attr]:
                i18n_key = pkg_info[
                    '__app__'].model.gem_name + '.info.' + attr.lower()

                if isinstance(pkg_info[attr], list):
                    val = ' '.join(
                        [str(e).strip() for e in pkg_info[attr] if e])
                    show_val = '\n'.join(
                        ['* ' + str(e).strip() for e in pkg_info[attr] if e])
                else:
                    val = str(pkg_info[attr]).strip()
                    show_val = val

                i18n_val = i18n.get('{}.{}'.format(i18n_key, val.lower()))

                if i18n_val:
                    val = i18n_val
                    show_val = val

                text = QLineEdit()
                text.setObjectName('field_value')
                text.setToolTip(show_val)
                text.setText(val)
                text.setCursorPosition(0)
                text.setReadOnly(True)

                label = QLabel(
                    i18n.get(i18n_key, i18n.get(attr.lower(),
                                                attr)).capitalize())
                label.setObjectName('field_name')

                self.gbox_info.layout().addWidget(label, idx, 0)
                self.gbox_info.layout().addWidget(text, idx, 1)
                self._gen_show_button(idx, show_val)

        layout.addWidget(scroll)

        lower_container = QWidget()
        lower_container.setObjectName('lower_container')
        lower_container.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        lower_container.setLayout(QHBoxLayout())

        self.bt_back = QPushButton('< {}'.format(
            self.i18n['back'].capitalize()))
        self.bt_back.setObjectName('back')
        self.bt_back.setVisible(False)
        self.bt_back.setCursor(QCursor(Qt.PointingHandCursor))
        self.bt_back.clicked.connect(self.back_to_info)

        lower_container.layout().addWidget(self.bt_back)
        lower_container.layout().addWidget(new_spacer())

        self.bt_close = QPushButton(self.i18n['close'].capitalize())
        self.bt_close.setObjectName('close')
        self.bt_close.setCursor(QCursor(Qt.PointingHandCursor))
        self.bt_close.clicked.connect(self.close)

        lower_container.layout().addWidget(self.bt_close)
        layout.addWidget(lower_container)
        self.setMinimumWidth(self.gbox_info.sizeHint().width() * 1.2)
        self.setMaximumHeight(screen_size.height() * 0.8)
        self.adjustSize()
Beispiel #5
0
def generate_i18n(app_config: dict, locale_dir: str) -> I18n:
    return I18n(*_gen_i18n_data(app_config, locale_dir))
Beispiel #6
0
    def __init__(self, history: PackageHistory, icon_cache: MemoryCache,
                 i18n: I18n):
        super(HistoryDialog, self).__init__()
        self.setWindowFlags(self.windowFlags() | Qt.WindowSystemMenuHint
                            | Qt.WindowMinMaxButtonsHint)

        view = PackageView(model=history.pkg, i18n=i18n)

        self.setWindowTitle('{} - {}'.format(i18n['popup.history.title'],
                                             view))

        layout = QVBoxLayout()
        self.setLayout(layout)

        table_history = QTableWidget()
        table_history.setFocusPolicy(Qt.NoFocus)
        table_history.setShowGrid(False)
        table_history.verticalHeader().setVisible(False)
        table_history.setAlternatingRowColors(True)

        table_history.setColumnCount(len(history.history[0]))
        table_history.setRowCount(len(history.history))
        table_history.setHorizontalHeaderLabels([
            i18n.get(history.pkg.get_type().lower() + '.history.' + key,
                     i18n.get(key, key)).capitalize()
            for key in sorted(history.history[0].keys())
        ])

        for row, data in enumerate(history.history):

            current_status = history.pkg_status_idx == row

            for col, key in enumerate(sorted(data.keys())):
                item = QTableWidgetItem()
                item.setText(str(data[key]))

                if current_status:
                    item.setBackground(
                        QColor('#ffbf00' if row != 0 else '#32CD32'))
                    tip = '{}. {}.'.format(
                        i18n['popup.history.selected.tooltip'],
                        i18n['version.{}'.format('updated' if row == 0 else
                                                 'outdated')].capitalize())

                    item.setToolTip(tip)

                table_history.setItem(row, col, item)

        layout.addWidget(table_history)

        header_horizontal = table_history.horizontalHeader()
        for i in range(0, table_history.columnCount()):
            header_horizontal.setSectionResizeMode(i, QHeaderView.Stretch)

        new_width = reduce(operator.add, [
            table_history.columnWidth(i)
            for i in range(table_history.columnCount())
        ])
        self.resize(new_width, table_history.height())

        # THERE ARE CRASHES WITH SOME RARE ICONS ( like insomnia ). IT CAN BE A QT BUG. IN THE MEANTIME, ONLY THE TYPE ICON WILL BE RENDERED
        #
        # icon_data = icon_cache.get(history.pkg.icon_url)
        # if icon_data and icon_data.get('icon'):
        #     self.setWindowIcon(icon_data.get('icon'))
        self.setWindowIcon(QIcon(history.pkg.get_type_icon_path()))
Beispiel #7
0
    def __init__(self, app: dict, icon_cache: MemoryCache, i18n: I18n, screen_size: QSize()):
        super(InfoDialog, self).__init__()
        self.setWindowTitle(str(app['__app__']))
        self.screen_size = screen_size
        self.i18n = i18n
        layout = QVBoxLayout()
        self.setLayout(layout)

        self.toolbar_field = QToolBar()
        self.bt_back = QPushButton(i18n['back'].capitalize())
        self.bt_back.clicked.connect(self.back_to_info)
        self.bt_back.setCursor(QCursor(Qt.PointingHandCursor))
        self.toolbar_field.addWidget(self.bt_back)
        self.layout().addWidget(self.toolbar_field)
        self.toolbar_field.hide()

        # shows complete field string
        self.text_field = QPlainTextEdit()
        self.text_field.setReadOnly(True)
        self.layout().addWidget(self.text_field)
        self.text_field.hide()

        self.gbox_info = QGroupBox()
        self.gbox_info.setMaximumHeight(self.screen_size.height() - self.screen_size.height() * 0.1)
        self.gbox_info_layout = QGridLayout()
        self.gbox_info.setLayout(self.gbox_info_layout)

        layout.addWidget(self.gbox_info)

        # THERE ARE CRASHES WITH SOME RARE ICONS ( like insomnia ). IT CAN BE A QT BUG. IN THE MEANTIME, ONLY THE TYPE ICON WILL BE RENDERED
        #
        # icon_data = icon_cache.get(app['__app__'].model.icon_url)
        #
        # if icon_data and icon_data.get('icon'):
        #     self.setWindowIcon(icon_data.get('icon'))
        self.setWindowIcon(QIcon(app['__app__'].model.get_type_icon_path()))

        for idx, attr in enumerate(sorted(app.keys())):
            if attr not in IGNORED_ATTRS and app[attr]:
                i18n_key = app['__app__'].model.gem_name + '.info.' + attr.lower()

                if isinstance(app[attr], list):
                    val = ' '.join([str(e).strip() for e in app[attr] if e])
                    show_val = '\n'.join(['* ' + str(e).strip() for e in app[attr] if e])
                else:
                    val = str(app[attr]).strip()
                    show_val = val

                i18n_val = i18n.get('{}.{}'.format(i18n_key, val.lower()))

                if i18n_val:
                    val = i18n_val
                    show_val = val

                text = QLineEdit()
                text.setToolTip(show_val)
                text.setText(val)
                text.setCursorPosition(0)
                text.setStyleSheet("width: 400px")
                text.setReadOnly(True)

                label = QLabel(i18n.get(i18n_key, i18n.get(attr.lower(), attr)).capitalize())
                label.setStyleSheet("font-weight: bold")

                self.gbox_info_layout.addWidget(label, idx, 0)
                self.gbox_info_layout.addWidget(text, idx, 1)
                self._gen_show_button(idx, show_val)

        self.adjustSize()