Esempio n. 1
0
    def __init__(self, parent=None):
        super(MainWin, self).__init__(parent)
        QTextCodec.setCodecForLocale(QTextCodec.codecForName('utf8'))
        self.setupUi(self)
        self.p = Material.Penguin()
        self.firstCheck()

        self.CreateTab.triggered.connect(self.addNewTab)
        self.DeleteTab.triggered.connect(self.delTab)
        self.Scan.triggered.connect(self.ScanEq)
        self.DeleteAllLog.triggered.connect(self.delLog)
        self.Help.triggered.connect(self.showHelp)
        self.Author.triggered.connect(self.showAuthor)
        self.Soft.triggered.connect(self.showSoft)
        self.UnScan.triggered.connect(self.delScan)
        self.RemoteScan.triggered.connect(self.RS)
        self.login_ID.triggered.connect(self.login)
        self.add_plan.triggered.connect(self.append_plan)
        self.add_report.triggered.connect(self.append_report)
        self.plan.triggered.connect(self.run_plan)
        self.del_plan.triggered.connect(self.remove_plan)
        self.del_report.triggered.connect(self.remove_report)
        self.report.triggered.connect(self.run_report)
        self.setting.triggered.connect(self.run_setting)
        self.delbtn.triggered.connect(self.delsetting)
    def findCodecs(self):
        codecMap = []
        iso8859RegExp = QRegExp('ISO[- ]8859-([0-9]+).*')

        for mib in QTextCodec.availableMibs():
            codec = QTextCodec.codecForMib(mib)
            sortKey = codec_name(codec).upper()
            rank = 0

            if sortKey.startswith('UTF-8'):
                rank = 1
            elif sortKey.startswith('UTF-16'):
                rank = 2
            elif iso8859RegExp.exactMatch(sortKey):
                if len(iso8859RegExp.cap(1)) == 1:
                    rank = 3
                else:
                    rank = 4
            else:
                rank = 5

            codecMap.append((str(rank) + sortKey, codec))

        codecMap.sort()
        self.codecs = [item[-1] for item in codecMap]
Esempio n. 3
0
    def getEncodings():
        """Returns a list of available encodings. static."""

        return [
            str(
                unicode(QTextCodec.codecForMib(mib).name().data(),
                        encoding='utf-8'))
            for mib in QTextCodec.availableMibs()
        ]
Esempio n. 4
0
	def showEncodingDialog(self):
		if not self.maybeSave(self.ind):
			return
		codecsSet = set(bytes(QTextCodec.codecForName(alias).name())
		                for alias in QTextCodec.availableCodecs())
		encoding, ok = QInputDialog.getItem(self, '',
			self.tr('Select file encoding from the list:'),
			[bytes(b).decode() for b in sorted(codecsSet)],
			0, False)
		if ok:
			self.currentTab.readTextFromFile(None, encoding)
Esempio n. 5
0
	def showEncodingDialog(self):
		if not self.maybeSave(self.ind):
			return
		codecsSet = set(bytes(QTextCodec.codecForName(alias).name())
		                for alias in QTextCodec.availableCodecs())
		encoding, ok = QInputDialog.getItem(self, '',
			self.tr('Select file encoding from the list:'),
			[bytes(b).decode() for b in sorted(codecsSet)],
			0, False)
		if ok:
			self.currentTab.readTextFromFile(None, encoding)
Esempio n. 6
0
def getFeaturesFromResponse(response):
    """Return a list of features from a valhalla response object"""
    codec = QTextCodec.codecForName("UTF-8")
    fields = QgsJsonUtils.stringToFields(json.dumps(response), codec)
    features = QgsJsonUtils.stringToFeatureList(json.dumps(response), fields,
                                                codec)
    return features
