This file is indexed.

/usr/lib/python3/dist-packages/pyx/path.py is in python3-pyx 0.14.1-1build1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
# -*- encoding: utf-8 -*-
#
#
# Copyright (C) 2002-2006 Jörg Lehmann <joergl@users.sourceforge.net>
# Copyright (C) 2003-2005 Michael Schindler <m-schindler@users.sourceforge.net>
# Copyright (C) 2002-2011 André Wobst <wobsta@users.sourceforge.net>
#
# This file is part of PyX (http://pyx.sourceforge.net/).
#
# PyX is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# PyX is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with PyX; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA

import math
from math import cos, sin, tan, acos, pi, radians, degrees
from . import trafo, unit
from .normpath import NormpathException, normpath, normsubpath, normline_pt, normcurve_pt
from . import bbox as bboxmodule

# set is available as an external interface to the normpath.set method
from .normpath import set


class _marker: pass

################################################################################

# specific exception for path-related problems
class PathException(Exception): pass

################################################################################
# Bezier helper functions
################################################################################

def _bezierpolyrange(x0, x1, x2, x3):
    tc = [0, 1]

    a = x3 - 3*x2 + 3*x1 - x0
    b = 2*x0 - 4*x1 + 2*x2
    c = x1 - x0

    s = b*b - 4*a*c
    if s >= 0:
        if b >= 0:
            q = -0.5*(b+math.sqrt(s))
        else:
            q = -0.5*(b-math.sqrt(s))

        try:
            t = q*1.0/a
        except ZeroDivisionError:
            pass
        else:
            if 0 < t < 1:
                tc.append(t)

        try:
            t = c*1.0/q
        except ZeroDivisionError:
            pass
        else:
            if 0 < t < 1:
                tc.append(t)

    p = [(((a*t + 1.5*b)*t + 3*c)*t + x0) for t in tc]

    return min(*p), max(*p)


def _arctobcurve(x_pt, y_pt, r_pt, phi1, phi2):
    """generate the best bezier curve corresponding to an arc segment"""

    dphi = phi2-phi1

    if dphi==0: return None

    # the two endpoints should be clear
    x0_pt, y0_pt = x_pt+r_pt*cos(phi1), y_pt+r_pt*sin(phi1)
    x3_pt, y3_pt = x_pt+r_pt*cos(phi2), y_pt+r_pt*sin(phi2)

    # optimal relative distance along tangent for second and third
    # control point
    l = r_pt*4*(1-cos(dphi/2))/(3*sin(dphi/2))

    x1_pt, y1_pt = x0_pt-l*sin(phi1), y0_pt+l*cos(phi1)
    x2_pt, y2_pt = x3_pt+l*sin(phi2), y3_pt-l*cos(phi2)

    return normcurve_pt(x0_pt, y0_pt, x1_pt, y1_pt, x2_pt, y2_pt, x3_pt, y3_pt)


def _arctobezierpath(x_pt, y_pt, r_pt, phi1, phi2, dphimax=45):
    apath = []

    phi1 = radians(phi1)
    phi2 = radians(phi2)
    dphimax = radians(dphimax)

    if phi2<phi1:
        # guarantee that phi2>phi1 ...
        phi2 = phi2 + (math.floor((phi1-phi2)/(2*pi))+1)*2*pi
    elif phi2>phi1+2*pi:
        # ... or remove unnecessary multiples of 2*pi
        phi2 = phi2 - (math.floor((phi2-phi1)/(2*pi))-1)*2*pi

    if r_pt == 0 or phi1-phi2 == 0: return []

    subdivisions = int((phi2-phi1)/dphimax)+1

    dphi = (phi2-phi1)/subdivisions

    for i in range(subdivisions):
        apath.append(_arctobcurve(x_pt, y_pt, r_pt, phi1+i*dphi, phi1+(i+1)*dphi))

    return apath

def _arcpoint(x_pt, y_pt, r_pt, angle):
    """return starting point of arc segment"""
    return x_pt+r_pt*cos(radians(angle)), y_pt+r_pt*sin(radians(angle))

def _arcbboxdata(x_pt, y_pt, r_pt, angle1, angle2):
    phi1 = radians(angle1)
    phi2 = radians(angle2)

    # starting end end point of arc segment
    sarcx_pt, sarcy_pt = _arcpoint(x_pt, y_pt, r_pt, angle1)
    earcx_pt, earcy_pt = _arcpoint(x_pt, y_pt, r_pt, angle2)

    # Now, we have to determine the corners of the bbox for the
    # arc segment, i.e. global maxima/mimima of cos(phi) and sin(phi)
    # in the interval [phi1, phi2]. These can either be located
    # on the borders of this interval or in the interior.

    if phi2 < phi1:
        # guarantee that phi2>phi1
        phi2 = phi2 + (math.floor((phi1-phi2)/(2*pi))+1)*2*pi

    # next minimum of cos(phi) looking from phi1 in counterclockwise
    # direction: 2*pi*floor((phi1-pi)/(2*pi)) + 3*pi

    if phi2 < (2*math.floor((phi1-pi)/(2*pi))+3)*pi:
        minarcx_pt = min(sarcx_pt, earcx_pt)
    else:
        minarcx_pt = x_pt-r_pt

    # next minimum of sin(phi) looking from phi1 in counterclockwise
    # direction: 2*pi*floor((phi1-3*pi/2)/(2*pi)) + 7/2*pi

    if phi2 < (2*math.floor((phi1-3.0*pi/2)/(2*pi))+7.0/2)*pi:
        minarcy_pt = min(sarcy_pt, earcy_pt)
    else:
        minarcy_pt = y_pt-r_pt

    # next maximum of cos(phi) looking from phi1 in counterclockwise
    # direction: 2*pi*floor((phi1)/(2*pi))+2*pi

    if phi2 < (2*math.floor((phi1)/(2*pi))+2)*pi:
        maxarcx_pt = max(sarcx_pt, earcx_pt)
    else:
        maxarcx_pt = x_pt+r_pt

    # next maximum of sin(phi) looking from phi1 in counterclockwise
    # direction: 2*pi*floor((phi1-pi/2)/(2*pi)) + 1/2*pi

    if phi2 < (2*math.floor((phi1-pi/2)/(2*pi))+5.0/2)*pi:
        maxarcy_pt = max(sarcy_pt, earcy_pt)
    else:
        maxarcy_pt = y_pt+r_pt

    return minarcx_pt, minarcy_pt, maxarcx_pt, maxarcy_pt


################################################################################
# path context and pathitem base class
################################################################################

