This file is indexed.

/usr/share/kde4/apps/kajongg/kdestub.py is in kajongg 4:4.14.1-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
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
# pylint: disable=too-many-lines
# -*- coding: utf-8 -*-

"""
Copyright (C) 2008-2014 Wolfgang Rohdewald <wolfgang@rohdewald.de>

Kajongg 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.

This program 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 this program if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.


Here we define replacement classes for the case that we have no
python interface to KDE.

"""

__all__ = ['KAboutData', 'KApplication', 'KCmdLineArgs', 'KConfig',
            'KCmdLineOptions', 'i18n', 'i18nc', 'ki18n',
            'KMessageBox', 'KConfigSkeleton', 'KDialogButtonBox',
            'KConfigDialog', 'KDialog', 'KLineEdit',
            'KUser', 'KToggleFullScreenAction', 'KStandardAction',
            'KXmlGuiWindow', 'KStandardDirs', 'KGlobal', 'KIcon', 'KAction']

import sys, os, subprocess, getpass, webbrowser, codecs
if os.name != 'nt':
    import pwd
import weakref
from collections import defaultdict
from argparse import ArgumentParser

try:
    from ConfigParser import SafeConfigParser, NoSectionError, NoOptionError
except ImportError:
    # gone with python3.4
    # pylint: disable=import-error
    from configparser import SafeConfigParser, NoSectionError, NoOptionError

from locale import _parse_localename, getdefaultlocale, setlocale, LC_ALL

# here come the replacements:

# pylint: disable=wildcard-import,unused-wildcard-import
from qt import *

from common import Internal, Debug, ENGLISHDICT
from util import xToUtf8, uniqueList
from statesaver import StateSaver

import gettext

def insertArgs(englishIn, *args):
    """format the string"""
    if '@' in englishIn:
        Internal.logger.debug('insertargs:%s' % englishIn)

    if '\004' in englishIn:
        englishIn = englishIn.split('\004')[1]
    result = englishIn
    if '%' in result:
        for idx in range(len(args)):
            result = result.replace('%%%d' % (idx+1), '{%d}' % idx)
        args = list(x.decode('utf-8') for x in args)
        result = result.format(*args)
    for ignore in ['numid', 'filename', 'interface']:
        result = result.replace('<%s>' % ignore, '')
        result = result.replace('</%s>' % ignore, '')
    return result

def i18n(englishIn, *args):
    """stub"""
    englishIn, args = xToUtf8(englishIn, args)
    if KGlobal.translation and englishIn:
        _ = KGlobal.translation.gettext(englishIn).decode('utf-8')
    else:
        _ = englishIn
    ENGLISHDICT[_] = englishIn
    return insertArgs(_, *args)

ki18n = i18n # pylint: disable=invalid-name

def i18nc(context, englishIn, *args):
    """The \004 trick is taken from kdecore/localization/gettext.h,
    definition of pgettext_aux"""
    withContext = '\004'.join([context, englishIn])
    if KGlobal.translation:
        _ = KGlobal.translation.gettext(withContext).decode('utf-8')
    else:
        _ = withContext
    if '\004' in _:
        # found no translation with context
        result = i18n(englishIn, *args)
    else:
        result = i18n(withContext, *args)
    return result

class OptionHelper(object):
    """stub"""
    def __init__(self, options):
        self.options = options

    def isSet(self, option):
        """did the user specify this option?"""
        if any(x[0].startswith('no%s' % option) for x in self.options):
            return not any(x.startswith('--no%s' % option) for x in sys.argv)
        else:
            return any(x.startswith('--%s' % option) for x in sys.argv)

    @staticmethod
    def getOption(option):
        """try to mimic KDE logic as far as we need it"""
        for arg in sys.argv:
            if arg.startswith('--%s' % option):
                parts = arg.split('=')
                if len(parts) > 1:
                    return parts[1]
                else:
                    return True
            if arg.startswith('--no%s' % option):
                parts = arg.split('=')
                if len(parts) > 1:
                    return parts[1]
                else:
                    return False
        return ''

class KCmdLineArgs(object):
    """stub"""
    options = None
    argv = None
    about = None

    @classmethod
    def parsedArgs(cls):
        """stub"""
        if '--help' in sys.argv:
            KCmdLineOptions.parser.parse_args()
            KCmdLineOptions.parser.print_help()
        return cls.options

    @classmethod
    def init(cls, argv, about):
        """stub"""
        cls.argv = argv
        cls.about = about

    @classmethod
    def addCmdLineOptions(cls, options):
        """stub"""
        cls.options = OptionHelper(options)

class KCmdLineOptions(list):
    """stub"""
    parser = ArgumentParser()
    def __init__(self):
        list.__init__(self)

    def add(self, definition, helptext, default=None):
        """stub"""
        self.append((definition, helptext, default))
        # self.parser is currently only used for generating --help text
        self.parser.add_argument('--' + definition, dest=definition, help=helptext, action='store_true')

class KAboutData(object):
    """stub"""
    License_GPL = 1

    def __init__(self, appname, catalog, programName, version, description,
        kajLicense, kajCopyright, aboutText, homePage):
        # pylint: disable=too-many-arguments
        KGlobal.aboutData = self
        self.appname = appname
        self.catalog = catalog
        self.programName = programName
        self.version = version
        self.description = description
        self.kajLicense = kajLicense
        self.kajCopyright = kajCopyright
        self.aboutText = aboutText
        self.homePage = homePage
        self._authors = []

    def addAuthor(self, name, description, mailAdress):
        """authors to be shown on about page"""
        self._authors.append((name, description, mailAdress))

    def authors(self):
        """stub"""
        return self._authors

    @staticmethod
    def licenseFile():
        """which may currently only be 1: GPL_V2"""
        for path in ('COPYING', '../COPYING',
            '%s/share/kde4/apps/LICENSES/GPL_V2' % KStandardDirs.prefix):
            path = os.path.abspath(path)
            if os.path.exists(path):
                return path

class KApplication(QApplication):
    """stub"""
    def __init__(self):
        QApplication.__init__(self, sys.argv)
        if os.name == 'nt':
            # on Linux, QCoreApplication initializes locale but not on Windows.
            # This is actually documented for QCoreApplication
            setlocale(LC_ALL, '')
        KLocale.initQtTranslator(self)

    @staticmethod
    def kApplication():
        """the global app instance"""
        return QApplication.instance()

class CaptionMixin(object):
    """used by KDialog and KXmlGuiWindow"""
    def setCaption(self, caption):
        """append app name"""
        if caption:
            if not caption.endswith(i18n('Kajongg')):
                caption += u' – {}'.format(i18n('Kajongg'))
        else:
            caption = i18n('Kajongg')
        self.setWindowTitle(caption)
        self.setWindowIcon(KIcon('kajongg'))

