summaryrefslogtreecommitdiffstats
path: root/src/VBox/ValidationKit/utils/clipboard/ClipUtil.cpp
blob: 4c1e10c5f9332dff1aaa62d491895126a2ead012 (plain)
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
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
/* $Id: ClipUtil.cpp $ */
/** @file
 * ClipUtil - Clipboard Utility
 */

/*
 * Copyright (C) 2021-2023 Oracle and/or its affiliates.
 *
 * This file is part of VirtualBox base platform packages, as
 * available from https://www.virtualbox.org.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation, in version 3 of the
 * License.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <https://www.gnu.org/licenses>.
 *
 * The contents of this file may alternatively be used under the terms
 * of the Common Development and Distribution License Version 1.0
 * (CDDL), a copy of it is provided in the "COPYING.CDDL" file included
 * in the VirtualBox distribution, in which case the provisions of the
 * CDDL are applicable instead of those of the GPL.
 *
 * You may elect to license modified versions of this file under the
 * terms and conditions of either the GPL or the CDDL or both.
 *
 * SPDX-License-Identifier: GPL-3.0-only OR CDDL-1.0
 */


/*********************************************************************************************************************************
*   Header Files                                                                                                                 *
*********************************************************************************************************************************/
#ifdef RT_OS_OS2
# define INCL_BASE
# define INCL_PM
# define INCL_ERRORS
# include <os2.h>
# undef RT_MAX
#endif

#include <iprt/assert.h>
#include <iprt/errcore.h>
#include <iprt/file.h>
#include <iprt/getopt.h>
#include <iprt/initterm.h>
#include <iprt/mem.h>
#include <iprt/message.h>
#include <iprt/process.h>
#include <iprt/string.h>
#include <iprt/stream.h>
#include <iprt/utf16.h>
#include <iprt/zero.h>

#ifdef RT_OS_DARWIN
/** @todo   */
#elif defined(RT_OS_WINDOWS)
# include <iprt/nt/nt-and-windows.h>
#elif !defined(RT_OS_OS2)
# include <X11/Xlib.h>
# include <X11/Xatom.h>
#endif


/*********************************************************************************************************************************
*   Defined Constants And Macros                                                                                                 *
*********************************************************************************************************************************/
#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2) || defined(RT_OS_DARWIN)
# undef MULTI_TARGET_CLIPBOARD
# undef CU_X11
#else
# define MULTI_TARGET_CLIPBOARD
# define CU_X11
#endif


/*********************************************************************************************************************************
*   Structures and Typedefs                                                                                                      *
*********************************************************************************************************************************/
/**
 * Clipboard format descriptor.
 */
typedef struct CLIPUTILFORMAT
{
    /** Format name. */
    const char *pszName;

#if defined(RT_OS_WINDOWS)
    /** Windows integer format (CF_XXXX). */
    UINT        fFormat;
    /** Windows string format name. */
    const WCHAR *pwszFormat;

#elif defined(RT_OS_OS2)
    /** OS/2 integer format. */
    ULONG       fFormat;
    /** OS/2 string format name. */
    const char *pszFormat;

#elif defined(RT_OS_DARWIN)
    /** Native format (flavor). */
    CFStringRef *hStrFormat;
#else
    /** The X11 atom for the format. */
    Atom        uAtom;
    /** The X11 atom name if uAtom must be termined dynamically. */
    const char *pszAtomName;
    /** @todo X11 */
#endif

    /** Description. */
    const char *pszDesc;
    /** CLIPUTILFORMAT_F_XXX. */
    uint32_t    fFlags;
} CLIPUTILFORMAT;
/** Pointer to a clipobard format descriptor. */
typedef CLIPUTILFORMAT const *PCCLIPUTILFORMAT;

/** Convert to/from UTF-8.  */
#define CLIPUTILFORMAT_F_CONVERT_UTF8       RT_BIT_32(0)
/** Ad hoc entry.  */
#define CLIPUTILFORMAT_F_AD_HOC             RT_BIT_32(1)


#ifdef MULTI_TARGET_CLIPBOARD
/**
 * Clipboard target descriptor.
 */
typedef struct CLIPUTILTARGET
{
    /** Target name.   */
    const char *pszName;
    /** The X11 atom for the target. */
    Atom        uAtom;
    /** The X11 atom name if uAtom must be termined dynamically. */
    const char *pszAtomName;
    /** Description. */
    const char *pszDesc;
} CLIPUTILTARGET;
/** Pointer to clipboard target descriptor. */
typedef CLIPUTILTARGET const *PCCLIPUTILTARGET;
#endif /* MULTI_TARGET_CLIPBOARD */


#ifdef RT_OS_OS2
/** Header for Odin32 specific clipboard entries.
 * (Used to get the correct size of the data.)
 */
typedef struct _Odin32ClipboardHeader
{
    /** Magic (CLIPHEADER_MAGIC) */
    char        achMagic[8];
    /** Size of the following data.
     * (The interpretation depends on the type.) */
    unsigned    cbData;
    /** Odin32 format number. */
    unsigned    uFormat;
} CLIPHEADER, *PCLIPHEADER;

#define CLIPHEADER_MAGIC "Odin\1\0\1"
#endif


/*********************************************************************************************************************************
*   Global Variables                                                                                                             *
*********************************************************************************************************************************/
/** Command line parameters */
static const RTGETOPTDEF g_aCmdOptions[] =
{
    { "--list",                     'l',                            RTGETOPT_REQ_NOTHING },
    { "--get",                      'g',                            RTGETOPT_REQ_STRING  },
    { "--get-file",                 'G',                            RTGETOPT_REQ_STRING  },
    { "--put",                      'p',                            RTGETOPT_REQ_STRING  },
    { "--put-file",                 'P',                            RTGETOPT_REQ_STRING  },
    { "--check",                    'c',                            RTGETOPT_REQ_STRING  },
    { "--check-file",               'C',                            RTGETOPT_REQ_STRING  },
    { "--check-not",                'n',                            RTGETOPT_REQ_STRING  },
    { "--zap",                      'z',                            RTGETOPT_REQ_NOTHING },
#ifdef MULTI_TARGET_CLIPBOARD
    { "--target",                   't',                            RTGETOPT_REQ_STRING  },
#endif
#if defined(RT_OS_OS2) || defined(RT_OS_WINDOWS)
    { "--close",                    'k',                            RTGETOPT_REQ_NOTHING },
#endif
    { "--wait",                     'w',                            RTGETOPT_REQ_UINT32 },
    { "--quiet",                    'q',                            RTGETOPT_REQ_NOTHING },
    { "--verbose",                  'v',                            RTGETOPT_REQ_NOTHING },
    { "--version",                  'V',                            RTGETOPT_REQ_NOTHING },
    { "--help",                     'h',                            RTGETOPT_REQ_NOTHING }, /* for Usage() */
};

/** Format descriptors. */
static CLIPUTILFORMAT g_aFormats[] =
{
#if defined(RT_OS_WINDOWS)
    { "text/ansi",                  CF_TEXT, NULL,              "ANSI text", 0 },
    { "text/utf-16",                CF_UNICODETEXT, NULL,       "UTF-16 text", 0 },
    { "text/utf-8",                 CF_UNICODETEXT, NULL,       "UTF-8 text", CLIPUTILFORMAT_F_CONVERT_UTF8 },
    /* https://docs.microsoft.com/en-us/windows/desktop/dataxchg/html-clipboard-format */
    { "text/html",                  0, L"HTML Format",          "HTML text", 0 },
    { "bitmap",                     CF_DIB, NULL,               "Bitmap (DIB)", 0 },
    { "bitmap/v5",                  CF_DIBV5, NULL,             "Bitmap version 5 (DIBv5)", 0 },
#elif defined(RT_OS_OS2)
    { "text/ascii",                 CF_TEXT, NULL,              "ASCII text", 0 },
    { "text/utf-8",                 CF_TEXT, NULL,              "UTF-8 text", CLIPUTILFORMAT_F_CONVERT_UTF8 },
    { "text/utf-16",                0, "Odin32 UnicodeText",    "UTF-16 text", 0},
#elif defined(RT_OS_DARWIN)
    { "text/utf-8",                 kUTTypeUTF8PlainText,       "UTF-8 text", 0 },
    { "text/utf-16",                kUTTypeUTF16PlainText,      "UTF-16 text", 0 },
#else
    /** @todo X11   */
    { "text/utf-8",                 None, "UTF8_STRING",       "UTF-8 text", 0 },
#endif
};

#ifdef MULTI_TARGET_CLIPBOARD
/** Target descriptors. */
static CLIPUTILTARGET g_aTargets[] =
{
    { "clipboard", 0, "CLIPBOARD",     "XA_CLIPBOARD: The clipboard (default)" },
    { "primary",   XA_PRIMARY,   NULL, "XA_PRIMARY:   Primary selected text (middle mouse button)" },
    { "secondary", XA_SECONDARY, NULL, "XA_SECONDARY: Secondary selected text (with ctrl)" },
};

