public GlobalChatLogic(Widget widget) { historyPanel = widget.Get <ScrollPanelWidget>("HISTORY_PANEL"); chatTemplate = historyPanel.Get <ContainerWidget>("CHAT_TEMPLATE"); nicknamePanel = widget.Get <ScrollPanelWidget>("NICKNAME_PANEL"); nicknameTemplate = nicknamePanel.Get("NICKNAME_TEMPLATE"); var textColor = ChromeMetrics.Get <Color>("GlobalChatTextColor"); var textLabel = chatTemplate.Get <LabelWidget>("TEXT"); textLabel.GetColor = () => textColor; historyPanel.Bind(Game.GlobalChat.History, MakeHistoryWidget, HistoryWidgetEquals, true); nicknamePanel.Bind(Game.GlobalChat.Users, MakeUserWidget, UserWidgetEquals, false); inputBox = widget.Get <TextFieldWidget>("CHAT_TEXTFIELD"); inputBox.IsDisabled = () => Game.GlobalChat.ConnectionStatus != ChatConnectionStatus.Joined; inputBox.OnEnterKey = EnterPressed; // IRC protocol limits messages to 510 characters + CRLF inputBox.MaxLength = 510; var nickName = Game.GlobalChat.SanitizedName(Game.Settings.Player.Name); var nicknameBox = widget.Get <TextFieldWidget>("NICKNAME_TEXTFIELD"); nicknameBox.Text = nickName; nicknameBox.OnTextEdited = () => { nicknameBox.Text = Game.GlobalChat.SanitizedName(nicknameBox.Text); }; var connectPanel = widget.Get("GLOBALCHAT_CONNECT_PANEL"); connectPanel.IsVisible = () => Game.GlobalChat.ConnectionStatus == ChatConnectionStatus.Disconnected; var disconnectButton = widget.Get <ButtonWidget>("DISCONNECT_BUTTON"); disconnectButton.OnClick = Game.GlobalChat.Disconnect; var connectAutomaticallyCheckBox = connectPanel.Get <CheckboxWidget>("CONNECT_AUTOMATICALLY_CHECKBOX"); connectAutomaticallyCheckBox.IsChecked = () => Game.Settings.Chat.ConnectAutomatically; connectAutomaticallyCheckBox.OnClick = () => { Game.Settings.Chat.ConnectAutomatically ^= true; Game.Settings.Save(); }; var connectButton = connectPanel.Get <ButtonWidget>("CONNECT_BUTTON"); connectButton.IsDisabled = () => !Game.GlobalChat.IsValidNickname(nicknameBox.Text); connectButton.OnClick = () => Game.GlobalChat.Connect(nicknameBox.Text); var mainPanel = widget.Get("GLOBALCHAT_MAIN_PANEL"); mainPanel.IsVisible = () => Game.GlobalChat.ConnectionStatus != ChatConnectionStatus.Disconnected; mainPanel.Get <LabelWidget>("CHANNEL_TOPIC").GetText = () => Game.GlobalChat.Topic; if (Game.Settings.Chat.ConnectAutomatically) { Game.GlobalChat.Connect(nickName); } }
public ServerTab() { // Generate the chat and user list chatMessageList = new ChatMessageList(); userList = new UserList(() => userSearch); messageBox = new TextFieldWidget( initialText: message, onChange: newMessage => message = newMessage ); // Create a tab container to hold the chat and trade list contents = new TabsContainer(); // Create a flex container to hold the chat tab content HorizontalFlexContainer chatRow = new HorizontalFlexContainer(DEFAULT_SPACING); // Chat container chatRow.Add( GenerateChat() ); // Right column (settings and user list) container chatRow.Add( new Container( GenerateRightColumn(), width: RIGHT_COLUMN_CONTAINER_WIDTH ) ); // Add the chat row as a tab contents.AddTab("Phinix_tabs_chat".Translate(), chatRow); // Add the active trades tab contents.AddTab("Phinix_tabs_trades".Translate(), new TradeList()); }
public CommonSelectorLogic(Widget widget, World world, WorldRenderer worldRenderer, string templateListId, string previewTemplateId) { this.Widget = widget; this.World = world; this.WorldRenderer = worldRenderer; Editor = widget.Parent.Get <EditorViewportControllerWidget>("MAP_EDITOR"); Panel = widget.Get <ScrollPanelWidget>(templateListId); ItemTemplate = Panel.Get <ScrollItemWidget>(previewTemplateId); Panel.Layout = new GridLayout(Panel); SearchTextField = widget.Get <TextFieldWidget>("SEARCH_TEXTFIELD"); SearchTextField.OnEscKey = () => { SearchTextField.Text = ""; SearchTextField.YieldKeyboardFocus(); return(true); }; var categorySelector = widget.Get <DropDownButtonWidget>("CATEGORIES_DROPDOWN"); categorySelector.GetText = () => { if (SelectedCategories.Count == 0) { return("None"); } if (!string.IsNullOrEmpty(searchFilter)) { return("Search Results"); } if (SelectedCategories.Count == 1) { return(SelectedCategories.First()); } if (SelectedCategories.Count == allCategories.Length) { return("All"); } return("Multiple"); }; categorySelector.OnMouseDown = _ => { if (SearchTextField != null) { SearchTextField.YieldKeyboardFocus(); } categorySelector.RemovePanel(); categorySelector.AttachPanel(CreateCategoriesPanel(Panel)); }; }
protected TextFieldWidget(TextFieldWidget widget) : base(widget) { Text = widget.Text; MaxLength = widget.MaxLength; Font = widget.Font; TextColor = widget.TextColor; TextColorDisabled = widget.TextColorDisabled; TextColorInvalid = widget.TextColorInvalid; VisualHeight = widget.VisualHeight; }
private Widget CreateWidgetForQuestion(QuestionStatement statement, GuiEnvironment environment, WidgetStyle style) { Widget questionWidget; switch (statement.Type) { case BooleanValueType _: questionWidget = new CheckBoxWidget(new BooleanValue(false), statement, environment, style); break; case DateValueType _: questionWidget = new DatePickerWidget(new DateValue(DateTime.Now), statement, environment, style); break; case StringValueType _: questionWidget = new TextFieldWidget(new StringValue(string.Empty), statement, environment, style); break; case DecimalValueType _: questionWidget = new ValidatedTextFieldWidget(new DecimalValue(0), new DecimalValidator(), statement, environment, style); break; case IntegerValueType _: questionWidget = new ValidatedTextFieldWidget(new IntegerValue(0), new IntegerValidator(), statement, environment, style); break; case MoneyValueType _: questionWidget = new ValidatedTextFieldWidget(new MoneyValue(0), new MoneyValidator(), statement, environment, style); break; default: throw new ArgumentOutOfRangeException(nameof(statement.Type)); } return(questionWidget); }
public IngameChatLogic(Widget widget, OrderManager orderManager, World world, ModData modData) { this.orderManager = orderManager; this.modRules = modData.DefaultRules; chatTraits = world.WorldActor.TraitsImplementing<INotifyChat>().ToArray(); var players = world.Players.Where(p => p != world.LocalPlayer && !p.NonCombatant && !p.IsBot); disableTeamChat = world.IsReplay || world.LobbyInfo.IsSinglePlayer || (world.LocalPlayer != null && !players.Any(p => p.IsAlliedWith(world.LocalPlayer))); teamChat = !disableTeamChat; tabCompletion.Commands = chatTraits.OfType<ChatCommands>().SelectMany(x => x.Commands.Keys).ToList(); tabCompletion.Names = orderManager.LobbyInfo.Clients.Select(c => c.Name).Distinct().ToList(); var chatPanel = (ContainerWidget)widget; chatOverlay = chatPanel.Get<ContainerWidget>("CHAT_OVERLAY"); chatOverlayDisplay = chatOverlay.Get<ChatDisplayWidget>("CHAT_DISPLAY"); chatOverlay.Visible = false; chatChrome = chatPanel.Get<ContainerWidget>("CHAT_CHROME"); chatChrome.Visible = true; var chatMode = chatChrome.Get<ButtonWidget>("CHAT_MODE"); chatMode.GetText = () => teamChat ? "Team" : "All"; chatMode.OnClick = () => teamChat ^= true; chatMode.IsDisabled = () => disableTeamChat; chatText = chatChrome.Get<TextFieldWidget>("CHAT_TEXTFIELD"); chatText.OnEnterKey = () => { var team = teamChat && !disableTeamChat; if (chatText.Text != "") { if (!chatText.Text.StartsWith("/")) orderManager.IssueOrder(Order.Chat(team, chatText.Text.Trim())); else if (chatTraits != null) { var text = chatText.Text.Trim(); foreach (var trait in chatTraits) trait.OnChat(orderManager.LocalClient.Name, text); } } chatText.Text = ""; CloseChat(); return true; }; chatText.OnTabKey = () => { var previousText = chatText.Text; chatText.Text = tabCompletion.Complete(chatText.Text); chatText.CursorPosition = chatText.Text.Length; if (chatText.Text == previousText) return SwitchTeamChat(); else return true; }; chatText.OnEscKey = () => { CloseChat(); return true; }; var chatClose = chatChrome.Get<ButtonWidget>("CHAT_CLOSE"); chatClose.OnClick += CloseChat; chatPanel.OnKeyPress = e => { if (e.Event == KeyInputEvent.Up) return false; if (!chatChrome.IsVisible() && (e.Key == Keycode.RETURN || e.Key == Keycode.KP_ENTER)) { OpenChat(); return true; } return false; }; chatScrollPanel = chatChrome.Get<ScrollPanelWidget>("CHAT_SCROLLPANEL"); chatTemplate = chatScrollPanel.Get<ContainerWidget>("CHAT_TEMPLATE"); chatScrollPanel.RemoveChildren(); chatScrollPanel.ScrollToBottom(); foreach (var chatLine in orderManager.ChatCache) AddChatLine(chatLine.Color, chatLine.Name, chatLine.Text, true); orderManager.AddChatLine += AddChatLineWrapper; Game.BeforeGameStart += UnregisterEvents; CloseChat(); }
public static void SetupNameWidget(OrderManager orderManager, Session.Client c, TextFieldWidget name) { name.Text = c.Name; name.OnEnterKey = () => { name.Text = name.Text.Trim(); if (name.Text.Length == 0) { name.Text = c.Name; } name.LoseFocus(); if (name.Text == c.Name) { return(true); } orderManager.IssueOrder(Order.Command("name " + name.Text)); Game.Settings.Player.Name = name.Text; Game.Settings.Save(); return(true); }; name.OnLoseFocus = () => name.OnEnterKey(); }
public GameSaveBrowserLogic(Widget widget, ModData modData, Action onExit, Action onStart, bool isSavePanel, World world) { panel = widget; this.modData = modData; this.onStart = onStart; this.onExit = onExit; this.isSavePanel = isSavePanel; Game.BeforeGameStart += OnGameStart; panel.Get <ButtonWidget>("CANCEL_BUTTON").OnClick = () => { Ui.CloseWindow(); onExit(); }; gameList = panel.Get <ScrollPanelWidget>("GAME_LIST"); var gameTemplate = panel.Get <ScrollItemWidget>("GAME_TEMPLATE"); var newTemplate = panel.Get <ScrollItemWidget>("NEW_TEMPLATE"); var mod = modData.Manifest; baseSavePath = Platform.ResolvePath(Platform.SupportDirPrefix, "Saves", mod.Id, mod.Metadata.Version); // Avoid filename conflicts when creating new saves if (isSavePanel) { panel.Get("SAVE_TITLE").IsVisible = () => true; defaultSaveFilename = world.Map.Title; var filenameAttempt = 0; while (true) { if (!File.Exists(Path.Combine(baseSavePath, defaultSaveFilename + ".orasav"))) { break; } defaultSaveFilename = world.Map.Title + " ({0})".F(++filenameAttempt); } var saveButton = panel.Get <ButtonWidget>("SAVE_BUTTON"); saveButton.OnClick = () => { Save(world); }; saveButton.IsVisible = () => true; var saveWidgets = panel.Get("SAVE_WIDGETS"); saveTextField = saveWidgets.Get <TextFieldWidget>("SAVE_TEXTFIELD"); gameList.Bounds.Height -= saveWidgets.Bounds.Height; saveWidgets.IsVisible = () => true; } else { panel.Get("LOAD_TITLE").IsVisible = () => true; var loadButton = panel.Get <ButtonWidget>("LOAD_BUTTON"); loadButton.IsVisible = () => true; loadButton.IsDisabled = () => selectedSave == null; loadButton.OnClick = () => { Load(); }; } if (Directory.Exists(baseSavePath)) { LoadGames(gameTemplate, newTemplate, world); } var renameButton = panel.Get <ButtonWidget>("RENAME_BUTTON"); renameButton.IsDisabled = () => selectedSave == null; renameButton.OnClick = () => { var initialName = Path.GetFileNameWithoutExtension(selectedSave); var invalidChars = Path.GetInvalidFileNameChars(); ConfirmationDialogs.TextInputPrompt( "Rename Save", "Enter a new file name:", initialName, onAccept: newName => Rename(initialName, newName), onCancel: null, acceptText: "Rename", cancelText: null, inputValidator: newName => { if (newName == initialName) { return(false); } if (string.IsNullOrWhiteSpace(newName)) { return(false); } if (newName.IndexOfAny(invalidChars) >= 0) { return(false); } if (File.Exists(Path.Combine(baseSavePath, newName))) { return(false); } return(true); }); }; var deleteButton = panel.Get <ButtonWidget>("DELETE_BUTTON"); deleteButton.IsDisabled = () => selectedSave == null; deleteButton.OnClick = () => { ConfirmationDialogs.ButtonPrompt( title: "Delete selected game save?", text: "Delete '{0}'?".F(Path.GetFileNameWithoutExtension(selectedSave)), onConfirm: () => { Delete(selectedSave); if (!games.Any() && !isSavePanel) { Ui.CloseWindow(); onExit(); } else { SelectFirstVisible(); } }, confirmText: "Delete", onCancel: () => { }); }; var deleteAllButton = panel.Get <ButtonWidget>("DELETE_ALL_BUTTON"); deleteAllButton.IsDisabled = () => !games.Any(); deleteAllButton.OnClick = () => { ConfirmationDialogs.ButtonPrompt( title: "Delete all game saves?", text: "Delete {0} game saves?".F(games.Count), onConfirm: () => { foreach (var s in games.ToList()) { Delete(s); } Ui.CloseWindow(); onExit(); }, confirmText: "Delete All", onCancel: () => { }); }; SelectFirstVisible(); }
public AssetBrowserLogic(Widget widget, Action onExit, World world) { panel = widget; var sourceDropdown = panel.Get <DropDownButtonWidget>("SOURCE_SELECTOR"); sourceDropdown.OnMouseDown = _ => ShowSourceDropdown(sourceDropdown); sourceDropdown.GetText = () => { var name = AssetSource != null ? AssetSource.Name : "All Packages"; if (name.Length > 15) { name = "..." + name.Substring(name.Length - 15); } return(name); }; AssetSource = FileSystem.MountedFolders.First(); spriteImage = panel.Get <ShpImageWidget>("SPRITE"); filenameInput = panel.Get <TextFieldWidget>("FILENAME_INPUT"); filenameInput.Text = spriteImage.Image + ".shp"; filenameInput.OnEnterKey = () => LoadAsset(filenameInput.Text); frameSlider = panel.Get <SliderWidget>("FRAME_SLIDER"); frameSlider.MaximumValue = (float)spriteImage.FrameCount; frameSlider.Ticks = spriteImage.FrameCount + 1; frameSlider.OnChange += x => { spriteImage.Frame = (int)Math.Round(x); }; frameSlider.GetValue = () => spriteImage.Frame; panel.Get <LabelWidget>("FRAME_COUNT").GetText = () => "{0}/{1}".F(spriteImage.Frame, spriteImage.FrameCount); playButton = panel.Get <ButtonWidget>("BUTTON_PLAY"); playButton.OnClick = () => { spriteImage.LoopAnimation = true; playButton.Visible = false; pauseButton.Visible = true; }; pauseButton = panel.Get <ButtonWidget>("BUTTON_PAUSE"); pauseButton.OnClick = () => { spriteImage.LoopAnimation = false; playButton.Visible = true; pauseButton.Visible = false; }; panel.Get <ButtonWidget>("BUTTON_STOP").OnClick = () => { spriteImage.LoopAnimation = false; frameSlider.Value = 0; spriteImage.Frame = 0; playButton.Visible = true; pauseButton.Visible = false; }; panel.Get <ButtonWidget>("BUTTON_NEXT").OnClick = () => { spriteImage.RenderNextFrame(); }; panel.Get <ButtonWidget>("BUTTON_PREV").OnClick = () => { spriteImage.RenderPreviousFrame(); }; panel.Get <ButtonWidget>("LOAD_BUTTON").OnClick = () => { LoadAsset(filenameInput.Text); }; assetList = panel.Get <ScrollPanelWidget>("ASSET_LIST"); template = panel.Get <ScrollItemWidget>("ASSET_TEMPLATE"); PopulateAssetList(); var palette = (WidgetUtils.ActiveModId() == "d2k") ? "d2k.pal" : "egopal.pal"; panel.Get <ButtonWidget>("EXPORT_BUTTON").OnClick = () => { var ExtractGameFiles = new string[][] { new string[] { "--extract", WidgetUtils.ActiveModId(), palette, "--userdir" }, new string[] { "--extract", WidgetUtils.ActiveModId(), "{0}.shp".F(spriteImage.Image), "--userdir" }, }; var ExportToPng = new string[][] { new string[] { "--png", Platform.SupportDir + "{0}.shp".F(spriteImage.Image), Platform.SupportDir + palette }, }; var ImportFromPng = new string[][] { }; var args = new WidgetArgs() { { "ExtractGameFiles", ExtractGameFiles }, { "ExportToPng", ExportToPng }, { "ImportFromPng", ImportFromPng } }; Ui.OpenWindow("CONVERT_ASSETS_PANEL", args); }; panel.Get <ButtonWidget>("EXTRACT_BUTTON").OnClick = () => { var ExtractGameFilesList = new List <string[]>(); var ExportToPngList = new List <string[]>(); ExtractGameFilesList.Add(new string[] { "--extract", WidgetUtils.ActiveModId(), palette, "--userdir" }); foreach (var shp in AvailableShps) { ExtractGameFilesList.Add(new string[] { "--extract", WidgetUtils.ActiveModId(), shp, "--userdir" }); ExportToPngList.Add(new string[] { "--png", Platform.SupportDir + shp, Platform.SupportDir + palette }); Console.WriteLine(Platform.SupportDir + shp); } var ExtractGameFiles = ExtractGameFilesList.ToArray(); var ExportToPng = ExportToPngList.ToArray(); var ImportFromPng = new string[][] { }; var args = new WidgetArgs() { { "ExtractGameFiles", ExtractGameFiles }, { "ExportToPng", ExportToPng }, { "ImportFromPng", ImportFromPng } }; Ui.OpenWindow("CONVERT_ASSETS_PANEL", args); }; panel.Get <ButtonWidget>("IMPORT_BUTTON").OnClick = () => { var imageSizeInput = panel.Get <TextFieldWidget>("IMAGE_SIZE_INPUT"); var imageFilename = panel.Get <TextFieldWidget>("IMAGE_FILENAME_INPUT"); var ExtractGameFiles = new string[][] { }; var ExportToPng = new string[][] { }; var ImportFromPng = new string[][] { new string[] { "--shp", Platform.SupportDir + imageFilename.Text, imageSizeInput.Text }, }; var args = new WidgetArgs() { { "ExtractGameFiles", ExtractGameFiles }, { "ExportToPng", ExportToPng }, { "ImportFromPng", ImportFromPng } }; Ui.OpenWindow("CONVERT_ASSETS_PANEL", args); }; panel.Get <ButtonWidget>("CLOSE_BUTTON").OnClick = () => { Ui.CloseWindow(); onExit(); }; }
public GlobalChatLogic(Widget widget) { historyPanel = widget.Get <ScrollPanelWidget>("HISTORY_PANEL"); historyTemplate = historyPanel.Get <LabelWidget>("HISTORY_TEMPLATE"); nicknamePanel = widget.Get <ScrollPanelWidget>("NICKNAME_PANEL"); nicknameTemplate = nicknamePanel.Get("NICKNAME_TEMPLATE"); historyPanel.Bind(Game.GlobalChat.History, MakeHistoryWidget, HistoryWidgetEquals, true); nicknamePanel.Bind(Game.GlobalChat.Users, MakeUserWidget, UserWidgetEquals, false); inputBox = widget.Get <TextFieldWidget>("CHAT_TEXTFIELD"); inputBox.IsDisabled = () => Game.GlobalChat.ConnectionStatus != ChatConnectionStatus.Joined; inputBox.OnEnterKey = EnterPressed; // Set a random default nick if (Game.Settings.Chat.Nickname == new ChatSettings().Nickname) { Game.Settings.Chat.Nickname += Game.CosmeticRandom.Next(100, 999); } var nicknameBox = widget.Get <TextFieldWidget>("NICKNAME_TEXTFIELD"); nicknameBox.Text = Game.GlobalChat.SanitizedName(Game.Settings.Chat.Nickname); nicknameBox.OnTextEdited = () => { nicknameBox.Text = Game.GlobalChat.SanitizedName(nicknameBox.Text); }; var connectPanel = widget.Get("GLOBALCHAT_CONNECT_PANEL"); connectPanel.IsVisible = () => Game.GlobalChat.ConnectionStatus == ChatConnectionStatus.Disconnected; var disconnectButton = widget.Get <ButtonWidget>("DISCONNECT_BUTTON"); disconnectButton.OnClick = Game.GlobalChat.Disconnect; var connectAutomaticallyCheckBox = connectPanel.Get <CheckboxWidget>("CONNECT_AUTOMATICALLY_CHECKBOX"); connectAutomaticallyCheckBox.IsChecked = () => Game.Settings.Chat.ConnectAutomatically; connectAutomaticallyCheckBox.OnClick = () => { Game.Settings.Chat.ConnectAutomatically ^= true; Game.Settings.Save(); }; var connectButton = connectPanel.Get <ButtonWidget>("CONNECT_BUTTON"); connectButton.IsDisabled = () => !Game.GlobalChat.IsValidNickname(nicknameBox.Text); connectButton.OnClick = () => { Game.Settings.Chat.Nickname = nicknameBox.Text; Game.Settings.Save(); Game.GlobalChat.Connect(); }; var mainPanel = widget.Get("GLOBALCHAT_MAIN_PANEL"); mainPanel.IsVisible = () => Game.GlobalChat.ConnectionStatus != ChatConnectionStatus.Disconnected; mainPanel.Get <LabelWidget>("CHANNEL_TOPIC").GetText = () => Game.GlobalChat.Topic; if (Game.Settings.Chat.ConnectAutomatically && Game.GlobalChat.IsValidNickname(Game.Settings.Chat.Nickname)) { Game.GlobalChat.Connect(); } }
public VxlBrowserLogic(Widget widget, Action onExit, ModData modData, World world, Dictionary <string, MiniYaml> logicArgs) { this.world = world; this.modData = modData; panel = widget; var voxelWidget = panel.GetOrNull <VoxelWidget>("VOXEL"); if (voxelWidget != null) { voxelWidget.GetVoxel = () => currentVoxel != null ? currentVoxel : null; currentPalette = voxelWidget.Palette; voxelWidget.GetPalette = () => currentPalette; voxelWidget.GetPlayerPalette = () => currentPlayerPalette; voxelWidget.GetNormalsPalette = () => currentNormalsPalette; voxelWidget.GetShadowPalette = () => currentShadowPalette; voxelWidget.GetLightAmbientColor = () => lightAmbientColor; voxelWidget.GetLightDiffuseColor = () => lightDiffuseColor; voxelWidget.GetLightPitch = () => lightPitch; voxelWidget.GetLightYaw = () => lightYaw; voxelWidget.IsVisible = () => !isVideoLoaded && !isLoadError; } var playerWidget = panel.GetOrNull <VqaPlayerWidget>("PLAYER"); if (playerWidget != null) { playerWidget.IsVisible = () => isVideoLoaded && !isLoadError; } var paletteDropDown = panel.GetOrNull <DropDownButtonWidget>("PALETTE_SELECTOR"); if (paletteDropDown != null) { paletteDropDown.OnMouseDown = _ => ShowPaletteDropdown(paletteDropDown, world); paletteDropDown.GetText = () => currentPalette; } var lightAmbientColorPreview = panel.GetOrNull <ColorPreviewManagerWidget>("LIGHT_AMBIENT_COLOR_MANAGER"); if (lightAmbientColorPreview != null) { lightAmbientColorPreview.Color = Color.FromArgb( Convert.ToInt32(lightAmbientColor[0] * 255), Convert.ToInt32(lightAmbientColor[1] * 255), Convert.ToInt32(lightAmbientColor[2] * 255) ); } var lightDiffuseColorPreview = panel.GetOrNull <ColorPreviewManagerWidget>("LIGHT_DIFFUSE_COLOR_MANAGER"); if (lightDiffuseColorPreview != null) { lightDiffuseColorPreview.Color = Color.FromArgb( Convert.ToInt32(lightDiffuseColor[0] * 255), Convert.ToInt32(lightDiffuseColor[1] * 255), Convert.ToInt32(lightDiffuseColor[2] * 255) ); } var playerPaletteDropDown = panel.GetOrNull <DropDownButtonWidget>("PLAYER_PALETTE_SELECTOR"); if (playerPaletteDropDown != null) { playerPaletteDropDown.OnMouseDown = _ => ShowPlayerPaletteDropdown(playerPaletteDropDown, world); playerPaletteDropDown.GetText = () => currentPlayerPalette; } var normalsPlaletteDropDown = panel.GetOrNull <DropDownButtonWidget>("NORMALS_PALETTE_SELECTOR"); if (normalsPlaletteDropDown != null) { normalsPlaletteDropDown.OnMouseDown = _ => ShowNormalsPaletteDropdown(normalsPlaletteDropDown, world); normalsPlaletteDropDown.GetText = () => currentNormalsPalette; } var shadowPlaletteDropDown = panel.GetOrNull <DropDownButtonWidget>("SHADOW_PALETTE_SELECTOR"); if (shadowPlaletteDropDown != null) { shadowPlaletteDropDown.OnMouseDown = _ => ShowShadowPaletteDropdown(normalsPlaletteDropDown, world); shadowPlaletteDropDown.GetText = () => currentShadowPalette; } scaleInput = panel.GetOrNull <TextFieldWidget>("SCALE_TEXT"); scaleInput.OnTextEdited = () => OnScaleEdit(); scaleInput.OnEscKey = scaleInput.YieldKeyboardFocus; lightPitchInput = panel.GetOrNull <TextFieldWidget>("LIGHTPITCH_TEXT"); lightPitchInput.OnTextEdited = () => OnLightPitchEdit(); lightPitchInput.OnEscKey = lightPitchInput.YieldKeyboardFocus; lightYawInput = panel.GetOrNull <TextFieldWidget>("LIGHTYAW_TEXT"); lightYawInput.OnTextEdited = () => OnLightYawEdit(); lightYawInput.OnEscKey = lightYawInput.YieldKeyboardFocus; var lightAmbientColorDropDown = panel.GetOrNull <DropDownButtonWidget>("LIGHT_AMBIENT_COLOR"); if (lightAmbientColorDropDown != null) { lightAmbientColorDropDown.OnMouseDown = _ => ShowLightAmbientColorDropDown(lightAmbientColorDropDown, lightAmbientColorPreview, world); lightAmbientColorBlock = panel.Get <ColorBlockWidget>("AMBIENT_COLORBLOCK"); lightAmbientColorBlock.GetColor = () => OpenRA.Primitives.Color.FromArgb( Convert.ToInt32(lightAmbientColor[0] * 255), Convert.ToInt32(lightAmbientColor[1] * 255), Convert.ToInt32(lightAmbientColor[2] * 255) ); } lightAmbientColorValue = panel.GetOrNull <LabelWidget>("LIGHTAMBIENTCOLOR_VALUE"); lightDiffuseColorValue = panel.GetOrNull <LabelWidget>("LIGHTDIFFUSECOLOR_VALUE"); var lightDiffuseColorDropDown = panel.GetOrNull <DropDownButtonWidget>("LIGHT_DIFFUSE_COLOR"); if (lightDiffuseColorDropDown != null) { lightDiffuseColorDropDown.OnMouseDown = _ => ShowLightDiffuseColorDropDown(lightDiffuseColorDropDown, lightDiffuseColorPreview, world); lightDiffuseColorBlock = panel.Get <ColorBlockWidget>("DIFFUSE_COLORBLOCK"); lightDiffuseColorBlock.GetColor = () => Color.FromArgb( Convert.ToInt32(lightDiffuseColor[0] * 255), Convert.ToInt32(lightDiffuseColor[1] * 255), Convert.ToInt32(lightDiffuseColor[2] * 255) ); } unitnameInput = panel.Get <TextFieldWidget>("FILENAME_INPUT"); unitnameInput.OnTextEdited = () => ApplyFilter(); unitnameInput.OnEscKey = unitnameInput.YieldKeyboardFocus; if (logicArgs.ContainsKey("SupportedFormats")) { allowedExtensions = FieldLoader.GetValue <string[]>("SupportedFormats", logicArgs["SupportedFormats"].Value); } else { allowedExtensions = new string[0]; } acceptablePackages = modData.ModFiles.MountedPackages.Where(p => p.Contents.Any(c => allowedExtensions.Contains(Path.GetExtension(c).ToLowerInvariant()))); unitList = panel.Get <ScrollPanelWidget>("ASSET_LIST"); template = panel.Get <ScrollItemWidget>("ASSET_TEMPLATE"); PopulateAssetList(); var closeButton = panel.GetOrNull <ButtonWidget>("CLOSE_BUTTON"); if (closeButton != null) { closeButton.OnClick = () => { if (isVideoLoaded) { player.Stop(); } Ui.CloseWindow(); onExit(); } } ; }
Func <bool> InitPanel(Widget panel) { hotkeyList = panel.Get <ScrollPanelWidget>("HOTKEY_LIST"); hotkeyList.Layout = new GridLayout(hotkeyList); headerTemplate = hotkeyList.Get("HEADER"); template = hotkeyList.Get("TEMPLATE"); emptyListMessage = panel.Get("HOTKEY_EMPTY_LIST"); remapDialog = panel.Get("HOTKEY_REMAP_DIALOG"); foreach (var hd in modData.Hotkeys.Definitions) { contexts.UnionWith(hd.Contexts); } filterInput = panel.Get <TextFieldWidget>("FILTER_INPUT"); filterInput.OnTextEdited = () => InitHotkeyList(); filterInput.OnEscKey = _ => { if (string.IsNullOrEmpty(filterInput.Text)) { filterInput.YieldKeyboardFocus(); } else { filterInput.Text = ""; filterInput.OnTextEdited(); } return(true); }; var contextDropdown = panel.GetOrNull <DropDownButtonWidget>("CONTEXT_DROPDOWN"); if (contextDropdown != null) { contextDropdown.OnMouseDown = _ => ShowContextDropdown(contextDropdown); var contextName = new CachedTransform <string, string>(GetContextDisplayName); contextDropdown.GetText = () => contextName.Update(currentContext); } if (logicArgs.TryGetValue("HotkeyGroups", out var hotkeyGroupsYaml)) { foreach (var hg in hotkeyGroupsYaml.Nodes) { var typesNode = hg.Value.Nodes.FirstOrDefault(n => n.Key == "Types"); if (typesNode != null) { hotkeyGroups.Add(hg.Key, FieldLoader.GetValue <HashSet <string> >("Types", typesNode.Value.Value)); } } InitHotkeyRemapDialog(panel); InitHotkeyList(); } return(() => { hotkeyEntryWidget.Key = selectedHotkeyDefinition != null ? modData.Hotkeys[selectedHotkeyDefinition.Name].GetValue() : Hotkey.Invalid; hotkeyEntryWidget.ForceYieldKeyboardFocus(); return false; }); }
public AssetBrowserLogic(Widget widget, Action onExit, ModData modData, World world, Dictionary <string, MiniYaml> logicArgs) { this.world = world; this.modData = modData; panel = widget; var ticker = panel.GetOrNull <LogicTickerWidget>("ANIMATION_TICKER"); if (ticker != null) { ticker.OnTick = () => { if (animateFrames) { SelectNextFrame(); } }; } var sourceDropdown = panel.GetOrNull <DropDownButtonWidget>("SOURCE_SELECTOR"); if (sourceDropdown != null) { sourceDropdown.OnMouseDown = _ => ShowSourceDropdown(sourceDropdown); var sourceName = new CachedTransform <IReadOnlyPackage, string>(GetSourceDisplayName); sourceDropdown.GetText = () => sourceName.Update(assetSource); } var spriteWidget = panel.GetOrNull <SpriteWidget>("SPRITE"); if (spriteWidget != null) { spriteWidget.GetSprite = () => currentSprites != null ? currentSprites[currentFrame] : null; currentPalette = spriteWidget.Palette; spriteWidget.GetPalette = () => currentPalette; spriteWidget.IsVisible = () => !isVideoLoaded && !isLoadError && currentSprites != null; } var playerWidget = panel.GetOrNull <VqaPlayerWidget>("PLAYER"); if (playerWidget != null) { playerWidget.IsVisible = () => isVideoLoaded && !isLoadError; } var modelWidget = panel.GetOrNull <ModelWidget>("VOXEL"); if (modelWidget != null) { modelWidget.GetVoxel = () => currentVoxel; currentPalette = modelWidget.Palette; modelWidget.GetPalette = () => currentPalette; modelWidget.GetPlayerPalette = () => currentPalette; modelWidget.GetRotation = () => modelOrientation; modelWidget.IsVisible = () => !isVideoLoaded && !isLoadError && currentVoxel != null; } var errorLabelWidget = panel.GetOrNull("ERROR"); if (errorLabelWidget != null) { errorLabelWidget.IsVisible = () => isLoadError; } var paletteDropDown = panel.GetOrNull <DropDownButtonWidget>("PALETTE_SELECTOR"); if (paletteDropDown != null) { paletteDropDown.OnMouseDown = _ => ShowPaletteDropdown(paletteDropDown, world); paletteDropDown.GetText = () => currentPalette; } var colorPreview = panel.GetOrNull <ColorPreviewManagerWidget>("COLOR_MANAGER"); if (colorPreview != null) { colorPreview.Color = Game.Settings.Player.Color; } var colorDropdown = panel.GetOrNull <DropDownButtonWidget>("COLOR"); if (colorDropdown != null) { colorDropdown.IsDisabled = () => currentPalette != colorPreview.PaletteName; colorDropdown.OnMouseDown = _ => ColorPickerLogic.ShowColorDropDown(colorDropdown, colorPreview, world); panel.Get <ColorBlockWidget>("COLORBLOCK").GetColor = () => Game.Settings.Player.Color; } filenameInput = panel.Get <TextFieldWidget>("FILENAME_INPUT"); filenameInput.OnTextEdited = () => ApplyFilter(); filenameInput.OnEscKey = filenameInput.YieldKeyboardFocus; var frameContainer = panel.GetOrNull("FRAME_SELECTOR"); if (frameContainer != null) { frameContainer.IsVisible = () => (currentSprites != null && currentSprites.Length > 1) || (isVideoLoaded && player != null && player.Video != null && player.Video.Frames > 1); } frameSlider = panel.GetOrNull <SliderWidget>("FRAME_SLIDER"); if (frameSlider != null) { frameSlider.OnChange += x => { if (!isVideoLoaded) { currentFrame = (int)Math.Round(x); } }; frameSlider.GetValue = () => isVideoLoaded ? player.Video.CurrentFrame : currentFrame; frameSlider.IsDisabled = () => isVideoLoaded; } var frameText = panel.GetOrNull <LabelWidget>("FRAME_COUNT"); if (frameText != null) { frameText.GetText = () => isVideoLoaded ? "{0} / {1}".F(player.Video.CurrentFrame + 1, player.Video.Frames) : "{0} / {1}".F(currentFrame, currentSprites.Length - 1); } var playButton = panel.GetOrNull <ButtonWidget>("BUTTON_PLAY"); if (playButton != null) { playButton.OnClick = () => { if (isVideoLoaded) { player.Play(); } else { animateFrames = true; } }; playButton.IsVisible = () => isVideoLoaded ? player.Paused : !animateFrames; } var pauseButton = panel.GetOrNull <ButtonWidget>("BUTTON_PAUSE"); if (pauseButton != null) { pauseButton.OnClick = () => { if (isVideoLoaded) { player.Pause(); } else { animateFrames = false; } }; pauseButton.IsVisible = () => isVideoLoaded ? !player.Paused : animateFrames; } var stopButton = panel.GetOrNull <ButtonWidget>("BUTTON_STOP"); if (stopButton != null) { stopButton.OnClick = () => { if (isVideoLoaded) { player.Stop(); } else { if (frameSlider != null) { frameSlider.Value = 0; } currentFrame = 0; animateFrames = false; } }; } var nextButton = panel.GetOrNull <ButtonWidget>("BUTTON_NEXT"); if (nextButton != null) { nextButton.OnClick = () => { if (!isVideoLoaded) { nextButton.OnClick = SelectNextFrame; } }; nextButton.IsVisible = () => !isVideoLoaded; } var prevButton = panel.GetOrNull <ButtonWidget>("BUTTON_PREV"); if (prevButton != null) { prevButton.OnClick = () => { if (!isVideoLoaded) { SelectPreviousFrame(); } }; prevButton.IsVisible = () => !isVideoLoaded; } var voxelContainer = panel.GetOrNull("VOXEL_SELECTOR"); if (voxelContainer != null) { voxelContainer.IsVisible = () => currentVoxel != null; } var rollSlider = panel.GetOrNull <SliderWidget>("ROLL_SLIDER"); if (rollSlider != null) { rollSlider.OnChange += x => { var roll = (int)x; modelOrientation = modelOrientation.WithRoll(new WAngle(roll)); }; rollSlider.GetValue = () => modelOrientation.Roll.Angle; } var pitchSlider = panel.GetOrNull <SliderWidget>("PITCH_SLIDER"); if (pitchSlider != null) { pitchSlider.OnChange += x => { var pitch = (int)x; modelOrientation = modelOrientation.WithPitch(new WAngle(pitch)); }; pitchSlider.GetValue = () => modelOrientation.Pitch.Angle; } var yawSlider = panel.GetOrNull <SliderWidget>("YAW_SLIDER"); if (yawSlider != null) { yawSlider.OnChange += x => { var yaw = (int)x; modelOrientation = modelOrientation.WithYaw(new WAngle(yaw)); }; yawSlider.GetValue = () => modelOrientation.Yaw.Angle; } var assetBrowserModData = modData.Manifest.Get <AssetBrowser>(); allowedExtensions = assetBrowserModData.SupportedExtensions; acceptablePackages = modData.ModFiles.MountedPackages.Where(p => p.Contents.Any(c => allowedExtensions.Contains(Path.GetExtension(c).ToLowerInvariant()))); assetList = panel.Get <ScrollPanelWidget>("ASSET_LIST"); template = panel.Get <ScrollItemWidget>("ASSET_TEMPLATE"); PopulateAssetList(); var closeButton = panel.GetOrNull <ButtonWidget>("CLOSE_BUTTON"); if (closeButton != null) { closeButton.OnClick = () => { if (isVideoLoaded) { player.Stop(); } Ui.CloseWindow(); onExit(); } } ; } void SelectNextFrame() { currentFrame++; if (currentFrame >= currentSprites.Length) { currentFrame = 0; } } void SelectPreviousFrame() { currentFrame--; if (currentFrame < 0) { currentFrame = currentSprites.Length - 1; } } Dictionary <string, bool> assetVisByName = new Dictionary <string, bool>(); bool FilterAsset(string filename) { var filter = filenameInput.Text; if (string.IsNullOrWhiteSpace(filter)) { return(true); } if (filename.IndexOf(filter, StringComparison.OrdinalIgnoreCase) >= 0) { return(true); } return(false); } void ApplyFilter() { assetVisByName.Clear(); assetList.Layout.AdjustChildren(); assetList.ScrollToTop(); // Select the first visible var firstVisible = assetVisByName.FirstOrDefault(kvp => kvp.Value); if (firstVisible.Key != null && modData.DefaultFileSystem.TryGetPackageContaining(firstVisible.Key, out var package, out var filename)) { LoadAsset(package, filename); } } void AddAsset(ScrollPanelWidget list, string filepath, IReadOnlyPackage package, ScrollItemWidget template) { var item = ScrollItemWidget.Setup(template, () => currentFilename == filepath && currentPackage == package, () => { LoadAsset(package, filepath); }); var label = item.Get <LabelWithTooltipWidget>("TITLE"); WidgetUtils.TruncateLabelToTooltip(label, filepath); item.IsVisible = () => { if (assetVisByName.TryGetValue(filepath, out var visible)) { return(visible); } visible = FilterAsset(filepath); assetVisByName.Add(filepath, visible); return(visible); }; list.AddChild(item); } bool LoadAsset(IReadOnlyPackage package, string filename) { if (isVideoLoaded) { player.Stop(); player = null; isVideoLoaded = false; } if (string.IsNullOrEmpty(filename)) { return(false); } if (!package.Contains(filename)) { return(false); } isLoadError = false; try { currentPackage = package; currentFilename = filename; var prefix = ""; var fs = modData.DefaultFileSystem as OpenRA.FileSystem.FileSystem; if (fs != null) { prefix = fs.GetPrefix(package); if (prefix != null) { prefix += "|"; } } if (Path.GetExtension(filename.ToLowerInvariant()) == ".vqa") { player = panel.Get <VqaPlayerWidget>("PLAYER"); player.Load(prefix + filename); player.DrawOverlay = false; isVideoLoaded = true; if (frameSlider != null) { frameSlider.MaximumValue = (float)player.Video.Frames - 1; frameSlider.Ticks = 0; } return(true); } if (Path.GetExtension(filename.ToLowerInvariant()) == ".vxl") { var voxelName = Path.GetFileNameWithoutExtension(filename); currentVoxel = world.ModelCache.GetModel(voxelName); currentSprites = null; } else { currentSprites = world.Map.Rules.Sequences.SpriteCache[prefix + filename]; currentFrame = 0; if (frameSlider != null) { frameSlider.MaximumValue = (float)currentSprites.Length - 1; frameSlider.Ticks = currentSprites.Length; } currentVoxel = null; } } catch (Exception ex) { isLoadError = true; Log.AddChannel("assetbrowser", "assetbrowser.log"); Log.Write("assetbrowser", "Error reading {0}:{3} {1}{3}{2}", filename, ex.Message, ex.StackTrace, Environment.NewLine); return(false); } return(true); } bool ShowSourceDropdown(DropDownButtonWidget dropdown) { var sourceName = new CachedTransform <IReadOnlyPackage, string>(GetSourceDisplayName); Func <IReadOnlyPackage, ScrollItemWidget, ScrollItemWidget> setupItem = (source, itemTemplate) => { var item = ScrollItemWidget.Setup(itemTemplate, () => assetSource == source, () => { assetSource = source; PopulateAssetList(); }); item.Get <LabelWidget>("LABEL").GetText = () => sourceName.Update(source); return(item); }; var sources = new[] { (IReadOnlyPackage)null }.Concat(acceptablePackages); dropdown.ShowDropDown("LABEL_DROPDOWN_TEMPLATE", 280, sources, setupItem); return(true); } void PopulateAssetList() { assetList.RemoveChildren(); var files = new SortedList <string, List <IReadOnlyPackage> >(); if (assetSource != null) { foreach (var content in assetSource.Contents) { files.Add(content, new List <IReadOnlyPackage> { assetSource }); } } else { foreach (var mountedPackage in modData.ModFiles.MountedPackages) { foreach (var content in mountedPackage.Contents) { if (!files.ContainsKey(content)) { files.Add(content, new List <IReadOnlyPackage> { mountedPackage }); } else { files[content].Add(mountedPackage); } } } } foreach (var file in files.OrderBy(s => s.Key)) { if (!allowedExtensions.Any(ext => file.Key.EndsWith(ext, true, CultureInfo.InvariantCulture))) { continue; } foreach (var package in file.Value) { AddAsset(assetList, file.Key, package, template); } } } bool ShowPaletteDropdown(DropDownButtonWidget dropdown, World world) { Func <string, ScrollItemWidget, ScrollItemWidget> setupItem = (name, itemTemplate) => { var item = ScrollItemWidget.Setup(itemTemplate, () => currentPalette == name, () => currentPalette = name); item.Get <LabelWidget>("LABEL").GetText = () => name; return(item); }; var palettes = world.WorldActor.TraitsImplementing <IProvidesAssetBrowserPalettes>() .SelectMany(p => p.PaletteNames); dropdown.ShowDropDown("LABEL_DROPDOWN_TEMPLATE", 280, palettes, setupItem); return(true); } string GetSourceDisplayName(IReadOnlyPackage source) { if (source == null) { return("All Packages"); } // Packages that are explicitly mounted in the filesystem use their explicit mount name var fs = (OpenRA.FileSystem.FileSystem)modData.DefaultFileSystem; var name = fs.GetPrefix(source); // Fall back to the path relative to the mod, engine, or support dir if (name == null) { name = source.Name; var compare = Platform.CurrentPlatform == PlatformType.Windows ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; if (name.StartsWith(modData.Manifest.Package.Name, compare)) { name = "$" + modData.Manifest.Id + "/" + name.Substring(modData.Manifest.Package.Name.Length + 1); } else if (name.StartsWith(Platform.EngineDir, compare)) { name = "./" + name.Substring(Platform.EngineDir.Length); } else if (name.StartsWith(Platform.SupportDir, compare)) { name = "^" + name.Substring(Platform.SupportDir.Length); } } if (name.Length > 18) { name = "..." + name.Substring(name.Length - 15); } return(name); } }
public IngameChatLogic(Widget widget, OrderManager orderManager, World world, ModData modData, bool isMenuChat) { this.orderManager = orderManager; this.modRules = modData.DefaultRules; chatTraits = world.WorldActor.TraitsImplementing <INotifyChat>().ToArray(); var players = world.Players.Where(p => p != world.LocalPlayer && !p.NonCombatant && !p.IsBot); disableTeamChat = world.IsReplay || world.LobbyInfo.NonBotClients.Count() == 1 || (world.LocalPlayer != null && !players.Any(p => p.IsAlliedWith(world.LocalPlayer))); teamChat = !disableTeamChat; tabCompletion.Commands = chatTraits.OfType <ChatCommands>().SelectMany(x => x.Commands.Keys).ToList(); tabCompletion.Names = orderManager.LobbyInfo.Clients.Select(c => c.Name).Distinct().ToList(); var chatPanel = (ContainerWidget)widget; chatOverlay = chatPanel.GetOrNull <ContainerWidget>("CHAT_OVERLAY"); if (chatOverlay != null) { chatOverlayDisplay = chatOverlay.Get <ChatDisplayWidget>("CHAT_DISPLAY"); chatOverlay.Visible = false; } chatChrome = chatPanel.Get <ContainerWidget>("CHAT_CHROME"); chatChrome.Visible = true; var chatMode = chatChrome.Get <ButtonWidget>("CHAT_MODE"); chatMode.GetText = () => teamChat ? "Team" : "All"; chatMode.OnClick = () => teamChat ^= true; chatMode.IsDisabled = () => disableTeamChat; chatText = chatChrome.Get <TextFieldWidget>("CHAT_TEXTFIELD"); chatText.MaxLength = UnitOrders.ChatMessageMaxLength; chatText.OnEnterKey = () => { var team = teamChat && !disableTeamChat; if (chatText.Text != "") { if (!chatText.Text.StartsWith("/", StringComparison.Ordinal)) { orderManager.IssueOrder(Order.Chat(team, chatText.Text.Trim())); } else if (chatTraits != null) { var text = chatText.Text.Trim(); foreach (var trait in chatTraits) { trait.OnChat(orderManager.LocalClient.Name, text); } } } chatText.Text = ""; if (!isMenuChat) { CloseChat(); } return(true); }; chatText.OnTabKey = () => { var previousText = chatText.Text; chatText.Text = tabCompletion.Complete(chatText.Text); chatText.CursorPosition = chatText.Text.Length; if (chatText.Text == previousText) { return(SwitchTeamChat()); } else { return(true); } }; chatText.OnEscKey = () => { if (!isMenuChat) { CloseChat(); } else { chatText.YieldKeyboardFocus(); } return(true); }; if (!isMenuChat) { var chatClose = chatChrome.Get <ButtonWidget>("CHAT_CLOSE"); chatClose.OnClick += CloseChat; chatPanel.OnKeyPress = e => { if (e.Event == KeyInputEvent.Up) { return(false); } if (!chatChrome.IsVisible() && (e.Key == Keycode.RETURN || e.Key == Keycode.KP_ENTER)) { OpenChat(); return(true); } return(false); }; } chatScrollPanel = chatChrome.Get <ScrollPanelWidget>("CHAT_SCROLLPANEL"); chatTemplate = chatScrollPanel.Get <ContainerWidget>("CHAT_TEMPLATE"); chatScrollPanel.RemoveChildren(); chatScrollPanel.ScrollToBottom(); foreach (var chatLine in orderManager.ChatCache) { AddChatLine(chatLine.Color, chatLine.Name, chatLine.Text, true); } orderManager.AddChatLine += AddChatLineWrapper; Game.BeforeGameStart += UnregisterEvents; chatText.IsDisabled = () => world.IsReplay && !Game.Settings.Debug.EnableDebugCommandsInReplays; if (!isMenuChat) { CloseChat(); var keyListener = chatChrome.Get <LogicKeyListenerWidget>("KEY_LISTENER"); keyListener.AddHandler(e => { if (e.Event == KeyInputEvent.Up || !chatText.IsDisabled()) { return(false); } if ((e.Key == Keycode.RETURN || e.Key == Keycode.KP_ENTER || e.Key == Keycode.ESCAPE) && e.Modifiers == Modifiers.None) { CloseChat(); return(true); } return(false); }); } }
public ActorEditLogic(Widget widget, World world, WorldRenderer worldRenderer, Dictionary <string, MiniYaml> logicArgs) { this.worldRenderer = worldRenderer; editorActorLayer = world.WorldActor.Trait <EditorActorLayer>(); editorActionManager = world.WorldActor.Trait <EditorActionManager>(); editor = widget.Parent.Get <EditorViewportControllerWidget>("MAP_EDITOR"); actorEditPanel = editor.Get <BackgroundWidget>("ACTOR_EDIT_PANEL"); typeLabel = actorEditPanel.Get <LabelWidget>("ACTOR_TYPE_LABEL"); actorIDField = actorEditPanel.Get <TextFieldWidget>("ACTOR_ID"); initContainer = actorEditPanel.Get("ACTOR_INIT_CONTAINER"); buttonContainer = actorEditPanel.Get("BUTTON_CONTAINER"); checkboxOptionTemplate = initContainer.Get("CHECKBOX_OPTION_TEMPLATE"); sliderOptionTemplate = initContainer.Get("SLIDER_OPTION_TEMPLATE"); dropdownOptionTemplate = initContainer.Get("DROPDOWN_OPTION_TEMPLATE"); initContainer.RemoveChildren(); var deleteButton = actorEditPanel.Get <ButtonWidget>("DELETE_BUTTON"); var cancelButton = actorEditPanel.Get <ButtonWidget>("CANCEL_BUTTON"); var okButton = actorEditPanel.Get <ButtonWidget>("OK_BUTTON"); actorIDErrorLabel = actorEditPanel.Get <LabelWidget>("ACTOR_ID_ERROR_LABEL"); actorIDErrorLabel.IsVisible = () => actorIDStatus != ActorIDStatus.Normal; actorIDErrorLabel.GetText = () => actorIDStatus == ActorIDStatus.Duplicate ? "Duplicate Actor ID" : "Enter an Actor ID"; MiniYaml yaml; if (logicArgs.TryGetValue("EditPanelPadding", out yaml)) { editPanelPadding = FieldLoader.GetValue <int>("EditPanelPadding", yaml.Value); } okButton.IsDisabled = () => !IsValid() || !editActorPreview.IsDirty; okButton.OnClick = Save; cancelButton.OnClick = Cancel; deleteButton.OnClick = Delete; actorEditPanel.IsVisible = () => CurrentActor != null && editor.CurrentBrush == editor.DefaultBrush && Game.RunTime > lastScrollTime + scrollVisibleTimeout; actorIDField.OnEscKey = () => { actorIDField.YieldKeyboardFocus(); return(true); }; actorIDField.OnTextEdited = () => { var actorId = actorIDField.Text.Trim(); if (string.IsNullOrWhiteSpace(actorId)) { nextActorIDStatus = ActorIDStatus.Empty; return; } // Check for duplicate actor ID if (CurrentActor.ID.Equals(actorId, StringComparison.OrdinalIgnoreCase)) { if (editorActorLayer[actorId] != null) { nextActorIDStatus = ActorIDStatus.Duplicate; return; } } SetActorID(actorId); nextActorIDStatus = ActorIDStatus.Normal; }; actorIDField.OnLoseFocus = () => { // Reset invalid IDs back to their starting value if (actorIDStatus != ActorIDStatus.Normal) { SetActorID(initialActorID); } }; }
public AssetBrowserLogic(Widget widget, Action onExit, ModData modData, WorldRenderer worldRenderer) { world = worldRenderer.World; this.modData = modData; panel = widget; var colorPickerPalettes = world.WorldActor.TraitsImplementing <IProvidesAssetBrowserColorPickerPalettes>() .SelectMany(p => p.ColorPickerPaletteNames) .ToArray(); palettes = world.WorldActor.TraitsImplementing <IProvidesAssetBrowserPalettes>() .SelectMany(p => p.PaletteNames) .Concat(colorPickerPalettes) .ToArray(); var ticker = panel.GetOrNull <LogicTickerWidget>("ANIMATION_TICKER"); if (ticker != null) { ticker.OnTick = () => { if (animateFrames && currentSprites != null) { SelectNextFrame(); } }; } var sourceDropdown = panel.GetOrNull <DropDownButtonWidget>("SOURCE_SELECTOR"); if (sourceDropdown != null) { sourceDropdown.OnMouseDown = _ => ShowSourceDropdown(sourceDropdown); var sourceName = new CachedTransform <IReadOnlyPackage, string>(GetSourceDisplayName); sourceDropdown.GetText = () => sourceName.Update(assetSource); } var spriteWidget = panel.GetOrNull <SpriteWidget>("SPRITE"); if (spriteWidget != null) { spriteWidget.GetSprite = () => currentSprites != null ? currentSprites[currentFrame] : null; currentPalette = spriteWidget.Palette; spriteScale = spriteWidget.Scale; spriteWidget.GetPalette = () => currentPalette; spriteWidget.IsVisible = () => !isVideoLoaded && !isLoadError && currentSprites != null; spriteWidget.GetScale = () => spriteScale; } var playerWidget = panel.GetOrNull <VideoPlayerWidget>("PLAYER"); if (playerWidget != null) { playerWidget.IsVisible = () => isVideoLoaded && !isLoadError; } var modelWidget = panel.GetOrNull <ModelWidget>("VOXEL"); if (modelWidget != null) { modelWidget.GetVoxel = () => currentVoxel; currentPalette = modelWidget.Palette; modelScale = modelWidget.Scale; modelWidget.GetPalette = () => currentPalette; modelWidget.GetPlayerPalette = () => currentPalette; modelWidget.GetRotation = () => modelOrientation; modelWidget.IsVisible = () => !isVideoLoaded && !isLoadError && currentVoxel != null; modelWidget.GetScale = () => modelScale; } var errorLabelWidget = panel.GetOrNull("ERROR"); if (errorLabelWidget != null) { errorLabelWidget.IsVisible = () => isLoadError; } var paletteDropDown = panel.GetOrNull <DropDownButtonWidget>("PALETTE_SELECTOR"); if (paletteDropDown != null) { paletteDropDown.OnMouseDown = _ => ShowPaletteDropdown(paletteDropDown); paletteDropDown.GetText = () => currentPalette; paletteDropDown.IsVisible = () => currentSprites != null || currentVoxel != null; panel.GetOrNull <LabelWidget>("PALETTE_DESC").IsVisible = () => currentSprites != null || currentVoxel != null; } var colorManager = modData.DefaultRules.Actors[SystemActors.World].TraitInfo <ColorPickerManagerInfo>(); colorManager.Color = Game.Settings.Player.Color; var colorDropdown = panel.GetOrNull <DropDownButtonWidget>("COLOR"); if (colorDropdown != null) { colorDropdown.IsDisabled = () => !colorPickerPalettes.Contains(currentPalette); colorDropdown.OnMouseDown = _ => ColorPickerLogic.ShowColorDropDown(colorDropdown, colorManager, worldRenderer); colorDropdown.IsVisible = () => currentSprites != null || currentVoxel != null; panel.Get <ColorBlockWidget>("COLORBLOCK").GetColor = () => colorManager.Color; } filenameInput = panel.Get <TextFieldWidget>("FILENAME_INPUT"); filenameInput.OnTextEdited = () => ApplyFilter(); filenameInput.OnEscKey = _ => { if (string.IsNullOrEmpty(filenameInput.Text)) { filenameInput.YieldKeyboardFocus(); } else { filenameInput.Text = ""; filenameInput.OnTextEdited(); } return(true); }; var frameContainer = panel.GetOrNull("FRAME_SELECTOR"); if (frameContainer != null) { frameContainer.IsVisible = () => (currentSprites != null && currentSprites.Length > 1) || (isVideoLoaded && player != null && player.Video != null && player.Video.FrameCount > 1) || currentSoundFormat != null; } frameSlider = panel.GetOrNull <SliderWidget>("FRAME_SLIDER"); if (frameSlider != null) { frameSlider.OnChange += x => { if (!isVideoLoaded) { currentFrame = (int)Math.Round(x); } }; frameSlider.GetValue = () => { if (isVideoLoaded) { return(player.Video.CurrentFrameIndex); } if (currentSound != null) { return(currentSound.SeekPosition * currentSoundFormat.SampleRate); } return(currentFrame); }; frameSlider.IsDisabled = () => isVideoLoaded || currentSoundFormat != null; } var frameText = panel.GetOrNull <LabelWidget>("FRAME_COUNT"); if (frameText != null) { frameText.GetText = () => { if (isVideoLoaded) { return($"{player.Video.CurrentFrameIndex + 1} / {player.Video.FrameCount}"); } if (currentSoundFormat != null) { return($"{Math.Round(currentSoundFormat.LengthInSeconds, 3)} sec"); } return($"{currentFrame} / {currentSprites.Length - 1}"); }; } var playButton = panel.GetOrNull <ButtonWidget>("BUTTON_PLAY"); if (playButton != null) { playButton.OnClick = () => { if (isVideoLoaded) { player.Play(); } else if (currentSoundFormat != null) { if (currentSound != null) { Game.Sound.StopSound(currentSound); } currentSound = Game.Sound.Play(currentSoundFormat, Game.Sound.SoundVolume); } else { animateFrames = true; } }; playButton.IsVisible = () => isVideoLoaded ? player.Paused : !animateFrames || currentSoundFormat != null; } var pauseButton = panel.GetOrNull <ButtonWidget>("BUTTON_PAUSE"); if (pauseButton != null) { pauseButton.OnClick = () => { if (isVideoLoaded) { player.Pause(); } else { animateFrames = false; } }; pauseButton.IsVisible = () => isVideoLoaded ? !player.Paused : (animateFrames && currentSoundFormat == null); } var stopButton = panel.GetOrNull <ButtonWidget>("BUTTON_STOP"); if (stopButton != null) { stopButton.OnClick = () => { if (isVideoLoaded) { player.Stop(); } else if (currentSound != null) { Game.Sound.StopSound(currentSound); } else { currentFrame = 0; animateFrames = false; } if (frameSlider != null) { frameSlider.Value = 0; } }; } var nextButton = panel.GetOrNull <ButtonWidget>("BUTTON_NEXT"); if (nextButton != null) { nextButton.OnClick = () => { if (!isVideoLoaded) { nextButton.OnClick = SelectNextFrame; } }; nextButton.IsVisible = () => !isVideoLoaded && currentSoundFormat == null; } var prevButton = panel.GetOrNull <ButtonWidget>("BUTTON_PREV"); if (prevButton != null) { prevButton.OnClick = () => { if (!isVideoLoaded) { SelectPreviousFrame(); } }; prevButton.IsVisible = () => !isVideoLoaded && currentSoundFormat == null; } var spriteScaleSlider = panel.GetOrNull <SliderWidget>("SPRITE_SCALE_SLIDER"); if (spriteScaleSlider != null) { spriteScaleSlider.OnChange += x => spriteScale = x; spriteScaleSlider.GetValue = () => spriteScale; spriteScaleSlider.IsVisible = () => currentSprites != null; panel.GetOrNull <LabelWidget>("SPRITE_SCALE").IsVisible = () => currentSprites != null; } var voxelContainer = panel.GetOrNull("VOXEL_SELECTOR"); if (voxelContainer != null) { voxelContainer.IsVisible = () => currentVoxel != null; } var rollSlider = panel.GetOrNull <SliderWidget>("ROLL_SLIDER"); if (rollSlider != null) { rollSlider.OnChange += x => { var roll = (int)x; modelOrientation = modelOrientation.WithRoll(new WAngle(roll)); }; rollSlider.GetValue = () => modelOrientation.Roll.Angle; } var pitchSlider = panel.GetOrNull <SliderWidget>("PITCH_SLIDER"); if (pitchSlider != null) { pitchSlider.OnChange += x => { var pitch = (int)x; modelOrientation = modelOrientation.WithPitch(new WAngle(pitch)); }; pitchSlider.GetValue = () => modelOrientation.Pitch.Angle; } var yawSlider = panel.GetOrNull <SliderWidget>("YAW_SLIDER"); if (yawSlider != null) { yawSlider.OnChange += x => { var yaw = (int)x; modelOrientation = modelOrientation.WithYaw(new WAngle(yaw)); }; yawSlider.GetValue = () => modelOrientation.Yaw.Angle; } var modelScaleSlider = panel.GetOrNull <SliderWidget>("MODEL_SCALE_SLIDER"); if (modelScaleSlider != null) { modelScaleSlider.OnChange += x => modelScale = x; modelScaleSlider.GetValue = () => modelScale; modelScaleSlider.IsVisible = () => currentVoxel != null; panel.GetOrNull <LabelWidget>("MODEL_SCALE").IsVisible = () => currentVoxel != null; } var assetBrowserModData = modData.Manifest.Get <AssetBrowser>(); allowedSpriteExtensions = assetBrowserModData.SpriteExtensions; allowedModelExtensions = assetBrowserModData.ModelExtensions; allowedAudioExtensions = assetBrowserModData.AudioExtensions; allowedVideoExtensions = assetBrowserModData.VideoExtensions; allowedExtensions = allowedSpriteExtensions .Union(allowedModelExtensions) .Union(allowedAudioExtensions) .Union(allowedVideoExtensions) .ToArray(); acceptablePackages = modData.ModFiles.MountedPackages.Where(p => p.Contents.Any(c => allowedExtensions.Contains(Path.GetExtension(c).ToLowerInvariant()))); assetList = panel.Get <ScrollPanelWidget>("ASSET_LIST"); template = panel.Get <ScrollItemWidget>("ASSET_TEMPLATE"); PopulateAssetList(); var closeButton = panel.GetOrNull <ButtonWidget>("CLOSE_BUTTON"); if (closeButton != null) { closeButton.OnClick = () => { ClearLoadedAssets(); Ui.CloseWindow(); onExit(); } } ; } void SelectNextFrame() { currentFrame++; if (currentFrame >= currentSprites.Length) { currentFrame = 0; } } void SelectPreviousFrame() { currentFrame--; if (currentFrame < 0) { currentFrame = currentSprites.Length - 1; } }
public IrcLogic(Widget widget) { var historyPanel = widget.Get <ScrollPanelWidget>("HISTORY_PANEL"); var historyTemplate = widget.Get <LabelWidget>("HISTORY_TEMPLATE"); var nicknamePanel = widget.Get <ScrollPanelWidget>("NICKNAME_PANEL"); var nicknameTemplate = widget.Get <LabelWidget>("NICKNAME_TEMPLATE"); inputBox = widget.Get <TextFieldWidget>("INPUT_BOX"); inputBox.OnEnterKey = EnterPressed; inputBox.OnTabKey = TabPressed; inputBox.IsDisabled = () => IrcClient.Instance.GetChannel(IrcClient.MainChannel) == null; nicknameBox = widget.Get <TextFieldWidget>("NICKNAME_BOX"); nicknameBox.Text = ChooseNickname(Game.Settings.Irc.Nickname); connectBG = widget.Get("IRC_CONNECT_BG"); ircContainer = widget.Get("IRC_CONTAINER"); widget.Get <ButtonWidget>("DISCONNECT_BUTTON").OnClick = IrcClient.Instance.Disconnect; MaybeShowConnectPanel(); historyPanel.Bind(IrcClient.Instance.History, item => MakeLabelWidget(historyTemplate, item), LabelItemEquals, true); var mainChannel = IrcClient.Instance.GetChannel(IrcClient.MainChannel); if (mainChannel != null) { nicknamePanel.Bind(mainChannel.Users, item => MakeLabelWidget(nicknameTemplate, item), LabelItemEquals, false); } IrcClient.Instance.OnSync += l => { var channel = l.GetChannel(); if (channel.Name.EqualsIC(IrcClient.MainChannel)) { nicknamePanel.Bind(channel.Users, item => MakeLabelWidget(nicknameTemplate, item), LabelItemEquals, false); } }; IrcClient.Instance.OnKick += l => { if (l.KickeeNickname.EqualsIC(IrcClient.Instance.LocalUser.Nickname) && l.Target.EqualsIC(IrcClient.MainChannel)) { nicknamePanel.Unbind(); } }; IrcClient.Instance.OnPart += l => { if (l.PrefixIsSelf() && l.Target.EqualsIC(IrcClient.MainChannel)) { nicknamePanel.Unbind(); } }; IrcClient.Instance.OnDisconnect += () => { nicknamePanel.Unbind(); MaybeShowConnectPanel(); }; commands.Add("me", args => { IrcClient.Instance.Act(IrcClient.MainChannel, args); IrcClient.AddAction(IrcClient.Instance.LocalUser.Nickname, args); }); commands.Add("slap", args => { IrcClient.Instance.Act(IrcClient.MainChannel, "slaps {0} around a bit with a large trout".F(args)); IrcClient.AddAction(IrcClient.Instance.LocalUser.Nickname, "slaps {0} around a bit with a large trout".F(args)); }); commands.Add("notice", args => { var split = args.Split(new[] { ' ' }, 2); if (split.Length < 2) { IrcClient.AddHistory("/notice: Not enough arguments"); return; } IrcClient.Instance.Notice(split[0], split[1]); IrcClient.AddSelfNotice(split[0], split[1]); }); commands.Add("disconnect", args => { Game.Settings.Irc.ConnectAutomatically = false; Game.Settings.Save(); IrcClient.Instance.Disconnect(); }); commands.Add("quit", args => { Game.Settings.Irc.ConnectAutomatically = false; Game.Settings.Save(); if (IrcClient.Instance.IsConnected) { IrcClient.Instance.Quit(args); } else { IrcClient.Instance.Disconnect(); } }); commands.Add("nick", args => IrcClient.Instance.SetNickname(args)); commands.Add("topic", args => IrcClient.Instance.GetTopic(IrcClient.MainChannel)); }
public AssetBrowserLogic(Widget widget, Action onExit, World world) { panel = widget; var sourceDropdown = panel.Get <DropDownButtonWidget>("SOURCE_SELECTOR"); sourceDropdown.OnMouseDown = _ => ShowSourceDropdown(sourceDropdown); sourceDropdown.GetText = () => { var name = assetSource != null?assetSource.Name.Replace(Platform.SupportDir, "^") : "All Packages"; if (name.Length > 15) { name = "..." + name.Substring(name.Length - 15); } return(name); }; assetSource = FileSystem.MountedFolders.First(); spriteWidget = panel.Get <ShpImageWidget>("SPRITE"); currentPalette = world.WorldActor.TraitsImplementing <PaletteFromFile>().First(p => p.Name == spriteWidget.Palette); var paletteDropDown = panel.Get <DropDownButtonWidget>("PALETTE_SELECTOR"); paletteDropDown.OnMouseDown = _ => ShowPaletteDropdown(paletteDropDown, world); paletteDropDown.GetText = () => currentPalette.Name; var colorPreview = panel.Get <ColorPreviewManagerWidget>("COLOR_MANAGER"); colorPreview.Color = Game.Settings.Player.Color; var color = panel.Get <DropDownButtonWidget>("COLOR"); color.IsDisabled = () => currentPalette.Name != colorPreview.Palette; color.OnMouseDown = _ => ShowColorDropDown(color, colorPreview, world); var block = panel.Get <ColorBlockWidget>("COLORBLOCK"); block.GetColor = () => Game.Settings.Player.Color.RGB; filenameInput = panel.Get <TextFieldWidget>("FILENAME_INPUT"); filenameInput.OnEnterKey = () => LoadAsset(filenameInput.Text); frameSlider = panel.Get <SliderWidget>("FRAME_SLIDER"); frameSlider.MaximumValue = (float)spriteWidget.FrameCount; frameSlider.Ticks = spriteWidget.FrameCount + 1; frameSlider.IsVisible = () => spriteWidget.FrameCount > 0; frameSlider.OnChange += x => { spriteWidget.Frame = (int)Math.Round(x); }; frameSlider.GetValue = () => spriteWidget.Frame; panel.Get <LabelWidget>("FRAME_COUNT").GetText = () => "{0} / {1}".F(spriteWidget.Frame + 1, spriteWidget.FrameCount + 1); playButton = panel.Get <ButtonWidget>("BUTTON_PLAY"); playButton.OnClick = () => { spriteWidget.LoopAnimation = true; playButton.Visible = false; pauseButton.Visible = true; }; pauseButton = panel.Get <ButtonWidget>("BUTTON_PAUSE"); pauseButton.OnClick = () => { spriteWidget.LoopAnimation = false; playButton.Visible = true; pauseButton.Visible = false; }; panel.Get <ButtonWidget>("BUTTON_STOP").OnClick = () => { spriteWidget.LoopAnimation = false; frameSlider.Value = 0; spriteWidget.Frame = 0; playButton.Visible = true; pauseButton.Visible = false; }; panel.Get <ButtonWidget>("BUTTON_NEXT").OnClick = () => { spriteWidget.RenderNextFrame(); }; panel.Get <ButtonWidget>("BUTTON_PREV").OnClick = () => { spriteWidget.RenderPreviousFrame(); }; panel.Get <ButtonWidget>("LOAD_BUTTON").OnClick = () => { LoadAsset(filenameInput.Text); }; assetList = panel.Get <ScrollPanelWidget>("ASSET_LIST"); template = panel.Get <ScrollItemWidget>("ASSET_TEMPLATE"); PopulateAssetList(); panel.Get <ButtonWidget>("CLOSE_BUTTON").OnClick = () => { Ui.CloseWindow(); onExit(); }; }
public AssetBrowserLogic(Widget widget, Action onExit, World world) { this.world = world; panel = widget; assetSource = GlobalFileSystem.MountedFolders.First(); var ticker = panel.GetOrNull <LogicTickerWidget>("ANIMATION_TICKER"); if (ticker != null) { ticker.OnTick = () => { if (animateFrames) { SelectNextFrame(); } }; } var sourceDropdown = panel.GetOrNull <DropDownButtonWidget>("SOURCE_SELECTOR"); if (sourceDropdown != null) { sourceDropdown.OnMouseDown = _ => ShowSourceDropdown(sourceDropdown); sourceDropdown.GetText = () => { var name = assetSource != null?assetSource.Name.Replace(Platform.SupportDir, "^") : "All Packages"; if (name.Length > 15) { name = "..." + name.Substring(name.Length - 15); } return(name); }; } var spriteWidget = panel.GetOrNull <SpriteWidget>("SPRITE"); if (spriteWidget != null) { spriteWidget.GetSprite = () => currentSprites != null ? currentSprites[currentFrame] : null; currentPalette = spriteWidget.Palette; spriteWidget.GetPalette = () => currentPalette; } var paletteDropDown = panel.GetOrNull <DropDownButtonWidget>("PALETTE_SELECTOR"); if (paletteDropDown != null) { paletteDropDown.OnMouseDown = _ => ShowPaletteDropdown(paletteDropDown, world); paletteDropDown.GetText = () => currentPalette; } var colorPreview = panel.GetOrNull <ColorPreviewManagerWidget>("COLOR_MANAGER"); if (colorPreview != null) { colorPreview.Color = Game.Settings.Player.Color; } var colorDropdown = panel.GetOrNull <DropDownButtonWidget>("COLOR"); if (colorDropdown != null) { colorDropdown.IsDisabled = () => currentPalette != colorPreview.PaletteName; colorDropdown.OnMouseDown = _ => ShowColorDropDown(colorDropdown, colorPreview, world); panel.Get <ColorBlockWidget>("COLORBLOCK").GetColor = () => Game.Settings.Player.Color.RGB; } filenameInput = panel.Get <TextFieldWidget>("FILENAME_INPUT"); filenameInput.OnTextEdited = () => ApplyFilter(filenameInput.Text); var frameContainer = panel.GetOrNull("FRAME_SELECTOR"); if (frameContainer != null) { frameContainer.IsVisible = () => currentSprites != null && currentSprites.Length > 1; } frameSlider = panel.Get <SliderWidget>("FRAME_SLIDER"); frameSlider.OnChange += x => { currentFrame = (int)Math.Round(x); }; frameSlider.GetValue = () => currentFrame; var frameText = panel.GetOrNull <LabelWidget>("FRAME_COUNT"); if (frameText != null) { frameText.GetText = () => "{0} / {1}".F(currentFrame + 1, currentSprites.Length); } var playButton = panel.GetOrNull <ButtonWidget>("BUTTON_PLAY"); if (playButton != null) { playButton.OnClick = () => animateFrames = true; playButton.IsVisible = () => !animateFrames; } var pauseButton = panel.GetOrNull <ButtonWidget>("BUTTON_PAUSE"); if (pauseButton != null) { pauseButton.OnClick = () => animateFrames = false; pauseButton.IsVisible = () => animateFrames; } var stopButton = panel.GetOrNull <ButtonWidget>("BUTTON_STOP"); if (stopButton != null) { stopButton.OnClick = () => { frameSlider.Value = 0; currentFrame = 0; animateFrames = false; }; } var nextButton = panel.GetOrNull <ButtonWidget>("BUTTON_NEXT"); if (nextButton != null) { nextButton.OnClick = SelectNextFrame; } var prevButton = panel.GetOrNull <ButtonWidget>("BUTTON_PREV"); if (prevButton != null) { prevButton.OnClick = SelectPreviousFrame; } assetList = panel.Get <ScrollPanelWidget>("ASSET_LIST"); template = panel.Get <ScrollItemWidget>("ASSET_TEMPLATE"); PopulateAssetList(); var closeButton = panel.GetOrNull <ButtonWidget>("CLOSE_BUTTON"); if (closeButton != null) { closeButton.OnClick = () => { Ui.CloseWindow(); onExit(); } } ; } void SelectNextFrame() { currentFrame++; if (currentFrame >= currentSprites.Length) { currentFrame = 0; } } void SelectPreviousFrame() { currentFrame--; if (currentFrame < 0) { currentFrame = currentSprites.Length - 1; } } Dictionary <string, bool> assetVisByName = new Dictionary <string, bool>(); bool FilterAsset(string filename) { var filter = filenameInput.Text; if (string.IsNullOrWhiteSpace(filter)) { return(true); } if (filename.IndexOf(filter, StringComparison.OrdinalIgnoreCase) >= 0) { return(true); } return(false); } void ApplyFilter(string filename) { assetVisByName.Clear(); assetList.Layout.AdjustChildren(); assetList.ScrollToTop(); // Select the first visible var firstVisible = assetVisByName.FirstOrDefault(kvp => kvp.Value); if (firstVisible.Key != null) { LoadAsset(firstVisible.Key); } } void AddAsset(ScrollPanelWidget list, string filepath, ScrollItemWidget template) { var filename = Path.GetFileName(filepath); var item = ScrollItemWidget.Setup(template, () => currentFilename == filename, () => { LoadAsset(filename); }); item.Get <LabelWidget>("TITLE").GetText = () => filepath; item.IsVisible = () => { bool visible; if (assetVisByName.TryGetValue(filepath, out visible)) { return(visible); } visible = FilterAsset(filepath); assetVisByName.Add(filepath, visible); return(visible); }; list.AddChild(item); } bool LoadAsset(string filename) { if (string.IsNullOrEmpty(filename)) { return(false); } if (!GlobalFileSystem.Exists(filename)) { return(false); } currentFilename = filename; currentSprites = world.Map.SequenceProvider.SpriteLoader.LoadAllSprites(filename); currentFrame = 0; frameSlider.MaximumValue = (float)currentSprites.Length - 1; frameSlider.Ticks = currentSprites.Length; return(true); } bool ShowSourceDropdown(DropDownButtonWidget dropdown) { Func <IFolder, ScrollItemWidget, ScrollItemWidget> setupItem = (source, itemTemplate) => { var item = ScrollItemWidget.Setup(itemTemplate, () => assetSource == source, () => { assetSource = source; PopulateAssetList(); }); item.Get <LabelWidget>("LABEL").GetText = () => source != null?source.Name.Replace(Platform.SupportDir, "^") : "All Packages"; return(item); }; // TODO: Re-enable "All Packages" once list generation is done in a background thread // var sources = new[] { (IFolder)null }.Concat(GlobalFileSystem.MountedFolders); var sources = GlobalFileSystem.MountedFolders; dropdown.ShowDropDown("LABEL_DROPDOWN_TEMPLATE", 280, sources, setupItem); return(true); } void PopulateAssetList() { assetList.RemoveChildren(); availableShps.Clear(); // TODO: This is too slow to run in the main thread // var files = AssetSource != null ? AssetSource.AllFileNames() : // GlobalFileSystem.MountedFolders.SelectMany(f => f.AllFileNames()); if (assetSource == null) { return; } var files = assetSource.AllFileNames().OrderBy(s => s); foreach (var file in files) { if (AllowedExtensions.Any(ext => file.EndsWith(ext, true, CultureInfo.InvariantCulture))) { AddAsset(assetList, file, template); availableShps.Add(file); } } } bool ShowPaletteDropdown(DropDownButtonWidget dropdown, World world) { Func <PaletteFromFile, ScrollItemWidget, ScrollItemWidget> setupItem = (palette, itemTemplate) => { var name = palette.Name; var item = ScrollItemWidget.Setup(itemTemplate, () => currentPalette == name, () => currentPalette = name); item.Get <LabelWidget>("LABEL").GetText = () => name; return(item); }; var palettes = world.WorldActor.TraitsImplementing <PaletteFromFile>(); dropdown.ShowDropDown("LABEL_DROPDOWN_TEMPLATE", 280, palettes, setupItem); return(true); }
public IngameChatLogic(Widget widget, OrderManager orderManager, World world, Ruleset modRules) { this.modRules = modRules; chatTraits = world.WorldActor.TraitsImplementing <INotifyChat>().ToList(); var players = world.Players.Where(p => p != world.LocalPlayer && !p.NonCombatant && !p.IsBot); var disableTeamChat = world.LocalPlayer == null || world.LobbyInfo.IsSinglePlayer || !players.Any(p => p.IsAlliedWith(world.LocalPlayer)); teamChat = !disableTeamChat; var chatPanel = (ContainerWidget)widget; chatOverlay = chatPanel.Get <ContainerWidget>("CHAT_OVERLAY"); chatOverlayDisplay = chatOverlay.Get <ChatDisplayWidget>("CHAT_DISPLAY"); chatOverlay.Visible = false; chatChrome = chatPanel.Get <ContainerWidget>("CHAT_CHROME"); chatChrome.Visible = true; var chatMode = chatChrome.Get <ButtonWidget>("CHAT_MODE"); chatMode.GetText = () => teamChat ? "Team" : "All"; chatMode.OnClick = () => teamChat ^= true; chatMode.IsDisabled = () => disableTeamChat; chatText = chatChrome.Get <TextFieldWidget>("CHAT_TEXTFIELD"); chatText.OnTabKey = () => { if (!disableTeamChat) { teamChat ^= true; } return(true); }; chatText.OnEnterKey = () => { var team = teamChat && !disableTeamChat; if (chatText.Text != "") { orderManager.IssueOrder(Order.Chat(team, chatText.Text.Trim())); } CloseChat(); return(true); }; chatText.OnEscKey = () => { CloseChat(); return(true); }; var chatClose = chatChrome.Get <ButtonWidget>("CHAT_CLOSE"); chatClose.OnClick += () => CloseChat(); chatPanel.OnKeyPress = (e) => { if (e.Event == KeyInputEvent.Up) { return(false); } if (!chatChrome.IsVisible() && (e.Key == Keycode.RETURN || e.Key == Keycode.KP_ENTER)) { OpenChat(); return(true); } return(false); }; chatScrollPanel = chatChrome.Get <ScrollPanelWidget>("CHAT_SCROLLPANEL"); chatTemplate = chatScrollPanel.Get <ContainerWidget>("CHAT_TEMPLATE"); chatScrollPanel.RemoveChildren(); Game.AddChatLine += AddChatLine; Game.BeforeGameStart += UnregisterEvents; CloseChat(); }
public virtual TResult Visit(TextFieldWidget expression, TEnvironment environment) { return(default(TResult)); }
public AssetBrowserLogic(Widget widget, Action onExit, ModData modData, World world, Dictionary <string, MiniYaml> logicArgs) { this.world = world; this.modData = modData; panel = widget; var ticker = panel.GetOrNull <LogicTickerWidget>("ANIMATION_TICKER"); if (ticker != null) { ticker.OnTick = () => { if (animateFrames) { SelectNextFrame(); } }; } var sourceDropdown = panel.GetOrNull <DropDownButtonWidget>("SOURCE_SELECTOR"); if (sourceDropdown != null) { sourceDropdown.OnMouseDown = _ => ShowSourceDropdown(sourceDropdown); sourceDropdown.GetText = () => { var name = assetSource != null?Platform.UnresolvePath(assetSource.Name) : "All Packages"; if (name.Length > 15) { name = "..." + name.Substring(name.Length - 15); } return(name); }; } var spriteWidget = panel.GetOrNull <SpriteWidget>("SPRITE"); if (spriteWidget != null) { spriteWidget.GetSprite = () => currentSprites != null ? currentSprites[currentFrame] : null; currentPalette = spriteWidget.Palette; spriteWidget.GetPalette = () => currentPalette; spriteWidget.IsVisible = () => !isVideoLoaded; } var playerWidget = panel.GetOrNull <VqaPlayerWidget>("PLAYER"); if (playerWidget != null) { playerWidget.IsVisible = () => isVideoLoaded; } var paletteDropDown = panel.GetOrNull <DropDownButtonWidget>("PALETTE_SELECTOR"); if (paletteDropDown != null) { paletteDropDown.OnMouseDown = _ => ShowPaletteDropdown(paletteDropDown, world); paletteDropDown.GetText = () => currentPalette; } var colorPreview = panel.GetOrNull <ColorPreviewManagerWidget>("COLOR_MANAGER"); if (colorPreview != null) { colorPreview.Color = Game.Settings.Player.Color; } var colorDropdown = panel.GetOrNull <DropDownButtonWidget>("COLOR"); if (colorDropdown != null) { colorDropdown.IsDisabled = () => currentPalette != colorPreview.PaletteName; colorDropdown.OnMouseDown = _ => ColorPickerLogic.ShowColorDropDown(colorDropdown, colorPreview, world); panel.Get <ColorBlockWidget>("COLORBLOCK").GetColor = () => Game.Settings.Player.Color.RGB; } filenameInput = panel.Get <TextFieldWidget>("FILENAME_INPUT"); filenameInput.OnTextEdited = () => ApplyFilter(filenameInput.Text); filenameInput.OnEscKey = filenameInput.YieldKeyboardFocus; var frameContainer = panel.GetOrNull("FRAME_SELECTOR"); if (frameContainer != null) { frameContainer.IsVisible = () => (currentSprites != null && currentSprites.Length > 1) || (isVideoLoaded && player != null && player.Video != null && player.Video.Frames > 1); } frameSlider = panel.Get <SliderWidget>("FRAME_SLIDER"); if (frameSlider != null) { frameSlider.OnChange += x => { if (!isVideoLoaded) { currentFrame = (int)Math.Round(x); } }; frameSlider.GetValue = () => isVideoLoaded ? player.Video.CurrentFrame : currentFrame; frameSlider.IsDisabled = () => isVideoLoaded; } var frameText = panel.GetOrNull <LabelWidget>("FRAME_COUNT"); if (frameText != null) { frameText.GetText = () => isVideoLoaded ? "{0} / {1}".F(player.Video.CurrentFrame + 1, player.Video.Frames) : "{0} / {1}".F(currentFrame, currentSprites.Length - 1); } var playButton = panel.GetOrNull <ButtonWidget>("BUTTON_PLAY"); if (playButton != null) { playButton.Key = new Hotkey(Keycode.SPACE, Modifiers.None); playButton.OnClick = () => { if (isVideoLoaded) { player.Play(); } else { animateFrames = true; } }; playButton.IsVisible = () => isVideoLoaded ? player.Paused : !animateFrames; } var pauseButton = panel.GetOrNull <ButtonWidget>("BUTTON_PAUSE"); if (pauseButton != null) { pauseButton.Key = new Hotkey(Keycode.SPACE, Modifiers.None); pauseButton.OnClick = () => { if (isVideoLoaded) { player.Pause(); } else { animateFrames = false; } }; pauseButton.IsVisible = () => isVideoLoaded ? !player.Paused : animateFrames; } var stopButton = panel.GetOrNull <ButtonWidget>("BUTTON_STOP"); if (stopButton != null) { stopButton.Key = new Hotkey(Keycode.RETURN, Modifiers.None); stopButton.OnClick = () => { if (isVideoLoaded) { player.Stop(); } else { frameSlider.Value = 0; currentFrame = 0; animateFrames = false; } }; } var nextButton = panel.GetOrNull <ButtonWidget>("BUTTON_NEXT"); if (nextButton != null) { nextButton.Key = new Hotkey(Keycode.RIGHT, Modifiers.None); nextButton.OnClick = () => { if (!isVideoLoaded) { nextButton.OnClick = SelectNextFrame; } }; nextButton.IsVisible = () => !isVideoLoaded; } var prevButton = panel.GetOrNull <ButtonWidget>("BUTTON_PREV"); if (prevButton != null) { prevButton.Key = new Hotkey(Keycode.LEFT, Modifiers.None); prevButton.OnClick = () => { if (!isVideoLoaded) { SelectPreviousFrame(); } }; prevButton.IsVisible = () => !isVideoLoaded; } if (logicArgs.ContainsKey("SupportedFormats")) { allowedExtensions = FieldLoader.GetValue <string[]>("SupportedFormats", logicArgs["SupportedFormats"].Value); } else { allowedExtensions = new string[0]; } acceptablePackages = modData.ModFiles.MountedPackages.Where(p => p.Contents.Any(c => allowedExtensions.Contains(Path.GetExtension(c).ToLowerInvariant()))); assetList = panel.Get <ScrollPanelWidget>("ASSET_LIST"); template = panel.Get <ScrollItemWidget>("ASSET_TEMPLATE"); PopulateAssetList(); var closeButton = panel.GetOrNull <ButtonWidget>("CLOSE_BUTTON"); if (closeButton != null) { closeButton.OnClick = () => { if (isVideoLoaded) { player.Stop(); } Ui.CloseWindow(); onExit(); } } ; } void SelectNextFrame() { currentFrame++; if (currentFrame >= currentSprites.Length) { currentFrame = 0; } } void SelectPreviousFrame() { currentFrame--; if (currentFrame < 0) { currentFrame = currentSprites.Length - 1; } } Dictionary <string, bool> assetVisByName = new Dictionary <string, bool>(); bool FilterAsset(string filename) { var filter = filenameInput.Text; if (string.IsNullOrWhiteSpace(filter)) { return(true); } if (filename.IndexOf(filter, StringComparison.OrdinalIgnoreCase) >= 0) { return(true); } return(false); } void ApplyFilter(string filename) { assetVisByName.Clear(); assetList.Layout.AdjustChildren(); assetList.ScrollToTop(); // Select the first visible var firstVisible = assetVisByName.FirstOrDefault(kvp => kvp.Value); if (firstVisible.Key != null) { LoadAsset(firstVisible.Key); } } void AddAsset(ScrollPanelWidget list, string filepath, ScrollItemWidget template) { var filename = Path.GetFileName(filepath); var item = ScrollItemWidget.Setup(template, () => currentFilename == filename, () => { LoadAsset(filename); }); item.Get <LabelWidget>("TITLE").GetText = () => filepath; item.IsVisible = () => { bool visible; if (assetVisByName.TryGetValue(filepath, out visible)) { return(visible); } visible = FilterAsset(filepath); assetVisByName.Add(filepath, visible); return(visible); }; list.AddChild(item); } bool LoadAsset(string filename) { if (isVideoLoaded) { player.Stop(); player = null; isVideoLoaded = false; } if (string.IsNullOrEmpty(filename)) { return(false); } if (!modData.DefaultFileSystem.Exists(filename)) { return(false); } if (Path.GetExtension(filename.ToLowerInvariant()) == ".vqa") { player = panel.Get <VqaPlayerWidget>("PLAYER"); currentFilename = filename; player.Load(filename); player.DrawOverlay = false; isVideoLoaded = true; frameSlider.MaximumValue = (float)player.Video.Frames - 1; frameSlider.Ticks = 0; return(true); } else { currentFilename = filename; currentSprites = world.Map.Rules.Sequences.SpriteCache[filename]; currentFrame = 0; frameSlider.MaximumValue = (float)currentSprites.Length - 1; frameSlider.Ticks = currentSprites.Length; } return(true); } bool ShowSourceDropdown(DropDownButtonWidget dropdown) { Func <IReadOnlyPackage, ScrollItemWidget, ScrollItemWidget> setupItem = (source, itemTemplate) => { var item = ScrollItemWidget.Setup(itemTemplate, () => assetSource == source, () => { assetSource = source; PopulateAssetList(); }); item.Get <LabelWidget>("LABEL").GetText = () => source != null?Platform.UnresolvePath(source.Name) : "All Packages"; return(item); }; var sources = new[] { (IReadOnlyPackage)null }.Concat(acceptablePackages); dropdown.ShowDropDown("LABEL_DROPDOWN_TEMPLATE", 280, sources, setupItem); return(true); } void PopulateAssetList() { assetList.RemoveChildren(); availableShps.Clear(); var files = assetSource != null ? assetSource.Contents : modData.ModFiles.MountedPackages.SelectMany(f => f.Contents).Distinct(); foreach (var file in files.OrderBy(s => s)) { if (allowedExtensions.Any(ext => file.EndsWith(ext, true, CultureInfo.InvariantCulture))) { AddAsset(assetList, file, template); availableShps.Add(file); } } } bool ShowPaletteDropdown(DropDownButtonWidget dropdown, World world) { Func <string, ScrollItemWidget, ScrollItemWidget> setupItem = (name, itemTemplate) => { var item = ScrollItemWidget.Setup(itemTemplate, () => currentPalette == name, () => currentPalette = name); item.Get <LabelWidget>("LABEL").GetText = () => name; return(item); }; var palettes = world.WorldActor.TraitsImplementing <IProvidesAssetBrowserPalettes>() .SelectMany(p => p.PaletteNames); dropdown.ShowDropDown("LABEL_DROPDOWN_TEMPLATE", 280, palettes, setupItem); return(true); } }
public IngameChatLogic(Widget widget, OrderManager orderManager, World world) { World = world; var chatPanel = (ContainerWidget)widget; ChatOverlay = chatPanel.Get <ContainerWidget>("CHAT_OVERLAY"); ChatOverlayDisplay = ChatOverlay.Get <ChatDisplayWidget>("CHAT_DISPLAY"); ChatOverlay.Visible = false; ChatChrome = chatPanel.Get <ContainerWidget>("CHAT_CHROME"); ChatChrome.Visible = true; var chatMode = ChatChrome.Get <ButtonWidget>("CHAT_MODE"); chatMode.GetText = () => TeamChat ? "Team" : "All"; chatMode.OnClick = () => TeamChat = !TeamChat; ChatText = ChatChrome.Get <TextFieldWidget>("CHAT_TEXTFIELD"); ChatText.OnTabKey = () => { TeamChat = !TeamChat; return(true); }; ChatText.OnEnterKey = () => { ChatText.Text = ChatText.Text.Trim(); if (ChatText.Text != "") { orderManager.IssueOrder(Order.Chat(TeamChat, ChatText.Text)); } CloseChat(); return(true); }; ChatText.OnEscKey = () => { CloseChat(); return(true); }; var chatClose = ChatChrome.Get <ButtonWidget>("CHAT_CLOSE"); chatClose.OnClick += () => CloseChat(); chatPanel.OnKeyPress = (e) => { if (e.Event == KeyInputEvent.Up) { return(false); } if (!IsOpen && (e.KeyName == "enter" || e.KeyName == "return")) { var shift = e.Modifiers.HasModifier(Modifiers.Shift); var toggle = Game.Settings.Game.TeamChatToggle; TeamChat = (!toggle && shift) || (toggle && (TeamChat ^ shift)); OpenChat(); return(true); } return(false); }; ChatScrollPanel = ChatChrome.Get <ScrollPanelWidget>("CHAT_SCROLLPANEL"); ChatTemplate = ChatScrollPanel.Get <ContainerWidget>("CHAT_TEMPLATE"); Game.AddChatLine += AddChatLine; Game.BeforeGameStart += UnregisterEvents; CloseChat(); ChatOverlayDisplay.AddLine(Color.White, null, "Use RETURN key to open chat window..."); }
public IngameChatLogic(Widget widget, OrderManager orderManager, World world, ModData modData, bool isMenuChat, Dictionary <string, MiniYaml> logicArgs) { this.orderManager = orderManager; this.modRules = modData.DefaultRules; chatTraits = world.WorldActor.TraitsImplementing <INotifyChat>().ToArray(); var players = world.Players.Where(p => p != world.LocalPlayer && !p.NonCombatant && !p.IsBot); var isObserver = orderManager.LocalClient != null && orderManager.LocalClient.IsObserver; var isOnlyObserver = isObserver && orderManager.LobbyInfo.Clients.All(c => c == orderManager.LocalClient || !c.IsObserver); var observersExist = orderManager.LobbyInfo.Clients.Any(c => c.IsObserver); var alwaysDisabled = world.IsReplay || world.LobbyInfo.NonBotClients.Count() == 1; var disableTeamChat = alwaysDisabled || isOnlyObserver || (world.LocalPlayer != null && !players.Any(p => p.IsAlliedWith(world.LocalPlayer))); var teamChat = !disableTeamChat; tabCompletion.Commands = chatTraits.OfType <ChatCommands>().SelectMany(x => x.Commands.Keys).ToList(); tabCompletion.Names = orderManager.LobbyInfo.Clients.Select(c => c.Name).Distinct().ToList(); var chatPanel = (ContainerWidget)widget; chatOverlay = chatPanel.GetOrNull <ContainerWidget>("CHAT_OVERLAY"); if (chatOverlay != null) { chatOverlayDisplay = chatOverlay.Get <ChatDisplayWidget>("CHAT_DISPLAY"); chatOverlay.Visible = false; } chatChrome = chatPanel.Get <ContainerWidget>("CHAT_CHROME"); chatChrome.Visible = true; var chatMode = chatChrome.Get <ButtonWidget>("CHAT_MODE"); chatMode.GetText = () => teamChat && !disableTeamChat ? "Team" : "All"; chatMode.OnClick = () => teamChat ^= true; // Team chat is disabled if we are the only spectator // This changes as soon as a defeated player can talk in the spectator chat if (!alwaysDisabled && isOnlyObserver) { chatMode.IsDisabled = () => { if (world.IsGameOver) { return(true); } disableTeamChat = players.All(p => p.WinState == WinState.Undefined); return(disableTeamChat); }; } else if (!alwaysDisabled && world.LocalPlayer != null) { chatMode.IsDisabled = () => { if (world.IsGameOver) { return(true); } // Check if we are the only living team member if (players.All(p => p.WinState != WinState.Undefined || !p.IsAlliedWith(world.LocalPlayer))) { disableTeamChat = true; return(disableTeamChat); } // Still alive and nothing changed since the start if (world.LocalPlayer.WinState == WinState.Undefined) { return(disableTeamChat); } // At this point our player is dead // Allow to chat with existing spectators if (observersExist) { disableTeamChat = false; return(disableTeamChat); } // Or wait until another player died disableTeamChat = players.All(p => p.WinState == WinState.Undefined); return(disableTeamChat); }; } else { chatMode.IsDisabled = () => disableTeamChat; } // Disable team chat after the game ended world.GameOver += () => disableTeamChat = true; chatText = chatChrome.Get <TextFieldWidget>("CHAT_TEXTFIELD"); chatText.MaxLength = UnitOrders.ChatMessageMaxLength; chatText.OnEnterKey = () => { var team = teamChat && !disableTeamChat; if (chatText.Text != "") { if (!chatText.Text.StartsWith("/", StringComparison.Ordinal)) { // This should never happen, but avoid a crash if it does somehow (chat will just stay open) if (!isObserver && orderManager.LocalClient == null && world.LocalPlayer == null) { return(true); } var teamNumber = 0U; if (team) { teamNumber = (isObserver || world.LocalPlayer.WinState != WinState.Undefined) ? uint.MaxValue : (uint)orderManager.LocalClient.Team; } orderManager.IssueOrder(Order.Chat(chatText.Text.Trim(), teamNumber)); } else if (chatTraits != null) { var text = chatText.Text.Trim(); var from = world.IsReplay ? null : orderManager.LocalClient.Name; foreach (var trait in chatTraits) { trait.OnChat(from, text); } } } chatText.Text = ""; if (!isMenuChat) { CloseChat(); } return(true); }; chatText.OnTabKey = () => { var previousText = chatText.Text; chatText.Text = tabCompletion.Complete(chatText.Text); chatText.CursorPosition = chatText.Text.Length; if (chatText.Text == previousText && !disableTeamChat) { teamChat ^= true; } return(true); }; chatText.OnEscKey = () => { if (!isMenuChat) { CloseChat(); } else { chatText.YieldKeyboardFocus(); } return(true); }; if (!isMenuChat) { var chatClose = chatChrome.Get <ButtonWidget>("CHAT_CLOSE"); chatClose.OnClick += CloseChat; chatPanel.OnKeyPress = e => { if (e.Event == KeyInputEvent.Up) { return(false); } if (!chatChrome.IsVisible() && (e.Key == Keycode.RETURN || e.Key == Keycode.KP_ENTER)) { OpenChat(); return(true); } return(false); }; } chatScrollPanel = chatChrome.Get <ScrollPanelWidget>("CHAT_SCROLLPANEL"); chatTemplate = chatScrollPanel.Get <ContainerWidget>("CHAT_TEMPLATE"); chatScrollPanel.RemoveChildren(); chatScrollPanel.ScrollToBottom(); foreach (var chatLine in orderManager.ChatCache) { AddChatLine(chatLine.Name, chatLine.Color, chatLine.Text, chatLine.TextColor, true); } orderManager.AddChatLine += AddChatLineWrapper; chatText.IsDisabled = () => world.IsReplay && !Game.Settings.Debug.EnableDebugCommandsInReplays; if (!isMenuChat) { CloseChat(); var keyListener = chatChrome.Get <LogicKeyListenerWidget>("KEY_LISTENER"); keyListener.AddHandler(e => { if (e.Event == KeyInputEvent.Up || !chatText.IsDisabled()) { return(false); } if ((e.Key == Keycode.RETURN || e.Key == Keycode.KP_ENTER || e.Key == Keycode.ESCAPE) && e.Modifiers == Modifiers.None) { CloseChat(); return(true); } return(false); }); } MiniYaml yaml; if (logicArgs.TryGetValue("ChatLineSound", out yaml)) { chatLineSound = yaml.Value; } }
public IngameChatLogic(Widget widget, OrderManager orderManager, World world, ModData modData, bool isMenuChat, Dictionary <string, MiniYaml> logicArgs) { this.orderManager = orderManager; modRules = modData.DefaultRules; this.isMenuChat = isMenuChat; this.world = world; var chatTraits = world.WorldActor.TraitsImplementing <INotifyChat>().ToArray(); var players = world.Players.Where(p => p != world.LocalPlayer && !p.NonCombatant && !p.IsBot); var isObserver = orderManager.LocalClient != null && orderManager.LocalClient.IsObserver; var alwaysDisabled = world.IsReplay || world.LobbyInfo.NonBotClients.Count() == 1; var disableTeamChat = alwaysDisabled || (world.LocalPlayer != null && !players.Any(p => p.IsAlliedWith(world.LocalPlayer))); var teamChat = !disableTeamChat; tabCompletion.Commands = chatTraits.OfType <ChatCommands>().SelectMany(x => x.Commands.Keys).ToList(); tabCompletion.Names = orderManager.LobbyInfo.Clients.Select(c => c.Name).Distinct().ToList(); if (logicArgs.TryGetValue("Templates", out var templateIds)) { foreach (var item in templateIds.Nodes) { var key = FieldLoader.GetValue <TextNotificationPool>("key", item.Key); templates[key] = Ui.LoadWidget(item.Value.Value, null, new WidgetArgs()); } } var chatPanel = (ContainerWidget)widget; chatOverlay = chatPanel.GetOrNull <ContainerWidget>("CHAT_OVERLAY"); if (chatOverlay != null) { chatOverlayDisplay = chatOverlay.Get <TextNotificationsDisplayWidget>("CHAT_DISPLAY"); chatOverlay.Visible = false; } chatChrome = chatPanel.Get <ContainerWidget>("CHAT_CHROME"); chatChrome.Visible = true; var chatMode = chatChrome.Get <ButtonWidget>("CHAT_MODE"); chatMode.GetText = () => teamChat && !disableTeamChat ? "Team" : "All"; chatMode.OnClick = () => teamChat ^= true; // Enable teamchat if we are a player and die, // or disable it when we are the only one left in the team if (!alwaysDisabled && world.LocalPlayer != null) { chatMode.IsDisabled = () => { if (world.IsGameOver || !chatEnabled) { return(true); } // The game is over for us, join spectator team chat if (world.LocalPlayer.WinState != WinState.Undefined) { disableTeamChat = false; return(disableTeamChat); } // If team chat isn't already disabled, check if we are the only living team member if (!disableTeamChat) { disableTeamChat = players.All(p => p.WinState != WinState.Undefined || !p.IsAlliedWith(world.LocalPlayer)); } return(disableTeamChat); }; } else { chatMode.IsDisabled = () => disableTeamChat || !chatEnabled; } // Disable team chat after the game ended world.GameOver += () => disableTeamChat = true; chatText = chatChrome.Get <TextFieldWidget>("CHAT_TEXTFIELD"); chatText.MaxLength = UnitOrders.ChatMessageMaxLength; chatText.OnEnterKey = _ => { var team = teamChat && !disableTeamChat; if (chatText.Text != "") { if (!chatText.Text.StartsWith("/", StringComparison.Ordinal)) { // This should never happen, but avoid a crash if it does somehow (chat will just stay open) if (!isObserver && orderManager.LocalClient == null && world.LocalPlayer == null) { return(true); } var teamNumber = 0U; if (team) { teamNumber = (isObserver || world.LocalPlayer.WinState != WinState.Undefined) ? uint.MaxValue : (uint)orderManager.LocalClient.Team; } orderManager.IssueOrder(Order.Chat(chatText.Text.Trim(), teamNumber)); } else if (chatTraits != null) { var text = chatText.Text.Trim(); var from = world.IsReplay ? null : orderManager.LocalClient.Name; foreach (var trait in chatTraits) { trait.OnChat(from, text); } } } chatText.Text = ""; if (!isMenuChat) { CloseChat(); } return(true); }; chatText.OnTabKey = e => { if (!chatMode.Key.IsActivatedBy(e) || chatMode.IsDisabled()) { chatText.Text = tabCompletion.Complete(chatText.Text); chatText.CursorPosition = chatText.Text.Length; } else { chatMode.OnKeyPress(e); } return(true); }; chatText.OnEscKey = _ => { if (!isMenuChat) { CloseChat(); } else { chatText.YieldKeyboardFocus(); } return(true); }; chatDisabledLabel = new CachedTransform <int, string>(x => x > 0 ? $"Chat available in {x} seconds..." : "Chat Disabled"); if (!isMenuChat) { var openTeamChatKey = new HotkeyReference(); if (logicArgs.TryGetValue("OpenTeamChatKey", out var hotkeyArg)) { openTeamChatKey = modData.Hotkeys[hotkeyArg.Value]; } var openGeneralChatKey = new HotkeyReference(); if (logicArgs.TryGetValue("OpenGeneralChatKey", out hotkeyArg)) { openGeneralChatKey = modData.Hotkeys[hotkeyArg.Value]; } var chatClose = chatChrome.Get <ButtonWidget>("CHAT_CLOSE"); chatClose.OnClick += CloseChat; chatPanel.OnKeyPress = e => { if (e.Event == KeyInputEvent.Up) { return(false); } if (!chatChrome.IsVisible() && (openTeamChatKey.IsActivatedBy(e) || openGeneralChatKey.IsActivatedBy(e))) { teamChat = !disableTeamChat && !openGeneralChatKey.IsActivatedBy(e); OpenChat(); return(true); } return(false); }; } chatScrollPanel = chatChrome.Get <ScrollPanelWidget>("CHAT_SCROLLPANEL"); chatScrollPanel.RemoveChildren(); chatScrollPanel.ScrollToBottom(); foreach (var notification in orderManager.NotificationsCache) { if (IsNotificationEligible(notification)) { AddNotification(notification, true); } } orderManager.AddTextNotification += AddNotificationWrapper; chatText.IsDisabled = () => !chatEnabled || (world.IsReplay && !Game.Settings.Debug.EnableDebugCommandsInReplays); if (!isMenuChat) { CloseChat(); var keyListener = chatChrome.Get <LogicKeyListenerWidget>("KEY_LISTENER"); keyListener.AddHandler(e => { if (e.Event == KeyInputEvent.Up || !chatText.IsDisabled()) { return(false); } if ((e.Key == Keycode.RETURN || e.Key == Keycode.KP_ENTER || e.Key == Keycode.ESCAPE) && e.Modifiers == Modifiers.None) { CloseChat(); return(true); } return(false); }); } if (logicArgs.TryGetValue("ChatLineSound", out var yaml)) { chatLineSound = yaml.Value; } }