summaryrefslogtreecommitdiffstats
path: root/src/ui/widget/spin-button-tool-item.cpp
blob: b283939e9af5e4ae8723f35e8636a9150f4093a0 (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
// SPDX-License-Identifier: GPL-2.0-or-later

#include "spin-button-tool-item.h"

#include <gtkmm/box.h>
#include <gtkmm/image.h>
#include <gtkmm/radiomenuitem.h>
#include <gtkmm/toolbar.h>

#include <utility>

#include "spinbutton.h"
#include "ui/icon-loader.h"

namespace Inkscape {
namespace UI {
namespace Widget {

/**
 * \brief Handler for the button's "focus-in-event" signal
 *
 * \param focus_event The event that triggered the signal
 *
 * \detail This just logs the current value of the spin-button
 *         and sets the _transfer_focus flag
 */
bool
SpinButtonToolItem::on_btn_focus_in_event(GdkEventFocus * /* focus_event */)
{
    _last_val = _btn->get_value();
    _transfer_focus = true;

    return false; // Event not consumed
}

/**
 * \brief Handler for the button's "focus-out-event" signal
 *
 * \param focus_event The event that triggered the signal
 *
 * \detail This just unsets the _transfer_focus flag
 */
bool
SpinButtonToolItem::on_btn_focus_out_event(GdkEventFocus * /* focus_event */)
{
    _transfer_focus = false;

    return false; // Event not consumed
}

/**
 * \brief Handler for the button's "key-press-event" signal
 *
 * \param key_event The event that triggered the signal
 *
 * \detail If the ESC key was pressed, restore the last value and defocus.
 *         If the Enter key was pressed, just defocus.
 */
bool
SpinButtonToolItem::on_btn_key_press_event(GdkEventKey *key_event)
{
    bool was_consumed = false; // Whether event has been consumed or not
    auto display = Gdk::Display::get_default();
    auto keymap  = display->get_keymap();
    guint key = 0;
    gdk_keymap_translate_keyboard_state(keymap, key_event->hardware_keycode,
                                        static_cast<GdkModifierType>(key_event->state),
                                        0, &key, 0, 0, 0);

    auto val = _btn->get_value();

    switch(key) {
        case GDK_KEY_Escape:
        {
            _transfer_focus = true;
            _btn->set_value(_last_val);
            defocus();
            was_consumed = true;
        }
        break;

        case GDK_KEY_Return:
        case GDK_KEY_KP_Enter:
        {
            _transfer_focus = true;
            defocus();
            was_consumed = true;
        }
        break;

        case GDK_KEY_Tab:
        {
            _transfer_focus = false;
            was_consumed = process_tab(1);
        }
        break;

        case GDK_KEY_ISO_Left_Tab:
        {
            _transfer_focus = false;
            was_consumed = process_tab(-1);
        }
        break;

        // TODO: Enable variable step-size if this is ever used
        case GDK_KEY_Up:
        case GDK_KEY_KP_Up:
        {
            _transfer_focus = false;
            _btn->set_value(val+1);
            was_consumed=true;
        }
        break;

        case GDK_KEY_Down:
        case GDK_KEY_KP_Down:
        {
            _transfer_focus = false;
            _btn->set_value(val-1);
            was_consumed=true;
        }
        break;

        case GDK_KEY_Page_Up:
        case GDK_KEY_KP_Page_Up:
        {
            _transfer_focus = false;
            _btn->set_value(val+10);
            was_consumed=true;
        }
        break;

        case GDK_KEY_Page_Down:
        case GDK_KEY_KP_Page_Down:
        {
            _transfer_focus = false;
            _btn->set_value(val-10);
            was_consumed=true;
        }
        break;

        case GDK_KEY_z:
        case GDK_KEY_Z:
        {
            _transfer_focus = false;
            _btn->set_value(_last_val);
            was_consumed = true;
        }
        break;
    }

    return was_consumed;
}

/**
 * \brief Shift focus to a different widget
 *
 * \details This only has an effect if the _transfer_focus flag and the _focus_widget are set
 */
void
SpinButtonToolItem::defocus()
{
    if(_transfer_focus && _focus_widget) {
        _focus_widget->grab_focus();
    }
}

/**
 * \brief Move focus to another spinbutton in the toolbar
 *
 * \param increment[in] The number of places to shift within the toolbar
 */
bool
SpinButtonToolItem::process_tab(int increment)
{
    // If the increment is zero, do nothing
    if(increment == 0) return true;

    // Here, we're working through the widget hierarchy:
    // Toolbar
    // |- ToolItem (*this)
    //    |-> Box
    //       |-> SpinButton (*_btn)
    //
    // Our aim is to find the next/previous spin-button within a toolitem in our toolbar

    bool handled = false;

    // We only bother doing this if the current item is actually in a toolbar!
    auto toolbar = dynamic_cast<Gtk::Toolbar *>(get_parent());

    if (toolbar) {
        // Get the index of the current item within the toolbar and the total number of items
        auto my_index = toolbar->get_item_index(*this);
        auto n_items  = toolbar->get_n_items();

        auto test_index = my_index + increment; // The index of the item we want to check

        // Loop through tool items as long as we're within the bounds of the toolbar and
        // we haven't yet found our new item to focus on
        while(test_index > 0 && test_index <= n_items && !handled) {

            auto tool_item = toolbar->get_nth_item(test_index);

            if(tool_item) {
                // There are now two options that we support:
                if(dynamic_cast<SpinButtonToolItem *>(tool_item)) {
                    // (1) The tool item is a SpinButtonToolItem, in which case, we just pass
                    //     focus to its spin-button
                    dynamic_cast<SpinButtonToolItem *>(tool_item)->grab_button_focus();
                    handled = true;
                }
                else if(dynamic_cast<Gtk::SpinButton *>(tool_item->get_child())) {
                    // (2) The tool item contains a plain Gtk::SpinButton, in which case we
                    //     pass focus directly to it
                    tool_item->get_child()->grab_focus();
                }
            }

            test_index += increment;
        }
    }

    return handled;
}

/**
 * \brief Handler for toggle events on numeric menu items
 *
 * \details Sets the adjustment to the desired value
 */
void
SpinButtonToolItem::on_numeric_menu_item_toggled(double value)
{
    auto adj = _btn->get_adjustment();
    adj->set_value(value);
}

Gtk::RadioMenuItem *
SpinButtonToolItem::create_numeric_menu_item(Gtk::RadioButtonGroup *group,
                                             double                 value,
                                             const Glib::ustring&   label)
{
    // Represent the value as a string
    std::ostringstream ss;
    ss << value;

    // Append the label if specified
    if (!label.empty()) {
        ss << ": " << label;
    }

    auto numeric_option = Gtk::manage(new Gtk::RadioMenuItem(*group, ss.str()));

    // Set the adjustment value in response to changes in the selected item
    auto toggled_handler = sigc::bind(sigc::mem_fun(*this, &SpinButtonToolItem::on_numeric_menu_item_toggled), value);
    numeric_option->signal_toggled().connect(toggled_handler);

    return numeric_option;
}

/**
 * \brief Create a menu containing fixed numeric options for the adjustment
 *
 * \details Each of these values represents a snap-point for the adjustment's value
 */
Gtk::Menu *
SpinButtonToolItem::create_numeric_menu()
{
    auto numeric_menu = Gtk::manage(new Gtk::Menu());

    Gtk::RadioMenuItem::Group group;

    // Get values for the adjustment
    auto adj = _btn->get_adjustment();
    auto adj_value = adj->get_value();
    auto lower = adj->get_lower();
    auto upper = adj->get_upper();
    auto step = adj->get_step_increment();
    auto page = adj->get_page_increment();

    auto digits = _btn->get_digits();

    // A number a little smaller than the smallest increment that can be
    // displayed in the spinbutton entry.
    //
    // For example, if digits = 0, we are displaying integers only and
    // epsilon = 0.9 * 10^-0 = 0.9
    //
    // For digits = 1, we get epsilon = 0.9 * 10^-1 = 0.09
    // For digits = 2, we get epsilon = 0.9 * 10^-2 = 0.009 etc...
    auto epsilon = 0.9 * pow(10.0, -float(digits));

    // Start by setting some fixed values based on the adjustment's
    // parameters.
    NumericMenuData values;
    values.push_back(std::make_pair(upper,            ""));
    values.push_back(std::make_pair(adj_value + page, ""));
    values.push_back(std::make_pair(adj_value + step, ""));
    values.push_back(std::make_pair(adj_value,        ""));
    values.push_back(std::make_pair(adj_value - step, ""));
    values.push_back(std::make_pair(adj_value - page, ""));
    values.push_back(std::make_pair(lower,            ""));

    // Now add any custom items
    for (auto custom_data : _custom_menu_data) {
        values.push_back(custom_data);
    }

    // Sort the numeric menu items into reverse numerical order (largest at top of menu)
    std::sort   (begin(values), end(values));
    std::reverse(begin(values), end(values));

    for (auto value : values)
    {
        auto numeric_menu_item = create_numeric_menu_item(&group, value.first, value.second);
        numeric_menu->append(*numeric_menu_item);

        if (fabs(adj_value - value.first) < epsilon) {
            // If the adjustment value is very close to the value of this menu item,
            // make this menu item active
            numeric_menu_item->set_active();
        }
    }

    return numeric_menu;
}

/**
 * \brief Create a menu-item in response to the "create-menu-proxy" signal
 *
 * \detail This is an override for the default Gtk::ToolItem handler so
 *         we don't need to explicitly connect this to the signal. It
 *         runs if the toolitem is unable to fit on the toolbar, and
 *         must be represented by a menu item instead.
 */
bool
SpinButtonToolItem::on_create_menu_proxy()
{
    // The main menu-item.  It just contains the label that normally appears
    // next to the spin-button, and an indicator for a sub-menu.
    auto menu_item = Gtk::manage(new Gtk::MenuItem(_label_text));
    auto numeric_menu = create_numeric_menu();
    menu_item->set_submenu(*numeric_menu);

    set_proxy_menu_item(_name, *menu_item);

    return true; // Finished handling the event
}

/**
 * \brief Create a new SpinButtonToolItem
 *
 * \param[in] name       A unique ID for this tool-item (not translatable)
 * \param[in] label_text The text to display in the toolbar
 * \param[in] adjustment The Gtk::Adjustment to attach to the spinbutton
 * \param[in] climb_rate The climb rate for the spin button (default = 0)
 * \param[in] digits     Number of decimal places to display
 */
SpinButtonToolItem::SpinButtonToolItem(const Glib::ustring            name,
                                       const Glib::ustring&           label_text,
                                       Glib::RefPtr<Gtk::Adjustment>& adjustment,
                                       double                         climb_rate,
                                       int                            digits)
    : _btn(Gtk::manage(new SpinButton(adjustment, climb_rate, digits))),
      _name(std::move(name)),
      _label_text(label_text),
      _last_val(0.0),
      _transfer_focus(false),
      _focus_widget(nullptr)
{
    set_margin_start(3);
    set_margin_end(3);
    set_name(_name);

    // Handle popup menu
    _btn->signal_popup_menu().connect(sigc::mem_fun(*this, &SpinButtonToolItem::on_popup_menu), false);

    // Handle button events
    auto btn_focus_in_event_cb = sigc::mem_fun(*this, &SpinButtonToolItem::on_btn_focus_in_event);
    _btn->signal_focus_in_event().connect(btn_focus_in_event_cb, false);

    auto btn_focus_out_event_cb = sigc::mem_fun(*this, &SpinButtonToolItem::on_btn_focus_out_event);
    _btn->signal_focus_out_event().connect(btn_focus_out_event_cb, false);

    auto btn_key_press_event_cb = sigc::mem_fun(*this, &SpinButtonToolItem::on_btn_key_press_event);
    _btn->signal_key_press_event().connect(btn_key_press_event_cb, false);

    auto btn_button_press_event_cb = sigc::mem_fun(*this, &SpinButtonToolItem::on_btn_button_press_event);
    _btn->signal_button_press_event().connect(btn_button_press_event_cb, false);

    _btn->add_events(Gdk::KEY_PRESS_MASK);

    // Create a label
    _label = Gtk::manage(new Gtk::Label(label_text));

    // Arrange the widgets in a horizontal box
    _hbox = Gtk::manage(new Gtk::Box());
    _hbox->set_spacing(3);
    _hbox->pack_start(*_label);
    _hbox->pack_start(*_btn);
    add(*_hbox);
    show_all();
}

void
SpinButtonToolItem::set_icon(const Glib::ustring& icon_name)
{
    _hbox->remove(*_label);
    _icon = Gtk::manage(sp_get_icon_image(icon_name, Gtk::ICON_SIZE_SMALL_TOOLBAR));

    if(_icon) {
        _hbox->pack_start(*_icon);
        _hbox->reorder_child(*_icon, 0);
    }

    show_all();
}

bool
SpinButtonToolItem::on_btn_button_press_event(const GdkEventButton *button_event)
{
    if (gdk_event_triggers_context_menu(reinterpret_cast<const GdkEvent *>(button_event)) &&
            button_event->type == GDK_BUTTON_PRESS) {
        do_popup_menu(button_event);
        return true;
    }

    return false;
}

void
SpinButtonToolItem::do_popup_menu(const GdkEventButton *button_event)
{
    auto menu = create_numeric_menu();
    menu->attach_to_widget(*_btn);
    menu->show_all();
    menu->popup_at_pointer(reinterpret_cast<const GdkEvent *>(button_event));
}

/**
 * \brief Create a popup menu
 */
bool
SpinButtonToolItem::on_popup_menu()
{
    do_popup_menu(nullptr);
    return true;
}

/**
 * \brief Transfers focus to the child spinbutton by default
 */
void
SpinButtonToolItem::on_grab_focus()
{
    grab_button_focus();
}

/**
 * \brief Set the tooltip to display on this (and all child widgets)
 *
 * \param[in] text The tooltip to display
 */
void
SpinButtonToolItem::set_all_tooltip_text(const Glib::ustring& text)
{
    set_tooltip_text(text);
    _btn->set_tooltip_text(text);
}

/**
 * \brief Set the widget that focus moves to when this one loses focus
 *
 * \param widget The widget that will gain focus
 */
void
SpinButtonToolItem::set_focus_widget(Gtk::Widget *widget)
{
    _focus_widget = widget;
}

/**
 * \brief Grab focus on the spin-button widget
 */
void
SpinButtonToolItem::grab_button_focus()
{
    _btn->grab_focus();
}

void
SpinButtonToolItem::set_custom_numeric_menu_data(std::vector<double>&              values,
                                                 const std::vector<Glib::ustring>& labels)
{
    if(values.size() != labels.size() && !labels.empty()) {
        g_warning("Cannot add custom menu items.  Value and label arrays are different sizes");
        return;
    }

    _custom_menu_data.clear();

    int i = 0;

    for (auto value : values) {
        if(labels.empty()) {
            _custom_menu_data.push_back(std::make_pair(value, ""));
        }
        else {
            _custom_menu_data.push_back(std::make_pair(value, labels[i++]));
        }
    }
}

Glib::RefPtr<Gtk::Adjustment>
SpinButtonToolItem::get_adjustment()
{
    return _btn->get_adjustment();
}
} // namespace Widget
} // namespace UI
} // namespace Inkscape
/*
  Local Variables:
  mode:c++
  c-file-style:"stroustrup"
  c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
  indent-tabs-mode:nil
  fill-column:99
  End:
*/
// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 :