def getDocUrl(languages):
    """returns the best match for the online user manual"""
    from twisted.web import client
    def processResult(dummyResult, fallbacks):
        """if status 404, try the next fallback language"""
        return getDocUrl(fallbacks) if factory.status == '404' else url
    host = 'docs.kde.org'
    path = '/stable/{}/kdegames/kajongg/index.html'.format(languages[0])
    url = 'http://' + host + path
    factory = client.HTTPClientFactory(url)
    factory.protocol = client.HTTPPageGetter
    factory.protocol.handleEndHeaders = lambda x: x
    Internal.reactor.connectTCP(host, 80, factory)
    factory.deferred.addCallback(processResult, languages[1:])
    return factory.deferred

def startHelp():
    """start the KDE help center for kajongg or go to docs.kde.org"""
    try:
        subprocess.Popen(['khelpcenter', 'help:/kajongg/index.html'])
    except OSError:
        def gotUrl(url):
            """now we know where the manual is"""
            webbrowser.open(url)
        languages = KGlobal.config().group('Locale').readEntry('Language').split(':')
        getDocUrl(languages).addCallback(gotUrl)

class IconLabel(QLabel):
    """for use in messages and about dialog"""
    def __init__(self, iconName, dialog):
        QLabel.__init__(self)
        icon = KIcon(iconName)
        option = QStyleOption()
        option.initFrom(dialog)
        self.setPixmap(icon.pixmap(dialog.style().pixelMetric(
            QStyle.PM_MessageBoxIconSize, option, dialog)))

class KMessageBox(object):
    """again only what we need"""
    NoExec = 1
    AllowLink = 2
    Options = int

    @staticmethod
    def createKMessageBox(dialog, icon, text, dummyStrlist, dummyAsk, dummyCheckboxReturn, options):
        """translated as far as needed from kmessagegox.cpp"""
        # pylint: disable=too-many-locals
        mainLayout = QVBoxLayout()

        hLayout = QHBoxLayout()
        hLayout.setContentsMargins(0, 0, 0, 0)
        hLayout.setSpacing(-1)
        mainLayout.addLayout(hLayout, 5)

        iconName = {
            QMessageBox.Information: 'dialog-information',
            QMessageBox.Warning: 'dialog-warning',
            QMessageBox.Question: 'dialog-information'}[icon]
        icon = KIcon(iconName)
        iconLayout = QVBoxLayout()
        iconLayout.addStretch(1)
        iconLayout.addWidget(IconLabel(iconName, dialog))
        iconLayout.addStretch(5)
        hLayout.addLayout(iconLayout, 0)

        messageLabel = QLabel(text)
        flags = Qt.TextSelectableByMouse
        if options & KMessageBox.AllowLink:
            flags |= Qt.LinksAccessibleByMouse
            messageLabel.setOpenExternalLinks(True)
        messageLabel.setTextInteractionFlags(flags)

        desktop = KApplication.kApplication().desktop().availableGeometry()
        if messageLabel.sizeHint().width() > desktop.width() * 0.5:
            messageLabel.setWordWrap(True)

        usingScrollArea = desktop.height() // 3 < messageLabel.sizeHint().height()
        if usingScrollArea:
            scrollArea = QScrollArea(dialog)
            scrollArea.setWidget(messageLabel)
            scrollArea.setWidgetResizable(True)
            scrollArea.setFocusPolicy(Qt.NoFocus)
            scrollPal = QPalette(scrollArea.palette())
            scrollArea.viewport().setPalette(scrollPal)
            hLayout.addWidget(scrollArea, 5)
        else:
            hLayout.addWidget(messageLabel, 5)

        mainLayout.addWidget(dialog.buttonBox)
        dialog.setLayout(mainLayout)

KDialogButtonBox = QDialogButtonBox # pylint: disable=invalid-name

class KDialog(CaptionMixin, QDialog):
    """QDialog should be enough for kajongg"""
    NoButton = 0
    Ok = QDialogButtonBox.Ok # pylint: disable=invalid-name
    Cancel = QDialogButtonBox.Cancel
    Yes = QDialogButtonBox.Yes
    No = QDialogButtonBox.No # pylint: disable=invalid-name
    Help = QDialogButtonBox.Help
    Apply = QDialogButtonBox.Apply
    RestoreDefaults = QDialogButtonBox.RestoreDefaults
    Default = QDialogButtonBox.RestoreDefaults
    Close = QDialogButtonBox.Close

    def __init__(self, parent=None, flags=None):
        if flags is None:
            flags = Qt.WindowFlags(0)
        QDialog.__init__(self, parent, flags)
        self.buttonBox = QDialogButtonBox()
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)
        self.__mainWidget = None

    def setButtons(self, buttonMask):
        """(re)create the buttonbox and put all wanted buttons into it"""
        if not buttonMask:
            self.buttonBox.clear()
            return
        self.buttonBox.setStandardButtons(buttonMask)
        if KDialog.Apply & buttonMask:
            self.buttonBox.button(KDialog.Apply).setText(i18n('&Apply'))
        if KDialog.Cancel & buttonMask:
            self.buttonBox.button(KDialog.Cancel).setText(i18n('&Cancel'))
        if KDialog.RestoreDefaults & buttonMask:
            self.buttonBox.button(KDialog.RestoreDefaults).setText(i18n('&Defaults'))
        if KDialog.Help & buttonMask:
            self.buttonBox.button(KDialog.Help).clicked.connect(startHelp)

    def setMainWidget(self, widget):
        """see KDialog.setMainWidget"""
        if self.layout() is None:
            QVBoxLayout(self)
            self.layout().addWidget(self.buttonBox)
        if self.__mainWidget:
            self.layout().removeWidget(self.__mainWidget)
            self.layout().removeWidget(self.buttonBox)
        self.__mainWidget = widget
        self.layout().addWidget(widget)
        self.layout().addWidget(self.buttonBox)

    def button(self, buttonCode):
        """returns the matching button"""
        return self.buttonBox.button(buttonCode)

    @staticmethod
    def ButtonCode(value): # pylint: disable=invalid-name
        """not needed in Python"""
        return value

    @staticmethod
    def spacingHint():
        """stub"""
        return QApplication.style().pixelMetric(QStyle.PM_DefaultLayoutSpacing)

    @staticmethod
    def marginHint():
        """stub"""
        return QApplication.style().pixelMetric(QStyle.PM_DefaultChildMargin)

class KUser(object):
    """only the things kajongg needs"""
    def __init__(self, uid=None):
        self.__uid = uid
    def fullName(self):
        """stub"""
        if os.name == 'nt':
            return self.loginName()
        else:
            return pwd.getpwnam(self.loginName()).pw_gecos.replace(',', '')
        return None
    @staticmethod
    def loginName():
        """stub"""
        return getpass.getuser()

class KToggleFullScreenAction(QAction):
    """stub"""
    def __init__(self, *dummyArgs):
        QAction.__init__(self, Internal.mainWindow)

    def setWindow(self, window):
        """stub"""

