1// Aseprite
2// Copyright (C) 2019-2022 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_palette.h"
13#include "app/commands/command.h"
14#include "app/commands/params.h"
15#include "app/context_access.h"
16#include "app/tx.h"
17#include "doc/palette.h"
18#include "doc/sprite.h"
19
20#include "palette_size.xml.h"
21
22#include <limits>
23
24namespace app {
25
26class PaletteSizeCommand : public Command {
27public:
28 PaletteSizeCommand();
29
30protected:
31 void onLoadParams(const Params& params) override;
32 bool onEnabled(Context* context) override;
33 void onExecute(Context* context) override;
34
35private:
36 int m_size;
37};
38
39PaletteSizeCommand::PaletteSizeCommand()
40 : Command(CommandId::PaletteSize(), CmdRecordableFlag)
41{
42 m_size = 0;
43}
44
45void PaletteSizeCommand::onLoadParams(const Params& params)
46{
47 m_size = params.get_as<int>("size");
48}
49
50bool PaletteSizeCommand::onEnabled(Context* context)
51{
52 return context->checkFlags(ContextFlags::ActiveDocumentIsWritable);
53}
54
55void PaletteSizeCommand::onExecute(Context* context)
56{
57 ContextReader reader(context);
58 const frame_t frame = reader.frame();
59 ASSERT(reader.palette());
60 Palette palette(*reader.palette());
61 int ncolors = (m_size != 0 ? m_size: palette.size());
62
63#ifdef ENABLE_UI
64 if (m_size == 0 && context->isUIAvailable()) {
65 app::gen::PaletteSize window;
66 window.colors()->setTextf("%d", ncolors);
67 window.openWindowInForeground();
68 if (window.closer() != window.ok())
69 return;
70
71 ncolors = window.colors()->textInt();
72 }
73#endif
74
75 if (ncolors == palette.size())
76 return;
77
78 palette.resize(std::clamp(ncolors, 1, std::numeric_limits<int>::max()));
79
80 ContextWriter writer(reader);
81 Tx tx(context, "Palette Size", ModifyDocument);
82 tx(new cmd::SetPalette(writer.sprite(), frame, &palette));
83 tx.commit();
84}
85
86Command* CommandFactory::createPaletteSizeCommand()
87{
88 return new PaletteSizeCommand;
89}
90
91} // namespace app
92