File: control.c

package info (click to toggle)
freeciv 3.2.2%2Bds-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 286,492 kB
  • sloc: ansic: 484,452; cpp: 37,766; sh: 10,374; makefile: 7,425; python: 2,938; xml: 652; sed: 11
file content (4115 lines) | stat: -rw-r--r-- 136,622 bytes parent folder | download
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
/***********************************************************************
 Freeciv - Copyright (C) 1996 - A Kjeldberg, L Gregersen, P Unold
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2, or (at your option)
   any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
***********************************************************************/

#ifdef HAVE_CONFIG_H
#include <fc_config.h>
#endif

/* utility */
#include "astring.h"
#include "bitvector.h"
#include "fcintl.h"
#include "log.h"
#include "mem.h"
#include "timing.h"

/* common */
#include "combat.h"
#include "game.h"
#include "map.h"
#include "movement.h"
#include "unitlist.h"

/* common/aicore */
#include "path_finding.h"

/* client/include */
#include "chatline_g.h"
#include "citydlg_g.h"
#include "dialogs_g.h"
#include "gui_main_g.h"
#include "mapctrl_g.h"
#include "mapview_g.h"
#include "menu_g.h"

/* client */
#include "audio.h"
#include "client_main.h"
#include "climap.h"
#include "climisc.h"
#include "editor.h"
#include "goto.h"
#include "options.h"
#include "overview_common.h"
#include "tilespec.h"
#include "update_queue.h"

#include "control.h"


struct client_disband_unit_data {
  int unit_id;
  int alt;
};

/* Ways to disband a unit. Sorted by preference. Starts with the worst. */
/* TODO: Should other actions that consumes the unit be considered?
 * Join City may be an appealing alternative. Perhaps it should be a
 * user configurable client option? */
static int disband_unit_alternatives[3] = {
  ACTION_DISBAND_UNIT,
  ACTION_DISBAND_UNIT_RECOVER,
  ACTION_HELP_WONDER,
};

/* gui-dep code may adjust depending on tile size etc: */
int num_units_below = MAX_NUM_UNITS_BELOW;

/* current_focus points to the current unit(s) in focus */
static struct unit_list *current_focus = NULL;

/* The previously focused unit(s).  Focus can generally be recalled
 * with keypad 5 (or the equivalent). */
static struct unit_list *previous_focus = NULL;

/* The priority unit(s) for unit_focus_advance(). */
static struct unit_list *urgent_focus_queue = NULL;

/* These should be set via set_hover_state() */
enum cursor_hover_state hover_state = HOVER_NONE;
enum unit_activity connect_activity;
struct extra_type *connect_tgt;

action_id goto_last_action;
int goto_last_tgt;
int goto_last_sub_tgt;
enum unit_orders goto_last_order; /* Last order for goto */

static struct tile *hover_tile = NULL;
static struct unit_list *battlegroups[MAX_NUM_BATTLEGROUPS];

/* Current moving unit. */
static struct unit *punit_moving = NULL;

/* units involved in current combat */
static struct unit *punit_attacking = NULL;
static struct unit *punit_defending = NULL;

/* The ID of the unit that currently is in the action selection process.
 *
 * The action selection process begins when the client asks the server what
 * actions a unit can take. It ends when the last follow up question is
 * answered.
 *
 * No common client code using client supports more than one action
 * selection process at once. The interface between the common client code
 * and the clients would have to change before that could happen. (See
 * action_selection_actor_unit() etc)
 */
static int action_selection_in_progress_for = IDENTITY_NUMBER_ZERO;

/*
 * This variable is TRUE iff a NON-AI controlled unit was focused this
 * turn.
 */
bool non_ai_unit_focus;

static void do_unit_teleport_to(struct unit *punit, struct tile *ptile);

/*************************************************************************/

static struct unit *quickselect(struct tile *ptile,
                                enum quickselect_type qtype);

/**********************************************************************//**
  Called only by client_game_init() in client/client_main.c
**************************************************************************/
void control_init(void)
{
  int i;

  current_focus = unit_list_new();
  previous_focus = unit_list_new();
  urgent_focus_queue = unit_list_new();

  for (i = 0; i < MAX_NUM_BATTLEGROUPS; i++) {
    battlegroups[i] = unit_list_new();
  }
  hover_tile = NULL;
}

/**********************************************************************//**
  Called only by client_game_free() in client/client_main.c
**************************************************************************/
void control_free(void)
{
  int i;

  unit_list_destroy(current_focus);
  current_focus = NULL;
  unit_list_destroy(previous_focus);
  previous_focus = NULL;
  unit_list_destroy(urgent_focus_queue);
  urgent_focus_queue = NULL;

  for (i = 0; i < MAX_NUM_BATTLEGROUPS; i++) {
    unit_list_destroy(battlegroups[i]);
    battlegroups[i] = NULL;
  }

  clear_hover_state();
  free_client_goto();
}

/**********************************************************************//**
  Returns list of units currently in focus.
**************************************************************************/
struct unit_list *get_units_in_focus(void)
{
  return current_focus;
}

/**********************************************************************//**
  Return the number of units currently in focus (0 or more).
**************************************************************************/
int get_num_units_in_focus(void)
{
  return (NULL != current_focus ? unit_list_size(current_focus) : 0);
}

/**********************************************************************//**
  Store the focus unit(s).  This is used so that we can return to the
  previously focused unit with an appropriate keypress.
**************************************************************************/
static void store_previous_focus(void)
{
  if (get_num_units_in_focus() > 0) {
    unit_list_clear(previous_focus);
    unit_list_iterate(get_units_in_focus(), punit) {
      unit_list_append(previous_focus, punit);
    } unit_list_iterate_end;
  }
}

/**********************************************************************//**
  Store a priority focus unit.
**************************************************************************/
void unit_focus_urgent(struct unit *punit)
{
  unit_list_append(urgent_focus_queue, punit);
}

/**********************************************************************//**
  Do various updates required when the set of units in focus changes.
**************************************************************************/
static void focus_units_changed(void)
{
  update_unit_info_label(get_units_in_focus());
  menus_update();
  /* Notify the GUI */
  real_focus_units_changed();
}

/**********************************************************************//**
  Called when a unit is killed; this removes it from the control lists.
**************************************************************************/
void control_unit_killed(struct unit *punit)
{
  int i;

  goto_unit_killed(punit);

  if (unit_is_in_focus(punit)
      && get_num_units_in_focus() == 1) {
    unit_focus_advance(FALSE);
  }

  unit_list_remove(get_units_in_focus(), punit);
  if (get_num_units_in_focus() < 1) {
    clear_hover_state();
  }

  unit_list_remove(previous_focus, punit);
  unit_list_remove(urgent_focus_queue, punit);

  for (i = 0; i < MAX_NUM_BATTLEGROUPS; i++) {
    unit_list_remove(battlegroups[i], punit);
  }

  focus_units_changed();
}

/**********************************************************************//**
  Change the battlegroup for this unit.
**************************************************************************/
void unit_change_battlegroup(struct unit *punit, int battlegroup)
{
  if (battlegroup < 0 || battlegroup >= MAX_NUM_BATTLEGROUPS) {
    battlegroup = BATTLEGROUP_NONE;
  }

  if (punit->battlegroup != battlegroup) {
    if (battlegroup != BATTLEGROUP_NONE) {
      unit_list_append(battlegroups[battlegroup], punit);
    }
    if (punit->battlegroup != BATTLEGROUP_NONE) {
      unit_list_remove(battlegroups[punit->battlegroup], punit);
    }
    punit->battlegroup = battlegroup;
  }
}

/**********************************************************************//**
  Call this on new units to enter them in the battlegroup lists.
**************************************************************************/
void unit_register_battlegroup(struct unit *punit)
{
  if (punit->battlegroup < 0 || punit->battlegroup >= MAX_NUM_BATTLEGROUPS) {
    punit->battlegroup = BATTLEGROUP_NONE;
  } else {
    unit_list_append(battlegroups[punit->battlegroup], punit);
  }
}

/**********************************************************************//**
  Enter the given hover state.

    activity => The connect activity (ACTIVITY_IRRIGATE, etc.)
    order => The last order (ORDER_PERFORM_ACTION, ORDER_LAST, etc.)
**************************************************************************/
void set_hover_state(struct unit_list *punits, enum cursor_hover_state state,
                     enum unit_activity activity,
                     struct extra_type *tgt,
                     int last_tgt,
                     int last_sub_tgt,
                     action_id action,
                     enum unit_orders order)
{
  fc_assert_ret((punits && unit_list_size(punits) > 0)
                || state == HOVER_NONE);
  fc_assert_ret(state == HOVER_CONNECT || activity == ACTIVITY_LAST);
  fc_assert_ret((state == HOVER_GOTO || state == HOVER_GOTO_SEL_TGT)
                || order == ORDER_LAST);
  fc_assert_ret((state == HOVER_GOTO || state == HOVER_GOTO_SEL_TGT)
                || action == ACTION_NONE);

  if (!((hover_state == HOVER_GOTO || hover_state == HOVER_GOTO_SEL_TGT)
        && (state == HOVER_GOTO || state == HOVER_GOTO_SEL_TGT))) {
    /* Exit goto unless this is a switch between goto states */
    exit_goto_state();
  }

  hover_state = state;
  connect_activity = activity;
  if (tgt) {
    connect_tgt = tgt;
  } else {
    connect_tgt = NULL;
  }
  goto_last_order = order;
  goto_last_action = action;
  goto_last_tgt = last_tgt;
  goto_last_sub_tgt = last_sub_tgt;
}

/**********************************************************************//**
  Clear current hover state (go to HOVER_NONE).
**************************************************************************/
void clear_hover_state(void)
{
  set_hover_state(NULL, HOVER_NONE,
                  ACTIVITY_LAST, NULL,
                  NO_TARGET, NO_TARGET, ACTION_NONE, ORDER_LAST);
}

/**********************************************************************//**
  Returns TRUE iff the client should ask the server about what actions a
  unit can perform.
**************************************************************************/
bool should_ask_server_for_actions(const struct unit *punit)
{
  return (punit->action_decision_want == ACT_DEC_ACTIVE
          /* The player is interested in getting a pop up for a mere
           * arrival. */
          || (punit->action_decision_want == ACT_DEC_PASSIVE
              && gui_options.popup_actor_arrival));
}

/**********************************************************************//**
  Returns TRUE iff it is OK to ask the server about what actions a unit
  can perform.
**************************************************************************/
static bool can_ask_server_for_actions(void)
{
  /* OK as long as no other unit already asked and aren't done yet. */
  return (action_selection_in_progress_for == IDENTITY_NUMBER_ZERO
          && action_selection_actor_unit() == IDENTITY_NUMBER_ZERO);
}

/**********************************************************************//**
  Ask the server about what actions punit may be able to perform against
  it's stored target tile.

  The server's reply will pop up the action selection dialog unless no
  alternatives exists.
**************************************************************************/
static void ask_server_for_actions(struct unit *punit)
{
  fc_assert_ret(punit);
  fc_assert_ret(punit->action_decision_tile);

  /* Only one action selection dialog at a time is supported. */
  fc_assert_msg(action_selection_in_progress_for == IDENTITY_NUMBER_ZERO,
                "Unit %d started action selection before unit %d was done",
                action_selection_in_progress_for, punit->id);
  action_selection_in_progress_for = punit->id;

  dsend_packet_unit_get_actions(&client.conn,
                                punit->id,
                                IDENTITY_NUMBER_ZERO,
                                tile_index(punit->action_decision_tile),
                                EXTRA_NONE,
                                REQEST_PLAYER_INITIATED);
}

/**********************************************************************//**
  Return TRUE iff this unit is in focus.
**************************************************************************/
bool unit_is_in_focus(const struct unit *punit)
{
  return unit_list_search(get_units_in_focus(), punit) != NULL;
}

/**********************************************************************//**
  Return TRUE iff a unit on this tile is in focus.
**************************************************************************/
struct unit *get_focus_unit_on_tile(const struct tile *ptile)
{
  unit_list_iterate(get_units_in_focus(), punit) {
    if (unit_tile(punit) == ptile) {
      return punit;
    }
  } unit_list_iterate_end;

  return NULL;
}

/**********************************************************************//**
  Return head of focus units list.
**************************************************************************/
struct unit *head_of_units_in_focus(void)
{
  return unit_list_get(current_focus, 0);
}

/**********************************************************************//**
  Finds a single focus unit that we can center on.  May return NULL.
**************************************************************************/
static struct tile *find_a_focus_unit_tile_to_center_on(void)
{
  struct unit *punit;

  if (NULL != (punit = get_focus_unit_on_tile(get_center_tile_mapcanvas()))) {
    return unit_tile(punit);
  } else if (get_num_units_in_focus() > 0) {
    return unit_tile(head_of_units_in_focus());
  } else {
    return NULL;
  }
}

/**********************************************************************//**
  Center on the focus unit, if off-screen and auto_center_on_unit is true.
**************************************************************************/
void auto_center_on_focus_unit(void)
{
  struct tile *ptile = find_a_focus_unit_tile_to_center_on();

  if (ptile && gui_options.auto_center_on_unit
      && !tile_visible_and_not_on_border_mapcanvas(ptile)) {
    center_tile_mapcanvas(ptile);
  }
}

/**********************************************************************//**
  Add unit to list of units currently in focus.
**************************************************************************/
static void current_focus_append(struct unit *punit)
{
  unit_list_append(current_focus, punit);

  punit->client.focus_status = FOCUS_AVAIL;
  refresh_unit_mapcanvas(punit, unit_tile(punit), TRUE, FALSE);

  if (should_ask_server_for_actions(punit)
      && can_ask_server_for_actions()) {
    ask_server_for_actions(punit);
  }

  if (gui_options.unit_selection_clears_orders) {
    clear_unit_orders(punit);
  }
}

/**********************************************************************//**
  Remove focus from unit.
**************************************************************************/
static void current_focus_remove(struct unit *punit)
{
  /* Close the action selection dialog if the actor unit lose focus. */
  if (action_selection_actor_unit() == punit->id) {
    action_selection_close();
  }

  unit_list_remove(current_focus, punit);
  refresh_unit_mapcanvas(punit, unit_tile(punit), TRUE, FALSE);
}

/**********************************************************************//**
  Clear all orders for the given unit.
**************************************************************************/
void clear_unit_orders(struct unit *punit)
{
  if (!punit) {
    return;
  }

  if (punit->activity != ACTIVITY_IDLE
      || punit->ssa_controller != SSA_NONE)  {
    punit->ssa_controller = SSA_NONE;
    refresh_unit_city_dialogs(punit);
    request_new_unit_activity(punit, ACTIVITY_IDLE);
  } else if (unit_has_orders(punit)) {
    /* Clear the focus unit's orders. */
    request_orders_cleared(punit);
  }
}

