コード例 #1
1
    def go_to_definition(self):
        self.dirty = True
        self.results = []
        locations = self.get_locations()
        if self._isVariable:
            preResults = [
                [file_manager.get_basename(x.path), x.path, x.lineno, '']
                for x in locations
                if (x.type == FILTERS['attribs']) and (x.name == self._search)]
        else:
            preResults = [
                [file_manager.get_basename(x.path), x.path, x.lineno, '']
                for x in locations
                if ((x.type == FILTERS['functions']) or
                    (x.type == FILTERS['classes'])) and
                   (x.name.startswith(self._search))]
        for data in preResults:
            file_object = QFile(data[1])
            if not file_object.open(QFile.ReadOnly):
                return

            stream = QTextStream(file_object)
            line_index = 0
            line = stream.readLine()
            while not self._cancel and not stream.atEnd():
                if line_index == data[2]:
                    data[3] = line
                    self.results.append(data)
                    break
                #take the next line!
                line = stream.readLine()
                line_index += 1
コード例 #2
0
    def loadDescription(self, startPara, nrPara):
        readme = QFile(self.readmePath)
        if not readme.open(QFile.ReadOnly):
            Colors.debug("- MenuContentItem.loadDescription: Could not load:",
                         self.readmePath)
            return ""

        in_str = QTextStream(readme)
        # Skip a certain number of paragraphs.
        while startPara:
            if not in_str.readLine():
                startPara -= 1

        # Read in the number of wanted paragraphs.
        result = ''
        line = in_str.readLine()
        while True:
            result += line + " "
            line = in_str.readLine()
            if not line:
                nrPara -= 1
                line = "<br><br>" + in_str.readLine()

            if nrPara == 0 or in_str.atEnd():
                break

        return Colors.contentColor + result
コード例 #3
0
ファイル: main.py プロジェクト: dnllc3/Tick-Tock
    def __init__(self, parent=None):
        super(ScheduleViewMenu, self).__init__()
        self.setupUi(self)
        self.home_button.clicked.connect(self.openMainWindow)
        scheduleFile = QFile("schedule.txt")
        if not scheduleFile.open(QIODevice.ReadOnly | QIODevice.Text):
            return

        text_in = QTextStream(scheduleFile)
        medication_info = text_in.readLine()
        prescription_info = text_in.readLine()
        time_spins = {
            1: self.time_spin_1,
            2: self.time_spin_2,
            3: self.time_spin_3,
            4: self.time_spin_4,
            5: self.time_spin_5,
        }
        i = 0
        while not text_in.atEnd():
            time_spins[i + 1].setText(text_in.readLine())
            i += 1

        self.medication_text.setText(medication_info)
        self.prescription_label.setText(prescription_info)
        t = threading.Timer(
            1.0, lambda: ConfirmedMenu.wait(self))  #prescription number
        t.start()
コード例 #4
0
    def _grep_file(self, file_path, file_name):
        """Search for each line inside the file."""
        if not self.by_phrase:
            with open(file_path, 'r') as f:
                content = f.read()
            words = [word for word in self.search_pattern.pattern().split('|')]
            words.insert(0, True)

            def check_whole_words(result, word):
                return result and content.find(word) != -1

            if not reduce(check_whole_words, words):
                return
        file_object = QFile(file_path)
        if not file_object.open(QFile.ReadOnly):
            return

        stream = QTextStream(file_object)
        lines = []
        line_index = 0
        line = stream.readLine()
        while not self._cancel and not (stream.atEnd() and not line):
            column = self.search_pattern.indexIn(line)
            if column != -1:
                lines.append((line_index, line))
            #take the next line!
            line = stream.readLine()
            line_index += 1
        #emit a signal!
        relative_file_name = file_manager.convert_to_relative(
            self.root_dir, file_path)
        self.found_pattern.emit((relative_file_name, lines))
コード例 #5
0
    def __readDepartmentsData(self):
        department_list = []  # of Department
        for file_name in MainWindow.dep_file_name_list:
            count = 0
            file = QFile(':/stuff/' + file_name + '.txt')
            if not file.open(QIODevice.ReadOnly | QIODevice.Text):
                raise FileNotFoundError(file_name)

            stream = QTextStream(file)
            stream.setCodec('UTF-8')
            dep_name = stream.readLine()
            if dep_name[-1] != ':':
                raise Exception('resource ' + file_name +
                                ' with no department mark')

            dep_name = dep_name[:-1]
            new_dep_obj = Department(dep_name)

            while not stream.atEnd():
                count += 1
                (n, s) = stream.readLine().split()
                if count == 1:
                    new_dep_obj.setBoss(Employee(n, s))
                else:
                    new_dep_obj.addEmployee(Employee(n, s))

            if count == 0:
                raise Exception('resource ' + file_name + ' has no items')

            department_list.append(new_dep_obj)
        return department_list
コード例 #6
0
    def go_to_definition(self):
        self.dirty = True
        self.results = []
        locations = self.get_locations()
        if self._isVariable:
            preResults = [
                [file_manager.get_basename(x.path), x.path, x.lineno, '']
                for x in locations
                if (x.type == FILTERS['attribs']) and (x.name == self._search)
            ]
        else:
            preResults = [[
                file_manager.get_basename(x.path), x.path, x.lineno, ''
            ] for x in locations if ((x.type == FILTERS['functions']) or
                                     (x.type == FILTERS['classes'])) and (
                                         x.name.startswith(self._search))]
        for data in preResults:
            file_object = QFile(data[1])
            if not file_object.open(QFile.ReadOnly):
                return

            stream = QTextStream(file_object)
            line_index = 0
            line = stream.readLine()
            while not self._cancel and not stream.atEnd():
                if line_index == data[2]:
                    data[3] = line
                    self.results.append(data)
                    break
                #take the next line!
                line = stream.readLine()
                line_index += 1
コード例 #7
0
    def _grep_file(self, file_path, file_name):
        """Search for each line inside the file."""
        if not self.by_phrase:
            with open(file_path, 'r') as f:
                content = f.read()
            words = [word for word in
                self.search_pattern.pattern().split('|')]
            words.insert(0, True)

            def check_whole_words(result, word):
                return result and content.find(word) != -1
            if not reduce(check_whole_words, words):
                return
        file_object = QFile(file_path)
        if not file_object.open(QFile.ReadOnly):
            return

        stream = QTextStream(file_object)
        lines = []
        line_index = 0
        line = stream.readLine()
        while not self._cancel and not (stream.atEnd() and not line):
            column = self.search_pattern.indexIn(line)
            if column != -1:
                lines.append((line_index, line))
            #take the next line!
            line = stream.readLine()
            line_index += 1
        #emit a signal!
        relative_file_name = file_manager.convert_to_relative(
            self.root_dir, file_path)
        self.found_pattern.emit((relative_file_name, lines))
コード例 #8
0
    def __loadRules(self):
        """
        Private method to load the rules of the subscription.
        """
        fileName = self.rulesFileName()
        f = QFile(fileName)
        if f.exists():
            if not f.open(QIODevice.ReadOnly):
                E5MessageBox.warning(
                    None, self.tr("Load subscription rules"),
                    self.tr(
                        """Unable to open adblock file '{0}' for reading.""").
                    format(fileName))
            else:
                textStream = QTextStream(f)
                header = textStream.readLine(1024)
                if not header.startswith("[Adblock"):
                    E5MessageBox.warning(
                        None, self.tr("Load subscription rules"),
                        self.tr("""AdBlock file '{0}' does not start"""
                                """ with [Adblock.""").format(fileName))
                    f.close()
                    f.remove()
                    self.__lastUpdate = QDateTime()
                else:
                    from .AdBlockRule import AdBlockRule

                    self.__updatePeriod = 0
                    self.__remoteModified = QDateTime()
                    self.__rules = []
                    self.__rules.append(AdBlockRule(header, self))
                    while not textStream.atEnd():
                        line = textStream.readLine()
                        self.__rules.append(AdBlockRule(line, self))
                        expires = self.__expiresRe.search(line)
                        if expires:
                            period, kind = expires.groups()
                            if kind:
                                # hours
                                self.__updatePeriod = int(period)
                            else:
                                # days
                                self.__updatePeriod = int(period) * 24
                        remoteModified = self.__remoteModifiedRe.search(line)
                        if remoteModified:
                            day, month, year, time, hour, minute = \
                                remoteModified.groups()
                            self.__remoteModified.setDate(
                                QDate(int(year),
                                      self.__monthNameToNumber[month],
                                      int(day)))
                            if time:
                                self.__remoteModified.setTime(
                                    QTime(int(hour), int(minute)))
                    self.__populateCache()
                    self.changed.emit()
        elif not fileName.endswith("_custom"):
            self.__lastUpdate = QDateTime()

        self.checkForUpdate()
