LCOV - code coverage report
Current view: top level - src/project/internal - saveprojectscenario.cpp Coverage Total Hit
Test: filtered_coverage.info Lines: 61.7 % 1218 752
Test Date: 2026-11-19 04:14:36

            Line data    Source code
       1              : /*
       2              :  * SPDX-License-Identifier: GPL-3.0-only
       3              :  * MuseScore-Studio-CLA-applies
       4              :  *
       5              :  * MuseScore Studio
       6              :  * Music Composition & Notation
       7              :  *
       8              :  * Copyright (C) 2026 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 "saveprojectscenario.h"
      24              : 
      25              : #include <QBuffer>
      26              : #include <QFile>
      27              : #include <QFileInfo>
      28              : #include <QTemporaryFile>
      29              : #include <QUrl>
      30              : 
      31              : #include "defer.h"
      32              : #include "translation.h"
      33              : 
      34              : #include "cloud/clouderrors.h"
      35              : #include "cloud/qml/Muse/Cloud/enums.h"
      36              : #include "engraving/infrastructure/mscio.h"
      37              : 
      38              : #include "notation/imasternotation.h"
      39              : #include "notation/inotation.h"
      40              : #include "notation/inotationinteraction.h"
      41              : 
      42              : #include "inotationproject.h"
      43              : #include "projecterrors.h"
      44              : #include "types/projecturis.h"
      45              : 
      46              : #include "log.h"
      47              : 
      48              : using namespace mu::project;
      49              : using namespace mu::notation;
      50              : using namespace muse;
      51              : using muse::async::Promise;
      52              : 
      53              : template<typename T>
      54          100 : static Promise<T> resolvedPromise(const T& value)
      55              : {
      56          300 :     return async::make_promise<T>([value](auto resolve) {
      57          100 :         return resolve(value);
      58          200 :     });
      59              : }
      60              : 
      61              : static constexpr int RETRY_SAVE_BTN_ID = int(IInteractive::Button::CustomButton);
      62              : static constexpr int SAVE_AS_BTN_ID    = RETRY_SAVE_BTN_ID + 1;
      63              : 
      64          141 : INotationProjectPtr SaveProjectScenario::currentNotationProject() const
      65              : {
      66          141 :     return projectSession()->project();
      67              : }
      68              : 
      69           28 : INotationInteractionPtr SaveProjectScenario::currentInteraction() const
      70              : {
      71           28 :     INotationProjectPtr project = currentNotationProject();
      72           28 :     if (!project || !project->masterNotation() || !project->masterNotation()->notation()) {
      73            0 :         return nullptr;
      74              :     }
      75              : 
      76           28 :     return project->masterNotation()->notation()->interaction();
      77           28 : }
      78              : 
      79           51 : bool SaveProjectScenario::isBusy(BusyStatus status) const
      80              : {
      81           51 :     return m_busyStatuses.contains(status);
      82              : }
      83              : 
      84          105 : void SaveProjectScenario::setBusy(BusyStatus status, bool isBusy)
      85              : {
      86          105 :     bool wasBusy = m_busyStatuses.contains(status);
      87          105 :     if (wasBusy == isBusy) {
      88           13 :         return;
      89              :     }
      90              : 
      91           92 :     if (isBusy) {
      92           46 :         m_busyStatuses.insert(status);
      93              :     } else {
      94           46 :         m_busyStatuses.erase(status);
      95              :     }
      96              : 
      97           92 :     m_busyChanged.notify();
      98              : }
      99              : 
     100            0 : muse::async::Notification SaveProjectScenario::busyChanged() const
     101              : {
     102            0 :     return m_busyChanged;
     103              : }
     104              : 
     105           49 : Promise<Ret> SaveProjectScenario::runIfNotBusy(BusyStatus status, const std::function<Promise<Ret>()>& flow)
     106              : {
     107           49 :     if (isBusy(status)) {
     108            3 :         return resolvedPromise(make_ret(Ret::Code::Busy));
     109              :     }
     110              : 
     111           46 :     setBusy(status, true);
     112              : 
     113           92 :     return flow().then<Ret>(this, [this, status](const Ret& ret, auto resolve) {
     114           46 :         setBusy(status, false);
     115           46 :         return resolve(ret);
     116           46 :     });
     117              : }
     118              : 
     119           12 : Promise<RetVal<Val> > SaveProjectScenario::openDialog(const UriQuery& query) const
     120              : {
     121           24 :     return async::make_promise<RetVal<Val> >([this, query](auto resolve) {
     122           12 :         interactive()->open(query)
     123           24 :         .onResolve(this, [resolve](const Val& val) {
     124           10 :             (void)resolve(RetVal<Val>::make_ok(val));
     125              :         })
     126           12 :         .onReject(this, [resolve](int code, const std::string& err) {
     127            2 :             (void)resolve(RetVal<Val>(muse::make_ret(code, err)));
     128              :         });
     129              : 
     130           12 :         return Promise<RetVal<Val> >::dummy_result();
     131           24 :     });
     132              : }
     133              : 
     134            1 : Promise<Ret> SaveProjectScenario::shareAudio()
     135              : {
     136            1 :     return shareAudio(AudioFile());
     137              : }
     138              : 
     139           32 : Ret SaveProjectScenario::canSaveProject() const
     140              : {
     141           32 :     auto project = currentNotationProject();
     142           32 :     if (!project) {
     143            0 :         LOGW() << "no current project";
     144            0 :         return make_ret(Err::NoProjectError);
     145              :     }
     146              : 
     147           32 :     return project->canSave();
     148           32 : }
     149              : 
     150            5 : Promise<Ret> SaveProjectScenario::saveProject(const muse::io::path_t& path)
     151              : {
     152            5 :     if (path.empty()) {
     153            1 :         return saveProject(SaveMode::Save);
     154              :     }
     155              : 
     156            8 :     return runIfNotBusy(BusyStatus::Saving, [this, path]() {
     157            6 :         return saveProjectAt(SaveLocation(SaveLocationType::Local, path));
     158            4 :     });
     159              : }
     160              : 
     161           18 : Promise<Ret> SaveProjectScenario::saveProject(SaveMode saveMode, SaveLocationType saveLocationType, bool force)
     162              : {
     163           36 :     return runIfNotBusy(BusyStatus::Saving, [this, saveMode, saveLocationType, force]() -> Promise<Ret> {
     164           17 :         INotationProjectPtr project = currentNotationProject();
     165           17 :         if (!project) {
     166            1 :             LOGW() << "no current project";
     167            1 :             return resolvedPromise(make_ret(Err::NoProjectError));
     168              :         }
     169              : 
     170           16 :         const bool isExistingSave = saveMode == SaveMode::Save && !project->isNewlyCreated();
     171           16 :         const bool wantNewCloudSave = saveLocationType == SaveLocationType::Cloud && !project->isCloudProject();
     172           16 :         if (isExistingSave && !wantNewCloudSave) {
     173              :             // Under these conditions, we can save without asking...
     174            7 :             SaveLocation location;
     175            7 :             if (project->isCloudProject()) {
     176            2 :                 location = SaveLocation(SaveLocationType::Cloud, project->cloudInfo());
     177              :             } else {
     178            5 :                 location = SaveLocation(SaveLocationType::Local);
     179              :             }
     180            7 :             return saveProjectAt(location, saveMode, force);
     181            7 :         }
     182              : 
     183           18 :         return askSaveLocation(project, saveMode, saveLocationType)
     184            9 :                .then<Ret>(this, [this, saveMode, force](const RetVal<SaveLocation>& response, auto resolve) {
     185            9 :             if (!response.ret) {
     186            7 :                 LOGE() << response.ret.toString();
     187            7 :                 return resolve(response.ret);
     188              :             }
     189              : 
     190            2 :             saveProjectAt(response.val, saveMode, force).onResolve(this, [resolve](const Ret& ret) {
     191            2 :                 (void)resolve(ret);
     192              :             });
     193              : 
     194            2 :             return Promise<Ret>::dummy_result();
     195            9 :         });
     196           53 :     });
     197              : }
     198              : 
     199            6 : Promise<Ret> SaveProjectScenario::publish()
     200              : {
     201           12 :     return runIfNotBusy(BusyStatus::Publishing, [this]() -> Promise<Ret> {
     202            6 :         Ret ret = canSaveProject();
     203            6 :         if (!ret) {
     204              :             //! NOTE The answer leads nowhere here, but the flow is not over while the question is up
     205            0 :             return askIfUserAgreesToSaveProjectWithErrors(ret, SaveLocationType::Cloud)
     206            0 :                    .then<Ret>(this, [ret](bool, auto resolve) {
     207            0 :                 return resolve(ret);
     208            0 :             });
     209              :         }
     210              : 
     211            6 :         auto project = currentNotationProject();
     212              : 
     213           12 :         return askPublishLocation(project)
     214           12 :                .then<Ret>(this, [this, project](const RetVal<CloudProjectInfo>& info, auto resolve) {
     215            6 :             if (info.ret.code() == RET_CODE_CHANGE_SAVE_LOCATION_TYPE) {
     216            2 :                 saveProjectLocallyInstead(project, SaveMode::Save).onResolve(this, [resolve](const Ret& saveRet) {
     217            2 :                     (void)resolve(saveRet);
     218              :                 });
     219              : 
     220            2 :                 return Promise<Ret>::dummy_result();
     221              :             }
     222              : 
     223            4 :             if (!info.ret) {
     224            0 :                 return resolve(info.ret);
     225              :             }
     226              : 
     227            4 :             exportMp3(project->masterNotation()->notation()).onResolve(this, [this, project, info, resolve](const AudioFile& audio) {
     228            4 :                 if (!audio.isValid()) {
     229            1 :                     (void)resolve(make_ret(Ret::Code::BadData));
     230            1 :                     return;
     231              :                 }
     232              : 
     233            6 :                 uploadProject(project, info.val, audio, /*openEditUrl=*/ true, /*publishMode=*/ true)
     234            3 :                 .onResolve(this, [resolve](const Ret& ret) {
     235            3 :                     (void)resolve(ret);
     236              :                 });
     237              :             });
     238              : 
     239            4 :             return Promise<Ret>::dummy_result();
     240            6 :         });
     241           18 :     });
     242              : }
     243              : 
     244            1 : Promise<Ret> SaveProjectScenario::shareAudio(const AudioFile& existingAudio)
     245              : {
     246            2 :     return runIfNotBusy(BusyStatus::AudioSharing, [this, existingAudio]() -> Promise<Ret> {
     247            1 :         auto project = currentNotationProject();
     248            1 :         if (!project) {
     249            1 :             LOGW() << "no current project";
     250            1 :             return resolvedPromise(make_ret(Err::NoProjectError));
     251              :         }
     252              : 
     253            0 :         return askShareAudioLocation(project)
     254            0 :                .then<Ret>(this, [this, project, existingAudio](const RetVal<CloudAudioInfo>& info, auto resolve) {
     255            0 :             if (!info.ret) {
     256            0 :                 return resolve(info.ret);
     257              :             }
     258              : 
     259            0 :             Promise<AudioFile> audioPromise = existingAudio.isValid()
     260            0 :                                               ? resolvedPromise(existingAudio)
     261            0 :                                               : exportMp3(project->masterNotation()->notation());
     262              : 
     263            0 :             audioPromise.onResolve(this, [this, project, info, resolve](const AudioFile& audio) {
     264            0 :                 if (!audio.isValid()) {
     265            0 :                     (void)resolve(make_ret(Ret::Code::BadData));
     266            0 :                     return;
     267              :                 }
     268              : 
     269            0 :                 uploadAudioToAudioCom(audio, project, info.val).onResolve(this, [resolve](const Ret& ret) {
     270            0 :                     (void)resolve(ret);
     271              :                 });
     272              :             });
     273              : 
     274            0 :             return Promise<Ret>::dummy_result();
     275            0 :         });
     276            3 :     });
     277              : }
     278              : 
     279            0 : Promise<Ret> SaveProjectScenario::uploadAudioToAudioCom(const AudioFile& audio, const INotationProjectPtr& project,
     280              :                                                         const CloudAudioInfo& info)
     281              : {
     282            0 :     return async::make_promise<Ret>([this, audio, project, info](auto resolve) {
     283            0 :         m_uploadingAudioProgress = audioComService()->uploadAudio(audio.device, audio.format, info.name,
     284            0 :                                                                   project->cloudAudioInfo().url, info.visibility,
     285            0 :                                                                   info.replaceExisting);
     286            0 :         LOGD() << "Uploading audio started";
     287            0 :         showUploadProgressDialog();
     288              : 
     289            0 :         m_uploadingAudioProgress->progressChanged().onReceive(this, [](int64_t current, int64_t total, const std::string&) {
     290            0 :             if (total > 0) {
     291            0 :                 LOGD() << "Uploading audio progress: " << current << " / " << total << " bytes";
     292              :             }
     293              :         });
     294              : 
     295            0 :         m_uploadingAudioProgress->finished().onReceive(this, [this, project, info, resolve](const ProgressResult& res) {
     296            0 :             LOGD() << "Uploading audio finished";
     297              : 
     298            0 :             m_uploadingAudioProgress->started().disconnect(this);
     299            0 :             m_uploadingAudioProgress->progressChanged().disconnect(this);
     300            0 :             m_uploadingAudioProgress->finished().disconnect(this);
     301              : 
     302            0 :             if (!res.ret) {
     303            0 :                 LOGE() << res.ret.toString();
     304              : 
     305            0 :                 onAudioUploadFailed(res.ret).onResolve(this, [resolve](const Ret& ret) {
     306            0 :                     (void)resolve(ret);
     307              :                 });
     308              : 
     309            0 :                 return;
     310              :             }
     311              : 
     312            0 :             ValMap resMap = res.val.toMap();
     313            0 :             onAudioSuccessfullyUploaded(resMap["editUrl"].toQString());
     314              : 
     315            0 :             if (!info.replaceExisting) {
     316            0 :                 CloudAudioInfo newInfo = project->cloudAudioInfo();
     317            0 :                 newInfo.url = QUrl(resMap["url"].toQString());
     318            0 :                 project->setCloudAudioInfo(newInfo);
     319            0 :             }
     320              : 
     321            0 :             (void)resolve(res.ret);
     322            0 :         });
     323              : 
     324            0 :         return Promise<Ret>::dummy_result();
     325            0 :     });
     326              : }
     327              : 
     328            2 : Promise<Ret> SaveProjectScenario::saveProjectAt(const muse::rcommand::Params& params)
     329              : {
     330            2 :     const std::string& path = params.at("path").toString();
     331            2 :     if (path.empty()) {
     332            1 :         return resolvedPromise(make_ret(Ret::Code::BadArgs));
     333              :     }
     334              : 
     335            2 :     return runIfNotBusy(BusyStatus::Saving, [this, path]() {
     336            2 :         return saveProjectAt(SaveLocation(muse::io::path_t(path)));
     337            1 :     });
     338            2 : }
     339              : 
     340           28 : Promise<Ret> SaveProjectScenario::saveProjectAt(const SaveLocation& location, SaveMode saveMode, bool force)
     341              : {
     342           28 :     INotationInteractionPtr interaction = currentInteraction();
     343           28 :     if (interaction && interaction->isTextEditingStarted()) {
     344            1 :         interaction->endEditText();
     345              :     }
     346              : 
     347           28 :     if (!force) {
     348           26 :         Ret ret = canSaveProject();
     349           26 :         if (!ret) {
     350           10 :             return askIfUserAgreesToSaveProjectWithErrors(ret, location)
     351           10 :                    .then<Ret>(this, [this, location, saveMode, ret](bool agreed, auto resolve) {
     352            5 :                 if (!agreed) {
     353            4 :                     return resolve(ret);
     354              :                 }
     355              : 
     356            1 :                 doSaveProjectAt(location, saveMode).onResolve(this, [resolve](const Ret& saveRet) {
     357            1 :                     (void)resolve(saveRet);
     358              :                 });
     359              : 
     360            1 :                 return Promise<Ret>::dummy_result();
     361            5 :             });
     362              :         }
     363           26 :     }
     364              : 
     365           23 :     return doSaveProjectAt(location, saveMode);
     366           28 : }
     367              : 
     368           24 : Promise<Ret> SaveProjectScenario::doSaveProjectAt(const SaveLocation& location, SaveMode saveMode)
     369              : {
     370           24 :     if (location.isLocal()) {
     371           20 :         return saveProjectLocally(location.localPath(), saveMode);
     372              :     }
     373              : 
     374            4 :     if (location.isCloud()) {
     375            3 :         return saveProjectToCloud(location.cloudInfo(), saveMode);
     376              :     }
     377              : 
     378            1 :     return resolvedPromise(make_ret(Err::UnknownError));
     379              : }
     380              : 
     381           37 : Promise<Ret> SaveProjectScenario::saveProjectLocally(const muse::io::path_t& filePath, SaveMode saveMode, bool createBackup)
     382              : {
     383           37 :     INotationProjectPtr project = currentNotationProject();
     384           37 :     if (!project) {
     385            0 :         return resolvedPromise(make_ret(Err::NoProjectError));
     386              :     }
     387              : 
     388           37 :     Ret ret = project->save(filePath, saveMode, createBackup);
     389              : 
     390           37 :     if (ret) {
     391           31 :         recentFilesController()->prependRecentFile(makeRecentFile(project));
     392           31 :         return resolvedPromise(make_ok());
     393              :     }
     394              : 
     395            6 :     LOGE() << ret.toString();
     396              : 
     397            6 :     if (ret.code() != (int)Err::CorruptionUponSavingError) {
     398            3 :         return warnScoreCouldnotBeSaved(ret);
     399              :     }
     400              : 
     401            6 :     return warnScoreHasBecomeCorruptedAfterSave(ret).then<Ret>(this, [this, filePath, saveMode, ret](int btn, auto resolve) {
     402            3 :         switch (btn) {
     403            1 :             case RETRY_SAVE_BTN_ID: {
     404              :                 // Retry the save. Do not create a backup this time because the target file has been corrupted
     405              :                 // already. Creating a backup file of a corrupted file now makes no sense and will corrupt
     406              :                 // the healthy backup file created on the first save attempt.
     407            1 :                 saveProjectLocally(filePath, saveMode, false /*createBackup*/).onResolve(this, [resolve](const Ret& retryRet) {
     408            1 :                     (void)resolve(retryRet);
     409              :                 });
     410              : 
     411            1 :                 return Promise<Ret>::dummy_result();
     412              :             }
     413              : 
     414            1 :             case SAVE_AS_BTN_ID: {
     415              :                 //! NOTE The save that started this one still holds the status; the new flow takes it over
     416            1 :                 setBusy(BusyStatus::Saving, false);
     417              : 
     418            1 :                 saveProject(SaveMode::SaveAs).onResolve(this, [resolve](const Ret& saveAsRet) {
     419            1 :                     (void)resolve(saveAsRet);
     420              :                 });
     421              : 
     422            1 :                 return Promise<Ret>::dummy_result();
     423              :             }
     424              :         }
     425              : 
     426            1 :         return resolve(ret);
     427            3 :     });
     428           37 : }
     429              : 
     430           19 : Promise<Ret> SaveProjectScenario::saveProjectToCloud(CloudProjectInfo info, SaveMode saveMode)
     431              : {
     432           38 :     return runIfNotBusy(BusyStatus::Uploading, [this, info, saveMode]() {
     433           36 :         return museScoreComService()->authorization()->checkCloudIsAvailable()
     434           36 :                .then<Ret>(this, [this, info, saveMode](const Ret& isCloudAvailable, auto resolve) {
     435           18 :             if (!isCloudAvailable) {
     436            4 :                 warnCloudIsNotAvailable().onResolve(this, [this, info, saveMode, resolve](const Ret&) {
     437            4 :                     INotationProjectPtr project = currentNotationProject();
     438            4 :                     if (!project) {
     439            0 :                         (void)resolve(make_ret(Err::NoProjectError));
     440            0 :                         return;
     441              :                     }
     442              : 
     443            4 :                     saveCloudProjectLocally(project, info, saveMode).onResolve(this, [resolve](const Ret& ret) {
     444            4 :                         (void)resolve(ret);
     445              :                     });
     446            4 :                 });
     447              : 
     448            4 :                 return Promise<Ret>::dummy_result();
     449              :             }
     450              : 
     451           14 :             doSaveProjectToCloud(info, saveMode).onResolve(this, [resolve](const Ret& ret) {
     452           14 :                 (void)resolve(ret);
     453              :             });
     454              : 
     455           14 :             return Promise<Ret>::dummy_result();
     456           36 :         });
     457           38 :     });
     458              : }
     459              : 
     460           14 : Promise<Ret> SaveProjectScenario::doSaveProjectToCloud(const CloudProjectInfo& info, SaveMode saveMode)
     461              : {
     462           14 :     std::string dialogText = muse::trc("project/save", "Log in to MuseScore.com to save this score to the cloud.");
     463              : 
     464           14 :     return ensureAuthorization(muse::cloud::MUSESCORE_COM_CLOUD_CODE, true, dialogText)
     465           28 :            .then<Ret>(this, [this, info, saveMode](const RetVal<Val>& auth, auto resolve) {
     466           14 :         if (!auth.ret) {
     467            1 :             return resolve(auth.ret);
     468              :         }
     469              : 
     470           13 :         INotationProjectPtr project = currentNotationProject();
     471           13 :         if (!project) {
     472            0 :             return resolve(make_ret(Err::NoProjectError));
     473              :         }
     474              : 
     475              :         using Response = muse::cloud::SaveToCloudResponse::SaveToCloudResponse;
     476           13 :         if (static_cast<Response>(auth.val.toInt()) == Response::SaveLocallyInstead) {
     477            2 :             saveProjectLocallyInstead(project, saveMode).onResolve(this, [resolve](const Ret& ret) {
     478            2 :                 (void)resolve(ret);
     479              :             });
     480              : 
     481            2 :             return Promise<Ret>::dummy_result();
     482              :         }
     483              : 
     484           11 :         saveAndUploadProject(project, info, saveMode).onResolve(this, [resolve](const Ret& ret) {
     485           11 :             (void)resolve(ret);
     486              :         });
     487              : 
     488           11 :         return Promise<Ret>::dummy_result();
     489           41 :     });
     490           14 : }
     491              : 
     492           11 : Promise<Ret> SaveProjectScenario::saveAndUploadProject(const INotationProjectPtr& project, CloudProjectInfo info, SaveMode saveMode)
     493              : {
     494           11 :     const bool isPublic = info.visibility == muse::cloud::Visibility::Public;
     495              : 
     496           11 :     if (saveMode != SaveMode::Save) {
     497            7 :         return doSaveAndUploadProject(project, info, saveMode, isPublic);
     498              :     }
     499              : 
     500              :     // Get up-to-date visibility information
     501            8 :     return museScoreComService()->downloadScoreInfo(info.sourceUrl)
     502            8 :            .then<Ret>(this, [this, project, info, saveMode](const RetVal<muse::cloud::ScoreInfo>& scoreInfo, auto resolve) {
     503            4 :         CloudProjectInfo actualInfo = info;
     504              : 
     505            4 :         if (scoreInfo.ret) {
     506            1 :             actualInfo.name = scoreInfo.val.title;
     507            1 :             actualInfo.visibility = scoreInfo.val.visibility;
     508              :         } else {
     509            6 :             LOGE() << "Failed to download up-to-date score info for " << actualInfo.sourceUrl
     510            3 :                    << "; falling back to last known name and visibility setting, namely "
     511            3 :                    << actualInfo.name << " and " << static_cast<int>(actualInfo.visibility);
     512              :         }
     513              : 
     514            4 :         const bool isPublic = actualInfo.visibility == muse::cloud::Visibility::Public;
     515            4 :         if (!isPublic) {
     516            3 :             doSaveAndUploadProject(project, actualInfo, saveMode, isPublic).onResolve(this, [resolve](const Ret& ret) {
     517            3 :                 (void)resolve(ret);
     518              :             });
     519              : 
     520            3 :             return Promise<Ret>::dummy_result();
     521              :         }
     522              : 
     523            1 :         warnBeforeSavingToExistingPubliclyVisibleCloudProject()
     524            1 :         .onResolve(this, [this, project, actualInfo, saveMode, isPublic, resolve](bool agreed) {
     525            1 :             if (!agreed) {
     526            1 :                 (void)resolve(make_ret(Ret::Code::Cancel));
     527            1 :                 return;
     528              :             }
     529              : 
     530            0 :             doSaveAndUploadProject(project, actualInfo, saveMode, isPublic).onResolve(this, [resolve](const Ret& ret) {
     531            0 :                 (void)resolve(ret);
     532              :             });
     533              :         });
     534              : 
     535            1 :         return Promise<Ret>::dummy_result();
     536            8 :     });
     537              : }
     538              : 
     539           10 : Promise<Ret> SaveProjectScenario::doSaveAndUploadProject(const INotationProjectPtr& project, const CloudProjectInfo& info,
     540              :                                                          SaveMode saveMode, bool isPublic)
     541              : {
     542           20 :     return needGenerateAudio(isPublic)
     543           20 :            .then<Ret>(this, [this, project, info, saveMode, isPublic](const RetVal<bool>& need, auto resolve) {
     544           10 :         if (!need.ret) {
     545            0 :             return resolve(need.ret);
     546              :         }
     547              : 
     548           10 :         const bool generateAudio = need.val;
     549              : 
     550           10 :         saveCloudProjectLocally(project, info, saveMode)
     551           10 :         .onResolve(this, [this, project, info, isPublic, generateAudio, resolve](const Ret& saveRet) {
     552           10 :             if (!saveRet) {
     553            0 :                 (void)resolve(saveRet);
     554            0 :                 return;
     555              :             }
     556              : 
     557           10 :             Promise<AudioFile> audioPromise = generateAudio
     558           20 :                                               ? exportMp3(project->masterNotation()->notation())
     559           19 :                                               : resolvedPromise(AudioFile());
     560              : 
     561           10 :             audioPromise.onResolve(this, [this, project, info, isPublic, generateAudio, resolve](const AudioFile& audio) {
     562           10 :                 if (generateAudio && !audio.isValid()) {
     563            1 :                     (void)resolve(make_ret(Ret::Code::BadData));
     564            1 :                     return;
     565              :                 }
     566              : 
     567           18 :                 uploadProject(project, info, audio, /*openEditUrl=*/ isPublic, /*publishMode=*/ false)
     568            9 :                 .onResolve(this, [this, resolve](const Ret& ret) {
     569            9 :                     if (ret) {
     570            5 :                         m_numberOfSavesToCloud++;
     571              :                     }
     572            9 :                     (void)resolve(ret);
     573              :                 });
     574              :             });
     575           10 :         });
     576              : 
     577           10 :         return Promise<Ret>::dummy_result();
     578           20 :     });
     579              : }
     580              : 
     581           14 : Promise<Ret> SaveProjectScenario::saveCloudProjectLocally(const INotationProjectPtr& project, const CloudProjectInfo& info,
     582              :                                                           SaveMode saveMode)
     583              : {
     584              :     // TODO(cloud): is this correct for all save modes?
     585           14 :     project->setCloudInfo(info);
     586              : 
     587           14 :     muse::io::path_t savingPath;
     588              : 
     589           14 :     if (project->isCloudProject()) {
     590            3 :         if (saveMode == SaveMode::Save || saveMode == SaveMode::AutoSave) {
     591            3 :             savingPath = project->path();
     592              :         }
     593              :     }
     594              : 
     595           14 :     if (savingPath.empty()) {
     596           12 :         ID scoreId = muse::cloud::idFromCloudUrl(info.sourceUrl);
     597              : 
     598           12 :         savingPath = configuration()->cloudProjectSavingPath(scoreId.toUint64());
     599              :     }
     600              : 
     601           28 :     return saveProjectLocally(savingPath, saveMode);
     602           14 : }
     603              : 
     604            4 : Promise<Ret> SaveProjectScenario::saveProjectLocallyInstead(const INotationProjectPtr& project, SaveMode saveMode)
     605              : {
     606            8 :     return askLocalPath(project, saveMode)
     607            4 :            .then<Ret>(this, [this, saveMode](const RetVal<muse::io::path_t>& path, auto resolve) {
     608            4 :         if (!path.ret) {
     609            2 :             LOGE() << path.ret.toString();
     610            2 :             return resolve(path.ret);
     611              :         }
     612              : 
     613            2 :         saveProjectLocally(path.val, saveMode).onResolve(this, [this, resolve](const Ret& ret) {
     614            2 :             configuration()->setLastUsedSaveLocationType(SaveLocationType::Local);
     615              : 
     616            2 :             (void)resolve(ret);
     617              :         });
     618              : 
     619            2 :         return Promise<Ret>::dummy_result();
     620            8 :     });
     621              : }
     622              : 
     623            0 : Promise<Ret> SaveProjectScenario::alsoShareAudioCom(const AudioFile& audio)
     624              : {
     625            0 :     if (!configuration()->showAlsoShareAudioComDialog()) {
     626            0 :         return shareAudio(audio);
     627              :     }
     628              : 
     629            0 :     UriQuery query("musescore://project/alsoshareaudiocom");
     630            0 :     query.addParam("rememberChoice", Val(!configuration()->hasAskedAlsoShareAudioCom()));
     631              : 
     632            0 :     auto audioHolder = std::make_shared<AudioFile>(audio);
     633              : 
     634            0 :     return openDialog(query).then<Ret>(this, [this, audioHolder](const RetVal<Val>& rv, auto resolve) {
     635            0 :         const AudioFile audio = *audioHolder;
     636            0 :         *audioHolder = AudioFile();
     637              : 
     638            0 :         DEFER {
     639            0 :             configuration()->setHasAskedAlsoShareAudioCom(true);
     640              :         };
     641              : 
     642            0 :         if (rv.val.isNull()) {
     643            0 :             return resolve(make_ret(Ret::Code::Cancel));
     644              :         }
     645              : 
     646            0 :         QVariantMap vals = rv.val.toQVariant().toMap();
     647            0 :         bool shareAudioCom = vals["share"].toBool();
     648            0 :         bool rememberChoice = vals["remember"].toBool();
     649              : 
     650            0 :         configuration()->setShowAlsoShareAudioComDialog(!rememberChoice);
     651            0 :         configuration()->setAlsoShareAudioCom(shareAudioCom);
     652              : 
     653            0 :         if (!shareAudioCom) {
     654            0 :             return resolve(make_ok());
     655              :         }
     656              : 
     657            0 :         shareAudio(audio).onResolve(this, [resolve](const Ret& ret) {
     658            0 :             (void)resolve(ret);
     659              :         });
     660              : 
     661            0 :         return Promise<Ret>::dummy_result();
     662            0 :     });
     663            0 : }
     664              : 
     665            1 : Promise<Ret> SaveProjectScenario::askAudioGenerationSettings() const
     666              : {
     667            3 :     return openDialog(UriQuery("musescore://project/audiogenerationsettings"))
     668            1 :            .then<Ret>(this, [this](const RetVal<Val>& res, auto resolve) {
     669            1 :         if (!res.ret) {
     670            0 :             return resolve(res.ret);
     671              :         }
     672              : 
     673            1 :         configuration()->setHasAskedAudioGenerationSettings(true);
     674              : 
     675            1 :         return resolve(make_ok());
     676            2 :     });
     677              : }
     678              : 
     679           17 : Promise<RetVal<bool> > SaveProjectScenario::needGenerateAudio(bool isPublicUpload) const
     680              : {
     681           17 :     if (isPublicUpload) {
     682            2 :         return resolvedPromise(RetVal<bool>::make_ok(true));
     683              :     }
     684              : 
     685           15 :     if (configuration()->hasAskedAudioGenerationSettings()) {
     686           14 :         return resolvedPromise(RetVal<bool>::make_ok(needGenerateAudioAccordingToSettings()));
     687              :     }
     688              : 
     689            2 :     return askAudioGenerationSettings().then<RetVal<bool> >(this, [this](const Ret& ret, auto resolve) {
     690            1 :         if (!ret) {
     691            0 :             return resolve(RetVal<bool>(ret));
     692              :         }
     693              : 
     694            1 :         return resolve(RetVal<bool>::make_ok(needGenerateAudioAccordingToSettings()));
     695            1 :     });
     696              : }
     697              : 
     698           15 : bool SaveProjectScenario::needGenerateAudioAccordingToSettings() const
     699              : {
     700           15 :     switch (configuration()->generateAudioTimePeriodType()) {
     701           11 :     case GenerateAudioTimePeriodType::Never:
     702           11 :         return false;
     703            1 :     case GenerateAudioTimePeriodType::Always:
     704            1 :         return true;
     705            3 :     case GenerateAudioTimePeriodType::AfterCertainNumberOfSaves: {
     706            3 :         int requiredNumberOfSaves = configuration()->numberOfSavesToGenerateAudio();
     707            3 :         if (requiredNumberOfSaves <= 0) {
     708            1 :             LOGW() << "invalid number of saves to generate audio: " << requiredNumberOfSaves;
     709            1 :             return true;
     710              :         }
     711              : 
     712            2 :         return m_numberOfSavesToCloud % requiredNumberOfSaves == 0;
     713              :     }
     714              :     }
     715              : 
     716            0 :     return false;
     717              : }
     718              : 
     719            5 : Promise<SaveProjectScenario::AudioFile> SaveProjectScenario::exportMp3(const INotationPtr notation) const
     720              : {
     721            5 :     QString mp3Path;
     722              :     {
     723            5 :         QTemporaryFile tempFile(configuration()->temporaryMp3FilePathTemplate().toQString());
     724            5 :         if (!tempFile.open()) {
     725            0 :             LOGE() << "Could not create a temp file";
     726            0 :             return resolvedPromise(AudioFile());
     727              :         }
     728              : 
     729            5 :         mp3Path = QFileInfo(tempFile).absoluteFilePath();
     730            5 :     }
     731              : 
     732            5 :     LOGD() << "mp3 path: " << mp3Path;
     733              : 
     734            5 :     if (mp3Path.isEmpty()) {
     735            0 :         LOGE() << "mp3 path is empty";
     736            0 :         return resolvedPromise(AudioFile());
     737              :     }
     738              : 
     739              :     // In the uploaded audio file, the repeats need to be expanded
     740            5 :     bool wasExpandRepeats = notationConfiguration()->isPlayRepeatsEnabled();
     741            5 :     if (!wasExpandRepeats) {
     742            5 :         notationConfiguration()->setIsPlayRepeatsEnabled(true);
     743              :     }
     744              : 
     745           25 :     return exportProjectScenario()->exportScores({ notation }, mp3Path)
     746           10 :            .then<AudioFile>(this, [this, mp3Path, wasExpandRepeats](const Ret& ret, auto resolve) {
     747            5 :         if (!wasExpandRepeats) {
     748            5 :             notationConfiguration()->setIsPlayRepeatsEnabled(false);
     749              :         }
     750              : 
     751            5 :         if (!ret) {
     752            2 :             LOGE() << "Could not export an mp3: " << ret.toString();
     753            2 :             fileSystem()->remove(mp3Path);
     754            2 :             return resolve(AudioFile());
     755              :         }
     756              : 
     757            6 :         std::shared_ptr<QFile> exportedFile(new QFile(mp3Path), [this](QFile* file) {
     758            3 :             file->close();
     759            3 :             fileSystem()->remove(file->fileName());
     760            3 :             delete file;
     761              :         });
     762              : 
     763            3 :         if (!exportedFile->open(QIODevice::ReadOnly)) {
     764            0 :             LOGE() << "Could not reopen exported mp3: " << mp3Path;
     765            0 :             return resolve(AudioFile());
     766              :         }
     767              : 
     768            3 :         AudioFile audio;
     769            3 :         audio.format = "mp3";
     770            3 :         audio.device = exportedFile;
     771              : 
     772            3 :         return resolve(audio);
     773            8 :     });
     774           10 : }
     775              : 
     776           11 : void SaveProjectScenario::showUploadProgressDialog()
     777              : {
     778           11 :     if (interactive()->isOpened(UPLOAD_PROGRESS_URI).val) {
     779            0 :         return;
     780              :     }
     781              : 
     782           11 :     interactive()->open(UPLOAD_PROGRESS_URI);
     783              : }
     784              : 
     785           15 : void SaveProjectScenario::closeUploadProgressDialog()
     786              : {
     787           15 :     if (interactive()->isOpened(UPLOAD_PROGRESS_URI).val) {
     788            0 :         interactive()->close(UriQuery(UPLOAD_PROGRESS_URI));
     789              :     }
     790           15 : }
     791              : 
     792           13 : Promise<Ret> SaveProjectScenario::uploadProject(INotationProjectPtr project, const CloudProjectInfo& info, const AudioFile& audio,
     793              :                                                 bool openEditUrl, bool publishMode)
     794              : {
     795           26 :     return async::make_promise<Ret>([this, project, info, audio, openEditUrl, publishMode](auto resolve) {
     796           13 :         if (!project) {
     797            0 :             return resolve(make_ret(Err::NoProjectError));
     798              :         }
     799              : 
     800           13 :         auto projectData = std::make_shared<QBuffer>();
     801           13 :         projectData->open(QIODevice::WriteOnly);
     802              : 
     803           13 :         Ret ret = project->writeToDevice(projectData.get());
     804           13 :         if (!ret) {
     805            2 :             LOGE() << ret.toString();
     806            2 :             return resolve(ret);
     807              :         }
     808              : 
     809           11 :         projectData->close();
     810           11 :         projectData->open(QIODevice::ReadOnly);
     811              : 
     812           11 :         bool isFirstSave = info.sourceUrl.isEmpty();
     813              : 
     814           22 :         ProgressPtr progress = museScoreComService()->uploadScore(projectData, info.name, info.visibility, info.sourceUrl,
     815           11 :                                                                   info.revisionId);
     816           11 :         m_uploadingProjectProgress = progress;
     817              : 
     818           11 :         showUploadProgressDialog();
     819           11 :         LOGD() << "Uploading project started";
     820              : 
     821           11 :         progress->progressChanged().onReceive(this, [](int64_t current, int64_t total, const std::string&) {
     822            0 :             if (total > 0) {
     823            0 :                 LOGD() << "Uploading project progress: " << current << " / " << total << " bytes";
     824              :             }
     825              :         });
     826              : 
     827           11 :         progress->finished().onReceive(this, [this, project, info, audio, openEditUrl, publishMode,
     828              :                                               isFirstSave, progress, resolve](const ProgressResult& res) {
     829           11 :             progress->progressChanged().disconnect(this);
     830           11 :             progress->finished().disconnect(this);
     831              : 
     832           11 :             if (!res.ret) {
     833            4 :                 LOGE() << res.ret.toString();
     834            8 :                 onProjectUploadFailed(project, res.ret, info, audio, openEditUrl, publishMode)
     835            4 :                 .onResolve(this, [resolve](const Ret& failRet) {
     836            4 :                     (void)resolve(failRet);
     837              :                 });
     838            6 :                 return;
     839              :             }
     840              : 
     841            7 :             ValMap urlMap = res.val.toMap();
     842            7 :             QString newSourceUrl = urlMap["sourceUrl"].toQString();
     843           11 :             QString editUrl = openEditUrl ? urlMap["editUrl"].toQString() : QString();
     844            7 :             int newRevisionId = urlMap["revisionId"].toInt();
     845              : 
     846            7 :             LOGD() << "Source url received: " << newSourceUrl;
     847              : 
     848            7 :             CloudProjectInfo cpinfo = project->cloudInfo();
     849            7 :             if (cpinfo.sourceUrl != newSourceUrl || cpinfo.revisionId != newRevisionId) {
     850              :                 // TODO(cloud): does this work correctly with different save modes?
     851            1 :                 cpinfo.sourceUrl = newSourceUrl;
     852            1 :                 cpinfo.revisionId = newRevisionId;
     853            1 :                 project->setCloudInfo(cpinfo);
     854              : 
     855            1 :                 if (!project->isNewlyCreated()) {
     856            1 :                     project->save();
     857              :                 }
     858              : 
     859            1 :                 if (project->isCloudProject()) {
     860            0 :                     moveProject(project, configuration()->cloudProjectPath(muse::cloud::idFromCloudUrl(cpinfo.sourceUrl).toUint64()), true);
     861              :                 }
     862              :             }
     863              : 
     864            7 :             if (audio.isValid()) {
     865            6 :                 uploadAudioToMuseScoreCom(audio, newSourceUrl, editUrl, isFirstSave, publishMode).onResolve(this,
     866            4 :                                                                                                             [resolve](const Ret& ret) {
     867            2 :                     (void)resolve(ret);
     868              :                 });
     869            2 :                 return;
     870              :             }
     871              : 
     872            5 :             onUploadFinished(editUrl, isFirstSave, audio, publishMode).onResolve(this, [res, resolve](const Ret&) {
     873            5 :                 (void)resolve(res.ret);
     874              :             });
     875           13 :         });
     876              : 
     877           11 :         return Promise<Ret>::dummy_result();
     878           39 :     });
     879              : }
     880              : 
     881            2 : Promise<Ret> SaveProjectScenario::uploadAudioToMuseScoreCom(const AudioFile& audio, const QUrl& sourceUrl, const QUrl& urlToOpen,
     882              :                                                             bool isFirstSave, bool publishMode)
     883              : {
     884            4 :     return async::make_promise<Ret>([this, audio, sourceUrl, urlToOpen, isFirstSave, publishMode](auto resolve) {
     885            2 :         m_uploadingAudioProgress = museScoreComService()->uploadAudio(audio.device, audio.format, sourceUrl);
     886              : 
     887            2 :         m_uploadingAudioProgress->progressChanged().onReceive(this, [](int64_t current, int64_t total, const std::string&) {
     888            0 :             if (total > 0) {
     889            0 :                 LOGD() << "Uploading audio progress: " << current << " / " << total << " bytes";
     890              :             }
     891              :         });
     892              : 
     893            2 :         m_uploadingAudioProgress->finished().onReceive(this, [this, audio, urlToOpen, isFirstSave, publishMode,
     894              :                                                               resolve](const ProgressResult& res) {
     895            2 :             LOGD() << "Uploading audio finished";
     896              : 
     897            2 :             if (!res.ret) {
     898            0 :                 LOGE() << res.ret.toString();
     899              :             }
     900              : 
     901            2 :             m_uploadingAudioProgress->progressChanged().disconnect(this);
     902            2 :             m_uploadingAudioProgress->finished().disconnect(this);
     903              : 
     904            2 :             onUploadFinished(urlToOpen, isFirstSave, audio, publishMode).onResolve(this, [res, resolve](const Ret&) {
     905            2 :                 (void)resolve(res.ret);
     906              :             });
     907              :         });
     908              : 
     909            2 :         return Promise<Ret>::dummy_result();
     910            4 :     });
     911              : }
     912              : 
     913            7 : Promise<Ret> SaveProjectScenario::onUploadFinished(const QUrl& urlToOpen, bool isFirstSave, const AudioFile& audio, bool publishMode)
     914              : {
     915              :     //! NOTE The exported audio has to outlive the message, because publishing offers to share it too.
     916              :     //! It is held through a holder the offer empties: what a resolved callback captured stays alive,
     917              :     //! and that would keep the temporary mp3 on disk.
     918            7 :     auto audioHolder = std::make_shared<AudioFile>(audio);
     919              : 
     920            7 :     return onProjectSuccessfullyUploaded(urlToOpen, isFirstSave)
     921           14 :            .then<Ret>(this, [this, audioHolder, publishMode](const Ret&, auto resolve) {
     922            7 :         const AudioFile sharedAudio = *audioHolder;
     923            7 :         *audioHolder = AudioFile();
     924              : 
     925            7 :         if (!publishMode || !(configuration()->alsoShareAudioCom() || configuration()->showAlsoShareAudioComDialog())) {
     926            7 :             return resolve(make_ok());
     927              :         }
     928              : 
     929            0 :         alsoShareAudioCom(sharedAudio).onResolve(this, [resolve](const Ret& ret) {
     930            0 :             (void)resolve(ret);
     931              :         });
     932              : 
     933            0 :         return Promise<Ret>::dummy_result();
     934           21 :     });
     935            7 : }
     936              : 
     937            7 : Promise<Ret> SaveProjectScenario::onProjectSuccessfullyUploaded(const QUrl& urlToOpen, bool isFirstSave)
     938              : {
     939            7 :     setBusy(BusyStatus::Uploading, false);
     940              : 
     941            7 :     closeUploadProgressDialog();
     942              : 
     943            7 :     if (!urlToOpen.isEmpty()) {
     944            0 :         platformInteractive()->openUrl(urlToOpen);
     945            0 :         return resolvedPromise(make_ok());
     946              :     }
     947              : 
     948            7 :     QUrl scoreManagerUrl = this->scoreManagerUrl();
     949              : 
     950            7 :     if (configuration()->openDetailedProjectUploadedDialog()) {
     951            0 :         UriQuery query("musescore://project/upload/success");
     952            0 :         query.addParam("scoreManagerUrl", Val(scoreManagerUrl.toString()));
     953            0 :         configuration()->setOpenDetailedProjectUploadedDialog(false);
     954              : 
     955            0 :         return openDialog(query).then<Ret>(this, [](const RetVal<Val>&, auto resolve) {
     956            0 :             return resolve(make_ok());
     957            0 :         });
     958            0 :     }
     959              : 
     960            7 :     if (!isFirstSave) {
     961            3 :         return resolvedPromise(make_ok());
     962              :     }
     963              : 
     964            4 :     IInteractive::ButtonData viewOnlineBtn(IInteractive::Button::CustomButton, muse::trc("project/save", "View online"));
     965            4 :     IInteractive::ButtonData okBtn = interactive()->buttonData(IInteractive::Button::Ok);
     966              : 
     967              :     std::string msg = muse::trc("project/save", "All saved changes will now update to the cloud. "
     968            4 :                                                 "You can manage this file in the score manager on MuseScore.com.");
     969              : 
     970           24 :     return interactive()->info(muse::trc("global", "Success!"), msg, { viewOnlineBtn, okBtn },
     971              :                                static_cast<int>(IInteractive::Button::Ok))
     972            8 :            .then<Ret>(this, [this, viewOnlineBtn, scoreManagerUrl](const IInteractive::Result& res, auto resolve) {
     973            4 :         if (res.isButton(viewOnlineBtn.btn)) {
     974            0 :             platformInteractive()->openUrl(scoreManagerUrl);
     975              :         }
     976              : 
     977            4 :         return resolve(make_ok());
     978            4 :     });
     979           11 : }
     980              : 
     981            4 : Promise<Ret> SaveProjectScenario::onProjectUploadFailed(INotationProjectPtr project, const Ret& ret, const CloudProjectInfo& info,
     982              :                                                         const AudioFile& audio, bool openEditUrl, bool publishMode)
     983              : {
     984            4 :     setBusy(BusyStatus::Uploading, false);
     985              : 
     986            4 :     closeUploadProgressDialog();
     987              : 
     988              :     //! NOTE The exported audio has to outlive the question, because a retry uploads it again.
     989              :     //! It is held through a holder the answer empties: what a resolved callback captured
     990              :     //! stays alive, and that would keep the temporary mp3 on disk.
     991            4 :     auto audioHolder = std::make_shared<AudioFile>(audio);
     992              : 
     993            4 :     return showCloudSaveError(ret, info, publishMode, true)
     994            8 :            .then<Ret>(this, [this, project, ret, info, audioHolder, openEditUrl, publishMode](const Ret& userResponse, auto resolve) {
     995            4 :         const AudioFile audio = *audioHolder;
     996            4 :         *audioHolder = AudioFile();
     997              : 
     998            4 :         switch (userResponse.code()) {
     999            1 :             case RET_CODE_CONFLICT_RESPONSE_SAVE_AS: {
    1000              :                 // The save that started this upload still holds the status; the new flow takes it over
    1001            1 :                 setBusy(BusyStatus::Saving, false);
    1002              : 
    1003            1 :                 saveProject(SaveMode::SaveAs).onResolve(this, [resolve](const Ret& saveRet) {
    1004            1 :                     (void)resolve(saveRet);
    1005              :                 });
    1006              : 
    1007            1 :                 return Promise<Ret>::dummy_result();
    1008              :             }
    1009            1 :             case RET_CODE_CONFLICT_RESPONSE_PUBLISH_AS_NEW_SCORE: {
    1010            1 :                 CloudProjectInfo newInfo = info;
    1011            1 :                 newInfo.sourceUrl = QUrl();
    1012              : 
    1013            1 :                 uploadProject(project, newInfo, audio, openEditUrl, publishMode).onResolve(this, [resolve](const Ret& uploadRet) {
    1014            1 :                     (void)resolve(uploadRet);
    1015              :                 });
    1016              : 
    1017            1 :                 return Promise<Ret>::dummy_result();
    1018            1 :             }
    1019            0 :             case RET_CODE_CONFLICT_RESPONSE_REPLACE: {
    1020            0 :                 museScoreComService()->downloadScoreInfo(info.sourceUrl)
    1021            0 :                 .onResolve(this, [this, project, ret, info, audio, openEditUrl, publishMode,
    1022              :                                   resolve](const RetVal<muse::cloud::ScoreInfo>& scoreInfo) {
    1023            0 :                     if (!scoreInfo.ret) {
    1024            0 :                         LOGE() << scoreInfo.ret.toString();
    1025            0 :                         showCloudSaveError(scoreInfo.ret, info, publishMode, false);
    1026            0 :                         (void)resolve(ret);
    1027            0 :                         return;
    1028              :                     }
    1029              : 
    1030            0 :                     CloudProjectInfo newInfo = info;
    1031            0 :                     newInfo.revisionId = scoreInfo.val.revisionId;
    1032              : 
    1033            0 :                     uploadProject(project, newInfo, audio, openEditUrl, publishMode).onResolve(this, [resolve](const Ret& uploadRet) {
    1034            0 :                         (void)resolve(uploadRet);
    1035              :                     });
    1036            0 :                 });
    1037              : 
    1038            0 :                 return Promise<Ret>::dummy_result();
    1039              :             }
    1040            2 :             default:
    1041            2 :                 break;
    1042              :         }
    1043              : 
    1044            2 :         return resolve(ret);
    1045           12 :     });
    1046            4 : }
    1047              : 
    1048            0 : void SaveProjectScenario::onAudioSuccessfullyUploaded(const QUrl& urlToOpen)
    1049              : {
    1050            0 :     closeUploadProgressDialog();
    1051              : 
    1052            0 :     platformInteractive()->openUrl(urlToOpen);
    1053            0 : }
    1054              : 
    1055            0 : Promise<Ret> SaveProjectScenario::onAudioUploadFailed(const Ret& ret)
    1056              : {
    1057            0 :     closeUploadProgressDialog();
    1058              : 
    1059            0 :     return showAudioCloudShareError(ret);
    1060              : }
    1061              : 
    1062            4 : Promise<Ret> SaveProjectScenario::warnCloudIsNotAvailable()
    1063              : {
    1064            4 :     closeUploadProgressDialog();
    1065              : 
    1066            4 :     if (!configuration()->showCloudIsNotAvailableWarning()) {
    1067            4 :         return resolvedPromise(make_ok());
    1068              :     }
    1069              : 
    1070            0 :     std::string title = muse::trc("project/save", "Unable to connect to the cloud");
    1071            0 :     std::string msg = muse::trc("project/save", "Your changes will be saved to a local file until the connection resumes.");
    1072              : 
    1073            0 :     return interactive()->warning(title, msg,
    1074              :                                   { IInteractive::Button::Ok }, IInteractive::Button::Ok,
    1075            0 :                                   IInteractive::Option::WithIcon | IInteractive::Option::WithDontShowAgainCheckBox)
    1076            0 :            .then<Ret>(this, [this](const IInteractive::Result& res, auto resolve) {
    1077            0 :         configuration()->setShowCloudIsNotAvailableWarning(res.showAgain());
    1078              : 
    1079            0 :         return resolve(make_ok());
    1080            0 :     });
    1081            0 : }
    1082              : 
    1083            2 : Promise<bool> SaveProjectScenario::refuseSaveAfter(Promise<Ret> shown)
    1084              : {
    1085            2 :     return shown.then<bool>(this, [](const Ret&, auto resolve) {
    1086            2 :         return resolve(false);
    1087            4 :     });
    1088              : }
    1089              : 
    1090            5 : Promise<bool> SaveProjectScenario::askIfUserAgreesToSaveProjectWithErrors(const Ret& ret, const SaveLocation& location)
    1091              : {
    1092            5 :     switch (static_cast<Err>(ret.code())) {
    1093            1 :     case Err::NoPartsError:
    1094            1 :         return refuseSaveAfter(warnScoreCouldnotBeSaved(muse::trc("project/save", "Please add at least one instrument to enable saving.")));
    1095            1 :     case Err::CorruptionUponOpenningError:
    1096            1 :         return askIfUserAgreesToSaveCorruptedScoreUponOpenning(location, ret.text());
    1097            3 :     case Err::CorruptionError: {
    1098            3 :         auto project = currentNotationProject();
    1099            3 :         return askIfUserAgreesToSaveCorruptedScore(location, ret.text(), project->isNewlyCreated());
    1100            3 :     }
    1101            0 :     default:
    1102            0 :         return resolvedPromise(false);
    1103              :     }
    1104              : }
    1105              : 
    1106            3 : Promise<bool> SaveProjectScenario::askIfUserAgreesToSaveCorruptedScore(const SaveLocation& location, const std::string& errorText,
    1107              :                                                                        bool newlyCreated)
    1108              : {
    1109            3 :     switch (location.type) {
    1110            0 :     case SaveLocationType::Cloud: {
    1111              :         Promise<Ret> shown = newlyCreated
    1112            0 :                              ? showErrCorruptedScoreCannotBeSaved(location, errorText)
    1113            0 :                              : warnCorruptedScoreCannotBeSavedOnCloud(errorText, !newlyCreated);
    1114              : 
    1115            0 :         return refuseSaveAfter(shown);
    1116            0 :     }
    1117            3 :     case SaveLocationType::Local:
    1118            3 :         return askIfUserAgreesToSaveCorruptedScoreLocally(errorText, !newlyCreated);
    1119            0 :     case SaveLocationType::Undefined:     // fallthrough
    1120              :     default:
    1121            0 :         return resolvedPromise(false);
    1122              :     }
    1123              : }
    1124              : 
    1125            0 : Promise<Ret> SaveProjectScenario::warnCorruptedScoreCannotBeSavedOnCloud(const std::string& errorText, bool canRevert)
    1126              : {
    1127            0 :     std::string title = muse::trc("project", "Your score cannot be uploaded to the cloud");
    1128              : 
    1129            0 :     IInteractive::Text text;
    1130            0 :     text.text = muse::trc("project", "This score has become corrupted and contains errors. "
    1131              :                                      "You can fix the errors manually, or save the score to your computer "
    1132            0 :                                      "and get help for this issue on MuseScore.org.");
    1133            0 :     text.detailedText = errorText;
    1134              : 
    1135            0 :     IInteractive::ButtonDatas buttons;
    1136            0 :     buttons.push_back(interactive()->buttonData(IInteractive::Button::Cancel));
    1137              : 
    1138            0 :     IInteractive::ButtonData saveCopyBtn(IInteractive::Button::CustomButton, muse::trc("project", "Save as…"), !canRevert /*accent*/);
    1139            0 :     buttons.push_back(saveCopyBtn);
    1140              : 
    1141            0 :     int defaultBtn = saveCopyBtn.btn;
    1142              : 
    1143            0 :     IInteractive::ButtonData revertToLastSavedBtn(saveCopyBtn.btn + 1, muse::trc("project", "Revert to last saved"),
    1144            0 :                                                   true /*accent*/);
    1145              : 
    1146            0 :     if (canRevert) {
    1147            0 :         buttons.push_back(revertToLastSavedBtn);
    1148            0 :         defaultBtn = revertToLastSavedBtn.btn;
    1149              :     }
    1150              : 
    1151            0 :     return interactive()->error(title, text, buttons, defaultBtn)
    1152            0 :            .then<Ret>(this, [this, saveCopyBtn, revertToLastSavedBtn](const IInteractive::Result& res, auto resolve) {
    1153            0 :         int btn = res.button();
    1154              : 
    1155            0 :         if (btn == saveCopyBtn.btn) {
    1156              :             //! NOTE The save that ran into this still holds the status; the new flow takes it over
    1157            0 :             setBusy(BusyStatus::Saving, false);
    1158              : 
    1159            0 :             saveProject(SaveMode::SaveAs, SaveLocationType::Local, true /*force*/)
    1160            0 :             .onResolve(this, [resolve](const Ret& ret) {
    1161            0 :                 (void)resolve(ret);
    1162              :             });
    1163              : 
    1164            0 :             return Promise<Ret>::dummy_result();
    1165              :         }
    1166              : 
    1167            0 :         if (btn == revertToLastSavedBtn.btn) {
    1168            0 :             askToRevertCorruptedScoreToLastSaved().onResolve(this, [resolve](const Ret& ret) {
    1169            0 :                 (void)resolve(ret);
    1170              :             });
    1171              : 
    1172            0 :             return Promise<Ret>::dummy_result();
    1173              :         }
    1174              : 
    1175            0 :         return resolve(make_ret(Ret::Code::Cancel));
    1176            0 :     });
    1177            0 : }
    1178              : 
    1179            3 : Promise<bool> SaveProjectScenario::askIfUserAgreesToSaveCorruptedScoreLocally(const std::string& errorText,
    1180              :                                                                               bool canRevert)
    1181              : {
    1182            3 :     std::string title = muse::trc("project", "This score has become corrupted and contains errors");
    1183              : 
    1184            3 :     IInteractive::Text text;
    1185            3 :     text.text = !canRevert
    1186            6 :                 ? muse::trc("project", "You can continue saving it locally, although the file may become unusable. "
    1187              :                                        "You can try to fix the errors manually, or get help for this issue on MuseScore.org.")
    1188              :                 : muse::trc("project", "You can continue saving it locally, although the file may become unusable. "
    1189              :                                        "To preserve your score, revert to the last saved version, or fix the errors manually. "
    1190            3 :                                        "You can also get help for this issue on MuseScore.org.");
    1191            3 :     text.detailedText = errorText;
    1192              : 
    1193            3 :     IInteractive::ButtonDatas buttons;
    1194            3 :     buttons.push_back(interactive()->buttonData(IInteractive::Button::Cancel));
    1195              : 
    1196            3 :     IInteractive::ButtonData saveAnywayBtn(IInteractive::Button::CustomButton, muse::trc("project", "Save anyway"),
    1197            3 :                                            !canRevert /*accent*/);
    1198            3 :     buttons.push_back(saveAnywayBtn);
    1199              : 
    1200            3 :     int defaultBtn = saveAnywayBtn.btn;
    1201              : 
    1202            6 :     IInteractive::ButtonData revertToLastSavedBtn(saveAnywayBtn.btn + 1, muse::trc("project", "Revert to last saved"),
    1203            3 :                                                   true /*accent*/);
    1204            3 :     if (canRevert) {
    1205            3 :         buttons.push_back(revertToLastSavedBtn);
    1206            3 :         defaultBtn = revertToLastSavedBtn.btn;
    1207              :     }
    1208              : 
    1209            6 :     return interactive()->error(title, text, buttons, defaultBtn)
    1210            6 :            .then<bool>(this, [this, saveAnywayBtn, revertToLastSavedBtn](const IInteractive::Result& res, auto resolve) {
    1211            3 :         if (res.isButton(revertToLastSavedBtn.btn)) {
    1212            2 :             askToRevertCorruptedScoreToLastSaved().onResolve(this, [resolve](const Ret&) {
    1213            2 :                 (void)resolve(false);
    1214              :             });
    1215              : 
    1216            2 :             return Promise<bool>::dummy_result();
    1217              :         }
    1218              : 
    1219            1 :         return resolve(res.isButton(saveAnywayBtn.btn));
    1220            6 :     });
    1221            3 : }
    1222              : 
    1223            1 : Promise<bool> SaveProjectScenario::askIfUserAgreesToSaveCorruptedScoreUponOpenning(const SaveLocation& location,
    1224              :                                                                                    const std::string& errorText)
    1225              : {
    1226            1 :     switch (location.type) {
    1227            1 :     case SaveLocationType::Cloud:
    1228            1 :         return refuseSaveAfter(showErrCorruptedScoreCannotBeSaved(location, errorText));
    1229            0 :     case SaveLocationType::Local:
    1230            0 :         return askIfUserAgreesToSaveCorruptedScoreLocally(errorText, false /*canRevert*/);
    1231            0 :     case SaveLocationType::Undefined:     // fallthrough
    1232              :     default:
    1233            0 :         return resolvedPromise(false);
    1234              :     }
    1235              : }
    1236              : 
    1237            1 : Promise<Ret> SaveProjectScenario::showErrCorruptedScoreCannotBeSaved(const SaveLocation& location, const std::string& errorText)
    1238              : {
    1239            1 :     std::string title = location.isLocal()
    1240            1 :                         ? muse::trc("project", "Your score cannot be saved")
    1241            1 :                         : muse::trc("project", "Your score cannot be uploaded to the cloud");
    1242              : 
    1243            1 :     IInteractive::Text text;
    1244            1 :     text.text = muse::trc("project", "This score is corrupted. You can get help for this issue on MuseScore.org.");
    1245            1 :     text.detailedText = errorText;
    1246              : 
    1247            1 :     IInteractive::ButtonData getHelpBtn(IInteractive::Button::CustomButton, muse::trc("project", "Get help"));
    1248              : 
    1249            6 :     return interactive()->error(title, text, {
    1250              :         getHelpBtn,
    1251            1 :         interactive()->buttonData(IInteractive::Button::Ok)
    1252            2 :     }).then<Ret>(this, [this, getHelpBtn](const IInteractive::Result& res, auto resolve) {
    1253            1 :         if (res.isButton(getHelpBtn.btn)) {
    1254            0 :             platformInteractive()->openUrl(configuration()->supportForumUrl());
    1255              :         }
    1256              : 
    1257            1 :         return resolve(make_ok());
    1258            2 :     });
    1259            3 : }
    1260              : 
    1261            3 : Promise<Ret> SaveProjectScenario::warnScoreCouldnotBeSaved(const Ret& ret)
    1262              : {
    1263            3 :     std::string message = ret.text();
    1264            3 :     if (message.empty()) {
    1265            3 :         message = muse::trc("project/save", "An unknown error occurred while saving this file.");
    1266              :     }
    1267              : 
    1268            3 :     return warnScoreCouldnotBeSaved(message)
    1269            6 :            .then<Ret>(this, [ret](const Ret&, auto resolve) {
    1270            3 :         return resolve(ret);
    1271            6 :     });
    1272            3 : }
    1273              : 
    1274            4 : Promise<Ret> SaveProjectScenario::warnScoreCouldnotBeSaved(const std::string& errorText)
    1275              : {
    1276            8 :     return interactive()->warning(muse::trc("project/save", "Your score could not be saved"), errorText)
    1277            4 :            .then<Ret>(this, [](const IInteractive::Result&, auto resolve) {
    1278            4 :         return resolve(make_ok());
    1279            8 :     });
    1280              : }
    1281              : 
    1282            3 : Promise<int> SaveProjectScenario::warnScoreHasBecomeCorruptedAfterSave(const Ret& ret)
    1283              : {
    1284            3 :     const QString errDetailsMessage = QString::fromStdString(ret.toString()).toHtmlEscaped();
    1285              : 
    1286            6 :     const QString supportForumLink = String("<a href=\"%1\" style=\"text-decoration: none\">MuseScore.org</a>")
    1287            3 :                                      .arg(configuration()->supportForumUrl().toString());
    1288              : 
    1289            3 :     const std::string title = muse::trc("project/save", "An error occurred while saving your score");
    1290              : 
    1291            6 :     const std::string body = muse::qtrc("project/save",
    1292              :                                         "To preserve your score, try saving it again. "
    1293              :                                         "If this message still appears, please save your score as new copy. "
    1294              :                                         "You can also get help for this issue on %1.<br/><br/>"
    1295              :                                         "Error details (please cite when asking for support): %2")
    1296            6 :                              .arg(supportForumLink, errDetailsMessage)
    1297            3 :                              .toStdString();
    1298              : 
    1299            3 :     IInteractive::ButtonDatas buttons;
    1300              : 
    1301            3 :     IInteractive::ButtonData saveAsBtn(SAVE_AS_BTN_ID, muse::trc("project/save", "Save as…"));
    1302            3 :     saveAsBtn.role = IInteractive::ButtonRole::ContinueRole;
    1303            3 :     buttons.push_back(saveAsBtn);
    1304              : 
    1305            3 :     IInteractive::ButtonData retryBtn(RETRY_SAVE_BTN_ID, muse::trc("project", "Try again"), true /*accent*/);
    1306            3 :     retryBtn.role = IInteractive::ButtonRole::ContinueRole;
    1307            3 :     buttons.push_back(retryBtn);
    1308              : 
    1309            3 :     IInteractive::ButtonData cancelBtn = interactive()->buttonData(IInteractive::Button::Cancel);
    1310            3 :     buttons.push_back(cancelBtn);
    1311              : 
    1312            6 :     return interactive()->error(title, IInteractive::Text(body, IInteractive::TextFormat::RichText), buttons, retryBtn.btn)
    1313            3 :            .then<int>(this, [](const IInteractive::Result& res, auto resolve) {
    1314            3 :         return resolve(res.button());
    1315            6 :     });
    1316            3 : }
    1317              : 
    1318            2 : Promise<Ret> SaveProjectScenario::askToRevertCorruptedScoreToLastSaved()
    1319              : {
    1320            3 :     TRACEFUNC;
    1321              : 
    1322            2 :     std::string title = muse::trc("project", "Revert to last saved?");
    1323            2 :     std::string body = muse::trc("project", "Your changes will be lost. This action cannot be undone.");
    1324              : 
    1325            8 :     return interactive()->warning(title, body, {
    1326              :         { IInteractive::Button::No, IInteractive::Button::Yes }
    1327              :     }, IInteractive::Button::Yes, IInteractive::Option::WithIcon)
    1328            2 :            .then<Ret>(this, [this](const IInteractive::Result& res, auto resolve) {
    1329            2 :         if (res.isButton(IInteractive::Button::No)) {
    1330            1 :             return resolve(make_ret(Ret::Code::Cancel));
    1331              :         }
    1332              : 
    1333            2 :         openProjectScenario()->revertToLastSaved().onResolve(this, [resolve](const Ret& ret) {
    1334            1 :             if (!ret) {
    1335            0 :                 LOGE() << "score was not reverted: " << ret.toString();
    1336              :             }
    1337              : 
    1338            1 :             (void)resolve(ret);
    1339              :         });
    1340              : 
    1341            1 :         return Promise<Ret>::dummy_result();
    1342            4 :     });
    1343            2 : }
    1344              : 
    1345           31 : RecentFile SaveProjectScenario::makeRecentFile(INotationProjectPtr project)
    1346              : {
    1347           31 :     RecentFile file;
    1348           31 :     file.path = project->path();
    1349              : 
    1350           31 :     if (project->isCloudProject()) {
    1351            3 :         file.displayNameOverride = project->cloudInfo().name;
    1352              :     }
    1353              : 
    1354           31 :     return file;
    1355            0 : }
    1356              : 
    1357            0 : void SaveProjectScenario::moveProject(INotationProjectPtr project, const muse::io::path_t& newPath, bool replace)
    1358              : {
    1359            0 :     muse::io::path_t oldPath = project->path();
    1360            0 :     if (oldPath == newPath) {
    1361            0 :         return;
    1362              :     }
    1363              : 
    1364            0 :     fileSystem()->move(oldPath, newPath, replace);
    1365            0 :     project->setPath(newPath);
    1366              : 
    1367            0 :     recentFilesController()->moveRecentFile(oldPath, makeRecentFile(project));
    1368            0 : }
    1369              : 
    1370            7 : QUrl SaveProjectScenario::scoreManagerUrl() const
    1371              : {
    1372            7 :     return museScoreComService()->scoreManagerUrl();
    1373              : }
    1374              : 
    1375            0 : static std::string saveCloudStatusCodeErrorMessage(const Ret& ret, bool withHelp = false)
    1376              : {
    1377            0 :     std::string message;
    1378              : 
    1379            0 :     switch (ret.code()) {
    1380            0 :     case int(cloud::Err::Status400_InvalidRequest):
    1381              :         //: %1 will be replaced with the error code that MuseScore.com returned; this might contain english text
    1382              :         //: that is deliberately not translated
    1383            0 :         message = muse::qtrc("project/cloud", "MuseScore.com returned an error code: %1.")
    1384            0 :                   .arg("400 Invalid request").toStdString();
    1385            0 :         break;
    1386            0 :     case int(cloud::Err::Status401_AuthorizationRequired):
    1387              :         //: %1 will be replaced with the error code that MuseScore.com returned; this might contain english text
    1388              :         //: that is deliberately not translated
    1389            0 :         message = muse::qtrc("project/cloud", "MuseScore.com returned an error code: %1.")
    1390            0 :                   .arg("401 Authorization required").toStdString();
    1391            0 :         break;
    1392            0 :     case int(cloud::Err::Status422_ValidationFailed):
    1393              :         //: %1 will be replaced with the error code that MuseScore.com returned; this might contain english text
    1394              :         //: that is deliberately not translated
    1395            0 :         message = muse::qtrc("project/cloud", "MuseScore.com returned an error code: %1.")
    1396            0 :                   .arg("422 Validation failed").toStdString();
    1397            0 :         break;
    1398            0 :     case int(cloud::Err::Status429_RateLimitExceeded):
    1399              :         //: %1 will be replaced with the error code that MuseScore.com returned; this might contain english text
    1400              :         //: that is deliberately not translated
    1401            0 :         message = muse::qtrc("project/cloud", "MuseScore.com returned an error code: %1.")
    1402            0 :                   .arg("429 Rate limit exceeded").toStdString();
    1403            0 :         break;
    1404            0 :     case int(cloud::Err::Status500_InternalServerError):
    1405              :         //: %1 will be replaced with the error code that MuseScore.com returned; this might contain english text
    1406              :         //: that is deliberately not translated
    1407            0 :         message = muse::qtrc("project/cloud", "MuseScore.com returned an error code: %1.")
    1408            0 :                   .arg("500 Internal server error").toStdString();
    1409            0 :         break;
    1410            0 :     case int(cloud::Err::UnknownStatusCode): {
    1411            0 :         if (const auto status = ret.data<int>("status", -1); status != -1) {
    1412              :             //: %1 will be replaced with the error code that MuseScore.com returned, which is a number.
    1413            0 :             message = muse::qtrc("project/cloud", "MuseScore.com returned an unknown error code: %1.")
    1414            0 :                       .arg(status).toStdString();
    1415              :         } else {
    1416            0 :             message = muse::trc("project/cloud", "MuseScore.com returned an unknown error code.");
    1417              :         }
    1418            0 :     } break;
    1419              :     }
    1420              : 
    1421            0 :     if (withHelp) {
    1422            0 :         message += "\n\n" + muse::trc("project/cloud", "Please try again later, or get help for this problem on MuseScore.com.");
    1423              :     }
    1424              : 
    1425            0 :     return message;
    1426            0 : }
    1427              : 
    1428            9 : Promise<RetVal<SaveLocation> > SaveProjectScenario::askSaveLocation(INotationProjectPtr project, SaveMode mode,
    1429              :                                                                     SaveLocationType preselectedType) const
    1430              : {
    1431            9 :     if (preselectedType != SaveLocationType::Undefined) {
    1432            1 :         return askSaveLocationOfType(project, mode, preselectedType);
    1433              :     }
    1434              : 
    1435           16 :     return saveLocationType()
    1436           16 :            .then<RetVal<SaveLocation> >(this, [this, project, mode](const RetVal<SaveLocationType>& type, auto resolve) {
    1437            8 :         if (!type.ret) {
    1438            0 :             return resolve(RetVal<SaveLocation>(type.ret));
    1439              :         }
    1440              : 
    1441            8 :         askSaveLocationOfType(project, mode, type.val).onResolve(this, [resolve](const RetVal<SaveLocation>& location) {
    1442            8 :             (void)resolve(location);
    1443              :         });
    1444              : 
    1445            8 :         return Promise<RetVal<SaveLocation> >::dummy_result();
    1446            8 :     });
    1447              : }
    1448              : 
    1449            9 : Promise<RetVal<SaveLocation> > SaveProjectScenario::askSaveLocationOfType(INotationProjectPtr project, SaveMode mode,
    1450              :                                                                           SaveLocationType type) const
    1451              : {
    1452            9 :     IF_ASSERT_FAILED(type != SaveLocationType::Undefined) {
    1453            0 :         return resolvedPromise(RetVal<SaveLocation>(make_ret(Ret::Code::UnknownError)));
    1454              :     }
    1455              : 
    1456              :     // The user may switch between Local and Cloud as often as they want
    1457            9 :     configuration()->setLastUsedSaveLocationType(type);
    1458              : 
    1459            9 :     if (type == SaveLocationType::Local) {
    1460           14 :         return askLocalPath(project, mode)
    1461           14 :                .then<RetVal<SaveLocation> >(this, [this, project, mode](const RetVal<muse::io::path_t>& path, auto resolve) {
    1462            7 :             switch (path.ret.code()) {
    1463            1 :                 case int(Ret::Code::Ok):
    1464            1 :                     return resolve(RetVal<SaveLocation>::make_ok(SaveLocation(path.val)));
    1465            0 :                 case RET_CODE_CHANGE_SAVE_LOCATION_TYPE: {
    1466            0 :                     askSaveLocationOfType(project, mode, SaveLocationType::Cloud)
    1467            0 :                     .onResolve(this, [resolve](const RetVal<SaveLocation>& location) {
    1468            0 :                         (void)resolve(location);
    1469              :                     });
    1470              : 
    1471            0 :                     return Promise<RetVal<SaveLocation> >::dummy_result();
    1472              :                 }
    1473            6 :                 default:
    1474            6 :                     return resolve(RetVal<SaveLocation>(path.ret));
    1475              :             }
    1476            7 :         });
    1477              :     }
    1478              : 
    1479            4 :     return askCloudLocation(project, mode)
    1480            4 :            .then<RetVal<SaveLocation> >(this, [this, project, mode](const RetVal<CloudProjectInfo>& info, auto resolve) {
    1481            2 :         switch (info.ret.code()) {
    1482            1 :             case int(Ret::Code::Ok):
    1483            1 :                 return resolve(RetVal<SaveLocation>::make_ok(SaveLocation(info.val)));
    1484            0 :             case RET_CODE_CHANGE_SAVE_LOCATION_TYPE: {
    1485            0 :                 askSaveLocationOfType(project, mode, SaveLocationType::Local)
    1486            0 :                 .onResolve(this, [resolve](const RetVal<SaveLocation>& location) {
    1487            0 :                     (void)resolve(location);
    1488              :                 });
    1489            0 :                 return Promise<RetVal<SaveLocation> >::dummy_result();
    1490              :             }
    1491            1 :             default:
    1492            1 :                 return resolve(RetVal<SaveLocation>(info.ret));
    1493              :         }
    1494            2 :     });
    1495              : }
    1496              : 
    1497           11 : Promise<RetVal<muse::io::path_t> > SaveProjectScenario::askLocalPath(INotationProjectPtr project, SaveMode saveMode) const
    1498              : {
    1499           11 :     std::string dialogTitle = muse::trc("project/save", "Save score");
    1500           11 :     std::string filenameAddition;
    1501              : 
    1502           11 :     if (saveMode == SaveMode::SaveCopy) {
    1503              :         //: used to form a filename suggestion, like "originalFile - copy"
    1504            1 :         filenameAddition = " - " + muse::trc("project/save", "copy", "a copy of a file");
    1505           10 :     } else if (saveMode == SaveMode::SaveSelection) {
    1506              :         //: used to form a filename suggestion, like "originalFile - selection"
    1507            0 :         filenameAddition = " - " + muse::trc("project/save", "selection");
    1508              :     }
    1509              : 
    1510           22 :     muse::io::path_t defaultPath = configuration()->defaultSavingFilePath(project, filenameAddition);
    1511              : 
    1512              :     std::vector<std::string> filter {
    1513            0 :         muse::trc("project", "MuseScore file") + " (*.mscz)",
    1514           11 :         muse::trc("project", "Uncompressed MuseScore folder [experimental]")
    1515              : #ifdef Q_OS_MAC
    1516              :         + " (*)"
    1517              : #else
    1518              :         + " (*.)"
    1519              : #endif
    1520           44 :     };
    1521              : 
    1522           11 :     return interactive()->selectSavingFile(dialogTitle, defaultPath, filter)
    1523            0 :            .then<RetVal<muse::io::path_t> >(this, [this](const muse::io::path_t& path, auto resolve, auto) {
    1524            3 :         muse::io::path_t selectedPath = path;
    1525              : 
    1526            3 :         if (selectedPath.empty()) {
    1527            0 :             return resolve(RetVal<muse::io::path_t>(make_ret(Ret::Code::Cancel)));
    1528              :         }
    1529              : 
    1530            3 :         if (!engraving::isMuseScoreFile(io::suffix(selectedPath))) {
    1531              :             // Then it must be that the user is trying to save a mscx file.
    1532              :             // At the selected path, a folder will be created,
    1533              :             // and inside the folder, a mscx file will be created.
    1534              :             // We should return the path to the mscx file.
    1535            0 :             selectedPath = selectedPath.appendingComponent(io::filename(selectedPath)).appendingSuffix(engraving::MSCX);
    1536              :         }
    1537              : 
    1538            3 :         configuration()->setLastSavedProjectsPath(io::dirpath(selectedPath));
    1539              : 
    1540            3 :         return resolve(RetVal<muse::io::path_t>::make_ok(selectedPath));
    1541           14 :     }, [](int code, const std::string& err, auto resolve, auto) {
    1542              :         //! NOTE Choosing nothing is not an error to report
    1543            8 :         if (code == int(Ret::Code::Cancel)) {
    1544            8 :             return resolve(RetVal<muse::io::path_t>(make_ret(Ret::Code::Cancel)));
    1545              :         }
    1546              : 
    1547            0 :         return resolve(RetVal<muse::io::path_t>(muse::make_ret(code, err)));
    1548           22 :     });
    1549           22 : }
    1550              : 
    1551            8 : Promise<RetVal<SaveLocationType> > SaveProjectScenario::saveLocationType() const
    1552              : {
    1553            8 :     bool shouldAsk = configuration()->shouldAskSaveLocationType();
    1554            8 :     SaveLocationType lastUsed = configuration()->lastUsedSaveLocationType();
    1555            8 :     if (!shouldAsk && lastUsed != SaveLocationType::Undefined) {
    1556            8 :         return resolvedPromise(RetVal<SaveLocationType>::make_ok(lastUsed));
    1557              :     }
    1558              : 
    1559            0 :     return askSaveLocationType();
    1560              : }
    1561              : 
    1562            0 : Promise<RetVal<SaveLocationType> > SaveProjectScenario::askSaveLocationType() const
    1563              : {
    1564            0 :     UriQuery query("musescore://project/asksavelocationtype");
    1565            0 :     bool shouldAsk = configuration()->shouldAskSaveLocationType();
    1566            0 :     query.addParam("askAgain", Val(shouldAsk));
    1567              : 
    1568            0 :     return openDialog(query).then<RetVal<SaveLocationType> >(this, [this](const RetVal<Val>& rv, auto resolve) {
    1569            0 :         if (!rv.ret) {
    1570            0 :             return resolve(RetVal<SaveLocationType>(rv.ret));
    1571              :         }
    1572              : 
    1573            0 :         QVariantMap vals = rv.val.toQVariant().toMap();
    1574              : 
    1575            0 :         bool askAgain = vals["askAgain"].toBool();
    1576            0 :         configuration()->setShouldAskSaveLocationType(askAgain);
    1577              : 
    1578            0 :         SaveLocationType type = static_cast<SaveLocationType>(vals["saveLocationType"].toInt());
    1579            0 :         return resolve(RetVal<SaveLocationType>::make_ok(type));
    1580            0 :     });
    1581            0 : }
    1582              : 
    1583            2 : Promise<RetVal<CloudProjectInfo> > SaveProjectScenario::askCloudLocation(INotationProjectPtr project, SaveMode mode) const
    1584              : {
    1585            2 :     return doAskCloudLocation(project, mode, false);
    1586              : }
    1587              : 
    1588            6 : Promise<RetVal<CloudProjectInfo> > SaveProjectScenario::askPublishLocation(INotationProjectPtr project) const
    1589              : {
    1590            6 :     return doAskCloudLocation(project, SaveMode::Save, true);
    1591              : }
    1592              : 
    1593            0 : Promise<RetVal<CloudAudioInfo> > SaveProjectScenario::askShareAudioLocation(INotationProjectPtr project) const
    1594              : {
    1595            0 :     return audioComService()->authorization()->checkCloudIsAvailable()
    1596            0 :            .then<RetVal<CloudAudioInfo> >(this, [this, project](const Ret& isCloudAvailable, auto resolve) {
    1597            0 :         if (!isCloudAvailable) {
    1598            0 :             warnCloudNotAvailableForSharingAudio().onResolve(this, [resolve](const Ret& ret) {
    1599            0 :                 (void)resolve(RetVal<CloudAudioInfo>(ret));
    1600              :             });
    1601              : 
    1602            0 :             return Promise<RetVal<CloudAudioInfo> >::dummy_result();
    1603              :         }
    1604              : 
    1605            0 :         doAskShareAudioLocation(project).onResolve(this, [resolve](const RetVal<CloudAudioInfo>& info) {
    1606            0 :             (void)resolve(info);
    1607              :         });
    1608              : 
    1609            0 :         return Promise<RetVal<CloudAudioInfo> >::dummy_result();
    1610            0 :     });
    1611              : }
    1612              : 
    1613            0 : Promise<RetVal<CloudAudioInfo> > SaveProjectScenario::doAskShareAudioLocation(INotationProjectPtr project) const
    1614              : {
    1615            0 :     std::string dialogText = muse::trc("project/save", "Log in or create a new account on Audio.com to share your music.");
    1616              : 
    1617            0 :     return ensureAuthorization(muse::cloud::AUDIO_COM_CLOUD_CODE, false, dialogText)
    1618            0 :            .then<RetVal<CloudAudioInfo> >(this, [this, project](const RetVal<Val>& auth, auto resolve) {
    1619            0 :         if (!auth.ret) {
    1620            0 :             return resolve(RetVal<CloudAudioInfo>(auth.ret));
    1621              :         }
    1622              : 
    1623            0 :         QString defaultName = project->displayName();
    1624            0 :         QUrl uploadUrl = project->cloudAudioInfo().url;
    1625            0 :         cloud::Visibility defaultVisibility = cloud::Visibility::Public;
    1626              : 
    1627            0 :         UriQuery query("musescore://project/savetocloud");
    1628            0 :         query.addParam("isPublishShare", Val(true));
    1629            0 :         query.addParam("name", Val(defaultName));
    1630            0 :         query.addParam("visibility", Val(defaultVisibility));
    1631            0 :         query.addParam("cloudCode", Val(cloud::AUDIO_COM_CLOUD_CODE));
    1632              : 
    1633            0 :         if (!uploadUrl.isEmpty()) {
    1634            0 :             query.addParam("existingScoreOrAudioUrl", Val(uploadUrl.toString()));
    1635              :         }
    1636              : 
    1637            0 :         openDialog(query).onResolve(this, [resolve, uploadUrl](const RetVal<Val>& rv) {
    1638            0 :             if (!rv.ret) {
    1639            0 :                 (void)resolve(RetVal<CloudAudioInfo>(rv.ret));
    1640            0 :                 return;
    1641              :             }
    1642              : 
    1643            0 :             QVariantMap vals = rv.val.toQVariant().toMap();
    1644              :             using Response = cloud::SaveToCloudResponse::SaveToCloudResponse;
    1645            0 :             auto response = static_cast<Response>(vals["response"].toInt());
    1646            0 :             switch (response) {
    1647            0 :                 case Response::Cancel:
    1648              :                 case Response::SaveLocallyInstead:
    1649            0 :                     (void)resolve(RetVal<CloudAudioInfo>(make_ret(Ret::Code::Cancel)));
    1650            0 :                     return;
    1651            0 :                 case Response::Ok:
    1652            0 :                     break;
    1653              :             }
    1654              : 
    1655            0 :             CloudAudioInfo result;
    1656            0 :             result.name = vals["name"].toString();
    1657            0 :             result.visibility = static_cast<cloud::Visibility>(vals["visibility"].toInt());
    1658            0 :             result.replaceExisting = vals["replaceExisting"].toBool() && !uploadUrl.isEmpty();
    1659              : 
    1660            0 :             (void)resolve(RetVal<CloudAudioInfo>::make_ok(result));
    1661            0 :         });
    1662              : 
    1663            0 :         return Promise<RetVal<CloudAudioInfo> >::dummy_result();
    1664            0 :     });
    1665            0 : }
    1666              : 
    1667            8 : Promise<RetVal<CloudProjectInfo> > SaveProjectScenario::doAskCloudLocation(INotationProjectPtr project, SaveMode mode,
    1668              :                                                                            bool isPublishShare) const
    1669              : {
    1670           16 :     return museScoreComService()->authorization()->checkCloudIsAvailable()
    1671           16 :            .then<RetVal<CloudProjectInfo> >(this, [this, project, mode, isPublishShare](const Ret& isCloudAvailable, auto resolve) {
    1672            8 :         if (!isCloudAvailable) {
    1673            0 :             warnCloudNotAvailableForUploading(isPublishShare).onResolve(this, [resolve](const Ret& ret) {
    1674            0 :                 (void)resolve(RetVal<CloudProjectInfo>(ret));
    1675              :             });
    1676              : 
    1677            0 :             return Promise<RetVal<CloudProjectInfo> >::dummy_result();
    1678              :         }
    1679              : 
    1680            8 :         doAskCloudLocationAuthorized(project, mode, isPublishShare).onResolve(this, [resolve](const RetVal<CloudProjectInfo>& info) {
    1681            8 :             (void)resolve(info);
    1682              :         });
    1683              : 
    1684            8 :         return Promise<RetVal<CloudProjectInfo> >::dummy_result();
    1685           16 :     });
    1686              : }
    1687              : 
    1688            8 : Promise<RetVal<CloudProjectInfo> > SaveProjectScenario::doAskCloudLocationAuthorized(INotationProjectPtr project, SaveMode mode,
    1689              :                                                                                      bool isPublishShare) const
    1690              : {
    1691              :     std::string dialogText = isPublishShare
    1692            8 :                              ? muse::trc("project/save", "Log in to MuseScore.com to publish this score.")
    1693            8 :                              : muse::trc("project/save", "Log in to MuseScore.com to save this score to the cloud.");
    1694              : 
    1695            8 :     return ensureAuthorization(muse::cloud::MUSESCORE_COM_CLOUD_CODE, true, dialogText)
    1696           16 :            .then<RetVal<CloudProjectInfo> >(this, [this, project, mode, isPublishShare](const RetVal<Val>& auth, auto resolve) {
    1697            8 :         if (!auth.ret) {
    1698            0 :             return resolve(RetVal<CloudProjectInfo>(auth.ret));
    1699              :         }
    1700              : 
    1701              :         using Response = cloud::SaveToCloudResponse::SaveToCloudResponse;
    1702            8 :         if (static_cast<Response>(auth.val.toInt()) == Response::SaveLocallyInstead) {
    1703            2 :             return resolve(RetVal<CloudProjectInfo>(Ret(RET_CODE_CHANGE_SAVE_LOCATION_TYPE)));
    1704              :         }
    1705              : 
    1706            6 :         askCloudProjectInfo(project, mode, isPublishShare).onResolve(this, [resolve](const RetVal<CloudProjectInfo>& info) {
    1707            6 :             (void)resolve(info);
    1708              :         });
    1709              : 
    1710            6 :         return Promise<RetVal<CloudProjectInfo> >::dummy_result();
    1711           16 :     });
    1712            8 : }
    1713              : 
    1714            6 : Promise<RetVal<CloudProjectInfo> > SaveProjectScenario::askCloudProjectInfo(INotationProjectPtr project, SaveMode mode,
    1715              :                                                                             bool isPublishShare) const
    1716              : {
    1717            6 :     const QString defaultName = project->displayName();
    1718            6 :     const cloud::Visibility defaultVisibility = isPublishShare ? cloud::Visibility::Public : cloud::Visibility::Private;
    1719            6 :     const QUrl existingScoreUrl = project->cloudInfo().sourceUrl;
    1720              : 
    1721            6 :     if (existingScoreUrl.isEmpty()) {
    1722           12 :         return askCloudProjectInfo(project, mode, isPublishShare, defaultName, defaultVisibility, existingScoreUrl);
    1723              :     }
    1724              : 
    1725            0 :     return museScoreComService()->downloadScoreInfo(existingScoreUrl)
    1726            0 :            .then<RetVal<CloudProjectInfo> >(this, [this, project, mode, isPublishShare, defaultName, defaultVisibility,
    1727              :                                                    existingScoreUrl](const RetVal<cloud::ScoreInfo>& scoreInfo, auto resolve) {
    1728            0 :         QString name = defaultName;
    1729            0 :         cloud::Visibility visibility = defaultVisibility;
    1730            0 :         QUrl scoreUrl = existingScoreUrl;
    1731              : 
    1732            0 :         if (scoreInfo.val.isValid()) {
    1733            0 :             const cloud::AccountInfo& accountInfo = museScoreComService()->authorization()->accountInfo();
    1734            0 :             if (accountInfo.id.toInt() != scoreInfo.val.owner.id) {
    1735            0 :                 scoreUrl = QUrl();
    1736              :             }
    1737              :         }
    1738              : 
    1739            0 :         switch (scoreInfo.ret.code()) {
    1740            0 :             case int(Ret::Code::Ok):
    1741            0 :                 name = scoreInfo.val.title;
    1742            0 :                 if (!isPublishShare) {
    1743            0 :                     visibility = scoreInfo.val.visibility;
    1744              :                 }
    1745            0 :                 break;
    1746              : 
    1747            0 :             case int(cloud::Err::Status400_InvalidRequest):
    1748              :             case int(cloud::Err::Status403_AccountNotActivated):
    1749              :             case int(cloud::Err::Status422_ValidationFailed):
    1750              :             case int(cloud::Err::Status429_RateLimitExceeded):
    1751              :             case int(cloud::Err::Status500_InternalServerError):
    1752              :             case int(cloud::Err::UnknownStatusCode):
    1753              :             case int(cloud::Err::NetworkError):
    1754            0 :                 showCloudSaveError(scoreInfo.ret, project->cloudInfo(), isPublishShare, false)
    1755            0 :                 .onResolve(this, [resolve](const Ret& ret) {
    1756            0 :                 (void)resolve(RetVal<CloudProjectInfo>(ret));
    1757              :             });
    1758              : 
    1759            0 :                 return Promise<RetVal<CloudProjectInfo> >::dummy_result();
    1760              : 
    1761              :             // It's possible the source URL is invalid or points to a score on a different user's account.
    1762              :             // In this situation we shouldn't show an error.
    1763            0 :             default: break;
    1764              :         }
    1765              : 
    1766            0 :         askCloudProjectInfo(project, mode, isPublishShare, name, visibility, scoreUrl)
    1767            0 :         .onResolve(this, [resolve](const RetVal<CloudProjectInfo>& info) {
    1768            0 :             (void)resolve(info);
    1769              :         });
    1770              : 
    1771            0 :         return Promise<RetVal<CloudProjectInfo> >::dummy_result();
    1772            0 :     });
    1773            6 : }
    1774              : 
    1775            6 : Promise<RetVal<CloudProjectInfo> > SaveProjectScenario::askCloudProjectInfo(INotationProjectPtr project, SaveMode mode,
    1776              :                                                                             bool isPublishShare, const QString& defaultName,
    1777              :                                                                             muse::cloud::Visibility defaultVisibility,
    1778              :                                                                             const QUrl& existingScoreUrl) const
    1779              : {
    1780            6 :     const CloudProjectInfo existingProjectInfo = project->cloudInfo();
    1781              : 
    1782            6 :     UriQuery query("musescore://project/savetocloud");
    1783           18 :     query.addParam("isPublishShare", Val(isPublishShare));
    1784           18 :     query.addParam("name", Val(defaultName));
    1785           18 :     query.addParam("visibility", Val(defaultVisibility));
    1786           18 :     query.addParam("existingScoreOrAudioUrl", Val(existingScoreUrl.toString()));
    1787           18 :     query.addParam("cloudCode", Val(cloud::MUSESCORE_COM_CLOUD_CODE));
    1788              : 
    1789            6 :     return openDialog(query)
    1790           12 :            .then<RetVal<CloudProjectInfo> >(this, [this, mode, isPublishShare, existingProjectInfo](const RetVal<Val>& rv, auto resolve) {
    1791            6 :         if (!rv.ret) {
    1792            1 :             return resolve(RetVal<CloudProjectInfo>(rv.ret));
    1793              :         }
    1794              : 
    1795            5 :         QVariantMap vals = rv.val.toQVariant().toMap();
    1796              :         using Response = cloud::SaveToCloudResponse::SaveToCloudResponse;
    1797            5 :         auto response = static_cast<Response>(vals["response"].toInt());
    1798            5 :         switch (response) {
    1799            0 :             case Response::Cancel:
    1800            0 :                 return resolve(RetVal<CloudProjectInfo>(make_ret(Ret::Code::Cancel)));
    1801            0 :             case Response::SaveLocallyInstead:
    1802            0 :                 return resolve(RetVal<CloudProjectInfo>(Ret(RET_CODE_CHANGE_SAVE_LOCATION_TYPE)));
    1803            5 :             case Response::Ok:
    1804            5 :                 break;
    1805              :         }
    1806              : 
    1807            5 :         CloudProjectInfo result;
    1808              : 
    1809            5 :         if ((mode == SaveMode::Save || isPublishShare) && vals["replaceExisting"].toBool()) {
    1810            0 :             result = existingProjectInfo;
    1811              :         }
    1812              : 
    1813            5 :         result.name = vals["name"].toString();
    1814            5 :         result.visibility = static_cast<cloud::Visibility>(vals["visibility"].toInt());
    1815              : 
    1816            5 :         warnBeforePublishing(isPublishShare, result.visibility).onResolve(this, [result, resolve](bool agreed) {
    1817            5 :             if (!agreed) {
    1818            0 :                 (void)resolve(RetVal<CloudProjectInfo>(make_ret(Ret::Code::Cancel)));
    1819            0 :                 return;
    1820              :             }
    1821              : 
    1822            5 :             (void)resolve(RetVal<CloudProjectInfo>::make_ok(result));
    1823              :         });
    1824              : 
    1825            5 :         return Promise<RetVal<CloudProjectInfo> >::dummy_result();
    1826           17 :     });
    1827            6 : }
    1828              : 
    1829            5 : Promise<bool> SaveProjectScenario::warnBeforePublishing(bool isPublishShare, cloud::Visibility visibility) const
    1830              : {
    1831            5 :     if (isPublishShare) {
    1832            4 :         if (!configuration()->shouldWarnBeforePublish()) {
    1833            8 :             return resolvedPromise(true);
    1834              :         }
    1835              :     } else {
    1836            1 :         if (!configuration()->shouldWarnBeforeSavingPubliclyToCloud()) {
    1837            2 :             return resolvedPromise(true);
    1838              :         }
    1839              :     }
    1840              : 
    1841            0 :     std::string title, message;
    1842              : 
    1843              :     IInteractive::ButtonDatas buttons = {
    1844            0 :         IInteractive::ButtonData(IInteractive::Button::Cancel, muse::trc("global", "Cancel")),
    1845            0 :         IInteractive::ButtonData(IInteractive::Button::Ok, muse::trc("project/save", "Publish"), true)
    1846            0 :     };
    1847              : 
    1848            0 :     IInteractive::Options options = IInteractive::Option::WithIcon | IInteractive::Option::WithDontShowAgainCheckBox;
    1849              : 
    1850            0 :     if (isPublishShare) {
    1851            0 :         title = muse::trc("project/save", "Publish changes online?");
    1852            0 :         message = muse::trc("project/save", "We will need to generate a new MP3 for web playback.");
    1853            0 :     } else if (visibility == cloud::Visibility::Public) {
    1854            0 :         title = muse::trc("project/save", "Publish this score online?"),
    1855            0 :         message = muse::trc("project/save", "All saved changes will be publicly visible on MuseScore.com. "
    1856              :                                             "If you want to make frequent changes, we recommend saving this "
    1857            0 :                                             "score privately until you’re ready to share it to the world.");
    1858              :     } else {
    1859            0 :         return resolvedPromise(true);
    1860              :     }
    1861              : 
    1862            0 :     return interactive()->warning(title, message, buttons, int(IInteractive::Button::Ok), options)
    1863            0 :            .then<bool>(this, [this, isPublishShare](const IInteractive::Result& res, auto resolve) {
    1864            0 :         bool ok = res.standardButton() == IInteractive::Button::Ok;
    1865            0 :         if (ok && !res.showAgain()) {
    1866            0 :             if (isPublishShare) {
    1867            0 :                 configuration()->setShouldWarnBeforePublish(false);
    1868              :             } else {
    1869            0 :                 configuration()->setShouldWarnBeforeSavingPubliclyToCloud(false);
    1870              :             }
    1871              :         }
    1872              : 
    1873            0 :         return resolve(ok);
    1874            0 :     });
    1875            0 : }
    1876              : 
    1877            1 : Promise<bool> SaveProjectScenario::warnBeforeSavingToExistingPubliclyVisibleCloudProject() const
    1878              : {
    1879              :     IInteractive::ButtonDatas buttons = {
    1880            0 :         IInteractive::ButtonData(IInteractive::Button::Cancel, muse::trc("global", "Cancel")),
    1881            1 :         IInteractive::ButtonData(IInteractive::Button::Ok, muse::trc("project/save", "Publish"), true)
    1882            4 :     };
    1883              : 
    1884            4 :     return interactive()->warning(
    1885            2 :         muse::trc("project/save", "Publish changes online?"),
    1886            2 :         muse::trc("project/save", "Your saved changes will be publicly visible. We will also "
    1887              :                                   "need to generate a new MP3 for public playback."),
    1888              :         buttons, int(IInteractive::Button::Ok))
    1889            1 :            .then<bool>(this, [](const IInteractive::Result& res, auto resolve) {
    1890            1 :         return resolve(res.standardButton() == IInteractive::Button::Ok);
    1891            2 :     });
    1892            2 : }
    1893              : 
    1894            0 : Promise<Ret> SaveProjectScenario::warnCloudNotAvailableForUploading(bool isPublishShare) const
    1895              : {
    1896            0 :     if (isPublishShare) {
    1897              :         //! NOTE Nothing to answer, so the flow does not wait for the message to be dismissed
    1898            0 :         interactive()->warning(muse::trc("project/save", "Unable to connect to MuseScore.com"),
    1899            0 :                                muse::trc("project/save", "Please check your internet connection or try again later."));
    1900            0 :         return resolvedPromise(make_ret(Ret::Code::Cancel));
    1901              :     }
    1902              : 
    1903              :     IInteractive::ButtonDatas buttons = {
    1904            0 :         IInteractive::ButtonData(IInteractive::Button::Cancel, muse::trc("global", "Cancel")),
    1905            0 :         IInteractive::ButtonData(IInteractive::Button::Ok, muse::trc("project/save", "Save to computer"), true)
    1906            0 :     };
    1907              : 
    1908            0 :     return interactive()->warning(muse::trc("project/save", "Unable to connect to the cloud"),
    1909            0 :                                   muse::trc("project/save", "Please check your internet connection or try again later."),
    1910              :                                   buttons, int(IInteractive::Button::Ok))
    1911            0 :            .then<Ret>(this, [](const IInteractive::Result& res, auto resolve) {
    1912            0 :         if (res.standardButton() == IInteractive::Button::Ok) {
    1913            0 :             return resolve(Ret(RET_CODE_CHANGE_SAVE_LOCATION_TYPE));
    1914              :         }
    1915              : 
    1916            0 :         return resolve(make_ret(Ret::Code::Cancel));
    1917            0 :     });
    1918            0 : }
    1919              : 
    1920            0 : Promise<Ret> SaveProjectScenario::warnCloudNotAvailableForSharingAudio() const
    1921              : {
    1922            0 :     return interactive()->warning(muse::trc("project/save", "Unable to connect to Audio.com"),
    1923            0 :                                   muse::trc("project/save", "Please check your internet connection or try again later."))
    1924            0 :            .then<Ret>(this, [](const IInteractive::Result&, auto resolve) {
    1925            0 :         return resolve(make_ret(Ret::Code::Cancel));
    1926            0 :     });
    1927              : }
    1928              : 
    1929           22 : Promise<RetVal<Val> > SaveProjectScenario::ensureAuthorization(const QString& cloudCode, bool publishingScore,
    1930              :                                                                const std::string& text) const
    1931              : {
    1932           22 :     IF_ASSERT_FAILED(cloudCode == muse::cloud::MUSESCORE_COM_CLOUD_CODE || cloudCode == muse::cloud::AUDIO_COM_CLOUD_CODE) {
    1933            0 :         return resolvedPromise(RetVal<Val>(make_ret(Err::UnknownError)));
    1934              :     }
    1935              : 
    1936           22 :     bool isMuseScoreCom = cloudCode == muse::cloud::MUSESCORE_COM_CLOUD_CODE;
    1937           44 :     bool userAuthorized = isMuseScoreCom ? museScoreComService()->authorization()->userAuthorized().val
    1938           22 :                           : audioComService()->authorization()->userAuthorized().val;
    1939              : 
    1940           22 :     if (userAuthorized) {
    1941           17 :         return resolvedPromise(RetVal<Val>::make_ok(Val()));
    1942              :     }
    1943              : 
    1944            5 :     UriQuery query("muse://cloud/requireauthorization");
    1945           15 :     query.addParam("text", Val(text));
    1946           15 :     query.addParam("cloudCode", Val(cloudCode));
    1947           15 :     query.addParam("publishingScore", Val(publishingScore));
    1948            5 :     return openDialog(query);
    1949            5 : }
    1950              : 
    1951            4 : Promise<Ret> SaveProjectScenario::showCloudSaveError(const Ret& ret, const CloudProjectInfo& info, bool isPublishShare,
    1952              :                                                      bool alreadyAttempted) const
    1953              : {
    1954            4 :     std::string title;
    1955            4 :     if (alreadyAttempted) {
    1956              :         title = isPublishShare
    1957            8 :                 ? muse::trc("project/save", "Your score could not be published")
    1958            4 :                 : muse::trc("project/save", "Your score could not be saved to the cloud");
    1959              :     } else {
    1960              :         title = isPublishShare
    1961            0 :                 ? muse::trc("project/save", "Your score cannot be published")
    1962            0 :                 : muse::trc("project/save", "Your score cannot be saved to the cloud");
    1963              :     }
    1964              : 
    1965            4 :     std::string msg;
    1966              : 
    1967              :     static constexpr int helpBtnCode = int(IInteractive::Button::CustomButton) + 1;
    1968              :     static constexpr int saveLocallyBtnCode = int(IInteractive::Button::CustomButton) + 2;
    1969              :     static constexpr int saveAsBtnCode = int(IInteractive::Button::CustomButton) + 3;
    1970              :     static constexpr int publishAsNewScoreBtnCode = int(IInteractive::Button::CustomButton) + 4;
    1971              :     static constexpr int replaceBtnCode = int(IInteractive::Button::CustomButton) + 5;
    1972              : 
    1973            4 :     IInteractive::ButtonData okBtn = interactive()->buttonData(IInteractive::Button::Ok);
    1974            4 :     IInteractive::ButtonData saveLocallyBtn { saveLocallyBtnCode, muse::trc("project/save", "Save to computer") };
    1975            4 :     IInteractive::ButtonData helpBtn { helpBtnCode, muse::trc("project/save", "Get help") };
    1976              : 
    1977            0 :     IInteractive::ButtonDatas buttons = (alreadyAttempted || isPublishShare)
    1978           12 :                                         ? (IInteractive::ButtonDatas { helpBtn, okBtn })
    1979           28 :                                         : (IInteractive::ButtonDatas { helpBtn, saveLocallyBtn, okBtn });
    1980              : 
    1981            4 :     int defaultButtonCode = okBtn.btn;
    1982              : 
    1983            4 :     switch (ret.code()) {
    1984            0 :     case int(cloud::Err::Status403_AccountNotActivated):
    1985            0 :         msg = muse::trc("project/cloud", "Your MuseScore.com account needs to be verified first. "
    1986            0 :                                          "Please activate your account via the link in the activation email.");
    1987            0 :         buttons = { okBtn };
    1988            0 :         break;
    1989            2 :     case int(cloud::Err::Status409_Conflict):
    1990            2 :         title = muse::trc("project/save", "There are conflicting changes in the online score");
    1991            2 :         if (isPublishShare) {
    1992            0 :             msg = muse::qtrc("project/save", "You can replace the <a href=\"%1\">online score</a>, or publish this as a new score "
    1993              :                                              "to avoid losing changes in the current online version.")
    1994            0 :                   .arg(info.sourceUrl.toString())
    1995            0 :                   .toStdString();
    1996            0 :             buttons = {
    1997            0 :                 interactive()->buttonData(IInteractive::Button::Cancel),
    1998            0 :                 IInteractive::ButtonData { publishAsNewScoreBtnCode, muse::trc("project/save", "Publish as new score") },
    1999            0 :                 IInteractive::ButtonData { replaceBtnCode, muse::trc("project/save", "Replace") }
    2000            0 :             };
    2001            0 :             defaultButtonCode = replaceBtnCode;
    2002              :         } else {
    2003            2 :             msg = muse::qtrc("project/save", "You can replace the <a href=\"%1\">online score</a>, or save this as a new file "
    2004              :                                              "to avoid losing changes in the current online version.")
    2005            4 :                   .arg(info.sourceUrl.toString())
    2006            2 :                   .toStdString();
    2007            8 :             buttons = {
    2008            2 :                 interactive()->buttonData(IInteractive::Button::Cancel),
    2009            0 :                 IInteractive::ButtonData { saveAsBtnCode, muse::trc("project/save", "Save as…") },
    2010            2 :                 IInteractive::ButtonData { replaceBtnCode, muse::trc("project/save", "Replace") }
    2011            8 :             };
    2012            2 :             defaultButtonCode = replaceBtnCode;
    2013              :         }
    2014            2 :         break;
    2015              : 
    2016            0 :     case int(cloud::Err::Status400_InvalidRequest):
    2017              :     case int(cloud::Err::Status401_AuthorizationRequired):
    2018              :     case int(cloud::Err::Status422_ValidationFailed):
    2019              :     case int(cloud::Err::Status429_RateLimitExceeded):
    2020              :     case int(cloud::Err::Status500_InternalServerError):
    2021              :     case int(cloud::Err::UnknownStatusCode):
    2022            0 :         msg = saveCloudStatusCodeErrorMessage(ret, /*withHelp=*/ true);
    2023            0 :         break;
    2024              : 
    2025            0 :     case int(cloud::Err::NetworkError):
    2026            0 :         msg = muse::mtrc("project/cloud", "Could not connect to <a href=\"%1\">MuseScore.com</a>. "
    2027              :                                           "Please check your internet connection or try again later.")
    2028            0 :               .arg(u"https://musescore.com").toStdString();
    2029            0 :         break;
    2030            2 :     default:
    2031            2 :         msg = muse::trc("project/cloud", "Please try again later, or get help for this problem on MuseScore.com.");
    2032            2 :         break;
    2033              :     }
    2034              : 
    2035            8 :     return interactive()->warning(title, msg, buttons, defaultButtonCode)
    2036            4 :            .then<Ret>(this, [this](const IInteractive::Result& res, auto resolve) {
    2037            4 :         switch (res.button()) {
    2038            0 :             case helpBtnCode:
    2039            0 :                 platformInteractive()->openUrl(configuration()->dotComBugReportUrl());
    2040            0 :                 break;
    2041            0 :             case saveLocallyBtnCode:
    2042            0 :                 return resolve(Ret(RET_CODE_CHANGE_SAVE_LOCATION_TYPE));
    2043            1 :             case saveAsBtnCode:
    2044            1 :                 return resolve(Ret(RET_CODE_CONFLICT_RESPONSE_SAVE_AS));
    2045            1 :             case publishAsNewScoreBtnCode:
    2046            1 :                 return resolve(Ret(RET_CODE_CONFLICT_RESPONSE_PUBLISH_AS_NEW_SCORE));
    2047            0 :             case replaceBtnCode:
    2048            0 :                 return resolve(Ret(RET_CODE_CONFLICT_RESPONSE_REPLACE));
    2049              :         }
    2050              : 
    2051            2 :         return resolve(make_ret(Ret::Code::Cancel));
    2052            8 :     });
    2053           12 : }
    2054              : 
    2055            0 : Promise<Ret> SaveProjectScenario::showAudioCloudShareError(const Ret& ret) const
    2056              : {
    2057            0 :     std::string title= muse::trc("project/share", "Your audio could not be shared");
    2058            0 :     std::string msg;
    2059              : 
    2060            0 :     IInteractive::ButtonData okBtn = interactive()->buttonData(IInteractive::Button::Ok);
    2061            0 :     IInteractive::ButtonDatas buttons = IInteractive::ButtonDatas { okBtn };
    2062              : 
    2063            0 :     switch (ret.code()) {
    2064            0 :     case int(cloud::Err::Status403_AccountNotActivated):
    2065            0 :         msg = muse::trc("project/share", "Your Audio.com account needs to be verified first. "
    2066            0 :                                          "Please activate your account via the link in the activation email.");
    2067            0 :         break;
    2068            0 :     case int(cloud::Err::UnknownStatusCode): {
    2069            0 :         if (const auto status = ret.data<int>("status", -1); status != -1) {
    2070              :             //: %1 will be replaced with the error code that audio.com returned, which is a number.
    2071            0 :             msg = muse::qtrc("project/share", "Audio.com returned an unknown error code: %1.")
    2072            0 :                   .arg(status).toStdString();
    2073              :         } else {
    2074            0 :             msg = muse::trc("project/share", "Audio.com returned an unknown error code.");
    2075              :         }
    2076            0 :         msg += "\n\n" + muse::trc("project/share", "Please try again later, or get help for this problem on Audio.com.");
    2077            0 :     } break;
    2078            0 :     case int(cloud::Err::NetworkError):
    2079            0 :         msg = muse::trc("project/share", "Could not connect to Audio.com. "
    2080            0 :                                          "Please check your internet connection or try again later.");
    2081            0 :         break;
    2082            0 :     default:
    2083            0 :         msg = muse::trc("project/share", "Please try again later, or get help for this problem on Audio.com.");
    2084            0 :         break;
    2085              :     }
    2086              : 
    2087            0 :     return interactive()->warning(title, msg, buttons)
    2088            0 :            .then<Ret>(this, [ret](const IInteractive::Result&, auto resolve) {
    2089            0 :         return resolve(ret);
    2090            0 :     });
    2091            0 : }
        

Generated by: LCOV version 2.0-1