summaryrefslogtreecommitdiffstats
path: root/chromium/ui/views/win/hwnd_message_handler.cc
blob: d5f442f71da7ad3b7087af40967d6df0579803f5 (plain)
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
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/views/win/hwnd_message_handler.h"

#include <dwmapi.h>
#include <oleacc.h>
#include <shellapi.h>
#include <tchar.h>
#include <wrl/client.h>

#include <utility>

#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/debug/alias.h"
#include "base/location.h"
#include "base/macros.h"
#include "base/message_loop/message_loop_current.h"
#include "base/single_thread_task_runner.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/time/time.h"
#include "base/trace_event/trace_event.h"
#include "base/win/scoped_gdi_object.h"
#include "base/win/windows_version.h"
#include "ui/accessibility/platform/ax_platform_node_win.h"
#include "ui/accessibility/platform/ax_system_caret_win.h"
#include "ui/base/ime/input_method.h"
#include "ui/base/ime/text_input_client.h"
#include "ui/base/ime/text_input_type.h"
#include "ui/base/ui_base_features.h"
#include "ui/base/view_prop.h"
#include "ui/base/win/internal_constants.h"
#include "ui/base/win/lock_state.h"
#include "ui/base/win/mouse_wheel_util.h"
#include "ui/base/win/shell.h"
#include "ui/base/win/touch_input.h"
#include "ui/display/win/dpi.h"
#include "ui/display/win/screen_win.h"
#include "ui/events/event.h"
#include "ui/events/event_constants.h"
#include "ui/events/event_utils.h"
#include "ui/events/keycodes/keyboard_code_conversion_win.h"
#include "ui/events/win/system_event_state_lookup.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/geometry/insets.h"
#include "ui/gfx/icon_util.h"
#include "ui/gfx/path.h"
#include "ui/gfx/path_win.h"
#include "ui/gfx/win/hwnd_util.h"
#include "ui/gfx/win/rendering_window_manager.h"
#include "ui/native_theme/native_theme_win.h"
#include "ui/views/views_delegate.h"
#include "ui/views/widget/widget_hwnd_utils.h"
#include "ui/views/win/fullscreen_handler.h"
#include "ui/views/win/hwnd_message_handler_delegate.h"
#include "ui/views/win/scoped_fullscreen_visibility.h"
#include "ui/views/win/windows_session_change_observer.h"

namespace views {
namespace {

// MoveLoopMouseWatcher is used to determine if the user canceled or completed a
// move. win32 doesn't appear to offer a way to determine the result of a move,
// so we install hooks to determine if we got a mouse up and assume the move
// completed.
class MoveLoopMouseWatcher {
 public:
  MoveLoopMouseWatcher(HWNDMessageHandler* host, bool hide_on_escape);
  ~MoveLoopMouseWatcher();

  // Returns true if the mouse is up, or if we couldn't install the hook.
  bool got_mouse_up() const { return got_mouse_up_; }

 private:
  // Instance that owns the hook. We only allow one instance to hook the mouse
  // at a time.
  static MoveLoopMouseWatcher* instance_;

  // Key and mouse callbacks from the hook.
  static LRESULT CALLBACK MouseHook(int n_code, WPARAM w_param, LPARAM l_param);
  static LRESULT CALLBACK KeyHook(int n_code, WPARAM w_param, LPARAM l_param);

  void Unhook();

  // HWNDMessageHandler that created us.
  HWNDMessageHandler* host_;

  // Should the window be hidden when escape is pressed?
  const bool hide_on_escape_;

  // Did we get a mouse up?
  bool got_mouse_up_;

  // Hook identifiers.
  HHOOK mouse_hook_;
  HHOOK key_hook_;

  DISALLOW_COPY_AND_ASSIGN(MoveLoopMouseWatcher);
};

// static
MoveLoopMouseWatcher* MoveLoopMouseWatcher::instance_ = NULL;

MoveLoopMouseWatcher::MoveLoopMouseWatcher(HWNDMessageHandler* host,
                                           bool hide_on_escape)
    : host_(host),
      hide_on_escape_(hide_on_escape),
      got_mouse_up_(false),
      mouse_hook_(NULL),
      key_hook_(NULL) {
  // Only one instance can be active at a time.
  if (instance_)
    instance_->Unhook();

  mouse_hook_ = SetWindowsHookEx(
      WH_MOUSE, &MouseHook, NULL, GetCurrentThreadId());
  if (mouse_hook_) {
    instance_ = this;
    // We don't care if setting the key hook succeeded.
    key_hook_ = SetWindowsHookEx(
        WH_KEYBOARD, &KeyHook, NULL, GetCurrentThreadId());
  }
  if (instance_ != this) {
    // Failed installation. Assume we got a mouse up in this case, otherwise
    // we'll think all drags were canceled.
    got_mouse_up_ = true;
  }
}

MoveLoopMouseWatcher::~MoveLoopMouseWatcher() {
  Unhook();
}

void MoveLoopMouseWatcher::Unhook() {
  if (instance_ != this)
    return;

  DCHECK(mouse_hook_);
  UnhookWindowsHookEx(mouse_hook_);
  if (key_hook_)
    UnhookWindowsHookEx(key_hook_);
  key_hook_ = NULL;
  mouse_hook_ = NULL;
  instance_ = NULL;
}

// static
LRESULT CALLBACK MoveLoopMouseWatcher::MouseHook(int n_code,
                                                 WPARAM w_param,
                                                 LPARAM l_param) {
  DCHECK(instance_);
  if (n_code == HC_ACTION && w_param == WM_LBUTTONUP)
    instance_->got_mouse_up_ = true;
  return CallNextHookEx(instance_->mouse_hook_, n_code, w_param, l_param);
}

// static
LRESULT CALLBACK MoveLoopMouseWatcher::KeyHook(int n_code,
                                               WPARAM w_param,
                                               LPARAM l_param) {
  if (n_code == HC_ACTION && w_param == VK_ESCAPE) {
    int value = TRUE;
    DwmSetWindowAttribute(instance_->host_->hwnd(),
                          DWMWA_TRANSITIONS_FORCEDISABLED, &value,
                          sizeof(value));
    if (instance_->hide_on_escape_)
      instance_->host_->Hide();
  }
  return CallNextHookEx(instance_->key_hook_, n_code, w_param, l_param);
}

// Called from OnNCActivate.
BOOL CALLBACK EnumChildWindowsForRedraw(HWND hwnd, LPARAM lparam) {
  DWORD process_id;
  GetWindowThreadProcessId(hwnd, &process_id);
  int flags = RDW_INVALIDATE | RDW_NOCHILDREN | RDW_FRAME;
  if (process_id == GetCurrentProcessId())
    flags |= RDW_UPDATENOW;
  RedrawWindow(hwnd, NULL, NULL, flags);
  return TRUE;
}

bool GetMonitorAndRects(const RECT& rect,
                        HMONITOR* monitor,
                        gfx::Rect* monitor_rect,
                        gfx::Rect* work_area) {
  DCHECK(monitor);
  DCHECK(monitor_rect);
  DCHECK(work_area);
  *monitor = MonitorFromRect(&rect, MONITOR_DEFAULTTONULL);
  if (!*monitor)
    return false;
  MONITORINFO monitor_info = { 0 };
  monitor_info.cbSize = sizeof(monitor_info);
  GetMonitorInfo(*monitor, &monitor_info);
  *monitor_rect = gfx::Rect(monitor_info.rcMonitor);
  *work_area = gfx::Rect(monitor_info.rcWork);
  return true;
}

struct FindOwnedWindowsData {
  HWND window;
  std::vector<Widget*> owned_widgets;
};

// Enables or disables the menu item for the specified command and menu.
void EnableMenuItemByCommand(HMENU menu, UINT command, bool enabled) {
  UINT flags = MF_BYCOMMAND | (enabled ? MF_ENABLED : MF_DISABLED | MF_GRAYED);
  EnableMenuItem(menu, command, flags);
}

// Callback used to notify child windows that the top level window received a
// DWMCompositionChanged message.
BOOL CALLBACK SendDwmCompositionChanged(HWND window, LPARAM param) {
  SendMessage(window, WM_DWMCOMPOSITIONCHANGED, 0, 0);
  return TRUE;
}

// The thickness of an auto-hide taskbar in pixels.
const int kAutoHideTaskbarThicknessPx = 2;

bool IsTopLevelWindow(HWND window) {
  long style = ::GetWindowLong(window, GWL_STYLE);
  if (!(style & WS_CHILD))
    return true;
  HWND parent = ::GetParent(window);
  return !parent || (parent == ::GetDesktopWindow());
}

ui::EventType GetTouchEventType(POINTER_FLAGS pointer_flags) {
  if (pointer_flags & POINTER_FLAG_DOWN)
    return ui::ET_TOUCH_PRESSED;
  if (pointer_flags & POINTER_FLAG_UPDATE)
    return ui::ET_TOUCH_MOVED;
  if (pointer_flags & POINTER_FLAG_UP)
    return ui::ET_TOUCH_RELEASED;
  return ui::ET_TOUCH_MOVED;
}

bool IsHitTestOnResizeHandle(LRESULT hittest) {
  return hittest == HTRIGHT || hittest == HTLEFT || hittest == HTTOP ||
         hittest == HTBOTTOM || hittest == HTTOPLEFT || hittest == HTTOPRIGHT ||
         hittest == HTBOTTOMLEFT || hittest == HTBOTTOMRIGHT;
}

// Convert |param| to the HitTest used in WindowResizeUtils.
HitTest GetWindowResizeHitTest(UINT param) {
  switch (param) {
    case WMSZ_BOTTOM:
      return HitTest::kBottom;
    case WMSZ_TOP:
      return HitTest::kTop;
    case WMSZ_LEFT:
      return HitTest::kLeft;
    case WMSZ_RIGHT:
      return HitTest::kRight;
    case WMSZ_TOPLEFT:
      return HitTest::kTopLeft;
    case WMSZ_TOPRIGHT:
      return HitTest::kTopRight;
    case WMSZ_BOTTOMLEFT:
      return HitTest::kBottomLeft;
    case WMSZ_BOTTOMRIGHT:
      return HitTest::kBottomRight;
    default:
      NOTREACHED();
      return HitTest::kBottomRight;
  }
}

const int kTouchDownContextResetTimeout = 500;

// Windows does not flag synthesized mouse messages from touch or pen in all
// cases. This causes us grief as we don't want to process touch and mouse
// messages concurrently. Hack as per msdn is to check if the time difference
// between the touch/pen message and the mouse move is within 500 ms and at the
// same location as the cursor.
const int kSynthesizedMouseMessagesTimeDifference = 500;

}  // namespace

// A scoping class that prevents a window from being able to redraw in response
// to invalidations that may occur within it for the lifetime of the object.
//
// Why would we want such a thing? Well, it turns out Windows has some
// "unorthodox" behavior when it comes to painting its non-client areas.
// Occasionally, Windows will paint portions of the default non-client area
// right over the top of the custom frame. This is not simply fixed by handling
// WM_NCPAINT/WM_PAINT, with some investigation it turns out that this
// rendering is being done *inside* the default implementation of some message
// handlers and functions:
//  . WM_SETTEXT
//  . WM_SETICON
//  . WM_NCLBUTTONDOWN
//  . EnableMenuItem, called from our WM_INITMENU handler
// The solution is to handle these messages and call DefWindowProc ourselves,
// but prevent the window from being able to update itself for the duration of
// the call. We do this with this class, which automatically calls its
// associated Window's lock and unlock functions as it is created and destroyed.
// See documentation in those methods for the technique used.
//
// The lock only has an effect if the window was visible upon lock creation, as
// it doesn't guard against direct visiblility changes, and multiple locks may
// exist simultaneously to handle certain nested Windows messages.
//
// This lock is disabled when DirectComposition is used and there's a child
// rendering window, as the WS_CLIPCHILDREN on the parent window should
// prevent the glitched rendering and making the window contents non-visible
// can cause a them to disappear for a frame.
//
// We normally skip locked updates when Aero is on for two reasons:
// 1. Because it isn't necessary. However, for windows without WS_CAPTION a
//    close button may still be drawn, so the resize lock remains enabled for
//    them. See http://crrev.com/130323
// 2. Because toggling the WS_VISIBLE flag may occur while the GPU process is
//    attempting to present a child window's backbuffer onscreen. When these
//    two actions race with one another, the child window will either flicker
//    or will simply stop updating entirely.
//
// IMPORTANT: Do not use this scoping object for large scopes or periods of
//            time! IT WILL PREVENT THE WINDOW FROM BEING REDRAWN! (duh).
//
// I would love to hear Raymond Chen's explanation for all this. And maybe a
// list of other messages that this applies to ;-)
class HWNDMessageHandler::ScopedRedrawLock {
 public:
  explicit ScopedRedrawLock(HWNDMessageHandler* owner)
      : owner_(owner),
        hwnd_(owner_->hwnd()),
        cancel_unlock_(false),
        should_lock_(owner_->IsVisible() && !owner->HasChildRenderingWindow() &&
                     ::IsWindow(hwnd_) &&
                     (!(GetWindowLong(hwnd_, GWL_STYLE) & WS_CAPTION) ||
                      !ui::win::IsAeroGlassEnabled())) {
    if (should_lock_)
      owner_->LockUpdates();
  }

  ~ScopedRedrawLock() {
    if (!cancel_unlock_ && should_lock_ && ::IsWindow(hwnd_))
      owner_->UnlockUpdates();
  }

  // Cancel the unlock operation, call this if the Widget is being destroyed.
  void CancelUnlockOperation() { cancel_unlock_ = true; }

 private:
  // The owner having its style changed.
  HWNDMessageHandler* owner_;
  // The owner's HWND, cached to avoid action after window destruction.
  HWND hwnd_;
  // A flag indicating that the unlock operation was canceled.
  bool cancel_unlock_;
  // If false, don't use redraw lock.
  const bool should_lock_;

