1. Even Wiik Thomassen
  2. pilgui

Source

pilgui / pilgui.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
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
PILGUI, a Graphical User Interface for Python Image Library (PIL).

A program for viewing images, which provides easy
access to PIL's funcionality.

ImageViewers should preferably be created through the factory function show.

If pythondoc is installed it will read PIL's documentation, to extend
the information available in dialogs. If pythondoc is missing the same
documentation can be stored in xml files, which the code will look for.

The GUI consist mainly of themed tk widgets (ttk), while toplevel windows
are Tkinter widgets, ttk is included with python 2.7 and the package should
work from python 2.5 and up.
"""

# List of improvements todo:
#  More complete list of file extensions for write and open dialogs
#  show() should return the viewer it created
#  Better support for color input
#  Disable menu's when no image is open
#  More descriptive modes list
#  List of fonts in draw text
#  Link the different image enhancers

import sys
import os
import inspect
import random
import urllib
import math

import Tkinter as tk
import ttk
import tkFileDialog
import tkMessageBox
import tkColorChooser

import xml.etree.ElementTree as ET

try:
    from PIL import (Image, ImageTk, ImageOps, ImageFilter, ImageChops,
            ImageStat, ImageEnhance, ImageDraw, ImageFont, ImageMode)
except ImportError:
    tkMessageBox.showerror('PIL not found',
            'Fatal error: Failed to import PIL.')
    raise RuntimeError('PILgui requires PIL to be installed')


def _convert_input(value):
    """Convert input to int or float if possible"""
    try:
        value = int(value)
    except ValueError:
        try:
            value = float(value)
        except ValueError:
            pass
    return value


def _handle_exception(ex, parent, txt=''):
    """Show error dialog with info without hiding the exception."""
    tkMessageBox.showerror('Unexpected error', '%s%s:\n%s' % (
        (txt and '%s\n' % txt), ex.__class__.__name__, ex), parent=parent)
    sys.excepthook(*sys.exc_info())


class ImageViewer(tk.Tk):
    """A toplevel window for viewing images and performing actions on them.

    The actions which can be performed are simply wrappers
    of PIL functionality.
    """

    read_extensions = []  # PIL supported read file types
    write_extensions = []  # PIL supported write file types
    pydoc_db = {}  # ElementTree's of PIL documentation

    def __init__(self, delay=False):
        """Sets up the Graphic User Interface.

        'delay': If true will postpone some tasks, to help improve
        the responsiveness of the loading of the viewer.
        """
        tk.Tk.__init__(self)
        self.title('PIL ImageViewer')
        self.geometry('700x500')

        self.default_path = sys.path[0]  # Used in open and write dialogs
        self.default_write_ext = '.png'  # Used in write dialog

        # Pulldown menu
        self.menubar = tk.Menu(self)
        self.config(menu=self.menubar)

        # Tabs for holding images
        self.tabs = []
        self.notebook = ttk.Notebook(self)
        self.notebook.pack(anchor='nw', fill='both', expand=1)

        # Populates the menu bar and prepares documentation for dialogs
        if not delay:
            self.build_menu()
            self.prepare_docs()

    def prepare_docs(self):
        """Add documentation to all registered actions."""
        if not self.pydoc_db:
            self.parse_pil_docs()
            if not self.pydoc_db:
                return

        for action in BaseAction.registered_actions:
            if action.require_dialog:
                action.docs_db = self.pydoc_db
                if callable(action.function):
                    action.prepare()

    def build_menu(self):
        """Fill the viewer's menu with actions."""
        # Supported PIL modes
        ImageMode.getmode('1')  # Initialize mode cache
        modes = ImageMode._modes.keys()

        resamplings = {
            'Nearest': Image.NEAREST, 'Linear': Image.LINEAR,
            'Cubic': Image.CUBIC
        }

        all_resamplings = {'Antialias': Image.ANTIALIAS}
        all_resamplings.update(resamplings)

        transforms = {
            'Extent': Image.EXTENT, 'Affine': Image.AFFINE, 'Quad': Image.QUAD,
            'Mesh': Image.MESH, 'Perspective': Image.PERSPECTIVE
        }

        transposes = {
            'Flip left right': Image.FLIP_LEFT_RIGHT,
            'Flip top bottom': Image.FLIP_TOP_BOTTOM,
            'Rotate 90 degrees': Image.ROTATE_90,
            'Rotate 180 degrees': Image.ROTATE_180,
            'Rotate 270 degrees': Image.ROTATE_270
        }

        # Draw operations
        draws = (
            PILDraw('arc', Boxes(4), Entry, Entry, Color),
            PILDraw('bitmap', Boxes(2), ImgList(masks=True), Color),
            PILDraw('chord', Boxes(4), Entry, Entry, Color, Color),
            PILDraw('ellipse', Boxes(4), Color, Color),
            PILDraw('line', Boxes(4), Color, Entry),
            PILDraw('pieslice', Boxes(4), Entry, Entry, Color, Color),
            PILDraw('point', Boxes(2), Color),
            PILDraw('rectangle', Boxes(4), Color, Color),
            PILDraw('text', Boxes(2), Entry, Color, FontList),
            #PILFunc(ImageDraw.floodfill, Img, Boxes(2), Color)
            #PILDraw('polygon') todo,
        )

        # Image operations
        operations = (
            PILFunc(ImageOps.autocontrast, Img,
                Entry(0, 100), Entry(0, 255, none=True)),
            PILFunc(ImageOps.colorize, Img, Color, Color),
            PILFunc(ImageOps.crop, Img, Entry),
            PILFunc(ImageOps.equalize, Img, ImgList),
            PILFunc(ImageOps.expand, Img, Entry, Color),
            PILFunc(ImageOps.fit, Img, Boxes(2),
                ListSelect(all_resamplings), Entry(0.0, 1.0), Boxes(2)),
            PILFunc(ImageOps.flip, Img),
            PILFunc(ImageOps.grayscale, Img),
            PILFunc(ImageOps.invert, Img),
            PILFunc(ImageOps.mirror, Img),
            PILFunc(ImageOps.posterize, Img, Entry(1, 8)),
            PILFunc(ImageOps.solarize, Img, Entry(0, 255)),
            PILFunc(ImageOps.gaussian_blur, Img, Entry),
            PILFunc(ImageOps.unsharp_mask, Img, Entry, Entry, Entry)
        )

        # Arithmetic image operations
        arithmetics = (
            PILFunc(ImageChops.constant, Img, Entry),
            PILFunc(ImageChops.duplicate, Img, new=True),
            PILFunc(ImageChops.invert, Img),
            PILFunc(ImageChops.lighter, ImgList, ImgList, new=True),
            PILFunc(ImageChops.darker, ImgList, ImgList, new=True),
            PILFunc(ImageChops.difference, ImgList, ImgList, new=True),
            PILFunc(ImageChops.multiply, ImgList, ImgList, new=True),
            PILFunc(ImageChops.screen, ImgList, ImgList, new=True),
            PILFunc(ImageChops.add, ImgList, ImgList, Entry, Entry, new=True),
            PILFunc(ImageChops.subtract,
                ImgList, ImgList, Entry, Entry, new=True),
            PILFunc(ImageChops.add_modulo, ImgList, ImgList, new=True),
            PILFunc(ImageChops.subtract_modulo, ImgList, ImgList, new=True),
            PILFunc(ImageChops.logical_and, ImgList, ImgList, new=True),
            PILFunc(ImageChops.logical_or, ImgList, ImgList, new=True),
            PILFunc(ImageChops.logical_xor, ImgList, ImgList, new=True),
            PILFunc(ImageChops.blend, ImgList, ImgList, Entry, new=True),
            PILFunc(ImageChops.composite,
                ImgList, ImgList, ImgList(True), new=True),
            PILFunc(ImageChops.offset, Img, Entry, Entry(none=True))
        )

        # Image filters
        filters = (
            PILFilter(ImageFilter.MedianFilter, Entry),
            PILFilter(ImageFilter.MinFilter, Entry),
            PILFilter(ImageFilter.MaxFilter, Entry),
            PILFilter(ImageFilter.ModeFilter, Entry),
            PILFilter(ImageFilter.GaussianBlur, Entry),
            PILFilter(ImageFilter.UnsharpMask, Entry, Entry, Entry),
            PILFilter(ImageFilter.BLUR),
            PILFilter(ImageFilter.CONTOUR),
            PILFilter(ImageFilter.DETAIL),
            PILFilter(ImageFilter.EDGE_ENHANCE),
            PILFilter(ImageFilter.EDGE_ENHANCE_MORE),
            PILFilter(ImageFilter.EMBOSS),
            PILFilter(ImageFilter.FIND_EDGES),
            PILFilter(ImageFilter.SMOOTH),
            PILFilter(ImageFilter.SMOOTH_MORE),
            PILFilter(ImageFilter.SHARPEN)
        )

        # File options
        menu = tk.Menu(self.menubar, tearoff=0)
        new = PILFunc(Image.new, ListSelect(modes), Boxes(2), Color, new=True)
        new.add_to_menu(menu, self)
        menu.add_command(label='Open..', command=self.open)
        menu.add_command(label='Download..', command=self.download)
        menu.add_command(label='Grab clipboard', command=self.grabclipboard)
        menu.add_separator()
        menu.add_command(label='Save..', command=self.save)
        menu.add_command(label='Close', command=self.close)
        menu.add_separator()
        menu.add_command(label='Exit', command=self.destroy)
        self.menubar.add_cascade(label='File', menu=menu)

        # View options
        menu = tk.Menu(self.menubar, tearoff=0)
        menu.add_command(label='Information',
                command=lambda: ImgInfoDialog(self))
        menu.add_command(label='Statistics',
                command=lambda: ImgStatsDialog(self))
        menu.add_separator()
        menu.add_command(label='Zoom in', command=lambda: self.zoom(scale=1.2))
        menu.add_command(label='Zoom out',
                         command=lambda: self.zoom(scale=0.8))
        menu.add_command(label='Fit to screen',
                         command=lambda: self.zoom(True))
        self.menubar.add_cascade(label='View', menu=menu)

        # Edit options
        self.edit = tk.Menu(self.menubar, tearoff=0)
        self.edit.add_command(label='Undo', state='disabled',
                command=lambda: self.current_tab().undo())
        self.edit.add_command(label='Redo', state='disabled',
                command=lambda: self.current_tab().redo())
        self.edit.add_separator()
        copy = PILMethod('copy', new=True)
        copy.add_to_menu(self.edit, self)
        convert = PILMethod('convert', ListSelect(modes))
        convert.add_to_menu(self.edit, self)
        crop = PILMethod('crop', Boxes(4))
        crop.add_to_menu(self.edit, self)
        paste = PILMethod('paste', ImgList, Boxes(4, 2), ImgList(masks=True))
        paste.add_to_menu(self.edit, self)
        self.edit.add_command(label='Enhance..', command=self.enhance)
        self.edit.add_separator()
        resize = PILMethod('resize', Boxes(2), ListSelect(all_resamplings))
        resize.add_to_menu(self.edit, self)
        rotate = PILMethod('rotate', Entry, ListSelect(resamplings), Bool)
        rotate.add_to_menu(self.edit, self)
        transpose = PILMethod('transpose', ListSelect(transposes))
        transpose.add_to_menu(self.edit, self)
        transform = PILMethod('transform', Boxes(2), ListSelect(transforms),
                Boxes(8, 4), ListSelect(resamplings))
        transform.add_to_menu(self.edit, self)
        self.menubar.add_cascade(label='Edit', menu=self.edit)

        # Draw actions
        menu = tk.Menu(self.menubar, tearoff=0)
        for ops in draws:
            ops.add_to_menu(menu, self)
        self.menubar.add_cascade(label='Draw', menu=menu)

        # Operations
        menu = tk.Menu(self.menubar, tearoff=0)
        for ops in operations:
            ops.add_to_menu(menu, self)
        self.menubar.add_cascade(label='Operations', menu=menu)

        # Arithmetics
        menu = tk.Menu(self.menubar, tearoff=0)
        for action in arithmetics:
            action.add_to_menu(menu, self)
        self.menubar.add_cascade(label='Arithmetics', menu=menu)

        # Filters
        menu = tk.Menu(self.menubar, tearoff=0)
        for action in filters:
            action.add_to_menu(menu, self)
        self.menubar.add_cascade(label='Filters', menu=menu)

    def current_tab(self):
        """Find the currently selected tab."""
        if self.tabs:
            return self.tabs[self.notebook.index('current')]
        return None

    def get_image(self):
        """Returns the currently viewed image."""
        return self.current_tab().get_image()

    def get_image_stats(self):
        """Get statistics object for the current image."""
        return ImageStat.Stat(self.get_image())

    def update_image(self, image, new=False):
        """Update the viewer with the given image.

        'new' tells the viewer to give it a new tab.
        """
        if new:
            self.view(image, active=True)
        else:
            frame = self.current_tab()
            if frame is not None:
                frame.view(image)

    def view(self, image, title=None, active=False):
        """View the given image.

        'title' is used to specify the label on the tab.
        'active' makes the image's tab be selected.
        """
        if title is None:
            title = 'img%i' % random.randint(1000, 9999)

        frame = ImageFrame(self.notebook, self, image)
        self.notebook.add(frame, text=title)
        self.tabs.append(frame)

        if active:
            self.notebook.select(len(self.tabs) - 1)

    def zoom(self, fit_to_screen=False, scale=None):
        """Resize the image.

        Resizes the currently viewed image with either a given scale,
        or the best scale for the screen (fixed aspect ratio).
        """
        image = self.get_image()
        if fit_to_screen:
            width = min(self.winfo_width(), self.winfo_screenwidth()) - 20
            height = min(self.winfo_height(), self.winfo_screenwidth()) - 50
            scale = float(width) / image.size[0]
            scale2 = float(height) / image.size[1]
            if scale2 < scale:
                scale = scale2
            new_size = (int(image.size[0] * scale), int(image.size[1] * scale))
        else:
            new_size = (int(image.size[0] * scale), int(image.size[1] * scale))
        self.update_image(image.resize(new_size, Image.ANTIALIAS))

    def close(self):
        """Close the tab of the currently viewed image.

        Will close the viewer if there are no open images.
        """
        if not self.tabs:
            self.destroy()
            return
        self.tabs.remove(self.current_tab())
        self.notebook.forget('current')
        if not self.tabs:
            self.destroy()

    def open(self, filename=None, title=None):
        """Open a file and view it.

        'filename': If not specified, will show a dialog for selecting a
        file, otherwise will try to open the file.
        'title': If provided is the label for the images tab, otherwise
        be taken from the filename.
        """
        # Get some of the supported image extensions from PIL
        if not self.read_extensions:
            for ext, name in Image.EXTENSION.items():
                self.read_extensions.append(('All images', ext))
                self.read_extensions.append((name, ext))

        if filename is None:
            filename = tkFileDialog.askopenfilename(
                    parent=self,
                    title='Select image to open',
                    initialdir=self.default_path,
                    filetypes=[('All files', '*.*')] + self.read_extensions)

        if filename:
            if title is None:
                self.default_path, title = os.path.split(filename)
            try:
                image = Image.open(filename)
            except IOError as e:
                _handle_exception(e, self, 'Failed to open the image.')
            else:
                image.load()
                self.view(image, title=title, active=True)

    def save(self):
        """Open a dialog for saving the currently viewed image."""
        # Get some of the supported write filetypes from PIL
        if not self.write_extensions:
            self.write_extensions += [(i, ext) for ext, i in
                                        Image.EXTENSION.items()]

        frame = self.current_tab()
        if frame is None:
            return

        filename = tkFileDialog.asksaveasfilename(
                parent=self,
                title='Save image as',
                defaultextension=self.default_write_ext,
                initialdir=self.default_path,
                filetypes=[('All files', '*.*')] + self.write_extensions)

        if filename:
            basepath, self.default_write_ext = os.path.splitext(filename)
            self.default_path = os.path.dirname(basepath)
            try:
                frame.get_image().save(filename)
            except (KeyError, IOError) as e:
                _handle_exception(e, self, 'Failed to save the image.')

    def download(self):
        """Open a dialog for downloading an image from the net."""
        d = DownloadDialog(self, 'Enter url to download')

        if d.result:
            try:
                filename, headers = urllib.urlretrieve(d.result)
            except IOError as e:
                _handle_exception(e, self, 'Illegal url, no such image.')
            else:
                self.open(filename, os.path.split(d.result)[1])

    def enhance(self):
        """Show dialog for enhancing certain aspects of an image."""
        image = self.get_image()
        d = ImgEnhanceDialog(self)
        if not d.result:
            self.update_image(image)

    def grabclipboard(self):
        """View images found in clipboard."""
        from PIL import ImageGrab
        im = ImageGrab.grabclipboard()
        if isinstance(im, Image.Image):
            self.view(im, active=True)
        elif im:
            for filename in im:
                try:
                    im = Image.open(filename)
                except IOError:
                    pass  # ignore this file
                else:
                    self.view(im, active=True)

    @classmethod
    def parse_pil_docs(cls):
        """Find PIL documentation in xml files, or create it with pythondoc."""
        modules = (Image, ImageOps, ImageFilter, ImageChops, ImageDraw)

        # Try to parse xml files if they exist
        not_found = []
        for module in modules:
            name = module.__name__
            try:
                cls.pydoc_db[name] = ET.parse('pythondoc-%s.xml' % name)
            except IOError:
                not_found.append(module)

        if not not_found:
            return  # If all exist we have what we need

        # Parse pythondoc from modules source files if available
        try:
            import pythondoc
        except ImportError:
            return  # Pythondoc is missing, we show less info in dialogs

        for module in not_found:
            source = module.__file__
            if source[-1] in 'oc' and source[-4:-1] == '.py':
                source = source[:-1]
            tree = ET.ElementTree(pythondoc.parse(source, prefix='PIL'))
            tree.write('pythondoc-%s.xml' % module.__name__)
            cls.pydoc_db[module.__name__] = tree


