Ejemplo n.º 1
0
def main():
    # if sys.platform.startswith('darwin'):
    #     try:
    #         from Foundation import NSBundle # Method requires pyobj-c
    #         bundle = NSBundle.mainBundle()
    #         if bundle:
    #             # app_name = os.path.splitext(os.path.basename(sys.argv[0]))[0]
    #             app_info = bundle.localizedInfoDictionary() or bundle.infoDictionary()
    #             if app_info:
    #                 app_info['CFBundleName'] = "Fantasy Creator"
    #     except ImportError:
    #         pass
    # else:
    #     qtc.QCoreApplication.setApplicationName("Fantasy Creator")

    parser = QCommandLineParser()
    app = QApplication(sys.argv)
    # app.setApplicationName('Fantasy Creator')
    # app.setApplicationVersion('0.1')

    parser.setApplicationDescription('GUI to create fantastical stories!')
    parser.addPositionalArgument(
        "open", QCoreApplication.translate("main", "A file to open."))

    parser.process(app)
    args = parser.positionalArguments()

    #app.setStyle(qtw.QStyleFactory.create('Fusion'))
    mw = MainWindow(args)
    app.aboutToQuit.connect(mw.clean_up)
    sys.exit(app.exec())
Ejemplo n.º 2
0
 def parse_cmdline(self) -> None:
     self.parser = QCommandLineParser()
     self.parser.setApplicationDescription(
         '\nVidCutter - the simplest + fastest media cutter & joiner')
     self.parser.addPositionalArgument('video', 'Preload video file',
                                       '[video]')
     self.parser.addPositionalArgument(
         'project', 'Open VidCutter project file (.vcp)', '[project]')
     self.debug_option = QCommandLineOption(
         ['debug'], 'debug mode; verbose console output & logging. '
         'This will basically output what is being logged to file to the '
         'console stdout. Mainly useful for debugging problems with your '
         'system video and/or audio stack and codec configuration.')
     self.parser.addOption(self.debug_option)
     self.parser.addVersionOption()
     self.parser.addHelpOption()
     self.parser.process(qApp)
     self.args = self.parser.positionalArguments()
     if self.parser.isSet(self.debug_option):
         os.environ['DEBUG'] = '1'
     if len(self.args) > 0:
         file_path = QFileInfo(self.args[0]).absoluteFilePath()
         if not os.path.exists(file_path):
             sys.stderr.write('\nERROR: File not found: %s\n' % file_path)
             self.close()
             qApp.exit(1)
         self.video = file_path
Ejemplo n.º 3
0
    def run(self):

        self.app = QApplication(sys.argv)

        parser = QCommandLineParser()
        parser.addPositionalArgument('lbr', 'Library to open')
        parser.process(self.app)
        args = parser.positionalArguments()

        self.wnd = uic.loadUi('editor_window.ui')

        self.wnd.actionOpen_DB.triggered.connect(self.on_open)
        self.wnd.actionExit.triggered.connect(self.on_exit)

        self.wnd.devices.itemEntered.connect(self.on_device_data)
        self.wnd.devices.itemSelectionChanged.connect(self.on_devices_select)

        self.wnd.packages.itemSelectionChanged.connect(self.on_packages_select)

        self.wnd.tabWidget_2.currentChanged.connect(self.on_tab_select)

        # Open library if sent as argument
        if (len(args) > 0):
            self.open_file(args[0])

        self.wnd.show()
        sys.exit(self.app.exec_())
Ejemplo n.º 4
0
 def parse_cmdline(self) -> None:
     self.parser = QCommandLineParser()
     self.parser.setApplicationDescription('\nVidCutter - the simplest + fastest video cutter & joiner')
     self.parser.addPositionalArgument('video', 'Preload video file', '[video]')
     self.parser.addPositionalArgument('project', 'Open VidCutter project file (.vcp)', '[project]')
     self.debug_option = QCommandLineOption(['debug'], 'debug mode; verbose console output & logging. ' +
                                            'This will basically output what is being logged to file to the ' +
                                            'console stdout. Mainly useful for debugging problems with your ' +
                                            'system video and/or audio stack and codec configuration.')
     self.dev_option = QCommandLineOption(['dev'], 'developer mode; disables the use of compiled resource files ' +
                                          'so that all app resources & assets are accessed directly from the file ' +
                                          'system allowing you to see UI changes immediately. this typically ' +
                                          'relates to changes made to Qt stylesheets (.qss), layout/templates, ' +
                                          'content includes and images. basically all assets defined in .qrc ' +
                                          'files throughout the codebase.')
     self.parser.addOption(self.debug_option)
     self.parser.addOption(self.dev_option)
     self.parser.addVersionOption()
     self.parser.addHelpOption()
     self.parser.process(qApp)
     self.args = self.parser.positionalArguments()
     if self.parser.isSet(self.debug_option):
         os.environ['DEBUG'] = '1'
     if self.parser.isSet(self.dev_option):
         self.devmode = True
     if len(self.args) > 0:
         file_path = QFileInfo(self.args[0]).absoluteFilePath()
         if not os.path.exists(file_path):
             sys.stderr.write('\nERROR: File not found: %s\n' % file_path)
             self.close()
             sys.exit(1)
         self.video = file_path