/** The current clipboard target. */
static CLIPUTILTARGET *g_pTarget = &g_aTargets[0];
#endif /* MULTI_TARGET_CLIPBOARD */

/** The -v/-q state. */
static unsigned g_uVerbosity = 1;

#ifdef RT_OS_DARWIN

#elif defined(RT_OS_OS2)
/** Anchorblock handle. */
static HAB      g_hOs2Ab = NULLHANDLE;
/** The message queue handle.   */
static HMQ      g_hOs2MsgQueue = NULLHANDLE;
/** Windows that becomes clipboard owner when setting data. */
static HWND     g_hOs2Wnd = NULLHANDLE;
/** Set if we've opened the clipboard. */
static bool     g_fOs2OpenedClipboard = false;
/** Set if we're the clipboard owner. */
static bool     g_fOs2ClipboardOwner = false;
/** Set when we receive a WM_TIMER message during DoWait(). */
static bool volatile g_fOs2TimerTicked = false;

#elif defined(RT_OS_WINDOWS)
/** Set if we've opened the clipboard. */
static bool     g_fWinOpenedClipboard = false;
/** Set when we receive a WM_TIMER message during DoWait(). */
static bool volatile g_fWinTimerTicked = false;
/** Window that becomes clipboard owner when setting data. */
static HWND     g_hWinWnd = NULL;

#else
/** Number of errors (incremented by error handle callback). */
static uint32_t volatile g_cX11Errors;
/** The X11 display. */
static Display *g_pX11Display = NULL;
/** The X11 dummy window.   */
static Window   g_hX11Window = 0;
/** TARGETS */
static Atom     g_uX11AtomTargets;
/** MULTIPLE */
static Atom     g_uX11AtomMultiple;

#endif


/**
 * Gets a format descriptor, complaining if invalid format.
 *
 * @returns Pointer to the descriptor if found, NULL + msg if not.
 * @param   pszFormat           The format to get.
 */
static PCCLIPUTILFORMAT GetFormatDesc(const char *pszFormat)
{
    for (size_t i = 0; i < RT_ELEMENTS(g_aFormats); i++)
        if (strcmp(pszFormat, g_aFormats[i].pszName) == 0)
        {
#if defined(RT_OS_DARWIN)
            /** @todo   */

#elif defined(RT_OS_OS2)
            if (g_aFormats[i].pszFormat && g_aFormats[i].fFormat == 0)
            {
                g_aFormats[i].fFormat = WinAddAtom(WinQuerySystemAtomTable(), g_aFormats[i].pszFormat);
                if (g_aFormats[i].fFormat == 0)
                    RTMsgError("WinAddAtom(,%s) failed: %#x", g_aFormats[i].pszFormat, WinGetLastError(g_hOs2Ab));
            }

#elif defined(RT_OS_WINDOWS)
            if (g_aFormats[i].pwszFormat && g_aFormats[i].fFormat == 0)
            {
                g_aFormats[i].fFormat = RegisterClipboardFormatW(g_aFormats[i].pwszFormat);
                if (g_aFormats[i].fFormat == 0)
                    RTMsgError("RegisterClipboardFormatW(%ls) failed: %u (%#x)",
                               g_aFormats[i].pwszFormat, GetLastError(), GetLastError());
            }
#elif defined(CU_X11)
            if (g_aFormats[i].pszAtomName && g_aFormats[i].uAtom == 0)
                g_aFormats[i].uAtom = XInternAtom(g_pX11Display, g_aFormats[i].pszAtomName, False);
#endif
            return &g_aFormats[i];
        }

    /*
     * Try register the format.
     */
    static CLIPUTILFORMAT AdHoc;
    AdHoc.pszName     = pszFormat;
    AdHoc.pszDesc     = pszFormat;
    AdHoc.fFlags      = CLIPUTILFORMAT_F_AD_HOC;
#ifdef RT_OS_DARWIN
/** @todo   */

#elif defined(RT_OS_OS2)
    AdHoc.pszFormat   = pszFormat;
    AdHoc.fFormat     = WinAddAtom(WinQuerySystemAtomTable(), pszFormat);
    if (AdHoc.fFormat == 0)
    {
        RTMsgError("Invalid format '%s' (%#x)", pszFormat, WinGetLastError(g_hOs2Ab));
        return NULL;
    }

#elif defined(RT_OS_WINDOWS)
    AdHoc.pwszFormat  = NULL;
    AdHoc.fFormat     = RegisterClipboardFormatA(pszFormat);
    if (AdHoc.fFormat == 0)
    {
        RTMsgError("RegisterClipboardFormatA(%s) failed: %u (%#x)", pszFormat, GetLastError(), GetLastError());
        return NULL;
    }

#else
    AdHoc.pszAtomName = pszFormat;
    AdHoc.uAtom       = XInternAtom(g_pX11Display, pszFormat, False);
    if (AdHoc.uAtom == None)
    {
        RTMsgError("Invalid format '%s' or out of memory for X11 atoms", pszFormat);
        return NULL;
    }

#endif
    return &AdHoc;
}


#ifdef RT_OS_DARWIN

/** @todo   */


#elif defined(RT_OS_OS2)

/**
 * The window procedure for the object window.
 *
 * @returns Message result.
 *
 * @param   hwnd    The window handle.
 * @param   msg     The message.
 * @param   mp1     Message parameter 1.
 * @param   mp2     Message parameter 2.
 */
static MRESULT EXPENTRY CuOs2WinProc(HWND hwnd, ULONG msg, MPARAM mp1, MPARAM mp2)
{
    if (g_uVerbosity > 2)
        RTMsgInfo("CuOs2WinProc: hwnd=%#lx msg=%#lx mp1=%#lx mp2=%#lx\n", hwnd, msg, mp1, mp2);

    switch (msg)
    {
        case WM_CREATE:
            return NULL; /* FALSE(/NULL) == Continue*/
        case WM_DESTROY:
            break;

        /*
         * Clipboard viewer message - the content has been changed.
         * This is sent *after* releasing the clipboard sem
         * and during the WinSetClipbrdViewer call.
         */
        case WM_DRAWCLIPBOARD:
            break;

        /*
         * Clipboard owner message - the content was replaced.
         * This is sent by someone with an open clipboard, so don't try open it now.
         */
        case WM_DESTROYCLIPBOARD:
            break;

        /*
         * Clipboard owner message - somebody is requesting us to render a format.
         * This is called by someone which owns the clipboard, but that's fine.
         */
        case WM_RENDERFMT:
            break;

        /*
         * Clipboard owner message - we're about to quit and should render all formats.
         */
        case WM_RENDERALLFMTS:
            break;

        /*
         * Clipboard owner messages dealing with owner drawn content.
         * We shouldn't be seeing any of these.
         */
        case WM_PAINTCLIPBOARD:
        case WM_SIZECLIPBOARD:
        case WM_HSCROLLCLIPBOARD:
        case WM_VSCROLLCLIPBOARD:
            AssertMsgFailed(("msg=%lx (%ld)\n", msg, msg));
            break;

        /*
         * We shouldn't be seeing any other messages according to the docs.
         * But for whatever reason, PM sends us a WM_ADJUSTWINDOWPOS message
         * during WinCreateWindow. So, ignore that and assert on anything else.
         */
        default:
            AssertMsgFailed(("msg=%lx (%ld)\n", msg, msg));
        case WM_ADJUSTWINDOWPOS:
            break;

        /*
         * We use this window fielding WM_TIMER during DoWait.
         */
        case WM_TIMER:
            if (SHORT1FROMMP(mp1) == 1)
                g_fOs2TimerTicked = true;
            break;
    }
    return NULL;
}


/**
 * Initialize the OS/2 bits.
 */
static RTEXITCODE CuOs2Init(void)
{
    g_hOs2Ab = WinInitialize(0);
    if (g_hOs2Ab == NULLHANDLE)
        return RTMsgErrorExitFailure("WinInitialize failed!");

    g_hOs2MsgQueue = WinCreateMsgQueue(g_hOs2Ab, 10);
    if (g_hOs2MsgQueue == NULLHANDLE)
        return RTMsgErrorExitFailure("WinCreateMsgQueue failed: %#x", WinGetLastError(g_hOs2Ab));

    static char s_szClass[] = "VBox-ClipUtilClipboardClass";
    if (!WinRegisterClass(g_hOs2Wnd, (PCSZ)s_szClass, CuOs2WinProc, 0, 0))
        return RTMsgErrorExitFailure("WinRegisterClass failed: %#x", WinGetLastError(g_hOs2Ab));

    g_hOs2Wnd = WinCreateWindow(HWND_OBJECT,                             /* hwndParent */
                                (PCSZ)s_szClass,                         /* pszClass */
                                (PCSZ)"VirtualBox Clipboard Utility",    /* pszName */
                                0,                                       /* flStyle */
                                0, 0, 0, 0,                              /* x, y, cx, cy */
                                NULLHANDLE,                              /* hwndOwner */
                                HWND_BOTTOM,                             /* hwndInsertBehind */
                                42,                                      /* id */
                                NULL,                                    /* pCtlData */
                                NULL);                                   /* pPresParams */
    if (g_hOs2Wnd == NULLHANDLE)
        return RTMsgErrorExitFailure("WinCreateWindow failed: %#x", WinGetLastError(g_hOs2Ab));

    return RTEXITCODE_SUCCESS;
}


