ShowColorDropDown() public static method

public static ShowColorDropDown ( DropDownButtonWidget color, ColorPreviewManagerWidget preview, World world ) : void
color DropDownButtonWidget
preview ColorPreviewManagerWidget
world World
return void
コード例 #1
0
        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);
        }
    }
コード例 #2
0
        Func <bool> InitPanel(Widget panel)
        {
            var ds          = Game.Settings.Graphics;
            var gs          = Game.Settings.Game;
            var scrollPanel = panel.Get <ScrollPanelWidget>("SETTINGS_SCROLLPANEL");

            SettingsUtils.BindCheckboxPref(panel, "CURSORDOUBLE_CHECKBOX", ds, "CursorDouble");
            SettingsUtils.BindCheckboxPref(panel, "VSYNC_CHECKBOX", ds, "VSync");
            SettingsUtils.BindCheckboxPref(panel, "FRAME_LIMIT_CHECKBOX", ds, "CapFramerate");
            SettingsUtils.BindIntSliderPref(panel, "FRAME_LIMIT_SLIDER", ds, "MaxFramerate");
            SettingsUtils.BindCheckboxPref(panel, "PLAYER_STANCE_COLORS_CHECKBOX", gs, "UsePlayerStanceColors");
            if (panel.GetOrNull <CheckboxWidget>("PAUSE_SHELLMAP_CHECKBOX") != null)
            {
                SettingsUtils.BindCheckboxPref(panel, "PAUSE_SHELLMAP_CHECKBOX", gs, "PauseShellmap");
            }

            var windowModeDropdown = panel.Get <DropDownButtonWidget>("MODE_DROPDOWN");

            windowModeDropdown.OnMouseDown = _ => ShowWindowModeDropdown(windowModeDropdown, ds, scrollPanel);
            windowModeDropdown.GetText     = () => ds.Mode == WindowMode.Windowed ?
                                             "Windowed" : ds.Mode == WindowMode.Fullscreen ? "Fullscreen (Legacy)" : "Fullscreen";

            var displaySelectionDropDown = panel.Get <DropDownButtonWidget>("DISPLAY_SELECTION_DROPDOWN");

            displaySelectionDropDown.OnMouseDown = _ => ShowDisplaySelectionDropdown(displaySelectionDropDown, ds);
            var displaySelectionLabel = new CachedTransform <int, string>(i => $"Display {i + 1}");

            displaySelectionDropDown.GetText    = () => displaySelectionLabel.Update(ds.VideoDisplay);
            displaySelectionDropDown.IsDisabled = () => Game.Renderer.DisplayCount < 2;

            var glProfileLabel    = new CachedTransform <GLProfile, string>(p => p.ToString());
            var glProfileDropdown = panel.Get <DropDownButtonWidget>("GL_PROFILE_DROPDOWN");
            var disableProfile    = Game.Renderer.SupportedGLProfiles.Length < 2 && ds.GLProfile == GLProfile.Automatic;

            glProfileDropdown.OnMouseDown = _ => ShowGLProfileDropdown(glProfileDropdown, ds);
            glProfileDropdown.GetText     = () => glProfileLabel.Update(ds.GLProfile);
            glProfileDropdown.IsDisabled  = () => disableProfile;

            var statusBarsDropDown = panel.Get <DropDownButtonWidget>("STATUS_BAR_DROPDOWN");

            statusBarsDropDown.OnMouseDown = _ => ShowStatusBarsDropdown(statusBarsDropDown, gs);
            statusBarsDropDown.GetText     = () => gs.StatusBars == StatusBarsType.Standard ?
                                             "Standard" : gs.StatusBars == StatusBarsType.DamageShow ? "Show On Damage" : "Always Show";

            var targetLinesDropDown = panel.Get <DropDownButtonWidget>("TARGET_LINES_DROPDOWN");

            targetLinesDropDown.OnMouseDown = _ => ShowTargetLinesDropdown(targetLinesDropDown, gs);
            targetLinesDropDown.GetText     = () => gs.TargetLines == TargetLinesType.Automatic ?
                                              "Automatic" : gs.TargetLines == TargetLinesType.Manual ? "Manual" : "Disabled";

            var battlefieldCameraDropDown = panel.Get <DropDownButtonWidget>("BATTLEFIELD_CAMERA_DROPDOWN");
            var battlefieldCameraLabel    = new CachedTransform <WorldViewport, string>(vs => ViewportSizeNames[vs]);

            battlefieldCameraDropDown.OnMouseDown = _ => ShowBattlefieldCameraDropdown(battlefieldCameraDropDown, viewportSizes, ds);
            battlefieldCameraDropDown.GetText     = () => battlefieldCameraLabel.Update(ds.ViewportDistance);

            BindTextNotificationPoolFilterSettings(panel, gs);

            // Update vsync immediately
            var vsyncCheckbox = panel.Get <CheckboxWidget>("VSYNC_CHECKBOX");
            var vsyncOnClick  = vsyncCheckbox.OnClick;

            vsyncCheckbox.OnClick = () =>
            {
                vsyncOnClick();
                Game.Renderer.SetVSyncEnabled(ds.VSync);
            };

            var uiScaleDropdown = panel.Get <DropDownButtonWidget>("UI_SCALE_DROPDOWN");
            var uiScaleLabel    = new CachedTransform <float, string>(s => $"{(int)(100 * s)}%");

            uiScaleDropdown.OnMouseDown = _ => ShowUIScaleDropdown(uiScaleDropdown, ds);
            uiScaleDropdown.GetText     = () => uiScaleLabel.Update(ds.UIScale);

            var minResolution  = viewportSizes.MinEffectiveResolution;
            var resolution     = Game.Renderer.Resolution;
            var disableUIScale = worldRenderer.World.Type != WorldType.Shellmap ||
                                 resolution.Width * ds.UIScale < 1.25f * minResolution.Width ||
                                 resolution.Height * ds.UIScale < 1.25f * minResolution.Height;

            uiScaleDropdown.IsDisabled = () => disableUIScale;

            panel.Get("DISPLAY_SELECTION_CONTAINER").IsVisible = () => ds.Mode != WindowMode.Windowed;
            panel.Get("WINDOW_RESOLUTION_CONTAINER").IsVisible = () => ds.Mode == WindowMode.Windowed;
            var windowWidth   = panel.Get <TextFieldWidget>("WINDOW_WIDTH");
            var origWidthText = windowWidth.Text = ds.WindowedSize.X.ToString();

            var windowHeight   = panel.Get <TextFieldWidget>("WINDOW_HEIGHT");
            var origHeightText = windowHeight.Text = ds.WindowedSize.Y.ToString();

            windowHeight.Text = ds.WindowedSize.Y.ToString();

            var restartDesc = panel.Get("RESTART_REQUIRED_DESC");

            restartDesc.IsVisible = () => ds.Mode != OriginalGraphicsMode || ds.VideoDisplay != OriginalVideoDisplay || ds.GLProfile != OriginalGLProfile ||
                                    (ds.Mode == WindowMode.Windowed && (origWidthText != windowWidth.Text || origHeightText != windowHeight.Text));

            var frameLimitCheckbox  = panel.Get <CheckboxWidget>("FRAME_LIMIT_CHECKBOX");
            var frameLimitOrigLabel = frameLimitCheckbox.Text;
            var frameLimitLabel     = new CachedTransform <int, string>(fps => frameLimitOrigLabel + $" ({fps} FPS)");

            frameLimitCheckbox.GetText = () => frameLimitLabel.Update(ds.MaxFramerate);

            panel.Get <SliderWidget>("FRAME_LIMIT_SLIDER").IsDisabled = () => !frameLimitCheckbox.IsChecked();

            // Player profile
            var ps = Game.Settings.Player;

            var escPressed    = false;
            var nameTextfield = panel.Get <TextFieldWidget>("PLAYERNAME");

            nameTextfield.IsDisabled  = () => worldRenderer.World.Type != WorldType.Shellmap;
            nameTextfield.Text        = Settings.SanitizedPlayerName(ps.Name);
            nameTextfield.OnLoseFocus = () =>
            {
                if (escPressed)
                {
                    escPressed = false;
                    return;
                }

                nameTextfield.Text = nameTextfield.Text.Trim();
                if (nameTextfield.Text.Length == 0)
                {
                    nameTextfield.Text = Settings.SanitizedPlayerName(ps.Name);
                }
                else
                {
                    nameTextfield.Text = Settings.SanitizedPlayerName(nameTextfield.Text);
                    ps.Name            = nameTextfield.Text;
                }
            };

            nameTextfield.OnEnterKey = _ => { nameTextfield.YieldKeyboardFocus(); return(true); };
            nameTextfield.OnEscKey   = _ =>
            {
                nameTextfield.Text = Settings.SanitizedPlayerName(ps.Name);
                escPressed         = true;
                nameTextfield.YieldKeyboardFocus();
                return(true);
            };

            var colorManager = modData.DefaultRules.Actors[SystemActors.World].TraitInfo <ColorPickerManagerInfo>();

            colorManager.Color = ps.Color;

            var colorDropdown = panel.Get <DropDownButtonWidget>("PLAYERCOLOR");

            colorDropdown.IsDisabled  = () => worldRenderer.World.Type != WorldType.Shellmap;
            colorDropdown.OnMouseDown = _ => ColorPickerLogic.ShowColorDropDown(colorDropdown, colorManager, worldRenderer, () =>
            {
                Game.Settings.Player.Color = colorManager.Color;
                Game.Settings.Save();
            });
            colorDropdown.Get <ColorBlockWidget>("COLORBLOCK").GetColor = () => ps.Color;

            SettingsUtils.AdjustSettingsScrollPanelLayout(scrollPanel);

            return(() =>
            {
                Exts.TryParseIntegerInvariant(windowWidth.Text, out var x);
                Exts.TryParseIntegerInvariant(windowHeight.Text, out var y);
                ds.WindowedSize = new int2(x, y);
                nameTextfield.YieldKeyboardFocus();

                return ds.Mode != OriginalGraphicsMode ||
                ds.VideoDisplay != OriginalVideoDisplay ||
                ds.WindowedSize != OriginalGraphicsWindowedSize ||
                ds.FullscreenSize != OriginalGraphicsFullscreenSize ||
                ds.GLProfile != OriginalGLProfile;
            });
        }
