Source

PyQt4 for Embedded Linux / install.py

   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
#!/usr/bin/env python

# install.py - Build and install Qt 4, SIP, Python and PyQt4 for Embedded Linux.
# Copyright (C) 2009-2010 David Boddie <david@boddie.org.uk>
#
# This program 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 3 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, see <http://www.gnu.org/licenses/>.

import os, popen2, sets, sys

################################################################################
# Install dependencies.
################################################################################

# libffi4-dev (ctypes)

################################################################################
# Set up some useful configuration settings.
################################################################################

def read_option(options, argv):

    number = len(argv)
    
    for option in options:
        try:
            argv.remove(option)
        except ValueError:
            pass
    
    return len(argv) != number

################################################################################
# Define useful functions.
################################################################################

def mkdir(path, dir = None):

    if dir:
        path = os.path.join(path, dir)
    if not os.path.exists(path):
        os.mkdir(path)
        print "Created", path, "directory."

def chdir(path):
    os.chdir(path)
    print "Entered", path, "directory."
    print

def system(command, verbose = True):

    if verbose:
        print command
    if os.system(command):
        sys.exit(1)

def prefix_join(*args):

    # Prepend the DESTDIR installation prefix to the absolute path beginning
    # with an absolute prefix path. We need to join these two directly instead
    # of using the os.path module's join() function because that will not
    # join absolute paths.
    dest_dir = env.get("DESTDIR", "")
    prefix_path = os.path.join(*args)
    
    if dest_dir.endswith(os.sep) or prefix_path.startswith(os.sep):
        return dest_dir + prefix_path
    else:
        return dest_dir + os.sep + prefix_path

################################################################################
# Look for archives.
################################################################################

def match_file_name(start, finish, name):

    endings = (os.extsep + "gz", os.extsep + "bz2", os.extsep + "tar")
    allowed = "0123456789."
    
    stem, ext = os.path.splitext(name)
    if ext not in endings:
        return None
    
    for ending in endings:
        if name.endswith(ending):
            name = name[:-len(ending)]
    
    if name.startswith(start) and (finish is None or name.endswith(finish)):
        version = name
        if start:
            version = version[len(start):]
        if finish:
            version = version[:-len(finish)]
        
        for i in range(len(version)):
            if version[i] not in allowed:
                if finish is None:
                    version = version[:i]
                    break
                else:
                    return None
        
        try:
            version = map(int, version.split("."))
        except ValueError:
            return None
        return version
    
    return None

def find_in_list(start, finish, files):

    found = []
    for name in files:
    
        version = match_file_name(start, finish, name)
        if version:
            found.append((name, version))
    
    return found

def find_matching_version(details, target_version):

    for name, version in details:
    
        if version == target_version:
            return name
    
    return details[0][0]

def require_version(name, archive_pattern, minimum, maximum = None):

    sys.stderr.write("Cannot locate an archive for %s.\n" % name)
    sys.stderr.write("Please place a copy of " + archive_pattern % ".".join(map(str, minimum)) + " ")
    if maximum:
        sys.stderr.write("or a version up to " + archive_pattern % ".".join(map(str, maximum)) + " ")
    else:
        sys.stderr.write("or later ")
    sys.stderr.write("in the current working directory.\n")

def choose_version(name, archive_pattern, allowed):

    while len(allowed) > 1:
        print "Please select a version of", name, "to use:"
        i = 1
        for archive, version in allowed:
            print "%i:" % i, archive
            i += 1
        try:
            value = int(raw_input(">"))
        except ValueError:
            continue
        
        if 1 <= value <= len(allowed):
            return [allowed[value - 1]]
    
    return []


def check_version(name, archive_pattern, pairs, minimum, maximum = None, optional = False):

    allowed = []
    for archive, version in pairs:
    
        if maximum and minimum <= version <= maximum:
            allowed.append((archive, version))
        elif minimum <= version:
            allowed.append((archive, version))
        else:
            allowed.append((archive, version))
    
    if not optional and not allowed:
        require_version(name, archive_pattern, minimum, maximum)
    elif len(allowed) > 1:
        allowed = choose_version(name, archive_pattern, allowed)
    
    return allowed


def locate_sources(path = os.curdir):

    global python_archive, python_version, python_changes
    global zlib_archive, zlib_version
    global sip_archive, sip_version, sip_changes
    global pyqt_archive, pyqt_changes
    global qt_archive, qt_version, qt_changes
    global tslib_archive, tslib_version
    
    files = os.listdir(path)
    
    python_archives = find_in_list("Python-", "", files)
    zlib_archives = find_in_list("zlib-", "", files)
    sip_archives = find_in_list("sip-", "", files)
    pyqt_archives = find_in_list("PyQt-x11-gpl-", "", files)
    qt_archives = find_in_list("qt-everywhere-opensource-src-", "", files)
    tslib_archives = find_in_list("tslib-", None, files)
    
    python_changes = find_in_list("Python-", "-embedded-patches", files)
    sip_changes = find_in_list("sip-Qt-Embedded-Linux-", "-changes", files)
    pyqt_changes = find_in_list("PyQt4-Qt-Embedded-Linux-", "-patches", files)
    qt_changes = find_in_list("qt-embedded-linux-", "-patches", files)
    
    python_archives = check_version("Python", "Python-%s.tar.gz", python_archives, [2,5,0], [2,9,9])
    python_changes = check_version("Python patches", "Python-%s-embedded-patches.tar.gz", python_changes, [2,5,0], [2,9,9])
    zlib_archives = check_version("zlib", "zlib-%s.tar.gz", zlib_archives, [1,2,3], [1,2,9])
    sip_archives = check_version("SIP", "sip-%s.tar.gz", sip_archives, [4,8,0])
    sip_changes = check_version("SIP changes", "sip-Qt-Embedded-Linux-%s-changes.tar.gz", sip_changes, [4,5,0])
    pyqt_archives = check_version("PyQt", "PyQt-x11-gpl-%s.tar.gz", pyqt_archives, [4,5,0])
    pyqt_changes = check_version("PyQt patches", "PyQt4-Qt-Embedded-Linux-%s-patches.tar.gz", pyqt_changes, [4,5,0])
    qt_archives = check_version("Qt", "qt-everywhere-opensource-src-%s.tar.bz2", qt_archives, [4,4,0])
    qt_changes = check_version("Qt patches", "qt-embedded-linux-%s-patches.tar.bz2", qt_changes, [4,5])
    tslib_archives = check_version("tslib", "tslib-%s.tar.bz2", tslib_archives, [1,0], None, optional = True)
    
    try:
        python_archive, python_version = python_archives[0]
        zlib_archive, zlib_version = zlib_archives[0]
        python_changes = find_matching_version(python_changes, python_version)
        sip_archive, sip_version = sip_archives[0]
        sip_changes = find_matching_version(sip_changes, sip_version)
        pyqt_archive = pyqt_archives[0][0]
        pyqt_changes = pyqt_changes[0][0]
        qt_archive, qt_version = qt_archives[0]
        qt_changes = qt_changes[0][0]
    
    except IndexError:
        sys.exit(1)
    
    # tslib is optional
    try:
        tslib_archive, tslib_version = tslib_archives[0]
    except IndexError:
        tslib_archive = tslib_version = None
    
    print "Using Python from", python_archive
    print "Using Python patches from", python_changes
    print "Using zlib from", zlib_archive
    print "Using SIP from", sip_archive
    print "Using SIP changes from", sip_changes
    print "Using PyQt from", pyqt_archive
    print "Using PyQt patches from", pyqt_changes
    print "Using Qt from", qt_archive
    print "Using Qt patches from", qt_changes
    if tslib_version:
        print "Using Tslib from", tslib_archive
        if tslib_version == [1, 0]:
            print "*** Plugins may not work correctly with this version of tslib. ***"
    print

