Exemplo n.º 1
0
 def composeDestDir(self, fnam, fiSource, extRef):
     fiOri = QtCore.QFileInfo(fnam)
     isAbs = fiOri.isAbsolute()
     dirSep = QtCore.QDir.separator()
     folderName = QtCore.QDir(extRef.filePath).dirName()
     subDirNames = QtCore.QFileInfo(self.prjFileName).baseName() + '_files'
     if self.optExportMode <> OEM_ABSOLUTIZE:
         subDirNames += dirSep
         if isAbs:
             """ BUG in pyQt?!?!?: without the QString cast the error "cannot concatenate 'str' and 'QChar' objects"
                 is raised and only if the first part is a str object (not the other way round)
             """
             subDirNames += QtCore.QString(
                 'absolute') + dirSep + fiSource.absoluteFilePath().replace(
                     ':', '_')
         else:
             if fiSource.absolutePath().startsWith(
                     self.env.instDir
             ) and self.optExportMode <> OEM_USERIZE:
                 subDirNames += 'factory'
             else:
                 subDirNames += 'user'
             subDirNames += dirSep + folderName
             if fiOri.path():
                 subDirNames += dirSep + fiOri.path()
     return QtCore.QDir(self.dExpFolder.absolutePath() + dirSep +
                        subDirNames)
Exemplo n.º 2
0
    def save_File(self):
        self.textView.clear()
        try:
            dialog = QtGui.QMessageBox.warning(
                self.centralwidget, 'Warning',
                "Please: only save into the UsersArea!!!",
                QtGui.QMessageBox.Ok)

            self.grab_Info()
            if self.textView.document().blockCount() > 1:
                if QtCore.QDir(P1defaultPath).exists():
                    defaultPath = P1defaultPath + 'parameters.dat'
                elif QtCore.QDir(EMFdefaultPath).exists():
                    defaultPath = EMFdefaultPath + 'parameters.dat'
                else:
                    defaultPath = 'parameters.dat'

                saveFileName = QtGui.QFileDialog.getSaveFileName(
                    self.centralwidget, 'Saving parameters.dat File',
                    defaultPath, '', '*.dat')
                if saveFileName:
                    savefile = open(saveFileName, 'w')
                    savefile.write(self.textView.toPlainText())
                    savefile.close()
        except AttributeError:
            error = QtGui.QMessageBox.warning(self.centralwidget, 'Error',
                                              "There are empty cells!",
                                              QtGui.QMessageBox.Ok)
Exemplo n.º 3
0
    def update_experiments(self):
        expList = self.get_experiment_list()
        query = QtSql.QSqlQuery(self.db)

        #For each animal, get folder "Experiments" (self.expPath)
        query.exec_("Select pathLocal,animalID,pathBackUP from Animal")

        #add new folders
        while query.next():
            pathLocalExp = QtCore.QDir(query.value(0)).filePath(
                self.expPath)  #ex: ../Rat034/Experiments
            animalID = query.value(1)
            pathBackUPExp = QtCore.QDir(query.value(2)).filePath(self.expPath)

            animalExp = QtCore.QDir(pathLocalExp)

            for folder in animalExp.entryList(["no file"], QtCore.QDir.AllDirs
                                              | QtCore.QDir.NoDotAndDotDot):
                if folder in expList:
                    expList.remove(folder)
                elif folder.startswith(animalID):
                    expPathLocal = animalExp.filePath(folder)
                    if pathBackUPExp.startswith("unknown"):
                        expPathBackUP = "unknown"
                    else:
                        expPathBackUP = QtCore.QDir(pathBackUPExp).filePath(
                            folder)
                    self.add_experiment(folder, animalID, expPathLocal,
                                        expPathBackUP)

        #remove deleted folders
        if len(expList) > 0:
            for exp in expList:
                self.delete_exp(exp)
Exemplo n.º 4
0
    def __init__(self, width, height, homeFolder=None):
        QtGui.QTreeView.__init__(self)
        self._width = width
        self._height = height
        self.model = QtGui.QFileSystemModel()
        self.setModel(self.model)
        self.setIndentation(15)

        # Set home folder and file filters
        if not homeFolder:
            if os.path.isdir('/home/tiago'):
                #homeFolder = '/home/tiago/Code/py/NeuroDAQanalysis/testData/'
                self.homeFolder = '/home/tiago/Data/Lab.local/'
            elif platform.system() == 'Darwin':
                print 'Mac OS X detected'
                self.homeFolder = '/Users/'
            elif platform.system() == 'Linux':
                self.homeFolder = '/home/'
            else:
                self.homeFolder = '/'
        self.model.setRootPath(
            QtCore.QDir.absolutePath(QtCore.QDir(self.homeFolder)))
        self.setRootIndex(
            self.model.index(
                QtCore.QDir.absolutePath(QtCore.QDir(self.homeFolder))))
        self.model.setNameFilters(
            ['*.hdf5', '*.tdms', '*.abf', '*.avi', '*.mp4'])

        # Hide some default columns
        self.setColumnHidden(1, True)
        self.setColumnHidden(2, True)
        self.setColumnHidden(3, True)