class KStandardAction(object):
    """stub"""
    @classmethod
    def preferences(cls, slot, actionCollection):
        """should add config dialog menu entry"""
        mainWindow = Internal.mainWindow
        separator = QAction(Internal.mainWindow)
        separator.setSeparator(True)
        mainWindow.actionStatusBar = mainWindow.kajonggAction('options_show_statusbar', None)
        mainWindow.actionStatusBar.setCheckable(True)
        mainWindow.actionStatusBar.setEnabled(True)
        mainWindow.actionStatusBar.toggled.connect(mainWindow.toggleStatusBar)
        mainWindow.actionStatusBar.setText(i18nc('@action:inmenu', "Show St&atusbar"))
        mainWindow.actionToolBar = mainWindow.kajonggAction('options_show_toolbar', None)
        mainWindow.actionToolBar.setCheckable(True)
        mainWindow.actionToolBar.setEnabled(True)
        mainWindow.actionToolBar.toggled.connect(mainWindow.toggleToolBar)
        mainWindow.actionToolBar.setText(i18nc('@action:inmenu', "Show &Toolbar"))

        actionCollection.addAction('', separator)

        action = KAction(mainWindow)
        action.triggered.connect(mainWindow.configureToolBar)
        action.setText(i18n('Configure Toolbars'))
        action.setIcon(KIcon('configure-toolbars')) # TODO: winprep
        action.setIconText(i18n('Configure toolbars'))
        separator = QAction(Internal.mainWindow)
        separator.setSeparator(True)
        actionCollection.addAction('options_configure_toolbars', action)

        action = KAction(mainWindow)
        action.triggered.connect(slot)
        action.setText(i18n('Configure Kajongg'))
        action.setIcon(KIcon('configure'))
        action.setIconText(i18n('Configure'))
        actionCollection.addAction('options_configure', action)

class KActionCollection(object):
    """stub"""
    def __init__(self, mainWindow):
        self.__actions = {}
        self.mainWindow = mainWindow

    def addAction(self, name, action):
        """stub"""
        self.__actions[name] = action
        for content in self.mainWindow.menus.values():
            if name in content[1]:
                content[0].addAction(action)

    def actions(self):
        """the actions in this collection"""
        return self.__actions

class MyStatusBarItem(object):
    """one of the four player items"""
    def __init__(self, text, idx, stretch=0):
        self.idx = idx
        self.stretch = stretch
        self.label = QLabel()
        self.label.setText(text)
        self.label.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)

class KStatusBar(QStatusBar):
    """stub"""
    def __init__(self, *args, **kwargs):
        QStatusBar.__init__(self, *args, **kwargs)
        self.__items = []

    def hasItem(self, idx):
        """stub"""
        return len(self.__items) > idx

    def changeItem(self, text, idx):
        """stub"""
        self.__items[idx].label.setText(text)

    def insertItem(self, text, idx, stretch):
        """stub"""
        item = MyStatusBarItem(text, idx, stretch)
        self.__items.append(item)
        self.insertWidget(item.idx, item.label, stretch=item.stretch)

    def removeItem(self, idx):
        """stub"""
        item = self.__items[idx]
        self.removeWidget(item.label)
        del self.__items[idx]

    def setItemAlignment(self, idx, alignment):
        """stub"""
        self.__items[idx].label.setAlignment(alignment)

class KXmlGuiWindow(CaptionMixin, QMainWindow):
    """stub"""
    def __init__(self):
        QMainWindow.__init__(self)
        self._actions = KActionCollection(self)
        self._toolBar = QToolBar(self)
        self._toolBar.setObjectName('Toolbar')
        self.addToolBar(self.toolBar())
        self.setStatusBar(KStatusBar(self))
        self.statusBar().setObjectName('StatusBar')
        self.menus = {}
        for menu in (
            (i18n('&Game'), ('scoreGame', 'play', 'abort', 'quit')),
            (i18n('&View'), ('scoreTable', 'explain')),
            (i18n('&Settings'), ('players', 'rulesets', 'demoMode', '', 'options_show_statusbar',
                'options_show_toolbar', '', 'options_configure_toolbars', 'options_configure')),
            (i18n('&Help'), ('help', 'aboutkajongg'))):
            self.menus[menu[0]] = (QMenu(menu[0]), menu[1])
            self.menuBar().addMenu(self.menus[menu[0]][0])
        self.setCaption('')
        self.actionHelp = self.kajonggAction("help", "help-contents", startHelp)
        self.actionHelp.setText(i18nc('@action:inmenu', 'Help'))
        self.actionAboutKajongg = self.kajonggAction('aboutkajongg', 'kajongg', self.aboutKajongg)
        self.actionAboutKajongg.setText(i18nc('@action:inmenu', 'About Kajongg'))
        self.toolBar().setMovable(False)
        self.toolBar().setFloatable(False)
        self.toolBar().setToolButtonStyle(Qt.ToolButtonTextBesideIcon)

    def showEvent(self, event):
        """now that the MainWindow code has run, we know all actions"""
        self.refreshToolBar()
        self.toolBar().setVisible(Internal.Preferences.toolBarVisible)
        self.actionStatusBar.setChecked(self.statusBar().isVisible())
        self.actionToolBar.setChecked(self.toolBar().isVisible())
        QMainWindow.showEvent(self, event)

    def hideEvent(self, event):
        """save status"""
        Internal.Preferences.toolBarVisible = self.toolBar().isVisible() # pylint: disable=attribute-defined-outside-init
        QMainWindow.hideEvent(self, event)

    def toggleStatusBar(self, checked):
        """show / hide status bar"""
        self.statusBar().setVisible(checked)

    def toggleToolBar(self, checked):
        """show / hide status bar"""
        self.toolBar().setVisible(checked)

    def configureToolBar(self):
        """configure toolbar"""
        dlg = KEditToolBar(self)
        dlg.show()

    def refreshToolBar(self):
        """reload settings for toolbar actions"""
        self.toolBar().clear()
        for name in Internal.Preferences.toolBarActions.split(','):
            self.toolBar().addAction(self.actionCollection().actions()[name])

    def actionCollection(self):
        """stub"""
        return self._actions

    def setupGUI(self):
        """stub"""
        self.applySettings()

    def toolBar(self):
        """stub"""
        return self._toolBar

    def kajonggAction(self, name, icon, slot=None, shortcut=None, actionData=None):
        """this is defined in MainWindow(KXmlGuiWindow)"""

    @staticmethod
    def aboutKajongg():
        """show an about dialog"""
        AboutKajonggDialog(Internal.mainWindow).exec_()

    def queryClose(self): # pylint: disable=no-self-use
        """default"""
        return True

    def queryExit(self): # pylint: disable=no-self-use
        """default"""
        return True

    def closeEvent(self, event):
        """call queryClose/queryExit"""
        if self.queryClose() and self.queryExit():
            event.accept()
        else:
            event.ignore()

