feat: Blax Defaults 1.0
Defaults for new stockpiles per type and for new storage buildings, a Defaults button in the storage tab, quick setup for empty shelves, default values for new bills, overlap warnings. Works with any DLC combination; tested on core only, every Royalty/Ideology/Biotech combination and with the compat mod set.
This commit is contained in:
parent
58dee2c3a3
commit
aba5ab08fe
|
|
@ -0,0 +1,9 @@
|
||||||
|
Source/**/bin/
|
||||||
|
Source/**/obj/
|
||||||
|
.vs/
|
||||||
|
*.user
|
||||||
|
Tests/**/1.7/
|
||||||
|
Tests/**/bin/
|
||||||
|
Tests/**/obj/
|
||||||
|
Tools/**/bin/
|
||||||
|
Tools/**/obj/
|
||||||
Binary file not shown.
Binary file not shown.
|
|
@ -0,0 +1,45 @@
|
||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<ModMetaData>
|
||||||
|
<name>Blax Defaults</name>
|
||||||
|
<author>Blax Gaming</author>
|
||||||
|
<packageId>blax.defaults</packageId>
|
||||||
|
<modVersion>1.0.0</modVersion>
|
||||||
|
<supportedVersions>
|
||||||
|
<li>1.7</li>
|
||||||
|
</supportedVersions>
|
||||||
|
<modDependencies>
|
||||||
|
<li>
|
||||||
|
<packageId>brrainz.harmony</packageId>
|
||||||
|
<displayName>Harmony</displayName>
|
||||||
|
<steamWorkshopUrl>steam://url/CommunityFilePage/2009463077</steamWorkshopUrl>
|
||||||
|
<downloadUrl>https://github.com/pardeike/HarmonyRimWorld/releases/latest</downloadUrl>
|
||||||
|
</li>
|
||||||
|
</modDependencies>
|
||||||
|
<loadAfter>
|
||||||
|
<li>brrainz.harmony</li>
|
||||||
|
</loadAfter>
|
||||||
|
<description>Starting settings for storage, bills, crops, buildings, animals and mechs.
|
||||||
|
|
||||||
|
Colonists, slaves and prisoners: Blax Castes.
|
||||||
|
|
||||||
|
Tune one stockpile, shelf or bill, click "Make default", and every new one you make starts like it. Nothing changes until you save a default, existing things are never touched, and nothing goes into your save. Works with any DLC combination, core only included.
|
||||||
|
|
||||||
|
<color=#19C63C>Storage</color>
|
||||||
|
- New stockpiles, dumping stockpiles, shelves, bookcases, hoppers, fridges and weapon racks start with the filter and priority you saved.
|
||||||
|
- A "Defaults" button in the storage tab: make default, load your default, load the game's default, forget.
|
||||||
|
- One click makes new shelves start empty at Normal, and they stay empty when you add mods.
|
||||||
|
|
||||||
|
<color=#19C63C>Bills</color>
|
||||||
|
- Values for every new bill: repeat mode, count and target, pause and resume, ingredient radius, skill range, drop on floor or best stockpile, and the counting options.
|
||||||
|
- Surgery bills and pasted bills are never touched.
|
||||||
|
|
||||||
|
<color=#19C63C>Your defaults stay</color>
|
||||||
|
- Defaults live in their own file, shared by every save, with a backup that a broken file never overwrites.
|
||||||
|
- Names from a mod you removed are skipped, not lost, and work again when the mod comes back.
|
||||||
|
- The settings page lists every default with Edit and Forget, and names mods that set the same things.
|
||||||
|
|
||||||
|
Multiplayer: not supported yet.
|
||||||
|
|
||||||
|
<color=#19C63C>Made by Blax</color>
|
||||||
|
Blax Gaming is a project of Blax Software, an Austrian software practice. We write Austrian-quality code in many fields: web platforms, mobile apps, backends, infrastructure, and the mods we play in our own colonies. www.blax.at</description>
|
||||||
|
</ModMetaData>
|
||||||
|
|
@ -0,0 +1,15 @@
|
||||||
|
# Changelog
|
||||||
|
|
||||||
|
## 1.0.0
|
||||||
|
|
||||||
|
- Stockpile defaults: drag a stockpile or a dumping stockpile and it starts with the filter and priority you saved for that type. A modded stockpile designator that builds on the vanilla one is a type of its own. An Expand drag that grows a zone leaves its filter alone.
|
||||||
|
- Storage building defaults: a new shelf, small shelf, bookcase, hopper, fridge or weapon rack starts with the default you saved for that building, from the moment its blueprint is placed. Changes you make on the blueprint still win. A shelf or hopper that auto-rebuild puts back keeps its old settings; a rebuilt bookcase starts from your default. Ruins, map generation, trader stock and things spawned without a blueprint keep the game's settings. A default never makes a building take items it can't hold.
|
||||||
|
- "Defaults" button in the storage tab of stockpiles and covered storage buildings, or a small icon where the tab has no priority button: "Make default for new shelves", "Load your default", "Load the game's default" and "Forget the default for new shelves", which asks first. On a stockpile each entry opens a menu of stockpile types. On linked shelves it reads and writes the group's settings. The tooltip says whether new ones start from your default.
|
||||||
|
- Quick setup: the settings page button "New shelves start empty at Normal" lists every covered storage building with a checkbox. General-purpose shelves are ticked; hoppers, bookcases and storage limited to one kind of item start unticked, and kinds that already have a default are marked. Confirming saves an empty default at Normal for each ticked kind, one that also refuses items mods add later.
|
||||||
|
- A storage default stores every item it allows and every item it refuses, plus a rule for items it lists in neither: follow the game's default (what "Make default" saves), refuse them or allow them.
|
||||||
|
- Values for every new bill: repeat mode, count, target, pause when satisfied and resume at, ingredient radius, allowed skill range, where products go (best stockpile or drop on floor), count equipped, count tainted, and the hit points and quality ranges. Each value starts at "the game's default" and only values you change are applied. "Do until you have X" falls back to "do X times" where the bill can't count its products. Surgery, mech gestation, mech resurrection and forming bills, pasted bills and loaded bills are never touched.
|
||||||
|
- Settings page (Mod settings > Blax Defaults): a master switch, a status line with the number of defaults and of names from inactive mods, and the sections Stockpiles, Storage buildings and Every new bill, each with its own switch. Every saved default has a row saying what it sets, with Edit and Forget; Forget asks first. Edit opens the item filter with a priority dropdown and the rule for unlisted items, also from the main menu.
|
||||||
|
- Defaults file: your defaults live in Config/BlaxDefaults/Defaults.xml in the game's save data folder, shared by every save, never in a save or in the mod settings. Every write goes to a temporary file first, is read back and checked, and only then replaces the file, with the previous version kept as Defaults.xml.bak. A file that fails to load is kept as a broken copy with its own name and is never rotated into the backup; the backup loads instead, and the settings page says so. A file that could not be read at startup is read again when first needed, and is moved aside under its own name before anything overwrites it. Defaults of a kind this version doesn't know, saved by a later version, are skipped and kept in the file, and a file from a newer version is read but never overwritten.
|
||||||
|
- Names from a mod or DLC you removed stay in the file, are skipped and counted on the settings page, and work again when the mod comes back. A saved default for a DLC building whose DLC is off shows disabled with "Needs Biotech" and stays in the file.
|
||||||
|
- Overlap warnings: the settings page names active mods that set the same starting settings, and the first game loaded in a session opens a window listing them, with "Don't remind me" per mod. 1.0 detects 1trickPwnyta's Defaults, Set my Defaults, [FSF] No Default Shelf Storage, [FSF] FrozenSnowFox Tweaks, Better Workbench Management, Default Ingredient Radius and Default Bill Ingredient Radius.
|
||||||
|
- Works with any DLC combination, core only included. Nothing goes into your save, so the mod can be added to or removed from a running colony.
|
||||||
|
|
@ -0,0 +1,24 @@
|
||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<LanguageData>
|
||||||
|
|
||||||
|
<!-- Shared keys. Each work package keeps its own strings in BlaxDefaults_<package>.xml. -->
|
||||||
|
|
||||||
|
<!-- DLC support -->
|
||||||
|
<BlaxDefaults_NeedsDlc>Needs {0}</BlaxDefaults_NeedsDlc>
|
||||||
|
|
||||||
|
<!-- Stockpile kinds -->
|
||||||
|
<BlaxDefaults_KindStockpile>stockpile</BlaxDefaults_KindStockpile>
|
||||||
|
<BlaxDefaults_KindStockpilePlural>stockpiles</BlaxDefaults_KindStockpilePlural>
|
||||||
|
<BlaxDefaults_KindDumping>dumping stockpile</BlaxDefaults_KindDumping>
|
||||||
|
<BlaxDefaults_KindDumpingPlural>dumping stockpiles</BlaxDefaults_KindDumpingPlural>
|
||||||
|
|
||||||
|
<!-- Plurals the language worker gets wrong ("shelfs"), keyed BlaxDefaults_Plural_<defName> -->
|
||||||
|
<BlaxDefaults_Plural_Shelf>shelves</BlaxDefaults_Plural_Shelf>
|
||||||
|
<BlaxDefaults_Plural_ShelfSmall>small shelves</BlaxDefaults_Plural_ShelfSmall>
|
||||||
|
|
||||||
|
<!-- The rule for items a storage default lists in neither list -->
|
||||||
|
<BlaxDefaults_UnlistedGame>follow the game's default</BlaxDefaults_UnlistedGame>
|
||||||
|
<BlaxDefaults_UnlistedRefuse>refuse them</BlaxDefaults_UnlistedRefuse>
|
||||||
|
<BlaxDefaults_UnlistedAllow>allow them</BlaxDefaults_UnlistedAllow>
|
||||||
|
|
||||||
|
</LanguageData>
|
||||||
|
|
@ -0,0 +1,42 @@
|
||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<LanguageData>
|
||||||
|
|
||||||
|
<!-- Work package "bills". Keys start with BlaxDefaults_. -->
|
||||||
|
|
||||||
|
<!-- The "Every new bill" section on the settings page -->
|
||||||
|
<BlaxDefaults_Bills_Intro>Values every new production bill starts with. Only values you change are applied; the rest keep the game's default. Surgery, mech gestation and pasted bills are never changed, and existing bills keep their values.</BlaxDefaults_Bills_Intro>
|
||||||
|
<BlaxDefaults_Bills_Off>Switched off: new bills start with the game's values. Your values stay saved.</BlaxDefaults_Bills_Off>
|
||||||
|
<BlaxDefaults_Bills_TargetNote>Bills that can't count their products use "do X times" instead.</BlaxDefaults_Bills_TargetNote>
|
||||||
|
<BlaxDefaults_Bills_ResumeNote>Resume at is not below the target, so these bills never pause. Set a lower resume value or a higher target.</BlaxDefaults_Bills_ResumeNote>
|
||||||
|
|
||||||
|
<!-- Row labels, one per value -->
|
||||||
|
<BlaxDefaults_Bills_RepeatMode>Repeat mode</BlaxDefaults_Bills_RepeatMode>
|
||||||
|
<BlaxDefaults_Bills_RepeatCount>Count (do X times)</BlaxDefaults_Bills_RepeatCount>
|
||||||
|
<BlaxDefaults_Bills_TargetCount>Target (do until you have X)</BlaxDefaults_Bills_TargetCount>
|
||||||
|
<BlaxDefaults_Bills_PauseWhenSatisfied>Pause when satisfied</BlaxDefaults_Bills_PauseWhenSatisfied>
|
||||||
|
<BlaxDefaults_Bills_UnpauseWhenYouHave>Resume at</BlaxDefaults_Bills_UnpauseWhenYouHave>
|
||||||
|
<BlaxDefaults_Bills_IngredientSearchRadius>Ingredient radius</BlaxDefaults_Bills_IngredientSearchRadius>
|
||||||
|
<BlaxDefaults_Bills_AllowedSkillRange>Allowed skill range</BlaxDefaults_Bills_AllowedSkillRange>
|
||||||
|
<BlaxDefaults_Bills_StoreMode>Where products go</BlaxDefaults_Bills_StoreMode>
|
||||||
|
<BlaxDefaults_Bills_IncludeEquipped>Count equipped</BlaxDefaults_Bills_IncludeEquipped>
|
||||||
|
<BlaxDefaults_Bills_IncludeTainted>Count tainted</BlaxDefaults_Bills_IncludeTainted>
|
||||||
|
<BlaxDefaults_Bills_HpRange>Hit points when counting</BlaxDefaults_Bills_HpRange>
|
||||||
|
<BlaxDefaults_Bills_QualityRange>Quality when counting</BlaxDefaults_Bills_QualityRange>
|
||||||
|
|
||||||
|
<!-- Row tooltips -->
|
||||||
|
<BlaxDefaults_Bills_RepeatCountTip>Used by bills set to "do X times".</BlaxDefaults_Bills_RepeatCountTip>
|
||||||
|
<BlaxDefaults_Bills_TargetOnlyTip>Used by bills set to "do until you have X".</BlaxDefaults_Bills_TargetOnlyTip>
|
||||||
|
|
||||||
|
<!-- Values and buttons -->
|
||||||
|
<BlaxDefaults_Bills_GameDefault>Game's default: {0}</BlaxDefaults_Bills_GameDefault>
|
||||||
|
<BlaxDefaults_Bills_Change>Change</BlaxDefaults_Bills_Change>
|
||||||
|
<BlaxDefaults_Bills_UseGameDefault>Game's default</BlaxDefaults_Bills_UseGameDefault>
|
||||||
|
<BlaxDefaults_Bills_ValueOn>On</BlaxDefaults_Bills_ValueOn>
|
||||||
|
<BlaxDefaults_Bills_ValueOff>Off</BlaxDefaults_Bills_ValueOff>
|
||||||
|
<BlaxDefaults_Bills_Unlimited>Unlimited</BlaxDefaults_Bills_Unlimited>
|
||||||
|
<BlaxDefaults_Bills_Range>{0} to {1}</BlaxDefaults_Bills_Range>
|
||||||
|
<BlaxDefaults_Bills_AnyQuality>any quality</BlaxDefaults_Bills_AnyQuality>
|
||||||
|
<BlaxDefaults_Bills_ResetAll>All values back to the game's default</BlaxDefaults_Bills_ResetAll>
|
||||||
|
<BlaxDefaults_Bills_ResetAllConfirm>Forget the values for every new bill? New bills then start with the game's values. Existing bills keep theirs.</BlaxDefaults_Bills_ResetAllConfirm>
|
||||||
|
|
||||||
|
</LanguageData>
|
||||||
|
|
@ -0,0 +1,6 @@
|
||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<LanguageData>
|
||||||
|
|
||||||
|
<!-- Work package "file". Keys start with BlaxDefaults_. -->
|
||||||
|
|
||||||
|
</LanguageData>
|
||||||
|
|
@ -0,0 +1,6 @@
|
||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<LanguageData>
|
||||||
|
|
||||||
|
<!-- Work package "hooks". Keys start with BlaxDefaults_. -->
|
||||||
|
|
||||||
|
</LanguageData>
|
||||||
|
|
@ -0,0 +1,58 @@
|
||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<LanguageData>
|
||||||
|
|
||||||
|
<!-- Work package "page". Keys start with BlaxDefaults_. -->
|
||||||
|
|
||||||
|
<!-- Settings page: master toggle and status -->
|
||||||
|
<BlaxDefaults_PageEnabled>Apply saved defaults to new things</BlaxDefaults_PageEnabled>
|
||||||
|
<BlaxDefaults_PageEnabledTip>Off: nothing new gets a default, and every new stockpile, storage building and bill starts with the game's settings. Your saved defaults stay in the file.</BlaxDefaults_PageEnabledTip>
|
||||||
|
<BlaxDefaults_PageStatusNone>No defaults saved yet.</BlaxDefaults_PageStatusNone>
|
||||||
|
<BlaxDefaults_PageStatusOne>1 default.</BlaxDefaults_PageStatusOne>
|
||||||
|
<BlaxDefaults_PageStatusMany>{0} defaults.</BlaxDefaults_PageStatusMany>
|
||||||
|
<BlaxDefaults_PageInactiveOne>1 name from a mod that is not active.</BlaxDefaults_PageInactiveOne>
|
||||||
|
<BlaxDefaults_PageInactiveMany>{0} names from mods that are not active.</BlaxDefaults_PageInactiveMany>
|
||||||
|
<BlaxDefaults_PageStatusTip>Defaults are shared by every save and kept in {0}. Names from mods that are not active are skipped and stay in the file, so they work again when the mod is back.</BlaxDefaults_PageStatusTip>
|
||||||
|
|
||||||
|
<!-- Settings page: broken defaults files found at startup -->
|
||||||
|
<BlaxDefaults_PageBrokenBoth>The defaults file and its backup could not be read, so no defaults are loaded. The broken files are kept in {0}: {1}</BlaxDefaults_PageBrokenBoth>
|
||||||
|
<BlaxDefaults_PageBrokenRecovered>A defaults file could not be read and is kept in {0}: {1}. Your defaults were read from {2}.</BlaxDefaults_PageBrokenRecovered>
|
||||||
|
<BlaxDefaults_PageBrokenEmpty>A defaults file could not be read and is kept in {0}: {1}. No defaults are loaded.</BlaxDefaults_PageBrokenEmpty>
|
||||||
|
<BlaxDefaults_PageUnread>The defaults file in {0} could not be read this session, so your defaults are not loaded. The log has the details. If you save a default, the file is first moved aside under a new name in that folder.</BlaxDefaults_PageUnread>
|
||||||
|
<BlaxDefaults_PageUnreadKept>The defaults file could not be read this session and is kept in {0}: {1}. The defaults in it are not loaded.</BlaxDefaults_PageUnreadKept>
|
||||||
|
<BlaxDefaults_PageNewerFile>The defaults file was made by a newer version of Blax Defaults. This version reads it but does not change it, so defaults you save or forget now only work until you quit.</BlaxDefaults_PageNewerFile>
|
||||||
|
|
||||||
|
<!-- Settings page: sections -->
|
||||||
|
<BlaxDefaults_PageSectionStockpiles>Stockpiles</BlaxDefaults_PageSectionStockpiles>
|
||||||
|
<BlaxDefaults_PageStockpilesToggle>New stockpiles start from your default</BlaxDefaults_PageStockpilesToggle>
|
||||||
|
<BlaxDefaults_PageStockpilesToggleTip>Off: new stockpiles start with the game's settings. The stockpile defaults below stay saved.</BlaxDefaults_PageStockpilesToggleTip>
|
||||||
|
<BlaxDefaults_PageStockpilesNone>No stockpile defaults yet. Make one with the Defaults button in a stockpile's storage tab.</BlaxDefaults_PageStockpilesNone>
|
||||||
|
<BlaxDefaults_PageSectionStorage>Storage buildings</BlaxDefaults_PageSectionStorage>
|
||||||
|
<BlaxDefaults_PageStorageToggle>New storage buildings start from your default</BlaxDefaults_PageStorageToggle>
|
||||||
|
<BlaxDefaults_PageStorageToggleTip>Off: new shelves, bookcases, hoppers and other storage buildings start with the game's settings. The defaults below stay saved.</BlaxDefaults_PageStorageToggleTip>
|
||||||
|
<BlaxDefaults_PageStorageNone>No storage building defaults yet. Make one with the Defaults button in a shelf's storage tab.</BlaxDefaults_PageStorageNone>
|
||||||
|
<BlaxDefaults_PageSectionBills>Every new bill</BlaxDefaults_PageSectionBills>
|
||||||
|
<BlaxDefaults_PageBillsToggle>New bills start with the values below</BlaxDefaults_PageBillsToggle>
|
||||||
|
<BlaxDefaults_PageBillsToggleTip>Off: new bills start with the game's values. The values below stay saved.</BlaxDefaults_PageBillsToggleTip>
|
||||||
|
|
||||||
|
<!-- Settings page: one row per saved default -->
|
||||||
|
<BlaxDefaults_PageRowSummary>{0}: {1}, allows {2} of {3} items</BlaxDefaults_PageRowSummary>
|
||||||
|
<BlaxDefaults_PageRowRefusesUnlisted>{0}, refuses unlisted items</BlaxDefaults_PageRowRefusesUnlisted>
|
||||||
|
<BlaxDefaults_PageRowAllowsUnlisted>{0}, allows unlisted items</BlaxDefaults_PageRowAllowsUnlisted>
|
||||||
|
<BlaxDefaults_PageRowUnlistedTip>Items this default lists neither as allowed nor as refused, such as items a mod adds later: {0}.</BlaxDefaults_PageRowUnlistedTip>
|
||||||
|
<BlaxDefaults_PageInactiveNamesTip>Names from mods that are not active, skipped until the mod is back: {0}</BlaxDefaults_PageInactiveNamesTip>
|
||||||
|
<BlaxDefaults_PageEdit>Edit</BlaxDefaults_PageEdit>
|
||||||
|
<BlaxDefaults_PageForget>Forget</BlaxDefaults_PageForget>
|
||||||
|
<BlaxDefaults_PageEditNeedsDlc>{0}. The default stays in the file and works again when the DLC is back.</BlaxDefaults_PageEditNeedsDlc>
|
||||||
|
<BlaxDefaults_PageEditKindMissing>This kind is not loaded, so its default can't be edited now. It stays in the file and works again when its mod is back.</BlaxDefaults_PageEditKindMissing>
|
||||||
|
<BlaxDefaults_PageForgetConfirm>Forget the default for new {0}? New ones start with the game's settings again. Existing ones keep their settings.</BlaxDefaults_PageForgetConfirm>
|
||||||
|
|
||||||
|
<!-- Storage edit window -->
|
||||||
|
<BlaxDefaults_PageEditTitle>Default for new {0}</BlaxDefaults_PageEditTitle>
|
||||||
|
<BlaxDefaults_PagePriority>Priority: {0}</BlaxDefaults_PagePriority>
|
||||||
|
<BlaxDefaults_PageUnlisted>Items not listed: {0}</BlaxDefaults_PageUnlisted>
|
||||||
|
<BlaxDefaults_PageUnlistedTip>What this default does with items it lists neither as allowed nor as refused, such as items a mod adds later. "Follow the game's default" gives them the setting new {0} get from the game.</BlaxDefaults_PageUnlistedTip>
|
||||||
|
<BlaxDefaults_PageFilterNeedsGame>The item filter can't be shown here without a loaded game. Load a game to edit this default.</BlaxDefaults_PageFilterNeedsGame>
|
||||||
|
<BlaxDefaults_PageSave>Save</BlaxDefaults_PageSave>
|
||||||
|
<BlaxDefaults_PageCancel>Cancel</BlaxDefaults_PageCancel>
|
||||||
|
|
||||||
|
</LanguageData>
|
||||||
|
|
@ -0,0 +1,40 @@
|
||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<LanguageData>
|
||||||
|
|
||||||
|
<!-- Work package "setup". Keys start with BlaxDefaults_. -->
|
||||||
|
|
||||||
|
<!-- Quick setup: new shelves start empty -->
|
||||||
|
<BlaxDefaults_QuickSetupButton>New shelves start empty at Normal</BlaxDefaults_QuickSetupButton>
|
||||||
|
<BlaxDefaults_QuickSetupTip>Pick the storage buildings that should start empty at Normal. Each ticked kind gets a default of its own that also refuses items mods add later. You can edit or forget each one on this page afterwards.</BlaxDefaults_QuickSetupTip>
|
||||||
|
<BlaxDefaults_QuickSetupTipFsf>[FSF] No Default Shelf Storage is active and does the same thing for every shelf. You only need one of the two.</BlaxDefaults_QuickSetupTipFsf>
|
||||||
|
<BlaxDefaults_QuickSetupTitle>New shelves start empty at Normal</BlaxDefaults_QuickSetupTitle>
|
||||||
|
<BlaxDefaults_QuickSetupIntro>Each ticked kind gets a default that allows nothing at Normal and also refuses items that mods add later. General-purpose shelves are ticked. Hoppers, bookcases and storage for one kind of item start unticked.</BlaxDefaults_QuickSetupIntro>
|
||||||
|
<BlaxDefaults_QuickSetupNone>No storage building to set up.</BlaxDefaults_QuickSetupNone>
|
||||||
|
<BlaxDefaults_QuickSetupHasDefault>has a default</BlaxDefaults_QuickSetupHasDefault>
|
||||||
|
<BlaxDefaults_QuickSetupReasonHasDefault>Already has a default. Ticking it replaces that default.</BlaxDefaults_QuickSetupReasonHasDefault>
|
||||||
|
<BlaxDefaults_QuickSetupReasonNotShelf>Not a plain storage building, so it starts unticked.</BlaxDefaults_QuickSetupReasonNotShelf>
|
||||||
|
<BlaxDefaults_QuickSetupReasonHopper>An empty hopper starves the nutrient paste dispenser, so it starts unticked.</BlaxDefaults_QuickSetupReasonHopper>
|
||||||
|
<BlaxDefaults_QuickSetupReasonOneCategory>Takes only one kind of item, so an empty default would stop it taking anything. It starts unticked.</BlaxDefaults_QuickSetupReasonOneCategory>
|
||||||
|
<BlaxDefaults_QuickSetupSaved>Saved {0} empty defaults.</BlaxDefaults_QuickSetupSaved>
|
||||||
|
|
||||||
|
<!-- Overlap warnings -->
|
||||||
|
<BlaxDefaults_WarnOverlaps>Warn about mods that set the same defaults</BlaxDefaults_WarnOverlaps>
|
||||||
|
<BlaxDefaults_WarnOverlapsTip>Names them here and shows one window on the first game you load in a session. "Don't remind me" in that window hides a mod from the window, not from this page.</BlaxDefaults_WarnOverlapsTip>
|
||||||
|
<BlaxDefaults_OverlapSettingsIntro>These active mods set some of the same starting settings:</BlaxDefaults_OverlapSettingsIntro>
|
||||||
|
<BlaxDefaults_OverlapLine>{MOD}: {WHAT}</BlaxDefaults_OverlapLine>
|
||||||
|
<BlaxDefaults_OverlapAdvice>Set each of these in one mod only, or the two overwrite each other.</BlaxDefaults_OverlapAdvice>
|
||||||
|
<BlaxDefaults_OverlapTitle>Mods that set the same defaults</BlaxDefaults_OverlapTitle>
|
||||||
|
<BlaxDefaults_OverlapMessage>{MODS} set some of the same starting settings as Blax Defaults. Set each of these in one mod only, or the two overwrite each other. The Blax Defaults settings page lists them too.</BlaxDefaults_OverlapMessage>
|
||||||
|
<BlaxDefaults_OverlapDontRemind>Don't remind me</BlaxDefaults_OverlapDontRemind>
|
||||||
|
<BlaxDefaults_OverlapDismissed>Not shown again</BlaxDefaults_OverlapDismissed>
|
||||||
|
|
||||||
|
<!-- What each overlapping mod sets -->
|
||||||
|
<BlaxDefaults_OverlapWhatDefaults>Starting settings for stockpiles, storage buildings and bills</BlaxDefaults_OverlapWhatDefaults>
|
||||||
|
<BlaxDefaults_OverlapWhatFsfShelves>Shelves start empty at Normal</BlaxDefaults_OverlapWhatFsfShelves>
|
||||||
|
<BlaxDefaults_OverlapWhatFsfTweaks>Its "No Default Storage Settings" option empties the starting filter of storage buildings</BlaxDefaults_OverlapWhatFsfTweaks>
|
||||||
|
<BlaxDefaults_OverlapWhatEmptyStorage>Storage buildings start empty at Normal</BlaxDefaults_OverlapWhatEmptyStorage>
|
||||||
|
<BlaxDefaults_OverlapWhatStoreMode>Where the products of new bills go</BlaxDefaults_OverlapWhatStoreMode>
|
||||||
|
<BlaxDefaults_OverlapWhatRadius>The ingredient radius of new bills</BlaxDefaults_OverlapWhatRadius>
|
||||||
|
<BlaxDefaults_OverlapWhatRepeat>The repeat mode of new bills</BlaxDefaults_OverlapWhatRepeat>
|
||||||
|
|
||||||
|
</LanguageData>
|
||||||
|
|
@ -0,0 +1,42 @@
|
||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<LanguageData>
|
||||||
|
|
||||||
|
<!-- Work package "tab". Keys start with BlaxDefaults_. -->
|
||||||
|
|
||||||
|
<!-- The button in the storage tab -->
|
||||||
|
<BlaxDefaults_TabButton>Defaults</BlaxDefaults_TabButton>
|
||||||
|
|
||||||
|
<!-- Menu entries. {0} is the kind in the plural: "shelves", "dumping stockpiles". -->
|
||||||
|
<BlaxDefaults_TabMakeDefault>Make default for new {0}</BlaxDefaults_TabMakeDefault>
|
||||||
|
<BlaxDefaults_TabLoadDefault>Load your default</BlaxDefaults_TabLoadDefault>
|
||||||
|
<BlaxDefaults_TabLoadGameDefault>Load the game's default</BlaxDefaults_TabLoadGameDefault>
|
||||||
|
<BlaxDefaults_TabForget>Forget the default for new {0}</BlaxDefaults_TabForget>
|
||||||
|
|
||||||
|
<!-- On a stockpile each entry opens a list of stockpile types -->
|
||||||
|
<BlaxDefaults_TabMakeDefaultType>Make default for a stockpile type</BlaxDefaults_TabMakeDefaultType>
|
||||||
|
<BlaxDefaults_TabForgetType>Forget the default for a stockpile type</BlaxDefaults_TabForgetType>
|
||||||
|
<BlaxDefaults_TabNoStockpileDefault>You have no default for any stockpile type yet.</BlaxDefaults_TabNoStockpileDefault>
|
||||||
|
|
||||||
|
<!-- Menu entry tooltips -->
|
||||||
|
<BlaxDefaults_TabMakeDefaultTip>New {0} start with the filter and priority shown here. The ones you already have keep their settings.</BlaxDefaults_TabMakeDefaultTip>
|
||||||
|
<BlaxDefaults_TabLoadDefaultTip>Sets the filter and priority shown here to your default for new {0}.</BlaxDefaults_TabLoadDefaultTip>
|
||||||
|
<BlaxDefaults_TabLoadGameDefaultTip>Sets the filter and priority shown here to the game's default for new {0}.</BlaxDefaults_TabLoadGameDefaultTip>
|
||||||
|
<BlaxDefaults_TabForgetTip>New {0} start from the game's default again. Asks first.</BlaxDefaults_TabForgetTip>
|
||||||
|
<BlaxDefaults_TabNoDefault>You have no default for new {0} yet.</BlaxDefaults_TabNoDefault>
|
||||||
|
|
||||||
|
<!-- After a click -->
|
||||||
|
<BlaxDefaults_TabMadeDefault>New {0} now start from your default.</BlaxDefaults_TabMadeDefault>
|
||||||
|
<BlaxDefaults_TabForgotten>New {0} now start from the game's default.</BlaxDefaults_TabForgotten>
|
||||||
|
<BlaxDefaults_TabForgetConfirm>Forget your default for new {0}?\n\nNew {0} will start from the game's default. The ones you already have keep their settings.</BlaxDefaults_TabForgetConfirm>
|
||||||
|
<BlaxDefaults_TabWriteFailed>Your default works until you quit, but the defaults file could not be written. The log has the details.</BlaxDefaults_TabWriteFailed>
|
||||||
|
|
||||||
|
<!-- The button's tooltip -->
|
||||||
|
<BlaxDefaults_TabTipYours>New {0} start from your default.</BlaxDefaults_TabTipYours>
|
||||||
|
<BlaxDefaults_TabTipGame>New {0} start from the game's default.</BlaxDefaults_TabTipGame>
|
||||||
|
<BlaxDefaults_TabTipStorageOff>New {0} start from the game's default: storage building defaults are off in the mod settings.</BlaxDefaults_TabTipStorageOff>
|
||||||
|
<BlaxDefaults_TabTipStockpilesSome>New stockpiles of these types start from your default:</BlaxDefaults_TabTipStockpilesSome>
|
||||||
|
<BlaxDefaults_TabTipStockpilesRest>Other types start from the game's default.</BlaxDefaults_TabTipStockpilesRest>
|
||||||
|
<BlaxDefaults_TabTipStockpilesNone>New stockpiles of every type start from the game's default.</BlaxDefaults_TabTipStockpilesNone>
|
||||||
|
<BlaxDefaults_TabTipStockpilesOff>New stockpiles start from the game's default: stockpile defaults are off in the mod settings.</BlaxDefaults_TabTipStockpilesOff>
|
||||||
|
|
||||||
|
</LanguageData>
|
||||||
|
|
@ -0,0 +1,132 @@
|
||||||
|
using System;
|
||||||
|
using HarmonyLib;
|
||||||
|
using RimWorld;
|
||||||
|
using Verse;
|
||||||
|
|
||||||
|
namespace BlaxDefaults
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Values for every new bill. Work package "bills" (design.md: "Values for every new bill"). A postfix on
|
||||||
|
/// BillUtility.MakeNewBill, whose only vanilla callers are the Bills tab's add menu and the dev colony maker.
|
||||||
|
/// Applies to exactly Bill_Production and Bill_ProductionWithUft: Bill_Autonomous, Bill_ProductionMech and
|
||||||
|
/// Bill_ResurrectMech also derive from Bill_Production (through Bill_Autonomous and Bill_Mech) and must be
|
||||||
|
/// skipped, so the check is on the exact type. Surgery (Bill_Medical), pasted bills (Bill.Clone) and loaded
|
||||||
|
/// bills never reach MakeNewBill.
|
||||||
|
/// </summary>
|
||||||
|
public static class BillDefaults
|
||||||
|
{
|
||||||
|
/// <summary>The repeat modes a default may name, in menu order: the three Bill_Production.ShouldDoNow knows.</summary>
|
||||||
|
public static readonly string[] RepeatModeNames = { "RepeatCount", "TargetCount", "Forever" };
|
||||||
|
|
||||||
|
/// <summary>The store modes a default may name, in menu order. Never SpecificStockpile: it needs a save-specific group.</summary>
|
||||||
|
public static readonly string[] StoreModeNames = { "BestStockpile", "DropOnFloor" };
|
||||||
|
|
||||||
|
/// <summary>The saved "Every new bill" values, or null.</summary>
|
||||||
|
public static BillValues Values => DefaultsLibrary.Get<BillValues>(DefaultsKeys.EveryBill);
|
||||||
|
|
||||||
|
/// <summary>True for exactly Bill_Production and Bill_ProductionWithUft.</summary>
|
||||||
|
public static bool AppliesTo(Bill bill)
|
||||||
|
{
|
||||||
|
Type t = bill?.GetType();
|
||||||
|
return t == typeof(Bill_Production) || t == typeof(Bill_ProductionWithUft);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>When BillsOn, AppliesTo(bill) and values are saved: Apply.</summary>
|
||||||
|
public static void OnNewBill(Bill bill)
|
||||||
|
{
|
||||||
|
if (!BlaxDefaultsMod.BillsOn || !AppliesTo(bill))
|
||||||
|
return;
|
||||||
|
BillValues values = Values;
|
||||||
|
if (values == null)
|
||||||
|
return;
|
||||||
|
Apply((Bill_Production)bill, values);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Writes every set value onto the bill: repeatMode (TargetCount only where
|
||||||
|
/// recipe.WorkerCounter.CanCountProducts(bill), else RepeatCount with the count), repeatCount,
|
||||||
|
/// targetCount, pauseWhenSatisfied, unpauseWhenYouHave, ingredientSearchRadius, allowedSkillRange,
|
||||||
|
/// SetStoreMode(BestStockpile or DropOnFloor, never SpecificStockpile), includeEquipped,
|
||||||
|
/// includeTainted, hpRange, qualityRange.
|
||||||
|
/// </summary>
|
||||||
|
public static void Apply(Bill_Production bill, BillValues values)
|
||||||
|
{
|
||||||
|
if (bill == null || values == null)
|
||||||
|
return;
|
||||||
|
|
||||||
|
BillRepeatModeDef repeat = ResolveRepeatMode(values.repeatMode);
|
||||||
|
if (repeat != null)
|
||||||
|
{
|
||||||
|
// The check the vanilla repeat menu makes (BillRepeatModeUtility.MakeConfigFloatMenu).
|
||||||
|
if (repeat == BillRepeatModeDefOf.TargetCount && !CanCountProducts(bill))
|
||||||
|
repeat = BillRepeatModeDefOf.RepeatCount;
|
||||||
|
bill.repeatMode = repeat;
|
||||||
|
}
|
||||||
|
if (values.setRepeatCount)
|
||||||
|
bill.repeatCount = values.repeatCount;
|
||||||
|
if (values.setTargetCount)
|
||||||
|
bill.targetCount = values.targetCount;
|
||||||
|
if (values.setPauseWhenSatisfied)
|
||||||
|
bill.pauseWhenSatisfied = values.pauseWhenSatisfied;
|
||||||
|
if (values.setUnpauseWhenYouHave)
|
||||||
|
bill.unpauseWhenYouHave = values.unpauseWhenYouHave;
|
||||||
|
if (values.setIngredientSearchRadius)
|
||||||
|
bill.ingredientSearchRadius = values.ingredientSearchRadius;
|
||||||
|
if (values.setAllowedSkillRange)
|
||||||
|
bill.allowedSkillRange = values.allowedSkillRange;
|
||||||
|
|
||||||
|
BillStoreModeDef store = ResolveStoreMode(values.storeMode);
|
||||||
|
if (store != null)
|
||||||
|
bill.SetStoreMode(store);
|
||||||
|
|
||||||
|
if (values.setIncludeEquipped)
|
||||||
|
bill.includeEquipped = values.includeEquipped;
|
||||||
|
if (values.setIncludeTainted)
|
||||||
|
bill.includeTainted = values.includeTainted;
|
||||||
|
if (values.setHpRange)
|
||||||
|
bill.hpRange = values.hpRange;
|
||||||
|
if (values.setQualityRange)
|
||||||
|
bill.qualityRange = values.qualityRange;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The repeat mode def for a saved name: RepeatCount, TargetCount or Forever; null for any other name.</summary>
|
||||||
|
public static BillRepeatModeDef ResolveRepeatMode(string name)
|
||||||
|
{
|
||||||
|
if (name.NullOrEmpty())
|
||||||
|
return null;
|
||||||
|
BillRepeatModeDef def = DefDatabase<BillRepeatModeDef>.GetNamedSilentFail(name);
|
||||||
|
return def == BillRepeatModeDefOf.RepeatCount || def == BillRepeatModeDefOf.TargetCount || def == BillRepeatModeDefOf.Forever
|
||||||
|
? def
|
||||||
|
: null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The store mode def for a saved name: BestStockpile or DropOnFloor; null for any other name, SpecificStockpile included.</summary>
|
||||||
|
public static BillStoreModeDef ResolveStoreMode(string name)
|
||||||
|
{
|
||||||
|
if (name.NullOrEmpty())
|
||||||
|
return null;
|
||||||
|
BillStoreModeDef def = DefDatabase<BillStoreModeDef>.GetNamedSilentFail(name);
|
||||||
|
return def == BillStoreModeDefOf.BestStockpile || def == BillStoreModeDefOf.DropOnFloor ? def : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Whether "do until you have X" works for this bill, as the vanilla menu decides it.</summary>
|
||||||
|
public static bool CanCountProducts(Bill_Production bill) =>
|
||||||
|
bill?.recipe?.WorkerCounter != null && bill.recipe.WorkerCounter.CanCountProducts(bill);
|
||||||
|
}
|
||||||
|
|
||||||
|
[HarmonyPatch(typeof(BillUtility), nameof(BillUtility.MakeNewBill))]
|
||||||
|
public static class Patch_BillUtility_MakeNewBill
|
||||||
|
{
|
||||||
|
public static void Postfix(Bill __result)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
BillDefaults.OnNewBill(__result);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
HookGuard.Report("BillUtility.MakeNewBill", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,104 @@
|
||||||
|
using System.Globalization;
|
||||||
|
using RimWorld;
|
||||||
|
using Verse;
|
||||||
|
|
||||||
|
namespace BlaxDefaults
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// The values a new production bill starts with, stored under DefaultsKeys.EveryBill ("bill:*"); recipe
|
||||||
|
/// defaults (1.1) reuse it per recipe. Every value starts at "the game's default": a value is applied
|
||||||
|
/// only when its set flag is on (repeatMode and storeMode: when not null). Strings and numbers only.
|
||||||
|
/// Pawn restrictions, a specific stockpile, names, styles and xenogerms are never part of it.
|
||||||
|
/// </summary>
|
||||||
|
public class BillValues : DefaultsEntry
|
||||||
|
{
|
||||||
|
/// <summary>BillRepeatModeDef name: RepeatCount, TargetCount or Forever. Null: the game's default.</summary>
|
||||||
|
public string repeatMode;
|
||||||
|
public bool setRepeatCount;
|
||||||
|
public int repeatCount = 1;
|
||||||
|
public bool setTargetCount;
|
||||||
|
public int targetCount = 10;
|
||||||
|
public bool setPauseWhenSatisfied;
|
||||||
|
public bool pauseWhenSatisfied;
|
||||||
|
public bool setUnpauseWhenYouHave;
|
||||||
|
public int unpauseWhenYouHave = 5;
|
||||||
|
public bool setIngredientSearchRadius;
|
||||||
|
/// <summary>999 is unlimited, as in vanilla.</summary>
|
||||||
|
public float ingredientSearchRadius = 999f;
|
||||||
|
public bool setAllowedSkillRange;
|
||||||
|
public IntRange allowedSkillRange = new IntRange(0, 20);
|
||||||
|
/// <summary>BillStoreModeDef name: BestStockpile or DropOnFloor, never SpecificStockpile. Null: the game's default.</summary>
|
||||||
|
public string storeMode;
|
||||||
|
public bool setIncludeEquipped;
|
||||||
|
public bool includeEquipped;
|
||||||
|
public bool setIncludeTainted;
|
||||||
|
public bool includeTainted;
|
||||||
|
public bool setHpRange;
|
||||||
|
public FloatRange hpRange = FloatRange.ZeroToOne;
|
||||||
|
public bool setQualityRange;
|
||||||
|
public QualityRange qualityRange = QualityRange.All;
|
||||||
|
|
||||||
|
public BillValues()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public BillValues(string key)
|
||||||
|
{
|
||||||
|
this.key = key;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>True when at least one value differs from "the game's default".</summary>
|
||||||
|
public bool AnySet =>
|
||||||
|
repeatMode != null || setRepeatCount || setTargetCount || setPauseWhenSatisfied || setUnpauseWhenYouHave
|
||||||
|
|| setIngredientSearchRadius || setAllowedSkillRange || storeMode != null || setIncludeEquipped
|
||||||
|
|| setIncludeTainted || setHpRange || setQualityRange;
|
||||||
|
|
||||||
|
public override void ExposeData()
|
||||||
|
{
|
||||||
|
base.ExposeData();
|
||||||
|
Scribe_Values.Look(ref repeatMode, "repeatMode");
|
||||||
|
Scribe_Values.Look(ref setRepeatCount, "setRepeatCount");
|
||||||
|
Scribe_Values.Look(ref repeatCount, "repeatCount", 1);
|
||||||
|
Scribe_Values.Look(ref setTargetCount, "setTargetCount");
|
||||||
|
Scribe_Values.Look(ref targetCount, "targetCount", 10);
|
||||||
|
Scribe_Values.Look(ref setPauseWhenSatisfied, "setPauseWhenSatisfied");
|
||||||
|
Scribe_Values.Look(ref pauseWhenSatisfied, "pauseWhenSatisfied");
|
||||||
|
Scribe_Values.Look(ref setUnpauseWhenYouHave, "setUnpauseWhenYouHave");
|
||||||
|
Scribe_Values.Look(ref unpauseWhenYouHave, "unpauseWhenYouHave", 5);
|
||||||
|
Scribe_Values.Look(ref setIngredientSearchRadius, "setIngredientSearchRadius");
|
||||||
|
Scribe_Values.Look(ref ingredientSearchRadius, "ingredientSearchRadius", 999f);
|
||||||
|
Scribe_Values.Look(ref setAllowedSkillRange, "setAllowedSkillRange");
|
||||||
|
Scribe_Values.Look(ref allowedSkillRange, "allowedSkillRange", new IntRange(0, 20));
|
||||||
|
Scribe_Values.Look(ref storeMode, "storeMode");
|
||||||
|
Scribe_Values.Look(ref setIncludeEquipped, "setIncludeEquipped");
|
||||||
|
Scribe_Values.Look(ref includeEquipped, "includeEquipped");
|
||||||
|
Scribe_Values.Look(ref setIncludeTainted, "setIncludeTainted");
|
||||||
|
Scribe_Values.Look(ref includeTainted, "includeTainted");
|
||||||
|
Scribe_Values.Look(ref setHpRange, "setHpRange");
|
||||||
|
Scribe_Values.Look(ref hpRange, "hpRange", FloatRange.ZeroToOne);
|
||||||
|
Scribe_Values.Look(ref setQualityRange, "setQualityRange");
|
||||||
|
Scribe_Values.Look(ref qualityRange, "qualityRange", QualityRange.All);
|
||||||
|
}
|
||||||
|
|
||||||
|
public override DefaultsEntry Clone() => (BillValues)MemberwiseClone();
|
||||||
|
|
||||||
|
public BillValues CloneValues() => (BillValues)Clone();
|
||||||
|
|
||||||
|
public override string Fingerprint()
|
||||||
|
{
|
||||||
|
CultureInfo c = CultureInfo.InvariantCulture;
|
||||||
|
return key + "|rm:" + repeatMode
|
||||||
|
+ "|rc:" + setRepeatCount + "," + repeatCount
|
||||||
|
+ "|tc:" + setTargetCount + "," + targetCount
|
||||||
|
+ "|ps:" + setPauseWhenSatisfied + "," + pauseWhenSatisfied
|
||||||
|
+ "|uy:" + setUnpauseWhenYouHave + "," + unpauseWhenYouHave
|
||||||
|
+ "|rad:" + setIngredientSearchRadius + "," + ingredientSearchRadius.ToString("R", c)
|
||||||
|
+ "|sk:" + setAllowedSkillRange + "," + allowedSkillRange.min + "~" + allowedSkillRange.max
|
||||||
|
+ "|sm:" + storeMode
|
||||||
|
+ "|eq:" + setIncludeEquipped + "," + includeEquipped
|
||||||
|
+ "|ta:" + setIncludeTainted + "," + includeTainted
|
||||||
|
+ "|hp:" + setHpRange + "," + hpRange.min.ToString("R", c) + "~" + hpRange.max.ToString("R", c)
|
||||||
|
+ "|q:" + setQualityRange + "," + qualityRange.min + "~" + qualityRange.max;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,442 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using RimWorld;
|
||||||
|
using UnityEngine;
|
||||||
|
using Verse;
|
||||||
|
|
||||||
|
namespace BlaxDefaults
|
||||||
|
{
|
||||||
|
/// <summary>One value of "Every new bill", one row of the settings section, in page order.</summary>
|
||||||
|
public enum BillField
|
||||||
|
{
|
||||||
|
RepeatMode,
|
||||||
|
RepeatCount,
|
||||||
|
TargetCount,
|
||||||
|
PauseWhenSatisfied,
|
||||||
|
UnpauseWhenYouHave,
|
||||||
|
IngredientSearchRadius,
|
||||||
|
AllowedSkillRange,
|
||||||
|
StoreMode,
|
||||||
|
IncludeEquipped,
|
||||||
|
IncludeTainted,
|
||||||
|
HpRange,
|
||||||
|
QualityRange,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The "Every new bill" values on the settings page, drawn under the section's billDefaults toggle by
|
||||||
|
/// SettingsPage. Work package "bills" (design.md: "Values for every new bill", players get). Each value has
|
||||||
|
/// a "game's default" state and only values the player changes are set: repeat mode (do X times, do until
|
||||||
|
/// you have X, do forever), the count (1), the target (10), pause when satisfied (off) and resume at (5),
|
||||||
|
/// ingredient radius (unlimited), allowed skill range (0 to 20), where products go (best stockpile or drop
|
||||||
|
/// on floor), count equipped (off), count tainted (off), and the hit points and quality ranges for counting.
|
||||||
|
/// Edits go to a clone of the saved BillValues (or a new one under DefaultsKeys.EveryBill) and are stored
|
||||||
|
/// with DefaultsLibrary.Set; when no value is set any more, the entry is forgotten.
|
||||||
|
///
|
||||||
|
/// Each row: the label, then either the game's value in grey and a "Change" button, or the editor and a
|
||||||
|
/// "Game's default" button. Edits made while the mouse button is held (sliders, ranges) are kept in
|
||||||
|
/// memory and stored once on release, so a drag writes the file once.
|
||||||
|
/// </summary>
|
||||||
|
public static class BillValuesSection
|
||||||
|
{
|
||||||
|
private const float RowHeight = 30f;
|
||||||
|
private const float RangeRowHeight = 32f;
|
||||||
|
private const float ButtonWidth = 140f;
|
||||||
|
private const float LabelWidthPct = 0.34f;
|
||||||
|
// The vanilla radius slider (Dialog_BillConfig): 3 to 100, and 100 means unlimited (999).
|
||||||
|
private const float RadiusMin = 3f;
|
||||||
|
private const float RadiusSliderMax = 100f;
|
||||||
|
private const float RadiusUnlimited = 999f;
|
||||||
|
private const int SkillRangeId = 0x4BD5B1;
|
||||||
|
private const int HpRangeId = 0x4BD5B2;
|
||||||
|
private const int QualityRangeId = 0x4BD5B3;
|
||||||
|
|
||||||
|
private static readonly Color Grey = new Color(0.65f, 0.65f, 0.65f);
|
||||||
|
|
||||||
|
/// <summary>The game's values, as a new BillValues holds them.</summary>
|
||||||
|
private static readonly BillValues Game = new BillValues();
|
||||||
|
|
||||||
|
/// <summary>Every value, in page order.</summary>
|
||||||
|
public static readonly BillField[] Fields = (BillField[])Enum.GetValues(typeof(BillField));
|
||||||
|
|
||||||
|
// Edits of a drag in progress, stored on mouse release.
|
||||||
|
private static BillValues pending;
|
||||||
|
// The saved values the rows showed last frame; another value means the library changed elsewhere.
|
||||||
|
private static string shownFingerprint;
|
||||||
|
private static readonly Dictionary<BillField, string> buffers = new Dictionary<BillField, string>();
|
||||||
|
|
||||||
|
public static void Draw(Listing_Standard l)
|
||||||
|
{
|
||||||
|
string savedPrint = BillDefaults.Values?.Fingerprint() ?? "";
|
||||||
|
if (pending == null && savedPrint != shownFingerprint)
|
||||||
|
buffers.Clear();
|
||||||
|
BillValues v = Working();
|
||||||
|
string before = v.Fingerprint();
|
||||||
|
|
||||||
|
GreyLabel(l, "BlaxDefaults_Bills_Intro".Translate());
|
||||||
|
if (!BlaxDefaultsMod.BillsOn)
|
||||||
|
GreyLabel(l, "BlaxDefaults_Bills_Off".Translate());
|
||||||
|
|
||||||
|
ModeRow(l, v, BillField.RepeatMode);
|
||||||
|
if (v.repeatMode == "TargetCount")
|
||||||
|
GreyLabel(l, "BlaxDefaults_Bills_TargetNote".Translate());
|
||||||
|
CountRow(l, v, BillField.RepeatCount, min: 1);
|
||||||
|
CountRow(l, v, BillField.TargetCount, min: 1);
|
||||||
|
BoolRow(l, v, BillField.PauseWhenSatisfied);
|
||||||
|
CountRow(l, v, BillField.UnpauseWhenYouHave, min: 0);
|
||||||
|
if (v.setTargetCount && v.setUnpauseWhenYouHave && v.unpauseWhenYouHave >= v.targetCount)
|
||||||
|
{
|
||||||
|
// As the vanilla bill window does: resume below the target, or the bill never pauses.
|
||||||
|
v.unpauseWhenYouHave = Mathf.Max(0, v.targetCount - 1);
|
||||||
|
buffers.Remove(BillField.UnpauseWhenYouHave);
|
||||||
|
}
|
||||||
|
if (PauseNeverStarts(v))
|
||||||
|
GreyLabel(l, "BlaxDefaults_Bills_ResumeNote".Translate());
|
||||||
|
RadiusRow(l, v);
|
||||||
|
RangeRow(l, v, BillField.AllowedSkillRange);
|
||||||
|
ModeRow(l, v, BillField.StoreMode);
|
||||||
|
BoolRow(l, v, BillField.IncludeEquipped);
|
||||||
|
BoolRow(l, v, BillField.IncludeTainted);
|
||||||
|
RangeRow(l, v, BillField.HpRange);
|
||||||
|
RangeRow(l, v, BillField.QualityRange);
|
||||||
|
|
||||||
|
if (v.AnySet && l.ButtonText("BlaxDefaults_Bills_ResetAll".Translate()))
|
||||||
|
{
|
||||||
|
Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation("BlaxDefaults_Bills_ResetAllConfirm".Translate(),
|
||||||
|
() => ForgetAll(), destructive: true));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (v.Fingerprint() != before)
|
||||||
|
pending = v;
|
||||||
|
if (pending != null && !Input.GetMouseButton(0))
|
||||||
|
{
|
||||||
|
BillValues p = pending;
|
||||||
|
pending = null;
|
||||||
|
Store(p);
|
||||||
|
}
|
||||||
|
shownFingerprint = BillDefaults.Values?.Fingerprint() ?? "";
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- the logic behind the rows (tested without drawing) -------------------------------------------
|
||||||
|
|
||||||
|
/// <summary>A copy to edit: the edits of a drag in progress, else a clone of the saved values, else new values under bill:*.</summary>
|
||||||
|
public static BillValues Working() =>
|
||||||
|
(pending ?? BillDefaults.Values)?.CloneValues() ?? new BillValues(DefaultsKeys.EveryBill);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Stores an edited copy under bill:*: DefaultsLibrary.Set when a value is set and something changed,
|
||||||
|
/// DefaultsLibrary.Forget when no value is set any more. Pass a copy (Working), never the live entry.
|
||||||
|
/// Returns false when the file write failed.
|
||||||
|
/// </summary>
|
||||||
|
public static bool Store(BillValues edited)
|
||||||
|
{
|
||||||
|
if (edited == null)
|
||||||
|
return false;
|
||||||
|
edited.key = DefaultsKeys.EveryBill;
|
||||||
|
BillValues saved = BillDefaults.Values;
|
||||||
|
if (!edited.AnySet)
|
||||||
|
return saved == null || DefaultsLibrary.Forget(DefaultsKeys.EveryBill);
|
||||||
|
if (saved != null && saved.Fingerprint() == edited.Fingerprint())
|
||||||
|
return true;
|
||||||
|
return DefaultsLibrary.Set(edited);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Changes a copy of the current values and stores it (Store). For menu choices and tests.</summary>
|
||||||
|
public static bool Edit(Action<BillValues> change)
|
||||||
|
{
|
||||||
|
BillValues v = Working();
|
||||||
|
change(v);
|
||||||
|
pending = null;
|
||||||
|
buffers.Clear();
|
||||||
|
return Store(v);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Forgets every value: new bills start with the game's values again.</summary>
|
||||||
|
public static void ForgetAll()
|
||||||
|
{
|
||||||
|
pending = null;
|
||||||
|
buffers.Clear();
|
||||||
|
DefaultsLibrary.Forget(DefaultsKeys.EveryBill);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>True when the value is set, false when it follows the game's default.</summary>
|
||||||
|
public static bool IsSet(BillValues v, BillField f)
|
||||||
|
{
|
||||||
|
switch (f)
|
||||||
|
{
|
||||||
|
case BillField.RepeatMode: return v.repeatMode != null;
|
||||||
|
case BillField.RepeatCount: return v.setRepeatCount;
|
||||||
|
case BillField.TargetCount: return v.setTargetCount;
|
||||||
|
case BillField.PauseWhenSatisfied: return v.setPauseWhenSatisfied;
|
||||||
|
case BillField.UnpauseWhenYouHave: return v.setUnpauseWhenYouHave;
|
||||||
|
case BillField.IngredientSearchRadius: return v.setIngredientSearchRadius;
|
||||||
|
case BillField.AllowedSkillRange: return v.setAllowedSkillRange;
|
||||||
|
case BillField.StoreMode: return v.storeMode != null;
|
||||||
|
case BillField.IncludeEquipped: return v.setIncludeEquipped;
|
||||||
|
case BillField.IncludeTainted: return v.setIncludeTainted;
|
||||||
|
case BillField.HpRange: return v.setHpRange;
|
||||||
|
case BillField.QualityRange: return v.setQualityRange;
|
||||||
|
default: return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Sets the value, starting from the game's value ("Change" before the player edits it).</summary>
|
||||||
|
public static void Change(BillValues v, BillField f) => Put(v, f, set: true);
|
||||||
|
|
||||||
|
/// <summary>Back to the game's default: the value is unset and holds the game's value again.</summary>
|
||||||
|
public static void Clear(BillValues v, BillField f) => Put(v, f, set: false);
|
||||||
|
|
||||||
|
private static void Put(BillValues v, BillField f, bool set)
|
||||||
|
{
|
||||||
|
switch (f)
|
||||||
|
{
|
||||||
|
case BillField.RepeatMode: v.repeatMode = set ? BillDefaults.RepeatModeNames[0] : null; break;
|
||||||
|
case BillField.RepeatCount: v.setRepeatCount = set; v.repeatCount = Game.repeatCount; break;
|
||||||
|
case BillField.TargetCount: v.setTargetCount = set; v.targetCount = Game.targetCount; break;
|
||||||
|
case BillField.PauseWhenSatisfied: v.setPauseWhenSatisfied = set; v.pauseWhenSatisfied = Game.pauseWhenSatisfied; break;
|
||||||
|
case BillField.UnpauseWhenYouHave: v.setUnpauseWhenYouHave = set; v.unpauseWhenYouHave = Game.unpauseWhenYouHave; break;
|
||||||
|
case BillField.IngredientSearchRadius: v.setIngredientSearchRadius = set; v.ingredientSearchRadius = Game.ingredientSearchRadius; break;
|
||||||
|
case BillField.AllowedSkillRange: v.setAllowedSkillRange = set; v.allowedSkillRange = Game.allowedSkillRange; break;
|
||||||
|
case BillField.StoreMode: v.storeMode = set ? BillDefaults.StoreModeNames[0] : null; break;
|
||||||
|
case BillField.IncludeEquipped: v.setIncludeEquipped = set; v.includeEquipped = Game.includeEquipped; break;
|
||||||
|
case BillField.IncludeTainted: v.setIncludeTainted = set; v.includeTainted = Game.includeTainted; break;
|
||||||
|
case BillField.HpRange: v.setHpRange = set; v.hpRange = Game.hpRange; break;
|
||||||
|
case BillField.QualityRange: v.setQualityRange = set; v.qualityRange = Game.qualityRange; break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Pause when satisfied is set on, but resume at (set or the game's 5) is not below the target, so bills never pause.</summary>
|
||||||
|
public static bool PauseNeverStarts(BillValues v) =>
|
||||||
|
v.setPauseWhenSatisfied && v.pauseWhenSatisfied
|
||||||
|
&& (v.setUnpauseWhenYouHave ? v.unpauseWhenYouHave : Game.unpauseWhenYouHave) >= (v.setTargetCount ? v.targetCount : Game.targetCount);
|
||||||
|
|
||||||
|
// ---- rows -------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The label, the game's value or the editor, and the button that switches between them. Returns the
|
||||||
|
/// editor's rect, or a zero rect when the value follows the game's default. A Change button with
|
||||||
|
/// onChange set calls it instead of setting the value.
|
||||||
|
/// </summary>
|
||||||
|
private static Rect Row(Listing_Standard l, BillValues v, BillField f, float height, Action onChange = null)
|
||||||
|
{
|
||||||
|
Rect row = l.GetRect(height);
|
||||||
|
string tip = TipKey(f);
|
||||||
|
if (tip != null)
|
||||||
|
TooltipHandler.TipRegion(row, tip.Translate());
|
||||||
|
Rect labelRect = row.LeftPart(LabelWidthPct);
|
||||||
|
Rect button = row.RightPartPixels(ButtonWidth);
|
||||||
|
var editor = new Rect(labelRect.xMax + 8f, row.y, button.x - labelRect.xMax - 16f, row.height);
|
||||||
|
|
||||||
|
Text.Anchor = TextAnchor.MiddleLeft;
|
||||||
|
Widgets.Label(labelRect, LabelKey(f).Translate());
|
||||||
|
bool set = IsSet(v, f);
|
||||||
|
if (!set)
|
||||||
|
{
|
||||||
|
GUI.color = Grey;
|
||||||
|
Widgets.Label(editor, "BlaxDefaults_Bills_GameDefault".Translate(GameValueText(f)));
|
||||||
|
GUI.color = Color.white;
|
||||||
|
}
|
||||||
|
Text.Anchor = TextAnchor.UpperLeft;
|
||||||
|
|
||||||
|
if (set)
|
||||||
|
{
|
||||||
|
if (Widgets.ButtonText(button, "BlaxDefaults_Bills_UseGameDefault".Translate()))
|
||||||
|
{
|
||||||
|
Clear(v, f);
|
||||||
|
buffers.Remove(f);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (Widgets.ButtonText(button, "BlaxDefaults_Bills_Change".Translate()))
|
||||||
|
{
|
||||||
|
if (onChange != null)
|
||||||
|
{
|
||||||
|
onChange();
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
Change(v, f);
|
||||||
|
buffers.Remove(f);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
l.Gap(l.verticalSpacing);
|
||||||
|
return IsSet(v, f) ? editor : Rect.zero;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void ModeRow(Listing_Standard l, BillValues v, BillField f)
|
||||||
|
{
|
||||||
|
Rect editor = Row(l, v, f, RowHeight, onChange: () => ModeMenu(f));
|
||||||
|
if (editor.width > 0f && Widgets.ButtonText(editor, ModeLabel(f, f == BillField.RepeatMode ? v.repeatMode : v.storeMode)))
|
||||||
|
ModeMenu(f);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void ModeMenu(BillField f)
|
||||||
|
{
|
||||||
|
var options = new List<FloatMenuOption>();
|
||||||
|
foreach (string name in f == BillField.RepeatMode ? BillDefaults.RepeatModeNames : BillDefaults.StoreModeNames)
|
||||||
|
{
|
||||||
|
string chosen = name;
|
||||||
|
options.Add(new FloatMenuOption(ModeLabel(f, chosen), () => Edit(x =>
|
||||||
|
{
|
||||||
|
if (f == BillField.RepeatMode)
|
||||||
|
x.repeatMode = chosen;
|
||||||
|
else
|
||||||
|
x.storeMode = chosen;
|
||||||
|
})));
|
||||||
|
}
|
||||||
|
Find.WindowStack.Add(new FloatMenu(options));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void CountRow(Listing_Standard l, BillValues v, BillField f, int min)
|
||||||
|
{
|
||||||
|
Rect editor = Row(l, v, f, RowHeight);
|
||||||
|
if (editor.width <= 0f)
|
||||||
|
return;
|
||||||
|
int value = f == BillField.RepeatCount ? v.repeatCount : f == BillField.TargetCount ? v.targetCount : v.unpauseWhenYouHave;
|
||||||
|
buffers.TryGetValue(f, out string buffer);
|
||||||
|
Widgets.IntEntry(editor, ref value, ref buffer);
|
||||||
|
if (value < min)
|
||||||
|
{
|
||||||
|
value = min;
|
||||||
|
buffer = value.ToString();
|
||||||
|
}
|
||||||
|
buffers[f] = buffer;
|
||||||
|
if (f == BillField.RepeatCount)
|
||||||
|
v.repeatCount = value;
|
||||||
|
else if (f == BillField.TargetCount)
|
||||||
|
v.targetCount = value;
|
||||||
|
else
|
||||||
|
v.unpauseWhenYouHave = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void BoolRow(Listing_Standard l, BillValues v, BillField f)
|
||||||
|
{
|
||||||
|
// Change turns the value on: off is already the game's default for all three.
|
||||||
|
Rect editor = Row(l, v, f, RowHeight, onChange: () =>
|
||||||
|
{
|
||||||
|
Change(v, f);
|
||||||
|
SetBool(v, f, true);
|
||||||
|
});
|
||||||
|
if (editor.width <= 0f)
|
||||||
|
return;
|
||||||
|
bool on = GetBool(v, f);
|
||||||
|
Widgets.CheckboxLabeled(editor, OnOff(on), ref on, placeCheckboxNearText: true);
|
||||||
|
SetBool(v, f, on);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void RadiusRow(Listing_Standard l, BillValues v)
|
||||||
|
{
|
||||||
|
Rect editor = Row(l, v, BillField.IngredientSearchRadius, RowHeight);
|
||||||
|
if (editor.width <= 0f)
|
||||||
|
return;
|
||||||
|
Rect slider = editor.LeftPart(0.7f);
|
||||||
|
Rect value = editor.RightPart(0.28f);
|
||||||
|
float shown = Mathf.Min(v.ingredientSearchRadius, RadiusSliderMax);
|
||||||
|
float now = Widgets.HorizontalSlider(slider, shown, RadiusMin, RadiusSliderMax, middleAlignment: true, roundTo: 1f);
|
||||||
|
if (now != shown)
|
||||||
|
v.ingredientSearchRadius = now >= RadiusSliderMax ? RadiusUnlimited : now;
|
||||||
|
Text.Anchor = TextAnchor.MiddleLeft;
|
||||||
|
Widgets.Label(value, RadiusText(v.ingredientSearchRadius));
|
||||||
|
Text.Anchor = TextAnchor.UpperLeft;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void RangeRow(Listing_Standard l, BillValues v, BillField f)
|
||||||
|
{
|
||||||
|
Rect editor = Row(l, v, f, RangeRowHeight);
|
||||||
|
if (editor.width <= 0f)
|
||||||
|
return;
|
||||||
|
switch (f)
|
||||||
|
{
|
||||||
|
case BillField.AllowedSkillRange:
|
||||||
|
Widgets.IntRange(editor, SkillRangeId, ref v.allowedSkillRange, 0, 20);
|
||||||
|
break;
|
||||||
|
case BillField.HpRange:
|
||||||
|
Widgets.FloatRange(editor, HpRangeId, ref v.hpRange, 0f, 1f, null, ToStringStyle.PercentZero);
|
||||||
|
// As the vanilla bill window rounds it.
|
||||||
|
v.hpRange.min = Mathf.Round(v.hpRange.min * 100f) / 100f;
|
||||||
|
v.hpRange.max = Mathf.Round(v.hpRange.max * 100f) / 100f;
|
||||||
|
break;
|
||||||
|
case BillField.QualityRange:
|
||||||
|
Widgets.QualityRange(editor, QualityRangeId, ref v.qualityRange);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void GreyLabel(Listing_Standard l, string text)
|
||||||
|
{
|
||||||
|
GUI.color = Grey;
|
||||||
|
l.Label(text);
|
||||||
|
GUI.color = Color.white;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- texts ------------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
private static string LabelKey(BillField f) => "BlaxDefaults_Bills_" + f;
|
||||||
|
|
||||||
|
private static string TipKey(BillField f)
|
||||||
|
{
|
||||||
|
switch (f)
|
||||||
|
{
|
||||||
|
case BillField.RepeatCount:
|
||||||
|
return "BlaxDefaults_Bills_RepeatCountTip";
|
||||||
|
case BillField.TargetCount:
|
||||||
|
case BillField.PauseWhenSatisfied:
|
||||||
|
case BillField.UnpauseWhenYouHave:
|
||||||
|
case BillField.IncludeEquipped:
|
||||||
|
case BillField.IncludeTainted:
|
||||||
|
case BillField.HpRange:
|
||||||
|
case BillField.QualityRange:
|
||||||
|
return "BlaxDefaults_Bills_TargetOnlyTip";
|
||||||
|
default:
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>What a new bill has when the value follows the game's default.</summary>
|
||||||
|
private static string GameValueText(BillField f)
|
||||||
|
{
|
||||||
|
switch (f)
|
||||||
|
{
|
||||||
|
case BillField.RepeatMode: return ModeLabel(f, BillDefaults.RepeatModeNames[0]);
|
||||||
|
case BillField.RepeatCount: return Game.repeatCount.ToString();
|
||||||
|
case BillField.TargetCount: return Game.targetCount.ToString();
|
||||||
|
case BillField.PauseWhenSatisfied: return OnOff(Game.pauseWhenSatisfied);
|
||||||
|
case BillField.UnpauseWhenYouHave: return Game.unpauseWhenYouHave.ToString();
|
||||||
|
case BillField.IngredientSearchRadius: return RadiusText(Game.ingredientSearchRadius);
|
||||||
|
case BillField.AllowedSkillRange:
|
||||||
|
return "BlaxDefaults_Bills_Range".Translate(Game.allowedSkillRange.min, Game.allowedSkillRange.max);
|
||||||
|
case BillField.StoreMode: return ModeLabel(f, BillDefaults.StoreModeNames[0]);
|
||||||
|
case BillField.IncludeEquipped: return OnOff(Game.includeEquipped);
|
||||||
|
case BillField.IncludeTainted: return OnOff(Game.includeTainted);
|
||||||
|
case BillField.HpRange:
|
||||||
|
return "BlaxDefaults_Bills_Range".Translate(Game.hpRange.min.ToStringPercent(), Game.hpRange.max.ToStringPercent());
|
||||||
|
case BillField.QualityRange: return "BlaxDefaults_Bills_AnyQuality".Translate();
|
||||||
|
default: return "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The vanilla label of a repeat or store mode ("Do until you have X", "Drop on floor"), or the saved name.</summary>
|
||||||
|
private static string ModeLabel(BillField f, string name)
|
||||||
|
{
|
||||||
|
Def def = f == BillField.RepeatMode ? BillDefaults.ResolveRepeatMode(name) : (Def)BillDefaults.ResolveStoreMode(name);
|
||||||
|
return def != null ? def.LabelCap.Resolve() : name;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string RadiusText(float radius) =>
|
||||||
|
radius >= RadiusUnlimited ? "BlaxDefaults_Bills_Unlimited".Translate().Resolve() : radius.ToString("F0");
|
||||||
|
|
||||||
|
private static string OnOff(bool on) => (on ? "BlaxDefaults_Bills_ValueOn" : "BlaxDefaults_Bills_ValueOff").Translate();
|
||||||
|
|
||||||
|
private static bool GetBool(BillValues v, BillField f) =>
|
||||||
|
f == BillField.PauseWhenSatisfied ? v.pauseWhenSatisfied : f == BillField.IncludeEquipped ? v.includeEquipped : v.includeTainted;
|
||||||
|
|
||||||
|
private static void SetBool(BillValues v, BillField f, bool on)
|
||||||
|
{
|
||||||
|
if (f == BillField.PauseWhenSatisfied)
|
||||||
|
v.pauseWhenSatisfied = on;
|
||||||
|
else if (f == BillField.IncludeEquipped)
|
||||||
|
v.includeEquipped = on;
|
||||||
|
else
|
||||||
|
v.includeTainted = on;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,46 @@
|
||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<!-- RimWorld 1.7 runs on .NET 10 (CoreCLR). Build: dotnet build -c Release -->
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
|
<AssemblyName>BlaxDefaults</AssemblyName>
|
||||||
|
<RootNamespace>BlaxDefaults</RootNamespace>
|
||||||
|
<LangVersion>latest</LangVersion>
|
||||||
|
<Nullable>disable</Nullable>
|
||||||
|
<ImplicitUsings>disable</ImplicitUsings>
|
||||||
|
<OutputPath>..\..\1.7\Assemblies\</OutputPath>
|
||||||
|
<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
|
||||||
|
<AppendRuntimeIdentifierToOutputPath>false</AppendRuntimeIdentifierToOutputPath>
|
||||||
|
<GenerateDependencyFile>false</GenerateDependencyFile>
|
||||||
|
<CopyLocalLockFileAssemblies>false</CopyLocalLockFileAssemblies>
|
||||||
|
<DebugType>portable</DebugType>
|
||||||
|
<Deterministic>true</Deterministic>
|
||||||
|
<!-- The SDK appends the git commit to the informational version, so every commit would change the
|
||||||
|
next build and the committed DLL could never match HEAD. Same source, same bytes. -->
|
||||||
|
<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
|
||||||
|
<!-- Keep local paths out of the shipped DLL/PDB. -->
|
||||||
|
<PathMap>$(MSBuildProjectDirectory)=Source/BlaxDefaults</PathMap>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<!-- Override on the command line if the game or the Harmony mod live elsewhere. -->
|
||||||
|
<PropertyGroup>
|
||||||
|
<RimWorldDir Condition="'$(RimWorldDir)' == ''">E:\SteamLibrary\steamapps\common\RimWorld</RimWorldDir>
|
||||||
|
<HarmonyDir Condition="'$(HarmonyDir)' == ''">E:\SteamLibrary\steamapps\workshop\content\294100\2009463077\1.7\Assemblies</HarmonyDir>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<Reference Include="Assembly-CSharp">
|
||||||
|
<HintPath>$(RimWorldDir)\Assembly-CSharp.dll</HintPath>
|
||||||
|
<Private>false</Private>
|
||||||
|
</Reference>
|
||||||
|
<Reference Include="UnityStubs">
|
||||||
|
<HintPath>$(RimWorldDir)\UnityStubs.dll</HintPath>
|
||||||
|
<Private>false</Private>
|
||||||
|
</Reference>
|
||||||
|
<Reference Include="0Harmony">
|
||||||
|
<HintPath>$(HarmonyDir)\0Harmony.dll</HintPath>
|
||||||
|
<Private>false</Private>
|
||||||
|
</Reference>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
|
|
@ -0,0 +1,31 @@
|
||||||
|
using UnityEngine;
|
||||||
|
using Verse;
|
||||||
|
|
||||||
|
namespace BlaxDefaults
|
||||||
|
{
|
||||||
|
public class BlaxDefaultsMod : Mod
|
||||||
|
{
|
||||||
|
public static BlaxDefaultsSettings Settings;
|
||||||
|
|
||||||
|
public BlaxDefaultsMod(ModContentPack content) : base(content)
|
||||||
|
{
|
||||||
|
Settings = GetSettings<BlaxDefaultsSettings>();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The master switch. True before the settings exist.</summary>
|
||||||
|
public static bool Enabled => Settings == null || Settings.enabled;
|
||||||
|
|
||||||
|
/// <summary>New stockpiles start from their type's default.</summary>
|
||||||
|
public static bool StockpilesOn => Enabled && (Settings == null || Settings.stockpileDefaults);
|
||||||
|
|
||||||
|
/// <summary>New storage buildings start from their kind's default.</summary>
|
||||||
|
public static bool StorageOn => Enabled && (Settings == null || Settings.storageDefaults);
|
||||||
|
|
||||||
|
/// <summary>New production bills get the values of "Every new bill".</summary>
|
||||||
|
public static bool BillsOn => Enabled && (Settings == null || Settings.billDefaults);
|
||||||
|
|
||||||
|
public override string SettingsCategory() => "Blax Defaults";
|
||||||
|
|
||||||
|
public override void DoSettingsWindowContents(Rect inRect) => SettingsPage.Draw(inRect);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,51 @@
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using Verse;
|
||||||
|
|
||||||
|
namespace BlaxDefaults
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Mod settings: the toggles and the dismissed overlap warnings only. The defaults themselves live in
|
||||||
|
/// their own file (DefaultsLibrary, DefaultsFile), never here: a mod settings file that fails to load is
|
||||||
|
/// replaced by fresh settings on the next write.
|
||||||
|
/// </summary>
|
||||||
|
public class BlaxDefaultsSettings : ModSettings
|
||||||
|
{
|
||||||
|
/// <summary>Master switch. Off: no hook applies anything; the defaults file is kept.</summary>
|
||||||
|
public bool enabled = true;
|
||||||
|
/// <summary>New stockpiles start from their type's default.</summary>
|
||||||
|
public bool stockpileDefaults = true;
|
||||||
|
/// <summary>New storage buildings start from their kind's default.</summary>
|
||||||
|
public bool storageDefaults = true;
|
||||||
|
/// <summary>New production bills get the values of "Every new bill".</summary>
|
||||||
|
public bool billDefaults = true;
|
||||||
|
/// <summary>The settings page and one message per session name active mods that set the same defaults.</summary>
|
||||||
|
public bool warnOverlaps = true;
|
||||||
|
/// <summary>Package ids whose overlap message the player dismissed with "Don't remind me".</summary>
|
||||||
|
public List<string> dismissedOverlaps = new List<string>();
|
||||||
|
|
||||||
|
public override void ExposeData()
|
||||||
|
{
|
||||||
|
base.ExposeData();
|
||||||
|
Scribe_Values.Look(ref enabled, "enabled", true);
|
||||||
|
Scribe_Values.Look(ref stockpileDefaults, "stockpileDefaults", true);
|
||||||
|
Scribe_Values.Look(ref storageDefaults, "storageDefaults", true);
|
||||||
|
Scribe_Values.Look(ref billDefaults, "billDefaults", true);
|
||||||
|
Scribe_Values.Look(ref warnOverlaps, "warnOverlaps", true);
|
||||||
|
Scribe_Collections.Look(ref dismissedOverlaps, "dismissedOverlaps", LookMode.Value);
|
||||||
|
if (Scribe.mode == LoadSaveMode.PostLoadInit || Scribe.mode == LoadSaveMode.LoadingVars)
|
||||||
|
dismissedOverlaps ??= new List<string>();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Back to the shipped values. Leaves the defaults file alone.</summary>
|
||||||
|
public void Reset()
|
||||||
|
{
|
||||||
|
var d = new BlaxDefaultsSettings();
|
||||||
|
enabled = d.enabled;
|
||||||
|
stockpileDefaults = d.stockpileDefaults;
|
||||||
|
storageDefaults = d.storageDefaults;
|
||||||
|
billDefaults = d.billDefaults;
|
||||||
|
warnOverlaps = d.warnOverlaps;
|
||||||
|
dismissedOverlaps = new List<string>();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,49 @@
|
||||||
|
using System;
|
||||||
|
using HarmonyLib;
|
||||||
|
using Verse;
|
||||||
|
|
||||||
|
namespace BlaxDefaults
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Reads the defaults file and applies the Harmony patches after every Mod class exists and the defs are
|
||||||
|
/// loaded. Patches go one class at a time, so a single broken target can't take the rest down.
|
||||||
|
/// </summary>
|
||||||
|
[StaticConstructorOnStartup]
|
||||||
|
public static class BlaxDefaultsStartup
|
||||||
|
{
|
||||||
|
public const string HarmonyId = "blax.defaults";
|
||||||
|
public static readonly Harmony Harmony = new Harmony(HarmonyId);
|
||||||
|
|
||||||
|
/// <summary>Patch classes applied and failed at startup, for the smoke test.</summary>
|
||||||
|
public static int PatchesApplied, PatchesFailed;
|
||||||
|
|
||||||
|
static BlaxDefaultsStartup()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
DefaultsLibrary.LoadAtStartup();
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
Log.Error("[Blax Defaults] Reading the defaults file failed: " + e);
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (Type type in typeof(BlaxDefaultsStartup).Assembly.GetTypes())
|
||||||
|
{
|
||||||
|
if (!type.IsDefined(typeof(HarmonyPatch), false))
|
||||||
|
continue;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Harmony.CreateClassProcessor(type).Patch();
|
||||||
|
PatchesApplied++;
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
PatchesFailed++;
|
||||||
|
Log.Error("[Blax Defaults] Patch " + type.Name + " failed: " + e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Log.Message("[Blax Defaults] " + PatchesApplied + " patches applied" + (PatchesFailed > 0 ? ", " + PatchesFailed + " failed" : ""));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,28 @@
|
||||||
|
using Verse;
|
||||||
|
|
||||||
|
namespace BlaxDefaults
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Shared mod detection. Defaults has no hard dependency on any other mod. Package ids of the mods
|
||||||
|
/// whose defaults overlap live next to their warning (OverlapWarnings); the ones here are siblings and
|
||||||
|
/// the mods the -Compat run loads, read from the installed copies' About/About.xml on 2026-11-29.
|
||||||
|
/// </summary>
|
||||||
|
public static class Compat
|
||||||
|
{
|
||||||
|
public const string BlaxCastes = "blax.castes";
|
||||||
|
public const string BlaxSlaves = "blax.slaves";
|
||||||
|
public const string BlaxZones = "blax.zones";
|
||||||
|
|
||||||
|
public const string RimFridge = "rimfridge.kv.rw";
|
||||||
|
public const string WeaponRacks = "Aelanna.WeaponRacks";
|
||||||
|
public const string ReplaceStuff = "Memegoddess.ReplaceStuff";
|
||||||
|
public const string Rimefeller = "Dubwise.Rimefeller";
|
||||||
|
public const string VfeSecurity = "VanillaExpanded.VFESecurity";
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Active by packageId, local or Steam copy. ModsConfig.IsActive misses a mod that is installed both
|
||||||
|
/// ways (the Steam copy gets a "_steam" postfix), so nothing in Blax Defaults uses it for mods.
|
||||||
|
/// </summary>
|
||||||
|
public static bool IsActive(string packageId) => ModLister.GetActiveModWithIdentifier(packageId, ignorePostfix: true) != null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,91 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using Verse;
|
||||||
|
|
||||||
|
namespace BlaxDefaults
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// One saved default, keyed by kind (see DefaultsKeys). Stored in the defaults file as strings only:
|
||||||
|
/// defNames, enum names, numbers. Loading never resolves a def, so it can never throw over a missing
|
||||||
|
/// one; names resolve at apply time with GetNamedSilentFail, and a name that doesn't resolve is skipped
|
||||||
|
/// and stays in the file. Changes to the format are additive only.
|
||||||
|
/// </summary>
|
||||||
|
public abstract class DefaultsEntry : IExposable
|
||||||
|
{
|
||||||
|
public string key;
|
||||||
|
|
||||||
|
public virtual void ExposeData()
|
||||||
|
{
|
||||||
|
Scribe_Values.Look(ref key, "key");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A deep copy. The library hands out its live entries; edit a clone, then DefaultsLibrary.Set it.</summary>
|
||||||
|
public abstract DefaultsEntry Clone();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Every value of the entry as one string, key included. The file write compares the read-back
|
||||||
|
/// entries with the library through this, so it must cover every field ExposeData writes.
|
||||||
|
/// </summary>
|
||||||
|
public abstract string Fingerprint();
|
||||||
|
|
||||||
|
/// <summary>Names in this entry that don't resolve now: from an inactive mod or a DLC that is off.</summary>
|
||||||
|
public virtual IEnumerable<string> UnresolvedNames()
|
||||||
|
{
|
||||||
|
yield break;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override string ToString() => GetType().Name + "(" + key + ")";
|
||||||
|
|
||||||
|
protected static string Join(IEnumerable<string> names) => names == null ? "" : string.Join(",", names);
|
||||||
|
|
||||||
|
protected static List<string> CopyList(List<string> list) => list == null ? new List<string>() : new List<string>(list);
|
||||||
|
|
||||||
|
protected static string SortedJoin(List<string> names)
|
||||||
|
{
|
||||||
|
if (names == null)
|
||||||
|
return "";
|
||||||
|
var copy = new List<string>(names);
|
||||||
|
copy.Sort(StringComparer.Ordinal);
|
||||||
|
return string.Join(",", copy);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The library keys. One default per kind: "stockpile:Stockpile", "stockpile:Dumping",
|
||||||
|
/// "stockpile:<designator type name>", "storage:<ThingDef>" and "bill:*" in 1.0. Later releases
|
||||||
|
/// add their own prefixes (bill:<RecipeDef>, bench:, animal:, slaughter:, mech:, grower:, building:).
|
||||||
|
/// </summary>
|
||||||
|
public static class DefaultsKeys
|
||||||
|
{
|
||||||
|
public const string StockpilePrefix = "stockpile:";
|
||||||
|
public const string StoragePrefix = "storage:";
|
||||||
|
public const string BillPrefix = "bill:";
|
||||||
|
|
||||||
|
/// <summary>The vanilla stockpile (DefaultStockpile preset): Designator_ZoneAddStockpile_Resources and _Expand.</summary>
|
||||||
|
public const string Stockpile = "stockpile:Stockpile";
|
||||||
|
/// <summary>The vanilla dumping stockpile: Designator_ZoneAddStockpile_Dumping.</summary>
|
||||||
|
public const string Dumping = "stockpile:Dumping";
|
||||||
|
/// <summary>"Every new bill", the values applied to every new production bill.</summary>
|
||||||
|
public const string EveryBill = "bill:*";
|
||||||
|
|
||||||
|
public static string ForStorage(ThingDef def) => StoragePrefix + def.defName;
|
||||||
|
|
||||||
|
public static string ForStorage(string defName) => StoragePrefix + defName;
|
||||||
|
|
||||||
|
/// <summary>A modded stockpile designator: its own type, keyed by type name.</summary>
|
||||||
|
public static string ForStockpileDesignator(Type designatorType) => StockpilePrefix + designatorType.Name;
|
||||||
|
|
||||||
|
public static bool IsStockpile(string key) => key != null && key.StartsWith(StockpilePrefix, StringComparison.Ordinal);
|
||||||
|
|
||||||
|
public static bool IsStorage(string key) => key != null && key.StartsWith(StoragePrefix, StringComparison.Ordinal);
|
||||||
|
|
||||||
|
public static bool IsBill(string key) => key != null && key.StartsWith(BillPrefix, StringComparison.Ordinal);
|
||||||
|
|
||||||
|
/// <summary>The part after the prefix: "Shelf" for "storage:Shelf".</summary>
|
||||||
|
public static string NameOf(string key)
|
||||||
|
{
|
||||||
|
int i = key?.IndexOf(':') ?? -1;
|
||||||
|
return i < 0 ? key : key.Substring(i + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,613 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Globalization;
|
||||||
|
using System.IO;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
|
using System.Xml;
|
||||||
|
using Verse;
|
||||||
|
|
||||||
|
namespace BlaxDefaults
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// A default in the file whose class this version doesn't have, such as a kind of default a later release
|
||||||
|
/// adds. Kept as the XML of its <li> and written back unchanged.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class UnknownEntry
|
||||||
|
{
|
||||||
|
/// <summary>Its <key>, or null when it has none.</summary>
|
||||||
|
public string Key;
|
||||||
|
/// <summary>Its Class attribute, or null when it has none.</summary>
|
||||||
|
public string ClassName;
|
||||||
|
/// <summary>The <li> node's OuterXml, as read (no whitespace between nodes).</summary>
|
||||||
|
public string Xml;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>What DefaultsFile.Read found in one file that loaded.</summary>
|
||||||
|
public sealed class FileContent
|
||||||
|
{
|
||||||
|
public List<DefaultsEntry> Entries = new List<DefaultsEntry>();
|
||||||
|
public List<UnknownEntry> Unknown = new List<UnknownEntry>();
|
||||||
|
/// <summary>The formatVersion in the root node, 0 when there is none.</summary>
|
||||||
|
public int Version;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The defaults file, Config/BlaxDefaults/Defaults.xml under the game's save data folder, with a .bak.
|
||||||
|
/// Work package "file" (design.md: "Defaults library, a file of names" and the tests of "Defaults library
|
||||||
|
/// and settings page").
|
||||||
|
///
|
||||||
|
/// Write, in this order: Scribe.saver.InitSaving on Defaults.xml.tmp with the library inside a try (on an
|
||||||
|
/// exception ForceStop, delete the .tmp, one error, both files untouched); read the .tmp back and compare
|
||||||
|
/// every entry's Fingerprint with the library (on a mismatch delete the .tmp, one error, both files
|
||||||
|
/// untouched); only then File.Replace(tmp, file, file + ".bak"), or File.Move(tmp, file) when there is no
|
||||||
|
/// main file.
|
||||||
|
///
|
||||||
|
/// Load: main file, then .bak. A file that fails to load is renamed at once to
|
||||||
|
/// Defaults.broken-<yyyyMMdd-HHmmss>.xml (main) or Defaults.bak.broken-<yyyyMMdd-HHmmss>.xml (backup),
|
||||||
|
/// with "-2", "-3" appended when that name exists; the main file is renamed even when the .bak loads.
|
||||||
|
/// Both failed: an empty library and one warning. Renaming is the only file operation at load.
|
||||||
|
/// The root node carries DefaultsLibrary.FormatVersion.
|
||||||
|
///
|
||||||
|
/// Entries of a class this version doesn't have (a later release's new kind of default) don't fail the
|
||||||
|
/// file: Read takes their <li> out before Scribe sees it and keeps its XML as an UnknownEntry, Load warns
|
||||||
|
/// once, and Write puts them back into the .tmp, so a newer version's defaults survive an older one. A
|
||||||
|
/// load that leaves a file unread in place (the Scribe was busy, an exception, a broken file that could
|
||||||
|
/// not be renamed) lists it in LoadResult.Unread; DefaultsLibrary retries the read and moves such a file
|
||||||
|
/// aside before its first write, so the write's rotation into .bak can never drop it.
|
||||||
|
///
|
||||||
|
/// File layout (what Scribe_Collections.Look with LookMode.Deep reads):
|
||||||
|
/// <BlaxDefaults><formatVersion>1</formatVersion><entries><li Class="BlaxDefaults.StorageTemplate">...</li></entries></BlaxDefaults>
|
||||||
|
/// </summary>
|
||||||
|
public static class DefaultsFile
|
||||||
|
{
|
||||||
|
public const string RootNode = "BlaxDefaults";
|
||||||
|
|
||||||
|
private const string VersionNode = "formatVersion";
|
||||||
|
private const string EntriesNode = "entries";
|
||||||
|
private const string LogPrefix = "[Blax Defaults] ";
|
||||||
|
|
||||||
|
public static string FolderPath => Path.Combine(GenFilePaths.ConfigFolderPath, "BlaxDefaults");
|
||||||
|
|
||||||
|
public static string FilePath => Path.Combine(FolderPath, "Defaults.xml");
|
||||||
|
|
||||||
|
public static string BackupPath => FilePath + ".bak";
|
||||||
|
|
||||||
|
public static string TempPath => FilePath + ".tmp";
|
||||||
|
|
||||||
|
// ---- load -------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// <summary>Reads the main file, then the backup, renaming broken files as described above. Never throws.</summary>
|
||||||
|
public static LoadResult Load()
|
||||||
|
{
|
||||||
|
var result = new LoadResult();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
LoadInto(result);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
result.Entries = new List<DefaultsEntry>();
|
||||||
|
result.Unknown = new List<UnknownEntry>();
|
||||||
|
result.LoadedFrom = null;
|
||||||
|
Log.Warning(LogPrefix + "Reading the defaults file failed, so Blax Defaults starts with no defaults for now: " + OneLine(e.Message));
|
||||||
|
}
|
||||||
|
MarkUnread(result);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void LoadInto(LoadResult result)
|
||||||
|
{
|
||||||
|
if (Scribe.mode != LoadSaveMode.Inactive)
|
||||||
|
{
|
||||||
|
// Reading now would break the game's own save or load, and calling the files broken would be wrong.
|
||||||
|
// The file stays as it is; DefaultsLibrary reads it again once the game is done.
|
||||||
|
Log.Warning(LogPrefix + "The defaults file was not read because the game was saving or loading. It is read again when Blax Defaults first needs it.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
DateTime now = DateTime.Now;
|
||||||
|
var problems = new List<string>();
|
||||||
|
|
||||||
|
if (File.Exists(FilePath))
|
||||||
|
{
|
||||||
|
FileContent main = Read(FilePath, out string why);
|
||||||
|
if (main != null)
|
||||||
|
{
|
||||||
|
Loaded(result, main, FilePath);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Renamed even when the .bak loads: the next write must not rotate this file into .bak.
|
||||||
|
problems.Add(SetAside(FilePath, why, now, result));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (File.Exists(BackupPath))
|
||||||
|
{
|
||||||
|
FileContent backup = Read(BackupPath, out string why);
|
||||||
|
if (backup != null)
|
||||||
|
{
|
||||||
|
if (problems.Count > 0)
|
||||||
|
Log.Warning(LogPrefix + problems[0] + " Your defaults were loaded from the backup, " + BackupPath + ".");
|
||||||
|
Loaded(result, backup, BackupPath);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
problems.Add(SetAside(BackupPath, why, now, result));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (problems.Count > 0)
|
||||||
|
{
|
||||||
|
// Every file there was failed: the library starts empty, and nothing is written until the
|
||||||
|
// player saves or forgets a default.
|
||||||
|
result.BothFailed = true;
|
||||||
|
Log.Warning(LogPrefix + string.Join(" ", problems) + " Blax Defaults starts with no defaults and writes nothing until you save or forget a default.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Fills the result from a file that loaded, with one warning for a newer format or entries this version skips.</summary>
|
||||||
|
private static void Loaded(LoadResult result, FileContent content, string path)
|
||||||
|
{
|
||||||
|
result.Entries = content.Entries;
|
||||||
|
result.Unknown = content.Unknown;
|
||||||
|
result.FormatVersion = content.Version;
|
||||||
|
result.LoadedFrom = path;
|
||||||
|
var notes = new List<string>();
|
||||||
|
if (content.Version > DefaultsLibrary.FormatVersion)
|
||||||
|
notes.Add("The defaults file " + path + " was made by a newer version of Blax Defaults (format " + content.Version + ", this version reads format "
|
||||||
|
+ DefaultsLibrary.FormatVersion + "). Your defaults are loaded, but this version does not change the file: defaults you save or forget now work until you quit.");
|
||||||
|
if (content.Unknown.Count > 0)
|
||||||
|
notes.Add(content.Unknown.Count + " " + (content.Unknown.Count == 1 ? "default" : "defaults") + " in " + path
|
||||||
|
+ " come from a newer version of Blax Defaults (" + string.Join(", ", content.Unknown.Select(u => u.ClassName ?? "no class").Distinct())
|
||||||
|
+ "). This version skips them and keeps them in the file.");
|
||||||
|
if (notes.Count > 0)
|
||||||
|
Log.Warning(LogPrefix + string.Join(" ", notes));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The defaults files still in place that no entries came from: both when nothing loaded (the read was
|
||||||
|
/// skipped, failed, or a broken file could not be renamed), the main file when the .bak loaded and the
|
||||||
|
/// main file could not be renamed. Never the .bak next to a main file that loaded: rotating it is normal.
|
||||||
|
/// </summary>
|
||||||
|
private static void MarkUnread(LoadResult result)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
result.Unread.Clear();
|
||||||
|
if (result.LoadedFrom == FilePath)
|
||||||
|
return;
|
||||||
|
if (File.Exists(FilePath))
|
||||||
|
result.Unread.Add(FilePath);
|
||||||
|
if (result.LoadedFrom == null && File.Exists(BackupPath))
|
||||||
|
result.Unread.Add(BackupPath);
|
||||||
|
}
|
||||||
|
catch (Exception)
|
||||||
|
{
|
||||||
|
// File.Exists doesn't throw; this only keeps Load's "never throws".
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Renames a file that failed to load to its broken copy and returns the sentence for the warning.</summary>
|
||||||
|
private static string SetAside(string path, string why, DateTime now, LoadResult result)
|
||||||
|
{
|
||||||
|
string what = path == BackupPath ? "The backup of the defaults file" : "The defaults file";
|
||||||
|
string reason = why.NullOrEmpty() ? "" : " (" + why + ")";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
string copy = BrokenCopyPath(path, now);
|
||||||
|
File.Move(path, copy);
|
||||||
|
result.BrokenCopies.Add(copy);
|
||||||
|
return what + " could not be read" + reason + " and was kept as " + copy + ".";
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
return what + " could not be read" + reason + ", and renaming it failed (" + OneLine(e.Message) + "): " + path + ".";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The free name for a broken copy of this file: Defaults.broken-<stamp>.xml, then -2, -3.</summary>
|
||||||
|
public static string BrokenCopyPath(string path, DateTime now) => AsidePath(path, now, "broken");
|
||||||
|
|
||||||
|
/// <summary>The free name for an unread file moved aside: Defaults.unread-<stamp>.xml, then -2, -3.</summary>
|
||||||
|
public static string UnreadCopyPath(string path, DateTime now) => AsidePath(path, now, "unread");
|
||||||
|
|
||||||
|
private static string AsidePath(string path, DateTime now, string tag)
|
||||||
|
{
|
||||||
|
if (path.NullOrEmpty())
|
||||||
|
return null;
|
||||||
|
string folder = Path.GetDirectoryName(path) ?? "";
|
||||||
|
string name = Path.GetFileName(path);
|
||||||
|
// Defaults.xml -> Defaults, Defaults.xml.bak -> Defaults.bak
|
||||||
|
string stem = name.EndsWith(".bak", StringComparison.OrdinalIgnoreCase)
|
||||||
|
? Path.GetFileNameWithoutExtension(name.Substring(0, name.Length - 4)) + ".bak"
|
||||||
|
: Path.GetFileNameWithoutExtension(name);
|
||||||
|
string stamp = now.ToString("yyyyMMdd-HHmmss", CultureInfo.InvariantCulture);
|
||||||
|
string candidate = Path.Combine(folder, stem + "." + tag + "-" + stamp + ".xml");
|
||||||
|
for (int n = 2; File.Exists(candidate) || Directory.Exists(candidate); n++)
|
||||||
|
candidate = Path.Combine(folder, stem + "." + tag + "-" + stamp + "-" + n.ToString(CultureInfo.InvariantCulture) + ".xml");
|
||||||
|
return candidate;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Moves a defaults file the load left unread to Defaults.unread-<stamp>.xml (Defaults.bak.unread-... for
|
||||||
|
/// the backup) and returns the new path; null with one error when that fails. DefaultsLibrary calls this
|
||||||
|
/// before its first write, so the write's rotation into .bak can't lose a file nobody read.
|
||||||
|
/// </summary>
|
||||||
|
public static string SetAsideUnread(string path)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
string copy = UnreadCopyPath(path, DateTime.Now);
|
||||||
|
File.Move(path, copy);
|
||||||
|
return copy;
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
Log.Error(LogPrefix + "The defaults file " + path + " was not read this session and could not be moved aside (" + OneLine(e.Message)
|
||||||
|
+ "), so it is not overwritten: your change works until you quit.");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- read -------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Reads one file into entries without renaming anything. Null when it fails to load (missing root,
|
||||||
|
/// truncated XML, an entry that doesn't load). Entries of a class this version doesn't have are left
|
||||||
|
/// out; Read returns them too.
|
||||||
|
/// </summary>
|
||||||
|
public static List<DefaultsEntry> ReadFile(string path) => ReadFile(path, out _);
|
||||||
|
|
||||||
|
/// <summary>ReadFile with the reason a file failed, for the load warning and the write error.</summary>
|
||||||
|
public static List<DefaultsEntry> ReadFile(string path, out string problem) => Read(path, out problem)?.Entries;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Reads one file without renaming anything: the entries, the entries of classes this version doesn't
|
||||||
|
/// have (as their XML) and the format version. Null when it fails to load. Used by Load and Write's read-back.
|
||||||
|
/// </summary>
|
||||||
|
public static FileContent Read(string path, out string problem)
|
||||||
|
{
|
||||||
|
problem = null;
|
||||||
|
var content = new FileContent();
|
||||||
|
XmlDocument doc;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (path.NullOrEmpty() || !File.Exists(path))
|
||||||
|
{
|
||||||
|
problem = "the file does not exist";
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (Scribe.mode != LoadSaveMode.Inactive)
|
||||||
|
{
|
||||||
|
problem = "the game was saving or loading";
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
// Parsed here first: Scribe.loader.InitLoading logs an error of its own for XML that isn't well
|
||||||
|
// formed, and a broken file is a case Load handles with one warning.
|
||||||
|
doc = ParseXml(path);
|
||||||
|
if (doc.DocumentElement == null || doc.DocumentElement.Name != RootNode)
|
||||||
|
{
|
||||||
|
problem = "the root node is not <" + RootNode + ">";
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
// An entry whose class this version doesn't have would fail in Scribe with two errors and fail
|
||||||
|
// the whole file (ScribeExtractor.SaveableFromNode falls back to the abstract DefaultsEntry).
|
||||||
|
// Out it goes before Scribe sees it, kept as XML for the next write.
|
||||||
|
content.Unknown = TakeUnknownEntries(doc.DocumentElement[EntriesNode]);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
problem = OneLine(e.Message);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
int version = 0;
|
||||||
|
List<DefaultsEntry> list = null;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// Scribe.loader.InitLoading(path) without reading the file again: the document minus the
|
||||||
|
// unknown entries. InitLoading does exactly this after its checks (Verse/ScribeLoader.cs:36-45).
|
||||||
|
Scribe.loader.curParent = null;
|
||||||
|
Scribe.loader.curPathRelToParent = null;
|
||||||
|
Scribe.loader.curXmlParent = doc.DocumentElement;
|
||||||
|
Scribe.mode = LoadSaveMode.LoadingVars;
|
||||||
|
Scribe_Values.Look(ref version, VersionNode);
|
||||||
|
Scribe_Collections.Look(ref list, EntriesNode, LookMode.Deep);
|
||||||
|
Scribe.loader.FinalizeLoading();
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
StopLoading();
|
||||||
|
problem = OneLine(e.Message);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (list == null)
|
||||||
|
{
|
||||||
|
problem = "it has no <" + EntriesNode + "> node";
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
for (int i = 0; i < list.Count; i++)
|
||||||
|
{
|
||||||
|
if (list[i] == null)
|
||||||
|
{
|
||||||
|
problem = "entry " + (i + 1) + " did not load";
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (list[i].key.NullOrEmpty())
|
||||||
|
{
|
||||||
|
problem = "entry " + (i + 1) + " has no key";
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
content.Entries = list;
|
||||||
|
content.Version = version;
|
||||||
|
return content;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static XmlDocument ParseXml(string path)
|
||||||
|
{
|
||||||
|
var doc = new XmlDocument();
|
||||||
|
using (var input = new StreamReader(path))
|
||||||
|
using (var reader = new XmlTextReader(input))
|
||||||
|
doc.Load(reader);
|
||||||
|
return doc;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Removes every <li> of the entries node whose Class this version can't load (no DefaultsEntry
|
||||||
|
/// subclass of that name, or no Class at all) and returns them in file order.
|
||||||
|
/// </summary>
|
||||||
|
private static List<UnknownEntry> TakeUnknownEntries(XmlElement entriesNode)
|
||||||
|
{
|
||||||
|
var unknown = new List<UnknownEntry>();
|
||||||
|
if (entriesNode == null)
|
||||||
|
return unknown;
|
||||||
|
var items = new List<XmlElement>();
|
||||||
|
foreach (XmlNode n in entriesNode.ChildNodes)
|
||||||
|
{
|
||||||
|
if (n is XmlElement e && e.Name == "li")
|
||||||
|
items.Add(e);
|
||||||
|
}
|
||||||
|
foreach (XmlElement li in items)
|
||||||
|
{
|
||||||
|
if (string.Equals(li.GetAttribute("IsNull"), "true", StringComparison.OrdinalIgnoreCase))
|
||||||
|
continue;
|
||||||
|
string className = li.HasAttribute("Class") ? li.GetAttribute("Class") : null;
|
||||||
|
if (IsEntryClass(className))
|
||||||
|
continue;
|
||||||
|
unknown.Add(new UnknownEntry { Key = li["key"]?.InnerText, ClassName = className, Xml = li.OuterXml });
|
||||||
|
entriesNode.RemoveChild(li);
|
||||||
|
}
|
||||||
|
return unknown;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>True when Scribe can make an entry of this class: a DefaultsEntry subclass that isn't abstract.</summary>
|
||||||
|
public static bool IsEntryClass(string className)
|
||||||
|
{
|
||||||
|
if (className.NullOrEmpty())
|
||||||
|
return false;
|
||||||
|
Type t = GenTypes.GetTypeInAnyAssembly(className);
|
||||||
|
return t != null && typeof(DefaultsEntry).IsAssignableFrom(t) && !t.IsAbstract;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- write ------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Writes these entries (DefaultsLibrary.All) through .tmp, read-back and File.Replace. Returns false
|
||||||
|
/// and leaves both files untouched when anything fails, with one error in the log. Never throws.
|
||||||
|
/// </summary>
|
||||||
|
public static bool Write(IReadOnlyList<DefaultsEntry> entries) => Write(entries, null);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Write with the entries of a newer version this version skipped at load (DefaultsLibrary.UnknownEntries):
|
||||||
|
/// they go into the .tmp after the library's entries, exactly as they were read, and are checked in the
|
||||||
|
/// read-back too.
|
||||||
|
/// </summary>
|
||||||
|
public static bool Write(IReadOnlyList<DefaultsEntry> entries, IReadOnlyList<UnknownEntry> unknown)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
entries ??= Array.Empty<DefaultsEntry>();
|
||||||
|
unknown ??= Array.Empty<UnknownEntry>();
|
||||||
|
if (Scribe.mode != LoadSaveMode.Inactive)
|
||||||
|
{
|
||||||
|
// InitSaving would force-stop the game's own save or load.
|
||||||
|
Log.Error(LogPrefix + "The defaults file was not written because the game was saving or loading. The previous file is kept.");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
Directory.CreateDirectory(FolderPath);
|
||||||
|
|
||||||
|
// 1. The library into the .tmp.
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Scribe.saver.InitSaving(TempPath, RootNode);
|
||||||
|
int version = DefaultsLibrary.FormatVersion;
|
||||||
|
Scribe_Values.Look(ref version, VersionNode, 0, forceSave: true);
|
||||||
|
SaveEntries(entries);
|
||||||
|
Scribe.saver.FinalizeSaving();
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
StopSaving();
|
||||||
|
DeleteTemp();
|
||||||
|
Log.Error(LogPrefix + "Writing the defaults file failed, so the previous file is kept: " + e);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1b. The entries of a newer version, back in as they were read.
|
||||||
|
if (unknown.Count > 0)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
AppendUnknown(TempPath, unknown);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
DeleteTemp();
|
||||||
|
Log.Error(LogPrefix + "Writing the defaults of a newer version back into the defaults file failed, so the previous file is kept: " + e);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. The .tmp read back and compared with the library.
|
||||||
|
string mismatch = CompareReadBack(entries, unknown);
|
||||||
|
if (mismatch != null)
|
||||||
|
{
|
||||||
|
DeleteTemp();
|
||||||
|
Log.Error(LogPrefix + "The new defaults file did not read back as written (" + mismatch + "), so the previous file is kept.");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. Only now the swap. The previous main file becomes the .bak.
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (File.Exists(FilePath))
|
||||||
|
File.Replace(TempPath, FilePath, BackupPath, ignoreMetadataErrors: true);
|
||||||
|
else
|
||||||
|
File.Move(TempPath, FilePath);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
DeleteTemp();
|
||||||
|
Log.Error(LogPrefix + "Replacing the defaults file failed, so the previous file is kept: " + e);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
// Only reached outside the three steps (the folder could not be made, for one), so the Scribe
|
||||||
|
// is not ours to stop here.
|
||||||
|
DeleteTemp();
|
||||||
|
Log.Error(LogPrefix + "Writing the defaults file failed, so the previous file is kept: " + e);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The entries as Scribe_Collections.Look(LookMode.Deep) writes them, one <li Class="..."> each, but
|
||||||
|
/// without Scribe_Deep's catch: Scribe_Deep logs an exception from an entry's ExposeData and carries on
|
||||||
|
/// (Verse/Scribe_Deep.cs:61-63), which would log a second error and leave a well-formed file without
|
||||||
|
/// the entry. Here the exception ends the write with the one error Write logs.
|
||||||
|
/// </summary>
|
||||||
|
private static void SaveEntries(IReadOnlyList<DefaultsEntry> entries)
|
||||||
|
{
|
||||||
|
if (!Scribe.EnterNode(EntriesNode))
|
||||||
|
throw new InvalidOperationException("could not open the <" + EntriesNode + "> node");
|
||||||
|
for (int i = 0; i < entries.Count; i++)
|
||||||
|
{
|
||||||
|
DefaultsEntry entry = entries[i];
|
||||||
|
if (entry == null)
|
||||||
|
throw new InvalidOperationException("entry " + (i + 1) + " is null");
|
||||||
|
if (!Scribe.EnterNode("li"))
|
||||||
|
throw new InvalidOperationException("could not open the node of " + entry);
|
||||||
|
Scribe.saver.WriteAttribute("Class", GenTypes.GetTypeNameWithoutIgnoredNamespaces(entry.GetType()));
|
||||||
|
entry.ExposeData();
|
||||||
|
Scribe.ExitNode();
|
||||||
|
}
|
||||||
|
Scribe.ExitNode();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Adds the unknown entries' <li> nodes to the entries node of the file, indented as Scribe writes.</summary>
|
||||||
|
private static void AppendUnknown(string path, IReadOnlyList<UnknownEntry> unknown)
|
||||||
|
{
|
||||||
|
XmlDocument doc = ParseXml(path);
|
||||||
|
XmlElement list = doc.DocumentElement?[EntriesNode] ?? throw new InvalidOperationException("the new file has no <" + EntriesNode + "> node");
|
||||||
|
foreach (UnknownEntry u in unknown)
|
||||||
|
{
|
||||||
|
XmlDocumentFragment fragment = doc.CreateDocumentFragment();
|
||||||
|
fragment.InnerXml = u.Xml;
|
||||||
|
list.AppendChild(fragment);
|
||||||
|
}
|
||||||
|
var settings = new XmlWriterSettings { Indent = true, IndentChars = "\t" };
|
||||||
|
using (XmlWriter writer = XmlWriter.Create(path, settings))
|
||||||
|
doc.Save(writer);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Null when the .tmp holds exactly these entries and unknown entries, in this order; otherwise what differs.</summary>
|
||||||
|
private static string CompareReadBack(IReadOnlyList<DefaultsEntry> entries, IReadOnlyList<UnknownEntry> unknown)
|
||||||
|
{
|
||||||
|
FileContent content = Read(TempPath, out string problem);
|
||||||
|
if (content == null)
|
||||||
|
return "it could not be read: " + problem;
|
||||||
|
if (content.Unknown.Count != unknown.Count)
|
||||||
|
return "it holds " + content.Unknown.Count + " defaults of a newer version instead of " + unknown.Count;
|
||||||
|
for (int i = 0; i < unknown.Count; i++)
|
||||||
|
{
|
||||||
|
if (!string.Equals(unknown[i].Xml, content.Unknown[i].Xml, StringComparison.Ordinal))
|
||||||
|
return "the default " + unknown[i].Key + " of a newer version reads back changed";
|
||||||
|
}
|
||||||
|
List<DefaultsEntry> back = content.Entries;
|
||||||
|
if (back.Count != entries.Count)
|
||||||
|
return "it holds " + back.Count + " entries instead of " + entries.Count;
|
||||||
|
for (int i = 0; i < entries.Count; i++)
|
||||||
|
{
|
||||||
|
string expected, actual;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
expected = entries[i].Fingerprint();
|
||||||
|
actual = back[i].Fingerprint();
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
return "comparing " + entries[i] + " failed: " + OneLine(e.Message);
|
||||||
|
}
|
||||||
|
if (!string.Equals(expected, actual, StringComparison.Ordinal))
|
||||||
|
return entries[i] + " reads back with other values";
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- helpers ----------------------------------------------------------------------
|
||||||
|
|
||||||
|
private static void StopSaving()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Scribe.saver.ForceStop();
|
||||||
|
}
|
||||||
|
catch (Exception)
|
||||||
|
{
|
||||||
|
// ForceStop closes the writer first; if that throws, at least give the game its Scribe back.
|
||||||
|
}
|
||||||
|
if (Scribe.mode == LoadSaveMode.Saving)
|
||||||
|
Scribe.mode = LoadSaveMode.Inactive;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void StopLoading()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Scribe.loader.ForceStop();
|
||||||
|
}
|
||||||
|
catch (Exception)
|
||||||
|
{
|
||||||
|
// Nothing more to undo.
|
||||||
|
}
|
||||||
|
if (Scribe.mode == LoadSaveMode.LoadingVars || Scribe.mode == LoadSaveMode.ResolvingCrossRefs || Scribe.mode == LoadSaveMode.PostLoadInit)
|
||||||
|
Scribe.mode = LoadSaveMode.Inactive;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void DeleteTemp()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (File.Exists(TempPath))
|
||||||
|
File.Delete(TempPath);
|
||||||
|
}
|
||||||
|
catch (Exception)
|
||||||
|
{
|
||||||
|
// A .tmp left behind is harmless: the next write truncates it, and loading never reads it.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string OneLine(string text)
|
||||||
|
{
|
||||||
|
if (text == null)
|
||||||
|
return "";
|
||||||
|
var sb = new StringBuilder(text.Length);
|
||||||
|
foreach (char c in text)
|
||||||
|
sb.Append(c == '\r' || c == '\n' ? ' ' : c);
|
||||||
|
return sb.ToString().Trim();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,307 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.IO;
|
||||||
|
using System.Linq;
|
||||||
|
using Verse;
|
||||||
|
|
||||||
|
namespace BlaxDefaults
|
||||||
|
{
|
||||||
|
/// <summary>What DefaultsFile.Load found.</summary>
|
||||||
|
public sealed class LoadResult
|
||||||
|
{
|
||||||
|
public List<DefaultsEntry> Entries = new List<DefaultsEntry>();
|
||||||
|
/// <summary>The file the entries came from (main or .bak), null when none loaded.</summary>
|
||||||
|
public string LoadedFrom;
|
||||||
|
/// <summary>Full paths of the broken copies made by this load (Defaults.broken-<timestamp>.xml and the like).</summary>
|
||||||
|
public List<string> BrokenCopies = new List<string>();
|
||||||
|
/// <summary>No file loaded and every file that existed failed (each was renamed to a broken copy): the library starts empty.</summary>
|
||||||
|
public bool BothFailed;
|
||||||
|
/// <summary>Entries of the loaded file whose class this version doesn't have; written back on every write.</summary>
|
||||||
|
public List<UnknownEntry> Unknown = new List<UnknownEntry>();
|
||||||
|
/// <summary>The loaded file's formatVersion; 0 when nothing loaded.</summary>
|
||||||
|
public int FormatVersion;
|
||||||
|
/// <summary>
|
||||||
|
/// Defaults files still in place that nothing was read from: the read was skipped (the game was saving or
|
||||||
|
/// loading), failed with an exception, or a broken file could not be renamed. DefaultsLibrary reads
|
||||||
|
/// again once and moves what is still unread aside before its first write.
|
||||||
|
/// </summary>
|
||||||
|
public List<string> Unread = new List<string>();
|
||||||
|
/// <summary>Where DefaultsLibrary moved the unread files before its first write (Defaults.unread-<timestamp>.xml).</summary>
|
||||||
|
public List<string> UnreadCopies = new List<string>();
|
||||||
|
|
||||||
|
/// <summary>The file came from a newer version of Blax Defaults: this version reads it but never writes it.</summary>
|
||||||
|
public bool FromNewerVersion => FormatVersion > DefaultsLibrary.FormatVersion;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The defaults in memory, one entry per kind, global and shared by every save. Read once at startup from
|
||||||
|
/// DefaultsFile; every Set or Forget writes the whole file through DefaultsFile.Write. Get returns the
|
||||||
|
/// live entry: never edit it in place, edit a Clone() and Set that. Nothing here touches a save.
|
||||||
|
///
|
||||||
|
/// Two guards keep the file safe when the startup load could not use it. A file left unread in place
|
||||||
|
/// (LoadResult.Unread: the game was saving or loading, an exception, a broken file that could not be
|
||||||
|
/// renamed) is read again once, on the first use with the Scribe free; whatever is still unread then is
|
||||||
|
/// moved aside (Defaults.unread-<timestamp>.xml) before the first write, so the write's rotation into
|
||||||
|
/// .bak can't drop it. A file of a newer format version is read but never written, since this version
|
||||||
|
/// would drop the fields that version added.
|
||||||
|
/// </summary>
|
||||||
|
public static class DefaultsLibrary
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// The defaults file format. Bump it whenever a release adds a kind of entry (a DefaultsEntry subclass)
|
||||||
|
/// or a field to one: an older version then reads the file, keeps the entries it can't load, and never
|
||||||
|
/// writes the file, so it can't drop what the newer version saved.
|
||||||
|
/// </summary>
|
||||||
|
public const int FormatVersion = 1;
|
||||||
|
|
||||||
|
private static readonly Dictionary<string, DefaultsEntry> entries = new Dictionary<string, DefaultsEntry>(StringComparer.Ordinal);
|
||||||
|
|
||||||
|
/// <summary>The startup load left a file unread in place: read it again on the next use.</summary>
|
||||||
|
private static bool retryPending;
|
||||||
|
|
||||||
|
private static bool warnedNewer;
|
||||||
|
|
||||||
|
/// <summary>Raised after an entry is set or forgotten (not after a test restore).</summary>
|
||||||
|
public static event Action Changed;
|
||||||
|
|
||||||
|
/// <summary>True once the startup load ran, whatever it found.</summary>
|
||||||
|
public static bool LoadedAtStartup { get; private set; }
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The last load's result (the startup load, or its retry): broken and unread copies, whether both files
|
||||||
|
/// failed, the entries of a newer version (for the settings page and the next write).
|
||||||
|
/// </summary>
|
||||||
|
public static LoadResult LastLoad { get; private set; } = new LoadResult();
|
||||||
|
|
||||||
|
/// <summary>False when the last write failed or was refused; the file then still holds the previous content.</summary>
|
||||||
|
public static bool LastWriteOk { get; private set; } = true;
|
||||||
|
|
||||||
|
/// <summary>True while the read the startup load skipped is still to be retried.</summary>
|
||||||
|
public static bool RetryPending => retryPending;
|
||||||
|
|
||||||
|
/// <summary>The loaded file came from a newer version: Set and Forget work in memory, the file is never written.</summary>
|
||||||
|
public static bool ReadOnly => LastLoad.FromNewerVersion;
|
||||||
|
|
||||||
|
/// <summary>Every entry, ordered by key.</summary>
|
||||||
|
public static List<DefaultsEntry> All
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
EnsureLoaded();
|
||||||
|
return entries.Values.OrderBy(e => e.key, StringComparer.Ordinal).ToList();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static int Count
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
EnsureLoaded();
|
||||||
|
return entries.Count;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static bool Has(string key)
|
||||||
|
{
|
||||||
|
EnsureLoaded();
|
||||||
|
return key != null && entries.ContainsKey(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static DefaultsEntry Get(string key)
|
||||||
|
{
|
||||||
|
EnsureLoaded();
|
||||||
|
return key != null && entries.TryGetValue(key, out DefaultsEntry e) ? e : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static T Get<T>(string key) where T : DefaultsEntry => Get(key) as T;
|
||||||
|
|
||||||
|
/// <summary>Entries whose key starts with this prefix, ordered by key.</summary>
|
||||||
|
public static List<DefaultsEntry> WithPrefix(string prefix)
|
||||||
|
{
|
||||||
|
EnsureLoaded();
|
||||||
|
return entries.Values.Where(e => e.key.StartsWith(prefix, StringComparison.Ordinal)).OrderBy(e => e.key, StringComparer.Ordinal).ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Adds or replaces the entry with its key and writes the file. Returns whether the write succeeded.</summary>
|
||||||
|
public static bool Set(DefaultsEntry entry)
|
||||||
|
{
|
||||||
|
if (entry == null || entry.key.NullOrEmpty())
|
||||||
|
throw new ArgumentException("A defaults entry needs a key.");
|
||||||
|
EnsureLoaded();
|
||||||
|
entries[entry.key] = entry;
|
||||||
|
return WriteAndNotify();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Adds or replaces several entries and writes the file once. Returns whether the write succeeded.</summary>
|
||||||
|
public static bool SetMany(IEnumerable<DefaultsEntry> batch)
|
||||||
|
{
|
||||||
|
List<DefaultsEntry> list = batch?.ToList() ?? new List<DefaultsEntry>();
|
||||||
|
if (list.Any(e => e == null || e.key.NullOrEmpty()))
|
||||||
|
throw new ArgumentException("A defaults entry needs a key.");
|
||||||
|
EnsureLoaded();
|
||||||
|
foreach (DefaultsEntry e in list)
|
||||||
|
entries[e.key] = e;
|
||||||
|
return WriteAndNotify();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Removes the entry and writes the file. False when there was no such entry.</summary>
|
||||||
|
public static bool Forget(string key)
|
||||||
|
{
|
||||||
|
EnsureLoaded();
|
||||||
|
if (key == null || !entries.Remove(key))
|
||||||
|
return false;
|
||||||
|
WriteAndNotify();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Reads the file into memory. Called once from BlaxDefaultsStartup; writes nothing.</summary>
|
||||||
|
public static void LoadAtStartup()
|
||||||
|
{
|
||||||
|
Install(DefaultsFile.Load() ?? new LoadResult(), retry: true);
|
||||||
|
LoadedAtStartup = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Clones of every entry, for a test to restore later.</summary>
|
||||||
|
public static List<DefaultsEntry> Snapshot()
|
||||||
|
{
|
||||||
|
EnsureLoaded();
|
||||||
|
return entries.Values.Select(e => e.Clone()).ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Puts a snapshot back in memory without writing the file. Tests only.</summary>
|
||||||
|
public static void RestoreForTests(List<DefaultsEntry> snapshot) => Replace(snapshot);
|
||||||
|
|
||||||
|
/// <summary>Replaces the whole library in memory without writing the file. For DefaultsFile tests that reload.</summary>
|
||||||
|
public static void ReplaceInMemory(IEnumerable<DefaultsEntry> loaded) => Replace(loaded);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Tests only: puts a load result in place as the startup load does (its entries in memory, LastLoad,
|
||||||
|
/// and with retry a pending read of its unread files), without touching the files.
|
||||||
|
/// </summary>
|
||||||
|
public static void InstallLoadForTests(LoadResult result, bool retry)
|
||||||
|
{
|
||||||
|
Install(result ?? new LoadResult(), retry);
|
||||||
|
warnedNewer = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void Install(LoadResult r, bool retry)
|
||||||
|
{
|
||||||
|
LastLoad = r;
|
||||||
|
Replace(r.Entries);
|
||||||
|
retryPending = retry && r.LoadedFrom == null && r.Unread.Count > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The retry of a startup read that left a file unread: once, on the first use with the Scribe free.
|
||||||
|
/// Entries set meanwhile (in memory only: a write needs the Scribe free too) win over the file's.
|
||||||
|
/// </summary>
|
||||||
|
private static void EnsureLoaded()
|
||||||
|
{
|
||||||
|
if (!retryPending || Scribe.mode != LoadSaveMode.Inactive)
|
||||||
|
return;
|
||||||
|
retryPending = false;
|
||||||
|
List<DefaultsEntry> meanwhile = entries.Values.ToList();
|
||||||
|
LoadResult r;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
r = DefaultsFile.Load() ?? new LoadResult();
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
Log.Error("[Blax Defaults] Reading the defaults file again failed: " + e);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Install(r, retry: false);
|
||||||
|
foreach (DefaultsEntry e in meanwhile)
|
||||||
|
entries[e.key] = e;
|
||||||
|
if (r.LoadedFrom != null)
|
||||||
|
Log.Message("[Blax Defaults] The defaults file was read on a second try: " + r.Entries.Count + " defaults from " + r.LoadedFrom + ".");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void Replace(IEnumerable<DefaultsEntry> loaded)
|
||||||
|
{
|
||||||
|
entries.Clear();
|
||||||
|
if (loaded == null)
|
||||||
|
return;
|
||||||
|
foreach (DefaultsEntry e in loaded)
|
||||||
|
{
|
||||||
|
if (e != null && !e.key.NullOrEmpty())
|
||||||
|
entries[e.key] = e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool WriteAndNotify()
|
||||||
|
{
|
||||||
|
bool ok;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
ok = Write();
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
Log.Error("[Blax Defaults] Writing the defaults file failed: " + e);
|
||||||
|
ok = false;
|
||||||
|
}
|
||||||
|
LastWriteOk = ok;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Changed?.Invoke();
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
Log.Error("[Blax Defaults] A listener of DefaultsLibrary.Changed failed: " + e);
|
||||||
|
}
|
||||||
|
return ok;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The file write behind both guards: refused for a newer version's file; unread files moved aside
|
||||||
|
/// first; the entries of a newer version written back, except those whose key the library has now.
|
||||||
|
/// </summary>
|
||||||
|
private static bool Write()
|
||||||
|
{
|
||||||
|
if (ReadOnly)
|
||||||
|
{
|
||||||
|
if (!warnedNewer)
|
||||||
|
{
|
||||||
|
warnedNewer = true;
|
||||||
|
Log.Warning("[Blax Defaults] The defaults file was made by a newer version of Blax Defaults (format " + LastLoad.FormatVersion
|
||||||
|
+ "), so this version does not write it. Your change works until you quit.");
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (!SetAsideUnread())
|
||||||
|
return false;
|
||||||
|
List<DefaultsEntry> all = All;
|
||||||
|
var keys = new HashSet<string>(all.Select(e => e.key), StringComparer.Ordinal);
|
||||||
|
List<UnknownEntry> unknown = LastLoad.Unknown.Where(u => u.Key == null || !keys.Contains(u.Key)).ToList();
|
||||||
|
return DefaultsFile.Write(all, unknown);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Moves every file the load left unread aside before the first write. False when one could not be
|
||||||
|
/// moved (one error): then nothing is written, so that file is never rotated away.
|
||||||
|
/// </summary>
|
||||||
|
private static bool SetAsideUnread()
|
||||||
|
{
|
||||||
|
List<string> unread = LastLoad.Unread;
|
||||||
|
if (unread.Count == 0)
|
||||||
|
return true;
|
||||||
|
// DefaultsFile.Write refuses while the game saves or loads; the files move on the write that happens.
|
||||||
|
if (Scribe.mode != LoadSaveMode.Inactive)
|
||||||
|
return true;
|
||||||
|
foreach (string path in unread.ToList())
|
||||||
|
{
|
||||||
|
if (File.Exists(path))
|
||||||
|
{
|
||||||
|
string copy = DefaultsFile.SetAsideUnread(path);
|
||||||
|
if (copy == null)
|
||||||
|
return false;
|
||||||
|
LastLoad.UnreadCopies.Add(copy);
|
||||||
|
}
|
||||||
|
unread.Remove(path);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,276 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Reflection;
|
||||||
|
using System.Reflection.Emit;
|
||||||
|
using HarmonyLib;
|
||||||
|
using RimWorld;
|
||||||
|
using UnityEngine;
|
||||||
|
using Verse;
|
||||||
|
|
||||||
|
namespace BlaxDefaults
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Edit window for one storage default. Work package "page" (design.md: "Defaults library and settings
|
||||||
|
/// page", how). Draws ThingFilterUI.DoThingFilterConfigWindow on a scratch StorageSettings built from the
|
||||||
|
/// game's default with the template on top (kind.LoadDefault), with the kind's parent filter; a priority
|
||||||
|
/// dropdown at the top; under the filter a dropdown for the unlisted rule (UnlistedRule.Label). Save
|
||||||
|
/// captures the scratch (kind.Capture), keeps the window's unlisted rule and any names of the original
|
||||||
|
/// template that don't resolve now (so nothing from an inactive mod is lost), and stores it with
|
||||||
|
/// DefaultsLibrary.Set. Needs defs only, not a running game: the places where the vanilla filter reads
|
||||||
|
/// the game are bridged by Patch_Listing_TreeThingFilter_MainMenu below.
|
||||||
|
/// </summary>
|
||||||
|
public class Dialog_EditStorageTemplate : Window
|
||||||
|
{
|
||||||
|
public readonly StorageKind Kind;
|
||||||
|
/// <summary>The settings the window edits: the kind's game default with the template on top, built in the constructor.</summary>
|
||||||
|
public StorageSettings Scratch;
|
||||||
|
public UnlistedRule Unlisted;
|
||||||
|
/// <summary>A copy of the template the window was opened with, or null for a new default.</summary>
|
||||||
|
public readonly StorageTemplate Original;
|
||||||
|
|
||||||
|
private readonly ThingFilterUI.UIState filterState = new ThingFilterUI.UIState();
|
||||||
|
|
||||||
|
private const float TitleHeight = 36f;
|
||||||
|
private const float RowHeight = 30f;
|
||||||
|
private const float Gap = 8f;
|
||||||
|
|
||||||
|
public Dialog_EditStorageTemplate(StorageKind kind, StorageTemplate template)
|
||||||
|
{
|
||||||
|
Kind = kind ?? throw new ArgumentNullException(nameof(kind));
|
||||||
|
Original = template?.CloneTemplate();
|
||||||
|
Scratch = new StorageSettings();
|
||||||
|
kind.LoadDefault(Scratch, template);
|
||||||
|
Unlisted = template?.unlisted ?? UnlistedRule.Game;
|
||||||
|
doCloseX = true;
|
||||||
|
forcePause = true;
|
||||||
|
absorbInputAroundWindow = true;
|
||||||
|
// Enter in the filter's search box must not close the window without saving.
|
||||||
|
closeOnAccept = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override Vector2 InitialSize => new Vector2(420f, 640f);
|
||||||
|
|
||||||
|
public override void DoWindowContents(Rect inRect)
|
||||||
|
{
|
||||||
|
Text.Font = GameFont.Medium;
|
||||||
|
Widgets.Label(new Rect(0f, 0f, inRect.width - 30f, TitleHeight), "BlaxDefaults_PageEditTitle".Translate(Kind.LabelPlural));
|
||||||
|
Text.Font = GameFont.Small;
|
||||||
|
|
||||||
|
float y = TitleHeight + 4f;
|
||||||
|
var priorityRect = new Rect(0f, y, Mathf.Min(220f, inRect.width), RowHeight);
|
||||||
|
if (Widgets.ButtonText(priorityRect, "BlaxDefaults_PagePriority".Translate(Scratch.Priority.Label().CapitalizeFirst())))
|
||||||
|
Find.WindowStack.Add(new FloatMenu(PriorityOptions()));
|
||||||
|
y += RowHeight + Gap;
|
||||||
|
|
||||||
|
float bottomHeight = RowHeight + Gap + RowHeight;
|
||||||
|
var filterRect = new Rect(0f, y, inRect.width, inRect.height - y - Gap - bottomHeight);
|
||||||
|
if (Current.Game == null && !MainMenuFilterGuard.Ready)
|
||||||
|
{
|
||||||
|
Widgets.DrawMenuSection(filterRect);
|
||||||
|
using (new TextBlock(Color.gray))
|
||||||
|
Widgets.Label(filterRect.ContractedBy(10f), "BlaxDefaults_PageFilterNeedsGame".Translate());
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
ThingFilterUI.DoThingFilterConfigWindow(filterRect, filterState, Scratch.filter, Kind.ParentFilter, TreeOpenMasks.Storage,
|
||||||
|
null, HiddenSpecialFilters(), map: Find.CurrentMap);
|
||||||
|
}
|
||||||
|
y = filterRect.yMax + Gap;
|
||||||
|
|
||||||
|
var unlistedRect = new Rect(0f, y, inRect.width, RowHeight);
|
||||||
|
if (Widgets.ButtonText(unlistedRect, "BlaxDefaults_PageUnlisted".Translate(Unlisted.Label())))
|
||||||
|
Find.WindowStack.Add(new FloatMenu(UnlistedOptions()));
|
||||||
|
TooltipHandler.TipRegion(unlistedRect, "BlaxDefaults_PageUnlistedTip".Translate(Kind.LabelPlural).Resolve());
|
||||||
|
y += RowHeight + Gap;
|
||||||
|
|
||||||
|
float half = (inRect.width - Gap) / 2f;
|
||||||
|
if (Widgets.ButtonText(new Rect(0f, y, half, RowHeight), "BlaxDefaults_PageSave".Translate()))
|
||||||
|
Save();
|
||||||
|
if (Widgets.ButtonText(new Rect(half + Gap, y, half, RowHeight), "BlaxDefaults_PageCancel".Translate()))
|
||||||
|
Close();
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<FloatMenuOption> PriorityOptions()
|
||||||
|
{
|
||||||
|
var list = new List<FloatMenuOption>();
|
||||||
|
foreach (StoragePriority p in Enum.GetValues(typeof(StoragePriority)))
|
||||||
|
{
|
||||||
|
if (p == StoragePriority.Unstored)
|
||||||
|
continue;
|
||||||
|
StoragePriority local = p;
|
||||||
|
list.Add(new FloatMenuOption(local.Label().CapitalizeFirst(), () => Scratch.Priority = local));
|
||||||
|
}
|
||||||
|
return list;
|
||||||
|
}
|
||||||
|
|
||||||
|
private List<FloatMenuOption> UnlistedOptions()
|
||||||
|
{
|
||||||
|
var list = new List<FloatMenuOption>();
|
||||||
|
foreach (UnlistedRule r in Enum.GetValues(typeof(UnlistedRule)))
|
||||||
|
{
|
||||||
|
UnlistedRule local = r;
|
||||||
|
list.Add(new FloatMenuOption(local.Label().CapitalizeFirst(), () => Unlisted = local));
|
||||||
|
}
|
||||||
|
return list;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The special filters the vanilla storage tab hides (ITab_Storage.HiddenSpecialThingFilters).</summary>
|
||||||
|
private static IEnumerable<SpecialThingFilterDef> HiddenSpecialFilters()
|
||||||
|
{
|
||||||
|
if (!ModsConfig.IdeologyActive)
|
||||||
|
yield break;
|
||||||
|
if (SpecialThingFilterDefOf.AllowVegetarian != null) yield return SpecialThingFilterDefOf.AllowVegetarian;
|
||||||
|
if (SpecialThingFilterDefOf.AllowCarnivore != null) yield return SpecialThingFilterDefOf.AllowCarnivore;
|
||||||
|
if (SpecialThingFilterDefOf.AllowCannibal != null) yield return SpecialThingFilterDefOf.AllowCannibal;
|
||||||
|
if (SpecialThingFilterDefOf.AllowInsectMeat != null) yield return SpecialThingFilterDefOf.AllowInsectMeat;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The template the window would save now: kind.Capture(Scratch) under the kind's key, with the window's
|
||||||
|
/// unlisted rule, plus every name of the original template that doesn't resolve now, in the list it was in.
|
||||||
|
/// Tests call this instead of clicking Save.
|
||||||
|
/// </summary>
|
||||||
|
public StorageTemplate BuildTemplate()
|
||||||
|
{
|
||||||
|
StorageTemplate t = Kind.Capture(Scratch);
|
||||||
|
t.unlisted = Unlisted;
|
||||||
|
t.KeepUnresolvedFrom(Original);
|
||||||
|
return t;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Saves BuildTemplate() with DefaultsLibrary.Set and closes the window.</summary>
|
||||||
|
public void Save()
|
||||||
|
{
|
||||||
|
DefaultsLibrary.Set(BuildTemplate());
|
||||||
|
Close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Lets the vanilla item filter draw without a game, for the edit window opened from the main menu. The
|
||||||
|
/// filter tree reads the game in two places: Listing_TreeThingFilter.DoCategoryChildren reads
|
||||||
|
/// Find.HiddenItemsManager (Verse/Listing_TreeThingFilter.cs:86), and DoThingDef (:190) and two search
|
||||||
|
/// helpers (:121, :406) call QuickSearchFilter.Matches(ThingDef), which reads it too
|
||||||
|
/// (RimWorld/QuickSearchFilter.cs:55). Find.HiddenItemsManager is Current.Game.hiddenItemsManager
|
||||||
|
/// (Verse/Find.cs:182) and throws at the main menu. In a game both replacements below do exactly what
|
||||||
|
/// vanilla does; without one nothing is hidden (defaults are global, so undiscovered items are offered too).
|
||||||
|
/// Patched on the callers, because the getter and Matches are small enough to be inlined.
|
||||||
|
/// </summary>
|
||||||
|
public static class MainMenuFilterGuard
|
||||||
|
{
|
||||||
|
private static HiddenItemsManager nothingHidden;
|
||||||
|
|
||||||
|
/// <summary>Getter calls and Matches(ThingDef) calls the transpiler replaced, per patched method.</summary>
|
||||||
|
public static readonly Dictionary<string, (int getter, int matches)> Replaced = new Dictionary<string, (int, int)>();
|
||||||
|
|
||||||
|
/// <summary>True when the item filter can draw without a game: both kinds of calls were found and replaced.</summary>
|
||||||
|
public static bool Ready
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
int getter = 0, matches = 0;
|
||||||
|
foreach (var r in Replaced.Values)
|
||||||
|
{
|
||||||
|
getter += r.getter;
|
||||||
|
matches += r.matches;
|
||||||
|
}
|
||||||
|
return getter > 0 && matches > 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The manager the filter reads at the main menu: hides nothing.</summary>
|
||||||
|
public static HiddenItemsManager NothingHidden
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
if (nothingHidden == null)
|
||||||
|
{
|
||||||
|
var m = new HiddenItemsManager();
|
||||||
|
m.ClearHiddenDefs();
|
||||||
|
nothingHidden = m;
|
||||||
|
}
|
||||||
|
return nothingHidden;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Replaces Find.HiddenItemsManager: the game's manager in a game, else NothingHidden.</summary>
|
||||||
|
public static HiddenItemsManager HiddenItems()
|
||||||
|
{
|
||||||
|
Game game = Current.Game;
|
||||||
|
return game != null ? game.hiddenItemsManager : NothingHidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Replaces QuickSearchFilter.Matches(ThingDef): vanilla in a game, else a label match with nothing hidden.</summary>
|
||||||
|
public static bool Matches(QuickSearchFilter filter, ThingDef td)
|
||||||
|
{
|
||||||
|
if (Current.Game != null)
|
||||||
|
return filter.Matches(td);
|
||||||
|
return filter.Matches(td.label);
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static readonly MethodInfo HiddenItemsGetter = AccessTools.PropertyGetter(typeof(Find), nameof(Find.HiddenItemsManager));
|
||||||
|
|
||||||
|
internal static readonly MethodInfo MatchesThingDef = AccessTools.Method(typeof(QuickSearchFilter), nameof(QuickSearchFilter.Matches), new[] { typeof(ThingDef) });
|
||||||
|
}
|
||||||
|
|
||||||
|
[HarmonyPatch]
|
||||||
|
public static class Patch_Listing_TreeThingFilter_MainMenu
|
||||||
|
{
|
||||||
|
/// <summary>Every method of the filter tree, local functions included, that calls the getter or Matches(ThingDef).</summary>
|
||||||
|
public static IEnumerable<MethodBase> TargetMethods()
|
||||||
|
{
|
||||||
|
var targets = new List<MethodBase>();
|
||||||
|
foreach (MethodInfo m in AccessTools.GetDeclaredMethods(typeof(Listing_TreeThingFilter)))
|
||||||
|
{
|
||||||
|
if (m.IsAbstract || m.ContainsGenericParameters || m.GetMethodBody() == null)
|
||||||
|
continue;
|
||||||
|
List<CodeInstruction> code;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
code = PatchProcessor.GetOriginalInstructions(m);
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
foreach (CodeInstruction ci in code)
|
||||||
|
{
|
||||||
|
if (ci.Calls(MainMenuFilterGuard.HiddenItemsGetter) || ci.Calls(MainMenuFilterGuard.MatchesThingDef))
|
||||||
|
{
|
||||||
|
targets.Add(m);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return targets;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, MethodBase original)
|
||||||
|
{
|
||||||
|
MethodInfo hiddenItems = AccessTools.Method(typeof(MainMenuFilterGuard), nameof(MainMenuFilterGuard.HiddenItems));
|
||||||
|
MethodInfo matches = AccessTools.Method(typeof(MainMenuFilterGuard), nameof(MainMenuFilterGuard.Matches));
|
||||||
|
int getterCalls = 0, matchesCalls = 0;
|
||||||
|
var result = new List<CodeInstruction>();
|
||||||
|
foreach (CodeInstruction ci in instructions)
|
||||||
|
{
|
||||||
|
if (ci.Calls(MainMenuFilterGuard.HiddenItemsGetter))
|
||||||
|
{
|
||||||
|
ci.opcode = OpCodes.Call;
|
||||||
|
ci.operand = hiddenItems;
|
||||||
|
getterCalls++;
|
||||||
|
}
|
||||||
|
else if (ci.Calls(MainMenuFilterGuard.MatchesThingDef))
|
||||||
|
{
|
||||||
|
// The filter instance and the def are already on the stack: the static takes them as its two arguments.
|
||||||
|
ci.opcode = OpCodes.Call;
|
||||||
|
ci.operand = matches;
|
||||||
|
matchesCalls++;
|
||||||
|
}
|
||||||
|
result.Add(ci);
|
||||||
|
}
|
||||||
|
MainMenuFilterGuard.Replaced[original?.Name ?? "?"] = (getterCalls, matchesCalls);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,94 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Reflection;
|
||||||
|
using RimWorld;
|
||||||
|
using Verse;
|
||||||
|
|
||||||
|
namespace BlaxDefaults
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Which DLC a def needs, for saved defaults whose def is not loaded. A vanilla DefOf field carries
|
||||||
|
/// [MayRequireBiotech] (or its DLC's attribute) for DLC content, such as ThingDefOf.GrowthVat; a name
|
||||||
|
/// without such a field (from a removed mod) has no DLC and counts as a name from an inactive mod.
|
||||||
|
/// Every feature that needs a DLC checks ModsConfig.<DLC>Active before it touches DLC content.
|
||||||
|
/// </summary>
|
||||||
|
public static class DlcSupport
|
||||||
|
{
|
||||||
|
public const string Royalty = "ludeon.rimworld.royalty";
|
||||||
|
public const string Ideology = "ludeon.rimworld.ideology";
|
||||||
|
public const string Biotech = "ludeon.rimworld.biotech";
|
||||||
|
public const string Anomaly = "ludeon.rimworld.anomaly";
|
||||||
|
public const string Odyssey = "ludeon.rimworld.odyssey";
|
||||||
|
|
||||||
|
// (def type, defName) -> lower-case DLC package id, from every [DefOf] class of the game.
|
||||||
|
private static Dictionary<(Type, string), string> mayRequire;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The package id of the DLC a def of this type and name needs, from the vanilla DefOf field with its
|
||||||
|
/// name; null when no DefOf field names it with a MayRequire attribute.
|
||||||
|
/// </summary>
|
||||||
|
public static string RequiredDlc(Type defType, string defName)
|
||||||
|
{
|
||||||
|
if (defName.NullOrEmpty())
|
||||||
|
return null;
|
||||||
|
mayRequire ??= Scan();
|
||||||
|
for (Type t = defType; t != null && typeof(Def).IsAssignableFrom(t); t = t.BaseType)
|
||||||
|
{
|
||||||
|
if (mayRequire.TryGetValue((t, defName), out string id))
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static string RequiredDlcOfThing(string defName) => RequiredDlc(typeof(ThingDef), defName);
|
||||||
|
|
||||||
|
/// <summary>True when the DLC with this package id is loaded.</summary>
|
||||||
|
public static bool IsActive(string dlcPackageId) => ModLister.GetActiveModWithIdentifier(dlcPackageId, ignorePostfix: true) != null;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The DLC that a def name which does not resolve is waiting for: its package id when a vanilla DefOf
|
||||||
|
/// field marks it and that DLC is off, else null (a name from an inactive mod).
|
||||||
|
/// </summary>
|
||||||
|
public static string MissingDlcOfThing(string defName)
|
||||||
|
{
|
||||||
|
string id = RequiredDlcOfThing(defName);
|
||||||
|
return id != null && !IsActive(id) ? id : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>"Biotech" for "ludeon.rimworld.biotech".</summary>
|
||||||
|
public static string DlcName(string dlcPackageId)
|
||||||
|
{
|
||||||
|
switch (dlcPackageId?.ToLowerInvariant())
|
||||||
|
{
|
||||||
|
case Royalty: return "Royalty";
|
||||||
|
case Ideology: return "Ideology";
|
||||||
|
case Biotech: return "Biotech";
|
||||||
|
case Anomaly: return "Anomaly";
|
||||||
|
case Odyssey: return "Odyssey";
|
||||||
|
default: return dlcPackageId;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>"Needs Biotech", the note on a disabled row or section.</summary>
|
||||||
|
public static string NeedsLabel(string dlcPackageId) => "BlaxDefaults_NeedsDlc".Translate(DlcName(dlcPackageId));
|
||||||
|
|
||||||
|
private static Dictionary<(Type, string), string> Scan()
|
||||||
|
{
|
||||||
|
var d = new Dictionary<(Type, string), string>();
|
||||||
|
foreach (Type type in typeof(ThingDefOf).Assembly.GetTypes())
|
||||||
|
{
|
||||||
|
if (!type.IsDefined(typeof(DefOf), false))
|
||||||
|
continue;
|
||||||
|
foreach (FieldInfo f in type.GetFields(BindingFlags.Public | BindingFlags.Static))
|
||||||
|
{
|
||||||
|
if (!typeof(Def).IsAssignableFrom(f.FieldType))
|
||||||
|
continue;
|
||||||
|
var attr = f.GetCustomAttribute<MayRequireAttribute>(true);
|
||||||
|
if (attr?.modId != null)
|
||||||
|
d[(f.FieldType, f.Name)] = attr.modId.ToLowerInvariant();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return d;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,32 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using Verse;
|
||||||
|
|
||||||
|
namespace BlaxDefaults
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Every hook body sits in try/catch and reports here, so a Defaults bug never breaks a construction, a
|
||||||
|
/// designation or a bill. Each hook logs its first failure only.
|
||||||
|
/// <code>
|
||||||
|
/// static void Postfix(...)
|
||||||
|
/// {
|
||||||
|
/// try { ... }
|
||||||
|
/// catch (Exception e) { HookGuard.Report("MakeNewZone", e); }
|
||||||
|
/// }
|
||||||
|
/// </code>
|
||||||
|
/// </summary>
|
||||||
|
public static class HookGuard
|
||||||
|
{
|
||||||
|
private static readonly HashSet<string> reported = new HashSet<string>();
|
||||||
|
|
||||||
|
public static void Report(string hook, Exception e)
|
||||||
|
{
|
||||||
|
lock (reported)
|
||||||
|
{
|
||||||
|
if (!reported.Add(hook))
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Log.Error("[Blax Defaults] " + hook + " failed; later failures of this hook are not logged: " + e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,279 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
|
using HarmonyLib;
|
||||||
|
using RimWorld;
|
||||||
|
using UnityEngine;
|
||||||
|
using Verse;
|
||||||
|
|
||||||
|
namespace BlaxDefaults
|
||||||
|
{
|
||||||
|
/// <summary>A mod that sets the same defaults: its package id, name and a keyed string naming what it sets.</summary>
|
||||||
|
public sealed class OverlapMod
|
||||||
|
{
|
||||||
|
public readonly string PackageId;
|
||||||
|
public readonly string Name;
|
||||||
|
public readonly string WhatKey;
|
||||||
|
|
||||||
|
public OverlapMod(string packageId, string name, string whatKey)
|
||||||
|
{
|
||||||
|
PackageId = packageId;
|
||||||
|
Name = name;
|
||||||
|
WhatKey = whatKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
public string What => WhatKey.Translate();
|
||||||
|
|
||||||
|
public override string ToString() => PackageId;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Names active mods that set the same defaults. Work package "setup" (design.md: "Overlap warnings").
|
||||||
|
/// Detection only, through Compat.IsActive; no patches against those mods. 1.0 detects for storage
|
||||||
|
/// 1trickPwnyta's Defaults (defaults.1trickPwnyta), the unofficial Defaults 1.7 repack, Set my Defaults,
|
||||||
|
/// [FSF] No Default Shelf Storage, [FSF] FrozenSnowFox Tweaks and Default Normal Empty Storage, and for the
|
||||||
|
/// bill values Better Workbench Management, Default Ingredient Radius, Default Bill Ingredient Radius and
|
||||||
|
/// Default Until X. Dismissed ids live in BlaxDefaultsSettings.dismissedOverlaps, never in a save.
|
||||||
|
///
|
||||||
|
/// Package ids, each read from the mod's own About/About.xml in its public source repository, with its
|
||||||
|
/// About/PublishedFileId.txt matching the Workshop item (checked 2026-11-29):
|
||||||
|
/// - 1trickPwnyta's Defaults (Workshop 3285178686, Experimental 3522445452): github.com/1trickPwnyta/DefaultsMod,
|
||||||
|
/// branches master and experimental (the same id on both; Castes' Compat also read branch 1.7).
|
||||||
|
/// - Set my Defaults (3737034968): github.com/jb-rimworld/set-my-defaults, branch main.
|
||||||
|
/// - [FSF] No Default Shelf Storage (945085502): github.com/FrozenSnowFox/FSF_No_Default_Shelf_Storage, branch main.
|
||||||
|
/// - [FSF] FrozenSnowFox Tweaks (2893432492): github.com/FrozenSnowFox/FSF_FrozenSnowFox_Tweaks, branch main.
|
||||||
|
/// - Better Workbench Management (935982361): github.com/Falconne/ImprovedWorkbenches, branch master,
|
||||||
|
/// mod-structure/About/About.xml.
|
||||||
|
/// - Default Ingredient Radius (2909706985): github.com/emipa606/DefaultIngredientRadius, branch main.
|
||||||
|
/// - Default Bill Ingredient Radius (3789671048): github.com/benpbmith/DefaultBillIngredientRadius, branch main.
|
||||||
|
/// Not listed yet, because no public About.xml could be read; add each once its id is read from the mod files:
|
||||||
|
/// - the unofficial Defaults 1.7 repack (3836680679): its Workshop description says its packageId differs
|
||||||
|
/// from the original's, without naming it (what: BlaxDefaults_OverlapWhatDefaults).
|
||||||
|
/// - Default Normal Empty Storage (3779351608): no public source; Nexus mod 758 (BlaxDefaults_OverlapWhatEmptyStorage).
|
||||||
|
/// - Default Until X (3554414830): no public source (BlaxDefaults_OverlapWhatRepeat).
|
||||||
|
/// None of these mods is installed on the test machine, so detection is tested with a simulated id.
|
||||||
|
/// </summary>
|
||||||
|
public static class OverlapWarnings
|
||||||
|
{
|
||||||
|
public const string Defaults1trickPwnyta = "defaults.1trickPwnyta";
|
||||||
|
public const string SetMyDefaults = "juliusberger.workbenchbilldefaults";
|
||||||
|
public const string FsfNoDefaultShelfStorage = "FrozenSnowFox.NoDefaultShelfStorage";
|
||||||
|
public const string FsfTweaks = "FrozenSnowFox.FrozenSnowFoxTweaks";
|
||||||
|
public const string BetterWorkbenchManagement = "falconne.BWM";
|
||||||
|
public const string DefaultIngredientRadius = "Mlie.DefaultIngredientRadius";
|
||||||
|
public const string DefaultBillIngredientRadius = "pkthxbai.defaultbillingredientradius";
|
||||||
|
|
||||||
|
/// <summary>Every overlapping mod Defaults knows, in the order the page lists them: storage, then bills.</summary>
|
||||||
|
public static readonly OverlapMod[] Mods =
|
||||||
|
{
|
||||||
|
new OverlapMod(Defaults1trickPwnyta, "1trickPwnyta's Defaults", "BlaxDefaults_OverlapWhatDefaults"),
|
||||||
|
new OverlapMod(SetMyDefaults, "Set my Defaults", "BlaxDefaults_OverlapWhatDefaults"),
|
||||||
|
new OverlapMod(FsfNoDefaultShelfStorage, "[FSF] No Default Shelf Storage", "BlaxDefaults_OverlapWhatFsfShelves"),
|
||||||
|
new OverlapMod(FsfTweaks, "[FSF] FrozenSnowFox Tweaks", "BlaxDefaults_OverlapWhatFsfTweaks"),
|
||||||
|
new OverlapMod(BetterWorkbenchManagement, "Better Workbench Management", "BlaxDefaults_OverlapWhatStoreMode"),
|
||||||
|
new OverlapMod(DefaultIngredientRadius, "Default Ingredient Radius", "BlaxDefaults_OverlapWhatRadius"),
|
||||||
|
new OverlapMod(DefaultBillIngredientRadius, "Default Bill Ingredient Radius", "BlaxDefaults_OverlapWhatRadius"),
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>Package ids treated as active on top of the real mod list. For tests only.</summary>
|
||||||
|
public static readonly HashSet<string> SimulatedActive = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||||
|
|
||||||
|
// The mod list can't change without a restart, so the real detection runs once.
|
||||||
|
private static List<OverlapMod> detected;
|
||||||
|
private static bool shownThisSession;
|
||||||
|
|
||||||
|
/// <summary>The overlapping mods that are active (real or simulated), in list order.</summary>
|
||||||
|
public static List<OverlapMod> Active()
|
||||||
|
{
|
||||||
|
detected ??= Mods.Where(m => Compat.IsActive(m.PackageId)).ToList();
|
||||||
|
if (SimulatedActive.Count == 0)
|
||||||
|
return new List<OverlapMod>(detected);
|
||||||
|
return Mods.Where(m => detected.Contains(m) || SimulatedActive.Contains(m.PackageId)).ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>True when the mod with this package id is active, real or simulated.</summary>
|
||||||
|
public static bool IsActive(string packageId) =>
|
||||||
|
!packageId.NullOrEmpty() && (SimulatedActive.Contains(packageId) || Compat.IsActive(packageId));
|
||||||
|
|
||||||
|
/// <summary>True when the player chose "Don't remind me" for this package id.</summary>
|
||||||
|
public static bool IsDismissed(string packageId)
|
||||||
|
{
|
||||||
|
List<string> dismissed = BlaxDefaultsMod.Settings?.dismissedOverlaps;
|
||||||
|
return dismissed != null && dismissed.Any(id => string.Equals(id, packageId, StringComparison.OrdinalIgnoreCase));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool WarningsOn => BlaxDefaultsMod.Settings == null || BlaxDefaultsMod.Settings.warnOverlaps;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The settings page text naming each active mod and what it sets; null when none or warnOverlaps is off.
|
||||||
|
/// Names dismissed mods too: "Don't remind me" only stops the window on load.
|
||||||
|
/// </summary>
|
||||||
|
public static string SettingsText()
|
||||||
|
{
|
||||||
|
if (!WarningsOn)
|
||||||
|
return null;
|
||||||
|
List<OverlapMod> active = Active();
|
||||||
|
if (active.Count == 0)
|
||||||
|
return null;
|
||||||
|
var sb = new StringBuilder();
|
||||||
|
sb.Append("BlaxDefaults_OverlapSettingsIntro".Translate());
|
||||||
|
foreach (OverlapMod mod in active)
|
||||||
|
sb.Append("\n- " + "BlaxDefaults_OverlapLine".Translate(mod.Name.Named("MOD"), mod.What.Named("WHAT")));
|
||||||
|
sb.Append("\n" + "BlaxDefaults_OverlapAdvice".Translate());
|
||||||
|
return sb.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The message text for these mods, or null for none.</summary>
|
||||||
|
public static string MessageText(List<OverlapMod> mods)
|
||||||
|
{
|
||||||
|
if (mods == null || mods.Count == 0)
|
||||||
|
return null;
|
||||||
|
string names = mods.Select(m => m.Name).ToCommaList(useAnd: true);
|
||||||
|
return "BlaxDefaults_OverlapMessage".Translate(names.Named("MODS"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The warnOverlaps checkbox and SettingsText, on the settings page.</summary>
|
||||||
|
public static void DrawSettings(Listing_Standard l)
|
||||||
|
{
|
||||||
|
BlaxDefaultsSettings s = BlaxDefaultsMod.Settings;
|
||||||
|
if (s == null)
|
||||||
|
return;
|
||||||
|
l.CheckboxLabeled("BlaxDefaults_WarnOverlaps".Translate(), ref s.warnOverlaps, "BlaxDefaults_WarnOverlapsTip".Translate());
|
||||||
|
string text = SettingsText();
|
||||||
|
if (text != null)
|
||||||
|
l.Label(text);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// On the first game loaded in a session: one window listing the active mods not yet dismissed, with
|
||||||
|
/// "Don't remind me" per mod. Returns the mods it named (empty after the first call of a session). A
|
||||||
|
/// plain message has no buttons, so it is a small window (Dialog_OverlapWarnings).
|
||||||
|
/// </summary>
|
||||||
|
public static List<OverlapMod> ShowOncePerSession()
|
||||||
|
{
|
||||||
|
var named = new List<OverlapMod>();
|
||||||
|
if (shownThisSession)
|
||||||
|
return named;
|
||||||
|
shownThisSession = true;
|
||||||
|
if (!WarningsOn)
|
||||||
|
return named;
|
||||||
|
foreach (OverlapMod mod in Active())
|
||||||
|
{
|
||||||
|
if (!IsDismissed(mod.PackageId))
|
||||||
|
named.Add(mod);
|
||||||
|
}
|
||||||
|
if (named.Count == 0)
|
||||||
|
return named;
|
||||||
|
var mods = new List<OverlapMod>(named);
|
||||||
|
// FinalizeInit runs inside the loading event; the window opens when it is done.
|
||||||
|
LongEventHandler.ExecuteWhenFinished(() => Find.WindowStack?.Add(new Dialog_OverlapWarnings(mods)));
|
||||||
|
return named;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>"Don't remind me": adds the id to dismissedOverlaps and writes the mod settings.</summary>
|
||||||
|
public static void Dismiss(string packageId)
|
||||||
|
{
|
||||||
|
BlaxDefaultsSettings s = BlaxDefaultsMod.Settings;
|
||||||
|
if (s == null || packageId.NullOrEmpty())
|
||||||
|
return;
|
||||||
|
s.dismissedOverlaps ??= new List<string>();
|
||||||
|
if (!IsDismissed(packageId))
|
||||||
|
s.dismissedOverlaps.Add(packageId);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
s.Write();
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
Log.Warning("[Blax Defaults] Writing the mod settings failed: " + e.Message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Lets ShowOncePerSession show again. Tests only.</summary>
|
||||||
|
public static void ResetSessionForTests()
|
||||||
|
{
|
||||||
|
shownThisSession = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The window on the first game loaded in a session: which active mods set the same defaults, each with
|
||||||
|
/// what it sets and "Don't remind me". Work package "setup".
|
||||||
|
/// </summary>
|
||||||
|
public class Dialog_OverlapWarnings : Window
|
||||||
|
{
|
||||||
|
public readonly List<OverlapMod> Mods;
|
||||||
|
private readonly HashSet<string> dismissedHere = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||||
|
|
||||||
|
private const float RowHeight = 56f;
|
||||||
|
private const float ButtonWidth = 150f;
|
||||||
|
private Vector2 scroll;
|
||||||
|
|
||||||
|
public Dialog_OverlapWarnings(List<OverlapMod> mods)
|
||||||
|
{
|
||||||
|
Mods = mods ?? new List<OverlapMod>();
|
||||||
|
doCloseX = true;
|
||||||
|
doCloseButton = true;
|
||||||
|
forcePause = true;
|
||||||
|
absorbInputAroundWindow = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override Vector2 InitialSize => new Vector2(560f, Mathf.Min(680f, 230f + Mods.Count * RowHeight));
|
||||||
|
|
||||||
|
public override void DoWindowContents(Rect inRect)
|
||||||
|
{
|
||||||
|
float y = inRect.y;
|
||||||
|
Text.Font = GameFont.Medium;
|
||||||
|
Widgets.Label(new Rect(inRect.x, y, inRect.width - 30f, 35f), "BlaxDefaults_OverlapTitle".Translate());
|
||||||
|
y += 40f;
|
||||||
|
|
||||||
|
Text.Font = GameFont.Small;
|
||||||
|
string message = OverlapWarnings.MessageText(Mods) ?? "";
|
||||||
|
float messageHeight = Text.CalcHeight(message, inRect.width);
|
||||||
|
Widgets.Label(new Rect(inRect.x, y, inRect.width, messageHeight), message);
|
||||||
|
y += messageHeight + 10f;
|
||||||
|
|
||||||
|
var outRect = new Rect(inRect.x, y, inRect.width, inRect.yMax - y - CloseButSize.y - 10f);
|
||||||
|
var viewRect = new Rect(0f, 0f, outRect.width - 16f, Mods.Count * RowHeight);
|
||||||
|
Widgets.BeginScrollView(outRect, ref scroll, viewRect);
|
||||||
|
for (int i = 0; i < Mods.Count; i++)
|
||||||
|
DrawRow(new Rect(0f, i * RowHeight, viewRect.width, RowHeight - 6f), Mods[i]);
|
||||||
|
Widgets.EndScrollView();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void DrawRow(Rect row, OverlapMod mod)
|
||||||
|
{
|
||||||
|
var textRect = new Rect(row.x, row.y, row.width - ButtonWidth - 10f, row.height);
|
||||||
|
Widgets.Label(textRect, mod.Name + "\n" + mod.What.Colorize(ColoredText.SubtleGrayColor));
|
||||||
|
var buttonRect = new Rect(row.xMax - ButtonWidth, row.y + (row.height - 30f) / 2f, ButtonWidth, 30f);
|
||||||
|
if (dismissedHere.Contains(mod.PackageId))
|
||||||
|
{
|
||||||
|
Text.Anchor = TextAnchor.MiddleCenter;
|
||||||
|
Widgets.Label(buttonRect, "BlaxDefaults_OverlapDismissed".Translate());
|
||||||
|
Text.Anchor = TextAnchor.UpperLeft;
|
||||||
|
}
|
||||||
|
else if (Widgets.ButtonText(buttonRect, "BlaxDefaults_OverlapDontRemind".Translate()))
|
||||||
|
{
|
||||||
|
OverlapWarnings.Dismiss(mod.PackageId);
|
||||||
|
dismissedHere.Add(mod.PackageId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[HarmonyPatch(typeof(Game), nameof(Game.FinalizeInit))]
|
||||||
|
public static class Patch_Game_FinalizeInit
|
||||||
|
{
|
||||||
|
public static void Postfix()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
OverlapWarnings.ShowOncePerSession();
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
HookGuard.Report("Game.FinalizeInit", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,247 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using RimWorld;
|
||||||
|
using UnityEngine;
|
||||||
|
using Verse;
|
||||||
|
|
||||||
|
namespace BlaxDefaults
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// "New shelves start empty at Normal". Work package "setup" (design.md: "Quick setup: new shelves start
|
||||||
|
/// empty"). The list holds StorageKinds.CoveredDefs(). A kind is ticked when its thingClass is
|
||||||
|
/// Building_Storage or a subclass, building.isHopper is false, and its parent filter allows things from at
|
||||||
|
/// least two top-level item categories (children of ThingCategoryDefOf.Root; each allowed def counts under
|
||||||
|
/// the top-level category its first thingCategories entry leads to; defs without one don't count). Kinds
|
||||||
|
/// that already have a default are marked and start unticked. Confirming saves EmptyTemplate per ticked kind.
|
||||||
|
/// </summary>
|
||||||
|
public static class QuickSetup
|
||||||
|
{
|
||||||
|
public sealed class Candidate
|
||||||
|
{
|
||||||
|
public ThingDef Def;
|
||||||
|
public bool Ticked;
|
||||||
|
public bool HasDefault;
|
||||||
|
/// <summary>
|
||||||
|
/// UntickedReason(Def), worked out once when the list is built (the rule scans every storable def,
|
||||||
|
/// too slow for every row on every GUI event); null when the preselection ticks the kind.
|
||||||
|
/// </summary>
|
||||||
|
public string UntickedReason;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Every covered def with its preselection, in def order.</summary>
|
||||||
|
public static List<Candidate> Candidates()
|
||||||
|
{
|
||||||
|
var list = new List<Candidate>();
|
||||||
|
foreach (ThingDef def in StorageKinds.CoveredDefs())
|
||||||
|
{
|
||||||
|
bool has = DefaultsLibrary.Has(DefaultsKeys.ForStorage(def));
|
||||||
|
string reason;
|
||||||
|
bool preselect;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
reason = UntickedReason(def);
|
||||||
|
preselect = reason == null;
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
// A modded def with odd storage settings stays unticked instead of breaking the list.
|
||||||
|
HookGuard.Report("QuickSetup.Preselect", e);
|
||||||
|
reason = null;
|
||||||
|
preselect = false;
|
||||||
|
}
|
||||||
|
list.Add(new Candidate { Def = def, HasDefault = has, UntickedReason = reason, Ticked = preselect && !has });
|
||||||
|
}
|
||||||
|
return list;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The preselection rule above, ignoring whether a default exists.</summary>
|
||||||
|
public static bool Preselect(ThingDef def) => UntickedReason(def) == null;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Why the preselection leaves the def unticked, as a keyed string; null when it ticks it. Ignores
|
||||||
|
/// whether a default exists.
|
||||||
|
/// </summary>
|
||||||
|
public static string UntickedReason(ThingDef def)
|
||||||
|
{
|
||||||
|
if (def?.building == null || def.thingClass == null || !typeof(Building_Storage).IsAssignableFrom(def.thingClass))
|
||||||
|
return "BlaxDefaults_QuickSetupReasonNotShelf";
|
||||||
|
// An empty hopper starves the nutrient paste dispenser (BuildingProperties.isHopper).
|
||||||
|
if (def.building.isHopper)
|
||||||
|
return "BlaxDefaults_QuickSetupReasonHopper";
|
||||||
|
if (TopLevelCategoryCount(StorageKinds.ParentFilterFor(def)) < 2)
|
||||||
|
return "BlaxDefaults_QuickSetupReasonOneCategory";
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>How many top-level item categories the filter allows things from.</summary>
|
||||||
|
public static int TopLevelCategoryCount(ThingFilter parentFilter)
|
||||||
|
{
|
||||||
|
var tops = new HashSet<ThingCategoryDef>();
|
||||||
|
foreach (ThingDef def in StorageKinds.StorableDefs(parentFilter))
|
||||||
|
{
|
||||||
|
ThingCategoryDef top = TopLevelCategoryOf(def);
|
||||||
|
if (top != null)
|
||||||
|
tops.Add(top);
|
||||||
|
}
|
||||||
|
return tops.Count;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The child of ThingCategoryDefOf.Root that the def's first thingCategories entry leads to, or null when
|
||||||
|
/// the def has no category or its first one isn't under Root.
|
||||||
|
/// </summary>
|
||||||
|
public static ThingCategoryDef TopLevelCategoryOf(ThingDef def)
|
||||||
|
{
|
||||||
|
ThingCategoryDef root = ThingCategoryDefOf.Root;
|
||||||
|
ThingCategoryDef cat = def?.thingCategories?.FirstOrDefault();
|
||||||
|
// The depth limit only guards against a modded category loop.
|
||||||
|
for (int depth = 0; cat != null && depth < 64; depth++)
|
||||||
|
{
|
||||||
|
if (cat.parent == root)
|
||||||
|
return cat;
|
||||||
|
cat = cat.parent;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Normal, allows nothing, refuses every storable def the def's parent filter allows, unlisted = Refuse,
|
||||||
|
/// so items a mod adds later are refused too. Not saved.
|
||||||
|
/// </summary>
|
||||||
|
public static StorageTemplate EmptyTemplate(ThingDef def)
|
||||||
|
{
|
||||||
|
var t = new StorageTemplate(DefaultsKeys.ForStorage(def))
|
||||||
|
{
|
||||||
|
Priority = StoragePriority.Normal,
|
||||||
|
unlisted = UnlistedRule.Refuse,
|
||||||
|
};
|
||||||
|
foreach (ThingDef d in StorageKinds.StorableDefs(StorageKinds.ParentFilterFor(def)))
|
||||||
|
t.refused.Add(d.defName);
|
||||||
|
return t;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Saves EmptyTemplate for each def, replacing any default it has. Returns how many were saved (put in
|
||||||
|
/// the library with one file write; DefaultsLibrary.LastWriteOk tells whether it succeeded).
|
||||||
|
/// </summary>
|
||||||
|
public static int Apply(IEnumerable<ThingDef> ticked)
|
||||||
|
{
|
||||||
|
if (ticked == null)
|
||||||
|
return 0;
|
||||||
|
List<DefaultsEntry> templates = ticked.Where(d => d != null).Distinct().Select(d => (DefaultsEntry)EmptyTemplate(d)).ToList();
|
||||||
|
if (templates.Count > 0)
|
||||||
|
DefaultsLibrary.SetMany(templates);
|
||||||
|
return templates.Count;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The settings page button that opens Dialog_QuickSetup, under the Storage buildings section. Its
|
||||||
|
/// tooltip says that [FSF] No Default Shelf Storage does the same thing while that mod is active.
|
||||||
|
/// </summary>
|
||||||
|
public static void DrawButton(Listing_Standard l)
|
||||||
|
{
|
||||||
|
Rect rect = l.GetRect(30f);
|
||||||
|
if (Widgets.ButtonText(rect, "BlaxDefaults_QuickSetupButton".Translate()))
|
||||||
|
Find.WindowStack.Add(new Dialog_QuickSetup());
|
||||||
|
TooltipHandler.TipRegion(rect, ButtonTooltip());
|
||||||
|
l.Gap(l.verticalSpacing);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The button's tooltip, with the [FSF] No Default Shelf Storage note while that mod is active.</summary>
|
||||||
|
public static string ButtonTooltip()
|
||||||
|
{
|
||||||
|
string tip = "BlaxDefaults_QuickSetupTip".Translate();
|
||||||
|
if (OverlapWarnings.IsActive(OverlapWarnings.FsfNoDefaultShelfStorage))
|
||||||
|
tip += "\n\n" + "BlaxDefaults_QuickSetupTipFsf".Translate();
|
||||||
|
return tip;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The quick setup list: a checkbox per QuickSetup.Candidate, Confirm and Cancel. Work package "setup".</summary>
|
||||||
|
public class Dialog_QuickSetup : Window
|
||||||
|
{
|
||||||
|
public readonly List<QuickSetup.Candidate> Candidates;
|
||||||
|
|
||||||
|
private const float RowHeight = 28f;
|
||||||
|
private const float ButtonHeight = 38f;
|
||||||
|
private Vector2 scroll;
|
||||||
|
|
||||||
|
public Dialog_QuickSetup()
|
||||||
|
{
|
||||||
|
Candidates = QuickSetup.Candidates();
|
||||||
|
doCloseX = true;
|
||||||
|
forcePause = true;
|
||||||
|
absorbInputAroundWindow = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override Vector2 InitialSize => new Vector2(480f, 600f);
|
||||||
|
|
||||||
|
/// <summary>Saves the empty default for every ticked kind. Returns how many were saved.</summary>
|
||||||
|
public int Confirm()
|
||||||
|
{
|
||||||
|
int saved = QuickSetup.Apply(Candidates.Where(c => c.Ticked).Select(c => c.Def));
|
||||||
|
if (saved > 0)
|
||||||
|
Messages.Message("BlaxDefaults_QuickSetupSaved".Translate(saved), MessageTypeDefOf.TaskCompletion, historical: false);
|
||||||
|
return saved;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void DoWindowContents(Rect inRect)
|
||||||
|
{
|
||||||
|
float y = inRect.y;
|
||||||
|
Text.Font = GameFont.Medium;
|
||||||
|
Widgets.Label(new Rect(inRect.x, y, inRect.width - 30f, 35f), "BlaxDefaults_QuickSetupTitle".Translate());
|
||||||
|
y += 40f;
|
||||||
|
|
||||||
|
Text.Font = GameFont.Small;
|
||||||
|
string intro = "BlaxDefaults_QuickSetupIntro".Translate();
|
||||||
|
float introHeight = Text.CalcHeight(intro, inRect.width);
|
||||||
|
Widgets.Label(new Rect(inRect.x, y, inRect.width, introHeight), intro);
|
||||||
|
y += introHeight + 10f;
|
||||||
|
|
||||||
|
var outRect = new Rect(inRect.x, y, inRect.width, inRect.yMax - y - ButtonHeight - 10f);
|
||||||
|
if (Candidates.Count == 0)
|
||||||
|
{
|
||||||
|
Widgets.Label(outRect, "BlaxDefaults_QuickSetupNone".Translate());
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
var viewRect = new Rect(0f, 0f, outRect.width - 16f, Candidates.Count * RowHeight);
|
||||||
|
Widgets.BeginScrollView(outRect, ref scroll, viewRect);
|
||||||
|
for (int i = 0; i < Candidates.Count; i++)
|
||||||
|
DrawRow(new Rect(0f, i * RowHeight, viewRect.width, RowHeight), Candidates[i], i);
|
||||||
|
Widgets.EndScrollView();
|
||||||
|
}
|
||||||
|
|
||||||
|
float buttonWidth = (inRect.width - 10f) / 2f;
|
||||||
|
var confirmRect = new Rect(inRect.x, inRect.yMax - ButtonHeight, buttonWidth, ButtonHeight);
|
||||||
|
var cancelRect = new Rect(confirmRect.xMax + 10f, confirmRect.y, buttonWidth, ButtonHeight);
|
||||||
|
if (Widgets.ButtonText(confirmRect, "Confirm".Translate()))
|
||||||
|
{
|
||||||
|
Confirm();
|
||||||
|
Close();
|
||||||
|
}
|
||||||
|
if (Widgets.ButtonText(cancelRect, "CancelButton".Translate()))
|
||||||
|
Close();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void DrawRow(Rect rect, QuickSetup.Candidate c, int index)
|
||||||
|
{
|
||||||
|
if (index % 2 == 1)
|
||||||
|
Widgets.DrawLightHighlight(rect);
|
||||||
|
string label = c.Def.LabelCap;
|
||||||
|
if (c.Def.modContentPack != null && !c.Def.modContentPack.IsOfficialMod)
|
||||||
|
label += " " + ("(" + c.Def.modContentPack.Name + ")").Colorize(ColoredText.SubtleGrayColor);
|
||||||
|
if (c.HasDefault)
|
||||||
|
label += " " + ("(" + "BlaxDefaults_QuickSetupHasDefault".Translate() + ")").Colorize(ColoredText.SubtleGrayColor);
|
||||||
|
Widgets.CheckboxLabeled(rect.ContractedBy(2f, 0f), label, ref c.Ticked);
|
||||||
|
|
||||||
|
string reason = c.UntickedReason;
|
||||||
|
string tip = reason == null ? null : (string)reason.Translate();
|
||||||
|
if (c.HasDefault)
|
||||||
|
tip = (tip == null ? "" : tip + "\n\n") + "BlaxDefaults_QuickSetupReasonHasDefault".Translate();
|
||||||
|
if (tip != null)
|
||||||
|
TooltipHandler.TipRegion(rect, tip);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,415 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Globalization;
|
||||||
|
using System.IO;
|
||||||
|
using System.Linq;
|
||||||
|
using RimWorld;
|
||||||
|
using UnityEngine;
|
||||||
|
using Verse;
|
||||||
|
|
||||||
|
namespace BlaxDefaults
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Mod settings > Blax Defaults. Work package "page" (design.md: "Defaults library and settings page",
|
||||||
|
/// players get / how / settings; "DLC support" for disabled rows).
|
||||||
|
///
|
||||||
|
/// Order on the page (inside a scroll view): the master toggle "enabled"; a status line (entry count, names
|
||||||
|
/// from inactive mods); the red BrokenFilesLine when the startup load found broken files; then one section
|
||||||
|
/// per category, each with its toggle: Stockpiles (stockpileDefaults, one row per stockpile entry),
|
||||||
|
/// Storage buildings (storageDefaults, one row per storage entry, then QuickSetup.DrawButton), Every new
|
||||||
|
/// bill (billDefaults, then BillValuesSection.Draw); last OverlapWarnings.DrawSettings. Each storage row
|
||||||
|
/// shows RowSummary with Edit (Dialog_EditStorageTemplate) and Forget (asks first). A row whose kind
|
||||||
|
/// needs a DLC that is off is drawn disabled with DisabledReason; a row whose kind is not loaded for
|
||||||
|
/// another reason (a removed mod) shows its inactive names and can't be edited. It all works from the
|
||||||
|
/// main menu: nothing here needs a running game.
|
||||||
|
/// </summary>
|
||||||
|
public static class SettingsPage
|
||||||
|
{
|
||||||
|
private const float ButtonWidth = 90f;
|
||||||
|
private const float ButtonHeight = 28f;
|
||||||
|
private const float RowPad = 4f;
|
||||||
|
|
||||||
|
private static Vector2 scrollPosition;
|
||||||
|
private static float viewHeight = 900f;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// What the page shows for one entry, cached by entry reference. Library entries are never edited in
|
||||||
|
/// place (DefaultsLibrary.Get hands out the live entry; changes go through a clone and Set), so a cached
|
||||||
|
/// row stays right until its entry is replaced. Saves resolving every name of every template each frame.
|
||||||
|
/// </summary>
|
||||||
|
private sealed class RowInfo
|
||||||
|
{
|
||||||
|
public string Summary;
|
||||||
|
public string Disabled;
|
||||||
|
public int Inactive;
|
||||||
|
public bool Editable;
|
||||||
|
public string Tip;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static readonly Dictionary<DefaultsEntry, RowInfo> rowCache = new Dictionary<DefaultsEntry, RowInfo>();
|
||||||
|
|
||||||
|
/// <summary>Called by BlaxDefaultsMod.DoSettingsWindowContents.</summary>
|
||||||
|
public static void Draw(Rect inRect)
|
||||||
|
{
|
||||||
|
BlaxDefaultsSettings s = BlaxDefaultsMod.Settings;
|
||||||
|
if (s == null)
|
||||||
|
return;
|
||||||
|
PruneCache();
|
||||||
|
|
||||||
|
var view = new Rect(0f, 0f, inRect.width - 16f, Mathf.Max(viewHeight, inRect.height));
|
||||||
|
Widgets.BeginScrollView(inRect, ref scrollPosition, view);
|
||||||
|
var l = new Listing_Standard { maxOneColumn = true };
|
||||||
|
l.Begin(view);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
DrawContents(l, s);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
viewHeight = l.CurHeight + 12f;
|
||||||
|
l.End();
|
||||||
|
Widgets.EndScrollView();
|
||||||
|
Text.Font = GameFont.Small;
|
||||||
|
GUI.color = Color.white;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void DrawContents(Listing_Standard l, BlaxDefaultsSettings s)
|
||||||
|
{
|
||||||
|
l.CheckboxLabeled("BlaxDefaults_PageEnabled".Translate(), ref s.enabled, "BlaxDefaults_PageEnabledTip".Translate());
|
||||||
|
|
||||||
|
List<DefaultsEntry> all = DefaultsLibrary.All;
|
||||||
|
int inactive = all.Sum(e => Info(e).Inactive);
|
||||||
|
l.Label(StatusLine(all.Count, inactive), -1f, (TipSignal)"BlaxDefaults_PageStatusTip".Translate(DefaultsFile.FilePath).Resolve());
|
||||||
|
|
||||||
|
string broken = BrokenFilesLine();
|
||||||
|
if (broken != null)
|
||||||
|
{
|
||||||
|
using (new TextBlock(ColorLibrary.RedReadable))
|
||||||
|
l.Label(broken);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Stockpiles
|
||||||
|
SectionHeader(l, "BlaxDefaults_PageSectionStockpiles".Translate());
|
||||||
|
l.CheckboxLabeled("BlaxDefaults_PageStockpilesToggle".Translate(), ref s.stockpileDefaults, "BlaxDefaults_PageStockpilesToggleTip".Translate());
|
||||||
|
DrawRows(l, StockpileEntries(), "BlaxDefaults_PageStockpilesNone");
|
||||||
|
|
||||||
|
// Storage buildings
|
||||||
|
SectionHeader(l, "BlaxDefaults_PageSectionStorage".Translate());
|
||||||
|
l.CheckboxLabeled("BlaxDefaults_PageStorageToggle".Translate(), ref s.storageDefaults, "BlaxDefaults_PageStorageToggleTip".Translate());
|
||||||
|
DrawRows(l, StorageBuildingEntries(), "BlaxDefaults_PageStorageNone");
|
||||||
|
Guarded("QuickSetup.DrawButton", () => QuickSetup.DrawButton(l));
|
||||||
|
|
||||||
|
// Every new bill
|
||||||
|
SectionHeader(l, "BlaxDefaults_PageSectionBills".Translate());
|
||||||
|
l.CheckboxLabeled("BlaxDefaults_PageBillsToggle".Translate(), ref s.billDefaults, "BlaxDefaults_PageBillsToggleTip".Translate());
|
||||||
|
Guarded("BillValuesSection.Draw", () => BillValuesSection.Draw(l));
|
||||||
|
|
||||||
|
l.GapLine();
|
||||||
|
Guarded("OverlapWarnings.DrawSettings", () => OverlapWarnings.DrawSettings(l));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Another package's part of the page: a failure there logs once and leaves the rest of the page drawn.</summary>
|
||||||
|
private static void Guarded(string what, Action draw)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
draw();
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
HookGuard.Report("SettingsPage " + what, e);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Text.Font = GameFont.Small;
|
||||||
|
Text.Anchor = TextAnchor.UpperLeft;
|
||||||
|
GUI.color = Color.white;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void SectionHeader(Listing_Standard l, string title)
|
||||||
|
{
|
||||||
|
l.GapLine();
|
||||||
|
Text.Font = GameFont.Medium;
|
||||||
|
l.Label(title);
|
||||||
|
Text.Font = GameFont.Small;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void DrawRows(Listing_Standard l, List<DefaultsEntry> entries, string noneKey)
|
||||||
|
{
|
||||||
|
if (entries.Count == 0)
|
||||||
|
{
|
||||||
|
using (new TextBlock(Color.gray))
|
||||||
|
l.Label(noneKey.Translate());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
foreach (DefaultsEntry entry in entries)
|
||||||
|
DrawRow(l, entry, Info(entry));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void DrawRow(Listing_Standard l, DefaultsEntry entry, RowInfo info)
|
||||||
|
{
|
||||||
|
float textWidth = l.ColumnWidth - 2f * ButtonWidth - 3f * 6f;
|
||||||
|
string note = info.Disabled ?? (info.Inactive > 0 ? InactiveText(info.Inactive) : null);
|
||||||
|
float textHeight = Text.CalcHeight(info.Summary, textWidth) + (note != null ? Text.CalcHeight(note, textWidth) : 0f);
|
||||||
|
float height = Mathf.Max(ButtonHeight + 2f * RowPad, textHeight + 2f * RowPad);
|
||||||
|
Rect row = l.GetRect(height);
|
||||||
|
Widgets.DrawHighlightIfMouseover(row);
|
||||||
|
|
||||||
|
var textRect = new Rect(row.x + 6f, row.y + RowPad, textWidth, height - 2f * RowPad);
|
||||||
|
using (new TextBlock(info.Disabled != null ? Color.gray : Color.white))
|
||||||
|
{
|
||||||
|
float summaryHeight = Text.CalcHeight(info.Summary, textWidth);
|
||||||
|
Widgets.Label(new Rect(textRect.x, textRect.y, textWidth, summaryHeight), info.Summary);
|
||||||
|
if (note != null)
|
||||||
|
{
|
||||||
|
using (new TextBlock(info.Disabled != null ? ColorLibrary.RedReadable : ColorLibrary.Gold))
|
||||||
|
Widgets.Label(new Rect(textRect.x, textRect.y + summaryHeight, textWidth, textRect.height - summaryHeight), note);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!info.Tip.NullOrEmpty())
|
||||||
|
TooltipHandler.TipRegion(textRect, info.Tip);
|
||||||
|
|
||||||
|
float buttonY = row.y + (height - ButtonHeight) / 2f;
|
||||||
|
var forgetRect = new Rect(row.xMax - ButtonWidth, buttonY, ButtonWidth, ButtonHeight);
|
||||||
|
var editRect = new Rect(forgetRect.x - 6f - ButtonWidth, buttonY, ButtonWidth, ButtonHeight);
|
||||||
|
if (Widgets.ButtonText(editRect, "BlaxDefaults_PageEdit".Translate(), active: info.Editable) && info.Editable)
|
||||||
|
OpenEditor(entry);
|
||||||
|
if (!info.Editable)
|
||||||
|
{
|
||||||
|
string why = info.Disabled != null
|
||||||
|
? "BlaxDefaults_PageEditNeedsDlc".Translate(info.Disabled).Resolve()
|
||||||
|
: "BlaxDefaults_PageEditKindMissing".Translate().Resolve();
|
||||||
|
TooltipHandler.TipRegion(editRect, why);
|
||||||
|
}
|
||||||
|
if (Widgets.ButtonText(forgetRect, "BlaxDefaults_PageForget".Translate()))
|
||||||
|
ConfirmForget(entry);
|
||||||
|
l.Gap(2f);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void OpenEditor(DefaultsEntry entry)
|
||||||
|
{
|
||||||
|
StorageKind kind = StorageKinds.ForKey(entry?.key);
|
||||||
|
if (kind == null || !(entry is StorageTemplate template))
|
||||||
|
return;
|
||||||
|
Find.WindowStack.Add(new Dialog_EditStorageTemplate(kind, template.CloneTemplate()));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static RowInfo Info(DefaultsEntry entry)
|
||||||
|
{
|
||||||
|
if (rowCache.TryGetValue(entry, out RowInfo info))
|
||||||
|
return info;
|
||||||
|
info = new RowInfo
|
||||||
|
{
|
||||||
|
Summary = RowSummary(entry),
|
||||||
|
Disabled = DisabledReason(entry),
|
||||||
|
Inactive = InactiveNameCount(entry),
|
||||||
|
Editable = entry is StorageTemplate && StorageKinds.ForKey(entry.key) != null,
|
||||||
|
Tip = RowTip(entry),
|
||||||
|
};
|
||||||
|
rowCache[entry] = info;
|
||||||
|
return info;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Drops cached rows of entries that left the library (forgotten or replaced).</summary>
|
||||||
|
private static void PruneCache()
|
||||||
|
{
|
||||||
|
if (rowCache.Count == 0)
|
||||||
|
return;
|
||||||
|
var live = new HashSet<DefaultsEntry>(DefaultsLibrary.All);
|
||||||
|
foreach (DefaultsEntry e in rowCache.Keys.Where(e => !live.Contains(e)).ToList())
|
||||||
|
rowCache.Remove(e);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string RowTip(DefaultsEntry entry)
|
||||||
|
{
|
||||||
|
var parts = new List<string>();
|
||||||
|
if (entry is StorageTemplate t)
|
||||||
|
parts.Add("BlaxDefaults_PageRowUnlistedTip".Translate(t.unlisted.Label()).Resolve());
|
||||||
|
if (DisabledReason(entry) == null)
|
||||||
|
{
|
||||||
|
List<string> names = entry.UnresolvedNames().ToList();
|
||||||
|
if (KindMissing(entry))
|
||||||
|
names.Insert(0, DefaultsKeys.NameOf(entry.key));
|
||||||
|
if (names.Count > 0)
|
||||||
|
{
|
||||||
|
string shown = string.Join(", ", names.Take(12)) + (names.Count > 12 ? ", ..." : "");
|
||||||
|
parts.Add("BlaxDefaults_PageInactiveNamesTip".Translate(shown).Resolve());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return parts.Count == 0 ? null : string.Join("\n\n", parts);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// What a row says: "Shelf: Normal, allows 14 of 1,903 items, refuses unlisted items". Counts only names
|
||||||
|
/// that resolve; the unlisted part is left out for UnlistedRule.Game.
|
||||||
|
/// </summary>
|
||||||
|
public static string RowSummary(DefaultsEntry entry)
|
||||||
|
{
|
||||||
|
if (entry == null)
|
||||||
|
return null;
|
||||||
|
if (!(entry is StorageTemplate t))
|
||||||
|
return KindLabel(entry);
|
||||||
|
int allows = t.allowed.Count(n => DefDatabase<ThingDef>.GetNamedSilentFail(n) != null);
|
||||||
|
int total = allows + t.refused.Count(n => DefDatabase<ThingDef>.GetNamedSilentFail(n) != null);
|
||||||
|
string text = "BlaxDefaults_PageRowSummary".Translate(KindLabel(entry), t.Priority.Label().CapitalizeFirst(),
|
||||||
|
FormatCount(allows), FormatCount(total)).Resolve();
|
||||||
|
switch (t.unlisted)
|
||||||
|
{
|
||||||
|
case UnlistedRule.Refuse:
|
||||||
|
return "BlaxDefaults_PageRowRefusesUnlisted".Translate(text).Resolve();
|
||||||
|
case UnlistedRule.Allow:
|
||||||
|
return "BlaxDefaults_PageRowAllowsUnlisted".Translate(text).Resolve();
|
||||||
|
default:
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The row label for an entry's kind: "Shelf", "Stockpile", or the key's name when the kind is not loaded.</summary>
|
||||||
|
public static string KindLabel(DefaultsEntry entry)
|
||||||
|
{
|
||||||
|
if (entry?.key == null)
|
||||||
|
return null;
|
||||||
|
if (entry.key == DefaultsKeys.EveryBill)
|
||||||
|
return "BlaxDefaults_PageSectionBills".Translate();
|
||||||
|
StorageKind kind = StorageKinds.ForKey(entry.key);
|
||||||
|
string label = kind?.Label;
|
||||||
|
return label.NullOrEmpty() ? DefaultsKeys.NameOf(entry.key) : label.CapitalizeFirst();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// "Needs Biotech" (or its DLC) when the entry's kind is a def that a DLC which is off would add, such as
|
||||||
|
/// storage:GrowthVat without Biotech; null otherwise. Such an entry is drawn disabled and its names are
|
||||||
|
/// not counted as inactive.
|
||||||
|
/// </summary>
|
||||||
|
public static string DisabledReason(DefaultsEntry entry)
|
||||||
|
{
|
||||||
|
if (entry == null || !DefaultsKeys.IsStorage(entry.key))
|
||||||
|
return null;
|
||||||
|
string defName = DefaultsKeys.NameOf(entry.key);
|
||||||
|
if (DefDatabase<ThingDef>.GetNamedSilentFail(defName) != null)
|
||||||
|
return null;
|
||||||
|
string dlc = DlcSupport.MissingDlcOfThing(defName);
|
||||||
|
return dlc == null ? null : DlcSupport.NeedsLabel(dlc);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Names in the entry from inactive mods or DLCs that are off; 0 for an entry drawn disabled. A stockpile
|
||||||
|
/// or storage kind that is not loaded and waits for no DLC (a removed mod) counts as one more name
|
||||||
|
/// (design.md, "DLC support").
|
||||||
|
/// </summary>
|
||||||
|
public static int InactiveNameCount(DefaultsEntry entry)
|
||||||
|
{
|
||||||
|
if (entry == null || DisabledReason(entry) != null)
|
||||||
|
return 0;
|
||||||
|
return entry.UnresolvedNames().Count() + (KindMissing(entry) ? 1 : 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A stockpile or storage key whose kind is not loaded now.</summary>
|
||||||
|
private static bool KindMissing(DefaultsEntry entry) =>
|
||||||
|
(DefaultsKeys.IsStorage(entry.key) || DefaultsKeys.IsStockpile(entry.key)) && StorageKinds.ForKey(entry.key) == null;
|
||||||
|
|
||||||
|
/// <summary>"3 defaults. 2 names from mods that are not active." The status line under the master toggle.</summary>
|
||||||
|
public static string StatusLine()
|
||||||
|
{
|
||||||
|
List<DefaultsEntry> all = DefaultsLibrary.All;
|
||||||
|
return StatusLine(all.Count, all.Sum(InactiveNameCount));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string StatusLine(int count, int inactive)
|
||||||
|
{
|
||||||
|
string text;
|
||||||
|
if (count == 0)
|
||||||
|
text = "BlaxDefaults_PageStatusNone".Translate();
|
||||||
|
else if (count == 1)
|
||||||
|
text = "BlaxDefaults_PageStatusOne".Translate();
|
||||||
|
else
|
||||||
|
text = "BlaxDefaults_PageStatusMany".Translate(FormatCount(count));
|
||||||
|
return inactive > 0 ? text + " " + InactiveText(inactive) : text;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string InactiveText(int inactive) =>
|
||||||
|
inactive == 1
|
||||||
|
? "BlaxDefaults_PageInactiveOne".Translate().Resolve()
|
||||||
|
: "BlaxDefaults_PageInactiveMany".Translate(FormatCount(inactive)).Resolve();
|
||||||
|
|
||||||
|
/// <summary>The red lines about the defaults file the last load found (broken, unread, newer), else null.</summary>
|
||||||
|
public static string BrokenFilesLine() => BrokenFilesLine(DefaultsLibrary.LastLoad);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The red lines for this load result, one per line, null when the load was clean: a file of a newer
|
||||||
|
/// version (read, never written); a file left unread, or where it was moved before the first write; the
|
||||||
|
/// broken copies and their folder. "The defaults file and its backup" only when there are two broken
|
||||||
|
/// copies: a lone broken file without a backup gets the one-file line.
|
||||||
|
/// </summary>
|
||||||
|
public static string BrokenFilesLine(LoadResult load)
|
||||||
|
{
|
||||||
|
if (load == null)
|
||||||
|
return null;
|
||||||
|
var lines = new List<string>();
|
||||||
|
if (load.FromNewerVersion)
|
||||||
|
lines.Add("BlaxDefaults_PageNewerFile".Translate().Resolve());
|
||||||
|
|
||||||
|
List<string> unread = load.Unread?.Where(p => !p.NullOrEmpty()).ToList() ?? new List<string>();
|
||||||
|
if (unread.Count > 0)
|
||||||
|
lines.Add("BlaxDefaults_PageUnread".Translate(Path.GetDirectoryName(unread[0])).Resolve());
|
||||||
|
List<string> unreadCopies = load.UnreadCopies?.Where(p => !p.NullOrEmpty()).ToList() ?? new List<string>();
|
||||||
|
if (unreadCopies.Count > 0)
|
||||||
|
lines.Add("BlaxDefaults_PageUnreadKept".Translate(Path.GetDirectoryName(unreadCopies[0]), string.Join(", ", unreadCopies.Select(Path.GetFileName))).Resolve());
|
||||||
|
|
||||||
|
List<string> copies = load.BrokenCopies?.Where(p => !p.NullOrEmpty()).ToList() ?? new List<string>();
|
||||||
|
if (copies.Count > 0)
|
||||||
|
{
|
||||||
|
string folder = Path.GetDirectoryName(copies[0]);
|
||||||
|
string names = string.Join(", ", copies.Select(Path.GetFileName));
|
||||||
|
if (load.BothFailed && copies.Count >= 2)
|
||||||
|
lines.Add("BlaxDefaults_PageBrokenBoth".Translate(folder, names).Resolve());
|
||||||
|
else if (!load.LoadedFrom.NullOrEmpty())
|
||||||
|
lines.Add("BlaxDefaults_PageBrokenRecovered".Translate(folder, names, Path.GetFileName(load.LoadedFrom)).Resolve());
|
||||||
|
else
|
||||||
|
lines.Add("BlaxDefaults_PageBrokenEmpty".Translate(folder, names).Resolve());
|
||||||
|
}
|
||||||
|
return lines.Count == 0 ? null : string.Join("\n", lines);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Forget with the confirmation dialog ("Forget the default for new shelves?").</summary>
|
||||||
|
public static void ConfirmForget(DefaultsEntry entry)
|
||||||
|
{
|
||||||
|
if (entry?.key == null)
|
||||||
|
return;
|
||||||
|
string key = entry.key;
|
||||||
|
StorageKind kind = StorageKinds.ForKey(key);
|
||||||
|
string what = kind != null ? kind.LabelPlural : KindLabel(entry);
|
||||||
|
Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation(
|
||||||
|
"BlaxDefaults_PageForgetConfirm".Translate(what),
|
||||||
|
() => DefaultsLibrary.Forget(key),
|
||||||
|
destructive: true));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The storage entries (stockpile: and storage: keys) in the order the page lists them.</summary>
|
||||||
|
public static List<DefaultsEntry> StorageEntries()
|
||||||
|
{
|
||||||
|
List<DefaultsEntry> list = StockpileEntries();
|
||||||
|
list.AddRange(StorageBuildingEntries());
|
||||||
|
return list;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Stockpile entries: the vanilla stockpile, the dumping stockpile, then modded types by key.</summary>
|
||||||
|
public static List<DefaultsEntry> StockpileEntries() =>
|
||||||
|
DefaultsLibrary.WithPrefix(DefaultsKeys.StockpilePrefix)
|
||||||
|
.OrderBy(e => e.key == DefaultsKeys.Stockpile ? 0 : e.key == DefaultsKeys.Dumping ? 1 : 2)
|
||||||
|
.ThenBy(e => e.key, StringComparer.Ordinal)
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
/// <summary>Storage building entries, by their row label.</summary>
|
||||||
|
public static List<DefaultsEntry> StorageBuildingEntries() =>
|
||||||
|
DefaultsLibrary.WithPrefix(DefaultsKeys.StoragePrefix)
|
||||||
|
.OrderBy(e => KindLabel(e), StringComparer.OrdinalIgnoreCase)
|
||||||
|
.ThenBy(e => e.key, StringComparer.Ordinal)
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
/// <summary>"1,903": the count with a thousands separator, as in the design's example row.</summary>
|
||||||
|
private static string FormatCount(int n) => n.ToString("N0", CultureInfo.InvariantCulture);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,58 @@
|
||||||
|
using System;
|
||||||
|
using HarmonyLib;
|
||||||
|
using RimWorld;
|
||||||
|
using Verse;
|
||||||
|
|
||||||
|
namespace BlaxDefaults
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// New stockpiles start from their type's default. Work package "hooks" (design.md: "New stockpiles start
|
||||||
|
/// from your default"). Designator_ZoneAdd.DesignateMultiCell calls MakeNewZone before RegisterZone and
|
||||||
|
/// before the zone has cells. Designators that override MakeNewZone without calling the base never get
|
||||||
|
/// here and keep their own filter. An Expand drag that grows a zone makes none, so it never gets here.
|
||||||
|
/// </summary>
|
||||||
|
public static class StockpileHooks
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// When StockpilesOn and the zone is a Zone_Stockpile: the type from StorageKinds.StockpileTypeOf, and
|
||||||
|
/// its saved template applied with ApplyDefault. No template: vanilla stays.
|
||||||
|
/// </summary>
|
||||||
|
public static void OnNewZone(Designator_ZoneAddStockpile designator, Zone zone)
|
||||||
|
{
|
||||||
|
if (!BlaxDefaultsMod.StockpilesOn || !(zone is Zone_Stockpile pile))
|
||||||
|
return;
|
||||||
|
StockpileType type = StorageKinds.StockpileTypeOf(designator);
|
||||||
|
if (type == null)
|
||||||
|
return;
|
||||||
|
ApplyDefault(pile, type);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Applies the type's saved template onto zone.settings (on top of what the vanilla constructor set). False without a template.</summary>
|
||||||
|
public static bool ApplyDefault(Zone_Stockpile zone, StockpileType type)
|
||||||
|
{
|
||||||
|
if (zone?.settings == null || type == null)
|
||||||
|
return false;
|
||||||
|
StorageTemplate template = DefaultsLibrary.Get<StorageTemplate>(type.Key);
|
||||||
|
if (template == null)
|
||||||
|
return false;
|
||||||
|
template.ApplyTo(zone.settings, StorageKinds.StockpileParentFilter);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[HarmonyPatch(typeof(Designator_ZoneAddStockpile), "MakeNewZone")]
|
||||||
|
public static class Patch_Designator_ZoneAddStockpile_MakeNewZone
|
||||||
|
{
|
||||||
|
public static void Postfix(Designator_ZoneAddStockpile __instance, Zone __result)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
StockpileHooks.OnNewZone(__instance, __result);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
HookGuard.Report("Designator_ZoneAddStockpile.MakeNewZone", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,49 @@
|
||||||
|
using System;
|
||||||
|
using HarmonyLib;
|
||||||
|
using RimWorld;
|
||||||
|
using Verse;
|
||||||
|
|
||||||
|
namespace BlaxDefaults
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// New storage buildings with a storage blueprint start from their kind's default. Work package "hooks"
|
||||||
|
/// (design.md: "New storage buildings start from your default"). The postfix runs after vanilla copied the
|
||||||
|
/// def default in Blueprint_Storage.PostMake; the blueprint hands its settings to the frame, and
|
||||||
|
/// Frame.CompleteConstruction copies them onto the building. Auto-rebuild of a Building_Storage copies the
|
||||||
|
/// old settings onto the new blueprint after PostMake, so it keeps them; a rebuilt bookcase starts from the
|
||||||
|
/// default. Changes made on the blueprint before it is built still win. PostMake runs inside
|
||||||
|
/// ThingMaker.MakeThing, before the blueprint has a faction or a map; loading a save never calls it.
|
||||||
|
/// </summary>
|
||||||
|
public static class StorageBuildingHooks
|
||||||
|
{
|
||||||
|
/// <summary>When StorageOn and the blueprint's BuildDef is covered and has a saved template: apply it onto blueprint.settings.</summary>
|
||||||
|
public static void OnBlueprintMade(Blueprint_Storage blueprint)
|
||||||
|
{
|
||||||
|
if (!BlaxDefaultsMod.StorageOn || blueprint?.settings == null)
|
||||||
|
return;
|
||||||
|
ThingDef def = blueprint.BuildDef;
|
||||||
|
if (def == null || !StorageKinds.IsCovered(def))
|
||||||
|
return;
|
||||||
|
StorageTemplate template = DefaultsLibrary.Get<StorageTemplate>(DefaultsKeys.ForStorage(def));
|
||||||
|
if (template == null)
|
||||||
|
return;
|
||||||
|
template.ApplyTo(blueprint.settings, StorageKinds.ParentFilterFor(def));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[HarmonyPatch(typeof(Blueprint_Storage), nameof(Blueprint_Storage.PostMake))]
|
||||||
|
public static class Patch_Blueprint_Storage_PostMake
|
||||||
|
{
|
||||||
|
public static void Postfix(Blueprint_Storage __instance)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
StorageBuildingHooks.OnBlueprintMade(__instance);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
HookGuard.Report("Blueprint_Storage.PostMake", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,295 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text;
|
||||||
|
using RimWorld;
|
||||||
|
using Verse;
|
||||||
|
|
||||||
|
namespace BlaxDefaults
|
||||||
|
{
|
||||||
|
/// <summary>The four entries of the Defaults menu, in menu order.</summary>
|
||||||
|
public enum StorageMenuEntry
|
||||||
|
{
|
||||||
|
MakeDefault,
|
||||||
|
LoadDefault,
|
||||||
|
LoadGameDefault,
|
||||||
|
Forget,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The Defaults button's menu. Work package "tab" (design.md: "Defaults button in the storage tab").
|
||||||
|
/// Entries: "Make default for new shelves" (always naming the kind), "Load your default", "Load the game's
|
||||||
|
/// default", "Forget the default for new shelves" (asks first). On a stockpile each entry opens a submenu
|
||||||
|
/// of StorageKinds.StockpileTypes. Load your default = kind.LoadDefault (the game's default, then the
|
||||||
|
/// template); Load the game's default = kind.LoadGameDefault. A linked shelf (StorageGroup) gives its first
|
||||||
|
/// member's def, and Load writes the group's settings.
|
||||||
|
/// </summary>
|
||||||
|
public static class StorageDefaultsMenu
|
||||||
|
{
|
||||||
|
/// <summary>The entries in menu order.</summary>
|
||||||
|
public static readonly StorageMenuEntry[] Entries =
|
||||||
|
{
|
||||||
|
StorageMenuEntry.MakeDefault, StorageMenuEntry.LoadDefault, StorageMenuEntry.LoadGameDefault, StorageMenuEntry.Forget,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The kinds this parent offers: every stockpile type for a Zone_Stockpile; the def for a covered
|
||||||
|
/// building (StorageKinds.IsCovered), its comp, a Blueprint_Storage (BuildDef), a Frame (BuildDef) or a
|
||||||
|
/// StorageGroup (first member's def); empty for anything else, such as a Zone subclass with
|
||||||
|
/// ISlotGroupParent from Preset Filtered Zones.
|
||||||
|
/// </summary>
|
||||||
|
public static List<StorageKind> KindsFor(IStoreSettingsParent parent)
|
||||||
|
{
|
||||||
|
var kinds = new List<StorageKind>();
|
||||||
|
if (parent == null)
|
||||||
|
return kinds;
|
||||||
|
if (parent is Zone_Stockpile)
|
||||||
|
{
|
||||||
|
foreach (StockpileType type in StorageKinds.StockpileTypes)
|
||||||
|
kinds.Add(StorageKinds.ForStockpile(type));
|
||||||
|
return kinds;
|
||||||
|
}
|
||||||
|
ThingDef def = parent is StorageGroup group ? DefOf(group.members?.FirstOrDefault()) : DefOf(parent);
|
||||||
|
if (def != null && StorageKinds.IsCovered(def))
|
||||||
|
kinds.Add(StorageKinds.ForDef(def));
|
||||||
|
return kinds;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The building def a storage parent or group member stands for: a blueprint's or frame's BuildDef, a
|
||||||
|
/// thing's def, a comp's thing's def. Null for anything else.
|
||||||
|
/// </summary>
|
||||||
|
public static ThingDef DefOf(object parentOrMember)
|
||||||
|
{
|
||||||
|
switch (parentOrMember)
|
||||||
|
{
|
||||||
|
case Blueprint_Build blueprint:
|
||||||
|
return blueprint.BuildDef;
|
||||||
|
case Frame frame:
|
||||||
|
return frame.BuildDef;
|
||||||
|
case Thing thing:
|
||||||
|
return thing.def;
|
||||||
|
case ThingComp comp:
|
||||||
|
return comp.parent?.def;
|
||||||
|
default:
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The settings the menu reads and writes: parent.GetStoreSettings() (a group's settings for a linked shelf).</summary>
|
||||||
|
public static StorageSettings SettingsOf(IStoreSettingsParent parent)
|
||||||
|
{
|
||||||
|
return parent?.GetStoreSettings();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// True when the parent gets the Defaults button: it has settings and at least one kind. The same test
|
||||||
|
/// as OptionsFor(parent) being non-empty, without building the options every frame.
|
||||||
|
/// </summary>
|
||||||
|
public static bool HasButton(IStoreSettingsParent parent) => SettingsOf(parent) != null && KindsFor(parent).Count > 0;
|
||||||
|
|
||||||
|
/// <summary>The menu options; empty when the parent gets no button.</summary>
|
||||||
|
public static List<FloatMenuOption> OptionsFor(IStoreSettingsParent parent)
|
||||||
|
{
|
||||||
|
var options = new List<FloatMenuOption>();
|
||||||
|
List<StorageKind> kinds = KindsFor(parent);
|
||||||
|
if (kinds.Count == 0 || SettingsOf(parent) == null)
|
||||||
|
return options;
|
||||||
|
if (kinds[0].IsStockpile)
|
||||||
|
{
|
||||||
|
foreach (StorageMenuEntry entry in Entries)
|
||||||
|
options.Add(SubmenuOption(parent, entry, kinds));
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
foreach (StorageMenuEntry entry in Entries)
|
||||||
|
options.Add(EntryOption(parent, entry, kinds[0], EntryLabel(entry, kinds[0])));
|
||||||
|
}
|
||||||
|
return options;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The submenu a stockpile's entry opens: one option per stockpile type, labelled with the type
|
||||||
|
/// ("Stockpile", "Dumping stockpile"). Empty when the parent offers no kinds.
|
||||||
|
/// </summary>
|
||||||
|
public static List<FloatMenuOption> Submenu(IStoreSettingsParent parent, StorageMenuEntry entry)
|
||||||
|
{
|
||||||
|
var options = new List<FloatMenuOption>();
|
||||||
|
if (SettingsOf(parent) == null)
|
||||||
|
return options;
|
||||||
|
foreach (StorageKind kind in KindsFor(parent))
|
||||||
|
options.Add(EntryOption(parent, entry, kind, kind.Label.CapitalizeFirst()));
|
||||||
|
return options;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The label of an entry for one building kind: "Make default for new shelves".</summary>
|
||||||
|
public static string EntryLabel(StorageMenuEntry entry, StorageKind kind)
|
||||||
|
{
|
||||||
|
switch (entry)
|
||||||
|
{
|
||||||
|
case StorageMenuEntry.MakeDefault:
|
||||||
|
return "BlaxDefaults_TabMakeDefault".Translate(kind.LabelPlural);
|
||||||
|
case StorageMenuEntry.LoadDefault:
|
||||||
|
return "BlaxDefaults_TabLoadDefault".Translate();
|
||||||
|
case StorageMenuEntry.LoadGameDefault:
|
||||||
|
return "BlaxDefaults_TabLoadGameDefault".Translate();
|
||||||
|
default:
|
||||||
|
return "BlaxDefaults_TabForget".Translate(kind.LabelPlural);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The label of a stockpile entry, which opens the type submenu: "Make default for a stockpile type".</summary>
|
||||||
|
public static string StockpileEntryLabel(StorageMenuEntry entry)
|
||||||
|
{
|
||||||
|
switch (entry)
|
||||||
|
{
|
||||||
|
case StorageMenuEntry.MakeDefault:
|
||||||
|
return "BlaxDefaults_TabMakeDefaultType".Translate();
|
||||||
|
case StorageMenuEntry.LoadDefault:
|
||||||
|
return "BlaxDefaults_TabLoadDefault".Translate();
|
||||||
|
case StorageMenuEntry.LoadGameDefault:
|
||||||
|
return "BlaxDefaults_TabLoadGameDefault".Translate();
|
||||||
|
default:
|
||||||
|
return "BlaxDefaults_TabForgetType".Translate();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// "New shelves start from your default." or "...from the game's default."; on a stockpile, the list of
|
||||||
|
/// every type that has a default.
|
||||||
|
/// </summary>
|
||||||
|
public static string Tooltip(IStoreSettingsParent parent)
|
||||||
|
{
|
||||||
|
List<StorageKind> kinds = KindsFor(parent);
|
||||||
|
if (kinds.Count == 0)
|
||||||
|
return null;
|
||||||
|
if (kinds[0].IsStockpile)
|
||||||
|
{
|
||||||
|
if (!BlaxDefaultsMod.StockpilesOn)
|
||||||
|
return "BlaxDefaults_TabTipStockpilesOff".Translate();
|
||||||
|
List<StorageKind> withDefault = kinds.Where(k => k.Saved != null).ToList();
|
||||||
|
if (withDefault.Count == 0)
|
||||||
|
return "BlaxDefaults_TabTipStockpilesNone".Translate();
|
||||||
|
var sb = new StringBuilder("BlaxDefaults_TabTipStockpilesSome".Translate().Resolve());
|
||||||
|
foreach (StorageKind k in withDefault)
|
||||||
|
sb.Append("\n- ").Append(k.Label.CapitalizeFirst());
|
||||||
|
if (withDefault.Count < kinds.Count)
|
||||||
|
sb.Append("\n\n").Append("BlaxDefaults_TabTipStockpilesRest".Translate().Resolve());
|
||||||
|
return sb.ToString();
|
||||||
|
}
|
||||||
|
StorageKind kind = kinds[0];
|
||||||
|
if (!BlaxDefaultsMod.StorageOn)
|
||||||
|
return "BlaxDefaults_TabTipStorageOff".Translate(kind.LabelPlural);
|
||||||
|
return (kind.Saved != null ? "BlaxDefaults_TabTipYours" : "BlaxDefaults_TabTipGame").Translate(kind.LabelPlural);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Saves kind.Capture(settings) under the kind's key, keeping the names of the previous default that
|
||||||
|
/// don't resolve now (an inactive mod or DLC), as the edit window does.
|
||||||
|
/// </summary>
|
||||||
|
public static void MakeDefault(StorageKind kind, StorageSettings settings)
|
||||||
|
{
|
||||||
|
if (kind == null || settings == null)
|
||||||
|
return;
|
||||||
|
StorageTemplate t = kind.Capture(settings);
|
||||||
|
t.KeepUnresolvedFrom(kind.Saved);
|
||||||
|
DefaultsLibrary.Set(t);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The game's default for the kind, then its saved template, written onto settings.</summary>
|
||||||
|
public static void LoadDefault(StorageKind kind, StorageSettings settings)
|
||||||
|
{
|
||||||
|
if (kind == null || settings == null)
|
||||||
|
return;
|
||||||
|
kind.LoadDefault(settings, kind.Saved);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The game's default for the kind, written onto settings.</summary>
|
||||||
|
public static void LoadGameDefault(StorageKind kind, StorageSettings settings)
|
||||||
|
{
|
||||||
|
if (kind == null || settings == null)
|
||||||
|
return;
|
||||||
|
kind.LoadGameDefault(settings);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Forgets the kind's default; with confirm, after a Dialog_MessageBox.CreateConfirmation.</summary>
|
||||||
|
public static void Forget(StorageKind kind, bool confirm)
|
||||||
|
{
|
||||||
|
if (kind == null)
|
||||||
|
return;
|
||||||
|
if (!confirm)
|
||||||
|
{
|
||||||
|
DefaultsLibrary.Forget(kind.Key);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation(
|
||||||
|
"BlaxDefaults_TabForgetConfirm".Translate(kind.LabelPlural),
|
||||||
|
() =>
|
||||||
|
{
|
||||||
|
if (DefaultsLibrary.Forget(kind.Key))
|
||||||
|
Messages.Message("BlaxDefaults_TabForgotten".Translate(kind.LabelPlural), MessageTypeDefOf.NeutralEvent, historical: false);
|
||||||
|
},
|
||||||
|
destructive: true));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- options ---------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// <summary>A stockpile entry: opens the type submenu; disabled when no type has a default to load or forget.</summary>
|
||||||
|
private static FloatMenuOption SubmenuOption(IStoreSettingsParent parent, StorageMenuEntry entry, List<StorageKind> kinds)
|
||||||
|
{
|
||||||
|
bool enabled = !NeedsSaved(entry) || kinds.Any(k => k.Saved != null);
|
||||||
|
Action open = null;
|
||||||
|
if (enabled)
|
||||||
|
open = () => Find.WindowStack.Add(new FloatMenu(Submenu(parent, entry)));
|
||||||
|
var option = new FloatMenuOption(StockpileEntryLabel(entry), open);
|
||||||
|
if (!enabled)
|
||||||
|
option.tooltip = new TipSignal("BlaxDefaults_TabNoStockpileDefault".Translate());
|
||||||
|
return option;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>One entry for one kind. Load your default and Forget are disabled without a saved default.</summary>
|
||||||
|
private static FloatMenuOption EntryOption(IStoreSettingsParent parent, StorageMenuEntry entry, StorageKind kind, string label)
|
||||||
|
{
|
||||||
|
bool saved = kind.Saved != null;
|
||||||
|
string plural = kind.LabelPlural;
|
||||||
|
Action action = null;
|
||||||
|
string tip;
|
||||||
|
switch (entry)
|
||||||
|
{
|
||||||
|
case StorageMenuEntry.MakeDefault:
|
||||||
|
action = () => DoMakeDefault(parent, kind);
|
||||||
|
tip = "BlaxDefaults_TabMakeDefaultTip".Translate(plural);
|
||||||
|
break;
|
||||||
|
case StorageMenuEntry.LoadDefault:
|
||||||
|
if (saved)
|
||||||
|
action = () => LoadDefault(kind, SettingsOf(parent));
|
||||||
|
tip = saved ? "BlaxDefaults_TabLoadDefaultTip".Translate(plural) : "BlaxDefaults_TabNoDefault".Translate(plural);
|
||||||
|
break;
|
||||||
|
case StorageMenuEntry.LoadGameDefault:
|
||||||
|
action = () => LoadGameDefault(kind, SettingsOf(parent));
|
||||||
|
tip = "BlaxDefaults_TabLoadGameDefaultTip".Translate(plural);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
if (saved)
|
||||||
|
action = () => Forget(kind, confirm: true);
|
||||||
|
tip = saved ? "BlaxDefaults_TabForgetTip".Translate(plural) : "BlaxDefaults_TabNoDefault".Translate(plural);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
return new FloatMenuOption(label, action) { tooltip = new TipSignal(tip) };
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool NeedsSaved(StorageMenuEntry entry) => entry == StorageMenuEntry.LoadDefault || entry == StorageMenuEntry.Forget;
|
||||||
|
|
||||||
|
private static void DoMakeDefault(IStoreSettingsParent parent, StorageKind kind)
|
||||||
|
{
|
||||||
|
StorageSettings settings = SettingsOf(parent);
|
||||||
|
if (settings == null)
|
||||||
|
return;
|
||||||
|
MakeDefault(kind, settings);
|
||||||
|
if (DefaultsLibrary.LastWriteOk)
|
||||||
|
Messages.Message("BlaxDefaults_TabMadeDefault".Translate(kind.LabelPlural), MessageTypeDefOf.NeutralEvent, historical: false);
|
||||||
|
else
|
||||||
|
Messages.Message("BlaxDefaults_TabWriteFailed".Translate(), MessageTypeDefOf.RejectInput, historical: false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,305 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using HarmonyLib;
|
||||||
|
using RimWorld;
|
||||||
|
using Verse;
|
||||||
|
|
||||||
|
namespace BlaxDefaults
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// A stockpile type: the vanilla stockpile, the vanilla dumping stockpile, or a modded subclass of
|
||||||
|
/// Designator_ZoneAddStockpile, which is a type of its own. A Zone_Stockpile doesn't remember which
|
||||||
|
/// designator made it, so on a stockpile every type is offered.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class StockpileType
|
||||||
|
{
|
||||||
|
public readonly string Key;
|
||||||
|
public readonly StorageSettingsPreset Preset;
|
||||||
|
/// <summary>Null for the two vanilla types; the designator class for a modded type.</summary>
|
||||||
|
public readonly Type DesignatorType;
|
||||||
|
private readonly string moddedLabel;
|
||||||
|
|
||||||
|
public StockpileType(string key, StorageSettingsPreset preset, Type designatorType, string moddedLabel)
|
||||||
|
{
|
||||||
|
Key = key;
|
||||||
|
Preset = preset;
|
||||||
|
DesignatorType = designatorType;
|
||||||
|
this.moddedLabel = moddedLabel;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool IsVanilla => DesignatorType == null;
|
||||||
|
|
||||||
|
/// <summary>"stockpile", "dumping stockpile", or a modded designator's NewZoneLabel.</summary>
|
||||||
|
public string Label
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
if (Key == DefaultsKeys.Stockpile) return "BlaxDefaults_KindStockpile".Translate();
|
||||||
|
if (Key == DefaultsKeys.Dumping) return "BlaxDefaults_KindDumping".Translate();
|
||||||
|
return moddedLabel.NullOrEmpty() ? DesignatorType.Name : moddedLabel;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public string LabelPlural
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
if (Key == DefaultsKeys.Stockpile) return "BlaxDefaults_KindStockpilePlural".Translate();
|
||||||
|
if (Key == DefaultsKeys.Dumping) return "BlaxDefaults_KindDumpingPlural".Translate();
|
||||||
|
return StorageKinds.PluralOf(Label);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public override string ToString() => Key;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// One kind that has its own storage default: a stockpile type or a storage building def. Knows its
|
||||||
|
/// key, label, parent filter and the game's default, and loads a default onto settings.
|
||||||
|
/// </summary>
|
||||||
|
public sealed class StorageKind
|
||||||
|
{
|
||||||
|
public readonly string Key;
|
||||||
|
/// <summary>The building def, or null for a stockpile type.</summary>
|
||||||
|
public readonly ThingDef Def;
|
||||||
|
/// <summary>The stockpile type, or null for a building.</summary>
|
||||||
|
public readonly StockpileType Stockpile;
|
||||||
|
|
||||||
|
public StorageKind(ThingDef def)
|
||||||
|
{
|
||||||
|
Def = def;
|
||||||
|
Key = DefaultsKeys.ForStorage(def);
|
||||||
|
}
|
||||||
|
|
||||||
|
public StorageKind(StockpileType stockpile)
|
||||||
|
{
|
||||||
|
Stockpile = stockpile;
|
||||||
|
Key = stockpile.Key;
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool IsStockpile => Stockpile != null;
|
||||||
|
|
||||||
|
/// <summary>"shelf", "stockpile".</summary>
|
||||||
|
public string Label => Def != null ? Def.label : Stockpile.Label;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// "shelves", "stockpiles". A key BlaxDefaults_Plural_<defName> in the active language wins over
|
||||||
|
/// StorageKinds.PluralOf.
|
||||||
|
/// </summary>
|
||||||
|
public string LabelPlural
|
||||||
|
{
|
||||||
|
get
|
||||||
|
{
|
||||||
|
if (Def == null)
|
||||||
|
return Stockpile.LabelPlural;
|
||||||
|
string key = "BlaxDefaults_Plural_" + Def.defName;
|
||||||
|
return key.CanTranslate() ? key.Translate().Resolve() : StorageKinds.PluralOf(Def.label);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>What settings of this kind may ever allow: the building's fixedStorageSettings, else every storable item.</summary>
|
||||||
|
public ThingFilter ParentFilter => Def != null ? StorageKinds.ParentFilterFor(Def) : StorageKinds.StockpileParentFilter;
|
||||||
|
|
||||||
|
/// <summary>The saved default, or null.</summary>
|
||||||
|
public StorageTemplate Saved => DefaultsLibrary.Get<StorageTemplate>(Key);
|
||||||
|
|
||||||
|
/// <summary>A fresh scratch StorageSettings holding the game's default for this kind.</summary>
|
||||||
|
public StorageSettings GameDefault() => Def != null ? StorageKinds.GameDefaultFor(Def) : StorageKinds.GameDefaultFor(Stockpile);
|
||||||
|
|
||||||
|
/// <summary>Replaces the target's priority, filter, special filters and ranges with the game's default.</summary>
|
||||||
|
public void LoadGameDefault(StorageSettings target) => target.CopyFrom(GameDefault());
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The game's default with the template on top, written in one CopyFrom: the same settings a new
|
||||||
|
/// thing of this kind gets. Without a template, the game's default.
|
||||||
|
/// </summary>
|
||||||
|
public void LoadDefault(StorageSettings target, StorageTemplate template)
|
||||||
|
{
|
||||||
|
StorageSettings scratch = GameDefault();
|
||||||
|
template?.ApplyTo(scratch, ParentFilter);
|
||||||
|
target.CopyFrom(scratch);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A template of these settings under this kind's key (unlisted = Game), not yet saved.</summary>
|
||||||
|
public StorageTemplate Capture(StorageSettings settings) => StorageTemplate.Capture(Key, settings, ParentFilter);
|
||||||
|
|
||||||
|
public override string ToString() => Key;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The kinds Defaults covers and the game's defaults for them.</summary>
|
||||||
|
public static class StorageKinds
|
||||||
|
{
|
||||||
|
/// <summary>The protected preset field of the vanilla stockpile designators.</summary>
|
||||||
|
public static readonly AccessTools.FieldRef<Designator_ZoneAddStockpile, StorageSettingsPreset> PresetRef =
|
||||||
|
AccessTools.FieldRefAccess<Designator_ZoneAddStockpile, StorageSettingsPreset>("preset");
|
||||||
|
|
||||||
|
private static readonly Func<Designator_ZoneAdd, string> NewZoneLabelGetter =
|
||||||
|
AccessTools.MethodDelegate<Func<Designator_ZoneAdd, string>>(AccessTools.PropertyGetter(typeof(Designator_ZoneAdd), "NewZoneLabel"));
|
||||||
|
|
||||||
|
private static List<ThingDef> everStorable;
|
||||||
|
private static List<StockpileType> stockpileTypes;
|
||||||
|
|
||||||
|
public static readonly StockpileType VanillaStockpile =
|
||||||
|
new StockpileType(DefaultsKeys.Stockpile, StorageSettingsPreset.DefaultStockpile, null, null);
|
||||||
|
|
||||||
|
public static readonly StockpileType VanillaDumping =
|
||||||
|
new StockpileType(DefaultsKeys.Dumping, StorageSettingsPreset.DumpingStockpile, null, null);
|
||||||
|
|
||||||
|
/// <summary>Every def with EverStorable(willMinifyIfPossible: true), in def order. Built once.</summary>
|
||||||
|
public static List<ThingDef> EverStorableDefs =>
|
||||||
|
everStorable ??= DefDatabase<ThingDef>.AllDefsListForReading.Where(d => d.EverStorable(willMinifyIfPossible: true)).ToList();
|
||||||
|
|
||||||
|
/// <summary>Every storable def the parent filter allows (all storable defs when it is null).</summary>
|
||||||
|
public static IEnumerable<ThingDef> StorableDefs(ThingFilter parentFilter)
|
||||||
|
{
|
||||||
|
foreach (ThingDef def in EverStorableDefs)
|
||||||
|
{
|
||||||
|
if (parentFilter == null || parentFilter.Allows(def))
|
||||||
|
yield return def;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static ThingFilter StockpileParentFilter => StorageSettings.EverStorableFixedSettings().filter;
|
||||||
|
|
||||||
|
/// <summary>The vanilla stockpile, the vanilla dumping stockpile, then one type per modded stockpile designator.</summary>
|
||||||
|
public static List<StockpileType> StockpileTypes => stockpileTypes ??= BuildStockpileTypes();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The type a designator makes: _Resources and _Expand give the vanilla stockpile, _Dumping the dumping
|
||||||
|
/// stockpile, any other subclass its own type.
|
||||||
|
/// </summary>
|
||||||
|
public static StockpileType StockpileTypeOf(Designator_ZoneAddStockpile designator)
|
||||||
|
{
|
||||||
|
if (designator == null)
|
||||||
|
return null;
|
||||||
|
Type t = designator.GetType();
|
||||||
|
if (IsVanillaStockpileDesignator(t))
|
||||||
|
return PresetRef(designator) == StorageSettingsPreset.DumpingStockpile ? VanillaDumping : VanillaStockpile;
|
||||||
|
string key = DefaultsKeys.ForStockpileDesignator(t);
|
||||||
|
return StockpileTypes.FirstOrDefault(s => s.Key == key)
|
||||||
|
?? new StockpileType(key, PresetRef(designator), t, SafeNewZoneLabel(designator));
|
||||||
|
}
|
||||||
|
|
||||||
|
public static StockpileType StockpileTypeForKey(string key) => StockpileTypes.FirstOrDefault(s => s.Key == key);
|
||||||
|
|
||||||
|
public static bool IsVanillaStockpileDesignator(Type t) =>
|
||||||
|
t == typeof(Designator_ZoneAddStockpile_Resources) || t == typeof(Designator_ZoneAddStockpile_Expand) || t == typeof(Designator_ZoneAddStockpile_Dumping);
|
||||||
|
|
||||||
|
/// <summary>True when the def's blueprint is a Blueprint_Storage or a subclass: shelves, bookcases, the hopper, fridges, weapon racks.</summary>
|
||||||
|
public static bool HasStorageBlueprint(ThingDef def) =>
|
||||||
|
def?.building?.blueprintClass != null && typeof(Blueprint_Storage).IsAssignableFrom(def.building.blueprintClass);
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Building kinds that get a default when made and a Defaults button. 1.0: defs with a storage
|
||||||
|
/// blueprint. 1.1 widens this to every def with a storage tab.
|
||||||
|
/// </summary>
|
||||||
|
public static bool IsCovered(ThingDef def) => HasStorageBlueprint(def);
|
||||||
|
|
||||||
|
/// <summary>Every covered building def, in def order.</summary>
|
||||||
|
public static IEnumerable<ThingDef> CoveredDefs() => DefDatabase<ThingDef>.AllDefsListForReading.Where(IsCovered);
|
||||||
|
|
||||||
|
public static ThingFilter ParentFilterFor(ThingDef def) =>
|
||||||
|
def?.building?.fixedStorageSettings?.filter ?? StockpileParentFilter;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The game's default for a building on a scratch StorageSettings: a copy of
|
||||||
|
/// def.building.defaultStorageSettings, or, when the def has none, an empty filter at the priority a
|
||||||
|
/// fresh StorageSettings(parent) takes (the fixed settings' priority, else Normal), as PostMake leaves it.
|
||||||
|
/// Defaults never edits defaultStorageSettings, so this always holds the loaded value.
|
||||||
|
/// </summary>
|
||||||
|
public static StorageSettings GameDefaultFor(ThingDef def)
|
||||||
|
{
|
||||||
|
var s = new StorageSettings();
|
||||||
|
StorageSettings d = def?.building?.defaultStorageSettings;
|
||||||
|
if (d != null)
|
||||||
|
s.CopyFrom(d);
|
||||||
|
else
|
||||||
|
s.Priority = def?.building?.fixedStorageSettings?.Priority ?? StoragePriority.Normal;
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The game's default for a stockpile type: SetFromPreset with its preset at Normal, as the Zone_Stockpile constructor does.</summary>
|
||||||
|
public static StorageSettings GameDefaultFor(StockpileType type)
|
||||||
|
{
|
||||||
|
var s = new StorageSettings();
|
||||||
|
s.SetFromPreset(type?.Preset ?? StorageSettingsPreset.DefaultStockpile);
|
||||||
|
s.Priority = StoragePriority.Normal;
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The plural of a kind's label for the menu, tooltips and the settings page: the active language worker's,
|
||||||
|
/// with two fixes for English, whose rule appends "s" after any last character
|
||||||
|
/// (Verse/LanguageWorker_English.cs:140-152): a label ending in "shelf" ends in "shelves", and a note in
|
||||||
|
/// parentheses at the end stays there ("Weapon Rack (1 slot)" gives "Weapon Racks (1 slot)", not
|
||||||
|
/// "Weapon Rack (1 slot)s"). An English label that doesn't end in a letter is returned unchanged.
|
||||||
|
/// </summary>
|
||||||
|
public static string PluralOf(string label)
|
||||||
|
{
|
||||||
|
if (label.NullOrEmpty())
|
||||||
|
return label;
|
||||||
|
LanguageWorker worker = Find.ActiveLanguageWorker;
|
||||||
|
if (!(worker is LanguageWorker_English))
|
||||||
|
return worker != null ? worker.Pluralize(label) : label;
|
||||||
|
|
||||||
|
string head = label, note = "";
|
||||||
|
int open = label.LastIndexOf(" (", StringComparison.Ordinal);
|
||||||
|
if (open > 0 && label.EndsWith(")", StringComparison.Ordinal))
|
||||||
|
{
|
||||||
|
head = label.Substring(0, open);
|
||||||
|
note = label.Substring(open);
|
||||||
|
}
|
||||||
|
if (head.Length == 0 || !char.IsLetter(head[head.Length - 1]))
|
||||||
|
return label;
|
||||||
|
if (head.EndsWith("shelf", StringComparison.OrdinalIgnoreCase))
|
||||||
|
return head.Substring(0, head.Length - 1) + (char.IsUpper(head[head.Length - 1]) ? "VES" : "ves") + note;
|
||||||
|
return worker.Pluralize(head) + note;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static StorageKind ForDef(ThingDef def) => def == null ? null : new StorageKind(def);
|
||||||
|
|
||||||
|
public static StorageKind ForStockpile(StockpileType type) => type == null ? null : new StorageKind(type);
|
||||||
|
|
||||||
|
/// <summary>The kind for a library key, or null when its def or designator is not loaded.</summary>
|
||||||
|
public static StorageKind ForKey(string key)
|
||||||
|
{
|
||||||
|
if (DefaultsKeys.IsStorage(key))
|
||||||
|
return ForDef(DefDatabase<ThingDef>.GetNamedSilentFail(DefaultsKeys.NameOf(key)));
|
||||||
|
if (DefaultsKeys.IsStockpile(key))
|
||||||
|
return ForStockpile(StockpileTypeForKey(key));
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static List<StockpileType> BuildStockpileTypes()
|
||||||
|
{
|
||||||
|
var list = new List<StockpileType> { VanillaStockpile, VanillaDumping };
|
||||||
|
// Modded designators: the instances the game made for its architect menu carry their preset.
|
||||||
|
var seen = new HashSet<Type>();
|
||||||
|
foreach (DesignationCategoryDef cat in DefDatabase<DesignationCategoryDef>.AllDefsListForReading)
|
||||||
|
{
|
||||||
|
if (cat.AllResolvedDesignators == null)
|
||||||
|
continue;
|
||||||
|
foreach (Designator d in cat.AllResolvedDesignators)
|
||||||
|
{
|
||||||
|
if (!(d is Designator_ZoneAddStockpile zd) || IsVanillaStockpileDesignator(d.GetType()) || !seen.Add(d.GetType()))
|
||||||
|
continue;
|
||||||
|
list.Add(new StockpileType(DefaultsKeys.ForStockpileDesignator(d.GetType()), PresetRef(zd), d.GetType(), SafeNewZoneLabel(zd)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return list;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string SafeNewZoneLabel(Designator_ZoneAdd d)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
return NewZoneLabelGetter(d);
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,92 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using HarmonyLib;
|
||||||
|
using RimWorld;
|
||||||
|
using UnityEngine;
|
||||||
|
using Verse;
|
||||||
|
|
||||||
|
namespace BlaxDefaults
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// The "Defaults" button in the storage tab. Work package "tab" (design.md: "Defaults button in the
|
||||||
|
/// storage tab"). ITab_Shells and ITab_BiosculpterNutritionStorage don't override FillTab, so they get it
|
||||||
|
/// too. The tab is 300 by 480 contracted by 10 and the priority button takes 160 px of the 35 px top row,
|
||||||
|
/// so the button starts at x 180 in tab coordinates; when IsPrioritySettingVisible is false the top row is
|
||||||
|
/// 20 px and the button is a 20 px icon. Both end at x 274, clear of the tab's own close X:
|
||||||
|
/// InspectTabBase.DoTabGUI draws Widgets.CloseButtonFor(rect.AtZero()) before FillTab
|
||||||
|
/// (Verse/InspectTabBase.cs:61), at (width - 22, 4, 18, 18) = (278, 4, 18, 18) (Verse/Widgets.cs:1697), in
|
||||||
|
/// the same coordinates (an ImmediateWindow with Margin 0). The design's (180, 10, 110, 29) and (270, 10)
|
||||||
|
/// covered that X, which takes the click first. Clicking opens FloatMenu(StorageDefaultsMenu.OptionsFor(parent));
|
||||||
|
/// the tooltip is StorageDefaultsMenu.Tooltip(parent). No button when OptionsFor returns nothing.
|
||||||
|
/// </summary>
|
||||||
|
public static class StorageTabButton
|
||||||
|
{
|
||||||
|
public static readonly Rect ButtonRect = new Rect(180f, 10f, 94f, 29f);
|
||||||
|
public static readonly Rect IconRect = new Rect(254f, 10f, 20f, 20f);
|
||||||
|
|
||||||
|
/// <summary>The tab's close X for a tab this wide, as Widgets.CloseButtonFor places it.</summary>
|
||||||
|
public static Rect CloseXRect(float tabWidth) => new Rect(tabWidth - 18f - 4f, 4f, 18f, 18f);
|
||||||
|
|
||||||
|
private const int TooltipId = 0x42D3_7A01;
|
||||||
|
|
||||||
|
/// <summary>The protected ITab_Storage.SelStoreSettingsParent (virtual; ITab_Shells overrides it).</summary>
|
||||||
|
public static readonly Func<ITab_Storage, IStoreSettingsParent> SelStoreSettingsParent =
|
||||||
|
AccessTools.MethodDelegate<Func<ITab_Storage, IStoreSettingsParent>>(AccessTools.PropertyGetter(typeof(ITab_Storage), "SelStoreSettingsParent"));
|
||||||
|
|
||||||
|
/// <summary>The protected ITab_Storage.IsPrioritySettingVisible.</summary>
|
||||||
|
public static readonly Func<ITab_Storage, bool> IsPrioritySettingVisible =
|
||||||
|
AccessTools.MethodDelegate<Func<ITab_Storage, bool>>(AccessTools.PropertyGetter(typeof(ITab_Storage), "IsPrioritySettingVisible"));
|
||||||
|
|
||||||
|
/// <summary>Draws the button for the tab's selected parent. Called from the FillTab postfix.</summary>
|
||||||
|
public static void Draw(ITab_Storage tab)
|
||||||
|
{
|
||||||
|
IStoreSettingsParent parent = SelStoreSettingsParent(tab);
|
||||||
|
// HasButton is OptionsFor(parent).Count > 0 without building the options every frame.
|
||||||
|
if (!StorageDefaultsMenu.HasButton(parent))
|
||||||
|
return;
|
||||||
|
|
||||||
|
bool full = IsPrioritySettingVisible(tab);
|
||||||
|
Rect rect = full ? ButtonRect : IconRect;
|
||||||
|
GameFont font = Text.Font;
|
||||||
|
TextAnchor anchor = Text.Anchor;
|
||||||
|
bool clicked;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Text.Font = GameFont.Small;
|
||||||
|
clicked = full
|
||||||
|
? Widgets.ButtonText(rect, "BlaxDefaults_TabButton".Translate())
|
||||||
|
: Widgets.ButtonImage(rect, TexUI.MakeDefault);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Text.Font = font;
|
||||||
|
Text.Anchor = anchor;
|
||||||
|
}
|
||||||
|
TooltipHandler.TipRegion(rect, () => StorageDefaultsMenu.Tooltip(parent) ?? "", TooltipId);
|
||||||
|
|
||||||
|
if (clicked)
|
||||||
|
{
|
||||||
|
List<FloatMenuOption> options = StorageDefaultsMenu.OptionsFor(parent);
|
||||||
|
if (options.Count > 0)
|
||||||
|
Find.WindowStack.Add(new FloatMenu(options));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[HarmonyPatch(typeof(ITab_Storage), "FillTab")]
|
||||||
|
public static class Patch_ITab_Storage_FillTab
|
||||||
|
{
|
||||||
|
public static void Postfix(ITab_Storage __instance)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (BlaxDefaultsMod.Enabled)
|
||||||
|
StorageTabButton.Draw(__instance);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
HookGuard.Report("ITab_Storage.FillTab", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,227 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Globalization;
|
||||||
|
using RimWorld;
|
||||||
|
using Verse;
|
||||||
|
|
||||||
|
namespace BlaxDefaults
|
||||||
|
{
|
||||||
|
/// <summary>What a storage default does with items it lists in neither "allowed" nor "refused".</summary>
|
||||||
|
public enum UnlistedRule
|
||||||
|
{
|
||||||
|
/// <summary>Follow the game's default for the kind. What "Make default" saves.</summary>
|
||||||
|
Game,
|
||||||
|
/// <summary>Refuse them. What the quick setup saves, so an empty shelf stays empty when a mod adds items.</summary>
|
||||||
|
Refuse,
|
||||||
|
Allow,
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class UnlistedRuleExtensions
|
||||||
|
{
|
||||||
|
public static string Label(this UnlistedRule rule) => ("BlaxDefaults_Unlisted" + rule).Translate();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A storage default for a stockpile type or a storage building: the priority, every item it allows and
|
||||||
|
/// every item it refuses (ThingDef names), a rule for items it lists in neither, the special filters,
|
||||||
|
/// and the hit points and quality ranges. Never a deep-saved ThingFilter: ThingFilter.ExposeData
|
||||||
|
/// resolves defs, and a missing one would break the load.
|
||||||
|
/// </summary>
|
||||||
|
public class StorageTemplate : DefaultsEntry
|
||||||
|
{
|
||||||
|
/// <summary>StoragePriority enum name. An unknown name leaves the priority alone.</summary>
|
||||||
|
public string priority = nameof(StoragePriority.Normal);
|
||||||
|
public List<string> allowed = new List<string>();
|
||||||
|
public List<string> refused = new List<string>();
|
||||||
|
public UnlistedRule unlisted = UnlistedRule.Game;
|
||||||
|
public List<string> allowedSpecial = new List<string>();
|
||||||
|
public List<string> refusedSpecial = new List<string>();
|
||||||
|
public FloatRange hitPoints = FloatRange.ZeroToOne;
|
||||||
|
public QualityRange quality = QualityRange.All;
|
||||||
|
|
||||||
|
public StorageTemplate()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public StorageTemplate(string key)
|
||||||
|
{
|
||||||
|
this.key = key;
|
||||||
|
}
|
||||||
|
|
||||||
|
public StoragePriority Priority
|
||||||
|
{
|
||||||
|
get => Enum.TryParse(priority, out StoragePriority p) && p != StoragePriority.Unstored ? p : StoragePriority.Normal;
|
||||||
|
set => priority = value.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void ExposeData()
|
||||||
|
{
|
||||||
|
base.ExposeData();
|
||||||
|
Scribe_Values.Look(ref priority, "priority", nameof(StoragePriority.Normal));
|
||||||
|
Scribe_Collections.Look(ref allowed, "allowed", LookMode.Value);
|
||||||
|
Scribe_Collections.Look(ref refused, "refused", LookMode.Value);
|
||||||
|
// As a string, so a rule a later version adds loads as Game instead of logging a parse error.
|
||||||
|
string rule = unlisted.ToString();
|
||||||
|
Scribe_Values.Look(ref rule, "unlisted", nameof(UnlistedRule.Game));
|
||||||
|
Scribe_Collections.Look(ref allowedSpecial, "allowedSpecial", LookMode.Value);
|
||||||
|
Scribe_Collections.Look(ref refusedSpecial, "refusedSpecial", LookMode.Value);
|
||||||
|
Scribe_Values.Look(ref hitPoints, "hitPoints", FloatRange.ZeroToOne);
|
||||||
|
Scribe_Values.Look(ref quality, "quality", QualityRange.All);
|
||||||
|
if (Scribe.mode == LoadSaveMode.LoadingVars)
|
||||||
|
{
|
||||||
|
unlisted = Enum.TryParse(rule, out UnlistedRule r) ? r : UnlistedRule.Game;
|
||||||
|
allowed ??= new List<string>();
|
||||||
|
refused ??= new List<string>();
|
||||||
|
allowedSpecial ??= new List<string>();
|
||||||
|
refusedSpecial ??= new List<string>();
|
||||||
|
priority ??= nameof(StoragePriority.Normal);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public override DefaultsEntry Clone() => new StorageTemplate(key)
|
||||||
|
{
|
||||||
|
priority = priority,
|
||||||
|
allowed = CopyList(allowed),
|
||||||
|
refused = CopyList(refused),
|
||||||
|
unlisted = unlisted,
|
||||||
|
allowedSpecial = CopyList(allowedSpecial),
|
||||||
|
refusedSpecial = CopyList(refusedSpecial),
|
||||||
|
hitPoints = hitPoints,
|
||||||
|
quality = quality,
|
||||||
|
};
|
||||||
|
|
||||||
|
public StorageTemplate CloneTemplate() => (StorageTemplate)Clone();
|
||||||
|
|
||||||
|
public override string Fingerprint() => key + "|" + ContentFingerprint();
|
||||||
|
|
||||||
|
/// <summary>The fingerprint without the key: equal for two templates that set the same settings.</summary>
|
||||||
|
public string ContentFingerprint() =>
|
||||||
|
priority + "|a:" + SortedJoin(allowed) + "|r:" + SortedJoin(refused) + "|u:" + unlisted
|
||||||
|
+ "|as:" + SortedJoin(allowedSpecial) + "|rs:" + SortedJoin(refusedSpecial)
|
||||||
|
+ "|hp:" + hitPoints.min.ToString("R", CultureInfo.InvariantCulture) + "~" + hitPoints.max.ToString("R", CultureInfo.InvariantCulture)
|
||||||
|
+ "|q:" + quality.min + "~" + quality.max;
|
||||||
|
|
||||||
|
public bool SameSettingsAs(StorageTemplate other) => other != null && ContentFingerprint() == other.ContentFingerprint();
|
||||||
|
|
||||||
|
public override IEnumerable<string> UnresolvedNames()
|
||||||
|
{
|
||||||
|
foreach (string n in allowed)
|
||||||
|
if (DefDatabase<ThingDef>.GetNamedSilentFail(n) == null) yield return n;
|
||||||
|
foreach (string n in refused)
|
||||||
|
if (DefDatabase<ThingDef>.GetNamedSilentFail(n) == null) yield return n;
|
||||||
|
foreach (string n in allowedSpecial)
|
||||||
|
if (DefDatabase<SpecialThingFilterDef>.GetNamedSilentFail(n) == null) yield return n;
|
||||||
|
foreach (string n in refusedSpecial)
|
||||||
|
if (DefDatabase<SpecialThingFilterDef>.GetNamedSilentFail(n) == null) yield return n;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Adds every name of the other template that doesn't resolve now (an inactive mod or DLC) to the list it
|
||||||
|
/// was in there, unless this template lists it already. Capture lists loaded defs only, so a default saved
|
||||||
|
/// over an older one calls this to keep that mod's items in the file (design.md: "Items from a mod you
|
||||||
|
/// removed stay in the file"). Used by "Make default" in the storage tab and by the edit window's Save.
|
||||||
|
/// </summary>
|
||||||
|
public void KeepUnresolvedFrom(StorageTemplate other)
|
||||||
|
{
|
||||||
|
if (other == null)
|
||||||
|
return;
|
||||||
|
KeepUnresolved(other.allowed, allowed, IsThingDef);
|
||||||
|
KeepUnresolved(other.refused, refused, IsThingDef);
|
||||||
|
KeepUnresolved(other.allowedSpecial, allowedSpecial, IsSpecialFilterDef);
|
||||||
|
KeepUnresolved(other.refusedSpecial, refusedSpecial, IsSpecialFilterDef);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool IsThingDef(string name) => DefDatabase<ThingDef>.GetNamedSilentFail(name) != null;
|
||||||
|
|
||||||
|
private static bool IsSpecialFilterDef(string name) => DefDatabase<SpecialThingFilterDef>.GetNamedSilentFail(name) != null;
|
||||||
|
|
||||||
|
private static void KeepUnresolved(List<string> from, List<string> to, Func<string, bool> resolves)
|
||||||
|
{
|
||||||
|
if (from == null)
|
||||||
|
return;
|
||||||
|
foreach (string name in from)
|
||||||
|
{
|
||||||
|
if (!name.NullOrEmpty() && !resolves(name) && !to.Contains(name))
|
||||||
|
to.Add(name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A template of these settings: every storable def the parent filter allows goes into "allowed" or
|
||||||
|
/// "refused", every configurable special filter into "allowedSpecial" or "refusedSpecial", and the
|
||||||
|
/// rule for unlisted items is Game. A template never names a def the parent refuses.
|
||||||
|
/// </summary>
|
||||||
|
public static StorageTemplate Capture(string key, StorageSettings settings, ThingFilter parentFilter)
|
||||||
|
{
|
||||||
|
var t = new StorageTemplate(key) { Priority = settings.Priority, unlisted = UnlistedRule.Game };
|
||||||
|
ThingFilter f = settings.filter;
|
||||||
|
foreach (ThingDef def in StorageKinds.StorableDefs(parentFilter))
|
||||||
|
(f.Allows(def) ? t.allowed : t.refused).Add(def.defName);
|
||||||
|
foreach (SpecialThingFilterDef sf in DefDatabase<SpecialThingFilterDef>.AllDefsListForReading)
|
||||||
|
{
|
||||||
|
if (sf.configurable)
|
||||||
|
(f.Allows(sf) ? t.allowedSpecial : t.refusedSpecial).Add(sf.defName);
|
||||||
|
}
|
||||||
|
t.hitPoints = f.AllowedHitPointsPercents;
|
||||||
|
t.quality = f.AllowedQualityLevels;
|
||||||
|
return t;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Writes the template onto settings that already hold the game's default for the kind (on a new
|
||||||
|
/// thing, what vanilla just set). The priority goes through the Priority setter; allowed names are
|
||||||
|
/// set only where the parent filter allows them; storable defs the parent allows that the template
|
||||||
|
/// lists in neither list follow the unlisted rule. The changes are made on a scratch copy and written
|
||||||
|
/// back with one CopyFrom, so a stockpile in play recalculates its haulables once, not per def.
|
||||||
|
/// </summary>
|
||||||
|
public void ApplyTo(StorageSettings target, ThingFilter parentFilter)
|
||||||
|
{
|
||||||
|
var scratch = new StorageSettings();
|
||||||
|
scratch.CopyFrom(target);
|
||||||
|
ApplyToScratch(scratch, parentFilter);
|
||||||
|
target.CopyFrom(scratch);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void ApplyToScratch(StorageSettings s, ThingFilter parentFilter)
|
||||||
|
{
|
||||||
|
s.Priority = Priority;
|
||||||
|
ThingFilter f = s.filter;
|
||||||
|
var listed = new HashSet<string>(allowed, StringComparer.Ordinal);
|
||||||
|
listed.UnionWith(refused);
|
||||||
|
foreach (string name in allowed)
|
||||||
|
{
|
||||||
|
ThingDef def = DefDatabase<ThingDef>.GetNamedSilentFail(name);
|
||||||
|
if (def != null && (parentFilter == null || parentFilter.Allows(def)))
|
||||||
|
f.SetAllow(def, true);
|
||||||
|
}
|
||||||
|
foreach (string name in refused)
|
||||||
|
{
|
||||||
|
ThingDef def = DefDatabase<ThingDef>.GetNamedSilentFail(name);
|
||||||
|
if (def != null)
|
||||||
|
f.SetAllow(def, false);
|
||||||
|
}
|
||||||
|
if (unlisted != UnlistedRule.Game)
|
||||||
|
{
|
||||||
|
foreach (ThingDef def in StorageKinds.StorableDefs(parentFilter))
|
||||||
|
{
|
||||||
|
if (!listed.Contains(def.defName))
|
||||||
|
f.SetAllow(def, unlisted == UnlistedRule.Allow);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
foreach (string name in allowedSpecial)
|
||||||
|
{
|
||||||
|
SpecialThingFilterDef sf = DefDatabase<SpecialThingFilterDef>.GetNamedSilentFail(name);
|
||||||
|
if (sf != null)
|
||||||
|
f.SetAllow(sf, true);
|
||||||
|
}
|
||||||
|
foreach (string name in refusedSpecial)
|
||||||
|
{
|
||||||
|
SpecialThingFilterDef sf = DefDatabase<SpecialThingFilterDef>.GetNamedSilentFail(name);
|
||||||
|
if (sf != null)
|
||||||
|
f.SetAllow(sf, false);
|
||||||
|
}
|
||||||
|
f.AllowedHitPointsPercents = hitPoints;
|
||||||
|
f.AllowedQualityLevels = quality;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,20 @@
|
||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<ModMetaData>
|
||||||
|
<name>Blax Defaults Tests</name>
|
||||||
|
<author>Blax Gaming</author>
|
||||||
|
<packageId>blax.defaults.tests</packageId>
|
||||||
|
<supportedVersions>
|
||||||
|
<li>1.7</li>
|
||||||
|
</supportedVersions>
|
||||||
|
<modDependencies>
|
||||||
|
<li>
|
||||||
|
<packageId>blax.defaults</packageId>
|
||||||
|
<displayName>Blax Defaults</displayName>
|
||||||
|
</li>
|
||||||
|
</modDependencies>
|
||||||
|
<loadAfter>
|
||||||
|
<li>blax.defaults</li>
|
||||||
|
<li>blax.castes</li>
|
||||||
|
</loadAfter>
|
||||||
|
<description>In-game test suite for Blax Defaults. Does nothing unless the game is started with -blaxdefaultstests (see Tests/run-tests.ps1). Not for players.</description>
|
||||||
|
</ModMetaData>
|
||||||
|
|
@ -0,0 +1,25 @@
|
||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<Defs>
|
||||||
|
|
||||||
|
<!-- A storable item only the test mod adds. Quick setup tests drop it from a template's lists,
|
||||||
|
as if a mod had added it after the default was saved. In Manufactured, so a shelf's def default allows it. -->
|
||||||
|
<ThingDef ParentName="ResourceBase">
|
||||||
|
<defName>BlaxTest_Widget</defName>
|
||||||
|
<label>test widget</label>
|
||||||
|
<description>Test item of the Blax Defaults test suite.</description>
|
||||||
|
<graphicData>
|
||||||
|
<texPath>Things/Item/Resource/ComponentIndustrial</texPath>
|
||||||
|
<graphicClass>Graphic_StackCount</graphicClass>
|
||||||
|
</graphicData>
|
||||||
|
<stackLimit>50</stackLimit>
|
||||||
|
<statBases>
|
||||||
|
<MaxHitPoints>70</MaxHitPoints>
|
||||||
|
<MarketValue>1</MarketValue>
|
||||||
|
<Mass>0.1</Mass>
|
||||||
|
</statBases>
|
||||||
|
<thingCategories>
|
||||||
|
<li>Manufactured</li>
|
||||||
|
</thingCategories>
|
||||||
|
</ThingDef>
|
||||||
|
|
||||||
|
</Defs>
|
||||||
|
|
@ -0,0 +1,452 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using BlaxDefaults;
|
||||||
|
using RimWorld;
|
||||||
|
using Verse;
|
||||||
|
|
||||||
|
namespace BlaxDefaultsTests
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Work package "bills". The tests of design.md: Values for every new bill.
|
||||||
|
/// Methods: [BlaxTest("<area>: <what>", phase: N)] public static void X(). Skip DLC-only checks with
|
||||||
|
/// Fixtures.NeedDlc(DlcSupport.Biotech) ("skipped: needs Biotech").
|
||||||
|
/// Headless tests call BillUtility.MakeNewBill directly; whether the Bills tab's add menu reaches the
|
||||||
|
/// postfix (the JIT may inline MakeNewBill there) needs a manual check in game.
|
||||||
|
/// </summary>
|
||||||
|
public static class BillsTests
|
||||||
|
{
|
||||||
|
private const string StoveCarry = "bills.stove";
|
||||||
|
|
||||||
|
// ---- the postfix on MakeNewBill ------------------------------------------------------------------
|
||||||
|
|
||||||
|
[BlaxTest("bills: drop on floor, radius 30, do until 20 on a new simple meal bill; values not set stay vanilla")]
|
||||||
|
public static void EveryBillValues()
|
||||||
|
{
|
||||||
|
Fixtures.Save(DropRadiusUntil20());
|
||||||
|
RecipeDef recipe = Recipe("CookMealSimple");
|
||||||
|
Bill_Production bill = MakeNew(recipe);
|
||||||
|
T.Equal(typeof(Bill_Production), bill.GetType(), "bill type");
|
||||||
|
T.Equal(BillStoreModeDefOf.DropOnFloor, bill.GetStoreMode(), "store mode");
|
||||||
|
T.Check(bill.GetSlotGroup() == null, "the bill has a store group");
|
||||||
|
T.Equal(30f, bill.ingredientSearchRadius, "ingredient radius");
|
||||||
|
T.Equal(BillRepeatModeDefOf.TargetCount, bill.repeatMode, "repeat mode");
|
||||||
|
T.Equal(20, bill.targetCount, "target count");
|
||||||
|
SameExcept(bill, new Bill_Production(recipe), "storeMode", "ingredientSearchRadius", "repeatMode", "targetCount");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("bills: a bill with an unfinished thing (Bill_ProductionWithUft) gets the values too")]
|
||||||
|
public static void UftBill()
|
||||||
|
{
|
||||||
|
Fixtures.Save(DropRadiusUntil20());
|
||||||
|
RecipeDef recipe = DefDatabase<RecipeDef>.GetNamedSilentFail("Make_ComponentIndustrial")
|
||||||
|
?? DefDatabase<RecipeDef>.AllDefs.FirstOrDefault(r => VanillaBillType(r) == typeof(Bill_ProductionWithUft));
|
||||||
|
Fixtures.NeedDef(recipe, "a recipe with an unfinished thing");
|
||||||
|
Bill_Production bill = MakeNew(recipe);
|
||||||
|
T.Equal(typeof(Bill_ProductionWithUft), bill.GetType(), "bill type of " + recipe.defName);
|
||||||
|
T.Equal(BillStoreModeDefOf.DropOnFloor, bill.GetStoreMode(), "store mode");
|
||||||
|
T.Equal(30f, bill.ingredientSearchRadius, "ingredient radius");
|
||||||
|
T.Equal(BillRepeatModeDefOf.TargetCount, bill.repeatMode, "repeat mode");
|
||||||
|
T.Equal(20, bill.targetCount, "target count");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("bills: every value is applied when set")]
|
||||||
|
public static void EveryValueApplied()
|
||||||
|
{
|
||||||
|
Fixtures.Save(AllSet());
|
||||||
|
Bill_Production bill = MakeNew(Recipe("CookMealSimple"));
|
||||||
|
T.Equal(BillRepeatModeDefOf.Forever, bill.repeatMode, "repeat mode");
|
||||||
|
T.Equal(3, bill.repeatCount, "repeat count");
|
||||||
|
T.Equal(7, bill.targetCount, "target count");
|
||||||
|
T.Equal(true, bill.pauseWhenSatisfied, "pause when satisfied");
|
||||||
|
T.Equal(2, bill.unpauseWhenYouHave, "resume at");
|
||||||
|
T.Equal(45f, bill.ingredientSearchRadius, "ingredient radius");
|
||||||
|
T.Equal(new IntRange(4, 12), bill.allowedSkillRange, "allowed skill range");
|
||||||
|
T.Equal(BillStoreModeDefOf.DropOnFloor, bill.GetStoreMode(), "store mode");
|
||||||
|
T.Equal(true, bill.includeEquipped, "count equipped");
|
||||||
|
T.Equal(true, bill.includeTainted, "count tainted");
|
||||||
|
T.Equal(new FloatRange(0.5f, 1f), bill.hpRange, "hit points range");
|
||||||
|
T.Equal(new QualityRange(QualityCategory.Good, QualityCategory.Legendary), bill.qualityRange, "quality range");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("bills: a recipe whose counter can't count products gets do X times, with the count when set")]
|
||||||
|
public static void CantCountGetsRepeatCount()
|
||||||
|
{
|
||||||
|
RecipeDef recipe = Recipe("CremateCorpse");
|
||||||
|
Fixtures.Save(DropRadiusUntil20());
|
||||||
|
Bill_Production bill = MakeNew(recipe);
|
||||||
|
T.Equal(typeof(Bill_Production), bill.GetType(), "bill type");
|
||||||
|
T.Check(!recipe.WorkerCounter.CanCountProducts(bill), "CremateCorpse can count its products; pick another recipe");
|
||||||
|
T.Equal(BillRepeatModeDefOf.RepeatCount, bill.repeatMode, "repeat mode without a count");
|
||||||
|
T.Equal(1, bill.repeatCount, "repeat count without a count (the game's)");
|
||||||
|
T.Equal(30f, bill.ingredientSearchRadius, "ingredient radius");
|
||||||
|
|
||||||
|
var withCount = DropRadiusUntil20();
|
||||||
|
withCount.setRepeatCount = true;
|
||||||
|
withCount.repeatCount = 4;
|
||||||
|
Fixtures.Save(withCount);
|
||||||
|
bill = MakeNew(recipe);
|
||||||
|
T.Equal(BillRepeatModeDefOf.RepeatCount, bill.repeatMode, "repeat mode with a count");
|
||||||
|
T.Equal(4, bill.repeatCount, "repeat count with a count");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("bills: a saved SpecificStockpile or an unknown mode name is skipped without an error")]
|
||||||
|
public static void BadNamesSkipped()
|
||||||
|
{
|
||||||
|
Fixtures.Save(new BillValues(DefaultsKeys.EveryBill)
|
||||||
|
{
|
||||||
|
storeMode = "SpecificStockpile",
|
||||||
|
repeatMode = "BlaxTest_Missing",
|
||||||
|
setIngredientSearchRadius = true,
|
||||||
|
ingredientSearchRadius = 20f,
|
||||||
|
});
|
||||||
|
Bill_Production bill = MakeNew(Recipe("CookMealSimple"));
|
||||||
|
T.Equal(BillStoreModeDefOf.BestStockpile, bill.GetStoreMode(), "store mode");
|
||||||
|
T.Equal(BillRepeatModeDefOf.RepeatCount, bill.repeatMode, "repeat mode");
|
||||||
|
T.Equal(20f, bill.ingredientSearchRadius, "ingredient radius");
|
||||||
|
T.Check(T.ErrorsSoFar().Count == 0, "errors logged: " + string.Join(" | ", T.ErrorsSoFar().Take(3)));
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("bills: a pasted bill (Bill.Clone) keeps its source's values when the saved values change")]
|
||||||
|
public static void CloneKeepsSource()
|
||||||
|
{
|
||||||
|
RecipeDef recipe = Recipe("CookMealSimple");
|
||||||
|
Fixtures.Save(DropRadiusUntil20());
|
||||||
|
Bill_Production source = MakeNew(recipe);
|
||||||
|
|
||||||
|
Fixtures.Save(new BillValues(DefaultsKeys.EveryBill)
|
||||||
|
{
|
||||||
|
storeMode = "BestStockpile",
|
||||||
|
setIngredientSearchRadius = true,
|
||||||
|
ingredientSearchRadius = 50f,
|
||||||
|
repeatMode = "Forever",
|
||||||
|
});
|
||||||
|
// As ITab_Bills pastes: Clone, then a new load id.
|
||||||
|
var pasted = (Bill_Production)source.Clone();
|
||||||
|
pasted.InitializeAfterClone();
|
||||||
|
T.Equal(BillStoreModeDefOf.DropOnFloor, pasted.GetStoreMode(), "pasted store mode");
|
||||||
|
T.Equal(30f, pasted.ingredientSearchRadius, "pasted ingredient radius");
|
||||||
|
T.Equal(BillRepeatModeDefOf.TargetCount, pasted.repeatMode, "pasted repeat mode");
|
||||||
|
T.Equal(20, pasted.targetCount, "pasted target count");
|
||||||
|
|
||||||
|
Bill_Production fresh = MakeNew(recipe);
|
||||||
|
T.Equal(50f, fresh.ingredientSearchRadius, "a new bill's radius after the change");
|
||||||
|
T.Equal(BillRepeatModeDefOf.Forever, fresh.repeatMode, "a new bill's repeat mode after the change");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("bills: surgery bills from HealthCardUtility.CreateSurgeryBill are untouched")]
|
||||||
|
public static void SurgeryUntouched()
|
||||||
|
{
|
||||||
|
Fixtures.Save(AllSet());
|
||||||
|
Pawn pawn = Fixtures.Worker();
|
||||||
|
RecipeDef recipe = Recipe("Anesthetize");
|
||||||
|
Bill_Medical bill = HealthCardUtility.CreateSurgeryBill(pawn, recipe, null, null, sendMessages: false);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
T.NotNull(bill, "the surgery bill");
|
||||||
|
T.Check(!BillDefaults.AppliesTo(bill), "AppliesTo is true for a Bill_Medical");
|
||||||
|
var vanilla = new Bill_Medical(recipe, null);
|
||||||
|
T.Equal(vanilla.ingredientSearchRadius, bill.ingredientSearchRadius, "surgery ingredient radius");
|
||||||
|
T.Equal(vanilla.allowedSkillRange, bill.allowedSkillRange, "surgery skill range");
|
||||||
|
BillDefaults.OnNewBill(bill);
|
||||||
|
T.Equal(vanilla.ingredientSearchRadius, bill.ingredientSearchRadius, "surgery ingredient radius after OnNewBill");
|
||||||
|
T.Equal(vanilla.allowedSkillRange, bill.allowedSkillRange, "surgery skill range after OnNewBill");
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
if (bill != null && pawn.BillStack.Bills.Contains(bill))
|
||||||
|
pawn.BillStack.Delete(bill);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("bills: only exact Bill_Production and Bill_ProductionWithUft get the values, not their mech and forming subclasses")]
|
||||||
|
public static void ExactTypesOnly()
|
||||||
|
{
|
||||||
|
Fixtures.Save(AllSet());
|
||||||
|
RecipeDef recipe = Recipe("CookMealSimple");
|
||||||
|
foreach (Type type in new[] { typeof(Bill_Autonomous), typeof(Bill_ProductionMech), typeof(Bill_ResurrectMech) })
|
||||||
|
{
|
||||||
|
Bill_Production bill = Construct(type, recipe);
|
||||||
|
T.Check(!BillDefaults.AppliesTo(bill), "AppliesTo is true for " + type.Name);
|
||||||
|
BillDefaults.OnNewBill(bill);
|
||||||
|
SameExcept(bill, Construct(type, recipe));
|
||||||
|
}
|
||||||
|
foreach (Type type in new[] { typeof(Bill_Production), typeof(Bill_ProductionWithUft) })
|
||||||
|
{
|
||||||
|
Bill_Production bill = Construct(type, recipe);
|
||||||
|
T.Check(BillDefaults.AppliesTo(bill), "AppliesTo is false for " + type.Name);
|
||||||
|
BillDefaults.OnNewBill(bill);
|
||||||
|
T.Equal(45f, bill.ingredientSearchRadius, type.Name + " ingredient radius after OnNewBill");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("bills: mech gestation and mech resurrection bills from MakeNewBill keep vanilla values (Biotech)")]
|
||||||
|
public static void MechBillsVanilla()
|
||||||
|
{
|
||||||
|
Fixtures.NeedDlc(DlcSupport.Biotech);
|
||||||
|
Fixtures.Save(AllSet());
|
||||||
|
foreach (Type type in new[] { typeof(Bill_ProductionMech), typeof(Bill_ResurrectMech) })
|
||||||
|
{
|
||||||
|
RecipeDef recipe = DefDatabase<RecipeDef>.AllDefs.FirstOrDefault(r => VanillaBillType(r) == type);
|
||||||
|
Fixtures.NeedDef(recipe, "a recipe that makes a " + type.Name);
|
||||||
|
Bill_Production bill = MakeNew(recipe);
|
||||||
|
T.Equal(type, bill.GetType(), "bill type of " + recipe.defName);
|
||||||
|
SameExcept(bill, Construct(type, recipe));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("bills: a forming bill (Bill_Autonomous) from MakeNewBill keeps vanilla values, where a recipe makes one")]
|
||||||
|
public static void FormingBillsVanilla()
|
||||||
|
{
|
||||||
|
Fixtures.Save(AllSet());
|
||||||
|
RecipeDef recipe = DefDatabase<RecipeDef>.AllDefs.FirstOrDefault(r => VanillaBillType(r) == typeof(Bill_Autonomous));
|
||||||
|
if (recipe == null)
|
||||||
|
{
|
||||||
|
// In the installed DLCs every forming recipe also gestates; ExactTypesOnly covers the class.
|
||||||
|
T.Info("no loaded recipe makes a Bill_Autonomous; checked by ExactTypesOnly only");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
Bill_Production bill = MakeNew(recipe);
|
||||||
|
T.Equal(typeof(Bill_Autonomous), bill.GetType(), "bill type of " + recipe.defName);
|
||||||
|
SameExcept(bill, Construct(typeof(Bill_Autonomous), recipe));
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("bills: with billDefaults or enabled off, new bills keep the game's values")]
|
||||||
|
public static void OffAppliesNothing()
|
||||||
|
{
|
||||||
|
Fixtures.Save(AllSet());
|
||||||
|
RecipeDef recipe = Recipe("CookMealSimple");
|
||||||
|
|
||||||
|
Fixtures.Settings.billDefaults = false;
|
||||||
|
T.Check(!BlaxDefaultsMod.BillsOn, "BillsOn with billDefaults off");
|
||||||
|
SameExcept(MakeNew(recipe), new Bill_Production(recipe));
|
||||||
|
|
||||||
|
Fixtures.Settings.billDefaults = true;
|
||||||
|
Fixtures.Settings.enabled = false;
|
||||||
|
T.Check(!BlaxDefaultsMod.BillsOn, "BillsOn with enabled off");
|
||||||
|
SameExcept(MakeNew(recipe), new Bill_Production(recipe));
|
||||||
|
|
||||||
|
Fixtures.Settings.enabled = true;
|
||||||
|
T.Equal(45f, MakeNew(recipe).ingredientSearchRadius, "ingredient radius with both on again");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("bills: no saved values, no change")]
|
||||||
|
public static void NothingSaved()
|
||||||
|
{
|
||||||
|
DefaultsLibrary.Forget(DefaultsKeys.EveryBill);
|
||||||
|
RecipeDef recipe = Recipe("CookMealSimple");
|
||||||
|
SameExcept(MakeNew(recipe), new Bill_Production(recipe));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- the settings section's logic ----------------------------------------------------------------
|
||||||
|
|
||||||
|
[BlaxTest("bills section: setting then clearing every value forgets the bill:* entry")]
|
||||||
|
public static void SectionForgetsWhenNothingSet()
|
||||||
|
{
|
||||||
|
DefaultsLibrary.Forget(DefaultsKeys.EveryBill);
|
||||||
|
T.Check(BillValuesSection.Store(new BillValues(DefaultsKeys.EveryBill)), "storing values with nothing set failed");
|
||||||
|
T.Check(!DefaultsLibrary.Has(DefaultsKeys.EveryBill), "storing values with nothing set added an entry");
|
||||||
|
|
||||||
|
foreach (BillField f in BillValuesSection.Fields)
|
||||||
|
{
|
||||||
|
T.Check(BillValuesSection.Edit(v => BillValuesSection.Change(v, f)), "storing " + f + " failed");
|
||||||
|
T.Check(BillValuesSection.IsSet(BillDefaults.Values, f), f + " is not set after Change");
|
||||||
|
}
|
||||||
|
BillValues all = BillDefaults.Values;
|
||||||
|
T.Equal(BillValuesSection.Fields.Length, BillValuesSection.Fields.Count(f => BillValuesSection.IsSet(all, f)), "values set");
|
||||||
|
T.Equal(DefaultsKeys.EveryBill, all.key, "key");
|
||||||
|
|
||||||
|
// Change starts from the game's value: a bill made now matches a vanilla bill.
|
||||||
|
RecipeDef recipe = Recipe("CookMealSimple");
|
||||||
|
SameExcept(MakeNew(recipe), new Bill_Production(recipe));
|
||||||
|
|
||||||
|
BillValuesSection.Edit(v =>
|
||||||
|
{
|
||||||
|
v.ingredientSearchRadius = 30f;
|
||||||
|
v.repeatMode = "Forever";
|
||||||
|
});
|
||||||
|
T.Equal(30f, BillDefaults.Values.ingredientSearchRadius, "radius after an edit");
|
||||||
|
|
||||||
|
BillField last = BillValuesSection.Fields.Last();
|
||||||
|
foreach (BillField f in BillValuesSection.Fields)
|
||||||
|
{
|
||||||
|
T.Check(BillValuesSection.Edit(v => BillValuesSection.Clear(v, f)), "storing the cleared " + f + " failed");
|
||||||
|
if (f == last)
|
||||||
|
break;
|
||||||
|
BillValues now = BillDefaults.Values;
|
||||||
|
T.NotNull(now, "the entry after clearing " + f + " while other values are set");
|
||||||
|
T.Check(!BillValuesSection.IsSet(now, f), f + " is still set after Clear");
|
||||||
|
if (f == BillField.IngredientSearchRadius)
|
||||||
|
T.Equal(999f, now.ingredientSearchRadius, "radius after Clear (the game's)");
|
||||||
|
}
|
||||||
|
T.Check(!DefaultsLibrary.Has(DefaultsKeys.EveryBill), "bill:* is still saved after every value was cleared");
|
||||||
|
T.Check(BillValuesSection.Working().key == DefaultsKeys.EveryBill && !BillValuesSection.Working().AnySet, "Working after forgetting");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("bills section: every row label and text of the section is in Keyed")]
|
||||||
|
public static void SectionStrings()
|
||||||
|
{
|
||||||
|
var keys = BillValuesSection.Fields.Select(f => "BlaxDefaults_Bills_" + f).Concat(new[]
|
||||||
|
{
|
||||||
|
"BlaxDefaults_Bills_Intro", "BlaxDefaults_Bills_Off", "BlaxDefaults_Bills_TargetNote", "BlaxDefaults_Bills_ResumeNote",
|
||||||
|
"BlaxDefaults_Bills_RepeatCountTip", "BlaxDefaults_Bills_TargetOnlyTip", "BlaxDefaults_Bills_GameDefault",
|
||||||
|
"BlaxDefaults_Bills_Change", "BlaxDefaults_Bills_UseGameDefault", "BlaxDefaults_Bills_ValueOn", "BlaxDefaults_Bills_ValueOff",
|
||||||
|
"BlaxDefaults_Bills_Unlimited", "BlaxDefaults_Bills_Range", "BlaxDefaults_Bills_AnyQuality", "BlaxDefaults_Bills_ResetAll",
|
||||||
|
"BlaxDefaults_Bills_ResetAllConfirm",
|
||||||
|
});
|
||||||
|
var missing = keys.Where(k => !k.CanTranslate()).ToList();
|
||||||
|
T.Check(missing.Count == 0, "strings missing from Keyed: " + string.Join(", ", missing));
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("bills section: the resume note shows when resume at is not below the target")]
|
||||||
|
public static void SectionPauseNote()
|
||||||
|
{
|
||||||
|
var v = new BillValues(DefaultsKeys.EveryBill) { setPauseWhenSatisfied = true, pauseWhenSatisfied = true };
|
||||||
|
T.Check(!BillValuesSection.PauseNeverStarts(v), "flagged with the game's target 10 and resume 5");
|
||||||
|
v.setTargetCount = true;
|
||||||
|
v.targetCount = 5;
|
||||||
|
T.Check(BillValuesSection.PauseNeverStarts(v), "not flagged with target 5 and the game's resume 5");
|
||||||
|
v.setUnpauseWhenYouHave = true;
|
||||||
|
v.unpauseWhenYouHave = 4;
|
||||||
|
T.Check(!BillValuesSection.PauseNeverStarts(v), "flagged with target 5 and resume 4");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("bills section: forget all removes the entry, and storing unchanged values writes nothing new")]
|
||||||
|
public static void SectionForgetAll()
|
||||||
|
{
|
||||||
|
Fixtures.Save(DropRadiusUntil20());
|
||||||
|
BillValues live = BillDefaults.Values;
|
||||||
|
T.Check(BillValuesSection.Store(BillValuesSection.Working()), "storing unchanged values failed");
|
||||||
|
T.Check(ReferenceEquals(live, BillDefaults.Values), "storing unchanged values replaced the entry");
|
||||||
|
BillValuesSection.ForgetAll();
|
||||||
|
T.Check(!DefaultsLibrary.Has(DefaultsKeys.EveryBill), "bill:* is still saved after ForgetAll");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- save and reload -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
[BlaxTest("bills: a new bill on a stove keeps its values in the save (setup)")]
|
||||||
|
public static void SavedBillSetup()
|
||||||
|
{
|
||||||
|
Fixtures.Save(new BillValues(DefaultsKeys.EveryBill)
|
||||||
|
{
|
||||||
|
storeMode = "DropOnFloor",
|
||||||
|
setIngredientSearchRadius = true,
|
||||||
|
ingredientSearchRadius = 30f,
|
||||||
|
repeatMode = "Forever",
|
||||||
|
});
|
||||||
|
CellRect area = Fixtures.EmptyArea(3, 3);
|
||||||
|
var stove = (Building_WorkTable)ThingMaker.MakeThing(Fixtures.Thing("FueledStove"));
|
||||||
|
stove.SetFactionDirect(Faction.OfPlayer);
|
||||||
|
GenSpawn.Spawn(stove, area.CenterCell, Fixtures.Map);
|
||||||
|
Fixtures.Keep(Fixtures.Track(stove));
|
||||||
|
Bill bill = Recipe("CookMealSimple").MakeNewBill();
|
||||||
|
bill.suspended = true; // nobody cooks during the other tests
|
||||||
|
stove.billStack.AddBill(bill);
|
||||||
|
T.Equal(BillStoreModeDefOf.DropOnFloor, ((Bill_Production)bill).GetStoreMode(), "store mode before the save");
|
||||||
|
T.Carry[StoveCarry] = stove.ThingID;
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("bills: a new bill on a stove keeps its values in the save", phase: 2)]
|
||||||
|
public static void SavedBillReloaded()
|
||||||
|
{
|
||||||
|
T.Check(T.Carry.TryGetValue(StoveCarry, out string id), "phase 1 carried no stove");
|
||||||
|
var stove = Fixtures.FindThingById(id) as Building_WorkTable;
|
||||||
|
T.NotNull(stove, "the stove after reload");
|
||||||
|
Bill_Production bill = stove.billStack.Bills.OfType<Bill_Production>().FirstOrDefault(b => b.recipe?.defName == "CookMealSimple");
|
||||||
|
T.NotNull(bill, "the simple meal bill after reload");
|
||||||
|
T.Equal(BillStoreModeDefOf.DropOnFloor, bill.GetStoreMode(), "store mode after reload");
|
||||||
|
T.Equal(30f, bill.ingredientSearchRadius, "ingredient radius after reload");
|
||||||
|
T.Equal(BillRepeatModeDefOf.Forever, bill.repeatMode, "repeat mode after reload");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- helpers -------------------------------------------------------------------------------------
|
||||||
|
|
||||||
|
private static RecipeDef Recipe(string defName) =>
|
||||||
|
Fixtures.NeedDef(DefDatabase<RecipeDef>.GetNamedSilentFail(defName), "RecipeDef " + defName);
|
||||||
|
|
||||||
|
private static Bill_Production MakeNew(RecipeDef recipe)
|
||||||
|
{
|
||||||
|
Bill bill = recipe.MakeNewBill();
|
||||||
|
T.Check(bill is Bill_Production, "MakeNewBill(" + recipe.defName + ") returned " + (bill?.GetType().Name ?? "null"));
|
||||||
|
return (Bill_Production)bill;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A bill of this class made with its constructor, as MakeNewBill would before the postfix.</summary>
|
||||||
|
private static Bill_Production Construct(Type type, RecipeDef recipe) =>
|
||||||
|
(Bill_Production)Activator.CreateInstance(type, recipe, null);
|
||||||
|
|
||||||
|
/// <summary>The class BillUtility.MakeNewBill picks for the recipe (RimWorld/BillUtility.cs:36-55).</summary>
|
||||||
|
private static Type VanillaBillType(RecipeDef r)
|
||||||
|
{
|
||||||
|
if (r.UsesUnfinishedThing) return typeof(Bill_ProductionWithUft);
|
||||||
|
if (r.mechResurrection) return typeof(Bill_ResurrectMech);
|
||||||
|
if (r.gestationCycles > 0) return typeof(Bill_ProductionMech);
|
||||||
|
if (r.formingTicks > 0) return typeof(Bill_Autonomous);
|
||||||
|
return typeof(Bill_Production);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>"Drop on floor, radius 30, do until 20", the design's example.</summary>
|
||||||
|
private static BillValues DropRadiusUntil20() => new BillValues(DefaultsKeys.EveryBill)
|
||||||
|
{
|
||||||
|
storeMode = "DropOnFloor",
|
||||||
|
setIngredientSearchRadius = true,
|
||||||
|
ingredientSearchRadius = 30f,
|
||||||
|
repeatMode = "TargetCount",
|
||||||
|
setTargetCount = true,
|
||||||
|
targetCount = 20,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>Every value set, each to something other than the game's value.</summary>
|
||||||
|
private static BillValues AllSet() => new BillValues(DefaultsKeys.EveryBill)
|
||||||
|
{
|
||||||
|
repeatMode = "Forever",
|
||||||
|
setRepeatCount = true,
|
||||||
|
repeatCount = 3,
|
||||||
|
setTargetCount = true,
|
||||||
|
targetCount = 7,
|
||||||
|
setPauseWhenSatisfied = true,
|
||||||
|
pauseWhenSatisfied = true,
|
||||||
|
setUnpauseWhenYouHave = true,
|
||||||
|
unpauseWhenYouHave = 2,
|
||||||
|
setIngredientSearchRadius = true,
|
||||||
|
ingredientSearchRadius = 45f,
|
||||||
|
setAllowedSkillRange = true,
|
||||||
|
allowedSkillRange = new IntRange(4, 12),
|
||||||
|
storeMode = "DropOnFloor",
|
||||||
|
setIncludeEquipped = true,
|
||||||
|
includeEquipped = true,
|
||||||
|
setIncludeTainted = true,
|
||||||
|
includeTainted = true,
|
||||||
|
setHpRange = true,
|
||||||
|
hpRange = new FloatRange(0.5f, 1f),
|
||||||
|
setQualityRange = true,
|
||||||
|
qualityRange = new QualityRange(QualityCategory.Good, QualityCategory.Legendary),
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>The values a bill default can set, by name, as text.</summary>
|
||||||
|
private static Dictionary<string, string> Describe(Bill_Production b) => new Dictionary<string, string>
|
||||||
|
{
|
||||||
|
["repeatMode"] = b.repeatMode?.defName,
|
||||||
|
["repeatCount"] = b.repeatCount.ToString(),
|
||||||
|
["targetCount"] = b.targetCount.ToString(),
|
||||||
|
["pauseWhenSatisfied"] = b.pauseWhenSatisfied.ToString(),
|
||||||
|
["unpauseWhenYouHave"] = b.unpauseWhenYouHave.ToString(),
|
||||||
|
["ingredientSearchRadius"] = b.ingredientSearchRadius.ToString("R"),
|
||||||
|
["allowedSkillRange"] = b.allowedSkillRange.ToString(),
|
||||||
|
["storeMode"] = b.GetStoreMode()?.defName,
|
||||||
|
["storeGroup"] = (b.GetSlotGroup() != null).ToString(),
|
||||||
|
["includeEquipped"] = b.includeEquipped.ToString(),
|
||||||
|
["includeTainted"] = b.includeTainted.ToString(),
|
||||||
|
["hpRange"] = b.hpRange.ToString(),
|
||||||
|
["qualityRange"] = b.qualityRange.ToString(),
|
||||||
|
};
|
||||||
|
|
||||||
|
/// <summary>Fails when the bill differs from the vanilla bill in any value other than those named.</summary>
|
||||||
|
private static void SameExcept(Bill_Production actual, Bill_Production vanilla, params string[] except)
|
||||||
|
{
|
||||||
|
Dictionary<string, string> a = Describe(actual), v = Describe(vanilla);
|
||||||
|
var diffs = a.Keys.Where(k => !except.Contains(k) && a[k] != v[k]).Select(k => k + " " + a[k] + " (vanilla " + v[k] + ")").ToList();
|
||||||
|
T.Check(diffs.Count == 0, actual.GetType().Name + " " + actual.recipe?.defName + " differs from vanilla: " + string.Join(", ", diffs));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,45 @@
|
||||||
|
<Project Sdk="Microsoft.NET.Sdk">
|
||||||
|
|
||||||
|
<!-- In-game test suite. Built and run by Tests/run-tests.ps1; the DLL is not committed. -->
|
||||||
|
<PropertyGroup>
|
||||||
|
<TargetFramework>net10.0</TargetFramework>
|
||||||
|
<AssemblyName>BlaxDefaultsTests</AssemblyName>
|
||||||
|
<RootNamespace>BlaxDefaultsTests</RootNamespace>
|
||||||
|
<LangVersion>latest</LangVersion>
|
||||||
|
<Nullable>disable</Nullable>
|
||||||
|
<ImplicitUsings>disable</ImplicitUsings>
|
||||||
|
<OutputPath>..\1.7\Assemblies\</OutputPath>
|
||||||
|
<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
|
||||||
|
<AppendRuntimeIdentifierToOutputPath>false</AppendRuntimeIdentifierToOutputPath>
|
||||||
|
<GenerateDependencyFile>false</GenerateDependencyFile>
|
||||||
|
<CopyLocalLockFileAssemblies>false</CopyLocalLockFileAssemblies>
|
||||||
|
<DebugType>portable</DebugType>
|
||||||
|
<PathMap>$(MSBuildProjectDirectory)=Tests/BlaxDefaultsTests/Source</PathMap>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<PropertyGroup>
|
||||||
|
<RimWorldDir Condition="'$(RimWorldDir)' == ''">E:\SteamLibrary\steamapps\common\RimWorld</RimWorldDir>
|
||||||
|
<HarmonyDir Condition="'$(HarmonyDir)' == ''">E:\SteamLibrary\steamapps\workshop\content\294100\2009463077\1.7\Assemblies</HarmonyDir>
|
||||||
|
<BlaxDefaultsDir Condition="'$(BlaxDefaultsDir)' == ''">$(MSBuildProjectDirectory)\..\..\..\1.7\Assemblies</BlaxDefaultsDir>
|
||||||
|
</PropertyGroup>
|
||||||
|
|
||||||
|
<ItemGroup>
|
||||||
|
<Reference Include="Assembly-CSharp">
|
||||||
|
<HintPath>$(RimWorldDir)\Assembly-CSharp.dll</HintPath>
|
||||||
|
<Private>false</Private>
|
||||||
|
</Reference>
|
||||||
|
<Reference Include="UnityStubs">
|
||||||
|
<HintPath>$(RimWorldDir)\UnityStubs.dll</HintPath>
|
||||||
|
<Private>false</Private>
|
||||||
|
</Reference>
|
||||||
|
<Reference Include="0Harmony">
|
||||||
|
<HintPath>$(HarmonyDir)\0Harmony.dll</HintPath>
|
||||||
|
<Private>false</Private>
|
||||||
|
</Reference>
|
||||||
|
<Reference Include="BlaxDefaults">
|
||||||
|
<HintPath>$(BlaxDefaultsDir)\BlaxDefaults.dll</HintPath>
|
||||||
|
<Private>false</Private>
|
||||||
|
</Reference>
|
||||||
|
</ItemGroup>
|
||||||
|
|
||||||
|
</Project>
|
||||||
|
|
@ -0,0 +1,695 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.IO;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
|
using System.Xml;
|
||||||
|
using BlaxDefaults;
|
||||||
|
using RimWorld;
|
||||||
|
using UnityEngine;
|
||||||
|
using Verse;
|
||||||
|
|
||||||
|
namespace BlaxDefaultsTests
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Work package "file". The tests of design.md: Defaults library and settings page (the file tests).
|
||||||
|
/// Methods: [BlaxTest("<area>: <what>", phase: N)] public static void X(). Skip DLC-only checks with
|
||||||
|
/// Fixtures.NeedDlc(DlcSupport.Biotech) ("skipped: needs Biotech").
|
||||||
|
///
|
||||||
|
/// Every test runs in a FileSandbox: the files in Config/BlaxDefaults of the test data folder are kept,
|
||||||
|
/// the folder is emptied for the test and put back exactly afterwards, so other tests see the file they
|
||||||
|
/// left. DefaultsFile.Load and ReadFile never touch the library in memory; tests that change it through
|
||||||
|
/// DefaultsLibrary rely on the fixture restore.
|
||||||
|
/// </summary>
|
||||||
|
public static class FileTests
|
||||||
|
{
|
||||||
|
private static readonly Regex MainCopyName = new Regex(@"^Defaults\.broken-\d{8}-\d{6}(-\d+)?\.xml$");
|
||||||
|
private static readonly Regex BackupCopyName = new Regex(@"^Defaults\.bak\.broken-\d{8}-\d{6}(-\d+)?\.xml$");
|
||||||
|
|
||||||
|
[BlaxTest("file: a template with a missing name is written and read back, the name is kept and applying logs nothing")]
|
||||||
|
public static void MissingNameRoundTrip()
|
||||||
|
{
|
||||||
|
using (new FileSandbox())
|
||||||
|
{
|
||||||
|
StorageKind kind = Fixtures.Kind("Shelf");
|
||||||
|
StorageTemplate template = Fixtures.Template(kind, StoragePriority.Important, ThingDefOf.Steel);
|
||||||
|
template.allowed.Add("BlaxTest_Missing");
|
||||||
|
T.Check(DefaultsFile.Write(Entries(template)), "Write returned false");
|
||||||
|
NoTemp();
|
||||||
|
|
||||||
|
List<DefaultsEntry> back = DefaultsFile.ReadFile(DefaultsFile.FilePath);
|
||||||
|
T.NotNull(back, "ReadFile of the written file");
|
||||||
|
T.Equal(1, back.Count, "entries read back");
|
||||||
|
var loaded = back[0] as StorageTemplate;
|
||||||
|
T.NotNull(loaded, "the entry read back as a StorageTemplate");
|
||||||
|
T.Equal(template.Fingerprint(), loaded.Fingerprint(), "fingerprint read back");
|
||||||
|
T.Check(loaded.allowed.Contains("Steel") && DefDatabase<ThingDef>.GetNamedSilentFail("Steel") != null, "Steel is not in the loaded template or does not resolve");
|
||||||
|
T.Check(loaded.allowed.Contains("BlaxTest_Missing"), "the missing name was dropped");
|
||||||
|
List<string> unresolved = loaded.UnresolvedNames().ToList();
|
||||||
|
T.Equal(1, unresolved.Count, "unresolved names (" + string.Join(",", unresolved) + ")");
|
||||||
|
|
||||||
|
var target = new StorageSettings();
|
||||||
|
using (var log = new LogCounter())
|
||||||
|
{
|
||||||
|
kind.LoadDefault(target, loaded);
|
||||||
|
T.Check(log.Count == 0, "applying the template logged: " + log.Describe());
|
||||||
|
}
|
||||||
|
T.Equal(StoragePriority.Important, target.Priority, "priority after applying");
|
||||||
|
T.Check(target.filter.Allows(ThingDefOf.Steel), "Steel refused after applying");
|
||||||
|
T.Check(T.ErrorsSoFar().Count == 0, "errors: " + string.Join(" | ", T.ErrorsSoFar()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("file: a stockpile default saved with Biotech loads without it, keeps Wastepack and applies Steel silently")]
|
||||||
|
public static void BiotechNameWithoutBiotech()
|
||||||
|
{
|
||||||
|
using (new FileSandbox())
|
||||||
|
{
|
||||||
|
// The file as a game with Biotech writes it: strings only, so it is the same with or without the DLC.
|
||||||
|
File.WriteAllText(DefaultsFile.FilePath, FileText(
|
||||||
|
"\t\t<li Class=\"BlaxDefaults.StorageTemplate\">\n"
|
||||||
|
+ "\t\t\t<key>" + DefaultsKeys.Stockpile + "</key>\n"
|
||||||
|
+ "\t\t\t<priority>Normal</priority>\n"
|
||||||
|
+ "\t\t\t<allowed>\n\t\t\t\t<li>Steel</li>\n\t\t\t</allowed>\n"
|
||||||
|
+ "\t\t\t<refused>\n\t\t\t\t<li>Wastepack</li>\n\t\t\t</refused>\n"
|
||||||
|
+ "\t\t\t<allowedSpecial />\n\t\t\t<refusedSpecial />\n"
|
||||||
|
+ "\t\t</li>\n"));
|
||||||
|
|
||||||
|
bool biotech = ModsConfig.BiotechActive;
|
||||||
|
LoadResult r;
|
||||||
|
using (var log = new LogCounter())
|
||||||
|
{
|
||||||
|
r = DefaultsFile.Load();
|
||||||
|
T.Check(log.Count == 0, "loading logged: " + log.Describe());
|
||||||
|
}
|
||||||
|
T.Equal(DefaultsFile.FilePath, r.LoadedFrom, "loaded from");
|
||||||
|
T.Equal(1, r.Entries.Count, "entries loaded");
|
||||||
|
var loaded = r.Entries[0] as StorageTemplate;
|
||||||
|
T.NotNull(loaded, "the entry loaded as a StorageTemplate");
|
||||||
|
T.Check(loaded.refused.Contains("Wastepack"), "Wastepack was dropped from the template");
|
||||||
|
List<string> unresolved = loaded.UnresolvedNames().ToList();
|
||||||
|
if (biotech)
|
||||||
|
{
|
||||||
|
T.Info("Biotech is active: Wastepack resolves here; a -NoDlc run checks it as an inactive name");
|
||||||
|
T.Equal(0, unresolved.Count, "unresolved names with Biotech (" + string.Join(",", unresolved) + ")");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
T.Check(unresolved.SequenceEqual(new[] { "Wastepack" }), "unresolved names without Biotech: " + string.Join(",", unresolved));
|
||||||
|
}
|
||||||
|
|
||||||
|
StorageKind kind = Fixtures.StockpileKind;
|
||||||
|
var target = new StorageSettings();
|
||||||
|
using (var log = new LogCounter())
|
||||||
|
{
|
||||||
|
kind.LoadDefault(target, loaded);
|
||||||
|
T.Check(log.Count == 0, "applying the template logged: " + log.Describe());
|
||||||
|
}
|
||||||
|
T.Check(target.filter.Allows(ThingDefOf.Steel), "Steel refused after applying");
|
||||||
|
if (biotech)
|
||||||
|
T.Check(!target.filter.Allows(Fixtures.Thing("Wastepack")), "Wastepack allowed after applying");
|
||||||
|
|
||||||
|
// Saved again, the name stays in the file.
|
||||||
|
T.Check(DefaultsFile.Write(r.Entries), "writing the loaded entries failed");
|
||||||
|
T.Check(File.ReadAllText(DefaultsFile.FilePath).Contains("<li>Wastepack</li>"), "Wastepack is not in the file after writing it again");
|
||||||
|
List<DefaultsEntry> again = DefaultsFile.ReadFile(DefaultsFile.FilePath);
|
||||||
|
T.Check(again != null && again.Count == 1 && ((StorageTemplate)again[0]).refused.Contains("Wastepack"), "Wastepack did not read back after writing it again");
|
||||||
|
NoTemp();
|
||||||
|
T.Check(T.ErrorsSoFar().Count == 0, "errors: " + string.Join(" | ", T.ErrorsSoFar()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("file: every write leaves the previous content in .bak")]
|
||||||
|
public static void BackupHoldsPrevious()
|
||||||
|
{
|
||||||
|
using (new FileSandbox())
|
||||||
|
{
|
||||||
|
T.Check(DefaultsFile.Write(Entries(Bill(10f))), "first write failed");
|
||||||
|
T.Check(!File.Exists(DefaultsFile.BackupPath), "the first write made a .bak");
|
||||||
|
byte[] previous = File.ReadAllBytes(DefaultsFile.FilePath);
|
||||||
|
|
||||||
|
var writes = new List<List<DefaultsEntry>>
|
||||||
|
{
|
||||||
|
Entries(Bill(20f)),
|
||||||
|
Entries(Bill(30f), Fixtures.Template(Fixtures.Kind("Shelf"), StoragePriority.Low, ThingDefOf.WoodLog)),
|
||||||
|
Entries(),
|
||||||
|
};
|
||||||
|
for (int i = 0; i < writes.Count; i++)
|
||||||
|
{
|
||||||
|
T.Check(DefaultsFile.Write(writes[i]), "write " + (i + 2) + " failed");
|
||||||
|
T.Check(SameBytes(previous, File.ReadAllBytes(DefaultsFile.BackupPath)), ".bak does not hold the content before write " + (i + 2));
|
||||||
|
List<DefaultsEntry> back = DefaultsFile.ReadFile(DefaultsFile.FilePath);
|
||||||
|
T.NotNull(back, "ReadFile after write " + (i + 2));
|
||||||
|
T.Equal(Prints(writes[i]), Prints(back), "entries read back after write " + (i + 2));
|
||||||
|
previous = File.ReadAllBytes(DefaultsFile.FilePath);
|
||||||
|
}
|
||||||
|
NoTemp();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("file: main file truncated, the .bak loads with one warning and the next save keeps it")]
|
||||||
|
public static void MainBrokenBackupGood()
|
||||||
|
{
|
||||||
|
using (new FileSandbox())
|
||||||
|
{
|
||||||
|
List<DefaultsEntry> older = Entries(Bill(10f));
|
||||||
|
T.Check(DefaultsFile.Write(older), "first write failed");
|
||||||
|
T.Check(DefaultsFile.Write(Entries(Bill(20f))), "second write failed");
|
||||||
|
byte[] backup = File.ReadAllBytes(DefaultsFile.BackupPath);
|
||||||
|
byte[] truncated = Truncate(DefaultsFile.FilePath);
|
||||||
|
|
||||||
|
LoadResult r;
|
||||||
|
using (var log = new LogCounter())
|
||||||
|
{
|
||||||
|
r = DefaultsFile.Load();
|
||||||
|
T.Equal(1, log.OurWarnings, "warnings from Blax Defaults (" + log.Describe() + ")");
|
||||||
|
T.Equal(1, log.Ours, "log lines from Blax Defaults (" + log.Describe() + ")");
|
||||||
|
}
|
||||||
|
T.Equal(DefaultsFile.BackupPath, r.LoadedFrom, "loaded from");
|
||||||
|
T.Check(!r.BothFailed, "BothFailed is set although the .bak loaded");
|
||||||
|
T.Equal(Prints(older), Prints(r.Entries), "entries loaded from .bak");
|
||||||
|
T.Equal(1, r.BrokenCopies.Count, "broken copies");
|
||||||
|
T.Check(!File.Exists(DefaultsFile.FilePath), "the broken main file is still Defaults.xml");
|
||||||
|
string copy = r.BrokenCopies[0];
|
||||||
|
T.Check(MainCopyName.IsMatch(Path.GetFileName(copy)), "broken copy name: " + Path.GetFileName(copy));
|
||||||
|
T.Check(File.Exists(copy) && SameBytes(truncated, File.ReadAllBytes(copy)), "the broken copy does not hold the original bytes");
|
||||||
|
T.Check(SameBytes(backup, File.ReadAllBytes(DefaultsFile.BackupPath)), "loading changed .bak");
|
||||||
|
|
||||||
|
// A default saved afterwards: a new main file, .bak untouched.
|
||||||
|
DefaultsLibrary.ReplaceInMemory(r.Entries);
|
||||||
|
StorageTemplate shelf = Fixtures.Template(Fixtures.Kind("Shelf"), StoragePriority.Important, ThingDefOf.Steel);
|
||||||
|
T.Check(DefaultsLibrary.Set(shelf), "saving a default after the load failed");
|
||||||
|
T.Check(File.Exists(DefaultsFile.FilePath), "saving a default made no new main file");
|
||||||
|
T.Check(SameBytes(backup, File.ReadAllBytes(DefaultsFile.BackupPath)), "saving a default changed .bak");
|
||||||
|
List<DefaultsEntry> back = DefaultsFile.ReadFile(DefaultsFile.FilePath);
|
||||||
|
T.NotNull(back, "ReadFile of the new main file");
|
||||||
|
T.Equal(Prints(DefaultsLibrary.All), Prints(back), "the new main file");
|
||||||
|
T.Check(File.Exists(copy) && SameBytes(truncated, File.ReadAllBytes(copy)), "saving a default changed the broken copy");
|
||||||
|
NoTemp();
|
||||||
|
T.Check(T.ErrorsSoFar().Count == 0, "errors: " + string.Join(" | ", T.ErrorsSoFar()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("file: both files truncated, an empty library and two broken copies, twice without a clash")]
|
||||||
|
public static void BothBroken()
|
||||||
|
{
|
||||||
|
using (new FileSandbox())
|
||||||
|
{
|
||||||
|
T.Check(DefaultsFile.Write(Entries(Bill(10f))), "first write failed");
|
||||||
|
T.Check(DefaultsFile.Write(Entries(Bill(20f))), "second write failed");
|
||||||
|
byte[] mainBytes = TruncatedBytes(DefaultsFile.FilePath);
|
||||||
|
byte[] backupBytes = TruncatedBytes(DefaultsFile.BackupPath);
|
||||||
|
var copies = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||||
|
|
||||||
|
for (int round = 1; round <= 2; round++)
|
||||||
|
{
|
||||||
|
File.WriteAllBytes(DefaultsFile.FilePath, mainBytes);
|
||||||
|
File.WriteAllBytes(DefaultsFile.BackupPath, backupBytes);
|
||||||
|
LoadResult r;
|
||||||
|
using (var log = new LogCounter())
|
||||||
|
{
|
||||||
|
r = DefaultsFile.Load();
|
||||||
|
T.Equal(1, log.OurWarnings, "round " + round + ": warnings from Blax Defaults (" + log.Describe() + ")");
|
||||||
|
T.Equal(1, log.Ours, "round " + round + ": log lines from Blax Defaults (" + log.Describe() + ")");
|
||||||
|
}
|
||||||
|
T.Equal(0, r.Entries.Count, "round " + round + ": entries");
|
||||||
|
T.Check(r.BothFailed, "round " + round + ": BothFailed is not set");
|
||||||
|
T.Equal(null, r.LoadedFrom, "round " + round + ": loaded from");
|
||||||
|
T.Equal(2, r.BrokenCopies.Count, "round " + round + ": broken copies");
|
||||||
|
string mainCopy = r.BrokenCopies.FirstOrDefault(p => MainCopyName.IsMatch(Path.GetFileName(p)));
|
||||||
|
string backupCopy = r.BrokenCopies.FirstOrDefault(p => BackupCopyName.IsMatch(Path.GetFileName(p)));
|
||||||
|
T.Check(mainCopy != null && backupCopy != null, "round " + round + ": copy names " + string.Join(", ", r.BrokenCopies.Select(Path.GetFileName)));
|
||||||
|
T.Check(SameBytes(mainBytes, File.ReadAllBytes(mainCopy)), "round " + round + ": the main file's copy does not hold the original bytes");
|
||||||
|
T.Check(SameBytes(backupBytes, File.ReadAllBytes(backupCopy)), "round " + round + ": the .bak's copy does not hold the original bytes");
|
||||||
|
foreach (string c in r.BrokenCopies)
|
||||||
|
T.Check(copies.Add(c), "round " + round + ": the copy name " + Path.GetFileName(c) + " was used before");
|
||||||
|
|
||||||
|
// Nothing written: the folder holds the broken copies and nothing else.
|
||||||
|
List<string> files = Directory.GetFiles(DefaultsFile.FolderPath).ToList();
|
||||||
|
T.Check(files.Count == copies.Count && files.All(copies.Contains),
|
||||||
|
"round " + round + ": files in the folder: " + string.Join(", ", files.Select(Path.GetFileName)));
|
||||||
|
}
|
||||||
|
T.Equal(4, copies.Count, "broken copies after two loads");
|
||||||
|
T.Check(T.ErrorsSoFar().Count == 0, "errors: " + string.Join(" | ", T.ErrorsSoFar()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("file: an entry that throws while saving leaves both files untouched, no .tmp and one error")]
|
||||||
|
public static void ThrowingEntry()
|
||||||
|
{
|
||||||
|
using (new FileSandbox())
|
||||||
|
{
|
||||||
|
T.Check(DefaultsFile.Write(Entries(Bill(10f))), "first write failed");
|
||||||
|
T.Check(DefaultsFile.Write(Entries(Bill(20f))), "second write failed");
|
||||||
|
byte[] main = File.ReadAllBytes(DefaultsFile.FilePath);
|
||||||
|
byte[] backup = File.ReadAllBytes(DefaultsFile.BackupPath);
|
||||||
|
List<DefaultsEntry> before = DefaultsLibrary.Snapshot();
|
||||||
|
|
||||||
|
T.AllowErrors();
|
||||||
|
bool ok = DefaultsLibrary.Set(new BlaxTestThrowingEntry("blaxtest:throws"));
|
||||||
|
List<string> errors = T.ErrorsSoFar();
|
||||||
|
foreach (string e in errors)
|
||||||
|
T.Info("logged: " + (e.Length > 300 ? e.Substring(0, 300) + "..." : e));
|
||||||
|
T.Check(!ok, "Set returned true for an entry that throws");
|
||||||
|
T.Check(!DefaultsLibrary.LastWriteOk, "LastWriteOk is true after the failed write");
|
||||||
|
T.Check(SameBytes(main, File.ReadAllBytes(DefaultsFile.FilePath)), "Defaults.xml changed");
|
||||||
|
T.Check(SameBytes(backup, File.ReadAllBytes(DefaultsFile.BackupPath)), "Defaults.xml.bak changed");
|
||||||
|
NoTemp();
|
||||||
|
T.Equal(1, errors.Count, "errors logged by the failed write");
|
||||||
|
T.Check(errors[0].Contains("Blax Defaults"), "the error is not from Blax Defaults");
|
||||||
|
|
||||||
|
// The library back as it was, and LastWriteOk as a good write leaves it for the tests after this one.
|
||||||
|
DefaultsLibrary.ReplaceInMemory(before);
|
||||||
|
var probe = new BillValues("blaxtest:probe");
|
||||||
|
T.Check(DefaultsLibrary.Set(probe) && DefaultsLibrary.Forget(probe.key), "a write after the failed one failed");
|
||||||
|
T.Check(DefaultsLibrary.LastWriteOk, "LastWriteOk is false after a good write");
|
||||||
|
NoTemp();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("file: the format version is in the root node")]
|
||||||
|
public static void FormatVersion()
|
||||||
|
{
|
||||||
|
using (new FileSandbox())
|
||||||
|
{
|
||||||
|
T.Check(DefaultsFile.Write(Entries(Bill(10f))), "Write returned false");
|
||||||
|
var doc = new XmlDocument();
|
||||||
|
doc.Load(DefaultsFile.FilePath);
|
||||||
|
XmlElement root = doc.DocumentElement;
|
||||||
|
T.Equal(DefaultsFile.RootNode, root?.Name, "root node");
|
||||||
|
T.Equal(DefaultsLibrary.FormatVersion.ToString(), root["formatVersion"]?.InnerText, "formatVersion in the root node");
|
||||||
|
T.Equal(1, root["entries"]?.ChildNodes.Count ?? -1, "entries in the file");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("file: another root node or a keyless entry fails the read, without an error")]
|
||||||
|
public static void ReadRejects()
|
||||||
|
{
|
||||||
|
using (new FileSandbox())
|
||||||
|
{
|
||||||
|
string path = DefaultsFile.FilePath;
|
||||||
|
File.WriteAllText(path, FileText("", root: "SettingsBlock"));
|
||||||
|
T.Check(DefaultsFile.ReadFile(path) == null, "a file with another root node loaded");
|
||||||
|
|
||||||
|
File.WriteAllText(path, FileText("\t\t<li Class=\"BlaxDefaults.BillValues\">\n\t\t\t<storeMode>DropOnFloor</storeMode>\n\t\t</li>\n"));
|
||||||
|
T.Check(DefaultsFile.ReadFile(path) == null, "a keyless entry loaded");
|
||||||
|
|
||||||
|
File.WriteAllText(path, FileText("\t\t<li Class=\"BlaxDefaults.BillValues\">\n\t\t\t<key>bill:*</key>\n\t\t\t<storeMode>DropOnFloor</storeMode>\n\t\t</li>\n"));
|
||||||
|
List<DefaultsEntry> good = DefaultsFile.ReadFile(path);
|
||||||
|
T.Check(good != null && good.Count == 1 && good[0] is BillValues b && b.storeMode == "DropOnFloor", "the same entry with a key did not load");
|
||||||
|
T.Check(T.ErrorsSoFar().Count == 0, "errors: " + string.Join(" | ", T.ErrorsSoFar()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("file: a lone broken main file without a backup gives one broken copy and the one-file line")]
|
||||||
|
public static void LoneBrokenMain()
|
||||||
|
{
|
||||||
|
using (new FileSandbox())
|
||||||
|
{
|
||||||
|
T.Check(DefaultsFile.Write(Entries(Bill(10f))), "first write failed");
|
||||||
|
T.Check(!File.Exists(DefaultsFile.BackupPath), "the first write made a .bak");
|
||||||
|
byte[] truncated = Truncate(DefaultsFile.FilePath);
|
||||||
|
LoadResult r;
|
||||||
|
using (var log = new LogCounter())
|
||||||
|
{
|
||||||
|
r = DefaultsFile.Load();
|
||||||
|
T.Equal(1, log.OurWarnings, "warnings from Blax Defaults (" + log.Describe() + ")");
|
||||||
|
}
|
||||||
|
T.Check(r.BothFailed, "BothFailed is not set");
|
||||||
|
T.Equal(1, r.BrokenCopies.Count, "broken copies");
|
||||||
|
T.Equal(0, r.Unread.Count, "unread files");
|
||||||
|
T.Check(SameBytes(truncated, File.ReadAllBytes(r.BrokenCopies[0])), "the broken copy does not hold the original bytes");
|
||||||
|
string line = SettingsPage.BrokenFilesLine(r);
|
||||||
|
T.Check(line != null && line.Contains(Path.GetFileName(r.BrokenCopies[0])), "the line doesn't name the copy: " + line);
|
||||||
|
T.Check(!line.Contains("backup"), "the line refers to a backup that never existed: " + line);
|
||||||
|
T.Check(T.ErrorsSoFar().Count == 0, "errors: " + string.Join(" | ", T.ErrorsSoFar()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("file: a default of a class this version doesn't have is skipped without an error, and every write keeps it")]
|
||||||
|
public static void UnknownClassKept()
|
||||||
|
{
|
||||||
|
using (new FileSandbox())
|
||||||
|
{
|
||||||
|
const string future = "\t\t<li Class=\"BlaxDefaults.BlaxTestFutureEntry\">\n\t\t\t<key>bench:BlaxTest</key>\n"
|
||||||
|
+ "\t\t\t<bills>\n\t\t\t\t<li>Make & mend</li>\n\t\t\t</bills>\n\t\t</li>\n";
|
||||||
|
const string noClass = "\t\t<li>\n\t\t\t<key>bench:NoClass</key>\n\t\t</li>\n";
|
||||||
|
File.WriteAllText(DefaultsFile.FilePath, FileText(BillLi + future + noClass));
|
||||||
|
byte[] before = File.ReadAllBytes(DefaultsFile.FilePath);
|
||||||
|
|
||||||
|
LoadResult r;
|
||||||
|
using (var log = new LogCounter())
|
||||||
|
{
|
||||||
|
r = DefaultsFile.Load();
|
||||||
|
T.Equal(1, log.OurWarnings, "warnings from Blax Defaults (" + log.Describe() + ")");
|
||||||
|
T.Equal(1, log.Ours, "log lines from Blax Defaults (" + log.Describe() + ")");
|
||||||
|
}
|
||||||
|
T.Check(T.ErrorsSoFar().Count == 0, "loading logged errors: " + string.Join(" | ", T.ErrorsSoFar()));
|
||||||
|
T.Equal(DefaultsFile.FilePath, r.LoadedFrom, "loaded from");
|
||||||
|
T.Equal(0, r.BrokenCopies.Count, "broken copies");
|
||||||
|
T.Equal(1, r.Entries.Count, "entries this version loads");
|
||||||
|
T.Equal(2, r.Unknown.Count, "defaults skipped");
|
||||||
|
T.Equal("bench:BlaxTest", r.Unknown[0].Key, "key of the first skipped default");
|
||||||
|
T.Equal("BlaxDefaults.BlaxTestFutureEntry", r.Unknown[0].ClassName, "class of the first skipped default");
|
||||||
|
T.Equal(null, r.Unknown[1].ClassName, "class of the default without one");
|
||||||
|
T.Check(SameBytes(before, File.ReadAllBytes(DefaultsFile.FilePath)), "loading changed the file");
|
||||||
|
|
||||||
|
// Through the library, as after a startup load: two writes keep both after the library's entries.
|
||||||
|
LoadResult previous = DefaultsLibrary.LastLoad;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
DefaultsLibrary.InstallLoadForTests(r, retry: false);
|
||||||
|
T.Check(DefaultsLibrary.Set(Fixtures.Template(Fixtures.Kind("Shelf"), StoragePriority.Low, ThingDefOf.Steel)), "saving a default failed");
|
||||||
|
T.Check(DefaultsLibrary.Set(Bill(30f)), "saving a second default failed");
|
||||||
|
FileContent back = DefaultsFile.Read(DefaultsFile.FilePath, out string problem);
|
||||||
|
T.NotNull(back, "Read of the written file (" + problem + ")");
|
||||||
|
T.Equal(2, back.Entries.Count, "entries this version loads after two writes");
|
||||||
|
T.Equal(2, back.Unknown.Count, "skipped defaults in the file after two writes");
|
||||||
|
T.Equal(r.Unknown[0].Xml, back.Unknown[0].Xml, "the first skipped default after two writes");
|
||||||
|
T.Equal(r.Unknown[1].Xml, back.Unknown[1].Xml, "the second skipped default after two writes");
|
||||||
|
T.Check(File.ReadAllText(DefaultsFile.FilePath).Contains("<li>Make & mend</li>"), "the escaped text in the skipped default changed");
|
||||||
|
FileContent bak = DefaultsFile.Read(DefaultsFile.BackupPath, out problem);
|
||||||
|
T.Check(bak != null && bak.Unknown.Count == 2, ".bak lost the skipped defaults (" + problem + ")");
|
||||||
|
NoTemp();
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
DefaultsLibrary.InstallLoadForTests(previous, retry: false);
|
||||||
|
}
|
||||||
|
T.Check(T.ErrorsSoFar().Count == 0, "errors: " + string.Join(" | ", T.ErrorsSoFar()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("file: a file of a newer format version loads with one warning, and the library never writes it")]
|
||||||
|
public static void NewerVersionReadOnly()
|
||||||
|
{
|
||||||
|
using (new FileSandbox())
|
||||||
|
{
|
||||||
|
int newer = DefaultsLibrary.FormatVersion + 1;
|
||||||
|
File.WriteAllText(DefaultsFile.FilePath, FileText(BillLi, version: newer));
|
||||||
|
byte[] before = File.ReadAllBytes(DefaultsFile.FilePath);
|
||||||
|
LoadResult r;
|
||||||
|
using (var log = new LogCounter())
|
||||||
|
{
|
||||||
|
r = DefaultsFile.Load();
|
||||||
|
T.Equal(1, log.OurWarnings, "warnings from Blax Defaults (" + log.Describe() + ")");
|
||||||
|
}
|
||||||
|
T.Equal(DefaultsFile.FilePath, r.LoadedFrom, "loaded from");
|
||||||
|
T.Equal(newer, r.FormatVersion, "format version read");
|
||||||
|
T.Check(r.FromNewerVersion, "FromNewerVersion is false");
|
||||||
|
T.Equal(1, r.Entries.Count, "entries loaded");
|
||||||
|
|
||||||
|
LoadResult previous = DefaultsLibrary.LastLoad;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
DefaultsLibrary.InstallLoadForTests(r, retry: false);
|
||||||
|
T.Check(DefaultsLibrary.ReadOnly, "ReadOnly is false for a newer version's file");
|
||||||
|
StorageTemplate shelf = Fixtures.Template(Fixtures.Kind("Shelf"), StoragePriority.Low, ThingDefOf.Steel);
|
||||||
|
using (var log = new LogCounter())
|
||||||
|
{
|
||||||
|
T.Check(!DefaultsLibrary.Set(shelf), "Set reports a write of a newer version's file");
|
||||||
|
T.Check(DefaultsLibrary.Forget(DefaultsKeys.EveryBill), "Forget of the loaded bill values");
|
||||||
|
T.Equal(1, log.OurWarnings, "warnings for two refused writes (" + log.Describe() + ")");
|
||||||
|
}
|
||||||
|
T.Check(!DefaultsLibrary.LastWriteOk, "LastWriteOk is true after a refused write");
|
||||||
|
T.Check(DefaultsLibrary.Get(shelf.key) == shelf, "the default is not kept in memory");
|
||||||
|
T.Check(SameBytes(before, File.ReadAllBytes(DefaultsFile.FilePath)), "the newer version's file changed");
|
||||||
|
T.Check(!File.Exists(DefaultsFile.BackupPath), "a .bak was made");
|
||||||
|
NoTemp();
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
DefaultsLibrary.InstallLoadForTests(previous, retry: false);
|
||||||
|
// LastWriteOk back as a good write leaves it, for the tests after this one.
|
||||||
|
var probe = new BillValues("blaxtest:probe");
|
||||||
|
DefaultsLibrary.Set(probe);
|
||||||
|
DefaultsLibrary.Forget(probe.key);
|
||||||
|
}
|
||||||
|
T.Check(DefaultsLibrary.LastWriteOk, "LastWriteOk is false after a good write");
|
||||||
|
T.Check(T.ErrorsSoFar().Count == 0, "errors: " + string.Join(" | ", T.ErrorsSoFar()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("file: a read skipped at startup is retried on first use, and the next write rotates the file as usual")]
|
||||||
|
public static void SkippedReadRetried()
|
||||||
|
{
|
||||||
|
using (new FileSandbox())
|
||||||
|
{
|
||||||
|
List<DefaultsEntry> two = Entries(Bill(10f), Fixtures.Template(Fixtures.Kind("Shelf"), StoragePriority.Low, ThingDefOf.WoodLog));
|
||||||
|
T.Check(DefaultsFile.Write(two), "first write failed");
|
||||||
|
byte[] original = File.ReadAllBytes(DefaultsFile.FilePath);
|
||||||
|
|
||||||
|
LoadResult r = SkippedLoad();
|
||||||
|
T.Equal(0, r.Entries.Count, "entries of the skipped read");
|
||||||
|
T.Equal(null, r.LoadedFrom, "loaded from");
|
||||||
|
T.Check(!r.BothFailed && r.BrokenCopies.Count == 0, "the skipped read called the file broken");
|
||||||
|
T.Check(r.Unread.Contains(DefaultsFile.FilePath), "Defaults.xml is not listed as unread: " + string.Join(", ", r.Unread));
|
||||||
|
T.Check(SameBytes(original, File.ReadAllBytes(DefaultsFile.FilePath)), "the skipped read changed the file");
|
||||||
|
|
||||||
|
LoadResult previous = DefaultsLibrary.LastLoad;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
DefaultsLibrary.InstallLoadForTests(r, retry: true);
|
||||||
|
T.Check(DefaultsLibrary.RetryPending, "no retry pending after a skipped read");
|
||||||
|
T.Equal(2, DefaultsLibrary.Count, "entries after the first use");
|
||||||
|
T.Check(!DefaultsLibrary.RetryPending, "the retry is still pending after the first use");
|
||||||
|
T.Equal(DefaultsFile.FilePath, DefaultsLibrary.LastLoad.LoadedFrom, "loaded from on the retry");
|
||||||
|
T.Equal(0, DefaultsLibrary.LastLoad.Unread.Count, "unread files after the retry");
|
||||||
|
|
||||||
|
T.Check(DefaultsLibrary.Set(Bill(20f)), "saving a default after the retry failed");
|
||||||
|
T.Check(SameBytes(original, File.ReadAllBytes(DefaultsFile.BackupPath)), ".bak does not hold the file read on the retry");
|
||||||
|
List<DefaultsEntry> back = DefaultsFile.ReadFile(DefaultsFile.FilePath);
|
||||||
|
T.Check(back != null && back.Count == 2, "the new file does not hold the shelf and the new bill values");
|
||||||
|
NoTemp();
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
DefaultsLibrary.InstallLoadForTests(previous, retry: false);
|
||||||
|
}
|
||||||
|
T.Check(T.ErrorsSoFar().Count == 0, "errors: " + string.Join(" | ", T.ErrorsSoFar()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("file: files left unread are moved aside before the first write, and later writes never touch them")]
|
||||||
|
public static void UnreadMovedAside()
|
||||||
|
{
|
||||||
|
using (new FileSandbox())
|
||||||
|
{
|
||||||
|
T.Check(DefaultsFile.Write(Entries(Bill(10f), Fixtures.Template(Fixtures.Kind("Shelf"), StoragePriority.Low, ThingDefOf.WoodLog))), "first write failed");
|
||||||
|
T.Check(DefaultsFile.Write(Entries(Bill(20f), Fixtures.Template(Fixtures.Kind("Shelf"), StoragePriority.Low, ThingDefOf.WoodLog))), "second write failed");
|
||||||
|
byte[] originalMain = File.ReadAllBytes(DefaultsFile.FilePath);
|
||||||
|
byte[] originalBak = File.ReadAllBytes(DefaultsFile.BackupPath);
|
||||||
|
|
||||||
|
LoadResult r = SkippedLoad();
|
||||||
|
T.Equal(2, r.Unread.Count, "unread files (" + string.Join(", ", r.Unread) + ")");
|
||||||
|
|
||||||
|
LoadResult previous = DefaultsLibrary.LastLoad;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
// As if the retry could not read them either.
|
||||||
|
DefaultsLibrary.InstallLoadForTests(r, retry: false);
|
||||||
|
StorageTemplate shelf = Fixtures.Template(Fixtures.Kind("Shelf"), StoragePriority.Important, ThingDefOf.Steel);
|
||||||
|
T.Check(DefaultsLibrary.Set(shelf), "saving a default failed");
|
||||||
|
T.Equal(0, DefaultsLibrary.LastLoad.Unread.Count, "unread files after the first write");
|
||||||
|
List<string> moved = DefaultsLibrary.LastLoad.UnreadCopies;
|
||||||
|
T.Equal(2, moved.Count, "files moved aside");
|
||||||
|
string mainCopy = moved.FirstOrDefault(p => UnreadMainName.IsMatch(Path.GetFileName(p)));
|
||||||
|
string bakCopy = moved.FirstOrDefault(p => UnreadBackupName.IsMatch(Path.GetFileName(p)));
|
||||||
|
T.Check(mainCopy != null && bakCopy != null, "names of the moved files: " + string.Join(", ", moved.Select(Path.GetFileName)));
|
||||||
|
T.Check(SameBytes(originalMain, File.ReadAllBytes(mainCopy)), "the moved main file does not hold the original bytes");
|
||||||
|
T.Check(SameBytes(originalBak, File.ReadAllBytes(bakCopy)), "the moved .bak does not hold the original bytes");
|
||||||
|
T.Check(!File.Exists(DefaultsFile.BackupPath), "the first write left a .bak");
|
||||||
|
T.Equal(Prints(Entries(shelf)), Prints(DefaultsFile.ReadFile(DefaultsFile.FilePath)), "the new main file");
|
||||||
|
|
||||||
|
T.Check(DefaultsLibrary.Set(Bill(40f)), "saving a second default failed");
|
||||||
|
T.Check(DefaultsFile.ReadFile(DefaultsFile.BackupPath)?.Count == 1, ".bak does not hold the first write");
|
||||||
|
T.Check(SameBytes(originalMain, File.ReadAllBytes(mainCopy)) && SameBytes(originalBak, File.ReadAllBytes(bakCopy)), "the second write changed a moved file");
|
||||||
|
|
||||||
|
string line = SettingsPage.BrokenFilesLine(DefaultsLibrary.LastLoad);
|
||||||
|
T.Check(line != null && line.Contains(Path.GetFileName(mainCopy)) && line.Contains(Path.GetFileName(bakCopy)), "the page line doesn't name the moved files: " + line);
|
||||||
|
NoTemp();
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
DefaultsLibrary.InstallLoadForTests(previous, retry: false);
|
||||||
|
}
|
||||||
|
T.Check(T.ErrorsSoFar().Count == 0, "errors: " + string.Join(" | ", T.ErrorsSoFar()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- helpers ----------------------------------------------------------------------
|
||||||
|
|
||||||
|
private static readonly Regex UnreadMainName = new Regex(@"^Defaults\.unread-\d{8}-\d{6}(-\d+)?\.xml$");
|
||||||
|
private static readonly Regex UnreadBackupName = new Regex(@"^Defaults\.bak\.unread-\d{8}-\d{6}(-\d+)?\.xml$");
|
||||||
|
|
||||||
|
private const string BillLi = "\t\t<li Class=\"BlaxDefaults.BillValues\">\n\t\t\t<key>bill:*</key>\n\t\t\t<storeMode>DropOnFloor</storeMode>\n\t\t</li>\n";
|
||||||
|
|
||||||
|
/// <summary>DefaultsFile.Load while the Scribe looks busy, as when the game saves or loads: one warning, nothing read.</summary>
|
||||||
|
private static LoadResult SkippedLoad()
|
||||||
|
{
|
||||||
|
LoadResult r;
|
||||||
|
using (var log = new LogCounter())
|
||||||
|
{
|
||||||
|
Scribe.mode = LoadSaveMode.LoadingVars;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
r = DefaultsFile.Load();
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Scribe.mode = LoadSaveMode.Inactive;
|
||||||
|
}
|
||||||
|
T.Equal(1, log.OurWarnings, "warnings from the skipped read (" + log.Describe() + ")");
|
||||||
|
}
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static BillValues Bill(float radius) =>
|
||||||
|
new BillValues(DefaultsKeys.EveryBill) { setIngredientSearchRadius = true, ingredientSearchRadius = radius };
|
||||||
|
|
||||||
|
private static List<DefaultsEntry> Entries(params DefaultsEntry[] entries) => entries.ToList();
|
||||||
|
|
||||||
|
private static string Prints(IEnumerable<DefaultsEntry> entries) => string.Join("\n", entries.Select(e => e.Fingerprint()));
|
||||||
|
|
||||||
|
private static bool SameBytes(byte[] a, byte[] b) => a != null && b != null && a.SequenceEqual(b);
|
||||||
|
|
||||||
|
/// <summary>Cuts the file to half its length and returns the bytes now in it.</summary>
|
||||||
|
private static byte[] Truncate(string path)
|
||||||
|
{
|
||||||
|
byte[] half = TruncatedBytes(path);
|
||||||
|
File.WriteAllBytes(path, half);
|
||||||
|
return half;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static byte[] TruncatedBytes(string path)
|
||||||
|
{
|
||||||
|
byte[] bytes = File.ReadAllBytes(path);
|
||||||
|
return bytes.Take(bytes.Length / 2).ToArray();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string FileText(string entries, string root = DefaultsFile.RootNode, int version = 1) =>
|
||||||
|
"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<" + root + ">\n\t<formatVersion>" + version + "</formatVersion>\n"
|
||||||
|
+ (entries.Length == 0 ? "\t<entries />\n" : "\t<entries>\n" + entries + "\t</entries>\n")
|
||||||
|
+ "</" + root + ">\n";
|
||||||
|
|
||||||
|
private static void NoTemp()
|
||||||
|
{
|
||||||
|
string[] temps = Directory.GetFiles(DefaultsFile.FolderPath, "*.tmp");
|
||||||
|
T.Check(temps.Length == 0, ".tmp left in Config/BlaxDefaults: " + string.Join(", ", temps.Select(Path.GetFileName)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Keeps the files of Config/BlaxDefaults, empties the folder for the test and puts them back exactly
|
||||||
|
/// afterwards. Refuses to run outside a -savedatafolder run, so the player's own file is never touched.
|
||||||
|
/// </summary>
|
||||||
|
private sealed class FileSandbox : IDisposable
|
||||||
|
{
|
||||||
|
private readonly Dictionary<string, byte[]> kept = new Dictionary<string, byte[]>(StringComparer.OrdinalIgnoreCase);
|
||||||
|
|
||||||
|
public FileSandbox()
|
||||||
|
{
|
||||||
|
if (!GenCommandLine.TryGetCommandLineArg("savedatafolder", out string dataFolder) || dataFolder.NullOrEmpty())
|
||||||
|
T.Fail("refusing to touch Config/BlaxDefaults outside a test data folder (no -savedatafolder)");
|
||||||
|
Directory.CreateDirectory(DefaultsFile.FolderPath);
|
||||||
|
foreach (string f in Directory.GetFiles(DefaultsFile.FolderPath))
|
||||||
|
kept[Path.GetFileName(f)] = File.ReadAllBytes(f);
|
||||||
|
Empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void Empty()
|
||||||
|
{
|
||||||
|
foreach (string f in Directory.GetFiles(DefaultsFile.FolderPath))
|
||||||
|
File.Delete(f);
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Empty();
|
||||||
|
foreach (var kv in kept)
|
||||||
|
File.WriteAllBytes(Path.Combine(DefaultsFile.FolderPath, kv.Key), kv.Value);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
T.Info("putting Config/BlaxDefaults back failed: " + e.Message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The log lines (message, warning, error) while it is open: Count those of the test's own thread, so a
|
||||||
|
/// line another thread happens to log meanwhile doesn't count; OurWarnings those of Blax Defaults.
|
||||||
|
/// </summary>
|
||||||
|
private sealed class LogCounter : IDisposable
|
||||||
|
{
|
||||||
|
private static LogCounter open;
|
||||||
|
private readonly int thread = Environment.CurrentManagedThreadId;
|
||||||
|
private readonly List<(LogType type, string text, bool sameThread)> lines = new List<(LogType, string, bool)>();
|
||||||
|
|
||||||
|
public LogCounter()
|
||||||
|
{
|
||||||
|
open = this;
|
||||||
|
Application.logMessageReceivedThreaded += OnLog;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void OnLog(string text, string stack, LogType type)
|
||||||
|
{
|
||||||
|
LogCounter c = open;
|
||||||
|
if (c == null) return;
|
||||||
|
lock (c.lines) c.lines.Add((type, text ?? "", Environment.CurrentManagedThreadId == c.thread));
|
||||||
|
}
|
||||||
|
|
||||||
|
public int Count
|
||||||
|
{
|
||||||
|
get { lock (lines) return lines.Count(l => l.sameThread); }
|
||||||
|
}
|
||||||
|
|
||||||
|
public int OurWarnings
|
||||||
|
{
|
||||||
|
get { lock (lines) return lines.Count(l => l.type == LogType.Warning && l.text.Contains("[Blax Defaults]")); }
|
||||||
|
}
|
||||||
|
|
||||||
|
public int Ours
|
||||||
|
{
|
||||||
|
get { lock (lines) return lines.Count(l => l.text.Contains("[Blax Defaults]")); }
|
||||||
|
}
|
||||||
|
|
||||||
|
public string Describe()
|
||||||
|
{
|
||||||
|
lock (lines)
|
||||||
|
return lines.Count == 0 ? "nothing" : string.Join(" | ", lines.Take(5).Select(l => l.type + ": " + l.text.Replace('\n', ' ')));
|
||||||
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
Application.logMessageReceivedThreaded -= OnLog;
|
||||||
|
open = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A test-only entry whose ExposeData throws while saving (the "file" tests).</summary>
|
||||||
|
public class BlaxTestThrowingEntry : DefaultsEntry
|
||||||
|
{
|
||||||
|
public BlaxTestThrowingEntry()
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public BlaxTestThrowingEntry(string key)
|
||||||
|
{
|
||||||
|
this.key = key;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void ExposeData()
|
||||||
|
{
|
||||||
|
base.ExposeData();
|
||||||
|
if (Scribe.mode == LoadSaveMode.Saving)
|
||||||
|
throw new InvalidOperationException("BlaxTest: this entry refuses to be saved");
|
||||||
|
}
|
||||||
|
|
||||||
|
public override DefaultsEntry Clone() => new BlaxTestThrowingEntry(key);
|
||||||
|
|
||||||
|
public override string Fingerprint() => key ?? "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,241 @@
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Reflection;
|
||||||
|
using BlaxDefaults;
|
||||||
|
using RimWorld;
|
||||||
|
using Verse;
|
||||||
|
|
||||||
|
namespace BlaxDefaultsTests
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Shared helpers for tests. Things, zones and areas made here are removed after each test unless passed
|
||||||
|
/// to Keep() or KeepZone(). Mod settings and the defaults library are restored after each test (the
|
||||||
|
/// library in memory only, the file is not rewritten), so tests may change them freely. Feature-specific
|
||||||
|
/// helpers belong in the feature's own test file.
|
||||||
|
/// </summary>
|
||||||
|
public static class Fixtures
|
||||||
|
{
|
||||||
|
private static readonly List<Thing> made = new List<Thing>();
|
||||||
|
private static readonly HashSet<Thing> kept = new HashSet<Thing>();
|
||||||
|
private static readonly List<Zone> madeZones = new List<Zone>();
|
||||||
|
private static readonly HashSet<Zone> keptZones = new HashSet<Zone>();
|
||||||
|
private static readonly List<CellRect> areas = new List<CellRect>();
|
||||||
|
private static List<DefaultsEntry> librarySnapshot;
|
||||||
|
private static bool keepLibrary;
|
||||||
|
|
||||||
|
public static Map Map => Find.CurrentMap;
|
||||||
|
|
||||||
|
public static BlaxDefaultsSettings Settings => BlaxDefaultsMod.Settings;
|
||||||
|
|
||||||
|
// ---- defaults library ------------------------------------------------------------
|
||||||
|
|
||||||
|
/// <summary>Saves the entry with DefaultsLibrary.Set and returns it. Restored after the test.</summary>
|
||||||
|
public static TE Save<TE>(TE entry) where TE : DefaultsEntry
|
||||||
|
{
|
||||||
|
DefaultsLibrary.Set(entry);
|
||||||
|
return entry;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A storage template under this key that allows exactly these defs (unlisted Game), not saved.</summary>
|
||||||
|
public static StorageTemplate Template(StorageKind kind, StoragePriority priority, params ThingDef[] allow)
|
||||||
|
{
|
||||||
|
StorageSettings s = kind.GameDefault();
|
||||||
|
s.filter.SetDisallowAll();
|
||||||
|
foreach (ThingDef d in allow)
|
||||||
|
s.filter.SetAllow(d, true);
|
||||||
|
s.Priority = priority;
|
||||||
|
return kind.Capture(s);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Leave the library as this test set it (phase-1 setup for phase-2 checks).</summary>
|
||||||
|
public static void KeepLibrary() => keepLibrary = true;
|
||||||
|
|
||||||
|
public static StorageKind Kind(string thingDefName) =>
|
||||||
|
StorageKinds.ForDef(NeedDef(DefDatabase<ThingDef>.GetNamedSilentFail(thingDefName), "ThingDef " + thingDefName));
|
||||||
|
|
||||||
|
public static StorageKind StockpileKind => StorageKinds.ForStockpile(StorageKinds.VanillaStockpile);
|
||||||
|
|
||||||
|
public static StorageKind DumpingKind => StorageKinds.ForStockpile(StorageKinds.VanillaDumping);
|
||||||
|
|
||||||
|
// ---- defs ------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// <summary>A def that must exist; fails the test otherwise.</summary>
|
||||||
|
public static TD NeedDef<TD>(TD def, string what) where TD : Def
|
||||||
|
{
|
||||||
|
T.NotNull(def, what);
|
||||||
|
return def;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static ThingDef Thing(string defName) => NeedDef(DefDatabase<ThingDef>.GetNamedSilentFail(defName), "ThingDef " + defName);
|
||||||
|
|
||||||
|
/// <summary>Skips the test unless the DLC is active: "needs Biotech".</summary>
|
||||||
|
public static void NeedDlc(string dlcPackageId)
|
||||||
|
{
|
||||||
|
if (!DlcSupport.IsActive(dlcPackageId))
|
||||||
|
T.Skip("needs " + DlcSupport.DlcName(dlcPackageId));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- map, things, zones ----------------------------------------------------------
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A free area of this size near the map centre: in bounds, away from the edge, unfogged, standable,
|
||||||
|
/// heavy-supporting terrain, no zone, nothing but grass or filth, which is removed. Tracked: buildings,
|
||||||
|
/// blueprints, frames, items and zones in it are removed after the test (kept ones stay).
|
||||||
|
/// </summary>
|
||||||
|
public static CellRect EmptyArea(int width, int height)
|
||||||
|
{
|
||||||
|
Map map = Map;
|
||||||
|
foreach (IntVec3 origin in GenRadial.RadialCellsAround(map.Center, 40f, useCenter: true))
|
||||||
|
{
|
||||||
|
var rect = new CellRect(origin.x, origin.z, width, height);
|
||||||
|
if (rect.Cells.All(c => Free(c, map)))
|
||||||
|
{
|
||||||
|
foreach (IntVec3 c in rect.Cells)
|
||||||
|
foreach (Thing t in map.thingGrid.ThingsListAt(c).ToList())
|
||||||
|
t.Destroy(DestroyMode.Vanish);
|
||||||
|
areas.Add(rect);
|
||||||
|
return rect;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
T.Fail("no empty " + width + "x" + height + " area near the map centre");
|
||||||
|
return default;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool Free(IntVec3 c, Map map) =>
|
||||||
|
c.InBounds(map) && !c.CloseToEdge(map, 5) && !c.Fogged(map) && c.Standable(map)
|
||||||
|
&& c.SupportsStructureType(map, TerrainAffordanceDefOf.Heavy) && c.GetZone(map) == null
|
||||||
|
&& map.thingGrid.ThingsListAt(c).All(t => (t is Plant plant && !plant.def.plant.IsTree) || t is Filth)
|
||||||
|
&& !areas.Any(r => r.Contains(c));
|
||||||
|
|
||||||
|
/// <summary>Removes the thing after the test unless kept.</summary>
|
||||||
|
public static TT Track<TT>(TT thing) where TT : Thing
|
||||||
|
{
|
||||||
|
if (thing != null) made.Add(thing);
|
||||||
|
return thing;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static TZ TrackZone<TZ>(TZ zone) where TZ : Zone
|
||||||
|
{
|
||||||
|
if (zone != null) madeZones.Add(zone);
|
||||||
|
return zone;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Exclude a thing from the per-test cleanup (phase-1 setup for phase-2 checks).</summary>
|
||||||
|
public static TT Keep<TT>(TT thing) where TT : Thing
|
||||||
|
{
|
||||||
|
kept.Add(thing);
|
||||||
|
return thing;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static TZ KeepZone<TZ>(TZ zone) where TZ : Zone
|
||||||
|
{
|
||||||
|
keptZones.Add(zone);
|
||||||
|
return zone;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A spawned free colonist of the quick-test colony, to complete frames with.</summary>
|
||||||
|
public static Pawn Worker()
|
||||||
|
{
|
||||||
|
Pawn p = Map.mapPawns.FreeColonistsSpawned.FirstOrDefault();
|
||||||
|
T.NotNull(p, "a spawned free colonist");
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Thing FindThingById(string thingId)
|
||||||
|
{
|
||||||
|
if (thingId == null) return null;
|
||||||
|
foreach (Map m in Find.Maps)
|
||||||
|
foreach (Thing t in m.listerThings.AllThings)
|
||||||
|
if (t.ThingID == thingId) return t;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static Zone FindZoneById(int id)
|
||||||
|
{
|
||||||
|
foreach (Map m in Find.Maps)
|
||||||
|
foreach (Zone z in m.zoneManager.AllZones)
|
||||||
|
if (z.ID == id) return z;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- time ------------------------------------------------------------------------
|
||||||
|
|
||||||
|
public static void Tick(int ticks)
|
||||||
|
{
|
||||||
|
for (int i = 0; i < ticks; i++) Find.TickManager.DoSingleTick();
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void QuietStoryteller()
|
||||||
|
{
|
||||||
|
Find.Storyteller.incidentQueue.Clear();
|
||||||
|
Find.Storyteller.storytellerComps.Clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- settings and cleanup (used by the runner) -----------------------------------
|
||||||
|
|
||||||
|
public static Dictionary<FieldInfo, object> SnapshotSettings()
|
||||||
|
{
|
||||||
|
keepLibrary = false;
|
||||||
|
librarySnapshot = DefaultsLibrary.Snapshot();
|
||||||
|
var d = new Dictionary<FieldInfo, object>();
|
||||||
|
if (Settings == null) return d;
|
||||||
|
foreach (FieldInfo f in typeof(BlaxDefaultsSettings).GetFields(BindingFlags.Public | BindingFlags.Instance))
|
||||||
|
{
|
||||||
|
object v = f.GetValue(Settings);
|
||||||
|
d[f] = v is List<string> list ? new List<string>(list) : v;
|
||||||
|
}
|
||||||
|
return d;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void RestoreSettings(Dictionary<FieldInfo, object> snapshot)
|
||||||
|
{
|
||||||
|
if (Settings != null)
|
||||||
|
{
|
||||||
|
foreach (var kv in snapshot)
|
||||||
|
kv.Key.SetValue(Settings, kv.Value is List<string> list ? new List<string>(list) : kv.Value);
|
||||||
|
}
|
||||||
|
if (!keepLibrary && librarySnapshot != null)
|
||||||
|
DefaultsLibrary.RestoreForTests(librarySnapshot);
|
||||||
|
keepLibrary = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void Cleanup()
|
||||||
|
{
|
||||||
|
foreach (Thing t in made)
|
||||||
|
{
|
||||||
|
if (t != null && !kept.Contains(t) && !t.Destroyed && t.Spawned)
|
||||||
|
t.Destroy(DestroyMode.Vanish);
|
||||||
|
}
|
||||||
|
made.Clear();
|
||||||
|
|
||||||
|
foreach (Zone z in madeZones)
|
||||||
|
{
|
||||||
|
if (z != null && !keptZones.Contains(z) && z.zoneManager != null && z.zoneManager.AllZones.Contains(z))
|
||||||
|
z.Delete(playSound: false);
|
||||||
|
}
|
||||||
|
madeZones.Clear();
|
||||||
|
|
||||||
|
Map map = Map;
|
||||||
|
if (map != null)
|
||||||
|
{
|
||||||
|
foreach (CellRect rect in areas)
|
||||||
|
{
|
||||||
|
foreach (IntVec3 c in rect.Cells)
|
||||||
|
{
|
||||||
|
if (!c.InBounds(map)) continue;
|
||||||
|
Zone z = c.GetZone(map);
|
||||||
|
if (z != null && !keptZones.Contains(z))
|
||||||
|
z.Delete(playSound: false);
|
||||||
|
foreach (Thing t in map.thingGrid.ThingsListAt(c).ToList())
|
||||||
|
{
|
||||||
|
if (t is Pawn || kept.Contains(t) || t.Destroyed) continue;
|
||||||
|
if (t is Building || t is Blueprint || t is Frame || t.def.EverHaulable)
|
||||||
|
t.Destroy(DestroyMode.Vanish);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
areas.Clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,316 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.IO;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Reflection;
|
||||||
|
using RimWorld;
|
||||||
|
using UnityEngine;
|
||||||
|
using Verse;
|
||||||
|
|
||||||
|
namespace BlaxDefaultsTests
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Marks a public static void method without parameters as a test. Phase 1 runs in a fresh
|
||||||
|
/// quick-test colony. Phase 2 runs after the runner saved that game and loaded it again.
|
||||||
|
/// </summary>
|
||||||
|
[AttributeUsage(AttributeTargets.Method)]
|
||||||
|
public sealed class BlaxTestAttribute : Attribute
|
||||||
|
{
|
||||||
|
public readonly string Name;
|
||||||
|
public readonly int Phase;
|
||||||
|
|
||||||
|
public BlaxTestAttribute(string name, int phase = 1)
|
||||||
|
{
|
||||||
|
Name = name;
|
||||||
|
Phase = phase;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public class TestFailure : Exception
|
||||||
|
{
|
||||||
|
public TestFailure(string message) : base(message) { }
|
||||||
|
}
|
||||||
|
|
||||||
|
public class TestSkipped : Exception
|
||||||
|
{
|
||||||
|
public TestSkipped(string message) : base(message) { }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Assertions and notes for test bodies.</summary>
|
||||||
|
public static class T
|
||||||
|
{
|
||||||
|
/// <summary>Values carried from phase 1 into phase 2. Store ThingIDs or def names, never objects.</summary>
|
||||||
|
public static readonly Dictionary<string, string> Carry = new Dictionary<string, string>();
|
||||||
|
|
||||||
|
/// <summary>Carry values read right before the save, after every phase-1 test ran.</summary>
|
||||||
|
internal static readonly Dictionary<string, Func<string>> CarryAtSaveTime = new Dictionary<string, Func<string>>();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Carries a value read right before the save instead of now, for state that later phase-1
|
||||||
|
/// tests may still change (a library entry, for example).
|
||||||
|
/// </summary>
|
||||||
|
public static void CarryAtSave(string key, Func<string> read) => CarryAtSaveTime[key] = read;
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// The test expects Blax Defaults to log errors (a broken file, a failed write): they no longer fail it.
|
||||||
|
/// Check them with ErrorsSoFar().
|
||||||
|
/// </summary>
|
||||||
|
public static void AllowErrors() => TestRunner.errorsAllowed = true;
|
||||||
|
|
||||||
|
/// <summary>Every error and exception logged since the current test started, ours and other mods', one line each.</summary>
|
||||||
|
public static List<string> ErrorsSoFar() => TestRunner.ErrorsSinceTestStart();
|
||||||
|
|
||||||
|
public static void Check(bool condition, string message)
|
||||||
|
{
|
||||||
|
if (!condition) throw new TestFailure(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void Equal<TV>(TV expected, TV actual, string what)
|
||||||
|
{
|
||||||
|
if (!EqualityComparer<TV>.Default.Equals(expected, actual))
|
||||||
|
throw new TestFailure($"{what}: expected {Show(expected)}, got {Show(actual)}");
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void NotNull(object value, string what)
|
||||||
|
{
|
||||||
|
if (value == null) throw new TestFailure(what + " is null");
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void Fail(string message) => throw new TestFailure(message);
|
||||||
|
|
||||||
|
public static void Skip(string reason) => throw new TestSkipped(reason);
|
||||||
|
|
||||||
|
/// <summary>Adds an INFO line under the current test in the results file.</summary>
|
||||||
|
public static void Info(string message) => TestRunner.Note(message);
|
||||||
|
|
||||||
|
private static string Show(object o) => o == null ? "null" : o.ToString();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Drives the suite when the game runs with -quicktest -blaxdefaultstests: phase 1, save, load,
|
||||||
|
/// phase 2, then writes BlaxDefaultsTestResults.txt into the save data folder and quits.
|
||||||
|
/// </summary>
|
||||||
|
public class TestRunner : GameComponent
|
||||||
|
{
|
||||||
|
public const string SaveName = "BlaxDefaultsTest";
|
||||||
|
public const string ResultFile = "BlaxDefaultsTestResults.txt";
|
||||||
|
|
||||||
|
private static int stage; // 0 waiting, 1 phase 1 done + reload queued, 2 finished
|
||||||
|
private static bool reloaded;
|
||||||
|
private static int pass, fail, skip;
|
||||||
|
private static string currentTest;
|
||||||
|
private static readonly List<string> modErrors = new List<string>();
|
||||||
|
private static readonly List<string> otherErrors = new List<string>();
|
||||||
|
private static bool hooked;
|
||||||
|
private int settleFrames;
|
||||||
|
private static int testModErrorsStart, testOtherErrorsStart;
|
||||||
|
internal static bool errorsAllowed;
|
||||||
|
|
||||||
|
/// <summary>The error texts in the game's log when the suite began, so before any test: what startup logged.</summary>
|
||||||
|
internal static List<string> StartupErrors = new List<string>();
|
||||||
|
|
||||||
|
public static bool Enabled => GenCommandLine.CommandLineArgPassed("blaxdefaultstests");
|
||||||
|
|
||||||
|
public static string ResultPath => Path.Combine(GenFilePaths.SaveDataFolderPath, ResultFile);
|
||||||
|
|
||||||
|
public TestRunner(Game game) { }
|
||||||
|
|
||||||
|
public override void LoadedGame()
|
||||||
|
{
|
||||||
|
if (Enabled && stage == 1) reloaded = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public override void GameComponentUpdate()
|
||||||
|
{
|
||||||
|
if (!Enabled || stage == 2) return;
|
||||||
|
if (LongEventHandler.AnyEventNowOrWaiting || Find.CurrentMap == null) return;
|
||||||
|
if (++settleFrames < 30) return;
|
||||||
|
|
||||||
|
if (stage == 0)
|
||||||
|
{
|
||||||
|
stage = 1;
|
||||||
|
Begin();
|
||||||
|
RunPhase(1);
|
||||||
|
Line("STAGE save+reload");
|
||||||
|
try
|
||||||
|
{
|
||||||
|
foreach (var kv in T.CarryAtSaveTime)
|
||||||
|
{
|
||||||
|
try { T.Carry[kv.Key] = kv.Value(); }
|
||||||
|
catch (Exception e) { Note("carry " + kv.Key + " failed: " + e.Message); }
|
||||||
|
}
|
||||||
|
GameDataSaveLoader.SaveGame(SaveName);
|
||||||
|
GameDataSaveLoader.LoadGame(SaveName);
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
Record("FAIL", "save and reload", e.ToString());
|
||||||
|
Finish();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (stage == 1 && reloaded)
|
||||||
|
{
|
||||||
|
stage = 2;
|
||||||
|
Line("STAGE phase 2 (after reload)");
|
||||||
|
RunPhase(2);
|
||||||
|
Finish();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void Begin()
|
||||||
|
{
|
||||||
|
try { File.Delete(ResultPath); } catch { }
|
||||||
|
StartupErrors = Log.Messages.Where(m => m.type == LogMessageType.Error && m.text != null).Select(m => m.text).ToList();
|
||||||
|
HookLog();
|
||||||
|
Line("BEGIN Blax Defaults in-game tests, RimWorld " + VersionControl.CurrentVersionStringWithRev);
|
||||||
|
Fixtures.QuietStoryteller();
|
||||||
|
Find.TickManager.CurTimeSpeed = TimeSpeed.Paused;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void HookLog()
|
||||||
|
{
|
||||||
|
if (hooked) return;
|
||||||
|
hooked = true;
|
||||||
|
Application.logMessageReceivedThreaded += (text, stack, type) =>
|
||||||
|
{
|
||||||
|
if (type != LogType.Error && type != LogType.Exception) return;
|
||||||
|
string where = currentTest ?? "(between tests)";
|
||||||
|
string entry = where + ": " + OneLine(text);
|
||||||
|
bool ours = !IsKnownForeignError(text, stack)
|
||||||
|
&& ((text != null && (text.Contains("BlaxDefaults") || text.Contains("Blax Defaults"))) || (stack != null && stack.Contains("BlaxDefaults")));
|
||||||
|
lock (modErrors) (ours ? modErrors : otherErrors).Add(entry);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Errors another mod logs from its own code while a test ticks the game. The test's frames are in the
|
||||||
|
/// stack, so the check above would blame Blax Defaults; these show as LOGERR lines instead. Each entry is a
|
||||||
|
/// text fragment and the frame that logs it, with a line saying which mod and why. None known yet.
|
||||||
|
/// </summary>
|
||||||
|
private static readonly (string text, string frame)[] KnownForeignErrors =
|
||||||
|
{
|
||||||
|
};
|
||||||
|
|
||||||
|
private static bool IsKnownForeignError(string text, string stack)
|
||||||
|
{
|
||||||
|
if (text == null || stack == null)
|
||||||
|
return false;
|
||||||
|
foreach (var (fragment, frame) in KnownForeignErrors)
|
||||||
|
{
|
||||||
|
if (text.Contains(fragment) && stack.Contains(frame))
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void RunPhase(int phase)
|
||||||
|
{
|
||||||
|
var tests = typeof(TestRunner).Assembly.GetTypes()
|
||||||
|
.SelectMany(t => t.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static))
|
||||||
|
.Select(m => (method: m, attr: m.GetCustomAttribute<BlaxTestAttribute>()))
|
||||||
|
.Where(x => x.attr != null && x.attr.Phase == phase)
|
||||||
|
.OrderBy(x => x.method.DeclaringType.FullName)
|
||||||
|
.ThenBy(x => x.method.MetadataToken)
|
||||||
|
.ToList();
|
||||||
|
foreach (var (method, attr) in tests) RunOne(attr.Name, method);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void RunOne(string name, MethodInfo method)
|
||||||
|
{
|
||||||
|
currentTest = name;
|
||||||
|
errorsAllowed = false;
|
||||||
|
int modErrorsBefore, otherErrorsBefore;
|
||||||
|
lock (modErrors) { modErrorsBefore = modErrors.Count; otherErrorsBefore = otherErrors.Count; }
|
||||||
|
testModErrorsStart = modErrorsBefore;
|
||||||
|
testOtherErrorsStart = otherErrorsBefore;
|
||||||
|
var settings = Fixtures.SnapshotSettings();
|
||||||
|
string status = "PASS", detail = "";
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Find.TickManager.CurTimeSpeed = TimeSpeed.Paused;
|
||||||
|
method.Invoke(null, null);
|
||||||
|
}
|
||||||
|
catch (TargetInvocationException tie) when (tie.InnerException is TestSkipped s)
|
||||||
|
{
|
||||||
|
status = "SKIP"; detail = s.Message;
|
||||||
|
}
|
||||||
|
catch (TargetInvocationException tie) when (tie.InnerException is TestFailure f)
|
||||||
|
{
|
||||||
|
status = "FAIL"; detail = f.Message;
|
||||||
|
}
|
||||||
|
catch (TargetInvocationException tie)
|
||||||
|
{
|
||||||
|
status = "FAIL"; detail = "exception: " + tie.InnerException;
|
||||||
|
}
|
||||||
|
catch (Exception e)
|
||||||
|
{
|
||||||
|
status = "FAIL"; detail = "runner exception: " + e;
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Fixtures.RestoreSettings(settings);
|
||||||
|
try { Fixtures.Cleanup(); } catch (Exception e) { Note("cleanup threw: " + OneLine(e.Message)); }
|
||||||
|
}
|
||||||
|
|
||||||
|
List<string> newModErrors, newOtherErrors;
|
||||||
|
lock (modErrors)
|
||||||
|
{
|
||||||
|
newModErrors = modErrors.Skip(modErrorsBefore).ToList();
|
||||||
|
newOtherErrors = otherErrors.Skip(otherErrorsBefore).ToList();
|
||||||
|
}
|
||||||
|
if (status == "PASS" && newModErrors.Count > 0 && !errorsAllowed)
|
||||||
|
{
|
||||||
|
status = "FAIL";
|
||||||
|
detail = "Blax Defaults logged errors: " + string.Join(" | ", newModErrors.Take(3));
|
||||||
|
}
|
||||||
|
Record(status, name, detail);
|
||||||
|
if (errorsAllowed)
|
||||||
|
foreach (string e in newModErrors.Take(5)) Line(" EXPECTEDERR " + e);
|
||||||
|
foreach (string e in newOtherErrors.Take(5)) Line(" LOGERR " + e);
|
||||||
|
currentTest = null;
|
||||||
|
errorsAllowed = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Every error logged since the current test started, ours first, then other mods'.</summary>
|
||||||
|
internal static List<string> ErrorsSinceTestStart()
|
||||||
|
{
|
||||||
|
lock (modErrors)
|
||||||
|
return modErrors.Skip(testModErrorsStart).Concat(otherErrors.Skip(testOtherErrorsStart)).ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void Finish()
|
||||||
|
{
|
||||||
|
stage = 2;
|
||||||
|
List<string> stray;
|
||||||
|
lock (modErrors) stray = modErrors.Where(e => e.StartsWith("(between tests)")).ToList();
|
||||||
|
foreach (string e in stray.Take(10)) Line(" MODERR " + e);
|
||||||
|
Line($"SUMMARY pass={pass} fail={fail} skip={skip} strayModErrors={stray.Count}");
|
||||||
|
Line("END");
|
||||||
|
Log.Message($"[BlaxTest] finished: pass={pass} fail={fail} skip={skip}");
|
||||||
|
Root.Shutdown();
|
||||||
|
}
|
||||||
|
|
||||||
|
internal static void Note(string message) => Line(" INFO " + OneLine(message));
|
||||||
|
|
||||||
|
private static void Record(string status, string name, string detail)
|
||||||
|
{
|
||||||
|
if (status == "PASS") pass++;
|
||||||
|
else if (status == "FAIL") fail++;
|
||||||
|
else skip++;
|
||||||
|
Line(string.IsNullOrEmpty(detail) ? $"{status} {name}" : $"{status} {name}: {OneLine(detail)}");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void Line(string text)
|
||||||
|
{
|
||||||
|
Log.Message("[BlaxTest] " + text);
|
||||||
|
try { File.AppendAllText(ResultPath, text + Environment.NewLine); } catch { }
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string OneLine(string s)
|
||||||
|
{
|
||||||
|
if (s == null) return "";
|
||||||
|
s = s.Replace("\r", " ").Replace("\n", " ⏎ ");
|
||||||
|
return s.Length > 1500 ? s.Substring(0, 1500) + "…" : s;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,436 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using BlaxDefaults;
|
||||||
|
using HarmonyLib;
|
||||||
|
using RimWorld;
|
||||||
|
using Verse;
|
||||||
|
|
||||||
|
namespace BlaxDefaultsTests
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Work package "hooks". The tests of design.md: New stockpiles start from your default; New storage buildings start from your default.
|
||||||
|
/// Methods: [BlaxTest("<area>: <what>", phase: N)] public static void X(). Skip DLC-only checks with
|
||||||
|
/// Fixtures.NeedDlc(DlcSupport.Biotech) ("skipped: needs Biotech").
|
||||||
|
/// </summary>
|
||||||
|
public static class HooksTests
|
||||||
|
{
|
||||||
|
private const string KeptZoneKey = "hooks.keptZone";
|
||||||
|
private const string KeptZoneSettingsKey = "hooks.keptZoneSettings";
|
||||||
|
|
||||||
|
// ---- stockpiles ------------------------------------------------------------------
|
||||||
|
|
||||||
|
[BlaxTest("stockpiles: a new stockpile starts from the Stockpile default")]
|
||||||
|
public static void NewStockpile()
|
||||||
|
{
|
||||||
|
SaveMealsOnlyStockpile();
|
||||||
|
CellRect area = Fixtures.EmptyArea(3, 3);
|
||||||
|
List<Zone_Stockpile> zones = Designate(GameDesignator<Designator_ZoneAddStockpile_Resources>(), area.Cells);
|
||||||
|
T.Equal(1, zones.Count, "new zones");
|
||||||
|
T.Equal(9, zones[0].CellCount, "cells of the new zone");
|
||||||
|
CheckMealsOnly(zones[0].settings, "the new stockpile");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("stockpiles: two disjoint blocks in one drag give two zones, both with the default")]
|
||||||
|
public static void TwoBlocks()
|
||||||
|
{
|
||||||
|
SaveMealsOnlyStockpile();
|
||||||
|
CellRect area = Fixtures.EmptyArea(7, 3);
|
||||||
|
// Columns 0-2 and 4-6; column 3 stays free, so the blocks don't touch.
|
||||||
|
IEnumerable<IntVec3> cells = area.Cells.Where(c => c.x - area.minX != 3);
|
||||||
|
List<Zone_Stockpile> zones = Designate(GameDesignator<Designator_ZoneAddStockpile_Resources>(), cells);
|
||||||
|
T.Equal(2, zones.Count, "new zones");
|
||||||
|
foreach (Zone_Stockpile z in zones)
|
||||||
|
{
|
||||||
|
T.Equal(9, z.CellCount, "cells of " + z.label);
|
||||||
|
CheckMealsOnly(z.settings, z.label);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("stockpiles: a dumping drag without a dumping default stays vanilla")]
|
||||||
|
public static void DumpingWithoutDefault()
|
||||||
|
{
|
||||||
|
SaveMealsOnlyStockpile();
|
||||||
|
ForgetInMemory(DefaultsKeys.Dumping);
|
||||||
|
CellRect area = Fixtures.EmptyArea(3, 3);
|
||||||
|
List<Zone_Stockpile> zones = Designate(GameDesignator<Designator_ZoneAddStockpile_Dumping>(), area.Cells);
|
||||||
|
T.Equal(1, zones.Count, "new zones");
|
||||||
|
StorageSettings s = zones[0].settings;
|
||||||
|
T.Equal(StoragePriority.Normal, s.Priority, "dumping stockpile priority");
|
||||||
|
T.Check(s.filter.Allows(ThingDefOf.ChunkSlagSteel), "the dumping stockpile refuses slag chunks");
|
||||||
|
T.Check(s.filter.Allows(ThingDefOf.Human.race.corpseDef), "the dumping stockpile refuses human corpses");
|
||||||
|
T.Check(!s.filter.Allows(ThingDefOf.MealSimple), "the dumping stockpile took the Stockpile default (allows MealSimple)");
|
||||||
|
CheckGameDefault(Fixtures.DumpingKind, s, "the dumping stockpile");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("stockpiles: an Expand drag next to a zone grows it without touching its filter")]
|
||||||
|
public static void ExpandKeepsFilter()
|
||||||
|
{
|
||||||
|
ForgetInMemory(DefaultsKeys.Stockpile);
|
||||||
|
CellRect area = Fixtures.EmptyArea(6, 3);
|
||||||
|
List<IntVec3> left = area.Cells.Where(c => c.x - area.minX < 3).ToList();
|
||||||
|
List<IntVec3> right = area.Cells.Where(c => c.x - area.minX >= 3).ToList();
|
||||||
|
List<Zone_Stockpile> made = Designate(GameDesignator<Designator_ZoneAddStockpile_Resources>(), left);
|
||||||
|
T.Equal(1, made.Count, "zones made by the first drag");
|
||||||
|
Zone_Stockpile zone = made[0];
|
||||||
|
zone.settings.Priority = StoragePriority.Low;
|
||||||
|
zone.settings.filter.SetAllow(ThingDefOf.Steel, false);
|
||||||
|
string before = Fixtures.StockpileKind.Capture(zone.settings).ContentFingerprint();
|
||||||
|
|
||||||
|
SaveMealsOnlyStockpile();
|
||||||
|
List<Zone_Stockpile> grown = Designate(new Designator_ZoneAddStockpile_Expand(), right, select: zone);
|
||||||
|
T.Equal(0, grown.Count, "zones made by the Expand drag");
|
||||||
|
T.Equal(18, zone.CellCount, "cells of the grown zone");
|
||||||
|
T.Equal(StoragePriority.Low, zone.settings.Priority, "priority of the grown zone");
|
||||||
|
T.Check(zone.settings.filter.Allows(ThingDefOf.WoodLog) && !zone.settings.filter.Allows(ThingDefOf.Steel),
|
||||||
|
"the grown zone's filter changed (WoodLog " + zone.settings.filter.Allows(ThingDefOf.WoodLog) + ", Steel " + zone.settings.filter.Allows(ThingDefOf.Steel) + ")");
|
||||||
|
T.Check(Fixtures.StockpileKind.Capture(zone.settings).ContentFingerprint() == before, "the grown zone's settings changed");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("stockpiles: an Expand drag away from any zone makes a stockpile with the Stockpile default")]
|
||||||
|
public static void ExpandAloneMakesStockpile()
|
||||||
|
{
|
||||||
|
SaveMealsOnlyStockpile();
|
||||||
|
CellRect area = Fixtures.EmptyArea(3, 3);
|
||||||
|
List<Zone_Stockpile> zones = Designate(new Designator_ZoneAddStockpile_Expand(), area.Cells);
|
||||||
|
T.Equal(1, zones.Count, "new zones");
|
||||||
|
CheckMealsOnly(zones[0].settings, "the stockpile an Expand drag made");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("stockpiles: with stockpile defaults or the master switch off, a new stockpile stays vanilla")]
|
||||||
|
public static void StockpilesOff()
|
||||||
|
{
|
||||||
|
SaveMealsOnlyStockpile();
|
||||||
|
Fixtures.Settings.stockpileDefaults = false;
|
||||||
|
List<Zone_Stockpile> zones = Designate(GameDesignator<Designator_ZoneAddStockpile_Resources>(), Fixtures.EmptyArea(3, 3).Cells);
|
||||||
|
T.Equal(1, zones.Count, "new zones with stockpile defaults off");
|
||||||
|
CheckGameDefault(Fixtures.StockpileKind, zones[0].settings, "a stockpile made with stockpile defaults off");
|
||||||
|
|
||||||
|
Fixtures.Settings.stockpileDefaults = true;
|
||||||
|
Fixtures.Settings.enabled = false;
|
||||||
|
zones = Designate(GameDesignator<Designator_ZoneAddStockpile_Resources>(), Fixtures.EmptyArea(3, 3).Cells);
|
||||||
|
T.Equal(1, zones.Count, "new zones with the master switch off");
|
||||||
|
CheckGameDefault(Fixtures.StockpileKind, zones[0].settings, "a stockpile made with the master switch off");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("stockpiles: a kept stockpile for the phase-2 check")]
|
||||||
|
public static void KeepStockpile()
|
||||||
|
{
|
||||||
|
SaveMealsOnlyStockpile();
|
||||||
|
List<Zone_Stockpile> zones = Designate(GameDesignator<Designator_ZoneAddStockpile_Resources>(), Fixtures.EmptyArea(3, 3).Cells);
|
||||||
|
T.Equal(1, zones.Count, "new zones");
|
||||||
|
Zone_Stockpile zone = Fixtures.KeepZone(zones[0]);
|
||||||
|
CheckMealsOnly(zone.settings, "the kept stockpile");
|
||||||
|
T.Carry[KeptZoneKey] = zone.ID.ToString();
|
||||||
|
T.Carry[KeptZoneSettingsKey] = Fixtures.StockpileKind.Capture(zone.settings).ContentFingerprint();
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("stockpiles: the kept stockpile's settings persist after save and reload", phase: 2)]
|
||||||
|
public static void KeptStockpilePersists()
|
||||||
|
{
|
||||||
|
T.Carry.TryGetValue(KeptZoneKey, out string idText);
|
||||||
|
T.Check(int.TryParse(idText, out int id), "phase 1 kept no stockpile");
|
||||||
|
var zone = Fixtures.FindZoneById(id) as Zone_Stockpile;
|
||||||
|
T.NotNull(zone, "the kept stockpile " + id);
|
||||||
|
CheckMealsOnly(zone.settings, "the kept stockpile after reload");
|
||||||
|
T.Check(Fixtures.StockpileKind.Capture(zone.settings).ContentFingerprint() == T.Carry[KeptZoneSettingsKey],
|
||||||
|
"the kept stockpile's settings changed over save and reload");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- storage buildings -----------------------------------------------------------
|
||||||
|
|
||||||
|
[BlaxTest("buildings: a shelf blueprint starts from the Shelf default")]
|
||||||
|
public static void ShelfBlueprint()
|
||||||
|
{
|
||||||
|
SaveSteelOnlyShelf();
|
||||||
|
CellRect area = Fixtures.EmptyArea(3, 3);
|
||||||
|
Blueprint_Storage bp = PlaceBlueprint(ThingDefOf.Shelf, ThingDefOf.WoodLog, area.CenterCell);
|
||||||
|
CheckSteelOnly(bp.settings, "the shelf blueprint");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("buildings: changes made on the blueprint win over the default when the shelf is built")]
|
||||||
|
public static void BlueprintChangesWin()
|
||||||
|
{
|
||||||
|
SaveSteelOnlyShelf();
|
||||||
|
CellRect area = Fixtures.EmptyArea(3, 3);
|
||||||
|
Thing shelf = Build(ThingDefOf.Shelf, ThingDefOf.WoodLog, area.CenterCell, bp => bp.settings.filter.SetAllow(ThingDefOf.WoodLog, true));
|
||||||
|
StorageSettings s = SettingsOf(shelf);
|
||||||
|
T.Equal(StoragePriority.Normal, s.Priority, "built shelf priority");
|
||||||
|
T.Check(s.filter.Allows(ThingDefOf.Steel), "the built shelf refuses Steel");
|
||||||
|
T.Check(s.filter.Allows(ThingDefOf.WoodLog), "the built shelf refuses WoodLog allowed on its blueprint");
|
||||||
|
T.Check(!s.filter.Allows(ThingDefOf.Silver), "the built shelf allows Silver");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("buildings: a shelf spawned without a blueprint keeps the game's default")]
|
||||||
|
public static void SpawnedShelfKeepsGameDefault()
|
||||||
|
{
|
||||||
|
SaveSteelOnlyShelf();
|
||||||
|
CellRect area = Fixtures.EmptyArea(3, 3);
|
||||||
|
Thing shelf = ThingMaker.MakeThing(ThingDefOf.Shelf, ThingDefOf.WoodLog);
|
||||||
|
shelf.SetFactionDirect(Faction.OfPlayer);
|
||||||
|
Fixtures.Track(GenSpawn.Spawn(shelf, area.CenterCell, Fixtures.Map, Rot4.North));
|
||||||
|
StorageSettings s = SettingsOf(shelf);
|
||||||
|
T.Equal(StoragePriority.Preferred, s.Priority, "spawned shelf priority");
|
||||||
|
CheckGameDefault(Fixtures.Kind("Shelf"), s, "the spawned shelf");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("buildings: auto-rebuild of a shelf keeps the destroyed shelf's settings")]
|
||||||
|
public static void RebuiltShelfKeepsSettings()
|
||||||
|
{
|
||||||
|
SaveSteelOnlyShelf();
|
||||||
|
CellRect area = Fixtures.EmptyArea(5, 5);
|
||||||
|
Thing shelf = Build(ThingDefOf.Shelf, ThingDefOf.WoodLog, area.CenterCell);
|
||||||
|
StorageSettings s = SettingsOf(shelf);
|
||||||
|
s.filter.SetDisallowAll();
|
||||||
|
s.filter.SetAllow(ThingDefOf.Silver, true);
|
||||||
|
StorageSettings rebuilt = DestroyWithAutoRebuild(shelf, area);
|
||||||
|
T.Check(rebuilt.filter.Allows(ThingDefOf.Silver), "the rebuild blueprint refuses Silver");
|
||||||
|
T.Check(!rebuilt.filter.Allows(ThingDefOf.Steel), "the rebuild blueprint allows Steel (the default replaced the old settings)");
|
||||||
|
T.Check(!rebuilt.filter.Allows(ThingDefOf.WoodLog), "the rebuild blueprint allows WoodLog");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("buildings: auto-rebuild of a bookcase starts from the Bookcase default")]
|
||||||
|
public static void RebuiltBookcaseTakesDefault()
|
||||||
|
{
|
||||||
|
ThingDef bookcase = Fixtures.Thing("Bookcase");
|
||||||
|
StorageKind kind = Fixtures.Kind("Bookcase");
|
||||||
|
Fixtures.Save(Fixtures.Template(kind, StoragePriority.Normal, ThingDefOf.Novel));
|
||||||
|
CellRect area = Fixtures.EmptyArea(5, 5);
|
||||||
|
Thing built = Build(bookcase, StuffFor(bookcase), area.CenterCell);
|
||||||
|
StorageSettings s = SettingsOf(built);
|
||||||
|
T.Check(s.filter.Allows(ThingDefOf.Novel) && !s.filter.Allows(ThingDefOf.TextBook), "the built bookcase did not take the default");
|
||||||
|
s.filter.SetDisallowAll();
|
||||||
|
s.filter.SetAllow(ThingDefOf.TextBook, true);
|
||||||
|
StorageSettings rebuilt = DestroyWithAutoRebuild(built, area);
|
||||||
|
T.Equal(StoragePriority.Normal, rebuilt.Priority, "rebuild blueprint priority");
|
||||||
|
T.Check(rebuilt.filter.Allows(ThingDefOf.Novel), "the rebuild blueprint refuses novels");
|
||||||
|
T.Check(!rebuilt.filter.Allows(ThingDefOf.TextBook), "the rebuild blueprint allows textbooks");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("buildings: a template naming Steel never makes a hopper accept Steel")]
|
||||||
|
public static void HopperNeverTakesSteel()
|
||||||
|
{
|
||||||
|
StorageKind kind = Fixtures.Kind("Hopper");
|
||||||
|
T.Check(!kind.ParentFilter.Allows(ThingDefOf.Steel), "the hopper's parent filter allows Steel");
|
||||||
|
StorageTemplate t = Fixtures.Template(kind, StoragePriority.Low);
|
||||||
|
t.allowed.Add(ThingDefOf.Steel.defName);
|
||||||
|
t.unlisted = UnlistedRule.Allow;
|
||||||
|
Fixtures.Save(t);
|
||||||
|
CellRect area = Fixtures.EmptyArea(3, 3);
|
||||||
|
Thing hopper = Build(ThingDefOf.Hopper, StuffFor(ThingDefOf.Hopper), area.CenterCell, bp =>
|
||||||
|
{
|
||||||
|
T.Equal(StoragePriority.Low, bp.settings.Priority, "hopper blueprint priority (the default was not applied)");
|
||||||
|
T.Check(!bp.settings.filter.Allows(ThingDefOf.Steel), "the hopper blueprint's filter allows Steel");
|
||||||
|
T.Check(!bp.settings.AllowedToAccept(ThingDefOf.Steel), "the hopper blueprint accepts Steel");
|
||||||
|
});
|
||||||
|
StorageSettings s = SettingsOf(hopper);
|
||||||
|
T.Check(!s.filter.Allows(ThingDefOf.Steel), "the built hopper's filter allows Steel");
|
||||||
|
T.Check(!s.AllowedToAccept(ThingDefOf.Steel), "the built hopper accepts Steel");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("buildings: with storage defaults or the master switch off, a shelf blueprint stays vanilla")]
|
||||||
|
public static void StorageOff()
|
||||||
|
{
|
||||||
|
SaveSteelOnlyShelf();
|
||||||
|
StorageKind kind = Fixtures.Kind("Shelf");
|
||||||
|
Fixtures.Settings.storageDefaults = false;
|
||||||
|
Blueprint_Storage bp = PlaceBlueprint(ThingDefOf.Shelf, ThingDefOf.WoodLog, Fixtures.EmptyArea(3, 3).CenterCell);
|
||||||
|
CheckGameDefault(kind, bp.settings, "a shelf blueprint placed with storage defaults off");
|
||||||
|
|
||||||
|
Fixtures.Settings.storageDefaults = true;
|
||||||
|
Fixtures.Settings.enabled = false;
|
||||||
|
bp = PlaceBlueprint(ThingDefOf.Shelf, ThingDefOf.WoodLog, Fixtures.EmptyArea(3, 3).CenterCell);
|
||||||
|
CheckGameDefault(kind, bp.settings, "a shelf blueprint placed with the master switch off");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- -Compat ---------------------------------------------------------------------
|
||||||
|
|
||||||
|
[BlaxTest("compat: a Weapon Racks rack built through a frame takes its default")]
|
||||||
|
public static void WeaponRackTakesDefault()
|
||||||
|
{
|
||||||
|
if (!Compat.IsActive(Compat.WeaponRacks))
|
||||||
|
T.Skip("Weapon Racks is not active");
|
||||||
|
ThingDef rack = Fixtures.Thing("WeaponRacks_1Rack");
|
||||||
|
T.Check(StorageKinds.IsCovered(rack), "WeaponRacks_1Rack is not covered");
|
||||||
|
StorageKind kind = StorageKinds.ForDef(rack);
|
||||||
|
ThingDef weapon = DefDatabase<ThingDef>.GetNamedSilentFail("Gun_Revolver");
|
||||||
|
if (weapon == null || !kind.ParentFilter.Allows(weapon))
|
||||||
|
weapon = StorageKinds.StorableDefs(kind.ParentFilter).FirstOrDefault(d => d.IsWeapon);
|
||||||
|
T.NotNull(weapon, "a weapon the rack takes");
|
||||||
|
StorageTemplate t = Fixtures.Save(Fixtures.Template(kind, StoragePriority.Low, weapon));
|
||||||
|
Thing built = Build(rack, StuffFor(rack), Fixtures.EmptyArea(3, 3).CenterCell);
|
||||||
|
StorageSettings s = SettingsOf(built);
|
||||||
|
T.Info("rack class " + built.GetType().FullName + ", template weapon " + weapon.defName);
|
||||||
|
T.Equal(StoragePriority.Low, s.Priority, "built rack priority");
|
||||||
|
T.Check(s.filter.Allows(weapon), "the built rack refuses " + weapon.defName);
|
||||||
|
T.Check(kind.Capture(s).SameSettingsAs(t), "the built rack's settings differ from the default");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("compat: Replace Stuff's stuff replacement of a shelf keeps the shelf's settings")]
|
||||||
|
public static void ReplaceStuffKeepsSettings()
|
||||||
|
{
|
||||||
|
if (!Compat.IsActive(Compat.ReplaceStuff))
|
||||||
|
T.Skip("Replace Stuff is not active");
|
||||||
|
var place = AccessTools.Method("Replace_Stuff.GenReplace:PlaceReplaceFrame");
|
||||||
|
T.NotNull(place, "Replace_Stuff.GenReplace.PlaceReplaceFrame");
|
||||||
|
SaveSteelOnlyShelf();
|
||||||
|
CellRect area = Fixtures.EmptyArea(5, 5);
|
||||||
|
Thing shelf = Build(ThingDefOf.Shelf, ThingDefOf.WoodLog, area.CenterCell);
|
||||||
|
StorageSettings s = SettingsOf(shelf);
|
||||||
|
s.filter.SetDisallowAll();
|
||||||
|
s.filter.SetAllow(ThingDefOf.Silver, true);
|
||||||
|
s.Priority = StoragePriority.Low;
|
||||||
|
|
||||||
|
var frame = place.Invoke(null, new object[] { shelf, ThingDefOf.Steel }) as Frame;
|
||||||
|
T.NotNull(frame, "the replace frame");
|
||||||
|
Fixtures.Track(frame);
|
||||||
|
frame.CompleteConstruction(Fixtures.Worker());
|
||||||
|
|
||||||
|
T.Check(shelf.Spawned, "the shelf is gone after the stuff replacement");
|
||||||
|
T.Equal(ThingDefOf.Steel, shelf.Stuff, "shelf stuff after the replacement");
|
||||||
|
StorageSettings after = SettingsOf(shelf);
|
||||||
|
T.Equal(StoragePriority.Low, after.Priority, "shelf priority after the replacement");
|
||||||
|
T.Check(after.filter.Allows(ThingDefOf.Silver), "the replaced shelf refuses Silver");
|
||||||
|
T.Check(!after.filter.Allows(ThingDefOf.Steel), "the replaced shelf allows Steel (the default was applied)");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- helpers ---------------------------------------------------------------------
|
||||||
|
|
||||||
|
/// <summary>"Stockpile: Important, simple meals only", saved.</summary>
|
||||||
|
private static void SaveMealsOnlyStockpile() =>
|
||||||
|
Fixtures.Save(Fixtures.Template(Fixtures.StockpileKind, StoragePriority.Important, ThingDefOf.MealSimple));
|
||||||
|
|
||||||
|
/// <summary>"Shelf: Normal, Steel only", saved.</summary>
|
||||||
|
private static void SaveSteelOnlyShelf() =>
|
||||||
|
Fixtures.Save(Fixtures.Template(Fixtures.Kind("Shelf"), StoragePriority.Normal, ThingDefOf.Steel));
|
||||||
|
|
||||||
|
private static void CheckMealsOnly(StorageSettings s, string what)
|
||||||
|
{
|
||||||
|
T.Equal(StoragePriority.Important, s.Priority, what + " priority");
|
||||||
|
T.Check(s.filter.Allows(ThingDefOf.MealSimple), what + " refuses MealSimple");
|
||||||
|
T.Check(!s.filter.Allows(ThingDefOf.Steel), what + " allows Steel");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void CheckSteelOnly(StorageSettings s, string what)
|
||||||
|
{
|
||||||
|
T.Equal(StoragePriority.Normal, s.Priority, what + " priority");
|
||||||
|
T.Check(s.filter.Allows(ThingDefOf.Steel), what + " refuses Steel");
|
||||||
|
T.Check(!s.filter.Allows(ThingDefOf.WoodLog), what + " allows WoodLog");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void CheckGameDefault(StorageKind kind, StorageSettings s, string what)
|
||||||
|
{
|
||||||
|
StorageTemplate expected = kind.Capture(kind.GameDefault());
|
||||||
|
StorageTemplate actual = kind.Capture(s);
|
||||||
|
T.Equal(expected.priority, actual.priority, what + " priority");
|
||||||
|
T.Check(actual.SameSettingsAs(expected), what + " differs from the game's default");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Removes an entry from the library in memory only; the runner restores it after the test.</summary>
|
||||||
|
private static void ForgetInMemory(string key) =>
|
||||||
|
DefaultsLibrary.RestoreForTests(DefaultsLibrary.Snapshot().Where(e => e.key != key).ToList());
|
||||||
|
|
||||||
|
/// <summary>Runs the designator over the cells as one drag and returns the stockpiles it made (tracked).</summary>
|
||||||
|
private static List<Zone_Stockpile> Designate(Designator_ZoneAddStockpile designator, IEnumerable<IntVec3> cells, Zone select = null)
|
||||||
|
{
|
||||||
|
Map map = Fixtures.Map;
|
||||||
|
Find.Selector.ClearSelection();
|
||||||
|
if (select != null)
|
||||||
|
Find.Selector.Select(select, playSound: false, forceDesignatorDeselect: false);
|
||||||
|
var before = new HashSet<Zone>(map.zoneManager.AllZones);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
designator.DesignateMultiCell(cells.ToList());
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Find.Selector.ClearSelection();
|
||||||
|
}
|
||||||
|
var made = map.zoneManager.AllZones.Where(z => !before.Contains(z)).ToList();
|
||||||
|
foreach (Zone z in made)
|
||||||
|
Fixtures.TrackZone(z);
|
||||||
|
T.Check(made.All(z => z is Zone_Stockpile), "the designator made a zone that is not a stockpile");
|
||||||
|
return made.Cast<Zone_Stockpile>().ToList();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The instance the game made for its architect menu, else a new one (the game makes them the same way).</summary>
|
||||||
|
private static TD GameDesignator<TD>() where TD : Designator, new() =>
|
||||||
|
DefDatabase<DesignationCategoryDef>.AllDefsListForReading
|
||||||
|
.SelectMany(c => c.AllResolvedDesignators ?? new List<Designator>())
|
||||||
|
.FirstOrDefault(d => d.GetType() == typeof(TD)) as TD ?? new TD();
|
||||||
|
|
||||||
|
private static ThingDef StuffFor(ThingDef def) => def.MadeFromStuff ? GenStuff.DefaultStuffFor(def) : null;
|
||||||
|
|
||||||
|
internal static StorageSettings SettingsOf(Thing t)
|
||||||
|
{
|
||||||
|
StorageSettings s = t is IStorageGroupMember member ? member.ThingStoreSettings : (t as IStoreSettingsParent)?.GetStoreSettings();
|
||||||
|
T.NotNull(s, "storage settings of " + t);
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Blueprint_Storage PlaceBlueprint(ThingDef def, ThingDef stuff, IntVec3 at)
|
||||||
|
{
|
||||||
|
Blueprint_Build placed = GenConstruct.PlaceBlueprintForBuild(def, at, Fixtures.Map, Rot4.North, Faction.OfPlayer, stuff);
|
||||||
|
Fixtures.Track(placed);
|
||||||
|
var bp = placed as Blueprint_Storage;
|
||||||
|
T.NotNull(bp, "a Blueprint_Storage for " + def.defName + " (got " + placed?.GetType().Name + ")");
|
||||||
|
return bp;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Places a blueprint, lets the test change it, turns it into a frame and completes the frame with a
|
||||||
|
/// colonist, as a construction job does. Returns the building (tracked).
|
||||||
|
/// </summary>
|
||||||
|
internal static Thing Build(ThingDef def, ThingDef stuff, IntVec3 at, Action<Blueprint_Storage> onBlueprint = null)
|
||||||
|
{
|
||||||
|
Map map = Fixtures.Map;
|
||||||
|
Blueprint_Storage bp = PlaceBlueprint(def, stuff, at);
|
||||||
|
onBlueprint?.Invoke(bp);
|
||||||
|
Pawn worker = Fixtures.Worker();
|
||||||
|
T.Check(bp.TryReplaceWithSolidThing(worker, out Thing made, out bool _), "the " + def.defName + " blueprint did not turn into a frame");
|
||||||
|
var frame = made as Frame;
|
||||||
|
T.NotNull(frame, "the " + def.defName + " frame");
|
||||||
|
Fixtures.Track(frame);
|
||||||
|
frame.CompleteConstruction(worker);
|
||||||
|
Thing built = at.GetThingList(map).FirstOrDefault(t => t.def == def);
|
||||||
|
T.NotNull(built, "the built " + def.defName);
|
||||||
|
return Fixtures.Track(built);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Destroys a player building with auto-rebuild on and its cell in the home area, as a raid would, and
|
||||||
|
/// returns a copy of the rebuild blueprint's settings. Restores auto-rebuild and the home area, then
|
||||||
|
/// cancels the blueprint as a player would, so Replace Stuff (in -Compat runs) forgets the destroyed
|
||||||
|
/// building and doesn't revive it into a later test's building on the same cell.
|
||||||
|
/// </summary>
|
||||||
|
private static StorageSettings DestroyWithAutoRebuild(Thing building, CellRect area)
|
||||||
|
{
|
||||||
|
Map map = Fixtures.Map;
|
||||||
|
T.Check(building.def.IsResearchFinished, building.def.defName + " needs research the test colony lacks, so auto-rebuild can't place it");
|
||||||
|
IntVec3 at = building.Position;
|
||||||
|
bool autoRebuild = Find.PlaySettings.autoRebuild;
|
||||||
|
Area_Home home = map.areaManager.Home;
|
||||||
|
var homeBefore = area.Cells.ToDictionary(c => c, c => home[c]);
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Find.PlaySettings.autoRebuild = true;
|
||||||
|
foreach (IntVec3 c in area.Cells)
|
||||||
|
home[c] = true;
|
||||||
|
building.Destroy(DestroyMode.KillFinalize);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Find.PlaySettings.autoRebuild = autoRebuild;
|
||||||
|
foreach (var kv in homeBefore)
|
||||||
|
home[kv.Key] = kv.Value;
|
||||||
|
}
|
||||||
|
Blueprint_Storage bp = at.GetThingList(map).OfType<Blueprint_Storage>().FirstOrDefault();
|
||||||
|
T.NotNull(bp, "the rebuild blueprint of " + building.def.defName);
|
||||||
|
Fixtures.Track(bp);
|
||||||
|
var copy = new StorageSettings();
|
||||||
|
copy.CopyFrom(bp.settings);
|
||||||
|
bp.Destroy(DestroyMode.Cancel);
|
||||||
|
return copy;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,347 @@
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Globalization;
|
||||||
|
using System.IO;
|
||||||
|
using System.Linq;
|
||||||
|
using BlaxDefaults;
|
||||||
|
using RimWorld;
|
||||||
|
using Verse;
|
||||||
|
|
||||||
|
namespace BlaxDefaultsTests
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Work package "page". The tests of design.md: Defaults library and settings page (the page and edit window).
|
||||||
|
/// Methods: [BlaxTest("<area>: <what>", phase: N)] public static void X(). Skip DLC-only checks with
|
||||||
|
/// Fixtures.NeedDlc(DlcSupport.Biotech) ("skipped: needs Biotech"). Drawing is checked by hand, since
|
||||||
|
/// headless runs have no GUI; these tests cover the strings and the templates the page and window build.
|
||||||
|
/// </summary>
|
||||||
|
public static class PageTests
|
||||||
|
{
|
||||||
|
private static readonly string[] PageKeys =
|
||||||
|
{
|
||||||
|
"BlaxDefaults_PageEnabled", "BlaxDefaults_PageEnabledTip", "BlaxDefaults_PageStatusNone", "BlaxDefaults_PageStatusOne",
|
||||||
|
"BlaxDefaults_PageStatusMany", "BlaxDefaults_PageInactiveOne", "BlaxDefaults_PageInactiveMany", "BlaxDefaults_PageStatusTip",
|
||||||
|
"BlaxDefaults_PageBrokenBoth", "BlaxDefaults_PageBrokenRecovered", "BlaxDefaults_PageBrokenEmpty",
|
||||||
|
"BlaxDefaults_PageUnread", "BlaxDefaults_PageUnreadKept", "BlaxDefaults_PageNewerFile",
|
||||||
|
"BlaxDefaults_PageSectionStockpiles", "BlaxDefaults_PageStockpilesToggle", "BlaxDefaults_PageStockpilesToggleTip",
|
||||||
|
"BlaxDefaults_PageStockpilesNone", "BlaxDefaults_PageSectionStorage", "BlaxDefaults_PageStorageToggle",
|
||||||
|
"BlaxDefaults_PageStorageToggleTip", "BlaxDefaults_PageStorageNone", "BlaxDefaults_PageSectionBills",
|
||||||
|
"BlaxDefaults_PageBillsToggle", "BlaxDefaults_PageBillsToggleTip", "BlaxDefaults_PageRowSummary",
|
||||||
|
"BlaxDefaults_PageRowRefusesUnlisted", "BlaxDefaults_PageRowAllowsUnlisted", "BlaxDefaults_PageRowUnlistedTip",
|
||||||
|
"BlaxDefaults_PageInactiveNamesTip", "BlaxDefaults_PageEdit", "BlaxDefaults_PageForget", "BlaxDefaults_PageEditNeedsDlc",
|
||||||
|
"BlaxDefaults_PageEditKindMissing", "BlaxDefaults_PageForgetConfirm", "BlaxDefaults_PageEditTitle", "BlaxDefaults_PagePriority",
|
||||||
|
"BlaxDefaults_PageUnlisted", "BlaxDefaults_PageUnlistedTip", "BlaxDefaults_PageFilterNeedsGame", "BlaxDefaults_PageSave",
|
||||||
|
"BlaxDefaults_PageCancel",
|
||||||
|
};
|
||||||
|
|
||||||
|
// ---- helpers ---------------------------------------------------------------------
|
||||||
|
|
||||||
|
private static StorageKind Shelf => Fixtures.Kind("Shelf");
|
||||||
|
|
||||||
|
/// <summary>A shelf template allowing Steel only, unlisted Game, not saved.</summary>
|
||||||
|
private static StorageTemplate ShelfSteel(StoragePriority priority = StoragePriority.Normal) =>
|
||||||
|
Fixtures.Template(Shelf, priority, ThingDefOf.Steel);
|
||||||
|
|
||||||
|
private static string Count(int n) => n.ToString("N0", CultureInfo.InvariantCulture);
|
||||||
|
|
||||||
|
private static string Normal => StoragePriority.Normal.Label().CapitalizeFirst();
|
||||||
|
|
||||||
|
/// <summary>Puts exactly these entries in memory without writing the file; the runner restores the library after the test.</summary>
|
||||||
|
private static void LibraryOf(params DefaultsEntry[] entries) => DefaultsLibrary.ReplaceInMemory(entries.ToList());
|
||||||
|
|
||||||
|
/// <summary>What differs between two templates, for failure messages (fingerprints are thousands of names long).</summary>
|
||||||
|
private static string Diff(StorageTemplate expected, StorageTemplate actual)
|
||||||
|
{
|
||||||
|
var parts = new List<string>();
|
||||||
|
void Lists(string what, List<string> e, List<string> a)
|
||||||
|
{
|
||||||
|
List<string> missing = e.Except(a).Take(5).ToList();
|
||||||
|
List<string> extra = a.Except(e).Take(5).ToList();
|
||||||
|
if (missing.Count + extra.Count > 0)
|
||||||
|
parts.Add(what + " missing [" + string.Join(",", missing) + "] extra [" + string.Join(",", extra) + "]");
|
||||||
|
}
|
||||||
|
if (expected.priority != actual.priority) parts.Add("priority " + expected.priority + " vs " + actual.priority);
|
||||||
|
if (expected.unlisted != actual.unlisted) parts.Add("unlisted " + expected.unlisted + " vs " + actual.unlisted);
|
||||||
|
Lists("allowed", expected.allowed, actual.allowed);
|
||||||
|
Lists("refused", expected.refused, actual.refused);
|
||||||
|
Lists("allowedSpecial", expected.allowedSpecial, actual.allowedSpecial);
|
||||||
|
Lists("refusedSpecial", expected.refusedSpecial, actual.refusedSpecial);
|
||||||
|
if (expected.hitPoints != actual.hitPoints) parts.Add("hitPoints " + expected.hitPoints + " vs " + actual.hitPoints);
|
||||||
|
if (expected.quality != actual.quality) parts.Add("quality " + expected.quality + " vs " + actual.quality);
|
||||||
|
return parts.Count == 0 ? "(same)" : string.Join("; ", parts);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- settings page ---------------------------------------------------------------
|
||||||
|
|
||||||
|
[BlaxTest("page: every string of the settings page and the edit window is in Keyed")]
|
||||||
|
public static void Strings()
|
||||||
|
{
|
||||||
|
var missing = PageKeys.Where(k => !k.CanTranslate()).ToList();
|
||||||
|
T.Check(missing.Count == 0, "strings missing from Keyed: " + string.Join(", ", missing));
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("page: a row names the kind, the priority, how many items it allows and the unlisted rule")]
|
||||||
|
public static void RowSummary_()
|
||||||
|
{
|
||||||
|
StorageTemplate t = ShelfSteel();
|
||||||
|
int total = StorageKinds.StorableDefs(Shelf.ParentFilter).Count();
|
||||||
|
T.Equal(total, t.allowed.Count + t.refused.Count, "names in a captured shelf template");
|
||||||
|
string expected = "Shelf: " + Normal + ", allows 1 of " + Count(total) + " items";
|
||||||
|
T.Info("row: " + expected);
|
||||||
|
T.Equal("Shelf", SettingsPage.KindLabel(t), "KindLabel of a shelf default");
|
||||||
|
T.Equal(expected, SettingsPage.RowSummary(t), "row with unlisted = Game");
|
||||||
|
t.unlisted = UnlistedRule.Refuse;
|
||||||
|
T.Equal(expected + ", refuses unlisted items", SettingsPage.RowSummary(t), "row with unlisted = Refuse");
|
||||||
|
t.unlisted = UnlistedRule.Allow;
|
||||||
|
T.Equal(expected + ", allows unlisted items", SettingsPage.RowSummary(t), "row with unlisted = Allow");
|
||||||
|
|
||||||
|
T.Equal("Stockpile", SettingsPage.KindLabel(new StorageTemplate(DefaultsKeys.Stockpile)), "KindLabel of the stockpile default");
|
||||||
|
T.Equal("Dumping stockpile", SettingsPage.KindLabel(new StorageTemplate(DefaultsKeys.Dumping)), "KindLabel of the dumping default");
|
||||||
|
T.Equal("BlaxTest_MissingShelf", SettingsPage.KindLabel(new StorageTemplate("storage:BlaxTest_MissingShelf")), "KindLabel of a kind that is not loaded");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("page: the status line counts defaults and names from inactive mods")]
|
||||||
|
public static void StatusLine_()
|
||||||
|
{
|
||||||
|
LibraryOf();
|
||||||
|
T.Equal("No defaults saved yet.", SettingsPage.StatusLine(), "status line of an empty library");
|
||||||
|
|
||||||
|
StorageTemplate clean = ShelfSteel();
|
||||||
|
LibraryOf(clean);
|
||||||
|
T.Equal("1 default.", SettingsPage.StatusLine(), "status line with one clean default");
|
||||||
|
|
||||||
|
StorageTemplate withMissing = ShelfSteel();
|
||||||
|
withMissing.allowed.Add("BlaxTest_Missing");
|
||||||
|
LibraryOf(withMissing);
|
||||||
|
T.Equal(1, SettingsPage.InactiveNameCount(withMissing), "inactive names of a template naming BlaxTest_Missing");
|
||||||
|
T.Equal("1 default. 1 name from a mod that is not active.", SettingsPage.StatusLine(), "status line");
|
||||||
|
T.Check(SettingsPage.RowSummary(withMissing).Contains("allows 1 of "), "the row counts the unresolved name: " + SettingsPage.RowSummary(withMissing));
|
||||||
|
|
||||||
|
// A kind from a removed mod is one more inactive name; its row still shows and can't be edited.
|
||||||
|
var gone = new StorageTemplate("storage:BlaxTest_MissingShelf");
|
||||||
|
gone.allowed.Add("Steel");
|
||||||
|
T.Equal(null, SettingsPage.DisabledReason(gone), "DisabledReason of a kind from a removed mod");
|
||||||
|
T.Equal(1, SettingsPage.InactiveNameCount(gone), "inactive names of a kind from a removed mod");
|
||||||
|
T.Equal(null, StorageKinds.ForKey(gone.key), "kind of storage:BlaxTest_MissingShelf");
|
||||||
|
|
||||||
|
var bill = new BillValues(DefaultsKeys.EveryBill) { storeMode = "DropOnFloor" };
|
||||||
|
LibraryOf(withMissing, gone, bill);
|
||||||
|
T.Equal("3 defaults. 2 names from mods that are not active.", SettingsPage.StatusLine(), "status line with three defaults");
|
||||||
|
T.Equal("Every new bill", SettingsPage.RowSummary(bill), "row of the every-bill values");
|
||||||
|
T.Check(!SettingsPage.StorageEntries().Contains(bill), "the every-bill values are listed as a storage row");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("dlc: without Biotech a Wastepack name in a stockpile default counts as an inactive name")]
|
||||||
|
public static void WastepackInactive()
|
||||||
|
{
|
||||||
|
if (ModsConfig.BiotechActive)
|
||||||
|
T.Skip("runs without Biotech only");
|
||||||
|
T.Equal(null, DefDatabase<ThingDef>.GetNamedSilentFail("Wastepack"), "Wastepack def without Biotech");
|
||||||
|
StorageTemplate t = Fixtures.Template(Fixtures.StockpileKind, StoragePriority.Normal, ThingDefOf.Steel);
|
||||||
|
t.refused.Add("Wastepack");
|
||||||
|
T.Equal(null, SettingsPage.DisabledReason(t), "DisabledReason of a stockpile default");
|
||||||
|
T.Equal(1, SettingsPage.InactiveNameCount(t), "inactive names");
|
||||||
|
LibraryOf(t);
|
||||||
|
T.Equal("1 default. 1 name from a mod that is not active.", SettingsPage.StatusLine(), "status line");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("dlc: a saved growth vat default shows disabled with Needs Biotech while Biotech is off")]
|
||||||
|
public static void GrowthVatDisabled()
|
||||||
|
{
|
||||||
|
var t = new StorageTemplate(DefaultsKeys.ForStorage("GrowthVat"));
|
||||||
|
t.allowed.Add("Steel");
|
||||||
|
t.allowed.Add("BlaxTest_Missing");
|
||||||
|
Fixtures.Save(t);
|
||||||
|
T.Check(SettingsPage.StorageEntries().Contains(t), "the growth vat default is not listed");
|
||||||
|
if (ModsConfig.BiotechActive)
|
||||||
|
{
|
||||||
|
T.Equal(null, SettingsPage.DisabledReason(t), "DisabledReason with Biotech");
|
||||||
|
T.Equal(1, SettingsPage.InactiveNameCount(t), "inactive names with Biotech (BlaxTest_Missing)");
|
||||||
|
T.Info("Biotech active: the growth vat row is enabled; the -NoDlc run checks the disabled row");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
T.Equal("Needs Biotech", SettingsPage.DisabledReason(t), "DisabledReason without Biotech");
|
||||||
|
T.Equal(0, SettingsPage.InactiveNameCount(t), "inactive names of a disabled row");
|
||||||
|
T.Equal("GrowthVat", SettingsPage.KindLabel(t), "KindLabel without Biotech");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("page: Forget removes the entry from the library and the page")]
|
||||||
|
public static void Forget()
|
||||||
|
{
|
||||||
|
StorageTemplate t = Fixtures.Save(ShelfSteel());
|
||||||
|
T.Check(SettingsPage.StorageEntries().Contains(t), "the saved shelf default is not listed");
|
||||||
|
T.Check(DefaultsLibrary.Forget(t.key), "Forget returned false");
|
||||||
|
T.Check(!SettingsPage.StorageEntries().Any(e => e.key == t.key), "the shelf default is still listed after Forget");
|
||||||
|
T.Check(!DefaultsLibrary.Has(t.key), "the shelf default is still in the library after Forget");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("page: storage rows list stockpile types first, then buildings by name, without the bill values")]
|
||||||
|
public static void StorageEntriesOrder()
|
||||||
|
{
|
||||||
|
LibraryOf(
|
||||||
|
new StorageTemplate("storage:Shelf"),
|
||||||
|
new BillValues(DefaultsKeys.EveryBill),
|
||||||
|
new StorageTemplate(DefaultsKeys.Dumping),
|
||||||
|
new StorageTemplate("stockpile:BlaxTest_Designator"),
|
||||||
|
new StorageTemplate(DefaultsKeys.Stockpile),
|
||||||
|
new StorageTemplate("storage:Bookcase"));
|
||||||
|
string order = string.Join(" ", SettingsPage.StorageEntries().Select(e => e.key));
|
||||||
|
T.Equal("stockpile:Stockpile stockpile:Dumping stockpile:BlaxTest_Designator storage:Bookcase storage:Shelf", order, "row order");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("page: the red line names the broken copies, and is empty for a clean load")]
|
||||||
|
public static void BrokenFilesLine_()
|
||||||
|
{
|
||||||
|
T.Equal(null, SettingsPage.BrokenFilesLine(new LoadResult()), "line for a clean load");
|
||||||
|
T.Equal(null, SettingsPage.BrokenFilesLine(null), "line for no load");
|
||||||
|
if (DefaultsLibrary.LastLoad.BrokenCopies.Count == 0)
|
||||||
|
T.Equal(null, SettingsPage.BrokenFilesLine(), "line for this run's startup load");
|
||||||
|
|
||||||
|
string folder = DefaultsFile.FolderPath;
|
||||||
|
const string main = "Defaults.broken-20261129-120000.xml";
|
||||||
|
const string bak = "Defaults.bak.broken-20261129-120000.xml";
|
||||||
|
var both = new LoadResult { BothFailed = true };
|
||||||
|
both.BrokenCopies.Add(Path.Combine(folder, main));
|
||||||
|
both.BrokenCopies.Add(Path.Combine(folder, bak));
|
||||||
|
string line = SettingsPage.BrokenFilesLine(both);
|
||||||
|
T.NotNull(line, "line when both files failed");
|
||||||
|
T.Info("both failed: " + line);
|
||||||
|
string shownFolder = Path.GetDirectoryName(Path.Combine(folder, main));
|
||||||
|
T.Check(line.Contains(main) && line.Contains(bak) && line.Contains(shownFolder), "the line doesn't name both copies and their folder: " + line);
|
||||||
|
|
||||||
|
var recovered = new LoadResult { LoadedFrom = DefaultsFile.BackupPath };
|
||||||
|
recovered.BrokenCopies.Add(Path.Combine(folder, main));
|
||||||
|
line = SettingsPage.BrokenFilesLine(recovered);
|
||||||
|
T.NotNull(line, "line when the backup loaded");
|
||||||
|
T.Check(line.Contains(main) && line.Contains(Path.GetFileName(DefaultsFile.BackupPath)), "the line doesn't name the copy and the backup: " + line);
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("page: a lone broken file gets the one-file line; unread and newer files get their own lines")]
|
||||||
|
public static void BrokenFilesLineCases()
|
||||||
|
{
|
||||||
|
string folder = DefaultsFile.FolderPath;
|
||||||
|
const string main = "Defaults.broken-20261129-120000.xml";
|
||||||
|
string shownFolder = Path.GetDirectoryName(Path.Combine(folder, main));
|
||||||
|
|
||||||
|
// Main file broken, no .bak ever written: Load sets BothFailed with one copy.
|
||||||
|
var lone = new LoadResult { BothFailed = true };
|
||||||
|
lone.BrokenCopies.Add(Path.Combine(folder, main));
|
||||||
|
string line = SettingsPage.BrokenFilesLine(lone);
|
||||||
|
T.Equal("BlaxDefaults_PageBrokenEmpty".Translate(shownFolder, main).Resolve(), line, "line for a lone broken file");
|
||||||
|
T.Check(!line.Contains("backup"), "the line for a lone broken file mentions a backup: " + line);
|
||||||
|
|
||||||
|
var unread = new LoadResult();
|
||||||
|
unread.Unread.Add(DefaultsFile.FilePath);
|
||||||
|
line = SettingsPage.BrokenFilesLine(unread);
|
||||||
|
T.Equal("BlaxDefaults_PageUnread".Translate(Path.GetDirectoryName(DefaultsFile.FilePath)).Resolve(), line, "line for an unread file");
|
||||||
|
|
||||||
|
const string kept = "Defaults.unread-20261129-120000.xml";
|
||||||
|
var moved = new LoadResult();
|
||||||
|
moved.UnreadCopies.Add(Path.Combine(folder, kept));
|
||||||
|
line = SettingsPage.BrokenFilesLine(moved);
|
||||||
|
T.Check(line != null && line.Contains(kept) && line.Contains(shownFolder), "the line doesn't name the moved file and its folder: " + line);
|
||||||
|
|
||||||
|
var newer = new LoadResult { LoadedFrom = DefaultsFile.FilePath, FormatVersion = DefaultsLibrary.FormatVersion + 1 };
|
||||||
|
T.Equal("BlaxDefaults_PageNewerFile".Translate().Resolve(), SettingsPage.BrokenFilesLine(newer), "line for a newer version's file");
|
||||||
|
var current = new LoadResult { LoadedFrom = DefaultsFile.FilePath, FormatVersion = DefaultsLibrary.FormatVersion };
|
||||||
|
T.Equal(null, SettingsPage.BrokenFilesLine(current), "line for a clean load of this version's file");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- edit window -----------------------------------------------------------------
|
||||||
|
|
||||||
|
[BlaxTest("edit window: unchanged, it builds the template it was opened with")]
|
||||||
|
public static void EditUnchanged()
|
||||||
|
{
|
||||||
|
StorageTemplate t = ShelfSteel(StoragePriority.Important);
|
||||||
|
t.unlisted = UnlistedRule.Refuse;
|
||||||
|
var w = new Dialog_EditStorageTemplate(Shelf, t);
|
||||||
|
T.NotNull(w.Scratch, "Scratch");
|
||||||
|
T.Equal(StoragePriority.Important, w.Scratch.Priority, "Scratch priority");
|
||||||
|
T.Check(w.Scratch.filter.Allows(ThingDefOf.Steel) && !w.Scratch.filter.Allows(ThingDefOf.WoodLog), "Scratch filter is not Steel only");
|
||||||
|
T.Equal(UnlistedRule.Refuse, w.Unlisted, "Unlisted");
|
||||||
|
StorageTemplate built = w.BuildTemplate();
|
||||||
|
T.Equal(Shelf.Key, built.key, "key of the built template");
|
||||||
|
T.Check(built.SameSettingsAs(t), "the built template differs from the one opened: " + Diff(t, built));
|
||||||
|
|
||||||
|
// Without a template (1.1 "Add a default") the window starts at the game's default.
|
||||||
|
var fresh = new Dialog_EditStorageTemplate(Shelf, null);
|
||||||
|
StorageTemplate gameDefault = Shelf.Capture(Shelf.GameDefault());
|
||||||
|
T.Equal(UnlistedRule.Game, fresh.Unlisted, "Unlisted without a template");
|
||||||
|
T.Check(fresh.BuildTemplate().SameSettingsAs(gameDefault), "without a template the window is not the game's default: " + Diff(gameDefault, fresh.BuildTemplate()));
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("edit window: changes to the filter, the priority and the unlisted rule reach the built template")]
|
||||||
|
public static void EditChanges()
|
||||||
|
{
|
||||||
|
StorageTemplate t = ShelfSteel();
|
||||||
|
var w = new Dialog_EditStorageTemplate(Shelf, t);
|
||||||
|
w.Scratch.filter.SetAllow(ThingDefOf.WoodLog, true);
|
||||||
|
w.Scratch.Priority = StoragePriority.Low;
|
||||||
|
w.Unlisted = UnlistedRule.Allow;
|
||||||
|
StorageTemplate built = w.BuildTemplate();
|
||||||
|
T.Check(built.allowed.Contains("WoodLog") && !built.refused.Contains("WoodLog"), "WoodLog is not allowed in the built template");
|
||||||
|
T.Check(built.allowed.Contains("Steel"), "Steel is no longer allowed");
|
||||||
|
T.Equal(StoragePriority.Low, built.Priority, "priority of the built template");
|
||||||
|
T.Equal(UnlistedRule.Allow, built.unlisted, "unlisted rule of the built template");
|
||||||
|
T.Check(!t.allowed.Contains("WoodLog"), "the window changed the template it was opened with");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("edit window: names from inactive mods survive in the list they were in")]
|
||||||
|
public static void EditKeepsUnresolved()
|
||||||
|
{
|
||||||
|
StorageTemplate t = ShelfSteel();
|
||||||
|
t.allowed.Add("BlaxTest_Missing");
|
||||||
|
t.refused.Add("BlaxTest_MissingRefused");
|
||||||
|
t.allowedSpecial.Add("BlaxTest_MissingFilter");
|
||||||
|
var w = new Dialog_EditStorageTemplate(Shelf, t);
|
||||||
|
w.Scratch.filter.SetAllow(ThingDefOf.WoodLog, true);
|
||||||
|
StorageTemplate built = w.BuildTemplate();
|
||||||
|
T.Check(built.allowed.Contains("BlaxTest_Missing"), "BlaxTest_Missing left the allowed list");
|
||||||
|
T.Check(built.refused.Contains("BlaxTest_MissingRefused"), "BlaxTest_MissingRefused left the refused list");
|
||||||
|
T.Check(built.allowedSpecial.Contains("BlaxTest_MissingFilter"), "BlaxTest_MissingFilter left the allowed special filters");
|
||||||
|
T.Check(!built.refused.Contains("BlaxTest_Missing") && !built.allowed.Contains("BlaxTest_MissingRefused"), "an unresolved name moved to the other list");
|
||||||
|
StorageTemplate again = w.BuildTemplate();
|
||||||
|
T.Equal(1, again.allowed.Count(n => n == "BlaxTest_Missing"), "copies of BlaxTest_Missing after a second build");
|
||||||
|
T.Equal(3, again.UnresolvedNames().Count(), "unresolved names after a second build");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("edit window: Save stores the template under the kind's key")]
|
||||||
|
public static void EditSave()
|
||||||
|
{
|
||||||
|
var w = new Dialog_EditStorageTemplate(Shelf, ShelfSteel());
|
||||||
|
w.Scratch.filter.SetAllow(ThingDefOf.WoodLog, true);
|
||||||
|
w.Save();
|
||||||
|
StorageTemplate saved = DefaultsLibrary.Get<StorageTemplate>(Shelf.Key);
|
||||||
|
T.NotNull(saved, "the saved shelf default");
|
||||||
|
T.Check(saved.allowed.Contains("WoodLog") && saved.allowed.Contains("Steel"), "the saved default doesn't allow Steel and WoodLog");
|
||||||
|
T.Check(saved.SameSettingsAs(w.BuildTemplate()), "the saved default differs from BuildTemplate: " + Diff(w.BuildTemplate(), saved));
|
||||||
|
|
||||||
|
var settings = new StorageSettings();
|
||||||
|
Shelf.LoadDefault(settings, saved);
|
||||||
|
T.Check(settings.filter.Allows(ThingDefOf.WoodLog) && settings.filter.Allows(ThingDefOf.Steel), "the saved default doesn't load as Steel and WoodLog");
|
||||||
|
|
||||||
|
StorageKind pile = Fixtures.StockpileKind;
|
||||||
|
var wp = new Dialog_EditStorageTemplate(pile, Fixtures.Template(pile, StoragePriority.Normal, ThingDefOf.Steel));
|
||||||
|
wp.Save();
|
||||||
|
T.NotNull(DefaultsLibrary.Get<StorageTemplate>(DefaultsKeys.Stockpile), "the stockpile default saved under " + DefaultsKeys.Stockpile);
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("edit window: the item filter's read of the game is bridged, so it draws from the main menu")]
|
||||||
|
public static void FilterGuard()
|
||||||
|
{
|
||||||
|
T.Info("patched: " + string.Join(", ", MainMenuFilterGuard.Replaced.Select(kv => kv.Key + " (getter " + kv.Value.getter + ", Matches " + kv.Value.matches + ")")));
|
||||||
|
T.Check(MainMenuFilterGuard.Ready, "the filter tree's reads of the game were not all replaced");
|
||||||
|
T.Check(MainMenuFilterGuard.Replaced.TryGetValue("DoCategoryChildren", out var children) && children.getter == 1,
|
||||||
|
"Find.HiddenItemsManager in Listing_TreeThingFilter.DoCategoryChildren was not replaced");
|
||||||
|
T.Check(MainMenuFilterGuard.Replaced.TryGetValue("DoThingDef", out var row) && row.matches == 1,
|
||||||
|
"QuickSearchFilter.Matches(ThingDef) in Listing_TreeThingFilter.DoThingDef was not replaced");
|
||||||
|
T.Check(ReferenceEquals(MainMenuFilterGuard.HiddenItems(), Find.HiddenItemsManager), "in a game the guard returns another manager than the game's");
|
||||||
|
var search = new QuickSearchFilter();
|
||||||
|
search.Text = "steel";
|
||||||
|
T.Equal(search.Matches(ThingDefOf.Steel), MainMenuFilterGuard.Matches(search, ThingDefOf.Steel), "Matches(Steel) in a game");
|
||||||
|
T.Equal(search.Matches(ThingDefOf.WoodLog), MainMenuFilterGuard.Matches(search, ThingDefOf.WoodLog), "Matches(WoodLog) in a game");
|
||||||
|
ThingDef hidden = DefDatabase<ThingDef>.AllDefsListForReading.FirstOrDefault(d => d.hiddenWhileUndiscovered);
|
||||||
|
if (hidden != null)
|
||||||
|
T.Check(!MainMenuFilterGuard.NothingHidden.Hidden(hidden), "the main menu manager hides " + hidden.defName);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,354 @@
|
||||||
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using BlaxDefaults;
|
||||||
|
using RimWorld;
|
||||||
|
using Verse;
|
||||||
|
|
||||||
|
namespace BlaxDefaultsTests
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Work package "setup". The tests of design.md: Quick setup: new shelves start empty; Overlap warnings.
|
||||||
|
/// Methods: [BlaxTest("<area>: <what>", phase: N)] public static void X(). Skip DLC-only checks with
|
||||||
|
/// Fixtures.NeedDlc(DlcSupport.Biotech) ("skipped: needs Biotech").
|
||||||
|
/// The end-to-end check "a shelf built afterwards allows nothing" needs the blueprint hook (package "hooks");
|
||||||
|
/// here the template goes through StorageKind.LoadDefault, the same path a new shelf takes.
|
||||||
|
/// </summary>
|
||||||
|
public static class SetupTests
|
||||||
|
{
|
||||||
|
private static readonly string[] SetupKeys =
|
||||||
|
{
|
||||||
|
"BlaxDefaults_QuickSetupButton", "BlaxDefaults_QuickSetupTip", "BlaxDefaults_QuickSetupTipFsf", "BlaxDefaults_QuickSetupTitle",
|
||||||
|
"BlaxDefaults_QuickSetupIntro", "BlaxDefaults_QuickSetupNone", "BlaxDefaults_QuickSetupHasDefault",
|
||||||
|
"BlaxDefaults_QuickSetupReasonHasDefault", "BlaxDefaults_QuickSetupReasonNotShelf", "BlaxDefaults_QuickSetupReasonHopper",
|
||||||
|
"BlaxDefaults_QuickSetupReasonOneCategory", "BlaxDefaults_QuickSetupSaved", "BlaxDefaults_WarnOverlaps",
|
||||||
|
"BlaxDefaults_WarnOverlapsTip", "BlaxDefaults_OverlapSettingsIntro", "BlaxDefaults_OverlapLine", "BlaxDefaults_OverlapAdvice",
|
||||||
|
"BlaxDefaults_OverlapTitle", "BlaxDefaults_OverlapMessage", "BlaxDefaults_OverlapDontRemind", "BlaxDefaults_OverlapDismissed",
|
||||||
|
"BlaxDefaults_OverlapWhatEmptyStorage", "BlaxDefaults_OverlapWhatRepeat",
|
||||||
|
};
|
||||||
|
|
||||||
|
// ---- quick setup ---------------------------------------------------------------
|
||||||
|
|
||||||
|
[BlaxTest("setup: the preselection saves empty Normal defaults for Shelf and ShelfSmall, none for Hopper or bookcases")]
|
||||||
|
public static void PreselectionSavesShelves()
|
||||||
|
{
|
||||||
|
ClearStorageEntries();
|
||||||
|
List<QuickSetup.Candidate> candidates = QuickSetup.Candidates();
|
||||||
|
T.Info("candidates: " + string.Join(", ", candidates.Select(c => c.Def.defName + (c.Ticked ? "+" : "-"))));
|
||||||
|
foreach (string name in new[] { "Shelf", "ShelfSmall" })
|
||||||
|
T.Check(Candidate(candidates, name).Ticked, name + " is not ticked");
|
||||||
|
foreach (string name in new[] { "Hopper", "Bookcase", "BookcaseSmall" })
|
||||||
|
T.Check(!Candidate(candidates, name).Ticked, name + " is ticked");
|
||||||
|
T.Check(candidates.All(c => !c.HasDefault), "a kind has a default after clearing the library");
|
||||||
|
|
||||||
|
int saved = QuickSetup.Apply(candidates.Where(c => c.Ticked).Select(c => c.Def));
|
||||||
|
T.Equal(candidates.Count(c => c.Ticked), saved, "defaults saved by Apply");
|
||||||
|
|
||||||
|
foreach (string name in new[] { "Shelf", "ShelfSmall" })
|
||||||
|
{
|
||||||
|
StorageKind kind = Fixtures.Kind(name);
|
||||||
|
StorageTemplate t = DefaultsLibrary.Get<StorageTemplate>(kind.Key);
|
||||||
|
T.NotNull(t, "the saved default for " + name);
|
||||||
|
T.Equal(StoragePriority.Normal, t.Priority, name + " priority");
|
||||||
|
T.Equal(0, t.allowed.Count, name + " allowed names");
|
||||||
|
T.Equal(UnlistedRule.Refuse, t.unlisted, name + " unlisted rule");
|
||||||
|
var storable = StorageKinds.StorableDefs(kind.ParentFilter).Select(d => d.defName).ToList();
|
||||||
|
T.Check(t.refused.Count == storable.Count && !storable.Except(t.refused).Any(),
|
||||||
|
name + " refuses " + t.refused.Count + " names, its parent allows " + storable.Count + " storable defs");
|
||||||
|
T.Check(t.refused.Contains(ThingDefOf.Steel.defName), name + " does not refuse Steel");
|
||||||
|
}
|
||||||
|
foreach (string name in new[] { "Hopper", "Bookcase", "BookcaseSmall" })
|
||||||
|
T.Check(!DefaultsLibrary.Has(Fixtures.Kind(name).Key), name + " got a default");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("setup: a kind with a default starts unticked and is marked")]
|
||||||
|
public static void ExistingDefaultUnticked()
|
||||||
|
{
|
||||||
|
ClearStorageEntries();
|
||||||
|
StorageKind shelf = Fixtures.Kind("Shelf");
|
||||||
|
StorageTemplate own = Fixtures.Save(Fixtures.Template(shelf, StoragePriority.Important, ThingDefOf.Steel));
|
||||||
|
List<QuickSetup.Candidate> candidates = QuickSetup.Candidates();
|
||||||
|
QuickSetup.Candidate c = Candidate(candidates, "Shelf");
|
||||||
|
T.Check(c.HasDefault, "Shelf is not marked as having a default");
|
||||||
|
T.Check(!c.Ticked, "Shelf with a default is ticked");
|
||||||
|
T.Check(QuickSetup.Preselect(shelf.Def), "Preselect(Shelf) is false");
|
||||||
|
QuickSetup.Candidate small = Candidate(candidates, "ShelfSmall");
|
||||||
|
T.Check(!small.HasDefault && small.Ticked, "ShelfSmall without a default is not ticked or is marked");
|
||||||
|
|
||||||
|
QuickSetup.Apply(candidates.Where(x => x.Ticked).Select(x => x.Def));
|
||||||
|
T.Check(DefaultsLibrary.Get<StorageTemplate>(shelf.Key).SameSettingsAs(own), "Apply replaced the unticked Shelf default");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("setup: top-level categories count by each def's first category")]
|
||||||
|
public static void TopLevelCategories()
|
||||||
|
{
|
||||||
|
ThingDef widget = Fixtures.Thing("BlaxTest_Widget");
|
||||||
|
T.Equal(ThingCategoryDefOf.Manufactured, QuickSetup.TopLevelCategoryOf(widget), "top-level category of BlaxTest_Widget");
|
||||||
|
var f = new ThingFilter();
|
||||||
|
f.SetAllow(widget, true);
|
||||||
|
T.Equal(1, QuickSetup.TopLevelCategoryCount(f), "categories of a widget-only filter");
|
||||||
|
f.SetAllow(ThingDefOf.ComponentIndustrial, true);
|
||||||
|
T.Equal(1, QuickSetup.TopLevelCategoryCount(f), "categories of widgets and components");
|
||||||
|
f.SetAllow(ThingDefOf.Steel, true);
|
||||||
|
T.Equal(2, QuickSetup.TopLevelCategoryCount(f), "categories with Steel added");
|
||||||
|
T.Equal(0, QuickSetup.TopLevelCategoryCount(new ThingFilter()), "categories of an empty filter");
|
||||||
|
T.Check(QuickSetup.TopLevelCategoryCount(StorageKinds.ParentFilterFor(Fixtures.Thing("Shelf"))) >= 2, "the shelf's parent filter has fewer than two categories");
|
||||||
|
T.Equal("BlaxDefaults_QuickSetupReasonHopper", QuickSetup.UntickedReason(Fixtures.Thing("Hopper")), "why the hopper is unticked");
|
||||||
|
T.Equal("BlaxDefaults_QuickSetupReasonNotShelf", QuickSetup.UntickedReason(Fixtures.Thing("Bookcase")), "why the bookcase is unticked");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("setup: the empty template loaded onto a shelf allows nothing, at Normal")]
|
||||||
|
public static void EmptyTemplateAllowsNothing()
|
||||||
|
{
|
||||||
|
StorageKind kind = Fixtures.Kind("Shelf");
|
||||||
|
StorageTemplate t = QuickSetup.EmptyTemplate(kind.Def);
|
||||||
|
T.Equal(kind.Key, t.key, "key");
|
||||||
|
T.Check(!DefaultsLibrary.Has(kind.Key) || DefaultsLibrary.Get(kind.Key) != t, "EmptyTemplate saved the template");
|
||||||
|
|
||||||
|
var s = new StorageSettings();
|
||||||
|
kind.LoadDefault(s, t);
|
||||||
|
T.Equal(StoragePriority.Normal, s.Priority, "priority");
|
||||||
|
var allowed = StorageKinds.StorableDefs(kind.ParentFilter).Where(d => s.filter.Allows(d)).Select(d => d.defName).ToList();
|
||||||
|
T.Check(allowed.Count == 0, "the shelf allows " + allowed.Count + " storable defs: " + string.Join(", ", allowed.Take(5)));
|
||||||
|
T.Info("defs still allowed outside the storable set: " + s.filter.AllowedDefCount);
|
||||||
|
T.Check(T.ErrorsSoFar().Count == 0, "loading the empty template logged errors");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("setup: a shelf built after the quick setup allows nothing, at Normal, and Apply writes the file once")]
|
||||||
|
public static void ShelfBuiltAfterSetupAllowsNothing()
|
||||||
|
{
|
||||||
|
ClearStorageEntries();
|
||||||
|
int changes = 0;
|
||||||
|
Action counter = () => changes++;
|
||||||
|
DefaultsLibrary.Changed += counter;
|
||||||
|
int saved;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
saved = QuickSetup.Apply(QuickSetup.Candidates().Where(c => c.Ticked).Select(c => c.Def));
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
DefaultsLibrary.Changed -= counter;
|
||||||
|
}
|
||||||
|
T.Check(saved >= 2, "the quick setup saved " + saved + " defaults");
|
||||||
|
T.Equal(1, changes, "library writes for one quick setup");
|
||||||
|
T.Check(DefaultsLibrary.LastWriteOk, "the defaults file write failed");
|
||||||
|
|
||||||
|
StorageKind kind = Fixtures.Kind("Shelf");
|
||||||
|
CellRect area = Fixtures.EmptyArea(3, 3);
|
||||||
|
Thing shelf = HooksTests.Build(ThingDefOf.Shelf, ThingDefOf.WoodLog, area.CenterCell);
|
||||||
|
StorageSettings s = HooksTests.SettingsOf(shelf);
|
||||||
|
T.Equal(StoragePriority.Normal, s.Priority, "built shelf priority");
|
||||||
|
var allowed = StorageKinds.StorableDefs(kind.ParentFilter).Where(d => s.filter.Allows(d)).Select(d => d.defName).ToList();
|
||||||
|
T.Check(allowed.Count == 0, "the built shelf allows " + allowed.Count + " storable defs: " + string.Join(", ", allowed.Take(5)));
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("setup: an item a mod adds later is refused, and follows the def default with unlisted Game")]
|
||||||
|
public static void LaterItemRefused()
|
||||||
|
{
|
||||||
|
StorageKind kind = Fixtures.Kind("Shelf");
|
||||||
|
ThingDef widget = Fixtures.Thing("BlaxTest_Widget");
|
||||||
|
T.Check(kind.GameDefault().filter.Allows(widget), "the shelf's def default refuses BlaxTest_Widget");
|
||||||
|
StorageTemplate t = QuickSetup.EmptyTemplate(kind.Def);
|
||||||
|
T.Check(t.refused.Remove(widget.defName), "the empty template does not list BlaxTest_Widget");
|
||||||
|
T.Check(!t.allowed.Contains(widget.defName), "the empty template allows BlaxTest_Widget");
|
||||||
|
|
||||||
|
var refuse = new StorageSettings();
|
||||||
|
kind.LoadDefault(refuse, t);
|
||||||
|
T.Check(!refuse.filter.Allows(widget), "unlisted Refuse: the shelf allows BlaxTest_Widget");
|
||||||
|
|
||||||
|
t.unlisted = UnlistedRule.Game;
|
||||||
|
var game = new StorageSettings();
|
||||||
|
kind.LoadDefault(game, t);
|
||||||
|
T.Check(game.filter.Allows(widget), "unlisted Game: the shelf refuses BlaxTest_Widget, its def default allows it");
|
||||||
|
T.Check(!game.filter.Allows(ThingDefOf.Steel), "unlisted Game: the shelf allows Steel");
|
||||||
|
T.Equal(StoragePriority.Normal, game.Priority, "unlisted Game: priority");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("setup: each candidate carries its unticked reason, worked out once, and Ticked follows it")]
|
||||||
|
public static void CandidateReasons()
|
||||||
|
{
|
||||||
|
ClearStorageEntries();
|
||||||
|
List<QuickSetup.Candidate> candidates = QuickSetup.Candidates();
|
||||||
|
T.Equal(null, Candidate(candidates, "Shelf").UntickedReason, "reason stored for Shelf");
|
||||||
|
T.Equal("BlaxDefaults_QuickSetupReasonHopper", Candidate(candidates, "Hopper").UntickedReason, "reason stored for Hopper");
|
||||||
|
T.Equal("BlaxDefaults_QuickSetupReasonNotShelf", Candidate(candidates, "Bookcase").UntickedReason, "reason stored for Bookcase");
|
||||||
|
foreach (QuickSetup.Candidate c in candidates)
|
||||||
|
{
|
||||||
|
T.Equal(QuickSetup.UntickedReason(c.Def), c.UntickedReason, c.Def.defName + ": stored reason");
|
||||||
|
T.Equal(c.UntickedReason == null && !c.HasDefault, c.Ticked, c.Def.defName + ": ticked");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// design.md expects the fridge ticked, but RimFridge sets building.isHopper on its FridgeBase (its 1.6
|
||||||
|
// Defs/ThingDefs_Buildings/Fridge_Base.xml:75), so paste dispensers draw from fridges, and the quick
|
||||||
|
// setup's own hopper rule leaves it unticked: an empty default would starve them like an empty hopper.
|
||||||
|
[BlaxTest("setup: -Compat: the RimFridge fridge is unticked as a hopper")]
|
||||||
|
public static void CompatFridgeUnticked()
|
||||||
|
{
|
||||||
|
if (!Compat.IsActive(Compat.RimFridge))
|
||||||
|
T.Skip("needs RimFridge (-Compat)");
|
||||||
|
ClearStorageEntries();
|
||||||
|
List<QuickSetup.Candidate> candidates = QuickSetup.Candidates();
|
||||||
|
T.Info("RimFridge kinds: " + string.Join(", ", candidates.Where(c => c.Def.defName.StartsWith("RimFridge_")).Select(c => c.Def.defName + (c.Ticked ? "+" : "-"))));
|
||||||
|
QuickSetup.Candidate fridge = Candidate(candidates, "RimFridge_Refrigerator");
|
||||||
|
T.Check(fridge.Def.building.isHopper, "RimFridge_Refrigerator is no longer a hopper: revisit this test");
|
||||||
|
T.Check(!fridge.Ticked, "RimFridge_Refrigerator is ticked");
|
||||||
|
T.Equal("BlaxDefaults_QuickSetupReasonHopper", fridge.UntickedReason, "why RimFridge_Refrigerator is unticked");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("setup: -Compat: Weapon Racks racks are unticked")]
|
||||||
|
public static void CompatWeaponRackUnticked()
|
||||||
|
{
|
||||||
|
if (!Compat.IsActive(Compat.WeaponRacks))
|
||||||
|
T.Skip("needs Weapon Racks (-Compat)");
|
||||||
|
ClearStorageEntries();
|
||||||
|
List<QuickSetup.Candidate> racks = QuickSetup.Candidates().Where(c => c.Def.defName.StartsWith("WeaponRacks_")).ToList();
|
||||||
|
T.Check(racks.Count > 0, "no Weapon Racks kind in the list");
|
||||||
|
T.Info("Weapon Racks kinds: " + string.Join(", ", racks.Select(c => c.Def.defName)));
|
||||||
|
T.Check(racks.All(c => !c.Ticked), "ticked racks: " + string.Join(", ", racks.Where(c => c.Ticked).Select(c => c.Def.defName)));
|
||||||
|
T.Equal("BlaxDefaults_QuickSetupReasonOneCategory", QuickSetup.UntickedReason(racks[0].Def), "why a rack is unticked");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- overlap warnings ----------------------------------------------------------
|
||||||
|
|
||||||
|
[BlaxTest("overlap: the list has unique ids, translated descriptions and every key")]
|
||||||
|
public static void OverlapList()
|
||||||
|
{
|
||||||
|
var ids = OverlapWarnings.Mods.Select(m => m.PackageId.ToLowerInvariant()).ToList();
|
||||||
|
T.Check(ids.Count > 0, "no overlap mods listed");
|
||||||
|
T.Equal(ids.Count, ids.Distinct().Count(), "distinct package ids");
|
||||||
|
T.Check(!ids.Contains("blax.defaults"), "Blax Defaults lists itself");
|
||||||
|
var missing = OverlapWarnings.Mods.Select(m => m.WhatKey).Concat(SetupKeys).Where(k => !k.CanTranslate()).Distinct().ToList();
|
||||||
|
T.Check(missing.Count == 0, "strings missing from Keyed: " + string.Join(", ", missing));
|
||||||
|
T.Info("really active: " + string.Join(", ", OverlapWarnings.Mods.Where(m => Compat.IsActive(m.PackageId)).Select(m => m.Name)));
|
||||||
|
T.Equal(null, OverlapWarnings.MessageText(new List<OverlapMod>()), "message text for no mods");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("overlap: an injected id shows on the settings page and in the window, once per session")]
|
||||||
|
public static void OverlapShownOnce()
|
||||||
|
{
|
||||||
|
OverlapMod mod = SimulatedMod(0);
|
||||||
|
Fixtures.Settings.warnOverlaps = true;
|
||||||
|
Fixtures.Settings.dismissedOverlaps = new List<string>();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
OverlapWarnings.ResetSessionForTests();
|
||||||
|
OverlapWarnings.SimulatedActive.Add(mod.PackageId);
|
||||||
|
T.Check(OverlapWarnings.Active().Contains(mod), "Active() misses the injected mod");
|
||||||
|
T.Check(OverlapWarnings.IsActive(mod.PackageId), "IsActive misses the injected mod");
|
||||||
|
|
||||||
|
string text = OverlapWarnings.SettingsText();
|
||||||
|
T.NotNull(text, "SettingsText");
|
||||||
|
T.Check(text.Contains(mod.Name) && text.Contains(mod.What), "SettingsText does not name " + mod.Name + " and what it sets: " + text);
|
||||||
|
string message = OverlapWarnings.MessageText(new List<OverlapMod> { mod });
|
||||||
|
T.Check(message != null && message.Contains(mod.Name), "MessageText does not name " + mod.Name);
|
||||||
|
|
||||||
|
List<OverlapMod> first = OverlapWarnings.ShowOncePerSession();
|
||||||
|
T.Check(first.Contains(mod), "the first call of the session does not name " + mod.Name);
|
||||||
|
Dialog_OverlapWarnings window = Find.WindowStack.WindowOfType<Dialog_OverlapWarnings>();
|
||||||
|
T.Check(window != null && window.Mods.Contains(mod), "no overlap window naming " + mod.Name);
|
||||||
|
List<OverlapMod> second = OverlapWarnings.ShowOncePerSession();
|
||||||
|
T.Equal(0, second.Count, "mods named by the second call of the session");
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
OverlapWarnings.SimulatedActive.Clear();
|
||||||
|
OverlapWarnings.ResetSessionForTests();
|
||||||
|
CloseOverlapWindows();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("overlap: a dismissed id is not shown again, and Dismiss keeps it in the mod settings")]
|
||||||
|
public static void OverlapDismissed()
|
||||||
|
{
|
||||||
|
OverlapMod dismissed = SimulatedMod(0);
|
||||||
|
OverlapMod other = SimulatedMod(1);
|
||||||
|
Fixtures.Settings.warnOverlaps = true;
|
||||||
|
Fixtures.Settings.dismissedOverlaps = new List<string>();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
OverlapWarnings.ResetSessionForTests();
|
||||||
|
OverlapWarnings.SimulatedActive.Add(dismissed.PackageId);
|
||||||
|
OverlapWarnings.SimulatedActive.Add(other.PackageId);
|
||||||
|
OverlapWarnings.Dismiss(dismissed.PackageId.ToUpperInvariant());
|
||||||
|
OverlapWarnings.Dismiss(dismissed.PackageId);
|
||||||
|
T.Equal(1, Fixtures.Settings.dismissedOverlaps.Count, "dismissed ids after dismissing one id twice");
|
||||||
|
T.Check(OverlapWarnings.IsDismissed(dismissed.PackageId), "IsDismissed is false after Dismiss");
|
||||||
|
|
||||||
|
List<OverlapMod> shown = OverlapWarnings.ShowOncePerSession();
|
||||||
|
T.Check(!shown.Contains(dismissed), "the dismissed " + dismissed.Name + " is shown");
|
||||||
|
T.Check(shown.Contains(other), "the not dismissed " + other.Name + " is not shown");
|
||||||
|
// The settings page names every active mod; "Don't remind me" only stops the window.
|
||||||
|
string text = OverlapWarnings.SettingsText();
|
||||||
|
T.Check(text != null && text.Contains(dismissed.Name), "SettingsText drops the dismissed mod");
|
||||||
|
|
||||||
|
OverlapWarnings.ResetSessionForTests();
|
||||||
|
CloseOverlapWindows();
|
||||||
|
OverlapWarnings.Dismiss(other.PackageId);
|
||||||
|
T.Equal(0, OverlapWarnings.ShowOncePerSession().Count, "mods shown with every active one dismissed");
|
||||||
|
T.Check(!Find.WindowStack.IsOpen(typeof(Dialog_OverlapWarnings)), "an overlap window opened with nothing to show");
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
OverlapWarnings.SimulatedActive.Clear();
|
||||||
|
OverlapWarnings.ResetSessionForTests();
|
||||||
|
CloseOverlapWindows();
|
||||||
|
// Dismiss wrote the mod settings; write them back without the test's ids.
|
||||||
|
Fixtures.Settings.dismissedOverlaps = new List<string>();
|
||||||
|
Fixtures.Settings.Write();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("overlap: with warnOverlaps off, no settings text and nothing shown")]
|
||||||
|
public static void OverlapOff()
|
||||||
|
{
|
||||||
|
OverlapMod mod = SimulatedMod(0);
|
||||||
|
Fixtures.Settings.warnOverlaps = false;
|
||||||
|
Fixtures.Settings.dismissedOverlaps = new List<string>();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
OverlapWarnings.ResetSessionForTests();
|
||||||
|
OverlapWarnings.SimulatedActive.Add(mod.PackageId);
|
||||||
|
T.Equal(null, OverlapWarnings.SettingsText(), "SettingsText with warnOverlaps off");
|
||||||
|
T.Equal(0, OverlapWarnings.ShowOncePerSession().Count, "mods shown with warnOverlaps off");
|
||||||
|
T.Check(!Find.WindowStack.IsOpen(typeof(Dialog_OverlapWarnings)), "an overlap window opened with warnOverlaps off");
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
OverlapWarnings.SimulatedActive.Clear();
|
||||||
|
OverlapWarnings.ResetSessionForTests();
|
||||||
|
CloseOverlapWindows();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- helpers -------------------------------------------------------------------
|
||||||
|
|
||||||
|
private static QuickSetup.Candidate Candidate(List<QuickSetup.Candidate> candidates, string defName)
|
||||||
|
{
|
||||||
|
QuickSetup.Candidate c = candidates.FirstOrDefault(x => x.Def.defName == defName);
|
||||||
|
T.NotNull(c, defName + " in the quick setup list");
|
||||||
|
return c;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Drops every storage building default from the library in memory; the runner restores it after the test.</summary>
|
||||||
|
private static void ClearStorageEntries() =>
|
||||||
|
DefaultsLibrary.RestoreForTests(DefaultsLibrary.Snapshot().Where(e => !DefaultsKeys.IsStorage(e.key)).ToList());
|
||||||
|
|
||||||
|
/// <summary>The n-th listed overlap mod that is not really active, to inject.</summary>
|
||||||
|
private static OverlapMod SimulatedMod(int n)
|
||||||
|
{
|
||||||
|
List<OverlapMod> inactive = OverlapWarnings.Mods.Where(m => !Compat.IsActive(m.PackageId)).ToList();
|
||||||
|
if (inactive.Count <= n)
|
||||||
|
T.Skip("needs " + (n + 1) + " overlap mods that are not active");
|
||||||
|
return inactive[n];
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void CloseOverlapWindows()
|
||||||
|
{
|
||||||
|
while (Find.WindowStack != null && Find.WindowStack.TryRemove(typeof(Dialog_OverlapWarnings), doCloseSound: false))
|
||||||
|
{
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,170 @@
|
||||||
|
using System;
|
||||||
|
using System.IO;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Text.RegularExpressions;
|
||||||
|
using BlaxDefaults;
|
||||||
|
using HarmonyLib;
|
||||||
|
using RimWorld;
|
||||||
|
using Verse;
|
||||||
|
|
||||||
|
namespace BlaxDefaultsTests
|
||||||
|
{
|
||||||
|
/// <summary>The harness and the shared types (integrator). Feature tests live in each package's own file.</summary>
|
||||||
|
public static class SmokeTests
|
||||||
|
{
|
||||||
|
private static readonly string[] SharedKeys =
|
||||||
|
{
|
||||||
|
"BlaxDefaults_NeedsDlc", "BlaxDefaults_KindStockpile", "BlaxDefaults_KindStockpilePlural", "BlaxDefaults_KindDumping",
|
||||||
|
"BlaxDefaults_KindDumpingPlural", "BlaxDefaults_UnlistedGame", "BlaxDefaults_UnlistedRefuse", "BlaxDefaults_UnlistedAllow",
|
||||||
|
};
|
||||||
|
|
||||||
|
[BlaxTest("startup: every patch class applied and logged, no errors mentioning Blax Defaults")]
|
||||||
|
public static void StartupLogged()
|
||||||
|
{
|
||||||
|
int classes = typeof(BlaxDefaultsStartup).Assembly.GetTypes().Count(t => t.IsDefined(typeof(HarmonyPatch), false));
|
||||||
|
int ours = Harmony.GetAllPatchedMethods()
|
||||||
|
.Select(Harmony.GetPatchInfo)
|
||||||
|
.Where(info => info != null)
|
||||||
|
.SelectMany(info => info.Prefixes.Concat(info.Postfixes).Concat(info.Finalizers).Concat(info.Transpilers))
|
||||||
|
.Count(p => p.owner == BlaxDefaultsStartup.HarmonyId);
|
||||||
|
T.Info("patch classes: " + classes + ", Harmony patches owned by " + BlaxDefaultsStartup.HarmonyId + ": " + ours);
|
||||||
|
T.Equal(0, BlaxDefaultsStartup.PatchesFailed, "patch classes that failed");
|
||||||
|
T.Equal(classes, BlaxDefaultsStartup.PatchesApplied, "patch classes applied");
|
||||||
|
bool logged = Log.Messages.Any(m => m.text != null && m.text.Contains("[Blax Defaults] " + classes + " patches applied"));
|
||||||
|
T.Check(logged, "startup line '[Blax Defaults] " + classes + " patches applied' not in the log");
|
||||||
|
// Only what was logged before the first test: tests that expect errors (a failed write) log them later.
|
||||||
|
var errors = TestRunner.StartupErrors.Where(t => t.Contains("Blax Defaults") || t.Contains("BlaxDefaults")).ToList();
|
||||||
|
T.Check(errors.Count == 0, "errors mentioning Blax Defaults at startup: " + string.Join(" | ", errors.Take(3)));
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("startup: settings, the library and the shared strings are loaded")]
|
||||||
|
public static void Loaded()
|
||||||
|
{
|
||||||
|
T.NotNull(BlaxDefaultsMod.Settings, "BlaxDefaultsMod.Settings");
|
||||||
|
T.Check(DefaultsLibrary.LoadedAtStartup, "DefaultsLibrary.LoadAtStartup did not run");
|
||||||
|
T.Info("library entries at the first test: " + DefaultsLibrary.Count + ", Royalty: " + ModsConfig.RoyaltyActive
|
||||||
|
+ ", Ideology: " + ModsConfig.IdeologyActive + ", Biotech: " + ModsConfig.BiotechActive);
|
||||||
|
var missing = SharedKeys.Where(k => !k.CanTranslate()).ToList();
|
||||||
|
T.Check(missing.Count == 0, "strings missing from Keyed: " + string.Join(", ", missing));
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("compat: IsActive finds Blax Defaults and the base game, not a made-up id")]
|
||||||
|
public static void IsActiveWorks()
|
||||||
|
{
|
||||||
|
T.Check(Compat.IsActive("blax.defaults"), "Compat.IsActive(\"blax.defaults\") is false while Blax Defaults runs");
|
||||||
|
T.Check(Compat.IsActive("ludeon.rimworld"), "Compat.IsActive(\"ludeon.rimworld\") is false");
|
||||||
|
T.Check(!Compat.IsActive("blax.defaults.does.not.exist"), "Compat.IsActive is true for a made-up id");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("dlc: DefOf MayRequire attributes name the DLC of a def")]
|
||||||
|
public static void DlcOfDefs()
|
||||||
|
{
|
||||||
|
T.Equal(DlcSupport.Biotech, DlcSupport.RequiredDlcOfThing("GrowthVat"), "DLC of GrowthVat");
|
||||||
|
T.Equal(DlcSupport.Ideology, DlcSupport.RequiredDlcOfThing("BiosculpterPod"), "DLC of BiosculpterPod");
|
||||||
|
T.Equal(null, DlcSupport.RequiredDlcOfThing("Shelf"), "DLC of Shelf");
|
||||||
|
T.Equal(null, DlcSupport.RequiredDlcOfThing("BlaxTest_Missing"), "DLC of a made-up name");
|
||||||
|
T.Equal(ModsConfig.BiotechActive ? null : DlcSupport.Biotech, DlcSupport.MissingDlcOfThing("GrowthVat"), "missing DLC of GrowthVat");
|
||||||
|
T.Equal("Needs Biotech", DlcSupport.NeedsLabel(DlcSupport.Biotech), "NeedsLabel");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("kinds: stockpile types, covered buildings, parent filters and the game's defaults")]
|
||||||
|
public static void Kinds()
|
||||||
|
{
|
||||||
|
T.Check(StorageKinds.StockpileTypes.Count >= 2, "fewer than two stockpile types");
|
||||||
|
T.Equal(DefaultsKeys.Stockpile, StorageKinds.StockpileTypes[0].Key, "first stockpile type");
|
||||||
|
T.Equal(DefaultsKeys.Dumping, StorageKinds.StockpileTypes[1].Key, "second stockpile type");
|
||||||
|
T.Equal("stockpile", StorageKinds.VanillaStockpile.Label, "stockpile label");
|
||||||
|
foreach (string name in new[] { "Shelf", "ShelfSmall", "Bookcase", "BookcaseSmall", "Hopper" })
|
||||||
|
T.Check(StorageKinds.IsCovered(Fixtures.Thing(name)), name + " is not covered");
|
||||||
|
T.Check(!StorageKinds.IsCovered(Fixtures.Thing("Grave")), "Grave is covered in 1.0");
|
||||||
|
T.Check(!StorageKinds.ParentFilterFor(Fixtures.Thing("Shelf")).Allows(ThingDefOf.ChunkSlagSteel), "the shelf's parent filter allows slag chunks");
|
||||||
|
|
||||||
|
StorageSettings shelf = Fixtures.Kind("Shelf").GameDefault();
|
||||||
|
T.Equal(StoragePriority.Preferred, shelf.Priority, "shelf game default priority");
|
||||||
|
T.Check(shelf.filter.Allows(ThingDefOf.Steel), "shelf game default refuses Steel");
|
||||||
|
StorageSettings pile = Fixtures.StockpileKind.GameDefault();
|
||||||
|
T.Equal(StoragePriority.Normal, pile.Priority, "stockpile game default priority");
|
||||||
|
T.Check(pile.filter.Allows(ThingDefOf.Steel) && pile.filter.Allows(ThingDefOf.MealSimple), "stockpile game default refuses Steel or MealSimple");
|
||||||
|
StorageSettings dump = Fixtures.DumpingKind.GameDefault();
|
||||||
|
T.Check(!dump.filter.Allows(ThingDefOf.Steel), "dumping game default allows Steel");
|
||||||
|
T.Check(dump.filter.Allows(ThingDefOf.ChunkSlagSteel), "dumping game default refuses slag chunks");
|
||||||
|
ThingDef wastepack = DefDatabase<ThingDef>.GetNamedSilentFail("Wastepack");
|
||||||
|
T.Equal(ModsConfig.BiotechActive, wastepack != null && dump.filter.Allows(wastepack), "dumping game default allows Wastepack");
|
||||||
|
T.Equal(Fixtures.Kind("Shelf").Key, StorageKinds.ForKey("storage:Shelf")?.Key, "ForKey(storage:Shelf)");
|
||||||
|
T.Equal(null, StorageKinds.ForKey("storage:BlaxTest_Missing"), "ForKey of a missing def");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("template: capture and apply round-trip, missing names are kept and skipped silently")]
|
||||||
|
public static void TemplateRoundTrip()
|
||||||
|
{
|
||||||
|
StorageKind kind = Fixtures.Kind("Shelf");
|
||||||
|
StorageTemplate t = Fixtures.Template(kind, StoragePriority.Important, ThingDefOf.Steel);
|
||||||
|
T.Check(t.allowed.SequenceEqual(new[] { "Steel" }), "allowed is " + string.Join(",", t.allowed));
|
||||||
|
T.Check(!t.refused.Contains("ChunkSlagSteel"), "the template names a def the shelf's parent refuses");
|
||||||
|
t.allowed.Add("BlaxTest_Missing");
|
||||||
|
T.Check(t.UnresolvedNames().SequenceEqual(new[] { "BlaxTest_Missing" }), "unresolved names: " + string.Join(",", t.UnresolvedNames()));
|
||||||
|
|
||||||
|
var target = new StorageSettings();
|
||||||
|
kind.LoadDefault(target, t);
|
||||||
|
T.Equal(StoragePriority.Important, target.Priority, "priority after LoadDefault");
|
||||||
|
T.Check(target.filter.Allows(ThingDefOf.Steel), "Steel refused after LoadDefault");
|
||||||
|
T.Check(!target.filter.Allows(ThingDefOf.WoodLog), "WoodLog allowed after LoadDefault");
|
||||||
|
T.Check(kind.Capture(target).SameSettingsAs(Fixtures.Template(kind, StoragePriority.Important, ThingDefOf.Steel)), "captured settings differ from the template");
|
||||||
|
T.Check(t.Clone().Fingerprint() == t.Fingerprint(), "a clone has another fingerprint");
|
||||||
|
T.Check(T.ErrorsSoFar().Count == 0, "applying the template logged errors");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("template: the unlisted rule decides items the template lists in neither list")]
|
||||||
|
public static void UnlistedRule_()
|
||||||
|
{
|
||||||
|
StorageKind kind = Fixtures.Kind("Shelf");
|
||||||
|
ThingDef widget = Fixtures.Thing("BlaxTest_Widget");
|
||||||
|
T.Check(kind.GameDefault().filter.Allows(widget), "the shelf's def default refuses BlaxTest_Widget");
|
||||||
|
StorageTemplate empty = Fixtures.Template(kind, StoragePriority.Normal);
|
||||||
|
empty.refused.Remove(widget.defName);
|
||||||
|
var s = new StorageSettings();
|
||||||
|
foreach (var (rule, allows) in new[] { (UnlistedRule.Refuse, false), (UnlistedRule.Game, true), (UnlistedRule.Allow, true) })
|
||||||
|
{
|
||||||
|
empty.unlisted = rule;
|
||||||
|
kind.LoadDefault(s, empty);
|
||||||
|
T.Equal(allows, s.filter.Allows(widget), "widget allowed with unlisted = " + rule);
|
||||||
|
T.Check(!s.filter.Allows(ThingDefOf.Steel), "Steel allowed with unlisted = " + rule);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("library: set, get, forget and the test restore, in memory")]
|
||||||
|
public static void Library()
|
||||||
|
{
|
||||||
|
int before = DefaultsLibrary.Count;
|
||||||
|
var bill = new BillValues(DefaultsKeys.EveryBill) { storeMode = "DropOnFloor", setIngredientSearchRadius = true, ingredientSearchRadius = 30f };
|
||||||
|
Fixtures.Save(bill);
|
||||||
|
T.Check(DefaultsLibrary.Get<BillValues>(DefaultsKeys.EveryBill) == bill, "Get does not return the saved entry");
|
||||||
|
T.Check(bill.AnySet, "AnySet is false");
|
||||||
|
T.Check(bill.CloneValues().Fingerprint() == bill.Fingerprint(), "a clone has another fingerprint");
|
||||||
|
T.Check(DefaultsLibrary.Forget(DefaultsKeys.EveryBill), "Forget returned false");
|
||||||
|
T.Check(!DefaultsLibrary.Has(DefaultsKeys.EveryBill), "entry still there after Forget");
|
||||||
|
T.Equal(before, DefaultsLibrary.Count, "count after Forget");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("harness: empty area and worker fixtures")]
|
||||||
|
public static void Fixtures_()
|
||||||
|
{
|
||||||
|
CellRect r = Fixtures.EmptyArea(3, 3);
|
||||||
|
T.Check(r.Cells.All(c => c.GetZone(Fixtures.Map) == null), "empty area has a zone");
|
||||||
|
T.Check(Fixtures.Worker().Spawned, "worker is not spawned");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("save: the save holds nothing of Blax Defaults outside the mod list", phase: 2)]
|
||||||
|
public static void NothingInSave()
|
||||||
|
{
|
||||||
|
string path = GenFilePaths.FilePathForSavedGame(TestRunner.SaveName);
|
||||||
|
T.Check(File.Exists(path), "no save at " + path);
|
||||||
|
string text = File.ReadAllText(path);
|
||||||
|
int metaEnd = text.IndexOf("</meta>", StringComparison.Ordinal);
|
||||||
|
string body = metaEnd < 0 ? text : text.Substring(metaEnd);
|
||||||
|
// The test runner is a GameComponent of the test mod, BlaxDefaultsTests.TestRunner; it is allowed.
|
||||||
|
var hits = Regex.Matches(body, @"BlaxDefaults(?!Tests)|blax\.defaults(?!\.tests)").Cast<Match>().Select(m => m.Value).ToList();
|
||||||
|
T.Check(hits.Count == 0, "the save names Blax Defaults outside the meta block: " + string.Join(", ", hits.Distinct()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,563 @@
|
||||||
|
using System.Collections.Generic;
|
||||||
|
using System.Linq;
|
||||||
|
using BlaxDefaults;
|
||||||
|
using HarmonyLib;
|
||||||
|
using RimWorld;
|
||||||
|
using UnityEngine;
|
||||||
|
using Verse;
|
||||||
|
|
||||||
|
namespace BlaxDefaultsTests
|
||||||
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Work package "tab". The tests of design.md: Defaults button in the storage tab.
|
||||||
|
/// Methods: [BlaxTest("<area>: <what>", phase: N)] public static void X(). Skip DLC-only checks with
|
||||||
|
/// Fixtures.NeedDlc(DlcSupport.Biotech) ("skipped: needs Biotech").
|
||||||
|
/// Drawing the button needs a GUI and is checked by hand; these tests drive the menu builder.
|
||||||
|
/// </summary>
|
||||||
|
public static class TabTests
|
||||||
|
{
|
||||||
|
private static readonly string[] TabKeys =
|
||||||
|
{
|
||||||
|
"BlaxDefaults_TabButton", "BlaxDefaults_TabMakeDefault", "BlaxDefaults_TabLoadDefault", "BlaxDefaults_TabLoadGameDefault",
|
||||||
|
"BlaxDefaults_TabForget", "BlaxDefaults_TabMakeDefaultType", "BlaxDefaults_TabForgetType", "BlaxDefaults_TabNoStockpileDefault",
|
||||||
|
"BlaxDefaults_TabMakeDefaultTip", "BlaxDefaults_TabLoadDefaultTip", "BlaxDefaults_TabLoadGameDefaultTip", "BlaxDefaults_TabForgetTip",
|
||||||
|
"BlaxDefaults_TabNoDefault", "BlaxDefaults_TabMadeDefault", "BlaxDefaults_TabForgotten", "BlaxDefaults_TabForgetConfirm",
|
||||||
|
"BlaxDefaults_TabWriteFailed", "BlaxDefaults_TabTipYours", "BlaxDefaults_TabTipGame", "BlaxDefaults_TabTipStorageOff",
|
||||||
|
"BlaxDefaults_TabTipStockpilesSome", "BlaxDefaults_TabTipStockpilesRest", "BlaxDefaults_TabTipStockpilesNone", "BlaxDefaults_TabTipStockpilesOff",
|
||||||
|
};
|
||||||
|
|
||||||
|
// ---- tests -----------------------------------------------------------------------
|
||||||
|
|
||||||
|
[BlaxTest("tab: every string of the Defaults button is in Keyed")]
|
||||||
|
public static void Strings()
|
||||||
|
{
|
||||||
|
var missing = TabKeys.Where(k => !k.CanTranslate()).ToList();
|
||||||
|
T.Check(missing.Count == 0, "strings missing from Keyed: " + string.Join(", ", missing));
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("tab: the tab's selected parent and priority row resolve through the delegates")]
|
||||||
|
public static void Delegates()
|
||||||
|
{
|
||||||
|
T.NotNull(StorageTabButton.SelStoreSettingsParent, "SelStoreSettingsParent delegate");
|
||||||
|
T.NotNull(StorageTabButton.IsPrioritySettingVisible, "IsPrioritySettingVisible delegate");
|
||||||
|
T.Check(StorageTabButton.IsPrioritySettingVisible(new ITab_Storage()), "ITab_Storage hides the priority row");
|
||||||
|
T.Check(!StorageTabButton.IsPrioritySettingVisible(new ITab_Shells()), "ITab_Shells shows the priority row: the icon rect would be wrong");
|
||||||
|
|
||||||
|
Zone_Stockpile zone = MakeStockpile(StorageSettingsPreset.DefaultStockpile);
|
||||||
|
Building_Storage shelf = SpawnShelf(ShelfCell(Fixtures.EmptyArea(5, 3)));
|
||||||
|
var (a, b, group) = LinkedShelves();
|
||||||
|
var tab = new ITab_Storage();
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Find.Selector.ClearSelection();
|
||||||
|
Find.Selector.Select(shelf, playSound: false, forceDesignatorDeselect: false);
|
||||||
|
T.Check(StorageTabButton.SelStoreSettingsParent(tab) == shelf, "a selected shelf is not the tab's parent");
|
||||||
|
Find.Selector.ClearSelection();
|
||||||
|
Find.Selector.Select(zone, playSound: false, forceDesignatorDeselect: false);
|
||||||
|
T.Check(StorageTabButton.SelStoreSettingsParent(tab) == zone, "a selected stockpile is not the tab's parent");
|
||||||
|
Find.Selector.ClearSelection();
|
||||||
|
Find.Selector.Select(a, playSound: false, forceDesignatorDeselect: false);
|
||||||
|
Find.Selector.Select(b, playSound: false, forceDesignatorDeselect: false);
|
||||||
|
T.Check(StorageTabButton.SelStoreSettingsParent(tab) == group, "two selected linked shelves don't give their group");
|
||||||
|
T.Check(StorageDefaultsMenu.HasButton(group), "the group of two linked shelves gets no button");
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
Find.Selector.ClearSelection();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("tab: a stockpile and a dumping stockpile offer every type, and all four entries open the type submenu")]
|
||||||
|
public static void StockpileMenu()
|
||||||
|
{
|
||||||
|
ForgetStockpileTypes();
|
||||||
|
List<StockpileType> types = StorageKinds.StockpileTypes;
|
||||||
|
Zone_Stockpile pile = MakeStockpile(StorageSettingsPreset.DefaultStockpile);
|
||||||
|
Zone_Stockpile dump = MakeStockpile(StorageSettingsPreset.DumpingStockpile);
|
||||||
|
|
||||||
|
foreach (Zone_Stockpile zone in new[] { pile, dump })
|
||||||
|
{
|
||||||
|
string what = zone.label;
|
||||||
|
List<StorageKind> kinds = StorageDefaultsMenu.KindsFor(zone);
|
||||||
|
T.Equal(string.Join(",", types.Select(t => t.Key)), string.Join(",", kinds.Select(k => k.Key)), "kinds of " + what);
|
||||||
|
T.Check(StorageDefaultsMenu.HasButton(zone), what + " gets no button");
|
||||||
|
T.Check(ReferenceEquals(zone.settings, StorageDefaultsMenu.SettingsOf(zone)), what + ": SettingsOf is not the zone's settings");
|
||||||
|
|
||||||
|
List<FloatMenuOption> options = StorageDefaultsMenu.OptionsFor(zone);
|
||||||
|
T.Equal(4, options.Count, "options on " + what);
|
||||||
|
for (int i = 0; i < 4; i++)
|
||||||
|
T.Equal(StorageDefaultsMenu.StockpileEntryLabel(StorageDefaultsMenu.Entries[i]), options[i].Label, "label of entry " + i + " on " + what);
|
||||||
|
T.Equal("Make default for a stockpile type", options[0].Label, "Make default label on " + what);
|
||||||
|
T.Check(!options[0].Disabled, what + ": Make default is disabled");
|
||||||
|
T.Check(options[1].Disabled, what + ": Load your default is enabled with no default saved");
|
||||||
|
T.Check(!options[2].Disabled, what + ": Load the game's default is disabled");
|
||||||
|
T.Check(options[3].Disabled, what + ": Forget is enabled with no default saved");
|
||||||
|
}
|
||||||
|
|
||||||
|
Fixtures.Save(Fixtures.StockpileKind.Capture(pile.settings));
|
||||||
|
foreach (Zone_Stockpile zone in new[] { pile, dump })
|
||||||
|
{
|
||||||
|
string what = zone.label;
|
||||||
|
List<FloatMenuOption> options = StorageDefaultsMenu.OptionsFor(zone);
|
||||||
|
T.Check(options.All(o => !o.Disabled), what + ": an entry is disabled with the stockpile default saved");
|
||||||
|
foreach (StorageMenuEntry entry in StorageDefaultsMenu.Entries)
|
||||||
|
{
|
||||||
|
List<FloatMenuOption> sub = StorageDefaultsMenu.Submenu(zone, entry);
|
||||||
|
T.Equal(types.Count, sub.Count, entry + " submenu size on " + what);
|
||||||
|
for (int i = 0; i < types.Count; i++)
|
||||||
|
{
|
||||||
|
StorageKind kind = StorageKinds.ForStockpile(types[i]);
|
||||||
|
T.Equal(kind.Label.CapitalizeFirst(), sub[i].Label, entry + " submenu entry " + i + " on " + what);
|
||||||
|
T.Check(sub[i].tooltip.HasValue && sub[i].tooltip.Value.text.Contains(kind.LabelPlural),
|
||||||
|
entry + " > " + sub[i].Label + ": the tooltip doesn't name " + kind.LabelPlural);
|
||||||
|
}
|
||||||
|
T.Equal("Stockpile", sub[0].Label, entry + " submenu first entry");
|
||||||
|
T.Equal("Dumping stockpile", sub[1].Label, entry + " submenu second entry");
|
||||||
|
bool needsSaved = entry == StorageMenuEntry.LoadDefault || entry == StorageMenuEntry.Forget;
|
||||||
|
T.Check(!sub[0].Disabled, entry + " > Stockpile is disabled with its default saved");
|
||||||
|
T.Equal(needsSaved, sub[1].Disabled, entry + " > Dumping stockpile disabled without a dumping default");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("tab: a shelf, a shelf blueprint and two linked shelves offer the shelf, and the labels name it")]
|
||||||
|
public static void BuildingMenu()
|
||||||
|
{
|
||||||
|
StorageKind shelfKind = ShelfKind;
|
||||||
|
DefaultsLibrary.Forget(shelfKind.Key);
|
||||||
|
Building_Storage shelf = SpawnShelf(ShelfCell(Fixtures.EmptyArea(5, 3)));
|
||||||
|
Blueprint_Storage blueprint = PlaceShelfBlueprint();
|
||||||
|
var (a, b, group) = LinkedShelves();
|
||||||
|
var parents = new (string what, IStoreSettingsParent parent)[]
|
||||||
|
{
|
||||||
|
("shelf", shelf), ("shelf blueprint", blueprint), ("group of two linked shelves", group), ("one of two linked shelves", a),
|
||||||
|
};
|
||||||
|
|
||||||
|
foreach (var (what, parent) in parents)
|
||||||
|
{
|
||||||
|
List<StorageKind> kinds = StorageDefaultsMenu.KindsFor(parent);
|
||||||
|
T.Equal(1, kinds.Count, "kinds of the " + what);
|
||||||
|
T.Equal(shelfKind.Key, kinds[0].Key, "kind of the " + what);
|
||||||
|
List<FloatMenuOption> options = StorageDefaultsMenu.OptionsFor(parent);
|
||||||
|
T.Equal(4, options.Count, "options on the " + what);
|
||||||
|
T.Equal("Make default for new shelves", options[0].Label, "Make default label on the " + what);
|
||||||
|
T.Equal("Load your default", options[1].Label, "Load your default label on the " + what);
|
||||||
|
T.Equal("Load the game's default", options[2].Label, "Load the game's default label on the " + what);
|
||||||
|
T.Equal("Forget the default for new shelves", options[3].Label, "Forget label on the " + what);
|
||||||
|
T.Check(!options[0].Disabled && !options[2].Disabled, what + ": Make default or Load the game's default is disabled");
|
||||||
|
T.Check(options[1].Disabled && options[3].Disabled, what + ": Load your default or Forget is enabled with no default saved");
|
||||||
|
T.Equal("New shelves start from the game's default.", StorageDefaultsMenu.Tooltip(parent), "tooltip on the " + what + " without a default");
|
||||||
|
}
|
||||||
|
|
||||||
|
StorageSettings groupSettings = group.GetStoreSettings();
|
||||||
|
T.Check(ReferenceEquals(groupSettings, StorageDefaultsMenu.SettingsOf(group)), "SettingsOf(group) is not the group's settings");
|
||||||
|
T.Check(ReferenceEquals(groupSettings, StorageDefaultsMenu.SettingsOf(a)), "SettingsOf(a linked shelf) is not the group's settings");
|
||||||
|
T.Check(ReferenceEquals(blueprint.settings, StorageDefaultsMenu.SettingsOf(blueprint)), "SettingsOf(blueprint) is not the blueprint's settings");
|
||||||
|
|
||||||
|
Fixtures.Save(shelfKind.Capture(shelf.settings));
|
||||||
|
foreach (var (what, parent) in parents)
|
||||||
|
{
|
||||||
|
T.Check(StorageDefaultsMenu.OptionsFor(parent).All(o => !o.Disabled), what + ": an entry is disabled with the shelf default saved");
|
||||||
|
T.Equal("New shelves start from your default.", StorageDefaultsMenu.Tooltip(parent), "tooltip on the " + what + " with a default");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("tab: Make default stores the current settings, Load your default writes them back after a change")]
|
||||||
|
public static void MakeAndLoad()
|
||||||
|
{
|
||||||
|
StorageKind shelfKind = ShelfKind;
|
||||||
|
Building_Storage shelf = SpawnShelf(ShelfCell(Fixtures.EmptyArea(5, 3)));
|
||||||
|
CheckMakeAndLoad(shelfKind, shelf, "shelf");
|
||||||
|
|
||||||
|
DefaultsLibrary.Forget(DefaultsKeys.Dumping);
|
||||||
|
Zone_Stockpile zone = MakeStockpile(StorageSettingsPreset.DefaultStockpile);
|
||||||
|
CheckMakeAndLoad(Fixtures.StockpileKind, zone, "stockpile");
|
||||||
|
T.Check(!DefaultsLibrary.Has(DefaultsKeys.Dumping), "making the stockpile default saved a dumping default");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("tab: Load the game's default restores Preferred and the shelf categories on a shelf")]
|
||||||
|
public static void ShelfGameDefault()
|
||||||
|
{
|
||||||
|
StorageKind shelfKind = ShelfKind;
|
||||||
|
Building_Storage shelf = SpawnShelf(ShelfCell(Fixtures.EmptyArea(5, 3)));
|
||||||
|
StorageSettings s = StorageDefaultsMenu.SettingsOf(shelf);
|
||||||
|
s.Priority = StoragePriority.Low;
|
||||||
|
s.filter.SetDisallowAll();
|
||||||
|
s.filter.SetAllow(ThingDefOf.Steel, true);
|
||||||
|
s.filter.AllowedHitPointsPercents = new FloatRange(0.5f, 1f);
|
||||||
|
|
||||||
|
StorageDefaultsMenu.OptionsFor(shelf)[2].action();
|
||||||
|
|
||||||
|
StorageSettings def = ShelfDef.building.defaultStorageSettings;
|
||||||
|
T.NotNull(def, "the shelf's defaultStorageSettings");
|
||||||
|
T.Equal(StoragePriority.Preferred, s.Priority, "priority after Load the game's default");
|
||||||
|
T.Check(shelfKind.Capture(s).SameSettingsAs(shelfKind.Capture(def)), "the shelf's settings differ from its def default");
|
||||||
|
T.Equal(def.filter.AllowedDefCount, s.filter.AllowedDefCount, "allowed defs");
|
||||||
|
T.Check(s.filter.Allows(ThingDefOf.MealSimple) && s.filter.Allows(ThingDefOf.WoodLog) && s.filter.Allows(ThingDefOf.Steel),
|
||||||
|
"a shelf category item is refused after Load the game's default");
|
||||||
|
CheckFullRanges(s, "shelf");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("tab: Load the game's default > stockpile turns a narrowed stockpile into a new vanilla stockpile")]
|
||||||
|
public static void StockpileGameDefault()
|
||||||
|
{
|
||||||
|
Zone_Stockpile zone = MakeStockpile(StorageSettingsPreset.DefaultStockpile);
|
||||||
|
StorageSettings s = zone.settings;
|
||||||
|
Narrow(s);
|
||||||
|
T.Check(!s.filter.Allows(ThingDefOf.MealSimple), "the narrowed stockpile still allows MealSimple");
|
||||||
|
|
||||||
|
StorageDefaultsMenu.Submenu(zone, StorageMenuEntry.LoadGameDefault)[0].action();
|
||||||
|
|
||||||
|
StorageSettings fresh = new Zone_Stockpile(StorageSettingsPreset.DefaultStockpile, Fixtures.Map.zoneManager).settings;
|
||||||
|
CheckSameAs(fresh, s, "stockpile after Load the game's default > stockpile");
|
||||||
|
T.Equal(StoragePriority.Normal, s.Priority, "priority");
|
||||||
|
T.Check(s.filter.Allows(ThingDefOf.MealSimple) && s.filter.Allows(ThingDefOf.WoodLog) && s.filter.Allows(ThingDefOf.Steel),
|
||||||
|
"a DefaultStockpile category item is refused: Load the game's default kept the Steel-only narrowing");
|
||||||
|
CheckFullRanges(s, "stockpile");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("tab: Load the game's default > dumping gives Corpses and Chunks at Normal, plus Wastepack only with Biotech")]
|
||||||
|
public static void DumpingGameDefault()
|
||||||
|
{
|
||||||
|
Zone_Stockpile zone = MakeStockpile(StorageSettingsPreset.DefaultStockpile);
|
||||||
|
StorageSettings s = zone.settings;
|
||||||
|
Narrow(s);
|
||||||
|
|
||||||
|
StorageDefaultsMenu.Submenu(zone, StorageMenuEntry.LoadGameDefault)[1].action();
|
||||||
|
|
||||||
|
T.Equal(StoragePriority.Normal, s.Priority, "priority");
|
||||||
|
ThingDef wastepack = DefDatabase<ThingDef>.GetNamedSilentFail("Wastepack");
|
||||||
|
foreach (ThingDef def in s.filter.AllowedThingDefs)
|
||||||
|
{
|
||||||
|
bool ok = def.IsWithinCategory(ThingCategoryDefOf.Corpses) || def.IsWithinCategory(ThingCategoryDefOf.Chunks) || (def == wastepack && ModsConfig.BiotechActive);
|
||||||
|
T.Check(ok, def.defName + " is allowed, but is neither a corpse, a chunk nor (with Biotech) Wastepack");
|
||||||
|
}
|
||||||
|
T.Check(!s.filter.Allows(ThingDefOf.Steel), "Steel is still allowed");
|
||||||
|
T.Check(s.filter.Allows(ThingDefOf.ChunkSlagSteel), "slag chunks are refused");
|
||||||
|
T.Check(s.filter.Allows(ThingDefOf.Human.race.corpseDef), "human corpses are refused");
|
||||||
|
if (ModsConfig.BiotechActive)
|
||||||
|
{
|
||||||
|
T.Check(wastepack != null && s.filter.Allows(wastepack), "Wastepack is refused with Biotech");
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
T.Check(wastepack == null || !s.filter.Allows(wastepack), "Wastepack is allowed without Biotech");
|
||||||
|
T.Info("Biotech off: the dumping default has no Wastepack");
|
||||||
|
}
|
||||||
|
StorageSettings fresh = new Zone_Stockpile(StorageSettingsPreset.DumpingStockpile, Fixtures.Map.zoneManager).settings;
|
||||||
|
CheckSameAs(fresh, s, "stockpile after Load the game's default > dumping");
|
||||||
|
CheckFullRanges(s, "dumping");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("tab: Forget > dumping removes only the dumping default; the tooltip lists both types before and one after")]
|
||||||
|
public static void ForgetDumping()
|
||||||
|
{
|
||||||
|
ForgetStockpileTypes();
|
||||||
|
Zone_Stockpile zone = MakeStockpile(StorageSettingsPreset.DefaultStockpile);
|
||||||
|
StorageKind pile = Fixtures.StockpileKind, dump = Fixtures.DumpingKind;
|
||||||
|
T.Equal("New stockpiles of every type start from the game's default.", StorageDefaultsMenu.Tooltip(zone), "tooltip without defaults");
|
||||||
|
|
||||||
|
Fixtures.Save(Fixtures.Template(pile, StoragePriority.Important, ThingDefOf.MealSimple));
|
||||||
|
Fixtures.Save(Fixtures.Template(dump, StoragePriority.Normal, ThingDefOf.ChunkSlagSteel));
|
||||||
|
string before = StorageDefaultsMenu.Tooltip(zone);
|
||||||
|
T.Check(Lists(before, pile) && Lists(before, dump), "the tooltip doesn't list both types: " + before);
|
||||||
|
|
||||||
|
StorageDefaultsMenu.Forget(dump, confirm: false);
|
||||||
|
T.Check(DefaultsLibrary.Has(DefaultsKeys.Stockpile), "Forget > dumping removed the stockpile default");
|
||||||
|
T.Check(!DefaultsLibrary.Has(DefaultsKeys.Dumping), "Forget > dumping kept the dumping default");
|
||||||
|
string after = StorageDefaultsMenu.Tooltip(zone);
|
||||||
|
T.Check(Lists(after, pile) && !Lists(after, dump), "the tooltip after Forget > dumping: " + after);
|
||||||
|
T.Check(StorageDefaultsMenu.Submenu(zone, StorageMenuEntry.Forget)[1].Disabled, "Forget > Dumping stockpile is enabled after forgetting it");
|
||||||
|
T.Check(!StorageDefaultsMenu.Submenu(zone, StorageMenuEntry.Forget)[0].Disabled, "Forget > Stockpile is disabled with its default saved");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("tab: a Zone subclass with ISlotGroupParent, a grave and no parent get no button")]
|
||||||
|
public static void NoButton()
|
||||||
|
{
|
||||||
|
TestSlotZone zone = TestSlotZone.Make();
|
||||||
|
T.NotNull(StorageDefaultsMenu.SettingsOf(zone), "the test zone's settings");
|
||||||
|
T.Equal(0, StorageDefaultsMenu.KindsFor(zone).Count, "kinds of a Zone subclass with ISlotGroupParent");
|
||||||
|
T.Equal(0, StorageDefaultsMenu.OptionsFor(zone).Count, "options of a Zone subclass with ISlotGroupParent");
|
||||||
|
T.Check(!StorageDefaultsMenu.HasButton(zone), "a Zone subclass with ISlotGroupParent gets a button");
|
||||||
|
T.Equal(null, StorageDefaultsMenu.Tooltip(zone), "tooltip of a Zone subclass with ISlotGroupParent");
|
||||||
|
|
||||||
|
ThingDef graveDef = Fixtures.Thing("Grave");
|
||||||
|
Thing grave = ThingMaker.MakeThing(graveDef, graveDef.MadeFromStuff ? GenStuff.DefaultStuffFor(graveDef) : null);
|
||||||
|
T.Check(grave is IStoreSettingsParent, "a grave is no IStoreSettingsParent");
|
||||||
|
T.Equal(0, StorageDefaultsMenu.OptionsFor((IStoreSettingsParent)grave).Count, "options of a grave (no storage blueprint in 1.0)");
|
||||||
|
|
||||||
|
T.Equal(0, StorageDefaultsMenu.OptionsFor(null).Count, "options of no parent");
|
||||||
|
T.Check(!StorageDefaultsMenu.HasButton(null), "no parent gets a button");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("tab: linked shelves: Load your default and Load the game's default write the group's settings")]
|
||||||
|
public static void LinkedLoad()
|
||||||
|
{
|
||||||
|
StorageKind shelfKind = ShelfKind;
|
||||||
|
var (a, b, group) = LinkedShelves();
|
||||||
|
StorageTemplate saved = Fixtures.Save(Fixtures.Template(shelfKind, StoragePriority.Important, ThingDefOf.Steel));
|
||||||
|
StorageSettings gs = group.GetStoreSettings();
|
||||||
|
T.Equal(StoragePriority.Preferred, gs.Priority, "the group's priority before loading");
|
||||||
|
|
||||||
|
// Load your default from one linked shelf's tab.
|
||||||
|
StorageDefaultsMenu.OptionsFor(a)[1].action();
|
||||||
|
T.Check(shelfKind.Capture(gs).SameSettingsAs(saved), "the group's settings differ from the default after Load your default");
|
||||||
|
T.Equal(StoragePriority.Important, gs.Priority, "the group's priority after Load your default");
|
||||||
|
T.Check(ReferenceEquals(a.GetStoreSettings(), gs) && ReferenceEquals(b.GetStoreSettings(), gs), "a shelf left the group");
|
||||||
|
T.Check(b.GetStoreSettings().filter.Allows(ThingDefOf.Steel) && !b.GetStoreSettings().filter.Allows(ThingDefOf.WoodLog),
|
||||||
|
"the other linked shelf doesn't take Steel only");
|
||||||
|
|
||||||
|
// Load the game's default from the group (both shelves selected).
|
||||||
|
StorageDefaultsMenu.OptionsFor(group)[2].action();
|
||||||
|
T.Equal(StoragePriority.Preferred, gs.Priority, "the group's priority after Load the game's default");
|
||||||
|
T.Check(shelfKind.Capture(gs).SameSettingsAs(shelfKind.Capture(ShelfDef.building.defaultStorageSettings)),
|
||||||
|
"the group's settings differ from the shelf's def default after Load the game's default");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("tab: the button and the icon stay clear of the tab's close X and the priority button")]
|
||||||
|
public static void ClearOfCloseX()
|
||||||
|
{
|
||||||
|
foreach (ITab_Storage tab in new ITab_Storage[] { new ITab_Storage(), new ITab_Shells() })
|
||||||
|
{
|
||||||
|
string which = tab.GetType().Name;
|
||||||
|
float width = Traverse.Create(tab).Field("size").GetValue<Vector2>().x;
|
||||||
|
T.Check(width > 0f, which + ": no tab width");
|
||||||
|
// Widgets.CloseButtonFor(rect.AtZero()), drawn by InspectTabBase.DoTabGUI before FillTab.
|
||||||
|
Rect closeX = StorageTabButton.CloseXRect(width);
|
||||||
|
T.Info(which + ": width " + width + ", close X at x " + closeX.xMin + " to " + closeX.xMax + ", y " + closeX.yMin + " to " + closeX.yMax);
|
||||||
|
// The priority button: (0, 0, 160, 29) inside the tab contracted by 10.
|
||||||
|
var priority = new Rect(10f, 10f, 160f, 29f);
|
||||||
|
foreach (var (what, rect) in new[] { ("button", StorageTabButton.ButtonRect), ("icon", StorageTabButton.IconRect) })
|
||||||
|
{
|
||||||
|
T.Check(!Overlap(rect, closeX), which + ": the " + what + " (x " + rect.xMin + " to " + rect.xMax + ") covers the close X");
|
||||||
|
T.Check(!Overlap(rect, priority), which + ": the " + what + " covers the priority button");
|
||||||
|
T.Check(rect.xMax <= width - 10f, which + ": the " + what + " reaches past the tab's 10 px margin");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("tab: Make default keeps the names from inactive mods of the previous default, in their lists")]
|
||||||
|
public static void MakeDefaultKeepsUnresolved()
|
||||||
|
{
|
||||||
|
StorageKind shelfKind = ShelfKind;
|
||||||
|
StorageTemplate old = Fixtures.Template(shelfKind, StoragePriority.Important, ThingDefOf.Steel);
|
||||||
|
old.allowed.Add("BlaxTest_Missing");
|
||||||
|
old.refused.Add("BlaxTest_MissingRefused");
|
||||||
|
old.refusedSpecial.Add("BlaxTest_MissingFilter");
|
||||||
|
Fixtures.Save(old);
|
||||||
|
|
||||||
|
Building_Storage shelf = SpawnShelf(ShelfCell(Fixtures.EmptyArea(5, 3)));
|
||||||
|
StorageSettings s = StorageDefaultsMenu.SettingsOf(shelf);
|
||||||
|
s.Priority = StoragePriority.Low;
|
||||||
|
s.filter.SetDisallowAll();
|
||||||
|
s.filter.SetAllow(ThingDefOf.WoodLog, true);
|
||||||
|
|
||||||
|
// "Make default for new shelves" from the menu, twice: the names stay once.
|
||||||
|
for (int click = 1; click <= 2; click++)
|
||||||
|
{
|
||||||
|
StorageDefaultsMenu.OptionsFor(shelf)[0].action();
|
||||||
|
StorageTemplate saved = DefaultsLibrary.Get<StorageTemplate>(shelfKind.Key);
|
||||||
|
T.NotNull(saved, "click " + click + ": the saved default");
|
||||||
|
T.Equal(1, saved.allowed.Count(n => n == "BlaxTest_Missing"), "click " + click + ": BlaxTest_Missing in the allowed list");
|
||||||
|
T.Equal(1, saved.refused.Count(n => n == "BlaxTest_MissingRefused"), "click " + click + ": BlaxTest_MissingRefused in the refused list");
|
||||||
|
T.Equal(1, saved.refusedSpecial.Count(n => n == "BlaxTest_MissingFilter"), "click " + click + ": BlaxTest_MissingFilter in the refused special filters");
|
||||||
|
T.Check(!saved.refused.Contains("BlaxTest_Missing") && !saved.allowed.Contains("BlaxTest_MissingRefused"), "click " + click + ": an unresolved name moved to the other list");
|
||||||
|
T.Equal(3, saved.UnresolvedNames().Count(), "click " + click + ": unresolved names");
|
||||||
|
T.Equal(StoragePriority.Low, saved.Priority, "click " + click + ": priority");
|
||||||
|
T.Equal(UnlistedRule.Game, saved.unlisted, "click " + click + ": unlisted rule");
|
||||||
|
T.Check(saved.allowed.Contains("WoodLog") && saved.refused.Contains("Steel"), "click " + click + ": the shelf's own settings were not saved");
|
||||||
|
}
|
||||||
|
T.Check(DefaultsLibrary.LastWriteOk, "the defaults file write failed");
|
||||||
|
}
|
||||||
|
|
||||||
|
[BlaxTest("tab: plural labels: shelf gives shelves, a note in parentheses stays at the end")]
|
||||||
|
public static void Plurals()
|
||||||
|
{
|
||||||
|
if (!(Find.ActiveLanguageWorker is LanguageWorker_English))
|
||||||
|
T.Skip("needs English as the game's language");
|
||||||
|
T.Equal("shelves", StorageKinds.PluralOf("shelf"), "plural of shelf");
|
||||||
|
T.Equal("Large shelves", StorageKinds.PluralOf("Large shelf"), "plural of Large shelf");
|
||||||
|
T.Equal("Weapon Racks (1 slot)", StorageKinds.PluralOf("Weapon Rack (1 slot)"), "plural of Weapon Rack (1 slot)");
|
||||||
|
T.Equal("bookcases", StorageKinds.PluralOf("bookcase"), "plural of bookcase");
|
||||||
|
T.Equal("hoppers", StorageKinds.PluralOf("hopper"), "plural of hopper");
|
||||||
|
T.Equal("storage 2", StorageKinds.PluralOf("storage 2"), "plural of a label ending in a digit");
|
||||||
|
T.Equal("shelves", ShelfKind.LabelPlural, "LabelPlural of Shelf");
|
||||||
|
T.Equal("bookcases", Fixtures.Kind("Bookcase").LabelPlural, "LabelPlural of Bookcase");
|
||||||
|
|
||||||
|
foreach (ThingDef def in StorageKinds.CoveredDefs())
|
||||||
|
{
|
||||||
|
string plural = StorageKinds.ForDef(def).LabelPlural;
|
||||||
|
T.Check(!plural.EndsWith(")s") && !plural.EndsWith("shelfs"), def.defName + ": plural " + plural);
|
||||||
|
if (def.defName.StartsWith("WeaponRacks_") || def.defName.StartsWith("RimFridge_"))
|
||||||
|
T.Info(def.defName + ": " + plural);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- helpers ---------------------------------------------------------------------
|
||||||
|
|
||||||
|
private static bool Overlap(Rect a, Rect b) => a.xMin < b.xMax && a.xMax > b.xMin && a.yMin < b.yMax && a.yMax > b.yMin;
|
||||||
|
|
||||||
|
private static ThingDef ShelfDef => Fixtures.Thing("Shelf");
|
||||||
|
|
||||||
|
private static StorageKind ShelfKind => Fixtures.Kind("Shelf");
|
||||||
|
|
||||||
|
private static void ForgetStockpileTypes()
|
||||||
|
{
|
||||||
|
foreach (StockpileType t in StorageKinds.StockpileTypes)
|
||||||
|
DefaultsLibrary.Forget(t.Key);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>A registered stockpile over an empty 3x3 area, made as vanilla's designator does (constructor, register, cells).</summary>
|
||||||
|
private static Zone_Stockpile MakeStockpile(StorageSettingsPreset preset)
|
||||||
|
{
|
||||||
|
CellRect area = Fixtures.EmptyArea(3, 3);
|
||||||
|
Map map = Fixtures.Map;
|
||||||
|
var zone = new Zone_Stockpile(preset, map.zoneManager);
|
||||||
|
map.zoneManager.RegisterZone(zone);
|
||||||
|
Fixtures.TrackZone(zone);
|
||||||
|
foreach (IntVec3 c in area.Cells)
|
||||||
|
zone.AddCell(c);
|
||||||
|
return zone;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The middle of a 5x3 (or larger) area: a 2x1 shelf fits in any rotation.</summary>
|
||||||
|
private static IntVec3 ShelfCell(CellRect area) => new IntVec3(area.minX + 2, 0, area.minZ + 1);
|
||||||
|
|
||||||
|
private static Building_Storage SpawnShelf(IntVec3 cell)
|
||||||
|
{
|
||||||
|
Thing t = ThingMaker.MakeThing(ShelfDef, ThingDefOf.WoodLog);
|
||||||
|
t.SetFaction(Faction.OfPlayer);
|
||||||
|
return (Building_Storage)Fixtures.Track(GenSpawn.Spawn(t, cell, Fixtures.Map, Rot4.North));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Blueprint_Storage PlaceShelfBlueprint()
|
||||||
|
{
|
||||||
|
IntVec3 cell = ShelfCell(Fixtures.EmptyArea(5, 3));
|
||||||
|
Blueprint_Build bp = GenConstruct.PlaceBlueprintForBuild(ShelfDef, cell, Fixtures.Map, Rot4.North, Faction.OfPlayer, ThingDefOf.WoodLog);
|
||||||
|
Fixtures.Track(bp);
|
||||||
|
T.Check(bp is Blueprint_Storage, "the shelf blueprint is a " + bp?.GetType().Name);
|
||||||
|
return (Blueprint_Storage)bp;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Two spawned shelves linked as vanilla's Link gizmo does: a new group from the first, then both join.</summary>
|
||||||
|
private static (Building_Storage a, Building_Storage b, StorageGroup group) LinkedShelves()
|
||||||
|
{
|
||||||
|
CellRect area = Fixtures.EmptyArea(5, 5);
|
||||||
|
Building_Storage a = SpawnShelf(new IntVec3(area.minX + 2, 0, area.minZ + 1));
|
||||||
|
Building_Storage b = SpawnShelf(new IntVec3(area.minX + 2, 0, area.minZ + 3));
|
||||||
|
StorageGroup group = Fixtures.Map.storageGroups.NewGroup();
|
||||||
|
group.InitFrom(a);
|
||||||
|
a.SetStorageGroup(group);
|
||||||
|
b.SetStorageGroup(group);
|
||||||
|
T.Check(a.storageGroup == group && b.storageGroup == group, "the shelves are not linked");
|
||||||
|
return (a, b, group);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Steel only, Important, hit points 50 to 100%, rotten refused, quality good or better.</summary>
|
||||||
|
private static void Narrow(StorageSettings s)
|
||||||
|
{
|
||||||
|
s.Priority = StoragePriority.Important;
|
||||||
|
s.filter.SetDisallowAll();
|
||||||
|
s.filter.SetAllow(ThingDefOf.Steel, true);
|
||||||
|
s.filter.AllowedHitPointsPercents = new FloatRange(0.5f, 1f);
|
||||||
|
s.filter.AllowedQualityLevels = new QualityRange(QualityCategory.Good, QualityCategory.Legendary);
|
||||||
|
SpecialThingFilterDef rotten = DefDatabase<SpecialThingFilterDef>.GetNamedSilentFail("AllowRotten");
|
||||||
|
if (rotten != null)
|
||||||
|
s.filter.SetAllow(rotten, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void CheckMakeAndLoad(StorageKind kind, IStoreSettingsParent parent, string what)
|
||||||
|
{
|
||||||
|
StorageSettings s = StorageDefaultsMenu.SettingsOf(parent);
|
||||||
|
s.Priority = StoragePriority.Important;
|
||||||
|
s.filter.SetDisallowAll();
|
||||||
|
s.filter.SetAllow(ThingDefOf.Steel, true);
|
||||||
|
s.filter.SetAllow(ThingDefOf.Silver, true);
|
||||||
|
s.filter.AllowedHitPointsPercents = new FloatRange(0.25f, 1f);
|
||||||
|
|
||||||
|
StorageDefaultsMenu.MakeDefault(kind, s);
|
||||||
|
StorageTemplate saved = DefaultsLibrary.Get<StorageTemplate>(kind.Key);
|
||||||
|
T.NotNull(saved, what + ": the saved default");
|
||||||
|
T.Check(saved.SameSettingsAs(kind.Capture(s)), what + ": the saved default differs from the current settings");
|
||||||
|
T.Equal(UnlistedRule.Game, saved.unlisted, what + ": unlisted rule of the saved default");
|
||||||
|
|
||||||
|
s.Priority = StoragePriority.Low;
|
||||||
|
s.filter.SetAllowAll(kind.ParentFilter);
|
||||||
|
s.filter.AllowedHitPointsPercents = FloatRange.ZeroToOne;
|
||||||
|
T.Check(!kind.Capture(s).SameSettingsAs(saved), what + ": the change left the settings equal to the default");
|
||||||
|
|
||||||
|
StorageDefaultsMenu.LoadDefault(kind, s);
|
||||||
|
T.Check(kind.Capture(s).SameSettingsAs(saved), what + ": the settings differ from the default after Load your default");
|
||||||
|
T.Equal(StoragePriority.Important, s.Priority, what + ": priority after Load your default");
|
||||||
|
T.Check(s.filter.Allows(ThingDefOf.Steel) && s.filter.Allows(ThingDefOf.Silver) && !s.filter.Allows(ThingDefOf.WoodLog),
|
||||||
|
what + ": not Steel and Silver only after Load your default");
|
||||||
|
T.Check(Mathf.Approximately(0.25f, s.filter.AllowedHitPointsPercents.min), what + ": hit points range after Load your default");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>Priority, allowed defs, every special filter and both ranges equal.</summary>
|
||||||
|
private static void CheckSameAs(StorageSettings expected, StorageSettings actual, string what)
|
||||||
|
{
|
||||||
|
T.Equal(expected.Priority, actual.Priority, what + ": priority");
|
||||||
|
var e = new HashSet<ThingDef>(expected.filter.AllowedThingDefs);
|
||||||
|
var a = new HashSet<ThingDef>(actual.filter.AllowedThingDefs);
|
||||||
|
var extra = a.Except(e).Select(d => d.defName).Take(5).ToList();
|
||||||
|
var missing = e.Except(a).Select(d => d.defName).Take(5).ToList();
|
||||||
|
T.Check(extra.Count == 0 && missing.Count == 0, what + ": allowed defs differ, extra " + string.Join(",", extra) + ", missing " + string.Join(",", missing));
|
||||||
|
foreach (SpecialThingFilterDef sf in DefDatabase<SpecialThingFilterDef>.AllDefsListForReading)
|
||||||
|
T.Equal(expected.filter.Allows(sf), actual.filter.Allows(sf), what + ": special filter " + sf.defName);
|
||||||
|
FloatRange eh = expected.filter.AllowedHitPointsPercents, ah = actual.filter.AllowedHitPointsPercents;
|
||||||
|
T.Check(Mathf.Approximately(eh.min, ah.min) && Mathf.Approximately(eh.max, ah.max), what + ": hit points " + ah + ", expected " + eh);
|
||||||
|
T.Equal(expected.filter.AllowedQualityLevels.min, actual.filter.AllowedQualityLevels.min, what + ": lowest quality");
|
||||||
|
T.Equal(expected.filter.AllowedQualityLevels.max, actual.filter.AllowedQualityLevels.max, what + ": highest quality");
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void CheckFullRanges(StorageSettings s, string what)
|
||||||
|
{
|
||||||
|
FloatRange hp = s.filter.AllowedHitPointsPercents;
|
||||||
|
T.Check(Mathf.Approximately(0f, hp.min) && Mathf.Approximately(1f, hp.max), what + ": hit points range is " + hp);
|
||||||
|
T.Equal(QualityCategory.Awful, s.filter.AllowedQualityLevels.min, what + ": lowest quality");
|
||||||
|
T.Equal(QualityCategory.Legendary, s.filter.AllowedQualityLevels.max, what + ": highest quality");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>The stockpile tooltip has a line "- Dumping stockpile" for this type.</summary>
|
||||||
|
private static bool Lists(string tooltip, StorageKind kind) =>
|
||||||
|
tooltip != null && tooltip.Split('\n').Any(l => l.Trim() == "- " + kind.Label.CapitalizeFirst());
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A Zone with ISlotGroupParent that is no Zone_Stockpile, like Preset Filtered Zones' Zone_PresetStockpile.
|
||||||
|
/// Never registered, so it never enters the save.
|
||||||
|
/// </summary>
|
||||||
|
public class TestSlotZone : Zone, ISlotGroupParent
|
||||||
|
{
|
||||||
|
public StorageSettings settings;
|
||||||
|
public SlotGroup slotGroup;
|
||||||
|
|
||||||
|
public static TestSlotZone Make()
|
||||||
|
{
|
||||||
|
var z = new TestSlotZone();
|
||||||
|
z.settings = new StorageSettings(z);
|
||||||
|
z.slotGroup = new SlotGroup(z);
|
||||||
|
return z;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected override Color NextZoneColor => Color.white;
|
||||||
|
|
||||||
|
public bool StorageTabVisible => true;
|
||||||
|
public bool IgnoreStoredThingsBeauty => false;
|
||||||
|
public string GroupingLabel => "test zones";
|
||||||
|
public int GroupingOrder => 0;
|
||||||
|
public bool HaulDestinationEnabled => true;
|
||||||
|
|
||||||
|
public StorageSettings GetStoreSettings() => settings;
|
||||||
|
public StorageSettings GetParentStoreSettings() => StorageSettings.EverStorableFixedSettings();
|
||||||
|
public void Notify_SettingsChanged() { }
|
||||||
|
public bool Accepts(Thing t) => settings.AllowedToAccept(t);
|
||||||
|
public IEnumerable<IntVec3> AllSlotCells() => Cells;
|
||||||
|
public List<IntVec3> AllSlotCellsList() => Cells;
|
||||||
|
public void Notify_ReceivedThing(Thing newItem) { }
|
||||||
|
public void Notify_LostThing(Thing newItem) { }
|
||||||
|
public string SlotYielderLabel() => label;
|
||||||
|
public SlotGroup GetSlotGroup() => slotGroup;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,205 @@
|
||||||
|
<#
|
||||||
|
Runs the in-game test suite. RimWorld 1.7 starts headless (no window, no focus change) with its
|
||||||
|
own save data folder, so your mod list, saves, settings and defaults file stay untouched. Needs Steam
|
||||||
|
running and the Harmony mod from the Workshop. Exit code: 0 all passed, 1 failures, 2 the run didn't finish.
|
||||||
|
|
||||||
|
.\Tests\run-tests.ps1 Harmony, the installed DLCs, Blax Defaults
|
||||||
|
.\Tests\run-tests.ps1 -Compat also the installed mods Defaults is tested next to: RimFridge, Weapon Racks,
|
||||||
|
Replace Stuff, Rimefeller, VFE Security, Vanilla Expanded Framework, Dubs Central
|
||||||
|
Heating, [DG]More Door Variants, Pick Up And Haul, Haul to Stack, Prison Labor,
|
||||||
|
Hospitality and Blax Castes
|
||||||
|
.\Tests\run-tests.ps1 -NoDlc core only, no DLC (DLC tests skip with "needs <DLC>")
|
||||||
|
.\Tests\run-tests.ps1 -Dlc Royalty,Biotech only these installed DLCs
|
||||||
|
.\Tests\run-tests.ps1 -NoBuild skip dotnet build
|
||||||
|
.\Tests\run-tests.ps1 -AllowWhileRunning run next to an open RimWorld (the test game runs at below-normal priority)
|
||||||
|
.\Tests\run-tests.ps1 -WaitForLock 1800 wait up to 1800 s for another run of this suite instead of failing
|
||||||
|
|
||||||
|
A release runs all 8 combinations of Royalty, Ideology and Biotech: -NoDlc, -Dlc with each alone, each pair, and all three.
|
||||||
|
Mods\BlaxDefaults must be a directory junction to this repo; it is created if missing and left in place.
|
||||||
|
While the suite runs, the test mod is linked into the game's Mods folder; that link is removed afterwards.
|
||||||
|
Only one run at a time: a lock file in the data folder holds the running script's process id. The build runs inside
|
||||||
|
the lock, so parallel callers with -WaitForLock build and run one after another.
|
||||||
|
Every run starts from default mod settings and an empty defaults library: the Blax Defaults settings file and
|
||||||
|
Config\BlaxDefaults in the data folder are deleted.
|
||||||
|
#>
|
||||||
|
param(
|
||||||
|
[string]$RimWorldDir = 'E:\SteamLibrary\steamapps\common\RimWorld',
|
||||||
|
[string]$DataDir = (Join-Path $env:TEMP 'BlaxDefaultsTest'),
|
||||||
|
[switch]$Compat,
|
||||||
|
[switch]$NoDlc,
|
||||||
|
[string[]]$Dlc,
|
||||||
|
[switch]$NoBuild,
|
||||||
|
[switch]$AllowWhileRunning,
|
||||||
|
[int]$WaitForLock = 0,
|
||||||
|
[int]$TimeoutSeconds = 900
|
||||||
|
)
|
||||||
|
$ErrorActionPreference = 'Stop'
|
||||||
|
# A wrong path (for example a switch passed as a positional value) would put the Mods junction somewhere odd.
|
||||||
|
if (-not (Test-Path -LiteralPath (Join-Path $RimWorldDir 'Assembly-CSharp.dll'))) { throw "No RimWorld 1.7 install at '$RimWorldDir'." }
|
||||||
|
$repo = Split-Path -Parent $PSScriptRoot
|
||||||
|
$testMod = Join-Path $PSScriptRoot 'BlaxDefaultsTests'
|
||||||
|
$modLink = Join-Path $RimWorldDir 'Mods\BlaxDefaults'
|
||||||
|
$link = Join-Path $RimWorldDir 'Mods\BlaxDefaultsTests'
|
||||||
|
$workshop = Join-Path $RimWorldDir '..\..\workshop\content\294100'
|
||||||
|
$lockFile = Join-Path $DataDir 'run.lock'
|
||||||
|
|
||||||
|
if ((Get-Process -Name RimWorld -ErrorAction SilentlyContinue) -and -not $AllowWhileRunning) {
|
||||||
|
throw 'RimWorld is running. Close it first, or pass -AllowWhileRunning.'
|
||||||
|
}
|
||||||
|
|
||||||
|
function Get-FullPath([string]$path) { [IO.Path]::GetFullPath($path).TrimEnd('\') }
|
||||||
|
|
||||||
|
# One run at a time. A lock whose process is gone is stale and taken over.
|
||||||
|
New-Item -ItemType Directory -Force $DataDir | Out-Null
|
||||||
|
function Enter-Lock {
|
||||||
|
$waited = [Diagnostics.Stopwatch]::StartNew()
|
||||||
|
for ($try = 0; $try -lt 2; $try++) {
|
||||||
|
try {
|
||||||
|
$stream = [IO.File]::Open($lockFile, [IO.FileMode]::CreateNew, [IO.FileAccess]::Write, [IO.FileShare]::Read)
|
||||||
|
$bytes = [Text.Encoding]::ASCII.GetBytes([string]$PID)
|
||||||
|
$stream.Write($bytes, 0, $bytes.Length)
|
||||||
|
$stream.Close()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
catch [IO.IOException] {
|
||||||
|
$owner = (Get-Content -LiteralPath $lockFile -Raw -ErrorAction SilentlyContinue)
|
||||||
|
$ownerPid = 0
|
||||||
|
if ($owner -and [int]::TryParse($owner.Trim(), [ref]$ownerPid) -and $ownerPid -ne $PID -and (Get-Process -Id $ownerPid -ErrorAction SilentlyContinue)) {
|
||||||
|
if ($waited.Elapsed.TotalSeconds -lt $WaitForLock) {
|
||||||
|
Start-Sleep -Seconds 5
|
||||||
|
$try = -1
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
throw "Another test run (process $ownerPid) is in progress. Lock: $lockFile"
|
||||||
|
}
|
||||||
|
Write-Warning "removing stale lock from process $owner"
|
||||||
|
Remove-Item -LiteralPath $lockFile -Force -ErrorAction SilentlyContinue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw "Could not take the lock $lockFile"
|
||||||
|
}
|
||||||
|
Enter-Lock
|
||||||
|
|
||||||
|
try {
|
||||||
|
# Mods\BlaxDefaults: a junction to this repo. Created if missing, never replaced.
|
||||||
|
if (Test-Path -LiteralPath $modLink) {
|
||||||
|
$item = Get-Item -LiteralPath $modLink -Force
|
||||||
|
if (-not ($item.Attributes -band [IO.FileAttributes]::ReparsePoint)) {
|
||||||
|
throw "$modLink is a real folder, not a junction to $repo. Move it away and run again."
|
||||||
|
}
|
||||||
|
$target = @($item.Target)[0]
|
||||||
|
if (-not $target -or (Get-FullPath $target) -ne (Get-FullPath $repo)) {
|
||||||
|
throw "$modLink points to '$target', not to $repo."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
New-Item -ItemType Junction -Path $modLink -Target $repo | Out-Null
|
||||||
|
Write-Host "Created junction $modLink -> $repo"
|
||||||
|
}
|
||||||
|
|
||||||
|
if (-not $NoBuild) {
|
||||||
|
foreach ($proj in (Join-Path $repo 'Source\BlaxDefaults\BlaxDefaults.csproj'), (Join-Path $testMod 'Source\BlaxDefaultsTests.csproj')) {
|
||||||
|
& dotnet build $proj -c Release -nologo -v q "-p:RimWorldDir=$RimWorldDir"
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw "build failed: $proj" }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# packageId (lower case) -> About.xml, for every installed local and Workshop mod
|
||||||
|
$installed = @{}
|
||||||
|
foreach ($about in @(Get-ChildItem (Join-Path $RimWorldDir 'Mods\*\About\About.xml') -ErrorAction SilentlyContinue) +
|
||||||
|
@(Get-ChildItem (Join-Path $workshop '*\About\About.xml') -ErrorAction SilentlyContinue)) {
|
||||||
|
$x = [xml](Get-Content -LiteralPath $about.FullName -Raw -Encoding UTF8)
|
||||||
|
if ($x.ModMetaData.packageId) { $installed[$x.ModMetaData.packageId.Trim().ToLower()] = $x }
|
||||||
|
}
|
||||||
|
function Add-WithDependencies([string]$id, [System.Collections.ArrayList]$list) {
|
||||||
|
$id = $id.ToLower()
|
||||||
|
if ($list -contains $id -or $id -like 'ludeon.*') { return }
|
||||||
|
$x = $installed[$id]
|
||||||
|
if (-not $x) { Write-Warning "not installed, skipped: $id"; return }
|
||||||
|
foreach ($dep in @($x.ModMetaData.modDependencies.li)) { if ($dep.packageId) { Add-WithDependencies $dep.packageId $list } }
|
||||||
|
[void]$list.Add($id)
|
||||||
|
}
|
||||||
|
|
||||||
|
# Load order: Harmony, core, DLCs, the mods Defaults is tested next to (Blax Castes among them), Blax Defaults, the tests.
|
||||||
|
# Every installed DLC is listed as known, so the game does not switch on a left-out DLC as "new".
|
||||||
|
$installedDlcs = @(@('Royalty', 'Ideology', 'Biotech', 'Anomaly', 'Odyssey') | Where-Object { Test-Path (Join-Path $RimWorldDir "Data\$_") })
|
||||||
|
if ($NoDlc) { $loadDlcs = @() }
|
||||||
|
elseif ($Dlc) {
|
||||||
|
$wanted = @($Dlc | ForEach-Object { $_ -split ',' } | ForEach-Object { $_.Trim() } | Where-Object { $_ })
|
||||||
|
foreach ($w in $wanted) { if ($installedDlcs -notcontains $w) { Write-Warning "DLC not installed or unknown, skipped: $w" } }
|
||||||
|
$loadDlcs = @($installedDlcs | Where-Object { $wanted -contains $_ })
|
||||||
|
}
|
||||||
|
else { $loadDlcs = @($installedDlcs) }
|
||||||
|
$mods = New-Object System.Collections.ArrayList
|
||||||
|
$expansions = @($installedDlcs | ForEach-Object { 'ludeon.rimworld.' + $_.ToLower() })
|
||||||
|
[void]$mods.Add('brrainz.harmony')
|
||||||
|
[void]$mods.Add('ludeon.rimworld')
|
||||||
|
foreach ($d in $loadDlcs) { [void]$mods.Add('ludeon.rimworld.' + $d.ToLower()) }
|
||||||
|
Write-Host ("DLCs: " + $(if ($loadDlcs.Count) { $loadDlcs -join ', ' } else { 'none' }))
|
||||||
|
if ($Compat) {
|
||||||
|
# Package ids read from the installed copies' About/About.xml (2026-11-29). Blax Zones joins once it has code.
|
||||||
|
foreach ($id in 'OskarPotocki.VanillaFactionsExpanded.Core', 'rimfridge.kv.rw', 'Aelanna.WeaponRacks', 'Memegoddess.ReplaceStuff',
|
||||||
|
'Dubwise.Rimefeller', 'VanillaExpanded.VFESecurity', 'Dubwise.DubsCentralHeating', 'local.moredoorvariants',
|
||||||
|
'Mehni.PickUpAndHaul', 'jkluch.HaulToStack', 'avius.prisonlabor', 'Orion.Hospitality', 'blax.castes') {
|
||||||
|
Add-WithDependencies $id $mods
|
||||||
|
}
|
||||||
|
}
|
||||||
|
[void]$mods.Add('blax.defaults')
|
||||||
|
[void]$mods.Add('blax.defaults.tests')
|
||||||
|
|
||||||
|
# fresh test data folder: mod list only, no old save, results, mod settings (files are named Mod_<folder>_<class>.xml)
|
||||||
|
# or defaults file (Config\BlaxDefaults, only ever this data folder's own)
|
||||||
|
New-Item -ItemType Directory -Force (Join-Path $DataDir 'Config') | Out-Null
|
||||||
|
Remove-Item -Force -ErrorAction SilentlyContinue (Join-Path $DataDir 'Saves\BlaxDefaultsTest.rws'), (Join-Path $DataDir 'BlaxDefaultsTestResults.txt')
|
||||||
|
Get-ChildItem -LiteralPath (Join-Path $DataDir 'Config') -Filter 'Mod_*.xml' -ErrorAction SilentlyContinue |
|
||||||
|
Where-Object { $_.Name -like 'Mod_BlaxDefaults_*' -or $_.Name -like 'Mod_blax.defaults_*' -or $_.Name -like 'Mod_BlaxCastes_*' } |
|
||||||
|
Remove-Item -Force -ErrorAction SilentlyContinue
|
||||||
|
# The defaults file and its .bak, .tmp and broken copies: files only, never recursive, never through a link.
|
||||||
|
$libraryDir = Join-Path $DataDir 'Config\BlaxDefaults'
|
||||||
|
if (Test-Path -LiteralPath $libraryDir) {
|
||||||
|
if ((Get-Item -LiteralPath $libraryDir -Force).Attributes -band [IO.FileAttributes]::ReparsePoint) {
|
||||||
|
throw "$libraryDir is a link. Remove it with cmd /c rmdir and run again."
|
||||||
|
}
|
||||||
|
Get-ChildItem -LiteralPath $libraryDir -File -Force | Remove-Item -Force
|
||||||
|
}
|
||||||
|
$li = { param($ids) ($ids | ForEach-Object { " <li>$_</li>" }) -join "`n" }
|
||||||
|
$modsConfig = "<?xml version=`"1.0`" encoding=`"utf-8`"?>`n<ModsConfigData>`n <version>1.7</version>`n <activeMods>`n" +
|
||||||
|
(& $li $mods) + "`n </activeMods>`n <knownExpansions>`n" + (& $li $expansions) + "`n </knownExpansions>`n</ModsConfigData>`n"
|
||||||
|
[IO.File]::WriteAllText((Join-Path $DataDir 'Config\ModsConfig.xml'), $modsConfig)
|
||||||
|
Write-Host ("Mods: " + ($mods -join ', '))
|
||||||
|
|
||||||
|
$createdLink = $false
|
||||||
|
try {
|
||||||
|
if (-not (Test-Path $link)) {
|
||||||
|
New-Item -ItemType Junction -Path $link -Target $testMod | Out-Null
|
||||||
|
$createdLink = $true
|
||||||
|
}
|
||||||
|
$gameArgs = "-headless -quicktest -blaxdefaultstests -NoFileLog -NoCrashDialog `"-savedatafolder=$DataDir`""
|
||||||
|
$sw = [Diagnostics.Stopwatch]::StartNew()
|
||||||
|
$p = Start-Process -FilePath (Join-Path $RimWorldDir 'RimWorld.exe') -WorkingDirectory $RimWorldDir -ArgumentList $gameArgs `
|
||||||
|
-RedirectStandardOutput (Join-Path $DataDir 'game.log') -RedirectStandardError (Join-Path $DataDir 'game.err.log') `
|
||||||
|
-WindowStyle Hidden -PassThru
|
||||||
|
if ($AllowWhileRunning) {
|
||||||
|
try { $p.PriorityClass = [Diagnostics.ProcessPriorityClass]::BelowNormal } catch { Write-Warning "could not lower the test game's priority: $_" }
|
||||||
|
}
|
||||||
|
if (-not $p.WaitForExit($TimeoutSeconds * 1000)) {
|
||||||
|
$p.Kill()
|
||||||
|
Write-Warning "timed out after $TimeoutSeconds s, test game (process $($p.Id)) killed"
|
||||||
|
}
|
||||||
|
Write-Host ("Game ran {0:N0} s. Log: {1}" -f $sw.Elapsed.TotalSeconds, (Join-Path $DataDir 'game.log'))
|
||||||
|
}
|
||||||
|
finally {
|
||||||
|
if ($createdLink -and (Test-Path $link)) { cmd /c rmdir "$link" | Out-Null }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
finally {
|
||||||
|
Remove-Item -LiteralPath $lockFile -Force -ErrorAction SilentlyContinue
|
||||||
|
}
|
||||||
|
|
||||||
|
$results = Join-Path $DataDir 'BlaxDefaultsTestResults.txt'
|
||||||
|
if (-not (Test-Path $results)) { Write-Host 'No results file: the suite never started. See game.log.'; exit 2 }
|
||||||
|
$lines = Get-Content -LiteralPath $results -Encoding UTF8
|
||||||
|
$lines | ForEach-Object { Write-Host $_ }
|
||||||
|
if (-not ($lines -match '^END$')) { Write-Host 'The run did not finish.'; exit 2 }
|
||||||
|
if ($lines -match '^FAIL ') { exit 1 }
|
||||||
|
exit 0
|
||||||
Loading…
Reference in New Issue