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.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 initHelpEngine(self): self.helpRootUrl = 'qthelp://com.trolltech.qt.%d%d%d/qdoc/' % QtCore.__version_info__ # Store help collection file in cache dir of assistant. cacheDir = QtGui.QDesktopServices.storageLocation(QtGui.QDesktopServices.DataLocation) + '/Trolltech/Assistant/' helpDataFile = 'qtdemo_%s.qhc' % QtCore.__version__ 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)
def initHelpEngine(self): self.helpRootUrl = QtCore.QString("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 the help engine (and a 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", QtCore.QVariant(QtCore.QString())).toString() 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", QtCore.QVariant(qtDocRoot))
def init_app_data_dir(): data_dir_path = '%s/%s' % (USER_APPDATA_DIR, APP_NAME) dir = QtCore.QDir(data_dir_path) if not dir.exists(data_dir_path): roaming_dir = QtCore.QDir(USER_APPDATA_DIR) if not roaming_dir.mkdir(APP_NAME): LOGGER.critical( 'Unable to access or create application data location: %s' % data_dir_path) raise AppDataDirReadWriteFailed
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.emit(QtCore.SIGNAL("showPage()")) return True
def create_temp_dir(): server, job, root = get_favourite_parent_paths() path = u'{}/{}/{}/.bookmark'.format(server, job, root) _dir = QtCore.QDir(path) if _dir.exists(): return _dir.mkpath(u'.')
def setDirPath(self, path): dir = QtCore.QDir(path) self.beginResetModel() self.fileList = list(dir.entryList()) self.fileCount = 0 self.endResetModel()
def filename_button_clicked(self): """Used to reveal the parent folder in the file explorer. """ if self._file is not None: actions.reveal(self._file) return if not self.parent_folder(): return _dir = QtCore.QDir(self.parent_folder()) if not _dir.exists(): mbox = QtWidgets.QMessageBox(parent=self) mbox.setWindowTitle('Folder does not yet exist') mbox.setIcon(QtWidgets.QMessageBox.Warning) mbox.setText('Destination folder does not exist.') mbox.setInformativeText( 'The destination folder does not yet exist. Do you want to create ' 'it now?') button = mbox.addButton('Create folder', QtWidgets.QMessageBox.AcceptRole) mbox.setDefaultButton(button) mbox.addButton('Cancel', QtWidgets.QMessageBox.RejectRole) if mbox.exec_() == QtWidgets.QMessageBox.RejectRole: return if not _dir.mkpath('.'): ui.ErrorBox('Could not create destination folder.').open() return actions.reveal(_dir.path())
def create_file(self): """Creates a new file on the disk. """ if not self._create_file: return if not self.parent_folder(): raise RuntimeError('Invalid parent folder') _dir = self.parent_folder() name = self.name() if not name or not _dir or '{invalid_token}' in name: raise RuntimeError('Invalid token in output name') _dir = QtCore.QDir(_dir) if not _dir.mkpath('.'): raise RuntimeError('Could name create folder.') file_info = QtCore.QFileInfo(self.db_source()) if file_info.exists(): raise RuntimeError( '{} already exists. Try incrementing the version number.'. format(name)) path = file_info.absoluteFilePath() open(os.path.normpath(path), 'a').close() self.itemCreated.emit(path)
def add_location_toggles_menu(self, menu_set): """Adds the menu needed to change context""" taskfolder_pixmap = images.ImageCache.get_rsc_pixmap( u'folder', common.SECONDARY_TEXT, common.MARGIN()) item_on_pixmap = images.ImageCache.get_rsc_pixmap( u'check', common.SECONDARY_TEXT, common.MARGIN()) item_off_pixmap = QtGui.QPixmap() key = u'Change task folder' menu_set[key] = collections.OrderedDict() menu_set[u'{}:icon'.format(key)] = taskfolder_pixmap model = self.parent().model().sourceModel() parent_item = model.parent_path if not parent_item: return menu_set if not all(parent_item): return menu_set dir_ = QtCore.QDir(u'/'.join(parent_item)) dir_.setFilter(QtCore.QDir.Dirs | QtCore.QDir.NoDotAndDotDot) for entry in sorted(dir_.entryList()): task_folder = model.task_folder() if task_folder: checked = task_folder.lower() == entry.lower() else: checked = False menu_set[key][entry] = { u'text': entry.title(), u'icon': item_on_pixmap if checked else item_off_pixmap, u'action': functools.partial(model.taskFolderChanged.emit, entry) } return menu_set
def setUpClass(cls): import uuid from PySide2 import QtCore, QtWidgets import bookmarks.common as common import bookmarks.settings as settings import bookmarks.standalone as standalone common.PRODUCT = u'bookmarks_unittest' settings.local_settings.deleteLater() settings.local_settings = settings.LocalSettings() settings.local_settings.setValue(u'servers', None) # Add mock server dir tempdir = QtCore.QStandardPaths.writableLocation( QtCore.QStandardPaths.TempLocation) cls.server = tempdir # Mock job dir _id = uuid.uuid4() cls.job = u'testroot_{id}'.format(id=_id) cls.root_dir = u'{tempdir}/testroot_{id}'.format( tempdir=tempdir, id=_id) _dir = QtCore.QDir(cls.root_dir) _dir.mkpath(u'.') for bookmark in cls.bookmarks: _dir.mkpath(u'./{}'.format(bookmark)) if not QtWidgets.QApplication.instance(): cls.app = standalone.StandaloneApp([]) else: cls.app = QtWidgets.QApplication.instance()
def get_template_folder(mode): """Returns the path where the ZIP template files are stored, associated with the given `mode`. Args: mode (str): A template mode, eg. `JobTemplateMode`. Returns: str: Path to the folder where the template zip files are stored. """ common.check_type(mode, str) data_location = QtCore.QStandardPaths.writableLocation( QtCore.QStandardPaths.GenericDataLocation ) path = TEMPLATES_DIR.format( root=data_location, product=common.product, mode=mode ) _dir = QtCore.QDir(path) if _dir.exists(): return path if not _dir.mkpath('.'): raise OSError('Failed to create template directory.') return path
def setUpClass(cls): from PySide2 import QtCore super(TestAddFileWidget, cls).setUpClass() _dir = QtCore.QDir(cls.root_dir) for bookmark in cls.bookmarks: _dir.mkpath(u'./{}'.format(bookmark)) _dir.mkpath(u'./{}/asset_a'.format(bookmark)) _dir.mkpath(u'./{}/taskdir_a'.format(bookmark))
def findQmFiles(self): trans_dir = QtCore.QDir("./translations") fileNames = trans_dir.entryList(["*.qm"], QtCore.QDir.Files, QtCore.QDir.Name) fileNames = [trans_dir.filePath(p) for p in fileNames] return fileNames
def add_children(self, parent_item, dir_path): directory = QtCore.QDir(dir_path) files_in_directory = directory.entryList( QtCore.QDir.NoDotAndDotDot | QtCore.QDir.AllEntries, QtCore.QDir.DirsFirst | QtCore.QDir.IgnoreCase) for file_name in files_in_directory: self.add_child(parent_item, dir_path, file_name)
def open() -> QtWidgets.QMainWindow: loader = QUiLoader() loader.setWorkingDirectory(QtCore.QDir(str(cfg.root_dir))) ui_file = QtCore.QFile(str(cfg.root_dir / "ui" / "MainWindow.ui")) ui_file.open(QtCore.QFile.ReadOnly) widget = loader.load(ui_file) widget.setWindowFlags(QtCore.Qt.Window) ui_file.close() return widget
def guiBrowseForLocalImagesFolder(self): if self.continuouslyUpdating: print('SemImageViewer: stop the continuous updating first.') return path = QtWidgets.QFileDialog.getExistingDirectory() if path: self._localImages = QtCore.QDir(path).entryList(['*.tif']) self._localImagesIndex = 0 self.localImagesFolder = path
def export_favourites(): """Saves all favourites including the descriptions and the thumbnails.""" try: import uuid from . import settings from . import images from . import bookmark_db res = QtWidgets.QFileDialog.getSaveFileName( caption=u'Select where to save your favourites', filter=u'*.favourites', dir=QtCore.QStandardPaths.writableLocation( QtCore.QStandardPaths.HomeLocation), ) destination, _ = res if not destination: return favourites = settings.local_settings.favourites() server, job, root = get_favourite_parent_paths() db = bookmark_db.get_db(server, job, root) zip_path = u'{}/{}/{}/{}.zip'.format(server, job, root, uuid.uuid4()) # Make sure the temp folder exists QtCore.QFileInfo(zip_path).dir().mkpath(u'.') with zipfile.ZipFile(zip_path, 'a') as z: # Adding thumbnail to zip for favourite in favourites: thumbnail_path = images.get_thumbnail_path( server, job, root, favourite) file_info = QtCore.QFileInfo(thumbnail_path) if not file_info.exists(): continue z.write(file_info.filePath(), file_info.fileName()) z.writestr(u'favourites', u'\n'.join(favourites)) file_info = QtCore.QFileInfo(zip_path) if not file_info.exists(): raise RuntimeError( u'Unexpected error occured: could not find the favourites file' ) QtCore.QDir().rename(file_info.filePath(), destination) if not QtCore.QFileInfo(destination).exists(): raise RuntimeError( u'Unexpected error occured: could not find the favourites file' ) reveal(destination) except Exception as e: from . import log from . import common_ui common_ui.ErrorBox(u'Could not save the favourites.', u'{}'.format(e)).open() log.error(u'Exporting favourites failed.') raise
def convert(self): srcDir = self.srcComboBox.currentText() destDir = self.destComboBox.currentText() self.currentDir = QtCore.QDir(srcDir) fileName = "*.wac" files = self.currentDir.entryList([fileName], QtCore.QDir.Files | QtCore.QDir.NoSymLinks) self.showFiles(files)
def add_children(self, parent_item, dir_path): directory = QtCore.QDir(dir_path) nodots = QtCore.QDir.NoDotAndDotDot AllEntries = QtCore.QDir.AllEntries DirsFirst = QtCore.QDir.DirsFirst IgnoreCase = QtCore.QDir.IgnoreCase files = directory.entryList(nodots | AllEntries, DirsFirst | IgnoreCase) for fileName in files: self.add_child(parent_item, dir_path, fileName)
def customEvent(self, event): """ Handle the custom events. Namely, if the directory is changed. """ if event.type() == EventTypes.DirectoryChange: # If the directory change event was accepted, then by all means change the directory. index = event.proxyIndex sourceIndex = event.sourceIndex self.proxyView.setRootIndex(index) self.address.path = QtCore.QDir( self.sourceModel.filePath(sourceIndex)) self.directoryChanged.emit(self.sourceModel.filePath(sourceIndex))
def find(self): self.filesTable.setRowCount(0) path = self.directoryComboBox.currentText() self.updateComboBox(self.directoryComboBox) self.currentDir = QtCore.QDir(path) fileName = "*.dcm" files = self.currentDir.entryList([fileName], QtCore.QDir.Files | QtCore.QDir.NoSymLinks) self.showFiles(files)
def save_copy(self): fd = QtWidgets.QFileDialog() fd.setDirectory(QtCore.QDir('~/')) savefn = fd.getSaveFileName(self, 'Save File')[0] pixmap = self.original_snap barray = QtCore.QByteArray() qbuffer = QtCore.QBuffer(barray) qbuffer.open(QtCore.QIODevice.WriteOnly) pixmap.save(qbuffer, "PNG") bytesio = BytesIO(barray.data()) bytesio.seek(0) with open(savefn, 'wb') as savefile: savefile.write(bytesio.read())
def tearDownClass(cls): from PySide2 import QtCore import bookmarks.settings as settings # Remove local settings file s = settings.local_settings.fileName() f = QtCore.QFileInfo(s) if f.exists(): f.dir().removeRecursively() # Remove temp directory _dir = QtCore.QDir(cls.root_dir) if _dir.exists(): _dir.removeRecursively()
def find(self): self.filesTable.setRowCount(0) fileName = self.fileComboBox.currentText() text = self.textComboBox.currentText() path = self.directoryComboBox.currentText() self.updateComboBox(self.fileComboBox) self.updateComboBox(self.textComboBox) self.updateComboBox(self.directoryComboBox) self.currentDir = QtCore.QDir(path) if not fileName: fileName = "*" files = self.currentDir.entryList([fileName], QtCore.QDir.Files | QtCore.QDir.NoSymLinks) if text: files = self.findFiles(files, text) self.showFiles(files)
def get_icon(self, index): """Downloads and sets the icon for the given index.""" if not index.isValid(): return try: url = index.data(ThumbnailUrlRole) response = urllib.request.urlopen(url) except Exception as e: log.error('Could not save thumbnail') return # Cache directory cache_dir_path = QtCore.QStandardPaths.writableLocation( QtCore.QStandardPaths.GenericDataLocation) cache_dir_path = '{}/{}/slack'.format(cache_dir_path, common.product) cache_file_path = '{}/{}.png'.format(cache_dir_path, index.data(ThumbnailHashRole)) # Let's check if the thumbnail has already been cached and if not, download it. if not QtCore.QFileInfo(cache_file_path).exists(): QtCore.QDir(cache_dir_path).mkpath('.') with open(cache_file_path, 'wb') as f: f.write(response.read()) image = images.oiio_get_qimage(cache_file_path) if not image: return if image.isNull(): return if image.isNull(): return icon = QtGui.QIcon() pixmap = QtGui.QPixmap.fromImage(image) icon.addPixmap(pixmap, QtGui.QIcon.Normal) icon.addPixmap(pixmap, QtGui.QIcon.Active) self.setData(index, icon, role=QtCore.Qt.DecorationRole)
def __init__(self, controller, hash, parent=None): super(CommitView, self).__init__(parent) self.setupUi(self) self.controller = controller self.hash = hash commit = controller.getCommit(hash) self.txtHash.setText(hash) self.txtAuthor.setText(commit.author) self.txtDate.setText( QtCore.QDateTime.fromTime_t(int( commit.timestamp)).toString("dd.MM.yyyy hh:mm")) self.txtDescription.setText(commit.description) self.lblLinesAdded.setText(commit.addedLines) if commit.deletedLines != '': self.lblLinesDeleted.setText(commit.deletedLines) else: self.lblLinesDeleted.setText("0") filesModel = QtWidgets.QFileSystemModel() filesModel.setRootPath(controller.project.getPath()) dir = QtCore.QDir() nameFilters = [ x.strip().split(os.sep)[-1] for x in self.controller.getDiff(hash) ] if nameFilters == []: dir.setNameFilters([""]) else: dir.setNameFilters(nameFilters) filesModel.setNameFilters(dir.nameFilters()) print(dir.nameFilters()) filesModel.setNameFilterDisables(False) self.treeFiles.setModel(filesModel) self.treeFiles.setRootIndex( filesModel.index(controller.project.getPath())) for i in range(1, 4): self.treeFiles.hideColumn(i) self.treeFiles.activated.connect(self.fileDiff)
def done(self, result): if result == QtWidgets.QDialog.Rejected: return super(base.BasePropertyEditor, self).done(result) # pylint: disable=E1003 if not self.name_editor.text(): raise ValueError('Must enter a name to create a job.') root = self.server name = self.name_editor.text() if not name: raise ValueError('Must enter a name to create job') name = name.replace('\\', '/') if '/' in name: _name = name.split('/')[-1] _root = name[:-len(_name) - 1] name = _name root = f'{self.server}/{_root}' if not QtCore.QFileInfo(root).exists(): if not QtCore.QDir(root).mkpath('.'): raise RuntimeError('Error creating folders.') # Create template and signal self.template_editor.template_list_widget.create(name, root) path = f'{root}/{name}' if not QtCore.QFileInfo(path).exists(): raise RuntimeError('Could not find the added job.') self.jobAdded.emit(path) path += f'/thumbnail.{common.thumbnail_format}' self.thumbnail_editor.save_image(destination=path) ui.MessageBox(f'{name} was successfully created.').open() return super(base.BasePropertyEditor, self).done(result) # pylint: disable=E1003
def add(self, *args, **kwargs): if not self.window().server() or not self.window().job(): return path = QtWidgets.QFileDialog.getExistingDirectory( self, 'Pick a new bookmark folder', self.window().job_path(), QtWidgets.QFileDialog.ShowDirsOnly | QtWidgets.QFileDialog.DontResolveSymlinks) if not path: return if not QtCore.QDir(path).mkdir(common.bookmark_cache_dir): raise RuntimeError('Could not create bookmark') name = path[len(self.window().job_path()) + 1:] for n in range(self.count()): item = self.item(n) if item.data(QtCore.Qt.DisplayRole) == name: ui.MessageBox( f'"{name}" is already a bookmark.' 'The selected folder is already a bookmark, skipping.' ).open() return item = QtWidgets.QListWidgetItem() item.setFlags(QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsUserCheckable) item.setCheckState(QtCore.Qt.Unchecked) item.setData(QtCore.Qt.DisplayRole, name) item.setData(QtCore.Qt.UserRole, path) size = QtCore.QSize(0, common.size(common.WidthMargin) * 2) item.setSizeHint(size) self.update_state(item) self.insertItem(self.count(), item) self.setCurrentItem(item)
def __init__(self, server, job, root, parent=None): super(BookmarkDB, self).__init__(parent=parent) self._connection = None self._server = server.lower().encode(u'utf-8') self._server_u = server.lower() self._job = job.lower().encode(u'utf-8') self._job_u = job.lower() self._root = root.lower().encode(u'utf-8') self._root_u = root.lower() self._bookmark = server + u'/' + job + u'/' + root self._database_path = u'{server}/{job}/{root}/.bookmark/bookmark.db'.format( server=server, job=job, root=root) # Let's make sure the parent folder exists before connecting _p = u'{}/.bookmark'.format(self._bookmark) if not QtCore.QFileInfo(_p).exists(): if not QtCore.QDir(self._bookmark).mkpath(u'.bookmark'): s = u'Unable to create folder "{}"'.format(_p) log.error(s) raise OSError(s) try: self._connection = sqlite3.connect(self._database_path, isolation_level=None, check_same_thread=False) self.init_tables() # I don't know if this is needed, but we should try to close the # DB connection when the instance is deleted self.destroyed.connect(self._connection.close) except Error as e: raise RuntimeError( u'Unable to connect to the database at "{}"\n-> "{}"'.format( self._database_path, e.message))