This file is indexed.

/usr/lib/python3/dist-packages/qwt/text.py is in python3-qwt 0.5.5-1.

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
# -*- coding: utf-8 -*-
#
# Licensed under the terms of the Qwt License
# Copyright (c) 2002 Uwe Rathmann, for the original C++ code
# Copyright (c) 2015 Pierre Raybaut, for the Python translation/optimization
# (see LICENSE file for more details)

"""
Text widgets
------------

QwtText
~~~~~~~

.. autoclass:: QwtText
   :members:
   
QwtTextLabel
~~~~~~~~~~~~

.. autoclass:: QwtTextLabel
   :members:

Text engines
------------

QwtTextEngine
~~~~~~~~~~~~~

.. autoclass:: QwtTextEngine
   :members:

QwtPlainTextEngine
~~~~~~~~~~~~~~~~~~
   
.. autoclass:: QwtPlainTextEngine
   :members:

QwtRichTextEngine
~~~~~~~~~~~~~~~~~
   
.. autoclass:: QwtRichTextEngine
   :members:
"""

import numpy as np
import struct

from qwt.qt.QtGui import (QPainter, QFrame, QSizePolicy, QPalette, QFont,
                          QFontMetrics, QApplication, QColor, QWidget,
                          QTextDocument, QTextOption, QFontMetricsF, QPixmap,
                          QFontInfo, QTransform, QAbstractTextDocumentLayout)
from qwt.qt.QtCore import Qt, QSizeF, QSize, QRectF

from qwt.painter import QwtPainter

QWIDGETSIZE_MAX = (1<<24)-1


def taggedRichText(text, flags):
    richText = text
    if flags & Qt.AlignJustify:
        richText = "<div align=\"justify\">" + richText + "</div>"
    elif flags & Qt.AlignRight:
        richText = "<div align=\"right\">" + richText + "</div>"
    elif flags & Qt.AlignHCenter:
        richText = "<div align=\"center\">" + richText + "</div>"
    return richText


class QwtRichTextDocument(QTextDocument):
    def __init__(self, text, flags, font):
        super(QwtRichTextDocument, self).__init__(None)
        self.setUndoRedoEnabled(False)
        self.setDefaultFont(font)
        self.setHtml(text)
        
        option = self.defaultTextOption()
        if flags & Qt.TextWordWrap:
            option.setWrapMode(QTextOption.WordWrap)
        else:
            option.setWrapMode(QTextOption.NoWrap)
        
        option.setAlignment(flags)
        self.setDefaultTextOption(option)
        
        root = self.rootFrame()
        fm = root.frameFormat()
        fm.setBorder(0)
        fm.setMargin(0)
        fm.setPadding(0)
        fm.setBottomMargin(0)
        fm.setLeftMargin(0)
        root.setFrameFormat(fm)

        self.adjustSize();


class QwtTextEngine(object):
    """
    Abstract base class for rendering text strings

    A text engine is responsible for rendering texts for a
    specific text format. They are used by `QwtText` to render a text.

    `QwtPlainTextEngine` and `QwtRichTextEngine` are part of the 
    `PythonQwt` library.
    The implementation of `QwtMathMLTextEngine` uses code from the 
    `Qt` solution package. Because of license implications it is built into
    a separate library.
 
    .. seealso::
    
        :py:meth:`qwt.text.QwtText.setTextEngine()`
    """
    def __init__(self):
        pass
    
    def heightForWidth(self, font, flags, text, width):
        """
        Find the height for a given width

        :param QFont font: Font of the text
        :param int flags: Bitwise OR of the flags used like in QPainter::drawText
        :param str text: Text to be rendered
        :param float width: Width
        :return: Calculated height
        """
        pass
    
    def textSize(self, font, flags, text):
        """
        Returns the size, that is needed to render text

        :param QFont font: Font of the text
        :param int flags: Bitwise OR of the flags like in for QPainter::drawText
        :param str text: Text to be rendered
        :return: Calculated size
        """
        pass

    def mightRender(self, text):
        """
        Test if a string can be rendered by this text engine

        :param str text: Text to be tested
        :return: True, if it can be rendered
        """
        pass

    def textMargins(self, font):
        """
        Return margins around the texts

        The textSize might include margins around the
        text, like QFontMetrics::descent(). In situations
        where texts need to be aligned in detail, knowing
        these margins might improve the layout calculations.

        :param QFont font: Font of the text
        :return: tuple (left, right, top, bottom) representing margins
        """
        pass

    def draw(self, painter, rect, flags, text):
        """
        Draw the text in a clipping rectangle

        :param QPainter painter: Painter
        :param QRectF rect: Clipping rectangle
        :param int flags: Bitwise OR of the flags like in for QPainter::drawText()
        :param str text: Text to be rendered
        """
        pass