def runmain():
    import sys

    app = QApplication(sys.argv)

    cmdParser = QCommandLineParser()
    cmdParser.setApplicationDescription(
        'Room file merger utility script for Basement Renovator. Takes a config file and feeds it to the cli roommerger script'
    )
    cmdParser.addHelpOption()

    cmdParser.addPositionalArgument(
        'configFile',
        '''json config file to grab configuration from; sets current working directory to its directory. Format:
    {
        files: [
            {
                outputFile: path to file to output,
                paths: [ path to file/folder to replace, ... ],
                skipSTB: optional, true to skip generating the stb,
                noRecomputeIds: optional, true to skip recompute room ids,
                startingId: starting room id to recompute from
            }...
        ]
    }
    ''')

    fileEditedOpt = QCommandLineOption(
        'fileEdited',
        'optional file to limit which rooms get merged from the config',
        'file')
    cmdParser.addOption(fileEditedOpt)

    cmdParser.process(app)

    configArg = cmdParser.positionalArguments()[0]
    configPath = Path(configArg).absolute().resolve()
    if not configArg or not configPath.is_file():
        print('Invalid config path!')
        return

    fileEditedArg = cmdParser.value(fileEditedOpt)
    fileEditedPath = None
    if fileEditedArg:
        fileEditedPath = Path(fileEditedArg).absolute().resolve()
        if not fileEditedPath.is_file():
            print('Invalid edited file path!')
            return

    scriptPath = Path(__file__ + '/../roommerger.py').absolute().resolve()

    with open(configPath) as configFile:
        config = json.load(configFile)

        mergeRooms(config['files'],
                   str(scriptPath),
                   configPath.parent,
                   fileEdited=fileEditedPath)

    print('Success! Merged all.')
Ejemplo n.º 6
0
def process_args(app):
    args = {}

    parser = QCommandLineParser()
    parser.setApplicationDescription(
        ('PyMemorise is a tool to help memorise tables of data.' +
         ' It was built as an exam revision aid.'))
    parser.addHelpOption()
    parser.addVersionOption()

    dbOption = QCommandLineOption(
        ["database-file", "d"],
        "path to database, will be created if does not exist", "db",
        str(Path.home().joinpath(".pymem.db")))
    parser.addOption(dbOption)

    parser.process(app)

    args["database"] = parser.value(dbOption)

    if parser.positionalArguments():
        print(parser.positionalArguments())
        parser.showHelp()

    return args
Ejemplo n.º 7
0
def main():
    app = QApplication(sys.argv)

    QCoreApplication.setOrganizationName("QtExamples")
    QCoreApplication.setApplicationName("html2pdf")
    QCoreApplication.setApplicationVersion(QT_VERSION_STR)

    parser = QCommandLineParser()
    parser.setApplicationDescription(
        QCoreApplication.translate(
            "main", "Converts the web page INPUT into the PDF file OUTPUT."
        )
    )
    parser.addHelpOption()
    parser.addVersionOption()
    parser.addPositionalArgument(
        QCoreApplication.translate("main", "INPUT"),
        QCoreApplication.translate("main", "Input URL for PDF conversion."),
    )
    parser.addPositionalArgument(
        QCoreApplication.translate("main", "OUTPUT"),
        QCoreApplication.translate("main", "Output file name for PDF conversion."),
    )

    parser.process(QCoreApplication.arguments())

    requiredArguments = parser.positionalArguments()
    if len(requiredArguments) != 2:
        parser.showHelp(1)

    converter = Html2PdfConverter(*requiredArguments[:2])
    ret = converter.run()
    sys.exit(ret)
Ejemplo n.º 8
0
def main():
    import sys

    app = QApplication(sys.argv)

    QQuickWindow.setDefaultAlphaBuffer(True)

    QCoreApplication.setApplicationName("Photosurface")
    QCoreApplication.setOrganizationName("QtProject")
    QCoreApplication.setApplicationVersion(QT_VERSION_STR)
    parser = QCommandLineParser()
    parser.setApplicationDescription("Qt Quick Demo - Photo Surface")
    parser.addHelpOption()
    parser.addVersionOption()
    parser.addPositionalArgument("directory",
                                 "The image directory or URL to show.")
    parser.process(app)

    initialUrl = QUrl()
    if parser.positionalArguments():
        initialUrl = QUrl.fromUserInput(parser.positionalArguments()[0],
                                        QDir.currentPath(),
                                        QUrl.AssumeLocalFile)
        if not initialUrl.isValid():
            print(
                'Invalid argument: "',
                parser.positionalArguments()[0],
                '": ',
                initialUrl.errorString(),
            )
            sys.exit(1)

    nameFilters = imageNameFilters()

    engine = QQmlApplicationEngine()
    context: QQmlContext = engine.rootContext()

    picturesLocationUrl = QUrl.fromLocalFile(QDir.homePath())
    picturesLocations = QStandardPaths.standardLocations(
        QStandardPaths.PicturesLocation)
    if picturesLocations:
        picturesLocationUrl = QUrl.fromLocalFile(picturesLocations[0])
        if not initialUrl and QDir(picturesLocations[0]).entryInfoList(
                nameFilters, QDir.Files):
            initialUrl = picturesLocationUrl

    context.setContextProperty("contextPicturesLocation", picturesLocationUrl)
    context.setContextProperty("contextInitialUrl", initialUrl)
    context.setContextProperty("contextImageNameFilters", nameFilters)

    engine.load(QUrl("qrc:///photosurface.qml"))
    if not engine.rootObjects():
        sys.exit(-1)

    sys.exit(app.exec_())