コード例 #3
0
ファイル: SettingsLogic.cs プロジェクト: wenzeslaus/OpenRA
        Action InitDisplayPanel(Widget panel)
        {
            var ds = Game.Settings.Graphics;
            var gs = Game.Settings.Game;

            BindCheckboxPref(panel, "HARDWARECURSORS_CHECKBOX", ds, "HardwareCursors");
            BindCheckboxPref(panel, "PIXELDOUBLE_CHECKBOX", ds, "PixelDouble");
            BindCheckboxPref(panel, "CURSORDOUBLE_CHECKBOX", ds, "CursorDouble");
            BindCheckboxPref(panel, "FRAME_LIMIT_CHECKBOX", ds, "CapFramerate");
            BindCheckboxPref(panel, "SHOW_SHELLMAP", gs, "ShowShellmap");
            BindCheckboxPref(panel, "ALWAYS_SHOW_STATUS_BARS_CHECKBOX", gs, "AlwaysShowStatusBars");
            BindCheckboxPref(panel, "TEAM_HEALTH_COLORS_CHECKBOX", gs, "TeamHealthColors");

            var languageDropDownButton = panel.Get <DropDownButtonWidget>("LANGUAGE_DROPDOWNBUTTON");

            languageDropDownButton.OnMouseDown = _ => ShowLanguageDropdown(languageDropDownButton);
            languageDropDownButton.GetText     = () => FieldLoader.Translate(ds.Language);

            var windowModeDropdown = panel.Get <DropDownButtonWidget>("MODE_DROPDOWN");

            windowModeDropdown.OnMouseDown = _ => ShowWindowModeDropdown(windowModeDropdown, ds);
            windowModeDropdown.GetText     = () => ds.Mode == WindowMode.Windowed ?
                                             "Windowed" : ds.Mode == WindowMode.Fullscreen ? "Fullscreen" : "Pseudo-Fullscreen";

            // Update zoom immediately
            var pixelDoubleCheckbox = panel.Get <CheckboxWidget>("PIXELDOUBLE_CHECKBOX");
            var pixelDoubleOnClick  = pixelDoubleCheckbox.OnClick;

            pixelDoubleCheckbox.OnClick = () =>
            {
                pixelDoubleOnClick();
                worldRenderer.Viewport.Zoom = ds.PixelDouble ? 2 : 1;
            };

            // Cursor doubling is only supported with software cursors and when pixel doubling is enabled
            var cursorDoubleCheckbox = panel.Get <CheckboxWidget>("CURSORDOUBLE_CHECKBOX");

            cursorDoubleCheckbox.IsDisabled = () => !ds.PixelDouble || Game.Cursor is HardwareCursor;

            var cursorDoubleIsChecked = cursorDoubleCheckbox.IsChecked;

            cursorDoubleCheckbox.IsChecked = () => !cursorDoubleCheckbox.IsDisabled() && cursorDoubleIsChecked();

            panel.Get("WINDOW_RESOLUTION").IsVisible = () => ds.Mode == WindowMode.Windowed;
            var windowWidth = panel.Get <TextFieldWidget>("WINDOW_WIDTH");

            windowWidth.Text = ds.WindowedSize.X.ToString();

            var windowHeight = panel.Get <TextFieldWidget>("WINDOW_HEIGHT");

            windowHeight.Text = ds.WindowedSize.Y.ToString();

            var frameLimitTextfield = panel.Get <TextFieldWidget>("FRAME_LIMIT_TEXTFIELD");

            frameLimitTextfield.Text        = ds.MaxFramerate.ToString();
            frameLimitTextfield.OnLoseFocus = () =>
            {
                int fps;
                Exts.TryParseIntegerInvariant(frameLimitTextfield.Text, out fps);
                ds.MaxFramerate          = fps.Clamp(1, 1000);
                frameLimitTextfield.Text = ds.MaxFramerate.ToString();
            };
            frameLimitTextfield.OnEnterKey = () => { frameLimitTextfield.YieldKeyboardFocus(); return(true); };
            frameLimitTextfield.IsDisabled = () => !ds.CapFramerate;

            // Player profile
            var ps = Game.Settings.Player;

            var nameTextfield = panel.Get <TextFieldWidget>("PLAYERNAME");

            nameTextfield.Text        = ps.Name;
            nameTextfield.OnEnterKey  = () => { nameTextfield.YieldKeyboardFocus(); return(true); };
            nameTextfield.OnLoseFocus = () => { ps.Name = nameTextfield.Text; };

            var colorPreview = panel.Get <ColorPreviewManagerWidget>("COLOR_MANAGER");

            colorPreview.Color = ps.Color;

            var colorDropdown = panel.Get <DropDownButtonWidget>("PLAYERCOLOR");

            colorDropdown.OnMouseDown = _ => ColorPickerLogic.ShowColorDropDown(colorDropdown, colorPreview, worldRenderer.World);
            colorDropdown.Get <ColorBlockWidget>("COLORBLOCK").GetColor = () => ps.Color.RGB;

            return(() =>
            {
                int x, y;
                Exts.TryParseIntegerInvariant(windowWidth.Text, out x);
                Exts.TryParseIntegerInvariant(windowHeight.Text, out y);
                ds.WindowedSize = new int2(x, y);
                frameLimitTextfield.YieldKeyboardFocus();
                nameTextfield.YieldKeyboardFocus();
            });
        }
