Source

yomogi / yomogi / terminal.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
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
#
# Copyright (c) 2008 NAKAMURA Yoshitaka <arumakanoy@gmail.com>
# 
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
# 
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#

import vte
import gtk
import gobject
import pango
import os
import re
import itertools
import difflib
import unicodedata
import urllib


synced_terminal = []

color_palette = {
    'Tango': (
        (0x2e2e, 0x3434, 0x3636),
        (0xcccc, 0x0000, 0x0000),
        (0x4e4e, 0x9a9a, 0x0606),
        (0xc4c4, 0xa0a0, 0x0000),
        (0x3434, 0x6565, 0xa4a4),
        (0x7575, 0x5050, 0x7b7b),
        (0x0606, 0x9820, 0x9a9a),
        (0xd3d3, 0xd7d7, 0xcfcf),
        (0x5555, 0x5757, 0x5353),
        (0xefef, 0x2929, 0x2929),
        (0x8a8a, 0xe2e2, 0x3434),
        (0xfcfc, 0xe9e9, 0x4f4f),
        (0x7272, 0x9f9f, 0xcfcf),
        (0xadad, 0x7f7f, 0xa8a8),
        (0x3434, 0xe2e2, 0xe2e2),
        (0xeeee, 0xeeee, 0xecec)
    ),
    'Linux Console': (
        (0x0000, 0x0000, 0x0000),
        (0xaaaa, 0x0000, 0x0000),
        (0x0000, 0xaaaa, 0x0000),
        (0xaaaa, 0x5555, 0x0000),
        (0x0000, 0x0000, 0xaaaa),
        (0xaaaa, 0x0000, 0xaaaa),
        (0x0000, 0xaaaa, 0xaaaa),
        (0xaaaa, 0xaaaa, 0xaaaa),
        (0x5555, 0x5555, 0x5555),
        (0xffff, 0x5555, 0x5555),
        (0x5555, 0xffff, 0x5555),
        (0xffff, 0xffff, 0x5555),
        (0x5555, 0x5555, 0xffff),
        (0xffff, 0x5555, 0xffff),
        (0x5555, 0xffff, 0xffff),
        (0xffff, 0xffff, 0xffff)
    ),

    'XTerm': (
        (0x0000, 0x0000, 0x0000),
        (0xcdcb, 0x0000, 0x0000),
        (0x0000, 0xcdcb, 0x0000),
        (0xcdcb, 0xcdcb, 0x0000),
        (0x1e1a, 0x908f, 0xffff),
        (0xcdcb, 0x0000, 0xcdcb),
        (0x0000, 0xcdcb, 0xcdcb),
        (0xe5e2, 0xe5e2, 0xe5e2),
        (0x4ccc, 0x4ccc, 0x4ccc),
        (0xffff, 0x0000, 0x0000),
        (0x0000, 0xffff, 0x0000),
        (0xffff, 0xffff, 0x0000),
        (0x4645, 0x8281, 0xb4ae),
        (0xffff, 0x0000, 0xffff),
        (0x0000, 0xffff, 0xffff),
        (0xffff, 0xffff, 0xffff)
    ),

    'Rxvt': (
        (0x0000, 0x0000, 0x0000),
        (0xcdcd, 0x0000, 0x0000),
        (0x0000, 0xcdcd, 0x0000),
        (0xcdcd, 0xcdcd, 0x0000),
        (0x0000, 0x0000, 0xcdcd),
        (0xcdcd, 0x0000, 0xcdcd),
        (0x0000, 0xcdcd, 0xcdcd),
        (0xfafa, 0xebeb, 0xd7d7),
        (0x4040, 0x4040, 0x4040),
        (0xffff, 0x0000, 0x0000),
        (0x0000, 0xffff, 0x0000),
        (0xffff, 0xffff, 0x0000),
        (0x0000, 0x0000, 0xffff),
        (0xffff, 0x0000, 0xffff),
        (0x0000, 0xffff, 0xffff),
        (0xffff, 0xffff, 0xffff)
    )
}

TARGET_URI_LIST = 0
TARGET_UTF8_STRING = 1
TARGET_TEXT = 2
TARGET_COMPOUND_TEXT = 3
TARGET_STRING = 4
TARGET_COLOR = 5
TARGET_BGIMAGE = 6
TARGET_RESET_BG = 7
TARGET_TEXT_PLAIN = 8
TARGET_MOZ_URL = 9

target = [
    #("application/x-color", 0, TARGET_COLOR),
    #("property/bgimage", 0, TARGET_BGIMAGE),
    #("x-special/gnome-reset-background", 0, TARGET_RESET_BG),
    ("text/uri-list", 0, TARGET_URI_LIST),
    ("text/x-moz-url", 0, TARGET_MOZ_URL),
    ("UTF8_STRING", 0, TARGET_UTF8_STRING),
    ("COMPOUND_TEXT", 0, TARGET_COMPOUND_TEXT),
    ("TEXT", 0, TARGET_TEXT),
    ("STRING", 0, TARGET_STRING),
    ("text/plain", 0, TARGET_TEXT_PLAIN)
]

USERCHARS = "-A-Za-z0-9"
PASSCHARS = "-A-Za-z0-9,?;.:/!%$^*&~\"#'"
HOSTCHARS = "-A-Za-z0-9"
PATHCHARS = "-A-Za-z0-9_$.+!*(),;:@&=?/~#%"
SCHEME    = "(?:file:/|https?:|ftps?:)"
USER      = "[" + USERCHARS + "]+(?::[" + PASSCHARS + "]+)?"
URLPATH   = "/[" + PATHCHARS + "]*[^]'.}>) \t\r\n,\\\"]"