################################################################################
# Make a working directory and enter it.
################################################################################

def make_working_directory():

    if not os.path.exists("Working"):
        os.mkdir("Working")
    
    chdir("Working")

################################################################################
# Unpack archives.
################################################################################

def unpack(archive, unpack_dir = None):

    endings = (os.extsep + "gz", os.extsep + "bz2", os.extsep + "tar")
    
    name = archive
    for ending in endings:
        if name.endswith(ending):
            name = name[:-len(ending)]
    
    unpacked_dir = os.path.abspath(os.path.split(name)[1])
    if unpack_dir:
        unpack_dir = os.path.abspath(unpack_dir)
    
    if unpack_dir:
        if os.path.isdir(unpack_dir):
            print archive, "has already been unpacked to", unpack_dir
            return unpack_dir
    elif os.path.isdir(unpacked_dir):
        print archive, "has already been unpacked to", unpacked_dir
        return unpacked_dir
    
    if archive.endswith(os.extsep + "gz"):
        print "Unpacking", archive
        system("tar zxf "+archive, verbose = False)
    elif archive.endswith(os.extsep + "bz2"):
        print "Unpacking", archive
        system("tar jxf "+archive, verbose = False)
    else:
        sys.stderr.write("Unknown archive file type: %s\n" % archive)
        sys.exit(1)
    
    if unpack_dir:
        unpack_dir = os.path.abspath(unpack_dir)
        print "Moving directory to", unpack_dir
        system("mv "+unpacked_dir + " " + unpack_dir, verbose = False)
        return unpack_dir
    else:
        return unpacked_dir

def unpack_sources():

    global native_python_dir, target_python_dir, python_changes_dir
    global target_zlib_dir
    global native_sip_dir, target_sip_dir, sip_changes_dir
    global pyqt_dir, pyqt_changes_dir
    global qt_dir, qt_build_dir, qt_changes_dir
    global target_tslib_dir
    
    native_python_dir = unpack(
        os.path.join(os.pardir, python_archive), "Python-native"
        )
    target_python_dir = unpack(
        os.path.join(os.pardir, python_archive), "Python-target"
        )
    python_changes_dir = unpack(os.path.join(os.pardir, python_changes))
    
    target_zlib_dir = unpack(
        os.path.join(os.pardir, zlib_archive),
        "zlib-%s-target" % ".".join(map(str, zlib_version))
        )
    
    native_sip_dir = unpack(
        os.path.join(os.pardir, sip_archive),
        "sip-%s-native" % ".".join(map(str, sip_version))
        )
    target_sip_dir = unpack(
        os.path.join(os.pardir, sip_archive),
        "sip-%s-target" % ".".join(map(str, sip_version))
        )
    sip_changes_dir = unpack(os.path.join(os.pardir, sip_changes))
    
    pyqt_dir = unpack(os.path.join(os.pardir, pyqt_archive))
    pyqt_changes_dir = unpack(os.path.join(os.pardir, pyqt_changes))
    
    qt_dir = unpack(os.path.join(os.pardir, qt_archive))
    
    qt_build_dir = qt_dir + "-build"
    mkdir(qt_build_dir)
    
    qt_changes_dir = unpack(os.path.join(os.pardir, qt_changes))
    
    if tslib_archive:
        target_tslib_dir = unpack(
            os.path.join(os.pardir, tslib_archive),
            "tslib-%s-target" % ".".join(map(str, tslib_version))
            )
    else:
        target_tslib_dir = None
    
    print
    print "Working directories:"
    print
    print native_python_dir
    print target_python_dir
    print python_changes_dir
    print target_zlib_dir
    print native_sip_dir
    print target_sip_dir
    print sip_changes_dir
    print pyqt_dir
    print pyqt_changes_dir
    print qt_dir
    print qt_build_dir
    print qt_changes_dir
    if target_tslib_dir:
        print target_tslib_dir
    print

################################################################################
# Update the environment variables.
################################################################################

def update_environment():

    global env
    
    env.update({
        "ORIGINAL_PATH": os.getenv("PATH"),
        "NATIVE_PYTHON_SRC": native_python_dir,
        "TARGET_PYTHON_SRC": target_python_dir,
        "PYTHONPATCHDIR": python_changes_dir,
        "PYTHON_VERSION": python_version,
        "PYTHON_MAJOR_MINOR": "%i.%i" % tuple(python_version[:2]),
        "QTDIR": qt_dir,
        "QT_BUILD_DIR": qt_build_dir,
        "QT_VERSION": qt_version,
        "QTPATCHDIR": qt_changes_dir,
        "NATIVE_SIPDIR": native_sip_dir,
        "TARGET_SIPDIR": target_sip_dir,
        "SIPCHANGESDIR": sip_changes_dir,
        "PYQTDIR": pyqt_dir,
        "PYQTPATCHDIR": pyqt_changes_dir,
        "TARGET_ZLIB_SRC": target_zlib_dir,
        "TARGET_TOOLS_BIN": os.path.join(env["TARGET_TOOLS"], "bin"),
        })
    
    if target_tslib_dir:
        env["TARGET_TSLIB_SRC"] = target_tslib_dir

