Пример #1
1
        public override bool GetState(Widget w)
        {
            if (w.Id == "CREATESERVER_CHECKBOX_ONLINE")
                return AdvertiseServerOnline;

            return false;
        }
        public WidgetInstance Build(Widget widget, IEnumerable<int> path, IBuildData buildData)
        {
            // Add the widget's parameters to the context to be picked up by any children
            var propertyInstances = widget.Properties.Select(p => p.Build(buildData)).ToList();
            buildData.ContextSets.Push(propertyInstances);

            var areas = widget.Areas.Select(
                (a, i) => new { Name = a.Name, Components = a.Build(this, path.Append(i), buildData) })
                .ToList()
                .ToDictionary(d => d.Name, d => d.Components);

            buildData.AreaContents.Push(areas);

            var specification = this.widgetSpecificationFinder(widget.Name);

            if (this.renderingInstructions.ShowAmendments)
            {
                specification.ApplyAmendments(this.componentLibrary);
            }

            // Notice that we're passing null as the path - we don't want to annotate the components from the widget
            // specification because they're not components that the editor of the current template can do anything about
            var components = specification.Components.Select((c, i) => c.Build(this, null, buildData)).ToList();

            buildData.AreaContents.Pop();
            buildData.ContextSets.Pop();

            return new WidgetInstance(
                path,
                this.renderingInstructions,
                components);
        }
Пример #3
0
 //////////////////////////////////////////////////////////////////////////
 // Constructor
 //////////////////////////////////////////////////////////////////////////
 public static WidgetPeer make(Widget self)
 {
     System.Type type = System.Type.GetType("Fan.Fwt." + self.type().name().val + "Peer");
       WidgetPeer peer = (WidgetPeer)System.Activator.CreateInstance(type);
       peer.m_self = self;
       return peer;
 }
Пример #4
0
	protected override void OnRender (Cairo.Context cr, Widget widget, Rectangle background_area, Rectangle cell_area, CellRendererState flags)
	{
		int x = (int) (cell_area.X + this.Xpad);
		int y = (int) (cell_area.Y + this.Ypad);
		int width = (int) (cell_area.Width - this.Xpad * 2);
		int height = (int) (cell_area.Height - this.Ypad * 2);

		widget.StyleContext.Save ();
		widget.StyleContext.AddClass ("trough");
		widget.StyleContext.RenderBackground (cr, x, y, width, height);
		widget.StyleContext.RenderFrame (cr, x, y, width, height);
		
		Border padding = widget.StyleContext.GetPadding (StateFlags.Normal);
		x += padding.Left;
		y += padding.Top;
		width -= padding.Left + padding.Right;
		height -= padding.Top + padding.Bottom;

		widget.StyleContext.Restore ();
		
		widget.StyleContext.Save ();
		widget.StyleContext.AddClass ("progressbar");
		widget.StyleContext.RenderActivity (cr, x, y, (int) (width * Percentage), height);
		widget.StyleContext.Restore ();
	}
Пример #5
0
        public ActionResult Create(FormCollection form)
        {

            Widget newWidget = new Widget();
            UpdateModel<Widget>(newWidget);

            //the category ID should be sent in as "categoryid"
            string categoryID = form["CategoryID"];
 
            var widgetCommand = newWidget.GetInsertCommand();

            //save the category too
            Categories_Widget map = new Categories_Widget();
            int catid = 0;
            int.TryParse(categoryID, out catid);
            map.CategoryID = catid;
            map.WidgetID = newWidget.WidgetID;

            var mapCommand = map.GetInsertCommand();

            KonaDB db = new KonaDB();
            db.ExecuteTransaction(new List<DbCommand>() { widgetCommand, mapCommand });

            //return a json result with the ID
            return Json(new { ID = newWidget.WidgetID, Zone = newWidget.Zone });

        }
Пример #6
0
		public void Split(string fieldName, string captionName, params string[] args)
		{
			Widget dataset = new Widget();
			WidgetCollection rows = this["rows"] as WidgetCollection;
			if (rows == null || rows.Count < 1)
			{
				return;
			}
			Widget prevRow = rows[0];
			object prevValue = prevRow[fieldName];
			WidgetCollection temp = new WidgetCollection();
			foreach (Widget i in rows)
			{
				object v = i[fieldName];
				if (!object.Equals(v, prevValue))
				{
					AddPreviousCategory(captionName, dataset, prevRow, temp, args);
					temp = new WidgetCollection();
					prevRow = i;
					prevValue = v;
				}
				temp.Add(i);
			}
			AddPreviousCategory(captionName, dataset, prevRow, temp, args);
			this["dataset"] = dataset;
			this.Remove("rows");
		}
Пример #7
0
        static void Main(string[] args)
        {
            bool input = true;
            while (input)
            {
            Course course = new Course();
            course.Name = Question.AskForString(" Course Name? ");
            course.CRN = Question.AskForInt(" Course CRN number? ");
            int size = Question.AskForInt(" Number of Students? ");

            Widget[] students = new Widget[size];

            for (int i = 0; i < size; i++)
            {
                students[i] = new Widget();
                students[i].SetID(Question.AskForString(" Student Name? "));
                students[i].SetDescription(Question.AskForString(" Student Snumber? "));
            }

            foreach (Widget Student in students)
            {
                Student.Print();
            }

            input = Question.AskForString(" Would you like to start over? ").ToLower().StartsWith("y");

            }

            System.Console.WriteLine();
            System.Console.WriteLine(" Press any key to continue...");
            System.Console.Write(" ");
            System.Console.ReadKey();
        }
Пример #8
0
 private string GetAlign(Widget frame)
 {
     if (((RadioButton)((HBox)((Frame)((Alignment)frame).Child).Child).Children[0]).Active == true)
         return "persistent-apps";
     else
         return "persistent-others";
 }
Пример #9
0
	public static void AddWidget(Container box, Widget widget, int position, bool expandAndFill = false)
	{
		box.Add(widget);
		((Box.BoxChild)box[widget]).Position = position;
		((Box.BoxChild)box[widget]).Expand = expandAndFill;
		((Box.BoxChild)box[widget]).Fill = expandAndFill;
	}
            private void AttachToTable(Table table,
						    Widget widget, uint x,
						    uint y, uint width)
            {
                //                      table.Attach(widget, x, x + width, y, y + 1, AttachOptions.Fill, AttachOptions.Fill, 2, 2);
                table.Attach (widget, x, x + width, y, y + 1);
            }
Пример #11
0
        public void SetUp()
        {
            var specification = new WidgetSpecification(
                "widget name",
                Enumerable.Empty<PropertySpecification>(),
                new IComponent[]
                    {
                        new Atom("atom", Enumerable.Empty<Property>()),
                        new Placeholder("area 1"),
                        new Container("container", Enumerable.Empty<Property>(), new[] { new Placeholder("area 2") })
                    });

            var widget = new Widget(
                "widget name",
                new[]
                    {
                        new Area("area 1", new IComponent[] { new Atom("atom", Enumerable.Empty<Property>()), new Atom("atom", Enumerable.Empty<Property>()) }),
                        new Area("area 2", new IComponent[] { new Atom("atom", Enumerable.Empty<Property>()), new Atom("atom", Enumerable.Empty<Property>()), new Atom("atom", Enumerable.Empty<Property>()) })
                    });

            var buildContext = new BuildData(Enumerable.Empty<IContextItem>());

            var builder = new Builder(RenderingInstructions.BuildForPreview(), n => specification, null);

            this.instance = (WidgetInstance)widget.Build(builder, new[] { 0 }, buildContext);
        }
Пример #12
0
 public DataGridColumn(string name, Widget viewTemplate, IDataBindable editTemplate, Widget headerTemplate)
 {
     this.name = name;
     this.viewTemplate = viewTemplate;
     this.editTemplate = editTemplate;
     this.headerTemplate = headerTemplate;
 }