Exemplo n.º 5
0
    def __init__(self):
        super(MenuManager, self).__init__()

        self.contentsDoc = None
        self.assistantProcess = QtCore.QProcess()
        self.helpRootUrl = ''
        self.docDir = QtCore.QDir()
        self.imgDir = QtCore.QDir()

        self.info = {}
        self.window = None
        self.qmlRoot = None
        self.declarativeEngine = None

        self.ticker = None
        self.tickerInAnim = None
        self.upButton = None
        self.downButton = None
        self.helpEngine = None
        self.score = Score()
        self.currentMenu = "[no menu visible]"
        self.currentCategory = "[no category visible]"
        self.currentMenuButtons = "[no menu buttons visible]"
        self.currentInfo = "[no info visible]"
        self.currentMenuCode = -1
        self.readXmlDocument()
        self.initHelpEngine()
    def load_core(self):
        """Loads all core extensions into the globals library and re-initialized the global config.
        
        This function bootstraps global library from the core library. It iterates through all extensions in the core library and populates the global config with any extensions it does not already contain and then loads them into the global config.

        """
        #Core extensions are loaded from the global directory.
        #If a core extension has been deleted from the global directory it will be replaced from the core directory.
        self.init_extension_config('core')
        _core_dir = QtCore.QDir(self.libraries['core'])
        _global_dir = QtCore.QDir(self.libraries['global'])
        _reload_globals = False
        for ext in self.extensions['core'].configs:
            try:
                #Check if the extension is in the globals
                global_extensions = list(self.extensions['global'].configs.keys())
                if ext['name'] in global_extensions:
                    self.log.debug(self.translate("logs", "Core extension {0} was found in the global extension list.".format(ext['name'])))
                    if not _global_dir.exists(ext['name']):
                        raise KeyError(self.translate("Extension {0} was found in the extension list, but it did not exist in the actual library. Loading it to global.".format(ext['name'])))
                    continue
            except KeyError:
                #If extension not loaded in globals it will raise a KeyError
                _core_ext_path = _core_dir.absoluteFilePath(ext['name'])
                _global_ext_path = _global_dir.absoluteFilePath(ext['name'])
                self.log.info(self.translate("logs", "Core extension {0} was missing from the global extension directory. Copying it into the global extension directory from the core now.".format(ext['name'])))
                #Copy extension into global directory
                if QtCore.QFile(_core_ext_path).copy(_global_ext_path):
                    self.log.debug(self.translate("logs", "Extension successfully copied."))
                else:
                    self.log.debug(self.translate("logs", "Extension was not copied."))
                _reload_globals = True
        if _reload_globals == True:
            self.init_extension_config("global")
Exemplo n.º 7
0
    def initHelpEngine(self):
        self.helpRootUrl = 'qthelp://com.trolltech.qt.%d%d%d/qdoc/' % (QtCore.QT_VERSION >> 16, (QtCore.QT_VERSION >> 8) & 0xff, QtCore.QT_VERSION & 0xff)

        # Store help collection file in cache dir of assistant.
        cacheDir = QtGui.QDesktopServices.storageLocation(QtGui.QDesktopServices.DataLocation) + '/Trolltech/Assistant/'
        helpDataFile = 'qtdemo_%s.qhc' % QtCore.QT_VERSION_STR

        dir = QtCore.QDir()
        if not dir.exists(cacheDir):
            dir.mkpath(cacheDir)

        # Create help engine (and new helpDataFile if it does not exist).
        self.helpEngine = QtHelp.QHelpEngineCore(cacheDir + helpDataFile)
        self.helpEngine.setupData()

        qtDocRoot = QtCore.QLibraryInfo.location(QtCore.QLibraryInfo.DocumentationPath) + '/qch'
        qtDocRoot = QtCore.QDir(qtDocRoot).absolutePath()

        qchFiles = ['/qt.qch', '/designer.qch', '/linguist.qch']

        oldDir = self.helpEngine.customValue('docDir', '')
        if oldDir != qtDocRoot:
            for qchFile in qchFiles:
                self.helpEngine.unregisterDocumentation(QtHelp.QHelpEngineCore.namespaceName(qtDocRoot + qchFile))

        # If the data that the engine will work on is not yet registered, do it
        # now.
        for qchFile in qchFiles:
            self.helpEngine.registerDocumentation(qtDocRoot + qchFile)

        self.helpEngine.setCustomValue('docDir', qtDocRoot)
