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_tile.h"
12
13#include "app/doc.h"
14#include "doc/image_io.h"
15#include "doc/sprite.h"
16#include "doc/tileset.h"
17#include "doc/tilesets.h"
18
19namespace app {
20namespace cmd {
21
22AddTile::AddTile(doc::Tileset* tileset,
23 const doc::ImageRef& image)
24 : WithTileset(tileset)
25 , WithImage(image.get())
26 , m_size(0)
27 , m_tileIndex(doc::notile)
28 , m_imageRef(image)
29{
30}
31
32AddTile::AddTile(doc::Tileset* tileset,
33 const doc::tile_index ti)
34 : WithTileset(tileset)
35 , WithImage(tileset->get(ti).get())
36 , m_size(0)
37 , m_tileIndex(ti)
38 , m_imageRef(nullptr)
39{
40}
41
42void AddTile::onExecute()
43{
44 doc::Tileset* tileset = this->tileset();
45 ASSERT(tileset);
46
47 if (m_tileIndex != doc::notile) {
48 ASSERT(!m_imageRef);
49 tileset->sprite()->incrementVersion();
50 tileset->incrementVersion();
51 }
52 else {
53 ASSERT(m_imageRef);
54 addTile(tileset, m_imageRef);
55 m_imageRef.reset();
56 }
57}
58
59void AddTile::onUndo()
60{
61 doc::Tileset* tileset = this->tileset();
62 ASSERT(tileset);
63
64 write_image(m_stream, image());
65 m_size = size_t(m_stream.tellp());
66
67 tileset->erase(m_tileIndex);
68
69 tileset->sprite()->incrementVersion();
70 tileset->incrementVersion();
71}
72
73void AddTile::onRedo()
74{
75 doc::Tileset* tileset = this->tileset();
76
77 ASSERT(!m_imageRef);
78 m_imageRef.reset(read_image(m_stream));
79 ASSERT(m_imageRef);
80
81 addTile(tileset, m_imageRef);
82 m_imageRef.reset();
83
84 m_stream.str(std::string());
85 m_stream.clear();
86 m_size = 0;
87}
88
89void AddTile::onFireNotifications()
90{
91 doc::Tileset* tileset = this->tileset();
92
93 // Notify that the tileset's changed
94 static_cast<Doc*>(tileset->sprite()->document())
95 ->notifyTilesetChanged(tileset);
96}
97
98void AddTile::addTile(doc::Tileset* tileset, const doc::ImageRef& image)
99{
100 if (m_tileIndex == doc::notile)
101 m_tileIndex = tileset->add(image);
102 else
103 tileset->insert(m_tileIndex, image);
104
105 tileset->sprite()->incrementVersion();
106 tileset->incrementVersion();
107}
108
109} // namespace cmd
110} // namespace app
111