class context:

    """context for pathitem"""

    def __init__(self, x_pt, y_pt, subfirstx_pt, subfirsty_pt):
        """initializes a context for path items

        x_pt, y_pt are the currentpoint. subfirstx_pt, subfirsty_pt
        are the starting point of the current subpath. There are no
        invalid contexts, i.e. all variables need to be set to integer
        or float numbers.
        """
        self.x_pt = x_pt
        self.y_pt = y_pt
        self.subfirstx_pt = subfirstx_pt
        self.subfirsty_pt = subfirsty_pt


class pathitem:

    """element of a PS style path"""

    def __str__(self):
        raise NotImplementedError()

    def createcontext(self):
        """creates a context from the current pathitem

        Returns a context instance. Is called, when no context has yet
        been defined, i.e. for the very first pathitem. Most of the
        pathitems do not provide this method. Note, that you should pass
        the context created by createcontext to updatebbox and updatenormpath
        of successive pathitems only; use the context-free createbbox and
        createnormpath for the first pathitem instead.
        """
        raise PathException("path must start with moveto or the like (%r)" % self)

    def createbbox(self):
        """creates a bbox from the current pathitem

        Returns a bbox instance. Is called, when a bbox has to be
        created instead of updating it, i.e. for the very first
        pathitem. Most pathitems do not provide this method.
        updatebbox must not be called for the created instance and the
        same pathitem.
        """
        raise PathException("path must start with moveto or the like (%r)" % self)

    def createnormpath(self, epsilon=_marker):
        """create a normpath from the current pathitem

        Return a normpath instance. Is called, when a normpath has to
        be created instead of updating it, i.e. for the very first
        pathitem. Most pathitems do not provide this method.
        updatenormpath must not be called for the created instance and
        the same pathitem.
        """
        raise PathException("path must start with moveto or the like (%r)" % self)

    def updatebbox(self, bbox, context):
        """updates the bbox to contain the pathitem for the given
        context

        Is called for all subsequent pathitems in a path to complete
        the bbox information. Both, the bbox and context are updated
        inplace. Does not return anything.
        """
        raise NotImplementedError(self)

    def updatenormpath(self, normpath, context):
        """update the normpath to contain the pathitem for the given
        context

        Is called for all subsequent pathitems in a path to complete
        the normpath. Both the normpath and the context are updated
        inplace. Most pathitem implementations will use
        normpath.normsubpath[-1].append to add normsubpathitem(s).
        Does not return anything.
        """
        raise NotImplementedError(self)

    def outputPS(self, file, writer):
        """write PS representation of pathitem to file"""
        raise NotImplementedError(self)

    def returnSVGdata(self, inverse_y, first, context):
        """return SVG representation of pathitem

        :param bool inverse_y: reverts y coordinate as SVG uses a
            different y direction, but when creating font paths no
            y inversion is needed.
        :param bool first: :class:`arc` and :class:`arcn` need to
            know whether it is first in the path to prepend a line
            or a move. Note that it can't tell from the context as
            it is not stored in the context whether it is first.
        :param context: :class:`arct` need the currentpoint and
            closepath needs the startingpoint of the last subpath
            to update the currentpoint
        :type context: :class:`context`
        :rtype: string

        """
        raise NotImplementedError(self)



################################################################################
# various pathitems
################################################################################
# Each one comes in two variants:
#  - one with suffix _pt. This one requires the coordinates
#    to be already in pts (mainly used for internal purposes)
#  - another which accepts arbitrary units


class closepath(pathitem):

    """Connect subpath back to its starting point"""

    __slots__ = ()

    def __str__(self):
        return "closepath()"

    def updatebbox(self, bbox, context):
        context.x_pt = context.subfirstx_pt
        context.y_pt = context.subfirsty_pt

    def updatenormpath(self, normpath, context):
        normpath.normsubpaths[-1].close()
        context.x_pt = context.subfirstx_pt
        context.y_pt = context.subfirsty_pt

    def outputPS(self, file, writer):
        file.write("closepath\n")

    def returnSVGdata(self, inverse_y, first, context):
        return "Z"


class pdfmoveto_pt(normline_pt):

    def outputPDF(self, file, writer):
        pass


class moveto_pt(pathitem):

    """Start a new subpath and set current point to (x_pt, y_pt) (coordinates in pts)"""

    __slots__ = "x_pt", "y_pt"

    def __init__(self, x_pt, y_pt):
        self.x_pt = x_pt
        self.y_pt = y_pt

    def __str__(self):
        return "moveto_pt(%g, %g)" % (self.x_pt, self.y_pt)

    def createcontext(self):
        return context(self.x_pt, self.y_pt, self.x_pt, self.y_pt)

    def createbbox(self):
        return bboxmodule.bbox_pt(self.x_pt, self.y_pt, self.x_pt, self.y_pt)

    def createnormpath(self, epsilon=_marker):
        if epsilon is _marker:
            return normpath([normsubpath([normline_pt(self.x_pt, self.y_pt, self.x_pt, self.y_pt)])])
        elif epsilon is None:
            return normpath([normsubpath([pdfmoveto_pt(self.x_pt, self.y_pt, self.x_pt, self.y_pt)],
                                         epsilon=epsilon)])
        else:
            return normpath([normsubpath([normline_pt(self.x_pt, self.y_pt, self.x_pt, self.y_pt)],
                                         epsilon=epsilon)])

    def updatebbox(self, bbox, context):
        bbox.includepoint_pt(self.x_pt, self.y_pt)
        context.x_pt = context.subfirstx_pt = self.x_pt
        context.y_pt = context.subfirsty_pt = self.y_pt

    def updatenormpath(self, normpath, context):
        if normpath.normsubpaths[-1].epsilon is not None:
            normpath.append(normsubpath([normline_pt(self.x_pt, self.y_pt, self.x_pt, self.y_pt)],
                                        epsilon=normpath.normsubpaths[-1].epsilon))
        else:
            normpath.append(normsubpath(epsilon=normpath.normsubpaths[-1].epsilon))
        context.x_pt = context.subfirstx_pt = self.x_pt
        context.y_pt = context.subfirsty_pt = self.y_pt

    def outputPS(self, file, writer):
        file.write("%g %g moveto\n" % (self.x_pt, self.y_pt) )

    def returnSVGdata(self, inverse_y, first, context):
        context.x_pt = context.subfirstx_pt = self.x_pt
        context.y_pt = context.subfirsty_pt = self.y_pt
        if inverse_y:
            return "M%g %g" % (self.x_pt, -self.y_pt)
        return "M%g %g" % (self.x_pt, self.y_pt)


