Esempio n. 1
0
def hgVersion(plugin):
    """
    Public method to determine the Mercurial version.
    
    @param plugin reference to the plugin object
    @type VcsMercurialPlugin
    @return tuple containing the Mercurial version as a string and as a tuple
        and an error message.
    @rtype tuple of str, tuple of int and str
    """
    versionStr = ""
    version = ()
    errorMsg = ""
    
    args = ["version"]
    args.extend(plugin.getGlobalOptions())
    process = QProcess()
    process.start('hg', args)
    procStarted = process.waitForStarted(5000)
    if procStarted:
        finished = process.waitForFinished(30000)
        if finished and process.exitCode() == 0:
            output = str(process.readAllStandardOutput(),
                         plugin.getPreferences("Encoding"), 'replace')
            versionStr = output.splitlines()[0].split()[-1][0:-1]
            v = list(re.match(r'.*?(\d+)\.(\d+)\.?(\d+)?(\+[0-9a-f-]+)?',
                              versionStr).groups())
            if v[-1] is None:
                del v[-1]
            for i in range(3):
                try:
                    v[i] = int(v[i])
                except TypeError:
                    v[i] = 0
                except IndexError:
                    v.append(0)
            version = tuple(v)
        else:
            if finished:
                errorMsg = QCoreApplication.translate(
                    "HgUtilities",
                    "The hg process finished with the exit code {0}"
                ).format(process.exitCode())
            else:
                errorMsg = QCoreApplication.translate(
                    "HgUtilities",
                    "The hg process did not finish within 30s.")
    else:
        errorMsg = QCoreApplication.translate(
            "HgUtilities",
            "Could not start the hg executable.")
    
    return versionStr, version, errorMsg
Esempio n. 2
0
    def __hgGetShelveNamesList(self, repodir):
        """
        Private method to get the list of shelved changes.
        
        @param repodir directory name of the repository (string)
        @return list of shelved changes (list of string)
        """
        args = self.vcs.initCommand("shelve")
        args.append('--list')
        args.append('--quiet')

        client = self.vcs.getClient()
        output = ""
        if client:
            output = client.runcommand(args)[0]
        else:
            process = QProcess()
            process.setWorkingDirectory(repodir)
            process.start('hg', args)
            procStarted = process.waitForStarted(5000)
            if procStarted:
                finished = process.waitForFinished(30000)
                if finished and process.exitCode() == 0:
                    output = str(process.readAllStandardOutput(),
                                 self.vcs.getEncoding(), 'replace')

        shelveNamesList = []
        for line in output.splitlines():
            shelveNamesList.append(line.strip())

        return shelveNamesList[:]
Esempio n. 3
0
 def __hgGetShelveNamesList(self, repodir):
     """
     Private method to get the list of shelved changes.
     
     @param repodir directory name of the repository (string)
     @return list of shelved changes (list of string)
     """
     args = self.vcs.initCommand("shelve")
     args.append('--list')
     args.append('--quiet')
     
     client = self.vcs.getClient()
     output = ""
     if client:
         output = client.runcommand(args)[0]
     else:
         process = QProcess()
         process.setWorkingDirectory(repodir)
         process.start('hg', args)
         procStarted = process.waitForStarted(5000)
         if procStarted:
             finished = process.waitForFinished(30000)
             if finished and process.exitCode() == 0:
                 output = str(process.readAllStandardOutput(),
                              self.vcs.getEncoding(), 'replace')
     
     shelveNamesList = []
     for line in output.splitlines():
         shelveNamesList.append(line.strip())
     
     return shelveNamesList[:]
Esempio n. 4
0
def main():
    if sys.version_info < (3, 5):
        raise RuntimeError('This package requires Python 3.5 or later')

    site_packages = get_python_lib()
    print('site_packages', site_packages)
    current_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
    print('current_dir', current_dir)

    env = QProcessEnvironment.systemEnvironment()
    PATH = '{0};{1};{2}'.format(os.path.dirname(PyQt5.__file__), sys.prefix,
                                env.value('PATH', ''))
    env.insert('PATH', PATH)
    env.insert('PYQTDESIGNERPATH', os.path.join(current_dir, 'Plugins'))
    env.insert('PYTHONPATH', os.path.join(current_dir))

    print('PATH', env.value('PATH', ''))
    print('PYQTDESIGNERPATH', env.value('PYQTDESIGNERPATH', ''))
    print('PYTHONPATH', env.value('PYTHONPATH', ''))

    ext = '.exe' if os.name == 'nt' else ''
    designer = QProcess()
    designer.setProcessEnvironment(env)

    # for PyQt5.5 latter,pyqt5-tools maybe have problem
    designer_bin = QLibraryInfo.location(
        QLibraryInfo.BinariesPath) + os.sep + 'designer' + ext
    print('designer_bin', designer_bin)

    if os.path.exists(designer_bin):
        designer.start(designer_bin)
        designer.waitForFinished(-1)
        sys.exit(designer.exitCode())
    else:
        raise Exception('Can not find designer')
Esempio n. 5
0
 def __getCommitMessage(self, repodir):
     """
     Private method to get the commit message of the current patch.
     
     @param repodir directory name of the repository (string)
     @return name of the current patch (string)
     """
     message = ""
     
     args = self.vcs.initCommand("qheader")
     
     client = self.vcs.getClient()
     if client:
         message = client.runcommand(args)[0]
     else:
         process = QProcess()
         process.setWorkingDirectory(repodir)
         process.start('hg', args)
         procStarted = process.waitForStarted(5000)
         if procStarted:
             finished = process.waitForFinished(30000)
             if finished and process.exitCode() == 0:
                 message = str(process.readAllStandardOutput(),
                               self.vcs.getEncoding(), 'replace')
     
     return message
Esempio n. 6
0
 def __getEntries(self, repodir, all):
     """
     Private method to get a list of files/directories being purged.
     
     @param repodir directory name of the repository (string)
     @param all flag indicating to delete all files including ignored ones
         (boolean)
     @return name of the current patch (string)
     """
     purgeEntries = []
     
     args = self.vcs.initCommand("purge")
     args.append("--print")
     if all:
         args.append("--all")
     
     client = self.vcs.getClient()
     if client:
         out, err = client.runcommand(args)
         if out:
             purgeEntries = out.strip().split()
     else:
         process = QProcess()
         process.setWorkingDirectory(repodir)
         process.start('hg', args)
         procStarted = process.waitForStarted(5000)
         if procStarted:
             finished = process.waitForFinished(30000)
             if finished and process.exitCode() == 0:
                 purgeEntries = str(
                     process.readAllStandardOutput(),
                     self.vcs.getEncoding(), 'replace').strip().split()
     
     return purgeEntries
Esempio n. 7
0
    def __getCommit(self, tag):
        """
        Private method to get the commit id for a tag.
        
        @param tag tag name (string)
        @return commit id shortened to 10 characters (string)
        """
        args = self.vcs.initCommand("show")
        args.append("--abbrev-commit")
        args.append("--abbrev={0}".format(
            self.vcs.getPlugin().getPreferences("CommitIdLength")))
        args.append("--no-patch")
        args.append(tag)

        output = ""
        process = QProcess()
        process.setWorkingDirectory(self.repodir)
        process.start('git', args)
        procStarted = process.waitForStarted(5000)
        if procStarted:
            finished = process.waitForFinished(30000)
            if finished and process.exitCode() == 0:
                output = str(process.readAllStandardOutput(),
                             Preferences.getSystem("IOEncoding"), 'replace')

        if output:
            for line in output.splitlines():
                if line.startswith("commit "):
                    commitId = line.split()[1]
                    return commitId

        return ""
Esempio n. 8
0
    def __getEntries(self, repodir, all):
        """
        Private method to get a list of files/directories being purged.
        
        @param repodir directory name of the repository (string)
        @param all flag indicating to delete all files including ignored ones
            (boolean)
        @return name of the current patch (string)
        """
        purgeEntries = []

        args = self.vcs.initCommand("purge")
        args.append("--print")
        if all:
            args.append("--all")

        client = self.vcs.getClient()
        if client:
            out, err = client.runcommand(args)
            if out:
                purgeEntries = out.strip().split()
        else:
            process = QProcess()
            process.setWorkingDirectory(repodir)
            process.start('hg', args)
            procStarted = process.waitForStarted(5000)
            if procStarted:
                finished = process.waitForFinished(30000)
                if finished and process.exitCode() == 0:
                    purgeEntries = str(process.readAllStandardOutput(),
                                       self.vcs.getEncoding(),
                                       'replace').strip().split()

        return purgeEntries