# Optionally unset the CC and CXX compiler environment variables.
#unset CC
#unset CXX

def create_native_directories():

    # Create the native tools directory if necessary.
    native_dir = env["NATIVE_TOOLS"]
    
    if not os.path.exists(native_dir):
        mkdir(native_dir)

def create_target_directories():

    # Create the target directory if necessary.
    target_dir = prefix_join(env["TARGETDIR"])
    
    mkdir(target_dir)
    mkdir(target_dir, "bin")
    mkdir(target_dir, "include")
    mkdir(target_dir, "lib")
    mkdir(target_dir, "man")
    mkdir(target_dir, "share")

################################################################################
# Build a native Python interpreter.
################################################################################

def build_native_python():

    # Enter the Python source directory:
    chdir(env["NATIVE_PYTHON_SRC"])
    
    system("./configure --prefix="+env["NATIVE_TOOLS"]+" --enable-shared --enable-unicode=ucs4")
    system("make -j"+env["HOST_COMPILERS"])
    system("make install")

################################################################################
# Build a native version of SIP.
################################################################################

def build_native_sip():

    # In the SIP directory:
    chdir(env["NATIVE_SIPDIR"])
    
    system("LD_LIBRARY_PATH="+os.path.join(env["NATIVE_TOOLS"], "lib ") + \
           os.path.join(env["NATIVE_TOOLS"], "bin", "python")+" configure.py")
    system("make -j"+env["HOST_COMPILERS"])
    system("make install")

################################################################################
# Build zlib for Embedded Linux.
################################################################################

def build_embedded_zlib():

    # In the zlib source directory:
    chdir(env["TARGET_ZLIB_SRC"])
    
    dest_dir = env.get("DESTDIR", "")
    
    env_commands = (
        "PATH="+env["TARGET_TOOLS_BIN"]+":"+env["ORIGINAL_PATH"] + " " + \
        "CC="+env["TARGET_PLATFORM_CC"] + " " + \
        "CXX="+env["TARGET_PLATFORM_CXX"] + " " + \
        'LDSHARED="'+env["TARGET_PLATFORM_LDSHARED"] + ' -shared" '
        )
    
    # zlib doesn't provide a way to specify separate prefix and installation
    # directories, so we construct a prefix based on the values we have.
    system(
        env_commands + \
        "./configure --shared --prefix="+prefix_join(dest_dir, env["TARGETDIR"])
        )
    system("make -j"+env["TARGET_COMPILERS"])
    system("make install")

################################################################################
# Build tslib for Embedded Linux.
################################################################################

def build_embedded_tslib():

    # In the tslib source directory.
    chdir(env["TARGET_TSLIB_SRC"])
    
    dest_dir = env.get("DESTDIR", "")
    
    system("./autogen.sh")
    
    env_commands = (
        "PATH="+env["TARGET_TOOLS_BIN"]+":"+env["ORIGINAL_PATH"] + " " + \
        "CC="+env["TARGET_PLATFORM_CC"] + " " + \
        "CXX="+env["TARGET_PLATFORM_CXX"] + " " + \
        "LDSHARED="+env["TARGET_PLATFORM_LDSHARED"] + " "
        "LDFLAGS=-L"+os.path.join(env["TARGETDIR"], "lib") + " "
#        "CFLAGS=-DDEBUG "
        )
    
    system(
        env_commands + \
        "./configure --prefix="+env["TARGETDIR"] + " " + \
        " --build="+env["TARGET_PLATFORM"]+" --host="+env["HOST_PLATFORM"]+"-linux"
        )
    
    print "Modifying config.h\n"
    text = open("config.h").read()
    text = text.replace("\n#define malloc rpl_malloc\n",
                        "\n/* #define malloc rpl_malloc */\n")
    open("config.h", "w").write(text)
    
    print "Modifying tslib-private.h\n"
    text = open(os.path.join("src", "tslib-private.h")).read()
    text = text.replace("\n#define DEBUG\n",
                        "\n/* #define DEBUG */\n")
    open(os.path.join("src", "tslib-private.h"), "w").write(text)
    
    system("make -j"+env["TARGET_COMPILERS"])
    if env.has_key("DESTDIR"):
        system("make install DESTDIR="+env["DESTDIR"])
    else:
        system("make install")

################################################################################
# Build Python for Embedded Linux.
################################################################################

def build_embedded_python():

    # In the Python source directory:
    chdir(env["TARGET_PYTHON_SRC"])
    
    dest_dir = env.get("DESTDIR", "")
    
    system("patch Makefile.pre.in "+os.path.join(env["PYTHONPATCHDIR"], "Makefile.pre.in.diff"))
    system("patch setup.py "+os.path.join(env["PYTHONPATCHDIR"], "setup.py.diff"))
    system("patch configure "+os.path.join(env["PYTHONPATCHDIR"], "configure.diff"))
    
    env_commands = (
        "PATH="+env["TARGET_TOOLS_BIN"]+":"+os.path.join(env["NATIVE_TOOLS"], "bin")+":"+env["ORIGINAL_PATH"] + " "
        "LD_LIBRARY_PATH="+os.path.join(env["NATIVE_TOOLS"], "lib") + " "
        )
    
    print "Building embedded Python with",
    os.system(env_commands + "python -V")
    print
    
    env_commands += (
        "CC="+env["TARGET_PLATFORM_CC"] + " " + \
        "CXX="+env["TARGET_PLATFORM_CXX"] + " " + \
        "CFLAGS=-I"+os.path.join(env["TARGETDIR"], "include") + " " + \
        "LDFLAGS=-L"+os.path.join(env["TARGETDIR"], "lib") + " "
        )
    
    system(
        env_commands + \
        "./configure --prefix="+env["TARGETDIR"]+" --enable-shared --enable-unicode=ucs4" + \
        " --build="+env["TARGET_PLATFORM"]+" --host="+env["HOST_PLATFORM"]
        )
    system("make -j"+env["TARGET_COMPILERS"])
    if env.has_key("DESTDIR"):
        system("make install DESTDIR="+env["DESTDIR"])
    else:
        system("make install")