/**
 * Terminates the OS/2 bits.
 */
static RTEXITCODE CuOs2Term(void)
{
    if (g_fOs2OpenedClipboard)
    {
        if (!WinCloseClipbrd(g_hOs2Ab))
            return RTMsgErrorExitFailure("WinCloseClipbrd failed: %#x", WinGetLastError(g_hOs2Ab));
        g_fOs2OpenedClipboard = false;
    }

    WinDestroyWindow(g_hOs2Wnd);
    g_hOs2Wnd = NULLHANDLE;

    WinDestroyMsgQueue(g_hOs2MsgQueue);
    g_hOs2MsgQueue = NULLHANDLE;

    WinTerminate(g_hOs2Ab);
    g_hOs2Ab = NULLHANDLE;

    return RTEXITCODE_SUCCESS;
}


/**
 * Opens the OS/2 clipboard.
 */
static RTEXITCODE CuOs2OpenClipboardIfNecessary(void)
{
    if (g_fOs2OpenedClipboard)
        return RTEXITCODE_SUCCESS;
    if (WinOpenClipbrd(g_hOs2Ab))
    {
        if (g_uVerbosity > 0)
            RTMsgInfo("Opened the clipboard\n");
        g_fOs2OpenedClipboard = true;
        return RTEXITCODE_SUCCESS;
    }
    return RTMsgErrorExitFailure("WinOpenClipbrd failed: %#x", WinGetLastError(g_hOs2Ab));
}


#elif defined(RT_OS_WINDOWS)

/**
 * Window procedure for the clipboard owner window on Windows.
 */
static LRESULT CALLBACK CuWinWndProc(HWND hWnd, UINT idMsg, WPARAM wParam, LPARAM lParam) RT_NOTHROW_DEF
{
    if (g_uVerbosity > 2)
        RTMsgInfo("CuWinWndProc: hWnd=%p idMsg=%#05x wParam=%#zx lParam=%#zx\n", hWnd, idMsg, wParam, lParam);

    switch (idMsg)
    {
        case WM_TIMER:
            if (wParam == 1)
                g_fWinTimerTicked = true;
            break;
    }
    return DefWindowProc(hWnd, idMsg, wParam, lParam);
}


/**
 * Initialize the Windows bits.
 */
static RTEXITCODE CuWinInit(void)
{
    /* Register the window class: */
    static wchar_t s_wszClass[] = L"VBox-ClipUtilClipboardClass";
    WNDCLASSW WndCls = {0};
    WndCls.style            = CS_NOCLOSE;
    WndCls.lpfnWndProc      = CuWinWndProc;
    WndCls.cbClsExtra       = 0;
    WndCls.cbWndExtra       = 0;
    WndCls.hInstance        = (HINSTANCE)GetModuleHandle(NULL);
    WndCls.hIcon            = NULL;
    WndCls.hCursor          = NULL;
    WndCls.hbrBackground    = (HBRUSH)(COLOR_BACKGROUND + 1);
    WndCls.lpszMenuName     = NULL;
    WndCls.lpszClassName    = s_wszClass;

    ATOM uAtomWndClass      = RegisterClassW(&WndCls);
    if (!uAtomWndClass)
        return RTMsgErrorExitFailure("RegisterClassW failed: %u (%#x)", GetLastError(), GetLastError());

    /* Create the clipboard owner window: */
    g_hWinWnd = CreateWindowExW(WS_EX_TRANSPARENT,                      /* fExStyle */
                                s_wszClass,                             /* pwszClass */
                                L"VirtualBox Clipboard Utility",        /* pwszName */
                                0,                                      /* fStyle */
                                0, 0, 0, 0,                             /* x, y, cx, cy */
                                HWND_MESSAGE,                           /* hWndParent */
                                NULL,                                   /* hMenu */
                                (HINSTANCE)GetModuleHandle(NULL),       /* hinstance */
                                NULL);                                  /* pParam */
    if (g_hWinWnd == NULL)
        return RTMsgErrorExitFailure("CreateWindowExW failed: %u (%#x)", GetLastError(), GetLastError());

    return RTEXITCODE_SUCCESS;
}

/**
 * Terminates the Windows bits.
 */
static RTEXITCODE CuWinTerm(void)
{
    RTEXITCODE rcExit = RTEXITCODE_SUCCESS;
    if (g_fWinOpenedClipboard)
    {
        if (CloseClipboard())
            g_fWinOpenedClipboard = false;
        else
            rcExit = RTMsgErrorExitFailure("CloseClipboard failed: %u (%#x)", GetLastError(), GetLastError());
    }

    if (g_hWinWnd != NULL)
    {
        if (!DestroyWindow(g_hWinWnd))
            rcExit = RTMsgErrorExitFailure("DestroyWindow failed: %u (%#x)", GetLastError(), GetLastError());
        g_hWinWnd = NULL;
    }

    return rcExit;
}


/**
 * Opens the window clipboard.
 */
static RTEXITCODE WinOpenClipboardIfNecessary(void)
{
    if (g_fWinOpenedClipboard)
        return RTEXITCODE_SUCCESS;
    if (OpenClipboard(g_hWinWnd))
    {
        if (g_uVerbosity > 0)
            RTMsgInfo("Opened the clipboard\n");
        g_fWinOpenedClipboard = true;
        return RTEXITCODE_SUCCESS;
    }
    return RTMsgErrorExitFailure("OpenClipboard failed: %u (%#x)", GetLastError(), GetLastError());
}


#else /* X11: */

/**
 * Error handler callback.
 */
static int CuX11ErrorCallback(Display *pX11Display, XErrorEvent *pErrEvt)
{
    g_cX11Errors++;
    char szErr[2048];
    XGetErrorText(pX11Display, pErrEvt->error_code, szErr, sizeof(szErr));
    RTMsgError("An X Window protocol error occurred: %s\n"
               "  Request code: %u\n"
               "  Minor code:   %u\n"
               "  Serial number of the failed request: %u\n",
               szErr, pErrEvt->request_code, pErrEvt->minor_code, pErrEvt->serial);
    return 0;
}


/**
 * Initialize the X11 bits.
 */
static RTEXITCODE CuX11Init(void)
{
    /*
     * Open the X11 display and create a little dummy window.
     */
    XSetErrorHandler(CuX11ErrorCallback);
    g_pX11Display = XOpenDisplay(NULL);
    if (!g_pX11Display)
        return RTMsgErrorExitFailure("XOpenDisplay failed");

    int const iDefaultScreen = DefaultScreen(g_pX11Display);
    g_hX11Window = XCreateSimpleWindow(g_pX11Display,
                                       RootWindow(g_pX11Display, iDefaultScreen),
                                       0 /*x*/, 0 /*y*/,
                                       1 /*cx*/, 1 /*cy*/,
                                       0 /*cPxlBorder*/,
                                       BlackPixel(g_pX11Display, iDefaultScreen) /*Border*/,
                                       WhitePixel(g_pX11Display, iDefaultScreen) /*Background*/);

    /*
     * Resolve any unknown atom values we might need later.
     */
    for (size_t i = 0; i < RT_ELEMENTS(g_aTargets); i++)
        if (g_aTargets[i].pszAtomName)
        {
            g_aTargets[i].uAtom = XInternAtom(g_pX11Display, g_aTargets[i].pszAtomName, False);
            if (g_uVerbosity > 2)
                RTPrintf("target %s atom=%#x\n", g_aTargets[i].pszName, g_aTargets[i].uAtom);
        }

    g_uX11AtomTargets = XInternAtom(g_pX11Display, "TARGETS", False);
    g_uX11AtomMultiple = XInternAtom(g_pX11Display, "MULTIPLE", False);

    return RTEXITCODE_SUCCESS;
}

#endif /* X11 */


#if defined(RT_OS_OS2) || defined(RT_OS_WINDOWS)
/**
 * Closes the clipboard if open.
 */