ASCENTCACHE = {}

def qwtScreenResolution():
    screenResolution = QSize()
    if not screenResolution.isValid():
        desktop = QApplication.desktop()
        if desktop is not None:
            screenResolution.setWidth(desktop.logicalDpiX())
            screenResolution.setHeight(desktop.logicalDpiY())
    return screenResolution

def qwtUnscaleFont(painter):
    if painter.font().pixelSize() >= 0:
        return
    screenResolution = qwtScreenResolution()
    pd = painter.device()
    if pd.logicalDpiX() != screenResolution.width() or\
       pd.logicalDpiY() != screenResolution.height():
        pixelFont = QFont(painter.font(), QApplication.desktop())
        pixelFont.setPixelSize(QFontInfo(pixelFont).pixelSize())
        painter.setFont(pixelFont)

class QwtPlainTextEngine(QwtTextEngine):
    """
    A text engine for plain texts

    `QwtPlainTextEngine` renders texts using the basic `Qt` classes
    `QPainter` and `QFontMetrics`.
    """
    def __init__(self):
        self.qrectf_max = QRectF(0, 0, QWIDGETSIZE_MAX, QWIDGETSIZE_MAX)
        self._fm_cache = {}
        self._fm_cache_f = {}
    
    def fontmetrics(self, font):
        fid = font.toString()
        fm = self._fm_cache.get(fid)
        if fm is None:
            return self._fm_cache.setdefault(fid, QFontMetrics(font))
        else:
            return fm
    
    def fontmetrics_f(self, font):
        fid = font.toString()
        fm = self._fm_cache_f.get(fid)
        if fm is None:
            return self._fm_cache_f.setdefault(fid, QFontMetricsF(font))
        else:
            return fm
    
    def heightForWidth(self, font, flags, text, width):
        """
        Find the height for a given width

        :param QFont font: Font of the text
        :param int flags: Bitwise OR of the flags used like in QPainter::drawText
        :param str text: Text to be rendered
        :param float width: Width
        :return: Calculated height
        """
        fm = self.fontmetrics_f(font)
        rect = fm.boundingRect(QRectF(0, 0, width, QWIDGETSIZE_MAX),
                               flags, text)
        return rect.height()
    
    def textSize(self, font, flags, text):
        """
        Returns the size, that is needed to render text

        :param QFont font: Font of the text
        :param int flags: Bitwise OR of the flags like in for QPainter::drawText
        :param str text: Text to be rendered
        :return: Calculated size
        """
        fm = self.fontmetrics_f(font)
        rect = fm.boundingRect(self.qrectf_max, flags, text)
        return rect.size()
    
    def effectiveAscent(self, font):
        global ASCENTCACHE
        fontKey = font.key()
        ascent = ASCENTCACHE.get(fontKey)
        if ascent is not None:
            return ascent
        return ASCENTCACHE.setdefault(fontKey, self.findAscent(font))
    
    def findAscent(self, font):
        dummy = "E"
        white = QColor(Qt.white)

        fm = self.fontmetrics(font)
        pm = QPixmap(fm.width(dummy), fm.height())
        pm.fill(white)
        
        p = QPainter(pm)
        p.setFont(font)
        p.drawText(0, 0, pm.width(), pm.height(), 0, dummy)
        p.end()
        
        img = pm.toImage()
        
        w = pm.width()
        linebytes = w*4
        for row in range(img.height()):
            line = img.scanLine(row).asstring(linebytes)
            for col in range(w):
                color = struct.unpack('I', line[col*4:(col+1)*4])[0]
                if color != white.rgb():
                    return fm.ascent()-row+1
        return fm.ascent()

    def textMargins(self, font):
        """
        Return margins around the texts

        The textSize might include margins around the
        text, like QFontMetrics::descent(). In situations
        where texts need to be aligned in detail, knowing
        these margins might improve the layout calculations.

        :param QFont font: Font of the text
        :return: tuple (left, right, top, bottom) representing margins
        """
        left = right = top = 0
        fm = self.fontmetrics_f(font)
        top = fm.ascent() - self.effectiveAscent(font)
        bottom = fm.descent()
        return left, right, top, bottom

    def draw(self, painter, rect, flags, text):
        """
        Draw the text in a clipping rectangle

        :param QPainter painter: Painter
        :param QRectF rect: Clipping rectangle
        :param int flags: Bitwise OR of the flags like in for QPainter::drawText()
        :param str text: Text to be rendered
        """
        painter.save()
        qwtUnscaleFont(painter)
        painter.drawText(rect, flags, text)
        painter.restore()
    
    def mightRender(self, text):
        """
        Test if a string can be rendered by this text engine

        :param str text: Text to be tested
        :return: True, if it can be rendered
        """
        return True