コード例 #9
0
ファイル: chart.py プロジェクト: PWilsonUofC/VGenes
    def openFile(self, path=None):
        if not path:
            path, _ = QFileDialog.getOpenFileName(self, "Choose a data file",
                    '', '*.cht')

        if path:
            f = QFile(path)

            if f.open(QFile.ReadOnly | QFile.Text):
                stream = QTextStream(f)

                self.model.removeRows(0, self.model.rowCount(QModelIndex()),
                        QModelIndex())

                row = 0
                line = stream.readLine()
                while line:
                    self.model.insertRows(row, 1, QModelIndex())

                    pieces = line.split(',')
                    self.model.setData(self.model.index(row, 0, QModelIndex()),
                                pieces[0])
                    self.model.setData(self.model.index(row, 1, QModelIndex()),
                                float(pieces[1]))
                    self.model.setData(self.model.index(row, 0, QModelIndex()),
                                QColor(pieces[2]), Qt.DecorationRole)

                    row += 1
                    line = stream.readLine()

                f.close()
                self.statusBar().showMessage("Loaded %s" % path, 2000)
コード例 #10
0
    def openFile(self, path=None):
        if not path:
            path, _ = QFileDialog.getOpenFileName(self, "Choose a data file",
                                                  '', '*.cht')

        if path:
            f = QFile(path)

            if f.open(QFile.ReadOnly | QFile.Text):
                stream = QTextStream(f)

                self.model.removeRows(0, self.model.rowCount(QModelIndex()),
                                      QModelIndex())

                row = 0
                line = stream.readLine()
                while line:
                    self.model.insertRows(row, 1, QModelIndex())

                    pieces = line.split(',')
                    self.model.setData(self.model.index(row, 0, QModelIndex()),
                                       pieces[0])
                    self.model.setData(self.model.index(row, 1, QModelIndex()),
                                       float(pieces[1]))
                    self.model.setData(self.model.index(row, 0, QModelIndex()),
                                       QColor(pieces[2]), Qt.DecorationRole)

                    row += 1
                    line = stream.readLine()

                f.close()
                self.statusBar().showMessage("Loaded %s" % path, 2000)
コード例 #11
0
ファイル: menucontent.py プロジェクト: Magdno1/Arianrhod
    def loadDescription(self, startPara, nrPara):
        readme = QFile(self.readmePath)
        if not readme.open(QFile.ReadOnly):
            Colors.debug("- MenuContentItem.loadDescription: Could not load:", self.readmePath)
            return ""

        in_str = QTextStream(readme)
        # Skip a certain number of paragraphs.
        while startPara:
            if not in_str.readLine():
                startPara -= 1

        # Read in the number of wanted paragraphs.
        result = ""
        line = in_str.readLine()
        while True:
            result += line + " "
            line = in_str.readLine()
            if not line:
                nrPara -= 1
                line = "<br><br>" + in_str.readLine()

            if nrPara == 0 or in_str.atEnd():
                break

        return Colors.contentColor + result
コード例 #12
0
    def __readDefaultSchedule(self, num_of_days):
        file_name = 'default'
        file = QFile(':/schedule/' + file_name + '.txt')

        if not file.open(QIODevice.ReadOnly | QIODevice.Text):
            raise FileNotFoundError(file_name)

        stream = QTextStream(file)
        stream.setCodec('UTF-8')

        Matrix = [[[] for i in range(0, num_of_days)] for j in range(0, 9)]
        days_of_week = [
            '', 'Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница',
            'Суббота', 'Воскресенье'
        ]
        while not stream.atEnd():
            week_day = stream.readLine()[:-1]
            line = stream.readLine()
            while line:
                params_of_event = line.split(',')
                time = int(params_of_event[0].replace(':', ''))
                duration = int(params_of_event[1])
                title = params_of_event[2]
                location = params_of_event[3]
                department = params_of_event[4]
                start_day_number = days_of_week.index(week_day)
                days_list = [
                    k for k in range(start_day_number, num_of_days, 7)
                ]

                type = ScheduleEvent.Type.HEAD if department == 'Руководство' else ScheduleEvent.Type.DEP
                participants_list = []
                if type == ScheduleEvent.Type.HEAD:
                    participants_list.append(self.firm.getBoss())
                    for dep in self.checked_departments:
                        participants_list.append(dep.getBoss())
                elif type == ScheduleEvent.Type.DEP:
                    for dep in self.checked_departments:
                        if dep.getName() == department:
                            participants_list.extend(dep.getEmployeeList())
                else:
                    raise Exception(
                        'Error while processing default schedule data: TYPE')

                for day in days_list:
                    if len(participants_list) != 0:
                        Matrix[int(time / 100) - 10][day - 1].append(
                            ScheduleEvent(time=time,
                                          duration=duration,
                                          title=title,
                                          location=location,
                                          type=type,
                                          part_list=participants_list,
                                          day=day))
                line = stream.readLine()

        self.Matrix = Matrix
コード例 #13
0
ファイル: myMainWindow.py プロジェクト: bingonline/QTPrj2
    def __openByStream(self, fileName):  ##用QTextStream打开文件
        fileDevice = QFile(fileName)
        if not fileDevice.exists():  #判断文件是否存在
            return False

        if not fileDevice.open(QIODevice.ReadOnly | QIODevice.Text):
            return False

        try:
            fileStream = QTextStream(fileDevice)
            fileStream.setAutoDetectUnicode(True)  #自动检测Unicode
            fileStream.setCodec("utf-8")  #必须设置编码,否则不能正常显示汉字

            # 一次性全部读出
            ##   text=fileStream.readAll()  #读取出来就是str
            ##   self.ui.textEdit.setPlainText(text)

            #逐行读取方式
            self.ui.textEdit.clear()
            while not fileStream.atEnd():
                lineStr = fileStream.readLine()  #读取文件的一行,读取出来就是str
                self.ui.textEdit.appendPlainText(lineStr)  #添加到文本框显示
        finally:
            fileDevice.close()  #关闭文件
        return True
コード例 #14
0
 def overseek(self):
     outdatar = ""
     CONFIGPATH = os.path.join(
         sys.path[0], "plugins\\ResolutionExtension\\Resolution.txt")
     if QFile(CONFIGPATH).exists() == False:  #Default
         outdatar = outdatar + self.overread(QSize(70, 70))
         outdatar = outdatar + self.overread(QSize(95, 80))
         outdatar = outdatar + self.overread(QSize(95, 95))
         outdatar = outdatar + self.overread(QSize(160, 140))
         outdatar = outdatar + self.overread(QSize(200, 200))
     else:
         fh = QFile(CONFIGPATH)
         fh.open(QIODevice.ReadOnly)
         stream = QTextStream(fh)
         stream.setCodec(CODEC)
         while stream.atEnd() == False:
             tem = stream.readLine()
             if tem[0] == '#':
                 continue
             tems = tem.split(",")
             if len(tems) == 2 and tems[0].isdigit() and tems[1].isdigit():
                 outdatar = outdatar + self.overread(
                     QSize(int(tems[0]), int(tems[1])))
         fh.close()
     return outdatar