/**********************************************************************//**
  Sets the focus unit directly. The unit given will be given the
  focus; if NULL the focus will be cleared.

  This function is called for several reasons. Sometimes a fast-focus
  happens immediately as a result of a client action. Other times it
  happens because of a server-sent packet that wakes up a unit.
**************************************************************************/
void unit_focus_set(struct unit *punit)
{
  bool focus_changed = FALSE;

  if (NULL != punit
      && NULL != client.conn.playing
      && unit_owner(punit) != client.conn.playing) {
    /* Callers should make sure this never happens. */
    return;
  }

  /* FIXME: This won't work quite right; for instance activating a
   * battlegroup twice in a row will store the focus erroneously. The only
   * solution would be a set_units_focus() */
  if (!(get_num_units_in_focus() == 1
	&& punit == head_of_units_in_focus())) {
    store_previous_focus();
    focus_changed = TRUE;
  }

  /* Close the action selection dialog if the actor unit lose focus. */
  unit_list_iterate(current_focus, punit_old) {
    if (action_selection_actor_unit() == punit_old->id) {
      action_selection_close();
    }
  } unit_list_iterate_end;

  /* Redraw the old focus unit (to fix blinking or remove the selection
   * circle). */
  unit_list_iterate(current_focus, punit_old) {
    refresh_unit_mapcanvas(punit_old, unit_tile(punit_old), TRUE, FALSE);
  } unit_list_iterate_end;
  unit_list_clear(current_focus);

  if (!can_client_change_view()) {
    /* This function can be called to set the focus to NULL when
     * disconnecting.  In this case we don't want any other actions! */
    fc_assert(punit == NULL);
    return;
  }

  if (NULL != punit) {
    current_focus_append(punit);
    auto_center_on_focus_unit();
  }

  if (focus_changed) {
    clear_hover_state();
    focus_units_changed();
  }
}

/**********************************************************************//**
  Adds this unit to the list of units in focus.
**************************************************************************/
void unit_focus_add(struct unit *punit)
{
  if (NULL != punit
      && NULL != client.conn.playing
      && unit_owner(punit) != client.conn.playing) {
    /* Callers should make sure this never happens. */
    return;
  }

  if (NULL == punit || !can_client_change_view()) {
    return;
  }

  if (unit_is_in_focus(punit)) {
    return;
  }

  if (hover_state != HOVER_NONE) {
    /* Can't continue with current goto if set of focus units
     * change. Cancel it. */
    clear_hover_state();
  }

  current_focus_append(punit);
  focus_units_changed();
}

/**********************************************************************//**
  Removes this unit from the list of units in focus.
**************************************************************************/
void unit_focus_remove(struct unit *punit)
{
  bool keep_in_focus = FALSE;

  if (NULL != punit
      && NULL != client.conn.playing
      && unit_owner(punit) != client.conn.playing) {
    /* Callers should make sure this never happens. */
    return;
  }

  if (NULL == punit || !can_client_change_view()) {
    return;
  }

  if (!unit_is_in_focus(punit)) {
    return;
  }

  if (hover_state != HOVER_NONE) {
    /* Can't continue with current goto if set of focus units
     * change. Cancel it. */
    clear_hover_state();
  }

  if (get_num_units_in_focus() == 1) {
    unit_focus_advance(TRUE);

    if (unit_is_in_focus(punit)) {
      /* Unit was restored to focus (there was no other units to focus to) */
      keep_in_focus = TRUE;
    }
  }

  if (!keep_in_focus) {
    current_focus_remove(punit);
    if (get_num_units_in_focus() > 0) {
      focus_units_changed();
    }
  }
}

/**********************************************************************//**
  The only difference is that here we draw the "cross".
**************************************************************************/
void unit_focus_set_and_select(struct unit *punit)
{
  unit_focus_set(punit);
  if (punit) {
    put_cross_overlay_tile(unit_tile(punit));
  }
}

/**********************************************************************//**
  Find the nearest available unit for focus, excluding any current unit
  in focus unless "accept_current" is TRUE.  If the current focus unit
  is the only possible unit, or if there is no possible unit, returns NULL.
**************************************************************************/
static struct unit *find_best_focus_candidate(bool accept_current)
{
  struct tile *ptile = get_center_tile_mapcanvas();

  if (!get_focus_unit_on_tile(ptile)) {
    struct unit *pfirst = head_of_units_in_focus();

    if (pfirst) {
      ptile = unit_tile(pfirst);
    }
  }

  iterate_outward(&(wld.map), ptile, FC_INFINITY, ptile2) {
    unit_list_iterate(ptile2->units, punit) {
      if ((!unit_is_in_focus(punit) || accept_current)
          && unit_owner(punit) == client.conn.playing
          && punit->client.focus_status == FOCUS_AVAIL
          && punit->activity == ACTIVITY_IDLE
          && !unit_has_orders(punit)
          && (punit->moves_left > 0 || unit_type_get(punit)->move_rate == 0)
          && !punit->done_moving
          && punit->ssa_controller == SSA_NONE) {
        return punit;
      }
    } unit_list_iterate_end;
  } iterate_outward_end;

  return NULL;
}

/**********************************************************************//**
  This function may be called from packhand.c, via unit_focus_update(),
  as a result of packets indicating change in activity for a unit. Also
  called when user press the "Wait" command.
 
  FIXME: Add feature to focus only units of a certain category.

  @param accept_current The current focus can be kept if no other candidates
**************************************************************************/
void unit_focus_advance(bool accept_current)
{
  struct unit *candidate = NULL;
  const int num_units_in_old_focus = get_num_units_in_focus();

  if (NULL == client.conn.playing
      || !is_player_phase(client.conn.playing, game.info.phase)
      || !can_client_change_view()) {
    unit_focus_set(NULL);
    return;
  }

  clear_hover_state();

  unit_list_iterate(get_units_in_focus(), punit) {
    /* 
     * Is the unit which just lost focus a non-AI unit? If yes this
     * enables the auto end turn.
     */
    if (punit->ssa_controller == SSA_NONE) {
      non_ai_unit_focus = TRUE;
      break;
    }
  } unit_list_iterate_end;

  if (unit_list_size(urgent_focus_queue) > 0) {
    /* Try top of the urgent list. */
    struct tile *focus_tile = (get_num_units_in_focus() > 0
                               ? unit_tile(head_of_units_in_focus())
                               : NULL);

    unit_list_iterate_safe(urgent_focus_queue, punit) {
      if ((ACTIVITY_IDLE != punit->activity
           || unit_has_orders(punit))
          /* This isn't an action decision needed because of an
           * ORDER_ACTION_MOVE located in the middle of an order. */
          && !should_ask_server_for_actions(punit)) {
        /* We have assigned new orders to this unit since, remove it. */
        unit_list_remove(urgent_focus_queue, punit);
      } else if (NULL == focus_tile
                 || focus_tile == unit_tile(punit)) {
        /* Use the first one found */
        candidate = punit;
        break;
      } else if (NULL == candidate) {
        candidate = punit;
      }
    } unit_list_iterate_safe_end;

    if (NULL != candidate) {
      unit_list_remove(urgent_focus_queue, candidate);

      /* Autocenter on Wakeup, regardless of the local option
       * "auto_center_on_unit". */
      if (!tile_visible_and_not_on_border_mapcanvas(unit_tile(candidate))) {
        center_tile_mapcanvas(unit_tile(candidate));
      }
    }
  }

  if (NULL == candidate) {
    candidate = find_best_focus_candidate(FALSE);

    if (!candidate) {
      /* Try for "waiting" units. */
      unit_list_iterate(client.conn.playing->units, punit) {
        if (punit->client.focus_status == FOCUS_WAIT) {
          punit->client.focus_status = FOCUS_AVAIL;
        }
      } unit_list_iterate_end;
      candidate = find_best_focus_candidate(FALSE);

      if (!candidate && accept_current) {
        /* Accept current focus unit as last resort. */
        candidate = find_best_focus_candidate(TRUE);
      }
    }
  }

  unit_focus_set(candidate);

  /* 
   * Handle auto-turn-done mode: If a unit was in focus (did move),
   * but now none are (no more to move) and there was at least one
   * non-AI unit this turn which was focused, then fake a Turn Done
   * keypress.
   */
  if (gui_options.auto_turn_done
      && num_units_in_old_focus > 0
      && get_num_units_in_focus() == 0
      && non_ai_unit_focus) {
    key_end_turn();
  }
}

/**********************************************************************//**
  If there is no unit currently in focus, or if the current unit in
  focus should not be in focus, then get a new focus unit.
  We let GOTO-ing units stay in focus, so that if they have moves left
  at the end of the goto, then they are still in focus.
**************************************************************************/
void unit_focus_update(void)
{
  if (NULL == client.conn.playing || !can_client_change_view()) {
    return;
  }

  if (!can_ask_server_for_actions()) {
    fc_assert(get_num_units_in_focus() > 0);

    /* An actor unit is asking the player what to do. Don't change the
     * focus. */
    return;
  }

  /* iterate zero times for no units in focus,
   * otherwise quit for any of the conditions. */
  unit_list_iterate(get_units_in_focus(), punit) {
    if ((punit->activity == ACTIVITY_IDLE
	 || punit->activity == ACTIVITY_GOTO
	 || unit_has_orders(punit))
	&& punit->moves_left > 0 
	&& !punit->done_moving
        && punit->ssa_controller == SSA_NONE) {
      return;
    }
  } unit_list_iterate_end;

  unit_focus_advance(TRUE);
}

/**********************************************************************//**
  Return a pointer to a visible unit, if there is one.
**************************************************************************/
struct unit *find_visible_unit(struct tile *ptile)
{
  struct unit *panyowned = NULL, *panyother = NULL, *ptptother = NULL;

  /* If no units here, return nothing. */
  if (unit_list_size(ptile->units) == 0) {
    return NULL;
  }

  /* If a unit is attacking we should show that on top */
  if (punit_attacking && same_pos(unit_tile(punit_attacking), ptile)) {
    unit_list_iterate(ptile->units, punit) {
      if (punit == punit_attacking) {
        return punit;
      }
    } unit_list_iterate_end;
  }

  /* If a unit is defending we should show that on top */
  if (punit_defending && same_pos(unit_tile(punit_defending), ptile)) {
    unit_list_iterate(ptile->units, punit) {
      if (punit == punit_defending) {
        return punit;
      }
    } unit_list_iterate_end;
  }

  /* If the unit in focus is at this tile, show that on top */
  unit_list_iterate(get_units_in_focus(), punit) {
    if (punit != punit_moving && unit_tile(punit) == ptile) {
      return punit;
    }
  } unit_list_iterate_end;

  /* If a city is here, return nothing (unit hidden by city). */
  if (tile_city(ptile)) {
    return NULL;
  }

  /* Iterate through the units to find the best one we prioritize this way:
       1: owned transporter.
       2: any owned unit
       3: any transporter
       4: any unit
     (always return first in stack). */
  unit_list_iterate(ptile->units, punit)
    if (unit_owner(punit) == client.conn.playing) {
      if (!unit_transported(punit)) {
        if (get_transporter_capacity(punit) > 0) {
	  return punit;
        } else if (!panyowned) {
	  panyowned = punit;
        }
      }
    } else if (!ptptother && !unit_transported(punit)) {
      if (get_transporter_capacity(punit) > 0) {
	ptptother = punit;
      } else if (!panyother) {
	panyother = punit;
      }
    }
  unit_list_iterate_end;

  return (panyowned ? panyowned : (ptptother ? ptptother : panyother));
}

/**********************************************************************//**
  Blink the active unit (if necessary). Return the time until the next
  blink (in seconds).
**************************************************************************/
double blink_active_unit(void)
{
  static struct timer *blink_timer = NULL;
  const double blink_time = get_focus_unit_toggle_timeout(tileset);

  if (get_num_units_in_focus() > 0) {
    if (!blink_timer || timer_read_seconds(blink_timer) > blink_time) {
      toggle_focus_unit_state(tileset);

      /* If we lag, we don't try to catch up.  Instead we just start a
       * new blink_time on every update. */
      blink_timer = timer_renew(blink_timer, TIMER_USER, TIMER_ACTIVE,
                                blink_timer != NULL ? NULL : "blink");
      timer_start(blink_timer);

      unit_list_iterate(get_units_in_focus(), punit) {
        /* We used to unqueue here, but that's inherently risky
         * for a function run from a timer - the UI can be in any
         * inconsistent state. */
	refresh_unit_mapcanvas(punit, unit_tile(punit), FALSE, FALSE);
      } unit_list_iterate_end;
    }

    return blink_time - timer_read_seconds(blink_timer);
  }

  return blink_time;
}

/**********************************************************************//**
  Blink the turn done button (if necessary).  Return the time until the next
  blink (in seconds).
**************************************************************************/
double blink_turn_done_button(void)
{
  static struct timer *blink_timer = NULL;
  const double blink_time = 0.5; /* half-second blink interval */

  if (NULL != client.conn.playing
      && client.conn.playing->is_alive
      && !client.conn.playing->phase_done
      && is_player_phase(client.conn.playing, game.info.phase)) {
    if (!blink_timer || timer_read_seconds(blink_timer) > blink_time) {
      int is_waiting = 0, is_moving = 0;
      bool blocking_mode;
      struct option *opt;

      opt = optset_option_by_name(server_optset, "turnblock");
      if (opt != NULL) {
        blocking_mode = option_bool_get(opt);
      } else {
        blocking_mode = FALSE;
      }

      players_iterate_alive(pplayer) {
        if ((pplayer->is_connected || blocking_mode)
            && is_player_phase(pplayer, game.info.phase)) {
          if (pplayer->phase_done) {
            is_waiting++;
          } else {
            is_moving++;
          }
        }
      } players_iterate_alive_end;

      if (is_moving == 1 && is_waiting > 0) {
	update_turn_done_button(FALSE);	/* stress the slow player! */
      }
      blink_timer = timer_renew(blink_timer, TIMER_USER, TIMER_ACTIVE,
                                blink_timer != NULL ? NULL : "blink");
      timer_start(blink_timer);
    }
    return blink_time - timer_read_seconds(blink_timer);
  }

  return blink_time;
}

/**********************************************************************//**
  Update unit icons (and arrow) in the information display, for specified
  punit as the active unit and other units on the same square.  In practice
  punit is almost always (or maybe strictly always?) the focus unit.
  
  Static vars store some info on current (ie previous) state, to avoid
  unnecessary redraws; initialise to "flag" values to always redraw first
  time.  In principle we _might_ need more info (eg ai.control, connecting),
  but in practice this is enough?

  Used to store unit_ids for below units, to use for callbacks (now done
  inside gui-dep set_unit_icon()), but even with ids here they would not
  be enough information to know whether to redraw -- instead redraw every
  time.  (Could store enough info to know, but is it worth it?)
**************************************************************************/
void update_unit_pix_label(struct unit_list *punitlist)
{
  int i;

  /* Check for any change in the unit's state.  This assumes that a unit's
   * orders cannot be changed directly but must be removed and then reset. */
  if (punitlist && unit_list_size(punitlist) > 0
      && C_S_OVER != client_state()) {
    /* There used to be a complicated and bug-prone check here to see if
     * the unit had actually changed.  This was misguided since the stacked
     * units (below) are redrawn in any case.  Unless we write a general
     * system for unit updates here we might as well just redraw it every
     * time. */
    struct unit *punit = unit_list_get(punitlist, 0);

    set_unit_icon(-1, punit);

    i = 0;			/* index into unit_below_canvas */
    unit_list_iterate(unit_tile(punit)->units, aunit) {
      if (aunit != punit) {
	if (i < num_units_below) {
	  set_unit_icon(i, aunit);
	}
	i++;
      }
    }
    unit_list_iterate_end;
    
    if (i > num_units_below) {
      set_unit_icons_more_arrow(TRUE);
    } else {
      set_unit_icons_more_arrow(FALSE);
      for (; i < num_units_below; i++) {
	set_unit_icon(i, NULL);
      }
    }
  } else {
    for (i = -1; i < num_units_below; i++) {
      set_unit_icon(i, NULL);
    }
    set_unit_icons_more_arrow(FALSE);
  }
}