Exemplo n.º 8
0
def getStyleSheet(name=None):
    """ Helper function to get the style sheet for the given name

	Args:
		name (str): Name of the stylesheet

	Raises:
		(ResourceNotFound): Raises if the style sheet is not available.

	Returns:
		(QString): Content of stylesheet files inside the directory.
	"""
    name = QtCore.QString(name or _guiCommon.defaultStyleSheet)

    if name not in availableStyleSheets():
        raise _exceptions.ResourceNotFound(
            "The given stylesheet(%s) is not available in resources." % name)

    styleSheetDirectory = QtCore.QDir(
        QtCore.QDir(_guiCommon.styleSheetRootDirectory).filePath(name))

    styleSheet = QtCore.QString()
    for fileInfo in styleSheetDirectory.entryInfoList():
        qssFilePath = fileInfo.absoluteFilePath()
        for fileType in _guiCommon.styleSheetsFileTypes:
            if qssFilePath.endsWith(fileType):
                qssFile = QtCore.QFile(qssFilePath)
                qssFile.open(QtCore.QIODevice.ReadOnly)
                if qssFile.isOpen():
                    styleSheet.append(
                        QtCore.QVariant(qssFile.readAll()).toString())
    return styleSheet
Exemplo n.º 9
0
    def run(self):
        #sound library load
        if self.source == 'personal':
            try:
                sound_list = self.load_library()
            except Exception as e:
                print e
                #                print 'personal library not found, reverting to default (factory 200802)'
                sound_list = self.load_midi(
                    local_path('presets/blofeld_fact_200802.mid'))
        else:
            sound_list = self.load_midi(self.source)
        self.library.addSoundBulk(sound_list)

        #wavetable library load
        path_txt = QtGui.QDesktopServices.storageLocation(
            QtGui.QDesktopServices.DataLocation) + '/wavetables/'
        wt_path = QtCore.QDir(path_txt)
        if not wt_path.exists():
            QtCore.QDir().mkpath(path_txt)
        else:
            self.wavetable_library.load_list(
                wt_path.entryInfoList(['*.syx'], sort=QtCore.QDir.Name))
#        print contents.join('\n')

        self.loaded.emit()
Exemplo n.º 10
0
    def del_session(self):
        if self.comboBox.currentText() != "Nouvelle session":
            directory = QtCore.QDir(QtCore.QDir.currentPath())
            directory.cdUp()
            directory.cd("apps\qgis\python\plugins\QDrone\sessions")
            popup = QtGui.QMessageBox()

            session_name = self.comboBox.currentText()

            for layer in QgsMapLayerRegistry.instance().mapLayers().values():
                if layer.name().find("flightPlan") != -1:
                    QgsMapLayerRegistry.instance().removeMapLayer(layer.id())

            del_files_dir = QtCore.QDir(directory)
            del_files_dir.cd(session_name)
            filesList = del_files_dir.entryList()
            for i in range(len(filesList)):
                del_files_dir.remove(filesList[i])

            if directory.rmdir(session_name):
                Str = "La session " + session_name.encode(
                    'utf-8') + " a été supprimée."
                popup.setText(Str.decode('utf-8'))
            else:
                popup.setText("Impossible de supprimer la session : " +
                              session_name + ".")
            self.refreshComboBox()
            self.objet_sessions.reject()
            popup.exec_()