class KStandardDirs(object):
    """as far as we need it. """
    _localBaseDirs = None
    _baseDirs = None
    prefix = None
    Recursive = 1

    def __init__(self):
        if KStandardDirs._baseDirs is None:
            KStandardDirs._localBaseDirs = defaultdict(str)
            KStandardDirs._localBaseDirs.update({
                'cache': '/var/tmp/kdecache-wr',
                'data': 'share/apps',
                'config': 'share/config',
                'appdata': 'share/apps/kajongg',
                })
            home = os.environ.get('KDEHOME', '~/.kde')
            for key, value in KStandardDirs._localBaseDirs.items():
                KStandardDirs._localBaseDirs[key] = os.path.normpath(os.path.expanduser(home + '/' + value))
            KStandardDirs._baseDirs = defaultdict(list)
            KStandardDirs._baseDirs.update({
                'data': ['share/kde4/apps'],
                'locale': ['share/locale'],
                'appdata': ['share/kde4/apps/kajongg'],
                'icon': ['share/icons'],
                })
            if os.name == 'nt':
                cwd = os.path.split(os.path.abspath(sys.argv[0]))[0]
                KStandardDirs.prefix = cwd
                dirMap = KStandardDirs._baseDirs
                for key in dirMap:
                    dirMap[key] = list(os.path.normpath(x) for x in dirMap[key])
            else:
                KStandardDirs.prefix = subprocess.Popen(['which', 'kde4-config'],
                    stdout=subprocess.PIPE).communicate()[0].split('/')[1]
                KStandardDirs.prefix = '/%s/' % KStandardDirs.prefix

    @classmethod
    def kde_default(cls, type_):
        """the default relative paths for standard resource types"""

    @classmethod
    def __tryPath(cls, *args):
        """try this path. Returns result and full actual path"""
        if args[0] == '':
            # happens because we use a defaultdict(str) for localBaseDirs
            return False, None
        tryThis = os.path.join(*args)
        exists = os.path.exists(tryThis)
        if Debug.locate:
            if exists:
                Internal.logger.debug('found: %s' % tryThis)
            else:
                Internal.logger.debug('not found: %s' % tryThis)
        return exists, tryThis

    @classmethod
    def locate(cls, type_, filename):
        """see KStandardDirs doc"""
        type_ = str(type_)
        filename = str(filename)
        found, path = cls.__tryPath(cls._localBaseDirs[type_], filename)
        if found:
            return path
        for baseDir in cls._baseDirs[type_]:
            found, path = cls.__tryPath(cls.prefix, baseDir, filename)
            if found:
                return path

    @classmethod
    def locateLocal(cls, type_, filename):
        """see KStandardDirs doc"""
        type_ = str(type_)
        filename = str(filename)
        fullPath = os.path.join(cls._localBaseDirs[type_], filename)
        if not os.path.exists(os.path.dirname(fullPath)):
            if Debug.locate:
                Internal.logger.debug('locateLocal creates missing dir %s', fullPath)
            os.makedirs(os.path.dirname(fullPath))
        if Debug.locate:
            Internal.logger.debug('locateLocal(%s, %s) returns %s' % (
                type_, filename, fullPath))
        return fullPath

    @classmethod
    def addResourceType(cls, type_, basetype, relativename):
        """see KStandardDirs doc"""
        type_ = str(type_)
        basetype = str(basetype)
        relativename = str(relativename)
        for baseDir in cls._baseDirs[basetype]:
            cls._baseDirs[str(type_)].append(os.path.normpath(os.path.join(baseDir, relativename)))

    @classmethod
    def resourceDirs(cls, type_):
        """see KStandardDirs doc"""
        type_ = str(type_)
        result = [cls._localBaseDirs[type_]]
        result.extend(cls._baseDirs[type_])
        return list(x for x in result if x is not None)

    @classmethod
    def findDirs(cls, type_, reldir):
        """Tries to find all directories whose names consist of the specified type and a relative path"""
        result = []
        type_ = str(type_)
        reldir = str(reldir)
        found, path = cls.__tryPath(cls._localBaseDirs[type_], reldir)
        if found:
            result.append(path)
        for baseDir in cls._baseDirs[type_]:
            found, path = cls.__tryPath(cls.prefix, baseDir, reldir)
            if found:
                result.append(path)
        return result

    @classmethod
    def findAllResources(cls, type_, filter_, dummyRecursive):
        """Return all resources with the specified type. Recursion is not implemented."""
        dirs = cls.findDirs(type_, '')
        type_ = str(type_)
        filter_ = str(filter_)
        assert filter_ == '*.desktop' # nothing else we need
        result = []
        for directory in dirs:
            result.extend(x for x in os.listdir(directory) if x.endswith('.desktop'))
        return result

    @classmethod
    def findResourceDir(cls, type_, filename):
        """tries to find the directory the file is in"""
        result = cls.findDirs(type_, filename)
        if Debug.locate:
            Internal.logger.debug('findResourceDir(%s,%s) finds %s' % (type_, filename, result))
        return result

class KDETranslator(QTranslator):
    """we also want Qt-only strings translated. Make Qt call this
    translator for its own strings"""
    def __init__(self, parent):
        QTranslator.__init__(self, parent)

    @staticmethod
    def translate(dummyContext, sourceText, dummyMessage, dummyNumber=-1):
        """for now this seems to translate all we need, otherwise
        search for translateQt in kdelibs/kdecore/localization"""
        return i18n(sourceText)

    @staticmethod
    def isEmpty():
        """stub"""
        return False

class KLocale(object):
    """as far as we need it"""
    @staticmethod
    def insertCatalog(dummy):
        """to be done for translation, I suppose"""

    @staticmethod
    def initQtTranslator(app):
        """stub"""
        QCoreApplication.installTranslator(KDETranslator(app))

class KConfigGroup(object):
    """mimic KConfigGroup as far as we need it"""
    def __init__(self, config, groupName):
        self.config = weakref.ref(config)
        self.groupName = groupName

    def __default(self, name):
        """defer computation of Languages until really needed"""
        if self.groupName == 'Locale' and name == 'Language':
            return QString(self.__availableLanguages())

    def readEntry(self, name, default=None):
        """get an entry from this group.
        If default is passed, the original returns QVariant, else QString.
        To make things easier, we never accept a default and
        always return QString"""
        assert default is None
        try:
            items = self.config().items(self.groupName)
        except NoSectionError:
            return self.__default(name)
        items = dict((x for x in items if x[0].startswith(name)))
        i18nItems = dict((x for x in items.items() if x[0].startswith(name + '[')))
        if i18nItems:
            for language in KGlobal.config().group('Locale').readEntry('Language').split(':'):
                key = '%s[%s]' % (name, language)
                if key in i18nItems:
                    return QString(i18nItems[key])
        if name in items:
            if self.groupName == 'Locale' and name == 'Language':
                languages = list(x for x in items[name].split(':') if self.__isLanguageInstalled(x))
                if languages:
                    return QString(':'.join(languages))
                else:
                    return QString(self.__availableLanguages())
            return QString(items[name])
        return self.__default(name)

    @classmethod
    def __extendRegionLanguages(cls, languages):
        """for de_DE, return de_DE, de"""
        for lang in languages:
            if lang is not None:
                yield lang
                if '_' in lang:
                    yield lang.split('_')[0]

    @classmethod
    def __availableLanguages(cls):
        """see python lib, getdefaultlocale (which only returns the first one)"""
        localenames = [getdefaultlocale()[0]]
        for variable in ('LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG'):
            try:
                localename = os.environ[variable]
            except KeyError:
                continue
            else:
                if variable == 'LANGUAGE':
                    localenames.extend(localename.split(':'))
                else:
                    localenames.append(localename)
        languages = list(_parse_localename(x)[0] for x in localenames if len(x))
        if languages:
            languages = uniqueList(cls.__extendRegionLanguages(languages))
            languages = list(x for x in languages if cls.__isLanguageInstalled(x))
        if 'en_US' not in languages:
            languages.extend(['en_US', 'en'])
        return ':'.join(languages)

    @classmethod
    def __isLanguageInstalled(cls, lang):
        """is any translation available for lang?"""
        return bool(KGlobal.dirs().findDirs('locale', lang))

    @classmethod
    def __isLanguageInstalledForKajongg(cls, lang):
        """see kdelibs, KCatalog::catalogLocaleDir"""
        relpath = '{lang}/LC_MESSAGES/kajongg.mo'.format(lang=lang)
        return bool(KGlobal.dirs().findResourceDir("locale", relpath))