/**********************************************************************//**
  Adjusts way combatants are displayed suitable for combat.
**************************************************************************/
void set_units_in_combat(struct unit *pattacker, struct unit *pdefender)
{
  punit_attacking = pattacker;
  punit_defending = pdefender;

  if (unit_is_in_focus(punit_attacking)
      || unit_is_in_focus(punit_defending)) {
    /* If one of the units is the focus unit, make sure hidden-focus is
     * disabled.  We don't just do this as a check later because then
     * with a blinking unit it would just disappear again right after the
     * battle. */
    focus_unit_in_combat(tileset);
  }
}

/**********************************************************************//**
  The action selection process is no longer in progress for the specified
  unit. It is safe to let another unit enter action selection.
**************************************************************************/
void action_selection_no_longer_in_progress(const int old_actor_id)
{
  struct unit *old_actor_unit;

  /* IDENTITY_NUMBER_ZERO is accepted for cases where the unit is gone
   * without a trace. */
  fc_assert_msg(old_actor_id == action_selection_in_progress_for
                || old_actor_id == IDENTITY_NUMBER_ZERO
                || action_selection_in_progress_for == IDENTITY_NUMBER_ZERO,
                "Decision taken for %d but selection is for %d.",
                old_actor_id, action_selection_in_progress_for);

  old_actor_unit = game_unit_by_number(old_actor_id);
  if (old_actor_unit != NULL
      && old_actor_unit->client.act_prob_cache != NULL) {
    FC_FREE(old_actor_unit->client.act_prob_cache);
  }

  /* Stop objecting to allowing the next unit to ask. */
  action_selection_in_progress_for = IDENTITY_NUMBER_ZERO;

  /* Clean up any client specific assumptions. */
  action_selection_no_longer_in_progress_gui_specific(old_actor_id);
}

/**********************************************************************//**
  Have the server record that a decision no longer is wanted for the
  specified unit.
**************************************************************************/
void action_decision_clear_want(const int old_actor_id)
{
  if (game_unit_by_number(old_actor_id) != NULL) {
    /* Have the server record that a decision no longer is wanted. */
    dsend_packet_unit_sscs_set(&client.conn, old_actor_id,
                               USSDT_UNQUEUE, IDENTITY_NUMBER_ZERO);
  }
}

/**********************************************************************//**
  Move on to the next unit in focus that needs an action decision.
**************************************************************************/
void action_selection_next_in_focus(const int old_actor_id)
{
  struct unit *old;

  old = game_unit_by_number(old_actor_id);

  /* Go to the next unit in focus that needs a decision. */
  unit_list_iterate(get_units_in_focus(), funit) {
    if (old != funit && should_ask_server_for_actions(funit)) {
      ask_server_for_actions(funit);
      return;
    }
  } unit_list_iterate_end;
}

/**********************************************************************//**
  Request that the player makes a decision for the specified unit.
**************************************************************************/
void action_decision_request(struct unit *actor_unit)
{
  fc_assert_ret(actor_unit);
  fc_assert_ret(actor_unit->action_decision_tile);

  if (!unit_is_in_focus(actor_unit)) {
    /* Getting feed back may be urgent. A unit standing next to an enemy
     * could be killed while waiting. */
    unit_focus_urgent(actor_unit);
  } else if (can_client_issue_orders()
             && can_ask_server_for_actions()) {
    /* No need to wait. The actor unit is in focus. No other actor unit
     * is currently asking about action selection. */
    ask_server_for_actions(actor_unit);
  }
}

/**********************************************************************//**
  Do a goto with an order at the end (or ORDER_LAST).
**************************************************************************/
void request_unit_goto(enum unit_orders last_order,
                       action_id act_id, int sub_tgt_id)
{
  struct unit_list *punits = get_units_in_focus();

  fc_assert_ret(act_id == ACTION_NONE
                || last_order == ORDER_PERFORM_ACTION);

  if (unit_list_size(punits) == 0) {
    return;
  }

  if (last_order == ORDER_PERFORM_ACTION) {
    /* An action has been specified. */
    fc_assert_ret(action_id_exists(act_id));

    unit_list_iterate(punits, punit) {
      if (!unit_can_do_action(punit, act_id)) {
        /* This unit can't perform the action specified in the last
         * order. */

        struct astring astr = ASTRING_INIT;

        if (role_units_translations(&astr,
                                    action_id_get_role(act_id),
                                    TRUE)) {
          /* ...but other units can perform it. */

          create_event(unit_tile(punit), E_BAD_COMMAND, ftc_client,
                        /* TRANS: Only Nuclear or ICBM can do Explode
                         * Nuclear. */
                       _("Only %s can do %s."),
                       astr_str(&astr),
                       action_id_name_translation(act_id));

          astr_free(&astr);
        } else {
          create_event(unit_tile(punit), E_BAD_COMMAND, ftc_client,
                       /* TRANS: Spy can't do Explode Nuclear. */
                       _("%s can't do %s."),
                       unit_name_translation(punit),
                       action_id_name_translation(act_id));
        }

        return;
      }
    } unit_list_iterate_end;
  }

  if (hover_state != HOVER_GOTO && hover_state != HOVER_GOTO_SEL_TGT) {
    set_hover_state(punits, HOVER_GOTO, ACTIVITY_LAST, NULL,
                    NO_TARGET, sub_tgt_id, act_id, last_order);
    enter_goto_state(punits);
    create_line_at_mouse_pos();
    update_unit_info_label(punits);
    control_mouse_cursor(NULL);
  } else {
    fc_assert_ret(goto_is_active());
    /* Adding a long range action in the middle isn't handled yet */
    fc_assert_ret(hover_state != HOVER_GOTO_SEL_TGT);
    goto_add_waypoint();
  }
}

/**********************************************************************//**
  Return TRUE if at least one of the units can do an attack at the tile.
**************************************************************************/
static bool can_units_attack_at(struct unit_list *punits,
                                const struct tile *ptile)
{
  unit_list_iterate(punits, punit) {
    if (is_attack_unit(punit)
        && can_unit_attack_tile(punit, NULL, ptile)) {
      return TRUE;
    }
  } unit_list_iterate_end;

  return FALSE;
}

/**********************************************************************//**
  Determines which mouse cursor should be used, according to hover_state,
  and the information gathered from the tile which is under the mouse
  cursor (ptile).
**************************************************************************/
void control_mouse_cursor(struct tile *ptile)
{
  struct unit *punit = NULL;
  struct city *pcity = NULL;
  struct unit_list *active_units = get_units_in_focus();
  enum cursor_type mouse_cursor_type = CURSOR_DEFAULT;

  if (!gui_options.enable_cursor_changes) {
    return;
  }

  if (C_S_RUNNING != client_state()) {
    update_mouse_cursor(CURSOR_DEFAULT);
    return;
  }

  if (is_server_busy()) {
    /* Server will not accept any commands. */
    update_mouse_cursor(CURSOR_WAIT);
    return;
  }

  if (!ptile) {
    if (hover_tile) {
      /* hover_tile is the tile that was previously under the mouse cursor. */
      ptile = hover_tile;
    } else {
      update_mouse_cursor(CURSOR_DEFAULT);
      return;
    }
  } else {
    hover_tile = ptile;
  }

  punit = find_visible_unit(ptile);
  pcity = ptile ? tile_city(ptile) : NULL;

  switch (hover_state) {
  case HOVER_NONE:
    if (NULL != punit
        && unit_owner(punit) == client_player()) {
      /* Set mouse cursor to select a unit.  */
      mouse_cursor_type = CURSOR_SELECT;
    } else if (NULL != pcity
	       && can_player_see_city_internals(client.conn.playing, pcity)) {
      /* Set mouse cursor to select a city. */
      mouse_cursor_type = CURSOR_SELECT;
    } else {
      /* Set default mouse cursor, because nothing selectable found. */
    }
    break;
  case HOVER_GOTO:
    /* Determine if the goto is valid, invalid, nuke or will attack. */
    if (is_valid_goto_destination(ptile)) {
      if (action_id_has_result_safe(goto_last_action, ACTRES_NUKE_UNITS)
          || action_id_has_result_safe(goto_last_action, ACTRES_NUKE)) {
        /* Goto results in nuclear attack. */
        mouse_cursor_type = CURSOR_NUKE;
      } else if (can_units_attack_at(active_units, ptile)) {
        /* Goto results in military attack. */
	mouse_cursor_type = CURSOR_ATTACK;
      } else if (is_enemy_city_tile(ptile, client.conn.playing)) {
        /* Goto results in attack of enemy city. */
	mouse_cursor_type = CURSOR_ATTACK;
      } else {
	mouse_cursor_type = CURSOR_GOTO;
      }
    } else {
      mouse_cursor_type = CURSOR_INVALID;
    }
    break;
  case HOVER_PATROL:
    if (is_valid_goto_destination(ptile)) {
      mouse_cursor_type = CURSOR_PATROL;
    } else {
      mouse_cursor_type = CURSOR_INVALID;
    }
    break;
  case HOVER_CONNECT:
    if (is_valid_goto_destination(ptile)) {
      mouse_cursor_type = CURSOR_GOTO;
    } else {
      mouse_cursor_type = CURSOR_INVALID;
    }
    break;
  case HOVER_TELEPORT:
    /* FIXME: check for invalid tiles. */
    mouse_cursor_type = CURSOR_TELEPORT;
    break;
  case HOVER_PARADROP:
    /* FIXME: check for invalid tiles. */
    mouse_cursor_type = CURSOR_PARADROP;
    break;
  case HOVER_ACT_SEL_TGT:
  case HOVER_GOTO_SEL_TGT:
    /* Select a tile to target / find targets on. */
    mouse_cursor_type = CURSOR_SELECT;
    break;
  };

  update_mouse_cursor(mouse_cursor_type);
}

/**********************************************************************//**
  Return TRUE if there are any units doing the activity on the tile.
**************************************************************************/
static bool is_activity_on_tile(struct tile *ptile,
                                enum unit_activity activity)
{
  unit_list_iterate(ptile->units, punit) {
    if (punit->activity == activity) {
      return TRUE;
    }
  } unit_list_iterate_end;

  return FALSE;
}

/**********************************************************************//**
  Fill orders to build recursive roads. This modifies ptile, so virtual
  copy of the real tile should be passed.
**************************************************************************/
int check_recursive_road_connect(struct tile *ptile,
                                 const struct extra_type *pextra,
                                 const struct unit *punit,
                                 const struct player *pplayer, int rec)
{
  int activity_mc = 0;
  struct terrain *pterrain = tile_terrain(ptile);
  const struct civ_map *nmap = &(wld.map);

  if (rec > MAX_EXTRA_TYPES) {
    return -1;
  }

  if (!is_extra_caused_by(pextra, EC_ROAD)) {
    return -1;
  }

  extra_deps_iterate(&(pextra->reqs), pdep) {
    if (!tile_has_extra(ptile, pdep)) {
      int single_mc;

      single_mc = check_recursive_road_connect(ptile, pdep, punit,
                                               pplayer, rec + 1);

      if (single_mc < 0) {
        return -1;
      }

      activity_mc += single_mc;
    }
  } extra_deps_iterate_end;

  /* Can build road after that? */
  if (punit != NULL) {
    if (!can_build_road(nmap, extra_road_get(pextra), punit, ptile)) {
      return -1;
    }
  } else if (pplayer != NULL) {
    if (!player_can_build_road(nmap, extra_road_get(pextra),
                               pplayer, ptile)) {
      return -1;
    }
  }

  tile_add_extra(ptile, pextra);

  activity_mc += terrain_extra_build_time(pterrain, ACTIVITY_GEN_ROAD, pextra);

  return activity_mc;
}

/*******************************************************************//**
  Can tile be irrigated by given unit? Unit can be NULL to check if
  any settler type unit of any player can irrigate.
***********************************************************************/
static bool can_be_irrigated(const struct tile *ptile,
                             const struct unit *punit)
{
  struct terrain* pterrain = tile_terrain(ptile);
  struct universal for_unit = { .kind = VUT_UTYPE,
                                .value.utype = unit_type_get(punit)};
  struct universal for_tile = { .kind = VUT_TERRAIN,
                                .value.terrain = tile_terrain(ptile)};

  if (T_UNKNOWN == pterrain) {
    return FALSE;
  }

  return action_id_univs_not_blocking(ACTION_IRRIGATE,
                                      &for_unit, &for_tile);
}

/**********************************************************************//**
  Return whether the unit can connect with given activity (or with
  any activity if activity arg is set to ACTIVITY_IDLE)

  This function is client-specific.
**************************************************************************/
bool can_unit_do_connect(struct unit *punit,
                         enum unit_activity activity,
                         struct extra_type *tgt) 
{
  struct tile *ptile = unit_tile(punit);
  struct road_type *proad = NULL;
  const struct req_context unit_ctxt = {
    .unit = punit,
    .unittype = unit_type_get(punit),
  };

  /* HACK: This code duplicates that in
   * can_unit_do_activity_targeted_at(). The general logic here is that
   * the connect is allowed if both:
   * (1) the unit can do that activity type, in general
   * (2) either
   *     (a) the activity has already been completed at this tile
   *     (b) it can be done by the unit at this tile. */
  switch (activity) {
  case ACTIVITY_GEN_ROAD:
    {
      struct tile *vtile;
      int build_time;

      fc_assert(is_extra_caused_by(tgt, EC_ROAD));

      proad = extra_road_get(tgt);

      if (tile_has_road(ptile, proad)) {
        /* This tile has road, can unit build road to other tiles too? */
        return are_reqs_active(&unit_ctxt, NULL, &tgt->reqs, RPT_POSSIBLE);
      }

      /* To start connect, unit must be able to build road to this
       * particular tile. */
      vtile = tile_virtual_new(ptile);
      build_time = check_recursive_road_connect(vtile, tgt, punit, NULL, 0);
      tile_virtual_destroy(vtile);

      return build_time >= 0;
    }

  case ACTIVITY_IRRIGATE:
    /* Special case for irrigation: only irrigate to make S_IRRIGATION,
     * never to transform tiles. */
    if (!unit_has_type_flag(punit, UTYF_SETTLERS)) {
      return FALSE;
    }
    if (tile_has_extra(ptile, tgt)) {
      return are_reqs_active(&unit_ctxt, NULL, &tgt->reqs, RPT_POSSIBLE);
    }

    return can_be_irrigated(ptile, punit)
      && can_build_extra(tgt, punit, ptile)
      && !is_activity_on_tile(ptile,
                              ACTIVITY_MINE);
  default:
    break;
  }

  return FALSE;
}

/**********************************************************************//**
  Prompt player for entering destination point for unit connect
  (e.g. connecting with roads)
**************************************************************************/
void request_unit_connect(enum unit_activity activity,
                          struct extra_type *tgt)
{
  struct unit_list *punits = get_units_in_focus();

