Ejemplo n.º 1
0
 def fillGrid2(self,home):
       print (QDir.currentPath())
       self.fileSystemModel.setRootPath(QDir.currentPath())
       self.ui.treeView.setModel(self.fileSystemModel)
       self.ui.treeView.setRootIndex(self.fileSystemModel.index(QDir.currentPath()))
       self.ui.treeView.hideColumn(1)
       self.ui.treeView.hideColumn(2)
       self.ui.treeView.hideColumn(3)
Ejemplo n.º 2
0
    def changeResolution(self):
        fileName = QFileDialog.getOpenFileName(
            self,
            'Load .prn file',
            directory=self.settings.value('unpacker/dir_open',
                                          QDir.currentPath()),
            filter='PRN files (*.prn *.bin);;All (*)')
        if not fileName:
            return
        file = QFile(fileName)
        if not file.open(QFile.ReadWrite):
            QMessageBox.warning(
                self, "Unpacker .prn",
                "Unable load file {}:\n{}.".format(fileName,
                                                   file.errorString()))
            return
        self.settings.setValue('unpacker/dir_open', QFileInfo(file).path())
        data = QDataStream(file)
        data.setByteOrder(QDataStream.LittleEndian)
        headerVersion = data.readInt32()
        xdpi = data.readInt32()
        ydpi = data.readInt32()

        dialog = ChangeResolutionDialog(xdpi, ydpi, self)
        if dialog.exec_():
            file.seek(4)
            data.writeInt32(dialog.sbXdpi.value())
            data.writeInt32(dialog.sbYdpi.value())
            self.status.showMessage("Resolution changed successful", 7000)
        file.close()
Ejemplo n.º 3
0
def s_value_parser(isotope, vx_size):
    """returns the s-voxel values for the isotope and voxel size"""
    import logging
    import csv
    import numpy as np
    from PyQt4.QtCore import QDir

    # todo: Verify if changes in directory file is necessary
    # todo: Retrieve from url if file does not exist
    file_name = QDir.currentPath() + "/SVoxels/{}{}mmsoft.txt".format(isotope, vx_size)
    logging.info("Parsing {} ...".format(file_name))
    index_value_pair = []
    with open(file_name, 'rb') as csv_file:
        reader = csv.reader(csv_file, delimiter='\t', quotechar='\'')
        i = 0
        for row in reader:
            if i > 1:
                ix = (int(row[0]), int(row[1]), int(row[2]))
                index_value_pair.append([ix, float(row[3])])
            i += 1
    # shape is last index read + 1 in each dimension
    shape = np.array(ix) + np.array([1, 1, 1])
    s_values = np.ndarray(shape)
    for iv in index_value_pair:
        s_values[iv[0]] = iv[1]
    logging.info("...s values read")
    return s_values
Ejemplo n.º 4
0
    def __init__(self, useDevelopmentRelease=False, useProposed=False):
        self.useDevelopmentRelease = useDevelopmentRelease
        self.useProposed = useProposed
        metaRelease = MetaReleaseCore(useDevelopmentRelease, useProposed)
        metaRelease.downloaded.wait()
        if metaRelease.new_dist is None and __name__ == "__main__":
            sys.exit()
        elif metaRelease.new_dist is None:
            return

        self.progressDialogue = QDialog()
        if os.path.exists("fetch-progress.ui"):
            self.APPDIR = QDir.currentPath()
        else:
            self.APPDIR = "/usr/share/ubuntu-release-upgrader"

        uic.loadUi(self.APPDIR + "/fetch-progress.ui", self.progressDialogue)
        self.progressDialogue.setWindowIcon(KIcon("system-software-update"))
        self.progressDialogue.setWindowTitle(_("Upgrade"))
        self.progress = KDEAcquireProgressAdapter(
            self.progressDialogue.installationProgress,
            self.progressDialogue.installingLabel,
            None)
        DistUpgradeFetcherCore.__init__(self, metaRelease.new_dist,
                                        self.progress)
Ejemplo n.º 5
0
    def dbSource(self):
        dbpath = QFileDialog.getOpenFileName(
            self, 'Select input VetEpiGIS database file', QDir.currentPath(),
            'SpatiaLite file (*.sqlite *.*)')

        if os.path.isfile(dbpath):
            self.lineEdit.setText(dbpath)
Ejemplo n.º 6
0
 def importProfile( self, filename  = '' ):
     """
     Exports the current profile to a file.
     
     :param      filename | <str>
     """
     if ( not (filename and isinstance(filename, basestring)) ):
         filename = QFileDialog.getOpenFileName( self,
                                                 'Import Layout from...',
                                                 QDir.currentPath(),
                                                 'XView (*.xview)')
         
         if type(filename) == tuple:
             filename = str(filename[0])
     
     filename = str(filename)
     if not filename:
         return
     
     if not filename.endswith('.xview'):
         filename += '.xview'
     
     profile = XViewProfile.load(filename)
     if ( not profile ):
         return
         
     profile.restore(self)
Ejemplo n.º 7
0
 def loadFilename( self, filename = '' ):
     """
     Loads a new XDK file into the system.
     
     :param      filename | <str>
     
     :return     <bool> | success
     """
     if ( not (filename and isinstance(filename, basestring)) ):
         filename = QFileDialog.getOpenFileName( self,
                                                 'Open XDK File',
                                                 QDir.currentPath(),
                                                 'XDK Files (*.xdk)' )
         
         if type(filename) == tuple:
             filename = str(filename[0])
         
         if not filename:
             return False
     
     if not (filename and os.path.exists(filename)):
         return False
     
     elif filename in self.loadedFilenames():
         return False
     
     self.loadFileRequested.emit(filename)
     self.setCursor(Qt.WaitCursor)
     
     return True
Ejemplo n.º 8
0
 def __init__(self, parent = None, *args):
     super(AnalyzerTab, self).__init__(parent, *args)
     self.currentFolder = QDir.currentPath()
     self.addFileRow()
     self.addListWidget()
     self.addReadRow()
     self.addProgressBars()
Ejemplo n.º 9
0
    def importProfile(self, filename=''):
        """
        Exports the current profile to a file.
        
        :param      filename | <str>
        """
        if (not (filename and isinstance(filename, basestring))):
            filename = QFileDialog.getOpenFileName(self,
                                                   'Import Layout from...',
                                                   QDir.currentPath(),
                                                   'XView (*.xview)')

            if type(filename) == tuple:
                filename = str(filename[0])

        filename = str(filename)
        if not filename:
            return

        if not filename.endswith('.xview'):
            filename += '.xview'

        profile = XViewProfile.load(filename)
        if (not profile):
            return

        profile.restore(self)
Ejemplo n.º 10
0
        def __init__(self):
            super(self.__class__, self).__init__()
            self.setupUi(
                self)  # This is defined in design.py file automatically

            # self.listWidget_Xoutput_files.addItem("deneme")

            cleaner_files_path = os.path.join(str(QDir.currentPath()),
                                              "cleaner_files")
            if not os.path.exists(cleaner_files_path):
                os.mkdir(cleaner_files_path)

            self.model = QFileSystemModel()
            self.model.setRootPath(cleaner_files_path)

            self.model.setNameFilters(QStringList(["Xoutput-n_analyses-*.txt"
                                                   ]))
            self.model.setNameFilterDisables(False)
            self.model.setFilter(QDir.Dirs | QDir.Files)

            self.treeView_Xoutput_files.setModel(self.model)

            self.treeView_Xoutput_files.setRootIndex(
                self.model.index(cleaner_files_path))

            self.treeView_Xoutput_files.setColumnWidth(0, 500)

            self.treeView_Xoutput_files.selectionModel(
            ).selectionChanged.connect(self.load_and_view_file_contents)

            self.rules_dict = {}

            self.special_button_for_level_01.setDisabled(True)
Ejemplo n.º 11
0
    def __saveScreenshot(self):
        format = "png"
        initialPath = QDesktopServices.storageLocation(
            QDesktopServices.PicturesLocation)
        # initialPath = QStandardPaths::writableLocation(QStandardPaths::PicturesLocation);
        if initialPath.isEmpty():
            initialPath = QDir.currentPath()
        initialPath += "/untitled." + format

        fileDialog = QtGui.QFileDialog(self, u"存储为", initialPath)
        fileDialog.setAcceptMode(QtGui.QFileDialog.AcceptSave)
        fileDialog.setFileMode(QtGui.QFileDialog.AnyFile)
        fileDialog.setDirectory(initialPath)
        mimeTypes = QStringList()

        for bf in QImageWriter.supportedImageFormats():
            mimeTypes.append(QLatin1String(bf))

        # fileDialog.setMin setMimeTypeFilters(mimeTypes)
        # fileDialog.selectMimeTypeFilter("image/" + format);
        fileDialog.setDefaultSuffix(format)
        if fileDialog.accept():
            return

        fileName = fileDialog.selectedFiles().first()

        if not self.originalPixmap.save(fileName):
            QtGui.QMessageBox.Warning(
                self, u"保存错误",
                u"图像无法存储到 \"%s\"." % str(QDir.toNativeSeparators(fileName)))