コード例 #15
0
ファイル: __init__.py プロジェクト: BakedRibs/Sudoku
 def openTxtFile(self):
     filePath = QFileDialog.getOpenFileName(self, "Open Txt File",
                                            os.getcwd() + "/sudokuIni/",
                                            "Txt Files(*.txt)")
     file = QFile(filePath[0])
     if file.open(QIODevice.ReadOnly):
         fileTxt = QTextStream(file)
         self.insertArray = []
         for i in range(9):
             self.insertArray.append([])
             line = fileTxt.readLine()
             lineParts = line.split(' ')
             for j in range(9):
                 self.insertArray[i].append(int(lineParts[j]))
         self.insertListConfirmed = []
         for i in range(9):
             for j in range(9):
                 if self.insertArray[i][j] != 0:
                     self.insertListConfirmed.append([[
                         i, j, self.insertArray[i][j]
                     ]])  #根据txt文件中读取的信息,设置确定的填充序列
         for i in range(len(self.insertListConfirmed)):
             self.setGridItem(
                 self.insertListConfirmed[i][
                     len(self.insertListConfirmed[i]) - 1][0],
                 self.insertListConfirmed[i][
                     len(self.insertListConfirmed[i]) - 1][1],
                 self.insertListConfirmed[i][
                     len(self.insertListConfirmed[i]) - 1][2])
             self.newOnlyOne[self.insertListConfirmed[i][
                 len(self.insertListConfirmed[i]) -
                 1][0]][self.insertListConfirmed[i][
                     len(self.insertListConfirmed[i]) - 1][1]] = 1
         self.showAllAlone()  #显示所有已经确定的小格
         self.fillBt.setEnabled(True)
コード例 #16
0
    def addDataSet(self):
        self.m_dataSet = VariantDataSet()
        itemList = []

        stream = QTextStream()
        dataFile = QFile(QFileInfo(__file__).absolutePath() + '/raindata.txt')
        if dataFile.open(QIODevice.ReadOnly | QIODevice.Text):
            stream.setDevice(dataFile)
            while not stream.atEnd():
                line = stream.readLine()
                if line.startswith('#'):
                    continue

                # Each line has three data items: year, month, and rainfall
                # values.
                strList = line.split(',')
                if len(strList) < 3:
                    continue

                # Store year and month as strings, and rainfall value as a
                # float into a tuple and add the tupe to the item list.
                newItem = (strList[0].strip(), strList[1].strip(),
                           float(strList[2]))
                itemList.append(newItem)

        self.m_dataSet.addItems(itemList)
        self.m_proxy.setDataSet(self.m_dataSet)

        self.m_mapping = VariantBarDataMapping(
            rowCategories=self.m_years, columnCategories=self.m_numericMonths)
        self.m_proxy.setMapping(self.m_mapping)
コード例 #17
0
ファイル: bdrc-audit.py プロジェクト: buda-base/bdrc-audit
    def findFiles(self, files, text):
        progressDialog = QProgressDialog(self)

        progressDialog.setCancelButtonText("&Cancel")
        progressDialog.setRange(0, files.count())
        progressDialog.setWindowTitle("Find Files")

        foundFiles = []

        for i in range(files.count()):
            progressDialog.setValue(i)
            progressDialog.setLabelText("Searching file number %d of %d..." %
                                        (i, files.count()))
            QApplication.processEvents()

            if progressDialog.wasCanceled():
                break

            inFile = QFile(self.currentDir.absoluteFilePath(files[i]))

            if inFile.open(QIODevice.ReadOnly):
                stream = QTextStream(inFile)
                while not stream.atEnd():
                    if progressDialog.wasCanceled():
                        break
                    line = stream.readLine()
                    if text in line:
                        foundFiles.append(files[i])
                        break

        progressDialog.close()

        return foundFiles
コード例 #18
0
ファイル: findfiles.py プロジェクト: death-finger/Scripts
    def findFiles(self, files, text):
        progressDialog = QProgressDialog(self)

        progressDialog.setCancelButtonText("&Cancel")
        progressDialog.setRange(0, files.count())
        progressDialog.setWindowTitle("Find Files")

        foundFiles = []

        for i in range(files.count()):
            progressDialog.setValue(i)
            progressDialog.setLabelText("Searching file number %d of %d..." % (i, files.count()))
            QApplication.processEvents()

            if progressDialog.wasCanceled():
                break

            inFile = QFile(self.currentDir.absoluteFilePath(files[i]))

            if inFile.open(QIODevice.ReadOnly):
                stream = QTextStream(inFile)
                while not stream.atEnd():
                    if progressDialog.wasCanceled():
                        break
                    line = stream.readLine()
                    if text in line:
                        foundFiles.append(files[i])
                        break

        progressDialog.close()

        return foundFiles
コード例 #19
0
    def _grep_file(self, file_path, file_name):
        """Search for each line inside the file"""
        file_obj = QFile(file_path)
        if not file_obj.open(QFile.ReadOnly):
            return
        stream = QTextStream(file_obj)
        lines = []
        append = lines.append
        line_index = 0
        line = stream.readLine()
        while not self._cancel and not stream.atEnd():
            column = self.search_pattern.indexIn(line)
            if column != -1:
                append((line_index, line))
            # Take the next line
            line = stream.readLine()
            line_index += 1

        p = os.path.join(self.root_dir, file_path)
        self.resultAvailable.emit((p, lines))
コード例 #20
0
ファイル: find_in_files.py プロジェクト: ninja-ide/ninja-ide
    def _grep_file(self, file_path, file_name):
        """Search for each line inside the file"""
        file_obj = QFile(file_path)
        if not file_obj.open(QFile.ReadOnly):
            return
        stream = QTextStream(file_obj)
        lines = []
        append = lines.append
        line_index = 0
        line = stream.readLine()
        while not self._cancel and not stream.atEnd():
            column = self.search_pattern.indexIn(line)
            if column != -1:
                append((line_index, line))
            # Take the next line
            line = stream.readLine()
            line_index += 1

        p = os.path.join(self.root_dir, file_path)
        self.resultAvailable.emit((p, lines))
コード例 #21
0
ファイル: UI.py プロジェクト: SarahNgl/Batak-Translator
 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();
コード例 #22
0
def _get_file_content(plugin_file):
    name = ':/plugins/{}'.format(plugin_file)
    file = QFile(name)
    if file.open(QIODevice.ReadOnly | QIODevice.Text):
        file_content = ""  # type: str
        text_stream = QTextStream(file)
        while not text_stream.atEnd():
            file_content += text_stream.readLine() + "\n"
        file.close()
        return file_content
    else:
        return None
コード例 #23
0
ファイル: window.py プロジェクト: svenoaks/retext
	def readExtension(self, fileName):
		extFile = QFile(fileName)
		extFile.open(QIODevice.ReadOnly)
		extension = {}
		stream = QTextStream(extFile)
		while not stream.atEnd():
			line = stream.readLine()
			if '=' in line:
				index = line.index('=')
				extension[line[:index].rstrip()] = line[index+1:].lstrip()
		extFile.close()
		return extension
コード例 #24
0
ファイル: window.py プロジェクト: daffodil/retext
	def readExtension(self, fileName):
		extFile = QFile(fileName)
		extFile.open(QIODevice.ReadOnly)
		extension = {}
		stream = QTextStream(extFile)
		while not stream.atEnd():
			line = stream.readLine()
			if '=' in line:
				index = line.index('=')
				extension[line[:index].rstrip()] = line[index+1:].lstrip()
		extFile.close()
		return extension
コード例 #25
0
    def loadFile(self, filePath):
        ret = True
        absPath = QFileInfo(filePath).path()
        rulesFile = QFile(filePath)
        if (not rulesFile.exists()):
            self.mError += self.tr("No rules file found at:\n%s\n" % filePath)
            return False

        if (not rulesFile.open(QIODevice.ReadOnly | QIODevice.Text)):
            self.mError += self.tr("Error opening rules file:\n%s\n" %
                                   filePath)
            return False

        i = QTextStream(rulesFile)
        line = ' '
        while line != '':
            line = i.readLine()
            rulePath = line.strip()
            if (rulePath == '' or rulePath.startswith('#')
                    or rulePath.startswith("//")):
                continue
            if (QFileInfo(rulePath).isRelative()):
                rulePath = absPath + '/' + rulePath
            if (not QFileInfo(rulePath).exists()):
                self.mError += self.tr("File not found:\n%s" % rulePath) + '\n'
                ret = False
                continue

            if (rulePath.lower().endswith(".tmx")):
                tmxFormat = TmxMapFormat()
                rules = tmxFormat.read(rulePath)
                if (not rules):
                    self.mError += self.tr("Opening rules map failed:\n%s" %
                                           tmxFormat.errorString()) + '\n'
                    ret = False
                    continue

                tilesetManager = TilesetManager.instance()
                tilesetManager.addReferences(rules.tilesets())
                autoMapper = None
                autoMapper = AutoMapper(self.mMapDocument, rules, rulePath)
                self.mWarning += autoMapper.warningString()
                error = autoMapper.errorString()
                if error != '':
                    self.mAutoMappers.append(autoMapper)
                else:
                    self.mError += error
                    del autoMapper

            if (rulePath.lower().endswith(".txt")):
                if (not self.loadFile(rulePath)):
                    ret = False
        return ret