url_re_str = SCHEME + "//(?:" + USER + "@)?[" + HOSTCHARS + ".]+" \
             "(?::[0-9]+)?(?:" + URLPATH + ")?/?"

www_ftp_re_str = "(?:www|ftp)[" + HOSTCHARS + "]*\\.[" + HOSTCHARS + ".]" \
                 "+(?::[0-9]+)?(?:" + URLPATH + ")?/?"

url_re = re.compile('(' + '|'.join((url_re_str, www_ftp_re_str)) + ')')

class VirtualTerminal(gtk.HBox):
    default_encoding = 'UTF-8'
    #default_encoding = 'EUC-JP'
    encoding_list = ['UTF-8', 'EUC-JP', 'CP932']
    font = 'M+1M+IPAG 11'
    opacity = 0.7
    fg_color = '#ffffff'
    bg_color = '#000000'
    hi_color = '#ff8888'
    palette ='Tango'
    word_chars = '-A-Za-z0-9,./?%&#:_'
    browser = 'firefox %s'
    show_scrollbar = True
    cursor_blinks = False
    command = None
    term_name = 'xterm'
    working_directory = ''
    scrollback_lines = 100

    def __init__(self, command=None, config=None):
        gtk.HBox.__init__(self)

        if config is not None:
            for k, v in config.iteritems():
                if hasattr(self, k):
                    setattr(self, k, v)

        self._highlight_pos_list = []

        fg_color = gtk.gdk.color_parse(self.fg_color)
        self._fg_color = (fg_color.red, fg_color.green, fg_color.blue)
        bg_color = gtk.gdk.color_parse(self.bg_color)
        self._bg_color = (bg_color.red, bg_color.green, bg_color.blue)
        self._palette = color_palette[self.palette]

        c = gtk.gdk.color_parse(self.hi_color)
        self._hi_color = (c.red_float, c.green_float, c.blue_float, 0.3)

        self.reverse_video = False

        if command is None:
            command = self.command

        self._terminal = vte.Terminal()
        self.pack_start(self._terminal, True, True, 0)

        self._scrollbar = None
        if self.show_scrollbar:
            self.add_scrollbar()

        self.connect('destroy', self.do_destroy)

        self._terminal.set_cursor_blinks(self.cursor_blinks)

        self._terminal.set_scrollback_lines(self.scrollback_lines)

        self._terminal.set_size_request(50, 50)

        self._terminal.connect('button-press-event', self.do_button_press)
        self._terminal.connect('key-press-event', self.do_key_press)

        self._terminal.connect('focus-in-event', self.do_focus_in)
        #self._terminal.connect('focus-out-event', self.do_focus_out)

        self._terminal.connect_after('expose-event', self.do_expose)

        self._terminal.drag_dest_set(gtk.DEST_DEFAULT_ALL, target,
                           gtk.gdk.ACTION_COPY|gtk.gdk.ACTION_MOVE)
        self._terminal.connect('drag-data-received',
                               self.do_drag_data_received)

        self._terminal.set_background_transparent(False)
        self.set_term_opacity(self.opacity)

        self.set_term_colors(self._fg_color, self._bg_color, self._palette)

        self._terminal.set_mouse_autohide(True)
        self._terminal.set_font_from_string(self.font)
        self._terminal.set_encoding(self.default_encoding)

        #self._terminal.set_emulation('xterm')
        self._terminal.set_backspace_binding(1) # ascii backspace
        #self._terminal.set_backspace_binding(2) # ascii delete
        #self._terminal.set_backspace_binding(3) # delete-sequence
        self._terminal.match_add(url_re_str.replace('(?:', '('))
        self._terminal.match_add(www_ftp_re_str.replace('(?:', '('))

        self._terminal.set_word_chars(self.word_chars)

        self.run_command(command)

    def add_scrollbar(self):
        if self._scrollbar is None:
            self._scrollbar = gtk.VScrollbar()
            self._scrollbar.set_adjustment(self._terminal.get_adjustment())
            self.pack_end(self._scrollbar, False, False, 0)

    def remove_scrollbar(self):
        if self._scrollbar is not None:
            self.remove(self._scrollbar)
            self._scrollbar.destroy()
            self._scrollbar = None

    def set_term_opacity(self, opacity):
        opacity = int(0xffff * opacity)
        self._terminal.set_opacity(opacity)

    def set_term_colors(self, fg_color, bg_color, palette):
        fg_color = gtk.gdk.Color(*fg_color)
        bg_color = gtk.gdk.Color(*bg_color)
        palette = [gtk.gdk.Color(*c) for c in palette]

        self._terminal.set_colors(fg_color, bg_color, palette)
        self._terminal.set_color_bold(fg_color)

    def run_command(self, command=None):
        env = os.environ.copy()
        env['TERM'] = self.term_name
        envv = ['%s=%s' % kv for kv in env.iteritems()]
        working_directory = os.path.expanduser(self.working_directory)

        if command is None:
            self._terminal.fork_command(envv=envv, directory=working_directory)
        else:
            if isinstance(command, (tuple, list)):
                argv = command
            else:
                argv = command.split()

            self._terminal.fork_command(argv[0], argv, envv, working_directory)

    def do_destroy(self, x):
        # XXX: to terminate child process
        self._terminal = None
        return False

    def do_button_press(self, terminal, event):
        self.grab_focus()
        if event.button == 1 and event.state & gtk.gdk.CONTROL_MASK:
            url = self.get_match_url(event)
            if url is not None:
                self.open_url(url)
                return True
            else:
                return False
        elif event.button == 3:
            self.do_popup(event)
            return True
        else:
            return False

    def do_key_press(self, terminal, event):
        keyname = gtk.gdk.keyval_name(event.keyval)

        if event.state == gtk.gdk.CONTROL_MASK|gtk.gdk.MOD1_MASK:
            # Ctrl + Alt + ...
            if keyname == 'm':
                self.do_popup(event)
                return True

            elif keyname == 'n':
                self.complete_word()
                return True

        if gtk.gdk.keyval_name(event.keyval) == 'Menu':
            self.do_popup(event)

        return False

    def do_drag_data_received(self, w, context, x, y, data, info, time):
        self.grab_focus()
        text = ''
        if info in (TARGET_STRING, TARGET_UTF8_STRING,
                    TARGET_COMPOUND_TEXT, TARGET_TEXT):
            text = data.data

        elif info == TARGET_TEXT_PLAIN and data.format == 8:
            text = data.data

        elif info == TARGET_MOZ_URL and data.format == 8:
            url = data.data.split('\n')[0]
            if url.startswith('file://'):
                url = urllib.unquote(url)
                url = url[len('file://'):]
                url = "'%s'" % url.replace("'", "'\\''")

            text = url.replace('\x00', '')

        elif info == TARGET_URI_LIST and data.format == 8:
            uri_list = []
            for uri in data.data.split('\r\n'):
                if not uri:
                    continue

                if uri.startswith('file://'):
                    uri = urllib.unquote(uri)
                    uri = uri[len('file://'):]
                    uri = "'%s'" % uri.replace("'", "'\\''")
                
                if uri:
                    uri_list.append(uri)

            text = ' '.join(uri_list)

        if text:
            self._terminal.feed_child(text)
            context.finish(True, False, time)
        else:
            context.finish(False, False, time)

    def do_focus_in(self, terminal, event):
        self.set_term_colors(self._fg_color, self._bg_color, self._palette)

    def do_focus_out(self, terminal, event):
        fg_color = [int(c * 0.8) for c in self._fg_color]
        bg_color = [int(c * 0.8) for c in self._bg_color]
        palette = [(int(c1 * 0.99), int(c2 * 0.99), int(c2 * 0.99))
                  for c1, c2, c3 in self._palette]
        self.set_term_colors(fg_color, bg_color, palette)

    def create_popup(self):
        menu = _Menu()

        copy_item = gtk.ImageMenuItem('_Copy')
        copy_icon = gtk.image_new_from_stock(gtk.STOCK_COPY,
                                             gtk.ICON_SIZE_MENU)
        copy_item.set_image(copy_icon)

        paste_item = gtk.ImageMenuItem('_Paste')
        paste_icon = gtk.image_new_from_stock(gtk.STOCK_PASTE,
                                             gtk.ICON_SIZE_MENU)
        paste_item.set_image(paste_icon)

        zoomin_item = gtk.ImageMenuItem('Zoom _In')
        zoomin_icon = gtk.image_new_from_stock(gtk.STOCK_ZOOM_IN,
                                               gtk.ICON_SIZE_MENU)
        zoomin_item.set_image(zoomin_icon)
        zoomout_item = gtk.ImageMenuItem('Zoom _Out')
        zoomout_icon = gtk.image_new_from_stock(gtk.STOCK_ZOOM_OUT,
                                               gtk.ICON_SIZE_MENU)
        zoomout_item.set_image(zoomout_icon)
        resetzoom_item = gtk.ImageMenuItem('_Reset Zoom')
        resetzoom_icon = gtk.image_new_from_stock(gtk.STOCK_ZOOM_100,
                                                  gtk.ICON_SIZE_MENU)
        resetzoom_item.set_image(resetzoom_icon)

        copyurl_item = gtk.MenuItem('Copy _URL')
        url = self.get_match_url()
        if url is not None:
            copyurl_item.connect_object('activate', self.copy_clipboard_str, url)
        else:
            copyurl_item.set_sensitive(False)

        copyurls_item = gtk.MenuItem('Copy UR_Ls')
        copyurls_submenu = _Menu()
        copyurls_item.set_submenu(copyurls_submenu)
        url_list = self.get_visible_urls()
        if url_list:
            for i, u in enumerate(url_list):
                m = gtk.MenuItem('_%d: %s' % (i, u))
                copyurls_submenu.append(m)
                m.connect_object('activate', self.copy_clipboard_str, u)
        else:
            copyurls_item.set_sensitive(False)

        reverse_item = gtk.CheckMenuItem('R_everse Video')
        if self.reverse_video:
            reverse_item.set_active(True)

        show_scrollbar_item = gtk.CheckMenuItem('Show Scroll_bar')
        if self.show_scrollbar:
            show_scrollbar_item.set_active(True)

        encoding_item = gtk.MenuItem('Character Encodin_gs')
        encoding_submenu = _Menu()
        encoding_item.set_submenu(encoding_submenu)
        group = None
        for e in self.encoding_list:
            m = gtk.RadioMenuItem(group, e)
            group = m
            encoding_submenu.add(m)

            if e == self._terminal.get_encoding():
                m.activate()

            m.connect('activate',
                      lambda *w: self._terminal.set_encoding(w[-1]), e)

        im_menu = gtk.MenuItem('Input _Methods')
        im_submenu = _Menu()
        im_menu.set_submenu(im_submenu)
        self._terminal.im_append_menuitems(im_submenu)

        clipboard = self.get_clipboard(gtk.gdk.SELECTION_CLIPBOARD)
        if not clipboard.wait_is_text_available():
            paste_item.set_sensitive(False)

        if not self._terminal.get_has_selection():
            copy_item.set_sensitive(False)

        menu.append(copy_item)
        menu.append(copyurl_item)
        menu.append(copyurls_item)
        menu.append(paste_item)
        menu.append(gtk.SeparatorMenuItem())
        menu.append(zoomin_item)
        menu.append(zoomout_item)
        menu.append(resetzoom_item)
        menu.append(gtk.SeparatorMenuItem())
        menu.append(reverse_item)
        menu.append(show_scrollbar_item)
        menu.append(encoding_item)
        menu.append(gtk.SeparatorMenuItem())
        menu.append(im_menu)

        copy_item.connect('activate', self.copy_clipboard)
        paste_item.connect('activate',
                           lambda x: self._terminal.paste_clipboard())
        zoomin_item.connect('activate', self.do_zoom_in)
        zoomout_item.connect('activate', self.do_zoom_out)
        resetzoom_item.connect('activate', self.do_reset_zoom)
        reverse_item.connect('toggled', self.do_reverse_video)
        show_scrollbar_item.connect('toggled', self.do_show_scrollbar)

        return menu

    def do_popup(self, event):
        menu = self.create_popup()

        menu.show_all()
        menu.popup(None, None, None, 3, event.time)

    def copy_clipboard(self, x):
        self._terminal.copy_clipboard()

        # XXX: workaround for sync mode copy and paste
        self.get_clipboard(gtk.gdk.SELECTION_CLIPBOARD).store()

    def copy_clipboard_str(self, string):
        c = self.get_clipboard(gtk.gdk.SELECTION_CLIPBOARD)
        c.set_text(string)
        c.store()

    def do_zoom_in(self, terminal):
        font = self._terminal.get_font()
        font.set_size(font.get_size()+pango.SCALE)
        self._terminal.set_font(font)

    def do_zoom_out(self, terminal):
        font = self._terminal.get_font()
        font.set_size(font.get_size()-pango.SCALE)
        self._terminal.set_font(font)

    def do_reset_zoom(self, terminal):
        self._terminal.set_font_from_string(self.font)

    def do_reverse_video(self, reverse_item):
        if reverse_item.get_active():
            self.reverse_video = True
            fg_color = gtk.gdk.color_parse(self.bg_color)
            bg_color = gtk.gdk.color_parse(self.fg_color)
        else:
            self.reverse_video = False
            fg_color = gtk.gdk.color_parse(self.fg_color)
            bg_color = gtk.gdk.color_parse(self.bg_color)

        self._fg_color = (fg_color.red, fg_color.green, fg_color.blue)
        self._bg_color = (bg_color.red, bg_color.green, bg_color.blue)

        # reset color
        self.do_focus_in(None, None)

    def do_show_scrollbar(self, show_scrollbar_item):
        if show_scrollbar_item.get_active():
            self.show_scrollbar = True
            self.add_scrollbar()
            self._scrollbar.show()
        else:
            self.show_scrollbar = False
            self.remove_scrollbar()

    def get_visible_urls(self):
        return url_re.findall(self._terminal.get_text(lambda *x: True))

    def get_match_url(self, event=None):
        cw = self._terminal.get_char_width()
        ch = self._terminal.get_char_height()

        try:
            x, y = int(event.x), int(event.y)
        except AttributeError:
            x, y = self.get_pointer()

        c = x / cw
        r = y / ch
        match = self._terminal.match_check(c, r)
        if match is not None:
            return match[0]
        else:
            return None

    def open_url(self, url):
        url = url.replace('\\', '\\\\')
        url = url.replace("'", "\\'")
        url = "'" + url + "'"
        cmd = self.browser % url
        cmd = cmd + ' &'
        os.system(cmd)

    def set_highlight_pos(self, position_list):
        # position_list = [(row_start, col_start, col_length), ....]
        if not self._terminal.window:
            return

        # merge overraped positions
        # [(1, 2, 4), (1, 4, 5), (1, 10, 10) ,(2, 5, 3)]
        # -> [(1, 2, 7), (1, 10, 10), (2, 5, 3)]

        class _isSequence(object):
            def __init__(self):
                self.last_value = 0
                self.return_value = 0

            def check(self, i):
                if self.last_value + 1 != i:
                    self.return_value = i

                self.last_value = i
                return self.return_value

        merged_position_list = []
        # TODO: wrap long lines
        for row_start, position_iter in itertools.groupby(sorted(position_list),
                                                          lambda x: x[0]):

            position_set = set(itertools.chain(*[xrange(start, start+length)
                                                 for _, start, length in position_iter]))

            for col_start, col_iter in itertools.groupby(position_set,
                                                         _isSequence().check):
                length = sum(1 for i in col_iter)
                merged_position_list.append((row_start, col_start, length))

        font_width = self.get_char_width()
        font_height = self.get_char_height()

        xpad, ypad = self.get_padding()

        _highlight_pos_list = []

        for row_start, col_start, col_length in merged_position_list:
            _highlight_pos_list.append((xpad / 2 + font_width * col_start,
                                        ypad / 2 + font_height * row_start,
                                        font_width * col_length,
                                        font_height))

        self._highlight_pos_list = _highlight_pos_list

        # redraw terminal
        self._terminal.queue_draw()

    def unset_highlight_position(self):
        self._highlight_pos_list = []

        # redraw terminal
        self._terminal.queue_draw()

    def do_expose(self, terminal, event):
        if not self._highlight_pos_list:
            return

        ctx = terminal.window.cairo_create()
        ctx.set_source_rgba(*self._hi_color)

        for pos in self._highlight_pos_list:
            ctx.rectangle(*pos)
            ctx.fill()

    def get_scrollbar_width(self):
        my_width = self.get_allocation().width
        term_width = self._terminal.get_allocation().width
        return my_width - term_width

    def get_char_width(self):
        return self._terminal.get_char_width()

    def get_char_height(self):
        return self._terminal.get_char_height()

    def match_check(self, *args, **kwargs):
        return self._terminal.match_check(*args, **kwargs)
    
    def grab_focus(self):
        return self._terminal.grab_focus()

    def set_size_request(self, w, h):
        return self._terminal.set_size_request(w, h)

    def is_focus(self):
        return self._terminal.is_focus()

    def get_padding(self):
        return self._terminal.get_padding()

    def get_adjustment(self):
        return self._terminal.get_adjustment()

    def get_utext(self):
        enc = self._terminal.get_encoding()
        return self._terminal.get_text(lambda *x: True).decode(enc, 'replace')

    def get_utext_as_seen(self):
        text = self.get_utext()
        col_num = self._terminal.get_column_count()

        for line in text.splitlines():
            if not line:
                yield ''
                continue

            line_width = 0
            buf = []
            for c in line.expandtabs():
                line_width += get_unicode_char_width(c)

                if line_width > col_num:
                    yield u''.join(buf)
                    buf = [c]
                    line_width = 1
                else:
                    buf.append(c)

            if buf:
                yield ''.join(buf)

    def complete_word(self):
        word = self.get_word_before_cursor()
        candidates = self.get_complete_candidates(word)
        if not candidates:
            return

        elif len(candidates) == 1:
            self._terminal.feed_child(candidates[0][len(word):])

        else:
            menu = _Menu()
            for w in candidates:
                item = gtk.MenuItem(w, use_underline=False)
                menu.append(item)
                item.connect('activate',
                             lambda *x: self._terminal.feed_child(x[-1]),
                             w[len(word):])

            menu.show_all()
            self.popup_near_cursor(menu)

    def popup_near_cursor(self, menu):
        cursor_x, cursor_y = self.get_cursor_pos_pixel()
        parent_x, parent_y = self.get_parent_window().get_position()
        x = int(parent_x + cursor_x)
        y = int(parent_y + cursor_y)

        menu.popup(None, None, lambda *_: (x, y, True), 3, 0)

        screen_height = self.get_screen().get_height()
        menu_height = menu.allocation.height

        if menu_height + y > screen_height:
            y = max(0, screen_height - menu_height)
            #menu.popdown()
            menu.popup(None, None, lambda *_: (x, y, True), 3, 0)

    def get_cursor_pos_pixel(self):
        col, row = self.get_viewed_cursor_position()

        font_width = self.get_char_width()
        font_height = self.get_char_height()

        xpad, ypad = self.get_padding()

        return (xpad / 2 + font_width * col, ypad / 2 + font_height * row)

    def get_viewed_cursor_position(self):
        col, row = self._terminal.get_cursor_position()
        top_row = self._terminal.get_adjustment().value
        return (col, row - top_row)

    def get_complete_candidates(self, word):
        candidates = set()
        for w in self.extract_words(self.get_utext()):
            if w != word and w.startswith(word):
                candidates.add(w)

        return sorted(candidates)

    def get_word_before_cursor(self):
        text = self.get_text_before_cursor()
        word = []
        for c in reversed(text):
            if not self._terminal.is_word_char(c):
                break

            word.insert(0, c)

        return ''.join(word)

    def get_text_before_cursor(self):
        col, row = self._terminal.get_cursor_position()
        return self._terminal.get_text_range(row, 0, row, col, lambda *x: True)[:col]

    def extract_words(self, text):
        word = []
        for c in text:
            if self._terminal.is_word_char(c):
                word.append(c)

            elif word:
                yield ''.join(word)
                word = []