Esempio n. 7
0
def _get_settings(config_dir=None):
    """
    配置文件
    """
    if config_dir is None:
        config_dir = os.path.join(os.path.abspath(os.path.curdir),
                                  "wallet_config")

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

    config_file = os.path.join(config_dir, "config.ini")

    settings_obj = QSettings(config_file, QSettings.IniFormat)
    settings_obj.setIniCodec(QTextCodec.codecForName("utf-8"))

    if settings_obj.value(Configs.db_used) is None:
        settings_obj.setValue(Configs.db_used, DBField.db_type[0])

    if settings_obj.value(Configs.db_path) is None:
        settings_obj.setValue(
            Configs.db_path,
            os.path.abspath(os.path.join("./", Configs.default_db_name)))

    return settings_obj
Esempio n. 8
0
    def __init__(self, log_textbox, parent, log_file):
        """Initializes a LogReader with the default display configuration.

        Args:
            log_textbox (QtWidgets.QPlainTextEdit): Textbox where logs are displayed.
            parent (App(QDialog)): Object corresponding to the parent UI element.
            log_file (str): Path to the logging file on disk.
        """
        super().__init__()
        self.parent = parent
        self.processes = {}
        self.decoder_stdout = QTextCodec.codecForLocale().makeDecoder()
        self.log_textbox = log_textbox
        self.cursor_output = self.log_textbox.textCursor()
        self.log_textbox.setReadOnly(True)
        self.log_textbox.setMaximumBlockCount(1000)  # limit console to 1000 lines
        self.log_str = ""
        self.progress = "█"
        self.process_signal.connect(self.append_output)
        self.app_name = ""
        self.gb = None

        # If log part of a tab widget we can switch to that tab when we have logs to show
        self.tab_widget = None
        self.tab_index = -1

        self.log_file = log_file
        os.makedirs(os.path.dirname(self.log_file), exist_ok=True)
        self.log_f = open(self.log_file, "w")
Esempio n. 9
0
    def openFile(self):
        filename, _ = QFileDialog.getOpenFileName(self, 'Open File',
                os.getenv('HOME'))

        if not filename:
            return

        fh = ''

        if QFile.exists(filename):
            fh = QFile(filename)

        if not fh.open(QFile.ReadOnly):
            QtGui.qApp.quit()

        data = fh.readAll()
        codec = QTextCodec.codecForUtfText(data)
        unistr = codec.toUnicode(data)

        tmp = ('Nopepad: %s' % filename)
        self.setWindowTitle(tmp)

        basename = QFileInfo(fh).baseName()
        self.statusBar().showMessage('File \'%s\' loaded' % basename)

        self.textEdit.setText(unistr)
    def aboutToShowSaveAsMenu(self):
        currentText = self.textEdit.toPlainText()

        for action in self.saveAsActs:
            codecName = action.data()
            codec = QTextCodec.codecForName(codecName)
            action.setVisible(codec and codec.canEncode(currentText))
Esempio n. 11
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())
    def __init__(self, parent=None):
        super().__init__(parent=parent)

        self.setProcessChannelMode(QProcess.MergedChannels)
        codec = QTextCodec.codecForLocale()
        self._decoder_stdout = codec.makeDecoder()

        self.readyReadStandardOutput.connect(self._ready_read_standard_output)
Esempio n. 13
0
 def init(cls, parent=None):
     """初始化配置实例
     :param cls:
     :param parent:
     """
     if not cls._Setting:
         cls._Setting = QSettings(ConfigFile, QSettings.IniFormat, parent)
         cls._Setting.setIniCodec(QTextCodec.codecForName('utf-8'))
Esempio n. 14
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. 15
0
	def showEncodingDialog(self):
		if not self.maybeSave(self.ind):
			return
		encoding, ok = QInputDialog.getItem(self, '',
			self.tr('Select file encoding from the list:'),
			[bytes(b).decode() for b in QTextCodec.availableCodecs()],
			0, False)
		if ok:
			self.currentTab.readTextFromFile(encoding)
Esempio n. 16
0
 def __init__(self):
     # Create a byte array that stays in scope as long as we do
     self.buffer = QByteArray()
     # Initialize the "real" QTextStream with a ByteArray buffer.
     super().__init__(self.buffer, QIODevice.ReadWrite)
     # The default codec is codecForLocale, which might vary with
     # the platform, so set a codec here for consistency. UTF-16
     # should entail minimal or no conversion on input or output.
     self.setCodec(QTextCodec.codecForName('UTF-16'))