  DISALLOW_COPY_AND_ASSIGN(ScopedRedrawLock);
};

// static HWNDMessageHandler member initialization.
base::LazyInstance<HWNDMessageHandler::FullscreenWindowMonitorMap>::
    DestructorAtExit HWNDMessageHandler::fullscreen_monitor_map_ =
        LAZY_INSTANCE_INITIALIZER;

////////////////////////////////////////////////////////////////////////////////
// HWNDMessageHandler, public:

long HWNDMessageHandler::last_touch_or_pen_message_time_ = 0;

HWNDMessageHandler::HWNDMessageHandler(HWNDMessageHandlerDelegate* delegate)
    : delegate_(delegate),
      fullscreen_handler_(new FullscreenHandler),
      waiting_for_close_now_(false),
      use_system_default_icon_(false),
      restored_enabled_(false),
      current_cursor_(NULL),
      previous_cursor_(NULL),
      dpi_(0),
      called_enable_non_client_dpi_scaling_(false),
      active_mouse_tracking_flags_(0),
      is_right_mouse_pressed_on_caption_(false),
      lock_updates_count_(0),
      ignore_window_pos_changes_(false),
      last_monitor_(NULL),
      is_first_nccalc_(true),
      menu_depth_(0),
      id_generator_(0),
      pen_processor_(
          &id_generator_,
          base::FeatureList::IsEnabled(features::kDirectManipulationStylus)),
      in_size_loop_(false),
      touch_down_contexts_(0),
      last_mouse_hwheel_time_(0),
      dwm_transition_desired_(false),
      sent_window_size_changing_(false),
      left_button_down_on_caption_(false),
      background_fullscreen_hack_(false),
      pointer_events_for_touch_(features::IsUsingWMPointerForTouch()),
      precision_touchpad_scroll_phase_enabled_(base::FeatureList::IsEnabled(
          features::kPrecisionTouchpadScrollPhase)),
      autohide_factory_(this) {}

HWNDMessageHandler::~HWNDMessageHandler() {
  DCHECK(delegate_->GetHWNDMessageDelegateInputMethod());
  delegate_->GetHWNDMessageDelegateInputMethod()->RemoveObserver(this);
  delegate_ = NULL;
  // Prevent calls back into this class via WNDPROC now that we've been
  // destroyed.
  ClearUserData();
}

void HWNDMessageHandler::Init(HWND parent, const gfx::Rect& bounds) {
  TRACE_EVENT0("views", "HWNDMessageHandler::Init");
  GetMonitorAndRects(bounds.ToRECT(), &last_monitor_, &last_monitor_rect_,
                     &last_work_area_);

  // Create the window.
  WindowImpl::Init(parent, bounds);

  if (!called_enable_non_client_dpi_scaling_ &&
      delegate_->HasFrame() &&
      base::win::IsProcessPerMonitorDpiAware()) {
    static auto enable_child_window_dpi_message_func = []() {
      // Derived signature; not available in headers.
      // This call gets Windows to scale the non-client area when WM_DPICHANGED
      // is fired.
      using EnableChildWindowDpiMessagePtr = LRESULT (WINAPI*)(HWND, BOOL);
      return reinterpret_cast<EnableChildWindowDpiMessagePtr>(
                 GetProcAddress(GetModuleHandle(L"user32.dll"),
                                "EnableChildWindowDpiMessage"));
    }();
    if (enable_child_window_dpi_message_func)
      enable_child_window_dpi_message_func(hwnd(), TRUE);
  }

  prop_window_target_.reset(new ui::ViewProp(hwnd(),
                            ui::WindowEventTarget::kWin32InputEventTarget,
                            static_cast<ui::WindowEventTarget*>(this)));
  DCHECK(delegate_->GetHWNDMessageDelegateInputMethod());
  delegate_->GetHWNDMessageDelegateInputMethod()->AddObserver(this);

  // Disable pen flicks (http://crbug.com/506977)
  base::win::DisableFlicks(hwnd());
}

void HWNDMessageHandler::InitModalType(ui::ModalType modal_type) {
  if (modal_type == ui::MODAL_TYPE_NONE)
    return;
  // We implement modality by crawling up the hierarchy of windows starting
  // at the owner, disabling all of them so that they don't receive input
  // messages.
  HWND start = ::GetWindow(hwnd(), GW_OWNER);
  while (start) {
    ::EnableWindow(start, FALSE);
    start = ::GetParent(start);
  }
}

void HWNDMessageHandler::Close() {
  if (!IsWindow(hwnd()))
    return;  // No need to do anything.

  // Let's hide ourselves right away.
  Hide();

  // Modal dialog windows disable their owner windows; re-enable them now so
  // they can activate as foreground windows upon this window's destruction.
  RestoreEnabledIfNecessary();

  // Re-enable flicks which removes the window property.
  base::win::EnableFlicks(hwnd());

  if (!waiting_for_close_now_) {
    // And we delay the close so that if we are called from an ATL callback,
    // we don't destroy the window before the callback returned (as the caller
    // may delete ourselves on destroy and the ATL callback would still
    // dereference us when the callback returns).
    waiting_for_close_now_ = true;
    base::ThreadTaskRunnerHandle::Get()->PostTask(
        FROM_HERE, base::BindOnce(&HWNDMessageHandler::CloseNow,
                                  msg_handler_weak_factory_.GetWeakPtr()));
  }
}

void HWNDMessageHandler::CloseNow() {
  // We may already have been destroyed if the selection resulted in a tab
  // switch which will have reactivated the browser window and closed us, so
  // we need to check to see if we're still a window before trying to destroy
  // ourself.
  waiting_for_close_now_ = false;
  if (IsWindow(hwnd()))
    DestroyWindow(hwnd());
}

gfx::Rect HWNDMessageHandler::GetWindowBoundsInScreen() const {
  RECT r;
  GetWindowRect(hwnd(), &r);
  return gfx::Rect(r);
}

gfx::Rect HWNDMessageHandler::GetClientAreaBoundsInScreen() const {
  RECT r;
  GetClientRect(hwnd(), &r);
  POINT point = { r.left, r.top };
  ClientToScreen(hwnd(), &point);
  return gfx::Rect(point.x, point.y, r.right - r.left, r.bottom - r.top);
}

gfx::Rect HWNDMessageHandler::GetRestoredBounds() const {
  // If we're in fullscreen mode, we've changed the normal bounds to the monitor
  // rect, so return the saved bounds instead.
  if (IsFullscreen())
    return fullscreen_handler_->GetRestoreBounds();

  gfx::Rect bounds;
  GetWindowPlacement(&bounds, NULL);
  return bounds;
}

gfx::Rect HWNDMessageHandler::GetClientAreaBounds() const {
  if (IsMinimized())
    return gfx::Rect();
  if (delegate_->WidgetSizeIsClientSize())
    return GetClientAreaBoundsInScreen();
  return GetWindowBoundsInScreen();
}

void HWNDMessageHandler::GetWindowPlacement(
    gfx::Rect* bounds,
    ui::WindowShowState* show_state) const {
  WINDOWPLACEMENT wp;
  wp.length = sizeof(wp);
  const bool succeeded = !!::GetWindowPlacement(hwnd(), &wp);
  DCHECK(succeeded);

  if (bounds != NULL) {
    if (wp.showCmd == SW_SHOWNORMAL) {
      // GetWindowPlacement can return misleading position if a normalized
      // window was resized using Aero Snap feature (see comment 9 in bug
      // 36421). As a workaround, using GetWindowRect for normalized windows.
      const bool succeeded = GetWindowRect(hwnd(), &wp.rcNormalPosition) != 0;
      DCHECK(succeeded);

      *bounds = gfx::Rect(wp.rcNormalPosition);
    } else {
      MONITORINFO mi;
      mi.cbSize = sizeof(mi);
      const bool succeeded = GetMonitorInfo(
          MonitorFromWindow(hwnd(), MONITOR_DEFAULTTONEAREST), &mi) != 0;
      DCHECK(succeeded);

      *bounds = gfx::Rect(wp.rcNormalPosition);
      // Convert normal position from workarea coordinates to screen
      // coordinates.
      bounds->Offset(mi.rcWork.left - mi.rcMonitor.left,
                     mi.rcWork.top - mi.rcMonitor.top);
    }
  }

  if (show_state) {
    if (wp.showCmd == SW_SHOWMAXIMIZED)
      *show_state = ui::SHOW_STATE_MAXIMIZED;
    else if (wp.showCmd == SW_SHOWMINIMIZED)
      *show_state = ui::SHOW_STATE_MINIMIZED;
    else
      *show_state = ui::SHOW_STATE_NORMAL;
  }
}

void HWNDMessageHandler::SetBounds(const gfx::Rect& bounds_in_pixels,
                                   bool force_size_changed) {
  background_fullscreen_hack_ = false;
  SetBoundsInternal(bounds_in_pixels, force_size_changed);
}

void HWNDMessageHandler::SetDwmFrameExtension(DwmFrameState state) {
  if (!delegate_->HasFrame() && ui::win::IsAeroGlassEnabled() &&
      !is_translucent_) {
    MARGINS m = {0, 0, 0, 0};
    if (state == DwmFrameState::ON)
      m = {0, 0, 1, 0};
    DwmExtendFrameIntoClientArea(hwnd(), &m);
  }
}

void HWNDMessageHandler::SetSize(const gfx::Size& size) {
  SetWindowPos(hwnd(), NULL, 0, 0, size.width(), size.height(),
               SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOMOVE);
}

void HWNDMessageHandler::CenterWindow(const gfx::Size& size) {
  HWND parent = GetParent(hwnd());
  if (!IsWindow(hwnd()))
    parent = ::GetWindow(hwnd(), GW_OWNER);
  gfx::CenterAndSizeWindow(parent, hwnd(), size);
}

void HWNDMessageHandler::SetRegion(HRGN region) {
  custom_window_region_.reset(region);
  ResetWindowRegion(true, true);
}

void HWNDMessageHandler::StackAbove(HWND other_hwnd) {
  // Windows API allows to stack behind another windows only.
  DCHECK(other_hwnd);
  HWND next_window = GetNextWindow(other_hwnd, GW_HWNDPREV);
  SetWindowPos(hwnd(), next_window ? next_window : HWND_TOP, 0, 0, 0, 0,
               SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE);
}

void HWNDMessageHandler::StackAtTop() {
  SetWindowPos(hwnd(), HWND_TOP, 0, 0, 0, 0,
               SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE);
}

void HWNDMessageHandler::Show() {
  if (IsWindow(hwnd())) {
    if (!(GetWindowLong(hwnd(), GWL_EXSTYLE) & WS_EX_TRANSPARENT) &&
        !(GetWindowLong(hwnd(), GWL_EXSTYLE) & WS_EX_NOACTIVATE)) {
      ShowWindowWithState(ui::SHOW_STATE_NORMAL);
    } else {
      ShowWindowWithState(ui::SHOW_STATE_INACTIVE);
    }
  }
}

void HWNDMessageHandler::ShowWindowWithState(ui::WindowShowState show_state) {
  TRACE_EVENT0("views", "HWNDMessageHandler::ShowWindowWithState");
  DWORD native_show_state;
  switch (show_state) {
    case ui::SHOW_STATE_INACTIVE:
      native_show_state = SW_SHOWNOACTIVATE;
      break;
    case ui::SHOW_STATE_MAXIMIZED:
      native_show_state = SW_SHOWMAXIMIZED;
      break;
    case ui::SHOW_STATE_MINIMIZED:
      native_show_state = SW_SHOWMINIMIZED;
      break;
    case ui::SHOW_STATE_NORMAL:
      native_show_state = SW_SHOWNORMAL;
      break;
    case ui::SHOW_STATE_FULLSCREEN:
      native_show_state = SW_SHOWNORMAL;
      SetFullscreen(true);
      break;
    default:
      native_show_state = delegate_->GetInitialShowState();
      break;
  }

  ShowWindow(hwnd(), native_show_state);
  // When launched from certain programs like bash and Windows Live Messenger,
  // show_state is set to SW_HIDE, so we need to correct that condition. We
  // don't just change show_state to SW_SHOWNORMAL because MSDN says we must
  // always first call ShowWindow with the specified value from STARTUPINFO,
  // otherwise all future ShowWindow calls will be ignored (!!#@@#!). Instead,
  // we call ShowWindow again in this case.
  if (native_show_state == SW_HIDE) {
    native_show_state = SW_SHOWNORMAL;
    ShowWindow(hwnd(), native_show_state);
  }

  // We need to explicitly activate the window if we've been shown with a state
  // that should activate, because if we're opened from a desktop shortcut while
  // an existing window is already running it doesn't seem to be enough to use
  // one of these flags to activate the window.
  if (native_show_state == SW_SHOWNORMAL ||
      native_show_state == SW_SHOWMAXIMIZED)
    Activate();

  if (!delegate_->HandleInitialFocus(show_state))
    SetInitialFocus();
}

void HWNDMessageHandler::ShowMaximizedWithBounds(const gfx::Rect& bounds) {
  WINDOWPLACEMENT placement = { 0 };
  placement.length = sizeof(WINDOWPLACEMENT);
  placement.showCmd = SW_SHOWMAXIMIZED;
  placement.rcNormalPosition = bounds.ToRECT();
  SetWindowPlacement(hwnd(), &placement);

  // We need to explicitly activate the window, because if we're opened from a
  // desktop shortcut while an existing window is already running it doesn't
  // seem to be enough to use SW_SHOWMAXIMIZED to activate the window.
  Activate();
}

void HWNDMessageHandler::Hide() {
  if (IsWindow(hwnd())) {
    // NOTE: Be careful not to activate any windows here (for example, calling
    // ShowWindow(SW_HIDE) will automatically activate another window).  This
    // code can be called while a window is being deactivated, and activating
    // another window will screw up the activation that is already in progress.
    SetWindowPos(hwnd(), NULL, 0, 0, 0, 0,
                 SWP_HIDEWINDOW | SWP_NOACTIVATE | SWP_NOMOVE |
                 SWP_NOREPOSITION | SWP_NOSIZE | SWP_NOZORDER);
  }
}

void HWNDMessageHandler::Maximize() {
  ExecuteSystemMenuCommand(SC_MAXIMIZE);
}

void HWNDMessageHandler::Minimize() {
  ExecuteSystemMenuCommand(SC_MINIMIZE);
  delegate_->HandleNativeBlur(NULL);
}

void HWNDMessageHandler::Restore() {
  ExecuteSystemMenuCommand(SC_RESTORE);
}

void HWNDMessageHandler::Activate() {
  if (IsMinimized())
    ::ShowWindow(hwnd(), SW_RESTORE);
  ::SetWindowPos(hwnd(), HWND_TOP, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
  SetForegroundWindow(hwnd());
}

void HWNDMessageHandler::Deactivate() {
  HWND next_hwnd = ::GetNextWindow(hwnd(), GW_HWNDNEXT);
  while (next_hwnd) {
    if (::IsWindowVisible(next_hwnd)) {
      ::SetForegroundWindow(next_hwnd);
      return;
    }
    next_hwnd = ::GetNextWindow(next_hwnd, GW_HWNDNEXT);
  }
}

void HWNDMessageHandler::SetAlwaysOnTop(bool on_top) {
  ::SetWindowPos(hwnd(), on_top ? HWND_TOPMOST : HWND_NOTOPMOST,
                 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
}

bool HWNDMessageHandler::IsVisible() const {
  return !!::IsWindowVisible(hwnd());
}

bool HWNDMessageHandler::IsActive() const {
  return GetActiveWindow() == hwnd();
}

bool HWNDMessageHandler::IsMinimized() const {
  return !!::IsIconic(hwnd());
}

bool HWNDMessageHandler::IsMaximized() const {
  return !!::IsZoomed(hwnd()) && !IsFullscreen();
}

bool HWNDMessageHandler::IsFullscreen() const {
  return fullscreen_handler_->fullscreen();
}

bool HWNDMessageHandler::IsAlwaysOnTop() const {
  return (GetWindowLong(hwnd(), GWL_EXSTYLE) & WS_EX_TOPMOST) != 0;
}

bool HWNDMessageHandler::RunMoveLoop(const gfx::Vector2d& drag_offset,
                                     bool hide_on_escape) {
  ReleaseCapture();
  MoveLoopMouseWatcher watcher(this, hide_on_escape);
  // In Aura, we handle touch events asynchronously. So we need to allow nested
  // tasks while in windows move loop.
  base::MessageLoopCurrent::ScopedNestableTaskAllower allow_nested;

  SendMessage(hwnd(), WM_SYSCOMMAND, SC_MOVE | 0x0002, GetMessagePos());
  // Windows doesn't appear to offer a way to determine whether the user
  // canceled the move or not. We assume if the user released the mouse it was
  // successful.
  return watcher.got_mouse_up();
}

void HWNDMessageHandler::EndMoveLoop() {
  SendMessage(hwnd(), WM_CANCELMODE, 0, 0);
}

void HWNDMessageHandler::SendFrameChanged() {
  SetWindowPos(hwnd(), NULL, 0, 0, 0, 0,
      SWP_FRAMECHANGED | SWP_NOACTIVATE | SWP_NOCOPYBITS |
      SWP_NOMOVE | SWP_NOOWNERZORDER | SWP_NOREPOSITION |
      SWP_NOSENDCHANGING | SWP_NOSIZE | SWP_NOZORDER);
}

void HWNDMessageHandler::FlashFrame(bool flash) {
  FLASHWINFO fwi;
  fwi.cbSize = sizeof(fwi);
  fwi.hwnd = hwnd();
  if (flash) {
    fwi.dwFlags = custom_window_region_.is_valid() ? FLASHW_TRAY : FLASHW_ALL;
    fwi.uCount = 4;
    fwi.dwTimeout = 0;
  } else {
    fwi.dwFlags = FLASHW_STOP;
  }
  FlashWindowEx(&fwi);
}

void HWNDMessageHandler::ClearNativeFocus() {
  ::SetFocus(hwnd());
}

void HWNDMessageHandler::SetCapture() {
  DCHECK(!HasCapture());
  ::SetCapture(hwnd());
}

void HWNDMessageHandler::ReleaseCapture() {
  if (HasCapture())
    ::ReleaseCapture();
}

bool HWNDMessageHandler::HasCapture() const {
  return ::GetCapture() == hwnd();
}

void HWNDMessageHandler::SetVisibilityChangedAnimationsEnabled(bool enabled) {
  int dwm_value = enabled ? FALSE : TRUE;
  DwmSetWindowAttribute(hwnd(), DWMWA_TRANSITIONS_FORCEDISABLED, &dwm_value,
                        sizeof(dwm_value));
}

bool HWNDMessageHandler::SetTitle(const base::string16& title) {
  base::string16 current_title;
  size_t len_with_null = GetWindowTextLength(hwnd()) + 1;
  if (len_with_null == 1 && title.length() == 0)
    return false;
  if (len_with_null - 1 == title.length() &&
      GetWindowText(hwnd(),
                    base::WriteInto(&current_title, len_with_null),
                    len_with_null) &&
      current_title == title)
    return false;
  SetWindowText(hwnd(), title.c_str());
  return true;
}

void HWNDMessageHandler::SetCursor(HCURSOR cursor) {
  if (cursor) {
    previous_cursor_ = ::SetCursor(cursor);
    current_cursor_ = cursor;
  } else if (previous_cursor_) {
    ::SetCursor(previous_cursor_);
    previous_cursor_ = NULL;
  }
}

void HWNDMessageHandler::FrameTypeChanged() {
  if (!custom_window_region_.is_valid() && IsFrameSystemDrawn())
    dwm_transition_desired_ = true;
  if (!dwm_transition_desired_ || !IsFullscreen())
    PerformDwmTransition();
}

void HWNDMessageHandler::SetWindowIcons(const gfx::ImageSkia& window_icon,
                                        const gfx::ImageSkia& app_icon) {
  if (!window_icon.isNull()) {
    base::win::ScopedHICON previous_icon = std::move(window_icon_);
    window_icon_ = IconUtil::CreateHICONFromSkBitmap(*window_icon.bitmap());
    SendMessage(hwnd(), WM_SETICON, ICON_SMALL,
                reinterpret_cast<LPARAM>(window_icon_.get()));
  }
  if (!app_icon.isNull()) {
    base::win::ScopedHICON previous_icon = std::move(app_icon_);
    app_icon_ = IconUtil::CreateHICONFromSkBitmap(*app_icon.bitmap());
    SendMessage(hwnd(), WM_SETICON, ICON_BIG,
                reinterpret_cast<LPARAM>(app_icon_.get()));
  }
}

void HWNDMessageHandler::SetFullscreen(bool fullscreen) {
  background_fullscreen_hack_ = false;
  fullscreen_handler()->SetFullscreen(fullscreen);

  // Add the fullscreen window to the fullscreen window map which is used to
  // handle window activations.
  HMONITOR monitor = MonitorFromWindow(hwnd(), MONITOR_DEFAULTTOPRIMARY);
  if (fullscreen) {
    (fullscreen_monitor_map_.Get())[monitor] = this;
  } else {
    FullscreenWindowMonitorMap::iterator iter =
        fullscreen_monitor_map_.Get().find(monitor);
    if (iter != fullscreen_monitor_map_.Get().end())
      fullscreen_monitor_map_.Get().erase(iter);
  }
  // If we are out of fullscreen and there was a pending DWM transition for the
  // window, then go ahead and do it now.
  if (!fullscreen && dwm_transition_desired_)
    PerformDwmTransition();
}

void HWNDMessageHandler::SetAspectRatio(float aspect_ratio) {
  // If the aspect ratio is not in the valid range, do nothing.
  DCHECK_GT(aspect_ratio, 0.0f);

  aspect_ratio_ = aspect_ratio;

  // When the aspect ratio is set, size the window to adhere to it. This keeps
  // the same origin point as the original window.
  RECT window_rect;
  if (GetWindowRect(hwnd(), &window_rect)) {
    gfx::Rect rect(window_rect);

    SizeRectToAspectRatio(WMSZ_BOTTOMRIGHT, &rect);
    SetBoundsInternal(rect, false);
  }
}

void HWNDMessageHandler::SizeConstraintsChanged() {
  LONG style = GetWindowLong(hwnd(), GWL_STYLE);
  // Ignore if this is not a standard window.
  if (style & (WS_POPUP | WS_CHILD))
    return;

  // Windows cannot have WS_THICKFRAME set if translucent.
  // See CalculateWindowStylesFromInitParams().
  if (delegate_->CanResize() && !is_translucent_) {
    style |= WS_THICKFRAME | WS_MAXIMIZEBOX;
    if (!delegate_->CanMaximize())
      style &= ~WS_MAXIMIZEBOX;
  } else {
    style &= ~(WS_THICKFRAME | WS_MAXIMIZEBOX);
  }
  if (delegate_->CanMinimize()) {
    style |= WS_MINIMIZEBOX;
  } else {
    style &= ~WS_MINIMIZEBOX;
  }
  SetWindowLong(hwnd(), GWL_STYLE, style);
}

bool HWNDMessageHandler::HasChildRenderingWindow() {
  // This can change dynamically if the system switches between GPU and
  // software rendering.
  return gfx::RenderingWindowManager::GetInstance()->HasValidChildWindow(
      hwnd());
}

////////////////////////////////////////////////////////////////////////////////
// HWNDMessageHandler, gfx::WindowImpl overrides:

HICON HWNDMessageHandler::GetDefaultWindowIcon() const {
  if (use_system_default_icon_)
    return nullptr;
  return ViewsDelegate::GetInstance()
             ? ViewsDelegate::GetInstance()->GetDefaultWindowIcon()
             : nullptr;
}

HICON HWNDMessageHandler::GetSmallWindowIcon() const {
  if (use_system_default_icon_)
    return nullptr;
  return ViewsDelegate::GetInstance()
             ? ViewsDelegate::GetInstance()->GetSmallWindowIcon()
             : nullptr;
}

LRESULT HWNDMessageHandler::OnWndProc(UINT message,
                                      WPARAM w_param,
                                      LPARAM l_param) {
  HWND window = hwnd();
  LRESULT result = 0;

  if (delegate_ && delegate_->PreHandleMSG(message, w_param, l_param, &result))
    return result;

  // Otherwise we handle everything else.
  // NOTE: We inline ProcessWindowMessage() as 'this' may be destroyed during
  // dispatch and ProcessWindowMessage() doesn't deal with that well.
  const BOOL old_msg_handled = msg_handled_;
  base::WeakPtr<HWNDMessageHandler> ref(msg_handler_weak_factory_.GetWeakPtr());
  const BOOL processed =
      _ProcessWindowMessage(window, message, w_param, l_param, result, 0);
  if (!ref)
    return 0;
  msg_handled_ = old_msg_handled;

  if (!processed) {
    result = DefWindowProc(window, message, w_param, l_param);
    // DefWindowProc() may have destroyed the window and/or us in a nested
    // message loop.
    if (!ref || !::IsWindow(window))
      return result;
  }

  if (delegate_) {
    delegate_->PostHandleMSG(message, w_param, l_param);
    if (message == WM_NCDESTROY) {
      RestoreEnabledIfNecessary();
      delegate_->HandleDestroyed();
    }
  }

  if (message == WM_ACTIVATE && IsTopLevelWindow(window))
    PostProcessActivateMessage(LOWORD(w_param), !!HIWORD(w_param),
                               reinterpret_cast<HWND>(l_param));
  return result;
}

void HWNDMessageHandler::OnFocus() {}

void HWNDMessageHandler::OnBlur() {}

void HWNDMessageHandler::OnCaretBoundsChanged(
    const ui::TextInputClient* client) {
  if (!client || client->GetTextInputType() == ui::TEXT_INPUT_TYPE_NONE)
    return;

  if (!ax_system_caret_)
    ax_system_caret_ = std::make_unique<ui::AXSystemCaretWin>(hwnd());

  const gfx::Rect dip_caret_bounds(client->GetCaretBounds());
  gfx::Rect caret_bounds =
      display::win::ScreenWin::DIPToScreenRect(hwnd(), dip_caret_bounds);
  // Collapse any selection.
  caret_bounds.set_width(1);
  ax_system_caret_->MoveCaretTo(caret_bounds);
}

void HWNDMessageHandler::OnTextInputStateChanged(
    const ui::TextInputClient* client) {}

void HWNDMessageHandler::OnInputMethodDestroyed(
    const ui::InputMethod* input_method) {
  DestroyAXSystemCaret();
}

void HWNDMessageHandler::OnShowVirtualKeyboardIfEnabled() {}

LRESULT HWNDMessageHandler::HandleMouseMessage(unsigned int message,
                                               WPARAM w_param,
                                               LPARAM l_param,
                                               bool* handled) {
  // Don't track forwarded mouse messages. We expect the caller to track the
  // mouse.
  base::WeakPtr<HWNDMessageHandler> ref(msg_handler_weak_factory_.GetWeakPtr());
  LRESULT ret = HandleMouseEventInternal(message, w_param, l_param, false);
  *handled = !ref.get() || msg_handled_;
  return ret;
}

LRESULT HWNDMessageHandler::HandleKeyboardMessage(unsigned int message,
                                                  WPARAM w_param,
                                                  LPARAM l_param,
                                                  bool* handled) {
  base::WeakPtr<HWNDMessageHandler> ref(msg_handler_weak_factory_.GetWeakPtr());
  LRESULT ret = 0;
  if ((message == WM_CHAR) || (message == WM_SYSCHAR))
    ret = OnImeMessages(message, w_param, l_param);
  else
    ret = OnKeyEvent(message, w_param, l_param);
  *handled = !ref.get() || msg_handled_;
  return ret;
}

LRESULT HWNDMessageHandler::HandleTouchMessage(unsigned int message,
                                               WPARAM w_param,
                                               LPARAM l_param,
                                               bool* handled) {
  base::WeakPtr<HWNDMessageHandler> ref(msg_handler_weak_factory_.GetWeakPtr());
  LRESULT ret = OnTouchEvent(message, w_param, l_param);
  *handled = !ref.get() || msg_handled_;
  return ret;
}

LRESULT HWNDMessageHandler::HandlePointerMessage(unsigned int message,
                                                 WPARAM w_param,
                                                 LPARAM l_param,
                                                 bool* handled) {
  base::WeakPtr<HWNDMessageHandler> ref(msg_handler_weak_factory_.GetWeakPtr());
  LRESULT ret = OnPointerEvent(message, w_param, l_param);
  *handled = !ref.get() || msg_handled_;
  return ret;
}

LRESULT HWNDMessageHandler::HandleScrollMessage(unsigned int message,
                                                WPARAM w_param,
                                                LPARAM l_param,
                                                bool* handled) {
  base::WeakPtr<HWNDMessageHandler> ref(msg_handler_weak_factory_.GetWeakPtr());
  LRESULT ret = OnScrollMessage(message, w_param, l_param);
  *handled = !ref.get() || msg_handled_;
  return ret;
}

LRESULT HWNDMessageHandler::HandleNcHitTestMessage(unsigned int message,
                                                   WPARAM w_param,
                                                   LPARAM l_param,
                                                   bool* handled) {
  base::WeakPtr<HWNDMessageHandler> ref(msg_handler_weak_factory_.GetWeakPtr());
  LRESULT ret = OnNCHitTest(
      gfx::Point(CR_GET_X_LPARAM(l_param), CR_GET_Y_LPARAM(l_param)));
  *handled = !ref.get() || msg_handled_;
  return ret;
}

void HWNDMessageHandler::HandleParentChanged() {
  // If the forwarder window's parent is changed then we need to reset our
  // context as we will not receive touch releases if the touch was initiated
  // in the forwarder window.
  touch_ids_.clear();
}

void HWNDMessageHandler::ApplyPinchZoomScale(float scale) {
  POINT cursor_pos = {0};
  ::GetCursorPos(&cursor_pos);
  ScreenToClient(hwnd(), &cursor_pos);

  ui::GestureEventDetails event_details(ui::ET_GESTURE_PINCH_UPDATE);
  event_details.set_device_type(ui::GestureDeviceType::DEVICE_TOUCHPAD);
  event_details.set_scale(scale);

  ui::GestureEvent event(cursor_pos.x, cursor_pos.y, ui::EF_NONE,
                         base::TimeTicks::Now(), event_details);
  delegate_->HandleGestureEvent(&event);
}

void HWNDMessageHandler::ApplyPinchZoomBegin() {
  POINT cursor_pos = {0};
  ::GetCursorPos(&cursor_pos);
  ScreenToClient(hwnd(), &cursor_pos);

  ui::GestureEventDetails event_details(ui::ET_GESTURE_PINCH_BEGIN);
  event_details.set_device_type(ui::GestureDeviceType::DEVICE_TOUCHPAD);

  ui::GestureEvent event(cursor_pos.x, cursor_pos.y, ui::EF_NONE,
                         base::TimeTicks::Now(), event_details);
  delegate_->HandleGestureEvent(&event);
}

void HWNDMessageHandler::ApplyPinchZoomEnd() {
  POINT cursor_pos = {0};
  ::GetCursorPos(&cursor_pos);
  ScreenToClient(hwnd(), &cursor_pos);

  ui::GestureEventDetails event_details(ui::ET_GESTURE_PINCH_END);
  event_details.set_device_type(ui::GestureDeviceType::DEVICE_TOUCHPAD);

  ui::GestureEvent event(cursor_pos.x, cursor_pos.y, ui::EF_NONE,
                         base::TimeTicks::Now(), event_details);
  delegate_->HandleGestureEvent(&event);
}

void HWNDMessageHandler::ApplyPanGestureEvent(
    int scroll_x,
    int scroll_y,
    ui::EventMomentumPhase momentum_phase,
    ui::ScrollEventPhase phase) {
  gfx::Vector2d offset{scroll_x, scroll_y};

  POINT root_location = {0};
  ::GetCursorPos(&root_location);

  POINT location = {root_location.x, root_location.y};
  ScreenToClient(hwnd(), &location);

  gfx::Point cursor_location(location);
  gfx::Point cursor_root_location(root_location);

  int modifiers = ui::GetModifiersFromKeyState();

  if (precision_touchpad_scroll_phase_enabled_) {
    ui::ScrollEvent event(ui::ET_SCROLL, cursor_location, ui::EventTimeForNow(),
                          modifiers, scroll_x, scroll_y, scroll_x, scroll_y, 2,
                          momentum_phase, phase);
    delegate_->HandleScrollEvent(&event);
  } else {
    ui::MouseWheelEvent wheel_event(
        offset, cursor_location, cursor_root_location, base::TimeTicks::Now(),
        modifiers | ui::EF_PRECISION_SCROLLING_DELTA, ui::EF_NONE);
    delegate_->HandleMouseEvent(&wheel_event);
  }
}

void HWNDMessageHandler::ApplyPanGestureScroll(int scroll_x, int scroll_y) {
  ApplyPanGestureEvent(scroll_x, scroll_y, ui::EventMomentumPhase::NONE,
                       ui::ScrollEventPhase::kUpdate);
}

void HWNDMessageHandler::ApplyPanGestureFling(int scroll_x, int scroll_y) {
  ApplyPanGestureEvent(scroll_x, scroll_y,
                       ui::EventMomentumPhase::INERTIAL_UPDATE,
                       ui::ScrollEventPhase::kNone);
}

void HWNDMessageHandler::ApplyPanGestureScrollBegin(int scroll_x,
                                                    int scroll_y) {
  // Phase information will be ingored in ApplyPanGestureEvent().
  ApplyPanGestureEvent(scroll_x, scroll_y, ui::EventMomentumPhase::NONE,
                       ui::ScrollEventPhase::kBegan);
}

void HWNDMessageHandler::ApplyPanGestureScrollEnd() {
  if (!precision_touchpad_scroll_phase_enabled_)
    return;

  ApplyPanGestureEvent(0, 0, ui::EventMomentumPhase::NONE,
                       ui::ScrollEventPhase::kEnd);
}

void HWNDMessageHandler::ApplyPanGestureFlingBegin() {
  if (!precision_touchpad_scroll_phase_enabled_)
    return;

  ApplyPanGestureEvent(0, 0, ui::EventMomentumPhase::BEGAN,
                       ui::ScrollEventPhase::kNone);
}

void HWNDMessageHandler::ApplyPanGestureFlingEnd() {
  if (!precision_touchpad_scroll_phase_enabled_)
    return;

  ApplyPanGestureEvent(0, 0, ui::EventMomentumPhase::END,
                       ui::ScrollEventPhase::kNone);
}

////////////////////////////////////////////////////////////////////////////////
// HWNDMessageHandler, private:

int HWNDMessageHandler::GetAppbarAutohideEdges(HMONITOR monitor) {
  autohide_factory_.InvalidateWeakPtrs();
  return ViewsDelegate::GetInstance()
             ? ViewsDelegate::GetInstance()->GetAppbarAutohideEdges(
                   monitor,
                   base::Bind(&HWNDMessageHandler::OnAppbarAutohideEdgesChanged,
                              autohide_factory_.GetWeakPtr()))
             : ViewsDelegate::EDGE_BOTTOM;
}

void HWNDMessageHandler::OnAppbarAutohideEdgesChanged() {
  // This triggers querying WM_NCCALCSIZE again.
  RECT client;
  GetWindowRect(hwnd(), &client);
  SetWindowPos(hwnd(), NULL, client.left, client.top,
               client.right - client.left, client.bottom - client.top,
               SWP_FRAMECHANGED);
}

void HWNDMessageHandler::SetInitialFocus() {
  if (!(GetWindowLong(hwnd(), GWL_EXSTYLE) & WS_EX_TRANSPARENT) &&
      !(GetWindowLong(hwnd(), GWL_EXSTYLE) & WS_EX_NOACTIVATE)) {
    // The window does not get keyboard messages unless we focus it.
    SetFocus(hwnd());
  }
}

void HWNDMessageHandler::PostProcessActivateMessage(
    int activation_state,
    bool minimized,
    HWND window_gaining_or_losing_activation) {
  DCHECK(IsTopLevelWindow(hwnd()));
  const bool active = activation_state != WA_INACTIVE && !minimized;
  if (delegate_->CanActivate())
    delegate_->HandleActivationChanged(active);

  if (!::IsWindow(window_gaining_or_losing_activation))
    window_gaining_or_losing_activation = ::GetForegroundWindow();

  // If the window losing activation is a fullscreen window, we reduce the size
  // of the window by 1px. i.e. Not fullscreen. This is to work around an
  // apparent bug in the Windows taskbar where in it tracks fullscreen state on
  // a per thread basis. This causes it not be a topmost window when any
  // maximized window on a thread which has a fullscreen window is active. This
  // affects the way these windows interact with the taskbar, they obscure it
  // when maximized, autohide does not work correctly, etc.
  // By reducing the size of the fullscreen window by 1px, we ensure that the
  // taskbar no longer treats the window and in turn the thread as a fullscreen
  // thread. This in turn ensures that maximized windows on the same thread
  // don't obscure the taskbar, etc.
  // Please note that this taskbar behavior only occurs if the window becoming
  // active is on the same monitor as the fullscreen window.
  if (!active) {
    if (IsFullscreen() && ::IsWindow(window_gaining_or_losing_activation)) {
      HMONITOR active_window_monitor = MonitorFromWindow(
          window_gaining_or_losing_activation, MONITOR_DEFAULTTOPRIMARY);
      HMONITOR fullscreen_window_monitor =
          MonitorFromWindow(hwnd(), MONITOR_DEFAULTTOPRIMARY);

      if (active_window_monitor == fullscreen_window_monitor)
        OnBackgroundFullscreen();
    }
  } else if (background_fullscreen_hack_) {
    // Restore the bounds of the window to fullscreen.
    DCHECK(IsFullscreen());
    MONITORINFO monitor_info = {sizeof(monitor_info)};
    GetMonitorInfo(MonitorFromWindow(hwnd(), MONITOR_DEFAULTTOPRIMARY),
                   &monitor_info);
    SetBoundsInternal(gfx::Rect(monitor_info.rcMonitor), false);
    // Inform the taskbar that this window is now a fullscreen window so it go
    // behind the window in the Z-Order. The taskbar heuristics to detect
    // fullscreen windows are not reliable. Marking it explicitly seems to work
    // around these problems.
    fullscreen_handler()->MarkFullscreen(true);
    background_fullscreen_hack_ = false;
  } else {
    // If the window becoming active has a fullscreen window on the same
    // monitor then we need to reduce the size of the fullscreen window by
    // 1 px. Please refer to the comments above for the reasoning behind
    // this.
    CheckAndHandleBackgroundFullscreenOnMonitor(
        window_gaining_or_losing_activation);
  }
}

void HWNDMessageHandler::RestoreEnabledIfNecessary() {
  if (delegate_->IsModal() && !restored_enabled_) {
    restored_enabled_ = true;
    // If we were run modally, we need to undo the disabled-ness we inflicted on
    // the owner's parent hierarchy.
    HWND start = ::GetWindow(hwnd(), GW_OWNER);
    while (start) {
      ::EnableWindow(start, TRUE);
      start = ::GetParent(start);
    }
  }
}

void HWNDMessageHandler::ExecuteSystemMenuCommand(int command) {
  if (command)
    SendMessage(hwnd(), WM_SYSCOMMAND, command, 0);
}

void HWNDMessageHandler::TrackMouseEvents(DWORD mouse_tracking_flags) {
  // Begin tracking mouse events for this HWND so that we get WM_MOUSELEAVE
  // when the user moves the mouse outside this HWND's bounds.
  if (active_mouse_tracking_flags_ == 0 || mouse_tracking_flags & TME_CANCEL) {
    if (mouse_tracking_flags & TME_CANCEL) {
      // We're about to cancel active mouse tracking, so empty out the stored
      // state.
      active_mouse_tracking_flags_ = 0;
    } else {
      active_mouse_tracking_flags_ = mouse_tracking_flags;
    }

    TRACKMOUSEEVENT tme;
    tme.cbSize = sizeof(tme);
    tme.dwFlags = mouse_tracking_flags;
    tme.hwndTrack = hwnd();
    tme.dwHoverTime = 0;
    TrackMouseEvent(&tme);
  } else if (mouse_tracking_flags != active_mouse_tracking_flags_) {
    TrackMouseEvents(active_mouse_tracking_flags_ | TME_CANCEL);
    TrackMouseEvents(mouse_tracking_flags);
  }
}

void HWNDMessageHandler::ClientAreaSizeChanged() {
  // Ignore size changes due to fullscreen windows losing activation.
  if (background_fullscreen_hack_ && !sent_window_size_changing_)
    return;
  gfx::Size s = GetClientAreaBounds().size();
  delegate_->HandleClientSizeChanged(s);

  current_window_size_message_++;
  sent_window_size_changing_ = false;
}

bool HWNDMessageHandler::GetClientAreaInsets(gfx::Insets* insets) const {
  if (delegate_->GetClientAreaInsets(insets))
    return true;
  DCHECK(insets->IsEmpty());

  // Returning false causes the default handling in OnNCCalcSize() to
  // be invoked.
  if (!delegate_->HasNonClientView() || HasSystemFrame())
    return false;

  if (IsMaximized()) {
    // Windows automatically adds a standard width border to all sides when a
    // window is maximized.
    int border_thickness = GetSystemMetrics(SM_CXSIZEFRAME);
    if (!delegate_->HasFrame())
      border_thickness -= 1;
    *insets = gfx::Insets(
        border_thickness, border_thickness, border_thickness, border_thickness);
    return true;
  }

  *insets = gfx::Insets();
  return true;
}

void HWNDMessageHandler::ResetWindowRegion(bool force, bool redraw) {
  // A native frame uses the native window region, and we don't want to mess
  // with it.
  // WS_EX_LAYERED automatically makes clicks on transparent pixels fall
  // through, but that isn't the case when using Direct3D to draw transparent
  // windows. So we route translucent windows throught to the delegate to
  // allow for a custom hit mask.
  if (!is_translucent_ && !custom_window_region_.is_valid() &&
      (IsFrameSystemDrawn() || !delegate_->HasNonClientView())) {
    if (force)
      SetWindowRgn(hwnd(), NULL, redraw);
    return;
  }

  // Changing the window region is going to force a paint. Only change the
  // window region if the region really differs.
  base::win::ScopedRegion current_rgn(CreateRectRgn(0, 0, 0, 0));
  GetWindowRgn(hwnd(), current_rgn.get());

  RECT window_rect;
  GetWindowRect(hwnd(), &window_rect);
  base::win::ScopedRegion new_region;
  if (custom_window_region_.is_valid()) {
    new_region.reset(CreateRectRgn(0, 0, 0, 0));
    CombineRgn(new_region.get(), custom_window_region_.get(), NULL, RGN_COPY);
  } else if (IsMaximized()) {
    HMONITOR monitor = MonitorFromWindow(hwnd(), MONITOR_DEFAULTTONEAREST);
    MONITORINFO mi;
    mi.cbSize = sizeof mi;
    GetMonitorInfo(monitor, &mi);
    RECT work_rect = mi.rcWork;
    OffsetRect(&work_rect, -window_rect.left, -window_rect.top);
    new_region.reset(CreateRectRgnIndirect(&work_rect));
  } else {
    gfx::Path window_mask;
    delegate_->GetWindowMask(gfx::Size(window_rect.right - window_rect.left,
                                       window_rect.bottom - window_rect.top),
                             &window_mask);
    if (!window_mask.isEmpty())
      new_region.reset(gfx::CreateHRGNFromSkPath(window_mask));
  }

  const bool has_current_region = current_rgn != 0;
  const bool has_new_region = new_region != 0;
  if (has_current_region != has_new_region ||
      (has_current_region && !EqualRgn(current_rgn.get(), new_region.get()))) {
    // SetWindowRgn takes ownership of the HRGN.
    SetWindowRgn(hwnd(), new_region.release(), redraw);
  }
}

void HWNDMessageHandler::UpdateDwmNcRenderingPolicy() {
  if (IsFullscreen())
    return;

  DWMNCRENDERINGPOLICY policy =
      custom_window_region_.is_valid() ||
              delegate_->GetFrameMode() == FrameMode::CUSTOM_DRAWN
          ? DWMNCRP_DISABLED
          : DWMNCRP_ENABLED;

  DwmSetWindowAttribute(hwnd(), DWMWA_NCRENDERING_POLICY,
                        &policy, sizeof(DWMNCRENDERINGPOLICY));
}

LRESULT HWNDMessageHandler::DefWindowProcWithRedrawLock(UINT message,
                                                        WPARAM w_param,
                                                        LPARAM l_param) {
  ScopedRedrawLock lock(this);
  // The Widget and HWND can be destroyed in the call to DefWindowProc, so use
  // the WeakPtrFactory to avoid unlocking (and crashing) after destruction.
  base::WeakPtr<HWNDMessageHandler> ref(msg_handler_weak_factory_.GetWeakPtr());
  LRESULT result = DefWindowProc(hwnd(), message, w_param, l_param);
  if (!ref)
    lock.CancelUnlockOperation();
  return result;
}

void HWNDMessageHandler::LockUpdates() {
  if (++lock_updates_count_ == 1) {
    SetWindowLong(hwnd(), GWL_STYLE,
                  GetWindowLong(hwnd(), GWL_STYLE) & ~WS_VISIBLE);
  }
}

void HWNDMessageHandler::UnlockUpdates() {
  if (--lock_updates_count_ <= 0) {
    SetWindowLong(hwnd(), GWL_STYLE,
                  GetWindowLong(hwnd(), GWL_STYLE) | WS_VISIBLE);
    lock_updates_count_ = 0;
  }
}

void HWNDMessageHandler::ForceRedrawWindow(int attempts) {
  if (ui::IsWorkstationLocked()) {
    // Presents will continue to fail as long as the input desktop is
    // unavailable.
    if (--attempts <= 0)
      return;
    base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
        FROM_HERE,
        base::BindOnce(&HWNDMessageHandler::ForceRedrawWindow,
                       msg_handler_weak_factory_.GetWeakPtr(), attempts),
        base::TimeDelta::FromMilliseconds(500));
    return;
  }
  InvalidateRect(hwnd(), NULL, FALSE);
}

bool HWNDMessageHandler::IsFrameSystemDrawn() const {
  FrameMode frame_mode = delegate_->GetFrameMode();
  return frame_mode == FrameMode::SYSTEM_DRAWN ||
         frame_mode == FrameMode::SYSTEM_DRAWN_NO_CONTROLS;
}

bool HWNDMessageHandler::HasSystemFrame() const {
  return delegate_->HasFrame() && IsFrameSystemDrawn();
}

// Message handlers ------------------------------------------------------------

void HWNDMessageHandler::OnActivateApp(BOOL active, DWORD thread_id) {
  if (delegate_->HasNonClientView() && !active &&
      thread_id != GetCurrentThreadId()) {
    delegate_->HandleAppDeactivated();
    // Also update the native frame if it is rendering the non-client area.
    if (HasSystemFrame())
      DefWindowProcWithRedrawLock(WM_NCACTIVATE, FALSE, 0);
  }
}

BOOL HWNDMessageHandler::OnAppCommand(HWND window,
                                      short command,
                                      WORD device,
                                      int keystate) {
  BOOL handled = !!delegate_->HandleAppCommand(command);
  SetMsgHandled(handled);
  // Make sure to return TRUE if the event was handled or in some cases the
  // system will execute the default handler which can cause bugs like going
  // forward or back two pages instead of one.
  return handled;
}

void HWNDMessageHandler::OnCancelMode() {
  delegate_->HandleCancelMode();
  // Need default handling, otherwise capture and other things aren't canceled.
  SetMsgHandled(FALSE);
}

void HWNDMessageHandler::OnCaptureChanged(HWND window) {
  delegate_->HandleCaptureLost();
}

void HWNDMessageHandler::OnClose() {
  delegate_->HandleClose();
}

void HWNDMessageHandler::OnCommand(UINT notification_code,
                                   int command,
                                   HWND window) {
  // If the notification code is > 1 it means it is control specific and we
  // should ignore it.
  if (notification_code > 1 || delegate_->HandleAppCommand(command))
    SetMsgHandled(FALSE);
}

LRESULT HWNDMessageHandler::OnCreate(CREATESTRUCT* create_struct) {
  if (is_translucent_) {
    // This is part of the magic to emulate layered windows with Aura
    // see the explanation elsewere when we set is_translucent_.
    MARGINS margins = {-1, -1, -1, -1};
    DwmExtendFrameIntoClientArea(hwnd(), &margins);

    ::SetProp(hwnd(), ui::kWindowTranslucent, reinterpret_cast<HANDLE>(1));
  }

  fullscreen_handler_->set_hwnd(hwnd());

  // This message initializes the window so that focus border are shown for
  // windows.
  SendMessage(hwnd(),
              WM_CHANGEUISTATE,
              MAKELPARAM(UIS_CLEAR, UISF_HIDEFOCUS),
              0);

  if (!delegate_->HasFrame()) {
    SetWindowLong(hwnd(), GWL_STYLE,
                  GetWindowLong(hwnd(), GWL_STYLE) & ~WS_CAPTION);
    SendFrameChanged();
  }

  // Get access to a modifiable copy of the system menu.
  GetSystemMenu(hwnd(), false);

  if (!pointer_events_for_touch_)
    RegisterTouchWindow(hwnd(), TWF_WANTPALM);

  // We need to allow the delegate to size its contents since the window may not
  // receive a size notification when its initial bounds are specified at window
  // creation time.
  ClientAreaSizeChanged();

  delegate_->HandleCreate();

  windows_session_change_observer_.reset(new WindowsSessionChangeObserver(
      base::Bind(&HWNDMessageHandler::OnSessionChange,
                 base::Unretained(this))));

  float scale_factor = display::win::ScreenWin::GetScaleFactorForHWND(hwnd());
  dpi_ = display::win::GetDPIFromScalingFactor(scale_factor);

  // TODO(beng): move more of NWW::OnCreate here.
  return 0;
}

void HWNDMessageHandler::OnDestroy() {
  ::RemoveProp(hwnd(), ui::kWindowTranslucent);
  windows_session_change_observer_.reset(nullptr);
  delegate_->HandleDestroying();
  // If the window going away is a fullscreen window then remove its references
  // from the full screen window map.
  for (auto iter = fullscreen_monitor_map_.Get().begin();
       iter != fullscreen_monitor_map_.Get().end();
       iter++) {
    if (iter->second == this) {
      fullscreen_monitor_map_.Get().erase(iter);
      break;
    }
  }
}

void HWNDMessageHandler::OnDisplayChange(UINT bits_per_pixel,
                                         const gfx::Size& screen_size) {
  delegate_->HandleDisplayChange();
  // Force a WM_NCCALCSIZE to occur to ensure that we handle auto hide
  // taskbars correctly.
  SendFrameChanged();
}

LRESULT HWNDMessageHandler::OnDwmCompositionChanged(UINT msg,
                                                    WPARAM w_param,
                                                    LPARAM l_param) {
  if (!delegate_->HasNonClientView()) {
    SetMsgHandled(FALSE);
    return 0;
  }

  FrameTypeChanged();
  return 0;
}

LRESULT HWNDMessageHandler::OnDpiChanged(UINT msg,
                                         WPARAM w_param,
                                         LPARAM l_param) {
  if (LOWORD(w_param) != HIWORD(w_param))
    NOTIMPLEMENTED() << "Received non-square scaling factors";

  int dpi;
  float scaling_factor;
  if (display::Display::HasForceDeviceScaleFactor()) {
    scaling_factor = display::Display::GetForcedDeviceScaleFactor();
    dpi = display::win::GetDPIFromScalingFactor(scaling_factor);
  } else {
    dpi = LOWORD(w_param);
    scaling_factor = display::win::GetScalingFactorFromDPI(dpi_);
  }

  // The first WM_DPICHANGED originates from EnableChildWindowDpiMessage during
  // initialization. We don't want to propagate this as the client is already
  // set at the current scale factor and may cause the window to display too
  // soon. See http://crbug.com/625076.
  if (dpi_ == dpi)
    return 0;

  dpi_ = dpi;
  SetBoundsInternal(gfx::Rect(*reinterpret_cast<RECT*>(l_param)), false);
  delegate_->HandleWindowScaleFactorChanged(scaling_factor);
  return 0;
}

void HWNDMessageHandler::OnEnterMenuLoop(BOOL from_track_popup_menu) {
  if (menu_depth_++ == 0)
    delegate_->HandleMenuLoop(true);
}

void HWNDMessageHandler::OnEnterSizeMove() {
  delegate_->HandleBeginWMSizeMove();
  SetMsgHandled(FALSE);
}

LRESULT HWNDMessageHandler::OnEraseBkgnd(HDC dc) {
  // Needed to prevent resize flicker.
  return 1;
}

void HWNDMessageHandler::OnExitMenuLoop(BOOL is_shortcut_menu) {
  if (--menu_depth_ == 0)
    delegate_->HandleMenuLoop(false);
  DCHECK_GE(0, menu_depth_);
}

void HWNDMessageHandler::OnExitSizeMove() {
  delegate_->HandleEndWMSizeMove();
  SetMsgHandled(FALSE);
  // If the window was moved to a monitor which has a fullscreen window active,
  // we need to reduce the size of the fullscreen window by 1px.
  CheckAndHandleBackgroundFullscreenOnMonitor(hwnd());
}

void HWNDMessageHandler::OnGetMinMaxInfo(MINMAXINFO* minmax_info) {
  gfx::Size min_window_size;
  gfx::Size max_window_size;
  delegate_->GetMinMaxSize(&min_window_size, &max_window_size);
  min_window_size = delegate_->DIPToScreenSize(min_window_size);
  max_window_size = delegate_->DIPToScreenSize(max_window_size);


  // Add the native frame border size to the minimum and maximum size if the
  // view reports its size as the client size.
  if (delegate_->WidgetSizeIsClientSize()) {
    RECT client_rect, window_rect;
    GetClientRect(hwnd(), &client_rect);
    GetWindowRect(hwnd(), &window_rect);
    CR_DEFLATE_RECT(&window_rect, &client_rect);
    min_window_size.Enlarge(window_rect.right - window_rect.left,
                            window_rect.bottom - window_rect.top);
    // Either axis may be zero, so enlarge them independently.
    if (max_window_size.width())
      max_window_size.Enlarge(window_rect.right - window_rect.left, 0);
    if (max_window_size.height())
      max_window_size.Enlarge(0, window_rect.bottom - window_rect.top);
  }
  minmax_info->ptMinTrackSize.x = min_window_size.width();
  minmax_info->ptMinTrackSize.y = min_window_size.height();
  if (max_window_size.width() || max_window_size.height()) {
    if (!max_window_size.width())
      max_window_size.set_width(GetSystemMetrics(SM_CXMAXTRACK));
    if (!max_window_size.height())
      max_window_size.set_height(GetSystemMetrics(SM_CYMAXTRACK));
    minmax_info->ptMaxTrackSize.x = max_window_size.width();
    minmax_info->ptMaxTrackSize.y = max_window_size.height();
  }
  SetMsgHandled(FALSE);
}

LRESULT HWNDMessageHandler::OnGetObject(UINT message,
                                        WPARAM w_param,
                                        LPARAM l_param) {
  LRESULT reference_result = static_cast<LRESULT>(0L);

  // Only the lower 32 bits of l_param are valid when checking the object id
  // because it sometimes gets sign-extended incorrectly (but not always).
  DWORD obj_id = static_cast<DWORD>(static_cast<DWORD_PTR>(l_param));

  // Accessibility readers will send an OBJID_CLIENT message
  if (delegate_->GetNativeViewAccessible() &&
      static_cast<DWORD>(OBJID_CLIENT) == obj_id) {
    // Retrieve MSAA dispatch object for the root view.
    Microsoft::WRL::ComPtr<IAccessible> root(
        delegate_->GetNativeViewAccessible());
    reference_result = LresultFromObject(IID_IAccessible, w_param,
        static_cast<IAccessible*>(root.Detach()));
  } else if (::GetFocus() == hwnd() && ax_system_caret_ &&
             static_cast<DWORD>(OBJID_CARET) == obj_id) {
    Microsoft::WRL::ComPtr<IAccessible> ax_system_caret_accessible =
        ax_system_caret_->GetCaret();
    reference_result = LresultFromObject(IID_IAccessible, w_param,
                                         ax_system_caret_accessible.Detach());
  }

  return reference_result;
}

LRESULT HWNDMessageHandler::OnImeMessages(UINT message,
                                          WPARAM w_param,
                                          LPARAM l_param) {
  LRESULT result = 0;
  base::WeakPtr<HWNDMessageHandler> ref(msg_handler_weak_factory_.GetWeakPtr());
  const bool msg_handled =
      delegate_->HandleIMEMessage(message, w_param, l_param, &result);
  if (ref.get())
    SetMsgHandled(msg_handled);
  return result;
}

void HWNDMessageHandler::OnInitMenu(HMENU menu) {
  bool is_fullscreen = IsFullscreen();
  bool is_minimized = IsMinimized();
  bool is_maximized = IsMaximized();
  bool is_restored = !is_fullscreen && !is_minimized && !is_maximized;

  ScopedRedrawLock lock(this);
  EnableMenuItemByCommand(menu, SC_RESTORE, delegate_->CanResize() &&
                          (is_minimized || is_maximized));
  EnableMenuItemByCommand(menu, SC_MOVE, is_restored);
  EnableMenuItemByCommand(menu, SC_SIZE, delegate_->CanResize() && is_restored);
  EnableMenuItemByCommand(menu, SC_MAXIMIZE, delegate_->CanMaximize() &&
                          !is_fullscreen && !is_maximized);
  EnableMenuItemByCommand(menu, SC_MINIMIZE, delegate_->CanMinimize() &&
                          !is_minimized);

  if (is_maximized && delegate_->CanResize())
    ::SetMenuDefaultItem(menu, SC_RESTORE, FALSE);
  else if (!is_maximized && delegate_->CanMaximize())
    ::SetMenuDefaultItem(menu, SC_MAXIMIZE, FALSE);
}

void HWNDMessageHandler::OnInputLangChange(DWORD character_set,
                                           HKL input_language_id) {
  delegate_->HandleInputLanguageChange(character_set, input_language_id);
}

LRESULT HWNDMessageHandler::OnKeyEvent(UINT message,
                                       WPARAM w_param,
                                       LPARAM l_param) {
  MSG msg = {
      hwnd(), message, w_param, l_param, static_cast<DWORD>(GetMessageTime())};
  ui::KeyEvent key(msg);
  base::WeakPtr<HWNDMessageHandler> ref(msg_handler_weak_factory_.GetWeakPtr());
  delegate_->HandleKeyEvent(&key);
  if (!ref)
    return 0;
  if (!key.handled())
    SetMsgHandled(FALSE);
  return 0;
}

void HWNDMessageHandler::OnKillFocus(HWND focused_window) {
  delegate_->HandleNativeBlur(focused_window);
  SetMsgHandled(FALSE);
}

LRESULT HWNDMessageHandler::OnMouseActivate(UINT message,
                                            WPARAM w_param,
                                            LPARAM l_param) {
  // Please refer to the comments in the header for the touch_down_contexts_
  // member for the if statement below.
  if (touch_down_contexts_)
    return MA_NOACTIVATE;

  // On Windows, if we select the menu item by touch and if the window at the
  // location is another window on the same thread, that window gets a
  // WM_MOUSEACTIVATE message and ends up activating itself, which is not
  // correct. We workaround this by setting a property on the window at the
  // current cursor location. We check for this property in our
  // WM_MOUSEACTIVATE handler and don't activate the window if the property is
  // set.
  if (::GetProp(hwnd(), ui::kIgnoreTouchMouseActivateForWindow)) {
    ::RemoveProp(hwnd(), ui::kIgnoreTouchMouseActivateForWindow);
    return MA_NOACTIVATE;
  }

  // TODO(beng): resolve this with the GetWindowLong() check on the subsequent
  //             line.
  if (delegate_->HasNonClientView()) {
    if (delegate_->CanActivate())
      return MA_ACTIVATE;
    if (delegate_->WantsMouseEventsWhenInactive())
      return MA_NOACTIVATE;
    return MA_NOACTIVATEANDEAT;
  }
  if (GetWindowLong(hwnd(), GWL_EXSTYLE) & WS_EX_NOACTIVATE)
    return MA_NOACTIVATE;
  SetMsgHandled(FALSE);
  return MA_ACTIVATE;
}

LRESULT HWNDMessageHandler::OnMouseRange(UINT message,
                                         WPARAM w_param,
                                         LPARAM l_param) {
  return HandleMouseEventInternal(message, w_param, l_param, true);
}

// On some systems with a high-resolution track pad and running Windows 10,
// using the scrolling gesture (two-finger scroll) on the track pad
// causes it to also generate a WM_POINTERDOWN message if the window
// isn't focused. This leads to a WM_POINTERACTIVATE message and the window
// gaining focus and coming to the front. This code detects a
// WM_POINTERACTIVATE coming from the track pad and kills the activation
// of the window. NOTE: most other trackpad messages come in as mouse
// messages, including WM_MOUSEWHEEL instead of WM_POINTERWHEEL.
LRESULT HWNDMessageHandler::OnPointerActivate(UINT message,
                                              WPARAM w_param,
                                              LPARAM l_param) {
  using GetPointerTypeFn = BOOL(WINAPI*)(UINT32, POINTER_INPUT_TYPE*);
  UINT32 pointer_id = GET_POINTERID_WPARAM(w_param);
  POINTER_INPUT_TYPE pointer_type;
  static GetPointerTypeFn get_pointer_type = reinterpret_cast<GetPointerTypeFn>(
      GetProcAddress(GetModuleHandleA("user32.dll"), "GetPointerType"));
  if (get_pointer_type && get_pointer_type(pointer_id, &pointer_type) &&
      pointer_type == PT_TOUCHPAD)
    return PA_NOACTIVATE;
  SetMsgHandled(FALSE);
  return -1;
}

LRESULT HWNDMessageHandler::OnPointerEvent(UINT message,
                                           WPARAM w_param,
                                           LPARAM l_param) {
  // WM_POINTER is not supported on Windows 7.
  if (base::win::GetVersion() == base::win::VERSION_WIN7) {
    SetMsgHandled(FALSE);
    return -1;
  }

  UINT32 pointer_id = GET_POINTERID_WPARAM(w_param);
  using GetPointerTypeFn = BOOL(WINAPI*)(UINT32, POINTER_INPUT_TYPE*);
  POINTER_INPUT_TYPE pointer_type;
  static GetPointerTypeFn get_pointer_type = reinterpret_cast<GetPointerTypeFn>(
      GetProcAddress(GetModuleHandleA("user32.dll"), "GetPointerType"));
  // If the WM_POINTER messages are not sent from a stylus device, then we do
  // not handle them to make sure we do not change the current behavior of
  // touch and mouse inputs.
  if (!get_pointer_type || !get_pointer_type(pointer_id, &pointer_type)) {
    SetMsgHandled(FALSE);
    return -1;
  }

  switch (pointer_type) {
    case PT_PEN:
      return HandlePointerEventTypePen(message, w_param, l_param);
    case PT_TOUCH:
      if (pointer_events_for_touch_)
        return HandlePointerEventTypeTouch(message, w_param, l_param);
      FALLTHROUGH;
    default:
      SetMsgHandled(FALSE);
      return -1;
  }
}

void HWNDMessageHandler::OnMove(const gfx::Point& point) {
  delegate_->HandleMove();
  SetMsgHandled(FALSE);
}

void HWNDMessageHandler::OnMoving(UINT param, const RECT* new_bounds) {
  delegate_->HandleMove();
}

LRESULT HWNDMessageHandler::OnNCActivate(UINT message,
                                         WPARAM w_param,
                                         LPARAM l_param) {
  // Per MSDN, w_param is either TRUE or FALSE. However, MSDN also hints that:
  // "If the window is minimized when this message is received, the application
  // should pass the message to the DefWindowProc function."
  // It is found out that the high word of w_param might be set when the window
  // is minimized or restored. To handle this, w_param's high word should be
  // cleared before it is converted to BOOL.
  BOOL active = static_cast<BOOL>(LOWORD(w_param));

  bool render_as_active = delegate_->IsAlwaysRenderAsActive();

  if (!delegate_->HasNonClientView()) {
    SetMsgHandled(FALSE);
    return 0;
  }

  if (!delegate_->CanActivate())
    return TRUE;

  // On activation, lift any prior restriction against rendering as inactive.
  if (active && render_as_active)
    delegate_->SetAlwaysRenderAsActive(false);

  if (delegate_->GetFrameMode() == FrameMode::CUSTOM_DRAWN) {
    // TODO(beng, et al): Hack to redraw this window and child windows
    //     synchronously upon activation. Not all child windows are redrawing
    //     themselves leading to issues like http://crbug.com/74604
    //     We redraw out-of-process HWNDs asynchronously to avoid hanging the
    //     whole app if a child HWND belonging to a hung plugin is encountered.
    RedrawWindow(hwnd(), NULL, NULL,
                 RDW_NOCHILDREN | RDW_INVALIDATE | RDW_UPDATENOW);
    EnumChildWindows(hwnd(), EnumChildWindowsForRedraw, NULL);
  }

  // The frame may need to redraw as a result of the activation change.
  // We can get WM_NCACTIVATE before we're actually visible. If we're not
  // visible, no need to paint.
  if (IsVisible())
    delegate_->SchedulePaint();

  // Calling DefWindowProc is only necessary if there's a system frame being
  // drawn. Otherwise it can draw an incorrect title bar and cause visual
  // corruption.
  if (!delegate_->HasFrame() ||
      delegate_->GetFrameMode() == FrameMode::CUSTOM_DRAWN) {
    SetMsgHandled(TRUE);
    return TRUE;
  }

  return DefWindowProcWithRedrawLock(
      WM_NCACTIVATE, render_as_active || active, 0);
}

LRESULT HWNDMessageHandler::OnNCCalcSize(BOOL mode, LPARAM l_param) {
  // We only override the default handling if we need to specify a custom
  // non-client edge width. Note that in most cases "no insets" means no
  // custom width, but in fullscreen mode or when the NonClientFrameView
  // requests it, we want a custom width of 0.

  // Let User32 handle the first nccalcsize for captioned windows
  // so it updates its internal structures (specifically caption-present)
  // Without this Tile & Cascade windows won't work.
  // See http://code.google.com/p/chromium/issues/detail?id=900
  if (is_first_nccalc_) {
    is_first_nccalc_ = false;
    if (GetWindowLong(hwnd(), GWL_STYLE) & WS_CAPTION) {
      SetMsgHandled(FALSE);
      return 0;
    }
  }

  gfx::Insets insets;
  bool got_insets = GetClientAreaInsets(&insets);
  if (!got_insets && !IsFullscreen() && !(mode && !delegate_->HasFrame())) {
    SetMsgHandled(FALSE);
    return 0;
  }

  RECT* client_rect = mode ?
      &(reinterpret_cast<NCCALCSIZE_PARAMS*>(l_param)->rgrc[0]) :
      reinterpret_cast<RECT*>(l_param);
  client_rect->left += insets.left();
  client_rect->top += insets.top();
  client_rect->bottom -= insets.bottom();
  client_rect->right -= insets.right();
  if (IsMaximized()) {
    // Find all auto-hide taskbars along the screen edges and adjust in by the
    // thickness of the auto-hide taskbar on each such edge, so the window isn't
    // treated as a "fullscreen app", which would cause the taskbars to
    // disappear.
    HMONITOR monitor = MonitorFromWindow(hwnd(), MONITOR_DEFAULTTONULL);
    if (!monitor) {
      // We might end up here if the window was previously minimized and the
      // user clicks on the taskbar button to restore it in the previously
      // maximized position. In that case WM_NCCALCSIZE is sent before the
      // window coordinates are restored to their previous values, so our
      // (left,top) would probably be (-32000,-32000) like all minimized
      // windows. So the above MonitorFromWindow call fails, but if we check
      // the window rect given with WM_NCCALCSIZE (which is our previous
      // restored window position) we will get the correct monitor handle.
      monitor = MonitorFromRect(client_rect, MONITOR_DEFAULTTONULL);
      if (!monitor) {
        // This is probably an extreme case that we won't hit, but if we don't
        // intersect any monitor, let us not adjust the client rect since our
        // window will not be visible anyway.
        return 0;
      }
    }
    const int autohide_edges = GetAppbarAutohideEdges(monitor);
    if (autohide_edges & ViewsDelegate::EDGE_LEFT)
      client_rect->left += kAutoHideTaskbarThicknessPx;
    if (autohide_edges & ViewsDelegate::EDGE_TOP) {
      if (IsFrameSystemDrawn()) {
        // Tricky bit.  Due to a bug in DwmDefWindowProc()'s handling of
        // WM_NCHITTEST, having any nonclient area atop the window causes the
        // caption buttons to draw onscreen but not respond to mouse
        // hover/clicks.
        // So for a taskbar at the screen top, we can't push the
        // client_rect->top down; instead, we move the bottom up by one pixel,
        // which is the smallest change we can make and still get a client area
        // less than the screen size. This is visibly ugly, but there seems to
        // be no better solution.
        --client_rect->bottom;
      } else {
        client_rect->top += kAutoHideTaskbarThicknessPx;
      }
    }
    if (autohide_edges & ViewsDelegate::EDGE_RIGHT)
      client_rect->right -= kAutoHideTaskbarThicknessPx;
    if (autohide_edges & ViewsDelegate::EDGE_BOTTOM)
      client_rect->bottom -= kAutoHideTaskbarThicknessPx;

    // We cannot return WVR_REDRAW when there is nonclient area, or Windows
    // exhibits bugs where client pixels and child HWNDs are mispositioned by
    // the width/height of the upper-left nonclient area.
    return 0;
  }

  // If the window bounds change, we're going to relayout and repaint anyway.
  // Returning WVR_REDRAW avoids an extra paint before that of the old client
  // pixels in the (now wrong) location, and thus makes actions like resizing a
  // window from the left edge look slightly less broken.
  // We special case when left or top insets are 0, since these conditions
  // actually require another repaint to correct the layout after glass gets
  // turned on and off.
  if (insets.left() == 0 || insets.top() == 0)
    return 0;
  return mode ? WVR_REDRAW : 0;
}

LRESULT HWNDMessageHandler::OnNCCreate(LPCREATESTRUCT lpCreateStruct) {
  SetMsgHandled(FALSE);
  if (delegate_->HasFrame() && base::win::IsProcessPerMonitorDpiAware()) {
    static auto enable_non_client_dpi_scaling_func = []() {
      return reinterpret_cast<decltype(::EnableNonClientDpiScaling)*>(
                 GetProcAddress(GetModuleHandle(L"user32.dll"),
                                "EnableNonClientDpiScaling"));
    }();
    called_enable_non_client_dpi_scaling_ =
        !!(enable_non_client_dpi_scaling_func &&
           enable_non_client_dpi_scaling_func(hwnd()));
  }
  return FALSE;
}

LRESULT HWNDMessageHandler::OnNCHitTest(const gfx::Point& point) {
  if (!delegate_->HasNonClientView()) {
    SetMsgHandled(FALSE);
    return 0;
  }

  // Some views may overlap the non client area of the window.
  // This means that we should look for these views before handing the
  // hittest message off to DWM or DefWindowProc.
  // If the hittest returned from the search for a view returns HTCLIENT
  // then it means that we have a view overlapping the non client area.
  // In all other cases we can fallback to the system default handling.

  // Allow the NonClientView to handle the hittest to see if we have a view
  // overlapping the non client area of the window.
  POINT temp = { point.x(), point.y() };
  MapWindowPoints(HWND_DESKTOP, hwnd(), &temp, 1);
  int component = delegate_->GetNonClientComponent(gfx::Point(temp));
  if (component == HTCLIENT)
    return component;

  // If the DWM is rendering the window controls, we need to give the DWM's
  // default window procedure first chance to handle hit testing.
  if (HasSystemFrame() &&
      delegate_->GetFrameMode() != FrameMode::SYSTEM_DRAWN_NO_CONTROLS) {
    LRESULT result;
    if (DwmDefWindowProc(hwnd(), WM_NCHITTEST, 0,
                         MAKELPARAM(point.x(), point.y()), &result)) {
      return result;
    }
  }

  // If the point is specified as custom or system nonclient item, return it.
  if (component != HTNOWHERE)
    return component;

  // Otherwise, we let Windows do all the native frame non-client handling for
  // us.
  LRESULT hit_test_code = DefWindowProc(hwnd(), WM_NCHITTEST, 0,
                                        MAKELPARAM(point.x(), point.y()));
  return hit_test_code;
}

void HWNDMessageHandler::OnNCPaint(HRGN rgn) {
  RECT window_rect;
  GetWindowRect(hwnd(), &window_rect);
  RECT dirty_region;
  // A value of 1 indicates paint all.
  if (!rgn || rgn == reinterpret_cast<HRGN>(1)) {
    dirty_region.left = 0;
    dirty_region.top = 0;
    dirty_region.right = window_rect.right - window_rect.left;
    dirty_region.bottom = window_rect.bottom - window_rect.top;
  } else {
    RECT rgn_bounding_box;
    GetRgnBox(rgn, &rgn_bounding_box);
    if (!IntersectRect(&dirty_region, &rgn_bounding_box, &window_rect)) {
      SetMsgHandled(FALSE);
      return;  // Dirty region doesn't intersect window bounds, bail.
    }

    // rgn_bounding_box is in screen coordinates. Map it to window coordinates.
    OffsetRect(&dirty_region, -window_rect.left, -window_rect.top);
  }

  // We only do non-client painting if we're not using the system frame.
  // It's required to avoid some native painting artifacts from appearing when
  // the window is resized.
  if (!delegate_->HasNonClientView() || IsFrameSystemDrawn()) {
    if (ui::win::IsAeroGlassEnabled()) {
      // The default WM_NCPAINT handler under Aero Glass doesn't clear the
      // nonclient area, so it'll remain the default white color. That area is
      // invisible initially (covered by the window border) but can become
      // temporarily visible on maximizing or fullscreening, so clear it here.
      HDC dc = GetWindowDC(hwnd());
      RECT client_rect;
      ::GetClientRect(hwnd(), &client_rect);
      ::MapWindowPoints(hwnd(), nullptr, reinterpret_cast<POINT*>(&client_rect),
                        2);
      ::OffsetRect(&client_rect, -window_rect.left, -window_rect.top);
      // client_rect now is in window space.

      base::win::ScopedRegion base(::CreateRectRgnIndirect(&dirty_region));
      base::win::ScopedRegion client(::CreateRectRgnIndirect(&client_rect));
      base::win::ScopedRegion nonclient(::CreateRectRgn(0, 0, 0, 0));
      ::CombineRgn(nonclient.get(), base.get(), client.get(), RGN_DIFF);

      ::SelectClipRgn(dc, nonclient.get());
      HBRUSH brush = CreateSolidBrush(0);
      ::FillRect(dc, &dirty_region, brush);
      ::DeleteObject(brush);
      ::ReleaseDC(hwnd(), dc);
    }
    SetMsgHandled(FALSE);
    return;
  }

  gfx::Size root_view_size = delegate_->GetRootViewSize();
  if (gfx::Size(window_rect.right - window_rect.left,
                window_rect.bottom - window_rect.top) != root_view_size) {
    // If the size of the window differs from the size of the root view it
    // means we're being asked to paint before we've gotten a WM_SIZE. This can
    // happen when the user is interactively resizing the window. To avoid
    // mass flickering we don't do anything here. Once we get the WM_SIZE we'll
    // reset the region of the window which triggers another WM_NCPAINT and
    // all is well.
    return;
  }
  delegate_->HandlePaintAccelerated(gfx::Rect(dirty_region));

  // When using a custom frame, we want to avoid calling DefWindowProc() since
  // that may render artifacts.
  SetMsgHandled(delegate_->GetFrameMode() == FrameMode::CUSTOM_DRAWN);
}

LRESULT HWNDMessageHandler::OnNCUAHDrawCaption(UINT message,
                                               WPARAM w_param,
                                               LPARAM l_param) {
  // See comment in widget_win.h at the definition of WM_NCUAHDRAWCAPTION for
  // an explanation about why we need to handle this message.
  SetMsgHandled(delegate_->GetFrameMode() == FrameMode::CUSTOM_DRAWN);
  return 0;
}

LRESULT HWNDMessageHandler::OnNCUAHDrawFrame(UINT message,
                                             WPARAM w_param,
                                             LPARAM l_param) {
  // See comment in widget_win.h at the definition of WM_NCUAHDRAWCAPTION for
  // an explanation about why we need to handle this message.
  SetMsgHandled(delegate_->GetFrameMode() == FrameMode::CUSTOM_DRAWN);
  return 0;
}

LRESULT HWNDMessageHandler::OnNotify(int w_param, NMHDR* l_param) {
  LRESULT l_result = 0;
  SetMsgHandled(delegate_->HandleTooltipNotify(w_param, l_param, &l_result));
  return l_result;
}

void HWNDMessageHandler::OnPaint(HDC dc) {
  // Call BeginPaint()/EndPaint() around the paint handling, as that seems
  // to do more to actually validate the window's drawing region. This only
  // appears to matter for Windows that have the WS_EX_COMPOSITED style set
  // but will be valid in general too.
  PAINTSTRUCT ps;
  HDC display_dc = BeginPaint(hwnd(), &ps);

  if (!display_dc) {
    // Collect some information as to why this may have happened and preserve
    // it on the stack so it shows up in a dump.
    // This is temporary data collection code in service of
    // http://crbug.com/512945
    DWORD last_error = GetLastError();
    size_t current_gdi_objects =
        GetGuiResources(GetCurrentProcess(), GR_GDIOBJECTS);
    size_t peak_gdi_objects = GetGuiResources(
        GetCurrentProcess(), GR_GDIOBJECTS_PEAK);
    base::debug::Alias(&last_error);
    base::debug::Alias(&current_gdi_objects);
    base::debug::Alias(&peak_gdi_objects);

    LOG(FATAL) << "Failed to create DC in BeginPaint(). GLE = " << last_error
               << ", GDI object count: " << current_gdi_objects
               << ", GDI peak count: " << peak_gdi_objects;
  }

  if (!IsRectEmpty(&ps.rcPaint)) {
    if (HasChildRenderingWindow()) {
      // If there's a child window that's being rendered to then clear the
      // area outside it (as WS_CLIPCHILDREN is set) with transparent black.
      // Otherwise, other portions of the backing store for the window can
      // flicker opaque black. http://crbug.com/586454

      FillRect(ps.hdc, &ps.rcPaint,
               reinterpret_cast<HBRUSH>(GetStockObject(BLACK_BRUSH)));
    }
    delegate_->HandlePaintAccelerated(gfx::Rect(ps.rcPaint));
  }

  EndPaint(hwnd(), &ps);
}

LRESULT HWNDMessageHandler::OnReflectedMessage(UINT message,
                                               WPARAM w_param,
                                               LPARAM l_param) {
  SetMsgHandled(FALSE);
  return 0;
}

LRESULT HWNDMessageHandler::OnScrollMessage(UINT message,
                                            WPARAM w_param,
                                            LPARAM l_param) {
  MSG msg = {
      hwnd(), message, w_param, l_param, static_cast<DWORD>(GetMessageTime())};
  ui::ScrollEvent event(msg);
  delegate_->HandleScrollEvent(&event);
  return 0;
}

LRESULT HWNDMessageHandler::OnSetCursor(UINT message,
                                        WPARAM w_param,
                                        LPARAM l_param) {
  // Reimplement the necessary default behavior here. Calling DefWindowProc can
  // trigger weird non-client painting for non-glass windows with custom frames.
  // Using a ScopedRedrawLock to prevent caption rendering artifacts may allow
  // content behind this window to incorrectly paint in front of this window.
  // Invalidating the window to paint over either set of artifacts is not ideal.
  wchar_t* cursor = IDC_ARROW;
  switch (LOWORD(l_param)) {
    case HTSIZE:
      cursor = IDC_SIZENWSE;
      break;
    case HTLEFT:
    case HTRIGHT:
      cursor = IDC_SIZEWE;
      break;
    case HTTOP:
    case HTBOTTOM:
      cursor = IDC_SIZENS;
      break;
    case HTTOPLEFT:
    case HTBOTTOMRIGHT:
      cursor = IDC_SIZENWSE;
      break;
    case HTTOPRIGHT:
    case HTBOTTOMLEFT:
      cursor = IDC_SIZENESW;
      break;
    case HTCLIENT:
      SetCursor(current_cursor_);
      return 1;
    case LOWORD(HTERROR):  // Use HTERROR's LOWORD value for valid comparison.
      SetMsgHandled(FALSE);
      break;
    default:
      // Use the default value, IDC_ARROW.
      break;
  }
  ::SetCursor(LoadCursor(NULL, cursor));
  return 1;
}

void HWNDMessageHandler::OnSetFocus(HWND last_focused_window) {
  delegate_->HandleNativeFocus(last_focused_window);
  SetMsgHandled(FALSE);
}

LRESULT HWNDMessageHandler::OnSetIcon(UINT size_type, HICON new_icon) {
  // Use a ScopedRedrawLock to avoid weird non-client painting.
  return DefWindowProcWithRedrawLock(WM_SETICON, size_type,
                                     reinterpret_cast<LPARAM>(new_icon));
}

LRESULT HWNDMessageHandler::OnSetText(const wchar_t* text) {
  // Use a ScopedRedrawLock to avoid weird non-client painting.
  return DefWindowProcWithRedrawLock(WM_SETTEXT, NULL,
                                     reinterpret_cast<LPARAM>(text));
}

void HWNDMessageHandler::OnSettingChange(UINT flags, const wchar_t* section) {
  if (!GetParent(hwnd()) && (flags == SPI_SETWORKAREA) &&
      !delegate_->WillProcessWorkAreaChange()) {
    // Fire a dummy SetWindowPos() call, so we'll trip the code in
    // OnWindowPosChanging() below that notices work area changes.
    ::SetWindowPos(hwnd(), 0, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE |
        SWP_NOZORDER | SWP_NOREDRAW | SWP_NOACTIVATE | SWP_NOOWNERZORDER);
    SetMsgHandled(TRUE);
  } else {
    if (flags == SPI_SETWORKAREA)
      delegate_->HandleWorkAreaChanged();
    SetMsgHandled(FALSE);
  }

  // If the work area is changing, then it could be as a result of the taskbar
  // broadcasting the WM_SETTINGCHANGE message due to changes in auto hide
  // settings, etc. Force a WM_NCCALCSIZE to occur to ensure that we handle
  // this correctly.
  if (flags == SPI_SETWORKAREA)
    SendFrameChanged();
}

void HWNDMessageHandler::OnSize(UINT param, const gfx::Size& size) {
  RedrawWindow(hwnd(), NULL, NULL, RDW_INVALIDATE | RDW_ALLCHILDREN);
  // ResetWindowRegion is going to trigger WM_NCPAINT. By doing it after we've
  // invoked OnSize we ensure the RootView has been laid out.
  ResetWindowRegion(false, true);
}

void HWNDMessageHandler::OnSizing(UINT param, RECT* rect) {
  // If the aspect ratio was not specified for the window, do nothing.
  if (!aspect_ratio_.has_value())
    return;

  gfx::Rect window_rect(*rect);
  SizeRectToAspectRatio(param, &window_rect);

  // TODO(apacible): Account for window borders as part of the aspect ratio.
  // https://crbug/869487.
  *rect = window_rect.ToRECT();
}

void HWNDMessageHandler::OnSysCommand(UINT notification_code,
                                      const gfx::Point& point) {
  // Windows uses the 4 lower order bits of |notification_code| for type-
  // specific information so we must exclude this when comparing.
  static const int sc_mask = 0xFFF0;
  // Ignore size/move/maximize in fullscreen mode.
  if (IsFullscreen() && (((notification_code & sc_mask) == SC_SIZE) ||
                         ((notification_code & sc_mask) == SC_MOVE) ||
                         ((notification_code & sc_mask) == SC_MAXIMIZE)))
    return;

  const bool window_control_action =
      (notification_code & sc_mask) == SC_MINIMIZE ||
      (notification_code & sc_mask) == SC_MAXIMIZE ||
      (notification_code & sc_mask) == SC_RESTORE;
  const bool custom_controls_frame_mode =
      delegate_->GetFrameMode() == FrameMode::SYSTEM_DRAWN_NO_CONTROLS ||
      delegate_->GetFrameMode() == FrameMode::CUSTOM_DRAWN;
  if (custom_controls_frame_mode && window_control_action)
    delegate_->ResetWindowControls();

  if (delegate_->GetFrameMode() == FrameMode::CUSTOM_DRAWN) {
    const bool window_bounds_change =
        (notification_code & sc_mask) == SC_MOVE ||
        (notification_code & sc_mask) == SC_SIZE;
    if (window_bounds_change || window_control_action)
      DestroyAXSystemCaret();
    if (window_bounds_change && !IsVisible()) {
      // Circumvent ScopedRedrawLocks and force visibility before entering a
      // resize or move modal loop to get continuous sizing/moving feedback.
      SetWindowLong(hwnd(), GWL_STYLE,
                    GetWindowLong(hwnd(), GWL_STYLE) | WS_VISIBLE);
    }
  }

  // Handle SC_KEYMENU, which means that the user has pressed the ALT
  // key and released it, so we should focus the menu bar.
  if ((notification_code & sc_mask) == SC_KEYMENU && point.x() == 0) {
    int modifiers = ui::EF_NONE;
    if (ui::win::IsShiftPressed())
      modifiers |= ui::EF_SHIFT_DOWN;
    if (ui::win::IsCtrlPressed())
      modifiers |= ui::EF_CONTROL_DOWN;
    // Retrieve the status of shift and control keys to prevent consuming
    // shift+alt keys, which are used by Windows to change input languages.
    ui::Accelerator accelerator(ui::KeyboardCodeForWindowsKeyCode(VK_MENU),
                                modifiers);
    delegate_->HandleAccelerator(accelerator);
    return;
  }

  // If the delegate can't handle it, the system implementation will be called.
  if (!delegate_->HandleCommand(notification_code)) {
    // If the window is being resized by dragging the borders of the window
    // with the mouse/touch/keyboard, we flag as being in a size loop.
    if ((notification_code & sc_mask) == SC_SIZE)
      in_size_loop_ = true;
    base::WeakPtr<HWNDMessageHandler> ref(
        msg_handler_weak_factory_.GetWeakPtr());

    DefWindowProc(hwnd(), WM_SYSCOMMAND, notification_code,
                  MAKELPARAM(point.x(), point.y()));

    if (!ref.get())
      return;
    in_size_loop_ = false;
  }
}

void HWNDMessageHandler::OnThemeChanged() {
  ui::NativeThemeWin::CloseHandles();
}

void HWNDMessageHandler::OnTimeChange() {
  // Call NowFromSystemTime() to force base::Time to re-initialize the clock
  // from system time. Otherwise base::Time::Now() might continue to reflect the
  // old system clock for some amount of time. See https://crbug.com/672906#c5
  base::Time::NowFromSystemTime();
}

LRESULT HWNDMessageHandler::OnTouchEvent(UINT message,
                                         WPARAM w_param,
                                         LPARAM l_param) {
  if (pointer_events_for_touch_) {
    // Release any associated memory with this event.
    CloseTouchInputHandle(reinterpret_cast<HTOUCHINPUT>(l_param));

    // Claim the event is handled. This shouldn't ever happen
    // because we don't register touch windows when we are using
    // pointer events.
    return 0;
  }

  // Handle touch events only on Aura for now.
  int num_points = LOWORD(w_param);
  std::unique_ptr<TOUCHINPUT[]> input(new TOUCHINPUT[num_points]);
  if (ui::GetTouchInputInfoWrapper(reinterpret_cast<HTOUCHINPUT>(l_param),
                                   num_points, input.get(),
                                   sizeof(TOUCHINPUT))) {
    // input[i].dwTime doesn't necessarily relate to the system time at all,
    // so use base::TimeTicks::Now().
    const base::TimeTicks event_time = base::TimeTicks::Now();
    TouchEvents touch_events;
    TouchIDs stale_touches(touch_ids_);

    for (int i = 0; i < num_points; ++i) {
      stale_touches.erase(input[i].dwID);
      POINT point;
      point.x = TOUCH_COORD_TO_PIXEL(input[i].x);
      point.y = TOUCH_COORD_TO_PIXEL(input[i].y);

      if (base::win::GetVersion() == base::win::VERSION_WIN7) {
        // Windows 7 sends touch events for touches in the non-client area,
        // whereas Windows 8 does not. In order to unify the behaviour, always
        // ignore touch events in the non-client area.
        LPARAM l_param_ht = MAKELPARAM(point.x, point.y);
        LRESULT hittest = SendMessage(hwnd(), WM_NCHITTEST, 0, l_param_ht);

        if (hittest != HTCLIENT)
          return 0;
      }

      ScreenToClient(hwnd(), &point);

      last_touch_or_pen_message_time_ = ::GetMessageTime();

      gfx::Point touch_point(point.x, point.y);
      size_t touch_id = id_generator_.GetGeneratedID(input[i].dwID);

      if (input[i].dwFlags & TOUCHEVENTF_DOWN) {
        touch_ids_.insert(input[i].dwID);
        GenerateTouchEvent(ui::ET_TOUCH_PRESSED, touch_point, touch_id,
                           event_time, &touch_events);
        touch_down_contexts_++;
        base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
            FROM_HERE,
            base::BindOnce(&HWNDMessageHandler::ResetTouchDownContext,
                           msg_handler_weak_factory_.GetWeakPtr()),
            base::TimeDelta::FromMilliseconds(kTouchDownContextResetTimeout));
      } else {
        if (input[i].dwFlags & TOUCHEVENTF_MOVE) {
          GenerateTouchEvent(ui::ET_TOUCH_MOVED, touch_point, touch_id,
                             event_time, &touch_events);
        }

        if (input[i].dwFlags & TOUCHEVENTF_UP) {
          touch_ids_.erase(input[i].dwID);
          GenerateTouchEvent(ui::ET_TOUCH_RELEASED, touch_point, touch_id,
                             event_time, &touch_events);
          id_generator_.ReleaseNumber(input[i].dwID);
        }
      }
    }
    // If a touch has been dropped from the list (without a TOUCH_EVENTF_UP)
    // we generate a simulated TOUCHEVENTF_UP event.
    for (auto touch_number : stale_touches) {
      // Log that we've hit this code. When usage drops off, we can remove
      // this "workaround". See https://crbug.com/811273
      UMA_HISTOGRAM_BOOLEAN("TouchScreen.MissedTOUCHEVENTF_UP", true);
      size_t touch_id = id_generator_.GetGeneratedID(touch_number);
      touch_ids_.erase(touch_number);
      GenerateTouchEvent(ui::ET_TOUCH_RELEASED, gfx::Point(0, 0), touch_id,
                         event_time, &touch_events);
      id_generator_.ReleaseNumber(touch_number);
    }

    // Handle the touch events asynchronously. We need this because touch
    // events on windows don't fire if we enter a modal loop in the context of
    // a touch event.
    base::ThreadTaskRunnerHandle::Get()->PostTask(
        FROM_HERE,
        base::BindOnce(&HWNDMessageHandler::HandleTouchEvents,
                       msg_handler_weak_factory_.GetWeakPtr(), touch_events));
  }
  CloseTouchInputHandle(reinterpret_cast<HTOUCHINPUT>(l_param));
  SetMsgHandled(FALSE);
  return 0;
}

void HWNDMessageHandler::OnWindowPosChanging(WINDOWPOS* window_pos) {
  if (ignore_window_pos_changes_) {
    // If somebody's trying to toggle our visibility, change the nonclient area,
    // change our Z-order, or activate us, we should probably let it go through.
    if (!(window_pos->flags & ((IsVisible() ? SWP_HIDEWINDOW : SWP_SHOWWINDOW) |
        SWP_FRAMECHANGED)) &&
        (window_pos->flags & (SWP_NOZORDER | SWP_NOACTIVATE))) {
      // Just sizing/moving the window; ignore.
      window_pos->flags |= SWP_NOSIZE | SWP_NOMOVE | SWP_NOREDRAW;
      window_pos->flags &= ~(SWP_SHOWWINDOW | SWP_HIDEWINDOW);
    }
  } else if (!GetParent(hwnd())) {
    RECT window_rect;
    const bool have_new_window_rect =
        !(window_pos->flags & SWP_NOMOVE) && !(window_pos->flags & SWP_NOSIZE);
    if (have_new_window_rect) {
      // We should use new window rect for detecting monitor and it's
      // parameters, if it is available. If we use |GetWindowRect()| instead,
      // we can break our same monitor detection logic (see |same_monitor|
      // below) and consequently Windows "Move to other monitor" shortcuts
      // (Win+Shift+Arrows). See crbug.com/656001.
      window_rect.left = window_pos->x;
      window_rect.top = window_pos->y;
      window_rect.right = window_pos->x + window_pos->cx - 1;
      window_rect.bottom = window_pos->y + window_pos->cy - 1;
    }

    HMONITOR monitor;
    gfx::Rect monitor_rect, work_area;
    if ((have_new_window_rect || GetWindowRect(hwnd(), &window_rect)) &&
        GetMonitorAndRects(window_rect, &monitor, &monitor_rect, &work_area)) {
      bool work_area_changed = (monitor_rect == last_monitor_rect_) &&
                               (work_area != last_work_area_);
      const bool same_monitor = monitor && (monitor == last_monitor_);

      gfx::Rect expected_maximized_bounds = work_area;
      if (IsMaximized()) {
        // Windows automatically adds a standard width border to all sides when
        // window is maximized. We should take this into account.
        gfx::Insets client_area_insets;
        if (GetClientAreaInsets(&client_area_insets))
          expected_maximized_bounds.Inset(client_area_insets.Scale(-1));
      }
      // Sometimes Windows incorrectly changes bounds of maximized windows after
      // attaching or detaching additional displays. In this case user can see
      // non-client area of the window (that should be hidden in normal case).
      // We should restore window position if problem occurs.
      const bool incorrect_maximized_bounds =
          IsMaximized() && have_new_window_rect &&
          (expected_maximized_bounds.x() != window_pos->x ||
           expected_maximized_bounds.y() != window_pos->y ||
           expected_maximized_bounds.width() != window_pos->cx ||
           expected_maximized_bounds.height() != window_pos->cy);

      // If the size of a background fullscreen window changes again, then we
      // should reset the |background_fullscreen_hack_| flag.
      if (background_fullscreen_hack_ &&
          (!(window_pos->flags & SWP_NOSIZE) &&
            (monitor_rect.height() - window_pos->cy != 1))) {
          background_fullscreen_hack_ = false;
      }
      const bool fullscreen_without_hack =
          IsFullscreen() && !background_fullscreen_hack_;

      if (same_monitor &&
          (incorrect_maximized_bounds || fullscreen_without_hack ||
           work_area_changed)) {
        // A rect for the monitor we're on changed.  Normally Windows notifies
        // us about this (and thus we're reaching here due to the SetWindowPos()
        // call in OnSettingChange() above), but with some software (e.g.
        // nVidia's nView desktop manager) the work area can change asynchronous
        // to any notification, and we're just sent a SetWindowPos() call with a
        // new (frequently incorrect) position/size.  In either case, the best
        // response is to throw away the existing position/size information in
        // |window_pos| and recalculate it based on the new work rect.
        gfx::Rect new_window_rect;
        if (IsFullscreen()) {
          new_window_rect = monitor_rect;
        } else if (IsMaximized()) {
          new_window_rect = expected_maximized_bounds;
        } else {
          new_window_rect = gfx::Rect(window_rect);
          new_window_rect.AdjustToFit(work_area);
        }
        window_pos->x = new_window_rect.x();
        window_pos->y = new_window_rect.y();
        window_pos->cx = new_window_rect.width();
        window_pos->cy = new_window_rect.height();
        // WARNING!  Don't set SWP_FRAMECHANGED here, it breaks moving the child
        // HWNDs for some reason.
        window_pos->flags &= ~(SWP_NOSIZE | SWP_NOMOVE | SWP_NOREDRAW);
        window_pos->flags |= SWP_NOCOPYBITS;

        // Now ignore all immediately-following SetWindowPos() changes.  Windows
        // likes to (incorrectly) recalculate what our position/size should be
        // and send us further updates.
        ignore_window_pos_changes_ = true;
        base::ThreadTaskRunnerHandle::Get()->PostTask(
            FROM_HERE,
            base::BindOnce(&HWNDMessageHandler::StopIgnoringPosChanges,
                           msg_handler_weak_factory_.GetWeakPtr()));
      }
      last_monitor_ = monitor;
      last_monitor_rect_ = monitor_rect;
      last_work_area_ = work_area;
    }
  }

  RECT window_rect;
  gfx::Size old_size;
  if (GetWindowRect(hwnd(), &window_rect))
    old_size = gfx::Rect(window_rect).size();
  gfx::Size new_size = gfx::Size(window_pos->cx, window_pos->cy);
  if ((old_size != new_size && !(window_pos->flags & SWP_NOSIZE)) ||
      window_pos->flags & SWP_FRAMECHANGED) {
    delegate_->HandleWindowSizeChanging();
    sent_window_size_changing_ = true;

    // It's possible that if Aero snap is being entered then the window size
    // won't actually change. Post a message to ensure swaps will be re-enabled
    // in that case.
    PostMessage(hwnd(), WM_WINDOWSIZINGFINISHED, ++current_window_size_message_,
                0);
    // Copying the old bits can sometimes cause a flash of black when
    // resizing. See https://crbug.com/739724
    if (is_translucent_)
      window_pos->flags |= SWP_NOCOPYBITS;
  }

  if (ScopedFullscreenVisibility::IsHiddenForFullscreen(hwnd())) {
    // Prevent the window from being made visible if we've been asked to do so.
    // See comment in header as to why we might want this.
    window_pos->flags &= ~SWP_SHOWWINDOW;
  }

  if (window_pos->flags & SWP_SHOWWINDOW)
    delegate_->HandleVisibilityChanging(true);
  else if (window_pos->flags & SWP_HIDEWINDOW) {
    SetDwmFrameExtension(DwmFrameState::OFF);
    delegate_->HandleVisibilityChanging(false);
  }

  SetMsgHandled(FALSE);
}

void HWNDMessageHandler::OnWindowPosChanged(WINDOWPOS* window_pos) {
  if (DidClientAreaSizeChange(window_pos))
    ClientAreaSizeChanged();
  if (window_pos->flags & SWP_FRAMECHANGED)
    SetDwmFrameExtension(DwmFrameState::ON);
  if (window_pos->flags & SWP_SHOWWINDOW) {
    delegate_->HandleVisibilityChanged(true);
    SetDwmFrameExtension(DwmFrameState::ON);
  } else if (window_pos->flags & SWP_HIDEWINDOW) {
    delegate_->HandleVisibilityChanged(false);
  }

  SetMsgHandled(FALSE);
}

LRESULT HWNDMessageHandler::OnWindowSizingFinished(UINT message,
                                                   WPARAM w_param,
                                                   LPARAM l_param) {
  // Check if a newer WM_WINDOWPOSCHANGING or WM_WINDOWPOSCHANGED have been
  // received after this message was posted.
  if (current_window_size_message_ != w_param)
    return 0;

  delegate_->HandleWindowSizeUnchanged();
  sent_window_size_changing_ = false;

  return 0;
}

void HWNDMessageHandler::OnSessionChange(WPARAM status_code) {
  // Direct3D presents are ignored while the screen is locked, so force the
  // window to be redrawn on unlock.
  if (status_code == WTS_SESSION_UNLOCK)
    ForceRedrawWindow(10);
}

void HWNDMessageHandler::HandleTouchEvents(const TouchEvents& touch_events) {
  base::WeakPtr<HWNDMessageHandler> ref(msg_handler_weak_factory_.GetWeakPtr());
  for (size_t i = 0; i < touch_events.size() && ref; ++i) {
    ui::TouchEvent* touch_event = const_cast<ui::TouchEvent*>(&touch_events[i]);
    delegate_->HandleTouchEvent(touch_event);
  }
}

void HWNDMessageHandler::ResetTouchDownContext() {
  touch_down_contexts_--;
}

LRESULT HWNDMessageHandler::HandleMouseEventInternal(UINT message,
                                                     WPARAM w_param,
                                                     LPARAM l_param,
                                                     bool track_mouse) {
  // We handle touch events in Aura. Windows generates synthesized mouse
  // messages whenever there's a touch, but it doesn't give us the actual touch
  // messages if it thinks the touch point is in non-client space.
  if (message != WM_MOUSEWHEEL && message != WM_MOUSEHWHEEL &&
      ui::IsMouseEventFromTouch(message)) {
    LRESULT hittest = SendMessage(hwnd(), WM_NCHITTEST, 0, l_param);
    // Always DefWindowProc on the titlebar. We could let the event fall through
    // and the special handling in HandleMouseInputForCaption would take care of
    // this, but in the touch case Windows does a better job.
    if (hittest == HTCAPTION || hittest == HTSYSMENU)
      SetMsgHandled(FALSE);
    // We must let Windows handle the caption buttons if it's drawing them, or
    // they won't work.
    if (delegate_->GetFrameMode() == FrameMode::SYSTEM_DRAWN &&
        (hittest == HTCLOSE || hittest == HTMINBUTTON ||
         hittest == HTMAXBUTTON)) {
      SetMsgHandled(FALSE);
    }
    // Let resize events fall through. Ignore everything else, as we're either
    // letting Windows handle it above or we've already handled the equivalent
    // touch message.
    if (!IsHitTestOnResizeHandle(hittest))
      return 0;
  }

  // Certain logitech drivers send the WM_MOUSEHWHEEL message to the parent
  // followed by WM_MOUSEWHEEL messages to the child window causing a vertical
  // scroll. We treat these WM_MOUSEWHEEL messages as WM_MOUSEHWHEEL
  // messages.
  if (message == WM_MOUSEHWHEEL)
    last_mouse_hwheel_time_ = ::GetMessageTime();

  if (message == WM_MOUSEWHEEL &&
      ::GetMessageTime() == last_mouse_hwheel_time_) {
    message = WM_MOUSEHWHEEL;
  }

  if (message == WM_RBUTTONUP && is_right_mouse_pressed_on_caption_) {
    is_right_mouse_pressed_on_caption_ = false;
    ReleaseCapture();
    // |point| is in window coordinates, but WM_NCHITTEST and TrackPopupMenu()
    // expect screen coordinates.
    POINT screen_point = CR_POINT_INITIALIZER_FROM_LPARAM(l_param);
    MapWindowPoints(hwnd(), HWND_DESKTOP, &screen_point, 1);
    w_param = SendMessage(hwnd(), WM_NCHITTEST, 0,
                          MAKELPARAM(screen_point.x, screen_point.y));
    if (w_param == HTCAPTION || w_param == HTSYSMENU) {
      gfx::ShowSystemMenuAtPoint(hwnd(), gfx::Point(screen_point));
      return 0;
    }
  } else if (message == WM_NCLBUTTONDOWN &&
             delegate_->GetFrameMode() == FrameMode::CUSTOM_DRAWN) {
    switch (w_param) {
      case HTCLOSE:
      case HTMINBUTTON:
      case HTMAXBUTTON: {
        // When the mouse is pressed down in these specific non-client areas,
        // we need to tell the RootView to send the mouse pressed event (which
        // sets capture, allowing subsequent WM_LBUTTONUP (note, _not_
        // WM_NCLBUTTONUP) to fire so that the appropriate WM_SYSCOMMAND can be
        // sent by the applicable button's ButtonListener. We _have_ to do this
        // way rather than letting Windows just send the syscommand itself (as
        // would happen if we never did this dance) because for some insane
        // reason DefWindowProc for WM_NCLBUTTONDOWN also renders the pressed
        // window control button appearance, in the Windows classic style, over
        // our view! Ick! By handling this message we prevent Windows from
        // doing this undesirable thing, but that means we need to roll the
        // sys-command handling ourselves.
        // Combine |w_param| with common key state message flags.
        w_param |= ui::win::IsCtrlPressed() ? MK_CONTROL : 0;
        w_param |= ui::win::IsShiftPressed() ? MK_SHIFT : 0;
      }
    }
  } else if (message == WM_NCRBUTTONDOWN &&
      (w_param == HTCAPTION || w_param == HTSYSMENU)) {
    is_right_mouse_pressed_on_caption_ = true;
    // We SetCapture() to ensure we only show the menu when the button
    // down and up are both on the caption. Note: this causes the button up to
    // be WM_RBUTTONUP instead of WM_NCRBUTTONUP.
    SetCapture();
  }

  long message_time = GetMessageTime();
  MSG msg = { hwnd(), message, w_param, l_param,
              static_cast<DWORD>(message_time),
              { CR_GET_X_LPARAM(l_param), CR_GET_Y_LPARAM(l_param) } };
  ui::MouseEvent event(msg);
  if (IsSynthesizedMouseMessage(message, message_time, l_param))
    event.set_flags(event.flags() | ui::EF_FROM_TOUCH);

  if (event.type() == ui::ET_MOUSE_MOVED && !HasCapture() && track_mouse) {
    // Windows only fires WM_MOUSELEAVE events if the application begins
    // "tracking" mouse events for a given HWND during WM_MOUSEMOVE events.
    // We need to call |TrackMouseEvents| to listen for WM_MOUSELEAVE.
    TrackMouseEvents((message == WM_NCMOUSEMOVE) ?
        TME_NONCLIENT | TME_LEAVE : TME_LEAVE);
  } else if (event.type() == ui::ET_MOUSE_EXITED) {
    // Reset our tracking flags so future mouse movement over this
    // NativeWidget results in a new tracking session. Fall through for
    // OnMouseEvent.
    active_mouse_tracking_flags_ = 0;
  } else if (event.type() == ui::ET_MOUSEWHEEL) {
    ui::MouseWheelEvent mouse_wheel_event(msg);
    // Reroute the mouse wheel to the window under the pointer if applicable.
    return (ui::RerouteMouseWheel(hwnd(), w_param, l_param) ||
            delegate_->HandleMouseEvent(&mouse_wheel_event))
               ? 0
               : 1;
  }

  // There are cases where the code handling the message destroys the window,
  // so use the weak ptr to check if destruction occured or not.
  base::WeakPtr<HWNDMessageHandler> ref(msg_handler_weak_factory_.GetWeakPtr());
  bool handled = delegate_->HandleMouseEvent(&event);

  if (!ref.get())
    return 0;

  if (!handled && message == WM_NCLBUTTONDOWN && w_param != HTSYSMENU &&
      w_param != HTCAPTION &&
      delegate_->GetFrameMode() == FrameMode::CUSTOM_DRAWN) {
    // TODO(msw): Eliminate undesired painting, or re-evaluate this workaround.
    // DefWindowProc for WM_NCLBUTTONDOWN does weird non-client painting, so we
    // need to call it inside a ScopedRedrawLock. This may cause other negative
    // side-effects (ex/ stifling non-client mouse releases).
    DefWindowProcWithRedrawLock(message, w_param, l_param);
    handled = true;
  }

  // We need special processing for mouse input on the caption.
  // Please refer to the HandleMouseInputForCaption() function for more
  // information.
  if (!handled)
    handled = HandleMouseInputForCaption(message, w_param, l_param);

  if (ref.get())
    SetMsgHandled(handled);
  return 0;
}

LRESULT HWNDMessageHandler::HandlePointerEventTypeTouch(UINT message,
                                                        WPARAM w_param,
                                                        LPARAM l_param) {
  UINT32 pointer_id = GET_POINTERID_WPARAM(w_param);
  using GetPointerTouchInfoFn = BOOL(WINAPI*)(UINT32, POINTER_TOUCH_INFO*);
  POINTER_TOUCH_INFO pointer_touch_info;
  static GetPointerTouchInfoFn get_pointer_touch_info =
      reinterpret_cast<GetPointerTouchInfoFn>(GetProcAddress(
          GetModuleHandleA("user32.dll"), "GetPointerTouchInfo"));
  if (!get_pointer_touch_info ||
      !get_pointer_touch_info(pointer_id, &pointer_touch_info)) {
    SetMsgHandled(FALSE);
    return -1;
  }

  last_touch_or_pen_message_time_ = ::GetMessageTime();
  // Ignore enter/leave events, otherwise they will be converted in
  // |GetTouchEventType| to ET_TOUCH_PRESSED/ET_TOUCH_RELEASED events, which
  // is not correct.
  if (message == WM_POINTERENTER || message == WM_POINTERLEAVE) {
    SetMsgHandled(TRUE);
    return 0;
  }

  // Increment |touch_down_contexts_| on a pointer down. This variable
  // is used to debounce the WM_MOUSEACTIVATE events.
  if (message == WM_POINTERDOWN) {
    touch_down_contexts_++;
    base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
        FROM_HERE,
        base::BindOnce(&HWNDMessageHandler::ResetTouchDownContext,
                       msg_handler_weak_factory_.GetWeakPtr()),
        base::TimeDelta::FromMilliseconds(kTouchDownContextResetTimeout));
  }

  size_t mapped_pointer_id = id_generator_.GetGeneratedID(pointer_id);
  POINTER_INFO pointer_info = pointer_touch_info.pointerInfo;
  POINT client_point = pointer_info.ptPixelLocationRaw;
  ScreenToClient(hwnd(), &client_point);
  gfx::Point touch_point = gfx::Point(client_point.x, client_point.y);

  POINTER_FLAGS pointer_flags = pointer_info.pointerFlags;
  ui::EventType event_type = GetTouchEventType(pointer_flags);
  const base::TimeTicks event_time = ui::EventTimeForNow();

  // The pressure from POINTER_TOUCH_INFO is normalized to a range between 0
  // and 1024, but we define the pressure of the range of [0,1].
  float pressure = static_cast<float>(pointer_touch_info.pressure) / 1024;
  float radius_x =
      (pointer_touch_info.rcContact.right - pointer_touch_info.rcContact.left) /
      2.0;
  float radius_y =
      (pointer_touch_info.rcContact.bottom - pointer_touch_info.rcContact.top) /
      2.0;
  int rotation_angle = pointer_touch_info.orientation;
  rotation_angle %= 180;
  if (rotation_angle < 0)
    rotation_angle += 180;

  ui::TouchEvent event(
      event_type, touch_point, event_time,
      ui::PointerDetails(ui::EventPointerType::POINTER_TYPE_TOUCH,
                         mapped_pointer_id, radius_x, radius_y, pressure,
                         pointer_touch_info.orientation, 0.0f, 0.0f, 0.0f),
      ui::GetModifiersFromKeyState(), rotation_angle);