Пример #13
0
 public static void SaveValue(Widget editor, PropertyItem item, dynamic target)
 {
     var getEditValue = editor as IGetEditValue;
     if (getEditValue != null)
         getEditValue.GetEditValue(item, target);
     else
     {
         var stringValue = editor as IStringValue;
         if (stringValue != null)
             target[item.Name] = stringValue.Value;
         else
         {
             var booleanValue = editor as IBooleanValue;
             if (booleanValue != null)
                 target[item.Name] = booleanValue.Value;
             else
             {
                 var doubleValue = editor as IDoubleValue;
                 if (doubleValue != null)
                 {
                     var value = doubleValue.Value;
                     target[item.Name] = Double.IsNaN(value.As<double>()) ? null : value;
                 }
                 else if (editor.Element.Is(":input"))
                 {
                     target[item.Name] = editor.Element.GetValue();
                 }
             }
         }
     }
 }
        public void SetUp()
        {
            var placeholder1 = new Placeholder("area 1");
            var placeholder2 = new Placeholder("area 2");
            var widgetSpecification = new WidgetSpecification("widget");
            widgetSpecification.Insert(0, placeholder1);
            widgetSpecification.Insert(1, placeholder2);

            var area = new Area("area 1");
            var widget = new Widget("widget", new[] { area });

            var buildContext = new BuildData(Enumerable.Empty<IContextItem>());

            var builder = new Builder(RenderingInstructions.BuildForPreview(), w => widgetSpecification, null);

            var instance = widget.Build(builder, new[] { 0 }, buildContext);

            var rendererFactory = MockRepository.GenerateStub<IRendererFactory>();
            this.viewHelper = MockRepository.GenerateStub<IViewHelper>();
            var multiRenderer = new MultiRenderer(rendererFactory);

            KolaConfigurationRegistry.RegisterRenderer(multiRenderer);

            this.result = instance.Render(multiRenderer);
        }
Пример #15
0
 public void Can_delete_entity()
 {
     var w = new Widget { Name = "sproket", Tags = new[] { "big", "small" } };
     var doc = _sx.Save(w);
     _sx.Delete(w);
     Assert.IsFalse(_sx.ListDocuments().Any(x => x.Id == doc.Id && x.Revision == doc.Revision));
 }
 //Take a widget, and extract its excluded choices, into excluded_choices list
 public void AppendExcluded(Widget w)
 {
     foreach(string s in (w as DialogWidget).excluded_choices)
     {
         excluded_choices.Add(s);
     }
 }
Пример #17
0
        public override bool OnMouseDown(Widget w, MouseInput mi)
        {
            if (w.Id == "SETTINGS_CHECKBOX_UNITDEBUG")
            {
                Game.Settings.UnitDebug = !Game.Settings.UnitDebug;
                return true;
            }

            if (w.Id == "SETTINGS_CHECKBOX_PATHDEBUG")
            {
                Game.Settings.PathDebug = !Game.Settings.PathDebug;
                return true;
            }

            if (w.Id == "SETTINGS_CHECKBOX_INDEXDEBUG")
            {
                Game.Settings.IndexDebug = !Game.Settings.IndexDebug;
                return true;
            }

            if (w.Id == "SETTINGS_CHECKBOX_PERFGRAPH")
            {
                Game.Settings.PerfGraph = !Game.Settings.PerfGraph;
                return true;
            }

            if (w.Id == "SETTINGS_CHECKBOX_PERFTEXT")
            {
                Game.Settings.PerfText = !Game.Settings.PerfText;
                return true;
            }

            return false;
        }
Пример #18
0
        public void GetAllProperties_By_Generic() {
            var widget = new Widget(1, "Widget No1");
            var accessor = DynamicAccessorFactory.CreateDynamicAccessor<Widget>();
            var properties = accessor.GetPropertyNameValueCollection(widget).ToDictionary(pair => pair.Key, pair => pair.Value);

            VerifyPropertyCollection(properties);
        }
Пример #19
0
	protected override void Render (Drawable window, Widget widget, Rectangle background_area, Rectangle cell_area, Rectangle expose_area, CellRendererState flags)
	{
		int width = 0, height = 0, x_offset = 0, y_offset = 0;
		StateType state;
		GetSize (widget, ref cell_area, out x_offset, out y_offset, out width, out height);

		if (widget.HasFocus)
			state = StateType.Active;
		else
			state = StateType.Normal;

		width -= (int) this.Xpad * 2;
		height -= (int) this.Ypad * 2;


		//FIXME: Style.PaintBox needs some customization so that if you pass it
		//a Gdk.Rectangle.Zero it gives a clipping area big enough to draw
		//everything
		Gdk.Rectangle clipping_area = new Gdk.Rectangle ((int) (cell_area.X + x_offset + this.Xpad), (int) (cell_area.Y + y_offset + this.Ypad), width - 1, height - 1);
		
		Style.PaintBox (widget.Style, (Gdk.Window) window, StateType.Normal, ShadowType.In, clipping_area, widget, "trough", (int) (cell_area.X + x_offset + this.Xpad), (int) (cell_area.Y + y_offset + this.Ypad), width - 1, height - 1);

		Gdk.Rectangle clipping_area2 = new Gdk.Rectangle ((int) (cell_area.X + x_offset + this.Xpad), (int) (cell_area.Y + y_offset + this.Ypad), (int) (width * Percentage), height - 1);
		
		Style.PaintBox (widget.Style, (Gdk.Window) window, state, ShadowType.Out, clipping_area2, widget, "bar", (int) (cell_area.X + x_offset + this.Xpad), (int) (cell_area.Y + y_offset + this.Ypad), (int) (width * Percentage), height - 1);
	}
Пример #20
0
        public void GetAllFields_By_Generic() {
            var widget = new Widget(1, "Widget No1");
            var accessor = DynamicAccessorFactory.CreateDynamicAccessor<Widget>();
            var fields = accessor.GetFieldNameValueCollection(widget).ToDictionary(pair => pair.Key, pair => pair.Value);

            VerifyFieldCollection(fields);
        }
Пример #21
0
		internal static FrameworkElementFactory CreateBoundColumnTemplate (ApplicationContext ctx, Widget parent, CellViewCollection views, string dataPath = ".")
		{
			if (views.Count == 1)
                return CreateBoundCellRenderer(ctx, parent, views[0], dataPath);
			
			FrameworkElementFactory container = new FrameworkElementFactory (typeof (StackPanel));
			container.SetValue (StackPanel.OrientationProperty, System.Windows.Controls.Orientation.Horizontal);

			foreach (CellView view in views) {
				var factory = CreateBoundCellRenderer(ctx, parent, view, dataPath);

				factory.SetValue(FrameworkElement.MarginProperty, CellMargins);

				if (view.VisibleField != null)
				{
					var binding = new Binding(dataPath + "[" + view.VisibleField.Index + "]");
					binding.Converter = new BooleanToVisibilityConverter();
					factory.SetBinding(UIElement.VisibilityProperty, binding);
				}
				else if (!view.Visible)
					factory.SetValue(UIElement.VisibilityProperty, Visibility.Collapsed);

				container.AppendChild(factory);
			}

			return container;
		}
Пример #22
0
        public override bool OnMouseUp(Widget w, MouseInput mi)
        {
            if (w.Id == "MAINMENU_BUTTON_CREATE")
            {
                Game.chrome.rootWidget.ShowMenu("CREATESERVER_BG");
                return true;
            }

            if (w.Id == "CREATESERVER_BUTTON_CANCEL")
            {
                Game.chrome.rootWidget.ShowMenu("MAINMENU_BG");
                return true;
            }

            if (w.Id == "CREATESERVER_BUTTON_START")
            {
                Game.chrome.rootWidget.ShowMenu(null);
                Log.Write("Creating server");

                Server.Server.ServerMain(AdvertiseServerOnline, Game.Settings.MasterServer,
                                        Game.Settings.GameName, Game.Settings.ListenPort,
                                        Game.Settings.ExternalPort, Game.Settings.InitialMods);

                Log.Write("Joining server");
                Game.JoinServer(IPAddress.Loopback.ToString(), Game.Settings.ListenPort);
                return true;
            }

            return false;
        }
Пример #23
0
 public VerticalLine(Widget parent)
     : base(parent)
 {
     Background = parent.Background;
     Foreground = ConsoleColor.Black;
     Border = BorderStyle.Thin;
 }
Пример #24
0
 public CircleSelector(
     Widget holder,
     Boolean fillEnabled = false,
     Boolean outlineEnabled = true,
     Boolean constantDrawing = false)
     : base(holder, fillEnabled, outlineEnabled, constantDrawing)
 {
 }
Пример #25
0
 public void Move(Widget w, double theta, uint r)
 {
     PolarFixedChild pfc = (PolarFixedChild)this[w];
     if (pfc != null) {
         pfc.Theta = theta;
         pfc.R = r;
     }
 }
 public void Session_can_only_save_attachments_to_enrolled_entities()
 {
     var a = "Sessions can save attachments!";
     var w = new Widget() {Name = "foo"};
     Assert.Throws<Exception>(
         () => _sx.AttachFile(w, "test.txt", "text/plain", new MemoryStream(Encoding.ASCII.GetBytes(a)))
     );
 }