  if (!can_units_do_connect(punits, activity, tgt)) {
    return;
  }

  if (hover_state != HOVER_CONNECT || connect_activity != activity
      || (connect_tgt != tgt
          && (activity == ACTIVITY_GEN_ROAD
              || activity == ACTIVITY_IRRIGATE))) {
    set_hover_state(punits, HOVER_CONNECT,
                    activity, tgt, NO_TARGET, NO_TARGET,
                    ACTION_NONE, ORDER_LAST);
    enter_goto_state(punits);
    create_line_at_mouse_pos();
    update_unit_info_label(punits);
    control_mouse_cursor(NULL);
  } else {
    fc_assert_ret(goto_is_active());
    goto_add_waypoint();
  }
}

/**********************************************************************//**
  Returns one of the unit of the transporter which can have focus next.
**************************************************************************/
struct unit *request_unit_unload_all(struct unit *punit)
{
  struct tile *ptile = unit_tile(punit);
  struct unit *plast = NULL;

  if (get_transporter_capacity(punit) == 0) {
    create_event(unit_tile(punit), E_BAD_COMMAND, ftc_client,
                 _("Only transporter units can be unloaded."));
    return NULL;
  }

  unit_list_iterate(ptile->units, pcargo) {
    if (unit_transport_get(pcargo) == punit) {
      request_unit_unload(pcargo);

      if (pcargo->activity == ACTIVITY_SENTRY) {
        dsend_packet_unit_sscs_set(&client.conn, pcargo->id,
                                   USSDT_SENTRY, 0);
      }

      if (unit_owner(pcargo) == unit_owner(punit)) {
	plast = pcargo;
      }
    }
  } unit_list_iterate_end;

  return plast;
}

/**********************************************************************//**
  Send unit airlift request to server.
**************************************************************************/
void request_unit_airlift(struct unit *punit, struct city *pcity)
{
  request_do_action(ACTION_AIRLIFT, punit->id, pcity->id, 0, "");
}

/**********************************************************************//**
  Return-and-recover for a particular unit.  This sets the unit to GOTO
  the nearest city.
**************************************************************************/
void request_unit_return(struct unit *punit)
{
  struct pf_path *path;

  if ((path = path_to_nearest_allied_city(punit))) {
    int turns = pf_path_last_position(path)->turn;
    int max_hp = unit_type_get(punit)->hp;

    if (punit->hp + turns *
        (get_unit_bonus(punit, EFT_UNIT_RECOVER)
         - (max_hp * unit_class_get(punit)->hp_loss_pct / 100))
	< max_hp) {
      struct unit_order order;

      order.order = ORDER_ACTIVITY;
      order.dir = DIR8_ORIGIN;
      order.activity = ACTIVITY_SENTRY;
      order.target = NO_TARGET;
      order.sub_target = NO_TARGET;
      order.action = ACTION_NONE;
      send_goto_path(punit, path, &order);
    } else {
      send_goto_path(punit, path, NULL);
    }
    pf_path_destroy(path);
  }
}

/**********************************************************************//**
  Wakes all owned sentried units on tile.
**************************************************************************/
void wakeup_sentried_units(struct tile *ptile)
{
  if (!can_client_issue_orders()) {
    return;
  }
  unit_list_iterate(ptile->units, punit) {
    if (punit->activity == ACTIVITY_SENTRY
	&& unit_owner(punit) == client.conn.playing) {
      request_new_unit_activity(punit, ACTIVITY_IDLE);
    }
  }
  unit_list_iterate_end;
}

/**********************************************************************//**
  (RP:) un-sentry all my own sentried units on punit's tile
**************************************************************************/
void request_unit_wakeup(struct unit *punit)
{
  wakeup_sentried_units(unit_tile(punit));
}

/**************************************************************************
  Defines specific hash tables needed for request_unit_select().
**************************************************************************/
#define SPECHASH_TAG unit_type
#define SPECHASH_IKEY_TYPE struct unit_type *
#define SPECHASH_IDATA_TYPE void *
#include "spechash.h"

#define SPECHASH_TAG continent
#define SPECHASH_INT_KEY_TYPE
#define SPECHASH_IDATA_TYPE void *
#include "spechash.h"

/**********************************************************************//**
  Select all units based on the given list of units and the selection modes.
**************************************************************************/
void request_unit_select(struct unit_list *punits,
                         enum unit_select_type_mode seltype,
                         enum unit_select_location_mode selloc)
{
  const struct player *pplayer;
  const struct tile *ptile;
  struct unit *punit_first;
  struct tile_hash *tile_table;
  struct unit_type_hash *type_table;
  struct continent_hash *cont_table;

  if (!can_client_change_view() || !punits
      || unit_list_size(punits) < 1) {
    return;
  }

  punit_first = unit_list_get(punits, 0);

  if (seltype == SELTYPE_SINGLE) {
    unit_focus_set(punit_first);
    return;
  }

  pplayer = unit_owner(punit_first);
  tile_table = tile_hash_new();
  type_table = unit_type_hash_new();
  cont_table = continent_hash_new();

  unit_list_iterate(punits, punit) {
    if (seltype == SELTYPE_SAME) {
      unit_type_hash_insert(type_table, unit_type_get(punit), NULL);
    }

    ptile = unit_tile(punit);
    if (selloc == SELLOC_TILE) {
      tile_hash_insert(tile_table, ptile, NULL);
    } else if (selloc == SELLOC_CONT) {
      continent_hash_insert(cont_table, tile_continent(ptile), NULL);
    }
  } unit_list_iterate_end;

  if (selloc == SELLOC_TILE) {
    tile_hash_iterate(tile_table, hash_tile) {
      unit_list_iterate(hash_tile->units, punit) {
        if (unit_owner(punit) != pplayer) {
          continue;
        }
        if (seltype == SELTYPE_SAME
            && !unit_type_hash_lookup(type_table, unit_type_get(punit), NULL)) {
          continue;
        }
        unit_focus_add(punit);
      } unit_list_iterate_end;
    } tile_hash_iterate_end;
  } else {
    unit_list_iterate(pplayer->units, punit) {
      ptile = unit_tile(punit);
      if ((seltype == SELTYPE_SAME
           && !unit_type_hash_lookup(type_table, unit_type_get(punit), NULL))
          || (selloc == SELLOC_CONT
              && !continent_hash_lookup(cont_table, tile_continent(ptile),
                                        NULL))) {
        continue;
      }

      unit_focus_add(punit);
    } unit_list_iterate_end;
  }

  tile_hash_destroy(tile_table);
  unit_type_hash_destroy(type_table);
  continent_hash_destroy(cont_table);
}

/**********************************************************************//**
  Return whether user should confirm the action. Buffer gets filled
  with explanation of the situation.
**************************************************************************/
static bool action_requires_confirmation(action_id act,
                                         char *buf, size_t bufsize)
{
  fc_assert(buf != NULL || bufsize == 0);

  if (bufsize > 0) {
    buf[0] = '\0';
  }

  if (act == ACTION_JOIN_CITY) {
    if (bufsize > 0) {
      fc_snprintf(buf, bufsize, _("Joining a city uses the unit"));
    }

    return TRUE;
  }

  return FALSE;
}

/**********************************************************************//**
  Request an actor unit to do a specific action.
  - action    : The action to be requested.
  - actor_id  : The unit ID of the actor unit.
  - target_id : The ID of the target unit, city or tile.
  - sub_tgt   : The sub target. Only some actions take a sub target. The
                sub target kind depends on the action. Example sub targets
                are the technology to steal from a city, the extra to
                pillage at a tile and the building to sabotage in a city.
  - name      : Used by ACTION_FOUND_CITY to specify city name.
**************************************************************************/
void request_do_action(action_id action, int actor_id,
                       int target_id, int sub_tgt, const char *name)
{
  char buf[400];

  if (action_requires_confirmation(action, buf, sizeof(buf))) {
    struct act_confirmation_data *data = fc_malloc(sizeof(struct act_confirmation_data));

    data->act = action;
    data->actor = actor_id;
    data->target = target_id;
    data->tgt_sub = sub_tgt;

    if (name != NULL) {
      data->name = fc_strdup(name);
    } else {
      data->name = NULL;
    }

    request_action_confirmation(buf, data);
  } else {
    struct unit *actor_unit = game_unit_by_number(actor_id);

    /* Giving an order takes back control. */
    request_unit_ssa_set(actor_unit, SSA_NONE);

    dsend_packet_unit_do_action(&client.conn,
                                actor_id, target_id, sub_tgt, name,
                                action);
  }
}

/**********************************************************************//**
  GUI (likely user) either confirmed the action, or not.
  Even if not, we have to free the data.
**************************************************************************/
void action_confirmation(struct act_confirmation_data *data, bool confirm)
{
  if (confirm) {
    struct unit *actor_unit = game_unit_by_number(data->actor);

    if (actor_unit != NULL) {
      /* Giving an order takes back control. */
      request_unit_ssa_set(actor_unit, SSA_NONE);

      dsend_packet_unit_do_action(&client.conn,
                                  data->actor,
                                  data->target,
                                  data->tgt_sub,
                                  data->name,
                                  data->act);
    }
  }

  if (data->name != NULL) {
    free(data->name);
  }

  free(data);
}

/**********************************************************************//**
  Request data for follow up questions about an action the unit can
  perform.
  - action : The action the follow up question is about.
  - actor_id : The unit ID of the acting unit.
  - target_id : The ID of the target unit or city.
**************************************************************************/
void request_action_details(action_id action, int actor_id,
                            int target_id)
{
  dsend_packet_unit_action_query(&client.conn,
                                 actor_id, target_id, action,
                                 /* Users that need the answer in the
                                  * background should send the packet them
                                  * self. At least for now. */
                                 REQEST_PLAYER_INITIATED);
}

/**********************************************************************//**
  Player pressed 'b' or otherwise instructed unit to build or add to city.
  If the unit can build a city, we popup the appropriate dialog.
  Otherwise, we just send a packet to the server.
  If this action is not appropriate, the server will respond
  with an appropriate message.  (This is to avoid duplicating
  all the server checks and messages here.)
**************************************************************************/
void request_unit_build_city(struct unit *punit)
{
  struct city *pcity;

  if ((pcity = tile_city(unit_tile(punit)))) {
    /* Try to join the city. */
    request_do_action(ACTION_JOIN_CITY, punit->id, pcity->id, 0, "");
  } else {
    /* The reply will trigger a dialog to name the new city. */
    dsend_packet_city_name_suggestion_req(&client.conn, punit->id);
  }
}

/**********************************************************************//**
  Order a unit to move to a neighboring tile without performing an action.

  Does nothing it the destination tile isn't next to the tile where the
  unit currently is located.
**************************************************************************/
void request_unit_non_action_move(struct unit *punit,
                                  struct tile *dest_tile)
{
  struct packet_unit_orders p;
  int dir;

  dir = get_direction_for_step(&(wld.map), unit_tile(punit), dest_tile);

  if (dir == -1) {
    /* The unit isn't located next to the destination tile. */
    return;
  }

  memset(&p, 0, sizeof(p));

  p.repeat = FALSE;
  p.vigilant = FALSE;

  p.unit_id = punit->id;
  p.src_tile = tile_index(unit_tile(punit));
  p.dest_tile = tile_index(dest_tile);

  p.length = 1;
  p.orders[0].order = ORDER_MOVE;
  p.orders[0].dir = dir;
  p.orders[0].activity = ACTIVITY_LAST;
  p.orders[0].target = NO_TARGET;
  p.orders[0].sub_target = NO_TARGET;
  p.orders[0].action = ACTION_NONE;

  request_unit_ssa_set(punit, SSA_NONE);
  send_packet_unit_orders(&client.conn, &p);
}

/**********************************************************************//**
  This function is called whenever the player pressed an arrow key.

  We do NOT take into account that punit might be a caravan or a diplomat
  trying to move into a city, or a diplomat going into a tile with a unit;
  the server will catch those cases and send the client a package to pop up
  a dialog. (the server code has to be there anyway as goto's are entirely
  in the server)
**************************************************************************/
void request_move_unit_direction(struct unit *punit, int dir)
{
  struct packet_unit_orders p;
  struct tile *dest_tile;

  /* Catches attempts to move off map */
  dest_tile = mapstep(&(wld.map), unit_tile(punit), dir);
  if (!dest_tile) {
    return;
  }

  if (!can_unit_exist_at_tile(&(wld.map), punit, dest_tile)) {
    if (request_transport(punit, dest_tile)) {
      return;
    }
  }

  /* The goto system isn't used to send the order because that would
   * prevent direction movement from overriding it.
   * Example of a situation when overriding the goto system is useful:
   * The goto system creates a longer path to make a move legal. The player
   * wishes to order the illegal move so the server will explain why the
   * short move is illegal. */

  memset(&p, 0, sizeof(p));

  p.repeat = FALSE;
  p.vigilant = FALSE;

  p.unit_id = punit->id;
  p.src_tile = tile_index(unit_tile(punit));
  p.dest_tile = tile_index(dest_tile);

  p.length = 1;
  p.orders[0].order = (gui_options.popup_last_move_to_allied
                       ? ORDER_ACTION_MOVE : ORDER_MOVE);
  p.orders[0].dir = dir;
  p.orders[0].activity = ACTIVITY_LAST;
  p.orders[0].target = NO_TARGET;
  p.orders[0].sub_target = NO_TARGET;
  p.orders[0].action = ACTION_NONE;

  request_unit_ssa_set(punit, SSA_NONE);
  send_packet_unit_orders(&client.conn, &p);
}

/**********************************************************************//**
  Send request for unit activity changing to server. If activity has
  target, use request_new_unit_activity_targeted() instead.
**************************************************************************/
void request_new_unit_activity(struct unit *punit, enum unit_activity act)
{
  request_new_unit_activity_targeted(punit, act, NULL);
}

/**********************************************************************//**
  Send request for unit activity changing to server. This is for
  activities that are targeted to certain special or base type.
**************************************************************************/
void request_new_unit_activity_targeted(struct unit *punit,
                                        enum unit_activity act,
                                        struct extra_type *tgt)
{
  if (!can_client_issue_orders()) {
    return;
  }

  /* Callers rely on this to take back control from server side agents. */
  request_unit_ssa_set(punit, SSA_NONE);

  if (tgt == NULL) {
    dsend_packet_unit_change_activity(&client.conn, punit->id, act, EXTRA_NONE);
  } else {
    dsend_packet_unit_change_activity(&client.conn, punit->id, act, extra_index(tgt));
  }
}

/**********************************************************************//**
  Destroy the client disband unit data.
**************************************************************************/
static void client_disband_unit_data_destroy(void *p)
{
  struct client_disband_unit_data *data = p;

  free(data);
}