class lineto_pt(pathitem):

    """Append straight line to (x_pt, y_pt) (coordinates in pts)"""

    __slots__ = "x_pt", "y_pt"

    def __init__(self, x_pt, y_pt):
        self.x_pt = x_pt
        self.y_pt = y_pt

    def __str__(self):
        return "lineto_pt(%g, %g)" % (self.x_pt, self.y_pt)

    def updatebbox(self, bbox, context):
        bbox.includepoint_pt(self.x_pt, self.y_pt)
        context.x_pt = self.x_pt
        context.y_pt = self.y_pt

    def updatenormpath(self, normpath, context):
        normpath.normsubpaths[-1].append(normline_pt(context.x_pt, context.y_pt,
                                                     self.x_pt, self.y_pt))
        context.x_pt = self.x_pt
        context.y_pt = self.y_pt

    def outputPS(self, file, writer):
        file.write("%g %g lineto\n" % (self.x_pt, self.y_pt) )

    def returnSVGdata(self, inverse_y, first, context):
        context.x_pt = self.x_pt
        context.y_pt = self.y_pt
        if inverse_y:
            return "L%g %g" % (self.x_pt, -self.y_pt)
        return "L%g %g" % (self.x_pt, self.y_pt)


class curveto_pt(pathitem):

    """Append curveto (coordinates in pts)"""

    __slots__ = "x1_pt", "y1_pt", "x2_pt", "y2_pt", "x3_pt", "y3_pt"

    def __init__(self, x1_pt, y1_pt, x2_pt, y2_pt, x3_pt, y3_pt):
        self.x1_pt = x1_pt
        self.y1_pt = y1_pt
        self.x2_pt = x2_pt
        self.y2_pt = y2_pt
        self.x3_pt = x3_pt
        self.y3_pt = y3_pt

    def __str__(self):
        return "curveto_pt(%g, %g, %g, %g, %g, %g)" % (self.x1_pt, self.y1_pt,
                                                       self.x2_pt, self.y2_pt,
                                                       self.x3_pt, self.y3_pt)

    def updatebbox(self, bbox, context):
        xmin_pt, xmax_pt = _bezierpolyrange(context.x_pt, self.x1_pt, self.x2_pt, self.x3_pt)
        ymin_pt, ymax_pt = _bezierpolyrange(context.y_pt, self.y1_pt, self.y2_pt, self.y3_pt)
        bbox.includepoint_pt(xmin_pt, ymin_pt)
        bbox.includepoint_pt(xmax_pt, ymax_pt)
        context.x_pt = self.x3_pt
        context.y_pt = self.y3_pt

    def updatenormpath(self, normpath, context):
        normpath.normsubpaths[-1].append(normcurve_pt(context.x_pt, context.y_pt,
                                                      self.x1_pt, self.y1_pt,
                                                      self.x2_pt, self.y2_pt,
                                                      self.x3_pt, self.y3_pt))
        context.x_pt = self.x3_pt
        context.y_pt = self.y3_pt

    def outputPS(self, file, writer):
        file.write("%g %g %g %g %g %g curveto\n" % (self.x1_pt, self.y1_pt,
                                                    self.x2_pt, self.y2_pt,
                                                    self.x3_pt, self.y3_pt))

    def returnSVGdata(self, inverse_y, first, context):
        context.x_pt = self.x3_pt
        context.y_pt = self.y3_pt
        if inverse_y:
            return "C%g %g %g %g %g %g" % (self.x1_pt, -self.y1_pt, self.x2_pt, -self.y2_pt, self.x3_pt, -self.y3_pt)
        return "C%g %g %g %g %g %g" % (self.x1_pt, self.y1_pt, self.x2_pt, self.y2_pt, self.x3_pt, self.y3_pt)


class rmoveto_pt(pathitem):

    """Perform relative moveto (coordinates in pts)"""

    __slots__ = "dx_pt", "dy_pt"

    def __init__(self, dx_pt, dy_pt):
         self.dx_pt = dx_pt
         self.dy_pt = dy_pt

    def __str__(self):
        return "rmoveto_pt(%g, %g)" % (self.dx_pt, self.dy_pt)

    def updatebbox(self, bbox, context):
        bbox.includepoint_pt(context.x_pt + self.dx_pt, context.y_pt + self.dy_pt)
        context.x_pt += self.dx_pt
        context.y_pt += self.dy_pt
        context.subfirstx_pt = context.x_pt
        context.subfirsty_pt = context.y_pt

    def updatenormpath(self, normpath, context):
        context.x_pt += self.dx_pt
        context.y_pt += self.dy_pt
        context.subfirstx_pt = context.x_pt
        context.subfirsty_pt = context.y_pt
        if normpath.normsubpaths[-1].epsilon is not None:
            normpath.append(normsubpath([normline_pt(context.x_pt, context.y_pt,
                                                     context.x_pt, context.y_pt)],
                                        epsilon=normpath.normsubpaths[-1].epsilon))
        else:
            normpath.append(normsubpath(epsilon=normpath.normsubpaths[-1].epsilon))

    def outputPS(self, file, writer):
        file.write("%g %g rmoveto\n" % (self.dx_pt, self.dy_pt) )

    def returnSVGdata(self, inverse_y, first, context):
        context.x_pt += self.dx_pt
        context.y_pt += self.dy_pt
        context.subfirstx_pt = context.x_pt
        context.subfirsty_pt = context.y_pt
        if inverse_y:
            return "m%g %g" % (self.dx_pt, -self.dy_pt)
        return "m%g %g" % (self.dx_pt, self.dy_pt)


class rlineto_pt(pathitem):

    """Perform relative lineto (coordinates in pts)"""

    __slots__ = "dx_pt", "dy_pt"

    def __init__(self, dx_pt, dy_pt):
        self.dx_pt = dx_pt
        self.dy_pt = dy_pt

    def __str__(self):
        return "rlineto_pt(%g %g)" % (self.dx_pt, self.dy_pt)

    def updatebbox(self, bbox, context):
        bbox.includepoint_pt(context.x_pt + self.dx_pt, context.y_pt + self.dy_pt)
        context.x_pt += self.dx_pt
        context.y_pt += self.dy_pt

    def updatenormpath(self, normpath, context):
        normpath.normsubpaths[-1].append(normline_pt(context.x_pt, context.y_pt,
                                                     context.x_pt + self.dx_pt, context.y_pt + self.dy_pt))
        context.x_pt += self.dx_pt
        context.y_pt += self.dy_pt

    def outputPS(self, file, writer):
        file.write("%g %g rlineto\n" % (self.dx_pt, self.dy_pt) )

    def returnSVGdata(self, inverse_y, first, context):
        context.x_pt += self.dx_pt
        context.y_pt += self.dy_pt
        if inverse_y:
            return "l%g %g" % (self.dx_pt, -self.dy_pt)
        return "l%g %g" % (self.dx_pt, self.dy_pt)