Пример #27
0
 public HorizontalBarGraph(Widget parent)
     : base(parent)
 {
     Entries = new List<int>();
     Foreground = ConsoleColor.DarkGreen;
     Background = Parent.Background;
     Max = 100;
 }
Пример #28
0
 internal static WidgetModel From(Widget widget)
 {
     return new WidgetModel()
     {
         WidgetId = widget.Id,
         WidgetDefinitionId = widget.WidgetDefinitionId
     };
 }
        public void AdjustChild(Widget w)
        {
            if (widget.Children.Count == 0)
                widget.ContentHeight = widget.ItemSpacing;

            w.Bounds.Y += widget.ContentHeight;
            widget.ContentHeight += w.Bounds.Height + widget.ItemSpacing;
        }
Пример #30
0
        public void Log_Enter_without_params_increments_counter()
        {
            var widget = new Widget();

            widget.DoStuff("with a param");

            Assert.AreEqual(1, Counter.For<Widget>("DoStuff").Count);
        }
Пример #31
0
        public IngameMenuLogic(Widget widget, ModData modData, World world, Action onExit, WorldRenderer worldRenderer,
                               IngameInfoPanel activePanel, Dictionary <string, MiniYaml> logicArgs)
        {
            this.modData       = modData;
            this.world         = world;
            this.worldRenderer = worldRenderer;
            this.onExit        = onExit;

            var buttonHandlers = new Dictionary <string, Action>
            {
                { "ABORT_MISSION", CreateAbortMissionButton },
                { "RESTART", CreateRestartButton },
                { "SURRENDER", CreateSurrenderButton },
                { "LOAD_GAME", CreateLoadGameButton },
                { "SAVE_GAME", CreateSaveGameButton },
                { "MUSIC", CreateMusicButton },
                { "SETTINGS", CreateSettingsButton },
                { "RESUME", CreateResumeButton },
                { "SAVE_MAP", CreateSaveMapButton },
                { "EXIT_EDITOR", CreateExitEditorButton }
            };

            isSinglePlayer = !world.LobbyInfo.GlobalSettings.Dedicated && world.LobbyInfo.NonBotClients.Count() == 1;

            menu = widget.Get("INGAME_MENU");
            mpe  = world.WorldActor.TraitOrDefault <MenuPaletteEffect>();
            mpe?.Fade(mpe.Info.MenuEffect);

            menu.Get <LabelWidget>("VERSION_LABEL").Text = modData.Manifest.Metadata.Version;

            buttonContainer = menu.Get("MENU_BUTTONS");
            buttonTemplate  = buttonContainer.Get <ButtonWidget>("BUTTON_TEMPLATE");
            buttonContainer.RemoveChild(buttonTemplate);
            buttonContainer.IsVisible = () => !hideMenu;

            if (logicArgs.TryGetValue("ButtonStride", out var buttonStrideNode))
            {
                buttonStride = FieldLoader.GetValue <int2>("ButtonStride", buttonStrideNode.Value);
            }

            var scriptContext = world.WorldActor.TraitOrDefault <LuaScript>();

            hasError = scriptContext != null && scriptContext.FatalErrorOccurred;

            if (logicArgs.TryGetValue("Buttons", out var buttonsNode))
            {
                var buttonIds = FieldLoader.GetValue <string[]>("Buttons", buttonsNode.Value);
                foreach (var button in buttonIds)
                {
                    if (buttonHandlers.TryGetValue(button, out var createHandler))
                    {
                        createHandler();
                    }
                }
            }

            // Recenter the button container
            if (buttons.Count > 0)
            {
                var expand = (buttons.Count - 1) * buttonStride;
                buttonContainer.Bounds.X      -= expand.X / 2;
                buttonContainer.Bounds.Y      -= expand.Y / 2;
                buttonContainer.Bounds.Width  += expand.X;
                buttonContainer.Bounds.Height += expand.Y;
            }

            var panelRoot = widget.GetOrNull("PANEL_ROOT");

            if (panelRoot != null && world.Type != WorldType.Editor)
            {
                Action <bool> requestHideMenu = h => hideMenu = h;
                var           gameInfoPanel   = Game.LoadWidget(world, "GAME_INFO_PANEL", panelRoot, new WidgetArgs()
                {
                    { "activePanel", activePanel },
                    { "hideMenu", requestHideMenu }
                });

                gameInfoPanel.IsVisible = () => !hideMenu;
            }
        }
Пример #32
0
        public VxlBrowserLogic(Widget widget, Action onExit, ModData modData, World world, Dictionary <string, MiniYaml> logicArgs)
        {
            this.world   = world;
            this.modData = modData;
            panel        = widget;

            var voxelWidget = panel.GetOrNull <VoxelWidget>("VOXEL");

            if (voxelWidget != null)
            {
                voxelWidget.GetVoxel             = () => currentVoxel != null ? currentVoxel : null;
                currentPalette                   = voxelWidget.Palette;
                voxelWidget.GetPalette           = () => currentPalette;
                voxelWidget.GetPlayerPalette     = () => currentPlayerPalette;
                voxelWidget.GetNormalsPalette    = () => currentNormalsPalette;
                voxelWidget.GetShadowPalette     = () => currentShadowPalette;
                voxelWidget.GetLightAmbientColor = () => lightAmbientColor;
                voxelWidget.GetLightDiffuseColor = () => lightDiffuseColor;
                voxelWidget.GetLightPitch        = () => lightPitch;
                voxelWidget.GetLightYaw          = () => lightYaw;
                voxelWidget.IsVisible            = () => !isVideoLoaded && !isLoadError;
            }

            var playerWidget = panel.GetOrNull <VqaPlayerWidget>("PLAYER");

            if (playerWidget != null)
            {
                playerWidget.IsVisible = () => isVideoLoaded && !isLoadError;
            }

            var paletteDropDown = panel.GetOrNull <DropDownButtonWidget>("PALETTE_SELECTOR");

            if (paletteDropDown != null)
            {
                paletteDropDown.OnMouseDown = _ => ShowPaletteDropdown(paletteDropDown, world);
                paletteDropDown.GetText     = () => currentPalette;
            }

            var lightAmbientColorPreview = panel.GetOrNull <ColorPreviewManagerWidget>("LIGHT_AMBIENT_COLOR_MANAGER");

            if (lightAmbientColorPreview != null)
            {
                lightAmbientColorPreview.Color = HSLColor.FromRGB(
                    Convert.ToInt32(lightAmbientColor[0] * 255),
                    Convert.ToInt32(lightAmbientColor[1] * 255),
                    Convert.ToInt32(lightAmbientColor[2] * 255)
                    );
            }

            var lightDiffuseColorPreview = panel.GetOrNull <ColorPreviewManagerWidget>("LIGHT_DIFFUSE_COLOR_MANAGER");

            if (lightDiffuseColorPreview != null)
            {
                lightDiffuseColorPreview.Color = HSLColor.FromRGB(
                    Convert.ToInt32(lightDiffuseColor[0] * 255),
                    Convert.ToInt32(lightDiffuseColor[1] * 255),
                    Convert.ToInt32(lightDiffuseColor[2] * 255)
                    );
            }

            var playerPaletteDropDown = panel.GetOrNull <DropDownButtonWidget>("PLAYER_PALETTE_SELECTOR");

            if (playerPaletteDropDown != null)
            {
                playerPaletteDropDown.OnMouseDown = _ => ShowPlayerPaletteDropdown(playerPaletteDropDown, world);
                playerPaletteDropDown.GetText     = () => currentPlayerPalette;
            }

            var normalsPlaletteDropDown = panel.GetOrNull <DropDownButtonWidget>("NORMALS_PALETTE_SELECTOR");

            if (normalsPlaletteDropDown != null)
            {
                normalsPlaletteDropDown.OnMouseDown = _ => ShowNormalsPaletteDropdown(normalsPlaletteDropDown, world);
                normalsPlaletteDropDown.GetText     = () => currentNormalsPalette;
            }

            var shadowPlaletteDropDown = panel.GetOrNull <DropDownButtonWidget>("SHADOW_PALETTE_SELECTOR");

            if (shadowPlaletteDropDown != null)
            {
                shadowPlaletteDropDown.OnMouseDown = _ => ShowShadowPaletteDropdown(normalsPlaletteDropDown, world);
                shadowPlaletteDropDown.GetText     = () => currentShadowPalette;
            }

            scaleInput = panel.GetOrNull <TextFieldWidget>("SCALE_TEXT");
            scaleInput.OnTextEdited = () => OnScaleEdit();
            scaleInput.OnEscKey     = scaleInput.YieldKeyboardFocus;

            lightPitchInput = panel.GetOrNull <TextFieldWidget>("LIGHTPITCH_TEXT");
            lightPitchInput.OnTextEdited = () => OnLightPitchEdit();
            lightPitchInput.OnEscKey     = lightPitchInput.YieldKeyboardFocus;

            lightYawInput = panel.GetOrNull <TextFieldWidget>("LIGHTYAW_TEXT");
            lightYawInput.OnTextEdited = () => OnLightYawEdit();
            lightYawInput.OnEscKey     = lightYawInput.YieldKeyboardFocus;


            var lightAmbientColorDropDown = panel.GetOrNull <DropDownButtonWidget>("LIGHT_AMBIENT_COLOR");

            if (lightAmbientColorDropDown != null)
            {
                lightAmbientColorDropDown.OnMouseDown = _ => ShowLightAmbientColorDropDown(lightAmbientColorDropDown, lightAmbientColorPreview, world);
                lightAmbientColorBlock          = panel.Get <ColorBlockWidget>("AMBIENT_COLORBLOCK");
                lightAmbientColorBlock.GetColor = () => System.Drawing.Color.FromArgb(
                    Convert.ToInt32(lightAmbientColor[0] * 255),
                    Convert.ToInt32(lightAmbientColor[1] * 255),
                    Convert.ToInt32(lightAmbientColor[2] * 255)
                    );
            }

            lightAmbientColorValue = panel.GetOrNull <LabelWidget>("LIGHTAMBIENTCOLOR_VALUE");
            lightDiffuseColorValue = panel.GetOrNull <LabelWidget>("LIGHTDIFFUSECOLOR_VALUE");

            var lightDiffuseColorDropDown = panel.GetOrNull <DropDownButtonWidget>("LIGHT_DIFFUSE_COLOR");

            if (lightDiffuseColorDropDown != null)
            {
                lightDiffuseColorDropDown.OnMouseDown = _ => ShowLightDiffuseColorDropDown(lightDiffuseColorDropDown, lightDiffuseColorPreview, world);
                lightDiffuseColorBlock          = panel.Get <ColorBlockWidget>("DIFFUSE_COLORBLOCK");
                lightDiffuseColorBlock.GetColor = () => System.Drawing.Color.FromArgb(
                    Convert.ToInt32(lightDiffuseColor[0] * 255),
                    Convert.ToInt32(lightDiffuseColor[1] * 255),
                    Convert.ToInt32(lightDiffuseColor[2] * 255)
                    );
            }

            unitnameInput = panel.Get <TextFieldWidget>("FILENAME_INPUT");
            unitnameInput.OnTextEdited = () => ApplyFilter();
            unitnameInput.OnEscKey     = unitnameInput.YieldKeyboardFocus;

            if (logicArgs.ContainsKey("SupportedFormats"))
            {
                allowedExtensions = FieldLoader.GetValue <string[]>("SupportedFormats", logicArgs["SupportedFormats"].Value);
            }
            else
            {
                allowedExtensions = new string[0];
            }

            acceptablePackages = modData.ModFiles.MountedPackages.Where(p =>
                                                                        p.Contents.Any(c => allowedExtensions.Contains(Path.GetExtension(c).ToLowerInvariant())));

            unitList = panel.Get <ScrollPanelWidget>("ASSET_LIST");
            template = panel.Get <ScrollItemWidget>("ASSET_TEMPLATE");
            PopulateAssetList();

            var closeButton = panel.GetOrNull <ButtonWidget>("CLOSE_BUTTON");

            if (closeButton != null)
            {
                closeButton.OnClick = () =>
                {
                    if (isVideoLoaded)
                    {
                        player.Stop();
                    }
                    Ui.CloseWindow();
                    onExit();
                }
            }
            ;
        }
