Beispiel #1
0
def convert_object_to_qjsvalue(obj, jsengine):
    """
    Convert any python object into a QJSValue. The conversion must happen in the GUI thread.
    :param obj:
    :param jsengine:
    :return:
    """
    if obj is None:
        return QJSValue()
    elif isinstance(obj, list) or isinstance(obj, tuple):
        length = len(obj)
        array = jsengine.newArray(length)
        for i, v in enumerate(obj):
            array.setProperty(i, convert_object_to_qjsvalue(v, jsengine))
        return array
    elif isinstance(obj, dict):
        array = jsengine.newArray()
        for k, v in obj.items():
            array.setProperty(k, convert_object_to_qjsvalue(v, jsengine))
        return array
    else:
        try:
            return QJSValue(obj)
        except TypeError:
            return QJSValue()
Beispiel #2
0
    def update_from_ui_metadata(self, ui_metadata: QtQml.QJSValue) -> bool:
        """
        Updates all metadata objects managed by this object with new values from ui_metadata
        :param ui_metadata: Value from QML containing new metadata
        :return: boolean saying if any WebMetadata have changed their urls a valid value
        """

        webmetadata_url_changed = False
        for db_name, metadata in ui_metadata.toVariant().items():
            for key, value in metadata.items():
                if not hasattr(self.get_metadata(MetadataClassMap[db_name]),
                               key):
                    continue
                if key == "tags":
                    value = Utils.convert_csv_to_list(value)
                elif key == "url" and isinstance(
                        self.get_metadata(
                            MetadataClassMap[db_name]), WebMetadata
                ) and value and value != self.get_metadata_value(
                        MetadataClassMap[db_name], "url"):
                    webmetadata_url_changed = True
                self.update_metadata_value(MetadataClassMap[db_name], key,
                                           value)
        for metadata in list(self.metadata.values()):
            if isinstance(metadata, WebMetadata) and not metadata.url:
                self.metadata.pop(metadata.DB_NAME)
                metadata.delete()
        return webmetadata_url_changed
Beispiel #3
0
    def onButtonClicked(self):

        window = engine.rootObjects()[0]
        ctx = engine.rootContext()
        print(window)
        # [ ] findChild가 아닌 뭘로 해야할까
        #   --> 그냥 qml내의 object에서 호출 clone을 만들어준다던가 하는 식으로 가기로 결정. 시간 소모 그만

        #logic = window.findChild(QObject, "Logic")
        #children = window.findChildren(QObject)
        children = ctx.findChildren(QObject)
        print("children : {}".format(children))
        c = 0
        for i in children:
            print("{} : {}".format(c, i.objectName()))
            c = c + 1
        #logic = engine.rootContext().findChild(QObject, "Logic")
        myObject = window.findChild(QObject, "myObject")
        #print("Logic : {}".format(logic))
        print("myObject: {}".format(myObject))
        #print(myObject)
        #if logic:
        #    logic.testjs()
        QJSValue(testjs).call()
        self.loop.call_soon(wsock.send, b'x')
Beispiel #4
0
    def enqueue(self, command, callback):
        """ Add an item of data awaiting processing to a queue of such items

            @param command: The tag of command
            @param callback: The callback function
        """
        self.callback.append(QJSValue(callback))
Beispiel #5
0
 def dump(self):
     print('Dump was called')
     # print('Callback is %s' % self.callback)
     # print(dir(self.callback))
     # print('Callback is callable %s' % self.callback.isCallable)
     # print('Callback is callable %s' % self.callback.isCallable())
     for c in self.callback:
         c.call([QJSValue('asdf')])
     self.callback = []
Beispiel #6
0
    def handleAddedLines(self, lines: QJSValue) -> None:
        lines = lines.toVariant()
        breakpoints = self._debugger.breakpoints

        for added_line in lines:
            breakpoints = set(x if x < added_line else int(x) + 1
                              for x in breakpoints)
        self._debugger.breakpoints = breakpoints
        self.breakpointsChanged.emit(self.breakpoints)
Beispiel #7
0
    def handleRemovedLines(self, lines: QJSValue) -> None:
        lines = lines.toVariant()
        breakpoints = self._debugger.breakpoints

        for removed_line in lines:
            if removed_line in breakpoints:
                breakpoints.remove(removed_line)
            breakpoints = set(x if x < removed_line else int(x) - 1
                              for x in breakpoints)

        self._debugger.breakpoints = breakpoints
        self.breakpointsChanged.emit(self.breakpoints)
