Don't return valid time() for the cursor pair
[pulseview.git] / pv / views / trace / ruler.cpp
blobbebf529147da67f5bc4d591255bce144d5d1674b
1 /*
2 * This file is part of the PulseView project.
4 * Copyright (C) 2012 Joel Holdsworth <joel@airwebreathe.org.uk>
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, see <http://www.gnu.org/licenses/>.
20 #include <extdef.h>
22 #include <QFontMetrics>
23 #include <QMenu>
24 #include <QMouseEvent>
26 #include <pv/globalsettings.hpp>
28 #include "ruler.hpp"
29 #include "view.hpp"
31 using namespace Qt;
33 using std::function;
34 using std::max;
35 using std::min;
36 using std::shared_ptr;
37 using std::vector;
39 namespace pv {
40 namespace views {
41 namespace trace {
43 const float Ruler::RulerHeight = 2.5f; // x Text Height
45 const float Ruler::HoverArrowSize = 0.5f; // x Text Height
47 Ruler::Ruler(View &parent) :
48 MarginWidget(parent)
50 setMouseTracking(true);
52 connect(&view_, SIGNAL(hover_point_changed(const QWidget*, QPoint)),
53 this, SLOT(on_hover_point_changed(const QWidget*, QPoint)));
54 connect(&view_, SIGNAL(offset_changed()),
55 this, SLOT(invalidate_tick_position_cache()));
56 connect(&view_, SIGNAL(scale_changed()),
57 this, SLOT(invalidate_tick_position_cache()));
58 connect(&view_, SIGNAL(tick_prefix_changed()),
59 this, SLOT(invalidate_tick_position_cache()));
60 connect(&view_, SIGNAL(tick_precision_changed()),
61 this, SLOT(invalidate_tick_position_cache()));
62 connect(&view_, SIGNAL(tick_period_changed()),
63 this, SLOT(invalidate_tick_position_cache()));
64 connect(&view_, SIGNAL(time_unit_changed()),
65 this, SLOT(invalidate_tick_position_cache()));
68 QSize Ruler::sizeHint() const
70 const int text_height = calculate_text_height();
71 return QSize(0, RulerHeight * text_height);
74 QSize Ruler::extended_size_hint() const
76 QRectF max_rect;
77 vector< shared_ptr<TimeItem> > items(view_.time_items());
78 for (auto &i : items)
79 max_rect = max_rect.united(i->label_rect(QRect()));
80 return QSize(0, sizeHint().height() - max_rect.top() / 2 +
81 ViewItem::HighlightRadius);
84 QString Ruler::format_time_with_distance(
85 const pv::util::Timestamp& distance,
86 const pv::util::Timestamp& t,
87 pv::util::SIPrefix prefix,
88 pv::util::TimeUnit unit,
89 unsigned precision,
90 bool sign)
92 const unsigned limit = 60;
94 if (t.is_zero())
95 return "0";
97 // If we have to use samples then we have no alternative formats
98 if (unit == pv::util::TimeUnit::Samples)
99 return pv::util::format_time_si_adjusted(t, prefix, precision, "sa", sign);
101 QString unit_string;
102 if (unit == pv::util::TimeUnit::Time)
103 unit_string = "s";
104 // Note: In case of pv::util::TimeUnit::None, unit_string remains empty
106 // View zoomed way out -> low precision (0), big distance (>=60s)
107 // -> DD:HH:MM
108 if ((precision == 0) && (distance >= limit))
109 return pv::util::format_time_minutes(t, 0, sign);
111 // View in "normal" range -> medium precision, medium step size
112 // -> HH:MM:SS.mmm... or xxxx (si unit) if less than limit seconds
113 // View zoomed way in -> high precision (>3), low step size (<1s)
114 // -> HH:MM:SS.mmm... or xxxx (si unit) if less than limit seconds
115 if (abs(t) < limit)
116 return pv::util::format_time_si_adjusted(t, prefix, precision, unit_string, sign);
117 else
118 return pv::util::format_time_minutes(t, precision, sign);
121 pv::util::Timestamp Ruler::get_absolute_time_from_x_pos(uint32_t x) const
123 return view_.offset() + ((double)x + 0.5) * view_.scale();
126 pv::util::Timestamp Ruler::get_ruler_time_from_x_pos(uint32_t x) const
128 return view_.ruler_offset() + ((double)x + 0.5) * view_.scale();
131 pv::util::Timestamp Ruler::get_ruler_time_from_absolute_time(const pv::util::Timestamp& abs_time) const
133 return abs_time + view_.zero_offset();
136 pv::util::Timestamp Ruler::get_absolute_time_from_ruler_time(const pv::util::Timestamp& ruler_time) const
138 return ruler_time - view_.zero_offset();
141 void Ruler::contextMenuEvent(QContextMenuEvent *event)
143 MarginWidget::contextMenuEvent(event);
145 // Don't show a context menu if the MarginWidget found a widget that shows one
146 if (event->isAccepted())
147 return;
149 context_menu_x_pos_ = event->pos().x();
151 QMenu *const menu = new QMenu(this);
153 QAction *const create_marker = new QAction(tr("Create marker here"), this);
154 connect(create_marker, SIGNAL(triggered()), this, SLOT(on_createMarker()));
155 menu->addAction(create_marker);
157 QAction *const set_zero_position = new QAction(tr("Set as zero point"), this);
158 connect(set_zero_position, SIGNAL(triggered()), this, SLOT(on_setZeroPosition()));
159 menu->addAction(set_zero_position);
161 QAction *const toggle_hover_marker = new QAction(this);
162 connect(toggle_hover_marker, SIGNAL(triggered()), this, SLOT(on_toggleHoverMarker()));
163 menu->addAction(toggle_hover_marker);
165 GlobalSettings settings;
166 const bool hover_marker_shown =
167 settings.value(GlobalSettings::Key_View_ShowHoverMarker).toBool();
168 toggle_hover_marker->setText(hover_marker_shown ?
169 tr("Disable mouse hover marker") : tr("Enable mouse hover marker"));
171 event->setAccepted(true);
172 menu->popup(event->globalPos());
175 void Ruler::resizeEvent(QResizeEvent*)
177 // the tick calculation depends on the width of this widget
178 invalidate_tick_position_cache();
181 vector< shared_ptr<ViewItem> > Ruler::items()
183 const vector< shared_ptr<TimeItem> > time_items(view_.time_items());
184 return vector< shared_ptr<ViewItem> >(
185 time_items.begin(), time_items.end());
188 void Ruler::item_hover(const shared_ptr<ViewItem> &item, QPoint pos)
190 (void)pos;
192 hover_item_ = dynamic_pointer_cast<TimeItem>(item);
195 shared_ptr<TimeItem> Ruler::get_reference_item() const
197 // Note: time() returns 0 if item returns no valid time
199 if (mouse_modifiers_ & Qt::ShiftModifier)
200 return nullptr;
202 if (hover_item_ && (hover_item_->time() != 0))
203 return hover_item_;
205 shared_ptr<TimeItem> ref_item;
206 const vector< shared_ptr<TimeItem> > items(view_.time_items());
208 for (auto i = items.rbegin(); i != items.rend(); i++) {
209 if ((*i)->enabled() && (*i)->selected()) {
210 if (!ref_item)
211 ref_item = *i;
212 else {
213 // Return nothing if multiple items are selected
214 ref_item.reset();
215 break;
220 if (ref_item && (ref_item->time() == 0))
221 ref_item.reset();
223 return ref_item;
226 shared_ptr<ViewItem> Ruler::get_mouse_over_item(const QPoint &pt)
228 const vector< shared_ptr<TimeItem> > items(view_.time_items());
230 for (auto i = items.rbegin(); i != items.rend(); i++)
231 if ((*i)->enabled() && (*i)->label_rect(rect()).contains(pt))
232 return *i;
234 return nullptr;
237 void Ruler::mouseDoubleClickEvent(QMouseEvent *event)
239 hover_item_ = view_.add_flag(get_absolute_time_from_x_pos(event->x()));
242 void Ruler::paintEvent(QPaintEvent*)
244 if (!tick_position_cache_) {
245 auto ffunc = [this](const pv::util::Timestamp& t) {
246 return format_time_with_distance(
247 this->view_.tick_period(),
249 this->view_.tick_prefix(),
250 this->view_.time_unit(),
251 this->view_.tick_precision());
254 tick_position_cache_ = calculate_tick_positions(
255 view_.tick_period(),
256 view_.ruler_offset(),
257 view_.scale(),
258 width(),
259 view_.minor_tick_count(),
260 ffunc);
263 const int ValueMargin = 3;
265 const int text_height = calculate_text_height();
266 const int ruler_height = RulerHeight * text_height;
267 const int major_tick_y1 = text_height + ValueMargin * 2;
268 const int minor_tick_y1 = (major_tick_y1 + ruler_height) / 2;
270 QPainter p(this);
272 // Draw the tick marks
273 p.setPen(palette().color(foregroundRole()));
275 for (const auto& tick: tick_position_cache_->major) {
276 const int leftedge = 0;
277 const int rightedge = width();
278 const int x_tick = tick.first;
279 if ((x_tick > leftedge) && (x_tick < rightedge)) {
280 const int x_left_bound = QFontMetrics(font()).width(tick.second) / 2;
281 const int x_right_bound = rightedge - x_left_bound;
282 const int x_legend = min(max(x_tick, x_left_bound), x_right_bound);
283 p.drawText(x_legend, ValueMargin, 0, text_height,
284 AlignCenter | AlignTop | TextDontClip, tick.second);
285 p.drawLine(QPointF(x_tick, major_tick_y1),
286 QPointF(tick.first, ruler_height));
290 for (const auto& tick: tick_position_cache_->minor) {
291 p.drawLine(QPointF(tick, minor_tick_y1),
292 QPointF(tick, ruler_height));
295 // Draw the hover mark
296 draw_hover_mark(p, text_height);
298 p.setRenderHint(QPainter::Antialiasing);
300 // The cursor labels are not drawn with the arrows exactly on the
301 // bottom line of the widget, because then the selection shadow
302 // would be clipped away.
303 const QRect r = rect().adjusted(0, 0, 0, -ViewItem::HighlightRadius);
305 // Draw the items
306 const vector< shared_ptr<TimeItem> > items(view_.time_items());
307 for (auto &i : items) {
308 const bool highlight = !item_dragging_ &&
309 i->label_rect(r).contains(mouse_point_);
310 i->paint_label(p, r, highlight);
314 void Ruler::draw_hover_mark(QPainter &p, int text_height)
316 const int x = view_.hover_point().x();
318 if (x == -1)
319 return;
321 p.setPen(QPen(Qt::NoPen));
322 p.setBrush(QBrush(palette().color(foregroundRole())));
324 const int b = RulerHeight * text_height;
325 const float hover_arrow_size = HoverArrowSize * text_height;
326 const QPointF points[] = {
327 QPointF(x, b),
328 QPointF(x - hover_arrow_size, b - hover_arrow_size),
329 QPointF(x + hover_arrow_size, b - hover_arrow_size)
331 p.drawPolygon(points, countof(points));
334 int Ruler::calculate_text_height() const
336 return QFontMetrics(font()).ascent();
339 TickPositions Ruler::calculate_tick_positions(
340 const pv::util::Timestamp& major_period,
341 const pv::util::Timestamp& offset,
342 const double scale,
343 const int width,
344 const unsigned int minor_tick_count,
345 function<QString(const pv::util::Timestamp&)> format_function)
347 TickPositions tp;
349 const pv::util::Timestamp minor_period = major_period / minor_tick_count;
350 const pv::util::Timestamp first_major_division = floor(offset / major_period);
351 const pv::util::Timestamp first_minor_division = ceil(offset / minor_period);
352 const pv::util::Timestamp t0 = first_major_division * major_period;
354 int division = (round(first_minor_division -
355 first_major_division * minor_tick_count)).convert_to<int>() - 1;
357 double x;
359 do {
360 pv::util::Timestamp t = t0 + division * minor_period;
361 x = ((t - offset) / scale).convert_to<double>();
363 if (division % minor_tick_count == 0) {
364 // Recalculate 't' without using 'minor_period' which is a fraction
365 t = t0 + division / minor_tick_count * major_period;
366 tp.major.emplace_back(x, format_function(t));
367 } else {
368 tp.minor.emplace_back(x);
371 division++;
372 } while (x < width);
374 return tp;
377 void Ruler::on_hover_point_changed(const QWidget* widget, const QPoint &hp)
379 (void)widget;
380 (void)hp;
382 update();
385 void Ruler::invalidate_tick_position_cache()
387 tick_position_cache_ = boost::none;
390 void Ruler::on_createMarker()
392 hover_item_ = view_.add_flag(get_absolute_time_from_x_pos(mouse_down_point_.x()));
395 void Ruler::on_setZeroPosition()
397 view_.set_zero_position(get_absolute_time_from_x_pos(mouse_down_point_.x()));
400 void Ruler::on_toggleHoverMarker()
402 GlobalSettings settings;
403 const bool state = settings.value(GlobalSettings::Key_View_ShowHoverMarker).toBool();
404 settings.setValue(GlobalSettings::Key_View_ShowHoverMarker, !state);
407 } // namespace trace
408 } // namespace views
409 } // namespace pv