Пример #33
0
 internal DockItem(DockFrame frame, Widget w, string id)
 {
     this.frame = frame;
     this.id    = id;
     content    = w;
 }
Пример #34
0
        public ProductionTooltipLogic(Widget widget, TooltipContainerWidget tooltipContainer, ProductionPaletteWidget palette, World world)
        {
            var mapRules = palette.World.Map.Rules;
            var pm       = palette.World.LocalPlayer.PlayerActor.Trait <PowerManager>();
            var pr       = palette.World.LocalPlayer.PlayerActor.Trait <PlayerResources>();

            widget.IsVisible = () => palette.TooltipIcon != null;
            var nameLabel     = widget.Get <LabelWidget>("NAME");
            var hotkeyLabel   = widget.Get <LabelWidget>("HOTKEY");
            var requiresLabel = widget.Get <LabelWidget>("REQUIRES");
            var powerLabel    = widget.Get <LabelWidget>("POWER");
            var powerIcon     = widget.Get <ImageWidget>("POWER_ICON");
            var timeLabel     = widget.Get <LabelWidget>("TIME");
            var timeIcon      = widget.Get <ImageWidget>("TIME_ICON");
            var costLabel     = widget.Get <LabelWidget>("COST");
            var costIcon      = widget.Get <ImageWidget>("COST_ICON");
            var descLabel     = widget.Get <LabelWidget>("DESC");

            var iconMargin = timeIcon.Bounds.X;

            var       font         = Game.Renderer.Fonts[nameLabel.Font];
            var       descFont     = Game.Renderer.Fonts[descLabel.Font];
            var       requiresFont = Game.Renderer.Fonts[requiresLabel.Font];
            ActorInfo lastActor    = null;

            tooltipContainer.BeforeRender = () =>
            {
                if (palette.TooltipIcon == null)
                {
                    return;
                }

                var actor = palette.TooltipIcon.Actor;
                if (actor == null || actor == lastActor)
                {
                    return;
                }

                var tooltip   = actor.TraitInfo <TooltipInfo>();
                var buildable = actor.TraitInfo <BuildableInfo>();
                var cost      = actor.TraitInfo <ValuedInfo>().Cost;

                nameLabel.GetText = () => tooltip.Name;

                var hotkey      = palette.TooltipIcon.Hotkey;
                var nameWidth   = font.Measure(tooltip.Name).X;
                var hotkeyText  = "({0})".F(hotkey.DisplayString());
                var hotkeyWidth = hotkey.IsValid() ? font.Measure(hotkeyText).X + 2 * nameLabel.Bounds.X : 0;
                hotkeyLabel.GetText  = () => hotkeyText;
                hotkeyLabel.Bounds.X = nameWidth + 2 * nameLabel.Bounds.X;
                hotkeyLabel.Visible  = hotkey.IsValid();

                var prereqs        = buildable.Prerequisites.Select(a => ActorName(mapRules, a)).Where(s => !s.StartsWith("~"));
                var requiresString = prereqs.Any() ? requiresLabel.Text.F(prereqs.JoinWith(", ")) : "";
                requiresLabel.GetText = () => requiresString;

                var power       = actor.TraitInfos <PowerInfo>().Where(i => i.UpgradeMinEnabledLevel < 1).Sum(i => i.Amount);
                var powerString = power.ToString();
                powerLabel.GetText  = () => powerString;
                powerLabel.GetColor = () => ((pm.PowerProvided - pm.PowerDrained) >= -power || power > 0)
                                        ? Color.White : Color.Red;
                powerLabel.IsVisible = () => power != 0;
                powerIcon.IsVisible  = () => power != 0;

                var lowpower = pm.PowerState != PowerState.Normal;
                var time     = palette.CurrentQueue == null ? 0 : palette.CurrentQueue.GetBuildTime(actor, buildable)
                               * (lowpower ? palette.CurrentQueue.Info.LowPowerSlowdown : 1);
                var timeString = WidgetUtils.FormatTime(time, world.Timestep);
                timeLabel.GetText  = () => timeString;
                timeLabel.GetColor = () => lowpower ? Color.Red : Color.White;

                var costString = cost.ToString();
                costLabel.GetText  = () => costString;
                costLabel.GetColor = () => pr.Cash + pr.Resources >= cost
                                        ? Color.White : Color.Red;

                var descString = buildable.Description.Replace("\\n", "\n");
                descLabel.GetText = () => descString;

                var leftWidth = new[] { nameWidth + hotkeyWidth, requiresFont.Measure(requiresString).X, descFont.Measure(descString).X }.Aggregate(Math.Max);
                var rightWidth = new[] { font.Measure(powerString).X, font.Measure(timeString).X, font.Measure(costString).X }.Aggregate(Math.Max);

                timeIcon.Bounds.X   = powerIcon.Bounds.X = costIcon.Bounds.X = leftWidth + 2 * nameLabel.Bounds.X;
                timeLabel.Bounds.X  = powerLabel.Bounds.X = costLabel.Bounds.X = timeIcon.Bounds.Right + iconMargin;
                widget.Bounds.Width = leftWidth + rightWidth + 3 * nameLabel.Bounds.X + timeIcon.Bounds.Width + iconMargin;

                var leftHeight  = font.Measure(tooltip.Name).Y + requiresFont.Measure(requiresString).Y + descFont.Measure(descString).Y;
                var rightHeight = font.Measure(powerString).Y + font.Measure(timeString).Y + font.Measure(costString).Y;
                widget.Bounds.Height = Math.Max(leftHeight, rightHeight) * 3 / 2 + 3 * nameLabel.Bounds.Y;

                lastActor = actor;
            };
        }
