Esempio n. 1
0
        string DeleteMap(string map)
        {
            var path = Game.ModData.MapCache[map].Map.Path;

            try
            {
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
                else if (Directory.Exists(path))
                {
                    Directory.Delete(path, true);
                }

                Game.ModData.MapCache[map].Invalidate();

                if (selectedUid == map)
                {
                    selectedUid = WidgetUtils.ChooseInitialMap(tabMaps[currentTab].Select(mp => mp.Uid).FirstOrDefault());
                }
            }
            catch (Exception ex)
            {
                Game.Debug("Failed to delete map '{0}'. See the debug.log file for details.", path);
                Log.Write("debug", ex.ToString());
            }

            return(selectedUid);
        }
Esempio n. 2
0
        public static void RunDedicatedServer()
        {
            while (true)
            {
                Settings.Server.Map = WidgetUtils.ChooseInitialMap(Settings.Server.Map);
                Settings.Save();
                CreateServer(new ServerSettings(Settings.Server));

                while (true)
                {
                    Thread.Sleep(100);

                    if (server.State == Server.ServerState.GameStarted && server.Conns.Count < 1)
                    {
                        Console.WriteLine("No one is playing, shutting down...");
                        server.Shutdown();
                        break;
                    }
                }

                if (Settings.Server.DedicatedLoop)
                {
                    Console.WriteLine("Starting a new server instance...");
                    ModData.MapCache.LoadMaps();
                    continue;
                }

                break;
            }
        }
Esempio n. 3
0
        public ServerCreationLogic(Widget widget, Action onExit, Action openLobby)
        {
            panel       = widget;
            onCreate    = openLobby;
            this.onExit = onExit;

            var settings = Game.Settings;

            preview = Game.ModData.MapCache[WidgetUtils.ChooseInitialMap(Game.Settings.Server.Map)];

            panel.Get <ButtonWidget>("BACK_BUTTON").OnClick   = () => { Ui.CloseWindow(); onExit(); };
            panel.Get <ButtonWidget>("CREATE_BUTTON").OnClick = CreateAndJoin;

            var mapButton = panel.GetOrNull <ButtonWidget>("MAP_BUTTON");

            if (mapButton != null)
            {
                panel.Get <ButtonWidget>("MAP_BUTTON").OnClick = () =>
                {
                    Ui.OpenWindow("MAPCHOOSER_PANEL", new WidgetArgs()
                    {
                        { "initialMap", preview.Uid },
                        { "onExit", () => { } },
                        { "onSelect", (Action <string>)(uid => preview = Game.ModData.MapCache[uid]) },
                        { "filter", MapVisibility.Lobby },
                    });
                };

                panel.Get <MapPreviewWidget>("MAP_PREVIEW").Preview = () => preview;
                panel.Get <LabelWidget>("MAP_NAME").GetText         = () => preview.Title;
            }

            panel.Get <TextFieldWidget>("SERVER_NAME").Text = settings.Server.Name ?? "";
            panel.Get <TextFieldWidget>("LISTEN_PORT").Text = settings.Server.ListenPort.ToString();
            advertiseOnline = Game.Settings.Server.AdvertiseOnline;

            var externalPort = panel.Get <TextFieldWidget>("EXTERNAL_PORT");

            externalPort.Text       = settings.Server.ExternalPort.ToString();
            externalPort.IsDisabled = () => !advertiseOnline;

            var advertiseCheckbox = panel.Get <CheckboxWidget>("ADVERTISE_CHECKBOX");

            advertiseCheckbox.IsChecked = () => advertiseOnline;
            advertiseCheckbox.OnClick   = () => advertiseOnline ^= true;

            allowPortForward = Game.Settings.Server.AllowPortForward;
            var checkboxUPnP = panel.Get <CheckboxWidget>("UPNP_CHECKBOX");

            checkboxUPnP.IsChecked  = () => allowPortForward;
            checkboxUPnP.OnClick    = () => allowPortForward ^= true;
            checkboxUPnP.IsDisabled = () => !Game.Settings.Server.NatDeviceAvailable;

            var passwordField = panel.GetOrNull <PasswordFieldWidget>("PASSWORD");

            if (passwordField != null)
            {
                passwordField.Text = Game.Settings.Server.Password;
            }
        }
