summaryrefslogtreecommitdiff
path: root/pyuno/source/module/pyuno.cxx
blob: d554f5ca769c2d10bfd90ea309ec3c51b8f5fe5f (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
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *
 * This file incorporates work covered by the following license notice:
 *
 *   Licensed to the Apache Software Foundation (ASF) under one or more
 *   contributor license agreements. See the NOTICE file distributed
 *   with this work for additional information regarding copyright
 *   ownership. The ASF licenses this file to you under the Apache
 *   License, Version 2.0 (the "License"); you may not use this file
 *   except in compliance with the License. You may obtain a copy of
 *   the License at http://www.apache.org/licenses/LICENSE-2.0 .
 */

#include <sal/config.h>

#include <algorithm>
#include <cassert>

#include <rtl/strbuf.hxx>
#include <rtl/ustrbuf.hxx>

#include <typelib/typedescription.hxx>

#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/lang/XTypeProvider.hpp>
#include <com/sun/star/beans/UnknownPropertyException.hpp>
#include <com/sun/star/container/XEnumerationAccess.hpp>
#include <com/sun/star/container/XIndexAccess.hpp>
#include <com/sun/star/container/XIndexContainer.hpp>
#include <com/sun/star/container/XIndexReplace.hpp>
#include <com/sun/star/container/XNameAccess.hpp>
#include <com/sun/star/container/XNameContainer.hpp>
#include <com/sun/star/container/XNameReplace.hpp>
#include <com/sun/star/script/CannotConvertException.hpp>
#include <com/sun/star/script/XInvocation2.hpp>
#include <com/sun/star/script/XTypeConverter.hpp>
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#include <comphelper/servicehelper.hxx>

#include "pyuno_impl.hxx"

using com::sun::star::uno::Sequence;
using com::sun::star::uno::Reference;
using com::sun::star::uno::XInterface;
using com::sun::star::uno::Any;
using com::sun::star::uno::makeAny;
using com::sun::star::uno::UNO_QUERY;
using com::sun::star::uno::Type;
using com::sun::star::uno::TypeClass;
using com::sun::star::uno::TypeDescription;
using com::sun::star::uno::RuntimeException;
using com::sun::star::uno::Exception;
using com::sun::star::lang::XSingleServiceFactory;
using com::sun::star::lang::XServiceInfo;
using com::sun::star::lang::XTypeProvider;
using com::sun::star::lang::XUnoTunnel;
using com::sun::star::script::XInvocation2;
using com::sun::star::container::XEnumeration;
using com::sun::star::container::XEnumerationAccess;
using com::sun::star::container::XIndexAccess;
using com::sun::star::container::XIndexContainer;
using com::sun::star::container::XIndexReplace;
using com::sun::star::container::XNameAccess;
using com::sun::star::container::XNameContainer;
using com::sun::star::container::XNameReplace;

namespace pyuno
{

static PyObject *PyUNO_str( PyObject * self );

static void PyUNO_del (PyObject* self)
{
    PyUNO* me = reinterpret_cast< PyUNO* > (self);
    {
        PyThreadDetach antiguard;
        delete me->members;
    }
    PyObject_Del (self);
}


OUString val2str( const void * pVal, typelib_TypeDescriptionReference * pTypeRef , sal_Int32 mode )
{
    assert( pVal );
    if (pTypeRef->eTypeClass == typelib_TypeClass_VOID)
        return "void";

    OUStringBuffer buf( 64 );
    buf.append( "(" + OUString::unacquired(&pTypeRef->pTypeName) + ")" );

    switch (pTypeRef->eTypeClass)
    {
    case typelib_TypeClass_INTERFACE:
    {
        buf.append( "0x" +
            OUString::number( reinterpret_cast< sal_IntPtr >(*static_cast<void * const *>(pVal)), 16 ));
        if( VAL2STR_MODE_DEEP == mode )
        {
            buf.append( "{" );        Reference< XInterface > r = *static_cast<Reference< XInterface > const *>(pVal);
            Reference< XServiceInfo > serviceInfo( r, UNO_QUERY);
            Reference< XTypeProvider > typeProvider(r,UNO_QUERY);
            if( serviceInfo.is() )
            {
                buf.append("implementationName=" );
                buf.append(serviceInfo->getImplementationName() );
                buf.append(", supportedServices={" );
                Sequence< OUString > seq = serviceInfo->getSupportedServiceNames();
                for( int i = 0 ; i < seq.getLength() ; i ++ )
                {
                    buf.append( seq[i] );
                    if( i +1 != seq.getLength() )
                        buf.append( "," );
                }
                buf.append("}");
            }

            if( typeProvider.is() )
            {
                buf.append(", supportedInterfaces={" );
                Sequence< Type > seq (typeProvider->getTypes());
                for( int i = 0 ; i < seq.getLength() ; i ++ )
                {
                    buf.append(seq[i].getTypeName());
                    if( i +1 != seq.getLength() )
                        buf.append( "," );
                }
                buf.append("}");
            }
            buf.append( "}" );
        }

        break;
    }
    case typelib_TypeClass_STRUCT:
    case typelib_TypeClass_EXCEPTION:
    {
        buf.append( "{ " );
        typelib_TypeDescription * pTypeDescr = nullptr;
        TYPELIB_DANGER_GET( &pTypeDescr, pTypeRef );
        assert( pTypeDescr );

        typelib_CompoundTypeDescription * pCompType = reinterpret_cast<typelib_CompoundTypeDescription *>(pTypeDescr);
        sal_Int32 nDescr = pCompType->nMembers;

        if (pCompType->pBaseTypeDescription)
        {
            buf.append( val2str( pVal, pCompType->pBaseTypeDescription->aBase.pWeakRef, mode ) );
            if (nDescr)
                buf.append( ", " );
        }

        typelib_TypeDescriptionReference ** ppTypeRefs = pCompType->ppTypeRefs;
        sal_Int32 * pMemberOffsets = pCompType->pMemberOffsets;
        rtl_uString ** ppMemberNames = pCompType->ppMemberNames;

        for ( sal_Int32 nPos = 0; nPos < nDescr; ++nPos )
        {
            buf.append( OUString::unacquired(&ppMemberNames[nPos]) + " = " );
            typelib_TypeDescription * pMemberType = nullptr;
            TYPELIB_DANGER_GET( &pMemberType, ppTypeRefs[nPos] );
            buf.append( val2str( static_cast<char const *>(pVal) + pMemberOffsets[nPos], pMemberType->pWeakRef, mode ) );
            TYPELIB_DANGER_RELEASE( pMemberType );
            if (nPos < (nDescr -1))
                buf.append( ", " );
        }

        TYPELIB_DANGER_RELEASE( pTypeDescr );

        buf.append( " }" );
        break;
    }
    case typelib_TypeClass_SEQUENCE:
    {
        typelib_TypeDescription * pTypeDescr = nullptr;
        TYPELIB_DANGER_GET( &pTypeDescr, pTypeRef );

        uno_Sequence * pSequence = *static_cast<uno_Sequence * const *>(pVal);
        typelib_TypeDescription * pElementTypeDescr = nullptr;
        TYPELIB_DANGER_GET( &pElementTypeDescr, reinterpret_cast<typelib_IndirectTypeDescription *>(pTypeDescr)->pType );

        sal_Int32 nElementSize = pElementTypeDescr->nSize;
        sal_Int32 nElements = pSequence->nElements;

        if (nElements)
        {
            buf.append( "{ " );
            char * pElements = pSequence->elements;
            for ( sal_Int32 nPos = 0; nPos < nElements; ++nPos )
            {
                buf.append( val2str( pElements + (nElementSize * nPos), pElementTypeDescr->pWeakRef, mode ) );
                if (nPos < (nElements -1))
                    buf.append( ", " );
            }
            buf.append( " }" );
        }
        else
        {
            buf.append( "{}" );
        }
        TYPELIB_DANGER_RELEASE( pElementTypeDescr );
        TYPELIB_DANGER_RELEASE( pTypeDescr );
        break;
    }
    case typelib_TypeClass_ANY:
        buf.append( "{ " );
        buf.append( val2str( static_cast<uno_Any const *>(pVal)->pData,
                             static_cast<uno_Any const *>(pVal)->pType ,
                             mode) );
        buf.append( " }" );
        break;
    case typelib_TypeClass_TYPE:
        buf.append( (*static_cast<typelib_TypeDescriptionReference * const *>(pVal))->pTypeName );
        break;
    case typelib_TypeClass_STRING:
        buf.append( "\"" +
            OUString::unacquired(&*static_cast<rtl_uString * const *>(pVal)) +
            "\"" );
        break;
    case typelib_TypeClass_ENUM:
    {
        typelib_TypeDescription * pTypeDescr = nullptr;
        TYPELIB_DANGER_GET( &pTypeDescr, pTypeRef );

        sal_Int32 * pValues = reinterpret_cast<typelib_EnumTypeDescription *>(pTypeDescr)->pEnumValues;
        sal_Int32 nPos = reinterpret_cast<typelib_EnumTypeDescription *>(pTypeDescr)->nEnumValues;
        while (nPos--)
        {
            if (pValues[nPos] == *static_cast<int const *>(pVal))
                break;
        }
        if (nPos >= 0)
            buf.append( reinterpret_cast<typelib_EnumTypeDescription *>(pTypeDescr)->ppEnumNames[nPos] );
        else
            buf.append( '?' );

        TYPELIB_DANGER_RELEASE( pTypeDescr );
        break;
    }
    case typelib_TypeClass_BOOLEAN:
        if (*static_cast<sal_Bool const *>(pVal))
            buf.append( "true" );
        else
            buf.append( "false" );
        break;
    case typelib_TypeClass_CHAR:
        buf.append( '\'' );
        buf.append( *static_cast<sal_Unicode const *>(pVal) );
        buf.append( '\'' );
        break;
    case typelib_TypeClass_FLOAT:
        buf.append( *static_cast<float const *>(pVal) );
        break;
    case typelib_TypeClass_DOUBLE:
        buf.append( *static_cast<double const *>(pVal) );
        break;
    case typelib_TypeClass_BYTE:
        buf.append( "0x" +
            OUString::number( static_cast<sal_Int32>(*static_cast<sal_Int8 const *>(pVal)), 16 ));
        break;
    case typelib_TypeClass_SHORT:
        buf.append( "0x" +
            OUString::number( static_cast<sal_Int32>(*static_cast<sal_Int16 const *>(pVal)), 16 ));
        break;
    case typelib_TypeClass_UNSIGNED_SHORT:
        buf.append( "0x" +
            OUString::number( static_cast<sal_Int32>(*static_cast<sal_uInt16 const *>(pVal)), 16 ));
        break;
    case typelib_TypeClass_LONG:
        buf.append( "0x" +
            OUString::number( *static_cast<sal_Int32 const *>(pVal), 16 ));
        break;
    case typelib_TypeClass_UNSIGNED_LONG:
        buf.append( "0x" +
            OUString::number( static_cast<sal_Int64>(*static_cast<sal_uInt32 const *>(pVal)), 16 ));
        break;
    case typelib_TypeClass_HYPER:
    case typelib_TypeClass_UNSIGNED_HYPER:
        buf.append( "0x" );
#if defined(__GNUC__) && defined(SPARC)
// I guess this really should check if there are strict alignment
// requirements, not just "GCC on SPARC".
        {
            sal_Int64 aVal;
            *(sal_Int32 *)&aVal = *(sal_Int32 *)pVal;
            *((sal_Int32 *)&aVal +1)= *((sal_Int32 *)pVal +1);
            buf.append( aVal, 16 );
        }
#else
        buf.append( *static_cast<sal_Int64 const *>(pVal), 16 );
#endif
        break;

    case typelib_TypeClass_VOID:
    case typelib_TypeClass_UNKNOWN:
    case typelib_TypeClass_SERVICE:
    case typelib_TypeClass_MODULE:
    default:
        buf.append( '?' );
    }

    return buf.makeStringAndClear();
}

static sal_Int32 lcl_PyNumber_AsSal_Int32( PyObject *pObj )
{
    // Check object is an index
    PyRef rIndex( PyNumber_Index( pObj ), SAL_NO_ACQUIRE );
    if ( !rIndex.is() )
        return -1;

    // Convert Python number to platform long, then check actual value against
    // bounds of sal_Int32
#if PY_VERSION_HEX >= 0x03020000
    int nOverflow;
    long nResult = PyLong_AsLongAndOverflow( pObj, &nOverflow );
    if ( nOverflow || nResult > SAL_MAX_INT32 || nResult < SAL_MIN_INT32) {
#else
    long nResult = PyLong_AsLong( pObj );
    if ( nResult > SAL_MAX_INT32 || nResult < SAL_MIN_INT32) {
#endif
        PyErr_SetString( PyExc_IndexError, "Python int too large to convert to UNO long" );
        return -1;
    }

    return nResult;
}

static int lcl_PySlice_GetIndicesEx( PyObject *pObject, sal_Int32 nLen, sal_Int32 *nStart, sal_Int32 *nStop, sal_Int32 *nStep, sal_Int32 *nSliceLength )
{
    Py_ssize_t nStart_ssize, nStop_ssize, nStep_ssize, nSliceLength_ssize;

    int nResult = PySlice_GetIndicesEx(
#if PY_VERSION_HEX >= 0x030200f0
        pObject,
#else
        reinterpret_cast<PySliceObject*>(pObject),
#endif
        nLen, &nStart_ssize, &nStop_ssize, &nStep_ssize, &nSliceLength_ssize );
    if (nResult == -1)
        return -1;

    if ( nStart_ssize > SAL_MAX_INT32 || nStart_ssize < SAL_MIN_INT32
         || nStop_ssize > SAL_MAX_INT32 || nStop_ssize < SAL_MIN_INT32
         || nStep_ssize > SAL_MAX_INT32 || nStep_ssize < SAL_MIN_INT32
         || nSliceLength_ssize > SAL_MAX_INT32 || nSliceLength_ssize < SAL_MIN_INT32 )
    {
        PyErr_SetString( PyExc_IndexError, "Python int too large to convert to UNO long" );
        return -1;
    }

    *nStart = static_cast<sal_Int32>(nStart_ssize);
    *nStop = static_cast<sal_Int32>(nStop_ssize);
    *nStep = static_cast<sal_Int32>(nStep_ssize);
    *nSliceLength = static_cast<sal_Int32>(nSliceLength_ssize);
    return 0;
}

static bool lcl_hasInterfaceByName( Any const &object, OUString const & interfaceName )
{
    Reference< XInterface > xInterface( object, UNO_QUERY );
    TypeDescription typeDesc( interfaceName );
    Any aInterface = xInterface->queryInterface( typeDesc.get()->pWeakRef );

    return aInterface.hasValue();
}

static PyObject *PyUNO_repr( PyObject  * self )
{
    return PyUNO_str( self );
}

static Py_hash_t PyUNO_hash( PyObject *self )
{

    PyUNO *me = reinterpret_cast<PyUNO *>(self);

    // Py_hash_t is not necessarily the same size as a pointer, but this is not
    // important for hashing - it just has to return the same value each time
    return sal::static_int_cast< Py_hash_t >( reinterpret_cast< sal_IntPtr > (
        *static_cast<void * const *>(me->members->wrappedObject.getValue()) ) );

}

PyObject *PyUNO_invoke( PyObject *object, const char *name , PyObject *args )
{
    PyRef ret;
    try
    {
        Runtime runtime;

        PyRef paras,callable;
        if( PyObject_IsInstance( object, getPyUnoClass().get() ) )
        {
            PyUNO* me = reinterpret_cast<PyUNO*>(object);
            OUString attrName = OUString::createFromAscii(name);
            if (! me->members->xInvocation->hasMethod (attrName))
            {
                throw RuntimeException( "Attribute " + attrName + " unknown" );
            }
            callable = PyUNO_callable_new (
                me->members->xInvocation,
                attrName,
                ACCEPT_UNO_ANY);
            paras = args;
        }
        else
        {
            // clean the tuple from uno.Any !
            int size = PyTuple_Size( args );
            { // for CC, keeping ref-count of tuple being 1
            paras = PyRef(PyTuple_New( size ), SAL_NO_ACQUIRE);
            }
            for( int i = 0 ; i < size ;i ++ )
            {
                PyObject * element = PyTuple_GetItem( args , i );
                if( PyObject_IsInstance( element , getAnyClass( runtime ).get() ) )
                {
                    element = PyObject_GetAttrString(
                        element, "value" );
                }
                else
                {
                    Py_XINCREF( element );
                }
                PyTuple_SetItem( paras.get(), i , element );
            }
            callable = PyRef( PyObject_GetAttrString( object , name ), SAL_NO_ACQUIRE );
            if( !callable.is() )
                return nullptr;
        }
        ret = PyRef( PyObject_CallObject( callable.get(), paras.get() ), SAL_NO_ACQUIRE );
    }
    catch (const css::lang::IllegalArgumentException &e)
    {
        raisePyExceptionWithAny( css::uno::makeAny( e ) );
    }
    catch (const css::script::CannotConvertException &e)
    {
        raisePyExceptionWithAny( css::uno::makeAny( e ) );
    }
    catch (const css::uno::RuntimeException &e)
    {
        raisePyExceptionWithAny( css::uno::makeAny( e ) );
    }
    catch (const css::uno::Exception &e)
    {
        raisePyExceptionWithAny( css::uno::makeAny( e ) );
    }

    return ret.getAcquired();
}

PyObject *PyUNO_str( PyObject * self )
{
    PyUNO *me = reinterpret_cast<PyUNO *>(self);

    OString buf;

    {
        PyThreadDetach antiguard;

        OUString s = val2str( me->members->wrappedObject.getValue(),
                              me->members->wrappedObject.getValueType().getTypeLibType() );
        buf = "pyuno object " + OUStringToOString(s,RTL_TEXTENCODING_ASCII_US);
    }

    return PyStr_FromString( buf.getStr() );
}

static PyObject* PyUNO_dir (PyObject* self)
{
    PyUNO* me = reinterpret_cast<PyUNO*>(self);

    PyObject* member_list = nullptr;
    Sequence<OUString> oo_member_list;

    try
    {
        oo_member_list = me->members->xInvocation->getMemberNames ();
        member_list = PyList_New (oo_member_list.getLength ());
        for (int i = 0; i < oo_member_list.getLength (); i++)
        {
            // setitem steals a reference
            PyList_SetItem (member_list, i, ustring2PyString(oo_member_list[i]).getAcquired() );
        }
    }
    catch( const RuntimeException &e )
    {
        raisePyExceptionWithAny( makeAny(e) );
    }

    return member_list;
}

static sal_Int32 lcl_detach_getLength( PyUNO const *me )
{
    PyThreadDetach antiguard;

    // If both XIndexContainer and XNameContainer are implemented, it is
    // assumed that getCount() gives the same result as the number of names
    // returned by getElementNames(), or the user may be surprised.

    // For XIndexContainer
    Reference< XIndexAccess > xIndexAccess( me->members->xInvocation, UNO_QUERY );
    if ( xIndexAccess.is() )
    {
        return xIndexAccess->getCount();
    }

    // For XNameContainer
    // Not terribly efficient - get the count of all the names
    Reference< XNameAccess > xNameAccess( me->members->xInvocation, UNO_QUERY );
    if ( xNameAccess.is() )
    {
        return xNameAccess->getElementNames().getLength();
    }

    return -1;
}

static int PyUNO_bool( PyObject* self )
{
    PyUNO* me = reinterpret_cast<PyUNO*>(self);

    try
    {
        int nLen = lcl_detach_getLength( me );
        if (nLen >= 0)
            return nLen == 0 ? 0 : 1;

        // Anything which doesn't have members is a scalar object and therefore true
        return 1;
    }
    catch( const css::uno::RuntimeException &e )
    {
        raisePyExceptionWithAny( css::uno::makeAny( e ) );
    }

    return -1;
}

static Py_ssize_t PyUNO_len( PyObject* self )
{
    PyUNO* me = reinterpret_cast<PyUNO*>(self);

    try
    {
        int nLen = lcl_detach_getLength( me );
        if (nLen >= 0)
            return nLen;

        PyErr_SetString( PyExc_TypeError, "object has no len()" );
    }
    catch( const css::uno::RuntimeException &e )
    {
        raisePyExceptionWithAny( css::uno::makeAny( e ) );
    }

    return -1;
}

static void lcl_getRowsColumns( PyUNO const * me, sal_Int32& nRows, sal_Int32& nColumns )
{
    Sequence<short> aOutParamIndex;
    Sequence<Any> aOutParam;
    Sequence<Any> aParams;
    Any aRet = me->members->xInvocation->invoke ( "getRows", aParams, aOutParamIndex, aOutParam );
    Reference< XIndexAccess > xIndexAccessRows( aRet, UNO_QUERY );
    nRows = xIndexAccessRows->getCount();
    aRet = me->members->xInvocation->invoke ( "getColumns", aParams, aOutParamIndex, aOutParam );
    Reference< XIndexAccess > xIndexAccessCols( aRet, UNO_QUERY );
    nColumns = xIndexAccessCols->getCount();
}

static PyRef lcl_indexToSlice( const PyRef& rIndex )
{
    Py_ssize_t nIndex = PyNumber_AsSsize_t( rIndex.get(), PyExc_IndexError );
    if (nIndex == -1 && PyErr_Occurred())
        return nullptr;
    PyRef rStart( PyLong_FromSsize_t( nIndex ), SAL_NO_ACQUIRE );
    PyRef rStop( PyLong_FromSsize_t( nIndex+1 ), SAL_NO_ACQUIRE );
    PyRef rStep( PyLong_FromLong( 1 ), SAL_NO_ACQUIRE );
    PyRef rSlice( PySlice_New( rStart.get(), rStop.get(), rStep.get() ), SAL_NO_ACQUIRE );

    return rSlice;
}

static PyObject* lcl_getitem_XCellRange( PyUNO const * me, PyObject* pKey )
{
    Runtime runtime;

    Sequence<short> aOutParamIndex;
    Sequence<Any> aOutParam;
    Sequence<Any> aParams;
    Any aRet;

    // Single string key is sugar for getCellRangeByName()
    if ( PyStr_Check( pKey ) ) {

        aParams.realloc (1);
        aParams[0] <<= pyString2ustring( pKey );
        {
            PyThreadDetach antiguard;
            aRet = me->members->xInvocation->invoke (
                "getCellRangeByName", aParams, aOutParamIndex, aOutParam );
        }
        PyRef rRet = runtime.any2PyObject ( aRet );
        return rRet.getAcquired();

    }

    PyRef rKey0, rKey1;
    if ( PyIndex_Check( pKey ) )
    {
        // [0] is equivalent to [0,:]
        rKey0 = pKey;
        rKey1 = PySlice_New( nullptr, nullptr, nullptr );
    }
    else if ( PyTuple_Check( pKey ) && (PyTuple_Size( pKey ) == 2) )
    {
        rKey0 = PyTuple_GetItem( pKey, 0 );
        rKey1 = PyTuple_GetItem( pKey, 1 );
    }
    else
    {
        PyErr_SetString( PyExc_KeyError, "invalid subscript" );
        return nullptr;
    }

    // If both keys are indices, return the corresponding cell
    if ( PyIndex_Check( rKey0.get() ) && PyIndex_Check( rKey1.get() ))
    {
        sal_Int32 nKey0_s = lcl_PyNumber_AsSal_Int32( rKey0.get() );
        sal_Int32 nKey1_s = lcl_PyNumber_AsSal_Int32( rKey1.get() );

        if ( ((nKey0_s == -1) || (nKey1_s == -1)) && PyErr_Occurred() )
            return nullptr;

        aParams.realloc( 2 );
        aParams[0] <<= nKey1_s;
        aParams[1] <<= nKey0_s;
        {
            PyThreadDetach antiguard;
            aRet = me->members->xInvocation->invoke (
                "getCellByPosition", aParams, aOutParamIndex, aOutParam );
        }
        PyRef rRet = runtime.any2PyObject( aRet );
        return rRet.getAcquired();
    }

    // If either argument is an index, coerce it to a slice
    if ( PyIndex_Check( rKey0.get() ) )
        rKey0 = lcl_indexToSlice( rKey0 );

    if ( PyIndex_Check( rKey1.get() ) )
        rKey1 = lcl_indexToSlice( rKey1 );

    // If both arguments are slices, return the corresponding cell range
    if ( PySlice_Check( rKey0.get() ) && PySlice_Check( rKey1.get() ) )
    {
        sal_Int32 nLen0 = SAL_MAX_INT32, nLen1 = SAL_MAX_INT32;
        sal_Int32 nStart0 = 0, nStop0 = 0, nStep0 = 0, nSliceLength0 = 0;
        sal_Int32 nStart1 = 0, nStop1 = 0, nStep1 = 0, nSliceLength1 = 0;

        {
            PyThreadDetach antiguard;

            if ( lcl_hasInterfaceByName( me->members->wrappedObject, "com.sun.star.table.XColumnRowRange" ) )
            {
                lcl_getRowsColumns (me, nLen0, nLen1);
            }
        }

        int nSuccess1 = lcl_PySlice_GetIndicesEx( rKey0.get(), nLen0, &nStart0, &nStop0, &nStep0, &nSliceLength0 );
        int nSuccess2 = lcl_PySlice_GetIndicesEx( rKey1.get(), nLen1, &nStart1, &nStop1, &nStep1, &nSliceLength1 );
        if ( ((nSuccess1 == -1) || (nSuccess2 == -1)) && PyErr_Occurred() )
            return nullptr;

        if ( nSliceLength0 <= 0 || nSliceLength1 <= 0 )
        {
            PyErr_SetString( PyExc_KeyError, "invalid number of rows or columns" );
            return nullptr;
        }

        if ( nStep0 == 1 && nStep1 == 1 )
        {
            aParams.realloc (4);
            aParams[0] <<= nStart1;
            aParams[1] <<= nStart0;
            aParams[2] <<= nStop1 - 1;
            aParams[3] <<= nStop0 - 1;
            {
                PyThreadDetach antiguard;
                aRet = me->members->xInvocation->invoke (
                    "getCellRangeByPosition", aParams, aOutParamIndex, aOutParam );
            }
            PyRef rRet = runtime.any2PyObject( aRet );
            return rRet.getAcquired();
        }

        PyErr_SetString( PyExc_KeyError, "step != 1 not supported" );
        return nullptr;
    }

    PyErr_SetString( PyExc_KeyError, "invalid subscript" );
    return nullptr;
}

static PyObject* lcl_getitem_index( PyUNO const *me, PyObject *pKey, Runtime const & runtime )
{
    Any aRet;
    sal_Int32 nIndex;

    nIndex = lcl_PyNumber_AsSal_Int32( pKey );
    if (nIndex == -1 && PyErr_Occurred())
        return nullptr;

    {
        PyThreadDetach antiguard;

        Reference< XIndexAccess > xIndexAccess( me->members->xInvocation, UNO_QUERY );
        if ( xIndexAccess.is() )
        {
            if (nIndex < 0)
                nIndex += xIndexAccess->getCount();
            aRet = xIndexAccess->getByIndex( nIndex );
        }
    }
    if ( aRet.hasValue() )
    {
        PyRef rRet ( runtime.any2PyObject( aRet ) );
        return rRet.getAcquired();
    }

    return nullptr;
}

static PyObject* lcl_getitem_slice( PyUNO const *me, PyObject *pKey )
{
    Runtime runtime;

    Reference< XIndexAccess > xIndexAccess;
    sal_Int32 nLen = 0;

    {
        PyThreadDetach antiguard;

        xIndexAccess.set( me->members->xInvocation, UNO_QUERY );
        if ( xIndexAccess.is() )
            nLen = xIndexAccess->getCount();
    }

    if ( xIndexAccess.is() )
    {
        sal_Int32 nStart = 0, nStop = 0, nStep = 0, nSliceLength = 0;
        int nSuccess = lcl_PySlice_GetIndicesEx(pKey, nLen, &nStart, &nStop, &nStep, &nSliceLength);
        if ( nSuccess == -1 && PyErr_Occurred() )
            return nullptr;

        PyRef rTuple( PyTuple_New( nSliceLength ), SAL_NO_ACQUIRE, NOT_NULL );
        sal_Int32 nCur, i;
        for ( nCur = nStart, i = 0; i < nSliceLength; nCur += nStep, i++ )
        {
            Any aRet;

            {
                PyThreadDetach antiguard;

                aRet = xIndexAccess->getByIndex( nCur );
            }
            PyRef rRet = runtime.any2PyObject( aRet );
            PyTuple_SetItem( rTuple.get(), i, rRet.getAcquired() );
        }

        return rTuple.getAcquired();
    }

    return nullptr;
}

static PyObject* lcl_getitem_string( PyUNO const *me, PyObject *pKey, Runtime const & runtime )
{
    OUString sKey = pyString2ustring( pKey );
    Any aRet;

    {
        PyThreadDetach antiguard;

        Reference< XNameAccess > xNameAccess( me->members->xInvocation, UNO_QUERY );
        if ( xNameAccess.is() )
        {
            aRet = xNameAccess->getByName( sKey );
        }
    }
    if ( aRet.hasValue() )
    {
        PyRef rRet = runtime.any2PyObject( aRet );
        return rRet.getAcquired();
    }

    return nullptr;
}

static PyObject* PyUNO_getitem( PyObject *self, PyObject *pKey )
{
    PyUNO* me = reinterpret_cast<PyUNO*>(self);
    Runtime runtime;

    try
    {
        // XIndexAccess access by index
        if ( PyIndex_Check( pKey ) )
        {
            PyObject* pRet = lcl_getitem_index( me, pKey, runtime );
            if ( pRet != nullptr || PyErr_Occurred() )
                return pRet;
        }

        // XIndexAccess access by slice
        if ( PySlice_Check( pKey ) )
        {
            PyObject* pRet = lcl_getitem_slice( me, pKey );
            if ( pRet != nullptr || PyErr_Occurred() )
                return pRet;
        }

        // XNameAccess access by key
        if ( PyStr_Check( pKey ) )
        {
            PyObject* pRet = lcl_getitem_string( me, pKey, runtime );
            if ( pRet != nullptr )
                return pRet;
        }

        // XCellRange/XColumnRowRange specialisation
        // Uses reflection as we can't have a hard dependency on XCellRange here
        bool hasXCellRange = false;

        {
            PyThreadDetach antiguard;

            hasXCellRange = lcl_hasInterfaceByName( me->members->wrappedObject, "com.sun.star.table.XCellRange" );
        }
        if ( hasXCellRange )
        {
            return lcl_getitem_XCellRange( me, pKey );
        }


        // If the object is an XIndexAccess and/or XNameAccess, but the
        // key passed wasn't suitable, give a TypeError which specifically
        // describes this
        Reference< XIndexAccess > xIndexAccess( me->members->xInvocation, UNO_QUERY );
        Reference< XNameAccess > xNameAccess( me->members->xInvocation, UNO_QUERY );
        if ( xIndexAccess.is() || xNameAccess.is() )
        {
            PyErr_SetString( PyExc_TypeError, "subscription with invalid type" );
            return nullptr;
        }

        PyErr_SetString( PyExc_TypeError, "object is not subscriptable" );
    }
    catch( const css::lang::IndexOutOfBoundsException & )
    {
        PyErr_SetString( PyExc_IndexError, "index out of range" );
    }
    catch( const css::container::NoSuchElementException & )
    {
        PyErr_SetString( PyExc_KeyError, "key not found" );
    }
    catch( const css::script::CannotConvertException &e )
    {
        raisePyExceptionWithAny( css::uno::makeAny( e ) );
    }
    catch( const css::lang::IllegalArgumentException &e )
    {
        raisePyExceptionWithAny( css::uno::makeAny( e ) );
    }
    catch( const css::lang::WrappedTargetException &e )
    {
        raisePyExceptionWithAny( css::uno::makeAny( e ) );
    }
    catch( const css::uno::RuntimeException &e )
    {
        raisePyExceptionWithAny( css::uno::makeAny( e ) );
    }

    return nullptr;
}

static int lcl_setitem_index( PyUNO const *me, PyObject *pKey, PyObject *pValue )
{
    Runtime runtime;

    Reference< XIndexContainer > xIndexContainer;
    Reference< XIndexReplace > xIndexReplace;
    sal_Int32 nIndex = lcl_PyNumber_AsSal_Int32( pKey );
    if ( nIndex == -1 && PyErr_Occurred() )
        return 0;

    bool isTuple = false;

    Any aValue;
    if ( pValue != nullptr )
    {
        isTuple = PyTuple_Check( pValue );

        try
        {
            aValue = runtime.pyObject2Any( pValue );
        }
        catch ( const css::uno::RuntimeException & )
        {
            // TODO pyObject2Any can't convert e.g. dicts but only throws
            // RuntimeException on failure. Fixing this will require an audit of
            // all the rest of PyUNO
            throw css::script::CannotConvertException();
        }
    }

    {
        PyThreadDetach antiguard;

        xIndexContainer.set( me->members->xInvocation, UNO_QUERY );
        if ( xIndexContainer.is() )
            xIndexReplace = xIndexContainer;
        else
            xIndexReplace.set( me->members->xInvocation, UNO_QUERY );

        if ( xIndexReplace.is() && nIndex < 0 )
            nIndex += xIndexReplace->getCount();

        // XIndexReplace replace by index
        if ( (pValue != nullptr) && xIndexReplace.is() )
        {
            if ( isTuple )
            {
                // Apply type specialisation to ensure the correct kind of sequence is passed
                Type aType = xIndexReplace->getElementType();
                aValue = runtime.getImpl()->cargo->xTypeConverter->convertTo( aValue, aType );
            }

            xIndexReplace->replaceByIndex( nIndex, aValue );
            return 0;
        }

        // XIndexContainer remove by index
        if ( (pValue == nullptr) && xIndexContainer.is() )
        {
            xIndexContainer->removeByIndex( nIndex );
            return 0;
        }
    }

    PyErr_SetString( PyExc_TypeError, "cannot assign to object" );
    return 1;
}

static int lcl_setitem_slice( PyUNO const *me, PyObject *pKey, PyObject *pValue )
{
    // XIndexContainer insert/remove/replace by slice
    Runtime runtime;

    Reference< XIndexReplace > xIndexReplace;
    Reference< XIndexContainer > xIndexContainer;
    sal_Int32 nLen = 0;

    {
        PyThreadDetach antiguard;

        xIndexContainer.set( me->members->xInvocation, UNO_QUERY );
        if ( xIndexContainer.is() )
            xIndexReplace = xIndexContainer;
        else
            xIndexReplace.set( me->members->xInvocation, UNO_QUERY );

        if ( xIndexReplace.is() )
            nLen = xIndexReplace->getCount();
    }

    if ( xIndexReplace.is() )
    {
        sal_Int32 nStart = 0, nStop = 0, nStep = 0, nSliceLength = 0;
        int nSuccess = lcl_PySlice_GetIndicesEx( pKey, nLen, &nStart, &nStop, &nStep, &nSliceLength );
        if ( (nSuccess == -1) && PyErr_Occurred() )
            return 0;

        if ( pValue == nullptr )
        {
            pValue = PyTuple_New( 0 );
        }

        if ( !PyTuple_Check (pValue) )
        {
            PyErr_SetString( PyExc_TypeError, "value is not a tuple" );
            return 1;
        }

        Py_ssize_t nTupleLength_ssize = PyTuple_Size( pValue );
        if ( nTupleLength_ssize > SAL_MAX_INT32 )
        {
            PyErr_SetString( PyExc_ValueError, "tuple too large" );
            return 1;
        }
        sal_Int32 nTupleLength = static_cast<sal_Int32>(nTupleLength_ssize);

        if ( (nTupleLength != nSliceLength) && (nStep != 1) )
        {
            PyErr_SetString( PyExc_ValueError, "number of items assigned must be equal" );
            return 1;
        }

        if ( (nTupleLength != nSliceLength) && !xIndexContainer.is() )
        {
            PyErr_SetString( PyExc_ValueError, "cannot change length" );
            return 1;
        }

        sal_Int32 nCur, i;
        sal_Int32 nMax = ::std::max( nSliceLength, nTupleLength );
        for ( nCur = nStart, i = 0; i < nMax; nCur += nStep, i++ )
        {
            if ( i < nTupleLength )
            {
                PyRef rItem = PyTuple_GetItem( pValue, i );
                bool isTuple = PyTuple_Check( rItem.get() );

                Any aItem;
                try
                {
                    aItem = runtime.pyObject2Any( rItem.get() );
                }
                catch ( const css::uno::RuntimeException & )
                {
                    // TODO pyObject2Any can't convert e.g. dicts but only throws
                    // RuntimeException on failure. Fixing this will require an audit of
                    // all the rest of PyUNO
                    throw css::script::CannotConvertException();
                }

                {
                    PyThreadDetach antiguard;

                    if ( isTuple )
                    {
                        // Apply type specialisation to ensure the correct kind of sequence is passed
                        Type aType = xIndexReplace->getElementType();
                        aItem = runtime.getImpl()->cargo->xTypeConverter->convertTo( aItem, aType );
                    }

                    if ( i < nSliceLength )
                    {
                        xIndexReplace->replaceByIndex( nCur, aItem );
                    }
                    else
                    {
                        xIndexContainer->insertByIndex( nCur, aItem );
                    }
                }
            }
            else
            {
                PyThreadDetach antiguard;

                xIndexContainer->removeByIndex( nCur );
                nCur--;
            }
        }

        return 0;
    }

    PyErr_SetString( PyExc_TypeError, "cannot assign to object" );
    return 1;
}

static int lcl_setitem_string( PyUNO const *me, PyObject *pKey, PyObject *pValue )
{
    Runtime runtime;

    OUString sKey = pyString2ustring( pKey );
    bool isTuple = false;

    Any aValue;
    if ( pValue != nullptr)
    {
        isTuple = PyTuple_Check( pValue );
        try
        {
            aValue = runtime.pyObject2Any( pValue );
        }
        catch( const css::uno::RuntimeException & )
        {
            // TODO pyObject2Any can't convert e.g. dicts but only throws
            // RuntimeException on failure. Fixing this will require an audit of
            // all the rest of PyUNO
            throw css::script::CannotConvertException();
        }
    }

    {
        PyThreadDetach antiguard;

        Reference< XNameContainer > xNameContainer( me->members->xInvocation, UNO_QUERY );
        Reference< XNameReplace > xNameReplace;
        if ( xNameContainer.is() )
            xNameReplace = xNameContainer;
        else
            xNameReplace.set( me->members->xInvocation, UNO_QUERY );

        if ( xNameReplace.is() )
        {
            if ( isTuple && aValue.hasValue() )
            {
                // Apply type specialisation to ensure the correct kind of sequence is passed
                Type aType = xNameReplace->getElementType();
                aValue = runtime.getImpl()->cargo->xTypeConverter->convertTo( aValue, aType );
            }

            if ( aValue.hasValue() )
            {
                if ( xNameContainer.is() )
                {
                    try {
                        xNameContainer->insertByName( sKey, aValue );
                        return 0;
                    }
                    catch( const css::container::ElementExistException & )
                    {
                        // Fall through, try replace instead
                    }
                }

                xNameReplace->replaceByName( sKey, aValue );
                return 0;
            }
            else if ( xNameContainer.is() )
            {
                xNameContainer->removeByName( sKey );
                return 0;
            }
        }
    }

    PyErr_SetString( PyExc_TypeError, "cannot assign to object" );
    return 1;
}

static int PyUNO_setitem( PyObject *self, PyObject *pKey, PyObject *pValue )
{
    PyUNO* me = reinterpret_cast<PyUNO*>(self);

    try
    {
        if ( PyIndex_Check( pKey ) )
        {
            return lcl_setitem_index( me, pKey, pValue );
        }
        else if ( PySlice_Check( pKey ) )
        {
            return lcl_setitem_slice( me, pKey, pValue );
        }
        else if ( PyStr_Check( pKey ) )
        {
            return lcl_setitem_string( me, pKey, pValue );
        }

        PyErr_SetString( PyExc_TypeError, "list index has invalid type" );
    }
    catch( const css::lang::IndexOutOfBoundsException & )
    {
        PyErr_SetString( PyExc_IndexError, "list index out of range" );
    }
    catch( const css::container::NoSuchElementException & )
    {
        PyErr_SetString( PyExc_KeyError, "key not found" );
    }
    catch( const css::lang::IllegalArgumentException & )
    {
        PyErr_SetString( PyExc_TypeError, "value has invalid type" );
    }
    catch( const css::script::CannotConvertException & )
    {
        PyErr_SetString( PyExc_TypeError, "value has invalid type" );
    }
    catch( const css::container::ElementExistException &e )
    {
        raisePyExceptionWithAny( css::uno::makeAny( e ) );
    }
    catch( const css::lang::WrappedTargetException &e )
    {
        raisePyExceptionWithAny( css::uno::makeAny( e ) );
    }
    catch( const css::uno::RuntimeException &e )
    {
        raisePyExceptionWithAny( css::uno::makeAny( e ) );
    }

    return 1;
}

static PyObject* PyUNO_iter( PyObject *self )
{
    PyUNO* me = reinterpret_cast<PyUNO*>(self);

    try
    {
        Reference< XEnumerationAccess > xEnumerationAccess;
        Reference< XEnumeration > xEnumeration;
        Reference< XIndexAccess > xIndexAccess;
        Reference< XNameAccess > xNameAccess;

        {
            PyThreadDetach antiguard;

            xEnumerationAccess.set( me->members->xInvocation, UNO_QUERY );
            if ( xEnumerationAccess.is() )
                xEnumeration = xEnumerationAccess->createEnumeration();
            else
                xEnumeration.set( me->members->wrappedObject, UNO_QUERY );

            if ( !xEnumeration.is() )
                xIndexAccess.set( me->members->xInvocation, UNO_QUERY );

            if ( !xIndexAccess.is() )
                xNameAccess.set( me->members->xInvocation, UNO_QUERY );
        }

        // XEnumerationAccess iterator
        // XEnumeration iterator
        if (xEnumeration.is())
        {
            return PyUNO_iterator_new( xEnumeration );
        }

        // XIndexAccess iterator
        if ( xIndexAccess.is() )
        {
            // We'd like to be able to use PySeqIter_New() here, but we're not
            // allowed to because we also implement the mapping protocol
            return PyUNO_list_iterator_new( xIndexAccess );
        }

        // XNameAccess iterator
        if (xNameAccess.is())
        {
            // There's no generic mapping iterator, but we can cobble our own
            // together using PySeqIter_New()
            Runtime runtime;
            Any aRet;

            {
                PyThreadDetach antiguard;
                aRet <<= xNameAccess->getElementNames();
            }
            PyRef rNames = runtime.any2PyObject( aRet );
            return PySeqIter_New( rNames.getAcquired() );
        }

        PyErr_SetString ( PyExc_TypeError, "object is not iterable" );
    }
    catch( css::script::CannotConvertException &e )
    {
        raisePyExceptionWithAny( css::uno::makeAny( e ) );
    }
    catch( css::lang::IllegalArgumentException &e )
    {
        raisePyExceptionWithAny( css::uno::makeAny( e ) );
    }
    catch( const css::uno::RuntimeException &e )
    {
        raisePyExceptionWithAny( css::uno::makeAny( e ) );
    }

    return nullptr;
}

static int PyUNO_contains( PyObject *self, PyObject *pKey )
{
    PyUNO* me = reinterpret_cast<PyUNO*>(self);

    Runtime runtime;

    try
    {
        Any aValue;
        try
        {
            aValue = runtime.pyObject2Any( pKey );
        }
        catch( const css::uno::RuntimeException & )
        {
            // TODO pyObject2Any can't convert e.g. dicts but only throws
            // RuntimeException on failure. Fixing this will require an audit of
            // all the rest of PyUNO
            throw css::script::CannotConvertException();
        }

        // XNameAccess is tried first, because checking key presence is much more
        // useful for objects which implement both XIndexAccess and XNameAccess

        // For XNameAccess
        if ( PyStr_Check( pKey ) )
        {
            OUString sKey;
            aValue >>= sKey;
            Reference< XNameAccess > xNameAccess;

            {
                PyThreadDetach antiguard;

                xNameAccess.set( me->members->xInvocation, UNO_QUERY );
                if ( xNameAccess.is() )
                {
                    bool hasKey = xNameAccess->hasByName( sKey );
                    return hasKey ? 1 : 0;
                }
            }
        }

        // For any other type of PyUNO iterable: Ugly iterative search by
        // content (XIndexAccess, XEnumerationAccess, XEnumeration)
        PyRef rIterator( PyUNO_iter( self ), SAL_NO_ACQUIRE );
        if ( rIterator.is() )
        {
            while ( PyObject* pItem = PyIter_Next( rIterator.get() ) )
            {
                PyRef rItem( pItem, SAL_NO_ACQUIRE );
                if ( PyObject_RichCompareBool( pKey, rItem.get(), Py_EQ ) == 1 )
                {
                    return 1;
                }
            }
            return 0;
        }

        PyErr_SetString( PyExc_TypeError, "argument is not iterable" );
    }
    catch( const css::script::CannotConvertException& )
    {
        PyErr_SetString( PyExc_TypeError, "invalid type passed as left argument to 'in'" );
    }
    catch( const css::container::NoSuchElementException &e )
    {
        raisePyExceptionWithAny( css::uno::makeAny( e ) );
    }
    catch( const css::lang::IndexOutOfBoundsException &e )
    {
        raisePyExceptionWithAny( css::uno::makeAny( e ) );
    }
    catch( const css::lang::IllegalArgumentException &e )
    {
        raisePyExceptionWithAny( css::uno::makeAny( e ) );
    }
    catch( const css::lang::WrappedTargetException &e )
    {
        raisePyExceptionWithAny( css::uno::makeAny( e ) );
    }
    catch( const css::uno::RuntimeException &e )
    {
        raisePyExceptionWithAny( css::uno::makeAny( e ) );
    }

    return -1;
}

static PyObject* PyUNO_getattr (PyObject* self, char* name)
{
    PyUNO* me;

    try
    {

        Runtime runtime;

        me = reinterpret_cast<PyUNO*>(self);
        if (strcmp (name, "__dict__") == 0)
        {
            Py_INCREF (Py_TYPE(me)->tp_dict);
            return Py_TYPE(me)->tp_dict;
        }
        if (strcmp (name, "__class__") == 0)
        {
            Py_INCREF (Py_None);
            return Py_None;
        }

        PyObject *pRet = PyObject_GenericGetAttr( self, PyUnicode_FromString( name ) );
        if( pRet )
            return pRet;
        PyErr_Clear();

        OUString attrName( OUString::createFromAscii( name ) );
        //We need to find out if it's a method...
        if (me->members->xInvocation->hasMethod (attrName))
        {
            //Create a callable object to invoke this...
            PyRef ret = PyUNO_callable_new (
                me->members->xInvocation,
                attrName);
            Py_XINCREF( ret.get() );
            return ret.get();

        }

        //or a property
        if (me->members->xInvocation->hasProperty ( attrName))
        {
            //Return the value of the property
            Any anyRet;
            {
                PyThreadDetach antiguard;
                anyRet = me->members->xInvocation->getValue (attrName);
            }
            PyRef ret = runtime.any2PyObject(anyRet);
            Py_XINCREF( ret.get() );
            return ret.get();
        }

        //or else...
        PyErr_SetString (PyExc_AttributeError, name);
    }
    catch( const css::reflection::InvocationTargetException & e )
    {
        raisePyExceptionWithAny( e.TargetException );
    }
    catch( const css::beans::UnknownPropertyException & e )
    {
        raisePyExceptionWithAny( makeAny(e) );
    }
    catch( const css::lang::IllegalArgumentException &e )
    {
        raisePyExceptionWithAny( makeAny(e) );
    }
    catch( const css::script::CannotConvertException &e )
    {
        raisePyExceptionWithAny( makeAny(e) );
    }
    catch( const RuntimeException &e )
    {
        raisePyExceptionWithAny( makeAny(e) );
    }

    return nullptr;
}

static int PyUNO_setattr (PyObject* self, char* name, PyObject* value)
{
    PyUNO* me;

    me = reinterpret_cast<PyUNO*>(self);
    try
    {
        Runtime runtime;
        Any val= runtime.pyObject2Any(value, ACCEPT_UNO_ANY);

        OUString attrName( OUString::createFromAscii( name ) );
        {
            PyThreadDetach antiguard;
            if (me->members->xInvocation->hasProperty (attrName))
            {
                me->members->xInvocation->setValue (attrName, val);
                return 0; //Keep with Python's boolean system
            }
        }
    }
    catch( const css::reflection::InvocationTargetException & e )
    {
        raisePyExceptionWithAny( e.TargetException );
        return 1;
    }
    catch( const css::beans::UnknownPropertyException & e )
    {
        raisePyExceptionWithAny( makeAny(e) );
        return 1;
    }
    catch( const css::script::CannotConvertException &e )
    {
        raisePyExceptionWithAny( makeAny(e) );
        return 1;
    }
    catch( const RuntimeException & e )
    {
        raisePyExceptionWithAny( makeAny( e ) );
        return 1;
    }
    PyErr_SetString (PyExc_AttributeError, name);
    return 1; //as above.
}

static PyObject* PyUNO_cmp( PyObject *self, PyObject *that, int op )
{
    PyObject *result;

    if(op != Py_EQ && op != Py_NE)
    {
        PyErr_SetString(PyExc_TypeError, "only '==' and '!=' comparisons are defined");
        return nullptr;
    }
    if( self == that )
    {
        result = (op == Py_EQ ? Py_True : Py_False);
        Py_INCREF(result);
        return result;
    }
    try
    {
        Runtime runtime;
        if( PyObject_IsInstance( that, getPyUnoClass().get() ) )
        {

            PyUNO *me = reinterpret_cast< PyUNO*> ( self );
            PyUNO *other = reinterpret_cast< PyUNO *> (that );
            css::uno::TypeClass tcMe = me->members->wrappedObject.getValueTypeClass();
            css::uno::TypeClass tcOther = other->members->wrappedObject.getValueTypeClass();

            if( tcMe == tcOther )
            {
                if( me->members->wrappedObject == other->members->wrappedObject )
                {
                    result = (op == Py_EQ ? Py_True : Py_False);
                    Py_INCREF(result);
                    return result;
                }
            }
        }
    }
    catch( const css::uno::RuntimeException & e)
    {
        raisePyExceptionWithAny( makeAny( e ) );
    }

    result = (op == Py_EQ ? Py_False : Py_True);
    Py_INCREF(result);
    return result;
}

static PyMethodDef PyUNOMethods[] =
{
    {"__dir__",    reinterpret_cast<PyCFunction>(PyUNO_dir),    METH_NOARGS,  nullptr},
    {nullptr,         nullptr,                                        0,            nullptr}
};

static PyNumberMethods PyUNONumberMethods[] =
{
    nullptr,                                         /* nb_add */
    nullptr,                                         /* nb_subtract */
    nullptr,                                         /* nb_multiply */
#if PY_MAJOR_VERSION < 3
    nullptr,                                         /* nb_divide */
#endif
    nullptr,                                         /* nb_remainder */
    nullptr,                                         /* nb_divmod */
    nullptr,                                         /* nb_power */
    nullptr,                                         /* nb_negative */
    nullptr,                                         /* nb_positive */
    nullptr,                                         /* nb_absolute */
    PyUNO_bool,                                      /* nb_bool */
    nullptr,                                         /* nb_invert */
    nullptr,                                         /* nb_lshift */
    nullptr,                                         /* nb_rshift */
    nullptr,                                         /* nb_and */
    nullptr,                                         /* nb_xor */
    nullptr,                                         /* nb_or */
#if PY_MAJOR_VERSION < 3
    nullptr,                                         /* nb_coerce */
#endif
    nullptr,                                         /* nb_int */
    nullptr,                                         /* nb_reserved */
    nullptr,                                         /* nb_float */
#if PY_MAJOR_VERSION < 3
    nullptr,                                         /* nb_oct */
    nullptr,                                         /* nb_hex */
#endif
    nullptr,                                         /* nb_inplace_add */
    nullptr,                                         /* nb_inplace_subtract */
    nullptr,                                         /* nb_inplace_multiply */
#if PY_MAJOR_VERSION < 3
    nullptr,                                         /* nb_inplace_divide */
#endif
    nullptr,                                         /* nb_inplace_remainder */
    nullptr,                                         /* nb_inplace_power */
    nullptr,                                         /* nb_inplace_lshift */
    nullptr,                                         /* nb_inplace_rshift */
    nullptr,                                         /* nb_inplace_and */
    nullptr,                                         /* nb_inplace_xor */
    nullptr,                                         /* nb_inplace_or */

    nullptr,                                         /* nb_floor_divide */
    nullptr,                                         /* nb_true_divide */
    nullptr,                                         /* nb_inplace_floor_divide */
    nullptr,                                         /* nb_inplace_true_divide */

    nullptr,                                         /* nb_index */
#if PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 5
    nullptr,                                         /* nb_matrix_multiply */
    nullptr,                                         /* nb_inplace_matrix_multiply */
#endif
};

static PySequenceMethods PyUNOSequenceMethods[] =
{
    nullptr,                                         /* sq_length */
    nullptr,                                         /* sq_concat */
    nullptr,                                         /* sq_repeat */
    nullptr,                                         /* sq_item */
    nullptr,                                         /* sq_slice */
    nullptr,                                         /* sq_ass_item */
    nullptr,                                         /* sq_ass_slice */
    PyUNO_contains,                                  /* sq_contains */
    nullptr,                                         /* sq_inplace_concat */
    nullptr                                          /* sq_inplace_repeat */
};

static PyMappingMethods PyUNOMappingMethods[] =
{
    PyUNO_len,                                       /* mp_length */
    PyUNO_getitem,                                   /* mp_subscript */
    PyUNO_setitem,                                   /* mp_ass_subscript */
};

static PyTypeObject PyUNOType =
{
    PyVarObject_HEAD_INIT( &PyType_Type, 0 )
    "pyuno",
    sizeof (PyUNO),
    0,
    PyUNO_del,
#if PY_VERSION_HEX >= 0x03080000
    0, // Py_ssize_t tp_vectorcall_offset
#else
    nullptr, // printfunc tp_print
#endif
    PyUNO_getattr,
    PyUNO_setattr,
    /* this type does not exist in Python 3: (cmpfunc) */ nullptr,
    PyUNO_repr,
    PyUNONumberMethods,
    PyUNOSequenceMethods,
    PyUNOMappingMethods,
    PyUNO_hash,
    nullptr,
    PyUNO_str,
    nullptr,
    nullptr,
    nullptr,
    Py_TPFLAGS_HAVE_ITER | Py_TPFLAGS_HAVE_RICHCOMPARE | Py_TPFLAGS_HAVE_SEQUENCE_IN,
    nullptr,
    nullptr,
    nullptr,
    PyUNO_cmp,
    0,
    PyUNO_iter,
    nullptr,
    PyUNOMethods,
    nullptr,
    nullptr,
    nullptr,
    nullptr,
    nullptr,
    nullptr,
    0,
    nullptr,
    nullptr,
    nullptr,
    nullptr,
    nullptr,
    nullptr,
    nullptr,
    nullptr,
    nullptr,
    nullptr,
    nullptr
    , 0
#if PY_VERSION_HEX >= 0x03040000
    , nullptr
#if PY_VERSION_HEX >= 0x03080000
    , nullptr // vectorcallfunc tp_vectorcall
#endif
#endif
};

int PyUNO_initType()
{
    return PyType_Ready(&PyUNOType);
}

PyRef getPyUnoClass()
{
    return PyRef( reinterpret_cast< PyObject * > ( &PyUNOType ) );
}

PyRef PyUNO_new (
    const Any &targetInterface,
    const Reference<XSingleServiceFactory> &ssf )
{
    Reference<XInvocation2> xInvocation;

    {
        PyThreadDetach antiguard;
        xInvocation.set(
            ssf->createInstanceWithArguments( Sequence<Any>( &targetInterface, 1 ) ), css::uno::UNO_QUERY_THROW );

        auto that = comphelper::getUnoTunnelImplementation<Adapter>(
            xInvocation->getIntrospection()->queryAdapter(cppu::UnoType<XUnoTunnel>::get()));
        if( that )
            return that->getWrappedObject();
    }
    if( !Py_IsInitialized() )
        throw RuntimeException();

    PyUNO* self = PyObject_New (PyUNO, &PyUNOType);
    if (self == nullptr)
        return PyRef(); // == error
    self->members = new PyUNOInternals;
    self->members->xInvocation = xInvocation;
    self->members->wrappedObject = targetInterface;
    return PyRef( reinterpret_cast<PyObject*>(self), SAL_NO_ACQUIRE );

}

}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */