This file is indexed.

/usr/lib/python3/dist-packages/Onboard/KbdWindow.py is in onboard 1.3.0-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
# -*- coding: utf-8 -*-

# Copyright © 2008 Chris Jones <tortoise@tortuga>
# Copyright © 2009-2011 Francesco Fumanti <francesco.fumanti@gmx.net>
# Copyright © 2012 Gerd Kohlberger <lowfi@chello.at>
# Copyright © 2010-2016 marmuta <marmvta@gmail.com>
#
# This file is part of Onboard.
#
# Onboard is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# Onboard is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

from __future__ import division, print_function, unicode_literals

import time

from Onboard.Version import require_gi_versions
require_gi_versions()
from gi.repository import GObject, GLib, GdkX11, Gdk, Gtk

from Onboard.definitions import DockingMonitor
from Onboard.utils       import Rect, Version
from Onboard.Timer       import CallOnce, Timer
from Onboard.WindowUtils import Orientation, WindowRectPersist, \
                                WindowRectTracker, set_unity_property, \
                                gtk_has_resize_grip_support
import Onboard.osk as osk

### Logging ###
import logging
_logger = logging.getLogger("KbdWindow")
###############

### Config Singleton ###
from Onboard.Config import Config
config = Config()
########################



class KbdWindowBase:
    """
    Very messy class holds the keyboard widget. The mess is the docked
    window support which is disable because of numerous metacity bugs.
    """
    def __init__(self, keyboard_widget, icp):
        _logger.debug("Entered in __init__")

        self._osk_util   = osk.Util()
        self._osk_struts = osk.Struts()

        self.application = None
        self.keyboard_widget = keyboard_widget
        self.icp = icp

        self.supports_alpha = False

        self._visible = False
        self._sticky = False
        self._iconified = False
        self._maximized = False

        self._screen_resizing = False

        self._docking_enabled = False
        self._docking_edge = None
        self._docking_rect = Rect()
        self._docking_monitor = None
        self._shrink_work_area = False
        self._dock_expand = False
        self._current_struts = None

        self._current_docking_monitor = None
        self._monitor_workarea = {}

        if gtk_has_resize_grip_support():
            self._default_resize_grip = self.get_has_resize_grip()
        else:
            self._default_resize_grip = False
        self._type_hint = None

        self._known_window_rects = []
        self._written_window_rects = {}
        self._written_dock_sizes = {}
        self._auto_position_started = False

        self._desktop_switch_count = 0
        self._moved_desktop_switch_count = 0

        self.set_accept_focus(False)
        self.set_app_paintable(True)
        self.set_keep_above(True)
        #Gtk.Settings.get_default().set_property("gtk-touchscreen-mode", True)

        Gtk.Window.set_default_icon_name("onboard")
        self.set_title(_("Onboard"))

        self.connect("window-state-event",      self._cb_window_state_event)
        self.connect("visibility-notify-event", self._cb_visibility_notify)
        self.connect('screen-changed',          self._cb_screen_changed)
        self.connect('composited-changed',      self._cb_composited_changed)
        self.connect("realize",                 self._cb_realize_event)
        self.connect("unrealize",               self._cb_unrealize_event)
        self.connect("configure-event",         self._on_configure_event)

        self.detect_window_manager()
        self.check_alpha_support()
        self.update_unrealize_options()

        self.add(self.keyboard_widget)

        _logger.debug("Leaving __init__")

    def cleanup(self):
        pass

    def _cb_realize_event(self, user_data):
        # Disable maximize function (LP #859288)
        # unity:    no effect, but double click on top bar unhides anyway
        # unity-2d: works and avoids the bug
        if self.get_window():
            self.get_window().set_functions(Gdk.WMFunction.RESIZE | \
                                            Gdk.WMFunction.MOVE | \
                                            Gdk.WMFunction.MINIMIZE | \
                                            Gdk.WMFunction.CLOSE)
        set_unity_property(self)

    def _cb_screen_changed(self, widget, old_screen=None):
        self.detect_window_manager()
        self.check_alpha_support()
        self.queue_draw()

    def _cb_composited_changed(self, widget):
        self.detect_window_manager()
        self.check_alpha_support()
        self.queue_draw()

    def emit_quit_onboard(self):
        self.emit("quit-onboard")

    def detect_window_manager(self):
        """
        Detect the WM and select WM specific behavior.

        Doctests:
        >>> osk_util = osk.Util()
        >>> len(osk_util.get_current_wm_name().lower()) > 0
        True
        """
        wm = config.quirks_name
        if not wm:
            # Returns None on X error BadWindow (LP: 1016980)
            # Keep the same quirks as before in that case.
            wm = self._osk_util.get_current_wm_name()

        if wm:
            config.quirks = None
            for cls in [WMQuirksCompiz, WMQuirksMetacity, WMQuirksMutter]:
                if  wm.lower() in cls.wms:
                    config.quirks = cls()
                    break

        if not config.quirks:
            config.quirks = WMQuirksDefault()

        _logger.debug("window manager: {}".format(wm))
        _logger.debug("quirks selected: {}" \
                                       .format(str(config.quirks.__class__)))
        return True

    def check_alpha_support(self):
        screen = self.get_screen()
        visual = screen.get_rgba_visual()
        self.supports_alpha = \
            visual and \
            (screen.is_composited() or \
             config.launched_by == config.LAUNCHER_UNITY_GREETER)

        self.keyboard_widget.supports_alpha = self.supports_alpha

        _logger.debug("screen changed, supports_alpha={}" \
                       .format(self.supports_alpha))

        # Unity may start onboard early, where there is no compositing
        # enabled yet. If we set the visual later the window never becomes
        # transparent -> do it as soon as there is an rgba visual.
        if visual:
            self.set_visual(visual)
            self.keyboard_widget.set_visual(visual)

            # Somehow Gtk 3.4 still needs these now deprecated calls,
            # even though IconPalette and LabelPopups don't.
            # Otherwise there will be a white background.
            gtk_version = Version(Gtk.MAJOR_VERSION, Gtk.MINOR_VERSION)
            if gtk_version < Version(3, 18):  # Xenial doesn't need them
                self.override_background_color(
                    Gtk.StateFlags.NORMAL, Gdk.RGBA(0, 0, 0, 0))
                self.keyboard_widget.override_background_color(
                    Gtk.StateFlags.NORMAL, Gdk.RGBA(0, 0, 0, 0))
        else:
            _logger.info(_("no window transparency available;"
                           " screen doesn't support alpha channels"))
        return False

    def _show_first_time(self):
        self.update_window_options()
        self.update_window_scaling_factor(True)
        self.pre_render_keys(*self.get_size())
        self.show()

    def move_resize(self, x, y, w, h):
        if not self.keyboard_widget.is_drag_initiated():
            self.pre_render_keys(w, h)
        super(KbdWindowBase, self).move_resize(x, y, w, h)

    def pre_render_keys(self, w, h):
        self.keyboard_widget.pre_render_keys(self, w, h)

    def _cb_realize_event(self, user_data):
        """ Gdk window created """
        # Disable maximize function (LP #859288)
        # unity:    no effect, but double click on top bar unhides anyway
        # unity-2d: works and avoids the bug
        self.get_window().set_functions(Gdk.WMFunction.RESIZE | \
                                        Gdk.WMFunction.MOVE | \
                                        Gdk.WMFunction.MINIMIZE | \
                                        Gdk.WMFunction.CLOSE)

        set_unity_property(self)

        if not config.xid_mode:   # not when embedding
            ord = config.is_override_redirect()
            if ord:
                self.set_override_redirect(True)

            self.update_taskbar_hint()
            self.restore_window_rect(startup = True)

        # set min window size for unity MT grab handles
        geom = Gdk.Geometry()
        geom.min_width, geom.min_height = \
                self.keyboard_widget.get_min_window_size()
        self.set_geometry_hints(self, geom, Gdk.WindowHints.MIN_SIZE)

    def _cb_unrealize_event(self, user_data):
        """ Gdk window destroyed """
        self.update_unrealize_options()

    def update_unrealize_options(self):
        if not config.xid_mode:   # not when embedding
            self.set_decorated(config.window.window_decoration)

            type_hint = config.quirks.get_window_type_hint(self)
            self.set_type_hint(type_hint)
            self._type_hint = type_hint

    def update_window_options(self, startup = False):
        if not config.xid_mode:   # not when embedding

            recreate = False

            # Window decoration toggled?
            decorated = config.window.window_decoration
            if decorated != self.get_decorated():
                recreate = True

            # Override redirect toggled?
            ord = config.is_override_redirect()
            if ord != self.get_override_redirect():
                recreate = True

            # Window type hint changed?
            type_hint = config.quirks.get_window_type_hint(self)
            if type_hint != self._type_hint:
                recreate = True

            # (re-)create the gdk window?
            if recreate:
                self._recreate_window()

            # Show the resize gripper?
            if gtk_has_resize_grip_support():
                if config.has_window_decoration():
                    self.set_has_resize_grip(self._default_resize_grip)
                else:
                    self.set_has_resize_grip(False)

            self.update_sticky_state()

    def _recreate_window(self):
        _logger.info("recreating window - window options changed")

        visible = None
        if self.get_realized(): # not starting up?
            visible = self.is_visible()
            self.hide()
            self.unrealize()

        self.realize()

        if not visible is None:
            Gtk.Window.set_visible(self, visible)

    def update_sticky_state(self):
        if not config.xid_mode:
            # Always on visible workspace?
            sticky = config.get_sticky_state()
            if self._sticky != sticky:
                self._sticky = sticky
                if sticky:
                    self.stick()
                else:
                    self.unstick()

            if self.icp:
                self.icp.update_sticky_state()

    def update_taskbar_hint(self):
        config.quirks.update_taskbar_hint(self)

    def _on_configure_event(self, widget, event):
        self.update_window_rect()
        self.update_window_scaling_factor()

        if _logger.isEnabledFor(logging.DEBUG):
            _logger.debug(
                "configure-event: event {}, allocated {}, "
                "window {}, scaling factor {}"
                .format(Rect(event.x, event.y, event.width, event.height),
                        (self.get_allocated_width(),
                        self.get_allocated_height()),
                        self.get_rect(),
                        config.window_scaling_factor))

    def update_window_scaling_factor(self, startup = False):
        """ check for changes to the window-scaling-factor """
        scale = self.get_scale_factor()
        _logger.debug("update_window_scaling_factor: scale {}"
                      .format(scale))

        if not scale is None and \
           config.window_scaling_factor != scale:
            config.window_scaling_factor = scale
            _logger.info("new window-scaling-factor '{}'".format(scale))

            keyboard = self.keyboard_widget.keyboard

            # In override redirect mode the window gets stuck with
            # the old scale -> recreate it
            if config.is_override_redirect() and \
               not startup and \
               not config.xid_mode:
                self._recreate_window()

                # Release pressed keys in case the switch was initiated
                # by Onboard, e.g. with the Return key in the terminal.
                keyboard.release_pressed_keys()

            # invalidate all images and key surfaces
            self.keyboard_widget.invalidate_images()
            keyboard.invalidate_ui()
            keyboard.commit_ui_updates()

    def is_visible(self):
        if not self.get_mapped():
            return False
        return self._visible

    def set_visible(self, visible):
        # Lazily show the window for smooth startup,
        # in particular with force-to-top mode enabled.
        if not self.get_realized():
            self._show_first_time()

        # Make sure the move button stays visible
        # Do this on hiding the window, because the window position
        # is unreliable when unhiding.
        if not visible and \
           self.can_move_into_view():
            self.move_home_rect_into_view()

        config.quirks.set_visible(self, visible)
        self.on_visibility_changed(visible)

    def on_visibility_changed(self, visible):

        if not visible:
            keyboard = self.keyboard_widget.keyboard
            keyboard.stop_raise_attempts()

        visible_before = self._visible
        self._visible = visible

        if not self._screen_resizing:
            if visible:
                self.set_icp_visible(False)
                self.update_sticky_state()
            else:
                # show the icon palette
                if config.is_icon_palette_in_use():
                    self.set_icp_visible(True)

        # update indicator menu for unity and unity2d
        # not necessary but doesn't hurt in gnome-shell, gnome classic
        if self.application:
            status_icon = self.application.status_icon
            if status_icon:
                status_icon.update_menu_items()

            service = self.application.service_keyboard
            if service:
                service.PropertiesChanged(service.IFACE,
                                          {'Visible': visible}, ['Visible'])

    def set_opacity(self, opacity):
        self.keyboard_widget.set_opacity(opacity)

    def get_opacity(self):
        return self.keyboard_widget.get_opacity()

    def is_maximized(self):
        return self._maximized

    def is_iconified(self):
        # Force-to-top windows are ignored by the window manager
        # and cannot be in iconified state.
        if config.is_force_to_top():
            return False

        return self._iconified

    def set_icp_visible(self, visible):
        """ Show/hide the icon palette """
        if self.icp:
            if visible:
                self.icp.show()
            else:
                self.icp.hide()

    def _cb_visibility_notify(self, widget, event):
        pass

    def _cb_window_state_event(self, widget, event):
        """
        This is the callback that gets executed when the user hides the
        onscreen keyboard by using the minimize button in the decoration
        of the window.
        Fails to be called when iconifying in gnome-shell (Oneiric).
        Fails to be called when iconifying in unity (Precise).
        Still keep it around for sticky changes.
        """
        _logger.debug("window-state-event: {}, {}"
                      .format(event.changed_mask, event.new_window_state))

        if event.changed_mask & Gdk.WindowState.MAXIMIZED:
            self._maximized = bool(event.new_window_state & Gdk.WindowState.MAXIMIZED)

        if event.changed_mask & Gdk.WindowState.ICONIFIED:
            self._iconified = bool(event.new_window_state & Gdk.WindowState.ICONIFIED)
            self._on_iconification_state_changed(self._iconified)

        if event.changed_mask & Gdk.WindowState.STICKY:
            self._sticky = bool(event.new_window_state & Gdk.WindowState.STICKY)

    def _on_iconification_state_changed(self, iconified):
            visible = not iconified
            was_visible = self.is_visible()

            self.on_visibility_changed(visible)

            # Cancel visibility transitions still in progress
            self.keyboard_widget.transition_visible_to(visible, 0.0)

            if was_visible != visible:
                if visible:
                    # Hiding may have left the window opacity at 0.
                    # Ramp up the opacity when it was unminimized by
                    # clicking the (unity) launcher.
                    self.keyboard_widget.update_transparency()

                # - Unminimizing from unity-2d launcher is a user
                #   triggered unhide -> lock auto-show visible.
                # - Minimizing while locked visible -> unlock
                keyboard = self.keyboard_widget.keyboard
                keyboard.update_auto_show_on_visibility_change(visible)

            return

    def on_transition_done(self, visible_before, visible_now):
        pass

    def do_set_gravity(self, edgeGravity):
        '''
        This will place the window on the edge corresponding to the edge gravity
        '''
        _logger.debug("Entered in do_set_gravity")
        self.edgeGravity = edgeGravity
        width, height = self.get_size()

        geom = self.get_screen().get_monitor_geometry(0)
        eg = self.edgeGravity

        x = 0
        y = 0
        if eg == Gdk.Gravity.SOUTH:
            y = geom.height - height
            y += 29 #to account for panel.

        self.move(x, y)

        GLib.idle_add(self.do_set_strut)

    def do_set_strut(self):
        _logger.debug("Entered in do_set_strut")
        propvals = [0,0,0,0,0,0,0,0,0,0,0,0]
        """propvals = [0,#left
                0, #right
                0, #top
                300,#bottom
                0,#left_start_y
                0,#left_end_y
                0,#right_start_y
                0,#right_end_y
                0,#top_start_x
                0,#top_end_x
                0,#bottom_start_x
                3000]#bottom_end_x"""

        screen = self.get_screen()
        biggestHeight = 0
        for n in range(screen.get_n_monitors()):
            tempHeight = screen.get_monitor_geometry(n).height
            if biggestHeight < tempHeight:
                biggestHeight = tempHeight

        eg = self.edgeGravity
        x, y = self.window.get_origin()

        width,height = self.get_size()

        if eg == Gdk.Gravity.NORTH:
            propvals[2] = height + y
            propvals[9] = width
        elif eg == Gdk.Gravity.SOUTH and y != 0:
            propvals[3] = biggestHeight - y
            propvals[11] = width - 1

            # tell window manager to not overlap buttons with maximized window
            self.window.property_change("_NET_WM_STRUT_PARTIAL",
                                        "CARDINAL",
                                        32,
                                        Gdk.PropMode.REPLACE,
                                        propvals)
        self.queue_resize_no_redraw()

    def can_move_into_view(self):
        return not config.xid_mode and \
           not config.has_window_decoration() and \
           not config.is_docking_enabled()


    def get_orientation_config_object(self):
        return None