class ImageFrame(ttk.Frame):
    """A frame which holds an image in a scrollable canvas."""

    history_length = 5  # Amount of versions of the current image to hold

    def __init__(self, parent, viewer, image):
        """Create a frame which holds an image.

        'parent' is the parent widget.
        'viewer' is the ImageViewer, used to disable/enable undo/redo.
        'image' is the actual image to show.
        """
        ttk.Frame.__init__(self, parent)
        self.viewer = viewer

        # Image history, for undo/redo
        self.current = image
        self.current_pos = 0
        self.history = []

        # Image canvas with scrollbars
        vscrollbar = AutoScrollbar(self)
        vscrollbar.grid(row=0, column=1, sticky='ns')
        hscrollbar = AutoScrollbar(self, orient='horizontal')
        hscrollbar.grid(row=1, column=0, sticky='ew')
        self.canvas = tk.Canvas(self,
                yscrollcommand=vscrollbar.set, xscrollcommand=hscrollbar.set)
        self.canvas.grid(row=0, column=0, sticky='nsew')
        vscrollbar.config(command=self.canvas.yview)
        hscrollbar.config(command=self.canvas.xview)

        # Make the canvas expandable
        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(0, weight=1)

        # Label with the actual image on it
        self.label = ttk.Label(self.canvas)
        self.label.rowconfigure(1, weight=1)
        self.label.columnconfigure(1, weight=1)
        self.view(image)
        self.label.grid()

        self.canvas.create_window(0, 0, anchor='nw', window=self.label)
        self.label.update_idletasks()
        self.canvas.config(scrollregion=self.canvas.bbox('all'))

    def get_image(self):
        """Return the image object which this tab is showing."""
        return self.current

    def view(self, image=None):
        """Show the image, and update image history."""
        # Update image version history
        if image is not None:
            if self.current_pos > 0:
                del self.history[0:self.current_pos]
                self.current_pos = 0
            self.history.insert(0, image)
            if len(self.history) > self.history_length:
                self.history.pop()
            self.current = image

        # Enable/disable undo/redo commands
        if self.current_pos < len(self.history) - 1:
            self.viewer.edit.entryconfig(0, state='normal')
        else:
            self.viewer.edit.entryconfig(0, state='disabled')
        if self.current_pos > 0:
            self.viewer.edit.entryconfig(1, state='normal')
        else:
            self.viewer.edit.entryconfig(1, state='disabled')

        # Show image on label
        if self.current.mode == '1':
            self._img = ImageTk.BitmapImage(self.current, foreground='white')
            self.label.configure(image=self._img, background='black')
        else:
            self._img = ImageTk.PhotoImage(self.current)
            self.label.configure(image=self._img, background=None)
        self.canvas.config(scrollregion=self.canvas.bbox('all'))

    def undo(self):
        """Show the previous image if possible."""
        if self.current_pos + 1 < len(self.history):
            self.current_pos += 1
            self.current = self.history[self.current_pos]
            self.view()

    def redo(self):
        """Show the newer image in the history if possible."""
        if self.current_pos - 1 >= 0:
            self.current_pos -= 1
            self.current = self.history[self.current_pos]
            self.view()


