--[[  v1.0
2025-12-03 Scripted by Koentje   Resizes image to conky window size, also resizes when window mode is normal and window gets resized!
                                 Converts jpg or other images file to png (LUA only works with PNG)
                                 The option 'c' is for keep converting the same image every conky update. This is especially handy
                                 if your image gets renewed all the time (download from an IP Cam for example)

                                  _____Transparency (0-100)
                                 |    _c = keep converting the image every conky update (leave empty for NOT)
                                 |   |
usage:  ${lua image /path/to/png 100 c}

]]

require 'cairo'
require "imlib2"

-- Split string
function split(inputstr, sep)
  if sep == nil then
    sep = '%s'
  end
  local t={}
  local i=1
  for str in string.gmatch(inputstr, '([^'..sep..']+)') do
    table.insert(t, str)
  end
 return t
end


-- Draw image
function fDrawImage(rcr,path,ww,hh,alph)
   local rcs=cairo_xlib_surface_create(conky_window.display,conky_window.drawable,conky_window.visual, ww, hh)
   local rcr=cairo_create(rcs)
     local img = cairo_image_surface_create_from_png(path)
     local w_img = cairo_image_surface_get_width(img)
     local h_img = cairo_image_surface_get_height(img)
       cairo_save(rcr)
       cairo_translate (rcr, 0, 0)  --xx, yy
       cairo_scale (rcr, ww/w_img, hh/h_img)
       cairo_set_source_surface (rcr, img, 0, 0) --xx, yy
       cairo_paint_with_alpha (rcr, alph)
       cairo_surface_destroy (img)
       collectgarbage ()
       cairo_restore (rcr)
       cairo_surface_destroy(rcs)
      cairo_destroy(rcr)
end


-- Main function
function conky_image(img,tt,cc)
    if conky_window==nil then return '' end
    orgimg = img

    -- Determine if we must keep converting
    local keepc = "no"
    if cc == nil then keepc = "no" end
    if cc == "c" then keepc = "yes" end

    -- Get geometry of conky window
    local wingeo = ("cpath=\"".. conky_config .."\"                                                         \
                       stitle=$(cat \"$cpath\" | grep \"own_window_title = \" | awk -F'= ' '{print $2}')    \
                       ctitle=$(echo \"$stitle\" | tr -d ,| cut -c2- | rev | cut -c2- | rev)                \
                       wmctrl -lG | grep \"$ctitle\" | awk '{print $5\",\"$6}'                              \
                    ")

--               local wingeo = BASH_GEO .." ".. conky_config
               local handle = io.popen(wingeo)
               local output = handle:read("*a")
               local result = output:gsub('[\n\r]', '')
               handle:close()
               local key = {result}
               local mykey = split(key[1], ",")
                 local www = string.sub(mykey[1],0)
                 local hhh = string.sub(mykey[2],0)

    -- Convert image if not PNG
    local convert = ("keepc=".. keepc .."                                                                   \
                      path=".. img .."                                                                      \
                      filename=${path%.*}                                                                   \
                      ext=${path##*.}                                                                       \
                          if [ \"$(which convert)\" = \"\" ]; then                                          \
                            echo \"Warning: 'Convert' not found!  Install Imagemagick.. \" > ./error.log    \
                          fi                                                                                \
                          if [ -f \"$path\" ]; then                                                         \
                             if [ \"$ext\" != \"png\" ]; then                                               \
                                if [ \"$keepc\" = \"no\" ]; then                                            \
                                   if ! [ -f \"$filename.png\" ]; then                                      \
                                     convert -quiet \"$path\" \"$filename.png\"                             \
                                   fi                                                                       \
                                 else                                                                       \
                                   convert -quiet \"$path\" \"$filename.png\"                               \
                                fi                                                                          \
                             fi                                                                             \
                          else                                                                              \
                            echo \"Warning: '\"$path\"' does not exist! \" >> ./error.log                   \
                          fi                                                                                \
                      echo \"$filename.png\"                                                                \
                     ")
                local ihandle = io.popen(convert)
                local ioutput = ihandle:read("*a")
                local iresult = ioutput:gsub('[\n\r]', '')
                ihandle:close()
                local img = iresult
                os.execute("if [ -f ./error.log ]; then cat ./error.log; rm -f ./error.log; echo \"Exit script..\n\"; pkill -f ".. conky_config ..";fi")

    -- For some debug info on terminal uncomment line below
    --print("geo: "..result, "conkypath: "..orgimg,"convertpath: "..iresult, "keep converting: "..keepc, "Transparency: "..tt)

    -- Determine transparency
    local alpha = 0
      if tt == nil then ttt = 100 end
         local ttt = tonumber(tt)
         if ttt >= 1 and ttt <= 100 then alpha = (ttt / 100) end
         if ttt <=0 then alpha = 0 end
         if ttt >=101 then alpha = 1 end
      fDrawImage(rcr,img,www,hhh,alpha)
    return ''
end