  event.latency()->AddLatencyNumberWithTimestamp(
      ui::INPUT_EVENT_LATENCY_ORIGINAL_COMPONENT, event_time, 1);

  // There are cases where the code handling the message destroys the
  // window, so use the weak ptr to check if destruction occurred or not.
  base::WeakPtr<HWNDMessageHandler> ref(msg_handler_weak_factory_.GetWeakPtr());
  delegate_->HandleTouchEvent(&event);

  if (ref) {
    // Release the pointer id only when |HWNDMessageHandler| and |id_generator_|
    // are not destroyed.
    if (event_type == ui::ET_TOUCH_RELEASED)
      id_generator_.ReleaseNumber(pointer_id);

    SetMsgHandled(event.handled());
  }
  return 0;
}

LRESULT HWNDMessageHandler::HandlePointerEventTypePen(UINT message,
                                                      WPARAM w_param,
                                                      LPARAM l_param) {
  UINT32 pointer_id = GET_POINTERID_WPARAM(w_param);
  using GetPointerPenInfoFn = BOOL(WINAPI*)(UINT32, POINTER_PEN_INFO*);
  POINTER_PEN_INFO pointer_pen_info;
  static GetPointerPenInfoFn get_pointer_pen_info =
      reinterpret_cast<GetPointerPenInfoFn>(
          GetProcAddress(GetModuleHandleA("user32.dll"), "GetPointerPenInfo"));
  if (!get_pointer_pen_info ||
      !get_pointer_pen_info(pointer_id, &pointer_pen_info)) {
    SetMsgHandled(FALSE);
    return -1;
  }

  POINT client_point = pointer_pen_info.pointerInfo.ptPixelLocationRaw;
  ScreenToClient(hwnd(), &client_point);
  gfx::Point point = gfx::Point(client_point.x, client_point.y);

  std::unique_ptr<ui::Event> event = pen_processor_.GenerateEvent(
      message, pointer_id, pointer_pen_info, point);

  // There are cases where the code handling the message destroys the
  // window, so use the weak ptr to check if destruction occured or not.
  base::WeakPtr<HWNDMessageHandler> ref(msg_handler_weak_factory_.GetWeakPtr());
  if (event) {
    if (event->IsTouchEvent()) {
      delegate_->HandleTouchEvent(event->AsTouchEvent());
    } else if (event->IsMouseEvent()) {
      delegate_->HandleMouseEvent(event->AsMouseEvent());
    } else {
      NOTREACHED();
    }
    last_touch_or_pen_message_time_ = ::GetMessageTime();
  }

  // Always mark as handled as we don't want to generate WM_MOUSE compatiblity
  // events.
  if (ref)
    SetMsgHandled(TRUE);
  return 0;
}