class KGlobal(object):
    """stub"""

    @classmethod
    def initStatic(cls):
        """init class members"""
        cls.dirInstance = KStandardDirs()
        cls.localeInstance = KLocale()
        cls.configInstance = KConfig()
        languages = str(cls.configInstance.group('Locale').readEntry('Language'))
        if languages:
            languages = languages.split(':')
        else:
            languages = None
        resourceDirs = KGlobal.dirs().findResourceDir('locale', '')
        cls.translation = gettext.NullTranslations()
        if languages:
            for resourceDir in resourceDirs:
                for language in languages:
                    for context in ('kajongg', 'libkmahjongg', 'kdelibs4', 'libphonon', 'kio4', 'kdeqt', 'libc'):
                        try:
                            cls.translation.add_fallback(gettext.translation(
                                context, resourceDir, languages=[language]))
                        except IOError:
                            # no translation for language/domain available
                            pass
        cls.translation.install()

    @classmethod
    def dirs(cls):
        """stub"""
        return cls.dirInstance

    @classmethod
    def locale(cls):
        """stub"""
        return cls.localeInstance

    @classmethod
    def config(cls):
        """stub"""
        return cls.configInstance

class KConfig(SafeConfigParser):
    """Parse KDE config files.
    This mimics KDE KConfig but can also be used like any SafeConfigParser but
    without support for a default section.
    We Override write() with a variant which does not put spaces
    around the '=' delimiter. This is configurable in Python3.3,
    so after kajongg is ported to Python3, this can be removed"""

    SimpleConfig = 1

    def __init__(self, path=None, dummyVariant=None):
        SafeConfigParser.__init__(self)
        if path is None:
            path = KGlobal.dirs().locateLocal("config", "kajonggrc")
        self.path = str(path)
        if os.path.exists(self.path):
            with codecs.open(self.path, 'r', encoding='utf-8') as cfgFile:
                self.readfp(cfgFile)

    def as_dict(self):
        """a dict of dicts"""
        result = dict(self._sections)
        for key in result:
            result[key] = dict(self._defaults, **result[key])
            result[key].pop('__name__', None)
        return result

    def optionxform(self, value):
        """KDE needs upper/lowercase distinction"""
        return value

    def setValue(self, section, option, value):
        """like set but add missing section"""
        if section not in self._sections:
            self.add_section(section)
        self.set(section, option, str(value))

    def writeToFile(self, fileName=None):
        """Write an .ini-format representation of the configuration state."""
        if fileName is None:
            fileName = self.path
        with open(fileName, 'wb') as filePointer:
            for section in self._sections:
                filePointer.write("[%s]\n" % section)
                for (key, value) in self._sections[section].items():
                    key = str(key)
                    value = str(value)
                    if key == "__name__":
                        continue
                    if value is not None:
                        key = "=".join((key, value.replace('\n', '\n\t')))
                    filePointer.write('%s\n' % (key))
                filePointer.write('\n')

    def group(self, groupName):
        """just like KConfig"""
        return KConfigGroup(self, groupName)

class KIcon(QIcon):
    """stub"""
    initDone = False
    def __init__(self, name=None):
        if name is None:
            QIcon.__init__(self)
            return
        if os.name == 'nt':
            # we have full control about file and location, no need to search
            extension = 'png'
            if name in ('games-kajongg-law', 'kajongg'):
                # windows 2000 does not support svg/svgz
                extension = 'svgz' if 'svgz' in QImageReader.supportedImageFormats() else 'ico'
            name = os.path.normpath('{}/share/icons/{}.{}'.format(KStandardDirs.prefix, name, extension))
            if not os.path.exists(name):
                Internal.logger.debug('not found:%s' % name)
                raise UserWarning('not found:%s' % name)
            QIcon.__init__(self, name)
            return
        dirs = KGlobal.dirs()
        if not KIcon.initDone:
            KIcon.initDone = True
            dirs.addResourceType('appicon', 'data', 'kajongg/pics/')
            dirs.addResourceType('appicon', 'icon', 'oxygen/48x48/actions/')
            dirs.addResourceType('appicon', 'icon', 'oxygen/48x48/categories/')
            dirs.addResourceType('appicon', 'icon', 'oxygen/48x48/status/')
            dirs.addResourceType('appicon', 'icon', 'hicolor/scalable/apps/')
            dirs.addResourceType('appicon', 'icon', 'hicolor/scalable/actions/')
        for suffix in ('png', 'svgz', 'svg', 'xpm'):
            result = dirs.locate('appicon', '.'.join([name, suffix]))
            if result:
                name = result
                break
        QIcon.__init__(self, name)

class KAction(QAction):
    """stub"""
    def __init__(self, *args, **kwargs):
        QAction.__init__(self, *args, **kwargs)
        self.__helpText = None

    def setHelpText(self, text):
        """stub"""
        self.__helpText = text

class KConfigSkeletonItem(object):
    """one preferences setting used by KOnfigSkeleton"""
    def __init__(self, skeleton, key, value, default=None):
        assert skeleton
        self.skeleton = skeleton
        self.group = skeleton.currentGroup
        self.key = key
        self._value = value
        if value is None:
            self._value = default
        self.default = default

    def value(self):
        """default getter"""
        return self._value

    def pythonValue(self):
        """default getter"""
        return self._value

    def setValue(self, value):
        """default setter"""
        self._value = value

    def setPythonValue(self, value):
        """default setter"""
        self._value = value

    def getFromConfig(self):
        """if not there, use default"""
        try:
            self._value = self.skeleton.config.get(self.group, self.key)
        except (NoSectionError, NoOptionError):
            self._value = self.default

class ItemBool(KConfigSkeletonItem):
    """boolean preferences setting used by KOnfigSkeleton"""
    def __init__(self, skeleton, key, value, default=None):
        KConfigSkeletonItem.__init__(self, skeleton, key, value, default)

    def getFromConfig(self):
        """if not there, use default"""
        try:
            self._value = self.skeleton.config.getboolean(self.group, self.key)
        except (NoSectionError, NoOptionError):
            self._value = self.default