Ejemplo n.º 12
0
 def getCommunicationConfig(self):
     config.reflashConfig()
     self.lineEdit_PLCIP.setText(config.PLC_IP)
     self.lineEdit_PLCPORT.setText(config.PLC_PORT)
     self.lineEdit_NIIP.setText(config.NI_IP)
     self.lineEdit_NIPORT.setText(config.NI_PORT)
     
     if config.PLATFORM == 1:
         self.radioButton_SIL.setChecked(True)
     elif config.PLATFORM == 2:
         self.radioButton_HIL.setChecked(True)
     currentDir = unicode(QDir.currentPath(),'gbk')
     PARAMDIR = os.path.join(currentDir,config.PARAMDIR)
     templist = os.listdir(PARAMDIR)
     paramlist = []
     for param in  templist:
         if param[-3:] == '.py' and 'PARAM'  in param.upper():
             paramlist.append(param)
     print paramlist
     if len(paramlist) != 0:
         self.comboBox_paramName.clear()
         self.paramlist = paramlist
         self.comboBox_paramName.addItems(paramlist)
         paramFileName = config.getTemp('paramSelect')
         if paramFileName != '':
             fileName = paramFileName + '.py'
             if fileName in  self.paramlist:
                 index = self.paramlist.index(fileName)
                 self.comboBox_paramName.setCurrentIndex(index)
Ejemplo n.º 13
0
    def loadFilename(self, filename=''):
        """
        Loads a new XDK file into the system.
        
        :param      filename | <str>
        
        :return     <bool> | success
        """
        if (not (filename and isinstance(filename, basestring))):
            filename = QFileDialog.getOpenFileName(self, 'Open XDK File',
                                                   QDir.currentPath(),
                                                   'XDK Files (*.xdk)')

            if type(filename) == tuple:
                filename = str(filename[0])

            if not filename:
                return False

        if not (filename and os.path.exists(filename)):
            return False

        elif filename in self.loadedFilenames():
            return False

        self.loadFileRequested.emit(filename)
        self.setCursor(Qt.WaitCursor)

        return True
Ejemplo n.º 14
0
 def watch_file(self, fname=None):
     logger.debug(msg("Watching file ... ", fname))
     if fname is None:
         fname = QFileDialog.getOpenFileName(self.console.widget,
                                             "Watch a Python Source File",
                                             QDir.currentPath(),
                                             "Python Source Files (*.py)")
     self.console.watch_file(fname)
Ejemplo n.º 15
0
	def saveImgFile(self):
		# opens dialog to save file with selected file type
		fileFormat = self.sender().data()
		initialPath = QDir.currentPath() + '/untitled.' + fileFormat
		fileName = QFileDialog.getSaveFileName(self, 
			"Save As...", initialPath,
			".%s Files (*.%s);;All Files (*)" % (fileFormat.lower(), fileFormat))
		if fileName:
			return self.canvas.scribbleArea.saveImage(fileName, fileFormat)
		return False
Ejemplo n.º 16
0
    def __init__(self, parent, uifile=''):
        super(XConfigWidget, self).__init__(parent)

        # load the ui if specified
        if (uifile):
            curr_dir = QDir.currentPath()
            QDir.setCurrent(os.path.dirname(uifile))
            uic.loadUi(uifile, self)
            QDir.setCurrent(curr_dir)

        self._plugin = None
Ejemplo n.º 17
0
 def load_scene_procedure(self):
     """
     Starts UI procedure to load scene form .gc file.
     """
     file_name = QFileDialog.getOpenFileName(self,
                                             "Open File",
                                             QDir.currentPath(),
                                             filter="GC File (*.gc)"
                                             )
     if file_name:
         self.load_scene_file(str(file_name))
Ejemplo n.º 18
0
 def __init__( self, parent, uifile = '' ):
     super(XConfigWidget, self).__init__(parent)
     
     # load the ui if specified
     if ( uifile ):
         curr_dir = QDir.currentPath()
         QDir.setCurrent(os.path.dirname(uifile))
         uic.loadUi(uifile, self)
         QDir.setCurrent(curr_dir)
     
     self._plugin  = None
Ejemplo n.º 19
0
 def import_directory_of_images(self):
     """
     Starts UI procedure to load scene from image stack.
     """
     param = QFileDialog.ShowDirsOnly | QFileDialog.DontResolveSymlinks
     folder_name = QFileDialog.getExistingDirectory(self,
                                                    "Open Directory",
                                                    QDir.currentPath(),
                                                    param
                                                    )
     if folder_name:
         self.load_image_stack_folder(str(folder_name))
Ejemplo n.º 20
0
 def getFileName(self):
     """
     Prompts a QFileDialog and asks user to give an xml file name. 
     Text of fileNameLineEdit is set to file name. 
     """
     fileName = unicode(
         QFileDialog.getSaveFileName(self.parent(),
                                     'Please give a file name',
                                     QDir.currentPath(), '*.xml'))
     if not fileName.endswith('.xml'):
         fileName += '.xml'
     self.fileNameLineEdit.setText(fileName)
Ejemplo n.º 21
0
    def pickFilepath(self):
        """
        Picks the image file to use for this icon path.
        """
        filepath = QFileDialog.getOpenFileName(self, 'Select Image File',
                                               QDir.currentPath(),
                                               self.fileTypes())

        if type(filepath) == tuple:
            filepath = str(filepath[0])

        if (filepath):
            self.setFilepath(filepath)
Ejemplo n.º 22
0
    def addFile(self, index):

        file = QFileDialog.getOpenFileName(
            self,
            'Load image',
            directory=self.settings.value('directories/dir_open',
                                          QDir.currentPath()),
            filter='Bitmap graphics (*.tif *.bmp);;All (*)')
        if not file:
            return
        self.settings.setValue('directories/dir_open', QFileInfo(file).path())
        self.settings.sync()
        self.addImageToTable(file, index)
    def load(self):
        fn = QFileDialog.getOpenFileName(self, "Cargar laberinto",
                                         QDir.currentPath(),
                                         "Laberintos (*.lab)")

        # QFileDialog.getOpenFileName devuelve '' si el usuario cancelo
        if len(fn) > 0:
            try:
                self.ui.frame.load(fn)
                self.disableButtons(False)
                self.reset()
            except:
                self.showLoadError(fn)
Ejemplo n.º 24
0
	def on_pushbutton_read(self):
		""""""
		self.currentId = 0
		self.isPlaying = False
		cpath = QDir.currentPath()
		self.filenames = QFileDialog.getOpenFileNames(self,"Open Photos",cpath,"IMAGE (*.jpg);;All (*.*)")
		self.label.setText(str(len(self.filenames))+" Photos are loaded")
		if len(self.filenames)==0:
			QMessageBox.information(self,"Open Photo Files", "File is not selected", QMessageBox.Ok)
			return
		self.horizontalSlider.setMinimum(0)
		self.horizontalSlider.setMaximum(len(self.filenames)-1)
		self.on_pushbuttion_first()
		self.adjustSize()
Ejemplo n.º 25
0
 def pickFilepath( self ):
     """
     Picks the image file to use for this icon path.
     """
     filepath = QFileDialog.getOpenFileName( self,
                                             'Select Image File',
                                             QDir.currentPath(),
                                             self.fileTypes())
     
     if type(filepath) == tuple:
         filepath = str(filepath[0])
     
     if ( filepath ):
         self.setFilepath(filepath)
Ejemplo n.º 26
0
 def __workingDirectory(path_):
     """
     Private function to determine working directory for the file dialog.
     
     @param path_ path of the intended working directory (string or QString)
     @return calculated working directory (QString)
     """
     path = QString(path_)
     if not path.isEmpty():
         info = QFileInfo(path)
         if info.exists() and info.isDir():
             return info.absoluteFilePath()
         return info.absolutePath()
     return QDir.currentPath()
Ejemplo n.º 27
0
 def import_ifp(self):
     """
     Starts UI procedure to import a scene from a Lytro raw file.
     """
     if read_ifp is None:
         QErrorMessage(self).showMessage('Lytro import unavailable.')
         return
     extension_filter = "LFP Raw File (*.lfp); LFP XRaw File (*.lfx);"
     file_name = QFileDialog.getOpenFileName(self.parent(),
                                             "Import File",
                                             QDir.currentPath(),
                                             filter=extension_filter,
                                             )
     if file_name:
         self.import_ifp_file(str(file_name))
