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

#include "llviewerprecompiledheaders.h"

#include "llviewerinput.h"

#include "llappviewer.h"
#include "llfloaterreg.h"
#include "llmath.h"
#include "llagent.h"
#include "llagentcamera.h"
#include "llfloaterimnearbychat.h"
#include "llfocusmgr.h"
#include "llkeybind.h" // LLKeyData
#include "llmorphview.h"
#include "llmoveview.h"
#include "lltoolfocus.h"
#include "lltoolpie.h"
#include "llviewercontrol.h"
#include "llviewerwindow.h"
#include "llvoavatarself.h"
#include "llfloatercamera.h"
#include "llinitparam.h"

//
// Constants
//

const F32 FLY_TIME = 0.5f;
const F32 FLY_FRAMES = 4;

const F32 NUDGE_TIME = 0.25f;  // in seconds
const S32 NUDGE_FRAMES = 2;
const F32 ORBIT_NUDGE_RATE = 0.05f;  // fraction of normal speed

const LLKeyData agent_control_lbutton(CLICK_LEFT, KEY_NONE, MASK_NONE, true);

struct LLKeyboardActionRegistry 
:	public LLRegistrySingleton<std::string, boost::function<bool (EKeystate keystate)>, LLKeyboardActionRegistry>
{
	LLSINGLETON_EMPTY_CTOR(LLKeyboardActionRegistry);
};

LLViewerInput gViewerInput;

bool agent_jump( EKeystate s )
{
	static BOOL first_fly_attempt(TRUE);
	if (KEYSTATE_UP == s)
	{
		first_fly_attempt = TRUE;
		return true;
	}
	F32 time = gKeyboard->getCurKeyElapsedTime();
	S32 frame_count = ll_round(gKeyboard->getCurKeyElapsedFrameCount());

	if( time < FLY_TIME 
		|| frame_count <= FLY_FRAMES 
		|| gAgent.upGrabbed()
		|| !gSavedSettings.getBOOL("AutomaticFly"))
	{
		gAgent.moveUp(1);
	}
	else
	{
		gAgent.setFlying(TRUE, first_fly_attempt);
		first_fly_attempt = FALSE;
		gAgent.moveUp(1);
	}
	return true;
}

bool agent_push_down( EKeystate s )
{
	if( KEYSTATE_UP == s  ) return true;
	gAgent.moveUp(-1);
	return true;
}

static void agent_check_temporary_run(LLAgent::EDoubleTapRunMode mode)
{
	if (gAgent.mDoubleTapRunMode == mode &&
		gAgent.getRunning() &&
		!gAgent.getAlwaysRun())
	{
		// Turn off temporary running.
		gAgent.clearRunning();
		gAgent.sendWalkRun(gAgent.getRunning());
	}
}

static void agent_handle_doubletap_run(EKeystate s, LLAgent::EDoubleTapRunMode mode)
{
	if (KEYSTATE_UP == s)
	{
		// Note: in case shift is already released, slide left/right run
		// will be released in agent_turn_left()/agent_turn_right()
		agent_check_temporary_run(mode);
	}
	else if (gSavedSettings.getBOOL("AllowTapTapHoldRun") &&
		 KEYSTATE_DOWN == s &&
		 !gAgent.getRunning())
	{
		if (gAgent.mDoubleTapRunMode == mode &&
		    gAgent.mDoubleTapRunTimer.getElapsedTimeF32() < NUDGE_TIME)
		{
			// Same walk-key was pushed again quickly; this is a
			// double-tap so engage temporary running.
			gAgent.setRunning();
			gAgent.sendWalkRun(gAgent.getRunning());
		}

		// Pressing any walk-key resets the double-tap timer
		gAgent.mDoubleTapRunTimer.reset();
		gAgent.mDoubleTapRunMode = mode;
	}
}

static void agent_push_forwardbackward( EKeystate s, S32 direction, LLAgent::EDoubleTapRunMode mode )
{
	agent_handle_doubletap_run(s, mode);
	if (KEYSTATE_UP == s) return;

	F32 time = gKeyboard->getCurKeyElapsedTime();
	S32 frame_count = ll_round(gKeyboard->getCurKeyElapsedFrameCount());

	if( time < NUDGE_TIME || frame_count <= NUDGE_FRAMES)
	{
		gAgent.moveAtNudge(direction);
	}
	else
	{
		gAgent.moveAt(direction);
	}
}

bool camera_move_forward( EKeystate s );

bool agent_push_forward( EKeystate s )
{
	if(gAgent.isMovementLocked()) return true;

	//in free camera control mode we need to intercept keyboard events for avatar movements
	if (LLFloaterCamera::inFreeCameraMode())
	{
		camera_move_forward(s);
	}
	else
	{
		agent_push_forwardbackward(s, 1, LLAgent::DOUBLETAP_FORWARD);
	}
	return true;
}

bool camera_move_backward( EKeystate s );

bool agent_push_backward( EKeystate s )
{
	if(gAgent.isMovementLocked()) return true;

	//in free camera control mode we need to intercept keyboard events for avatar movements
	if (LLFloaterCamera::inFreeCameraMode())
	{
		camera_move_backward(s);
	}
	else if (!gAgent.backwardGrabbed() && gAgentAvatarp->isSitting() && gSavedSettings.getBOOL("LeaveMouselook"))
	{
		gAgentCamera.changeCameraToThirdPerson();
	}
	else
	{
		agent_push_forwardbackward(s, -1, LLAgent::DOUBLETAP_BACKWARD);
	}
	return true;
}

static void agent_slide_leftright( EKeystate s, S32 direction, LLAgent::EDoubleTapRunMode mode )
{
	agent_handle_doubletap_run(s, mode);
	if( KEYSTATE_UP == s ) return;
	F32 time = gKeyboard->getCurKeyElapsedTime();
	S32 frame_count = ll_round(gKeyboard->getCurKeyElapsedFrameCount());

	if( time < NUDGE_TIME || frame_count <= NUDGE_FRAMES)
	{
		gAgent.moveLeftNudge(direction);
	}
	else
	{
		gAgent.moveLeft(direction);
	}
}