Esempio n. 9
0
 def __getParents(self, rev):
     """
     Private method to get the parents of the currently viewed
     file/directory.
     
     @param rev revision number to get parents for (string)
     @return list of parent revisions (list of strings)
     """
     errMsg = ""
     parents = []
     
     if int(rev) > 0:
         args = self.vcs.initCommand("parents")
         if self.mode == "incoming":
             if self.bundle:
                 args.append("--repository")
                 args.append(self.bundle)
             elif self.vcs.bundleFile and \
                     os.path.exists(self.vcs.bundleFile):
                 args.append("--repository")
                 args.append(self.vcs.bundleFile)
         args.append("--template")
         args.append("{rev}:{node|short}\n")
         args.append("-r")
         args.append(rev)
         if not self.projectMode:
             args.append(self.filename)
         
         output = ""
         if self.__hgClient:
             output, errMsg = self.__hgClient.runcommand(args)
         else:
             process = QProcess()
             process.setWorkingDirectory(self.repodir)
             process.start('hg', args)
             procStarted = process.waitForStarted(5000)
             if procStarted:
                 finished = process.waitForFinished(30000)
                 if finished and process.exitCode() == 0:
                     output = str(process.readAllStandardOutput(),
                                  self.vcs.getEncoding(), 'replace')
                 else:
                     if not finished:
                         errMsg = self.tr(
                             "The hg process did not finish within 30s.")
             else:
                 errMsg = self.tr("Could not start the hg executable.")
         
         if errMsg:
             E5MessageBox.critical(
                 self,
                 self.tr("Mercurial Error"),
                 errMsg)
         
         if output:
             parents = [p for p in output.strip().splitlines()]
     
     return parents
    def start(self, path):
        """
        Public slot to start the list command.
        
        @param path name of directory to be listed (string)
        """
        dname, fname = self.vcs.splitPath(path)

        # find the root of the repo
        repodir = dname
        while not os.path.isdir(os.path.join(repodir, self.vcs.adminDir)):
            repodir = os.path.dirname(repodir)
            if os.path.splitdrive(repodir)[1] == os.sep:
                return

        args = self.vcs.initCommand("qguard")
        args.append("--list")

        output = ""
        if self.__hgClient:
            output = self.__hgClient.runcommand(args)[0]
        else:
            process = QProcess()
            process.setWorkingDirectory(repodir)
            process.start('hg', args)
            procStarted = process.waitForStarted(5000)
            if procStarted:
                finished = process.waitForFinished(30000)
                if finished and process.exitCode() == 0:
                    output = str(process.readAllStandardOutput(),
                                 self.vcs.getEncoding(), 'replace')

        if output:
            guardsDict = {}
            for line in output.splitlines():
                if line:
                    patchName, guards = line.strip().split(":", 1)
                    guardsDict[patchName] = guards.strip().split()
            for patchName in sorted(guardsDict.keys()):
                patchItm = QTreeWidgetItem(self.guardsTree, [patchName])
                patchItm.setExpanded(True)
                for guard in guardsDict[patchName]:
                    if guard.startswith("+"):
                        icon = UI.PixmapCache.getIcon("plus.png")
                        guard = guard[1:]
                    elif guard.startswith("-"):
                        icon = UI.PixmapCache.getIcon("minus.png")
                        guard = guard[1:]
                    else:
                        icon = None
                        guard = self.tr("Unguarded")
                    itm = QTreeWidgetItem(patchItm, [guard])
                    if icon:
                        itm.setIcon(0, icon)
        else:
            QTreeWidgetItem(self.guardsTree, [self.tr("no patches found")])
 def start(self, path):
     """
     Public slot to start the list command.
     
     @param path name of directory to be listed (string)
     """
     dname, fname = self.vcs.splitPath(path)
     
     # find the root of the repo
     repodir = dname
     while not os.path.isdir(os.path.join(repodir, self.vcs.adminDir)):
         repodir = os.path.dirname(repodir)
         if os.path.splitdrive(repodir)[1] == os.sep:
             return
     
     args = self.vcs.initCommand("qguard")
     args.append("--list")
     
     output = ""
     if self.__hgClient:
         output = self.__hgClient.runcommand(args)[0]
     else:
         process = QProcess()
         process.setWorkingDirectory(repodir)
         process.start('hg', args)
         procStarted = process.waitForStarted(5000)
         if procStarted:
             finished = process.waitForFinished(30000)
             if finished and process.exitCode() == 0:
                 output = str(process.readAllStandardOutput(),
                              self.vcs.getEncoding(), 'replace')
     
     if output:
         guardsDict = {}
         for line in output.splitlines():
             if line:
                 patchName, guards = line.strip().split(":", 1)
                 guardsDict[patchName] = guards.strip().split()
         for patchName in sorted(guardsDict.keys()):
             patchItm = QTreeWidgetItem(self.guardsTree, [patchName])
             patchItm.setExpanded(True)
             for guard in guardsDict[patchName]:
                 if guard.startswith("+"):
                     icon = UI.PixmapCache.getIcon("plus.png")
                     guard = guard[1:]
                 elif guard.startswith("-"):
                     icon = UI.PixmapCache.getIcon("minus.png")
                     guard = guard[1:]
                 else:
                     icon = None
                     guard = self.tr("Unguarded")
                 itm = QTreeWidgetItem(patchItm, [guard])
                 if icon:
                     itm.setIcon(0, icon)
     else:
         QTreeWidgetItem(self.guardsTree, [self.tr("no patches found")])
Esempio n. 12
0
    def __getParents(self, rev):
        """
        Private method to get the parents of the currently viewed
        file/directory.
        
        @param rev revision number to get parents for (string)
        @return list of parent revisions (list of strings)
        """
        errMsg = ""
        parents = []

        if int(rev) > 0:
            args = self.vcs.initCommand("parents")
            if self.mode == "incoming":
                if self.bundle:
                    args.append("--repository")
                    args.append(self.bundle)
                elif self.vcs.bundleFile and \
                        os.path.exists(self.vcs.bundleFile):
                    args.append("--repository")
                    args.append(self.vcs.bundleFile)
            args.append("--template")
            args.append("{rev}:{node|short}\n")
            args.append("-r")
            args.append(rev)
            if not self.projectMode:
                args.append(self.filename)

            output = ""
            if self.__hgClient:
                output, errMsg = self.__hgClient.runcommand(args)
            else:
                process = QProcess()
                process.setWorkingDirectory(self.repodir)
                process.start('hg', args)
                procStarted = process.waitForStarted(5000)
                if procStarted:
                    finished = process.waitForFinished(30000)
                    if finished and process.exitCode() == 0:
                        output = str(process.readAllStandardOutput(),
                                     self.vcs.getEncoding(), 'replace')
                    else:
                        if not finished:
                            errMsg = self.tr(
                                "The hg process did not finish within 30s.")
                else:
                    errMsg = self.tr("Could not start the hg executable.")

            if errMsg:
                E5MessageBox.critical(self, self.tr("Mercurial Error"), errMsg)

            if output:
                parents = [p for p in output.strip().splitlines()]

        return parents
Esempio n. 13
0
    def runProcess(self, args):
        """
        Public method to execute the conda with the given arguments.
        
        The conda executable is called with the given arguments and
        waited for its end.
        
        @param args list of command line arguments
        @type list of str
        @return tuple containing a flag indicating success and the output
            of the process
        @rtype tuple of (bool, str)
        """
        exe = Preferences.getConda("CondaExecutable")
        if not exe:
            exe = "conda"

        process = QProcess()
        process.start(exe, args)
        procStarted = process.waitForStarted(15000)
        if procStarted:
            finished = process.waitForFinished(30000)
            if finished:
                if process.exitCode() == 0:
                    output = str(process.readAllStandardOutput(),
                                 Preferences.getSystem("IOEncoding"),
                                 'replace').strip()
                    return True, output
                else:
                    return (
                        False,
                        self.tr("conda exited with an error ({0}).").format(
                            process.exitCode()))
            else:
                process.terminate()
                process.waitForFinished(2000)
                process.kill()
                process.waitForFinished(3000)
                return False, self.tr("conda did not finish within"
                                      " 30 seconds.")

        return False, self.tr("conda could not be started.")
Esempio n. 14
0
    def runProcess(self, args, interpreter):
        """
        Public method to execute the current pip with the given arguments.
        
        The selected pip executable is called with the given arguments and
        waited for its end.
        
        @param args list of command line arguments
        @type list of str
        @param interpreter path of the Python interpreter to be used
        @type str
        @return tuple containing a flag indicating success and the output
            of the process
        @rtype tuple of (bool, str)
        """
        ioEncoding = Preferences.getSystem("IOEncoding")

        process = QProcess()
        process.start(interpreter, args)
        procStarted = process.waitForStarted()
        if procStarted:
            finished = process.waitForFinished(30000)
            if finished:
                if process.exitCode() == 0:
                    output = str(process.readAllStandardOutput(), ioEncoding,
                                 'replace')
                    return True, output
                else:
                    return (
                        False,
                        self.tr("python exited with an error ({0}).").format(
                            process.exitCode()))
            else:
                process.terminate()
                process.waitForFinished(2000)
                process.kill()
                process.waitForFinished(3000)
                return False, self.tr("python did not finish within"
                                      " 30 seconds.")

        return False, self.tr("python could not be started.")
Esempio n. 15
0
    def __setPyvenvVersion(self):
        """
        Private method to determine the pyvenv version and set the respective
        label.
        """
        calls = []
        if self.pythonExecEdit.text():
            calls.append((self.pythonExecEdit.text(), ["-m", "venv"]))
        calls.extend([
            (sys.executable.replace("w.exe", ".exe"), ["-m", "venv"]),
            ("python3", ["-m", "venv"]),
            ("python", ["-m", "venv"]),
        ])

        proc = QProcess()
        for prog, args in calls:
            proc.start(prog, args)

            if not proc.waitForStarted(5000):
                # try next entry
                continue

            if not proc.waitForFinished(5000):
                # process hangs, kill it
                QTimer.singleShot(2000, proc.kill)
                proc.waitForFinished(3000)
                version = self.tr('<pyvenv did not finish within 5s.>')
                self.__pyvenvFound = False
                break

            if proc.exitCode() not in [0, 2]:
                # returned with error code, try next
                continue

            proc.start(prog, ["--version"])
            proc.waitForFinished(5000)
            output = str(proc.readAllStandardOutput(),
                         Preferences.getSystem("IOEncoding"),
                         'replace').strip()
            match = re.match(self.__versionRe, output)
            if match:
                self.__pyvenvFound = True
                version = match.group(1)
                break
        else:
            self.__pyvenvFound = False
            version = self.tr('<No suitable pyvenv found.>')

        self.pyvenvButton.setText(
            self.tr("pyvenv Version: {0}".format(version)))
        self.pyvenvButton.setEnabled(self.__pyvenvFound)
        if not self.__pyvenvFound:
            self.pyvenvButton.setChecked(False)
 def __applyGuards(self):
     """
     Private slot to apply the defined guards to the current patch.
     """
     if self.__dirtyList:
         guardsList = []
         for row in range(self.guardsList.count()):
             itm = self.guardsList.item(row)
             guard = itm.data(Qt.UserRole) + itm.text()
             guardsList.append(guard)
         
         args = self.vcs.initCommand("qguard")
         args.append(self.patchNameLabel.text())
         if guardsList:
             args.append("--")
             args.extend(guardsList)
         else:
             args.append("--none")
         
         error = ""
         if self.__hgClient:
             error = self.__hgClient.runcommand(args)[1]
         else:
             process = QProcess()
             process.setWorkingDirectory(self.__repodir)
             process.start('hg', args)
             procStarted = process.waitForStarted(5000)
             if procStarted:
                 finished = process.waitForFinished(30000)
                 if finished:
                     if process.exitCode() != 0:
                         error = str(process.readAllStandardError(),
                                     self.vcs.getEncoding(), 'replace')
                 else:
                     E5MessageBox.warning(
                         self,
                         self.tr("Apply Guard Definitions"),
                         self.tr(
                             """The Mercurial process did not finish"""
                             """ in time."""))
         
         if error:
             E5MessageBox.warning(
                 self,
                 self.tr("Apply Guard Definitions"),
                 self.tr("""<p>The defined guards could not be"""
                         """ applied.</p><p>Reason: {0}</p>""")
                 .format(error))
         else:
                         self.__dirtyList = False
                         self.on_patchSelector_activated(
                             self.patchNameLabel.text())
 def __applyGuards(self):
     """
     Private slot to apply the defined guards to the current patch.
     """
     if self.__dirtyList:
         guardsList = []
         for row in range(self.guardsList.count()):
             itm = self.guardsList.item(row)
             guard = itm.data(Qt.UserRole) + itm.text()
             guardsList.append(guard)
         
         args = self.vcs.initCommand("qguard")
         args.append(self.patchNameLabel.text())
         if guardsList:
             args.append("--")
             args.extend(guardsList)
         else:
             args.append("--none")
         
         error = ""
         if self.__hgClient:
             error = self.__hgClient.runcommand(args)[1]
         else:
             process = QProcess()
             process.setWorkingDirectory(self.__repodir)
             process.start('hg', args)
             procStarted = process.waitForStarted(5000)
             if procStarted:
                 finished = process.waitForFinished(30000)
                 if finished:
                     if process.exitCode() != 0:
                         error = str(process.readAllStandardError(),
                                     self.vcs.getEncoding(), 'replace')
                 else:
                     E5MessageBox.warning(
                         self,
                         self.tr("Apply Guard Definitions"),
                         self.tr(
                             """The Mercurial process did not finish"""
                             """ in time."""))
         
         if error:
             E5MessageBox.warning(
                 self,
                 self.tr("Apply Guard Definitions"),
                 self.tr("""<p>The defined guards could not be"""
                         """ applied.</p><p>Reason: {0}</p>""")
                 .format(error))
         else:
                         self.__dirtyList = False
                         self.on_patchSelector_activated(
                             self.patchNameLabel.text())
