예제 #1
0
파일: iogroup.py 프로젝트: bsberry/stlib
    def __init__(self, parent=None, in_designer=False):
        QWidget.__init__(self, parent=parent)

        self.in_designer = in_designer

        ui = os.path.join(QFileInfo.absolutePath(QFileInfo(__file__)),
                          'iogroup.ui')

        # TODO: CAMPid 9549757292917394095482739548437597676742
        if not QFileInfo(ui).isAbsolute():
            ui_file = os.path.join(QFileInfo.absolutePath(QFileInfo(__file__)),
                                   ui)
        else:
            ui_file = ui
        ui_file = QFile(ui_file)
        ui_file.open(QFile.ReadOnly | QFile.Text)
        ts = QTextStream(ui_file)
        sio = io.StringIO(ts.readAll())
        self.ui = uic.loadUi(sio, self)

        self._status_frame = ''
        self._status_signal_format = ''
        self._set_frame = ''
        self._set_signal_format = ''
        self._override_frame = ''
        self._override_signal_format = ''

        self._quantity = 0
        self._tx = True

        self.points = []
예제 #2
0
    def __init__(self, parent=None, in_designer=False):
        QWidget.__init__(self, parent=parent)

        self.in_designer = in_designer

        ui = os.path.join(QFileInfo.absolutePath(QFileInfo(__file__)),
                          'compoundtoggle.ui')

        # TODO: CAMPid 9549757292917394095482739548437597676742
        if not QFileInfo(ui).isAbsolute():
            ui_file = os.path.join(QFileInfo.absolutePath(QFileInfo(__file__)),
                                   ui)
        else:
            ui_file = ui
        ui_file = QFile(ui_file)
        ui_file.open(QFile.ReadOnly | QFile.Text)
        ts = QTextStream(ui_file)
        sio = io.StringIO(ts.readAll())
        self.ui = uic.loadUi(sio, self)

        self.ui.command.in_designer = self.in_designer
        self.ui.status_on.in_designer = self.in_designer
        self.ui.status_off.in_designer = self.in_designer

        if self.in_designer:
            self.ui.status_off.set_value(self.ui.status_off.on_value)
            self.ui.status_on.set_value(self.ui.status_off.on_value)
예제 #3
0
파일: iopoint.py 프로젝트: bsberry/stlib
    def __init__(self, parent=None, in_designer=False):
        QWidget.__init__(self, parent=parent)

        self.in_designer = in_designer

        ui = os.path.join(QFileInfo.absolutePath(QFileInfo(__file__)),
                          'iopoint.ui')

        # TODO: CAMPid 9549757292917394095482739548437597676742
        if not QFileInfo(ui).isAbsolute():
            ui_file = os.path.join(QFileInfo.absolutePath(QFileInfo(__file__)),
                                   ui)
        else:
            ui_file = ui
        ui_file = QFile(ui_file)
        ui_file.open(QFile.ReadOnly | QFile.Text)
        ts = QTextStream(ui_file)
        sio = io.StringIO(ts.readAll())
        self.ui = uic.loadUi(sio, self)

        self.ui.status.in_designer = self.in_designer
        self.ui.set.in_designer = self.in_designer
        self.ui.override.in_designer = self.in_designer

        self.update_configuration()
예제 #4
0
파일: __main__.py 프로젝트: altendky/st
    def __init__(self, ui_file, bus, devices=[], parent=None):
        QtWidgets.QMainWindow.__init__(self, parent=parent)

        self.bus = bus

        # TODO: CAMPid 980567566238416124867857834291346779
        ico_file = os.path.join(QFileInfo.absolutePath(QFileInfo(__file__)), "icon.ico")
        ico = QtGui.QIcon(ico_file)
        self.setWindowIcon(ico)

        ui = ui_file
        # TODO: CAMPid 9549757292917394095482739548437597676742
        if not QFileInfo(ui).isAbsolute():
            ui_file = os.path.join(QFileInfo.absolutePath(QFileInfo(__file__)), ui)
        else:
            ui_file = ui
        ui_file = QFile(ui_file)
        ui_file.open(QFile.ReadOnly | QFile.Text)
        ts = QTextStream(ui_file)
        sio = io.StringIO(ts.readAll())
        self.ui = uic.loadUi(sio, self)

        self.ui.action_About.triggered.connect(self.about)

        device_tree = epyqlib.devicetree.Tree()
        device_tree_model = epyqlib.devicetree.Model(root=device_tree)
        device_tree_model.device_removed.connect(self._remove_device)
        self.ui.device_tree.setModel(device_tree_model)

        self.ui.device_tree.device_selected.connect(self.set_current_device)
예제 #5
0
    def __init__(self, parent=None, in_designer=False):
        QWidget.__init__(self, parent=parent)

        self.in_designer = in_designer

        ui = os.path.join(QFileInfo.absolutePath(QFileInfo(__file__)),
                          'hmidialog.ui')

        # TODO: CAMPid 9549757292917394095482739548437597676742
        if not QFileInfo(ui).isAbsolute():
            ui_file = os.path.join(QFileInfo.absolutePath(QFileInfo(__file__)),
                                   ui)
        else:
            ui_file = ui
        ui_file = QFile(ui_file)
        ui_file.open(QFile.ReadOnly | QFile.Text)
        ts = QTextStream(ui_file)
        sio = io.StringIO(ts.readAll())
        self.ui = uic.loadUi(sio, self)

        self.ok_action = None
        self.cancel_action = None
        self.ui.ok_button.clicked.connect(self.ok)
        self.ui.cancel_button.clicked.connect(self.cancel)

        self.label.setWordWrap(True)
예제 #6
0
    def __setFileName(self, fileName):
        """
        Private method to set the file name to save the download into.
        
        @param fileName name of the file to save into
        @type str
        """
        fileInfo = QFileInfo(fileName)
        WebBrowserWindow.downloadManager().setDownloadDirectory(
            fileInfo.absoluteDir().absolutePath())
        self.filenameLabel.setText(fileInfo.fileName())

        self.__fileName = fileName

        # check file path for saving
        saveDirPath = QFileInfo(self.__fileName).dir()
        if not saveDirPath.exists():
            if not saveDirPath.mkpath(saveDirPath.absolutePath()):
                self.progressBar.setVisible(False)
                self.on_stopButton_clicked()
                self.infoLabel.setText(
                    self.tr("Download directory ({0}) couldn't be created.").
                    format(saveDirPath.absolutePath()))
                self.__setDateTime()
                return

        self.filenameLabel.setText(QFileInfo(self.__fileName).fileName())