コード例 #26
0
ファイル: EntrySorting.py プロジェクト: devzeb/retext
    def __getSortingFileEntries(self) -> [str]:
        if not self.sortingFile.open(QFile.ReadOnly | QFile.Text):
            return []

        sortingFileEntries = []

        inStream = QTextStream(self.sortingFile)
        while not inStream.atEnd():
            line = inStream.readLine()  # A QByteArray
            sortingFileEntries.append(line)

        self.sortingFile.close()

        return sortingFileEntries
コード例 #27
0
    def loadFile(self, filePath):
        ret = True
        absPath = QFileInfo(filePath).path()
        rulesFile = QFile(filePath)
        if (not rulesFile.exists()):
            self.mError += self.tr("No rules file found at:\n%s\n"%filePath)
            return False

        if (not rulesFile.open(QIODevice.ReadOnly | QIODevice.Text)):
            self.mError += self.tr("Error opening rules file:\n%s\n"%filePath)
            return False

        i = QTextStream(rulesFile)
        line = ' '
        while line != '':
            line = i.readLine()
            rulePath = line.strip()
            if (rulePath=='' or rulePath.startswith('#') or rulePath.startswith("//")):
                continue
            if (QFileInfo(rulePath).isRelative()):
                rulePath = absPath + '/' + rulePath
            if (not QFileInfo(rulePath).exists()):
                self.mError += self.tr("File not found:\n%s"%rulePath) + '\n'
                ret = False
                continue

            if (rulePath.lower().endswith(".tmx")):
                tmxFormat = TmxMapFormat()
                rules = tmxFormat.read(rulePath)
                if (not rules):
                    self.mError += self.tr("Opening rules map failed:\n%s"%tmxFormat.errorString()) + '\n'
                    ret = False
                    continue

                tilesetManager = TilesetManager.instance()
                tilesetManager.addReferences(rules.tilesets())
                autoMapper = None
                autoMapper = AutoMapper(self.mMapDocument, rules, rulePath)
                self.mWarning += autoMapper.warningString()
                error = autoMapper.errorString()
                if error != '':
                    self.mAutoMappers.append(autoMapper)
                else:
                    self.mError += error
                    del autoMapper

            if (rulePath.lower().endswith(".txt")):
                if (not self.loadFile(rulePath)):
                    ret = False
        return ret
 def extruder_M2O(self):
     flag = False
     CONFIGPATH = os.path.join(sys.path[0],"plugins\\ResolutionExtension\\Resolution.txt")
     if QFile(CONFIGPATH).exists() == True:
         fh = QFile(CONFIGPATH)
         fh.open(QIODevice.ReadOnly)
         stream = QTextStream(fh)
         stream.setCodec(CODEC)
         while stream.atEnd() == False:
             tem = stream.readLine()
             if tem.startswith("# extruder_M2O"):
                 if (tem.split("="))[1].strip().lower() == "yes":
                     flag = True
             else:
                 continue
         fh.close()
     return flag
コード例 #29
0
ファイル: mainwindow.py プロジェクト: panderan/text-detection
 def init_resources(self):
     strfile = QFile(':/string/strings')
     strfile.open(QIODevice.ReadOnly | QIODevice.Text)
     ts = QTextStream(strfile)
     key, value = "", ""
     while ts.atEnd() == False:
         line = ts.readLine()
         if len(line) < 1:
             continue
         elif line[0] == '@':
             if key != "":
                 self.strings[key] = value
                 key, value = "", ""
             key = line[1:]
         else:
             value += line
     self.strings[key] = value
     strfile.close()
コード例 #30
0
 def __readTxt(self, file_name: str) -> bool:
     """
     :param file_name: str,txt文件名
     :return: bool,是否成功
     """
     file_device = QFile(file_name)
     if not file_device.exists():
         return False
     if not file_device.open(QIODevice.ReadOnly | QIODevice.Text):
         return False
     try:
         file_stream = QTextStream(file_device)
         file_stream.setAutoDetectUnicode(True)  # 自动检测unicode
         file_stream.setCodec('utf-8')  # 不然不能读取汉字
         while not file_stream.atEnd():
             line_str = file_stream.readLine()  # 一行行读,读出来就是str
             self.__import2Table(line_str)
     finally:
         file_device.close()
     return True
コード例 #31
0
    def __openByStream(self, fileName):
        fileDevice = QFile(fileName)
        if not fileDevice.exists():
            return False

        if not fileDevice.open(QIODevice.ReadOnly | QIODevice.Text):
            return False

        try:
            fileStream = QTextStream(fileDevice)
            fileStream.setAutoDetectUnicode(True)
            fileStream.setCodec("utf-8")

            self.ui.textEdit.clear()
            while not fileStream.atEnd():
                lineStr = fileStream.readLine()
                self.ui.textEdit.appendPlainText(lineStr)

        finally:
            fileDevice.close()
        return True
コード例 #32
0
 def parse(parent, path, lang="[ru]"):
     """Статическая функция для парсинга файла с расширением .desktop
        для получения названия, исполняемой строки, и имя иконки.
        в качестве первого входящего параметра используется ссылка на родителя, 
        т.е. на MainWindow для вызова QMessageBox, в качество второго параметра
        имя файла, и третий не обязательный это код языка в кв. скобках.
        После того как будет получено имя иконки проверяем, существует ли этот файл,
        если нет, то пытаемся найти имя файла функцией getIconFromName.
        Опять проверяем на существование полученного результата, если не существуют
        то возвращаем путь к иконке "зашитой" в ресурсы :/images/icon.png.
     """
     file = QFile(path)
     if not file.open(QFile.ReadOnly | QFile.Text):
         QMessageBox.information(parent, "Не могу открыть файл", path)
         return "", "", ""
     title = ""
     icon = ""
     exec = ""
     firstline = True
     if path.endswith(".desktop"):
         stream = QTextStream(file)
         while not stream.atEnd():
             line = stream.readLine()
             if len(line) > 1:
                 if firstline:
                     if line == "[Desktop Entry]":
                         firstline = False
                 else:
                     if line.startswith("["): break
                     if line.startswith("Icon="):
                         icon = line[-len(line) + 5:]
                     if line.startswith("Name" + lang + "="):
                         title = line[-len(line) + 9:]
                     if line.startswith("Name=") and title == "":
                         title = line[-len(line) + 5:]
                     if line.startswith("Exec="):
                         exec = line[-len(line) + 5:]
     file.close()
     return title, icon, exec
コード例 #33
0
    def addData(self):
        dataArray = []

        stream = QTextStream()
        dataFile = QFile(QFileInfo(__file__).absolutePath() + '/data.txt')
        if dataFile.open(QIODevice.ReadOnly | QIODevice.Text):
            stream.setDevice(dataFile)
            while not stream.atEnd():
                line = stream.readLine()
                if line.startswith('#'):
                    continue

                strList = line.split(',')
                # Each line has three data items: xPos, yPos and zPos values.
                if len(strList) < 3:
                    continue

                position = QVector3D(float(strList[0]), float(strList[1]),
                                     float(strList[2]))
                dataArray.append(QScatterDataItem(position))

        self.m_graph.seriesList()[0].dataProxy().resetArray(dataArray)
