-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGuiDialogQuartermaster.cs
More file actions
644 lines (554 loc) · 33.6 KB
/
Copy pathGuiDialogQuartermaster.cs
File metadata and controls
644 lines (554 loc) · 33.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
using System;
using System.Collections.Generic;
using System.Linq;
using Vintagestory.API.Client;
using Vintagestory.API.Common;
using Vintagestory.API.Config;
using Vintagestory.API.Datastructures;
using Vintagestory.API.MathTools;
namespace Quartermaster
{
// --- DATA DEFINITIONS ---
[ProtoBuf.ProtoContract(ImplicitFields = ProtoBuf.ImplicitFields.AllPublic)]
public class PacketQuartermasterRequest { }
[ProtoBuf.ProtoContract(ImplicitFields = ProtoBuf.ImplicitFields.AllPublic)]
public class PacketQuartermasterResponse
{
public List<QuartermasterItemDTO> Items = new List<QuartermasterItemDTO>();
public bool LocateOnly;
// Slot stats across the deposit-eligible containers (chests/trunks) in range,
// for the "Empty slots" label.
public int FreeSlots;
public int TotalSlots;
}
// Lightweight periodic refresh of the "Empty slots" label while the ledger is open,
// so placing/filling chests in range updates the count without a full ledger rescan.
[ProtoBuf.ProtoContract(ImplicitFields = ProtoBuf.ImplicitFields.AllPublic)]
public class PacketSlotStatsRequest { }
[ProtoBuf.ProtoContract(ImplicitFields = ProtoBuf.ImplicitFields.AllPublic)]
public class PacketSlotStats
{
public int FreeSlots;
public int TotalSlots;
}
[ProtoBuf.ProtoContract(ImplicitFields = ProtoBuf.ImplicitFields.AllPublic)]
public class QuartermasterItemDTO
{
public string Code;
public int Count;
public string Type;
public string VariantType;
public string Variant;
public string Material;
// Full attribute tree of a representative stack, so attribute-driven blocks
// (clutter, bookshelves, etc.) render with the exact appearance they had in storage.
public byte[] AttributesData;
public List<SimplePos> Locations = new List<SimplePos>();
}
[ProtoBuf.ProtoContract(ImplicitFields = ProtoBuf.ImplicitFields.AllPublic)]
public class SimplePos { public int X, Y, Z; }
[ProtoBuf.ProtoContract(ImplicitFields = ProtoBuf.ImplicitFields.AllPublic)]
public class PacketWithdraw
{
public string Code;
public string Type; // "Block" or "Item"
public string VariantType; // itemstack "type" attribute (decorative chests, clutter)
public string Variant; // itemstack "variant" attribute (clutter bookshelves)
public string Material; // itemstack "material" attribute
public int Mode; // 0 = one stack, 1 = single item, 2 = all
}
[ProtoBuf.ProtoContract(ImplicitFields = ProtoBuf.ImplicitFields.AllPublic)]
public class PacketDeposit
{
public int Mode; // 0 = whole cursor stack, 1 = one from cursor, 2 = deposit all from backpack, 3 = one specific player slot (shift-click)
public string InventoryClass; // Mode 3: "hotbar" or "backpack"
public int SlotId; // Mode 3: slot index within that inventory
}
// Client asks for the tag-excluded container positions near the player (sent while
// holding a Quartermaster's Tag, to drive the "Excluded" label overlay).
[ProtoBuf.ProtoContract(ImplicitFields = ProtoBuf.ImplicitFields.AllPublic)]
public class PacketExcludedRequest { }
[ProtoBuf.ProtoContract(ImplicitFields = ProtoBuf.ImplicitFields.AllPublic)]
public class PacketExcludedList
{
public List<SimplePos> Positions = new List<SimplePos>();
}
[Flags]
public enum ItemCategory
{
None = 0,
Food = 1,
Tools = 2,
Fuel = 4,
Wood = 8,
Wearables = 16,
Metals = 32,
Building = 64,
Plants = 128,
Decor = 256,
Powders = 512
}
public class QuartermasterEntry
{
public ItemStack Stack;
public List<BlockPos> Locations;
public ItemCategory Category;
}
public class GuiDialogQuartermaster : GuiDialog
{
public override string ToggleKeyCombinationCode => null;
private QuartermasterModSystem modSystem;
private List<QuartermasterEntry> allEntries = new List<QuartermasterEntry>();
private List<QuartermasterEntry> filteredEntries = new List<QuartermasterEntry>();
private InventoryGeneric virtualInventory;
// A always-empty 1-slot inventory rendered as the "drop to deposit" cell.
private InventoryGeneric depositCellInventory;
private string currentSearchText = "";
private ItemCategory activeCategories = ItemCategory.None;
private int currentPage = 0;
// LAYOUT: 10 Columns, 9 Rows (90 Items)
private const int COLS = 10;
private int itemsPerPage = 90;
private bool isWaitingForServer = false;
private long openTime = 0;
// Server-controlled read-only mode (LocateOnly config). When true the deposit/withdraw
// controls are hidden and grid clicks locate instead of withdraw. Writes are also
// blocked server-side regardless of this flag.
private bool locateOnly = false;
// Read by the mod system's shift-click deposit hook, so it can leave vanilla
// click behavior alone on a read-only station.
public bool IsLocateOnly => locateOnly;
// The entries currently shown on the visible page, indexed to match the grid slots.
private List<QuartermasterEntry> currentVisibleEntries = new List<QuartermasterEntry>();
// Empty/total slot counts across the deposit-eligible containers in range.
// -1 = not received yet this session (label stays blank until the first reply).
private int freeSlots = -1;
private int totalSlots;
public GuiDialogQuartermaster(ICoreClientAPI capi, QuartermasterModSystem system) : base(capi)
{
this.modSystem = system;
}
public void UpdateDataFromServer(List<QuartermasterItemDTO> data, bool locateOnly, int freeSlots, int totalSlots)
{
this.locateOnly = locateOnly;
this.freeSlots = freeSlots;
this.totalSlots = totalSlots;
allEntries.Clear();
foreach (var dto in data)
{
try
{
AssetLocation code = new AssetLocation(dto.Code);
CollectibleObject collectible = (dto.Type == "Block") ? (CollectibleObject)capi.World.GetBlock(code) : (CollectibleObject)capi.World.GetItem(code);
if (collectible != null)
{
ItemStack stack = new ItemStack(collectible, dto.Count);
// Attribute-variant blocks (decorative chests, clutter, bookshelves) share
// one code and encode their appearance in itemstack attributes. Restore the
// full attribute tree of a representative stack so the correct name, icon,
// and mesh render (a bookshelf's "variant", a chest's "type", etc.).
if (dto.AttributesData != null && dto.AttributesData.Length > 0)
stack.Attributes = TreeAttribute.CreateFromBytes(dto.AttributesData);
else
{
if (!string.IsNullOrEmpty(dto.VariantType)) stack.Attributes.SetString("type", dto.VariantType);
if (!string.IsNullOrEmpty(dto.Material)) stack.Attributes.SetString("material", dto.Material);
}
List<BlockPos> locs = dto.Locations.Select(p => new BlockPos(p.X, p.Y, p.Z)).ToList();
allEntries.Add(new QuartermasterEntry() { Stack = stack, Locations = locs, Category = ClassifyCollectible(collectible) });
}
}
catch { }
}
allEntries.Sort((a, b) => string.Compare(a.Stack.GetName(), b.Stack.GetName(), StringComparison.OrdinalIgnoreCase));
isWaitingForServer = false;
FilterItems(currentSearchText);
if (IsOpened()) ComposeDialog();
}
// Food fallback for meal-only ingredients. These have no direct NutritionProps
// (they only gain nutrition once cooked into a meal, via the "nutritionPropsWhenInMeal"
// attribute), so when that attribute check doesn't catch them they'd vanish from the
// Food tab — e.g. raw soybeans/peanuts ("beans"), raw eggs, dough, butter, raw cassava.
// These are matched as code PREFIXES (e.g. "legume-soybean"), not substrings, so they
// don't catch lookalikes like "seeds-soybean", "butterfly-*" or "leggings".
private static readonly string[] FoodCodeParts =
{
"legume", "egg", "dough", "butter", "rawcassava"
};
// Fuel = what players actually stockpile as fuel. NOT "anything flammable":
// in VS planks/sticks/candles burn at 700° (same as firewood) and ferns/grass
// at 600°, so CombustibleProps/burn-temperature can't separate fuel from kindling.
// lignite/anthracite codes don't contain "coal", so they're listed explicitly.
private static readonly string[] FuelCodeParts = { "firewood", "charcoal", "coke", "coal", "lignite", "anthracite", "peat" };
// Wood-material blocks already cover crafted wood (planks, logs, furniture, axles,
// etc.); these catch the wood *items* that aren't blocks (no BlockMaterial to check).
private static readonly string[] WoodItemCodeParts = { "firewood", "plank", "board", "log", "stick" };
// Weapons / ammunition the Tool enum doesn't cover: arrows & sling bullets (class
// ItemArrow), clubs (no tool), plus likely modded weapons. "bow" is omitted on
// purpose (it collides with "bowl") — bows already classify via Tool != null.
private static readonly string[] WeaponCodeParts =
{
"arrow", "bullets", "club", "spear", "javelin", "sword",
"dagger", "mace", "halberd", "crossbow", "bolt"
};
// Plants: growing/harvestable flora and their propagules. Living plant blocks
// (flowers, grass, ferns, mushrooms, reeds, vines) already match via the Plant/Leaves
// block material; these catch the item forms and saplings, which aren't Plant-material
// blocks. "seeds" covers "seeds-*"; mushroom items also gain the Food flag separately.
private static readonly string[] PlantCodeParts =
{
"seeds", "sapling", "flower", "mushroom", "cutting",
"bamboo", "papyrus", "cattail", "reedmace"
};
// Decor: purely decorative, non-functional pieces — paintings/pictures, tapestries,
// and the decorative "clutter" blocks (which share a code and vary by "type").
private static readonly string[] DecorCodeParts =
{
"painting", "picture", "tapestry", "clutter"
};
// Powders: milled/crushed/pulverized substances (flour, crushed ore, bonemeal-style
// powders). Flour is anchored so it doesn't catch unrelated codes.
private static readonly string[] PowderCodeParts =
{
"powder", "crushed", "pulverized"
};
// Classifies a collectible into one or more categories. Food/Tools/Wearables come
// from real collectible properties; Fuel/Wood have no single defining property, so
// they match against curated code lists (Wood also via the block's Wood material).
private static ItemCategory ClassifyCollectible(CollectibleObject collectible)
{
ItemCategory cat = ItemCategory.None;
if (collectible == null) return cat;
// Food: directly edible (NutritionProps), plus ingredients that only gain
// nutrition once cooked/in a meal (raw eggs, beans, etc. carry
// "nutritionPropsWhenInMeal" instead of a direct NutritionProps).
string path = collectible.Code?.Path ?? "";
if (collectible.NutritionProps != null ||
collectible.Attributes?["nutritionPropsWhenInMeal"].Exists == true) cat |= ItemCategory.Food;
else foreach (var part in FoodCodeParts) if (path == part || path.StartsWith(part + "-")) { cat |= ItemCategory.Food; break; }
// Tools: anything with a tool type (covers bow/spear/sling), plus weapons/ammo
// the Tool enum misses (arrows, bullets, clubs, modded swords...).
if (collectible.Tool != null) cat |= ItemCategory.Tools;
else foreach (var part in WeaponCodeParts) if (path.Contains(part)) { cat |= ItemCategory.Tools; break; }
foreach (var part in FuelCodeParts) if (path.Contains(part)) { cat |= ItemCategory.Fuel; break; }
// Wood: any Wood-material block (raw + crafted: planks, furniture, axles...),
// plus the wood items that aren't blocks.
bool isWoodBlock = collectible is Block block && block.BlockMaterial == EnumBlockMaterial.Wood;
if (isWoodBlock) cat |= ItemCategory.Wood;
else foreach (var part in WoodItemCodeParts) if (path.Contains(part)) { cat |= ItemCategory.Wood; break; }
// Wearables: slot-worn items. Clothing/hats/armor/jewelry carry a "clothescategory"
// attribute; bags/backpacks carry a "backpack" attribute (mounts like boat seats
// and saddles have neither, so they stay out). Plus temporal gears.
if (collectible.Attributes?["clothescategory"].Exists == true) cat |= ItemCategory.Wearables;
if (collectible.Attributes?["backpack"].Exists == true) cat |= ItemCategory.Wearables;
if (path.Contains("gear") && path.Contains("temporal")) cat |= ItemCategory.Wearables;
// Metals & Ore: ingots/nuggets/ore. "ore" is anchored (prefix/material) since the
// bare substring hits forest/core/lore/etc.
bool isOreBlock = collectible is Block oreBlock && oreBlock.BlockMaterial == EnumBlockMaterial.Ore;
if (isOreBlock || path.StartsWith("ore-") || path == "ore" ||
path.StartsWith("nugget") || path.StartsWith("ingot") ||
path.Contains("metalbit") || path.Contains("metalplate") ||
path.Contains("looseore") || path.Contains("crystalizedore"))
cat |= ItemCategory.Metals;
// Building: stone & ceramic blocks (rock, cobble, bricks, tiles, fired clay).
if (collectible is Block buildBlock &&
(buildBlock.BlockMaterial == EnumBlockMaterial.Stone || buildBlock.BlockMaterial == EnumBlockMaterial.Ceramic))
cat |= ItemCategory.Building;
// Plants: living Plant/Leaves blocks, plus seed/sapling/cutting items. Flower pots
// are excluded — they're empty decorative containers ("flowerpot" matches "flower").
bool isPlantBlock = collectible is Block plantBlock &&
(plantBlock.BlockMaterial == EnumBlockMaterial.Plant || plantBlock.BlockMaterial == EnumBlockMaterial.Leaves);
if (isPlantBlock) cat |= ItemCategory.Plants;
else if (!path.Contains("flowerpot"))
foreach (var part in PlantCodeParts) if (path.Contains(part)) { cat |= ItemCategory.Plants; break; }
// Decor: paintings/pictures, tapestries, decorative clutter.
foreach (var part in DecorCodeParts) if (path.Contains(part)) { cat |= ItemCategory.Decor; break; }
// Powders: crushed/pulverized substances, plus flour (anchored).
if (path == "flour" || path.StartsWith("flour-")) cat |= ItemCategory.Powders;
else foreach (var part in PowderCodeParts) if (path.Contains(part)) { cat |= ItemCategory.Powders; break; }
return cat;
}
private void FilterItems(string searchText)
{
currentSearchText = searchText.ToLower();
ApplyFilters();
}
// Search text (substring) AND category selection (OR across active categories).
// No active categories means "All".
private void ApplyFilters()
{
IEnumerable<QuartermasterEntry> query = allEntries;
if (!string.IsNullOrEmpty(currentSearchText))
query = query.Where(e => e.Stack.GetName()?.ToLower().Contains(currentSearchText) == true);
if (activeCategories != ItemCategory.None)
query = query.Where(e => (e.Category & activeCategories) != 0);
filteredEntries = query.ToList();
currentPage = 0;
UpdateView();
}
private void OnCategoryToggle(ItemCategory category, bool on)
{
if (on) activeCategories |= category;
else activeCategories &= ~category;
ApplyFilters();
ComposeDialog();
}
private void UpdateView()
{
int skip = currentPage * itemsPerPage;
currentVisibleEntries = filteredEntries.Skip(skip).Take(itemsPerPage).ToList();
virtualInventory = new InventoryGeneric(Math.Max(1, currentVisibleEntries.Count), "quartermaster-grid", capi, null);
for (int i = 0; i < currentVisibleEntries.Count; i++)
{
virtualInventory[i].Itemstack = currentVisibleEntries[i].Stack;
}
}
public void ComposeDialog()
{
if (virtualInventory == null) virtualInventory = new InventoryGeneric(1, "quartermaster-init", capi, null);
double windowWidth = 850;
double gridWidth = 480;
double leftMargin = 170;
double windowHeight = 620;
ElementBounds dialogBounds = ElementStdBounds.AutosizedMainDialog.WithAlignment(EnumDialogArea.CenterMiddle);
ElementBounds bgBounds = ElementBounds.Fixed(0, 0, windowWidth, windowHeight);
ElementBounds searchBounds = ElementBounds.Fixed(leftMargin, 45, gridWidth, 30);
// Category filter toggles, stacked vertically in the empty right-hand strip.
const double catBtnW = 130, catBtnH = 30, catBtnGap = 8;
double catColX = leftMargin + gridWidth + 45;
double catColY = 85, catStep = catBtnH + catBtnGap;
// Centered over the button column and vertically aligned with the search bar's middle.
ElementBounds catLabelBounds = ElementBounds.Fixed(catColX, 49, catBtnW, 22);
ElementBounds foodBtnBounds = ElementBounds.Fixed(catColX, catColY + 0 * catStep, catBtnW, catBtnH);
ElementBounds toolsBtnBounds = ElementBounds.Fixed(catColX, catColY + 1 * catStep, catBtnW, catBtnH);
ElementBounds fuelBtnBounds = ElementBounds.Fixed(catColX, catColY + 2 * catStep, catBtnW, catBtnH);
ElementBounds woodBtnBounds = ElementBounds.Fixed(catColX, catColY + 3 * catStep, catBtnW, catBtnH);
ElementBounds wearablesBtnBounds = ElementBounds.Fixed(catColX, catColY + 4 * catStep, catBtnW, catBtnH);
ElementBounds metalsBtnBounds = ElementBounds.Fixed(catColX, catColY + 5 * catStep, catBtnW, catBtnH);
ElementBounds buildingBtnBounds = ElementBounds.Fixed(catColX, catColY + 6 * catStep, catBtnW, catBtnH);
ElementBounds plantsBtnBounds = ElementBounds.Fixed(catColX, catColY + 7 * catStep, catBtnW, catBtnH);
ElementBounds decorBtnBounds = ElementBounds.Fixed(catColX, catColY + 8 * catStep, catBtnW, catBtnH);
ElementBounds powdersBtnBounds = ElementBounds.Fixed(catColX, catColY + 9 * catStep, catBtnW, catBtnH);
// HEIGHT: 435px (fits 9 rows).
ElementBounds gridBounds = ElementBounds.Fixed(leftMargin, 85, gridWidth + 5, 435);
ElementBounds prevButtonBounds = ElementBounds.Fixed(leftMargin, 575, 80, 30);
ElementBounds nextButtonBounds = ElementBounds.Fixed(leftMargin + gridWidth - 80, 575, 80, 30);
ElementBounds statusLabelBounds = ElementBounds.Fixed(windowWidth / 2 - 150, 580, 300, 30);
// Controls / help live in the empty left strip (content starts at leftMargin = 170)
ElementBounds depositTitleBounds = ElementBounds.Fixed(10, 42, 150, 22);
ElementBounds depositCellBounds = ElementBounds.Fixed(57, 68, 48, 48);
ElementBounds depositHintBounds = ElementBounds.Fixed(5, 120, 160, 34);
ElementBounds depositAllBounds = ElementBounds.Fixed(15, 160, 140, 28);
ElementBounds helpBounds = ElementBounds.Fixed(10, 205, 155, 350);
// Bottom of the left strip, tall enough for the text to wrap to two lines
// without the second line running off the dialog's bottom edge.
ElementBounds slotStatsBounds = ElementBounds.Fixed(5, 556, 160, 44);
if (depositCellInventory == null)
depositCellInventory = new InventoryGeneric(1, "quartermaster-depositcell", capi, null);
int totalPages = (int)Math.Ceiling((double)filteredEntries.Count / itemsPerPage);
if (totalPages < 1) totalPages = 1;
string statusText = isWaitingForServer ? "Scanning Storage..." : $"Page {currentPage + 1} / {totalPages} ({filteredEntries.Count} Items)";
string helpText = locateOnly
? "Read-only station.\n\n" +
"Locate:\n" +
"• Middle-click an item\n" +
"• (or left-click an item)"
: "Withdraw:\n" +
"• Left-click: one stack\n" +
"• Right-click: one item\n" +
"• Shift+click: all\n\n" +
"Deposit:\n" +
"• Shift+click an item in\n" +
" your hotbar or bags\n\n" +
"Locate:\n" +
"• Middle-click an item";
var centered = CairoFont.WhiteSmallText().WithOrientation(EnumTextOrientation.Center);
var compo = capi.Gui.CreateCompo("quartermasterdialog", dialogBounds)
.AddShadedDialogBG(bgBounds)
.AddDialogTitleBar(locateOnly ? "Quartermaster's Ledger (read-only)" : "Quartermaster's Ledger", OnTitleBarClose)
.AddTextInput(searchBounds, OnSearchChanged, CairoFont.WhiteSmallText(), "searchBar")
.AddStaticText("Categories", centered, catLabelBounds)
.AddToggleButton("Food", CairoFont.WhiteSmallText(), on => OnCategoryToggle(ItemCategory.Food, on), foodBtnBounds, "catFood")
.AddToggleButton("Tools", CairoFont.WhiteSmallText(), on => OnCategoryToggle(ItemCategory.Tools, on), toolsBtnBounds, "catTools")
.AddToggleButton("Fuel", CairoFont.WhiteSmallText(), on => OnCategoryToggle(ItemCategory.Fuel, on), fuelBtnBounds, "catFuel")
.AddToggleButton("Wood", CairoFont.WhiteSmallText(), on => OnCategoryToggle(ItemCategory.Wood, on), woodBtnBounds, "catWood")
.AddToggleButton("Wearables", CairoFont.WhiteSmallText(), on => OnCategoryToggle(ItemCategory.Wearables, on), wearablesBtnBounds, "catWearables")
.AddToggleButton("Ores & Metals", CairoFont.WhiteSmallText(), on => OnCategoryToggle(ItemCategory.Metals, on), metalsBtnBounds, "catMetals")
.AddToggleButton("Building", CairoFont.WhiteSmallText(), on => OnCategoryToggle(ItemCategory.Building, on), buildingBtnBounds, "catBuilding")
.AddToggleButton("Plants", CairoFont.WhiteSmallText(), on => OnCategoryToggle(ItemCategory.Plants, on), plantsBtnBounds, "catPlants")
.AddToggleButton("Decor", CairoFont.WhiteSmallText(), on => OnCategoryToggle(ItemCategory.Decor, on), decorBtnBounds, "catDecor")
.AddToggleButton("Powders", CairoFont.WhiteSmallText(), on => OnCategoryToggle(ItemCategory.Powders, on), powdersBtnBounds, "catPowders")
.AddItemSlotGrid(virtualInventory, OnSlotClick, COLS, gridBounds, "itemgrid")
.AddSmallButton("Prev", OnPrevPage, prevButtonBounds)
.AddSmallButton("Next", OnNextPage, nextButtonBounds)
.AddDynamicText(statusText, CairoFont.WhiteSmallText().WithOrientation(EnumTextOrientation.Center), statusLabelBounds, "statusLabel")
.AddDynamicText(SlotStatsText(), centered, slotStatsBounds, "slotStatsLabel");
// Deposit controls only when writes are allowed (LocateOnly hides them).
if (!locateOnly)
{
compo
.AddStaticText("Deposit", centered, depositTitleBounds)
.AddItemSlotGrid(depositCellInventory, OnSlotClick, 1, depositCellBounds, "depositcell")
.AddStaticText("Drop a held item here\nto store it", CairoFont.WhiteDetailText().WithOrientation(EnumTextOrientation.Center), depositHintBounds)
.AddSmallButton("Deposit All", OnDepositAll, depositAllBounds, EnumButtonStyle.Normal, "depositAllButton");
}
compo.AddStaticText(helpText, CairoFont.WhiteDetailText(), helpBounds, "helpText");
// Compose(false): never auto-focus the first element (the search bar). The
// dialog recomposes on server replies, paging and category toggles, and the
// default would silently hand the search bar focus each time — where it eats
// WASD and the Shift of a shift-click deposit. Typing flow is kept by
// OnSearchChanged, which refocuses the bar explicitly after its recompose.
SingleComposer = compo.Compose(false);
// Disable the grids' built-in slot interaction; we handle clicks ourselves in
// OnMouseDown so nothing is moved client-side on these virtual inventories.
var slotGrid = SingleComposer.GetSlotGrid("itemgrid");
if (slotGrid != null) slotGrid.CanClickSlot = (slotId) => false;
var depositGrid = SingleComposer.GetSlotGrid("depositcell");
if (depositGrid != null) depositGrid.CanClickSlot = (slotId) => false;
if (!string.IsNullOrEmpty(currentSearchText))
SingleComposer.GetTextInput("searchBar").SetValue(currentSearchText);
// Recompose rebuilds the toggles in the off state; restore from the active set.
SingleComposer.GetToggleButton("catFood").SetValue(activeCategories.HasFlag(ItemCategory.Food));
SingleComposer.GetToggleButton("catTools").SetValue(activeCategories.HasFlag(ItemCategory.Tools));
SingleComposer.GetToggleButton("catFuel").SetValue(activeCategories.HasFlag(ItemCategory.Fuel));
SingleComposer.GetToggleButton("catWood").SetValue(activeCategories.HasFlag(ItemCategory.Wood));
SingleComposer.GetToggleButton("catWearables").SetValue(activeCategories.HasFlag(ItemCategory.Wearables));
SingleComposer.GetToggleButton("catMetals").SetValue(activeCategories.HasFlag(ItemCategory.Metals));
SingleComposer.GetToggleButton("catBuilding").SetValue(activeCategories.HasFlag(ItemCategory.Building));
SingleComposer.GetToggleButton("catPlants").SetValue(activeCategories.HasFlag(ItemCategory.Plants));
SingleComposer.GetToggleButton("catDecor").SetValue(activeCategories.HasFlag(ItemCategory.Decor));
SingleComposer.GetToggleButton("catPowders").SetValue(activeCategories.HasFlag(ItemCategory.Powders));
}
private string SlotStatsText()
{
if (freeSlots < 0) return "";
return $"Empty slots: {freeSlots:n0} / {totalSlots:n0}";
}
// Called on the periodic slot-stats reply while the dialog is open. Updates the
// label text in place — deliberately no ComposeDialog, which would steal focus
// from the search bar mid-typing every refresh.
public void UpdateSlotStats(int free, int total)
{
freeSlots = free;
totalSlots = total;
if (IsOpened()) SingleComposer?.GetDynamicText("slotStatsLabel")?.SetNewText(SlotStatsText());
}
private void OnSearchChanged(string text)
{
if (capi.World.ElapsedMilliseconds - openTime < 500 && !string.IsNullOrEmpty(text)) return;
if (text == currentSearchText) return;
FilterItems(text);
ComposeDialog();
SingleComposer.FocusElement(SingleComposer.GetTextInput("searchBar").TabIndex);
}
private bool OnPrevPage()
{
if (currentPage > 0) { currentPage--; UpdateView(); ComposeDialog(); }
return true;
}
private bool OnNextPage()
{
int totalPages = (int)Math.Ceiling((double)filteredEntries.Count / itemsPerPage);
if (currentPage < totalPages - 1) { currentPage++; UpdateView(); ComposeDialog(); }
return true;
}
// The grid's own click handling is disabled (CanClickSlot=false); this is a no-op
// required by AddItemSlotGrid's signature. All clicks go through OnMouseDown.
private void OnSlotClick(object packet) { }
private bool OnDepositAll()
{
QuartermasterModSystem.clientChannel?.SendPacket(new PacketDeposit { Mode = 2 });
return true;
}
public override void OnMouseDown(MouseEvent args)
{
var mouse = capi.World.Player.InventoryManager.MouseItemSlot;
// Deposit cell: drop a held item here to store it.
var depositCell = SingleComposer?.GetSlotGrid("depositcell");
if (!args.Handled && depositCell != null && depositCell.Bounds.PointInside(args.X, args.Y))
{
if (mouse?.Itemstack != null)
{
QuartermasterModSystem.clientChannel?.SendPacket(new PacketDeposit
{
Mode = args.Button == EnumMouseButton.Right ? 1 : 0
});
}
args.Handled = true;
return;
}
var grid = SingleComposer?.GetSlotGrid("itemgrid");
if (!args.Handled && grid != null && grid.Bounds.PointInside(args.X, args.Y))
{
// Deposits go through the deposit cell; ignore a held item over the grid
// so nothing is placed/withdrawn by accident.
if (mouse?.Itemstack != null) { args.Handled = true; return; }
// grid.hoverSlotId is only refreshed on mouse-move events, so it goes stale
// (resets to -1) whenever the dialog recomposes after a withdraw. Recompute it
// from the actual click position so a click on a stationary cursor still works.
grid.OnMouseMove(capi, args);
int slotId = grid.hoverSlotId;
if (slotId >= 0 && slotId < currentVisibleEntries.Count)
{
var entry = currentVisibleEntries[slotId];
bool shift = capi.Input.KeyboardKeyState[(int)GlKeys.ShiftLeft] || capi.Input.KeyboardKeyState[(int)GlKeys.ShiftRight];
// Locate: middle-click (or any click in read-only mode).
if (locateOnly || args.Button == EnumMouseButton.Middle)
{
if (entry.Locations.Count > 0)
{
modSystem.SetHighlights(entry.Locations, entry.Stack.GetName());
TryClose();
}
else
{
capi.ShowChatMessage("Quartermaster: no known location for that item.");
}
}
else
{
int mode = shift ? 2 : (args.Button == EnumMouseButton.Right ? 1 : 0);
QuartermasterModSystem.clientChannel?.SendPacket(new PacketWithdraw
{
Code = entry.Stack.Collectible.Code.ToString(),
Type = entry.Stack.Class.ToString(),
VariantType = entry.Stack.Attributes?.GetString("type"),
Variant = entry.Stack.Attributes?.GetString("variant"),
Material = entry.Stack.Attributes?.GetString("material"),
Mode = mode
});
}
}
args.Handled = true;
return;
}
base.OnMouseDown(args);
}
private void OnTitleBarClose() => TryClose();
public override void OnGuiOpened()
{
openTime = capi.World.ElapsedMilliseconds;
isWaitingForServer = true;
// Blank the slot-stats label until this session's first server reply — the
// player may have moved, so a count from the previous spot would be wrong.
freeSlots = -1;
// Start each session with a fresh, empty search and no category filters.
currentSearchText = "";
activeCategories = ItemCategory.None;
currentPage = 0;
FilterItems("");
if (virtualInventory == null) virtualInventory = new InventoryGeneric(1, "quartermaster-init", capi, null);
ComposeDialog();
QuartermasterModSystem.clientChannel?.SendPacket(new PacketQuartermasterRequest());
SingleComposer.FocusElement(-1);
}
public bool IsLookingAtStation()
{
var blockSel = capi.World.Player.CurrentBlockSelection;
if (blockSel?.Block == null) return false;
// The lectern can be consulted wherever it's placed (no foundation requirement);
// this just confirms the player is actually looking at one so the hotkey opens it.
return blockSel.Block.Code.Path.Contains("quartermasterdesk");
}
}
}