]> git.lizzy.rs Git - nothing.git/blob - src/game/level/level_editor/undo_history.c
Remove Lt from LevelEditor
[nothing.git] / src / game / level / level_editor / undo_history.c
1 #include <stdlib.h>
2 #include <stdio.h>
3
4 #include <SDL.h>
5
6 #include "system/nth_alloc.h"
7 #include "system/stacktrace.h"
8 #include "undo_history.h"
9 #include "config.h"
10
11 typedef struct {
12     RevertAction revert;
13     void *context_data;
14     size_t context_data_size;
15 } HistoryItem;
16
17 static
18 void undo_history_destroy_item(void *item)
19 {
20     free(((HistoryItem*)item)->context_data);
21 }
22
23 UndoHistory create_undo_history(void)
24 {
25     UndoHistory result;
26     result.actions = create_ring_buffer(
27         sizeof(HistoryItem),
28         UNDO_HISTORY_CAPACITY,
29         undo_history_destroy_item);
30     return result;
31 }
32
33 void undo_history_push(UndoHistory *undo_history,
34                        RevertAction revert,
35                        void *context_data,
36                        size_t context_data_size)
37 {
38     trace_assert(undo_history);
39
40     HistoryItem item = {
41         .revert = revert,
42         .context_data = malloc(context_data_size),
43         .context_data_size = context_data_size
44     };
45     trace_assert(item.context_data);
46     memcpy(item.context_data, context_data, context_data_size);
47
48     ring_buffer_push(&undo_history->actions, &item);
49 }
50
51 void undo_history_pop(UndoHistory *undo_history)
52 {
53     trace_assert(undo_history);
54
55     if (undo_history->actions.count > 0) {
56         HistoryItem *item = ring_buffer_top(&undo_history->actions);
57         item->revert(item->context_data, item->context_data_size);
58         ring_buffer_pop(&undo_history->actions);
59     }
60 }
61
62 void undo_history_clean(UndoHistory *undo_history)
63 {
64     trace_assert(undo_history);
65
66     while (undo_history->actions.count) {
67         ring_buffer_pop(&undo_history->actions);
68     }
69 }