summaryrefslogtreecommitdiff
path: root/Userland/Applications/PDFViewer/NumericInput.cpp
blob: a11e38795f11299bf59f1710a7eac0164d16f07d (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
/*
 * Copyright (c) 2021, Matthew Olsson <mattco@serenityos.org>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include "NumericInput.h"
#include "ctype.h"

NumericInput::NumericInput()
{
    set_text("0");

    on_change = [&] {
        auto number_opt = text().to_int();
        if (number_opt.has_value()) {
            set_current_number(number_opt.value(), false);
            return;
        }

        StringBuilder builder;
        bool first = true;
        for (auto& ch : text()) {
            if (isdigit(ch) || (first && ((ch == '-' && m_min_number < 0) || ch == '+')))
                builder.append(ch);
            first = false;
        }

        auto new_number_opt = builder.to_string().to_int();
        if (!new_number_opt.has_value()) {
            m_needs_text_reset = true;
            set_text(builder.to_string());
            return;
        } else {
            m_needs_text_reset = false;
        }

        set_text(builder.to_string());
        set_current_number(new_number_opt.value(), false);
    };

    on_up_pressed = [&] {
        if (m_current_number < m_max_number)
            set_current_number(m_current_number + 1);
    };

    on_down_pressed = [&] {
        if (m_current_number > m_min_number)
            set_current_number(m_current_number - 1);
    };

    on_focusout = [&] { on_focus_lost(); };
    on_return_pressed = [&] { on_focus_lost(); };
    on_escape_pressed = [&] { on_focus_lost(); };
}

void NumericInput::set_min_number(i32 number)
{
    m_min_number = number;
    if (m_current_number < number)
        set_current_number(number);
}

void NumericInput::set_max_number(i32 number)
{
    m_max_number = number;
    if (m_current_number > number)
        set_current_number(number);
}

void NumericInput::on_focus_lost()
{
    if (m_needs_text_reset) {
        set_text(String::number(m_current_number));
        m_needs_text_reset = false;
    }
    if (on_number_changed)
        on_number_changed(m_current_number);
}

void NumericInput::set_current_number(i32 number, bool call_change_handler)
{
    if (number == m_current_number)
        return;

    m_current_number = clamp(number, m_min_number, m_max_number);
    set_text(String::number(m_current_number));
    if (on_number_changed && call_change_handler)
        on_number_changed(m_current_number);
}