static RTEXITCODE CuCloseClipboard(void)
{
# if defined(RT_OS_OS2)
    if (g_fOs2OpenedClipboard)
    {
        if (!WinCloseClipbrd(g_hOs2Ab))
            return RTMsgErrorExitFailure("WinCloseClipbrd failed: %#x", WinGetLastError(g_hOs2Ab));
        g_fOs2OpenedClipboard = false;
        if (g_uVerbosity > 0)
            RTMsgInfo("Closed the clipboard.\n");
    }
# else
    if (g_fWinOpenedClipboard)
    {
        if (!CloseClipboard())
            return RTMsgErrorExitFailure("CloseClipboard failed: %u (%#x)", GetLastError(), GetLastError());
        g_fWinOpenedClipboard = false;
        if (g_uVerbosity > 0)
            RTMsgInfo("Closed the clipboard.\n");
    }
# endif
    else if (g_uVerbosity > 0)
        RTMsgInfo("No need to close clipboard, not opened.\n");

    return RTEXITCODE_SUCCESS;
}
#endif /* RT_OS_OS2 || RT_OS_WINDOWS */


/**
 * Lists the clipboard format.
 */
static RTEXITCODE ListClipboardContent(void)
{
#if defined(RT_OS_OS2)
    RTEXITCODE rcExit = CuOs2OpenClipboardIfNecessary();
    if (rcExit == RTEXITCODE_SUCCESS)
    {
        HATOMTBL const hAtomTbl  = WinQuerySystemAtomTable();
        uint32_t       idx       = 0;
        ULONG          fFormat   = 0;
        while ((fFormat = WinEnumClipbrdFmts(g_hOs2Ab)) != 0)
        {
            char szName[256] = {0};
            ULONG cchRet = WinQueryAtomName(hAtomTbl, fFormat, szName, sizeof(szName));
            if (cchRet != 0)
                RTPrintf("#%02u: %#06x - %s\n", idx, fFormat, szName);
            else
            {
                const char *pszName = NULL;
                switch (fFormat)
                {
                    case CF_TEXT: pszName = "CF_TEXT"; break;
                    case CF_BITMAP: pszName = "CF_BITMAP"; break;
                    case CF_DSPTEXT: pszName = "CF_DSPTEXT"; break;
                    case CF_DSPBITMAP: pszName = "CF_DSPBITMAP"; break;
                    case CF_METAFILE: pszName = "CF_METAFILE"; break;
                    case CF_DSPMETAFILE: pszName = "CF_DSPMETAFILE"; break;
                    case CF_PALETTE: pszName = "CF_PALETTE"; break;
                    default:
                        break;
                }
                if (pszName)
                    RTPrintf("#%02u: %#06x - %s\n", idx, fFormat, pszName);
                else
                    RTPrintf("#%02u: %#06x\n", idx, fFormat);
            }

            idx++;
        }
    }

    return rcExit;

#elif defined(RT_OS_WINDOWS)
    RTEXITCODE rcExit = WinOpenClipboardIfNecessary();
    if (rcExit == RTEXITCODE_SUCCESS)
    {
        SetLastError(0);
        uint32_t idx     = 0;
        UINT     fFormat = 0;
        while ((fFormat = EnumClipboardFormats(fFormat)) != 0)
        {
            WCHAR wszName[256];
            int   cchName = GetClipboardFormatNameW(fFormat, wszName, RT_ELEMENTS(wszName));
            if (cchName > 0)
                RTPrintf("#%02u: %#06x - %ls\n", idx, fFormat, wszName);
            else
            {
                const char *pszName = NULL;
                switch (fFormat)
                {
                    case CF_TEXT: pszName = "CF_TEXT"; break;
                    case CF_BITMAP: pszName = "CF_BITMAP"; break;
                    case CF_METAFILEPICT: pszName = "CF_METAFILEPICT"; break;
                    case CF_SYLK: pszName = "CF_SYLK"; break;
                    case CF_DIF: pszName = "CF_DIF"; break;
                    case CF_TIFF: pszName = "CF_TIFF"; break;
                    case CF_OEMTEXT: pszName = "CF_OEMTEXT"; break;
                    case CF_DIB: pszName = "CF_DIB"; break;
                    case CF_PALETTE: pszName = "CF_PALETTE"; break;
                    case CF_PENDATA: pszName = "CF_PENDATA"; break;
                    case CF_RIFF: pszName = "CF_RIFF"; break;
                    case CF_WAVE: pszName = "CF_WAVE"; break;
                    case CF_UNICODETEXT: pszName = "CF_UNICODETEXT"; break;
                    case CF_ENHMETAFILE: pszName = "CF_ENHMETAFILE"; break;
                    case CF_HDROP: pszName = "CF_HDROP"; break;
                    case CF_LOCALE: pszName = "CF_LOCALE"; break;
                    case CF_DIBV5: pszName = "CF_DIBV5"; break;
                    default:
                        break;
                }
                if (pszName)
                    RTPrintf("#%02u: %#06x - %s\n", idx, fFormat, pszName);
                else
                    RTPrintf("#%02u: %#06x\n", idx, fFormat);
            }

            idx++;
        }
        if (idx == 0)
            RTPrintf("Empty\n");
    }
    return rcExit;

#elif defined(CU_X11)
    /* Request the TARGETS property: */
    Atom uAtomDst = g_uX11AtomTargets;
    int rc = XConvertSelection(g_pX11Display, g_pTarget->uAtom, g_uX11AtomTargets, uAtomDst, g_hX11Window, CurrentTime);
    if (g_uVerbosity > 1)
        RTPrintf("XConvertSelection -> %d\n", rc);

    /* Wait for the reply: */
    for (;;)
    {
        XEvent Evt = {0};
        rc = XNextEvent(g_pX11Display, &Evt);
        if (Evt.type == SelectionNotify)
        {
            if (g_uVerbosity > 1)
                RTPrintf("XNextEvent -> %d; type=SelectionNotify\n", rc);
            if (Evt.xselection.selection == g_pTarget->uAtom)
            {
                if (Evt.xselection.property == None)
                    return RTMsgErrorExitFailure("XConvertSelection(,%s,TARGETS,) failed", g_pTarget->pszName);

                /* Get the TARGETS property data: */
                Atom            uAtomRetType = 0;
                int             iActualFmt   = 0;
                unsigned long   cbLeftToRead = 0;
                unsigned long   cItems       = 0;
                unsigned char  *pbData       = NULL;
                rc = XGetWindowProperty(g_pX11Display, g_hX11Window, uAtomDst,
                                        0 /*offset*/, sizeof(Atom) * 4096 /* should be enough */, True /*fDelete*/, XA_ATOM,
                                        &uAtomRetType, &iActualFmt, &cItems, &cbLeftToRead, &pbData);
                if (g_uVerbosity > 1)
                    RTPrintf("XConvertSelection -> %d; uAtomRetType=%u iActualFmt=%d cItems=%lu cbLeftToRead=%lu pbData=%p\n",
                             rc, uAtomRetType, iActualFmt, cItems, cbLeftToRead, pbData);
                if (pbData && cItems > 0)
                {
                    /* Display the TARGETS: */
                    Atom const *paTargets = (Atom const *)pbData;
                    for (unsigned long i = 0; i < cItems; i++)
                    {
                        const char *pszName = XGetAtomName(g_pX11Display, paTargets[i]);
                        if (pszName)
                            RTPrintf("#%02u: %#06x - %s\n", i, paTargets[i], pszName);
                        else
                            RTPrintf("#%02u: %#06x\n", i, paTargets[i]);
                    }
                }
                else
                    RTMsgInfo("Empty");
                if (pbData)
                    XFree(pbData);
                return RTEXITCODE_SUCCESS;
            }
        }
        else if (g_uVerbosity > 1)
            RTPrintf("XNextEvent -> %d; type=%d\n", rc, Evt.type);
    }

#else
    return RTMsgErrorExitFailure("ListClipboardContent is not implemented");
#endif
}


/**
 * Reads the given clipboard format and stores it in on the heap.
 *
 * @returns Success indicator.
 * @param   pFmtDesc    The format to get.
 * @param   ppvData     Where to return the pointer to the data. Free using
 *                      RTMemFree when done.
 * @param   pcbData     Where to return the amount of data returned.
 */