Пример #35
0
 void editBox_ValueChanged(Widget source, EventArgs e)
 {
     setValue();
 }
Пример #36
0
        public void divert(_HeroFlightManifest newManifest)
        {
            D.assert(manifest.tag == newManifest.tag);
            if (manifest.type == HeroFlightDirection.push && newManifest.type == HeroFlightDirection.pop)
            {
                D.assert(newManifest.animation.status == AnimationStatus.reverse);
                D.assert(manifest.fromHero == newManifest.toHero);
                D.assert(manifest.toHero == newManifest.fromHero);
                D.assert(manifest.fromRoute == newManifest.toRoute);
                D.assert(manifest.toRoute == newManifest.fromRoute);

                _proxyAnimation.parent = new ReverseAnimation(newManifest.animation);
                heroRectTween          = new ReverseTween <Rect>(heroRectTween);
            }
            else if (manifest.type == HeroFlightDirection.pop && newManifest.type == HeroFlightDirection.push)
            {
                D.assert(newManifest.animation.status == AnimationStatus.forward);
                D.assert(manifest.toHero == newManifest.fromHero);
                D.assert(manifest.toRoute == newManifest.fromRoute);

                _proxyAnimation.parent = newManifest.animation.drive(
                    new FloatTween(
                        begin: manifest.animation.value,
                        end: 1.0f
                        )
                    );

                if (manifest.fromHero != newManifest.toHero)
                {
                    manifest.fromHero.endFlight(keepPlaceholder: true);
                    newManifest.toHero.startFlight();
                    heroRectTween = _doCreateRectTween(
                        heroRectTween.end,
                        HeroUtils._boundingBoxFor(newManifest.toHero.context, newManifest.toRoute.subtreeContext)
                        );
                }
                else
                {
                    heroRectTween = _doCreateRectTween(heroRectTween.end, heroRectTween.begin);
                }
            }
            else
            {
                D.assert(manifest.fromHero != newManifest.fromHero);
                D.assert(manifest.toHero != newManifest.toHero);

                heroRectTween = _doCreateRectTween(
                    heroRectTween.evaluate(_proxyAnimation),
                    HeroUtils._boundingBoxFor(newManifest.toHero.context, newManifest.toRoute.subtreeContext)
                    );
                shuttle = null;

                if (newManifest.type == HeroFlightDirection.pop)
                {
                    _proxyAnimation.parent = new ReverseAnimation(newManifest.animation);
                }
                else
                {
                    _proxyAnimation.parent = newManifest.animation;
                }
                manifest.fromHero.endFlight(keepPlaceholder: true);
                manifest.toHero.endFlight(keepPlaceholder: true);

                // Let the heroes in each of the routes rebuild with their placeholders.
                newManifest.fromHero.startFlight(shouldIncludedChildInPlaceholder: newManifest.type == HeroFlightDirection.push);
                newManifest.toHero.startFlight();

                overlayEntry.markNeedsBuild();
            }

            _aborted = false;
            manifest = newManifest;
        }
Пример #37
0
 void IXwtRender.SwapBuffers(Widget widget)
 {
 }
Пример #38
0
 public UpdatesView(LauncherWindow game) : base(game)
 {
     widgets = new Widget[13];
 }
Пример #39
0
 public void RemoveColumn(ListViewColumn col, object handle)
 {
     Widget.RemoveColumn((Gtk.TreeViewColumn)handle);
 }
 public StoreProvider(Store <State> store, Widget child, Key key = null) : base(key: key, child: child)
 {
     D.assert(store != null);
     D.assert(child != null);
     this._store = store;
 }
Пример #41
0
        public void DrawImage(GraphicsHandler graphics, RectangleF source, RectangleF destination)
        {
            var image = Widget.GetFrame(1f, Size.Ceiling(destination.Size));

            graphics.Control.DrawImage(image.Bitmap.ToSD(), destination.ToSD(), source.ToSD(), sd.GraphicsUnit.Pixel);
        }
Пример #42
0
 public override void OnLoadComplete(EventArgs e)
 {
     base.OnLoadComplete(e);
     inGroupBox = Widget.FindParent <GroupBox>() != null;
     SetMargins();
 }
Пример #43
0
 public AutomationButtonWidgetViewModel(Widget widget, IAutomationService automationService)
     : base(widget)
 {
     _automationService = automationService;
     ItemClickedCommand = new CaptionCommand <AutomationButtonWidgetViewModel>("", OnItemClicked);
 }
Пример #44
0
        public IrcLogic(Widget widget)
        {
            var historyPanel     = widget.Get <ScrollPanelWidget>("HISTORY_PANEL");
            var historyTemplate  = widget.Get <LabelWidget>("HISTORY_TEMPLATE");
            var nicknamePanel    = widget.Get <ScrollPanelWidget>("NICKNAME_PANEL");
            var nicknameTemplate = widget.Get <LabelWidget>("NICKNAME_TEMPLATE");

            inputBox            = widget.Get <TextFieldWidget>("INPUT_BOX");
            inputBox.OnEnterKey = EnterPressed;
            inputBox.OnTabKey   = TabPressed;
            inputBox.IsDisabled = () => IrcClient.Instance.GetChannel(IrcClient.MainChannel) == null;

            nicknameBox      = widget.Get <TextFieldWidget>("NICKNAME_BOX");
            nicknameBox.Text = ChooseNickname(Game.Settings.Irc.Nickname);

            connectBG    = widget.Get("IRC_CONNECT_BG");
            ircContainer = widget.Get("IRC_CONTAINER");

            widget.Get <ButtonWidget>("DISCONNECT_BUTTON").OnClick = IrcClient.Instance.Disconnect;

            MaybeShowConnectPanel();

            historyPanel.Bind(IrcClient.Instance.History, item => MakeLabelWidget(historyTemplate, item), LabelItemEquals, true);

            var mainChannel = IrcClient.Instance.GetChannel(IrcClient.MainChannel);

            if (mainChannel != null)
            {
                nicknamePanel.Bind(mainChannel.Users, item => MakeLabelWidget(nicknameTemplate, item), LabelItemEquals, false);
            }

            IrcClient.Instance.OnSync += l =>
            {
                var channel = l.GetChannel();
                if (channel.Name.EqualsIC(IrcClient.MainChannel))
                {
                    nicknamePanel.Bind(channel.Users, item => MakeLabelWidget(nicknameTemplate, item), LabelItemEquals, false);
                }
            };
            IrcClient.Instance.OnKick += l =>
            {
                if (l.KickeeNickname.EqualsIC(IrcClient.Instance.LocalUser.Nickname) && l.Target.EqualsIC(IrcClient.MainChannel))
                {
                    nicknamePanel.Unbind();
                }
            };
            IrcClient.Instance.OnPart += l =>
            {
                if (l.PrefixIsSelf() && l.Target.EqualsIC(IrcClient.MainChannel))
                {
                    nicknamePanel.Unbind();
                }
            };
            IrcClient.Instance.OnDisconnect += () =>
            {
                nicknamePanel.Unbind();
                MaybeShowConnectPanel();
            };

            commands.Add("me", args =>
            {
                IrcClient.Instance.Act(IrcClient.MainChannel, args);
                IrcClient.AddAction(IrcClient.Instance.LocalUser.Nickname, args);
            });
            commands.Add("slap", args =>
            {
                IrcClient.Instance.Act(IrcClient.MainChannel, "slaps {0} around a bit with a large trout".F(args));
                IrcClient.AddAction(IrcClient.Instance.LocalUser.Nickname, "slaps {0} around a bit with a large trout".F(args));
            });
            commands.Add("notice", args =>
            {
                var split = args.Split(new[] { ' ' }, 2);
                if (split.Length < 2)
                {
                    IrcClient.AddHistory("/notice: Not enough arguments");
                    return;
                }
                IrcClient.Instance.Notice(split[0], split[1]);
                IrcClient.AddSelfNotice(split[0], split[1]);
            });
            commands.Add("disconnect", args =>
            {
                Game.Settings.Irc.ConnectAutomatically = false;
                Game.Settings.Save();
                IrcClient.Instance.Disconnect();
            });
            commands.Add("quit", args =>
            {
                Game.Settings.Irc.ConnectAutomatically = false;
                Game.Settings.Save();
                if (IrcClient.Instance.IsConnected)
                {
                    IrcClient.Instance.Quit(args);
                }
                else
                {
                    IrcClient.Instance.Disconnect();
                }
            });
            commands.Add("nick", args => IrcClient.Instance.SetNickname(args));
            commands.Add("topic", args => IrcClient.Instance.GetTopic(IrcClient.MainChannel));
        }