예제 #7
0
파일: listselect.py 프로젝트: bsberry/stlib
    def __init__(self, parent=None, in_designer=False, action=None):
        QWidget.__init__(self, parent=parent)

        self.in_designer = in_designer

        ui = os.path.join(QFileInfo.absolutePath(QFileInfo(__file__)),
                          'listselect.ui')

        # TODO: CAMPid 9549757292917394095482739548437597676742
        if not QFileInfo(ui).isAbsolute():
            ui_file = os.path.join(
                QFileInfo.absolutePath(QFileInfo(__file__)), ui)
        else:
            ui_file = ui
        ui_file = QFile(ui_file)
        ui_file.open(QFile.ReadOnly | QFile.Text)
        ts = QTextStream(ui_file)
        sio = io.StringIO(ts.readAll())
        self.ui = uic.loadUi(sio, self)

        self.action = action
        self.items = {}
        self.ui.accept_button.clicked.connect(self.accept)
        self.ui.cancel_button.clicked.connect(
            functools.partial(self.exit, value=None))
예제 #8
0
    def addImages(self):
        imageFileNames = QFileDialog.getOpenFileNames(
            caption="Select image files to label")

        if not imageFileNames[0] or len(imageFileNames[0]) == 0:
            return

        imageFileNames = imageFileNames[0]
        labelsDir = QFileInfo(self.labelsFileName).absoluteDir()
        originDir = QFileInfo(imageFileNames[0]).absoluteDir()

        #Copy image files to the labels folder
        if originDir.absolutePath() != labelsDir.absolutePath():
            progDialog = QProgressDialog(
                "Copying image files to the labels folder", "Cancel", 0,
                len(imageFileNames), self)

        i = 0
        for imageFileName in imageFileNames:
            progDialog.setValue(i)

            oldName = QFileInfo(imageFileName).fileName()
            newPath = labelsDir.absoluteFilePath(oldName)

            print("Copying {} to {}".format(imageFileName, newPath))

            ok = QFile.copy(imageFileName, newPath)

            QApplication.processEvents()

            if not ok:
                print("Error copying {} to {}".format(imageFileName, newPath))

            i += 1

        progDialog.setValue(len(imageFileNames))
        progDialog.close()

        currentImageFileNames = [s.fileName for s in self.labeledImages]

        newImgIdx = len(self.labeledImages)

        for imageFileName in imageFileNames:
            normalizedFileName = QFileInfo(imageFileName).fileName()

            if normalizedFileName in currentImageFileNames:
                print("File {} already in dataset, skipping".format(
                    normalizedFileName))
                continue

            self.labeledImages.append(LabeledImage(normalizedFileName, []))

        self.fileListModel.setStringList(
            [s.fileName for s in self.labeledImages])
        self.loadImageAtIndex(newImgIdx)

        print("Added {} images to dataset".format(len(imageFileNames)))
        print("New length of labeledImages array {}".format(
            len(self.labeledImages)))
예제 #9
0
    def unzipdownloadFile(self, downladFile, latestVersion):
        import zipfile
        fileInfo = None
        self.newV2rayPath = None
        if QFile.exists(downladFile):
            fileInfo = QFileInfo(QFile(downladFile))
        else:
            return False

        def checkFilesize(file):
            v2rayFile = QFile(file.absoluteFilePath())
            # check file size need open the file
            v2rayFile.open(QIODevice.ReadOnly | QIODevice.Text)
            if v2rayFile.error() == v2rayFile.NoError:
                if v2rayFile.size() > 600000:
                    v2rayFile.close()
                    return True
            else:
                v2rayFile.close()
                return False

        if (fileInfo):
            with zipfile.ZipFile(fileInfo.absoluteFilePath(), "r") as zip_ref:
                for i in zip_ref.namelist():
                    absoluteFilePath = fileInfo.absolutePath(
                    ) + QDir.separator() + i
                    if re.search("/v2ray.exe$",
                                 absoluteFilePath):  # ## windows
                        self.newV2rayPath = None
                        self.newV2rayPath = QFileInfo(QFile(absoluteFilePath))
                        if self.newV2rayPath and checkFilesize(
                                self.newV2rayPath):
                            break
                    if re.search("/v2ray$", absoluteFilePath):  # ## other
                        self.newV2rayPath = None
                        self.newV2rayPath = QFileInfo(QFile(absoluteFilePath))
                        if self.newV2rayPath and checkFilesize(
                                self.newV2rayPath):
                            break
                try:
                    zip_ref.extractall(fileInfo.absolutePath())
                except PermissionError:
                    return
                if sys.platform.startswith('win'): pass
                else:
                    os.chmod(self.newV2rayPath.absoluteFilePath(), 0o755)
                    os.chmod(
                        self.newV2rayPath.absoluteFilePath()[:-5] + "v2ctl",
                        0o755)
            if self.newV2rayPath:
                if (self.stopV2ray): self.stopV2ray.emit()
                self.bridgetreasureChest.setV2raycoreFilePath(
                    self.newV2rayPath.absoluteFilePath())
                self.bridgetreasureChest.setV2raycoreVersion(latestVersion)
                self.bridgetreasureChest.save.emit()
                if (self.startV2ray): self.startV2ray.emit()
                return True
            else:
                return False
예제 #10
0
    def loadImages(self, fileNames):
        for fileName in fileNames:
            row = self.imagesTable.rowCount()
            self.imagesTable.setRowCount(row + 1)
            fileInfo = QFileInfo(fileName)
            imageName = fileInfo.baseName()
            fileImage2x = fileInfo.absolutePath(
            ) + '/' + imageName + "@2x." + fileInfo.suffix()
            fileInfo2x = QFileInfo(fileImage2x)
            image = QImage(fileName)
            toolTip = "Directory: {}\nFile: {}\nFile@2x: {}\nSize: {}x{}".format(
                QDir.toNativeSeparators(fileInfo.absolutePath()),
                fileInfo.fileName(),
                fileInfo2x.fileName() if fileInfo2x.exists else "<None>",
                image.width(), image.height())
            fileItem = QTableWidgetItem(imageName)
            fileItem.setData(Qt.UserRole, fileName)
            fileItem.setIcon(QIcon(QPixmap.fromImage(image)))
            fileItem.setFlags((fileItem.flags() | Qt.ItemIsUserCheckable)
                              & ~Qt.ItemIsEditable)
            fileItem.setToolTip(toolTip)
            self.imagesTable.setItem(row, 0, fileItem)

            mode = QIcon.Normal
            state = QIcon.Off

            if self.guessModeStateAct.isChecked():
                if "_act" in imageName:
                    mode = QIcon.Active
                elif "_dis" in imageName:
                    mode = QIcon.Disabled
                elif "_sel" in imageName:
                    mode = QIcon.Selected

                if "_on" in imageName:
                    mode = QIcon.On

            modeItem = QTableWidgetItem(IconPreviewArea.iconModeNames()[
                IconPreviewArea.iconModes().index(mode)])
            modeItem.setToolTip(toolTip)
            self.imagesTable.setItem(row, 1, modeItem)
            stateItem = QTableWidgetItem(IconPreviewArea.iconStateNames()[
                IconPreviewArea.iconStates().index(state)])
            stateItem.setToolTip(toolTip)
            self.imagesTable.setItem(row, 2, stateItem)
            self.imagesTable.openPersistentEditor(modeItem)
            self.imagesTable.openPersistentEditor(stateItem)
            fileItem.setCheckState(Qt.Checked)