static RTEXITCODE ReadClipboardData(PCCLIPUTILFORMAT pFmtDesc, void **ppvData, size_t *pcbData)
{
    *ppvData = NULL;
    *pcbData = 0;

#if defined(RT_OS_OS2)
    RTEXITCODE rcExit = CuOs2OpenClipboardIfNecessary();
    if (rcExit == RTEXITCODE_SUCCESS)
    {
        ULONG fFmtInfo = 0;
        if (WinQueryClipbrdFmtInfo(g_hOs2Ab, pFmtDesc->fFormat, &fFmtInfo))
        {
            ULONG uData = WinQueryClipbrdData(g_hOs2Ab, pFmtDesc->fFormat);
            if (fFmtInfo & CFI_POINTER)
            {
                PCLIPHEADER pOdinHdr = (PCLIPHEADER)uData;
                if (pFmtDesc->fFormat == CF_TEXT)
                {
                    if (pFmtDesc->fFlags & CLIPUTILFORMAT_F_CONVERT_UTF8)
                    {
                        char *pszUtf8 = NULL;
                        int rc = RTStrCurrentCPToUtf8(&pszUtf8, (const char *)uData);
                        if (RT_SUCCESS(rc))
                        {
                            *pcbData = strlen(pszUtf8) + 1;
                            *ppvData = RTMemDup(pszUtf8, *pcbData);
                            RTStrFree(pszUtf8);
                        }
                        else
                            return RTMsgErrorExitFailure("RTStrCurrentCPToUtf8 failed: %Rrc", rc);
                    }
                    else
                    {
                        *pcbData = strlen((const char *)uData) + 1;
                        *ppvData = RTMemDup((const char *)uData, *pcbData);
                    }
                }
                else if (   strcmp(pFmtDesc->pszFormat, "Odin32 UnicodeText") == 0
                         && memcmp(pOdinHdr->achMagic, CLIPHEADER_MAGIC, sizeof(pOdinHdr->achMagic)) == 0)
                {
                    *pcbData = pOdinHdr->cbData;
                    *ppvData = RTMemDup(pOdinHdr + 1, pOdinHdr->cbData);
                }
                else
                {
                    /* We could use DosQueryMem here to figure out the size of the allocation... */
                    *pcbData = PAGE_SIZE - (uData & PAGE_OFFSET_MASK);
                    *ppvData = RTMemDup((void const *)uData, *pcbData);
                }
            }
            else
            {
                *pcbData = sizeof(uData);
                *ppvData = RTMemDup(&uData, sizeof(uData));
            }
            if (!*ppvData)
                rcExit = RTMsgErrorExitFailure("Out of memory allocating %#zx bytes.", *pcbData);
        }
        else
            rcExit = RTMsgErrorExitFailure("WinQueryClipbrdFmtInfo(,%s,) failed: %#x\n",
                                           pFmtDesc->pszName, WinGetLastError(g_hOs2Ab));
    }
    return rcExit;

#elif defined(RT_OS_WINDOWS)
    RTEXITCODE rcExit = WinOpenClipboardIfNecessary();
    if (rcExit == RTEXITCODE_SUCCESS)
    {
        HANDLE hData = GetClipboardData(pFmtDesc->fFormat);
        if (hData != NULL)
        {
            SIZE_T const cbData = GlobalSize(hData);
            PVOID  const pvData = GlobalLock(hData);
            if (pvData != NULL)
            {
                *pcbData = cbData;
                if (cbData != 0)
                {
                    if (pFmtDesc->fFlags & CLIPUTILFORMAT_F_CONVERT_UTF8)
                    {
                        char  *pszUtf8 = NULL;
                        size_t cchUtf8 = 0;
                        int rc = RTUtf16ToUtf8Ex((PCRTUTF16)pvData, cbData / sizeof(RTUTF16), &pszUtf8, 0, &cchUtf8);
                        if (RT_SUCCESS(rc))
                        {
                            *pcbData = cchUtf8 + 1;
                            *ppvData = RTMemDup(pszUtf8, cchUtf8 + 1);
                            RTStrFree(pszUtf8);
                            if (!*ppvData)
                                rcExit = RTMsgErrorExitFailure("Out of memory allocating %#zx bytes.", cbData);
                        }
                        else
                            rcExit = RTMsgErrorExitFailure("RTUtf16ToUtf8Ex failed: %Rrc", rc);
                    }
                    else
                    {
                        *ppvData = RTMemDup(pvData, cbData);
                        if (!*ppvData)
                            rcExit = RTMsgErrorExitFailure("Out of memory allocating %#zx bytes.", cbData);
                    }
                }
                GlobalUnlock(hData);
            }
            else
                rcExit = RTMsgErrorExitFailure("GetClipboardData(%s) failed: %u (%#x)\n",
                                               pFmtDesc->pszName, GetLastError(), GetLastError());
        }
        else
            rcExit = RTMsgErrorExitFailure("GetClipboardData(%s) failed: %u (%#x)\n",
                                           pFmtDesc->pszName, GetLastError(), GetLastError());
    }
    return rcExit;

#elif defined(CU_X11)

    /* Request the data: */
    Atom const uAtomDst = pFmtDesc->uAtom;
    int rc = XConvertSelection(g_pX11Display, g_pTarget->uAtom, pFmtDesc->uAtom, uAtomDst, g_hX11Window, CurrentTime);
    if (g_uVerbosity > 1)
        RTPrintf("XConvertSelection -> %d\n", rc);

    /* Wait for the reply: */
    for (;;)
    {
        XEvent Evt = {0};
        rc = XNextEvent(g_pX11Display, &Evt);
        if (Evt.type == SelectionNotify)
        {
            if (g_uVerbosity > 1)
                RTPrintf("XNextEvent -> %d; type=SelectionNotify\n", rc);
            if (Evt.xselection.selection == g_pTarget->uAtom)
            {
                if (Evt.xselection.property == None)
                    return RTMsgErrorExitFailure("XConvertSelection(,%s,%s,) failed", g_pTarget->pszName, pFmtDesc->pszName);

                /*
                 * Retrieve the data.
                 */
                Atom            uAtomRetType   = 0;
                int             cBitsActualFmt = 0;
                unsigned long   cbLeftToRead   = 0;
                unsigned long   cItems         = 0;
                unsigned char  *pbData         = NULL;
                rc = XGetWindowProperty(g_pX11Display, g_hX11Window, uAtomDst,
                                        0 /*offset*/, _64M, False/*fDelete*/, AnyPropertyType,
                                        &uAtomRetType, &cBitsActualFmt, &cItems, &cbLeftToRead, &pbData);
                if (g_uVerbosity > 1)
                    RTPrintf("XConvertSelection -> %d; uAtomRetType=%u cBitsActualFmt=%d cItems=%lu cbLeftToRead=%lu pbData=%p\n",
                             rc, uAtomRetType, cBitsActualFmt, cItems, cbLeftToRead, pbData);
                RTEXITCODE rcExit = RTEXITCODE_SUCCESS;
                if (pbData && cItems > 0)
                {
                    *pcbData = cItems * (cBitsActualFmt / 8);
                    *ppvData = RTMemDup(pbData, *pcbData);
                    if (!*ppvData)
                        rcExit = RTMsgErrorExitFailure("Out of memory allocating %#zx bytes.", *pcbData);
                }
                if (pbData)
                    XFree(pbData);
                XDeleteProperty(g_pX11Display, g_hX11Window, uAtomDst);
                return rcExit;
            }
        }
        else if (g_uVerbosity > 1)
            RTPrintf("XNextEvent -> %d; type=%d\n", rc, Evt.type);
    }

#else
    RT_NOREF(pFmtDesc);
    return RTMsgErrorExitFailure("ReadClipboardData is not implemented\n");
#endif
}


/**
 * Puts the given data and format on the clipboard.
 *
 * @returns Success indicator.
 * @param   pFmtDesc     The format.
 * @param   pvData       The data.
 * @param   cbData       The amount of data in bytes.
 */