コード例 #34
0
class QtSingleApplication(QApplication):
    """
    This class makes sure that we can only start one Tribler application.
    When a user tries to open a second Tribler instance, the current active one will be brought to front.
    """

    messageReceived = pyqtSignal(unicode)

    def __init__(self, win_id, *argv):

        logfunc = logging.info
        logfunc(sys._getframe().f_code.co_name + '()')

        QApplication.__init__(self, *argv)

        self._id = win_id
        self._activation_window = None
        self._activate_on_message = False

        # Is there another instance running?
        self._outSocket = QLocalSocket()
        self._outSocket.connectToServer(self._id)
        self._isRunning = self._outSocket.waitForConnected()

        self._outStream = None
        self._inSocket = None
        self._inStream = None
        self._server = None

        if self._isRunning:
            # Yes, there is.
            self._outStream = QTextStream(self._outSocket)
            self._outStream.setCodec('UTF-8')
        else:
            # No, there isn't, at least not properly.
            # Cleanup any past, crashed server.
            error = self._outSocket.error()
            logfunc(LOGVARSTR % ('self._outSocket.error()', error))
            if error == QLocalSocket.ConnectionRefusedError:
                logfunc('received QLocalSocket.ConnectionRefusedError; ' + \
                        'removing server.')
                self.close()
                QLocalServer.removeServer(self._id)
            self._outSocket = None
            self._server = QLocalServer()
            self._server.listen(self._id)
            self._server.newConnection.connect(self._on_new_connection)

        logfunc(sys._getframe().f_code.co_name + '(): returning')

    def close(self):
        logfunc = logging.info
        logfunc(sys._getframe().f_code.co_name + '()')
        if self._inSocket:
            self._inSocket.disconnectFromServer()
        if self._outSocket:
            self._outSocket.disconnectFromServer()
        if self._server:
            self._server.close()
        logfunc(sys._getframe().f_code.co_name + '(): returning')

    def is_running(self):
        return self._isRunning

    def get_id(self):
        return self._id

    def activation_window(self):
        return self._activation_window

    def set_activation_window(self, activation_window, activate_on_message=True):
        self._activation_window = activation_window
        self._activate_on_message = activate_on_message

    def activate_window(self):
        if not self._activation_window:
            return
        self._activation_window.setWindowState(
            self._activation_window.windowState() & ~Qt.WindowMinimized)
        self._activation_window.raise_()

    def send_message(self, msg):
        if not self._outStream:
            return False
        self._outStream << msg << '\n'
        self._outStream.flush()
        return self._outSocket.waitForBytesWritten()

    def _on_new_connection(self):
        if self._inSocket:
            self._inSocket.readyRead.disconnect(self._on_ready_read)
        self._inSocket = self._server.nextPendingConnection()
        if not self._inSocket:
            return
        self._inStream = QTextStream(self._inSocket)
        self._inStream.setCodec('UTF-8')
        self._inSocket.readyRead.connect(self._on_ready_read)
        if self._activate_on_message:
            self.activate_window()

    def _on_ready_read(self):
        while True:
            msg = self._inStream.readLine()
            if not msg:
                break
            self.messageReceived.emit(msg)
コード例 #35
0
ファイル: qt_single_application.py プロジェクト: step21/vorta
class QtSingleApplication(QApplication):
    """
    Adapted from https://stackoverflow.com/a/12712362/11038610

    Published by Johan Rade under 2-clause BSD license, opensource.org/licenses/BSD-2-Clause
    """
    message_received_event = pyqtSignal(str)

    def __init__(self, id, *argv):

        super().__init__(*argv)
        self._id = id

        # Is there another instance running?
        self._outSocket = QLocalSocket()
        self._outSocket.connectToServer(self._id)
        self._isRunning = self._outSocket.waitForConnected()

        if self._isRunning:
            # Yes, there is.
            self._outStream = QTextStream(self._outSocket)
            self._outStream.setCodec('UTF-8')
        else:
            # No, there isn't.
            self._outSocket = None
            self._outStream = None
            self._inSocket = None
            self._inStream = None
            self._server = QLocalServer()
            self._server.removeServer(self._id)
            self._server.listen(self._id)
            self._server.newConnection.connect(self._onNewConnection)

    def isRunning(self):
        return self._isRunning

    def id(self):
        return self._id

    def sendMessage(self, msg):
        if not self._outStream:
            return False
        self._outStream << msg << '\n'
        self._outStream.flush()
        return self._outSocket.waitForBytesWritten()

    def _onNewConnection(self):
        if self._inSocket:
            self._inSocket.readyRead.disconnect(self._onReadyRead)
        self._inSocket = self._server.nextPendingConnection()
        if not self._inSocket:
            return
        self._inStream = QTextStream(self._inSocket)
        self._inStream.setCodec('UTF-8')
        self._inSocket.readyRead.connect(self._onReadyRead)

    def _onReadyRead(self):
        while True:
            msg = self._inStream.readLine()
            if not msg:
                break
            self.message_received_event.emit(msg)
コード例 #36
0
 def loadQTextStream(self):
     error = None
     fh = None
     try:
         fh = QFile(self.__fname)
         if not fh.open(QIODevice.ReadOnly):
             raise IOError(unicode(fh.errorString()))
         stream = QTextStream(fh)
         stream.setCodec(CODEC)
         self.clear(False)
         lino = 0
         while not stream.atEnd():
             title = year = minutes = acquired = notes = None
             line = stream.readLine()
             lino += 1
             if not line.startsWith("{{MOVIE}}"):
                 raise ValueError("no movie record found")
             else:
                 title = line.mid(len("{{MOVIE}}")).trimmed()
             if stream.atEnd():
                 raise ValueError("premature end of file")
             line = stream.readLine()
             lino += 1
             parts = line.split(" ")
             if parts.count() != 3:
                 raise ValueError("invalid numeric data")
             year = intFromQStr(parts[0])
             minutes = intFromQStr(parts[1])
             ymd = parts[2].split("-")
             if ymd.count() != 3:
                 raise ValueError("invalid acquired date")
             acquired = QDate(intFromQStr(ymd[0]), intFromQStr(ymd[1]),
                              intFromQStr(ymd[2]))
             if stream.atEnd():
                 raise ValueError("premature end of file")
             line = stream.readLine()
             lino += 1
             if line != "{NOTES}":
                 raise ValueError("notes expected")
             notes = QString()
             while not stream.atEnd():
                 line = stream.readLine()
                 lino += 1
                 if line == "{{ENDMOVIE}}":
                     if (title is None or year is None or minutes is None
                             or acquired is None or notes is None):
                         raise ValueError("incomplete record")
                     self.add(
                         Movie(title, year, minutes, acquired,
                               notes.trimmed()))
                     break
                 else:
                     notes += line + "\n"
             else:
                 raise ValueError("missing endmovie marker")
     except (IOError, OSError, ValueError) as e:
         error = "Failed to load: {0} on line {1}".format(e, lino)
     finally:
         if fh is not None:
             fh.close()
         if error is not None:
             return False, error
         self.__dirty = False
         return True, "Loaded {0} movie records from {1}".format(
             len(self.__movies),
             QFileInfo(self.__fname).fileName())