bool HWNDMessageHandler::IsSynthesizedMouseMessage(unsigned int message,
                                                   int message_time,
                                                   LPARAM l_param) {
  if (ui::IsMouseEventFromTouch(message))
    return true;
  // Ignore mouse messages which occur at the same location as the current
  // cursor position and within a time difference of 500 ms from the last
  // touch message.
  if (last_touch_or_pen_message_time_ &&
      message_time >= last_touch_or_pen_message_time_ &&
      ((message_time - last_touch_or_pen_message_time_) <=
       kSynthesizedMouseMessagesTimeDifference)) {
    POINT mouse_location = CR_POINT_INITIALIZER_FROM_LPARAM(l_param);
    ::ClientToScreen(hwnd(), &mouse_location);
    POINT cursor_pos = {0};
    ::GetCursorPos(&cursor_pos);
    if (memcmp(&cursor_pos, &mouse_location, sizeof(POINT)))
      return false;
    return true;
  }
  return false;
}

void HWNDMessageHandler::PerformDwmTransition() {
  dwm_transition_desired_ = false;

  UpdateDwmNcRenderingPolicy();
  // Don't redraw the window here, because we need to hide and show the window
  // which will also trigger a redraw.
  ResetWindowRegion(true, false);
  // The non-client view needs to update too.
  delegate_->HandleFrameChanged();

  if (IsVisible() && IsFrameSystemDrawn()) {
    // For some reason, we need to hide the window after we change from a custom
    // frame to a native frame.  If we don't, the client area will be filled
    // with black.  This seems to be related to an interaction between DWM and
    // SetWindowRgn, but the details aren't clear. Additionally, we need to
    // specify SWP_NOZORDER here, otherwise if you have multiple chrome windows
    // open they will re-appear with a non-deterministic Z-order.
    UINT flags = SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER;
    SetWindowPos(hwnd(), NULL, 0, 0, 0, 0, flags | SWP_HIDEWINDOW);
    SetWindowPos(hwnd(), NULL, 0, 0, 0, 0, flags | SWP_SHOWWINDOW);
  }
  // WM_DWMCOMPOSITIONCHANGED is only sent to top level windows, however we want
  // to notify our children too, since we can have MDI child windows who need to
  // update their appearance.
  EnumChildWindows(hwnd(), &SendDwmCompositionChanged, NULL);
}

