1// Aseprite Document Library
2// Copyright (C) 2019 Igara Studio S.A.
3// Copyright (C) 2001-2016 David Capello
4//
5// This file is released under the terms of the MIT license.
6// Read LICENSE.txt for more information.
7
8#ifdef HAVE_CONFIG_H
9#include "config.h"
10#endif
11
12#include "doc/tags.h"
13
14#include "base/debug.h"
15#include "doc/tag.h"
16
17#include <algorithm>
18
19namespace doc {
20
21Tags::Tags(Sprite* sprite)
22 : m_sprite(sprite)
23{
24}
25
26Tags::~Tags()
27{
28 for (Tag* tag : m_tags) {
29 tag->setOwner(nullptr);
30 delete tag;
31 }
32}
33
34void Tags::add(Tag* tag)
35{
36 auto it = begin(), end = this->end();
37 for (; it != end; ++it) {
38 if ((*it)->fromFrame() > tag->fromFrame() ||
39 ((*it)->fromFrame() == tag->fromFrame() &&
40 (*it)->toFrame() < tag->toFrame()))
41 break;
42 }
43 m_tags.insert(it, tag);
44 tag->setOwner(this);
45}
46
47void Tags::remove(Tag* tag)
48{
49 auto it = std::find(m_tags.begin(), m_tags.end(), tag);
50 ASSERT(it != m_tags.end());
51 if (it != m_tags.end())
52 m_tags.erase(it);
53
54 tag->setOwner(nullptr);
55}
56
57Tag* Tags::getByName(const std::string& name) const
58{
59 for (Tag* tag : *this) {
60 if (tag->name() == name)
61 return tag;
62 }
63 return nullptr;
64}
65
66Tag* Tags::getById(ObjectId id) const
67{
68 for (Tag* tag : *this) {
69 if (tag->id() == id)
70 return tag;
71 }
72 return nullptr;
73}
74
75Tag* Tags::innerTag(const frame_t frame) const
76{
77 const Tag* found = nullptr;
78 for (const Tag* tag : *this) {
79 if (frame >= tag->fromFrame() &&
80 frame <= tag->toFrame()) {
81 if (!found ||
82 (tag->toFrame() - tag->fromFrame()) < (found->toFrame() - found->fromFrame())) {
83 found = tag;
84 }
85 }
86 }
87 return const_cast<Tag*>(found);
88}
89
90Tag* Tags::outerTag(const frame_t frame) const
91{
92 const Tag* found = nullptr;
93 for (const Tag* tag : *this) {
94 if (frame >= tag->fromFrame() &&
95 frame <= tag->toFrame()) {
96 if (!found ||
97 (tag->toFrame() - tag->fromFrame()) > (found->toFrame() - found->fromFrame())) {
98 found = tag;
99 }
100 }
101 }
102 return const_cast<Tag*>(found);
103}
104
105} // namespace doc
106