Exemplo n.º 11
0
    def __init__(self, icon, parent=None):
        QtGui.QSystemTrayIcon.__init__(self, icon, parent)

        #test if VirtualDVD folder exists in home
        home = QtCore.QDir.homePath()
        v = home + "/VirtualDVD/"
        b = QtCore.QDir(v).exists()

        if b == False:
            #mkdir the folder
            d = QtCore.QDir().mkdir(v)
            if d == False:
                #raise error. Could not create folder
                m = "Could not create virtual dvd folder"
                msg = QtGui.QMessageBox.critical(self.parent(), "Error", m)
                raise Exception(m)

        #create the systray menu
        menu = QtGui.QMenu(parent)
        exitAction = menu.addAction(QtGui.QIcon(QtGui.QPixmap("exit.png")), "Exit")
        mountAction = menu.addAction(QtGui.QIcon(QtGui.QPixmap("mount.png")), "Mount Image...")
        umountAction = menu.addAction(QtGui.QIcon(QtGui.QPixmap("umount.png")), "Unmount Image...")

        self.setContextMenu(menu)
        QtCore.QObject.connect(exitAction, QtCore.SIGNAL('triggered()'), self.exit)
        QtCore.QObject.connect(mountAction, QtCore.SIGNAL('triggered()'), self.mount)
        QtCore.QObject.connect(umountAction, QtCore.SIGNAL('triggered()'), self.umount)
    def walk_dir(self, dir_path, parentNode):
        ## Grab the children of the path
        files = dir_path.entryInfoList(QtCore.QDir.AllEntries
                                       | QtCore.QDir.NoDotAndDotDot)
        ## The mode of the tree.
        isList = (self.toolButtonGroup.checkedId() == 1)
        ## Recurse through the files
        for child in files:
            if child.isDir():
                # Add the child directory and scan it
                if isList:
                    self.walk_dir(QtCore.QDir(child.absoluteFilePath()),
                                  parentNode)
                else:
                    treeItem = QtGui.QTreeWidgetItem(parentNode)
                    treeItem.setText(0, child.fileName())
                    treeItem.setIcon(0, Icon(Ico.Folder))
                    self.walk_dir(QtCore.QDir(child.absoluteFilePath()),
                                  treeItem)

            else:
                # Add it as a file
                if child.suffix() == 'pde':
                    treeItem = QtGui.QTreeWidgetItem(parentNode)
                    treeItem.setText(0, child.fileName())
                    treeItem.setData(0, QtCore.Qt.UserRole, child.filePath())
                    treeItem.setIcon(0, Icon(Ico.Project))
    def set_library_defaults(self):
        """Sets the default directories for core, user, and global extensions.
        
        OS Defaults:
        
          OSX:
            user: $HOME/Library/Commotion/extension_data/
            global: /Library/Application Support /Commotion/extension_data/
        
          Windows:
            user: %APPDATA%\\Local\\Commotion\\extension_data\\.
            global: %COMMON_APPDATA%\\Local\\Commotion\extension_data\\.
            The %APPDATA% path is usually C:\\Documents and Settings\\User Name\\Application Data; the %COMMON_APPDATA% path is usually C:\\Documents and Settings\\All Users\\Application Data.
        
          Linux:
            user: $HOME/.Commotion/extension_data/
            global: /usr/share/Commotion/extension_data/
        
        Raises:
          IOError: If the application does not have permission to create ANY of the extension directories.
        """
        #==== Core ====#
        _app_path = QtCore.QDir(QtCore.QCoreApplication.applicationDirPath())
        _app_path.cd("extensions")
        _app_path.cd("core")
        #set the core extension directory
        self.libraries['core'] = _app_path.absolutePath()
        self.log.debug(self.translate("logs", "Core extension directory succesfully set."))

        #==== SYSTEM DEFAULTS =====#
        self.log.debug(self.translate("logs", "Setting the default extension directory defaults."))
        platform = sys.platform
        #Default global and user extension directories per platform.
        #win23, darwin, and linux supported.
        platform_dirs = {
            'darwin': {
                'user' : os.path.join("Library", "Commotion", "extension_data"),
                'user_root': QtCore.QDir.home(),
                'global' : os.path.join("Library", "Application Support", "Commotion", "extension_data"),
                'global_root' : QtCore.QDir.root()},
            'win32' : {
                'user':os.path.join("Local", "Commotion", "extension_data"),
                'user_root': QtCore.QDir(os.getenv('APPDATA')),
                'global':os.path.join("Local", "Commotion", "extension_data"),
                'global_root' : QtCore.QDir(os.getenv('COMMON_APPDATA'))},
            'linux': {
                'user':os.path.join(".Commotion", "extension_data"),
                'user_root': QtCore.QDir.home(),
                'global':os.path.join("extensions", "global"),
                'global_root' : QtCore.QDir(QtCore.QCoreApplication.applicationDirPath())}}
        for path_type in ['user', 'global']:
            ext_dir = platform_dirs[platform][path_type+'_root']
            ext_path = platform_dirs[platform][path_type]
            self.log.debug(self.translate("logs", "The root directory of {0} is {1}.".format(path_type, ext_dir.path())))
            #move the root directory to the correct sub-path.
            lib_path = ext_dir.filePath(ext_path)
            self.log.debug(self.translate("logs", "The extension directory has been set to {0}..".format(lib_path)))
            #Set the extension directory.
            self.libraries[path_type] = lib_path