Пример #45
0
        internal static Dictionary <object, _HeroState> _allHeroesFor(
            BuildContext context,
            bool isUserGestureTransition,
            NavigatorState navigator)
        {
            D.assert(context != null);
            D.assert(navigator != null);

            Dictionary <object, _HeroState> result = new Dictionary <object, _HeroState> {
            };

            void inviteHero(StatefulElement hero, object tag)
            {
                D.assert(() => {
                    if (result.ContainsKey(tag))
                    {
                        throw new UIWidgetsError(
                            new List <DiagnosticsNode>()
                        {
                            new ErrorSummary("There are multiple heroes that share the same tag within a subtree."),
                            new ErrorDescription(
                                "Within each subtree for which heroes are to be animated (i.e. a PageRoute subtree), " +
                                "each Hero must have a unique non-null tag.\n" +
                                $"In this case, multiple heroes had the following tag: {tag}\n"
                                ),
                            new DiagnosticsProperty <StatefulElement>("Here is the subtree for one of the offending heroes", hero, linePrefix: "# ", style: DiagnosticsTreeStyle.dense),
                        });
                    }
                    return(true);
                });
                Hero       heroWidget = hero.widget as Hero;
                _HeroState heroState  = hero.state as _HeroState;

                if (!isUserGestureTransition || heroWidget.transitionOnUserGestures)
                {
                    result[tag] = heroState;
                }
                else
                {
                    heroState.ensurePlaceholderIsHidden();
                }
            }

            void visitor(Element element)
            {
                Widget widget = element.widget;

                if (widget is Hero)
                {
                    StatefulElement hero = element as StatefulElement;
                    object          tag  = ((Hero)widget).tag;
                    D.assert(tag != null);
                    if (Navigator.of(hero) == navigator)
                    {
                        inviteHero(hero, tag);
                    }
                    else
                    {
                        ModalRoute heroRoute = ModalRoute.of(hero);
                        if (heroRoute != null && heroRoute is PageRoute && heroRoute.isCurrent)
                        {
                            inviteHero(hero, tag);
                        }
                    }
                }

                element.visitChildren(visitor);
            }

            context.visitChildElements(visitor);
            return(result);
        }
Пример #46
0
 bool LabelItemEquals(Widget widget, object item)
 {
     return(item != null && ((LabelWidget)widget).GetText() == item.ToString());
 }
Пример #47
0
        static uint TableGetRowForItem(Table table, Widget item)
        {
            var child = (Table.TableChild)table[item];

            return(child.TopAttach);
        }
Пример #48
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 && !isLoadError;
            }

            var playerWidget = panel.GetOrNull <VqaPlayerWidget>("PLAYER");

            if (playerWidget != null)
            {
                playerWidget.IsVisible = () => isVideoLoaded && !isLoadError;
            }

            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.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.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
                    {
                        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;
            }

            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);
            }

            isLoadError = false;

            try
            {
                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);
                }

                currentFilename          = filename;
                currentSprites           = world.Map.Rules.Sequences.SpriteCache[filename];
                currentFrame             = 0;
                frameSlider.MaximumValue = (float)currentSprites.Length - 1;
                frameSlider.Ticks        = currentSprites.Length;
            }
            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)
        {
            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);
        }
    }
Пример #49
0
        void on_cierraventanas_clicked(object sender, EventArgs args)
        {
            Widget win = (Widget)sender;

            win.Toplevel.Destroy();
        }
Пример #50
0
 /// <summary>
 /// Triggered when the user actuates a widget
 /// </summary>
 /// <param name="widget">widget actuated</param>
 /// <param name="handled">was this handled?</param>
 public void OnWidgetActuated(Widget widget, ref bool handled)
 {
     _alphabetScannerCommon.OnWidgetActuated(widget, ref handled);
 }
Пример #51
0
        public override void Construct()
        {
            Transaction = null;
            Result      = TradeDialogResult.Pending;

            Border = "border-fancy";

            var bottomRow = AddChild(new Widget
            {
                AutoLayout  = AutoLayout.DockBottom,
                MinimumSize = new Point(0, 32)
            });

            TotalDisplay = bottomRow.AddChild(new Widget
            {
                MinimumSize       = new Point(128, 0),
                AutoLayout        = AutoLayout.DockLeft,
                Font              = "outline-font",
                TextColor         = new Vector4(1, 1, 1, 1),
                TextVerticalAlign = VerticalAlign.Center
            });

            SpaceDisplay = bottomRow.AddChild(new Widget
            {
                MinimumSize       = new Point(128, 0),
                AutoLayout        = AutoLayout.DockLeft,
                Font              = "outline-font",
                TextColor         = new Vector4(1, 1, 1, 1),
                TextVerticalAlign = VerticalAlign.Center
            });

            bottomRow.AddChild(new Widget
            {
                Font       = "outline-font",
                Border     = "border-button",
                TextColor  = new Vector4(1, 1, 1, 1),
                Text       = "Propose Trade",
                AutoLayout = AutoLayout.DockRight,
                OnClick    = (sender, args) =>
                {
                    if (EnvoyColumns.Valid && PlayerColumns.Valid)
                    {
                        Result      = TradeDialogResult.Propose;
                        Transaction = new TradeTransaction
                        {
                            EnvoyEntity  = Envoy,
                            EnvoyItems   = EnvoyColumns.SelectedResources,
                            EnvoyMoney   = EnvoyColumns.TradeMoney,
                            PlayerEntity = Player,
                            PlayerItems  = PlayerColumns.SelectedResources,
                            PlayerMoney  = PlayerColumns.TradeMoney
                        };
                        this.Close();
                    }
                    else
                    {
                        Root.ShowTooltip(Root.MousePosition, "Trade is invalid");
                    }
                }
            });

            bottomRow.AddChild(new Widget
            {
                Font       = "outline-font",
                Border     = "border-button",
                TextColor  = new Vector4(1, 1, 1, 1),
                Text       = "Cancel",
                AutoLayout = AutoLayout.DockRight,
                Padding    = new Margin(0, 0, 0, 16),
                OnClick    = (sender, args) =>
                {
                    Result = TradeDialogResult.Cancel;
                    this.Close();
                }
            });

            var mainPanel = AddChild(new TwoColumns
            {
                AutoLayout = AutoLayout.DockFill
            });

            EnvoyColumns = mainPanel.AddChild(new ResourceColumns
            {
                TradeEntity            = Envoy,
                ValueSourceEntity      = Envoy,
                AutoLayout             = AutoLayout.DockFill,
                LeftHeader             = "Their Items",
                RightHeader            = "They Offer",
                OnTotalSelectedChanged = (s) => UpdateBottomDisplays()
            }) as ResourceColumns;

            PlayerColumns = mainPanel.AddChild(new ResourceColumns
            {
                TradeEntity            = Player,
                ValueSourceEntity      = Envoy,
                AutoLayout             = AutoLayout.DockFill,
                ReverseColumnOrder     = true,
                LeftHeader             = "Our Items",
                RightHeader            = "We Offer",
                OnTotalSelectedChanged = (s) => UpdateBottomDisplays()
            }) as ResourceColumns;

            UpdateBottomDisplays();
        }
