File: juce_linux_X11_Clipboard.cpp

package info (click to toggle)
juce 5.4.7~ds0-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 46,252 kB
  • sloc: cpp: 367,378; java: 7,200; ansic: 796; xml: 247; sh: 192; makefile: 152; cs: 132; python: 123
file content (280 lines) | stat: -rw-r--r-- 10,738 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
/*
  ==============================================================================

   This file is part of the JUCE library.
   Copyright (c) 2017 - ROLI Ltd.

   JUCE is an open source library subject to commercial or open-source
   licensing.

   By using JUCE, you agree to the terms of both the JUCE 5 End-User License
   Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
   27th April 2017).

   End User License Agreement: www.juce.com/juce-5-licence
   Privacy Policy: www.juce.com/juce-5-privacy-policy

   Or: You may also use this code under the terms of the GPL v3 (see
   www.gnu.org/licenses).

   JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
   EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
   DISCLAIMED.

  ==============================================================================
*/

namespace juce
{

extern ::Window juce_messageWindowHandle;

namespace ClipboardHelpers
{
    static String localClipboardContent;
    static Atom   atom_UTF8_STRING;
    static Atom   atom_CLIPBOARD;
    static Atom   atom_TARGETS;

    //==============================================================================
    static void initSelectionAtoms (::Display* display)
    {
        static bool isInitialised = false;

        if (! isInitialised)
        {
            isInitialised = true;

            atom_UTF8_STRING = Atoms::getCreating (display, "UTF8_STRING");
            atom_CLIPBOARD   = Atoms::getCreating (display, "CLIPBOARD");
            atom_TARGETS     = Atoms::getCreating (display, "TARGETS");
        }
    }

    //==============================================================================
    // Read the content of a window property as either a locale-dependent string or an utf8 string
    // works only for strings shorter than 1000000 bytes
    static String readWindowProperty (::Display* display, Window window, Atom prop)
    {
        String returnData;

        if (display != nullptr)
        {
            char* clipData;
            Atom actualType;
            int actualFormat;
            unsigned long numItems, bytesLeft;

            if (XGetWindowProperty (display, window, prop,
                                    0L /* offset */, 1000000 /* length (max) */, False,
                                    AnyPropertyType /* format */,
                                    &actualType, &actualFormat, &numItems, &bytesLeft,
                                    (unsigned char**) &clipData) == Success)
            {
                if (actualType == atom_UTF8_STRING && actualFormat == 8)
                    returnData = String::fromUTF8 (clipData, (int) numItems);
                else if (actualType == XA_STRING && actualFormat == 8)
                    returnData = String (clipData, numItems);

                if (clipData != nullptr)
                    XFree (clipData);

                jassert (bytesLeft == 0 || numItems == 1000000);
            }

            XDeleteProperty (display, window, prop);
        }

        return returnData;
    }

    //==============================================================================
    // Send a SelectionRequest to the window owning the selection and waits for its answer (with a timeout) */
    static bool requestSelectionContent (::Display* display, String& selectionContent,
                                         Atom selection, Atom requestedFormat)
    {
        Atom property_name = XInternAtom (display, "JUCE_SEL", false);

        // The selection owner will be asked to set the JUCE_SEL property on the
        // juce_messageWindowHandle with the selection content
        XConvertSelection (display, selection, requestedFormat, property_name,
                           juce_messageWindowHandle, CurrentTime);

        int count = 50; // will wait at most for 200 ms

        while (--count >= 0)
        {
            XEvent event;

            if (XCheckTypedWindowEvent (display, juce_messageWindowHandle, SelectionNotify, &event))
            {
                if (event.xselection.property == property_name)
                {
                    jassert (event.xselection.requestor == juce_messageWindowHandle);

                    selectionContent = readWindowProperty (display, event.xselection.requestor,
                                                           event.xselection.property);
                    return true;
                }

                return false;  // the format we asked for was denied.. (event.xselection.property == None)
            }

            // not very elegant.. we could do a select() or something like that...
            // however clipboard content requesting is inherently slow on x11, it
            // often takes 50ms or more so...
            Thread::sleep (4);
        }

        return false;
    }

