Disabled GUI component mid-handle for now... may look at it later again

Import mojo
Import diddy

Const ACTION_CLICKED$ = "clicked"
Const ACTION_VALUE_CHANGED$ = "changed"

Class Rectangle
	Field x#, y#, w#, h#
	Field empty? = False

	Method New(x#, y#, w#, h#)
		Set(x, y, w, h)
	End

	Method Set:Void(x#, y#, w#, h#)
		Self.x = x
		Self.y = y
		Self.w = w
		Self.h = h
		Self.empty = Self.w <= 0 Or Self.h <= 0
	End

	Method Set:Void(srcRect:Rectangle)
		Self.x = srcRect.x
		Self.y = srcRect.y
		Self.w = srcRect.w
		Self.h = srcRect.h
		Self.empty = Self.w <= 0 Or Self.h <= 0
	End

	Method Clear:Void()
		Self.w = -1
		Self.h = -1
		Self.empty = True
	End

	Method Intersect:Void(x#, y#, w#, h#)
		If x >= Self.x + Self.w Or y >= Self.y + Self.h Or Self.x >= x + w Or Self.y >= y + h Then
			Clear()
			Return
		End

		Local r% = Self.x + Self.w
		Local b% = Self.y + Self.h
		If Self.x < x Then Self.x = x
		If Self.y < y Then Self.y = y
		If r > x + w Then r = x + w
		If b > y + h Then b = y + h
		Self.w = r - Self.x
		Self.h = b - Self.y
	End
End

Class GUI Implements ActionListener
	Field desktop:Desktop
	Field scissors:Rectangle[] = New Rectangle[128]
	Field scissorDepth:Int = 0

	Field mouseDown:Bool[3]
	Field mouseDownX:Float[3]
	Field mouseDownY:Float[3]
	Field mouseDownComponent:Component[3]

	Field mouseLastX:Float
	Field mouseLastY:Float
	Field mouseLastComponent:Component
	Field mouseThisX:Float
	Field mouseThisY:Float
	Field mouseThisComponent:Component

	Method New()
		desktop = New Desktop(Self)
		desktop.SetBounds(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)
		For Local i% = 0 Until scissors.Length
			scissors[i] = New Rectangle
		Next
	End

	Method PushScissor:Void(x#, y#, w#, h#)
		' don't use assert, for speed on android (one less method call)
		If scissorDepth >= scissors.Length Then Error("GUI.PushScissor: Out of space for scissors.")
		If scissorDepth = 0 Then
			scissors[0].Set(x, y, w, h)
		Else
			scissors[scissorDepth].Set(scissors[scissorDepth-1])
			scissors[scissorDepth].Intersect(x, y, w, h)
		End
		scissorDepth += 1
		UpdateScissor()
	End

	Method PopScissor:Void()
		If scissorDepth > 0 Then
			scissorDepth -= 1
			scissors[scissorDepth].Clear()
		End
		UpdateScissor()
	End

	Method UpdateScissor:Void()
		If scissorDepth > 0 Then
			If Not EmptyScissor() Then
				SetScissor(scissors[scissorDepth-1].x * SCREENX_RATIO, scissors[scissorDepth-1].y * SCREENY_RATIO, scissors[scissorDepth-1].w * SCREENX_RATIO, scissors[scissorDepth-1].h * SCREENY_RATIO)
			End
		Else
			SetScissor(0, 0, DEVICE_WIDTH, DEVICE_HEIGHT)
		End
	End

	Method EmptyScissor:Bool()
		If scissorDepth <= 0 Then Return False
		Return scissors[scissorDepth-1].empty
	End

	Method Draw()
		desktop.Draw(Self)
		scissorDepth = 0
		SetScissor(0, 0, DEVICE_WIDTH, DEVICE_HEIGHT)
	End

	' TODO: check Z-order
	Method ComponentAtPoint:Component(x#, y#, parent:Component=Null)
		' if no parent, it's the desktop
		If parent = Null Then parent = desktop
		' if the mouse is outside the component, return null
		If parent.midHandle
			x += parent.w2
			y += parent.h2
		EndIf

		If x<0 Or y<0 Or x >= parent.w Or y >= parent.h Then Return Null

		' check if it's inside a child
		Local rv:Component = Null
		For Local i% = 0 Until parent.children.Size
			Local c:Component = parent.children.Get(i)
			rv = ComponentAtPoint(x-c.x, y-c.y, c)

			If rv <> Null Then Return rv
		Next
		' not inside a child, so it's this one
		Return parent
	End

	Method GetAbsoluteX:Float(comp:Component)
		Local rv# = comp.x
		While comp.parent <> Null
			comp = comp.parent
			rv += comp.x
		Wend
		Return rv
	End

	Method GetAbsoluteY:Float(comp:Component)
		Local rv# = comp.y
		While comp.parent <> Null
			comp = comp.parent
			rv += comp.y
		Wend
		Return rv
	End

	Method Update:Void()
		mouseLastX = mouseThisX
		mouseLastY = mouseThisY
		mouseLastComponent = mouseThisComponent
		mouseThisX = game.mouseX
		mouseThisY = game.mouseY
		mouseThisComponent = ComponentAtPoint(mouseThisX, mouseThisY)
		DoMouse(MOUSE_LEFT)
		DoMouse(MOUSE_MIDDLE)
		DoMouse(MOUSE_RIGHT)
	End

	Method DoMouse:Void(button%)
		Local absX#, absY#
		If MouseHit(button) Then
			mouseDown[button] = True
			mouseDownX[button] = mouseThisX
			mouseDownY[button] = mouseThisY
			mouseDownComponent[button] = mouseThisComponent

			' fire pressed on mouseThisComponent
			If mouseThisComponent.mouseAdapter <> Null Then
				absX = GetAbsoluteX(mouseThisComponent)
				absY = GetAbsoluteY(mouseThisComponent)
				mouseThisComponent.mouseAdapter.MousePressed(mouseThisX-absX, mouseThisY-absY, button, mouseThisX, mouseThisY)
			End

			' set mouseDown
			mouseThisComponent.mouseDown = True

		ElseIf mouseDown[button] Then
			' if we released the button
			If Not MouseDown(button) Then
				mouseDown[button] = False
				Local comp:Component = mouseDownComponent[button]
				mouseDownComponent[button] = Null

				' fire mouse released on comp
				If comp.mouseAdapter <> Null Then
					absX = GetAbsoluteX(comp)
					absY = GetAbsoluteY(comp)
					comp.mouseAdapter.MouseReleased(mouseThisX-absX, mouseThisY-absY, button, mouseThisX, mouseThisY)
				End

				' clear mouseDown
				comp.mouseDown = False

				' if we released on the same component, fire mouse clicked
				If mouseThisComponent = comp Then
					If comp.mouseAdapter <> Null Then comp.mouseAdapter.MouseClicked(mouseThisX-absX, mouseThisY-absY, button, mouseThisX, mouseThisY)
				End

			ElseIf mouseLastX <> mouseThisX Or mouseLastY <> mouseThisY Then
				' fire mouse dragged on mouseDownComponent
				If mouseDownComponent[button].mouseMotionAdapter <> Null Then
					absX = GetAbsoluteX(mouseDownComponent[button])
					absY = GetAbsoluteY(mouseDownComponent[button])
					mouseDownComponent[button].mouseMotionAdapter.MouseDragged(mouseThisX-absX, mouseThisY-absY, button, mouseThisX, mouseThisY)
				End

				' if the component changed, fire exit/enter
				If mouseThisComponent <> mouseLastComponent Then
					' fire mouse exited on mouseLastComponent
					If mouseLastComponent.mouseAdapter <> Null Then
						absX = GetAbsoluteX(mouseLastComponent)
						absY = GetAbsoluteY(mouseLastComponent)
						mouseLastComponent.mouseAdapter.MouseExited(mouseThisX-absX, mouseThisY-absY, mouseThisComponent, mouseThisX, mouseThisY)
					End

					' clear mouseHover
					mouseLastComponent.mouseHover = False

					' fire mouse entered on mouseThisComponent
					If mouseThisComponent.mouseAdapter <> Null Then
						absX = GetAbsoluteX(mouseThisComponent)
						absY = GetAbsoluteY(mouseThisComponent)
						mouseThisComponent.mouseAdapter.MouseEntered(mouseThisX-absX, mouseThisY-absY, mouseLastComponent, mouseThisX, mouseThisY)
					End

					' set the STATE_HOVER bit
					mouseThisComponent.mouseHover = True
				End
			End
		Else
			If mouseLastX <> mouseThisX Or mouseLastY <> mouseThisY Then
				' fire mouse moved on mouseThisComponent
				If mouseThisComponent <> Null And mouseThisComponent.mouseMotionAdapter <> Null Then
					absX = GetAbsoluteX(mouseThisComponent)
					absY = GetAbsoluteY(mouseThisComponent)
					mouseThisComponent.mouseMotionAdapter.MouseMoved(mouseThisX-absX, mouseThisY-absY, mouseThisX, absY)
				End

				' if the component changed, fire exit/enter
				If mouseThisComponent <> mouseLastComponent Then
					' fire mouse exited on mouseLastComponent
					If mouseLastComponent <> Null Then
						If mouseLastComponent.mouseAdapter <> Null Then
							absX = GetAbsoluteX(mouseLastComponent)
							absY = GetAbsoluteY(mouseLastComponent)
							mouseLastComponent.mouseAdapter.MouseExited(mouseThisX-absX, mouseThisY-absY, mouseThisComponent, mouseThisX, mouseThisY)
						End

						' clear mouseHover
						mouseLastComponent.mouseHover = False
					End

					' fire mouse entered on mouseThisComponent
					If mouseThisComponent <> Null Then
						If mouseThisComponent.mouseAdapter <> Null Then
							absX = GetAbsoluteX(mouseThisComponent)
							absY = GetAbsoluteY(mouseThisComponent)
							mouseThisComponent.mouseAdapter.MouseEntered(mouseThisX-absX, mouseThisY-absY, mouseLastComponent, mouseThisX, mouseThisY)
						End
						' set mouseHover
						mouseThisComponent.mouseHover = True
					End
				End
			End
		End
	End

	Method ActionPerformed:Void(source:Component, action:String)
	End
End

Interface ActionListener
	Method ActionPerformed:Void(source:Component, action:String)
End

Interface MouseListener
	Method MousePressed:Void(x#, y#, button%, absoluteX#, absoluteY#)
	Method MouseReleased:Void(x#, y#, button%, absoluteX#, absoluteY#)
	Method MouseClicked:Void(x#, y#, button%, absoluteX#, absoluteY#)
	Method MouseEntered:Void(x#, y#, exitedComp:Component, absoluteX#, absoluteY#)
	Method MouseExited:Void(x#, y#, enteredComp:Component, absoluteX#, absoluteY#)
End

Class AbstractMouseAdapter Implements MouseListener Abstract
	Method MousePressed:Void(x#, y#, button%, absoluteX#, absoluteY#)
	End
	Method MouseReleased:Void(x#, y#, button%, absoluteX#, absoluteY#)
	End
	Method MouseClicked:Void(x#, y#, button%, absoluteX#, absoluteY#)
	End
	Method MouseEntered:Void(x#, y#, exitedComp:Component, absoluteX#, absoluteY#)
	End
	Method MouseExited:Void(x#, y#, enteredComp:Component, absoluteX#, absoluteY#)
	End
End

Interface MouseMotionListener
	Method MouseMoved:Void(x#, y#, absoluteX#, absoluteY#)
	Method MouseDragged:Void(x#, y#, button%, absoluteX#, absoluteY#)
End

Class AbstractMouseMotionAdapter Implements MouseMotionListener Abstract
	Method MouseMoved:Void(x#, y#, absoluteX#, absoluteY#)
	End
	Method MouseDragged:Void(x#, y#, button%, absoluteX#, absoluteY#)
	End
End

Class Desktop Extends Component
	Field restrictWindows:Bool = True
	Field parentGUI:GUI
	Method New(parentGUI:GUI)
		Super.New(Null)
		Self.parentGUI = parentGUI
	End

	Method ActionPerformed:Void(source:Component, action:String)
		parentGUI.ActionPerformed(source, action)
	End
End

Class Component Implements ActionListener
Private
	Field midHandle:Bool = False
	Field alpha# = 1
	Field children:ArrayList<Component> = New ArrayList<Component>
	Field mouseAdapter:MouseListener
	Field mouseMotionAdapter:MouseMotionListener
	Field forwardAction:ActionListener = Null
	Field mouseHover:Bool = False
	Field mouseDown:Bool = False

	Field styleNormal:ComponentStyle = Null

Public
	Field parent:Component

	Field x#, y#
	Field w#, h#
	Field w2#, h2#
	Field visible:Bool = True

	Method MouseAdapter:Void(mouseAdapter:MouseListener) Property
		Self.mouseAdapter = mouseAdapter
	End
	Method MouseAdapter:MouseListener() Property
		Return Self.mouseAdapter
	End
	Method MouseMotionAdapter:Void(mouseMotionAdapter:MouseMotionListener) Property
		Self.mouseMotionAdapter = mouseMotionAdapter
	End
	Method MouseMotionAdapter:MouseMotionListener() Property
		Return Self.mouseMotionAdapter
	End
	Method MidHandle:Void(mid:Bool) Property
		Self.midHandle = mid
	End
	Method MidHandle:Bool() Property
		Return Self.midHandle
	End

	Method StyleNormal:ComponentStyle() Property
		If styleNormal = Null Then styleNormal = New ComponentStyle
		Return styleNormal
	End
	Method StyleNormal:Void(style:ComponentStyle) Property
		AssertNotNull(style, "StyleNormal may not be null.")
		styleNormal = style
	End

	Method GetStyle:ComponentStyle(name$)
		If name = "normal" Then Return styleNormal
		Return Null
	End

	Method SetStyle:Void(name$, style:ComponentStyle)
		If name = "normal" Then styleNormal = style
	End

	Method New(parent:Component)
		styleNormal = New ComponentStyle
		' if this isn't the desktop, it must have a parent
		If Not Desktop(Self) Then
			AssertNotNull(parent, "Components must have a parent.")
			Self.parent = parent
			parent.children.Add(Self)
		Else
			styleNormal.drawBackground = False
		End
		AddNotify()
	End

	Method Alpha#() Property
		Return alpha
	End

	Method Alpha:Void(alpha#) Property
		Self.alpha = alpha
		If Self.alpha < 0 Then Self.alpha = 0
		If Self.alpha > 1 Then Self.alpha = 1
	End

	Method SetBackground:Void(red#, green#, blue#)
		If red < 0 Then red = 0
		If red > 255 Then red = 255
		If green < 0 Then green = 0
		If green > 255 Then green = 255
		If blue < 0 Then blue = 0
		If blue > 255 Then blue = 255
		styleNormal.red = red
		styleNormal.green = green
		styleNormal.blue = blue
		styleNormal.drawBackground = True
	End

	Method SetBackground:Void(drawBackground:Bool)
		styleNormal.drawBackground = drawBackground
	End

	Method SetLocation:Void(x#, y#)
		Self.x = x
		Self.y = y
		Layout()
	End

	Method SetSize:Void(w#, h#)
		Self.w = w
		Self.h = h
		Self.w2 = w / 2
		Self.h2 = h / 2
		Layout()
	End

	Method SetBounds:Void(x#, y#, w#, h#)
		Self.x = x
		Self.y = y
		Self.w = w
		Self.h = h
		Layout()
	End

	Method Draw:Void(parentGui:GUI, alpha# = 1, absx# = 0, absy# = 0)
		If visible Then
			parentGui.PushScissor(absx, absy, w, h)
			If Not parentGui.EmptyScissor() Then
				SetAlpha(alpha)
				DrawComponent()
				DrawChildren(parentGui, alpha, absx, absy)
			End
			parentGui.PopScissor()
		End
	End

	Method DrawChildren:Void(parentGui:GUI, alpha# = 1, absx#, absy#)
		For Local c:Component = EachIn children
			PushMatrix()
			Translate(c.x, c.y)
			If Not c.midHandle
				c.Draw(parentGui, c.alpha * alpha, absx + c.x, absy + c.y)
			Else
				c.Draw(parentGui, c.alpha * alpha, absx + c.x - c.w2, absy + c.y - c.h2)
			End
			PopMatrix()
		Next
	End

	Method DrawComponent:Void()
		Local style:ComponentStyle = GetCurrentStyle()
		If style <> Null Then
			' background colour first
			If style.drawBackground Then
				SetColor(style.red, style.green, style.blue)
				SetAlpha(alpha)
				DrawRect(0, 0, w, h)
			End

			' image next, priority = down, hover, normal
			If mouseDown And style.downImage <> Null Then
				SetColor(255,255,255)
				SetAlpha(alpha)
				If style.downImageMode = ComponentStyle.IMAGE_GRID Then
					style.downImage.DrawGrid(0, 0, w, h, style.downImageFrame)
				ElseIf style.downImageMode = ComponentStyle.IMAGE_NORMAL Then
					style.downImage.Draw(0, 0, 0, 1, 1, style.downImageFrame)
				End
			ElseIf mouseHover And style.hoverImage <> Null Then
				SetColor(255,255,255)
				SetAlpha(alpha)
				If style.hoverImageMode = ComponentStyle.IMAGE_GRID Then
					style.hoverImage.DrawGrid(0, 0, w, h, style.hoverImageFrame)
				ElseIf style.hoverImageMode = ComponentStyle.IMAGE_NORMAL Then
					style.hoverImage.Draw(0, 0, 0, 1, 1, style.hoverImageFrame)
				End
			ElseIf style.image <> Null Then
				SetColor(255,255,255)
				SetAlpha(alpha)
				If style.imageMode = ComponentStyle.IMAGE_GRID Then
					style.image.DrawGrid(0, 0, w, h, style.imageFrame)
				ElseIf style.imageMode = ComponentStyle.IMAGE_NORMAL Then
					style.image.Draw(0, 0, 0, 1, 1, style.imageFrame)
				End
			End

			' reset stuff
			SetColor(255,255,255)
			SetAlpha(1)
		End
	End

	Method GetCurrentStyle:ComponentStyle()
		Return styleNormal
	End

	Method Dispose:Void(recursing:Bool = False)
		' we do an empty check first to save creating an enumerator object
		If Not children.IsEmpty() Then
			Local enum:AbstractEnumerator<Component> = children.Enumerator()
			While enum.HasNext()
				Local c:Component = enum.NextObject()
				c.Dispose(True)
				enum.Remove()
			End
		End
		DisposeNotify()
		Local p:Component = Self.parent
		Self.parent = Null
		If Not recursing Then p.children.Remove(Self)
	End

	Method AddNotify:Void()
	End

	Method DisposeNotify:Void()
	End

	Method Layout:Void()
	End

	Method ActionPerformed:Void(source:Component, action:String)
		If forwardAction <> Null Then
			forwardAction.ActionPerformed(source, action)
		End
	End

	Method FindActionTarget:ActionListener()
		' if this is a window or desktop, return itself
		If Window(Self) <> Null Or Desktop(Self) <> Null Then Return Self
		' traverse up the hierarchy and find the closest Window or Desktop to receive the actions
		Local comp:Component = Self
		While Window(Self) = Null And Desktop(Self) = Null And comp.parent <> Null
			comp = comp.parent
		End
		Return comp
	End
End

Class ComponentStyle
	Global IMAGE_NORMAL% = 0
	Global IMAGE_TILE% = 1
	Global IMAGE_STRETCH% = 2
	Global IMAGE_GRID% = 3

	Field drawBackground:Bool = True
	Field red:Int = 255
	Field green:Int = 255
	Field blue:Int = 255
	Field image:GameImage = Null
	Field imageFrame:Int = 0
	Field imageMode:Int = IMAGE_NORMAL
	Field imageAlignX:Float = 0
	Field imageAlignY:Float = 0
	Field hoverImage:GameImage = Null
	Field hoverImageFrame:Int = 0
	Field hoverImageMode:Int = IMAGE_NORMAL
	Field hoverImageAlignX:Float = 0
	Field hoverImageAlignY:Float = 0
	Field downImage:GameImage = Null
	Field downImageFrame:Int = 0
	Field downImageMode:Int = IMAGE_NORMAL
	Field downImageAlignX:Float = 0
	Field downImageAlignY:Float = 0
End

Class Panel Extends Component
	Method New(parent:Component)
		Super.New(parent)
	End
End

Class Window Extends Component Implements MouseListener, MouseMotionListener
Private
	Field contentPane:Panel
	Field titlePane:Panel
	Field buttonPane:Panel

	Field closeButton:WindowButtonPanelButton

	Field titleHeight:Int = 22
	Field buttonWidth:Int = 15

	' note: a window can be all three of these states at once!
	' priority is: minimised, maximised, shaded
	Field maximised:Bool = False
	Field minimised:Bool = False
	Field shaded:Bool = False
	Field dragX#, dragY#, originalX#, originalY#
	Field dragging:Bool = False

	Field normalX#, normalY#, normalWidth#, normalHeight#

	Method CreateButtonPane:Void()
		buttonPane = New Panel(Self)
		buttonPane.w = buttonWidth*3
		buttonPane.StyleNormal.drawBackground = False
		'closeButton = New WindowButtonPanelButton(buttonPane, WindowButtonPanelButton.CLOSE_BUTTON)
		'closeButton.StyleNormal.red = 255
		'closeButton.StyleNormal.green = 255
		'closeButton.StyleNormal.blue = 255
		'closeButton.SetBounds(0, 0, buttonWidth, buttonWidth)
	End

	Method CreateContentPane:Void()
		contentPane = New Panel(Self)
		contentPane.StyleNormal.drawBackground = False
	End

	Method CreateTitlePane:Void()
		titlePane = New Panel(Self)
		titlePane.StyleNormal.drawBackground = False
		titlePane.mouseAdapter = Self
		titlePane.mouseMotionAdapter = Self
	End
Public
	Method ContentPane:Panel() Property
		Return contentPane
	End

	Method ContentPane:Void(contentPane:Panel) Property
		If self.contentPane <> Null Then self.contentPane.Dispose()
		Self.contentPane = contentPane
	End

	Method TitlePane:Panel() Property
		Return titlePane
	End

	Method ButtonPane:Panel() Property
		Return buttonPane
	End

	Method Maximised:Void(maximised:Bool) Property
		StoreWindowSize()
		Self.maximised = maximised
		UpdateWindowSize()
	End

	Method Maximised:Bool() Property
		Return maximised
	End

	Method Minimised:Void(minimised:Bool) Property
		StoreWindowSize()
		Self.minimised = minimised
		UpdateWindowSize()
	End

	Method Minimised:Bool() Property
		Return minimised
	End

	Method Shaded:Void(shaded:Bool) Property
		StoreWindowSize()
		Self.shaded = shaded
		UpdateWindowSize()
	End

	Method Shaded:Bool() Property
		Return shaded
	End

	Method StoreWindowSize:Void()
		If maximised Or minimised Then Return
		normalX = x
		normalY = y
		If Not shaded Then
			normalWidth = w
			normalHeight = h
		End
	End

	Method UpdateWindowSize:Void()
		If Not maximised And Not minimised And Not shaded Then
			SetBounds(normalX, normalY, normalWidth, normalHeight)
		ElseIf minimised Then
			SetBounds(0, 0, 50, titleHeight)
		ElseIf maximised Then
			SetBounds(0, 0, parent.w, parent.h)
		ElseIf shaded Then
			SetBounds(normalX, normalY, normalWidth, titleHeight)
		End
	End

	Method New(parent:Component)
		Super.New(parent)
		CreateButtonPane()
		CreateContentPane()
		CreateTitlePane()
	End

	Method Layout:Void()
		If minimised Or shaded Then
			If contentPane <> Null Then contentPane.visible = False
		Else
			If contentPane <> Null Then
				contentPane.visible = True
				contentPane.SetBounds(4, titleHeight, w-8, h-titleHeight-4)
			End
		End
		buttonPane.SetBounds(w-buttonPane.w-4, 0, buttonPane.w, titleHeight)
		titlePane.SetBounds(4, 0, buttonPane.x-4, titleHeight)
	End

	Method MousePressed:Void(x#, y#, button%, absoluteX#, absoluteY#)
		If dragging Then Return
		If maximised Or minimised Then Return
		dragging = True
		dragX = absoluteX
		dragY = absoluteY
		originalX = Self.x
		originalY = Self.y
	End

	Method MouseReleased:Void(x#, y#, button%, absoluteX#, absoluteY#)
		dragging = False
	End

	Method MouseDragged:Void(x#, y#, button%, absoluteX#, absoluteY#)
		If maximised Or minimised Then dragging = False
		If Not dragging Then Return
		Local dx# = absoluteX-dragX, dy# = absoluteY-dragY
		Local newX# = originalX + dx, newY# = originalY + dy

		If Desktop(parent) <> Null And Desktop(parent).restrictWindows Then
			If newX + w > parent.w Then newX = parent.w - w
			If newY + h > parent.h Then newY = parent.h - h
			If newX < 0 Then newX = 0
			If newY < 0 Then newY = 0
		End
		SetLocation(newX, newY)
	End

	Method MouseClicked:Void(x#, y#, button%, absoluteX#, absoluteY#)
	End

	Method MouseEntered:Void(x#, y#, exitedComp:Component, absoluteX#, absoluteY#)
	End

	Method MouseExited:Void(x#, y#, enteredComp:Component, absoluteX#, absoluteY#)
	End

	Method MouseMoved:Void(x#, y#, absoluteX#, absoluteY#)
	End
End

Class WindowButtonPanelButton Extends Button
	Const CLOSE_BUTTON% = 0
	Const MAXIMISE_BUTTON% = 1
	Const MINIMISE_BUTTON% = 2
	Const SHADE_BUTTON% = 3
	Field buttonType%

	Method New(parent:Component, buttonType%)
		Super.New(parent)
		Self.buttonType = buttonType
	End

	Method ButtonClicked:Void()
		Local window:Window = Window(parent)
		AssertNotNull(window, "WindowButtonPanelButton.ButtonClicked: window was null")
		Select buttonType
			Case CLOSE_BUTTON
				window.Dispose()
		End
	End
End

Class Label Extends Component
Private
	Field text:String
	Field textRed%, textGreen%, textBlue%
	Field textXOffset# = 0
	Field textYOffset# = 0
	Field textXAlign# = 0
	Field textYAlign# = 0

Public

	Method Text:Void(txt:String, xAlign:Float, yAlign:Float) Property
		text = txt
		textXAlign = xAlign
		textYAlign = yAlign
	End

	Method New(parent:Component)
		Super.New(parent)
	End

	Method DrawComponent:Void()
		Super.DrawComponent()
		If text.Length > 0
			DrawText text, w*textXAlign+textXOffset, h*textYAlign+textYOffset, textXAlign, textYAlign
		End
	End
End

Class Button Extends Label Implements MouseListener
Private
	Field styleSelected:ComponentStyle = Null

Public
	Field selected:Bool
	Field toggle:Bool
	Field radioGroup:RadioGroup
	Field radioValue$

	Method New(parent:Component)
		Super.New(parent)
		Self.forwardAction = FindActionTarget()
		mouseAdapter = Self
	End

	Method New(parent:Component, image:GameImage)
		Super.New(parent)
		Self.forwardAction = FindActionTarget()
		mouseAdapter = Self
		Self.StyleNormal.image = image
		Self.StyleNormal.drawBackground = False
		Self.SetSize(image.w, image.h)
		If image.midhandled
			image.MidHandle(False)
			Self.midHandle = False
		End
	End

	Method New(parent:Component, image:GameImage, clickImage:GameImage)
		Super.New(parent)
		Self.forwardAction = FindActionTarget()
		mouseAdapter = Self
		Self.StyleNormal.image = image
		Self.styleNormal.downImage = clickImage
		Self.StyleNormal.drawBackground = False
		Self.SetSize(image.w, image.h)
		If image.midhandled
			image.MidHandle(False)
			Self.midHandle = False
		End
	End

	Method New(parent:Component, forwardAction:Component)
		Super.New(parent)
		Self.forwardAction = forwardAction
		mouseAdapter = Self
	End

	Method StyleSelected:ComponentStyle() Property
		If styleSelected = Null Then styleSelected = New ComponentStyle
		Return styleSelected
	End
	Method StyleSelected:Void(style:ComponentStyle) Property
		styleSelected = style
	End

	Method GetStyle:ComponentStyle(name$)
		If name = "selected" Then Return styleSelected
		Return Super.GetStyle(name)
	End

	Method SetStyle:Void(name$, style:ComponentStyle)
		If name = "selected" Then
			styleSelected = style
		Else
			Super.GetStyle(name)
		End
	End

	Method GetCurrentStyle:ComponentStyle()
		If selected And styleSelected <> Null Then Return styleSelected
		Return Super.GetCurrentStyle()
	End

	Method MouseClicked:Void(x#, y#, button%, absoluteX#, absoluteY#)
		' is it a radio button?
		If radioGroup <> Null Then
			radioGroup.SelectButton(Self)
		' is it a toggle button?
		ElseIf toggle Then
			selected = Not selected
		End
		ActionPerformed(Self, ACTION_CLICKED)
	End

	Method MousePressed:Void(x#, y#, button%, absoluteX#, absoluteY#)
	End

	Method MouseReleased:Void(x#, y#, button%, absoluteX#, absoluteY#)
	End

	Method MouseEntered:Void(x#, y#, exitedComp:Component, absoluteX#, absoluteY#)
	End

	Method MouseExited:Void(x#, y#, enteredComp:Component, absoluteX#, absoluteY#)
	End
End

Class RadioGroup
	Field buttons:ArrayList<Button> = New ArrayList<Button>
	Field currentValue$

	Method SelectButton:String(button:Button)
		For Local b:Button = EachIn buttons
			b.selected = (b = button)
			If b.selected Then
				currentValue = b.radioValue
			End
		Next
		Return currentValue
	End

	Method SelectValue:Button(value$)
		Local rv:Button = Null
		For Local b:Button = EachIn buttons
			b.selected = (b.radioValue = value)
			If b.selected Then
				currentValue = value
				rv = b
			End
		Next
		Return rv
	End

	Method AddButton:Void(button:Button, value$)
		button.radioValue = value
		button.radioGroup = Self
		buttons.Add(button)
	End

	Method RemoveButton:Void(button:Button)
		button.radioValue = ""
		button.radioGroup = Null
		buttons.Remove(button)
	End
End

Class Slider Extends Component Implements MouseListener, MouseMotionListener
	Const SLIDER_HORIZONTAL% = 0
	Const SLIDER_VERTICAL% = 1
	Const SLIDER_DIRECTION_TL_TO_BR% = 0 ' min is top or left, max is bottom or right
	Const SLIDER_DIRECTION_BR_TO_TL% = 1 ' min is bottom or right, max is top or left
Private
	Field buttonUpLeft:Button ' the button used for up and left
	Field buttonDownRight:Button ' the button used for down and right
	Field handle:Label
	Field showButtons:Bool
	Field orientation:Int = SLIDER_HORIZONTAL
	Field direction:Int = SLIDER_DIRECTION_TL_TO_BR

	Field dragX%, dragY%, originalX%, originalY%
	Field dragging:Bool = False

	Field styleLeftButton:ComponentStyle
	Field styleRightButton:ComponentStyle
	Field styleTopButton:ComponentStyle
	Field styleBottomButton:ComponentStyle
	Field styleHorizontalHandle:ComponentStyle
	Field styleVerticalHandle:ComponentStyle

Public
	Field minValue% = 0
	Field maxValue% = 100
	Field value% = 50
	Field tickInterval% = 10
	Field handleMargin% = 10
	Field handleSize% = 10
	Field buttonSize% = 15
	Field snapToTicks:Bool = True

	Method New(parent:Component)
		Super.New(parent)
		buttonUpLeft = New Button(Self, Self)
		buttonDownRight = New Button(Self, Self)
		handle = New Label(Self)
		handle.mouseAdapter = Self
		handle.mouseMotionAdapter = Self
		buttonUpLeft.visible = False
		buttonDownRight.visible = False
	End

	Method GetStyle:ComponentStyle(name$)
		If name = "leftButton" Then
			Return styleLeftButton
		ElseIf name = "rightButton" Then
			Return styleRightButton
		ElseIf name = "topButton" Then
			Return styleTopButton
		ElseIf name = "bottomButton" Then
			Return styleBottomButton
		ElseIf name = "horizontalHandle" Then
			Return styleHorizontalHandle
		ElseIf name = "verticalHandle" Then
			Return styleVerticalHandle
		End
		Return Super.GetStyle(name)
	End

	Method SetStyle:Void(name$, style:ComponentStyle)
		If name = "leftButton" Then
			styleLeftButton = style
		ElseIf name = "rightButton" Then
			styleRightButton = style
		ElseIf name = "topButton" Then
			styleTopButton = style
		ElseIf name = "bottomButton" Then
			styleBottomButton = style
		ElseIf name = "horizontalHandle" Then
			styleHorizontalHandle = style
		ElseIf name = "verticalHandle" Then
			styleVerticalHandle = style
		Else
			Super.SetStyle(name, style)
		End
		UpdateStyles()
	End

	Method ShowButtons:Bool() Property
		Return showButtons
	End

	Method ShowButtons:Void(showButtons:Bool) Property
		If showButtons <> Self.showButtons Then
			Self.showButtons = showButtons
			Layout()
		End
		Self.showButtons = showButtons
	End

	Method Orientation:Int() Property
		Return orientation
	End

	Method Orientation:Void(orientation:Int) Property
		If Self.orientation <> orientation Then
			Self.orientation = orientation
			UpdateStyles()
			Layout()
		End
		Self.orientation = orientation
	End

	Method Direction:Int() Property
		Return direction
	End

	Method Direction:Void(direction:Int) Property
		If Self.direction <> direction Then
			Self.direction = direction
			Layout()
		End
		Self.direction = direction
	End

	Method DrawComponent:Void()
		Super.DrawComponent()
		' TODO: render groove and ticks, etc.
	End

	Method UpdateStyles:Void()
		If orientation = SLIDER_HORIZONTAL Then
			buttonUpLeft.StyleNormal = styleLeftButton
			buttonDownRight.StyleNormal = styleRightButton
			handle.StyleNormal = styleHorizontalHandle
		Else
			buttonUpLeft.StyleNormal = styleTopButton
			buttonDownRight.StyleNormal = styleBottomButton
			handle.StyleNormal = styleVerticalHandle
		End
	End

	' TODO: adjust layout using xml offsets rather than hardcoded
	Method Layout:Void()
		If showButtons Then
			If orientation = SLIDER_HORIZONTAL Then
				buttonUpLeft.SetBounds(0, 0, buttonSize, Self.h)
				buttonDownRight.SetBounds(Self.w - buttonSize, 0, buttonSize, Self.h)
			Else
				buttonUpLeft.SetBounds(0, 0, Self.w, buttonSize)
				buttonDownRight.SetBounds(0, Self.h - buttonSize, Self.w, buttonSize)
			End
			buttonUpLeft.visible = True
			buttonDownRight.visible = True
		Else
			buttonUpLeft.visible = False
			buttonDownRight.visible = False
		End
		Local startVal% = buttonSize+handleMargin
		Local endVal% = -buttonSize-handleMargin
		Local fraction# = Float(value-minValue)/Float(maxValue-minValue)
		Local currentVal%
		If orientation = SLIDER_HORIZONTAL Then
			endVal += Self.w
			currentVal = startVal + (endVal - startVal) * fraction
			handle.SetBounds(currentVal-handleSize/2, 0, handleSize, Self.h)
		Else
			endVal += Self.h
			currentVal = startVal + (endVal - startVal) * fraction
			handle.SetBounds(0, currentVal-handleSize/2, Self.w, handleSize)
		End
	End

	Method HandleDrag:Int(mx%, my%)
		Local pos%, topLeft% = handleMargin, bottomRight% = -handleMargin
		If showButtons Then
			topLeft += buttonSize
			bottomRight -= buttonSize
		End
		If orientation = SLIDER_HORIZONTAL Then
			bottomRight += w
			pos = Min(Max(topLeft, mx), bottomRight)
		Else
			bottomRight += h
			pos = Min(Max(topLeft, my), bottomRight)
		End
		Local fraction# = Float(pos-topLeft) / Float(bottomRight-topLeft)
		If direction = SLIDER_DIRECTION_BR_TO_TL Then fraction = 1-fraction

		Local oldValue% = value
		value = SnapToValue(minValue + (maxValue - minValue)*fraction)

		' if it changed, update the layout and fire an event
		If value <> oldValue Then
			Local target:ActionListener = forwardAction
			If target = Null Then target = FindActionTarget()
			If target <> Null Then
				Layout()
				target.ActionPerformed(Self, ACTION_VALUE_CHANGED)
			EndIf
		End
	End

	Method ActionPerformed:Void(source:Component, action:String)
		If source = buttonUpLeft And action = ACTION_CLICKED Then
			If direction = SLIDER_DIRECTION_TL_TO_BR Then
				AdjustValue(-1)
			Else
				AdjustValue(1)
			End
		ElseIf source = buttonDownRight And action = ACTION_CLICKED Then
			If direction = SLIDER_DIRECTION_TL_TO_BR Then
				AdjustValue(1)
			Else
				AdjustValue(-1)
			End
		End
	End

	Method SnapToValue:Int(val%)
		If val < minValue Then
			val = minValue
			Return val
		End
		If val > maxValue Then
			val = maxValue
			Return val
		End
		If val Mod tickInterval = 0 Then Return val
		If val Mod tickInterval < tickInterval / 2 Then
			val -= val Mod tickInterval
		Else
			val -= val Mod tickInterval
			val += tickInterval
		End
		Return val
	End

	Method AdjustValue:Bool(amount%)
		If amount = 0 Then Return
		Local oldValue% = value

		' snap if we must
		If value Mod tickInterval > 0 Then
			If amount < 0 Then
				value += tickInterval - (value Mod tickInterval)
			Else
				value -= value Mod tickInterval
			End
		End

		' adjust it
		value += amount * tickInterval

		' check that it's in range
		If value < minValue Then value = minValue
		If value > maxValue Then value = maxValue

		' if it changed, update the layout and fire an event
		If value <> oldValue Then
			Local target:ActionListener = forwardAction
			If target = Null Then target = FindActionTarget()
			If target <> Null Then
				Layout()
				target.ActionPerformed(Self, ACTION_VALUE_CHANGED)
			EndIf
		End
		Return value <> oldValue
	End

	Method MousePressed:Void(x#, y#, button%, absoluteX#, absoluteY#)
		If dragging Then Return
		dragging = True
		HandleDrag(handle.x + x, handle.y + y)
	End

	Method MouseReleased:Void(x#, y#, button%, absoluteX#, absoluteY#)
		dragging = False
		HandleDrag(handle.x + x, handle.y + y)
	End

	Method MouseDragged:Void(x#, y#, button%, absoluteX#, absoluteY#)
		If Not dragging Then Return
		HandleDrag(handle.x + x, handle.y + y)
	End

	Method MouseClicked:Void(x#, y#, button%, absoluteX#, absoluteY#)
	End

	Method MouseEntered:Void(x#, y#, exitedComp:Component, absoluteX#, absoluteY#)
	End

	Method MouseExited:Void(x#, y#, enteredComp:Component, absoluteX#, absoluteY#)
	End

	Method MouseMoved:Void(x#, y#, absoluteX#, absoluteY#)
	End
End

Import mojo
Import diddy

Const ACTION_CLICKED$ = "clicked"
Const ACTION_VALUE_CHANGED$ = "changed"

Class Rectangle
	Field x#, y#, w#, h#
	Field empty? = False

	Method New(x#, y#, w#, h#)
		Set(x, y, w, h)
	End

	Method Set:Void(x#, y#, w#, h#)
		Self.x = x
		Self.y = y
		Self.w = w
		Self.h = h
		Self.empty = Self.w <= 0 Or Self.h <= 0
	End

	Method Set:Void(srcRect:Rectangle)
		Self.x = srcRect.x
		Self.y = srcRect.y
		Self.w = srcRect.w
		Self.h = srcRect.h
		Self.empty = Self.w <= 0 Or Self.h <= 0
	End

	Method Clear:Void()
		Self.w = -1
		Self.h = -1
		Self.empty = True
	End

	Method Intersect:Void(x#, y#, w#, h#)
		If x >= Self.x + Self.w Or y >= Self.y + Self.h Or Self.x >= x + w Or Self.y >= y + h Then
			Clear()
			Return
		End

		Local r% = Self.x + Self.w
		Local b% = Self.y + Self.h
		If Self.x < x Then Self.x = x
		If Self.y < y Then Self.y = y
		If r > x + w Then r = x + w
		If b > y + h Then b = y + h
		Self.w = r - Self.x
		Self.h = b - Self.y
	End
End

Class GUI Implements ActionListener
	Field desktop:Desktop
	Field scissors:Rectangle[] = New Rectangle[128]
	Field scissorDepth:Int = 0

	Field mouseDown:Bool[3]
	Field mouseDownX:Float[3]
	Field mouseDownY:Float[3]
	Field mouseDownComponent:Component[3]

	Field mouseLastX:Float
	Field mouseLastY:Float
	Field mouseLastComponent:Component
	Field mouseThisX:Float
	Field mouseThisY:Float
	Field mouseThisComponent:Component

	Method New()
		desktop = New Desktop(Self)
		desktop.SetBounds(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)
		For Local i% = 0 Until scissors.Length
			scissors[i] = New Rectangle
		Next
	End

	Method PushScissor:Void(x#, y#, w#, h#)
		' don't use assert, for speed on android (one less method call)
		If scissorDepth >= scissors.Length Then Error("GUI.PushScissor: Out of space for scissors.")
		If scissorDepth = 0 Then
			scissors[0].Set(x, y, w, h)
		Else
			scissors[scissorDepth].Set(scissors[scissorDepth-1])
			scissors[scissorDepth].Intersect(x, y, w, h)
		End
		scissorDepth += 1
		UpdateScissor()
	End

	Method PopScissor:Void()
		If scissorDepth > 0 Then
			scissorDepth -= 1
			scissors[scissorDepth].Clear()
		End
		UpdateScissor()
	End

	Method UpdateScissor:Void()
		If scissorDepth > 0 Then
			If Not EmptyScissor() Then
				SetScissor(scissors[scissorDepth-1].x * SCREENX_RATIO, scissors[scissorDepth-1].y * SCREENY_RATIO, scissors[scissorDepth-1].w * SCREENX_RATIO, scissors[scissorDepth-1].h * SCREENY_RATIO)
			End
		Else
			SetScissor(0, 0, DEVICE_WIDTH, DEVICE_HEIGHT)
		End
	End

	Method EmptyScissor:Bool()
		If scissorDepth <= 0 Then Return False
		Return scissors[scissorDepth-1].empty
	End

	Method Draw()
		desktop.Draw(Self)
		scissorDepth = 0
		SetScissor(0, 0, DEVICE_WIDTH, DEVICE_HEIGHT)
	End

	' TODO: check Z-order
	Method ComponentAtPoint:Component(x#, y#, parent:Component=Null)
		' if no parent, it's the desktop
		If parent = Null Then parent = desktop
		' if the mouse is outside the component, return null
		If parent.midHandle
			x += parent.w2
			y += parent.h2
		EndIf

		If x<0 Or y<0 Or x >= parent.w Or y >= parent.h Then Return Null

		' check if it's inside a child
		Local rv:Component = Null
		For Local i% = 0 Until parent.children.Size
			Local c:Component = parent.children.Get(i)
			rv = ComponentAtPoint(x-c.x, y-c.y, c)

			If rv <> Null Then Return rv
		Next
		' not inside a child, so it's this one
		Return parent
	End

	Method GetAbsoluteX:Float(comp:Component)
		Local rv# = comp.x
		While comp.parent <> Null
			comp = comp.parent
			rv += comp.x
		Wend
		Return rv
	End

	Method GetAbsoluteY:Float(comp:Component)
		Local rv# = comp.y
		While comp.parent <> Null
			comp = comp.parent
			rv += comp.y
		Wend
		Return rv
	End

	Method Update:Void()
		mouseLastX = mouseThisX
		mouseLastY = mouseThisY
		mouseLastComponent = mouseThisComponent
		mouseThisX = game.mouseX
		mouseThisY = game.mouseY
		mouseThisComponent = ComponentAtPoint(mouseThisX, mouseThisY)
		DoMouse(MOUSE_LEFT)
		DoMouse(MOUSE_MIDDLE)
		DoMouse(MOUSE_RIGHT)
	End

	Method DoMouse:Void(button%)
		Local absX#, absY#
		If MouseHit(button) Then
			mouseDown[button] = True
			mouseDownX[button] = mouseThisX
			mouseDownY[button] = mouseThisY
			mouseDownComponent[button] = mouseThisComponent

			' fire pressed on mouseThisComponent
			If mouseThisComponent.mouseAdapter <> Null Then
				absX = GetAbsoluteX(mouseThisComponent)
				absY = GetAbsoluteY(mouseThisComponent)
				mouseThisComponent.mouseAdapter.MousePressed(mouseThisX-absX, mouseThisY-absY, button, mouseThisX, mouseThisY)
			End

			' set mouseDown
			mouseThisComponent.mouseDown = True

		ElseIf mouseDown[button] Then
			' if we released the button
			If Not MouseDown(button) Then
				mouseDown[button] = False
				Local comp:Component = mouseDownComponent[button]
				mouseDownComponent[button] = Null

				' fire mouse released on comp
				If comp.mouseAdapter <> Null Then
					absX = GetAbsoluteX(comp)
					absY = GetAbsoluteY(comp)
					comp.mouseAdapter.MouseReleased(mouseThisX-absX, mouseThisY-absY, button, mouseThisX, mouseThisY)
				End

				' clear mouseDown
				comp.mouseDown = False

				' if we released on the same component, fire mouse clicked
				If mouseThisComponent = comp Then
					If comp.mouseAdapter <> Null Then comp.mouseAdapter.MouseClicked(mouseThisX-absX, mouseThisY-absY, button, mouseThisX, mouseThisY)
				End

			ElseIf mouseLastX <> mouseThisX Or mouseLastY <> mouseThisY Then
				' fire mouse dragged on mouseDownComponent
				If mouseDownComponent[button].mouseMotionAdapter <> Null Then
					absX = GetAbsoluteX(mouseDownComponent[button])
					absY = GetAbsoluteY(mouseDownComponent[button])
					mouseDownComponent[button].mouseMotionAdapter.MouseDragged(mouseThisX-absX, mouseThisY-absY, button, mouseThisX, mouseThisY)
				End

				' if the component changed, fire exit/enter
				If mouseThisComponent <> mouseLastComponent Then
					' fire mouse exited on mouseLastComponent
					If mouseLastComponent.mouseAdapter <> Null Then
						absX = GetAbsoluteX(mouseLastComponent)
						absY = GetAbsoluteY(mouseLastComponent)
						mouseLastComponent.mouseAdapter.MouseExited(mouseThisX-absX, mouseThisY-absY, mouseThisComponent, mouseThisX, mouseThisY)
					End

					' clear mouseHover
					mouseLastComponent.mouseHover = False

					' fire mouse entered on mouseThisComponent
					If mouseThisComponent.mouseAdapter <> Null Then
						absX = GetAbsoluteX(mouseThisComponent)
						absY = GetAbsoluteY(mouseThisComponent)
						mouseThisComponent.mouseAdapter.MouseEntered(mouseThisX-absX, mouseThisY-absY, mouseLastComponent, mouseThisX, mouseThisY)
					End

					' set the STATE_HOVER bit
					mouseThisComponent.mouseHover = True
				End
			End
		Else
			If mouseLastX <> mouseThisX Or mouseLastY <> mouseThisY Then
				' fire mouse moved on mouseThisComponent
				If mouseThisComponent <> Null And mouseThisComponent.mouseMotionAdapter <> Null Then
					absX = GetAbsoluteX(mouseThisComponent)
					absY = GetAbsoluteY(mouseThisComponent)
					mouseThisComponent.mouseMotionAdapter.MouseMoved(mouseThisX-absX, mouseThisY-absY, mouseThisX, absY)
				End

				' if the component changed, fire exit/enter
				If mouseThisComponent <> mouseLastComponent Then
					' fire mouse exited on mouseLastComponent
					If mouseLastComponent <> Null Then
						If mouseLastComponent.mouseAdapter <> Null Then
							absX = GetAbsoluteX(mouseLastComponent)
							absY = GetAbsoluteY(mouseLastComponent)
							mouseLastComponent.mouseAdapter.MouseExited(mouseThisX-absX, mouseThisY-absY, mouseThisComponent, mouseThisX, mouseThisY)
						End

						' clear mouseHover
						mouseLastComponent.mouseHover = False
					End

					' fire mouse entered on mouseThisComponent
					If mouseThisComponent <> Null Then
						If mouseThisComponent.mouseAdapter <> Null Then
							absX = GetAbsoluteX(mouseThisComponent)
							absY = GetAbsoluteY(mouseThisComponent)
							mouseThisComponent.mouseAdapter.MouseEntered(mouseThisX-absX, mouseThisY-absY, mouseLastComponent, mouseThisX, mouseThisY)
						End
						' set mouseHover
						mouseThisComponent.mouseHover = True
					End
				End
			End
		End
	End

	Method ActionPerformed:Void(source:Component, action:String)
	End
End

Interface ActionListener
	Method ActionPerformed:Void(source:Component, action:String)
End

Interface MouseListener
	Method MousePressed:Void(x#, y#, button%, absoluteX#, absoluteY#)
	Method MouseReleased:Void(x#, y#, button%, absoluteX#, absoluteY#)
	Method MouseClicked:Void(x#, y#, button%, absoluteX#, absoluteY#)
	Method MouseEntered:Void(x#, y#, exitedComp:Component, absoluteX#, absoluteY#)
	Method MouseExited:Void(x#, y#, enteredComp:Component, absoluteX#, absoluteY#)
End

Class AbstractMouseAdapter Implements MouseListener Abstract
	Method MousePressed:Void(x#, y#, button%, absoluteX#, absoluteY#)
	End
	Method MouseReleased:Void(x#, y#, button%, absoluteX#, absoluteY#)
	End
	Method MouseClicked:Void(x#, y#, button%, absoluteX#, absoluteY#)
	End
	Method MouseEntered:Void(x#, y#, exitedComp:Component, absoluteX#, absoluteY#)
	End
	Method MouseExited:Void(x#, y#, enteredComp:Component, absoluteX#, absoluteY#)
	End
End

Interface MouseMotionListener
	Method MouseMoved:Void(x#, y#, absoluteX#, absoluteY#)
	Method MouseDragged:Void(x#, y#, button%, absoluteX#, absoluteY#)
End

Class AbstractMouseMotionAdapter Implements MouseMotionListener Abstract
	Method MouseMoved:Void(x#, y#, absoluteX#, absoluteY#)
	End
	Method MouseDragged:Void(x#, y#, button%, absoluteX#, absoluteY#)
	End
End

Class Desktop Extends Component
	Field restrictWindows:Bool = True
	Field parentGUI:GUI
	Method New(parentGUI:GUI)
		Super.New(Null)
		Self.parentGUI = parentGUI
	End

	Method ActionPerformed:Void(source:Component, action:String)
		parentGUI.ActionPerformed(source, action)
	End
End

Class Component Implements ActionListener
Private
	Field midHandle:Bool = False
	Field alpha# = 1
	Field children:ArrayList<Component> = New ArrayList<Component>
	Field mouseAdapter:MouseListener
	Field mouseMotionAdapter:MouseMotionListener
	Field forwardAction:ActionListener = Null
	Field mouseHover:Bool = False
	Field mouseDown:Bool = False

	Field styleNormal:ComponentStyle = Null

Public
	Field parent:Component

	Field x#, y#
	Field w#, h#
	Field w2#, h2#
	Field visible:Bool = True

	Method MouseAdapter:Void(mouseAdapter:MouseListener) Property
		Self.mouseAdapter = mouseAdapter
	End
	Method MouseAdapter:MouseListener() Property
		Return Self.mouseAdapter
	End
	Method MouseMotionAdapter:Void(mouseMotionAdapter:MouseMotionListener) Property
		Self.mouseMotionAdapter = mouseMotionAdapter
	End
	Method MouseMotionAdapter:MouseMotionListener() Property
		Return Self.mouseMotionAdapter
	End
	Method MidHandle:Void(mid:Bool) Property
		Self.midHandle = mid
	End
	Method MidHandle:Bool() Property
		Return Self.midHandle
	End

	Method StyleNormal:ComponentStyle() Property
		If styleNormal = Null Then styleNormal = New ComponentStyle
		Return styleNormal
	End
	Method StyleNormal:Void(style:ComponentStyle) Property
		AssertNotNull(style, "StyleNormal may not be null.")
		styleNormal = style
	End

	Method GetStyle:ComponentStyle(name$)
		If name = "normal" Then Return styleNormal
		Return Null
	End

	Method SetStyle:Void(name$, style:ComponentStyle)
		If name = "normal" Then styleNormal = style
	End

	Method New(parent:Component)
		styleNormal = New ComponentStyle
		' if this isn't the desktop, it must have a parent
		If Not Desktop(Self) Then
			AssertNotNull(parent, "Components must have a parent.")
			Self.parent = parent
			parent.children.Add(Self)
		Else
			styleNormal.drawBackground = False
		End
		AddNotify()
	End

	Method Alpha#() Property
		Return alpha
	End

	Method Alpha:Void(alpha#) Property
		Self.alpha = alpha
		If Self.alpha < 0 Then Self.alpha = 0
		If Self.alpha > 1 Then Self.alpha = 1
	End

	Method SetBackground:Void(red#, green#, blue#)
		If red < 0 Then red = 0
		If red > 255 Then red = 255
		If green < 0 Then green = 0
		If green > 255 Then green = 255
		If blue < 0 Then blue = 0
		If blue > 255 Then blue = 255
		styleNormal.red = red
		styleNormal.green = green
		styleNormal.blue = blue
		styleNormal.drawBackground = True
	End

	Method SetBackground:Void(drawBackground:Bool)
		styleNormal.drawBackground = drawBackground
	End

	Method SetLocation:Void(x#, y#)
		Self.x = x
		Self.y = y
		Layout()
	End

	Method SetSize:Void(w#, h#)
		Self.w = w
		Self.h = h
		Self.w2 = w / 2
		Self.h2 = h / 2
		Layout()
	End

	Method SetBounds:Void(x#, y#, w#, h#)
		Self.x = x
		Self.y = y
		Self.w = w
		Self.h = h
		Layout()
	End

	Method Draw:Void(parentGui:GUI, alpha# = 1, absx# = 0, absy# = 0)
		If visible Then
			parentGui.PushScissor(absx, absy, w, h)
			If Not parentGui.EmptyScissor() Then
				SetAlpha(alpha)
				DrawComponent()
				DrawChildren(parentGui, alpha, absx, absy)
			End
			parentGui.PopScissor()
		End
	End

	Method DrawChildren:Void(parentGui:GUI, alpha# = 1, absx#, absy#)
		For Local c:Component = EachIn children
			PushMatrix()
			Translate(c.x, c.y)
			If Not c.midHandle
				c.Draw(parentGui, c.alpha * alpha, absx + c.x, absy + c.y)
			Else
				c.Draw(parentGui, c.alpha * alpha, absx + c.x - c.w2, absy + c.y - c.h2)
			End
			PopMatrix()
		Next
	End

	Method DrawComponent:Void()
		Local style:ComponentStyle = GetCurrentStyle()
		If style <> Null Then
			' background colour first
			If style.drawBackground Then
				SetColor(style.red, style.green, style.blue)
				SetAlpha(alpha)
				DrawRect(0, 0, w, h)
			End

			' image next, priority = down, hover, normal
			If mouseDown And style.downImage <> Null Then
				SetColor(255,255,255)
				SetAlpha(alpha)
				If style.downImageMode = ComponentStyle.IMAGE_GRID Then
					style.downImage.DrawGrid(0, 0, w, h, style.downImageFrame)
				ElseIf style.downImageMode = ComponentStyle.IMAGE_NORMAL Then
					style.downImage.Draw(0, 0, 0, 1, 1, style.downImageFrame)
				End
			ElseIf mouseHover And style.hoverImage <> Null Then
				SetColor(255,255,255)
				SetAlpha(alpha)
				If style.hoverImageMode = ComponentStyle.IMAGE_GRID Then
					style.hoverImage.DrawGrid(0, 0, w, h, style.hoverImageFrame)
				ElseIf style.hoverImageMode = ComponentStyle.IMAGE_NORMAL Then
					style.hoverImage.Draw(0, 0, 0, 1, 1, style.hoverImageFrame)
				End
			ElseIf style.image <> Null Then
				SetColor(255,255,255)
				SetAlpha(alpha)
				If style.imageMode = ComponentStyle.IMAGE_GRID Then
					style.image.DrawGrid(0, 0, w, h, style.imageFrame)
				ElseIf style.imageMode = ComponentStyle.IMAGE_NORMAL Then
					style.image.Draw(0, 0, 0, 1, 1, style.imageFrame)
				End
			End

			' reset stuff
			SetColor(255,255,255)
			SetAlpha(1)
		End
	End

	Method GetCurrentStyle:ComponentStyle()
		Return styleNormal
	End

	Method Dispose:Void(recursing:Bool = False)
		' we do an empty check first to save creating an enumerator object
		If Not children.IsEmpty() Then
			Local enum:AbstractEnumerator<Component> = children.Enumerator()
			While enum.HasNext()
				Local c:Component = enum.NextObject()
				c.Dispose(True)
				enum.Remove()
			End
		End
		DisposeNotify()
		Local p:Component = Self.parent
		Self.parent = Null
		If Not recursing Then p.children.Remove(Self)
	End

	Method AddNotify:Void()
	End

	Method DisposeNotify:Void()
	End

	Method Layout:Void()
	End

	Method ActionPerformed:Void(source:Component, action:String)
		If forwardAction <> Null Then
			forwardAction.ActionPerformed(source, action)
		End
	End

	Method FindActionTarget:ActionListener()
		' if this is a window or desktop, return itself
		If Window(Self) <> Null Or Desktop(Self) <> Null Then Return Self
		' traverse up the hierarchy and find the closest Window or Desktop to receive the actions
		Local comp:Component = Self
		While Window(Self) = Null And Desktop(Self) = Null And comp.parent <> Null
			comp = comp.parent
		End
		Return comp
	End
End

Class ComponentStyle
	Global IMAGE_NORMAL% = 0
	Global IMAGE_TILE% = 1
	Global IMAGE_STRETCH% = 2
	Global IMAGE_GRID% = 3

	Field drawBackground:Bool = True
	Field red:Int = 255
	Field green:Int = 255
	Field blue:Int = 255
	Field image:GameImage = Null
	Field imageFrame:Int = 0
	Field imageMode:Int = IMAGE_NORMAL
	Field imageAlignX:Float = 0
	Field imageAlignY:Float = 0
	Field hoverImage:GameImage = Null
	Field hoverImageFrame:Int = 0
	Field hoverImageMode:Int = IMAGE_NORMAL
	Field hoverImageAlignX:Float = 0
	Field hoverImageAlignY:Float = 0
	Field downImage:GameImage = Null
	Field downImageFrame:Int = 0
	Field downImageMode:Int = IMAGE_NORMAL
	Field downImageAlignX:Float = 0
	Field downImageAlignY:Float = 0
End

Class Panel Extends Component
	Method New(parent:Component)
		Super.New(parent)
	End
End

Class Window Extends Component Implements MouseListener, MouseMotionListener
Private
	Field contentPane:Panel
	Field titlePane:Panel
	Field buttonPane:Panel

	Field closeButton:WindowButtonPanelButton

	Field titleHeight:Int = 22
	Field buttonWidth:Int = 15

	' note: a window can be all three of these states at once!
	' priority is: minimised, maximised, shaded
	Field maximised:Bool = False
	Field minimised:Bool = False
	Field shaded:Bool = False
	Field dragX#, dragY#, originalX#, originalY#
	Field dragging:Bool = False

	Field normalX#, normalY#, normalWidth#, normalHeight#

	Method CreateButtonPane:Void()
		buttonPane = New Panel(Self)
		buttonPane.w = buttonWidth*3
		buttonPane.StyleNormal.drawBackground = False
		'closeButton = New WindowButtonPanelButton(buttonPane, WindowButtonPanelButton.CLOSE_BUTTON)
		'closeButton.StyleNormal.red = 255
		'closeButton.StyleNormal.green = 255
		'closeButton.StyleNormal.blue = 255
		'closeButton.SetBounds(0, 0, buttonWidth, buttonWidth)
	End

	Method CreateContentPane:Void()
		contentPane = New Panel(Self)
		contentPane.StyleNormal.drawBackground = False
	End

	Method CreateTitlePane:Void()
		titlePane = New Panel(Self)
		titlePane.StyleNormal.drawBackground = False
		titlePane.mouseAdapter = Self
		titlePane.mouseMotionAdapter = Self
	End
Public
	Method ContentPane:Panel() Property
		Return contentPane
	End

	Method ContentPane:Void(contentPane:Panel) Property
		If self.contentPane <> Null Then self.contentPane.Dispose()
		Self.contentPane = contentPane
	End

	Method TitlePane:Panel() Property
		Return titlePane
	End

	Method ButtonPane:Panel() Property
		Return buttonPane
	End

	Method Maximised:Void(maximised:Bool) Property
		StoreWindowSize()
		Self.maximised = maximised
		UpdateWindowSize()
	End

	Method Maximised:Bool() Property
		Return maximised
	End

	Method Minimised:Void(minimised:Bool) Property
		StoreWindowSize()
		Self.minimised = minimised
		UpdateWindowSize()
	End

	Method Minimised:Bool() Property
		Return minimised
	End

	Method Shaded:Void(shaded:Bool) Property
		StoreWindowSize()
		Self.shaded = shaded
		UpdateWindowSize()
	End

	Method Shaded:Bool() Property
		Return shaded
	End

	Method StoreWindowSize:Void()
		If maximised Or minimised Then Return
		normalX = x
		normalY = y
		If Not shaded Then
			normalWidth = w
			normalHeight = h
		End
	End

	Method UpdateWindowSize:Void()
		If Not maximised And Not minimised And Not shaded Then
			SetBounds(normalX, normalY, normalWidth, normalHeight)
		ElseIf minimised Then
			SetBounds(0, 0, 50, titleHeight)
		ElseIf maximised Then
			SetBounds(0, 0, parent.w, parent.h)
		ElseIf shaded Then
			SetBounds(normalX, normalY, normalWidth, titleHeight)
		End
	End

	Method New(parent:Component)
		Super.New(parent)
		CreateButtonPane()
		CreateContentPane()
		CreateTitlePane()
	End

	Method Layout:Void()
		If minimised Or shaded Then
			If contentPane <> Null Then contentPane.visible = False
		Else
			If contentPane <> Null Then
				contentPane.visible = True
				contentPane.SetBounds(4, titleHeight, w-8, h-titleHeight-4)
			End
		End
		buttonPane.SetBounds(w-buttonPane.w-4, 0, buttonPane.w, titleHeight)
		titlePane.SetBounds(4, 0, buttonPane.x-4, titleHeight)
	End

	Method MousePressed:Void(x#, y#, button%, absoluteX#, absoluteY#)
		If dragging Then Return
		If maximised Or minimised Then Return
		dragging = True
		dragX = absoluteX
		dragY = absoluteY
		originalX = Self.x
		originalY = Self.y
	End

	Method MouseReleased:Void(x#, y#, button%, absoluteX#, absoluteY#)
		dragging = False
	End

	Method MouseDragged:Void(x#, y#, button%, absoluteX#, absoluteY#)
		If maximised Or minimised Then dragging = False
		If Not dragging Then Return
		Local dx# = absoluteX-dragX, dy# = absoluteY-dragY
		Local newX# = originalX + dx, newY# = originalY + dy

		If Desktop(parent) <> Null And Desktop(parent).restrictWindows Then
			If newX + w > parent.w Then newX = parent.w - w
			If newY + h > parent.h Then newY = parent.h - h
			If newX < 0 Then newX = 0
			If newY < 0 Then newY = 0
		End
		SetLocation(newX, newY)
	End

	Method MouseClicked:Void(x#, y#, button%, absoluteX#, absoluteY#)
	End

	Method MouseEntered:Void(x#, y#, exitedComp:Component, absoluteX#, absoluteY#)
	End

	Method MouseExited:Void(x#, y#, enteredComp:Component, absoluteX#, absoluteY#)
	End

	Method MouseMoved:Void(x#, y#, absoluteX#, absoluteY#)
	End
End

Class WindowButtonPanelButton Extends Button
	Const CLOSE_BUTTON% = 0
	Const MAXIMISE_BUTTON% = 1
	Const MINIMISE_BUTTON% = 2
	Const SHADE_BUTTON% = 3
	Field buttonType%

	Method New(parent:Component, buttonType%)
		Super.New(parent)
		Self.buttonType = buttonType
	End

	Method ButtonClicked:Void()
		Local window:Window = Window(parent)
		AssertNotNull(window, "WindowButtonPanelButton.ButtonClicked: window was null")
		Select buttonType
			Case CLOSE_BUTTON
				window.Dispose()
		End
	End
End

Class Label Extends Component
Private
	Field text:String
	Field textRed%, textGreen%, textBlue%
	Field textXOffset# = 0
	Field textYOffset# = 0
	Field textXAlign# = 0
	Field textYAlign# = 0

Public

	Method Text:Void(txt:String, xAlign:Float, yAlign:Float) Property
		text = txt
		textXAlign = xAlign
		textYAlign = yAlign
	End

	Method New(parent:Component)
		Super.New(parent)
	End

	Method DrawComponent:Void()
		Super.DrawComponent()
		If text.Length > 0
			DrawText text, w*textXAlign+textXOffset, h*textYAlign+textYOffset, textXAlign, textYAlign
		End
	End
End

Class Button Extends Label Implements MouseListener
Private
	Field styleSelected:ComponentStyle = Null

Public
	Field selected:Bool
	Field toggle:Bool
	Field radioGroup:RadioGroup
	Field radioValue$

	Method New(parent:Component)
		Super.New(parent)
		Self.forwardAction = FindActionTarget()
		mouseAdapter = Self
	End

	Method New(parent:Component, image:GameImage)
		Super.New(parent)
		Self.forwardAction = FindActionTarget()
		mouseAdapter = Self
		Self.StyleNormal.image = image
		Self.StyleNormal.drawBackground = False
		Self.SetSize(image.w, image.h)
		If image.midhandled
			Self.midHandle = True
		End
	End

	Method New(parent:Component, image:GameImage, clickImage:GameImage)
		Super.New(parent)
		Self.forwardAction = FindActionTarget()
		mouseAdapter = Self
		Self.StyleNormal.image = image
		Self.styleNormal.downImage = clickImage
		Self.StyleNormal.drawBackground = False
		Self.SetSize(image.w, image.h)
		If image.midhandled
			Self.midHandle = True
		End
	End

	Method New(parent:Component, forwardAction:Component)
		Super.New(parent)
		Self.forwardAction = forwardAction
		mouseAdapter = Self
	End

	Method StyleSelected:ComponentStyle() Property
		If styleSelected = Null Then styleSelected = New ComponentStyle
		Return styleSelected
	End
	Method StyleSelected:Void(style:ComponentStyle) Property
		styleSelected = style
	End

	Method GetStyle:ComponentStyle(name$)
		If name = "selected" Then Return styleSelected
		Return Super.GetStyle(name)
	End

	Method SetStyle:Void(name$, style:ComponentStyle)
		If name = "selected" Then
			styleSelected = style
		Else
			Super.GetStyle(name)
		End
	End

	Method GetCurrentStyle:ComponentStyle()
		If selected And styleSelected <> Null Then Return styleSelected
		Return Super.GetCurrentStyle()
	End

	Method MouseClicked:Void(x#, y#, button%, absoluteX#, absoluteY#)
		' is it a radio button?
		If radioGroup <> Null Then
			radioGroup.SelectButton(Self)
		' is it a toggle button?
		ElseIf toggle Then
			selected = Not selected
		End
		ActionPerformed(Self, ACTION_CLICKED)
	End

	Method MousePressed:Void(x#, y#, button%, absoluteX#, absoluteY#)
	End

	Method MouseReleased:Void(x#, y#, button%, absoluteX#, absoluteY#)
	End

	Method MouseEntered:Void(x#, y#, exitedComp:Component, absoluteX#, absoluteY#)
	End

	Method MouseExited:Void(x#, y#, enteredComp:Component, absoluteX#, absoluteY#)
	End
End

Class RadioGroup
	Field buttons:ArrayList<Button> = New ArrayList<Button>
	Field currentValue$

	Method SelectButton:String(button:Button)
		For Local b:Button = EachIn buttons
			b.selected = (b = button)
			If b.selected Then
				currentValue = b.radioValue
			End
		Next
		Return currentValue
	End

	Method SelectValue:Button(value$)
		Local rv:Button = Null
		For Local b:Button = EachIn buttons
			b.selected = (b.radioValue = value)
			If b.selected Then
				currentValue = value
				rv = b
			End
		Next
		Return rv
	End

	Method AddButton:Void(button:Button, value$)
		button.radioValue = value
		button.radioGroup = Self
		buttons.Add(button)
	End

	Method RemoveButton:Void(button:Button)
		button.radioValue = ""
		button.radioGroup = Null
		buttons.Remove(button)
	End
End

Class Slider Extends Component Implements MouseListener, MouseMotionListener
	Const SLIDER_HORIZONTAL% = 0
	Const SLIDER_VERTICAL% = 1
	Const SLIDER_DIRECTION_TL_TO_BR% = 0 ' min is top or left, max is bottom or right
	Const SLIDER_DIRECTION_BR_TO_TL% = 1 ' min is bottom or right, max is top or left
Private
	Field buttonUpLeft:Button ' the button used for up and left
	Field buttonDownRight:Button ' the button used for down and right
	Field handle:Label
	Field showButtons:Bool
	Field orientation:Int = SLIDER_HORIZONTAL
	Field direction:Int = SLIDER_DIRECTION_TL_TO_BR

	Field dragX%, dragY%, originalX%, originalY%
	Field dragging:Bool = False

	Field styleLeftButton:ComponentStyle
	Field styleRightButton:ComponentStyle
	Field styleTopButton:ComponentStyle
	Field styleBottomButton:ComponentStyle
	Field styleHorizontalHandle:ComponentStyle
	Field styleVerticalHandle:ComponentStyle

Public
	Field minValue% = 0
	Field maxValue% = 100
	Field value% = 50
	Field tickInterval% = 10
	Field handleMargin% = 10
	Field handleSize% = 10
	Field buttonSize% = 15
	Field snapToTicks:Bool = True

	Method New(parent:Component)
		Super.New(parent)
		buttonUpLeft = New Button(Self, Self)
		buttonDownRight = New Button(Self, Self)
		handle = New Label(Self)
		handle.mouseAdapter = Self
		handle.mouseMotionAdapter = Self
		buttonUpLeft.visible = False
		buttonDownRight.visible = False
	End

	Method GetStyle:ComponentStyle(name$)
		If name = "leftButton" Then
			Return styleLeftButton
		ElseIf name = "rightButton" Then
			Return styleRightButton
		ElseIf name = "topButton" Then
			Return styleTopButton
		ElseIf name = "bottomButton" Then
			Return styleBottomButton
		ElseIf name = "horizontalHandle" Then
			Return styleHorizontalHandle
		ElseIf name = "verticalHandle" Then
			Return styleVerticalHandle
		End
		Return Super.GetStyle(name)
	End

	Method SetStyle:Void(name$, style:ComponentStyle)
		If name = "leftButton" Then
			styleLeftButton = style
		ElseIf name = "rightButton" Then
			styleRightButton = style
		ElseIf name = "topButton" Then
			styleTopButton = style
		ElseIf name = "bottomButton" Then
			styleBottomButton = style
		ElseIf name = "horizontalHandle" Then
			styleHorizontalHandle = style
		ElseIf name = "verticalHandle" Then
			styleVerticalHandle = style
		Else
			Super.SetStyle(name, style)
		End
		UpdateStyles()
	End

	Method ShowButtons:Bool() Property
		Return showButtons
	End

	Method ShowButtons:Void(showButtons:Bool) Property
		If showButtons <> Self.showButtons Then
			Self.showButtons = showButtons
			Layout()
		End
		Self.showButtons = showButtons
	End

	Method Orientation:Int() Property
		Return orientation
	End

	Method Orientation:Void(orientation:Int) Property
		If Self.orientation <> orientation Then
			Self.orientation = orientation
			UpdateStyles()
			Layout()
		End
		Self.orientation = orientation
	End

	Method Direction:Int() Property
		Return direction
	End

	Method Direction:Void(direction:Int) Property
		If Self.direction <> direction Then
			Self.direction = direction
			Layout()
		End
		Self.direction = direction
	End

	Method DrawComponent:Void()
		Super.DrawComponent()
		' TODO: render groove and ticks, etc.
	End

	Method UpdateStyles:Void()
		If orientation = SLIDER_HORIZONTAL Then
			buttonUpLeft.StyleNormal = styleLeftButton
			buttonDownRight.StyleNormal = styleRightButton
			handle.StyleNormal = styleHorizontalHandle
		Else
			buttonUpLeft.StyleNormal = styleTopButton
			buttonDownRight.StyleNormal = styleBottomButton
			handle.StyleNormal = styleVerticalHandle
		End
	End

	' TODO: adjust layout using xml offsets rather than hardcoded
	Method Layout:Void()
		If showButtons Then
			If orientation = SLIDER_HORIZONTAL Then
				buttonUpLeft.SetBounds(0, 0, buttonSize, Self.h)
				buttonDownRight.SetBounds(Self.w - buttonSize, 0, buttonSize, Self.h)
			Else
				buttonUpLeft.SetBounds(0, 0, Self.w, buttonSize)
				buttonDownRight.SetBounds(0, Self.h - buttonSize, Self.w, buttonSize)
			End
			buttonUpLeft.visible = True
			buttonDownRight.visible = True
		Else
			buttonUpLeft.visible = False
			buttonDownRight.visible = False
		End
		Local startVal% = buttonSize+handleMargin
		Local endVal% = -buttonSize-handleMargin
		Local fraction# = Float(value-minValue)/Float(maxValue-minValue)
		Local currentVal%
		If orientation = SLIDER_HORIZONTAL Then
			endVal += Self.w
			currentVal = startVal + (endVal - startVal) * fraction
			handle.SetBounds(currentVal-handleSize/2, 0, handleSize, Self.h)
		Else
			endVal += Self.h
			currentVal = startVal + (endVal - startVal) * fraction
			handle.SetBounds(0, currentVal-handleSize/2, Self.w, handleSize)
		End
	End

	Method HandleDrag:Int(mx%, my%)
		Local pos%, topLeft% = handleMargin, bottomRight% = -handleMargin
		If showButtons Then
			topLeft += buttonSize
			bottomRight -= buttonSize
		End
		If orientation = SLIDER_HORIZONTAL Then
			bottomRight += w
			pos = Min(Max(topLeft, mx), bottomRight)
		Else
			bottomRight += h
			pos = Min(Max(topLeft, my), bottomRight)
		End
		Local fraction# = Float(pos-topLeft) / Float(bottomRight-topLeft)
		If direction = SLIDER_DIRECTION_BR_TO_TL Then fraction = 1-fraction

		Local oldValue% = value
		value = SnapToValue(minValue + (maxValue - minValue)*fraction)

		' if it changed, update the layout and fire an event
		If value <> oldValue Then
			Local target:ActionListener = forwardAction
			If target = Null Then target = FindActionTarget()
			If target <> Null Then
				Layout()
				target.ActionPerformed(Self, ACTION_VALUE_CHANGED)
			EndIf
		End
	End

	Method ActionPerformed:Void(source:Component, action:String)
		If source = buttonUpLeft And action = ACTION_CLICKED Then
			If direction = SLIDER_DIRECTION_TL_TO_BR Then
				AdjustValue(-1)
			Else
				AdjustValue(1)
			End
		ElseIf source = buttonDownRight And action = ACTION_CLICKED Then
			If direction = SLIDER_DIRECTION_TL_TO_BR Then
				AdjustValue(1)
			Else
				AdjustValue(-1)
			End
		End
	End

	Method SnapToValue:Int(val%)
		If val < minValue Then
			val = minValue
			Return val
		End
		If val > maxValue Then
			val = maxValue
			Return val
		End
		If val Mod tickInterval = 0 Then Return val
		If val Mod tickInterval < tickInterval / 2 Then
			val -= val Mod tickInterval
		Else
			val -= val Mod tickInterval
			val += tickInterval
		End
		Return val
	End

	Method AdjustValue:Bool(amount%)
		If amount = 0 Then Return
		Local oldValue% = value

		' snap if we must
		If value Mod tickInterval > 0 Then
			If amount < 0 Then
				value += tickInterval - (value Mod tickInterval)
			Else
				value -= value Mod tickInterval
			End
		End

		' adjust it
		value += amount * tickInterval

		' check that it's in range
		If value < minValue Then value = minValue
		If value > maxValue Then value = maxValue

		' if it changed, update the layout and fire an event
		If value <> oldValue Then
			Local target:ActionListener = forwardAction
			If target = Null Then target = FindActionTarget()
			If target <> Null Then
				Layout()
				target.ActionPerformed(Self, ACTION_VALUE_CHANGED)
			EndIf
		End
		Return value <> oldValue
	End

	Method MousePressed:Void(x#, y#, button%, absoluteX#, absoluteY#)
		If dragging Then Return
		dragging = True
		HandleDrag(handle.x + x, handle.y + y)
	End

	Method MouseReleased:Void(x#, y#, button%, absoluteX#, absoluteY#)
		dragging = False
		HandleDrag(handle.x + x, handle.y + y)
	End

	Method MouseDragged:Void(x#, y#, button%, absoluteX#, absoluteY#)
		If Not dragging Then Return
		HandleDrag(handle.x + x, handle.y + y)
	End

	Method MouseClicked:Void(x#, y#, button%, absoluteX#, absoluteY#)
	End

	Method MouseEntered:Void(x#, y#, exitedComp:Component, absoluteX#, absoluteY#)
	End

	Method MouseExited:Void(x#, y#, enteredComp:Component, absoluteX#, absoluteY#)
	End

	Method MouseMoved:Void(x#, y#, absoluteX#, absoluteY#)
	End
End


Fixed background's flickering when state is created

Strict

Import mojo
Import reflection

Import flxextern
Import flxbasic
Import flxstate
Import flxcamera
Import flxtimer
Import flxtext
Import flxg
Import flxu
Import flxtilemap
Import system.flxassetsmanager
Import system.flxfont
Import system.flxdebugger
Import system.flxreplay
Import plugin.timermanager

#If TARGET = "xna" Or TARGET = "psm" Or TARGET = "win8"
	Import "data/beep_flx.wav"
#ElseIf TARGET = "html5"
	Import "data/beep_flx.ogg"
	Import "data/beep_flx.mp3"
#ElseIf TARGET = "glfw" Or TARGET = "bmax"
	Import "data/beep_flx.ogg"
#Else
	Import "data/beep_flx.mp3"
#End

Class FlxGame extends App

	Field useSoundHotKeys:Bool

	Field useSystemCursor:Bool

	Field forceDebugger:Bool

	Field _state:FlxState

	Field _requestedState:FlxState

	Field _requestedReset:Bool

	Field _debugger:FlxDebugger

	Field _debuggerUp:Bool

	Field _replay:FlxReplay

	Field _replayRequested:Bool

	Field _recordingRequested:Bool

	Field _replaying:Bool

	Field _recording:Bool

	Field _replayCancelKeys:Int[]

	Field _replayTimer:Float

	Field _replayCallback:FlxReplayListener

Private
	Field _iState:ClassInfo

	Field _created:Bool

	Field _step:Int

	Field _soundTrayTimer:Float

	Field _soundTrayWidth:Float

	Field _soundTrayHeight:Float

	Field _soundTrayX:Float

	Field _soundTrayY:Float

	Field _soundTrayVisible:Bool

	Field _soundTrayLabel:FlxText

	Field _updaterate:Int

	Field _stateReady:Bool

Public
	Method New(gameSizeX:Int, gameSizeY:Int, initialState:ClassInfo, zoom:Float = 1, updaterate:Int = 60, useSystemCursor:Bool = False)
		Local classObject:GlobalInfo

		For Local classInfo:ClassInfo = EachIn GetClasses()
			classObject = classInfo.GetGlobal("ClassObject", False)
			If (classObject = Null) classObject = classInfo.GetGlobal("ClassInfo", False)

			If (classObject <> Null) Then
				classObject.SetValue(classInfo)
			End If
		Next

		_soundTrayTimer = 0
		_soundTrayWidth = 160
		_soundTrayHeight = 45
		_soundTrayX = 0
		_soundTrayY	= -_soundTrayHeight
		_soundTrayVisible = False

		FlxG.Init(Self, gameSizeX, gameSizeY, zoom)
		FlxG.Updaterate = updaterate

		_state = Null

		useSoundHotKeys = Not FlxIsMobile()
		Self.useSystemCursor = useSystemCursor

		If (Not useSystemCursor) HideMouse()

		forceDebugger = False
		_debuggerUp = False

		_replay = New FlxReplay()
		_replayRequested = False
		_recordingRequested = False
		_replaying = False
		_recording = False

		_iState = initialState
		_requestedState = Null
		_requestedReset = True
		_created = False
	End Method

	Method OnCreate:Int()
		_InitData()
		_Step()

		#Rem
		_soundTrayLabel = New FlxText(10, 32, _soundTrayWidth, "VOLUME")
		_soundTrayLabel.SetFormat(FlxText.SYSTEM_FONT, 16, FlxG.WHITE, FlxText.ALIGN_CENTER)
		#End
		Return 0
	End Method

	Method OnUpdate:Int()
		If (FlxG.Updaterate <> _updaterate) Then
			_ResetFramerate()
		End If

		FlxG.UpdateDevice()
		_Step()

	#If TARGET <> "ios" And TARGET <> "android" And TARGET <> "psm"
		If (useSoundHotKeys) Then
			If (KeyHit(KEY_0)) Then
				FlxG.Mute = Not FlxG.Mute

				If (FlxG.VolumeHandler <> Null) Then
					If (FlxG.Mute) Then
						FlxG.VolumeHandler.OnVolumeChange(0)
					Else
						FlxG.VolumeHandler.OnVolumeChange(FlxG.Volume())
					End If
				End If

				_ShowSoundTray()
			End If

			If (KeyHit(KEY_MINUS)) Then
				FlxG.Mute = False
				FlxG.Volume(FlxG.Volume() - .1)
				_ShowSoundTray()
			End If

			If (KeyHit(KEY_EQUALS)) Then
				FlxG.Mute = False
				FlxG.Volume(FlxG.Volume() + .1)
				_ShowSoundTray()
			End If
		End If

		_UpdateSoundTray(_step)
	#End

		Return 0
	End Method

	Method OnRender:Int()
	#If FLX_DEBUG_ENABLED = "1"
		FlxBasic._VisibleCount = 0
	#End

		If ( Not _stateReady) Then
			Cls(FlxG._BgColor.r, FlxG._BgColor.g, FlxG._BgColor.b)

			_state.Create()
			_stateReady = True
			Return 0
		End If

		_Draw()
		Return 0
	End Method

	Method OnSuspend:Int()
		ShowMouse()
		FlxG.PauseSounds()
		Return 0
	End Method

	Method OnResume:Int()
	#If FLX_DEBUG_ENABLED = "1"
		If (Not _debuggerUp And Not useSystemCursor) Then
			HideMouse()
		End If
	#Else
		If ( Not useSystemCursor) Then
			HideMouse()
		End If
	#End

		FlxG.ResetInput()
		FlxG.ResumeSounds()
		Return 0
	End Method

	Method OnBack:Int()
		If (_state = Null Or _state.Back()) Then
			Return Super.OnBack()
		End If

		Return 0
	End Method

	Method OnClose:Int()
		If (_state = Null Or _state.Close()) Then
			Return Super.OnClose()
		End If

		Return 0
	End Method

	Method OnContentInit:Void()
	End Method

Private
	Method _ShowSoundTray:Void(silent:Bool = False)
		If (Not silent) Then
			FlxG.Play("beep" + FlxG.DATA_SUFFIX)
		End If

		_soundTrayTimer = 1
		_soundTrayY = 0
		_soundTrayVisible = True
	End Method

	Method _SwitchState:Void()
		FlxG.ResetCameras()
		FlxG.ResetInput()
		FlxG.DestroySounds()

	#If FLX_DEBUG_ENABLED = "1"
		If (_debugger <> Null) Then
			'TODO!
		End If
	#End

		Local timeManager:TimerManager = FlxTimer.Manager()
		If (timeManager <> Null) timeManager.Clear()

		If (_state <> Null) _state.Destroy()

		_state = _requestedState
		_stateReady = False

		If (FlxG.Updaterate <> _updaterate) Then
			_ResetFramerate()
		End If
	End Method

	Method _Step:Void()
		If (_requestedReset) Then
			_requestedReset = False
			_requestedState = FlxState(_iState.NewInstance())
			_replayTimer = 0
			_replayCancelKeys = []
			_Reset()
			FlxG.Reset()
		End If

		If (_recordingRequested) Then
			_recordingRequested = False
			_replay.Create(FlxG.GlobalSeed)
			_recording = True

		#If FLX_DEBUG_ENABLED = "1"
			If (_debugger <> Null) Then
				'TODO
				FlxG.Log("FLIXEL: starting new flixel gameplay record.")
			End If
		#End

		ElseIf (_replayRequested)
			_replayRequested = False
			_replay.Rewind()
			FlxG.GlobalSeed = _replay.seed

		#If FLX_DEBUG_ENABLED = "1"
			If (_debugger <> Null) Then
				'TODO
			End If
		#End

			_replaying = True
		End If

		If (_state <> _requestedState) Then
			_SwitchState()
			Return
		End If

		if (Not _stateReady) Return

	#If FLX_DEBUG_ENABLED = "1"
		FlxBasic._ActiveCount = 0
	#End

		If (_replaying) Then
			If (_replayCancelKeys.Length() > 0 And Not KeyDown(192) And Not KeyDown(220)) Then
				Local i:Int = 0
				Local l:Int = _replayCancelKeys.Length()

				While (i < l)
					If (KeyDown(_replayCancelKeys[i])) Then
						If (_replayCallback <> Null) Then
							_replayCallback.OnReplayComplete()
							_replayCallback = Null
						Else
							FlxG.StopReplay()
						End If

						Exit
					End If

					i += 1
				Wend
			End If

			_replay.PlayNextFrame()

			If (_replayTimer > 0) Then
				_replayTimer -= _step

				If (_replayTimer <= 0) Then
					If (_replayCallback <> Null) Then
						_replayCallback.OnReplayComplete()
						_replayCallback = Null
					Else
						FlxG.StopReplay()
					End If
				End If
			End If

			If (_replaying And _replay.finished) Then
				FlxG.StopReplay()

				If (_replayCallback <> Null) Then
					_replayCallback.OnReplayComplete()
					_replayCallback = Null
				End If
			End If

		#If FLX_DEBUG_ENABLED = "1"
			If (_debugger <> Null) Then
				'TODO
			End If
		#End

		Else
			FlxG.UpdateInput()
		End If

		If (_recording) Then
			_replay.RecordFrame()

		#If FLX_DEBUG_ENABLED = "1"
			If (_debugger <> Null) Then
				'TODO
			End If
		#End

		End If

		_Update()

	#If FLX_DEBUG_ENABLED = "1"
		If (_debugger <> Null) Then
			'TODO
		End If
	#End
	End Method

	Method _Update:Void()
		FlxG.Elapsed = FlxG.TimeScale * (_step / 1000.0)

		FlxG.UpdateSounds()
		FlxG.UpdatePlugins()
		_state.Update()

		If (FlxG.Tweener.active And FlxG.Tweener.HasTween) Then
			FlxG.Tweener.UpdateTweens()
		End If

		FlxG.UpdateCameras()

	#If FLX_DEBUG_ENABLED = "1"
		If (_debuggerUp) Then
			'TODO!
		End If
	#End
	End Method

	Method _UpdateSoundTray:Void(ms:Int)
		If (Not _soundTrayVisible) Return

		If (_soundTrayTimer > 0) Then
			_soundTrayTimer -= ms / 1000.0

		ElseIf (_soundTrayY > -_soundTrayHeight)
			_soundTrayY =_soundTrayY - (ms / 1000.0 * FlxG.Height * 2)

			If (_soundTrayY <= -_soundTrayHeight) Then
				_soundTrayVisible = False

				'TODO Save sound settings
			End If
		End If
	End Method

	Method _Draw:Void()
		Cls(FlxG._BgColor.r, FlxG._BgColor.g, FlxG._BgColor.b)

	#If TARGET <> "ios" And TARGET <> "android" And TARGET <> "psm" And TARGET <> "win8"
		If( Not FlxG.Mobile) Then
			PushMatrix()
		End If
	#End

		Translate(FlxG._DeviceOffsetX, FlxG._DeviceOffsetY)
		Scale(FlxG._DeviceScaleFactorX, FlxG._DeviceScaleFactorY)

		FlxG._LastDrawingColor = FlxG.WHITE
		FlxG._LastDrawingBlend = GetBlend()
		FlxG._LastDrawingAlpha = GetAlpha()
		FlxG._CurrentCamera = Null

		Local i:Int = 0
		Local l:Int = FlxG.Cameras.Length()

		While(i < l)
			FlxG._CurrentCamera = FlxG.Cameras.Get(i)

			If (FlxG._CurrentCamera <> Null And FlxG._CurrentCamera.active And FlxG._CurrentCamera.exists And FlxG._CurrentCamera.visible) Then
				FlxG._CurrentCamera.DrawFX() 'not really draw. Only calculation
				FlxG._CurrentCamera.Lock()
				_state.Draw()
				FlxG.DrawPlugins()
				FlxG._CurrentCamera.Unlock()
			End If

			i+=1
		Wend

	#If TARGET <> "ios" And TARGET <> "android" And TARGET <> "psm" And TARGET <> "win8"
		If( Not FlxG.Mobile) Then
			PopMatrix()
			_DrawSoundTray()
			FlxG.Mouse.Draw()
		End If
	#End
	End Method

	Method _DrawSoundTray:Void()
		If (_soundTrayVisible) Then
			Local globalVolume:Int = FlxU.Round(FlxG.Volume() * 10)
			If (FlxG.Mute) globalVolume = 0

			PushMatrix()

			Transform(FlxG._DeviceScaleFactorX, 0, 0, FlxG._DeviceScaleFactorY, ( (FlxG.DeviceWidth - _soundTrayWidth * FlxG._DeviceScaleFactorX) * 0.5), _soundTrayY)

			If (FlxG._LastDrawingAlpha <> .5) Then
				SetAlpha(.5)
				FlxG._LastDrawingAlpha = .5
			End If

			If (FlxG._LastDrawingColor <> FlxG.BLACK) Then
				SetColor(0, 0, 0)
			End If

			DrawRect(0, 0, _soundTrayWidth, _soundTrayHeight)

			SetColor(255, 255, 255)
			FlxG._LastDrawingColor = FlxG.WHITE

			Local bx:Int = 20
			Local by:Int = 28

			Local i:Int = 0
			While (i < 10)
				If (i < globalVolume) Then
					If (FlxG._LastDrawingAlpha <> 1) Then
						SetAlpha(1)
						FlxG._LastDrawingAlpha = 1
					End If

				Else
					If (FlxG._LastDrawingAlpha <> .5) Then
						SetAlpha(.5)
						FlxG._LastDrawingAlpha = .5
					End If
				End If

				DrawRect(bx, by, 8, i * 2)

				bx += 12
				by -= 2
				i += 1
			Wend

			'_soundTrayLabel.Draw()

			PopMatrix()
		End If
	End Method

	Method _Reset:Void()
		If (FlxG.Updaterate <> _updaterate) Then
			_ResetFramerate()
		End If

		Local date:Int[] = GetDate()

		Seed = (date[3] * 3600 + date[4] * 60 + date[5]) * 1000 + date[6]
		FlxG.UpdateDevice()
	End Method

	Method _ResetFramerate:Void()
		SetUpdateRate(FlxG.Updaterate)
		_step = 1000 / FlxG.Updaterate
		_updaterate = FlxG.Updaterate
	End Method

	Method _InitData:Void()
		FlxAssetsManager.Init()

		Local minSystemFontSize:Int = 8
		Local maxSystemFontSize:Int = 24
		Local fontPathPrefix:String = FlxText.SYSTEM_FONT + "_font_"

		Local system:FlxFont = 	FlxAssetsManager.AddFont(FlxText.SYSTEM_FONT)

		For Local size:Int = minSystemFontSize To maxSystemFontSize
			system.SetPath(size, fontPathPrefix + size + FlxG.DATA_SUFFIX)
		Next

		FlxAssetsManager.AddImage("default" + FlxG.DATA_SUFFIX, "default" +  FlxG.DATA_SUFFIX + ".png")
		FlxAssetsManager.AddImage("button" + FlxG.DATA_SUFFIX, "button" + FlxG.DATA_SUFFIX + ".png")
		FlxAssetsManager.AddImage(FlxTilemap.AUTOTILES, FlxTilemap.AUTOTILES + ".png")
		FlxAssetsManager.AddImage(FlxTilemap.AUTOTILES_ALT, FlxTilemap.AUTOTILES_ALT + ".png")
		FlxAssetsManager.AddCursor("cursor" + FlxG.DATA_SUFFIX, "cursor" + FlxG.DATA_SUFFIX + ".png")

		FlxAssetsManager.AddSound("beep" + FlxG.DATA_SUFFIX, "beep" + FlxG.DATA_SUFFIX + "." + FlxSound.GetValidExt())

		Local contentInitTrigger:FunctionInfo

		For Local classInfo:ClassInfo = EachIn GetClasses()
			contentInitTrigger = classInfo.GetFunction("OnContentInit",[], False)
			If (contentInitTrigger <> Null) contentInitTrigger.Invoke([])
		Next

		Self.OnContentInit()
	End Method
End Class

Strict

Import mojo
Import reflection

Import flxextern
Import flxbasic
Import flxstate
Import flxcamera
Import flxtimer
Import flxtext
Import flxg
Import flxu
Import flxtilemap
Import system.flxassetsmanager
Import system.flxfont
Import system.flxdebugger
Import system.flxreplay
Import plugin.timermanager

#If TARGET = "xna" Or TARGET = "psm" Or TARGET = "win8"
	Import "data/beep_flx.wav"
#ElseIf TARGET = "html5"
	Import "data/beep_flx.ogg"
	Import "data/beep_flx.mp3"
#ElseIf TARGET = "glfw" Or TARGET = "bmax"
	Import "data/beep_flx.ogg"
#Else
	Import "data/beep_flx.mp3"
#End

Class FlxGame extends App

	Field useSoundHotKeys:Bool

	Field useSystemCursor:Bool

	Field forceDebugger:Bool

	Field _state:FlxState

	Field _requestedState:FlxState

	Field _requestedReset:Bool

	Field _debugger:FlxDebugger

	Field _debuggerUp:Bool

	Field _replay:FlxReplay

	Field _replayRequested:Bool

	Field _recordingRequested:Bool

	Field _replaying:Bool

	Field _recording:Bool

	Field _replayCancelKeys:Int[]

	Field _replayTimer:Float

	Field _replayCallback:FlxReplayListener

Private
	Field _iState:ClassInfo

	Field _created:Bool

	Field _step:Int

	Field _soundTrayTimer:Float

	Field _soundTrayWidth:Float

	Field _soundTrayHeight:Float

	Field _soundTrayX:Float

	Field _soundTrayY:Float

	Field _soundTrayVisible:Bool

	Field _soundTrayLabel:FlxText

	Field _updaterate:Int

	Field _stateReady:Bool

Public
	Method New(gameSizeX:Int, gameSizeY:Int, initialState:ClassInfo, zoom:Float = 1, updaterate:Int = 60, useSystemCursor:Bool = False)
		Local classObject:GlobalInfo

		For Local classInfo:ClassInfo = EachIn GetClasses()
			classObject = classInfo.GetGlobal("ClassObject", False)
			If (classObject = Null) classObject = classInfo.GetGlobal("ClassInfo", False)

			If (classObject <> Null) Then
				classObject.SetValue(classInfo)
			End If
		Next

		_soundTrayTimer = 0
		_soundTrayWidth = 160
		_soundTrayHeight = 45
		_soundTrayX = 0
		_soundTrayY	= -_soundTrayHeight
		_soundTrayVisible = False

		FlxG.Init(Self, gameSizeX, gameSizeY, zoom)
		FlxG.Updaterate = updaterate

		_state = Null

		useSoundHotKeys = Not FlxIsMobile()
		Self.useSystemCursor = useSystemCursor

		If (Not useSystemCursor) HideMouse()

		forceDebugger = False
		_debuggerUp = False

		_replay = New FlxReplay()
		_replayRequested = False
		_recordingRequested = False
		_replaying = False
		_recording = False

		_iState = initialState
		_requestedState = Null
		_requestedReset = True
		_created = False
	End Method

	Method OnCreate:Int()
		_InitData()
		_Step()

		#Rem
		_soundTrayLabel = New FlxText(10, 32, _soundTrayWidth, "VOLUME")
		_soundTrayLabel.SetFormat(FlxText.SYSTEM_FONT, 16, FlxG.WHITE, FlxText.ALIGN_CENTER)
		#End
		Return 0
	End Method

	Method OnUpdate:Int()
		If (FlxG.Updaterate <> _updaterate) Then
			_ResetFramerate()
		End If

		FlxG.UpdateDevice()
		_Step()

	#If TARGET <> "ios" And TARGET <> "android" And TARGET <> "psm"
		If (useSoundHotKeys) Then
			If (KeyHit(KEY_0)) Then
				FlxG.Mute = Not FlxG.Mute

				If (FlxG.VolumeHandler <> Null) Then
					If (FlxG.Mute) Then
						FlxG.VolumeHandler.OnVolumeChange(0)
					Else
						FlxG.VolumeHandler.OnVolumeChange(FlxG.Volume())
					End If
				End If

				_ShowSoundTray()
			End If

			If (KeyHit(KEY_MINUS)) Then
				FlxG.Mute = False
				FlxG.Volume(FlxG.Volume() - .1)
				_ShowSoundTray()
			End If

			If (KeyHit(KEY_EQUALS)) Then
				FlxG.Mute = False
				FlxG.Volume(FlxG.Volume() + .1)
				_ShowSoundTray()
			End If
		End If

		_UpdateSoundTray(_step)
	#End

		Return 0
	End Method

	Method OnRender:Int()
	#If FLX_DEBUG_ENABLED = "1"
		FlxBasic._VisibleCount = 0
	#End

		If ( Not _stateReady) Then
			_state.Create()
			_stateReady = True
			Return 0
		End If

		_Draw()
		Return 0
	End Method

	Method OnSuspend:Int()
		ShowMouse()
		FlxG.PauseSounds()
		Return 0
	End Method

	Method OnResume:Int()
	#If FLX_DEBUG_ENABLED = "1"
		If (Not _debuggerUp And Not useSystemCursor) Then
			HideMouse()
		End If
	#Else
		If ( Not useSystemCursor) Then
			HideMouse()
		End If
	#End

		FlxG.ResetInput()
		FlxG.ResumeSounds()
		Return 0
	End Method

	Method OnBack:Int()
		If (_state = Null Or _state.Back()) Then
			Return Super.OnBack()
		End If

		Return 0
	End Method

	Method OnClose:Int()
		If (_state = Null Or _state.Close()) Then
			Return Super.OnClose()
		End If

		Return 0
	End Method

	Method OnContentInit:Void()
	End Method

Private
	Method _ShowSoundTray:Void(silent:Bool = False)
		If (Not silent) Then
			FlxG.Play("beep" + FlxG.DATA_SUFFIX)
		End If

		_soundTrayTimer = 1
		_soundTrayY = 0
		_soundTrayVisible = True
	End Method

	Method _SwitchState:Void()
		FlxG.ResetCameras()
		FlxG.ResetInput()
		FlxG.DestroySounds()

	#If FLX_DEBUG_ENABLED = "1"
		If (_debugger <> Null) Then
			'TODO!
		End If
	#End

		Local timeManager:TimerManager = FlxTimer.Manager()
		If (timeManager <> Null) timeManager.Clear()

		If (_state <> Null) _state.Destroy()

		_state = _requestedState
		_stateReady = False

		If (FlxG.Updaterate <> _updaterate) Then
			_ResetFramerate()
		End If
	End Method

	Method _Step:Void()
		If (_requestedReset) Then
			_requestedReset = False
			_requestedState = FlxState(_iState.NewInstance())
			_replayTimer = 0
			_replayCancelKeys = []
			_Reset()
			FlxG.Reset()
		End If

		If (_recordingRequested) Then
			_recordingRequested = False
			_replay.Create(FlxG.GlobalSeed)
			_recording = True

		#If FLX_DEBUG_ENABLED = "1"
			If (_debugger <> Null) Then
				'TODO
				FlxG.Log("FLIXEL: starting new flixel gameplay record.")
			End If
		#End

		ElseIf (_replayRequested)
			_replayRequested = False
			_replay.Rewind()
			FlxG.GlobalSeed = _replay.seed

		#If FLX_DEBUG_ENABLED = "1"
			If (_debugger <> Null) Then
				'TODO
			End If
		#End

			_replaying = True
		End If

		If (_state <> _requestedState) Then
			_SwitchState()
			Return
		End If

		if (Not _stateReady) Return

	#If FLX_DEBUG_ENABLED = "1"
		FlxBasic._ActiveCount = 0
	#End

		If (_replaying) Then
			If (_replayCancelKeys.Length() > 0 And Not KeyDown(192) And Not KeyDown(220)) Then
				Local i:Int = 0
				Local l:Int = _replayCancelKeys.Length()

				While (i < l)
					If (KeyDown(_replayCancelKeys[i])) Then
						If (_replayCallback <> Null) Then
							_replayCallback.OnReplayComplete()
							_replayCallback = Null
						Else
							FlxG.StopReplay()
						End If

						Exit
					End If

					i += 1
				Wend
			End If

			_replay.PlayNextFrame()

			If (_replayTimer > 0) Then
				_replayTimer -= _step

				If (_replayTimer <= 0) Then
					If (_replayCallback <> Null) Then
						_replayCallback.OnReplayComplete()
						_replayCallback = Null
					Else
						FlxG.StopReplay()
					End If
				End If
			End If

			If (_replaying And _replay.finished) Then
				FlxG.StopReplay()

				If (_replayCallback <> Null) Then
					_replayCallback.OnReplayComplete()
					_replayCallback = Null
				End If
			End If

		#If FLX_DEBUG_ENABLED = "1"
			If (_debugger <> Null) Then
				'TODO
			End If
		#End

		Else
			FlxG.UpdateInput()
		End If

		If (_recording) Then
			_replay.RecordFrame()

		#If FLX_DEBUG_ENABLED = "1"
			If (_debugger <> Null) Then
				'TODO
			End If
		#End

		End If

		_Update()

	#If FLX_DEBUG_ENABLED = "1"
		If (_debugger <> Null) Then
			'TODO
		End If
	#End
	End Method

	Method _Update:Void()
		FlxG.Elapsed = FlxG.TimeScale * (_step / 1000.0)

		FlxG.UpdateSounds()
		FlxG.UpdatePlugins()
		_state.Update()

		If (FlxG.Tweener.active And FlxG.Tweener.HasTween) Then
			FlxG.Tweener.UpdateTweens()
		End If

		FlxG.UpdateCameras()

	#If FLX_DEBUG_ENABLED = "1"
		If (_debuggerUp) Then
			'TODO!
		End If
	#End
	End Method

	Method _UpdateSoundTray:Void(ms:Int)
		If (Not _soundTrayVisible) Return

		If (_soundTrayTimer > 0) Then
			_soundTrayTimer -= ms / 1000.0

		ElseIf (_soundTrayY > -_soundTrayHeight)
			_soundTrayY =_soundTrayY - (ms / 1000.0 * FlxG.Height * 2)

			If (_soundTrayY <= -_soundTrayHeight) Then
				_soundTrayVisible = False

				'TODO Save sound settings
			End If
		End If
	End Method

	Method _Draw:Void()
		Cls(FlxG._BgColor.r, FlxG._BgColor.g, FlxG._BgColor.b)

	#If TARGET <> "ios" And TARGET <> "android" And TARGET <> "psm" And TARGET <> "win8"
		If( Not FlxG.Mobile) Then
			PushMatrix()
		End If
	#End

		Translate(FlxG._DeviceOffsetX, FlxG._DeviceOffsetY)
		Scale(FlxG._DeviceScaleFactorX, FlxG._DeviceScaleFactorY)

		FlxG._LastDrawingColor = FlxG.WHITE
		FlxG._LastDrawingBlend = GetBlend()
		FlxG._LastDrawingAlpha = GetAlpha()
		FlxG._CurrentCamera = Null

		Local i:Int = 0
		Local l:Int = FlxG.Cameras.Length()

		While(i < l)
			FlxG._CurrentCamera = FlxG.Cameras.Get(i)

			If (FlxG._CurrentCamera <> Null And FlxG._CurrentCamera.active And FlxG._CurrentCamera.exists And FlxG._CurrentCamera.visible) Then
				FlxG._CurrentCamera.DrawFX() 'not really draw. Only calculation
				FlxG._CurrentCamera.Lock()
				_state.Draw()
				FlxG.DrawPlugins()
				FlxG._CurrentCamera.Unlock()
			End If

			i+=1
		Wend

	#If TARGET <> "ios" And TARGET <> "android" And TARGET <> "psm" And TARGET <> "win8"
		If( Not FlxG.Mobile) Then
			PopMatrix()
			_DrawSoundTray()
			FlxG.Mouse.Draw()
		End If
	#End
	End Method

	Method _DrawSoundTray:Void()
		If (_soundTrayVisible) Then
			Local globalVolume:Int = FlxU.Round(FlxG.Volume() * 10)
			If (FlxG.Mute) globalVolume = 0

			PushMatrix()

			Transform(FlxG._DeviceScaleFactorX, 0, 0, FlxG._DeviceScaleFactorY, ( (FlxG.DeviceWidth - _soundTrayWidth * FlxG._DeviceScaleFactorX) * 0.5), _soundTrayY)

			If (FlxG._LastDrawingAlpha <> .5) Then
				SetAlpha(.5)
				FlxG._LastDrawingAlpha = .5
			End If

			If (FlxG._LastDrawingColor <> FlxG.BLACK) Then
				SetColor(0, 0, 0)
			End If

			DrawRect(0, 0, _soundTrayWidth, _soundTrayHeight)

			SetColor(255, 255, 255)
			FlxG._LastDrawingColor = FlxG.WHITE

			Local bx:Int = 20
			Local by:Int = 28

			Local i:Int = 0
			While (i < 10)
				If (i < globalVolume) Then
					If (FlxG._LastDrawingAlpha <> 1) Then
						SetAlpha(1)
						FlxG._LastDrawingAlpha = 1
					End If

				Else
					If (FlxG._LastDrawingAlpha <> .5) Then
						SetAlpha(.5)
						FlxG._LastDrawingAlpha = .5
					End If
				End If

				DrawRect(bx, by, 8, i * 2)

				bx += 12
				by -= 2
				i += 1
			Wend

			'_soundTrayLabel.Draw()

			PopMatrix()
		End If
	End Method

	Method _Reset:Void()
		If (FlxG.Updaterate <> _updaterate) Then
			_ResetFramerate()
		End If

		Local date:Int[] = GetDate()

		Seed = (date[3] * 3600 + date[4] * 60 + date[5]) * 1000 + date[6]
		FlxG.UpdateDevice()
	End Method

	Method _ResetFramerate:Void()
		SetUpdateRate(FlxG.Updaterate)
		_step = 1000 / FlxG.Updaterate
		_updaterate = FlxG.Updaterate
	End Method

	Method _InitData:Void()
		FlxAssetsManager.Init()

		Local minSystemFontSize:Int = 8
		Local maxSystemFontSize:Int = 24
		Local fontPathPrefix:String = FlxText.SYSTEM_FONT + "_font_"

		Local system:FlxFont = 	FlxAssetsManager.AddFont(FlxText.SYSTEM_FONT)

		For Local size:Int = minSystemFontSize To maxSystemFontSize
			system.SetPath(size, fontPathPrefix + size + FlxG.DATA_SUFFIX)
		Next

		FlxAssetsManager.AddImage("default" + FlxG.DATA_SUFFIX, "default" +  FlxG.DATA_SUFFIX + ".png")
		FlxAssetsManager.AddImage("button" + FlxG.DATA_SUFFIX, "button" + FlxG.DATA_SUFFIX + ".png")
		FlxAssetsManager.AddImage(FlxTilemap.AUTOTILES, FlxTilemap.AUTOTILES + ".png")
		FlxAssetsManager.AddImage(FlxTilemap.AUTOTILES_ALT, FlxTilemap.AUTOTILES_ALT + ".png")
		FlxAssetsManager.AddCursor("cursor" + FlxG.DATA_SUFFIX, "cursor" + FlxG.DATA_SUFFIX + ".png")

		FlxAssetsManager.AddSound("beep" + FlxG.DATA_SUFFIX, "beep" + FlxG.DATA_SUFFIX + "." + FlxSound.GetValidExt())

		Local contentInitTrigger:FunctionInfo

		For Local classInfo:ClassInfo = EachIn GetClasses()
			contentInitTrigger = classInfo.GetFunction("OnContentInit",[], False)
			If (contentInitTrigger <> Null) contentInitTrigger.Invoke([])
		Next

		Self.OnContentInit()
	End Method
End Class