diff --git a/Source/Comps/CompRimMindDialogue.cs b/Source/Comps/CompRimMindDialogue.cs index 15c123f..8dbcd32 100644 --- a/Source/Comps/CompRimMindDialogue.cs +++ b/Source/Comps/CompRimMindDialogue.cs @@ -24,7 +24,7 @@ public override void CompTick() if (!settings.enabled || !settings.autoDialogueEnabled) return; // Sample natural encounters every 250 ticks (~4 seconds) if (!pawn.IsHashIntervalTick(250)) return; - if (!RimMindAPI.IsConfigured()) return; + if (!RimMindAPI.Settings.IsConfigured()) return; if (!IsEligible()) return; int currentTick = Find.TickManager.TicksGame; @@ -192,9 +192,7 @@ internal static bool TryDispatchTrigger( private Pawn? FindNearbyCompanion() { if (PawnOrNull is not Pawn pawn) return null; - Map? map = pawn.Map; - var spawnedColonists = map?.mapPawns?.FreeColonistsSpawned; - if (spawnedColonists == null) return null; + var spawnedColonists = RimMindPawnLookup.GetSpawnedColonistsSafe(pawn.Map); for (int i = 0; i < spawnedColonists.Count; i++) { @@ -216,9 +214,7 @@ public override IEnumerable CompGetGizmosExtra() yield return new Command_Action { - defaultLabel = "RimMind.Dialogue.UI.Gizmo.ChatWith".CanTranslate() - ? "RimMind.Dialogue.UI.Gizmo.ChatWith".Translate(parent.LabelShort).ToString() - : $"Chat with {parent.LabelShort}", + defaultLabel = RimMindAPI.Text.TrOr("RimMind.Dialogue.UI.Gizmo.ChatWith", "Chat with {0}", parent.LabelShort), icon = ContentFinder.Get("UI/RimMindDialogue_Icon", reportFailure: false), action = () => Find.WindowStack.Add(new Window_Dialogue(pawn)) }; diff --git a/Source/Core/DialogueContextProviderRegistrar.cs b/Source/Core/DialogueContextProviderRegistrar.cs index e46e470..cd1d4ae 100644 --- a/Source/Core/DialogueContextProviderRegistrar.cs +++ b/Source/Core/DialogueContextProviderRegistrar.cs @@ -86,7 +86,7 @@ internal static void RegisterAll() private static void RegisterScenarios() { - ScenarioRegistry.Register(new ScenarioDescriptor + RimMindAPI.Context.RegisterScenario(new ScenarioDescriptor { Id = ScenarioIds.Dialogue, DefaultBaseRounds = 10, @@ -124,7 +124,7 @@ private static void RegisterScenarios() } }); - ScenarioRegistry.Register(new ScenarioDescriptor + RimMindAPI.Context.RegisterScenario(new ScenarioDescriptor { Id = ScenarioIds.CrisisDialogue, DefaultBaseRounds = 8, @@ -178,7 +178,7 @@ private static void RegisterScenarios() var t = memories[i]; if (t?.def == null || t.def.defName != "RimMindDialogue_Thought") continue; - string desc = (t as Thought_RimMindDialogue)?.aiDescription ?? t.def.label; + string desc = (t as Thought_RimMindDialogue)?.aiDescription ?? t.def.label ?? t.def.defName; float hours = (float)t.DurationTicks / RimMindTime.TicksPerHour; sb.AppendLine(Tr("RimMind.Dialogue.Context.ThoughtRemaining", desc, $"{hours:F1}")); any = true; @@ -217,7 +217,7 @@ private static void RegisterScenarios() var directRel = pawn.relations?.DirectRelations?.FirstOrDefault(r => r != null && r.otherPawn == recipient); if (directRel?.def != null) - sb.AppendLine(Tr("RimMind.Dialogue.Context.DirectRelation", directRel.def.label)); + sb.AppendLine(Tr("RimMind.Dialogue.Context.DirectRelation", directRel.def.label ?? directRel.def.defName)); return sb.ToString().TrimEnd(); } diff --git a/Source/Core/DialogueOverlayLayout.cs b/Source/Core/DialogueOverlayLayout.cs index 676d3e8..b365dfc 100644 --- a/Source/Core/DialogueOverlayLayout.cs +++ b/Source/Core/DialogueOverlayLayout.cs @@ -78,6 +78,35 @@ public static int FindFirstVisibleIndex( return first; } + /// + /// Computes the shrink-wrapped render height for the overlay based on active visible line heights, + /// clamped between and . + /// + public static float ComputeRenderHeight( + IReadOnlyList lineHeights, + float maxHeight, + float minHeight, + float chromeHeight, + bool forceExpandToMax = false) + { + float safeMin = Math.Max(0f, minHeight); + float safeMax = Math.Max(safeMin, maxHeight); + if (forceExpandToMax) + return safeMax; + + if (lineHeights == null || lineHeights.Count == 0) + return safeMin; + + float contentSum = 0f; + for (int i = 0; i < lineHeights.Count; i++) + { + contentSum += Math.Max(0f, lineHeights[i]); + } + + float desired = contentSum + Math.Max(0f, chromeHeight); + return Clamp(desired, safeMin, safeMax); + } + /// /// Determines whether the dialogue overlay should be rendered on the HUD. /// When empty and not interacted with (hover/drag/resize), keeps the screen completely clean. diff --git a/Source/Core/DialogueRequestCoordinator.cs b/Source/Core/DialogueRequestCoordinator.cs index 1b98797..032e3e6 100644 --- a/Source/Core/DialogueRequestCoordinator.cs +++ b/Source/Core/DialogueRequestCoordinator.cs @@ -107,13 +107,13 @@ public void HandleTrigger( return "Dialogue participant is unavailable."; if (recipient != null && (!RimMind.Presentation.Api.RimMindPawnLookup.IsActiveSpawnedColonist(recipient) || recipient.Downed)) return "Dialogue recipient is unavailable."; - if (!RimMindAPI.IsConfigured()) + if (!RimMindAPI.Settings.IsConfigured()) return "AI is not configured."; if (!_activityState.IsReady(settings, currentTick)) return "Dialogue startup delay is active."; if (_reservations.IsPawnPending(pawn.thingIDNumber)) return "A dialogue request is already pending for this pawn."; - if (RimMindAPI.ShouldSkipDialogue(pawn, ToTriggerKind(type))) + if (RimMindAPI.Ext.ShouldSkipDialogue(pawn, ToTriggerKind(type))) return "AI dialogue condition is not met."; if (DialogueFlowPolicy.UsesMonologueCooldown( @@ -268,17 +268,18 @@ void ReportFailure(string error, bool showAutomaticError = true) var gameState = new GameStateInfo(); if (isCrisis) { - string mentalReason = pawn.MentalStateDef?.label ?? ("RimMind.Dialogue.Prompt.SevereCrisis".CanTranslate() - ? "RimMind.Dialogue.Prompt.SevereCrisis".Translate().ToString() - : "Severe Crisis"); - string crisisSection = "RimMind.Dialogue.Prompt.CrisisBreakdown".CanTranslate() - ? "RimMind.Dialogue.Prompt.CrisisBreakdown".Translate(mentalReason).ToString() - : $"[CRISIS BREAKDOWN: {mentalReason}] Speaker is currently suffering a mental break or severe distress. Do NOT engage in calm polite small talk. Output an intense, raw, emotional monologue or confrontation reflecting extreme distress, agony, panic, or rage."; + string mentalReason = pawn.MentalStateDef?.label ?? RimMindAPI.Text.TrOr( + "RimMind.Dialogue.Prompt.SevereCrisis", + "Severe Crisis"); + string crisisSection = RimMindAPI.Text.TrOr( + "RimMind.Dialogue.Prompt.CrisisBreakdown", + "[CRISIS BREAKDOWN: {0}] Speaker is currently suffering a mental break or severe distress. Do NOT engage in calm polite small talk. Output an intense, raw, emotional monologue or confrontation reflecting extreme distress, agony, panic, or rage.", + mentalReason); gameState.AddSection("crisis_expression", crisisSection); } - string autoTriggerInstruction = "RimMind.Dialogue.Prompt.AutoTrigger".CanTranslate() - ? "RimMind.Dialogue.Prompt.AutoTrigger".Translate().ToString() - : "Based on your current state and surroundings, respond naturally."; + string autoTriggerInstruction = RimMindAPI.Text.TrOr( + "RimMind.Dialogue.Prompt.AutoTrigger", + "Based on your current state and surroundings, respond naturally."); string triggerPayload = string.IsNullOrWhiteSpace(formattedContext) ? autoTriggerInstruction : $"{formattedContext}\n{autoTriggerInstruction}"; @@ -379,26 +380,26 @@ private static string FormatContext( { string formatted = type switch { - DialogueTriggerType.Chitchat => - "RimMind.Dialogue.Prompt.Context.Chitchat".CanTranslate() - ? "RimMind.Dialogue.Prompt.Context.Chitchat".Translate(context).ToString() - : $"[Chitchat: {context}]", - DialogueTriggerType.Hediff => - "RimMind.Dialogue.Prompt.Context.Hediff".CanTranslate() - ? "RimMind.Dialogue.Prompt.Context.Hediff".Translate(context).ToString() - : $"[Health condition: {context}]", - DialogueTriggerType.LevelUp => - "RimMind.Dialogue.Prompt.Context.LevelUp".CanTranslate() - ? "RimMind.Dialogue.Prompt.Context.LevelUp".Translate(context).ToString() - : $"[Skill level up: {context}]", - DialogueTriggerType.Thought => - "RimMind.Dialogue.Prompt.Context.Thought".CanTranslate() - ? "RimMind.Dialogue.Prompt.Context.Thought".Translate(context).ToString() - : $"[Recent thought: {context}]", - DialogueTriggerType.Auto => - "RimMind.Dialogue.Prompt.Context.Auto".CanTranslate() - ? "RimMind.Dialogue.Prompt.Context.Auto".Translate(context).ToString() - : context, + DialogueTriggerType.Chitchat => RimMindAPI.Text.TrOr( + "RimMind.Dialogue.Prompt.Context.Chitchat", + "[Chitchat: {0}]", + context), + DialogueTriggerType.Hediff => RimMindAPI.Text.TrOr( + "RimMind.Dialogue.Prompt.Context.Hediff", + "[Health condition: {0}]", + context), + DialogueTriggerType.LevelUp => RimMindAPI.Text.TrOr( + "RimMind.Dialogue.Prompt.Context.LevelUp", + "[Skill level up: {0}]", + context), + DialogueTriggerType.Thought => RimMindAPI.Text.TrOr( + "RimMind.Dialogue.Prompt.Context.Thought", + "[Recent thought: {0}]", + context), + DialogueTriggerType.Auto => RimMindAPI.Text.TrOr( + "RimMind.Dialogue.Prompt.Context.Auto", + "{0}", + context), _ => context }; @@ -407,12 +408,11 @@ private static string FormatContext( : GetRecipientRoleKey(recipient); if (recipient != null && roleKey != null) { - string recipientLine = "RimMind.Dialogue.Prompt.Context.Recipient".CanTranslate() - ? "RimMind.Dialogue.Prompt.Context.Recipient".Translate(recipient.Name.ToStringShort).ToString() - : $"[Recipient: {recipient.Name.ToStringShort}]"; - string roleLine = roleKey.CanTranslate() - ? roleKey.Translate().ToString() - : roleKey; + string recipientLine = RimMindAPI.Text.TrOr( + "RimMind.Dialogue.Prompt.Context.Recipient", + "[Recipient: {0}]", + recipient.Name.ToStringShort); + string roleLine = RimMindAPI.Text.TrOr(roleKey, roleKey); formatted += "\n" + recipientLine + "\n" + roleLine; } diff --git a/Source/Core/DialogueTextSanitizer.cs b/Source/Core/DialogueTextSanitizer.cs index 53c1c65..c796641 100644 --- a/Source/Core/DialogueTextSanitizer.cs +++ b/Source/Core/DialogueTextSanitizer.cs @@ -1,6 +1,7 @@ using System; using System.Text.RegularExpressions; using Newtonsoft.Json.Linq; +using RimMind.Presentation.Api; namespace RimMind.Dialogue.Core { @@ -138,29 +139,12 @@ public static string CleanFormattingGlitches(string text) if (string.IsNullOrWhiteSpace(text)) return string.Empty; - string result = text.Trim(); - - // Strip trailing code blocks - while (result.EndsWith("```")) - { - result = result.Substring(0, result.Length - 3).TrimEnd(); - } - - // Strip leading code blocks - if (result.StartsWith("```")) - { - int firstNewline = result.IndexOf('\n'); - if (firstNewline >= 0) - result = result.Substring(firstNewline + 1).TrimStart(); - else - result = result.TrimStart('`').TrimStart(); - } + // Delegate generic // and markdown code fence stripping to Core. + string result = RimMindAPI.Json.StripThinkingAndCodeFences(text); + if (string.IsNullOrWhiteSpace(result)) + return string.Empty; - // Strip ... blocks and residual XML wrapper tags (, , , , , ) - if (result.IndexOf("", StringComparison.OrdinalIgnoreCase) >= 0) - { - result = Regex.Replace(result, @"[\s\S]*?", string.Empty, RegexOptions.IgnoreCase).Trim(); - } + // Strip Dialogue-specific residual XML wrapper tags (, , , , etc.) if (result.IndexOf('<') >= 0 && result.IndexOf('>') >= 0) { result = Regex.Replace( @@ -171,56 +155,49 @@ public static string CleanFormattingGlitches(string text) } // Defensively extract inner speech if text contains or is wrapped in raw JSON object - if (result.Contains("{") && result.Contains("}")) + if (result.IndexOf('{') >= 0 && result.IndexOf('}') >= 0) { - try + string jsonCandidate = result; + while (jsonCandidate.StartsWith("{{", StringComparison.Ordinal) && jsonCandidate.EndsWith("}}", StringComparison.Ordinal)) + { + jsonCandidate = jsonCandidate.Substring(1, jsonCandidate.Length - 2).Trim(); + } + + if (RimMindAPI.Json.TryParseJObjectWithRepair(jsonCandidate, out var obj) && obj != null) { - int start = result.IndexOf('{'); - int end = result.LastIndexOf('}'); - if (start >= 0 && end > start) + var paramsObj = obj["parameters"] as JObject ?? obj["arguments"] as JObject; + string? innerSpeech = obj["speech"]?.ToString() + ?? obj["reply"]?.ToString() + ?? obj["dialogue"]?.ToString() + ?? obj["content"]?.ToString() + ?? obj["text"]?.ToString() + ?? paramsObj?["speech"]?.ToString() + ?? paramsObj?["reply"]?.ToString() + ?? paramsObj?["dialogue"]?.ToString() + ?? paramsObj?["content"]?.ToString() + ?? paramsObj?["text"]?.ToString(); + if (!string.IsNullOrWhiteSpace(innerSpeech)) + { + result = innerSpeech!.Trim(); + } + } + else + { + var m = Regex.Match(jsonCandidate, @"""(?:speech|reply|dialogue|content|text)""\s*:\s*""(?(?:\\.|[^""\\])*)"""); + if (m.Success) { - string jsonCandidate = result.Substring(start, end - start + 1); - while (jsonCandidate.StartsWith("{{") && jsonCandidate.EndsWith("}}")) - { - jsonCandidate = jsonCandidate.Substring(1, jsonCandidate.Length - 2).Trim(); - } try { - var obj = JObject.Parse(jsonCandidate); - var paramsObj = obj["parameters"] as JObject ?? obj["arguments"] as JObject; - string? innerSpeech = obj["speech"]?.ToString() - ?? obj["reply"]?.ToString() - ?? obj["dialogue"]?.ToString() - ?? obj["content"]?.ToString() - ?? obj["text"]?.ToString() - ?? paramsObj?["speech"]?.ToString() - ?? paramsObj?["reply"]?.ToString() - ?? paramsObj?["dialogue"]?.ToString() - ?? paramsObj?["content"]?.ToString() - ?? paramsObj?["text"]?.ToString(); - if (!string.IsNullOrWhiteSpace(innerSpeech)) - { - result = innerSpeech!.Trim(); - } - } - catch - { - var m = Regex.Match(jsonCandidate, @"""(?:speech|reply|dialogue|content|text)""\s*:\s*""(?(?:\\.|[^""\\])*)"""); - if (m.Success) - { - string unescaped = Regex.Unescape(m.Groups["val"].Value); - if (!string.IsNullOrWhiteSpace(unescaped)) - { - result = unescaped.Trim(); - } - } + string unescaped = Regex.Unescape(m.Groups["val"].Value); + if (!string.IsNullOrWhiteSpace(unescaped)) + result = unescaped.Trim(); } + catch { } } } - catch { } } - // Defensively extract inner speech if text is wrapped in pseudo-function-call syntax: express_dialogue(speech=..., thought_tag=..., ...) + // Defensively extract inner speech if text is wrapped in pseudo-function-call syntax: express_dialogue(speech=..., ...) if (DialogueToolParser.TryParsePseudoFunctionCall(result, out var pseudoObj) && pseudoObj != null) { string? pseudoSpeech = pseudoObj["speech"]?.ToString() @@ -268,8 +245,7 @@ public static string CleanFormattingGlitches(string text) /// /// Formats dialogue text for overhead map motes (MoteMaker.ThrowText) by stripping - /// formatting glitches, capping total length, and inserting a line break near the midpoint - /// so long lines never stretch horizontally across the entire screen. + /// formatting glitches, capping total length, and delegating CJK-aware line wrapping to Core. /// public static string FormatOverheadMoteText(string? text, int maxLineLength = 26, int maxTotalLength = 52) { @@ -283,26 +259,7 @@ public static string FormatOverheadMoteText(string? text, int maxLineLength = 26 cleaned = cleaned.Substring(0, maxTotalLength).TrimEnd(',', '。', ',', '.', '、', ' ') + "..."; } - if (cleaned.Length <= maxLineLength) - return cleaned; - - int splitPos = -1; - int searchStart = Math.Max(10, maxLineLength - 8); - int searchEnd = Math.Min(cleaned.Length - 4, maxLineLength + 6); - char[] breakChars = { ',', '。', '!', '?', ';', ',', '.', '!', '?', ';', ' ' }; - for (int i = searchEnd; i >= searchStart; i--) - { - if (Array.IndexOf(breakChars, cleaned[i]) >= 0) - { - splitPos = i + 1; - break; - } - } - - if (splitPos <= 0 || splitPos >= cleaned.Length) - splitPos = maxLineLength; - - return cleaned.Substring(0, splitPos).TrimEnd() + "\n" + cleaned.Substring(splitPos).TrimStart(); + return RimMindAPI.Text.WrapForMote(cleaned, maxLineLength); } /// diff --git a/Source/Core/DialogueToolParser.cs b/Source/Core/DialogueToolParser.cs index 92ec177..94d1a5e 100644 --- a/Source/Core/DialogueToolParser.cs +++ b/Source/Core/DialogueToolParser.cs @@ -1,9 +1,8 @@ using System; -using System.Collections.Generic; -using Newtonsoft.Json; +using System.Text.RegularExpressions; using Newtonsoft.Json.Linq; -using RimMind.Domain.Llm; using RimMind.Domain.ValueObjects; +using RimMind.Presentation.Api; namespace RimMind.Dialogue.Core { @@ -20,6 +19,11 @@ public static class DialogueToolParser private const int MaxRelationDelta = 5; private const int MinRelationDelta = -5; + // Dialogue-specific malformed pseudo-call quirk: express_dialogue(speech)=(...) + private static readonly Regex MalformedParenAssignRegex = new Regex( + @"\b(?:express_dialogue|record_morning_thought|[a-z_][a-z0-9_]*)\s*\(\s*(?speech|reply|dialogue|content|text|narration)\s*\)\s*[:=]\s*\((?[\s\S]+)\)\s*$", + RegexOptions.IgnoreCase | RegexOptions.Compiled); + public static bool TryParse(string? toolCallsJson, bool isMonologue, out DialogueOutput output) { output = new DialogueOutput(); @@ -28,72 +32,50 @@ public static bool TryParse(string? toolCallsJson, bool isMonologue, out Dialogu try { - string cleaned = toolCallsJson!.Trim(); - if (cleaned.StartsWith("```")) - { - int firstNewline = cleaned.IndexOf('\n'); - if (firstNewline >= 0) - cleaned = cleaned.Substring(firstNewline + 1); - if (cleaned.EndsWith("```")) - cleaned = cleaned.Substring(0, cleaned.Length - 3); - cleaned = cleaned.Trim(); - } + string trimmed = toolCallsJson!.Trim(); + // Avoid running outer code-fence regex across already-framed JSON objects/arrays, + // because tool arguments may legally contain escaped ```json ... ``` blocks inside string fields. + bool startsLikeJson = trimmed.StartsWith("[", StringComparison.Ordinal) + || trimmed.StartsWith("{", StringComparison.Ordinal); + string cleaned = startsLikeJson + ? trimmed + : RimMindAPI.Json.StripThinkingAndCodeFences(trimmed); + if (string.IsNullOrWhiteSpace(cleaned)) + return false; JObject? targetArgsObj = null; - if (!cleaned.StartsWith("{") && !cleaned.StartsWith("[")) + if (startsLikeJson) { - int braceStart = cleaned.IndexOf('{'); - int braceEnd = cleaned.LastIndexOf('}'); - if (braceStart >= 0 && braceEnd > braceStart) + if (cleaned.StartsWith("[", StringComparison.Ordinal)) { - cleaned = cleaned.Substring(braceStart, braceEnd - braceStart + 1).Trim(); + targetArgsObj = ExtractArgumentsFromJsonArray(cleaned); } - else if (TryParsePseudoFunctionCall(cleaned, out var pseudoArgs)) + else if (RimMindAPI.Json.TryParseJObjectWithRepair(cleaned, out var directObj) && directObj != null) { - targetArgsObj = pseudoArgs; - } - else - { - return false; + targetArgsObj = ExtractArguments(directObj); } } if (targetArgsObj == null) { - JToken token = JToken.Parse(cleaned); - - if (token is JArray arr) + string? payload = RimMindAPI.Json.ExtractJsonPayload(cleaned); + if (!string.IsNullOrWhiteSpace(payload)) { - foreach (var item in arr) + if (payload!.StartsWith("[", StringComparison.Ordinal)) { - if (item is JObject obj) - { - string? name = GetToolName(obj); - if (string.Equals(name, DialogueToolDefinitions.ExpressDialogueToolName, StringComparison.OrdinalIgnoreCase)) - { - targetArgsObj = ExtractArguments(obj); - if (targetArgsObj != null) break; - } - } + targetArgsObj = ExtractArgumentsFromJsonArray(payload); } - - if (targetArgsObj == null) + else if (RimMindAPI.Json.TryParseJObjectWithRepair(payload, out var singleObj) && singleObj != null) { - foreach (var item in arr) - { - if (item is JObject obj) - { - targetArgsObj = ExtractArguments(obj); - if (targetArgsObj != null) break; - } - } + targetArgsObj = ExtractArguments(singleObj); } } - else if (token is JObject singleObj) - { - targetArgsObj = ExtractArguments(singleObj); - } + } + + if (targetArgsObj == null && TryParsePseudoFunctionCall(cleaned, out var pseudoArgs)) + { + targetArgsObj = pseudoArgs; } if (targetArgsObj == null) @@ -104,30 +86,28 @@ public static bool TryParse(string? toolCallsJson, bool isMonologue, out Dialogu return false; output.Speech = speech!.Trim(); - if (output.Speech.StartsWith("{") && output.Speech.EndsWith("}")) + if (output.Speech.StartsWith("{", StringComparison.Ordinal) + && output.Speech.EndsWith("}", StringComparison.Ordinal) + && RimMindAPI.Json.TryParseJObjectWithRepair(output.Speech, out var inner) + && inner != null) { - try + string? innerSpeech = GetString(inner, "speech", "reply", "dialogue", "content", "text", "narration"); + if (!string.IsNullOrWhiteSpace(innerSpeech)) { - var inner = JObject.Parse(output.Speech); - string? innerSpeech = GetString(inner, "speech", "reply", "dialogue", "content", "text", "narration"); - if (!string.IsNullOrWhiteSpace(innerSpeech)) + output.Speech = innerSpeech!.Trim(); + if (inner.TryGetValue("thought", StringComparison.OrdinalIgnoreCase, out var thoughtToken) && thoughtToken is JObject thoughtObj) + { + output.ThoughtTag ??= GetString(thoughtObj, "tag", "thought_tag"); + output.ThoughtDesc ??= GetString(thoughtObj, "description", "desc", "thought_desc"); + } + output.ThoughtTag ??= GetString(inner, "thought_tag", "tag", "thought"); + output.ThoughtDesc ??= GetString(inner, "thought_desc", "description", "desc"); + if (!isMonologue && output.RelationDelta == 0) { - output.Speech = innerSpeech!.Trim(); - if (inner.TryGetValue("thought", StringComparison.OrdinalIgnoreCase, out var thoughtToken) && thoughtToken is JObject thoughtObj) - { - output.ThoughtTag ??= GetString(thoughtObj, "tag", "thought_tag"); - output.ThoughtDesc ??= GetString(thoughtObj, "description", "desc", "thought_desc"); - } - output.ThoughtTag ??= GetString(inner, "thought_tag", "tag", "thought"); - output.ThoughtDesc ??= GetString(inner, "thought_desc", "description", "desc"); - if (!isMonologue && output.RelationDelta == 0) - { - int d = GetInt(inner, "relation_delta", "delta", "relation"); - output.RelationDelta = Math.Clamp(d, MinRelationDelta, MaxRelationDelta); - } + int d = GetInt(inner, "relation_delta", "delta", "relation"); + output.RelationDelta = Math.Clamp(d, MinRelationDelta, MaxRelationDelta); } } - catch { } } output.ThoughtTag ??= GetString(targetArgsObj, "thought_tag", "tag", "thought"); @@ -165,6 +145,51 @@ public static bool TryParse(string? toolCallsJson, bool isMonologue, out Dialogu } } + private static JObject? ExtractArgumentsFromJsonArray(string arrayJson) + { + JArray? arr = null; + try + { + arr = JToken.Parse(arrayJson) as JArray; + } + catch + { + string? repaired = RimMindAPI.Json.TryRepairJson(arrayJson); + if (!string.IsNullOrWhiteSpace(repaired)) + { + try { arr = JToken.Parse(repaired!) as JArray; } + catch { arr = null; } + } + } + + if (arr == null) + return null; + + foreach (var item in arr) + { + if (item is JObject obj) + { + string? name = GetToolName(obj); + if (string.Equals(name, DialogueToolDefinitions.ExpressDialogueToolName, StringComparison.OrdinalIgnoreCase)) + { + var args = ExtractArguments(obj); + if (args != null) return args; + } + } + } + + foreach (var item in arr) + { + if (item is JObject obj) + { + var args = ExtractArguments(obj); + if (args != null) return args; + } + } + + return null; + } + private static string? GetToolName(JObject obj) { if (obj.TryGetValue("name", StringComparison.OrdinalIgnoreCase, out var nameToken) && nameToken.Type == JTokenType.String) @@ -186,6 +211,10 @@ public static bool TryParse(string? toolCallsJson, bool isMonologue, out Dialogu { argsToken = directArgs; } + else if (obj.TryGetValue("parameters", StringComparison.OrdinalIgnoreCase, out var directParams)) + { + argsToken = directParams; + } else if (obj.TryGetValue("function", StringComparison.OrdinalIgnoreCase, out var fnToken) && fnToken is JObject fnObj) { if (fnObj.TryGetValue("arguments", StringComparison.OrdinalIgnoreCase, out var nestedArgs)) @@ -196,7 +225,7 @@ public static bool TryParse(string? toolCallsJson, bool isMonologue, out Dialogu if (argsToken == null) { - if (obj.ContainsKey("speech") || obj.ContainsKey("reply") || obj.ContainsKey("narration")) + if (obj.ContainsKey("speech") || obj.ContainsKey("reply") || obj.ContainsKey("narration") || obj.ContainsKey("dialogue")) return obj; return null; } @@ -208,18 +237,9 @@ public static bool TryParse(string? toolCallsJson, bool isMonologue, out Dialogu if (argsToken.Type == JTokenType.String) { - string rawArgs = argsToken.Value()?.Trim() ?? string.Empty; - if (string.IsNullOrWhiteSpace(rawArgs)) return null; - if (rawArgs.StartsWith("```")) - { - int firstNewline = rawArgs.IndexOf('\n'); - if (firstNewline >= 0) - rawArgs = rawArgs.Substring(firstNewline + 1); - if (rawArgs.EndsWith("```")) - rawArgs = rawArgs.Substring(0, rawArgs.Length - 3); - rawArgs = rawArgs.Trim(); - } - return JObject.Parse(rawArgs); + string rawArgs = argsToken.Value() ?? string.Empty; + if (RimMindAPI.Json.TryParseJObjectWithRepair(rawArgs, out var parsed) && parsed != null) + return parsed; } return null; @@ -270,45 +290,45 @@ internal static bool TryParsePseudoFunctionCall(string text, out JObject? argsOb argsObj = null; if (string.IsNullOrWhiteSpace(text)) return false; - var fnMatch = System.Text.RegularExpressions.Regex.Match( - text.Trim(), - @"\b(?:express_dialogue|record_morning_thought|[a-z_][a-z0-9_]*)\s*\((?[\s\S]+?)\)?\s*$", - System.Text.RegularExpressions.RegexOptions.IgnoreCase); - if (!fnMatch.Success) return false; - - string inner = fnMatch.Groups["inner"].Value.Trim(); - var keyMatches = System.Text.RegularExpressions.Regex.Matches( - inner, - @"(?:^|,\s*)(?speech|reply|dialogue|content|text|narration|thought_tag|thought_desc|tag|desc|description|relation_delta|delta|relation|thought|motivation|mindset)\)?\s*[:=]\s*", - System.Text.RegularExpressions.RegexOptions.IgnoreCase); - if (keyMatches.Count == 0) return false; - - var jObj = new JObject(); - for (int i = 0; i < keyMatches.Count; i++) + // Primary path: delegate to Core's unified pseudo-function-call parser. + var calls = RimMindAPI.Json.ParsePseudoFunctionCalls(text); + if (calls != null && calls.Count > 0) { - string key = keyMatches[i].Groups["key"].Value; - int valStart = keyMatches[i].Index + keyMatches[i].Length; - int valEnd = (i + 1 < keyMatches.Count) ? keyMatches[i + 1].Index : inner.Length; - string rawVal = inner.Substring(valStart, valEnd - valStart).Trim(); - if ((rawVal.StartsWith("\"") && rawVal.EndsWith("\"") && rawVal.Length >= 2) || - (rawVal.StartsWith("'") && rawVal.EndsWith("'") && rawVal.Length >= 2) || - (rawVal.StartsWith("“") && rawVal.EndsWith("”") && rawVal.Length >= 2) || - (rawVal.StartsWith("(") && rawVal.EndsWith(")") && rawVal.Length >= 2)) + foreach (var call in calls) { - rawVal = rawVal.Substring(1, rawVal.Length - 2).Replace("\\\"", "\"").Trim(); + if (string.Equals(call.Name, DialogueToolDefinitions.ExpressDialogueToolName, StringComparison.OrdinalIgnoreCase) + && RimMindAPI.Json.TryParseJObjectWithRepair(call.ArgumentsJson, out var expressObj) + && expressObj != null) + { + argsObj = expressObj; + return true; + } } - else if (rawVal.StartsWith("(") && keyMatches[i].Value.IndexOf(')') >= 0) + + foreach (var call in calls) { - rawVal = rawVal.Substring(1).TrimEnd(')').Trim(); + if (RimMindAPI.Json.TryParseJObjectWithRepair(call.ArgumentsJson, out var parsed) + && parsed != null + && GetString(parsed, "speech", "reply", "dialogue", "content", "text", "narration") != null) + { + argsObj = parsed; + return true; + } } - if (int.TryParse(rawVal, out int intVal)) - jObj[key] = intVal; - else - jObj[key] = rawVal; } - argsObj = jObj; - return true; + // Narrow Dialogue-specific quirk fallback: express_dialogue(speech)=(...) + var malformed = MalformedParenAssignRegex.Match(text.Trim()); + if (malformed.Success) + { + argsObj = new JObject + { + [malformed.Groups["key"].Value] = malformed.Groups["val"].Value.Trim() + }; + return true; + } + + return false; } } } diff --git a/Source/Core/NpcResponseHandler.cs b/Source/Core/NpcResponseHandler.cs index d6c83a0..351362b 100644 --- a/Source/Core/NpcResponseHandler.cs +++ b/Source/Core/NpcResponseHandler.cs @@ -71,7 +71,7 @@ public static class NpcResponseHandler try { string summary = replyText.Length > 80 ? replyText.Substring(0, 80) + "..." : replyText; - RimMind.Presentation.Api.RimMindAPI.PublishPerception(pawn.thingIDNumber, "dialogue_completed", summary, 0.4f); + RimMindAPI.Bus.PublishPerception(pawn.thingIDNumber, "dialogue_completed", summary, 0.4f); } catch (Exception ex) { RimMindErrors.Warn($"[RimMind] PublishPerception dialogue_completed failed: {ex.Message}"); } diff --git a/Source/Core/ResponseJsonParser.cs b/Source/Core/ResponseJsonParser.cs index 311265e..3a3babc 100644 --- a/Source/Core/ResponseJsonParser.cs +++ b/Source/Core/ResponseJsonParser.cs @@ -1,12 +1,13 @@ using System; -using System.Collections.Generic; -using System.Text.RegularExpressions; -using Newtonsoft.Json; using Newtonsoft.Json.Linq; -using RimMind.Domain.ValueObjects; +using RimMind.Presentation.Api; namespace RimMind.Dialogue.Core { + /// + /// Legacy compatibility forwarder kept for binary/test compatibility. + /// Delegates JSON extraction and repair to Core . + /// [Obsolete("Use DialogueToolParser instead. RimMind mainline dialogue is now unified under native express_dialogue tool calls.")] public static class ResponseJsonParser { @@ -18,90 +19,47 @@ public static class ResponseJsonParser public static void TryParseResponseJson(string? rawResponse, bool isMonologue, ref string replyText, ref string? thoughtTag, ref string? thoughtDesc, ref int relationDelta) { - if (string.IsNullOrWhiteSpace(rawResponse)) return; - - string cleaned = rawResponse!.Trim(); - if (cleaned.StartsWith("```")) - { - int firstNewline = cleaned.IndexOf('\n'); - if (firstNewline >= 0) - cleaned = cleaned.Substring(firstNewline + 1); - if (cleaned.EndsWith("```")) - cleaned = cleaned.Substring(0, cleaned.Length - 3); - cleaned = cleaned.Trim(); - } + if (string.IsNullOrWhiteSpace(rawResponse)) + return; - int firstBrace = cleaned.IndexOf('{'); - int lastBrace = cleaned.LastIndexOf('}'); - if (firstBrace >= 0 && lastBrace > firstBrace) - { - cleaned = cleaned.Substring(firstBrace, lastBrace - firstBrace + 1); - } - else - { + if (!RimMindAPI.Json.TryParseJObjectWithRepair(rawResponse, out var obj) || obj == null) return; - } - bool extractedReply = false; - try + foreach (var field in ReplyFieldNames) { - var obj = JsonConvert.DeserializeObject>(cleaned); - if (obj != null) + if (obj.TryGetValue(field, StringComparison.OrdinalIgnoreCase, out var token) + && token.Type == JTokenType.String) { - foreach (var field in ReplyFieldNames) - { - if (obj.TryGetValue(field, out var val) && val is string str && !string.IsNullOrEmpty(str)) - { - replyText = str; - extractedReply = true; - break; - } - } - - if (obj.TryGetValue("thought", out var thoughtObj)) + string? str = token.Value(); + if (!string.IsNullOrEmpty(str)) { - if (thoughtObj is JObject thoughtJObj) - { - thoughtTag = thoughtJObj.Value("tag"); - thoughtDesc = thoughtJObj.Value("description"); - } - else if (thoughtObj is string tagStr && !string.IsNullOrEmpty(tagStr)) - { - thoughtTag = tagStr; - } - } - - if (!isMonologue && obj.TryGetValue("relation_delta", out var relObj)) - { - if (relObj is long relLong) relationDelta = (int)relLong; - else if (relObj is int relInt) relationDelta = relInt; + replyText = str!; + break; } } } - catch (Exception ex) - { - RimMindErrors.Warn($"[RimMind] TryParseResponseJson failed: {ex.Message}"); - } - // Fallback regex extraction if JSON parse or fields failed - if (!extractedReply) + if (obj.TryGetValue("thought", StringComparison.OrdinalIgnoreCase, out var thoughtToken)) { - try + if (thoughtToken is JObject thoughtJObj) { - var match = Regex.Match( - cleaned, - "\"(?:reply|narration|dialogue|speech|text|content|message)\"\\s*:\\s*\"((?:\\\\\"|[^\"])+)\"", - RegexOptions.IgnoreCase); - if (match.Success) - { - replyText = Regex.Unescape(match.Groups[1].Value); - } + thoughtTag = thoughtJObj.Value("tag"); + thoughtDesc = thoughtJObj.Value("description"); } - catch + else if (thoughtToken.Type == JTokenType.String) { - // Ignore regex errors + string? tagStr = thoughtToken.Value(); + if (!string.IsNullOrEmpty(tagStr)) + thoughtTag = tagStr; } } + + if (!isMonologue + && obj.TryGetValue("relation_delta", StringComparison.OrdinalIgnoreCase, out var relToken) + && relToken.Type == JTokenType.Integer) + { + relationDelta = relToken.Value(); + } } } } diff --git a/Source/Core/RimMindDialogueService.cs b/Source/Core/RimMindDialogueService.cs index 45b696c..aecc724 100644 --- a/Source/Core/RimMindDialogueService.cs +++ b/Source/Core/RimMindDialogueService.cs @@ -3,7 +3,9 @@ using System.Collections.Generic; using System.Linq; using RimMind.Dialogue.Settings; +using RimMind.Presentation.Api; using RimWorld; +using UnityEngine; using Verse; namespace RimMind.Dialogue.Core @@ -119,6 +121,31 @@ public static void TryTriggerReply( replier, originalMessage); + internal const float OverheadMoteBaseZOffset = 1.35f; + internal const float OverheadMotePerExtraLineZOffset = 0.25f; + internal const float OverheadMoteMaxExtraZOffset = 0.75f; + + /// + /// Computes the world-space spawn position for an overhead speech mote so multi-line + /// dialogue floats cleanly above the colonist's head and never collides with the pawn's + /// nameplate below . + /// + internal static Vector3 ComputeOverheadMotePosition(Vector3 pawnDrawPos, string? moteText) + { + int extraLines = 0; + if (!string.IsNullOrEmpty(moteText)) + { + for (int i = 0; i < moteText!.Length; i++) + { + if (moteText[i] == '\n') + extraLines++; + } + } + + float extraZ = Math.Min(OverheadMoteMaxExtraZOffset, extraLines * OverheadMotePerExtraLineZOffset); + return new Vector3(pawnDrawPos.x, pawnDrawPos.y, pawnDrawPos.z + OverheadMoteBaseZOffset + extraZ); + } + public static void DisplayInteraction(Pawn initiator, Pawn? recipient, string replyText) { if (initiator.Map == null) return; @@ -126,8 +153,9 @@ public static void DisplayInteraction(Pawn initiator, Pawn? recipient, string re string moteText = DialogueTextSanitizer.FormatOverheadMoteText(replyText); if (string.IsNullOrWhiteSpace(moteText)) return; - MoteMaker.ThrowText(initiator.DrawPos, initiator.Map, moteText, - new UnityEngine.Color(0.85f, 0.95f, 1f), 6f); + Vector3 spawnPos = ComputeOverheadMotePosition(initiator.DrawPos, moteText); + MoteMaker.ThrowText(spawnPos, initiator.Map, moteText, + new Color(0.85f, 0.95f, 1f), 6f); } public static void RegisterTriggerType(string typeId, string labelKey) @@ -139,7 +167,7 @@ public static string GetTriggerLabel(DialogueTriggerType type) { string typeStr = type.ToString(); if (RegisteredTriggerLabels.TryGetValue(typeStr, out var label)) - return label.CanTranslate() ? (string)label.Translate() : label; + return RimMindAPI.Text.TrOr(label, label); return type switch { DialogueTriggerType.Chitchat => "RimMind.Dialogue.Trigger.Chitchat".Translate(), diff --git a/Source/Data/RimMindDialogueWorldComponent.cs b/Source/Data/RimMindDialogueWorldComponent.cs index 1093643..d1a7159 100644 --- a/Source/Data/RimMindDialogueWorldComponent.cs +++ b/Source/Data/RimMindDialogueWorldComponent.cs @@ -1,6 +1,7 @@ using System.Collections.Generic; using RimMind.Dialogue.Core; using RimMind.Dialogue.Settings; +using RimMind.Presentation.Api; using RimWorld.Planet; using Verse; @@ -8,14 +9,17 @@ namespace RimMind.Dialogue.Data { public class RimMindDialogueWorldComponent : WorldComponent { + private static readonly WorldScopedComponentCache _instanceCache = + new WorldScopedComponentCache(); + private List _savedEntries = new List(); - private static RimMindDialogueWorldComponent? _instance; - public static RimMindDialogueWorldComponent? Instance => _instance; + public static RimMindDialogueWorldComponent? Instance => _instanceCache.Get(); + + internal static void ResetInstanceCache() => _instanceCache.Reset(); public RimMindDialogueWorldComponent(World world) : base(world) { - _instance = this; } public override void ExposeData() diff --git a/Source/Debug/DialogueBehaviorAutotestSuite.cs b/Source/Debug/DialogueBehaviorAutotestSuite.cs index b8cd8c1..8d07e93 100644 --- a/Source/Debug/DialogueBehaviorAutotestSuite.cs +++ b/Source/Debug/DialogueBehaviorAutotestSuite.cs @@ -26,9 +26,10 @@ public override void RunSuite(IInGameBehaviorSuiteContext context) Pawn? pawn = context.ActiveColonist; // 1. CompRimMindDialogue Attachment - if (context.CurrentMap?.mapPawns?.FreeColonists != null && context.CurrentMap.mapPawns.FreeColonists.Count > 0) + var colonists = RimMindPawnLookup.GetSpawnedColonistsSafe(context.CurrentMap); + if (colonists.Count > 0) { - bool anyAttached = context.CurrentMap.mapPawns.FreeColonists.Any(p => p.GetComp() != null); + bool anyAttached = colonists.Any(p => p.GetComp() != null); context.Assert(anyAttached, "Free colonists on map have CompRimMindDialogue attached"); } else if (pawn != null) diff --git a/Source/Debug/DialogueDebugActions.cs b/Source/Debug/DialogueDebugActions.cs index 685e843..b45c3a8 100644 --- a/Source/Debug/DialogueDebugActions.cs +++ b/Source/Debug/DialogueDebugActions.cs @@ -4,6 +4,7 @@ using RimMind.Dialogue.Core; using RimMind.Dialogue.Settings; using RimMind.Dialogue.UI; +using RimMind.Presentation.Api; using RimWorld; using Verse; @@ -81,12 +82,11 @@ private static void ToggleOverlay() private static Pawn? FindAnotherColonist(Pawn exclude) { - var map = exclude.Map; - if (map == null) return null; - - foreach (var p in map.mapPawns.FreeColonistsSpawned) + var colonists = RimMindPawnLookup.GetSpawnedColonistsSafe(exclude.Map); + for (int i = 0; i < colonists.Count; i++) { - if (p != exclude) return p; + var p = colonists[i]; + if (p != null && p != exclude) return p; } return null; } diff --git a/Source/Extensions/DialogueSettingsTab.cs b/Source/Extensions/DialogueSettingsTab.cs index 1f3e49f..adae486 100644 --- a/Source/Extensions/DialogueSettingsTab.cs +++ b/Source/Extensions/DialogueSettingsTab.cs @@ -1,7 +1,7 @@ -using UnityEngine; -using Verse; -using RimMind.Presentation.Settings; using RimMind.Dialogue.Settings; +using RimMind.Presentation.Api; +using RimMind.Presentation.Settings; +using UnityEngine; namespace RimMind.Dialogue { @@ -9,7 +9,7 @@ internal sealed class DialogueSettingsTab : ISettingsTab { public string Id => "dialogue"; public string OwnerModId => "RimMindDialogue"; - public string Label => "RimMind.Dialogue.Settings.TabLabel".CanTranslate() ? "RimMind.Dialogue.Settings.TabLabel".Translate() : "Dialogue"; + public string Label => RimMindAPI.Text.TrOr("RimMind.Dialogue.Settings.TabLabel", "Dialogue"); public void Draw(Rect rect) => RimMindDialogueSettings.DrawSettingsContent(rect); } } diff --git a/Source/Patches/FloatMenuPatch.cs b/Source/Patches/FloatMenuPatch.cs index ca03a38..d2ad663 100644 --- a/Source/Patches/FloatMenuPatch.cs +++ b/Source/Patches/FloatMenuPatch.cs @@ -85,13 +85,13 @@ private static bool IsValidTarget(Pawn target) private static void AddTalkOption(List result, Pawn initiator, Pawn target) { - if (RimMindAPI.ShouldSkipFloatMenu()) return; + if (RimMindAPI.Ext.ShouldSkipFloatMenu()) return; result.Add(new FloatMenuOption( "RimMind.Dialogue.UI.FloatMenu.ChatWith".Translate(target.LabelShortCap), delegate { - if (!RimMindAPI.IsConfigured()) + if (!RimMindAPI.Settings.IsConfigured()) { Messages.Message("RimMind.Dialogue.UI.FloatMenu.APINotConfigured".Translate(), MessageTypeDefOf.RejectInput, false); diff --git a/Source/Patches/HediffPatch.cs b/Source/Patches/HediffPatch.cs index bfff5f3..217faf7 100644 --- a/Source/Patches/HediffPatch.cs +++ b/Source/Patches/HediffPatch.cs @@ -93,9 +93,7 @@ public static void Postfix(Pawn_HealthTracker __instance, Hediff hediff) hediff.def.makesSickThought, isLifeThreatening, hediff.Part?.Label)); - string context = "RimMind.Dialogue.Context.HediffOccurred".CanTranslate() - ? (string)"RimMind.Dialogue.Context.HediffOccurred".Translate(label) - : label; + string context = RimMindAPI.Text.TrOr("RimMind.Dialogue.Context.HediffOccurred", "{0}", label); RimMindDialogueService.HandleTrigger(pawn, context, DialogueTriggerType.Hediff, null); } } diff --git a/Source/Settings/RimMindDialogueSettings.cs b/Source/Settings/RimMindDialogueSettings.cs index 6c5231e..0d01c2c 100644 --- a/Source/Settings/RimMindDialogueSettings.cs +++ b/Source/Settings/RimMindDialogueSettings.cs @@ -104,167 +104,132 @@ public override void ExposeData() } private static Vector2 _settingsScrollPos = Vector2.zero; + private static float _measuredSettingsHeight = 640f; public static void DrawSettingsContent(UnityEngine.Rect inRect) { var s = Get(); - Rect contentArea = SettingsUIDrawer.SplitContentArea(inRect); - Rect bottomBar = SettingsUIDrawer.SplitBottomBar(inRect); - - float contentH = EstimateSettingsHeight(); - Rect viewRect = new Rect(0f, 0f, contentArea.width - 16f, contentH); - Widgets.BeginScrollView(contentArea, ref _settingsScrollPos, viewRect); - - var listing = new Listing_Standard(); - listing.Begin(viewRect); - - listing.CheckboxLabeled("RimMind.Dialogue.Settings.Enable".Translate(), ref s.enabled, - "RimMind.Dialogue.Settings.Enable.Desc".Translate()); - - SettingsUIDrawer.DrawSectionHeader(listing, "RimMind.Dialogue.Settings.TriggerSources".Translate()); - listing.CheckboxLabeled("RimMind.Dialogue.Settings.ChitchatIntercept".Translate(), ref s.chitchatEnabled, - "RimMind.Dialogue.Settings.ChitchatIntercept.Desc".Translate()); - listing.CheckboxLabeled("RimMind.Dialogue.Settings.HediffReaction".Translate(), ref s.hediffEnabled, - "RimMind.Dialogue.Settings.HediffReaction.Desc".Translate()); - listing.CheckboxLabeled("RimMind.Dialogue.Settings.LevelUpReaction".Translate(), ref s.levelUpEnabled, - "RimMind.Dialogue.Settings.LevelUpReaction.Desc".Translate()); - listing.CheckboxLabeled("RimMind.Dialogue.Settings.ThoughtReaction".Translate(), ref s.thoughtEnabled, - "RimMind.Dialogue.Settings.ThoughtReaction.Desc".Translate()); - if (s.thoughtEnabled) - { - listing.Label(" " + "RimMind.Dialogue.Settings.MoodThreshold".Translate($"{s.moodChangeThreshold:F0}")); - s.moodChangeThreshold = listing.Slider(s.moodChangeThreshold, 1f, 5f); - } - listing.CheckboxLabeled("RimMind.Dialogue.Settings.AutoMonologue".Translate(), ref s.autoDialogueEnabled, - "RimMind.Dialogue.Settings.AutoMonologue.Desc".Translate()); - if (s.autoDialogueEnabled) - { - listing.LabelWithTooltip( - " " + "RimMind.Dialogue.Settings.AutoInterval".Translate(s.autoDialogueCooldownHours), - "RimMind.Dialogue.Settings.AutoMonologueDesc".Translate()); - s.autoDialogueCooldownHours = (int)listing.Slider(s.autoDialogueCooldownHours, 1f, 24f); - } - listing.CheckboxLabeled("RimMind.Dialogue.Settings.PlayerDialogueGizmo".Translate(), ref s.playerDialogueEnabled, - "RimMind.Dialogue.Settings.PlayerDialogueGizmo.Desc".Translate()); - - SettingsUIDrawer.DrawSectionHeader(listing, "RimMind.Dialogue.Settings.Section.Behavior".Translate()); - listing.LabelWithTooltip( - "RimMind.Dialogue.Settings.MonologueCooldown".Translate($"{s.monologueCooldownTicks / 2500f:F1}", $"{s.monologueCooldownTicks}"), - "RimMind.Dialogue.Settings.MonologueCooldown.Desc".Translate()); - s.monologueCooldownTicks = (int)listing.Slider(s.monologueCooldownTicks, 3600f, 72000f); - s.monologueCooldownTicks = (s.monologueCooldownTicks / 600) * 600; - - listing.LabelWithTooltip( - "RimMind.Dialogue.Settings.MaxDailyDialogues".Translate(s.maxDailyDialogueRounds), - "RimMind.Dialogue.Settings.MaxDailyDialogues.Desc".Translate()); - s.maxDailyDialogueRounds = (int)listing.Slider(s.maxDailyDialogueRounds, 1f, 20f); - - listing.LabelWithTooltip( - "RimMind.Dialogue.Settings.GlobalConcurrency".Translate(s.globalConcurrency), - "RimMind.Dialogue.Settings.GlobalConcurrency.Desc".Translate()); - s.globalConcurrency = (int)listing.Slider(s.globalConcurrency, 1f, 10f); - - listing.CheckboxLabeled("RimMind.Dialogue.Settings.EnableDialogueReply".Translate(), ref s.enableDialogueReply, - "RimMind.Dialogue.Settings.EnableDialogueReply.Desc".Translate()); - if (s.enableDialogueReply) - { - listing.LabelWithTooltip( - "RimMind.Dialogue.Settings.MaxDailyReplies".Translate(s.maxDailyReplyRounds), - "RimMind.Dialogue.Settings.MaxDailyReplies.Desc".Translate()); - s.maxDailyReplyRounds = (int)listing.Slider(s.maxDailyReplyRounds, 1f, 50f); - } - - listing.CheckboxLabeled("RimMind.Dialogue.Settings.StartDelay".Translate(), ref s.startDelayEnabled, - "RimMind.Dialogue.Settings.StartDelay.Desc".Translate()); - if (s.startDelayEnabled) - { - listing.Label(" " + "RimMind.Dialogue.Settings.StartDelayValue".Translate(s.startDelaySeconds)); - s.startDelaySeconds = (int)listing.Slider(s.startDelaySeconds, 1f, 60f); - } - - SettingsUIDrawer.DrawSectionHeader(listing, "RimMind.Dialogue.Settings.Section.Display".Translate()); - listing.CheckboxLabeled("RimMind.Dialogue.Settings.ShowNotification".Translate(), ref s.showThoughtNotification, - "RimMind.Dialogue.Settings.ShowNotification.Desc".Translate()); - listing.CheckboxLabeled("RimMind.Dialogue.Settings.ShowOverlay".Translate(), ref s.overlayEnabled, - "RimMind.Dialogue.Settings.ShowOverlay.Desc".Translate()); - listing.LabelWithTooltip( - "RimMind.Dialogue.Settings.OverlayOpacity".Translate($"{s.overlayOpacity:P0}"), - "RimMind.Dialogue.Settings.OverlayOpacity.Desc".Translate()); - s.overlayOpacity = listing.Slider(s.overlayOpacity, 0.1f, 1f); - listing.LabelWithTooltip( - "RimMind.Dialogue.Settings.OverlayMaxMessages".Translate(s.overlayMaxMessages), - "RimMind.Dialogue.Settings.OverlayMaxMessages.Desc".Translate()); - s.overlayMaxMessages = (int)listing.Slider(s.overlayMaxMessages, 3f, 20f); - - listing.End(); - Widgets.EndScrollView(); - - SettingsUIDrawer.DrawBottomBar(bottomBar, () => - { - s.enabled = true; - s.chitchatEnabled = true; - s.hediffEnabled = true; - s.levelUpEnabled = true; - s.thoughtEnabled = true; - s.autoDialogueEnabled = true; - s.playerDialogueEnabled = true; - s.moodChangeThreshold = 3f; - s.autoDialogueCooldownHours = 12; - s.maxDailyDialogueRounds = 6; - s.globalConcurrency = 3; - s.showThoughtNotification = false; - s.enableDialogueReply = true; - s.maxDailyReplyRounds = 12; - s.monologueCooldownTicks = 36000; - s.enableRecreationSocial = true; - s.recreationSocialChance = 0.35f; - s.enableDiningSocial = true; - s.diningSocialChance = 0.30f; - s.enableCoworkerSocial = true; - s.coworkerSocialChance = 0.25f; - s.startDelayEnabled = true; - s.startDelaySeconds = 10; - s.overlayEnabled = true; - s.overlayOpacity = 0.75f; - s.overlayMaxMessages = 8; - s.overlayX = 20f; - s.overlayY = 320f; - s.overlayW = 420f; - s.overlayH = 220f; - }); - - Get().Write(); + SettingsUIDrawer.DrawScrollableSettingsPage( + inRect, + ref _settingsScrollPos, + ref _measuredSettingsHeight, + listing => + { + listing.CheckboxLabeled("RimMind.Dialogue.Settings.Enable".Translate(), ref s.enabled, + "RimMind.Dialogue.Settings.Enable.Desc".Translate()); + + SettingsUIDrawer.DrawSectionHeader(listing, "RimMind.Dialogue.Settings.TriggerSources".Translate()); + listing.CheckboxLabeled("RimMind.Dialogue.Settings.ChitchatIntercept".Translate(), ref s.chitchatEnabled, + "RimMind.Dialogue.Settings.ChitchatIntercept.Desc".Translate()); + listing.CheckboxLabeled("RimMind.Dialogue.Settings.HediffReaction".Translate(), ref s.hediffEnabled, + "RimMind.Dialogue.Settings.HediffReaction.Desc".Translate()); + listing.CheckboxLabeled("RimMind.Dialogue.Settings.LevelUpReaction".Translate(), ref s.levelUpEnabled, + "RimMind.Dialogue.Settings.LevelUpReaction.Desc".Translate()); + listing.CheckboxLabeled("RimMind.Dialogue.Settings.ThoughtReaction".Translate(), ref s.thoughtEnabled, + "RimMind.Dialogue.Settings.ThoughtReaction.Desc".Translate()); + if (s.thoughtEnabled) + { + listing.Label(" " + "RimMind.Dialogue.Settings.MoodThreshold".Translate($"{s.moodChangeThreshold:F0}")); + s.moodChangeThreshold = listing.Slider(s.moodChangeThreshold, 1f, 5f); + } + listing.CheckboxLabeled("RimMind.Dialogue.Settings.AutoMonologue".Translate(), ref s.autoDialogueEnabled, + "RimMind.Dialogue.Settings.AutoMonologue.Desc".Translate()); + if (s.autoDialogueEnabled) + { + listing.LabelWithTooltip( + " " + "RimMind.Dialogue.Settings.AutoInterval".Translate(s.autoDialogueCooldownHours), + "RimMind.Dialogue.Settings.AutoMonologueDesc".Translate()); + s.autoDialogueCooldownHours = (int)listing.Slider(s.autoDialogueCooldownHours, 1f, 24f); + } + listing.CheckboxLabeled("RimMind.Dialogue.Settings.PlayerDialogueGizmo".Translate(), ref s.playerDialogueEnabled, + "RimMind.Dialogue.Settings.PlayerDialogueGizmo.Desc".Translate()); + + SettingsUIDrawer.DrawSectionHeader(listing, "RimMind.Dialogue.Settings.Section.Behavior".Translate()); + listing.LabelWithTooltip( + "RimMind.Dialogue.Settings.MonologueCooldown".Translate($"{s.monologueCooldownTicks / 2500f:F1}", $"{s.monologueCooldownTicks}"), + "RimMind.Dialogue.Settings.MonologueCooldown.Desc".Translate()); + s.monologueCooldownTicks = (int)listing.Slider(s.monologueCooldownTicks, 3600f, 72000f); + s.monologueCooldownTicks = (s.monologueCooldownTicks / 600) * 600; + + listing.LabelWithTooltip( + "RimMind.Dialogue.Settings.MaxDailyDialogues".Translate(s.maxDailyDialogueRounds), + "RimMind.Dialogue.Settings.MaxDailyDialogues.Desc".Translate()); + s.maxDailyDialogueRounds = (int)listing.Slider(s.maxDailyDialogueRounds, 1f, 20f); + + listing.LabelWithTooltip( + "RimMind.Dialogue.Settings.GlobalConcurrency".Translate(s.globalConcurrency), + "RimMind.Dialogue.Settings.GlobalConcurrency.Desc".Translate()); + s.globalConcurrency = (int)listing.Slider(s.globalConcurrency, 1f, 10f); + + listing.CheckboxLabeled("RimMind.Dialogue.Settings.EnableDialogueReply".Translate(), ref s.enableDialogueReply, + "RimMind.Dialogue.Settings.EnableDialogueReply.Desc".Translate()); + if (s.enableDialogueReply) + { + listing.LabelWithTooltip( + "RimMind.Dialogue.Settings.MaxDailyReplies".Translate(s.maxDailyReplyRounds), + "RimMind.Dialogue.Settings.MaxDailyReplies.Desc".Translate()); + s.maxDailyReplyRounds = (int)listing.Slider(s.maxDailyReplyRounds, 1f, 50f); + } + + listing.CheckboxLabeled("RimMind.Dialogue.Settings.StartDelay".Translate(), ref s.startDelayEnabled, + "RimMind.Dialogue.Settings.StartDelay.Desc".Translate()); + if (s.startDelayEnabled) + { + listing.Label(" " + "RimMind.Dialogue.Settings.StartDelayValue".Translate(s.startDelaySeconds)); + s.startDelaySeconds = (int)listing.Slider(s.startDelaySeconds, 1f, 60f); + } + + SettingsUIDrawer.DrawSectionHeader(listing, "RimMind.Dialogue.Settings.Section.Display".Translate()); + listing.CheckboxLabeled("RimMind.Dialogue.Settings.ShowNotification".Translate(), ref s.showThoughtNotification, + "RimMind.Dialogue.Settings.ShowNotification.Desc".Translate()); + listing.CheckboxLabeled("RimMind.Dialogue.Settings.ShowOverlay".Translate(), ref s.overlayEnabled, + "RimMind.Dialogue.Settings.ShowOverlay.Desc".Translate()); + listing.LabelWithTooltip( + "RimMind.Dialogue.Settings.OverlayOpacity".Translate($"{s.overlayOpacity:P0}"), + "RimMind.Dialogue.Settings.OverlayOpacity.Desc".Translate()); + s.overlayOpacity = listing.Slider(s.overlayOpacity, 0.1f, 1f); + listing.LabelWithTooltip( + "RimMind.Dialogue.Settings.OverlayMaxMessages".Translate(s.overlayMaxMessages), + "RimMind.Dialogue.Settings.OverlayMaxMessages.Desc".Translate()); + s.overlayMaxMessages = (int)listing.Slider(s.overlayMaxMessages, 3f, 20f); + }, + onReset: () => ResetToDefaults(s), + onDirtySave: () => s.Write()); } - private static float EstimateSettingsHeight() + private static void ResetToDefaults(RimMindDialogueSettings s) { - var s = Get(); - float h = 30f; - h += 24f; // Enable - h += 38f + 24f * 4; // Trigger sources header + 4 checkboxes - if (s.thoughtEnabled) - h += 24f + 32f; - h += 24f; // AutoMonologue - if (s.autoDialogueEnabled) - h += 24f + 32f; - h += 24f; // PlayerDialogueGizmo - h += 38f; // Behavior header - h += 24f + 32f; // MonologueCooldown - h += 24f + 32f; // MaxDailyDialogues - h += 24f + 32f; // GlobalConcurrency - h += 24f; // EnableDialogueReply - if (s.enableDialogueReply) - h += 24f + 32f; - h += 24f; // StartDelay - if (s.startDelayEnabled) - h += 24f + 32f; - h += 38f; // Display header - h += 24f; // ShowNotification - h += 24f; // ShowOverlay - h += 24f + 32f; // OverlayOpacity - h += 24f + 32f; // OverlayMaxMessages - return h + 40f; + s.enabled = true; + s.chitchatEnabled = true; + s.hediffEnabled = true; + s.levelUpEnabled = true; + s.thoughtEnabled = true; + s.autoDialogueEnabled = true; + s.playerDialogueEnabled = true; + s.moodChangeThreshold = 3f; + s.autoDialogueCooldownHours = 12; + s.maxDailyDialogueRounds = 6; + s.globalConcurrency = 3; + s.showThoughtNotification = false; + s.enableDialogueReply = true; + s.maxDailyReplyRounds = 12; + s.monologueCooldownTicks = 36000; + s.enableRecreationSocial = true; + s.recreationSocialChance = 0.35f; + s.enableDiningSocial = true; + s.diningSocialChance = 0.30f; + s.enableCoworkerSocial = true; + s.coworkerSocialChance = 0.25f; + s.startDelayEnabled = true; + s.startDelaySeconds = 10; + s.overlayEnabled = true; + s.overlayOpacity = 0.75f; + s.overlayMaxMessages = 8; + s.overlayX = 20f; + s.overlayY = 320f; + s.overlayW = 420f; + s.overlayH = 220f; } } } diff --git a/Source/Thoughts/ThoughtInjector.cs b/Source/Thoughts/ThoughtInjector.cs index 11ec43d..b282f74 100644 --- a/Source/Thoughts/ThoughtInjector.cs +++ b/Source/Thoughts/ThoughtInjector.cs @@ -2,6 +2,7 @@ using System.Collections.Concurrent; using System.Collections.Generic; using RimMind.Domain.ValueObjects; +using RimMind.Presentation.Api; using RimWorld; using UnityEngine; using Verse; @@ -80,11 +81,11 @@ public static string MapTagToLabel(string tag) string upperTag = tag.ToUpperInvariant(); if (LabelMap.TryGetValue(upperTag, out string? key) && !string.IsNullOrEmpty(key)) { - return key.CanTranslate() ? key.Translate().ToString() : tag; + return RimMindAPI.Text.TrOr(key!, tag); } if (tag.StartsWith("RimMind.", StringComparison.OrdinalIgnoreCase)) { - return tag.CanTranslate() ? tag.Translate().ToString() : tag; + return RimMindAPI.Text.TrOr(tag, tag); } return tag; } @@ -113,12 +114,10 @@ public static void InjectRelationDelta(Pawn pawn, Pawn recipient, float delta) thought.otherPawn = recipient; thought.opinionOffset = delta; - const string posKey = "RimMind.Dialogue.Relation.Positive"; - const string negKey = "RimMind.Dialogue.Relation.Negative"; string pawnName = recipient.Name.ToStringShort; thought.aiLabel = delta > 0 - ? (posKey.CanTranslate() ? posKey.Translate(pawnName).ToString() : $"pleasant conversation with {pawnName}") - : (negKey.CanTranslate() ? negKey.Translate(pawnName).ToString() : $"unpleasant conversation with {pawnName}"); + ? RimMindAPI.Text.TrOr("RimMind.Dialogue.Relation.Positive", "pleasant conversation with {0}", pawnName) + : RimMindAPI.Text.TrOr("RimMind.Dialogue.Relation.Negative", "unpleasant conversation with {0}", pawnName); pawn.needs?.mood?.thoughts?.memories?.TryGainMemory(thought); } diff --git a/Source/Thoughts/Thought_RimMindDialogue.cs b/Source/Thoughts/Thought_RimMindDialogue.cs index a8f37fe..f58db23 100644 --- a/Source/Thoughts/Thought_RimMindDialogue.cs +++ b/Source/Thoughts/Thought_RimMindDialogue.cs @@ -16,9 +16,9 @@ public override string LabelCap { if (aiLabel.NullOrEmpty()) return base.LabelCap; string text; - if (ThoughtInjector.TryGetLabelKey(aiLabel, out string? mappedKey) && !string.IsNullOrEmpty(mappedKey) && mappedKey.CanTranslate()) + if (ThoughtInjector.TryGetLabelKey(aiLabel, out string? mappedKey) && !string.IsNullOrEmpty(mappedKey)) { - text = mappedKey.Translate().ToString(); + text = RimMindAPI.Text.TrOr(mappedKey!, RimMindAPI.Thoughts.FormatCleanLabel(aiLabel)); } else { diff --git a/Source/UI/DialogueOverlay.cs b/Source/UI/DialogueOverlay.cs index 94e22fd..ffc3a58 100644 --- a/Source/UI/DialogueOverlay.cs +++ b/Source/UI/DialogueOverlay.cs @@ -4,6 +4,7 @@ using RimMind.Dialogue.Core; using RimMind.Dialogue.Settings; using RimMind.Dialogue.UI; +using RimMind.Presentation.Api; using RimWorld; using UnityEngine; using Verse; @@ -15,6 +16,7 @@ public class DialogueOverlay : MapComponent private bool _isDragging; private bool _isResizing; private bool _positionDirty; + private bool _wasHovered; private Vector2 _dragStartOffset; private Rect _windowRect; private bool _cacheDirty = true; @@ -35,9 +37,11 @@ public class DialogueOverlay : MapComponent private const int LiveColonistCacheIntervalTicks = 60; private const float OptionsBarHeight = 24f; private const float ResizeHandleSize = 24f; - private const float TextPadding = 4f; + private const float TextPadding = 6f; private const float MinWidth = 300f; private const float MinHeight = 100f; + private const float MinAutoFitHeight = 34f; + private const float MinHoveredHeight = 76f; private const float AlertsMargin = 245f; private const float TopColonistBarMargin = 96f; @@ -65,10 +69,55 @@ public override void MapComponentOnGUI() NormalizeWindowRect(); EnsureCachedEntries(settings); - HandleInput(); + EnsureLayoutMetrics(_windowRect.width - TextPadding * 2f); + + float maxAllowedRenderH = Mathf.Min( + _windowRect.height, + Mathf.Max(MinAutoFitHeight, Verse.UI.screenHeight - _windowRect.y)); + float idleHeight = DialogueOverlayLayout.ComputeRenderHeight( + _cachedLineHeights, + maxAllowedRenderH, + MinAutoFitHeight, + TextPadding * 2f, + forceExpandToMax: false); + float hoveredHeight = DialogueOverlayLayout.ComputeRenderHeight( + _cachedLineHeights, + Mathf.Max(maxAllowedRenderH, MinHoveredHeight), + MinHoveredHeight, + OptionsBarHeight + TextPadding * 2f, + forceExpandToMax: _isResizing); + + float hoverTestHeight = _cachedEntries.Count == 0 + ? MinHoveredHeight + : (_wasHovered ? hoveredHeight : idleHeight); + var hoverHitRect = new Rect(_windowRect.x, _windowRect.y, _windowRect.width, hoverTestHeight); + bool isMouseOver = Mouse.IsOver(hoverHitRect); + bool showChrome = isMouseOver || _isDragging || _isResizing; + _wasHovered = showChrome; + + var renderRect = new Rect( + _windowRect.x, + _windowRect.y, + _windowRect.width, + showChrome ? hoveredHeight : idleHeight); + + HandleInput(renderRect); NormalizeWindowRect(); - bool isMouseOver = Mouse.IsOver(_windowRect); + if (_isDragging || _isResizing) + { + EnsureLayoutMetrics(_windowRect.width - TextPadding * 2f); + float updatedMaxH = Mathf.Min( + _windowRect.height, + Mathf.Max(MinHoveredHeight, Verse.UI.screenHeight - _windowRect.y)); + float updatedHeight = DialogueOverlayLayout.ComputeRenderHeight( + _cachedLineHeights, + updatedMaxH, + MinHoveredHeight, + OptionsBarHeight + TextPadding * 2f, + forceExpandToMax: _isResizing); + renderRect = new Rect(_windowRect.x, _windowRect.y, _windowRect.width, updatedHeight); + } if (!DialogueOverlayLayout.ShouldRender(_cachedEntries.Count, isMouseOver, _isDragging, _isResizing)) { @@ -83,23 +132,23 @@ public override void MapComponentOnGUI() Color previousColor = GUI.color; GameFont previousFont = Text.Font; TextAnchor previousAnchor = Text.Anchor; - GUI.BeginGroup(_windowRect); + GUI.BeginGroup(renderRect); try { - var inRect = new Rect(Vector2.zero, _windowRect.size); + var inRect = new Rect(Vector2.zero, renderRect.size); Widgets.DrawBoxSolid(inRect, new Color(0.08f, 0.08f, 0.12f, settings.overlayOpacity)); - DrawMessages(inRect); + DrawMessages(inRect, reserveTopChrome: showChrome); - if (isMouseOver || _isDragging || _isResizing) + if (showChrome) { DrawOptionsBar(inRect); var resizeRect = new Rect(inRect.width - ResizeHandleSize, inRect.height - ResizeHandleSize, ResizeHandleSize, ResizeHandleSize); GUI.DrawTexture(resizeRect, TexUI.WinExpandWidget); - TooltipHandler.TipRegion(resizeRect, "RimMind.Dialogue.UI.Overlay.DragResize".Translate()); + TooltipHandler.TipRegion(resizeRect, RimMindAPI.Text.TrOr("RimMind.Dialogue.UI.Overlay.DragResize", "Drag to resize")); } } finally @@ -178,17 +227,14 @@ private void RefreshLiveColonistCache(int nowTick) _lastLiveColonistRefreshTick = nowTick; _liveColonistIds.Clear(); int liveHash = 0; - var spawned = map?.mapPawns?.FreeColonistsSpawned; - if (spawned != null) + var spawned = RimMindPawnLookup.GetSpawnedColonistsSafe(map); + for (int i = 0; i < spawned.Count; i++) { - for (int i = 0; i < spawned.Count; i++) + var p = spawned[i]; + if (p != null && RimMindPawnLookup.IsActiveSpawnedColonist(p)) { - var p = spawned[i]; - if (p != null && RimMind.Presentation.Api.RimMindPawnLookup.IsActiveSpawnedColonist(p)) - { - _liveColonistIds.Add(p.thingIDNumber); - liveHash = unchecked(liveHash * 397 ^ p.thingIDNumber); - } + _liveColonistIds.Add(p.thingIDNumber); + liveHash = unchecked(liveHash * 397 ^ p.thingIDNumber); } } @@ -199,29 +245,54 @@ private void RefreshLiveColonistCache(int nowTick) } } - private void DrawMessages(Rect inRect) + private void EnsureLayoutMetrics(float contentWidth) { - if (_cachedEntries.Count == 0) return; + if (_cachedEntries.Count == 0) + { + _cachedLayoutWidth = contentWidth; + return; + } - var contentRect = inRect.ContractedBy(TextPadding); - contentRect.yMin += OptionsBarHeight; + float safeWidth = Mathf.Max(20f, contentWidth); + if (Mathf.Abs(_cachedLayoutWidth - safeWidth) <= 0.5f) + return; + GameFont prevFont = Text.Font; Text.Font = GameFont.Small; - Text.Anchor = TextAnchor.UpperLeft; - - if (Mathf.Abs(_cachedLayoutWidth - contentRect.width) > 0.5f) + try { - float maxLabelWidth = Mathf.Max(60f, contentRect.width * 0.4f); + float maxLabelWidth = Mathf.Max(60f, safeWidth * 0.4f); for (int i = 0; i < _cachedEntries.Count; i++) { _cachedLabelWidths[i] = Mathf.Min(maxLabelWidth, Text.CalcSize(_cachedLabels[i]).x); - float replyWidth = Mathf.Max(1f, contentRect.width - _cachedLabelWidths[i] - TextPadding); + float replyWidth = Mathf.Max(1f, safeWidth - _cachedLabelWidths[i] - TextPadding); _cachedLineHeights[i] = Mathf.Max( Text.CalcHeight(_cachedLabels[i], Mathf.Max(1f, _cachedLabelWidths[i])), Text.CalcHeight(_cachedDisplayReplies[i], replyWidth)) + 2f; } - _cachedLayoutWidth = contentRect.width; + _cachedLayoutWidth = safeWidth; + } + finally + { + Text.Font = prevFont; } + } + + private void DrawMessages(Rect inRect, bool reserveTopChrome) + { + if (_cachedEntries.Count == 0) return; + + var contentRect = inRect.ContractedBy(TextPadding); + if (reserveTopChrome) + contentRect.yMin += OptionsBarHeight; + + if (contentRect.height <= 0f || contentRect.width <= 0f) + return; + + Text.Font = GameFont.Small; + Text.Anchor = TextAnchor.UpperLeft; + + EnsureLayoutMetrics(contentRect.width); int firstVisible = DialogueOverlayLayout.FindFirstVisibleIndex(_cachedLineHeights, contentRect.height); float y = contentRect.y; @@ -310,20 +381,20 @@ private void DrawOptionsBar(Rect inRect) } } - private void HandleInput() + private void HandleInput(Rect activeRect) { Event currentEvent = Event.current; if (currentEvent.type == EventType.MouseDown && currentEvent.button == 0) { var openBtnScreenRect = new Rect( - _windowRect.xMax - 60f, _windowRect.y + 2f, 56f, OptionsBarHeight - 4f); + activeRect.xMax - 60f, activeRect.y + 2f, 56f, OptionsBarHeight - 4f); var closeBtnScreenRect = new Rect( - _windowRect.xMax - 82f, _windowRect.y + 2f, 20f, OptionsBarHeight - 4f); + activeRect.xMax - 82f, activeRect.y + 2f, 20f, OptionsBarHeight - 4f); var resizeScreenRect = new Rect( - _windowRect.xMax - ResizeHandleSize, _windowRect.yMax - ResizeHandleSize, + activeRect.xMax - ResizeHandleSize, activeRect.yMax - ResizeHandleSize, ResizeHandleSize, ResizeHandleSize); if (resizeScreenRect.Contains(currentEvent.mousePosition)) @@ -334,7 +405,7 @@ private void HandleInput() else if (!openBtnScreenRect.Contains(currentEvent.mousePosition) && !closeBtnScreenRect.Contains(currentEvent.mousePosition)) { - var dragRect = new Rect(_windowRect.x, _windowRect.y, _windowRect.width, OptionsBarHeight); + var dragRect = new Rect(activeRect.x, activeRect.y, activeRect.width, OptionsBarHeight); if (dragRect.Contains(currentEvent.mousePosition)) { _isDragging = true; diff --git a/Source/UI/Window_Dialogue.cs b/Source/UI/Window_Dialogue.cs index d1cc797..8e774eb 100644 --- a/Source/UI/Window_Dialogue.cs +++ b/Source/UI/Window_Dialogue.cs @@ -1,222 +1,90 @@ -using System.Collections.Generic; -using System.Threading; -using RimMind.Domain.ValueObjects; using RimMind.Dialogue.Core; +using RimMind.Domain.ValueObjects; using RimMind.Presentation.Api; +using RimMind.Presentation.UI; using RimWorld; -using UnityEngine; using Verse; namespace RimMind.Dialogue.UI { - public class Window_Dialogue : Window + public class Window_Dialogue : RimMindChatWindowBase { private readonly Pawn _pawn; private readonly Pawn? _initiator; - private readonly List<(string role, string content)> _messages = new List<(string, string)>(); - private string _inputText = string.Empty; - private bool _isWaiting; - private bool _closed; - private readonly CancellationTokenSource _lifetime = new CancellationTokenSource(); - private Vector2 _scrollPosition; - private bool _autoScroll = true; - private const float InputHeight = 36f; - private const float SendButtonWidth = 80f; - private const float Padding = 8f; - private const float HeaderHeight = 28f; - private const float StatusHeight = 22f; - private const float ScrollbarWidth = 16f; - private static readonly Color UserColor = new Color(0.7f, 0.85f, 1f); - private static readonly Color PawnColor = new Color(1f, 0.95f, 0.8f); - private static readonly Color ChatBgColor = new Color(0.08f, 0.08f, 0.12f, 0.5f); - private static readonly Color StatusColor = new Color(1f, 1f, 0.5f); - - public override Vector2 InitialSize => new Vector2(480f, 540f); public Window_Dialogue(Pawn pawn, Pawn? initiator = null) : base() { _pawn = pawn; _initiator = initiator; RimMindDialogueService.SetActiveRecipient(pawn, initiator); - doCloseX = true; - closeOnAccept = false; - forcePause = false; - closeOnClickedOutside = false; - absorbInputAroundWindow = false; - draggable = true; } public override void PostClose() { - if (_closed) return; - _closed = true; - _isWaiting = false; - _lifetime.Cancel(); - _lifetime.Dispose(); - RimMindDialogueService.SetActiveRecipient(_pawn, null); + bool wasOpen = !IsClosed; base.PostClose(); - } - - public override void DoWindowContents(Rect inRect) - { - if (!RimMindPawnLookup.IsEligibleColonist(_pawn) || _pawn.Downed) - { - Close(); - return; - } - - Text.Font = GameFont.Small; - - float statusH = _isWaiting ? StatusHeight + Padding : 0f; - float chatHeight = inRect.height - HeaderHeight - statusH - InputHeight - Padding * 3; - float inputY = inRect.yMax - InputHeight; - - Rect headerRect = new Rect(inRect.x, inRect.y, inRect.width, HeaderHeight); - Rect chatRect = new Rect(inRect.x, inRect.y + HeaderHeight + Padding, inRect.width, chatHeight); - - GUI.color = new Color(0.8f, 0.95f, 1f); - Text.Anchor = TextAnchor.MiddleCenter; - string title = _initiator != null - ? "RimMind.Dialogue.UI.ChatTitleWithInitiator".Translate(_initiator.Name.ToStringShort, _pawn.Name.ToStringShort) - : "RimMind.Dialogue.UI.ChatTitle".Translate(_pawn.Name.ToStringShort); - Widgets.Label(headerRect, title); - Text.Anchor = TextAnchor.UpperLeft; - GUI.color = Color.white; - - Widgets.DrawBoxSolid(chatRect, ChatBgColor); - DrawChatHistory(chatRect); - - if (_isWaiting) - { - Rect statusRect = new Rect(inRect.x, inputY - StatusHeight - Padding, inRect.width, StatusHeight); - GUI.color = StatusColor; - Text.Anchor = TextAnchor.MiddleCenter; - Widgets.Label(statusRect, "RimMind.Dialogue.UI.Thinking".Translate()); - Text.Anchor = TextAnchor.UpperLeft; - GUI.color = Color.white; - } - - Rect inputRect = new Rect(inRect.x, inputY, inRect.width - SendButtonWidth - Padding, InputHeight); - Rect sendRect = new Rect(inRect.xMax - SendButtonWidth, inputY, SendButtonWidth, InputHeight); - - _inputText = Widgets.TextField(inputRect, _inputText); - - if (!_isWaiting) + if (wasOpen) { - if (Widgets.ButtonText(sendRect, "RimMind.Dialogue.UI.Send".Translate())) - { - if (!_inputText.NullOrEmpty()) - SendMessage(); - } - } - else - { - Widgets.ButtonText(sendRect, "RimMind.Dialogue.UI.Send".Translate()); - } - - if (!_isWaiting && Event.current.type == EventType.KeyDown - && Event.current.keyCode == KeyCode.Return && !_inputText.NullOrEmpty()) - { - SendMessage(); - Event.current.Use(); + RimMindDialogueService.SetActiveRecipient(_pawn, null); } } - private void DrawChatHistory(Rect rect) - { - if (_messages.Count == 0) return; - - float contentWidth = rect.width - ScrollbarWidth; - float contentHeight = CalcMessagesHeight(_messages, contentWidth - Padding * 2); - Rect viewRect = new Rect(0f, 0f, contentWidth, contentHeight); + protected override bool ValidateCanStayOpen() + => RimMindPawnLookup.IsEligibleColonist(_pawn) && !_pawn.Downed; - float prevScrollY = _scrollPosition.y; - Widgets.BeginScrollView(rect, ref _scrollPosition, viewRect); + protected override string GetTitle() => _initiator != null + ? RimMindAPI.Text.TrOr( + "RimMind.Dialogue.UI.ChatTitleWithInitiator", + "{0} & {1}", + _initiator.Name.ToStringShort, + _pawn.Name.ToStringShort) + : RimMindAPI.Text.TrOr( + "RimMind.Dialogue.UI.ChatTitle", + "Chat with {0}", + _pawn.Name.ToStringShort); - float y = 0f; - int index = 0; - foreach (var (role, content) in _messages) - { - string prefix = role == "user" - ? (_initiator != null - ? "RimMind.Dialogue.UI.PawnPrefix".Translate(_initiator.Name.ToStringShort) - : "RimMind.Dialogue.UI.PlayerPrefix".Translate()) - : "RimMind.Dialogue.UI.PawnPrefix".Translate(_pawn.Name.ToStringShort); - string line = prefix + content; - float lineH = Text.CalcHeight(line, contentWidth - Padding * 2) + Padding; - - if (index % 2 == 0) - { - Widgets.DrawBoxSolid(new Rect(0f, y, contentWidth, lineH), - new Color(1f, 1f, 1f, 0.03f)); - } + protected override string GetWaitingText() + => RimMindAPI.Text.TrOr("RimMind.Dialogue.UI.Thinking", "Thinking..."); - Color color = role == "user" ? UserColor : PawnColor; - GUI.color = color; - Widgets.Label(new Rect(Padding, y, contentWidth - Padding * 2, lineH), line); - GUI.color = Color.white; + protected override string GetSendButtonLabel() + => RimMindAPI.Text.TrOr("RimMind.Dialogue.UI.Send", "Send"); - y += lineH; - index++; - } - - Widgets.EndScrollView(); - - float maxScroll = Mathf.Max(0f, contentHeight - rect.height); - if (_autoScroll && maxScroll > 0f) - _scrollPosition.y = maxScroll; - - if (Mathf.Abs(prevScrollY - _scrollPosition.y) > 1f && _scrollPosition.y < maxScroll - 1f) - _autoScroll = false; - - if (_scrollPosition.y >= maxScroll - 2f) - _autoScroll = true; - } - - private float CalcMessagesHeight(List<(string role, string content)> messages, float width) + protected override string GetPrefixForRole(string role) { - float h = 0f; - foreach (var (role, content) in messages) + if (role == "user") { - string prefix = role == "user" - ? (_initiator != null - ? "RimMind.Dialogue.UI.PawnPrefix".Translate(_initiator.Name.ToStringShort) - : "RimMind.Dialogue.UI.PlayerPrefix".Translate()) - : "RimMind.Dialogue.UI.PawnPrefix".Translate(_pawn.Name.ToStringShort); - h += Text.CalcHeight(prefix + content, width) + Padding; + return _initiator != null + ? RimMindAPI.Text.TrOr("RimMind.Dialogue.UI.PawnPrefix", "{0}: ", _initiator.Name.ToStringShort) + : RimMindAPI.Text.TrOr("RimMind.Dialogue.UI.PlayerPrefix", "You: "); } - return h + Padding; + return RimMindAPI.Text.TrOr("RimMind.Dialogue.UI.PawnPrefix", "{0}: ", _pawn.Name.ToStringShort); } - private void SendMessage() + protected override void OnSubmitUserMessage(string trimmedInput) { - if (_closed) return; - string message = _inputText.Trim(); - _inputText = string.Empty; - _isWaiting = true; - _autoScroll = true; + if (IsClosed) return; + SetWaiting(true); + AppendMessage("user", trimmedInput); - // 本地记录用户消息用于显示 - _messages.Add(("user", message)); - - DialogueService.RequestReply(_pawn, message, _initiator, + DialogueService.RequestReply(_pawn, trimmedInput, _initiator, onReply: reply => { - if (_closed) return; - _messages.Add(("assistant", reply)); - _isWaiting = false; - _autoScroll = true; + if (IsClosed) return; + PostReply("assistant", reply); }, onError: error => { - if (_closed) return; - _isWaiting = false; - _autoScroll = true; + if (IsClosed) return; + SetWaiting(false); RimMindErrors.Warn($"[RimMind-Dialogue] Player dialogue error: {error}"); - Messages.Message( - "RimMind.Dialogue.UI.FloatMenu.RequestFailed".Translate(_pawn.Name.ToStringShort), + Verse.Messages.Message( + RimMindAPI.Text.TrOr( + "RimMind.Dialogue.UI.FloatMenu.RequestFailed", + "Dialogue request failed for {0}", + _pawn.Name.ToStringShort), MessageTypeDefOf.RejectInput, false); - }, cancellationToken: _lifetime.Token); + }, + cancellationToken: LifetimeToken); } } } diff --git a/Source/UI/Window_DialogueLog.cs b/Source/UI/Window_DialogueLog.cs index 3b963da..6bc651b 100644 --- a/Source/UI/Window_DialogueLog.cs +++ b/Source/UI/Window_DialogueLog.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using RimMind.Dialogue.Core; +using RimMind.Presentation.Api; using UnityEngine; using Verse; @@ -17,13 +18,13 @@ public class Window_DialogueLog : Window private const float Padding = 6f; private const float TabHeight = 28f; - private static readonly (DialogueCategory cat, string key)[] CategoryKeys = new[] + private static readonly (DialogueCategory cat, string key, string fallback)[] CategoryKeys = new[] { - (DialogueCategory.ColonistMonologue, "RimMind.Dialogue.UI.Log.ColonistMonologue"), - (DialogueCategory.ColonistDialogue, "RimMind.Dialogue.UI.Log.ColonistDialogue"), - (DialogueCategory.PlayerDialogue, "RimMind.Dialogue.UI.Log.PlayerDialogue"), - (DialogueCategory.NonColonistMonologue, "RimMind.Dialogue.UI.Log.NonColonistMonologue"), - (DialogueCategory.NonColonistDialogue, "RimMind.Dialogue.UI.Log.NonColonistDialogue"), + (DialogueCategory.ColonistMonologue, "RimMind.Dialogue.UI.Log.ColonistMonologue", "Colonist Monologue"), + (DialogueCategory.ColonistDialogue, "RimMind.Dialogue.UI.Log.ColonistDialogue", "Colonist Dialogue"), + (DialogueCategory.PlayerDialogue, "RimMind.Dialogue.UI.Log.PlayerDialogue", "Player Dialogue"), + (DialogueCategory.NonColonistMonologue, "RimMind.Dialogue.UI.Log.NonColonistMonologue", "Non-Colonist Monologue"), + (DialogueCategory.NonColonistDialogue, "RimMind.Dialogue.UI.Log.NonColonistDialogue", "Non-Colonist Dialogue"), }; public override Vector2 InitialSize => new Vector2(720f, 560f); @@ -64,9 +65,9 @@ public override void DoWindowContents(Rect inRect) private void DrawCategoryBar(Rect rect) { float x = rect.x; - foreach (var (cat, key) in CategoryKeys) + foreach (var (cat, key, fallback) in CategoryKeys) { - string label = key.Translate(); + string label = RimMindAPI.Text.TrOr(key, fallback); float width = Text.CalcSize(label).x + 20f; var btnRect = new Rect(x, rect.y, width, rect.height); @@ -353,7 +354,7 @@ private static string FormatEntry(DialogueLogEntry entry) private static string TranslateTrigger(string triggerKey) { if (RimMindDialogueService.RegisteredTriggerLabels.TryGetValue(triggerKey, out var labelKey)) - return labelKey.CanTranslate() ? (string)labelKey.Translate() : labelKey; + return RimMindAPI.Text.TrOr(labelKey, labelKey); return triggerKey switch { diff --git a/Tests/Contracts/DialoguePipelineContracts.cs b/Tests/Contracts/DialoguePipelineContracts.cs index 0570d2f..57a12ec 100644 --- a/Tests/Contracts/DialoguePipelineContracts.cs +++ b/Tests/Contracts/DialoguePipelineContracts.cs @@ -213,6 +213,7 @@ private static void AssertPreserved(string? raw) string? description = "old description"; int relationDelta = 4; +#pragma warning disable CS0618 ResponseJsonParser.TryParseResponseJson( raw, false, @@ -220,6 +221,7 @@ private static void AssertPreserved(string? raw) ref tag, ref description, ref relationDelta); +#pragma warning restore CS0618 Assert.Equal("before", reply); Assert.Equal("OLD", tag); diff --git a/Tests/Contracts/DialogueVisualAndCoreAdoptionContracts.cs b/Tests/Contracts/DialogueVisualAndCoreAdoptionContracts.cs new file mode 100644 index 0000000..fd4e93d --- /dev/null +++ b/Tests/Contracts/DialogueVisualAndCoreAdoptionContracts.cs @@ -0,0 +1,151 @@ +using System; +using RimMind.Dialogue.Core; +using RimMind.Dialogue.Settings; +using RimMind.Presentation.Api; +using RimWorld; +using UnityEngine; +using Verse; +using Xunit; + +namespace RimMind.Dialogue.Tests.Contracts +{ + public sealed class DialogueVisualAndCoreAdoptionContracts + { + [Fact] + public void DialogueOverlayLayout_ComputeRenderHeight_ShrinkWrapsToVisibleMessages() + { + // 3 short lines (~22px each) with maxHeight=220 must shrink-wrap tightly instead of leaving 140px void + float idleThreeLines = DialogueOverlayLayout.ComputeRenderHeight( + new[] { 22f, 22f, 22f }, + maxHeight: 220f, + minHeight: 34f, + chromeHeight: 12f, + forceExpandToMax: false); + Assert.Equal(78f, idleThreeLines); + + // Hovering adds the options bar (24px) and never shrinks below idle height (zero hover flicker) + float hoveredThreeLines = DialogueOverlayLayout.ComputeRenderHeight( + new[] { 22f, 22f, 22f }, + maxHeight: 220f, + minHeight: 76f, + chromeHeight: 36f, + forceExpandToMax: false); + Assert.Equal(102f, hoveredThreeLines); + Assert.True(hoveredThreeLines >= idleThreeLines); + + // Overflowing content clamps cleanly to user's max height cap + float overflowing = DialogueOverlayLayout.ComputeRenderHeight( + new[] { 30f, 30f, 30f, 30f, 30f, 30f, 30f, 30f }, + maxHeight: 220f, + minHeight: 34f, + chromeHeight: 12f, + forceExpandToMax: false); + Assert.Equal(220f, overflowing); + + // Empty list clamps to minHeight unless resizing forces expansion to maxHeight + Assert.Equal(34f, DialogueOverlayLayout.ComputeRenderHeight( + Array.Empty(), + maxHeight: 220f, + minHeight: 34f, + chromeHeight: 12f, + forceExpandToMax: false)); + Assert.Equal(220f, DialogueOverlayLayout.ComputeRenderHeight( + new[] { 22f }, + maxHeight: 220f, + minHeight: 76f, + chromeHeight: 36f, + forceExpandToMax: true)); + } + + [Fact] + public void OverheadSpeechMote_SpawnsAbovePawnHeadAndNameplate_AndScalesWithLineCount() + { + var basePos = new Vector3(10f, 0f, 20f); + + Vector3 singleLinePos = RimMindDialogueService.ComputeOverheadMotePosition(basePos, "Short line."); + Assert.Equal(10f, singleLinePos.x); + Assert.Equal(0f, singleLinePos.y); + Assert.True(singleLinePos.z >= basePos.z + 1.35f); + + Vector3 twoLinePos = RimMindDialogueService.ComputeOverheadMotePosition(basePos, "First line\nSecond line"); + Assert.True(twoLinePos.z > singleLinePos.z); + Assert.Equal(basePos.z + 1.60f, twoLinePos.z, 3); + + Vector3 manyLinesPos = RimMindDialogueService.ComputeOverheadMotePosition(basePos, "1\n2\n3\n4\n5\n6"); + Assert.Equal( + basePos.z + RimMindDialogueService.OverheadMoteBaseZOffset + RimMindDialogueService.OverheadMoteMaxExtraZOffset, + manyLinesPos.z, + 3); + + // Verify DisplayInteraction throws the mote at the elevated Z position + MoteMaker.Thrown.Clear(); + var map = new Map(); + var pawn = new Pawn { thingIDNumber = 77, IsColonist = true, Faction = Faction.OfPlayer, Map = map, Spawned = true }; + RimMindDialogueService.DisplayInteraction(pawn, null, "Can you shut up? I'm losing my mind."); + var thrown = Assert.Single(MoteMaker.Thrown); + Assert.Same(map, thrown.Map); + Assert.True(thrown.Position.z >= pawn.DrawPos.z + RimMindDialogueService.OverheadMoteBaseZOffset); + Assert.Contains("\n", thrown.Text); + } + + [Fact] + public void FormatOverheadMoteText_DelegatesCjkAwareWrappingToCore() + { + // Wide CJK characters count as 2 display units in Core MoteTextFormatter, so 20 Chinese chars wrap cleanly + string cjk = "今天外面冷得要命,我们得赶紧把木头搬进棚子里取暖。"; + string wrappedCjk = DialogueTextSanitizer.FormatOverheadMoteText(cjk, maxLineLength: 26, maxTotalLength: 52); + Assert.Contains("\n", wrappedCjk); + + string en = "Can you shut up? I'm losing my mind right now."; + string wrappedEn = DialogueTextSanitizer.FormatOverheadMoteText(en, maxLineLength: 26, maxTotalLength: 52); + Assert.Contains("\n", wrappedEn); + } + + [Fact] + public void DialogueToolParser_HandlesThinkingBlocksAndTruncatedJsonViaCore() + { + string raw = "Consider mood and frostbite.\n```json\n{\"name\":\"express_dialogue\",\"arguments\":{\"speech\":\"Too cold out here.\",\"thought_tag\":\"STRESSED\"}}\n```"; + Assert.True(DialogueToolParser.TryParse(raw, isMonologue: true, out var output)); + Assert.Equal("Too cold out here.", output.Speech); + Assert.Equal("STRESSED", output.ThoughtTag); + Assert.Equal(0, output.RelationDelta); + + string truncated = "{\"speech\":\"Hang in there\",\"thought_tag\":\"ENCOURAGED\""; + Assert.True(DialogueToolParser.TryParse(truncated, isMonologue: true, out var repaired)); + Assert.Equal("Hang in there", repaired.Speech); + Assert.Equal("ENCOURAGED", repaired.ThoughtTag); + } + + [Fact] + public void RimMindDialogueSettings_DrawSettingsContent_OnlyWritesWhenDirty() + { + var settings = new RimMindDialogueSettings(); + settings.WriteCount = 0; + + GUI.changed = false; + RimMindDialogueSettings.DrawSettingsContent(new Rect(0, 0, 600, 500)); + Assert.Equal(0, settings.WriteCount); + + // Simulate a control mutating GUI.changed during draw via onDirtySave contract + var prev = GUI.changed; + try + { + GUI.changed = false; + RimMind.Presentation.UI.SettingsUIDrawer.DrawScrollableSettingsPage( + new Rect(0, 0, 600, 500), + ref scrollPos, + ref measuredH, + _ => { GUI.changed = true; }, + onDirtySave: () => settings.Write()); + Assert.Equal(1, settings.WriteCount); + } + finally + { + GUI.changed = prev; + } + } + + private static Vector2 scrollPos; + private static float measuredH = 500f; + } +} diff --git a/Tests/DialogueBoundaryStubs.cs b/Tests/DialogueBoundaryStubs.cs index 0369bdd..b7e522b 100644 --- a/Tests/DialogueBoundaryStubs.cs +++ b/Tests/DialogueBoundaryStubs.cs @@ -1,7 +1,13 @@ using System; +using System.Collections.Concurrent; using System.Collections.Generic; +using System.Threading; +using Newtonsoft.Json.Linq; using RimMind.Application.Common.Models.Memory; +using RimMind.Application.Features.Context; +using RimMind.Application.Features.Json; using RimMind.Application.Features.Llm; +using RimMind.Application.Features.Prompt; using RimMind.Domain.Llm; using RimMind.Domain.ValueObjects; using UnityEngine; @@ -29,10 +35,42 @@ public static void PublishPerception(int pawnId, string type, string text, float => Perceptions.Add((pawnId, text)); public static class Settings { + public static bool IsConfigured() => Configured; public static float ActivityFrequencyScale { get; set; } = 1.0f; public static int ScaleCooldown(int baseCooldownTicks, int minFloorTicks = 0) => RimMind.Application.Common.Helpers.ActivityCooldownScaler.Scale(baseCooldownTicks, ActivityFrequencyScale, minFloorTicks); } + public static class Ext + { + public static bool ShouldSkipDialogue(Pawn pawn, string type) => Skip; + public static bool ShouldSkipFloatMenu() => Skip; + } + public static class Text + { + public static string TrOr(string key, string fallback, params object[] args) + => RimMindText.TrOr(key, fallback, args); + public static string Tr(string key, params object[] args) + => RimMindText.Tr(key, args); + public static string WrapForMote(string? text, int maxCharsPerLine = MoteTextFormatter.DefaultMaxCharsPerLine) + => MoteTextFormatter.WrapForMote(text, maxCharsPerLine); + } + public static class Json + { + public static string StripThinkingAndCodeFences(string? raw) + => LlmPayloadParser.StripThinkingAndCodeFences(raw); + public static string? ExtractJsonPayload(string? raw) + => LlmPayloadParser.ExtractJsonPayload(raw); + public static bool TryParseJObjectWithRepair(string? raw, out JObject? obj) + => LlmPayloadParser.TryParseJObjectWithRepair(raw, out obj); + public static bool TryDeserializeWithRepair(string? raw, out T? value) where T : class + => LlmPayloadParser.TryDeserializeWithRepair(raw, out value); + public static IReadOnlyList ParsePseudoFunctionCalls(string? raw) + => LlmPayloadParser.ParsePseudoFunctionCalls(raw); + public static string? TryRepairJson(string input) + => JsonRepairer.TryRepair(input); + public static string? TryRepairTruncatedJson(string input) + => JsonRepairer.TryRepairTruncatedJson(input); + } public static class Thoughts { public static string FormatCleanLabel(string rawTagOrKey, string defaultPrefixToStrip = "RimMind.") @@ -68,6 +106,8 @@ public static class Bus public static void RegisterEventType(string name) where T : RimMind.Domain.Events.AgentBusEvent => RimMind.Application.Features.AgentBus.AgentBusImpl.RegisterKnownEventType(name, typeof(T)); public static void PublishOnMainThread(T evt) where T : RimMind.Domain.Events.AgentBusEvent { } + public static void PublishPerception(int pawnId, string type, string text, float salience = 0.5f) + => Perceptions.Add((pawnId, text)); } public static class MainThreadSnapshot { @@ -89,6 +129,8 @@ public static class Context { public static string ScenarioDialogue => RimMind.Application.Common.Models.Context.ScenarioIds.Dialogue; public static TestContextRegistry ContextKeys { get; } = new(); + public static void RegisterScenario(ScenarioDescriptor descriptor) + => ScenarioRegistry.Register(descriptor); } public sealed class TestContextRegistry { @@ -181,12 +223,15 @@ public static void Message(string text, Pawn pawn, RimWorld.MessageTypeDef type, } public static class MoteMaker { - public static void ThrowText(Vector3 position, Map map, string text, Color color, float duration) { } + public static readonly List<(Vector3 Position, Map Map, string Text)> Thrown = new(); + public static void ThrowText(Vector3 position, Map map, string text, Color color, float duration) + => Thrown.Add((position, map, text)); } public class ModSettings { + public int WriteCount; public virtual void ExposeData() { } - public void Write() { } + public void Write() => WriteCount++; } public class ThingComp { @@ -208,7 +253,7 @@ public class Command_Action : Gizmo } public class Window { - public bool doCloseX, closeOnAccept, forcePause, closeOnClickedOutside, + public bool doCloseButton, doCloseX, closeOnAccept, forcePause, closeOnClickedOutside, absorbInputAroundWindow, draggable; public virtual Vector2 InitialSize => default; public virtual void PostClose() { } @@ -283,7 +328,12 @@ public struct Vector2 public Vector2(float x, float y) { this.x = x; this.y = y; } public static Vector2 zero => default; } - public struct Vector3 { } + public struct Vector3 + { + public float x, y, z; + public Vector3(float x, float y, float z) { this.x = x; this.y = y; this.z = z; } + public static Vector3 operator +(Vector3 a, Vector3 b) => new(a.x + b.x, a.y + b.y, a.z + b.z); + } public struct Rect { public float x, y, width, height; @@ -301,7 +351,7 @@ public Color(float r, float g, float b, float a = 1) { } public class Texture2D { } public enum TextAnchor { MiddleCenter, UpperLeft } public enum EventType { KeyDown, Repaint } - public enum KeyCode { Return } + public enum KeyCode { Return, KeypadEnter } public class Event { public static Event current = new() { type = EventType.Repaint }; @@ -309,11 +359,115 @@ public class Event public KeyCode keyCode; public void Use() { } } - public static class GUI { public static Color color; } + public static class GUI { public static Color color; public static bool enabled = true; public static bool changed; } } namespace RimMind.Presentation.UI { + public readonly struct ChatWindowMessage + { + public ChatWindowMessage(string role, string content, string? senderPrefix = null) + { + Role = role ?? string.Empty; + Content = content ?? string.Empty; + SenderPrefix = senderPrefix; + } + public string Role { get; } + public string Content { get; } + public string? SenderPrefix { get; } + } + + public abstract class RimMindChatWindowBase : Window + { + private readonly List _messages = new(); + private readonly ConcurrentQueue _mainThreadUpdates = new(); + private readonly CancellationTokenSource _lifetime = new(); + private string _inputText = string.Empty; + private bool _isWaiting; + private bool _closed; + + protected RimMindChatWindowBase() + { + doCloseButton = false; + doCloseX = true; + closeOnAccept = false; + forcePause = false; + closeOnClickedOutside = false; + absorbInputAroundWindow = false; + draggable = true; + } + + public override Vector2 InitialSize => new Vector2(480f, 540f); + protected CancellationToken LifetimeToken => _lifetime.Token; + protected bool IsClosed => _closed; + protected bool IsWaiting => _isWaiting; + protected IReadOnlyList Messages => _messages; + + protected virtual Color HeaderColor => new Color(0.8f, 0.95f, 1f); + protected abstract string GetTitle(); + protected abstract string GetWaitingText(); + protected abstract string GetSendButtonLabel(); + protected abstract string GetPrefixForRole(string role); + protected abstract void OnSubmitUserMessage(string trimmedInput); + protected virtual bool ValidateCanStayOpen() => true; + protected virtual void OnMessageAppended(ChatWindowMessage message) { } + + protected void AppendMessage(string role, string content, string? senderPrefix = null, bool notifyHook = true) + { + if (string.IsNullOrEmpty(content)) return; + var msg = new ChatWindowMessage(role, content, senderPrefix); + _messages.Add(msg); + if (notifyHook) OnMessageAppended(msg); + } + + protected void PostReply(string role, string content, bool clearWaiting = true, string? senderPrefix = null) + { + if (_closed) return; + _mainThreadUpdates.Enqueue(() => + { + if (_closed) return; + if (clearWaiting) _isWaiting = false; + if (!string.IsNullOrEmpty(content)) AppendMessage(role, content, senderPrefix); + }); + } + + protected void SetWaiting(bool waiting) => _isWaiting = waiting; + + public override void PostClose() + { + if (!_closed) + { + _closed = true; + _isWaiting = false; + try { _lifetime.Cancel(); } catch (ObjectDisposedException) { } + try { _lifetime.Dispose(); } catch (ObjectDisposedException) { } + } + base.PostClose(); + } + + public override void DoWindowContents(Rect inRect) + { + if (!ValidateCanStayOpen()) + { + Close(); + return; + } + while (_mainThreadUpdates.TryDequeue(out var update)) + update?.Invoke(); + + Widgets.Label(inRect, GetTitle()); + if (_isWaiting) Widgets.Label(inRect, GetWaitingText()); + _inputText = Widgets.TextField(inRect, _inputText ?? string.Empty); + bool sendClicked = Widgets.ButtonText(inRect, GetSendButtonLabel()); + if (sendClicked && !_isWaiting && !string.IsNullOrWhiteSpace(_inputText)) + { + string trimmed = _inputText.Trim(); + _inputText = string.Empty; + OnSubmitUserMessage(trimmed); + } + } + } + public static class SettingsUIDrawer { public static Rect SplitContentArea(Rect rect) => rect; @@ -321,5 +475,23 @@ public static class SettingsUIDrawer public static void DrawSectionHeader(Listing_Standard listing, string text) { } public static void DrawBottomBar(Rect rect, Action reset) { } public static void LabelWithTooltip(this Verse.Listing_Standard listing, string label, string? tooltip, UnityEngine.Color? textColor = null) { } + public static void DrawScrollableSettingsPage( + Rect inRect, + ref Vector2 scrollPos, + ref float measuredHeight, + Action drawContent, + Action? onReset = null, + Action? onDirtySave = null) + { + bool prevChanged = GUI.changed; + GUI.changed = false; + var listing = new Listing_Standard(); + listing.Begin(inRect); + drawContent(listing); + listing.End(); + bool dirty = GUI.changed; + GUI.changed = prevChanged || dirty; + if (dirty) onDirtySave?.Invoke(); + } } } diff --git a/Tests/RimMindDialogue.Tests.csproj b/Tests/RimMindDialogue.Tests.csproj index d752b94..750d783 100644 --- a/Tests/RimMindDialogue.Tests.csproj +++ b/Tests/RimMindDialogue.Tests.csproj @@ -14,7 +14,7 @@ - +