Esempio n. 17
0
	def showEncodingDialog(self):
		if not self.maybeSave(self.ind):
			return
		encoding, ok = QInputDialog.getItem(self, '',
			self.tr('Select file encoding from the list:'),
			[bytes(b).decode() for b in QTextCodec.availableCodecs()],
			0, False)
		if ok:
			self.openFileMain(encoding)
Esempio n. 18
0
 def __init__(self):
     # Create a byte array that stays in scope as long as we do
     self.buffer = QByteArray()
     # Initialize the "real" QTextStream with a ByteArray buffer.
     super().__init__(self.buffer, QIODevice.ReadWrite)
     # The default codec is codecForLocale, which might vary with
     # the platform, so set a codec here for consistency. UTF-16
     # should entail minimal or no conversion on input or output.
     self.setCodec( QTextCodec.codecForName('UTF-16') )
Esempio n. 19
0
def readData(path):
    file=QFile(path)
    if not file.open(QIODevice.ReadOnly):
        log.warn("读取样式文件失败")
        return ''
    stream=QTextStream(file)
    stream.setCodec(QTextCodec.codecForName('utf-8'))
    data=stream.readAll()
    del stream
    return data
Esempio n. 20
0
def loadTranslators(qtTransDir, app, translationFiles=()):
    """
    Module function to load all required translations.
    
    @param qtTransDir directory of the Qt translations files (string)
    @param app reference to the application object (QApplication)
    @param translationFiles tuple of additional translations to
        be loaded (tuple of strings)
    @return the requested locale (string)
    """
    import Preferences
    
    global loaded_translators
    
    if qVersion() < "5.0.0":
        # set the default encoding for tr()
        QTextCodec.setCodecForTr(QTextCodec.codecForName("utf-8"))
    
    translations = ("qt", "eric6") + translationFiles
    loc = Preferences.getUILanguage()
    if loc is None:
        return

    if loc == "System":
        loc = QLocale.system().name()
    if loc != "C":
        dirs = [getConfig('ericTranslationsDir'), Globals.getConfigDir()]
        if qtTransDir is not None:
            dirs.append(qtTransDir)

        loca = loc
        for tf in ["{0}_{1}".format(tr, loc) for tr in translations]:
            translator, ok = loadTranslatorForLocale(dirs, tf)
            loaded_translators[tf] = translator
            if ok:
                app.installTranslator(translator)
            else:
                if tf.startswith("eric6"):
                    loca = None
        loc = loca
    else:
        loc = None
    return loc
Esempio n. 21
0
def loadTranslators(qtTransDir, app, translationFiles=()):
    """
    Module function to load all required translations.
    
    @param qtTransDir directory of the Qt translations files (string)
    @param app reference to the application object (QApplication)
    @param translationFiles tuple of additional translations to
        be loaded (tuple of strings)
    @return the requested locale (string)
    """
    import Preferences
    
    global loaded_translators
    
    if qVersion() < "5.0.0":
        # set the default encoding for tr()
        QTextCodec.setCodecForTr(QTextCodec.codecForName("utf-8"))
    
    translations = ("qt", "eric6") + translationFiles
    loc = Preferences.getUILanguage()
    if loc is None:
        return

    if loc == "System":
        loc = QLocale.system().name()
    if loc != "C":
        dirs = [getConfig('ericTranslationsDir'), Globals.getConfigDir()]
        if qtTransDir is not None:
            dirs.append(qtTransDir)

        loca = loc
        for tf in ["{0}_{1}".format(tr, loc) for tr in translations]:
            translator, ok = loadTranslatorForLocale(dirs, tf)
            loaded_translators[tf] = translator
            if ok:
                app.installTranslator(translator)
            else:
                if tf.startswith("eric6"):
                    loca = None
        loc = loca
    else:
        loc = None
    return loc
    def updateTextEdit(self):
        mib = self.encodingComboBox.itemData(self.encodingComboBox.currentIndex())
        codec = QTextCodec.codecForMib(mib)

        data = QTextStream(self.encodedData)
        data.setAutoDetectUnicode(False)
        data.setCodec(codec)

        self.decodedStr = data.readAll()
        self.textEdit.setPlainText(self.decodedStr)