class QwtRichTextEngine(QwtTextEngine):
    """
    A text engine for `Qt` rich texts

    `QwtRichTextEngine` renders `Qt` rich texts using the classes
    of the Scribe framework of `Qt`.
    """
    def __init__(self):
        pass
    
    def heightForWidth(self, font, flags, text, width):
        """
        Find the height for a given width

        :param QFont font: Font of the text
        :param int flags: Bitwise OR of the flags used like in QPainter::drawText
        :param str text: Text to be rendered
        :param float width: Width
        :return: Calculated height
        """
        doc = QwtRichTextDocument(text, flags, font)
        doc.setPageSize(QSizeF(width, QWIDGETSIZE_MAX))
        return doc.documentLayout().documentSize().height()
    
    def textSize(self, font, flags, text):
        """
        Returns the size, that is needed to render text

        :param QFont font: Font of the text
        :param int flags: Bitwise OR of the flags like in for QPainter::drawText
        :param str text: Text to be rendered
        :return: Calculated size
        """
        doc = QwtRichTextDocument(text, flags, font)
        option = doc.defaultTextOption()
        if option.wrapMode() != QTextOption.NoWrap:
            option.setWrapMode(QTextOption.NoWrap)
            doc.setDefaultTextOption(option)
            doc.adjustSize()
        return doc.size()
    
    def draw(self, painter, rect, flags, text):
        """
        Draw the text in a clipping rectangle

        :param QPainter painter: Painter
        :param QRectF rect: Clipping rectangle
        :param int flags: Bitwise OR of the flags like in for QPainter::drawText()
        :param str text: Text to be rendered
        """
        txt = QwtRichTextDocument(text, flags, painter.font())
        painter.save()
        unscaledRect = QRectF(rect)
        if painter.font().pixelSize() < 0:
            res = qwtScreenResolution()
            pd = painter.device()
            if pd.logicalDpiX() != res.width()\
               or pd.logicalDpiY() != res.height():
                transform = QTransform()
                transform.scale(res.width()/float(pd.logicalDpiX()),
                                res.height()/float(pd.logicalDpiY()))
                painter.setWorldTransform(transform, True)
                invtrans, _ok = transform.inverted()
                unscaledRect = invtrans.mapRect(rect)
        txt.setDefaultFont(painter.font())
        txt.setPageSize(QSizeF(unscaledRect.width(), QWIDGETSIZE_MAX))
        layout = txt.documentLayout()
        height = layout.documentSize().height()
        y = unscaledRect.y()
        if flags & Qt.AlignBottom:
            y += unscaledRect.height()-height
        elif flags & Qt.AlignVCenter:
            y += (unscaledRect.height()-height)/2
        context = QAbstractTextDocumentLayout.PaintContext()
        context.palette.setColor(QPalette.Text, painter.pen().color())
        painter.translate(unscaledRect.x(), y)
        layout.draw(painter, context)
        painter.restore()
    
    def taggedText(self, text, flags):
        return self.taggedRichText(text,flags)

    def mightRender(self, text):
        """
        Test if a string can be rendered by this text engine

        :param str text: Text to be tested
        :return: True, if it can be rendered
        """
        return Qt.mightBeRichText(text)
    
    def textMargins(self, font):
        """
        Return margins around the texts

        The textSize might include margins around the
        text, like QFontMetrics::descent(). In situations
        where texts need to be aligned in detail, knowing
        these margins might improve the layout calculations.

        :param QFont font: Font of the text
        :return: tuple (left, right, top, bottom) representing margins
        """
        return 0, 0, 0, 0



class QwtText_PrivateData(object):
    def __init__(self):
        self.renderFlags = Qt.AlignCenter
        self.borderRadius = 0
        self.borderPen = Qt.NoPen
        self.backgroundBrush = Qt.NoBrush
        self.paintAttributes = 0
        self.layoutAttributes = 0
        self.textEngine = None
        
        self.text = None
        self.font = None
        self.color = None

class QwtText_LayoutCache(object):
    def __init__(self):
        self.textSize = QSizeF()
        self.font = None
    
    def invalidate(self):
        self.textSize = QSizeF()

