]> git.tdb.fi Git - libs/gltk.git/blob - source/listdata.h
38706f8b1cc9ac64648c8b4a0202034b5e1475c3
[libs/gltk.git] / source / listdata.h
1 #ifndef MSP_GLTK_LISTDATA_H_
2 #define MSP_GLTK_LISTDATA_H_
3
4 #include <string>
5 #include <vector>
6 #include <sigc++/signal.h>
7 #include <msp/strings/lexicalcast.h>
8
9 namespace Msp {
10 namespace GLtk {
11
12 class ListData
13 {
14 public:
15         sigc::signal<void, unsigned> signal_item_added;
16         sigc::signal<void, unsigned> signal_item_removed;
17         sigc::signal<void> signal_cleared;
18         sigc::signal<void> signal_refresh_strings;
19
20 protected:
21         ListData() { }
22 public:
23         virtual ~ListData() { }
24
25         virtual unsigned size() const = 0;
26         virtual std::string get_string(unsigned) const = 0;
27         void refresh_strings() const { signal_refresh_strings.emit(); }
28 };
29
30 template<typename T>
31 class ListDataStore: public ListData
32 {
33 protected:
34         std::vector<T> items;
35
36         ListDataStore() { }
37
38 public:
39         void append(const T &v) { insert(items.size(), v); }
40
41         void insert(unsigned i, const T & v)
42         {
43                 if(i>items.size())
44                         throw std::out_of_range("ListDataStore::insert");
45
46                 items.insert(items.begin()+i, v);
47                 signal_item_added.emit(i);
48         }
49
50         const T &get(unsigned i) const
51         {
52                 if(i>=items.size())
53                         throw std::out_of_range("ListDataStore::get");
54
55                 return items[i];
56         }
57
58         void remove(unsigned i)
59         {
60                 if(i>=items.size())
61                         throw std::out_of_range("ListDataStore::remove");
62
63                 items.erase(items.begin()+i);
64                 signal_item_removed.emit(i);
65         }
66
67         void clear()
68         {
69                 items.clear();
70                 signal_cleared.emit();
71         }
72
73         virtual unsigned size() const { return items.size(); }
74 };
75
76 template<typename T>
77 class BasicListData: public ListDataStore<T>
78 {
79 public:
80         virtual std::string get_string(unsigned i) const
81         { return lexical_cast<std::string>(this->get(i)); }
82 };
83
84 template<typename T>
85 class FunctionListData: public ListDataStore<T>
86 {
87 public:
88         typedef std::string Func(const T &);
89
90 private:
91         Func *func;
92
93 public:
94         FunctionListData(Func f): func(f) { }
95
96         virtual std::string get_string(unsigned i) const
97         { return func(this->get(i)); }
98 };
99
100 } // namespace GLtk
101 } // namespace Msp
102
103 #endif