Beispiel #8
0
    def update_from_ui_config(self, ui_config: QtQml.QJSValue) -> bool:
        self.logger.info("Updating config")
        old_folders = self.folders
        self.folders = ui_config.property("folders").toVariant()
        if old_folders != self.folders:
            PandaViewer.threads.folder_watcher_thread.queue.put(None)
        self.confirm_delete = ui_config.property("confirm_delete").toString()
        self.ex_member_id = ui_config.property("ex_member_id").toString()
        self.ex_pass_hash = ui_config.property("ex_pass_hash").toString()

        self.extract_zip = ui_config.property("extract_zip").toString()
        self.extract_cbz = ui_config.property("extract_cbz").toString()
        self.extract_rar = ui_config.property("extract_rar").toString()
        self.extract_cbr = ui_config.property("extract_cbr").toString()

        folder_options = ui_config.property("folder_options").toVariant()
        update_auto_metadata_collection = False
        for folder in folder_options:
            if folder_options.get(folder) != self.folder_options.get(folder):
                self.folder_metadata_map = folder_options
                update_auto_metadata_collection = True
                break
        self.folder_options = folder_options
        self.save()
        return update_auto_metadata_collection
Beispiel #9
0
    def update_from_ui_config(self, ui_config: QtQml.QJSValue) -> bool:
        self.logger.info("Updating config")
        old_folders = self.folders
        self.folders = ui_config.property("folders").toVariant()
        if old_folders != self.folders:
            PandaViewer.threads.folder_watcher_thread.queue.put(None)
        self.confirm_delete = ui_config.property("confirm_delete").toString()
        self.ex_member_id = ui_config.property("ex_member_id").toString()
        self.ex_pass_hash = ui_config.property("ex_pass_hash").toString()

        self.extract_zip = ui_config.property("extract_zip").toString()
        self.extract_cbz = ui_config.property("extract_cbz").toString()
        self.extract_rar = ui_config.property("extract_rar").toString()
        self.extract_cbr = ui_config.property("extract_cbr").toString()

        folder_options = ui_config.property("folder_options").toVariant()
        update_auto_metadata_collection = False
        for folder in folder_options:
            if folder_options.get(folder) != self.folder_options.get(folder):
                self.folder_metadata_map = folder_options
                update_auto_metadata_collection = True
                break
        self.folder_options = folder_options
        self.save()
        return update_auto_metadata_collection
Beispiel #10
0
    def dnsResolve(self, host):
        """Resolve a DNS hostname.

        Resolves the given DNS hostname into an IP address, and returns it
        in the dot-separated format as a string.

        Args:
            host: hostname to resolve.
        """
        ips = QHostInfo.fromName(host)
        if ips.error() != QHostInfo.NoError or not ips.addresses():
            err_f = "Failed to resolve host during PAC evaluation: {}"
            log.network.info(err_f.format(host))
            return QJSValue(QJSValue.NullValue)
        else:
            return ips.addresses()[0].toString()
    def addHighlightMultiColorRule(self, patterns: List[str], color: QJSValue,
                                   fontSettings: QFont) -> None:
        """
        Adds highlight rule to syntax highlighter
        :param patterns: Regexp pattners to be matched
        :param color: Foreground color of matched text
        :param fontSettings: Determinates font weight and italic
        """

        pattern_format = list()
        self._base_font = fontSettings

        for single_color in color.toVariant():
            pattern_format.append(
                self._setupFormat(QColor(single_color), fontSettings))

        for single_pattern in patterns:
            self._syntax_highlighter.addHighlightRule(
                HighlightRule(pattern_format,
                              QRegularExpression(single_pattern)))
Beispiel #12
0
    def update_from_ui_metadata(self, ui_metadata: QtQml.QJSValue) -> bool:
        """
        Updates all metadata objects managed by this object with new values from ui_metadata
        :param ui_metadata: Value from QML containing new metadata
        :return: boolean saying if any WebMetadata have changed their urls a valid value
        """

        webmetadata_url_changed = False
        for db_name, metadata in ui_metadata.toVariant().items():
            for key, value in metadata.items():
                if not hasattr(self.get_metadata(MetadataClassMap[db_name]), key):
                    continue
                if key == "tags":
                    value = Utils.convert_csv_to_list(value)
                elif key == "url" and isinstance(self.get_metadata(MetadataClassMap[db_name]),
                        WebMetadata) and value and value != self.get_metadata_value(MetadataClassMap[db_name], "url"):
                    webmetadata_url_changed = True
                self.update_metadata_value(MetadataClassMap[db_name], key, value)
        for metadata in list(self.metadata.values()):
            if isinstance(metadata, WebMetadata) and not metadata.url:
                self.metadata.pop(metadata.DB_NAME)
                metadata.delete()
        return webmetadata_url_changed