void HWNDMessageHandler::GenerateTouchEvent(ui::EventType event_type,
                                            const gfx::Point& point,
                                            size_t id,
                                            base::TimeTicks time_stamp,
                                            TouchEvents* touch_events) {
  ui::TouchEvent event(
      event_type, point, time_stamp,
      ui::PointerDetails(ui::EventPointerType::POINTER_TYPE_TOUCH, id));

  event.set_flags(ui::GetModifiersFromKeyState());

  event.latency()->AddLatencyNumberWithTimestamp(
      ui::INPUT_EVENT_LATENCY_ORIGINAL_COMPONENT, time_stamp, 1);

  touch_events->push_back(event);
}

bool HWNDMessageHandler::HandleMouseInputForCaption(unsigned int message,
                                                    WPARAM w_param,
                                                    LPARAM l_param) {
  // If we are receive a WM_NCLBUTTONDOWN messsage for the caption, the
  // following things happen.
  // 1. This message is defproced which will post a WM_SYSCOMMAND message with
  //    SC_MOVE and a constant 0x0002 which is documented on msdn as
  //    SC_DRAGMOVE.
  // 2. The WM_SYSCOMMAND message is defproced in our handler which works
  //    correctly in all cases except the case when we click on the caption
  //    and hold. The defproc appears to try and detect whether a mouse move
  //    is going to happen presumably via the DragEnter or a similar
  //    implementation which in its modal loop appears to only peek for
  //    mouse input briefly.
  // 3. Our workhorse message pump relies on the tickler posted message to get
  //    control during modal loops which does not happen in the above case for
  //    a while leading to the problem where activity on the page pauses
  //    briefly or at times stops for a while.
  // To fix this we don't defproc the WM_NCLBUTTONDOWN message and instead wait
  // for the subsequent WM_NCMOUSEMOVE/WM_MOUSEMOVE message. Once we receive
  // these messages and the mouse actually moved, we defproc the
  // WM_NCLBUTTONDOWN message.
  bool handled = false;
  switch (message) {
    case WM_NCLBUTTONDOWN: {
      if (w_param == HTCAPTION) {
        left_button_down_on_caption_ = true;
        // Cache the location where the click occurred. We use this in the
        // WM_NCMOUSEMOVE message to determine if the mouse actually moved.F
        caption_left_button_click_pos_.set_x(CR_GET_X_LPARAM(l_param));
        caption_left_button_click_pos_.set_y(CR_GET_Y_LPARAM(l_param));
        handled = true;
      }
      break;
    }

    // WM_NCMOUSEMOVE is received for normal drags which originate on the
    // caption and stay there.
    // WM_MOUSEMOVE can be received for drags which originate on the caption
    // and move towards the client area.
    case WM_MOUSEMOVE:
    case WM_NCMOUSEMOVE: {
      if (!left_button_down_on_caption_)
        break;

      bool should_handle_pending_ncl_button_down = true;
      // Check if the mouse actually moved.
      if (message == WM_NCMOUSEMOVE) {
        if (caption_left_button_click_pos_.x() == CR_GET_X_LPARAM(l_param) &&
            caption_left_button_click_pos_.y() == CR_GET_Y_LPARAM(l_param)) {
          should_handle_pending_ncl_button_down = false;
        }
      }
      if (should_handle_pending_ncl_button_down) {
        l_param = MAKELPARAM(caption_left_button_click_pos_.x(),
                             caption_left_button_click_pos_.y());
        // TODO(msw): Eliminate undesired painting, or re-evaluate this
        // workaround.
        // DefWindowProc for WM_NCLBUTTONDOWN does weird non-client painting,
        // so we need to call it inside a ScopedRedrawLock. This may cause
        // other negative side-effects
        // (ex/ stifling non-client mouse releases).
        // We may be deleted in the context of DefWindowProc. Don't refer to
        // any member variables after the DefWindowProc call.
        left_button_down_on_caption_ = false;

        if (delegate_->GetFrameMode() == FrameMode::CUSTOM_DRAWN) {
          DefWindowProcWithRedrawLock(WM_NCLBUTTONDOWN, HTCAPTION, l_param);
        } else {
          DefWindowProc(hwnd(), WM_NCLBUTTONDOWN, HTCAPTION, l_param);
        }
      }
      break;
    }

    case WM_NCMOUSELEAVE: {
      // If the DWM is rendering the window controls, we need to give the DWM's
      // default window procedure the chance to repaint the window border icons
      if (HasSystemFrame())
        handled = DwmDefWindowProc(hwnd(), WM_NCMOUSELEAVE, 0, 0, NULL) != 0;
      break;
    }

    default:
      left_button_down_on_caption_ = false;
      break;
  }
  return handled;
}