class BaseInput():
    """Represents an argument requiring input from the user."""

    def __init__(self, name=None):
        self.value = None
        self.label = None  # Label for the argument if required
        self.require_input = True  # Argument requires user input?
        self.optional = False  # Is the argument optional
        self.default = None  # The default value for the argument
        self.name = name  # Argument is not positional, but named
        self.docs = []  # List of string documenting the argument

    def verify(self):
        """Verify that the input is valid, and return it."""
        return True, self.value

    def get_entry(self, parent, viewer=None, width=8):
        """Create TK entry box for the argument."""
        self.entry = ttk.Entry(parent, width=width)
        if self.default is not None:
            self.entry.insert(0, self.default)
        return self.entry


class Img(BaseInput):
    """Represents the currently viewed image."""

    def __init__(self):
        BaseInput.__init__(self)
        self.require_input = False


class ListSelect(BaseInput):

    def __init__(self, data, *args, **vargs):
        BaseInput.__init__(self, *args, **vargs)
        if not isinstance(data, dict):
            data = {i: i for i in data}
        self.list_data = data

    def get_entry(self, parent, viewer):
        keys = sorted(self.list_data.keys())
        if keys:
            w = max(5, max(map(len, keys)))
        else:
            w = 5
        self.box = ttk.Combobox(parent, state='readonly', values=keys, width=w)

        # Select default value in box
        if keys:
            if not self.optional and self.default is None:
                self.box.current(0)
            else:
                for i in range(len(keys)):
                    if self.list_data[keys[i]] == self.default:
                        self.box.current(i)

        return self.box

    def verify(self):
        value = self.box.get()
        if not value:
            if self.optional:
                return True, None
            return False, None
        return True, self.list_data[value]


