1// Aseprite
2// Copyright (C) 2019 Igara Studio S.A.
3// Copyright (C) 2001-2018 David Capello
4//
5// This program is distributed under the terms of
6// the End-User License Agreement for Aseprite.
7
8#ifdef HAVE_CONFIG_H
9#include "config.h"
10#endif
11
12#include "app/cmd/set_mask.h"
13#include "app/commands/command.h"
14#include "app/commands/params.h"
15#include "app/context_access.h"
16#include "app/file_selector.h"
17#include "app/i18n/strings.h"
18#include "app/modules/gui.h"
19#include "app/tx.h"
20#include "app/util/msk_file.h"
21#include "doc/mask.h"
22#include "doc/sprite.h"
23#include "fmt/format.h"
24#include "ui/alert.h"
25
26namespace app {
27
28class LoadMaskCommand : public Command {
29 std::string m_filename;
30
31public:
32 LoadMaskCommand();
33
34protected:
35 void onLoadParams(const Params& params) override;
36 bool onEnabled(Context* context) override;
37 void onExecute(Context* context) override;
38};
39
40LoadMaskCommand::LoadMaskCommand()
41 : Command(CommandId::LoadMask(), CmdRecordableFlag)
42{
43 m_filename = "";
44}
45
46void LoadMaskCommand::onLoadParams(const Params& params)
47{
48 m_filename = params.get("filename");
49}
50
51bool LoadMaskCommand::onEnabled(Context* context)
52{
53 return context->checkFlags(ContextFlags::ActiveDocumentIsWritable);
54}
55
56void LoadMaskCommand::onExecute(Context* context)
57{
58 const ContextReader reader(context);
59
60 if (context->isUIAvailable()) {
61 base::paths exts = { "msk" };
62 base::paths selectedFilename;
63 if (!app::show_file_selector(
64 Strings::load_selection_title(), m_filename, exts,
65 FileSelectorType::Open, selectedFilename))
66 return;
67
68 m_filename = selectedFilename.front();
69 }
70
71 std::unique_ptr<Mask> mask(load_msk_file(m_filename.c_str()));
72 if (!mask) {
73 ui::Alert::show(fmt::format(Strings::alerts_error_loading_file(), m_filename));
74 return;
75 }
76
77 {
78 ContextWriter writer(reader);
79 Doc* document = writer.document();
80 Tx tx(writer.context(),
81 Strings::load_selection_title(),
82 DoesntModifyDocument);
83 tx(new cmd::SetMask(document, mask.get()));
84 tx.commit();
85
86 update_screen_for_document(document);
87 }
88}
89
90Command* CommandFactory::createLoadMaskCommand()
91{
92 return new LoadMaskCommand;
93}
94
95} // namespace app
96