################################################################################
# Build SIP for Embedded Linux.
################################################################################

def build_embedded_sip():

    # Enter the distribution directory.
    chdir(env["TARGET_SIPDIR"])
    
    dest_dir = env.get("DESTDIR", "")
    
    # Copy the specs into the distribution.
    system("cp "+os.path.join(env["SIPCHANGESDIR"], "specs", local_settings.sip_target_platform)+" specs")
    
    env_commands = (
        "PATH="+os.path.join(env["TARGET_TOOLS_BIN"])+":"+env["ORIGINAL_PATH"]+" "
        "LD_LIBRARY_PATH="+os.path.join(env["NATIVE_TOOLS"], "lib")+" "
        )
    
    # Using a native Python interpreter, configure the build system.
    system(
        env_commands + os.path.join(env["NATIVE_TOOLS"], "bin", "python")+" configure.py " + \
        "-b "+os.path.join(env["TARGETDIR"], "bin") + " " + \
        "-d "+os.path.join(env["TARGETDIR"], "lib", "python"+env["PYTHON_MAJOR_MINOR"], "site-packages") + " " + \
        "-e "+os.path.join(env["TARGETDIR"], "include", "python"+env["PYTHON_MAJOR_MINOR"]) + " " + \
        "-v "+os.path.join(env["TARGETDIR"], "share", "sip") + " " + \
        "-p "+local_settings.sip_target_platform
        )
    
    system(env_commands + "make -j"+env["TARGET_COMPILERS"])
    if env.has_key("DESTDIR"):
        system(env_commands + "make install DESTDIR="+env["DESTDIR"])
    else:
        system(env_commands + "make install")

################################################################################
# Build Qt for Embedded Linux.
################################################################################

def read_dependencies(rule, lines, dependencies = {}):

    targets_line = filter(lambda line: line.startswith(rule + ":"), lines)[0]
    targets = filter(lambda t: "-" in t, targets_line.split(":")[1].split())
    
    dependencies.setdefault(rule, {"allow": set(), "deny": set()})
    
    for target in targets:
    
        # Add each dependency of the rule that does not deal with tools,
        # examples, demos or legacy support to a list.
        pieces = target.split("-")
        
        if pieces[1] not in ("tools", "examples", "demos", "qt3support") or \
            pieces[1:3] == ["tools", "bootstrap"]:
        
            # Find the dependencies for each dependency.
            read_dependencies(target, lines, dependencies)
            
            dependencies[rule]["allow"].add(target)
        
        else:
            dependencies[rule]["deny"].add(target)
    
    return dependencies

def filter_dependencies(rule, dependencies, usage = {}):

    if dependencies[rule]["deny"]:
        return False
    
    this_usage = {rule: 1}
    
    for target in dependencies[rule]["allow"]:
        if not filter_dependencies(target, dependencies, this_usage):
            return False
    
    for key, value in this_usage.items():
        usage[key] = usage.get(key, 0) + value
    
    return True

def build_qt(target = None, qt_options = [], configuration_profile = None, extra_configuration = None):

    # Enter the distribution directory.
    chdir(env["QT_BUILD_DIR"])
    
    dest_dir = env.get("DESTDIR", "")
    
    system("python "+os.path.join(env["QTPATCHDIR"], "patch_files.py")+" "+env["QTPATCHDIR"]+" "+env["QTDIR"])
    
    env_commands = "PATH="+os.path.join(env["TARGET_TOOLS_BIN"])+":"+env["ORIGINAL_PATH"]+" "
    
    # I unset the CC and CXX environment variables to avoid a predefined reliance
    # on distcc.
    env_commands += "CC= CXX= "
    
    command = env_commands + os.path.join(env["QTDIR"], "configure") + \
              " -prefix "+env["TARGETDIR"] + \
              " " + " ".join(qt_options) + \
              " -release -fast -confirm-license"
    
    if configuration_profile:
        command += " -qconfig "+configuration_profile
    if extra_configuration:
        command += " " + "".join(map(lambda x: " -D "+x, extra_configuration))
    if "-qt-mouse-tslib" in qt_options: # and target_tslib_dir:
        command += (
            " -L "+prefix_join(env["TARGETDIR"], "lib") + \
            " -I "+prefix_join(env["TARGETDIR"], "include")
            )
    
    system(command)
    
    system(env_commands + "make -j"+env["TARGET_COMPILERS"]+" sub-src")
    system(env_commands + "make sub-moc")
    
    # Find the targets for the libraries, tools and plugins we need to install.
    lines = open("Makefile").readlines()
    
    # Construct a tree of dependencies.
    dependencies = read_dependencies("install_subtargets", lines)
    usage = {}
    filtered = filter(lambda dep: filter_dependencies(dep, dependencies, usage),
                      dependencies["install_subtargets"]["allow"])
    
    targets = filter(lambda rule: usage[rule] == 1, filtered)
    
    for target in targets:
    
        if env.has_key("DESTDIR"):
            system(env_commands + "make " + target + " INSTALL_ROOT="+env["DESTDIR"])
        else:
            system(env_commands + "make " + target)
    
    if env.has_key("DESTDIR"):
        system("make install_qmake INSTALL_ROOT="+env["DESTDIR"])
        system("make install_mkspecs INSTALL_ROOT="+env["DESTDIR"])
    else:
        system("make install_qmake")
        system("make install_mkspecs")

################################################################################
# Build PyQt4 for Embedded Linux.
################################################################################

# Qt features with an empty PyQt feature are internal Qt features that should
# have no effect on the PyQt API.

