// ============================================================================
//  file_dialog  —  Qt 桌面示例
//  来源：川大 C++/LinuxC wiki「02.Qt方向」
//  原文片段：[58954535:12]
//  说明：本文件由 gen_part3.py 从 wiki 片段生成（必要时补 main/QApplication
//        外壳、include、修正笔误）。详见 docs/ERRATA.md。
//        离屏验证：QT_QPA_PLATFORM=offscreen tools/run_qt.sh <target>（自动退出）
// ============================================================================

#include <QApplication>
#include <QMainWindow>
#include <QAction>
#include <QMenuBar>
#include <QToolBar>
#include <QFileDialog>
#include <QFile>
#include <QTextStream>
#include <QMessageBox>
#include <QTimer>

class MainWindow : public QMainWindow {
    Q_OBJECT
public:
    MainWindow() {
        QAction* openAction = new QAction(QStringLiteral("打开..."), this);
        QAction* saveAction = new QAction(QStringLiteral("保存..."), this);
        menuBar()->addMenu(QStringLiteral("文件"))->addAction(openAction);
        menuBar()->addMenu(QStringLiteral("文件"))->addAction(saveAction);
        connect(openAction, &QAction::triggered, this, &MainWindow::openFile);
        connect(saveAction, &QAction::triggered, this, &MainWindow::saveFile);
    }
private slots:
    void openFile() {
        QString path = QFileDialog::getOpenFileName(this, QStringLiteral("打开文件"));
        if (path.isEmpty()) return;
        QFile file(path);
        if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
            QMessageBox::warning(this, QStringLiteral("错误"), QStringLiteral("打开失败"));
            return;
        }
        QTextStream in(&file);
        QString text = in.readAll();
        file.close();
        QMessageBox::information(this, QStringLiteral("内容"), text);
    }
    void saveFile() {
        QString path = QFileDialog::getSaveFileName(this, QStringLiteral("保存文件"));
        if (path.isEmpty()) return;
        QFile file(path);
        if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
            QMessageBox::warning(this, QStringLiteral("错误"), QStringLiteral("保存失败"));
            return;
        }
        QTextStream out(&file);
        out << QStringLiteral("示例保存内容");
        file.close();
    }
};

int main(int argc, char* argv[]) {
    QApplication app(argc, argv);
    MainWindow w; w.show();
    // 仅在离屏自动化验证时（QT_QPA_PLATFORM=offscreen）200ms 后自动退出；
    // 正常运行（有显示环境）窗口保持打开，不自动退出。
    if (qgetenv("QT_QPA_PLATFORM") == "offscreen") {
        QTimer::singleShot(200, &app, &QApplication::quit);
    }
    return app.exec();
}

#include "file_dialog.moc"
