Example #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
Example #2
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)
Example #3
0
    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
Example #4
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
    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))
Example #6
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()
Example #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))
    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
Example #9
0
    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
Example #10
0
    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
Example #11
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
Example #12
0
    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()
Example #13
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
    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
Example #15
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
Example #16
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
Example #17
0
	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
Example #18
0
	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
Example #19
0
    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
 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
Example #21
0
 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()
Example #22
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))
Example #23
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();
Example #24
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))
Example #25
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
Example #26
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
Example #27
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)
Example #28
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
Example #29
0
    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
Example #30
0
    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
Example #31
0
    def receiveMessage(self):
        stream = QTextStream(self.conn)
        if stream.atEnd():
            return
        data = stream.readAll()

        for json_str in data.split("\n")[:-1]:
            obj = json.loads(json_str)
            msgType = obj["type"]
            if msgType == self.TYPE_NOTIFICATION:
                self.log("Notification Received. code: {0}".format(
                    obj["params"].get("code")))
                if obj["params"].get("code") == self.N_DATA_RECEIVED:
                    memKey = obj["params"]["memoryKey"]
                    mem = self._mem[memKey]
                    if mem.isAttached():
                        mem.detach()
                        self.log(
                            "Shared memory detached: key={0}".format(memKey))
                    del self._mem[memKey]
                else:
                    self.notified.emit(obj["params"])

            elif msgType == self.TYPE_REQUEST:
                self.log(
                    "Request Received. dataType: {0}, renderId: {1}".format(
                        obj["params"].get("dataType"),
                        obj["params"].get("renderId")))
                self.requestReceived.emit(obj["params"])

            elif msgType == self.TYPE_RESPONSE:
                self.log(
                    "Response Received. dataType: {0}, renderId: {1}".format(
                        obj["meta"].get("dataType"),
                        obj["meta"].get("renderId")))
                mem = QSharedMemory(obj["memoryKey"])
                if not mem.attach(QSharedMemory.ReadOnly):
                    self.log(
                        "Cannot attach this process to the shared memory segment: {0}"
                        .format(mem.errorString()))
                    return

                size = mem.size()
                self.log("Size of memory segment is {0} bytes.".format(size))

                mem.lock()
                ba = QByteArray()
                buffer = QBuffer(ba)
                buffer.setData(mem.constData())
                mem.unlock()
                mem.detach()

                data = ba.data()
                lines = data.split(b"\n")
                for line in lines[:5]:
                    self.log(line[:76])
                if len(lines) > 5:
                    self.log("--Total {0} Lines Received--".format(len(lines)))

                self.notify({
                    "code": self.N_DATA_RECEIVED,
                    "memoryKey": obj["memoryKey"]
                })
                self.responseReceived.emit(data, obj["meta"])
Example #32
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()
Example #33
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())
Example #34
0
class NSwapFile(QObject):
    """
    In case Ninja-IDE crash, this can be used to recover the lost data.

    When the user begins to edit an existing file on the disk, this object
    creates a swap file and activates a timer that will execute a function,
    that will update that swap file as soon as the timeout ends (by default,
    is 15 seconds).
    The swap file is deleted when the original file is saved or closed.
    When system or Ninja crash, the swap file exists on disk and Ninja will
    used to recover the lost data.
    """

    canBeRecovered = pyqtSignal()

    def __init__(self, neditable):
        QObject.__init__(self)
        self._neditable = neditable
        self.__swap_file = QFile()
        self.__stream = QTextStream()

        # Activate timer when user typing
        self.__timer = QTimer()
        self.__timer.setSingleShot(True)

        self.__timer.timeout.connect(self._finish_typing)
        self._neditable.fileLoaded.connect(self._file_loaded)
        self._neditable.fileSaved.connect(self._file_saved)

        self.init(tracking=True)

    def init(self, tracking):
        if tracking:
            self._neditable.editor.textChanged.connect(self._start_typing)
            self._neditable.fileClosing.connect(self._file_closed)
        else:
            self._neditable.editor.textChanged.disconnect(self._start_typing)
            self._neditable.fileClosing.disconnect(self._file_closed)

    def _file_closed(self):
        """Editor was closed normally, now remove swap file"""

        self.__remove()

    def _file_saved(self):
        """If file is saved, remove swap file"""

        # Remove old swap file and set the name for the new swap file
        self.__remove()
        self.__update_filename()

    def __remove(self):
        """Remove swap file"""

        if self.__swap_file.fileName() and self.__swap_file.exists():
            self.__stream.setDevice(None)
            self.__swap_file.close()
            self.__swap_file.remove()

    def _file_loaded(self):
        """This slot is executed when a file is loaded on the editor and
        look for swap file, if exists then can be recover"""

        self.__update_filename()
        if self.__swap_file.exists():
            # In recovery process can't edit
            self._neditable.editor.setReadOnly(True)
            # Ok, can be recover
            self.canBeRecovered.emit()

    def __update_filename(self):
        # First clear filename
        self.__swap_file.setFileName("")
        # Get new path
        filename = self.filename()
        self.__swap_file.setFileName(filename)

    def _start_typing(self):
        # Skip if editor is not modified
        if not self._neditable.editor.is_modified:
            return
        # No swap file, no work
        if not self.__swap_file.fileName():
            return
        # Create the file
        if not self.__swap_file.exists():
            self.__swap_file.open(QIODevice.WriteOnly)
            permissions = QFileDevice.ReadOwner | QFileDevice.WriteOwner
            self.__swap_file.setPermissions(permissions)
            self.__stream.setDevice(self.__swap_file)

        if self.__timer.isActive():
            self.__timer.stop()
        # Write swap file to the disk every 10 seconds by default
        self.__timer.start(settings.SWAP_FILE_INTERVAL * 1000)

    def _finish_typing(self):
        if not self.__swap_file.isOpen():
            return
        logger.debug("Now write the swap file...")
        text = self._neditable.editor.text
        self.__swap_file.write(text.encode())
        self.__swap_file.flush()

    def filename(self):
        """Returns the filename for swap file"""

        path, name = os.path.split(
            os.path.join(SWAP_PATH, self._neditable.nfile.file_name))
        filename = os.path.join(path, "%s.ninja-swap" % name)
        return filename

    def recover(self):
        self._neditable.editor.setReadOnly(False)
        # Disconnect signals
        self.init(tracking=False)

        self.__stream.setDevice(self.__swap_file)
        if not self.__swap_file.open(QIODevice.ReadOnly):
            logger.warning("Can't open swap file")
            return
        # Ok
        data = []
        append = data.append
        while not self.__stream.atEnd():
            line = self.__stream.readLine()
            append(line)

        # Set data in the editor
        self._neditable.editor.text = "\n".join(data)
        self._neditable.document.setModified(True)

        # Close swap file
        self.__stream.setDevice(None)
        self.__swap_file.close()
        # Reconnect signals
        self.init(tracking=True)

    def discard(self):
        self._neditable.editor.setReadOnly(False)
        # Remove swap file
        self.__remove()