void HWNDMessageHandler::SetBoundsInternal(const gfx::Rect& bounds_in_pixels,
                                           bool force_size_changed) {
  LONG style = GetWindowLong(hwnd(), GWL_STYLE);
  if (style & WS_MAXIMIZE)
    SetWindowLong(hwnd(), GWL_STYLE, style & ~WS_MAXIMIZE);

  gfx::Size old_size = GetClientAreaBounds().size();
  SetWindowPos(hwnd(), NULL, bounds_in_pixels.x(), bounds_in_pixels.y(),
               bounds_in_pixels.width(), bounds_in_pixels.height(),
               SWP_NOACTIVATE | SWP_NOZORDER);

  // If HWND size is not changed, we will not receive standard size change
  // notifications. If |force_size_changed| is |true|, we should pretend size is
  // changed.
  if (old_size == bounds_in_pixels.size() && force_size_changed &&
      !background_fullscreen_hack_) {
    delegate_->HandleClientSizeChanged(GetClientAreaBounds().size());
    ResetWindowRegion(false, true);
  }
}

void HWNDMessageHandler::CheckAndHandleBackgroundFullscreenOnMonitor(
    HWND window) {
  HMONITOR monitor = MonitorFromWindow(window, MONITOR_DEFAULTTOPRIMARY);

  FullscreenWindowMonitorMap::iterator iter =
      fullscreen_monitor_map_.Get().find(monitor);
  if (iter != fullscreen_monitor_map_.Get().end()) {
    DCHECK(iter->second);
    if (window != iter->second->hwnd())
      iter->second->OnBackgroundFullscreen();
  }
}