class QwtText(object):
    """
    A class representing a text

    A `QwtText` is a text including a set of attributes how to render it.

      - Format:
      
      A text might include control sequences (f.e tags) describing
      how to render it. Each format (f.e MathML, TeX, Qt Rich Text)
      has its own set of control sequences, that can be handles by
      a special `QwtTextEngine` for this format.

      - Background:
      
      A text might have a background, defined by a `QPen` and `QBrush`
      to improve its visibility. The corners of the background might
      be rounded.
      
      - Font:

      A text might have an individual font.

      - Color
      
      A text might have an individual color.
      
      - Render Flags
      
      Flags from `Qt.AlignmentFlag` and `Qt.TextFlag` used like in
      `QPainter.drawText()`.
        
    ..seealso::
    
        :py:meth:`qwt.text.QwtTextEngine`, 
        :py:meth:`qwt.text.QwtTextLabel`
        
    Text formats:
    
      * `QwtText.AutoText`:
      
        The text format is determined using `QwtTextEngine.mightRender()` for
        all available text engines in increasing order > PlainText.
        If none of the text engines can render the text is rendered
        like `QwtText.PlainText`.
          
      * `QwtText.PlainText`:

        Draw the text as it is, using a QwtPlainTextEngine.

      * `QwtText.RichText`:

        Use the Scribe framework (Qt Rich Text) to render the text.
        
      * `QwtText.MathMLText`:

        Use a MathML (http://en.wikipedia.org/wiki/MathML) render engine
        to display the text. The Qwt MathML extension offers such an engine
        based on the MathML renderer of the Qt solutions package. 
        To enable MathML support the following code needs to be added to the
        application::
        
            QwtText.setTextEngine(QwtText.MathMLText, QwtMathMLTextEngine())
        
      * `QwtText.TeXText`:

        Use a TeX (http://en.wikipedia.org/wiki/TeX) render engine
        to display the text ( not implemented yet ).
        
      * `QwtText.OtherFormat`:
      
        The number of text formats can be extended using `setTextEngine`.
        Formats >= `QwtText.OtherFormat` are not used by Qwt.

    Paint attributes:
    
      * `QwtText.PaintUsingTextFont`: The text has an individual font.
      * `QwtText.PaintUsingTextColor`: The text has an individual color.
      * `QwtText.PaintBackground`: The text has an individual background.

    Layout attributes:
    
      * `QwtText.MinimumLayout`:
      
        Layout the text without its margins. This mode is useful if a
        text needs to be aligned accurately, like the tick labels of a scale.
        If `QwtTextEngine.textMargins` is not implemented for the format
        of the text, `MinimumLayout` has no effect.

    .. py:class:: QwtText([text=None], [textFormat=None], [other=None])
    
        :param str text: Text content
        :param int textFormat: Text format
        :param qwt.text.QwtText other: Object to copy (text and textFormat arguments are ignored)
    """

    # enum TextFormat
    AutoText, PlainText, RichText, MathMLText, TeXText = list(range(5))
    OtherFormat = 100
    
    # enum PaintAttribute
    PaintUsingTextFont = 0x01
    PaintUsingTextColor = 0x02
    PaintBackground = 0x04
    
    # enum LayoutAttribute
    MinimumLayout = 0x01

    # Optimization: a single text engine for all QwtText objects
    # (this is not how it's implemented in Qwt6 C++ library)
    __map = {PlainText: QwtPlainTextEngine(), RichText:  QwtRichTextEngine()}

    def __init__(self, text=None, textFormat=None, other=None):
        self.__desktopwidget = None
        if text is None:
            text = ''
        if textFormat is None:
            textFormat = self.AutoText
        if other is not None:
            text = other
        if isinstance(text, QwtText):
            self.__data = text.__data
            self.__layoutCache = text.__layoutCache
        else:
            self.__data = QwtText_PrivateData()
            self.__data.text = text
            self.__data.textEngine = self.textEngine(text, textFormat)
            self.__layoutCache = QwtText_LayoutCache()

    @property
    def _desktopwidget(self):
        """
        Property used to store the Application Desktop Widget to avoid calling 
        the `QApplication.desktop()" function more than necessary as its 
        calling time is not negligible.
        """
        if self.__desktopwidget is None:
            self.__desktopwidget = QApplication.desktop()
        return self.__desktopwidget
    
    def __eq__(self, other):
        return self.__data.renderFlags == other.__data.renderFlags and\
               self.__data.text == other.__data.text and\
               self.__data.font == other.__data.font and\
               self.__data.color == other.__data.color and\
               self.__data.borderRadius == other.__data.borderRadius and\
               self.__data.borderPen == other.__data.borderPen and\
               self.__data.backgroundBrush == other.__data.backgroundBrush and\
               self.__data.paintAttributes == other.__data.paintAttributes and\
               self.__data.textEngine == other.__data.textEngine

    def __ne__(self, other):
        return not self.__eq__(other)

    def isEmpty(self):
        """
        :return: True if text is empty
        """
        return len(self.text()) == 0

    def setText(self, text, textFormat=None):
        """
        Assign a new text content

        :param str text: Text content
        :param int textFormat: Text format

        .. seealso::
        
            :py:meth:`text()`
        """
        if textFormat is None:
            textFormat = self.AutoText
        self.__data.text = text
        self.__data.textEngine = self.textEngine(text, textFormat)
        self.__layoutCache.invalidate()
    
    def text(self):
        """
        :return: Text content

        .. seealso::
        
            :py:meth:`setText()`
        """
        return self.__data.text
    
    def setRenderFlags(self, renderFlags):
        """
        Change the render flags

        The default setting is `Qt.AlignCenter`

        :param int renderFlags: Bitwise OR of the flags used like in `QPainter.drawText()`

        .. seealso::
        
            :py:meth:`renderFlags()`, 
            :py:meth:`qwt.text.QwtTextEngine.draw()`
        """
        renderFlags = Qt.AlignmentFlag(renderFlags)
        if renderFlags != self.__data.renderFlags:
            self.__data.renderFlags = renderFlags
            self.__layoutCache.invalidate()
    
    def renderFlags(self):
        """
        :return: Render flags

        .. seealso::
        
            :py:meth:`setRenderFlags()`
        """
        return self.__data.renderFlags
    
    def setFont(self, font):
        """
        Set the font.

        :param QFont font: Font

        .. note::
        
            Setting the font might have no effect, when
            the text contains control sequences for setting fonts.

        .. seealso::
        
            :py:meth:`font()`, :py:meth:`usedFont()`
        """
        self.__data.font = font
        self.setPaintAttribute(self.PaintUsingTextFont)
    
    def font(self):
        """
        :return: Return the font

        .. seealso::
        
            :py:meth:`setFont()`, :py:meth:`usedFont()`
        """
        return self.__data.font
        
    def usedFont(self, defaultFont):
        """
        Return the font of the text, if it has one.
        Otherwise return defaultFont.
   
        :param QFont defaultFont: Default font
        :return: Font used for drawing the text

        .. seealso::
        
            :py:meth:`setFont()`, :py:meth:`font()`
        """
        if self.__data.paintAttributes & self.PaintUsingTextFont:
            return self.__data.font
        return defaultFont
    
    def setColor(self, color):
        """
        Set the pen color used for drawing the text.
   
        :param QColor color: Color
        
        .. note::
        
            Setting the color might have no effect, when
            the text contains control sequences for setting colors.

        .. seealso::
        
            :py:meth:`color()`, :py:meth:`usedColor()`
        """
        self.__data.color = QColor(color)
        self.setPaintAttribute(self.PaintUsingTextColor)
    
    def color(self):
        """
        :return: Return the pen color, used for painting the text

        .. seealso::
        
            :py:meth:`setColor()`, :py:meth:`usedColor()`
        """
        return self.__data.color
    
    def usedColor(self, defaultColor):
        """
        Return the color of the text, if it has one.
        Otherwise return defaultColor.
   
        :param QColor defaultColor: Default color
        :return: Color used for drawing the text

        .. seealso::
        
            :py:meth:`setColor()`, :py:meth:`color()`
        """
        if self.__data.paintAttributes & self.PaintUsingTextColor:
            return self.__data.color
        return defaultColor
    
    def setBorderRadius(self, radius):
        """
        Set the radius for the corners of the border frame
   
        :param float radius: Radius of a rounded corner

        .. seealso::
        
            :py:meth:`borderRadius()`, :py:meth:`setBorderPen()`, 
            :py:meth:`setBackgroundBrush()`
        """
        self.__data.borderRadius = max([0., radius])
    
    def borderRadius(self):
        """
        :return: Radius for the corners of the border frame

        .. seealso::
        
            :py:meth:`setBorderRadius()`, :py:meth:`borderPen()`, 
            :py:meth:`backgroundBrush()`
        """
        return self.__data.borderRadius
    
    def setBorderPen(self, pen):
        """
        Set the background pen
   
        :param QPen pen: Background pen

        .. seealso::
        
            :py:meth:`borderPen()`, :py:meth:`setBackgroundBrush()`
        """
        self.__data.borderPen = pen
        self.setPaintAttribute(self.PaintBackground)
    
    def borderPen(self):
        """
        :return: Background pen

        .. seealso::
        
            :py:meth:`setBorderPen()`, :py:meth:`backgroundBrush()`
        """
        return self.__data.borderPen
            
    def setBackgroundBrush(self, brush):
        """
        Set the background brush
   
        :param QBrush brush: Background brush

        .. seealso::
        
            :py:meth:`backgroundBrush()`, :py:meth:`setBorderPen()`
        """
        self.__data.backgroundBrush = brush
        self.setPaintAttribute(self.PaintBackground)
    
    def backgroundBrush(self):
        """
        :return: Background brush

        .. seealso::
        
            :py:meth:`setBackgroundBrush()`, :py:meth:`borderPen()`
        """
        return self.__data.backgroundBrush
    
    def setPaintAttribute(self, attribute, on=True):
        """
        Change a paint attribute
   
        :param int attribute: Paint attribute
        :param bool on: On/Off

        .. note::
        
            Used by `setFont()`, `setColor()`, `setBorderPen()` 
            and `setBackgroundBrush()`

        .. seealso::
        
            :py:meth:`testPaintAttribute()`
        """
        if on:
            self.__data.paintAttributes |= attribute
        else:
            self.__data.paintAttributes &= ~attribute
    
    def testPaintAttribute(self, attribute):
        """
        Test a paint attribute
   
        :param int attribute: Paint attribute
        :return: True, if attribute is enabled

        .. seealso::
        
            :py:meth:`setPaintAttribute()`
        """
        return self.__data.paintAttributes & attribute
        
    
    def setLayoutAttribute(self, attribute, on=True):
        """
        Change a layout attribute
   
        :param int attribute: Layout attribute
        :param bool on: On/Off

        .. seealso::
        
            :py:meth:`testLayoutAttribute()`
        """
        if on:
            self.__data.layoutAttributes |= attribute
        else:
            self.__data.layoutAttributes &= ~attribute
    
    def testLayoutAttribute(self, attribute):
        """
        Test a layout attribute
   
        :param int attribute: Layout attribute
        :return: True, if attribute is enabled

        .. seealso::
        
            :py:meth:`setLayoutAttribute()`
        """
        return self.__data.layoutAttributes & attribute
    
    def heightForWidth(self, width, defaultFont=None):
        """
        Find the height for a given width
   
        :param float width: Width
        :param QFont defaultFont: Font, used for the calculation if the text has no font
        :return: Calculated height
        """
        if defaultFont is None:
            defaultFont = QFont()
        font = QFont(self.usedFont(defaultFont), self._desktopwidget)
        h = 0
        if self.__data.layoutAttributes & self.MinimumLayout:
            (left, right, top, bottom
             ) = self.__data.textEngine.textMargins(font)
            h = self.__data.textEngine.heightForWidth(font,
                            self.__data.renderFlags, self.__data.text,
                            width + left + right)
            h -= top + bottom
        else:
            h = self.__data.textEngine.heightForWidth(font,
                            self.__data.renderFlags, self.__data.text, width)
        return h
    
    def textSize(self, defaultFont):
        """
        Returns the size, that is needed to render text
   
        :param QFont defaultFont Font, used for the calculation if the text has no font
        :return: Caluclated size
        """
        font = QFont(self.usedFont(defaultFont), self._desktopwidget)
        if not self.__layoutCache.textSize.isValid() or\
           self.__layoutCache.font is not font:
            self.__layoutCache.textSize =\
                self.__data.textEngine.textSize(font, self.__data.renderFlags,
                                                self.__data.text)
            self.__layoutCache.font = font
        sz = self.__layoutCache.textSize
        if self.__data.layoutAttributes & self.MinimumLayout:
            (left, right, top, bottom
             ) = self.__data.textEngine.textMargins(font)
            sz -= QSizeF(left + right, top + bottom)
        return sz
    
    def draw(self, painter, rect):
        """
        Draw a text into a rectangle
   
        :param QPainter painter: Painter
        :param QRectF rect: Rectangle
        """
        if self.__data.paintAttributes & self.PaintBackground:
            if self.__data.borderPen != Qt.NoPen or\
               self.__data.backgroundBrush != Qt.NoBrush:
                painter.save()
                painter.setPen(self.__data.borderPen)
                painter.setBrush(self.__data.backgroundBrush)
                if self.__data.borderRadius == 0:
                    painter.drawRect(rect)
                else:
                    painter.setRenderHint(QPainter.Antialiasing, True)
                    painter.drawRoundedRect(rect, self.__data.borderRadius,
                                            self.__data.borderRadius)
                painter.restore()
        painter.save()
        if self.__data.paintAttributes & self.PaintUsingTextFont:
            painter.setFont(self.__data.font)
        if self.__data.paintAttributes & self.PaintUsingTextColor:
            if self.__data.color.isValid():
                painter.setPen(self.__data.color)
        expandedRect = rect
        if self.__data.layoutAttributes & self.MinimumLayout:
            font = QFont(painter.font(), self._desktopwidget)
            (left, right, top, bottom
             ) = self.__data.textEngine.textMargins(font)
            expandedRect.setTop(rect.top()-top)
            expandedRect.setBottom(rect.bottom()+bottom)
            expandedRect.setLeft(rect.left()-left)
            expandedRect.setRight(rect.right()+right)
        self.__data.textEngine.draw(painter, expandedRect,
                                    self.__data.renderFlags, self.__data.text)
        painter.restore()
    
    def textEngine(self, text=None, format_=None):
        """
        Find the text engine for a text format

        In case of `QwtText.AutoText` the first text engine
        (beside `QwtPlainTextEngine`) is returned, where 
        `QwtTextEngine.mightRender` returns true. 
        If there is none `QwtPlainTextEngine` is returned.

        If no text engine is registered for the format `QwtPlainTextEngine`
        is returned.

        :param str text: Text, needed in case of AutoText
        :param int format: Text format
        :return: Corresponding text engine
        """
        if text is None:
            return self.__map.get(format_)
        elif format_ is not None:
            if format_ == QwtText.AutoText:
                for key, engine in list(self.__map.items()):
                    if key != QwtText.PlainText:
                        if engine and engine.mightRender(text):
                            return engine
            engine = self.__map.get(format_)
            if engine is not None:
                return engine
            return self.__map[QwtText.PlainText]
        else:
            raise TypeError("%s().textEngine() takes 1 or 2 argument(s) (none"\
                            " given)" % self.__class__.__name__)
    
    def setTextEngine(self, format_, engine):
        """
        Assign/Replace a text engine for a text format

        With setTextEngine it is possible to extend `PythonQwt` with
        other types of text formats.

        For `QwtText.PlainText` it is not allowed to assign a engine to None.

        :param int format_: Text format
        :param qwt.text.QwtTextEngine engine: Text engine

        .. seealso::
        
            :py:meth:`setPaintAttribute()`
            
        .. warning::
            
            Using `QwtText.AutoText` does nothing.
        """
        if format_ == QwtText.AutoText:
            return
        if format_ == QwtText.PlainText and engine is None:
            return
        self.__map.setdefault(format_, engine)