bool agent_slide_left( EKeystate s )
{
	if(gAgent.isMovementLocked()) return true;
	agent_slide_leftright(s, 1, LLAgent::DOUBLETAP_SLIDELEFT);
	return true;
}


bool agent_slide_right( EKeystate s )
{
	if(gAgent.isMovementLocked()) return true;
	agent_slide_leftright(s, -1, LLAgent::DOUBLETAP_SLIDERIGHT);
	return true;
}

bool camera_spin_around_cw( EKeystate s );

bool agent_turn_left(EKeystate s)
{
	//in free camera control mode we need to intercept keyboard events for avatar movements
	if (LLFloaterCamera::inFreeCameraMode())
	{
		camera_spin_around_cw(s);
		return true;
	}

	if(gAgent.isMovementLocked()) return false;

	if (LLToolCamera::getInstance()->mouseSteerMode())
	{
		agent_slide_left(s);
	}
	else
	{
		if (KEYSTATE_UP == s)
		{
			// Check temporary running. In case user released 'left' key with shift already released.
			agent_check_temporary_run(LLAgent::DOUBLETAP_SLIDELEFT);
			return true;
		}
		F32 time = gKeyboard->getCurKeyElapsedTime();
		gAgent.moveYaw( LLFloaterMove::getYawRate( time ) );
	}
	return true;
}

bool camera_spin_around_ccw( EKeystate s );

bool agent_turn_right( EKeystate s )
{
	//in free camera control mode we need to intercept keyboard events for avatar movements
	if (LLFloaterCamera::inFreeCameraMode())
	{
		camera_spin_around_ccw(s);
		return true;
	}

	if(gAgent.isMovementLocked()) return false;

	if (LLToolCamera::getInstance()->mouseSteerMode())
	{
		agent_slide_right(s);
	}
	else
	{
		if (KEYSTATE_UP == s)
		{
			// Check temporary running. In case user released 'right' key with shift already released.
			agent_check_temporary_run(LLAgent::DOUBLETAP_SLIDERIGHT);
			return true;
		}
		F32 time = gKeyboard->getCurKeyElapsedTime();
		gAgent.moveYaw( -LLFloaterMove::getYawRate( time ) );
	}
	return true;
}

bool agent_look_up( EKeystate s )
{
	if( KEYSTATE_UP == s  ) return true;
	gAgent.movePitch(-1);
	//gAgent.rotate(-2.f * DEG_TO_RAD, gAgent.getFrame().getLeftAxis() );
	return true;
}


bool agent_look_down( EKeystate s )
{
	if( KEYSTATE_UP == s  ) return true;
	gAgent.movePitch(1);
	//gAgent.rotate(2.f * DEG_TO_RAD, gAgent.getFrame().getLeftAxis() );
	return true;
}

bool agent_toggle_fly( EKeystate s )
{
	// Only catch the edge
	if (KEYSTATE_DOWN == s )
	{
		LLAgent::toggleFlying();
	}
	return true;
}

F32 get_orbit_rate()
{
	F32 time = gKeyboard->getCurKeyElapsedTime();
	if( time < NUDGE_TIME )
	{
		F32 rate = ORBIT_NUDGE_RATE + time * (1 - ORBIT_NUDGE_RATE)/ NUDGE_TIME;
		//LL_INFOS() << rate << LL_ENDL;
		return rate;
	}
	else
	{
		return 1;
	}
}

bool camera_spin_around_ccw( EKeystate s )
{
	if( KEYSTATE_UP == s  ) return true;
	gAgentCamera.unlockView();
	gAgentCamera.setOrbitLeftKey( get_orbit_rate() );
	return true;
}


bool camera_spin_around_cw( EKeystate s )
{
	if( KEYSTATE_UP == s  ) return true;
	gAgentCamera.unlockView();
	gAgentCamera.setOrbitRightKey( get_orbit_rate() );
	return true;
}

bool camera_spin_around_ccw_sitting( EKeystate s )
{
	if( KEYSTATE_UP == s && gAgent.mDoubleTapRunMode != LLAgent::DOUBLETAP_SLIDERIGHT ) return true;
	if (gAgent.rotateGrabbed() || gAgentCamera.sitCameraEnabled() || gAgent.getRunning())
	{
		//send keystrokes, but do not change camera
		agent_turn_right(s);
	}
	else
	{
		//change camera but do not send keystrokes
		gAgentCamera.setOrbitLeftKey( get_orbit_rate() );
	}
	return true;
}


bool camera_spin_around_cw_sitting( EKeystate s )
{
	if( KEYSTATE_UP == s && gAgent.mDoubleTapRunMode != LLAgent::DOUBLETAP_SLIDELEFT ) return true;
	if (gAgent.rotateGrabbed() || gAgentCamera.sitCameraEnabled() || gAgent.getRunning())
	{
		//send keystrokes, but do not change camera
		agent_turn_left(s);
	}
	else
	{
		//change camera but do not send keystrokes
		gAgentCamera.setOrbitRightKey( get_orbit_rate() );
	}
	return true;
}


bool camera_spin_over( EKeystate s )
{
	if( KEYSTATE_UP == s  ) return true;
	gAgentCamera.unlockView();
	gAgentCamera.setOrbitUpKey( get_orbit_rate() );
	return true;
}


bool camera_spin_under( EKeystate s )
{
	if( KEYSTATE_UP == s  ) return true;
	gAgentCamera.unlockView();
	gAgentCamera.setOrbitDownKey( get_orbit_rate() );
	return true;
}

bool camera_spin_over_sitting( EKeystate s )
{
	if( KEYSTATE_UP == s  ) return true;
	if (gAgent.upGrabbed() || gAgentCamera.sitCameraEnabled())
	{
		//send keystrokes, but do not change camera
		agent_jump(s);
	}
	else
	{
		//change camera but do not send keystrokes
		gAgentCamera.setOrbitUpKey( get_orbit_rate() );
	}
	return true;
}


bool camera_spin_under_sitting( EKeystate s )
{
	if( KEYSTATE_UP == s  ) return true;
	if (gAgent.downGrabbed() || gAgentCamera.sitCameraEnabled())
	{
		//send keystrokes, but do not change camera
		agent_push_down(s);
	}
	else
	{
		//change camera but do not send keystrokes
		gAgentCamera.setOrbitDownKey( get_orbit_rate() );
	}
	return true;
}