Esempio n. 18
0
    def start(self):
        if self.launched_before:
            self.callDaemon()
            return

        ray_control_process = QProcess()
        ray_control_process.start("ray_control", ['get_port_gui_free'])
        ray_control_process.waitForFinished(2000)

        if ray_control_process.exitCode() == 0:
            port_str_lines = ray_control_process.readAllStandardOutput().data(
            ).decode('utf-8')
            port_str = port_str_lines.partition('\n')[0]

            if port_str and port_str.isdigit():
                self.address = Address(int(port_str))
                self.port = self.address.port
                self.url = self.address.url
                self.launched_before = True
                self.is_local = True
                self.callDaemon()
                return

        server = GUIServerThread.instance()
        if not server:
            sys.stderr.write(
                "impossible for GUI to launch daemon. server missing.\n")

        # start process
        arguments = [
            '--gui-url',
            str(server.url), '--osc-port',
            str(self.port), '--session-root', CommandLineArgs.session_root
        ]

        if CommandLineArgs.session:
            arguments.append('--session')
            arguments.append(CommandLineArgs.session)

        if CommandLineArgs.debug_only:
            arguments.append('--debug-only')
        elif CommandLineArgs.debug:
            arguments.append('--debug')
        elif CommandLineArgs.no_client_messages:
            arguments.append('--no-client-messages')

        if CommandLineArgs.config_dir:
            arguments.append('--config-dir')
            arguments.append(CommandLineArgs.config_dir)

        self.process.startDetached('ray-daemon', arguments)
Esempio n. 19
0
 def __getPatchesList(self, repodir, listType, withSummary=False):
     """
     Private method to get a list of patches of a given type.
     
     @param repodir directory name of the repository (string)
     @param listType type of patches list to get
         (Queues.APPLIED_LIST, Queues.UNAPPLIED_LIST, Queues.SERIES_LIST)
     @param withSummary flag indicating to get a summary as well (boolean)
     @return list of patches (list of string)
     @exception ValueError raised to indicate an invalid patch list type
     """
     patchesList = []
     
     if listType == Queues.APPLIED_LIST:
         args = self.vcs.initCommand("qapplied")
     elif listType == Queues.UNAPPLIED_LIST:
         args = self.vcs.initCommand("qunapplied")
     elif listType == Queues.SERIES_LIST:
         args = self.vcs.initCommand("qseries")
     else:
         raise ValueError("illegal value for listType")
     if withSummary:
         args.append("--summary")
     
     client = self.vcs.getClient()
     output = ""
     if client:
         output = client.runcommand(args)[0]
     else:
         process = QProcess()
         process.setWorkingDirectory(repodir)
         process.start('hg', args)
         procStarted = process.waitForStarted(5000)
         if procStarted:
             finished = process.waitForFinished(30000)
             if finished and process.exitCode() == 0:
                 output = str(process.readAllStandardOutput(),
                              self.vcs.getEncoding(), 'replace')
     
     for line in output.splitlines():
         if withSummary:
             li = line.strip().split(": ")
             if len(li) == 1:
                 patch, summary = li[0][:-1], ""
             else:
                 patch, summary = li[0], li[1]
             patchesList.append("{0}@@{1}".format(patch, summary))
         else:
             patchesList.append(line.strip())
     
     return patchesList
Esempio n. 20
0
def execute_exe_qprocess(exe_path, exe_param):
    process = QProcess()
    folder_path, file_name = os.path.split(exe_path)
    # 指定exe运行的路径
    process.setWorkingDirectory(folder_path)
    param = exe_param.split(" ")
    process.start(exe_path, param)
    # 设置超时时间20s,如果a=True,说明exe执行完毕。如果a=False,说明到达超时时间,关闭exe执行进程
    a = process.waitForFinished(20000)
    output = process.readAll()  # exe的输出信息
    returncode = process.exitCode()  # exe的返回值
    print(a)
    print(output)
    print(returncode)
Esempio n. 21
0
    def runProcess(self, args, cmd=""):
        """
        Public method to execute the current pip with the given arguments.
        
        The selected pip executable is called with the given arguments and
        waited for its end.
        
        @param args list of command line arguments (list of string)
        @param cmd pip command to be used (string)
        @return tuple containing a flag indicating success and the output
            of the process (string)
        """
        if not cmd:
            cmd = self.__plugin.getPreferences("CurrentPipExecutable")
        ioEncoding = Preferences.getSystem("IOEncoding")

        process = QProcess()
        process.start(cmd, args)
        procStarted = process.waitForStarted()
        if procStarted:
            finished = process.waitForFinished(30000)
            if finished:
                if process.exitCode() == 0:
                    output = str(process.readAllStandardOutput(), ioEncoding,
                                 'replace')
                    return True, output
                else:
                    return False, self.tr("pip exited with an error ({0}).")\
                        .format(process.exitCode())
            else:
                process.terminate()
                process.waitForFinished(2000)
                process.kill()
                process.waitForFinished(3000)
                return False, self.tr("pip did not finish within 30 seconds.")

        return False, self.tr("pip could not be started.")
Esempio n. 22
0
 def __repoRoot(self, url):
     """
     Private method to get the repository root using the svn info command.
     
     @param url the repository URL to browser (string)
     @return repository root (string)
     """
     ioEncoding = Preferences.getSystem("IOEncoding")
     repoRoot = None
     
     process = QProcess()
     
     args = []
     args.append('info')
     self.vcs.addArguments(args, self.vcs.options['global'])
     args.append('--xml')
     args.append(url)
     
     process.start('svn', args)
     procStarted = process.waitForStarted(5000)
     if procStarted:
         finished = process.waitForFinished(30000)
         if finished:
             if process.exitCode() == 0:
                 output = str(process.readAllStandardOutput(), ioEncoding,
                              'replace')
                 for line in output.splitlines():
                     line = line.strip()
                     if line.startswith('<root>'):
                         repoRoot = line.replace('<root>', '')\
                             .replace('</root>', '')
                         break
             else:
                 error = str(process.readAllStandardError(),
                             Preferences.getSystem("IOEncoding"),
                             'replace')
                 self.errors.insertPlainText(error)
                 self.errors.ensureCursorVisible()
     else:
         QApplication.restoreOverrideCursor()
         E5MessageBox.critical(
             self,
             self.tr('Process Generation Error'),
             self.tr(
                 'The process {0} could not be started. '
                 'Ensure, that it is in the search path.'
             ).format('svn'))
     return repoRoot
Esempio n. 23
0
 def __repoRoot(self, url):
     """
     Private method to get the repository root using the svn info command.
     
     @param url the repository URL to browser (string)
     @return repository root (string)
     """
     ioEncoding = Preferences.getSystem("IOEncoding")
     repoRoot = None
     
     process = QProcess()
     
     args = []
     args.append('info')
     self.vcs.addArguments(args, self.vcs.options['global'])
     args.append('--xml')
     args.append(url)
     
     process.start('svn', args)
     procStarted = process.waitForStarted(5000)
     if procStarted:
         finished = process.waitForFinished(30000)
         if finished:
             if process.exitCode() == 0:
                 output = str(process.readAllStandardOutput(), ioEncoding,
                              'replace')
                 for line in output.splitlines():
                     line = line.strip()
                     if line.startswith('<root>'):
                         repoRoot = line.replace('<root>', '')\
                             .replace('</root>', '')
                         break
             else:
                 error = str(process.readAllStandardError(),
                             Preferences.getSystem("IOEncoding"),
                             'replace')
                 self.errors.insertPlainText(error)
                 self.errors.ensureCursorVisible()
     else:
         QApplication.restoreOverrideCursor()
         E5MessageBox.critical(
             self,
             self.tr('Process Generation Error'),
             self.tr(
                 'The process {0} could not be started. '
                 'Ensure, that it is in the search path.'
             ).format('svn'))
     return repoRoot
