/
clipboard.cpp
647 lines (512 loc) · 14.5 KB
/
clipboard.cpp
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
/*
clipboard.cpp
Работа с буфером обмена.
*/
/*
Copyright © 1996 Eugene Roshal
Copyright © 2000 Far Group
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. The name of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// BUGBUG
#include "platform.headers.hpp"
// Self:
#include "clipboard.hpp"
// Internal:
#include "console.hpp"
#include "encoding.hpp"
#include "eol.hpp"
#include "exception.hpp"
#include "log.hpp"
// Platform:
#include "platform.chrono.hpp"
// Common:
#include "common/enum_substrings.hpp"
#include "common/singleton.hpp"
#include "common/string_utils.hpp"
// External:
//----------------------------------------------------------------------------
void default_clipboard_mode::set(clipboard_mode Mode) noexcept
{
m_Mode = Mode;
}
clipboard_mode default_clipboard_mode::get() noexcept
{
return m_Mode;
}
//-----------------------------------------------------------------------------
enum class clipboard::clipboard_format
{
vertical_block_oem,
vertical_block_unicode,
preferred_drop_effect,
ms_dev_column_select,
borland_ide_dev_block,
notepad_plusplus_binary_text_length,
count
};
//-----------------------------------------------------------------------------
class system_clipboard final: public clipboard, public singleton<system_clipboard>
{
IMPLEMENTS_SINGLETON;
public:
~system_clipboard() override
{
system_clipboard::Close();
}
bool Open() override
{
assert(!m_Opened);
if (m_Opened)
return false;
// Clipboard is a shared resource
const size_t Attempts = 5;
for (const auto& i: irange(Attempts))
{
if (OpenClipboard(console.GetWindow()))
{
m_Opened = true;
return true;
}
os::chrono::sleep_for((i + 1) * 50ms);
}
return false;
}
bool Close() noexcept override
{
// Closing already closed buffer is OK
if (!m_Opened)
return true;
if (!CloseClipboard())
{
LOGWARNING(L"CloseClipboard(): {}"sv, last_error());
return false;
}
m_Opened = false;
return true;
}
bool Clear() override
{
assert(m_Opened);
return EmptyClipboard() != FALSE;
}
private:
system_clipboard() = default;
HANDLE GetData(unsigned uFormat) const override
{
assert(m_Opened);
return GetClipboardData(uFormat);
}
bool SetData(unsigned const Format, os::memory::global::ptr&& Data) override
{
assert(m_Opened);
if (!SetClipboardData(Format, Data.get()))
{
LOGWARNING(L"SetClipboardData(): {}"sv, last_error());
return false;
}
// Owned by the OS now
(void)Data.release();
return true;
}
unsigned RegisterFormat(clipboard_format Format) const override
{
static std::pair<const wchar_t*, unsigned> FormatNames[] =
{
{ L"FAR_VerticalBlock", 0 },
{ L"FAR_VerticalBlock_Unicode", 0 },
{ CFSTR_PREFERREDDROPEFFECT, 0 },
{ L"MSDEVColumnSelect", 0 },
{ L"Borland IDE Block Type", 0 },
{ L"Notepad++ binary text length", 0 },
};
static_assert(std::size(FormatNames) == static_cast<size_t>(clipboard_format::count));
assert(Format < clipboard_format::count);
auto& [FormatName, FormatId] = FormatNames[static_cast<unsigned>(Format)];
if (!FormatId)
{
FormatId = RegisterClipboardFormat(FormatName);
if (!FormatId)
{
LOGWARNING(L"RegisterClipboardFormat(): {}"sv, last_error());
}
}
return FormatId;
}
bool IsFormatAvailable(unsigned Format) const override
{
return Format && IsClipboardFormatAvailable(Format);
}
};
//-----------------------------------------------------------------------------
class internal_clipboard final: public clipboard, public singleton<internal_clipboard>
{
IMPLEMENTS_SINGLETON;
public:
static auto CreateInstance()
{
return std::unique_ptr<clipboard>(new internal_clipboard);
}
~internal_clipboard() override
{
internal_clipboard::Close();
}
bool Open() override
{
assert(!m_Opened);
if (m_Opened)
return false;
m_Opened = true;
return true;
}
bool Close() noexcept override
{
// Closing already closed buffer is OK
m_Opened = false;
return true;
}
bool Clear() override
{
assert(m_Opened);
if (!m_Opened)
return false;
m_InternalData.clear();
return true;
}
private:
internal_clipboard() = default;
HANDLE GetData(unsigned uFormat) const override
{
assert(m_Opened);
if (!m_Opened || !uFormat)
return nullptr;
const auto ItemIterator = m_InternalData.find(uFormat);
return ItemIterator != m_InternalData.cend()? ItemIterator->second.get() : nullptr;
}
bool SetData(unsigned uFormat, os::memory::global::ptr&& hMem) override
{
assert(m_Opened);
if (!m_Opened)
return false;
m_InternalData[uFormat] = std::move(hMem);
return true;
}
unsigned RegisterFormat(clipboard_format Format) const override
{
enum { FarClipboardMagic = 0xFC };
return static_cast<unsigned>(Format) + FarClipboardMagic;
}
bool IsFormatAvailable(unsigned Format) const override
{
return Format && contains(m_InternalData, Format);
}
std::unordered_map<unsigned, os::memory::global::ptr> m_InternalData;
};
//-----------------------------------------------------------------------------
static thread_local clipboard* OverridenInternalClipboard;
void clipboard_restorer::operator()(const clipboard* Clip) const noexcept
{
OverridenInternalClipboard = nullptr;
delete Clip;
}
std::unique_ptr<clipboard, clipboard_restorer> OverrideClipboard()
{
auto ClipPtr = internal_clipboard::CreateInstance();
OverridenInternalClipboard = ClipPtr.get();
return std::unique_ptr<clipboard, clipboard_restorer>(ClipPtr.release());
}
clipboard& clipboard::GetInstance(clipboard_mode Mode)
{
if (OverridenInternalClipboard)
return *OverridenInternalClipboard;
if (Mode == clipboard_mode::system)
return system_clipboard::instance();
return internal_clipboard::instance();
}
bool clipboard::SetText(const string_view Str)
{
if (!Clear())
return false;
auto hData = os::memory::global::copy(Str);
if (!hData)
return false;
if (!SetData(CF_UNICODETEXT, std::move(hData)))
return false;
// 'Notepad++ binary text length'
// return value is ignored - non-critical feature
if (const auto Format = RegisterFormat(clipboard_format::notepad_plusplus_binary_text_length))
SetData(Format, os::memory::global::copy(static_cast<uint32_t>(Str.size())));
// return value is ignored - non-critical feature
if (auto Locale = os::memory::global::copy(GetUserDefaultLCID()))
SetData(CF_LOCALE, std::move(Locale));
return true;
}
bool clipboard::SetVText(const string_view Str)
{
if (!SetText(Str))
return false;
const auto FarVerticalBlock = RegisterFormat(clipboard_format::vertical_block_unicode);
if (!FarVerticalBlock)
return false;
if (!SetData(FarVerticalBlock, os::memory::global::copy(0)))
return false;
// 'Borland IDE Block Type'
// return value is ignored - non-critical feature
if (const auto Format = RegisterFormat(clipboard_format::borland_ide_dev_block))
SetData(Format, os::memory::global::copy('\x02'));
// 'MSDEVColumnSelect'
// return value is ignored - non-critical feature
if (const auto Format = RegisterFormat(clipboard_format::ms_dev_column_select))
SetData(Format, os::memory::global::copy(0));
return true;
}
bool clipboard::SetHDROP(const string_view NamesData, const bool bMoved)
{
if (NamesData.empty())
return false;
auto Memory = os::memory::global::alloc(GMEM_MOVEABLE, sizeof(DROPFILES) + (NamesData.size() + 1) * sizeof(wchar_t));
if (!Memory)
return false;
const auto Drop = os::memory::global::lock<LPDROPFILES>(Memory);
if (!Drop)
return false;
Drop->pFiles = sizeof(DROPFILES);
Drop->pt.x = 0;
Drop->pt.y = 0;
Drop->fNC = TRUE;
Drop->fWide = TRUE;
*copy_string(NamesData, edit_as<wchar_t*>(Drop.get() + 1)) = {};
if (!Clear() || !SetData(CF_HDROP, std::move(Memory)))
return false;
if (!bMoved)
return true;
auto hMemoryMove = os::memory::global::copy<DWORD>(DROPEFFECT_MOVE);
if (!hMemoryMove)
return false;
if (const auto Format = RegisterFormat(clipboard_format::preferred_drop_effect))
return SetData(Format, std::move(hMemoryMove));
return false;
}
bool clipboard::GetText(string& Data) const
{
const auto hClipData = GetData(CF_UNICODETEXT);
if (!hClipData)
return GetHDROPAsText(Data);
const auto ClipAddr = os::memory::global::lock<const wchar_t*>(hClipData);
if (!ClipAddr)
return false;
const auto GetBinaryTextLength = [this]
{
const auto Format = RegisterFormat(clipboard_format::notepad_plusplus_binary_text_length);
if (!Format)
return string::npos;
const auto hClipDataLen = GetData(Format);
if (!hClipDataLen)
return string::npos;
const auto ClipLength = os::memory::global::lock<const uint32_t*>(hClipDataLen);
return ClipLength? static_cast<size_t>(*ClipLength) : string::npos;
};
const auto DataSize = GetBinaryTextLength();
Data.assign(ClipAddr.get(), DataSize == string::npos? std::wcslen(ClipAddr.get()) : DataSize);
return true;
}
bool clipboard::GetHDROPAsText(string& data) const
{
const auto hClipData = GetData(CF_HDROP);
if (!hClipData)
return false;
const auto Files = os::memory::global::lock<const DROPFILES*>(hClipData);
if (!Files)
return false;
const auto StartA = view_as<const char*>(Files.get(), Files->pFiles);
const auto Eol = eol::system.str();
if (Files->fWide)
{
const auto Start = view_as<const wchar_t*>(StartA);
for (const auto& i: enum_substrings(Start))
{
append(data, i, Eol);
}
}
else
{
for (const auto& i: enum_substrings(StartA))
{
append(data, encoding::ansi::get_chars(i), Eol);
}
}
return true;
}
bool clipboard::GetVText(string& Data) const
{
const auto IsBorlandVerticalBlock = [this]
{
const auto Format = RegisterFormat(clipboard_format::borland_ide_dev_block);
if (!Format)
return false;
const auto hClipData = GetData(Format);
if (!hClipData)
return false;
const auto ClipAddr = os::memory::global::lock<const char*>(hClipData);
return ClipAddr && *ClipAddr == 0x02;
};
if (IsFormatAvailable(RegisterFormat(clipboard_format::vertical_block_unicode)) ||
IsFormatAvailable(RegisterFormat(clipboard_format::ms_dev_column_select)) ||
IsBorlandVerticalBlock())
{
return GetText(Data);
}
const auto Format = RegisterFormat(clipboard_format::vertical_block_oem);
if (!Format)
return false;
const auto hClipData = GetData(Format);
if (!hClipData)
return false;
const auto OemData = os::memory::global::lock<const char*>(hClipData);
if (!OemData)
return false;
encoding::oem::get_chars(OemData.get(), Data);
return true;
}
//-----------------------------------------------------------------------------
bool SetClipboardText(const string_view Str)
{
const clipboard_accessor Clip;
return Clip->Open() && Clip->SetText(Str);
}
bool SetClipboardVText(const string_view Str)
{
const clipboard_accessor Clip;
return Clip->Open() && Clip->SetVText(Str);
}
bool GetClipboardText(string& data)
{
const clipboard_accessor Clip;
return Clip->Open() && Clip->GetText(data);
}
bool GetClipboardVText(string& data)
{
const clipboard_accessor Clip;
return Clip->Open() && Clip->GetVText(data);
}
bool ClearClipboard()
{
const clipboard_accessor Clip;
return Clip->Open() && Clip->Clear();
}
bool ClearInternalClipboard()
{
const clipboard_accessor Clip(clipboard_mode::internal);
return Clip->Open() && Clip->Clear();
}
bool CopyData(const clipboard_accessor& From, const clipboard_accessor& To)
{
string Data;
if (From->GetVText(Data))
{
return To->SetVText(Data);
}
if (From->GetText(Data))
{
return To->SetText(Data);
}
return false;
}
#ifdef ENABLE_TESTS
#include "testing.hpp"
class clipboard_guard
{
public:
NONCOPYABLE(clipboard_guard);
clipboard_guard()
{
const clipboard_accessor Clip(clipboard_mode::system);
if (!Clip->Open())
return;
m_Data.reserve(CountClipboardFormats());
for (auto i = EnumClipboardFormats(0); i; i = EnumClipboardFormats(i))
{
if (i == CF_BITMAP || i == CF_ENHMETAFILE)
continue;
m_Data.emplace_back(i, os::memory::global::copy(GetClipboardData(i)));
}
}
~clipboard_guard()
{
if (m_Data.empty())
return;
const clipboard_accessor Clip(clipboard_mode::system);
if (!Clip->Open())
return;
for (auto& [Format, Data]: m_Data)
{
SetClipboardData(Format, Data.release());
}
}
private:
std::vector<std::pair<unsigned, os::memory::global::ptr>> m_Data;
};
TEST_CASE("clipboard.stream")
{
SCOPED_ACTION(clipboard_guard);
const auto Baseline = L"\0 Comfortably Numb \0"sv;
string Str;
const auto Mode = default_clipboard_mode::get();
const std::array Types
{
std::pair{&SetClipboardText, &GetClipboardText},
std::pair{&SetClipboardVText, &GetClipboardVText},
};
for (const auto i: { clipboard_mode::system, clipboard_mode::internal })
{
default_clipboard_mode::set(i);
for (const auto& [Set, Get]: Types)
{
REQUIRE(Set(Baseline));
REQUIRE(Get(Str));
REQUIRE(Str == Baseline);
REQUIRE(ClearClipboard());
REQUIRE(!Get(Str));
}
}
default_clipboard_mode::set(Mode);
}
TEST_CASE("clipboard.accessors")
{
SCOPED_ACTION(clipboard_guard);
const auto Baseline = L"\0 Hey Macarena \0"sv;
string Str;
const clipboard_accessor
ClipSystem(clipboard_mode::system),
ClipInternal(clipboard_mode::internal);
REQUIRE(ClipSystem->Open());
REQUIRE(ClipSystem->SetText(Baseline));
REQUIRE(ClipInternal->Open());
REQUIRE(CopyData(ClipSystem, ClipInternal));
REQUIRE(ClipSystem->Clear());
REQUIRE(ClipSystem->Close());
REQUIRE(ClipInternal->GetText(Str));
REQUIRE(ClipInternal->Clear());
REQUIRE(ClipInternal->Close());
REQUIRE(Str == Baseline);
}
#endif