Esempio n. 4
0
        internal MapChooserLogic(Widget widget, string initialMap, Action onExit, Action <Map> onSelect)
        {
            map = Game.modData.AvailableMaps[WidgetUtils.ChooseInitialMap(initialMap)];

            widget.Get <ButtonWidget>("BUTTON_OK").OnClick     = () => { Ui.CloseWindow(); onSelect(map); };
            widget.Get <ButtonWidget>("BUTTON_CANCEL").OnClick = () => { Ui.CloseWindow(); onExit(); };

            scrollpanel = widget.Get <ScrollPanelWidget>("MAP_LIST");
            scrollpanel.ScrollVelocity = 40f;
            scrollpanel.Layout         = new GridLayout(scrollpanel);

            itemTemplate = scrollpanel.Get <ScrollItemWidget>("MAP_TEMPLATE");

            var gameModeDropdown = widget.GetOrNull <DropDownButtonWidget>("GAMEMODE_FILTER");

            if (gameModeDropdown != null)
            {
                var selectableMaps = Game.modData.AvailableMaps.Where(m => m.Value.Selectable).ToList();
                var gameModes      = selectableMaps
                                     .GroupBy(m => m.Value.Type)
                                     .Select(g => Pair.New(g.Key, g.Count())).ToList();

                // 'all game types' extra item
                gameModes.Insert(0, Pair.New(null as string, selectableMaps.Count()));

                Func <Pair <string, int>, string> showItem =
                    x => "{0} ({1})".F(x.First ?? "All Game Types", x.Second);

                Func <Pair <string, int>, ScrollItemWidget, ScrollItemWidget> setupItem = (ii, template) =>
                {
                    var item = ScrollItemWidget.Setup(template,
                                                      () => gameMode == ii.First,
                                                      () => { gameMode = ii.First; EnumerateMaps(onSelect); });
                    item.Get <LabelWidget>("LABEL").GetText = () => showItem(ii);
                    return(item);
                };

                gameModeDropdown.OnClick = () =>
                                           gameModeDropdown.ShowDropDown("LABEL_DROPDOWN_TEMPLATE", 210, gameModes, setupItem);

                gameModeDropdown.GetText = () => showItem(gameModes.First(m => m.First == gameMode));
            }

            var randomMapButton = widget.GetOrNull <ButtonWidget>("RANDOMMAP_BUTTON");

            if (randomMapButton != null)
            {
                randomMapButton.OnClick = () =>
                {
                    var kv = visibleMaps.Random(Game.CosmeticRandom);
                    map = kv.Value;
                    scrollpanel.ScrollToItem(kv.Key);
                };
                randomMapButton.IsDisabled = () => visibleMaps == null || visibleMaps.Count == 0;
            }

            EnumerateMaps(onSelect);
        }
Esempio n. 5
0
        void StartSkirmishGame()
        {
            var map = WidgetUtils.ChooseInitialMap(Game.Settings.Server.Map);

            ConnectionLogic.Connect(IPAddress.Loopback.ToString(),
                                    Game.CreateLocalServer(map),
                                    () => OpenLobbyPanel(MenuType.Main, true),
                                    () => { Game.CloseServer(); Menu = MenuType.Main; });
        }