Esempio n. 24
0
    def run(self, argv, error_message, in_build_dir=False, timeout=30000):
        """ Execute a command and capture the output. """

        if in_build_dir:
            project = self._project

            saved_cwd = os.getcwd()
            build_dir = project.path_from_user(project.build_dir)
            build_dir = QDir.toNativeSeparators(build_dir)
            os.chdir(build_dir)
            self._message_handler.verbose_message(
                "{0} is now the current directory".format(build_dir))
        else:
            saved_cwd = None

        self._message_handler.verbose_message("Running '{0}'".format(
            ' '.join(argv)))

        QCoreApplication.processEvents()

        process = QProcess()

        process.readyReadStandardOutput.connect(
            lambda: self._message_handler.progress_message(
                QTextCodec.codecForLocale().toUnicode(
                    process.readAllStandardOutput()).strip()))

        stderr_output = QByteArray()
        process.readyReadStandardError.connect(
            lambda: stderr_output.append(process.readAllStandardError()))

        process.start(argv[0], argv[1:])
        finished = process.waitForFinished(timeout)

        if saved_cwd is not None:
            os.chdir(saved_cwd)
            self._message_handler.verbose_message(
                "{0} is now the current directory".format(saved_cwd))

        if not finished:
            raise UserException(error_message, process.errorString())

        if process.exitStatus() != QProcess.NormalExit or process.exitCode(
        ) != 0:
            raise UserException(
                error_message,
                QTextCodec.codecForLocale().toUnicode(stderr_output).strip())
Esempio n. 25
0
    def run(self, argv, error_message, in_build_dir=False):
        """ Execute a command and capture the output. """

        if in_build_dir:
            project = self._project

            saved_cwd = os.getcwd()
            build_dir = project.path_from_user(project.build_dir)
            build_dir = QDir.toNativeSeparators(build_dir)
            os.chdir(build_dir)
            self._message_handler.verbose_message(
                    "{0} is now the current directory".format(build_dir))
        else:
            saved_cwd = None

        self._message_handler.verbose_message(
                "Running '{0}'".format(' '.join(argv)))

        QCoreApplication.processEvents()

        process = QProcess()

        process.readyReadStandardOutput.connect(
                lambda: self._message_handler.progress_message(
                        QTextCodec.codecForLocale().toUnicode(
                                process.readAllStandardOutput()).strip()))

        stderr_output = QByteArray()
        process.readyReadStandardError.connect(
                lambda: stderr_output.append(process.readAllStandardError()))

        process.start(argv[0], argv[1:])
        finished = process.waitForFinished()

        if saved_cwd is not None:
            os.chdir(saved_cwd)
            self._message_handler.verbose_message(
                    "{0} is now the current directory".format(saved_cwd))

        if not finished:
            raise UserException(error_message, process.errorString())

        if process.exitStatus() != QProcess.NormalExit or process.exitCode() != 0:
            raise UserException(error_message,
                    QTextCodec.codecForLocale().toUnicode(stderr_output).strip())
Esempio n. 26
0
    def on_patchSelector_activated(self, patch):
        """
        Private slot to get the list of guards for the given patch name.
        
        @param patch selected patch name (empty for current patch)
        """
        self.guardsList.clear()
        self.patchNameLabel.setText("")

        args = self.vcs.initCommand("qguard")
        if patch:
            args.append(patch)

        output = ""
        if self.__hgClient:
            output = self.__hgClient.runcommand(args)[0].strip()
        else:
            process = QProcess()
            process.setWorkingDirectory(self.__repodir)
            process.start('hg', args)
            procStarted = process.waitForStarted(5000)
            if procStarted:
                finished = process.waitForFinished(30000)
                if finished and process.exitCode() == 0:
                    output = str(process.readAllStandardOutput(),
                                 self.vcs.getEncoding(), 'replace').strip()

        if output:
            patchName, guards = output.split(":", 1)
            self.patchNameLabel.setText(patchName)
            guardsList = guards.strip().split()
            for guard in guardsList:
                if guard.startswith("+"):
                    icon = UI.PixmapCache.getIcon("plus.png")
                    guard = guard[1:]
                elif guard.startswith("-"):
                    icon = UI.PixmapCache.getIcon("minus.png")
                    guard = guard[1:]
                else:
                    icon = None
                    guard = self.tr("Unguarded")
                itm = QListWidgetItem(guard, self.guardsList)
                if icon:
                    itm.setIcon(icon)
Esempio n. 27
0
 def on_patchSelector_activated(self, patch):
     """
     Private slot to get the list of guards for the given patch name.
     
     @param patch selected patch name (empty for current patch)
     """
     self.guardsList.clear()
     self.patchNameLabel.setText("")
     
     args = self.vcs.initCommand("qguard")
     if patch:
         args.append(patch)
     
     output = ""
     if self.__hgClient:
         output = self.__hgClient.runcommand(args)[0].strip()
     else:
         process = QProcess()
         process.setWorkingDirectory(self.__repodir)
         process.start('hg', args)
         procStarted = process.waitForStarted(5000)
         if procStarted:
             finished = process.waitForFinished(30000)
             if finished and process.exitCode() == 0:
                 output = str(process.readAllStandardOutput(),
                              self.vcs.getEncoding(), 'replace').strip()
     
     if output:
         patchName, guards = output.split(":", 1)
         self.patchNameLabel.setText(patchName)
         guardsList = guards.strip().split()
         for guard in guardsList:
             if guard.startswith("+"):
                 icon = UI.PixmapCache.getIcon("plus.png")
                 guard = guard[1:]
             elif guard.startswith("-"):
                 icon = UI.PixmapCache.getIcon("minus.png")
                 guard = guard[1:]
             else:
                 icon = None
                 guard = self.tr("Unguarded")
             itm = QListWidgetItem(guard, self.guardsList)
             if icon:
                 itm.setIcon(icon)
Esempio n. 28
0
def qtDesignerStart():
    """ Set widgets/plugins paths and start QtDesigner """

    # Get base path and QProcess system environment
    base = os.path.dirname(__file__)
    env = QProcessEnvironment.systemEnvironment()

    # Path for tell python where it can find the widgets directory
    pybase = os.path.join(base, 'python')
    # Path for tell QtDesigner where it can find the plugins directory
    wbase = os.path.join(base, 'widgets')

    # Insert paths to QProcess system environment
    env.insert('PYQTDESIGNERPATH', pybase)
    env.insert('PYTHONPATH', wbase)

    # inform user
    inform('env add "PYQTDESIGNERPATH" plugins path - ' + pybase)
    inform('env add "PYTHONPATH" widgets path - ' + wbase)

    # Create QProcess and set environment
    designer = QProcess()
    designer.setProcessEnvironment(env)

    # Get QtDesigner binaries path
    designer_bin = QLibraryInfo.location(QLibraryInfo.BinariesPath)

    # Platform specefic
    if sys.platform == 'darwin':
        designer_bin += '/Designer.app/Contents/MacOS/Designer'
    else:
        designer_bin += '/designer'

    # inform user
    inform('designer bin - ' + designer_bin)
    inform('start QtDesigner...')

    # Start QtDesigner
    designer.start(designer_bin)
    designer.waitForFinished(-1)
    sys.exit(designer.exitCode())
Esempio n. 29
0
    def __getQueuesList(self):
        """
        Private method to get a list of all queues and the name of the active
        queue.
        
        @return tuple with a list of all queues and the name of the active
            queue (list of strings, string)
        """
        queuesList = []
        activeQueue = ""

        args = self.vcs.initCommand("qqueue")
        args.append("--list")

        output = ""
        if self.__hgClient:
            output = self.__hgClient.runcommand(args)[0]
        else:
            process = QProcess()
            process.setWorkingDirectory(self.__repodir)
            process.start('hg', args)
            procStarted = process.waitForStarted(5000)
            if procStarted:
                finished = process.waitForFinished(30000)
                if finished and process.exitCode() == 0:
                    output = str(process.readAllStandardOutput(),
                                 self.vcs.getEncoding(), 'replace')

        for queue in output.splitlines():
            queue = queue.strip()
            if queue.endswith(")"):
                queue = queue.rsplit(None, 1)[0]
                activeQueue = queue
            queuesList.append(queue)

        if self.__suppressActive:
            if activeQueue in queuesList:
                queuesList.remove(activeQueue)
            activeQueue = ""
        return queuesList, activeQueue
 def __getQueuesList(self):
     """
     Private method to get a list of all queues and the name of the active
     queue.
     
     @return tuple with a list of all queues and the name of the active
         queue (list of strings, string)
     """
     queuesList = []
     activeQueue = ""
     
     args = self.vcs.initCommand("qqueue")
     args.append("--list")
     
     output = ""
     if self.__hgClient:
         output = self.__hgClient.runcommand(args)[0]
     else:
         process = QProcess()
         process.setWorkingDirectory(self.__repodir)
         process.start('hg', args)
         procStarted = process.waitForStarted(5000)
         if procStarted:
             finished = process.waitForFinished(30000)
             if finished and process.exitCode() == 0:
                 output = str(process.readAllStandardOutput(),
                              self.vcs.getEncoding(), 'replace')
     
     for queue in output.splitlines():
         queue = queue.strip()
         if queue.endswith(")"):
             queue = queue.rsplit(None, 1)[0]
             activeQueue = queue
         queuesList.append(queue)
     
     if self.__suppressActive:
         if activeQueue in queuesList:
             queuesList.remove(activeQueue)
         activeQueue = ""
     return queuesList, activeQueue
Esempio n. 31
0
def run_qprocess(cmd: str, *args: str, cwd=None) -> str:
    """Run a shell command synchronously using QProcess.

    Args:
        cmd: The command to run.
        args: Any arguments passed to the command.
        cwd: Directory of the command to run in.
    Returns:
        The standard output of the command.
    Raises:
        OSError on failure.
    """
    process = QProcess()
    if cwd is not None:
        process.setWorkingDirectory(cwd)
    process.start(cmd, args)
    if not process.waitForFinished():
        raise OSError("Error waiting for process")
    if process.exitStatus() != QProcess.NormalExit or process.exitCode() != 0:
        stderr = qbytearray_to_str(process.readAllStandardError()).strip()
        raise OSError(stderr)
    return qbytearray_to_str(process.readAllStandardOutput()).strip()