コード例 #4
0
        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);
        }
    }
コード例 #5
0
        Action InitDisplayPanel(Widget panel)
        {
            var ds = Game.Settings.Graphics;
            var gs = Game.Settings.Game;

            BindCheckboxPref(panel, "HARDWARECURSORS_CHECKBOX", ds, "HardwareCursors");
            BindCheckboxPref(panel, "PIXELDOUBLE_CHECKBOX", ds, "PixelDouble");
            BindCheckboxPref(panel, "CURSORDOUBLE_CHECKBOX", ds, "CursorDouble");
            BindCheckboxPref(panel, "FRAME_LIMIT_CHECKBOX", ds, "CapFramerate");
            BindCheckboxPref(panel, "DISPLAY_TARGET_LINES_CHECKBOX", gs, "DrawTargetLine");
            BindCheckboxPref(panel, "PLAYER_STANCE_COLORS_CHECKBOX", gs, "UsePlayerStanceColors");

            var languageDropDownButton = panel.Get <DropDownButtonWidget>("LANGUAGE_DROPDOWNBUTTON");

            languageDropDownButton.OnMouseDown = _ => ShowLanguageDropdown(languageDropDownButton, modData.Languages);
            languageDropDownButton.GetText     = () => FieldLoader.Translate(ds.Language);

            var windowModeDropdown = panel.Get <DropDownButtonWidget>("MODE_DROPDOWN");

            windowModeDropdown.OnMouseDown = _ => ShowWindowModeDropdown(windowModeDropdown, ds);
            windowModeDropdown.GetText     = () => ds.Mode == WindowMode.Windowed ?
                                             "Windowed" : ds.Mode == WindowMode.Fullscreen ? "Fullscreen (Legacy)" : "Fullscreen";

            var statusBarsDropDown = panel.Get <DropDownButtonWidget>("STATUS_BAR_DROPDOWN");

            statusBarsDropDown.OnMouseDown = _ => ShowStatusBarsDropdown(statusBarsDropDown, gs);
            statusBarsDropDown.GetText     = () => gs.StatusBars.ToString() == "Standard" ?
                                             "Standard" : gs.StatusBars.ToString() == "DamageShow" ? "Show On Damage" : "Always Show";

            // Update zoom immediately
            var pixelDoubleCheckbox = panel.Get <CheckboxWidget>("PIXELDOUBLE_CHECKBOX");
            var pixelDoubleOnClick  = pixelDoubleCheckbox.OnClick;

            pixelDoubleCheckbox.OnClick = () =>
            {
                pixelDoubleOnClick();
                worldRenderer.Viewport.Zoom = ds.PixelDouble ? 2 : 1;
            };

            // Cursor doubling is only supported with software cursors and when pixel doubling is enabled
            var cursorDoubleCheckbox = panel.Get <CheckboxWidget>("CURSORDOUBLE_CHECKBOX");

            cursorDoubleCheckbox.IsDisabled = () => !ds.PixelDouble || Game.Cursor is HardwareCursor;

            var cursorDoubleIsChecked = cursorDoubleCheckbox.IsChecked;

            cursorDoubleCheckbox.IsChecked = () => !cursorDoubleCheckbox.IsDisabled() && cursorDoubleIsChecked();

            panel.Get("WINDOW_RESOLUTION").IsVisible = () => ds.Mode == WindowMode.Windowed;
            var windowWidth = panel.Get <TextFieldWidget>("WINDOW_WIDTH");

            windowWidth.Text = ds.WindowedSize.X.ToString();

            var windowHeight = panel.Get <TextFieldWidget>("WINDOW_HEIGHT");

            windowHeight.Text = ds.WindowedSize.Y.ToString();

            var frameLimitTextfield = panel.Get <TextFieldWidget>("FRAME_LIMIT_TEXTFIELD");

            frameLimitTextfield.Text = ds.MaxFramerate.ToString();
            var escPressed = false;

            frameLimitTextfield.OnLoseFocus = () =>
            {
                if (escPressed)
                {
                    escPressed = false;
                    return;
                }

                int fps;
                Exts.TryParseIntegerInvariant(frameLimitTextfield.Text, out fps);
                ds.MaxFramerate          = fps.Clamp(1, 1000);
                frameLimitTextfield.Text = ds.MaxFramerate.ToString();
            };

            frameLimitTextfield.OnEnterKey = () => { frameLimitTextfield.YieldKeyboardFocus(); return(true); };
            frameLimitTextfield.OnEscKey   = () =>
            {
                frameLimitTextfield.Text = ds.MaxFramerate.ToString();
                escPressed = true;
                frameLimitTextfield.YieldKeyboardFocus();
                return(true);
            };

            frameLimitTextfield.IsDisabled = () => !ds.CapFramerate;

            // Player profile
            var ps = Game.Settings.Player;

            var nameTextfield = panel.Get <TextFieldWidget>("PLAYERNAME");

            nameTextfield.IsDisabled  = () => worldRenderer.World.Type != WorldType.Shellmap;
            nameTextfield.Text        = Settings.SanitizedPlayerName(ps.Name);
            nameTextfield.OnLoseFocus = () =>
            {
                if (escPressed)
                {
                    escPressed = false;
                    return;
                }

                nameTextfield.Text = nameTextfield.Text.Trim();
                if (nameTextfield.Text.Length == 0)
                {
                    nameTextfield.Text = Settings.SanitizedPlayerName(ps.Name);
                }
                else
                {
                    nameTextfield.Text = Settings.SanitizedPlayerName(nameTextfield.Text);
                    ps.Name            = nameTextfield.Text;
                }
            };

            nameTextfield.OnEnterKey = () => { nameTextfield.YieldKeyboardFocus(); return(true); };
            nameTextfield.OnEscKey   = () =>
            {
                nameTextfield.Text = Settings.SanitizedPlayerName(ps.Name);
                escPressed         = true;
                nameTextfield.YieldKeyboardFocus();
                return(true);
            };

            var colorPreview = panel.Get <ColorPreviewManagerWidget>("COLOR_MANAGER");

            colorPreview.Color = ps.Color;

            var colorDropdown = panel.Get <DropDownButtonWidget>("PLAYERCOLOR");

            colorDropdown.IsDisabled  = () => worldRenderer.World.Type != WorldType.Shellmap;
            colorDropdown.OnMouseDown = _ => ColorPickerLogic.ShowColorDropDown(colorDropdown, colorPreview, worldRenderer.World);
            colorDropdown.Get <ColorBlockWidget>("COLORBLOCK").GetColor = () => ps.Color.RGB;

            return(() =>
            {
                int x, y;
                Exts.TryParseIntegerInvariant(windowWidth.Text, out x);
                Exts.TryParseIntegerInvariant(windowHeight.Text, out y);
                ds.WindowedSize = new int2(x, y);
                frameLimitTextfield.YieldKeyboardFocus();
                nameTextfield.YieldKeyboardFocus();
            });
        }
