Code: Select all
void EditorTabWidget::onFileExternallyModified(const QString &filePath) {
// Check if changes are being handled by the program
if (internalChangeInProgress) {
return;
}
// Set the flag for change handling
internalChangeInProgress = true;
QMessageBox msgBox;
msgBox.setText(QString("The file %1 has been modified by an external program.").arg(filePath));
msgBox.setInformativeText("What would you like to do?");
// Add buttons
QPushButton *restoreButton = msgBox.addButton(tr("Restore"), QMessageBox::ActionRole);
QPushButton *discardButton = msgBox.addButton(QMessageBox::Discard);
msgBox.setDefaultButton(discardButton);
msgBox.exec();
if (msgBox.clickedButton() == restoreButton) {
// Restore from backup
QString backupPath = backupPaths.value(filePath);
if (!backupPath.isEmpty()) {
QFile backupFile(backupPath);
QFile originalFile(filePath);
if (backupFile.open(QIODevice::ReadOnly) && originalFile.open(QIODevice::WriteOnly)) {
QTextStream in(&backupFile);
QTextStream out(&originalFile);
out findChild("edit_field");
if (textEdit) {
textEdit->setPlainText(in.readAll());
}
}
originalFile.close();
// Restore the watcher after loading
if (watcher) {
for (auto &path : openFilesList) {
watcher->addPath(path);
}
}
} else {
QMessageBox::critical(this, "Error", "Failed to open the file for reloading.");
}
}
// Reset the flag after processing is complete
internalChangeInProgress = false;
}
Code: Select all
class EditorTabWidget : public QTabWidget {
Q_OBJECT
public:
explicit EditorTabWidget(QWidget *parent = nullptr);
QStringListModel *getModel() { return &modelNames; }
bool fileSaved(int index);
void removeTab(int index);
QString saveAs(int index);
QList openFilesList;
public slots:
void addEdit(const QString &fileName);
void addSaved(const QString &filePath);
void addEmpty();
int closeAllTabs();
private slots:
void fileChanged(); // Tracks changes within the editor
void onFileExternallyModified(
const QString &filePath); // Tracks external changes
private:
void addFile(const QString &fileName = "untitled");
void setFile(int index, const QString &fileName = "untitled");
void removeFile(int index);
void saveBackup(const QString &filePath); // Creates or updates the file backup
// Monitoring external changes
void watchExternalFileChanges(const QString &filePath);
QIcon savedButton;
QIcon notSavedButton;
QString styleSheet;
QStringListModel modelNames;
QFileSystemWatcher fileWatcher; // For monitoring external file changes
QMap
backupPaths; // Mapping between files and their backups
QVector closeButtons;
bool internalChangeInProgress = false;
QWidget *findTabWidget(const QString &filePath);
};