Esempio n. 1
0
def loadPage(url):
    page = QtWebKit.QWebPage()
    loop = QtCore.QEventLoop() # Create event loop
    page.mainFrame().loadFinished.connect(loop.quit) # Connect loadFinished to loop quit
    page.mainFrame().load(url)
    loop.exec_() # Run event loop, it will end on loadFinished
    return page.mainFrame().toHtml()
Esempio n. 2
0
    def __init__(self, parent=None, *args, **kwargs):
        super(OverlayDialogBase, self).__init__(parent, *args, **kwargs)
        self.parent = parent
        self.setColor(QtGui.QColor(255, 255, 255, 200))

        self.ret = None
        self.layout = None
        self.button = None
        self.messageLabel = None
        self.content = None
        self.outerLayout = None
        self.contentLayout = None
        self.returnValueSet = False
        self.eventLoop = QtCore.QEventLoop()

        self.closeHint = QtGui.QLabel(self)
        self.closeHint.setText("Close/Abort with [esc]")
        self.closeHint.adjustSize()

        self.setGeometry(self.parent.geometry())
        # self.setGeometry(QtCore.QRect(0,0,100,100))
        self.parentEventHandler = OverlayDialogBase.ParentEventHandler(self)
        self.parent.installEventFilter(self.parentEventHandler)
        #
        # self.setupContent()
        # self.setupLayout()

        self.show()
        self.setFocus()
Esempio n. 3
0
    def __init__(self, application, dialog):
        """Initialize an IntegratedEventLoop object.

        Args:
            application : (QtGui.QApplication)
                The PySide application.

            dialog : (QtGui.QWidget)
                The widget to display.

        Raises:
            N/A

        Returns
            N/A

        """
        # The PySide application.
        self._application = application

        # The dialog to display.
        self._dialog = dialog

        # Stash a new version of the PySide event loop.
        self._eventLoop = QtCore.QEventLoop()
Esempio n. 4
0
 def __init__(self, application, dialogs):
     # We need the application to send posted events.  We hold a reference
     # to any dialogs to ensure that they don't get garbage collected
     # (and thus close in the process).  The reference count for this object
     # will go to zero when it removes itself from Houdini's event loop.
     self.application = application
     self.dialogs = dialogs
     self.event_loop = QtCore.QEventLoop()
Esempio n. 5
0
    def __init__(self, application, dialog):
        # The PySide application.
        self._application = application

        # The dialog to display.
        self._dialog = dialog

        # Stash a new version of the PySide event loop.
        self._eventLoop = QtCore.QEventLoop()
Esempio n. 6
0
def waittasks(tasks, timeout=0, abortSignal=None, autoQuit=False):
    """
  @param  tasks  [Task]
  @param* timeout  int
  @param* abortSignal  Signal or None  signal with auto type
  @param* autoQuit  bool  if quit eventloop when qApp.aboutToQuit
  """
    if not tasks:
        return
    loop = QtCore.QEventLoop()
    connectCount = 0
    for task in tasks:
        if not task.completed:
            task.finished.connect(loop.quit, Qt.QueuedConnection)
            connectCount += 1
    if not connectCount:
        return

    aborted = False

    def abort():
        aborted = True
        loop.quit()

    if abortSignal:
        abortSignal.connect(abort)
    # Make sure the eventloop quit before closing
    if autoQuit:
        qApp = QtCore.QCoreApplication.instance()
        qApp.aboutToQuit.connect(abort)
    timer = None
    if timeout:
        timer = QtCore.QTimer()
        timer.setInterval(timeout)
        timer.setSingleShot(True)
        timer.timeout.connect(abort)

    finishCount = 0
    completeCount = 0
    while not aborted and finishCount < connectCount and completeCount < len(
            tasks):
        loop.exec_()
        finishCount += 1
        completeCount = 0
        for it in tasks:
            if it.completed:
                completeCount += 1

    if timer:
        timer.timeout.disconnect(abort)
    if abortSignal:
        abortSignal.disconnect(abort)
    if autoQuit:
        qApp.aboutToQuit.disconnect(abort)