class QwtTextLabel_PrivateData(object):
    def __init__(self):
        self.indent = 4
        self.margin = 0
        self.text = QwtText()


class QwtTextLabel(QFrame):
    """
    A Widget which displays a QwtText

    .. py:class:: QwtTextLabel(parent)
    
        :param QWidget parent: Parent widget

    .. py:class:: QwtTextLabel([text=None], [parent=None])
    
        :param str text: Text
        :param QWidget parent: Parent widget
    """
    def __init__(self, *args):
        if len(args) == 0:
            text, parent = None, None
        elif len(args) == 1:
            if isinstance(args[0], QWidget):
                text = None
                parent, = args
            else:
                parent = None
                text, = args
        elif len(args) == 2:
            text, parent = args
        else:
            raise TypeError("%s() takes 0, 1 or 2 argument(s) (%s given)"\
                            % (self.__class__.__name__, len(args)))
        super(QwtTextLabel, self).__init__(parent)
        self.init()
        if text is not None:
            self.__data.text = text
    
    def init(self):
        self.__data = QwtTextLabel_PrivateData()
        self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
    
    def setPlainText(self, text):
        """
        Interface for the designer plugin - does the same as setText()
        
        :param str text: Text
        
        .. seealso::
        
            :py:meth:`plainText()`
        """
        self.setText(QwtText(text))
        
    def plainText(self):
        """
        Interface for the designer plugin
        
        :return: Text as plain text
        
        .. seealso::
        
            :py:meth:`setPlainText()`
        """
        return self.__data.text.text()
    
    def setText(self, text, textFormat=QwtText.AutoText):
        """
        Change the label's text, keeping all other QwtText attributes
        
        :param text: New text
        :type text: qwt.text.QwtText or str
        :param int textFormat: Format of text
        
        .. seealso::
        
            :py:meth:`text()`
        """
        if isinstance(text, QwtText):
            self.__data.text = text
        else:
            self.__data.text.setText(text, textFormat)
        self.update()
        self.updateGeometry()
    
    def text(self):
        """
        :return: Return the text
        
        .. seealso::
        
            :py:meth:`setText()`
        """
        return self.__data.text
        
    def clear(self):
        """
        Clear the text and all `QwtText` attributes
        """
        self.__data.text = QwtText()
        self.update()
        self.updateGeometry()
    
    def indent(self):
        """
        :return: Label's text indent in pixels
        
        .. seealso::
        
            :py:meth:`setIndent()`
        """
        return self.__data.indent
    
    def setIndent(self, indent):
        """
        Set label's text indent in pixels
        
        :param int indent: Indentation in pixels
        
        .. seealso::
        
            :py:meth:`indent()`
        """
        if indent < 0:
            indent = 0
        self.__data.indent = indent
        self.update()
        self.updateGeometry()
    
    def margin(self):
        """
        :return: Label's text indent in pixels
        
        .. seealso::
        
            :py:meth:`setMargin()`
        """
        return self.__data.margin
        
    def setMargin(self, margin):
        """
        Set label's margin in pixels
        
        :param int margin: Margin in pixels
        
        .. seealso::
        
            :py:meth:`margin()`
        """
        self.__data.margin = margin
        self.update()
        self.updateGeometry()
    
    def sizeHint(self):
        """
        Return a size hint
        """
        return self.minimumSizeHint()
    
    def minimumSizeHint(self):
        """
        Return a minimum size hint
        """
        sz = self.__data.text.textSize(self.font())
        mw = 2*(self.frameWidth()+self.__data.margin)
        mh = mw
        indent = self.__data.indent
        if indent <= 0:
            indent = self.defaultIndent()
        if indent > 0:
            align = self.__data.text.renderFlags()
            if align & Qt.AlignLeft or align & Qt.AlignRight:
                mw += self.__data.indent
            elif align & Qt.AlignTop or align & Qt.AlignBottom:
                mh += self.__data.indent
        sz += QSizeF(mw, mh)
        return QSize(np.ceil(sz.width()), np.ceil(sz.height()))

    def heightForWidth(self, width):
        """
        :param int width: Width
        :return: Preferred height for this widget, given the width.
        """
        renderFlags = self.__data.text.renderFlags()
        indent = self.__data.indent
        if indent <= 0:
            indent = self.defaultIndent()
        width -= 2*self.frameWidth()
        if renderFlags & Qt.AlignLeft or renderFlags & Qt.AlignRight:
            width -= indent
        height = np.ceil(self.__data.text.heightForWidth(width, self.font()))
        if renderFlags & Qt.AlignTop or renderFlags & Qt.AlignBottom:
            height += indent
        height += 2*self.frameWidth()
        return height
    
    def paintEvent(self, event):
        painter = QPainter(self)
        if not self.contentsRect().contains(event.rect()):
            painter.save()
            painter.setClipRegion(event.region() & self.frameRect())
            self.drawFrame(painter)
            painter.restore()
        painter.setClipRegion(event.region() & self.contentsRect())
        self.drawContents(painter)
    
    def drawContents(self, painter):
        """
        Redraw the text and focus indicator
        
        :param QPainter painter: Painter
        """
        r = self.textRect()
        if r.isEmpty():
            return
        painter.setFont(self.font())
        painter.setPen(self.palette().color(QPalette.Active, QPalette.Text))
        self.drawText(painter, QRectF(r))
        if self.hasFocus():
            m = 2
            focusRect = self.contentsRect().adjusted(m, m, -m+1, -m+1)
            QwtPainter.drawFocusRect(painter, self, focusRect)
    
    def drawText(self, painter, textRect):
        """
        Redraw the text

        :param QPainter painter: Painter
        :param QRectF textRect: Text rectangle
        """
        self.__data.text.draw(painter, textRect)
    
    def textRect(self):
        """
        Calculate geometry for the text in widget coordinates

        :return: Geometry for the text
        """
        r = self.contentsRect()
        if not r.isEmpty() and self.__data.margin > 0:
            r.setRect(r.x()+self.__data.margin, r.y()+self.__data.margin,
                      r.width()-2*self.__data.margin,
                      r.height()-2*self.__data.margin)
        if not r.isEmpty():
            indent = self.__data.indent
            if indent <= 0:
                indent = self.defaultIndent()
            if indent > 0:
                renderFlags = self.__data.text.renderFlags()
                if renderFlags & Qt.AlignLeft:
                    r.setX(r.x()+indent)
                elif renderFlags & Qt.AlignRight:
                    r.setWidth(r.width()-indent)
                elif renderFlags & Qt.AlignTop:
                    r.setY(r.y()+indent)
                elif renderFlags & Qt.AlignBottom:
                    r.setHeight(r.height()-indent)
        return r
    
    def defaultIndent(self):
        if self.frameWidth() <= 0:
            return 0
        if self.__data.text.testPaintAttribute(QwtText.PaintUsingTextFont):
            fnt = self.__data.text.font()
        else:
            fnt = self.font()
        return QFontMetrics(fnt).width('x')/2