Esempio n. 23
0
def readData(path):
    """red file data"""
    file = QFile(path)
    if not file.open(QIODevice.ReadOnly):
        return
    stream = QTextStream(file)
    stream.setCodec(QTextCodec.codecForName('UTF-8'))
    data = stream.readAll()
    file.close()
    del stream
    return data
Esempio n. 24
0
 def save_to_ini_file(self):
     settings = QSettings("ZhongLiuYiYuanConfig.ini", QSettings.IniFormat)
     settings.setIniCodec(QTextCodec.codecForName("GB2312"))
     settings.beginGroup("CompanyList")
     for i in range(len(self.companyList)):
         settings.setValue("companyName" + str(i), self.companyList[i])
     settings.endGroup()
     settings.beginGroup("ItemPriceList")
     for j in self.checkItemPriceDict:
         settings.setValue(j, str(self.checkItemPriceDict[j]))
     settings.endGroup()
Esempio n. 25
0
 def load(self, data, editable=False):
     if isinstance(data, str):
         unistr = data
     else:
         codec = QTextCodec.codecForHtml(data)
         unistr = codec.toUnicode(data)
     if Qt.mightBeRichText(unistr):
         self.textEdit.setHtml(unistr)
     else:
         self.textEdit.setPlainText(unistr)
     self.textEdit.setReadOnly(not editable)
Esempio n. 26
0
 def readText(self, path):
     file = QFile(path)
     if not file.open(QIODevice.ReadOnly):
         return ''
     stream = QTextStream(file)
     # 下面这句设置编码根据文件的编码自行确定
     stream.setCodec(QTextCodec.codecForName('UTF-8'))
     data = stream.readAll()
     file.close()
     del stream
     return data
Esempio n. 27
0
    def read(self):
        """ Reads the file and returns the content """

        _file = QFile(self.filename)
        if not _file.open(QIODevice.ReadOnly | QIODevice.Text):
            raise Exception(_file.errorString())

        # Codec
        codec = QTextCodec.codecForLocale()
        stream = QTextStream(_file)
        stream.setCodec(codec)
        return stream.readAll()
Esempio n. 28
0
 def __init__(self, parent=None):
     super().__init__(parent)
     self.profile = None
     self.started.connect(signals.node_started)
     self.started.connect(self.node_started)
     self.finished.connect(self.node_finished)
     self.finished.connect(signals.node_finished)
     self.errorOccurred.connect(self.node_error)
     self.errorOccurred.connect(signals.node_error)
     self.setProcessChannelMode(QProcess.MergedChannels)
     self.readyReadStandardOutput.connect(self.on_stdout_ready)
     self.decoder = QTextCodec.codecForLocale()
Esempio n. 29
0
    def read(self):
        """ Reads the file and returns the content """

        _file = QFile(self.filename)
        if not _file.open(QIODevice.ReadOnly | QIODevice.Text):
            raise Exception(_file.errorString())

        # Codec
        codec = QTextCodec.codecForLocale()
        stream = QTextStream(_file)
        stream.setCodec(codec)
        return stream.readAll()
Esempio n. 30
0
    def read_file(self, path):
        """Read in a file
        """
        file = QFile(path)
        fileinfo = QFileInfo(file)

        file.open(QIODevice.ReadOnly)
        data = file.readAll()
        codec = QTextCodec.codecForName('UTF-8')

        self.contents = codec.toUnicode(data).rstrip("\n")

        self.filename = fileinfo.fileName()