class Bool(ListSelect):

    def __init__(self):
        ListSelect.__init__(self, {'True': True, 'False': False})


class ImgList(ListSelect):
    """Represents a list of all open images."""

    def __init__(self, masks=False):
        ListSelect.__init__(self, {})
        self.only_masks = masks

    def get_entry(self, parent, viewer):
        self.list_data = {f.name: f.get_image() for f in viewer.tabs}
        if self.only_masks:
            modes = ('1', 'L', 'RGBA')
            self.list_data = {n: i for n, i in
                    self.list_data.items() if i.mode in modes}
        return ListSelect.get_entry(self, parent, viewer)


class FontList(ListSelect):
    """Represents all installed fonts, todo."""

    def __init__(self):
        ListSelect.__init__(self, {'Default': ImageFont.load_default()})


class Color(BaseInput):
    """Represent a color input."""

    def get_entry(self, parent, viewer):
        frame = ttk.Frame(parent)
        self.entry = ttk.Entry(frame, width=8)
        self.entry.pack(side='left')
        ttk.Button(frame, text='.', width=3,
                command=lambda: self.select_color(viewer)).pack(side='left')
        return frame

    def select_color(self, viewer):
        color = self.entry.get()
        if len(color) != 7 or color[0] != '#':
            color = ''
        tmp, new_color = tkColorChooser.askcolor(color, parent=viewer)
        if new_color:
            self.entry.delete(0, 'end')
            self.entry.insert(0, new_color)

    def verify(self):
        # TODO: better testing, accept rbg(..) & lue(..) ??
        color = _convert_input(self.entry.get())

        if not color:
            if self.optional:
                return True, self.default
            else:
                return False, color

        if ',' in color:
            color = color.replace('(', '').replace(')', '').split(',')
            color = tuple([int(i) for i in color if i])
            if color:
                return True, color
            else:
                return False, color

        return True, color


