Remove FluentBundle.Arguments helper method.

This commit is contained in:
Paul Chote
2024-10-02 22:40:05 +01:00
committed by Gustas
parent b29b685058
commit d6285affec
71 changed files with 273 additions and 283 deletions

View File

@@ -112,15 +112,15 @@ namespace OpenRA
} }
} }
public string GetString(string key, IDictionary<string, object> arguments = null) public string GetString(string key, object[] args = null)
{ {
if (!TryGetString(key, out var message, arguments)) if (!TryGetString(key, out var message, args))
message = key; message = key;
return message; return message;
} }
public bool TryGetString(string key, out string value, IDictionary<string, object> arguments = null) public bool TryGetString(string key, out string value, object[] args = null)
{ {
if (key == null) if (key == null)
throw new ArgumentNullException(nameof(key)); throw new ArgumentNullException(nameof(key));
@@ -133,12 +133,29 @@ namespace OpenRA
return false; return false;
} }
var fluentArguments = new Dictionary<string, IFluentType>(); Dictionary<string, IFluentType> fluentArgs = null;
if (arguments != null) if (args != null)
foreach (var (k, v) in arguments) {
fluentArguments.Add(k, v.ToFluentType()); if (args.Length % 2 != 0)
throw new ArgumentException("Expected a comma separated list of name, value arguments " +
"but the number of arguments is not a multiple of two", nameof(args));
var result = bundle.TryGetAttrMessage(key, fluentArguments, out var errors, out value); fluentArgs = new Dictionary<string, IFluentType>();
for (var i = 0; i < args.Length; i += 2)
{
var argKey = args[i] as string;
if (string.IsNullOrEmpty(argKey))
throw new ArgumentException($"Expected the argument at index {i} to be a non-empty string", nameof(args));
var argValue = args[i + 1];
if (argValue == null)
throw new ArgumentNullException(nameof(args), $"Expected the argument at index {i + 1} to be a non-null value");
fluentArgs.Add(argKey, argValue.ToFluentType());
}
}
var result = bundle.TryGetAttrMessage(key, fluentArgs, out var errors, out value);
foreach (var error in errors) foreach (var error in errors)
Log.Write("debug", $"FluentBundle of {key}: {error}"); Log.Write("debug", $"FluentBundle of {key}: {error}");
@@ -157,31 +174,5 @@ namespace OpenRA
{ {
return bundle.HasAttrMessage(key); return bundle.HasAttrMessage(key);
} }
// Adapted from Fluent.Net.SimpleExample.TranslationService by Mark Weaver
public static Dictionary<string, object> Arguments(string name, object value, params object[] args)
{
if (args.Length % 2 != 0)
throw new ArgumentException("Expected a comma separated list of name, value arguments"
+ " but the number of arguments is not a multiple of two", nameof(args));
var argumentDictionary = new Dictionary<string, object> { { name, value } };
for (var i = 0; i < args.Length; i += 2)
{
name = args[i] as string;
if (string.IsNullOrEmpty(name))
throw new ArgumentException($"Expected the argument at index {i} to be a non-empty string",
nameof(args));
value = args[i + 1];
if (value == null)
throw new ArgumentNullException(nameof(args), $"Expected the argument at index {i + 1} to be a non-null value");
argumentDictionary.Add(name, value);
}
return argumentDictionary;
}
} }
} }

View File

@@ -9,7 +9,6 @@
*/ */
#endregion #endregion
using System.Collections.Generic;
using OpenRA.FileSystem; using OpenRA.FileSystem;
namespace OpenRA namespace OpenRA
@@ -32,7 +31,7 @@ namespace OpenRA
} }
} }
public static string GetString(string key, IDictionary<string, object> args = null) public static string GetString(string key, params object[] args)
{ {
lock (SyncObject) lock (SyncObject)
{ {
@@ -48,7 +47,7 @@ namespace OpenRA
} }
} }
public static bool TryGetString(string key, out string message, IDictionary<string, object> args = null) public static bool TryGetString(string key, out string message, params object[] args)
{ {
lock (SyncObject) lock (SyncObject)
{ {
@@ -65,7 +64,7 @@ namespace OpenRA
} }
/// <summary>Should only be used by <see cref="MapPreview"/>.</summary> /// <summary>Should only be used by <see cref="MapPreview"/>.</summary>
internal static bool TryGetModString(string key, out string message, IDictionary<string, object> args = null) internal static bool TryGetModString(string key, out string message, params object[] args)
{ {
lock (SyncObject) lock (SyncObject)
{ {

View File

@@ -595,7 +595,7 @@ namespace OpenRA
Log.Write("debug", "Taking screenshot " + path); Log.Write("debug", "Taking screenshot " + path);
Renderer.SaveScreenshot(path); Renderer.SaveScreenshot(path);
TextNotificationsManager.Debug(FluentProvider.GetString(SavedScreenshot, FluentBundle.Arguments("filename", filename))); TextNotificationsManager.Debug(FluentProvider.GetString(SavedScreenshot, "filename", filename));
} }
} }

View File

@@ -153,9 +153,8 @@ namespace OpenRA
{ {
var number = Players.Where(p => p.BotType == player.BotType).ToList().IndexOf(player) + 1; var number = Players.Where(p => p.BotType == player.BotType).ToList().IndexOf(player) + 1;
return FluentProvider.GetString(EnumeratedBotName, return FluentProvider.GetString(EnumeratedBotName,
FluentBundle.Arguments(
"name", FluentProvider.GetString(player.Name), "name", FluentProvider.GetString(player.Name),
"number", number)); "number", number);
} }
return player.Name; return player.Name;

View File

@@ -227,7 +227,7 @@ namespace OpenRA
/// Functionality mirrors <see cref="FluentProvider.GetString"/>, except instead of using /// Functionality mirrors <see cref="FluentProvider.GetString"/>, except instead of using
/// loaded <see cref="Map"/>'s fluent bundle as backup, we use this <see cref="MapPreview"/>'s. /// loaded <see cref="Map"/>'s fluent bundle as backup, we use this <see cref="MapPreview"/>'s.
/// </summary> /// </summary>
public string GetLocalisedString(string key, IDictionary<string, object> args = null) public string GetLocalisedString(string key, object[] args = null)
{ {
// PERF: instead of loading mod level strings per each MapPreview, reuse the already loaded one in FluentProvider. // PERF: instead of loading mod level strings per each MapPreview, reuse the already loaded one in FluentProvider.
if (FluentProvider.TryGetModString(key, out var message, args)) if (FluentProvider.TryGetModString(key, out var message, args))

View File

@@ -9,8 +9,8 @@
*/ */
#endregion #endregion
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using Linguini.Shared.Types.Bundle; using Linguini.Shared.Types.Bundle;
namespace OpenRA.Network namespace OpenRA.Network
@@ -55,30 +55,31 @@ namespace OpenRA.Network
public readonly string Key = string.Empty; public readonly string Key = string.Empty;
[FieldLoader.LoadUsing(nameof(LoadArguments))] [FieldLoader.LoadUsing(nameof(LoadArguments))]
public readonly Dictionary<string, object> Arguments; public readonly object[] Arguments;
static object LoadArguments(MiniYaml yaml) static object LoadArguments(MiniYaml yaml)
{ {
var arguments = new Dictionary<string, object>(); var arguments = new List<object>();
var argumentsNode = yaml.NodeWithKeyOrDefault("Arguments"); var argumentsNode = yaml.NodeWithKeyOrDefault("Arguments");
if (argumentsNode != null) if (argumentsNode != null)
{ {
foreach (var argumentNode in argumentsNode.Value.Nodes) foreach (var argumentNode in argumentsNode.Value.Nodes)
{ {
var argument = FieldLoader.Load<FluentArgument>(argumentNode.Value); var argument = FieldLoader.Load<FluentArgument>(argumentNode.Value);
arguments.Add(argument.Key);
if (argument.Type == FluentArgument.FluentArgumentType.Number) if (argument.Type == FluentArgument.FluentArgumentType.Number)
{ {
if (!double.TryParse(argument.Value, out var number)) if (!double.TryParse(argument.Value, out var number))
Log.Write("debug", $"Failed to parse {argument.Value}"); Log.Write("debug", $"Failed to parse {argument.Value}");
arguments.Add(argument.Key, number); arguments.Add(number);
} }
else else
arguments.Add(argument.Key, argument.Value); arguments.Add(argument.Value);
} }
} }
return arguments; return arguments.ToArray();
} }
public FluentMessage(MiniYaml yaml) public FluentMessage(MiniYaml yaml)
@@ -87,21 +88,31 @@ namespace OpenRA.Network
FieldLoader.Load(this, yaml); FieldLoader.Load(this, yaml);
} }
public static string Serialize(string key, Dictionary<string, object> arguments = null) public static string Serialize(string key, object[] args)
{ {
var root = new List<MiniYamlNode> var root = new List<MiniYamlNode>
{ {
new("Protocol", ProtocolVersion.ToStringInvariant()), new("Protocol", ProtocolVersion.ToStringInvariant()),
new("Key", key) new("Key", key),
}; };
if (arguments != null) if (args != null)
{ {
var argumentsNode = new MiniYaml("", arguments var nodes = new List<MiniYamlNode>();
.Select(a => new FluentArgument(a.Key, a.Value)) for (var i = 0; i < args.Length; i += 2)
.Select((argument, i) => new MiniYamlNode("Argument@" + i, FieldSaver.Save(argument)))); {
var argKey = args[i] as string;
if (string.IsNullOrEmpty(argKey))
throw new ArgumentException($"Expected the argument at index {i} to be a non-empty string", nameof(args));
root.Add(new MiniYamlNode("Arguments", argumentsNode)); var argValue = args[i + 1];
if (argValue == null)
throw new ArgumentNullException(nameof(args), $"Expected the argument at index {i + 1} to be a non-null value");
nodes.Add(new MiniYamlNode($"Argument@{i / 2}", FieldSaver.Save(new FluentArgument(argKey, argValue))));
}
root.Add(new MiniYamlNode("Arguments", new MiniYaml("", nodes)));
} }
return new MiniYaml("", root) return new MiniYaml("", root)

View File

@@ -91,7 +91,7 @@ namespace OpenRA.Network
World.OutOfSync(); World.OutOfSync();
IsOutOfSync = true; IsOutOfSync = true;
TextNotificationsManager.AddSystemLine(DesyncCompareLogs, FluentBundle.Arguments("frame", frame)); TextNotificationsManager.AddSystemLine(DesyncCompareLogs, "frame", frame);
} }
public void StartGame() public void StartGame()

View File

@@ -231,7 +231,7 @@ namespace OpenRA.Network
break; break;
if (orderManager.World.Paused != pause && world != null && world.LobbyInfo.NonBotClients.Count() > 1) if (orderManager.World.Paused != pause && world != null && world.LobbyInfo.NonBotClients.Count() > 1)
TextNotificationsManager.AddSystemLine(pause ? GamePaused : GameUnpaused, FluentBundle.Arguments("player", client.Name)); TextNotificationsManager.AddSystemLine(pause ? GamePaused : GameUnpaused, "player", client.Name);
orderManager.World.Paused = pause; orderManager.World.Paused = pause;
orderManager.World.PredictedPaused = pause; orderManager.World.PredictedPaused = pause;

View File

@@ -239,8 +239,8 @@ namespace OpenRA
var botInfo = botInfos.First(b => b.Type == BotType); var botInfo = botInfos.First(b => b.Type == BotType);
var botsOfSameType = World.Players.Where(c => c.BotType == BotType).ToArray(); var botsOfSameType = World.Players.Where(c => c.BotType == BotType).ToArray();
return FluentProvider.GetString(EnumeratedBotName, return FluentProvider.GetString(EnumeratedBotName,
FluentBundle.Arguments("name", FluentProvider.GetString(botInfo.Name), "name", FluentProvider.GetString(botInfo.Name),
"number", botsOfSameType.IndexOf(this) + 1)); "number", botsOfSameType.IndexOf(this) + 1);
} }
return PlayerName; return PlayerName;

View File