예제 #11
0
    def onLoadClicked(self, fileType):
        mySettings = QSettings()
        fileDir = mySettings.value(self.DEFAULT_DIR_KEY)
        if fileDir is None:
            fileDir = os.path.dirname(__file__)
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        fileDialog = QFileDialog()
        fileDialog.setDirectory(fileDir)

        defaultFile = os.path.join(fileDir, defaultFiles[fileType])

        fileName, _ = \
          fileDialog.getOpenFileName(self,
                                     "QFileDialog.getOpenFileName()",
                                     defaultFile, "All Files (*);"
                                     "MHD Files (*.mhd);"
                                     "VTP Files (*.vtp)",
                                     options=options)
        if fileName:
            # Update default dir
            currentDir = QFileInfo(fileName).absoluteDir()
            mySettings.setValue(self.DEFAULT_DIR_KEY,
                                currentDir.absolutePath())
            info = QFileInfo(fileName)
            if (info.completeSuffix() == "mhd") and fileType == 0:
                # Load data
                self.loadFile(fileName)
            elif (info.completeSuffix() == "vtp") and fileType == 1:
                self.loadSurface(fileName, index=0)
            elif (info.completeSuffix() == "vtp") and fileType == 2:
                self.loadSurface(fileName, index=1)
            elif (info.completeSuffix() == "mhd") and fileType == 3:
                self.loadUSFile(fileName)
예제 #12
0
 def on_pbOpenFile_clicked(self):
     if self.pbOpenFile.text() == "exit":
         print("\nKill dumpcap and tshark")
         p1 = subprocess.Popen(shlex.split("taskkill /f /im dumpcap.exe"))
         p1.wait()
         p1.terminate()
         p1.kill()
         ##########
         p2 = subprocess.Popen(shlex.split("taskkill /f /im tshark.exe"))
         p2.wait()
         p2.terminate()
         p2.kill()
         ##########
         self.createReportFile()
         print("Bye!")
         self.close()
     else:
         self.pushButton.setEnabled(False)
         self.pbOpenFile.setEnabled(False)
         self.comboBoxInterface.setEnabled(False)
         self.pbOpenFile.setText("processing..")
         fname = QFileDialog.getOpenFileName(
             self, 'Open file', self.fpath,
             "Packet capture file (*.pcapng *.pcap *.cap)")
         if len(fname) != 0:
             fname = fname[0]
             fileNameInfo = QFileInfo(fname)
             self.fpath = fileNameInfo.absolutePath(
             )  # use same dir in next call
             self.sniffer.sniff(0, fname)
         self.pbOpenFile.setEnabled(True)
         self.pbOpenFile.setText("open file")
예제 #13
0
    def __init__(self, parent=None, in_designer=False):

        QWidget.__init__(self, parent=parent)

        self.in_designer = in_designer

        # If true, flips the compound scale on y axis if vertically oriented.
        self.cs_vertically_flipped = False

        ui = self.getPath()

        # TODO: CAMPid 9549757292917394095482739548437597676742
        if not QFileInfo(ui).isAbsolute():
            ui_file = os.path.join(QFileInfo.absolutePath(QFileInfo(__file__)),
                                   ui)
        else:
            ui_file = ui
        ui_file = QFile(ui_file)
        ui_file.open(QFile.ReadOnly | QFile.Text)
        ts = QTextStream(ui_file)
        sio = io.StringIO(ts.readAll())
        self.ui = uic.loadUi(sio, self)

        self.ui.command.in_designer = in_designer
        self.ui.echo.in_designer = in_designer
        self.ui.status.in_designer = in_designer
        self.ui.numeric_status.in_designer = in_designer

        self.update_echo_visibility()
예제 #14
0
 def pdf_ext(self):
     fileName, filetype = QFileDialog.getOpenFileName(self)
     fileinfo = QFileInfo(fileName)
     file_path = fileinfo.absolutePath()
     # print(file_path)  # 打印文件绝对路径(不包括文件名和后缀名)
     print(fileName)
     ext_pdf(file_path, fileName)
예제 #15
0
    def msg(self):

        directory1 = QFileDialog.getExistingDirectory(self, "选择文件夹", "/")
        print(directory1)  # 打印文件夹路径

        fileName, filetype = QFileDialog.getOpenFileName(
            self, "选择文件", "/", "All Files (*);;Text Files (*.txt)")
        print(fileName, filetype)  # 打印文件全部路径(包括文件名和后缀名)和文件类型
        print(fileName)  # 打印文件全部路径(包括文件名和后缀名)
        fileinfo = QFileInfo(fileName)
        print(fileinfo)  # 打印与系统相关的文件信息,包括文件的名字和在文件系统中位置,文件的访问权限,是否是目录或符合链接,等等。
        file_name = fileinfo.fileName()
        print(file_name)  # 打印文件名和后缀名
        file_suffix = fileinfo.suffix()
        print(file_suffix)  # 打印文件后缀名
        file_path = fileinfo.absolutePath()
        print(file_path)  # 打印文件绝对路径(不包括文件名和后缀名)

        files, ok1 = QFileDialog.getOpenFileNames(self, "多文件选择", "/",
                                                  "所有文件 (*);;文本文件 (*.txt)")
        print(files, ok1)  # 打印所选文件全部路径(包括文件名和后缀名)和文件类型

        fileName2, ok2 = QFileDialog.getSaveFileName(self, "文件保存", "/",
                                                     "图片文件 (*.png);;(*.jpeg)")
        print(fileName2)  # 打印保存文件的全部路径(包括文件名和后缀名)
예제 #16
0
 def getfile(self):
     self.fileName, self.filetype = QFileDialog.getOpenFileName(
         self, "选择文件", "/", "PDF Files (*.pdf)")
     fileinfo = QFileInfo(self.fileName)
     self.file_path = fileinfo.absolutePath()
     if self.file_path != '':
         self.getNumPages()
예제 #17
0
    def __init__(self, parent=None, in_designer=False):
        QtWidgets.QWidget.__init__(self, parent=parent)

        self.in_designer = in_designer

        ui = 'variableselection.ui'
        self.file_name = ui
        # TODO: CAMPid 9549757292917394095482739548437597676742
        if not QFileInfo(ui).isAbsolute():
            ui_file = os.path.join(QFileInfo.absolutePath(QFileInfo(__file__)),
                                   ui)
        else:
            ui_file = ui
        ui_file = QFile(ui_file)
        ui_file.open(QFile.ReadOnly | QFile.Text)
        ts = QTextStream(ui_file)
        sio = io.StringIO(ts.readAll())
        self.ui = uic.loadUi(sio, self)

        self.ui.load_binary_button.clicked.connect(self.load_binary)
        self.ui.save_selection_button.clicked.connect(self.save_selection)
        self.ui.load_selection_button.clicked.connect(self.load_selection)
        self.ui.update_parameters_button.clicked.connect(
            self.update_parameters)
        self.ui.process_raw_log_button.clicked.connect(self.process_raw_log)
        self.ui.process_raw_log_button.setEnabled(False)

        self.ui.view.tree_view.setContextMenuPolicy(Qt.CustomContextMenu)
        self.ui.view.tree_view.customContextMenuRequested.connect(
            self.context_menu)

        self.progress = None