class rcurveto_pt(pathitem):

    """Append rcurveto (coordinates in pts)"""

    __slots__ = "dx1_pt", "dy1_pt", "dx2_pt", "dy2_pt", "dx3_pt", "dy3_pt"

    def __init__(self, dx1_pt, dy1_pt, dx2_pt, dy2_pt, dx3_pt, dy3_pt):
        self.dx1_pt = dx1_pt
        self.dy1_pt = dy1_pt
        self.dx2_pt = dx2_pt
        self.dy2_pt = dy2_pt
        self.dx3_pt = dx3_pt
        self.dy3_pt = dy3_pt

    def __str__(self):
        return "rcurveto_pt(%g, %g, %g, %g, %g, %g)" % (self.dx1_pt, self.dy1_pt,
                                                        self.dx2_pt, self.dy2_pt,
                                                        self.dx3_pt, self.dy3_pt)

    def updatebbox(self, bbox, context):
        xmin_pt, xmax_pt = _bezierpolyrange(context.x_pt,
                                            context.x_pt+self.dx1_pt,
                                            context.x_pt+self.dx2_pt,
                                            context.x_pt+self.dx3_pt)
        ymin_pt, ymax_pt = _bezierpolyrange(context.y_pt,
                                            context.y_pt+self.dy1_pt,
                                            context.y_pt+self.dy2_pt,
                                            context.y_pt+self.dy3_pt)
        bbox.includepoint_pt(xmin_pt, ymin_pt)
        bbox.includepoint_pt(xmax_pt, ymax_pt)
        context.x_pt += self.dx3_pt
        context.y_pt += self.dy3_pt

    def updatenormpath(self, normpath, context):
        normpath.normsubpaths[-1].append(normcurve_pt(context.x_pt, context.y_pt,
                                                      context.x_pt + self.dx1_pt, context.y_pt + self.dy1_pt,
                                                      context.x_pt + self.dx2_pt, context.y_pt + self.dy2_pt,
                                                      context.x_pt + self.dx3_pt, context.y_pt + self.dy3_pt))
        context.x_pt += self.dx3_pt
        context.y_pt += self.dy3_pt

    def outputPS(self, file, writer):
        file.write("%g %g %g %g %g %g rcurveto\n" % (self.dx1_pt, self.dy1_pt,
                                                     self.dx2_pt, self.dy2_pt,
                                                     self.dx3_pt, self.dy3_pt))

    def returnSVGdata(self, inverse_y, first, context):
        context.x_pt += self.dx3_pt
        context.y_pt += self.dy3_pt
        if inverse_y:
            return "c%g %g %g %g %g %g" % (self.dx1_pt, -self.dy1_pt, self.dx2_pt, -self.dy2_pt, self.dx3_pt, -self.dy3_pt)
        return "c%g %g %g %g %g %g" % (self.dx1_pt, self.dy1_pt, self.dx2_pt, self.dy2_pt, self.dx3_pt, self.dy3_pt)


class arc_pt(pathitem):

    """Append counterclockwise arc (coordinates in pts)"""

    __slots__ = "x_pt", "y_pt", "r_pt", "angle1", "angle2"

    sweep = 0

    def __init__(self, x_pt, y_pt, r_pt, angle1, angle2):
        self.x_pt = x_pt
        self.y_pt = y_pt
        self.r_pt = r_pt
        self.angle1 = angle1
        self.angle2 = angle2

    def __str__(self):
        return "arc_pt(%g, %g, %g, %g, %g)" % (self.x_pt, self.y_pt, self.r_pt,
                                               self.angle1, self.angle2)

    def createcontext(self):
        x1_pt, y1_pt = _arcpoint(self.x_pt, self.y_pt, self.r_pt, self.angle1)
        x2_pt, y2_pt = _arcpoint(self.x_pt, self.y_pt, self.r_pt, self.angle2)
        return context(x2_pt, y2_pt, x1_pt, y1_pt)

    def createbbox(self):
        return bboxmodule.bbox_pt(*_arcbboxdata(self.x_pt, self.y_pt, self.r_pt,
                                                self.angle1, self.angle2))

    def createnormpath(self, epsilon=_marker):
        if epsilon is _marker:
            return normpath([normsubpath(_arctobezierpath(self.x_pt, self.y_pt, self.r_pt, self.angle1, self.angle2))])
        else:
            return normpath([normsubpath(_arctobezierpath(self.x_pt, self.y_pt, self.r_pt, self.angle1, self.angle2),
                                         epsilon=epsilon)])

    def updatebbox(self, bbox, context):
        minarcx_pt, minarcy_pt, maxarcx_pt, maxarcy_pt = _arcbboxdata(self.x_pt, self.y_pt, self.r_pt,
                                                                      self.angle1, self.angle2)
        bbox.includepoint_pt(minarcx_pt, minarcy_pt)
        bbox.includepoint_pt(maxarcx_pt, maxarcy_pt)
        context.x_pt, context.y_pt = _arcpoint(self.x_pt, self.y_pt, self.r_pt, self.angle2)

    def updatenormpath(self, normpath, context):
        if normpath.normsubpaths[-1].closed:
            normpath.append(normsubpath([normline_pt(context.x_pt, context.y_pt,
                                                         *_arcpoint(self.x_pt, self.y_pt, self.r_pt, self.angle1))],
                                        epsilon=normpath.normsubpaths[-1].epsilon))
        else:
            normpath.normsubpaths[-1].append(normline_pt(context.x_pt, context.y_pt,
                                                         *_arcpoint(self.x_pt, self.y_pt, self.r_pt, self.angle1)))
        normpath.normsubpaths[-1].extend(_arctobezierpath(self.x_pt, self.y_pt, self.r_pt, self.angle1, self.angle2))
        context.x_pt, context.y_pt = _arcpoint(self.x_pt, self.y_pt, self.r_pt, self.angle2)

    def outputPS(self, file, writer):
        file.write("%g %g %g %g %g arc\n" % (self.x_pt, self.y_pt,
                                             self.r_pt,
                                             self.angle1,
                                             self.angle2))

    def returnSVGdata(self, inverse_y, first, context):
        # move or line to the start point
        x_pt, y_pt = _arcpoint(self.x_pt, self.y_pt, self.r_pt, self.angle1)
        if inverse_y:
            y_pt = -y_pt
        if first:
            data = ["M%g %g" % (x_pt, y_pt)]
        else:
            data = ["L%g %g" % (x_pt, y_pt)]

        angle1 = self.angle1
        angle2 = self.angle2

        # make 0 < angle2-angle1 < 2*360
        if angle2 < angle1:
            angle2 += (math.floor((angle1-angle2)/360)+1)*360
        elif angle2 > angle1 + 360:
            angle2 -= (math.floor((angle2-angle1)/360)-1)*360
        # svg arcs become unstable when close to 360 degree and cannot
        # express more than 360 degree at all, so we might need to split.
        subdivisions = int((angle2-angle1)/350)+1

        # we equal split by subdivisions
        large = "1" if (angle2-angle1)/subdivisions > 180 else "0"
        for i in range(subdivisions):
            x_pt, y_pt = _arcpoint(self.x_pt, self.y_pt, self.r_pt, angle1 + (i+1)*(angle2-angle1)/subdivisions)
            if inverse_y:
                y_pt = -y_pt
            data.append("A%g %g 0 %s 0 %g %g" % (self.r_pt, self.r_pt, large, x_pt, y_pt))

        context.x_pt = x_pt
        context.y_pt = y_pt
        return "".join(data)