/**********************************************************************//**
  Try to disband a unit using actions ordered by preference.
**************************************************************************/
static void do_disband_alternative(void *p)
{
  struct unit *punit;
  struct city *pcity;
  struct tile *ptile;
  int last_request_id_used;
  struct client_disband_unit_data *next;
  struct client_disband_unit_data *data = p;
  int act;
  const struct civ_map *nmap = &(wld.map);

  fc_assert_ret(can_client_issue_orders());

  /* Fetch the unit to get rid of. */
  punit = player_unit_by_number(client_player(), data->unit_id);

  if (punit == NULL) {
    /* Success! It is gone. */
    return;
  }

  if (data->alt == -1) {
    /* All alternatives have been tried. */
    create_event(unit_tile(punit), E_BAD_COMMAND, ftc_client,
                  /* TRANS: Unable to get rid of Leader. */
                 _("Unable to get rid of %s."),
                 unit_name_translation(punit));
    return;
  }

  act = disband_unit_alternatives[data->alt];

  /* Prepare the data for the next try in case this try fails. */
  next = fc_malloc(sizeof(struct client_disband_unit_data));
  next->unit_id = data->unit_id;
  next->alt = data->alt - 1;

  /* Latest request ID before trying to send a request. */
  last_request_id_used = client.conn.client.last_request_id_used;

  /* Send a request to the server unless it is known to be pointless. */
  switch (action_id_get_target_kind(act)) {
  case ATK_CITY:
    if ((pcity = tile_city(unit_tile(punit)))
        && action_prob_possible(action_prob_vs_city(nmap, punit,
                                                    act, pcity))) {
      request_do_action(act, punit->id, pcity->id, 0, "");
    }
    break;
  case ATK_UNIT:
    if (action_prob_possible(action_prob_vs_unit(nmap, punit, act, punit))) {
      request_do_action(act, punit->id, punit->id, 0, "");
    }
    break;
  case ATK_UNITS:
    if ((ptile = unit_tile(punit))
        && action_prob_possible(action_prob_vs_stack(nmap, punit, act, ptile))) {
      request_do_action(act, punit->id, ptile->index, 0, "");
    }
    break;
  case ATK_TILE:
    if ((ptile = unit_tile(punit))
        && action_prob_possible(action_prob_vs_tile(nmap, punit, act,
                                                    ptile, NULL))) {
      request_do_action(act, punit->id, ptile->index, 0, "");
    }
    break;
  case ATK_EXTRAS:
    if ((ptile = unit_tile(punit))
        && action_prob_possible(action_prob_vs_extras(nmap, punit, act,
                                                      ptile, NULL))) {
      request_do_action(act, punit->id, ptile->index, 0, "");
    }
    break;
  case ATK_SELF:
    if (action_prob_possible(action_prob_self(nmap, punit, act))) {
      request_do_action(act, punit->id, punit->id, 0, "");
    }
    break;
  case ATK_COUNT:
    fc_assert(action_id_get_target_kind(act) != ATK_COUNT);
    break;
  }

  if (last_request_id_used != client.conn.client.last_request_id_used) {
    /* A request was sent. */

    /* Check if it worked. Move on if it didn't. */
    update_queue_connect_processing_finished_full
        (client.conn.client.last_request_id_used,
         do_disband_alternative, next,
         client_disband_unit_data_destroy);
  } else {
    /* No request was sent. */

    /* Move on. */
    do_disband_alternative(next);

    /* Won't be freed by anyone else. */
    client_disband_unit_data_destroy(next);
  }
}

/**********************************************************************//**
  Send request to disband unit to server.
**************************************************************************/
void request_unit_disband(struct unit *punit)
{
  struct client_disband_unit_data *data;

  /* Set up disband data. Start at the end of the array. */
  data = fc_malloc(sizeof(struct client_disband_unit_data));
  data->unit_id = punit->id;
  data->alt = 2;

  /* Begin. */
  do_disband_alternative(data);

  /* Won't be freed by anyone else. */
  client_disband_unit_data_destroy(data);
}

/**********************************************************************//**
  Send request to change unit homecity to server.
**************************************************************************/
void request_unit_change_homecity(struct unit *punit)
{
  struct city *pcity = tile_city(unit_tile(punit));

  if (pcity) {
    request_do_action(ACTION_HOME_CITY, punit->id, pcity->id, 0, "");
  }
}

/**********************************************************************//**
  Send request to upgrade unit to server.
**************************************************************************/
void request_unit_upgrade(struct unit *punit)
{
  struct city *pcity = tile_city(unit_tile(punit));

  if (pcity) {
    request_do_action(ACTION_UPGRADE_UNIT, punit->id, pcity->id, 0, "");
  }
}

/**********************************************************************//**
  Sends unit convert packet.
**************************************************************************/
void request_unit_convert(struct unit *punit)
{
  request_new_unit_activity(punit, ACTIVITY_CONVERT);
}

/**********************************************************************//**
  Call to request (from the server) that the unit is put under the
  control of the specified server side agent or - if agent is SSA_NONE -
  under client control.
**************************************************************************/
void request_unit_ssa_set(const struct unit *punit,
                          enum server_side_agent agent)
{
  if (punit) {
    dsend_packet_unit_server_side_agent_set(&client.conn, punit->id,
                                            agent);
  }
}

/**********************************************************************//**
  Call to request (from the server) that the settler unit is put into
  autosettler mode.
**************************************************************************/
void request_unit_autosettlers(const struct unit *punit)
{
  if (punit && can_unit_do_autosettlers(punit)) {
    request_unit_ssa_set(punit, SSA_AUTOSETTLER);
  } else if (punit) {
    create_event(unit_tile(punit), E_BAD_COMMAND, ftc_client,
                 _("Only settler units can be put into auto mode."));
  }
}

/**********************************************************************//**
  Send a request to the server that the cargo be loaded into the transporter.

  If ptransporter is NULL a suitable transporter will be chosen.
**************************************************************************/
void request_unit_load(struct unit *pcargo, struct unit *ptrans,
                       struct tile *ptile)
{
  if (!ptrans) {
    ptrans = transporter_for_unit(pcargo);
  }

  if (ptrans
      && can_client_issue_orders()
      && could_unit_load(pcargo, ptrans)) {
    action_by_result_iterate(paction,
                             same_pos(unit_tile(pcargo), ptile)
                             ? ACTRES_TRANSPORT_BOARD
                             : ACTRES_TRANSPORT_EMBARK) {
      enum gen_action act_id = action_id(paction);

      if (action_prob_possible(action_prob_vs_unit(&(wld.map), pcargo, act_id,
                                                   ptrans))) {
        /* Try the first action that may be legal. */
        /* Implement something like do_disband_alternative() if a ruleset
         * appears where this isn't good enough. */
        request_do_action(act_id, pcargo->id, ptrans->id, 0, "");
        break;
      }
    } action_by_result_iterate_end;

    /* Sentry the unit. */
    /* FIXME: Should not sentry if above loading fails (transport moved away,
     *        or filled already in server side) */
    dsend_packet_unit_sscs_set(&client.conn, pcargo->id,
                               USSDT_SENTRY, 1);
  }
}

/**********************************************************************//**
  Send a request to the server that the cargo be unloaded from its current
  transporter.
**************************************************************************/
void request_unit_unload(struct unit *pcargo)
{
  struct unit *ptrans = unit_transport_get(pcargo);

  if (can_client_issue_orders()
      && ptrans != NULL
      && can_unit_unload(pcargo, ptrans)
      && can_unit_survive_at_tile(&(wld.map), pcargo, unit_tile(pcargo))) {
    if (unit_owner(pcargo) == client.conn.playing) {
      request_do_action(ACTION_TRANSPORT_DEBOARD,
                        pcargo->id, ptrans->id, 0, "");
    } else {
      request_do_action(ACTION_TRANSPORT_UNLOAD,
                        ptrans->id, pcargo->id, 0, "");
    }

    if (unit_owner(pcargo) == client.conn.playing
        && pcargo->activity == ACTIVITY_SENTRY) {
      /* Activate the unit. */
      dsend_packet_unit_sscs_set(&client.conn, pcargo->id,
                                 USSDT_SENTRY, 0);
    }
  }
}

/**********************************************************************//**
  Send request to do caravan action - establishing trade route or
  helping in wonder building - to server.
**************************************************************************/
void request_unit_caravan_action(struct unit *punit, action_id action)
{
  struct city *target_city;

  if (!((target_city = tile_city(unit_tile(punit))))) {
    return;
  }

  if (action == ACTION_TRADE_ROUTE) {
    request_do_action(ACTION_TRADE_ROUTE, punit->id,
                      target_city->id, 0, "");
  } else if (action == ACTION_HELP_WONDER) {
    request_do_action(ACTION_HELP_WONDER, punit->id,
                      target_city->id, 0, "");
  } else {
    log_error("request_unit_caravan_action() Bad action (%d)", action);
  }
}

/**********************************************************************//**
  Have the player select what tile to paradrop to. Once selected a
  paradrop request will be sent to server.
**************************************************************************/
void request_unit_paradrop(struct unit_list *punits)
{
  bool can = FALSE;
  struct tile *offender = NULL;

  if (unit_list_size(punits) == 0) {
    return;
  }
  unit_list_iterate(punits, punit) {
    if (can_unit_paradrop(&(wld.map), punit)) {
      can = TRUE;
      break;
    }
    if (!offender) { /* Take first offender tile/unit */
      offender = unit_tile(punit);
    }
  } unit_list_iterate_end;
  if (can) {
    create_event(unit_tile(unit_list_get(punits, 0)), E_BEGINNER_HELP,
                 ftc_client,
                 /* TRANS: paradrop target tile. */
                 _("Click on a tile to paradrop to it."));

    set_hover_state(punits, HOVER_PARADROP, ACTIVITY_LAST, NULL,
                    NO_TARGET, NO_TARGET, ACTION_NONE, ORDER_LAST);
    update_unit_info_label(punits);
  } else {
    create_event(offender, E_BAD_COMMAND, ftc_client,
                 _("Only paratrooper units can do this."));
  }
}

/**********************************************************************//**
  Have the player select what tile to teleport to. Once selected a
  teleport request will be sent to server.
**************************************************************************/
static void request_unit_teleport(struct unit_list *punits)
{
  bool can = FALSE;
  struct tile *offender = NULL;

  if (unit_list_size(punits) == 0) {
    return;
  }

  unit_list_iterate(punits, punit) {
    if (can_unit_teleport(&(wld.map), punit)) {
      can = TRUE;
      break;
    }
    if (!offender) { /* Take first offender tile/unit */
      offender = unit_tile(punit);
    }
  } unit_list_iterate_end;

  if (can) {
    create_event(unit_tile(unit_list_get(punits, 0)), E_BEGINNER_HELP,
                 ftc_client,
                 /* TRANS: teleport target tile. */
                 _("Click on a tile to teleport to it."));

    set_hover_state(punits, HOVER_TELEPORT, ACTIVITY_LAST, NULL,
                    NO_TARGET, NO_TARGET, ACTION_NONE, ORDER_LAST);
    update_unit_info_label(punits);
  } else {
    create_event(offender, E_BAD_COMMAND, ftc_client,
                 _("Only teleporting units can do this."));
  }
}

/**********************************************************************//**
  Either start new patrol route planning, or add waypoint to current one.
**************************************************************************/
void request_unit_patrol(void)
{
  struct unit_list *punits = get_units_in_focus();

  if (unit_list_size(punits) == 0) {
    return;
  }

  if (hover_state != HOVER_PATROL) {
    set_hover_state(punits, HOVER_PATROL, ACTIVITY_LAST, NULL,
                    NO_TARGET, NO_TARGET, ACTION_NONE, ORDER_LAST);
    update_unit_info_label(punits);
    enter_goto_state(punits);
    create_line_at_mouse_pos();
  } else {
    fc_assert_ret(goto_is_active());
    goto_add_waypoint();
  }
}

/**********************************************************************//**
  Try to sentry unit.
**************************************************************************/
void request_unit_sentry(struct unit *punit)
{
  if (punit->activity != ACTIVITY_SENTRY
      && can_unit_do_activity_client(punit, ACTIVITY_SENTRY)) {
    request_new_unit_activity(punit, ACTIVITY_SENTRY);
  }
}

/**********************************************************************//**
  Try to fortify unit.
**************************************************************************/
void request_unit_fortify(struct unit *punit)
{
  if (punit->activity != ACTIVITY_FORTIFYING
      && can_unit_do_activity_client(punit, ACTIVITY_FORTIFYING)) {
    request_new_unit_activity(punit, ACTIVITY_FORTIFYING);
  }
}

/**********************************************************************//**
  Send pillage request to server.
**************************************************************************/
void request_unit_pillage(struct unit *punit)
{
  if (!game.info.pillage_select) {
    /* Leave choice up to the server */
    request_new_unit_activity_targeted(punit, ACTIVITY_PILLAGE, NULL);
  } else {
    bv_extras pspossible;
    int count = 0;

    BV_CLR_ALL(pspossible);
    extra_type_iterate(potential) {
      if (can_unit_do_activity_targeted_client(punit, ACTIVITY_PILLAGE,
                                               potential)) {
        BV_SET(pspossible, extra_index(potential));
        count++;
      }
    } extra_type_iterate_end;

    if (count > 1) {
      popup_pillage_dialog(punit, pspossible);
    } else {
      /* Should be only one choice... */
      struct extra_type *target = get_preferred_pillage(pspossible);

      if (target != NULL) {
        request_new_unit_activity_targeted(punit, ACTIVITY_PILLAGE, target);
      }
    }
  }
}

/**********************************************************************//**
  Toggle display of city outlines on the map
**************************************************************************/
void request_toggle_city_outlines(void) 
{
  if (!can_client_change_view()) {
    return;
  }

  gui_options.draw_city_outlines = !gui_options.draw_city_outlines;
  update_map_canvas_visible();
}

/**********************************************************************//**
  Toggle display of worker output of cities on the map
**************************************************************************/
void request_toggle_city_output(void)
{
  if (!can_client_change_view()) {
    return;
  }
  
  gui_options.draw_city_output = !gui_options.draw_city_output;
  update_map_canvas_visible();
}

/**********************************************************************//**
  Toggle display of grid lines on the map
**************************************************************************/
void request_toggle_map_grid(void) 
{
  if (!can_client_change_view()) {
    return;
  }

  gui_options.draw_map_grid ^= 1;
  update_map_canvas_visible();
}

/**********************************************************************//**
  Toggle display of national borders on the map
**************************************************************************/
void request_toggle_map_borders(void) 
{
  if (!can_client_change_view()) {
    return;
  }

  gui_options.draw_borders ^= 1;
  update_map_canvas_visible();
}

/**********************************************************************//**
  Toggle display of native tiles on the map
**************************************************************************/
void request_toggle_map_native(void) 
{
  if (!can_client_change_view()) {
    return;
  }

  gui_options.draw_native ^= 1;
  update_map_canvas_visible();
}

/**********************************************************************//**
  Toggle display of city full bar.
**************************************************************************/
void request_toggle_city_full_bar(void)
{
  if (!can_client_change_view()) {
    return;
  }

  gui_options.draw_full_citybar ^= 1;
  update_map_canvas_visible();
}

/**********************************************************************//**
  Toggle display of city names
**************************************************************************/
void request_toggle_city_names(void)
{
  if (!can_client_change_view()) {
    return;
  }

  gui_options.draw_city_names ^= 1;
  update_map_canvas_visible();
}
 
/**********************************************************************//**
  Toggle display of city growth (turns-to-grow)
**************************************************************************/
void request_toggle_city_growth(void)
{
  if (!can_client_change_view()) {
    return;
  }

  gui_options.draw_city_growth ^= 1;
  update_map_canvas_visible();
}