コード例 #37
0
ファイル: dsingleapplication.py プロジェクト: yxsyxs/QMusic
class QSingleApplication(QApplication):

    messageReceived = pyqtSignal(str)

    def __init__(self, id, *argv):

        super(QSingleApplication, self).__init__(*argv)
        self._id = id
        self._activationWindow = None
        self._activateOnMessage = False
        self._server = None

        # Is there another instance running?
        self._outSocket = QLocalSocket()
        self._outSocket.connectToServer(self._id)
        self._outSocket.error.connect(self.handleError)
        self._isRunning = self._outSocket.waitForConnected()

        if self._isRunning:
            # Yes, there is.
            self._outStream = QTextStream(self._outSocket)
            self._outStream.setCodec('UTF-8')
        else:
            # No, there isn't.
            self._outSocket = None
            self._outStream = None
            self._inSocket = None
            self._inStream = None
            self._server = QLocalServer()
            self._server.listen(self._id)
            self._server.newConnection.connect(self._onNewConnection)
            self.aboutToQuit.connect(self.removeServer)

    def handleError(self, msg):
        print(msg)

    def server(self):
        return self._server

    def isRunning(self):
        return self._isRunning

    def id(self):
        return self._id

    def activationWindow(self):
        return self._activationWindow

    def setActivationWindow(self, activationWindow, activateOnMessage=True):
        self._activationWindow = activationWindow
        self._activateOnMessage = activateOnMessage

    def activateWindow(self):
        if not self._activationWindow:
            print("No registered ActivationWindow")
            return
        # Unfortunately this *doesn't* do much of any use, as it won't
        # bring the window to the foreground under KDE... sigh.
        self._activationWindow.setWindowState(
            self._activationWindow.windowState() & ~Qt.WindowMinimized)
        self._activationWindow.raise_()
        self._activationWindow.requestActivate()

    def sendMessage(self, msg, msecs=5000):
        if not self._outStream:
            return False
        self._outStream << msg << ''
        if not self._outSocket.waitForBytesWritten(msecs):
            raise RuntimeError("Bytes not written within %ss" %
                               (msecs / 1000.))

    def _onNewConnection(self):
        if self._inSocket:
            self._inSocket.readyRead.disconnect(self._onReadyRead)
        self._inSocket = self._server.nextPendingConnection()
        if not self._inSocket:
            return
        self._inStream = QTextStream(self._inSocket)
        self._inStream.setCodec('UTF-8')
        self._inSocket.readyRead.connect(self._onReadyRead)
        if self._activateOnMessage:
            self.activateWindow()

    def _onReadyRead(self):
        while True:
            msg = self._inStream.readLine()
            if not msg:
                break
            print("Message received")
            self.messageReceived.emit(msg)

    def removeServer(self):
        self._server.close()
        self._server.removeServer(self._id)
コード例 #38
0
ファイル: singleapplication.py プロジェクト: jasonrlz/klmc
class SingleApplication(QApplication):
    messageReceived = pyqtSignal(str)

    def __init__(self, appid, *argv):
        super(SingleApplication, self).__init__(*argv)
        self._appid = appid
        self._activationWindow = None
        self._activateOnMessage = False
        self._outSocket = QLocalSocket()
        self._outSocket.connectToServer(self._appid)
        self._isRunning = self._outSocket.waitForConnected()
        self._outStream = None
        self._inSocket = None
        self._inStream = None
        self._server = None
        self.settings = QSettings(SingleApplication.getSettingsPath(),
                                  QSettings.IniFormat)
        self.singleInstance = self.settings.value('singleInstance',
                                                  'on',
                                                  type=str) in {'on', 'true'}
        if self._isRunning and self.singleInstance:
            self._outStream = QTextStream(self._outSocket)
            for a in argv[0][1:]:
                a = os.path.join(os.getcwd(), a)
                if os.path.isfile(a):
                    self.sendMessage(a)
                    break
            sys.exit(0)
        else:
            error = self._outSocket.error()
            if error == QLocalSocket.ConnectionRefusedError:
                self.close()
                QLocalServer.removeServer(self._appid)
            self._outSocket = None
            self._server = QLocalServer()
            self._server.listen(self._appid)
            self._server.newConnection.connect(self._onNewConnection)

    def close(self):
        if self._inSocket:
            self._inSocket.disconnectFromServer()
        if self._outSocket:
            self._outSocket.disconnectFromServer()
        if self._server:
            self._server.close()

    @staticmethod
    def getSettingsPath() -> str:
        if sys.platform == 'win32':
            settings_path = os.path.join(QDir.homePath(), 'AppData', 'Local',
                                         'vidcutter')
        elif sys.platform == 'darwin':
            settings_path = os.path.join(QDir.homePath(), 'Library',
                                         'Preferences', 'vidcutter')
        else:
            if QFileInfo(__file__).absolutePath().startswith('/app/'):
                settings_path = QProcessEnvironment.systemEnvironment().value(
                    'XDG_CONFIG_HOME', '')
                if not len(settings_path):
                    settings_path = os.path.join(QDir.homePath(), '.var',
                                                 'app',
                                                 vidcutter.__desktopid__,
                                                 'config')
            else:
                settings_path = os.path.join(QDir.homePath(), '.config',
                                             'vidcutter')
        return os.path.join(settings_path, 'vidcutter.ini')

    def isRunning(self):
        return self._isRunning

    def appid(self):
        return self._appid

    def activationWindow(self):
        return self._activationWindow

    def setActivationWindow(self, activationWindow, activateOnMessage=True):
        self._activationWindow = activationWindow
        self._activateOnMessage = activateOnMessage

    def activateWindow(self):
        if not self._activationWindow:
            return
        self._activationWindow.setWindowState(
            self._activationWindow.windowState() & ~Qt.WindowMinimized)
        self._activationWindow.raise_()
        self._activationWindow.activateWindow()

    def sendMessage(self, msg):
        if not self._outStream:
            return False
        # noinspection PyUnresolvedReferences
        self._outStream << msg << '\n'
        self._outStream.flush()
        return self._outSocket.waitForBytesWritten()

    def _onNewConnection(self):
        if self._inSocket:
            self._inSocket.readyRead.disconnect(self._onReadyRead)
        self._inSocket = self._server.nextPendingConnection()
        if not self._inSocket:
            return
        self._inStream = QTextStream(self._inSocket)
        self._inSocket.readyRead.connect(self._onReadyRead)
        if self._activateOnMessage:
            self.activateWindow()

    def _onReadyRead(self):
        while True:
            msg = self._inStream.readLine()
            if not msg:
                break
            self.messageReceived.emit(msg)
コード例 #39
0
 def __loadRules(self):
     """
     Private method to load the rules of the subscription.
     """
     fileName = self.rulesFileName()
     f = QFile(fileName)
     if f.exists():
         if not f.open(QIODevice.ReadOnly):
             E5MessageBox.warning(
                 None,
                 self.tr("Load subscription rules"),
                 self.tr(
                     """Unable to open adblock file '{0}' for reading.""")
                 .format(fileName))
         else:
             textStream = QTextStream(f)
             header = textStream.readLine(1024)
             if not header.startswith("[Adblock"):
                 E5MessageBox.warning(
                     None,
                     self.tr("Load subscription rules"),
                     self.tr("""AdBlock file '{0}' does not start"""
                             """ with [Adblock.""")
                     .format(fileName))
                 f.close()
                 f.remove()
                 self.__lastUpdate = QDateTime()
             else:
                 from .AdBlockRule import AdBlockRule
                 
                 self.__updatePeriod = 0
                 self.__remoteModified = QDateTime()
                 self.__rules = []
                 self.__rules.append(AdBlockRule(header, self))
                 while not textStream.atEnd():
                     line = textStream.readLine()
                     self.__rules.append(AdBlockRule(line, self))
                     expires = self.__expiresRe.search(line)
                     if expires:
                         period, kind = expires.groups()
                         if kind:
                             # hours
                             self.__updatePeriod = int(period)
                         else:
                             # days
                             self.__updatePeriod = int(period) * 24
                     remoteModified = self.__remoteModifiedRe.search(line)
                     if remoteModified:
                         day, month, year, time, hour, minute = \
                             remoteModified.groups()
                         self.__remoteModified.setDate(
                             QDate(int(year),
                                   self.__monthNameToNumber[month],
                                   int(day))
                         )
                         if time:
                             self.__remoteModified.setTime(
                                 QTime(int(hour), int(minute)))
                 self.__populateCache()
                 self.changed.emit()
     elif not fileName.endswith("_custom"):
         self.__lastUpdate = QDateTime()
     
     self.checkForUpdate()