Esempio n. 32
0
def load_cr3(path) -> QPixmap:
    """Extract the thumbnail from the image and initialize QPixmap"""

    process = QProcess()
    process.start(f"exiftool -b -JpgFromRaw {path}")
    process.waitForFinished()

    if process.exitStatus() != QProcess.NormalExit or process.exitCode() != 0:
        stderr = process.readAllStandardError()
        raise ValueError(f"Error calling exiftool: '{stderr.data().decode()}'")

    handler = QImageReader(process, "jpeg".encode())
    handler.setAutoTransform(True)

    process.closeWriteChannel()
    process.terminate()

    # Extract QImage from QImageReader and convert to QPixmap
    pixmap = QPixmap()
    pixmap.convertFromImage(handler.read())

    return pixmap
Esempio n. 33
0
def load_frame(path) -> QPixmap:
    """Extract the first frame from the video and initialize QPixmap"""

    process = QProcess()
    process.start(
        f"ffmpeg -loglevel quiet -i {path} -vframes 1 -f image2 pipe:1")
    process.waitForFinished()

    if process.exitStatus() != QProcess.NormalExit or process.exitCode() != 0:
        stderr = process.readAllStandardError()
        raise ValueError(f"Error calling ffmpeg: '{stderr.data().decode()}'")

    handler = QImageReader(process, "jpeg".encode())
    handler.setAutoTransform(True)

    process.closeWriteChannel()
    process.terminate()

    # Extract QImage from QImageReader and convert to QPixmap
    pixmap = QPixmap()
    pixmap.convertFromImage(handler.read())

    return pixmap
Esempio n. 34
0
 def getGuardsList(self, repodir, all=True):
     """
     Public method to get a list of all guards defined.
     
     @param repodir directory name of the repository (string)
     @param all flag indicating to get all guards (boolean)
     @return sorted list of guards (list of strings)
     """
     guardsList = []
     
     args = self.vcs.initCommand("qselect")
     if all:
         args.append("--series")
     
     client = self.vcs.getClient()
     output = ""
     if client:
         output = client.runcommand(args)[0]
     else:
         process = QProcess()
         process.setWorkingDirectory(repodir)
         process.start('hg', args)
         procStarted = process.waitForStarted(5000)
         if procStarted:
             finished = process.waitForFinished(30000)
             if finished and process.exitCode() == 0:
                 output = str(process.readAllStandardOutput(),
                              self.vcs.getEncoding(), 'replace')
     
     for guard in output.splitlines():
         guard = guard.strip()
         if all:
             guard = guard[1:]
         if guard not in guardsList:
             guardsList.append(guard)
     
     return sorted(guardsList)
Esempio n. 35
0
 def generateKey(self):
     qp = QProcess()
     qp.start("ssh-keygen",["-t",self._keytype,"-N",self._passphrase,"-f",self._filename])
     qp.waitForFinished(3000)
     self.keyGenerated.emit((qp.exitCode() == 0))
Esempio n. 36
0
 def hgQueueCreateRenameQueue(self, name, isCreate):
     """
     Public method to create a new queue or rename the active queue.
     
     @param name file/directory name (string)
     @param isCreate flag indicating to create a new queue (boolean)
     """
     # find the root of the repo
     repodir = self.vcs.splitPath(name)[0]
     while not os.path.isdir(os.path.join(repodir, self.vcs.adminDir)):
         repodir = os.path.dirname(repodir)
         if os.path.splitdrive(repodir)[1] == os.sep:
             return
     
     if isCreate:
         title = self.tr("Create New Queue")
     else:
         title = self.tr("Rename Active Queue")
     from .HgQueuesQueueManagementDialog import \
         HgQueuesQueueManagementDialog
     dlg = HgQueuesQueueManagementDialog(
         HgQueuesQueueManagementDialog.NAME_INPUT,
         title, False, repodir, self.vcs)
     if dlg.exec_() == QDialog.Accepted:
         queueName = dlg.getData()
         if queueName:
             args = self.vcs.initCommand("qqueue")
             if isCreate:
                 args.append("--create")
             else:
                 args.append("--rename")
             args.append(queueName)
             
             client = self.vcs.getClient()
             error = ""
             if client:
                 error = client.runcommand(args)[1]
             else:
                 process = QProcess()
                 process.setWorkingDirectory(repodir)
                 process.start('hg', args)
                 procStarted = process.waitForStarted(5000)
                 if procStarted:
                     finished = process.waitForFinished(30000)
                     if finished:
                         if process.exitCode() != 0:
                             error = str(process.readAllStandardError(),
                                         self.vcs.getEncoding(), 'replace')
             
             if error:
                 if isCreate:
                     errMsg = self.tr(
                         "Error while creating a new queue.")
                 else:
                     errMsg = self.tr(
                         "Error while renaming the active queue.")
                 E5MessageBox.warning(
                     None,
                     title,
                     """<p>{0}</p><p>{1}</p>""".format(errMsg, error))
             else:
                 if self.queuesListQueuesDialog is not None and \
                    self.queuesListQueuesDialog.isVisible():
                     self.queuesListQueuesDialog.refresh()
 def on_patchSelector_activated(self, patch):
     """
     Private slot to get the list of guards defined for the given patch
     name.
     
     @param patch selected patch name (empty for current patch)
     """
     if self.__dirtyList:
         res = E5MessageBox.question(
             self,
             self.tr("Unsaved Changes"),
             self.tr("""The guards list has been changed."""
                     """ Shall the changes be applied?"""),
             E5MessageBox.StandardButtons(
                 E5MessageBox.Apply |
                 E5MessageBox.Discard),
             E5MessageBox.Apply)
         if res == E5MessageBox.Apply:
             self.__applyGuards()
         else:
             self.__dirtyList = False
     
     self.guardsList.clear()
     self.patchNameLabel.setText("")
     
     self.guardCombo.clear()
     guardsList = self.extension.getGuardsList(self.__repodir)
     self.guardCombo.addItems(guardsList)
     self.guardCombo.setEditText("")
     
     args = self.vcs.initCommand("qguard")
     if patch:
         args.append(patch)
     
     output = ""
     if self.__hgClient:
         output = self.__hgClient.runcommand(args)[0]
     else:
         process = QProcess()
         process.setWorkingDirectory(self.__repodir)
         process.start('hg', args)
         procStarted = process.waitForStarted(5000)
         if procStarted:
             finished = process.waitForFinished(30000)
             if finished and process.exitCode() == 0:
                 output = str(process.readAllStandardOutput(),
                              self.vcs.getEncoding(), 'replace').strip()
     
     if output:
         patchName, guards = output.split(":", 1)
         self.patchNameLabel.setText(patchName)
         guardsList = guards.strip().split()
         for guard in guardsList:
             if guard.startswith("+"):
                 icon = UI.PixmapCache.getIcon("plus.png")
                 guard = guard[1:]
                 sign = "+"
             elif guard.startswith("-"):
                 icon = UI.PixmapCache.getIcon("minus.png")
                 guard = guard[1:]
                 sign = "-"
             else:
                 continue
             itm = QListWidgetItem(icon, guard, self.guardsList)
             itm.setData(Qt.UserRole, sign)
     
     self.on_guardsList_itemSelectionChanged()
Esempio n. 38
0
 def _performMonitor(self):
     """
     Protected method implementing the monitoring action.
     
     This method populates the statusList member variable
     with a list of strings giving the status in the first column and the
     path relative to the project directory starting with the third column.
     The allowed status flags are:
     <ul>
         <li>"A" path was added but not yet comitted</li>
         <li>"M" path has local changes</li>
         <li>"O" path was removed</li>
         <li>"R" path was deleted and then re-added</li>
         <li>"U" path needs an update</li>
         <li>"Z" path contains a conflict</li>
         <li>" " path is back at normal</li>
     </ul>
     
     @return tuple of flag indicating successful operation (boolean) and
         a status message in case of non successful operation (string)
     """
     self.shouldUpdate = False
     
     if self.__client is None and not self.__useCommandLine:
         if self.vcs.version >= (2, 9, 9):
             # versions below that have a bug causing a second
             # instance to not recognize changes to the status
             from .HgClient import HgClient
             client = HgClient(self.projectDir, "utf-8", self.vcs)
             ok, err = client.startServer()
             if ok:
                 self.__client = client
             else:
                 self.__useCommandLine = True
         else:
             self.__useCommandLine = True
     
     # step 1: get overall status
     args = self.vcs.initCommand("status")
     args.append('--noninteractive')
     args.append('--all')
     
     output = ""
     error = ""
     if self.__client:
         output, error = self.__client.runcommand(args)
     else:
         process = QProcess()
         process.setWorkingDirectory(self.projectDir)
         process.start('hg', args)
         procStarted = process.waitForStarted(5000)
         if procStarted:
             finished = process.waitForFinished(300000)
             if finished and process.exitCode() == 0:
                 output = str(process.readAllStandardOutput(),
                              self.vcs.getEncoding(), 'replace')
             else:
                 process.kill()
                 process.waitForFinished()
                 error = str(process.readAllStandardError(),
                             self.vcs.getEncoding(), 'replace')
         else:
             process.kill()
             process.waitForFinished()
             error = self.tr("Could not start the Mercurial process.")
     
     if error:
         return False, error
     
     states = {}
     for line in output.splitlines():
         if not line.startswith("  "):
             flag, name = line.split(" ", 1)
             if flag in "AMR":
                 if flag == "R":
                     status = "O"
                 else:
                     status = flag
                 states[name] = status
     
     # step 2: get conflicting changes
     args = self.vcs.initCommand("resolve")
     args.append('--list')
     
     output = ""
     error = ""
     if self.__client:
         output, error = self.__client.runcommand(args)
     else:
         process.setWorkingDirectory(self.projectDir)
         process.start('hg', args)
         procStarted = process.waitForStarted(5000)
         if procStarted:
             finished = process.waitForFinished(300000)
             if finished and process.exitCode() == 0:
                 output = str(process.readAllStandardOutput(),
                              self.vcs.getEncoding(), 'replace')
     
     for line in output.splitlines():
         flag, name = line.split(" ", 1)
         if flag == "U":
             states[name] = "Z"  # conflict
     
     # step 3: collect the status to be reported back
     for name in states:
         try:
             if self.reportedStates[name] != states[name]:
                 self.statusList.append(
                     "{0} {1}".format(states[name], name))
         except KeyError:
             self.statusList.append("{0} {1}".format(states[name], name))
     for name in self.reportedStates.keys():
         if name not in states:
             self.statusList.append("  {0}".format(name))
     self.reportedStates = states
     
     return True, \
         self.tr("Mercurial status checked successfully")