/**********************************************************************//**
  Toggle display of city productions
**************************************************************************/
void request_toggle_city_productions(void)
{
  if (!can_client_change_view()) {
    return;
  }

  gui_options.draw_city_productions ^= 1;
  update_map_canvas_visible();
}

/**********************************************************************//**
  Toggle display of city buycost
**************************************************************************/
void request_toggle_city_buycost(void)
{
  if (!can_client_change_view()) {
    return;
  }

  gui_options.draw_city_buycost ^= 1;
  update_map_canvas_visible();
}

/**********************************************************************//**
  Toggle display of city trade routes
**************************************************************************/
void request_toggle_city_trade_routes(void)
{
  if (!can_client_change_view()) {
    return;
  }

  gui_options.draw_city_trade_routes ^= 1;
  update_map_canvas_visible();
}

/**********************************************************************//**
  Toggle display of unit stack sizes
**************************************************************************/
void request_toggle_unit_stack_size(void)
{
  if (!can_client_change_view()) {
    return;
  }

  gui_options.draw_unit_stack_size ^= 1;
  update_map_canvas_visible();
}

/**********************************************************************//**
  Toggle display of terrain
**************************************************************************/
void request_toggle_terrain(void)
{
  if (!can_client_change_view()) {
    return;
  }

  gui_options.draw_terrain ^= 1;
  update_map_canvas_visible();
}

/**********************************************************************//**
  Toggle display of coastline
**************************************************************************/
void request_toggle_coastline(void)
{
  if (!can_client_change_view()) {
    return;
  }

  gui_options.draw_coastline ^= 1;
  update_map_canvas_visible();
}

/**********************************************************************//**
  Toggle display of paths
**************************************************************************/
void request_toggle_paths(void)
{
  if (!can_client_change_view()) {
    return;
  }

  gui_options.draw_paths ^= 1;
  update_map_canvas_visible();
}

/**********************************************************************//**
  Toggle display of irrigation
**************************************************************************/
void request_toggle_irrigation(void)
{
  if (!can_client_change_view()) {
    return;
  }

  gui_options.draw_irrigation ^= 1;
  update_map_canvas_visible();
}

/**********************************************************************//**
  Toggle display of mines
**************************************************************************/
void request_toggle_mines(void)
{
  if (!can_client_change_view()) {
    return;
  }

  gui_options.draw_mines ^= 1;
  update_map_canvas_visible();
}

/**********************************************************************//**
  Toggle display of bases
**************************************************************************/
void request_toggle_bases(void)
{
  if (!can_client_change_view()) {
    return;
  }

  gui_options.draw_fortress_airbase ^= 1;
  update_map_canvas_visible();
}

/**********************************************************************//**
  Toggle display of resources
**************************************************************************/
void request_toggle_resources(void)
{
  if (!can_client_change_view()) {
    return;
  }

  gui_options.draw_specials ^= 1;
  update_map_canvas_visible();
}

/**********************************************************************//**
  Toggle display of huts
**************************************************************************/
void request_toggle_huts(void)
{
  if (!can_client_change_view()) {
    return;
  }

  gui_options.draw_huts ^= 1;
  update_map_canvas_visible();
}

/**********************************************************************//**
  Toggle display of pollution
**************************************************************************/
void request_toggle_pollution(void)
{
  if (!can_client_change_view()) {
    return;
  }

  gui_options.draw_pollution ^= 1;
  update_map_canvas_visible();
}

/**********************************************************************//**
  Toggle display of cities
**************************************************************************/
void request_toggle_cities(void)
{
  if (!can_client_change_view()) {
    return;
  }

  gui_options.draw_cities ^= 1;
  update_map_canvas_visible();
}

/**********************************************************************//**
  Toggle display of units
**************************************************************************/
void request_toggle_units(void)
{
  if (!can_client_change_view()) {
    return;
  }

  gui_options.draw_units ^= 1;
  update_map_canvas_visible();
}

/**********************************************************************//**
  Toggle display of unit solid background.
**************************************************************************/
void request_toggle_unit_solid_bg(void)
{
  if (!can_client_change_view()) {
    return;
  }

  gui_options.solid_color_behind_units ^= 1;
  update_map_canvas_visible();
}

/**********************************************************************//**
  Toggle display of unit shields.
**************************************************************************/
void request_toggle_unit_shields(void)
{
  if (!can_client_change_view()) {
    return;
  }

  gui_options.draw_unit_shields ^= 1;
  update_map_canvas_visible();
}

/**********************************************************************//**
  Toggle display of focus unit
**************************************************************************/
void request_toggle_focus_unit(void)
{
  if (!can_client_change_view()) {
    return;
  }

  gui_options.draw_focus_unit ^= 1;
  update_map_canvas_visible();
}

/**********************************************************************//**
  Toggle display of fog of war
**************************************************************************/
void request_toggle_fog_of_war(void)
{
  if (!can_client_change_view()) {
    return;
  }

  gui_options.draw_fog_of_war ^= 1;
  update_map_canvas_visible();
  refresh_overview_canvas();
}

/**********************************************************************//**
  Center to focus unit.
**************************************************************************/
void request_center_focus_unit(void)
{
  struct tile *ptile = find_a_focus_unit_tile_to_center_on();

  if (ptile) {
    center_tile_mapcanvas(ptile);
  }
}

/**********************************************************************//**
  Set units in list to waiting focus. If they are current focus units,
  advance focus.
**************************************************************************/
void request_units_wait(struct unit_list *punits)
{
  unit_list_iterate(punits, punit) {
    punit->client.focus_status = FOCUS_WAIT;
  } unit_list_iterate_end;
  if (punits == get_units_in_focus()) {
    unit_focus_advance(TRUE);
  }
}

/**********************************************************************//**
  Set focus units to FOCUS_DONE state.
**************************************************************************/
void request_unit_move_done(void)
{
  if (get_num_units_in_focus() > 0) {
    enum unit_focus_status new_status = FOCUS_DONE;
    unit_list_iterate(get_units_in_focus(), punit) {
      /* If any of the focused units are busy, keep all of them
       * in focus; another tap of the key will dismiss them */
      if (punit->activity != ACTIVITY_IDLE) {
        new_status = FOCUS_WAIT;
      }
    } unit_list_iterate_end;
    unit_list_iterate(get_units_in_focus(), punit) {
      clear_unit_orders(punit);
      punit->client.focus_status = new_status;
    } unit_list_iterate_end;
    if (new_status == FOCUS_DONE) {
      unit_focus_advance(TRUE);
    }
  }
}

/**********************************************************************//**
  Called to have the client move a unit from one location to another,
  updating the graphics if necessary.  The caller must redraw the target
  location after the move.
**************************************************************************/
void do_move_unit(struct unit *punit, struct unit *target_unit)
{
  struct tile *src_tile = unit_tile(punit);
  struct tile *dst_tile = unit_tile(target_unit);
  bool was_teleported, do_animation;
  bool in_focus = unit_is_in_focus(punit);

  was_teleported = !is_tiles_adjacent(src_tile, dst_tile);
  do_animation = (!was_teleported && gui_options.smooth_move_unit_msec > 0);

  if (!was_teleported
      && punit->activity != ACTIVITY_SENTRY
      && !unit_transported(punit)) {
    audio_play_sound(unit_type_get(punit)->sound_move,
                     unit_type_get(punit)->sound_move_alt,
                     NULL);
  }

  if (unit_owner(punit) == client.conn.playing
      && gui_options.auto_center_on_unit
      && !unit_has_orders(punit)
      && punit->activity != ACTIVITY_GOTO
      && punit->activity != ACTIVITY_SENTRY
      && ((gui_options.auto_center_on_automated
           && punit->ssa_controller != SSA_NONE)
          || (punit->ssa_controller == SSA_NONE))
      && !tile_visible_and_not_on_border_mapcanvas(dst_tile)) {
    center_tile_mapcanvas(dst_tile);
  }

  if (hover_state != HOVER_NONE && in_focus) {
    /* Cancel current goto/patrol/connect/nuke command. */
    clear_hover_state();
    update_unit_info_label(get_units_in_focus());
  }

  unit_list_remove(src_tile->units, punit);

  if (!unit_transported(punit)) {
    /* Mark the unit as moving unit, then find_visible_unit() won't return
     * it. It is especially useful to don't draw many times the unit when
     * refreshing the canvas. */
    punit_moving = punit;

    /* We have to refresh the tile before moving.  This will draw
     * the tile without the unit (because it was unlinked above). */
    refresh_unit_mapcanvas(punit, src_tile, TRUE, FALSE);

    if (!gui_options.auto_center_on_automated
        && punit->ssa_controller != SSA_NONE) {
      /* Dont animate automatic units */
    } else if (do_animation) {
      int dx, dy;

      /* For the duration of the animation the unit exists at neither
       * tile. */
      map_distance_vector(&dx, &dy, src_tile, dst_tile);
      move_unit_map_canvas(punit, src_tile, dx, dy);
    }
  }

  unit_tile_set(punit, dst_tile);
  unit_list_prepend(dst_tile->units, punit);

  if (!unit_transported(punit)) {
    /* For find_visible_unit(), see above. */
    punit_moving = NULL;

    refresh_unit_mapcanvas(punit, dst_tile, TRUE, FALSE);
  }

  /* With the "full" city bar we have to update the city bar when units move
   * into or out of a city.  For foreign cities this is handled separately,
   * via the occupied field of the short-city packet. */
  if (NULL != tile_city(src_tile)
      && can_player_see_units_in_city(client.conn.playing, tile_city(src_tile))) {
    update_city_description(tile_city(src_tile));
  }
  if (NULL != tile_city(dst_tile)
      && can_player_see_units_in_city(client.conn.playing, tile_city(dst_tile))) {
    update_city_description(tile_city(dst_tile));
  }

  if (in_focus) {
    menus_update();
  }
}

/**********************************************************************//**
  An action selection dialog for the selected units against the specified
  tile is wanted.
**************************************************************************/
static void do_unit_act_sel_vs(struct tile *ptile)
{
  unit_list_iterate(get_units_in_focus(), punit) {
    if (utype_may_act_at_all(unit_type_get(punit))) {
      /* Have the server record that an action decision is wanted for
       * this unit against this tile. */
      dsend_packet_unit_sscs_set(&client.conn, punit->id,
                                 USSDT_QUEUE, tile_index(ptile));
    }
  } unit_list_iterate_end;
}

/**********************************************************************//**
  Handles everything when the user clicked a tile
**************************************************************************/
void do_map_click(struct tile *ptile, enum quickselect_type qtype)
{
  struct city *pcity = tile_city(ptile);
  struct unit_list *punits = get_units_in_focus();
  bool maybe_goto = FALSE;

  if (hover_state != HOVER_NONE) {
    switch (hover_state) {
    case HOVER_NONE:
      break;
    case HOVER_GOTO:
      do_unit_goto(ptile);
      break;
    case HOVER_TELEPORT:
      unit_list_iterate(punits, punit) {
        do_unit_teleport_to(punit, ptile);
      } unit_list_iterate_end;
      break;
    case HOVER_PARADROP:
      unit_list_iterate(punits, punit) {
        do_unit_paradrop_to(punit, ptile);
      } unit_list_iterate_end;
      break;
    case HOVER_CONNECT:
      do_unit_connect(ptile, connect_activity, connect_tgt);
      break;
    case HOVER_PATROL:
      do_unit_patrol_to(ptile);
      break;	
    case HOVER_ACT_SEL_TGT:
      do_unit_act_sel_vs(ptile);
      break;
    case HOVER_GOTO_SEL_TGT:
      fc_assert(action_id_exists(goto_last_action));
      do_unit_goto(ptile);
      break;
    }

    clear_hover_state();
    update_unit_info_label(get_units_in_focus());
  } else if (qtype != SELECT_POPUP && qtype != SELECT_APPEND) {
    /* Bypass stack or city popup if quickselect is specified. */
    struct unit *qunit = quickselect(ptile, qtype);

    if (qunit) {
      unit_focus_set_and_select(qunit);
      maybe_goto = gui_options.keyboardless_goto;
    }
  } else if (NULL != pcity
             && can_player_see_city_internals(client.conn.playing, pcity)) {
    /* Otherwise use popups. */
    popup_city_dialog(pcity);
  } else if (unit_list_size(ptile->units) == 0
             && NULL == pcity
             && get_num_units_in_focus() > 0) {
    maybe_goto = gui_options.keyboardless_goto;
  } else if (unit_list_size(ptile->units) == 1
             && !get_transporter_occupancy(unit_list_get(ptile->units, 0))) {
    struct unit *punit = unit_list_get(ptile->units, 0);

    if (unit_owner(punit) == client.conn.playing) {
      if (can_unit_do_activity_client(punit, ACTIVITY_IDLE)) {
        maybe_goto = gui_options.keyboardless_goto;
        if (qtype == SELECT_APPEND) {
          unit_focus_add(punit);
        } else {
          unit_focus_set_and_select(punit);
        }
      }
    } else if (pcity) {
      /* Don't hide the unit in the city. */
      unit_select_dialog_popup(ptile);
    }
  } else if (unit_list_size(ptile->units) > 0) {
    /* The stack list is always popped up, even if it includes enemy units.
     * If the server doesn't want the player to know about them it shouldn't
     * tell them! The previous behavior would only pop up the stack if you
     * owned a unit on the tile. This gave cheating clients an advantage,
     * and also showed you allied units if (and only if) you had a unit on
     * the tile (inconsistent). */
    unit_select_dialog_popup(ptile);
  }

  /* See mapctrl_common.c */
  keyboardless_goto_start_tile = maybe_goto ? ptile : NULL;
  keyboardless_goto_button_down = maybe_goto;
  keyboardless_goto_active = FALSE;
}

/**********************************************************************//**
  Quickselecting a unit is normally done with [control] left, right click,
  for the current tile. Bypassing the stack popup is quite convenient,
  and can be tactically important in furious multiplayer games.
**************************************************************************/
static struct unit *quickselect(struct tile *ptile,
                                enum quickselect_type qtype)
{
  int listsize = unit_list_size(ptile->units);
  struct unit *panytransporter = NULL,
              *panymovesea  = NULL, *panysea  = NULL,
              *panymoveland = NULL, *panyland = NULL,
              *panymoveunit = NULL, *panyunit = NULL;

  fc_assert_ret_val(qtype > SELECT_POPUP, NULL);

  if (qtype == SELECT_FOCUS) {
    return head_of_units_in_focus();
  }

  if (listsize == 0) {
    return NULL;
  } else if (listsize == 1) {
    struct unit *punit = unit_list_get(ptile->units, 0);
    return (unit_owner(punit) == client.conn.playing) ? punit : NULL;
  }

  /*  Quickselect priorities. Units with moves left
   *  before exhausted. Focus unit is excluded.
   *
   *    SEA:  Transporter
   *          Sea unit
   *          Any unit
   *
   *    LAND: Military land unit
   *          Non-combatant
   *          Sea unit
   *          Any unit
   */