Ejemplo n.º 28
0
    def saveAs(self, filename=''):
        """saves the selected files"""
        saveDialog = QFileDialog(
            self, 'Feicim Save file(s) dialog', QDir.currentPath(),
            'Python option(*.py);;Option file (*.opts);;Text file (*.txt);;CSV (*.csv)'
        )
        saveDialog.setAcceptMode(QFileDialog.AcceptSave)

        saveDialog.selectFile(filename)
        #self.connect(saveDialog, SIGNAL("filterSelected(const QString &)"),self.filter )
        ##saveDialog.setDirectory (QDir.currentPath())
        #filters = ['Option file (*.opts)' ,'Pool xml file (*.xml)','*.txt']
        #filters = ['Option file (*.opts)','*.py','*.txt']
        #saveDialog.setFilter(';;'.join(filters))
        #saveDialog.setFilter('Option file (*.opts);;Text file (*.txt);;Python option')
        #saveDialog.setFileMode(QFileDialog.AnyFile)
        #saveDialog.setViewMode(QFileDialog.Detail)

        ext = ''
        if saveDialog.exec_():
            filename = str(saveDialog.selectedFiles()[0])
            ext = saveDialog.selectedFilter()
            if 'Text file (*.txt)' in ext:
                if not filename.endswith('.txt'):
                    filename += '.txt'
            elif 'Option file (*.opts)' in ext:
                if not filename.endswith('.opts'):
                    filename += '.opts'
            elif 'Python option(*.py)' in ext:
                if not filename.endswith('.py'):
                    filename += '.py'
            elif 'CSV (*.csv)' in ext:
                if not filename.endswith('.csv'):
                    filename += '.csv'
            try:
                open(filename)
            except IOError:
                pass
            else:
                response = QMessageBox.warning(self, "File dialog",
                                               "File exists, overwrite?",
                                               QMessageBox.Ok, QMessageBox.No)
                if response == QMessageBox.No:
                    filename = ''
        if filename == '':
            return '', ''

        return filename, ext
Ejemplo n.º 29
0
    def save_scene(self):
        file_name = QFileDialog.getSaveFileName(self,
                                                "Save File",
                                                QDir.currentPath(),
                                                filter="GC File (*.gc)",
                                                )
        if file_name:
            def task():
                with open(file_name, 'wb') as out_file:
                    scene = self.render_area.gc_scene
                    gcio.write_file(out_file, scene)

            loader = BlockingTask(task,
                                  'Saving file.',
                                  parent=self)
            loader.start_task()
Ejemplo n.º 30
0
    def _create_control ( self, parent ):
        # If the caller provided a default path instead of a default directory
        # and filename, split the path into it directory and filename
        # components.
        if ((len( self.default_path )      != 0) and
            (len( self.default_directory ) == 0) and
            (len( self.default_filename )  == 0)):
            default_directory, default_filename = \
                os.path.split( self.default_path )
        else:
            default_directory = self.default_directory
            default_filename  = self.default_filename

        # Convert the filter:
        keep    = True
        filters = QStringList()

        for f in self.wildcard.split( '|' ):
            if keep and f:
                filters << f

            keep = not keep

        # Set the default directory:
        if not default_directory:
            default_directory = QDir.currentPath()

        dlg = QFileDialog( parent, self.title, default_directory )

        dlg.setViewMode( QFileDialog.Detail )
        dlg.selectFile( default_filename )
        dlg.setFilters( filters )

        if self.wildcard_index < filters.count():
            dlg.selectFilter( filters[ self.wildcard_index ] )

        if self.action == 'open':
            dlg.setAcceptMode( QFileDialog.AcceptOpen )
            dlg.setFileMode( QFileDialog.ExistingFile )
        elif self.action == 'open files':
            dlg.setAcceptMode( QFileDialog.AcceptOpen )
            dlg.setFileMode( QFileDialog.ExistingFiles )
        else:
            dlg.setAcceptMode( QFileDialog.AcceptSave )
            dlg.setFileMode( QFileDialog.AnyFile )

        return dlg
Ejemplo n.º 31
0
    def generateTrainSet(self):
        """
        Gerneruje zestaw treningowy.
        Przeprowadza naukę sieci neuronowej.
        Parametry treningu sieci są pobierane z elementów GUI.

        Uwaga: Każdorazowo sieć tworzona jest na nowo.
        
        """

        if len(self.ui.o_zbiorTreningowy.text()) == 0:
            QMessageBox.warning(None, "BMMSI",
                                u"Należy podać istniejącą scieżkę")
            return

        gen = GenratorPlikuTestowego()
        gen.generuj(self.ui.o_zbiorTreningowy.text())

        if self.siec_neuronowa is not None:
            del self.siec_neuronowa
            self.siec_neuronowa = None

        ssn_params = [
            25,
        ]  #wartstwa wejściowa
        # warstwy ukryte
        for x in range(self.ui.i_iloscWarstwUkrytych.value()):
            ssn_params.append(self.ui.i_liczbaNeuronowWarstwaUkryta.value())
        # warstwa wyjściowa
        ssn_params.append(4)
        self.siec_neuronowa = SSN(
            2 + self.ui.i_iloscWarstwUkrytych.value(),
            ssn_params,
        )

        self.siec_neuronowa.logEntry.connect(self.addLineToLog)

        self.siec_neuronowa.train(
            (QDir.currentPath() + QDir.separator() + "test.txt"),
            liczbaEpok=self.ui.i_liczbaEpok.value(),
            N=self.ui.i_wspolczynnikUczenia.value(),
            M=self.ui.i_wspolczynnikMomentum.value(),
            min_blad=self.ui.i_limiWartosciBledu.value())

        self.ui.ib_testuj.setEnabled(True)
Ejemplo n.º 32
0
    def __init__(self, parent=None):
        """
        Konstruktor klasy okna.
        Tworzy okno widoczne na ekranie i połączenia przycisków w stylu Qt.
        
        """
        QtGui.QWidget.__init__(self, parent)

        self.ui = Ui_Form()
        self.ui.setupUi(self)
        self.ui.ib_zbiorTreningowy.clicked.connect(self.chooseFolder)
        self.ui.ib_zbudujTrenujSiec.clicked.connect(self.generateTrainSet)
        self.ui.ib_testuj.clicked.connect(self.testCustomText)
        self.ui.o_zbiorTreningowy.setText(QDir.currentPath() +
                                          QDir.separator() + u"testFolder")

        # Na początku nie mamy zadnej sieci
        self.siec_neuronowa = None
Ejemplo n.º 33
0
    def __init__(self, parent=None):
        """
        Konstruktor klasy okna.
        Tworzy okno widoczne na ekranie i połączenia przycisków w stylu Qt.
        
        """
        QtGui.QWidget.__init__(self, parent)

        self.ui = Ui_Form()
        self.ui.setupUi(self)
        self.ui.ib_zbiorTreningowy.clicked.connect(self.chooseFolder)
        self.ui.ib_zbudujTrenujSiec.clicked.connect(self.generateTrainSet)
        self.ui.ib_testuj.clicked.connect(self.testCustomText)
        self.ui.o_zbiorTreningowy.setText(
            QDir.currentPath()+QDir.separator()+u"testFolder")
        
        # Na początku nie mamy zadnej sieci
        self.siec_neuronowa = None
Ejemplo n.º 34
0
 def saveAs( self, filename = '' ):
     """
     Saves the current document to the inputed filename.  If no filename \
     is supplied, then the user will be prompted to supply a filename.
     
     :param      filename | <str>
     
     :return     <bool> | success
     """
     if ( not (filename and isinstance(filename, basestring)) ):
         langTypes = XLanguage.pluginFileTypes()
         filename = QFileDialog.getSaveFileName( None,
                                                 'Save File As...',
                                                 QDir.currentPath(),
                                                 langTypes)
         
         if type(filename) == tuple:
             filename = str(filename[0])
     
     if ( not filename ):
         return False
     
     docfile = QFile(filename)
     if ( not docfile.open(QFile.WriteOnly) ):
         logger.warning('Could not open %s for writing.' % filename)
         return False
     
     success = self.write(docfile)
     docfile.close()
     
     if success:
         filename = str(filename)
         self._filename = filename
         
         self.setModified(False)
         
         # set the language
         lang = XLanguage.byFileType(os.path.splitext(filename)[1])
         if ( lang != self.language() ):
             self.setLanguage(lang)
     
     return success