bool camera_move_forward( EKeystate s )
{
	if( KEYSTATE_UP == s  ) return true;
	gAgentCamera.unlockView();
	gAgentCamera.setOrbitInKey( get_orbit_rate() );
	return true;
}


bool camera_move_backward( EKeystate s )
{
	if( KEYSTATE_UP == s  ) return true;
	gAgentCamera.unlockView();
	gAgentCamera.setOrbitOutKey( get_orbit_rate() );
	return true;
}

bool camera_move_forward_sitting( EKeystate s )
{
	if( KEYSTATE_UP == s && gAgent.mDoubleTapRunMode != LLAgent::DOUBLETAP_FORWARD ) return true;
	if (gAgent.forwardGrabbed() || gAgentCamera.sitCameraEnabled() || (gAgent.getRunning() && !gAgent.getAlwaysRun()))
	{
		agent_push_forward(s);
	}
	else
	{
		gAgentCamera.setOrbitInKey( get_orbit_rate() );
	}
	return true;
}

bool camera_move_backward_sitting( EKeystate s )
{
	if( KEYSTATE_UP == s && gAgent.mDoubleTapRunMode != LLAgent::DOUBLETAP_BACKWARD ) return true;

	if (gAgent.backwardGrabbed() || gAgentCamera.sitCameraEnabled() || (gAgent.getRunning() && !gAgent.getAlwaysRun()))
	{
		agent_push_backward(s);
	}
	else
	{
		gAgentCamera.setOrbitOutKey( get_orbit_rate() );
	}
	return true;
}

bool camera_pan_up( EKeystate s )
{
	if( KEYSTATE_UP == s  ) return true;
	gAgentCamera.unlockView();
	gAgentCamera.setPanUpKey( get_orbit_rate() );
	return true;
}

bool camera_pan_down( EKeystate s )
{
	if( KEYSTATE_UP == s  ) return true;
	gAgentCamera.unlockView();
	gAgentCamera.setPanDownKey( get_orbit_rate() );
	return true;
}

bool camera_pan_left( EKeystate s )
{
	if( KEYSTATE_UP == s  ) return true;
	gAgentCamera.unlockView();
	gAgentCamera.setPanLeftKey( get_orbit_rate() );
	return true;
}

bool camera_pan_right( EKeystate s )
{
	if( KEYSTATE_UP == s  ) return true;
	gAgentCamera.unlockView();
	gAgentCamera.setPanRightKey( get_orbit_rate() );
	return true;
}

bool camera_pan_in( EKeystate s )
{
	if( KEYSTATE_UP == s  ) return true;
	gAgentCamera.unlockView();
	gAgentCamera.setPanInKey( get_orbit_rate() );
	return true;
}

bool camera_pan_out( EKeystate s )
{
	if( KEYSTATE_UP == s  ) return true;
	gAgentCamera.unlockView();
	gAgentCamera.setPanOutKey( get_orbit_rate() );
	return true;
}

bool camera_move_forward_fast( EKeystate s )
{
	if( KEYSTATE_UP == s  ) return true;
	gAgentCamera.unlockView();
	gAgentCamera.setOrbitInKey(2.5f);
	return true;
}

bool camera_move_backward_fast( EKeystate s )
{
	if( KEYSTATE_UP == s  ) return true;
	gAgentCamera.unlockView();
	gAgentCamera.setOrbitOutKey(2.5f);
	return true;
}


bool edit_avatar_spin_ccw( EKeystate s )
{
	if( KEYSTATE_UP == s  ) return true;
	gMorphView->setCameraDrivenByKeys( TRUE );
	gAgentCamera.setOrbitLeftKey( get_orbit_rate() );
	//gMorphView->orbitLeft( get_orbit_rate() );
	return true;
}


bool edit_avatar_spin_cw( EKeystate s )
{
	if( KEYSTATE_UP == s  ) return true;
	gMorphView->setCameraDrivenByKeys( TRUE );
	gAgentCamera.setOrbitRightKey( get_orbit_rate() );
	//gMorphView->orbitRight( get_orbit_rate() );
	return true;
}

bool edit_avatar_spin_over( EKeystate s )
{
	if( KEYSTATE_UP == s  ) return true;
	gMorphView->setCameraDrivenByKeys( TRUE );
	gAgentCamera.setOrbitUpKey( get_orbit_rate() );
	//gMorphView->orbitUp( get_orbit_rate() );
	return true;
}


bool edit_avatar_spin_under( EKeystate s )
{
	if( KEYSTATE_UP == s  ) return true;
	gMorphView->setCameraDrivenByKeys( TRUE );
	gAgentCamera.setOrbitDownKey( get_orbit_rate() );
	//gMorphView->orbitDown( get_orbit_rate() );
	return true;
}

bool edit_avatar_move_forward( EKeystate s )
{
	if( KEYSTATE_UP == s  ) return true;
	gMorphView->setCameraDrivenByKeys( TRUE );
	gAgentCamera.setOrbitInKey( get_orbit_rate() );
	//gMorphView->orbitIn();
	return true;
}


bool edit_avatar_move_backward( EKeystate s )
{
	if( KEYSTATE_UP == s  ) return true;
	gMorphView->setCameraDrivenByKeys( TRUE );
	gAgentCamera.setOrbitOutKey( get_orbit_rate() );
	//gMorphView->orbitOut();
	return true;
}

bool stop_moving( EKeystate s )
{
	if( KEYSTATE_DOWN != s  ) return true;
	// stop agent
	gAgent.setControlFlags(AGENT_CONTROL_STOP);

	// cancel autopilot
	gAgent.stopAutoPilot();
	return true;
}

bool start_chat( EKeystate s )
{
    if (LLAppViewer::instance()->quitRequested())
    {
        return true; // can't talk, gotta go, kthxbye!
    }
    if (KEYSTATE_DOWN != s) return true;

	// start chat
	LLFloaterIMNearbyChat::startChat(NULL);
	return true;
}

