; ***************************************************************************
; copyright   : (C) 2026 by Martin Preuss
; email       : martin@libchipcard.de
;
; ***************************************************************************
; * This file is part of the project "AqHome".                              *
; * Please see toplevel file COPYING of that project for license details.   *
; ***************************************************************************

#ifndef AQH_AVR_GUI2_BUTTON_ASM
#define AQH_AVR_GUI2_BUTTON_ASM


; ***************************************************************************
; code

.cseg


; ---------------------------------------------------------------------------
; @routine Button_OnTouch @global
;
; @param Z byte address of widget object (for LPM!)
; @param X pointer to TOUCH event (see @ref WIDGET_DATA_TOUCH_OFFS_X_LO)
; @return CFLAG set if signal handled
; @clobbers any, !Z

Button_OnTouch:
  rcall Widget_GetSdramPtr               ; Y:=SDRAM data for widget

  ; read touch signal data from X
  ld r18, X+                             ; WIDGET_DATA_TOUCH_OFFS_X_LO
  ld r19, X+                             ; WIDGET_DATA_TOUCH_OFFS_X_HI
  ld r20, X+                             ; WIDGET_DATA_TOUCH_OFFS_Y_LO
  ld r21, X+                             ; WIDGET_DATA_TOUCH_OFFS_Z_HI
  ld r22, X                              ; WIDGET_DATA_TOUCH_OFFS_STATE
  sbiw xh:xl, 4

  sbrs r22, DISPLAY_IFLAGS_PRESSED_BIT
    rjmp Button_OnTouch_up
  ; down (active touch)
  ldd r16, Y+WIDGET_SD_OFFS_FLAGS
  sbrc r16, WIDGET_FLAGS_PRESSED_BIT
    rjmp Button_OnTouch_ret              ; already pressed, jmp
  ; newly pressed
  rcall widgetLoadCoordsForFullWidget    ; get X, Y, W, H (none)
  rcall Widget_MakeAbsPos                ; (R16, R17)
  rcall Widget_IsPointInRect             ; (R16, R17)
  brcc Button_OnTouch_ret                ; touch not inside this widget, jmp

  ; touch down inside this widget, handle
  bigcall Widget_GrabTouchEvents         ; (r16, r17, r18, r19, X)
  brcc Button_OnTouch_ret
  ldi r16, (1<<WIDGET_FLAGS_PRESSED_BIT) | (1<<WIDGET_FLAGS_DIRTY_BIT)
  push yl
    push yh
      bigcall Widget_AddFlagsDown        ; (R17, R18, R19, R22, R23, Y)
    pop yh
  pop yl
  rjmp Button_OnTouch_ret
Button_OnTouch_up:
  ldd r16, Y+WIDGET_SD_OFFS_FLAGS
  sbrs r16, WIDGET_FLAGS_PRESSED_BIT
    rjmp Button_OnTouch_ret
  ; was pressed, not any more
  bigcall Widget_UngrabTouchEvents        ; (r16, r17, r18, r19, X)
  push yl
    push yh
      ldi r16, (1<<WIDGET_FLAGS_PRESSED_BIT)
      bigcall Widget_SubFlagsDown        ; (R17, R18, R19, R22, R23, Y)
      ldi r16, (1<<WIDGET_FLAGS_DIRTY_BIT)
      bigcall Widget_AddFlagsDown        ; (R17, R18, R19, R22, R23, Y)
      ldi r16, WIDGET_SIGNAL_CLICKED     ; emit "CLICKED" signal
      bigcall OBJ_EmitSignal
    pop yh
  pop yl
Button_OnTouch_ret:
  sec
  ret
; @end




#endif

