1// Aseprite
2// Copyright (C) 2018 Igara Studio S.A.
3// Copyright (C) 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/script/docobj.h"
13#include "app/script/engine.h"
14#include "app/script/luacpp.h"
15#include "doc/sprite.h"
16
17namespace app {
18namespace script {
19
20using namespace doc;
21
22namespace {
23
24struct PalettesObj {
25 ObjectId spriteId;
26 PalettesObj(Sprite* sprite)
27 : spriteId(sprite->id()) {
28 }
29 PalettesObj(const PalettesObj&) = delete;
30 PalettesObj& operator=(const PalettesObj&) = delete;
31
32 Sprite* sprite(lua_State* L) { return check_docobj(L, doc::get<Sprite>(spriteId)); }
33};
34
35int Palettes_gc(lua_State* L)
36{
37 get_obj<PalettesObj>(L, 1)->~PalettesObj();
38 return 0;
39}
40
41int Palettes_len(lua_State* L)
42{
43 auto obj = get_obj<PalettesObj>(L, 1);
44 lua_pushinteger(L, obj->sprite(L)->getPalettes().size());
45 return 1;
46}
47
48int Palettes_index(lua_State* L)
49{
50 auto obj = get_obj<PalettesObj>(L, 1);
51 auto sprite = obj->sprite(L);
52 auto& pals = sprite->getPalettes();
53 int i = lua_tointeger(L, 2);
54 if (i < 1 || i > int(pals.size()))
55 return luaL_error(L, "index out of bounds %d", i);
56 push_sprite_palette(L, sprite, pals[i-1]);
57 return 1;
58}
59
60const luaL_Reg Palettes_methods[] = {
61 { "__gc", Palettes_gc },
62 { "__len", Palettes_len },
63 { "__index", Palettes_index },
64 { nullptr, nullptr }
65};
66
67} // anonymous namespace
68
69DEF_MTNAME(PalettesObj);
70
71void register_palettes_class(lua_State* L)
72{
73 using Palettes = PalettesObj;
74 REG_CLASS(L, Palettes);
75}
76
77void push_sprite_palettes(lua_State* L, Sprite* sprite)
78{
79 push_new<PalettesObj>(L, sprite);
80}
81
82} // namespace script
83} // namespace app
84