components_ui_buttongroup_JRButtonGroup.bs


import "pkg:/source/utils/misc.bs"

sub init()
  m.top.layoutDirection = "horiz"
  m.top.itemSpacings = 12

  m.top.buttonFocused = 0
end sub

' center the button group horizontally
' NOTE: this centers using the entire screen width, not the parent bounding rect
sub center()
  buttonsBoundingRect = m.top.boundingRect()

  m.top.translation = [(1920 - buttonsBoundingRect.width) / 2, m.top.translation[1]]
end sub

' Use instead of setFocus(true)
sub focus()
  m.top.setFocus(true)
  if m.top.buttonFocused <> invalid
    button = m.top.getChild(m.top.buttonFocused)
    if button <> invalid
      button.setFocus(true)
    end if
  end if
end sub

function onKeyEvent(key as string, press as boolean) as boolean
  if not press then return false

  currentFocus = m.top.buttonFocused
  currentFocusButton = m.top.getChild(currentFocus)

  ' print "currentFocus =", currentFocus
  ' print "currentFocusButton =", currentFocusButton
  ' print "m.top.getChildCount() =", m.top.getChildCount()

  if key = "right"
    ' Move right, skipping disabled buttons
    for i = currentFocus + 1 to m.top.getChildCount() - 1
      button = m.top.getChild(i)

      if button.enabled
        currentFocusButton.setFocus(false)
        m.top.buttonFocused = i
        button.setFocus(true)
        return true
      end if
    end for
    ' wrap if needed
    for i = 0 to currentFocus - 1
      button = m.top.getChild(i)

      if button.enabled
        currentFocusButton.setFocus(false)
        m.top.buttonFocused = i
        button.setFocus(true)
        return true
      end if
    end for
  else if key = "left"
    ' Move left, skipping disabled buttons
    for i = currentFocus - 1 to 0 step -1
      button = m.top.getChild(i)

      if button.enabled
        currentFocusButton.setFocus(false)
        m.top.buttonFocused = i
        button.setFocus(true)
        return true
      end if
    end for
    ' wrap if needed
    for i = m.top.getChildCount() - 1 to currentFocus + 1 step -1
      button = m.top.getChild(i)

      if button.enabled
        currentFocusButton.setFocus(false)
        m.top.buttonFocused = i
        button.setFocus(true)
        return true
      end if
    end for
  end if

  if key = "OK"
    print "OK pressed from JRButtonGroup, buttonFocused =", m.top.buttonFocused
    m.top.buttonSelected = m.top.buttonFocused
    return true
  end if

  return false
end function