  unit_list_iterate(ptile->units, punit)  {
    if (unit_owner(punit) != client.conn.playing || unit_is_in_focus(punit)) {
      continue;
    }
  if (qtype == SELECT_SEA) {
    /* Transporter. */
    if (get_transporter_capacity(punit)) {
      if (punit->moves_left > 0) {
        return punit;
      } else if (!panytransporter) {
        panytransporter = punit;
      }
    }
    /* Any sea, pref. moves left. */
    else if (utype_move_type(unit_type_get(punit)) == UMT_SEA) {
      if (punit->moves_left > 0) {
        if (!panymovesea) {
          panymovesea = punit;
        }
      } else if (!panysea) {
          panysea = punit;
      }
    }
  } else if (qtype == SELECT_LAND) {
    if (utype_move_type(unit_type_get(punit)) == UMT_LAND) {
      if (punit->moves_left > 0) {
        if (!is_special_unit(punit)) {
          return punit;
        } else if (!panymoveland) {
          panymoveland = punit;
        }
      } else if (!panyland) {
        panyland = punit;
      }
    }
    else if (utype_move_type(unit_type_get(punit)) == UMT_SEA) {
      if (punit->moves_left > 0) {
        panymovesea = punit;
      } else {
        panysea = punit;
      }
    }
  }
  if (punit->moves_left > 0 && !panymoveunit) {
    panymoveunit = punit;
  }
  if (!panyunit) {
    panyunit = punit;
  }
    } unit_list_iterate_end;

  if (qtype == SELECT_SEA) {
    if (panytransporter) {
      return panytransporter;
    } else if (panymovesea) {
      return panymovesea;
    } else if (panysea) {
      return panysea;
    } else if (panymoveunit) {
      return panymoveunit;
    } else if (panyunit) {
      return panyunit;
    }
  }
  else if (qtype == SELECT_LAND) {
    if (panymoveland) {
      return panymoveland;
    } else if (panyland) {
      return panyland;
    } else if (panymovesea) {
      return panymovesea;
    } else if (panysea) {
      return panysea;
    } else if (panymoveunit) {
      return panymoveunit;
    } else if (panyunit) {
      return panyunit;
    }
  }
  return NULL;
}

/**********************************************************************//**
  Finish the goto mode and let the units stored in goto_map_list move
  to a given location.
**************************************************************************/
void do_unit_goto(struct tile *ptile)
{
  fc_assert_ret(hover_state == HOVER_GOTO
                || hover_state == HOVER_GOTO_SEL_TGT);
  fc_assert_ret(goto_is_active());

  if (hover_state == HOVER_GOTO_SEL_TGT) {
    send_goto_route();
    return;
  }

  if (is_valid_goto_draw_line(ptile)) {
    send_goto_route();
  } else {
    create_event(ptile, E_BAD_COMMAND, ftc_client,
                 _("Didn't find a route to the destination!"));
  }
}

/**********************************************************************//**
  Teleport to a location.
**************************************************************************/
static void do_unit_teleport_to(struct unit *punit, struct tile *ptile)
{
  struct action *teleport_action = NULL;

  action_iterate(act_id) {
    struct action *paction = action_by_number(act_id);

    if (!action_has_result(paction, ACTRES_TELEPORT)) {
      /* Not relevant. */
      continue;
    }

    if (action_prob_possible(
          action_prob_unit_vs_tgt(&(wld.map), paction, punit,
                                  tile_city(ptile), NULL,
                                  ptile, NULL))) {
      if (teleport_action == NULL) {
        /* This is the first possible teleport action. */
        teleport_action = paction;
      } else {
        /* More than one teleport action may be possible. The user must
         * choose. Have the server record that an action decision is wanted
         * for this unit so the dialog will be brought up. */
        dsend_packet_unit_sscs_set(&client.conn, punit->id,
                                   USSDT_QUEUE, tile_index(ptile));
        return;
      }
    }
  } action_iterate_end;

  if (teleport_action != NULL) {
    request_do_action(teleport_action->id, punit->id,
                      tile_index(ptile), 0 , "");
  }
}

/**********************************************************************//**
  Paradrop to a location.
**************************************************************************/
void do_unit_paradrop_to(struct unit *punit, struct tile *ptile)
{
  struct action *paradrop_action = NULL;

  action_iterate(act_id) {
    struct action *paction = action_by_number(act_id);

    if (!(action_has_result(paction, ACTRES_PARADROP_CONQUER)
          || action_has_result(paction, ACTRES_PARADROP))) {
      /* Not relevant. */
      continue;
    }

    if (action_prob_possible(
          action_prob_unit_vs_tgt(&(wld.map), paction, punit,
                                  tile_city(ptile), NULL,
                                  ptile, NULL))) {
      if (paradrop_action == NULL) {
        /* This is the first possible paradrop action. */
        paradrop_action = paction;
      } else {
        /* More than one paradrop action may be possible. The user must
         * choose. Have the server record that an action decision is wanted
         * for this unit so the dialog will be brought up. */
        dsend_packet_unit_sscs_set(&client.conn, punit->id,
                                   USSDT_QUEUE, tile_index(ptile));
        return;
      }
    }
  } action_iterate_end;

  if (paradrop_action != NULL) {
    request_do_action(paradrop_action->id, punit->id,
                      tile_index(ptile), 0 , "");
  }
}

/**********************************************************************//**
  Patrol to a location.
**************************************************************************/
void do_unit_patrol_to(struct tile *ptile)
{
  if (is_valid_goto_draw_line(ptile)
      && !is_non_allied_unit_tile(ptile, client.conn.playing)) {
    send_patrol_route();
  } else {
    create_event(ptile, E_BAD_COMMAND, ftc_client,
                 _("Didn't find a route to the destination!"));
  }

  clear_hover_state();
}

/**********************************************************************//**
  "Connect" to the given location.
**************************************************************************/
void do_unit_connect(struct tile *ptile,
                     enum unit_activity activity,
                     struct extra_type *tgt)
{
  if (is_valid_goto_draw_line(ptile)) {
    send_connect_route(activity, tgt);
  } else {
    create_event(ptile, E_BAD_COMMAND, ftc_client,
                 _("Didn't find a route to the destination!"));
  }

  clear_hover_state();
}

/**********************************************************************//**
  The 'Escape' key.
**************************************************************************/
void key_cancel_action(void)
{
  struct unit_list *punits = get_units_in_focus();
  cancel_tile_hiliting();

  switch (hover_state) {
  case HOVER_GOTO_SEL_TGT:
    set_hover_state(punits, HOVER_GOTO, connect_activity, connect_tgt,
                    goto_last_tgt, goto_last_sub_tgt,
                    goto_last_action, goto_last_order);
    break;
  case HOVER_GOTO:
  case HOVER_PATROL:
  case HOVER_CONNECT:
    if (goto_pop_waypoint()) {
      break;
    }
    fc__fallthrough; /* else fall through: */
  case HOVER_TELEPORT:
  case HOVER_PARADROP:
  case HOVER_ACT_SEL_TGT:
    clear_hover_state();
    update_unit_info_label(get_units_in_focus());

    keyboardless_goto_button_down = FALSE;
    keyboardless_goto_active = FALSE;
    keyboardless_goto_start_tile = NULL;
    break;
  case HOVER_NONE:
    break;
  };
}

/**********************************************************************//**
  Center the mapview on the player's named capital,
  or print a failure message.
**************************************************************************/
void key_center_capital(void)
{
  struct city *capital = player_primary_capital(client_player());

  if (capital)  {
    /* Center on the tile, and pop up the crosshair overlay. */
    center_tile_mapcanvas(capital->tile);
    put_cross_overlay_tile(capital->tile);
  } else {
    create_event(NULL, E_BAD_COMMAND, ftc_client,
                 _("Oh my! You seem to have no capital!"));
  }
}

/**********************************************************************//**
  Handle user 'end turn' input.
**************************************************************************/
void key_end_turn(void)
{
  send_turn_done();
}

/**********************************************************************//**
  Recall the previous focus unit(s).  See store_previous_focus().
**************************************************************************/
void key_recall_previous_focus_unit(void)
{
  int i = 0;

  /* Could use unit_list_copy here instead. Just having safe genlists
   * wouldn't be sufficient since we don't want to skip units already
   * removed from focus... */
  unit_list_iterate_safe(previous_focus, punit) {
    if (i == 0) {
      unit_focus_set(punit);
    } else {
      unit_focus_add(punit);
    }
    i++;
  } unit_list_iterate_safe_end;
}

/**********************************************************************//**
  Move the focus unit in the given direction.  Here directions are
  defined according to the GUI, so that north is "up" in the interface.
**************************************************************************/
void key_unit_move(enum direction8 gui_dir)
{
  unit_list_iterate(get_units_in_focus(), punit) {
    enum direction8 map_dir = gui_to_map_dir(gui_dir);

    request_move_unit_direction(punit, map_dir);
  } unit_list_iterate_end;
}

/**********************************************************************//**
  Handle use 'build city' input.
**************************************************************************/
void key_unit_build_city(void)
{
  unit_list_iterate(get_units_in_focus(), punit) {
    request_unit_build_city(punit);
  } unit_list_iterate_end;
}

/**********************************************************************//**
  Handle user 'help build wonder' input
**************************************************************************/
void key_unit_build_wonder(void)
{
  unit_list_iterate(get_units_in_focus(), punit) {
    if (unit_can_do_action(punit, ACTION_HELP_WONDER)) {
      request_unit_caravan_action(punit, ACTION_HELP_WONDER);
    }
  } unit_list_iterate_end;
}

/**********************************************************************//**
  Handle user pressing key for 'Connect' command
**************************************************************************/
void key_unit_connect(enum unit_activity activity,
                      struct extra_type *tgt)
{
  request_unit_connect(activity, tgt);
}

/**********************************************************************//**
  Handle user 'Do...' input
**************************************************************************/
void key_unit_action_select(void)
{
  struct tile *ptile;

  unit_list_iterate(get_units_in_focus(), punit) {
    if (utype_may_act_at_all(unit_type_get(punit))
        && (ptile = unit_tile(punit))) {
      /* Have the server record that an action decision is wanted for this
       * unit. */
      dsend_packet_unit_sscs_set(&client.conn, punit->id,
                                 USSDT_QUEUE, tile_index(ptile));
    }
  } unit_list_iterate_end;
}

/**********************************************************************//**
  Have the user select what action the unit(s) in focus should perform to
  the targets at the tile the user will specify by clicking on it.

  Will stop asking for a target tile and have each actor unit act against
  its own tile if called twice.
**************************************************************************/
void key_unit_action_select_tgt(void)
{
  struct unit_list *punits = get_units_in_focus();

  if (hover_state == HOVER_ACT_SEL_TGT) {
    /* The 2nd key press means that the actor should target its own
     * tile. */
    key_unit_action_select();

    /* Target tile selected. Clean up hover state. */
    clear_hover_state();
    update_unit_info_label(punits);

    return;
  } else if (hover_state == HOVER_GOTO_SEL_TGT) {
    fc_assert(action_id_exists(goto_last_action));

    /* We don't support long range actions in the middle of orders yet so
     * send it at once. */
    send_goto_route();

    /* Target tile selected. Clean up hover state. */
    clear_hover_state();
    update_unit_info_label(punits);

    return;
  } else if (hover_state == HOVER_GOTO
             && action_id_exists(goto_last_action)) {
    struct action *paction = action_by_number(goto_last_action);

    create_event(unit_tile(unit_list_get(punits, 0)), E_BEGINNER_HELP,
                 ftc_client,
                 /* TRANS: Perform action inside a goto. */
                 _("Click on a tile to do %s against it."),
                 action_name_translation(paction));

    set_hover_state(punits, HOVER_GOTO_SEL_TGT,
                    connect_activity, connect_tgt,
                    goto_last_tgt, goto_last_sub_tgt,
                    goto_last_action, goto_last_order);

    return;
  }

  create_event(unit_tile(unit_list_get(punits, 0)), E_BEGINNER_HELP,
               ftc_client,
               /* TRANS: "Do..." action selection dialog target. */
               _("Click on a tile to act against it. "
                 "Press 'd' again to act against own tile."));

  set_hover_state(punits, HOVER_ACT_SEL_TGT, ACTIVITY_LAST, NULL,
                  NO_TARGET, NO_TARGET, ACTION_NONE, ORDER_LAST);
}

/**********************************************************************//**
  Handle user 'unit done' input
**************************************************************************/
void key_unit_done(void)
{
  request_unit_move_done();
}

/**********************************************************************//**
  Handle user 'unit goto' input
**************************************************************************/
void key_unit_goto(void)
{
  request_unit_goto(ORDER_LAST, ACTION_NONE, -1);
}

/**********************************************************************//**
  Handle user 'paradrop' input
**************************************************************************/
void key_unit_paradrop(void)
{
  request_unit_paradrop(get_units_in_focus());
}

/**********************************************************************//**
  Handle user 'patrol' input
**************************************************************************/
void key_unit_patrol(void)
{
  request_unit_patrol();
}

/**********************************************************************//**
  Handle user 'teleport' input
**************************************************************************/
void key_unit_teleport(void)
{
  request_unit_teleport(get_units_in_focus());
}

/**********************************************************************//**
  Handle user 'establish trade route' input
**************************************************************************/
void key_unit_trade_route(void)
{
  unit_list_iterate(get_units_in_focus(), punit) {
    /* TODO: Is falling back on ACTION_MARKETPLACE if not able to establish
     * a trade route trade a good idea or an unplecant surprice? */
    if (unit_can_do_action(punit, ACTION_TRADE_ROUTE)) {
      request_unit_caravan_action(punit, ACTION_TRADE_ROUTE);
    }
  } unit_list_iterate_end;
}

/**********************************************************************//**
  Handle user 'unload all' input
**************************************************************************/
void key_unit_unload_all(void)
{
  struct unit *pnext_focus = NULL, *plast;

  unit_list_iterate(get_units_in_focus(), punit) {
    if ((plast = request_unit_unload_all(punit))) {
      pnext_focus = plast;
    }
  } unit_list_iterate_end;

  if (pnext_focus) {
    unit_list_iterate(get_units_in_focus(), punit) {
      /* Unfocus the ships, and advance the focus to the last unloaded unit.
       * If there is no unit unloaded (which shouldn't happen, but could if
       * the caller doesn't check if the transporter is loaded), the we
       * don't do anything. */
      punit->client.focus_status = FOCUS_WAIT;
    } unit_list_iterate_end;
    unit_focus_set(pnext_focus);
  }
}

/**********************************************************************//**
  Handle user 'wait' input
**************************************************************************/
void key_unit_wait(void)
{
  request_units_wait(get_units_in_focus());
}

/**********************************************************************//**
  Handle user 'wakeup others' input
**************************************************************************/
void key_unit_wakeup_others(void)
{
  unit_list_iterate(get_units_in_focus(), punit) {
    request_unit_wakeup(punit);
  } unit_list_iterate_end;
}

/**********************************************************************//**
  Handle user 'build base of class airbase' input
**************************************************************************/
void key_unit_airbase(void)
{
  unit_list_iterate(get_units_in_focus(), punit) {
    struct base_type *pbase =
      get_base_by_gui_type(BASE_GUI_AIRBASE, punit, unit_tile(punit));

    if (pbase) {
      struct extra_type *pextra = base_extra_get(pbase);

      request_new_unit_activity_targeted(punit, ACTIVITY_BASE, pextra);
    }
  } unit_list_iterate_end;
}