예제 #18
0
    def __init__(self, parent=None, in_designer=False):

        self.s_vertically_flipped = False

        ui_file = os.path.join(QFileInfo.absolutePath(QFileInfo(__file__)),
                               'scale.ui')

        epyqlib.widgets.abstractwidget.AbstractWidget.__init__(
            self, ui=ui_file, parent=parent, in_designer=in_designer)

        epyqlib.mixins.OverrideRange.__init__(self)

        self._breakpoints = [
            self._min + (self._max - self._min) * n
            for n in [0.10, 0.25, 0.75, 0.90]
        ]

        dark_red_transparent = QColor(Qt.darkRed)
        dark_red_transparent.setAlpha(0)
        dark_yellow_transparent = QColor(Qt.darkYellow)
        dark_yellow_transparent.setAlpha(0)
        dark_green_transparent = QColor(Qt.darkGreen)
        dark_green_transparent.setAlpha(0)

        self._colors = [
            dark_red_transparent, dark_yellow_transparent,
            dark_green_transparent, dark_yellow_transparent,
            dark_red_transparent
        ]

        self._frame = None
        self._signal = None

        self.update_configuration()
예제 #19
0
    def generate_pj_info(self):
        """
        triggered by button add
        1. create new project info dict every time
        2. extract project name and address from LineEdit; check if exist and if it is cas and msh file
        3. when second step done, get journal path from get_journal function
        :return: signal_add_pj(dict)
        """
        self.pj_dict = {
            "project_name": '',
            "project_address": '',
            "journal": ''
        }
        if self.checkbox_journal.isChecked():
            case_path = QFileInfo(self.edit_journal_address.text())
        else:
            case_path = QFileInfo(self.edit_project_address.text()
                                  )  # QFileInfo can deeply analyze path info
        accepted_file_type = ['cas', 'msh', 'h5', 'jou']

        if (case_path.exists()) and (case_path.suffix() in accepted_file_type):
            self.pj_dict["project_name"] = case_path.baseName()
            self.pj_dict["project_address"] = case_path.absolutePath()
            self.pj_dict['journal'] = self.get_journal(case_path,
                                                       case_path.fileName())
            self.signal_add_pj.emit(self.pj_dict)
            self.close()
            print('generate new project:', self.pj_dict)
        else:
            QMessageBox.warning(self, self.make_trans('warning'),
                                self.make_trans('no_case_mesh'),
                                QMessageBox.Yes, QMessageBox.Yes)
            print('file not exists')
예제 #20
0
 def openFolder(self):
     """
     Public slot to open the folder containing the downloaded file.
     """
     info = QFileInfo(self.__fileName)
     url = QUrl.fromLocalFile(info.absolutePath())
     QDesktopServices.openUrl(url)
예제 #21
0
	def openNet(self):
		filename, filter = QFileDialog.getOpenFileName(self, "Abrir arquivo...", self._lastPath, "XML files (*.xml *.pnml)")
		if filename is None or filename == "":
			return
		if not (filename.endswith(".xml") or filename.endswith(".pnml")):
			filename = filename + ".xml"
		file = QFile(filename)
		if not file.open(QIODevice.ReadOnly):
			return
		doc = QDomDocument("PetriNetDoc")
		ans, errMsg, errLine, errColl = doc.setContent(file)
		if not ans:
			return
		nets = PFSNet.createFromXml(doc, self)
		if len(nets) == 0:
			return
		self.nonempty.emit()
		for net in nets:
			f = QFileInfo(filename)
			net._filename = f.fileName()
			net._filepath = f.absolutePath()
			file.close()
			self._lastPath = net._filepath
			net.undoStack.cleanChanged.connect(self.changeCurrentTabName)
			self._idNet = self._idNet + 1
			i = self._tab.addTab(net, net.getTabName())
			self._tab.setCurrentIndex(i)
			if self._tab.count() == 1:
				self.updateUndoRedoAction()
			self._sm.fixTransitions(net._pages[0]._scene)
			self.nonempty.emit()
			if self._tab.count() == 1:
				self.updateUndoRedoAction()
예제 #22
0
 def onLoadClicked(self, fileType):
     mySettings = QSettings()
     fileDir = mySettings.value(self.DEFAULT_DIR_KEY)
     options = QFileDialog.Options()
     options |= QFileDialog.DontUseNativeDialog
     fileDialog = QFileDialog()
     fileDialog.setDirectory(fileDir)
     fileName, _ = \
       fileDialog.getOpenFileName(self,
                                  "QFileDialog.getOpenFileName()",
                                  "", "All Files (*);"
                                  ";MHD Files (*.mhd);"
                                  ";VTP Files (*.vtp)",
                                  options=options)
     if fileName:
         # Update default dir
         currentDir = QFileInfo(fileName).absoluteDir()
         mySettings.setValue(self.DEFAULT_DIR_KEY,
                             currentDir.absolutePath())
         info = QFileInfo(fileName)
         if (info.completeSuffix() == "vtp") and fileType == 1:
             self.loadSurface(fileName)
         elif (info.completeSuffix() == "mhd") and fileType == 0:
             # Load data
             self.loadFile(fileName)
예제 #23
0
    def __init__(self, parent=None, in_designer=False):
        QtWidgets.QWidget.__init__(self, parent=parent)

        self.in_designer = in_designer

        ui = 'devicetreeview.ui'
        # TODO: CAMPid 9549757292917394095482739548437597676742
        if not QFileInfo(ui).isAbsolute():
            ui_file = os.path.join(QFileInfo.absolutePath(QFileInfo(__file__)),
                                   ui)
        else:
            ui_file = ui
        ui_file = QFile(ui_file)
        ui_file.open(QFile.ReadOnly | QFile.Text)
        ts = QTextStream(ui_file)
        sio = io.StringIO(ts.readAll())
        self.ui = uic.loadUi(sio, self)

        self.resize_columns = epyqlib.devicetree.Columns(
            name=True,
            nickname=True,
            bitrate=True,
            transmit=True,
        )

        self.ui.tree_view.setContextMenuPolicy(Qt.CustomContextMenu)
        self.ui.tree_view.customContextMenuRequested.connect(self.context_menu)

        self.model = None