static RTEXITCODE WriteClipboardData(PCCLIPUTILFORMAT pFmtDesc, void const *pvData, size_t cbData)
{
#if defined(RT_OS_OS2)
    RTEXITCODE rcExit = CuOs2OpenClipboardIfNecessary();
    if (rcExit == RTEXITCODE_SUCCESS)
    {
        /** @todo do we need to become owner? */

        /* Convert to local code page if needed: */
        char *pszLocale = NULL;
        if (pFmtDesc->fFlags & CLIPUTILFORMAT_F_CONVERT_UTF8)
        {
            int rc = RTStrUtf8ToCurrentCPEx(&pszLocale, (char *)pvData, cbData);
            if (RT_SUCCESS(rc))
            {
                pvData = pszLocale;
                cbData = strlen(pszLocale) + 1;
            }
            else
                return RTMsgErrorExitFailure("RTStrUtf8ToCurrentCPEx failed: %Rrc\n", rc);
        }

        /* Allocate a bunch of shared memory for the object. */
        PVOID  pvShared = NULL;
        APIRET orc = DosAllocSharedMem(&pvShared, NULL, cbData,
                                       OBJ_GIVEABLE | OBJ_GETTABLE | OBJ_TILE | PAG_READ | PAG_WRITE | PAG_COMMIT);
        if (orc == NO_ERROR)
        {
            memcpy(pvShared, pvData, cbData);

            if (WinSetClipbrdData(g_hOs2Ab, (uintptr_t)pvShared, pFmtDesc->fFormat, CFI_POINTER))
            {
                if (g_uVerbosity > 0)
                    RTMsgInfo("Put '%s' on the clipboard: %p LB %zu\n", pFmtDesc->pszName, pvShared, cbData);
                rcExit = RTEXITCODE_SUCCESS;
            }
            else
            {
                rcExit = RTMsgErrorExitFailure("WinSetClipbrdData(,%p LB %#x,%s,) failed: %#x\n",
                                               pvShared, cbData, pFmtDesc->pszName, WinGetLastError(g_hOs2Ab));
                DosFreeMem(pvShared);
            }
        }
        else
            rcExit = RTMsgErrorExitFailure("DosAllocSharedMem(,, %#x,) -> %u", cbData, orc);
        RTStrFree(pszLocale);
    }
    return rcExit;


#elif defined(RT_OS_WINDOWS)
    RTEXITCODE rcExit = WinOpenClipboardIfNecessary();
    if (rcExit == RTEXITCODE_SUCCESS)
    {
        /*
         * Do input data conversion.
         */
        PRTUTF16 pwszFree = NULL;
        if (pFmtDesc->fFlags & CLIPUTILFORMAT_F_CONVERT_UTF8)
        {
            size_t cwcConv = 0;
            int rc = RTStrToUtf16Ex((char const *)pvData, cbData, &pwszFree, 0, &cwcConv);
            if (RT_SUCCESS(rc))
            {
                pvData = pwszFree;
                cbData = cwcConv * sizeof(RTUTF16);
            }
            else
                return RTMsgErrorExitFailure("RTStrToTUtf16Ex failed: %Rrc\n", rc);
        }

        /*
         * Text formats generally include the zero terminator.
         */
        uint32_t cbZeroPadding = 0;
        if (pFmtDesc->fFormat == CF_UNICODETEXT)
            cbZeroPadding = sizeof(WCHAR);
        else if (pFmtDesc->fFormat == CF_TEXT)
            cbZeroPadding = sizeof(char);

        HANDLE hDstData = GlobalAlloc(GMEM_MOVEABLE | GMEM_ZEROINIT, cbData + cbZeroPadding);
        if (hDstData)
        {
            if (cbData)
            {
                PVOID pvDstData = GlobalLock(hDstData);
                if (pvDstData)
                    memcpy(pvDstData, pvData, cbData);
                else
                    rcExit = RTMsgErrorExitFailure("GlobalLock failed: %u (%#x)\n", GetLastError(), GetLastError());
            }
            if (rcExit == RTEXITCODE_SUCCESS)
            {
                if (SetClipboardData(pFmtDesc->fFormat, hDstData))
                {
                    if (g_uVerbosity > 0)
                        RTMsgInfo("Put '%s' on the clipboard: %p LB %zu\n", pFmtDesc->pszName, hDstData, cbData + cbZeroPadding);
                }
                else
                {
                    rcExit = RTMsgErrorExitFailure("SetClipboardData(%s) failed: %u (%#x)\n",
                                                   pFmtDesc->pszName, GetLastError(), GetLastError());
                    GlobalFree(hDstData);
                }
            }
            else
                GlobalFree(hDstData);
        }
        else
            rcExit = RTMsgErrorExitFailure("GlobalAlloc(,%#zx) failed: %u (%#x)\n",
                                           cbData + cbZeroPadding, GetLastError(), GetLastError());
    }
    return rcExit;

#else
    RT_NOREF(pFmtDesc, pvData, cbData);
    return RTMsgErrorExitFailure("WriteClipboardData is not implemented\n");
#endif
}


/**
 * Check if the given data + format matches what's actually on the clipboard.
 *
 * @returns Success indicator.
 * @param   pFmtDesc    The format to compare.
 * @param   pvExpect    The expected clipboard data.
 * @param   cbExpect    The size of the expected clipboard data.
 */
static RTEXITCODE CompareDataWithClipboard(PCCLIPUTILFORMAT pFmtDesc, void const *pvExpect, size_t cbExpect)
{
    void      *pvData = NULL;
    size_t     cbData = 0;
    RTEXITCODE rcExit = ReadClipboardData(pFmtDesc, &pvData, &cbData);
    if (rcExit == RTEXITCODE_SUCCESS)
    {
        if (   cbData == cbExpect
            && memcmp(pvData, pvExpect, cbData) == 0)
            rcExit = RTEXITCODE_SUCCESS;
        else
            rcExit = RTMsgErrorExitFailure("Mismatch for '%s' (cbData=%#zx cbExpect=%#zx)\n",
                                           pFmtDesc->pszName, cbData, cbExpect);
        RTMemFree(pvData);
    }
    return rcExit;
}


/**
 * Gets the given clipboard format.
 *
 * @returns Success indicator.
 * @param   pFmtDesc    The format to get.
 * @param   pStrmOut    Where to output the data.
 * @param   fIsStdOut   Set if @a pStrmOut is standard output, clear if not.
 */
static RTEXITCODE ClipboardContentToStdOut(PCCLIPUTILFORMAT pFmtDesc)
{
    void      *pvData = NULL;
    size_t     cbData = 0;
    RTEXITCODE rcExit = ReadClipboardData(pFmtDesc, &pvData, &cbData);
    if (rcExit == RTEXITCODE_SUCCESS)
    {
        int rc = RTStrmWrite(g_pStdOut, pvData, cbData);
        RTMemFree(pvData);
        if (RT_FAILURE(rc))
            rcExit = RTMsgErrorExitFailure("Error writing %#zx bytes to standard output: %Rrc", cbData, rc);
    }
    return rcExit;
}


/**
 * Gets the given clipboard format.
 *
 * @returns Success indicator.
 * @param   pFmtDesc    The format to get.
 * @param   pszFilename The output filename.
 */
static RTEXITCODE ClipboardContentToFile(PCCLIPUTILFORMAT pFmtDesc, const char *pszFilename)
{
    void      *pvData = NULL;
    size_t     cbData = 0;
    RTEXITCODE rcExit = ReadClipboardData(pFmtDesc, &pvData, &cbData);
    if (rcExit == RTEXITCODE_SUCCESS)
    {
        RTFILE hFile = NIL_RTFILE;
        int rc = RTFileOpen(&hFile, pszFilename,
                            RTFILE_O_WRITE | RTFILE_O_DENY_WRITE | RTFILE_O_CREATE_REPLACE
                            | (0770 << RTFILE_O_CREATE_MODE_SHIFT));
        if (RT_SUCCESS(rc))
        {
            rc = RTFileWrite(hFile, pvData, cbData, NULL);
            int const rc2 = RTFileClose(hFile);
            if (RT_FAILURE(rc) || RT_FAILURE(rc2))
            {
                if (RT_FAILURE_NP(rc))
                    RTMsgError("Writing %#z bytes to '%s' failed: %Rrc", cbData, pszFilename, rc);
                else
                    RTMsgError("Closing '%s' failed: %Rrc", pszFilename, rc2);
                RTMsgInfo("Deleting '%s'.", pszFilename);
                RTFileDelete(pszFilename);
                rcExit = RTEXITCODE_FAILURE;
            }
        }
        else
            rcExit = RTMsgErrorExitFailure("Failed to open '%s' for writing: %Rrc", pszFilename, rc);
        RTMemFree(pvData);
    }
    return rcExit;
}


/**
 * Puts the given format + data onto the clipboard.
 *
 * @returns Success indicator.
 * @param   pFmtDesc    The format to put.
 * @param   pszData     The string data.
 */
static RTEXITCODE PutStringOnClipboard(PCCLIPUTILFORMAT pFmtDesc, const char *pszData)
{
    return WriteClipboardData(pFmtDesc, pszData, strlen(pszData));
}


/**
 * Puts a format + file content onto the clipboard.
 *
 * @returns Success indicator.
 * @param   pFmtDesc    The format to put.
 * @param   pszFilename The filename.
 */
static RTEXITCODE PutFileOnClipboard(PCCLIPUTILFORMAT pFmtDesc, const char *pszFilename)
{
    RTEXITCODE rcExit = RTEXITCODE_SUCCESS;
    void      *pvData = NULL;
    size_t     cbData = 0;
    int rc = RTFileReadAll(pszFilename, &pvData, &cbData);
    if (RT_SUCCESS(rc))
    {
        rcExit = WriteClipboardData(pFmtDesc, pvData, cbData);
        RTFileReadAllFree(pvData, cbData);
    }
    else
        rcExit = RTMsgErrorExitFailure("Failed to open and read '%s' into memory: %Rrc", pszFilename, rc);
    return rcExit;
}


/**
 * Checks if the given format + data matches what's on the clipboard.
 *
 * @returns Success indicator.
 * @param   pFmtDesc    The format to check.
 * @param   pszData     The string data.
 */
static RTEXITCODE CheckStringAgainstClipboard(PCCLIPUTILFORMAT pFmtDesc, const char *pszData)
{
    return CompareDataWithClipboard(pFmtDesc, pszData, strlen(pszData));
}


/**
 * Check if the given format + file content matches what's on the clipboard.
 *
 * @returns Success indicator.
 * @param   pFmtDesc    The format to check.
 * @param   pszFilename The filename.
 */
