Пример #1
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