Esempio n. 6
0
        public ServerCreationLogic(Widget widget, Action onExit, Action openLobby)
        {
            panel       = widget;
            onCreate    = openLobby;
            this.onExit = onExit;

            var settings = Game.Settings;

            panel.Get <ButtonWidget>("BACK_BUTTON").OnClick   = () => { Ui.CloseWindow(); onExit(); };
            panel.Get <ButtonWidget>("CREATE_BUTTON").OnClick = CreateAndJoin;

            map = Game.modData.AvailableMaps[WidgetUtils.ChooseInitialMap(Game.Settings.Server.Map)];

            var mapButton = panel.GetOrNull <ButtonWidget>("MAP_BUTTON");

            if (mapButton != null)
            {
                panel.Get <ButtonWidget>("MAP_BUTTON").OnClick = () =>
                {
                    Ui.OpenWindow("MAPCHOOSER_PANEL", new WidgetArgs()
                    {
                        { "initialMap", map.Uid },
                        { "onExit", () => {} },
                        { "onSelect", (Action <Map>)(m => map = m) }
                    });
                };

                panel.Get <MapPreviewWidget>("MAP_PREVIEW").Map = () => map;
                panel.Get <LabelWidget>("MAP_NAME").GetText     = () => map.Title;
            }

            panel.Get <TextFieldWidget>("SERVER_NAME").Text = settings.Server.Name ?? "";
            panel.Get <TextFieldWidget>("LISTEN_PORT").Text = settings.Server.ListenPort.ToString();
            advertiseOnline = Game.Settings.Server.AdvertiseOnline;

            var externalPort = panel.Get <TextFieldWidget>("EXTERNAL_PORT");

            externalPort.Text       = settings.Server.ExternalPort.ToString();
            externalPort.IsDisabled = () => !advertiseOnline;

            var advertiseCheckbox = panel.Get <CheckboxWidget>("ADVERTISE_CHECKBOX");

            advertiseCheckbox.IsChecked = () => advertiseOnline;
            advertiseCheckbox.OnClick   = () => advertiseOnline ^= true;

            allowPortForward = Game.Settings.Server.AllowPortForward;
            var UPnPCheckbox = panel.Get <CheckboxWidget>("UPNP_CHECKBOX");

            UPnPCheckbox.IsChecked  = () => allowPortForward;
            UPnPCheckbox.OnClick    = () => allowPortForward ^= true;
            UPnPCheckbox.IsDisabled = () => !Game.Settings.Server.NatDeviceAvailable;
        }
Esempio n. 7
0
 void DeleteAllMaps(string[] maps, Action <string> after)
 {
     ConfirmationDialogs.PromptConfirmAction(
         "Delete maps",
         "Delete all maps on this page?",
         () =>
     {
         maps.Do(m => DeleteMap(m));
         if (after != null)
         {
             after(WidgetUtils.ChooseInitialMap(null));
         }
     },
         null,
         "Delete");
 }
Esempio n. 8
0
        public static void InitializeMod(string mod, Arguments args)
        {
            // Clear static state if we have switched mods
            LobbyInfoChanged       = () => { };
            ConnectionStateChanged = om => { };
            BeforeGameStart        = () => { };
            OnRemoteDirectConnect  = (a, b) => { };
            delayedActions         = new ActionQueue();

            Ui.ResetAll();

            if (worldRenderer != null)
            {
                worldRenderer.Dispose();
            }
            worldRenderer = null;
            if (server != null)
            {
                server.Shutdown();
            }
            if (OrderManager != null)
            {
                OrderManager.Dispose();
            }

            if (ModData != null)
            {
                ModData.Dispose();
            }
            ModData = null;

            // Fall back to default if the mod doesn't exist
            if (!ModMetadata.AllMods.ContainsKey(mod))
            {
                mod = new GameSettings().Mod;
            }

            Console.WriteLine("Loading mod: {0}", mod);
            Settings.Game.Mod = mod;

            Sound.StopMusic();
            Sound.StopVideo();
            Sound.Initialize();

            ModData = new ModData(mod, !Settings.Server.Dedicated);
            ModData.InitializeLoaders();
            if (!Settings.Server.Dedicated)
            {
                Renderer.InitializeFonts(ModData.Manifest);
            }

            using (new PerfTimer("LoadMaps"))
                ModData.MapCache.LoadMaps();

            if (Settings.Graphics.HardwareCursors)
            {
                try
                {
                    Cursor = new HardwareCursor(ModData.CursorProvider);
                }
                catch (Exception e)
                {
                    Log.Write("debug", "Failed to initialize hardware cursors. Falling back to software cursors.");
                    Log.Write("debug", "Error was: " + e.Message);

                    Console.WriteLine("Failed to initialize hardware cursors. Falling back to software cursors.");
                    Console.WriteLine("Error was: " + e.Message);

                    Cursor = new SoftwareCursor(ModData.CursorProvider);
                    Settings.Graphics.HardwareCursors = false;
                }
            }
            else
            {
                Cursor = new SoftwareCursor(ModData.CursorProvider);
            }

            PerfHistory.Items["render"].HasNormalTick         = false;
            PerfHistory.Items["batches"].HasNormalTick        = false;
            PerfHistory.Items["render_widgets"].HasNormalTick = false;
            PerfHistory.Items["render_flip"].HasNormalTick    = false;

            JoinLocal();

            if (Settings.Server.Dedicated)
            {
                while (true)
                {
                    Settings.Server.Map = WidgetUtils.ChooseInitialMap(Settings.Server.Map);
                    Settings.Save();
                    CreateServer(new ServerSettings(Settings.Server));
                    while (true)
                    {
                        Thread.Sleep(100);

                        if (server.State == Server.ServerState.GameStarted && server.Conns.Count < 1)
                        {
                            Console.WriteLine("No one is playing, shutting down...");
                            server.Shutdown();
                            break;
                        }
                    }

                    if (Settings.Server.DedicatedLoop)
                    {
                        Console.WriteLine("Starting a new server instance...");
                        ModData.MapCache.LoadMaps();
                        continue;
                    }

                    break;
                }

                Environment.Exit(0);
            }
            else
            {
                ModData.LoadScreen.StartGame(args);
            }
        }
