z_mirror/CursorEnhancements

git clone https://git.raiguard.me/z_mirror/CursorEnhancements

Caleb HeuerClear item history on configuration changed and harden against crash55b779d

trunk
2.3 KiB101 linesraw
1local util = require("scripts.util")
2
3local max_history_size = 10
4
5--- @param e EventData.CustomInputEvent
6local function on_recall_last_item(e)
7  local player = game.get_player(e.player_index)
8  if not player then
9    return
10  end
11
12  local history = storage.item_history[e.player_index]
13  if not history then
14    return
15  end
16  local index = storage.history_index[e.player_index]
17
18  if not (history and index) then
19    return
20  end
21
22  local cursor_item = util.get_cursor_item(player)
23  if cursor_item and index <= 1 then
24    index = index + 1
25  end
26
27  local item = history[index]
28  if not item or not item.name.valid or not item.quality.valid then
29    return
30  end
31
32  util.set_cursor(player, item)
33
34  if index + 1 > #history then
35    storage.history_index[e.player_index] = 0
36  else
37    storage.history_index[e.player_index] = index + 1
38  end
39
40  storage.item_update_tick[e.player_index] = e.tick
41end
42
43--- @param e EventData.on_player_cursor_stack_changed
44local function on_player_cursor_stack_changed(e)
45  local player = game.get_player(e.player_index)
46  if not player then
47    return
48  end
49
50  if e.tick == storage.item_update_tick[e.player_index] then
51    return
52  end
53
54  local history = storage.item_history[e.player_index]
55  if not history then
56    history = {}
57    storage.item_history[e.player_index] = history
58  end
59
60  storage.history_index[e.player_index] = 1
61
62  local cursor_item = util.get_cursor_item(player)
63  if not cursor_item or cursor_item.name.has_flag("spawnable") then
64    return
65  end
66
67  for i, history_item in pairs(history) do
68    if serpent.line(cursor_item) == serpent.line(history_item) then
69      table.insert(history, 1, table.remove(history, i))
70      return
71    end
72  end
73
74  table.insert(history, 1, cursor_item)
75
76  if #history > max_history_size then
77    table.remove(history)
78  end
79end
80
81local function init()
82  --- @type table<uint, ItemWithQualityID[]?>
83  storage.item_history = {}
84  --- @type table<uint, number>
85  storage.item_update_tick = {}
86  --- @type table<uint, number>
87  storage.history_index = {}
88end
89
90--- @type event_handler
91local recall_last_item = {}
92
93recall_last_item.on_init = init
94recall_last_item.on_configuration_changed = init
95
96recall_last_item.events = {
97  ["cen-recall-last-item"] = on_recall_last_item,
98  [defines.events.on_player_cursor_stack_changed] = on_player_cursor_stack_changed,
99}
100
101return recall_last_item