class arcn_pt(pathitem):

    """Append clockwise arc (coordinates in pts)"""

    __slots__ = "x_pt", "y_pt", "r_pt", "angle1", "angle2"

    sweep = 1

    def __init__(self, x_pt, y_pt, r_pt, angle1, angle2):
        self.x_pt = x_pt
        self.y_pt = y_pt
        self.r_pt = r_pt
        self.angle1 = angle1
        self.angle2 = angle2

    def __str__(self):
        return "arcn_pt(%g, %g, %g, %g, %g)" % (self.x_pt, self.y_pt, self.r_pt,
                                                self.angle1, self.angle2)

    def createcontext(self):
        x1_pt, y1_pt = _arcpoint(self.x_pt, self.y_pt, self.r_pt, self.angle1)
        x2_pt, y2_pt = _arcpoint(self.x_pt, self.y_pt, self.r_pt, self.angle2)
        return context(x2_pt, y2_pt, x1_pt, y1_pt)

    def createbbox(self):
        return bboxmodule.bbox_pt(*_arcbboxdata(self.x_pt, self.y_pt, self.r_pt,
                                                self.angle2, self.angle1))

    def createnormpath(self, epsilon=_marker):
        if epsilon is _marker:
            return normpath([normsubpath(_arctobezierpath(self.x_pt, self.y_pt, self.r_pt, self.angle2, self.angle1))]).reversed()
        else:
            return normpath([normsubpath(_arctobezierpath(self.x_pt, self.y_pt, self.r_pt, self.angle2, self.angle1),
                                         epsilon=epsilon)]).reversed()

    def updatebbox(self, bbox, context):
        minarcx_pt, minarcy_pt, maxarcx_pt, maxarcy_pt = _arcbboxdata(self.x_pt, self.y_pt, self.r_pt,
                                                                      self.angle2, self.angle1)
        bbox.includepoint_pt(minarcx_pt, minarcy_pt)
        bbox.includepoint_pt(maxarcx_pt, maxarcy_pt)
        context.x_pt, context.y_pt = _arcpoint(self.x_pt, self.y_pt, self.r_pt, self.angle2)

    def updatenormpath(self, normpath, context):
        if normpath.normsubpaths[-1].closed:
            normpath.append(normsubpath([normline_pt(context.x_pt, context.y_pt,
                                                         *_arcpoint(self.x_pt, self.y_pt, self.r_pt, self.angle1))],
                                        epsilon=normpath.normsubpaths[-1].epsilon))
        else:
            normpath.normsubpaths[-1].append(normline_pt(context.x_pt, context.y_pt,
                                                         *_arcpoint(self.x_pt, self.y_pt, self.r_pt, self.angle1)))
        bpathitems = _arctobezierpath(self.x_pt, self.y_pt, self.r_pt, self.angle2, self.angle1)
        bpathitems.reverse()
        for bpathitem in bpathitems:
            normpath.normsubpaths[-1].append(bpathitem.reversed())
        context.x_pt, context.y_pt = _arcpoint(self.x_pt, self.y_pt, self.r_pt, self.angle2)

    def outputPS(self, file, writer):
        file.write("%g %g %g %g %g arcn\n" % (self.x_pt, self.y_pt,
                                              self.r_pt,
                                              self.angle1,
                                              self.angle2))

    def returnSVGdata(self, inverse_y, first, context):
        # move or line to the start point
        x_pt, y_pt = _arcpoint(self.x_pt, self.y_pt, self.r_pt, self.angle1)
        if inverse_y:
            y_pt = -y_pt
        if first:
            data = ["M%g %g" % (x_pt, y_pt)]
        else:
            data = ["L%g %g" % (x_pt, y_pt)]

        angle1 = self.angle1
        angle2 = self.angle2

        # make 0 < angle1-angle2 < 2*360
        if angle1 < angle2:
            angle1 += (math.floor((angle2-angle1)/360)+1)*360
        elif angle1 > angle2 + 360:
            angle1 -= (math.floor((angle1-angle2)/360)-1)*360
        # svg arcs become unstable when close to 360 degree and cannot
        # express more than 360 degree at all, so we might need to split.
        subdivisions = int((angle1-angle2)/350)+1

        # we equal split by subdivisions
        large = "1" if (angle1-angle2)/subdivisions > 180 else "0"
        for i in range(subdivisions):
            x_pt, y_pt = _arcpoint(self.x_pt, self.y_pt, self.r_pt, angle1 + (i+1)*(angle2-angle1)/subdivisions)
            if inverse_y:
                y_pt = -y_pt
            data.append("A%g %g 0 %s 1 %g %g" % (self.r_pt, self.r_pt, large, x_pt, y_pt))

        context.x_pt = x_pt
        context.y_pt = y_pt
        return "".join(data)