Esempio n. 9
0
        public static void InitializeWithMods(string[] mods)
        {
            // Clear static state if we have switched mods
            LobbyInfoChanged       = () => {};
            AddChatLine            = (a, b, c) => {};
            ConnectionStateChanged = om => {};
            BeforeGameStart        = () => {};
            Ui.ResetAll();

            worldRenderer = null;
            if (server != null)
            {
                server.Shutdown();
            }
            if (orderManager != null)
            {
                orderManager.Dispose();
            }

            // Discard any invalid mods, set RA as default
            var mm = mods.Where(m => Mod.AllMods.ContainsKey(m)).ToArray();

            if (mm.Length == 0)
            {
                mm = new[] { "ra" }
            }
            ;
            Console.WriteLine("Loading mods: {0}", mm.JoinWith(","));
            Settings.Game.Mods = mm;

            Sound.StopMusic();
            Sound.StopVideo();
            Sound.Initialize();

            modData = new ModData(mm);
            Renderer.InitializeFonts(modData.Manifest);
            modData.LoadInitialAssets(true);


            PerfHistory.items["render"].hasNormalTick         = false;
            PerfHistory.items["batches"].hasNormalTick        = false;
            PerfHistory.items["render_widgets"].hasNormalTick = false;
            PerfHistory.items["render_flip"].hasNormalTick    = false;

            JoinLocal();
            viewport = new Viewport(new int2(Renderer.Resolution), Rectangle.Empty, Renderer);

            if (Game.Settings.Server.Dedicated)
            {
                while (true)
                {
                    Game.Settings.Server.Map = WidgetUtils.ChooseInitialMap(Game.Settings.Server.Map);
                    Game.Settings.Save();
                    Game.CreateServer(new ServerSettings(Game.Settings.Server));
                    while (true)
                    {
                        System.Threading.Thread.Sleep(100);

                        if ((server.State == Server.ServerState.GameStarted) &&
                            (server.conns.Count <= 1))
                        {
                            Console.WriteLine("No one is playing, shutting down...");
                            server.Shutdown();
                            break;
                        }
                    }
                    if (Game.Settings.Server.DedicatedLoop)
                    {
                        Console.WriteLine("Starting a new server instance...");
                        continue;
                    }
                    else
                    {
                        break;
                    }
                }
                System.Environment.Exit(0);
            }
            else
            {
                modData.LoadScreen.StartGame();
                Settings.Save();
            }
        }