Exemplo n.º 14
0
    def setup(self):
        self.initHelpEngine()

        self.documentationDir = QtCore.QDir(
            QtCore.QLibraryInfo.location(
                QtCore.QLibraryInfo.DocumentationPath))

        self.imagesDir = QtCore.QDir(self.documentationDir)

        if self.documentationDir.cd("html") and self.documentationDir.cd(
                "images"):
            self.imagesDir.setPath(self.documentationDir.path())
            self.documentationDir.cdUp()
        else:
            QtGui.QMessageBox.warning(
                self, self.tr("No Documentation Found"),
                self.tr("I could not find the Qt documentation."))

        self.maximumLabels = 0

        self.demosDir = QtCore.QDir("./../../demos")
        demoCategories = self.readInfo(":/demos.xml", self.demosDir)

        self.examplesDir = QtCore.QDir("./../../")
        exampleCategories = self.readInfo(":/examples.xml", self.examplesDir)

        if demoCategories + exampleCategories <= 0:
            QtGui.QMessageBox.warning(self, self.tr("No Examples or Demos found"),
                                        self.tr("I could not find any PyQt examples or demos.\n"\
                                                "Please ensure that PyQt is installed correctly."),
                                        QtGui.QMessageBox.Cancel, QtGui.QMessageBox.NoButton)
            return False

        self.maximumLabels = max(demoCategories + exampleCategories,
                                 self.maximumLabels)

        for category in self.categories:
            self.maximumLabels = max(
                len(self.categories[category]['examples']) + 1,
                self.maximumLabels)

        mainDescription = self.categories['[main]']['description']
        if len(mainDescription) > 0:
            mainDescription += self.tr("\n")

        self.categories['[main]']['description'] = mainDescription + self.tr(
            "<p>Press <b>Escape</b>, <b>Backspace</b>, or <b>%1</b> to "
            "return to a previous menu.</p>"
            "<p>Press <b>%2</b> to switch between normal and full screen "
            "modes.</p>"
            "<p>Use <b>%3</b> to exit the launcher.</p>") \
                .arg(QtCore.QString(QtGui.QKeySequence(self.tr("Alt+Left")))) \
                .arg(QtCore.QString(QtGui.QKeySequence(self.tr("Ctrl+F")))) \
                .arg(QtCore.QString(QtGui.QKeySequence(self.tr("Ctrl+Q"))))

        self.showPage.emit()

        return True
Exemplo n.º 15
0
    def add_animal(self, folderName, animalPathLocal):
        query = QtSql.QSqlQuery(self.db)
        animalPathBackUP = QtCore.QDir(self.backUPPath).filePath(folderName)
        if not QtCore.QDir(animalPathBackUP).exists():
            animalPathBackUP = "unknown"

        sqlAdd = ("INSERT INTO Animal"
                  "(animalID,pathLocal,pathBackUP)"
                  "VALUES (:animalID, :pathLocal, :pathBackUP)")
        query.prepare(sqlAdd)
        query.bindValue(":animalID", folderName)
        query.bindValue(":pathLocal", animalPathLocal)
        query.bindValue(":pathBackUP", animalPathBackUP)
        query.exec_()
Exemplo n.º 16
0
 def set_logfile(self, logfile=None):
     """Set the file to log to.
     
     Args:
     logfile (string): The absolute path to the file to log to.
       optional: defaults to the default system logfile path.
     """
     if logfile:
         log_dir = QtCore.QDir(os.path.dirname(logfile))
         if not log_dir.exists():
             if log_dir.mkpath(log_dir.absolutePath()):
                 self.logfile = logfile
     platform = sys.platform
     if platform == 'darwin':
         #Try <user>/Library/Logs first
         log_dir = QtCore.QDir(os.path.join(QtCore.QDir.homePath(), "Library", "Logs"))
         #if it does not exist try and create it
         if not log_dir.exists():
             if not log_dir.mkpath(log_dir.absolutePath()):
                 raise NotADirectoryError("Attempted to set logging to the user's Commotion directory. The directory '<home>/.Commotion' does not exist and could not be created.")
         self.logfile = log_dir.filePath("commotion.log")
     elif platform in ['win32', 'cygwin']:
         #Try ../AppData/Local/Commotion first
         log_dir = QtCore.QDir(os.path.join(os.getenv('APPDATA'), "Local", "Commotion"))
         #if it does not exist try and create it
         if not log_dir.exists():
             if not log_dir.mkpath(log_dir.absolutePath()):
                 raise NotADirectoryError("Attempted to set logging to the user's Commotion directory. The directory '<home>/.Commotion' does not exist and could not be created.")
         self.logfile = log_dir.filePath("commotion.log")
     elif platform == 'linux':
         #Try /var/logs/
         log_dir = QtCore.QDir("/var/logs/")
         if not log_dir.exists(): #Seriously! What kind of twisted linux system is this?
             if log_dir.mkpath(log_dir.absolutePath()):
                 self.logfile = log_dir.filePath("commotion.log")
             else:
                 #If fail then just write logs in home directory
                 #TODO check if this is appropriate... its not.
                 home = QtCore.QDir.home()
                 if not home.exists(".Commotion") and not home.mkdir(".Commotion"):
                     raise NotADirectoryError("Attempted to set logging to the user's Commotion directory. The directory '{0}/.Commotion' does not exist and could not be created.".format(home.absolutePath()))
                 else:
                     home.cd(".Commotion")
                     self.logfile = home.filePath("commotion.log")
         else:
             self.logfile = log_dir.filePath("commotion.log")
     else:
         #I'm out!
         raise OSError("Could not create a logfile.")