Esempio n. 31
0
    def __init__(self, parent=None):
        super().__init__(parent=parent)

        # merge stderr channel into stdout channel
        self.setProcessChannelMode(QProcess.MergedChannels)

        # prepare decoding process' output to Unicode
        codec = QTextCodec.codecForLocale()
        self._decoder_stdout = codec.makeDecoder()
        # only necessary when stderr channel isn't merged into stdout:
        # self._decoder_stderr = codec.makeDecoder()

        self.readyReadStandardOutput.connect(self._ready_read_standard_output)
Esempio n. 32
0
    def read_file(self, path):
        """Read in a file
        """
        file = QFile(path)
        fileinfo = QFileInfo(file)

        file.open(QIODevice.ReadOnly)
        data = file.readAll()
        codec = QTextCodec.codecForName("UTF-8")

        self.contents = codec.toUnicode(data).rstrip("\n")

        self.filename = fileinfo.fileName()
Esempio n. 33
0
            def on_load():
                file = QFile(filename)
                fileinfo = QFileInfo(file)

                file.open(QFile.ReadOnly)
                data = file.readAll()
                codec = QTextCodec.codecForUtfText(data)
                unistr = codec.toUnicode(data)

                self.page().mainFrame().findFirstElement("#editor").setInnerXml(unistr)
                self.page().mainFrame().evaluateJavaScript("init()")

                suffix = fileinfo.suffix()
                self.page().mainFrame().evaluateJavaScript("editor.getSession().setMode('%s');" % (
                    self.SUFIX_2_MODE[suffix] if suffix in self.SUFIX_2_MODE else self.SUFIX_2_MODE[None]
                ))
Esempio n. 34
0
    def save(self, data, path=None):
        if path:
            self.filename = path
            self.is_new = False

        _file = QFile(self.filename)
        if not _file.open(QIODevice.WriteOnly | QIODevice.Truncate):
            raise Exception(_file.errorString())

        stream = QTextStream(_file)
        stream.setCodec(QTextCodec.codecForLocale())
        stream << data
        stream.flush()
        _file.close()
        # Emit the signal
        self.fileSaved.emit(self.filename)
Esempio n. 35
0
    def save(self, data, path=None):
        if path:
            self.filename = path
            self.is_new = False

        _file = QFile(self.filename)
        if not _file.open(QIODevice.WriteOnly | QIODevice.Truncate):
            raise Exception(_file.errorString())

        stream = QTextStream(_file)
        stream.setCodec(QTextCodec.codecForLocale())
        stream << data
        stream.flush()
        _file.close()
        # Emit the signal
        self.fileSaved.emit(self.filename)
Esempio n. 36
0
def getFeaturesFromResponse(response):
    """Return a list of features from a valhalla response object
    """
    fields = QgsFields()
    fields.append(QgsField("opacity", QVariant.Double))
    fields.append(QgsField("fill", QVariant.String))
    fields.append(QgsField("fillOpacity", QVariant.Double))
    fields.append(QgsField("fill-opacity", QVariant.Double))
    # FIXME: in fact, due to a bug in qgis parser, we cannot use this field
    fields.append(QgsField("contour", QVariant.Int))
    fields.append(QgsField("color", QVariant.String))
    fields.append(QgsField("fillColor", QVariant.String))
    codec = QTextCodec.codecForName("UTF-8")
    features = QgsJsonUtils.stringToFeatureList(json.dumps(response), fields,
                                                codec)
    # LOG.debug('features : {}'.format(features))
    return features
Esempio n. 37
0
    def open(self, filename):
        if not QFile.exists(filename):
            return

        file = QFile(filename)

        file.open(QFile.ReadOnly)
        data = file.readAll()
        codec = QTextCodec.codecForUtfText(data)
        unistr = codec.toUnicode(data)

        self._set_window_title(filename)

        self.webView.page().mainFrame().findFirstElement("#editor").setInnerXml(unistr)
        self.webView.page().mainFrame().evaluateJavaScript("init()")

        self._set_mode_by_filename(filename)
