Exemplo n.º 1
0
    def _copy_file(self, uid: str = "", source_path: str = "", dest_path: str = ""):
        self._current_uid = uid

        source_file = QFile(source_path)
        dest_file = QFile(dest_path)

        if not source_file.open(QFile.ReadOnly):
            self.copy_error.emit(uid, FileCopier.CannotOpenSourceFile)
            return

        dest_file_info = QFileInfo(dest_file)
        dest_dir = dest_file_info.absoluteDir()
        if not dest_dir.exists():
            if not dest_dir.mkpath(dest_dir.absolutePath()):
                self.copy_error.emit(uid, FileCopier.CannotCreateDestinationDirectory)
                return

        if not dest_file.open(QFile.WriteOnly):
            ic(dest_path, dest_file.errorString())
            self.copy_error.emit(uid, FileCopier.CannotOpenDestinationFile)
            return

        progress: int = 0
        total: int = source_file.size()
        error: int = FileCopier.NoError
        while True:
            if self._cancel_current:
                self._cancel_current = False
                self.copy_cancelled.emit(uid)
                break

            data: Union[bytes, int] = source_file.read(_COPY_BLOCK_SIZE)
            if isinstance(data, int):
                assert data == -1
                error = FileCopier.CannotReadSourceFile
                break

            data_len = len(data)
            if data_len == 0:
                self.copy_progress.emit(uid, progress, total)
                break

            if data_len != dest_file.write(data):
                error = FileCopier.CannotWriteDestinationFile
                break

            progress += data_len
            self.copy_progress.emit(uid, progress, total)

            qApp.processEvents()

        source_file.close()
        dest_file.close()
        if error != FileCopier.NoError:
            dest_file.remove()
            self.copy_error.emit(uid, error)
        else:
            dest_file.setPermissions(source_file.permissions())
            self.copy_complete.emit(uid)
Exemplo n.º 2
0
 def __post_execution(self):
     """Execute a script after executing the project."""
     filePostExec = QFile(self.postExec)
     if filePostExec.exists() and \
             bool(QFile.ExeUser & filePostExec.permissions()):
         ext = file_manager.get_file_extension(self.postExec)
         if not self.pythonExec:
             self.pythonExec = settings.PYTHON_PATH
         self.currentProcess = self._postExecScriptProc
         if ext == 'py':
             self._postExecScriptProc.start(self.pythonExec,
                                            [self.postExec])
         else:
             self._postExecScriptProc.start(self.postExec)
Exemplo n.º 3
0
 def __post_execution(self):
     """Execute a script after executing the project."""
     filePostExec = QFile(self.postExec)
     if filePostExec.exists() and \
       bool(QFile.ExeUser & filePostExec.permissions()):
         ext = file_manager.get_file_extension(self.postExec)
         if not self.pythonPath:
             self.pythonPath = settings.PYTHON_PATH
         self.currentProcess = self._postExecScriptProc
         if ext == 'py':
             self._postExecScriptProc.start(self.pythonPath,
                 [self.postExec])
         else:
             self._postExecScriptProc.start(self.postExec)
Exemplo n.º 4
0
    def __pre_execution(self):
        """Execute a script before executing the project"""

        filePreExec = QFile(self.preExec)
        if filePreExec.exists() and \
                bool(QFile.ExeUser & filePreExec.permissions()):
            ext = file_manager.get_file_extension(self.preExec)
            if not self.pythonExec:
                self.pythonExec = settings.PYTHON_PATH
            self.currentProcess = self._preExecScriptProc
            self.__preScriptExecuted = True
            if ext == 'py':
                self._preExecScriptProc.start(self.pythonExec, [self.preExec])
            else:
                self._preExecScriptProc.start(self.preExec)
        else:
            self.__main_execution()
Exemplo n.º 5
0
    def save(self, parent, filename=None):
        """Saves the current file and sets is_modified to False.
        If the file has never been saved (i.e., doesn't have a filename) or is not writable, this method calls save_as.
        :type parent: QWidget - The parent window for dialogs, alerts, etc.
        :type filename: str - Full path of file or None (the default)
        :rtype: bool - True = Successfully saved file, False = error (user was notified) or user cancelled
        """
        if filename is None:
            filename = self.filename

        # If the current file has never been saved...
        if filename is None:
            # ...call save_as instead
            self.on_file_saveas()

        wavfile = QFile(filename)
        # If the original file exists, but can't be opened for writing...
        if wavfile.exists() and not wavfile.open(QIODevice.ReadWrite):
            # ...then treat this as a Save-As command
            return self.save_as(parent)

        tmpfile = QTemporaryFile(filename)
        # If we can't open our temporary file for writing...
        if not QTemporaryFile.open(QIODevice.WriteOnly):
            # ...something's wrong (disk full?), so report it to the user and exit
            QMessageBox.critical(
                parent, make_caption('Warning'),
                "Unable to create temporary file:\n\n\t<b>{}</b>\n\n\n{}".
                format(tmpfile.fileName(), tmpfile.errorString()))
            return False

        # If the original file exists...
        if wavfile.exists():
            # ...set the temporary file permissions to match the original
            tmpfile.setPermissions(wavfile.permissions())  # Ignore errors
        elif sys.platform == 'win32':
            # ...otherwise (on Windows) use standard permissions
            tmpfile.setPermissions(QFile.WriteGroup | QFile.WriteOther)
        elif sys.platform.startswith('linux') or sys.platform.startswith(
                'darwin'):
            # ...otherwise (on Linux) use the file mode creation mask for the current process
            tmpfile.setPermissions(self.umask_as_permission()
                                   & Document.PERMISSION_MASK)
        else:
            raise RuntimeError(
                'Unsupported platform: ' +
                sys.platform)  # TODO - check this at startup, not here

        tmpfile.close()  # TODO - is this necessary?

        # Write out the WAV file
        try:
            with wave.open(tmpfile.fileName(), mode='wb') as wave_write:
                # Set the audio file properties
                wave_write.setnchannels(self.channels)
                wave_write.setsampwidth(self.bytes_per_sample)
                wave_write.setframerate(self.sampling_rate)
                wave_write.setnframes(self.frames)
                wave_write.setcomptype(None)

                # Write the contents of memory out to the file
                wave_write.writeframes(self.frames)

        except wave.Error as e:
            # An error occurred, notify user and return False
            QMessageBox.critical(
                parent, make_caption('Warning'),
                "Unable to write file:\n\n\t<b>{}</b>\n\n\n{}".format(
                    tmpfile.fileName(), e.args[0]))
            return False

        # Data was written successfully to temp file, so inform QTemporaryFile not to remove it automatically; we're
        # going to rename it to the original file
        tmpfile.setAutoRemove(False)

        backup_filename = filename + '~'
        # Remove any previous backup
        QFile.remove(backup_filename)
        # Rename the original file to the backup name
        QFile.rename(filename, backup_filename)
        # Rename the temporary file to the original name
        if not tmpfile.rename(filename):
            # If anything goes wrong, rename the backup file back to the original name
            QFile.rename(backup_filename, filename)
            QMessageBox.critical(
                parent, make_caption('Warning'),
                "Unable to rename file:\n\n\tFrom: <b>{}</b>\n\tTo: <b>{}</b>\n\n\n{}"
                .format(backup_filename, filename, tmpfile.errorString()))
            return False

        settings = QSettings()
        if not settings.value(
                Settings.CREATE_BACKUP_ON_SAVE,
                defaultValue=Settings.CREATE_BACKUP_ON_SAVE_DFLT):
            QFile.remove(backup_filename)

        self.is_modified = False
        self._set_filename(filename)

        return True