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/app.h"
13#include "app/cmd/set_mask.h"
14#include "app/color_picker.h"
15#include "app/color_utils.h"
16#include "app/commands/command.h"
17#include "app/context_access.h"
18#include "app/modules/editors.h"
19#include "app/modules/gui.h"
20#include "app/tools/tool_box.h"
21#include "app/tx.h"
22#include "app/ui/editor/editor.h"
23#include "app/ui/toolbar.h"
24#include "doc/algorithm/shrink_bounds.h"
25#include "doc/cel.h"
26#include "doc/image.h"
27#include "doc/layer.h"
28#include "doc/mask.h"
29#include "doc/sprite.h"
30
31namespace app {
32
33class MaskContentCommand : public Command {
34public:
35 MaskContentCommand();
36
37protected:
38 bool onEnabled(Context* context) override;
39 void onExecute(Context* context) override;
40};
41
42MaskContentCommand::MaskContentCommand()
43 : Command(CommandId::MaskContent(), CmdRecordableFlag)
44{
45}
46
47bool MaskContentCommand::onEnabled(Context* context)
48{
49 return context->checkFlags(ContextFlags::ActiveDocumentIsWritable |
50 ContextFlags::ActiveLayerIsImage);
51}
52
53void MaskContentCommand::onExecute(Context* context)
54{
55 Doc* document;
56 {
57 ContextWriter writer(context);
58 document = writer.document();
59
60 Cel* cel = writer.cel(); // Get current cel (can be NULL)
61 if (!cel)
62 return;
63
64 gfx::Color color;
65 if (writer.layer()->isBackground()) {
66 ColorPicker picker;
67 picker.pickColor(*writer.site(),
68 gfx::PointF(0.0, 0.0),
69 current_editor->projection(),
70 ColorPicker::FromComposition);
71 color = color_utils::color_for_layer(picker.color(), writer.layer());
72 }
73 else
74 color = cel->image()->maskColor();
75
76 Mask newMask;
77 gfx::Rect imgBounds = cel->image()->bounds();
78 if (algorithm::shrink_cel_bounds(cel, color, imgBounds)) {
79 newMask.replace(imgBounds);
80 }
81 else {
82 newMask.replace(cel->bounds());
83 }
84
85 Tx tx(writer.context(), "Select Content", DoesntModifyDocument);
86 tx(new cmd::SetMask(document, &newMask));
87 document->resetTransformation();
88 tx.commit();
89 }
90
91 // Select marquee tool
92 if (tools::Tool* tool = App::instance()->toolBox()
93 ->getToolById(tools::WellKnownTools::RectangularMarquee)) {
94 ToolBar::instance()->selectTool(tool);
95 }
96
97 update_screen_for_document(document);
98}
99
100Command* CommandFactory::createMaskContentCommand()
101{
102 return new MaskContentCommand;
103}
104
105} // namespace app
106