golang-design / clipboard

πŸ“‹ cross-platform clipboard package that supports accessing text and image in Go (macOS/Linux/Windows/Android/iOS)
https://golang.design/x/clipboard
MIT License
579 stars 64 forks source link

Add Init() #18

Closed hrntknr closed 2 years ago

hrntknr commented 2 years ago

If you are using Linux without X11 enabled, an error will occur at the time of import. Add Test() methods to check if the clipboard is accessible for conditional branching.

Fixes #19

hrntknr commented 2 years ago

please check @changkun

hrntknr commented 2 years ago

I've just seen #13 for the first time, but the problem we want to solve is the same: changing the interface will cause problems for existing applications, so the implementation is backwards compatible.

I like the idea of Init but not entirely sure if this is how we should proceed.

Checking the implementation in init makes sense and is useful for some users. However, it also narrows down the use cases, and in my opinion, it would be great if the architecture was error-free in import.

hrntknr commented 2 years ago

We believe that if you can access clipbord once, you can always access it a second time or later. Therefore, to eliminate the overhead, we use canAccessClipbord to manage it. Also, to maintain backward compatibility as much as possible, we check each time and display an appropriate error message (errmsg). Without this check, the test results will look like the following

write failed with status: -1
write failed with status: -1
--- FAIL: TestClipboard (0.00s)
    --- FAIL: TestClipboard/image (0.00s)
        clipboard_test.go:60: read clipboard that stores image data as image should success, but got: nil
    --- FAIL: TestClipboard/text (0.00s)
        clipboard_test.go:105: read clipboard taht stores text data as text should success, but got: nil
write failed with status: -1
write failed with status: -1
--- FAIL: TestClipboardMultipleWrites (0.00s)
    clipboard_test.go:153: read clipboard that should store text data as text should success, got: nil
write failed with status: -1
write failed with status: -1
write failed with status: -1
write failed with status: -1
write failed with status: -1
write failed with status: -1
write failed with status: -1
--- FAIL: TestClipboardWatch (2.00s)
    clipboard_test.go:238: clipboard watch never receives a notification
write failed with status: -1
--- FAIL: ExampleRead (0.00s)
got:

want:
Hello, δΈ–η•Œ
write failed with status: -1
changkun commented 2 years ago

Without this check, the test results will look like the following

I think if one can pass Init(), then the system environment is sufficient to access clipboard information. However, indeed it may fail at some point for some reason. But as the current API is designed to behave: if there is an error when accessing the clipboard, it returns nothing and one may retry calling it afterward. Panic after the success of Init is an undesired behavior as discussed in #19.