LCOV - code coverage report
Current view: top level - muse/framework/interactive/internal - interactive.cpp Coverage Total Hit
Test: filtered_coverage.info Lines: 13.4 % 724 97
Test Date: 2026-11-19 04:14:36

            Line data    Source code
       1              : /*
       2              :  * SPDX-License-Identifier: GPL-3.0-only
       3              :  * MuseScore-CLA-applies
       4              :  *
       5              :  * MuseScore Studio
       6              :  * Music Composition & Notation
       7              :  *
       8              :  * Copyright (C) 2021 MuseScore Limited and others
       9              :  *
      10              :  * This program is free software: you can redistribute it and/or modify
      11              :  * it under the terms of the GNU General Public License version 3 as
      12              :  * published by the Free Software Foundation.
      13              :  *
      14              :  * This program is distributed in the hope that it will be useful,
      15              :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      16              :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      17              :  * GNU General Public License for more details.
      18              :  *
      19              :  * You should have received a copy of the GNU General Public License
      20              :  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
      21              :  */
      22              : 
      23              : #include "interactive.h"
      24              : 
      25              : #include <QColorDialog>
      26              : #include <QDialog>
      27              : #include <QFileDialog>
      28              : #include <QGuiApplication>
      29              : #include <QMetaProperty>
      30              : #include <QMetaType>
      31              : #include <QQmlEngine>
      32              : #include <QUrl>
      33              : #include <QWidget>
      34              : #include <QWindow>
      35              : 
      36              : #include "async/async.h"
      37              : #include "io/path.h"
      38              : #include "translation.h"
      39              : 
      40              : #include "diagnostics/diagnosticutils.h"
      41              : 
      42              : #include "filedialogfilters.h"
      43              : #include "widgetdialogadapter.h"
      44              : #include "ui/view/widgetdialog.h"
      45              : 
      46              : #include "muse_framework_config.h"
      47              : 
      48              : #include "defer.h"
      49              : #include "log.h"
      50              : 
      51              : using namespace muse;
      52              : using namespace muse::interactive;
      53              : using namespace muse::async;
      54              : 
      55              : // === QmlLaunchData ===
      56              : 
      57            0 : QmlLaunchData::QmlLaunchData(QObject* parent)
      58            0 :     : QObject(parent)
      59              : {
      60            0 : }
      61              : 
      62            0 : QVariant QmlLaunchData::value(const QString& key) const
      63              : {
      64            0 :     return m_data.value(key);
      65              : }
      66              : 
      67            0 : void QmlLaunchData::setValue(const QString& key, const QVariant& val)
      68              : {
      69            0 :     m_data[key] = val;
      70            0 : }
      71              : 
      72            0 : QVariant QmlLaunchData::data() const
      73              : {
      74            0 :     return m_data;
      75              : }
      76              : 
      77              : // === Interactive ===
      78              : 
      79            2 : Interactive::Interactive(const muse::modularity::ContextPtr& ctx)
      80           12 :     : QObject(), Contextable(ctx)
      81              : {
      82            2 :     connect(qApp, &QGuiApplication::focusWindowChanged, this, [this](QWindow* window) {
      83            0 :         raiseWindowInStack(window);
      84            0 :     });
      85              : 
      86            2 :     connect(qApp, &QGuiApplication::focusObjectChanged, this, [this](QObject* obj) {
      87            0 :         auto widget = dynamic_cast<QWidget*>(obj);
      88              : 
      89            0 :         if (widget && widget->isWindow()) {
      90            0 :             raiseWindowInStack(widget);
      91              :         }
      92            0 :     });
      93           12 : }
      94              : 
      95            0 : void Interactive::raiseWindowInStack(QObject* newActiveWindow)
      96              : {
      97            0 :     if (!newActiveWindow || m_stack.isEmpty() || m_stack.top().window == newActiveWindow) {
      98            0 :         return;
      99              :     }
     100              : 
     101            0 :     for (int i = 0; i < m_stack.size(); ++i) {
     102            0 :         bool found = m_stack[i].window == newActiveWindow;
     103            0 :         if (m_stack[i].window && m_stack[i].window->isWidgetType()) {
     104            0 :             found = newActiveWindow->objectName() == (m_stack[i].window->objectName() + "Window");
     105              :         }
     106              : 
     107            0 :         if (found) {
     108            0 :             ObjectInfo info = m_stack.takeAt(i);
     109            0 :             m_stack.push(info);
     110            0 :             notifyAboutCurrentUriChanged();
     111            0 :             return;
     112            0 :         }
     113              :     }
     114              : }
     115              : 
     116            2 : IInteractive::ButtonData Interactive::buttonData(Button b) const
     117              : {
     118            2 :     constexpr bool accent = true;
     119              : 
     120            2 :     switch (b) {
     121            0 :     case IInteractive::Button::NoButton:    return ButtonData(int(b), "");
     122            0 :     case IInteractive::Button::Ok:          return ButtonData(int(b), muse::trc("global", "OK"), accent);
     123            0 :     case IInteractive::Button::Save:        return ButtonData(int(b), muse::trc("global", "Save"), accent);
     124            0 :     case IInteractive::Button::SaveAll:     return ButtonData(int(b), muse::trc("global", "Save all"));
     125            0 :     case IInteractive::Button::DontSave:    return ButtonData(int(b), muse::trc("global", "Don’t save"));
     126            0 :     case IInteractive::Button::Open:        return ButtonData(int(b), muse::trc("global", "Open"));
     127            1 :     case IInteractive::Button::Yes:         return ButtonData(int(b), muse::trc("global", "Yes"), accent);
     128            0 :     case IInteractive::Button::YesToAll:    return ButtonData(int(b), muse::trc("global", "Yes to all"), accent);
     129            1 :     case IInteractive::Button::No:          return ButtonData(int(b), muse::trc("global", "No"));
     130            0 :     case IInteractive::Button::NoToAll:     return ButtonData(int(b), muse::trc("global", "No to all"));
     131            0 :     case IInteractive::Button::Abort:       return ButtonData(int(b), muse::trc("global", "Abort"));
     132            0 :     case IInteractive::Button::Retry:       return ButtonData(int(b), muse::trc("global", "Retry"));
     133            0 :     case IInteractive::Button::Ignore:      return ButtonData(int(b), muse::trc("global", "Ignore"));
     134            0 :     case IInteractive::Button::Close:       return ButtonData(int(b), muse::trc("global", "Close"));
     135            0 :     case IInteractive::Button::Cancel:      return ButtonData(int(b), muse::trc("global", "Cancel"));
     136            0 :     case IInteractive::Button::Discard:     return ButtonData(int(b), muse::trc("global", "Discard"));
     137            0 :     case IInteractive::Button::Help:        return ButtonData(int(b), muse::trc("global", "Help"));
     138            0 :     case IInteractive::Button::Apply:       return ButtonData(int(b), muse::trc("global", "Apply"));
     139            0 :     case IInteractive::Button::Reset:       return ButtonData(int(b), muse::trc("global", "Reset"));
     140            0 :     case IInteractive::Button::Continue:    return ButtonData(int(b), muse::trc("global", "Continue"));
     141            0 :     case IInteractive::Button::Next:
     142              :     case IInteractive::Button::Back:
     143              :     case IInteractive::Button::Select:
     144              :     case IInteractive::Button::Clear:
     145              :     case IInteractive::Button::Done:
     146              :     case IInteractive::Button::RestoreDefaults:
     147            0 :     case IInteractive::Button::CustomButton: break;
     148              :     }
     149              : 
     150            0 :     return ButtonData(int(b), "");
     151              : }
     152              : 
     153            1 : UriQuery Interactive::makeQuery(const std::string& type, const std::string& contentTitle,
     154              :                                 const Text& text,
     155              :                                 const ButtonDatas& buttons, int defBtn,
     156              :                                 const Options& options, const std::string& dialogTitle) const
     157              : {
     158            1 :     auto format = [](IInteractive::TextFormat f) {
     159            1 :         switch (f) {
     160            1 :         case IInteractive::TextFormat::Auto:      return Qt::AutoText;
     161            0 :         case IInteractive::TextFormat::PlainText: return Qt::PlainText;
     162            0 :         case IInteractive::TextFormat::RichText:  return Qt::RichText;
     163              :         }
     164            0 :         return Qt::PlainText;
     165              :     };
     166              : 
     167            2 :     UriQuery q("muse://interactive/standard");
     168            1 :     q.set("type", type)
     169            2 :     .set("contentTitle", contentTitle)
     170            3 :     .set("text", text.text)
     171            3 :     .set("textFormat", (int)format(text.format))
     172            3 :     .set("detailedText", text.detailedText)
     173            2 :     .set("defaultButtonId", defBtn)
     174            3 :     .set("withIcon", options.testFlag(IInteractive::Option::WithIcon))
     175            3 :     .set("withDontShowAgainCheckBox", options.testFlag(IInteractive::Option::WithDontShowAgainCheckBox))
     176            2 :     .set("dialogTitle", dialogTitle);
     177              : 
     178            1 :     ValList buttonsList;
     179            1 :     ValList customButtonsList;
     180            1 :     if (buttons.empty()) {
     181            0 :         buttonsList.push_back(Val(static_cast<int>(IInteractive::Button::Ok)));
     182              :     } else {
     183            3 :         for (const IInteractive::ButtonData& buttonData: buttons) {
     184            2 :             ValMap customButton;
     185            6 :             customButton["text"] = Val(buttonData.text);
     186            6 :             customButton["buttonId"] = Val(buttonData.btn);
     187            6 :             customButton["role"] = Val(static_cast<int>(buttonData.role));
     188            6 :             customButton["isAccent"] = Val(buttonData.accent);
     189            6 :             customButton["isLeftSide"] = Val(buttonData.leftSide);
     190            6 :             customButton["icon"] = Val(buttonData.icon);
     191            2 :             customButtonsList.push_back(Val(customButton));
     192            2 :         }
     193              :     }
     194              : 
     195            3 :     q.set("buttons", Val(buttonsList))
     196            3 :     .set("customButtons", Val(customButtonsList));
     197              : 
     198            1 :     return q;
     199            1 : }
     200              : 
     201            0 : IInteractive::Result Interactive::makeResult(const Val& val) const
     202              : {
     203            0 :     QVariantMap resultMap = val.toQVariant().toMap();
     204            0 :     int btn = resultMap["buttonId"].toInt();
     205            0 :     bool showAgain = resultMap["showAgain"].toBool();
     206            0 :     return IInteractive::Result(btn, showAgain);
     207            0 : }
     208              : 
     209            1 : async::Promise<IInteractive::Result> Interactive::openStandardAsync(const std::string& type, const std::string& contentTitle,
     210              :                                                                     const Text& text,
     211              :                                                                     const ButtonDatas& buttons, int defBtn,
     212              :                                                                     const Options& options, const std::string& dialogTitle)
     213              : {
     214            1 :     UriQuery q = makeQuery(type, contentTitle, text, buttons, defBtn, options, dialogTitle);
     215              : 
     216            1 :     return openAsync(q).then<IInteractive::Result>(
     217              :         this,
     218            0 :         [this](const Val& val, auto resolve, auto /*reject*/) {
     219            0 :         return resolve(makeResult(val));
     220              :     },
     221            1 :         [](int code, const std::string& msg, auto resolve, auto reject) {
     222              :         //! NOTE To simplify writing the handlers
     223            1 :         (void)resolve(IInteractive::Result((int)IInteractive::Button::Cancel));
     224            1 :         return reject(code, msg);
     225            2 :     });
     226            1 : }
     227              : 
     228            0 : IInteractive::Result Interactive::openStandardSync(const std::string& type, const std::string& contentTitle,
     229              :                                                    const Text& text,
     230              :                                                    const ButtonDatas& buttons, int defBtn,
     231              :                                                    const Options& options, const std::string& dialogTitle)
     232              : {
     233            0 :     UriQuery q = makeQuery(type, contentTitle, text, buttons, defBtn, options, dialogTitle);
     234            0 :     RetVal<Val> rv = openSync(q);
     235              : 
     236            0 :     if (rv.ret) {
     237            0 :         return makeResult(rv.val);
     238              :     } else {
     239            0 :         return IInteractive::Result((int)IInteractive::Button::Cancel);
     240              :     }
     241            0 : }
     242              : 
     243            0 : IInteractive::Result Interactive::questionSync(const std::string& contentTitle, const Text& text,
     244              :                                                const ButtonDatas& buttons, int defBtn,
     245              :                                                const Options& options, const std::string& dialogTitle)
     246              : {
     247            0 :     return openStandardSync("QUESTION", contentTitle, text, buttons, defBtn, options, dialogTitle);
     248              : }
     249              : 
     250            1 : async::Promise<IInteractive::Result> Interactive::question(const std::string& contentTitle, const Text& text,
     251              :                                                            const ButtonDatas& buttons, int defBtn,
     252              :                                                            const Options& options, const std::string& dialogTitle)
     253              : {
     254            2 :     return openStandardAsync("QUESTION", contentTitle, text, buttons, defBtn, options, dialogTitle);
     255              : }
     256              : 
     257            0 : IInteractive::Result Interactive::infoSync(const std::string& contentTitle, const Text& text,
     258              :                                            const ButtonDatas& buttons, int defBtn,
     259              :                                            const Options& options, const std::string& dialogTitle)
     260              : {
     261            0 :     return openStandardSync("INFO", contentTitle, text, buttons, defBtn, options, dialogTitle);
     262              : }
     263              : 
     264            0 : async::Promise<IInteractive::Result> Interactive::info(const std::string& contentTitle, const Text& text,
     265              :                                                        const ButtonDatas& buttons, int defBtn,
     266              :                                                        const Options& options, const std::string& dialogTitle)
     267              : {
     268            0 :     return openStandardAsync("INFO", contentTitle, text, buttons, defBtn, options, dialogTitle);
     269              : }
     270              : 
     271            0 : IInteractive::Result Interactive::warningSync(const std::string& contentTitle, const Text& text,
     272              :                                               const ButtonDatas& buttons, int defBtn,
     273              :                                               const Options& options, const std::string& dialogTitle)
     274              : {
     275            0 :     return openStandardSync("WARNING", contentTitle, text, buttons, defBtn, options, dialogTitle);
     276              : }
     277              : 
     278            0 : async::Promise<IInteractive::Result> Interactive::warning(const std::string& contentTitle, const Text& text,
     279              :                                                           const ButtonDatas& buttons, int defBtn,
     280              :                                                           const Options& options, const std::string& dialogTitle)
     281              : {
     282            0 :     return openStandardAsync("WARNING", contentTitle, text, buttons, defBtn, options, dialogTitle);
     283              : }
     284              : 
     285            0 : IInteractive::Result Interactive::errorSync(const std::string& contentTitle, const Text& text,
     286              :                                             const ButtonDatas& buttons, int defBtn,
     287              :                                             const Options& options, const std::string& dialogTitle)
     288              : {
     289            0 :     return openStandardSync("ERROR", contentTitle, text, buttons, defBtn, options, dialogTitle);
     290              : }
     291              : 
     292            0 : async::Promise<IInteractive::Result> Interactive::error(const std::string& contentTitle, const Text& text,
     293              :                                                         const ButtonDatas& buttons, int defBtn,
     294              :                                                         const Options& options, const std::string& dialogTitle)
     295              : {
     296            0 :     return openStandardAsync("ERROR", contentTitle, text, buttons, defBtn, options, dialogTitle);
     297              : }
     298              : 
     299            0 : void Interactive::showProgress(const std::string& title, Progress progress)
     300              : {
     301            0 :     Uri uri("muse://interactive/progress");
     302            0 :     QVariantMap params;
     303            0 :     params["title"] = QString::fromStdString(title);
     304            0 :     params["progress"] = QVariant::fromValue(progress);
     305              : 
     306            0 :     openAsync(uri, params);
     307            0 : }
     308              : 
     309              : #ifdef Q_OS_LINUX
     310              : // see QQuickPlatformFileDialog::FileMode
     311              : enum class FileDialogMode {
     312              :     OpenFile = 0,
     313              :     OpenFiles = 1,
     314              :     SaveFile = 2
     315              : };
     316              : 
     317            0 : static UriQuery makeSelectFileQuery(FileDialogMode mode, const std::string& title, const io::path_t& current,
     318              :                                     const std::vector<std::string>& filter, const int options = 0)
     319              : {
     320            0 :     UriQuery q("muse://interactive/selectfile");
     321            0 :     q.set("title", title);
     322              : 
     323            0 :     const bool isOpenMode = mode == FileDialogMode::OpenFile || mode == FileDialogMode::OpenFiles;
     324            0 :     const bool hidesFilterDetails = options & QFileDialog::HideNameFilterDetails;
     325            0 :     const bool matchCaseInsensitively = isOpenMode && hidesFilterDetails;
     326              : 
     327            0 :     ValList filterList;
     328            0 :     for (const std::string& f : filter) {
     329            0 :         filterList.push_back(Val(matchCaseInsensitively ? caseInsensitiveNameFilter(f) : f));
     330              :     }
     331              : 
     332            0 :     q.set("nameFilters", filterList);
     333            0 :     q.set("fileMode", static_cast<int>(mode));
     334            0 :     q.set("options", options);
     335            0 :     if (mode == FileDialogMode::OpenFile || mode == FileDialogMode::OpenFiles) {
     336            0 :         q.set("selectExisting", true);
     337            0 :         q.set("folder", QUrl::fromLocalFile(current.toQString()).toString().toStdString());
     338            0 :     } else if (mode == FileDialogMode::SaveFile) {
     339            0 :         q.set("currentFile", QUrl::fromLocalFile(current.toQString()).toString().toStdString());
     340              :     }
     341              : 
     342            0 :     return q;
     343            0 : }
     344              : 
     345              : #endif
     346              : 
     347              : #ifndef Q_OS_LINUX
     348              : static QString filterToString(const std::vector<std::string>& filter)
     349              : {
     350              :     QStringList result;
     351              :     for (const std::string& nameFilter : filter) {
     352              :         result << QString::fromStdString(nameFilter);
     353              :     }
     354              : 
     355              :     return result.join(";;");
     356              : }
     357              : 
     358              : #endif
     359              : 
     360            0 : async::Promise<io::path_t> Interactive::selectOpeningFile(const std::string& title, const io::path_t& dir,
     361              :                                                           const std::vector<std::string>& filter)
     362              : {
     363              : #ifndef Q_OS_LINUX
     364              :     return async::make_promise<io::path_t>([title, dir, filter](auto resolve, auto reject) {
     365              :         QFileDialog* dlg = new QFileDialog(nullptr, QString::fromStdString(title), dir.toQString(), filterToString(filter));
     366              : 
     367              :         dlg->setFileMode(QFileDialog::ExistingFile);
     368              : 
     369              :         QObject::connect(dlg, &QFileDialog::finished, [dlg, resolve, reject](int result) {
     370              :             DEFER {
     371              :                 //! Must be called AFTER resolve/reject, as they may process posted events
     372              :                 dlg->deleteLater();
     373              :             };
     374              : 
     375              :             QStringList files = dlg->selectedFiles();
     376              : 
     377              :             if (result != QDialog::Accepted || files.isEmpty()) {
     378              :                 Ret ret = muse::make_ret(Ret::Code::Cancel);
     379              :                 (void)reject(ret.code(), ret.text());
     380              :                 return;
     381              :             }
     382              : 
     383              :             QString file = files.first();
     384              :             (void)resolve(file);
     385              :         });
     386              : 
     387              :         dlg->open();
     388              : 
     389              :         return async::Promise<io::path_t>::Result::unchecked();
     390              :     }, async::PromiseType::AsyncByBody);
     391              : 
     392              : #else
     393              : 
     394            0 :     UriQuery q = makeSelectFileQuery(FileDialogMode::OpenFile, title, dir, filter);
     395              : 
     396            0 :     async::Promise<Val> promise = openAsync(q);
     397              : 
     398            0 :     return async::make_promise<io::path_t>([promise, this](auto resolve, auto reject) {
     399            0 :         async::Promise<Val> mut = promise;
     400            0 :         mut.onResolve(this, [resolve](const Val& val) {
     401            0 :             (void)resolve(QUrl::fromUserInput(val.toQString()).toLocalFile());
     402            0 :         }).onReject(this, [resolve, reject](int code, const std::string& err) {
     403            0 :             (void)reject(code, err);
     404              :         });
     405            0 :         return async::Promise<io::path_t>::Result::unchecked();
     406            0 :     }, async::PromiseType::AsyncByBody);
     407              : #endif
     408            0 : }
     409              : 
     410            0 : io::path_t Interactive::selectOpeningFileSync(const std::string& title, const io::path_t& dir, const std::vector<std::string>& filter,
     411              :                                               const int options)
     412              : {
     413              : #ifndef Q_OS_LINUX
     414              :     const QFileDialog::Options qoptions = QFileDialog::Options::fromInt(options);
     415              :     QString result = QFileDialog::getOpenFileName(nullptr, QString::fromStdString(title), dir.toQString(), filterToString(
     416              :                                                       filter), nullptr, qoptions);
     417              :     return result;
     418              : #else
     419            0 :     UriQuery q = makeSelectFileQuery(FileDialogMode::OpenFile, title, dir, filter, options);
     420              : 
     421            0 :     RetVal<Val> rv = openSync(q);
     422            0 :     if (!rv.ret) {
     423            0 :         return io::path_t();
     424              :     }
     425              : 
     426            0 :     return QUrl::fromUserInput(rv.val.toQString()).toLocalFile();
     427              : #endif
     428            0 : }
     429              : 
     430            0 : io::paths_t Interactive::selectOpeningFilesSync(const std::string& title, const io::path_t& dir, const std::vector<std::string>& filter,
     431              :                                                 const int options)
     432              : {
     433              : #ifndef Q_OS_LINUX
     434              :     const QFileDialog::Options qoptions = QFileDialog::Options::fromInt(options);
     435              :     const QStringList result = QFileDialog::getOpenFileNames(nullptr, QString::fromStdString(title), dir.toQString(), filterToString(
     436              :                                                                  filter), nullptr, qoptions);
     437              : 
     438              :     io::paths_t paths;
     439              :     paths.reserve(result.size());
     440              :     for (const QString& path : result) {
     441              :         paths.emplace_back(path);
     442              :     }
     443              : 
     444              :     return paths;
     445              : #else
     446            0 :     UriQuery q = makeSelectFileQuery(FileDialogMode::OpenFiles, title, dir, filter, options);
     447              : 
     448            0 :     RetVal<Val> rv = openSync(q);
     449            0 :     if (!rv.ret) {
     450            0 :         return io::paths_t();
     451              :     }
     452              : 
     453            0 :     ValList urls = rv.val.toList();
     454              : 
     455            0 :     io::paths_t paths;
     456            0 :     paths.reserve(urls.size());
     457            0 :     for (const Val& url : urls) {
     458            0 :         paths.emplace_back(QUrl::fromUserInput(url.toQString()).toLocalFile());
     459              :     }
     460              : 
     461            0 :     return paths;
     462              : #endif
     463            0 : }
     464              : 
     465            0 : async::Promise<io::path_t> Interactive::selectSavingFile(const std::string& title, const io::path_t& dir,
     466              :                                                          const std::vector<std::string>& filter, bool confirmOverwrite)
     467              : {
     468              : #ifndef Q_OS_LINUX
     469              :     return async::make_promise<io::path_t>([title, dir, filter, confirmOverwrite](auto resolve, auto reject) {
     470              :         QFileDialog* dlg = new QFileDialog(nullptr, QString::fromStdString(title), dir.toQString(), filterToString(filter));
     471              : 
     472              :         dlg->setAcceptMode(QFileDialog::AcceptSave);
     473              :         dlg->setFileMode(QFileDialog::AnyFile);
     474              :         dlg->setOption(QFileDialog::DontConfirmOverwrite, !confirmOverwrite);
     475              : 
     476              :         QObject::connect(dlg, &QFileDialog::finished, [dlg, resolve, reject](int result) {
     477              :             DEFER {
     478              :                 //! Must be called AFTER resolve/reject, as they may process posted events
     479              :                 dlg->deleteLater();
     480              :             };
     481              : 
     482              :             QStringList files = dlg->selectedFiles();
     483              : 
     484              :             if (result != QDialog::Accepted || files.isEmpty()) {
     485              :                 Ret ret = muse::make_ret(Ret::Code::Cancel);
     486              :                 (void)reject(ret.code(), ret.text());
     487              :                 return;
     488              :             }
     489              : 
     490              :             QString file = files.first();
     491              :             (void)resolve(file);
     492              :         });
     493              : 
     494              :         dlg->open();
     495              : 
     496              :         return async::Promise<io::path_t>::Result::unchecked();
     497              :     });
     498              : 
     499              : #else
     500              : 
     501              :     UriQuery q
     502            0 :         = makeSelectFileQuery(FileDialogMode::SaveFile, title, dir, filter, !confirmOverwrite ? QFileDialog::DontConfirmOverwrite : 0);
     503              : 
     504            0 :     async::Promise<Val> promise = openAsync(q);
     505              : 
     506            0 :     return async::make_promise<io::path_t>([promise, this](auto resolve, auto reject) {
     507            0 :         async::Promise<Val> mut = promise;
     508            0 :         mut.onResolve(this, [resolve](const Val& val) {
     509            0 :             (void)resolve(QUrl::fromUserInput(val.toQString()).toLocalFile());
     510            0 :         }).onReject(this, [resolve, reject](int code, const std::string& err) {
     511            0 :             (void)reject(code, err);
     512              :         });
     513            0 :         return async::Promise<io::path_t>::Result::unchecked();
     514            0 :     }, async::PromiseType::AsyncByBody);
     515              : #endif
     516            0 : }
     517              : 
     518            0 : io::path_t Interactive::selectSavingFileSync(const std::string& title, const io::path_t& dir, const std::vector<std::string>& filter,
     519              :                                              bool confirmOverwrite)
     520              : {
     521              : #ifndef Q_OS_LINUX
     522              :     QFileDialog::Options options;
     523              :     options.setFlag(QFileDialog::DontConfirmOverwrite, !confirmOverwrite);
     524              :     QString result = QFileDialog::getSaveFileName(nullptr, QString::fromStdString(title), dir.toQString(), filterToString(
     525              :                                                       filter), nullptr, options);
     526              :     return result;
     527              : #else
     528              : 
     529              :     UriQuery q
     530            0 :         = makeSelectFileQuery(FileDialogMode::SaveFile, title, dir, filter, !confirmOverwrite ? QFileDialog::DontConfirmOverwrite : 0);
     531              : 
     532            0 :     RetVal<Val> rv = openSync(q);
     533            0 :     if (!rv.ret) {
     534            0 :         return io::path_t();
     535              :     }
     536              : 
     537            0 :     return QUrl::fromUserInput(rv.val.toQString()).toLocalFile();
     538              : #endif
     539            0 : }
     540              : 
     541            0 : io::path_t Interactive::selectDirectory(const std::string& title, const io::path_t& dir)
     542              : {
     543              : #ifndef Q_OS_LINUX
     544              :     QString result = QFileDialog::getExistingDirectory(nullptr, QString::fromStdString(title), dir.toQString());
     545              :     return result;
     546              : #else
     547              : 
     548            0 :     UriQuery q("muse://interactive/selectdir");
     549            0 :     q.set("title", title);
     550            0 :     q.set("folder", QUrl::fromLocalFile(dir.toQString()).toLocalFile().toStdString());
     551              : 
     552            0 :     RetVal<Val> rv = openSync(q);
     553            0 :     if (!rv.ret) {
     554            0 :         return io::path_t();
     555              :     }
     556              : 
     557            0 :     return QUrl::fromUserInput(rv.val.toQString()).toLocalFile();
     558              : #endif
     559            0 : }
     560              : 
     561            0 : io::paths_t Interactive::selectMultipleDirectories(const std::string& title, const io::path_t& dir, const io::paths_t& selectedDirectories)
     562              : {
     563            0 :     UriQuery q("muse://interactive/selectmultipledirectories");
     564            0 :     q.set("title", title)
     565            0 :     .set("selectedDirectories", io::pathsToString(selectedDirectories))
     566            0 :     .set("startDir", dir.toStdString());
     567              : 
     568            0 :     RetVal<Val> result = openSync(q);
     569            0 :     if (!result.ret) {
     570            0 :         return selectedDirectories;
     571              :     }
     572              : 
     573            0 :     return io::pathsFromString(result.val.toString());
     574            0 : }
     575              : 
     576            0 : static std::vector<QColor> getCustomColors()
     577              : {
     578            0 :     const int customColorCount = QColorDialog::customCount();
     579            0 :     std::vector<QColor> customColors;
     580            0 :     customColors.reserve(customColorCount);
     581            0 :     for (int i = 0; i < customColorCount; ++i) {
     582            0 :         customColors.push_back(QColorDialog::customColor(i));
     583              :     }
     584              : 
     585            0 :     return customColors;
     586            0 : }
     587              : 
     588            0 : static void setCustomColors(const std::vector<QColor>& customColors)
     589              : {
     590            0 :     const int customColorCount = std::min(QColorDialog::customCount(), static_cast<int>(customColors.size()));
     591            0 :     for (int i = 0; i < customColorCount; ++i) {
     592            0 :         QColorDialog::setCustomColor(i, customColors[i]);
     593              :     }
     594            0 : }
     595              : 
     596            0 : async::Promise<Color> Interactive::selectColor(const Color& color, const std::string& title, bool allowAlpha)
     597              : {
     598            0 :     if (m_isSelectColorOpened) {
     599            0 :         LOGW() << "already opened";
     600            0 :         return async::make_promise<Color>([](auto, auto reject) {
     601            0 :             Ret ret = muse::make_ret(Ret::Code::UnknownError);
     602            0 :             return reject(ret.code(), ret.text());
     603            0 :         });
     604              :     }
     605              : 
     606            0 :     m_isSelectColorOpened = true;
     607              : 
     608            0 :     setCustomColors(uiConfiguration()->colorDialogCustomColors());
     609              : 
     610            0 :     return async::make_promise<Color>([this, color, title, allowAlpha](auto resolve, auto reject) {
     611              :         //! FIX https://github.com/musescore/MuseScore/issues/23208
     612              : #ifdef MUSE_MODULE_SHORTCUTS_V2
     613            0 :         shortcutsController()->setActive(false);
     614              : #else
     615              :         shortcutsRegister()->setActive(false);
     616              : #endif
     617              : 
     618            0 :         QColorDialog* dlg = new QColorDialog();
     619            0 :         if (!title.empty()) {
     620            0 :             dlg->setWindowTitle(QString::fromStdString(title));
     621              :         }
     622              : 
     623            0 :         QColor currentColor = color.toQColor();
     624              : 
     625              :         // If the color is fully transparent, set alpha to opaque, to avoid "Hm, nothing happened" user confusion
     626            0 :         if (currentColor.alpha() == 0) {
     627            0 :             currentColor.setAlpha(255);
     628              :         }
     629              : 
     630            0 :         dlg->setCurrentColor(currentColor);
     631            0 :         dlg->setOption(QColorDialog::ShowAlphaChannel, allowAlpha);
     632              : 
     633            0 :         QObject::connect(dlg, &QColorDialog::finished, [this, dlg, resolve, reject](int result) {
     634            0 :             DEFER {
     635              :                 //! Must be called AFTER resolve/reject, as they may process posted events
     636            0 :                 dlg->deleteLater();
     637              :             };
     638              : 
     639            0 :             uiConfiguration()->setColorDialogCustomColors(getCustomColors());
     640              : 
     641            0 :             m_isSelectColorOpened = false;
     642              : #ifdef MUSE_MODULE_SHORTCUTS_V2
     643            0 :             shortcutsController()->setActive(true);
     644              : #else
     645              :             shortcutsRegister()->setActive(true);
     646              : #endif
     647              : 
     648            0 :             if (result != QDialog::Accepted) {
     649            0 :                 Ret ret = muse::make_ret(Ret::Code::Cancel);
     650            0 :                 (void)reject(ret.code(), ret.text());
     651            0 :                 return;
     652            0 :             }
     653              : 
     654            0 :             QColor selectedColor = dlg->selectedColor();
     655            0 :             (void)resolve(Color::fromQColor(selectedColor));
     656            0 :         });
     657              : 
     658            0 :         dlg->open();
     659              : 
     660            0 :         return async::Promise<Color>::dummy_result();
     661            0 :     }, async::PromiseType::AsyncByBody);
     662              : }
     663              : 
     664            0 : bool Interactive::isSelectColorOpened() const
     665              : {
     666            0 :     return m_isSelectColorOpened;
     667              : }
     668              : 
     669            0 : RetVal<Val> Interactive::openSync(const UriQuery& q)
     670              : {
     671              : #ifndef MUSE_MODULE_INTERACTIVE_SYNC_SUPPORTED
     672              :     NOT_SUPPORTED;
     673              :     std::abort();
     674              :     {
     675              :         RetVal<Val> rv;
     676              :         rv.ret = muse::make_ret(Ret::Code::NotSupported);
     677              :         return rv;
     678              :     }
     679              : #endif
     680              : 
     681            0 :     RetVal<Val> rv;
     682            0 :     QEventLoop loop;
     683            0 :     bool finished = false;
     684            0 :     Promise<Val>::Resolve resolve;
     685            0 :     Promise<Val>::Reject reject;
     686            0 :     Promise<Val> promise = async::make_promise<Val>([&resolve, &reject](auto res, auto rej) {
     687            0 :         resolve = res;
     688            0 :         reject = rej;
     689            0 :         return Promise<Val>::Result::unchecked();
     690            0 :     }, PromiseType::AsyncByBody);
     691              : 
     692            0 :     promise.onResolve(this, [&rv, &loop, &finished](const Val& val) {
     693            0 :         rv = RetVal<Val>::make_ok(val);
     694            0 :         finished = true;
     695            0 :         loop.quit();
     696            0 :     });
     697              : 
     698            0 :     promise.onReject(this, [&rv, &loop, &finished](int code, const std::string& err) {
     699            0 :         LOGE() << code << " " << err;
     700            0 :         rv.ret = make_ret(code, err);
     701            0 :         finished = true;
     702            0 :         loop.quit();
     703            0 :     });
     704              : 
     705            0 :     auto func = openFunc(q);
     706            0 :     func(resolve, reject);
     707              : 
     708            0 :     ContainerMeta openMeta = uriRegister()->meta(q.uri());
     709            0 :     if (openMeta.type == ContainerMeta::PrimaryPage) {
     710            0 :         LOGW() << "Primary pages should not open in synchronous mode, please fix this.";
     711            0 :         return rv;
     712              :     }
     713              : 
     714              :     //! NOTE: The dialog may have finished synchronously while opening (e.g. it
     715              :     //! closed itself on load); quit() before exec() is lost, so don't enter the loop.
     716            0 :     if (finished) {
     717            0 :         return rv;
     718              :     }
     719              : 
     720            0 :     loop.exec();
     721              : 
     722            0 :     return rv;
     723            0 : }
     724              : 
     725            1 : async::Promise<Val> Interactive::open(const UriQuery& uri)
     726              : {
     727            1 :     return openAsync(uri);
     728              : }
     729              : 
     730            2 : Promise<Val> Interactive::openAsync(const UriQuery& q)
     731              : {
     732            2 :     return doOpenAsync(openFunc(q));
     733              : }
     734              : 
     735            0 : async::Promise<Val> Interactive::openAsync(const Uri& uri, const QVariantMap& params)
     736              : {
     737            0 :     return doOpenAsync(openFunc(UriQuery(uri), params));
     738              : }
     739              : 
     740            2 : Promise<Val> Interactive::doOpenAsync(const Promise<Val>::BodyResolveReject& open)
     741              : {
     742            4 :     return async::make_promise<Val>([this, open](auto resolve, auto reject) {
     743              :         //! NOTE The opening may fail synchronously, before the caller subscribes to the returned promise,
     744              :         //! so the handlers are attached before it starts, and the failure is reported later
     745            2 :         Promise<Val>::Resolve openResolve;
     746            2 :         Promise<Val>::Reject openReject;
     747            2 :         Promise<Val> opening = async::make_promise<Val>([&openResolve, &openReject](auto res, auto rej) {
     748            2 :             openResolve = res;
     749            2 :             openReject = rej;
     750            2 :             return Promise<Val>::Result::unchecked();
     751              :         }, PromiseType::AsyncByBody);
     752              : 
     753            2 :         opening.onResolve(this, [resolve](const Val& val) {
     754            0 :             (void)resolve(val);
     755              :         });
     756              : 
     757            2 :         opening.onReject(this, [this, reject](int code, const std::string& msg) {
     758            2 :             Async::call(this, [reject, code, msg]() {
     759            2 :                 (void)reject(code, msg);
     760              :             });
     761              :         });
     762              : 
     763            2 :         open(openResolve, openReject);
     764              : 
     765            4 :         return Promise<Val>::Result::unchecked();
     766            6 :     }, PromiseType::AsyncByBody);
     767              : }
     768              : 
     769            2 : Promise<Val>::BodyResolveReject Interactive::openFunc(const UriQuery& q)
     770              : {
     771            2 :     QVariantMap params;
     772            2 :     const UriQuery::Params& p = q.params();
     773           13 :     for (auto it = p.cbegin(); it != p.cend(); ++it) {
     774           11 :         params[QString::fromStdString(it->first)] = it->second.toQVariant();
     775              :     }
     776              : 
     777            4 :     return openFunc(q, params);
     778            2 : }
     779              : 
     780            2 : Promise<Val>::BodyResolveReject Interactive::openFunc(const UriQuery& q, const QVariantMap& params)
     781              : {
     782            2 :     auto func = [this, q, params](Promise<Val>::Resolve resolve, Promise<Val>::Reject reject) {
     783            2 :         IF_ASSERT_FAILED(!m_openingObject.objectId.isValid()) {
     784            0 :             LOGE() << "The opening of the previous object has not been completed"
     785            0 :                    << ", objectId: " << m_openingObject.objectId.toString()
     786            0 :                    << ", query: " << m_openingObject.query.toString();
     787              :         }
     788              : 
     789            2 :         m_openingObject = { q, resolve, reject, QVariant(), nullptr };
     790              : 
     791            2 :         RetVal<OpenData> openedRet;
     792              : 
     793            2 :         notifyAboutCurrentUriWillBeChanged();
     794              : 
     795              :         //! NOTE Currently, extensions do not replace the default functionality
     796              :         //! But in the future, we may allow extensions to replace the current functionality
     797              :         //! (first check for the presence of an extension with this uri,
     798              :         //! and if it is found, then open it)
     799              : 
     800            2 :         ContainerMeta openMeta = uriRegister()->meta(q.uri());
     801            2 :         switch (openMeta.type) {
     802            0 :         case ContainerMeta::QWidgetDialog:
     803            0 :             openedRet = openWidgetDialog(q.uri(), params);
     804            0 :             break;
     805            0 :         case ContainerMeta::PrimaryPage:
     806              :         case ContainerMeta::QmlDialog:
     807            0 :             openedRet = openQml(q.uri(), params);
     808            0 :             break;
     809            2 :         case ContainerMeta::Undefined: {
     810            2 :             openedRet.ret = make_ret(Ret::Code::UnknownError);
     811            2 :         } break;
     812              :         }
     813              : 
     814            2 :         if (!openedRet.ret) {
     815            2 :             LOGE() << "failed open err: " << openedRet.ret.toString() << ", uri: " << q.toString();
     816            2 :             return reject(openedRet.ret.code(), openedRet.ret.text());
     817              :         }
     818              : 
     819            0 :         return Promise<Val>::Result::unchecked();
     820            6 :     };
     821              : 
     822            4 :     return func;
     823            2 : }
     824              : 
     825            0 : RetVal<bool> Interactive::isOpened(const UriQuery& uri) const
     826              : {
     827            0 :     for (const ObjectInfo& objectInfo: allOpenObjects()) {
     828            0 :         if (objectInfo.query == uri) {
     829            0 :             return RetVal<bool>::make_ok(true);
     830              :         }
     831            0 :     }
     832              : 
     833            0 :     return RetVal<bool>::make_ok(false);
     834              : }
     835              : 
     836            0 : RetVal<bool> Interactive::isOpened(const Uri& uri) const
     837              : {
     838            0 :     for (const ObjectInfo& objectInfo: allOpenObjects()) {
     839            0 :         if (objectInfo.query.uri() == uri) {
     840            0 :             return RetVal<bool>::make_ok(true);
     841              :         }
     842            0 :     }
     843              : 
     844            0 :     return RetVal<bool>::make_ok(false);
     845              : }
     846              : 
     847            0 : RetVal<bool> Interactive::isOpened(const QString& objectId) const
     848              : {
     849            0 :     for (const ObjectInfo& objectInfo: allOpenObjects()) {
     850            0 :         if (objectInfo.objectId == objectId) {
     851            0 :             return RetVal<bool>::make_ok(true);
     852              :         }
     853            0 :     }
     854              : 
     855            0 :     return RetVal<bool>::make_ok(false);
     856              : }
     857              : 
     858            0 : async::Channel<Uri> Interactive::opened() const
     859              : {
     860            0 :     return m_opened;
     861              : }
     862              : 
     863            0 : void Interactive::raise(const UriQuery& uri)
     864              : {
     865            0 :     for (const ObjectInfo& objectInfo: allOpenObjects()) {
     866            0 :         if (objectInfo.query != uri) {
     867            0 :             continue;
     868              :         }
     869              : 
     870            0 :         ContainerMeta openMeta = uriRegister()->meta(objectInfo.query.uri());
     871            0 :         switch (openMeta.type) {
     872            0 :         case ContainerMeta::QWidgetDialog: {
     873            0 :             if (auto window = dynamic_cast<QWidget*>(objectInfo.window)) {
     874            0 :                 window->raise();
     875            0 :                 window->activateWindow();
     876              :             }
     877            0 :         } break;
     878            0 :         case ContainerMeta::QmlDialog:
     879            0 :             raiseQml(objectInfo.objectId);
     880            0 :             break;
     881            0 :         case ContainerMeta::PrimaryPage:
     882              :         case ContainerMeta::Undefined:
     883            0 :             break;
     884              :         }
     885            0 :     }
     886            0 : }
     887              : 
     888            0 : Promise<Ret> Interactive::close(const UriQuery& uri)
     889              : {
     890            0 :     std::vector<ObjectInfo> objs = collectOpenObjects([&uri](const ObjectInfo& obj) {
     891            0 :         return obj.query == uri;
     892            0 :     });
     893              : 
     894            0 :     return closeObjects(objs);
     895            0 : }
     896              : 
     897            0 : Promise<Ret> Interactive::close(const Uri& uri)
     898              : {
     899            0 :     std::vector<ObjectInfo> objs = collectOpenObjects([&uri](const ObjectInfo& obj) {
     900            0 :         return obj.query.uri() == uri;
     901            0 :     });
     902              : 
     903            0 :     return closeObjects(objs);
     904            0 : }
     905              : 
     906            0 : Ret Interactive::closeSync(const UriQuery& uri)
     907              : {
     908            0 :     std::vector<ObjectInfo> objs = collectOpenObjects([&uri](const ObjectInfo& obj) {
     909            0 :         return obj.query == uri;
     910            0 :     });
     911              : 
     912            0 :     return closeObjectsSync(objs);
     913            0 : }
     914              : 
     915            0 : Promise<Ret> Interactive::closeAllDialogs()
     916              : {
     917            0 :     return closeObjects(openDialogs());
     918              : }
     919              : 
     920            0 : Ret Interactive::closeAllDialogsSync()
     921              : {
     922            0 :     return closeObjectsSync(openDialogs());
     923              : }
     924              : 
     925            0 : std::vector<Interactive::ObjectInfo> Interactive::openDialogs() const
     926              : {
     927            0 :     return collectOpenObjects([this](const ObjectInfo& obj) {
     928            0 :         if (muse::diagnostics::isDiagnosticsUri(obj.query.uri())) {
     929            0 :             return false;
     930              :         }
     931            0 :         ContainerMeta meta = uriRegister()->meta(obj.query.uri());
     932            0 :         return meta.type == ContainerMeta::QWidgetDialog || meta.type == ContainerMeta::QmlDialog;
     933            0 :     });
     934              : }
     935              : 
     936            0 : Promise<Ret> Interactive::closeObjects(const std::vector<ObjectInfo>& objs)
     937              : {
     938            0 :     return async::make_promise<Ret>([this, objs](auto resolve, auto) {
     939            0 :         if (objs.empty()) {
     940            0 :             return resolve(make_ok());
     941              :         }
     942              : 
     943            0 :         auto count = std::make_shared<size_t>(objs.size());
     944            0 :         auto ret = std::make_shared<Ret>(make_ok());
     945              : 
     946            0 :         for (const ObjectInfo& obj : objs) {
     947            0 :             const QString objectId = obj.objectId.toString();
     948            0 :             bool ok = m_onClosedFuncs.try_emplace(objectId, [this, objectId, count, ret, resolve](const Ret& funcRet) {
     949            0 :                 if (!funcRet) {
     950            0 :                     *ret = funcRet;
     951              :                 }
     952              : 
     953            0 :                 if (--(*count) == 0) {
     954            0 :                     (void)resolve(*ret);
     955              :                 }
     956              : 
     957            0 :                 muse::remove(m_onClosedFuncs, objectId);
     958              :             }).second;
     959              : 
     960            0 :             IF_ASSERT_FAILED(ok) {
     961            0 :                 if (--(*count) == 0) {
     962            0 :                     (void)resolve(*ret);
     963              :                 }
     964            0 :                 continue;
     965              :             }
     966              : 
     967            0 :             ContainerMeta meta = uriRegister()->meta(obj.query.uri());
     968            0 :             switch (meta.type) {
     969            0 :                 case ContainerMeta::QWidgetDialog: {
     970            0 :                     if (auto window = dynamic_cast<QWidget*>(obj.window)) {
     971            0 :                         ok = window->close();
     972              :                     } else {
     973            0 :                         ok = false;
     974              :                     }
     975            0 :                 } break;
     976            0 :                 case ContainerMeta::QmlDialog:
     977            0 :                     closeQml(obj.objectId);
     978            0 :                     break;
     979            0 :                 case ContainerMeta::PrimaryPage:
     980              :                 case ContainerMeta::Undefined:
     981            0 :                     break;
     982              :             }
     983              : 
     984            0 :             if (!ok) {
     985            0 :                 if (auto it = m_onClosedFuncs.find(objectId); it != m_onClosedFuncs.end()) {
     986            0 :                     it->second(make_ret(Ret::Code::UnknownError));
     987              :                 }
     988              :             }
     989              :         }
     990              : 
     991            0 :         return Promise<Ret>::dummy_result();
     992            0 :     });
     993              : }
     994              : 
     995            0 : Ret Interactive::closeObjectsSync(const std::vector<ObjectInfo>& objs)
     996              : {
     997            0 :     if (objs.empty()) {
     998            0 :         return make_ok();
     999              :     }
    1000              : 
    1001            0 :     QEventLoop loop;
    1002            0 :     Ret ret = make_ok();
    1003              : 
    1004            0 :     closeObjects(objs).onResolve(this, [&loop, &ret](const Ret& closeRet) {
    1005            0 :         ret = closeRet;
    1006            0 :         loop.quit();
    1007            0 :     });
    1008              : 
    1009            0 :     loop.exec();
    1010              : 
    1011            0 :     return ret;
    1012            0 : }
    1013              : 
    1014            0 : void Interactive::fillData(QmlLaunchData* data, const Uri& uri, const QVariantMap& params) const
    1015              : {
    1016            0 :     ContainerMeta meta = uriRegister()->meta(uri);
    1017            0 :     data->setValue("module", meta.qmlModule);
    1018            0 :     data->setValue("path", meta.qmlPath);
    1019            0 :     data->setValue("type", meta.type);
    1020            0 :     data->setValue("uri", QString::fromStdString(uri.toString()));
    1021            0 :     data->setValue("params", params);
    1022            0 :     data->setValue("modal", params.value("modal", ""));
    1023            0 : }
    1024              : 
    1025            0 : void Interactive::fillData(QObject* object, const QVariantMap& params) const
    1026              : {
    1027            0 :     const QMetaObject* metaObject = object->metaObject();
    1028            0 :     for (int i = 0; i < metaObject->propertyCount(); i++) {
    1029            0 :         QMetaProperty metaProperty = metaObject->property(i);
    1030            0 :         if (params.contains(metaProperty.name())) {
    1031            0 :             object->setProperty(metaProperty.name(), params[metaProperty.name()]);
    1032              :         }
    1033              :     }
    1034            0 : }
    1035              : 
    1036            0 : ValCh<Uri> Interactive::currentUri() const
    1037              : {
    1038            0 :     ValCh<Uri> v;
    1039            0 :     if (!m_stack.empty()) {
    1040            0 :         v.val = m_stack.last().query.uri();
    1041              :     }
    1042            0 :     v.ch = m_currentUriChanged;
    1043            0 :     return v;
    1044            0 : }
    1045              : 
    1046            0 : RetVal<bool> Interactive::isCurrentUriDialog() const
    1047              : {
    1048            0 :     if (m_stack.empty()) {
    1049            0 :         return RetVal<bool>::make_ok(false);
    1050              :     }
    1051              : 
    1052            0 :     const ObjectInfo& last = m_stack.last();
    1053            0 :     if (!last.window) {
    1054            0 :         return RetVal<bool>::make_ok(false);
    1055              :     }
    1056              : 
    1057            0 :     return RetVal<bool>::make_ok(last.window != mainWindow()->qWindow());
    1058              : }
    1059              : 
    1060            0 : async::Notification Interactive::currentUriAboutToBeChanged() const
    1061              : {
    1062            0 :     return m_currentUriAboutToBeChanged;
    1063              : }
    1064              : 
    1065            0 : std::vector<Uri> Interactive::stack() const
    1066              : {
    1067            0 :     std::vector<Uri> uris;
    1068            0 :     for (const ObjectInfo& info : m_stack) {
    1069            0 :         uris.push_back(info.query.uri());
    1070              :     }
    1071            0 :     return uris;
    1072            0 : }
    1073              : 
    1074            0 : QWindow* Interactive::topWindow() const
    1075              : {
    1076            0 :     QWindow* mainWin = mainWindow()->qWindow();
    1077            0 :     if (!mainWin) {
    1078            0 :         mainWin = qApp->focusWindow();
    1079              :     }
    1080              : 
    1081            0 :     if (m_stack.empty()) {
    1082            0 :         LOGE() << "stack is empty";
    1083            0 :         return mainWin;
    1084              :     }
    1085              : 
    1086            0 :     const ObjectInfo& last = m_stack.last();
    1087            0 :     if (!last.window) {
    1088            0 :         return mainWin;
    1089              :     }
    1090              : 
    1091            0 :     if (last.window == mainWin) {
    1092            0 :         return mainWin;
    1093              :     }
    1094              : 
    1095              :     // TODO/HACK: last.window doesn't seem to have a parent when the top window is a widget....
    1096            0 :     if (!last.window->parent() && !topWindowIsWidget()) {
    1097            0 :         ASSERT_X("Window must have a parent!");
    1098              :     }
    1099              : 
    1100            0 :     if (!last.window->isWidgetType()) {
    1101            0 :         QWindow* qwindow = qobject_cast<QWindow*>(last.window);
    1102            0 :         IF_ASSERT_FAILED(qwindow) {
    1103            0 :             return mainWin;
    1104              :         }
    1105            0 :         return qwindow;
    1106              :     }
    1107              : 
    1108              :     // QWidget
    1109            0 :     QWidget* qwidget = qobject_cast<QWidget*>(last.window);
    1110            0 :     QWindow* qwindow = qwidget->windowHandle();
    1111            0 :     IF_ASSERT_FAILED(qwindow) {
    1112            0 :         return mainWin;
    1113              :     }
    1114            0 :     return qwindow;
    1115              : }
    1116              : 
    1117            0 : bool Interactive::topWindowIsWidget() const
    1118              : {
    1119            0 :     if (m_stack.empty()) {
    1120            0 :         return false;
    1121              :     }
    1122              : 
    1123            0 :     const ObjectInfo& last = m_stack.last();
    1124            0 :     if (!last.window) {
    1125            0 :         return false;
    1126              :     }
    1127              : 
    1128            0 :     return last.window->isWidgetType();
    1129              : }
    1130              : 
    1131            0 : QString Interactive::objectId(const QVariant& val) const
    1132              : {
    1133              :     static int count(0);
    1134              : 
    1135            0 :     ++count;
    1136              : 
    1137            0 :     QString objectId;
    1138            0 :     if (val.canConvert<QObject*>()) {
    1139            0 :         QObject* obj = val.value<QObject*>();
    1140            0 :         IF_ASSERT_FAILED(obj) {
    1141            0 :             return QString();
    1142              :         }
    1143              : 
    1144            0 :         objectId = QString(obj->metaObject()->className()) + "_" + QString::number(count);
    1145              :     } else {
    1146            0 :         objectId = "unknown_" + QString::number(count);
    1147              :     }
    1148            0 :     return "object://" + objectId;
    1149            0 : }
    1150              : 
    1151            0 : Ret Interactive::toRet(const QVariant& jsr) const
    1152              : {
    1153            0 :     QVariantMap jsobj = jsr.toMap();
    1154            0 :     IF_ASSERT_FAILED(jsobj.contains("errcode")) {
    1155            0 :         return make_ret(Ret::Code::UnknownError);
    1156              :     }
    1157              : 
    1158            0 :     Ret ret;
    1159            0 :     ret.setCode(jsobj.value("errcode").toInt());
    1160            0 :     ret.setText(jsobj.value("text").toString().toStdString());
    1161            0 :     return ret;
    1162            0 : }
    1163              : 
    1164            0 : RetVal<Val> Interactive::toRetVal(const QVariant& jsrv) const
    1165              : {
    1166            0 :     RetVal<Val> rv;
    1167            0 :     QVariantMap jsobj = jsrv.toMap();
    1168              : 
    1169            0 :     IF_ASSERT_FAILED(jsobj.contains("errcode")) {
    1170            0 :         rv.ret = make_ret(Ret::Code::UnknownError);
    1171            0 :         return rv;
    1172              :     }
    1173              : 
    1174            0 :     int errcode = jsobj.value("errcode").toInt();
    1175            0 :     QVariant val = jsobj.value("value");
    1176              : 
    1177            0 :     rv.ret.setCode(errcode);
    1178            0 :     rv.val = Val::fromQVariant(val);
    1179              : 
    1180            0 :     return rv;
    1181            0 : }
    1182              : 
    1183            0 : RetVal<Interactive::OpenData> Interactive::openWidgetDialog(const Uri& uri, const QVariantMap& params)
    1184              : {
    1185            0 :     RetVal<OpenData> result;
    1186              : 
    1187            0 :     ContainerMeta meta = uriRegister()->meta(uri);
    1188            0 :     int widgetMetaTypeId = meta.widgetMetaTypeId;
    1189              : 
    1190              :     static int count(0);
    1191            0 :     QString objectId = QString("%1_%2").arg(widgetMetaTypeId).arg(++count);
    1192              : 
    1193            0 :     QMetaType metaType = QMetaType(widgetMetaTypeId);
    1194            0 :     ui::WidgetDialog* dialog = static_cast<ui::WidgetDialog*>(metaType.create());
    1195              : 
    1196            0 :     if (!dialog) {
    1197            0 :         result.ret = make_ret(Ret::Code::UnknownError);
    1198            0 :         return result;
    1199              :     }
    1200              : 
    1201            0 :     dialog->setProperty("ioc_context", iocContext()->id);
    1202              : 
    1203            0 :     dialog->classBegin();
    1204              : 
    1205            0 :     fillData(dialog, params);
    1206              : 
    1207            0 :     dialog->componentComplete();
    1208              : 
    1209              :     //! NOTE Will be deleted with the dialog
    1210            0 :     WidgetDialogAdapter* adapter = new WidgetDialogAdapter(dialog);
    1211            0 :     adapter->onShow([this, objectId, dialog]() {
    1212            0 :         if (isOpened(objectId).val) {
    1213            0 :             LOGE() << "Dialog is already opened: " << objectId << ", ignoring this show event";
    1214            0 :             return;
    1215              :         }
    1216              : 
    1217            0 :         async::Async::call(this, [this, objectId, dialog]() {
    1218            0 :             QQmlEngine::setObjectOwnership(dialog, QQmlEngine::CppOwnership);
    1219            0 :             QQmlEngine::setObjectOwnership(dialog->windowHandle(), QQmlEngine::CppOwnership);
    1220            0 :             onOpen(ContainerMeta::QWidgetDialog, objectId, dialog->window());
    1221            0 :         });
    1222              :     })
    1223            0 :     .onHide([this, objectId, dialog]() {
    1224            0 :         if (!isOpened(objectId).val) {
    1225            0 :             LOGE() << "Dialog is not opened: " << objectId << ", ignoring this hide event";
    1226            0 :             return;
    1227              :         }
    1228              : 
    1229            0 :         QDialog::DialogCode dialogCode = static_cast<QDialog::DialogCode>(dialog->result());
    1230            0 :         Ret::Code errorCode = dialogCode == QDialog::Accepted ? Ret::Code::Ok : Ret::Code::Cancel;
    1231              : 
    1232            0 :         QVariantMap ret;
    1233            0 :         ret["errcode"] = static_cast<int>(errorCode);
    1234              : 
    1235            0 :         onClose(objectId, ret);
    1236              : 
    1237            0 :         dialog->deleteLater();
    1238            0 :     });
    1239              : 
    1240            0 :     bool modal = params.value("modal", "true") == "true";
    1241            0 :     dialog->setWindowModality(modal ? Qt::ApplicationModal : Qt::NonModal);
    1242            0 :     dialog->show();
    1243            0 :     dialog->activateWindow(); // give keyboard focus to aid blind users
    1244              : 
    1245            0 :     result.ret = make_ret(Ret::Code::Ok);
    1246            0 :     result.val.objectId = objectId;
    1247              : 
    1248            0 :     return result;
    1249            0 : }
    1250              : 
    1251            0 : RetVal<Interactive::OpenData> Interactive::openQml(const Uri& uri, const QVariantMap& params)
    1252              : {
    1253            0 :     QmlLaunchData data;
    1254            0 :     fillData(&data, uri, params);
    1255              : 
    1256            0 :     m_openRequested.send(&data);
    1257              : 
    1258            0 :     RetVal<OpenData> result;
    1259            0 :     result.ret = toRet(data.value("ret"));
    1260            0 :     result.val.objectId = data.value("objectId").toString();
    1261              : 
    1262            0 :     return result;
    1263            0 : }
    1264              : 
    1265            0 : void Interactive::closeQml(const QVariant& objectId)
    1266              : {
    1267            0 :     m_closeRequested.send(objectId);
    1268            0 : }
    1269              : 
    1270            0 : void Interactive::raiseQml(const QVariant& objectId)
    1271              : {
    1272            0 :     m_raiseRequested.send(objectId);
    1273            0 : }
    1274              : 
    1275            0 : void Interactive::onOpen(const QVariant& type, const QVariant& objectId, QObject* window)
    1276              : {
    1277            0 :     ContainerMeta::Type containerMeta = type.value<ContainerMeta::Type>();
    1278              : 
    1279            0 :     IF_ASSERT_FAILED(containerMeta != ContainerMeta::Undefined) {
    1280            0 :         containerMeta = ContainerMeta::QmlDialog;
    1281              :     }
    1282              : 
    1283            0 :     m_openingObject.objectId = objectId;
    1284            0 :     m_openingObject.window = window;
    1285            0 :     if (!m_openingObject.window) {
    1286            0 :         m_openingObject.window = (containerMeta == ContainerMeta::PrimaryPage) ? mainWindow()->qWindow() : qApp->focusWindow();
    1287              :     }
    1288              : 
    1289            0 :     if (m_openingObject.query.param("floating").toBool()) {
    1290            0 :         m_floatingObjects.push_back(m_openingObject);
    1291            0 :         m_openingObject = ObjectInfo(); // clear
    1292            0 :         return;
    1293              :     }
    1294              : 
    1295            0 :     if (ContainerMeta::PrimaryPage == containerMeta) {
    1296              :         // Replace bottom item of the stack, because that always reflects the current PrimaryPage
    1297            0 :         if (m_stack.empty()) {
    1298            0 :             m_stack.push(m_openingObject);
    1299              :         } else {
    1300            0 :             m_stack[0] = m_openingObject;
    1301              :         }
    1302            0 :     } else if (ContainerMeta::QmlDialog == containerMeta) {
    1303            0 :         m_stack.push(m_openingObject);
    1304            0 :     } else if (ContainerMeta::QWidgetDialog == containerMeta) {
    1305            0 :         m_stack.push(m_openingObject);
    1306              :     } else {
    1307            0 :         IF_ASSERT_FAILED_X(false, "unknown page type") {
    1308              :             m_stack.push(m_openingObject);
    1309              :         }
    1310              :     }
    1311              : 
    1312            0 :     notifyAboutCurrentUriChanged();
    1313              : 
    1314            0 :     if (ContainerMeta::PrimaryPage == containerMeta && m_openingObject.resolve) {
    1315            0 :         auto resolve = m_openingObject.resolve;
    1316            0 :         Async::call(this, [resolve]() {
    1317            0 :             (void)resolve(Val(true));
    1318            0 :         });
    1319            0 :     }
    1320              : 
    1321            0 :     Uri uri = m_openingObject.query.uri();
    1322            0 :     m_openingObject = ObjectInfo(); // clear
    1323              : 
    1324            0 :     Async::call(this, [this, uri]() {
    1325            0 :         m_opened.send(uri);
    1326            0 :     });
    1327            0 : }
    1328              : 
    1329            0 : void Interactive::onClose(const QString& objectId, const QVariant& jsrv)
    1330              : {
    1331            0 :     RetVal<Val> rv = toRetVal(jsrv);
    1332              : 
    1333            0 :     ObjectInfo obj;
    1334              : 
    1335            0 :     bool inStack = false;
    1336            0 :     for (int i = 0; i < m_stack.size(); ++i) {
    1337            0 :         if (m_stack.at(i).objectId == objectId) {
    1338            0 :             obj = m_stack.at(i);
    1339            0 :             inStack = true;
    1340            0 :             m_stack.remove(i);
    1341            0 :             break;
    1342              :         }
    1343              :     }
    1344              : 
    1345            0 :     if (!inStack) {
    1346            0 :         for (size_t i = 0; i < m_floatingObjects.size(); ++i) {
    1347            0 :             if (m_floatingObjects.at(i).objectId == objectId) {
    1348            0 :                 obj = m_floatingObjects.at(i);
    1349            0 :                 m_floatingObjects.erase(m_floatingObjects.begin() + i);
    1350            0 :                 break;
    1351              :             }
    1352              :         }
    1353              :     }
    1354              : 
    1355            0 :     DO_ASSERT(obj.objectId.isValid());
    1356              : 
    1357            0 :     if (rv.ret) {
    1358            0 :         (void)obj.resolve(rv.val);
    1359              :     } else {
    1360            0 :         (void)obj.reject(rv.ret.code(), rv.ret.text());
    1361              :     }
    1362              : 
    1363            0 :     if (inStack) {
    1364            0 :         notifyAboutCurrentUriChanged();
    1365              :     }
    1366              : 
    1367            0 :     Async::call(this, [this, objectId, rv]() {
    1368            0 :         auto onClosedIt = m_onClosedFuncs.find(objectId);
    1369            0 :         if (onClosedIt != m_onClosedFuncs.end()) {
    1370            0 :             onClosedIt->second(rv.ret);
    1371              :         }
    1372            0 :     });
    1373            0 : }
    1374              : 
    1375            0 : std::vector<Interactive::ObjectInfo> Interactive::allOpenObjects() const
    1376              : {
    1377            0 :     std::vector<ObjectInfo> result;
    1378              : 
    1379            0 :     result.insert(result.end(), m_stack.cbegin(), m_stack.cend());
    1380            0 :     result.insert(result.end(), m_floatingObjects.cbegin(), m_floatingObjects.cend());
    1381              : 
    1382            0 :     return result;
    1383            0 : }
    1384              : 
    1385            0 : std::vector<Interactive::ObjectInfo> Interactive::collectOpenObjects(std::function<bool(const ObjectInfo&)> accepted) const
    1386              : {
    1387            0 :     std::vector<ObjectInfo> result;
    1388            0 :     for (const ObjectInfo& obj : allOpenObjects()) {
    1389            0 :         if (accepted(obj)) {
    1390            0 :             result.push_back(obj);
    1391              :         }
    1392            0 :     }
    1393              : 
    1394            0 :     return result;
    1395            0 : }
    1396              : 
    1397            0 : void Interactive::notifyAboutCurrentUriChanged()
    1398              : {
    1399            0 :     m_currentUriChanged.send(currentUri().val);
    1400            0 : }
    1401              : 
    1402            2 : void Interactive::notifyAboutCurrentUriWillBeChanged()
    1403              : {
    1404            2 :     m_currentUriAboutToBeChanged.notify();
    1405            2 : }
        

Generated by: LCOV version 2.0-1