Ejemplo n.º 35
0
 def pickFilepath( self ):
     """
     Prompts the user to select a filepath from the system based on the \
     current filepath mode.
     """
     mode = self.filepathMode()
     
     filepath = ''
     filepaths = []
     curr_dir = str(self._filepathEdit.text())
     if ( not curr_dir ):
         curr_dir = QDir.currentPath()
     
     if mode == XFilepathEdit.Mode.SaveFile:
         filepath = QFileDialog.getSaveFileName( self,
                                                 self.windowTitle(),
                                                 curr_dir,
                                                 self.filepathTypes() )
                                                 
     elif mode == XFilepathEdit.Mode.OpenFile:
         filepath = QFileDialog.getOpenFileName( self,
                                                 self.windowTitle(),
                                                 curr_dir,
                                                 self.filepathTypes() )
     
     elif mode == XFilepathEdit.Mode.OpenFiles:
         filepaths = QFileDialog.getOpenFileNames( self,
                                                   self.windowTitle(),
                                                   curr_dir,
                                                   self.filepathTypes() )
     
     else:
         filepath = QFileDialog.getExistingDirectory( self,
                                                      self.windowTitle(),
                                                      curr_dir )
     
     if filepath:
         if type(filepath) == tuple:
             filepath = filepath[0]
         self.setFilepath(str(filepath))
     elif filepaths:
         self.setFilepaths(map(str, filepaths))
Ejemplo n.º 36
0
    def getOutPutVRTFilename(self):
        """
        Get name of the output VRT. The folder of the output filename will be saved in settings for next time
        :return: filename of the vrt
        """
        logger.debug("getOutPutVRTFilename")
        settings = QSettings()
        lastFolder = settings.value("rasterDisplayComposer_vrtlastFolder")

        if lastFolder:
            path = lastFolder
        else:
            path = QDir.currentPath()

        fileOpened = QFileDialog.getOpenFileName(None, "Load a raster file",
                                                 path)

        settings.setValue("rasterDisplayComposer_vrtlastFolder",
                          os.path.dirname(fileOpened))
        settings.sync()
        return fileOpened
Ejemplo n.º 37
0
    def generateTrainSet(self):
        """
        Gerneruje zestaw treningowy.
        Przeprowadza naukę sieci neuronowej.
        Parametry treningu sieci są pobierane z elementów GUI.

        Uwaga: Każdorazowo sieć tworzona jest na nowo.
        
        """
        
        if len (self.ui.o_zbiorTreningowy.text()) == 0:
            QMessageBox.warning(None, "BMMSI", u"Należy podać istniejącą scieżkę")
            return
        
        gen = GenratorPlikuTestowego()
        gen.generuj(self.ui.o_zbiorTreningowy.text())
        
        if self.siec_neuronowa is not None:
            del self.siec_neuronowa
            self.siec_neuronowa = None
            
        ssn_params = [25,] #wartstwa wejściowa
        # warstwy ukryte
        for x in range(self.ui.i_iloscWarstwUkrytych.value()):
            ssn_params.append(self.ui.i_liczbaNeuronowWarstwaUkryta.value())
        # warstwa wyjściowa
        ssn_params.append(4)
        self.siec_neuronowa = SSN( 2 + self.ui.i_iloscWarstwUkrytych.value(), 
                                  ssn_params,
                                  )
                                  
        self.siec_neuronowa.logEntry.connect(self.addLineToLog)
        
        self.siec_neuronowa.train((QDir.currentPath()+QDir.separator()+"test.txt"),
                                  liczbaEpok=self.ui.i_liczbaEpok.value(),
                                  N=self.ui.i_wspolczynnikUczenia.value(),
                                  M=self.ui.i_wspolczynnikMomentum.value(),
                                  min_blad = self.ui.i_limiWartosciBledu.value() )
                                  
        self.ui.ib_testuj.setEnabled(True)
Ejemplo n.º 38
0
def getOutputDirectory(ui):
    """
    Opens a dialog to get the output directory
    """
    current_directory = ui.lineEdit_working_dir.text()
    if ui.lineEdit_working_dir.text():
        path = current_directory
    else:
        path = QDir.currentPath()
    output_directory = ""
    dir_dest = QFileDialog.getExistingDirectory(None, u"Répertoire de destination des fichiers de TerreImage", path)
    if dir_dest:
        ui.lineEdit_working_dir.setText(dir_dest)
        output_directory = dir_dest
        update_subdirectories(output_directory)

#         except UnicodeEncodeError:
#             QMessageBox.warning( None , "Erreur", u'Le répertoire que vous avec sélectionné contient un ou des caractères spéciaux. \
# La version actuelle du plugin ne gère pas ce type de répertoires. \
# Veuillez renommer le répertoire ou choisir un autre emplacement.', QMessageBox.Ok )

    return output_directory
Ejemplo n.º 39
0
    def savedlg(self):
        self.filename = QFileDialog.getSaveFileName(
            self, "Log Filename",
            self.settings.value('directories/dir_save', QDir.currentPath()),
            "Text (*.log *.txt);;All (*)")
        if not self.filename:
            return

        self.file = QFile(self.filename)
        self.lblFileName.setText(self.filename)
        if not self.file.open(QFile.WriteOnly):
            QMessageBox.warning(
                self, self.title, "Unable to write file {}:\n{}.".format(
                    self.filename, self.file.errorString()))
            self.file = None
            return
        self.textStream = QTextStream(self.file)
        self.textStream.setCodec('UTF-8')

        self.settings.setValue('directories/dir_save',
                               QFileInfo(self.file).path())
        self.file.close()
Ejemplo n.º 40
0
def getOutputDirectory(ui):
    """
    Opens a dialog to get the output directory
    """
    current_directory = ui.lineEdit_working_dir.text()
    if ui.lineEdit_working_dir.text():
        path = current_directory
    else:
        path = QDir.currentPath()
    output_directory = ""
    dir_dest = QFileDialog.getExistingDirectory(None, str("Répertoire de destination des fichiers de TerreImage"), path)
    if dir_dest:
        ui.lineEdit_working_dir.setText(dir_dest)
        output_directory = dir_dest
        update_subdirectories(output_directory)

#         except UnicodeEncodeError:
#             QMessageBox.warning( None , "Erreur", u'Le répertoire que vous avec sélectionné contient un ou des caractères spéciaux. \
# La version actuelle du plugin ne gère pas ce type de répertoires. \
# Veuillez renommer le répertoire ou choisir un autre emplacement.', QMessageBox.Ok )

    return output_directory
Ejemplo n.º 41
0
    def pickFilepath(self):
        """
        Prompts the user to select a filepath from the system based on the \
        current filepath mode.
        """
        mode = self.filepathMode()

        filepath = ''
        filepaths = []
        curr_dir = str(self._filepathEdit.text())
        if (not curr_dir):
            curr_dir = QDir.currentPath()

        if mode == XFilepathEdit.Mode.SaveFile:
            filepath = QFileDialog.getSaveFileName(self, self.windowTitle(),
                                                   curr_dir,
                                                   self.filepathTypes())

        elif mode == XFilepathEdit.Mode.OpenFile:
            filepath = QFileDialog.getOpenFileName(self, self.windowTitle(),
                                                   curr_dir,
                                                   self.filepathTypes())

        elif mode == XFilepathEdit.Mode.OpenFiles:
            filepaths = QFileDialog.getOpenFileNames(self, self.windowTitle(),
                                                     curr_dir,
                                                     self.filepathTypes())

        else:
            filepath = QFileDialog.getExistingDirectory(
                self, self.windowTitle(), curr_dir)

        if filepath:
            if type(filepath) == tuple:
                filepath = filepath[0]
            self.setFilepath(str(filepath))
        elif filepaths:
            self.setFilepaths(map(str, filepaths))