conversion_dict = {
    "QT_NO_ACCESSIBILITY": "PyQt_Accessibility",
    "QT_NO_ACTION": "PyQt_Action",
    "QT_NO_ANIMATION": "PyQt_Animation",
    "QT_NO_BIG_CODECS": "PyQt_BigCodecs",                       # internal
    "QT_NO_BUTTONGROUP": "PyQt_ButtonGroup",
    "QT_NO_CALENDARWIDGET": "PyQt_CalendarWidget",
    "QT_NO_CLIPBOARD": "PyQt_Clipboard",
    "QT_NO_CODECS": "PyQt_Codecs",                              # internal
    "QT_NO_COLORDIALOG": "PyQt_ColorDialog",
    "QT_NO_COLORNAMES": "",
    "QT_NO_COLUMNVIEW": "PyQt_ColumnView",
    "QT_NO_COMBOBOX": "PyQt_ComboBox",
    "QT_NO_COMPLETER": "PyQt_Completer",
    "QT_NO_CONCURRENT": "PyQt_Concurrent",                      # not wrapped
    "QT_NO_CONTEXTMENU": "PyQt_ContextMenu",
    "QT_NO_COP": "PyQt_COP",                                    # not wrapped
    "QT_NO_CSSPARSER": "PyQt_CSSParser",
    "QT_NO_CUPS": "",                                           # internal
    "QT_NO_CURSOR": "PyQt_Cursor",
    "QT_NO_DBUS": "PyQt_DBus",
    "QT_NO_DATASTREAM": "PyQt_DataStream",
    "QT_NO_DATAWIDGETMAPPER": "PyQt_DataWidgetMapper",
    "QT_NO_DATESTRING": "PyQt_DateString",
    "QT_NO_DATETIMEEDIT": "PyQt_DateTimeEdit",
    "QT_NO_DESKTOPSERVICES": "PyQt_DesktopServices",
    "QT_NO_DIAL": "PyQt_Dial",
    "QT_NO_DIRECTPAINTER": "",                                  # internal
    "QT_NO_DIRMODEL": "PyQt_DirModel",
    "QT_NO_DOCKWIDGET": "PyQt_DockWidget",
    "QT_NO_DOM": "PyQt_DOMClasses",
    "QT_NO_DRAGANDDROP": "PyQt_DragAndDrop",
    "QT_NO_EFFECTS": "",                                        # internal
    "QT_NO_ERRORMESSAGE": "PyQt_ErrorMessage",
    "QT_NO_FILEDIALOG": "PyQt_FileDialog",
    "QT_NO_FILESYSTEMMODEL": "PyQt_FileSystemModel",
    "QT_NO_FILESYSTEMWATCHER": "PyQt_FileSystemWatcher",
    "QT_NO_FONTCOMBOBOX": "PyQt_FontComboBox",
    "QT_NO_FONTDIALOG": "PyQt_FontDialog",
    "QT_NO_FREETYPE": "",                                       # internal
    "QT_NO_FSCOMPLETER": "PyQt_FSCompleter",
    "QT_NO_FTP": "PyQt_FTP",
    "QT_NO_QFUTURE": "PyQt_Future",
    "QT_NO_GESTURES": "PyQt_Gestures",
    "QT_NO_GRAPHICSEFFECT": "PyQt_GraphicsEffect",
    "QT_NO_GRAPHICSSVGITEM": "PyQt_GraphicsSVGItem",
    "QT_NO_GRAPHICSVIEW": "PyQt_GraphicsView",
    "QT_NO_GROUPBOX": "PyQt_GroupBox",
    "QT_NO_HOSTINFO": "PyQt_HostInfo",          # May be missing a test in Qt.
    "QT_NO_HTTP": "PyQt_HTTP",
    "QT_NO_ICON": "PyQt_Icon",                  # May be missing a test in Qt.
    "QT_NO_IDENTITYPROXYMODEL": "PyQt_IdentityProxyModel",
    "QT_NO_IM": "PyQt_IM",
    "QT_NO_IMAGEFORMATPLUGIN": "PyQt_ImageFormatPlugin",
    "QT_NO_IMAGEFORMAT_BMP": "PyQt_ImageFormat_BMP",
    "QT_NO_IMAGEFORMAT_JPEG": "PyQt_ImageFormat_JPEG",
    "QT_NO_IMAGEFORMAT_PNG": "PyQt_ImageFormat_PNG",
    "QT_NO_IMAGEFORMAT_PPM": "PyQt_ImageFormat_PPM",
    "QT_NO_IMAGEFORMAT_XBM": "PyQt_ImageFormat_XBM",
    "QT_NO_IMAGEFORMAT_XPM": "PyQt_ImageFormat_XPM",
    "QT_NO_IMAGE_HEURISTIC_MASK": "PyQt_Image_Heuristic_Mask",
    "QT_NO_IMAGE_TEXT": "PyQt_Image_Text",
    "QT_NO_INPUTDIALOG": "PyQt_InputDialog",
    "QT_NO_ITEMVIEWS": "PyQt_ItemViews",
    "QT_NO_LCDNUMBER": "PyQt_LCDNumber",
    "QT_NO_LIBRARY": "PyQt_Library",
    "QT_NO_LINEEDIT": "PyQt_LineEdit",
    "QT_NO_LINEEDITMENU": "PyQt_LineEditMenu",
    "QT_NO_LISTVIEW": "PyQt_ListView",
    "QT_NO_LISTWIDGET": "PyQt_ListWidget",
    "QT_NO_MAINWINDOW": "PyQt_MainWindow",
    "QT_NO_MDIAREA": "PyQt_MDIArea",
    "QT_NO_MENU": "PyQt_Menu",
    "QT_NO_MENUBAR": "PyQt_MenuBar",
    "QT_NO_MESSAGEBOX": "PyQt_MessageBox",
    "QT_NO_MOVIE": "PyQt_Movie",
    "QT_NO_NETWORKDISKCACHE": "PyQt_NetworkDiskCache",
    "QT_NO_NETWORKPROXY": "PyQt_NetworkProxy",
    "QT_NO_BEARERMANAGEMENT": "PyQt_BearerManagement",
    "QT_NO_PAINTONSCREEN": "",                                  # internal
    "QT_NO_PAINT_DEBUG": "",                                    # internal
    "QT_NO_PHONON_ABSTRACTMEDIASTREAM": "",
    "QT_NO_PHONON_AUDIOCAPTURE": "",
    "QT_NO_PHONON_EFFECT": "",
    "QT_NO_PHONON_EFFECTWIDGET": "PyQt_Phonon_EffectWidget",
    "QT_NO_PHONON_MEDIACONTROLLER": "",
    "QT_NO_PHONON_OBJECTDESCRIPTIONMODEL": "",
    "QT_NO_PHONON_PLATFORMPLUGIN": "",
    "QT_NO_PHONON_SEEKSLIDER": "PyQt_Phonon_SeekSlider",
    "QT_NO_PHONON_SETTINGSGROUP": "PyQt_Phonon_SettingsGroup",
    "QT_NO_PHONON_VIDEO": "",
    "QT_NO_PHONON_VIDEOPLAYER": "",
    "QT_NO_PHONON_VOLUMEFADEREFFECT": "",
    "QT_NO_PHONON_VOLUMESLIDER": "PyQt_Phonon_VolumeSlider",
    "QT_NO_PICTURE": "PyQt_Picture",
    "QT_NO_PRINTDIALOG": "PyQt_PrintDialog",
    "QT_NO_PRINTER": "PyQt_Printer",
    "QT_NO_PRINTPREVIEWDIALOG": "PyQt_PrintPreviewDialog",
    "QT_NO_PRINTPREVIEWWIDGET": "PyQt_PrintPreviewWidget",
    "QT_NO_PROCESS": "PyQt_Process",
    "QT_NO_PROGRESSBAR": "PyQt_ProgressBar",
    "QT_NO_PROGRESSDIALOG": "PyQt_ProgressDialog",
    "QT_NO_PROPERTIES": "PyQt_Properties",                      # internal
    "QT_NO_PROXYMODEL": "PyQt_ProxyModel",
    "QT_NO_QUUID_STRING": "PyQt_UUIDString",
    "QT_NO_QWSEMBEDWIDGET": "",                                 # not wrapped
    "QT_NO_QWS_ALPHA_CURSOR": "",                               # internal
    "QT_NO_QWS_CURSOR": "PyQt_QWS_Cursor",  # Not used in any wrapped classes.
    "QT_NO_QWS_DECORATION_DEFAULT": "",                         # not wrapped
    "QT_NO_QWS_DECORATION_STYLED": "",                          # not wrapped
    "QT_NO_QWS_DECORATION_WINDOWS": "",                         # not wrapped
    "QT_NO_QWS_DYNAMICSCREENTRANSFORMATION": "",                # internal
    "QT_NO_QWS_INPUTMETHODS": "",                               # not wrapped
    "QT_NO_QWS_KEYBOARD": "",                                   # not wrapped
    "QT_NO_QWS_MANAGER": "PyQt_QWS_Manager",
    "QT_NO_QWS_MOUSE": "",                                      # not wrapped
    "QT_NO_QWS_MOUSE_AUTO": "",                                 # internal
    "QT_NO_QWS_MOUSE_MANUAL": "",                               # internal
    "QT_NO_QWS_MULTIPROCESS": "",                               # internal
    "QT_NO_QWS_PROPERTIES": "",                                 # internal
    "QT_NO_QWS_PROXYSCREEN": "",                                # internal
    "QT_NO_QWS_QPF": "",                                       # internal
    "QT_NO_QWS_QPF2": "",                                       # internal
    "QT_NO_QWS_SOUNDSERVER": "",                                # not wrapped
    "QT_NO_QWS_TRANSFORMED": "",
    "QT_NO_QWS_VNC": "",
    "QT_NO_RASTERCALLBACKS": "",                                # not wrapped
    "QT_NO_RAWFONT": "PyQt_RawFont",                            # internal
    "QT_NO_RESIZEHANDLER": "",                                  # internal
    "QT_NO_RUBBERBAND": "PyQt_RubberBand",
    "QT_NO_SCRIPT": "",                                 # internal/unnecessary
    "QT_NO_SCROLLAREA": "PyQt_ScrollArea",
    "QT_NO_SCROLLBAR": "PyQt_ScrollBar",
    "QT_NO_SESSIONMANAGER": "PyQt_SessionManager",
    "QT_NO_SETTINGS": "PyQt_Settings",
    "QT_NO_SHAREDMEMORY": "PyQt_SharedMemory",
    "QT_NO_SHORTCUT": "PyQt_Shortcut",
    "QT_NO_SIGNALMAPPER": "PyQt_SignalMapper",
    "QT_NO_SIZEGRIP": "PyQt_SizeGrip",
    "QT_NO_SLIDER": "PyQt_Slider",
    "QT_NO_SOCKS5": "",                                         # internal
    "QT_NO_SOFTKEYMANAGER": "PyQt_SoftKeyManager",
    "QT_NO_SORTFILTERPROXYMODEL": "PyQt_SortFilterProxyModel",
    "QT_NO_SOUND": "PyQt_Sound",
    "QT_NO_SPINBOX": "PyQt_SpinBox",
    "QT_NO_SPINWIDGET": "",                                 # not wrapped (Qt 3)
    "QT_NO_SPLASHSCREEN": "PyQt_SplashScreen",
    "QT_NO_SPLITTER": "PyQt_Splitter",
    "QT_NO_STACKEDWIDGET": "PyQt_StackedWidget",
    "QT_NO_STANDARDITEMMODEL": "PyQt_StandardItemModel",
    "QT_NO_STATUSBAR": "PyQt_StatusBar",
    "QT_NO_STATUSTIP": "PyQt_StatusTip",
    "QT_NO_STATEMACHINE": "PyQt_StateMachine",
    "QT_NO_STL": "",                                            # internal
    "QT_NO_STRINGLISTMODEL": "PyQt_StringListModel",
    "QT_NO_STYLE_CDE": "",                                      # not wrapped
    "QT_NO_STYLE_CLEANLOOKS": "",                               # not wrapped
    "QT_NO_STYLE_MOTIF": "",                                    # not wrapped
    "QT_NO_STYLE_PLASTIQUE": "",                                # not wrapped
    "QT_NO_STYLE_STYLESHEET": "PyQt_Style_StyleSheet",
        # Beware: QApplication::styleSheet() is not covered.
    "QT_NO_STYLE_WINDOWS": "",                                  # not wrapped
    "QT_NO_STYLE_WINDOWSCE": "",                                # not wrapped
    "QT_NO_STYLE_WINDOWSMOBILE": "",                            # not wrapped
    "QT_NO_STYLE_WINDOWSVISTA": "",                             # not wrapped
    "QT_NO_STYLE_WINDOWSXP": "",                                # not wrapped
    "QT_NO_SVG": "",                                    # internal/unnecessary
    "QT_NO_SVGGENERATOR": "PyQt_SVGGenerator",
    "QT_NO_SVGRENDERER": "PyQt_SVGRenderer",
    "QT_NO_SVGWIDGET": "PyQt_SVGWidget",
    "QT_NO_SXE": "",                                            # internal
    "QT_NO_SYNTAXHIGHLIGHTER": "PyQt_SyntaxHighlighter",
    "QT_NO_SYSTEMSEMAPHORE": "PyQt_SystemSemaphore",
    "QT_NO_SYSTEMTRAYICON": "PyQt_SystemTrayIcon",
    "QT_NO_TABBAR": "PyQt_TabBar",
    "QT_NO_TABDIALOG": "",                                      # internal
    "QT_NO_TABLETEVENT": "PyQt_TabletEvent",
    "QT_NO_TABLEVIEW": "PyQt_TableView",
    "QT_NO_TABLEWIDGET": "PyQt_TableWidget",
    "QT_NO_TABWIDGET": "PyQt_TabWidget",
    "QT_NO_TEMPORARYFILE": "PyQt_TemporaryFile",
    "QT_NO_TEXTBROWSER": "PyQt_TextBrowser",
    "QT_NO_TEXTCODEC": "PyQt_TextCodec",
    "QT_NO_TEXTCODECPLUGIN": "",                                # not wrapped
    "QT_NO_TEXTDATE": "PyQt_TextDate",
    "QT_NO_TEXTEDIT": "PyQt_TextEdit",
    "QT_NO_TEXTEDITMENU": "PyQt_TextEditMenu",
    "QT_NO_TEXTHTMLPARSER": "PyQt_TextHTMLParser",
    "QT_NO_TEXTODFWRITER": "",                                  # to do
    "QT_NO_TEXTSTREAM": "PyQt_TextStream",
    "QT_NO_THREAD": "PyQt_Thread",
    "QT_NO_TOOLBAR": "PyQt_ToolBar",
    "QT_NO_TOOLBOX": "PyQt_ToolBox",
    "QT_NO_TOOLBUTTON": "PyQt_ToolButton",
    "QT_NO_TOOLTIP": "PyQt_ToolTip",
    "QT_NO_TRANSLATION": "PyQt_Translation",
    "QT_NO_TRANSLATION_UTF8": "",                               # internal
    "QT_NO_TREEVIEW": "PyQt_TreeView",
    "QT_NO_TREEWIDGET": "PyQt_TreeWidget",
    "QT_NO_UDPSOCKET": "PyQt_UDPSocket",
    "QT_NO_UNDOCOMMAND": "PyQt_UndoCommand",
    "QT_NO_UNDOGROUP": "PyQt_UndoGroup",
    "QT_NO_UNDOSTACK": "PyQt_UndoStack",
        # Beware: QUndoView::setStack() and stack() are not covered.
    "QT_NO_UNDOVIEW": "PyQt_UndoView",
    "QT_NO_URLINFO": "PyQt_URLInfo",
    "QT_NO_VALIDATOR": "PyQt_Validator",
    "QT_NO_WHATSTHIS": "PyQt_WhatsThis",
    "QT_NO_WHEELEVENT": "PyQt_WheelEvent",
    "QT_NO_WIN_ACTIVEQT": "",                                   # internal
    "QT_NO_WIZARD": "PyQt_Wizard",
    "QT_NO_WORKSPACE": "PyQt_Workspace",
    "QT_NO_XMLSTREAM": "PyQt_XMLStream",
    "QT_NO_XMLSTREAMREADER": "PyQt_XMLStreamReader",
    "QT_NO_XMLSTREAMWRITER": "PyQt_XMLStreamWriter",
    "QT_QWS_SCREEN_COORDINATES": ""                             # internal
    }

