/
sliderwidget.cpp
649 lines (546 loc) · 17.1 KB
/
sliderwidget.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
/** @file sliderwidget.cpp Slider to pick a value within a range.
*
* @authors Copyright (c) 2013 Jaakko Keränen <jaakko.keranen@iki.fi>
*
* @par License
* GPL: http://www.gnu.org/licenses/gpl.html
*
* <small>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version. This program 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 General
* Public License for more details. You should have received a copy of the GNU
* General Public License along with this program; if not, see:
* http://www.gnu.org/licenses</small>
*/
#include "ui/widgets/sliderwidget.h"
#include "ui/widgets/dialogwidget.h"
#include "ui/widgets/lineeditwidget.h"
#include "TextDrawable"
#include <de/Drawable>
#include <de/MouseEvent>
#include <cmath>
using namespace de;
using namespace ui;
/**
* Popup for editing the value of a slider.
*/
class ValuePopup : public PopupWidget
{
public:
ValuePopup(SliderWidget &slider)
{
setContent(_edit = new LineEditWidget);
//_edit->setEmptyContentHint(tr("Enter value"));
_edit->setSignalOnEnter(true);
connect(_edit, SIGNAL(enterPressed(QString)), &slider, SLOT(setValueFromText(QString)));
connect(_edit, SIGNAL(enterPressed(QString)), this, SLOT(close()));
_edit->rule().setInput(Rule::Width, slider.style().rules().rule("slider.editor"));
_edit->setText(QString::number(slider.value() * slider.displayFactor(), 'g', 4));
}
LineEditWidget &editor() const
{
return *_edit;
}
void preparePanelForOpening()
{
PopupWidget::preparePanelForOpening();
root().setFocus(_edit);
}
void panelClosing()
{
PopupWidget::panelClosing();
root().setFocus(0);
}
private:
LineEditWidget *_edit;
};
DENG_GUI_PIMPL(SliderWidget)
{
ddouble value;
Ranged range;
ddouble step;
int precision;
ddouble displayFactor;
String minLabel;
String maxLabel;
enum State {
Inert,
Hovering,
Grabbed
};
State state;
Vector2i grabFrom;
ddouble grabValue;
// Visualization.
bool animating;
Animation pos;
int endLabelSize;
Animation frameOpacity;
// GL objects.
enum Labels {
Value,
Start,
End,
NUM_LABELS
};
TextDrawable labels[NUM_LABELS];
Drawable drawable;
GLUniform uMvpMatrix;
GLUniform uColor;
Instance(Public *i)
: Base(i),
value(0),
range(0, 0),
step(0),
precision(0),
displayFactor(1),
state(Inert),
animating(false),
uMvpMatrix("uMvpMatrix", GLUniform::Mat4),
uColor ("uColor", GLUniform::Vec4)
{
self.setFont("slider.label");
frameOpacity.setValue(.25f);
updateStyle();
}
void updateStyle()
{
endLabelSize = style().rules().rule("slider.label").valuei();
for(int i = 0; i < int(NUM_LABELS); ++i)
{
labels[i].setFont(i == Value? style().fonts().font("slider.value") : self.font());
labels[i].setLineWrapWidth(endLabelSize);
}
}
void glInit()
{
DefaultVertexBuf *buf = new DefaultVertexBuf;
drawable.addBuffer(buf);
shaders().build(drawable.program(), "generic.textured.color_ucolor")
<< uMvpMatrix << uColor << uAtlas();
for(int i = 0; i < int(NUM_LABELS); ++i)
{
labels[i].init(atlas(), self.font());
}
updateValueLabel();
updateRangeLabels();
}
void glDeinit()
{
drawable.clear();
for(int i = 0; i < int(NUM_LABELS); ++i)
{
labels[i].deinit();
}
}
Rectanglei contentRect() const
{
Vector4i margins = self.margins().toVector();
return self.rule().recti().adjusted(margins.xy(), -margins.zw());
}
/// Determines the total area where the slider is moving.
Rectanglei sliderRect() const
{
Rectanglei const rect = contentRect();
return Rectanglei(Vector2i(rect.topLeft.x + endLabelSize, rect.topLeft.y),
Vector2i(rect.bottomRight.x - endLabelSize, rect.bottomRight.y));
}
/// Determines the area where the slider currently is.
Rectanglei sliderValueRect() const
{
Rectanglei const area = sliderRect();
ddouble i = range.size() > 0? (pos - range.start) / range.size() : 0;
return Rectanglei::fromSize(Vector2i(area.topLeft.x +
(area.width() - endLabelSize) * i,
area.topLeft.y),
Vector2ui(endLabelSize, area.height()));
}
void updateGeometry()
{
Rectanglei rect;
if(self.hasChangedPlace(rect))
{
self.requestGeometry();
}
// Update texts.
for(int i = 0; i < int(NUM_LABELS); ++i)
{
if(labels[i].update())
{
//qDebug() << "label" << i << "updated";
self.requestGeometry();
}
}
if(!self.geometryRequested()) return;
//ColorBank::Colorf const accentColor = style().colors().colorf("accent");
ColorBank::Colorf const textColor = style().colors().colorf("text");
ColorBank::Colorf const invTextColor = style().colors().colorf("inverted.text");
Vector4i const margin = self.margins().toVector();
rect = rect.adjusted(margin.xy(), -margin.zw());
DefaultVertexBuf::Builder verts;
self.glMakeGeometry(verts);
// verts.makeQuad(rect, Vector4f(1, 0, 1, .5f),
// atlas().imageRectf(root().solidWhitePixel()).middle());
// Determine the area where the slider is moving.
Rectanglei sliderArea = sliderRect();
// verts.makeFlexibleFrame(sliderArea.expanded(5), 6, Vector4f(1, 1, 1, .2f),
// atlas().imageRectf(root().gradientFrame()));
// Range dots.
int numDots = de::clamp(5, round<int>(range.size() / step) + 1, 11);
int dotSpace = sliderArea.width() - endLabelSize;
int dotX = sliderArea.topLeft.x + endLabelSize / 2;
float altAlpha = 0;
if(dotSpace / numDots > 30)
{
altAlpha = .5f;
numDots = 2 * numDots + 1;
}
Image::Size const dotSize = atlas().imageRect(root().tinyDot()).size();
for(int i = 0; i < numDots; ++i)
{
Vector2i dotPos(dotX + dotSpace * float(i) / float(numDots - 1),
sliderArea.middle().y);
Vector4f dotColor = textColor;
dotColor.w *= .666f;
if(altAlpha > 0 && i % 2)
{
// Dim alt dots.
dotColor.w *= altAlpha;
}
verts.makeQuad(Rectanglei::fromSize(dotPos - dotSize.toVector2i()/2, dotSize),
dotColor, atlas().imageRectf(root().tinyDot()));
}
// Current slider position.
Rectanglei slider = sliderValueRect();
// verts.makeQuad(slider, style().colors().colorf("accent"),
// atlas().imageRectf(root().solidWhitePixel()).middle());
verts.makeQuad(slider.expanded(2), state == Grabbed? textColor : invTextColor,
atlas().imageRectf(root().solidWhitePixel()).middle());
verts.makeFlexibleFrame(slider.expanded(5), 6, Vector4f(1, 1, 1, frameOpacity),
atlas().imageRectf(root().gradientFrame()));
// Labels.
if(labels[Start].isReady())
{
labels[Start].makeVertices(verts,
Rectanglei(rect.topLeft,
Vector2i(rect.topLeft.x + endLabelSize,
rect.bottomRight.y)),
ui::AlignCenter, ui::AlignCenter,
textColor);
}
if(labels[End].isReady())
{
labels[End].makeVertices(verts,
Rectanglei(Vector2i(rect.bottomRight.x - endLabelSize,
rect.topLeft.y),
rect.bottomRight),
ui::AlignCenter, ui::AlignCenter,
textColor);
}
if(labels[Value].isReady())
{
labels[Value].makeVertices(verts, slider,
ui::AlignCenter, ui::AlignCenter,
state == Grabbed? invTextColor : textColor);
}
drawable.buffer<DefaultVertexBuf>()
.setVertices(gl::TriangleStrip, verts, animating? gl::Dynamic : gl::Static);
self.requestGeometry(false);
}
void draw()
{
updateGeometry();
uColor = Vector4f(1, 1, 1, self.visibleOpacity());
drawable.draw();
}
void setState(State st)
{
if(state == st) return;
//State const prev = state;
state = st;
animating = true;
switch(st)
{
case Inert:
//scale.setValue(1.f, .3f);
//scale.setStyle(prev == Down? Animation::Bounce : Animation::EaseOut);
frameOpacity.setValue(.25f, .6);
break;
case Hovering:
//scale.setValue(1.1f, .15f);
//scale.setStyle(Animation::EaseOut);
frameOpacity.setValue(.5f, .15);
break;
case Grabbed:
//scale.setValue(.95f);
frameOpacity.setValue(.8f);
break;
}
self.requestGeometry();
}
void updateHover(Vector2i const &pos)
{
if(state == Grabbed) return;
if(self.hitTest(pos))
{
if(state == Inert) setState(Hovering);
}
else if(state == Hovering)
{
setState(Inert);
}
}
void updateValueLabel()
{
if(!minLabel.isEmpty() && fequal(value, range.start))
{
labels[Value].setText(minLabel);
}
else if(!maxLabel.isEmpty() && fequal(value, range.end))
{
labels[Value].setText(maxLabel);
}
else
{
labels[Value].setText(QString::number(value * displayFactor, 'f', precision));
}
}
void setValue(ddouble v)
{
// Round to nearest step.
if(step > 0)
{
v = de::round<ddouble>((v - range.start) / step) * step + range.start;
}
v = range.clamp(v);
if(!fequal(v, value))
{
value = v;
updateValueLabel();
animating = true;
pos.setValue(float(value), 0.1);
self.requestGeometry();
emit self.valueChanged(v);
}
}
void updateRangeLabels()
{
labels[Start].setText(minLabel.isEmpty()? QString::number(range.start * displayFactor) : minLabel);
labels[End].setText(maxLabel.isEmpty()? QString::number(range.end * displayFactor) : maxLabel);
}
void startGrab(MouseEvent const &ev)
{
if(sliderValueRect().contains(ev.pos()))
{
setState(Grabbed);
grabFrom = ev.pos();
grabValue = value;
}
}
void updateGrab(MouseEvent const &ev)
{
DENG2_ASSERT(state == Grabbed);
//qDebug() << "delta" << (ev.pos() - grabFrom).asText();
Rectanglei const area = sliderRect();
ddouble unitsPerPixel = range.size() / (area.width() - endLabelSize);
setValue(grabValue + (ev.pos().x - grabFrom.x) * unitsPerPixel);
emit self.valueChangedByUser(value);
}
/// Amount to step when clicking a label.
ddouble clickStep() const
{
if(step > 0)
{
return step;
}
return 1.0 / std::pow(10.0, precision) / displayFactor;
}
void endGrab(MouseEvent const &ev)
{
if(state == Grabbed)
{
setState(Inert);
updateHover(ev.pos());
}
else
{
Rectanglei const rect = contentRect();
//qDebug() << "click step:" << clickStep() << "value:" << value << "range:"
// << range.asText() << "new value:" << value - clickStep();
// Maybe a click on the start/end label?
if(rect.contains(ev.pos()))
{
if(ev.pos().x < rect.left() + endLabelSize)
{
setValue(value - clickStep());
emit self.valueChangedByUser(value);
}
else if(ev.pos().x > rect.right() - endLabelSize)
{
setValue(value + clickStep());
emit self.valueChangedByUser(value);
}
}
}
}
};
SliderWidget::SliderWidget(String const &name)
: GuiWidget(name), d(new Instance(this))
{
/*
// Testing.
setRange(Rangef(0, 1));
setPrecision(2);
setValue(.5f);
*/
// Default size.
rule().setInput(Rule::Width, style().rules().rule("slider.width"))
.setInput(Rule::Height, font().height() + margins().height());
}
void SliderWidget::setRange(Rangei const &intRange, int step)
{
setRange(Ranged(intRange.start, intRange.end), ddouble(step));
}
void SliderWidget::setRange(Rangef const &floatRange, float step)
{
setRange(Ranged(floatRange.start, floatRange.end), ddouble(step));
}
void SliderWidget::setRange(Ranged const &doubleRange, ddouble step)
{
d->range = doubleRange;
d->step = step;
d->updateRangeLabels();
d->setValue(d->value);
d->pos.finish();
}
void SliderWidget::setPrecision(int precisionDecimals)
{
d->precision = precisionDecimals;
d->updateValueLabel();
}
void SliderWidget::setValue(ddouble value)
{
d->setValue(value);
}
void SliderWidget::setMinLabel(const String &labelText)
{
d->minLabel = labelText;
d->updateRangeLabels();
d->updateValueLabel();
}
void SliderWidget::setMaxLabel(const String &labelText)
{
d->maxLabel = labelText;
d->updateRangeLabels();
d->updateValueLabel();
}
void SliderWidget::setDisplayFactor(ddouble factor)
{
d->displayFactor = factor;
d->updateRangeLabels();
d->updateValueLabel();
}
Ranged SliderWidget::range() const
{
return d->range;
}
ddouble SliderWidget::value() const
{
return d->value;
}
ddouble SliderWidget::displayFactor() const
{
return d->displayFactor;
}
void SliderWidget::viewResized()
{
GuiWidget::viewResized();
d->uMvpMatrix = root().projMatrix2D();
}
void SliderWidget::update()
{
GuiWidget::update();
if(d->animating)
{
requestGeometry();
d->animating = !d->pos.done() || !d->frameOpacity.done();
}
}
void SliderWidget::drawContent()
{
d->draw();
}
bool SliderWidget::handleEvent(Event const &event)
{
if(event.type() == Event::MousePosition)
{
if(d->state == Instance::Grabbed)
{
d->updateGrab(event.as<MouseEvent>());
return true;
}
d->updateHover(event.as<MouseEvent>().pos());
}
// Left mouse button can be used to drag/step the value.
if(d->state != Instance::Inert)
{
switch(handleMouseClick(event, MouseEvent::Left))
{
case MouseClickStarted:
d->startGrab(event.as<MouseEvent>());
return true;
case MouseClickAborted:
case MouseClickFinished:
d->endGrab(event.as<MouseEvent>());
return true;
default:
break;
}
}
// Right-click to edit the value as text.
if(d->state != Instance::Grabbed)
{
switch(handleMouseClick(event, MouseEvent::Right))
{
case MouseClickFinished: {
ValuePopup *pop = new ValuePopup(*this);
pop->setAnchorAndOpeningDirection(rule(),
rule().recti().middle().y < root().viewHeight().valuei()/2? ui::Down : ui::Up);
pop->setDeleteAfterDismissed(true);
//root().add(pop);
//pop->open();
root().add(pop);
pop->open();
//pop->viewResized();
//pop->notifyTree(&Widget::viewResized);
//root().setFocus(&pop->editor());
return true; }
case MouseClickStarted:
case MouseClickAborted:
return true;
default:
break;
}
}
return GuiWidget::handleEvent(event);
}
void SliderWidget::setValueFromText(QString text)
{
setValue(text.toDouble() / d->displayFactor);
emit valueChangedByUser(d->value);
}
void SliderWidget::glInit()
{
d->glInit();
}
void SliderWidget::glDeinit()
{
d->glDeinit();
}
void SliderWidget::updateStyle()
{
d->updateStyle();
}