static RTEXITCODE CheckFileAgainstClipboard(PCCLIPUTILFORMAT pFmtDesc, const char *pszFilename)
{
    RTEXITCODE rcExit = RTEXITCODE_SUCCESS;
    void      *pvData = NULL;
    size_t     cbData = 0;
    int rc = RTFileReadAll(pszFilename, &pvData, &cbData);
    if (RT_SUCCESS(rc))
    {
        rcExit = CompareDataWithClipboard(pFmtDesc, pvData, cbData);
        RTFileReadAllFree(pvData, cbData);
    }
    else
        rcExit = RTMsgErrorExitFailure("Failed to open and read '%s' into memory: %Rrc", pszFilename, rc);
    return rcExit;
}


/**
 * Check that the given format is not on the clipboard.
 *
 * @returns Success indicator.
 * @param   pFmtDesc    The format to check.
 */
static RTEXITCODE CheckFormatNotOnClipboard(PCCLIPUTILFORMAT pFmtDesc)
{
#if defined(RT_OS_OS2)
    RTEXITCODE rcExit = CuOs2OpenClipboardIfNecessary();
    if (rcExit == RTEXITCODE_SUCCESS)
    {
        ULONG fFmtInfo = 0;
        if (WinQueryClipbrdFmtInfo(g_hOs2Ab, pFmtDesc->fFormat, &fFmtInfo))
            rcExit = RTMsgErrorExitFailure("Format '%s' is present");
    }
    return rcExit;

#elif defined(RT_OS_WINDOWS)
    RTEXITCODE rcExit = WinOpenClipboardIfNecessary();
    if (rcExit == RTEXITCODE_SUCCESS)
    {
        if (IsClipboardFormatAvailable(pFmtDesc->fFormat))
            rcExit = RTMsgErrorExitFailure("Format '%s' is present");
    }
    return rcExit;

#else
    RT_NOREF(pFmtDesc);
    return RTMsgErrorExitFailure("CheckFormatNotOnClipboard is not implemented");
#endif
}


/**
 * Empties the clipboard.
 *
 * @returns Success indicator.
 */
static RTEXITCODE ZapAllClipboardData(void)
{
#if defined(RT_OS_OS2)
    RTEXITCODE rcExit = CuOs2OpenClipboardIfNecessary();
    if (rcExit == RTEXITCODE_SUCCESS)
    {
        ULONG fFmtInfo = 0;
        if (WinEmptyClipbrd(g_hOs2Ab))
        {
            WinSetClipbrdOwner(g_hOs2Ab, g_hOs2Wnd); /* Probably unnecessary? */
            WinSetClipbrdOwner(g_hOs2Ab, NULLHANDLE);
            g_fOs2ClipboardOwner = false;
        }
        else
            rcExit = RTMsgErrorExitFailure("WinEmptyClipbrd() failed: %#x\n", WinGetLastError(g_hOs2Ab));
    }
    return rcExit;

#elif defined(RT_OS_WINDOWS)
    RTEXITCODE rcExit = WinOpenClipboardIfNecessary();
    if (rcExit == RTEXITCODE_SUCCESS)
    {
        if (!EmptyClipboard())
            rcExit = RTMsgErrorExitFailure("EmptyClipboard() failed: %u (%#x)\n", GetLastError(), GetLastError());
    }
    return rcExit;

#else
    return RTMsgErrorExitFailure("ZapAllClipboardData is not implemented");
#endif
}


/**
 * Waits/delays at least @a cMsWait milliseconds.
 *
 * @returns Success indicator.
 * @param   cMsWait     Minimum wait/delay time in milliseconds.
 */
static RTEXITCODE DoWait(uint32_t cMsWait)
{
    uint64_t const msStart = RTTimeMilliTS();
    if (g_uVerbosity > 1)
        RTMsgInfo("Waiting %u ms...\n", cMsWait);

#if defined(RT_OS_OS2)
    /*
     * Arm a timer which will timeout after the desired period and
     * quit when we've dispatched it.
     */
    g_fOs2TimerTicked = false;
    if (WinStartTimer(g_hOs2Ab, g_hOs2Wnd, 1 /*idEvent*/, cMsWait + 1) != 0)
    {
        QMSG Msg;
        while (WinGetMsg(g_hOs2Ab, &Msg, NULL, 0, 0))
        {
            WinDispatchMsg(g_hOs2Ab, &Msg);
            if (g_fOs2TimerTicked || RTTimeMilliTS() - msStart >= cMsWait)
                break;
        }

        if (!WinStopTimer(g_hOs2Ab, g_hOs2Wnd, 1 /*idEvent*/))
            RTMsgWarning("WinStopTimer failed: %#x", WinGetLastError(g_hOs2Ab));
    }
    else
        return RTMsgErrorExitFailure("WinStartTimer(,,,%u ms) failed: %#x", cMsWait + 1, WinGetLastError(g_hOs2Ab));

#elif defined(RT_OS_WINDOWS)
    /*
     * Arm a timer which will timeout after the desired period and
     * quit when we've dispatched it.
     */
    g_fWinTimerTicked = false;
    if (SetTimer(g_hWinWnd, 1 /*idEvent*/, cMsWait + 1, NULL /*pfnTimerProc*/) != 0)
    {
        MSG Msg;
        while (GetMessageW(&Msg, NULL, 0, 0))
        {
            TranslateMessage(&Msg);
            DispatchMessageW(&Msg);
            if (g_fWinTimerTicked || RTTimeMilliTS() - msStart >= cMsWait)
                break;
        }

        if (!KillTimer(g_hWinWnd, 1 /*idEvent*/))
            RTMsgWarning("KillTimer failed: %u (%#x)", GetLastError(), GetLastError());
    }
    else
        return RTMsgErrorExitFailure("SetTimer(,,%u ms,) failed: %u (%#x)", cMsWait + 1, GetLastError(), GetLastError());

#else
/** @todo X11 needs to run it's message queue too, because if we're offering
 *        things on the "clipboard" we must reply to requests for them.  */
    /*
     * Just a plain simple RTThreadSleep option (will probably not be used in the end):
     */
    for (;;)
    {
        uint64_t cMsElapsed = RTTimeMilliTS() - msStart;
        if (cMsElapsed >= cMsWait)
            break;
        RTThreadSleep(cMsWait - cMsElapsed);
    }
#endif

    if (g_uVerbosity > 2)
        RTMsgInfo("Done waiting after %u ms.\n", RTTimeMilliTS() - msStart);
    return RTEXITCODE_SUCCESS;
}


/**
 * Display the usage to @a pStrm.
 */
static void Usage(PRTSTREAM pStrm)
{
    RTStrmPrintf(pStrm,
                 "usage: %s [--get <fmt> [--get ...]] [--get-file <fmt> <file> [--get-file ...]]\n"
                 "       %s [--zap] [--put <fmt> <content> [--put ...]] [--put-file <fmt> <file> [--put-file ...]] [--wait <ms>]\n"
                 "       %s [--check <fmt> <expected> [--check ...]] [--check-file <fmt> <file> [--check-file ...]]\n"
                 "           [--check-no <fmt> [--check-no ...]]\n"
                 , RTProcShortName(), RTProcShortName(), RTProcShortName());
    RTStrmPrintf(pStrm, "\n");
    RTStrmPrintf(pStrm, "Actions/Options:\n");

    for (unsigned i = 0; i < RT_ELEMENTS(g_aCmdOptions); i++)
    {
        const char *pszHelp;
        switch (g_aCmdOptions[i].iShort)
        {
            case 'l':   pszHelp = "List the clipboard content."; break;
            case 'g':   pszHelp = "Get given clipboard format and writes it to standard output."; break;
            case 'G':   pszHelp = "Get given clipboard format and writes it to the specified file."; break;
            case 'p':   pszHelp = "Puts given format and content on the clipboard."; break;
            case 'P':   pszHelp = "Puts given format and file content on the clipboard."; break;
            case 'c':   pszHelp = "Checks that the given format and content matches the clipboard."; break;
            case 'C':   pszHelp = "Checks that the given format and file content matches the clipboard."; break;
            case 'n':   pszHelp = "Checks that the given format is not on the clipboard."; break;
            case 'z':   pszHelp = "Zaps the clipboard content."; break;
#ifdef MULTI_TARGET_CLIPBOARD
            case 't':   pszHelp = "Selects the target clipboard."; break;
#endif
#if defined(RT_OS_OS2) || defined(RT_OS_WINDOWS)
            case 'k':   pszHelp = "Closes the clipboard if open (win,os2)."; break;
#endif
            case 'w':   pszHelp = "Waits a given number of milliseconds before continuing."; break;
            case 'v':   pszHelp = "More verbose execution."; break;
            case 'q':   pszHelp = "Quiet execution."; break;
            case 'h':   pszHelp = "Displays this help and exit"; break;
            case 'V':   pszHelp = "Displays the program revision"; break;

            default:
                pszHelp = "Option undocumented";
                break;
        }
        if ((unsigned)g_aCmdOptions[i].iShort < 127U)
        {
            char szOpt[64];
            RTStrPrintf(szOpt, sizeof(szOpt), "%s, -%c", g_aCmdOptions[i].pszLong, g_aCmdOptions[i].iShort);
            RTStrmPrintf(pStrm, "  %-19s %s\n", szOpt, pszHelp);
        }
        else
            RTStrmPrintf(pStrm, "  %-19s %s\n", g_aCmdOptions[i].pszLong, pszHelp);
    }
    RTStrmPrintf(pStrm,
                 "\n"
                 "Note! Options are processed in the order they are given.\n");

    RTStrmPrintf(pStrm, "\nFormats:\n");
    for (size_t i = 0; i < RT_ELEMENTS(g_aFormats); i++)
        RTStrmPrintf(pStrm, "    %-12s: %s\n", g_aFormats[i].pszName, g_aFormats[i].pszDesc);

#ifdef MULTI_TARGET_CLIPBOARD
    RTStrmPrintf(pStrm, "\nTarget:\n");
    for (size_t i = 0; i < RT_ELEMENTS(g_aTargets); i++)
        RTStrmPrintf(pStrm, "    %-12s: %s\n", g_aTargets[i].pszName, g_aTargets[i].pszDesc);
#endif
}