Esempio n. 7
0
 def waitForReadyRead(self, msecs=30000):
     wait = QtCore.QEventLoop()
     self.readyRead.connect(wait.quit)
     if msecs > 0:
         timer = QtCore.QTimer()
         timer.setSingleShot(True)
         timer.setInterval(msecs)
         self.readyRead.connect(timer.stop)
         timer.timeout.connect(wait.quit)
     wait.exec_()
     return len(self.__queue) > 0
Esempio n. 8
0
    def accept(self):
        """Compute the RAOs and plot them"""
        if not self.lc:
            return False
        if self.running:
            return
        self.form.group_pbar.show()

        min_period = Units.parseQuantity(self.form.min_period.text())
        max_period = Units.parseQuantity(self.form.max_period.text())
        n_period = self.form.n_period.value()
        periods = [min_period + (max_period - min_period) * i / (n_period - 1) \
            for i in range(n_period)]
        omegas = [2.0 * np.pi / T.getValueAs('s').Value for T in periods]

        # Generate the simulations
        sims = Tools.simulation(self.lc, self.ship, self.weights, self.tanks,
                                self.mesh, omegas)

        # Start solving the problems
        self.loop = QtCore.QEventLoop()
        self.timer = QtCore.QTimer()
        self.timer.setSingleShot(True)
        QtCore.QObject.connect(self.timer, QtCore.SIGNAL("timeout()"),
                               self.loop, QtCore.SLOT("quit()"))
        self.running = True
        n = len(periods) * len(Tools.DIRS)
        self.form.pbar.setMinimum(0)
        self.form.pbar.setMaximum(n)
        self.form.pbar.setValue(0)
        msg = QtGui.QApplication.translate("ship_console", "Computing RAOs",
                                           None)
        App.Console.PrintMessage(msg + '...\n')
        points = []
        plts = {}
        for dof in Tools.DOFS:
            plts[dof] = PlotAux.Plot(dof, periods)
        for i, data in enumerate(Tools.solve_sim(sims, omegas)):
            App.Console.PrintMessage("\t{} / {}\n".format(i + 1, n))
            self.form.pbar.setValue(i + 1)
            ii, jj, dataset = data
            for dof in Tools.DOFS:
                rao_complex = dataset.sel(radiating_dof=dof).data[0]
                plts[dof].rao[ii, jj + 1] = abs(rao_complex)
                plts[dof].phase[ii, jj + 1] = cmath.phase(rao_complex)
                plts[dof].update()
            self.timer.start(0.0)
            self.loop.exec_()
            if (not self.running):
                break
        return True
Esempio n. 9
0
    def accept(self):
        if not self.tank:
            return False
        self.form.group_pbar.show()

        n = self.form.points.value()
        self.form.pbar.setMinimum(0)
        self.form.pbar.setMaximum(n - 1)
        self.form.pbar.setValue(0)

        # Start iterating
        self.loop = QtCore.QEventLoop()
        self.timer = QtCore.QTimer()
        self.timer.setSingleShot(True)
        QtCore.QObject.connect(self.timer, QtCore.SIGNAL("timeout()"),
                               self.loop, QtCore.SLOT("quit()"))
        self.running = True
        # Get the hydrostatics
        msg = QtGui.QApplication.translate("ship_console",
                                           "Computing capacity curve", None)
        App.Console.PrintMessage(msg + '...\n')
        l = [0.0]
        z = [Units.parseQuantity("0 m")]
        v = [Units.parseQuantity("0 m^3")]
        plt = None
        for i in range(1, n):
            App.Console.PrintMessage("\t{} / {}\n".format(i, n - 1))
            self.form.pbar.setValue(i)
            level = i / (n - 1)
            h, vol = Tools.compute_capacity(self.tank, level)
            l.append(100 * level)
            z.append(h)
            v.append(vol)
            if plt is None:
                plt = PlotAux.Plot(l, z, v)
            else:
                plt.update(l, z, v)
            self.timer.start(0.0)
            self.loop.exec_()
            if (not self.running):
                break
        return True
