local lgi = require 'lgi'
local GObject = lgi.GObject
local Gtk = lgi.Gtk
local Gdk = lgi.Gdk

local window = Gtk.Window {
   Gtk.Box {
      orientation = 'VERTICAL',
      Gtk.Button {
	 id = 'copy',
	 label = 'copy',
      },
      Gtk.Button {
	 id = 'paste',
	 label = 'paste',
      },
   },
   on_destroy = Gtk.main_quit,
}

local atom = Gdk.Atom.intern_static_string('STRING')

local function clipboard_get_func(clipboard, selectiondata, info)
   print('* clipboard_get_func', clipboard, selectiondata, info)
   selectiondata:set(atom, 8, 'source')
end

local function clipboard_clear_func(clipboard)
   print('* clipboard_clear_func')
end

function window.child.copy:on_clicked()
   local clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
   clipboard:set_with_closures({ Gtk.TargetEntry.new('STRING', 0, 0) },
			       GObject.Closure(clipboard_get_func),
			       GObject.Closure(clipboard_clear_func))
end

local function paste_contents_received(clipboard, selectiondata, data)
   print('* __paste_contents_received:', clipboard, selectiondata, data)
   print('  --data=', selectiondata:get_data())
   print('  --format=', selectiondata:get_format())
   print('  --target=', selectiondata:get_target():name())
end

function window.child.paste:on_clicked()
   clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
   clipboard:request_contents(atom, paste_contents_received)
end

window:show_all()
Gtk.main()
