switch.nim 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. # author: Ethosa
  2. ## Displays colour rectangle.
  3. import
  4. ../thirdparty/opengl,
  5. ../core/vector2,
  6. ../core/rect2,
  7. ../core/anchor,
  8. ../core/input,
  9. ../core/color,
  10. ../core/enums,
  11. ../core/themes,
  12. ../nodes/node,
  13. control
  14. type
  15. SwitchHandler* = proc(self: SwitchRef, toggled: bool)
  16. SwitchObj* = object of ControlRef
  17. value*: bool
  18. color_enable*, color_disable*: ColorRef
  19. back_enable*, back_disable*: ColorRef
  20. on_switch*: SwitchHandler ## This called when switch toggled.
  21. SwitchRef* = ref SwitchObj
  22. let switch_handler = proc(self: SwitchRef, toggled: bool) = discard
  23. proc Switch*(name: string = "Switch"): SwitchRef =
  24. ## Creates a new Switch.
  25. ##
  26. ## Arguments:
  27. ## - `name` is a node name.
  28. runnableExamples:
  29. var colorrect1 = Switch("Switch")
  30. nodepattern(SwitchRef)
  31. controlpattern()
  32. result.color_disable = current_theme~accent_dark
  33. result.color_enable = current_theme~accent
  34. result.back_disable = current_theme~background_deep
  35. result.back_enable = current_theme~accent_dark
  36. result.value = false
  37. result.rect_size.x = 50
  38. result.rect_size.y = 20
  39. result.on_switch = switch_handler
  40. result.kind = COLOR_RECT_NODE
  41. method draw*(self: SwitchRef, w, h: GLfloat) =
  42. ## this method uses in the `window.nim`.
  43. let
  44. x = -w/2 + self.global_position.x
  45. y = h/2 - self.global_position.y
  46. color = if self.value: self.color_enable else: self.color_disable
  47. back = if self.value: self.back_enable else: self.back_disable
  48. glColor(back)
  49. glRectf(x, y, x+self.rect_size.x, y-self.rect_size.y)
  50. glColor(color)
  51. if self.value:
  52. glRectf(x + self.rect_size.x - 10, y, x + self.rect_size.x, y-self.rect_size.y)
  53. else:
  54. glRectf(x, y, x + 10, y-self.rect_size.y)
  55. # Press
  56. if self.pressed:
  57. self.on_press(self, last_event.x, last_event.y)
  58. method duplicate*(self: SwitchRef): SwitchRef {.base.} =
  59. ## Duplicates Switch object and create a new Switch.
  60. self.deepCopy()
  61. method handle*(self: SwitchRef, event: InputEvent, mouse_on: var NodeRef) =
  62. ## Handles user input. This uses in the `window.nim`.
  63. procCall self.ControlRef.handle(event, mouse_on)
  64. if self.hovered and event.kind == MOUSE and event.pressed:
  65. self.value = not self.value
  66. self.on_switch(self, self.value)
  67. method toggle*(self: SwitchRef) {.base.} =
  68. ## Toggles value.
  69. self.value = not self.value