コード例 #6
0
        public IntroductionPromptLogic(Widget widget, ModData modData, WorldRenderer worldRenderer, Action onComplete)
        {
            var ps = Game.Settings.Player;
            var ds = Game.Settings.Graphics;
            var gs = Game.Settings.Game;

            var escPressed    = false;
            var nameTextfield = widget.Get <TextFieldWidget>("PLAYERNAME");

            nameTextfield.IsDisabled  = () => worldRenderer.World.Type != WorldType.Shellmap;
            nameTextfield.Text        = Settings.SanitizedPlayerName(ps.Name);
            nameTextfield.OnLoseFocus = () =>
            {
                if (escPressed)
                {
                    escPressed = false;
                    return;
                }

                nameTextfield.Text = nameTextfield.Text.Trim();
                if (nameTextfield.Text.Length == 0)
                {
                    nameTextfield.Text = Settings.SanitizedPlayerName(ps.Name);
                }
                else
                {
                    nameTextfield.Text = Settings.SanitizedPlayerName(nameTextfield.Text);
                    ps.Name            = nameTextfield.Text;
                }
            };

            nameTextfield.OnEnterKey = () => { nameTextfield.YieldKeyboardFocus(); return(true); };
            nameTextfield.OnEscKey   = () =>
            {
                nameTextfield.Text = Settings.SanitizedPlayerName(ps.Name);
                escPressed         = true;
                nameTextfield.YieldKeyboardFocus();
                return(true);
            };

            var colorManager = modData.DefaultRules.Actors[SystemActors.World].TraitInfo <ColorPickerManagerInfo>();

            colorManager.Color = ps.Color;

            var mouseControlDescClassic = widget.Get("MOUSE_CONTROL_DESC_CLASSIC");

            mouseControlDescClassic.IsVisible = () => gs.UseClassicMouseStyle;

            var mouseControlDescModern = widget.Get("MOUSE_CONTROL_DESC_MODERN");

            mouseControlDescModern.IsVisible = () => !gs.UseClassicMouseStyle;

            var mouseControlDropdown = widget.Get <DropDownButtonWidget>("MOUSE_CONTROL_DROPDOWN");

            mouseControlDropdown.OnMouseDown = _ => InputSettingsLogic.ShowMouseControlDropdown(mouseControlDropdown, gs);
            mouseControlDropdown.GetText     = () => gs.UseClassicMouseStyle ? "Classic" : "Modern";

            foreach (var container in new[] { mouseControlDescClassic, mouseControlDescModern })
            {
                var classicScrollRight = container.Get("DESC_SCROLL_RIGHT");
                classicScrollRight.IsVisible = () => gs.UseClassicMouseStyle ^ gs.UseAlternateScrollButton;

                var classicScrollMiddle = container.Get("DESC_SCROLL_MIDDLE");
                classicScrollMiddle.IsVisible = () => !gs.UseClassicMouseStyle ^ gs.UseAlternateScrollButton;

                var zoomDesc = container.Get("DESC_ZOOM");
                zoomDesc.IsVisible = () => gs.ZoomModifier == Modifiers.None;

                var zoomDescModifier = container.Get <LabelWidget>("DESC_ZOOM_MODIFIER");
                zoomDescModifier.IsVisible = () => gs.ZoomModifier != Modifiers.None;

                var zoomDescModifierTemplate = zoomDescModifier.Text;
                var zoomDescModifierLabel    = new CachedTransform <Modifiers, string>(
                    mod => zoomDescModifierTemplate.Replace("MODIFIER", mod.ToString()));
                zoomDescModifier.GetText = () => zoomDescModifierLabel.Update(gs.ZoomModifier);

                var edgescrollDesc = container.Get <LabelWidget>("DESC_EDGESCROLL");
                edgescrollDesc.IsVisible = () => gs.ViewportEdgeScroll;
            }

            SettingsUtils.BindCheckboxPref(widget, "EDGESCROLL_CHECKBOX", gs, "ViewportEdgeScroll");

            var colorDropdown = widget.Get <DropDownButtonWidget>("PLAYERCOLOR");

            colorDropdown.IsDisabled  = () => worldRenderer.World.Type != WorldType.Shellmap;
            colorDropdown.OnMouseDown = _ => ColorPickerLogic.ShowColorDropDown(colorDropdown, colorManager, worldRenderer);
            colorDropdown.Get <ColorBlockWidget>("COLORBLOCK").GetColor = () => ps.Color;

            var viewportSizes             = modData.Manifest.Get <WorldViewportSizes>();
            var battlefieldCameraDropDown = widget.Get <DropDownButtonWidget>("BATTLEFIELD_CAMERA_DROPDOWN");
            var battlefieldCameraLabel    = new CachedTransform <WorldViewport, string>(vs => DisplaySettingsLogic.ViewportSizeNames[vs]);

            battlefieldCameraDropDown.OnMouseDown = _ => DisplaySettingsLogic.ShowBattlefieldCameraDropdown(battlefieldCameraDropDown, viewportSizes, ds);
            battlefieldCameraDropDown.GetText     = () => battlefieldCameraLabel.Update(ds.ViewportDistance);

            var uiScaleDropdown = widget.Get <DropDownButtonWidget>("UI_SCALE_DROPDOWN");
            var uiScaleLabel    = new CachedTransform <float, string>(s => $"{(int)(100 * s)}%");

            uiScaleDropdown.OnMouseDown = _ => DisplaySettingsLogic.ShowUIScaleDropdown(uiScaleDropdown, ds);
            uiScaleDropdown.GetText     = () => uiScaleLabel.Update(ds.UIScale);

            var minResolution  = viewportSizes.MinEffectiveResolution;
            var resolution     = Game.Renderer.Resolution;
            var disableUIScale = worldRenderer.World.Type != WorldType.Shellmap ||
                                 resolution.Width * ds.UIScale < 1.25f * minResolution.Width ||
                                 resolution.Height * ds.UIScale < 1.25f * minResolution.Height;

            uiScaleDropdown.IsDisabled = () => disableUIScale;

            SettingsUtils.BindCheckboxPref(widget, "CURSORDOUBLE_CHECKBOX", ds, "CursorDouble");

            widget.Get <ButtonWidget>("CONTINUE_BUTTON").OnClick = () =>
            {
                Game.Settings.Game.IntroductionPromptVersion = IntroductionVersion;
                Game.Settings.Save();
                Ui.CloseWindow();
                onComplete();
            };
        }
コード例 #7
0
        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;
            }
        }