7 #include "WaypointList.hxx"
10 #include <boost/tuple/tuple.hpp>
12 #include <plib/puAux.h>
14 #include <simgear/route/waypoint.hxx>
15 #include <simgear/structure/callback.hxx>
16 #include <simgear/sg_inlines.h>
18 #include <Main/globals.hxx>
19 #include <Main/fg_props.hxx>
21 #include <Navaids/positioned.hxx>
22 #include <Autopilot/route_mgr.hxx>
24 // select if the widget grabs keys necessary to fly aircraft from the keyboard,
25 // or not. See http://code.google.com/p/flightgear-bugs/issues/detail?id=338
26 // for discussion about why / what is going on.
27 #define AVOID_FLIGHT_KEYS 1
29 using namespace flightgear;
37 static const double BLINK_TIME = 0.3;
38 static const int DRAG_START_DISTANCE_PX = 5;
40 class RouteManagerWaypointModel :
41 public WaypointList::Model,
42 public SGPropertyChangeListener
45 RouteManagerWaypointModel()
47 _rm = static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"));
49 SGPropertyNode* routeEdited = fgGetNode("/autopilot/route-manager/signals/edited", true);
50 routeEdited->addChangeListener(this);
53 virtual ~RouteManagerWaypointModel()
55 SGPropertyNode* routeEdited = fgGetNode("/autopilot/route-manager/signals/edited", true);
56 routeEdited->removeChangeListener(this);
59 // implement WaypointList::Model
60 virtual unsigned int numWaypoints() const
62 return _rm->numWaypts();
65 virtual int currentWaypoint() const
67 return _rm->currentIndex();
70 virtual flightgear::Waypt* waypointAt(unsigned int index) const
72 if (index >= numWaypoints()) {
76 return _rm->wayptAtIndex(index);
79 virtual void deleteAt(unsigned int index)
81 _rm->removeWayptAtIndex(index);
84 virtual void moveWaypointToIndex(unsigned int srcIndex, unsigned int destIndex)
86 SG_LOG(SG_GENERAL, SG_INFO, "moveWaypoint: from " << srcIndex << " to " << destIndex);
87 if (destIndex > srcIndex) {
91 unsigned int currentWpIndex = currentWaypoint();
92 WayptRef w(_rm->removeWayptAtIndex(srcIndex));
93 SG_LOG(SG_GENERAL, SG_INFO, "wpt:" << w->ident());
94 _rm->insertWayptAtIndex(w, destIndex);
96 if (srcIndex == currentWpIndex) {
97 // current waypoint was moved
98 _rm->jumpToIndex(destIndex);
102 virtual void setUpdateCallback(SGCallback* cb)
107 // implement SGPropertyChangeListener
108 void valueChanged(SGPropertyNode *prop)
119 //////////////////////////////////////////////////////////////////////////////
121 static void drawClippedString(puFont& font, const char* s, int x, int y, int maxWidth)
123 int fullWidth = font.getStringWidth(s);
124 if (fullWidth <= maxWidth) { // common case, easy and efficent
125 font.drawString(s, x, y);
130 int len = buf.size();
133 fullWidth = font.getStringWidth(buf.c_str());
134 } while (fullWidth > maxWidth);
136 font.drawString(buf.c_str(), x, y);
139 //////////////////////////////////////////////////////////////////////////////
141 WaypointList::WaypointList(int x, int y, int width, int height) :
142 puFrame(x, y, width, height),
143 GUI_ID(FGCLASS_WAYPOINTLIST),
146 _dragScroll(SCROLL_NO),
149 _updateCallback(NULL),
150 _scrollCallback(NULL),
153 // pretend to be a list, so fgPopup doesn't mess with our mouse events
154 type |= PUCLASS_LIST;
155 setModel(new RouteManagerWaypointModel());
156 setSize(width, height);
162 WaypointList::~WaypointList()
165 delete _updateCallback;
166 delete _scrollCallback;
169 void WaypointList::setUpdateCallback(SGCallback* cb)
171 _updateCallback = cb;
174 void WaypointList::setScrollCallback(SGCallback* cb)
176 _scrollCallback = cb;
179 void WaypointList::setSize(int width, int height)
181 double scrollP = getVScrollPercent();
183 puFrame::setSize(width, height);
185 if (wantsVScroll()) {
186 setVScrollPercent(scrollP);
192 int WaypointList::checkHit ( int button, int updown, int x, int y )
194 if ( isHit( x, y ) || ( puActiveWidget () == this ) )
196 doHit ( button, updown, x, y ) ;
204 void WaypointList::doHit( int button, int updown, int x, int y )
206 puFrame::doHit(button, updown, x, y);
207 if (updown == PU_DRAG) {
212 if (button != active_mouse_button) {
216 if (updown == PU_UP) {
217 puDeactivateWidget();
222 } else if (updown == PU_DOWN) {
223 puSetActiveWidget(this, x, y);
230 int row = rowForY(y - abox.min[1]);
231 if (row >= (int) _model->numWaypoints()) {
232 row = -1; // 'no selection'
235 if (row == getSelected()) {
236 _showLatLon = !_showLatLon;
244 void WaypointList::handleDrag(int x, int y)
247 // don't start drags immediately, require a certain mouse movement first
248 int manhattanLength = abs(x - _mouseDownX) + abs(y - _mouseDownY);
249 if (manhattanLength < DRAG_START_DISTANCE_PX) {
253 _dragSourceRow = rowForY(y - abox.min[1]);
254 Waypt* wp = _model->waypointAt(_dragSourceRow);
255 if (!wp || wp->flag(WPT_GENERATED)) {
256 return; // don't allow generated points to be dragged
260 _dragScroll = SCROLL_NO;
263 if (y < abox.min[1]) {
264 if (_dragScroll != SCROLL_DOWN) {
265 _dragScroll = SCROLL_DOWN;
266 _dragScrollTime.stamp();
268 } else if (y > abox.max[1]) {
269 if (_dragScroll != SCROLL_UP) {
270 _dragScroll = SCROLL_UP;
271 _dragScrollTime.stamp();
274 _dragScroll = SCROLL_NO;
275 _dragTargetRow = rowForY(y - abox.min[1] - (rowHeightPx() / 2));
279 void WaypointList::doDrop(int x, int y)
282 puDeactivateWidget();
284 SG_LOG(SG_GENERAL, SG_INFO, "doDrop");
286 if ((y < abox.min[1]) || (y >= abox.max[1])) {
287 SG_LOG(SG_GENERAL, SG_INFO, "y out of bounds:" << y);
291 if (_dragSourceRow == _dragTargetRow) {
292 SG_LOG(SG_GENERAL, SG_INFO, "source and target row match");
296 _model->moveWaypointToIndex(_dragSourceRow, _dragTargetRow);
298 // keep row indexes linged up when moving an item down the list
299 if (_dragSourceRow < _dragTargetRow) {
303 setSelected(_dragTargetRow);
306 void WaypointList::invokeDownCallback(void)
309 _dragScroll = SCROLL_NO;
310 SG_LOG(SG_GENERAL, SG_INFO, "cancel drag");
313 int WaypointList::rowForY(int y) const
319 // flip y to increase down, not up (as rows do)
320 int flipY = _heightPx - y;
321 int row = (flipY + _scrollPx) / rowHeightPx();
325 void WaypointList::draw( int dx, int dy )
327 puFrame::draw(dx, dy);
333 if (_dragScroll != SCROLL_NO) {
337 double dt = (SGTimeStamp::now() - _blinkTimer).toSecs();
338 if (dt > BLINK_TIME) {
343 glEnable(GL_SCISSOR_TEST);
344 GLint sx = (int) abox.min[0],
346 GLsizei w = (GLsizei) abox.max[0] - abox.min[0],
349 sx += border_thickness;
350 sy += border_thickness;
351 w -= 2 * border_thickness;
352 h -= 2 * border_thickness;
354 glScissor(sx + dx, sy + dy, w, h);
355 int row = firstVisibleRow(),
356 final = lastVisibleRow(),
357 rowHeight = rowHeightPx(),
360 y -= (_scrollPx % rowHeight); // partially draw the first row
362 _arrowWidth = legendFont.getStringWidth(">");
363 for ( ; row <= final; ++row, y += rowHeight) {
364 drawRow(dx, dy, row, y);
365 } // of row drawing iteration
367 glDisable(GL_SCISSOR_TEST);
370 // draw the insert marker after the rows
371 int insertY = (_dragTargetRow * rowHeight) - _scrollPx;
372 SG_CLAMP_RANGE(insertY, 0, std::min(_heightPx, totalHeightPx()));
374 glColor4f(1.0f, 0.5f, 0.0f, 0.8f);
377 glVertex2f(dx + abox.min[0], dy + abox.max[1] - insertY);
378 glVertex2f(dx + abox.max[0], dy + abox.max[1] - insertY);
383 void WaypointList::drawRow(int dx, int dy, int rowIndex, int y)
385 flightgear::Waypt* wp(_model->waypointAt(rowIndex));
387 bool isSelected = (rowIndex == getSelected());
388 bool isCurrent = (rowIndex == _model->currentWaypoint());
389 bool isDragSource = (_dragging && (rowIndex == _dragSourceRow));
392 bkgBox.min[1] = abox.max[1] - y;
393 bkgBox.max[1] = bkgBox.min[1] + rowHeightPx();
396 puFont* f = &legendFont;
397 bool drawBox = false;
399 if (wp->flag(WPT_MISS)) {
401 puSetColor(col, 1.0, 0.0, 0.0, 0.3); // red
402 } else if (wp->flag(WPT_ARRIVAL)) {
404 puSetColor(col, 0.0, 0.0, 0.0, 0.3);
405 } else if (wp->flag(WPT_DEPARTURE)) {
407 puSetColor(col, 0.0, 0.0, 0.0, 0.3);
411 // draw later, on *top* of text string
412 } else if (isSelected) { // -PLAIN means selected, apparently
413 bkgBox.draw(dx, dy, -PUSTYLE_PLAIN, colour, false, 0);
414 } else if (drawBox) {
415 bkgBox.draw(dx, dy, PUSTYLE_PLAIN, &col, false, 0);
419 glColor4f (1.0, 0.5, 0.0, 1.0) ;
421 glColor4fv ( colour [ PUCOL_LEGEND ] ) ;
424 int xx = dx + abox.min[0] + PUSTR_LGAP;
425 int yy = dy + abox.max[1] - y ;
426 yy += 4; // center text in row height
429 f->drawString(">", xx, yy);
433 x += _arrowWidth + PUSTR_LGAP;
438 int count = ::snprintf(buffer, 128, "%03d %-5s", rowIndex, wp->ident().c_str());
440 FGPositioned* src = wp->source();
441 if (src && !src->name().empty() && (src->name() != wp->ident())) {
442 // append name if present, and different to id
443 ::snprintf(buffer + count, 128 - count, " (%s)", src->name().c_str());
446 drawClippedString(legendFont, buffer, x, yy, 300);
447 x += 300 + PUSTR_LGAP;
450 SGGeod p(wp->position());
451 char ns = (p.getLatitudeDeg() > 0.0) ? 'N' : 'S';
452 char ew = (p.getLongitudeDeg() > 0.0) ? 'E' : 'W';
454 ::snprintf(buffer, 128 - count, "%4.2f%c %4.2f%c",
455 fabs(p.getLongitudeDeg()), ew, fabs(p.getLatitudeDeg()), ns);
456 } else if (rowIndex > 0) {
459 Waypt* prev = _model->waypointAt(rowIndex - 1);
460 boost::tie(courseDeg, distanceM) = wp->courseAndDistanceFrom(prev->position());
462 ::snprintf(buffer, 128 - count, "%03.0f %5.1fnm",
463 courseDeg, distanceM * SG_METER_TO_NM);
466 f->drawString(buffer, x, yy);
467 x += 100 + PUSTR_LGAP;
469 if (wp->altitudeRestriction() != RESTRICT_NONE) {
470 int altHundredFt = (wp->altitudeFt() + 50) / 100; // round to nearest 100ft
471 if (altHundredFt < 100) {
472 count = ::snprintf(buffer, 128, "%d'", altHundredFt * 100);
473 } else { // display as a flight-level
474 count = ::snprintf(buffer, 128, "FL%d", altHundredFt);
477 f->drawString(buffer, x, yy);
478 } // of valid wp altitude
479 x += 60 + PUSTR_LGAP;
481 if (wp->speedRestriction() == SPEED_RESTRICT_MACH) {
482 count = ::snprintf(buffer, 126, "%03.2fM", wp->speedMach());
483 f->drawString(buffer, x, yy);
484 } else if (wp->speedRestriction() != RESTRICT_NONE) {
485 count = ::snprintf(buffer, 126, "%dKts", (int) wp->speedKts());
486 f->drawString(buffer, x, yy);
490 puSetColor(col, 1.0, 0.5, 0.0, 0.5);
491 bkgBox.draw(dx, dy, PUSTYLE_PLAIN, &col, false, 0);
495 const double SCROLL_PX_SEC = 200.0;
497 void WaypointList::doDragScroll()
499 double dt = (SGTimeStamp::now() - _dragScrollTime).toSecs();
500 _dragScrollTime.stamp();
501 int deltaPx = (int)(dt * SCROLL_PX_SEC);
503 if (_dragScroll == SCROLL_UP) {
504 _scrollPx = _scrollPx - deltaPx;
505 SG_CLAMP_RANGE(_scrollPx, 0, scrollRangePx());
506 _dragTargetRow = firstVisibleRow();
508 _scrollPx = _scrollPx + deltaPx;
509 SG_CLAMP_RANGE(_scrollPx, 0, scrollRangePx());
510 _dragTargetRow = lastFullyVisibleRow() + 1;
513 if (_scrollCallback) {
514 (*_scrollCallback)();
518 int WaypointList::getSelected()
520 return getIntegerValue();
523 void WaypointList::setSelected(int rowIndex)
525 if (rowIndex == getSelected()) {
531 if (rowIndex == -1) {
535 ensureRowVisible(rowIndex);
538 void WaypointList::ensureRowVisible(int rowIndex)
540 if ((rowIndex >= firstFullyVisibleRow()) && (rowIndex <= lastFullyVisibleRow())) {
541 return; // already visible, fine
544 // ideal position would place the desired row in the middle of the
545 // visible section - hence subtract half the visible height.
546 int targetScrollPx = (rowIndex * rowHeightPx()) - (_heightPx / 2);
548 // clamp the scroll value to something valid
549 SG_CLAMP_RANGE(targetScrollPx, 0, scrollRangePx());
550 _scrollPx = targetScrollPx;
553 if (_scrollCallback) { // keep scroll observers in sync
554 (*_scrollCallback)();
558 unsigned int WaypointList::numWaypoints() const
564 return _model->numWaypoints();
567 bool WaypointList::wantsVScroll() const
569 return totalHeightPx() > _heightPx;
572 float WaypointList::getVScrollPercent() const
574 float scrollRange = scrollRangePx();
575 if (scrollRange < 1.0f) {
579 return _scrollPx / scrollRange;
582 float WaypointList::getVScrollThumbPercent() const
584 return _heightPx / (float) totalHeightPx();
587 void WaypointList::setVScrollPercent(float perc)
589 float scrollRange = scrollRangePx();
590 _scrollPx = (int)(scrollRange * perc);
593 int WaypointList::firstVisibleRow() const
595 return _scrollPx / rowHeightPx();
598 int WaypointList::firstFullyVisibleRow() const
600 int rh = rowHeightPx();
601 return (_scrollPx + rh - 1) / rh;
604 int WaypointList::numVisibleRows() const
606 int rh = rowHeightPx();
607 int topOffset = _scrollPx % rh; // pixels of first visible row
608 return (_heightPx - topOffset + rh - 1) / rh;
612 int WaypointList::numFullyVisibleRows() const
614 int rh = rowHeightPx();
615 int topOffset = _scrollPx % rh; // pixels of first visible row
616 return (_heightPx - topOffset) / rh;
619 int WaypointList::rowHeightPx() const
621 return legendFont.getStringHeight() + PUSTR_BGAP;
624 int WaypointList::scrollRangePx() const
626 return std::max(0, totalHeightPx() - _heightPx);
629 int WaypointList::totalHeightPx() const
635 return (int) _model->numWaypoints() * rowHeightPx();
638 int WaypointList::lastFullyVisibleRow() const
640 int row = firstFullyVisibleRow() + numFullyVisibleRows();
641 return std::min(row, (int) _model->numWaypoints() - 1);
644 int WaypointList::lastVisibleRow() const
646 int row = firstVisibleRow() + numVisibleRows();
647 return std::min(row, (int) _model->numWaypoints() - 1);
650 void WaypointList::setModel(Model* model)
657 _model->setUpdateCallback(make_callback(this, &WaypointList::modelUpdateCallback));
662 int WaypointList::checkKey (int key, int updown )
664 if ((updown == PU_UP) || !isVisible () || !isActive () || (window != puGetWindow())) {
668 #ifdef AVOID_FLIGHT_KEYS
679 setSelected(_model->numWaypoints() - 1);
683 case PU_KEY_PAGE_UP :
684 if (getSelected() >= 0) {
685 setSelected(getSelected() - 1);
690 case PU_KEY_PAGE_DOWN : {
691 int newSel = getSelected() + 1;
692 if (newSel >= (int) _model->numWaypoints()) {
701 if (getSelected() >= 0) {
702 Waypt* wp = _model->waypointAt(getSelected());
703 if (wp->flag(WPT_GENERATED)) {
707 if (wp->altitudeRestriction() != RESTRICT_NONE) {
708 int curAlt = (static_cast<int>(wp->altitudeFt()) + 50) / 100;
710 wp->setAltitude(0, RESTRICT_NONE);
712 wp->setAltitude((curAlt - 10) * 100, wp->altitudeRestriction());
719 if (getSelected() >= 0) {
720 flightgear::Waypt* wp = _model->waypointAt(getSelected());
721 if (wp->flag(WPT_GENERATED)) {
725 if (wp->altitudeRestriction() == RESTRICT_NONE) {
726 wp->setAltitude(1000, RESTRICT_AT);
728 int curAlt = (static_cast<int>(wp->altitudeFt()) + 50) / 100;
729 wp->setAltitude((curAlt + 10) * 100, wp->altitudeRestriction());
735 if (getSelected() >= 0) {
736 int index = getSelected();
737 Waypt* wp = _model->waypointAt(getSelected());
738 if (wp->flag(WPT_GENERATED)) {
742 _model->deleteAt(index);
743 setSelected(index - 1);
754 void WaypointList::modelUpdateCallback()
758 if (_updateCallback) {
759 (*_updateCallback)();
763 //////////////////////////////////////////////////////////////////////////////
766 static void handle_scrollbar(puObject* scrollbar)
768 ScrolledWaypointList* self = (ScrolledWaypointList*)scrollbar->getUserData();
769 self->setScrollPercent(scrollbar->getFloatValue());
772 static void waypointListCb(puObject* wpl)
774 ScrolledWaypointList* self = (ScrolledWaypointList*)wpl->getUserData();
775 self->setValue(wpl->getIntegerValue());
776 self->invokeCallback();
779 ScrolledWaypointList::ScrolledWaypointList(int x, int y, int width, int height) :
783 // ensure our type is compound, so fgPopup::applySize doesn't descend into
784 // us, and try to cast our children's user-data to GUIInfo*.
785 type |= PUCLASS_LIST;
790 void ScrolledWaypointList::setValue(float v)
792 puGroup::setValue(v);
796 void ScrolledWaypointList::setValue(int v)
798 puGroup::setValue(v);
802 void ScrolledWaypointList::init(int w, int h)
804 _list = new WaypointList(0, 0, w, h);
805 _list->setUpdateCallback(make_callback(this, &ScrolledWaypointList::modelUpdated));
806 _hasVScroll = _list->wantsVScroll();
807 _list->setUserData(this);
808 _list->setCallback(waypointListCb);
810 _list->setScrollCallback(make_callback(this, &ScrolledWaypointList::updateScroll));
812 _scrollbar = new puaScrollBar(w - _scrollWidth, 0, h,
813 1 /*arrow*/, 1 /* vertical */, _scrollWidth);
814 _scrollbar->setMinValue(0.0);
815 _scrollbar->setMaxValue(1.0);
816 _scrollbar->setUserData(this);
817 _scrollbar->setCallback(handle_scrollbar);
818 close(); // close the group
823 void ScrolledWaypointList::modelUpdated()
827 updateWantsScroll(w, h);
830 void ScrolledWaypointList::setScrollPercent(float v)
832 // slider's min is the bottom, so invert the value
833 _list->setVScrollPercent(1.0f - v);
836 void ScrolledWaypointList::setSize(int w, int h)
838 updateWantsScroll(w, h);
839 puGroup::setSize(w, h);
842 void ScrolledWaypointList::updateWantsScroll(int w, int h)
844 _hasVScroll = _list->wantsVScroll();
847 _scrollbar->reveal();
848 _scrollbar->setPosition(w - _scrollWidth, 0);
849 _scrollbar->setSize(_scrollWidth, h);
850 _list->setSize(w - _scrollWidth, h);
854 _list->setSize(w, h);
858 void ScrolledWaypointList::updateScroll()
860 // _scrollbar->setMaxValue(_list->numWaypoints());
861 _scrollbar->setValue(1.0f - _list->getVScrollPercent());
862 _scrollbar->setSliderFraction(_list->getVScrollThumbPercent());