Пример #1
0
    def interactiveImport(self, addWarning=False):
        """Prompt the user for import type & proceed with import.

        Return the structure if import is successful, otherwise None
        Arguments:
            addWarning - if True, add non-valid file warning to dialog
        """
        dialog = miscdialogs.RadioChoiceDialog(_('Import File'),
                                               _('Choose Import Method'),
                                               methods.items(),
                                               QApplication.activeWindow())
        if addWarning:
            fileName = self.pathObj.name
            dialog.addLabelBox(
                _('Invalid File'),
                _('"{0}" is not a valid TreeLine file.\n\n'
                  'Use an import filter?').format(fileName))
        if dialog.exec_() != QDialog.Accepted:
            return None
        method = dialog.selectedButton()
        if not self.pathObj:
            filters = ';;'.join((globalref.fileFilters[fileFilters[method]],
                                 globalref.fileFilters['all']))
            defaultFilePath = str(globalref.mainControl.defaultPathObj(True))
            filePath, selFltr = QFileDialog.getOpenFileName(
                QApplication.activeWindow(), _('TreeLine - Import File'),
                defaultFilePath, filters)
            if not filePath:
                return None
            self.pathObj = pathlib.Path(filePath)
        self.errorMessage = ''
        try:
            QApplication.setOverrideCursor(Qt.WaitCursor)
            structure = getattr(self, method)()
            QApplication.restoreOverrideCursor()
        except IOError:
            QApplication.restoreOverrideCursor()
            QMessageBox.warning(
                QApplication.activeWindow(), 'TreeLine',
                _('Error - could not read file {0}').format(self.pathObj))
            return None
        except UnicodeDecodeError:
            prevEncoding = globalref.localTextEncoding
            globalref.localTextEncoding = 'utf-8'
            structure = getattr(self, method)()
            globalref.localTextEncoding = prevEncoding
            QApplication.restoreOverrideCursor()
        if not structure:
            message = _('Error - improper format in {0}').format(self.pathObj)
            if self.errorMessage:
                message = '{0}\n{1}'.format(message, self.errorMessage)
                self.errorMessage = ''
            QMessageBox.warning(QApplication.activeWindow(), 'TreeLine',
                                message)
        return structure
Пример #2
0
    def interactiveImport(self, addWarning=False):
        """Prompt the user for import type & proceed with import.

        Return the model if import is successful, otherwise None
        Arguments:
            addWarning - if True, add non-valid file warning to dialog
        """
        dialog = miscdialogs.RadioChoiceDialog(
            _('Import File'), _('Choose Import Method'), methods.items(),
            QtGui.QApplication.activeWindow())
        if addWarning:
            fileName = os.path.basename(self.filePath)
            dialog.addLabelBox(
                _('Invalid File'),
                _('"{0}" is not a valid TreeLine file.\n\n'
                  'Use an import filter?').format(fileName))
        if dialog.exec_() != QtGui.QDialog.Accepted:
            return None
        method = dialog.selectedButton()
        if not self.filePath:
            filters = ';;'.join((globalref.fileFilters[fileFilters[method]],
                                 globalref.fileFilters['all']))
            defaultFilePath = globalref.mainControl.defaultFilePath(True)
            self.filePath = QtGui.QFileDialog.getOpenFileName(
                QtGui.QApplication.activeWindow(), _('TreeLine - Import File'),
                defaultFilePath, filters)
            if not self.filePath:
                return None
        self.errorMessage = ''
        try:
            QtGui.QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)
            model = getattr(self, method)()
            QtGui.QApplication.restoreOverrideCursor()
        except IOError:
            QtGui.QApplication.restoreOverrideCursor()
            QtGui.QMessageBox.warning(
                QtGui.QApplication.activeWindow(), 'TreeLine',
                _('Error - could not read file {0}').format(self.filePath))
            return None
        if not model:
            message = _('Error - improper format in {0}').format(self.filePath)
            if self.errorMessage:
                message = '{0}\n{1}'.format(message, self.errorMessage)
                self.errorMessage = ''
            QtGui.QMessageBox.warning(QtGui.QApplication.activeWindow(),
                                      'TreeLine', message)
        return model