예제 #24
0
    def __init__(self, parent=None, in_designer=False):
        QtWidgets.QWidget.__init__(self, parent=parent)

        self.in_designer = in_designer

        ui = 'listmenuview.ui'
        # TODO: CAMPid 9549757292917394095482739548437597676742
        if not QFileInfo(ui).isAbsolute():
            ui_file = os.path.join(QFileInfo.absolutePath(QFileInfo(__file__)),
                                   ui)
        else:
            ui_file = ui
        ui_file = QFile(ui_file)
        ui_file.open(QFile.ReadOnly | QFile.Text)
        ts = QTextStream(ui_file)
        sio = io.StringIO(ts.readAll())
        self.ui = uic.loadUi(sio, self)

        scroll_bar = self.ui.list_view.verticalScrollBar()
        up = functools.partial(scroll_bar.triggerAction,
                               QAbstractSlider.SliderPageStepSub)
        self.ui.up_button.clicked.connect(up)
        down = functools.partial(scroll_bar.triggerAction,
                                 QAbstractSlider.SliderPageStepAdd)
        self.ui.down_button.clicked.connect(down)

        self.ui.list_view.viewport().setAutoFillBackground(False)

        self.ui.list_view.clicked.connect(self.clicked)
예제 #25
0
   def on_actOpen_triggered(self):
      curPath=QDir.currentPath()    #获取当前路径
      filename,flt=QFileDialog.getOpenFileName(self,"打开一个文件",curPath,
                  "地震数据文件(*.txt);;所有文件(*.*)")
      if (filename==""):
         return

      aFile=open(filename,'r')
      allLines=aFile.readlines()  #读取所有行,list类型,每行末尾带有 \n
      aFile.close()
      fileInfo=QFileInfo(filename)
      QDir.setCurrent(fileInfo.absolutePath())
      self.__labFileName.setText("数据文件:"+fileInfo.fileName())
      
      rowCnt=len(allLines)    #行数,即数据点数
      self.__vectData=[0]*rowCnt   #列表
      for i in range(rowCnt):      
         lineText=allLines[i].strip()  #字符串表示的数字
         self.__vectData[i]=float(lineText)
      minV=min(self.__vectData)  #最小值
      self.ui.spinY_Min.setValue(minV)
      maxV=max(self.__vectData)  #最大值
      self.ui.spinY_Max.setValue(maxV)
      
      if self.ui.radioFill_None.isChecked():
         self.do_redrawWave()    #绘制波形曲线
      else:
         self.do_redrawFill()    #绘制有填充的波形
      self.ui.frameSetup.setEnabled(True)
예제 #26
0
 def openFolder(self):
     """
     Public slot to open the folder containing the downloaded file.
     """
     info = QFileInfo(self.__fileName)
     url = QUrl.fromLocalFile(info.absolutePath())
     QDesktopServices.openUrl(url)
예제 #27
0
파일: dualscale.py 프로젝트: bsberry/stlib
    def __init__(self, parent=None, in_designer=False):

        QWidget.__init__(self, parent=parent)

        self.in_designer = in_designer

        self.d_vertically_flipped = False

        ui = self.getPath()

        # TODO: CAMPid 9549757292917394095482739548437597676742
        if not QFileInfo(ui).isAbsolute():
            ui_file = os.path.join(QFileInfo.absolutePath(QFileInfo(__file__)),
                                   ui)
        else:
            ui_file = ui
        ui_file = QFile(ui_file)
        ui_file.open(QFile.ReadOnly | QFile.Text)
        ts = QTextStream(ui_file)
        sio = io.StringIO(ts.readAll())
        self.ui = uic.loadUi(sio, self)

        self.scale1 = epyqlib.widgets.scale.Scale(self, in_designer)
        self.scale2 = epyqlib.widgets.scale.Scale(self, in_designer)
        # color ranges, scale markers, labels, needle painted.
        self.scale1.scale.m_paintMode = 1
        # needle, cover painted.
        self.scale2.scale.m_paintMode = 3
        # scale2's needle is blue
        self.scale2.scale.isBlue = True
        self.stackedLayout = QStackedLayout()
        self.stackedLayout.addWidget(self.scale2)
        self.stackedLayout.addWidget(self.scale1)
        self.stackedLayout.setStackingMode(1)
        self.ui.glayout.addLayout(self.stackedLayout, 0, 0)
예제 #28
0
    def on_btnAdd_clicked(self):
        ##      curPath=os.getcwd()     #获取系统当前目录
        ##      curPath=QDir.homePath()
        curPath = QDir.currentPath()
        dlgTitle = "选择音频文件"
        filt = "音频文件(*.mp3 *.wav *.wma);;所有文件(*.*)"
        fileList, flt = QFileDialog.getOpenFileNames(self, dlgTitle, curPath,
                                                     filt)
        count = len(fileList)
        if count < 1:
            return

        filename = fileList[0]
        fileInfo = QFileInfo(filename)  #文件信息
        QDir.setCurrent(fileInfo.absolutePath())  #重设当前路径

        for i in range(count):
            filename = fileList[i]
            fileInfo.setFile(filename)
            song = QMediaContent(QUrl.fromLocalFile(filename))
            self.playlist.addMedia(song)  #添加播放媒体
            ##         basename=os.path.basename(filename)    #文件名和后缀
            basename = fileInfo.baseName()
            self.ui.listWidget.addItem(basename)  #添加到界面文件列表

        if (self.player.state() != QMediaPlayer.PlayingState):
            self.playlist.setCurrentIndex(0)
            self.player.play()
예제 #29
0
    def absolute_path(self, path=""):
        # TODO: CAMPid 9549757292917394095482739548437597676742
        if not QFileInfo(path).isAbsolute():
            path = os.path.join(
                QFileInfo.absolutePath(QFileInfo(self.config_path)), path)

        return path
예제 #30
0
    def _addIcon(self):
        filter_ = self.tr("Images (*.jpg *.jpeg *.bmp *.png *.tiff *.gif);;"
                          "All files (*.*)")
        fileName, _selectedFilter = QFileDialog.getOpenFileName(self,
                self.tr("Open File"), self.latestDir,
                filter_)
        if fileName:
            file_info = QFileInfo(fileName)
            self.latestDir = file_info.absolutePath()

            image = QImage()
            if image.load(fileName):
                maxWidth = 22
                maxHeight = 15
                if image.width() > maxWidth or image.height() > maxHeight:
                    scaledImage = image.scaled(maxWidth, maxHeight,
                            Qt.KeepAspectRatio, Qt.SmoothTransformation)
                else:
                    scaledImage = image

                ba = QByteArray()
                buffer = QBuffer(ba)
                buffer.open(QIODevice.WriteOnly)
                scaledImage.save(buffer, 'png')

                model = self.model()
                index = model.index(self.selectedIndex().row(), model.fieldIndex('icon'))
                model.setData(index, ba)
예제 #31
0
 def fopen(self, filename):
     fname = QFileInfo(filename)
     self.filePath = str(fname.absolutePath())
     fn = str(fname.baseName())
     main = NewEditorMainWindow(fn, self.filePath, self.library)
     self.library.mainWins.append(main)
     main.show()