class Boxes(BaseInput):

    def __init__(self, count, min_=None, name=None):
        BaseInput.__init__(self, name=name)
        self.box_count = count  # Amount of input boxes to display
        if min_ is not None:
            self.min_count = min_  # Minimum of values required
        else:
            self.min_count = count

    def get_entry(self, parent, viewer):
        frame = ttk.Frame(parent)
        self.boxes = [None] * self.box_count

        # Split boxes over lines of max 4
        nr = boxes = self.box_count
        lines = 2
        while nr > 4:
            nr = int(math.ceil(boxes / lines))
            lines += 1

        for i in range(len(self.boxes)):
            self.boxes[i] = ttk.Entry(frame, width=6)
            self.boxes[i].grid(row=(i // nr), column=(i % nr), padx=1, pady=1)

        if self.default:
            for i in range(min(len(self.default), len(self.boxes))):
                self.boxes[i].insert(0, self.default[i])

        return frame

    def verify(self):
        values = []
        for i in range(len(self.boxes)):
            value = self.boxes[i].get()
            if value:
                values.append(_convert_input(value))
        values = tuple(values)
        if self.optional and not values:
            return True, None
        if len(values) >= self.min_count:
            return True, values
        return False, values


class Entry(BaseInput):
    """Entry is simply a value, which can be a string, int or float."""

    def __init__(self, start=None, end=None, name=None, none=False):
        BaseInput.__init__(self, name=name)
        self.start = start
        self.end = end
        self.none = none  # The argument accepts None as value

    def verify(self):
        """Test the validity of the value, and convert it if neceserly."""
        value = self.entry.get()

        if self.none or self.optional:
            if value == '' or value.lower() == 'none':
                return True, None
        if not value and not self.optional:
            return False, value

        # Convert value to int or float if possible
        value = _convert_input(value)

        # Test against range if provided
        if self.start is not None and value < self.start:
            return False, value
        if self.end is not None and value > self.end:
            return False, value

        # Value is valid
        return True, value


class BaseAction():

    # All actions created, used to register pydoc documentations
    registered_actions = []

    def __init__(self, func, *args, **vargs):
        self.function = func  # Called to apply the action
        self.args = list(args)  # Arguments to function
        self.prepared = False  # Are the arguments processed?
        self.docs_db = None  # Hook for ElementTrees with docs for PIL modules
        self.documentation = ''  # Displayed in the dialog window, if set

        # Label for menu
        if 'name' in vargs:
            name = vargs['name']
        else:
            name = func.__name__
        self.name = name.replace('_', ' ').capitalize()

        # Docstring
        if 'docstr' in vargs:
            self.__doc__ = vargs['docstr']
        else:
            self.__doc__ = func.__doc__

        # Create a new image instead of updating
        if 'new' in vargs and vargs['new']:
            self.new = True
        else:
            self.new = False

        # Prepare dialog if needed
        if len(args) == 0 or (len(args) == 1 and args[0] is Img):
            self.require_dialog = False
        else:
            self.require_dialog = True
            self.name += '..'

        self.registered_actions.append(self)

    def prepare(self):
        if not self.prepared:
            self.prepare_args()
        if self.docs_db is not None:
            self.prepare_docs()

    def prepare_args(self):
        # Support for func being class
        func = self.function
        if inspect.isclass(func):
            func = func.__init__

        # Adjust for self
        offset = 0
        if inspect.ismethod(func):
            offset = 1

        # Find arg names and default values by inspection
        names, varargs, varkw, defaults = inspect.getargspec(func)
        for i in range(len(self.args)):
            # Initialize arguments if they are class
            if (inspect.isclass(self.args[i]) and
                    issubclass(self.args[i], BaseInput)):
                self.args[i] = self.args[i]()

            if self.args[i].require_input:
                j = i + offset
                if self.args[i].name is not None:
                    j = names.index(self.args[i].name)  # Named args

                self.args[i].label = names[j].capitalize()
                self.args[i].name = names[j]

                if defaults is not None:
                    j -= (len(names) - len(defaults))
                    if j >= 0 and j < len(defaults):
                        self.args[i].optional = True
                        self.args[i].default = defaults[j]
                        self.args[i].docs.append('Optional.')

        self.prepared = True

    def prepare_docs(self):
        def innertext(node):
            if node is None:
                return ''

            # Traverse nodetree, find text and tail
            def parse(node):
                txt = []
                txt.append(node.text)
                for n in node[:]:
                    txt.extend(parse(n))
                    if n.tag == 'p':
                        txt.append('&break;')  # Hack to replace /p with \n\n
                txt.append(node.tail)
                return txt

            # Tidy node's inner text
            text = ''.join(i for i in parse(node) if i)
            text = ' '.join(text.split())  # Remove extra white space
            text = text.replace('&break;', '\n\n')
            return text.replace('\n ', '\n').rstrip()

        # Handle functions, methods and class
        func = self.function
        if inspect.isclass(func):
            func = func.__init__
        if inspect.ismethod(func):
            tag = 'method'
            module = func.im_class.__module__
            name = '%s.%s.%s' % (module, func.im_class.__name__, func.__name__)
        else:
            tag = 'function'
            module = func.__module__
            name = '%s.%s' % (module, func.__name__)

        # Hack for methods which belongs to subclasses of Image
        if module not in self.docs_db:
            module = 'PIL.Image'
            name = '%s.Image.%s' % (module, func.__name__)

        # Find the functions info
        tree = self.docs_db[module]
        nodes = tree.findall('.//%s[@name]' % tag)
        node = [n for n in nodes if n.get('name') == name][0]
        info = node.find('info')

        # The functions description
        self.documentation = innertext(info.find('description'))
        if not self.documentation:
            self.documentation = innertext(info.find('summary'))

        # Argument descriptions
        params = {}
        for param in info.findall('param') + info.findall('keyparam'):
            params[param.get('name')] = innertext(param)

        for arg in self.args:
            if arg.require_input and arg.name in params:
                arg.docs.append(params[arg.name])

        self.docs_db = None

    def add_to_menu(self, menu, viewer):
        """Adds the action to the TK menu."""
        self.viewer = viewer
        menu.add_command(label=self.name, command=self.action)


class PILFunc(BaseAction):

    def action(self):
        """Called when the user selects the action in the GUI's menu."""
        self.prepare()
        image = self.viewer.get_image()

        for arg in self.args:
            if isinstance(arg, Img):
                arg.value = image

        if not self.require_dialog:
            values = [i.value for i in self.args if i.value is not None]
            kw = {}
        else:
            dialog = DialogFactory(self.viewer, self)
            if dialog.result is None:
                return  # Dialog cancelled, abort action
            values, kw = dialog.result

        try:
            output = self.function(*values, **kw)
            self.viewer.update_image(output, new=self.new)
        except Exception as e:
            _handle_exception(e, self.viewer)


class PILMethod(PILFunc):

    def __init__(self, method, *args, **vargs):
        BaseAction.__init__(self, method, *args,
                            name=method, docstr='', **vargs)
        self.method_name = method

    def action(self):
        """Called when the user selects the action in the GUI's menu."""
        image = self.viewer.get_image()
        self.function = getattr(image, self.method_name)
        self.__doc__ = self.function.__doc__
        PILFunc.action(self)


class PILDraw(PILMethod):

    def action(self):
        """Called when the user selects the action in the GUI's menu."""
        image = self.viewer.get_image()
        self.draw = ImageDraw.Draw(image)
        self.function = getattr(self.draw, self.method_name)
        self.__doc__ = self.function.__doc__
        PILFunc.action(self)


class PILFilter(BaseAction):

    def __init__(self, filter_, *args, **vargs):
        BaseAction.__init__(self, filter_, *args, name=filter_.name, **vargs)

    def action(self):
        """Called when the user selects the action in the GUI's menu."""
        self.prepare()
        if not self.require_dialog:
            filter_ = self.function()
        else:
            dialog = DialogFactory(self.viewer, self)
            if dialog.result is None:
                return  # Dialog cancelled, abort action
            values, kw = dialog.result
            filter_ = self.function(*values, **kw)

        try:
            output = self.viewer.get_image().filter(filter_)
            self.viewer.update_image(output, new=self.new)
        except Exception as e:
            _handle_exception(e, self.viewer)


class Dialog(tk.Toplevel):
    """A dialog support class.

    Source: http://effbot.org/tkinterbook/tkinter-dialog-windows.htm
    Copyright: 1995-2010 by Fredrik Lundh
    """

    def __init__(self, parent, title=None):
        tk.Toplevel.__init__(self, parent)
        self.transient(parent)

        if title:
            self.title(title)

        self.parent = parent
        self.result = None

        body = ttk.Frame(self)
        self.initial_focus = self.body(body)
        body.pack(padx=5, pady=5)

        self.buttonbox()
        self.grab_set()

        if not self.initial_focus:
            self.initial_focus = self

        self.protocol("WM_DELETE_WINDOW", self.cancel)

        self.geometry("+%d+%d" % (parent.winfo_rootx() + 50,
                                  parent.winfo_rooty() + 50))
        self.initial_focus.focus_set()
        self.wait_window(self)

    #
    # construction hooks
    def body(self, master):
        # create dialog body.  return widget that should have
        # initial focus.  this method should be overridden
        pass

    def buttonbox(self):
        # add standard button box. override if you don't want the
        # standard buttons
        box = ttk.Frame(self)

        w = ttk.Button(box, text="OK", width=10,
                       command=self.ok, default="active")
        w.pack(side="left", padx=5, pady=5)
        w = ttk.Button(box, text="Cancel", width=10, command=self.cancel)
        w.pack(side="left", padx=5, pady=5)

        self.bind("<Return>", self.ok)
        self.bind("<Escape>", self.cancel)

        box.pack()

    #
    # standard button semantics
    def ok(self, event=None):
        if not self.validate():
            self.initial_focus.focus_set()  # put focus back
            return

        self.withdraw()
        self.update_idletasks()
        self.apply()
        self.cancel()

    def cancel(self, event=None):
        # put focus back to the parent window
        self.parent.focus_set()
        self.destroy()

    #
    # command hooks
    def validate(self):
        return 1  # override

    def apply(self):
        pass  # override


class DialogFactory(Dialog):
    """Create dialogs for requesting input from user to execute an action."""

    def __init__(self, viewer, action):
        self.viewer = viewer
        self.action = action
        self.invalid_label = None
        Dialog.__init__(self, viewer, title=action.name)

    def body(self, master):
        """Adds documentation, labels and input for required user input."""
        # Documentation
        row = 0
        if not self.action.documentation and self.action.__doc__:
            self.action.documentation = inspect.cleandoc(self.action.__doc__)
        if self.action.documentation:
            txt = self.action.documentation
            tmp = ttk.Label(master, text=txt, wraplength=500,
                            padding=(2, 2, 2, 4))
            tmp.grid(columnspan=3)
            row += 1

        # Inputs
        for arg in self.action.args:
            if not arg.require_input:
                continue
            arg.label_w = ttk.Label(master, text='%s:' % arg.label, padding=2)
            arg.label_w.grid(row=row, column=0, sticky='e')
            tmp = arg.get_entry(master, self.viewer)
            padx = 1
            if isinstance(tmp, ttk.Frame):
                padx = 0
            tmp.grid(row=row, column=1, sticky='w', padx=padx)
            if arg.docs:
                tmp = ttk.Label(master, text=' '.join(arg.docs),
                                wraplength=350, padding=2)
                tmp.grid(row=row, column=2, sticky='w')
            row += 1

        # Frame for providing extra info later
        self.extra_info = ttk.Frame(master, padding=2)
        self.extra_info.grid(columnspan=3)

    def validate(self):
        """Check that neceserly arguments are valid.

        Checks that all arguments which aren't optional are provided,
        and that the provided arguments are valid.
        """
        values = []
        kw = {}
        invalids = []
        for arg in self.action.args:
            if arg.value is not None:
                valid, value = True, arg.value
            else:
                valid, value = arg.verify()

            # Show visually which arg is invalid
            if arg.require_input:
                if valid:
                    arg.label_w.configure(foreground='black')
                else:
                    arg.label_w.configure(foreground='red')
                    invalids.append(arg)
                    continue

            if not arg.optional:
                values.append(value)
            else:
                if value is not None:  # Supress optional None values
                    kw[arg.name] = value

        # Show which labels are not valid
        if invalids:
            if self.invalid_label is not None:
                self.invalid_label.pack_forget()
            text = 'Invalid input for: %s' % (
                    ', '.join([a.label for a in invalids]))
            self.invalid_label = ttk.Label(self.extra_info,
                                           text=text, foreground='red')
            self.invalid_label.pack()
            return False

        self.result = values, kw
        return True


class AutoScrollbar(ttk.Scrollbar):
    """A scrollbar that hides itself if it's not needed.

    Only works if you use the grid geometry manager.
    Source: http://effbot.org/zone/tkinter-autoscrollbar.htm
    Copyright: 1995-2010 by Fredrik Lundh
    """

    def set(self, lo, hi):
        if float(lo) <= 0.0 and float(hi) >= 1.0:
            self.grid_remove()
        else:
            self.grid()
        ttk.Scrollbar.set(self, lo, hi)

    def pack(self, **kw):
        raise tk.TclError, "cannot use pack with this widget"

    def place(self, **kw):
        raise tk.TclError, "cannot use place with this widget"


class DownloadDialog(Dialog):
    """Dialog for accepting an url to an image to download."""

    def body(self, master):
        ttk.Label(master, text='Enter URL to download image from').grid()
        self.e = ttk.Entry(master, width='54')
        self.e.insert(0, 'http://www.')
        self.e.grid(row=1)
        return self.e

    def apply(self):
        self.result = self.e.get()


class ImgInfoDialog(Dialog):
    """DIalog for showing basic information for an image."""

    def __init__(self, viewer):
        self._viewer = viewer
        Dialog.__init__(self, viewer, 'Image information')

    def body(self, master):
        img = self._viewer.get_image()
        data = ('Size: %i x %i' % img.size,
                'Mode: %s' % img.mode,
                'Format: %s' % img.format,
                'Color bands: %s' % str(img.getbands()),
                'Color extrema: %s' % str(img.getextrema()),
                'Bounding box: %i %i %i %i' % img.getbbox(),
                'Info: %s' % str(img.info))

        for txt in data:
            ttk.Label(master, text=txt).pack()


class ImgStatsDialog(Dialog):
    """Dialog for showing different statistics for an image."""

    def __init__(self, viewer):
        self._viewer = viewer
        Dialog.__init__(self, viewer, 'Image statistics')

    def body(self, master):
        def to_str(stats):
            return ', '.join(map(str, stats))
        stat = self._viewer.get_image_stats()
        data = ('Min & max: %s', stat.extrema, 'Count: %s', stat.count,
                'Median: %s', stat.median, 'Mean: %s', stat.mean,
                'Root-mean-square: %s', stat.rms, 'Variance: %s', stat.var,
                'Standard deviation: %s', stat.stddev, 'Sum: %s', stat.sum,
                'Square sum: %s', stat.sum2)
        for i in range(len(data)):
            if i % 2 == 0:
                ttk.Label(master, text=data[i] % to_str(data[i + 1])).pack()


class ImgEnhanceDialog(Dialog):
    """Dialog for enhancing aspects of an image.

    For example color and contrast etc.
    """

    def __init__(self, viewer):
        self.viewer = viewer
        self.image = viewer.get_image()
        self.enhancers = {
            'Color': ImageEnhance.Color, 'Contrast': ImageEnhance.Contrast,
            'Brightness': ImageEnhance.Brightness,
            'Sharpness': ImageEnhance.Sharpness
        }
        Dialog.__init__(self, viewer, 'Image enhancer')

    def body(self, master):
        def create_scale(text, lo, hi):
            var = tk.StringVar()
            frame = ttk.LabelFrame(master, text=text)
            label = ttk.Label(frame, textvariable=var, padding=3)
            scale = ttk.Scale(frame, orient='horizontal',
                    from_=lo, to=hi, length=200,
                    command=lambda value: self.update(var, value, text))
            scale.set(1.0)
            label.pack(side='left')
            scale.pack(side='left')
            frame.pack()
            return var

        self.color = create_scale('Color', 0.0, 4.0)
        self.contrast = create_scale('Contrast', -2.0, 3.0)
        self.brightness = create_scale('Brightness', 0.0, 4.0)
        self.sharpness = create_scale('Sharpness', -2.0, 3.0)

    def update(self, var, value, key):
        value = float(value)
        var.set('%+.2f' % value)
        enhancer = self.enhancers[key](self.image)
        self.viewer.update_image(enhancer.enhance(value))

    def apply(self):
        self.result = True


def show(images=None):
    """Factory method for creating an image viewer.

    Accepts a list of images or image-adresses to open.
    Improves responsiveness of viewer startup by delaying
    menu creation, image loading and preparing documentation.
    """
    viewer = ImageViewer(delay=True)

    def init():
        viewer.build_menu()  # Creates the viewers menu
        for img in (images or []):
            if Image.isImageType(img):
                viewer.view(img)
            else:
                viewer.open(img)

        # Generates documentation for dialogs
        viewer.after(500, viewer.prepare_docs)

    # Delay tasks which slows the loading of the viewer.
    viewer.after(500, init)
    viewer.mainloop()  # TODO: return the viewer, but mainloop??..


if __name__ == '__main__':
    show(sys.argv[1:])