Esempio n. 38
0
    def load(self, f):
        if not QFile.exists(f):
            return False

        fh = QFile(f)
        if not fh.open(QFile.ReadOnly):
            return False

        data = fh.readAll()
        codec = QTextCodec.codecForHtml(data)
        unistr = codec.toUnicode(data)

        if Qt.mightBeRichText(unistr):
            self.textEdit.setHtml(unistr)
        else:
            self.textEdit.setPlainText(unistr)

        self.setCurrentFileName(f)
        return True
Esempio n. 39
0
    def load(self, f):
        if not QFile.exists(f):
            return False

        fh = QFile(f)
        if not fh.open(QFile.ReadOnly):
            return False

        data = fh.readAll()
        codec = QTextCodec.codecForHtml(data)
        unistr = codec.toUnicode(data)

        if Qt.mightBeRichText(unistr):
            self.textEdit.setHtml(unistr)
        else:
            self.textEdit.setPlainText(unistr)

        self.setCurrentFileName(f)
        return True
 def __init__(self, debugServer, passive):
     """
     Constructor
     
     @param debugServer reference to the debug server (DebugServer)
     @param passive flag indicating passive connection mode (boolean)
     """
     super(DebuggerInterfacePython, self).__init__()
     
     self.__isNetworked = True
     self.__autoContinue = False
     
     self.debugServer = debugServer
     self.passive = passive
     self.process = None
     
     self.qsock = None
     self.queue = []
     
     # set default values for capabilities of clients
     self.clientCapabilities = ClientDefaultCapabilities
     
     # set translation function
     self.translate = self.__identityTranslation
     
     self.codec = QTextCodec.codecForName(
         Preferences.getSystem("StringEncoding"))
     
     self.__unicodeRe = re.compile(r"""\bu(["'])""")
     
     if passive:
         # set translation function
         if Preferences.getDebugger("PathTranslation"):
             self.translateRemote = \
                 Preferences.getDebugger("PathTranslationRemote")
             self.translateLocal = \
                 Preferences.getDebugger("PathTranslationLocal")
             self.translate = self.__remoteTranslation
         else:
             self.translate = self.__identityTranslation
     
     # attribute to remember the name of the executed script
     self.__scriptName = ""
Esempio n. 41
0
 def __init__(self, debugServer, passive):
     """
     Constructor
     
     @param debugServer reference to the debug server (DebugServer)
     @param passive flag indicating passive connection mode (boolean)
     """
     super(DebuggerInterfacePython, self).__init__()
     
     self.__isNetworked = True
     self.__autoContinue = False
     
     self.debugServer = debugServer
     self.passive = passive
     self.process = None
     
     self.qsock = None
     self.queue = []
     
     # set default values for capabilities of clients
     self.clientCapabilities = ClientDefaultCapabilities
     
     # set translation function
     self.translate = self.__identityTranslation
     
     self.codec = QTextCodec.codecForName(
         Preferences.getSystem("StringEncoding"))
     
     self.__unicodeRe = re.compile(r"""\bu(["'])""")
     
     if passive:
         # set translation function
         if Preferences.getDebugger("PathTranslation"):
             self.translateRemote = \
                 Preferences.getDebugger("PathTranslationRemote")
             self.translateLocal = \
                 Preferences.getDebugger("PathTranslationLocal")
             self.translate = self.__remoteTranslation
         else:
             self.translate = self.__identityTranslation
     
     # attribute to remember the name of the executed script
     self.__scriptName = ""
Esempio n. 42
0
 def runFile(self):
     myCmd0= 'python /Users/tania/Desktop/Desktop/ORIGINAL/Code/Tugas_Akhir/AksaraBatak/Translator/converter.py'
     myCmd = 'python test_model.py ./models/CNN.pth ./models/voc-model-labels.txt ./outs/ImageSets/test.txt'
     myCmd2 = 'python /Users/tania/Desktop/Desktop/ORIGINAL/Code/Tugas_Akhir/AksaraBatak/BFS/bfs.py'
     os.system(myCmd0)
     os.system(myCmd)
     os.system(myCmd2)     
     
     file = QFile("/Users/tania/Desktop/Desktop/ORIGINAL/Code/Tugas_Akhir/AksaraBatak/BFS/outputBFS.txt")
     
     if file.open(QIODevice.ReadOnly | QIODevice.Text):
         stream = QTextStream(file)
         while not stream.atEnd():   
             line = file.readLine()
             line.append(stream.readLine()+"\n")
             encodedString = line.append(stream.readLine()+"\n")
             codec = QTextCodec.codecForName("KOI8-R")
             string = codec.toUnicode(encodedString)
             self.results.setText(string)
     file.close();