class ItemString(KConfigSkeletonItem):
    """string preferences setting used by KOnfigSkeleton"""
    def __init__(self, skeleton, key, value, default=None):
        if value == '':
            value = default
        KConfigSkeletonItem.__init__(self, skeleton, key, value, default)

    def pythonValue(self):
        return str(self._value)

    def setPythonValue(self, value):
        self._value = QString(value)

class ItemInt(KConfigSkeletonItem):
    """integer preferences setting used by KOnfigSkeleton"""
    def __init__(self, skeleton, key, value, default=0):
        KConfigSkeletonItem.__init__(self, skeleton, key, value, default)
        self.minValue = -99999
        self.maxValue = 99999999

    def getFromConfig(self):
        """if not there, use default"""
        try:
            self._value = self.skeleton.config.getint(self.group, self.key)
        except (NoSectionError, NoOptionError):
            self._value = self.default

    def setMinValue(self, value):
        """minimum value for this setting"""
        self.minValue = value

    def setMaxValue(self, value):
        """maximum value for this setting"""
        self.maxValue = value

class KConfigSkeleton(object):
    """handles preferences settings"""
    def __init__(self):
        self.currentGroup = None
        self.items = []
        self.config = KConfig()
        self.addBool('MainWindow', 'toolBarVisible', True)
        self.addString('MainWindow', 'toolBarActions', 'quit,play,scoreTable,explain,players,options_configure')

    def addBool(self, group, name, default=None):
        """to be overridden in MainWindow"""

    def addString(self, group, name, default=None):
        """to be overridden in MainWindow"""

    def readConfig(self):
        """init already read config"""
        for item in self.items:
            item.getFromConfig()

    def writeConfig(self):
        """to the same file name"""
        for item in self.items:
            self.config.setValue(item.group, item.key, item.pythonValue())
        self.config.writeToFile()

    def as_dict(self):
        """a dict of dicts"""
        result = defaultdict(dict)
        for item in self.items:
            result[str(item.group)][str(item.key)] = item.pythonValue()
        return result

    def setCurrentGroup(self, group):
        """to be used by following add* calls"""
        self.currentGroup = group

    def addItemString(self, key, value, default=None):
        """add a string preference"""
        result = ItemString(self, key, value, default)
        result.getFromConfig()
        self.items.append(result)
        return result

    def addItemBool(self, key, value, default=False):
        """add a boolean preference"""
        result = ItemBool(self, key, value, default)
        result.getFromConfig()
        self.items.append(result)
        return result

    def addItemInt(self, key, value, default=0):
        """add an integer preference"""
        result = ItemInt(self, key, value, default)
        result.getFromConfig()
        self.items.append(result)
        return result

class AboutKajonggDialog(KDialog):
    """about kajongg dialog"""
    def __init__(self, parent):
        # pylint: disable=too-many-locals, too-many-statements
        KDialog.__init__(self, parent)
        self.setCaption(i18n('About Kajongg'))
        self.setButtons(KDialog.Close)
        vLayout = QVBoxLayout()
        hLayout1 = QHBoxLayout()
        hLayout1.addWidget(IconLabel('kajongg', self))
        h1vLayout = QVBoxLayout()
        h1vLayout.addWidget(QLabel('Kajongg'))
        h1vLayout.addWidget(QLabel(i18n('Version %1', Internal.version)))
        underVersions = []
        try:
            versions = subprocess.Popen(['kde4-config', '-v'],
                stdout=subprocess.PIPE).communicate()[0]
            versions = versions.split('\n')
            versions = (x.strip() for x in versions if ': ' in x.strip())
            versions = dict(x.split(': ') for x in versions)
            underVersions.append('KDE %s' % versions['KDE'])
        except OSError:
            underVersions.append(i18n('KDE (not installed)'))
        underVersions.append('Qt %s' % QT_VERSION_STR)
        underVersions.append('PyQt %s' % PYQT_VERSION_STR)
        underVersions.append('Python {}.{}.{} {}'.format(*sys.version_info[:5]))
        h1vLayout.addWidget(QLabel(i18nc('running under version', 'Under %s' % ', '.join(underVersions))))
        h1vLayout.addWidget(QLabel(i18n('Not using Python KDE bindings')))
        hLayout1.addLayout(h1vLayout)
        spacerItem = QSpacerItem(20, 20, QSizePolicy.Expanding, QSizePolicy.Expanding)
        hLayout1.addItem(spacerItem)
        vLayout.addLayout(hLayout1)
        tabWidget = QTabWidget()

        data = KGlobal.aboutData

        aboutWidget = QWidget()
        aboutLayout = QVBoxLayout()
        aboutLabel = QLabel()
        aboutLabel.setWordWrap(True)
        aboutLabel.setOpenExternalLinks(True)
        aboutLabel.setText('<br /><br />'.join([data.description, data.aboutText,
            data.kajCopyright,
            '<a href="{link}">{link}</a>'.format(link=data.homePage)]))
        licenseLabel = QLabel()
        licenseLabel.setText(
            '<a href="file://{link}">GNU General Public License Version 2</a>'.format(
            link=data.licenseFile()))
        licenseLabel.linkActivated.connect(self.showLicense)
        aboutLayout.addWidget(aboutLabel)
        aboutLayout.addWidget(licenseLabel)
        aboutWidget.setLayout(aboutLayout)
        tabWidget.addTab(aboutWidget, '&About')

        authorWidget = QWidget()
        authorLayout = QVBoxLayout()
        bugsLabel = QLabel(i18n('Please use <a href="http://bugs.kde.org">http://bugs.kde.org</a> to report bugs.'))
        bugsLabel.setContentsMargins(0, 2, 0, 4)
        bugsLabel.setOpenExternalLinks(True)
        authorLayout.addWidget(bugsLabel)

        titleLabel = QLabel(i18n('Authors:'))
        authorLayout.addWidget(titleLabel)

        for name, description, mail in data.authors():
            label = QLabel(u'{name} <a href="mailto:{mail}">{mail}</a>: {description}'.format(
                name=name, mail=mail, description=description))
            label.setOpenExternalLinks(True)
            authorLayout.addWidget(label)
        spacerItem = QSpacerItem(20, 20, QSizePolicy.Expanding, QSizePolicy.Expanding)
        authorLayout.addItem(spacerItem)
        authorWidget.setLayout(authorLayout)
        tabWidget.addTab(authorWidget, 'A&uthor')
        vLayout.addWidget(tabWidget)

        vLayout.addWidget(self.buttonBox)
        self.setLayout(vLayout)
        self.buttonBox.setFocus()

    @staticmethod
    def showLicense():
        """as the name says"""
        LicenseDialog(Internal.mainWindow).exec_()