Esempio n. 39
0
class MainWindow(QMainWindow,Ui_MainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()

        self.start_logo()

        self.setupUi(self)
        self.sysencoding =sys.stdout.encoding
        #self.centralWidget = PyPreviewer(self)
        #self.setCentralWidget(self.centralWidget)
        self.setupEditor()

        self.setWindowIcon(QIcon('PyPreviewer.ico'))


        #메뉴 이벤트 생성
        self.createEvent()

        self.dirty = False
        self.plainTextEdit_2.textChanged.connect(self.setDirty)
        self.fileName = None
        self.plainTextEdit_2.setTabStopWidth(35)
        self.plainTextEdit_2.setPlainText("# -*- coding: utf-8 -*-\n# 반갑습니다~\n# #은 파이썬에서 주석입니다.\nprint(\"이 부분은 출력창입니다.\")\nprint(\"구구단 예제\")\nfor i in range(2,10):\n\tprint(i,\"단\")\n\tfor j in range(2,10):\n\t\tprint(i,\"X\", j, \"=\", i*j)\n# 파이썬 실행은 아래 실행버튼을 눌러주세요.\n# 파이썬 학습 관련 및 예제는 왼쪽 화면을 이용하시기 바랍니다.")

        #web view
        #self.exampleView.load(QUrl("http://www.google.com"))
        self.startfilepath=os.getcwd() +"/PyStudy_web/Main.html"
        self.exampleView.load(QUrl.fromLocalFile(self.startfilepath))
        self.locationEdit = QLineEdit(self)
        self.locationEdit.setSizePolicy(QSizePolicy.Expanding,
                self.locationEdit.sizePolicy().verticalPolicy())
        self.locationEdit.returnPressed.connect(self.changeLocation)

        toolBar = QToolBar()
        self.addToolBar(toolBar)
        self.insertToolBarBreak(toolBar)
        toolBar.addAction(self.exampleView.pageAction(QWebPage.Back))
        toolBar.addAction(self.exampleView.pageAction(QWebPage.Forward))
        toolBar.addAction(self.action_myHome)
        toolBar.addAction(self.exampleView.pageAction(QWebPage.Reload))
        #toolBar.addAction(self.exampleView.pageAction(QWebPage.Stop))
        toolBar.addWidget(self.locationEdit)



        #사용자 입력 파이썬 파일 실행
        print ('Connecting process')
        self.process = QProcess(self)
        self.process.setProcessChannelMode(QProcess.SeparateChannels)
        self.process.setInputChannelMode(QProcess.ManagedInputChannel)

        self.process.readyReadStandardOutput.connect(self.stdoutReady)
        self.process.readyReadStandardError.connect(self.stderrReady)
        self.process.started.connect(lambda: print('ExampleProgramStarted!'))
        self.process.finished.connect(lambda:print('ExampleProgramFinished!'))
        print('Starting process')
        #self.process.start('python', ['ExampleTest.py'])

    def start_logo(self):
        img_logo = QPixmap('pystudylogo.png')
        self.splash = QSplashScreen(img_logo, Qt.WindowStaysOnTopHint)
        self.splash.setMask(img_logo.mask())
        self.splash.show()
        time.sleep(1.8)
        self.splash.close()
    def show_logo(self):
        img_logo = QPixmap('pystudylogo.png')
        self.splash = QSplashScreen(img_logo, Qt.WindowStaysOnTopHint)
        self.splash.setMask(img_logo.mask())
        self.splash.show()
        self.splash.repaint()
    def createEvent(self):
        self.ProgramRunButton.clicked.connect(self.clickAction_ProgramRunButton)
        self.ProgramStopButton.clicked.connect(self.clickAction_ProgramStopButton)
        self.actionRun.triggered.connect(self.clickAction_ProgramRunButton)
        self.actionStop.triggered.connect(self.clickAction_ProgramStopButton)
        self.ClearButton.clicked.connect(self.clickAction_ProgramEraseButton)
        self.actionClear.triggered.connect(self.clickAction_ProgramEraseButton)
        self.actionNew_File.triggered.connect(self.clickAction_fileNew)
        self.actionFile_Open.triggered.connect(self.clickAction_fileOpen)
        self.actionFile_Save.triggered.connect(self.clickAction_fileSave)
        self.actionFile_Save_as.triggered.connect(self.clickAction_fileSaveAs)
        self.action_example.triggered.connect(self.clickAction_exampleOpen)
        self.actionPythonHelp.triggered.connect(self.clickAction_PythonHelp)
        self.actionHelp.triggered.connect(self.clickAction_ProgramHelp)
        self.MessagepushButton.clicked.connect(self.clickAction_MessagePushButton)
        self.actionStyleSheet_default.triggered.connect(self.clickAction_styleDefault)
        self.actionStyleSheet_Black.triggered.connect(self.clickAction_styleBlack)
        self.actionStyleSheet_Load.triggered.connect(self.clickAction_styleLoad)
        self.actionAbout_PyStudy.triggered.connect(self.show_logo)
        self.action_myHome.triggered.connect(self.go_myHome)
        self.action_exit.triggered.connect(self.close)
    def setDirty(self):
        #'On change of text in textEdit window, set the flag "dirty" to True''
        if self.dirty:
            return True
        self.dirty = True
        self.updateStatus('소스 수정중...')

    def clearDirty(self):
        #'''Clear the dirty flag and update status'''
        self.dirty = False

    def updateStatus(self, message):
        if self.fileName is not None:
            flbase = os.path.basename(self.fileName)
            self.setWindowTitle("PyStudy Simple Editor - " + flbase + "[*]" )
            self.statusBar().showMessage(message, 3000)
        self.setWindowModified(self.dirty)
    def clickAction_exampleOpen(self):
        fname, filter = QFileDialog.getOpenFileName(self, "예제파일 열기창", '.', "HTML File(*.html *.htm)")
        if not (fname == ""):
            #self.exampleView.load(QUrl(fname))
            self.exampleView.setUrl(QUrl.fromLocalFile(fname))
            #self.plainTextEdit_2.setPlainText(codecs.open(fname, "r", "utf-8" ).read())
            #self.fileName = fname
        else:
            return
        self.updateStatus('example File opened.')
    def clickAction_exampleDirectOpen(self,fname):
        if not (fname == ""):
            fname = os.getcwd()+r"\\"+fname
            print(fname)
            self.exampleView.setUrl(QUrl.fromLocalFile(fname))
        else:
            return
        self.updateStatus('example File opened.')

    def clickAction_fileNew(self):
        #'''Clear the editor window for a new file with name specified in fileSaveAs method.'''
        self.plainTextEdit_2.clear()
        self.statusBar().showMessage('새 소스파일 생성', 8000)
        self.dirty = False
        self.fileName = None

    def clickAction_fileOpen(self):
        fname, filter = QFileDialog.getOpenFileName(self, "소스파일 열기창", '.', "Python File(*.py)")
        if not (fname == ""):
            self.plainTextEdit_2.setPlainText(codecs.open(fname, "r", "utf-8" ).read())
            self.fileName = fname
        else:
            return
        self.clearDirty()
        self.updateStatus('File opened.')


    def clickAction_fileSave(self):
        if self.fileName is None:
            return self.clickAction_fileSaveAs()
        else:
            fname = self.fileName
            fl = codecs.open(fname, "w", "utf-8" )
            tempText = self.plainTextEdit_2.toPlainText()
            if tempText:
                fl.write(tempText)
                fl.close()
                self.clearDirty()
                self.updateStatus('Saved file')
                return True
            else:
                self.statusBar().showMessage('파일 저장 실패 ...', 5000)
                return False

    def clickAction_fileSaveAs(self):
        path = self.fileName if self.fileName is not None else "."
        fname,filter = QFileDialog.getSaveFileName(self,
                        "다른이름으로 저장", path, "Python File(*.py)")
        if fname:
            if "." not in fname:
                fname += ".py"
            self.fileName = fname
            self.clickAction_fileSave()
            self.statusBar().showMessage('SaveAs file' + fname, 8000)
            self.clearDirty()
    def clickAction_ProgramRunButton(self):
        self.clickAction_fileSave()
        self.process.start('python', [self.fileName],QIODevice.ReadWrite)
    def clickAction_ProgramStopButton(self):
        self.process.kill()
        self.append_plainTextEdit_3("\n\n프로세스 정지 with exit code "+str(self.process.exitCode())+"\n\n")
    def clickAction_ProgramEraseButton(self):
        self.plainTextEdit_3.clear()
    def append_plainTextEdit_3(self, text):
        cursor = self.plainTextEdit_3.textCursor()
        cursor.movePosition(cursor.End)
        cursor.insertText(text)
        #self.output.ensureCursorVisible()

    def stdoutReady(self):
        if self.sysencoding == "cp949":
            text = str(self.process.readAllStandardOutput(), "cp949")#독립실행시
        elif self.sysencoding == "UTF-8":
            text = str(self.process.readAllStandardOutput(), "utf-8")#pycharm
        else:
            text = str(self.process.readAllStandardOutput(), "cp949")#독립실행시
        self.append_plainTextEdit_3(text)

    def stderrReady(self):
        if self.sysencoding == "cp949":
            text = str(self.process.readAllStandardError(), "cp949")#독립실행시
        elif self.sysencoding == "UTF-8":
            text = str(self.process.readAllStandardError(), "utf-8")#pycharm
        else:
            text = str(self.process.readAllStandardError(), "cp949")#독립실행시
        self.append_plainTextEdit_3(text)

    def clickAction_PythonHelp(self):
        temppath=os.path.abspath('..')+r"\파이썬도움말\animation.py"
        tempoption = os.path.abspath('..')+r"\파이썬도움말"
        pythonhelp_process=QProcess()
        pythonhelp_process.start('python', [temppath,tempoption])
        pythonhelp_process.started()
        #  TypeError: native Qt signal is not callable
    def clickAction_MessagePushButton(self):
        temp = self.messagelineEdit.text()
        self.append_plainTextEdit_3(temp)
        self.append_plainTextEdit_3("\n")
        bArray = QByteArray()

        if self.sysencoding == "cp949":
            bArray.append(temp.encode(encoding='cp949',errors='ignore'))#독립실행시
        elif self.sysencoding == "UTF-8":
            bArray.append(temp.encode(encoding='utf-8',errors='ignore'))#pycharm
        else:
            bArray.append(temp.encode(encoding='cp949',errors='ignore'))#독립실행시
        bArray.append("\n")
        if( self.process.write(bArray) == -1):
            print("chlidprocess write error")
        self.messagelineEdit.clear()
    def clickAction_styleLoad(self):
        fname, filter = QFileDialog.getOpenFileName(self, "QT스타일시트파일 불러오기", '.', "Qt-StyleSheet(*.qss)")
        if fname:
            file = QFile(fname)
            file.open(QFile.ReadOnly)
            styleSheet = file.readAll()
            styleSheet = str(styleSheet, encoding='utf8') # Python v3.
            self.setStyleSheet(styleSheet)
            print ("test")
    def clickAction_styleDefault(self):
        self.set_StyleSheet("default")
    def clickAction_styleBlack(self):
        self.set_StyleSheet("black")
    def clickAction_ProgramHelp(self):
        self.startfilepath=os.getcwd() +"/PyStudy_web/Pystudy.html"
        self.exampleView.load(QUrl.fromLocalFile(self.startfilepath))
    def set_StyleSheet(self, sheetName):
        if sheetName:
            file = QFile('stylesheet/%s.qss' % sheetName.lower())
            file.open(QFile.ReadOnly)
            styleSheet = file.readAll()
            styleSheet = str(styleSheet, encoding='utf8') # Python v3.
            self.setStyleSheet(styleSheet)

    def setupEditor(self):
        font = QFont()
        font.setFamily('Courier')
        font.setFixedPitch(True)
        font.setPointSize(10)

        self.editor = self.plainTextEdit_2
        self.editor.setFont(font)
        self.highlighter = Highlighter(self.editor.document())

    def changeLocation(self):
        url = QUrl.fromUserInput(self.locationEdit.text())
        self.exampleView.load(url)
        self.exampleView.setFocus()
    def go_myHome(self):
        self.exampleView.load(QUrl.fromLocalFile(self.startfilepath))
        self.exampleView.setFocus()
Esempio n. 40
0
class Process(QObject):
    """
    Use the QProcess mechanism to run a subprocess asynchronously

    This will interact well with Qt Gui objects, eg by connecting the
    `output` signals to an `QTextEdit.append` method and the `started`
    and `finished` signals to a `QPushButton.setEnabled`.

    eg::
        import sys
        from PyQt5.QtCore import *
        from PyQt5.QtWidgets import *

        class Example(QMainWindow):

            def __init__(self):
                super().__init__()
                textEdit = QTextEdit()

                self.setCentralWidget(textEdit)
                self.setGeometry(300, 300, 350, 250)
                self.setWindowTitle('Main window')
                self.show()

                self.process = Process()
                self.process.output.connect(textEdit.append)
                self.process.run(sys.executable, ["-u", "-m", "pip", "list"])

        def main():
            app = QApplication(sys.argv)
            ex = Example()
            sys.exit(app.exec_())
    """

    started = pyqtSignal()
    output = pyqtSignal(str)
    finished = pyqtSignal()
    Slots = namedtuple("Slots", ["started", "output", "finished"])
    Slots.__new__.__defaults__ = (None, None, None)

    def __init__(self):
        super().__init__()
        #
        # Always run unbuffered and with UTF-8 IO encoding
        #
        self.environment = QProcessEnvironment.systemEnvironment()
        self.environment.insert("PYTHONUNBUFFERED", "1")
        self.environment.insert("PYTHONIOENCODING", "utf-8")

    def _set_up_run(self, **envvars):
        """Set up common elements of a QProcess run"""
        self.process = QProcess()
        environment = QProcessEnvironment(self.environment)
        for k, v in envvars.items():
            environment.insert(k, v)
        self.process.setProcessEnvironment(environment)
        self.process.setProcessChannelMode(QProcess.MergedChannels)

    def run_blocking(self, command, args, wait_for_s=30.0, **envvars):
        """Run `command` with `args` via QProcess, passing `envvars` as
        environment variables for the process.

        Wait `wait_for_s` seconds for completion and return any stdout/stderr
        """
        logger.info(
            "About to run blocking %s with args %s and envvars %s",
            command,
            args,
            envvars,
        )
        self._set_up_run(**envvars)
        self.process.start(command, args)
        return self.wait(wait_for_s=wait_for_s)

    def run(self, command, args, **envvars):
        """Run `command` asynchronously with `args` via QProcess, passing `envvars`
        as environment variables for the process."""
        logger.info(
            "About to run %s with args %s and envvars %s",
            command,
            args,
            envvars,
        )
        self._set_up_run(**envvars)
        self.process.readyRead.connect(self._readyRead)
        self.process.started.connect(self._started)
        self.process.finished.connect(self._finished)
        partial = functools.partial(self.process.start, command, args)
        QTimer.singleShot(1, partial)

    def wait(self, wait_for_s=30):
        """Wait for the process to complete, optionally timing out.
        Return any stdout/stderr.

        If the process fails to complete in time or returns an error, raise a
        VirtualEnvironmentError
        """
        finished = self.process.waitForFinished(int(1000 * wait_for_s))
        exit_status = self.process.exitStatus()
        exit_code = self.process.exitCode()
        output = self.data()
        #
        # if waitForFinished completes, either the process has successfully finished
        # or it crashed, was terminated or timed out. If it does finish successfully
        # we might still have an error code. In each case we might still have data
        # from stdout/stderr. Unfortunately there's no way to determine that the
        # process was timed out, as opposed to crashing in some other way
        #
        # The three elements in play are:
        #
        # finished (yes/no)
        # exitStatus (normal (0) / crashed (1)) -- we don't currently distinguish
        # exitCode (whatever the program returns; conventionally 0 => ok)
        #
        logger.debug(
            "Finished: %s; exitStatus %s; exitCode %s",
            finished,
            exit_status,
            exit_code,
        )

        #
        # Exceptions raised here will be caught by the crash-handler which will try to
        # generate a URI out of it. There's an upper limit on URI size of ~2000
        #
        if not finished:
            logger.error(compact(output))
            raise VirtualEnvironmentError(
                "Process did not terminate normally:\n" + compact(output))

        if exit_code != 0:
            #
            # We finished normally but we might still have an error-code on finish
            #
            logger.error(compact(output))
            raise VirtualEnvironmentError(
                "Process finished but with error code %d:\n%s" %
                (exit_code, compact(output)))

        return output

    def data(self):
        """Return all the data from the running process, converted to unicode"""
        output = self.process.readAll().data()
        return output.decode(ENCODING, errors="replace")

    def _started(self):
        self.started.emit()

    def _readyRead(self):
        self.output.emit(self.data().strip())

    def _finished(self):
        self.finished.emit()
Esempio n. 41
0
 def hgQueueDeletePurgeActivateQueue(self, name, operation):
     """
     Public method to delete the reference to a queue and optionally
     remove the patch directory or set the active queue.
     
     @param name file/directory name (string)
     @param operation operation to be performed (Queues.QUEUE_DELETE,
         Queues.QUEUE_PURGE, Queues.QUEUE_ACTIVATE)
     @exception ValueError raised to indicate an invalid operation
     """
     # find the root of the repo
     repodir = self.vcs.splitPath(name)[0]
     while not os.path.isdir(os.path.join(repodir, self.vcs.adminDir)):
         repodir = os.path.dirname(repodir)
         if os.path.splitdrive(repodir)[1] == os.sep:
             return
     
     if operation == Queues.QUEUE_PURGE:
         title = self.tr("Purge Queue")
     elif operation == Queues.QUEUE_DELETE:
         title = self.tr("Delete Queue")
     elif operation == Queues.QUEUE_ACTIVATE:
         title = self.tr("Activate Queue")
     else:
         raise ValueError("illegal value for operation")
     
     from .HgQueuesQueueManagementDialog import \
         HgQueuesQueueManagementDialog
     dlg = HgQueuesQueueManagementDialog(
         HgQueuesQueueManagementDialog.QUEUE_INPUT,
         title, True, repodir, self.vcs)
     if dlg.exec_() == QDialog.Accepted:
         queueName = dlg.getData()
         if queueName:
             args = self.vcs.initCommand("qqueue")
             if operation == Queues.QUEUE_PURGE:
                 args.append("--purge")
             elif operation == Queues.QUEUE_DELETE:
                 args.append("--delete")
             args.append(queueName)
             
             client = self.vcs.getClient()
             error = ""
             if client:
                 error = client.runcommand(args)[1]
             else:
                 process = QProcess()
                 process.setWorkingDirectory(repodir)
                 process.start('hg', args)
                 procStarted = process.waitForStarted(5000)
                 if procStarted:
                     finished = process.waitForFinished(30000)
                     if finished:
                         if process.exitCode() != 0:
                             error = str(process.readAllStandardError(),
                                         self.vcs.getEncoding(), 'replace')
             
             if error:
                 if operation == Queues.QUEUE_PURGE:
                     errMsg = self.tr("Error while purging the queue.")
                 elif operation == Queues.QUEUE_DELETE:
                     errMsg = self.tr("Error while deleting the queue.")
                 elif operation == Queues.QUEUE_ACTIVATE:
                     errMsg = self.tr(
                         "Error while setting the active queue.")
                 E5MessageBox.warning(
                     None,
                     title,
                     """<p>{0}</p><p>{1}</p>""".format(errMsg, error))
             else:
                 if self.queuesListQueuesDialog is not None and \
                    self.queuesListQueuesDialog.isVisible():
                     self.queuesListQueuesDialog.refresh()
Esempio n. 42
0
def parse_asn1(*files, **options):
    """ Call the ASN.1 parser on a number of files, and return the module
        containing the AST
        This function uses QProcess to launch the ASN.1 compiler because
        the subprocess module from Python has issues on the Windows platform
    """
    global AST

    ast_version = options.get("ast_version", ASN1.UniqueEnumeratedNames)
    flags = options.get("flags", [ASN1.AstOnly])
    assert isinstance(ast_version, ASN1)
    assert isinstance(flags, list)
    # if os.name == 'posix' and hasattr(sys, 'frozen'):
    # Frozen Linux binaries are expected to use the frozen ASN.1 compiler
    # No: there are issues with freezing the .NET applications - discard
    #     asn1exe = 'asn1scc'
    # else:
    #    asn1exe = 'asn1.exe'
    path_to_asn1scc = spawn.find_executable("asn1.exe")

    if not path_to_asn1scc:
        raise TypeError("ASN.1 Compiler not found in path")
    if os.name == "posix":
        path_to_mono = spawn.find_executable("mono")
        if not path_to_mono:
            raise TypeErorr('"mono" not found in path. Please install it.')
        binary = path_to_mono
        arg0 = path_to_asn1scc
    else:
        binary = path_to_asn1scc
        arg0 = ""
    asn1scc_root = os.path.abspath(os.path.dirname(path_to_asn1scc))
    # Create a temporary directory to store dataview.py and import it
    tempdir = tempfile.mkdtemp()
    sys.path.append(tempdir)
    if os.name == "nt":
        # On windows, remove the drive letter, workaround to ASN1SCC bug
        tempdir = tempdir[2:]
        asn1scc_root = asn1scc_root[2:]
    filename = str(uuid.uuid4()).replace("-", "_")
    filepath = tempdir + os.sep + filename + ".py"

    stg = asn1scc_root + os.sep + "python.stg"

    args = [arg0, "-customStgAstVerion", str(ast_version.value), "-customStg", stg + ":" + filepath] + list(*files)
    asn1scc = QProcess()
    LOG.debug(os.getcwd())
    LOG.debug(binary + " " + " ".join(args))
    asn1scc.start(binary, args)
    if not asn1scc.waitForStarted():
        raise TypeError("Could not start ASN.1 Compiler")
    if not asn1scc.waitForFinished():
        raise TypeError("Execution of ASN.1 Compiler timed out")
    exitcode = asn1scc.exitCode()
    result = asn1scc.readAllStandardError()
    if exitcode != 0:
        raise TypeError("ASN.1 Compiler Error (exit code = {}) - {}".format(exitcode, str(result)))
    else:
        if filename in AST.viewkeys():
            # Re-import module if it was already loaded
            ast = AST[filename]
            reload(ast)
        else:
            ast = importlib.import_module(filename)
            AST[filename] = ast
        return ast
Esempio n. 43
0
""" This Designer script is an utility that can be used to run the Qt Designer tool interface
    adding automatically the environment variables needed to detect the new widget plugins from the project.
"""

# PyQt5 modules
from PyQt5.QtCore import QProcess, QProcessEnvironment

# Python modules
import os

if __name__ == "__main__":
    designer_bin = 'designer'

    plugin_path = os.path.join(os.path.dirname(__file__), 'plugins')
    widget_path = os.path.join(os.path.dirname(__file__), 'src', 'widgets')
    custom_path = os.path.join(os.path.dirname(__file__), 'src')
    project_path = os.path.join(os.path.dirname(__file__))

    env = QProcessEnvironment.systemEnvironment()
    env.insert('PYQTDESIGNERPATH', plugin_path)
    env.insert('PYTHONPATH', f"{widget_path};{custom_path};{project_path}")

    designer = QProcess()
    designer.setProcessEnvironment(env)
    designer.start(designer_bin)
    designer.waitForFinished(-1)
    designer.exitCode()
Esempio n. 44
0
        "modules.</p>"
        "<p>It also sets the <tt>PYTHONPATH</tt> environment variable to the "
        "<tt>widgets</tt> directory that is also part of this example.  This "
        "directory contains the Python modules that implement the example "
        "custom widgets.</p>"
        "<p>All of the example custom widgets should then appear in "
        "Designer's widget box in the <b>PyQt Examples</b> group.</p>")

