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
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; fill-column: 100 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include <config_features.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#ifdef IOS
#include <sys/mman.h>
#include <sys/stat.h>
#include <unicode/udata.h>
#include <unicode/ucnv.h>
#include <premac.h>
#import <Foundation/Foundation.h>
#import <CoreGraphics/CoreGraphics.h>
#include <postmac.h>
#endif
#ifdef ANDROID
#include <osl/detail/android-bootstrap.h>
#endif
#include <algorithm>
#include <memory>
#include <iostream>
#include <boost/property_tree/json_parser.hpp>
#include <boost/algorithm/string.hpp>
#include <LibreOfficeKit/LibreOfficeKit.h>
#include <LibreOfficeKit/LibreOfficeKitEnums.h>
#include <sal/log.hxx>
#include <vcl/errinf.hxx>
#include <vcl/lok.hxx>
#include <o3tl/any.hxx>
#include <osl/file.hxx>
#include <osl/process.h>
#include <osl/thread.h>
#include <rtl/bootstrap.hxx>
#include <rtl/strbuf.hxx>
#include <rtl/uri.hxx>
#include <svl/zforlist.hxx>
#include <cppuhelper/bootstrap.hxx>
#include <comphelper/base64.hxx>
#include <comphelper/dispatchcommand.hxx>
#include <comphelper/lok.hxx>
#include <comphelper/processfactory.hxx>
#include <comphelper/string.hxx>
#include <comphelper/profilezone.hxx>
#include <comphelper/propertysequence.hxx>
#include <comphelper/scopeguard.hxx>
#include <comphelper/threadpool.hxx>
#include <comphelper/sequenceashashmap.hxx>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/container/XNameAccess.hpp>
#include <com/sun/star/frame/Desktop.hpp>
#include <com/sun/star/frame/DispatchResultEvent.hpp>
#include <com/sun/star/frame/DispatchResultState.hpp>
#include <com/sun/star/frame/XDispatchProvider.hpp>
#include <com/sun/star/frame/XDispatchResultListener.hpp>
#include <com/sun/star/frame/XSynchronousDispatch.hpp>
#include <com/sun/star/frame/XStorable.hpp>
#include <com/sun/star/lang/Locale.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/reflection/theCoreReflection.hpp>
#include <com/sun/star/reflection/XIdlClass.hpp>
#include <com/sun/star/reflection/XIdlReflection.hpp>
#include <com/sun/star/style/XStyleFamiliesSupplier.hpp>
#include <com/sun/star/util/URLTransformer.hpp>
#include <com/sun/star/datatransfer/clipboard/XClipboard.hpp>
#include <com/sun/star/datatransfer/UnsupportedFlavorException.hpp>
#include <com/sun/star/datatransfer/XTransferable2.hpp>
#include <com/sun/star/text/TextContentAnchorType.hpp>
#include <com/sun/star/document/XRedlinesSupplier.hpp>
#include <com/sun/star/ui/GlobalAcceleratorConfiguration.hpp>
#include <com/sun/star/xml/crypto/SEInitializer.hpp>
#include <com/sun/star/xml/crypto/XSEInitializer.hpp>
#include <com/sun/star/xml/crypto/XSecurityEnvironment.hpp>
#include <com/sun/star/xml/crypto/XCertificateCreator.hpp>
#include <com/sun/star/security/XCertificate.hpp>
#include <com/sun/star/linguistic2/LinguServiceManager.hpp>
#include <com/sun/star/linguistic2/XSpellChecker.hpp>
#include <com/sun/star/i18n/LocaleCalendar2.hpp>
#include <com/sun/star/i18n/ScriptType.hpp>
#include <com/sun/star/lang/DisposedException.hpp>
#include <editeng/flstitem.hxx>
#ifdef IOS
#include <sfx2/app.hxx>
#endif
#include <sfx2/objsh.hxx>
#include <sfx2/docfilt.hxx>
#include <sfx2/docfile.hxx>
#include <sfx2/viewsh.hxx>
#include <sfx2/viewfrm.hxx>
#include <sfx2/msgpool.hxx>
#include <sfx2/dispatch.hxx>
#include <sfx2/lokcharthelper.hxx>
#include <sfx2/DocumentSigner.hxx>
#include <sfx2/sidebar/SidebarDockingWindow.hxx>
#include <sfx2/sidebar/SidebarController.hxx>
#include <svx/dialmgr.hxx>
#include <svx/strings.hrc>
#include <svx/svdview.hxx>
#include <svx/svxids.hrc>
#include <svx/ucsubset.hxx>
#include <vcl/vclevent.hxx>
#include <vcl/GestureEvent.hxx>
#include <vcl/svapp.hxx>
#include <unotools/resmgr.hxx>
#include <tools/fract.hxx>
#include <tools/json_writer.hxx>
#include <svtools/ctrltool.hxx>
#include <svtools/langtab.hxx>
#include <vcl/floatwin.hxx>
#include <vcl/fontcharmap.hxx>
#include <vcl/graphicfilter.hxx>
#ifdef IOS
#include <vcl/sysdata.hxx>
#endif
#include <vcl/virdev.hxx>
#include <vcl/ImageTree.hxx>
#include <vcl/ITiledRenderable.hxx>
#include <vcl/dialoghelper.hxx>
#include <unicode/uchar.h>
#include <unotools/confignode.hxx>
#include <unotools/syslocaleoptions.hxx>
#include <unotools/mediadescriptor.hxx>
#include <unotools/pathoptions.hxx>
#include <unotools/tempfile.hxx>
#include <unotools/streamwrap.hxx>
#include <osl/module.hxx>
#include <comphelper/sequence.hxx>
#include <sfx2/sfxbasemodel.hxx>
#include <svl/undo.hxx>
#include <unotools/datetime.hxx>
#include <i18nlangtag/mslangid.hxx>
#include <i18nlangtag/languagetag.hxx>
#include <vcl/builder.hxx>
#include <vcl/abstdlg.hxx>
#include <tools/diagnose_ex.h>
#include <vcl/uitest/uiobject.hxx>
#include <vcl/jsdialog/executor.hxx>
// Needed for getUndoManager()
#include <com/sun/star/document/XUndoManager.hpp>
#include <com/sun/star/document/XUndoManagerSupplier.hpp>
#include <editeng/sizeitem.hxx>
#include <svx/rulritem.hxx>
#include <svx/pageitem.hxx>
#include <app.hxx>
#include "../app/cmdlineargs.hxx"
// We also need to hackily be able to start the main libreoffice thread:
#include "../app/sofficemain.h"
#include "../app/officeipcthread.hxx"
#include <lib/init.hxx>
#include "lokinteractionhandler.hxx"
#include "lokclipboard.hxx"
#include <officecfg/Office/Impress.hxx>
using namespace css;
using namespace vcl;
using namespace desktop;
using namespace utl;
static LibLibreOffice_Impl *gImpl = nullptr;
static std::weak_ptr< LibreOfficeKitClass > gOfficeClass;
static std::weak_ptr< LibreOfficeKitDocumentClass > gDocumentClass;
static void SetLastExceptionMsg(const OUString& s = OUString())
{
SAL_WARN_IF(!s.isEmpty(), "lok", "lok exception '" + s + "'");
if (gImpl)
gImpl->maLastExceptionMsg = s;
}
namespace {
struct ExtensionMap
{
const char *extn;
const char *filterName;
};
}
const ExtensionMap aWriterExtensionMap[] =
{
{ "doc", "MS Word 97" },
{ "docm", "MS Word 2007 XML VBA" },
{ "docx", "MS Word 2007 XML" },
{ "fodt", "OpenDocument Text Flat XML" },
{ "html", "HTML (StarWriter)" },
{ "odt", "writer8" },
{ "ott", "writer8_template" },
{ "pdf", "writer_pdf_Export" },
{ "epub", "EPUB" },
{ "rtf", "Rich Text Format" },
{ "txt", "Text" },
{ "xhtml", "XHTML Writer File" },
{ "png", "writer_png_Export" },
{ nullptr, nullptr }
};
const ExtensionMap aCalcExtensionMap[] =
{
{ "csv", "Text - txt - csv (StarCalc)" },
{ "fods", "OpenDocument Spreadsheet Flat XML" },
{ "html", "HTML (StarCalc)" },
{ "ods", "calc8" },
{ "ots", "calc8_template" },
{ "pdf", "calc_pdf_Export" },
{ "xhtml", "XHTML Calc File" },
{ "xls", "MS Excel 97" },
{ "xlsm", "Calc MS Excel 2007 VBA XML" },
{ "xlsx", "Calc MS Excel 2007 XML" },
{ "png", "calc_png_Export" },
{ nullptr, nullptr }
};
const ExtensionMap aImpressExtensionMap[] =
{
{ "fodp", "OpenDocument Presentation Flat XML" },
{ "html", "impress_html_Export" },
{ "odg", "impress8_draw" },
{ "odp", "impress8" },
{ "otp", "impress8_template" },
{ "pdf", "impress_pdf_Export" },
{ "potm", "Impress MS PowerPoint 2007 XML Template" },
{ "pot", "MS PowerPoint 97 Vorlage" },
{ "pptm", "Impress MS PowerPoint 2007 XML VBA" },
{ "pptx", "Impress MS PowerPoint 2007 XML" },
{ "pps", "MS PowerPoint 97 Autoplay" },
{ "ppt", "MS PowerPoint 97" },
{ "svg", "impress_svg_Export" },
{ "xhtml", "XHTML Impress File" },
{ "png", "impress_png_Export"},
{ nullptr, nullptr }
};
const ExtensionMap aDrawExtensionMap[] =
{
{ "fodg", "draw_ODG_FlatXML" },
{ "html", "draw_html_Export" },
{ "odg", "draw8" },
{ "pdf", "draw_pdf_Export" },
{ "svg", "draw_svg_Export" },
{ "xhtml", "XHTML Draw File" },
{ "png", "draw_png_Export"},
{ nullptr, nullptr }
};
static OUString getUString(const char* pString)
{
if (pString == nullptr)
return OUString();
OString sString(pString, strlen(pString));
return OStringToOUString(sString, RTL_TEXTENCODING_UTF8);
}
// Tolerate embedded \0s etc.
static char *convertOString(const OString &rStr)
{
char* pMemory = static_cast<char*>(malloc(rStr.getLength() + 1));
assert(pMemory); // don't tolerate failed allocations.
memcpy(pMemory, rStr.getStr(), rStr.getLength() + 1);
return pMemory;
}
static char *convertOUString(const OUString &aStr)
{
return convertOString(OUStringToOString(aStr, RTL_TEXTENCODING_UTF8));
}
/// Try to convert a relative URL to an absolute one, unless it already looks like a URL.
static OUString getAbsoluteURL(const char* pURL)
{
OUString aURL(getUString(pURL));
if (aURL.isEmpty())
return aURL;
// convert relative paths to absolute ones
OUString aWorkingDir;
osl_getProcessWorkingDir(&aWorkingDir.pData);
if (!aWorkingDir.endsWith("/"))
aWorkingDir += "/";
try
{
return rtl::Uri::convertRelToAbs(aWorkingDir, aURL);
}
catch (const rtl::MalformedUriException &)
{
}
return OUString();
}
static uno::Any jsonToUnoAny(const boost::property_tree::ptree& aTree)
{
uno::Any aAny;
uno::Any aValue;
sal_Int32 nFields;
uno::Reference< reflection::XIdlField > aField;
boost::property_tree::ptree aNodeNull, aNodeValue, aNodeField;
const std::string& rType = aTree.get<std::string>("type", "");
const std::string& rValue = aTree.get<std::string>("value", "");
uno::Sequence< uno::Reference< reflection::XIdlField > > aFields;
uno::Reference< reflection:: XIdlClass > xIdlClass =
css::reflection::theCoreReflection::get(comphelper::getProcessComponentContext())->forName(OUString::fromUtf8(rType.c_str()));
if (xIdlClass.is())
{
uno::TypeClass aTypeClass = xIdlClass->getTypeClass();
xIdlClass->createObject(aAny);
aFields = xIdlClass->getFields();
nFields = aFields.getLength();
aNodeValue = aTree.get_child("value", aNodeNull);
if (nFields > 0 && aNodeValue != aNodeNull)
{
for (sal_Int32 itField = 0; itField < nFields; ++itField)
{
aField = aFields[itField];
aNodeField = aNodeValue.get_child(aField->getName().toUtf8().getStr(), aNodeNull);
if (aNodeField != aNodeNull)
{
aValue = jsonToUnoAny(aNodeField);
aField->set(aAny, aValue);
}
}
}
else if (!rValue.empty())
{
if (aTypeClass == uno::TypeClass_VOID)
aAny.clear();
else if (aTypeClass == uno::TypeClass_BYTE)
aAny <<= static_cast<sal_Int8>(OString(rValue.c_str()).toInt32());
else if (aTypeClass == uno::TypeClass_BOOLEAN)
aAny <<= OString(rValue.c_str()).toBoolean();
else if (aTypeClass == uno::TypeClass_SHORT)
aAny <<= static_cast<sal_Int16>(OString(rValue.c_str()).toInt32());
else if (aTypeClass == uno::TypeClass_UNSIGNED_SHORT)
aAny <<= static_cast<sal_uInt16>(OString(rValue.c_str()).toUInt32());
else if (aTypeClass == uno::TypeClass_LONG)
aAny <<= OString(rValue.c_str()).toInt32();
else if (aTypeClass == uno::TypeClass_UNSIGNED_LONG)
aAny <<= static_cast<sal_uInt32>(OString(rValue.c_str()).toInt32());
else if (aTypeClass == uno::TypeClass_FLOAT)
aAny <<= OString(rValue.c_str()).toFloat();
else if (aTypeClass == uno::TypeClass_DOUBLE)
aAny <<= OString(rValue.c_str()).toDouble();
else if (aTypeClass == uno::TypeClass_STRING)
aAny <<= OUString::fromUtf8(rValue.c_str());
}
}
return aAny;
}
std::vector<beans::PropertyValue> desktop::jsonToPropertyValuesVector(const char* pJSON)
{
std::vector<beans::PropertyValue> aArguments;
if (pJSON && pJSON[0] != '\0')
{
boost::property_tree::ptree aTree, aNodeNull, aNodeValue;
std::stringstream aStream(pJSON);
boost::property_tree::read_json(aStream, aTree);
for (const auto& rPair : aTree)
{
const std::string& rType = rPair.second.get<std::string>("type", "");
const std::string& rValue = rPair.second.get<std::string>("value", "");
beans::PropertyValue aValue;
aValue.Name = OUString::fromUtf8(rPair.first.c_str());
if (rType == "string")
aValue.Value <<= OUString::fromUtf8(rValue.c_str());
else if (rType == "boolean")
aValue.Value <<= OString(rValue.c_str()).toBoolean();
else if (rType == "float")
aValue.Value <<= OString(rValue.c_str()).toFloat();
else if (rType == "long")
aValue.Value <<= OString(rValue.c_str()).toInt32();
else if (rType == "short")
aValue.Value <<= sal_Int16(OString(rValue.c_str()).toInt32());
else if (rType == "unsigned short")
aValue.Value <<= sal_uInt16(OString(rValue.c_str()).toUInt32());
else if (rType == "int64")
aValue.Value <<= OString(rValue.c_str()).toInt64();
else if (rType == "int32")
aValue.Value <<= OString(rValue.c_str()).toInt32();
else if (rType == "int16")
aValue.Value <<= sal_Int16(OString(rValue.c_str()).toInt32());
else if (rType == "uint64")
aValue.Value <<= OString(rValue.c_str()).toUInt64();
else if (rType == "uint32")
aValue.Value <<= OString(rValue.c_str()).toUInt32();
else if (rType == "uint16")
aValue.Value <<= sal_uInt16(OString(rValue.c_str()).toUInt32());
else if (rType == "[]byte")
{
aNodeValue = rPair.second.get_child("value", aNodeNull);
if (aNodeValue != aNodeNull && aNodeValue.size() == 0)
{
uno::Sequence< sal_Int8 > aSeqByte(reinterpret_cast<const sal_Int8*>(rValue.c_str()), rValue.size());
aValue.Value <<= aSeqByte;
}
}
else if (rType == "[]any")
{
aNodeValue = rPair.second.get_child("value", aNodeNull);
if (aNodeValue != aNodeNull && !aNodeValue.empty())
{
sal_Int32 itSeq = 0;
uno::Sequence< uno::Any > aSeq(aNodeValue.size());
for (const auto& rSeqPair : aNodeValue)
aSeq[itSeq++] = jsonToUnoAny(rSeqPair.second);
aValue.Value <<= aSeq;
}
}
else
SAL_WARN("desktop.lib", "jsonToPropertyValuesVector: unhandled type '"<<rType<<"'");
aArguments.push_back(aValue);
}
}
return aArguments;
}
static StringMap jsonToStringMap(const char* pJSON)
{
StringMap aArgs;
if (pJSON && pJSON[0] != '\0')
{
std::stringstream aStream(pJSON);
boost::property_tree::ptree aTree;
boost::property_tree::read_json(aStream, aTree);
for (const auto& rPair : aTree)
{
aArgs[OUString::fromUtf8(rPair.first.c_str())] = OUString::fromUtf8(rPair.second.get_value<std::string>(".").c_str());
}
}
return aArgs;
}
static boost::property_tree::ptree unoAnyToPropertyTree(const uno::Any& anyItem)
{
boost::property_tree::ptree aTree;
OUString aType = anyItem.getValueTypeName();
aTree.put("type", aType.toUtf8().getStr());
if (aType == "string")
aTree.put("value", anyItem.get<OUString>().toUtf8().getStr());
else if (aType == "unsigned long")
aTree.put("value", OString::number(anyItem.get<sal_uInt32>()).getStr());
else if (aType == "long")
aTree.put("value", OString::number(anyItem.get<sal_Int32>()).getStr());
else if (aType == "[]any")
{
uno::Sequence<uno::Any> aSeq;
if (anyItem >>= aSeq)
{
boost::property_tree::ptree aSubTree;
for (auto i = 0; i < aSeq.getLength(); ++i)
{
aSubTree.add_child(OString::number(i).getStr(), unoAnyToPropertyTree(aSeq[i]));
}
aTree.add_child("value", aSubTree);
}
}
// TODO: Add more as required
return aTree;
}
namespace desktop {
RectangleAndPart RectangleAndPart::Create(const std::string& rPayload)
{
RectangleAndPart aRet;
if (rPayload.compare(0, 5, "EMPTY") == 0) // payload starts with "EMPTY"
{
aRet.m_aRectangle = tools::Rectangle(0, 0, SfxLokHelper::MaxTwips, SfxLokHelper::MaxTwips);
if (comphelper::LibreOfficeKit::isPartInInvalidation())
aRet.m_nPart = std::stol(rPayload.substr(6));
return aRet;
}
std::istringstream aStream(rPayload);
tools::Long nLeft, nTop, nWidth, nHeight;
tools::Long nPart = INT_MIN;
char nComma;
if (comphelper::LibreOfficeKit::isPartInInvalidation())
{
aStream >> nLeft >> nComma >> nTop >> nComma >> nWidth >> nComma >> nHeight >> nComma >> nPart;
}
else
{
aStream >> nLeft >> nComma >> nTop >> nComma >> nWidth >> nComma >> nHeight;
}
if (nWidth > 0 && nHeight > 0)
{
// The top-left corner starts at (0, 0).
// Anything negative is invalid.
if (nLeft < 0)
{
nWidth += nLeft;
nLeft = 0;
}
if (nTop < 0)
{
nHeight += nTop;
nTop = 0;
}
if (nWidth > 0 && nHeight > 0)
{
aRet.m_aRectangle = tools::Rectangle(nLeft, nTop, nLeft + nWidth, nTop + nHeight);
}
}
// else leave empty rect.
aRet.m_nPart = nPart;
return aRet;
}
RectangleAndPart& CallbackFlushHandler::CallbackData::setRectangleAndPart(const std::string& payload)
{
setRectangleAndPart(RectangleAndPart::Create(payload));
// Return reference to the cached object.
return boost::get<RectangleAndPart>(PayloadObject);
}
void CallbackFlushHandler::CallbackData::setRectangleAndPart(const RectangleAndPart& rRectAndPart)
{
PayloadString = rRectAndPart.toString().getStr();
PayloadObject = rRectAndPart;
}
const RectangleAndPart& CallbackFlushHandler::CallbackData::getRectangleAndPart() const
{
assert(PayloadObject.which() == 1);
return boost::get<RectangleAndPart>(PayloadObject);
}
boost::property_tree::ptree& CallbackFlushHandler::CallbackData::setJson(const std::string& payload)
{
boost::property_tree::ptree aTree;
std::stringstream aStream(payload);
boost::property_tree::read_json(aStream, aTree);
// Let boost normalize the payload so it always matches the cache.
setJson(aTree);
// Return reference to the cached object.
return boost::get<boost::property_tree::ptree>(PayloadObject);
}
void CallbackFlushHandler::CallbackData::setJson(const boost::property_tree::ptree& rTree)
{
std::stringstream aJSONStream;
constexpr bool bPretty = false; // Don't waste time and bloat logs.
boost::property_tree::write_json(aJSONStream, rTree, bPretty);
PayloadString = boost::trim_copy(aJSONStream.str());
PayloadObject = rTree;
}
const boost::property_tree::ptree& CallbackFlushHandler::CallbackData::getJson() const
{
assert(PayloadObject.which() == 2);
return boost::get<boost::property_tree::ptree>(PayloadObject);
}
bool CallbackFlushHandler::CallbackData::validate() const
{
switch (PayloadObject.which())
{
// Not cached.
case 0:
return true;
// RectangleAndPart.
case 1:
return getRectangleAndPart().toString().getStr() == PayloadString;
// Json.
case 2:
{
std::stringstream aJSONStream;
boost::property_tree::write_json(aJSONStream, getJson(), false);
const std::string aExpected = boost::trim_copy(aJSONStream.str());
return aExpected == PayloadString;
}
default:
assert(!"Unknown variant type; please add an entry to validate.");
}
return false;
}
}
namespace {
bool lcl_isViewCallbackType(const int type)
{
switch (type)
{
case LOK_CALLBACK_CELL_VIEW_CURSOR:
case LOK_CALLBACK_GRAPHIC_VIEW_SELECTION:
case LOK_CALLBACK_INVALIDATE_VIEW_CURSOR:
case LOK_CALLBACK_TEXT_VIEW_SELECTION:
case LOK_CALLBACK_VIEW_CURSOR_VISIBLE:
return true;
default:
return false;
}
}
int lcl_getViewId(const std::string& payload)
{
// this is a cheap way how to get the viewId from a JSON message; proper
// parsing is terribly expensive, and we just need the viewId here
size_t viewIdPos = payload.find("viewId");
if (viewIdPos == std::string::npos)
return 0;
size_t numberPos = payload.find(":", viewIdPos + 6);
if (numberPos == std::string::npos)
return 0;
for (++numberPos; numberPos < payload.length(); ++numberPos)
{
if (payload[numberPos] == ',' || payload[numberPos] == '}' || (payload[numberPos] >= '0' && payload[numberPos] <= '9'))
break;
}
if (numberPos < payload.length() && payload[numberPos] >= '0' && payload[numberPos] <= '9')
return strtol(payload.substr(numberPos).c_str(), nullptr, 10);
return 0;
}
int lcl_getViewId(const desktop::CallbackFlushHandler::CallbackData& rCallbackData)
{
if (rCallbackData.isCached())
return rCallbackData.getJson().get<int>("viewId");
return lcl_getViewId(rCallbackData.PayloadString);
}
std::string extractCertificate(const std::string & certificate)
{
const std::string header("-----BEGIN CERTIFICATE-----");
const std::string footer("-----END CERTIFICATE-----");
std::string result;
size_t pos1 = certificate.find(header);
if (pos1 == std::string::npos)
return result;
size_t pos2 = certificate.find(footer, pos1 + 1);
if (pos2 == std::string::npos)
return result;
pos1 = pos1 + header.length();
pos2 = pos2 - pos1;
return certificate.substr(pos1, pos2);
}
std::string extractPrivateKey(const std::string & privateKey)
{
const std::string header("-----BEGIN PRIVATE KEY-----");
const std::string footer("-----END PRIVATE KEY-----");
std::string result;
size_t pos1 = privateKey.find(header);
if (pos1 == std::string::npos)
return result;
size_t pos2 = privateKey.find(footer, pos1 + 1);
if (pos2 == std::string::npos)
return result;
pos1 = pos1 + header.length();
pos2 = pos2 - pos1;
return privateKey.substr(pos1, pos2);
}
OUString lcl_getCurrentDocumentMimeType(const LibLODocument_Impl* pDocument)
{
SfxBaseModel* pBaseModel = dynamic_cast<SfxBaseModel*>(pDocument->mxComponent.get());
if (!pBaseModel)
return "";
SfxObjectShell* pObjectShell = pBaseModel->GetObjectShell();
if (!pObjectShell)
return "";
SfxMedium* pMedium = pObjectShell->GetMedium();
if (!pMedium)
return "";
auto pFilter = pMedium->GetFilter();
if (!pFilter)
return "";
return pFilter->GetMimeType();
}
// Gets an undo manager to enter and exit undo context. Needed by ToggleOrientation
css::uno::Reference< css::document::XUndoManager > getUndoManager( const css::uno::Reference< css::frame::XFrame >& rxFrame )
{
const css::uno::Reference< css::frame::XController >& xController = rxFrame->getController();
if ( xController.is() )
{
const css::uno::Reference< css::frame::XModel >& xModel = xController->getModel();
if ( xModel.is() )
{
const css::uno::Reference< css::document::XUndoManagerSupplier > xSuppUndo( xModel, css::uno::UNO_QUERY_THROW );
return css::uno::Reference< css::document::XUndoManager >( xSuppUndo->getUndoManager(), css::uno::UNO_SET_THROW );
}
}
return css::uno::Reference< css::document::XUndoManager > ();
}
// Adjusts page margins for Writer doc. Needed by ToggleOrientation
void ExecuteMarginLRChange(
const tools::Long nPageLeftMargin,
const tools::Long nPageRightMargin,
SvxLongLRSpaceItem* pPageLRMarginItem)
{
pPageLRMarginItem->SetLeft( nPageLeftMargin );
pPageLRMarginItem->SetRight( nPageRightMargin );
SfxViewShell::Current()->GetDispatcher()->ExecuteList(SID_ATTR_PAGE_LRSPACE,
SfxCallMode::RECORD, { pPageLRMarginItem });
}
// Adjusts page margins for Writer doc. Needed by ToggleOrientation
void ExecuteMarginULChange(
const tools::Long nPageTopMargin,
const tools::Long nPageBottomMargin,
SvxLongULSpaceItem* pPageULMarginItem)
{
pPageULMarginItem->SetUpper( nPageTopMargin );
pPageULMarginItem->SetLower( nPageBottomMargin );
SfxViewShell::Current()->GetDispatcher()->ExecuteList(SID_ATTR_PAGE_ULSPACE,
SfxCallMode::RECORD, { pPageULMarginItem });
}
// Main function which toggles page orientation of the Writer doc. Needed by ToggleOrientation
void ExecuteOrientationChange()
{
std::unique_ptr<SvxPageItem> pPageItem(new SvxPageItem(SID_ATTR_PAGE));
std::unique_ptr<SvxSizeItem> pPageSizeItem(new SvxSizeItem(SID_ATTR_PAGE_SIZE));
std::unique_ptr<SvxLongLRSpaceItem> pPageLRMarginItem(new SvxLongLRSpaceItem( 0, 0, SID_ATTR_PAGE_LRSPACE ));
std::unique_ptr<SvxLongULSpaceItem> pPageULMarginItem(new SvxLongULSpaceItem( 0, 0, SID_ATTR_PAGE_ULSPACE ));
// 1mm in twips rounded
// This should be in sync with MINBODY in sw/source/uibase/sidebar/PageMarginControl.hxx
constexpr tools::Long MINBODY = 56;
css::uno::Reference< css::document::XUndoManager > mxUndoManager(
getUndoManager( SfxViewFrame::Current()->GetFrame().GetFrameInterface() ) );
if ( mxUndoManager.is() )
mxUndoManager->enterUndoContext( "" );
const SfxPoolItem* pItem;
SfxViewFrame::Current()->GetBindings().GetDispatcher()->QueryState(SID_ATTR_PAGE_SIZE, pItem);
pPageSizeItem.reset( static_cast<SvxSizeItem*>(pItem->Clone()) );
SfxViewFrame::Current()->GetBindings().GetDispatcher()->QueryState(SID_ATTR_PAGE_LRSPACE, pItem);
pPageLRMarginItem.reset( static_cast<SvxLongLRSpaceItem*>(pItem->Clone()) );
SfxViewFrame::Current()->GetBindings().GetDispatcher()->QueryState(SID_ATTR_PAGE_ULSPACE, pItem);
pPageULMarginItem.reset( static_cast<SvxLongULSpaceItem*>(pItem->Clone()) );
{
bool bIsLandscape = false;
if ( pPageSizeItem->GetSize().Width() > pPageSizeItem->GetSize().Height())
bIsLandscape = true;
// toggle page orientation
pPageItem->SetLandscape(!bIsLandscape);
// swap the width and height of the page size
const tools::Long nRotatedWidth = pPageSizeItem->GetSize().Height();
const tools::Long nRotatedHeight = pPageSizeItem->GetSize().Width();
pPageSizeItem->SetSize(Size(nRotatedWidth, nRotatedHeight));
// apply changed attributes
if (SfxViewShell::Current())
{
SfxViewShell::Current()->GetDispatcher()->ExecuteList(SID_ATTR_PAGE_SIZE,
SfxCallMode::RECORD, { pPageSizeItem.get(), pPageItem.get() });
}
}
// check, if margin values still fit to the changed page size.
// if not, adjust margin values
{
const tools::Long nML = pPageLRMarginItem->GetLeft();
const tools::Long nMR = pPageLRMarginItem->GetRight();
const tools::Long nTmpPW = nML + nMR + MINBODY;
const tools::Long nPW = pPageSizeItem->GetSize().Width();
if ( nTmpPW > nPW )
{
if ( nML <= nMR )
{
ExecuteMarginLRChange( pPageLRMarginItem->GetLeft(), nMR - (nTmpPW - nPW ), pPageLRMarginItem.get() );
}
else
{
ExecuteMarginLRChange( nML - (nTmpPW - nPW ), pPageLRMarginItem->GetRight(), pPageLRMarginItem.get() );
}
}
const tools::Long nMT = pPageULMarginItem->GetUpper();
const tools::Long nMB = pPageULMarginItem->GetLower();
const tools::Long nTmpPH = nMT + nMB + MINBODY;
const tools::Long nPH = pPageSizeItem->GetSize().Height();
if ( nTmpPH > nPH )
{
if ( nMT <= nMB )
{
ExecuteMarginULChange( pPageULMarginItem->GetUpper(), nMB - ( nTmpPH - nPH ), pPageULMarginItem.get() );
}
else
{
ExecuteMarginULChange( nMT - ( nTmpPH - nPH ), pPageULMarginItem->GetLower(), pPageULMarginItem.get() );
}
}
}
if ( mxUndoManager.is() )
mxUndoManager->leaveUndoContext();
}
void setupSidebar(const OUString& sidebarDeckId = "")
{
SfxViewShell* pViewShell = SfxViewShell::Current();
SfxViewFrame* pViewFrame = pViewShell ? pViewShell->GetViewFrame() : nullptr;
if (pViewFrame)
{
if (!pViewFrame->GetChildWindow(SID_SIDEBAR))
pViewFrame->SetChildWindow(SID_SIDEBAR, false /* create it */, true /* focus */);
pViewFrame->ShowChildWindow(SID_SIDEBAR, true);
// Force synchronous population of panels
SfxChildWindow *pChild = pViewFrame->GetChildWindow(SID_SIDEBAR);
if (!pChild)
return;
auto pDockingWin = dynamic_cast<sfx2::sidebar::SidebarDockingWindow *>(pChild->GetWindow());
if (!pDockingWin)
return;
OUString currentDeckId = pDockingWin->GetSidebarController()->GetCurrentDeckId();
// check if it is the chart deck id, if it is, don't switch to default deck
bool switchToDefault = true;
if (currentDeckId == "ChartDeck")
switchToDefault = false;
if (!sidebarDeckId.isEmpty())
{
pDockingWin->GetSidebarController()->SwitchToDeck(sidebarDeckId);
}
else
{
if (switchToDefault)
pDockingWin->GetSidebarController()->SwitchToDefaultDeck();
}
pDockingWin->SyncUpdate();
}
else
SetLastExceptionMsg("No view shell or sidebar");
}
void hideSidebar()
{
SfxViewShell* pViewShell = SfxViewShell::Current();
SfxViewFrame* pViewFrame = pViewShell? pViewShell->GetViewFrame(): nullptr;
if (pViewFrame)
pViewFrame->SetChildWindow(SID_SIDEBAR, false , false );
else
SetLastExceptionMsg("No view shell or sidebar");
}
VclPtr<Window> getSidebarWindow()
{
VclPtr<Window> xRet;
setupSidebar();
SfxViewShell* pViewShell = SfxViewShell::Current();
SfxViewFrame* pViewFrame = pViewShell? pViewShell->GetViewFrame(): nullptr;
if (!pViewFrame)
return xRet;
// really a SidebarChildWindow
SfxChildWindow *pChild = pViewFrame->GetChildWindow(SID_SIDEBAR);
if (!pChild)
return xRet;
// really a SidebarDockingWindow
vcl::Window *pWin = pChild->GetWindow();
if (!pWin)
return xRet;
xRet = pWin;
return xRet;
}
} // end anonymous namespace
// Could be anonymous in principle, but for the unit testing purposes, we
// declare it in init.hxx.
OUString desktop::extractParameter(OUString& rOptions, const OUString& rName)
{
OUString aValue;
OUString aNameEquals(rName + "=");
OUString aCommaNameEquals("," + rName + "=");
int nIndex = -1;
if (rOptions.startsWith(aNameEquals))
{
size_t nLen = aNameEquals.getLength();
int nComma = rOptions.indexOf(",", nLen);
if (nComma >= 0)
{
aValue = rOptions.copy(nLen, nComma - nLen);
rOptions = rOptions.copy(nComma + 1);
}
else
{
aValue = rOptions.copy(nLen);
rOptions.clear();
}
}
else if ((nIndex = rOptions.indexOf(aCommaNameEquals)) >= 0)
{
size_t nLen = aCommaNameEquals.getLength();
int nComma = rOptions.indexOf(",", nIndex + nLen);
if (nComma >= 0)
{
aValue = rOptions.copy(nIndex + nLen, nComma - nIndex - nLen);
rOptions = rOptions.copy(0, nIndex) + rOptions.copy(nComma);
}
else
{
aValue = rOptions.copy(nIndex + nLen);
rOptions = rOptions.copy(0, nIndex);
}
}
return aValue;
}
extern "C"
{
static void doc_destroy(LibreOfficeKitDocument* pThis);
static int doc_saveAs(LibreOfficeKitDocument* pThis, const char* pUrl, const char* pFormat, const char* pFilterOptions);
static int doc_getDocumentType(LibreOfficeKitDocument* pThis);
static int doc_getParts(LibreOfficeKitDocument* pThis);
static char* doc_getPartPageRectangles(LibreOfficeKitDocument* pThis);
static int doc_getPart(LibreOfficeKitDocument* pThis);
static void doc_setPart(LibreOfficeKitDocument* pThis, int nPart);
static void doc_selectPart(LibreOfficeKitDocument* pThis, int nPart, int nSelect);
static void doc_moveSelectedParts(LibreOfficeKitDocument* pThis, int nPosition, bool bDuplicate);
static char* doc_getPartName(LibreOfficeKitDocument* pThis, int nPart);
static void doc_setPartMode(LibreOfficeKitDocument* pThis, int nPartMode);
static void doc_paintTile(LibreOfficeKitDocument* pThis,
unsigned char* pBuffer,
const int nCanvasWidth, const int nCanvasHeight,
const int nTilePosX, const int nTilePosY,
const int nTileWidth, const int nTileHeight);
#ifdef IOS
static void doc_paintTileToCGContext(LibreOfficeKitDocument* pThis,
void* rCGContext,
const int nCanvasWidth, const int nCanvasHeight,
const int nTilePosX, const int nTilePosY,
const int nTileWidth, const int nTileHeight);
#endif
static void doc_paintPartTile(LibreOfficeKitDocument* pThis,
unsigned char* pBuffer,
const int nPart,
const int nCanvasWidth, const int nCanvasHeight,
const int nTilePosX, const int nTilePosY,
const int nTileWidth, const int nTileHeight);
static int doc_getTileMode(LibreOfficeKitDocument* pThis);
static void doc_getDocumentSize(LibreOfficeKitDocument* pThis,
long* pWidth,
long* pHeight);
static void doc_initializeForRendering(LibreOfficeKitDocument* pThis,
const char* pArguments);
static void doc_registerCallback(LibreOfficeKitDocument* pThis,
LibreOfficeKitCallback pCallback,
void* pData);
static void doc_postKeyEvent(LibreOfficeKitDocument* pThis,
int nType,
int nCharCode,
int nKeyCode);
static void doc_postWindowExtTextInputEvent(LibreOfficeKitDocument* pThis,
unsigned nWindowId,
int nType,
const char* pText);
static void doc_removeTextContext(LibreOfficeKitDocument* pThis,
unsigned nLOKWindowId,
int nCharBefore,
int nCharAfter);
static void doc_sendDialogEvent(LibreOfficeKitDocument* pThis,
unsigned long long int nLOKWindowId,
const char* pArguments);
static void doc_postWindowKeyEvent(LibreOfficeKitDocument* pThis,
unsigned nLOKWindowId,
int nType,
int nCharCode,
int nKeyCode);
static void doc_postMouseEvent (LibreOfficeKitDocument* pThis,
int nType,
int nX,
int nY,
int nCount,
int nButtons,
int nModifier);
static void doc_postWindowMouseEvent (LibreOfficeKitDocument* pThis,
unsigned nLOKWindowId,
int nType,
int nX,
int nY,
int nCount,
int nButtons,
int nModifier);
static void doc_postWindowGestureEvent(LibreOfficeKitDocument* pThis,
unsigned nLOKWindowId,
const char* pType,
int nX,
int nY,
int nOffset);
static void doc_postUnoCommand(LibreOfficeKitDocument* pThis,
const char* pCommand,
const char* pArguments,
bool bNotifyWhenFinished);
static void doc_setWindowTextSelection(LibreOfficeKitDocument* pThis,
unsigned nLOKWindowId,
bool swap,
int nX,
int nY);
static void doc_setTextSelection (LibreOfficeKitDocument* pThis,
int nType,
int nX,
int nY);
static char* doc_getTextSelection(LibreOfficeKitDocument* pThis,
const char* pMimeType,
char** pUsedMimeType);
static int doc_getSelectionType(LibreOfficeKitDocument* pThis);
static int doc_getClipboard (LibreOfficeKitDocument* pThis,
const char **pMimeTypes,
size_t *pOutCount,
char ***pOutMimeTypes,
size_t **pOutSizes,
char ***pOutStreams);
static int doc_setClipboard (LibreOfficeKitDocument* pThis,
const size_t nInCount,
const char **pInMimeTypes,
const size_t *pInSizes,
const char **pInStreams);
static bool doc_paste(LibreOfficeKitDocument* pThis,
const char* pMimeType,
const char* pData,
size_t nSize);
static void doc_setGraphicSelection (LibreOfficeKitDocument* pThis,
int nType,
int nX,
int nY);
static void doc_resetSelection (LibreOfficeKitDocument* pThis);
static char* doc_getCommandValues(LibreOfficeKitDocument* pThis, const char* pCommand);
static void doc_setClientZoom(LibreOfficeKitDocument* pThis,
int nTilePixelWidth,
int nTilePixelHeight,
int nTileTwipWidth,
int nTileTwipHeight);
static void doc_setClientVisibleArea(LibreOfficeKitDocument* pThis, int nX, int nY, int nWidth, int nHeight);
static void doc_setOutlineState(LibreOfficeKitDocument* pThis, bool bColumn, int nLevel, int nIndex, bool bHidden);
static int doc_createView(LibreOfficeKitDocument* pThis);
static int doc_createViewWithOptions(LibreOfficeKitDocument* pThis, const char* pOptions);
static void doc_destroyView(LibreOfficeKitDocument* pThis, int nId);
static void doc_setView(LibreOfficeKitDocument* pThis, int nId);
static int doc_getView(LibreOfficeKitDocument* pThis);
static int doc_getViewsCount(LibreOfficeKitDocument* pThis);
static bool doc_getViewIds(LibreOfficeKitDocument* pThis, int* pArray, size_t nSize);
static void doc_setViewLanguage(LibreOfficeKitDocument* pThis, int nId, const char* language);
static unsigned char* doc_renderFontOrientation(LibreOfficeKitDocument* pThis,
const char *pFontName,
const char *pChar,
int* pFontWidth,
int* pFontHeight,
int pOrientation);
static unsigned char* doc_renderFont(LibreOfficeKitDocument* pThis,
const char *pFontName,
const char *pChar,
int* pFontWidth,
int* pFontHeight);
static char* doc_getPartHash(LibreOfficeKitDocument* pThis, int nPart);
static void doc_paintWindow(LibreOfficeKitDocument* pThis, unsigned nLOKWindowId, unsigned char* pBuffer,
const int nX, const int nY,
const int nWidth, const int nHeight);
static void doc_paintWindowDPI(LibreOfficeKitDocument* pThis, unsigned nLOKWindowId, unsigned char* pBuffer,
const int nX, const int nY,
const int nWidth, const int nHeight,
const double fDPIScale);
static void doc_paintWindowForView(LibreOfficeKitDocument* pThis, unsigned nLOKWindowId, unsigned char* pBuffer,
const int nX, const int nY,
const int nWidth, const int nHeight,
const double fDPIScale, int viewId);
static void doc_postWindow(LibreOfficeKitDocument* pThis, unsigned
nLOKWindowId, int nAction, const char* pData);
static char* doc_getPartInfo(LibreOfficeKitDocument* pThis, int nPart);
static bool doc_insertCertificate(LibreOfficeKitDocument* pThis,
const unsigned char* pCertificateBinary,
const int nCertificateBinarySize,
const unsigned char* pPrivateKeyBinary,
const int nPrivateKeyBinarySize);
static bool doc_addCertificate(LibreOfficeKitDocument* pThis,
const unsigned char* pCertificateBinary,
const int nCertificateBinarySize);
static int doc_getSignatureState(LibreOfficeKitDocument* pThis);
static size_t doc_renderShapeSelection(LibreOfficeKitDocument* pThis, char** pOutput);
static void doc_resizeWindow(LibreOfficeKitDocument* pThis, unsigned nLOKWindowId,
const int nWidth, const int nHeight);
static void doc_completeFunction(LibreOfficeKitDocument* pThis, const char*);
static void doc_sendFormFieldEvent(LibreOfficeKitDocument* pThis,
const char* pArguments);
} // extern "C"
namespace {
ITiledRenderable* getTiledRenderable(LibreOfficeKitDocument* pThis)
{
LibLODocument_Impl* pDocument = static_cast<LibLODocument_Impl*>(pThis);
return dynamic_cast<ITiledRenderable*>(pDocument->mxComponent.get());
}
#ifndef IOS
/*
* Unfortunately clipboard creation using UNO is insanely baroque.
* we also need to ensure that this works for the first view which
* has no clear 'createView' called for it (unfortunately).
*/
rtl::Reference<LOKClipboard> forceSetClipboardForCurrentView(LibreOfficeKitDocument *pThis)
{
ITiledRenderable* pDoc = getTiledRenderable(pThis);
rtl::Reference<LOKClipboard> xClip(LOKClipboardFactory::getClipboardForCurView());
SAL_INFO("lok", "Set to clipboard for view " << xClip.get());
// FIXME: using a hammer here - should not be necessary if all tests used createView.
pDoc->setClipboard(uno::Reference<datatransfer::clipboard::XClipboard>(xClip->getXI(), UNO_QUERY));
return xClip;
}
#endif
} // anonymous namespace
LibLODocument_Impl::LibLODocument_Impl(const uno::Reference <css::lang::XComponent> &xComponent, int nDocumentId)
: mxComponent(xComponent)
, mnDocumentId(nDocumentId)
{
m_pDocumentClass = gDocumentClass.lock();
if (!m_pDocumentClass)
{
m_pDocumentClass = std::make_shared<LibreOfficeKitDocumentClass>();
m_pDocumentClass->nSize = sizeof(LibreOfficeKitDocumentClass);
m_pDocumentClass->destroy = doc_destroy;
m_pDocumentClass->saveAs = doc_saveAs;
m_pDocumentClass->getDocumentType = doc_getDocumentType;
m_pDocumentClass->getParts = doc_getParts;
m_pDocumentClass->getPartPageRectangles = doc_getPartPageRectangles;
m_pDocumentClass->getPart = doc_getPart;
m_pDocumentClass->setPart = doc_setPart;
m_pDocumentClass->selectPart = doc_selectPart;
m_pDocumentClass->moveSelectedParts = doc_moveSelectedParts;
m_pDocumentClass->getPartName = doc_getPartName;
m_pDocumentClass->setPartMode = doc_setPartMode;
m_pDocumentClass->paintTile = doc_paintTile;
#ifdef IOS
m_pDocumentClass->paintTileToCGContext = doc_paintTileToCGContext;
#endif
m_pDocumentClass->paintPartTile = doc_paintPartTile;
m_pDocumentClass->getTileMode = doc_getTileMode;
m_pDocumentClass->getDocumentSize = doc_getDocumentSize;
m_pDocumentClass->initializeForRendering = doc_initializeForRendering;
m_pDocumentClass->registerCallback = doc_registerCallback;
m_pDocumentClass->postKeyEvent = doc_postKeyEvent;
m_pDocumentClass->postWindowExtTextInputEvent = doc_postWindowExtTextInputEvent;
m_pDocumentClass->removeTextContext = doc_removeTextContext;
m_pDocumentClass->postWindowKeyEvent = doc_postWindowKeyEvent;
m_pDocumentClass->postMouseEvent = doc_postMouseEvent;
m_pDocumentClass->postWindowMouseEvent = doc_postWindowMouseEvent;
m_pDocumentClass->sendDialogEvent = doc_sendDialogEvent;
m_pDocumentClass->postUnoCommand = doc_postUnoCommand;
m_pDocumentClass->setTextSelection = doc_setTextSelection;
m_pDocumentClass->setWindowTextSelection = doc_setWindowTextSelection;
m_pDocumentClass->getTextSelection = doc_getTextSelection;
m_pDocumentClass->getSelectionType = doc_getSelectionType;
m_pDocumentClass->getClipboard = doc_getClipboard;
m_pDocumentClass->setClipboard = doc_setClipboard;
m_pDocumentClass->paste = doc_paste;
m_pDocumentClass->setGraphicSelection = doc_setGraphicSelection;
m_pDocumentClass->resetSelection = doc_resetSelection;
m_pDocumentClass->getCommandValues = doc_getCommandValues;
m_pDocumentClass->setClientZoom = doc_setClientZoom;
m_pDocumentClass->setClientVisibleArea = doc_setClientVisibleArea;
m_pDocumentClass->setOutlineState = doc_setOutlineState;
m_pDocumentClass->createView = doc_createView;
m_pDocumentClass->destroyView = doc_destroyView;
m_pDocumentClass->setView = doc_setView;
m_pDocumentClass->getView = doc_getView;
m_pDocumentClass->getViewsCount = doc_getViewsCount;
m_pDocumentClass->getViewIds = doc_getViewIds;
m_pDocumentClass->renderFont = doc_renderFont;
m_pDocumentClass->renderFontOrientation = doc_renderFontOrientation;
m_pDocumentClass->getPartHash = doc_getPartHash;
m_pDocumentClass->paintWindow = doc_paintWindow;
m_pDocumentClass->paintWindowDPI = doc_paintWindowDPI;
m_pDocumentClass->paintWindowForView = doc_paintWindowForView;
m_pDocumentClass->postWindow = doc_postWindow;
m_pDocumentClass->resizeWindow = doc_resizeWindow;
m_pDocumentClass->setViewLanguage = doc_setViewLanguage;
m_pDocumentClass->getPartInfo = doc_getPartInfo;
m_pDocumentClass->insertCertificate = doc_insertCertificate;
m_pDocumentClass->addCertificate = doc_addCertificate;
m_pDocumentClass->getSignatureState = doc_getSignatureState;
m_pDocumentClass->renderShapeSelection = doc_renderShapeSelection;
m_pDocumentClass->postWindowGestureEvent = doc_postWindowGestureEvent;
m_pDocumentClass->createViewWithOptions = doc_createViewWithOptions;
m_pDocumentClass->completeFunction = doc_completeFunction;
m_pDocumentClass->sendFormFieldEvent = doc_sendFormFieldEvent;
gDocumentClass = m_pDocumentClass;
}
pClass = m_pDocumentClass.get();
#ifndef IOS
forceSetClipboardForCurrentView(this);
#endif
}
LibLODocument_Impl::~LibLODocument_Impl()
{
try
{
mxComponent->dispose();
}
catch (const css::lang::DisposedException&)
{
TOOLS_WARN_EXCEPTION("lok", "failed to dispose document");
}
}
static OUString getGenerator()
{
OUString sGenerator(
Translate::ExpandVariables("%PRODUCTNAME %PRODUCTVERSION%PRODUCTEXTENSION (%1)"));
OUString os("$_OS");
::rtl::Bootstrap::expandMacros(os);
return sGenerator.replaceFirst("%1", os);
}
extern "C" {
CallbackFlushHandler::CallbackFlushHandler(LibreOfficeKitDocument* pDocument, LibreOfficeKitCallback pCallback, void* pData)
: Idle( "lokit timer callback" ),
m_pDocument(pDocument),
m_pCallback(pCallback),
m_pData(pData),
m_nDisableCallbacks(0)
{
SetPriority(TaskPriority::POST_PAINT);
// Add the states that are safe to skip duplicates on, even when
// not consequent (i.e. do no emit them if unchanged from last).
m_states.emplace(LOK_CALLBACK_TEXT_SELECTION, "NIL");
m_states.emplace(LOK_CALLBACK_GRAPHIC_SELECTION, "NIL");
m_states.emplace(LOK_CALLBACK_INVALIDATE_VISIBLE_CURSOR, "NIL");
m_states.emplace(LOK_CALLBACK_STATE_CHANGED, "NIL");
m_states.emplace(LOK_CALLBACK_MOUSE_POINTER, "NIL");
m_states.emplace(LOK_CALLBACK_CELL_CURSOR, "NIL");
m_states.emplace(LOK_CALLBACK_CELL_FORMULA, "NIL");
m_states.emplace(LOK_CALLBACK_CELL_ADDRESS, "NIL");
m_states.emplace(LOK_CALLBACK_CURSOR_VISIBLE, "NIL");
m_states.emplace(LOK_CALLBACK_SET_PART, "NIL");
Start();
}
CallbackFlushHandler::~CallbackFlushHandler()
{
Stop();
}
void CallbackFlushHandler::callback(const int type, const char* payload, void* data)
{
CallbackFlushHandler* self = static_cast<CallbackFlushHandler*>(data);
if (self)
{
self->queue(type, payload);
}
}
void CallbackFlushHandler::queue(const int type, const char* data)
{
comphelper::ProfileZone aZone("CallbackFlushHandler::queue");
CallbackData aCallbackData(type, (data ? data : "(nil)"));
const std::string& payload = aCallbackData.PayloadString;
SAL_INFO("lok", "Queue: [" << type << "]: [" << payload << "] on " << m_queue.size() << " entries.");
bool bIsChartActive = false;
if (type == LOK_CALLBACK_GRAPHIC_SELECTION)
{
LokChartHelper aChartHelper(SfxViewShell::Current());
bIsChartActive = aChartHelper.GetWindow() != nullptr;
}
if (callbacksDisabled() && !bIsChartActive)
{
// We drop notifications when this is set, except for important ones.
// When we issue a complex command (such as .uno:InsertAnnotation)
// there will be multiple notifications. On the first invalidation
// we will start painting, but other events will get fired
// while the complex command in question executes.
// We don't want to suppress everything here on the wrong assumption
// that no new events are fired during painting.
if (type != LOK_CALLBACK_STATE_CHANGED &&
type != LOK_CALLBACK_INVALIDATE_TILES &&
type != LOK_CALLBACK_INVALIDATE_VISIBLE_CURSOR &&
type != LOK_CALLBACK_CURSOR_VISIBLE &&
type != LOK_CALLBACK_VIEW_CURSOR_VISIBLE &&
type != LOK_CALLBACK_TEXT_SELECTION &&
type != LOK_CALLBACK_TEXT_SELECTION_START &&
type != LOK_CALLBACK_TEXT_SELECTION_END &&
type != LOK_CALLBACK_REFERENCE_MARKS)
{
SAL_INFO("lok", "Skipping while painting [" << type << "]: [" << payload << "].");
return;
}
// In Writer we drop all notifications during painting.
if (doc_getDocumentType(m_pDocument) == LOK_DOCTYPE_TEXT)
return;
}
// Suppress invalid payloads.
if (type == LOK_CALLBACK_INVALIDATE_VISIBLE_CURSOR &&
payload.find(", 0, 0, ") != std::string::npos)
{
// The cursor position is often the relative coordinates of the widget
// issuing it, instead of the absolute one that we expect.
// This is temporary however, and, once the control is created and initialized
// correctly, it eventually emits the correct absolute coordinates.
SAL_INFO("lok", "Skipping invalid event [" << type << "]: [" << payload << "].");
return;
}
std::unique_lock<std::mutex> lock(m_mutex);
// drop duplicate callbacks for the listed types
switch (type)
{
case LOK_CALLBACK_TEXT_SELECTION_START:
case LOK_CALLBACK_TEXT_SELECTION_END:
case LOK_CALLBACK_TEXT_SELECTION:
case LOK_CALLBACK_GRAPHIC_SELECTION:
case LOK_CALLBACK_GRAPHIC_VIEW_SELECTION:
case LOK_CALLBACK_INVALIDATE_VISIBLE_CURSOR:
case LOK_CALLBACK_INVALIDATE_VIEW_CURSOR:
case LOK_CALLBACK_STATE_CHANGED:
case LOK_CALLBACK_MOUSE_POINTER:
case LOK_CALLBACK_CELL_CURSOR:
case LOK_CALLBACK_CELL_VIEW_CURSOR:
case LOK_CALLBACK_CELL_FORMULA:
case LOK_CALLBACK_CELL_ADDRESS:
case LOK_CALLBACK_CURSOR_VISIBLE:
case LOK_CALLBACK_VIEW_CURSOR_VISIBLE:
case LOK_CALLBACK_SET_PART:
case LOK_CALLBACK_TEXT_VIEW_SELECTION:
case LOK_CALLBACK_INVALIDATE_HEADER:
case LOK_CALLBACK_WINDOW:
case LOK_CALLBACK_CALC_FUNCTION_LIST:
case LOK_CALLBACK_INVALIDATE_SHEET_GEOMETRY:
{
const auto& pos = std::find_if(m_queue.rbegin(), m_queue.rend(),
[type] (const queue_type::value_type& elem) { return (elem.Type == type); });
if (pos != m_queue.rend() && pos->PayloadString == payload)
{
SAL_INFO("lok", "Skipping queue duplicate [" << type << + "]: [" << payload << "].");
return;
}
}
break;
}
if (type == LOK_CALLBACK_TEXT_SELECTION && payload.empty())
{
const auto& posStart = std::find_if(m_queue.rbegin(), m_queue.rend(),
[] (const queue_type::value_type& elem) { return (elem.Type == LOK_CALLBACK_TEXT_SELECTION_START); });
if (posStart != m_queue.rend())
posStart->PayloadString.clear();
const auto& posEnd = std::find_if(m_queue.rbegin(), m_queue.rend(),
[] (const queue_type::value_type& elem) { return (elem.Type == LOK_CALLBACK_TEXT_SELECTION_END); });
if (posEnd != m_queue.rend())
posEnd->PayloadString.clear();
}
// When payload is empty discards any previous state.
if (payload.empty())
{
switch (type)
{
case LOK_CALLBACK_TEXT_SELECTION_START:
case LOK_CALLBACK_TEXT_SELECTION_END:
case LOK_CALLBACK_TEXT_SELECTION:
case LOK_CALLBACK_GRAPHIC_SELECTION:
case LOK_CALLBACK_INVALIDATE_VISIBLE_CURSOR:
case LOK_CALLBACK_INVALIDATE_TILES:
if (removeAll(
[type](const queue_type::value_type& elem) { return (elem.Type == type); }))
SAL_INFO("lok", "Removed dups of [" << type << "]: [" << payload << "].");
break;
}
}
else
{
switch (type)
{
// These are safe to use the latest state and ignore previous
// ones (if any) since the last overrides previous ones.
case LOK_CALLBACK_TEXT_SELECTION_START:
case LOK_CALLBACK_TEXT_SELECTION_END:
case LOK_CALLBACK_TEXT_SELECTION:
case LOK_CALLBACK_MOUSE_POINTER:
case LOK_CALLBACK_CELL_CURSOR:
case LOK_CALLBACK_CELL_FORMULA:
case LOK_CALLBACK_CELL_ADDRESS:
case LOK_CALLBACK_CURSOR_VISIBLE:
case LOK_CALLBACK_SET_PART:
case LOK_CALLBACK_STATUS_INDICATOR_SET_VALUE:
case LOK_CALLBACK_RULER_UPDATE:
{
if (removeAll(
[type](const queue_type::value_type& elem) { return (elem.Type == type); }))
SAL_INFO("lok", "Removed dups of [" << type << "]: [" << payload << "].");
}
break;
// These are safe to use the latest state and ignore previous
// ones (if any) since the last overrides previous ones,
// but only if the view is the same.
case LOK_CALLBACK_CELL_VIEW_CURSOR:
case LOK_CALLBACK_GRAPHIC_VIEW_SELECTION:
case LOK_CALLBACK_INVALIDATE_VIEW_CURSOR:
case LOK_CALLBACK_INVALIDATE_VISIBLE_CURSOR:
case LOK_CALLBACK_TEXT_VIEW_SELECTION:
case LOK_CALLBACK_VIEW_CURSOR_VISIBLE:
case LOK_CALLBACK_CALC_FUNCTION_LIST:
case LOK_CALLBACK_JSDIALOG:
{
// deleting the duplicate of visible cursor message can cause hyperlink popup not to show up on second/or more click on the same place.
// If the hyperlink is not empty we can bypass that to show the popup
const bool hyperLinkException = type == LOK_CALLBACK_INVALIDATE_VISIBLE_CURSOR &&
payload.find("\"hyperlink\":\"\"") == std::string::npos &&
payload.find("\"hyperlink\": {}") == std::string::npos;
const int nViewId = lcl_getViewId(payload);
removeAll(
[type, nViewId, hyperLinkException] (const queue_type::value_type& elem) {
return (elem.Type == type && nViewId == lcl_getViewId(elem) && !hyperLinkException);
}
);
}
break;
case LOK_CALLBACK_INVALIDATE_TILES:
if (processInvalidateTilesEvent(aCallbackData))
return;
break;
// State changes with same name override previous ones with a different value.
// Ex. ".uno:PageStatus=Slide 20 of 83" overwrites any previous PageStatus.
case LOK_CALLBACK_STATE_CHANGED:
{
// Compare the state name=value and overwrite earlier entries with same name.
const auto pos = payload.find('=');
if (pos != std::string::npos)
{
const std::string name = payload.substr(0, pos + 1);
// This is needed because otherwise it creates some problems when
// a save occurs while a cell is still edited in Calc.
if (name != ".uno:ModifiedStatus=")
{
removeAll(
[type, &name] (const queue_type::value_type& elem) {
return (elem.Type == type) && (elem.PayloadString.compare(0, name.size(), name) == 0);
}
);
}
}
}
break;
case LOK_CALLBACK_WINDOW:
if (processWindowEvent(aCallbackData))
return;
break;
case LOK_CALLBACK_GRAPHIC_SELECTION:
{
// remove only selection ranges and 'EMPTY' messages
// always send 'INPLACE' and 'INPLACE EXIT' messages
removeAll([type, payload] (const queue_type::value_type& elem)
{ return (elem.Type == type && elem.PayloadString[0] != 'I'); });
}
break;
}
}
// Validate that the cached data and the payload string are identical.
assert(aCallbackData.validate() && "Cached callback payload object and string mismatch!");
m_queue.emplace_back(aCallbackData);
SAL_INFO("lok", "Queued #" << (m_queue.size() - 1) <<
" [" << type << "]: [" << payload << "] to have " << m_queue.size() << " entries.");
#ifdef DBG_UTIL
{
// Dump the queue state and validate cached data.
int i = 1;
std::ostringstream oss;
if (m_queue.empty())
oss << "Empty";
else
oss << m_queue.size() << " items\n";
for (const CallbackData& c : m_queue)
oss << i++ << ": [" << c.Type << "] [" << c.PayloadString << "].\n";
SAL_INFO("lok", "Current Queue: " << oss.str());
assert(
std::all_of(
m_queue.begin(), m_queue.end(),
[](const CallbackData& c) { return c.validate(); }));
}
#endif
lock.unlock();
if (!IsActive())
{
Start();
}
}
bool CallbackFlushHandler::processInvalidateTilesEvent(CallbackData& aCallbackData)
{
const std::string& payload = aCallbackData.PayloadString;
const int type = aCallbackData.Type;
RectangleAndPart& rcNew = aCallbackData.setRectangleAndPart(payload);
if (rcNew.isEmpty())
{
SAL_INFO("lok", "Skipping invalid event [" << type << "]: [" << payload << "].");
return true;
}
// If we have to invalidate all tiles, we can skip any new tile invalidation.
// Find the last INVALIDATE_TILES entry, if any to see if it's invalidate-all.
const auto& pos
= std::find_if(m_queue.rbegin(), m_queue.rend(), [](const queue_type::value_type& elem) {
return (elem.Type == LOK_CALLBACK_INVALIDATE_TILES);
});
if (pos != m_queue.rend())
{
const RectangleAndPart& rcOld = pos->getRectangleAndPart();
if (rcOld.isInfinite() && (rcOld.m_nPart == -1 || rcOld.m_nPart == rcNew.m_nPart))
{
SAL_INFO("lok", "Skipping queue [" << type << "]: [" << payload
<< "] since all tiles need to be invalidated.");
return true;
}
if (rcOld.m_nPart == -1 || rcOld.m_nPart == rcNew.m_nPart)
{
// If fully overlapping.
if (rcOld.m_aRectangle.IsInside(rcNew.m_aRectangle))
{
SAL_INFO("lok", "Skipping queue [" << type << "]: [" << payload
<< "] since overlaps existing all-parts.");
return true;
}
}
}
if (rcNew.isInfinite())
{
SAL_INFO("lok", "Have Empty [" << type << "]: [" << payload
<< "] so removing all with part " << rcNew.m_nPart << ".");
removeAll([&rcNew](const queue_type::value_type& elem) {
if (elem.Type == LOK_CALLBACK_INVALIDATE_TILES)
{
// Remove exiting if new is all-encompassing, or if of the same part.
const RectangleAndPart rcOld = RectangleAndPart::Create(elem.PayloadString);
return (rcNew.m_nPart == -1 || rcOld.m_nPart == rcNew.m_nPart);
}
// Keep others.
return false;
});
}
else
{
const auto rcOrig = rcNew;
SAL_INFO("lok", "Have [" << type << "]: [" << payload << "] so merging overlapping.");
removeAll([&rcNew](const queue_type::value_type& elem) {
if (elem.Type == LOK_CALLBACK_INVALIDATE_TILES)
{
const RectangleAndPart& rcOld = elem.getRectangleAndPart();
if (rcNew.m_nPart != -1 && rcOld.m_nPart != -1 && rcOld.m_nPart != rcNew.m_nPart)
{
SAL_INFO("lok", "Nothing to merge between new: "
<< rcNew.toString() << ", and old: " << rcOld.toString());
return false;
}
if (rcNew.m_nPart == -1)
{
// Don't merge unless fully overlapped.
SAL_INFO("lok", "New " << rcNew.toString() << " has " << rcOld.toString()
<< "?");
if (rcNew.m_aRectangle.IsInside(rcOld.m_aRectangle))
{
SAL_INFO("lok", "New " << rcNew.toString() << " engulfs old "
<< rcOld.toString() << ".");
return true;
}
}
else if (rcOld.m_nPart == -1)
{
// Don't merge unless fully overlapped.
SAL_INFO("lok", "Old " << rcOld.toString() << " has " << rcNew.toString()
<< "?");
if (rcOld.m_aRectangle.IsInside(rcNew.m_aRectangle))
{
SAL_INFO("lok", "New " << rcNew.toString() << " engulfs old "
<< rcOld.toString() << ".");
return true;
}
}
else
{
const tools::Rectangle rcOverlap
= rcNew.m_aRectangle.GetIntersection(rcOld.m_aRectangle);
const bool bOverlap = !rcOverlap.IsEmpty();
SAL_INFO("lok", "Merging " << rcNew.toString() << " & " << rcOld.toString()
<< " => " << rcOverlap.toString()
<< " Overlap: " << bOverlap);
if (bOverlap)
{
rcNew.m_aRectangle.Union(rcOld.m_aRectangle);
SAL_INFO("lok", "Merged: " << rcNew.toString());
return true;
}
}
}
// Keep others.
return false;
});
if (rcNew.m_aRectangle != rcOrig.m_aRectangle)
{
SAL_INFO("lok", "Replacing: " << rcOrig.toString() << " by " << rcNew.toString());
if (rcNew.m_aRectangle.GetWidth() < rcOrig.m_aRectangle.GetWidth()
|| rcNew.m_aRectangle.GetHeight() < rcOrig.m_aRectangle.GetHeight())
{
SAL_WARN("lok", "Error: merged rect smaller.");
}
}
}
aCallbackData.setRectangleAndPart(rcNew);
// Queue this one.
return false;
}
bool CallbackFlushHandler::processWindowEvent(CallbackData& aCallbackData)
{
const std::string& payload = aCallbackData.PayloadString;
const int type = aCallbackData.Type;
boost::property_tree::ptree& aTree = aCallbackData.setJson(payload);
const unsigned nLOKWindowId = aTree.get<unsigned>("id", 0);
const std::string aAction = aTree.get<std::string>("action", "");
if (aAction == "invalidate")
{
std::string aRectStr = aTree.get<std::string>("rectangle", "");
// no 'rectangle' field => invalidate all of the window =>
// remove all previous window part invalidations
if (aRectStr.empty())
{
removeAll([&nLOKWindowId](const queue_type::value_type& elem) {
if (elem.Type == LOK_CALLBACK_WINDOW)
{
const boost::property_tree::ptree& aOldTree = elem.getJson();
if (nLOKWindowId == aOldTree.get<unsigned>("id", 0)
&& aOldTree.get<std::string>("action", "") == "invalidate")
{
return true;
}
}
return false;
});
}
else
{
// if we have to invalidate all of the window, ignore
// any part invalidation message
const auto invAllExist = std::any_of(m_queue.rbegin(), m_queue.rend(),
[&nLOKWindowId] (const queue_type::value_type& elem)
{
if (elem.Type != LOK_CALLBACK_WINDOW)
return false;
const boost::property_tree::ptree& aOldTree = elem.getJson();
return nLOKWindowId == aOldTree.get<unsigned>("id", 0)
&& aOldTree.get<std::string>("action", "") == "invalidate"
&& aOldTree.get<std::string>("rectangle", "").empty();
});
// we found a invalidate-all window callback
if (invAllExist)
{
SAL_INFO("lok.dialog", "Skipping queue ["
<< type << "]: [" << payload
<< "] since whole window needs to be invalidated.");
return true;
}
std::istringstream aRectStream(aRectStr);
tools::Long nLeft, nTop, nWidth, nHeight;
char nComma;
aRectStream >> nLeft >> nComma >> nTop >> nComma >> nWidth >> nComma >> nHeight;
tools::Rectangle aNewRect(nLeft, nTop, nLeft + nWidth, nTop + nHeight);
bool currentIsRedundant = false;
removeAll([&aNewRect, &nLOKWindowId,
¤tIsRedundant](const queue_type::value_type& elem) {
if (elem.Type != LOK_CALLBACK_WINDOW)
return false;
const boost::property_tree::ptree& aOldTree = elem.getJson();
if (aOldTree.get<std::string>("action", "") == "invalidate")
{
// Not possible that we encounter an empty rectangle here; we already handled this case above.
std::istringstream aOldRectStream(aOldTree.get<std::string>("rectangle", ""));
tools::Long nOldLeft, nOldTop, nOldWidth, nOldHeight;
char nOldComma;
aOldRectStream >> nOldLeft >> nOldComma >> nOldTop >> nOldComma >> nOldWidth
>> nOldComma >> nOldHeight;
const tools::Rectangle aOldRect = tools::Rectangle(
nOldLeft, nOldTop, nOldLeft + nOldWidth, nOldTop + nOldHeight);
if (nLOKWindowId == aOldTree.get<unsigned>("id", 0))
{
if (aNewRect == aOldRect)
{
SAL_INFO("lok.dialog", "Duplicate rect [" << aNewRect.toString()
<< "]. Skipping new.");
// We have a rectangle in the queue already that makes the current Callback useless.
currentIsRedundant = true;
return false;
}
// new one engulfs the old one?
else if (aNewRect.IsInside(aOldRect))
{
SAL_INFO("lok.dialog",
"New rect [" << aNewRect.toString() << "] engulfs old ["
<< aOldRect.toString() << "]. Replacing old.");
return true;
}
// old one engulfs the new one?
else if (aOldRect.IsInside(aNewRect))
{
SAL_INFO("lok.dialog",
"Old rect [" << aOldRect.toString() << "] engulfs new ["
<< aNewRect.toString() << "]. Skipping new.");
// We have a rectangle in the queue already that makes the current Callback useless.
currentIsRedundant = true;
return false;
}
else
{
// Overlapping rects.
const tools::Rectangle aPreMergeRect = aNewRect;
aNewRect.Union(aOldRect);
SAL_INFO("lok.dialog", "Merging rects ["
<< aPreMergeRect.toString() << "] & ["
<< aOldRect.toString() << "] = ["
<< aNewRect.toString()
<< "]. Replacing old.");
return true;
}
}
}
// keep rest
return false;
});
// Do not enqueue if redundant.
if (currentIsRedundant)
return true;
aTree.put("rectangle", aNewRect.toString().getStr());
aCallbackData.setJson(aTree);
assert(aCallbackData.validate() && "Validation after setJson failed!");
}
}
else if (aAction == "created")
{
// Remove all previous actions on same dialog, if we are creating it anew.
removeAll([&nLOKWindowId](const queue_type::value_type& elem) {
if (elem.Type == LOK_CALLBACK_WINDOW)
{
const boost::property_tree::ptree& aOldTree = elem.getJson();
if (nLOKWindowId == aOldTree.get<unsigned>("id", 0))
return true;
}
return false;
});
VclPtr<Window> pWindow = vcl::Window::FindLOKWindow(nLOKWindowId);
if (!pWindow)
{
gImpl->maLastExceptionMsg = "Document doesn't support dialog rendering, or window not found.";
return false;
}
#ifndef IOS
auto xClip = forceSetClipboardForCurrentView(m_pDocument);
uno::Reference<datatransfer::clipboard::XClipboard> xClipboard(xClip.get());
pWindow->SetClipboard(xClipboard);
#endif
}
else if (aAction == "size_changed")
{
// A size change is practically re-creation of the window.
// But at a minimum it's a full invalidation.
removeAll([&nLOKWindowId](const queue_type::value_type& elem) {
if (elem.Type == LOK_CALLBACK_WINDOW)
{
const boost::property_tree::ptree& aOldTree = elem.getJson();
if (nLOKWindowId == aOldTree.get<unsigned>("id", 0))
{
const std::string aOldAction = aOldTree.get<std::string>("action", "");
if (aOldAction == "invalidate")
return true;
}
}
return false;
});
}
// Queue this one.
return false;
}
void CallbackFlushHandler::Invoke()
{
comphelper::ProfileZone aZone("CallbackFlushHandler::Invoke");
if (!m_pCallback)
return;
std::scoped_lock<std::mutex> lock(m_mutex);
SAL_INFO("lok", "Flushing " << m_queue.size() << " elements.");
for (const auto& rCallbackData : m_queue)
{
const int type = rCallbackData.Type;
const auto& payload = rCallbackData.PayloadString;
const int viewId = lcl_isViewCallbackType(type) ? lcl_getViewId(rCallbackData) : -1;
if (viewId == -1)
{
const auto stateIt = m_states.find(type);
if (stateIt != m_states.end())
{
// If the state didn't change, it's safe to ignore.
if (stateIt->second == payload)
{
SAL_INFO("lok", "Skipping duplicate [" << type << "]: [" << payload << "].");
continue;
}
stateIt->second = payload;
}
}
else
{
const auto statesIt = m_viewStates.find(viewId);
if (statesIt != m_viewStates.end())
{
auto& states = statesIt->second;
const auto stateIt = states.find(type);
if (stateIt != states.end())
{
// If the state didn't change, it's safe to ignore.
if (stateIt->second == payload)
{
SAL_INFO("lok", "Skipping view duplicate [" << type << ',' << viewId << "]: [" << payload << "].");
continue;
}
SAL_INFO("lok", "Replacing an element in view states [" << type << ',' << viewId << "]: [" << payload << "].");
stateIt->second = payload;
}
else
{
SAL_INFO("lok", "Inserted a new element in view states: [" << type << ',' << viewId << "]: [" << payload << "]");
states.emplace(type, payload);
}
}
}
m_pCallback(type, payload.c_str(), m_pData);
}
m_queue.clear();
}
bool CallbackFlushHandler::removeAll(const std::function<bool (const CallbackFlushHandler::queue_type::value_type&)>& rTestFunc)
{
auto newEnd = std::remove_if(m_queue.begin(), m_queue.end(), rTestFunc);
if (newEnd != m_queue.end())
{
m_queue.erase(newEnd, m_queue.end());
return true;
}
return false;
}
void CallbackFlushHandler::addViewStates(int viewId)
{
const auto& result = m_viewStates.emplace(viewId, decltype(m_viewStates)::mapped_type());
if (!result.second && result.first != m_viewStates.end())
{
result.first->second.clear();
}
}
void CallbackFlushHandler::removeViewStates(int viewId)
{
m_viewStates.erase(viewId);
}
static void doc_destroy(LibreOfficeKitDocument *pThis)
{
comphelper::ProfileZone aZone("doc_destroy");
SolarMutexGuard aGuard;
LOKClipboardFactory::releaseClipboardForView(-1);
LibLODocument_Impl *pDocument = static_cast<LibLODocument_Impl*>(pThis);
delete pDocument;
}
static void lo_destroy (LibreOfficeKit* pThis);
static int lo_initialize (LibreOfficeKit* pThis, const char* pInstallPath, const char* pUserProfilePath);
static LibreOfficeKitDocument* lo_documentLoad (LibreOfficeKit* pThis, const char* pURL);
static char * lo_getError (LibreOfficeKit* pThis);
static void lo_freeError (char* pFree);
static LibreOfficeKitDocument* lo_documentLoadWithOptions (LibreOfficeKit* pThis,
const char* pURL,
const char* pOptions);
static void lo_registerCallback (LibreOfficeKit* pThis,
LibreOfficeKitCallback pCallback,
void* pData);
static char* lo_getFilterTypes(LibreOfficeKit* pThis);
static void lo_setOptionalFeatures(LibreOfficeKit* pThis, unsigned long long features);
static void lo_setDocumentPassword(LibreOfficeKit* pThis,
const char* pURL,
const char* pPassword);
static char* lo_getVersionInfo(LibreOfficeKit* pThis);
static int lo_runMacro (LibreOfficeKit* pThis, const char* pURL);
static bool lo_signDocument(LibreOfficeKit* pThis,
const char* pUrl,
const unsigned char* pCertificateBinary,
const int nCertificateBinarySize,
const unsigned char* pPrivateKeyBinary,
const int nPrivateKeyBinarySize);
static void lo_runLoop(LibreOfficeKit* pThis,
LibreOfficeKitPollCallback pPollCallback,
LibreOfficeKitWakeCallback pWakeCallback,
void* pData);
LibLibreOffice_Impl::LibLibreOffice_Impl()
: m_pOfficeClass( gOfficeClass.lock() )
, maThread(nullptr)
, mpCallback(nullptr)
, mpCallbackData(nullptr)
, mOptionalFeatures(0)
{
if(!m_pOfficeClass) {
m_pOfficeClass = std::make_shared<LibreOfficeKitClass>();
m_pOfficeClass->nSize = sizeof(LibreOfficeKitClass);
m_pOfficeClass->destroy = lo_destroy;
m_pOfficeClass->documentLoad = lo_documentLoad;
m_pOfficeClass->getError = lo_getError;
m_pOfficeClass->freeError = lo_freeError;
m_pOfficeClass->documentLoadWithOptions = lo_documentLoadWithOptions;
m_pOfficeClass->registerCallback = lo_registerCallback;
m_pOfficeClass->getFilterTypes = lo_getFilterTypes;
m_pOfficeClass->setOptionalFeatures = lo_setOptionalFeatures;
m_pOfficeClass->setDocumentPassword = lo_setDocumentPassword;
m_pOfficeClass->getVersionInfo = lo_getVersionInfo;
m_pOfficeClass->runMacro = lo_runMacro;
m_pOfficeClass->signDocument = lo_signDocument;
m_pOfficeClass->runLoop = lo_runLoop;
gOfficeClass = m_pOfficeClass;
}
pClass = m_pOfficeClass.get();
}
LibLibreOffice_Impl::~LibLibreOffice_Impl()
{
}
namespace
{
#ifdef IOS
void paintTileToCGContext(ITiledRenderable* pDocument,
void* rCGContext, const Size nCanvasSize,
const int nTilePosX, const int nTilePosY,
const int nTileWidth, const int nTileHeight)
{
SystemGraphicsData aData;
aData.rCGContext = reinterpret_cast<CGContextRef>(rCGContext);
ScopedVclPtrInstance<VirtualDevice> pDevice(aData, Size(1, 1), DeviceFormat::DEFAULT);
pDevice->SetBackground(Wallpaper(COL_TRANSPARENT));
pDevice->SetOutputSizePixel(nCanvasSize);
pDocument->paintTile(*pDevice, nCanvasSize.Width(), nCanvasSize.Height(),
nTilePosX, nTilePosY, nTileWidth, nTileHeight);
}
void paintTileIOS(LibreOfficeKitDocument* pThis,
unsigned char* pBuffer,
const int nCanvasWidth, const int nCanvasHeight, const double fDPIScale,
const int nTilePosX, const int nTilePosY,
const int nTileWidth, const int nTileHeight)
{
CGContextRef pCGContext = CGBitmapContextCreate(pBuffer, nCanvasWidth, nCanvasHeight, 8,
nCanvasWidth * 4, CGColorSpaceCreateDeviceRGB(),
kCGImageAlphaPremultipliedFirst | kCGImageByteOrder32Little);
CGContextTranslateCTM(pCGContext, 0, nCanvasHeight);
CGContextScaleCTM(pCGContext, fDPIScale, -fDPIScale);
doc_paintTileToCGContext(pThis, (void*) pCGContext, nCanvasWidth, nCanvasHeight, nTilePosX, nTilePosY, nTileWidth, nTileHeight);
CGContextRelease(pCGContext);
}
#endif
void setLanguageAndLocale(OUString const & aLangISO)
{
SvtSysLocaleOptions aLocalOptions;
aLocalOptions.SetLocaleConfigString(aLangISO);
aLocalOptions.SetUILocaleConfigString(aLangISO);
aLocalOptions.Commit();
}
void setFormatSpecificFilterData(OUString const & sFormat, comphelper::SequenceAsHashMap & rFilterDataMap)
{
if (sFormat == "pdf")
{
// always export bookmarks, which is needed for annotations
rFilterDataMap["ExportBookmarks"] <<= true;
}
}
} // anonymous namespace
// Wonder global state ...
static uno::Reference<css::uno::XComponentContext> xContext;
static uno::Reference<css::lang::XMultiServiceFactory> xSFactory;
static uno::Reference<css::lang::XMultiComponentFactory> xFactory;
static LibreOfficeKitDocument* lo_documentLoad(LibreOfficeKit* pThis, const char* pURL)
{
return lo_documentLoadWithOptions(pThis, pURL, nullptr);
}
static LibreOfficeKitDocument* lo_documentLoadWithOptions(LibreOfficeKit* pThis, const char* pURL, const char* pOptions)
{
comphelper::ProfileZone aZone("lo_documentLoadWithOptions");
SolarMutexGuard aGuard;
static int nDocumentIdCounter = 0;
LibLibreOffice_Impl* pLib = static_cast<LibLibreOffice_Impl*>(pThis);
pLib->maLastExceptionMsg.clear();
OUString aURL(getAbsoluteURL(pURL));
if (aURL.isEmpty())
{
pLib->maLastExceptionMsg = "Filename to load was not provided.";
SAL_INFO("lok", "URL for load is empty");
return nullptr;
}
pLib->maLastExceptionMsg.clear();
if (!xContext.is())
{
pLib->maLastExceptionMsg = "ComponentContext is not available";
SAL_INFO("lok", "ComponentContext is not available");
return nullptr;
}
uno::Reference<frame::XDesktop2> xComponentLoader = frame::Desktop::create(xContext);
if (!xComponentLoader.is())
{
pLib->maLastExceptionMsg = "ComponentLoader is not available";
SAL_INFO("lok", "ComponentLoader is not available");
return nullptr;
}
try
{
// 'Language=...' is an option that LOK consumes by itself, and does
// not pass it as a parameter to the filter
OUString aOptions = getUString(pOptions);
const OUString aLanguage = extractParameter(aOptions, "Language");
bool isValidLangTag = LanguageTag::isValidBcp47(aLanguage, nullptr);
if (!aLanguage.isEmpty() && isValidLangTag)
{
SfxLokHelper::setDefaultLanguage(aLanguage);
// Set the LOK language tag, used for dialog tunneling.
comphelper::LibreOfficeKit::setLanguageTag(LanguageTag(aLanguage));
comphelper::LibreOfficeKit::setLocale(LanguageTag(aLanguage));
SAL_INFO("lok", "Set document language to " << aLanguage);
// use with care - it sets it for the entire core, not just the
// document
setLanguageAndLocale(aLanguage);
// Need to reset the static initialized values
SvNumberFormatter::resetTheCurrencyTable();
}
const OUString aDeviceFormFactor = extractParameter(aOptions, "DeviceFormFactor");
SfxLokHelper::setDeviceFormFactor(aDeviceFormFactor);
uno::Sequence<css::beans::PropertyValue> aFilterOptions(2);
aFilterOptions[0] = css::beans::PropertyValue( "FilterOptions",
0,
uno::makeAny(aOptions),
beans::PropertyState_DIRECT_VALUE);
rtl::Reference<LOKInteractionHandler> const pInteraction(
new LOKInteractionHandler("load", pLib));
auto const pair(pLib->mInteractionMap.insert(std::make_pair(aURL.toUtf8(), pInteraction)));
comphelper::ScopeGuard const g([&] () {
if (pair.second)
{
pLib->mInteractionMap.erase(aURL.toUtf8());
}
});
uno::Reference<task::XInteractionHandler2> const xInteraction(pInteraction.get());
aFilterOptions[1].Name = "InteractionHandler";
aFilterOptions[1].Value <<= xInteraction;
/* TODO
sal_Int16 nMacroExecMode = document::MacroExecMode::USE_CONFIG;
aFilterOptions[2].Name = "MacroExecutionMode";
aFilterOptions[2].Value <<= nMacroExecMode;
sal_Int16 nUpdateDoc = document::UpdateDocMode::ACCORDING_TO_CONFIG;
aFilterOptions[3].Name = "UpdateDocMode";
aFilterOptions[3].Value <<= nUpdateDoc;
*/
uno::Reference<lang::XComponent> xComponent = xComponentLoader->loadComponentFromURL(
aURL, "_blank", 0,
aFilterOptions);
assert(!xComponent.is() || pair.second); // concurrent loading of same URL ought to fail
if (!xComponent.is())
{
pLib->maLastExceptionMsg = "loadComponentFromURL returned an empty reference";
SAL_INFO("lok", "Document can't be loaded - " << pLib->maLastExceptionMsg);
return nullptr;
}
LibLODocument_Impl* pDocument = new LibLODocument_Impl(xComponent, nDocumentIdCounter++);
// Do we know that after loading the document, its initial view is the "current" view?
SfxLokHelper::setDocumentIdOfView(pDocument->mnDocumentId);
if (pLib->mpCallback)
{
int nState = doc_getSignatureState(pDocument);
pLib->mpCallback(LOK_CALLBACK_SIGNATURE_STATUS, OString::number(nState).getStr(), pLib->mpCallbackData);
}
return pDocument;
}
catch (const uno::Exception& exception)
{
pLib->maLastExceptionMsg = exception.Message;
TOOLS_INFO_EXCEPTION("lok", "Document can't be loaded");
}
return nullptr;
}
static int lo_runMacro(LibreOfficeKit* pThis, const char *pURL)
{
comphelper::ProfileZone aZone("lo_runMacro");
SolarMutexGuard aGuard;
LibLibreOffice_Impl* pLib = static_cast<LibLibreOffice_Impl*>(pThis);
pLib->maLastExceptionMsg.clear();
OUString sURL( pURL, strlen(pURL), RTL_TEXTENCODING_UTF8 );
if (sURL.isEmpty())
{
pLib->maLastExceptionMsg = "Macro to run was not provided.";
SAL_INFO("lok", "Macro URL is empty");
return false;
}
if (!sURL.startsWith("macro://"))
{
pLib->maLastExceptionMsg = "This doesn't look like macro URL";
SAL_INFO("lok", "Macro URL is invalid");
return false;
}
pLib->maLastExceptionMsg.clear();
if (!xContext.is())
{
pLib->maLastExceptionMsg = "ComponentContext is not available";
SAL_INFO("lok", "ComponentContext is not available");
return false;
}
util::URL aURL;
aURL.Complete = sURL;
uno::Reference < util::XURLTransformer > xParser( util::URLTransformer::create( xContext ) );
if( xParser.is() )
xParser->parseStrict( aURL );
uno::Reference<frame::XDesktop2> xComponentLoader = frame::Desktop::create(xContext);
if (!xComponentLoader.is())
{
pLib->maLastExceptionMsg = "ComponentLoader is not available";
SAL_INFO("lok", "ComponentLoader is not available");
return false;
}
xFactory = xContext->getServiceManager();
if (xFactory.is())
{
uno::Reference<frame::XDispatchProvider> xDP;
xSFactory.set(xFactory, uno::UNO_QUERY_THROW);
xDP.set( xSFactory->createInstance("com.sun.star.comp.sfx2.SfxMacroLoader"), uno::UNO_QUERY );
uno::Reference<frame::XDispatch> xD = xDP->queryDispatch( aURL, OUString(), 0);
if (!xD.is())
{
pLib->maLastExceptionMsg = "Macro loader is not available";
SAL_INFO("lok", "Macro loader is not available");
return false;
}
uno::Reference < frame::XSynchronousDispatch > xSyncDisp( xD, uno::UNO_QUERY_THROW );
uno::Sequence<css::beans::PropertyValue> aEmpty;
css::beans::PropertyValue aErr;
uno::Any aRet = xSyncDisp->dispatchWithReturnValue( aURL, aEmpty );
aRet >>= aErr;
if (aErr.Name == "ErrorCode")
{
sal_uInt32 nErrCode = 0; // ERRCODE_NONE
aErr.Value >>= nErrCode;
pLib->maLastExceptionMsg = "An error occurred running macro (error code: " + OUString::number( nErrCode ) + ")";
SAL_INFO("lok", "Macro execution terminated with error code " << nErrCode);
return false;
}
return true;
}
return false;
}
static bool lo_signDocument(LibreOfficeKit* /*pThis*/,
const char* pURL,
const unsigned char* pCertificateBinary,
const int nCertificateBinarySize,
const unsigned char* pPrivateKeyBinary,
const int nPrivateKeyBinarySize)
{
comphelper::ProfileZone aZone("lo_signDocument");
OUString aURL(getAbsoluteURL(pURL));
if (aURL.isEmpty())
return false;
if (!xContext.is())
return false;
uno::Sequence<sal_Int8> aCertificateSequence;
std::string aCertificateString(reinterpret_cast<const char*>(pCertificateBinary), nCertificateBinarySize);
std::string aCertificateBase64String = extractCertificate(aCertificateString);
if (!aCertificateBase64String.empty())
{
OUString aBase64OUString = OUString::createFromAscii(aCertificateBase64String.c_str());
comphelper::Base64::decode(aCertificateSequence, aBase64OUString);
}
else
{
aCertificateSequence.realloc(nCertificateBinarySize);
std::copy(pCertificateBinary, pCertificateBinary + nCertificateBinarySize, aCertificateSequence.begin());
}
uno::Sequence<sal_Int8> aPrivateKeySequence;
std::string aPrivateKeyString(reinterpret_cast<const char*>(pPrivateKeyBinary), nPrivateKeyBinarySize);
std::string aPrivateKeyBase64String = extractPrivateKey(aPrivateKeyString);
if (!aPrivateKeyBase64String.empty())
{
OUString aBase64OUString = OUString::createFromAscii(aPrivateKeyBase64String.c_str());
comphelper::Base64::decode(aPrivateKeySequence, aBase64OUString);
}
else
{
aPrivateKeySequence.realloc(nPrivateKeyBinarySize);
std::copy(pPrivateKeyBinary, pPrivateKeyBinary + nPrivateKeyBinarySize, aPrivateKeySequence.begin());
}
uno::Reference<xml::crypto::XSEInitializer> xSEInitializer = xml::crypto::SEInitializer::create(xContext);
uno::Reference<xml::crypto::XXMLSecurityContext> xSecurityContext = xSEInitializer->createSecurityContext(OUString());
if (!xSecurityContext.is())
return false;
uno::Reference<xml::crypto::XSecurityEnvironment> xSecurityEnvironment = xSecurityContext->getSecurityEnvironment();
uno::Reference<xml::crypto::XCertificateCreator> xCertificateCreator(xSecurityEnvironment, uno::UNO_QUERY);
if (!xCertificateCreator.is())
return false;
uno::Reference<security::XCertificate> xCertificate = xCertificateCreator->createDERCertificateWithPrivateKey(aCertificateSequence, aPrivateKeySequence);
if (!xCertificate.is())
return false;
sfx2::DocumentSigner aDocumentSigner(aURL);
if (!aDocumentSigner.signDocument(xCertificate))
return false;
return true;
}
static void lo_registerCallback (LibreOfficeKit* pThis,
LibreOfficeKitCallback pCallback,
void* pData)
{
SolarMutexGuard aGuard;
LibLibreOffice_Impl* pLib = static_cast<LibLibreOffice_Impl*>(pThis);
pLib->maLastExceptionMsg.clear();
pLib->mpCallback = pCallback;
pLib->mpCallbackData = pData;
}
static int doc_saveAs(LibreOfficeKitDocument* pThis, const char* sUrl, const char* pFormat, const char* pFilterOptions)
{
comphelper::ProfileZone aZone("doc_saveAs");
SolarMutexGuard aGuard;
SetLastExceptionMsg();
LibLODocument_Impl* pDocument = static_cast<LibLODocument_Impl*>(pThis);
OUString sFormat = getUString(pFormat);
OUString aURL(getAbsoluteURL(sUrl));
uno::Reference<frame::XStorable> xStorable(pDocument->mxComponent, uno::UNO_QUERY_THROW);
if (aURL.isEmpty())
{
SetLastExceptionMsg("Filename to save to was not provided.");
SAL_INFO("lok", "URL for save is empty");
return false;
}
try
{
const ExtensionMap* pMap;
switch (doc_getDocumentType(pThis))
{
case LOK_DOCTYPE_SPREADSHEET:
pMap = aCalcExtensionMap;
break;
case LOK_DOCTYPE_PRESENTATION:
pMap = aImpressExtensionMap;
break;
case LOK_DOCTYPE_DRAWING:
pMap = aDrawExtensionMap;
break;
case LOK_DOCTYPE_TEXT:
pMap = aWriterExtensionMap;
break;
case LOK_DOCTYPE_OTHER:
default:
SAL_INFO("lok", "Can't save document - unsupported document type.");
return false;
}
if (pFormat == nullptr)
{
// sniff from the extension
sal_Int32 idx = aURL.lastIndexOf(".");
if( idx > 0 )
{
sFormat = aURL.copy( idx + 1 );
}
else
{
SetLastExceptionMsg("input filename without a suffix");
return false;
}
}
OUString aFilterName;
for (sal_Int32 i = 0; pMap[i].extn; ++i)
{
if (sFormat.equalsIgnoreAsciiCaseAscii(pMap[i].extn))
{
aFilterName = getUString(pMap[i].filterName);
break;
}
}
if (aFilterName.isEmpty())
{
SetLastExceptionMsg("no output filter found for provided suffix");
return false;
}
OUString aFilterOptions = getUString(pFilterOptions);
// Check if watermark for pdf is passed by filteroptions...
// It is not a real filter option so it must be filtered out.
OUString watermarkText, sFullSheetPreview;
int aIndex = -1;
if ((aIndex = aFilterOptions.indexOf(",Watermark=")) >= 0)
{
int bIndex = aFilterOptions.indexOf("WATERMARKEND");
watermarkText = aFilterOptions.copy(aIndex+11, bIndex-(aIndex+11));
OUString temp = aFilterOptions.copy(0, aIndex);
aFilterOptions = temp + aFilterOptions.copy(bIndex+12);
}
if ((aIndex = aFilterOptions.indexOf(",FullSheetPreview=")) >= 0)
{
int bIndex = aFilterOptions.indexOf("FULLSHEETPREVEND");
sFullSheetPreview = aFilterOptions.copy(aIndex+18, bIndex-(aIndex+18));
OUString temp = aFilterOptions.copy(0, aIndex);
aFilterOptions = temp + aFilterOptions.copy(bIndex+16);
}
bool bFullSheetPreview = sFullSheetPreview == "true";
// 'TakeOwnership' == this is a 'real' SaveAs (that is, the document
// gets a new name). When this is not provided, the meaning of
// saveAs() is more like save-a-copy, which allows saving to any
// random format like PDF or PNG.
// It is not a real filter option, so we have to filter it out.
const uno::Sequence<OUString> aOptionSeq = comphelper::string::convertCommaSeparated(aFilterOptions);
std::vector<OUString> aFilteredOptionVec;
bool bTakeOwnership = false;
MediaDescriptor aSaveMediaDescriptor;
for (const auto& rOption : aOptionSeq)
{
if (rOption == "TakeOwnership")
bTakeOwnership = true;
else if (rOption == "NoFileSync")
aSaveMediaDescriptor["NoFileSync"] <<= true;
else
aFilteredOptionVec.push_back(rOption);
}
aSaveMediaDescriptor["Overwrite"] <<= true;
aSaveMediaDescriptor["FilterName"] <<= aFilterName;
auto aFilteredOptionSeq = comphelper::containerToSequence<OUString>(aFilteredOptionVec);
aFilterOptions = comphelper::string::convertCommaSeparated(aFilteredOptionSeq);
aSaveMediaDescriptor[MediaDescriptor::PROP_FILTEROPTIONS()] <<= aFilterOptions;
comphelper::SequenceAsHashMap aFilterDataMap;
setFormatSpecificFilterData(sFormat, aFilterDataMap);
if (!watermarkText.isEmpty())
aFilterDataMap["TiledWatermark"] <<= watermarkText;
if (bFullSheetPreview)
aFilterDataMap["SinglePageSheets"] <<= true;
if (!aFilterDataMap.empty())
{
aSaveMediaDescriptor["FilterData"] <<= aFilterDataMap.getAsConstPropertyValueList();
}
// add interaction handler too
if (gImpl)
{
// gImpl does not have to exist when running from a unit test
rtl::Reference<LOKInteractionHandler> const pInteraction(
new LOKInteractionHandler("saveas", gImpl, pDocument));
uno::Reference<task::XInteractionHandler2> const xInteraction(pInteraction.get());
aSaveMediaDescriptor[MediaDescriptor::PROP_INTERACTIONHANDLER()] <<= xInteraction;
}
if (bTakeOwnership)
xStorable->storeAsURL(aURL, aSaveMediaDescriptor.getAsConstPropertyValueList());
else
xStorable->storeToURL(aURL, aSaveMediaDescriptor.getAsConstPropertyValueList());
return true;
}
catch (const uno::Exception& exception)
{
SetLastExceptionMsg("exception: " + exception.Message);
}
return false;
}
/**
* Initialize UNO commands, in the sense that from now on, the LOK client gets updates for status
* changes of these commands. This is necessary, because (unlike in the desktop case) there are no
* toolbars hosting widgets these UNO commands, so no such status updates would be sent to the
* headless LOK clients out of the box.
*/
static void doc_iniUnoCommands ()
{
SolarMutexGuard aGuard;
SetLastExceptionMsg();
OUString sUnoCommands[] =
{
OUString(".uno:AlignLeft"),
OUString(".uno:AlignHorizontalCenter"),
OUString(".uno:AlignRight"),
OUString(".uno:BackColor"),
OUString(".uno:BackgroundColor"),
OUString(".uno:TableCellBackgroundColor"),
OUString(".uno:Bold"),
OUString(".uno:CenterPara"),
OUString(".uno:CharBackColor"),
OUString(".uno:CharBackgroundExt"),
OUString(".uno:CharFontName"),
OUString(".uno:Color"),
OUString(".uno:ControlCodes"),
OUString(".uno:DecrementIndent"),
OUString(".uno:DefaultBullet"),
OUString(".uno:DefaultNumbering"),
OUString(".uno:FontColor"),
OUString(".uno:FontHeight"),
OUString(".uno:IncrementIndent"),
OUString(".uno:Italic"),
OUString(".uno:JustifyPara"),
OUString(".uno:OutlineFont"),
OUString(".uno:LeftPara"),
OUString(".uno:LanguageStatus"),
OUString(".uno:RightPara"),
OUString(".uno:Shadowed"),
OUString(".uno:SubScript"),
OUString(".uno:SuperScript"),
OUString(".uno:Strikeout"),
OUString(".uno:StyleApply"),
OUString(".uno:Underline"),
OUString(".uno:ModifiedStatus"),
OUString(".uno:Undo"),
OUString(".uno:Redo"),
OUString(".uno:InsertPage"),
OUString(".uno:DeletePage"),
OUString(".uno:DuplicatePage"),
OUString(".uno:Cut"),
OUString(".uno:Copy"),
OUString(".uno:Paste"),
OUString(".uno:SelectAll"),
OUString(".uno:InsertAnnotation"),
OUString(".uno:DeleteAnnotation"),
OUString(".uno:ReplyComment"),
OUString(".uno:ResolveComment"),
OUString(".uno:ResolveCommentThread"),
OUString(".uno:InsertRowsBefore"),
OUString(".uno:InsertRowsAfter"),
OUString(".uno:InsertColumnsBefore"),
OUString(".uno:InsertColumnsAfter"),
OUString(".uno:MergeCells"),
OUString(".uno:DeleteRows"),
OUString(".uno:DeleteColumns"),
OUString(".uno:DeleteTable"),
OUString(".uno:SelectTable"),
OUString(".uno:EntireRow"),
OUString(".uno:EntireColumn"),
OUString(".uno:EntireCell"),
OUString(".uno:AssignLayout"),
OUString(".uno:StatusDocPos"),
OUString(".uno:RowColSelCount"),
OUString(".uno:StatusPageStyle"),
OUString(".uno:InsertMode"),
OUString(".uno:SpellOnline"),
OUString(".uno:StatusSelectionMode"),
OUString(".uno:StateTableCell"),
OUString(".uno:StatusBarFunc"),
OUString(".uno:StatePageNumber"),
OUString(".uno:StateWordCount"),
OUString(".uno:SelectionMode"),
OUString(".uno:PageStatus"),
OUString(".uno:LayoutStatus"),
OUString(".uno:Context"),
OUString(".uno:WrapText"),
OUString(".uno:ToggleMergeCells"),
OUString(".uno:NumberFormatCurrency"),
OUString(".uno:NumberFormatPercent"),
OUString(".uno:NumberFormatDecimal"),
OUString(".uno:NumberFormatDate"),
OUString(".uno:FrameLineColor"),
OUString(".uno:SortAscending"),
OUString(".uno:SortDescending"),
OUString(".uno:TrackChanges"),
OUString(".uno:ShowTrackedChanges"),
OUString(".uno:NextTrackedChange"),
OUString(".uno:PreviousTrackedChange"),
OUString(".uno:AcceptAllTrackedChanges"),
OUString(".uno:RejectAllTrackedChanges"),
OUString(".uno:TableDialog"),
OUString(".uno:FormatCellDialog"),
OUString(".uno:FontDialog"),
OUString(".uno:ParagraphDialog"),
OUString(".uno:OutlineBullet"),
OUString(".uno:InsertIndexesEntry"),
OUString(".uno:DocumentRepair"),
OUString(".uno:TransformDialog"),
OUString(".uno:InsertPageHeader"),
OUString(".uno:InsertPageFooter"),
OUString(".uno:OnlineAutoFormat"),
OUString(".uno:InsertObjectChart"),
OUString(".uno:InsertSection"),
OUString(".uno:InsertAnnotation"),
OUString(".uno:InsertPagebreak"),
OUString(".uno:InsertColumnBreak"),
OUString(".uno:HyperlinkDialog"),
OUString(".uno:InsertSymbol"),
OUString(".uno:EditRegion"),
OUString(".uno:ThesaurusDialog"),
OUString(".uno:FormatArea"),
OUString(".uno:FormatLine"),
OUString(".uno:FormatColumns"),
OUString(".uno:Watermark"),
OUString(".uno:ResetAttributes"),
OUString(".uno:Orientation"),
OUString(".uno:ObjectAlignLeft"),
OUString(".uno:ObjectAlignRight"),
OUString(".uno:AlignCenter"),
OUString(".uno:TransformPosX"),
OUString(".uno:TransformPosY"),
OUString(".uno:TransformWidth"),
OUString(".uno:TransformHeight"),
OUString(".uno:ObjectBackOne"),
OUString(".uno:SendToBack"),
OUString(".uno:ObjectForwardOne"),
OUString(".uno:BringToFront"),
OUString(".uno:WrapRight"),
OUString(".uno:WrapThrough"),
OUString(".uno:WrapLeft"),
OUString(".uno:WrapIdeal"),
OUString(".uno:WrapOn"),
OUString(".uno:WrapOff"),
OUString(".uno:UpdateCurIndex"),
OUString(".uno:InsertCaptionDialog"),
OUString(".uno:FormatGroup"),
OUString(".uno:SplitTable"),
OUString(".uno:MergeCells"),
OUString(".uno:DeleteNote"),
OUString(".uno:AcceptChanges"),
OUString(".uno:FormatPaintbrush"),
OUString(".uno:SetDefault"),
OUString(".uno:ParaLeftToRight"),
OUString(".uno:ParaRightToLeft"),
OUString(".uno:ParaspaceIncrease"),
OUString(".uno:ParaspaceDecrease"),
OUString(".uno:AcceptTrackedChange"),
OUString(".uno:RejectTrackedChange"),
OUString(".uno:ShowResolvedAnnotations"),
OUString(".uno:InsertBreak"),
OUString(".uno:InsertEndnote"),
OUString(".uno:InsertFootnote"),
OUString(".uno:InsertReferenceField"),
OUString(".uno:InsertBookmark"),
OUString(".uno:InsertAuthoritiesEntry"),
OUString(".uno:InsertMultiIndex"),
OUString(".uno:InsertField"),
OUString(".uno:InsertPageNumberField"),
OUString(".uno:InsertPageCountField"),
OUString(".uno:InsertDateField"),
OUString(".uno:InsertTitleField"),
OUString(".uno:InsertFieldCtrl"),
OUString(".uno:CharmapControl"),
OUString(".uno:EnterGroup"),
OUString(".uno:LeaveGroup"),
OUString(".uno:AlignUp"),
OUString(".uno:AlignMiddle"),
OUString(".uno:AlignDown"),
OUString(".uno:TraceChangeMode"),
OUString(".uno:Combine"),
OUString(".uno:Merge"),
OUString(".uno:Dismantle"),
OUString(".uno:Substract"),
OUString(".uno:DistributeSelection"),
OUString(".uno:Intersect"),
OUString(".uno:BorderInner"),
OUString(".uno:BorderOuter"),
OUString(".uno:FreezePanes"),
OUString(".uno:FreezePanesColumn"),
OUString(".uno:FreezePanesRow"),
OUString(".uno:Sidebar")
};
util::URL aCommandURL;
SfxViewShell* pViewShell = SfxViewShell::Current();
SfxViewFrame* pViewFrame = pViewShell? pViewShell->GetViewFrame(): nullptr;
// check if Frame-Controller were created.
if (!pViewFrame)
{
SAL_WARN("lok", "iniUnoCommands: No Frame-Controller created.");
return;
}
if (!xContext.is())
xContext = comphelper::getProcessComponentContext();
if (!xContext.is())
{
SAL_WARN("lok", "iniUnoCommands: Component context is not available");
return;
}
SfxSlotPool& rSlotPool = SfxSlotPool::GetSlotPool(pViewFrame);
uno::Reference<util::XURLTransformer> xParser(util::URLTransformer::create(xContext));
for (const auto & sUnoCommand : sUnoCommands)
{
aCommandURL.Complete = sUnoCommand;
xParser->parseStrict(aCommandURL);
// when null, this command is not supported by the given component
// (like eg. Calc does not have ".uno:DefaultBullet" etc.)
if (const SfxSlot* pSlot = rSlotPool.GetUnoSlot(aCommandURL.Path))
{
// Initialize slot to dispatch .uno: Command.
pViewFrame->GetBindings().GetDispatch(pSlot, aCommandURL, false);
}
}
}
static int doc_getDocumentType (LibreOfficeKitDocument* pThis)
{
comphelper::ProfileZone aZone("doc_getDocumentType");
SolarMutexGuard aGuard;
SetLastExceptionMsg();
LibLODocument_Impl* pDocument = static_cast<LibLODocument_Impl*>(pThis);
try
{
uno::Reference<lang::XServiceInfo> xDocument(pDocument->mxComponent, uno::UNO_QUERY_THROW);
if (xDocument->supportsService("com.sun.star.sheet.SpreadsheetDocument"))
{
return LOK_DOCTYPE_SPREADSHEET;
}
else if (xDocument->supportsService("com.sun.star.presentation.PresentationDocument"))
{
return LOK_DOCTYPE_PRESENTATION;
}
else if (xDocument->supportsService("com.sun.star.drawing.DrawingDocument"))
{
return LOK_DOCTYPE_DRAWING;
}
else if (xDocument->supportsService("com.sun.star.text.TextDocument") || xDocument->supportsService("com.sun.star.text.WebDocument"))
{
return LOK_DOCTYPE_TEXT;
}
else
{
SetLastExceptionMsg("unknown document type");
}
}
catch (const uno::Exception& exception)
{
SetLastExceptionMsg("exception: " + exception.Message);
}
return LOK_DOCTYPE_OTHER;
}
static int doc_getParts (LibreOfficeKitDocument* pThis)
{
comphelper::ProfileZone aZone("doc_getParts");
SolarMutexGuard aGuard;
ITiledRenderable* pDoc = getTiledRenderable(pThis);
if (!pDoc)
{
SetLastExceptionMsg("Document doesn't support tiled rendering");
return 0;
}
return pDoc->getParts();
}
static int doc_getPart (LibreOfficeKitDocument* pThis)
{
comphelper::ProfileZone aZone("doc_getPart");
SolarMutexGuard aGuard;
SetLastExceptionMsg();
ITiledRenderable* pDoc = getTiledRenderable(pThis);
if (!pDoc)
{
SetLastExceptionMsg("Document doesn't support tiled rendering");
return 0;
}
return pDoc->getPart();
}
static void doc_setPart(LibreOfficeKitDocument* pThis, int nPart)
{
comphelper::ProfileZone aZone("doc_setPart");
SolarMutexGuard aGuard;
SetLastExceptionMsg();
ITiledRenderable* pDoc = getTiledRenderable(pThis);
if (!pDoc)
{
SetLastExceptionMsg("Document doesn't support tiled rendering");
return;
}
pDoc->setPart( nPart );
}
static char* doc_getPartInfo(LibreOfficeKitDocument* pThis, int nPart)
{
comphelper::ProfileZone aZone("doc_getPartInfo");
SolarMutexGuard aGuard;
ITiledRenderable* pDoc = getTiledRenderable(pThis);
if (!pDoc)
{
SetLastExceptionMsg("Document doesn't support tiled rendering");
return nullptr;
}
return convertOUString(pDoc->getPartInfo(nPart));
}
static void doc_selectPart(LibreOfficeKitDocument* pThis, int nPart, int nSelect)
{
SolarMutexGuard aGuard;
if (gImpl)
gImpl->maLastExceptionMsg.clear();
ITiledRenderable* pDoc = getTiledRenderable(pThis);
if (!pDoc)
{
gImpl->maLastExceptionMsg = "Document doesn't support tiled rendering";
return;
}
pDoc->selectPart( nPart, nSelect );
}
static void doc_moveSelectedParts(LibreOfficeKitDocument* pThis, int nPosition, bool bDuplicate)
{
SolarMutexGuard aGuard;
if (gImpl)
gImpl->maLastExceptionMsg.clear();
ITiledRenderable* pDoc = getTiledRenderable(pThis);
if (!pDoc)
{
gImpl->maLastExceptionMsg = "Document doesn't support tiled rendering";
return;
}
pDoc->moveSelectedParts(nPosition, bDuplicate);
}
static char* doc_getPartPageRectangles(LibreOfficeKitDocument* pThis)
{
comphelper::ProfileZone aZone("doc_getPartPageRectangles");
SolarMutexGuard aGuard;
SetLastExceptionMsg();
ITiledRenderable* pDoc = getTiledRenderable(pThis);
if (!pDoc)
{
SetLastExceptionMsg("Document doesn't support tiled rendering");
return nullptr;
}
return convertOUString(pDoc->getPartPageRectangles());
}
static char* doc_getPartName(LibreOfficeKitDocument* pThis, int nPart)
{
comphelper::ProfileZone aZone("doc_getPartName");
SolarMutexGuard aGuard;
SetLastExceptionMsg();
ITiledRenderable* pDoc = getTiledRenderable(pThis);
if (!pDoc)
{
SetLastExceptionMsg("Document doesn't support tiled rendering");
return nullptr;
}
return convertOUString(pDoc->getPartName(nPart));
}
static char* doc_getPartHash(LibreOfficeKitDocument* pThis, int nPart)
{
comphelper::ProfileZone aZone("doc_getPartHash");
SolarMutexGuard aGuard;
SetLastExceptionMsg();
ITiledRenderable* pDoc = getTiledRenderable(pThis);
if (!pDoc)
{
SetLastExceptionMsg("Document doesn't support tiled rendering");
return nullptr;
}
return convertOUString(pDoc->getPartHash(nPart));
}
static void doc_setPartMode(LibreOfficeKitDocument* pThis,
int nPartMode)
{
comphelper::ProfileZone aZone("doc_setPartMode");
SolarMutexGuard aGuard;
SetLastExceptionMsg();
ITiledRenderable* pDoc = getTiledRenderable(pThis);
if (!pDoc)
{
SetLastExceptionMsg("Document doesn't support tiled rendering");
return;
}
int nCurrentPart = pDoc->getPart();
pDoc->setPartMode(nPartMode);
// We need to make sure the internal state is updated, just changing the mode
// might not update the relevant shells (i.e. impress will keep rendering the
// previous mode unless we do this).
// TODO: we might want to do this within the relevant components rather than
// here, but that's also dependent on how we implement embedded object
// rendering I guess?
// TODO: we could be clever and e.g. set to 0 when we change to/from
// embedded object mode, and not when changing between slide/notes/combined
// modes?
if ( nCurrentPart < pDoc->getParts() )
{
pDoc->setPart( nCurrentPart );
}
else
{
pDoc->setPart( 0 );
}
}
static void doc_paintTile(LibreOfficeKitDocument* pThis,
unsigned char* pBuffer,
const int nCanvasWidth, const int nCanvasHeight,
const int nTilePosX, const int nTilePosY,
const int nTileWidth, const int nTileHeight)
{
comphelper::ProfileZone aZone("doc_paintTile");
SolarMutexGuard aGuard;
SetLastExceptionMsg();
SAL_INFO( "lok.tiledrendering", "paintTile: painting [" << nTileWidth << "x" << nTileHeight <<
"]@(" << nTilePosX << ", " << nTilePosY << ") to [" <<
nCanvasWidth << "x" << nCanvasHeight << "]px" );
ITiledRenderable* pDoc = getTiledRenderable(pThis);
if (!pDoc)
{
SetLastExceptionMsg("Document doesn't support tiled rendering");
return;
}
#if defined(UNX) && !defined(MACOSX) && !defined(ENABLE_HEADLESS)
// Painting of zoomed or HiDPI spreadsheets is special, we actually draw everything at 100%,
// and only set cairo's (or CoreGraphic's, in the iOS case) scale factor accordingly, so that
// everything is painted bigger or smaller. This is different to what Calc's internal scaling
// would do - because that one is trying to fit the lines between cells to integer multiples of
// pixels.
comphelper::ScopeGuard dpiScaleGuard([]() { comphelper::LibreOfficeKit::setDPIScale(1.0); });
#if defined(IOS)
double fDPIScaleX = 1.0;
paintTileIOS(pThis, pBuffer, nCanvasWidth, nCanvasHeight, fDPIScaleX, nTilePosX, nTilePosY, nTileWidth, nTileHeight);
#else
ScopedVclPtrInstance< VirtualDevice > pDevice(DeviceFormat::DEFAULT);
#if !defined(ANDROID) || HAVE_FEATURE_ANDROID_LOK
// Don't set the transparent background in the 'old' (JNI-based) Android
// app - no idea why it needs avoiding this.
// Set background to transparent by default.
pDevice->SetBackground(Wallpaper(COL_TRANSPARENT));
#endif
pDevice->SetOutputSizePixelScaleOffsetAndBuffer(
Size(nCanvasWidth, nCanvasHeight), Fraction(1.0), Point(),
pBuffer);
pDoc->paintTile(*pDevice, nCanvasWidth, nCanvasHeight,
nTilePosX, nTilePosY, nTileWidth, nTileHeight);
static bool bDebug = getenv("LOK_DEBUG_TILES") != nullptr;
if (bDebug)
{
// Draw a small red rectangle in the top left corner so that it's easy to see where a new tile begins.
tools::Rectangle aRect(0, 0, 5, 5);
aRect = pDevice->PixelToLogic(aRect);
pDevice->Push(PushFlags::FILLCOLOR | PushFlags::LINECOLOR);
pDevice->SetFillColor(COL_LIGHTRED);
pDevice->SetLineColor();
pDevice->DrawRect(aRect);
pDevice->Pop();
}
#endif
#else
(void) pBuffer;
#endif
}
#ifdef IOS
// This function is separate only to be used by LibreOfficeLight. If that app can be retired, this
// function's code can be inlined.
static void doc_paintTileToCGContext(LibreOfficeKitDocument* pThis,
void* rCGContext,
const int nCanvasWidth, const int nCanvasHeight,
const int nTilePosX, const int nTilePosY,
const int nTileWidth, const int nTileHeight)
{
SolarMutexGuard aGuard;
SetLastExceptionMsg();
SAL_INFO( "lok.tiledrendering", "paintTileToCGContext: painting [" << nTileWidth << "x" << nTileHeight <<
"]@(" << nTilePosX << ", " << nTilePosY << ") to [" <<
nCanvasWidth << "x" << nCanvasHeight << "]px" );
ITiledRenderable* pDoc = getTiledRenderable(pThis);
if (!pDoc)
{
SetLastExceptionMsg("Document doesn't support tiled rendering");
return;
}
Size aCanvasSize(nCanvasWidth, nCanvasHeight);
paintTileToCGContext(pDoc, rCGContext, aCanvasSize, nTilePosX, nTilePosY, nTileWidth, nTileHeight);
}
#endif
static void doc_paintPartTile(LibreOfficeKitDocument* pThis,
unsigned char* pBuffer,
const int nPart,
const int nCanvasWidth, const int nCanvasHeight,
const int nTilePosX, const int nTilePosY,
const int nTileWidth, const int nTileHeight)
{
comphelper::ProfileZone aZone("doc_paintPartTile");
SolarMutexGuard aGuard;
SetLastExceptionMsg();
SAL_INFO( "lok.tiledrendering", "paintPartTile: painting @ " << nPart << " ["
<< nTileWidth << "x" << nTileHeight << "]@("
<< nTilePosX << ", " << nTilePosY << ") to ["
<< nCanvasWidth << "x" << nCanvasHeight << "]px" );
LibLODocument_Impl* pDocument = static_cast<LibLODocument_Impl*>(pThis);
int nOrigViewId = doc_getView(pThis);
if (nOrigViewId < 0)
{
// tile painting always needs a SfxViewShell::Current(), but actually
// it does not really matter which one - all of them should paint the
// same thing. It's important to get a view for the correct document,
// though.
// doc_getViewsCount() returns the count of views for the document in the current view.
int viewCount = doc_getViewsCount(pThis);
if (viewCount == 0)
return;
std::vector<int> viewIds(viewCount);
doc_getViewIds(pThis, viewIds.data(), viewCount);
nOrigViewId = viewIds[0];
doc_setView(pThis, nOrigViewId);
}
// Disable callbacks while we are painting.
if (nOrigViewId >= 0)
{
const auto handlerIt = pDocument->mpCallbackFlushHandlers.find(nOrigViewId);
if (handlerIt != pDocument->mpCallbackFlushHandlers.end())
handlerIt->second->disableCallbacks();
}
try
{
// Text documents have a single coordinate system; don't change part.
int nOrigPart = 0;
const bool isText = (doc_getDocumentType(pThis) == LOK_DOCTYPE_TEXT);
int nViewId = nOrigViewId;
if (!isText)
{
// Check if just switching to another view is enough, that has
// less side-effects.
if (nPart != doc_getPart(pThis))
{
SfxViewShell* pViewShell = SfxViewShell::GetFirst();
while (pViewShell)
{
if (pViewShell->getPart() == nPart)
{
nViewId = static_cast<sal_Int32>(pViewShell->GetViewShellId());
doc_setView(pThis, nViewId);
break;
}
pViewShell = SfxViewShell::GetNext(*pViewShell);
}
}
nOrigPart = doc_getPart(pThis);
if (nPart != nOrigPart)
{
doc_setPart(pThis, nPart);
}
}
doc_paintTile(pThis, pBuffer, nCanvasWidth, nCanvasHeight, nTilePosX, nTilePosY, nTileWidth, nTileHeight);
if (!isText && nPart != nOrigPart)
{
doc_setPart(pThis, nOrigPart);
}
if (!isText && nViewId != nOrigViewId)
{
doc_setView(pThis, nOrigViewId);
}
}
catch (const std::exception&)
{
// Nothing to do but restore the PartTilePainting flag.
}
if (nOrigViewId >= 0)
{
const auto handlerIt = pDocument->mpCallbackFlushHandlers.find(nOrigViewId);
if (handlerIt != pDocument->mpCallbackFlushHandlers.end())
handlerIt->second->enableCallbacks();
}
}
static int doc_getTileMode(SAL_UNUSED_PARAMETER LibreOfficeKitDocument* /*pThis*/)
{
SetLastExceptionMsg();
return LOK_TILEMODE_BGRA;
}
static void doc_getDocumentSize(LibreOfficeKitDocument* pThis,
long* pWidth,
long* pHeight)
{
comphelper::ProfileZone aZone("doc_getDocumentSize");
SolarMutexGuard aGuard;
SetLastExceptionMsg();
ITiledRenderable* pDoc = getTiledRenderable(pThis);
if (pDoc)
{
Size aDocumentSize = pDoc->getDocumentSize();
*pWidth = aDocumentSize.Width();
*pHeight = aDocumentSize.Height();
}
else
{
SetLastExceptionMsg("Document doesn't support tiled rendering");
}
}
static void doc_initializeForRendering(LibreOfficeKitDocument* pThis,
const char* pArguments)
{
comphelper::ProfileZone aZone("doc_initializeForRendering");
SolarMutexGuard aGuard;
SetLastExceptionMsg();
ITiledRenderable* pDoc = getTiledRenderable(pThis);
if (pDoc)
{
doc_iniUnoCommands();
pDoc->initializeForTiledRendering(
comphelper::containerToSequence(jsonToPropertyValuesVector(pArguments)));
}
}
static void doc_registerCallback(LibreOfficeKitDocument* pThis,
LibreOfficeKitCallback pCallback,
void* pData)
{
SolarMutexGuard aGuard;
SetLastExceptionMsg();
LibLODocument_Impl* pDocument = static_cast<LibLODocument_Impl*>(pThis);
int nView = SfxLokHelper::getView();
if (nView < 0)
return;
if (pCallback != nullptr)
{
size_t nId = nView;
for (auto& pair : pDocument->mpCallbackFlushHandlers)
{
if (pair.first == nId)
continue;
pair.second->addViewStates(nView);
}
}
else
{
size_t nId = nView;
for (auto& pair : pDocument->mpCallbackFlushHandlers)
{
if (pair.first == nId)
continue;
pair.second->removeViewStates(nView);
}
}
pDocument->mpCallbackFlushHandlers[nView] = std::make_shared<CallbackFlushHandler>(pThis, pCallback, pData);
if (pCallback != nullptr)
{
size_t nId = nView;
for (const auto& pair : pDocument->mpCallbackFlushHandlers)
{
if (pair.first == nId)
continue;
pDocument->mpCallbackFlushHandlers[nView]->addViewStates(pair.first);
}
}
if (SfxViewShell* pViewShell = SfxViewShell::Current())
{
pViewShell->registerLibreOfficeKitViewCallback(CallbackFlushHandler::callback, pDocument->mpCallbackFlushHandlers[nView].get());
}
}
/// Returns the JSON representation of all the comments in the document
static char* getPostIts(LibreOfficeKitDocument* pThis)
{
SetLastExceptionMsg();
ITiledRenderable* pDoc = getTiledRenderable(pThis);
if (!pDoc)
{
SetLastExceptionMsg("Document doesn't support tiled rendering");
return nullptr;
}
tools::JsonWriter aJsonWriter;
pDoc->getPostIts(aJsonWriter);
return aJsonWriter.extractData();
}
/// Returns the JSON representation of the positions of all the comments in the document
static char* getPostItsPos(LibreOfficeKitDocument* pThis)
{
SetLastExceptionMsg();
ITiledRenderable* pDoc = getTiledRenderable(pThis);
if (!pDoc)
{
SetLastExceptionMsg("Document doesn't support tiled rendering");
return nullptr;
}
tools::JsonWriter aJsonWriter;
pDoc->getPostItsPos(aJsonWriter);
return aJsonWriter.extractData();
}
static char* getRulerState(LibreOfficeKitDocument* pThis)
{
SetLastExceptionMsg();
ITiledRenderable* pDoc = getTiledRenderable(pThis);
if (!pDoc)
{
SetLastExceptionMsg("Document doesn't support tiled rendering");
return nullptr;
}
tools::JsonWriter aJsonWriter;
pDoc->getRulerState(aJsonWriter);
return aJsonWriter.extractData();
}
static void doc_postKeyEvent(LibreOfficeKitDocument* pThis, int nType, int nCharCode, int nKeyCode)
{
comphelper::ProfileZone aZone("doc_postKeyEvent");
SolarMutexGuard aGuard;
SetLastExceptionMsg();
ITiledRenderable* pDoc = getTiledRenderable(pThis);
if (!pDoc)
{
SetLastExceptionMsg("Document doesn't support tiled rendering");
return;
}
try
{
pDoc->postKeyEvent(nType, nCharCode, nKeyCode);
}
catch (const uno::Exception& exception)
{
SetLastExceptionMsg(exception.Message);
SAL_INFO("lok", "Failed to postKeyEvent " << exception.Message);
}
}
static void doc_postWindowExtTextInputEvent(LibreOfficeKitDocument* pThis, unsigned nWindowId, int nType, const char* pText)
{
comphelper::ProfileZone aZone("doc_postWindowExtTextInputEvent");
SolarMutexGuard aGuard;
VclPtr<vcl::Window> pWindow;
if (nWindowId == 0)
{
ITiledRenderable* pDoc = getTiledRenderable(pThis);
if (!pDoc)
{
SetLastExceptionMsg("Document doesn't support tiled rendering");
return;
}
pWindow = pDoc->getDocWindow();
}
else
{
pWindow = vcl::Window::FindLOKWindow(nWindowId);
}
if (!pWindow)
{
SetLastExceptionMsg("No window found for window id: " + OUString::number(nWindowId));
return;
}
SfxLokHelper::postExtTextEventAsync(pWindow, nType, OUString::fromUtf8(OString(pText, strlen(pText))));
}
static void doc_removeTextContext(LibreOfficeKitDocument* pThis, unsigned nLOKWindowId, int nCharBefore, int nCharAfter)
{
SolarMutexGuard aGuard;
VclPtr<vcl::Window> pWindow;
if (nLOKWindowId == 0)
{
ITiledRenderable* pDoc = getTiledRenderable(pThis);
if (!pDoc)
{
gImpl->maLastExceptionMsg = "Document doesn't support tiled rendering";
return;
}
pWindow = pDoc->getDocWindow();
}
else
{
pWindow = vcl::Window::FindLOKWindow(nLOKWindowId);
}
if (!pWindow)
{
gImpl->maLastExceptionMsg = "No window found for window id: " + OUString::number(nLOKWindowId);
return;
}
// Annoyingly - backspace and delete are handled in the apps via an accelerator
// which are PostMessage'd by SfxViewShell::ExecKey_Impl so to stay in the same
// order we do this synchronously here, unless we're in a dialog.
if (nCharBefore > 0)
{
// backspace
if (nLOKWindowId == 0)
{
KeyEvent aEvt(8, 1283);
for (int i = 0; i < nCharBefore; ++i)
pWindow->KeyInput(aEvt);
}
else
SfxLokHelper::postKeyEventAsync(pWindow, LOK_KEYEVENT_KEYINPUT, 8, 1283, nCharBefore - 1);
}
if (nCharAfter > 0)
{
// delete (forward)
if (nLOKWindowId == 0)
{
KeyEvent aEvt(46, 1286);
for (int i = 0; i < nCharAfter; ++i)
pWindow->KeyInput(aEvt);
}
else
SfxLokHelper::postKeyEventAsync(pWindow, LOK_KEYEVENT_KEYINPUT, 46, 1286, nCharAfter - 1);
}
}
static void doc_postWindowKeyEvent(LibreOfficeKitDocument* /*pThis*/, unsigned nLOKWindowId, int nType, int nCharCode, int nKeyCode)
{
comphelper::ProfileZone aZone("doc_postWindowKeyEvent");
SolarMutexGuard aGuard;
SetLastExceptionMsg();
VclPtr<Window> pWindow = vcl::Window::FindLOKWindow(nLOKWindowId);
if (!pWindow)
{
SetLastExceptionMsg("Document doesn't support dialog rendering, or window not found.");
return;
}
KeyEvent aEvent(nCharCode, nKeyCode, 0);
switch (nType)
{
case LOK_KEYEVENT_KEYINPUT:
Application::PostKeyEvent(VclEventId::WindowKeyInput, pWindow, &aEvent);
break;
case LOK_KEYEVENT_KEYUP:
Application::PostKeyEvent(VclEventId::WindowKeyUp, pWindow, &aEvent);
break;
default:
assert(false);
break;
}
}
static size_t doc_renderShapeSelection(LibreOfficeKitDocument* pThis, char** pOutput)
{
comphelper::ProfileZone aZone("doc_renderShapeSelection");
SolarMutexGuard aGuard;
SetLastExceptionMsg();
LokChartHelper aChartHelper(SfxViewShell::Current());
if (aChartHelper.GetWindow())
return 0;
try
{
LibLODocument_Impl* pDocument = static_cast<LibLODocument_Impl*>(pThis);
uno::Reference<frame::XStorable> xStorable(pDocument->mxComponent, uno::UNO_QUERY_THROW);
SvMemoryStream aOutStream;
uno::Reference<io::XOutputStream> xOut = new utl::OOutputStreamWrapper(aOutStream);
utl::MediaDescriptor aMediaDescriptor;
switch (doc_getDocumentType(pThis))
{
case LOK_DOCTYPE_PRESENTATION:
aMediaDescriptor["FilterName"] <<= OUString("impress_svg_Export");
break;
case LOK_DOCTYPE_TEXT:
aMediaDescriptor["FilterName"] <<= OUString("writer_svg_Export");
break;
case LOK_DOCTYPE_SPREADSHEET:
aMediaDescriptor["FilterName"] <<= OUString("calc_svg_Export");
break;
default:
SAL_WARN("lok", "Failed to render shape selection: Document type is not supported");
}
aMediaDescriptor["SelectionOnly"] <<= true;
aMediaDescriptor["OutputStream"] <<= xOut;
xStorable->storeToURL("private:stream", aMediaDescriptor.getAsConstPropertyValueList());
if (pOutput)
{
const size_t nOutputSize = aOutStream.GetEndOfData();
*pOutput = static_cast<char*>(malloc(nOutputSize));
if (*pOutput)
{
std::memcpy(*pOutput, aOutStream.GetData(), nOutputSize);
return nOutputSize;
}
}
}
catch (const uno::Exception& exception)
{
css::uno::Any exAny( cppu::getCaughtException() );
SetLastExceptionMsg(exception.Message);
SAL_WARN("lok", "Failed to render shape selection: " << exceptionToString(exAny));
}
return 0;
}
namespace {
/** Class to react on finishing of a dispatched command.
This will call a LOK_COMMAND_FINISHED callback when postUnoCommand was
called with the parameter requesting the notification.
@see LibreOfficeKitCallbackType::LOK_CALLBACK_UNO_COMMAND_RESULT.
*/
class DispatchResultListener : public cppu::WeakImplHelper<css::frame::XDispatchResultListener>
{
OString maCommand; ///< Command for which this is the result.
std::shared_ptr<CallbackFlushHandler> mpCallback; ///< Callback to call.
public:
DispatchResultListener(const char* pCommand, std::shared_ptr<CallbackFlushHandler> const & pCallback)
: maCommand(pCommand)
, mpCallback(pCallback)
{
assert(mpCallback);
}
virtual void SAL_CALL dispatchFinished(const css::frame::DispatchResultEvent& rEvent) override
{
boost::property_tree::ptree aTree;
aTree.put("commandName", maCommand.getStr());
if (rEvent.State != frame::DispatchResultState::DONTKNOW)
{
bool bSuccess = (rEvent.State == frame::DispatchResultState::SUCCESS);
aTree.put("success", bSuccess);
}
aTree.add_child("result", unoAnyToPropertyTree(rEvent.Result));
std::stringstream aStream;
boost::property_tree::write_json(aStream, aTree);
OString aPayload = aStream.str().c_str();
mpCallback->queue(LOK_CALLBACK_UNO_COMMAND_RESULT, aPayload.getStr());
}
virtual void SAL_CALL disposing(const css::lang::EventObject&) override {}
};
} // anonymous namespace
static void doc_sendDialogEvent(LibreOfficeKitDocument* /*pThis*/, unsigned long long int nWindowId, const char* pArguments)
{
SolarMutexGuard aGuard;
StringMap aMap(jsonToStringMap(pArguments));
VclPtr<Window> pWindow = vcl::Window::FindLOKWindow(nWindowId);
if (!pWindow && nWindowId >= 1000000000 /* why unsigned? */)
pWindow = getSidebarWindow();
if (aMap.find("id") == aMap.end())
return;
static constexpr OUStringLiteral sClickAction(u"CLICK");
static constexpr OUStringLiteral sSelectAction(u"SELECT");
static constexpr OUStringLiteral sClearAction(u"CLEAR");
static constexpr OUStringLiteral sTypeAction(u"TYPE");
static constexpr OUStringLiteral sUpAction(u"UP");
static constexpr OUStringLiteral sDownAction(u"DOWN");
static constexpr OUStringLiteral sValue(u"VALUE");
bool bIsWeldedDialog = false;
try
{
OString sControlId = OUStringToOString(aMap["id"], RTL_TEXTENCODING_ASCII_US);
bIsWeldedDialog = jsdialog::ExecuteAction(nWindowId, sControlId, aMap);
if (!bIsWeldedDialog)
bIsWeldedDialog = jsdialog::ExecuteAction(reinterpret_cast<sal_uInt64>(SfxViewShell::Current()),
sControlId, aMap);
if (!pWindow)
{
SetLastExceptionMsg("Document doesn't support dialog rendering, or window not found.");
return;
}
if (!bIsWeldedDialog)
{
WindowUIObject aUIObject(pWindow);
std::unique_ptr<UIObject> pUIWindow(aUIObject.get_visible_child(aMap["id"]));
if (pUIWindow) {
bool bIsClickAction = false;
if (aMap.find("cmd") != aMap.end()) {
if (aMap["cmd"] == "selected")
{
aMap["POS"] = aMap["data"];
aMap["TEXT"] = aMap["data"];
pUIWindow->execute(sSelectAction, aMap);
}
else if (aMap["cmd"] == "plus")
{
pUIWindow->execute(sUpAction, aMap);
}
else if (aMap["cmd"] == "minus")
{
pUIWindow->execute(sDownAction, aMap);
}
else if (aMap["cmd"] == "set")
{
aMap["TEXT"] = aMap["data"];
pUIWindow->execute(sClearAction, aMap);
pUIWindow->execute(sTypeAction, aMap);
}
else if (aMap["cmd"] == "value")
{
aMap["VALUE"] = aMap["data"];
pUIWindow->execute(sValue, aMap);
}
else
bIsClickAction = true;
}
else
bIsClickAction = true;
if (bIsClickAction)
pUIWindow->execute(sClickAction, aMap);
}
}
} catch(...) {}
// force resend
if (!bIsWeldedDialog)
pWindow->Resize();
}
static void doc_postUnoCommand(LibreOfficeKitDocument* pThis, const char* pCommand, const char* pArguments, bool bNotifyWhenFinished)
{
comphelper::ProfileZone aZone("doc_postUnoCommand");
SolarMutexGuard aGuard;
SetLastExceptionMsg();
SfxObjectShell* pDocSh = SfxObjectShell::Current();
OUString aCommand(pCommand, strlen(pCommand), RTL_TEXTENCODING_UTF8);
LibLODocument_Impl* pDocument = static_cast<LibLODocument_Impl*>(pThis);
std::vector<beans::PropertyValue> aPropertyValuesVector(jsonToPropertyValuesVector(pArguments));
if (!vcl::lok::isUnipoll())
{
beans::PropertyValue aSynchronMode;
aSynchronMode.Name = "SynchronMode";
aSynchronMode.Value <<= false;
aPropertyValuesVector.push_back(aSynchronMode);
}
int nView = SfxLokHelper::getView();
if (nView < 0)
return;
if (gImpl && aCommand == ".uno:ToggleOrientation")
{
ExecuteOrientationChange();
return;
}
// handle potential interaction
if (gImpl && aCommand == ".uno:Save")
{
// Check if saving a PDF file
OUString aMimeType = lcl_getCurrentDocumentMimeType(pDocument);
if (aMimeType == "application/pdf")
{
// If we have a PDF file (for saving annotations for example), we need
// to run save-as to the same file as the opened document. Plain save
// doesn't work as the PDF is not a "native" format.
uno::Reference<frame::XStorable> xStorable(pDocument->mxComponent, uno::UNO_QUERY_THROW);
OUString aURL = xStorable->getLocation();
OString aURLUtf8 = OUStringToOString(aURL, RTL_TEXTENCODING_UTF8);
bool bResult = doc_saveAs(pThis, aURLUtf8.getStr(), "pdf", nullptr);
// Send the result of save
boost::property_tree::ptree aTree;
aTree.put("commandName", pCommand);
aTree.put("success", bResult);
std::stringstream aStream;
boost::property_tree::write_json(aStream, aTree);
OString aPayload = aStream.str().c_str();
pDocument->mpCallbackFlushHandlers[nView]->queue(LOK_CALLBACK_UNO_COMMAND_RESULT, aPayload.getStr());
return;
}
rtl::Reference<LOKInteractionHandler> const pInteraction(
new LOKInteractionHandler("save", gImpl, pDocument));
uno::Reference<task::XInteractionHandler2> const xInteraction(pInteraction.get());
beans::PropertyValue aValue;
aValue.Name = "InteractionHandler";
aValue.Value <<= xInteraction;
aPropertyValuesVector.push_back(aValue);
bool bDontSaveIfUnmodified = false;
aPropertyValuesVector.erase(std::remove_if(aPropertyValuesVector.begin(),
aPropertyValuesVector.end(),
[&bDontSaveIfUnmodified](const beans::PropertyValue& aItem){
if (aItem.Name == "DontSaveIfUnmodified")
{
bDontSaveIfUnmodified = aItem.Value.get<bool>();
return true;
}
return false;
}), aPropertyValuesVector.end());
// skip saving and tell the result via UNO_COMMAND_RESULT
if (bDontSaveIfUnmodified && !pDocSh->IsModified())
{
boost::property_tree::ptree aTree;
aTree.put("commandName", pCommand);
aTree.put("success", false);
// Add the reason for not saving
const uno::Any aResultValue = uno::makeAny(OUString("unmodified"));
aTree.add_child("result", unoAnyToPropertyTree(aResultValue));
std::stringstream aStream;
boost::property_tree::write_json(aStream, aTree);
OString aPayload = aStream.str().c_str();
pDocument->mpCallbackFlushHandlers[nView]->queue(LOK_CALLBACK_UNO_COMMAND_RESULT, aPayload.getStr());
return;
}
}
else if (gImpl && aCommand == ".uno:TransformDialog")
{
bool bNeedConversion = false;
SfxViewShell* pViewShell = SfxViewShell::Current();
LokChartHelper aChartHelper(pViewShell);
if (aChartHelper.GetWindow() )
{
bNeedConversion = true;
}
else if (const SdrView* pView = pViewShell->GetDrawView())
{
if (OutputDevice* pOutputDevice = pView->GetFirstOutputDevice())
{
bNeedConversion = (pOutputDevice->GetMapMode().GetMapUnit() == MapUnit::Map100thMM);
}
}
if (bNeedConversion)
{
sal_Int32 value;
for (beans::PropertyValue& rPropValue: aPropertyValuesVector)
{
if (rPropValue.Name == "TransformPosX"
|| rPropValue.Name == "TransformPosY"
|| rPropValue.Name == "TransformWidth"
|| rPropValue.Name == "TransformHeight"
|| rPropValue.Name == "TransformRotationX"
|| rPropValue.Name == "TransformRotationY")
{
rPropValue.Value >>= value;
value = OutputDevice::LogicToLogic(value, MapUnit::MapTwip, MapUnit::Map100thMM);
rPropValue.Value <<= value;
}
}
}
if (aChartHelper.GetWindow() && aPropertyValuesVector.size() > 0)
{
if (aPropertyValuesVector[0].Name != "Action")
{
tools::Rectangle aChartBB = aChartHelper.GetChartBoundingBox();
int nLeft = OutputDevice::LogicToLogic(aChartBB.Left(), MapUnit::MapTwip, MapUnit::Map100thMM);
int nTop = OutputDevice::LogicToLogic(aChartBB.Top(), MapUnit::MapTwip, MapUnit::Map100thMM);
for (beans::PropertyValue& rPropValue: aPropertyValuesVector)
{
if (rPropValue.Name == "TransformPosX" || rPropValue.Name == "TransformRotationX")
{
auto const value = *o3tl::doAccess<sal_Int32>(rPropValue.Value);
rPropValue.Value <<= value - nLeft;
}
else if (rPropValue.Name == "TransformPosY" || rPropValue.Name == "TransformRotationY")
{
auto const value = *o3tl::doAccess<sal_Int32>(rPropValue.Value);
rPropValue.Value <<= value - nTop;
}
}
}
util::URL aCommandURL;
aCommandURL.Path = "LOKTransform";
css::uno::Reference<css::frame::XDispatch>& aChartDispatcher = aChartHelper.GetXDispatcher();
aChartDispatcher->dispatch(aCommandURL, comphelper::containerToSequence(aPropertyValuesVector));
return;
}
}
else if (gImpl && aCommand == ".uno:LOKSidebarWriterPage")
{
setupSidebar("WriterPageDeck");
return;
}
else if (gImpl && aCommand == ".uno:SidebarShow")
{
setupSidebar();
return;
}
else if (gImpl && aCommand == ".uno:SidebarHide")
{
hideSidebar();
return;
}
bool bResult = false;
LokChartHelper aChartHelper(SfxViewShell::Current());
if (aChartHelper.GetWindow() && aCommand != ".uno:Save" )
{
util::URL aCommandURL;
aCommandURL.Path = aCommand.copy(5);
css::uno::Reference<css::frame::XDispatch>& aChartDispatcher = aChartHelper.GetXDispatcher();
aChartDispatcher->dispatch(aCommandURL, comphelper::containerToSequence(aPropertyValuesVector));
return;
}
else if (bNotifyWhenFinished && pDocument->mpCallbackFlushHandlers.count(nView))
{
bResult = comphelper::dispatchCommand(aCommand, comphelper::containerToSequence(aPropertyValuesVector),
new DispatchResultListener(pCommand, pDocument->mpCallbackFlushHandlers[nView]));
}
else
bResult = comphelper::dispatchCommand(aCommand, comphelper::containerToSequence(aPropertyValuesVector));
if (!bResult)
{
SetLastExceptionMsg("Failed to dispatch " + aCommand);
}
}
static void doc_postMouseEvent(LibreOfficeKitDocument* pThis, int nType, int nX, int nY, int nCount, int nButtons, int nModifier)
{
comphelper::ProfileZone aZone("doc_postMouseEvent");
SolarMutexGuard aGuard;
SetLastExceptionMsg();
ITiledRenderable* pDoc = getTiledRenderable(pThis);
if (!pDoc)
{
SetLastExceptionMsg("Document doesn't support tiled rendering");
return;
}
try
{
pDoc->postMouseEvent(nType, nX, nY, nCount, nButtons, nModifier);
}
catch (const uno::Exception& exception)
{
SetLastExceptionMsg(exception.Message);
SAL_INFO("lok", "Failed to postMouseEvent " << exception.Message);
}
}
static void doc_postWindowMouseEvent(LibreOfficeKitDocument* /*pThis*/, unsigned nLOKWindowId, int nType, int nX, int nY, int nCount, int nButtons, int nModifier)
{
comphelper::ProfileZone aZone("doc_postWindowMouseEvent");
SolarMutexGuard aGuard;
SetLastExceptionMsg();
VclPtr<Window> pWindow = vcl::Window::FindLOKWindow(nLOKWindowId);
if (!pWindow)
{
SetLastExceptionMsg("Document doesn't support dialog rendering, or window not found.");
return;
}
const Point aPos(nX, nY);
MouseEvent aEvent(aPos, nCount, MouseEventModifiers::SIMPLECLICK, nButtons, nModifier);
vcl::EnableDialogInput(pWindow);
switch (nType)
{
case LOK_MOUSEEVENT_MOUSEBUTTONDOWN:
Application::PostMouseEvent(VclEventId::WindowMouseButtonDown, pWindow, &aEvent);
break;
case LOK_MOUSEEVENT_MOUSEBUTTONUP:
Application::PostMouseEvent(VclEventId::WindowMouseButtonUp, pWindow, &aEvent);
break;
case LOK_MOUSEEVENT_MOUSEMOVE:
Application::PostMouseEvent(VclEventId::WindowMouseMove, pWindow, &aEvent);
break;
default:
assert(false);
break;
}
}
static void doc_postWindowGestureEvent(LibreOfficeKitDocument* /*pThis*/, unsigned nLOKWindowId, const char* pType, int nX, int nY, int nOffset)
{
comphelper::ProfileZone aZone("doc_postWindowGestureEvent");
SolarMutexGuard aGuard;
SetLastExceptionMsg();
VclPtr<Window> pWindow = vcl::Window::FindLOKWindow(nLOKWindowId);
if (!pWindow)
{
SetLastExceptionMsg("Document doesn't support dialog rendering, or window not found.");
return;
}
OString aType(pType);
GestureEventType eEventType = GestureEventType::PanningUpdate;
if (aType == "panBegin")
eEventType = GestureEventType::PanningBegin;
else if (aType == "panEnd")
eEventType = GestureEventType::PanningEnd;
GestureEvent aEvent {
sal_Int32(nX),
sal_Int32(nY),
eEventType,
sal_Int32(nOffset),
PanningOrientation::Vertical,
};
vcl::EnableDialogInput(pWindow);
Application::PostGestureEvent(VclEventId::WindowGestureEvent, pWindow, &aEvent);
}
static void doc_setTextSelection(LibreOfficeKitDocument* pThis, int nType, int nX, int nY)
{
comphelper::ProfileZone aZone("doc_setTextSelection");
SolarMutexGuard aGuard;
SetLastExceptionMsg();
ITiledRenderable* pDoc = getTiledRenderable(pThis);
if (!pDoc)
{
SetLastExceptionMsg("Document doesn't support tiled rendering");
return;
}
pDoc->setTextSelection(nType, nX, nY);
}
static void doc_setWindowTextSelection(LibreOfficeKitDocument* /*pThis*/, unsigned nLOKWindowId, bool swap, int nX, int nY)
{
comphelper::ProfileZone aZone("doc_setWindowTextSelection");
SolarMutexGuard aGuard;
SetLastExceptionMsg();
VclPtr<Window> pWindow = vcl::Window::FindLOKWindow(nLOKWindowId);
if (!pWindow)
{
SetLastExceptionMsg("Document doesn't support dialog rendering, or window not found.");
return;
}
Size aOffset(pWindow->GetOutOffXPixel(), pWindow->GetOutOffYPixel());
Point aCursorPos(nX, nY);
aCursorPos.Move(aOffset);
sal_uInt16 nModifier = swap ? KEY_MOD1 + KEY_MOD2 : KEY_SHIFT;
MouseEvent aCursorEvent(aCursorPos, 1, MouseEventModifiers::SIMPLECLICK, 0, nModifier);
Application::PostMouseEvent(VclEventId::WindowMouseButtonDown, pWindow, &aCursorEvent);
Application::PostMouseEvent(VclEventId::WindowMouseButtonUp, pWindow, &aCursorEvent);
}
static bool getFromTransferrable(
const css::uno::Reference<css::datatransfer::XTransferable> &xTransferable,
const OString &aInMimeType, OString &aRet);
static bool encodeImageAsHTML(
const css::uno::Reference<css::datatransfer::XTransferable> &xTransferable,
const OString &aMimeType, OString &aRet)
{
if (!getFromTransferrable(xTransferable, aMimeType, aRet))
return false;
// Encode in base64.
auto aSeq = Sequence<sal_Int8>(reinterpret_cast<const sal_Int8*>(aRet.getStr()),
aRet.getLength());
OUStringBuffer aBase64Data;
comphelper::Base64::encode(aBase64Data, aSeq);
// Embed in HTML.
aRet = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\n"
"<html><head>"
"<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\"/><meta "
"name=\"generator\" content=\""
+ getGenerator().toUtf8()
+ "\"/>"
"</head><body><img src=\"data:" + aMimeType + ";base64,"
+ aBase64Data.makeStringAndClear().toUtf8() + "\"/></body></html>";
return true;
}
static bool encodeTextAsHTML(
const css::uno::Reference<css::datatransfer::XTransferable> &xTransferable,
const OString &aMimeType, OString &aRet)
{
if (!getFromTransferrable(xTransferable, aMimeType, aRet))
return false;
// Embed in HTML - FIXME: needs some escaping.
aRet = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\n"
"<html><head>"
"<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\"/><meta "
"name=\"generator\" content=\""
+ getGenerator().toUtf8()
+ "\"/></head><body><pre>" + aRet + "</pre></body></html>";
return true;
}
static bool getFromTransferrable(
const css::uno::Reference<css::datatransfer::XTransferable> &xTransferable,
const OString &aInMimeType, OString &aRet)
{
OString aMimeType(aInMimeType);
// Take care of UTF-8 text here.
bool bConvert = false;
sal_Int32 nIndex = 0;
if (aMimeType.getToken(0, ';', nIndex) == "text/plain")
{
if (aMimeType.getToken(0, ';', nIndex) == "charset=utf-8")
{
aMimeType = "text/plain;charset=utf-16";
bConvert = true;
}
}
datatransfer::DataFlavor aFlavor;
aFlavor.MimeType = OUString::fromUtf8(aMimeType.getStr());
if (aMimeType == "text/plain;charset=utf-16")
aFlavor.DataType = cppu::UnoType<OUString>::get();
else
aFlavor.DataType = cppu::UnoType< uno::Sequence<sal_Int8> >::get();
if (!xTransferable->isDataFlavorSupported(aFlavor))
{
// Try harder for HTML it is our copy/paste meta-file format
if (aInMimeType == "text/html")
{
// Desperate measures - convert text to HTML instead.
if (encodeTextAsHTML(xTransferable, "text/plain;charset=utf-8", aRet))
return true;
// If html is not supported, might be a graphic-selection,
if (encodeImageAsHTML(xTransferable, "image/png", aRet))
return true;
}
SetLastExceptionMsg("Flavor " + aFlavor.MimeType + " is not supported");
return false;
}
uno::Any aAny;
try
{
aAny = xTransferable->getTransferData(aFlavor);
}
catch (const css::datatransfer::UnsupportedFlavorException& e)
{
SetLastExceptionMsg("Unsupported flavor " + aFlavor.MimeType + " exception " + e.Message);
return false;
}
catch (const css::uno::Exception& e)
{
SetLastExceptionMsg("Exception getting " + aFlavor.MimeType + " exception " + e.Message);
return false;
}
if (aFlavor.DataType == cppu::UnoType<OUString>::get())
{
OUString aString;
aAny >>= aString;
if (bConvert)
aRet = OUStringToOString(aString, RTL_TEXTENCODING_UTF8);
else
aRet = OString(reinterpret_cast<const char *>(aString.getStr()), aString.getLength() * sizeof(sal_Unicode));
}
else
{
uno::Sequence<sal_Int8> aSequence;
aAny >>= aSequence;
aRet = OString(reinterpret_cast<char*>(aSequence.getArray()), aSequence.getLength());
}
return true;
}
static char* doc_getTextSelection(LibreOfficeKitDocument* pThis, const char* pMimeType, char** pUsedMimeType)
{
comphelper::ProfileZone aZone("doc_getTextSelection");
SolarMutexGuard aGuard;
SetLastExceptionMsg();
ITiledRenderable* pDoc = getTiledRenderable(pThis);
if (!pDoc)
{
SetLastExceptionMsg("Document doesn't support tiled rendering");
return nullptr;
}
css::uno::Reference<css::datatransfer::XTransferable> xTransferable = pDoc->getSelection();
if (!xTransferable)
{
SetLastExceptionMsg("No selection available");
return nullptr;
}
const char *pType = pMimeType;
if (!pType || pType[0] == '\0')
pType = "text/plain;charset=utf-8";
OString aRet;
bool bSuccess = getFromTransferrable(xTransferable, OString(pType), aRet);
if (!bSuccess)
return nullptr;
if (pUsedMimeType) // legacy
{
if (pMimeType)
*pUsedMimeType = strdup(pMimeType);
else
*pUsedMimeType = nullptr;
}
return convertOString(aRet);
}
static int doc_getSelectionType(LibreOfficeKitDocument* pThis)
{
comphelper::ProfileZone aZone("doc_getSelectionType");
SolarMutexGuard aGuard;
SetLastExceptionMsg();
ITiledRenderable* pDoc = getTiledRenderable(pThis);
if (!pDoc)
{
SetLastExceptionMsg("Document doesn't support tiled rendering");
return LOK_SELTYPE_NONE;
}
css::uno::Reference<css::datatransfer::XTransferable2> xTransferable(pDoc->getSelection(), css::uno::UNO_QUERY);
if (!xTransferable)
{
SetLastExceptionMsg("No selection available");
return LOK_SELTYPE_NONE;
}
if (xTransferable->isComplex())
return LOK_SELTYPE_COMPLEX;
OString aRet;
bool bSuccess = getFromTransferrable(xTransferable, "text/plain;charset=utf-8", aRet);
if (!bSuccess)
return LOK_SELTYPE_NONE;
if (aRet.getLength() > 10000)
return LOK_SELTYPE_COMPLEX;
return aRet.getLength() ? LOK_SELTYPE_TEXT : LOK_SELTYPE_NONE;
}
static int doc_getClipboard(LibreOfficeKitDocument* pThis,
const char **pMimeTypes,
size_t *pOutCount,
char ***pOutMimeTypes,
size_t **pOutSizes,
char ***pOutStreams)
{
comphelper::ProfileZone aZone("doc_getClipboard");
SolarMutexGuard aGuard;
SetLastExceptionMsg();
assert (pOutCount);
assert (pOutMimeTypes);
assert (pOutSizes);
assert (pOutStreams);
*pOutCount = 0;
*pOutMimeTypes = nullptr;
*pOutSizes = nullptr;
*pOutStreams = nullptr;
ITiledRenderable* pDoc = getTiledRenderable(pThis);
if (!pDoc)
{
SetLastExceptionMsg("Document doesn't support tiled rendering");
return 0;
}
rtl::Reference<LOKClipboard> xClip(LOKClipboardFactory::getClipboardForCurView());
css::uno::Reference<css::datatransfer::XTransferable> xTransferable = xClip->getContents();
SAL_INFO("lok", "Got from clip: " << xClip.get() << " transferrable: " << xTransferable);
if (!xTransferable)
{
SetLastExceptionMsg("No clipboard content available");
return 0;
}
std::vector<OString> aMimeTypes;
if (!pMimeTypes) // everything
{
const uno::Sequence< css::datatransfer::DataFlavor > flavors = xTransferable->getTransferDataFlavors();
if (!flavors.getLength())
{
SetLastExceptionMsg("Flavourless selection");
return 0;
}
for (const auto &it : flavors)
aMimeTypes.push_back(OUStringToOString(it.MimeType, RTL_TEXTENCODING_UTF8));
}
else
{
for (size_t i = 0; pMimeTypes[i]; ++i)
aMimeTypes.push_back(OString(pMimeTypes[i]));
}
*pOutCount = aMimeTypes.size();
*pOutSizes = static_cast<size_t *>(malloc(*pOutCount * sizeof(size_t)));
*pOutMimeTypes = static_cast<char **>(malloc(*pOutCount * sizeof(char *)));
*pOutStreams = static_cast<char **>(malloc(*pOutCount * sizeof(char *)));
for (size_t i = 0; i < aMimeTypes.size(); ++i)
{
if (aMimeTypes[i] == "text/plain;charset=utf-16")
(*pOutMimeTypes)[i] = strdup("text/plain;charset=utf-8");
else
(*pOutMimeTypes)[i] = strdup(aMimeTypes[i].getStr());
OString aRet;
bool bSuccess = getFromTransferrable(xTransferable, (*pOutMimeTypes)[i], aRet);
if (!bSuccess || aRet.getLength() < 1)
{
(*pOutSizes)[i] = 0;
(*pOutStreams)[i] = nullptr;
}
else
{
(*pOutSizes)[i] = aRet.getLength();
(*pOutStreams)[i] = convertOString(aRet);
}
}
return 1;
}
static int doc_setClipboard(LibreOfficeKitDocument* pThis,
const size_t nInCount,
const char **pInMimeTypes,
const size_t *pInSizes,
const char **pInStreams)
{
#ifdef IOS
(void) pThis;
(void) nInCount;
(void) pInMimeTypes;
(void) pInSizes;
(void) pInStreams;
#else
comphelper::ProfileZone aZone("doc_setClipboard");
SolarMutexGuard aGuard;
SetLastExceptionMsg();
ITiledRenderable* pDoc = getTiledRenderable(pThis);
if (!pDoc)
{
SetLastExceptionMsg("Document doesn't support tiled rendering");
return false;
}
uno::Reference<datatransfer::XTransferable> xTransferable(new LOKTransferable(nInCount, pInMimeTypes, pInSizes, pInStreams));
auto xClip = forceSetClipboardForCurrentView(pThis);
xClip->setContents(xTransferable, uno::Reference<datatransfer::clipboard::XClipboardOwner>());
SAL_INFO("lok", "Set clip: " << xClip.get() << " to: " << xTransferable);
if (!pDoc->isMimeTypeSupported())
{
SetLastExceptionMsg("Document doesn't support this mime type");
return false;
}
#endif
return true;
}
static bool doc_paste(LibreOfficeKitDocument* pThis, const char* pMimeType, const char* pData, size_t nSize)
{
comphelper::ProfileZone aZone("doc_paste");
SolarMutexGuard aGuard;
const char *pInMimeTypes[1];
const char *pInStreams[1];
size_t pInSizes[1];
pInMimeTypes[0] = pMimeType;
pInSizes[0] = nSize;
pInStreams[0] = pData;
if (!doc_setClipboard(pThis, 1, pInMimeTypes, pInSizes, pInStreams))
return false;
uno::Sequence<beans::PropertyValue> aPropertyValues(comphelper::InitPropertySequence(
{
{"AnchorType", uno::makeAny(static_cast<sal_uInt16>(text::TextContentAnchorType_AS_CHARACTER))},
{"IgnoreComments", uno::makeAny(true)},
}));
if (!comphelper::dispatchCommand(".uno:Paste", aPropertyValues))
{
SetLastExceptionMsg("Failed to dispatch the .uno: command");
return false;
}
return true;
}
static void doc_setGraphicSelection(LibreOfficeKitDocument* pThis, int nType, int nX, int nY)
{
comphelper::ProfileZone aZone("doc_setGraphicSelection");
SolarMutexGuard aGuard;
SetLastExceptionMsg();
ITiledRenderable* pDoc = getTiledRenderable(pThis);
if (!pDoc)
{
SetLastExceptionMsg("Document doesn't support tiled rendering");
return;
}
pDoc->setGraphicSelection(nType, nX, nY);
}
static void doc_resetSelection(LibreOfficeKitDocument* pThis)
{
comphelper::ProfileZone aZone("doc_resetSelection");
SolarMutexGuard aGuard;
SetLastExceptionMsg();
ITiledRenderable* pDoc = getTiledRenderable(pThis);
if (!pDoc)
{
SetLastExceptionMsg("Document doesn't support tiled rendering");
return;
}
pDoc->resetSelection();
}
static char* getLanguages(const char* pCommand)
{
css::uno::Sequence< css::lang::Locale > aLocales;
if (xContext.is())
{
css::uno::Reference<css::linguistic2::XLinguServiceManager2> xLangSrv = css::linguistic2::LinguServiceManager::create(xContext);
if (xLangSrv.is())
{
css::uno::Reference<css::linguistic2::XSpellChecker> xSpell = xLangSrv->getSpellChecker();
if (xSpell.is())
aLocales = xSpell->getLocales();
}
}
boost::property_tree::ptree aTree;
aTree.put("commandName", pCommand);
boost::property_tree::ptree aValues;
boost::property_tree::ptree aChild;
OUString sLanguage;
for ( css::lang::Locale const & locale : std::as_const(aLocales) )
{
const LanguageTag aLanguageTag( locale );
sLanguage = SvtLanguageTable::GetLanguageString(aLanguageTag.getLanguageType());
if (sLanguage.startsWith("{") && sLanguage.endsWith("}"))
continue;
sLanguage += ";" + aLanguageTag.getBcp47(false);
aChild.put("", sLanguage.toUtf8());
aValues.push_back(std::make_pair("", aChild));
}
aTree.add_child("commandValues", aValues);
std::stringstream aStream;
boost::property_tree::write_json(aStream, aTree);
char* pJson = static_cast<char*>(malloc(aStream.str().size() + 1));
assert(pJson); // Don't handle OOM conditions
strcpy(pJson, aStream.str().c_str());
pJson[aStream.str().size()] = '\0';
return pJson;
}
static char* getFonts (const char* pCommand)
{
SfxObjectShell* pDocSh = SfxObjectShell::Current();
const SvxFontListItem* pFonts = static_cast<const SvxFontListItem*>(
pDocSh->GetItem(SID_ATTR_CHAR_FONTLIST));
const FontList* pList = pFonts ? pFonts->GetFontList() : nullptr;
boost::property_tree::ptree aTree;
aTree.put("commandName", pCommand);
boost::property_tree::ptree aValues;
if ( pList )
{
sal_uInt16 nFontCount = pList->GetFontNameCount();
for (sal_uInt16 i = 0; i < nFontCount; ++i)
{
boost::property_tree::ptree aChildren;
const FontMetric& rFontMetric = pList->GetFontName(i);
const int* pAry = pList->GetSizeAry(rFontMetric);
sal_uInt16 nSizeCount = 0;
while (pAry[nSizeCount])
{
boost::property_tree::ptree aChild;
aChild.put("", static_cast<float>(pAry[nSizeCount]) / 10);
aChildren.push_back(std::make_pair("", aChild));
nSizeCount++;
}
aValues.add_child(rFontMetric.GetFamilyName().toUtf8().getStr(), aChildren);
}
}
aTree.add_child("commandValues", aValues);
std::stringstream aStream;
boost::property_tree::write_json(aStream, aTree);
char* pJson = static_cast<char*>(malloc(aStream.str().size() + 1));
assert(pJson); // Don't handle OOM conditions
strcpy(pJson, aStream.str().c_str());
pJson[aStream.str().size()] = '\0';
return pJson;
}
static char* getFontSubset (const OString& aFontName)
{
OUString aFoundFont(::rtl::Uri::decode(OStringToOUString(aFontName, RTL_TEXTENCODING_UTF8), rtl_UriDecodeStrict, RTL_TEXTENCODING_UTF8));
SfxObjectShell* pDocSh = SfxObjectShell::Current();
const SvxFontListItem* pFonts = static_cast<const SvxFontListItem*>(
pDocSh->GetItem(SID_ATTR_CHAR_FONTLIST));
const FontList* pList = pFonts ? pFonts->GetFontList() : nullptr;
boost::property_tree::ptree aTree;
aTree.put("commandName", ".uno:FontSubset");
boost::property_tree::ptree aValues;
if ( pList && !aFoundFont.isEmpty() )
{
sal_uInt16 nFontCount = pList->GetFontNameCount();
sal_uInt16 nItFont = 0;
for (; nItFont < nFontCount; ++nItFont)
{
if (aFoundFont == pList->GetFontName(nItFont).GetFamilyName())
{
break;
}
}
if ( nItFont < nFontCount )
{
FontCharMapRef xFontCharMap (new FontCharMap());
auto aDevice(VclPtr<VirtualDevice>::Create(DeviceFormat::DEFAULT));
const vcl::Font& aFont(pList->GetFontName(nItFont));
aDevice->SetFont(aFont);
aDevice->GetFontCharMap(xFontCharMap);
SubsetMap aSubMap(xFontCharMap);
for (auto const& subset : aSubMap.GetSubsetMap())
{
boost::property_tree::ptree aChild;
aChild.put("", static_cast<int>(ublock_getCode(subset.GetRangeMin())));
aValues.push_back(std::make_pair("", aChild));
}
}
}
aTree.add_child("commandValues", aValues);
std::stringstream aStream;
boost::property_tree::write_json(aStream, aTree);
char* pJson = static_cast<char*>(malloc(aStream.str().size() + 1));
assert(pJson); // Don't handle OOM conditions
strcpy(pJson, aStream.str().c_str());
pJson[aStream.str().size()] = '\0';
return pJson;
}
static char* getStyles(LibreOfficeKitDocument* pThis, const char* pCommand)
{
LibLODocument_Impl* pDocument = static_cast<LibLODocument_Impl*>(pThis);
boost::property_tree::ptree aTree;
aTree.put("commandName", pCommand);
uno::Reference<css::style::XStyleFamiliesSupplier> xStyleFamiliesSupplier(pDocument->mxComponent, uno::UNO_QUERY);
const uno::Reference<container::XNameAccess> xStyleFamilies = xStyleFamiliesSupplier->getStyleFamilies();
const uno::Sequence<OUString> aStyleFamilies = xStyleFamilies->getElementNames();
static const std::vector<OUString> aWriterStyles =
{
"Text body",
"Quotations",
"Title",
"Subtitle",
"Heading 1",
"Heading 2",
"Heading 3"
};
// We need to keep a list of the default style names
// in order to filter these out later when processing
// the full list of styles.
std::set<OUString> aDefaultStyleNames;
boost::property_tree::ptree aValues;
for (OUString const & sStyleFam : aStyleFamilies)
{
boost::property_tree::ptree aChildren;
uno::Reference<container::XNameAccess> xStyleFamily(xStyleFamilies->getByName(sStyleFam), uno::UNO_QUERY);
// Writer provides a huge number of styles, we have a list of 7 "default" styles which
// should be shown in the normal dropdown, which we should add to the start of the list
// to simplify their selection.
if (sStyleFam == "ParagraphStyles"
&& doc_getDocumentType(pThis) == LOK_DOCTYPE_TEXT)
{
for (const OUString& rStyle: aWriterStyles)
{
aDefaultStyleNames.insert( rStyle );
boost::property_tree::ptree aChild;
aChild.put("", rStyle.toUtf8());
aChildren.push_back(std::make_pair("", aChild));
}
}
const uno::Sequence<OUString> aStyles = xStyleFamily->getElementNames();
for (const OUString& rStyle: aStyles )
{
// Filter out the default styles - they are already at the top
// of the list
if (aDefaultStyleNames.find(rStyle) == aDefaultStyleNames.end() ||
(sStyleFam != "ParagraphStyles" || doc_getDocumentType(pThis) != LOK_DOCTYPE_TEXT) )
{
boost::property_tree::ptree aChild;
aChild.put("", rStyle.toUtf8());
aChildren.push_back(std::make_pair("", aChild));
}
}
aValues.add_child(sStyleFam.toUtf8().getStr(), aChildren);
}
// Header & Footer Styles
{
boost::property_tree::ptree aChild;
boost::property_tree::ptree aChildren;
const OUString sPageStyles("PageStyles");
uno::Reference<beans::XPropertySet> xProperty;
uno::Reference<container::XNameContainer> xContainer;
if (xStyleFamilies->hasByName(sPageStyles) && (xStyleFamilies->getByName(sPageStyles) >>= xContainer))
{
const uno::Sequence<OUString> aSeqNames = xContainer->getElementNames();
for (OUString const & sName : aSeqNames)
{
bool bIsPhysical;
xProperty.set(xContainer->getByName(sName), uno::UNO_QUERY);
if (xProperty.is() && (xProperty->getPropertyValue("IsPhysical") >>= bIsPhysical) && bIsPhysical)
{
OUString displayName;
xProperty->getPropertyValue("DisplayName") >>= displayName;
aChild.put("", displayName.toUtf8());
aChildren.push_back(std::make_pair("", aChild));
}
}
aValues.add_child("HeaderFooter", aChildren);
}
}
{
boost::property_tree::ptree aCommandList;
{
boost::property_tree::ptree aChild;
OUString sClearFormat = SvxResId(RID_SVXSTR_CLEARFORM);
boost::property_tree::ptree aName;
aName.put("", sClearFormat.toUtf8());
aChild.push_back(std::make_pair("text", aName));
boost::property_tree::ptree aCommand;
aCommand.put("", ".uno:ResetAttributes");
aChild.push_back(std::make_pair("id", aCommand));
aCommandList.push_back(std::make_pair("", aChild));
}
aValues.add_child("Commands", aCommandList);
}
aTree.add_child("commandValues", aValues);
std::stringstream aStream;
boost::property_tree::write_json(aStream, aTree);
char* pJson = static_cast<char*>(malloc(aStream.str().size() + 1));
assert(pJson); // Don't handle OOM conditions
strcpy(pJson, aStream.str().c_str());
pJson[aStream.str().size()] = '\0';
return pJson;
}
namespace {
enum class UndoOrRedo
{
UNDO,
REDO
};
}
/// Returns the JSON representation of either an undo or a redo stack.
static char* getUndoOrRedo(LibreOfficeKitDocument* pThis, UndoOrRedo eCommand)
{
LibLODocument_Impl* pDocument = static_cast<LibLODocument_Impl*>(pThis);
auto pBaseModel = dynamic_cast<SfxBaseModel*>(pDocument->mxComponent.get());
if (!pBaseModel)
return nullptr;
SfxObjectShell* pObjectShell = pBaseModel->GetObjectShell();
if (!pObjectShell)
return nullptr;
SfxUndoManager* pUndoManager = pObjectShell->GetUndoManager();
if (!pUndoManager)
return nullptr;
OUString aString;
if (eCommand == UndoOrRedo::UNDO)
aString = pUndoManager->GetUndoActionsInfo();
else
aString = pUndoManager->GetRedoActionsInfo();
char* pJson = strdup(aString.toUtf8().getStr());
return pJson;
}
/// Returns the JSON representation of the redline stack.
static char* getTrackedChanges(LibreOfficeKitDocument* pThis)
{
LibLODocument_Impl* pDocument = static_cast<LibLODocument_Impl*>(pThis);
uno::Reference<document::XRedlinesSupplier> xRedlinesSupplier(pDocument->mxComponent, uno::UNO_QUERY);
tools::JsonWriter aJson;
// We want positions of the track changes also which is not possible from
// UNO. Enable positioning information for text documents only for now, so
// construct the tracked changes JSON from inside the sw/, not here using UNO
if (doc_getDocumentType(pThis) != LOK_DOCTYPE_TEXT && xRedlinesSupplier.is())
{
auto redlinesNode = aJson.startNode("redlines");
uno::Reference<container::XEnumeration> xRedlines = xRedlinesSupplier->getRedlines()->createEnumeration();
for (size_t nIndex = 0; xRedlines->hasMoreElements(); ++nIndex)
{
uno::Reference<beans::XPropertySet> xRedline(xRedlines->nextElement(), uno::UNO_QUERY);
auto redlineNode = aJson.startNode("");
aJson.put("index", static_cast<sal_Int32>(nIndex));
OUString sAuthor;
xRedline->getPropertyValue("RedlineAuthor") >>= sAuthor;
aJson.put("author", sAuthor);
OUString sType;
xRedline->getPropertyValue("RedlineType") >>= sType;
aJson.put("type", sType);
OUString sComment;
xRedline->getPropertyValue("RedlineComment") >>= sComment;
aJson.put("comment", sComment);
OUString sDescription;
xRedline->getPropertyValue("RedlineDescription") >>= sDescription;
aJson.put("description", sDescription);
util::DateTime aDateTime;
xRedline->getPropertyValue("RedlineDateTime") >>= aDateTime;
OUString sDateTime = utl::toISO8601(aDateTime);
aJson.put("dateTime", sDateTime);
}
}
else
{
ITiledRenderable* pDoc = getTiledRenderable(pThis);
if (!pDoc)
{
SetLastExceptionMsg("Document doesn't support tiled rendering");
return nullptr;
}
pDoc->getTrackedChanges(aJson);
}
return aJson.extractData();
}
/// Returns the JSON representation of the redline author table.
static char* getTrackedChangeAuthors(LibreOfficeKitDocument* pThis)
{
ITiledRenderable* pDoc = getTiledRenderable(pThis);
if (!pDoc)
{
SetLastExceptionMsg("Document doesn't support tiled rendering");
return nullptr;
}
tools::JsonWriter aJsonWriter;
pDoc->getTrackedChangeAuthors(aJsonWriter);
return aJsonWriter.extractData();
}
static char* doc_getCommandValues(LibreOfficeKitDocument* pThis, const char* pCommand)
{
comphelper::ProfileZone aZone("doc_getCommandValues");
SolarMutexGuard aGuard;
SetLastExceptionMsg();
OString aCommand(pCommand);
static constexpr OStringLiteral aViewRowColumnHeaders(".uno:ViewRowColumnHeaders");
static constexpr OStringLiteral aSheetGeometryData(".uno:SheetGeometryData");
static constexpr OStringLiteral aCellCursor(".uno:CellCursor");
static constexpr OStringLiteral aFontSubset(".uno:FontSubset&name=");
if (!strcmp(pCommand, ".uno:LanguageStatus"))
{
return getLanguages(pCommand);
}
else if (!strcmp(pCommand, ".uno:CharFontName"))
{
return getFonts(pCommand);
}
else if (!strcmp(pCommand, ".uno:StyleApply"))
{
return getStyles(pThis, pCommand);
}
else if (aCommand == ".uno:Undo")
{
return getUndoOrRedo(pThis, UndoOrRedo::UNDO);
}
else if (aCommand == ".uno:Redo")
{
return getUndoOrRedo(pThis, UndoOrRedo::REDO);
}
else if (aCommand == ".uno:AcceptTrackedChanges")
{
return getTrackedChanges(pThis);
}
else if (aCommand == ".uno:TrackedChangeAuthors")
{
return getTrackedChangeAuthors(pThis);
}
else if (aCommand == ".uno:ViewAnnotations")
{
return getPostIts(pThis);
}
else if (aCommand == ".uno:ViewAnnotationsPosition")
{
return getPostItsPos(pThis);
}
else if (aCommand == ".uno:RulerState")
{
return getRulerState(pThis);
}
else if (aCommand.startsWith(aViewRowColumnHeaders))
{
ITiledRenderable* pDoc = getTiledRenderable(pThis);
if (!pDoc)
{
SetLastExceptionMsg("Document doesn't support tiled rendering");
return nullptr;
}
tools::Rectangle aRectangle;
if (aCommand.getLength() > aViewRowColumnHeaders.getLength())
{
// Command has parameters.
int nX = 0;
int nY = 0;
int nWidth = 0;
int nHeight = 0;
OString aArguments = aCommand.copy(aViewRowColumnHeaders.getLength() + 1);
sal_Int32 nParamIndex = 0;
do
{
OString aParamToken = aArguments.getToken(0, '&', nParamIndex);
sal_Int32 nIndex = 0;
OString aKey;
OString aValue;
do
{
OString aToken = aParamToken.getToken(0, '=', nIndex);
if (!aKey.getLength())
aKey = aToken;
else
aValue = aToken;
}
while (nIndex >= 0);
if (aKey == "x")
nX = aValue.toInt32();
else if (aKey == "y")
nY = aValue.toInt32();
else if (aKey == "width")
nWidth = aValue.toInt32();
else if (aKey == "height")
nHeight = aValue.toInt32();
}
while (nParamIndex >= 0);
aRectangle = tools::Rectangle(nX, nY, nX + nWidth, nY + nHeight);
}
tools::JsonWriter aJsonWriter;
pDoc->getRowColumnHeaders(aRectangle, aJsonWriter);
return aJsonWriter.extractData();
}
else if (aCommand.startsWith(aSheetGeometryData))
{
ITiledRenderable* pDoc = getTiledRenderable(pThis);
if (!pDoc)
{
SetLastExceptionMsg("Document doesn't support tiled rendering");
return nullptr;
}
bool bColumns = true;
bool bRows = true;
bool bSizes = true;
bool bHidden = true;
bool bFiltered = true;
bool bGroups = true;
if (aCommand.getLength() > aSheetGeometryData.getLength())
{
bColumns = bRows = bSizes = bHidden = bFiltered = bGroups = false;
OString aArguments = aCommand.copy(aSheetGeometryData.getLength() + 1);
sal_Int32 nParamIndex = 0;
do
{
OString aParamToken = aArguments.getToken(0, '&', nParamIndex);
sal_Int32 nIndex = 0;
OString aKey;
OString aValue;
do
{
OString aToken = aParamToken.getToken(0, '=', nIndex);
if (!aKey.getLength())
aKey = aToken;
else
aValue = aToken;
} while (nIndex >= 0);
bool bEnableFlag = aValue.isEmpty() ||
aValue.equalsIgnoreAsciiCase("true") || aValue.toInt32() > 0;
if (!bEnableFlag)
continue;
if (aKey == "columns")
bColumns = true;
else if (aKey == "rows")
bRows = true;
else if (aKey == "sizes")
bSizes = true;
else if (aKey == "hidden")
bHidden = true;
else if (aKey == "filtered")
bFiltered = true;
else if (aKey == "groups")
bGroups = true;
} while (nParamIndex >= 0);
}
OString aGeomDataStr
= pDoc->getSheetGeometryData(bColumns, bRows, bSizes, bHidden, bFiltered, bGroups);
if (aGeomDataStr.isEmpty())
return nullptr;
return convertOString(aGeomDataStr);
}
else if (aCommand.startsWith(aCellCursor))
{
ITiledRenderable* pDoc = getTiledRenderable(pThis);
if (!pDoc)
{
SetLastExceptionMsg("Document doesn't support tiled rendering");
return nullptr;
}
// Ignore command's deprecated parameters.
tools::JsonWriter aJsonWriter;
pDoc->getCellCursor(aJsonWriter);
return aJsonWriter.extractData();
}
else if (aCommand.startsWith(aFontSubset))
{
return getFontSubset(OString(pCommand + aFontSubset.getLength()));
}
else
{
SetLastExceptionMsg("Unknown command, no values returned");
return nullptr;
}
}
static void doc_setClientZoom(LibreOfficeKitDocument* pThis, int nTilePixelWidth, int nTilePixelHeight,
int nTileTwipWidth, int nTileTwipHeight)
{
comphelper::ProfileZone aZone("doc_setClientZoom");
SolarMutexGuard aGuard;
SetLastExceptionMsg();
ITiledRenderable* pDoc = getTiledRenderable(pThis);
if (!pDoc)
{
SetLastExceptionMsg("Document doesn't support tiled rendering");
return;
}
pDoc->setClientZoom(nTilePixelWidth, nTilePixelHeight, nTileTwipWidth, nTileTwipHeight);
}
static void doc_setClientVisibleArea(LibreOfficeKitDocument* pThis, int nX, int nY, int nWidth, int nHeight)
{
comphelper::ProfileZone aZone("doc_setClientVisibleArea");
SolarMutexGuard aGuard;
SetLastExceptionMsg();
ITiledRenderable* pDoc = getTiledRenderable(pThis);
if (!pDoc)
{
SetLastExceptionMsg("Document doesn't support tiled rendering");
return;
}
tools::Rectangle aRectangle(Point(nX, nY), Size(nWidth, nHeight));
pDoc->setClientVisibleArea(aRectangle);
}
static void doc_setOutlineState(LibreOfficeKitDocument* pThis, bool bColumn, int nLevel, int nIndex, bool bHidden)
{
comphelper::ProfileZone aZone("doc_setOutlineState");
SolarMutexGuard aGuard;
SetLastExceptionMsg();
ITiledRenderable* pDoc = getTiledRenderable(pThis);
if (!pDoc)
{
SetLastExceptionMsg("Document doesn't support tiled rendering");
return;
}
pDoc->setOutlineState(bColumn, nLevel, nIndex, bHidden);
}
static int doc_createViewWithOptions(LibreOfficeKitDocument* pThis,
const char* pOptions)
{
comphelper::ProfileZone aZone("doc_createView");
SolarMutexGuard aGuard;
SetLastExceptionMsg();
OUString aOptions = getUString(pOptions);
const OUString aLanguage = extractParameter(aOptions, "Language");
if (!aLanguage.isEmpty())
{
// Set the LOK language tag, used for dialog tunneling.
comphelper::LibreOfficeKit::setLanguageTag(LanguageTag(aLanguage));
comphelper::LibreOfficeKit::setLocale(LanguageTag(aLanguage));
}
const OUString aDeviceFormFactor = extractParameter(aOptions, "DeviceFormFactor");
SfxLokHelper::setDeviceFormFactor(aDeviceFormFactor);
int nId = SfxLokHelper::createView();
#ifdef IOS
(void) pThis;
#else
forceSetClipboardForCurrentView(pThis);
#endif
return nId;
}
static int doc_createView(LibreOfficeKitDocument* pThis)
{
return doc_createViewWithOptions(pThis, nullptr); // No options.
}
static void doc_destroyView(SAL_UNUSED_PARAMETER LibreOfficeKitDocument* /*pThis*/, int nId)
{
comphelper::ProfileZone aZone("doc_destroyView");
SolarMutexGuard aGuard;
SetLastExceptionMsg();
LOKClipboardFactory::releaseClipboardForView(nId);
SfxLokHelper::destroyView(nId);
}
static void doc_setView(SAL_UNUSED_PARAMETER LibreOfficeKitDocument* /*pThis*/, int nId)
{
comphelper::ProfileZone aZone("doc_setView");
SolarMutexGuard aGuard;
SetLastExceptionMsg();
SfxLokHelper::setView(nId);
}
static int doc_getView(SAL_UNUSED_PARAMETER LibreOfficeKitDocument* /*pThis*/)
{
comphelper::ProfileZone aZone("doc_getView");
SolarMutexGuard aGuard;
SetLastExceptionMsg();
return SfxLokHelper::getView();
}
static int doc_getViewsCount(SAL_UNUSED_PARAMETER LibreOfficeKitDocument* /*pThis*/)
{
comphelper::ProfileZone aZone("doc_getViewsCount");
SolarMutexGuard aGuard;
SetLastExceptionMsg();
return SfxLokHelper::getViewsCount();
}
static bool doc_getViewIds(SAL_UNUSED_PARAMETER LibreOfficeKitDocument* /*pThis*/, int* pArray, size_t nSize)
{
comphelper::ProfileZone aZone("doc_getViewsIds");
SolarMutexGuard aGuard;
SetLastExceptionMsg();
return SfxLokHelper::getViewIds(pArray, nSize);
}
static void doc_setViewLanguage(SAL_UNUSED_PARAMETER LibreOfficeKitDocument* /*pThis*/, int nId, const char* language)
{
comphelper::ProfileZone aZone("doc_setViewLanguage");
SolarMutexGuard aGuard;
SetLastExceptionMsg();
OUString sLanguage = OStringToOUString(language, RTL_TEXTENCODING_UTF8);
SfxLokHelper::setViewLanguage(nId, sLanguage);
SfxLokHelper::setViewLocale(nId, sLanguage);
}
unsigned char* doc_renderFont(LibreOfficeKitDocument* pThis,
const char* pFontName,
const char* pChar,
int* pFontWidth,
int* pFontHeight)
{
return doc_renderFontOrientation(pThis, pFontName, pChar, pFontWidth, pFontHeight, 0);
}
unsigned char* doc_renderFontOrientation(SAL_UNUSED_PARAMETER LibreOfficeKitDocument* /*pThis*/,
const char* pFontName,
const char* pChar,
int* pFontWidth,
int* pFontHeight,
int pOrientation)
{
comphelper::ProfileZone aZone("doc_renderFont");
SolarMutexGuard aGuard;
SetLastExceptionMsg();
OString aSearchedFontName(pFontName);
OUString aText(OStringToOUString(pChar, RTL_TEXTENCODING_UTF8));
SfxObjectShell* pDocSh = SfxObjectShell::Current();
const SvxFontListItem* pFonts = static_cast<const SvxFontListItem*>(
pDocSh->GetItem(SID_ATTR_CHAR_FONTLIST));
const FontList* pList = pFonts ? pFonts->GetFontList() : nullptr;
const int nDefaultFontSize = 25;
if ( pList )
{
sal_uInt16 nFontCount = pList->GetFontNameCount();
for (sal_uInt16 i = 0; i < nFontCount; ++i)
{
const FontMetric& rFontMetric = pList->GetFontName(i);
const OUString& aFontName = rFontMetric.GetFamilyName();
if (aSearchedFontName != aFontName.toUtf8())
continue;
if (aText.isEmpty())
aText = rFontMetric.GetFamilyName();
auto aDevice(VclPtr<VirtualDevice>::Create(DeviceFormat::DEFAULT));
::tools::Rectangle aRect;
vcl::Font aFont(rFontMetric);
aFont.SetFontSize(Size(0, nDefaultFontSize));
aFont.SetOrientation(Degree10(pOrientation));
aDevice->SetFont(aFont);
aDevice->GetTextBoundRect(aRect, aText);
if (aRect.IsEmpty())
break;
int nFontWidth = aRect.BottomRight().X() + 1;
int nFontHeight = aRect.BottomRight().Y() + 1;
if (nFontWidth <= 0 || nFontHeight <= 0)
break;
if (*pFontWidth > 0 && *pFontHeight > 0)
{
double fScaleX = *pFontWidth / static_cast<double>(nFontWidth) / 1.5;
double fScaleY = *pFontHeight / static_cast<double>(nFontHeight) / 1.5;
double fScale = std::min(fScaleX, fScaleY);
if (fScale >= 1.0)
{
int nFontSize = fScale * nDefaultFontSize;
aFont.SetFontSize(Size(0, nFontSize));
aDevice->SetFont(aFont);
}
aRect = tools::Rectangle(0, 0, *pFontWidth, *pFontHeight);
nFontWidth = *pFontWidth;
nFontHeight = *pFontHeight;
}
unsigned char* pBuffer = static_cast<unsigned char*>(malloc(4 * nFontWidth * nFontHeight));
if (!pBuffer)
break;
memset(pBuffer, 0, nFontWidth * nFontHeight * 4);
aDevice->SetBackground(Wallpaper(COL_TRANSPARENT));
aDevice->SetOutputSizePixelScaleOffsetAndBuffer(
Size(nFontWidth, nFontHeight), Fraction(1.0), Point(),
pBuffer);
if (*pFontWidth > 0 && *pFontHeight > 0)
{
DrawTextFlags const nStyle =
DrawTextFlags::Center
| DrawTextFlags::VCenter
| DrawTextFlags::Bottom
| DrawTextFlags::MultiLine
| DrawTextFlags::WordBreak;// | DrawTextFlags::WordBreakHyphenation ;
aDevice->DrawText(aRect, aText, nStyle);
}
else
{
*pFontWidth = nFontWidth;
*pFontHeight = nFontHeight;
aDevice->DrawText(Point(0,0), aText);
}
return pBuffer;
}
}
return nullptr;
}
static void doc_paintWindow(LibreOfficeKitDocument* pThis, unsigned nLOKWindowId,
unsigned char* pBuffer,
const int nX, const int nY,
const int nWidth, const int nHeight)
{
doc_paintWindowDPI(pThis, nLOKWindowId, pBuffer, nX, nY, nWidth, nHeight, 1.0);
}
static void doc_paintWindowDPI(LibreOfficeKitDocument* pThis, unsigned nLOKWindowId,
unsigned char* pBuffer,
const int nX, const int nY,
const int nWidth, const int nHeight,
const double fDPIScale)
{
doc_paintWindowForView(pThis, nLOKWindowId, pBuffer, nX, nY, nWidth, nHeight, fDPIScale, -1);
}
static void doc_paintWindowForView(LibreOfficeKitDocument* pThis, unsigned nLOKWindowId,
unsigned char* pBuffer, const int nX, const int nY,
const int nWidth, const int nHeight,
const double fDPIScale, int viewId)
{
comphelper::ProfileZone aZone("doc_paintWindowDPI");
SolarMutexGuard aGuard;
SetLastExceptionMsg();
VclPtr<Window> pWindow = vcl::Window::FindLOKWindow(nLOKWindowId);
if (!pWindow)
{
SetLastExceptionMsg("Document doesn't support dialog rendering, or window not found.");
return;
}
// Used to avoid work in setView if set.
comphelper::LibreOfficeKit::setDialogPainting(true);
if (viewId >= 0)
doc_setView(pThis, viewId);
// Setup cairo (or CoreGraphics, in the iOS case) to draw with the changed DPI scale (and return
// back to 1.0 when the painting finishes)
comphelper::ScopeGuard dpiScaleGuard([]() { comphelper::LibreOfficeKit::setDPIScale(1.0); });
comphelper::LibreOfficeKit::setDPIScale(fDPIScale);
#if defined(IOS)
CGContextRef cgc = CGBitmapContextCreate(pBuffer, nWidth, nHeight, 8, nWidth*4, CGColorSpaceCreateDeviceRGB(), kCGImageAlphaNoneSkipFirst | kCGImageByteOrder32Little);
CGContextTranslateCTM(cgc, 0, nHeight);
CGContextScaleCTM(cgc, fDPIScale, -fDPIScale);
SystemGraphicsData aData;
aData.rCGContext = cgc;
ScopedVclPtrInstance<VirtualDevice> pDevice(aData, Size(1, 1), DeviceFormat::DEFAULT);
pDevice->SetBackground(Wallpaper(COL_TRANSPARENT));
pDevice->SetOutputSizePixel(Size(nWidth, nHeight));
MapMode aMapMode(pDevice->GetMapMode());
aMapMode.SetOrigin(Point(-(nX / fDPIScale), -(nY / fDPIScale)));
pDevice->SetMapMode(aMapMode);
pWindow->PaintToDevice(pDevice.get(), Point(0, 0));
CGContextRelease(cgc);
#else
ScopedVclPtrInstance<VirtualDevice> pDevice(DeviceFormat::DEFAULT);
pDevice->SetBackground(Wallpaper(COL_TRANSPARENT));
pDevice->SetOutputSizePixelScaleOffsetAndBuffer(Size(nWidth, nHeight), Fraction(1.0), Point(), pBuffer);
MapMode aMapMode(pDevice->GetMapMode());
aMapMode.SetOrigin(Point(-(nX / fDPIScale), -(nY / fDPIScale)));
pDevice->SetMapMode(aMapMode);
pWindow->PaintToDevice(pDevice.get(), Point(0, 0));
#endif
comphelper::LibreOfficeKit::setDialogPainting(false);
}
static void doc_postWindow(LibreOfficeKitDocument* /*pThis*/, unsigned nLOKWindowId, int nAction, const char* pData)
{
comphelper::ProfileZone aZone("doc_postWindow");
SolarMutexGuard aGuard;
SetLastExceptionMsg();
VclPtr<Window> pWindow = vcl::Window::FindLOKWindow(nLOKWindowId);
if (!pWindow)
{
SetLastExceptionMsg("Document doesn't support dialog rendering, or window not found.");
return;
}
if (nAction == LOK_WINDOW_CLOSE)
{
bool bWasDialog = vcl::CloseDialog(pWindow);
if (!bWasDialog)
{
if (FloatingWindow* pFloatWin = dynamic_cast<FloatingWindow*>(pWindow.get()))
pFloatWin->EndPopupMode(FloatWinPopupEndFlags::Cancel | FloatWinPopupEndFlags::CloseAll);
}
}
else if (nAction == LOK_WINDOW_PASTE)
{
OUString aMimeType;
css::uno::Sequence<sal_Int8> aData;
std::vector<beans::PropertyValue> aArgs(jsonToPropertyValuesVector(pData));
{
aArgs.size() == 2 &&
aArgs[0].Name == "MimeType" && (aArgs[0].Value >>= aMimeType) &&
aArgs[1].Name == "Data" && (aArgs[1].Value >>= aData);
}
if (!aMimeType.isEmpty() && aData.hasElements())
{
uno::Reference<datatransfer::XTransferable> xTransferable(new LOKTransferable(aMimeType, aData));
uno::Reference<datatransfer::clipboard::XClipboard> xClipboard(new LOKClipboard);
xClipboard->setContents(xTransferable, uno::Reference<datatransfer::clipboard::XClipboardOwner>());
pWindow->SetClipboard(xClipboard);
KeyEvent aEvent(0, KEY_PASTE, 0);
Application::PostKeyEvent(VclEventId::WindowKeyInput, pWindow, &aEvent);
}
else
SetLastExceptionMsg("Window command 'paste': wrong parameters.");
}
}
// CERTIFICATE AND DOCUMENT SIGNING
static bool doc_insertCertificate(LibreOfficeKitDocument* pThis,
const unsigned char* pCertificateBinary, const int nCertificateBinarySize,
const unsigned char* pPrivateKeyBinary, const int nPrivateKeySize)
{
comphelper::ProfileZone aZone("doc_insertCertificate");
if (!xContext.is())
return false;
LibLODocument_Impl* pDocument = static_cast<LibLODocument_Impl*>(pThis);
if (!pDocument->mxComponent.is())
return false;
SfxBaseModel* pBaseModel = dynamic_cast<SfxBaseModel*>(pDocument->mxComponent.get());
if (!pBaseModel)
return false;
SfxObjectShell* pObjectShell = pBaseModel->GetObjectShell();
if (!pObjectShell)
return false;
uno::Reference<xml::crypto::XSEInitializer> xSEInitializer = xml::crypto::SEInitializer::create(xContext);
uno::Reference<xml::crypto::XXMLSecurityContext> xSecurityContext = xSEInitializer->createSecurityContext(OUString());
if (!xSecurityContext.is())
return false;
uno::Reference<xml::crypto::XSecurityEnvironment> xSecurityEnvironment = xSecurityContext->getSecurityEnvironment();
uno::Reference<xml::crypto::XCertificateCreator> xCertificateCreator(xSecurityEnvironment, uno::UNO_QUERY);
if (!xCertificateCreator.is())
return false;
uno::Sequence<sal_Int8> aCertificateSequence;
std::string aCertificateString(reinterpret_cast<const char*>(pCertificateBinary), nCertificateBinarySize);
std::string aCertificateBase64String = extractCertificate(aCertificateString);
if (!aCertificateBase64String.empty())
{
OUString aBase64OUString = OUString::createFromAscii(aCertificateBase64String.c_str());
comphelper::Base64::decode(aCertificateSequence, aBase64OUString);
}
else
{
aCertificateSequence.realloc(nCertificateBinarySize);
std::copy(pCertificateBinary, pCertificateBinary + nCertificateBinarySize, aCertificateSequence.begin());
}
uno::Sequence<sal_Int8> aPrivateKeySequence;
std::string aPrivateKeyString(reinterpret_cast<const char*>(pPrivateKeyBinary), nPrivateKeySize);
std::string aPrivateKeyBase64String = extractPrivateKey(aPrivateKeyString);
if (!aPrivateKeyBase64String.empty())
{
OUString aBase64OUString = OUString::createFromAscii(aPrivateKeyBase64String.c_str());
comphelper::Base64::decode(aPrivateKeySequence, aBase64OUString);
}
else
{
aPrivateKeySequence.realloc(nPrivateKeySize);
std::copy(pPrivateKeyBinary, pPrivateKeyBinary + nPrivateKeySize, aPrivateKeySequence.begin());
}
uno::Reference<security::XCertificate> xCertificate = xCertificateCreator->createDERCertificateWithPrivateKey(aCertificateSequence, aPrivateKeySequence);
if (!xCertificate.is())
return false;
SolarMutexGuard aGuard;
return pObjectShell->SignDocumentContentUsingCertificate(xCertificate);
}
static bool doc_addCertificate(LibreOfficeKitDocument* pThis,
const unsigned char* pCertificateBinary, const int nCertificateBinarySize)
{
comphelper::ProfileZone aZone("doc_addCertificate");
if (!xContext.is())
return false;
LibLODocument_Impl* pDocument = static_cast<LibLODocument_Impl*>(pThis);
if (!pDocument->mxComponent.is())
return false;
SfxBaseModel* pBaseModel = dynamic_cast<SfxBaseModel*>(pDocument->mxComponent.get());
if (!pBaseModel)
return false;
SfxObjectShell* pObjectShell = pBaseModel->GetObjectShell();
if (!pObjectShell)
return false;
uno::Reference<xml::crypto::XSEInitializer> xSEInitializer = xml::crypto::SEInitializer::create(xContext);
uno::Reference<xml::crypto::XXMLSecurityContext> xSecurityContext = xSEInitializer->createSecurityContext(OUString());
if (!xSecurityContext.is())
return false;
uno::Reference<xml::crypto::XSecurityEnvironment> xSecurityEnvironment = xSecurityContext->getSecurityEnvironment();
uno::Reference<xml::crypto::XCertificateCreator> xCertificateCreator(xSecurityEnvironment, uno::UNO_QUERY);
if (!xCertificateCreator.is())
return false;
uno::Sequence<sal_Int8> aCertificateSequence;
std::string aCertificateString(reinterpret_cast<const char*>(pCertificateBinary), nCertificateBinarySize);
std::string aCertificateBase64String = extractCertificate(aCertificateString);
if (!aCertificateBase64String.empty())
{
OUString aBase64OUString = OUString::createFromAscii(aCertificateBase64String.c_str());
comphelper::Base64::decode(aCertificateSequence, aBase64OUString);
}
else
{
aCertificateSequence.realloc(nCertificateBinarySize);
std::copy(pCertificateBinary, pCertificateBinary + nCertificateBinarySize, aCertificateSequence.begin());
}
uno::Reference<security::XCertificate> xCertificate = xCertificateCreator->addDERCertificateToTheDatabase(aCertificateSequence, "TCu,Cu,Tu");
if (!xCertificate.is())
return false;
SAL_INFO("lok", "Certificate Added = IssuerName: " << xCertificate->getIssuerName() << " SubjectName: " << xCertificate->getSubjectName());
return true;
}
static int doc_getSignatureState(LibreOfficeKitDocument* pThis)
{
comphelper::ProfileZone aZone("doc_getSignatureState");
LibLODocument_Impl* pDocument = static_cast<LibLODocument_Impl*>(pThis);
if (!pDocument->mxComponent.is())
return int(SignatureState::UNKNOWN);
SfxBaseModel* pBaseModel = dynamic_cast<SfxBaseModel*>(pDocument->mxComponent.get());
if (!pBaseModel)
return int(SignatureState::UNKNOWN);
SfxObjectShell* pObjectShell = pBaseModel->GetObjectShell();
if (!pObjectShell)
return int(SignatureState::UNKNOWN);
SolarMutexGuard aGuard;
pObjectShell->RecheckSignature(false);
return int(pObjectShell->GetDocumentSignatureState());
}
static void doc_resizeWindow(LibreOfficeKitDocument* /*pThis*/, unsigned nLOKWindowId,
const int nWidth, const int nHeight)
{
SolarMutexGuard aGuard;
if (gImpl)
gImpl->maLastExceptionMsg.clear();
VclPtr<Window> pWindow = vcl::Window::FindLOKWindow(nLOKWindowId);
if (!pWindow)
{
gImpl->maLastExceptionMsg = "Document doesn't support dialog resizing, or window not found.";
return;
}
pWindow->SetSizePixel(Size(nWidth, nHeight));
}
static void doc_completeFunction(LibreOfficeKitDocument* pThis, const char* pFunctionName)
{
SolarMutexGuard aGuard;
SetLastExceptionMsg();
ITiledRenderable* pDoc = getTiledRenderable(pThis);
if (!pDoc)
{
SetLastExceptionMsg("Document doesn't support tiled rendering");
return;
}
pDoc->completeFunction(OUString::fromUtf8(pFunctionName));
}
static void doc_sendFormFieldEvent(LibreOfficeKitDocument* pThis, const char* pArguments)
{
SolarMutexGuard aGuard;
// Supported in Writer only
if (doc_getDocumentType(pThis) != LOK_DOCTYPE_TEXT)
return;
StringMap aMap(jsonToStringMap(pArguments));
ITiledRenderable* pDoc = getTiledRenderable(pThis);
if (!pDoc)
{
SetLastExceptionMsg("Document doesn't support tiled rendering!");
return;
}
// Sanity check
if (aMap.find("type") == aMap.end() || aMap.find("cmd") == aMap.end())
{
SetLastExceptionMsg("Wrong arguments for sendFormFieldEvent!");
return;
}
pDoc->executeFromFieldEvent(aMap);
}
static char* lo_getError (LibreOfficeKit *pThis)
{
comphelper::ProfileZone aZone("lo_getError");
SolarMutexGuard aGuard;
LibLibreOffice_Impl* pLib = static_cast<LibLibreOffice_Impl*>(pThis);
return convertOUString(pLib->maLastExceptionMsg);
}
static void lo_freeError(char* pFree)
{
free(pFree);
}
static char* lo_getFilterTypes(LibreOfficeKit* pThis)
{
SolarMutexGuard aGuard;
SetLastExceptionMsg();
LibLibreOffice_Impl* pImpl = static_cast<LibLibreOffice_Impl*>(pThis);
if (!xSFactory.is())
xSFactory = comphelper::getProcessServiceFactory();
if (!xSFactory.is())
{
pImpl->maLastExceptionMsg = "Service factory is not available";
return nullptr;
}
uno::Reference<container::XNameAccess> xTypeDetection(xSFactory->createInstance("com.sun.star.document.TypeDetection"), uno::UNO_QUERY);
const uno::Sequence<OUString> aTypes = xTypeDetection->getElementNames();
boost::property_tree::ptree aTree;
for (const OUString& rType : aTypes)
{
uno::Sequence<beans::PropertyValue> aValues;
if (xTypeDetection->getByName(rType) >>= aValues)
{
auto it = std::find_if(aValues.begin(), aValues.end(), [](const beans::PropertyValue& rValue) { return rValue.Name == "MediaType"; });
OUString aValue;
if (it != aValues.end() && (it->Value >>= aValue) && !aValue.isEmpty())
{
boost::property_tree::ptree aChild;
aChild.put("MediaType", aValue.toUtf8());
aTree.add_child(rType.toUtf8().getStr(), aChild);
}
}
}
std::stringstream aStream;
boost::property_tree::write_json(aStream, aTree);
return strdup(aStream.str().c_str());
}
static void lo_setOptionalFeatures(LibreOfficeKit* pThis, unsigned long long const features)
{
comphelper::ProfileZone aZone("lo_setOptionalFeatures");
SolarMutexGuard aGuard;
SetLastExceptionMsg();
LibLibreOffice_Impl *const pLib = static_cast<LibLibreOffice_Impl*>(pThis);
pLib->mOptionalFeatures = features;
if (features & LOK_FEATURE_PART_IN_INVALIDATION_CALLBACK)
comphelper::LibreOfficeKit::setPartInInvalidation(true);
if (features & LOK_FEATURE_NO_TILED_ANNOTATIONS)
comphelper::LibreOfficeKit::setTiledAnnotations(false);
if (features & LOK_FEATURE_RANGE_HEADERS)
comphelper::LibreOfficeKit::setRangeHeaders(true);
if (features & LOK_FEATURE_VIEWID_IN_VISCURSOR_INVALIDATION_CALLBACK)
comphelper::LibreOfficeKit::setViewIdForVisCursorInvalidation(true);
}
static void lo_setDocumentPassword(LibreOfficeKit* pThis,
const char* pURL, const char* pPassword)
{
comphelper::ProfileZone aZone("lo_setDocumentPassword");
SolarMutexGuard aGuard;
SetLastExceptionMsg();
assert(pThis);
assert(pURL);
LibLibreOffice_Impl *const pLib = static_cast<LibLibreOffice_Impl*>(pThis);
assert(pLib->mInteractionMap.find(OString(pURL)) != pLib->mInteractionMap.end());
pLib->mInteractionMap.find(OString(pURL))->second->SetPassword(pPassword);
}
static char* lo_getVersionInfo(SAL_UNUSED_PARAMETER LibreOfficeKit* /*pThis*/)
{
SetLastExceptionMsg();
return convertOUString(ReplaceStringHookProc(
"{ "
"\"ProductName\": \"%PRODUCTNAME\", "
"\"ProductVersion\": \"%PRODUCTVERSION\", "
"\"ProductExtension\": \"%PRODUCTEXTENSION\", "
"\"BuildId\": \"%BUILDID\" "
"}"));
}
static void aBasicErrorFunc(const OUString& rError, const OUString& rAction)
{
OString aBuffer = "Unexpected dialog: " +
OUStringToOString(rAction, RTL_TEXTENCODING_ASCII_US) +
" Error: " +
OUStringToOString(rError, RTL_TEXTENCODING_ASCII_US);
fprintf(stderr, "Unexpected basic error dialog '%s'\n", aBuffer.getStr());
}
static bool initialize_uno(const OUString& aAppProgramURL)
{
#ifdef IOS
// For iOS we already hardcode the inifile as "rc" in the .app directory.
rtl::Bootstrap::setIniFilename(aAppProgramURL + "/" SAL_CONFIGFILE("fundamental"));
xContext = cppu::defaultBootstrap_InitialComponentContext(aAppProgramURL + "/rc");
#elif defined MACOSX
rtl::Bootstrap::setIniFilename(aAppProgramURL + "/../Resources/" SAL_CONFIGFILE("soffice"));
xContext = cppu::defaultBootstrap_InitialComponentContext();
#else
rtl::Bootstrap::setIniFilename(aAppProgramURL + "/" SAL_CONFIGFILE("soffice"));
xContext = cppu::defaultBootstrap_InitialComponentContext();
#endif
if (!xContext.is())
{
SetLastExceptionMsg("XComponentContext could not be created");
SAL_INFO("lok", "XComponentContext could not be created");
return false;
}
xFactory = xContext->getServiceManager();
if (!xFactory.is())
{
SetLastExceptionMsg("XMultiComponentFactory could not be created");
SAL_INFO("lok", "XMultiComponentFactory could not be created");
return false;
}
xSFactory.set(xFactory, uno::UNO_QUERY_THROW);
comphelper::setProcessServiceFactory(xSFactory);
SAL_INFO("lok", "Uno initialized - " << xContext.is());
// set UserInstallation to user profile dir in test/user-template
// rtl::Bootstrap aDefaultVars;
// aDefaultVars.set(OUString("UserInstallation"), aAppProgramURL + "../registry" );
// configmgr setup ?
return true;
}
// pre-unipoll version.
static void lo_startmain(void*)
{
osl_setThreadName("lo_startmain");
if (comphelper::SolarMutex::get())
Application::GetSolarMutex().tryToAcquire();
Application::UpdateMainThread();
soffice_main();
Application::ReleaseSolarMutex();
}
// unipoll version.
static void lo_runLoop(LibreOfficeKit* /*pThis*/,
LibreOfficeKitPollCallback pPollCallback,
LibreOfficeKitWakeCallback pWakeCallback,
void* pData)
{
#if defined(IOS) || defined(ANDROID)
Application::GetSolarMutex().acquire();
#endif
{
SolarMutexGuard aGuard;
vcl::lok::registerPollCallbacks(pPollCallback, pWakeCallback, pData);
Application::UpdateMainThread();
soffice_main();
}
#if defined(IOS) || defined(ANDROID)
vcl::lok::unregisterPollCallbacks();
Application::ReleaseSolarMutex();
#endif
}
static bool bInitialized = false;
static void lo_status_indicator_callback(void *data, comphelper::LibreOfficeKit::statusIndicatorCallbackType type, int percent)
{
LibLibreOffice_Impl* pLib = static_cast<LibLibreOffice_Impl*>(data);
if (!pLib->mpCallback)
return;
switch (type)
{
case comphelper::LibreOfficeKit::statusIndicatorCallbackType::Start:
pLib->mpCallback(LOK_CALLBACK_STATUS_INDICATOR_START, nullptr, pLib->mpCallbackData);
break;
case comphelper::LibreOfficeKit::statusIndicatorCallbackType::SetValue:
pLib->mpCallback(LOK_CALLBACK_STATUS_INDICATOR_SET_VALUE,
OUString(OUString::number(percent)).toUtf8().getStr(), pLib->mpCallbackData);
break;
case comphelper::LibreOfficeKit::statusIndicatorCallbackType::Finish:
pLib->mpCallback(LOK_CALLBACK_STATUS_INDICATOR_FINISH, nullptr, pLib->mpCallbackData);
break;
}
}
/// Used only by LibreOfficeKit when used by Online to pre-initialize
static void preloadData()
{
comphelper::ProfileZone aZone("preload data");
// Create user profile in the temp directory for loading the dictionaries
OUString sUserPath;
rtl::Bootstrap::get("UserInstallation", sUserPath);
utl::TempFile aTempDir(nullptr, true);
aTempDir.EnableKillingFile();
rtl::Bootstrap::set("UserInstallation", aTempDir.GetURL());
// Register the bundled extensions
desktop::Desktop::SynchronizeExtensionRepositories(true);
bool bAbort = desktop::Desktop::CheckExtensionDependencies();
if(bAbort)
std::cerr << "CheckExtensionDependencies failed" << std::endl;
// preload all available dictionaries
css::uno::Reference<css::linguistic2::XLinguServiceManager> xLngSvcMgr =
css::linguistic2::LinguServiceManager::create(comphelper::getProcessComponentContext());
css::uno::Reference<linguistic2::XSpellChecker> xSpellChecker(xLngSvcMgr->getSpellChecker());
std::cerr << "Preloading dictionaries: ";
css::uno::Reference<linguistic2::XSupportedLocales> xSpellLocales(xSpellChecker, css::uno::UNO_QUERY_THROW);
uno::Sequence< css::lang::Locale > aLocales = xSpellLocales->getLocales();
for (auto &it : aLocales)
{
std::cerr << it.Language << "_" << it.Country << " ";
css::beans::PropertyValues aNone;
xSpellChecker->isValid("forcefed", it, aNone);
}
std::cerr << "\n";
// Hack to load and cache the module liblocaledata_others.so which is not loaded normally
// (when loading dictionaries of just non-Asian locales). Creating a XCalendar4 of one Asian locale
// will cheaply load this missing "others" locale library. Appending an Asian locale in
// LOK_ALLOWLIST_LANGUAGES env-var also works but at the cost of loading that dictionary.
css::uno::Reference< css::i18n::XCalendar4 > xCal = css::i18n::LocaleCalendar2::create(comphelper::getProcessComponentContext());
css::lang::Locale aAsianLocale = {"hi", "IN", ""};
xCal->loadDefaultCalendar(aAsianLocale);
// preload all available thesauri
css::uno::Reference<linguistic2::XThesaurus> xThesaurus(xLngSvcMgr->getThesaurus());
css::uno::Reference<linguistic2::XSupportedLocales> xThesLocales(xSpellChecker, css::uno::UNO_QUERY_THROW);
aLocales = xThesLocales->getLocales();
std::cerr << "Preloading thesauri: ";
for (auto &it : aLocales)
{
std::cerr << it.Language << "_" << it.Country << " ";
css::beans::PropertyValues aNone;
xThesaurus->queryMeanings("forcefed", it, aNone);
}
std::cerr << "\n";
css::uno::Reference< css::ui::XAcceleratorConfiguration > xGlobalCfg = css::ui::GlobalAcceleratorConfiguration::create(
comphelper::getProcessComponentContext());
xGlobalCfg->getAllKeyEvents();
std::cerr << "Preload icons\n";
ImageTree &images = ImageTree::get();
images.getImageUrl("forcefed.png", "style", "FO_oo");
std::cerr << "Preload languages\n";
// force load language singleton
SvtLanguageTable::HasLanguageType(LANGUAGE_SYSTEM);
(void)LanguageTag::isValidBcp47("foo", nullptr);
std::cerr << "Preload fonts\n";
// Initialize fonts.
css::uno::Reference<css::linguistic2::XLinguServiceManager2> xLangSrv = css::linguistic2::LinguServiceManager::create(xContext);
if (xLangSrv.is())
{
css::uno::Reference<css::linguistic2::XSpellChecker> xSpell = xLangSrv->getSpellChecker();
if (xSpell.is())
aLocales = xSpell->getLocales();
}
for (const auto& aLocale : std::as_const(aLocales))
{
//TODO: Add more types and cache more aggressively. For now this initializes the fontcache.
using namespace ::com::sun::star::i18n::ScriptType;
LanguageType nLang;
nLang = MsLangId::resolveSystemLanguageByScriptType(LanguageTag::convertToLanguageType(aLocale, false), LATIN);
OutputDevice::GetDefaultFont(DefaultFontType::LATIN_SPREADSHEET, nLang, GetDefaultFontFlags::OnlyOne);
nLang = MsLangId::resolveSystemLanguageByScriptType(LanguageTag::convertToLanguageType(aLocale, false), ASIAN);
OutputDevice::GetDefaultFont(DefaultFontType::CJK_SPREADSHEET, nLang, GetDefaultFontFlags::OnlyOne);
nLang = MsLangId::resolveSystemLanguageByScriptType(LanguageTag::convertToLanguageType(aLocale, false), COMPLEX);
OutputDevice::GetDefaultFont(DefaultFontType::CTL_SPREADSHEET, nLang, GetDefaultFontFlags::OnlyOne);
}
// Set user profile's path back to the original one
rtl::Bootstrap::set("UserInstallation", sUserPath);
}
namespace {
class ProfileZoneDumper : public AutoTimer
{
static const int dumpTimeoutMS = 5000;
public:
ProfileZoneDumper() : AutoTimer( "zone dumper" )
{
SetTimeout(dumpTimeoutMS);
Start();
}
virtual void Invoke() override
{
const css::uno::Sequence<OUString> aEvents =
comphelper::ProfileRecording::getRecordingAndClear();
OStringBuffer aOutput;
for (const auto &s : aEvents)
{
aOutput.append(OUStringToOString(s, RTL_TEXTENCODING_UTF8));
aOutput.append("\n");
}
OString aChunk = aOutput.makeStringAndClear();
if (gImpl && gImpl->mpCallback)
gImpl->mpCallback(LOK_CALLBACK_PROFILE_FRAME, aChunk.getStr(), gImpl->mpCallbackData);
}
};
static void activateNotebookbar(const OUString& rApp)
{
OUString aPath = "org.openoffice.Office.UI.ToolbarMode/Applications/" + rApp;
const utl::OConfigurationTreeRoot aAppNode(xContext, aPath, true);
if (aAppNode.isValid())
{
aAppNode.setNodeValue("Active", makeAny(OUString("notebookbar.ui")));
aAppNode.commit();
}
}
}
static int lo_initialize(LibreOfficeKit* pThis, const char* pAppPath, const char* pUserProfileUrl)
{
enum {
PRE_INIT, // setup shared data in master process
SECOND_INIT, // complete init. after fork
FULL_INIT // do a standard complete init.
} eStage;
// Did we do a pre-initialize
static bool bPreInited = false;
static bool bUnipoll = false;
static bool bProfileZones = false;
static bool bNotebookbar = false;
{ // cf. string lifetime for preinit
std::vector<OUString> aOpts;
// ':' delimited options - avoiding ABI change for new parameters
const char *pOptions = getenv("SAL_LOK_OPTIONS");
if (pOptions)
aOpts = comphelper::string::split(OUString(pOptions, strlen(pOptions), RTL_TEXTENCODING_UTF8), ':');
for (const auto &it : aOpts)
{
if (it == "unipoll")
bUnipoll = true;
else if (it == "profile_events")
bProfileZones = true;
else if (it == "sc_no_grid_bg")
comphelper::LibreOfficeKit::setCompatFlag(
comphelper::LibreOfficeKit::Compat::scNoGridBackground);
else if (it == "sc_print_twips_msgs")
comphelper::LibreOfficeKit::setCompatFlag(
comphelper::LibreOfficeKit::Compat::scPrintTwipsMsgs);
else if (it == "notebookbar")
bNotebookbar = true;
}
}
// What stage are we at ?
if (pThis == nullptr)
eStage = PRE_INIT;
else if (bPreInited)
eStage = SECOND_INIT;
else
eStage = FULL_INIT;
LibLibreOffice_Impl* pLib = static_cast<LibLibreOffice_Impl*>(pThis);
if (bInitialized)
return 1;
// Turn profile zones on early
if (bProfileZones && eStage == SECOND_INIT)
{
comphelper::ProfileRecording::startRecording(true);
new ProfileZoneDumper();
}
comphelper::ProfileZone aZone("lok-init");
if (eStage == PRE_INIT)
rtl_alloc_preInit(true);
else if (eStage == SECOND_INIT)
rtl_alloc_preInit(false);
if (eStage != SECOND_INIT)
comphelper::LibreOfficeKit::setActive();
if (eStage != PRE_INIT)
comphelper::LibreOfficeKit::setStatusIndicatorCallback(lo_status_indicator_callback, pLib);
if (pUserProfileUrl && eStage != PRE_INIT)
{
OUString url(
pUserProfileUrl, strlen(pUserProfileUrl), RTL_TEXTENCODING_UTF8);
OUString path;
if (url.startsWithIgnoreAsciiCase("vnd.sun.star.pathname:", &path))
{
OUString url2;
osl::FileBase::RC e = osl::FileBase::getFileURLFromSystemPath(
path, url2);
if (e == osl::FileBase::E_None)
url = url2;
else
SAL_WARN("lok", "resolving <" << url << "> failed with " << +e);
}
rtl::Bootstrap::set("UserInstallation", url);
if (eStage == SECOND_INIT)
utl::Bootstrap::reloadData();
}
OUString aAppPath;
if (pAppPath)
{
aAppPath = OUString(pAppPath, strlen(pAppPath), RTL_TEXTENCODING_UTF8);
}
else
{
#ifdef ANDROID
aAppPath = OUString::fromUtf8(lo_get_app_data_dir()) + "/program";
#else
// Fun conversion dance back and forth between URLs and system paths...
OUString aAppURL;
::osl::Module::getUrlFromAddress( reinterpret_cast< oslGenericFunction >(lo_initialize),
aAppURL);
osl::FileBase::getSystemPathFromFileURL( aAppURL, aAppPath );
#endif
#ifdef IOS
// The above gives something like
// "/private/var/containers/Bundle/Application/953AA851-CC15-4C60-A2CB-C2C6F24E6F71/Foo.app/Foo",
// and we want to drop the final component (the binary name).
sal_Int32 lastSlash = aAppPath.lastIndexOf('/');
assert(lastSlash > 0);
aAppPath = aAppPath.copy(0, lastSlash);
#endif
}
OUString aAppURL;
if (osl::FileBase::getFileURLFromSystemPath(aAppPath, aAppURL) != osl::FileBase::E_None)
return 0;
#ifdef IOS
// A LibreOffice-using iOS app should have the ICU data file in the app bundle. Initialize ICU
// to use that.
NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
int fd = open([[bundlePath stringByAppendingPathComponent:@"ICU.dat"] UTF8String], O_RDONLY);
if (fd == -1)
NSLog(@"Could not open ICU data file %s", [[bundlePath stringByAppendingPathComponent:@"ICU.dat"] UTF8String]);
else
{
struct stat st;
if (fstat(fd, &st) == -1)
NSLog(@"fstat on ICU data file failed: %s", strerror(errno));
else
{
void *icudata = mmap(0, (size_t) st.st_size, PROT_READ, MAP_FILE|MAP_PRIVATE, fd, 0);
if (icudata == MAP_FAILED)
NSLog(@"mmap failed: %s", strerror(errno));
else
{
UErrorCode icuStatus = U_ZERO_ERROR;
udata_setCommonData(icudata, &icuStatus);
if (U_FAILURE(icuStatus))
NSLog(@"udata_setCommonData failed");
else
{
// Quick test that ICU works...
UConverter *cnv = ucnv_open("iso-8859-3", &icuStatus);
if (U_SUCCESS(icuStatus))
ucnv_close(cnv);
else
NSLog(@"ucnv_open() failed: %s", u_errorName(icuStatus));
}
}
}
close(fd);
}
#endif
try
{
if (eStage != SECOND_INIT)
{
SAL_INFO("lok", "Attempting to initialize UNO");
if (!initialize_uno(aAppURL))
return false;
// Force headless -- this is only for bitmap rendering.
rtl::Bootstrap::set("SAL_USE_VCLPLUGIN", "svp");
// We specifically need to make sure we have the "headless"
// command arg set (various code specifically checks via
// CommandLineArgs):
desktop::Desktop::GetCommandLineArgs().setHeadless();
#ifdef IOS
if (InitVCL() && [NSThread isMainThread])
{
static bool bFirstTime = true;
if (bFirstTime)
{
Application::GetSolarMutex().release();
bFirstTime = false;
}
}
SfxApplication::GetOrCreate();
#endif
#if HAVE_FEATURE_ANDROID_LOK
// Register the bundled extensions - so that the dictionaries work
desktop::Desktop::SynchronizeExtensionRepositories(false);
bool bFailed = desktop::Desktop::CheckExtensionDependencies();
if (bFailed)
SAL_INFO("lok", "CheckExtensionDependencies failed");
#endif
if (eStage == PRE_INIT)
{
{
comphelper::ProfileZone aInit("Init vcl");
std::cerr << "Init vcl\n";
InitVCL();
}
// pre-load all graphic libraries.
GraphicFilter::GetGraphicFilter().preload();
// pre-load all component libraries.
if (!xContext.is())
throw css::uno::DeploymentException("preInit: XComponentContext is not created");
css::uno::Reference< css::uno::XInterface > xService;
xContext->getValueByName("/singletons/com.sun.star.lang.theServiceManager") >>= xService;
if (!xService.is())
throw css::uno::DeploymentException("preInit: XMultiComponentFactory is not created");
css::uno::Reference<css::lang::XInitialization> aService(
xService, css::uno::UNO_QUERY_THROW);
// pre-requisites:
// In order to load implementations and invoke
// component factory it is required:
// 1) defaultBootstrap_InitialComponentContext()
// 2) comphelper::setProcessServiceFactory(xSFactory);
// 3) InitVCL()
{
comphelper::ProfileZone aInit("preload");
aService->initialize({css::uno::makeAny<OUString>("preload")});
}
{ // Force load some modules
comphelper::ProfileZone aInit("preload modules");
VclBuilder::preload();
VclAbstractDialogFactory::Create();
}
preloadData();
// Release Solar Mutex, lo_startmain thread should acquire it.
Application::ReleaseSolarMutex();
}
setLanguageAndLocale("en-US");
}
if (eStage != PRE_INIT)
{
SAL_INFO("lok", "Re-initialize temp paths");
SvtPathOptions aOptions;
OUString aNewTemp;
osl::FileBase::getTempDirURL(aNewTemp);
aOptions.SetTempPath(aNewTemp);
desktop::Desktop::CreateTemporaryDirectory();
// The RequestHandler is specifically set to be ready when all the other
// init in Desktop::Main (run from soffice_main) is done. We can enable
// the RequestHandler here (without starting any IPC thread;
// shortcutting the invocation in Desktop::Main that would start the IPC
// thread), and can then use it to wait until we're definitely ready to
// continue.
SAL_INFO("lok", "Enabling RequestHandler");
RequestHandler::Enable(false);
SAL_INFO("lok", "Starting soffice_main");
RequestHandler::SetReady(false);
if (!bUnipoll)
{
// Start the main thread only in non-unipoll mode (i.e. multithreaded).
pLib->maThread = osl_createThread(lo_startmain, nullptr);
SAL_INFO("lok", "Waiting for RequestHandler");
RequestHandler::WaitForReady();
SAL_INFO("lok", "RequestHandler ready -- continuing");
}
else
InitVCL();
}
if (eStage != SECOND_INIT)
ErrorRegistry::RegisterDisplay(aBasicErrorFunc);
SAL_INFO("lok", "LOK Initialized");
if (eStage == PRE_INIT)
bPreInited = true;
else
bInitialized = true;
}
catch (css::uno::Exception& exception)
{
fprintf(stderr, "Bootstrapping exception '%s'\n",
OUStringToOString(exception.Message, RTL_TEXTENCODING_UTF8).getStr());
}
if (eStage == PRE_INIT)
{
comphelper::ThreadPool::getSharedOptimalPool().shutdown();
}
// Turn off quick editing on IOS and ANDROID
#if defined IOS || defined ANDROID
if (officecfg::Office::Impress::Misc::TextObject::QuickEditing::get())
{
std::shared_ptr<comphelper::ConfigurationChanges> batch(comphelper::ConfigurationChanges::create());
officecfg::Office::Impress::Misc::TextObject::QuickEditing::set(false, batch);
batch->commit();
}
#endif
if (bNotebookbar)
{
activateNotebookbar("Writer");
activateNotebookbar("Calc");
activateNotebookbar("Impress");
}
return bInitialized;
}
SAL_JNI_EXPORT
LibreOfficeKit *libreofficekit_hook_2(const char* install_path, const char* user_profile_url)
{
if (!gImpl)
{
SAL_INFO("lok", "Create libreoffice object");
gImpl = new LibLibreOffice_Impl();
if (!lo_initialize(gImpl, install_path, user_profile_url))
{
lo_destroy(gImpl);
}
}
return static_cast<LibreOfficeKit*>(gImpl);
}
SAL_JNI_EXPORT
LibreOfficeKit *libreofficekit_hook(const char* install_path)
{
return libreofficekit_hook_2(install_path, nullptr);
}
SAL_JNI_EXPORT
int lok_preinit(const char* install_path, const char* user_profile_url)
{
return lo_initialize(nullptr, install_path, user_profile_url);
}
static void lo_destroy(LibreOfficeKit* pThis)
{
SolarMutexClearableGuard aGuard;
LibLibreOffice_Impl* pLib = static_cast<LibLibreOffice_Impl*>(pThis);
gImpl = nullptr;
SAL_INFO("lok", "LO Destroy");
comphelper::LibreOfficeKit::setStatusIndicatorCallback(nullptr, nullptr);
uno::Reference <frame::XDesktop2> xDesktop = frame::Desktop::create ( ::comphelper::getProcessComponentContext() );
// FIXME: the terminate() call here is a no-op because it detects
// that LibreOfficeKit::isActive() and then returns early!
bool bSuccess = xDesktop.is() && xDesktop->terminate();
if (!bSuccess)
{
bSuccess = GetpApp() && GetpApp()->QueryExit();
}
if (!bSuccess)
{
Application::Quit();
}
aGuard.clear();
osl_joinWithThread(pLib->maThread);
osl_destroyThread(pLib->maThread);
delete pLib;
bInitialized = false;
SAL_INFO("lok", "LO Destroy Done");
}
#ifdef IOS
// Used by the unmaintained LibreOfficeLight app. Once that has been retired, get rid of this, too.
__attribute__((visibility("default")))
void temporaryHackToInvokeCallbackHandlers(LibreOfficeKitDocument* pThis)
{
SolarMutexGuard aGuard;
LibLODocument_Impl* pDocument = static_cast<LibLODocument_Impl*>(pThis);
int nOrigViewId = doc_getView(pThis);
if (nOrigViewId >= 0 && pDocument->mpCallbackFlushHandlers[nOrigViewId])
{
pDocument->mpCallbackFlushHandlers[nOrigViewId]->Invoke();
}
}
#endif
} // extern "C"
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|