Esempio n. 43
0
 def __init__(self, debugServer, passive):
     """
     Constructor
     
     @param debugServer reference to the debug server (DebugServer)
     @param passive flag indicating passive connection mode (boolean)
     """
     super(DebuggerInterfaceRuby, self).__init__()
     
     self.__isNetworked = True
     self.__autoContinue = not passive
     
     self.debugServer = debugServer
     self.passive = passive
     self.process = None
     
     self.qsock = None
     self.queue = []
     
     # set default values for capabilities of clients
     self.clientCapabilities = ClientDefaultCapabilities
     
     # set translation function
     self.translate = self.__identityTranslation
     
     self.codec = QTextCodec.codecForName(
         str(Preferences.getSystem("StringEncoding")))
     
     if passive:
         # set translation function
         if Preferences.getDebugger("PathTranslation"):
             self.translateRemote = \
                 Preferences.getDebugger("PathTranslationRemote")
             self.translateLocal = \
                 Preferences.getDebugger("PathTranslationLocal")
             self.translate = self.__remoteTranslation
         else:
             self.translate = self.__identityTranslation
Esempio n. 44
0
 def __init__(self, conf = "qt.conf", parent = None):
     QSettings.__init__(self, conf, QSettings.IniFormat, parent)
     self.setIniCodec(QTextCodec.codecForName("utf-8"))