# Tell Qt Designer where it can find the directory containing the plugins and
# Python where it can find the widgets.
base = os.path.dirname(__file__)
env = QProcessEnvironment.systemEnvironment()
env.insert('PYQTDESIGNERPATH', os.path.join(base, 'python'))
env.insert('PYTHONPATH', os.path.join(base, 'widgets'))

# Start Designer.
designer = QProcess()
designer.setProcessEnvironment(env)

designer_bin = QLibraryInfo.location(QLibraryInfo.BinariesPath)

if sys.platform == 'darwin':
    designer_bin += '/Designer.app/Contents/MacOS/Designer'
else:
    designer_bin += '/designer'

designer.start(designer_bin)
designer.waitForFinished(-1)

sys.exit(designer.exitCode())
Esempio n. 45
0
class VideoService(QObject):
    def __init__(self, parent):
        super(VideoService, self).__init__(parent)
        self.parent = parent
        self.consoleOutput = ''
        if sys.platform == 'win32':
            self.backend = os.path.join(self.getAppPath(), 'bin', 'ffmpeg.exe')
            if not os.path.exists(self.backend):
                self.backend = find_executable('ffmpeg.exe')
        elif sys.platform == 'darwin':
            self.backend = os.path.join(self.getAppPath(), 'bin', 'ffmpeg')
        else:
            for exe in ('ffmpeg', 'avconv'):
                exe_path = find_executable(exe)
                if exe_path is not None:
                    self.backend = exe_path
                    break
        self.initProc()

    def initProc(self) -> None:
        self.proc = QProcess(self.parent)
        self.proc.setProcessChannelMode(QProcess.MergedChannels)
        env = QProcessEnvironment.systemEnvironment()
        self.proc.setProcessEnvironment(env)
        self.proc.setWorkingDirectory(self.getAppPath())
        if hasattr(self.proc, 'errorOccurred'):
            self.proc.errorOccurred.connect(self.cmdError)

    def capture(self, source: str, frametime: str) -> QPixmap:
        img, capres = None, QPixmap()
        try:
            img = QTemporaryFile(os.path.join(QDir.tempPath(), 'XXXXXX.jpg'))
            if img.open():
                imagecap = img.fileName()
                args = '-ss %s -i "%s" -vframes 1 -s 100x70 -y %s' % (
                    frametime, source, imagecap)
                if self.cmdExec(self.backend, args):
                    capres = QPixmap(imagecap, 'JPG')
        finally:
            del img
        return capres

    def cut(self, source: str, output: str, frametime: str,
            duration: str) -> bool:
        args = '-i "%s" -ss %s -t %s -vcodec copy -acodec copy -y "%s"' \
               % (source, frametime, duration, QDir.fromNativeSeparators(output))
        return self.cmdExec(self.backend, args)

    def join(self, filelist: list, output: str) -> bool:
        args = '-f concat -safe 0 -i "%s" -c copy -y "%s"' % (
            filelist, QDir.fromNativeSeparators(output))
        return self.cmdExec(self.backend, args)

    def cmdExec(self, cmd: str, args: str = None) -> bool:
        if os.getenv('DEBUG', False):
            print('VideoService CMD: %s %s' % (cmd, args))
        if self.proc.state() == QProcess.NotRunning:
            self.proc.start(cmd, shlex.split(args))
            self.proc.waitForFinished(-1)
            if self.proc.exitStatus(
            ) == QProcess.NormalExit and self.proc.exitCode() == 0:
                return True
        return False

    @pyqtSlot(QProcess.ProcessError)
    def cmdError(self, error: QProcess.ProcessError) -> None:
        if error != QProcess.Crashed:
            QMessageBox.critical(self.parent.parent,
                                 '',
                                 '<h4>%s Error:</h4>' % self.backend +
                                 '<p>%s</p>' % self.proc.errorString(),
                                 buttons=QMessageBox.Close)
            qApp.quit()

    def getAppPath(self) -> str:
        if getattr(sys, 'frozen', False):
            return sys._MEIPASS
        return QFileInfo(__file__).absolutePath()