Exemplo n.º 17
0
    def restoreCurrentProfile(self):
        """
        Restore the values for the current profile from a pickled object
        :return:
        """
        self.debug("Tying to restore current profile information")
        d = QtCore.QDir(config.PROFILES[PROFILE_DIRSAVEDPROFILES])

        # setting filter
        filter = self.PROFILE_PICKLE_NAME_FILTER.format(config.PROFILES[PROFILE_START][PROFILE_NICKNAME])
        d.setNameFilters([filter])

        # setting sorting
        d.setSorting(QtCore.QDir.Time)

        elist = d.entryInfoList()

        # keep certain numbe rof configurations intact
        if len(elist)>self.PROFILES_MAX_NUMBER:
            prof2del = elist[-len(elist)+self.PROFILES_MAX_NUMBER-1:]

            for prof in prof2del:
                self.debug("Too many profiles, removing some ({})".format(prof.absoluteFilePath()))
                d.remove(prof.absoluteFilePath())

        # loading the latest profile info
        if len(elist)>0:
            self.restoreProfile(elist[0])
Exemplo n.º 18
0
    def updateWorkDir(self):
        for i in reversed(range(self.gridLayout.count())):
            self.gridLayout.itemAt(i).widget().setParent(None)
        self.selectedImage = ""
        self.selectedImageDir = ""

        #self.selectDirButton.setText(unicode(QtCore.QDir(self.workDir).dirName()))
        folderIterator = QtCore.QDirIterator(
            self.workDir, QtCore.QDir.Dirs | QtCore.QDir.NoDotAndDotDot)
        self.checkAllBox = QtGui.QCheckBox('Check/Uncheck All', self)
        self.checkAllBox.setChecked(True)
        self.checkAllBox.stateChanged.connect(lambda: (self.checkAll(
        ) if self.checkAllBox.isChecked() else self.unCheckAll()))
        self.gridLayout.addWidget(self.checkAllBox)
        self.folderWidgets = []
        i = 0
        while folderIterator.hasNext():

            tempDir = QtCore.QDir(folderIterator.next())

            self.folderWidgets.append(imageFolderWidget(tempDir))
            self.gridLayout.addWidget(self.folderWidgets[-1])
            self.folderWidgets[-1].signal_hideall.connect(
                self.hideAllImageLabels)
            self.folderWidgets[-1].signal_show_image.connect(
                lambda key=i: self.updateImage(key))
            self.folderWidgets[-1].signal_show_images.connect(
                lambda key=i: self.updateImages(key))
            i += 1
        try:
            self.updateImages(0)
        except IndexError:
            self.signal_update_images.emit()
Exemplo n.º 19
0
 def delete(self, uid):
     uid_item = self.model.findItems(uid, QtCore.Qt.MatchExactly, 4)[0]
     row = uid_item.row()
     file_info = self.model.item(row, 3).data().toPyObject()
     QtCore.QDir().remove(file_info.absoluteFilePath())
     self.model.takeRow(uid_item.row())
     self.wavetable_data.pop(str(uid))
Exemplo n.º 20
0
 def directory_handling(self):
     # 读取成功记录
     self.success_record = self.success_handler.readFile()
     # 得到新的文件列表
     new_file_list = self.update_file_list()
     # 处理用户在当前目录下更改文件名的行为
     for my_file in self.model.ListItem:
         file_dir = QtCore.QDir()
         if not file_dir.exists(my_file.path):
             # print my_file
             self.deleting(my_file.path)
     # 更新View里的列表
     for my_file in new_file_list:
         # 未曾传输的文件
         if my_file not in self.success_record:
             # 且这是第一次操作或该文件是新加入到当前路径中来的
             if my_file not in self.curr_file_list or self.first_time:
                 self.adding(my_file)
                 self.should_sync = True
                 # print unicode(my_file, encoding="UTF-8")
     if self.should_sync:
         # 发射自动同步信号
         self.emit(QtCore.SIGNAL("auto_sync_should_start"))
     # 更新当前列表(即文件记录)
     self.curr_file_list = new_file_list
