-
Notifications
You must be signed in to change notification settings - Fork 15
/
imgui_keybindmenu.cpp
1537 lines (1307 loc) · 58.5 KB
/
imgui_keybindmenu.cpp
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
/*
* Prototype of a keybinding menu. Searching for "Doom3" should give you most of the places
* in the code that need to be adjusted when integrating this in a real game.
*
* This code assumes that each key is bound to either one command (or action) or none at all.
* IMHO this is a reasonable assumption to make (and true in Doom3), but if your game (or whatever)
* allows binding the same key to multiple commands at the same time, that will require many changes.
*
* Based on ImGui's example code for SDL2 + classic OpenGL (because Doom3 uses OpenGL 1.4).
* The keybinding menu doesn't interact with OpenGL directly, so that part is easy to change,
* but I added some hacks in the SDL2-specific code (gamepadStartPressed and hadKeyDownEvent)
* that must be ported for different input backends.
*
* To build, you also need the following source files from Dear ImGui 1.90.6 or 1.91.2 (other versions
* might work, but those have been tested):
* imgui.cpp imgui_demo.cpp imgui_draw.cpp imgui_tables.cpp imgui_widgets.cpp
* backends/imgui_impl_sdl2.cpp backends/imgui_impl_opengl2.cpp
* Furthermore you need to add the imgui root directory (that contains imgui.h) and its backends/
* to the header-search directories (-I option in GCC/clang)
* Or you just replace examples/example_sdl2_opengl2/main.cpp with this file and build and run that
* example.
*
* (C) 2024 Daniel Gibson
*
* Released under MIT license, like Dear ImGui
*/
// Dear ImGui: standalone example application for SDL2 + OpenGL
// (SDL is a cross-platform general purpose library for handling windows, inputs, OpenGL/Vulkan/Metal graphics context creation, etc.)
// Learn about Dear ImGui:
// - FAQ https://dearimgui.com/faq
// - Getting Started https://dearimgui.com/getting-started
// - Documentation https://dearimgui.com/docs (same as your local docs/ folder).
// - Introduction, links and more at the top of imgui.cpp
// **DO NOT USE THIS CODE IF YOUR CODE/ENGINE IS USING MODERN OPENGL (SHADERS, VBO, VAO, etc.)**
// **Prefer using the code in the example_sdl2_opengl3/ folder**
// See imgui_impl_sdl2.cpp for details.
#define IMGUI_DEFINE_MATH_OPERATORS
#include "imgui.h"
#include "imgui_internal.h"
#include "imgui_impl_sdl2.h"
#include "imgui_impl_opengl2.h"
#include <stdio.h>
#include <SDL.h>
#include <SDL_opengl.h>
#include <string>
#include <vector>
// emulate idStr..
class idStr : public std::string {
public:
idStr() = default;
idStr(const char* s) : std::string(s) {}
int Length() const {
return (int)length();
}
operator const char* (void) const {
return c_str();
}
static idStr Format( const char* format, ... );
static idStr VFormat( const char* format, va_list argptr );
};
idStr idStr::Format( const char* format, ... )
{
va_list argptr;
va_start( argptr, format );
idStr ret = VFormat( format, argptr );
va_end( argptr );
return ret;
}
idStr idStr::VFormat( const char* format, va_list argptr )
{
idStr ret;
int len;
va_list argptrcopy;
char buffer[16000];
// make a copy of argptr in case we need to call vsnprintf() again after truncation
#ifdef va_copy // IIRC older VS versions didn't have this?
va_copy( argptrcopy, argptr );
#else
argptrcopy = argptr;
#endif
len = vsnprintf( buffer, sizeof(buffer), format, argptr );
if ( len < (int)sizeof(buffer) ) {
ret = buffer;
} else {
// string was truncated, because buffer wasn't big enough.
ret.resize( len );
vsnprintf( &ret[0], len+1, format, argptrcopy );
}
va_end( argptrcopy );
return ret;
}
// add tooltip with given text to the previously added widget (visible if that item is hovered)
static void AddTooltip( const char* text )
{
if ( ImGui::BeginItemTooltip() )
{
ImGui::PushTextWrapPos( ImGui::GetFontSize() * 35.0f );
ImGui::TextUnformatted( text );
ImGui::PopTextWrapPos();
ImGui::EndTooltip();
}
}
// add a grey "(?)" that can be hovered for a tooltip with a description
// (or similar additional information)
static void AddDescrTooltip( const char* description )
{
if ( description != nullptr ) {
ImGui::SameLine();
ImGui::TextDisabled( "(?)" );
AddTooltip( description );
}
}
// was there a key down or button (mouse/gamepad) down event this frame?
// used to make the warning overlay disappear
static bool hadKeyDownEvent = false;
// for special case in IsCancelKeyPressed()
static bool gamepadStartPressed = false;
static idStr warningOverlayText;
static double warningOverlayStartTime = -100.0;
static ImVec2 warningOverlayStartPos;
static float blaScale = 1.0f;
static void UpdateWarningOverlay()
{
double timeNow = ImGui::GetTime();
if ( timeNow - warningOverlayStartTime > 4.0f ) {
return;
}
// also hide if a key was pressed or maybe even if the mouse was moved (too much)
ImVec2 mdv = ImGui::GetMousePos() - warningOverlayStartPos; // Mouse Delta Vector
float mouseDelta = sqrtf( mdv.x * mdv.x + mdv.y * mdv.y );
const float fontSize = ImGui::GetFontSize();
if ( mouseDelta > fontSize * 4.0f || hadKeyDownEvent ) {
warningOverlayStartTime = -100.0f;
return;
}
ImGui::SetNextWindowPos(ImGui::GetMainViewport()->GetCenter(), ImGuiCond_Always, ImVec2(0.5f, 0.5f));
ImGui::PushStyleColor( ImGuiCol_WindowBg, ImVec4(1.0f, 0.4f, 0.4f, 0.4f) );
float padSize = fontSize * 2.0f;
ImGui::PushStyleVar( ImGuiStyleVar_WindowPadding, ImVec2(padSize, padSize) );
int winFlags = ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove
| ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_AlwaysAutoResize;
ImGui::Begin("WarningOverlay", NULL, winFlags);
ImDrawList* drawList = ImGui::GetWindowDrawList();
ImVec2 points[] = {
{0, 40}, {40, 40}, {20, 0}, // triangle
{20, 12}, {20, 28}, // line
{20, 33} // dot
};
float iconScale = blaScale; // TODO: global scale also used for fontsize
ImVec2 offset = ImGui::GetWindowPos() + ImVec2(fontSize, fontSize);
for ( ImVec2& v : points ) {
v.x = roundf( v.x * iconScale );
v.y = roundf( v.y * iconScale );
v += offset;
}
ImU32 color = ImGui::GetColorU32( ImVec4(0.1f, 0.1f, 0.1f, 1.0f) );
//drawList->AddPolyline( points, 3, color, ImDrawFlags_RoundCornersAll | ImDrawFlags_Closed,
// roundf( iconScale * 4.0f ) );
drawList->AddTriangle( points[0], points[1], points[2], color, roundf( iconScale * 4.0f ) );
drawList->AddPolyline( points+3, 2, color, 0, roundf( iconScale * 3.0f ) );
float dotRadius = 2.0f * iconScale;
drawList->AddEllipseFilled( points[5], ImVec2(dotRadius, dotRadius), color, 0, 6 );
ImGui::Indent( 40.0f * iconScale );
ImGui::TextUnformatted( warningOverlayText.c_str() );
ImGui::End();
ImGui::PopStyleVar(); // WindowPadding
ImGui::PopStyleColor(); // WindowBg
}
static void ShowWarningOverlay( const char* text )
{
warningOverlayText = text;
warningOverlayStartTime = ImGui::GetTime();
warningOverlayStartPos = ImGui::GetMousePos();
}
static bool IsKeyPressed( ImGuiKey key ) {
return ImGui::IsKeyPressed( key, false );
}
// Enter or gamepad A, used to confirm or (when a binding table entry is focused/selected) to start binding a key
static bool IsConfirmKeyPressed() {
return IsKeyPressed( ImGuiKey_Enter ) || IsKeyPressed( ImGuiKey_KeypadEnter )
|| IsKeyPressed( ImGuiKey_GamepadFaceDown );
}
static bool IsClearKeyPressed() {
return IsKeyPressed( ImGuiKey_Delete ) || IsKeyPressed( ImGuiKey_Backspace )
|| IsKeyPressed( ImGuiKey_GamepadFaceUp );
}
static bool IsCancelKeyPressed() {
// using Escape, gamepad Start and gamepad B for cancel, except in the
// binding case (so gamepad B can be bound), there only Esc and Start work.
// when the binding popup is active, gamepad nav is disabled, so
// IsKeyPressed( ImGuiKey_Gamepad* ) returns false.
// That means that I need another way to detect gamepad Start being pressed for that case.
// In this demo I'm using gamepadStartPressed, in Doom3/dhewm3 I'll likely ask Doom3 if it
// thinks that Escape is pressed, becazse there gamepad start generates an Escape key event.
// Note: In Doom3, Escape opens/closes the main menu, so in dhewm3 the gamepad Start button
// behaves the same, incl. the specialty that it can't be bound by the user
return gamepadStartPressed || IsKeyPressed( ImGuiKey_Escape ) || IsKeyPressed( ImGuiKey_GamepadFaceRight );
// || IsKeyPressed( ImGuiKey_GamepadStart );
}
static const char* GetGamepadStartName() {
return "Start"; // TODO: get from Doom3, could be different depending on xbox vs PS vs nintendo
}
static const char* GetGamepadCancelButtonNames() {
return "Start or B"; // TODO: get from Doom3, will be different depending on xbox vs PS vs nintendo
}
static const char* GetGamepadBindNowButtonName() { // TODO: rename to confirm or sth
return "A"; // TODO: get from Doom3, will be different depending on xbox vs PS vs nintendo
}
static const char* GetGamepadUnbindButtonName() {
return "Y"; // TODO: get from Doom3, ...
}
const char* GetKeyName( int keyNum, bool localized = true )
{
if( keyNum <= 0 )
return "<none>";
// TODO: use Doom3's idKeyInput::KeyNumToString(keyNum, localized) instead
// "localized" here not only means that the keyname might be translated, but also
// that it's a name for displaying that might change with updates, while the not-localized
// name is the internal name used in configs when storing key bindings that might be
// less nice to read, but doesn't contain spaces and should not change with updates of dhewm3
// (or wherever you integrate this code into)
if ( localized ) {
return ImGui::GetKeyName( (ImGuiKey)keyNum );
} else {
// prepend _int_ so I can tell internal and localized name apart
// just a dummy, in Doom3 use idKeyInput::KeyNumToString(keyNum, false)
static char internalKeyName[128];
snprintf(internalKeyName, sizeof(internalKeyName), "_int_%s", ImGui::GetKeyName( (ImGuiKey)keyNum ) );
return internalKeyName;
}
}
// background color for the first column of the binding table, that contains the name of the command
static ImU32 displayNameBGColor = 0;
static const ImVec4 RedButtonColor(1.00f, 0.17f, 0.17f, 0.58f);
static const ImVec4 RedButtonHoveredColor(1.00f, 0.17f, 0.17f, 1.00f);
static const ImVec4 RedButtonActiveColor(1.00f, 0.37f, 0.37f, 1.00f);
static float CalcDialogButtonWidth()
{
// with the standard font, 120px wide Ok/Cancel buttons look good,
// this text (+default padding) has that width there
float testTextWidth = ImGui::CalcTextSize( "Ok or Cancel ???" ).x;
float framePadWidth = ImGui::GetStyle().FramePadding.x;
return testTextWidth + 2.0f * framePadWidth;
}
enum BindingEntrySelectionState {
BESS_NotSelected = 0,
BESS_Selected,
BESS_WantBind,
BESS_WantClear,
BESS_WantRebind // we were in WantBind, but the key is already bound to another command, so show a confirmation popup
};
struct BoundKey {
int keyNum = -1;
idStr keyName;
idStr internalKeyName; // the one used in bind commands in the D3 console and config
void Set( int _keyNum )
{
keyNum = _keyNum;
keyName = GetKeyName( _keyNum );
internalKeyName = GetKeyName( _keyNum, false );
}
void Clear()
{
keyNum = -1;
keyName = "";
internalKeyName = "";
}
BoundKey() = default;
BoundKey ( int _keyNum ) {
Set( _keyNum );
}
};
struct BindingEntry;
static BindingEntry* FindBindingEntryForKey( int keyNum );
static int numBindingColumns = 4; // TODO: in Doom3, save in CVar (in_maxBindingsPerCommand or sth)
static int rebindKeyNum = -1; // only used for HandleRebindPopup()
static BindingEntry* rebindOtherEntry = nullptr; // ditto
struct BindingEntry {
idStr command; // "_impulse3" or "_forward" or similar - or "" for heading entry
idStr displayName;
const char* description = nullptr;
std::vector<BoundKey> bindings;
enum {
BIND_NONE = -1, // no binding currently selected
// all are selected (clicked command name column): clear all,
// or add a new binding in some visible column (idx in bindings < numBindingColumns)
BIND_ALL = -2,
// append new binding at the end, or set it in unused bindings entry, if any (used by AllBindingsWindow)
BIND_APPEND = -3
};
// which binding is currently selected in the UI, if any (and only if this
// binding entry is currently active according to Draw()'s oldSelState)
int selectedBinding = BIND_NONE; // index in bindings or one of the enum values
BindingEntry() = default;
BindingEntry( const char* _displayName ) : displayName(_displayName) {}
BindingEntry( const char* _command, const char* _displayName, const char* descr = nullptr )
: command( _command ), displayName( _displayName ), description( descr ) {}
// TODO: the following constructor is only relevant for the proof of concept code
BindingEntry( const char* _command, const char* _displayName, const char* descr, std::initializer_list<BoundKey> boundKeys )
: command( _command ), displayName( _displayName ), description( descr ), bindings( boundKeys ) {}
#if 0
BindingEntry( const idStr& _command, const idStr& _displayName, const char* descr = nullptr )
: command( _command ), displayName( _displayName ), description( descr ) {}
BindingEntry( const idStr& _command, const char* _displayName, const char* descr = nullptr )
: command( _command ), displayName( _displayName ), description( descr ) {}
BindingEntry( const BindingEntryTemplate& bet )
: command( bet.command ), description( bet.description ) {
displayName = GetLocalizedString( bet.nameLocStr, bet.name );
displayName.StripTrailingWhitespace();
}
#endif
bool IsHeading() const
{
return command.Length() == 0;
}
void Init()
{
// TODO: get bindings for command from Doom3
}
// only removes the entry from bindings, does *not* unbind!
void RemoveBindingEntry( unsigned idx )
{
if ( idx < bindings.size() ) {
auto it = bindings.begin();
it += idx;
bindings.erase( it );
}
}
// remove all entries from bindings that don't have a key set
void CompactBindings()
{
for ( int i = bindings.size() - 1; i >= 0; --i ) {
if ( bindings[i].keyNum == -1 ) {
RemoveBindingEntry( i );
}
}
}
// also updates this->selectedColumn
void UpdateSelectionState( int bindIdx, /* in+out */ BindingEntrySelectionState& selState )
{
// if currently a popup is shown for creating a new binding or clearing one (BESS_WantBind
// or BESS_WantClear), everything is still rendered, but in a disabled (greyed out) state
// and shouldn't handle any input => then there's not much to do here,
// except for highlighting at the end of the function
if ( selState < BESS_WantBind ) {
if ( ImGui::IsItemFocused() ) {
// Note: even when using the mouse, clicking a selectable will make it focused,
// so it's possible to select a command (or specific binding of a command)
// with the mouse and then press Enter to (re)bind it or Delete to clear it.
// So whether something is selected mostly is equivalent to it being focused.
// In the initial development of this code that wasn't the case, so there
// *might* be some small inconsistencies due to that; but also intentional
// special cases, like a binding entry being drawn as selected while
// one of the popups is open to modify it
// (=> it doesn't have focus then because the popup has focus)
// That's not just cosmetical, selState and selectedBinding are
// used to configure the popup.
selectedBinding = bindIdx;
if ( IsConfirmKeyPressed() ) {
printf("focus bind now bindIdx %d selected_Binding %d\n", bindIdx, selectedBinding);
selState = BESS_WantBind;
} else if ( IsClearKeyPressed() ) {
printf("focus clear now bindIdx %d selected_Binding %d\n", bindIdx, selectedBinding);
bool nothingToClear = false;
if ( bindIdx == BIND_ALL ) {
if ( bindings.size() == 0 ) {
ShowWarningOverlay( "No keys are bound to this command, so there's nothing to unbind" );
nothingToClear = true;
}
} else if ( bindIdx < 0 || bindIdx >= (int)bindings.size() || bindings[bindIdx].keyNum == -1 ) {
ShowWarningOverlay( "No bound key selected for unbind" );
nothingToClear = true;
}
selState = nothingToClear ? BESS_Selected : BESS_WantClear;
} else if ( selState == BESS_NotSelected ) {
printf("focus select %s bindIdx %d selected_Binding %d\n", displayName.c_str(), bindIdx, selectedBinding);
selState = BESS_Selected;
}
} else if (selectedBinding == bindIdx && selState != BESS_NotSelected) {
// apparently this was still selected last frame, but is not focused anymore => unselect it
printf("unselect %s %d from lack of focus\n", displayName.c_str(), bindIdx);
selState = BESS_NotSelected;
}
if ( ImGui::IsItemHovered() ) { // mouse cursor is on this item
if ( bindIdx == BIND_ALL ) {
// if the first column (command name, like "Move Left") is hovered, highlight the whole row
// A normal Selectable would use ImGuiCol_HeaderHovered, but I use that as the "selected"
// color (in Draw()), so use the next brighter thing (ImGuiCol_HeaderActive) here.
ImU32 highlightRowColor = ImGui::GetColorU32( ImGui::GetStyleColorVec4(ImGuiCol_HeaderActive) );
ImGui::TableSetBgColor( ImGuiTableBgTarget_RowBg0, highlightRowColor );
}
if ( ImGui::IsMouseDoubleClicked( 0 ) ) {
printf("hover doubleclick bindIdx %d selected_Binding %d\n", bindIdx, selectedBinding);
selState = BESS_WantBind;
selectedBinding = bindIdx;
}
// Note: single-clicking an item gives it focus, so that's implictly
// handled above in `if ( ImGui::IsItemFocused() ) { ...`
}
}
// this column is selected => highlight it
if ( selState != BESS_NotSelected && selectedBinding == bindIdx ) {
// ImGuiCol_Header would be the regular "selected cell/row" color that Selectable would use
// but ImGuiCol_HeaderHovered is more visible, IMO
ImU32 highlightRowColor = ImGui::GetColorU32( ImGui::GetStyleColorVec4(ImGuiCol_HeaderHovered) );
ImGui::TableSetBgColor( ImGuiTableBgTarget_CellBg, highlightRowColor );
if ( bindIdx == BIND_ALL ) {
// the displayName column is selected => highlight the whole row
ImGui::TableSetBgColor( ImGuiTableBgTarget_RowBg0, highlightRowColor );
// (yes, still set the highlight color for ImGuiTableBgTarget_CellBg above for extra
// highlighting of the column 0 cell, otherwise it'd look darker due to displayNameBGColor)
}
}
//printf("XX returning from UpdateSelectionState() %s selectedBinding = %d selState = %d\n", displayName.c_str(), selectedBinding, selState);
}
bool DrawAllBindingsWindow( /* in+out */ BindingEntrySelectionState& selState, bool newOpen, const ImVec2& btnMin, const ImVec2& btnMax )
{
bool showThisMenu = true;
idStr menuWinTitle = idStr::Format( "All keys bound to %s###allBindingsWindow", displayName.c_str() );
int numBindings = bindings.size();
ImGuiWindowFlags menuWinFlags = ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings;
const float fontSize = ImGui::GetFontSize();
ImVec2 winMinSize = ImGui::CalcTextSize( menuWinTitle, nullptr, true );
winMinSize.x += fontSize * 2.0f;
const ImGuiViewport& viewPort = *ImGui::GetMainViewport();
ImVec2 maxWinSize( viewPort.WorkSize.x, viewPort.WorkSize.y * 0.9f );
// make sure the window is big enough to show the full title (incl. displayName)
// and that it fits into the screen (it can scroll if it gets too long)
ImGui::SetNextWindowSizeConstraints( winMinSize, maxWinSize );
static ImVec2 winPos;
if ( newOpen ) {
// position the window right next to the [++] button that opens/closes it
winPos = btnMin;
winPos.x = btnMax.x + ImGui::GetStyle().ItemInnerSpacing.x;
ImGui::OpenPopup( menuWinTitle );
ImGui::SetNextWindowPos(winPos);
ImGui::SetNextWindowFocus();
}
if ( ImGui::Begin( menuWinTitle, &showThisMenu, menuWinFlags ) )
{
ImGuiTableFlags tableFlags = ImGuiTableFlags_RowBg;
if ( numBindings > 0 && ImGui::BeginTable( "AllBindingsForCommand", 2, tableFlags ) ) {
ImGui::TableSetupColumn("command", ImGuiTableColumnFlags_WidthStretch);
ImGui::TableSetupColumn("buttons", ImGuiTableColumnFlags_WidthFixed);
ImGui::TableNextRow();
ImGui::TableSetColumnIndex( 0 );
// turn the next button (Unbind all) red
ImGui::PushStyleColor( ImGuiCol_Button, RedButtonColor );
ImGui::PushStyleColor( ImGuiCol_ButtonHovered, RedButtonHoveredColor );
ImGui::PushStyleColor( ImGuiCol_ButtonActive, RedButtonActiveColor );
ImGui::Indent();
if ( ImGui::Button( idStr::Format( "Unbind all" ) ) ) {
selState = BESS_WantClear;
selectedBinding = BIND_ALL;
} else {
ImGui::SetItemTooltip( "Remove all keybindings for %s", displayName.c_str() );
}
ImGui::Unindent();
ImGui::PopStyleColor(3); // return to normal button color
ImGui::TableSetColumnIndex( 1 );
float helpHoverWidth = ImGui::CalcTextSize("(?)").x;
float offset = ImGui::GetContentRegionAvail().x - helpHoverWidth;
ImGui::SetCursorPosX( ImGui::GetCursorPosX() + offset );
ImGui::AlignTextToFramePadding();
ImGui::TextDisabled( "(?)" );
if ( ImGui::BeginItemTooltip() ) {
ImGui::PushTextWrapPos( ImGui::GetFontSize() * 35.0f );
ImGui::Text( "You can close this window with Escape or %s on the gamepad or by clicking the little (x) button or by clicking the [++] button again.",
GetGamepadCancelButtonNames() );
ImGui::PopTextWrapPos();
ImGui::EndTooltip();
}
ImGui::Spacing();
ImU32 highlightRowColor = 0;
if ( selectedBinding == BIND_ALL ) {
highlightRowColor = ImGui::GetColorU32( ImGui::GetStyleColorVec4(ImGuiCol_HeaderHovered) );
}
ImGui::Indent( fontSize * 0.5f );
for ( int bnd = 0; bnd < numBindings; ++bnd ) {
ImGui::TableNextRow();
ImGui::TableSetColumnIndex( 0 );
ImGui::PushID( bnd ); // the buttons have the same names in every row, so push the row number as ID
bool colHasBinding = bindings[bnd].keyNum != -1;
const char* keyName = "";
if ( colHasBinding ) {
keyName = bindings[bnd].keyName.c_str();
ImGui::AlignTextToFramePadding();
ImGui::TextUnformatted( keyName );
AddTooltip( bindings[bnd].internalKeyName.c_str() );
}
if ( selectedBinding == BIND_ALL ) {
// if all bindings are selected from the binding table (for clear all),
// mark the whole first row here. otherwise, nothing is marked here,
// as in this window only the buttons are clickble, not the key cells
ImGui::TableSetBgColor( ImGuiTableBgTarget_CellBg, highlightRowColor );
}
ImGui::TableNextColumn();
if ( colHasBinding ) {
if ( ImGui::Button( "Rebind" ) ) {
selState = BESS_WantBind;
selectedBinding = bnd;
} else {
ImGui::SetItemTooltip( "Unbind '%s' and bind another key to %s", keyName, displayName.c_str() );
}
ImGui::SameLine();
ImGui::SetCursorPosX( ImGui::GetCursorPosX() + fontSize*0.5f );
if ( ImGui::Button( "Unbind" ) ) {
selState = BESS_WantClear;
selectedBinding = bnd;
} else {
ImGui::SetItemTooltip( "Unbind key '%s' from %s", keyName, displayName.c_str() );
}
} else {
if ( ImGui::Button( "Bind" ) ) {
selState = BESS_WantBind;
selectedBinding = bnd;
} else {
ImGui::SetItemTooltip( "Set a keybinding for %s", displayName.c_str() );
}
}
ImGui::PopID(); // bnd
}
ImGui::EndTable();
}
const char* addBindButtonLabel = (numBindings == 0) ? "Bind a key" : "Bind another key";
float buttonWidth = ImGui::CalcTextSize(addBindButtonLabel).x + 2.0f * ImGui::GetStyle().FramePadding.x;
ImGui::SetCursorPosX(ImGui::GetContentRegionMax().x - buttonWidth);
if ( ImGui::Button( addBindButtonLabel ) ) {
selState = BESS_WantBind;
selectedBinding = BIND_APPEND;
} else {
ImGui::SetItemTooltip( "Add %s keybinding for %s",
(numBindings == 0) ? "a" : "another",
displayName.c_str() );
}
ImVec2 winSize = ImGui::GetWindowSize();
ImRect winRect;
winRect.Min = ImGui::GetWindowPos();
winRect.Max = winRect.Min + winSize;
ImRect workRect(viewPort.WorkPos, viewPort.WorkPos + viewPort.WorkSize);
if ( !workRect.Contains(winRect) ) {
// this window is at least partly outside the visible area of the screen (or SDL window)
// => move it around so it's completely visible, if possible
ImRect r_avoid( btnMin, btnMax );
r_avoid.Expand( ImGui::GetStyle().ItemInnerSpacing );
ImGuiDir dir = ImGuiDir_Right;
ImVec2 newWinPos = ImGui::FindBestWindowPosForPopupEx( ImVec2(btnMin.x, btnMax.y),
winSize, &dir, workRect, r_avoid, ImGuiPopupPositionPolicy_Default );
ImVec2 posDiff = newWinPos - winPos;
if ( fabsf(posDiff.x) > 2.0f || fabsf(posDiff.y) > 2.0f ) {
winPos = newWinPos;
ImGui::SetWindowPos( newWinPos );
}
}
// allow closing this window with escape
if ( ImGui::IsWindowFocused() && IsCancelKeyPressed() ) {
showThisMenu = false;
}
}
ImGui::End();
return showThisMenu;
}
BindingEntrySelectionState Draw( int bindRowNum, const BindingEntrySelectionState oldSelState )
{
if ( IsHeading() ) {
ImGui::SeparatorText( displayName );
if ( description ) {
AddDescrTooltip( description );
}
} else {
ImGui::PushID( command );
ImGui::TableNextRow( 0, ImGui::GetFrameHeightWithSpacing() );
ImGui::TableSetColumnIndex( 0 );
ImGui::AlignTextToFramePadding();
// the first column (with the display name in it) gets a different background color
ImGui::TableSetBgColor( ImGuiTableBgTarget_CellBg, displayNameBGColor );
BindingEntrySelectionState newSelState = oldSelState;
// not really using the selectable feature, mostly making it selectable
// so keyboard/gamepad navigation works
ImGui::Selectable( "##cmd", false, 0 );
UpdateSelectionState( BIND_ALL, newSelState );
ImGui::SameLine();
ImGui::TextUnformatted( displayName );
AddTooltip( command );
if ( description ) {
AddDescrTooltip( description );
}
int numBindings = bindings.size();
for ( int bnd=0; bnd < numBindingColumns ; ++bnd ) {
ImGui::TableSetColumnIndex( bnd+1 );
bool colHasBinding = (bnd < numBindings) && bindings[bnd].keyNum != -1;
char selTxt[128];
if ( colHasBinding ) {
snprintf( selTxt, sizeof(selTxt), "%s###%d", bindings[bnd].keyName.c_str(), bnd );
} else {
snprintf( selTxt, sizeof(selTxt), "###%d", bnd );
}
ImGui::Selectable( selTxt, false, 0 );
UpdateSelectionState( bnd, newSelState );
if ( colHasBinding ) {
AddTooltip( bindings[bnd].internalKeyName.c_str() );
}
}
ImGui::TableSetColumnIndex( numBindingColumns + 1 );
// the last column contains a "++" button that opens a window that lists all bindings
// for this rows command (including ones not listed in the table because of lack of columns)
// if there actually are more bindings than columns, the button is red, else it has the default color
// clicking the button again will close the window, and the buttons color depends on whether
// its window is open or not. only one such window can be open at at time, clicking the
// button in another row closes the current window and opens a new one
static int showAllBindingsMenuRowNum = -1;
bool allBindWinWasOpen = (showAllBindingsMenuRowNum == bindRowNum);
int styleColorsToPop = 0;
if ( numBindings <= numBindingColumns ) {
if ( allBindWinWasOpen ) {
// if the all bindings menu/window is showed for this entry,
// the button is "active" => switch its normal and hovered colors
ImVec4 btnColor = ImGui::GetStyleColorVec4( ImGuiCol_ButtonHovered );
ImGui::PushStyleColor( ImGuiCol_ButtonHovered, ImGui::GetStyleColorVec4(ImGuiCol_Button) );
ImGui::PushStyleColor( ImGuiCol_Button, btnColor );
styleColorsToPop = 2;
}
} else { // more bindings than can be shown in the table => make ++ button red
ImGui::PushStyleColor( ImGuiCol_Button, allBindWinWasOpen ? RedButtonHoveredColor : RedButtonColor );
ImGui::PushStyleColor( ImGuiCol_ButtonHovered, allBindWinWasOpen ? RedButtonColor : RedButtonHoveredColor );
ImGui::PushStyleColor( ImGuiCol_ButtonActive, RedButtonActiveColor );
styleColorsToPop = 3;
}
// TODO: close the window if another row has been selected (or used to create/delete a binding or whatever)?
bool newOpen = false;
if ( ImGui::Button( "++" ) ) {
showAllBindingsMenuRowNum = allBindWinWasOpen ? -1 : bindRowNum;
newOpen = true;
CompactBindings();
}
if ( ImGui::IsItemFocused() && newSelState != BESS_NotSelected ) {
printf("> Draw(): unselect because ++ button seems to be focused\n");
newSelState = BESS_NotSelected;
}
ImVec2 btnMin = ImGui::GetItemRectMin();
ImVec2 btnMax = ImGui::GetItemRectMax();
if ( numBindings > numBindingColumns ) {
ImGui::SetItemTooltip( "There are additional bindings for %s.\nClick here to show all its bindings.", displayName.c_str() );
} else {
ImGui::SetItemTooltip( "Show all bindings for %s in a list", displayName.c_str() );
}
if ( styleColorsToPop > 0 ) {
ImGui::PopStyleColor( styleColorsToPop ); // restore button colors
}
if ( showAllBindingsMenuRowNum == bindRowNum ) {
ImGui::SetNextWindowBgAlpha( 1.0f );
if ( !DrawAllBindingsWindow( newSelState, newOpen, btnMin, btnMax ) ) {
showAllBindingsMenuRowNum = -1;
CompactBindings();
}
}
ImGui::PopID();
if ( newSelState == BESS_NotSelected ) {
if(oldSelState != newSelState)
printf("> Draw(): new state of %s is not selected\n", displayName.c_str());
selectedBinding = BIND_NONE;
}
return newSelState;
}
return BESS_NotSelected;
}
void Bind( int keyNum ) {
if ( keyNum >= 0 ) {
printf( "bind key %d to %s (%s)\n", keyNum, command.c_str(), displayName.c_str() );
// TODO: actual Doom3 bind implementation!
}
}
void Unbind( int keyNum ) {
if ( keyNum >= 0 ) {
printf( "unbind key %d from %s (%s)\n", keyNum, command.c_str(), displayName.c_str() );
// TODO: actual Doom3 unbind implementation!
}
}
BindingEntrySelectionState HandleClearPopup( const char* popupName, bool newOpen )
{
BindingEntrySelectionState ret = BESS_WantClear;
const int selectedBinding = this->selectedBinding;
if ( ImGui::BeginPopupModal( popupName, NULL, ImGuiWindowFlags_AlwaysAutoResize ) )
{
if ( selectedBinding == BIND_ALL ) {
ImGui::Text( "Clear all keybindings for %s ?", displayName.c_str() );
} else {
ImGui::Text( "Unbind key '%s' from command %s ?",
bindings[selectedBinding].keyName.c_str(), displayName.c_str() );
}
ImGui::NewLine();
ImGui::Text( "Press Enter (or gamepad %s) to confirm, or\nEscape (or gamepad %s) to cancel.",
GetGamepadBindNowButtonName(), GetGamepadCancelButtonNames() );
ImGui::NewLine();
// center the Ok and Cancel buttons
float dialogButtonWidth = CalcDialogButtonWidth();
float spaceBetweenButtons = ImGui::GetFontSize();
float buttonOffset = (ImGui::GetWindowWidth() - 2.0f*dialogButtonWidth - spaceBetweenButtons) * 0.5f;
ImGui::SetCursorPosX( buttonOffset );
bool confirmedByKey = false;
if ( !newOpen && !ImGui::IsAnyItemFocused() ) {
// if no item is focused (=> not using keyboard or gamepad navigation to select
// [Ok] or [Cancel] button), check if Enter has been pressed to confirm deletion
// (otherwise, enter can be used to chose the selected button)
// also, don't do this when just opened, because then enter might still
// be pressed from selecting the Unbind button in the AllBindingsWindow
confirmedByKey = IsConfirmKeyPressed();
}
if ( ImGui::Button( "Ok", ImVec2(dialogButtonWidth, 0) ) || confirmedByKey ) {
if ( selectedBinding == BIND_ALL ) {
for ( BoundKey& bk : bindings ) {
Unbind( bk.keyNum );
}
bindings.clear();
// don't select all columns after they have been cleared,
// instead only select the first, good point to add a new binding
this->selectedBinding = 0;
} else {
Unbind( bindings[selectedBinding].keyNum );
if ( selectedBinding == numBindingColumns - 1 ) {
// when removing the binding of the last column visible
// in the big binding table, remove that entry so
// the next one not visible there can take its place
RemoveBindingEntry( selectedBinding );
} else {
bindings[selectedBinding].Clear();
}
}
ImGui::CloseCurrentPopup();
ret = BESS_Selected;
}
ImGui::SetItemDefaultFocus();
ImGui::SameLine( 0.0f, spaceBetweenButtons );
if ( ImGui::Button( "Cancel", ImVec2(dialogButtonWidth, 0) ) || IsCancelKeyPressed() ) {
ImGui::CloseCurrentPopup();
ret = BESS_Selected;
}
ImGui::EndPopup();
}
return ret;
}
void AddKeyBinding( int keyNum )
{
assert( selectedBinding != -1 );
Bind( keyNum );
int numBindings = bindings.size();
if ( selectedBinding == BIND_ALL || selectedBinding == BIND_APPEND ) {
for ( int i=0; i < numBindings; ++i ) {
// if there's an empty column, use that
if ( bindings[i].keyNum == -1 ) {
bindings[i].Set( keyNum );
// select the column this was inserted into
selectedBinding = i;
return;
}
}
if ( numBindings < numBindingColumns || selectedBinding == BIND_APPEND ) {
// just append an entry to bindings
bindings.push_back( BoundKey(keyNum) );
selectedBinding = numBindings;
} else {
// insert in last column of table so it's visible
// (but don't remove any elements from bindings!)
auto it = bindings.cbegin(); // I fucking hate STL.
it += (numBindingColumns-1);
bindings.insert( it, BoundKey(keyNum) );
selectedBinding = numBindingColumns-1;
}
} else {
int selectedBinding = this->selectedBinding;
assert( selectedBinding >= 0 );
if ( selectedBinding < numBindings ) {
Unbind( bindings[selectedBinding].keyNum );
bindings[selectedBinding].Set( keyNum );
} else {
if ( selectedBinding > numBindings ) {
// apparently a column with other unset columns before it was selected
// => add enough empty columns
bindings.resize( selectedBinding );
}
bindings.push_back( BoundKey(keyNum) );
}
}
}
void RemoveKeyBinding( int keyNum )
{
int delPos = -1;
int numBindings = bindings.size();
for ( int i = 0; i < numBindings; ++i ) {
if ( bindings[i].keyNum == keyNum ) {
delPos = i;
break;
}
}
if ( delPos != -1 ) {
Unbind( keyNum );
RemoveBindingEntry( delPos );
}
}
BindingEntrySelectionState HandleBindPopup( const char* popupName, bool newOpen )
{
BindingEntrySelectionState ret = BESS_WantBind;
const int selectedBinding = this->selectedBinding;
assert(selectedBinding == BIND_ALL || selectedBinding == BIND_APPEND || selectedBinding >= 0);
ImGuiIO& io = ImGui::GetIO();
// disable keyboard and gamepad input while the bind popup is open
io.ConfigFlags &= ~(ImGuiConfigFlags_NavEnableGamepad | ImGuiConfigFlags_NavEnableKeyboard);
if ( ImGui::BeginPopupModal( popupName, NULL, ImGuiWindowFlags_AlwaysAutoResize ) )
{
if ( selectedBinding < 0 || selectedBinding >= (int)bindings.size()
|| bindings[selectedBinding].keyNum == -1 ) {
// add a binding
ImGui::Text( "Press a key or button to bind to %s", displayName.c_str() );
} else {
// overwrite a binding
ImGui::Text( "Press a key or button to replace '%s' binding to %s",
bindings[selectedBinding].keyName.c_str(), displayName.c_str() );
}
ImGui::NewLine();
ImGui::TextUnformatted( "To bind a mouse button, click it in the following field" );
const float windowWidth = ImGui::GetWindowWidth();
ImVec2 clickFieldSize( windowWidth * 0.8f, ImGui::GetTextLineHeightWithSpacing() * 4.0f );
ImGui::SetCursorPosX( windowWidth * 0.1f );
ImGui::Button( "###clickField", clickFieldSize );
bool clickFieldHovered = ImGui::IsItemHovered();
ImGui::NewLine();
ImGui::Text( "... or press Escape (or gamepad %s) to cancel.", GetGamepadStartName() );
ImGui::NewLine();
// center the Cancel button
float dialogButtonWidth = CalcDialogButtonWidth();
float buttonOffset = (windowWidth - dialogButtonWidth) * 0.5f;
ImGui::SetCursorPosX( buttonOffset );
if ( ImGui::Button( "Cancel", ImVec2(dialogButtonWidth, 0) ) || IsCancelKeyPressed() ) {
ImGui::CloseCurrentPopup();
ret = BESS_Selected;
io.ConfigFlags |= (ImGuiConfigFlags_NavEnableGamepad | ImGuiConfigFlags_NavEnableKeyboard);
} else if ( !newOpen ) {
// find out if any key is pressed and bind that (except for Esc which can't be
// bound and is already handled though IsCancelKeyPressed() above)
// (but don't run this when the popup has just been opened, because then
// the key that opened this, likely Enter, is still registered as pressed)
// TODO: use Doom3's mechanism to figure out what D3 key is pressed
ImGuiKey pressedKey = ImGuiKey_None;
for ( int k = ImGuiKey_NamedKey_BEGIN; k < ImGuiKey_NamedKey_END; ++k ) {
ImGuiKey key = (ImGuiKey)k;