Ejemplo n.º 9
0
def main():
    # register representation factories
    representationFactories.registerAllFactories()
    # initialize the app
    app = Application(sys.argv)
    app.setOrganizationName("TruFont")
    app.setOrganizationDomain("trufont.github.io")
    app.setApplicationName("TruFont")
    app.setApplicationVersion(__version__)
    app.setWindowIcon(QIcon(":/resources/app.png"))

    # Qt's translation for itself. May not be installed.
    qtTranslator = QTranslator()
    qtTranslator.load("qt_" + QLocale.system().name(),
                      QLibraryInfo.location(QLibraryInfo.TranslationsPath))
    app.installTranslator(qtTranslator)

    appTranslator = QTranslator()
    appTranslator.load("trufont_" + QLocale.system().name(),
                       os.path.dirname(os.path.realpath(__file__)) +
                       "/resources")
    app.installTranslator(appTranslator)

    app.loadGlyphList()
    # parse options and open fonts
    parser = QCommandLineParser()
    parser.setApplicationDescription(QApplication.translate(
        "Command-line parser", "The TruFont font editor."))
    parser.addHelpOption()
    parser.addVersionOption()
    parser.addPositionalArgument(QApplication.translate(
        "Command-line parser", "files"), QApplication.translate(
        "Command-line parser", "The UFO files to open."))
    parser.process(app)
    args = parser.positionalArguments()
    if not len(args):
        fontPath = None
        # maybe load recent file
        settings = QSettings()
        loadRecentFile = settings.value("misc/loadRecentFile", False, bool)
        if loadRecentFile:
            recentFiles = settings.value("core/recentFiles", [], type=str)
            if len(recentFiles) and os.path.exists(recentFiles[0]):
                fontPath = recentFiles[0]
                app.openFile(fontPath)
        # otherwise, create a new file
        if fontPath is None:
            app.newFile()
    else:
        for fontPath in args:
            app.openFile(fontPath)
    sys.exit(app.exec_())
def directory(app):
    #app = QApplication(sys.argv)

    QCoreApplication.setApplicationVersion(QT_VERSION_STR)
    parser = QCommandLineParser()
    parser.setApplicationDescription("File Directory")
    parser.addHelpOption()
    parser.addVersionOption()

    dontUseCustomDirectoryIconsOption = QCommandLineOption(
        'C', "Set QFileIconProvider.DontUseCustomDirectoryIcons")
    parser.addOption(dontUseCustomDirectoryIconsOption)
    parser.addPositionalArgument('', "The directory to start in.")
    parser.process(app)
    try:
        rootPath = parser.positionalArguments().pop(0)
    except IndexError:
        rootPath = None

    model = QFileSystemModel()
    model.setRootPath('')
    filter = ['*.db']  #filtering out just by db
    model.setNameFilters(filter)
    model.setNameFilterDisables(0)  #Only show the filtered .db paths
    #filename = model.filePath()
    #print(filename)

    if parser.isSet(dontUseCustomDirectoryIconsOption):
        model.iconProvider().setOptions(
            QFileIconProvider.DontUseCustomDirectoryIcons)
    tree = QTreeView()
    tree.setModel(model)
    if rootPath is not None:
        rootIndex = model.index(QDir.cleanPath(rootPath))
        if rootIndex.isValid():
            tree.setRootIndex(rootIndex)

    # Demonstrating look and feel features.
    tree.setAnimated(False)
    tree.setIndentation(20)
    tree.setSortingEnabled(True)

    availableSize = QApplication.desktop().availableGeometry(tree).size()
    tree.resize(availableSize / 2)
    tree.setColumnWidth(0, tree.width() / 3)

    tree.setWindowTitle("Directory View")
    tree.show()

    sys.exit(app.exec_())
Ejemplo n.º 11
0
def main():
    app = QCoreApplication(sys.argv)

    # Set some application details.
    app.setApplicationName("MyApp")
    app.setApplicationVersion("0.1.0")
    app.setOrganizationName("My Organization")
    app.setOrganizationDomain("www.my-organization.org")

    # Create a verbosity command line option.
    verbose_option = QCommandLineOption(
        "verbose", "Verbose mode. Print out debug messages.")

    # Setup the commandline parser.
    command_parser = QCommandLineParser()
    command_parser.addHelpOption()
    command_parser.addVersionOption()

    # Add the commandline options.
    command_parser.addOption(verbose_option)

    # Process the command line.
    command_parser.process(app)

    # Set the basic logger mnessage format and verbosity level.
    logger = logging.getLogger()

    # This dictates how the messages are formatted.
    formatter = logging.Formatter(fmt=MESSAGE_FORMAT, style='{')

    # This handler sends everything to stdout.
    handler = logging.StreamHandler()
    handler.setFormatter(formatter)

    # Add the handler to the logger.
    logger.addHandler(handler)

    # Check if the verbosity flag is set and set the log level to debug if it is.
    if command_parser.isSet(verbose_option):
        logger.setLevel(logging.DEBUG)
        logger.debug("Setting loglevel to debug.")

    else:
        logger.setLevel(logging.ERROR)

    # Start the event loop.
    sys.exit(app.exec())
