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
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617 | diff -urN pyotherside-1.4.0~git20150111/docs/conf.py pyotherside/docs/conf.py
--- pyotherside-1.4.0~git20150111/docs/conf.py 2015-02-18 12:07:06.000000000 +0200
+++ pyotherside/docs/conf.py 2015-02-18 12:18:28.787571658 +0200
@@ -48,9 +48,9 @@
# built documents.
#
# The short X.Y version.
-version = '1.3'
+version = '1.4'
# The full version, including alpha/beta/rc tags.
-release = '1.3.0'
+release = '1.4.0'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
diff -urN pyotherside-1.4.0~git20150111/docs/index.rst pyotherside/docs/index.rst
--- pyotherside-1.4.0~git20150111/docs/index.rst 2015-02-18 12:07:06.000000000 +0200
+++ pyotherside/docs/index.rst 2015-02-18 12:18:28.787571658 +0200
@@ -28,7 +28,7 @@
Import Versions
---------------
-The current QML API version of PyOtherSide is 1.3. When new features are
+The current QML API version of PyOtherSide is 1.4. When new features are
introduced, or behavior is changed, the API version will be bumped and
documented here.
@@ -55,6 +55,18 @@
your Python files are embedded as Qt Resources, relative to your QML files
(use :func:`Qt.resolvedUrl` from the QML file).
+io.thp.pyotherside 1.4
+``````````````````````
+
+* Added :func:`getattr`
+
+* :func:`call` and :func:`call_sync` now accept a Python callable object
+ for the first parameter (previously, only strings were supported)
+
+* If :func:`error` doesn't have a handler defined, error messages will be
+ printed to the console as warnings
+
+
QML ``Python`` Element
----------------------
@@ -67,7 +79,7 @@
.. code-block:: javascript
- import io.thp.pyotherside 1.3
+ import io.thp.pyotherside 1.4
Signals
```````
@@ -81,6 +93,12 @@
Error handler for errors from Python.
+.. versionchanged:: 1.4.0
+ If the error signal is not connected, PyOtherSide will print the
+ error as QWarning on the console (previously, error messages
+ were only shown if the signal was connected and printed there).
+ To avoid printing the error, just define a no-op handler.
+
Methods
```````
@@ -127,7 +145,7 @@
Once modules are imported, Python function can be called on the
imported modules using:
-.. function:: call(string func, args=[], function callback(result) {})
+.. function:: call(var func, args=[], function callback(result) {})
Call the Python function ``func`` with ``args`` asynchronously.
If ``args`` is omitted, ``func`` will be called without arguments.
@@ -139,16 +157,8 @@
signal is emitted with ``traceback`` containing the exception info
(QML API version 1.2 and newer).
-.. function:: callMethod(obj, string method, args=[], function callback(result) {})
-
- Call the Python method ``method`` on object ``obj`` with ``args``
- asynchronously.
- If ``args`` is omitted, ``method`` will be called without arguments.
- If ``callback`` is a callable, it will be called with the Python
- method result as single argument when the call has succeeded.
-
- If a JavaScript exception occurs in the callback, the :func:`error`
- signal is emitted with ``traceback`` containing the exception info.
+.. versionchanged:: 1.4.0
+ ``func`` can also be a Python callable object, not just a string.
Attributes on Python objects can be accessed using :func:`getattr`:
@@ -156,6 +166,8 @@
Get the attribute ``attr`` of the Python object ``obj``.
+.. versionadded:: 1.4.0
+
For some of these methods, there also exist synchronous variants, but it is
highly recommended to use the asynchronous variants instead to avoid blocking
the QML UI thread:
@@ -168,13 +180,12 @@
Import a Python module. Returns ``true`` on success, ``false`` otherwise.
-.. function:: call_sync(string func, var args=[]) -> var
+.. function:: call_sync(var func, var args=[]) -> var
Call a Python function. Returns the return value of the Python function.
-.. function:: callMethod_sync(obj, string method, var args=[]) -> var
-
- Call a Python method. Returns the return value of the Python method.
+.. versionchanged:: 1.4.0
+ ``func`` can also be a Python callable object, not just a string.
The following functions allow access to the version of the running PyOtherSide
plugin and Python interpreter.
@@ -355,6 +366,10 @@
+--------------------+------------+-----------------------------+
| iterable | JS Array | since PyOtherSide 1.3.0 |
+--------------------+------------+-----------------------------+
+| object | (opaque) | since PyOtherSide 1.4.0 |
++--------------------+------------+-----------------------------+
+| pyotherside.QObject| QObject | since PyOtherSide 1.4.0 |
++--------------------+------------+-----------------------------+
Trying to pass in other types than the ones listed here is undefined
behavior and will usually result in an error.
@@ -457,6 +472,59 @@
alternative, ``addImportPath('qrc:/')`` will add the root directory of the Qt
Resources to Python's module search path.
+.. _qobjects in python:
+
+Accessing QObjects from Python
+==============================
+
+.. versionadded:: 1.4.0
+
+Since version 1.4, PyOtherSide allows passing QObjects from QML to Python, and
+accessing (setting / getting) properties and calling slots and dynamic methods.
+References to QObjects passed to Python can be passed back to QML transparently:
+
+.. code-block:: python
+
+ # Assume func will be called with a QObject as sole argument
+ def func(qobject):
+ # Getting properties
+ print(qobject.x)
+
+ # Setting properties
+ qobject.x = 123
+
+ # Calling slots and dynamic functions
+ print(qobject.someFunction(123, 'b'))
+
+ # Returning a QObject reference to the caller
+ return qobject
+
+It is possible to store a reference (bound method) to a method of a QObject.
+Such references cannot be passed to QML, and can only be used in Python for the
+lifetime of the QObject. If you need to pass such a bound method to QML, you
+can wrap it into a Python object (or even just a lambda) and pass that instead:
+
+.. code-block:: python
+
+ def func(qobject):
+ # Can store a reference to a bound method
+ bound_method = qobject.someFunction
+
+ # Calling the bound method
+ bound_method(123, 'b')
+
+ # If you need to return the bound method, you must wrap it
+ # in a lambda (or any other Python object), the bound method
+ # cannot be returned as-is for now
+ return lambda a, b: bound_method(a, b)
+
+It's not possible to instantiate new QObjects from within Python, and it's
+not possible to subclass QObject from within Python. Also, be aware that a
+reference to a QObject in Python will become invalid when the QObject is
+deleted (there's no way for PyOtherSide to prevent referenced QObjects from
+being deleted, but PyOtherSide tries hard to detect the deletion of objects
+and give meaningful error messages in case the reference is accessed).
+
Cookbook
========
@@ -679,7 +747,7 @@
.. code-block:: javascript
import QtQuick 2.0
- import io.thp.pyotherside 1.3
+ import io.thp.pyotherside 1.4
Rectangle {
color: 'black'
@@ -775,7 +843,7 @@
.. code-block:: javascript
import QtQuick 2.0
- import io.thp.pyotherside 1.3
+ import io.thp.pyotherside 1.4
Image {
id: image
@@ -854,6 +922,119 @@
After installing PyOtherSide in the locally-build Qt 5 (cross-compiled for
BB10), the QML plugins folder can be deployed with the .bar file.
+Building for Android
+--------------------
+
+Unlike Blackberry there is no Python or Qt present by default and both need to be shipped with the application.
+
+The current solution can be summarized like this:
+
+1. Statically cross-compile Python 3 for Android using the Android NDK
+2. Statically compile PyOtherSide against the Android Python build and bundle the Python standard library inside the PyOtherSide binary
+3. Use the Qt 5 SDK to make a QtQuick application - the SDK will handle bundling of your application file and of the PyOtherSide binary automatically
+
+A more detailed guide follows. It describes how to get from the source code of the relevant components to being able to run an Android application
+with a Qt Quick 2.0 GUI running on an Android device. The `gPodder` podcast aggregator serves as (full featured & fully functional!) example of such an application.
+
+Performed in this environment:
+* Fedora 20
+* Qt 5.3.1 Android SDK
+* latest Android SDK with API level 14 installed
+* OpenJDK 1.7
+* a few GB of harddrive space
+* an Android 4.0+ device connected to the computer that is accessible over *adb* (eq. the debugging mode is enabled)
+
+*This is just one example environment where these build instructions have been tested to work. Reasonably similar environments should work just as well.*
+
+The build is going to be done in a folder called ``build`` in the users home directory,
+lets say that the use is named ``user`` (replace accordingly for your environment).
+
+We start in the home directory:
+
+.. code-block:: sh
+
+ mkdir build
+ cd build
+
+Now clone the needed projects, load submodules and switch to correct branches.
+
+.. code-block:: sh
+
+ git clone --branch fixes https://github.com/thp/python3-android
+ git clone https://github.com/thp/pyotherside
+ git clone --recursive https://github.com/gpodder/gpodder-android
+
+Next we will build Python 3 for Android. This will first download the Android NDK, then Python 3 source code, followed by crosscompiling the Python 3 code for Android on ARM.
+*NOTE that this step alone can require multiple GB of harddisk space.*
+
+.. code-block:: sh
+
+ cd python3-android
+ make all
+
+As the next step we modify the ``python.pri.android`` file to point to our Python build. If should look like this as a result (remember to modify it for your environment):
+
+.. code-block:: qmake
+
+ QMAKE_LIBS += -L/home/user/build/python3-android/build/9d-14-arm-linux-androideabi-4.8/lib -lpython3.3m -ldl -lm -lc -lssl -lcrypto
+ QMAKE_CXXFLAGS += -I/home/user/build/python3-android/build/9d-14-arm-linux-androideabi-4.8/include/python3.3m/
+
+Then copy the file over the python.pri file in the PyOtherSide project directory:
+
+.. code-block:: sh
+
+ cd ..
+ cp python3-android/python.pri.android pyotherside/python.pri
+
+PyOtherSide can also help us ship & load the Python standard library if we can provide it a suitable zip bundle, which can be created like this:
+
+.. code-block:: sh
+
+ cd python3-android/build/9d-14-arm-linux-androideabi-4.8/lib/python3.3/
+ zip -r pythonlib.zip *
+ cd ../../../../..
+
+For PyOtherSide to include the packed Python standard library it needs to be placed in its src subfolder:
+
+.. code-block:: sh
+
+ mv python3-android/build/9d-14-arm-linux-androideabi-4.8/lib/python3.3/pythonlib.zip pyotherside/src/
+
+PyOtherSide will then use the qrc mechanism to compile the compressed standard library during inside it's own binary. This removes the need for us to handle its shipping & loading ourself.
+
+Next you need to build PyOtherSide with QtCreator from the Qt 5.3 Android SDK, so make sure that the Qt 5.3 Android kit is using the exact same NDK that has been used to build Python 3 for Android. To do that go to *settings*, find the *kits* section, select the Android kit and make sure that the NDK path points to:
+
+``/home/user/build/python3-android/sdk/android-ndk-r9d``
+
+Next open the pyotherside/pyotherside.pro project file on QtCreator, select the Android kit and once the project loads go to the *project view* and make sure that under *run* the API level is set to 14 (this corresponds to Android 4.0 and later). The Android Python 3 build has been built for API level 14 and our PyOtherSide build should do the same to be compatible.
+
+Also make sure that shadow build is disabled, just in case.
+
+Once done with the configuration got to the *build* menu and select the *built pyotherside* option - this should build PyOtherSide for Android and statically compile in our Python build and also include the Python standard library zip file with qrc.
+
+As the next step we need to move the PyOtherSide binary to the QML plugin folder for the Qt Android SDK, so that it can be fetched by the SDK when building gPodder.
+
+Let's say we have the SDK installed in the ``/opt`` directory (default for the Qt SDK installer on Linux), giving us this path to the plugin folder:
+
+``/opt/Qt5.3/5.3/android_armv7/qml``
+
+First create the folder structure for the pyotherside plugin:
+
+.. code-block:: sh
+
+ mkdir -p /opt/Qt5.3/5.3/android_armv7/qml/io/thp/pyotherside
+
+Then copy the pyotherside binary and *qmldir* file to the folder:
+
+.. code-block:: sh
+
+ cp pyotherside/src/libpyothersideplugin.so /opt/Qt5.3/5.3/android_armv7/qml/io/thp/pyotherside/
+ cp pyotherside/src/qmldir /opt/Qt5.3/5.3/android_armv7/qml/io/thp/pyotherside/
+
+Next open the gPodder project in QtCreator (gpodder-android/gpodder-android.pro) and again make sure the Android kit is selected, that the API level 14 is used and that *shadow build* is disabled. Then just press the *Run* button and the SDK should build an Android APK that includes the libpyotherside binary (it fetched automatically from the plugins directory because is referenced in the gPodder QML source code) and deploy it to the device where gPodder should be started.
+
+.. _gPodder: http://gpodder.org/
+
Building for Windows
--------------------
@@ -918,6 +1099,17 @@
ChangeLog
=========
+Version 1.4.0 (UNRELEASED)
+--------------------------
+
+* Support for passing Python objects to QML and keeping references there
+* Add :func:`getattr` to get an attribute from a Python object
+* :func:`call` and :func:`call_sync` now also accept a Python callable as
+ first argument
+* Support for `Accessing QObjects from Python`_ (properties and slots)
+* Print error messages to the console if :func:`error` doesn't have any
+ handlers connected
+
Version 1.3.0 (2014-07-24)
--------------------------
diff -urN pyotherside-1.4.0~git20150111/examples/helloworld.qml pyotherside/examples/helloworld.qml
--- pyotherside-1.4.0~git20150111/examples/helloworld.qml 2015-02-18 12:07:06.000000000 +0200
+++ pyotherside/examples/helloworld.qml 2015-02-18 12:18:28.787571658 +0200
@@ -1,5 +1,5 @@
import QtQuick 2.0
-import io.thp.pyotherside 1.0
+import io.thp.pyotherside 1.4
Rectangle {
width: 200
diff -urN pyotherside-1.4.0~git20150111/examples/qobject_reference.py pyotherside/examples/qobject_reference.py
--- pyotherside-1.4.0~git20150111/examples/qobject_reference.py 1970-01-01 02:00:00.000000000 +0200
+++ pyotherside/examples/qobject_reference.py 2015-02-18 12:18:28.791571658 +0200
@@ -0,0 +1,65 @@
+import threading
+import time
+import pyotherside
+
+# If you try to instantiate a QObject, it's unbound
+unbound = pyotherside.QObject()
+print(unbound)
+try:
+ unbound.a = 1
+except Exception as e:
+ print('Got exception:', e)
+
+def do_something(bar):
+ while True:
+ print('got: ', bar.dynamicFunction(1, 2, 3))
+ time.sleep(1)
+
+def foo(bar, py):
+ # Printing the objects will give some info on the
+ # QObject class and memory address
+ print('got:', bar, py)
+
+ # Ok, this is pretty wicked - we can now call into
+ # the PyOtherSide QML element from within Python
+ # (not that it's a good idea to do this, mind you..)
+ print(py.evaluate)
+ print(py.evaluate('3*3'))
+
+ try:
+ bar.i_am_pretty_sure_this_attr_does_not_exist = 147
+ except Exception as e:
+ print('Got exception (as expected):', e)
+
+ try:
+ bar.x = 'i dont think i can set this to a string'
+ except Exception as e:
+ print('Got exception (as expected):', e)
+
+ # This doesn't work yet, because we can't convert a bound
+ # member function to a Qt/QML type yet (fallback to None)
+ try:
+ bar.dynamicFunction(bar.dynamicFunction, 2, 3)
+ except Exception as e:
+ print('Got exception (as expected):', e)
+
+ # Property access works just like expected
+ print(bar.x, bar.color, bar.scale)
+ bar.x *= 3
+
+ # Printing a member function gives a bound method
+ print(bar.dynamicFunction)
+
+ # Calling a member function is just as easy
+ result = bar.dynamicFunction(1, 2, 3)
+ print('result:', result)
+
+ try:
+ bar.dynamicFunction(1, 2, 3, unexpected=123)
+ except Exception as e:
+ print('Got exception (as expected):', e)
+
+ threading.Thread(target=do_something, args=[bar]).start()
+
+ # Returning QObject references from Python also works
+ return bar
diff -urN pyotherside-1.4.0~git20150111/examples/qobject_reference.qml pyotherside/examples/qobject_reference.qml
--- pyotherside-1.4.0~git20150111/examples/qobject_reference.qml 1970-01-01 02:00:00.000000000 +0200
+++ pyotherside/examples/qobject_reference.qml 2015-02-18 12:18:28.791571658 +0200
@@ -0,0 +1,37 @@
+import QtQuick 2.0
+import io.thp.pyotherside 1.4
+
+Rectangle {
+ id: root
+ width: 400
+ height: 400
+
+ Rectangle {
+ id: foo
+ x: 123
+ y: 123
+ width: 20
+ height: 20
+ color: 'blue'
+
+ function dynamicFunction(a, b, c) {
+ console.log('In QML, dynamicFunction got: ' + a + ', ' + b + ', ' + c);
+ rotation += 4;
+ return 'hello';
+ }
+ }
+
+ Python {
+ id: py
+
+ Component.onCompleted: {
+ addImportPath(Qt.resolvedUrl('.'));
+ importModule('qobject_reference', function () {
+ call('qobject_reference.foo', [foo, py], function (result) {
+ console.log('In QML, got result: ' + result);
+ result.color = 'green';
+ });
+ });
+ }
+ }
+}
diff -urN pyotherside-1.4.0~git20150111/pyotherside.pri pyotherside/pyotherside.pri
--- pyotherside-1.4.0~git20150111/pyotherside.pri 2015-02-18 12:07:06.000000000 +0200
+++ pyotherside/pyotherside.pri 2015-02-18 12:18:28.791571658 +0200
@@ -1,2 +1,2 @@
PROJECTNAME = pyotherside
-VERSION = 1.3.0
+VERSION = 1.4.0
diff -urN pyotherside-1.4.0~git20150111/README pyotherside/README
--- pyotherside-1.4.0~git20150111/README 2015-02-18 12:07:06.000000000 +0200
+++ pyotherside/README 2015-02-18 12:18:28.783571658 +0200
@@ -29,6 +29,12 @@
./tests/tests
+If you want to link PyOtherSide statically against Python 3, you can include
+the Python Standard Library in PyOtherSide as Qt Resource and have it extracted
+automatically on load, for this, zip up the Standard Library and place the .zip
+file as "pythonlib.zip" into src/ before running qmake.
+
+
More information:
Project page: https://thp.io/2011/pyotherside/
diff -urN pyotherside-1.4.0~git20150111/src/converter.h pyotherside/src/converter.h
--- pyotherside-1.4.0~git20150111/src/converter.h 2015-02-18 12:07:06.000000000 +0200
+++ pyotherside/src/converter.h 2015-02-18 12:18:28.791571658 +0200
@@ -20,6 +20,7 @@
#define PYOTHERSIDE_CONVERTER_H
#include "pyobject_ref.h"
+#include "qobject_ref.h"
struct ConverterDate {
ConverterDate(int y, int m, int d)
@@ -105,9 +106,10 @@
TIME,
DATETIME,
PYOBJECT,
+ QOBJECT,
};
- virtual enum Type type(V&) = 0;
+ virtual enum Type type(const V&) = 0;
virtual long long integer(V&) = 0;
virtual double floating(V&) = 0;
virtual bool boolean(V&) = 0;
@@ -118,6 +120,7 @@
virtual ConverterTime time(V&) = 0;
virtual ConverterDateTime dateTime(V&) = 0;
virtual PyObjectRef pyObject(V&) = 0;
+ virtual QObjectRef qObject(V&) = 0;
virtual V fromInteger(long long v) = 0;
virtual V fromFloating(double v) = 0;
@@ -127,6 +130,7 @@
virtual V fromTime(ConverterTime time) = 0;
virtual V fromDateTime(ConverterDateTime dateTime) = 0;
virtual V fromPyObject(const PyObjectRef &pyobj) = 0;
+ virtual V fromQObject(const QObjectRef &qobj) = 0;
virtual ListBuilder<V> *newList() = 0;
virtual DictBuilder<V> *newDict() = 0;
virtual V none() = 0;
@@ -193,6 +197,8 @@
return tconv.fromDateTime(fconv.dateTime(from));
case FC::PYOBJECT:
return tconv.fromPyObject(fconv.pyObject(from));
+ case FC::QOBJECT:
+ return tconv.fromQObject(fconv.qObject(from));
}
return tconv.none();
diff -urN pyotherside-1.4.0~git20150111/src/ensure_gil_state.h pyotherside/src/ensure_gil_state.h
--- pyotherside-1.4.0~git20150111/src/ensure_gil_state.h 1970-01-01 02:00:00.000000000 +0200
+++ pyotherside/src/ensure_gil_state.h 2015-02-18 12:18:28.791571658 +0200
@@ -0,0 +1,32 @@
+
+/**
+ * PyOtherSide: Asynchronous Python 3 Bindings for Qt 5
+ * Copyright (c) 2014, Felix Krull <f_krull@gmx.de>
+ * Copyright (c) 2014, Thomas Perl <m@thp.io>
+ *
+ * Permission to use, copy, modify, and/or distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
+ * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
+ * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
+ * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
+ * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
+ * PERFORMANCE OF THIS SOFTWARE.
+ **/
+
+#include "Python.h"
+
+class EnsureGILState {
+ public:
+ EnsureGILState() : gil_state(PyGILState_Ensure()) { }
+ ~EnsureGILState() { PyGILState_Release(gil_state); }
+
+ private:
+ PyGILState_STATE gil_state;
+};
+
+#define ENSURE_GIL_STATE EnsureGILState _ensure; Q_UNUSED(_ensure)
+
diff -urN pyotherside-1.4.0~git20150111/src/global_libpython_loader.cpp pyotherside/src/global_libpython_loader.cpp
--- pyotherside-1.4.0~git20150111/src/global_libpython_loader.cpp 2015-02-18 12:07:06.000000000 +0200
+++ pyotherside/src/global_libpython_loader.cpp 2015-02-18 12:18:28.791571658 +0200
@@ -20,7 +20,7 @@
namespace GlobalLibPythonLoader {
-#ifdef __linux__
+#if defined(__linux__) && !defined(ANDROID)
#define _GNU_SOURCE
#include <link.h>
diff -urN pyotherside-1.4.0~git20150111/src/pyobject_converter.h pyotherside/src/pyobject_converter.h
--- pyotherside-1.4.0~git20150111/src/pyobject_converter.h 2015-02-18 12:07:06.000000000 +0200
+++ pyotherside/src/pyobject_converter.h 2015-02-18 12:18:28.791571658 +0200
@@ -20,9 +20,11 @@
#define PYOTHERSIDE_PYOBJECT_CONVERTER_H
#include "converter.h"
+#include "pyqobject.h"
#include "Python.h"
#include "datetime.h"
+#include <QDebug>
class PyObjectListBuilder : public ListBuilder<PyObject *> {
@@ -137,8 +139,14 @@
}
}
- virtual enum Type type(PyObject *&o) {
- if (PyBool_Check(o)) {
+ virtual enum Type type(PyObject * const & o) {
+ if (PyObject_TypeCheck(o, &pyotherside_QObjectType)) {
+ return QOBJECT;
+ } else if (PyObject_TypeCheck(o, &pyotherside_QObjectMethodType)) {
+ qWarning("Cannot convert QObjectMethod yet - falling back to None");
+ // TODO: Implement passing QObjectMethod references around
+ return NONE;
+ } else if (PyBool_Check(o)) {
return BOOLEAN;
} else if (PyLong_Check(o)) {
return INTEGER;
@@ -203,6 +211,14 @@
PyDateTime_DATE_GET_MICROSECOND(o) / 1000);
}
virtual PyObjectRef pyObject(PyObject *&o) { return PyObjectRef(o); }
+ virtual QObjectRef qObject(PyObject *&o) {
+ if (PyObject_TypeCheck(o, &pyotherside_QObjectType)) {
+ pyotherside_QObject *result = reinterpret_cast<pyotherside_QObject *>(o);
+ return QObjectRef(*(result->m_qobject_ref));
+ }
+
+ return QObjectRef();
+ }
virtual PyObject * fromInteger(long long v) { return PyLong_FromLong((long)v); }
virtual PyObject * fromFloating(double v) { return PyFloat_FromDouble(v); }
@@ -214,6 +230,11 @@
return PyDateTime_FromDateAndTime(v.y, v.m, v.d, v.time.h, v.time.m, v.time.s, v.time.ms * 1000);
}
virtual PyObject * fromPyObject(const PyObjectRef &pyobj) { return pyobj.newRef(); }
+ virtual PyObject * fromQObject(const QObjectRef &qobj) {
+ pyotherside_QObject *result = PyObject_New(pyotherside_QObject, &pyotherside_QObjectType);
+ result->m_qobject_ref = new QObjectRef(qobj);
+ return reinterpret_cast<PyObject *>(result);
+ }
virtual ListBuilder<PyObject *> *newList() { return new PyObjectListBuilder(); }
virtual DictBuilder<PyObject *> *newDict() { return new PyObjectDictBuilder(); }
virtual PyObject * none() { Py_RETURN_NONE; }
diff -urN pyotherside-1.4.0~git20150111/src/pyobject_ref.cpp pyotherside/src/pyobject_ref.cpp
--- pyotherside-1.4.0~git20150111/src/pyobject_ref.cpp 2015-02-18 12:07:06.000000000 +0200
+++ pyotherside/src/pyobject_ref.cpp 2015-02-18 12:18:28.791571658 +0200
@@ -18,22 +18,12 @@
**/
#include "pyobject_ref.h"
+#include "ensure_gil_state.h"
-class EnsureGILState {
- public:
- EnsureGILState() : gil_state(PyGILState_Ensure()) { }
- ~EnsureGILState() { PyGILState_Release(gil_state); }
-
- private:
- PyGILState_STATE gil_state;
-};
-
-#define ENSURE_GIL_STATE EnsureGILState _ensure; Q_UNUSED(_ensure)
-
-PyObjectRef::PyObjectRef(PyObject *obj)
+PyObjectRef::PyObjectRef(PyObject *obj, bool consume)
: pyobject(obj)
{
- if (pyobject) {
+ if (pyobject && !consume) {
ENSURE_GIL_STATE;
Py_INCREF(pyobject);
}
@@ -56,6 +46,27 @@
}
}
+PyObjectRef &
+PyObjectRef::operator=(const PyObjectRef &other)
+{
+ if (this != &other) {
+ if (pyobject || other.pyobject) {
+ ENSURE_GIL_STATE;
+
+ if (pyobject) {
+ Py_CLEAR(pyobject);
+ }
+
+ if (other.pyobject) {
+ pyobject = other.pyobject;
+ Py_INCREF(pyobject);
+ }
+ }
+ }
+
+ return *this;
+}
+
PyObject *
PyObjectRef::newRef() const
{
@@ -66,3 +77,10 @@
return pyobject;
}
+
+PyObject *
+PyObjectRef::borrow() const
+{
+ // Borrowed reference
+ return pyobject;
+}
diff -urN pyotherside-1.4.0~git20150111/src/pyobject_ref.h pyotherside/src/pyobject_ref.h
--- pyotherside-1.4.0~git20150111/src/pyobject_ref.h 2015-02-18 12:07:06.000000000 +0200
+++ pyotherside/src/pyobject_ref.h 2015-02-18 12:18:28.791571658 +0200
@@ -26,12 +26,16 @@
class PyObjectRef {
public:
- explicit PyObjectRef(PyObject *obj=0);
+ explicit PyObjectRef(PyObject *obj=0, bool consume=false);
PyObjectRef(const PyObjectRef &other);
virtual ~PyObjectRef();
+ PyObjectRef &operator=(const PyObjectRef &other);
PyObject *newRef() const;
+ PyObject *borrow() const;
+ operator bool() const { return (pyobject != 0); }
+
private:
PyObject *pyobject;
};
diff -urN pyotherside-1.4.0~git20150111/src/pyotherside_plugin.cpp pyotherside/src/pyotherside_plugin.cpp
--- pyotherside-1.4.0~git20150111/src/pyotherside_plugin.cpp 2015-02-18 12:07:06.000000000 +0200
+++ pyotherside/src/pyotherside_plugin.cpp 2015-02-18 12:18:28.791571658 +0200
@@ -20,6 +20,7 @@
#include "qpython.h"
#include "qpython_imageprovider.h"
#include "global_libpython_loader.h"
+#include "pythonlib_loader.h"
#include "pyotherside_plugin.h"
@@ -50,6 +51,9 @@
// load libpython again RTLD_GLOBAL again. We do this here.
GlobalLibPythonLoader::loadPythonGlobally();
+ // Extract and load embedded Python Standard Library, if necessary
+ PythonLibLoader::extractPythonLibrary();
+
engine->addImageProvider(PYOTHERSIDE_IMAGEPROVIDER_ID, new QPythonImageProvider);
}
@@ -61,4 +65,5 @@
// There is no PyOtherSide 1.1 import, as it's the same as 1.0
qmlRegisterType<QPython12>(uri, 1, 2, PYOTHERSIDE_QPYTHON_NAME);
qmlRegisterType<QPython13>(uri, 1, 3, PYOTHERSIDE_QPYTHON_NAME);
+ qmlRegisterType<QPython14>(uri, 1, 4, PYOTHERSIDE_QPYTHON_NAME);
}
diff -urN pyotherside-1.4.0~git20150111/src/pyqobject.h pyotherside/src/pyqobject.h
--- pyotherside-1.4.0~git20150111/src/pyqobject.h 1970-01-01 02:00:00.000000000 +0200
+++ pyotherside/src/pyqobject.h 2015-02-18 12:18:28.791571658 +0200
@@ -0,0 +1,39 @@
+
+/**
+ * PyOtherSide: Asynchronous Python 3 Bindings for Qt 5
+ * Copyright (c) 2014, Thomas Perl <m@thp.io>
+ *
+ * Permission to use, copy, modify, and/or distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
+ * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
+ * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
+ * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
+ * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
+ * PERFORMANCE OF THIS SOFTWARE.
+ **/
+
+#ifndef PYOTHERSIDE_PYQOBJECT_H
+#define PYOTHERSIDE_PYQOBJECT_H
+
+#include "Python.h"
+
+#include "qobject_ref.h"
+
+typedef struct {
+ PyObject_HEAD
+ QObjectRef *m_qobject_ref;
+} pyotherside_QObject;
+
+typedef struct {
+ PyObject_HEAD
+ QObjectMethodRef *m_method_ref;
+} pyotherside_QObjectMethod;
+
+extern PyTypeObject pyotherside_QObjectType;
+extern PyTypeObject pyotherside_QObjectMethodType;
+
+#endif /* PYOTHERSIDE_PYQOBJECT_H */
diff -urN pyotherside-1.4.0~git20150111/src/pythonlib_loader.cpp pyotherside/src/pythonlib_loader.cpp
--- pyotherside-1.4.0~git20150111/src/pythonlib_loader.cpp 1970-01-01 02:00:00.000000000 +0200
+++ pyotherside/src/pythonlib_loader.cpp 2015-02-18 12:18:28.791571658 +0200
@@ -0,0 +1,54 @@
+
+/**
+ * PyOtherSide: Asynchronous Python 3 Bindings for Qt 5
+ * Copyright (c) 2014, Thomas Perl <m@thp.io>
+ *
+ * Permission to use, copy, modify, and/or distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
+ * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
+ * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
+ * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
+ * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
+ * PERFORMANCE OF THIS SOFTWARE.
+ **/
+
+#include "pythonlib_loader.h"
+
+#include <QStandardPaths>
+#include <QDir>
+
+namespace PythonLibLoader {
+
+#if defined(PYTHONLIB_LOADER_HAVE_PYTHONLIB_ZIP)
+
+bool extractPythonLibrary()
+{
+ QString source(":/io/thp/pyotherside/pythonlib.zip");
+ QString destdir(QStandardPaths::writableLocation(QStandardPaths::TempLocation));
+ QString destination(QDir(destdir).filePath("pythonlib.zip"));
+
+ // Our embedded Python library should have priority over other path elements
+ qputenv("PYTHONPATH", (destination + ":" + QString::fromUtf8(qgetenv("PYTHONPATH"))).toUtf8());
+
+ if (QFile::exists(destination)) {
+ return true;
+ }
+
+ return QFile::copy(source, destination);
+}
+
+#else /* PYTHONLIB_LOADER_HAVE_PYTHONLIB_ZIP */
+
+bool extractPythonLibrary()
+{
+ // No need to extract the Python library
+ return true;
+}
+
+#endif /* PYTHONLIB_LOADER_HAVE_PYTHONLIB_ZIP */
+
+}; /* namespace PythonLibLoader */
diff -urN pyotherside-1.4.0~git20150111/src/pythonlib_loader.h pyotherside/src/pythonlib_loader.h
--- pyotherside-1.4.0~git20150111/src/pythonlib_loader.h 1970-01-01 02:00:00.000000000 +0200
+++ pyotherside/src/pythonlib_loader.h 2015-02-18 12:18:28.791571658 +0200
@@ -0,0 +1,26 @@
+
+/**
+ * PyOtherSide: Asynchronous Python 3 Bindings for Qt 5
+ * Copyright (c) 2014, Thomas Perl <m@thp.io>
+ *
+ * Permission to use, copy, modify, and/or distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
+ * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
+ * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
+ * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
+ * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
+ * PERFORMANCE OF THIS SOFTWARE.
+ **/
+
+#ifndef PYOTHERSIDE_PYTHONLIB_LOADER_H
+#define PYOTHERSIDE_PYTHONLIB_LOADER_H
+
+namespace PythonLibLoader {
+ bool extractPythonLibrary();
+};
+
+#endif /* PYOTHERSIDE_PYTHONLIB_LOADER_H */
diff -urN pyotherside-1.4.0~git20150111/src/pythonlib_loader.qrc pyotherside/src/pythonlib_loader.qrc
--- pyotherside-1.4.0~git20150111/src/pythonlib_loader.qrc 1970-01-01 02:00:00.000000000 +0200
+++ pyotherside/src/pythonlib_loader.qrc 2015-02-18 12:18:28.791571658 +0200
@@ -0,0 +1,6 @@
+<!DOCTYPE RCC>
+<RCC version="1.0">
+ <qresource prefix="/io/thp/pyotherside/">
+ <file>pythonlib.zip</file>
+ </qresource>
+</RCC>
diff -urN pyotherside-1.4.0~git20150111/src/qobject_ref.cpp pyotherside/src/qobject_ref.cpp
--- pyotherside-1.4.0~git20150111/src/qobject_ref.cpp 1970-01-01 02:00:00.000000000 +0200
+++ pyotherside/src/qobject_ref.cpp 2015-02-18 12:18:28.795571658 +0200
@@ -0,0 +1,75 @@
+
+/**
+ * PyOtherSide: Asynchronous Python 3 Bindings for Qt 5
+ * Copyright (c) 2014, Thomas Perl <m@thp.io>
+ *
+ * Permission to use, copy, modify, and/or distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
+ * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
+ * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
+ * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
+ * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
+ * PERFORMANCE OF THIS SOFTWARE.
+ **/
+
+#include "qobject_ref.h"
+
+QObjectRef::QObjectRef(QObject *obj)
+ : qobject(obj)
+{
+ if (qobject) {
+ QObject::connect(qobject, SIGNAL(destroyed(QObject *)),
+ this, SLOT(handleDestroyed(QObject *)));
+ }
+}
+
+QObjectRef::QObjectRef(const QObjectRef &other)
+ : qobject(other.qobject)
+{
+ if (qobject) {
+ QObject::connect(qobject, SIGNAL(destroyed(QObject *)),
+ this, SLOT(handleDestroyed(QObject *)));
+ }
+}
+
+QObjectRef::~QObjectRef()
+{
+ if (qobject) {
+ QObject::disconnect(qobject, SIGNAL(destroyed(QObject *)),
+ this, SLOT(handleDestroyed(QObject *)));
+ }
+}
+
+QObjectRef &
+QObjectRef::operator=(const QObjectRef &other)
+{
+ if (this != &other) {
+ if (qobject != other.qobject) {
+ if (qobject) {
+ QObject::disconnect(qobject, SIGNAL(destroyed(QObject *)),
+ this, SLOT(handleDestroyed(QObject *)));
+ }
+
+ if (other.qobject) {
+ qobject = other.qobject;
+ QObject::connect(qobject, SIGNAL(destroyed(QObject *)),
+ this, SLOT(handleDestroyed(QObject *)));
+ }
+ }
+ }
+
+ return *this;
+}
+
+void
+QObjectRef::handleDestroyed(QObject *obj)
+{
+ if (obj == qobject) {
+ // Have to remove internal reference, as qobject is destroyed
+ qobject = NULL;
+ }
+}
diff -urN pyotherside-1.4.0~git20150111/src/qobject_ref.h pyotherside/src/qobject_ref.h
--- pyotherside-1.4.0~git20150111/src/qobject_ref.h 1970-01-01 02:00:00.000000000 +0200
+++ pyotherside/src/qobject_ref.h 2015-02-18 12:18:28.795571658 +0200
@@ -0,0 +1,60 @@
+
+/**
+ * PyOtherSide: Asynchronous Python 3 Bindings for Qt 5
+ * Copyright (c) 2014, Thomas Perl <m@thp.io>
+ *
+ * Permission to use, copy, modify, and/or distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
+ * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
+ * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
+ * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
+ * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
+ * PERFORMANCE OF THIS SOFTWARE.
+ **/
+
+#ifndef PYOTHERSIDE_QOBJECT_REF_H
+#define PYOTHERSIDE_QOBJECT_REF_H
+
+#include <QObject>
+
+class QObjectRef : public QObject {
+ Q_OBJECT
+
+public:
+ explicit QObjectRef(QObject *obj=0);
+ virtual ~QObjectRef();
+
+ QObjectRef(const QObjectRef &other);
+ QObjectRef &operator=(const QObjectRef &other);
+
+ QObject *value() const { return qobject; }
+ operator bool() const { return (qobject != 0); }
+
+private slots:
+ void handleDestroyed(QObject *obj);
+
+private:
+ QObject *qobject;
+};
+
+class QObjectMethodRef {
+public:
+ QObjectMethodRef(const QObjectRef &object, const QString &method)
+ : m_object(object)
+ , m_method(method)
+ {
+ }
+
+ const QObjectRef &object() { return m_object; }
+ const QString &method() { return m_method; }
+
+private:
+ QObjectRef m_object;
+ QString m_method;
+};
+
+#endif // PYOTHERSIDE_QOBJECT_REF_H
diff -urN pyotherside-1.4.0~git20150111/src/qpython.cpp pyotherside/src/qpython.cpp
--- pyotherside-1.4.0~git20150111/src/qpython.cpp 2015-02-18 12:07:06.000000000 +0200
+++ pyotherside/src/qpython.cpp 2015-02-18 12:18:28.795571658 +0200
@@ -22,9 +22,12 @@
#include "qpython_priv.h"
#include "qpython_worker.h"
+#include "ensure_gil_state.h"
+
#include <QDebug>
#include <QJSEngine>
+#include <QMetaMethod>
#define SINCE_API_VERSION(smaj, smin) \
@@ -41,6 +44,7 @@
, handlers()
, api_version_major(api_version_major)
, api_version_minor(api_version_minor)
+ , error_connections(0)
{
if (priv == NULL) {
priv = new QPythonPriv;
@@ -51,10 +55,8 @@
QObject::connect(priv, SIGNAL(receive(QVariant)),
this, SLOT(receive(QVariant)));
- QObject::connect(this, SIGNAL(process(QString,QVariant,QJSValue *)),
- worker, SLOT(process(QString,QVariant,QJSValue *)));
- QObject::connect(this, SIGNAL(processMethod(QVariant,QString,QVariant,QJSValue *)),
- worker, SLOT(processMethod(QVariant,QString,QVariant,QJSValue *)));
+ QObject::connect(this, SIGNAL(process(QVariant,QVariant,QJSValue *)),
+ worker, SLOT(process(QVariant,QVariant,QJSValue *)));
QObject::connect(worker, SIGNAL(finished(QVariant,QJSValue *)),
this, SLOT(finished(QVariant,QJSValue *)));
@@ -76,9 +78,25 @@
}
void
+QPython::connectNotify(const QMetaMethod &signal)
+{
+ if (signal == QMetaMethod::fromSignal(&QPython::error)) {
+ error_connections++;
+ }
+}
+
+void
+QPython::disconnectNotify(const QMetaMethod &signal)
+{
+ if (signal == QMetaMethod::fromSignal(&QPython::error)) {
+ error_connections--;
+ }
+}
+
+void
QPython::addImportPath(QString path)
{
- priv->enter();
+ ENSURE_GIL_STATE;
// Strip leading "file://" (for use with Qt.resolvedUrl())
if (path.startsWith("file://")) {
@@ -96,7 +114,7 @@
QString filename = "/io/thp/pyotherside/qrc_importer.py";
QString errorMessage = priv->importFromQRC(module, filename);
if (!errorMessage.isNull()) {
- emit error(errorMessage);
+ emitError(errorMessage);
}
}
@@ -104,10 +122,8 @@
PyObject *sys_path = PySys_GetObject((char*)"path");
- PyObject *cwd = PyUnicode_FromString(utf8bytes.constData());
- PyList_Insert(sys_path, 0, cwd);
- Py_DECREF(cwd);
- priv->leave();
+ PyObjectRef cwd(PyUnicode_FromString(utf8bytes.constData()), true);
+ PyList_Insert(sys_path, 0, cwd.borrow());
}
void
@@ -130,25 +146,24 @@
QByteArray utf8bytes = name.toUtf8();
const char *moduleName = utf8bytes.constData();
- priv->enter();
+ ENSURE_GIL_STATE;
bool use_api_10 = (api_version_major == 1 && api_version_minor == 0);
- PyObject *module = NULL;
+ PyObjectRef module;
if (use_api_10) {
// PyOtherSide API 1.0 behavior (star import)
- module = PyImport_ImportModule(moduleName);
+ module = PyObjectRef(PyImport_ImportModule(moduleName), true);
} else {
// PyOtherSide API 1.2 behavior: "import x.y.z"
- PyObject *fromList = PyList_New(0);
- module = PyImport_ImportModuleEx(const_cast<char *>(moduleName), NULL, NULL, fromList);
- Py_XDECREF(fromList);
+ PyObjectRef fromList(PyList_New(0), true);
+ module = PyObjectRef(PyImport_ImportModuleEx(const_cast<char *>(moduleName),
+ NULL, NULL, fromList.borrow()), true);
}
- if (module == NULL) {
- emit error(QString("Cannot import module: %1 (%2)").arg(name).arg(priv->formatExc()));
- priv->leave();
+ if (!module) {
+ emitError(QString("Cannot import module: %1 (%2)").arg(name).arg(priv->formatExc()));
return false;
}
@@ -162,9 +177,7 @@
}
}
- PyDict_SetItemString(priv->globals, moduleName, module);
- Py_CLEAR(module);
- priv->leave();
+ PyDict_SetItemString(priv->globals.borrow(), moduleName, module.borrow());
return true;
}
@@ -187,7 +200,7 @@
// call is asynchronous (it returns before we call into JS), so do
// the next best thing and report the error to our error handler in
// QML instead.
- emit error("pyotherside.send() failed handler: " +
+ emitError("pyotherside.send() failed handler: " +
result.property("fileName").toString() + ":" +
result.property("lineNumber").toString() + ": " +
result.toString());
@@ -211,22 +224,19 @@
QVariant
QPython::evaluate(QString expr)
{
- priv->enter();
- PyObject *o = priv->eval(expr);
- if (o == NULL) {
- emit error(QString("Cannot evaluate '%1' (%2)").arg(expr).arg(priv->formatExc()));
- priv->leave();
+ ENSURE_GIL_STATE;
+
+ PyObjectRef o(priv->eval(expr), true);
+ if (!o) {
+ emitError(QString("Cannot evaluate '%1' (%2)").arg(expr).arg(priv->formatExc()));
return QVariant();
}
- QVariant v = convertPyObjectToQVariant(o);
- Py_DECREF(o);
- priv->leave();
- return v;
+ return convertPyObjectToQVariant(o.borrow());
}
void
-QPython::call(QString func, QVariant args, QJSValue callback)
+QPython::call(QVariant func, QVariant args, QJSValue callback)
{
QJSValue *cb = 0;
if (!callback.isNull() && !callback.isUndefined() && callback.isCallable()) {
@@ -236,100 +246,70 @@
}
QVariant
-QPython::call_sync(QString func, QVariant args)
-{
- priv->enter();
- PyObject *callable = priv->eval(func);
-
- if (callable == NULL) {
- emit error(QString("Function not found: '%1' (%2)").arg(func).arg(priv->formatExc()));
- priv->leave();
- return QVariant();
- }
-
- QVariant v;
- QString errorMessage = priv->call(callable, func, args, &v);
- if (!errorMessage.isNull()) {
- emit error(errorMessage);
- }
- Py_DECREF(callable);
- priv->leave();
- return v;
-}
-
-void
-QPython::callMethod(QVariant obj, QString method, QVariant args, QJSValue callback)
+QPython::call_sync(QVariant func, QVariant args)
{
- QJSValue *cb = 0;
- if (!callback.isNull() && !callback.isUndefined() && callback.isCallable()) {
- cb = new QJSValue(callback);
- }
- emit processMethod(obj, method, args, cb);
-}
+ ENSURE_GIL_STATE;
-QVariant
-QPython::callMethod_sync(QVariant obj, QString method, QVariant args)
-{
- priv->enter();
- PyObject *pyobj = convertQVariantToPyObject(obj);
+ PyObjectRef callable;
+ QString name;
- if (pyobj == NULL) {
- emit error(QString("Failed to convert %1 to python object: '%1' (%2)").arg(obj.toString()).arg(priv->formatExc()));
- priv->leave();
- return QVariant();
+ if (SINCE_API_VERSION(1, 4)) {
+ if (static_cast<QMetaType::Type>(func.type()) == QMetaType::QString) {
+ // Using version >= 1.4, but func is a string
+ callable = PyObjectRef(priv->eval(func.toString()), true);
+ name = func.toString();
+ } else {
+ // Try to interpret "func" as a Python object
+ callable = PyObjectRef(convertQVariantToPyObject(func), true);
+ PyObjectRef repr = PyObjectRef(PyObject_Repr(callable.borrow()), true);
+ name = convertPyObjectToQVariant(repr.borrow()).toString();
+ }
+ } else {
+ // Versions before 1.4 only support func as a string
+ callable = PyObjectRef(priv->eval(func.toString()), true);
+ name = func.toString();
}
- QByteArray byteArray = method.toUtf8();
- const char *methodStr = byteArray.data();
-
- PyObject *callable = PyObject_GetAttrString(pyobj, methodStr);
-
- if (callable == NULL) {
- emit error(QString("Method not found: '%1' (%2)").arg(method).arg(priv->formatExc()));
- Py_DECREF(pyobj);
- priv->leave();
+ if (!callable) {
+ emitError(QString("Function not found: '%1' (%2)").arg(name).arg(priv->formatExc()));
return QVariant();
}
QVariant v;
- QString errorMessage = priv->call(callable, method, args, &v);
+ QString errorMessage = priv->call(callable.borrow(), name, args, &v);
if (!errorMessage.isNull()) {
- emit error(errorMessage);
+ emitError(errorMessage);
}
- Py_DECREF(callable);
- Py_DECREF(pyobj);
- priv->leave();
return v;
}
QVariant
QPython::getattr(QVariant obj, QString attr) {
- priv->enter();
- PyObject *pyobj = convertQVariantToPyObject(obj);
+ if (!SINCE_API_VERSION(1, 4)) {
+ emitError(QString("Import PyOtherSide 1.4 or newer to use getattr()"));
+ return QVariant();
+ }
- if (pyobj == NULL) {
- emit error(QString("Failed to convert %1 to python object: '%1' (%2)").arg(obj.toString()).arg(priv->formatExc()));
- priv->leave();
+ ENSURE_GIL_STATE;
+
+ PyObjectRef pyobj(convertQVariantToPyObject(obj), true);
+
+ if (!pyobj) {
+ emitError(QString("Failed to convert %1 to python object: '%1' (%2)").arg(obj.toString()).arg(priv->formatExc()));
return QVariant();
}
QByteArray byteArray = attr.toUtf8();
const char *attrStr = byteArray.data();
- PyObject *o = PyObject_GetAttrString(pyobj, attrStr);
+ PyObjectRef o(PyObject_GetAttrString(pyobj.borrow(), attrStr), true);
- if (o == NULL) {
- emit error(QString("Attribute not found: '%1' (%2)").arg(attr).arg(priv->formatExc()));
- Py_DECREF(pyobj);
- priv->leave();
+ if (!o) {
+ emitError(QString("Attribute not found: '%1' (%2)").arg(attr).arg(priv->formatExc()));
return QVariant();
}
- QVariant v = convertPyObjectToQVariant(o);
- Py_DECREF(o);
- Py_DECREF(pyobj);
- priv->leave();
- return v;
+ return convertPyObjectToQVariant(o.borrow());
}
void
@@ -341,7 +321,7 @@
QJSValue callbackResult = callback->call(args);
if (SINCE_API_VERSION(1, 2)) {
if (callbackResult.isError()) {
- emit error(callbackResult.property("fileName").toString() + ":" +
+ emitError(callbackResult.property("fileName").toString() + ":" +
callbackResult.property("lineNumber").toString() + ": " +
callbackResult.toString());
}
@@ -358,7 +338,7 @@
QJSValue callbackResult = callback->call(args);
if (SINCE_API_VERSION(1, 2)) {
if (callbackResult.isError()) {
- emit error(callbackResult.property("fileName").toString() + ":" +
+ emitError(callbackResult.property("fileName").toString() + ":" +
callbackResult.property("lineNumber").toString() + ": " +
callbackResult.toString());
}
@@ -377,3 +357,16 @@
{
return QString(PY_VERSION);
}
+
+void
+QPython::emitError(const QString &message)
+{
+ if (error_connections) {
+ emit error(message);
+ } else {
+ // We should only print the error if SINCE_API_VERSION(1, 4), but as
+ // the error messages are useful for debugging (especially if users
+ // don't import the latest API version), we do it unconditionally
+ qWarning("Unhandled PyOtherSide error: %s", message.toUtf8().constData());
+ }
+}
diff -urN pyotherside-1.4.0~git20150111/src/qpython.h pyotherside/src/qpython.h
--- pyotherside-1.4.0~git20150111/src/qpython.h 2015-02-18 12:07:06.000000000 +0200
+++ pyotherside/src/qpython.h 2015-02-18 12:18:28.795571658 +0200
@@ -204,12 +204,12 @@
* }
* \endcode
*
- * \arg func The Python function to call
+ * \arg func The Python function to call (string or Python callable)
* \arg args A list of arguments, or \c [] for no arguments
* \arg callback A callback that receives the function call result
**/
Q_INVOKABLE void
- call(QString func,
+ call(QVariant func,
QVariant args=QVariantList(),
QJSValue callback=QJSValue());
@@ -233,80 +233,12 @@
* }
* \endcode
*
- * \arg func The Python function to call
+ * \arg func The Python function to call (string or Python callable)
* \arg args A list of arguments, or \c [] for no arguments
* \result The return value of the Python call as Qt data type
**/
Q_INVOKABLE QVariant
- call_sync(QString func, QVariant args=QVariantList());
-
-
- /**
- * \brief Asynchronously call a Python method
- *
- * Call a method of a Python object asynchronously and call back
- * into QML when the result is available:
- *
- * \code
- * Python {
- * Component.onCompleted: {
- * importModule('datetime', function() {
- * call('datetime.datetime.now', [], function(dt) {
- * console.log(dt);
- * callMethod(dt, 'strftime', ['%Y-%m-%d'], function(result) {
- * console.log(result);
- * });
- * });
- * });
- * }
- * }
- * \endcode
- *
- * \arg obj The Python object
- * \arg method The method to call
- * \arg args A list of arguments, or \c [] for no arguments
- * \arg callback A callback that receives the function call result
- **/
- Q_INVOKABLE void
- callMethod(
- QVariant obj,
- QString func,
- QVariant args=QVariantList(),
- QJSValue callback=QJSValue());
-
-
- /**
- * \brief Synchronously call a Python method
- *
- * This is the synchronous variant of callMethod(). In general, you
- * should use callMethod() instead of this function to avoid blocking
- * the QML UI thread. Example usage:
- *
- * \code
- * Python {
- * Component.onCompleted: {
- * importModule('datetime', function() {
- * call('datetime.datetime.now', [], function(dt) {
- * console.log(dt);
- * console.log(
- * callMethod_sync(dt, 'strftime', ['%Y-%m-%d'])
- * );
- * });
- * });
- * }
- * }
- * \endcode
- *
- * \arg obj The Python object
- * \arg method The method to call
- * \arg args A list of arguments, or \c [] for no arguments
- * \result The return value of the Python call as Qt data type
- **/
- Q_INVOKABLE QVariant
- callMethod_sync(
- QVariant obj,
- QString func,
- QVariant args=QVariantList());
+ call_sync(QVariant func, QVariant args=QVariantList());
/**
* \brief Get an attribute value of a Python object synchronously
@@ -370,8 +302,7 @@
void error(QString traceback);
/* For internal use only */
- void process(QString func, QVariant args, QJSValue *callback);
- void processMethod(QVariant obj, QString method, QVariant args, QJSValue *callback);
+ void process(QVariant func, QVariant args, QJSValue *callback);
void import(QString name, QJSValue *callback);
private slots:
@@ -380,6 +311,9 @@
void finished(QVariant result, QJSValue *callback);
void imported(bool result, QJSValue *callback);
+ void connectNotify(const QMetaMethod &signal);
+ void disconnectNotify(const QMetaMethod &signal);
+
private:
static QPythonPriv *priv;
@@ -389,6 +323,9 @@
int api_version_major;
int api_version_minor;
+
+ void emitError(const QString &message);
+ int error_connections;
};
class QPython10 : public QPython {
@@ -417,5 +354,14 @@
{
}
};
+
+class QPython14 : public QPython {
+Q_OBJECT
+public:
+ QPython14(QObject *parent=0)
+ : QPython(parent, 1, 4)
+ {
+ }
+};
#endif /* PYOTHERSIDE_QPYTHON_H */
diff -urN pyotherside-1.4.0~git20150111/src/qpython_imageprovider.cpp pyotherside/src/qpython_imageprovider.cpp
--- pyotherside-1.4.0~git20150111/src/qpython_imageprovider.cpp 2015-02-18 12:07:06.000000000 +0200
+++ pyotherside/src/qpython_imageprovider.cpp 2015-02-18 12:18:28.795571658 +0200
@@ -19,6 +19,7 @@
#include "qpython_priv.h"
#include "qpython_imageprovider.h"
+#include "ensure_gil_state.h"
#include <QDebug>
@@ -36,9 +37,9 @@
cleanup_python_qimage(void *data)
{
QPythonPriv *priv = QPythonPriv::instance();
- priv->enter();
+
+ ENSURE_GIL_STATE;
Py_XDECREF(static_cast<PyObject *>(data));
- priv->leave();
}
QImage
@@ -83,20 +84,20 @@
//
// pyotherside.set_image_provider(image_provider)
- priv->enter();
- PyObject *args = Py_BuildValue("(N(ii))",
+ ENSURE_GIL_STATE;
+
+ PyObjectRef args(Py_BuildValue("(N(ii))",
PyUnicode_FromString(id_utf8.constData()),
- requestedSize.width(), requestedSize.height());
- PyObject *result = PyObject_Call(priv->image_provider, args, NULL);
- Py_DECREF(args);
+ requestedSize.width(), requestedSize.height()), true);
+ PyObjectRef result(PyObject_Call(priv->image_provider.borrow(), args.borrow(), NULL), true);
- if (result == NULL) {
+ if (!result) {
qDebug() << "Error while calling the image provider";
PyErr_Print();
goto cleanup;
}
- if (!PyArg_ParseTuple(result, "O(ii)i", &pixels, &width, &height, &format)) {
+ if (!PyArg_ParseTuple(result.borrow(), "O(ii)i", &pixels, &width, &height, &format)) {
PyErr_Clear();
qDebug() << "Image provider must return (pixels, (width, height), format)";
goto cleanup;
@@ -179,8 +180,6 @@
}
cleanup:
- Py_XDECREF(result);
- priv->leave();
*size = img.size();
return img;
diff -urN pyotherside-1.4.0~git20150111/src/qpython_priv.cpp pyotherside/src/qpython_priv.cpp
--- pyotherside-1.4.0~git20150111/src/qpython_priv.cpp 2015-02-18 12:07:06.000000000 +0200
+++ pyotherside/src/qpython_priv.cpp 2015-02-18 12:18:28.795571658 +0200
@@ -20,12 +20,19 @@
#include "qpython_priv.h"
+#include "ensure_gil_state.h"
+
#include <QImage>
#include <QDebug>
#include <QResource>
#include <QFile>
#include <QDir>
+#include <QMetaObject>
+#include <QMetaProperty>
+#include <QMetaMethod>
+#include <QGenericArgument>
+
static QPythonPriv *priv = NULL;
static QString
@@ -41,6 +48,57 @@
return QString::fromUtf8(conv.string(object));
}
+
+PyTypeObject pyotherside_QObjectType = {
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "pyotherside.QObject", /* tp_name */
+ sizeof(pyotherside_QObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ 0, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ 0, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT, /* tp_flags */
+ "Wrapped QObject", /* tp_doc */
+};
+
+PyTypeObject pyotherside_QObjectMethodType = {
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "pyotherside.QObjectMethod", /* tp_name */
+ sizeof(pyotherside_QObjectMethod), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ 0, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ 0, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT, /* tp_flags */
+ "Bound method of wrapped QObject", /* tp_doc */
+};
+
+
+
PyObject *
pyotherside_send(PyObject *self, PyObject *args)
{
@@ -51,12 +109,7 @@
PyObject *
pyotherside_atexit(PyObject *self, PyObject *o)
{
- if (priv->atexit_callback != NULL) {
- Py_DECREF(priv->atexit_callback);
- }
-
- Py_INCREF(o);
- priv->atexit_callback = o;
+ priv->atexit_callback = PyObjectRef(o);
Py_RETURN_NONE;
}
@@ -64,12 +117,7 @@
PyObject *
pyotherside_set_image_provider(PyObject *self, PyObject *o)
{
- if (priv->image_provider != NULL) {
- Py_DECREF(priv->image_provider);
- }
-
- Py_INCREF(o);
- priv->image_provider = o;
+ priv->image_provider = PyObjectRef(o);
Py_RETURN_NONE;
}
@@ -143,6 +191,225 @@
return convertQVariantToPyObject(dir.entryList());
}
+void
+pyotherside_QObject_dealloc(pyotherside_QObject *self)
+{
+ delete self->m_qobject_ref;
+ Py_TYPE(self)->tp_free((PyObject *)self);
+}
+
+PyObject *
+pyotherside_QObject_repr(PyObject *o)
+{
+ if (!PyObject_TypeCheck(o, &pyotherside_QObjectType)) {
+ return PyErr_Format(PyExc_TypeError, "Not a pyotherside.QObject");
+ }
+
+ pyotherside_QObject *pyqobject = reinterpret_cast<pyotherside_QObject *>(o);
+ QObjectRef *ref = pyqobject->m_qobject_ref;
+ if (ref) {
+ QObject *qobject = ref->value();
+ const QMetaObject *metaObject = qobject->metaObject();
+
+ return PyUnicode_FromFormat("<pyotherside.QObject wrapper for %s at %p>",
+ metaObject->className(), qobject);
+ }
+
+ return PyUnicode_FromFormat("<dangling pyotherside.QObject wrapper>");
+}
+
+PyObject *
+pyotherside_QObject_getattro(PyObject *o, PyObject *attr_name)
+{
+ if (!PyObject_TypeCheck(o, &pyotherside_QObjectType)) {
+ return PyErr_Format(PyExc_TypeError, "Not a pyotherside.QObject");
+ }
+
+ if (!PyUnicode_Check(attr_name)) {
+ return PyErr_Format(PyExc_TypeError, "attr_name must be a string");
+ }
+
+ pyotherside_QObject *pyqobject = reinterpret_cast<pyotherside_QObject *>(o);
+ QObjectRef *ref = pyqobject->m_qobject_ref;
+ if (!ref) {
+ return PyErr_Format(PyExc_ValueError, "Dangling QObject");
+ }
+ QObject *qobject = ref->value();
+ if (!qobject) {
+ return PyErr_Format(PyExc_ReferenceError, "Referenced QObject was deleted");
+ }
+
+ const QMetaObject *metaObject = qobject->metaObject();
+ QString attrName = convertPyObjectToQVariant(attr_name).toString();
+
+ for (int i=0; i<metaObject->propertyCount(); i++) {
+ QMetaProperty property = metaObject->property(i);
+ if (attrName == property.name()) {
+ return convertQVariantToPyObject(property.read(qobject));
+ }
+ }
+
+ for (int i=0; i<metaObject->methodCount(); i++) {
+ QMetaMethod method = metaObject->method(i);
+ if (attrName == method.name()) {
+ pyotherside_QObjectMethod *result = PyObject_New(pyotherside_QObjectMethod,
+ &pyotherside_QObjectMethodType);
+ result->m_method_ref = new QObjectMethodRef(*ref, attrName);
+ return reinterpret_cast<PyObject *>(result);
+ }
+ }
+
+ return PyErr_Format(PyExc_AttributeError, "Not a valid attribute");
+}
+
+int
+pyotherside_QObject_setattro(PyObject *o, PyObject *attr_name, PyObject *v)
+{
+ if (!PyObject_TypeCheck(o, &pyotherside_QObjectType)) {
+ PyErr_Format(PyExc_TypeError, "Not a pyotherside.QObject");
+ return -1;
+ }
+
+ if (!PyUnicode_Check(attr_name)) {
+ PyErr_Format(PyExc_TypeError, "attr_name must be a string");
+ return -1;
+ }
+
+ pyotherside_QObject *pyqobject = reinterpret_cast<pyotherside_QObject *>(o);
+ QObjectRef *ref = pyqobject->m_qobject_ref;
+ if (!ref) {
+ PyErr_Format(PyExc_ValueError, "Dangling QObject");
+ return -1;
+ }
+ QObject *qobject = ref->value();
+ if (!qobject) {
+ PyErr_Format(PyExc_ReferenceError, "Referenced QObject was deleted");
+ return -1;
+ }
+
+ const QMetaObject *metaObject = qobject->metaObject();
+ QString attrName = convertPyObjectToQVariant(attr_name).toString();
+
+ for (int i=0; i<metaObject->propertyCount(); i++) {
+ QMetaProperty property = metaObject->property(i);
+ if (attrName == property.name()) {
+ QVariant variant(convertPyObjectToQVariant(v));
+ if (!property.write(qobject, variant)) {
+ PyErr_Format(PyExc_AttributeError, "Could not set property %s to %s(%s)",
+ attrName.toUtf8().constData(),
+ variant.typeName(),
+ variant.toString().toUtf8().constData());
+ return -1;
+ }
+
+ return 0;
+ }
+ }
+
+ PyErr_Format(PyExc_AttributeError, "Property does not exist: %s",
+ attrName.toUtf8().constData());
+ return -1;
+}
+
+void
+pyotherside_QObjectMethod_dealloc(pyotherside_QObjectMethod *self)
+{
+ delete self->m_method_ref;
+ Py_TYPE(self)->tp_free((PyObject *)self);
+}
+
+PyObject *
+pyotherside_QObjectMethod_repr(PyObject *o)
+{
+ if (!PyObject_TypeCheck(o, &pyotherside_QObjectMethodType)) {
+ return PyErr_Format(PyExc_TypeError, "Not a pyotherside.QObjectMethod");
+ }
+
+ pyotherside_QObjectMethod *pyqobjectmethod = reinterpret_cast<pyotherside_QObjectMethod *>(o);
+
+ QObjectMethodRef *ref = pyqobjectmethod->m_method_ref;
+ if (!ref) {
+ return PyUnicode_FromFormat("<dangling pyotherside.QObjectMethod>");
+ }
+
+ QObjectRef oref = ref->object();
+ QObject *qobject = oref.value();
+ if (!qobject) {
+ return PyUnicode_FromFormat("<pyotherside.QObjectMethod '%s' bound to deleted QObject>",
+ ref->method().toUtf8().constData());
+ }
+
+ const QMetaObject *metaObject = qobject->metaObject();
+ return PyUnicode_FromFormat("<pyotherside.QObjectMethod '%s' bound to %s at %p>",
+ ref->method().toUtf8().constData(), metaObject->className(), qobject);
+}
+
+
+PyObject *
+pyotherside_QObjectMethod_call(PyObject *callable_object, PyObject *args, PyObject *kw)
+{
+ if (!PyObject_TypeCheck(callable_object, &pyotherside_QObjectMethodType)) {
+ return PyErr_Format(PyExc_TypeError, "Not a pyotherside.QObjectMethod");
+ }
+
+ if (!PyTuple_Check(args)) {
+ return PyErr_Format(PyExc_TypeError, "Argument list not a tuple");
+ }
+
+ if (kw) {
+ if (!PyMapping_Check(kw)) {
+ return PyErr_Format(PyExc_TypeError, "Keyword arguments not a mapping");
+ }
+
+ if (PyMapping_Size(kw) > 0) {
+ return PyErr_Format(PyExc_ValueError, "Keyword arguments not supported");
+ }
+ }
+
+ QList<QVariant> qargs = convertPyObjectToQVariant(args).toList();
+
+ pyotherside_QObjectMethod *pyqobjectmethod = reinterpret_cast<pyotherside_QObjectMethod *>(callable_object);
+ QObjectMethodRef *ref = pyqobjectmethod->m_method_ref;
+ if (!ref) {
+ return PyErr_Format(PyExc_ValueError, "Dangling QObject");
+ }
+
+ QList<QGenericArgument> genericArguments;
+ for (int j=0; j<qargs.size(); j++) {
+ const QVariant& argument = qargs[j];
+ genericArguments.append(QGenericArgument(argument.typeName(), argument.constData()));
+ }
+
+ QObject *o = ref->object().value();
+ if (!o) {
+ return PyErr_Format(PyExc_ReferenceError, "Referenced QObject was deleted");
+ }
+ const QMetaObject *metaObject = o->metaObject();
+
+ for (int i=0; i<metaObject->methodCount(); i++) {
+ QMetaMethod method = metaObject->method(i);
+
+ if (method.name() == ref->method()) {
+ QVariant result;
+ if (method.invoke(o, Qt::DirectConnection,
+ Q_RETURN_ARG(QVariant, result), genericArguments.value(0),
+ genericArguments.value(1), genericArguments.value(2),
+ genericArguments.value(3), genericArguments.value(4),
+ genericArguments.value(5), genericArguments.value(6),
+ genericArguments.value(7), genericArguments.value(8),
+ genericArguments.value(9))) {
+ return convertQVariantToPyObject(result);
+ }
+
+ return PyErr_Format(PyExc_RuntimeError, "QObject method call failed");
+ }
+ }
+
+ return PyErr_Format(PyExc_RuntimeError, "QObject method not found: %s",
+ ref->method().toUtf8().constData());
+}
+
+
static PyMethodDef PyOtherSideMethods[] = {
/* Introduced in PyOtherSide 1.0 */
{"send", pyotherside_send, METH_VARARGS, "Send data to Qt."},
@@ -192,60 +459,81 @@
// Version of PyOtherSide (new in 1.3)
PyModule_AddStringConstant(pyotherside, "version", PYOTHERSIDE_VERSION);
+ // QObject wrappers (new in 1.4)
+ pyotherside_QObjectType.tp_new = PyType_GenericNew;
+ pyotherside_QObjectType.tp_repr = pyotherside_QObject_repr;
+ pyotherside_QObjectType.tp_getattro = pyotherside_QObject_getattro;
+ pyotherside_QObjectType.tp_setattro = pyotherside_QObject_setattro;
+ pyotherside_QObjectType.tp_dealloc = (destructor)pyotherside_QObject_dealloc;
+ if (PyType_Ready(&pyotherside_QObjectType) < 0) {
+ qFatal("Could not initialize QObjectType");
+ // Not reached
+ return NULL;
+ }
+ Py_INCREF(&pyotherside_QObjectType);
+ PyModule_AddObject(pyotherside, "QObject", (PyObject *)(&pyotherside_QObjectType));
+
+ pyotherside_QObjectMethodType.tp_new = PyType_GenericNew;
+ pyotherside_QObjectMethodType.tp_repr = pyotherside_QObjectMethod_repr;
+ pyotherside_QObjectMethodType.tp_call = pyotherside_QObjectMethod_call;
+ pyotherside_QObjectMethodType.tp_dealloc = (destructor)pyotherside_QObjectMethod_dealloc;
+ if (PyType_Ready(&pyotherside_QObjectMethodType) < 0) {
+ qFatal("Could not initialize QObjectMethodType");
+ // Not reached
+ return NULL;
+ }
+ Py_INCREF(&pyotherside_QObjectMethodType);
+ PyModule_AddObject(pyotherside, "QObjectMethod", (PyObject *)(&pyotherside_QObjectMethodType));
+
return pyotherside;
}
QPythonPriv::QPythonPriv()
- : locals(NULL)
- , globals(NULL)
- , gil_state()
- , atexit_callback(NULL)
- , image_provider(NULL)
- , traceback_mod(NULL)
+ : locals()
+ , globals()
+ , atexit_callback()
+ , image_provider()
+ , traceback_mod()
+ , pyotherside_mod()
+ , thread_state(NULL)
{
PyImport_AppendInittab("pyotherside", PyOtherSide_init);
- Py_Initialize();
+ Py_InitializeEx(0);
PyEval_InitThreads();
- locals = PyDict_New();
- assert(locals != NULL);
+ locals = PyObjectRef(PyDict_New(), true);
+ assert(locals);
- globals = PyDict_New();
- assert(globals != NULL);
+ globals = PyObjectRef(PyDict_New(), true);
+ assert(globals);
- traceback_mod = PyImport_ImportModule("traceback");
- assert(traceback_mod != NULL);
+ traceback_mod = PyObjectRef(PyImport_ImportModule("traceback"), true);
+ assert(traceback_mod);
priv = this;
- if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
- PyDict_SetItemString(globals, "__builtins__",
+ if (PyDict_GetItemString(globals.borrow(), "__builtins__") == NULL) {
+ PyDict_SetItemString(globals.borrow(), "__builtins__",
PyEval_GetBuiltins());
}
- leave();
-}
+ // Need to "self-import" the pyotherside module here, so that Python code
+ // can use objects wrapped with pyotherside.QObject without crashing when
+ // the user's Python code doesn't "import pyotherside"
+ pyotherside_mod = PyObjectRef(PyImport_ImportModule("pyotherside"), true);
+ assert(pyotherside_mod);
-QPythonPriv::~QPythonPriv()
-{
- enter();
- Py_DECREF(traceback_mod);
- Py_DECREF(globals);
- Py_DECREF(locals);
- Py_Finalize();
+ // Release the GIL
+ thread_state = PyEval_SaveThread();
}
-void
-QPythonPriv::enter()
+QPythonPriv::~QPythonPriv()
{
- gil_state = PyGILState_Ensure();
-}
+ // Re-acquire the previously-released GIL
+ PyEval_RestoreThread(thread_state);
-void
-QPythonPriv::leave()
-{
- PyGILState_Release(gil_state);
+ Py_Finalize();
}
void
@@ -286,7 +574,7 @@
goto cleanup;
}
- list = PyObject_CallMethod(traceback_mod,
+ list = PyObject_CallMethod(traceback_mod.borrow(),
"format_exception", "OOO", type, value, traceback);
if (list == NULL) {
@@ -330,7 +618,7 @@
{
QByteArray utf8bytes = expr.toUtf8();
PyObject *result = PyRun_String(utf8bytes.constData(),
- Py_eval_input, globals, locals);
+ Py_eval_input, globals.borrow(), locals.borrow());
return result;
}
@@ -342,21 +630,16 @@
return;
}
- priv->enter();
- if (priv->atexit_callback != NULL) {
- PyObject *args = PyTuple_New(0);
- PyObject *result = PyObject_Call(priv->atexit_callback, args, NULL);
- Py_DECREF(args);
- Py_XDECREF(result);
-
- Py_DECREF(priv->atexit_callback);
- priv->atexit_callback = NULL;
- }
- if (priv->image_provider != NULL) {
- Py_DECREF(priv->image_provider);
- priv->image_provider = NULL;
+ ENSURE_GIL_STATE;
+
+ if (priv->atexit_callback) {
+ PyObjectRef args(PyTuple_New(0), true);
+ PyObjectRef result(PyObject_Call(priv->atexit_callback.borrow(), args.borrow(), NULL), true);
+ Q_UNUSED(result);
}
- priv->leave();
+
+ priv->atexit_callback = PyObjectRef();
+ priv->image_provider = PyObjectRef();
}
QPythonPriv *
@@ -368,15 +651,15 @@
QString
QPythonPriv::importFromQRC(const char *module, const QString &filename)
{
- PyObject *sys_modules = PySys_GetObject((char *)"modules");
- if (!PyMapping_Check(sys_modules)) {
+ PyObjectRef sys_modules(PySys_GetObject((char *)"modules"), true);
+ if (!PyMapping_Check(sys_modules.borrow())) {
return QString("sys.modules is not a mapping object");
}
- PyObject *qrc_importer = PyMapping_GetItemString(sys_modules,
- (char *)module);
+ PyObjectRef qrc_importer(PyMapping_GetItemString(sys_modules.borrow(),
+ (char *)module), true);
- if (qrc_importer == NULL) {
+ if (!qrc_importer) {
PyErr_Clear();
QFile qrc_importer_code(":" + filename);
@@ -387,27 +670,24 @@
QByteArray ba = qrc_importer_code.readAll();
QByteArray fn = QString("qrc:/" + filename).toUtf8();
- PyObject *co = Py_CompileString(ba.constData(), fn.constData(),
- Py_file_input);
- if (co == NULL) {
+ PyObjectRef co(Py_CompileString(ba.constData(), fn.constData(),
+ Py_file_input), true);
+ if (!co) {
QString result = QString("Cannot compile qrc importer: %1")
.arg(formatExc());
PyErr_Clear();
return result;
}
- qrc_importer = PyImport_ExecCodeModule((char *)module, co);
- if (qrc_importer == NULL) {
+ qrc_importer = PyObjectRef(PyImport_ExecCodeModule((char *)module, co.borrow()), true);
+ if (!qrc_importer) {
QString result = QString("Cannot exec qrc importer: %1")
.arg(formatExc());
PyErr_Clear();
return result;
}
- Py_XDECREF(co);
}
- Py_XDECREF(qrc_importer);
-
return QString();
}
@@ -418,25 +698,21 @@
return QString("Not a callable: %1").arg(name);
}
- PyObject *argl = convertQVariantToPyObject(args);
- if (!PyList_Check(argl)) {
- Py_XDECREF(argl);
+ PyObjectRef argl(convertQVariantToPyObject(args), true);
+ if (!PyList_Check(argl.borrow())) {
return QString("Not a parameter list in call to %1: %2")
.arg(name).arg(args.toString());
}
- PyObject *argt = PyList_AsTuple(argl);
- Py_DECREF(argl);
- PyObject *o = PyObject_Call(callable, argt, NULL);
- Py_DECREF(argt);
+ PyObjectRef argt(PyList_AsTuple(argl.borrow()), true);
+ PyObjectRef o(PyObject_Call(callable, argt.borrow(), NULL), true);
- if (o == NULL) {
+ if (!o) {
return QString("Return value of PyObject call is NULL: %1").arg(priv->formatExc());
} else {
if (v != NULL) {
- *v = convertPyObjectToQVariant(o);
+ *v = convertPyObjectToQVariant(o.borrow());
}
- Py_DECREF(o);
}
return QString();
}
diff -urN pyotherside-1.4.0~git20150111/src/qpython_priv.h pyotherside/src/qpython_priv.h
--- pyotherside-1.4.0~git20150111/src/qpython_priv.h 2015-02-18 12:07:06.000000000 +0200
+++ pyotherside/src/qpython_priv.h 2015-02-18 12:18:28.795571658 +0200
@@ -21,10 +21,14 @@
#include "Python.h"
+#include "pyobject_ref.h"
+#include "pyqobject.h"
+
#include <QObject>
#include <QVariant>
#include <QString>
+
class QPythonPriv : public QObject {
Q_OBJECT
@@ -34,9 +38,6 @@
PyObject *eval(QString expr);
- void enter();
- void leave();
-
QString importFromQRC(const char *module, const QString &filename);
QString call(PyObject *callable, QString name, QVariant args, QVariant *v);
@@ -46,12 +47,13 @@
QString formatExc();
- PyObject *locals;
- PyObject *globals;
- PyGILState_STATE gil_state;
- PyObject *atexit_callback;
- PyObject *image_provider;
- PyObject *traceback_mod;
+ PyObjectRef locals;
+ PyObjectRef globals;
+ PyObjectRef atexit_callback;
+ PyObjectRef image_provider;
+ PyObjectRef traceback_mod;
+ PyObjectRef pyotherside_mod;
+ PyThreadState *thread_state;
signals:
void receive(QVariant data);
diff -urN pyotherside-1.4.0~git20150111/src/qpython_worker.cpp pyotherside/src/qpython_worker.cpp
--- pyotherside-1.4.0~git20150111/src/qpython_worker.cpp 2015-02-18 12:07:06.000000000 +0200
+++ pyotherside/src/qpython_worker.cpp 2015-02-18 12:18:28.795571658 +0200
@@ -32,21 +32,12 @@
}
void
-QPythonWorker::process(QString func, QVariant args, QJSValue *callback)
+QPythonWorker::process(QVariant func, QVariant args, QJSValue *callback)
{
QVariant result = qpython->call_sync(func, args);
if (callback) {
emit finished(result, callback);
}
-}
-
-void
-QPythonWorker::processMethod(QVariant obj, QString method, QVariant args, QJSValue *callback)
-{
- QVariant result = qpython->callMethod_sync(obj, method, args);
- if (callback) {
- emit finished(result, callback);
- }
}
void
diff -urN pyotherside-1.4.0~git20150111/src/qpython_worker.h pyotherside/src/qpython_worker.h
--- pyotherside-1.4.0~git20150111/src/qpython_worker.h 2015-02-18 12:07:06.000000000 +0200
+++ pyotherside/src/qpython_worker.h 2015-02-18 12:18:28.795571658 +0200
@@ -34,8 +34,7 @@
~QPythonWorker();
public slots:
- void process(QString func, QVariant args, QJSValue *callback);
- void processMethod(QVariant obj, QString method, QVariant args, QJSValue *callback);
+ void process(QVariant func, QVariant args, QJSValue *callback);
void import(QString func, QJSValue *callback);
signals:
diff -urN pyotherside-1.4.0~git20150111/src/qvariant_converter.h pyotherside/src/qvariant_converter.h
--- pyotherside-1.4.0~git20150111/src/qvariant_converter.h 2015-02-18 12:07:06.000000000 +0200
+++ pyotherside/src/qvariant_converter.h 2015-02-18 12:18:28.795571658 +0200
@@ -22,9 +22,12 @@
#include "converter.h"
#include <QVariant>
+
#include <QTime>
#include <QDate>
#include <QDateTime>
+#include <QJSValue>
+
#include <QDebug>
class QVariantListBuilder : public ListBuilder<QVariant> {
@@ -63,7 +66,7 @@
class QVariantListIterator : public ListIterator<QVariant> {
public:
- QVariantListIterator(QVariant &v) : list(v.toList()), pos(0) {}
+ QVariantListIterator(const QVariant &v) : list(v.toList()), pos(0) {}
virtual ~QVariantListIterator() {}
virtual bool next(QVariant *v) {
@@ -84,7 +87,7 @@
class QVariantDictIterator : public DictIterator<QVariant> {
public:
- QVariantDictIterator(QVariant &v) : dict(v.toMap()), keys(dict.keys()), pos(0) {}
+ QVariantDictIterator(const QVariant &v) : dict(v.toMap()), keys(dict.keys()), pos(0) {}
virtual ~QVariantDictIterator() {}
virtual bool next(QVariant *key, QVariant *value) {
@@ -111,7 +114,11 @@
QVariantConverter() : stringstorage() {}
virtual ~QVariantConverter() {}
- virtual enum Type type(QVariant &v) {
+ virtual enum Type type(const QVariant &v) {
+ if (v.canConvert<QObject *>()) {
+ return QOBJECT;
+ }
+
QMetaType::Type t = (QMetaType::Type)v.type();
switch (t) {
case QMetaType::Bool:
@@ -142,6 +149,9 @@
int userType = v.userType();
if (userType == qMetaTypeId<PyObjectRef>()) {
return PYOBJECT;
+ } else if (userType == qMetaTypeId<QJSValue>()) {
+ // TODO: Support boxing a QJSValue as reference in Python
+ return type(v.value<QJSValue>().toVariant());
} else {
qDebug() << "Cannot convert:" << v;
return NONE;
@@ -150,10 +160,18 @@
}
virtual ListIterator<QVariant> *list(QVariant &v) {
+ // XXX: Until we support boxing QJSValue objects directly in Python
+ if (v.userType() == qMetaTypeId<QJSValue>()) {
+ return new QVariantListIterator(v.value<QJSValue>().toVariant());
+ }
return new QVariantListIterator(v);
}
virtual DictIterator<QVariant> *dict(QVariant &v) {
+ // XXX: Until we support boxing QJSValue objects directly in Python
+ if (v.userType() == qMetaTypeId<QJSValue>()) {
+ return new QVariantDictIterator(v.value<QJSValue>().toVariant());
+ }
return new QVariantDictIterator(v);
}
@@ -196,6 +214,10 @@
return v.value<PyObjectRef>();
}
+ virtual QObjectRef qObject(QVariant &v) {
+ return QObjectRef(v.value<QObject *>());
+ }
+
virtual ListBuilder<QVariant> *newList() {
return new QVariantListBuilder;
}
@@ -218,6 +240,9 @@
virtual QVariant fromPyObject(const PyObjectRef &pyobj) {
return QVariant::fromValue(pyobj);
}
+ virtual QVariant fromQObject(const QObjectRef &qobj) {
+ return QVariant::fromValue(qobj.value());
+ }
virtual QVariant none() { return QVariant(); };
private:
diff -urN pyotherside-1.4.0~git20150111/src/src.pro pyotherside/src/src.pro
--- pyotherside-1.4.0~git20150111/src/src.pro 2015-02-18 12:07:06.000000000 +0200
+++ pyotherside/src/src.pro 2015-02-18 12:18:28.795571658 +0200
@@ -31,6 +31,14 @@
# Importer from Qt Resources
RESOURCES += qrc_importer.qrc
+# Embedded Python Library (add pythonlib.zip if you want this)
+exists (pythonlib.zip) {
+ RESOURCES += pythonlib_loader.qrc
+ DEFINES *= PYTHONLIB_LOADER_HAVE_PYTHONLIB_ZIP
+}
+HEADERS += pythonlib_loader.h
+SOURCES += pythonlib_loader.cpp
+
# Python QML Object
SOURCES += qpython.cpp
HEADERS += qpython.h
@@ -47,6 +55,14 @@
SOURCES += pyobject_ref.cpp
HEADERS += pyobject_ref.h
+# QObject wrapper class exposed to Python
+SOURCES += qobject_ref.cpp
+HEADERS += qobject_ref.h
+HEADERS += pyqobject.h
+
+# GIL helper
+HEADERS += ensure_gil_state.h
+
# Type System Conversion Logic
HEADERS += converter.h
HEADERS += qvariant_converter.h
diff -urN pyotherside-1.4.0~git20150111/tests/test_added_in_14/test_added_in_14.qml pyotherside/tests/test_added_in_14/test_added_in_14.qml
--- pyotherside-1.4.0~git20150111/tests/test_added_in_14/test_added_in_14.qml 1970-01-01 02:00:00.000000000 +0200
+++ pyotherside/tests/test_added_in_14/test_added_in_14.qml 2015-02-18 12:18:28.795571658 +0200
@@ -0,0 +1,26 @@
+import QtQuick 2.0
+// Note that we import 1.3 here instead of >= 1.4
+import io.thp.pyotherside 1.3
+
+Python {
+ Component.onCompleted: {
+ var foo = undefined;
+
+ // qml: Received error: Import PyOtherSide 1.4 or newer to use getattr()
+ getattr(foo, 'test');
+
+ var func = eval('[]');
+
+ // qml: Received error: Function not found: '' (unexpected EOF while parsing (<string>, line 0))
+ call(func, [], function (result) {});
+
+ // qml: Received error: Function not found: '' (unexpected EOF while parsing (<string>, line 0))
+ var result = call_sync(func, []);
+
+ Qt.quit();
+ }
+
+ onError: {
+ console.log('Received error: ' + traceback);
+ }
+}
diff -urN pyotherside-1.4.0~git20150111/tests/test_issue23/issue23.qml pyotherside/tests/test_issue23/issue23.qml
--- pyotherside-1.4.0~git20150111/tests/test_issue23/issue23.qml 1970-01-01 02:00:00.000000000 +0200
+++ pyotherside/tests/test_issue23/issue23.qml 2015-02-18 12:18:28.795571658 +0200
@@ -0,0 +1,30 @@
+/**
+ * Issue #23: importModule runs forever
+ * https://github.com/thp/pyotherside/issues/23
+ **/
+
+import QtQuick 2.0
+import io.thp.pyotherside 1.3
+
+Rectangle {
+ width: 300
+ height: 300
+
+ Text {
+ id: text
+ anchors.centerIn: parent
+ }
+
+ Python {
+ Component.onCompleted: {
+ importModule('gi.repository.Gio', function() {
+ console.log('import completed');
+ call('gi.repository.Gio.Settings.new("org.gnome.Vino").keys', [], function(result) {
+ text.text = result.join('\n');
+ });
+ });
+ }
+
+ onError: console.log('Error: ' + traceback);
+ }
+}
diff -urN pyotherside-1.4.0~git20150111/tests/tests.cpp pyotherside/tests/tests.cpp
--- pyotherside-1.4.0~git20150111/tests/tests.cpp 2015-02-18 12:07:06.000000000 +0200
+++ pyotherside/tests/tests.cpp 2015-02-18 12:18:28.799571658 +0200
@@ -113,6 +113,73 @@
*destructor_called = true;
}
+void TestPyOtherSide::testPyObjectRefAssignment()
+{
+ // Test assignment operator of PyObjectRef
+ bool destructor_called_foo = false;
+ PyObject *foo = PyCapsule_New(&destructor_called_foo, "test", destruct);
+
+ bool destructor_called_bar = false;
+ PyObject *bar = PyCapsule_New(&destructor_called_bar, "test", destruct);
+
+ QVERIFY(foo);
+ QVERIFY(foo->ob_refcnt == 1);
+
+ QVERIFY(bar);
+ QVERIFY(bar->ob_refcnt == 1);
+
+ {
+ PyObjectRef a(foo);
+ PyObjectRef b(bar);
+ PyObjectRef c; // empty
+
+ // foo got a new reference in a
+ QVERIFY(foo->ob_refcnt == 2);
+ // bar got a new reference in b
+ QVERIFY(bar->ob_refcnt == 2);
+
+ // Overwrite empty reference with reference to bar
+ c = b;
+ // bar got a new reference in c
+ QVERIFY(bar->ob_refcnt == 3);
+ // reference count for foo is unchanged
+ QVERIFY(foo->ob_refcnt == 2);
+
+ // Overwrite reference to bar with reference to foo
+ b = a;
+ // bar lost a reference in b
+ QVERIFY(bar->ob_refcnt == 2);
+ // foo got a new reference in b
+ QVERIFY(foo->ob_refcnt == 3);
+
+ // Overwrite reference to foo with empty reference
+ a = PyObjectRef();
+ // foo lost a reference in a
+ QVERIFY(foo->ob_refcnt == 2);
+
+ Py_DECREF(foo);
+
+ // there is still a reference to foo in b
+ QVERIFY(foo->ob_refcnt == 1);
+ QVERIFY(!destructor_called_foo);
+
+ // a falls out of scope (but is empty)
+ // b falls out of scope, foo loses a reference
+ // c falls out of scope, bar loses a reference
+ }
+
+ // Now that b fell out of scope, foo was destroyed
+ QVERIFY(destructor_called_foo);
+
+ // But we still have a single reference to bar
+ QVERIFY(!destructor_called_bar);
+ QVERIFY(bar->ob_refcnt == 1);
+ Py_CLEAR(bar);
+
+ // Now bar is also gone
+ QVERIFY(destructor_called_bar);
+}
+
void
TestPyOtherSide::testPyObjectRefRoundTrip()
{
@@ -156,6 +223,19 @@
}
void
+TestPyOtherSide::testQObjectRef()
+{
+ QObject *o = new QObject();
+ QObjectRef ref(o);
+
+ QVERIFY(ref.value() == o);
+
+ delete o;
+
+ QVERIFY(ref.value() == NULL);
+}
+
+void
TestPyOtherSide::testQVariantConverter()
{
test_converter_for<QVariant>(new QVariantConverter);
diff -urN pyotherside-1.4.0~git20150111/tests/tests.h pyotherside/tests/tests.h
--- pyotherside-1.4.0~git20150111/tests/tests.h 2015-02-18 12:07:06.000000000 +0200
+++ pyotherside/tests/tests.h 2015-02-18 12:18:28.799571658 +0200
@@ -35,6 +35,8 @@
void testQVariantConverter();
void testPyObjectConverter();
void testPyObjectRefRoundTrip();
+ void testPyObjectRefAssignment();
+ void testQObjectRef();
void testConvertToPythonAndBack();
void testSetToList();
};
diff -urN pyotherside-1.4.0~git20150111/tests/tests.pro pyotherside/tests/tests.pro
--- pyotherside-1.4.0~git20150111/tests/tests.pro 2015-02-18 12:07:06.000000000 +0200
+++ pyotherside/tests/tests.pro 2015-02-18 12:18:28.799571658 +0200
@@ -11,6 +11,7 @@
SOURCES += ../src/qpython_worker.cpp
SOURCES += ../src/qpython_priv.cpp
SOURCES += ../src/pyobject_ref.cpp
+SOURCES += ../src/qobject_ref.cpp
HEADERS += ../src/qpython.h
HEADERS += ../src/qpython_worker.h
@@ -18,6 +19,8 @@
HEADERS += ../src/converter.h
HEADERS += ../src/qvariant_converter.h
HEADERS += ../src/pyobject_converter.h
+HEADERS += ../src/pyobject_ref.h
+HEADERS += ../src/qobject_ref.h
DEPENDPATH += . ../src
INCLUDEPATH += . ../src
diff -urN pyotherside-1.4.0~git20150111/tests/test_wrapped/test_wrapped.qml pyotherside/tests/test_wrapped/test_wrapped.qml
--- pyotherside-1.4.0~git20150111/tests/test_wrapped/test_wrapped.qml 2015-02-18 12:07:06.000000000 +0200
+++ pyotherside/tests/test_wrapped/test_wrapped.qml 2015-02-18 12:18:28.799571658 +0200
@@ -1,5 +1,5 @@
import QtQuick 2.0
-import io.thp.pyotherside 1.0
+import io.thp.pyotherside 1.4
Rectangle {
id: page
@@ -18,10 +18,15 @@
console.log('attribute bar of foo: ' + getattr(foo, 'bar'));
- callMethod(foo, 'methodman', ['the pain'], function (result) {
+ var func = getattr(foo, 'methodman');
+
+ call(func, ['the pain'], function (result) {
console.log('methodman() result: ' + result);
});
+ var mmr = call_sync(func, ['the pain']);
+ console.log('methodman() sync result: ' + mmr);
+
var result = call_sync('test_wrapped.set_foo', [foo]);
console.log('got result: ' + result);
});
|