class KbdWindow(KbdWindowBase, WindowRectPersist, Gtk.Window):

    # Minimum window size (for resizing in system mode, see handle_motion())
    MINIMUM_SIZE = 20

    home_rect = None

    def __init__(self, keyboard_widget, icp):
        self._last_ignore_configure_time = None
        self._last_configures = []
        self._was_visible = False
        self._user_positioning_begin_rect = Rect()

        Gtk.Window.__init__(self,
                            urgency_hint = False,
                            width_request=self.MINIMUM_SIZE,
                            height_request=self.MINIMUM_SIZE)

        KbdWindowBase.__init__(self, keyboard_widget, icp)

        WindowRectPersist.__init__(self)

        GObject.signal_new("quit-onboard", KbdWindow,
                           GObject.SignalFlags.RUN_LAST,
                           GObject.TYPE_BOOLEAN, ())

        self._auto_position_poll_timer = Timer()

        self.restore_window_rect(startup = True)

        self.connect("map",                     self._on_map_event)
        self.connect("unmap",                   self._on_unmap_event)
        self.connect("delete-event", self._on_delete_event)
        # Connect_after seems broken in Quantal, the callback is never called.
        #self.connect_after("configure-event", self._on_configure_event_after)

        self._osk_util.connect_root_property_notify(["_NET_WORKAREA",
                                                     "_NET_CURRENT_DESKTOP"],
                                                self._on_root_property_notify)

        once = CallOnce(100).enqueue  # call at most once per 100ms

        rect_changed = lambda x: once(self._on_config_rect_changed)
        config.window.position_notify_add(rect_changed)
        config.window.size_notify_add(rect_changed)

        dock_size_changed = lambda x: once(self._on_config_dock_size_changed)
        config.window.dock_size_notify_add(dock_size_changed)

    def cleanup(self):
        WindowRectPersist.cleanup(self)
        KbdWindowBase.cleanup(self)
        if self.icp:
            self.icp.cleanup()
            self.icp.destroy()
            self.icp = None

    def _on_root_property_notify(self, property):
        """ Fixme: Exceptions get lost in here."""

        if property == "_NET_WORKAREA":

           if config.is_docking_enabled() and \
              not config.xid_mode:
                monitor = self.get_docking_monitor()
                new_area = self.get_monitor_workarea(monitor)
                area = self._monitor_workarea.get(monitor)
                if area:
                    # Only check for x changes, y is too dangerous for now,
                    # too easy to get the timing wrong and end up with double docks.
                    if area.x != new_area.x or \
                       area.w != new_area.w:
                        area.x = new_area.x
                        area.w = new_area.w

                        _logger.info("workarea changed to {}, "
                                     "using {} for docking." \
                                     .format(str(new_area), str(area)))
                        self.update_docking()

        elif property == "_NET_CURRENT_DESKTOP":
            # OpenBox: Make sure to move the keyboard to the new desktop
            #          on the next occasion.
            # Unity:   Never reached (Raring), _NET_CURRENT_DESKTOP isn't
            #          set when switching desktops there. However we do get a
            #          configure event, so the transitioning code moves the
            #          window and it is brought to the current desktop anyway.
            self._desktop_switch_count += 1

    def _on_map_event(self, user_data):
        pass

    def _on_unmap_event(self, user_data):
        # Turn off struts in case this unmap is in response to
        # changes in window options, force-to-top in particular.
        if config.is_docking_enabled():
            self.clear_struts()

        # untity starts onboard before the desktops
        # workarea has settled, reset it here on hiding,
        # as we know our struts are gone from this point.
        self.reset_monitor_workarea()

    def on_visibility_changed(self, visible):
        if not self._visible and visible and \
           not config.is_docking_enabled() and \
           not config.xid_mode:
            rect = self.get_current_rect()
            if not rect is None: # shouldn't happen, fix this
                self.move_resize(*rect) # sync position
                self.keyboard_widget.sync_transition_position(rect)

        KbdWindowBase.on_visibility_changed(self, visible)

    def _on_config_rect_changed(self):
        """ Gsettings position or size changed """
        if not config.xid_mode and \
           not config.is_docking_enabled():
            orientation = self.get_screen_orientation()
            rect = self.read_window_rect(orientation)

            # Only apply the new rect if it isn't the one we just wrote to
            # gsettings. Someone has to have manually changed the values
            # in gsettings to allow moving the window.
            rects = list(self._written_window_rects.values())
            if not any(rect == r for r in rects):
                self.restore_window_rect()

    def _on_config_dock_size_changed(self):
        """ Gsettings size changed """
        if not config.xid_mode and \
           config.is_docking_enabled():
            size = self.get_dock_size()

            # Only apply the new rect if it isn't the one we just wrote to
            # gsettings. Someone has to have manually changed the values
            # in gsettings to allow moving the window.
            sizes = list(self._written_dock_sizes.values())
            if not any(size == sz for sz in sizes):
                self.restore_window_rect()

    def on_user_positioning_begin(self):
        keyboard = self.keyboard_widget.keyboard

        self.stop_save_position_timer()
        self.stop_auto_positioning()
        keyboard.stop_raise_attempts()
        keyboard.freeze_auto_show()

        self._user_positioning_begin_rect = self.get_rect()

    def on_user_positioning_done(self):
        self.update_window_rect()

        #self.detect_docking()
        if config.is_docking_enabled():
            self.write_docking_size(self.get_screen_orientation(),
                                    self.get_size())
            self.update_docking()
        else:
            # Attempt to filter out accidental resize frame clicks to prevent
            # losing the home position without clear user intention.
            proximity = 30
            rh = self.get_home_rect()
            began_near_home = \
                self._user_positioning_begin_rect.inflate(proximity) \
                .intersection(rh) == rh
            moved = self.keyboard_widget.was_moving()
            update_home_position = began_near_home or moved

            self.update_home_rect(update_home_position)

        # Thaw auto show only after a short delay to stop the window
        # from hiding due to spurios focus events after a system resize.
        keyboard = self.keyboard_widget.keyboard
        keyboard.thaw_auto_show(1.0)

    def detect_docking(self):
        if self.keyboard_widget.was_moving():
            config.window.docking_enabled = False

    def _on_configure_event(self, widget, event):
        KbdWindowBase._on_configure_event(self, widget, event)

        if not config.is_docking_enabled():
            # Connect_after seems broken in Quantal, but we still need to
            # get in after the default configure handler is done. Try to run
            # _on_configure_event_after in an idle handler instead.
            GLib.idle_add(self._on_configure_event_after, widget, event.copy())

    def _on_configure_event_after(self, widget, event):
        """
        Run this after KeyboardWidget's configure handler.
        After resizing Keyboard.update_layout() has to be called before
        limit_position() or the window jumps when it was close
        to the opposite screen edge of the resize handle.
        """
        # Configure event due to user positioning?
        result = self._filter_configure_event(self._window_rect)
        if result == 0:
            self.update_home_rect()

            # While moving with the title bar...
            if config.has_window_decoration():

                # stop auto-show from hiding the keyboard
                keyboard = self.keyboard_widget.keyboard
                keyboard.freeze_auto_show(1.0)

                # cut off any leftover auto-show repositioning
                self.stop_auto_positioning()

                # keep the window active (LP: #1461823)
                self.keyboard_widget.touch_inactivity_timer()

    def _filter_configure_event(self, rect):
        """
        Returns 0 for detected user positioning/sizing.
        Multiple defenses against false positives, i.e.
        window movement by autoshow, screen rotation, whathaveyou.
        """

        # There is no user positioning in xembed mode.
        if config.xid_mode:
            return -1

        # There is no system provided way to move/resize in
        # force-to-top mode. Solely rely on on_user_positioning_done().
        if config.is_force_to_top():
            return -2

        # There is no user positioning for invisible windows.
        if not self.is_visible():
            return -3

        # There is no user positioning for iconified windows.
        if self.is_iconified():
            return -4

        # There is no user positioning for maximized windows.
        if self.is_maximized():
            return -5

        # Remember past n configure events.
        now = time.time()
        max_events = 4
        self._last_configures = self._last_configures[-(max_events - 1):]

        # Same rect as before?
        if len(self._last_configures) and \
           self._last_configures[-1][0] == rect:
            return 1

        self._last_configures.append([rect, now])

        # Only just started?
        if len(self._last_configures) < max_events:
            return 2

        # Did we just move the window by auto-show?
        if not self._last_ignore_configure_time is None and \
           time.time() - self._last_ignore_configure_time < 0.5:
            return 3

        # Is the new window rect one of our known ones?
        if self.is_known_rect(self._window_rect):
            return 4

        # Dragging the decorated frame doesn't produce continous
        # configure-events anymore as in Oneriric (Precise).
        # Disable all affected checks based on this.
        # The home rect will probably get lost occasionally.
        if not config.has_window_decoration():

            # Less than n configure events in the last x seconds?
            first = self._last_configures[0]
            intervall = now - first[1]
            if intervall > 1.0:
                return 5

            # Is there a jump > threshold in past positions?
            r0 = self._last_configures[-1][0]
            r1 = self._last_configures[-2][0]
            dx = r1.x - r0.x
            dy = r1.y - r0.y
            d2 = dx * dx + dy * dy
            if d2 > 50**2:
                self._last_configures = [] # restart
                return 6

        return 0

    def ignore_configure_events(self):
        self._last_ignore_configure_time = time.time()

    def remember_rect(self, rect):
        """
        Remember the last 3 rectangles of auto-show repositioning.
        Time and order of configure events is somewhat unpredictable,
        so don't rely only on a single remembered rect.
        """
        self._known_window_rects = self._known_window_rects[-3:]
        self._known_window_rects.append(rect)

        # Remembering the rects doesn't help if respositioning outside
        # of the work area in compiz with force-to-top mode disabled.
        # WM corrects window positions to fit into the viewable area.
        # -> add timing based block
        self.ignore_configure_events()

    def get_known_rects(self):
        """
        Return all rects that may have resulted from internal
        window moves, not from user controlled drag operations.
        """
        rects = list(self._known_window_rects)

        co = config.window.landscape
        rects.append(Rect(co.x, co.y, co.width, co.height))

        co = config.window.portrait
        rects.append(Rect(co.x, co.y, co.width, co.height))

        rects.append(self.home_rect)
        return rects

    def is_known_rect(self, rect):
        """
        The home rect should be updated in response to user positiong/resizing.
        However we are unable to detect the end of window movement/resizing
        when window decoration is enabled. Instead we check if the current
        window rect is different from the ones auto-show knows and assume
        the user has changed it in this case.
        """
        return any(rect == r for r in self.get_known_rects())

    def move_home_rect_into_view(self):
        """
        Make sure the home rect is valid, move it if necessary.
        This function may be called even if the window is invisible.
        """
        rect = self._window_rect.copy()
        x, y = rect.x, rect.y
        _x, _y = self.keyboard_widget.limit_position(x, y)
        if _x != x or _y != y:
            self.update_home_rect()

    def update_home_rect(self, update_home_position=True):
        if config.is_docking_enabled():
            return

        # update home rect
        rect = self._window_rect.copy()
        if not update_home_position:
            rh = self.home_rect
            rect.x = rh.x
            rect.y = rh.y

        # Make sure the move button stays visible
        if self.can_move_into_view():
            rect.x, rect.y = self.keyboard_widget.limit_position(rect.x, rect.y)

        self.home_rect = rect.copy()
        self.start_save_position_timer()

        # Make transitions aware of the new position,
        # undoubtedly reached by user positioning.
        # Else, window snaps back to the last transition position.
        self.keyboard_widget.sync_transition_position(rect)

    def get_home_rect(self):
        """
        Get the un-repositioned rect, the one auto-show falls back to
        when there is nowhere else to move.
        """
        if config.is_docking_enabled():
            rect = self.get_dock_rect()
        else:
            rect = self.home_rect
        return rect

    def get_visible_rect(self):
        """
        Returns the rect of the visible window rect with auto-show
        repositioning taken into account.
        """
        home_rect = self.get_home_rect()  # aware of docking
        rect = home_rect

        if config.is_auto_show_enabled():

            r = self.get_repositioned_window_rect(home_rect)
            if not r is None:
                rect = r

        return rect

    def auto_position(self):
        self._auto_position_started = True

        # Leave the first commit to AutoShow._begin_transition()
        self.update_position(False)

        # With docking enabled, when focusing the search entry of a
        # maximized firefox window, it changes position when the work
        # area shrinks and ends up below Onboard.
        # -> periodically update the window position for a little while,
        #    this way slow systems can catch up too eventually (Nexus 7).
        self._poll_auto_position_start_time = time.time()
        start_delay = 0.1
        self._auto_position_poll_timer.start(start_delay,
                                             self._on_auto_position_poll,
                                             start_delay)

    def _on_auto_position_poll(self, delay):
        self.update_position()

        # start another timer for progressively longer intervals
        delay = min(delay * 2.0, 1.0)
        if time.time() + delay < self._poll_auto_position_start_time + 3.0:
            self._auto_position_poll_timer.start(delay,
                                                 self._on_auto_position_poll,
                                                 delay)
            return True
        else:
            return False

    def stop_auto_positioning(self):
        self._auto_position_poll_timer.stop()

    def update_position(self, commit=True):
        home_rect = self.get_home_rect()
        rect = self.get_repositioned_window_rect(home_rect)
        if rect is None:
            # move back home
            rect = home_rect

        if self.get_position() != rect.get_position():
            self.keyboard_widget.transition_position_to(rect.x, rect.y)
            if commit:
                self.keyboard_widget.commit_transition()

    def get_repositioned_window_rect(self, home_rect):
        if config.can_auto_show_reposition():
            clearance = config.auto_show.widget_clearance
            test_clearance = clearance
            move_clearance = clearance
            limit_rects = None  # None: all monitors

            # No test clearance when docking. Make it harder to jump
            # out of the dock, for example for the bottom search box
            # in maximized firefox.
            if config.is_docking_enabled():
                test_clearance = (clearance[0], 0, clearance[2], 0)

                # limit the horizontal freedom to the docking monitor
                area, geom = self.get_docking_monitor_rects()
                limit_rects = [area]

            horizontal, vertical = self.get_repositioning_constraints()
            keyboard = self.keyboard_widget.keyboard
            rect = keyboard.get_auto_show_repositioned_window_rect( \
                                            self.keyboard_widget,
                                            home_rect, limit_rects,
                                            test_clearance, move_clearance,
                                            horizontal, vertical)
        else:
            rect = None

        return rect

    def reposition(self, x, y):
        """
        Move the window from a transition, not meant for user positioning.
        """
        # remember rects to distinguish from user move/resize
        w, h = self.get_size()
        self.remember_rect(Rect(x, y, w, h))

        # In Trusty, Compiz, floating window with force-to-top enabled,
        # this window's configure-event lies about the window position
        # after un-hiding by auto-show, which leads to jumping when
        # moving or resizing afterwards.
        #
        # Test case:
        # 1) Start onboard with auto-show enabled
        # 2) Focus text entry to show the keyboard
        # 3) Move the keyboard
        # 4) Unfocus all text entries to hide the keyboard
        # 5) Focus text entry to show the keyboard
        # 6) Move the keyboard
        #    -> keyboard jumps to the previous position
        #
        # Workaround: force position change to get new, hopefully
        #             correct configure-events
        if self._auto_position_started:
            self._auto_position_started = False
            if config.quirks.must_fix_configure_event():
                self.move(x-1, y)

        self.move(x, y)

    def get_repositioning_constraints(self):
        """
        Return allowed respositioning directions for auto-show.
        """
        if config.is_docking_enabled() and \
           self.get_dock_expand():
            return False, True
        else:
            return True, True

    def get_hidden_rect(self):
        """
        Returns the rect of the hidden window with auto-show
        repositioning taken into account.
        """
        if config.is_docking_enabled():
            return self.get_docking_hideout_rect()
        return self.get_visible_rect()

    def get_current_rect(self):
        """
        Returns the window rect with auto-show
        repositioning taken into account.
        """
        if self.is_visible():
            rect = self.get_visible_rect()
        else:
            rect = self.get_hidden_rect()
        return rect

    def on_restore_window_rect(self, rect):
        """
        Overload for WindowRectPersist.
        """
        if not config.is_docking_enabled():
            self.home_rect = rect.copy()

        # check for alternative auto-show position
        r = self.get_current_rect()
        if r != rect:
            # remember our rects to distinguish from user move/resize
            self.remember_rect(r)
            rect = r

        self.keyboard_widget.sync_transition_position(rect)
        return rect

    def on_save_window_rect(self, rect):
        """
        Overload for WindowRectPersist.
        """
        # Ignore <rect> (self._window_rect), it may just be a temporary one
        # set by auto-show. Save the user selected home_rect instead.
        return self.home_rect

    def read_window_rect(self, orientation):
        """
        Read orientation dependent rect.
        Overload for WindowRectPersist.
        """
        if orientation == Orientation.LANDSCAPE:
            co = config.window.landscape
        else:
            co = config.window.portrait
        rect = Rect(co.x, co.y, co.width, co.height)
        return rect

    def write_window_rect(self, orientation, rect):
        """
        Write orientation dependent rect.
        Overload for WindowRectPersist.
        """
        # There are separate rects for normal and rotated screen (tablets).
        if orientation == Orientation.LANDSCAPE:
            co = config.window.landscape
        else:
            co = config.window.portrait

        # remember that we wrote this rect to gsettings
        self._written_window_rects[orientation] = rect.copy()

        # write to gsettings and trigger notifications
        co.delay()
        co.x, co.y, co.width, co.height = rect
        co.apply()

    def write_docking_size(self, orientation, size):
        co = self.get_orientation_config_object()
        expand = self.get_dock_expand()

        # remember that we wrote this rect to gsettings
        self._written_dock_sizes[orientation] = tuple(size)

        # write to gsettings and trigger notifications
        co.delay()
        if not expand:
            co.dock_width = size[0]
        co.dock_height = size[1]
        co.apply()

    def get_orientation_config_object(self):
        orientation = self.get_screen_orientation()
        if orientation == Orientation.LANDSCAPE:
            co = config.window.landscape
        else:
            co = config.window.portrait
        return co

    def on_transition_done(self, visible_before, visible_now):
        if visible_now:
            self.assure_on_current_desktop()
            self.update_docking()

    def on_screen_size_changed(self, screen):
        """ Screen rotation, etc. """
        if config.is_docking_enabled():
            # Can't correctly position the window while struts are active
            # -> turn them off for a moment
            self.clear_struts()

            # Attempt to hide the keyboard now. This won't work that well
            # as the system doesn't refresh the screen anymore until
            # after the rotation.
            self._was_visible = self.is_visible()
            self._screen_resizing = True
            keyboard_widget = self.keyboard_widget
            if keyboard_widget:
                keyboard_widget.transition_visible_to(False, 0.0)
                keyboard_widget.commit_transition()

        WindowRectPersist.on_screen_size_changed(self, screen)

    def on_screen_size_changed_delayed(self, screen):
        if config.is_docking_enabled():
            self._screen_resizing = False
            self.reset_monitor_workarea()

            # The keyboard size may have changed, draw with the new size now,
            # while it's still in the hideout, so we don't have to watch.
            self.restore_window_rect()
            self.keyboard_widget.process_updates()

            keyboard_widget = self.keyboard_widget
            if keyboard_widget and self._was_visible:
                keyboard_widget.transition_visible_to(True, 0.0, 0.4)
                keyboard_widget.commit_transition()
        else:
            self.restore_window_rect()

    def limit_size(self, rect):
        """
        Limits the given window rect to fit on screen.
        """
        if self.keyboard_widget:
            return self.keyboard_widget.limit_size(rect)
        return rect

    def _on_delete_event(self, event, data=None):
        if config.lockdown.disable_quit:
            if self.keyboard_widget:
                return True
        else:
            self.emit_quit_onboard()

    def on_docking_notify(self):
        self.update_docking()
        self.keyboard_widget.update_window_handles()

    def update_docking(self, force_update = False):
        enable = config.is_docking_enabled()
        if enable:
            rect = self.get_dock_rect()
        else:
            rect = Rect()
        shrink = config.window.docking_shrink_workarea
        expand = self.get_dock_expand()
        edge = config.window.docking_edge
        monitor = self.get_docking_monitor(True)

        if self._docking_enabled != enable or \
           (self._docking_enabled and \
            (self._docking_rect != rect or \
             self._shrink_work_area != shrink or \
             self._dock_expand != expand or \
             bool(self._current_struts) != shrink or
             self._docking_monitor != monitor)
           ):
            self._current_docking_monitor = monitor

            self._realize_docking(enable)

            self._shrink_work_area = shrink
            self._dock_expand = expand
            self._docking_edge = edge
            self._docking_monitor = monitor
            self._docking_enabled = enable
            self._docking_rect = rect

    def _realize_docking(self, enable):
        if enable:
            self._set_docking_struts(config.window.docking_shrink_workarea,
                                     config.window.docking_edge,
                                     self.get_dock_expand())
            self.restore_window_rect() # knows about docking
        else:
            self.restore_window_rect()
            self.clear_struts()

    def update_docking_monitor(self):
        mon_before = self._current_docking_monitor
        mon_now = self.get_docking_monitor(True)
        self._current_docking_monitor = mon_now
        return mon_before != mon_now

    def clear_struts(self):
        self._set_docking_struts(False)

    def _set_docking_struts(self, enable, edge = None, expand = True):
        if not self.get_realized():
            # no window, no xid
            return

        win = self.get_window()
        try:
            xid = win.get_xid()  # requires GdkX11 import
        except AttributeError:
            # docking unavailable on Wayland
            return

        if not enable:
            self._apply_struts(xid, None)
            return

        area, geom = self.get_docking_monitor_rects()
        root = self.get_rootwin_rect()

        rect = self.get_dock_rect()
        top_start_x = top_end_x = 0
        bottom_start_x = bottom_end_x = 0

        if edge: # Bottom
            top    = 0
            bottom = geom.h - area.bottom() + rect.h
            #bottom = root.h - area.bottom() + rect.h
            bottom_start_x = rect.left()
            bottom_end_x   = rect.right() - 1
        else:    # Top
            top    = area.top() + rect.h
            bottom = 0
            top_start_x = rect.left()
            top_end_x   = rect.right() - 1


        struts = [0, 0, top, bottom, 0, 0, 0, 0,
                  top_start_x, top_end_x, bottom_start_x, bottom_end_x]

        scale = config.window_scaling_factor
        if scale != 1.0:
            struts = [val * scale for val in struts]

        self._apply_struts(xid, struts)

    def _apply_struts(self, xid, struts = None):
        if self._current_struts != struts:
            if struts is None:
                self._osk_struts.clear(xid)
            else:
                self._osk_struts.set(xid, struts)
            self._current_struts = struts

    def get_dock_size(self):
        co = self.get_orientation_config_object()
        return co.dock_width, co.dock_height

    def get_dock_expand(self):
        co = self.get_orientation_config_object()
        return co.dock_expand

    def get_dock_rect(self):
        area, geom = self.get_docking_monitor_rects()
        edge = config.window.docking_edge

        width, height = self.get_dock_size()
        rect = Rect(area.x, 0, area.w, height)
        if edge: # Bottom
            rect.y = area.y + area.h - height
        else:    # Top
            rect.y = area.y

        expand = self.get_dock_expand()
        if expand:
            rect.w = area.w
            rect.x = area.x
        else:
            rect.w = min(width, area.w)
            rect.x = rect.x + (area.w - rect.w) // 2
        return rect

    def get_docking_hideout_rect(self, reference_rect = None):
        """ Where the keyboard goes to hide when it slides off-screen. """
        area, geom = self.get_docking_monitor_rects()
        rect = self.get_dock_rect()
        hideout = rect

        mcx, mcy = geom.get_center()
        if reference_rect:
            cx, cy = reference_rect.get_center()
        else:
            cx, cy = rect.get_center()
        clearance = 10
        if cy > mcy:
            hideout.y = geom.bottom() + clearance  # below Bottom
        else:
            hideout.y = geom.top() - rect.h - clearance # above Top

        return hideout

    def get_docking_monitor_rects(self):
        screen = self.get_screen()
        monitor = self.get_docking_monitor()

        area = self._monitor_workarea.get(monitor)
        if area is None:
            area = self.update_monitor_workarea(monitor)

        geom = screen.get_monitor_geometry(monitor)
        geom = Rect(geom.x, geom.y, geom.width, geom.height)

        return area, geom

    def get_docking_monitor(self, force_update=False):
        if self._current_docking_monitor is None or force_update:
            screen = self.get_screen()
            docking_monitor = config.window.docking_monitor

            monitor = int(docking_monitor)
            if monitor < 100:
                if monitor < 0 or \
                   monitor >= screen.get_n_monitors():
                    docking_monitor = DockingMonitor.PRIMARY

            if docking_monitor == DockingMonitor.ACTIVE:
                monitor = self._get_monitor_at_active_window(screen)
            elif docking_monitor == DockingMonitor.PRIMARY:
                monitor = screen.get_primary_monitor()
        else:
            monitor = self._current_docking_monitor
        return monitor

    @staticmethod
    def _get_monitor_at_active_window(screen):
        window = screen.get_active_window()
        if window:
            # Sometimes causes X error "BadDrawable" in Vivid for Francesco
            Gdk.error_trap_push()
            monitor = screen.get_monitor_at_window(window)
            if Gdk.error_trap_pop():
                monitor = screen.get_primary_monitor()
        else:
            monitor = screen.get_primary_monitor()
        return monitor

    def reset_monitor_workarea(self):
        self._monitor_workarea = {}

    def update_monitor_workarea(self, monitor):
        """
        Save the workarea, so we don't have to
        check all the time if our strut is already installed.
        """
        area = self.get_monitor_workarea(monitor)
        self._monitor_workarea[monitor] = area
        return area

    def get_monitor_workarea(self, monitor):
        screen = self.get_screen()
        area = screen.get_monitor_workarea(monitor)
        area = Rect(area.x, area.y, area.width, area.height)
        return area

    @staticmethod
    def get_rootwin_rect():
        rootwin = Gdk.get_default_root_window()
        return Rect.from_position_size(rootwin.get_position(),
                                (rootwin.get_width(), rootwin.get_height()))

    def assure_on_current_desktop(self):
        """
        Make sure the window is visible in the current desktop in OpenBox and
        perhaps other WMs, except Compiz/Unity. Dbus Show() then makes Onboard
        appear after switching desktop (LP: 1092166, Raring).
        """
        if self._moved_desktop_switch_count != self._desktop_switch_count:
            win = self.get_window()
            if win:
                win.move_to_current_desktop()
                self._moved_desktop_switch_count = self._desktop_switch_count

    def raise_to_top(self):
        win = self.get_window()
        if win and self.is_visible():
            win.raise_()