Ejemplo n.º 12
0
    def parse_cmdline(self) -> None:
        self.parser = QCommandLineParser()
        self.parser.setApplicationDescription(
            'The simply FAST & ACCURATE video cutter & joiner')
        self.parser.addPositionalArgument('video',
                                          'Preloads the video file in app.',
                                          '[video]')
        self.edl_option = QCommandLineOption(
            'edl', 'Preloads clip index from a previously saved EDL file.\n' +
            'NOTE: You must also set the video argument for this to work.',
            'edl file')
        self.debug_option = QCommandLineOption(
            ['d', 'debug'],
            'Output all info, warnings and errors to the console. ' +
            'This will basically output what is being logged to file to the ' +
            'console stdout. Mainly useful for debugging problems with your ' +
            'system video and/or audio stack and codec configuration.')

        self.parser.addOption(self.edl_option)
        self.parser.addOption(self.debug_option)
        self.parser.addVersionOption()
        self.parser.addHelpOption()
        self.parser.process(qApp)
        self.args = self.parser.positionalArguments()
        if self.parser.value('edl').strip() and not os.path.exists(
                self.parser.value('edl')):
            print('\n    ERROR: EDL file not found.\n', file=sys.stderr)
            self.close()
            sys.exit(1)
        if self.parser.value('edl').strip() and len(self.args) == 0:
            print('\n    ERROR: Video file argument is missing.\n',
                  file=sys.stderr)
            self.close()
            sys.exit(1)
        if self.parser.value('edl').strip():
            self.edl = self.parser.value('edl')
        if self.parser.isSet(self.debug_option):
            os.environ['DEBUG'] = '1'
        if len(self.args) > 0 and not os.path.exists(self.args[0]):
            print('\n    ERROR: Video file not found.\n', file=sys.stderr)
            self.close()
            sys.exit(1)
        if len(self.args) > 0:
            self.video = self.args[0]
Ejemplo n.º 13
0
def processArguments(arguments):
    parser = QCommandLineParser()
    parser.addHelpOption()
    parser.addVersionOption()

    delayOption = QCommandLineOption(["d", "delay"],
                                     "Take a screenshot after NUM seconds",
                                     "NUM")
    fullscreenOption = QCommandLineOption(
        ["f", "fullscreen"], "Take a screenshot of the whole screen")
    topWindowOption = QCommandLineOption(
        ["w", "top-window"], "Take a screenshot of the most top window")
    savePathOption = QCommandLineOption(
        ["s", "save-path"], "Specify a path to save the screenshot", "PATH")
    startFromDesktopOption = QCommandLineOption(
        ["i", "icon"],
        "Indicate that this program's started by clicking desktop file.")
    noNotificationOption = QCommandLineOption(["n", "no-notification"],
                                              "Don't send notifications.")

    parser.addOption(delayOption)
    parser.addOption(fullscreenOption)
    parser.addOption(topWindowOption)
    parser.addOption(savePathOption)
    parser.addOption(noNotificationOption)
    parser.addOption(startFromDesktopOption)
    parser.process(arguments)

    delay = int(parser.value(delayOption) or 0)
    fullscreen = bool(parser.isSet(fullscreenOption) or False)
    topWindow = bool(parser.isSet(topWindowOption) or False)
    savePath = str(parser.value(savePathOption) or "")
    startFromDesktop = bool(parser.isSet(startFromDesktopOption) or False)
    noNotification = bool(parser.isSet(noNotificationOption) or False)

    return {
        "delay": delay,
        "fullscreen": fullscreen,
        "topWindow": topWindow,
        "savePath": savePath,
        "startFromDesktop": startFromDesktop,
        "noNotification": noNotification
    }
Ejemplo n.º 14
0
    def __init__(self, app):
        self.log = logs.logger.add_module("CliParser")
        QApplication.setApplicationName("fotobox")
        QApplication.setApplicationVersion("1.0")

        self.parser = QCommandLineParser()
        self.parser.setApplicationDescription("Fotobox")
        self.parser.addHelpOption()
        self.parser.addVersionOption()

        self.cursorOption = QCommandLineOption(["m", "mouse-cursor"],
                                               "Maus anzeigen")
        self.parser.addOption(self.cursorOption)

        self.configOption = QCommandLineOption(["c", "config"],
                                               "Systemkonfiguration setzen")
        self.parser.addOption(self.configOption)

        self.loggingOption = QCommandLineOption(["log"], "Logging aktivieren",
                                                "level", "INFO")
        self.parser.addOption(self.loggingOption)

        self.parser.process(app)