@@ -22,12 +22,12 @@ namespace OpenRA.Server
readonly Dictionary<int, List<long>> messageTracker = new(); readonly Dictionary<int, List<long>> messageTracker = new();
readonly Server server; readonly Server server;
readonly Action<Connection, int, int, byte[]> dispatchOrdersToClient; readonly Action<Connection, int, int, byte[]> dispatchOrdersToClient;
readonly Action<Connection, string, Dictionary<string, object>> sendLocalizedMessageTo; readonly Action<Connection, string, object[]> sendLocalizedMessageTo;
public PlayerMessageTracker( public PlayerMessageTracker(
Server server, Server server,
Action<Connection, int, int, byte[]> dispatchOrdersToClient, Action<Connection, int, int, byte[]> dispatchOrdersToClient,
Action<Connection, string, Dictionary<string, object>> sendLocalizedMessageTo) Action<Connection, string, object[]> sendLocalizedMessageTo)
{ {
this.server = server; this.server = server;
this.dispatchOrdersToClient = dispatchOrdersToClient; this.dispatchOrdersToClient = dispatchOrdersToClient;
@@ -56,7 +56,7 @@ namespace OpenRA.Server
if (!isAdmin && time < settings.FloodLimitJoinCooldown) if (!isAdmin && time < settings.FloodLimitJoinCooldown)
{ {
var remaining = CalculateRemaining(settings.FloodLimitJoinCooldown); var remaining = CalculateRemaining(settings.FloodLimitJoinCooldown);
sendLocalizedMessageTo(conn, ChatTemporaryDisabled, FluentBundle.Arguments("remaining", remaining)); sendLocalizedMessageTo(conn, ChatTemporaryDisabled, new object[] { "remaining", remaining });
return true; return true;
} }
@@ -64,7 +64,7 @@ namespace OpenRA.Server
if (tracker.Count >= settings.FloodLimitMessageCount) if (tracker.Count >= settings.FloodLimitMessageCount)
{ {
var remaining = CalculateRemaining(tracker[0] + settings.FloodLimitInterval); var remaining = CalculateRemaining(tracker[0] + settings.FloodLimitInterval);
sendLocalizedMessageTo(conn, ChatTemporaryDisabled, FluentBundle.Arguments("remaining", remaining)); sendLocalizedMessageTo(conn, ChatTemporaryDisabled, new object[] { "remaining", remaining });
return true; return true;
} }

View File

@@ -580,7 +580,7 @@ namespace OpenRA.Server
Log.Write("server", $"{client.Name} ({newConn.EndPoint}) has joined the game."); Log.Write("server", $"{client.Name} ({newConn.EndPoint}) has joined the game.");
SendLocalizedMessage(Joined, FluentBundle.Arguments("player", client.Name)); SendLocalizedMessage(Joined, "player", client.Name);
if (Type == ServerType.Dedicated) if (Type == ServerType.Dedicated)
{ {
@@ -952,18 +952,18 @@ namespace OpenRA.Server
WriteLineWithTimeStamp(text); WriteLineWithTimeStamp(text);
} }
public void SendLocalizedMessage(string key, Dictionary<string, object> arguments = null) public void SendLocalizedMessage(string key, params object[] args)
{ {
var text = FluentMessage.Serialize(key, arguments); var text = FluentMessage.Serialize(key, args);
DispatchServerOrdersToClients(Order.FromTargetString("FluentMessage", text, true)); DispatchServerOrdersToClients(Order.FromTargetString("FluentMessage", text, true));
if (Type == ServerType.Dedicated) if (Type == ServerType.Dedicated)
WriteLineWithTimeStamp(FluentProvider.GetString(key, arguments)); WriteLineWithTimeStamp(FluentProvider.GetString(key, args));
} }
public void SendLocalizedMessageTo(Connection conn, string key, Dictionary<string, object> arguments = null) public void SendLocalizedMessageTo(Connection conn, string key, object[] args = null)
{ {
var text = FluentMessage.Serialize(key, arguments); var text = FluentMessage.Serialize(key, args);
DispatchOrdersToClient(conn, 0, 0, Order.FromTargetString("FluentMessage", text, true).Serialize()); DispatchOrdersToClient(conn, 0, 0, Order.FromTargetString("FluentMessage", text, true).Serialize());
} }
@@ -998,7 +998,7 @@ namespace OpenRA.Server
if (!InterpretCommand(o.TargetString, conn)) if (!InterpretCommand(o.TargetString, conn))
{ {
Log.Write("server", $"Unknown server command: {o.TargetString}"); Log.Write("server", $"Unknown server command: {o.TargetString}");
SendLocalizedMessageTo(conn, UnknownServerCommand, FluentBundle.Arguments("command", o.TargetString)); SendLocalizedMessageTo(conn, UnknownServerCommand, new object[] { "command", o.TargetString });
} }
break; break;
@@ -1180,14 +1180,14 @@ namespace OpenRA.Server
if (State == ServerState.GameStarted) if (State == ServerState.GameStarted)
{ {
if (dropClient.IsObserver) if (dropClient.IsObserver)
SendLocalizedMessage(ObserverDisconnected, FluentBundle.Arguments("player", dropClient.Name)); SendLocalizedMessage(ObserverDisconnected, "player", dropClient.Name);
else if (dropClient.Team > 0) else if (dropClient.Team > 0)
SendLocalizedMessage(PlayerTeamDisconnected, FluentBundle.Arguments("player", dropClient.Name, "team", dropClient.Team)); SendLocalizedMessage(PlayerTeamDisconnected, "player", dropClient.Name, "team", dropClient.Team);
else else
SendLocalizedMessage(PlayerDisconnected, FluentBundle.Arguments("player", dropClient.Name)); SendLocalizedMessage(PlayerDisconnected, "player", dropClient.Name);
} }
else else
SendLocalizedMessage(LobbyDisconnected, FluentBundle.Arguments("player", dropClient.Name)); SendLocalizedMessage(LobbyDisconnected, "player", dropClient.Name);
LobbyInfo.Clients.RemoveAll(c => c.Index == toDrop.PlayerIndex); LobbyInfo.Clients.RemoveAll(c => c.Index == toDrop.PlayerIndex);
@@ -1204,7 +1204,7 @@ namespace OpenRA.Server
if (nextAdmin != null) if (nextAdmin != null)
{ {
nextAdmin.IsAdmin = true; nextAdmin.IsAdmin = true;
SendLocalizedMessage(NewAdmin, FluentBundle.Arguments("player", nextAdmin.Name)); SendLocalizedMessage(NewAdmin, "player", nextAdmin.Name);
} }
} }

View File

@@ -107,7 +107,7 @@ namespace OpenRA.Server
if (!kickee.IsObserver && !server.HasClientWonOrLost(kickee)) if (!kickee.IsObserver && !server.HasClientWonOrLost(kickee))
{ {
// Vote kick cannot be the sole deciding factor for a game. // Vote kick cannot be the sole deciding factor for a game.
server.SendLocalizedMessageTo(conn, InsufficientVotes, FluentBundle.Arguments("kickee", kickee.Name)); server.SendLocalizedMessageTo(conn, InsufficientVotes, new object[] { "kickee", kickee.Name });
EndKickVote(); EndKickVote();
return false; return false;
} }
@@ -135,7 +135,7 @@ namespace OpenRA.Server
Log.Write("server", $"Vote kick started on {kickeeID}."); Log.Write("server", $"Vote kick started on {kickeeID}.");
voteKickTimer = Stopwatch.StartNew(); voteKickTimer = Stopwatch.StartNew();
server.SendLocalizedMessage(VoteKickStarted, FluentBundle.Arguments("kicker", kicker.Name, "kickee", kickee.Name)); server.SendLocalizedMessage(VoteKickStarted, "kicker", kicker.Name, "kickee", kickee.Name);
server.DispatchServerOrdersToClients(new Order("StartKickVote", null, false) { ExtraData = (uint)kickeeID }.Serialize()); server.DispatchServerOrdersToClients(new Order("StartKickVote", null, false) { ExtraData = (uint)kickeeID }.Serialize());
this.kickee = (kickee, kickeeConn); this.kickee = (kickee, kickeeConn);
voteKickerStarter = (kicker, conn); voteKickerStarter = (kicker, conn);
@@ -145,7 +145,7 @@ namespace OpenRA.Server
voteTracker[conn.PlayerIndex] = vote; voteTracker[conn.PlayerIndex] = vote;
else else
{ {
server.SendLocalizedMessageTo(conn, AlreadyVoted, null); server.SendLocalizedMessageTo(conn, AlreadyVoted);
return false; return false;
} }
@@ -168,9 +168,9 @@ namespace OpenRA.Server
} }
var votesNeeded = eligiblePlayers / 2 + 1; var votesNeeded = eligiblePlayers / 2 + 1;
server.SendLocalizedMessage(VoteKickProgress, FluentBundle.Arguments( server.SendLocalizedMessage(VoteKickProgress,
"kickee", kickee.Name, "kickee", kickee.Name,
"percentage", votesFor * 100 / eligiblePlayers)); "percentage", votesFor * 100 / eligiblePlayers);
// If a player or players during a vote lose or disconnect, it is possible that a downvote will // If a player or players during a vote lose or disconnect, it is possible that a downvote will
// kick a client. Guard against that situation. // kick a client. Guard against that situation.
@@ -210,7 +210,7 @@ namespace OpenRA.Server
return; return;
if (sendMessage) if (sendMessage)
server.SendLocalizedMessage(VoteKickEnded, FluentBundle.Arguments("kickee", kickee.Client.Name)); server.SendLocalizedMessage(VoteKickEnded, "kickee", kickee.Client.Name);
server.DispatchServerOrdersToClients(new Order("EndKickVote", null, false) { ExtraData = (uint)kickee.Client.Index }.Serialize()); server.DispatchServerOrdersToClients(new Order("EndKickVote", null, false) { ExtraData = (uint)kickee.Client.Index }.Serialize());

View File

@@ -41,9 +41,9 @@ namespace OpenRA
AddTextNotification(TextNotificationPool.Transients, SystemClientId, SystemMessageLabel, FluentProvider.GetString(text)); AddTextNotification(TextNotificationPool.Transients, SystemClientId, SystemMessageLabel, FluentProvider.GetString(text));
} }
public static void AddFeedbackLine(string text, Dictionary<string, object> arguments = null) public static void AddFeedbackLine(string text, params object[] args)
{ {
AddTextNotification(TextNotificationPool.Feedback, SystemClientId, SystemMessageLabel, FluentProvider.GetString(text, arguments)); AddTextNotification(TextNotificationPool.Feedback, SystemClientId, SystemMessageLabel, FluentProvider.GetString(text, args));
} }
public static void AddMissionLine(string prefix, string text, Color? prefixColor = null) public static void AddMissionLine(string prefix, string text, Color? prefixColor = null)
@@ -51,19 +51,19 @@ namespace OpenRA
AddTextNotification(TextNotificationPool.Mission, SystemClientId, prefix, text, prefixColor); AddTextNotification(TextNotificationPool.Mission, SystemClientId, prefix, text, prefixColor);
} }
public static void AddPlayerJoinedLine(string text, Dictionary<string, object> arguments = null) public static void AddPlayerJoinedLine(string text, params object[] args)
{ {
AddTextNotification(TextNotificationPool.Join, SystemClientId, SystemMessageLabel, FluentProvider.GetString(text, arguments)); AddTextNotification(TextNotificationPool.Join, SystemClientId, SystemMessageLabel, FluentProvider.GetString(text, args));
} }
public static void AddPlayerLeftLine(string text, Dictionary<string, object> arguments = null) public static void AddPlayerLeftLine(string text, params object[] args)
{ {
AddTextNotification(TextNotificationPool.Leave, SystemClientId, SystemMessageLabel, FluentProvider.GetString(text, arguments)); AddTextNotification(TextNotificationPool.Leave, SystemClientId, SystemMessageLabel, FluentProvider.GetString(text, args));
} }
public static void AddSystemLine(string text, Dictionary<string, object> arguments = null) public static void AddSystemLine(string text, params object[] args)
{ {
AddSystemLine(SystemMessageLabel, FluentProvider.GetString(text, arguments)); AddSystemLine(SystemMessageLabel, FluentProvider.GetString(text, args));
} }
public static void AddSystemLine(string prefix, string text) public static void AddSystemLine(string prefix, string text)

View File

@@ -51,13 +51,11 @@ namespace OpenRA.Mods.Cnc.Installer
Action<long> onProgress = null; Action<long> onProgress = null;
if (stream.Length < InstallFromSourceLogic.ShowPercentageThreshold) if (stream.Length < InstallFromSourceLogic.ShowPercentageThreshold)
updateMessage(FluentProvider.GetString( updateMessage(FluentProvider.GetString(InstallFromSourceLogic.Extracting, "filename", displayFilename));
InstallFromSourceLogic.Extracing,
FluentBundle.Arguments("filename", displayFilename)));
else else
onProgress = b => updateMessage(FluentProvider.GetString( onProgress = b => updateMessage(FluentProvider.GetString(InstallFromSourceLogic.ExtractingProgress,
InstallFromSourceLogic.ExtractingProgress, "filename", displayFilename,
FluentBundle.Arguments("filename", displayFilename, "progress", 100 * b / stream.Length))); "progress", 100 * b / stream.Length));
using (var target = File.OpenWrite(targetPath)) using (var target = File.OpenWrite(targetPath))
{ {

View File

@@ -40,7 +40,7 @@ namespace OpenRA.Mods.Common.Commands
if (Commands.TryGetValue(name, out var command)) if (Commands.TryGetValue(name, out var command))
command.InvokeCommand(name, message[(1 + name.Length)..].Trim()); command.InvokeCommand(name, message[(1 + name.Length)..].Trim());
else else
TextNotificationsManager.Debug(FluentProvider.GetString(InvalidCommand, FluentBundle.Arguments("name", name))); TextNotificationsManager.Debug(FluentProvider.GetString(InvalidCommand, "name", name));
return false; return false;
} }

View File

@@ -168,7 +168,8 @@ namespace OpenRA.Mods.Common.Widgets
{ {
editorActorPreview = editorLayer.Add(actor); editorActorPreview = editorLayer.Add(actor);
Text = FluentProvider.GetString(AddedActor, Text = FluentProvider.GetString(AddedActor,
FluentBundle.Arguments("name", editorActorPreview.Info.Name, "id", editorActorPreview.ID)); "name", editorActorPreview.Info.Name,
"id", editorActorPreview.ID);
} }
public void Undo() public void Undo()

View File

@@ -146,7 +146,7 @@ namespace OpenRA.Mods.Common.Widgets
undoClipboard = CopySelectionContents(); undoClipboard = CopySelectionContents();
Text = FluentProvider.GetString(CopiedTiles, FluentBundle.Arguments("amount", clipboard.Tiles.Count)); Text = FluentProvider.GetString(CopiedTiles, "amount", clipboard.Tiles.Count);
} }
/// <summary> /// <summary>

View File