def get_unicode_char_width(c):
    eaw = unicodedata.east_asian_width(c)
    if eaw in ['F', 'W']:
        char_width = 2
    elif eaw == 'A':
        if os.environ.get('VTE_CJK_WIDTH', '').lower() == 'wide':
            char_width = 2
        elif os.environ.get('VTE_CJK_WIDTH', '').lower() == 'narrow':
            char_width = 1
        else:
            lang = os.environ.get('LC_ALL', '') or \
                   os.environ.get('LC_CTYPE', '') or \
                   os.environ.get('LANG', '')
            if lang[:2].lower() in ('ja', 'ko', 'vi', 'zh'):
                char_width = 2
            else:
                char_width = 1
    else:
        char_width = 1

    return char_width


class _Menu(gtk.Menu):
    '''gtk.Menu with additional key bindings
    '''
    def __init__(self, *args, **kwargs):
        super(_Menu, self).__init__(*args, **kwargs)

        self.connect('key-press-event', self.do_key_press)

    def do_key_press(self, menu, event):
        keyname = gtk.gdk.keyval_name(event.keyval)

        if event.state == gtk.gdk.CONTROL_MASK:
            if keyname in ('m', 'y'):
                # emulate retuen key press
                e = gtk.gdk.Event(gtk.gdk.KEY_PRESS)
                e.state = 0
                e.keyval = gtk.keysyms.Return
                keymap = gtk.gdk.keymap_get_default()
                e.hardware_keycode = keymap.get_entries_for_keyval(gtk.keysyms.Return)[0][0]
                e.window = event.window
                e.time = 0
                self.emit('key-press-event', e)
                return True

            elif keyname in ('e', 'g'):
                self.popdown()
                return True


