 USING: accessors arrays colors fry io.styles kernel math
 math.geometry.rect math.order math.vectors namespaces opengl
 sequences ui.gadgets ui.gadgets.scrollers ui.gadgets.status-bar
-ui.gadgets.worlds ui.gestures ui.render models math.ranges sequences
-combinators ;
+ui.gadgets.worlds ui.gadgets.theme ui.gestures ui.render models
+math.ranges sequences combinators ;
 IN: ui.gadgets.tables
 
 ! Row rendererer protocol

: validate-row ( m table -- n )
    control-value length 1- min 0 max ;

: first-visible-row ( table -- n )
    [
        [ clip get loc>> second origin get second - ] dip
        y>row
    ] keep validate-row ;

: last-visible-row ( table -- n )
    [
        [ clip get rect-extent nip second origin get second - ] dip
        y>row
    ] keep validate-row 1+ ;

: column-loc ( font column width align -- loc )
    [ [ [ open-font ] dip string-width ] dip swap - ] dip

: (select-row) ( table row -- )
    over validate-row
    [ [ thin-row-rect ] [ drop ] 2bi scroll>rect ]
    [ >>selected-index relayout-1 ]
    2bi ;

: mouse-row ( table -- n )
    [ hand-rel second ] keep y>row ;

: table-button-down ( table -- )
    dup request-focus
    dup control-value empty? [ drop ] [
        dup [ mouse-row ] keep validate-row
        [ >>mouse-index ] [ (select-row) ] bi
    ] if ;

: row-action ( table -- )
    dup selected-row dup
    [ swap action>> call ] [ 2drop ] if ;

: table-button-up ( table -- )
    hand-click# get 2 =
    [ row-action ] [ update-selected-value ] if ;

: select-row ( table row -- )
    [ (select-row) ] [ drop update-selected-value ] 2bi ;

: prev-row ( table -- )
    dup selected-index>> [ 1- ] [ 0 ] if* select-row ;

: next-row ( table -- )
    dup selected-index>> [ 1+ ] [ 0 ] if* select-row ;

: first-row ( table -- )
    0 select-row ;