bool start_gesture( EKeystate s )
{
	LLUICtrl* focus_ctrlp = dynamic_cast<LLUICtrl*>(gFocusMgr.getKeyboardFocus());
	if (KEYSTATE_UP == s &&
		! (focus_ctrlp && focus_ctrlp->acceptsTextInput()))
	{
 		if ((LLFloaterReg::getTypedInstance<LLFloaterIMNearbyChat>("nearby_chat"))->getCurrentChat().empty())
 		{
 			// No existing chat in chat editor, insert '/'
 			LLFloaterIMNearbyChat::startChat("/");
 		}
 		else
 		{
 			// Don't overwrite existing text in chat editor
 			LLFloaterIMNearbyChat::startChat(NULL);
 		}
	}
	return true;
}

bool run_forward(EKeystate s)
{
    if (KEYSTATE_UP != s)
    {
        if (gAgent.mDoubleTapRunMode != LLAgent::DOUBLETAP_FORWARD)
        {
            gAgent.mDoubleTapRunMode = LLAgent::DOUBLETAP_FORWARD;
        }
        if (!gAgent.getRunning())
        {
            gAgent.setRunning();
            gAgent.sendWalkRun(true);
        }
    }
    else if(KEYSTATE_UP == s)
    {
        if (gAgent.mDoubleTapRunMode == LLAgent::DOUBLETAP_FORWARD)
            gAgent.mDoubleTapRunMode = LLAgent::DOUBLETAP_NONE;
        gAgent.clearRunning();
        gAgent.sendWalkRun(false);
    }
    agent_push_forward(s);
    return true;
}

bool run_backward(EKeystate s)
{
    if (KEYSTATE_UP != s)
    {
        if (gAgent.mDoubleTapRunMode != LLAgent::DOUBLETAP_BACKWARD)
        {
            gAgent.mDoubleTapRunMode = LLAgent::DOUBLETAP_BACKWARD;
        }
        if (!gAgent.getRunning())
        {
            gAgent.setRunning();
            gAgent.sendWalkRun(true);
        }
    }
    else if (KEYSTATE_UP == s)
    {
        if (gAgent.mDoubleTapRunMode == LLAgent::DOUBLETAP_BACKWARD)
            gAgent.mDoubleTapRunMode = LLAgent::DOUBLETAP_NONE;
        gAgent.clearRunning();
        gAgent.sendWalkRun(false);
    }
    agent_push_backward(s);
    return true;
}

bool run_left(EKeystate s)
{
    if (KEYSTATE_UP != s)
    {
        if (gAgent.mDoubleTapRunMode != LLAgent::DOUBLETAP_SLIDELEFT)
        {
            gAgent.mDoubleTapRunMode = LLAgent::DOUBLETAP_SLIDELEFT;
        }
        if (!gAgent.getRunning())
        {
            gAgent.setRunning();
            gAgent.sendWalkRun(true);
        }
    }
    else if (KEYSTATE_UP == s)
    {
        if (gAgent.mDoubleTapRunMode == LLAgent::DOUBLETAP_SLIDELEFT)
            gAgent.mDoubleTapRunMode = LLAgent::DOUBLETAP_NONE;
        gAgent.clearRunning();
        gAgent.sendWalkRun(false);
    }
    agent_slide_left(s);
    return true;
}

bool run_right(EKeystate s)
{
    if (KEYSTATE_UP != s)
    {
        if (gAgent.mDoubleTapRunMode != LLAgent::DOUBLETAP_SLIDERIGHT)
        {
            gAgent.mDoubleTapRunMode = LLAgent::DOUBLETAP_SLIDERIGHT;
        }
        if (!gAgent.getRunning())
        {
            gAgent.setRunning();
            gAgent.sendWalkRun(true);
        }
    }
    else if (KEYSTATE_UP == s)
    {
        if (gAgent.mDoubleTapRunMode == LLAgent::DOUBLETAP_SLIDERIGHT)
            gAgent.mDoubleTapRunMode = LLAgent::DOUBLETAP_NONE;
        gAgent.clearRunning();
        gAgent.sendWalkRun(false);
    }
    agent_slide_right(s);
    return true;
}

bool toggle_run(EKeystate s)
{
    if (KEYSTATE_DOWN != s) return true;
    bool run = gAgent.getAlwaysRun();
    if (run)
    {
        gAgent.clearAlwaysRun();
        gAgent.clearRunning();
    }
    else
    {
        gAgent.setAlwaysRun();
        gAgent.setRunning();
    }
    gAgent.sendWalkRun(!run);
	return true;
}

bool toggle_sit(EKeystate s)
{
    if (KEYSTATE_DOWN != s) return true;
    if (gAgent.isSitting())
    {
        gAgent.standUp();
    }
    else
    {
        gAgent.sitDown();
    }
	return true;
}

bool toggle_pause_media(EKeystate s) // analogue of play/pause button in top bar
{
    if (KEYSTATE_DOWN != s) return true;
    bool pause = LLViewerMedia::getInstance()->isAnyMediaPlaying();
    LLViewerMedia::getInstance()->setAllMediaPaused(pause);
    return true;
}

bool toggle_enable_media(EKeystate s)
{
    if (KEYSTATE_DOWN != s) return true;
    bool pause = LLViewerMedia::getInstance()->isAnyMediaPlaying() || LLViewerMedia::getInstance()->isAnyMediaShowing();
    LLViewerMedia::getInstance()->setAllMediaEnabled(!pause);
    return true;
}

bool walk_to(EKeystate s)
{
    if (KEYSTATE_DOWN != s) return true;
    return LLToolPie::getInstance()->walkToClickedLocation();
}

bool teleport_to(EKeystate s)
{
    if (KEYSTATE_DOWN != s) return true;
    return LLToolPie::getInstance()->teleportToClickedLocation();
}

bool toggle_voice(EKeystate s)
{
    if (KEYSTATE_DOWN != s) return true;
    if (!LLAgent::isActionAllowed("speak")) return false;
    LLVoiceClient::getInstance()->toggleUserPTTState();
    return true;
}