Esempio n. 10
0
    def accept(self):
        if self.lc is None:
            return False
        self.form.group_pbar.show()
        self.save()

        roll = Units.parseQuantity(self.form.angle.text())
        n_points = self.form.n_points.value()
        var_trim = self.form.var_trim.isChecked()
        self.form.pbar.setMinimum(0)
        self.form.pbar.setMaximum(n_points)
        self.form.pbar.setValue(0)

        # Compute some constants
        COG, W = Tools.weights_cog(self.weights)
        TW = Units.parseQuantity("0 kg")
        VOLS = []
        for t in self.tanks:
            # t[0] = tank object
            # t[1] = load density
            # t[2] = filling level
            vol = t[0].Proxy.getVolume(t[0], t[2])
            VOLS.append(vol)
            TW += vol * t[1]
        TW = TW * Tools.G

        # Start traversing the queried angles
        self.loop = QtCore.QEventLoop()
        self.timer = QtCore.QTimer()
        self.timer.setSingleShot(True)
        QtCore.QObject.connect(self.timer, QtCore.SIGNAL("timeout()"),
                               self.loop, QtCore.SLOT("quit()"))
        self.running = True
        rolls = []
        gzs = []
        drafts = []
        trims = []
        plt = None
        for i in range(n_points):
            App.Console.PrintMessage("{0} / {1}\n".format(i + 1, n_points))
            self.form.pbar.setValue(i + 1)
            rolls.append(roll * i / float(n_points - 1))
            point = Tools.solve_point(W, COG, TW, VOLS, self.ship, self.tanks,
                                      rolls[-1], var_trim)
            if point is None:
                gzs.append(Units.Quantity(0, Units.Length))
                drafts.append(Units.Quantity(0, Units.Length))
                trims.append(Units.Quantity(0, Units.Angle))
            else:
                gzs.append(point[0])
                drafts.append(point[1])
                trims.append(point[2])
            if plt is None:
                plt = PlotAux.Plot(rolls, gzs, drafts, trims)
            else:
                plt.update(rolls, gzs, drafts, trims)
            self.timer.start(0.0)
            self.loop.exec_()
            if (not self.running):
                break
        return True
Esempio n. 11
0
    def accept(self):
        if not self.ship:
            return False
        if self.running:
            return
        self.form.group_pbar.show()
        self.save()

        trim = Units.parseQuantity(Locale.fromString(self.form.trim.text()))
        min_draft = Units.parseQuantity(
            Locale.fromString(self.form.min_draft.text()))
        max_draft = Units.parseQuantity(
            Locale.fromString(self.form.max_draft.text()))
        n_draft = self.form.n_draft.value()
        self.form.pbar.setMinimum(0)
        self.form.pbar.setMaximum(n_draft)
        self.form.pbar.setValue(0)

        draft = min_draft
        drafts = [draft]
        dDraft = (max_draft - min_draft) / (n_draft - 1)
        for i in range(1, n_draft):
            draft = draft + dDraft
            drafts.append(draft)

        # Get external faces
        self.loop = QtCore.QEventLoop()
        self.timer = QtCore.QTimer()
        self.timer.setSingleShot(True)
        QtCore.QObject.connect(self.timer, QtCore.SIGNAL("timeout()"),
                               self.loop, QtCore.SLOT("quit()"))
        self.running = True
        faces = self.externalFaces(self.ship.Shape)
        if not self.running:
            return False
        if len(faces) == 0:
            msg = QtGui.QApplication.translate(
                "ship_console",
                "Failure detecting external faces from the ship object", None)
            App.Console.PrintError(msg + '\n')
            return False
        faces = Part.makeShell(faces)

        # Get the hydrostatics
        msg = QtGui.QApplication.translate("ship_console",
                                           "Computing hydrostatics", None)
        App.Console.PrintMessage(msg + '...\n')
        points = []
        plt = None
        for i in range(len(drafts)):
            App.Console.PrintMessage("\t{} / {}\n".format(i + 1, len(drafts)))
            self.form.pbar.setValue(i + 1)
            draft = drafts[i]
            point = Tools.Point(self.ship, faces, draft, trim)
            points.append(point)
            if plt is None:
                plt = PlotAux.Plot(self.ship, points)
            else:
                plt.update(self.ship, points)
            self.timer.start(0.0)
            self.loop.exec_()
            if (not self.running):
                break
        return True
Esempio n. 12
0
# A floating toolbar for commonly used SOPs

import hou
from PySide import QtCore as qtc
from PySide import QtGui as qtg
from functools import partial

#-------------------------------------------------------------------

try:
    app = qtg.QApplication(['houdini'])
except:
    app = qtg.QApplication.instance()

eventLoop = qtc.QEventLoop()