class arct_pt(pathitem):

    """Append tangent arc (coordinates in pts)"""

    __slots__ = "x1_pt", "y1_pt", "x2_pt", "y2_pt", "r_pt"

    def __init__(self, x1_pt, y1_pt, x2_pt, y2_pt, r_pt):
        self.x1_pt = x1_pt
        self.y1_pt = y1_pt
        self.x2_pt = x2_pt
        self.y2_pt = y2_pt
        self.r_pt = r_pt

    def __str__(self):
        return "arct_pt(%g, %g, %g, %g, %g)" % (self.x1_pt, self.y1_pt,
                                                self.x2_pt, self.y2_pt,
                                                self.r_pt)

    def _pathitems(self, x_pt, y_pt):
        """return pathitems corresponding to arct for given currentpoint x_pt, y_pt.

        The return is a list containing line_pt, arc_pt, a arcn_pt instances.

        This is a helper routine for updatebbox and updatenormpath,
        which will delegate the work to the constructed pathitem.
        """

        # direction of tangent 1
        dx1_pt, dy1_pt = self.x1_pt-x_pt, self.y1_pt-y_pt
        l1_pt = math.hypot(dx1_pt, dy1_pt)
        dx1, dy1 = dx1_pt/l1_pt, dy1_pt/l1_pt

        # direction of tangent 2
        dx2_pt, dy2_pt = self.x2_pt-self.x1_pt, self.y2_pt-self.y1_pt
        l2_pt = math.hypot(dx2_pt, dy2_pt)
        dx2, dy2 = dx2_pt/l2_pt, dy2_pt/l2_pt

        # intersection angle between two tangents in the range (-pi, pi).
        # We take the orientation from the sign of the vector product.
        # Negative (positive) angles alpha corresponds to a turn to the right (left)
        # as seen from currentpoint.
        if dx1*dy2-dy1*dx2 > 0:
            alpha = acos(dx1*dx2+dy1*dy2) 
        else:
            alpha = -acos(dx1*dx2+dy1*dy2) 

        try:
            # two tangent points
            xt1_pt = self.x1_pt - dx1*self.r_pt*tan(abs(alpha)/2)
            yt1_pt = self.y1_pt - dy1*self.r_pt*tan(abs(alpha)/2)
            xt2_pt = self.x1_pt + dx2*self.r_pt*tan(abs(alpha)/2)
            yt2_pt = self.y1_pt + dy2*self.r_pt*tan(abs(alpha)/2)

            # direction point 1 -> center of arc
            dmx_pt = 0.5*(xt1_pt+xt2_pt) - self.x1_pt
            dmy_pt = 0.5*(yt1_pt+yt2_pt) - self.y1_pt
            lm_pt = math.hypot(dmx_pt, dmy_pt)
            dmx, dmy = dmx_pt/lm_pt, dmy_pt/lm_pt

            # center of arc
            mx_pt = self.x1_pt + dmx*self.r_pt/cos(alpha/2)
            my_pt = self.y1_pt + dmy*self.r_pt/cos(alpha/2)

            # angle around which arc is centered
            phi = degrees(math.atan2(-dmy, -dmx))

            # half angular width of arc
            deltaphi = degrees(alpha)/2

            line = lineto_pt(*_arcpoint(mx_pt, my_pt, self.r_pt, phi-deltaphi))
            if alpha > 0:
                return [line, arc_pt(mx_pt, my_pt, self.r_pt, phi-deltaphi, phi+deltaphi)]
            else:
                return [line, arcn_pt(mx_pt, my_pt, self.r_pt, phi-deltaphi, phi+deltaphi)]

        except ZeroDivisionError:
            # in the degenerate case, we just return a line as specified by the PS 
            # language reference
            return [lineto_pt(self.x1_pt, self.y1_pt)]

    def updatebbox(self, bbox, context):
        for pathitem in self._pathitems(context.x_pt, context.y_pt):
            pathitem.updatebbox(bbox, context)

    def updatenormpath(self, normpath, context):
        for pathitem in self._pathitems(context.x_pt, context.y_pt):
            pathitem.updatenormpath(normpath, context)

    def outputPS(self, file, writer):
        file.write("%g %g %g %g %g arct\n" % (self.x1_pt, self.y1_pt,
                                              self.x2_pt, self.y2_pt,
                                              self.r_pt))

    def returnSVGdata(self, inverse_y, first, context):
        # first is always False as arct cannot be first, it has no createcontext method
        return "".join(pathitem.returnSVGdata(inverse_y, first, context) for pathitem in self._pathitems(context.x_pt, context.y_pt))

#
# now the pathitems that convert from user coordinates to pts
#

class moveto(moveto_pt):

    """Set current point to (x, y)"""

    __slots__ = "x_pt", "y_pt"

    def __init__(self, x, y):
        moveto_pt.__init__(self, unit.topt(x), unit.topt(y))


class lineto(lineto_pt):

    """Append straight line to (x, y)"""

    __slots__ = "x_pt", "y_pt"

    def __init__(self, x, y):
        lineto_pt.__init__(self, unit.topt(x), unit.topt(y))


class curveto(curveto_pt):

    """Append curveto"""

    __slots__ = "x1_pt", "y1_pt", "x2_pt", "y2_pt", "x3_pt", "y3_pt"

    def __init__(self, x1, y1, x2, y2, x3, y3):
        curveto_pt.__init__(self,
                            unit.topt(x1), unit.topt(y1),
                            unit.topt(x2), unit.topt(y2),
                            unit.topt(x3), unit.topt(y3))

class rmoveto(rmoveto_pt):

    """Perform relative moveto"""

    __slots__ = "dx_pt", "dy_pt"

    def __init__(self, dx, dy):
        rmoveto_pt.__init__(self, unit.topt(dx), unit.topt(dy))


class rlineto(rlineto_pt):

    """Perform relative lineto"""

    __slots__ = "dx_pt", "dy_pt"

    def __init__(self, dx, dy):
        rlineto_pt.__init__(self, unit.topt(dx), unit.topt(dy))


class rcurveto(rcurveto_pt):

    """Append rcurveto"""

    __slots__ = "dx1_pt", "dy1_pt", "dx2_pt", "dy2_pt", "dx3_pt", "dy3_pt"

    def __init__(self, dx1, dy1, dx2, dy2, dx3, dy3):
        rcurveto_pt.__init__(self,
                             unit.topt(dx1), unit.topt(dy1),
                             unit.topt(dx2), unit.topt(dy2),
                             unit.topt(dx3), unit.topt(dy3))


class arcn(arcn_pt):

    """Append clockwise arc"""

    __slots__ = "x_pt", "y_pt", "r_pt", "angle1", "angle2"

    def __init__(self, x, y, r, angle1, angle2):
        arcn_pt.__init__(self, unit.topt(x), unit.topt(y), unit.topt(r), angle1, angle2)


class arc(arc_pt):

    """Append counterclockwise arc"""

    __slots__ = "x_pt", "y_pt", "r_pt", "angle1", "angle2"

    def __init__(self, x, y, r, angle1, angle2):
        arc_pt.__init__(self, unit.topt(x), unit.topt(y), unit.topt(r), angle1, angle2)


class arct(arct_pt):

    """Append tangent arc"""

    __slots__ = "x1_pt", "y1_pt", "x2_pt", "y2_pt", "r_pt"

    def __init__(self, x1, y1, x2, y2, r):
        arct_pt.__init__(self, unit.topt(x1), unit.topt(y1),
                         unit.topt(x2), unit.topt(y2), unit.topt(r))

#
# "combined" pathitems provided for performance reasons
#

class multilineto_pt(pathitem):

    """Perform multiple linetos (coordinates in pts)"""

    __slots__ = "points_pt"

    def __init__(self, points_pt):
        self.points_pt = points_pt

    def __str__(self):
        result = []
        for point_pt in self.points_pt:
            result.append("(%g, %g)" % point_pt )
        return "multilineto_pt([%s])" % (", ".join(result))

    def updatebbox(self, bbox, context):
        for point_pt in self.points_pt:
            bbox.includepoint_pt(*point_pt)
        if self.points_pt:
            context.x_pt, context.y_pt = self.points_pt[-1]

    def updatenormpath(self, normpath, context):
        x0_pt, y0_pt = context.x_pt, context.y_pt
        for point_pt in self.points_pt:
            normpath.normsubpaths[-1].append(normline_pt(x0_pt, y0_pt, *point_pt))
            x0_pt, y0_pt = point_pt
        context.x_pt, context.y_pt = x0_pt, y0_pt

    def outputPS(self, file, writer):
        for point_pt in self.points_pt:
            file.write("%g %g lineto\n" % point_pt )

    def returnSVGdata(self, inverse_y, first, context):
        if self.points_pt:
            context.x_pt, context.y_pt = self.points_pt[-1]
        if inverse_y:
            return "".join("L%g %g" % (x_pt, -y_pt) for x_pt, y_pt in self.points_pt)
        return "".join("L%g %g" % point_pt for point_pt in self.points_pt)