/**********************************************************************//**
  Handle user 'autoexplore' input
**************************************************************************/
void key_unit_auto_explore(void)
{
  unit_list_iterate(get_units_in_focus(), punit) {
    if (can_unit_do_activity_client(punit, ACTIVITY_EXPLORE)) {
      request_unit_ssa_set(punit, SSA_AUTOEXPLORE);
    }
  } unit_list_iterate_end;
}

/**********************************************************************//**
  Call to request (from the server) that the focus unit is put into
  autosettler mode.
**************************************************************************/
void key_unit_auto_settle(void)
{
  unit_list_iterate(get_units_in_focus(), punit) {
    if (can_unit_do_autosettlers(punit)) {
      request_unit_autosettlers(punit);
    }
  } unit_list_iterate_end;
}

/**********************************************************************//**
  Unit convert key pressed or respective menu entry selected.
**************************************************************************/
void key_unit_convert(void)
{
  unit_list_iterate(get_units_in_focus(), punit) {
    request_unit_convert(punit);
  } unit_list_iterate_end;
}

/**********************************************************************//**
  Handle user 'fortify' input
**************************************************************************/
void key_unit_fortify(void)
{
  unit_list_iterate(get_units_in_focus(), punit) {
    if (can_unit_do_activity_client(punit, ACTIVITY_FORTIFYING)) {
      request_new_unit_activity(punit, ACTIVITY_FORTIFYING);
    }
  } unit_list_iterate_end;
}

/**********************************************************************//**
  Handle user 'build base of class fortress' input
**************************************************************************/
void key_unit_fortress(void)
{
  unit_list_iterate(get_units_in_focus(), punit) {
    struct base_type *pbase =
      get_base_by_gui_type(BASE_GUI_FORTRESS, punit, unit_tile(punit));

    if (pbase) {
      struct extra_type *pextra = base_extra_get(pbase);

      request_new_unit_activity_targeted(punit, ACTIVITY_BASE, pextra);
    }
  } unit_list_iterate_end;
}

/**********************************************************************//**
  Handle user 'change homecity' input
**************************************************************************/
void key_unit_homecity(void)
{
  unit_list_iterate(get_units_in_focus(), punit) {
    request_unit_change_homecity(punit);
  } unit_list_iterate_end;
}

/**********************************************************************//**
  Handle user extra building input of given type
**************************************************************************/
static void key_unit_extra(enum unit_activity act, enum extra_cause cause)
{
  unit_list_iterate(get_units_in_focus(), punit) {
    struct extra_type *tgt = next_extra_for_tile(unit_tile(punit),
                                                 cause,
                                                 unit_owner(punit),
                                                 punit);

    if (can_unit_do_activity_targeted_client(punit, act, tgt)) {
      request_new_unit_activity_targeted(punit, act, tgt);
    }
  } unit_list_iterate_end;
}

/**********************************************************************//**
  Handle user 'irrigate' input
**************************************************************************/
void key_unit_irrigate(void)
{
  key_unit_extra(ACTIVITY_IRRIGATE, EC_IRRIGATION);
}

/**********************************************************************//**
  Handle user 'cultivate' input
**************************************************************************/
void key_unit_cultivate(void)
{
  unit_list_iterate(get_units_in_focus(), punit) {
    if (can_unit_do_activity_client(punit, ACTIVITY_CULTIVATE)) {
      request_new_unit_activity(punit, ACTIVITY_CULTIVATE);
    }
  } unit_list_iterate_end;
}

/**********************************************************************//**
  Handle user 'build mine' input
**************************************************************************/
void key_unit_mine(void)
{
  key_unit_extra(ACTIVITY_MINE, EC_MINE);
}

/**********************************************************************//**
  Handle user 'plant' input
**************************************************************************/
void key_unit_plant(void)
{
  unit_list_iterate(get_units_in_focus(), punit) {
    if (can_unit_do_activity_client(punit, ACTIVITY_PLANT)) {
      request_new_unit_activity(punit, ACTIVITY_PLANT);
    }
  } unit_list_iterate_end;
}

/**********************************************************************//**
  Handle user 'pillage' input
**************************************************************************/
void key_unit_pillage(void)
{
  unit_list_iterate(get_units_in_focus(), punit) {
    if (can_unit_do_activity_client(punit, ACTIVITY_PILLAGE)) {
      request_unit_pillage(punit);
    }
  } unit_list_iterate_end;
}

/**********************************************************************//**
  Handle user 'clean' input
**************************************************************************/
void key_unit_clean(void)
{
  unit_list_iterate(get_units_in_focus(), punit) {
    struct extra_type *tgt = prev_extra_in_tile(unit_tile(punit),
                                                ERM_CLEAN,
                                                unit_owner(punit),
                                                punit);

    if (tgt != NULL
        && can_unit_do_activity_targeted_client(punit, ACTIVITY_CLEAN, tgt)) {
      request_new_unit_activity_targeted(punit, ACTIVITY_CLEAN, tgt);
    }
  } unit_list_iterate_end;
}

/**********************************************************************//**
  Handle user 'build road or railroad' input
**************************************************************************/
void key_unit_road(void)
{
  unit_list_iterate(get_units_in_focus(), punit) {
    struct extra_type *tgt = next_extra_for_tile(unit_tile(punit),
                                                 EC_ROAD,
                                                 unit_owner(punit),
                                                 punit);

    if (tgt != NULL
        && can_unit_do_activity_targeted_client(punit, ACTIVITY_GEN_ROAD, tgt)) {
      request_new_unit_activity_targeted(punit, ACTIVITY_GEN_ROAD, tgt);
    }
  } unit_list_iterate_end;
}

/**********************************************************************//**
  Handle user 'sentry' input
**************************************************************************/
void key_unit_sentry(void)
{
  unit_list_iterate(get_units_in_focus(), punit) {
    if (can_unit_do_activity_client(punit, ACTIVITY_SENTRY)) {
      request_new_unit_activity(punit, ACTIVITY_SENTRY);
    }
  } unit_list_iterate_end;
}

/**********************************************************************//**
  Handle user 'transform unit' input
**************************************************************************/
void key_unit_transform(void)
{
  unit_list_iterate(get_units_in_focus(), punit) {
    if (can_unit_do_activity_client(punit, ACTIVITY_TRANSFORM)) {
      request_new_unit_activity(punit, ACTIVITY_TRANSFORM);
    }
  } unit_list_iterate_end;
}

/**********************************************************************//**
  Assign all focus units to this battlegroup.
**************************************************************************/
void key_unit_assign_battlegroup(int battlegroup, bool append)
{
  if (NULL != client.conn.playing && can_client_issue_orders()
      && battlegroups >= 0 && battlegroup < MAX_NUM_BATTLEGROUPS) {
    if (!append) {
      unit_list_iterate_safe(battlegroups[battlegroup], punit) {
	if (!unit_is_in_focus(punit)) {
	  punit->battlegroup = BATTLEGROUP_NONE;
          dsend_packet_unit_sscs_set(&client.conn, punit->id,
                                     USSDT_BATTLE_GROUP,
                                     BATTLEGROUP_NONE);
	  refresh_unit_mapcanvas(punit, unit_tile(punit), TRUE, FALSE);
	  unit_list_remove(battlegroups[battlegroup], punit);
	}
      } unit_list_iterate_safe_end;
    }
    unit_list_iterate(get_units_in_focus(), punit) {
      if (punit->battlegroup != battlegroup) {
	if (punit->battlegroup >= 0
	    && punit->battlegroup < MAX_NUM_BATTLEGROUPS) {
	  unit_list_remove(battlegroups[punit->battlegroup], punit);
	}
	punit->battlegroup = battlegroup;
        dsend_packet_unit_sscs_set(&client.conn, punit->id,
                                   USSDT_BATTLE_GROUP,
                                   battlegroup);
	unit_list_append(battlegroups[battlegroup], punit);
	refresh_unit_mapcanvas(punit, unit_tile(punit), TRUE, FALSE);
      }
    } unit_list_iterate_end;
    unit_list_iterate(battlegroups[battlegroup], punit) {
      unit_focus_add(punit);
    } unit_list_iterate_end;
  }
}

/**********************************************************************//**
  Bring this battlegroup into focus.
**************************************************************************/
void key_unit_select_battlegroup(int battlegroup, bool append)
{
  if (NULL != client.conn.playing && can_client_change_view()
      && battlegroups >= 0 && battlegroup < MAX_NUM_BATTLEGROUPS) {
    int i = 0;

    if (unit_list_size(battlegroups[battlegroup]) == 0 && !append) {
      unit_focus_set(NULL);
      return;
    }

    /* FIXME: this is very inefficient and can be improved. */
    unit_list_iterate(battlegroups[battlegroup], punit) {
      if (i == 0 && !append) {
	unit_focus_set(punit);
      } else {
	unit_focus_add(punit);
      }
      i++;
    } unit_list_iterate_end;
  }
}

/**********************************************************************//**
  Toggle drawing of city outlines.
**************************************************************************/
void key_city_outlines_toggle(void)
{
  request_toggle_city_outlines();
}

/**********************************************************************//**
  Toggle drawing of city output produced by workers of the city.
**************************************************************************/
void key_city_output_toggle(void)
{
  request_toggle_city_output();
}

/**********************************************************************//**
  Handle user 'toggle map grid' input
**************************************************************************/
void key_map_grid_toggle(void)
{
  request_toggle_map_grid();
}

/**********************************************************************//**
  Toggle map borders on the mapview on/off based on a keypress.
**************************************************************************/
void key_map_borders_toggle(void)
{
  request_toggle_map_borders();
}

/**********************************************************************//**
  Toggle native tiles on the mapview on/off based on a keypress.
**************************************************************************/
void key_map_native_toggle(void)
{
  request_toggle_map_native();
}

/**********************************************************************//**
  Toggle the "Draw the city bar" option.
**************************************************************************/
void key_city_full_bar_toggle(void)
{
  request_toggle_city_full_bar();
}

/**********************************************************************//**
  Handle user 'toggle city names display' input
**************************************************************************/
void key_city_names_toggle(void)
{
  request_toggle_city_names();
}

/**********************************************************************//**
  Toggles the "show city growth turns" option by passing off the
  request to another function...
**************************************************************************/
void key_city_growth_toggle(void)
{
  request_toggle_city_growth();
}

/**********************************************************************//**
  Toggles the showing of the buy cost of the current production in the
  city descriptions.
**************************************************************************/
void key_city_buycost_toggle(void)
{
  request_toggle_city_buycost();
}

/**********************************************************************//**
  Handle user 'toggle city production display' input
**************************************************************************/
void key_city_productions_toggle(void)
{
  request_toggle_city_productions();
}

/**********************************************************************//**
  Handle client request to toggle drawing of trade route information
  by the city name for cities visible on the main map view.
**************************************************************************/
void key_city_trade_routes_toggle(void)
{
  request_toggle_city_trade_routes();
}

/**********************************************************************//**
  Handle client request to toggle drawing of unit stack size information
**************************************************************************/
void key_unit_stack_size_toggle(void)
{
  request_toggle_unit_stack_size();
}

/**********************************************************************//**
  Handle user 'toggle terrain display' input
**************************************************************************/
void key_terrain_toggle(void)
{
  request_toggle_terrain();
}

/**********************************************************************//**
  Handle user 'toggle coastline display' input
**************************************************************************/
void key_coastline_toggle(void)
{
  request_toggle_coastline();
}

/**********************************************************************//**
  Handle user 'toggle paths display' input
**************************************************************************/
void key_paths_toggle(void)
{
  request_toggle_paths();
}

/**********************************************************************//**
  Handle user 'toggle irrigation display' input
**************************************************************************/
void key_irrigation_toggle(void)
{
  request_toggle_irrigation();
}

/**********************************************************************//**
  Handle user 'toggle mine display' input
**************************************************************************/
void key_mines_toggle(void)
{
  request_toggle_mines();
}

/**********************************************************************//**
  Handle user 'toggle bases display' input
**************************************************************************/
void key_bases_toggle(void)
{
  request_toggle_bases();
}

/**********************************************************************//**
  Handle user 'toggle resources display' input
**************************************************************************/
void key_resources_toggle(void)
{
  request_toggle_resources();
}

/**********************************************************************//**
  Handle user 'toggle huts display' input
**************************************************************************/
void key_huts_toggle(void)
{
  request_toggle_huts();
}

/**********************************************************************//**
  Handle user 'toggle pollution display' input
**************************************************************************/
void key_pollution_toggle(void)
{
  request_toggle_pollution();
}

/**********************************************************************//**
  Handle user 'toggle cities display' input
**************************************************************************/
void key_cities_toggle(void)
{
  request_toggle_cities();
}

/**********************************************************************//**
  Handle user 'toggle units display' input
**************************************************************************/
void key_units_toggle(void)
{
  request_toggle_units();
}

/**********************************************************************//**
  Toggle the "Solid unit background color" option.
**************************************************************************/
void key_unit_solid_bg_toggle(void)
{
  request_toggle_unit_solid_bg();
}

/**********************************************************************//**
  Toggle the "Draw shield graphics for units" option.
**************************************************************************/
void key_unit_shields_toggle(void)
{
  request_toggle_unit_shields();
}

/**********************************************************************//**
  Handle user 'toggle key units display' input
**************************************************************************/
void key_focus_unit_toggle(void)
{
  request_toggle_focus_unit();
}

/**********************************************************************//**
  Handle user 'toggle fog of war display' input
**************************************************************************/
void key_fog_of_war_toggle(void)
{
  request_toggle_fog_of_war();
}

/**********************************************************************//**
  Toggle editor mode in the server.
**************************************************************************/
void key_editor_toggle(void)
{
  dsend_packet_edit_mode(&client.conn, !game.info.is_edit_mode);
}

/**********************************************************************//**
  Recalculate borders.
**************************************************************************/
void key_editor_recalculate_borders(void)
{
  send_packet_edit_recalculate_borders(&client.conn);
}

/**********************************************************************//**
  Send a request to the server to toggle fog-of-war for the current
  player (only applies in edit mode).
**************************************************************************/
void key_editor_toggle_fogofwar(void)
{
  if (client_has_player()) {
    dsend_packet_edit_toggle_fogofwar(&client.conn, client_player_number());
  }
}

/**********************************************************************//**
  All units ready to build city to the tile should now proceed.
**************************************************************************/
void finish_city(struct tile *ptile, const char *name)
{
  unit_list_iterate(ptile->units, punit) {
    if (punit->client.asking_city_name) {
      /* Unit will disappear only in case city building still success.
       * Cancel city building status just in case something has changed
       * to prevent city building in the meanwhile and unit will remain
       * alive. */
      punit->client.asking_city_name = FALSE;
      request_do_action(ACTION_FOUND_CITY, punit->id, ptile->index,
                        0, name);
    }
  } unit_list_iterate_end;
}

/**********************************************************************//**
  Do not build city after all. Cancel city building mark from all units
  prepared for it.
**************************************************************************/
void cancel_city(struct tile *ptile)
{
  unit_list_iterate(ptile->units, punit) {
    punit->client.asking_city_name = FALSE;
  } unit_list_iterate_end;
}