# Features not introduced by Qt need to be passed to build_embedded_pyqt() as additional
# configuration lines.

def read_configuration(configuration_file, features_file):

    dependents = read_features(features_file)
    
    definitions = sets.Set()
    for line in open(configuration_file).readlines():
    
        pieces = line.strip().split()
        if len(pieces) == 3 and pieces[:2] == ["#", "define"]:
        
            definitions.add(pieces[2])
            
            features = dependents.get(pieces[2], [])
            i = 0
            while i < len(features):
                definitions.add(features[i])
                features += dependents.get(features[i], [])
                i += 1
    
    return list(definitions)

def read_features(features_file):

    features = {}
    lines = map(lambda line: line.strip(), open(features_file).readlines())
    feature = ""
    
    for line in lines:
    
        try:
            key, value = line.split(":")
        except ValueError:
            continue
        
        if key == "Feature":
            feature = value.lstrip()
        elif feature and key == "Requires" and value:
            features[feature] = value.lstrip().split()
    
    # Turn the dictionary of dependencies into a dictionary of dependents
    # so that we can figure out which features to switch off when any given
    # feature is disabled.
    
    dependents = {}
    for feature, dependencies in features.items():
    
        for dependency in dependencies:
            dependents.setdefault("QT_NO_"+dependency, []).append("QT_NO_"+feature)
    
    return dependents