Beispiel #13
0
 def apply(self, config: QtQml.QJSValue):
     params = config.toVariant()
     func_name = params['func_name']
     params.pop('func_name')
     self._image.img = functions[func_name](self.img_src.current, params)
     self.set_image(self._image)
Beispiel #14
0
 def classifyImages(self, paths: QJSValue):
     paths = paths.toVariant()
     # TODO
     print(paths)
     pass
Beispiel #15
0
 def enqueue(self, command, callback):
     print('Enqueuing function of %s' % command)
     # print('Test callback is %s' % callback)
     # print('Callback is callable?:  %s' % callback.isCallable())
     self.callback.append(QJSValue(callback))
Beispiel #16
0
 def getHslFromHex(self, hexColor, callback):
     color = self.hexToRgb(hexColor)
     color = colorModel.colorRgbToHsl(color[0], color[1], color[2])
     if callback.isCallable():
         callback.call([QJSValue(color[0]), QJSValue(color[1]), QJSValue(color[2])])
Beispiel #17
0
 def dump(self):
     """ Return to callbacks """
     print('Dump was called')
     for c in self.callback:
         c.call([QJSValue('IT IS A TEST RESPONSE')])
     self.callback = []
Beispiel #18
0
    def getLastMethodWorkMetrics(self, callback):
        max_mtime = 0
        for dirname, subdirs, files in os.walk('{}/temp/log'.format(self.appDir)):
            for fname in files:
                full_path = os.path.join(dirname, fname)
                mtime = os.stat(full_path).st_mtime
                if mtime > max_mtime:
                    max_mtime = mtime
                    max_dir = dirname
                    max_file = fname

        methodTime = methodMSE = methodPSNR = methodRMS = 0
        segmentCount = sumOfSimilar = sumOfCoinciding = methodArea = 0
        methodPerimetr = methodCenterOfMass = methodCompactness = 0
        with open('{}/{}'.format(max_dir, max_file), 'r') as fileStream:
            for textLine in fileStream.readlines():
                if 'Timer: ' in textLine:
                    methodTime = textLine.replace('Timer: ', '')
                if 'MSE: ' in textLine:
                    methodMSE = textLine.replace('MSE: ', '')
                if 'PSNR: ' in textLine:
                    methodPSNR = textLine.replace('PSNR: ', '')
                if 'RMS: ' in textLine:
                    methodRMS = textLine.replace('RMS: ', '')
                if 'Segments count: ' in textLine:
                    segmentCount = textLine.replace('Segments count: ', '')
                if 'Sum of similar: ' in textLine:
                    sumOfSimilar = textLine.replace('Sum of similar: ', '')
                if 'Sum of coinciding: ' in textLine:
                    sumOfCoinciding = textLine.replace('Sum of coinciding: ', '')
                if 'Area: ' in textLine:
                    methodArea = textLine.replace('Area: ', '')
                if 'Perimetr: ' in textLine:
                    methodPerimetr = textLine.replace('Perimetr: ', '')
                if 'Center of mass: ' in textLine:
                    methodCenterOfMass = textLine.replace('Center of mass: ', '')
                if 'Compactness: ' in textLine:
                    methodCompactness = textLine.replace('Compactness: ', '')
        responseText = '<h1>{}</h1><h2>Timer(seconds):</h2>{}'.format(
            max_file.replace('.log', ''),
            methodTime)
        if methodMSE:
            responseText = '{}<h2>MSE:</h2>{}'.format(responseText, methodMSE)
        if methodPSNR:
            responseText = '{}<h2>PSNR:</h2>{}'.format(responseText, methodPSNR)
        if methodRMS:
            responseText = '{}<h2>RMS:</h2>{}'.format(responseText, methodRMS)
        if segmentCount:
            responseText = '{}<h2>Segments count:</h2>{}'.format(responseText, segmentCount)
        if sumOfSimilar:
            responseText = '{}<h2>Sum of similar:</h2>{}'.format(responseText, sumOfSimilar)
        if sumOfCoinciding:
            responseText = '{}<h2>Sum of coinciding:</h2>{}'.format(responseText, sumOfCoinciding)
        if methodArea:
            responseText = '{}<h2>Area:</h2>{}'.format(responseText, methodArea)
        if methodPerimetr:
            responseText = '{}<h2>Perimetr:</h2>{}'.format(responseText, methodPerimetr)
        if methodCenterOfMass:
            responseText = '{}<h2>Center of mass:</h2>{}'.format(responseText, methodCenterOfMass)
        if methodCompactness:
            responseText = '{}<h2>Compactness:</h2>{}'.format(responseText, methodCompactness)
        if callback.isCallable():
            callback.call([QJSValue(responseText)])