class multicurveto_pt(pathitem):

    """Perform multiple curvetos (coordinates in pts)"""

    __slots__ = "points_pt"

    def __init__(self, points_pt):
        self.points_pt = points_pt

    def __str__(self):
        result = []
        for point_pt in self.points_pt:
            result.append("(%g, %g, %g, %g, %g, %g)" % point_pt )
        return "multicurveto_pt([%s])" % (", ".join(result))

    def updatebbox(self, bbox, context):
        for point_pt in self.points_pt:
            xmin_pt, xmax_pt = _bezierpolyrange(context.x_pt, point_pt[0], point_pt[2], point_pt[4])
            ymin_pt, ymax_pt = _bezierpolyrange(context.y_pt, point_pt[1], point_pt[3], point_pt[5])
            bbox.includepoint_pt(xmin_pt, ymin_pt)
            bbox.includepoint_pt(xmax_pt, ymax_pt)
            context.x_pt, context.y_pt = point_pt[4:]

    def updatenormpath(self, normpath, context):
        x0_pt, y0_pt = context.x_pt, context.y_pt
        for point_pt in self.points_pt:
            normpath.normsubpaths[-1].append(normcurve_pt(x0_pt, y0_pt, *point_pt))
            x0_pt, y0_pt = point_pt[4:]
        context.x_pt, context.y_pt = x0_pt, y0_pt

    def outputPS(self, file, writer):
        for point_pt in self.points_pt:
            file.write("%g %g %g %g %g %g curveto\n" % point_pt)

    def returnSVGdata(self, inverse_y, first, context):
        if self.points_pt:
            context.x_pt, context.y_pt = self.points_pt[-1][4:]
        if inverse_y:
            return "".join("C%g %g %g %g %g %g" % (x1_pt, -y1_pt, x2_pt, -y2_pt, x3_pt, -y3_pt)
                           for x1_pt, y1_pt, x2_pt, y2_pt, x3_pt, y3_pt in self.points_pt)
        return "".join("C%g %g %g %g %g %g" % point_pt for point_pt in self.points_pt)


################################################################################
# path: PS style path
################################################################################

class path:

    """PS style path"""

    __slots__ = "pathitems", "_normpath"

    def __init__(self, *pathitems):
        """construct a path from pathitems *args"""

        for apathitem in pathitems:
            assert isinstance(apathitem, pathitem), "only pathitem instances allowed"

        self.pathitems = list(pathitems)
        # normpath cache (when no epsilon is set)
        self._normpath = None

    def __add__(self, other):
        """create new path out of self and other"""
        return path(*(self.pathitems + other.path().pathitems))

    def __iadd__(self, other):
        """add other inplace

        If other is a normpath instance, it is converted to a path before
        being added.
        """
        self.pathitems += other.path().pathitems
        self._normpath = None
        return self

    def __getitem__(self, i):
        """return path item i"""
        return self.pathitems[i]

    def __len__(self):
        """return the number of path items"""
        return len(self.pathitems)

    def __str__(self):
        l = ", ".join(map(str, self.pathitems))
        return "path(%s)" % l

    def append(self, apathitem):
        """append a path item"""
        assert isinstance(apathitem, pathitem), "only pathitem instance allowed"
        self.pathitems.append(apathitem)
        self._normpath = None

    def arclen_pt(self):
        """return arc length in pts"""
        return self.normpath().arclen_pt()

    def arclen(self):
        """return arc length"""
        return self.normpath().arclen()

    def arclentoparam_pt(self, lengths_pt):
        """return the param(s) matching the given length(s)_pt in pts"""
        return self.normpath().arclentoparam_pt(lengths_pt)

    def arclentoparam(self, lengths):
        """return the param(s) matching the given length(s)"""
        return self.normpath().arclentoparam(lengths)

    def at_pt(self, params):
        """return coordinates of path in pts at param(s) or arc length(s) in pts"""
        return self.normpath().at_pt(params)

    def at(self, params):
        """return coordinates of path at param(s) or arc length(s)"""
        return self.normpath().at(params)

    def atbegin_pt(self):
        """return coordinates of the beginning of first subpath in path in pts"""
        return self.normpath().atbegin_pt()

    def atbegin(self):
        """return coordinates of the beginning of first subpath in path"""
        return self.normpath().atbegin()

    def atend_pt(self):
        """return coordinates of the end of last subpath in path in pts"""
        return self.normpath().atend_pt()

    def atend(self):
        """return coordinates of the end of last subpath in path"""
        return self.normpath().atend()

    def bbox(self):
        """return bbox of path"""
        if self.pathitems:
            bbox = self.pathitems[0].createbbox()
            context = self.pathitems[0].createcontext()
            for pathitem in self.pathitems[1:]:
                pathitem.updatebbox(bbox, context)
            return bbox
        else:
            return bboxmodule.empty()

    def begin(self):
        """return param corresponding of the beginning of the path"""
        return self.normpath().begin()

    def curvature_pt(self, params):
        """return the curvature in 1/pts at param(s) or arc length(s) in pts"""
        return self.normpath().curvature_pt(params)

    def end(self):
        """return param corresponding of the end of the path"""
        return self.normpath().end()

    def extend(self, pathitems):
        """extend path by pathitems"""
        for apathitem in pathitems:
            assert isinstance(apathitem, pathitem), "only pathitem instance allowed"
        self.pathitems.extend(pathitems)
        self._normpath = None

    def intersect(self, other):
        """intersect self with other path

        Returns a tuple of lists consisting of the parameter values
        of the intersection points of the corresponding normpath.
        """
        return self.normpath().intersect(other)

    def join(self, other):
        """join other path/normpath inplace

        If other is a normpath instance, it is converted to a path before
        being joined.
        """
        self.pathitems = self.joined(other).path().pathitems
        self._normpath = None
        return self

    def joined(self, other):
        """return path consisting of self and other joined together"""
        return self.normpath().joined(other).path()

    # << operator also designates joining
    __lshift__ = joined

    def normpath(self, epsilon=_marker):
        """convert the path into a normpath"""
        # use cached value if existent and epsilon is _marker
        if self._normpath is not None and epsilon is _marker:
            return self._normpath
        if self.pathitems:
            if epsilon is _marker:
                np = self.pathitems[0].createnormpath()
            else:
                np = self.pathitems[0].createnormpath(epsilon)
            context = self.pathitems[0].createcontext()
            for pathitem in self.pathitems[1:]:
                pathitem.updatenormpath(np, context)
        else:
            np = normpath()
        if epsilon is _marker:
            self._normpath = np
        return np

    def paramtoarclen_pt(self, params):
        """return arc lenght(s) in pts matching the given param(s)"""
        return self.normpath().paramtoarclen_pt(params)

    def paramtoarclen(self, params):
        """return arc lenght(s) matching the given param(s)"""
        return self.normpath().paramtoarclen(params)

    def path(self):
        """return corresponding path, i.e., self"""
        return self

    def reversed(self):
        """return reversed normpath"""
        # TODO: couldn't we try to return a path instead of converting it
        #       to a normpath (but this might not be worth the trouble)
        return self.normpath().reversed()

    def rotation_pt(self, params):
        """return rotation at param(s) or arc length(s) in pts"""
        return self.normpath().rotation(params)

    def rotation(self, params):
        """return rotation at param(s) or arc length(s)"""
        return self.normpath().rotation(params)

    def split_pt(self, params):
        """split normpath at param(s) or arc length(s) in pts and return list of normpaths"""
        return self.normpath().split_pt(params)

    def split(self, params):
        """split normpath at param(s) or arc length(s) and return list of normpaths"""
        return self.normpath().split(params)

    def tangent_pt(self, params, length):
        """return tangent vector of path at param(s) or arc length(s) in pts

        If length in pts is not None, the tangent vector will be scaled to
        the desired length.
        """
        return self.normpath().tangent_pt(params, length)

    def tangent(self, params, length=1):
        """return tangent vector of path at param(s) or arc length(s)

        If length is not None, the tangent vector will be scaled to
        the desired length.
        """
        return self.normpath().tangent(params, length)

    def trafo_pt(self, params):
        """return transformation at param(s) or arc length(s) in pts"""
        return self.normpath().trafo(params)

    def trafo(self, params):
        """return transformation at param(s) or arc length(s)"""
        return self.normpath().trafo(params)

    def transformed(self, trafo):
        """return transformed path"""
        return self.normpath().transformed(trafo)

    def outputPS(self, file, writer):
        """write PS code to file"""
        for pitem in self.pathitems:
            pitem.outputPS(file, writer)

    def outputPDF(self, file, writer):
        """write PDF code to file"""
        # PDF only supports normsubpathitems; we need to use a normpath
        # with epsilon equals None to prevent failure for paths shorter
        # than epsilon
        self.normpath(epsilon=None).outputPDF(file, writer)

    def returnSVGdata(self, inverse_y=True):
        """return SVG code"""
        if not self.pathitems:
            return ""
        context = self.pathitems[0].createcontext()
        return "".join(pitem.returnSVGdata(inverse_y, not i, context) for i, pitem in enumerate(self.pathitems))


