Commit df98b11c47bfff61383068e5e45a54cc2ad6599a

Alex Szpakowski 2015-04-06T15:26:37

Merged default into iOS-improvements

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
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
diff --git a/.hgignore b/.hgignore
index c16de75..029dfaf 100644
--- a/.hgignore
+++ b/.hgignore
@@ -8,6 +8,9 @@ Makefile
 sdl-config
 SDL2.spec
 build
+Build
+*xcuserdata*
+*xcworkspacedata*
 
 # for Xcode
 *.orig
diff --git a/Xcode-iOS/Demos/src/fireworks.c b/Xcode-iOS/Demos/src/fireworks.c
index 6c60dd1..a5beada 100644
--- a/Xcode-iOS/Demos/src/fireworks.c
+++ b/Xcode-iOS/Demos/src/fireworks.c
@@ -387,6 +387,9 @@ main(int argc, char *argv[])
     SDL_GL_SetAttribute(SDL_GL_RETAINED_BACKING, 0);
     SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1);
 
+    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 1);
+    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
+
     /* create main window and renderer */
     window = SDL_CreateWindow(NULL, 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT,
                                 SDL_WINDOW_OPENGL |
diff --git a/Xcode-iOS/SDL/SDL.xcodeproj/project.pbxproj b/Xcode-iOS/SDL/SDL.xcodeproj/project.pbxproj
index 44055ca..747f150 100755
--- a/Xcode-iOS/SDL/SDL.xcodeproj/project.pbxproj
+++ b/Xcode-iOS/SDL/SDL.xcodeproj/project.pbxproj
@@ -1274,8 +1274,14 @@
 		FD6526640DE8FCCB002AD96B /* Debug */ = {
 			isa = XCBuildConfiguration;
 			buildSettings = {
+				CLANG_ENABLE_OBJC_ARC = YES;
+				CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
+				CLANG_WARN_OBJC_IMPLICIT_ATOMIC_PROPERTIES = YES;
 				COPY_PHASE_STRIP = NO;
 				IPHONEOS_DEPLOYMENT_TARGET = 5.1.1;
+				GCC_WARN_MULTIPLE_DEFINITION_TYPES_FOR_SELECTOR = YES;
+				GCC_WARN_STRICT_SELECTOR_MATCH = YES;
+				GCC_WARN_UNDECLARED_SELECTOR = YES;
 				PRODUCT_NAME = SDL2;
 				SKIP_INSTALL = YES;
 			};
@@ -1284,8 +1290,14 @@
 		FD6526650DE8FCCB002AD96B /* Release */ = {
 			isa = XCBuildConfiguration;
 			buildSettings = {
+				CLANG_ENABLE_OBJC_ARC = YES;
+				CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
+				CLANG_WARN_OBJC_IMPLICIT_ATOMIC_PROPERTIES = YES;
 				COPY_PHASE_STRIP = YES;
 				IPHONEOS_DEPLOYMENT_TARGET = 5.1.1;
+				GCC_WARN_MULTIPLE_DEFINITION_TYPES_FOR_SELECTOR = YES;
+				GCC_WARN_STRICT_SELECTOR_MATCH = YES;
+				GCC_WARN_UNDECLARED_SELECTOR = YES;
 				PRODUCT_NAME = SDL2;
 				SKIP_INSTALL = YES;
 			};
diff --git a/include/SDL_config_iphoneos.h b/include/SDL_config_iphoneos.h
index 4e3eb2c..79da366 100644
--- a/include/SDL_config_iphoneos.h
+++ b/include/SDL_config_iphoneos.h
@@ -145,6 +145,9 @@
 /* enable iPhone keyboard support */
 #define SDL_IPHONE_KEYBOARD 1
 
+/* enable iOS extended launch screen */
+#define SDL_IPHONE_LAUNCHSCREEN 1
+
 /* enable joystick subsystem */
 #define SDL_JOYSTICK_DISABLED 0
 
diff --git a/include/SDL_hints.h b/include/SDL_hints.h
index ecc3ba0..5eaba8f 100644
--- a/include/SDL_hints.h
+++ b/include/SDL_hints.h
@@ -261,8 +261,9 @@ extern "C" {
 #define SDL_HINT_ORIENTATIONS "SDL_IOS_ORIENTATIONS"
     
 /**
- *  \brief  A variable controlling whether an Android built-in accelerometer should be
- *  listed as a joystick device, rather than listing actual joysticks only.
+ *  \brief  A variable controlling whether the Android / iOS built-in
+ *  accelerometer should be listed as a joystick device, rather than listing
+ *  actual joysticks only.
  *
  *  This variable can be set to the following values:
  *    "0"       - List only real joysticks and accept input from them
@@ -345,7 +346,7 @@ extern "C" {
 
 
 /**
- *  \brief If set to 1, then do not allow high-DPI windows. ("Retina" on Mac)
+ *  \brief If set to 1, then do not allow high-DPI windows. ("Retina" on Mac and iOS)
  */
 #define SDL_HINT_VIDEO_HIGHDPI_DISABLED "SDL_VIDEO_HIGHDPI_DISABLED"
 
diff --git a/include/SDL_system.h b/include/SDL_system.h
index 65d3786..ad610ba 100644
--- a/include/SDL_system.h
+++ b/include/SDL_system.h
@@ -76,6 +76,20 @@ extern DECLSPEC SDL_bool SDLCALL SDL_DXGIGetOutputInfo( int displayIndex, int *a
 extern DECLSPEC int SDLCALL SDL_iPhoneSetAnimationCallback(SDL_Window * window, int interval, void (*callback)(void*), void *callbackParam);
 extern DECLSPEC void SDLCALL SDL_iPhoneSetEventPump(SDL_bool enabled);
 
+/**
+   \brief Returns the OpenGL Renderbuffer Object associated with the window's main view.
+
+   The Renderbuffer must be bound when calling SDL_GL_SwapWindow.
+ */
+extern DECLSPEC Uint32 SDLCALL SDL_iPhoneGetViewRenderbuffer(SDL_Window * window);
+
+/**
+   \brief Returns the OpenGL Framebuffer Object associated with the window's main view.
+
+   The Framebuffer must be bound when rendering to the screen.
+ */
+extern DECLSPEC Uint32 SDLCALL SDL_iPhoneGetViewFramebuffer(SDL_Window * window);
+
 #endif /* __IPHONEOS__ */
 
 
diff --git a/premake/Xcode-iOS/SDL_config_premake.h b/premake/Xcode-iOS/SDL_config_premake.h
index e0a8641..bae64b1 100644
--- a/premake/Xcode-iOS/SDL_config_premake.h
+++ b/premake/Xcode-iOS/SDL_config_premake.h
@@ -126,6 +126,9 @@
 #ifndef SDL_IPHONE_KEYBOARD
 #define SDL_IPHONE_KEYBOARD 1
 #endif
+#ifndef SDL_IPHONE_LAUNCHSCREEN
+#define SDL_IPHONE_LAUNCHSCREEN 1
+#endif
 #ifndef SDL_POWER_UIKIT
 #define SDL_POWER_UIKIT 1
 #endif
diff --git a/src/file/cocoa/SDL_rwopsbundlesupport.m b/src/file/cocoa/SDL_rwopsbundlesupport.m
index 1ae399c..a56879e 100644
--- a/src/file/cocoa/SDL_rwopsbundlesupport.m
+++ b/src/file/cocoa/SDL_rwopsbundlesupport.m
@@ -50,14 +50,13 @@ FILE* SDL_OpenFPFromBundleOrFallback(const char *file, const char *mode)
     NSString* full_path_with_file_to_try = [resource_path stringByAppendingPathComponent:ns_string_file_component];
     if([file_manager fileExistsAtPath:full_path_with_file_to_try]) {
         fp = fopen([full_path_with_file_to_try fileSystemRepresentation], mode);
-    }
-    else {
+    } else {
         fp = fopen(file, mode);
     }
 
     return fp;
 }}
 
-#endif /* __MACOSX__ */
+#endif /* __APPLE__ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/filesystem/cocoa/SDL_sysfilesystem.m b/src/filesystem/cocoa/SDL_sysfilesystem.m
index dab51c5..74e1e7b 100644
--- a/src/filesystem/cocoa/SDL_sysfilesystem.m
+++ b/src/filesystem/cocoa/SDL_sysfilesystem.m
@@ -41,6 +41,7 @@ SDL_GetBasePath(void)
     const char* baseType = [[[bundle infoDictionary] objectForKey:@"SDL_FILESYSTEM_BASE_DIR_TYPE"] UTF8String];
     const char *base = NULL;
     char *retval = NULL;
+
     if (baseType == NULL) {
         baseType = "resource";
     }
@@ -52,6 +53,7 @@ SDL_GetBasePath(void)
         /* this returns the exedir for non-bundled  and the resourceDir for bundled apps */
         base = [[bundle resourcePath] fileSystemRepresentation];
     }
+
     if (base) {
         const size_t len = SDL_strlen(base) + 2;
         retval = (char *) SDL_malloc(len);
@@ -69,9 +71,10 @@ char *
 SDL_GetPrefPath(const char *org, const char *app)
 { @autoreleasepool
 {
-    NSArray *array = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
     char *retval = NULL;
 
+    NSArray *array = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
+
     if ([array count] > 0) {  /* we only want the first item in the list. */
         NSString *str = [array objectAtIndex:0];
         const char *base = [str fileSystemRepresentation];
diff --git a/src/joystick/iphoneos/SDL_sysjoystick.m b/src/joystick/iphoneos/SDL_sysjoystick.m
index 56c3925..25bdfbb 100644
--- a/src/joystick/iphoneos/SDL_sysjoystick.m
+++ b/src/joystick/iphoneos/SDL_sysjoystick.m
@@ -23,6 +23,7 @@
 /* This is the iOS implementation of the SDL joystick API */
 
 #include "SDL_joystick.h"
+#include "SDL_hints.h"
 #include "SDL_stdinc.h"
 #include "../SDL_sysjoystick.h"
 #include "../SDL_joystick_c.h"
@@ -32,9 +33,10 @@
 /* needed for SDL_IPHONE_MAX_GFORCE macro */
 #import "SDL_config_iphoneos.h"
 
-const char *accelerometerName = "iOS accelerometer";
+const char *accelerometerName = "iOS Accelerometer";
 
 static CMMotionManager *motionManager = nil;
+static int numjoysticks = 0;
 
 /* Function to scan the system for joysticks.
  * Joystick 0 should be the system default joystick.
@@ -43,12 +45,18 @@ static CMMotionManager *motionManager = nil;
 int
 SDL_SYS_JoystickInit(void)
 {
-    return (1);
+    const char *hint = SDL_GetHint(SDL_HINT_ACCELEROMETER_AS_JOYSTICK);
+    if (!hint || SDL_atoi(hint)) {
+        /* Default behavior, accelerometer as joystick */
+        numjoysticks = 1;
+    }
+
+    return numjoysticks;
 }
 
 int SDL_SYS_NumJoysticks()
 {
-    return 1;
+    return numjoysticks;
 }
 
 void SDL_SYS_JoystickDetect()
@@ -81,13 +89,15 @@ SDL_SYS_JoystickOpen(SDL_Joystick * joystick, int device_index)
     joystick->nballs = 0;
     joystick->nbuttons = 0;
 
-    if (motionManager == nil) {
-        motionManager = [[CMMotionManager alloc] init];
-    }
+    @autoreleasepool {
+        if (motionManager == nil) {
+            motionManager = [[CMMotionManager alloc] init];
+        }
 
-    /* Shorter times between updates can significantly increase CPU usage. */
-    motionManager.accelerometerUpdateInterval = 0.1;
-    [motionManager startAccelerometerUpdates];
+        /* Shorter times between updates can significantly increase CPU usage. */
+        motionManager.accelerometerUpdateInterval = 0.1;
+        [motionManager startAccelerometerUpdates];
+    }
 
     return 0;
 }
@@ -104,11 +114,13 @@ static void SDL_SYS_AccelerometerUpdate(SDL_Joystick * joystick)
     const SInt16 maxsint16 = 0x7FFF;
     CMAcceleration accel;
 
-    if (!motionManager.accelerometerActive) {
-        return;
-    }
+    @autoreleasepool {
+        if (!motionManager.accelerometerActive) {
+            return;
+        }
 
-    accel = [[motionManager accelerometerData] acceleration];
+        accel = motionManager.accelerometerData.acceleration;
+    }
 
     /*
      Convert accelerometer data from floating point to Sint16, which is what
@@ -152,17 +164,20 @@ SDL_SYS_JoystickUpdate(SDL_Joystick * joystick)
 void
 SDL_SYS_JoystickClose(SDL_Joystick * joystick)
 {
-    [motionManager stopAccelerometerUpdates];
+    @autoreleasepool {
+        [motionManager stopAccelerometerUpdates];
+    }
 }
 
 /* Function to perform any system-specific joystick related cleanup */
 void
 SDL_SYS_JoystickQuit(void)
 {
-    if (motionManager != nil) {
-        [motionManager release];
+    @autoreleasepool {
         motionManager = nil;
     }
+
+    numjoysticks = 0;
 }
 
 SDL_JoystickGUID SDL_SYS_JoystickGetDeviceGUID( int device_index )
diff --git a/src/power/uikit/SDL_syspower.m b/src/power/uikit/SDL_syspower.m
index 60c4274..4984b78 100644
--- a/src/power/uikit/SDL_syspower.m
+++ b/src/power/uikit/SDL_syspower.m
@@ -50,24 +50,24 @@ SDL_UIKit_UpdateBatteryMonitoring(void)
 SDL_bool
 SDL_GetPowerInfo_UIKit(SDL_PowerState * state, int *seconds, int *percent)
 {
-    UIDevice *uidev = [UIDevice currentDevice];
+    @autoreleasepool {
+        UIDevice *uidev = [UIDevice currentDevice];
 
-    if (!SDL_UIKitLastPowerInfoQuery) {
-        SDL_assert([uidev isBatteryMonitoringEnabled] == NO);
-        [uidev setBatteryMonitoringEnabled:YES];
-    }
+        if (!SDL_UIKitLastPowerInfoQuery) {
+            SDL_assert(uidev.isBatteryMonitoringEnabled == NO);
+            uidev.batteryMonitoringEnabled = YES;
+        }
 
-    /* UIKit_GL_SwapWindow() (etc) will check this and disable the battery
-     *  monitoring if the app hasn't queried it in the last X seconds.
-     *  Apparently monitoring the battery burns battery life.  :)
-     *  Apple's docs say not to monitor the battery unless you need it.
-     */
-    SDL_UIKitLastPowerInfoQuery = SDL_GetTicks();
+        /* UIKit_GL_SwapWindow() (etc) will check this and disable the battery
+         *  monitoring if the app hasn't queried it in the last X seconds.
+         *  Apparently monitoring the battery burns battery life.  :)
+         *  Apple's docs say not to monitor the battery unless you need it.
+         */
+        SDL_UIKitLastPowerInfoQuery = SDL_GetTicks();
 
-    *seconds = -1;   /* no API to estimate this in UIKit. */
+        *seconds = -1;   /* no API to estimate this in UIKit. */
 
-    switch ([uidev batteryState])
-    {
+        switch (uidev.batteryState) {
         case UIDeviceBatteryStateCharging:
             *state = SDL_POWERSTATE_CHARGING;
             break;
@@ -84,11 +84,12 @@ SDL_GetPowerInfo_UIKit(SDL_PowerState * state, int *seconds, int *percent)
         default:
             *state = SDL_POWERSTATE_UNKNOWN;
             break;
-    }
+        }
 
-    const float level = [uidev batteryLevel];
-    *percent = ( (level < 0.0f) ? -1 : ((int) ((level * 100) + 0.5f)) );
-    return SDL_TRUE;            /* always the definitive answer on iOS. */
+        const float level = uidev.batteryLevel;
+        *percent = ( (level < 0.0f) ? -1 : ((int) ((level * 100) + 0.5f)) );
+        return SDL_TRUE; /* always the definitive answer on iOS. */
+    }
 }
 
 #endif /* SDL_POWER_UIKIT */
diff --git a/src/render/opengles/SDL_render_gles.c b/src/render/opengles/SDL_render_gles.c
index 72cce30..617bf65 100644
--- a/src/render/opengles/SDL_render_gles.c
+++ b/src/render/opengles/SDL_render_gles.c
@@ -55,6 +55,7 @@ static const float inv255f = 1.0f / 255.0f;
 static SDL_Renderer *GLES_CreateRenderer(SDL_Window * window, Uint32 flags);
 static void GLES_WindowEvent(SDL_Renderer * renderer,
                              const SDL_WindowEvent *event);
+static int GLES_GetOutputSize(SDL_Renderer * renderer, int *w, int *h);
 static int GLES_CreateTexture(SDL_Renderer * renderer, SDL_Texture * texture);
 static int GLES_UpdateTexture(SDL_Renderer * renderer, SDL_Texture * texture,
                               const SDL_Rect * rect, const void *pixels,
@@ -321,6 +322,7 @@ GLES_CreateRenderer(SDL_Window * window, Uint32 flags)
     }
 
     renderer->WindowEvent = GLES_WindowEvent;
+    renderer->GetOutputSize = GLES_GetOutputSize;
     renderer->CreateTexture = GLES_CreateTexture;
     renderer->UpdateTexture = GLES_UpdateTexture;
     renderer->LockTexture = GLES_LockTexture;
@@ -438,6 +440,13 @@ GLES_WindowEvent(SDL_Renderer * renderer, const SDL_WindowEvent *event)
     }
 }
 
+static int
+GLES_GetOutputSize(SDL_Renderer * renderer, int *w, int *h)
+{
+    SDL_GL_GetDrawableSize(renderer->window, w, h);
+    return 0;
+}
+
 static SDL_INLINE int
 power_of_2(int input)
 {
diff --git a/src/render/opengles2/SDL_render_gles2.c b/src/render/opengles2/SDL_render_gles2.c
index 71ee708..05ef00a 100644
--- a/src/render/opengles2/SDL_render_gles2.c
+++ b/src/render/opengles2/SDL_render_gles2.c
@@ -370,6 +370,13 @@ GLES2_WindowEvent(SDL_Renderer * renderer, const SDL_WindowEvent *event)
 }
 
 static int
+GLES2_GetOutputSize(SDL_Renderer * renderer, int *w, int *h)
+{
+    SDL_GL_GetDrawableSize(renderer->window, w, h);
+    return 0;
+}
+
+static int
 GLES2_UpdateViewport(SDL_Renderer * renderer)
 {
     GLES2_DriverContext *data = (GLES2_DriverContext *)renderer->driverdata;
@@ -2059,6 +2066,7 @@ GLES2_CreateRenderer(SDL_Window *window, Uint32 flags)
 
     /* Populate the function pointers for the module */
     renderer->WindowEvent         = &GLES2_WindowEvent;
+    renderer->GetOutputSize       = &GLES2_GetOutputSize;
     renderer->CreateTexture       = &GLES2_CreateTexture;
     renderer->UpdateTexture       = &GLES2_UpdateTexture;
     renderer->UpdateTextureYUV    = &GLES2_UpdateTextureYUV;
diff --git a/src/video/SDL_video.c b/src/video/SDL_video.c
index c8cb2fa..81d6254 100644
--- a/src/video/SDL_video.c
+++ b/src/video/SDL_video.c
@@ -1107,22 +1107,22 @@ SDL_RestoreMousePosition(SDL_Window *window)
     }
 }
 
-static void
+static int
 SDL_UpdateFullscreenMode(SDL_Window * window, SDL_bool fullscreen)
 {
     SDL_VideoDisplay *display;
     SDL_Window *other;
 
-    CHECK_WINDOW_MAGIC(window,);
+    CHECK_WINDOW_MAGIC(window,-1);
 
     /* if we are in the process of hiding don't go back to fullscreen */
     if ( window->is_hiding && fullscreen )
-        return;
+        return 0;
     
 #ifdef __MACOSX__
     if (Cocoa_SetWindowFullscreenSpace(window, fullscreen)) {
         window->last_fullscreen_flags = window->flags;
-        return;
+        return 0;
     }
 #endif
 
@@ -1139,7 +1139,7 @@ SDL_UpdateFullscreenMode(SDL_Window * window, SDL_bool fullscreen)
     /* See if anything needs to be done now */
     if ((display->fullscreen_window == window) == fullscreen) {
         if ((window->last_fullscreen_flags & FULLSCREEN_MASK) == (window->flags & FULLSCREEN_MASK)) {
-            return;
+            return 0;
         }
     }
 
@@ -1168,9 +1168,13 @@ SDL_UpdateFullscreenMode(SDL_Window * window, SDL_bool fullscreen)
 
                 /* only do the mode change if we want exclusive fullscreen */
                 if ((window->flags & SDL_WINDOW_FULLSCREEN_DESKTOP) != SDL_WINDOW_FULLSCREEN_DESKTOP) {
-                    SDL_SetDisplayModeForDisplay(display, &fullscreen_mode);
+                    if (SDL_SetDisplayModeForDisplay(display, &fullscreen_mode) < 0) {
+                        return -1;
+                    }
                 } else {
-                    SDL_SetDisplayModeForDisplay(display, NULL);
+                    if (SDL_SetDisplayModeForDisplay(display, NULL) < 0) {
+                        return -1;
+                    }
                 }
 
                 if (_this->SetWindowFullscreen) {
@@ -1189,7 +1193,7 @@ SDL_UpdateFullscreenMode(SDL_Window * window, SDL_bool fullscreen)
                 SDL_RestoreMousePosition(other);
 
                 window->last_fullscreen_flags = window->flags;
-                return;
+                return 0;
             }
         }
     }