Пример #3
0
    def __init__(self, fileName='', progName='', version='', coDirName=''):
        """Initialize and set the path to the config file.

        Creates the path dir structure if necessary (if fileName is given).
        On Windows, uses the module path's config directory if it exists.
        Arguments:
            fileName -- the config file name, excluding the extension
            progName -- the program name, for dialog headings & config dir name
            version -- a version string, for config dir names
            coDirName -- the company name for the config dir in Windows OS
        """
        super().__init__()
        self.modified = False
        self.path = pathlib.Path()

        if not fileName:
            return  # no storage without fileName (temporary options only)
        if not version:
            version = '0'
        appDirName = '{0}-{1}'.format(progName.lower(), version)
        fileNameSuffix = '.ini' if sys.platform.startswith('win') else 'rc'

        if not Options.basePath and progName and coDirName:
            if sys.platform.startswith('win'):  # Windows
                userPath = (pathlib.Path(os.environ.get('APPDATA', '')) /
                            coDirName / appDirName)
            else:  # Linux, etc.
                userPath = (pathlib.Path(os.path.expanduser('~')) /
                            ('.' + appDirName))
            if userPath.is_dir():
                Options.basePath = userPath
            else:
                modPath = pathlib.Path(sys.path[0]).resolve()
                if modPath.is_file():
                    modPath = modPath.parent  # for frozen binary
                modConfigPath = modPath / 'config'
                if modConfigPath.is_dir():
                    Options.basePath = modConfigPath
                elif os.access(str(modPath), os.W_OK):
                    dialog = miscdialogs.RadioChoiceDialog(
                        progName, _('Choose configuration file location'),
                        [(_('User\'s home directory (recommended)'), 0),
                         (_('Program directory (for portable use)'), 1)])
                    if dialog.exec_() != QDialog.Accepted:
                        sys.exit(0)
                    if dialog.selectedButton() == 1:
                        Options.basePath = modConfigPath
                if not Options.basePath:
                    Options.basePath = userPath
            try:
                if not Options.basePath.is_dir():
                    Options.basePath.mkdir(parents=True)
                iconPath = Options.basePath / 'icons'
                if not iconPath.is_dir():
                    iconPath.mkdir()
                templatePath = Options.basePath / 'templates'
                if not templatePath.is_dir():
                    templatePath.mkdir()
                templateExportPath = templatePath / 'exports'
                if not templateExportPath.is_dir():
                    templateExportPath.mkdir()
            except OSError:
                Options.basePath = None
        if Options.basePath:
            self.path = Options.basePath / (fileName + fileNameSuffix)
Пример #4
0
    def __init__(self, fileName='', progName='', version='', coDirName=''):
        """Initialize and set the path to the config file.

        Creates the path dir structure if necessary (if fileName is given).
        On Windows, uses the module path's config directory if it exists.
        Arguments:
            fileName -- the config file name, excluding the extension
            progName -- the program name, for dialog headings & config dir name
            version -- a version string, for config dir names
            coDirName -- the company name for the config dir in Windows OS
        """
        super().__init__()
        self.modified = False
        self.path = ''

        if not fileName:
            return    # no storage without fileName (temporary options only)
        appDirName = '{0}-{1}'.format(progName.lower(), version)
        if sys.platform.startswith('win'):    # Windows
            fileNameSuffix = '.ini'
            if not Options.basePath:
                userPath = os.path.join(os.environ.get('APPDATA', ''),
                                        coDirName, appDirName)
        else:    # Linux, etc.
            fileNameSuffix = 'rc'
            if not Options.basePath:
                userPath = os.path.join(os.environ.get('HOME', ''),
                                        '.' + appDirName)
        if not Options.basePath:
            if os.path.exists(userPath):
                Options.basePath = userPath
            else:
                modPath = os.path.dirname(os.path.abspath(sys.path[0]))
                modConfigPath = os.path.join(modPath, 'config')
                if os.path.exists(modConfigPath):
                    Options.basePath = modConfigPath
                elif os.access(modPath, os.W_OK):
                    dialog = miscdialogs.RadioChoiceDialog(progName,
                              _('Choose configuration file location'),
                              [(_('User\'s home directory (recommended)'), 0),
                               (_('Program directory (for portable use)'), 1)])
                    if dialog.exec_() != QtGui.QDialog.Accepted:
                        sys.exit(0)
                    if dialog.selectedButton() == 1:
                        Options.basePath = modConfigPath
                if not Options.basePath:
                    Options.basePath = userPath
            try:
                if not os.path.exists(Options.basePath):
                    os.makedirs(Options.basePath)
                iconPath = os.path.join(Options.basePath, 'icons')
                if not os.path.exists(iconPath):
                    os.makedirs(iconPath)
                templatePath = os.path.join(Options.basePath, 'templates')
                if not os.path.exists(templatePath):
                    os.makedirs(templatePath)
                pluginPath = os.path.join(Options.basePath, 'plugins')
                if not os.path.exists(pluginPath):
                    os.makedirs(pluginPath)
            except OSError:
                Options.basePath = ''
        if Options.basePath:
            self.path = os.path.join(Options.basePath,
                                     fileName + fileNameSuffix)