Ejemplo n.º 15
0
def main(use_resources=False):

    parser = QCommandLineParser()
    geometryOpt = QCommandLineOption('geometry', 'Main window geometry',
                                     'geometry')
    parser.addOption(geometryOpt)
    parser.process(sys.argv)
    if parser.isSet('geometry'):
        try:
            geometry = tuple(
                int(val) for val in parser.value('geometry').split('x'))
            if len(geometry) != 4:
                raise
            if any(val < 1 for val in geometry):
                raise
        except:
            print(
                'The --geometry argument value must have a format such as 1x1x640x320 (x, y, width, height).'
            )
            exit(0)
    else:
        geometry = None

    app = QApplication(sys.argv)
    app.setApplicationName('pyrMExplorer')
    app.setOrganizationName('rMTools')
    if use_resources:
        icon_path = resource_path('icon.ico')
    else:
        icon_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                 'icon.ico')
    app.setWindowIcon(QIcon(icon_path))
    mainWindow = RmExplorerWindow()
    if geometry:
        mainWindow.setGeometry(*geometry)
    mainWindow.show()
    sys.exit(app.exec_())
Ejemplo n.º 16
0
    - process command line options (--help, --version, --verbose)
    - create instance of application class (ui)
    - call setupUi to set dialog properties (calls retranslateUi)
    - call parseConfigFile
    - show the QDialog
    - the application will process messages until it is told to exit
    """
    import sys, os
    from subprocess import Popen, PIPE
    from configparser import ConfigParser

    app = QApplication(sys.argv)
    app.setApplicationName("gitStatus.py")
    app.setApplicationVersion("1.0.0")

    clp = QCommandLineParser()  # handle command line options
    clp.addHelpOption()
    clp.addVersionOption()
    verboseOption = QCommandLineOption("verbose",
                                       "Issue progress messages to console.")
    clp.addOption(verboseOption)
    clp.process(sys.argv)

    GitStatus = QtWidgets.QDialog()  # create QDialog
    ui = Ui_GitStatus()  # instantiate ui
    ui.setupUi(GitStatus)  # configure all widgets
    ui.isVerbose = clp.isSet(verboseOption)

    if not ui.parseConfigFile():  # read the .ini file
        sys.exit(1)
Ejemplo n.º 17
0
def runmain():
    import sys

    app = QApplication(sys.argv)

    cmdParser = QCommandLineParser()
    cmdParser.setApplicationDescription(
        'Room file merger utility script for Basement Renovator. Takes a set of file paths'
    )
    cmdParser.addHelpOption()

    cmdParser.addPositionalArgument('file', 'xml files to merge')

    outputFileOpt = QCommandLineOption('output',
                                       'output filename, must be xml', 'file')
    cmdParser.addOption(outputFileOpt)

    stbOpt = QCommandLineOption(
        'stb', 'whether to save an stb version of the file next to it')
    cmdParser.addOption(stbOpt)

    noRecompIdsOpt = QCommandLineOption(
        'noRecomputeIds',
        'turn off recomputing room ids; useful for special room merging')
    cmdParser.addOption(noRecompIdsOpt)

    idOpt = QCommandLineOption(
        'startingId', 'optional starting id to use when recomputing room ids',
        'id')
    cmdParser.addOption(idOpt)

    skipOpt = QCommandLineOption(
        'roommerge',
        'placeholder argument used to prevent recursive execution')
    cmdParser.addOption(skipOpt)

    cmdParser.process(app)

    if cmdParser.isSet(skipOpt):
        print('Recursive execution from save hook, skipping')
        return

    paths = cmdParser.positionalArguments()
    if not paths:
        print('Must specify at least one file to merge!')
        return

    outputFileArg = cmdParser.value(outputFileOpt)
    outputFilePath = Path(outputFileArg).absolute().resolve()
    if not outputFileArg or outputFilePath.suffix != '.xml':
        print('Must specify xml output file!')
        return

    lastModified = None
    if outputFilePath.exists():
        lastModified = outputFilePath.stat().st_mtime

    idArg = cmdParser.value(idOpt)

    noRecompIdsArg = cmdParser.isSet(noRecompIdsOpt)
    stbArg = cmdParser.isSet(stbOpt)

    mergeRoomFile = None
    i = -1
    while (i + 1) < len(paths):
        i += 1

        file = paths[i]

        path = Path(file)
        if path.is_dir():
            files = list(filter(lambda f: f.suffix == '.xml', path.iterdir()))
            print('Adding xml files to queue from: ', path)
            del paths[i]
            i -= 1
            paths.extend(files)

    paths = list(filter(lambda f: Path(f).exists(), paths))

    if lastModified:
        anyModified = next(
            (file for file in paths if file.stat().st_mtime > lastModified),
            None) is not None
        if not anyModified:
            print('----')
            print(
                'Skipping since no xmls in folder have been modified since last update'
            )
            return

    for file in paths:
        print('----')
        print('Path:', file)

        path = Path(file)

        print('Merging file...')
        if path.suffix != '.xml':
            print('Must be xml! Skipping!')
            continue

        roomFile = cvt.xmlToCommon(path)
        if not mergeRoomFile:
            mergeRoomFile = roomFile
        else:
            mergeRoomFile.rooms.extend(roomFile.rooms)

    print('----')

    if not mergeRoomFile:
        print('No rooms files to merge')
        return

    if not noRecompIdsArg:
        recomputeRoomIDs(mergeRoomFile.rooms, idArg and int(idArg))

    cvt.commonToXML(outputFilePath, mergeRoomFile.rooms, file=mergeRoomFile)
    if stbArg:
        cvt.commonToSTBAB(outputFileArg.replace('.xml', '.stb'),
                          mergeRoomFile.rooms)

    settings = QSettings(__file__ + '/../../settings.ini', QSettings.IniFormat)
    saveHooks = settings.value('HooksSave')
    if saveHooks:
        fullPath = str(outputFilePath)
        for hook in saveHooks:
            hook = Path(hook).absolute().resolve()
            try:
                subprocess.run([str(hook), fullPath, '--save', '--roommerge'],
                               cwd=hook.parent,
                               timeout=60)
            except Exception as e:
                print('Save hook failed! Reason:', e)

    print('Success! Merged to', outputFileArg)
Ejemplo n.º 18
0
 def __init__(self, args):
     super().__init__()
     self.args = args
     settings = QSettings()
     self.imageParam = {
         Option.DPI: settings.value("Export/exportDPI", 150, type=int),
         Option.QUAL: settings.value("Export/exportQuality", 80, type=int),
     }
     self.cli_mode = False
     self.requestedRecursive = False
     self.overwrite = Overwrite.UNSET
     self.dstDir = ""
     self._initStrings()
     self.parser = QCommandLineParser()
     #self.parser.setSingleDashWordOptionMode(QCommandLineself.parser.ParseAsLongOptions)
     self.parser.setApplicationDescription(
         self._appDescriptionStr.format(productName=__productname__))
     # Adding the '-h, --help' option
     self.parser.addHelpOption()
     # Adding the '-v --version' option
     self.parser.addVersionOption()
     # Allowing positional arguments (the file/files to open or process)
     self.parser.addPositionalArgument(
         _translate(
             "CommandLine", "path",
             "Commandline argument name. If you translate this name, translate it accordingly into the path description and path syntax."
         ), self._pathDescriptionStr,
         _translate(
             "CommandLine", "[<path> [ <path2>...]]",
             "Commandline argument syntax. If you translate <path>, translate the name and path description accordingly."
         ))
     # Adding command line options
     self.options = {
         Option.TIKZ:
         QCommandLineOption(
             ["t", "tikz"],
             self._batchOptionStr.format(formatID='TIkZ'),
         ),
         Option.PDF:
         QCommandLineOption(
             ["f", "pdf"],
             self._batchOptionStr.format(formatID='PDF'),
         ),
         Option.PNG:
         QCommandLineOption(
             ["p", "png"],
             self._batchOptionStr.format(formatID='PNG'),
         ),
         Option.JPEG:
         QCommandLineOption(
             ["j", "jpeg"],
             self._batchOptionStr.format(formatID='JPEG'),
         ),
         Option.SVG:
         QCommandLineOption(
             ["s", "svg"],
             self._batchOptionStr.format(formatID='SVG'),
         ),
         Option.DPI:
         QCommandLineOption(
             ["dpi"],
             self._dpiOptionStr.format(
                 defaultDPI=self.imageParam[Option.DPI]),
             "N",
         ),
         Option.QUAL:
         QCommandLineOption(
             ["quality"],
             self._qualityOptionStr.format(
                 defaultQuality=self.imageParam[Option.QUAL]),
             "Q",
         ),
         Option.DEST:
         QCommandLineOption(
             ["destination"],
             self._destDirOptionStr,
             "D",
         ),
         Option.LINK:
         QCommandLineOption(
             ["links"],
             self._followLinksOptionStr,
         ),
         Option.OVER:
         QCommandLineOption(
             ["overwrite"],
             self._overwriteOptionStr,
         ),
         Option.REC:
         QCommandLineOption(
             ["r"],
             self._recurseOptionStr,
         ),
     }
     # Adding the options in the list
     for option in self.options.values():
         self.parser.addOption(option)
Ejemplo n.º 19
0
def main():
    global app
    # register representation factories
    baseRepresentationFactories.registerAllFactories()
    representationFactories.registerAllFactories()
    if hasattr(Qt, "AA_EnableHighDpiScaling"):
        QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    # initialize the app
    app = Application(sys.argv)
    app.setOrganizationName("TruFont")
    app.setOrganizationDomain("trufont.github.io")
    app.setApplicationName("TruFont")
    app.setApplicationVersion(__version__)
    app.setWindowIcon(QIcon(":app.png"))
    app.setAttribute(Qt.AA_UseHighDpiPixmaps, True)
    appFont = platformSpecific.UIFontOverride()
    if appFont is not None:
        app.setFont(appFont)
    app.setStyleSheet(platformSpecific.appStyleSheet())

    # Install stream redirection
    app.outputWindow = OutputWindow()
    # Exception handling
    sys.excepthook = errorReports.exceptionCallback

    # Qt's translation for itself. May not be installed.
    qtTranslator = QTranslator()
    qtTranslator.load(
        "qt_" + QLocale.system().name(),
        QLibraryInfo.location(QLibraryInfo.TranslationsPath),
    )
    app.installTranslator(qtTranslator)

    appTranslator = QTranslator()
    appTranslator.load(
        "trufont_" + QLocale.system().name(),
        os.path.dirname(os.path.realpath(__file__)) + "/resources",
    )
    app.installTranslator(appTranslator)

    # parse options and open fonts
    parser = QCommandLineParser()
    parser.setApplicationDescription(
        QApplication.translate("Command-line parser", "The TruFont font editor.")
    )
    parser.addHelpOption()
    parser.addVersionOption()
    parser.addPositionalArgument(
        QApplication.translate("Command-line parser", "files"),
        QApplication.translate("Command-line parser", "The UFO files to open."),
    )
    parser.process(app)
    # load menu
    if platformSpecific.useGlobalMenuBar():
        app.fetchMenuBar()
        app.setQuitOnLastWindowClosed(False)
    # bootstrap extensions
    folder = app.getExtensionsDirectory()
    for file in os.listdir(folder):
        if not file.rstrip("\\/ ").endswith(".tfExt"):
            continue
        path = os.path.join(folder, file)
        try:
            extension = TExtension(path)
            if extension.launchAtStartup:
                extension.run()
        except Exception as e:
            msg = QApplication.translate(
                "Extensions", f"The extension at {path} could not be run."
            )
            errorReports.showWarningException(e, msg)
            continue
        app.registerExtension(extension)
    # process files
    args = parser.positionalArguments()
    if not args:
        # maybe load recent file
        loadRecentFile = settings.loadRecentFile()
        if loadRecentFile:
            recentFiles = settings.recentFiles()
            if len(recentFiles) and os.path.exists(recentFiles[0]):
                app.openFile(recentFiles[0])
    else:
        for fontPath in args:
            app.openFile(fontPath)
    # if we did not open a font, spawn new font or go headless
    if not app.allFonts():
        if platformSpecific.shouldSpawnDocument():
            app.newFile()
        else:
            # HACK: on OSX we may want to trigger native QMenuBar display
            # without opening any window. Since Qt infers new menu bar on
            # focus change, fire the signal.
            app.focusWindowChanged.emit(None)
    sys.exit(app.exec_())
Ejemplo n.º 20
0
def main():
	multiprocessing.set_start_method('spawn')

	if markups.__version_tuple__ < (2, ):
		sys.exit('Error: ReText needs PyMarkups 2.0 or newer to run.')

	# If we're running on Windows without a console, then discard stdout
	# and save stderr to a file to facilitate debugging in case of crashes.
	if sys.executable.endswith('pythonw.exe'):
		sys.stdout = open(devnull, 'w')
		sys.stderr = open('stderr.log', 'w')

	try:
		# See https://github.com/retext-project/retext/issues/399
		# and https://launchpad.net/bugs/941826
		ctypes.CDLL('libGL.so.1', ctypes.RTLD_GLOBAL)
	except OSError:
		pass

	# Needed for Qt WebEngine on Windows
	QApplication.setAttribute(Qt.ApplicationAttribute.AA_ShareOpenGLContexts)
	QApplication.setAttribute(Qt.ApplicationAttribute.AA_UseHighDpiPixmaps)
	app = QApplication(sys.argv)
	app.setOrganizationName("ReText project")
	app.setApplicationName("ReText")
	app.setApplicationDisplayName("ReText")
	app.setApplicationVersion(app_version)
	app.setOrganizationDomain('mitya57.me')
	app.setDesktopFileName('me.mitya57.ReText.desktop')
	QNetworkProxyFactory.setUseSystemConfiguration(True)

	initializeDataDirs()
	RtTranslator = QTranslator()
	for path in datadirs:
		if RtTranslator.load('retext_' + globalSettings.uiLanguage,
		                     join(path, 'locale')):
			break
	QtTranslator = QTranslator()
	QtTranslator.load("qtbase_" + globalSettings.uiLanguage,
		QLibraryInfo.location(QLibraryInfo.LibraryLocation.TranslationsPath))
	app.installTranslator(RtTranslator)
	app.installTranslator(QtTranslator)

	parser = QCommandLineParser()
	parser.addHelpOption()
	parser.addVersionOption()
	previewOption = QCommandLineOption('preview',
		QApplication.translate('main', 'Open the files in preview mode'))
	newWindowOption = QCommandLineOption('new-window',
		QApplication.translate('main', 'Create a new window even if there is an existing one'))
	parser.addOption(previewOption)
	parser.addOption(newWindowOption)
	parser.addPositionalArgument('files',
		QApplication.translate('main', 'List of files to open'),
		'[files...]')

	parser.process(app)
	filesToOpen = parser.positionalArguments()

	print('Using configuration file:', settings.fileName())
	if globalSettings.appStyleSheet:
		sheetfile = QFile(globalSettings.appStyleSheet)
		sheetfile.open(QIODevice.OpenModeFlag.ReadOnly)
		app.setStyleSheet(QTextStream(sheetfile).readAll())
		sheetfile.close()
	window = ReTextWindow()

	openInExistingWindow = (globalSettings.openFilesInExistingWindow
		and not parser.isSet(newWindowOption))
	connection = QDBusConnection.sessionBus()
	if connection.isConnected() and openInExistingWindow:
		connection.registerObject('/', window, QDBusConnection.RegisterOption.ExportAllSlots)
		serviceName = 'me.mitya57.ReText'
		if not connection.registerService(serviceName) and filesToOpen:
			print('Opening the file(s) in the existing window of ReText.')
			iface = QDBusInterface(serviceName, '/', '', connection)
			for fileName in filesToOpen:
				iface.call('openFileWrapper', fileName)
			qWidgetIface = QDBusInterface(serviceName, '/', 'org.qtproject.Qt.QWidget', connection)
			qWidgetIface.call('raise')
			sys.exit(0)

	window.show()
	# ReText can change directory when loading files, so we
	# need to have a list of canonical names before loading
	fileNames = list(map(canonicalize, filesToOpen))
	readStdIn = False

	if globalSettings.openLastFilesOnStartup:
		window.restoreLastOpenedFiles()
	for fileName in fileNames:
		if QFile.exists(fileName):
			window.openFileWrapper(fileName)
			if parser.isSet(previewOption):
				window.actionPreview.setChecked(True)
				window.preview(True)
		elif fileName == '-':
			readStdIn = True

	inputData = ''
	if readStdIn and sys.stdin is not None:
		if sys.stdin.isatty():
			print('Reading stdin, press ^D to end...')
		inputData = sys.stdin.read()
	if inputData or not window.tabWidget.count():
		window.createNew(inputData)
	signal.signal(signal.SIGINT, lambda sig, frame: window.close())
	sys.exit(app.exec())
Ejemplo n.º 21
0
import sys

from PyQt5.QtCore import (
    QCommandLineOption,
    QCommandLineParser,
    QCoreApplication,
    QDir,
    QT_VERSION_STR,
)
from PyQt5.QtWidgets import QApplication, QFileIconProvider, QFileSystemModel, QTreeView

app = QApplication(sys.argv)

QCoreApplication.setApplicationVersion(QT_VERSION_STR)
parser = QCommandLineParser()
parser.setApplicationDescription("Qt Dir View Example")
parser.addHelpOption()
parser.addVersionOption()

dontUseCustomDirectoryIconsOption = QCommandLineOption(
    "c", "Set QFileIconProvider.DontUseCustomDirectoryIcons")
parser.addOption(dontUseCustomDirectoryIconsOption)
parser.addPositionalArgument("directory", "The directory to start in.")
parser.process(app)
try:
    rootPath = parser.positionalArguments().pop(0)
except IndexError:
    rootPath = None

model = QFileSystemModel()
Ejemplo n.º 22
0
def main():
    global app

    # Register representation factories
    baseRepresentationFactories.registerAllFactories()
    representationFactories.registerAllFactories()

    # initialize the app
    app = Application(sys.argv)
    app.setOrganizationName("SimpleFont")
    app.setOrganizationDomain("elih.blog/simplefont")
    app.setApplicationName("SimpleFont")
    app.setApplicationVersion(__version__)
    app.setWindowIcon(QIcon(":app.png"))
    app.setAttribute(Qt.AA_UseHighDpiPixmaps, True)
    appFont = platformSpecific.UIFontOverride()
    if appFont is not None:
        app.setFont(appFont)
    # app.setStyleSheet(platformSpecific.appStyleSheet())
    app.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())

    # Install stream redirection
    app.outputWindow = OutputWindow()
    # Exception handling
    sys.excepthook = errorReports.exceptionCallback

    # Qt's translation for itself. May not be installed.
    # qtTranslator = QTranslator()
    # qtTranslator.load("qt_" + QLocale.system().name(),
    #                   QLibraryInfo.location(QLibraryInfo.TranslationsPath))
    # app.installTranslator(qtTranslator)

    # appTranslator = QTranslator()
    # appTranslator.load("simplefont_" + QLocale.system().name(),
    #                    os.path.dirname(os.path.realpath(__file__)) +
    #                    "/resources")
    # app.installTranslator(appTranslator)

    # parse options and open fonts
    parser = QCommandLineParser()
    parser.setApplicationDescription(QApplication.translate(
        "Command-line parser", "The SimpleFont font editor."))
    parser.addHelpOption()
    parser.addVersionOption()
    parser.addPositionalArgument(QApplication.translate(
        "Command-line parser", "files"), QApplication.translate(
        "Command-line parser", "The UFO files to open."))
    parser.process(app)
    
    # load menu
    if platformSpecific.useGlobalMenuBar():
        app.fetchMenuBar()
        app.setQuitOnLastWindowClosed(False)

    # bootstrap extensions

    # process files
    args = parser.positionalArguments()
    if not args:
        # maybe load recent file
        loadRecentFile = settings.loadRecentFile()
        if loadRecentFile:
            recentFiles = settings.recentFiles()
            if len(recentFiles) and os.path.exists(recentFiles[0]):
                app.openFile(recentFiles[0])
    else:
        for fontPath in args:
            app.openFile(fontPath)
    # if we did not open a font, spawn new font or go headless
    if not app.allFonts():
        if platformSpecific.shouldSpawnDocument():
            app.newFile()
        else:
            # HACK: on OSX we may want to trigger native QMenuBar display
            # without opening any window. Since Qt infers new menu bar on
            # focus change, fire the signal.
            app.focusWindowChanged.emit(None)
    sys.exit(app.exec_())