def convert_configuration(configuration_lines):

    definitions = []
    unknown = []
    for definition in configuration_lines:
    
        try:
            definition = conversion_dict[definition]
        except KeyError:
            unknown.append(definition)
            continue
        
        if definition:
            definitions.append(definition)
    
    if unknown:
        sys.stderr.write("Unknown features: %s\n" % " ".join(unknown))
        sys.exit(1)
    
    definitions.sort()
    
    qt_version_number = (env["QT_VERSION"][0] << 16) + \
                        (env["QT_VERSION"][1] << 8) + \
                        env["QT_VERSION"][2]
    
    lines = [prefix_join(env["TARGETDIR"]),
             prefix_join(env["TARGETDIR"], "include"),
             prefix_join(env["TARGETDIR"], "lib"),
             prefix_join(env["TARGETDIR"], "bin"),
             prefix_join(env["TARGETDIR"]),
             prefix_join(env["TARGETDIR"], "plugins"),
             str(qt_version_number),
             "8",                       # open source edition
             "Open Source",
             "shared"] + definitions
    
    return lines

def build_embedded_pyqt(configuration_lines = None):

    if not configuration_lines:
        configuration_lines = []
    
    dest_dir = env.get("DESTDIR", "")
    
    # Enter the distribution directory.
    chdir(env["PYQTDIR"])
    
    env_commands = (
        "PATH="+os.path.join(env["TARGET_TOOLS_BIN"])+":"+env["ORIGINAL_PATH"] + " "
        "CROSS_SIPCONFIG="+prefix_join(env["TARGETDIR"], "lib", "python"+env["PYTHON_MAJOR_MINOR"], "site-packages") + " "
        "LD_LIBRARY_PATH="+os.path.join(env["NATIVE_TOOLS"], "lib") + " "
        "QMAKESPEC="+prefix_join(env["TARGETDIR"], "mkspecs", "qws", env["TARGET_PLATFORM_SPEC"]) + " "
        )
    
    # Create a configuration file for the configure script to use.
    open("qtdirs.out", "w").write("\n".join(configuration_lines))
    
    # Copy the new configure script and qtdirs.out into the distribution.
    system("cp "+os.path.join(env["PYQTPATCHDIR"], "configure-qws.py")+" .")
    system("python "+os.path.join(env["PYQTPATCHDIR"], "patch_files.py")+" "+os.path.join(env["PYQTPATCHDIR"], "sip")+" sip")
    system("python "+os.path.join(env["PYQTPATCHDIR"], "patch_files.py")+" "+os.path.join(env["PYQTPATCHDIR"], "qpy")+" qpy")
    
    system(
        env_commands + \
        os.path.join(env["NATIVE_TOOLS"], "bin", "python")+" configure-qws.py " + \
        "-b "+os.path.join(env["TARGETDIR"], "bin") + " " + \
        "-d "+os.path.join(env["TARGETDIR"], "lib", "python"+env["PYTHON_MAJOR_MINOR"], "site-packages") + " " + \
        "-l "+prefix_join(env["TARGETDIR"], "include", "python"+env["PYTHON_MAJOR_MINOR"]) + " " + \
        "-m "+prefix_join(env["TARGETDIR"], "lib", "python"+env["PYTHON_MAJOR_MINOR"], "config") + " " + \
        "-q "+prefix_join(env["TARGETDIR"], "bin", "qmake") + " " + \
        "-v "+os.path.join(env["TARGETDIR"], "share", "sip", "PyQt4") + " " + \
        "-w --confirm-license"
        )
    
    # You may need to fix the -I /usr/include/python2.5 entries in
    # qpy/QtCore/Makefile and qpy/QtGui/Makefile to refer to
    # $TARGETDIR/include/python2.5 instead.
    
    env_commands = "PATH="+os.path.join(env["TARGET_TOOLS_BIN"])+":"+env["ORIGINAL_PATH"]+" "
    system(env_commands + "make -j"+env["TARGET_COMPILERS"])
    
    # Since support for DESTDIR was added later, I've made it optional.
    if env.has_key("DESTDIR"):
        system(env_commands + "make install DESTDIR="+env["DESTDIR"])
    else:
        system(env_commands + "make install")


