! Widgets and an embedded Open dialog share the parent event loop.
program gui_demo
  use gaspardos_gui
  implicit none
  type(GO64_WindowOptions), target :: options
  type(GO64_Event), target :: event
  character(kind=c_char,len=5), target :: label = 'Open' // c_null_char
  character(kind=c_char,len=11), target :: path = '/AHCIDISK0' // c_null_char
  character(kind=c_char,len=1), target :: empty = c_null_char
  character(kind=c_char), target :: result(4096)
  character(len=4095) :: chosen
  type(c_ptr) :: ui, dialog
  integer(c_int64_t) :: window, r, action, pause, n, active
  integer :: i, attempt
  logical :: ready

  options%x=0; options%y=0; options%width=1000; options%height=700
  options%background=int(z'E8E8E8',c_int32_t)
  options%title=c_null_char
  options%title(1:7) = (/ 'F', 'o', 'r', 't', 'r', 'a', 'n' /)
  window=GO64_window_create(c_loc(options))
  if (window < 0) stop 1
  ui=gof_widgets_new(1000,700)
  dialog=gof_dialog_new()
  if (.not.c_associated(ui) .or. .not.c_associated(dialog)) stop 2
  r=gof_widgets_add(ui,1,1,16,16,120,28,c_loc(label(1:1)),0)
  if (r < 0) stop 3
  ready=.false.
  do
    r=GO64_window_event(window,c_loc(event),1_c_int64_t)
    if (r == 0) then
      if (event%type == 15 .or. event%type == GO64_ERROR) exit
      if (event%type == GO64_READY) ready=.true.
      active=gof_dialog_active(dialog)
      if (active == 1) then
        r=gof_dialog_event(dialog,c_loc(event),GO64_ticks())
      else
        action=gof_widgets_event(ui,c_loc(event))
        if (action < 0) exit
        if (action == 1) then
          r=gof_dialog_begin(dialog,0,c_loc(path(1:1)),c_loc(empty(1:1)),0)
          if (r < 0) exit
        end if
      end if
      if (active == 1 .and. gof_dialog_active(dialog) == 0) then
        if (gof_dialog_accepted(dialog) == 1) then
          n=gof_dialog_result(dialog,c_loc(result),int(size(result),c_int64_t))
          chosen=''
          do i=1,int(min(max(n,0_c_int64_t),4095_c_int64_t))
            chosen(i:i)=result(i)
          end do
          print *, trim(chosen)
        end if
        ! Request a full widget redraw after the modal dialog closes.
        r=gof_widgets_text(ui,1,c_loc(label(1:1)))
      end if
    else if (r /= -11) then
      exit
    end if
    if (ready) then
      if (gof_dialog_active(dialog) == 1) then
        r=gof_dialog_tick(dialog)
        if (r < 0) exit
        r=gof_dialog_paint(dialog,window)
      else
        r=gof_widgets_paint(ui,window)
      end if
      if (r < 0 .and. r /= -11) exit
    end if
    pause=GO64_yield()
  end do
  r=gof_dialog_delete(dialog)
  r=gof_widgets_delete(ui)
  do attempt=1,1000
    r=GO64_window_destroy(window)
    if (r /= -11) exit
    pause=GO64_yield()
  end do
  if (r < 0) stop 4
end program gui_demo