Esempio n. 10
0
        public static void InitializeMod(string mod, Arguments args)
        {
            // Clear static state if we have switched mods
            LobbyInfoChanged       = () => { };
            AddChatLine            = (a, b, c) => { };
            ConnectionStateChanged = om => { };
            BeforeGameStart        = () => { };
            Ui.ResetAll();

            worldRenderer = null;
            if (server != null)
            {
                server.Shutdown();
            }
            if (orderManager != null)
            {
                orderManager.Dispose();
            }

            // Fall back to default if the mod doesn't exist
            if (!ModMetadata.AllMods.ContainsKey(mod))
            {
                mod = new GameSettings().Mod;
            }

            Console.WriteLine("Loading mod: {0}", mod);
            Settings.Game.Mod = mod;

            Sound.StopMusic();
            Sound.StopVideo();
            Sound.Initialize();

            modData = new ModData(mod);
            Renderer.InitializeFonts(modData.Manifest);
            modData.InitializeLoaders();
            using (new PerfTimer("LoadMaps"))
                modData.MapCache.LoadMaps();

            PerfHistory.items["render"].hasNormalTick         = false;
            PerfHistory.items["batches"].hasNormalTick        = false;
            PerfHistory.items["render_widgets"].hasNormalTick = false;
            PerfHistory.items["render_flip"].hasNormalTick    = false;

            JoinLocal();

            if (Settings.Server.Dedicated)
            {
                while (true)
                {
                    Settings.Server.Map = WidgetUtils.ChooseInitialMap(Settings.Server.Map);
                    Settings.Save();
                    CreateServer(new ServerSettings(Settings.Server));
                    while (true)
                    {
                        System.Threading.Thread.Sleep(100);

                        if (server.State == Server.ServerState.GameStarted && server.Conns.Count < 1)
                        {
                            Console.WriteLine("No one is playing, shutting down...");
                            server.Shutdown();
                            break;
                        }
                    }

                    if (Settings.Server.DedicatedLoop)
                    {
                        Console.WriteLine("Starting a new server instance...");
                        modData.MapCache.LoadMaps();
                        continue;
                    }

                    break;
                }

                Environment.Exit(0);
            }
            else
            {
                var window = args != null?args.GetValue("Launch.Window", null) : null;

                if (!string.IsNullOrEmpty(window))
                {
                    var installData = modData.Manifest.ContentInstaller;
                    if (installData.InstallerBackgroundWidget != null)
                    {
                        Ui.LoadWidget(installData.InstallerBackgroundWidget, Ui.Root, new WidgetArgs());
                    }

                    Widgets.Ui.OpenWindow(window, new WidgetArgs());
                }
                else
                {
                    modData.LoadScreen.StartGame();
                    Settings.Save();
                    var replay = args != null?args.GetValue("Launch.Replay", null) : null;

                    if (!string.IsNullOrEmpty(replay))
                    {
                        Game.JoinReplay(replay);
                    }
                }
            }
        }