################################################################################
# Calls to build functions and additional changes to configuration go here.
################################################################################

if __name__ == "__main__":

    py_suffix = os.extsep + "py"
    pyc_suffix = os.extsep + "pyc"
    
    argv = sys.argv[:]
    quiet = read_option(("-q", "--quiet"), argv)
    
    if len(argv) == 2:
    
        settings_file = argv[1]
        if settings_file.endswith(py_suffix):
            settings_file = settings_file[:-len(py_suffix)]
        
        local_settings = __import__(settings_file)
    
    elif len(argv) == 1:
        import local_settings
    
    else:
        sys.stderr.write("Usage: %s [local settings file]\n" % sys.argv[0])
        sys.exit(1)
    
    env = local_settings.env
    
    print "Default settings:"
    print
    for key, value in env.items():
        print key, ":", value
    print
    
    print "Qt configuration options:", local_settings.qt_options
    print "Qt configuration profile:", local_settings.qt_configuration_profile
    print "Extra Qt configuration:", local_settings.extra_qt_configuration
    print "Extra PyQt configuration:", local_settings.extra_pyqt_configuration
    print
    
    if not quiet:
    
        settings_source_file = local_settings.__file__
        if settings_source_file.endswith(pyc_suffix):
            settings_source_file = settings_source_file[:-len(pyc_suffix)] + py_suffix
        
        print "Exit and edit the %s file to change these values." % settings_source_file
        while True:
            a = raw_input("Continue or exit (c|e):")
            if a == "c":
                break
            elif a == "e":
                sys.exit()
    
    # Locate and unpack sources in the current directory, and update the global
    # dictionary of useful variables to expose to child processes.
    locate_sources()
    make_working_directory()
    unpack_sources()
    update_environment()
    
    # Check whether the Qt configuration profile exists before we start.
    if local_settings.qt_configuration_profile:
    
        qconfig_path = os.path.join(env["QTDIR"], "src", "corelib", "global")
        features_path = os.path.join(qconfig_path, "qfeatures" + os.extsep + "txt")
        configuration_file = "qconfig-" + local_settings.qt_configuration_profile+os.extsep+"h"
        
        config_dirs = [os.pardir, qconfig_path]
        
        for config_dir in config_dirs:
            config_path = os.path.join(config_dir, configuration_file)
            if os.path.exists(config_path):
                if config_dir != qconfig_path:
                    system("cp " + config_path + " " + os.path.join(qconfig_path, configuration_file))
                break
        else:
            sys.stderr.write("Cannot locate %s.\n" % configuration_file)
            sys.exit(1)
        
        qt_configuration_lines = read_configuration(config_path, features_path)
    else:
        qt_configuration_lines = []
    
    qt_configuration_profile = local_settings.qt_configuration_profile
    extra_qt_configuration = local_settings.extra_qt_configuration
    
    pyqt_configuration_lines = convert_configuration(qt_configuration_lines + extra_qt_configuration)
    pyqt_configuration_lines += local_settings.extra_pyqt_configuration
    
    # If configuration checks were successful, we can create the target
    # directories.
    create_target_directories()
    
    build_native_python()
    build_native_sip()
    
    if env["TARGET_TOOLS"] != env["NATIVE_TOOLS"]:
        build_embedded_zlib()
        build_embedded_python()
        build_embedded_sip()
        
        if tslib_archive:
            build_embedded_tslib()
    
    build_qt(qt_options = local_settings.qt_options,
             configuration_profile = qt_configuration_profile,
             extra_configuration = extra_qt_configuration)
    
    # The following features are PyQt-specific and may need to be passed to
    # build_embedded_pyqt() as additional configuration lines:
    #
    # Py_DateTime
    # PyQt_NoQtPrintRangeBug
    # PyQt_OpenSSL
    # PyQt_qreal_double
    # Py_v3
    
    build_embedded_pyqt(pyqt_configuration_lines)
    
    sys.exit()