コード例 #40
0
ファイル: application.py プロジェクト: gitter-badger/eddy
class Eddy(QApplication):
    """
    This class implements the main Qt application.
    """
    messageReceived = pyqtSignal(str)

    def __init__(self, argv):
        """
        Initialize Eddy.
        :type argv: list
        """
        super().__init__(argv)

        parser = ArgumentParser()
        parser.add_argument('--nosplash', dest='nosplash', action='store_true')
        parser.add_argument('--tests', dest='tests', action='store_true')

        options, args = parser.parse_known_args(args=argv)

        self.inSocket = None
        self.inStream = None
        self.outSocket = QLocalSocket()
        self.outSocket.connectToServer(APPID)
        self.outStream = None
        self.isRunning = self.outSocket.waitForConnected()
        self.mainwindow = None
        self.pendingOpen = []
        self.server = None

        # We do not initialize a new instance of Eddy if there is a process running
        # and we are not executing the tests suite: we'll create a socket instead so we can
        # exchange messages between the 2 processes (this one and the already running one).
        if self.isRunning and not options.tests:
            self.outStream = QTextStream(self.outSocket)
            self.outStream.setCodec('UTF-8')
        else:
            self.server = QLocalServer()
            self.server.listen(APPID)
            self.outSocket = None
            self.outStream = None

            connect(self.server.newConnection, self.newConnection)
            connect(self.messageReceived, self.readMessage)

            ############################################################################################################
            #                                                                                                          #
            #   PERFORM EDDY INITIALIZATION                                                                            #
            #                                                                                                          #
            ############################################################################################################

            # Draw the splashscreen.
            self.splashscreen = None
            if not options.nosplash:
                self.splashscreen = SplashScreen(min_splash_time=4)
                self.splashscreen.show()

            # Setup layout.
            self.setStyle(Clean('Fusion'))
            with open(expandPath('@eddy/ui/clean.qss')) as sheet:
                self.setStyleSheet(sheet.read())

            # Create the main window.
            self.mainwindow = MainWindow()

            # Close the splashscreen.
            if self.splashscreen:
                self.splashscreen.wait(self.splashscreen.remaining)
                self.splashscreen.close()

            # Display the mainwindow.
            self.mainwindow.show()

            if Platform.identify() is Platform.Darwin:
                # On MacOS files being opened are handled as a QFileOpenEvent but since we don't
                # have a Main Window initialized we store them locally and we open them here.
                for filepath in self.pendingOpen:
                    self.openFile(filepath)
                self.pendingOpen = []
            else:
                # Perform document opening if files have been added to sys.argv. This is not
                # executed on Mac OS since this is already handled as a QFileOpenEvent instance.
                for filepath in argv:
                    self.openFile(filepath)

    ####################################################################################################################
    #                                                                                                                  #
    #   EVENTS                                                                                                         #
    #                                                                                                                  #
    ####################################################################################################################

    def event(self, event):
        """
        Executed when an event is received.
        :type event: T <= QEvent | QFileOpenEvent
        """
        if event.type() == QEvent.FileOpen:
            self.pendingOpen = [event.file()]
            return True
        return super().event(event)

    ####################################################################################################################
    #                                                                                                                  #
    #   INTERFACE                                                                                                      #
    #                                                                                                                  #
    ####################################################################################################################

    def activate(self):
        """
        Activate the application by raising the main window.
        """
        if self.mainwindow:
            self.mainwindow.setWindowState((self.mainwindow.windowState() & ~Qt.WindowMinimized) | Qt.WindowActive)
            self.mainwindow.activateWindow()
            self.mainwindow.raise_()

    def openFile(self, filepath):
        """
        Open the given file in the activation window.
        :type filepath: str
        :rtype: bool
        """
        if self.mainwindow:
            if not isEmpty(filepath) and os.path.isfile(filepath) and filepath.endswith(Filetype.Graphol.extension):
                self.mainwindow.openFile(filepath)
                return True
        return False

    def sendMessage(self, message):
        """
        Send a message to the other alive Eddy's process.
        :type message: str
        :rtype: bool
        """
        if self.outStream:
            self.outStream = self.outStream << message << '\n'
            self.outStream.flush()
            return self.outSocket.waitForBytesWritten()
        return False

    ####################################################################################################################
    #                                                                                                                  #
    #   SLOTS                                                                                                          #
    #                                                                                                                  #
    ####################################################################################################################

    @pyqtSlot()
    def newConnection(self):
        """
        Executed whenever a message is received.
        """
        if self.inSocket:
            # Disconnect previously connected signal slot.
            disconnect(self.inSocket.readyRead, self.readyRead)

        # Create a new socket.
        self.inSocket = self.server.nextPendingConnection()

        if self.inSocket:
            self.inStream = QTextStream(self.inSocket)
            self.inStream.setCodec('UTF-8')
            connect(self.inSocket.readyRead, self.readyRead)
            self.activate()

    @pyqtSlot()
    def readyRead(self):
        """
        Executed whenever we need to read a message.
        """
        while True:
            message = self.inStream.readLine()
            if isEmpty(message):
                break
            self.messageReceived.emit(message)

    @pyqtSlot(str)
    def readMessage(self, message):
        """
        Read a received message.
        :type message: str
        """
        for filepath in message.split(' '):
            self.openFile(filepath)
コード例 #41
0
class QtSingleApplication(QApplication):
    messageReceived = pyqtSignal(str)

    def __init__(self, _id, _viewer_id, *argv):

        super(QtSingleApplication, self).__init__(*argv)
        self._id = _id
        self._viewer_id = _viewer_id
        self._activationWindow = None
        self._activateOnMessage = False

        # Is there another instance running?
        self._outSocket = QLocalSocket()
        self._outSocket.connectToServer(self._id)
        self._isRunning = self._outSocket.waitForConnected(-1)

        if self._isRunning:
            # Yes, there is.
            self._outStream = QTextStream(self._outSocket)
            self._outStream.setCodec('UTF-8')
            # Is there another viewer runnging?
            self._outSocketViewer = QLocalSocket()
            self._outSocketViewer.connectToServer(self._viewer_id)
            self._isRunningViewer = self._outSocketViewer.waitForConnected(-1)
            if self._isRunningViewer:
                self._outStreamViewer = QTextStream(self._outSocketViewer)
                self._outStreamViewer.setCodec('UTF-8')
            else:
                # app is running, we announce us as viewer app
                # First we remove existing servers of that name that might not have been properly closed as the server died
                QLocalServer.removeServer(self._viewer_id)
                self._outSocketViewer = None
                self._outStreamViewer = None
                self._inSocket = None
                self._inStream = None
                self._server = QLocalServer()
                self._server.listen(self._viewer_id)
                self._server.newConnection.connect(self._onNewConnection)
        else:
            self._isRunningViewer = False
            # No, there isn't.
            # First we remove existing servers of that name that might not have been properly closed as the server died
            QLocalServer.removeServer(self._id)
            self._outSocket = None
            self._outStream = None
            self._inSocket = None
            self._inStream = None
            self._server = QLocalServer()
            self._server.listen(self._id)
            self._server.newConnection.connect(self._onNewConnection)

    def isRunning(self):
        return self._isRunning

    def isRunningViewer(self):
        return self._isRunningViewer

    def id(self):
        return self._id

    def activationWindow(self):
        return self._activationWindow

    def setActivationWindow(self, activationWindow, activateOnMessage=True):
        self._activationWindow = activationWindow
        self._activateOnMessage = activateOnMessage

    def activateWindow(self):
        if not self._activationWindow:
            return

        self._activationWindow.show()
        self._activationWindow.setWindowState(
            self._activationWindow.windowState() & ~Qt.WindowMinimized)
        self._activationWindow.raise_()
        self._activationWindow.activateWindow()

    def sendMessage(self, msg):
        if not self._outStream:
            return False
        self._outStream << msg << '\n'
        self._outStream.flush()
        return self._outSocket.waitForBytesWritten()

    @pyqtSlot()
    def _onNewConnection(self):
        if self._inSocket:
            self._inSocket.readyRead.disconnect(self._onReadyRead)
        self._inSocket = self._server.nextPendingConnection()
        if not self._inSocket:
            return
        self._inStream = QTextStream(self._inSocket)
        self._inStream.setCodec('UTF-8')
        self._inSocket.readyRead.connect(self._onReadyRead)
        if self._activateOnMessage and self._isRunning:
            self.activateWindow()

    @pyqtSlot()
    def _onReadyRead(self):
        while True:
            msg = self._inStream.readLine()
            if not msg: break
            self.messageReceived.emit(msg)