예제 #32
0
    def __init__(self, parent=None, in_designer=False, action=None):
        QWidget.__init__(self, parent=parent)

        self.in_designer = in_designer

        ui = os.path.join(QFileInfo.absolutePath(QFileInfo(__file__)),
                          'numberpad.ui')

        # TODO: CAMPid 9549757292917394095482739548437597676742
        if not QFileInfo(ui).isAbsolute():
            ui_file = os.path.join(QFileInfo.absolutePath(QFileInfo(__file__)),
                                   ui)
        else:
            ui_file = ui
        ui_file = QFile(ui_file)
        ui_file.open(QFile.ReadOnly | QFile.Text)
        ts = QTextStream(ui_file)
        sio = io.StringIO(ts.readAll())
        self.ui = uic.loadUi(sio, self)

        self.action = action
        self.ui.accept_button.clicked.connect(self.accept)
        self.ui.cancel_button.clicked.connect(
            functools.partial(self.exit, value=None))
        self.ui.up_button.clicked.connect(self.ui.cancel_button.clicked)

        numeric_buttons = []

        for number in range(10):
            button = getattr(self.ui, 'button_{}'.format(number))
            button.clicked.connect(
                functools.partial(self.ui.edit.insert, str(number)))
            numeric_buttons.append(button)

        self.ui.button_decimal.clicked.connect(
            functools.partial(self.ui.edit.insert, '.'))
        numeric_buttons.append(self.ui.button_decimal)

        self.ui.button_backspace.clicked.connect(self.ui.edit.backspace)

        for button in numeric_buttons:
            button.setStyleSheet('''
                QPushButton {
                    border: 0px;
                }
            ''')
예제 #33
0
    def _addIcon(self):
        filter_ = self.tr("Images (*.jpg *.jpeg *.bmp *.png *.tiff *.gif *.ico);;"
                          "All files (*.*)")
        fileName, _selectedFilter = QFileDialog.getOpenFileName(self,
                self.tr("Open File"), self.latestDir,
                filter_)
        if fileName:
            file_info = QFileInfo(fileName)
            self.latestDir = file_info.absolutePath()

            self.loadFromFile(fileName)
예제 #34
0
    def destinationButtonClicked(self):
        destination = self.destination.text()
        if not destination and self.collection:
            destination = self.latestDir + '/' + self.collection.getCollectionName() + '_mobile.db'
        file, _selectedFilter = QFileDialog.getSaveFileName(
            self, self.tr("Select destination"), destination, "*.db")
        if file:
            file_info = QFileInfo(file)
            self.latestDir = file_info.absolutePath()

            self.destination.setText(file)
            self.acceptButton.setEnabled(True)
예제 #35
0
 def create_wallet(database):
     target_dir = QFileInfo(database).absoluteDir()
     if not target_dir.exists():
         QDir().mkdir(target_dir.absolutePath())
     db = sqlite3.connect(database)
     cursor = db.cursor()
     try:
         for cq in WalletDatabase.__WALLET_INIT_WALLET_QUERY:
             cursor.execute(cq)
     except sqlite3.Error as e:
         raise WalletDatabaseException(tr('WalletDatabase', 'Failed to create wallet: %s') % e)
     db.commit()
     db.close()
예제 #36
0
파일: __main__.py 프로젝트: altendky/st
def excepthook(excType, excValue, tracebackobj):
    """
    Global function to catch unhandled exceptions.

    @param excType exception type
    @param excValue exception value
    @param tracebackobj traceback object
    """
    separator = "-" * 70
    email = "*****@*****.**"

    try:
        hash = "Revision Hash: {}\n\n".format(epyq.revision.hash)
    except:
        hash = ""

    notice = (
        """An unhandled exception occurred. Please report the problem via email to:\n"""
        """\t\t{email}\n\n{hash}"""
        """A log has been written to "{log}".\n\nError information:\n""".format(email=email, hash=hash, log=log.name)
    )
    # TODO: add something for version
    versionInfo = ""
    timeString = time.strftime("%Y-%m-%d, %H:%M:%S")

    tbinfofile = io.StringIO()
    traceback.print_tb(tracebackobj, None, tbinfofile)
    tbinfofile.seek(0)
    tbinfo = tbinfofile.read()
    errmsg = "%s: \n%s" % (str(excType), str(excValue))
    sections = [separator, timeString, separator, errmsg, separator, tbinfo]
    msg = "\n".join(sections)

    errorbox = QMessageBox()
    errorbox.setWindowTitle("EPyQ")
    errorbox.setIcon(QMessageBox.Critical)

    # TODO: CAMPid 980567566238416124867857834291346779
    ico_file = os.path.join(QFileInfo.absolutePath(QFileInfo(__file__)), "icon.ico")
    ico = QtGui.QIcon(ico_file)
    errorbox.setWindowIcon(ico)

    complete = str(notice) + str(msg) + str(versionInfo)

    sys.stderr.write(complete)
    errorbox.setText(complete)
    errorbox.exec_()
예제 #37
0
파일: __main__.py 프로젝트: altendky/st
    def about(self):
        box = QMessageBox()
        box.setWindowTitle("About EPyQ")

        # TODO: CAMPid 980567566238416124867857834291346779
        ico_file = os.path.join(QFileInfo.absolutePath(QFileInfo(__file__)), "icon.ico")
        ico = QtGui.QIcon(ico_file)
        box.setWindowIcon(ico)

        message = [__copyright__, __license__]

        try:
            import epyq.revision
        except ImportError:
            pass
        else:
            message.append(epyq.revision.hash)

        box.setText("\n".join(message))
        box.exec_()
예제 #38
0
    def addFilesClicked(self):
        newFiles = QFileDialog.getOpenFileNames(self, "Please select the files to add to stack", "",
                                                "Images (*.png *.jpg *.bmp)")
        for file in newFiles[0]:
            entries = self.fileTreeWidget.findItems(file, Qt.MatchCaseSensitive)
            for entry in entries:
                self.fileTreeWidget.takeItem(self.fileTreeWidget.row(entry))
            item = QTreeWidgetItem()

            fileInfo = QFileInfo(file)
            fileInfo.fileName()

            exif = getExifInfo(file)

            item.setText(0, fileInfo.fileName())
            item.setText(1, exif.exposureTime)
            item.setText(2, exif.aperture)
            item.setText(3, exif.ISO)
            item.setText(4, fileInfo.absolutePath())
            self.fileTreeWidget.insertTopLevelItem(self.fileTreeWidget.topLevelItemCount(), item)
