From 1439109f0f50f0a8fb64f322d2bb6b033f6f1627 Mon Sep 17 00:00:00 2001 From: Kelly Kinkade Date: Sun, 29 Nov 2026 09:53:47 -0600 Subject: [PATCH 1/4] fix slow trade good marking rewrite the UI and backend processing for `movegoods` to avoid repeatedly retraversing the item list while (un)marking items for trade also use a coroutine to ensure the frame pump continues to run when (un)marking a large number of items fixes DFHack/dfhack#6050 --- changelog.txt | 1 + internal/caravan/movegoods.lua | 151 ++++++++++++++++++++++++++++----- test/caravan/movegoods.lua | 2 + 3 files changed, 135 insertions(+), 19 deletions(-) diff --git a/changelog.txt b/changelog.txt index bcad33ea6..22b641bfa 100644 --- a/changelog.txt +++ b/changelog.txt @@ -31,6 +31,7 @@ Template for new versions: ## New Features ## Fixes +- `caravan`: fix UI freeze in the ``Move goods to/from depot`` dialog when marking or unmarking large item groups; item lists are now built incrementally so the UI stays responsive ## Misc Improvements diff --git a/internal/caravan/movegoods.lua b/internal/caravan/movegoods.lua index 1feab69f6..b07e38f90 100644 --- a/internal/caravan/movegoods.lua +++ b/internal/caravan/movegoods.lua @@ -149,6 +149,14 @@ function MoveGoods:init() self.marked = {} self.item_values = {} self.items_by_id = {} + -- maps each item id to the shared choice data tables that contain it so + -- toggles can be propagated without rescanning the choice lists + self.datas_by_item = {} + -- items are scanned incrementally so the UI stays responsive on forts + -- with many items; scan_queued holds the inside_containers settings that + -- are waiting to be built and self.scan holds the in-progress scan + self.scan_queued = {} + self.on_render = self:callback('pump_scan') self.animal_ethics, self.wood_ethics = get_ethics_restrictions() self.banned_items = common.get_banned_items() @@ -288,6 +296,19 @@ function MoveGoods:init() frame={l=0, t=2}, text='Click to mark/unmark for trade. Shift click to mark/unmark a range of items.', }, + widgets.Label{ + view_id='scan_status', + frame={r=0, t=0}, + auto_width=true, + visible=function() + return self.scan ~= nil or next(self.scan_queued) ~= nil + end, + text={{text=function() + local scan = self.scan + if not scan then return 'Scanning items...' end + return ('Scanning items... %d/%d'):format(scan.cursor, scan.total) + end}}, + }, widgets.HotkeyLabel{ frame={l=0, b=0}, label='Select all/none', @@ -486,15 +507,49 @@ local function get_distance(bld, pos) return math.max(math.abs(bld.centerx - pos.x), math.abs(bld.centery - pos.y)) + math.abs(bld.z - pos.z) end +-- item scanning runs incrementally in a coroutine so the UI stays responsive +-- on forts with a large number of items. the coroutine yields after each time +-- slice and is resumed once per rendered frame by pump_scan(). +local SCAN_TIME_BUDGET_MS = 10 +local SCAN_TIME_CHECK = 32 + +function MoveGoods:request_scan(inside_containers) + -- a single scan builds both the grouped and ungrouped choice lists for + -- its inside_containers setting + if self.choices_cache[get_cache_index(true, inside_containers)] then return end + if self.scan and self.scan.inside_containers == inside_containers then return end + self.scan_queued[inside_containers] = true +end + function MoveGoods:cache_choices() local group_items = self.subviews.group_items:getOptionValue() local inside_containers = self.subviews.inside_containers:getOptionValue() local cache_idx = get_cache_index(group_items, inside_containers) - if self.choices_cache[cache_idx] then return self.choices_cache[cache_idx] end + if not self.choices_cache[cache_idx] then + -- request the lists to be built asynchronously; the visible choices + -- will be populated when the scan completes + self:request_scan(inside_containers) + return nil + end + return self.choices_cache[cache_idx] +end +-- scans all items and builds the grouped and ungrouped choice lists for the +-- scan's inside_containers setting. runs inside a coroutine and yields after +-- each time slice so the UI does not stall while the lists are built. +function MoveGoods:build_choices(scan) + local inside_containers = scan.inside_containers local pending = self.pending_item_ids local groups = {} - for _, item in ipairs(df.global.world.items.other.IN_PLAY) do + local items = df.global.world.items.other.IN_PLAY + local deadline = dfhack.getTickCount() + SCAN_TIME_BUDGET_MS + for i = 0, #items - 1 do + if i % SCAN_TIME_CHECK == 0 and dfhack.getTickCount() >= deadline then + scan.cursor = i + coroutine.yield() + deadline = dfhack.getTickCount() + SCAN_TIME_BUDGET_MS + end + local item = items[i] if not item or not is_tradeable_item(item, self.depot) then goto continue end if inside_containers and is_container(item) and contains_non_liquid_powder(item) then goto continue @@ -568,17 +623,33 @@ function MoveGoods:cache_choices() ::continue:: end + scan.cursor = #items + local group_choices, nogroup_choices = {}, {} local cache_threshold = common.get_threshold(common.get_broker_skill()) + local processed = 0 for _, group in pairs(groups) do local data = group.data for item_id, item_data in pairs(data.items) do + -- index the shared data tables that contain each item so toggles + -- can be propagated without rescanning the choice lists + local datas = self.datas_by_item[item_id] + if not datas then + datas = {} + self.datas_by_item[item_id] = datas + end + datas[data] = true local nogroup_choice = copyall(group) nogroup_choice.icon = curry(get_entry_icon, data, item_id) nogroup_choice.text = make_choice_text(item_data.item.flags.in_building, data.dist, data.per_item_value, 1, data.desc, cache_threshold) nogroup_choice.item_id = item_id table.insert(nogroup_choices, nogroup_choice) + processed = processed + 1 + if processed % SCAN_TIME_CHECK == 0 and dfhack.getTickCount() >= deadline then + coroutine.yield() + deadline = dfhack.getTickCount() + SCAN_TIME_BUDGET_MS + end end data.total_value = data.per_item_value * data.quantity group.text = make_choice_text(data.num_at_depot == data.quantity, data.dist, @@ -595,15 +666,53 @@ function MoveGoods:cache_choices() if is_marked then self.value_pending = self.value_pending + (self.item_values[item_id] or 0) end + processed = processed + 1 + if processed % SCAN_TIME_CHECK == 0 and dfhack.getTickCount() >= deadline then + coroutine.yield() + deadline = dfhack.getTickCount() + SCAN_TIME_BUDGET_MS + end end self.choices_cache[get_cache_index(true, inside_containers)] = group_choices self.choices_cache[get_cache_index(false, inside_containers)] = nogroup_choices - return self.choices_cache[cache_idx] +end + +-- starts the next queued scan or resumes the in-progress scan. called once +-- per rendered frame via the on_render hook so the UI stays responsive while +-- the choice lists are being built. +function MoveGoods:pump_scan() + if not self.scan then + local inside_containers = next(self.scan_queued) + if inside_containers == nil then return end + self.scan_queued[inside_containers] = nil + local scan = { + inside_containers=inside_containers, + cursor=0, + total=#df.global.world.items.other.IN_PLAY, + } + scan.coro = coroutine.create(function() self:build_choices(scan) end) + self.scan = scan + end + -- the choice list is still being built; don't show 'No matches' + self.subviews.list.not_found.visible = false + local ok, err = coroutine.resume(self.scan.coro) + if not ok then error(err, 0) end + if coroutine.status(self.scan.coro) == 'dead' then + self.scan = nil + self:refresh_list() + end +end + +-- runs all queued scans to completion, ensuring items_by_id is populated for +-- every item that could have been marked +function MoveGoods:finish_scans() + while self.scan ~= nil or next(self.scan_queued) ~= nil do + self:pump_scan() + end end function MoveGoods:get_choices() - local raw_choices = self:cache_choices() + local raw_choices = self:cache_choices() or {} local choices = {} local include_forbidden = not self.subviews.hide_forbidden:getOptionValue() local provenance = self.subviews.provenance:getOptionValue() @@ -675,29 +784,32 @@ function MoveGoods:get_choices() end -- keeps the marked flag consistent in every cached choice list that contains --- this item so other filter views reflect the toggle +-- this item so other filter views reflect the toggle. the items tables are +-- shared between the grouped and ungrouped lists, so updating each data table +-- once updates every row that displays it. function MoveGoods:sync_marked(item_id) local marked = self.marked[item_id] - for _, choices in pairs(self.choices_cache) do - for _, choice in ipairs(choices) do - local items = choice.data.items - if items[item_id] then - items[item_id].pending = marked - local selected = 0 - for _, item_data in pairs(items) do - if item_data.pending then selected = selected + 1 end - end - choice.data.selected = selected - end + local pending_changed = false + for data in pairs(self.datas_by_item[item_id] or {}) do + local item_data = data.items[item_id] + if item_data.pending ~= marked then + item_data.pending = marked + data.selected = data.selected + (marked and 1 or -1) + pending_changed = true end end + -- only count the value when the item's effective marked state changed; an + -- item that was already pending via the default state gains no value when + -- it is explicitly marked + if pending_changed then + self.value_pending = self.value_pending + + (self.item_values[item_id] or 0) * (marked and 1 or -1) + end end function MoveGoods:set_marked(item_id, marked) if self.marked[item_id] == marked then return end self.marked[item_id] = marked - self.value_pending = self.value_pending + - (self.item_values[item_id] or 0) * (marked and 1 or -1) self:sync_marked(item_id) end @@ -787,7 +899,8 @@ function MoveGoodsModal:onDismiss() local depot = self.depot if not depot then return end local move_goods = self.subviews.move_goods - move_goods:cache_choices() -- make sure marked/items_by_id are populated + -- every id in marked comes from a completed scan, so items_by_id is + -- already populated for all of them even if a scan is still running local pending = self.pending_item_ids for item_id, marked in pairs(move_goods.marked) do local item = move_goods.items_by_id[item_id] diff --git a/test/caravan/movegoods.lua b/test/caravan/movegoods.lua index bc2ac186a..a5b8c3613 100644 --- a/test/caravan/movegoods.lua +++ b/test/caravan/movegoods.lua @@ -49,6 +49,7 @@ local function run_check() w.subviews.inside_containers:setOption(inside and 'Yes' or 'No') w.subviews.group_items:setOption(group and 'Yes' or 'No') w:cache_choices() + w:finish_scans() expect.eq(expected_pending(w), w.value_pending) end end @@ -85,6 +86,7 @@ function test.marks_persist_across_filter_views() w.subviews.inside_containers:setOption(inside and 'Yes' or 'No') w.subviews.group_items:setOption(group and 'Yes' or 'No') w:cache_choices() + w:finish_scans() local c = find_choice(w, marked_id) if c then expect.true_(c.data.items[marked_id].pending) end end From a1882fd3e90a7228887660daeac26feb82ea5c95 Mon Sep 17 00:00:00 2001 From: Kelly Kinkade Date: Sun, 29 Nov 2026 11:37:47 -0600 Subject: [PATCH 2/4] optimize item scanning item scan in the test fort i am using was taking ~6s. these changes trim it to about ~2s which is a significant improvement will look into why dfhack.item.* methods are so slow to invoke (~95-100 microseconds per call) - there might be a core issue here that can be mitigated but that'll be done separately --- changelog.txt | 2 +- internal/caravan/common.lua | 33 +-- internal/caravan/movegoods.lua | 381 ++++++++++++++++++++++++--------- 3 files changed, 294 insertions(+), 122 deletions(-) diff --git a/changelog.txt b/changelog.txt index 22b641bfa..4a5aa7ee1 100644 --- a/changelog.txt +++ b/changelog.txt @@ -31,7 +31,7 @@ Template for new versions: ## New Features ## Fixes -- `caravan`: fix UI freeze in the ``Move goods to/from depot`` dialog when marking or unmarking large item groups; item lists are now built incrementally so the UI stays responsive +- `caravan`: fix UI freeze in the ``Move goods to/from depot`` dialog when marking or unmarking large item groups; item lists are now built incrementally so the UI stays responsive, and the item scan itself is faster ## Misc Improvements diff --git a/internal/caravan/common.lua b/internal/caravan/common.lua index e0a54b0b0..73bea8a25 100644 --- a/internal/caravan/common.lua +++ b/internal/caravan/common.lua @@ -92,10 +92,16 @@ function obfuscate_value(value, threshold) return ('%s?'):format(estimate(threshold*30, 999, 1000)) end --- takes into account trade agreements -function get_perceived_value(item, caravan_state) +local EMPTY_CONTAINED = {} + +-- takes into account trade agreements. contained is an optional precomputed +-- contents list so callers that scan many items can look it up once per item. +function get_perceived_value(item, caravan_state, contained) local value = dfhack.items.getValue(item, caravan_state) - for _,contained_item in ipairs(dfhack.items.getContainedItems(item)) do + if not contained then + contained = item.flags.container and dfhack.items.getContainedItems(item) or EMPTY_CONTAINED + end + for _,contained_item in ipairs(contained) do value = value + dfhack.items.getValue(contained_item, caravan_state) for _,contained_contained_item in ipairs(dfhack.items.getContainedItems(contained_item)) do value = value + dfhack.items.getValue(contained_contained_item, caravan_state) @@ -611,21 +617,20 @@ function get_info_widgets(self, export_agreements, strict_ethical_bins_default, end local function match_risky(item, risky_items) - for item_type, subtypes in pairs(risky_items) do - for subtype in pairs(subtypes) do - if item_type == item:getType() and (subtype == -1 or subtype == item:getSubtype()) then - return true - end - end - end - return false + local subtypes = risky_items[item:getType()] + if not subtypes then return false end + return subtypes[-1] ~= nil or subtypes[item:getSubtype()] ~= nil end --- returns is_banned, is_risky -function scan_banned(item, risky_items) +-- returns is_banned, is_risky. contained is an optional precomputed contents +-- list so callers that scan many items can look it up once per item. +function scan_banned(item, risky_items, contained) if not dfhack.items.checkMandates(item) then return true, true end if match_risky(item, risky_items) then return false, true end - for _,contained_item in ipairs(dfhack.items.getContainedItems(item)) do + if not contained then + contained = item.flags.container and dfhack.items.getContainedItems(item) or EMPTY_CONTAINED + end + for _,contained_item in ipairs(contained) do if not dfhack.items.checkMandates(contained_item) then return true, true end if match_risky(contained_item, risky_items) then return false, true end end diff --git a/internal/caravan/movegoods.lua b/internal/caravan/movegoods.lua index b07e38f90..e5abc008b 100644 --- a/internal/caravan/movegoods.lua +++ b/internal/caravan/movegoods.lua @@ -153,9 +153,11 @@ function MoveGoods:init() -- toggles can be propagated without rescanning the choice lists self.datas_by_item = {} -- items are scanned incrementally so the UI stays responsive on forts - -- with many items; scan_queued holds the inside_containers settings that - -- are waiting to be built and self.scan holds the in-progress scan + -- with many items; scan_queued and nogroup_queued hold the + -- inside_containers settings waiting to be built and self.scan holds the + -- in-progress build self.scan_queued = {} + self.nogroup_queued = {} self.on_render = self:callback('pump_scan') self.animal_ethics, self.wood_ethics = get_ethics_restrictions() @@ -302,11 +304,13 @@ function MoveGoods:init() auto_width=true, visible=function() return self.scan ~= nil or next(self.scan_queued) ~= nil + or next(self.nogroup_queued) ~= nil end, text={{text=function() local scan = self.scan if not scan then return 'Scanning items...' end - return ('Scanning items... %d/%d'):format(scan.cursor, scan.total) + local label = scan.kind == 'nogroup' and 'Building item list' or 'Scanning items' + return ('%s... %d/%d'):format(label, scan.cursor, scan.total) end}}, }, widgets.HotkeyLabel{ @@ -377,43 +381,74 @@ local function is_container(item) ) end -local function is_tradeable_item(item, depot) - if item.flags.hostile or - item.flags.removed or - item.flags.dead_dwarf or - item.flags.spider_web or - item.flags.construction or - item.flags.encased or - item.flags.murder or - item.flags.trader or - item.flags.owned or - item.flags.garbage_collect or - item.flags.on_fire +-- dfhack.items.getPosition returns an unpacked triple or nil; repack it so +-- the result can be reused for the distance column and tile keys. for items +-- not in an inventory the C++ just returns item->pos, so read the field +-- directly and only pay for the call when the ref walk can differ. +local function item_pos(item, flags) + if flags.in_inventory then + local x, y, z = dfhack.items.getPosition(item) + return x and xyz2pos(x, y, z) or nil + end + -- field read mirrors the C++ return; invalid coords read as -30000 + local pos = item.pos + return pos.x ~= -30000 and pos or nil +end + +-- returns the item's position if it is tradeable, or false if not. returning +-- the position lets callers reuse it for the distance column instead of +-- walking the item refs again. walkable_cache memoizes the (expensive) +-- canWalkBetween check per tile since stockpile items cluster heavily. +local function is_tradeable_item(item, depot, depot_pos, walkable_cache) + local flags = item.flags + if flags.hostile or + flags.removed or + flags.dead_dwarf or + flags.spider_web or + flags.construction or + flags.encased or + flags.murder or + flags.trader or + flags.owned or + flags.garbage_collect or + flags.on_fire then return false end - if item.flags.in_inventory then + if flags.in_inventory then local gref = dfhack.items.getGeneralRef(item, df.general_ref_type.CONTAINED_IN_ITEM) if not gref then return false end if not is_container(gref:getItem()) or item:isLiquidPowder() then return false end end - if item.flags.in_job then + if flags.in_job then local spec_ref = dfhack.items.getSpecificRef(item, df.specific_ref_type.JOB) - if not spec_ref then return true end - return spec_ref.data.job.job_type == df.job_type.BringItemToDepot + if not spec_ref then return item_pos(item, flags) or false end + if spec_ref.data.job.job_type ~= df.job_type.BringItemToDepot then return false end + return item_pos(item, flags) or false end - if item.flags.in_building then + if flags.in_building then if dfhack.items.getHolderBuilding(item) ~= depot then return false end for _, contained_item in ipairs(depot.contained_items) do - if contained_item.use_mode == df.building_item_role_type.TEMP then return true end + if contained_item.use_mode == df.building_item_role_type.TEMP then + return item_pos(item, flags) or false + end -- building construction materials if item == contained_item.item then return false end end end - return dfhack.maps.canWalkBetween(xyz2pos(dfhack.items.getPosition(item)), - xyz2pos(depot.centerx, depot.centery, depot.z)) + local pos = item_pos(item, flags) + if not pos then return false end + -- items on the same tile share walkability; memoize per tile since the + -- check is expensive and stockpiles cluster many items onto few tiles + local tile_key = (pos.x*1024 + pos.y)*1024 + pos.z + 64 + local walkable = walkable_cache[tile_key] + if walkable == nil then + walkable = dfhack.maps.canWalkBetween(pos, depot_pos) + walkable_cache[tile_key] = walkable + end + return walkable and pos or false end local function get_entry_icon(data, item_id) @@ -439,7 +474,7 @@ local function is_ethical_item(item, animal_ethics, wood_ethics) (not wood_ethics or not common.has_wood(item)) end -local function is_ethical_product(item, animal_ethics, wood_ethics) +local function is_ethical_product(item, animal_ethics, wood_ethics, contained) if not animal_ethics and not wood_ethics then return true end -- if item is not a container or is an empty container, then the ethics is not mixed @@ -449,7 +484,7 @@ local function is_ethical_product(item, animal_ethics, wood_ethics) if not item.flags.container then return has_ethical, is_mixed end - local contained_items = dfhack.items.getContainedItems(item) + local contained_items = contained or dfhack.items.getContainedItems(item) if #contained_items == 0 then return has_ethical, is_mixed end @@ -480,10 +515,10 @@ local function is_ethical_product(item, animal_ethics, wood_ethics) return has_ethical, is_mixed end -local function make_container_search_key(item, desc) +local function make_container_search_key(item, desc, contained) local words = {} common.add_words(words, desc) - for _, contained_item in ipairs(dfhack.items.getContainedItems(item)) do + for _, contained_item in ipairs(contained or dfhack.items.getContainedItems(item)) do common.add_words(words, dfhack.items.getReadableDescription(contained_item)) end return table.concat(words, ' ') @@ -496,8 +531,19 @@ local function get_cache_index(group_items, inside_containers) return val end -local function contains_non_liquid_powder(container) - for _, item in ipairs(dfhack.items.getContainedItems(container)) do +local EMPTY_CONTAINED = {} + +-- descriptions for these item types depend on fields that the surrogate +-- description key does not cover (e.g. which body part a corpse piece is), so +-- they are always computed directly +local NO_DESC_CACHE_TYPES = { + [df.item_type.CORPSE] = true, + [df.item_type.CORPSEPIECE] = true, + [df.item_type.REMAINS] = true, +} + +local function contains_non_liquid_powder(container, contained) + for _, item in ipairs(contained or dfhack.items.getContainedItems(container)) do if not item:isLiquidPowder() then return true end end return false @@ -514,11 +560,21 @@ local SCAN_TIME_BUDGET_MS = 10 local SCAN_TIME_CHECK = 32 function MoveGoods:request_scan(inside_containers) - -- a single scan builds both the grouped and ungrouped choice lists for - -- its inside_containers setting - if self.choices_cache[get_cache_index(true, inside_containers)] then return end - if self.scan and self.scan.inside_containers == inside_containers then return end - self.scan_queued[inside_containers] = true + if not self.choices_cache[get_cache_index(true, inside_containers)] then + -- a scan builds the grouped choice list for its inside_containers + -- setting; the ungrouped list is built lazily on demand afterwards + if not (self.scan and self.scan.inside_containers == inside_containers + and self.scan.kind == 'scan') then + self.scan_queued[inside_containers] = true + end + return + end + if not self.choices_cache[get_cache_index(false, inside_containers)] + and not (self.scan and self.scan.inside_containers == inside_containers + and self.scan.kind == 'nogroup') then + -- the grouped list exists; queue the ungrouped list to be built + self.nogroup_queued[inside_containers] = true + end end function MoveGoods:cache_choices() @@ -534,15 +590,30 @@ function MoveGoods:cache_choices() return self.choices_cache[cache_idx] end --- scans all items and builds the grouped and ungrouped choice lists for the --- scan's inside_containers setting. runs inside a coroutine and yields after --- each time slice so the UI does not stall while the lists are built. +-- scans all items and builds the grouped choice list for the scan's +-- inside_containers setting; the ungrouped list is built lazily by +-- build_nogroup if it is ever requested. runs inside a coroutine and yields +-- after each time slice so the UI does not stall while the list is built. function MoveGoods:build_choices(scan) local inside_containers = scan.inside_containers local pending = self.pending_item_ids local groups = {} local items = df.global.world.items.other.IN_PLAY local deadline = dfhack.getTickCount() + SCAN_TIME_BUDGET_MS + local depot_pos = xyz2pos(self.depot.centerx, self.depot.centery, self.depot.z) + -- skip per-item ban checks entirely when nothing can be banned or risky + local need_ban_scan = #df.global.world.mandates.all > 0 or next(self.risky_items) ~= nil + -- trade requests require an active caravan + local has_caravans = #df.global.plotinfo.caravans > 0 + -- dfhack.items module calls are expensive (~100us each), so expensive + -- per-item results are memoized: walkability per tile, descriptions and + -- values per surrogate key of cheap item fields + local walkable_cache = {} + local desc_cache = {} + local value_cache = {} + -- only some item classes have a 'name' field; probing it errors on others, + -- so capability is determined once per item type + local name_capable_by_type = {} for i = 0, #items - 1 do if i % SCAN_TIME_CHECK == 0 and dfhack.getTickCount() >= deadline then scan.cursor = i @@ -550,57 +621,110 @@ function MoveGoods:build_choices(scan) deadline = dfhack.getTickCount() + SCAN_TIME_BUDGET_MS end local item = items[i] - if not item or not is_tradeable_item(item, self.depot) then goto continue end - if inside_containers and is_container(item) and contains_non_liquid_powder(item) then - goto continue - elseif not inside_containers and item.flags.in_inventory then + if not item then goto continue end + local flags = item.flags + -- skip contained items early; they are the bulk of items in play on + -- large forts and are not shown in this view + if not inside_containers and flags.in_inventory then goto continue end + local pos = is_tradeable_item(item, self.depot, depot_pos, walkable_cache) + if not pos then goto continue end + local contained = flags.container and dfhack.items.getContainedItems(item) or EMPTY_CONTAINED + if inside_containers and flags.container and is_container(item) and contains_non_liquid_powder(item, contained) then goto continue end local item_id = item.id - local value = common.get_perceived_value(item) + local wear_level = item:getWear() + local item_type = item:getType() + local item_subtype = item:getSubtype() + local quality = item:getQuality() + -- most items share a description and value with identical items, so + -- only compute the (expensive) readable description and value once per + -- distinct surrogate. items whose desc or value can vary independently + -- (artifacts, named, improved or written-on items, corpse pieces, + -- magical items, containers) are always computed. + local name_capable = name_capable_by_type[item_type] + if name_capable == nil then + name_capable = pcall(function() return item.name.has_name end) + name_capable_by_type[item_type] = name_capable + end + local can_desc_cache = not (flags.artifact or item:hasWriting() or item:hasImprovements() + or NO_DESC_CACHE_TYPES[item_type] + or (name_capable and item.name.has_name)) + -- value also varies with container contents and magic powers + local can_value_cache = can_desc_cache and not flags.container and not item:getMagic() + local cache_key + if can_desc_cache then + cache_key = ('%d/%d/%d/%d/%d/%d/%d/%d/%d'):format( + item_type, item_subtype, item:getMaterial(), item:getMaterialIndex(), + quality, wear_level, item:getStackSize(), + flags.foreign and 1 or 0, flags.rotten and 1 or 0) + end + local value + if can_value_cache then + value = value_cache[cache_key] + if not value then + value = common.get_perceived_value(item, nil, contained) + value_cache[cache_key] = value + end + else + value = common.get_perceived_value(item, nil, contained) + end if value <= 0 then goto continue end self.item_values[item_id] = value self.items_by_id[item_id] = item -- explicit user marks win; otherwise fall back to the initial state local is_pending = self.marked[item_id] if is_pending == nil then - is_pending = not not pending[item_id] or item.flags.in_building + is_pending = not not pending[item_id] or flags.in_building end - local dist = get_distance(self.depot, xyz2pos(dfhack.items.getPosition(item))) - local is_forbidden = item.flags.forbid - local is_banned, is_risky = common.scan_banned(item, self.risky_items) - local is_requested = dfhack.items.isRequestedTradeGood(item) - local wear_level = item:getWear() - local desc = dfhack.items.getReadableDescription(item) - local key = ('%s/%d'):format(desc, value) - if groups[key] then - local group = groups[key] - group.data.items[item_id] = {item=item, pending=is_pending, banned=is_banned, requested=is_requested} - group.data.quantity = group.data.quantity + 1 - group.data.dist = math.min(group.data.dist or math.huge, dist) - group.data.selected = group.data.selected + (is_pending and 1 or 0) - group.data.num_at_depot = group.data.num_at_depot + (item.flags.in_building and 1 or 0) - group.data.has_forbidden = group.data.has_forbidden or is_forbidden - group.data.has_banned = group.data.has_banned or is_banned - group.data.has_risky = group.data.has_risky or is_risky - group.data.has_requested = group.data.has_requested or is_requested + local dist = get_distance(self.depot, pos) + local is_forbidden = flags.forbid + local is_banned, is_risky = false, false + if need_ban_scan then + is_banned, is_risky = common.scan_banned(item, self.risky_items, contained) + end + local is_requested = has_caravans and dfhack.items.isRequestedTradeGood(item) + local desc + if can_desc_cache then + desc = desc_cache[cache_key] + if not desc then + desc = dfhack.items.getReadableDescription(item) + desc_cache[cache_key] = desc + end else - local has_ethical, is_ethical_mixed = is_ethical_product(item, self.animal_ethics, self.wood_ethics) - local data = { + desc = dfhack.items.getReadableDescription(item) + end + local subgroups = groups[desc] + local group = subgroups and subgroups[value] + local data + if group then + data = group.data + data.items[item_id] = {item=item, pending=is_pending, banned=is_banned, requested=is_requested} + data.quantity = data.quantity + 1 + data.dist = math.min(data.dist or math.huge, dist) + data.selected = data.selected + (is_pending and 1 or 0) + data.num_at_depot = data.num_at_depot + (flags.in_building and 1 or 0) + data.has_forbidden = data.has_forbidden or is_forbidden + data.has_banned = data.has_banned or is_banned + data.has_risky = data.has_risky or is_risky + data.has_requested = data.has_requested or is_requested + else + local has_ethical, is_ethical_mixed = is_ethical_product(item, self.animal_ethics, self.wood_ethics, contained) + data = { desc=desc, per_item_value=value, item=item, -- a representative item that we can use for filtering later items={[item_id]={item=item, pending=is_pending, banned=is_banned, risky=is_risky, requested=is_requested}}, - item_type=item:getType(), - item_subtype=item:getSubtype(), + item_type=item_type, + item_subtype=item_subtype, quantity=1, - quality=item.flags.artifact and 6 or item:getQuality(), + quality=flags.artifact and 6 or quality, dist=dist, wear=wear_level, selected=is_pending and 1 or 0, - num_at_depot=item.flags.in_building and 1 or 0, + num_at_depot=flags.in_building and 1 or 0, has_forbidden=is_forbidden, - has_foreign=item.flags.foreign, + has_foreign=flags.foreign, has_banned=is_banned, has_risky=is_risky, has_requested=is_requested, @@ -608,8 +732,8 @@ function MoveGoods:build_choices(scan) ethical_mixed=is_ethical_mixed, } local search_key - if not inside_containers and is_container(item) then - search_key = make_container_search_key(item, desc) + if not inside_containers and flags.container and is_container(item) then + search_key = make_container_search_key(item, desc, contained) else search_key = common.make_search_key(desc) end @@ -618,43 +742,36 @@ function MoveGoods:build_choices(scan) icon=curry(get_entry_icon, data), data=data, } - groups[key] = entry + if not subgroups then + subgroups = {} + groups[desc] = subgroups + end + subgroups[value] = entry + end + -- index the shared data table containing this item so toggles can be + -- propagated without rescanning the choice lists + local datas = self.datas_by_item[item_id] + if not datas then + datas = {} + self.datas_by_item[item_id] = datas end + datas[data] = true ::continue:: end scan.cursor = #items - local group_choices, nogroup_choices = {}, {} + local group_choices = {} local cache_threshold = common.get_threshold(common.get_broker_skill()) local processed = 0 - for _, group in pairs(groups) do - local data = group.data - for item_id, item_data in pairs(data.items) do - -- index the shared data tables that contain each item so toggles - -- can be propagated without rescanning the choice lists - local datas = self.datas_by_item[item_id] - if not datas then - datas = {} - self.datas_by_item[item_id] = datas - end - datas[data] = true - local nogroup_choice = copyall(group) - nogroup_choice.icon = curry(get_entry_icon, data, item_id) - nogroup_choice.text = make_choice_text(item_data.item.flags.in_building, - data.dist, data.per_item_value, 1, data.desc, cache_threshold) - nogroup_choice.item_id = item_id - table.insert(nogroup_choices, nogroup_choice) - processed = processed + 1 - if processed % SCAN_TIME_CHECK == 0 and dfhack.getTickCount() >= deadline then - coroutine.yield() - deadline = dfhack.getTickCount() + SCAN_TIME_BUDGET_MS - end + for _, subgroups in pairs(groups) do + for _, group in pairs(subgroups) do + local data = group.data + data.total_value = data.per_item_value * data.quantity + group.text = make_choice_text(data.num_at_depot == data.quantity, data.dist, + data.total_value, data.quantity, data.desc, cache_threshold) + table.insert(group_choices, group) end - data.total_value = data.per_item_value * data.quantity - group.text = make_choice_text(data.num_at_depot == data.quantity, data.dist, - data.total_value, data.quantity, data.desc, cache_threshold) - table.insert(group_choices, group) end self.value_pending = 0 @@ -674,39 +791,89 @@ function MoveGoods:build_choices(scan) end self.choices_cache[get_cache_index(true, inside_containers)] = group_choices + -- any ungrouped list built from an older scan holds stale data tables + self.choices_cache[get_cache_index(false, inside_containers)] = nil +end + +-- expands the grouped choice list for the scan's inside_containers setting +-- into the ungrouped per-item list. run lazily the first time the ungrouped +-- view is requested since it costs one row per tradeable item. +function MoveGoods:build_nogroup(scan) + local inside_containers = scan.inside_containers + local group_choices = self.choices_cache[get_cache_index(true, inside_containers)] + if not group_choices then return end + local nogroup_choices = {} + local cache_threshold = common.get_threshold(common.get_broker_skill()) + local deadline = dfhack.getTickCount() + SCAN_TIME_BUDGET_MS + local processed = 0 + for _, group in ipairs(group_choices) do + local data = group.data + for item_id, item_data in pairs(data.items) do + local nogroup_choice = copyall(group) + nogroup_choice.icon = curry(get_entry_icon, data, item_id) + nogroup_choice.text = make_choice_text(item_data.item.flags.in_building, + data.dist, data.per_item_value, 1, data.desc, cache_threshold) + nogroup_choice.item_id = item_id + table.insert(nogroup_choices, nogroup_choice) + processed = processed + 1 + scan.cursor = processed + if processed % SCAN_TIME_CHECK == 0 and dfhack.getTickCount() >= deadline then + coroutine.yield() + deadline = dfhack.getTickCount() + SCAN_TIME_BUDGET_MS + end + end + end self.choices_cache[get_cache_index(false, inside_containers)] = nogroup_choices end --- starts the next queued scan or resumes the in-progress scan. called once --- per rendered frame via the on_render hook so the UI stays responsive while --- the choice lists are being built. +-- starts the next queued scan or nogroup build, or resumes the in-progress +-- one. called once per rendered frame via the on_render hook so the UI stays +-- responsive while the choice lists are being built. function MoveGoods:pump_scan() if not self.scan then local inside_containers = next(self.scan_queued) - if inside_containers == nil then return end - self.scan_queued[inside_containers] = nil + local kind = 'scan' + if inside_containers == nil then + inside_containers = next(self.nogroup_queued) + if inside_containers == nil then return end + self.nogroup_queued[inside_containers] = nil + kind = 'nogroup' + else + self.scan_queued[inside_containers] = nil + end local scan = { inside_containers=inside_containers, + kind=kind, cursor=0, - total=#df.global.world.items.other.IN_PLAY, } - scan.coro = coroutine.create(function() self:build_choices(scan) end) + if kind == 'nogroup' then + local total = 0 + for _, group in ipairs(self.choices_cache[get_cache_index(true, inside_containers)] or {}) do + total = total + group.data.quantity + end + scan.total = total + scan.coro = coroutine.create(function() self:build_nogroup(scan) end) + else + scan.total = #df.global.world.items.other.IN_PLAY + scan.coro = coroutine.create(function() self:build_choices(scan) end) + end self.scan = scan end -- the choice list is still being built; don't show 'No matches' self.subviews.list.not_found.visible = false local ok, err = coroutine.resume(self.scan.coro) - if not ok then error(err, 0) end if coroutine.status(self.scan.coro) == 'dead' then self.scan = nil self:refresh_list() end + if not ok then error(err, 0) end end -- runs all queued scans to completion, ensuring items_by_id is populated for -- every item that could have been marked function MoveGoods:finish_scans() - while self.scan ~= nil or next(self.scan_queued) ~= nil do + while self.scan ~= nil or next(self.scan_queued) ~= nil + or next(self.nogroup_queued) ~= nil do self:pump_scan() end end From 5f56eacfade32fa67fb28bb7d075a22ceb87d89f Mon Sep 17 00:00:00 2001 From: Kelly Kinkade Date: Sun, 29 Nov 2026 13:30:00 -0600 Subject: [PATCH 3/4] fix handling of grouped items mark preservation was not working correctly in conjunction with item grouping, caused a CI test failure --- internal/caravan/movegoods.lua | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/internal/caravan/movegoods.lua b/internal/caravan/movegoods.lua index e5abc008b..ee8a0193f 100644 --- a/internal/caravan/movegoods.lua +++ b/internal/caravan/movegoods.lua @@ -559,7 +559,7 @@ end local SCAN_TIME_BUDGET_MS = 10 local SCAN_TIME_CHECK = 32 -function MoveGoods:request_scan(inside_containers) +function MoveGoods:request_scan(inside_containers, group_items) if not self.choices_cache[get_cache_index(true, inside_containers)] then -- a scan builds the grouped choice list for its inside_containers -- setting; the ungrouped list is built lazily on demand afterwards @@ -567,12 +567,14 @@ function MoveGoods:request_scan(inside_containers) and self.scan.kind == 'scan') then self.scan_queued[inside_containers] = true end - return end - if not self.choices_cache[get_cache_index(false, inside_containers)] + if not group_items + and not self.choices_cache[get_cache_index(false, inside_containers)] and not (self.scan and self.scan.inside_containers == inside_containers and self.scan.kind == 'nogroup') then - -- the grouped list exists; queue the ungrouped list to be built + -- the ungrouped list was requested; queue it to be built. scans always + -- drain before nogroup builds, so the source grouped list will exist + -- by the time it runs even if its scan was just queued above self.nogroup_queued[inside_containers] = true end end @@ -584,7 +586,7 @@ function MoveGoods:cache_choices() if not self.choices_cache[cache_idx] then -- request the lists to be built asynchronously; the visible choices -- will be populated when the scan completes - self:request_scan(inside_containers) + self:request_scan(inside_containers, group_items) return nil end return self.choices_cache[cache_idx] From 5f1d0ddc47f79593e6d694e2764a94349f5d7158 Mon Sep 17 00:00:00 2001 From: Kelly Kinkade Date: Sun, 29 Nov 2026 15:31:39 -0600 Subject: [PATCH 4/4] fix test test got desynced from implementation --- test/caravan/movegoods.lua | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/test/caravan/movegoods.lua b/test/caravan/movegoods.lua index a5b8c3613..2d9d720cb 100644 --- a/test/caravan/movegoods.lua +++ b/test/caravan/movegoods.lua @@ -46,8 +46,9 @@ local function run_check() local w = movegoods.MoveGoods{pending_item_ids=ids, depot=depot} for _, inside in ipairs{false, true} do for _, group in ipairs{false, true} do - w.subviews.inside_containers:setOption(inside and 'Yes' or 'No') - w.subviews.group_items:setOption(group and 'Yes' or 'No') + -- setOption matches option values, not labels + w.subviews.inside_containers:setOption(inside) + w.subviews.group_items:setOption(group) w:cache_choices() w:finish_scans() expect.eq(expected_pending(w), w.value_pending) @@ -83,8 +84,9 @@ function test.marks_persist_across_filter_views() for idx in pairs(w.choices_cache) do w.choices_cache[idx] = nil end for _, inside in ipairs{false, true} do for _, group in ipairs{false, true} do - w.subviews.inside_containers:setOption(inside and 'Yes' or 'No') - w.subviews.group_items:setOption(group and 'Yes' or 'No') + -- setOption matches option values, not labels + w.subviews.inside_containers:setOption(inside) + w.subviews.group_items:setOption(group) w:cache_choices() w:finish_scans() local c = find_choice(w, marked_id)