class KbdPlugWindow(KbdWindowBase, WindowRectTracker, Gtk.Plug):
    def __init__(self, keyboard_widget, icp = None):
        Gtk.Plug.__init__(self)
        WindowRectTracker.__init__(self)
        KbdWindowBase.__init__(self, keyboard_widget, icp)

    def _on_configure_event(self, widget, event):
        KbdWindowBase._on_configure_event(self, widget, event)

    def toggle_visible(self):
        pass


class WMQuirksDefault:
    """ Miscellaneous window managers, no special quirks """
    wms = ()

    @staticmethod
    def set_visible(window, visible):
        if window.is_iconified():
            if visible and \
               not config.xid_mode:
                window.deiconify()
                window.present()
        else:
            Gtk.Window.set_visible(window, visible)

    @staticmethod
    def update_taskbar_hint(window):
        window.set_skip_taskbar_hint(True)

    @staticmethod
    def get_window_type_hint(window):
        if config.is_docking_enabled():
            return Gdk.WindowTypeHint.DOCK
        else:
            return Gdk.WindowTypeHint.NORMAL

    @staticmethod
    def can_set_override_redirect(window):
        # struts fail for override redirect windows in metacity and mutter
        return not config.is_docking_enabled()

    @staticmethod
    def must_fix_configure_event():
        """ does configure-event need fixing? """
        return False

