class KAutoSaveFile


Module kdecore
Namespace
Class KAutoSaveFile
Inherits QFile
Creates and manages an "auto-save" file. Autosave files are temporary files that applications use to store the unsaved data in a file they have open for editing. KAutoSaveFile allows you to easily create and manage such files, as well as to recover the unsaved data left over by a crashed or otherwise gone process.

Each KAutoSaveFile object is associated with one specific file that the application holds open. KAutoSaveFile is also a QObject, so it can be reparented to the actual opened file object, so as to manage the lifetime of the temporary file.

Typical use consists of: - verifying whether stale autosave files exist for the opened file - deciding whether to recover the old, autosaved data - if not recovering, creating a KAutoSaveFile object for the opened file - during normal execution of the program, periodically save unsaved data into the KAutoSaveFile file.

KAutoSaveFile holds a lock on the autosave file, so it's safe to delete the file and recreate it later. Because of that, disposing of stale autosave files should be done with releaseLock(). No lock is held on the managed file.

Examples: Opening a new file:

void Document.open(const KUrl &url)
{
// check whether autosave files exist:
QList staleFiles = KAutoSaveFile.staleFiles(url);
if (!staleFiles.isEmpty()) {
if (KMessageBox.questionYesNo(parent,
"Auto-saved files exist. Do you want to recover them now?",
"File Recovery",
"Recover", "Don't recover") == KMessage.Yes) {
recoverFiles(staleFiles);
return;
} else {
// remove the stale files
foreach (KAutoSaveFile *stale, staleFiles) {
stale->open(QIODevice.ReadWrite);
delete stale;
}
}
}

// create new autosave object m_autosave = new KAutoSaveFile(url, this);

// continue the process of opening file 'url' ... }

The function recoverFiles could loop over the list of files and do this:

foreach (KAutoSaveFile *stale, staleFiles) {
if (!stale->open(QIODevice.ReadWrite)) {
// show an error message; we could not steal the lockfile
// maybe another application got to the file before us?
delete stale;
continue;
}
Document *doc = new Document;
doc->m_autosave = stale;
stale->setParent(doc); // reparent

doc->setUrl(stale->managedFile()); doc->setContents(stale->readAll()); doc->setState(Document.Modified); // mark it as modified and unsaved

documentManager->addDocument(doc); }

If the file is unsaved, periodically write the contents to the save file:

if (!m_autosave->isOpen() && !m_autosave->open(QIODevice.ReadWrite)) {
// show error: could not open the autosave file
}
m_autosave->write(contents());

When the user saves the file, the autosaved file is no longer necessary and can be removed or emptied.

m_autosave->resize(0); // leaves the file open

m_autosave->remove(); // closes the file

Author Jacob R Rideout



methods