Пример #52
0
        public WorldTooltipLogic(Widget widget, World world, TooltipContainerWidget tooltipContainer, ViewportControllerWidget viewport)
        {
            widget.IsVisible = () => viewport.TooltipType != WorldTooltipType.None;
            var label  = widget.Get <LabelWidget>("LABEL");
            var flag   = widget.Get <ImageWidget>("FLAG");
            var owner  = widget.Get <LabelWidget>("OWNER");
            var extras = widget.Get <LabelWidget>("EXTRA");

            var font        = Game.Renderer.Fonts[label.Font];
            var ownerFont   = Game.Renderer.Fonts[owner.Font];
            var labelText   = "";
            var showOwner   = false;
            var flagFaction = "";
            var ownerName   = "";
            var ownerColor  = Color.White;
            var extraText   = "";

            var singleHeight        = widget.Get("SINGLE_HEIGHT").Bounds.Height;
            var doubleHeight        = widget.Get("DOUBLE_HEIGHT").Bounds.Height;
            var extraHeightOnDouble = extras.Bounds.Y;
            var extraHeightOnSingle = extraHeightOnDouble - (doubleHeight - singleHeight);

            tooltipContainer.BeforeRender = () =>
            {
                if (viewport == null || viewport.TooltipType == WorldTooltipType.None)
                {
                    return;
                }

                var index = 0;
                extraText = "";
                showOwner = false;

                Player o = null;
                switch (viewport.TooltipType)
                {
                case WorldTooltipType.Unexplored:
                    labelText = "Unrevealed Terrain";
                    break;

                case WorldTooltipType.Resource:
                    labelText = viewport.ResourceTooltip.Info.Name;
                    break;

                case WorldTooltipType.Actor:
                {
                    o         = viewport.ActorTooltip.Owner;
                    showOwner = o != null && !o.NonCombatant && viewport.ActorTooltip.TooltipInfo.IsOwnerRowVisible;

                    var stance = o == null || world.RenderPlayer == null ? Stance.None : o.Stances[world.RenderPlayer];
                    labelText = viewport.ActorTooltip.TooltipInfo.TooltipForPlayerStance(stance);
                    break;
                }

                case WorldTooltipType.FrozenActor:
                {
                    o         = viewport.FrozenActorTooltip.TooltipOwner;
                    showOwner = o != null && !o.NonCombatant && viewport.FrozenActorTooltip.TooltipInfo.IsOwnerRowVisible;

                    var stance = o == null || world.RenderPlayer == null ? Stance.None : o.Stances[world.RenderPlayer];
                    labelText = viewport.FrozenActorTooltip.TooltipInfo.TooltipForPlayerStance(stance);
                    break;
                }
                }

                if (viewport.ActorTooltipExtra != null)
                {
                    foreach (var info in viewport.ActorTooltipExtra)
                    {
                        if (info.IsTooltipVisible(world.RenderPlayer))
                        {
                            if (index != 0)
                            {
                                extraText += "\n";
                            }
                            extraText += info.TooltipText;
                            index++;
                        }
                    }
                }

                var textWidth = Math.Max(font.Measure(labelText).X, font.Measure(extraText).X);
                label.Bounds.Width  = textWidth;
                widget.Bounds.Width = 2 * label.Bounds.X + textWidth;

                if (showOwner)
                {
                    flagFaction          = o.Faction.InternalName;
                    ownerName            = o.PlayerName;
                    ownerColor           = o.Color;
                    widget.Bounds.Height = doubleHeight;
                    widget.Bounds.Width  = Math.Max(widget.Bounds.Width,
                                                    owner.Bounds.X + ownerFont.Measure(ownerName).X + label.Bounds.X);
                    index++;
                }
                else
                {
                    widget.Bounds.Height = singleHeight;
                }

                if (extraText != "")
                {
                    widget.Bounds.Height += font.Measure(extraText).Y + extras.Bounds.Height;
                    if (showOwner)
                    {
                        extras.Bounds.Y = extraHeightOnDouble;
                    }
                    else
                    {
                        extras.Bounds.Y = extraHeightOnSingle;
                    }
                }
            };

            label.GetText           = () => labelText;
            flag.IsVisible          = () => showOwner;
            flag.GetImageCollection = () => "flags";
            flag.GetImageName       = () => flagFaction;
            owner.IsVisible         = () => showOwner;
            owner.GetText           = () => ownerName;
            owner.GetColor          = () => ownerColor;
            extras.GetText          = () => extraText;
        }
Пример #53
0
 /// <summary>
 /// Not used
 /// </summary>
 /// <param name="parent"></param>
 /// <param name="widget"></param>
 public void SetTargetControl(Form parent, Widget widget)
 {
 }
Пример #54
0
        public void RenderSelection(Widget widget, IntVector2 offset)
        {
            widget.PrepareRendererState();
            var gridSpans = new List <Core.Components.GridSpanList>();

            foreach (var row in Document.Current.Rows)
            {
                gridSpans.Add(row.Components.GetOrAdd <Core.Components.GridSpanListComponent>().Spans.GetNonOverlappedSpans());
            }

            for (var row = 0; row < Document.Current.Rows.Count; row++)
            {
                var spans       = gridSpans[row];
                int?lastColumn  = null;
                var topSpans    = row > 0 ? gridSpans[row - 1].GetEnumerator() : (IEnumerator <Core.Components.GridSpan>)null;
                var bottomSpans = row + 1 < Document.Current.Rows.Count ? gridSpans[row + 1].GetEnumerator() : (IEnumerator <Core.Components.GridSpan>)null;
                Core.Components.GridSpan?topSpan    = null;
                Core.Components.GridSpan?bottomSpan = null;
                var offsetRow        = row + offset.Y;
                var gridWidgetBottom = (0 <= offsetRow && offsetRow < Document.Current.Rows.Count) ? (float?)Document.Current.Rows[offsetRow].GridWidget().Bottom() : null;
                for (var i = 0; i < spans.Count; i++)
                {
                    var span       = spans[i];
                    var isLastSpan = i + 1 == spans.Count;
                    for (var column = span.A; column < span.B; column++)
                    {
                        var isLeftCellMissing = !lastColumn.HasValue || column - 1 > lastColumn.Value;
                        if (topSpans != null && (!topSpan.HasValue || column >= topSpan.Value.B))
                        {
                            do
                            {
                                if (!topSpans.MoveNext())
                                {
                                    topSpans = null;
                                    topSpan  = null;
                                    break;
                                }
                                topSpan = topSpans.Current;
                            } while (column >= topSpan.Value.B);
                        }
                        var isTopCellMissing   = !topSpan.HasValue || column < topSpan.Value.A;
                        var isRightCellMissing = column + 1 == span.B && (isLastSpan || column + 1 < spans[i + 1].A);
                        if (bottomSpans != null && (!bottomSpan.HasValue || column >= bottomSpan.Value.B))
                        {
                            do
                            {
                                if (!bottomSpans.MoveNext())
                                {
                                    bottomSpans = null;
                                    bottomSpan  = null;
                                    break;
                                }
                                bottomSpan = bottomSpans.Current;
                            } while (column >= bottomSpan.Value.B);
                        }
                        var isBottomCellMissing = !bottomSpan.HasValue || column < bottomSpan.Value.A;
                        lastColumn = column;

                        var a = CellToGridCoordinates(new IntVector2(column, row) + offset);
                        var b = CellToGridCoordinates(new IntVector2(column + 1, row + 1) + offset);
                        a = new Vector2(a.X + 1.5f, a.Y + 0.5f);
                        b = new Vector2(b.X - 0.5f, (gridWidgetBottom ?? b.Y) - 0.5f);
                        Renderer.DrawRect(a + Vector2.Up * 0.5f, b + new Vector2(1f + (isRightCellMissing ? 0 : 1), (isBottomCellMissing ? 0 : 1)), ColorTheme.Current.TimelineGrid.Selection);
                        if (isLeftCellMissing)
                        {
                            Renderer.DrawLine(a.X, a.Y - (isTopCellMissing ? 0 : 1), a.X, b.Y + (isBottomCellMissing ? 0 : 1), ColorTheme.Current.TimelineGrid.SelectionBorder, cap: LineCap.Square);
                        }
                        if (isTopCellMissing)
                        {
                            Renderer.DrawLine(a.X - (isLeftCellMissing ? 0 : 1), a.Y, b.X + (isRightCellMissing ? 0 : 1), a.Y, ColorTheme.Current.TimelineGrid.SelectionBorder, cap: LineCap.Square);
                        }
                        if (isRightCellMissing)
                        {
                            Renderer.DrawLine(b.X, a.Y - (isTopCellMissing ? 0 : 1), b.X, b.Y + (isBottomCellMissing ? 0 : 1), ColorTheme.Current.TimelineGrid.SelectionBorder, cap: LineCap.Square);
                        }
                        if (isBottomCellMissing)
                        {
                            Renderer.DrawLine(a.X - (isLeftCellMissing ? 0 : 1), b.Y, b.X + (isRightCellMissing ? 0 : 1), b.Y, ColorTheme.Current.TimelineGrid.SelectionBorder, cap: LineCap.Square);
                        }
                    }
                }
                topSpans = spans.GetEnumerator();
            }
        }
