Back to all posts
Header image, not needed to understand the article

How to Use the Clipboard in Gio UI

Posted Jan 14, 2025 at 9:48 AM
Edited  Feb 03, 2025 at 7:53 PM

Tags:


I just spent an embarrassingly long time figuring out how to use the clipboard in Gio UI, so I want to document it somewhere for someone who may be having the same problem as me.


TLDR:

// Write text to clipboard
gtx.Execute(clipboard.WriteCmd{Type: "application/text", Data: io.NopCloser(strings.NewReader(text))})

// Read from clipboard to some editor e
gtx.Execute(clipboard.ReadCmd{Tag: e})

As you may know from a previous post, I’m working on a password manager. For a while, there’s been an annoyance with it that I just couldn’t shake. Since I couldn’t figure out how I was meant to interact with the clipboard with the tools Gio provides, I was using another library, tiagomelo/go-clipboard, to do it. Now, I don’t mean any disrespect to tiagomelo, since his library definitely has it’s uses, but it’s essentially a wrapper around other clipboard utilities. The end user must have one of those utilities installed in order for the copy/paste functionality to work.

This was extremely annoying to me. I didn’t want someone using QPass to have to install wl-clipboard or something as a dependency. It felt unnecessary. So I took another look at Gio’s documentation to see if I could find the problem. Still nothing, just like the last dozen times I checked. I knew there must be a way to do it though, because I had found a clipboard.go file in the repo from just googling “gioui clipboard”. So I took a deep dive into the code.

Long story short, after a couple hours of clicking between references and function calls I finally figured it out. It’s just a command that you execute with your layout.Context. clipboard.WriteCmd takes in Type, a string representing the MIME type of whatever you’re copying; and Data, an instance of io.ReadCloser containing the data you want to copy. clipboard.ReadCmd takes an instance of event.Tag. I haven’t fully figured out what event.Tag is meant to be (it looks like an alias for any to me? idk, I really only needed to figure out clipboard.WriteCmd for my purposes), but I do know that passing in a widget.Editor will paste the contents of the clipboard into that editor. So that’s useful.

So that’s what I was able to figure out, hopefully this helps someone. I’m going to see about contributing to Gio’s documentation if possible.