class LicenseDialog(KDialog):
    """see kaboutapplicationdialog.cpp"""
    def __init__(self, parent):
        KDialog.__init__(self, parent)
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.setCaption(i18n("License Agreement"))
        self.setButtons(KDialog.Close)
        self.buttonBox.setFocus()
        licenseText = open(KGlobal.aboutData.licenseFile()).read()
        self.licenseBrowser = QTextBrowser()
        self.licenseBrowser.setLineWrapMode(QTextEdit.NoWrap)
        self.licenseBrowser.setText(licenseText)

        vLayout = QVBoxLayout()
        vLayout.addWidget(self.licenseBrowser)
        vLayout.addWidget(self.buttonBox)
        self.setLayout(vLayout)

    def sizeHint(self):
        """try to set up the dialog such that the full width of the
        document is visible without horizontal scroll-bars being required"""
        idealWidth = self.licenseBrowser.document().idealWidth() + (2 * self.marginHint()) \
            + self.licenseBrowser.verticalScrollBar().width() * 2 + 1
        # try to allow enough height for a reasonable number of lines to be shown
        metrics = QFontMetrics(self.licenseBrowser.font())
        idealHeight = metrics.height() * 30
        return KDialog.sizeHint(self).expandedTo(QSize(idealWidth, idealHeight))

class KConfigDialog(KDialog):
    """for the game preferences"""
    settingsChanged = pyqtSignal()
    dialog = None
    getFunc = {
            'QCheckBox': 'isChecked',
            'QSlider': 'value',
            'QLineEdit': 'text'}
    setFunc = {
            'QCheckBox': 'setChecked',
            'QSlider': 'setValue',
            'QLineEdit': 'setText'}

    def __init__(self, parent, name, preferences):
        KDialog.__init__(self, parent)
        self.setCaption(i18n('Configure'))
        self.name = name
        self.preferences = preferences
        self.orgPref = None
        self.configWidgets = {}
        self.iconList = QListWidget()
        self.iconList.setViewMode(QListWidget.IconMode)
        self.iconList.setFlow(QListWidget.TopToBottom)
        self.iconList.setUniformItemSizes(True)
        self.iconList.itemClicked.connect(self.iconClicked)
        self.iconList.currentItemChanged.connect(self.iconClicked)
        self.tabSpace = QStackedWidget()
        self.setButtons(KDialog.Help | KDialog.Ok | KDialog.Apply | KDialog.Cancel | KDialog.RestoreDefaults)
        self.buttonBox.button(KDialog.Apply).clicked.connect(self.applySettings)
        cmdLayout = QHBoxLayout()
        cmdLayout.addWidget(self.buttonBox)
        self.contentLayout = QHBoxLayout()
        self.contentLayout.addWidget(self.iconList)
        self.contentLayout.addWidget(self.tabSpace)
        layout = QVBoxLayout()
        layout.addLayout(self.contentLayout)
        layout.addLayout(cmdLayout)
        self.setLayout(layout)

    @classmethod
    def showDialog(cls, settings):
        """constructor"""
        assert settings == 'settings'
        if cls.dialog:
            cls.dialog.updateWidgets()
            cls.dialog.updateButtons()
            cls.dialog.show()
            return cls.dialog

    def showEvent(self, dummyEvent):
        """if the settings dialog shows, rememeber current values
        and show them in the widgets"""
        self.orgPref = self.preferences.as_dict()
        self.updateWidgets()

    def iconClicked(self, item):
        """show the wanted config tab"""
        self.setCurrentPage(self.pages[self.iconList.indexFromItem(item).row()])

    @classmethod
    def allChildren(cls, widget):
        """recursively find all widgets holding settings: Their object name
        starts with kcfg_"""
        result = []
        for child in widget.children():
            if str(child.objectName()).startswith('kcfg_'):
                result.append(child)
            else:
                result.extend(cls.allChildren(child))
        return result

    def addPage(self, configTab, name, iconName):
        """add a page to the config dialog"""
        item = QListWidgetItem(KIcon(iconName), name)
        item.setTextAlignment(Qt.AlignHCenter)
        font = item.font()
        font.setBold(True)
        item.setFont(font)
        item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
        self.iconList.addItem(item)
        self.tabSpace.addWidget(configTab)
        icons = list(self.iconList.item(x) for x in range(len(self.iconList)))
        neededIconWidth = max(self.iconList.visualItemRect(x).width() for x in icons)
        margins = self.iconList.contentsMargins()
        neededIconWidth += margins.left() + margins.right()
        self.iconList.setMaximumWidth(neededIconWidth)
        self.iconList.setMinimumWidth(neededIconWidth)
        for child in self.allChildren(self):
            self.configWidgets[str(child.objectName()).replace('kcfg_', '')] = child
            if isinstance(child, QCheckBox):
                child.stateChanged.connect(self.updateButtons)
            elif isinstance(child, QSlider):
                child.valueChanged.connect(self.updateButtons)
            elif isinstance(child, KLineEdit):
                child.textChanged.connect(self.updateButtons)
        self.updateButtons()
        return configTab

    def applySettings(self):
        """Apply pressed"""
        changed = self.updateButtons()
        self.updateSettings()
        if changed:
            self.settingsChanged.emit()
        self.updateButtons()

    def accept(self):
        """OK pressed"""
        changed = self.updateButtons()
        self.updateSettings()
        if changed:
            self.settingsChanged.emit()
        KDialog.accept(self)

    def updateButtons(self):
        """Updates the Apply and Default buttons. Returns True if there was a changed setting"""
        changed = False
        for name, widget in self.configWidgets.items():
            oldValue = self.preferences[name]
            newValue = getattr(widget, self.getFunc[widget.__class__.__name__])()
            if oldValue != newValue:
                changed = True
                break
        self.buttonBox.button(KDialog.Apply).setEnabled(changed)
        return changed

    def updateSettings(self):
        """Update the settings from the dialog"""
        for name, widget in self.configWidgets.items():
            self.preferences[name] = getattr(widget, self.getFunc[widget.__class__.__name__])()
        self.preferences.writeConfig()

    def updateWidgets(self):
        """Update the dialog based on the settings"""
        self.preferences.readConfig()
        for name, widget in self.configWidgets.items():
            getattr(widget, self.setFunc[widget.__class__.__name__])(getattr(self.preferences, name))

    def setCurrentPage(self, page):
        """show wanted page and select its icon"""
        self.tabSpace.setCurrentWidget(page)
        for idx in range(self.tabSpace.count()):
            self.iconList.item(idx).setSelected(idx == self.tabSpace.currentIndex())

class KSeparator(QFrame):
    """used for toolbar editor"""
    def __init__(self, parent=None):
        QFrame.__init__(self, parent)
        self.setLineWidth(1)
        self.setMidLineWidth(0)
        self.setFrameShape(QFrame.HLine)
        self.setFrameShadow(QFrame.Sunken)
        self.setMinimumSize(0, 2)