@@ -308,13 +308,13 @@ namespace OpenRA.Mods.Common.Widgets
}; };
if (selection.Area != null) if (selection.Area != null)
Text = FluentProvider.GetString(SelectedArea, FluentBundle.Arguments( Text = FluentProvider.GetString(SelectedArea,
"x", selection.Area.TopLeft.X, "x", selection.Area.TopLeft.X,
"y", selection.Area.TopLeft.Y, "y", selection.Area.TopLeft.Y,
"width", selection.Area.BottomRight.X - selection.Area.TopLeft.X, "width", selection.Area.BottomRight.X - selection.Area.TopLeft.X,
"height", selection.Area.BottomRight.Y - selection.Area.TopLeft.Y)); "height", selection.Area.BottomRight.Y - selection.Area.TopLeft.Y);
else if (selection.Actor != null) else if (selection.Actor != null)
Text = FluentProvider.GetString(SelectedActor, FluentBundle.Arguments("id", selection.Actor.ID)); Text = FluentProvider.GetString(SelectedActor, "id", selection.Actor.ID);
else else
Text = FluentProvider.GetString(ClearedSelection); Text = FluentProvider.GetString(ClearedSelection);
} }
@@ -360,8 +360,7 @@ namespace OpenRA.Mods.Common.Widgets
Actor = defaultBrush.Selection.Actor Actor = defaultBrush.Selection.Actor
}; };
Text = FluentProvider.GetString(RemovedActor, Text = FluentProvider.GetString(RemovedActor, "name", actor.Info.Name, "id", actor.ID);
FluentBundle.Arguments("name", actor.Info.Name, "id", actor.ID));
} }
public void Execute() public void Execute()
@@ -397,8 +396,7 @@ namespace OpenRA.Mods.Common.Widgets
this.editorActorLayer = editorActorLayer; this.editorActorLayer = editorActorLayer;
this.actor = actor; this.actor = actor;
Text = FluentProvider.GetString(RemovedActor, Text = FluentProvider.GetString(RemovedActor, "name", actor.Info.Name, "id", actor.ID);
FluentBundle.Arguments("name", actor.Info.Name, "id", actor.ID));
} }
public void Execute() public void Execute()
@@ -466,7 +464,7 @@ namespace OpenRA.Mods.Common.Widgets
to = worldRenderer.Viewport.ViewToWorld(pixelTo + pixelOffset) + cellOffset; to = worldRenderer.Viewport.ViewToWorld(pixelTo + pixelOffset) + cellOffset;
layer.MoveActor(actor, to); layer.MoveActor(actor, to);
Text = FluentProvider.GetString(MovedActor, FluentBundle.Arguments("id", actor.ID, "x1", from.X, "y1", from.Y, "x2", to.X, "y2", to.Y)); Text = FluentProvider.GetString(MovedActor, "id", actor.ID, "x1", from.X, "y1", from.Y, "x2", to.X, "y2", to.Y);
} }
} }
@@ -487,7 +485,7 @@ namespace OpenRA.Mods.Common.Widgets
this.resourceLayer = resourceLayer; this.resourceLayer = resourceLayer;
this.cell = cell; this.cell = cell;
Text = FluentProvider.GetString(RemovedResource, FluentBundle.Arguments("type", resourceType)); Text = FluentProvider.GetString(RemovedResource, "type", resourceType);
} }
public void Execute() public void Execute()

View File

@@ -150,9 +150,9 @@ namespace OpenRA.Mods.Common.Widgets
} }
if (type != null) if (type != null)
Text = FluentProvider.GetString(AddedMarkerTiles, FluentBundle.Arguments("amount", paintTiles.Count, "type", type)); Text = FluentProvider.GetString(AddedMarkerTiles, "amount", paintTiles.Count, "type", type);
else else
Text = FluentProvider.GetString(RemovedMarkerTiles, FluentBundle.Arguments("amount", paintTiles.Count)); Text = FluentProvider.GetString(RemovedMarkerTiles, "amount", paintTiles.Count);
} }
} }
@@ -176,7 +176,7 @@ namespace OpenRA.Mods.Common.Widgets
tiles = new HashSet<CPos>(markerLayerOverlay.Tiles[tile]); tiles = new HashSet<CPos>(markerLayerOverlay.Tiles[tile]);
Text = FluentProvider.GetString(ClearedSelectedMarkerTiles, FluentBundle.Arguments("amount", tiles.Count, "type", tile)); Text = FluentProvider.GetString(ClearedSelectedMarkerTiles, "amount", tiles.Count, "type", tile);
} }
public void Execute() public void Execute()
@@ -213,7 +213,7 @@ namespace OpenRA.Mods.Common.Widgets
var allTilesCount = tiles.Values.Select(x => x.Count).Sum(); var allTilesCount = tiles.Values.Select(x => x.Count).Sum();
Text = FluentProvider.GetString(ClearedAllMarkerTiles, FluentBundle.Arguments("amount", allTilesCount)); Text = FluentProvider.GetString(ClearedAllMarkerTiles, "amount", allTilesCount);
} }
public void Execute() public void Execute()

View File

@@ -168,7 +168,7 @@ namespace OpenRA.Mods.Common.Widgets
resourceLayer.ClearResources(resourceCell.Cell); resourceLayer.ClearResources(resourceCell.Cell);
resourceLayer.AddResource(resourceCell.NewResourceType, resourceCell.Cell, resourceLayer.GetMaxDensity(resourceCell.NewResourceType)); resourceLayer.AddResource(resourceCell.NewResourceType, resourceCell.Cell, resourceLayer.GetMaxDensity(resourceCell.NewResourceType));
cellResources.Add(resourceCell); cellResources.Add(resourceCell);
Text = FluentProvider.GetString(AddedResource, FluentBundle.Arguments("amount", cellResources.Count, "type", resourceType)); Text = FluentProvider.GetString(AddedResource, "amount", cellResources.Count, "type", resourceType);
} }
} }
} }

View File

@@ -192,7 +192,7 @@ namespace OpenRA.Mods.Common.Widgets
var terrainInfo = (ITemplatedTerrainInfo)map.Rules.TerrainInfo; var terrainInfo = (ITemplatedTerrainInfo)map.Rules.TerrainInfo;
terrainTemplate = terrainInfo.Templates[template]; terrainTemplate = terrainInfo.Templates[template];
Text = FluentProvider.GetString(AddedTile, FluentBundle.Arguments("id", terrainTemplate.Id)); Text = FluentProvider.GetString(AddedTile, "id", terrainTemplate.Id);
} }
public void Execute() public void Execute()
@@ -264,7 +264,7 @@ namespace OpenRA.Mods.Common.Widgets
var terrainInfo = (ITemplatedTerrainInfo)map.Rules.TerrainInfo; var terrainInfo = (ITemplatedTerrainInfo)map.Rules.TerrainInfo;
terrainTemplate = terrainInfo.Templates[template]; terrainTemplate = terrainInfo.Templates[template];
Text = FluentProvider.GetString(FilledTile, FluentBundle.Arguments("id", terrainTemplate.Id)); Text = FluentProvider.GetString(FilledTile, "id", terrainTemplate.Id);
} }
public void Execute() public void Execute()

View File

@@ -44,13 +44,12 @@ namespace OpenRA.Mods.Common.Installer
Action<long> onProgress = null; Action<long> onProgress = null;
if (length < InstallFromSourceLogic.ShowPercentageThreshold) if (length < InstallFromSourceLogic.ShowPercentageThreshold)
updateMessage(FluentProvider.GetString( updateMessage(FluentProvider.GetString(InstallFromSourceLogic.CopyingFilename,
InstallFromSourceLogic.CopyingFilename, "filename", displayFilename));
FluentBundle.Arguments("filename", displayFilename)));
else else
onProgress = b => updateMessage(FluentProvider.GetString( onProgress = b => updateMessage(FluentProvider.GetString(InstallFromSourceLogic.CopyingFilenameProgress,
InstallFromSourceLogic.CopyingFilenameProgress, "filename", displayFilename,
FluentBundle.Arguments("filename", displayFilename, "progress", 100 * b / length))); "progress", 100 * b / length));
InstallerUtils.CopyStream(source, target, length, onProgress); InstallerUtils.CopyStream(source, target, length, onProgress);
} }

View File

@@ -68,13 +68,12 @@ namespace OpenRA.Mods.Common.Installer
Action<long> onProgress = null; Action<long> onProgress = null;
if (length < InstallFromSourceLogic.ShowPercentageThreshold) if (length < InstallFromSourceLogic.ShowPercentageThreshold)
updateMessage(FluentProvider.GetString( updateMessage(FluentProvider.GetString(InstallFromSourceLogic.Extracting,
InstallFromSourceLogic.Extracing, "filename", displayFilename));
FluentBundle.Arguments("filename", displayFilename)));
else else
onProgress = b => updateMessage(FluentProvider.GetString( onProgress = b => updateMessage(FluentProvider.GetString(InstallFromSourceLogic.ExtractingProgress,
InstallFromSourceLogic.ExtractingProgress, "filename", displayFilename,
FluentBundle.Arguments("filename", displayFilename, "progress", 100 * b / length))); "progress", 100 * b / length));
using (var target = File.OpenWrite(targetPath)) using (var target = File.OpenWrite(targetPath))
{ {

View File

@@ -66,7 +66,7 @@ namespace OpenRA.Mods.Common.Installer
var displayFilename = Path.GetFileName(Path.GetFileName(targetPath)); var displayFilename = Path.GetFileName(Path.GetFileName(targetPath));
void OnProgress(int percent) => updateMessage(FluentProvider.GetString( void OnProgress(int percent) => updateMessage(FluentProvider.GetString(
InstallFromSourceLogic.ExtractingProgress, InstallFromSourceLogic.ExtractingProgress,
FluentBundle.Arguments("filename", displayFilename, "progress", percent))); "filename", displayFilename, "progress", percent));
reader.ExtractFile(node.Value.Value, target, OnProgress); reader.ExtractFile(node.Value.Value, target, OnProgress);
} }
} }

View File

@@ -46,9 +46,9 @@ namespace OpenRA.Mods.Common.Installer
{ {
Log.Write("install", $"Extracting {sourcePath} -> {targetPath}"); Log.Write("install", $"Extracting {sourcePath} -> {targetPath}");
var displayFilename = Path.GetFileName(Path.GetFileName(targetPath)); var displayFilename = Path.GetFileName(Path.GetFileName(targetPath));
void OnProgress(int percent) => updateMessage(FluentProvider.GetString( void OnProgress(int percent) => updateMessage(FluentProvider.GetString(InstallFromSourceLogic.ExtractingProgress,
InstallFromSourceLogic.ExtractingProgress, "filename", displayFilename,
FluentBundle.Arguments("filename", displayFilename, "progress", percent))); "progress", percent));
reader.ExtractFile(node.Value.Value, target, OnProgress); reader.ExtractFile(node.Value.Value, target, OnProgress);
} }
} }

View File

@@ -61,11 +61,12 @@ namespace OpenRA.Mods.Common.Installer
Action<long> onProgress = null; Action<long> onProgress = null;
if (length < InstallFromSourceLogic.ShowPercentageThreshold) if (length < InstallFromSourceLogic.ShowPercentageThreshold)
updateMessage(FluentProvider.GetString(InstallFromSourceLogic.Extracing, FluentBundle.Arguments("filename", displayFilename))); updateMessage(FluentProvider.GetString(InstallFromSourceLogic.Extracting,
"filename", displayFilename));
else else
onProgress = b => updateMessage(FluentProvider.GetString( onProgress = b => updateMessage(FluentProvider.GetString(InstallFromSourceLogic.ExtractingProgress,
InstallFromSourceLogic.ExtractingProgress, "filename", displayFilename,
FluentBundle.Arguments("filename", displayFilename, "progress", 100 * b / length))); "progress", 100 * b / length));
using (var target = File.OpenWrite(targetPath)) using (var target = File.OpenWrite(targetPath))
{ {

View File

@@ -49,9 +49,9 @@ namespace OpenRA.Mods.Common.Installer
using (var targetStream = File.OpenWrite(targetPath)) using (var targetStream = File.OpenWrite(targetPath))
sourceStream.CopyTo(targetStream); sourceStream.CopyTo(targetStream);
updateMessage(FluentProvider.GetString( updateMessage(FluentProvider.GetString(InstallFromSourceLogic.ExtractingProgress,
InstallFromSourceLogic.ExtractingProgress, "filename", displayFilename,
FluentBundle.Arguments("filename", displayFilename, "progress", 100))); "progress", 100));
extracted.Add(targetPath); extracted.Add(targetPath);
} }

View File