Ejemplo n.º 42
0
	def __init__(self,parent=None):
		"""Constructor"""
		QtGui.QWidget.__init__(self,parent)
		self.setupUi(self)
		
		self.filenames = []
		self.currentId = 0
		self.isPlaying = False
		self.timer = QTimer()
		self.timer.setSingleShot(False)
		self.timer.timeout.connect(self.autoLoadImage)
		self.bmp_width = 1280
		self.bmp_height = 1024
		self.spinBox.setRange(0,100)
		self.spinBox.setValue(30)
		self.label.setText('Photo Player ready!')
		img = QImage()
		cur = QDir.currentPath()
		img.load(cur+"/index.jpg")
		self.label_image.setPixmap(QPixmap.fromImage(img))
		
		self.checkBox_2.setChecked(False)

		self.doubleSpinBox_threshold1.setRange(0,1000)
		self.doubleSpinBox_threshold2.setRange(0,1000)
		self.doubleSpinBox_threshold1.setValue(50)
		self.doubleSpinBox_threshold2.setValue(100)
		self.on_checkbox_clicked()		
		
		self.pushButton_convert2bmp.clicked.connect(self.on_pushbutton_read)
		self.pushButton_autoplay.clicked.connect(self.on_pushbutton_autoplay)
		self.pushButton_next.clicked.connect(self.on_pushbuttion_next)
		self.pushButton_pre.clicked.connect(self.on_pushbuttion_pre)
		self.pushButton_first.clicked.connect(self.on_pushbuttion_first)
		self.pushButton_last.clicked.connect(self.on_pushbuttion_last)
		self.checkBox.clicked.connect(self.on_checkbox_clicked)
		self.horizontalSlider.valueChanged.connect(self.on_slider_changed)
		self.checkBox_2.clicked.connect(self.on_checkbox2_clicked)
Ejemplo n.º 43
0
    def exportProfile(self, filename=''):
        """
        Exports the current profile to a file.
        
        :param      filename | <str>
        """
        if not (filename and isinstance(filename, basestring)):
            filename = QFileDialog.getSaveFileName(self, 'Export Layout as...',
                                                   QDir.currentPath(),
                                                   'XView (*.xview)')

            if type(filename) == tuple:
                filename = filename[0]

        filename = str(filename)
        if not filename:
            return

        if not filename.endswith('.xview'):
            filename += '.xview'

        profile = self.saveProfile()
        profile.save(filename)
Ejemplo n.º 44
0
 def exportProfile( self, filename  = '' ):
     """
     Exports the current profile to a file.
     
     :param      filename | <str>
     """
     if not (filename and isinstance(filename, basestring)):
         filename = QFileDialog.getSaveFileName( self,
                                                 'Export Layout as...',
                                                 QDir.currentPath(),
                                                 'XView (*.xview)')
         
         if type(filename) == tuple:
             filename = filename[0]
     
     filename = str(filename)
     if not filename:
         return
     
     if not filename.endswith('.xview'):
         filename += '.xview'
     
     profile = self.saveProfile()
     profile.save(filename)
Ejemplo n.º 45
0
    def __init__(self, parent):
        super(SourceFileTreeWidget, self).__init__(parent)
        self.ui = Ui_SourceFileTreeWidget()
        self.ui.setupUi(self)
        self.file_model = QFileSystemModel()
        #self.file_model.setFilter(QDir.AllEntries | QDir.NoDot)
        self.set_filter()
        self.ui.tree.setModel(self.file_model)
        self.ui.tree.resizeColumnToContents(0)
        self.ui.custom_root.setText(QDir.currentPath())
        self.set_root()

        header = self.ui.tree.header()
        header.setResizeMode(QHeaderView.ResizeToContents)
        #header.setStretchLastSection(True)
        #header.setSortIndicator(0, Qt.AscendingOrder)
        #header.setSortIndicatorShown(True)
        #header.setClickable(True)
        self.connect(self.ui.tree, QtCore.SIGNAL('doubleClicked(QModelIndex)'), self.open_file)
        self.connect(self.ui.ok_filter, QtCore.SIGNAL('clicked()'), self.set_filter)
        self.connect(self.ui.custom_filter, QtCore.SIGNAL('returnPressed()'), self.set_filter)
        self.connect(self.ui.ok_root, QtCore.SIGNAL('clicked()'), self.set_root)
        self.connect(self.ui.custom_root, QtCore.SIGNAL('returnPressed()'), self.set_root)
        self.open_file_signal = None
Ejemplo n.º 46
0
    def changeResolution(self):
        fileName = QFileDialog.getOpenFileName(self, 'Load .prn file', directory=self.settings.value('unpacker/dir_open',QDir.currentPath()), filter='PRN files (*.prn *.bin);;All (*)')
        if not fileName:
            return
        file = QFile(fileName)
        if not file.open(QFile.ReadWrite):
            QMessageBox.warning(self, "Unpacker .prn", "Unable load file {}:\n{}.".format(fileName, file.errorString()))
            return
        self.settings.setValue('unpacker/dir_open', QFileInfo(file).path())
        data = QDataStream(file)
        data.setByteOrder(QDataStream.LittleEndian)
        headerVersion = data.readInt32()
        xdpi = data.readInt32()
        ydpi = data.readInt32()

        dialog = ChangeResolutionDialog(xdpi, ydpi, self)
        if dialog.exec_():
            file.seek(4)
            data.writeInt32(dialog.sbXdpi.value())
            data.writeInt32(dialog.sbYdpi.value())
            self.status.showMessage("Resolution changed successful", 7000)
        file.close()
Ejemplo n.º 47
0
    def unpackPrnFile(self):
        fileName = QFileDialog.getOpenFileName(self, 'Load .prn file', directory=self.settings.value('unpacker/dir_open',QDir.currentPath()), filter='PRN files (*.prn *.bin);;All (*)')
        if not fileName:
            return
        file = QFile(fileName)
        if not file.open(QFile.ReadOnly):
            QMessageBox.warning(self, "Unpacker .prn", "Unable load file {}:\n{}.".format(fileName, file.errorString()))
            return
        self.settings.setValue('unpacker/dir_open', QFileInfo(file).path())
        data = QDataStream(file)
        data.setByteOrder(QDataStream.LittleEndian)
        file_name = QFileInfo(file).fileName()

        headerVersion = int.from_bytes(data.readRawData(4), 'little', signed=False)
        self.status.showMessage("Header Type: {:#X}".format(headerVersion))

        if headerVersion == self.NEW_RIP_FILE:
            xdpi = data.readInt32()
            ydpi = data.readInt32()
            bpl = data.readInt32()
            imgh = data.readInt32()
            imgw = data.readInt32()
            ppw = data.readInt32()
            colnum = data.readInt32()
            bitsperdrop = data.readInt32()
            colorOrder = data.readRawData(16).decode().replace(chr(0), '')
            colorList = list(colorOrder)
            name = b'\xff\xfe' + data.readRawData(512)
            name = name.decode('utf-16').replace(chr(0), '')
            zero = data.readInt32()
        elif headerVersion == self.STD_RIP_FILE:
            xdpi = data.readInt32()
            ydpi = data.readInt32()
            bpl = data.readInt32()
            imgh = data.readInt32()
            imgw = data.readInt32()
            ppw = data.readInt32()
            colnum = data.readInt32()
            bitsperdrop = data.readInt32()
            if not bitsperdrop:
                QMessageBox.warning(self, "Unpacker .prn", "File format not supported")
                return
            colorOrder = data.readRawData(16).decode().replace(chr(0), '')
            colorList = list(colorOrder)
            zero = data.readInt32()
            name = 'Not used in this format'
        elif headerVersion == self.CALDERA_RIP_FILE:
            xdpi = data.readInt32()
            ydpi = data.readInt32()
            bpl = data.readInt32()
            imgh = data.readInt32()
            imgw = data.readInt32()
            ppw = data.readInt32()
            colnum = data.readInt32()
            bitsperdrop = data.readInt32()
            if not bitsperdrop:
                QMessageBox.warning(self, "Unpacker .prn", "File format not supported")
                return
            colorOrder = data.readRawData(16).decode().replace(chr(0), '')
            colorList = list(colorOrder)
            zero = data.readInt32()
            name = 'Not used in this format'
        else:
            QMessageBox.warning(self, "Unpacker .prn", "File format not supported")
            return

        colors = {}
        for color in colorList:
            colors[color] = {}
            for level in range(1, 2**bitsperdrop):
                colors[color][level] = QImage(imgw, imgh , QImage.Format_Mono)
                colors[color][level].setColor(0, qRgb(255, 255, 255))
                colors[color][level].setColor(1, qRgb(0, 0, 0))
                colors[color][level].fill(0)

        pd = QProgressDialog('Analyze file ...', 'Cancel', 0, imgh-1, self)
        pd.setWindowTitle('Analyze ...')
        pd.open()

        mask = 0xFF>>(8-bitsperdrop) # Получаем маску для текущего количества бит на каплю
        for row in range(imgh):
            for color in colorList:
                for bytenum in range(0, bpl, bitsperdrop): # Получаем номер байта, с которого будем читать
                    byte = int.from_bytes(data.readRawData(bitsperdrop), 'big')
                    for pix in range(8):
                        shift = (7 - pix)*bitsperdrop
                        pixel = (byte>>shift)&mask
                        if pixel > 0:
                            numofpix = 8*bytenum/bitsperdrop + pix
                            if numofpix < imgw:
                                colors[color][pixel].setPixel(numofpix, row, 1)
            pd.setValue(row)
            if pd.wasCanceled():
                pd.close()
                file.close()
                return
        pd.close()
        file.close()

        catalog = QFileDialog.getExistingDirectory(self, directory=self.settings.value('unpacker/dir_save',QDir.currentPath()))
        if catalog is None:
            return
        self.settings.setValue('unpacker/dir_save', catalog)

        file = QFile("{}\{}_{}.txt".format(catalog, file_name, colorOrder))
        if not file.open(QFile.WriteOnly | QFile.Text):
            QMessageBox.warning(self, "Prn creator", "Unable create file {}:\n{}.".format(name, file.errorString()))
            return

        text = QTextStream(file)
        text << "Filename: {}\n".format(file_name)
        text << "Test Name: {}\n\n".format(name)
        text << "X Resolution: {} dpi\n".format(xdpi)
        text << "Y Resolution: {} dpi\n".format(ydpi)
        text << "Image Width: {} pix\n".format(imgw)
        text << "Image Height: {} pix\n\n".format(imgh)
        text << "Bits Per Drop: {}\n".format(bitsperdrop)
        text << "Bytes Per Line: {}\n\n".format(bpl)
        text << "Number Of Colors: {}\n".format(colnum)
        text << "Order Of Colors: {}\n\n".format(colorOrder)
        text << "Paper Width: {}\n".format(ppw)

        for color in colorList:
            for level in range(1, 2**bitsperdrop):
                colors[color][level].save("{}\{}.{}.gs{}.tif".format(catalog, file_name, "{}".format(color) if color.isupper() else "_{}".format(color), level))

        self.status.showMessage("Unpacking finished", 7000)