@@ -1209,6 +1213,7 @@ SDL_UpdateFullscreenMode(SDL_Window * window, SDL_bool fullscreen)
     SDL_RestoreMousePosition(window);
 
     window->last_fullscreen_flags = window->flags;
+    return 0;
 }
 
 #define CREATE_FLAGS \
@@ -1935,9 +1940,7 @@ SDL_SetWindowFullscreen(SDL_Window * window, Uint32 flags)
     window->flags &= ~FULLSCREEN_MASK;
     window->flags |= flags;
 
-    SDL_UpdateFullscreenMode(window, FULLSCREEN_VISIBLE(window));
-
-    return 0;
+    return SDL_UpdateFullscreenMode(window, FULLSCREEN_VISIBLE(window));
 }
 
 static SDL_Surface *
diff --git a/src/video/uikit/SDL_uikitappdelegate.h b/src/video/uikit/SDL_uikitappdelegate.h
index d5430be..45dd91e 100644
--- a/src/video/uikit/SDL_uikitappdelegate.h
+++ b/src/video/uikit/SDL_uikitappdelegate.h
@@ -21,12 +21,21 @@
 
 #import <UIKit/UIKit.h>
 
-@interface SDLUIKitDelegate : NSObject<UIApplicationDelegate> {
-}
+@interface SDLLaunchScreenController : UIViewController
 
-+ (id) sharedAppDelegate;
+- (instancetype)init;
+- (void)loadView;
+- (NSUInteger)supportedInterfaceOrientations;
+
+@end
+
+@interface SDLUIKitDelegate : NSObject<UIApplicationDelegate>
+
++ (id)sharedAppDelegate;
 + (NSString *)getAppDelegateClassName;
 
+- (void)hideLaunchScreen;
+
 @end
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/uikit/SDL_uikitappdelegate.m b/src/video/uikit/SDL_uikitappdelegate.m
index f112672..2ae6182 100644
--- a/src/video/uikit/SDL_uikitappdelegate.m
+++ b/src/video/uikit/SDL_uikitappdelegate.m
@@ -28,8 +28,10 @@
 #include "SDL_system.h"
 #include "SDL_main.h"
 
-#include "SDL_uikitappdelegate.h"
-#include "SDL_uikitmodes.h"
+#import "SDL_uikitappdelegate.h"
+#import "SDL_uikitmodes.h"
+#import "SDL_uikitwindow.h"
+
 #include "../../events/SDL_events_c.h"
 
 #ifdef main
@@ -39,12 +41,10 @@
 static int forward_argc;
 static char **forward_argv;
 static int exit_status;
-static UIWindow *launch_window;
 
 int main(int argc, char **argv)
 {
     int i;
-    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
 
     /* store arguments */
     forward_argc = argc;
@@ -56,7 +56,9 @@ int main(int argc, char **argv)
     forward_argv[i] = NULL;
 
     /* Give over control to run loop, SDLUIKitDelegate will handle most things from here */
-    UIApplicationMain(argc, argv, NULL, [SDLUIKitDelegate getAppDelegateClassName]);
+    @autoreleasepool {
+        UIApplicationMain(argc, argv, nil, [SDLUIKitDelegate getAppDelegateClassName]);
+    }
 
     /* free the memory we used to hold copies of argc and argv */
     for (i = 0; i < forward_argc; i++) {
@@ -64,7 +66,6 @@ int main(int argc, char **argv)
     }
     free(forward_argv);
 
-    [pool release];
     return exit_status;
 }
 
@@ -75,224 +76,262 @@ SDL_IdleTimerDisabledChanged(void *userdata, const char *name, const char *oldVa
     [UIApplication sharedApplication].idleTimerDisabled = disable;
 }
 