Esempio n. 11
0
        internal MapChooserLogic(Widget widget, string initialMap, MapClassification initialTab, Action onExit, Action <string> onSelect, MapVisibility filter)
        {
            this.widget   = widget;
            this.onSelect = onSelect;

            var approving = new Action(() => { Ui.CloseWindow(); onSelect(selectedUid); });
            var canceling = new Action(() => { Ui.CloseWindow(); onExit(); });

            var okButton = widget.Get <ButtonWidget>("BUTTON_OK");

            okButton.Disabled = this.onSelect == null;
            okButton.OnClick  = approving;
            widget.Get <ButtonWidget>("BUTTON_CANCEL").OnClick = canceling;

            gameModeDropdown = widget.GetOrNull <DropDownButtonWidget>("GAMEMODE_FILTER");

            var itemTemplate = widget.Get <ScrollItemWidget>("MAP_TEMPLATE");

            widget.RemoveChild(itemTemplate);

            var mapFilterInput = widget.GetOrNull <TextFieldWidget>("MAPFILTER_INPUT");

            if (mapFilterInput != null)
            {
                mapFilterInput.TakeKeyboardFocus();
                mapFilterInput.OnEscKey = () =>
                {
                    if (mapFilterInput.Text.Length == 0)
                    {
                        canceling();
                    }
                    else
                    {
                        mapFilter = mapFilterInput.Text = null;
                        EnumerateMaps(currentTab, itemTemplate);
                    }

                    return(true);
                };
                mapFilterInput.OnEnterKey   = () => { approving(); return(true); };
                mapFilterInput.OnTextEdited = () =>
                {
                    mapFilter = mapFilterInput.Text;
                    EnumerateMaps(currentTab, itemTemplate);
                };
            }

            var randomMapButton = widget.GetOrNull <ButtonWidget>("RANDOMMAP_BUTTON");

            if (randomMapButton != null)
            {
                randomMapButton.OnClick = () =>
                {
                    var uid = visibleMaps.Random(Game.CosmeticRandom);
                    selectedUid = uid;
                    scrollpanels[currentTab].ScrollToItem(uid, smooth: true);
                };
                randomMapButton.IsDisabled = () => visibleMaps == null || visibleMaps.Length == 0;
            }

            var deleteMapButton = widget.Get <ButtonWidget>("DELETE_MAP_BUTTON");

            deleteMapButton.IsDisabled = () => Game.ModData.MapCache[selectedUid].Class != MapClassification.User;
            deleteMapButton.IsVisible  = () => currentTab == MapClassification.User;
            deleteMapButton.OnClick    = () =>
            {
                DeleteOneMap(selectedUid, (string newUid) =>
                {
                    RefreshMaps(currentTab, filter);
                    EnumerateMaps(currentTab, itemTemplate);
                    if (!tabMaps[currentTab].Any())
                    {
                        SwitchTab(Game.ModData.MapCache[newUid].Class, itemTemplate);
                    }
                });
            };

            var deleteAllMapsButton = widget.Get <ButtonWidget>("DELETE_ALL_MAPS_BUTTON");

            deleteAllMapsButton.IsVisible = () => currentTab == MapClassification.User;
            deleteAllMapsButton.OnClick   = () =>
            {
                DeleteAllMaps(visibleMaps, (string newUid) =>
                {
                    RefreshMaps(currentTab, filter);
                    EnumerateMaps(currentTab, itemTemplate);
                    SwitchTab(Game.ModData.MapCache[newUid].Class, itemTemplate);
                });
            };

            SetupMapTab(MapClassification.User, filter, "USER_MAPS_TAB_BUTTON", "USER_MAPS_TAB", itemTemplate);
            SetupMapTab(MapClassification.System, filter, "SYSTEM_MAPS_TAB_BUTTON", "SYSTEM_MAPS_TAB", itemTemplate);

            if (initialMap == null && tabMaps.Keys.Contains(initialTab) && tabMaps[initialTab].Any())
            {
                selectedUid = WidgetUtils.ChooseInitialMap(tabMaps[initialTab].Select(mp => mp.Uid).First());
                currentTab  = initialTab;
            }
            else
            {
                selectedUid = WidgetUtils.ChooseInitialMap(initialMap);
                currentTab  = tabMaps.Keys.FirstOrDefault(k => tabMaps[k].Select(mp => mp.Uid).Contains(selectedUid));
            }

            SwitchTab(currentTab, itemTemplate);
        }
