1// Aseprite
2// Copyright (C) 2019-2020 Igara Studio S.A.
3//
4// This program is distributed under the terms of
5// the End-User License Agreement for Aseprite.
6
7#ifdef HAVE_CONFIG_H
8#include "config.h"
9#endif
10
11#include "app/cmd/add_tileset.h"
12
13#include "doc/sprite.h"
14#include "doc/subobjects_io.h"
15#include "doc/tileset.h"
16#include "doc/tileset_io.h"
17#include "doc/tilesets.h"
18
19namespace app {
20namespace cmd {
21
22using namespace doc;
23
24AddTileset::AddTileset(doc::Sprite* sprite, doc::Tileset* tileset)
25 : WithSprite(sprite)
26 , WithTileset(tileset)
27 , m_size(0)
28 , m_tilesetIndex(-1)
29{
30}
31
32AddTileset::AddTileset(doc::Sprite* sprite, const doc::tileset_index tsi)
33 : WithSprite(sprite)
34 , WithTileset(sprite->tilesets()->get(tsi))
35 , m_size(0)
36 , m_tilesetIndex(tsi)
37{
38}
39
40void AddTileset::onExecute()
41{
42 Tileset* tileset = this->tileset();
43
44 addTileset(tileset);
45}
46
47void AddTileset::onUndo()
48{
49 doc::Tileset* tileset = this->tileset();
50 write_tileset(m_stream, tileset);
51 m_size = size_t(m_stream.tellp());
52
53 doc::Sprite* sprite = this->sprite();
54 sprite->tilesets()->erase(m_tilesetIndex);
55
56 sprite->incrementVersion();
57 sprite->tilesets()->incrementVersion();
58
59 delete tileset;
60}
61
62void AddTileset::onRedo()
63{
64 auto sprite = this->sprite();
65 doc::Tileset* tileset = read_tileset(m_stream, sprite);
66
67 addTileset(tileset);
68
69 m_stream.str(std::string());
70 m_stream.clear();
71 m_size = 0;
72}
73
74void AddTileset::addTileset(doc::Tileset* tileset)
75{
76 auto sprite = this->sprite();
77
78 if (m_tilesetIndex == -1)
79 m_tilesetIndex = sprite->tilesets()->add(tileset);
80 else
81 sprite->tilesets()->set(m_tilesetIndex, tileset);
82
83 sprite->incrementVersion();
84 sprite->tilesets()->incrementVersion();
85}
86
87} // namespace cmd
88} // namespace app
89