@@ -224,7 +224,7 @@ namespace OpenRA.Mods.Common.Server
if (server.State == ServerState.GameStarted) if (server.State == ServerState.GameStarted)
{ {
server.SendLocalizedMessageTo(conn, StateUnchangedGameStarted, FluentBundle.Arguments("command", command)); server.SendLocalizedMessageTo(conn, StateUnchangedGameStarted, new object[] { "command", command });
return false; return false;
} }
else if (client.State == Session.ClientState.Ready && !(command.StartsWith("state", StringComparison.Ordinal) || command == "startgame")) else if (client.State == Session.ClientState.Ready && !(command.StartsWith("state", StringComparison.Ordinal) || command == "startgame"))
@@ -303,7 +303,7 @@ namespace OpenRA.Mods.Common.Server
{ {
if (!Enum<Session.ClientState>.TryParse(s, false, out var state)) if (!Enum<Session.ClientState>.TryParse(s, false, out var state))
{ {
server.SendLocalizedMessageTo(conn, MalformedCommand, FluentBundle.Arguments("command", "state")); server.SendLocalizedMessageTo(conn, MalformedCommand, new object[] { "command", "state" });
return true; return true;
} }
@@ -399,7 +399,7 @@ namespace OpenRA.Mods.Common.Server
return true; return true;
} }
server.SendLocalizedMessageTo(conn, MalformedCommand, FluentBundle.Arguments("command", "allow_spectate")); server.SendLocalizedMessageTo(conn, MalformedCommand, new object[] { "command", "allow_spectate" });
return true; return true;
} }
@@ -488,7 +488,7 @@ namespace OpenRA.Mods.Common.Server
var parts = s.Split(' '); var parts = s.Split(' ');
if (parts.Length < 3) if (parts.Length < 3)
{ {
server.SendLocalizedMessageTo(conn, MalformedCommand, FluentBundle.Arguments("command", "slot_bot")); server.SendLocalizedMessageTo(conn, MalformedCommand, new object[] { "command", "slot_bot" });
return true; return true;
} }
@@ -652,7 +652,7 @@ namespace OpenRA.Mods.Common.Server
server.SyncLobbyInfo(); server.SyncLobbyInfo();
server.SendLocalizedMessage(ChangedMap, FluentBundle.Arguments("player", client.Name, "map", server.Map.Title)); server.SendLocalizedMessage(ChangedMap, "player", client.Name, "map", server.Map.Title);
if ((server.LobbyInfo.GlobalSettings.MapStatus & Session.MapStatus.UnsafeCustomRules) != 0) if ((server.LobbyInfo.GlobalSettings.MapStatus & Session.MapStatus.UnsafeCustomRules) != 0)
server.SendLocalizedMessage(CustomRules); server.SendLocalizedMessage(CustomRules);
@@ -722,7 +722,7 @@ namespace OpenRA.Mods.Common.Server
if (option.IsLocked) if (option.IsLocked)
{ {
server.SendLocalizedMessageTo(conn, OptionLocked, FluentBundle.Arguments("option", option.Name)); server.SendLocalizedMessageTo(conn, OptionLocked, new object[] { "option", option.Name });
return true; return true;
} }
@@ -739,7 +739,7 @@ namespace OpenRA.Mods.Common.Server
oo.Value = oo.PreferredValue = split[1]; oo.Value = oo.PreferredValue = split[1];
server.SyncLobbyGlobalSettings(); server.SyncLobbyGlobalSettings();
server.SendLocalizedMessage(ValueChanged, FluentBundle.Arguments("player", client.Name, "name", option.Name, "value", option.Label(split[1]))); server.SendLocalizedMessage(ValueChanged, "player", client.Name, "name", option.Name, "value", option.Label(split[1]));
foreach (var c in server.LobbyInfo.Clients) foreach (var c in server.LobbyInfo.Clients)
c.State = Session.ClientState.NotReady; c.State = Session.ClientState.NotReady;
@@ -768,10 +768,10 @@ namespace OpenRA.Mods.Common.Server
foreach (var o in allOptions) foreach (var o in allOptions)
{ {
if (o.DefaultValue != server.LobbyInfo.GlobalSettings.LobbyOptions[o.Id].Value) if (o.DefaultValue != server.LobbyInfo.GlobalSettings.LobbyOptions[o.Id].Value)
server.SendLocalizedMessage(ValueChanged, FluentBundle.Arguments( server.SendLocalizedMessage(ValueChanged,
"player", client.Name, "player", client.Name,
"name", o.Name, "name", o.Name,
"value", o.Label(o.DefaultValue))); "value", o.Label(o.DefaultValue));
options[o.Id] = new Session.LobbyOptionState options[o.Id] = new Session.LobbyOptionState
{ {
@@ -805,7 +805,7 @@ namespace OpenRA.Mods.Common.Server
if (!Exts.TryParseInt32Invariant(raw, out var teamCount)) if (!Exts.TryParseInt32Invariant(raw, out var teamCount))
{ {
server.SendLocalizedMessageTo(conn, NumberTeams, FluentBundle.Arguments("raw", raw)); server.SendLocalizedMessageTo(conn, NumberTeams, new object[] { "raw", raw });
return true; return true;
} }
@@ -850,7 +850,7 @@ namespace OpenRA.Mods.Common.Server
var split = s.Split(' '); var split = s.Split(' ');
if (split.Length < 2) if (split.Length < 2)
{ {
server.SendLocalizedMessageTo(conn, MalformedCommand, FluentBundle.Arguments("command", "kick")); server.SendLocalizedMessageTo(conn, MalformedCommand, new object[] { "command", "kick" });
return true; return true;
} }
@@ -877,14 +877,14 @@ namespace OpenRA.Mods.Common.Server
} }
Log.Write("server", $"Kicking client {kickClientID}."); Log.Write("server", $"Kicking client {kickClientID}.");
server.SendLocalizedMessage(AdminKicked, FluentBundle.Arguments("admin", client.Name, "player", kickClient.Name)); server.SendLocalizedMessage(AdminKicked, "admin", client.Name, "player", kickClient.Name);
server.SendOrderTo(kickConn, "ServerError", YouWereKicked); server.SendOrderTo(kickConn, "ServerError", YouWereKicked);
server.DropClient(kickConn); server.DropClient(kickConn);
if (bool.TryParse(split[1], out var tempBan) && tempBan) if (bool.TryParse(split[1], out var tempBan) && tempBan)
{ {
Log.Write("server", $"Temporarily banning client {kickClientID} ({kickClient.IPAddress})."); Log.Write("server", $"Temporarily banning client {kickClientID} ({kickClient.IPAddress}).");
server.SendLocalizedMessage(TempBan, FluentBundle.Arguments("admin", client.Name, "player", kickClient.Name)); server.SendLocalizedMessage(TempBan, "admin", client.Name, "player", kickClient.Name);
server.TempBans.Add(kickClient.IPAddress); server.TempBans.Add(kickClient.IPAddress);
} }
@@ -902,7 +902,7 @@ namespace OpenRA.Mods.Common.Server
var split = s.Split(' '); var split = s.Split(' ');
if (split.Length != 2) if (split.Length != 2)
{ {
server.SendLocalizedMessageTo(conn, MalformedCommand, FluentBundle.Arguments("command", "vote_kick")); server.SendLocalizedMessageTo(conn, MalformedCommand, new object[] { "command", "vote_kick" });
return true; return true;
} }
@@ -930,14 +930,14 @@ namespace OpenRA.Mods.Common.Server
if (!bool.TryParse(split[1], out var vote)) if (!bool.TryParse(split[1], out var vote))
{ {
server.SendLocalizedMessageTo(conn, MalformedCommand, FluentBundle.Arguments("command", "vote_kick")); server.SendLocalizedMessageTo(conn, MalformedCommand, new object[] { "command", "vote_kick" });
return true; return true;
} }
if (server.VoteKickTracker.VoteKick(conn, client, kickConn, kickClient, kickClientID, vote)) if (server.VoteKickTracker.VoteKick(conn, client, kickConn, kickClient, kickClientID, vote))
{ {
Log.Write("server", $"Kicking client {kickClientID}."); Log.Write("server", $"Kicking client {kickClientID}.");
server.SendLocalizedMessage(Kicked, FluentBundle.Arguments("player", kickClient.Name)); server.SendLocalizedMessage(Kicked, "player", kickClient.Name);
server.SendOrderTo(kickConn, "ServerError", YouWereKicked); server.SendOrderTo(kickConn, "ServerError", YouWereKicked);
server.DropClient(kickConn); server.DropClient(kickConn);
@@ -980,7 +980,7 @@ namespace OpenRA.Mods.Common.Server
foreach (var b in bots) foreach (var b in bots)
b.BotControllerClientIndex = newAdminId; b.BotControllerClientIndex = newAdminId;
server.SendLocalizedMessage(NewAdmin, FluentBundle.Arguments("player", newAdminClient.Name)); server.SendLocalizedMessage(NewAdmin, "player", newAdminClient.Name);
Log.Write("server", $"{newAdminClient.Name} is now the admin."); Log.Write("server", $"{newAdminClient.Name} is now the admin.");
server.SyncLobbyClients(); server.SyncLobbyClients();
@@ -1014,7 +1014,7 @@ namespace OpenRA.Mods.Common.Server
targetClient.Handicap = 0; targetClient.Handicap = 0;
targetClient.Color = Color.White; targetClient.Color = Color.White;
targetClient.State = Session.ClientState.NotReady; targetClient.State = Session.ClientState.NotReady;
server.SendLocalizedMessage(MoveSpectators, FluentBundle.Arguments("admin", client.Name, "player", targetClient.Name)); server.SendLocalizedMessage(MoveSpectators, "admin", client.Name, "player", targetClient.Name);
Log.Write("server", $"{client.Name} moved {targetClient.Name} to spectators."); Log.Write("server", $"{client.Name} moved {targetClient.Name} to spectators.");
server.SyncLobbyClients(); server.SyncLobbyClients();
CheckAutoStart(server); CheckAutoStart(server);
@@ -1032,7 +1032,7 @@ namespace OpenRA.Mods.Common.Server
return true; return true;
Log.Write("server", $"Player@{conn.EndPoint} is now known as {sanitizedName}."); Log.Write("server", $"Player@{conn.EndPoint} is now known as {sanitizedName}.");
server.SendLocalizedMessage(Nick, FluentBundle.Arguments("player", client.Name, "name", sanitizedName)); server.SendLocalizedMessage(Nick, "player", client.Name, "name", sanitizedName);
client.Name = sanitizedName; client.Name = sanitizedName;
server.SyncLobbyClients(); server.SyncLobbyClients();
@@ -1062,8 +1062,8 @@ namespace OpenRA.Mods.Common.Server
var faction = parts[1]; var faction = parts[1];
if (!factions.Contains(faction)) if (!factions.Contains(faction))
{ {
server.SendLocalizedMessageTo(conn, InvalidFactionSelected, FluentBundle.Arguments("faction", faction)); server.SendLocalizedMessageTo(conn, InvalidFactionSelected, new object[] { "faction", faction });
server.SendLocalizedMessageTo(conn, SupportedFactions, FluentBundle.Arguments("factions", factions.JoinWith(", "))); server.SendLocalizedMessageTo(conn, SupportedFactions, new object[] { "factions", factions.JoinWith(", ") });
return true; return true;
} }

View File

@@ -9,7 +9,6 @@
*/ */
#endregion #endregion
using System.Collections.Generic;
using System.Linq; using System.Linq;
using OpenRA.Server; using OpenRA.Server;
using S = OpenRA.Server.Server; using S = OpenRA.Server.Server;
@@ -69,13 +68,13 @@ namespace OpenRA.Mods.Common.Server
{ {
if (!c.TimeoutMessageShown && c.TimeSinceLastResponse > PingInterval * 2) if (!c.TimeoutMessageShown && c.TimeSinceLastResponse > PingInterval * 2)
{ {
server.SendLocalizedMessage(ConnectionProblems, FluentBundle.Arguments("player", client.Name)); server.SendLocalizedMessage(ConnectionProblems, "player", client.Name);
c.TimeoutMessageShown = true; c.TimeoutMessageShown = true;
} }
} }
else else
{ {
server.SendLocalizedMessage(Timeout, FluentBundle.Arguments("player", client.Name)); server.SendLocalizedMessage(Timeout, "player", client.Name);
server.DropClient(c); server.DropClient(c);
} }
} }
@@ -94,11 +93,7 @@ namespace OpenRA.Mods.Common.Server
if (client != null) if (client != null)
{ {
var timeout = (ConnTimeout - c.TimeSinceLastResponse) / 1000; var timeout = (ConnTimeout - c.TimeSinceLastResponse) / 1000;
server.SendLocalizedMessage(TimeoutIn, new Dictionary<string, object>() server.SendLocalizedMessage(TimeoutIn, "player", client.Name, "timeout", timeout);
{
{ "player", client.Name },
{ "timeout", timeout }
});
} }
} }
} }

View File