Esempio n. 12
0
        public static void InitializeWithMod(string mod)
        {
            // Clear static state if we have switched mods
            LobbyInfoChanged       = () => { };
            AddChatLine            = (a, b, c) => { };
            ConnectionStateChanged = om => { };
            BeforeGameStart        = () => { };
            Ui.ResetAll();

            worldRenderer = null;
            if (server != null)
            {
                server.Shutdown();
            }
            if (orderManager != null)
            {
                orderManager.Dispose();
            }

            // Fall back to RA if the mod doesn't exist
            if (!Mod.AllMods.ContainsKey(mod))
            {
                mod = "ra";
            }

            Console.WriteLine("Loading mod: {0}", mod);
            Settings.Game.Mod = mod;

            Sound.StopMusic();
            Sound.StopVideo();
            Sound.Initialize();

            modData = new ModData(mod);
            Renderer.InitializeFonts(modData.Manifest);
            modData.InitializeLoaders();

            PerfHistory.items["render"].hasNormalTick         = false;
            PerfHistory.items["batches"].hasNormalTick        = false;
            PerfHistory.items["render_widgets"].hasNormalTick = false;
            PerfHistory.items["render_flip"].hasNormalTick    = false;

            JoinLocal();

            if (Settings.Server.Dedicated)
            {
                while (true)
                {
                    Settings.Server.Map = WidgetUtils.ChooseInitialMap(Settings.Server.Map);
                    Settings.Save();
                    CreateServer(new ServerSettings(Settings.Server));
                    while (true)
                    {
                        System.Threading.Thread.Sleep(100);

                        if (server.State == Server.ServerState.GameStarted && server.Conns.Count <= 1)
                        {
                            Console.WriteLine("No one is playing, shutting down...");
                            server.Shutdown();
                            break;
                        }
                    }

                    if (Settings.Server.DedicatedLoop)
                    {
                        Console.WriteLine("Starting a new server instance...");
                        continue;
                    }

                    break;
                }

                Environment.Exit(0);
            }
            else
            {
                modData.LoadScreen.StartGame();
                Settings.Save();
            }
        }
Esempio n. 13
0
        public ServerCreationLogic(Widget widget, Action onExit, Action openLobby)
        {
            panel       = widget;
            onCreate    = openLobby;
            this.onExit = onExit;

            var settings = Game.Settings;

            preview = Game.ModData.MapCache[WidgetUtils.ChooseInitialMap(Game.Settings.Server.Map)];

            panel.Get <ButtonWidget>("CREATE_BUTTON").OnClick = CreateAndJoin;

            var mapButton = panel.GetOrNull <ButtonWidget>("MAP_BUTTON");

            if (mapButton != null)
            {
                panel.Get <ButtonWidget>("MAP_BUTTON").OnClick = () =>
                {
                    Ui.OpenWindow("MAPCHOOSER_PANEL", new WidgetArgs()
                    {
                        { "initialMap", preview.Uid },
                        { "initialTab", MapClassification.System },
                        { "onExit", () => { } },
                        { "onSelect", (Action <string>)(uid => preview = Game.ModData.MapCache[uid]) },
                        { "filter", MapVisibility.Lobby },
                        { "onStart", () => { } }
                    });
                };

                panel.Get <MapPreviewWidget>("MAP_PREVIEW").Preview = () => preview;

                var mapTitle = panel.Get <LabelWidget>("MAP_NAME");
                if (mapTitle != null)
                {
                    var font  = Game.Renderer.Fonts[mapTitle.Font];
                    var title = new CachedTransform <MapPreview, string>(m => WidgetUtils.TruncateText(m.Title, mapTitle.Bounds.Width, font));
                    mapTitle.GetText = () => title.Update(preview);
                }
            }

            var serverName = panel.Get <TextFieldWidget>("SERVER_NAME");

            serverName.Text        = Settings.SanitizedServerName(settings.Server.Name);
            serverName.OnEnterKey  = () => { serverName.YieldKeyboardFocus(); return(true); };
            serverName.OnLoseFocus = () =>
            {
                serverName.Text      = Settings.SanitizedServerName(serverName.Text);
                settings.Server.Name = serverName.Text;
            };

            panel.Get <TextFieldWidget>("LISTEN_PORT").Text = settings.Server.ListenPort.ToString();

            advertiseOnline = Game.Settings.Server.AdvertiseOnline;

            var externalPort = panel.Get <TextFieldWidget>("EXTERNAL_PORT");

            externalPort.Text       = settings.Server.ExternalPort.ToString();
            externalPort.IsDisabled = () => !advertiseOnline;

            var advertiseCheckbox = panel.Get <CheckboxWidget>("ADVERTISE_CHECKBOX");

            advertiseCheckbox.IsChecked = () => advertiseOnline;
            advertiseCheckbox.OnClick   = () => advertiseOnline ^= true;

            allowPortForward = Game.Settings.Server.AllowPortForward;
            var checkboxUPnP = panel.Get <CheckboxWidget>("UPNP_CHECKBOX");

            checkboxUPnP.IsChecked  = () => allowPortForward;
            checkboxUPnP.OnClick    = () => allowPortForward ^= true;
            checkboxUPnP.IsDisabled = () => !Game.Settings.Server.NatDeviceAvailable;

            var passwordField = panel.GetOrNull <PasswordFieldWidget>("PASSWORD");

            if (passwordField != null)
            {
                passwordField.Text = Game.Settings.Server.Password;
            }
        }
