include gui/tin/tinewg.exw
include std\filesys.e

sequence picdir=current_dir()
atom fileindex=0,lastindex=0
object dirlist={}

constant popup= CreatePopupMenu ()
AppendTextItem (popup,100,{ "Choose Folder" , "Next Picture" , "Previous Picture" , "--" , "Exit" })
EnableItem(popup,{101,102},False)

WindowType=NoBorderWin
Window("",-1,-1,ScreenWidth(),ScreenHeight())

atom mypic=LoadPic("pic.jpg")
sequence x = GetClientRect(WinHwnd)
CopyMBToControl(mypic,0,0,GetImageWidth(mypic),GetImageHeight(mypic),WinHwnd,0,0,x[3],x[4])
DeleteImage(mypic)

procedure display_pic()
    mypic=LoadPic(picdir&"\\"&dirlist[fileindex][D_NAME])
    CopyMBToControl(mypic,0,0,GetImageWidth(mypic),GetImageHeight(mypic),WinHwnd,0,0,x[3],x[4])
    DeleteImage(mypic)
end procedure

procedure show_popup()
sequence rect
atom result
    rect= GetWindowRect ( WinHwnd )
    result= TrackPopupMenu (popup,rect[1]+MouseX,rect[2]+MouseY, WinHwnd , False )
    --InfoMsg(result,"Popup Menu")
end procedure
SetHandler(WinHwnd,RRelease,routine_id("show_popup"))

procedure key_handler()
if EventItem=KEY_ESCAPE then
    CloseApp()
elsif EventItem=KEY_LEFT then
    EventItem=102
    menu()
elsif EventItem=KEY_RIGHT then
    EventItem=101
    menu()
elsif EventItem=KEY_DOWN then
    EventItem=100
    menu()
end if

end procedure
SetHandler(WinHwnd,Key,routine_id("key_handler"))

procedure menu()
    if EventItem=103 then
        CloseApp()
    elsif EventItem=100 then
        picdir=DirDlg("Choose Folder")
        dirlist=dir(picdir&"\\*.jpg")
        if atom(dirlist) then
            fileindex=0
            dirlist={}
            EnableItem(popup,{101,102},False)
        else
            fileindex=1
            lastindex=length(dirlist)
            EnableItem(popup,{101,102},True)
            display_pic()
        end if
    elsif EventItem=101 then
        if fileindex>0 then
            if fileindex<lastindex then
                fileindex+=1
                display_pic()
            else
                fileindex=1
                display_pic()
            end if
        end if
    elsif EventItem=102 then
        if fileindex>1 then
                fileindex-=1
                display_pic()
        else
                fileindex=lastindex
                display_pic()
        end if
    end if
end procedure
SetHandler(WinHwnd,Menu,routine_id("menu"))

procedure left_click()
    EventItem=101
    menu()
end procedure
SetHandler(WinHwnd,Click,routine_id("left_click"))

WinMain()