Exemplo n.º 21
0
 def __init__(self):
     super(LoginView, self).__init__()
     self.ui = Ui_Dialog()
     self.ui.setupUi(self)
     self.setFixedSize(self.width(), self.height())
     # 初始化用户信息
     self.app_id = ""
     self.secret_id = ""
     self.secret_key = ""
     self.bucket = ""
     self.working_directory = ""
     self.dir = QtCore.QDir()
     self.up_agent = Uploader()
     # 链接按钮信号
     self.ui.confirm_button.clicked.connect(self.login_check)
     self.ui.cancel_button.clicked.connect(self.close)
     self.ui.file_button.clicked.connect(self.open_file_nav)
     # 增加返回码exception
     self.execption_table = ['-1899', '-1893']
     self.ui.message_label.setStyleSheet("QLabel { color : red; }")
     # 初始化两个读写器
     self.config_ini = QtCore.QSettings("../main/pref.ini",
                                        QtCore.QSettings.IniFormat)
     self.info_ini = QtCore.QSettings("../main/userinfo.ini",
                                      QtCore.QSettings.IniFormat)
Exemplo n.º 22
0
    def download(self, file_name, url, isPackage=False):
        try:
            u = urllib2.urlopen(url)
        except:
            self.errorMessage("Hata",
                              u"İnternet bağlantınızı kontrol ediniz !")
            return
        if (isPackage):
            workingDir = QtCore.QDir(self.ui.le_path.text())
            f = open(workingDir.absolutePath() + "/packages/" + file_name,
                     'wb')
        else:
            f = open(file_name, 'wb')
        meta = u.info()
        file_size = int(meta.getheaders("Content-Length")[0])
        print "Downloading: %s Bytes: %s" % (file_name, file_size)

        file_size_dl = 0
        block_sz = 8192
        while True:
            QtGui.QApplication.processEvents()
            buffer = u.read(block_sz)
            if not buffer:
                break

            file_size_dl += len(buffer)
            f.write(buffer)
            status = r"%10d  [%3.2f%%]" % (file_size_dl,
                                           file_size_dl * 100. / file_size)
            #status = status + chr(8)*(len(status)+1)
            #print status,
            self.ui.lbl_progress.setText(status)
        f.close()
	def save_screenshot(self):
		initialPath = QtCore.QDir().currentPath() + "/.png"

		file = QtGui.QFileDialog().getSaveFileName(self, "Save as", initialPath,
				"%s Files (*.%s);;All Files (*)" % ('png'.upper(), 'png'))
		if file:
			self.pixmap.save(file, 'png')
Exemplo n.º 24
0
    def walk_dir(self, dir_path, parentNode):
        dir_path = QtCore.QDir(dir_path)
        info_list = dir_path.entryInfoList(QtCore.QDir.AllEntries
                                           | QtCore.QDir.NoDotAndDotDot)

        isList = self.toolButtonGroup.checkedId() == 1

        for fileInfo in info_list:
            if fileInfo.isDir():

                if isList:
                    self.walk_dir(fileInfo.filePath(), parentNode)
                else:
                    treeItem = QtGui.QTreeWidgetItem(parentNode)
                    treeItem.setText(
                        0, fileInfo.fileName())  ## hack to remove .html
                    treeItem.setIcon(0, Icon(Ico.Folder))
                    self.walk_dir(fileInfo.filePath(), treeItem)
            #self.tree.addTopLevelItem(treeItem)
            #self.tree.setItemExpanded(treeItem, True)
            #return
            else:
                #print "pde" , fileInfo.filePath()
                if fileInfo.suffix() == 'pde':
                    treeItem = QtGui.QTreeWidgetItem(parentNode)
                    treeItem.setText(
                        0, fileInfo.fileName())  ## hack to remove .html
                    treeItem.setData(0, QtCore.Qt.UserRole,
                                     fileInfo.filePath())
                    treeItem.setIcon(0, Icon(Ico.Sketch))