Esempio n. 46
0
 def _performMonitor(self):
     """
     Protected method implementing the monitoring action.
     
     This method populates the statusList member variable
     with a list of strings giving the status in the first column and the
     path relative to the project directory starting with the third column.
     The allowed status flags are:
     <ul>
         <li>"A" path was added but not yet comitted</li>
         <li>"M" path has local changes</li>
         <li>"O" path was removed</li>
         <li>"R" path was deleted and then re-added</li>
         <li>"U" path needs an update</li>
         <li>"Z" path contains a conflict</li>
         <li>" " path is back at normal</li>
     </ul>
     
     @return tuple of flag indicating successful operation (boolean) and
         a status message in case of non successful operation (string)
     """
     self.shouldUpdate = False
     
     process = QProcess()
     args = []
     args.append('status')
     if not Preferences.getVCS("MonitorLocalStatus"):
         args.append('--show-updates')
     args.append('--non-interactive')
     args.append('.')
     process.setWorkingDirectory(self.projectDir)
     process.start('svn', args)
     procStarted = process.waitForStarted(5000)
     if procStarted:
         finished = process.waitForFinished(300000)
         if finished and process.exitCode() == 0:
             output = str(process.readAllStandardOutput(),
                          self.__ioEncoding, 'replace')
             states = {}
             for line in output.splitlines():
                 if self.rx_status1.exactMatch(line):
                     flags = self.rx_status1.cap(1)
                     path = self.rx_status1.cap(3).strip()
                 elif self.rx_status2.exactMatch(line):
                     flags = self.rx_status2.cap(1)
                     path = self.rx_status2.cap(5).strip()
                 else:
                     continue
                 if flags[0] in "ACDMR" or \
                    (flags[0] == " " and flags[-1] == "*"):
                     if flags[-1] == "*":
                         status = "U"
                     else:
                         status = flags[0]
                     if status == "C":
                         status = "Z"    # give it highest priority
                     elif status == "D":
                         status = "O"
                     if status == "U":
                         self.shouldUpdate = True
                     name = path
                     states[name] = status
                     try:
                         if self.reportedStates[name] != status:
                             self.statusList.append(
                                 "{0} {1}".format(status, name))
                     except KeyError:
                         self.statusList.append(
                             "{0} {1}".format(status, name))
             for name in list(self.reportedStates.keys()):
                 if name not in states:
                     self.statusList.append("  {0}".format(name))
             self.reportedStates = states
             return True, self.tr(
                 "Subversion status checked successfully (using svn)")
         else:
             process.kill()
             process.waitForFinished()
             return False, \
                 str(process.readAllStandardError(),
                     Preferences.getSystem("IOEncoding"),
                     'replace')
     else:
         process.kill()
         process.waitForFinished()
         return False, self.tr(
             "Could not start the Subversion process.")