aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/me/shedaniel/gui/widget/KeyBindButton.java
blob: 51a4d0df112292adc62ca75286e4664d2af6e87a (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
package me.shedaniel.gui.widget;

import me.shedaniel.ClientListener;
import me.shedaniel.library.KeyBindFunction;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.resources.I18n;
import net.minecraft.util.text.TextFormatting;

import java.awt.event.KeyEvent;
import java.util.function.Consumer;

public class KeyBindButton extends GuiButton {
    
    private int currentKey;
    private Consumer<Integer> onEditKeyBind;
    private boolean editMode;
    
    public KeyBindButton(int buttonId, int x, int y, int widthIn, int heightIn, int currentKey, Consumer<Integer> onEditKeyBind) {
        super(buttonId, x, y, widthIn, heightIn, "");
        this.currentKey = currentKey;
        this.onEditKeyBind = onEditKeyBind;
    }
    
    @Override
    public boolean charTyped(char p_charTyped_1_, int p_charTyped_2_) {
        if (editMode) {
            currentKey = KeyEvent.getExtendedKeyCodeForChar(p_charTyped_1_);
            onEditKeyBind.accept(currentKey);
            editMode = false;
            return true;
        }
        return false;
    }
    
    @Override
    public void render(int mouseX, int mouseY, float partialTicks) {
        this.displayString = editMode ? I18n.format("text.rei.listeningkey") : KeyEvent.getKeyText(currentKey);
        if (!editMode && ClientListener.keyBinds.stream().map(KeyBindFunction::getKey).filter(integer -> integer == currentKey).count() > 1)
            this.displayString = TextFormatting.RED + this.displayString;
        super.render(mouseX, mouseY, partialTicks);
    }
    
    @Override
    public void focusChanged(boolean focused) {
        if (focused == false)
            editMode = focused;
    }
    
    @Override
    public void onClick(double mouseX, double mouseY) {
        editMode = !editMode;
    }
    
    @Override
    public boolean canFocus() {
        return true;
    }
    
}