예제 #39
0
파일: builder.py 프로젝트: doudz/pyqtdeploy
    def _write_qmake(self, build_dir, required_ext, required_libraries, job_writer, opt, resource_names):
        """ Create the .pro file for qmake. """

        project = self._project

        f = self._create_file(build_dir + '/' +
                project.get_executable_basename() + '.pro')

        f.write('TEMPLATE = app\n')

        # Configure the CONFIG and QT values that are project dependent.
        needs_cpp11 = False
        needs_gui = False
        qmake_qt4 = set()
        qmake_config4 = set()
        qmake_qt5 = set()
        qmake_config5 = set()

        for pyqt_m in project.pyqt_modules:
            metadata = self._get_pyqt_module_metadata(pyqt_m)

            if metadata.cpp11:
                needs_cpp11 = True

            if metadata.gui:
                needs_gui = True

            qmake_qt4.update(metadata.qt4)
            qmake_config4.update(metadata.config4)
            qmake_qt5.update(metadata.qt5)
            qmake_config5.update(metadata.config5)

        both_qt = qmake_qt4 & qmake_qt5
        qmake_qt4 -= both_qt
        qmake_qt5 -= both_qt

        both_config = qmake_qt4 & qmake_qt5
        qmake_config4 -= both_config
        qmake_config5 -= both_config

        both_config.add('warn_off')

        if project.application_is_console or not needs_gui:
            both_config.add('console')

        if needs_cpp11:
            both_config.add('c++11')

        f.write('\n')
        f.write('CONFIG += {0}\n'.format(' '.join(both_config)))

        if not project.application_is_bundle:
            f.write('CONFIG -= app_bundle\n')

        if not needs_gui:
            f.write('QT -= gui\n')

        if both_qt:
            f.write('QT += {0}\n'.format(' '.join(both_qt)))

        if qmake_config4 or qmake_qt4:
            f.write('\n')
            f.write('lessThan(QT_MAJOR_VERSION, 5) {\n')

            if qmake_config4:
                f.write('    CONFIG += {0}\n'.format(' '.join(qmake_config4)))

            if qmake_qt4:
                f.write('    QT += {0}\n'.format(' '.join(qmake_qt4)))

            f.write('}\n')

        if qmake_config5 or qmake_qt5:
            f.write('\n')
            f.write('greaterThan(QT_MAJOR_VERSION, 4) {\n')

            if qmake_config5:
                f.write('    CONFIG += {0}\n'.format(' '.join(qmake_config5)))

            if qmake_qt5:
                f.write('    QT += {0}\n'.format(' '.join(qmake_qt5)))

            f.write('}\n')

        # Modules can share sources so we need to make sure we don't include
        # them more than once.  We might as well handle the other things in the
        # same way.
        used_sources = {}
        used_defines = {}
        used_includepath = {}
        used_libs = {}
        used_inittab = {}

        # Handle any static PyQt modules.
        if len(project.pyqt_modules) > 0:
            site_packages = project.path_from_user(
                    project.python_target_stdlib_dir) + '/site-packages'
            pyqt_version = 'PyQt5' if project.application_is_pyqt5 else 'PyQt4'

            l_libs = []
            for pyqt in self._get_all_pyqt_modules():
                # The sip module is always needed (implicitly or explicitly) if
                # we have got this far.  We handle it separately as it is in a
                # different directory.
                if pyqt == 'sip':
                    continue

                # The uic module is pure Python.
                if pyqt == 'uic':
                    continue

                self._add_value_for_scopes(used_inittab,
                        pyqt_version + '.' + pyqt)

                lib_name = pyqt
                if self._get_pyqt_module_metadata(pyqt).needs_suffix:
                    # Qt4's qmake thinks -lQtCore etc. always refer to the Qt
                    # libraries so PyQt4 creates static libraries with a
                    # suffix.
                    lib_name += '_s'

                l_libs.append('-l' + lib_name)

            # Add the LIBS value for any PyQt modules to the global scope.
            if len(l_libs) > 0:
                self._add_value_for_scopes(used_libs,
                        '-L{0}/{1} {2}'.format(site_packages, pyqt_version,
                                ' '.join(l_libs)))

            # Add the sip module.
            self._add_value_for_scopes(used_inittab, 'sip')
            self._add_value_for_scopes(used_libs,
                    '-L{0} -lsip'.format(site_packages))

        # Handle any other extension modules.
        for other_em in project.other_extension_modules:
            scoped_values = self._parse_scoped_values(other_em.libs, False)

            for scope, values in scoped_values.items():
                self._add_value_for_scopes(used_inittab, other_em.name,
                        [scope])
                self._add_value_set_for_scope(used_libs, values, scope)

        # Configure the target Python interpreter.
        if project.python_target_include_dir != '':
            self._add_value_for_scopes(used_includepath,
                    project.path_from_user(project.python_target_include_dir))

        if project.python_target_library != '':
            fi = QFileInfo(project.path_from_user(
                    project.python_target_library))

            lib_dir = fi.absolutePath()
            lib = fi.completeBaseName()

            # This is smart enough to translate the Python library as a UNIX .a
            # file to what Windows needs.
            if lib.startswith('lib'):
                lib = lib[3:]

            if '.' in lib:
                self._add_value_for_scopes(used_libs,
                        '-L{0} -l{1}'.format(lib_dir, lib.replace('.', '')),
                        ['win32'])
                self._add_value_for_scopes(used_libs,
                        '-L{0} -l{1}'.format(lib_dir, lib), ['!win32'])
            else:
                self._add_value_for_scopes(used_libs,
                        '-L{0} -l{1}'.format(lib_dir, lib))

        # Handle any standard library extension modules.
        if len(required_ext) != 0:
            source_dir = project.path_from_user(project.python_source_dir)
            source_scopes = set()

            for name, module in required_ext.items():
                # Get the list of all applicable scopes.
                module_scopes = self._stdlib_scopes(module.scope)

                if len(module_scopes) == 0:
                    # The module is specific to a platform for which we are
                    # using the python.org Python libraries so ignore it
                    # completely.
                    continue

                self._add_value_for_scopes(used_inittab, name, module_scopes)

                for source in module.source:
                    scopes, source = self._get_scope_and_value(source,
                            module_scopes)
                    source = self._python_source_file(source_dir, source)
                    self._add_value_for_scopes(used_sources, source, scopes)

                    source_scopes.update(scopes)

                if module.defines is not None:
                    for define in module.defines:
                        scopes, define = self._get_scope_and_value(define,
                                module_scopes)
                        self._add_value_for_scopes(used_defines, define,
                                scopes)

                if module.includepath is not None:
                    for includepath in module.includepath:
                        scopes, includepath = self._get_scope_and_value(
                                includepath, module_scopes)
                        includepath = self._python_source_file(source_dir,
                                includepath)
                        self._add_value_for_scopes(used_includepath,
                                includepath, scopes)

                if module.libs is not None:
                    for lib in module.libs:
                        scopes, lib = self._get_scope_and_value(lib,
                                module_scopes)
                        self._add_value_for_scopes(used_libs, lib, scopes)

            self._add_value_for_scopes(used_includepath,
                    source_dir + '/Modules', source_scopes)

            self._add_value_for_scopes(used_includepath, source_dir + '/PC',
                    ['win32'])

        # Handle any required external libraries.
        for required_lib in required_libraries:
            for xlib in project.external_libraries:
                if xlib.name == required_lib:
                    if xlib.defines != '':
                        self._add_parsed_scoped_values(used_defines,
                                xlib.defines, False)

                    if xlib.includepath != '':
                        self._add_parsed_scoped_values(used_includepath,
                                xlib.includepath, True)

                    if xlib.libs != '':
                        self._add_parsed_scoped_values(used_libs, xlib.libs,
                                False)

                    break
            else:
                for xlib in external_libraries_metadata:
                    if xlib.name == required_lib:
                        scopes = self._stdlib_scopes()

                        if len(scopes) != 0:
                            for lib in xlib.libs.split():
                                self._add_value_for_scopes(used_libs, lib,
                                        scopes)

                        break

        # Specify the resource files.
        f.write('\n')
        f.write('RESOURCES = \\\n')
        f.write(' \\\n'.join(['    resources/{0}'.format(n) for n in resource_names]))
        f.write('\n')

        # Specify the source and header files.
        f.write('\n')

        f.write('SOURCES = pyqtdeploy_main.cpp pyqtdeploy_start.cpp pdytools_module.cpp\n')
        self._write_main(build_dir, used_inittab)
        self._copy_lib_file('pyqtdeploy_start.cpp', build_dir)
        self._copy_lib_file('pdytools_module.cpp', build_dir)

        headers = 'HEADERS = pyqtdeploy_version.h frozen_bootstrap.h'
        if project.application_script != '':
            f.write('DEFINES += PYQTDEPLOY_FROZEN_MAIN\n')
            headers += ' frozen_main.h'

        if opt:
            f.write('DEFINES += PYQTDEPLOY_OPTIMIZED\n')

        f.write(headers)
        f.write('\n')

        # Get the set of all scopes used.
        used_scopes = set(used_sources.keys())
        used_scopes.update(used_defines.keys())
        used_scopes.update(used_includepath.keys())
        used_scopes.update(used_libs.keys())

        # Write out grouped by scope.
        for scope in used_scopes:
            f.write('\n')

            if scope == '':
                prefix = ''
                tail = None
            elif scope.startswith('win32_'):
                # We could avoid the hardcoded handling by reverting to
                # defining appropriate CONFIG values in a pre_configuration.pro
                # file.
                prefix = '        '
                f.write(
                        'win32 {\n    %scontains(QMAKE_TARGET.arch, x86_64) {\n' % ('!' if scope == 'win32_x86' else ''))
                tail = '    }\n}\n'
            else:
                prefix = '    '
                f.write('%s {\n' % scope)
                tail = '}\n'

            for defines in used_defines.get(scope, ()):
                f.write('{0}DEFINES += {1}\n'.format(prefix, defines))

            for includepath in used_includepath.get(scope, ()):
                f.write('{0}INCLUDEPATH += {1}\n'.format(prefix, includepath))

            for lib in used_libs.get(scope, ()):
                f.write('{0}LIBS += {1}\n'.format(prefix, lib))

            for source in used_sources.get(scope, ()):
                f.write('{0}SOURCES += {1}\n'.format(prefix, source))

            if tail is not None:
                f.write(tail)

        # Add the project independent post-configuration stuff.
        self._write_embedded_lib_file('post_configuration.pro', f)

        # Add any application specific stuff.
        qmake_configuration = project.qmake_configuration.strip()

        if qmake_configuration != '':
            f.write('\n' + qmake_configuration + '\n')

        # All done.
        f.close()