Esempio n. 45
0
def start(filenames=None, projects_path=None,
          extra_plugins=None, linenos=None):
    app = QApplication(sys.argv)
    QCoreApplication.setOrganizationName('NINJA-IDE')
    QCoreApplication.setOrganizationDomain('NINJA-IDE')
    QCoreApplication.setApplicationName('NINJA-IDE')
    app.setWindowIcon(QIcon(resources.IMAGES['icon']))

    # Check if there is another session of ninja-ide opened
    # and in that case send the filenames and projects to that session
    running = ipc.is_running()
    start_server = not running[0]
    if running[0] and (filenames or projects_path):
        sended = ipc.send_data(running[1], filenames, projects_path, linenos)
        running[1].close()
        if sended:
            sys.exit()
    else:
        running[1].close()

    # Create and display the splash screen
    splash_pix = QPixmap(resources.IMAGES['splash'])
    splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
    splash.setMask(splash_pix.mask())
    splash.show()
    app.processEvents()

    # Set the cursor to unblinking
    if sys.platform != 'win32':
        app.setCursorFlashTime(0)

    #Set the codec for strings (QString)
    print("codec:", QTextCodec.codecForName('utf-8'))
    #QTextCodec.setCodecForCStrings(QTextCodec.codecForName('utf-8'))

    #Translator
    #qsettings = QSettings()
    qsettings = QSettings(resources.SETTINGS_PATH, QSettings.IniFormat)
    language = QLocale.system().name()
    lang = qsettings.value('preferences/interface/language',
        defaultValue=language, type='QString') + '.qm'
    lang_path = file_manager.create_path(resources.LANGS, lang)
    if file_manager.file_exists(lang_path):
        settings.LANGUAGE = lang_path
    elif file_manager.file_exists(file_manager.create_path(
      resources.LANGS_DOWNLOAD, lang)):
        settings.LANGUAGE = file_manager.create_path(
            resources.LANGS_DOWNLOAD, lang)
    translator = QTranslator()
    if settings.LANGUAGE:
        translator.load(settings.LANGUAGE)
        app.installTranslator(translator)

        qtTranslator = QTranslator()
        qtTranslator.load("qt_" + language,
            QLibraryInfo.location(QLibraryInfo.TranslationsPath))
        app.installTranslator(qtTranslator)

    #Loading Syntax
    splash.showMessage("Loading Syntax", Qt.AlignRight | Qt.AlignTop, Qt.black)
    json_manager.load_syntax()

    #Read Settings
    splash.showMessage("Loading Settings", Qt.AlignRight | Qt.AlignTop,
        Qt.black)
    settings.load_settings()

    #Set Stylesheet
    style_applied = False
    if settings.NINJA_SKIN not in ('Default', 'Classic Theme'):
        file_name = ("%s.qss" % settings.NINJA_SKIN)
        qss_file = file_manager.create_path(resources.NINJA_THEME_DOWNLOAD,
            file_name)
        if file_manager.file_exists(qss_file):
            with open(qss_file) as f:
                qss = f.read()
                app.setStyleSheet(qss)
                style_applied = True
    if not style_applied:
        if settings.NINJA_SKIN == 'Default':
            with open(resources.NINJA_THEME) as f:
                qss = f.read()
        else:
            with open(resources.NINJA__THEME_CLASSIC) as f:
                qss = f.read()
        app.setStyleSheet(qss)

    #Loading Schemes
    splash.showMessage("Loading Schemes",
        Qt.AlignRight | Qt.AlignTop, Qt.black)
    scheme = qsettings.value('preferences/editor/scheme', "default",
        type='QString')
    if scheme != 'default':
        scheme = file_manager.create_path(resources.EDITOR_SKINS,
            scheme + '.color')
        if file_manager.file_exists(scheme):
            resources.CUSTOM_SCHEME = json_manager.parse(open(scheme))

    #Loading Shortcuts
    resources.load_shortcuts()
    #Loading GUI
    splash.showMessage("Loading GUI", Qt.AlignRight | Qt.AlignTop, Qt.black)
    ide = IDE(start_server)

    #Showing GUI
    ide.show()

    #Loading Session Files
    splash.showMessage("Loading Files and Projects",
        Qt.AlignRight | Qt.AlignTop, Qt.black)
    #Files in Main Tab
    main_files = qsettings.value('openFiles/mainTab', [])
    if main_files is not None:
        mainFiles = list(main_files)
    else:
        mainFiles = list()
    tempFiles = []
    for file_ in mainFiles:
        fileData = list(file_)
        if fileData:
            lineno = fileData[1]
            tempFiles.append((fileData[0], lineno))
    mainFiles = tempFiles
    #Files in Secondary Tab
    sec_files = qsettings.value('openFiles/secondaryTab', [])
    if sec_files is not None:
        secondaryFiles = list(sec_files)
    else:
        secondaryFiles = list()
    tempFiles = []
    for file_ in secondaryFiles:
        fileData = list(file_)
        lineno = fileData[1]
        tempFiles.append((fileData[0], lineno))
    secondaryFiles = tempFiles
    # Recent Files
    recent = qsettings.value('openFiles/recentFiles', [])
    if recent is not None:
        recent_files = list(recent)
    else:
        recent_files = list()
    recent_files = [file_ for file_ in recent_files]
    #Current File
    current_file = qsettings.value('openFiles/currentFile', '', type='QString')
    #Projects
    projects_list = qsettings.value('openFiles/projects', [])
    if projects_list is not None:
        projects = list(projects_list)
    else:
        projects = list()
    projects = [project for project in projects]
    #Include files received from console args
    file_with_nro = list([(f[0], f[1] - 1) for f in zip(filenames, linenos)])
    file_without_nro = list([(f, 0) for f in filenames[len(linenos):]])
    mainFiles += file_with_nro + file_without_nro
    #Include projects received from console args
    if projects_path:
        projects += projects_path
    ide.load_session_files_projects(mainFiles, secondaryFiles, projects,
        current_file, recent_files)
    #Load external plugins
    if extra_plugins:
        ide.load_external_plugins(extra_plugins)

    splash.finish(ide)
    ide.notify_plugin_errors()
    ide.show_python_detection()
    sys.exit(app.exec_())