-
-@interface SDL_launchscreenviewcontroller : UIViewController {
-	
-}
-
-@end
-
-@implementation SDL_launchscreenviewcontroller
-
-- (id)init
+/* Load a launch image using the old UILaunchImageFile-era naming rules. */
+static UIImage *
+SDL_LoadLaunchImageNamed(NSString *name, int screenh)
 {
-    self = [super init];
-    if (self == nil) {
-        return nil;
+    UIInterfaceOrientation curorient = [UIApplication sharedApplication].statusBarOrientation;
+    UIUserInterfaceIdiom idiom = [UIDevice currentDevice].userInterfaceIdiom;
+    UIImage *image = nil;
+
+    if (idiom == UIUserInterfaceIdiomPhone && screenh == 568) {
+        /* The image name for the iPhone 5 uses its height as a suffix. */
+        image = [UIImage imageNamed:[NSString stringWithFormat:@"%@-568h", name]];
+    } else if (idiom == UIUserInterfaceIdiomPad) {
+        /* iPad apps can launch in any orientation. */
+        if (UIInterfaceOrientationIsLandscape(curorient)) {
+            if (curorient == UIInterfaceOrientationLandscapeLeft) {
+                image = [UIImage imageNamed:[NSString stringWithFormat:@"%@-LandscapeLeft", name]];
+            } else {
+                image = [UIImage imageNamed:[NSString stringWithFormat:@"%@-LandscapeRight", name]];
+            }
+            if (!image) {
+                image = [UIImage imageNamed:[NSString stringWithFormat:@"%@-Landscape", name]];
+            }
+        } else {
+            if (curorient == UIInterfaceOrientationPortraitUpsideDown) {
+                image = [UIImage imageNamed:[NSString stringWithFormat:@"%@-PortraitUpsideDown", name]];
+            }
+            if (!image) {
+                image = [UIImage imageNamed:[NSString stringWithFormat:@"%@-Portrait", name]];
+            }
+        }
     }
 
-    NSString* launch_screen_name = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"UILaunchStoryboardName"];
-
-    if(launch_screen_name) {
-        // TODO: If the NIB is not in the bundle, this will throw an exception. We might consider a pre-emptive check, but returning a useless viewcontroller isn't helpful and the check should be outside.
-        UIView* launch_screen = [[[NSBundle mainBundle] loadNibNamed:launch_screen_name owner:self options:nil] objectAtIndex:0];
-        CGSize size = [UIScreen mainScreen].bounds.size;
-        
-        CGRect bounds = CGRectMake(0, 0, size.width, size.height);
-        
-        [launch_screen setFrame:bounds];
-        [self setView:launch_screen];
-        [launch_screen release];
+    if (!image) {
+        image = [UIImage imageNamed:name];
     }
 
-    
-
-
-    return self;
+    return image;
 }
 
-- (NSUInteger)supportedInterfaceOrientations
-{
-    NSUInteger orientationMask = UIInterfaceOrientationMaskAll;
-    
-    /* Don't allow upside-down orientation on the phone, so answering calls is in the natural orientation */
-    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
-        orientationMask &= ~UIInterfaceOrientationMaskPortraitUpsideDown;
-    }
-    return orientationMask;
+@implementation SDLLaunchScreenController {
+    UIInterfaceOrientationMask supportedOrientations;
 }
 
-- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orient
+- (instancetype)init
 {
-    NSUInteger orientationMask = [self supportedInterfaceOrientations];
-    return (orientationMask & (1 << orient));
-}
-
-@end
-
-
-@interface SDL_splashviewcontroller : UIViewController {
-    UIImageView *splash;
-    UIImage *splashPortrait;
-    UIImage *splashLandscape;
-}
+    if (!(self = [super initWithNibName:nil bundle:nil])) {
+        return nil;
+    }
 
-- (void)updateSplashImage:(UIInterfaceOrientation)interfaceOrientation;
-@end
+    NSBundle *bundle = [NSBundle mainBundle];
+    NSString *screenname = [bundle objectForInfoDictionaryKey:@"UILaunchStoryboardName"];
 
-@implementation SDL_splashviewcontroller
+    /* Normally we don't want to rotate from the initial orientation. */
+    supportedOrientations = (1 << [UIApplication sharedApplication].statusBarOrientation);
 
-- (id)init
-{
-    self = [super init];
-    if (self == nil) {
-        return nil;
+    /* Launch screens were added in iOS 8. Otherwise we use launch images. */
+    if (screenname && UIKit_IsSystemVersionAtLeast(8.0)) {
+        @try {
+            self.view = [bundle loadNibNamed:screenname owner:self options:nil][0];
+        }
+        @catch (NSException *exception) {
+            /* iOS displays a blank screen rather than falling back to an image,
+             * if a launch screen name is specified but it fails to load. */
+            return nil;
+        }
     }
 
-    self->splash = [[UIImageView alloc] init];
-    [self setView:self->splash];
-
-    CGSize size = [UIScreen mainScreen].bounds.size;
-    float height = SDL_max(size.width, size.height);
-    /* FIXME: Some where around iOS 7, UILaunchImages in the Info.plist was introduced which explicitly maps image names to devices and orientations.
-     This gets rid of the hardcoded magic file names and allows more control for OS version, orientation, retina, and device.
-     But this existing code needs to be modified to look in the Info.plist for each key and act appropriately for the correct iOS version.
-     But iOS 8 superscedes this process and introduces the LaunchScreen NIB which uses autolayout to handle all orientations and devices.
-     Since we now have a LaunchScreen solution, this may never get fixed, 
-     but this note is here for anybody trying to debug their program on iOS 7 and doesn't understand why their Info.plist isn't working.
-     */
-    self->splashPortrait = [UIImage imageNamed:[NSString stringWithFormat:@"Default-%dh.png", (int)height]];
-    if (!self->splashPortrait) {
-        self->splashPortrait = [UIImage imageNamed:@"Default.png"];
-    }
-    self->splashLandscape = [UIImage imageNamed:@"Default-Landscape.png"];
-    if (!self->splashLandscape && self->splashPortrait) {
-        self->splashLandscape = [[UIImage alloc] initWithCGImage: self->splashPortrait.CGImage
-                                                           scale: 1.0
-                                                     orientation: UIImageOrientationRight];
-    }
-    if (self->splashPortrait) {
-        [self->splashPortrait retain];
-    }
-    if (self->splashLandscape) {
-        [self->splashLandscape retain];
-    }
+    if (!self.view) {
+        NSArray *launchimages = [bundle objectForInfoDictionaryKey:@"UILaunchImages"];
+        UIInterfaceOrientation curorient = [UIApplication sharedApplication].statusBarOrientation;
+        NSString *imagename = nil;
+        UIImage *image = nil;
 
-    [self updateSplashImage:[[UIApplication sharedApplication] statusBarOrientation]];
+        int screenw = (int)([UIScreen mainScreen].bounds.size.width + 0.5);
+        int screenh = (int)([UIScreen mainScreen].bounds.size.height + 0.5);
 
-    return self;
-}
+        /* We always want portrait-oriented size, to match UILaunchImageSize. */
+        if (screenw > screenh) {
+            int width = screenw;
+            screenw = screenh;
+            screenh = width;
+        }
 
-- (NSUInteger)supportedInterfaceOrientations
-{
-    NSUInteger orientationMask = UIInterfaceOrientationMaskAll;
+        /* Xcode 5 introduced a dictionary of launch images in Info.plist. */
+        if (launchimages) {
+            for (NSDictionary *dict in launchimages) {
+                UIInterfaceOrientationMask orientmask = UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskPortraitUpsideDown;
+                NSString *minversion   = dict[@"UILaunchImageMinimumOSVersion"];
+                NSString *sizestring   = dict[@"UILaunchImageSize"];
+                NSString *orientstring = dict[@"UILaunchImageOrientation"];
+
+                /* Ignore this image if the current version is too low. */
+                if (minversion && !UIKit_IsSystemVersionAtLeast(minversion.doubleValue)) {
+                    continue;
+                }
+
+                /* Ignore this image if the size doesn't match. */
+                if (sizestring) {
+                    CGSize size = CGSizeFromString(sizestring);
+                    if ((int)(size.width + 0.5) != screenw || (int)(size.height + 0.5) != screenh) {
+                        continue;
+                    }
+                }
+
+                if (orientstring) {
+                    if ([orientstring isEqualToString:@"PortraitUpsideDown"]) {
+                        orientmask = UIInterfaceOrientationMaskPortraitUpsideDown;
+                    } else if ([orientstring isEqualToString:@"Landscape"]) {
+                        orientmask = UIInterfaceOrientationMaskLandscape;
+                    } else if ([orientstring isEqualToString:@"LandscapeLeft"]) {
+                        orientmask = UIInterfaceOrientationMaskLandscapeLeft;
+                    } else if ([orientstring isEqualToString:@"LandscapeRight"]) {
+                        orientmask = UIInterfaceOrientationMaskLandscapeRight;
+                    }
+                }
+
+                /* Ignore this image if the orientation doesn't match. */
+                if ((orientmask & (1 << curorient)) == 0) {
+                    continue;
+                }
+
+                imagename = dict[@"UILaunchImageName"];
+            }
+
+            if (imagename) {
+                image = [UIImage imageNamed:imagename];
+            }
+        } else {
+            imagename = [bundle objectForInfoDictionaryKey:@"UILaunchImageFile"];
+
+            if (imagename) {
+                image = SDL_LoadLaunchImageNamed(imagename, screenh);
+            }
+
+            if (!image) {
+                image = SDL_LoadLaunchImageNamed(@"Default", screenh);
+            }
+        }
+
+        if (image) {
+            if (image.size.width > image.size.height) {
+                supportedOrientations = UIInterfaceOrientationMaskLandscape;
+            } else {
+                supportedOrientations = UIInterfaceOrientationMaskPortrait;
+            }
 
-    /* Don't allow upside-down orientation on the phone, so answering calls is in the natural orientation */
-    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
-        orientationMask &= ~UIInterfaceOrientationMaskPortraitUpsideDown;
+            self.view = [[UIImageView alloc] initWithImage:image];
+        }
     }
-    return orientationMask;
-}
 
-- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orient
-{
-    NSUInteger orientationMask = [self supportedInterfaceOrientations];
-    return (orientationMask & (1 << orient));
+    return self;
 }
 
-- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration
+- (void)loadView
 {
-    [self updateSplashImage:interfaceOrientation];
+    /* Do nothing. */
 }
 
-- (void)updateSplashImage:(UIInterfaceOrientation)interfaceOrientation
+- (NSUInteger)supportedInterfaceOrientations
 {
-    UIImage *image;
-
-    if (UIInterfaceOrientationIsLandscape(interfaceOrientation)) {
-        image = self->splashLandscape;
-    } else {
-        image = self->splashPortrait;
-    }
-    if (image)
-    {
-        splash.image = image;
-    }
+    return supportedOrientations;
 }
 
 @end
 
-
-@implementation SDLUIKitDelegate
+@implementation SDLUIKitDelegate {
+    UIWindow *launchWindow;
+}
 
 /* convenience method */
-+ (id) sharedAppDelegate
++ (id)sharedAppDelegate
 {
-    /* the delegate is set in UIApplicationMain(), which is garaunteed to be called before this method */
-    return [[UIApplication sharedApplication] delegate];
+    /* the delegate is set in UIApplicationMain(), which is guaranteed to be
+     * called before this method */
+    return [UIApplication sharedApplication].delegate;
 }
 
 + (NSString *)getAppDelegateClassName
 {
-    /* subclassing notice: when you subclass this appdelegate, make sure to add a category to override
-       this method and return the actual name of the delegate */
+    /* subclassing notice: when you subclass this appdelegate, make sure to add
+     * a category to override this method and return the actual name of the
+     * delegate */
     return @"SDLUIKitDelegate";
 }
 
-- (id)init
+- (void)hideLaunchScreen
 {
-    self = [super init];
-    return self;
+    UIWindow *window = launchWindow;
+
+    if (!window || window.hidden) {
+        return;
+    }
+
+    launchWindow = nil;
+
+    /* Do a nice animated fade-out (roughly matches the real launch behavior.) */
+    [UIView animateWithDuration:0.2 animations:^{
+        window.alpha = 0.0;
+    } completion:^(BOOL finished) {
+        window.hidden = YES;
+    }];
 }
 
 - (void)postFinishLaunch
 {
+    /* Hide the launch screen the next time the run loop is run. SDL apps will
+     * have a chance to load resources while the launch screen is still up. */
+    [self performSelector:@selector(hideLaunchScreen) withObject:nil afterDelay:0.0];
+
     /* run the user's application, passing argc and argv */
     SDL_iPhoneSetEventPump(SDL_TRUE);
     exit_status = SDL_main(forward_argc, forward_argv);
     SDL_iPhoneSetEventPump(SDL_FALSE);
 
-    /* If we showed a splash image, clean it up */
-    if (launch_window) {
-        [launch_window release];
-        launch_window = NULL;
+    if (launchWindow) {
+        launchWindow.hidden = YES;
+        launchWindow = nil;
     }
 
     /* exit, passing the return status from the user's application */
-    /* We don't actually exit to support applications that do setup in
-     * their main function and then allow the Cocoa event loop to run.
-     */
+    /* We don't actually exit to support applications that do setup in their
+     * main function and then allow the Cocoa event loop to run. */
     /* exit(exit_status); */
 }
 
 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
 {
-    /* Keep the launch image up until we set a video mode */
-    launch_window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
-
-    /* iOS 8 introduces LaunchScreen NIBs which use autolayout to handle all devices and orientations with a single NIB instead of multiple launch images.
-     This is also the only way to get the App Store badge "Optimized for iPhone 6 and iPhone 6 Plus".
-     So if the application is running on iOS 8 or greater AND has specified a LaunchScreen in their Info.plist, we should use the LaunchScreen NIB.
-     Otherwise, we should fallback to the legacy behavior of launch screen images.
-     */
-    NSString* launch_screen_name = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"UILaunchStoryboardName"];
-    if( ([[UIDevice currentDevice].systemVersion intValue] >= 8) && (nil != launch_screen_name) ) {
-        // iOS 8.0 and above uses LaunchScreen.xib
-        SDL_launchscreenviewcontroller* launch_screen_view_controller = [[SDL_launchscreenviewcontroller alloc] init];
-        launch_window.rootViewController = launch_screen_view_controller;
-        [launch_window addSubview:launch_screen_view_controller.view];
-        [launch_window makeKeyAndVisible];
-    } else {
-        // Anything less than iOS 8.0
-
-        UIViewController *splashViewController = [[SDL_splashviewcontroller alloc] init];
-        launch_window.rootViewController = splashViewController;
-        [launch_window addSubview:splashViewController.view];
-        [launch_window makeKeyAndVisible];
+    NSBundle *bundle = [NSBundle mainBundle];
+    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
+
+#if SDL_IPHONE_LAUNCHSCREEN
+    /* The normal launch screen is displayed until didFinishLaunching returns,
+     * but SDL_main is called after that happens and there may be a noticeable
+     * delay between the start of SDL_main and when the first real frame is
+     * displayed (e.g. if resources are loaded before SDL_GL_SwapWindow is
+     * called), so we show the launch screen programmatically until the first
+     * time events are pumped. */
+    UIViewController *viewcontroller = [[SDLLaunchScreenController alloc] init];
+
+    if (viewcontroller.view) {
+        launchWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
+
+        /* We don't want the launch window immediately hidden when a real SDL
+         * window is shown - we fade it out ourselves when we're ready. */
+        launchWindow.windowLevel = UIWindowLevelNormal + 1.0;
+
+        /* Show the window but don't make it key. Events should always go to
+         * other windows when possible. */
+        launchWindow.hidden = NO;
+
+        launchWindow.rootViewController = viewcontroller;
     }
+#endif
 
     /* Set working directory to resource path */
-    [[NSFileManager defaultManager] changeCurrentDirectoryPath: [[NSBundle mainBundle] resourcePath]];
+    [[NSFileManager defaultManager] changeCurrentDirectoryPath:[bundle resourcePath]];
 
     /* register a callback for the idletimer hint */
     SDL_AddHintCallback(SDL_HINT_IDLE_TIMER_DISABLED,
@@ -314,7 +353,35 @@ SDL_IdleTimerDisabledChanged(void *userdata, const char *name, const char *oldVa
     SDL_SendAppEvent(SDL_APP_LOWMEMORY);
 }
 
-- (void) applicationWillResignActive:(UIApplication*)application
+- (void)application:(UIApplication *)application didChangeStatusBarOrientation:(UIInterfaceOrientation)oldStatusBarOrientation
+{
+    BOOL isLandscape = UIInterfaceOrientationIsLandscape(application.statusBarOrientation);
+    SDL_VideoDevice *_this = SDL_GetVideoDevice();
+
+    if (_this && _this->num_displays > 0) {
+        SDL_DisplayMode *desktopmode = &_this->displays[0].desktop_mode;
+        SDL_DisplayMode *currentmode = &_this->displays[0].current_mode;
+
+        /* The desktop display mode should be kept in sync with the screen
+         * orientation so that updating a window's fullscreen state to
+         * SDL_WINDOW_FULLSCREEN_DESKTOP keeps the window dimensions in the
+         * correct orientation. */
+        if (isLandscape != (desktopmode->w > desktopmode->h)) {
+            int height = desktopmode->w;
+            desktopmode->w = desktopmode->h;
+            desktopmode->h = height;
+        }
+
+        /* Same deal with the current mode + SDL_GetCurrentDisplayMode. */
+        if (isLandscape != (currentmode->w > currentmode->h)) {
+            int height = currentmode->w;
+            currentmode->w = currentmode->h;
+            currentmode->h = height;
+        }
+    }
+}
+
+- (void)applicationWillResignActive:(UIApplication*)application
 {
     SDL_VideoDevice *_this = SDL_GetVideoDevice();
     if (_this) {
@@ -327,17 +394,17 @@ SDL_IdleTimerDisabledChanged(void *userdata, const char *name, const char *oldVa
     SDL_SendAppEvent(SDL_APP_WILLENTERBACKGROUND);
 }
 
-- (void) applicationDidEnterBackground:(UIApplication*)application
+- (void)applicationDidEnterBackground:(UIApplication*)application
 {
     SDL_SendAppEvent(SDL_APP_DIDENTERBACKGROUND);
 }
 
-- (void) applicationWillEnterForeground:(UIApplication*)application
+- (void)applicationWillEnterForeground:(UIApplication*)application
 {
     SDL_SendAppEvent(SDL_APP_WILLENTERFOREGROUND);
 }
 
-- (void) applicationDidBecomeActive:(UIApplication*)application
+- (void)applicationDidBecomeActive:(UIApplication*)application
 {
     SDL_SendAppEvent(SDL_APP_DIDENTERFOREGROUND);
 
@@ -353,11 +420,11 @@ SDL_IdleTimerDisabledChanged(void *userdata, const char *name, const char *oldVa
 
 - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
 {
-    NSURL *fileURL = [url filePathURL];
+    NSURL *fileURL = url.filePathURL;
     if (fileURL != nil) {
-        SDL_SendDropFile([[fileURL path] UTF8String]);
+        SDL_SendDropFile([fileURL.path UTF8String]);
     } else {
-        SDL_SendDropFile([[url absoluteString] UTF8String]);
+        SDL_SendDropFile([url.absoluteString UTF8String]);
     }
     return YES;
 }
diff --git a/src/video/uikit/SDL_uikitevents.m b/src/video/uikit/SDL_uikitevents.m
index 94fba87..48bb1bd 100644
--- a/src/video/uikit/SDL_uikitevents.m
+++ b/src/video/uikit/SDL_uikitevents.m
@@ -40,8 +40,9 @@ SDL_iPhoneSetEventPump(SDL_bool enabled)
 void
 UIKit_PumpEvents(_THIS)
 {
-    if (!UIKit_EventPumpEnabled)
+    if (!UIKit_EventPumpEnabled) {
         return;
+    }
 
     /* Let the run loop run for a short amount of time: long enough for
        touch events to get processed (which is important to get certain
diff --git a/src/video/uikit/SDL_uikitmessagebox.m b/src/video/uikit/SDL_uikitmessagebox.m
index c24f3ff..f540f0c 100644
--- a/src/video/uikit/SDL_uikitmessagebox.m
+++ b/src/video/uikit/SDL_uikitmessagebox.m
@@ -30,35 +30,20 @@
 
 static SDL_bool s_showingMessageBox = SDL_FALSE;
 
-@interface UIKit_UIAlertViewDelegate : NSObject <UIAlertViewDelegate> {
-@private
-    int *clickedButtonIndex;
-}
+@interface SDLAlertViewDelegate : NSObject <UIAlertViewDelegate>
 
-- (id)initWithButtonIndex:(int *)_buttonIndex;
-- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex;
+@property (nonatomic, assign) int clickedIndex;
 
 @end
 
-@implementation UIKit_UIAlertViewDelegate
-
-- (id)initWithButtonIndex:(int *)buttonIndex
-{
-    self = [self init];
-    if (self == nil) {
-        return nil;
-    }
-    self->clickedButtonIndex = buttonIndex;
-
-    return self;
-}
+@implementation SDLAlertViewDelegate
 
-- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex;
+- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
 {
-    *clickedButtonIndex = (int)buttonIndex;
+    _clickedIndex = (int)buttonIndex;
 }
 
-@end /* UIKit_UIAlertViewDelegate */
+@end
 
 
 SDL_bool
@@ -70,41 +55,38 @@ UIKit_ShowingMessageBox()
 int
 UIKit_ShowMessageBox(const SDL_MessageBoxData *messageboxdata, int *buttonid)
 {
-    int clicked;
-
-    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
-
-    UIAlertView* alert = [[UIAlertView alloc] init];
+    int i;
+    const SDL_MessageBoxButtonData *buttons = messageboxdata->buttons;
 
-    alert.title = [NSString stringWithUTF8String:messageboxdata->title];
-    alert.message = [NSString stringWithUTF8String:messageboxdata->message];
-    alert.delegate = [[UIKit_UIAlertViewDelegate alloc] initWithButtonIndex:&clicked];
+    @autoreleasepool {
+        UIAlertView *alert = [[UIAlertView alloc] init];
+        SDLAlertViewDelegate *delegate = [[SDLAlertViewDelegate alloc] init];
 
-    const SDL_MessageBoxButtonData *buttons = messageboxdata->buttons;
-    int i;
-    for (i = 0; i < messageboxdata->numbuttons; ++i) {
-        [alert addButtonWithTitle:[[NSString alloc] initWithUTF8String:buttons[i].text]];
-    }
+        alert.delegate = delegate;
+        alert.title = @(messageboxdata->title);
+        alert.message = @(messageboxdata->message);
 
-    /* Set up for showing the alert */
-    clicked = messageboxdata->numbuttons;
+        for (i = 0; i < messageboxdata->numbuttons; ++i) {
+            [alert addButtonWithTitle:@(buttons[i].text)];
+        }
 
-    [alert show];
+        /* Set up for showing the alert */
+        delegate.clickedIndex = messageboxdata->numbuttons;
 
-    /* Run the main event loop until the alert has finished */
-    /* Note that this needs to be done on the main thread */
-    s_showingMessageBox = SDL_TRUE;
-    while (clicked == messageboxdata->numbuttons) {
-        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
-    }
-    s_showingMessageBox = SDL_FALSE;
+        [alert show];
 
-    *buttonid = messageboxdata->buttons[clicked].buttonid;
+        /* Run the main event loop until the alert has finished */
+        /* Note that this needs to be done on the main thread */
+        s_showingMessageBox = SDL_TRUE;
+        while (delegate.clickedIndex == messageboxdata->numbuttons) {
+            [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
+        }
+        s_showingMessageBox = SDL_FALSE;
 
-    [alert.delegate release];
-    [alert release];
+        *buttonid = messageboxdata->buttons[delegate.clickedIndex].buttonid;
 
-    [pool release];
+        alert.delegate = nil;
+    }
 
     return 0;
 }
diff --git a/src/video/uikit/SDL_uikitmodes.h b/src/video/uikit/SDL_uikitmodes.h
index 9f2e9dd..65c185f 100644
--- a/src/video/uikit/SDL_uikitmodes.h
+++ b/src/video/uikit/SDL_uikitmodes.h
@@ -25,17 +25,17 @@
 
 #include "SDL_uikitvideo.h"
 
-typedef struct
-{
-    UIScreen *uiscreen;
-    CGFloat scale;
-} SDL_DisplayData;
-
-typedef struct
-{
-    UIScreenMode *uiscreenmode;
-    CGFloat scale;
-} SDL_DisplayModeData;
+@interface SDL_DisplayData : NSObject
+
+@property (nonatomic, strong) UIScreen *uiscreen;
+
+@end
+
+@interface SDL_DisplayModeData : NSObject
+
+@property (nonatomic, strong) UIScreenMode *uiscreenmode;
+
+@end
 
 extern SDL_bool UIKit_IsDisplayLandscape(UIScreen *uiscreen);
 
diff --git a/src/video/uikit/SDL_uikitmodes.m b/src/video/uikit/SDL_uikitmodes.m
index 05e33d9..1fb9a03 100644
--- a/src/video/uikit/SDL_uikitmodes.m
+++ b/src/video/uikit/SDL_uikitmodes.m
@@ -25,27 +25,36 @@
 #include "SDL_assert.h"
 #include "SDL_uikitmodes.h"
 
+@implementation SDL_DisplayData
+
+@synthesize uiscreen;
+
+@end
+
+@implementation SDL_DisplayModeData
+
+@synthesize uiscreenmode;
+
+@end
+
 
 static int
 UIKit_AllocateDisplayModeData(SDL_DisplayMode * mode,
-    UIScreenMode * uiscreenmode, CGFloat scale)
+    UIScreenMode * uiscreenmode)
 {
-    SDL_DisplayModeData *data = NULL;
+    SDL_DisplayModeData *data = nil;
 
     if (uiscreenmode != nil) {
         /* Allocate the display mode data */
-        data = (SDL_DisplayModeData *) SDL_malloc(sizeof(*data));
+        data = [[SDL_DisplayModeData alloc] init];
         if (!data) {
             return SDL_OutOfMemory();
         }
 
-        data->uiscreenmode = uiscreenmode;
-        [data->uiscreenmode retain];
-
-        data->scale = scale;
+        data.uiscreenmode = uiscreenmode;
     }
 
-    mode->driverdata = data;
+    mode->driverdata = (void *) CFBridgingRetain(data);
 
     return 0;
 }
@@ -54,23 +63,21 @@ static void
 UIKit_FreeDisplayModeData(SDL_DisplayMode * mode)
 {
     if (mode->driverdata != NULL) {
-        SDL_DisplayModeData *data = (SDL_DisplayModeData *)mode->driverdata;
-        [data->uiscreenmode release];
-        SDL_free(data);
+        CFRelease(mode->driverdata);
         mode->driverdata = NULL;
     }
 }
 
 static int
 UIKit_AddSingleDisplayMode(SDL_VideoDisplay * display, int w, int h,
-    UIScreenMode * uiscreenmode, CGFloat scale)
+    UIScreenMode * uiscreenmode)
 {
     SDL_DisplayMode mode;
     SDL_zero(mode);
 
     mode.format = SDL_PIXELFORMAT_ABGR8888;
     mode.refresh_rate = 0;
-    if (UIKit_AllocateDisplayModeData(&mode, uiscreenmode, scale) < 0) {
+    if (UIKit_AllocateDisplayModeData(&mode, uiscreenmode) < 0) {
         return -1;
     }
 
@@ -85,16 +92,16 @@ UIKit_AddSingleDisplayMode(SDL_VideoDisplay * display, int w, int h,
 }
 
 static int
-UIKit_AddDisplayMode(SDL_VideoDisplay * display, int w, int h, CGFloat scale,
+UIKit_AddDisplayMode(SDL_VideoDisplay * display, int w, int h,
                      UIScreenMode * uiscreenmode, SDL_bool addRotation)
 {
-    if (UIKit_AddSingleDisplayMode(display, w, h, uiscreenmode, scale) < 0) {
+    if (UIKit_AddSingleDisplayMode(display, w, h, uiscreenmode) < 0) {
         return -1;
     }
 
     if (addRotation) {
         /* Add the rotated version */
-        if (UIKit_AddSingleDisplayMode(display, h, w, uiscreenmode, scale) < 0) {
+        if (UIKit_AddSingleDisplayMode(display, h, w, uiscreenmode) < 0) {
             return -1;
         }
     }
@@ -105,7 +112,7 @@ UIKit_AddDisplayMode(SDL_VideoDisplay * display, int w, int h, CGFloat scale,
 static int
 UIKit_AddDisplay(UIScreen *uiscreen)
 {
-    CGSize size = [uiscreen bounds].size;
+    CGSize size = uiscreen.bounds.size;
 
     /* Make sure the width/height are oriented correctly */
     if (UIKit_IsDisplayLandscape(uiscreen) != (size.width > size.height)) {
@@ -114,24 +121,16 @@ UIKit_AddDisplay(UIScreen *uiscreen)
         size.height = height;
     }
 
-    /* When dealing with UIKit all coordinates are specified in terms of
-     * what Apple refers to as points. [UIScreen scale] indicates the
-     * relationship between points and pixels. Since SDL has no notion
-     * of points, we must compensate in all cases where dealing with such
-     * units.
-     */
-    CGFloat scale = [uiscreen scale];
-
     SDL_VideoDisplay display;
     SDL_DisplayMode mode;
     SDL_zero(mode);
     mode.format = SDL_PIXELFORMAT_ABGR8888;
-    mode.w = (int)(size.width * scale);
-    mode.h = (int)(size.height * scale);
+    mode.w = (int) size.width;
+    mode.h = (int) size.height;
 
-    UIScreenMode * uiscreenmode = [uiscreen currentMode];
+    UIScreenMode *uiscreenmode = uiscreen.currentMode;
 
-    if (UIKit_AllocateDisplayModeData(&mode, uiscreenmode, scale) < 0) {
+    if (UIKit_AllocateDisplayModeData(&mode, uiscreenmode) < 0) {
         return -1;
     }
 
@@ -140,17 +139,15 @@ UIKit_AddDisplay(UIScreen *uiscreen)
     display.current_mode = mode;
 
     /* Allocate the display data */
-    SDL_DisplayData *data = (SDL_DisplayData *) SDL_malloc(sizeof(*data));
+    SDL_DisplayData *data = [[SDL_DisplayData alloc] init];
     if (!data) {
         UIKit_FreeDisplayModeData(&display.desktop_mode);
         return SDL_OutOfMemory();
     }
 
-    [uiscreen retain];
-    data->uiscreen = uiscreen;
-    data->scale = scale;
+    data.uiscreen = uiscreen;
 
-    display.driverdata = data;
+    display.driverdata = (void *) CFBridgingRetain(data);
     SDL_AddVideoDisplay(&display);
 
     return 0;
@@ -160,9 +157,9 @@ SDL_bool
 UIKit_IsDisplayLandscape(UIScreen *uiscreen)
 {
     if (uiscreen == [UIScreen mainScreen]) {
-        return UIInterfaceOrientationIsLandscape([[UIApplication sharedApplication] statusBarOrientation]);
+        return UIInterfaceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation);
     } else {
-        CGSize size = [uiscreen bounds].size;
+        CGSize size = uiscreen.bounds.size;
         return (size.width > size.height);
     }
 }
@@ -170,9 +167,11 @@ UIKit_IsDisplayLandscape(UIScreen *uiscreen)
 int
 UIKit_InitModes(_THIS)
 {
-    for (UIScreen *uiscreen in [UIScreen screens]) {
-        if (UIKit_AddDisplay(uiscreen) < 0) {
-            return -1;
+    @autoreleasepool {
+        for (UIScreen *uiscreen in [UIScreen screens]) {
+            if (UIKit_AddDisplay(uiscreen) < 0) {
+                return -1;
+            }
         }
     }
 
@@ -182,34 +181,35 @@ UIKit_InitModes(_THIS)
 void
 UIKit_GetDisplayModes(_THIS, SDL_VideoDisplay * display)
 {
-    SDL_DisplayData *data = (SDL_DisplayData *) display->driverdata;
-
-    SDL_bool isLandscape = UIKit_IsDisplayLandscape(data->uiscreen);
-    SDL_bool addRotation = (data->uiscreen == [UIScreen mainScreen]);
-
-    for (UIScreenMode *uimode in [data->uiscreen availableModes]) {
-        CGSize size = [uimode size];
-        int w = (int)size.width;
-        int h = (int)size.height;
-
-        /* Make sure the width/height are oriented correctly */
-        if (isLandscape != (w > h)) {
-            int tmp = w;
-            w = h;
-            h = tmp;
+    @autoreleasepool {
+        SDL_DisplayData *data = (__bridge SDL_DisplayData *) display->driverdata;
+
+        SDL_bool isLandscape = UIKit_IsDisplayLandscape(data.uiscreen);
+        SDL_bool addRotation = (data.uiscreen == [UIScreen mainScreen]);
+        CGFloat scale = data.uiscreen.scale;
+
+#ifdef __IPHONE_8_0
+        /* The UIScreenMode of an iPhone 6 Plus should be 1080x1920 rather than
+         * 1242x2208 (414x736@3x), so we should use the native scale. */
+        if ([data.uiscreen respondsToSelector:@selector(nativeScale)]) {
+            scale = data.uiscreen.nativeScale;
         }
+#endif
+
+        for (UIScreenMode *uimode in data.uiscreen.availableModes) {
+            /* The size of a UIScreenMode is in pixels, but we deal exclusively
+             * in points (except in SDL_GL_GetDrawableSize.) */
+            int w = (int)(uimode.size.width / scale);
+            int h = (int)(uimode.size.height / scale);
+
+            /* Make sure the width/height are oriented correctly */
+            if (isLandscape != (w > h)) {
+                int tmp = w;
+                w = h;
+                h = tmp;
+            }
 
-        /* Add the native screen resolution. */
-        UIKit_AddDisplayMode(display, w, h, data->scale, uimode, addRotation);
-
-        if (data->scale != 1.0f) {
-            /* Add the native screen resolution divided by its scale.
-             * This is so devices capable of e.g. 640x960 also advertise 320x480.
-             */
-            UIKit_AddDisplayMode(display,
-                (int)(size.width / data->scale),
-                (int)(size.height / data->scale),
-                1.0f, uimode, addRotation);
+            UIKit_AddDisplayMode(display, w, h, uimode, addRotation);
         }
     }
 }
@@ -217,19 +217,24 @@ UIKit_GetDisplayModes(_THIS, SDL_VideoDisplay * display)
 int
 UIKit_SetDisplayMode(_THIS, SDL_VideoDisplay * display, SDL_DisplayMode * mode)
 {
-    SDL_DisplayData *data = (SDL_DisplayData *) display->driverdata;
-    SDL_DisplayModeData *modedata = (SDL_DisplayModeData *)mode->driverdata;
-
-    [data->uiscreen setCurrentMode:modedata->uiscreenmode];
-
-    if (data->uiscreen == [UIScreen mainScreen]) {
-        if (mode->w > mode->h) {
-            if (!UIKit_IsDisplayLandscape(data->uiscreen)) {
-                [[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeRight animated:NO];
-            }
-        } else if (mode->w < mode->h) {
-            if (UIKit_IsDisplayLandscape(data->uiscreen)) {
-                [[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationPortrait animated:NO];
+    @autoreleasepool {
+        SDL_DisplayData *data = (__bridge SDL_DisplayData *) display->driverdata;
+        SDL_DisplayModeData *modedata = (__bridge SDL_DisplayModeData *)mode->driverdata;
+
+        [data.uiscreen setCurrentMode:modedata.uiscreenmode];
+
+        if (data.uiscreen == [UIScreen mainScreen]) {
+            /* [UIApplication setStatusBarOrientation:] no longer works reliably
+             * in recent iOS versions, so we can't rotate the screen when setting
+             * the display mode. */
+            if (mode->w > mode->h) {
+                if (!UIKit_IsDisplayLandscape(data.uiscreen)) {
+                    return SDL_SetError("Screen orientation does not match display mode size");
+                }
+            } else if (mode->w < mode->h) {
+                if (UIKit_IsDisplayLandscape(data.uiscreen)) {
+                    return SDL_SetError("Screen orientation does not match display mode size");
+                }
             }
         }
     }
@@ -242,19 +247,21 @@ UIKit_QuitModes(_THIS)
 {
     /* Release Objective-C objects, so higher level doesn't free() them. */
     int i, j;
-    for (i = 0; i < _this->num_displays; i++) {
-        SDL_VideoDisplay *display = &_this->displays[i];
+    @autoreleasepool {
+        for (i = 0; i < _this->num_displays; i++) {
+            SDL_VideoDisplay *display = &_this->displays[i];
+
+            UIKit_FreeDisplayModeData(&display->desktop_mode);
+            for (j = 0; j < display->num_display_modes; j++) {
+                SDL_DisplayMode *mode = &display->display_modes[j];
+                UIKit_FreeDisplayModeData(mode);
+            }
 
-        UIKit_FreeDisplayModeData(&display->desktop_mode);
-        for (j = 0; j < display->num_display_modes; j++) {
-            SDL_DisplayMode *mode = &display->display_modes[j];
-            UIKit_FreeDisplayModeData(mode);
+            if (display->driverdata != NULL) {
+                CFRelease(display->driverdata);
+                display->driverdata = NULL;
+            }
         }
-
-        SDL_DisplayData *data = (SDL_DisplayData *) display->driverdata;
-        [data->uiscreen release];
-        SDL_free(data);
-        display->driverdata = NULL;
     }
 }
 
diff --git a/src/video/uikit/SDL_uikitopengles.h b/src/video/uikit/SDL_uikitopengles.h
index 947678c..f169189 100644
--- a/src/video/uikit/SDL_uikitopengles.h
+++ b/src/video/uikit/SDL_uikitopengles.h
@@ -25,6 +25,8 @@
 
 extern int UIKit_GL_MakeCurrent(_THIS, SDL_Window * window,
                                 SDL_GLContext context);
+extern void UIKit_GL_GetDrawableSize(_THIS, SDL_Window * window,
+                                     int * w, int * h);
 extern void UIKit_GL_SwapWindow(_THIS, SDL_Window * window);
 extern SDL_GLContext UIKit_GL_CreateContext(_THIS, SDL_Window * window);
 extern void UIKit_GL_DeleteContext(_THIS, SDL_GLContext context);
diff --git a/src/video/uikit/SDL_uikitopengles.m b/src/video/uikit/SDL_uikitopengles.m
index 8d71ee8..e9178c1 100644
--- a/src/video/uikit/SDL_uikitopengles.m
+++ b/src/video/uikit/SDL_uikitopengles.m
@@ -23,10 +23,10 @@
 #if SDL_VIDEO_DRIVER_UIKIT
 
 #include "SDL_uikitopengles.h"
-#include "SDL_uikitopenglview.h"
-#include "SDL_uikitappdelegate.h"
+#import "SDL_uikitopenglview.h"
 #include "SDL_uikitmodes.h"
 #include "SDL_uikitwindow.h"
+#include "SDL_uikitevents.h"
 #include "../SDL_sysvideo.h"
 #include "../../events/SDL_keyboard_c.h"
 #include "../../events/SDL_mouse_c.h"
@@ -40,148 +40,189 @@ void *
 UIKit_GL_GetProcAddress(_THIS, const char *proc)
 {
     /* Look through all SO's for the proc symbol.  Here's why:
-       -Looking for the path to the OpenGL Library seems not to work in the iPhone Simulator.
-       -We don't know that the path won't change in the future.
-    */
+     * -Looking for the path to the OpenGL Library seems not to work in the iOS Simulator.
+     * -We don't know that the path won't change in the future. */
     return dlsym(RTLD_DEFAULT, proc);
 }
 
 /*
-    note that SDL_GL_Delete context makes it current without passing the window
+  note that SDL_GL_DeleteContext makes it current without passing the window
 */
-int UIKit_GL_MakeCurrent(_THIS, SDL_Window * window, SDL_GLContext context)
+int
+UIKit_GL_MakeCurrent(_THIS, SDL_Window * window, SDL_GLContext context)
 {
-    [EAGLContext setCurrentContext: context];
+    @autoreleasepool {
+        SDLEAGLContext *eaglcontext = (__bridge SDLEAGLContext *) context;
+
+        if (![EAGLContext setCurrentContext:eaglcontext]) {
+            return SDL_SetError("Could not make EAGL context current");
+        }
+
+        if (eaglcontext) {
+            [eaglcontext.sdlView setSDLWindow:window];
+        }
+    }
+
     return 0;
 }
 
+void
+UIKit_GL_GetDrawableSize(_THIS, SDL_Window * window, int * w, int * h)
+{
+    @autoreleasepool {
+        SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata;
+        UIView *view = data.viewcontroller.view;
+        if ([view isKindOfClass:[SDL_uikitopenglview class]]) {
+            SDL_uikitopenglview *glview = (SDL_uikitopenglview *) view;
+            if (w) {
+                *w = glview.backingWidth;
+            }
+            if (h) {
+                *h = glview.backingHeight;
+            }
+        }
+    }
+}
+
 int
 UIKit_GL_LoadLibrary(_THIS, const char *path)
 {
-    /*
-        shouldn't be passing a path into this function
-        why?  Because we've already loaded the library
-        and because the SDK forbids loading an external SO
-    */
+    /* We shouldn't pass a path to this function, since we've already loaded the
+     * library. */
     if (path != NULL) {
-        return SDL_SetError("iPhone GL Load Library just here for compatibility");
+        return SDL_SetError("iOS GL Load Library just here for compatibility");
     }
     return 0;
 }
 
 void UIKit_GL_SwapWindow(_THIS, SDL_Window * window)
 {
+    @autoreleasepool {
+        SDLEAGLContext *context = (__bridge SDLEAGLContext *) SDL_GL_GetCurrentContext();
+
 #if SDL_POWER_UIKIT
-    /* Check once a frame to see if we should turn off the battery monitor. */
-    SDL_UIKit_UpdateBatteryMonitoring();
+        /* Check once a frame to see if we should turn off the battery monitor. */
+        SDL_UIKit_UpdateBatteryMonitoring();
 #endif
 
-    SDL_WindowData *data = (SDL_WindowData *)window->driverdata;
+        [context.sdlView swapBuffers];
 
-    if (nil == data->view) {
-        return;
+        /* You need to pump events in order for the OS to make changes visible.
+         * We don't pump events here because we don't want iOS application events
+         * (low memory, terminate, etc.) to happen inside low level rendering. */
     }
-    [data->view swapBuffers];
-
-    /* You need to pump events in order for the OS to make changes visible.
-       We don't pump events here because we don't want iOS application events
-       (low memory, terminate, etc.) to happen inside low level rendering.
-     */
 }
 
-SDL_GLContext UIKit_GL_CreateContext(_THIS, SDL_Window * window)
+SDL_GLContext
+UIKit_GL_CreateContext(_THIS, SDL_Window * window)
 {
-    SDL_uikitopenglview *view;
-    SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
-    SDL_VideoDisplay *display = SDL_GetDisplayForWindow(window);
-    SDL_DisplayData *displaydata = display->driverdata;
-    SDL_DisplayModeData *displaymodedata = display->current_mode.driverdata;
-    UIWindow *uiwindow = data->uiwindow;
-    EAGLSharegroup *share_group = nil;
-
-    if (_this->gl_config.share_with_current_context) {
-        SDL_uikitopenglview *view = (SDL_uikitopenglview *) SDL_GL_GetCurrentContext();
-        share_group = [view.context sharegroup];
-    }
+    @autoreleasepool {
+        SDL_uikitopenglview *view;
+        SDL_WindowData *data = (__bridge SDL_WindowData *) window->driverdata;
+        CGRect frame = UIKit_ComputeViewFrame(window, data.uiwindow.screen);
+        EAGLSharegroup *sharegroup = nil;
+        CGFloat scale = 1.0;
+
+        if (_this->gl_config.share_with_current_context) {
+            EAGLContext *context = (__bridge EAGLContext *) SDL_GL_GetCurrentContext();
+            sharegroup = context.sharegroup;
+        }
 
-    /* construct our view, passing in SDL's OpenGL configuration data */
-    CGRect frame;
-    if (window->flags & (SDL_WINDOW_FULLSCREEN|SDL_WINDOW_BORDERLESS)) {
-        frame = [displaydata->uiscreen bounds];
-    } else {
-        frame = [displaydata->uiscreen applicationFrame];
-    }
-    view = [[SDL_uikitopenglview alloc] initWithFrame: frame
-                                    scale: displaymodedata->scale
-                                    retainBacking: _this->gl_config.retained_backing
-                                    rBits: _this->gl_config.red_size
-                                    gBits: _this->gl_config.green_size
-                                    bBits: _this->gl_config.blue_size
-                                    aBits: _this->gl_config.alpha_size
-                                    depthBits: _this->gl_config.depth_size
-                                    stencilBits: _this->gl_config.stencil_size
-                                    majorVersion: _this->gl_config.major_version
-                                    shareGroup: share_group];
-    if (!view) {
-        return NULL;
-    }
+        if (window->flags & SDL_WINDOW_ALLOW_HIGHDPI) {
+            /* Set the scale to the natural scale factor of the screen - the
+             * backing dimensions of the OpenGL view will match the pixel
+             * dimensions of the screen rather than the dimensions in points. */
+#ifdef __IPHONE_8_0
+            if ([data.uiwindow.screen respondsToSelector:@selector(nativeScale)]) {
+                scale = data.uiwindow.screen.nativeScale;
+            } else
+#endif
+            {
+                scale = data.uiwindow.screen.scale;
+            }
+        }
 
-    data->view = view;
-    view->viewcontroller = data->viewcontroller;
-    if (view->viewcontroller != nil) {
-        [view->viewcontroller setView:view];
-        [view->viewcontroller retain];
+        /* construct our view, passing in SDL's OpenGL configuration data */
+        view = [[SDL_uikitopenglview alloc] initWithFrame:frame
+                                                    scale:scale
+                                            retainBacking:_this->gl_config.retained_backing
+                                                    rBits:_this->gl_config.red_size
+                                                    gBits:_this->gl_config.green_size
+                                                    bBits:_this->gl_config.blue_size
+                                                    aBits:_this->gl_config.alpha_size
+                                                depthBits:_this->gl_config.depth_size
+                                              stencilBits:_this->gl_config.stencil_size
+                                                     sRGB:_this->gl_config.framebuffer_srgb_capable
+                                             majorVersion:_this->gl_config.major_version
+                                               shareGroup:sharegroup];
+        if (!view) {
+            return NULL;
+        }
+
+        SDLEAGLContext *context = view.context;
+        if (UIKit_GL_MakeCurrent(_this, window, (__bridge SDL_GLContext) context) < 0) {
+            UIKit_GL_DeleteContext(_this, (SDL_GLContext) CFBridgingRetain(context));
+            return NULL;
+        }
+
+        /* We return a +1'd context. The window's driverdata owns the view (via
+         * MakeCurrent.) */
+        return (SDL_GLContext) CFBridgingRetain(context);
     }
-    [uiwindow addSubview: view];
+}
 
-    /* The view controller needs to be the root in order to control rotation on iOS 6.0 */
-    if (uiwindow.rootViewController == nil) {
-        uiwindow.rootViewController = view->viewcontroller;
+void
+UIKit_GL_DeleteContext(_THIS, SDL_GLContext context)
+{
+    @autoreleasepool {
+        /* Transfer ownership the +1'd context to ARC. */
+        SDLEAGLContext *eaglcontext = (SDLEAGLContext *) CFBridgingRelease(context);
+
+        /* Detach the context's view from its window. */
+        [eaglcontext.sdlView setSDLWindow:NULL];
     }
+}
 
-    EAGLContext *context = view.context;
-    if (UIKit_GL_MakeCurrent(_this, window, context) < 0) {
-        UIKit_GL_DeleteContext(_this, context);
-        return NULL;
+Uint32
+SDL_iPhoneGetViewRenderbuffer(SDL_Window * window)
+{
+    if (!window) {
+        SDL_SetError("Invalid window");
+        return 0;
     }
 
-    /* Make this window the current mouse focus for touch input */
-    if (displaydata->uiscreen == [UIScreen mainScreen]) {
-        SDL_SetMouseFocus(window);
-        SDL_SetKeyboardFocus(window);
+    @autoreleasepool {
+        SDL_WindowData *data = (__bridge SDL_WindowData *) window->driverdata;
+        UIView *view = data.viewcontroller.view;
+        if ([view isKindOfClass:[SDL_uikitopenglview class]]) {
+            SDL_uikitopenglview *glview = (SDL_uikitopenglview *) view;
+            return glview.drawableRenderbuffer;
+        }
     }
 
-    return context;
+    SDL_SetError("Window does not have an attached OpenGL view");
+    return 0;
 }
 
-void UIKit_GL_DeleteContext(_THIS, SDL_GLContext context)
+Uint32
+SDL_iPhoneGetViewFramebuffer(SDL_Window * window)
 {
-    SDL_Window *window;
-
-    /* Find the view associated with this context */
-    for (window = _this->windows; window; window = window->next) {
-        SDL_WindowData *data = (SDL_WindowData *) window->driverdata;
-        SDL_uikitopenglview *view = data->view;
-        if (view.context == context) {
-            /* the delegate has retained the view, this will release him */
-            if (view->viewcontroller) {
-                UIWindow *uiwindow = (UIWindow *)view.superview;
-                if (uiwindow.rootViewController == view->viewcontroller) {
-                    uiwindow.rootViewController = nil;
-                }
-                [view->viewcontroller setView:nil];
-                [view->viewcontroller release];
-            }
-            [view removeFromSuperview];
+    if (!window) {
+        SDL_SetError("Invalid window");
+        return 0;
+    }
 
-            /* FIXME: This doesn't actually call view dealloc - what is holding a reference to it? */
-            [view release];
-            return;
+    @autoreleasepool {
+        SDL_WindowData *data = (__bridge SDL_WindowData *) window->driverdata;
+        UIView *view = data.viewcontroller.view;
+        if ([view isKindOfClass:[SDL_uikitopenglview class]]) {
+            SDL_uikitopenglview *glview = (SDL_uikitopenglview *) view;
+            return glview.drawableFramebuffer;
         }
     }
 
-    /* View not found... delete the context anyway? */
-    [(EAGLContext *)context release];
+    SDL_SetError("Window does not have an attached OpenGL view");
+    return 0;
 }
 
 #endif /* SDL_VIDEO_DRIVER_UIKIT */
diff --git a/src/video/uikit/SDL_uikitopenglview.h b/src/video/uikit/SDL_uikitopenglview.h
index eed2e5b..1dcac28 100644
--- a/src/video/uikit/SDL_uikitopenglview.h
+++ b/src/video/uikit/SDL_uikitopenglview.h
@@ -21,66 +21,48 @@
 
 #import <UIKit/UIKit.h>
 #import <OpenGLES/EAGL.h>
-#import <OpenGLES/ES1/gl.h>
-#import <OpenGLES/ES1/glext.h>
+#import <OpenGLES/ES2/gl.h>
+
 #import "SDL_uikitview.h"
-/*
-    This class wraps the CAEAGLLayer from CoreAnimation into a convenient UIView subclass.
-    The view content is basically an EAGL surface you render your OpenGL scene into.
-    Note that setting the view non-opaque will only work if the EAGL surface has an alpha channel.
- */
-@interface SDL_uikitopenglview : SDL_uikitview {
+#include "SDL_uikitvideo.h"
+
+@class SDL_uikitopenglview;
 
-@private
-    /* The pixel dimensions of the backbuffer */
-    GLint backingWidth;
-    GLint backingHeight;
+@interface SDLEAGLContext : EAGLContext
 
-    EAGLContext *context;
+@property (nonatomic, weak) SDL_uikitopenglview *sdlView;
+
+@end
 
-    /* OpenGL names for the renderbuffer and framebuffers used to render to this view */
-    GLuint viewRenderbuffer, viewFramebuffer;
+@interface SDL_uikitopenglview : SDL_uikitview
 
-    /* OpenGL name for the depth buffer that is attached to viewFramebuffer, if it exists (0 if it does not exist) */
-    GLuint depthRenderbuffer;
+- (instancetype)initWithFrame:(CGRect)frame
+                        scale:(CGFloat)scale
+                retainBacking:(BOOL)retained
+                        rBits:(int)rBits
+                        gBits:(int)gBits
+                        bBits:(int)bBits
+                        aBits:(int)aBits
+                    depthBits:(int)depthBits
+                  stencilBits:(int)stencilBits
+                         sRGB:(BOOL)sRGB
+                 majorVersion:(int)majorVersion
+                   shareGroup:(EAGLSharegroup*)shareGroup;
 
-    /* format of depthRenderbuffer */
-    GLenum depthBufferFormat;
+@property (nonatomic, readonly, strong) SDLEAGLContext *context;
 
-    id displayLink;
-    int animationInterval;
-    void (*animationCallback)(void*);
-    void *animationCallbackParam;
-}
+/* The width and height of the drawable in pixels (as opposed to points.) */
+@property (nonatomic, readonly) int backingWidth;
+@property (nonatomic, readonly) int backingHeight;
 
-@property (nonatomic, retain, readonly) EAGLContext *context;
+@property (nonatomic, readonly) GLuint drawableRenderbuffer;
+@property (nonatomic, readonly) GLuint drawableFramebuffer;
 
 - (void)swapBuffers;
 - (void)setCurrentContext;
 
-- (id)initWithFrame:(CGRect)frame
-    scale:(CGFloat)scale
-    retainBacking:(BOOL)retained
-    rBits:(int)rBits
-    gBits:(int)gBits
-    bBits:(int)bBits
-    aBits:(int)aBits
-    depthBits:(int)depthBits
-    stencilBits:(int)stencilBits
-    majorVersion:(int)majorVersion
-    shareGroup:(EAGLSharegroup*)shareGroup;
-
 - (void)updateFrame;
 
-- (void)setAnimationCallback:(int)interval
-    callback:(void (*)(void*))callback
-    callbackParam:(void*)callbackParam;
-
-- (void)startAnimation;
-- (void)stopAnimation;
-
-- (void)doLoop:(CADisplayLink*)sender;
-
 @end
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/uikit/SDL_uikitopenglview.m b/src/video/uikit/SDL_uikitopenglview.m
index 144100b..df848f3 100644
--- a/src/video/uikit/SDL_uikitopenglview.m
+++ b/src/video/uikit/SDL_uikitopenglview.m
@@ -22,170 +22,190 @@
 
 #if SDL_VIDEO_DRIVER_UIKIT
 
-#include <QuartzCore/QuartzCore.h>
 #include <OpenGLES/EAGLDrawable.h>
-#include "SDL_uikitopenglview.h"
-#include "SDL_uikitmessagebox.h"
+#include <OpenGLES/ES2/glext.h>
+#import "SDL_uikitopenglview.h"
+#include "SDL_uikitwindow.h"
 
+@implementation SDLEAGLContext
 
-@implementation SDL_uikitopenglview
+@end
+
+@implementation SDL_uikitopenglview {
+    /* The renderbuffer and framebuffer used to render to this layer. */
+    GLuint viewRenderbuffer, viewFramebuffer;
+
+    /* The depth buffer that is attached to viewFramebuffer, if it exists. */
+    GLuint depthRenderbuffer;
+
+    /* format of depthRenderbuffer */
+    GLenum depthBufferFormat;
+}
 
 @synthesize context;
+@synthesize backingWidth;
+@synthesize backingHeight;
 
 + (Class)layerClass
 {
     return [CAEAGLLayer class];
 }
 
-- (id)initWithFrame:(CGRect)frame
-      scale:(CGFloat)scale
-      retainBacking:(BOOL)retained
-      rBits:(int)rBits
-      gBits:(int)gBits
-      bBits:(int)bBits
-      aBits:(int)aBits
-      depthBits:(int)depthBits
-      stencilBits:(int)stencilBits
-      majorVersion:(int)majorVersion
-      shareGroup:(EAGLSharegroup*)shareGroup
+- (instancetype)initWithFrame:(CGRect)frame
+                        scale:(CGFloat)scale
+                retainBacking:(BOOL)retained
+                        rBits:(int)rBits
+                        gBits:(int)gBits
+                        bBits:(int)bBits
+                        aBits:(int)aBits
+                    depthBits:(int)depthBits
+                  stencilBits:(int)stencilBits
+                         sRGB:(BOOL)sRGB
+                 majorVersion:(int)majorVersion
+                   shareGroup:(EAGLSharegroup*)shareGroup
 {
-    depthBufferFormat = 0;
-
     if ((self = [super initWithFrame:frame])) {
         const BOOL useStencilBuffer = (stencilBits != 0);
         const BOOL useDepthBuffer = (depthBits != 0);
         NSString *colorFormat = nil;
 
         /* The EAGLRenderingAPI enum values currently map 1:1 to major GLES
-           versions, and this allows us to handle future OpenGL ES versions.
-         */
+         * versions, and this allows us to handle future OpenGL ES versions. */
         EAGLRenderingAPI api = majorVersion;
 
-        if (rBits == 8 && gBits == 8 && bBits == 8) {
+        context = [[SDLEAGLContext alloc] initWithAPI:api sharegroup:shareGroup];
+        if (!context || ![EAGLContext setCurrentContext:context]) {
+            SDL_SetError("OpenGL ES %d not supported", majorVersion);
+            return nil;
+        }
+
+        context.sdlView = self;
+
+        if (sRGB) {
+            /* sRGB EAGL drawable support was added in iOS 7. */
+            if (UIKit_IsSystemVersionAtLeast(7.0)) {
+                colorFormat = kEAGLColorFormatSRGBA8;
+            } else {
+                SDL_SetError("sRGB drawables are not supported.");
+                return nil;
+            }
+        } else if (rBits >= 8 || gBits >= 8 || bBits >= 8) {
             /* if user specifically requests rbg888 or some color format higher than 16bpp */
             colorFormat = kEAGLColorFormatRGBA8;
         } else {
-            /* default case (faster) */
+            /* default case (potentially faster) */
             colorFormat = kEAGLColorFormatRGB565;
         }
 
-        /* Get the layer */
         CAEAGLLayer *eaglLayer = (CAEAGLLayer *)self.layer;
 
         eaglLayer.opaque = YES;
-        eaglLayer.drawableProperties = [NSDictionary dictionaryWithObjectsAndKeys:
-                                        [NSNumber numberWithBool: retained], kEAGLDrawablePropertyRetainedBacking, colorFormat, kEAGLDrawablePropertyColorFormat, nil];
-
-        context = [[EAGLContext alloc] initWithAPI:api sharegroup:shareGroup];
-        if (!context || ![EAGLContext setCurrentContext:context]) {
-            [self release];
-            SDL_SetError("OpenGL ES %d not supported", majorVersion);
-            return nil;
-        }
+        eaglLayer.drawableProperties = @{
+            kEAGLDrawablePropertyRetainedBacking:@(retained),
+            kEAGLDrawablePropertyColorFormat:colorFormat
+        };
 
         /* Set the appropriate scale (for retina display support) */
         self.contentScaleFactor = scale;
 
-        /* create the buffers */
-        glGenFramebuffersOES(1, &viewFramebuffer);
-        glGenRenderbuffersOES(1, &viewRenderbuffer);
+        /* Create the color Renderbuffer Object */
+        glGenRenderbuffers(1, &viewRenderbuffer);
+        glBindRenderbuffer(GL_RENDERBUFFER, viewRenderbuffer);
+
+        if (![context renderbufferStorage:GL_RENDERBUFFER fromDrawable:eaglLayer]) {
+            SDL_SetError("Failed to create OpenGL ES drawable");
+            return nil;
+        }
 
-        glBindFramebufferOES(GL_FRAMEBUFFER_OES, viewFramebuffer);
-        glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer);
-        [context renderbufferStorage:GL_RENDERBUFFER_OES fromDrawable:(CAEAGLLayer*)self.layer];
-        glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, viewRenderbuffer);
+        /* Create the Framebuffer Object */
+        glGenFramebuffers(1, &viewFramebuffer);
+        glBindFramebuffer(GL_FRAMEBUFFER, viewFramebuffer);
 
-        glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &backingWidth);
-        glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &backingHeight);
+        /* attach the color renderbuffer to the FBO */
+        glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, viewRenderbuffer);
+
+        glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &backingWidth);
+        glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &backingHeight);
 
         if ((useDepthBuffer) || (useStencilBuffer)) {
             if (useStencilBuffer) {
                 /* Apparently you need to pack stencil and depth into one buffer. */
                 depthBufferFormat = GL_DEPTH24_STENCIL8_OES;
             } else if (useDepthBuffer) {
-                /* iOS only has 24-bit depth buffers, even with GL_DEPTH_COMPONENT16_OES */
+                /* iOS only uses 32-bit float (exposed as fixed point 24-bit)
+                 * depth buffers. */
                 depthBufferFormat = GL_DEPTH_COMPONENT24_OES;
             }
 
-            glGenRenderbuffersOES(1, &depthRenderbuffer);
-            glBindRenderbufferOES(GL_RENDERBUFFER_OES, depthRenderbuffer);
-            glRenderbufferStorageOES(GL_RENDERBUFFER_OES, depthBufferFormat, backingWidth, backingHeight);
+            glGenRenderbuffers(1, &depthRenderbuffer);
+            glBindRenderbuffer(GL_RENDERBUFFER, depthRenderbuffer);
+            glRenderbufferStorage(GL_RENDERBUFFER, depthBufferFormat, backingWidth, backingHeight);
             if (useDepthBuffer) {
-                glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthRenderbuffer);
+                glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthRenderbuffer);
             }
             if (useStencilBuffer) {
-                glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_STENCIL_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthRenderbuffer);
+                glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, depthRenderbuffer);
             }
         }
 
-        if (glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES) != GL_FRAMEBUFFER_COMPLETE_OES) {
-            return NO;
+        if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
+            SDL_SetError("Failed creating OpenGL ES framebuffer");
+            return nil;
         }
 
-        glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer);
-        /* end create buffers */
+        glBindRenderbuffer(GL_RENDERBUFFER, viewRenderbuffer);
 
-        self.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
-        self.autoresizesSubviews = YES;
+        [self setDebugLabels];
     }
+
     return self;
 }
 
+- (GLuint)drawableRenderbuffer
+{
+    return viewRenderbuffer;
+}
+
+- (GLuint)drawableFramebuffer
+{
+    return viewFramebuffer;
+}
+
 - (void)updateFrame
 {
-    glBindFramebufferOES(GL_FRAMEBUFFER_OES, viewFramebuffer);
-    glBindRenderbufferOES(GL_RENDERBUFFER_OES, 0);
-    glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, 0);
-    glDeleteRenderbuffersOES(1, &viewRenderbuffer);
+    GLint prevRenderbuffer = 0;
+    glGetIntegerv(GL_RENDERBUFFER_BINDING, &prevRenderbuffer);
 
-    glGenRenderbuffersOES(1, &viewRenderbuffer);
-    glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer);
-    [context renderbufferStorage:GL_RENDERBUFFER_OES fromDrawable:(CAEAGLLayer*)self.layer];
-    glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, viewRenderbuffer);
+    glBindRenderbuffer(GL_RENDERBUFFER, viewRenderbuffer);
+    [context renderbufferStorage:GL_RENDERBUFFER fromDrawable:(CAEAGLLayer *)self.layer];
 
-    glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &backingWidth);
-    glGetRenderbufferParameterivOES(GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &backingHeight);
+    glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &backingWidth);
+    glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &backingHeight);
 
     if (depthRenderbuffer != 0) {
-        glBindRenderbufferOES(GL_RENDERBUFFER_OES, depthRenderbuffer);
-        glRenderbufferStorageOES(GL_RENDERBUFFER_OES, depthBufferFormat, backingWidth, backingHeight);
+        glBindRenderbuffer(GL_RENDERBUFFER, depthRenderbuffer);
+        glRenderbufferStorage(GL_RENDERBUFFER, depthBufferFormat, backingWidth, backingHeight);
     }
 
-    glBindRenderbufferOES(GL_RENDERBUFFER_OES, viewRenderbuffer);
+    glBindRenderbuffer(GL_RENDERBUFFER, prevRenderbuffer);
 }
 
-- (void)setAnimationCallback:(int)interval
-    callback:(void (*)(void*))callback
-    callbackParam:(void*)callbackParam
+- (void)setDebugLabels
 {
-    [self stopAnimation];
-
-    animationInterval = interval;
-    animationCallback = callback;
-    animationCallbackParam = callbackParam;
-
-    if (animationCallback)
-        [self startAnimation];
-}
-
-- (void)startAnimation
-{
-    displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(doLoop:)];
-    [displayLink setFrameInterval:animationInterval];
-    [displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
-}
+    if (viewFramebuffer != 0) {
+        glLabelObjectEXT(GL_FRAMEBUFFER, viewFramebuffer, 0, "context FBO");
+    }
 
-- (void)stopAnimation
-{
-    [displayLink invalidate];
-    displayLink = nil;
-}
+    if (viewRenderbuffer != 0) {
+        glLabelObjectEXT(GL_RENDERBUFFER, viewRenderbuffer, 0, "context color buffer");
+    }
 
-- (void)doLoop:(CADisplayLink*)sender
-{
-    /* Don't run the game loop while a messagebox is up */
-    if (!UIKit_ShowingMessageBox()) {
-        animationCallback(animationCallbackParam);
+    if (depthRenderbuffer != 0) {
+        if (depthBufferFormat == GL_DEPTH24_STENCIL8_OES) {
+            glLabelObjectEXT(GL_RENDERBUFFER, depthRenderbuffer, 0, "context depth-stencil buffer");
+        } else {
+            glLabelObjectEXT(GL_RENDERBUFFER, depthRenderbuffer, 0, "context depth buffer");
+        }
     }
 }
 
@@ -194,44 +214,60 @@
     [EAGLContext setCurrentContext:context];
 }
 
-
 - (void)swapBuffers
 {
     /* viewRenderbuffer should always be bound here. Code that binds something
-        else is responsible for rebinding viewRenderbuffer, to reduce
-        duplicate state changes. */
-    [context presentRenderbuffer:GL_RENDERBUFFER_OES];
+     * else is responsible for rebinding viewRenderbuffer, to reduce duplicate
+     * state changes. */
+    [context presentRenderbuffer:GL_RENDERBUFFER];
 }
 
-
 - (void)layoutSubviews
 {
-    [EAGLContext setCurrentContext:context];
-    [self updateFrame];
+    [super layoutSubviews];
+
+    int width  = (int) (self.bounds.size.width * self.contentScaleFactor);
+    int height = (int) (self.bounds.size.height * self.contentScaleFactor);
+
+    /* Update the color and depth buffer storage if the layer size has changed. */
+    if (width != backingWidth || height != backingHeight) {
+        EAGLContext *prevContext = [EAGLContext currentContext];
+        if (prevContext != context) {
+            [EAGLContext setCurrentContext:context];
+        }
+
+        [self updateFrame];
+
+        if (prevContext != context) {
+            [EAGLContext setCurrentContext:prevContext];
+        }
+    }
 }
 
 - (void)destroyFramebuffer
 {
-    glDeleteFramebuffersOES(1, &viewFramebuffer);
-    viewFramebuffer = 0;
-    glDeleteRenderbuffersOES(1, &viewRenderbuffer);
-    viewRenderbuffer = 0;
+    if (viewFramebuffer != 0) {
+        glDeleteFramebuffers(1, &viewFramebuffer);
+        viewFramebuffer = 0;
+    }
 
-    if (depthRenderbuffer) {
-        glDeleteRenderbuffersOES(1, &depthRenderbuffer);
+    if (viewRenderbuffer != 0) {
+        glDeleteRenderbuffers(1, &viewRenderbuffer);
+        viewRenderbuffer = 0;
+    }
+
+    if (depthRenderbuffer != 0) {
+        glDeleteRenderbuffers(1, &depthRenderbuffer);
         depthRenderbuffer = 0;
     }
 }
 
-
 - (void)dealloc
 {
-    [self destroyFramebuffer];
     if ([EAGLContext currentContext] == context) {
+        [self destroyFramebuffer];
         [EAGLContext setCurrentContext:nil];
     }
-    [context release];
-    [super dealloc];
 }
 
 @end
diff --git a/src/video/uikit/SDL_uikitvideo.h b/src/video/uikit/SDL_uikitvideo.h
index ef62982..dac80a2 100644
--- a/src/video/uikit/SDL_uikitvideo.h
+++ b/src/video/uikit/SDL_uikitvideo.h
@@ -25,20 +25,8 @@
 
 #include "../SDL_sysvideo.h"
 
-#ifndef __IPHONE_6_0
-/* This enum isn't available in older SDKs, but we use it for our own purposes on iOS 5.1 and for the system on iOS 6.0 */
-enum UIInterfaceOrientationMask
-{
-    UIInterfaceOrientationMaskPortrait = (1 << UIInterfaceOrientationPortrait),
-    UIInterfaceOrientationMaskLandscapeLeft = (1 << UIInterfaceOrientationLandscapeLeft),
-    UIInterfaceOrientationMaskLandscapeRight = (1 << UIInterfaceOrientationLandscapeRight),
-    UIInterfaceOrientationMaskPortraitUpsideDown = (1 << UIInterfaceOrientationPortraitUpsideDown),
-    UIInterfaceOrientationMaskLandscape = (UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight),
-    UIInterfaceOrientationMaskAll = (UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight | UIInterfaceOrientationMaskPortraitUpsideDown),
-    UIInterfaceOrientationMaskAllButUpsideDown = (UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskLandscapeLeft | UIInterfaceOrientationMaskLandscapeRight),
-};
-#endif /* !__IPHONE_6_0 */
-
+BOOL UIKit_IsSystemVersionAtLeast(double version);
+CGRect UIKit_ComputeViewFrame(SDL_Window *window, UIScreen *screen);
 
 #endif /* _SDL_uikitvideo_h */
 
diff --git a/src/video/uikit/SDL_uikitvideo.m b/src/video/uikit/SDL_uikitvideo.m
index 4893bc1..c3448ef 100644
--- a/src/video/uikit/SDL_uikitvideo.m
+++ b/src/video/uikit/SDL_uikitvideo.m
@@ -75,15 +75,15 @@ UIKit_CreateDevice(int devindex)
     device->SetDisplayMode = UIKit_SetDisplayMode;
     device->PumpEvents = UIKit_PumpEvents;
     device->CreateWindow = UIKit_CreateWindow;
+    device->SetWindowTitle = UIKit_SetWindowTitle;
     device->ShowWindow = UIKit_ShowWindow;
     device->HideWindow = UIKit_HideWindow;
     device->RaiseWindow = UIKit_RaiseWindow;
+    device->SetWindowBordered = UIKit_SetWindowBordered;
     device->SetWindowFullscreen = UIKit_SetWindowFullscreen;
     device->DestroyWindow = UIKit_DestroyWindow;
     device->GetWindowWMInfo = UIKit_GetWindowWMInfo;
 
-    /* !!! FIXME: implement SetWindowBordered */
-
 #if SDL_IPHONE_KEYBOARD
     device->HasScreenKeyboardSupport = UIKit_HasScreenKeyboardSupport;
     device->ShowScreenKeyboard = UIKit_ShowScreenKeyboard;
@@ -93,12 +93,13 @@ UIKit_CreateDevice(int devindex)
 #endif
 
     /* OpenGL (ES) functions */
-    device->GL_MakeCurrent        = UIKit_GL_MakeCurrent;
-    device->GL_SwapWindow        = UIKit_GL_SwapWindow;
+    device->GL_MakeCurrent      = UIKit_GL_MakeCurrent;
+    device->GL_GetDrawableSize  = UIKit_GL_GetDrawableSize;
+    device->GL_SwapWindow       = UIKit_GL_SwapWindow;
     device->GL_CreateContext    = UIKit_GL_CreateContext;
     device->GL_DeleteContext    = UIKit_GL_DeleteContext;
     device->GL_GetProcAddress   = UIKit_GL_GetProcAddress;
-    device->GL_LoadLibrary        = UIKit_GL_LoadLibrary;
+    device->GL_LoadLibrary      = UIKit_GL_LoadLibrary;
     device->free = UIKit_DeleteDevice;
 
     device->gl_config.accelerated = 1;
@@ -129,6 +130,25 @@ UIKit_VideoQuit(_THIS)
     UIKit_QuitModes(_this);
 }
 
+BOOL
+UIKit_IsSystemVersionAtLeast(double version)
+{
+    return [[UIDevice currentDevice].systemVersion doubleValue] >= version;
+}
+
+CGRect
+UIKit_ComputeViewFrame(SDL_Window *window, UIScreen *screen)
+{
+    BOOL hasiOS7 = UIKit_IsSystemVersionAtLeast(7.0);
+
+    if (hasiOS7 || (window->flags & (SDL_WINDOW_BORDERLESS|SDL_WINDOW_FULLSCREEN))) {
+        /* The view should always show behind the status bar in iOS 7+. */
+        return screen.bounds;
+    } else {
+        return screen.applicationFrame;
+    }
+}
+
 /*
  * iOS log support.
  *
diff --git a/src/video/uikit/SDL_uikitview.h b/src/video/uikit/SDL_uikitview.h
index ce616c0..dda94b3 100644
--- a/src/video/uikit/SDL_uikitview.h
+++ b/src/video/uikit/SDL_uikitview.h
@@ -20,59 +20,22 @@
 */
 
 #import <UIKit/UIKit.h>
-#import "SDL_uikitviewcontroller.h"
 
-#include "SDL_touch.h"
-
-#define IPHONE_TOUCH_EFFICIENT_DANGEROUS
+#include "../SDL_sysvideo.h"
 
-#ifndef IPHONE_TOUCH_EFFICIENT_DANGEROUS
-#define MAX_SIMULTANEOUS_TOUCHES 5
-#endif
+#include "SDL_touch.h"
 
-#if SDL_IPHONE_KEYBOARD
-@interface SDL_uikitview : UIView<UITextFieldDelegate> {
-#else
-@interface SDL_uikitview : UIView {
-#endif
+@interface SDL_uikitview : UIView
 
-    SDL_TouchID touchId;
-    UITouch *leftFingerDown;
-#ifndef IPHONE_TOUCH_EFFICIENT_DANGEROUS
-    UITouch *finger[MAX_SIMULTANEOUS_TOUCHES];
-#endif
+- (instancetype)initWithFrame:(CGRect)frame;
 
-#if SDL_IPHONE_KEYBOARD
-    UITextField *textField;
-    BOOL keyboardVisible;
-    SDL_Rect textInputRect;
-    int keyboardHeight;
-#endif
+- (void)setSDLWindow:(SDL_Window *)window;
 
-@public
-    SDL_uikitviewcontroller *viewcontroller;
-}
 - (CGPoint)touchLocation:(UITouch *)touch shouldNormalize:(BOOL)normalize;
 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event;
 - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event;
 - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event;
 
-#if SDL_IPHONE_KEYBOARD
-- (void)showKeyboard;
-- (void)hideKeyboard;
-- (void)initializeKeyboard;
-@property (readonly) BOOL keyboardVisible;
-@property (nonatomic,assign) SDL_Rect textInputRect;
-@property (nonatomic,assign) int keyboardHeight;
-
-SDL_bool UIKit_HasScreenKeyboardSupport(_THIS);
-void UIKit_ShowScreenKeyboard(_THIS, SDL_Window *window);
-void UIKit_HideScreenKeyboard(_THIS, SDL_Window *window);
-SDL_bool UIKit_IsScreenKeyboardShown(_THIS, SDL_Window *window);
-void UIKit_SetTextInputRect(_THIS, SDL_Rect *rect);
-
-#endif
-
 @end
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/uikit/SDL_uikitview.m b/src/video/uikit/SDL_uikitview.m
index c51a3ba..8bd1f31 100644
--- a/src/video/uikit/SDL_uikitview.m
+++ b/src/video/uikit/SDL_uikitview.m
@@ -24,438 +24,167 @@
 
 #include "SDL_uikitview.h"
 
-#include "../../events/SDL_keyboard_c.h"
 #include "../../events/SDL_mouse_c.h"
 #include "../../events/SDL_touch_c.h"
+#include "../../events/SDL_events_c.h"
 
-#if SDL_IPHONE_KEYBOARD
-#include "keyinfotable.h"
-#endif
-#include "SDL_uikitappdelegate.h"
-#include "SDL_uikitmodes.h"
-#include "SDL_uikitwindow.h"
+#import "SDL_uikitappdelegate.h"
+#import "SDL_uikitmodes.h"
+#import "SDL_uikitwindow.h"
 
-void _uikit_keyboard_init() ;
+@implementation SDL_uikitview {
+    SDL_Window *sdlwindow;
 
-@implementation SDL_uikitview
+    SDL_TouchID touchId;
+    UITouch * __weak firstFingerDown;
+}
 
-- (void)dealloc
+- (instancetype)initWithFrame:(CGRect)frame
 {
-    [super dealloc];
+    if ((self = [super initWithFrame:frame])) {
+        self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
+        self.autoresizesSubviews = YES;
+
+        self.multipleTouchEnabled = YES;
+
+        touchId = 1;
+        SDL_AddTouch(touchId, "");
+    }
+
+    return self;
 }
 
-- (id)initWithFrame:(CGRect)frame
+- (void)setSDLWindow:(SDL_Window *)window
 {
-    self = [super initWithFrame: frame];
+    SDL_WindowData *data = nil;
+
+    if (window == sdlwindow) {
+        return;
+    }
 
-#if SDL_IPHONE_KEYBOARD
-    [self initializeKeyboard];
-#endif
+    if (sdlwindow) {
+        SDL_uikitview *view = nil;
+        data = (__bridge SDL_WindowData *) sdlwindow->driverdata;
 
-    self.multipleTouchEnabled = YES;
+        [data.views removeObject:self];
 
-    touchId = 1;
-    SDL_AddTouch(touchId, "");
+        [self removeFromSuperview];
 
-    return self;
+        /* Restore the next-oldest view in the old window. */
+        if (data.views.count > 0) {
+            view = data.views[data.views.count - 1];
+        }
+
+        data.viewcontroller.view = view;
+
+        if (data.uiwindow.rootViewController != data.viewcontroller) {
+            data.uiwindow.rootViewController = data.viewcontroller;
+        } else if (view) {
+            [data.uiwindow addSubview:view];
+        }
 
+        [data.uiwindow layoutIfNeeded];
+    }
+
+    if (window) {
+        data = (__bridge SDL_WindowData *) window->driverdata;
+
+        /* Make sure the SDL window has a strong reference to this view. */
+        [data.views addObject:self];
+
+        /* Replace the view controller's old view with this one. */
+        [data.viewcontroller.view removeFromSuperview];
+        data.viewcontroller.view = self;
+
+        if (data.uiwindow.rootViewController != data.viewcontroller) {
+            /* The root view controller handles rotation and the status bar.
+             * Assigning it also adds the controller's view to the window. */
+            data.uiwindow.rootViewController = data.viewcontroller;
+        } else {
+            [data.uiwindow addSubview:self];
+        }
+
+        /* The view's bounds may not be correct until the next event cycle. That
+         * might happen after the current dimensions are queried, so we force a
+         * layout now to immediately update the bounds. */
+        [data.uiwindow layoutIfNeeded];
+    }
+
+    sdlwindow = window;
 }
 
 - (CGPoint)touchLocation:(UITouch *)touch shouldNormalize:(BOOL)normalize
 {
-    CGPoint point = [touch locationInView: self];
-
-    /* Get the display scale and apply that to the input coordinates */
-    SDL_Window *window = self->viewcontroller.window;
-    SDL_VideoDisplay *display = SDL_GetDisplayForWindow(window);
-    SDL_DisplayModeData *displaymodedata = (SDL_DisplayModeData *) display->current_mode.driverdata;
+    CGPoint point = [touch locationInView:self];
 
     if (normalize) {
-        CGRect bounds = [self bounds];
+        CGRect bounds = self.bounds;
         point.x /= bounds.size.width;
         point.y /= bounds.size.height;
-    } else {
-        point.x *= displaymodedata->scale;
-        point.y *= displaymodedata->scale;
     }
+
     return point;
 }
 
 - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
 {
-    NSEnumerator *enumerator = [touches objectEnumerator];
-    UITouch *touch = (UITouch*)[enumerator nextObject];
-
-    while (touch) {
-        if (!leftFingerDown) {
+    for (UITouch *touch in touches) {
+        if (!firstFingerDown) {
             CGPoint locationInView = [self touchLocation:touch shouldNormalize:NO];
 
-            /* send moved event */
-            SDL_SendMouseMotion(self->viewcontroller.window, SDL_TOUCH_MOUSEID, 0, locationInView.x, locationInView.y);
+            /* send mouse moved event */
+            SDL_SendMouseMotion(sdlwindow, SDL_TOUCH_MOUSEID, 0, locationInView.x, locationInView.y);
 
             /* send mouse down event */
-            SDL_SendMouseButton(self->viewcontroller.window, SDL_TOUCH_MOUSEID, SDL_PRESSED, SDL_BUTTON_LEFT);
+            SDL_SendMouseButton(sdlwindow, SDL_TOUCH_MOUSEID, SDL_PRESSED, SDL_BUTTON_LEFT);
 
-            leftFingerDown = touch;
+            firstFingerDown = touch;
         }
 
         CGPoint locationInView = [self touchLocation:touch shouldNormalize:YES];
-#ifdef IPHONE_TOUCH_EFFICIENT_DANGEROUS
-        /* FIXME: TODO: Using touch as the fingerId is potentially dangerous
-         * It is also much more efficient than storing the UITouch pointer
-         * and comparing it to the incoming event.
-         */
         SDL_SendTouch(touchId, (SDL_FingerID)((size_t)touch),
                       SDL_TRUE, locationInView.x, locationInView.y, 1.0f);
-#else
-        int i;
-        for(i = 0; i < MAX_SIMULTANEOUS_TOUCHES; i++) {
-            if (finger[i] == NULL) {
-                finger[i] = touch;
-                SDL_SendTouch(touchId, i,
-                              SDL_TRUE, locationInView.x, locationInView.y, 1.0f);
-                break;
-            }
-        }
-#endif
-        touch = (UITouch*)[enumerator nextObject];
     }
 }
 
 - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
 {
-    NSEnumerator *enumerator = [touches objectEnumerator];
-    UITouch *touch = (UITouch*)[enumerator nextObject];
-
-    while(touch) {
-        if (touch == leftFingerDown) {
+    for (UITouch *touch in touches) {
+        if (touch == firstFingerDown) {
             /* send mouse up */
-            SDL_SendMouseButton(self->viewcontroller.window, SDL_TOUCH_MOUSEID, SDL_RELEASED, SDL_BUTTON_LEFT);
-            leftFingerDown = nil;
+            SDL_SendMouseButton(sdlwindow, SDL_TOUCH_MOUSEID, SDL_RELEASED, SDL_BUTTON_LEFT);
+            firstFingerDown = nil;
         }
 
         CGPoint locationInView = [self touchLocation:touch shouldNormalize:YES];
-#ifdef IPHONE_TOUCH_EFFICIENT_DANGEROUS
-        SDL_SendTouch(touchId, (long)touch,
+        SDL_SendTouch(touchId, (SDL_FingerID)((size_t)touch),
                       SDL_FALSE, locationInView.x, locationInView.y, 1.0f);
-#else
-        int i;
-        for (i = 0; i < MAX_SIMULTANEOUS_TOUCHES; i++) {
-            if (finger[i] == touch) {
-                SDL_SendTouch(touchId, i,
-                              SDL_FALSE, locationInView.x, locationInView.y, 1.0f);
-                finger[i] = NULL;
-                break;
-            }
-        }
-#endif
-        touch = (UITouch*)[enumerator nextObject];
     }
 }
 
 - (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
 {
-    /*
-        this can happen if the user puts more than 5 touches on the screen
-        at once, or perhaps in other circumstances.  Usually (it seems)
-        all active touches are canceled.
-    */
-    [self touchesEnded: touches withEvent: event];
+    [self touchesEnded:touches withEvent:event];
 }
 
 - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
 {
-    NSEnumerator *enumerator = [touches objectEnumerator];
-    UITouch *touch = (UITouch*)[enumerator nextObject];
-
-    while (touch) {
-        if (touch == leftFingerDown) {
+    for (UITouch *touch in touches) {
+        if (touch == firstFingerDown) {
             CGPoint locationInView = [self touchLocation:touch shouldNormalize:NO];
 
             /* send moved event */
-            SDL_SendMouseMotion(self->viewcontroller.window, SDL_TOUCH_MOUSEID, 0, locationInView.x, locationInView.y);
+            SDL_SendMouseMotion(sdlwindow, SDL_TOUCH_MOUSEID, 0, locationInView.x, locationInView.y);
         }
 
         CGPoint locationInView = [self touchLocation:touch shouldNormalize:YES];
-#ifdef IPHONE_TOUCH_EFFICIENT_DANGEROUS
-        SDL_SendTouchMotion(touchId, (long)touch,
+        SDL_SendTouchMotion(touchId, (SDL_FingerID)((size_t)touch),
                             locationInView.x, locationInView.y, 1.0f);
-#else
-        int i;
-        for (i = 0; i < MAX_SIMULTANEOUS_TOUCHES; i++) {
-            if (finger[i] == touch) {
-                SDL_SendTouchMotion(touchId, i,
-                                    locationInView.x, locationInView.y, 1.0f);
-                break;
-            }
-        }
-#endif
-        touch = (UITouch*)[enumerator nextObject];
-    }
-}
-
-/*
-    ---- Keyboard related functionality below this line ----
-*/
-#if SDL_IPHONE_KEYBOARD
-
-@synthesize textInputRect = textInputRect;
-@synthesize keyboardHeight = keyboardHeight;
-
-/* Is the iPhone virtual keyboard visible onscreen? */
-- (BOOL)keyboardVisible
-{
-    return keyboardVisible;
-}
-
-/* Set ourselves up as a UITextFieldDelegate */
-- (void)initializeKeyboard
-{
-    textField = [[UITextField alloc] initWithFrame: CGRectZero];
-    textField.delegate = self;
-    /* placeholder so there is something to delete! */
-    textField.text = @" ";
-
-    /* set UITextInputTrait properties, mostly to defaults */
-    textField.autocapitalizationType = UITextAutocapitalizationTypeNone;
-    textField.autocorrectionType = UITextAutocorrectionTypeNo;
-    textField.enablesReturnKeyAutomatically = NO;
-    textField.keyboardAppearance = UIKeyboardAppearanceDefault;
-    textField.keyboardType = UIKeyboardTypeDefault;
-    textField.returnKeyType = UIReturnKeyDefault;
-    textField.secureTextEntry = NO;
-
-    textField.hidden = YES;
-    keyboardVisible = NO;
-    /* add the UITextField (hidden) to our view */
-    [self addSubview: textField];
-    [textField release];
-    
-    _uikit_keyboard_init();
-}
-
-/* reveal onscreen virtual keyboard */
-- (void)showKeyboard
-{
-    keyboardVisible = YES;
-    [textField becomeFirstResponder];
-}
-
-/* hide onscreen virtual keyboard */
-- (void)hideKeyboard
-{
-    keyboardVisible = NO;
-    [textField resignFirstResponder];
-}
-
-/* UITextFieldDelegate method.  Invoked when user types something. */
-- (BOOL)textField:(UITextField *)_textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
-{
-    if ([string length] == 0) {
-        /* it wants to replace text with nothing, ie a delete */
-        SDL_SendKeyboardKey(SDL_PRESSED, SDL_SCANCODE_BACKSPACE);
-        SDL_SendKeyboardKey(SDL_RELEASED, SDL_SCANCODE_BACKSPACE);
-    }
-    else {
-        /* go through all the characters in the string we've been sent
-           and convert them to key presses */
-        int i;
-        for (i = 0; i < [string length]; i++) {
-
-            unichar c = [string characterAtIndex: i];
-
-            Uint16 mod = 0;
-            SDL_Scancode code;
-
-            if (c < 127) {
-                /* figure out the SDL_Scancode and SDL_keymod for this unichar */
-                code = unicharToUIKeyInfoTable[c].code;
-                mod  = unicharToUIKeyInfoTable[c].mod;
-            }
-            else {
-                /* we only deal with ASCII right now */
-                code = SDL_SCANCODE_UNKNOWN;
-                mod = 0;
-            }
-
-            if (mod & KMOD_SHIFT) {
-                /* If character uses shift, press shift down */
-                SDL_SendKeyboardKey(SDL_PRESSED, SDL_SCANCODE_LSHIFT);
-            }
-            /* send a keydown and keyup even for the character */
-            SDL_SendKeyboardKey(SDL_PRESSED, code);
-            SDL_SendKeyboardKey(SDL_RELEASED, code);
-            if (mod & KMOD_SHIFT) {
-                /* If character uses shift, press shift back up */
-                SDL_SendKeyboardKey(SDL_RELEASED, SDL_SCANCODE_LSHIFT);
-            }
-        }
-        SDL_SendKeyboardText([string UTF8String]);
     }
-    return NO; /* don't allow the edit! (keep placeholder text there) */
 }
 
-/* Terminates the editing session */
-- (BOOL)textFieldShouldReturn:(UITextField*)_textField
-{
-    SDL_SendKeyboardKey(SDL_PRESSED, SDL_SCANCODE_RETURN);
-    SDL_SendKeyboardKey(SDL_RELEASED, SDL_SCANCODE_RETURN);
-    SDL_StopTextInput();
-    return YES;
-}
-
-#endif
-
 @end
 
-/* iPhone keyboard addition functions */
-#if SDL_IPHONE_KEYBOARD
-
-static SDL_uikitview * getWindowView(SDL_Window * window)
-{
-    if (window == NULL) {
-        SDL_SetError("Window does not exist");
-        return nil;
-    }
-
-    SDL_WindowData *data = (SDL_WindowData *)window->driverdata;
-    SDL_uikitview *view = data != NULL ? data->view : nil;
-
-    if (view == nil) {
-        SDL_SetError("Window has no view");
-    }
-
-    return view;
-}
-
-SDL_bool UIKit_HasScreenKeyboardSupport(_THIS)
-{
-    return SDL_TRUE;
-}
-
-void UIKit_ShowScreenKeyboard(_THIS, SDL_Window *window)
-{
-    SDL_uikitview *view = getWindowView(window);
-    if (view != nil) {
-        [view showKeyboard];
-    }
-}
-
-void UIKit_HideScreenKeyboard(_THIS, SDL_Window *window)
-{
-    SDL_uikitview *view = getWindowView(window);
-    if (view != nil) {
-        [view hideKeyboard];
-    }
-}
-
-SDL_bool UIKit_IsScreenKeyboardShown(_THIS, SDL_Window *window)
-{
-    SDL_uikitview *view = getWindowView(window);
-    if (view == nil) {
-        return 0;
-    }
-
-    return view.keyboardVisible;
-}
-
-
-void _uikit_keyboard_update() {
-    SDL_Window *window = SDL_GetFocusWindow();
-    if (!window) { return; }
-    SDL_WindowData *data = (SDL_WindowData *)window->driverdata;
-    if (!data) { return; }
-    SDL_uikitview *view = data->view;
-    if (!view) { return; }
-    
-    SDL_Rect r = view.textInputRect;
-    int height = view.keyboardHeight;
-    int offsetx = 0;
-    int offsety = 0;
-    float scale = [UIScreen mainScreen].scale;
-    if (height) {
-        int sw,sh;
-        SDL_GetWindowSize(window,&sw,&sh);
-        int bottom = (r.y + r.h);
-        int kbottom = sh - height;
-        if (kbottom < bottom) {
-            offsety = kbottom-bottom;
-        }
-    }
-    UIInterfaceOrientation ui_orient = [[UIApplication sharedApplication] statusBarOrientation];
-    if (ui_orient == UIInterfaceOrientationLandscapeLeft) {
-        int tmp = offsetx; offsetx = offsety; offsety = tmp;
-    }
-    if (ui_orient == UIInterfaceOrientationLandscapeRight) {
-        offsety = -offsety;
-        int tmp = offsetx; offsetx = offsety; offsety = tmp;
-    }
-    if (ui_orient == UIInterfaceOrientationPortraitUpsideDown) {
-        offsety = -offsety;
-    }
-
-    offsetx /= scale;
-    offsety /= scale;
-
-    view.frame = CGRectMake(offsetx,offsety,view.frame.size.width,view.frame.size.height);
-}
-
-void _uikit_keyboard_set_height(int height) {
-    SDL_uikitview *view = getWindowView(SDL_GetFocusWindow());
-    if (view == nil) {
-        return ;
-    }
-    
-    view.keyboardHeight = height;
-    _uikit_keyboard_update();
-}
-
-void _uikit_keyboard_init() {
-    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
-    NSOperationQueue *queue = [NSOperationQueue mainQueue];
-    [center addObserverForName:UIKeyboardWillShowNotification
-                        object:nil
-                         queue:queue
-                    usingBlock:^(NSNotification *notification) {
-                        int height = 0;
-                        CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
-                        height = keyboardSize.height;
-                        UIInterfaceOrientation ui_orient = [[UIApplication sharedApplication] statusBarOrientation];
-                        if (ui_orient == UIInterfaceOrientationLandscapeRight || ui_orient == UIInterfaceOrientationLandscapeLeft) {
-                            height = keyboardSize.width;
-                        }
-                        height *= [UIScreen mainScreen].scale;
-                        _uikit_keyboard_set_height(height);
-                    }
-     ];
-    [center addObserverForName:UIKeyboardDidHideNotification
-                        object:nil
-                         queue:queue
-                    usingBlock:^(NSNotification *notification) {
-                        _uikit_keyboard_set_height(0);
-                    }
-     ];
-}
-
-void
-UIKit_SetTextInputRect(_THIS, SDL_Rect *rect)
-{
-    if (!rect) {
-        SDL_InvalidParamError("rect");
-        return;
-    }
-    
-    SDL_uikitview *view = getWindowView(SDL_GetFocusWindow());
-    if (view == nil) {
-        return ;
-    }
-
-    view.textInputRect = *rect;
-}
-
-
-#endif /* SDL_IPHONE_KEYBOARD */
-
 #endif /* SDL_VIDEO_DRIVER_UIKIT */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/src/video/uikit/SDL_uikitviewcontroller.h b/src/video/uikit/SDL_uikitviewcontroller.h
index e8d595d..b8cf3dc 100644
--- a/src/video/uikit/SDL_uikitviewcontroller.h
+++ b/src/video/uikit/SDL_uikitviewcontroller.h
@@ -23,18 +23,56 @@
 
 #include "../SDL_sysvideo.h"
 
-@interface SDL_uikitviewcontroller : UIViewController {
-@private
-    SDL_Window *window;
-}
+#include "SDL_touch.h"
 
-@property (readwrite) SDL_Window *window;
+#if SDL_IPHONE_KEYBOARD
+@interface SDL_uikitviewcontroller : UIViewController <UITextFieldDelegate>
+#else
+@interface SDL_uikitviewcontroller : UIViewController
+#endif
+
+@property (nonatomic, assign) SDL_Window *window;
+
+- (instancetype)initWithSDLWindow:(SDL_Window *)_window;
+
+- (void)setAnimationCallback:(int)interval
+                    callback:(void (*)(void*))callback
+               callbackParam:(void*)callbackParam;
+
+- (void)startAnimation;
+- (void)stopAnimation;
+
+- (void)doLoop:(CADisplayLink*)sender;
 
-- (id)initWithSDLWindow:(SDL_Window *)_window;
 - (void)loadView;
 - (void)viewDidLayoutSubviews;
 - (NSUInteger)supportedInterfaceOrientations;
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orient;
 - (BOOL)prefersStatusBarHidden;
+- (UIStatusBarStyle)preferredStatusBarStyle;
+
+#if SDL_IPHONE_KEYBOARD
+- (void)showKeyboard;
+- (void)hideKeyboard;
+- (void)initKeyboard;
+- (void)deinitKeyboard;
+
+- (void)keyboardWillShow:(NSNotification *)notification;
+- (void)keyboardWillHide:(NSNotification *)notification;
+
+- (void)updateKeyboard;
+
+@property (nonatomic, assign, getter=isKeyboardVisible) BOOL keyboardVisible;
+@property (nonatomic, assign) SDL_Rect textInputRect;
+@property (nonatomic, assign) int keyboardHeight;
+#endif
 
 @end
+
+#if SDL_IPHONE_KEYBOARD
+SDL_bool UIKit_HasScreenKeyboardSupport(_THIS);
+void UIKit_ShowScreenKeyboard(_THIS, SDL_Window *window);
+void UIKit_HideScreenKeyboard(_THIS, SDL_Window *window);
+SDL_bool UIKit_IsScreenKeyboardShown(_THIS, SDL_Window *window);
+void UIKit_SetTextInputRect(_THIS, SDL_Rect *rect);
+#endif
diff --git a/src/video/uikit/SDL_uikitviewcontroller.m b/src/video/uikit/SDL_uikitviewcontroller.m
index 447b80b..af1f68d 100644
--- a/src/video/uikit/SDL_uikitviewcontroller.m
+++ b/src/video/uikit/SDL_uikitviewcontroller.m
@@ -28,107 +28,388 @@
 #include "../SDL_sysvideo.h"
 #include "../../events/SDL_events_c.h"
 
-#include "SDL_uikitviewcontroller.h"
+#import "SDL_uikitviewcontroller.h"
+#import "SDL_uikitmessagebox.h"
 #include "SDL_uikitvideo.h"
 #include "SDL_uikitmodes.h"
 #include "SDL_uikitwindow.h"
 
+#if SDL_IPHONE_KEYBOARD
+#include "keyinfotable.h"
+#endif
 
-@implementation SDL_uikitviewcontroller
+@implementation SDL_uikitviewcontroller {
+    CADisplayLink *displayLink;
+    int animationInterval;
+    void (*animationCallback)(void*);
+    void *animationCallbackParam;
+
+#if SDL_IPHONE_KEYBOARD
+    UITextField *textField;
+#endif
+}
 
 @synthesize window;
 
-- (id)initWithSDLWindow:(SDL_Window *)_window
+- (instancetype)initWithSDLWindow:(SDL_Window *)_window
 {
-    self = [self init];
-    if (self == nil) {
-        return nil;
-    }
-    self.window = _window;
+    if (self = [super initWithNibName:nil bundle:nil]) {
+        self.window = _window;
 
+#if SDL_IPHONE_KEYBOARD
+        [self initKeyboard];
+#endif
+    }
     return self;
 }
 
+- (void)dealloc
+{
+#if SDL_IPHONE_KEYBOARD
+    [self deinitKeyboard];
+#endif
+}
+
+- (void)setAnimationCallback:(int)interval
+                    callback:(void (*)(void*))callback
+               callbackParam:(void*)callbackParam
+{
+    [self stopAnimation];
+
+    animationInterval = interval;
+    animationCallback = callback;
+    animationCallbackParam = callbackParam;
+
+    if (animationCallback) {
+        [self startAnimation];
+    }
+}
+
+- (void)startAnimation
+{
+    displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(doLoop:)];
+    [displayLink setFrameInterval:animationInterval];
+    [displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
+}
+
+- (void)stopAnimation
+{
+    [displayLink invalidate];
+    displayLink = nil;
+}
+
+- (void)doLoop:(CADisplayLink*)sender
+{
+    /* Don't run the game loop while a messagebox is up */
+    if (!UIKit_ShowingMessageBox()) {
+        animationCallback(animationCallbackParam);
+    }
+}
+
 - (void)loadView
 {
-    /* do nothing. */
+    /* Do nothing. */
 }
 
 - (void)viewDidLayoutSubviews
 {
-    if (self->window->flags & SDL_WINDOW_RESIZABLE) {
-        SDL_WindowData *data = self->window->driverdata;
-        SDL_VideoDisplay *display = SDL_GetDisplayForWindow(self->window);
-        SDL_DisplayModeData *displaymodedata = (SDL_DisplayModeData *) display->current_mode.driverdata;
-        const CGSize size = data->view.bounds.size;
-        int w, h;
+    const CGSize size = self.view.bounds.size;
+    int w = (int) size.width;
+    int h = (int) size.height;
+
+    SDL_SendWindowEvent(window, SDL_WINDOWEVENT_RESIZED, w, h);
+}
+
+- (NSUInteger)supportedInterfaceOrientations
+{
+    return UIKit_GetSupportedOrientations(window);
+}
+
+- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orient
+{
+    return ([self supportedInterfaceOrientations] & (1 << orient)) != 0;
+}
+
+- (BOOL)prefersStatusBarHidden
+{
+    return (window->flags & (SDL_WINDOW_FULLSCREEN|SDL_WINDOW_BORDERLESS)) != 0;
+}
+
+- (UIStatusBarStyle)preferredStatusBarStyle
+{
+    /* We assume most SDL apps don't have a bright white background. */
+    return UIStatusBarStyleLightContent;
+}
+
+/*
+ ---- Keyboard related functionality below this line ----
+ */
+#if SDL_IPHONE_KEYBOARD
+
+@synthesize textInputRect;
+@synthesize keyboardHeight;
+@synthesize keyboardVisible;
+
+/* Set ourselves up as a UITextFieldDelegate */
+- (void)initKeyboard
+{
+    textField = [[UITextField alloc] initWithFrame:CGRectZero];
+    textField.delegate = self;
+    /* placeholder so there is something to delete! */
+    textField.text = @" ";
+
+    /* set UITextInputTrait properties, mostly to defaults */
+    textField.autocapitalizationType = UITextAutocapitalizationTypeNone;
+    textField.autocorrectionType = UITextAutocorrectionTypeNo;
+    textField.enablesReturnKeyAutomatically = NO;
+    textField.keyboardAppearance = UIKeyboardAppearanceDefault;
+    textField.keyboardType = UIKeyboardTypeDefault;
+    textField.returnKeyType = UIReturnKeyDefault;
+    textField.secureTextEntry = NO;
 
-        w = (int)(size.width * displaymodedata->scale);
-        h = (int)(size.height * displaymodedata->scale);
+    textField.hidden = YES;
+    keyboardVisible = NO;
 
-        SDL_SendWindowEvent(self->window, SDL_WINDOWEVENT_RESIZED, w, h);
+    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
+    [center addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
+    [center addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
+}
+
+- (void)setView:(UIView *)view
+{
+    [super setView:view];
+
+    [view addSubview:textField];
+
+    if (keyboardVisible) {
+        [self showKeyboard];
     }
 }
 
-- (NSUInteger)supportedInterfaceOrientations
+- (void)deinitKeyboard
 {
-    NSUInteger orientationMask = 0;
+    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
+    [center removeObserver:self name:UIKeyboardWillShowNotification object:nil];
+    [center removeObserver:self name:UIKeyboardWillHideNotification object:nil];
+}
 
-    const char *orientationsCString;
-    if ((orientationsCString = SDL_GetHint(SDL_HINT_ORIENTATIONS)) != NULL) {
-        BOOL rotate = NO;
-        NSString *orientationsNSString = [NSString stringWithCString:orientationsCString
-                                                            encoding:NSUTF8StringEncoding];
-        NSArray *orientations = [orientationsNSString componentsSeparatedByCharactersInSet:
-                                 [NSCharacterSet characterSetWithCharactersInString:@" "]];
+/* reveal onscreen virtual keyboard */
+- (void)showKeyboard
+{
+    keyboardVisible = YES;
+    if (textField.window) {
+        [textField becomeFirstResponder];
+    }
+}
 
-        if ([orientations containsObject:@"LandscapeLeft"]) {
-            orientationMask |= UIInterfaceOrientationMaskLandscapeLeft;
-        }
-        if ([orientations containsObject:@"LandscapeRight"]) {
-            orientationMask |= UIInterfaceOrientationMaskLandscapeRight;
-        }
-        if ([orientations containsObject:@"Portrait"]) {
-            orientationMask |= UIInterfaceOrientationMaskPortrait;
+/* hide onscreen virtual keyboard */
+- (void)hideKeyboard
+{
+    keyboardVisible = NO;
+    [textField resignFirstResponder];
+}
+
+- (void)keyboardWillShow:(NSNotification *)notification
+{
+    CGRect kbrect = [[notification userInfo][UIKeyboardFrameBeginUserInfoKey] CGRectValue];
+    UIView *view = self.view;
+    int height = 0;
+
+    /* The keyboard rect is in the coordinate space of the screen, but we want
+     * its height in the view's coordinate space. */
+#ifdef __IPHONE_8_0
+    if ([view respondsToSelector:@selector(convertRect:fromCoordinateSpace:)]) {
+        UIScreen *screen = view.window.screen;
+        kbrect = [view convertRect:kbrect fromCoordinateSpace:screen.coordinateSpace];
+        height = kbrect.size.height;
+    } else
+#endif
+    {
+        /* In iOS 7 and below, the screen's coordinate space is never rotated. */
+        if (UIInterfaceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation)) {
+            height = kbrect.size.width;
+        } else {
+            height = kbrect.size.height;
         }
-        if ([orientations containsObject:@"PortraitUpsideDown"]) {
-            orientationMask |= UIInterfaceOrientationMaskPortraitUpsideDown;
+    }
+
+    [self setKeyboardHeight:height];
+}
+
+- (void)keyboardWillHide:(NSNotification *)notification
+{
+    [self setKeyboardHeight:0];
+}
+
+- (void)updateKeyboard
+{
+    SDL_Rect textrect = self.textInputRect;
+    CGAffineTransform t = self.view.transform;
+    CGPoint offset = CGPointMake(0.0, 0.0);
+
+    if (self.keyboardHeight) {
+        int rectbottom = textrect.y + textrect.h;
+        int kbottom = self.view.bounds.size.height - self.keyboardHeight;
+        if (kbottom < rectbottom) {
+            offset.y = kbottom - rectbottom;
         }
+    }
+
+    /* Put the offset into the this view transform's coordinate space. */
+    t.tx = 0.0;
+    t.ty = 0.0;
+    offset = CGPointApplyAffineTransform(offset, t);
+
+    t.tx = offset.x;
+    t.ty = offset.y;
+
+    /* Move the view by applying the updated transform. */
+    self.view.transform = t;
+}
 
-    } else if (self->window->flags & SDL_WINDOW_RESIZABLE) {
-        orientationMask = UIInterfaceOrientationMaskAll;  /* any orientation is okay. */
+- (void)setKeyboardHeight:(int)height
+{
+    keyboardVisible = height > 0;
+    keyboardHeight = height;
+    [self updateKeyboard];
+}
+
+/* UITextFieldDelegate method.  Invoked when user types something. */
+- (BOOL)textField:(UITextField *)_textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
+{
+    NSUInteger len = string.length;
+
+    if (len == 0) {
+        /* it wants to replace text with nothing, ie a delete */
+        SDL_SendKeyboardKey(SDL_PRESSED, SDL_SCANCODE_BACKSPACE);
+        SDL_SendKeyboardKey(SDL_RELEASED, SDL_SCANCODE_BACKSPACE);
     } else {
-        if (self->window->w >= self->window->h) {
-            orientationMask |= UIInterfaceOrientationMaskLandscape;
-        }
-        if (self->window->h >= self->window->w) {
-            orientationMask |= (UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskPortraitUpsideDown);
+        /* go through all the characters in the string we've been sent and
+         * convert them to key presses */
+        int i;
+        for (i = 0; i < len; i++) {
+            unichar c = [string characterAtIndex:i];
+            Uint16 mod = 0;
+            SDL_Scancode code;
+
+            if (c < 127) {
+                /* figure out the SDL_Scancode and SDL_keymod for this unichar */
+                code = unicharToUIKeyInfoTable[c].code;
+                mod  = unicharToUIKeyInfoTable[c].mod;
+            } else {
+                /* we only deal with ASCII right now */
+                code = SDL_SCANCODE_UNKNOWN;
+                mod = 0;
+            }
+
+            if (mod & KMOD_SHIFT) {
+                /* If character uses shift, press shift down */
+                SDL_SendKeyboardKey(SDL_PRESSED, SDL_SCANCODE_LSHIFT);
+            }
+
+            /* send a keydown and keyup even for the character */
+            SDL_SendKeyboardKey(SDL_PRESSED, code);
+            SDL_SendKeyboardKey(SDL_RELEASED, code);
+
+            if (mod & KMOD_SHIFT) {
+                /* If character uses shift, press shift back up */
+                SDL_SendKeyboardKey(SDL_RELEASED, SDL_SCANCODE_LSHIFT);
+            }
         }
+
+        SDL_SendKeyboardText([string UTF8String]);
+    }
+
+    return NO; /* don't allow the edit! (keep placeholder text there) */
+}
+
+/* Terminates the editing session */
+- (BOOL)textFieldShouldReturn:(UITextField*)_textField
+{
+    SDL_SendKeyboardKey(SDL_PRESSED, SDL_SCANCODE_RETURN);
+    SDL_SendKeyboardKey(SDL_RELEASED, SDL_SCANCODE_RETURN);
+    SDL_StopTextInput();
+    return YES;
+}
+
+#endif
+
+@end
+
+/* iPhone keyboard addition functions */
+#if SDL_IPHONE_KEYBOARD
+
+static SDL_uikitviewcontroller *
+GetWindowViewController(SDL_Window * window)
+{
+    if (!window || !window->driverdata) {
+        SDL_SetError("Invalid window");
+        return nil;
     }
 
-    /* Don't allow upside-down orientation on the phone, so answering calls is in the natural orientation */
-    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
-        orientationMask &= ~UIInterfaceOrientationMaskPortraitUpsideDown;
+    SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata;
+
+    return data.viewcontroller;
+}
+
+SDL_bool
+UIKit_HasScreenKeyboardSupport(_THIS)
+{
+    return SDL_TRUE;
+}
+
+void
+UIKit_ShowScreenKeyboard(_THIS, SDL_Window *window)
+{
+    @autoreleasepool {
+        SDL_uikitviewcontroller *vc = GetWindowViewController(window);
+        [vc showKeyboard];
     }
-    return orientationMask;
 }
 
-- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orient
+void
+UIKit_HideScreenKeyboard(_THIS, SDL_Window *window)
 {
-    NSUInteger orientationMask = [self supportedInterfaceOrientations];
-    return (orientationMask & (1 << orient));
+    @autoreleasepool {
+        SDL_uikitviewcontroller *vc = GetWindowViewController(window);
+        [vc hideKeyboard];
+    }
 }
 
-- (BOOL)prefersStatusBarHidden
+SDL_bool
+UIKit_IsScreenKeyboardShown(_THIS, SDL_Window *window)
 {
-    if (self->window->flags & (SDL_WINDOW_FULLSCREEN|SDL_WINDOW_BORDERLESS)) {
-        return YES;
-    } else {
-        return NO;
+    @autoreleasepool {
+        SDL_uikitviewcontroller *vc = GetWindowViewController(window);
+        if (vc != nil) {
+            return vc.isKeyboardVisible;
+        }
+        return SDL_FALSE;
     }
 }
 
-@end
+void
+UIKit_SetTextInputRect(_THIS, SDL_Rect *rect)
+{
+    if (!rect) {
+        SDL_InvalidParamError("rect");
+        return;
+    }
+
+    @autoreleasepool {
+        SDL_uikitviewcontroller *vc = GetWindowViewController(SDL_GetFocusWindow());
+        if (vc != nil) {
+            vc.textInputRect = *rect;
+
+            if (vc.keyboardVisible) {
+                [vc updateKeyboard];
+            }
+        }
+    }
+}
+
+
+#endif /* SDL_IPHONE_KEYBOARD */
 
 #endif /* SDL_VIDEO_DRIVER_UIKIT */
 
diff --git a/src/video/uikit/SDL_uikitwindow.h b/src/video/uikit/SDL_uikitwindow.h
index 494b028..73203d1 100644
--- a/src/video/uikit/SDL_uikitwindow.h
+++ b/src/video/uikit/SDL_uikitwindow.h
@@ -23,28 +23,33 @@
 
 #include "../SDL_sysvideo.h"
 #import "SDL_uikitvideo.h"
-#import "SDL_uikitopenglview.h"
+#import "SDL_uikitview.h"
 #import "SDL_uikitviewcontroller.h"
 
-typedef struct SDL_WindowData SDL_WindowData;
-
 extern int UIKit_CreateWindow(_THIS, SDL_Window * window);
+extern void UIKit_SetWindowTitle(_THIS, SDL_Window * window);
 extern void UIKit_ShowWindow(_THIS, SDL_Window * window);
 extern void UIKit_HideWindow(_THIS, SDL_Window * window);
 extern void UIKit_RaiseWindow(_THIS, SDL_Window * window);
+extern void UIKit_SetWindowBordered(_THIS, SDL_Window * window, SDL_bool bordered);
 extern void UIKit_SetWindowFullscreen(_THIS, SDL_Window * window, SDL_VideoDisplay * display, SDL_bool fullscreen);
 extern void UIKit_DestroyWindow(_THIS, SDL_Window * window);
 extern SDL_bool UIKit_GetWindowWMInfo(_THIS, SDL_Window * window,
                                       struct SDL_SysWMinfo * info);
 
+extern NSUInteger UIKit_GetSupportedOrientations(SDL_Window * window);
+
 @class UIWindow;
 
-struct SDL_WindowData
-{
-    UIWindow *uiwindow;
-    SDL_uikitopenglview *view;
-    SDL_uikitviewcontroller *viewcontroller;
-};
+@interface SDL_WindowData : NSObject
+
+@property (nonatomic, strong) UIWindow *uiwindow;
+@property (nonatomic, strong) SDL_uikitviewcontroller *viewcontroller;
+
+/* Array of SDL_uikitviews owned by this window. */
+@property (nonatomic, copy) NSMutableArray *views;
+
+@end
 
 #endif /* _SDL_uikitwindow_h */
 
diff --git a/src/video/uikit/SDL_uikitwindow.m b/src/video/uikit/SDL_uikitwindow.m
index 2b15677..550b6f9 100644
--- a/src/video/uikit/SDL_uikitwindow.m
+++ b/src/video/uikit/SDL_uikitwindow.m
@@ -37,89 +37,110 @@
 #include "SDL_uikitwindow.h"
 #import "SDL_uikitappdelegate.h"
 
-#import "SDL_uikitopenglview.h"
+#import "SDL_uikitview.h"
 
 #include <Foundation/Foundation.h>
 
+@implementation SDL_WindowData
 
+@synthesize uiwindow;
+@synthesize viewcontroller;
+@synthesize views;
+
+- (instancetype)init
+{
+    if ((self = [super init])) {
+        views = [NSMutableArray new];
+    }
+
+    return self;
+}
+
+@end
+
+@interface SDL_uikitwindow : UIWindow
+
+- (void)layoutSubviews;
+
+@end
+
+@implementation SDL_uikitwindow
+
+- (void)layoutSubviews
+{
+    /* Workaround to fix window orientation issues in iOS 8+. */
+    self.frame = self.screen.bounds;
+    [super layoutSubviews];
+}
+
+@end
 
 
 static int SetupWindowData(_THIS, SDL_Window *window, UIWindow *uiwindow, SDL_bool created)
 {
     SDL_VideoDisplay *display = SDL_GetDisplayForWindow(window);
-    SDL_DisplayModeData *displaymodedata = (SDL_DisplayModeData *) display->current_mode.driverdata;
-    SDL_DisplayData *displaydata = (SDL_DisplayData *) display->driverdata;
-    SDL_WindowData *data;
+    SDL_DisplayData *displaydata = (__bridge SDL_DisplayData *) display->driverdata;
+    SDL_uikitview *view;
+
+    CGRect frame = UIKit_ComputeViewFrame(window, displaydata.uiscreen);
+    int width  = (int) frame.size.width;
+    int height = (int) frame.size.height;
 
-    /* Allocate the window data */
-    data = (SDL_WindowData *)SDL_malloc(sizeof(*data));
+    SDL_WindowData *data = [[SDL_WindowData alloc] init];
     if (!data) {
         return SDL_OutOfMemory();
     }
-    data->uiwindow = uiwindow;
-    data->viewcontroller = nil;
-    data->view = nil;
-
-    /* Fill in the SDL window with the window data */
-    {
-        window->x = 0;
-        window->y = 0;
-
-        CGRect bounds;
-        if (window->flags & (SDL_WINDOW_FULLSCREEN|SDL_WINDOW_BORDERLESS)) {
-            bounds = [displaydata->uiscreen bounds];
-        } else {
-            bounds = [displaydata->uiscreen applicationFrame];
-        }
 
-        /* Get frame dimensions in pixels */
-        int width = (int)(bounds.size.width * displaymodedata->scale);
-        int height = (int)(bounds.size.height * displaymodedata->scale);
+    window->driverdata = (void *) CFBridgingRetain(data);
+
+    data.uiwindow = uiwindow;
+
+    /* only one window on iOS, always shown */
+    window->flags &= ~SDL_WINDOW_HIDDEN;
+
+    if (displaydata.uiscreen == [UIScreen mainScreen]) {
+        window->flags |= SDL_WINDOW_INPUT_FOCUS;  /* always has input focus */
+    } else {
+        window->flags &= ~SDL_WINDOW_RESIZABLE;  /* window is NEVER resizable */
+        window->flags &= ~SDL_WINDOW_INPUT_FOCUS;  /* never has input focus */
+        window->flags |= SDL_WINDOW_BORDERLESS;  /* never has a status bar. */
+    }
+
+    if (displaydata.uiscreen == [UIScreen mainScreen]) {
+        NSUInteger orients = UIKit_GetSupportedOrientations(window);
+        BOOL supportsLandscape = (orients & UIInterfaceOrientationMaskLandscape) != 0;
+        BOOL supportsPortrait = (orients & (UIInterfaceOrientationMaskPortrait|UIInterfaceOrientationMaskPortraitUpsideDown)) != 0;
 
         /* Make sure the width/height are oriented correctly */
-        if (UIKit_IsDisplayLandscape(displaydata->uiscreen) != (width > height)) {
+        if ((width > height && !supportsLandscape) || (height > width && !supportsPortrait)) {
             int temp = width;
             width = height;
             height = temp;
         }
-
-        window->w = width;
-        window->h = height;
     }
 
-    window->driverdata = data;
+    window->x = 0;
+    window->y = 0;
+    window->w = width;
+    window->h = height;
 
-    /* only one window on iOS, always shown */
-    window->flags &= ~SDL_WINDOW_HIDDEN;
+    /* The View Controller will handle rotating the view when the device
+     * orientation changes. This will trigger resize events, if appropriate. */
+    data.viewcontroller = [[SDL_uikitviewcontroller alloc] initWithSDLWindow:window];
 
-    /* SDL_WINDOW_BORDERLESS controls whether status bar is hidden.
-     * This is only set if the window is on the main screen. Other screens
-     *  just force the window to have the borderless flag.
-     */
-    if (displaydata->uiscreen == [UIScreen mainScreen]) {
-        window->flags |= SDL_WINDOW_INPUT_FOCUS;  /* always has input focus */
+    /* The window will initially contain a generic view so resizes, touch events,
+     * etc. can be handled without an active OpenGL view/context. */
+    view = [[SDL_uikitview alloc] initWithFrame:frame];
 
-        /* This was setup earlier for our window, and in iOS 7 is controlled by the view, not the application
-        if ([UIApplication sharedApplication].statusBarHidden) {
-            window->flags |= SDL_WINDOW_BORDERLESS;
-        } else {
-            window->flags &= ~SDL_WINDOW_BORDERLESS;
-        }
-        */
-    } else {
-        window->flags &= ~SDL_WINDOW_RESIZABLE;  /* window is NEVER resizeable */
-        window->flags &= ~SDL_WINDOW_INPUT_FOCUS;  /* never has input focus */
-        window->flags |= SDL_WINDOW_BORDERLESS;  /* never has a status bar. */
-    }
+    /* Sets this view as the controller's view, and adds the view to the window
+     * heirarchy. */
+    [view setSDLWindow:window];
 
-    /* The View Controller will handle rotating the view when the
-     * device orientation changes. This will trigger resize events, if
-     * appropriate.
-     */
-    SDL_uikitviewcontroller *controller;
-    controller = [SDL_uikitviewcontroller alloc];
-    data->viewcontroller = [controller initWithSDLWindow:window];
-    [data->viewcontroller setTitle:@"SDL App"];  /* !!! FIXME: hook up SDL_SetWindowTitle() */
+    /* Make this window the current mouse focus for touch input */
+    if (displaydata.uiscreen == [UIScreen mainScreen]) {
+        SDL_SetMouseFocus(window);
+        SDL_SetKeyboardFocus(window);
+    }
 
     return 0;
 }
@@ -127,173 +148,165 @@ static int SetupWindowData(_THIS, SDL_Window *window, UIWindow *uiwindow, SDL_bo
 int
 UIKit_CreateWindow(_THIS, SDL_Window *window)
 {
-    SDL_VideoDisplay *display = SDL_GetDisplayForWindow(window);
-    SDL_DisplayData *data = (SDL_DisplayData *) display->driverdata;
-    const BOOL external = ([UIScreen mainScreen] != data->uiscreen);
-    const CGSize origsize = [[data->uiscreen currentMode] size];
+    @autoreleasepool {
+        SDL_VideoDisplay *display = SDL_GetDisplayForWindow(window);
+        SDL_DisplayData *data = (__bridge SDL_DisplayData *) display->driverdata;
+        const CGSize origsize = data.uiscreen.currentMode.size;
 
-    /* SDL currently puts this window at the start of display's linked list. We rely on this. */
-    SDL_assert(_this->windows == window);
-
-    /* We currently only handle a single window per display on iOS */
-    if (window->next != NULL) {
-        return SDL_SetError("Only one window allowed per display.");
-    }
+        /* SDL currently puts this window at the start of display's linked list. We rely on this. */
+        SDL_assert(_this->windows == window);
 
-    /* If monitor has a resolution of 0x0 (hasn't been explicitly set by the
-     * user, so it's in standby), try to force the display to a resolution
-     * that most closely matches the desired window size.
-     */
-    if ((origsize.width == 0.0f) && (origsize.height == 0.0f)) {
-        if (display->num_display_modes == 0) {
-            _this->GetDisplayModes(_this, display);
+        /* We currently only handle a single window per display on iOS */
+        if (window->next != NULL) {
+            return SDL_SetError("Only one window allowed per display.");
         }
 
-        int i;
-        const SDL_DisplayMode *bestmode = NULL;
-        for (i = display->num_display_modes; i >= 0; i--) {
-            const SDL_DisplayMode *mode = &display->display_modes[i];
-            if ((mode->w >= window->w) && (mode->h >= window->h))
-                bestmode = mode;
-        }
+        /* If monitor has a resolution of 0x0 (hasn't been explicitly set by the
+         * user, so it's in standby), try to force the display to a resolution
+         * that most closely matches the desired window size. */
+        if ((origsize.width == 0.0f) && (origsize.height == 0.0f)) {
+            if (display->num_display_modes == 0) {
+                _this->GetDisplayModes(_this, display);
+            }
 
-        if (bestmode) {
-            SDL_DisplayModeData *modedata = (SDL_DisplayModeData *)bestmode->driverdata;
-            [data->uiscreen setCurrentMode:modedata->uiscreenmode];
+            int i;
+            const SDL_DisplayMode *bestmode = NULL;
+            for (i = display->num_display_modes; i >= 0; i--) {
+                const SDL_DisplayMode *mode = &display->display_modes[i];
+                if ((mode->w >= window->w) && (mode->h >= window->h)) {
+                    bestmode = mode;
+                }
+            }
 
-            /* desktop_mode doesn't change here (the higher level will
-             * use it to set all the screens back to their defaults
-             * upon window destruction, SDL_Quit(), etc.
-             */
-            display->current_mode = *bestmode;
-        }
-    }
+            if (bestmode) {
+                SDL_DisplayModeData *modedata = (__bridge SDL_DisplayModeData *)bestmode->driverdata;
+                [data.uiscreen setCurrentMode:modedata.uiscreenmode];
 
-    if (data->uiscreen == [UIScreen mainScreen]) {
-        if (window->flags & (SDL_WINDOW_FULLSCREEN|SDL_WINDOW_BORDERLESS)) {
-            [UIApplication sharedApplication].statusBarHidden = YES;
-        } else {
-            [UIApplication sharedApplication].statusBarHidden = NO;
+                /* desktop_mode doesn't change here (the higher level will
+                 * use it to set all the screens back to their defaults
+                 * upon window destruction, SDL_Quit(), etc. */
+                display->current_mode = *bestmode;
+            }
         }
-    }
 
-    if (!(window->flags & SDL_WINDOW_RESIZABLE)) {
-        if (window->w > window->h) {
-            if (!UIKit_IsDisplayLandscape(data->uiscreen)) {
-                [[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeRight animated:NO];
-            }
-        } else if (window->w < window->h) {
-            if (UIKit_IsDisplayLandscape(data->uiscreen)) {
-                [[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationPortrait animated:NO];
+        if (data.uiscreen == [UIScreen mainScreen]) {
+            NSUInteger orientations = UIKit_GetSupportedOrientations(window);
+            UIApplication *app = [UIApplication sharedApplication];
+
+            if (window->flags & (SDL_WINDOW_FULLSCREEN|SDL_WINDOW_BORDERLESS)) {
+                app.statusBarHidden = YES;
+            } else {
+                app.statusBarHidden = NO;
             }
         }
-    }
 
-    /* ignore the size user requested, and make a fullscreen window */
-    /* !!! FIXME: can we have a smaller view? */
-    UIWindow *uiwindow = [UIWindow alloc];
-    uiwindow = [uiwindow initWithFrame:[data->uiscreen bounds]];
-
-    /* put the window on an external display if appropriate. This implicitly
-     * does [uiwindow setframe:[uiscreen bounds]], so don't do it on the
-     * main display, where we land by default, as that would eat the
-     * status bar real estate.
-     */
-    if (external) {
-        [uiwindow setScreen:data->uiscreen];
-    }
+        /* ignore the size user requested, and make a fullscreen window */
+        /* !!! FIXME: can we have a smaller view? */
+        UIWindow *uiwindow = [[SDL_uikitwindow alloc] initWithFrame:data.uiscreen.bounds];
 
-    if (SetupWindowData(_this, window, uiwindow, SDL_TRUE) < 0) {
-        [uiwindow release];
-        return -1;
+        /* put the window on an external display if appropriate. */
+        if (data.uiscreen != [UIScreen mainScreen]) {
+            [uiwindow setScreen:data.uiscreen];
+        }
+
+        if (SetupWindowData(_this, window, uiwindow, SDL_TRUE) < 0) {
+            return -1;
+        }
     }
 
     return 1;
+}
 
+void
+UIKit_SetWindowTitle(_THIS, SDL_Window * window)
+{
+    @autoreleasepool {
+        SDL_WindowData *data = (__bridge SDL_WindowData *) window->driverdata;
+        if (window->title) {
+            data.viewcontroller.title = @(window->title);
+        } else {
+            data.viewcontroller.title = nil;
+        }
+    }
 }
 
 void
 UIKit_ShowWindow(_THIS, SDL_Window * window)
 {
-    UIWindow *uiwindow = ((SDL_WindowData *) window->driverdata)->uiwindow;
-
-    [uiwindow makeKeyAndVisible];
+    @autoreleasepool {
+        SDL_WindowData *data = (__bridge SDL_WindowData *) window->driverdata;
+        [data.uiwindow makeKeyAndVisible];
+    }
 }
 
 void
 UIKit_HideWindow(_THIS, SDL_Window * window)
 {
-    UIWindow *uiwindow = ((SDL_WindowData *) window->driverdata)->uiwindow;
-
-    uiwindow.hidden = YES;
+    @autoreleasepool {
+        SDL_WindowData *data = (__bridge SDL_WindowData *) window->driverdata;
+        data.uiwindow.hidden = YES;
+    }
 }
 
 void
 UIKit_RaiseWindow(_THIS, SDL_Window * window)
 {
     /* We don't currently offer a concept of "raising" the SDL window, since
-     *  we only allow one per display, in the iOS fashion.
+     * we only allow one per display, in the iOS fashion.
      * However, we use this entry point to rebind the context to the view
-     *  during OnWindowRestored processing.
-     */
+     * during OnWindowRestored processing. */
     _this->GL_MakeCurrent(_this, _this->current_glwin, _this->current_glctx);
 }
 
-void
-UIKit_SetWindowFullscreen(_THIS, SDL_Window * window, SDL_VideoDisplay * display, SDL_bool fullscreen)
+static void
+UIKit_UpdateWindowBorder(_THIS, SDL_Window * window)
 {
-    SDL_DisplayData *displaydata = (SDL_DisplayData *) display->driverdata;
-    SDL_DisplayModeData *displaymodedata = (SDL_DisplayModeData *) display->current_mode.driverdata;
-    UIWindow *uiwindow = ((SDL_WindowData *) window->driverdata)->uiwindow;
+    SDL_WindowData *data = (__bridge SDL_WindowData *) window->driverdata;
+    SDL_uikitviewcontroller *viewcontroller = data.viewcontroller;
 
-    if (fullscreen) {
-        [UIApplication sharedApplication].statusBarHidden = YES;
-    } else {
-        [UIApplication sharedApplication].statusBarHidden = NO;
+    if (data.uiwindow.screen == [UIScreen mainScreen]) {
+        if (window->flags & (SDL_WINDOW_FULLSCREEN | SDL_WINDOW_BORDERLESS)) {
+            [UIApplication sharedApplication].statusBarHidden = YES;
+        } else {
+            [UIApplication sharedApplication].statusBarHidden = NO;
+        }
+
+        /* iOS 7+ won't update the status bar until we tell it to. */
+        if ([viewcontroller respondsToSelector:@selector(setNeedsStatusBarAppearanceUpdate)]) {
+            [viewcontroller setNeedsStatusBarAppearanceUpdate];
+        }
     }
 
-    CGRect bounds;
-    if (fullscreen) {
-        bounds = [displaydata->uiscreen bounds];
-    } else {
-        bounds = [displaydata->uiscreen applicationFrame];
+    /* Update the view's frame to account for the status bar change. */
+    viewcontroller.view.frame = UIKit_ComputeViewFrame(window, data.uiwindow.screen);
+    [viewcontroller.view setNeedsLayout];
+    [viewcontroller.view layoutIfNeeded];
+}
+
+void
+UIKit_SetWindowBordered(_THIS, SDL_Window * window, SDL_bool bordered)
+{
+    @autoreleasepool {
+        UIKit_UpdateWindowBorder(_this, window);
     }
+}
 
-    /* Get frame dimensions in pixels */
-    int width = (int)(bounds.size.width * displaymodedata->scale);
-    int height = (int)(bounds.size.height * displaymodedata->scale);
-
-    /* We can pick either width or height here and we'll rotate the
-       screen to match, so we pick the closest to what we wanted.
-     */
-    if (window->w >= window->h) {
-        if (width > height) {
-            window->w = width;
-            window->h = height;
-        } else {
-            window->w = height;
-            window->h = width;
-        }
-    } else {
-        if (width > height) {
-            window->w = height;
-            window->h = width;
-        } else {
-            window->w = width;
-            window->h = height;
-        }
+void
+UIKit_SetWindowFullscreen(_THIS, SDL_Window * window, SDL_VideoDisplay * display, SDL_bool fullscreen)
+{
+    @autoreleasepool {
+        UIKit_UpdateWindowBorder(_this, window);
     }
 }
 
 void
 UIKit_DestroyWindow(_THIS, SDL_Window * window)
 {
-    SDL_WindowData *data = (SDL_WindowData *)window->driverdata;
-
-    if (data) {
-        [data->viewcontroller release];
-        [data->uiwindow release];
-        SDL_free(data);
+    @autoreleasepool {
+        if (window->driverdata != NULL) {
+            SDL_WindowData *data = (SDL_WindowData *) CFBridgingRelease(window->driverdata);
+            [data.viewcontroller stopAnimation];
+        }
     }
     window->driverdata = NULL;
 }
@@ -301,29 +314,82 @@ UIKit_DestroyWindow(_THIS, SDL_Window * window)
 SDL_bool
 UIKit_GetWindowWMInfo(_THIS, SDL_Window * window, SDL_SysWMinfo * info)
 {
-    UIWindow *uiwindow = ((SDL_WindowData *) window->driverdata)->uiwindow;
+    @autoreleasepool {
+        SDL_WindowData *data = (__bridge SDL_WindowData *) window->driverdata;
 
-    if (info->version.major <= SDL_MAJOR_VERSION) {
-        info->subsystem = SDL_SYSWM_UIKIT;
-        info->info.uikit.window = uiwindow;
-        return SDL_TRUE;
-    } else {
-        SDL_SetError("Application not compiled with SDL %d.%d\n",
-                     SDL_MAJOR_VERSION, SDL_MINOR_VERSION);
-        return SDL_FALSE;
+        if (info->version.major <= SDL_MAJOR_VERSION) {
+            info->subsystem = SDL_SYSWM_UIKIT;
+            info->info.uikit.window = data.uiwindow;
+            return SDL_TRUE;
+        } else {
+            SDL_SetError("Application not compiled with SDL %d.%d\n",
+                         SDL_MAJOR_VERSION, SDL_MINOR_VERSION);
+            return SDL_FALSE;
+        }
     }
 }
 
+NSUInteger
+UIKit_GetSupportedOrientations(SDL_Window * window)
+{
+    const char *hint = SDL_GetHint(SDL_HINT_ORIENTATIONS);
+    NSUInteger orientationMask = 0;
+
+    @autoreleasepool {
+        if (hint != NULL) {
+            NSArray *orientations = [@(hint) componentsSeparatedByString:@" "];
+
+            if ([orientations containsObject:@"LandscapeLeft"]) {
+                orientationMask |= UIInterfaceOrientationMaskLandscapeLeft;
+            }
+            if ([orientations containsObject:@"LandscapeRight"]) {
+                orientationMask |= UIInterfaceOrientationMaskLandscapeRight;
+            }
+            if ([orientations containsObject:@"Portrait"]) {
+                orientationMask |= UIInterfaceOrientationMaskPortrait;
+            }
+            if ([orientations containsObject:@"PortraitUpsideDown"]) {
+                orientationMask |= UIInterfaceOrientationMaskPortraitUpsideDown;
+            }
+        }
+
+        if (orientationMask == 0 && (window->flags & SDL_WINDOW_RESIZABLE)) {
+            /* any orientation is okay. */
+            orientationMask = UIInterfaceOrientationMaskAll;
+        }
+
+        if (orientationMask == 0) {
+            if (window->w >= window->h) {
+                orientationMask |= UIInterfaceOrientationMaskLandscape;
+            }
+            if (window->h >= window->w) {
+                orientationMask |= (UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskPortraitUpsideDown);
+            }
+        }
+
+        /* Don't allow upside-down orientation on the phone, so answering calls is in the natural orientation */
+        if ([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPhone) {
+            orientationMask &= ~UIInterfaceOrientationMaskPortraitUpsideDown;
+        }
+    }
+
+    return orientationMask;
+}
+
 int
 SDL_iPhoneSetAnimationCallback(SDL_Window * window, int interval, void (*callback)(void*), void *callbackParam)
 {
-    SDL_WindowData *data = window ? (SDL_WindowData *)window->driverdata : NULL;
+    if (!window || !window->driverdata) {
+        return SDL_SetError("Invalid window");
+    }
 
-    if (!data || !data->view) {
-        return SDL_SetError("Invalid window or view not set");
+    @autoreleasepool {
+        SDL_WindowData *data = (__bridge SDL_WindowData *)window->driverdata;
+        [data.viewcontroller setAnimationCallback:interval
+                                         callback:callback
+                                    callbackParam:callbackParam];
     }
 
-    [data->view setAnimationCallback:interval callback:callback callbackParam:callbackParam];
     return 0;
 }