예제 #40
0
 def __getFileName(self):
     """
     Private method to get the file name to save to from the user.
     """
     if self.__gettingFileName:
         return
     
     import Helpviewer.HelpWindow
     downloadDirectory = Helpviewer.HelpWindow.HelpWindow\
         .downloadManager().downloadDirectory()
     
     if self.__fileName:
         fileName = self.__fileName
         originalFileName = self.__originalFileName
         self.__toDownload = True
         ask = False
     else:
         defaultFileName, originalFileName = \
             self.__saveFileName(downloadDirectory)
         fileName = defaultFileName
         self.__originalFileName = originalFileName
         ask = True
     self.__autoOpen = False
     if not self.__toDownload:
         from .DownloadAskActionDialog import DownloadAskActionDialog
         url = self.__reply.url()
         dlg = DownloadAskActionDialog(
             QFileInfo(originalFileName).fileName(),
             self.__reply.header(QNetworkRequest.ContentTypeHeader),
             "{0}://{1}".format(url.scheme(), url.authority()),
             self)
         if dlg.exec_() == QDialog.Rejected or dlg.getAction() == "cancel":
             self.progressBar.setVisible(False)
             self.__reply.close()
             self.on_stopButton_clicked()
             self.filenameLabel.setText(
                 self.tr("Download canceled: {0}").format(
                     QFileInfo(defaultFileName).fileName()))
             self.__canceledFileSelect = True
             return
         
         if dlg.getAction() == "scan":
             self.__mainWindow.requestVirusTotalScan(url)
             
             self.progressBar.setVisible(False)
             self.__reply.close()
             self.on_stopButton_clicked()
             self.filenameLabel.setText(
                 self.tr("VirusTotal scan scheduled: {0}").format(
                     QFileInfo(defaultFileName).fileName()))
             self.__canceledFileSelect = True
             return
         
         self.__autoOpen = dlg.getAction() == "open"
         if PYQT_VERSION_STR >= "5.0.0":
             from PyQt5.QtCore import QStandardPaths
             tempLocation = QStandardPaths.standardLocations(
                 QStandardPaths.TempLocation)[0]
         else:
             from PyQt5.QtGui import QDesktopServices
             tempLocation = QDesktopServices.storageLocation(
                 QDesktopServices.TempLocation)
         fileName = tempLocation + '/' + \
             QFileInfo(fileName).completeBaseName()
     
     if ask and not self.__autoOpen and self.__requestFilename:
         self.__gettingFileName = True
         fileName = E5FileDialog.getSaveFileName(
             None,
             self.tr("Save File"),
             defaultFileName,
             "")
         self.__gettingFileName = False
         if not fileName:
             self.progressBar.setVisible(False)
             self.__reply.close()
             self.on_stopButton_clicked()
             self.filenameLabel.setText(
                 self.tr("Download canceled: {0}")
                     .format(QFileInfo(defaultFileName).fileName()))
             self.__canceledFileSelect = True
             return
     
     fileInfo = QFileInfo(fileName)
     Helpviewer.HelpWindow.HelpWindow.downloadManager()\
         .setDownloadDirectory(fileInfo.absoluteDir().absolutePath())
     self.filenameLabel.setText(fileInfo.fileName())
     
     self.__output.setFileName(fileName + ".part")
     self.__fileName = fileName
     
     # check file path for saving
     saveDirPath = QFileInfo(self.__fileName).dir()
     if not saveDirPath.exists():
         if not saveDirPath.mkpath(saveDirPath.absolutePath()):
             self.progressBar.setVisible(False)
             self.on_stopButton_clicked()
             self.infoLabel.setText(self.tr(
                 "Download directory ({0}) couldn't be created.")
                 .format(saveDirPath.absolutePath()))
             return
     
     self.filenameLabel.setText(QFileInfo(self.__fileName).fileName())
     if self.__requestFilename:
         self.__readyRead()