def qt_callback():
    if not ctl.isVisible():
        try:
            hou.ui.removeEventLoopCallback(qt_callback)
        except:
            pass
    eventLoop.processEvents()
    app.sendPostedEvents(None, 0)


#-------------------------------------------------------------------
ctl = None
Esempio n. 13
0
    def accept(self):
        if not self.ship:
            return False
        if self.running:
            return
        self.save()

        mw = self.getMainWindow()
        form = mw.findChild(QtGui.QWidget, "TaskPanel")
        form.trim = self.widget(QtGui.QLineEdit, "Trim")
        form.minDraft = self.widget(QtGui.QLineEdit, "MinDraft")
        form.maxDraft = self.widget(QtGui.QLineEdit, "MaxDraft")
        form.nDraft = self.widget(QtGui.QSpinBox, "NDraft")

        trim = Units.Quantity(Locale.fromString(
            form.trim.text())).getValueAs('deg').Value
        min_draft = Units.Quantity(Locale.fromString(
            form.minDraft.text())).getValueAs('m').Value
        max_draft = Units.Quantity(Locale.fromString(
            form.maxDraft.text())).getValueAs('m').Value
        n_draft = form.nDraft.value()

        draft = min_draft
        drafts = [draft]
        dDraft = (max_draft - min_draft) / (n_draft - 1)
        for i in range(1, n_draft):
            draft = draft + dDraft
            drafts.append(draft)

        # Compute data
        # Get external faces
        self.loop = QtCore.QEventLoop()
        self.timer = QtCore.QTimer()
        self.timer.setSingleShot(True)
        QtCore.QObject.connect(self.timer, QtCore.SIGNAL("timeout()"),
                               self.loop, QtCore.SLOT("quit()"))
        self.running = True
        faces = self.externalFaces(self.ship.Shape)
        if not self.running:
            return False
        if len(faces) == 0:
            msg = QtGui.QApplication.translate(
                "ship_console",
                "Failure detecting external faces from the ship object", None,
                QtGui.QApplication.UnicodeUTF8)
            App.Console.PrintError(msg + '\n')
            return False
        faces = Part.makeShell(faces)
        # Get the hydrostatics
        msg = QtGui.QApplication.translate("ship_console",
                                           "Computing hydrostatics", None,
                                           QtGui.QApplication.UnicodeUTF8)
        App.Console.PrintMessage(msg + '...\n')
        points = []
        for i in range(len(drafts)):
            App.Console.PrintMessage("\t{} / {}\n".format(i + 1, len(drafts)))
            draft = drafts[i]
            point = Tools.Point(self.ship, faces, draft, trim)
            points.append(point)
            self.timer.start(0.0)
            self.loop.exec_()
            if (not self.running):
                break
        PlotAux.Plot(self.ship, trim, points)
        return True
Esempio n. 14
0
 def show(self):
     self._ui.show()
     q = QtCore.QEventLoop()
     q.exec_()