int main(int argc, char *argv[])
{
    /*
     * Init IPRT.
     */
    int rc = RTR3InitExe(argc, &argv, 0);
    if (RT_FAILURE(rc))
        return RTMsgInitFailure(rc);

    /*
     * Host specific init.
     */
#ifdef RT_OS_DARWIN
    RTEXITCODE rcExit = RTEXITCODE_SUCCESS;
#elif defined(RT_OS_OS2)
    RTEXITCODE rcExit = CuOs2Init();
#elif defined(RT_OS_WINDOWS)
    RTEXITCODE rcExit = CuWinInit();
#else
    RTEXITCODE rcExit = CuX11Init();
#endif
    if (rcExit != RTEXITCODE_SUCCESS)
        return rcExit;

    /*
     * Process options (in order).
     */
    RTGETOPTUNION ValueUnion;
    RTGETOPTSTATE GetState;
    RTGetOptInit(&GetState, argc, argv, g_aCmdOptions, RT_ELEMENTS(g_aCmdOptions), 1, 0 /* fFlags */);
    while ((rc = RTGetOpt(&GetState, &ValueUnion)) != 0)
    {
        RTEXITCODE rcExit2 = RTEXITCODE_SUCCESS;
        switch (rc)
        {
#if defined(RT_OS_OS2) || defined(RT_OS_WINDOWS)
            case 'k':
                rcExit2 = CuCloseClipboard();
                break;
#endif

            case 'l':
                rcExit2 = ListClipboardContent();
                break;

            case 'g':
            {
                PCCLIPUTILFORMAT pFmtDesc = GetFormatDesc(ValueUnion.psz);
                if (pFmtDesc)
                    rcExit2 = ClipboardContentToStdOut(pFmtDesc);
                else
                    rcExit2 = RTEXITCODE_FAILURE;
                break;
            }

            case 'G':
            {
                PCCLIPUTILFORMAT pFmtDesc = GetFormatDesc(ValueUnion.psz);
                if (pFmtDesc)
                {
                    rc = RTGetOptFetchValue(&GetState, &ValueUnion, RTGETOPT_REQ_STRING);
                    if (RT_SUCCESS(rc))
                        rcExit2 = ClipboardContentToFile(pFmtDesc, ValueUnion.psz);
                    else
                        return RTMsgErrorExitFailure("No filename given with --get-file");
                }
                else
                    rcExit2 = RTEXITCODE_FAILURE;
                break;
            }

            case 'p':
            {
                PCCLIPUTILFORMAT pFmtDesc = GetFormatDesc(ValueUnion.psz);
                if (pFmtDesc)
                {
                    rc = RTGetOptFetchValue(&GetState, &ValueUnion, RTGETOPT_REQ_STRING);
                    if (RT_SUCCESS(rc))
                        rcExit2 = PutStringOnClipboard(pFmtDesc, ValueUnion.psz);
                    else
                        return RTMsgErrorExitFailure("No data string given with --put");
                }
                else
                    rcExit2 = RTEXITCODE_FAILURE;
                break;
            }

            case 'P':
            {
                PCCLIPUTILFORMAT pFmtDesc = GetFormatDesc(ValueUnion.psz);
                if (pFmtDesc)
                {
                    rc = RTGetOptFetchValue(&GetState, &ValueUnion, RTGETOPT_REQ_STRING);
                    if (RT_SUCCESS(rc))
                        rcExit2 = PutFileOnClipboard(pFmtDesc, ValueUnion.psz);
                    else
                        return RTMsgErrorExitFailure("No filename given with --put-file");
                }
                else
                    rcExit2 = RTEXITCODE_FAILURE;
                break;
            }

            case 'c':
            {
                PCCLIPUTILFORMAT pFmtDesc = GetFormatDesc(ValueUnion.psz);
                if (pFmtDesc)
                {
                    rc = RTGetOptFetchValue(&GetState, &ValueUnion, RTGETOPT_REQ_STRING);
                    if (RT_SUCCESS(rc))
                        rcExit2 = CheckStringAgainstClipboard(pFmtDesc, ValueUnion.psz);
                    else
                        return RTMsgErrorExitFailure("No data string given with --check");
                }
                else
                    rcExit2 = RTEXITCODE_FAILURE;
                break;
            }

            case 'C':
            {
                PCCLIPUTILFORMAT pFmtDesc = GetFormatDesc(ValueUnion.psz);
                if (pFmtDesc)
                {
                    rc = RTGetOptFetchValue(&GetState, &ValueUnion, RTGETOPT_REQ_STRING);
                    if (RT_SUCCESS(rc))
                        rcExit2 = CheckFileAgainstClipboard(pFmtDesc, ValueUnion.psz);
                    else
                        return RTMsgErrorExitFailure("No filename given with --check-file");
                }
                else
                    rcExit2 = RTEXITCODE_FAILURE;
                break;
            }

            case 'n':
            {
                PCCLIPUTILFORMAT pFmtDesc = GetFormatDesc(ValueUnion.psz);
                if (pFmtDesc)
                    rcExit2 = CheckFormatNotOnClipboard(pFmtDesc);
                else
                    rcExit2 = RTEXITCODE_FAILURE;
                break;
            }


            case 'z':
                rcExit2 = ZapAllClipboardData();
                break;

#ifdef MULTI_TARGET_CLIPBOARD
            case 't':
            {
                CLIPUTILTARGET *pNewTarget = NULL;
                for (size_t i = 0; i < RT_ELEMENTS(g_aTargets); i++)
                    if (strcmp(ValueUnion.psz, g_aTargets[i].pszName) == 0)
                    {
                        pNewTarget = &g_aTargets[i];
                        break;
                    }
                if (!pNewTarget)
                    return RTMsgErrorExitFailure("Unknown target '%s'", ValueUnion.psz);
                if (pNewTarget != g_pTarget && g_uVerbosity > 0)
                    RTMsgInfo("Switching from '%s' to '%s'\n", g_pTarget->pszName, pNewTarget->pszName);
                g_pTarget = pNewTarget;
                break;
            }
#endif

            case 'w':
                rcExit2 = DoWait(ValueUnion.u32);
                break;

            case 'q':
                g_uVerbosity = 0;
                break;

            case 'v':
                g_uVerbosity++;
                break;

            case 'h':
                Usage(g_pStdOut);
                return RTEXITCODE_SUCCESS;

            case 'V':
            {
                char szRev[] = "$Revision: 155244 $";
                szRev[RT_ELEMENTS(szRev) - 2] = '\0';
                RTPrintf(RTStrStrip(strchr(szRev, ':') + 1));
                return RTEXITCODE_SUCCESS;
            }

            default:
                return RTGetOptPrintError(rc, &ValueUnion);
        }

        if (rcExit2 != RTEXITCODE_SUCCESS && rcExit == RTEXITCODE_SUCCESS)
            rcExit = rcExit2;
    }

    /*
     * Host specific cleanup.
     */
#if defined(RT_OS_OS2)
    RTEXITCODE rcExit2 = CuOs2Term();
#elif defined(RT_OS_WINDOWS)
    RTEXITCODE rcExit2 = CuWinTerm();
#else
    RTEXITCODE rcExit2 = RTEXITCODE_SUCCESS;
#endif
    if (rcExit2 != RTEXITCODE_SUCCESS && rcExit != RTEXITCODE_SUCCESS)
        rcExit = rcExit2;

    return rcExit;
}