class MainWindow(gtk.Window):
    title= 'Yomogi'

    highlight_diff = False
    sync_scroll = False

    window_icon_name = 'utilities-terminal'

    default_terminal_size = (80, 24)
    terminal_size_list = [(80, 24), (80, 43), (132, 24), (132, 43)]

    def __init__(self, opts):
        gtk.Window.__init__(self)

        self.opts = opts

        if 'title' in opts:
            self.title = opts['title']

        self.set_default_size(400, 300)
        self.set_title(self.title)

        icon_theme = gtk.icon_theme_get_default()
        icons = [icon_theme.load_icon(self.window_icon_name, size, 0)
                 for size in icon_theme.get_icon_sizes(self.window_icon_name)
                 if size > 0]
        if icons:
            self.set_icon_list(*icons)

        self.connect('destroy', self.close_window)

        self.is_fullscreen = False
        self._timer_id = None
        self._diff_timer_id = None

        config = {}
        config_file = os.path.expanduser('~/.yomogirc')
        if os.path.exists(config_file):
            execfile(config_file, config)
        self.config = config

        self.config.update(self.opts)

        if self.config.get('use_alpha', True):
            self.initialize_alpha()

        if 'default_terminal_size' in self.config:
            self.default_terminal_size = self.config['default_terminal_size']

        if 'terminal_size_list' in self.config:
            self.terminal_size_list = self.config['terminal_size_list']

        terminal = self.create_terminal()
        self.add(terminal)

        def_x, def_y = self.default_terminal_size
        xpad, ypad = terminal.get_padding()

        w = terminal.get_char_width() * def_x + xpad
        h = terminal.get_char_height() * def_y + ypad
        terminal.set_size_request(w, h)

        self.show_all()

        # Revert size_request
        terminal.set_size_request(50, 50)

    def initialize_alpha(self):
        screen = self.get_screen()
        colormap = screen.get_rgba_colormap()
        if colormap and screen.is_composited():
            self.set_colormap(colormap)

    def create_terminal(self):
        terminal = VirtualTerminal(config=self.config)

        terminal._terminal.disconnect_by_func(terminal.do_button_press)
        terminal._terminal.disconnect_by_func(terminal.do_key_press)

        terminal.connect('destroy', self.do_term_destroy)
        terminal._terminal.connect_object('button-press-event',
                                          self.do_term_button_press, terminal)
        terminal._terminal.connect_object('key-press-event',
                                          self.do_term_key_press, terminal)
        terminal._terminal.connect_object('commit',
                                          self.do_term_commit, terminal)
        terminal._terminal.connect_object('child-exited',
                                          self.close_frame, terminal)
        terminal._terminal.connect_object('focus-in-event',
                                          self.do_term_focus_in, terminal)
        terminal._terminal.connect_object('contents-changed',
                                          self.do_term_contents_changed,
                                          terminal)
        terminal._terminal.connect('window-title-changed',
                                   self.do_term_title_changed)
        terminal._terminal.connect('char-size-changed',
                                   self.do_term_title_changed)
        terminal.connect('size-allocate', self.do_term_size_allocate)
        adjustment = terminal.get_adjustment()
        adjustment.connect_object('value-changed',
                                  self.do_term_adjustment_value_changed,
                                  terminal)

        return terminal

    @property
    def terminal_list(self):
        return [t for t in get_all_children(self)
                if isinstance(t, VirtualTerminal)]

    def do_term_destroy(self, terminal):
        if terminal in synced_terminal:
            synced_terminal.remove(terminal)

        return False

    def do_term_button_press(self, terminal, event):
        terminal.grab_focus()
        if event.button == 1 and event.state & gtk.gdk.CONTROL_MASK:
            url = terminal.get_match_url(event)
            if url is not None:
                terminal.open_url(url)
                return True
            else:
                return False
        elif event.button == 3:
            self.do_term_popup(terminal, event)
            return True
        else:
            return False

    def do_term_key_press(self, terminal, event):
        keyname = gtk.gdk.keyval_name(event.keyval)

        if event.state == gtk.gdk.MOD1_MASK:
            # Alt + ...
            if keyname == 'Up':
                self.child_focus(gtk.DIR_UP)
                return True

            elif keyname == 'Down':
                self.child_focus(gtk.DIR_DOWN)
                return True

            elif keyname == 'Right':
                self.child_focus(gtk.DIR_RIGHT)
                return True

            elif keyname == 'Left':
                self.child_focus(gtk.DIR_LEFT)
                return True

        if event.state == gtk.gdk.CONTROL_MASK and 'Tab' in keyname:
            self.child_focus(gtk.DIR_TAB_FORWARD)
            return True

        if event.state == gtk.gdk.CONTROL_MASK|gtk.gdk.SHIFT_MASK \
           and 'Tab' in keyname:
            self.child_focus(gtk.DIR_TAB_BACKWARD)
            return True

        if event.state == gtk.gdk.CONTROL_MASK|gtk.gdk.MOD1_MASK:
            # Ctrl + Alt + ...
            if keyname == 'h':
                self.child_focus(gtk.DIR_LEFT)
                return True

            elif keyname == 'j':
                self.child_focus(gtk.DIR_DOWN)
                return True

            elif keyname == 'k':
                self.child_focus(gtk.DIR_UP)
                return True

            elif keyname == 'l':
                self.child_focus(gtk.DIR_RIGHT)
                return True

            elif keyname == 'm':
                self.do_term_popup(terminal, event)
                return True

            elif keyname == 'n':
                terminal.complete_word()
                return True

        if gtk.gdk.keyval_name(event.keyval) == 'Menu':
            self.do_term_popup(terminal, event)

        return False

    def do_term_commit(self, terminal, text, length):
        if terminal.is_focus() and self.is_active() \
           and terminal in synced_terminal:
            for t in synced_terminal:
                if t is not terminal:
                    t._terminal.feed_child(text)

    def do_term_focus_in(self, terminal, event):
        for t in self.terminal_list:
            if t is not terminal:
                if terminal in synced_terminal and t in synced_terminal:
                    t.do_focus_in(None, None)
                else:
                    t.do_focus_out(None, None)

        self.do_term_title_changed(terminal._terminal)


    def do_term_title_changed(self, _terminal, *args):
        title = _terminal.get_window_title()

        col = _terminal.get_column_count()
        row = _terminal.get_row_count()

        if title:
            self.set_title('%s - %s - %dx%d' % (self.title, title, col, row))
        else:
            self.set_title('%s - %dx%d' % (self.title, col, row))

    def do_term_size_allocate(self, terminal, rect):
        if not terminal.is_focus():
            return

        if self._timer_id is not None:
            gobject.source_remove(self._timer_id)
            self._timer_id = None

        self._timer_id = gobject.timeout_add(100, self.do_timeout, terminal)

    def do_timeout(self, terminal):
        self.do_term_title_changed(terminal._terminal)
        gobject.source_remove(self._timer_id)
        self._timer_id = None

    def create_term_popup(self, terminal):
        menu = terminal.create_popup()

        open_term_item = gtk.MenuItem('Open _Terminal')
        fullscreen_item = gtk.CheckMenuItem('_Full Screen')
        if self.is_fullscreen:
            fullscreen_item.set_active(True)

        resize_terminal_item = gtk.MenuItem('Resi_ze Terminal')
        resize_terminal_submenu = _Menu()
        resize_terminal_item.set_submenu(resize_terminal_submenu)
        for i, (x, y) in enumerate(self.terminal_size_list):
            m = gtk.MenuItem('_%d: %dx%d' % (i, x, y))
            resize_terminal_submenu.append(m)
            m.connect('activate', self.resize_terminal, terminal, x, y)

        split_vert_item = gtk.MenuItem('Split Frame _Vertically')
        split_horiz_item = gtk.MenuItem('Split Frame _Horizontally')
        close_frame_item = gtk.MenuItem('Close Frame')
        close_other_item = gtk.MenuItem('Close Other Frame')
        if len(self.terminal_list) <= 1:
            close_other_item.set_sensitive(False)

        sync_frame_item = gtk.CheckMenuItem('_Sync this frame')
        if terminal in synced_terminal:
            sync_frame_item.set_active(True)

        sync_all_item = gtk.MenuItem('S_ync All Frames in This Window')
        async_all_item = gtk.MenuItem('_Async All Frames in This Window')

        sync_scroll_item = gtk.CheckMenuItem('Sy_nc Scroll')
        if MainWindow.sync_scroll:
            sync_scroll_item.set_active(True)

        highlight_diff_item = gtk.CheckMenuItem('Highlight _Diffs in the Synced Frames')
        if MainWindow.highlight_diff:
            highlight_diff_item.set_active(True)

        menu.prepend(gtk.SeparatorMenuItem())
        menu.prepend(highlight_diff_item)
        menu.prepend(sync_scroll_item)
        menu.prepend(async_all_item)
        menu.prepend(sync_all_item)
        menu.prepend(sync_frame_item)
        menu.prepend(gtk.SeparatorMenuItem())
        menu.prepend(close_other_item)
        menu.prepend(close_frame_item)
        menu.prepend(split_horiz_item)
        menu.prepend(split_vert_item)
        menu.prepend(gtk.SeparatorMenuItem())
        menu.prepend(resize_terminal_item)
        menu.prepend(fullscreen_item)
        menu.prepend(open_term_item)

        open_term_item.connect('activate', lambda x: MainWindow(self.opts))
        fullscreen_item.connect('toggled', self.toggle_fullscreen)
        split_vert_item.connect('activate',
                lambda x: self.split_frame_vertically(terminal))
        split_horiz_item.connect('activate',
                lambda x: self.split_frame_horizontally(terminal))
        close_frame_item.connect('activate',
                lambda x: self.close_frame(terminal))
        close_other_item.connect('activate',
                lambda x: self.close_other_frame(terminal))
        sync_frame_item.connect('toggled', self.toggle_term_sync, terminal)
        sync_scroll_item.connect('toggle', self.toggle_sync_scroll)
        highlight_diff_item.connect('toggled', self.toggle_highlight_diff, terminal)
        sync_all_item.connect('activate', self.sync_term_all)
        async_all_item.connect('activate', self.async_term_all)

        return menu

    def toggle_fullscreen(self, fullscreen_item):
        if fullscreen_item.get_active():
            self.fullscreen()
            self.is_fullscreen = True
        else:
            self.unfullscreen()
            self.is_fullscreen = False

    def resize_terminal(self, item, terminal, x, y):
        xpad, ypad = terminal.get_padding()
        w = terminal.get_char_width() * x + xpad
        h = terminal.get_char_height() * y + ypad
        s_witdh = terminal.get_scrollbar_width()
        self.resize(w + s_witdh, h)

    def toggle_term_sync(self, sync_frame_item, terminal):
        if sync_frame_item.get_active():
            synced_terminal.append(terminal)

            if MainWindow.highlight_diff:
                # Diff
                self._calculate_diff(terminal)

        else:
            synced_terminal.remove(terminal)

            terminal.unset_highlight_position()

        # reset dim
        terminal.do_focus_in(None, None)

    def toggle_sync_scroll(self, sync_scroll_item):
        MainWindow.sync_scroll = sync_scroll_item.get_active()

    def toggle_highlight_diff(self, highlight_diff_item, terminal):
        MainWindow.highlight_diff = highlight_diff_item.get_active()

        if MainWindow.highlight_diff:
            if terminal in synced_terminal:
                self._calculate_diff(terminal)

        else:
            for term in synced_terminal:
                term.unset_highlight_position()

    def sync_term_all(self, x):
        self._sync_term_all(self)

    def _sync_term_all(self, parent):
        focused_term = None

        for c in parent.get_children():
            if isinstance(c, VirtualTerminal) and c not in synced_terminal:
                synced_terminal.append(c)

                if c.is_focus():
                    focused_term = c

            elif isinstance(c, (gtk.VPaned, gtk.HPaned)):
                self._sync_term_all(c)

        if MainWindow.highlight_diff and focused_term is not None:
            self._calculate_diff(focused_term)

    def async_term_all(self, x):
        self._async_term_all(self)

    def _async_term_all(self, parent):
        for c in parent.get_children():
            if isinstance(c, VirtualTerminal) and c in synced_terminal:
                synced_terminal.remove(c)

                c.unset_highlight_position()

            elif isinstance(c, (gtk.VPaned, gtk.HPaned)):
                self._async_term_all(c)

    def do_term_popup(self, terminal, event):
        menu = self.create_term_popup(terminal)

        menu.show_all()
        menu.popup(None, None, None, 3, event.time)

    def split_frame_vertically(self, terminal):
        self._split_frame(terminal, gtk.HPaned, 'width')

    def split_frame_horizontally(self, terminal):
        self._split_frame(terminal, gtk.VPaned, 'height')

    def _split_frame(self, terminal, paned_class, attr):
        parent = terminal.get_parent()
        parent.remove(terminal)

        paned = paned_class()

        if isinstance(parent, MainWindow):
            parent.add(paned)
        elif parent.get_child1():
            parent.pack2(paned, False, False)
        else:
            parent.pack1(paned, False, False)

        paned.pack1(terminal, False, False)

        new_terminal = self.create_terminal()
        paned.pack2(new_terminal, False, False)

        alloc = parent.get_allocation()
        pos = getattr(alloc, attr)
        if isinstance(parent, paned_class):
            pos = pos - parent.get_position()
        pos = pos / 2
        paned.set_position(pos)

        parent.show_all()
        new_terminal.grab_focus()

    def close_frame(self, terminal):
        parent = terminal.get_parent()

        if parent is self:
            return self.destroy()

        grand_parent = parent.get_parent()
        grand_parent.remove(parent)

        for c in parent.get_children():
            parent.remove(c)
            if c is not terminal:
                if isinstance(grand_parent, MainWindow):
                    grand_parent.add(c)
                elif grand_parent.get_child1():
                    grand_parent.pack2(c, False, False)
                else:
                    grand_parent.pack1(c, False, False)

                # Find next terminal
                while not isinstance(c, VirtualTerminal):
                    c = c.get_child1()
                c.grab_focus()

        terminal.destroy()
        parent.destroy()

    def close_other_frame(self, terminal):
        for t in self.terminal_list:
            if t is not terminal:
                self.close_frame(t)

    def close_window(self, *args):
        main_window_list = [w for w in gtk.window_list_toplevels()
                              if isinstance(w, MainWindow)]
        if len(main_window_list) <= 1:
            gtk.main_quit()
        else:
            for t in self.terminal_list:
                t.destroy()

            return False

    def do_term_adjustment_value_changed(self, terminal):
        if not MainWindow.sync_scroll or \
           not terminal.is_focus() or \
           not self.is_active() or \
           terminal not in synced_terminal:
            return

        adjustment = terminal.get_adjustment()

        value_from_bottom = adjustment.upper - (adjustment.value + adjustment.page_size)

        for t in synced_terminal:
            if t is terminal:
                continue

            adjustment = t.get_adjustment()
            value = adjustment.upper - (value_from_bottom + adjustment.page_size)
            adjustment.set_value(value)

    def do_term_contents_changed(self, terminal):
        if not MainWindow.highlight_diff or \
           terminal not in synced_terminal:
            return

        # TODO: Use active window/terminal as diff base

        if self._diff_timer_id is not None:
            gobject.source_remove(self._diff_timer_id)
            self._diff_timer_id = None

        self._diff_timer_id = gobject.timeout_add(500,
                                                  self.do_diff_timeout,
                                                  terminal)

    def do_diff_timeout(self, terminal):
        gobject.source_remove(self._diff_timer_id)
        self._diff_timer_id = None

        self._calculate_diff(terminal)

    def _calculate_diff(self, terminal):
        base_text = list(terminal.get_utext_as_seen())

        base_highlight_pos = []

        for other_terminal in synced_terminal:
            if other_terminal is terminal:
                continue

            other_text = list(other_terminal.get_utext_as_seen())

            other_highlight_pos = []

            diff = list(difflib.ndiff(other_text, base_text))

            base_row_index = 0
            other_row_index = 0

            for diff_index, d in enumerate(diff):
                if d.startswith('?'):
                    pass

                elif d.startswith(' '):
                    base_row_index += 1
                    other_row_index += 1

                else:
                    if d.startswith('+'):
                        base_row_index += 1

                        _row_index = base_row_index
                        _highlight_pos = base_highlight_pos
                        _line = base_text[base_row_index-1]

                    elif d.startswith('-'):
                        other_row_index += 1

                        _row_index = other_row_index
                        _highlight_pos = other_highlight_pos
                        _line = other_text[other_row_index-1]

                    try:
                        maybe_guide = diff[diff_index+1]
                        if maybe_guide.startswith('?'):
                            # drop first 2 chars and last newline
                            guide = maybe_guide[2:-1]

                        else:
                            guide = ''

                    except IndexError:
                        guide = ''

                    if guide:
                        for mobj in re.finditer('[^ ]+', guide):
                            m_start = mobj.start()
                            col_start = sum(map(get_unicode_char_width,
                                                _line[:m_start]))

                            col_length = sum(map(get_unicode_char_width,
                                                 _line[m_start:mobj.end()]))

                            # TODO: wrap long lines
                            _highlight_pos.append((_row_index-1, col_start, col_length))

                    else:
                            _highlight_pos.append((_row_index-1, 0, len(d)-2))

            other_terminal.set_highlight_pos(other_highlight_pos)

        terminal.set_highlight_pos(base_highlight_pos)


def get_all_children(obj):
    for c in obj.get_children():
        yield c
        if hasattr(c, 'get_children'):
            for cc in get_all_children(c):
                yield cc