bool voice_follow_key(EKeystate s)
{
    if (KEYSTATE_DOWN == s)
    {
        if (!LLAgent::isActionAllowed("speak")) return false;
        LLVoiceClient::getInstance()->setUserPTTState(true);
        return true;
    }
    else if (KEYSTATE_UP == s && LLVoiceClient::getInstance()->getUserPTTState())
    {
        LLVoiceClient::getInstance()->setUserPTTState(false);
        return true;
    }
    return false;
}

bool agen_control_lbutton_handle(EKeystate s)
{
    switch (s)
    {
    case KEYSTATE_DOWN:
        gAgent.setControlFlags(AGENT_CONTROL_LBUTTON_DOWN);
        break;
    case KEYSTATE_UP:
        gAgent.setControlFlags(AGENT_CONTROL_LBUTTON_UP);
        break;
    default:
        break;
    }
    return true;
}

#define REGISTER_KEYBOARD_ACTION(KEY, ACTION) LLREGISTER_STATIC(LLKeyboardActionRegistry, KEY, ACTION);
REGISTER_KEYBOARD_ACTION("jump", agent_jump);
REGISTER_KEYBOARD_ACTION("push_down", agent_push_down);
REGISTER_KEYBOARD_ACTION("push_forward", agent_push_forward);
REGISTER_KEYBOARD_ACTION("push_backward", agent_push_backward);
REGISTER_KEYBOARD_ACTION("look_up", agent_look_up);
REGISTER_KEYBOARD_ACTION("look_down", agent_look_down);
REGISTER_KEYBOARD_ACTION("toggle_fly", agent_toggle_fly);
REGISTER_KEYBOARD_ACTION("turn_left", agent_turn_left);
REGISTER_KEYBOARD_ACTION("turn_right", agent_turn_right);
REGISTER_KEYBOARD_ACTION("slide_left", agent_slide_left);
REGISTER_KEYBOARD_ACTION("slide_right", agent_slide_right);
REGISTER_KEYBOARD_ACTION("spin_around_ccw", camera_spin_around_ccw);
REGISTER_KEYBOARD_ACTION("spin_around_cw", camera_spin_around_cw);
REGISTER_KEYBOARD_ACTION("spin_around_ccw_sitting", camera_spin_around_ccw_sitting);
REGISTER_KEYBOARD_ACTION("spin_around_cw_sitting", camera_spin_around_cw_sitting);
REGISTER_KEYBOARD_ACTION("spin_over", camera_spin_over);
REGISTER_KEYBOARD_ACTION("spin_under", camera_spin_under);
REGISTER_KEYBOARD_ACTION("spin_over_sitting", camera_spin_over_sitting);
REGISTER_KEYBOARD_ACTION("spin_under_sitting", camera_spin_under_sitting);
REGISTER_KEYBOARD_ACTION("move_forward", camera_move_forward);
REGISTER_KEYBOARD_ACTION("move_backward", camera_move_backward);
REGISTER_KEYBOARD_ACTION("move_forward_sitting", camera_move_forward_sitting);
REGISTER_KEYBOARD_ACTION("move_backward_sitting", camera_move_backward_sitting);
REGISTER_KEYBOARD_ACTION("pan_up", camera_pan_up);
REGISTER_KEYBOARD_ACTION("pan_down", camera_pan_down);
REGISTER_KEYBOARD_ACTION("pan_left", camera_pan_left);
REGISTER_KEYBOARD_ACTION("pan_right", camera_pan_right);
REGISTER_KEYBOARD_ACTION("pan_in", camera_pan_in);
REGISTER_KEYBOARD_ACTION("pan_out", camera_pan_out);
REGISTER_KEYBOARD_ACTION("move_forward_fast", camera_move_forward_fast);
REGISTER_KEYBOARD_ACTION("move_backward_fast", camera_move_backward_fast);
REGISTER_KEYBOARD_ACTION("edit_avatar_spin_ccw", edit_avatar_spin_ccw);
REGISTER_KEYBOARD_ACTION("edit_avatar_spin_cw", edit_avatar_spin_cw);
REGISTER_KEYBOARD_ACTION("edit_avatar_spin_over", edit_avatar_spin_over);
REGISTER_KEYBOARD_ACTION("edit_avatar_spin_under", edit_avatar_spin_under);
REGISTER_KEYBOARD_ACTION("edit_avatar_move_forward", edit_avatar_move_forward);
REGISTER_KEYBOARD_ACTION("edit_avatar_move_backward", edit_avatar_move_backward);
REGISTER_KEYBOARD_ACTION("stop_moving", stop_moving);
REGISTER_KEYBOARD_ACTION("start_chat", start_chat);
REGISTER_KEYBOARD_ACTION("start_gesture", start_gesture);
REGISTER_KEYBOARD_ACTION("run_forward", run_forward);
REGISTER_KEYBOARD_ACTION("run_backward", run_backward);
REGISTER_KEYBOARD_ACTION("run_left", run_left);
REGISTER_KEYBOARD_ACTION("run_right", run_right);
REGISTER_KEYBOARD_ACTION("toggle_run", toggle_run);
REGISTER_KEYBOARD_ACTION("toggle_sit", toggle_sit);
REGISTER_KEYBOARD_ACTION("toggle_pause_media", toggle_pause_media);
REGISTER_KEYBOARD_ACTION("toggle_enable_media", toggle_enable_media);
REGISTER_KEYBOARD_ACTION("teleport_to", teleport_to);
REGISTER_KEYBOARD_ACTION("walk_to", walk_to);
REGISTER_KEYBOARD_ACTION("toggle_voice", toggle_voice);
REGISTER_KEYBOARD_ACTION("voice_follow_key", voice_follow_key);
#undef REGISTER_KEYBOARD_ACTION

LLViewerInput::LLViewerInput()
{
    resetBindings();

	for (S32 i = 0; i < KEY_COUNT; i++)
	{
		mKeyHandledByUI[i] = FALSE;
    }
    for (S32 i = 0; i < CLICK_COUNT; i++)
    {
        mMouseLevel[i] = MOUSE_STATE_SILENT;
    }
	// we want the UI to never see these keys so that they can always control the avatar/camera
	for(KEY k = KEY_PAD_UP; k <= KEY_PAD_DIVIDE; k++) 
	{
		mKeysSkippedByUI.insert(k);	
	}
}