Пример #55
0
        public void DrawImage(GraphicsHandler graphics, float x, float y, float width, float height)
        {
            var image = Widget.GetFrame(1f, Size.Ceiling(new SizeF(width, height)));

            graphics.Control.DrawImage(image.Bitmap.ToSD(), x, y, width, height);
        }
Пример #56
0
        public override Widget buildTransitions(BuildContext context, Animation <float> animation,
                                                Animation <float> secondaryAnimation, Widget child)
        {
            Widget result = new Align(
                alignment: Alignment.bottomCenter,
                child: new FractionalTranslation(
                    translation: this._offsetTween.evaluate(animation: this._animation),
                    child: child
                    )
                );

            if (this.overlayBuilder != null)
            {
                result = new Stack(
                    children: new List <Widget> {
                    Positioned.fill(
                        child: new Opacity(
                            opacity: this._opacityTween.evaluate(animation: this._animation),
                            child: this.overlayBuilder(context)
                            )
                        ),
                    result
                });
            }

            return(result);
        }
Пример #57
0
        public TestResultsPad()
        {
            UnitTestService.TestSuiteChanged     += new EventHandler(OnTestSuiteChanged);
            IdeApp.Workspace.WorkspaceItemClosed += OnWorkspaceItemClosed;

            panel = new VBox {
                Name = "testResultBox"
            };

            // Results notebook

            book = new HPaned();
            panel.PackStart(book, true, true, 0);
            panel.FocusChain = new Gtk.Widget [] { book };

            // Failures tree
            failuresTreeView = new MonoDevelop.Ide.Gui.Components.PadTreeView {
                Name = "testResultsTree"
            };
            failuresTreeView.HeadersVisible = false;
            failuresStore = new TreeStore(typeof(Xwt.Drawing.Image), typeof(string), typeof(object), typeof(string), typeof(int), typeof(int));
            SemanticModelAttribute modelAttr = new SemanticModelAttribute("store__Image", "store__Message", "store__RootTest",
                                                                          "store__FileName", "store__FileNumber", "store__ErrorOrStackTrace");

            TypeDescriptor.AddAttributes(failuresStore, modelAttr);

            var pr = new CellRendererImage();
            CellRendererText tr  = new CellRendererText();
            TreeViewColumn   col = new TreeViewColumn();

            col.PackStart(pr, false);
            col.AddAttribute(pr, "image", 0);
            col.PackStart(tr, false);
            col.AddAttribute(tr, "markup", 1);
            failuresTreeView.AppendColumn(col);
            failuresTreeView.Model = failuresStore;

            var sw = new MonoDevelop.Components.CompactScrolledWindow();

            sw.ShadowType = ShadowType.None;
            sw.Add(failuresTreeView);
            book.Pack1(sw, true, true);

            outputView = new MonoDevelop.Ide.Gui.Components.LogView.LogTextView {
                Name = "testResultOutput"
            };
            outputView.ModifyFont(FontService.MonospaceFont);
            outputView.Editable = false;
            bold        = new TextTag("bold");
            bold.Weight = Pango.Weight.Bold;
            outputView.Buffer.TagTable.Add(bold);
            sw            = new MonoDevelop.Components.CompactScrolledWindow();
            sw.ShadowType = ShadowType.None;
            sw.Add(outputView);
            book.Pack2(sw, true, true);
            outputViewScrolled = sw;

            failuresTreeView.RowActivated      += OnRowActivated;
            failuresTreeView.Selection.Changed += OnRowSelected;
            failuresTreeView.DoPopupMenu        = delegate(EventButton evt) {
                IdeApp.CommandService.ShowContextMenu(failuresTreeView, evt,
                                                      "/MonoDevelop/UnitTesting/ContextMenu/TestResultsPad");
            };

            panel.ShowAll();

            outputViewScrolled.Hide();
        }
Пример #58
0
 void RenderSelection(Widget widget)
 {
     RenderSelection(widget, IntVector2.Zero);
 }
Пример #59
0
 Widget _defaultTransitionsBuilder(BuildContext context, Animation <double>
                                   animation, Animation <double> secondaryAnimation, Widget child)
 {
     return(child);
 }
Пример #60
0
        public ButtonTooltipWithDescHighlightLogic(Widget widget, ButtonWidget button, Dictionary <string, MiniYaml> logicArgs)
        {
            var label      = widget.Get <LabelWidget>("LABEL");
            var font       = Game.Renderer.Fonts[label.Font];
            var text       = button.GetTooltipText();
            var labelWidth = font.Measure(text).X;
            var key        = button.Key.GetValue();

            label.GetText       = () => text;
            label.Bounds.Width  = labelWidth;
            widget.Bounds.Width = 2 * label.Bounds.X + labelWidth;

            if (key.IsValid())
            {
                var hotkey = widget.Get <LabelWidget>("HOTKEY");
                hotkey.Visible = true;

                var hotkeyLabel = "({0})".F(key.DisplayString());
                hotkey.GetText  = () => hotkeyLabel;
                hotkey.Bounds.X = labelWidth + 2 * label.Bounds.X;

                widget.Bounds.Width = hotkey.Bounds.X + label.Bounds.X + font.Measure(hotkeyLabel).X;
            }

            var desc = button.GetTooltipDesc();

            if (!string.IsNullOrEmpty(desc))
            {
                var descTemplate   = widget.Get <LabelWidget>("DESC");
                var highlightColor = FieldLoader.GetValue <Color>("Highlight", logicArgs["Highlight"].Value);
                widget.RemoveChild(descTemplate);

                var descFont   = Game.Renderer.Fonts[descTemplate.Font];
                var descWidth  = 0;
                var descOffset = descTemplate.Bounds.Y;

                foreach (var l in desc.Split(new[] { "\\n" }, StringSplitOptions.None))
                {
                    var line      = l;
                    var lineWidth = 0;
                    var xOffset   = descTemplate.Bounds.X;

                    while (line.Length > 0)
                    {
                        var highlightStart = line.IndexOf('{');
                        var highlightEnd   = line.IndexOf('}', 0);

                        if (highlightStart > 0 && highlightEnd > highlightStart)
                        {
                            if (highlightStart > 0)
                            {
                                // Normal line segment before highlight
                                var lineNormal      = line.Substring(0, highlightStart);
                                var lineNormalWidth = descFont.Measure(lineNormal).X;
                                var lineNormalLabel = (LabelWidget)descTemplate.Clone();
                                lineNormalLabel.GetText      = () => lineNormal;
                                lineNormalLabel.Bounds.X     = descTemplate.Bounds.X + lineWidth;
                                lineNormalLabel.Bounds.Y     = descOffset;
                                lineNormalLabel.Bounds.Width = lineNormalWidth;
                                widget.AddChild(lineNormalLabel);

                                lineWidth += lineNormalWidth;
                            }

                            // Highlight line segment
                            var lineHighlight      = line.Substring(highlightStart + 1, highlightEnd - highlightStart - 1);
                            var lineHighlightWidth = descFont.Measure(lineHighlight).X;
                            var lineHighlightLabel = (LabelWidget)descTemplate.Clone();
                            lineHighlightLabel.GetText      = () => lineHighlight;
                            lineHighlightLabel.GetColor     = () => highlightColor;
                            lineHighlightLabel.Bounds.X     = descTemplate.Bounds.X + lineWidth;
                            lineHighlightLabel.Bounds.Y     = descOffset;
                            lineHighlightLabel.Bounds.Width = lineHighlightWidth;
                            widget.AddChild(lineHighlightLabel);

                            lineWidth += lineHighlightWidth;
                            line       = line.Substring(highlightEnd + 1);
                        }
                        else
                        {
                            // Final normal line segment
                            var lineLabel = (LabelWidget)descTemplate.Clone();
                            var width     = descFont.Measure(line).X;
                            lineLabel.GetText  = () => line;
                            lineLabel.Bounds.X = descTemplate.Bounds.X + lineWidth;
                            lineLabel.Bounds.Y = descOffset;
                            widget.AddChild(lineLabel);

                            lineWidth += width;
                            break;
                        }
                    }

                    descWidth = Math.Max(descWidth, lineWidth);

                    descOffset += descTemplate.Bounds.Height;
                }

                widget.Bounds.Width   = Math.Max(widget.Bounds.Width, descTemplate.Bounds.X * 2 + descWidth);
                widget.Bounds.Height += descOffset - descTemplate.Bounds.Y + descTemplate.Bounds.X;
            }
        }