1// Aseprite
2// Copyright (C) 2021 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/replace_tileset.h"
12
13#include "doc/layer.h"
14#include "doc/layer_tilemap.h"
15#include "doc/sprite.h"
16#include "doc/sprite.h"
17#include "doc/tileset.h"
18#include "doc/tileset_io.h"
19#include "doc/tilesets.h"
20
21namespace app {
22namespace cmd {
23
24using namespace doc;
25
26ReplaceTileset::ReplaceTileset(doc::Sprite* sprite,
27 const doc::tileset_index tsi,
28 doc::Tileset* newTileset)
29 : WithSprite(sprite)
30 , m_tsi(tsi)
31 , m_newTileset(newTileset)
32{
33}
34
35void ReplaceTileset::onExecute()
36{
37 Sprite* spr = sprite();
38 doc::Tileset* actualTileset = spr->tilesets()->get(m_tsi);
39 doc::Tileset* restoreTileset;
40 if (m_newTileset) {
41 restoreTileset = m_newTileset;
42 m_newTileset = nullptr;
43 }
44 else {
45 restoreTileset = doc::read_tileset(m_stream, spr, true);
46 }
47
48 m_stream.str(std::string());
49 m_stream.clear();
50 doc::write_tileset(m_stream, actualTileset);
51 m_size = size_t(m_stream.tellp());
52
53 replaceTileset(restoreTileset);
54 delete actualTileset;
55}
56
57void ReplaceTileset::replaceTileset(Tileset* newTileset)
58{
59 Sprite* spr = sprite();
60
61 for (Layer* lay : spr->allLayers()) {
62 if (lay->isTilemap() &&
63 static_cast<LayerTilemap*>(lay)->tilesetIndex() == m_tsi) {
64 lay->incrementVersion();
65 }
66 }
67
68 spr->replaceTileset(m_tsi, newTileset);
69 spr->tilesets()->incrementVersion();
70 spr->incrementVersion();
71}
72
73} // namespace cmd
74} // namespace app
75