Esempio n. 14
0
        internal MapChooserLogic(Widget widget, string initialMap, Action onExit, Action <string> onSelect, MapVisibility filter)
        {
            selectedUid = WidgetUtils.ChooseInitialMap(initialMap);

            var approving = new Action(() => { Ui.CloseWindow(); onSelect(selectedUid); });
            var canceling = new Action(() => { Ui.CloseWindow(); onExit(); });

            widget.Get <ButtonWidget>("BUTTON_OK").OnClick     = approving;
            widget.Get <ButtonWidget>("BUTTON_CANCEL").OnClick = canceling;

            scrollpanel        = widget.Get <ScrollPanelWidget>("MAP_LIST");
            scrollpanel.Layout = new GridLayout(scrollpanel);

            itemTemplate = scrollpanel.Get <ScrollItemWidget>("MAP_TEMPLATE");

            var gameModeDropdown = widget.GetOrNull <DropDownButtonWidget>("GAMEMODE_FILTER");

            if (gameModeDropdown != null)
            {
                var selectableMaps = Game.ModData.MapCache.Where(m => m.Status == MapStatus.Available && (m.Map.Visibility & filter) != 0);
                var gameModes      = selectableMaps
                                     .GroupBy(m => m.Type)
                                     .Select(g => Pair.New(g.Key, g.Count())).ToList();

                // 'all game types' extra item
                gameModes.Insert(0, Pair.New(null as string, selectableMaps.Count()));

                Func <Pair <string, int>, string> showItem =
                    x => "{0} ({1})".F(x.First ?? "All Game Types", x.Second);

                Func <Pair <string, int>, ScrollItemWidget, ScrollItemWidget> setupItem = (ii, template) =>
                {
                    var item = ScrollItemWidget.Setup(template,
                                                      () => gameMode == ii.First,
                                                      () => { gameMode = ii.First; EnumerateMaps(onSelect, filter); });
                    item.Get <LabelWidget>("LABEL").GetText = () => showItem(ii);
                    return(item);
                };

                gameModeDropdown.OnClick = () =>
                                           gameModeDropdown.ShowDropDown("LABEL_DROPDOWN_TEMPLATE", 210, gameModes, setupItem);

                gameModeDropdown.GetText = () => showItem(gameModes.First(m => m.First == gameMode));
            }

            var mapfilterInput = widget.GetOrNull <TextFieldWidget>("MAPFILTER_INPUT");

            if (mapfilterInput != null)
            {
                mapfilterInput.TakeKeyboardFocus();
                mapfilterInput.OnEscKey = () =>
                {
                    if (mapfilterInput.Text.Length == 0)
                    {
                        canceling();
                    }
                    else
                    {
                        mapFilter = mapfilterInput.Text = null;
                        EnumerateMaps(onSelect, filter);
                    }

                    return(true);
                };
                mapfilterInput.OnEnterKey   = () => { approving(); return(true); };
                mapfilterInput.OnTextEdited = () =>
                { mapFilter = mapfilterInput.Text; EnumerateMaps(onSelect, filter); };
            }

            var randomMapButton = widget.GetOrNull <ButtonWidget>("RANDOMMAP_BUTTON");

            if (randomMapButton != null)
            {
                randomMapButton.OnClick = () =>
                {
                    var uid = visibleMaps.Random(Game.CosmeticRandom);
                    selectedUid = uid;
                    scrollpanel.ScrollToItem(uid, smooth: true);
                };
                randomMapButton.IsDisabled = () => visibleMaps == null || visibleMaps.Length == 0;
            }

            EnumerateMaps(onSelect, filter);
        }