コード例 #42
0
class QtSingleApplication(QApplication):

    messageReceived = pyqtSignal(str)

    def __init__(self, id, *argv):

        super(QtSingleApplication, self).__init__(*argv)
        self._id = id
        self._activationWindow = None
        self._activateOnMessage = False

        # Is there another instance running?
        self._outSocket = QLocalSocket()
        self._outSocket.connectToServer(self._id)
        self._isRunning = self._outSocket.waitForConnected()

        if self._isRunning:
            # Yes, there is.
            self._outStream = QTextStream(self._outSocket)
            self._outStream.setCodec("UTF-8")
        else:
            # No, there isn't.
            self._outSocket = None
            self._outStream = None
            self._inSocket = None
            self._inStream = None
            self._server = QLocalServer()
            self._server.listen(self._id)
            self._server.newConnection.connect(self._onNewConnection)

    def isRunning(self):
        return self._isRunning

    def id(self):
        return self._id

    def activationWindow(self):
        return self._activationWindow

    def setActivationWindow(self, activationWindow, activateOnMessage=True):
        self._activationWindow = activationWindow
        self._activateOnMessage = activateOnMessage

    def activateWindow(self):
        if not self._activationWindow:
            return

        self._activationWindow.show()
        self._activationWindow.setWindowState(self._activationWindow.windowState() & ~Qt.WindowMinimized)
        self._activationWindow.raise_()
        self._activationWindow.activateWindow()

    def sendMessage(self, msg):
        if not self._outStream:
            return False
        self._outStream << msg << "\n"
        self._outStream.flush()
        return self._outSocket.waitForBytesWritten()

    def _onNewConnection(self):
        if self._inSocket:
            self._inSocket.readyRead.disconnect(self._onReadyRead)
        self._inSocket = self._server.nextPendingConnection()
        if not self._inSocket:
            return
        self._inStream = QTextStream(self._inSocket)
        self._inStream.setCodec("UTF-8")
        self._inSocket.readyRead.connect(self._onReadyRead)
        if self._activateOnMessage:
            self.activateWindow()

    def _onReadyRead(self):
        while True:
            msg = self._inStream.readLine()
            if not msg:
                break
            self.messageReceived.emit(msg)
コード例 #43
0
ファイル: flareplugin.py プロジェクト: theall/Python-Tiled
    def read(self, fileName):
        file = QFile(fileName)
        if (not file.open (QIODevice.ReadOnly)):
            self.mError = self.tr("Could not open file for reading.")
            return None
        
        # default to values of the original flare alpha game.
        map = Map(Map.Orientation.Isometric, 256, 256, 64, 32)
        stream = QTextStream(file)
        line = QString()
        sectionName = QString()
        newsection = False
        path = QFileInfo(file).absolutePath()
        base = 10
        gidMapper = GidMapper()
        gid = 1
        tilelayer = None
        objectgroup = None
        mapobject = None
        tilesetsSectionFound = False
        headerSectionFound = False
        tilelayerSectionFound = False # tile layer or objects
        while (not stream.atEnd()):
            line = stream.readLine()
            if line == '':
                continue
            startsWith = line[0]
            if (startsWith == '['):
                sectionName = line[1:line.index(']')]
                newsection = True
                continue
            
            if (sectionName == "header"):
                headerSectionFound = True
                #get map properties
                epos = line.index('=')
                if (epos != -1):
                    key = line[:epos].strip()
                    value = line[epos + 1:].strip()
                    if (key == "width"):
                        map.setWidth(Int(value))
                    elif (key == "height"):
                        map.setHeight(Int(value))
                    elif (key == "tilewidth"):
                        map.setTileWidth(Int(value))
                    elif (key == "tileheight"):
                        map.setTileHeight(Int(value))
                    elif (key == "orientation"):
                        map.setOrientation(orientationFromString(value))
                    else:
                        map.setProperty(key, value)
                
            elif (sectionName == "tilesets"):
                tilesetsSectionFound = True
                epos = line.index('=')
                key = line[:epos].strip()
                value = line[epos + 1:].strip()
                if (key == "tileset"):
                    _list = value.split(',')
                    absoluteSource = _list[0]
                    if (QDir.isRelativePath(absoluteSource)):
                        absoluteSource = path + '/' + absoluteSource
                    tilesetwidth = 0
                    tilesetheight = 0
                    if len(_list) > 2:
                        tilesetwidth = Int(_list[1])
                        tilesetheight = Int(_list[2])
                    
                    tileset = Tileset.create(QFileInfo(absoluteSource).fileName(), tilesetwidth, tilesetheight)
                    ok = tileset.loadFromImage(absoluteSource)
                    if not ok:
                        self.mError = self.tr("Error loading tileset %s, which expands to %s. Path not found!"%(_list[0], absoluteSource))
                        return None
                    else :
                        if len(_list) > 4:
                            tileset.setTileOffset(QPoint(Int(_list[3]),Int(_list[4])))
                        gidMapper.insert(gid, tileset)
                        if len(_list) > 5:
                            gid += Int(_list[5])
                        else :
                            gid += tileset.tileCount()
                        
                        map.addTileset(tileset)

            elif (sectionName == "layer"):
                if (not tilesetsSectionFound):
                    self.mError = self.tr("No tilesets section found before layer section.")
                    return None
                
                tilelayerSectionFound = True
                epos = line.index('=')
                if (epos != -1):
                    key = line[:epos].strip()
                    value = line[epos + 1:].strip()
                    if (key == "type"):
                        tilelayer = TileLayer(value, 0, 0, map.width(),map.height())
                        map.addLayer(tilelayer)
                    elif (key == "format"):
                        if (value == "dec"):
                            base = 10
                        elif (value == "hex"):
                            base = 16
                        
                    elif (key == "data"):
                        for y in range(map.height()):
                            line = stream.readLine()
                            l = line.split(',')
                            for x in range(min(map.width(), len(l))):
                                ok = False
                                tileid = int(l[x], base)
                                c, ok = gidMapper.gidToCell(tileid)
                                if (not ok):
                                    self.mError += self.tr("Error mapping tile id %1.").arg(tileid)
                                    return None
                                
                                tilelayer.setCell(x, y, c)

                    else :
                        tilelayer.setProperty(key, value)

            else :
                if (newsection):
                    if (map.indexOfLayer(sectionName) == -1):
                        objectgroup = ObjectGroup(sectionName, 0,0,map.width(), map.height())
                        map.addLayer(objectgroup)
                    else :
                        objectgroup = map.layerAt(map.indexOfLayer(sectionName))
                    
                    mapobject = MapObject()
                    objectgroup.addObject(mapobject)
                    newsection = False
                
                if (not mapobject):
                    continue
                if (startsWith == '#'):
                    name = line[1].strip()
                    mapobject.setName(name)
                
                epos = line.index('=')
                if (epos != -1):
                    key = line[:epos].strip()
                    value = line[epos + 1:].strip()
                    if (key == "type"):
                        mapobject.setType(value)
                    elif (key == "location"):
                        loc = value.split(',')
                        x,y = 0.0, 0.0
                        w,h = 0, 0
                        if (map.orientation() == Map.Orthogonal):
                            x = loc[0].toFloat()*map.tileWidth()
                            y = loc[1].toFloat()*map.tileHeight()
                            if len(loc) > 3:
                                w = Int(loc[2])*map.tileWidth()
                                h = Int(loc[3])*map.tileHeight()
                            else :
                                w = map.tileWidth()
                                h = map.tileHeight()
                            
                        else :
                            x = loc[0].toFloat()*map.tileHeight()
                            y = loc[1].toFloat()*map.tileHeight()
                            if len(loc) > 3:
                                w = Int(loc[2])*map.tileHeight()
                                h = Int(loc[3])*map.tileHeight()
                            else :
                                w = h = map.tileHeight()

                        mapobject.setPosition(QPointF(x, y))
                        mapobject.setSize(w, h)
                    else :
                        mapobject.setProperty(key, value)


        if (not headerSectionFound or not tilesetsSectionFound or not tilelayerSectionFound):
            self.mError = self.tr("This seems to be no valid flare map. "
                        "A Flare map consists of at least a header "
                        "section, a tileset section and one tile layer.")
            return None
        
        return map