    //==============================================================================
    // Called from the event loop in juce_linux_Messaging in response to SelectionRequest events
    static void handleSelection (XSelectionRequestEvent& evt)
    {
        ClipboardHelpers::initSelectionAtoms (evt.display);

        // the selection content is sent to the target window as a window property
        XSelectionEvent reply;
        reply.type = SelectionNotify;
        reply.display = evt.display;
        reply.requestor = evt.requestor;
        reply.selection = evt.selection;
        reply.target = evt.target;
        reply.property = None; // == "fail"
        reply.time = evt.time;

        HeapBlock<char> data;
        int propertyFormat = 0;
        size_t numDataItems = 0;

        if (evt.selection == XA_PRIMARY || evt.selection == ClipboardHelpers::atom_CLIPBOARD)
        {
            if (evt.target == XA_STRING || evt.target == ClipboardHelpers::atom_UTF8_STRING)
            {
                // translate to utf8
                numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsUTF8() + 1;
                data.calloc (numDataItems + 1);
                ClipboardHelpers::localClipboardContent.copyToUTF8 (data, numDataItems);
                propertyFormat = 8; // bits/item
            }
            else if (evt.target == ClipboardHelpers::atom_TARGETS)
            {
                // another application wants to know what we are able to send
                numDataItems = 2;
                propertyFormat = 32; // atoms are 32-bit
                data.calloc (numDataItems * 4);
                Atom* atoms = reinterpret_cast<Atom*> (data.getData());
                atoms[0] = ClipboardHelpers::atom_UTF8_STRING;
                atoms[1] = XA_STRING;

                evt.target = XA_ATOM;
            }
        }
        else
        {
            DBG ("requested unsupported clipboard");
        }

        if (data != nullptr)
        {
            const size_t maxReasonableSelectionSize = 1000000;

            // for very big chunks of data, we should use the "INCR" protocol , which is a pain in the *ss
            if (evt.property != None && numDataItems < maxReasonableSelectionSize)
            {
                XChangeProperty (evt.display, evt.requestor,
                                 evt.property, evt.target,
                                 propertyFormat /* 8 or 32 */, PropModeReplace,
                                 reinterpret_cast<const unsigned char*> (data.getData()), (int) numDataItems);
                reply.property = evt.property; // " == success"
            }
        }

        XSendEvent (evt.display, evt.requestor, 0, NoEventMask, (XEvent*) &reply);
    }
}

//==============================================================================
typedef void (*SelectionRequestCallback) (XSelectionRequestEvent&);
extern SelectionRequestCallback handleSelectionRequest;

struct ClipboardCallbackInitialiser
{
    ClipboardCallbackInitialiser()
    {
        handleSelectionRequest = ClipboardHelpers::handleSelection;
    }
};

static ClipboardCallbackInitialiser clipboardInitialiser;

//==============================================================================
void SystemClipboard::copyTextToClipboard (const String& clipText)
{
    ScopedXDisplay xDisplay;

    if (auto display = xDisplay.display)
    {
        ClipboardHelpers::initSelectionAtoms (display);
        ClipboardHelpers::localClipboardContent = clipText;

        XSetSelectionOwner (display, XA_PRIMARY, juce_messageWindowHandle, CurrentTime);
        XSetSelectionOwner (display, ClipboardHelpers::atom_CLIPBOARD, juce_messageWindowHandle, CurrentTime);
    }
}

String SystemClipboard::getTextFromClipboard()
{
    String content;
    ScopedXDisplay xDisplay;

    if (auto display = xDisplay.display)
    {
        ClipboardHelpers::initSelectionAtoms (display);

        /* 1) try to read from the "CLIPBOARD" selection first (the "high
           level" clipboard that is supposed to be filled by ctrl-C
           etc). When a clipboard manager is running, the content of this
           selection is preserved even when the original selection owner
           exits.

           2) and then try to read from "PRIMARY" selection (the "legacy" selection
           filled by good old x11 apps such as xterm)
        */
        Atom selection = XA_PRIMARY;
        Window selectionOwner = None;

        if ((selectionOwner = XGetSelectionOwner (display, selection)) == None)
        {
            selection = ClipboardHelpers::atom_CLIPBOARD;
            selectionOwner = XGetSelectionOwner (display, selection);
        }

        if (selectionOwner != None)
        {
            if (selectionOwner == juce_messageWindowHandle)
            {
                content = ClipboardHelpers::localClipboardContent;
            }
            else
            {
                // first try: we want an utf8 string
                bool ok = ClipboardHelpers::requestSelectionContent (display, content,
                                                                     selection, ClipboardHelpers::atom_UTF8_STRING);

                if (! ok)
                {
                    // second chance, ask for a good old locale-dependent string ..
                    ok = ClipboardHelpers::requestSelectionContent (display, content,
                                                                    selection, XA_STRING);
                }
            }
        }
    }

    return content;
}

} // namespace juce