Esempio n. 15
0
    def __init__(self, textEdit, initialPrompt, locals = None):
        """Constructor.

        The optional 'locals' argument specifies the dictionary in
        which code will be executed; it defaults to a newly created
        dictionary with key "__name__" set to "__console__" and key
        "__doc__" set to None.

        """

        QtCore.QObject.__init__(self)

        self.interpreter = Interpreter(textEdit, locals)
        self.interpreter.locals['help'] = _Helper(self, self)

        self.completer = _Completer(self.interpreter.locals)
        # last line + last incomplete lines
        self.lines = []

        # flag: the interpreter needs more input to run the last lines. 
        self.more = 0

        # history
        self.history = []
        self.historyPointer = None
        self.historyInput = ''

        # flag: readline() is being used for e.g. raw_input and input().
        # We use a nested QEventloop here because we want to emulate
        # modeless UI even though the readline protocol requires blocking calls.
        self.readlineEventLoop = QtCore.QEventLoop(textEdit)

        # interpreter prompt.
        try:
            sys.ps1
        except AttributeError:
            sys.ps1 = ">>> "
        try:
            sys.ps2
        except AttributeError:
            sys.ps2 = "... "
            
        self.textEdit = textEdit
        self.connect(self.textEdit, QtCore.SIGNAL('destroyed()'),
                     self._TextEditDestroyedSlot)

        self.connect(self.textEdit, QtCore.SIGNAL("returnPressed()"),
                     self._ReturnPressedSlot)

        self.connect(self.textEdit, QtCore.SIGNAL("requestComplete()"),
                     self._CompleteSlot)

        self.connect(self.textEdit, QtCore.SIGNAL("requestNext()"),
                     self._NextSlot)

        self.connect(self.textEdit, QtCore.SIGNAL("requestPrev()"),
                     self._PrevSlot)

        appInstance = QtGui.QApplication.instance()
        self.connect(appInstance,
                     QtCore.SIGNAL("appControllerQuit()"),
                     self._QuitSlot)
        
        self.textEdit.setTabChangesFocus(False)

        self.textEdit.setWordWrapMode(QtGui.QTextOption.WrapAnywhere)
        self.textEdit.setWindowTitle('Interpreter')
        
        self.textEdit.promptLength = len(sys.ps1)

        # Do initial auto-import.
        self._DoAutoImports()

        # interpreter banner
        self.write('Python %s on %s.\n' % (sys.version, sys.platform))

        # Run $PYTHONSTARTUP startup script.
        startupFile = os.getenv('PYTHONSTARTUP')
        if startupFile:
            path = os.path.realpath(os.path.expanduser(startupFile))
            if os.path.isfile(path):
                self.ExecStartupFile(path)

        self.write(initialPrompt)
        self.write(sys.ps1)
        self.SetInputStart()
Esempio n. 16
0
def prepareVideoSeries(sourceFolder, destinationFolder):
    progress = QtGui.QProgressDialog("Scanning files...", "Abort Copy", 0, 100,
                                     QtGui.QApplication.activeWindow())

    progress.setWindowModality(QtCore.Qt.WindowModal)
    progress.setValue(0)
    progress.forceShow()

    projects = []
    project_cfg_path = os.path.join(destinationFolder, 'projects.yaml')

    folderWalk = list(os.walk(sourceFolder))

    progress.setRange(0, sum([len(f) for r, d, f in folderWalk]))

    work_thread = QtCore.QThread()

    cnt = 0
    for root, dirs, filenames in folderWalk:
        if progress.wasCanceled():
            break

        rel_folder = getRelativeFolder(sourceFolder, root)
        for filename in filenames:
            if progress.wasCanceled():
                break

            if filename.endswith(('.avi', '.mp4', '.mpeg')):
                progress.setLabelText(
                    "Copying files...\n Processing {}\n({} / {})".format(
                        filename, cnt,
                        sum([len(f) for r, d, f in folderWalk])))
                progress.setValue(cnt)

                if len(filenames) > 1:
                    bn = os.path.basename(filename).split('.')[0]
                    tmp_dest = os.path.join(destinationFolder, rel_folder, bn)
                    projects += [os.path.join(rel_folder, bn)]
                else:
                    tmp_dest = os.path.join(destinationFolder, rel_folder)
                    projects += [rel_folder]

                tmp_project_cfg_path = ''.join(
                    ['../' for x in range(rel_folder.count('/') + 1)])
                tmp_project_cfg_path += 'projects.yaml'

                if not os.path.exists(tmp_dest):
                    os.makedirs(tmp_dest)

                work_thread = QtCore.QThread()
                worker = Worker(root, filename, tmp_dest, tmp_project_cfg_path)

                worker.moveToThread(work_thread)
                work_thread.started.connect(worker.start_processing)
                progress.canceled.connect(work_thread.quit)

                eventloop = QtCore.QEventLoop()
                worker.done_signal.connect(eventloop.exit)

                work_thread.start()
                eventloop.exec_()

                # shutil.copy(os.path.join(root, filename), tmp_dest)
                # PFFVP.prepareFolder(tmp_dest, projectCFGPath=tmp_project_cfg_path)

            cnt += 1
            progress.setValue(cnt)

    work_thread.quit()
    work_thread.wait()

    if not progress.wasCanceled():
        yamlString = yaml.dump(sorted(projects), default_flow_style=False)

        with open(project_cfg_path, 'w') as f:
            f.writelines(yamlString)
Esempio n. 17
0
 def __init__(self):
     super(self.__class__, self).__init__()
     self.eventLoop = QtCore.QEventLoop(self)