Ejemplo n.º 48
0
    def savePrnFile(self):
        width = 0
        height = 0
        images = {}
        for index in range(self.table.rowCount()):
            image = self.table.item(index, 0).data(Qt.UserRole)
            color = self.colors[self.table.cellWidget(index, 1).currentText()]
            if color not in images:
                images[color] = {}

            levelCmb = self.table.cellWidget(index, 2)
            level = levelCmb.itemData(levelCmb.currentIndex())
            if level in images[color]:
                QMessageBox.warning(self, "Error!", "Duplicated GS Level for color!")
                return
            else:
                images[color][level] = image

            if width != 0:
                if width != image.width():
                    QMessageBox.warning(self, "Error!", "Width of images does not match!")
                    return
            else:
                width = image.width()

            if height != 0:
                if height != image.height():
                    QMessageBox.warning(self, "Error!", "Height of images does not match!")
                    return
            else:
                height = image.height()

        fileName = QFileDialog.getSaveFileName(self, "Save .prn file", self.settings.value('directories/dir_save', QDir.currentPath()),
                "PRN Files (*.prn);;BIN Files (*.bin)")

        if not fileName:
            return

        file = QFile(fileName)
        if not file.open(QFile.WriteOnly):
            QMessageBox.warning(self, "Prn Creator", "Unable to write file {}:\n{}.".format(self.fileName, file.errorString()))
            return
        self.settings.setValue('directories/dir_save', QFileInfo(file).path())

        self.testName, status = QInputDialog.getText(self, "Test name", "Enter name of the test to write into file:", text="Test")

        if not status:
            QMessageBox.warning(self, "Prn Creator", "Name changed to 'Test'")
            self.testName = "Test"

        self.fileName = QFileInfo(file).fileName()
        self.out = QDataStream(file)
        self.out.setByteOrder(QDataStream.LittleEndian)

        colors = ''
        for color in images:
            colors+=color

        self.imgwidth = width
        self.imgheight = height
        self.bytesPerLine = int((self.gsLevel*self.imgwidth+31)/32)*4
        self.writeNewHeader(colors)

        pd = QProgressDialog('Writing file ...', 'Cancel', 0, self.imgheight-1, self)
        pd.setWindowTitle('Creating file...')
        pd.open()


        tmp = 0
        # Записывать данные будем построчно
        for row in range(self.imgheight):
            # обходим по порядку цветов, как расположены в файле
            for color in colors:
                # Добиваем строку до длины, кратной 32м байтам
                for column in range (int(self.bytesPerLine/self.gsLevel*8)):
                    shift = 7-column+int(column/8)*8
                    pixel = 0
                    # Упорядочиваем уровни (на всякий)
                    levels = sorted(list(images[color].keys()))
                    # Если изображение меньше длины строки, то
                    if column < self.imgwidth:
                        for level in levels:
                            # Выбираем максимальный уровень из тех, что указаны в данном пикселе на всех слоях
                            if images[color][level].pixel(column, row) == self.black:
                                pixel = level
                    tmp |= (pixel<<shift*self.gsLevel)
                    # Как только сдвиг обнулится, то записываем в файл
                    if not shift:
                        self.out.writeRawData(tmp.to_bytes(self.gsLevel, 'big'))
                        tmp=0
            pd.setValue(row)
            if pd.wasCanceled():
                pd.close()
                file.close()
                return
        pd.close()
        file.close()

        self.status.showMessage("File created successful", 7000)
Ejemplo n.º 49
0
    def addFile(self, index):

        file = QFileDialog.getOpenFileName(self, 'Load image', directory=self.settings.value('directories/dir_open',QDir.currentPath()), filter='Bitmap graphics (*.tif *.bmp);;All (*)')
        if not file:
            return
        self.settings.setValue('directories/dir_open', QFileInfo(file).path())
        self.settings.sync()
        self.addImageToTable(file, index)
Ejemplo n.º 50
0
Archivo: system.py Proyecto: gem/sidd
def get_app_dir():
    """ get the path to the application's root directory."""
    return str(QDir.currentPath())
Ejemplo n.º 51
0
 def __getDefaultSaveDir(self):
     " Provides the default directory to save files to "
     project = GlobalData().project
     if project.isLoaded():
         return project.getProjectDir()
     return QDir.currentPath()
Ejemplo n.º 52
0
    def savePrnFile(self):
        width = 0
        height = 0
        images = {}
        for index in range(self.table.rowCount()):
            image = self.table.item(index, 0).data(Qt.UserRole)
            color = self.colors[self.table.cellWidget(index, 1).currentText()]
            if color not in images:
                images[color] = {}

            levelCmb = self.table.cellWidget(index, 2)
            level = levelCmb.itemData(levelCmb.currentIndex())
            if level in images[color]:
                QMessageBox.warning(self, "Error!",
                                    "Duplicated GS Level for color!")
                return
            else:
                images[color][level] = image

            if width != 0:
                if width != image.width():
                    QMessageBox.warning(self, "Error!",
                                        "Width of images does not match!")
                    return
            else:
                width = image.width()

            if height != 0:
                if height != image.height():
                    QMessageBox.warning(self, "Error!",
                                        "Height of images does not match!")
                    return
            else:
                height = image.height()

        fileName = QFileDialog.getSaveFileName(
            self, "Save .prn file",
            self.settings.value('directories/dir_save', QDir.currentPath()),
            "PRN Files (*.prn);;BIN Files (*.bin)")

        if not fileName:
            return

        file = QFile(fileName)
        if not file.open(QFile.WriteOnly):
            QMessageBox.warning(
                self, "Prn Creator",
                "Unable to write file {}:\n{}.".format(self.fileName,
                                                       file.errorString()))
            return
        self.settings.setValue('directories/dir_save', QFileInfo(file).path())

        self.testName, status = QInputDialog.getText(
            self,
            "Test name",
            "Enter name of the test to write into file:",
            text="Test")

        if not status:
            QMessageBox.warning(self, "Prn Creator", "Name changed to 'Test'")
            self.testName = "Test"

        self.fileName = QFileInfo(file).fileName()
        self.out = QDataStream(file)
        self.out.setByteOrder(QDataStream.LittleEndian)

        colors = ''
        for color in images:
            colors += color

        self.imgwidth = width
        self.imgheight = height
        self.bytesPerLine = int((self.gsLevel * self.imgwidth + 31) / 32) * 4
        self.writeNewHeader(colors)

        pd = QProgressDialog('Writing file ...', 'Cancel', 0,
                             self.imgheight - 1, self)
        pd.setWindowTitle('Creating file...')
        pd.open()

        tmp = 0
        # Записывать данные будем построчно
        for row in range(self.imgheight):
            # обходим по порядку цветов, как расположены в файле
            for color in colors:
                # Добиваем строку до длины, кратной 32м байтам
                for column in range(int(self.bytesPerLine / self.gsLevel * 8)):
                    shift = 7 - column + int(column / 8) * 8
                    pixel = 0
                    # Упорядочиваем уровни (на всякий)
                    levels = sorted(list(images[color].keys()))
                    # Если изображение меньше длины строки, то
                    if column < self.imgwidth:
                        for level in levels:
                            # Выбираем максимальный уровень из тех, что указаны в данном пикселе на всех слоях
                            if images[color][level].pixel(column,
                                                          row) == self.black:
                                pixel = level
                    tmp |= (pixel << shift * self.gsLevel)
                    # Как только сдвиг обнулится, то записываем в файл
                    if not shift:
                        self.out.writeRawData(tmp.to_bytes(
                            self.gsLevel, 'big'))
                        tmp = 0
            pd.setValue(row)
            if pd.wasCanceled():
                pd.close()
                file.close()
                return
        pd.close()
        file.close()

        self.status.showMessage("File created successful", 7000)