class WMQuirksCompiz(WMQuirksDefault):
    """ Unity with Compiz """
    wms = ("compiz")

    @staticmethod
    def get_window_type_hint(window):
        if config.is_docking_enabled():
            # repel unity MT touch handles with DOCK, but we have OR enabled now
            return Gdk.WindowTypeHint.NORMAL
        else:
            if config.is_force_to_top():
                # NORMAL keeps Onboard on top of fullscreen firefox (LP: 1035578)
                return Gdk.WindowTypeHint.NORMAL
            else:
                if config.window.window_decoration:
                    # Keep showing the minimize button
                    return Gdk.WindowTypeHint.NORMAL
                else:
                    # don't get resized by compiz's grid plugin (LP: 893644)
                    return Gdk.WindowTypeHint.UTILITY

    @staticmethod
    def can_set_override_redirect(window):
        # Can't type into unity dash with keys below dash without
        # override redirect. -> turn it on even when docking. Apparently
        # Compiz can handle struts with OR windows.
        return True

    @staticmethod
    def must_fix_configure_event():
        return config.is_force_to_top() and \
            not config.xid_mode # in Trusty


class WMQuirksMutter(WMQuirksDefault):
    """ Gnome-shell """

    wms = ("mutter", "GNOME Shell".lower())

    @staticmethod
    def set_visible(window, visible):
        if window.is_iconified() and visible:
            # When minimized, Mutter doesn't react when asked to
            # remove WM_STATE_HIDDEN. Once the window was minimized
            # by title bar button it cannot be unhidden by auto-show.
            # The only workaround I found is re-mapping it (Precise).
            window.unmap()
            window.map()

        WMQuirksDefault.set_visible(window, visible)


class WMQuirksMetacity(WMQuirksDefault):
    """ Unity-2d, Gnome Classic """

    wms = ("metacity")

    @staticmethod
    def set_visible(window, visible):
        # Metacity is good at iconifying. Take advantage of that
        # and get onboard minimized to the task list when possible.
        if not config.xid_mode and \
           not config.is_force_to_top() and \
           not config.has_unhide_option():
            if visible:
                window.deiconify()
                window.present()
            else:
                window.iconify()
        else:
            WMQuirksDefault.set_visible(window, visible)

    @staticmethod
    def update_taskbar_hint(window):
        window.set_skip_taskbar_hint(config.xid_mode or \
                                     config.is_force_to_top() or \
                                     config.has_unhide_option())