// static
BOOL LLViewerInput::modeFromString(const std::string& string, S32 *mode)
{
	if (string == "FIRST_PERSON")
	{
		*mode = MODE_FIRST_PERSON;
		return TRUE;
	}
	else if (string == "THIRD_PERSON")
	{
		*mode = MODE_THIRD_PERSON;
		return TRUE;
	}
	else if (string == "EDIT_AVATAR")
	{
		*mode = MODE_EDIT_AVATAR;
		return TRUE;
	}
	else if (string == "SITTING")
	{
		*mode = MODE_SITTING;
		return TRUE;
	}
	else
	{
		*mode = MODE_THIRD_PERSON;
		return FALSE;
	}
}

// static
BOOL LLViewerInput::mouseFromString(const std::string& string, EMouseClickType *mode)
{
    if (string == "LMB")
    {
        *mode = CLICK_LEFT;
        return TRUE;
    }
    else if (string == "Double LMB")
    {
        *mode = CLICK_DOUBLELEFT;
        return TRUE;
    }
    else if (string == "MMB")
    {
        *mode = CLICK_MIDDLE;
        return TRUE;
    }
    else if (string == "MB4")
    {
        *mode = CLICK_BUTTON4;
        return TRUE;
    }
    else if (string == "MB5")
    {
        *mode = CLICK_BUTTON5;
        return TRUE;
    }
    else
    {
        *mode = CLICK_NONE;
        return FALSE;
    }
}

BOOL LLViewerInput::handleKey(KEY translated_key, MASK translated_mask, BOOL repeated)
{
	// check for re-map
	EKeyboardMode mode = gViewerInput.getMode();
	U32 keyidx = (translated_mask<<16) | translated_key;
	key_remap_t::iterator iter = mRemapKeys[mode].find(keyidx);
	if (iter != mRemapKeys[mode].end())
	{
		translated_key = (iter->second) & 0xff;
		translated_mask = (iter->second)>>16;
	}

	// No repeats of F-keys
	BOOL repeatable_key = (translated_key < KEY_F1 || translated_key > KEY_F12);
	if (!repeatable_key && repeated)
	{
		return FALSE;
	}

	LL_DEBUGS("UserInput") << "keydown -" << translated_key << "-" << LL_ENDL;
	// skip skipped keys
	if(mKeysSkippedByUI.find(translated_key) != mKeysSkippedByUI.end()) 
	{
		mKeyHandledByUI[translated_key] = FALSE;
		LL_INFOS("KeyboardHandling") << "Key wasn't handled by UI!" << LL_ENDL;
	}
	else
	{
		// it is sufficient to set this value once per call to handlekey
		// without clearing it, as it is only used in the subsequent call to scanKey
		mKeyHandledByUI[translated_key] = gViewerWindow->handleKey(translated_key, translated_mask); 
		// mKeyHandledByUI is not what you think ... this indicates whether the UI has handled this keypress yet (any keypress)
		// NOT whether some UI shortcut wishes to handle the keypress
	  
	}
	return mKeyHandledByUI[translated_key];
}

BOOL LLViewerInput::handleKeyUp(KEY translated_key, MASK translated_mask)
{
	return gViewerWindow->handleKeyUp(translated_key, translated_mask);
}

BOOL LLViewerInput::bindKey(const S32 mode, const KEY key, const MASK mask, const std::string& function_name)
{
	S32 index;
	typedef boost::function<bool(EKeystate)> function_t;
	function_t function = NULL;
	std::string name;

	// Allow remapping of F2-F12
	if (function_name[0] == 'F')
	{
		int c1 = function_name[1] - '0';
		int c2 = function_name[2] ? function_name[2] - '0' : -1;
		if (c1 >= 0 && c1 <= 9 && c2 >= -1 && c2 <= 9)
		{
			int idx = c1;
			if (c2 >= 0)
				idx = idx*10 + c2;
			if (idx >=2 && idx <= 12)
			{
				U32 keyidx = ((mask<<16)|key);
				(mRemapKeys[mode])[keyidx] = ((0<<16)|(KEY_F1+(idx-1)));
				return TRUE;
			}
		}
	}

	// Not remapped, look for a function
	
	function_t* result = LLKeyboardActionRegistry::getValue(function_name);
	if (result)
	{
		function = *result;
	}

	if (!function)
	{
		LL_ERRS() << "Can't bind key to function " << function_name << ", no function with this name found" << LL_ENDL;
		return FALSE;
	}

	// check for duplicate first and overwrite
    S32 size = mKeyBindings[mode].size();
    for (index = 0; index < size; index++)
    {
        if (key == mKeyBindings[mode][index].mKey && mask == mKeyBindings[mode][index].mMask)
            break;
    }

	if (mode >= MODE_COUNT)
	{
		LL_ERRS() << "LLKeyboard::bindKey() - unknown mode passed" << mode << LL_ENDL;
		return FALSE;
	}

    LLKeyboardBinding bind;
    bind.mKey = key;
    bind.mMask = mask;
    bind.mFunction = function;

    mKeyBindings[mode].push_back(bind);

	return TRUE;
}

BOOL LLViewerInput::bindMouse(const S32 mode, const EMouseClickType mouse, const MASK mask, const std::string& function_name)
{
    S32 index;
    typedef boost::function<bool(EKeystate)> function_t;
    function_t function = NULL;

    function_t* result = LLKeyboardActionRegistry::getValue(function_name);
    if (result)
    {
        function = *result;
    }

    if (!function)
    {
        LL_ERRS() << "Can't bind key to function " << function_name << ", no function with this name found" << LL_ENDL;
        return FALSE;
    }

    // check for duplicate first and overwrite
    S32 size = mMouseBindings[mode].size();
    for (index = 0; index < size; index++)
    {
        if (mouse == mMouseBindings[mode][index].mMouse && mask == mMouseBindings[mode][index].mMask)
            break;
    }

    if (mode >= MODE_COUNT)
    {
        LL_ERRS() << "LLKeyboard::bindKey() - unknown mode passed" << mode << LL_ENDL;
        return FALSE;
    }

    LLMouseBinding bind;
    bind.mMouse = mouse;
    bind.mMask = mask;
    bind.mFunction = function;

    mMouseBindings[mode].push_back(bind);

    return TRUE;
}