void HWNDMessageHandler::OnBackgroundFullscreen() {
  // Reduce the bounds of the window by 1px to ensure that Windows does
  // not treat this like a fullscreen window.
  MONITORINFO monitor_info = {sizeof(monitor_info)};
  GetMonitorInfo(MonitorFromWindow(hwnd(), MONITOR_DEFAULTTOPRIMARY),
                 &monitor_info);
  gfx::Rect shrunk_rect(monitor_info.rcMonitor);
  shrunk_rect.set_height(shrunk_rect.height() - 1);
  background_fullscreen_hack_ = true;
  SetBoundsInternal(shrunk_rect, false);
  // Inform the taskbar that this window is no longer a fullscreen window so it
  // can bring itself to the top of the Z-Order. The taskbar heuristics to
  // detect fullscreen windows are not reliable. Marking it explicitly seems to
  // work around these problems.
  fullscreen_handler()->MarkFullscreen(false);
}

void HWNDMessageHandler::DestroyAXSystemCaret() {
  ax_system_caret_ = nullptr;
}

void HWNDMessageHandler::SizeRectToAspectRatio(UINT param,
                                               gfx::Rect* window_rect) {
  gfx::Size min_window_size;
  gfx::Size max_window_size;
  delegate_->GetMinMaxSize(&min_window_size, &max_window_size);
  WindowResizeUtils::SizeMinMaxToAspectRatio(
      aspect_ratio_.value(), &min_window_size, &max_window_size);
  min_window_size = delegate_->DIPToScreenSize(min_window_size);
  max_window_size = delegate_->DIPToScreenSize(max_window_size);
  WindowResizeUtils::SizeRectToAspectRatio(
      GetWindowResizeHitTest(param), aspect_ratio_.value(), min_window_size,
      max_window_size, window_rect);
}

}  // namespace views