Exemplo n.º 25
0
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)

        mainLayout = QtGui.QHBoxLayout()
        mainLayout.setMargin(0)
        self.setLayout(mainLayout)

        self.destinationLine = QtGui.QLineEdit()
        self.destinationLine.textChanged.connect(self.textChanged.emit)
        mainLayout.addWidget(self.destinationLine)

        homePath = QtCore.QDir().homePath()

        # Todo: Workspace must unpack to the platform specific home
        # directory by default
        if sys.platform == 'win32':
            path = os.path.join(homePath, "My Documents", "PcodeProjects")
        elif sys.platform == 'darwin':
            path = os.path.join(homePath, "Documents", "PcodeProjects")
        else:
            path = os.path.join(homePath, "My Documents", "PcodeProjects")
        path = os.path.normpath(path)
        self.destinationLine.setText(path)

        self.browseButton = QtGui.QPushButton('...')
        self.browseButton.clicked.connect(self.browsePath)
        mainLayout.addWidget(self.browseButton)
Exemplo n.º 26
0
 def setDirPath(self, path):
     dir = QtCore.QDir(path)
     stringList = ['*.xlsx']
     dir.setNameFilters(stringList)
     self.fileList = list(dir.entryList())
     self.fileCount = 0
     self.reset()
Exemplo n.º 27
0
    def on_loadDataButton_clicked(self):
        print "on_pushButton_clicked"
        
        path, ok = QtGui.QInputDialog.getText(self.ui, 'Input Dialog', 'Enter path of data set:', QtGui.QLineEdit.Normal, r'D:\_uchar\vortex')
        if ok:
            print path
        
        self.path = str(path)

        dir = QtCore.QDir(path)
        files = dir.entryList(['*.mhd'], QtCore.QDir.Files | QtCore.QDir.NoSymLinks)
   
        file_list = map(str, files)
        print len(file_list)
        print file_list
        
        list1 = []
        for filename in file_list:
            # Create an item with a caption
            item = QtGui.QStandardItem(filename)
            list1.append(item)
        
        self.model = QtGui.QStandardItemModel()
        self.model.clear()
        self.model.appendColumn(list1)
        self.ui.listView.setModel(self.model)
Exemplo n.º 28
0
 def load_functions(self):
     self.tree = {}
     self.functions = []
     root_path = settings.api_define_path()
     rootDir = QtCore.QDir(root_path)
     self.tree = {}
     self.walk_dir(rootDir, '/')
Exemplo n.º 29
0
    def getSettings():
        # Next step add all informations
        #See __init__.initGui
        #keys = ['path', 'planet', 'rapideye', 'landsat8', 'sentinel2', 'date1', 'date2']

        keys = ['path']
        values = {}
        for k in keys:
            values[k] = "{0}/{1}".format(DialogImageSettingPL.localSetting, k)
        data = None
        s = QtCore.QSettings()
        path = s.value(values['path'], None)
        if not path is None:
            # Next step add all informations
            # planet = s.value( values['planet'], None )
            # planet = True if planet == "true" else False
            # rapideye = s.value( values['rapideye'], None )
            # rapideye = True if rapideye == "true" else False
            # ...
            # if QtCore.QDir( path ).exists():
            #   data = { 'isOk': True, 'path': path, 'planet': planet, 'rapideye': rapideye,... }

            if QtCore.QDir(path).exists():
                data = {'isOk': True, 'path': path}
            else:
                data = {'isOk': False, 'has_path': True, 'path': path}
                s.remove(values['path'])
        else:
            data = {'isOk': False, 'has_path': False}

        return data
Exemplo n.º 30
0
 def load_skins(self):
     deck_skins_path = QtCore.QDir("skins:/")
     for i in self.get_bases("skins"):
         if deck_skins_path.exists("skins:/{}/deck.ini".format(i)):
             skin_info=QtCore.QSettings("skins:/{}/deck.ini".format(i), \
                QtCore.QSettings.IniFormat)
             skin_info.beginGroup("Deck Skin")
             for_deck = skin_info.value("definition", "")
             if for_deck:
                 if for_deck in self.deck_defs:
                     if self.deck_defs[for_deck]['definition'].conforms(i):
                         self.deck_defs[for_deck]['skins'].append(str(i))
                         #copy metadata
                     else:
                         print(("Deck definition {for_deck}"
                                " is not compatible with {i}"
                                ", skipping {i}...").format(**locals()))
                 else:
                     print(("Deck definition {for_deck} is not installed"
                            ", skipping {i}...").format(**locals()))
             else:
                 print(("Cannot confirm which deck definitions"
                        " {i} is compatible with, skipping...").format(i=i))
             skin_info.endGroup()
         else:
             print(("Cannot confirm which deck definitions"
                    " {i} is compatible with, skipping...").format(i=i))