@@ -105,7 +105,7 @@ namespace OpenRA.Mods.Common.Traits
if (info.SuppressNotifications) if (info.SuppressNotifications)
return; return;
TextNotificationsManager.AddSystemLine(PlayerIsDefeated, FluentBundle.Arguments("player", player.ResolvedPlayerName)); TextNotificationsManager.AddSystemLine(PlayerIsDefeated, "player", player.ResolvedPlayerName);
Game.RunAfterDelay(info.NotificationDelay, () => Game.RunAfterDelay(info.NotificationDelay, () =>
{ {
if (Game.IsCurrentWorld(player.World) && player == player.World.LocalPlayer) if (Game.IsCurrentWorld(player.World) && player == player.World.LocalPlayer)
@@ -121,7 +121,7 @@ namespace OpenRA.Mods.Common.Traits
if (info.SuppressNotifications) if (info.SuppressNotifications)
return; return;
TextNotificationsManager.AddSystemLine(PlayerIsVictorious, FluentBundle.Arguments("player", player.ResolvedPlayerName)); TextNotificationsManager.AddSystemLine(PlayerIsVictorious, "player", player.ResolvedPlayerName);
Game.RunAfterDelay(info.NotificationDelay, () => Game.RunAfterDelay(info.NotificationDelay, () =>
{ {
if (Game.IsCurrentWorld(player.World) && player == player.World.LocalPlayer) if (Game.IsCurrentWorld(player.World) && player == player.World.LocalPlayer)

View File

@@ -275,8 +275,10 @@ namespace OpenRA.Mods.Common.Traits
return; return;
} }
var arguments = FluentBundle.Arguments("cheat", order.OrderString, "player", self.Owner.ResolvedPlayerName, "suffix", debugSuffix); TextNotificationsManager.Debug(FluentProvider.GetString(CheatUsed,
TextNotificationsManager.Debug(FluentProvider.GetString(CheatUsed, arguments)); "cheat", order.OrderString,
"player", self.Owner.ResolvedPlayerName,
"suffix", debugSuffix));
} }
bool IUnlocksRenderPlayer.RenderPlayerUnlocked => Enabled; bool IUnlocksRenderPlayer.RenderPlayerUnlocked => Enabled;

View File

@@ -151,7 +151,7 @@ namespace OpenRA.Mods.Common.Traits
if (info.SuppressNotifications) if (info.SuppressNotifications)
return; return;
TextNotificationsManager.AddSystemLine(PlayerIsDefeated, FluentBundle.Arguments("player", player.ResolvedPlayerName)); TextNotificationsManager.AddSystemLine(PlayerIsDefeated, "player", player.ResolvedPlayerName);
Game.RunAfterDelay(info.NotificationDelay, () => Game.RunAfterDelay(info.NotificationDelay, () =>
{ {
if (Game.IsCurrentWorld(player.World) && player == player.World.LocalPlayer) if (Game.IsCurrentWorld(player.World) && player == player.World.LocalPlayer)
@@ -167,7 +167,7 @@ namespace OpenRA.Mods.Common.Traits
if (info.SuppressNotifications) if (info.SuppressNotifications)
return; return;
TextNotificationsManager.AddSystemLine(PlayerIsVictorious, FluentBundle.Arguments("player", player.ResolvedPlayerName)); TextNotificationsManager.AddSystemLine(PlayerIsVictorious, "player", player.ResolvedPlayerName);
Game.RunAfterDelay(info.NotificationDelay, () => Game.RunAfterDelay(info.NotificationDelay, () =>
{ {
if (Game.IsCurrentWorld(player.World) && player == player.World.LocalPlayer) if (Game.IsCurrentWorld(player.World) && player == player.World.LocalPlayer)

View File

@@ -90,7 +90,7 @@ namespace OpenRA.Mods.Common.Traits
if (m == 0) if (m == 0)
return FluentProvider.GetString(NoTimeLimit); return FluentProvider.GetString(NoTimeLimit);
else else
return FluentProvider.GetString(TimeLimitOption, FluentBundle.Arguments("minutes", m)); return FluentProvider.GetString(TimeLimitOption, "minutes", m);
}); });
yield return new LobbyOption(map, "timelimit", TimeLimitLabel, TimeLimitDescription, TimeLimitDropdownVisible, TimeLimitDisplayOrder, yield return new LobbyOption(map, "timelimit", TimeLimitLabel, TimeLimitDescription, TimeLimitDropdownVisible, TimeLimitDisplayOrder,

View File

@@ -10,7 +10,6 @@
#endregion #endregion
using System; using System;
using System.Collections.Generic;
using OpenRA.Widgets; using OpenRA.Widgets;
namespace OpenRA.Mods.Common.Widgets namespace OpenRA.Mods.Common.Widgets
@@ -21,8 +20,8 @@ namespace OpenRA.Mods.Common.Widgets
ModData modData, ModData modData,
string title, string title,
string text, string text,
Dictionary<string, object> titleArguments = null, object[] titleArguments = null,
Dictionary<string, object> textArguments = null, object[] textArguments = null,
Action onConfirm = null, Action onConfirm = null,
string confirmText = null, string confirmText = null,
Action onCancel = null, Action onCancel = null,

View File

@@ -238,7 +238,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
if (frameText != null) if (frameText != null)
{ {
var soundLength = new CachedTransform<double, string>(p => var soundLength = new CachedTransform<double, string>(p =>
FluentProvider.GetString(LengthInSeconds, FluentBundle.Arguments("length", Math.Round(p, 3)))); FluentProvider.GetString(LengthInSeconds, "length", Math.Round(p, 3)));
frameText.GetText = () => frameText.GetText = () =>
{ {

View File

@@ -66,7 +66,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
var panel = widget; var panel = widget;
panel.Get<ButtonWidget>("ABORT_BUTTON").OnClick = () => { CloseWindow(); onAbort(); }; panel.Get<ButtonWidget>("ABORT_BUTTON").OnClick = () => { CloseWindow(); onAbort(); };
var connectingDesc = FluentProvider.GetString(ConnectingToEndpoint, FluentBundle.Arguments("endpoint", endpoint)); var connectingDesc = FluentProvider.GetString(ConnectingToEndpoint, "endpoint", endpoint);
widget.Get<LabelWidget>("CONNECTING_DESC").GetText = () => connectingDesc; widget.Get<LabelWidget>("CONNECTING_DESC").GetText = () => connectingDesc;
} }
@@ -130,7 +130,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
onRetry(pass); onRetry(pass);
}; };
var connectingDescText = FluentProvider.GetString(CouldNotConnectToTarget, FluentBundle.Arguments("target", connection.Target)); var connectingDescText = FluentProvider.GetString(CouldNotConnectToTarget, "target", connection.Target);
widget.Get<LabelWidget>("CONNECTING_DESC").GetText = () => connectingDescText; widget.Get<LabelWidget>("CONNECTING_DESC").GetText = () => connectingDescText;
var connectionError = widget.Get<LabelWidget>("CONNECTION_ERROR"); var connectionError = widget.Get<LabelWidget>("CONNECTION_ERROR");

View File

@@ -454,7 +454,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
{ {
Actor = actor; Actor = actor;
this.handles = handles; this.handles = handles;
Text = FluentProvider.GetString(EditedActor, FluentBundle.Arguments("name", actor.Info.Name, "id", actor.ID)); Text = FluentProvider.GetString(EditedActor, "name", actor.Info.Name, "id", actor.ID);
} }
public void Execute() public void Execute()
@@ -466,7 +466,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
var after = Actor; var after = Actor;
if (before != after) if (before != after)
Text = FluentProvider.GetString(EditedActorId, FluentBundle.Arguments("name", after.Info.Name, "old-id", before.ID, "new-id", after.ID)); Text = FluentProvider.GetString(EditedActorId, "name", after.Info.Name, "old-id", before.ID, "new-id", after.ID);
} }
public void Do() public void Do()

View File

@@ -112,7 +112,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
var tooltip = a.TraitInfos<EditorOnlyTooltipInfo>().FirstOrDefault(ti => ti.EnabledByDefault) as TooltipInfoBase var tooltip = a.TraitInfos<EditorOnlyTooltipInfo>().FirstOrDefault(ti => ti.EnabledByDefault) as TooltipInfoBase
?? a.TraitInfos<TooltipInfo>().FirstOrDefault(ti => ti.EnabledByDefault); ?? a.TraitInfos<TooltipInfo>().FirstOrDefault(ti => ti.EnabledByDefault);
var actorType = FluentProvider.GetString(ActorTypeTooltip, FluentBundle.Arguments("actorType", a.Name)); var actorType = FluentProvider.GetString(ActorTypeTooltip, "actorType", a.Name);
var searchTerms = new List<string>() { a.Name }; var searchTerms = new List<string>() { a.Name };
if (tooltip != null) if (tooltip != null)

View File

@@ -58,7 +58,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
const string OverwriteSavePrompt = "dialog-overwrite-save.prompt"; const string OverwriteSavePrompt = "dialog-overwrite-save.prompt";
[FluentReference] [FluentReference]
const string OverwriteSaveAccpet = "dialog-overwrite-save.confirm"; const string OverwriteSaveAccept = "dialog-overwrite-save.confirm";
readonly Widget panel; readonly Widget panel;
readonly ScrollPanelWidget gameList; readonly ScrollPanelWidget gameList;
@@ -173,7 +173,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
ConfirmationDialogs.ButtonPrompt(modData, ConfirmationDialogs.ButtonPrompt(modData,
title: DeleteSaveTitle, title: DeleteSaveTitle,
text: DeleteSavePrompt, text: DeleteSavePrompt,
textArguments: FluentBundle.Arguments("save", Path.GetFileNameWithoutExtension(selectedSave)), textArguments: new object[] { "save", Path.GetFileNameWithoutExtension(selectedSave) },
onConfirm: () => onConfirm: () =>
{ {
Delete(selectedSave); Delete(selectedSave);
@@ -197,7 +197,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
ConfirmationDialogs.ButtonPrompt(modData, ConfirmationDialogs.ButtonPrompt(modData,
title: DeleteAllSavesTitle, title: DeleteAllSavesTitle,
text: DeleteAllSavesPrompt, text: DeleteAllSavesPrompt,
textArguments: FluentBundle.Arguments("count", games.Count), textArguments: new object[] { "count", games.Count },
onConfirm: () => onConfirm: () =>
{ {
foreach (var s in games.ToList()) foreach (var s in games.ToList())
@@ -293,7 +293,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
} }
catch (Exception ex) catch (Exception ex)
{ {
TextNotificationsManager.Debug(FluentProvider.GetString(SaveDeletionFailed, FluentBundle.Arguments("savePath", savePath))); TextNotificationsManager.Debug(FluentProvider.GetString(SaveDeletionFailed, "savePath", savePath));
Log.Write("debug", ex.ToString()); Log.Write("debug", ex.ToString());
return; return;
} }
@@ -373,9 +373,9 @@ namespace OpenRA.Mods.Common.Widgets.Logic
ConfirmationDialogs.ButtonPrompt(modData, ConfirmationDialogs.ButtonPrompt(modData,
title: OverwriteSaveTitle, title: OverwriteSaveTitle,
text: OverwriteSavePrompt, text: OverwriteSavePrompt,
textArguments: FluentBundle.Arguments("file", saveTextField.Text), textArguments: new object[] { "file", saveTextField.Text },
onConfirm: Inner, onConfirm: Inner,
confirmText: OverwriteSaveAccpet, confirmText: OverwriteSaveAccept,
onCancel: () => { }); onCancel: () => { });
} }
else else

View File

@@ -160,8 +160,8 @@ namespace OpenRA.Mods.Common.Widgets.Logic
ConfirmationDialogs.ButtonPrompt(modData, ConfirmationDialogs.ButtonPrompt(modData,
title: VoteKickTitle, title: VoteKickTitle,
text: botsCount > 0 ? VoteKickPromptBreakBots : VoteKickPrompt, text: botsCount > 0 ? VoteKickPromptBreakBots : VoteKickPrompt,
titleArguments: FluentBundle.Arguments("player", client.Name), titleArguments: new object[] { "player", client.Name },
textArguments: FluentBundle.Arguments("bots", botsCount), textArguments: new object[] { "bots", botsCount },
onConfirm: () => onConfirm: () =>
{ {
orderManager.IssueOrder(Order.Command($"vote_kick {client.Index} {true}")); orderManager.IssueOrder(Order.Command($"vote_kick {client.Index} {true}"));
@@ -176,8 +176,8 @@ namespace OpenRA.Mods.Common.Widgets.Logic
ConfirmationDialogs.ButtonPrompt(modData, ConfirmationDialogs.ButtonPrompt(modData,
title: VoteKickTitle, title: VoteKickTitle,
text: botsCount > 0 ? VoteKickPromptBreakBots : VoteKickPrompt, text: botsCount > 0 ? VoteKickPromptBreakBots : VoteKickPrompt,
titleArguments: FluentBundle.Arguments("player", client.Name), titleArguments: new object[] { "player", client.Name },
textArguments: FluentBundle.Arguments("bots", botsCount), textArguments: new object[] { "bots", botsCount },
onConfirm: () => onConfirm: () =>
{ {
orderManager.IssueOrder(Order.Command($"vote_kick {client.Index} {true}")); orderManager.IssueOrder(Order.Command($"vote_kick {client.Index} {true}"));
@@ -201,7 +201,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
ConfirmationDialogs.ButtonPrompt(modData, ConfirmationDialogs.ButtonPrompt(modData,
title: KickTitle, title: KickTitle,
text: KickPrompt, text: KickPrompt,
titleArguments: FluentBundle.Arguments("player", client.Name), titleArguments: new object[] { "player", client.Name },
onConfirm: () => onConfirm: () =>
{ {
orderManager.IssueOrder(Order.Command($"kick {client.Index} {false}")); orderManager.IssueOrder(Order.Command($"kick {client.Index} {false}"));
@@ -227,7 +227,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
{ {
var teamHeader = ScrollItemWidget.Setup(teamTemplate, () => false, () => { }); var teamHeader = ScrollItemWidget.Setup(teamTemplate, () => false, () => { });
var team = t.Key > 0 var team = t.Key > 0
? FluentProvider.GetString(TeamNumber, FluentBundle.Arguments("team", t.Key)) ? FluentProvider.GetString(TeamNumber, "team", t.Key)
: FluentProvider.GetString(NoTeam); : FluentProvider.GetString(NoTeam);
teamHeader.Get<LabelWidget>("TEAM").GetText = () => team; teamHeader.Get<LabelWidget>("TEAM").GetText = () => team;
var teamRating = teamHeader.Get<LabelWidget>("TEAM_SCORE"); var teamRating = teamHeader.Get<LabelWidget>("TEAM_SCORE");

View File

@@ -47,7 +47,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
var pausedText = FluentProvider.GetString(GameTimerLogic.Paused); var pausedText = FluentProvider.GetString(GameTimerLogic.Paused);
var maxSpeedText = FluentProvider.GetString(MaxSpeed); var maxSpeedText = FluentProvider.GetString(MaxSpeed);
var speedText = new CachedTransform<int, string>(p => var speedText = new CachedTransform<int, string>(p =>
FluentProvider.GetString(Speed, FluentBundle.Arguments("percentage", p))); FluentProvider.GetString(Speed, "percentage", p));
if (timer != null) if (timer != null)
{ {
@@ -79,7 +79,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
} }
var timerText = new CachedTransform<int, string>(p => var timerText = new CachedTransform<int, string>(p =>
FluentProvider.GetString(Complete, FluentBundle.Arguments("percentage", p))); FluentProvider.GetString(Complete, "percentage", p));
if (timer is LabelWithTooltipWidget timerTooltip) if (timer is LabelWithTooltipWidget timerTooltip)
{ {
var connection = orderManager.Connection as ReplayConnection; var connection = orderManager.Connection as ReplayConnection;

View File

@@ -54,12 +54,12 @@ namespace OpenRA.Mods.Common.Widgets.Logic.Ingame
// Check if selecting actors on the screen has selected new units // Check if selecting actors on the screen has selected new units
if (newSelection.Count > selection.Actors.Count) if (newSelection.Count > selection.Actors.Count)
TextNotificationsManager.AddFeedbackLine(SelectedUnitsAcrossScreen, FluentBundle.Arguments("units", newSelection.Count)); TextNotificationsManager.AddFeedbackLine(SelectedUnitsAcrossScreen, "units", newSelection.Count);
else else
{ {
// Select actors in the world that have highest selection priority // Select actors in the world that have highest selection priority
newSelection = SelectionUtils.SelectActorsInWorld(world, null, eligiblePlayers).SubsetWithHighestSelectionPriority(e.Modifiers).ToList(); newSelection = SelectionUtils.SelectActorsInWorld(world, null, eligiblePlayers).SubsetWithHighestSelectionPriority(e.Modifiers).ToList();
TextNotificationsManager.AddFeedbackLine(SelectedUnitsAcrossMap, FluentBundle.Arguments("units", newSelection.Count)); TextNotificationsManager.AddFeedbackLine(SelectedUnitsAcrossMap, "units", newSelection.Count);
} }
selection.Combine(world, newSelection, false, false); selection.Combine(world, newSelection, false, false);

View File

@@ -79,12 +79,12 @@ namespace OpenRA.Mods.Common.Widgets.Logic.Ingame
// Check if selecting actors on the screen has selected new units // Check if selecting actors on the screen has selected new units
if (newSelection.Count > selection.Actors.Count) if (newSelection.Count > selection.Actors.Count)
TextNotificationsManager.AddFeedbackLine(SelectedUnitsAcrossScreen, FluentBundle.Arguments("units", newSelection.Count)); TextNotificationsManager.AddFeedbackLine(SelectedUnitsAcrossScreen, "units", newSelection.Count);
else else
{ {
// Select actors in the world that have the same selection class as one of the already selected actors // Select actors in the world that have the same selection class as one of the already selected actors
newSelection = SelectionUtils.SelectActorsInWorld(world, selectedClasses, eligiblePlayers).ToList(); newSelection = SelectionUtils.SelectActorsInWorld(world, selectedClasses, eligiblePlayers).ToList();
TextNotificationsManager.AddFeedbackLine(SelectedUnitsAcrossMap, FluentBundle.Arguments("units", newSelection.Count)); TextNotificationsManager.AddFeedbackLine(SelectedUnitsAcrossMap, "units", newSelection.Count);
} }
selection.Combine(world, newSelection, true, false); selection.Combine(world, newSelection, true, false);

View File

@@ -45,7 +45,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
displayResources = playerResources.GetCashAndResources(); displayResources = playerResources.GetCashAndResources();
siloUsageTooltipCache = new CachedTransform<(int Resources, int Capacity), string>(x => siloUsageTooltipCache = new CachedTransform<(int Resources, int Capacity), string>(x =>
FluentProvider.GetString(SiloUsage, FluentBundle.Arguments("usage", x.Resources, "capacity", x.Capacity))); FluentProvider.GetString(SiloUsage, "usage", x.Resources, "capacity", x.Capacity));
cashLabel = widget.Get<LabelWithTooltipWidget>("CASH"); cashLabel = widget.Get<LabelWithTooltipWidget>("CASH");
cashLabel.GetTooltipText = () => siloUsageTooltip; cashLabel.GetTooltipText = () => siloUsageTooltip;
} }

View File

@@ -194,7 +194,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
return true; return true;
}; };
chatAvailableIn = new CachedTransform<int, string>(x => FluentProvider.GetString(ChatAvailability, FluentBundle.Arguments("seconds", x))); chatAvailableIn = new CachedTransform<int, string>(x => FluentProvider.GetString(ChatAvailability, "seconds", x));
if (!isMenuChat) if (!isMenuChat)
{ {

View File

@@ -494,7 +494,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
ConfirmationDialogs.ButtonPrompt(modData, ConfirmationDialogs.ButtonPrompt(modData,
title: ErrorMaxPlayerTitle, title: ErrorMaxPlayerTitle,
text: ErrorMaxPlayerPrompt, text: ErrorMaxPlayerPrompt,
textArguments: FluentBundle.Arguments("players", playerCount, "max", MapPlayers.MaximumPlayerCount), textArguments: new object[] { "players", playerCount, "max", MapPlayers.MaximumPlayerCount },
onConfirm: ShowMenu, onConfirm: ShowMenu,
confirmText: ErrorMaxPlayerAccept); confirmText: ErrorMaxPlayerAccept);

View File

@@ -39,9 +39,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
FluentProvider.GetString(Infinite) : FluentProvider.GetString(Infinite) :
powerManager.PowerProvided.ToString(NumberFormatInfo.CurrentInfo); powerManager.PowerProvided.ToString(NumberFormatInfo.CurrentInfo);
return FluentProvider.GetString( return FluentProvider.GetString(PowerUsage, "usage", usage.Current, "capacity", capacity);
PowerUsage,
FluentBundle.Arguments("usage", usage.Current, "capacity", capacity));
}); });
powerBar.GetBarColor = () => powerBar.GetBarColor = () =>

View File

@@ -41,11 +41,9 @@ namespace OpenRA.Mods.Common.Widgets.Logic
var tooltipTextCached = new CachedTransform<(int, int?), string>(((int Usage, int? Capacity) args) => var tooltipTextCached = new CachedTransform<(int, int?), string>(((int Usage, int? Capacity) args) =>
{ {
var capacity = args.Capacity == null ? unlimitedCapacity : args.Capacity.Value.ToString(NumberFormatInfo.CurrentInfo); var capacity = args.Capacity == null ? unlimitedCapacity : args.Capacity.Value.ToString(NumberFormatInfo.CurrentInfo);
return FluentProvider.GetString( return FluentProvider.GetString(PowerUsage,
PowerUsage, "usage", args.Usage.ToString(NumberFormatInfo.CurrentInfo),
FluentBundle.Arguments( "capacity", capacity);
"usage", args.Usage.ToString(NumberFormatInfo.CurrentInfo),
"capacity", capacity));
}); });
power.GetTooltipText = () => power.GetTooltipText = () =>

View File

@@ -28,12 +28,8 @@ namespace OpenRA.Mods.Common.Widgets.Logic
siloBar.GetProvided = () => playerResources.ResourceCapacity; siloBar.GetProvided = () => playerResources.ResourceCapacity;
siloBar.GetUsed = () => playerResources.Resources; siloBar.GetUsed = () => playerResources.Resources;
siloBar.TooltipTextCached = new CachedTransform<(float Current, float Capacity), string>(usage => siloBar.TooltipTextCached = new CachedTransform<(float Current, float Capacity), string>(
{ usage => FluentProvider.GetString(SiloUsage, "usage", usage.Current, "capacity", usage.Capacity));
return FluentProvider.GetString(
SiloUsage,
FluentBundle.Arguments("usage", usage.Current, "capacity", usage.Capacity));
});
siloBar.GetBarColor = () => siloBar.GetBarColor = () =>
{ {
if (playerResources.Resources == playerResources.ResourceCapacity) if (playerResources.Resources == playerResources.ResourceCapacity)

View File

@@ -121,7 +121,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
{ {
totalPlayers += t.Count(); totalPlayers += t.Count();
var label = noTeams ? FluentProvider.GetString(Players) : t.Key > 0 var label = noTeams ? FluentProvider.GetString(Players) : t.Key > 0
? FluentProvider.GetString(TeamNumber, FluentBundle.Arguments("team", t.Key)) ? FluentProvider.GetString(TeamNumber, "team", t.Key)
: FluentProvider.GetString(NoTeam); : FluentProvider.GetString(NoTeam);
groups.Add(label, t); groups.Add(label, t);

View File

@@ -286,7 +286,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
tt.IgnoreMouseOver = true; tt.IgnoreMouseOver = true;
var teamLabel = tt.Get<LabelWidget>("TEAM"); var teamLabel = tt.Get<LabelWidget>("TEAM");
var teamText = team.Key > 0 ? FluentProvider.GetString(TeamNumber, FluentBundle.Arguments("team", team.Key)) var teamText = team.Key > 0 ? FluentProvider.GetString(TeamNumber, "team", team.Key)
: FluentProvider.GetString(NoTeam); : FluentProvider.GetString(NoTeam);
teamLabel.GetText = () => teamText; teamLabel.GetText = () => teamText;
tt.Bounds.Width = teamLabel.Bounds.Width = Game.Renderer.Fonts[tt.Font].Measure(teamText).X; tt.Bounds.Width = teamLabel.Bounds.Width = Game.Renderer.Fonts[tt.Font].Measure(teamText).X;

View File

@@ -105,7 +105,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
var requiresSize = int2.Zero; var requiresSize = int2.Zero;
if (prereqs.Count > 0) if (prereqs.Count > 0)
{ {
var requiresText = FluentProvider.GetString(Requires, FluentBundle.Arguments("prequisites", prereqs.JoinWith(", "))); var requiresText = FluentProvider.GetString(Requires, "prequisites", prereqs.JoinWith(", "));
requiresLabel.GetText = () => requiresText; requiresLabel.GetText = () => requiresText;
requiresSize = requiresFont.Measure(requiresText); requiresSize = requiresFont.Measure(requiresText);
requiresLabel.Visible = true; requiresLabel.Visible = true;

View File

@@ -86,7 +86,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
var status = new CachedTransform<string, string>(s => WidgetUtils.TruncateText(s, statusLabel.Bounds.Width, statusFont)); var status = new CachedTransform<string, string>(s => WidgetUtils.TruncateText(s, statusLabel.Bounds.Width, statusFont));
statusLabel.GetText = () => status.Update(getStatusText()); statusLabel.GetText = () => status.Update(getStatusText());
var text = FluentProvider.GetString(Downloading, FluentBundle.Arguments("title", download.Title)); var text = FluentProvider.GetString(Downloading, "title", download.Title);
panel.Get<LabelWidget>("TITLE").GetText = () => text; panel.Get<LabelWidget>("TITLE").GetText = () => text;
ShowDownloadDialog(); ShowDownloadDialog();
@@ -117,7 +117,9 @@ namespace OpenRA.Mods.Common.Widgets.Logic
dataSuffix = SizeSuffixes[mag]; dataSuffix = SizeSuffixes[mag];
getStatusText = () => FluentProvider.GetString(DownloadingFrom, getStatusText = () => FluentProvider.GetString(DownloadingFrom,
FluentBundle.Arguments("host", host, "received", $"{dataReceived:0.00}", "suffix", dataSuffix)); "host", host,
"received", $"{dataReceived:0.00}",
"suffix", dataSuffix);
progressBar.Indeterminate = true; progressBar.Indeterminate = true;
} }
else else
@@ -128,8 +130,11 @@ namespace OpenRA.Mods.Common.Widgets.Logic
dataSuffix = SizeSuffixes[mag]; dataSuffix = SizeSuffixes[mag];
getStatusText = () => FluentProvider.GetString(DownloadingFromProgress, getStatusText = () => FluentProvider.GetString(DownloadingFromProgress,
FluentBundle.Arguments("host", host, "received", $"{dataReceived:0.00}", "total", $"{dataTotal:0.00}", "host", host,
"suffix", dataSuffix, "progress", progressPercentage)); "received", $"{dataReceived:0.00}",
"total", $"{dataTotal:0.00}",
"suffix", dataSuffix,
"progress", progressPercentage);
progressBar.Indeterminate = false; progressBar.Indeterminate = false;
} }
@@ -232,7 +237,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
continue; continue;
} }
OnExtractProgress(FluentProvider.GetString(ExtractingEntry, FluentBundle.Arguments("entry", kv.Value))); OnExtractProgress(FluentProvider.GetString(ExtractingEntry, "entry", kv.Value));
Log.Write("install", "Extracting " + kv.Value); Log.Write("install", "Extracting " + kv.Value);
var targetPath = Platform.ResolvePath(kv.Key); var targetPath = Platform.ResolvePath(kv.Key);
Directory.CreateDirectory(Path.GetDirectoryName(targetPath)); Directory.CreateDirectory(Path.GetDirectoryName(targetPath));

View File

@@ -62,7 +62,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
const string CheckInstallLog = "label-check-install-log"; const string CheckInstallLog = "label-check-install-log";
[FluentReference("filename")] [FluentReference("filename")]
public const string Extracing = "label-extracting-filename"; public const string Extracting = "label-extracting-filename";
[FluentReference("filename", "progress")] [FluentReference("filename", "progress")]
public const string ExtractingProgress = "label-extracting-filename-progress"; public const string ExtractingProgress = "label-extracting-filename-progress";
@@ -168,7 +168,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
{ {
foreach (var kv in sources) foreach (var kv in sources)
{ {
message = FluentProvider.GetString(SearchingSourceFor, FluentBundle.Arguments("title", kv.Value.Title)); message = FluentProvider.GetString(SearchingSourceFor, "title", kv.Value.Title);
var sourceResolver = kv.Value.ObjectCreator.CreateObject<ISourceResolver>($"{kv.Value.Type.Value}SourceResolver"); var sourceResolver = kv.Value.ObjectCreator.CreateObject<ISourceResolver>($"{kv.Value.Type.Value}SourceResolver");

View File

@@ -22,7 +22,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
[ObjectCreator.UseCtor] [ObjectCreator.UseCtor]
public KickClientLogic(Widget widget, string clientName, Action<bool> okPressed, Action cancelPressed) public KickClientLogic(Widget widget, string clientName, Action<bool> okPressed, Action cancelPressed)
{ {
var kickMessage = FluentProvider.GetString(KickClient, FluentBundle.Arguments("player", clientName)); var kickMessage = FluentProvider.GetString(KickClient, "player", clientName);
widget.Get<LabelWidget>("TITLE").GetText = () => kickMessage; widget.Get<LabelWidget>("TITLE").GetText = () => kickMessage;
var tempBan = false; var tempBan = false;

View File

@@ -22,7 +22,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
[ObjectCreator.UseCtor] [ObjectCreator.UseCtor]
public KickSpectatorsLogic(Widget widget, int clientCount, Action okPressed, Action cancelPressed) public KickSpectatorsLogic(Widget widget, int clientCount, Action okPressed, Action cancelPressed)
{ {
var kickMessage = FluentProvider.GetString(KickSpectators, FluentBundle.Arguments("count", clientCount)); var kickMessage = FluentProvider.GetString(KickSpectators, "count", clientCount);
widget.Get<LabelWidget>("TEXT").GetText = () => kickMessage; widget.Get<LabelWidget>("TEXT").GetText = () => kickMessage;
widget.Get<ButtonWidget>("OK_BUTTON").OnClick = () => widget.Get<ButtonWidget>("OK_BUTTON").OnClick = () =>

View File

@@ -323,7 +323,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
{ {
var teamOptions = Enumerable.Range(2, teamCount - 1).Reverse().Select(d => new DropDownOption var teamOptions = Enumerable.Range(2, teamCount - 1).Reverse().Select(d => new DropDownOption
{ {
Title = FluentProvider.GetString(NumberTeams, FluentBundle.Arguments("count", d)), Title = FluentProvider.GetString(NumberTeams, "count", d),
IsSelected = () => false, IsSelected = () => false,
OnClick = () => orderManager.IssueOrder(Order.Command($"assignteams {d}")) OnClick = () => orderManager.IssueOrder(Order.Command($"assignteams {d}"))
}).ToList(); }).ToList();
@@ -539,7 +539,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
chatTextField.OnEscKey = _ => chatTextField.YieldKeyboardFocus(); chatTextField.OnEscKey = _ => chatTextField.YieldKeyboardFocus();
chatAvailableIn = new CachedTransform<int, string>(x => FluentProvider.GetString(ChatAvailability, FluentBundle.Arguments("seconds", x))); chatAvailableIn = new CachedTransform<int, string>(x => FluentProvider.GetString(ChatAvailability, "seconds", x));
chatDisabled = FluentProvider.GetString(ChatDisabled); chatDisabled = FluentProvider.GetString(ChatDisabled);
lobbyChatPanel = lobby.Get<ScrollPanelWidget>("CHAT_DISPLAY"); lobbyChatPanel = lobby.Get<ScrollPanelWidget>("CHAT_DISPLAY");

View File

@@ -106,7 +106,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
} }
var authorCache = new CachedTransform<string, string>( var authorCache = new CachedTransform<string, string>(
text => FluentProvider.GetString(CreatedBy, FluentBundle.Arguments("author", text))); text => FluentProvider.GetString(CreatedBy, "author", text));
Widget SetupAuthorAndMapType(Widget parent) Widget SetupAuthorAndMapType(Widget parent)
{ {
@@ -169,9 +169,9 @@ namespace OpenRA.Mods.Common.Widgets.Logic
// Server does not provide the total file length. // Server does not provide the total file length.
if (map.DownloadPercentage == 0) if (map.DownloadPercentage == 0)
return FluentProvider.GetString(Downloading, FluentBundle.Arguments("size", map.DownloadBytes / 1024)); return FluentProvider.GetString(Downloading, "size", map.DownloadBytes / 1024);
return FluentProvider.GetString(DownloadingPercentage, FluentBundle.Arguments("size", map.DownloadBytes / 1024, "progress", map.DownloadPercentage)); return FluentProvider.GetString(DownloadingPercentage, "size", map.DownloadBytes / 1024, "progress", map.DownloadPercentage);
}; };
return parent; return parent;

View File

@@ -49,7 +49,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
var labelText = ""; var labelText = "";
string playerFaction = null; string playerFaction = null;
var playerTeam = -1; var playerTeam = -1;
teamMessage = new CachedTransform<int, string>(t => FluentProvider.GetString(TeamNumber, FluentBundle.Arguments("team", t))); teamMessage = new CachedTransform<int, string>(t => FluentProvider.GetString(TeamNumber, "team", t));
var disabledSpawn = FluentProvider.GetString(DisabledSpawn); var disabledSpawn = FluentProvider.GetString(DisabledSpawn);
var availableSpawn = FluentProvider.GetString(AvailableSpawn); var availableSpawn = FluentProvider.GetString(AvailableSpawn);

View File

@@ -346,7 +346,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
catch (Exception e) catch (Exception e)
{ {
Game.RunAfterTick(() => // run on the main thread Game.RunAfterTick(() => // run on the main thread
SetNewsStatus(FluentProvider.GetString(NewsRetrivalFailed, FluentBundle.Arguments("message", e.Message)))); SetNewsStatus(FluentProvider.GetString(NewsRetrivalFailed, "message", e.Message)));
} }
}); });
} }
@@ -417,7 +417,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
} }
catch (Exception ex) catch (Exception ex)
{ {
SetNewsStatus(FluentProvider.GetString(NewsParsingFailed, FluentBundle.Arguments("message", ex.Message))); SetNewsStatus(FluentProvider.GetString(NewsParsingFailed, "message", ex.Message));
} }
return null; return null;
@@ -438,9 +438,9 @@ namespace OpenRA.Mods.Common.Widgets.Logic
titleLabel.GetText = () => item.Title; titleLabel.GetText = () => item.Title;
var authorDateTimeLabel = newsItem.Get<LabelWidget>("AUTHOR_DATETIME"); var authorDateTimeLabel = newsItem.Get<LabelWidget>("AUTHOR_DATETIME");
var authorDateTime = FluentProvider.GetString(AuthorDateTime, FluentBundle.Arguments( var authorDateTime = FluentProvider.GetString(AuthorDateTime,
"author", item.Author, "author", item.Author,
"datetime", item.DateTime.ToLocalTime().ToString(CultureInfo.CurrentCulture))); "datetime", item.DateTime.ToLocalTime().ToString(CultureInfo.CurrentCulture));
authorDateTimeLabel.GetText = () => authorDateTime; authorDateTimeLabel.GetText = () => authorDateTime;

View File

@@ -205,9 +205,9 @@ namespace OpenRA.Mods.Common.Widgets.Logic
var remoteMapText = new CachedTransform<(int Searching, int Unavailable), string>(counts => var remoteMapText = new CachedTransform<(int Searching, int Unavailable), string>(counts =>
{ {
if (counts.Searching > 0) if (counts.Searching > 0)
return FluentProvider.GetString(MapSearchingCount, FluentBundle.Arguments("count", counts.Searching)); return FluentProvider.GetString(MapSearchingCount, "count", counts.Searching);
return FluentProvider.GetString(MapUnavailableCount, FluentBundle.Arguments("count", counts.Unavailable)); return FluentProvider.GetString(MapUnavailableCount, "count", counts.Unavailable);
}); });
remoteMapLabel.IsVisible = () => remoteMapPool != null && (remoteSearching > 0 || remoteUnavailable > 0); remoteMapLabel.IsVisible = () => remoteMapPool != null && (remoteSearching > 0 || remoteUnavailable > 0);
@@ -458,13 +458,13 @@ namespace OpenRA.Mods.Common.Widgets.Logic
if (type != null) if (type != null)
details = type + " "; details = type + " ";
details += FluentProvider.GetString(Players, FluentBundle.Arguments("players", preview.PlayerCount)); details += FluentProvider.GetString(Players, "players", preview.PlayerCount);
detailsWidget.GetText = () => details; detailsWidget.GetText = () => details;
} }
var authorWidget = item.GetOrNull<LabelWithTooltipWidget>("AUTHOR"); var authorWidget = item.GetOrNull<LabelWithTooltipWidget>("AUTHOR");
if (authorWidget != null && !string.IsNullOrEmpty(preview.Author)) if (authorWidget != null && !string.IsNullOrEmpty(preview.Author))
WidgetUtils.TruncateLabelToTooltip(authorWidget, FluentProvider.GetString(CreatedBy, FluentBundle.Arguments("author", preview.Author))); WidgetUtils.TruncateLabelToTooltip(authorWidget, FluentProvider.GetString(CreatedBy, "author", preview.Author));
var sizeWidget = item.GetOrNull<LabelWidget>("SIZE"); var sizeWidget = item.GetOrNull<LabelWidget>("SIZE");
if (sizeWidget != null) if (sizeWidget != null)
@@ -502,7 +502,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
} }
catch (Exception ex) catch (Exception ex)
{ {
TextNotificationsManager.Debug(FluentProvider.GetString(MapDeletionFailed, FluentBundle.Arguments("map", map))); TextNotificationsManager.Debug(FluentProvider.GetString(MapDeletionFailed, "map", map));
Log.Write("debug", ex.ToString()); Log.Write("debug", ex.ToString());
} }
@@ -514,7 +514,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
ConfirmationDialogs.ButtonPrompt(modData, ConfirmationDialogs.ButtonPrompt(modData,
title: DeleteMapTitle, title: DeleteMapTitle,
text: DeleteMapPrompt, text: DeleteMapPrompt,
textArguments: FluentBundle.Arguments("title", modData.MapCache[map].Title), textArguments: new object[] { "title", modData.MapCache[map].Title },
onConfirm: () => onConfirm: () =>
{ {
var newUid = DeleteMap(map); var newUid = DeleteMap(map);

View File

@@ -365,7 +365,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
var nameFont = Game.Renderer.Fonts[nameLabel.Font]; var nameFont = Game.Renderer.Fonts[nameLabel.Font];
var controller = orderManager.LobbyInfo.Clients.FirstOrDefault(c => c.Index == client.BotControllerClientIndex); var controller = orderManager.LobbyInfo.Clients.FirstOrDefault(c => c.Index == client.BotControllerClientIndex);
if (controller != null) if (controller != null)
nameLabel.GetText = () => FluentProvider.GetString(BotManagedBy, FluentBundle.Arguments("name", controller.Name)); nameLabel.GetText = () => FluentProvider.GetString(BotManagedBy, "name", controller.Name);
widget.Bounds.Width = nameFont.Measure(nameLabel.GetText()).X + 2 * nameLabel.Bounds.Left; widget.Bounds.Width = nameFont.Measure(nameLabel.GetText()).X + 2 * nameLabel.Bounds.Left;
} }

View File

@@ -182,7 +182,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
}); });
var replayDuration = new CachedTransform<ReplayMetadata, string>(r => var replayDuration = new CachedTransform<ReplayMetadata, string>(r =>
FluentProvider.GetString(Duration, FluentBundle.Arguments("time", WidgetUtils.FormatTimeSeconds((int)selectedReplay.GameInfo.Duration.TotalSeconds)))); FluentProvider.GetString(Duration, "time", WidgetUtils.FormatTimeSeconds((int)selectedReplay.GameInfo.Duration.TotalSeconds)));
panel.Get<LabelWidget>("DURATION").GetText = () => replayDuration.Update(selectedReplay); panel.Get<LabelWidget>("DURATION").GetText = () => replayDuration.Update(selectedReplay);
SetupFilters(); SetupFilters();
@@ -507,7 +507,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
ConfirmationDialogs.ButtonPrompt(modData, ConfirmationDialogs.ButtonPrompt(modData,
title: DeleteReplayTitle, title: DeleteReplayTitle,
text: DeleteReplayPrompt, text: DeleteReplayPrompt,
textArguments: FluentBundle.Arguments("replay", Path.GetFileNameWithoutExtension(r.FilePath)), textArguments: new object[] { "replay", Path.GetFileNameWithoutExtension(r.FilePath) },
onConfirm: () => onConfirm: () =>
{ {
DeleteReplay(r); DeleteReplay(r);
@@ -545,7 +545,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
ConfirmationDialogs.ButtonPrompt(modData, ConfirmationDialogs.ButtonPrompt(modData,
title: DeleteAllReplaysTitle, title: DeleteAllReplaysTitle,
text: DeleteAllReplaysPrompt, text: DeleteAllReplaysPrompt,
textArguments: FluentBundle.Arguments("count", list.Count), textArguments: new object[] { "count", list.Count },
onConfirm: () => onConfirm: () =>
{ {
foreach (var replayMetadata in list) foreach (var replayMetadata in list)
@@ -584,7 +584,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
} }
catch (Exception ex) catch (Exception ex)
{ {
TextNotificationsManager.Debug(FluentProvider.GetString(ReplayDeletionFailed, FluentBundle.Arguments("file", replay.FilePath))); TextNotificationsManager.Debug(FluentProvider.GetString(ReplayDeletionFailed, "file", replay.FilePath));
Log.Write("debug", ex.ToString()); Log.Write("debug", ex.ToString());
return; return;
} }
@@ -725,7 +725,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
foreach (var p in players) foreach (var p in players)
{ {
var label = noTeams ? FluentProvider.GetString(Players) : p.Key > 0 var label = noTeams ? FluentProvider.GetString(Players) : p.Key > 0
? FluentProvider.GetString(TeamNumber, FluentBundle.Arguments("team", p.Key)) ? FluentProvider.GetString(TeamNumber, "team", p.Key)
: FluentProvider.GetString(NoTeam); : FluentProvider.GetString(NoTeam);
teams.Add(label, p); teams.Add(label, p);

View File

@@ -10,7 +10,6 @@
#endregion #endregion
using System; using System;
using System.Collections.Generic;
using OpenRA.FileFormats; using OpenRA.FileFormats;
namespace OpenRA.Mods.Common.Widgets.Logic namespace OpenRA.Mods.Common.Widgets.Logic
@@ -48,32 +47,32 @@ namespace OpenRA.Mods.Common.Widgets.Logic
onCancel ??= DoNothing; onCancel ??= DoNothing;
if (replayMeta == null) if (replayMeta == null)
return IncompatibleReplayDialog(IncompatibleReplayPrompt, null, modData, onCancel); return IncompatibleReplayDialog(modData, onCancel, IncompatibleReplayPrompt);
var version = replayMeta.GameInfo.Version; var version = replayMeta.GameInfo.Version;
if (version == null) if (version == null)
return IncompatibleReplayDialog(UnknownVersion, null, modData, onCancel); return IncompatibleReplayDialog(modData, onCancel, UnknownVersion);
var mod = replayMeta.GameInfo.Mod; var mod = replayMeta.GameInfo.Mod;
if (mod == null) if (mod == null)
return IncompatibleReplayDialog(UnknownMod, null, modData, onCancel); return IncompatibleReplayDialog(modData, onCancel, UnknownMod);
if (!Game.Mods.ContainsKey(mod)) if (!Game.Mods.ContainsKey(mod))
return IncompatibleReplayDialog(UnvailableMod, FluentBundle.Arguments("mod", mod), modData, onCancel); return IncompatibleReplayDialog(modData, onCancel, UnvailableMod, "mod", mod);
if (Game.Mods[mod].Metadata.Version != version) if (Game.Mods[mod].Metadata.Version != version)
return IncompatibleReplayDialog(IncompatibleVersion, FluentBundle.Arguments("version", version), modData, onCancel); return IncompatibleReplayDialog(modData, onCancel, IncompatibleVersion, "version", version);
if (replayMeta.GameInfo.MapPreview.Status != MapStatus.Available) if (replayMeta.GameInfo.MapPreview.Status != MapStatus.Available)
return IncompatibleReplayDialog(UnvailableMap, FluentBundle.Arguments("map", replayMeta.GameInfo.MapUid), modData, onCancel); return IncompatibleReplayDialog(modData, onCancel, UnvailableMap, "map", replayMeta.GameInfo.MapUid);
return true; return true;
} }
static bool IncompatibleReplayDialog(string text, Dictionary<string, object> textArguments, ModData modData, Action onCancel) static bool IncompatibleReplayDialog(ModData modData, Action onCancel, string text, params object[] args)
{ {
ConfirmationDialogs.ButtonPrompt( ConfirmationDialogs.ButtonPrompt(
modData, IncompatibleReplayTitle, text, textArguments: textArguments, onCancel: onCancel, cancelText: IncompatibleReplayAccept); modData, IncompatibleReplayTitle, text, textArguments: args, onCancel: onCancel, cancelText: IncompatibleReplayAccept);
return false; return false;
} }
} }

View File

@@ -239,14 +239,13 @@ namespace OpenRA.Mods.Common.Widgets.Logic
} }
catch (System.Net.Sockets.SocketException e) catch (System.Net.Sockets.SocketException e)
{ {
var message = FluentProvider.GetString(ServerCreationFailedPrompt, FluentBundle.Arguments("port", Game.Settings.Server.ListenPort)); var message = FluentProvider.GetString(ServerCreationFailedPrompt, "port", Game.Settings.Server.ListenPort);
// AddressAlreadyInUse (WSAEADDRINUSE) // AddressAlreadyInUse (WSAEADDRINUSE)
if (e.ErrorCode == 10048) if (e.ErrorCode == 10048)
message += "\n" + FluentProvider.GetString(ServerCreationFailedPortUsed); message += "\n" + FluentProvider.GetString(ServerCreationFailedPortUsed);
else else
message += "\n" + FluentProvider.GetString(ServerCreationFailedError, message += "\n" + FluentProvider.GetString(ServerCreationFailedError, "message", e.Message, "code", e.ErrorCode);
FluentBundle.Arguments("message", e.Message, "code", e.ErrorCode));
ConfirmationDialogs.ButtonPrompt(modData, ServerCreationFailedTitle, message, ConfirmationDialogs.ButtonPrompt(modData, ServerCreationFailedTitle, message,
onCancel: () => { }, cancelText: ServerCreationFailedCancel); onCancel: () => { }, cancelText: ServerCreationFailedCancel);

View File

@@ -164,11 +164,11 @@ namespace OpenRA.Mods.Common.Widgets.Logic
mapStatusSearching = FluentProvider.GetString(MapStatusSearching); mapStatusSearching = FluentProvider.GetString(MapStatusSearching);
mapClassificationUnknown = FluentProvider.GetString(MapClassificationUnknown); mapClassificationUnknown = FluentProvider.GetString(MapClassificationUnknown);
players = new CachedTransform<int, string>(i => FluentProvider.GetString(PlayersLabel, FluentBundle.Arguments("players", i))); players = new CachedTransform<int, string>(i => FluentProvider.GetString(PlayersLabel, "players", i));
bots = new CachedTransform<int, string>(i => FluentProvider.GetString(BotsLabel, FluentBundle.Arguments("bots", i))); bots = new CachedTransform<int, string>(i => FluentProvider.GetString(BotsLabel, "bots", i));
spectators = new CachedTransform<int, string>(i => FluentProvider.GetString(SpectatorsLabel, FluentBundle.Arguments("spectators", i))); spectators = new CachedTransform<int, string>(i => FluentProvider.GetString(SpectatorsLabel, "spectators", i));
minutes = new CachedTransform<double, string>(i => FluentProvider.GetString(InProgress, FluentBundle.Arguments("minutes", i))); minutes = new CachedTransform<double, string>(i => FluentProvider.GetString(InProgress, "minutes", i));
passwordProtected = FluentProvider.GetString(PasswordProtected); passwordProtected = FluentProvider.GetString(PasswordProtected);
waitingForPlayers = FluentProvider.GetString(WaitingForPlayers); waitingForPlayers = FluentProvider.GetString(WaitingForPlayers);
serverShuttingDown = FluentProvider.GetString(ServerShuttingDown); serverShuttingDown = FluentProvider.GetString(ServerShuttingDown);
@@ -318,7 +318,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
var playersLabel = widget.GetOrNull<LabelWidget>("PLAYER_COUNT"); var playersLabel = widget.GetOrNull<LabelWidget>("PLAYER_COUNT");
if (playersLabel != null) if (playersLabel != null)
{ {
var playersText = new CachedTransform<int, string>(p => FluentProvider.GetString(PlayersOnline, FluentBundle.Arguments("players", p))); var playersText = new CachedTransform<int, string>(p => FluentProvider.GetString(PlayersOnline, "players", p));
playersLabel.IsVisible = () => playerCount != 0; playersLabel.IsVisible = () => playerCount != 0;
playersLabel.GetText = () => playersText.Update(playerCount); playersLabel.GetText = () => playersText.Update(playerCount);
} }
@@ -582,7 +582,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
foreach (var p in players) foreach (var p in players)
{ {
var label = noTeams ? FluentProvider.GetString(Players) : p.Key > 0 var label = noTeams ? FluentProvider.GetString(Players) : p.Key > 0
? FluentProvider.GetString(TeamNumber, FluentBundle.Arguments("team", p.Key)) ? FluentProvider.GetString(TeamNumber, "team", p.Key)
: FluentProvider.GetString(NoTeam); : FluentProvider.GetString(NoTeam);
teams.Add(label, p); teams.Add(label, p);
} }
@@ -765,7 +765,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
if (game.Clients.Length > 10) if (game.Clients.Length > 10)
displayClients = displayClients displayClients = displayClients
.Take(9) .Take(9)
.Append(FluentProvider.GetString(OtherPlayers, FluentBundle.Arguments("players", game.Clients.Length - 9))); .Append(FluentProvider.GetString(OtherPlayers, "players", game.Clients.Length - 9));
var tooltip = displayClients.JoinWith("\n"); var tooltip = displayClients.JoinWith("\n");
players.GetTooltipText = () => tooltip; players.GetTooltipText = () => tooltip;

View File

@@ -171,7 +171,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
var displaySelectionDropDown = panel.Get<DropDownButtonWidget>("DISPLAY_SELECTION_DROPDOWN"); var displaySelectionDropDown = panel.Get<DropDownButtonWidget>("DISPLAY_SELECTION_DROPDOWN");
displaySelectionDropDown.OnMouseDown = _ => ShowDisplaySelectionDropdown(displaySelectionDropDown, ds); displaySelectionDropDown.OnMouseDown = _ => ShowDisplaySelectionDropdown(displaySelectionDropDown, ds);
var displaySelectionLabel = new CachedTransform<int, string>(i => FluentProvider.GetString(Display, FluentBundle.Arguments("number", i + 1))); var displaySelectionLabel = new CachedTransform<int, string>(i => FluentProvider.GetString(Display, "number", i + 1));
displaySelectionDropDown.GetText = () => displaySelectionLabel.Update(ds.VideoDisplay); displaySelectionDropDown.GetText = () => displaySelectionLabel.Update(ds.VideoDisplay);
displaySelectionDropDown.IsDisabled = () => Game.Renderer.DisplayCount < 2; displaySelectionDropDown.IsDisabled = () => Game.Renderer.DisplayCount < 2;
@@ -242,7 +242,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
var frameLimitGamespeedCheckbox = panel.Get<CheckboxWidget>("FRAME_LIMIT_GAMESPEED_CHECKBOX"); var frameLimitGamespeedCheckbox = panel.Get<CheckboxWidget>("FRAME_LIMIT_GAMESPEED_CHECKBOX");
var frameLimitCheckbox = panel.Get<CheckboxWidget>("FRAME_LIMIT_CHECKBOX"); var frameLimitCheckbox = panel.Get<CheckboxWidget>("FRAME_LIMIT_CHECKBOX");
var frameLimitLabel = new CachedTransform<int, string>(fps => FluentProvider.GetString(FrameLimiter, FluentBundle.Arguments("fps", fps))); var frameLimitLabel = new CachedTransform<int, string>(fps => FluentProvider.GetString(FrameLimiter, "fps", fps));
frameLimitCheckbox.GetText = () => frameLimitLabel.Update(ds.MaxFramerate); frameLimitCheckbox.GetText = () => frameLimitLabel.Update(ds.MaxFramerate);
frameLimitCheckbox.IsDisabled = () => ds.CapFramerateToGameFps; frameLimitCheckbox.IsDisabled = () => ds.CapFramerateToGameFps;

View File

@@ -229,16 +229,16 @@ namespace OpenRA.Mods.Common.Widgets.Logic
duplicateNotice.IsVisible = () => !isHotkeyValid; duplicateNotice.IsVisible = () => !isHotkeyValid;
var duplicateNoticeText = new CachedTransform<HotkeyDefinition, string>(hd => var duplicateNoticeText = new CachedTransform<HotkeyDefinition, string>(hd =>
hd != null ? hd != null ?
FluentProvider.GetString(DuplicateNotice, FluentBundle.Arguments("key", hd.Description, FluentProvider.GetString(DuplicateNotice,
"context", hd.Contexts.First(c => selectedHotkeyDefinition.Contexts.Contains(c)))) : "key", hd.Description,
""); "context", hd.Contexts.First(c => selectedHotkeyDefinition.Contexts.Contains(c))) : "");
duplicateNotice.GetText = () => duplicateNoticeText.Update(duplicateHotkeyDefinition); duplicateNotice.GetText = () => duplicateNoticeText.Update(duplicateHotkeyDefinition);
var originalNotice = panel.Get<LabelWidget>("ORIGINAL_NOTICE"); var originalNotice = panel.Get<LabelWidget>("ORIGINAL_NOTICE");
originalNotice.TextColor = ChromeMetrics.Get<Color>("NoticeInfoColor"); originalNotice.TextColor = ChromeMetrics.Get<Color>("NoticeInfoColor");
originalNotice.IsVisible = () => isHotkeyValid && !isHotkeyDefault; originalNotice.IsVisible = () => isHotkeyValid && !isHotkeyDefault;
var originalNoticeText = new CachedTransform<HotkeyDefinition, string>(hd => var originalNoticeText = new CachedTransform<HotkeyDefinition, string>(hd =>
FluentProvider.GetString(OriginalNotice, FluentBundle.Arguments("key", hd?.Default.DisplayString()))); FluentProvider.GetString(OriginalNotice, "key", hd?.Default.DisplayString()));
originalNotice.GetText = () => originalNoticeText.Update(selectedHotkeyDefinition); originalNotice.GetText = () => originalNoticeText.Update(selectedHotkeyDefinition);
var readonlyNotice = panel.Get<LabelWidget>("READONLY_NOTICE"); var readonlyNotice = panel.Get<LabelWidget>("READONLY_NOTICE");

View File

@@ -143,7 +143,7 @@ namespace OpenRA.Mods.Common.Widgets.Logic
ConfirmationDialogs.ButtonPrompt(modData, ConfirmationDialogs.ButtonPrompt(modData,
title: ResetTitle, title: ResetTitle,
text: ResetPrompt, text: ResetPrompt,
titleArguments: FluentBundle.Arguments("panel", panels[activePanel]), titleArguments: new object[] { "panel", panels[activePanel] },
onConfirm: Reset, onConfirm: Reset,
confirmText: ResetAccept, confirmText: ResetAccept,
onCancel: () => { }, onCancel: () => { },

View File

@@ -59,7 +59,10 @@ namespace OpenRA.Mods.Common.Widgets
{ {
var self = p.Instances[0].Self; var self = p.Instances[0].Self;
var time = WidgetUtils.FormatTime(p.RemainingTicks, false, self.World.Timestep); var time = WidgetUtils.FormatTime(p.RemainingTicks, false, self.World.Timestep);
var text = FluentProvider.GetString(Format, FluentBundle.Arguments("player", self.Owner.ResolvedPlayerName, "support-power", p.Name, "time", time)); var text = FluentProvider.GetString(Format,
"player", self.Owner.ResolvedPlayerName,
"support-power", p.Name,
"time", time);
var color = !p.Ready || Game.LocalTick % 50 < 25 ? self.OwnerColor() : Color.White; var color = !p.Ready || Game.LocalTick % 50 < 25 ? self.OwnerColor() : Color.White;

View File

@@ -28,9 +28,9 @@ label-players = {$player ->
public void TestOne() public void TestOne()
{ {
var bundle = new FluentBundle("en", pluralForms, e => Console.WriteLine(e.Message)); var bundle = new FluentBundle("en", pluralForms, e => Console.WriteLine(e.Message));
var label = bundle.GetString("label-players", FluentBundle.Arguments("player", 1)); var label = bundle.GetString("label-players", new object[] { "player", 1 });
Assert.That("One player", Is.EqualTo(label)); Assert.That("One player", Is.EqualTo(label));
label = bundle.GetString("label-players", FluentBundle.Arguments("player", 2)); label = bundle.GetString("label-players", new object[] { "player", 2 });
Assert.That("2 players", Is.EqualTo(label)); Assert.That("2 players", Is.EqualTo(label));
} }
} }