Ejemplo n.º 53
0
    def unpackPrnFile(self):
        fileName = QFileDialog.getOpenFileName(
            self,
            'Load .prn file',
            directory=self.settings.value('unpacker/dir_open',
                                          QDir.currentPath()),
            filter='PRN files (*.prn *.bin);;All (*)')
        if not fileName:
            return
        file = QFile(fileName)
        if not file.open(QFile.ReadOnly):
            QMessageBox.warning(
                self, "Unpacker .prn",
                "Unable load file {}:\n{}.".format(fileName,
                                                   file.errorString()))
            return
        self.settings.setValue('unpacker/dir_open', QFileInfo(file).path())
        data = QDataStream(file)
        data.setByteOrder(QDataStream.LittleEndian)
        file_name = QFileInfo(file).fileName()

        headerVersion = int.from_bytes(data.readRawData(4),
                                       'little',
                                       signed=False)
        self.status.showMessage("Header Type: {:#X}".format(headerVersion))

        if headerVersion == self.NEW_RIP_FILE:
            xdpi = data.readInt32()
            ydpi = data.readInt32()
            bpl = data.readInt32()
            imgh = data.readInt32()
            imgw = data.readInt32()
            ppw = data.readInt32()
            colnum = data.readInt32()
            bitsperdrop = data.readInt32()
            colorOrder = data.readRawData(16).decode().replace(chr(0), '')
            colorList = list(colorOrder)
            name = b'\xff\xfe' + data.readRawData(512)
            name = name.decode('utf-16').replace(chr(0), '')
            zero = data.readInt32()
        elif headerVersion == self.STD_RIP_FILE:
            xdpi = data.readInt32()
            ydpi = data.readInt32()
            bpl = data.readInt32()
            imgh = data.readInt32()
            imgw = data.readInt32()
            ppw = data.readInt32()
            colnum = data.readInt32()
            bitsperdrop = data.readInt32()
            if not bitsperdrop:
                QMessageBox.warning(self, "Unpacker .prn",
                                    "File format not supported")
                return
            colorOrder = data.readRawData(16).decode().replace(chr(0), '')
            colorList = list(colorOrder)
            zero = data.readInt32()
            name = 'Not used in this format'
        elif headerVersion == self.CALDERA_RIP_FILE:
            xdpi = data.readInt32()
            ydpi = data.readInt32()
            bpl = data.readInt32()
            imgh = data.readInt32()
            imgw = data.readInt32()
            ppw = data.readInt32()
            colnum = data.readInt32()
            bitsperdrop = data.readInt32()
            if not bitsperdrop:
                QMessageBox.warning(self, "Unpacker .prn",
                                    "File format not supported")
                return
            colorOrder = data.readRawData(16).decode().replace(chr(0), '')
            colorList = list(colorOrder)
            zero = data.readInt32()
            name = 'Not used in this format'
        else:
            QMessageBox.warning(self, "Unpacker .prn",
                                "File format not supported")
            return

        colors = {}
        for color in colorList:
            colors[color] = {}
            for level in range(1, 2**bitsperdrop):
                colors[color][level] = QImage(imgw, imgh, QImage.Format_Mono)
                colors[color][level].setColor(0, qRgb(255, 255, 255))
                colors[color][level].setColor(1, qRgb(0, 0, 0))
                colors[color][level].fill(0)

        pd = QProgressDialog('Analyze file ...', 'Cancel', 0, imgh - 1, self)
        pd.setWindowTitle('Analyze ...')
        pd.open()

        mask = 0xFF >> (
            8 - bitsperdrop
        )  # Получаем маску для текущего количества бит на каплю
        for row in range(imgh):
            for color in colorList:
                for bytenum in range(
                        0, bpl, bitsperdrop
                ):  # Получаем номер байта, с которого будем читать
                    byte = int.from_bytes(data.readRawData(bitsperdrop), 'big')
                    for pix in range(8):
                        shift = (7 - pix) * bitsperdrop
                        pixel = (byte >> shift) & mask
                        if pixel > 0:
                            numofpix = 8 * bytenum / bitsperdrop + pix
                            if numofpix < imgw:
                                colors[color][pixel].setPixel(numofpix, row, 1)
            pd.setValue(row)
            if pd.wasCanceled():
                pd.close()
                file.close()
                return
        pd.close()
        file.close()

        catalog = QFileDialog.getExistingDirectory(
            self,
            directory=self.settings.value('unpacker/dir_save',
                                          QDir.currentPath()))
        if catalog is None:
            return
        self.settings.setValue('unpacker/dir_save', catalog)

        file = QFile("{}\{}_{}.txt".format(catalog, file_name, colorOrder))
        if not file.open(QFile.WriteOnly | QFile.Text):
            QMessageBox.warning(
                self, "Prn creator",
                "Unable create file {}:\n{}.".format(name, file.errorString()))
            return

        text = QTextStream(file)
        text << "Filename: {}\n".format(file_name)
        text << "Test Name: {}\n\n".format(name)
        text << "X Resolution: {} dpi\n".format(xdpi)
        text << "Y Resolution: {} dpi\n".format(ydpi)
        text << "Image Width: {} pix\n".format(imgw)
        text << "Image Height: {} pix\n\n".format(imgh)
        text << "Bits Per Drop: {}\n".format(bitsperdrop)
        text << "Bytes Per Line: {}\n\n".format(bpl)
        text << "Number Of Colors: {}\n".format(colnum)
        text << "Order Of Colors: {}\n\n".format(colorOrder)
        text << "Paper Width: {}\n".format(ppw)

        for color in colorList:
            for level in range(1, 2**bitsperdrop):
                colors[color][level].save("{}\{}.{}.gs{}.tif".format(
                    catalog, file_name, "{}".format(color)
                    if color.isupper() else "_{}".format(color), level))

        self.status.showMessage("Unpacking finished", 7000)
Ejemplo n.º 54
0
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.setMinimumWidth(500)
        self.setMinimumHeight(200)
        self._dynamic = False

        self.setWindowTitle("Export data")
        self.activateWindow()

        layout = QFormLayout()
        current_case = getCurrentCaseName()

        self._case_model = AllCasesModel()
        self._case_combo = QComboBox()
        self._case_combo.setSizeAdjustPolicy(QComboBox.AdjustToMinimumContentsLength)
        self._case_combo.setMinimumContentsLength(20)
        self._case_combo.setModel(self._case_model)
        self._case_combo.setCurrentIndex(self._case_model.indexOf(current_case))
        layout.addRow("Select case:", self._case_combo)

        self._export_keyword_model = ExportKeywordModel()

        self._kw_model = self._export_keyword_model.getKeyWords()
        self._keywords = QComboBox()
        self._keywords.addItems(self._kw_model)
        layout.addRow("Select keyword:", self._keywords)

        self._active_realizations_model = ActiveRealizationsModel()
        self._active_realizations_field = StringBox(self._active_realizations_model, "config/simulation/active_realizations")
        self._active_realizations_field.setValidator(RangeStringArgument())
        self._active_realizations_field.getValidationSupport().validationChanged.connect(self.validateExportDialog)
        layout.addRow("Active realizations:", self._active_realizations_field)

        file_name_button = QToolButton()
        file_name_button.setText("Browse")
        file_name_button.clicked.connect(self.selectFileDirectory)

        self._defaultPath = QDir.currentPath() + "/export"
        self._file_name = QLineEdit()
        self._file_name.setEnabled(False)
        self._file_name.setText(self._defaultPath)
        self._file_name.textChanged.connect(self.validateExportDialog)
        self._file_name.setMinimumWidth(250)

        file_name_layout = QHBoxLayout()
        file_name_layout.addWidget(self._file_name)
        file_name_layout.addWidget(file_name_button)
        layout.addRow("Select directory to save files to:", file_name_layout)

        self._gen_kw_file_types = ["Parameter list", "Template based"]
        self._field_kw_file_types = ["Eclipse GRDECL", "RMS roff"]
        self._gen_data_file_types = ["Gen data"]

        self._file_type_model = self._field_kw_file_types
        self._file_type_combo = QComboBox()
        self._file_type_combo.setSizeAdjustPolicy(QComboBox.AdjustToContents)
        self._file_type_combo.addItems(self._file_type_model)
        layout.addRow("Select file format:", self._file_type_combo)

        self._report_step = QLineEdit()
        layout.addRow("Report step:", self._report_step)

        self._gen_data_report_step_model = []
        self._gen_data_report_step = QComboBox()
        layout.addRow("Report step:", self._gen_data_report_step)

        self.setLayout(layout)
        self._keywords.currentIndexChanged.connect(self.keywordSelected)
        self.keywordSelected()