class ToolBarItem(QListWidgetItem):
    """a toolbar item"""
    emptyIcon = None
    def __init__(self, action, parent):
        self.action = action
        self.parent = parent
        QListWidgetItem.__init__(self, self.icon, self.text, parent)
        # drop between items, not onto items
        self.setFlags((self.flags() | Qt.ItemIsDragEnabled) & ~Qt.ItemIsDropEnabled)

    @property
    def icon(self):
        """the action icon, default is an empty icon"""
        result = self.action.icon()
        if result.isNull():
            if not self.emptyIcon:
                iconSize = self.parent.style().pixelMetric(QStyle.PM_SmallIconSize)
                self.emptyIcon = QPixmap(iconSize, iconSize)
                self.emptyIcon.fill(Qt.transparent)
                self.emptyIcon = QIcon(self.emptyIcon)
            result = self.emptyIcon
        return result

    @property
    def text(self):
        """the action text"""
        return self.action.text().replace('&', '')

class ToolBarList(QListWidget):
    """QListWidget without internal moves"""
    def __init__(self, parent):
        QListWidget.__init__(self, parent)
        self.setDragDropMode(QAbstractItemView.DragDrop) # no internal moves

class KEditToolBar(KDialog):
    """stub"""
    def __init__(self, parent=None):
        # pylint: disable=too-many-statements
        KDialog.__init__(self, parent)
        self.setCaption(i18n('Configure Toolbars'))
        StateSaver(self)
        self.inactiveLabel = QLabel(i18n("A&vailable actions:"), self)
        self.inactiveList = ToolBarList(self)
        self.inactiveList.setDragEnabled(True)
        self.inactiveList.setMinimumSize(180, 250)
        self.inactiveList.setDropIndicatorShown(False)
        self.inactiveLabel.setBuddy(self.inactiveList)
        self.inactiveList.itemSelectionChanged.connect(self.inactiveSelectionChanged)
        self.inactiveList.itemDoubleClicked.connect(self.insertButton)
        self.inactiveList.setSortingEnabled(True)

        self.activeLabel = QLabel(i18n('Curr&ent actions:'), self)
        self.activeList = ToolBarList(self)
        self.activeList.setDragEnabled(True)
        self.activeLabel.setBuddy(self.activeList)
        self.activeList.itemSelectionChanged.connect(self.activeSelectionChanged)
        self.activeList.itemDoubleClicked.connect(self.removeButton)

        self.upAction = QToolButton(self)
        self.upAction.setIcon(KIcon('go-up'))
        self.upAction.setEnabled(False)
        self.upAction.setAutoRepeat(True)
        self.upAction.clicked.connect(self.upButton)
        self.insertAction = QToolButton(self)
        self.insertAction.setIcon(KIcon('go-next' if QApplication.isRightToLeft else 'go-previous'))
        self.insertAction.setEnabled(False)
        self.insertAction.clicked.connect(self.insertButton)
        self.removeAction = QToolButton(self)
        self.removeAction.setIcon(KIcon('go-previous' if QApplication.isRightToLeft else 'go-next'))
        self.removeAction.setEnabled(False)
        self.removeAction.clicked.connect(self.removeButton)
        self.downAction = QToolButton(self)
        self.downAction.setIcon(KIcon('go-down'))
        self.downAction.setEnabled(False)
        self.downAction.setAutoRepeat(True)
        self.downAction.clicked.connect(self.downButton)

        top_layout = QVBoxLayout(self)
        top_layout.setMargin(0)
        list_layout = QHBoxLayout()

        inactive_layout = QVBoxLayout()
        active_layout = QVBoxLayout()

        button_layout = QGridLayout()

        button_layout.setSpacing(0)
        button_layout.setRowStretch(0, 10)
        button_layout.addWidget(self.upAction, 1, 1)
        button_layout.addWidget(self.removeAction, 2, 0)
        button_layout.addWidget(self.insertAction, 2, 2)
        button_layout.addWidget(self.downAction, 3, 1)
        button_layout.setRowStretch(4, 10)

        inactive_layout.addWidget(self.inactiveLabel)
        inactive_layout.addWidget(self.inactiveList, 1)
        active_layout.addWidget(self.activeLabel)
        active_layout.addWidget(self.activeList, 1)

        list_layout.addLayout(inactive_layout)
        list_layout.addLayout(button_layout)
        list_layout.addLayout(active_layout)

        top_layout.addLayout(list_layout, 10)
        top_layout.addWidget(KSeparator(self))
        self.loadActions()

        self.buttonBox = QDialogButtonBox()
        top_layout.addWidget(self.buttonBox)
        self.setButtons(KDialog.Ok | KDialog.Cancel)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)

    def accept(self):
        """save and close"""
        self.saveActions()
        self.hide()

    def reject(self):
        """do not save and close"""
        self.hide()

    def inactiveSelectionChanged(self):
        """update buttons"""
        if self.inactiveList.selectedItems():
            self.insertAction.setEnabled(True)
        else:
            self.insertAction.setEnabled(False)

    def activeSelectionChanged(self):
        """update buttons"""
        row = self.activeList.currentRow()
        toolItem = None
        if self.activeList.selectedItems():
            toolItem = self.activeList.selectedItems()[0]
        self.removeAction.setEnabled(bool(toolItem))
        if toolItem:
            self.upAction.setEnabled(bool(row))
            self.downAction.setEnabled(row < len(self.activeList) - 1)
        else:
            self.upAction.setEnabled(False)
            self.downAction.setEnabled(False)

    def insertButton(self):
        """activate an action"""
        self.__moveItem(toActive=True)

    def removeButton(self):
        """deactivate an action"""
        self.__moveItem(toActive=False)

    def __moveItem(self, toActive):
        """move item between the two lists"""
        if toActive:
            fromList = self.inactiveList
            toList = self.activeList
        else:
            fromList = self.activeList
            toList = self.inactiveList
        item = fromList.takeItem(fromList.currentRow())
        ToolBarItem(item.action, toList)

    def upButton(self):
        """move action up"""
        self.__moveUpDown(moveUp=True)

    def downButton(self):
        """move action down"""
        self.__moveUpDown(moveUp=False)

    def __moveUpDown(self, moveUp):
        """change place of action in list"""
        active = self.activeList
        row = active.currentRow()
        item = active.takeItem(row)
        offset = -1 if moveUp else 1
        newRow = row + offset
        active.insertItem(newRow, item)
        active.setCurrentRow(newRow)

    def loadActions(self):
        """load active actions from Preferences"""
        for name, action in Internal.mainWindow.actionCollection().actions().items():
            if action.text():
                if name in Internal.Preferences.toolBarActions:
                    ToolBarItem(action, self.activeList)
                else:
                    ToolBarItem(action, self.inactiveList)

    def saveActions(self):
        """write active actions into Preferences"""
        activeActions = (self.activeList.item(x).action for x in range(len(self.activeList)))
        names = {v:k for k, v in Internal.mainWindow.actionCollection().actions().items()}
        activeNames = list(names[x] for x in activeActions)
        Internal.Preferences.toolBarActions = ','.join(activeNames) # pylint: disable=attribute-defined-outside-init
        Internal.mainWindow.refreshToolBar()

KGlobal.initStatic()