LLViewerInput::KeyBinding::KeyBinding()
:	key("key"),
	mouse("mouse"),
	mask("mask"),
	command("command")
{}

LLViewerInput::KeyMode::KeyMode()
:	bindings("binding")
{}

LLViewerInput::Keys::Keys()
:	first_person("first_person"),
	third_person("third_person"),
	sitting("sitting"),
	edit_avatar("edit_avatar")
{}

void LLViewerInput::resetBindings()
{
    for (S32 i = 0; i < MODE_COUNT; i++)
    {
        mKeyBindings[i].clear();
        mMouseBindings[i].clear();
    }
}

S32 LLViewerInput::loadBindingsXML(const std::string& filename)
{
    resetBindings();

	S32 binding_count = 0;
	Keys keys;
	LLSimpleXUIParser parser;

	if (parser.readXUI(filename, keys) 
		&& keys.validateBlock())
	{
		binding_count += loadBindingMode(keys.first_person, MODE_FIRST_PERSON);
		binding_count += loadBindingMode(keys.third_person, MODE_THIRD_PERSON);
		binding_count += loadBindingMode(keys.sitting, MODE_SITTING);
		binding_count += loadBindingMode(keys.edit_avatar, MODE_EDIT_AVATAR);
	}
	return binding_count;
}

S32 count_masks(const MASK &mask)
{
    S32 res = 0;
    if (mask & MASK_CONTROL)
    {
        res++;
    }
    if (mask & MASK_SHIFT)
    {
        res++;
    }
    if (mask & MASK_ALT)
    {
        res++;
    }
    return res;
}

bool compare_key_by_mask(LLKeyboardBinding i1, LLKeyboardBinding i2)
{
    return (count_masks(i1.mMask) > count_masks(i2.mMask));
}

bool compare_mouse_by_mask(LLMouseBinding i1, LLMouseBinding i2)
{
    return (count_masks(i1.mMask) > count_masks(i2.mMask));
}

S32 LLViewerInput::loadBindingMode(const LLViewerInput::KeyMode& keymode, S32 mode)
{
	S32 binding_count = 0;
	for (LLInitParam::ParamIterator<KeyBinding>::const_iterator it = keymode.bindings.begin(), 
			end_it = keymode.bindings.end();
		it != end_it;
		++it)
	{
        bool processed = false;
        std::string key_str = it->key.getValue();
        if (!key_str.empty() && key_str != "NONE")
        {
            KEY key;
            LLKeyboard::keyFromString(key_str, &key);
            if (key != KEY_NONE)
            {
                MASK mask;
                LLKeyboard::maskFromString(it->mask, &mask);
                bindKey(mode, key, mask, it->command);
                processed = true;
            }
            else
            {
                LL_WARNS_ONCE() << "There might be issues in keybindings' file" << LL_ENDL;
            }
        }
        if (!processed && it->mouse.isProvided() && !it->mouse.getValue().empty())
        {
            EMouseClickType mouse;
            mouseFromString(it->mouse.getValue(), &mouse);
            if (mouse != CLICK_NONE)
            {
                MASK mask;
                LLKeyboard::maskFromString(it->mask, &mask);
                bindMouse(mode, mouse, mask, it->command);
                processed = true;
            }
            else
            {
                LL_WARNS_ONCE() << "There might be issues in keybindings' file" << LL_ENDL;
            }
        }
        if (processed)
        {
            // total
            binding_count++;
        }
    }

    // sort lists by mask (so that Shift+W is executed before W, if both are assigned, but if Shift+W is not assigned W should be executed)
    std::sort(mKeyBindings[mode].begin(), mKeyBindings[mode].end(), compare_key_by_mask);
    std::sort(mMouseBindings[mode].begin(), mMouseBindings[mode].end(), compare_mouse_by_mask);

	return binding_count;
}

EKeyboardMode LLViewerInput::getMode() const
{
	if ( gAgentCamera.cameraMouselook() )
	{
		return MODE_FIRST_PERSON;
	}
	else if ( gMorphView && gMorphView->getVisible())
	{
		return MODE_EDIT_AVATAR;
	}
	else if (isAgentAvatarValid() && gAgentAvatarp->isSitting())
	{
		return MODE_SITTING;
	}
	else
	{
		return MODE_THIRD_PERSON;
	}
}

bool LLViewerInput::scanKey(const std::vector<LLKeyboardBinding> &binding,
                               S32 binding_count,
                               KEY key,
                               MASK mask,
                               BOOL key_down,
                               BOOL key_up,
                               BOOL key_level,
                               bool repeat) const
{
	for (S32 i = 0; i < binding_count; i++)
	{
		if (binding[i].mKey == key)
		{
			if ((binding[i].mMask & mask) == binding[i].mMask)
			{
				bool res = false;
				if (key_down && !repeat)
				{
					// ...key went down this frame, call function
					res = binding[i].mFunction( KEYSTATE_DOWN );
					return true;
				}
				else if (key_up)
				{
					// ...key went down this frame, call function
					res = binding[i].mFunction( KEYSTATE_UP );
				}
				else if (key_level)
				{
					// ...key held down from previous frame
					// Not windows, just call the function.
					res = binding[i].mFunction( KEYSTATE_LEVEL );
				}//if
				// Key+Mask combinations are supposed to be unique, so we won't find anything else
				return res;
			}//if
		}//if
	}//for
	return false;
}