Ejemplo n.º 55
0
@contact : ****@massclouds.com
@site    : http://blog.csdn.net/***
@software: PyCharm
@time    : 17-1-5 下午5:19
"""

from PyQt4.QtGui import QApplication,QTreeView,QFileSystemModel, QListView
from PyQt4.QtCore import QDir
import sys


if __name__ == '__main__':
    app = QApplication(sys.argv)
    # 1. 创建 模型 model  */
    model = QFileSystemModel()            # 创建文件系统模型
    model.setRootPath(QDir.currentPath()) # 指定要监视的目录

    # 2. 创建 视图 view  */
    tree = QTreeView()                                 # 创建树型视图
    tree.setModel(model)                               # 为视图指定模型
    tree.setRootIndex(model.index(QDir.currentPath() ))# 指定根索引

    listw = QListView()                                # 创建列表视图
    listw.setModel(model)                              # 为视图指定模型
    listw.setRootIndex(model.index(QDir.currentPath()))# 指定根索引

    tree.setWindowTitle("QTreeView")
    tree.show()
    listw.setWindowTitle("QListView")
    listw.show()
Ejemplo n.º 56
0
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.setMinimumWidth(500)
        self.setMinimumHeight(200)
        self._dynamic = False

        self.setWindowTitle("Export data")
        self.activateWindow()

        layout = QFormLayout()
        current_case = getCurrentCaseName()

        self._case_model = AllCasesModel()
        self._case_combo = QComboBox()
        self._case_combo.setSizeAdjustPolicy(QComboBox.AdjustToMinimumContentsLength)
        self._case_combo.setMinimumContentsLength(20)
        self._case_combo.setModel(self._case_model)
        self._case_combo.setCurrentIndex(self._case_model.indexOf(current_case))
        layout.addRow("Select case:", self._case_combo)

        self._export_keyword_model = ExportKeywordModel()

        self._kw_model = self._export_keyword_model.getKeyWords()
        self._keywords = QComboBox()
        self._keywords.addItems(self._kw_model)
        layout.addRow("Select keyword:", self._keywords)

        self._active_realizations_model = ActiveRealizationsModel()
        self._active_realizations_field = StringBox(self._active_realizations_model, "config/simulation/active_realizations")
        self._active_realizations_field.setValidator(RangeStringArgument())
        self._active_realizations_field.getValidationSupport().validationChanged.connect(self.validateExportDialog)
        layout.addRow("Active realizations:", self._active_realizations_field)

        file_name_button = QToolButton()
        file_name_button.setText("Browse")
        file_name_button.clicked.connect(self.selectFileDirectory)

        self._defaultPath = QDir.currentPath() + "/export"
        self._file_name = QLineEdit()
        self._file_name.setEnabled(False)
        self._file_name.setText(self._defaultPath)
        self._file_name.textChanged.connect(self.validateExportDialog)
        self._file_name.setMinimumWidth(250)

        file_name_layout = QHBoxLayout()
        file_name_layout.addWidget(self._file_name)
        file_name_layout.addWidget(file_name_button)
        layout.addRow("Select directory to save files to:", file_name_layout)

        self._gen_kw_file_types = ["Parameter list", "Template based"]
        self._field_kw_file_types = ["Eclipse GRDECL", "RMS roff"]
        self._gen_data_file_types = ["Gen data"]

        self._file_type_model = self._field_kw_file_types
        self._file_type_combo = QComboBox()
        self._file_type_combo.setSizeAdjustPolicy(QComboBox.AdjustToContents)
        self._file_type_combo.addItems(self._file_type_model)
        layout.addRow("Select file format:", self._file_type_combo)

        self._report_step = QLineEdit()
        layout.addRow("Report step:", self._report_step)

        self._gen_data_report_step_model = []
        self._gen_data_report_step = QComboBox()
        layout.addRow("Report step:", self._gen_data_report_step)

        self.setLayout(layout)
        self._keywords.currentIndexChanged.connect(self.keywordSelected)
        self.keywordSelected()
Ejemplo n.º 57
0
##
#############################################################################

import sys
from PyQt4.QtCore import QDir, Qt
from PyQt4.QtGui import *

app = QApplication(sys.argv)

background = QWidget()
palette = QPalette()
palette.setColor(QPalette.Window, QColor(Qt.white))
background.setPalette(palette)

model = QFileSystemModel()
model.setRootPath(QDir.currentPath())

treeView = QTreeView(background)
treeView.setModel(model)
treeView.setRootIndex(model.index(QDir.currentPath()))

listView = QListView(background)
listView.setModel(model)
listView.setRootIndex(model.index(QDir.currentPath()))

tableView = QTableView(background)
tableView.setModel(model)
tableView.setRootIndex(model.index(QDir.currentPath()))

selection = QItemSelectionModel(model)
treeView.setSelectionModel(selection)
Ejemplo n.º 58
0
def get_workinglayer_on_opening(iface):
    settings = QSettings()
    last_folder = settings.value("terre_image_last_folder")

    if last_folder:
        path = last_folder
    else:
        path = QDir.currentPath()

    file_opened = QFileDialog.getOpenFileName(
        None, "Selectionner un fichier raster", path)

    settings.setValue("terre_image_last_folder", os.path.dirname(file_opened))
    settings.sync()

    if file_opened:
        #         try:
        #             str(file_opened)
        #         except UnicodeEncodeError:
        #             QMessageBox.warning( None , "Erreur", u'L\'image que vous essayez d\'ouvrir contient un ou des caractères spéciaux. \
        # La version actuelle du plugin ne gère pas ce type de fichiers. \
        # Veuillez renommer le fichier et ou les répertoires le contenant.', QMessageBox.Ok )
        #             return None, None
        #         else:
        #             if file_opened.find(" ") != -1:
        #                 QMessageBox.warning( None , "Attention", u'L\'image que vous essayez d\'ouvrir contient un ou plusieurs espaces. Les traitements sur cette image provoqueront une erreur.'.encode('utf8'), QMessageBox.Ok )

        if file_opened.endswith(".qgs"):
            # open new qgis project
            pass
        else:
            raster_layer = manage_QGIS.get_raster_layer(
                file_opened,
                os.path.splitext(os.path.basename(file_opened))[0])
            type_image = terre_image_processing.get_sensor_id(file_opened)
            logger.debug("type_image {}".format(type_image))
            layer = WorkingLayer(file_opened, raster_layer)
            layer.set_type(type_image)
            # self.layer = self.canvas.currentLayer()
            if layer:
                # self.define_bands(self.layer)
                # manage_bands()
                # self.red, self.green, self.blue, self.pir, self.mir = manage_bands().get_values()
                red, green, blue, pir, mir = manage_bands(
                    type_image, layer.get_band_number()).get_values()

                if red != -1 or green != -1 or blue != -1 or pir != -1 or mir != -1:
                    all_set = True
                    bands = {
                        'red': red,
                        'green': green,
                        'blue': blue,
                        'pir': pir,
                        'mir': mir
                    }
                    for i in range(1, layer.get_band_number() + 1):
                        if i not in bands.values():
                            all_set = False
                    if all_set:
                        layer.set_bands(bands)

                        logger.debug("{} {} {} {} {}".format(
                            red, green, blue, pir, mir))

                        cst = TerreImageConstant()
                        cst.index_group = cst.iface.legendInterface().addGroup(
                            "Terre Image", True, None)

                        manage_QGIS.add_qgis_raser_layer(
                            raster_layer, iface.mapCanvas(), bands)
                        terre_image_gdal_system.compute_overviews(file_opened)
                        return layer, bands
                    else:
                        QMessageBox.warning(
                            None, "Erreur",
                            u'Il y a un problème dans la définition des bandes spectrales.',
                            QMessageBox.Ok)
                        return None, None
                else:
                    return None, None
    else:
        return None, None