#
# some special kinds of path, again in two variants
#

class line_pt(path):

    """straight line from (x1_pt, y1_pt) to (x2_pt, y2_pt) in pts"""

    def __init__(self, x1_pt, y1_pt, x2_pt, y2_pt):
        path.__init__(self, moveto_pt(x1_pt, y1_pt), lineto_pt(x2_pt, y2_pt))


class curve_pt(path):

    """bezier curve with control points (x0_pt, y1_pt),..., (x3_pt, y3_pt) in pts"""

    def __init__(self, x0_pt, y0_pt, x1_pt, y1_pt, x2_pt, y2_pt, x3_pt, y3_pt):
        path.__init__(self,
                      moveto_pt(x0_pt, y0_pt),
                      curveto_pt(x1_pt, y1_pt, x2_pt, y2_pt, x3_pt, y3_pt))


class rect_pt(path):

    """rectangle at position (x_pt, y_pt) with width_pt and height_pt in pts"""

    def __init__(self, x_pt, y_pt, width_pt, height_pt):
        path.__init__(self, moveto_pt(x_pt, y_pt),
                            lineto_pt(x_pt+width_pt, y_pt),
                            lineto_pt(x_pt+width_pt, y_pt+height_pt),
                            lineto_pt(x_pt, y_pt+height_pt),
                            closepath())


class circle_pt(path):

    """circle with center (x_pt, y_pt) and radius_pt in pts"""

    def __init__(self, x_pt, y_pt, radius_pt, arcepsilon=0.1):
        path.__init__(self, moveto_pt(x_pt+radius_pt, y_pt),
                            arc_pt(x_pt, y_pt, radius_pt, arcepsilon, 360-arcepsilon),
                            closepath())


class ellipse_pt(path):

    """ellipse with center (x_pt, y_pt) in pts,
    the two axes (a_pt, b_pt) in pts,
    and the angle angle of the first axis"""

    def __init__(self, x_pt, y_pt, a_pt, b_pt, angle, **kwargs):
        t = trafo.scale(a_pt, b_pt).rotated(angle).translated_pt(x_pt, y_pt)
        p = circle_pt(0, 0, 1, **kwargs).normpath(epsilon=None).transformed(t).path()
        path.__init__(self, *p.pathitems)


class line(line_pt):

    """straight line from (x1, y1) to (x2, y2)"""

    def __init__(self, x1, y1, x2, y2):
        line_pt.__init__(self, unit.topt(x1), unit.topt(y1),
                               unit.topt(x2), unit.topt(y2))


class curve(curve_pt):

    """bezier curve with control points (x0, y1),..., (x3, y3)"""

    def __init__(self, x0, y0, x1, y1, x2, y2, x3, y3):
        curve_pt.__init__(self, unit.topt(x0), unit.topt(y0),
                                unit.topt(x1), unit.topt(y1),
                                unit.topt(x2), unit.topt(y2),
                                unit.topt(x3), unit.topt(y3))


class rect(rect_pt):

    """rectangle at position (x,y) with width and height"""

    def __init__(self, x, y, width, height):
        rect_pt.__init__(self, unit.topt(x), unit.topt(y),
                               unit.topt(width), unit.topt(height))


class circle(circle_pt):

    """circle with center (x,y) and radius"""

    def __init__(self, x, y, radius, **kwargs):
        circle_pt.__init__(self, unit.topt(x), unit.topt(y), unit.topt(radius), **kwargs)


class ellipse(ellipse_pt):

    """ellipse with center (x, y), the two axes (a, b),
    and the angle angle of the first axis"""

    def __init__(self, x, y, a, b, angle, **kwargs):
        ellipse_pt.__init__(self, unit.topt(x), unit.topt(y), unit.topt(a), unit.topt(b), angle, **kwargs)