// Called from scanKeyboard.
bool LLViewerInput::scanKey(KEY key, BOOL key_down, BOOL key_up, BOOL key_level) const
{
	if (LLApp::isExiting())
	{
		return false;
	}

	S32 mode = getMode();
	// Consider keyboard scanning as NOT mouse event. JC
	MASK mask = gKeyboard->currentMask(FALSE);

	if (mKeyHandledByUI[key])
	{
		return false;
	}

	// don't process key down on repeated keys
	BOOL repeat = gKeyboard->getKeyRepeated(key);

    bool res = scanKey(mKeyBindings[mode], mKeyBindings[mode].size(), key, mask, key_down, key_up, key_level, repeat);

    if (!res && agent_control_lbutton.canHandle(CLICK_NONE, key, mask))
    {
        if (key_down && !repeat)
        {
            res = agen_control_lbutton_handle(KEYSTATE_DOWN);
        }
        if (key_up)
        {
            res = agen_control_lbutton_handle(KEYSTATE_UP);
        }
    }
    return res;
}

BOOL LLViewerInput::handleMouse(LLWindow *window_impl, LLCoordGL pos, MASK mask, EMouseClickType clicktype, BOOL down)
{
    BOOL handled = gViewerWindow->handleAnyMouseClick(window_impl, pos, mask, clicktype, down);

    if (clicktype != CLICK_NONE)
    {
        // Special case
        // If UI doesn't handle double click, LMB click is issued, so supres LMB 'down' when doubleclick is set
        // handle !down as if we are handling doubleclick

        bool double_click_sp = (clicktype == CLICK_LEFT
            && (mMouseLevel[CLICK_DOUBLELEFT] != MOUSE_STATE_SILENT)
            && mMouseLevel[CLICK_LEFT] == MOUSE_STATE_SILENT);
        if (double_click_sp && !down)
        {
            // Process doubleclick instead
            clicktype = CLICK_DOUBLELEFT;
        }


        if (double_click_sp && down)
        {
            // Consume click.
            // Due to handling, double click that is not handled will be immediately followed by LMB click
        }
        // If UI handled 'down', it should handle 'up' as well
        // If we handle 'down' not by UI, then we should handle 'up'/'level' regardless of UI
        else if (handled)
        {
            // UI handled new 'down' so iterupt whatever state we were in.
            if (mMouseLevel[clicktype] != MOUSE_STATE_SILENT)
            {
                if (mMouseLevel[clicktype] == MOUSE_STATE_DOWN)
                {
                    mMouseLevel[clicktype] = MOUSE_STATE_CLICK;
                }
                else
                {
                    mMouseLevel[clicktype] = MOUSE_STATE_UP;
                }
            }
        }
        else if (down)
        {
            if (mMouseLevel[clicktype] == MOUSE_STATE_DOWN)
            {
                // this is repeated hit (mouse does not repeat event until release)
                // for now treat rapid clicking like mouse being held
                mMouseLevel[clicktype] = MOUSE_STATE_LEVEL;
            }
            else
            {
                mMouseLevel[clicktype] = MOUSE_STATE_DOWN;
            }
        }
        else if (mMouseLevel[clicktype] != MOUSE_STATE_SILENT)
        {
            // Released mouse key
            if (mMouseLevel[clicktype] == MOUSE_STATE_DOWN)
            {
                mMouseLevel[clicktype] = MOUSE_STATE_CLICK;
            }
            else 
            {
                mMouseLevel[clicktype] = MOUSE_STATE_UP;
            }
        }
    }

    return handled;
}

bool LLViewerInput::scanMouse(const std::vector<LLMouseBinding> &binding, S32 binding_count, EMouseClickType mouse, MASK mask, EMouseState state) const
{
    for (S32 i = 0; i < binding_count; i++)
    {
        if (binding[i].mMouse == mouse && (binding[i].mMask & mask) == binding[i].mMask)
        {
            bool res = false;
            switch (state)
            {
            case MOUSE_STATE_DOWN:
                res = binding[i].mFunction(KEYSTATE_DOWN);
                break;
            case MOUSE_STATE_CLICK:
                // Button went down and up in scope of single frame
                // might not work best with some functions,
                // but some function need specific states specifically
                res = binding[i].mFunction(KEYSTATE_DOWN);
                res |= binding[i].mFunction(KEYSTATE_UP);
                break;
            case MOUSE_STATE_LEVEL:
                res = binding[i].mFunction(KEYSTATE_LEVEL);
                break;
            case MOUSE_STATE_UP:
                res = binding[i].mFunction(KEYSTATE_UP);
                break;
            default:
                break;
            }
            // Key+Mask combinations are supposed to be unique, no need to continue
            return res;
        }
    }
    return false;
}

// todo: this recods key, scanMouse() triggers functions with EKeystate
bool LLViewerInput::scanMouse(EMouseClickType click, EMouseState state) const
{
    bool res = false;
    S32 mode = getMode();
    MASK mask = gKeyboard->currentMask(TRUE);
    res = scanMouse(mMouseBindings[mode], mMouseBindings[mode].size(), click, mask, state);
    // no user defined actions found or those actions can't handle the key/button, handle control if nessesary
    if (!res && agent_control_lbutton.canHandle(click, KEY_NONE, mask))
    {
        switch (state)
        {
        case MOUSE_STATE_DOWN:
            agen_control_lbutton_handle(KEYSTATE_DOWN);
            res = true;
            break;
        case MOUSE_STATE_CLICK:
            // might not work best with some functions,
            // but some function need specific states too specifically
            agen_control_lbutton_handle(KEYSTATE_DOWN);
            agen_control_lbutton_handle(KEYSTATE_UP);
            res = true;
            break;
        case MOUSE_STATE_UP:
            agen_control_lbutton_handle(KEYSTATE_UP);
            res = true;
            break;
        default:
            break;
        }
    }
    return res;
}

void LLViewerInput::scanMouse()
{
    for (S32 i = 0; i < CLICK_COUNT; i++)
    {
        if (mMouseLevel[i] != MOUSE_STATE_SILENT)
        {
            scanMouse((EMouseClickType)i, mMouseLevel[i]);
            if (mMouseLevel[i] == MOUSE_STATE_DOWN)
            {
                // mouse doesn't support 'continued' state, so after handling, switch to LEVEL
                mMouseLevel[i] = MOUSE_STATE_LEVEL;
            }
            else if (mMouseLevel[i] == MOUSE_STATE_UP || mMouseLevel[i] == MOUSE_STATE_CLICK)
            {
                mMouseLevel[i] = MOUSE_STATE_SILENT;
            }
        }
    }
}