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 FlightPlanWaypointModel :
41 public WaypointList::Model,
42 public SGPropertyChangeListener
45 FlightPlanWaypointModel(flightgear::FlightPlan* fp) :
48 SGPropertyNode* routeEdited = fgGetNode("/autopilot/route-manager/signals/edited", true);
49 SGPropertyNode* flightplanChanged = fgGetNode("/autopilot/route-manager/signals/flightplan-changed", true);
50 routeEdited->addChangeListener(this);
51 flightplanChanged->addChangeListener(this);
54 ~FlightPlanWaypointModel()
56 SGPropertyNode* routeEdited = fgGetNode("/autopilot/route-manager/signals/edited", true);
57 SGPropertyNode* flightplanChanged = fgGetNode("/autopilot/route-manager/signals/flightplan-changed", true);
58 routeEdited->removeChangeListener(this);
59 flightplanChanged->removeChangeListener(this);
62 // implement WaypointList::Model
63 virtual unsigned int numWaypoints() const
65 return _fp->numLegs();
68 virtual int currentWaypoint() const
70 return _fp->currentIndex();
73 virtual flightgear::Waypt* waypointAt(unsigned int index) const
75 if (index >= numWaypoints()) {
79 return _fp->legAtIndex(index)->waypoint();
82 virtual void deleteAt(unsigned int index)
84 _fp->deleteIndex(index);
87 virtual void moveWaypointToIndex(unsigned int srcIndex, unsigned int destIndex)
89 SG_LOG(SG_GENERAL, SG_INFO, "moveWaypoint: from " << srcIndex << " to " << destIndex);
90 if (destIndex > srcIndex) {
94 unsigned int currentWpIndex = currentWaypoint();
95 WayptRef w(waypointAt(currentWpIndex));
96 _fp->deleteIndex(currentWpIndex);
98 SG_LOG(SG_GENERAL, SG_INFO, "wpt:" << w->ident());
99 _fp->insertWayptAtIndex(w, destIndex);
101 if (srcIndex == currentWpIndex) {
102 // current waypoint was moved
103 _fp->setCurrentIndex(destIndex);
107 virtual void setUpdateCallback(SGCallback* cb)
112 // implement SGPropertyChangeListener
113 void valueChanged(SGPropertyNode *prop)
115 if (prop->getNameString() == "edited") {
121 if (prop->getNameString() == "flightplan-changed") {
123 static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"))->flightPlan();
127 flightgear::FlightPlan* _fp;
131 //////////////////////////////////////////////////////////////////////////////
133 static void drawClippedString(puFont& font, const char* s, int x, int y, int maxWidth)
135 int fullWidth = font.getStringWidth(s);
136 if (fullWidth <= maxWidth) { // common case, easy and efficent
137 font.drawString(s, x, y);
142 int len = buf.size();
145 fullWidth = font.getStringWidth(buf.c_str());
146 } while (fullWidth > maxWidth);
148 font.drawString(buf.c_str(), x, y);
151 //////////////////////////////////////////////////////////////////////////////
153 WaypointList::WaypointList(int x, int y, int width, int height) :
154 puFrame(x, y, width, height),
155 GUI_ID(FGCLASS_WAYPOINTLIST),
158 _dragScroll(SCROLL_NO),
161 _updateCallback(NULL),
162 _scrollCallback(NULL),
165 // pretend to be a list, so fgPopup doesn't mess with our mouse events
166 type |= PUCLASS_LIST;
167 flightgear::FlightPlan* fp =
168 static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"))->flightPlan();
169 setModel(new FlightPlanWaypointModel(fp));
170 setSize(width, height);
176 WaypointList::~WaypointList()
179 delete _updateCallback;
180 delete _scrollCallback;
183 void WaypointList::setUpdateCallback(SGCallback* cb)
185 _updateCallback = cb;
188 void WaypointList::setScrollCallback(SGCallback* cb)
190 _scrollCallback = cb;
193 void WaypointList::setSize(int width, int height)
195 double scrollP = getVScrollPercent();
197 puFrame::setSize(width, height);
199 if (wantsVScroll()) {
200 setVScrollPercent(scrollP);
206 int WaypointList::checkHit ( int button, int updown, int x, int y )
208 if ( isHit( x, y ) || ( puActiveWidget () == this ) )
210 doHit ( button, updown, x, y ) ;
218 void WaypointList::doHit( int button, int updown, int x, int y )
220 puFrame::doHit(button, updown, x, y);
221 if (updown == PU_DRAG) {
226 if (button != active_mouse_button) {
230 if (updown == PU_UP) {
231 puDeactivateWidget();
236 } else if (updown == PU_DOWN) {
237 puSetActiveWidget(this, x, y);
244 int row = rowForY(y - abox.min[1]);
245 if (row >= (int) _model->numWaypoints()) {
246 row = -1; // 'no selection'
249 if (row == getSelected()) {
250 _showLatLon = !_showLatLon;
258 void WaypointList::handleDrag(int x, int y)
261 // don't start drags immediately, require a certain mouse movement first
262 int manhattanLength = abs(x - _mouseDownX) + abs(y - _mouseDownY);
263 if (manhattanLength < DRAG_START_DISTANCE_PX) {
267 _dragSourceRow = rowForY(y - abox.min[1]);
268 Waypt* wp = _model->waypointAt(_dragSourceRow);
269 if (!wp || wp->flag(WPT_GENERATED)) {
270 return; // don't allow generated points to be dragged
274 _dragScroll = SCROLL_NO;
277 if (y < abox.min[1]) {
278 if (_dragScroll != SCROLL_DOWN) {
279 _dragScroll = SCROLL_DOWN;
280 _dragScrollTime.stamp();
282 } else if (y > abox.max[1]) {
283 if (_dragScroll != SCROLL_UP) {
284 _dragScroll = SCROLL_UP;
285 _dragScrollTime.stamp();
288 _dragScroll = SCROLL_NO;
289 _dragTargetRow = rowForY(y - abox.min[1] - (rowHeightPx() / 2));
293 void WaypointList::doDrop(int x, int y)
296 puDeactivateWidget();
298 SG_LOG(SG_GENERAL, SG_INFO, "doDrop");
300 if ((y < abox.min[1]) || (y >= abox.max[1])) {
301 SG_LOG(SG_GENERAL, SG_INFO, "y out of bounds:" << y);
305 if (_dragSourceRow == _dragTargetRow) {
306 SG_LOG(SG_GENERAL, SG_INFO, "source and target row match");
310 _model->moveWaypointToIndex(_dragSourceRow, _dragTargetRow);
312 // keep row indexes linged up when moving an item down the list
313 if (_dragSourceRow < _dragTargetRow) {
317 setSelected(_dragTargetRow);
320 void WaypointList::invokeDownCallback(void)
323 _dragScroll = SCROLL_NO;
324 SG_LOG(SG_GENERAL, SG_INFO, "cancel drag");
327 int WaypointList::rowForY(int y) const
333 // flip y to increase down, not up (as rows do)
334 int flipY = _heightPx - y;
335 int row = (flipY + _scrollPx) / rowHeightPx();
339 void WaypointList::draw( int dx, int dy )
341 puFrame::draw(dx, dy);
347 if (_dragScroll != SCROLL_NO) {
351 double dt = (SGTimeStamp::now() - _blinkTimer).toSecs();
352 if (dt > BLINK_TIME) {
357 glEnable(GL_SCISSOR_TEST);
358 GLint sx = (int) abox.min[0],
360 GLsizei w = (GLsizei) abox.max[0] - abox.min[0],
363 sx += border_thickness;
364 sy += border_thickness;
365 w -= 2 * border_thickness;
366 h -= 2 * border_thickness;
368 glScissor(sx + dx, sy + dy, w, h);
369 int row = firstVisibleRow(),
370 final = lastVisibleRow(),
371 rowHeight = rowHeightPx(),
374 y -= (_scrollPx % rowHeight); // partially draw the first row
376 _arrowWidth = legendFont.getStringWidth(">");
377 for ( ; row <= final; ++row, y += rowHeight) {
378 drawRow(dx, dy, row, y);
379 } // of row drawing iteration
381 glDisable(GL_SCISSOR_TEST);
384 // draw the insert marker after the rows
385 int insertY = (_dragTargetRow * rowHeight) - _scrollPx;
386 SG_CLAMP_RANGE(insertY, 0, std::min(_heightPx, totalHeightPx()));
388 glColor4f(1.0f, 0.5f, 0.0f, 0.8f);
391 glVertex2f(dx + abox.min[0], dy + abox.max[1] - insertY);
392 glVertex2f(dx + abox.max[0], dy + abox.max[1] - insertY);
397 void WaypointList::drawRow(int dx, int dy, int rowIndex, int y)
399 flightgear::Waypt* wp(_model->waypointAt(rowIndex));
401 bool isSelected = (rowIndex == getSelected());
402 bool isCurrent = (rowIndex == _model->currentWaypoint());
403 bool isDragSource = (_dragging && (rowIndex == _dragSourceRow));
406 bkgBox.min[1] = abox.max[1] - y;
407 bkgBox.max[1] = bkgBox.min[1] + rowHeightPx();
410 puFont* f = &legendFont;
411 bool drawBox = false;
413 if (wp->flag(WPT_MISS)) {
415 puSetColor(col, 1.0, 0.0, 0.0, 0.3); // red
416 } else if (wp->flag(WPT_ARRIVAL) || wp->flag(WPT_DEPARTURE)) {
418 puSetColor(col, 0.0, 0.0, 0.0, 0.3);
419 } else if (wp->flag(WPT_APPROACH)) {
421 puSetColor(col, 0.0, 0.0, 0.1, 0.3);
425 // draw later, on *top* of text string
426 } else if (isSelected) { // -PLAIN means selected, apparently
427 bkgBox.draw(dx, dy, -PUSTYLE_PLAIN, colour, false, 0);
428 } else if (drawBox) {
429 bkgBox.draw(dx, dy, PUSTYLE_PLAIN, &col, false, 0);
433 glColor4f (1.0, 0.5, 0.0, 1.0) ;
435 glColor4fv ( colour [ PUCOL_LEGEND ] ) ;
438 int xx = dx + abox.min[0] + PUSTR_LGAP;
439 int yy = dy + abox.max[1] - y ;
440 yy += 4; // center text in row height
443 f->drawString(">", xx, yy);
447 x += _arrowWidth + PUSTR_LGAP;
452 int count = ::snprintf(buffer, 128, "%03d %-5s", rowIndex, wp->ident().c_str());
454 FGPositioned* src = wp->source();
455 if (src && !src->name().empty() && (src->name() != wp->ident())) {
456 // append name if present, and different to id
457 ::snprintf(buffer + count, 128 - count, " (%s)", src->name().c_str());
460 drawClippedString(legendFont, buffer, x, yy, 300);
461 x += 300 + PUSTR_LGAP;
464 SGGeod p(wp->position());
465 char ns = (p.getLatitudeDeg() > 0.0) ? 'N' : 'S';
466 char ew = (p.getLongitudeDeg() > 0.0) ? 'E' : 'W';
468 ::snprintf(buffer, 128 - count, "%4.2f%c %4.2f%c",
469 fabs(p.getLongitudeDeg()), ew, fabs(p.getLatitudeDeg()), ns);
470 } else if (rowIndex > 0) {
473 Waypt* prev = _model->waypointAt(rowIndex - 1);
474 boost::tie(courseDeg, distanceM) = wp->courseAndDistanceFrom(prev->position());
476 ::snprintf(buffer, 128 - count, "%03.0f %5.1fnm",
477 courseDeg, distanceM * SG_METER_TO_NM);
480 f->drawString(buffer, x, yy);
481 x += 100 + PUSTR_LGAP;
483 if (wp->altitudeRestriction() != RESTRICT_NONE) {
484 int altHundredFt = (wp->altitudeFt() + 50) / 100; // round to nearest 100ft
485 if (altHundredFt < 100) {
486 count = ::snprintf(buffer, 128, "%d'", altHundredFt * 100);
487 } else { // display as a flight-level
488 count = ::snprintf(buffer, 128, "FL%d", altHundredFt);
491 f->drawString(buffer, x, yy);
492 } // of valid wp altitude
493 x += 60 + PUSTR_LGAP;
495 if (wp->speedRestriction() == SPEED_RESTRICT_MACH) {
496 count = ::snprintf(buffer, 126, "%03.2fM", wp->speedMach());
497 f->drawString(buffer, x, yy);
498 } else if (wp->speedRestriction() != RESTRICT_NONE) {
499 count = ::snprintf(buffer, 126, "%dKts", (int) wp->speedKts());
500 f->drawString(buffer, x, yy);
504 puSetColor(col, 1.0, 0.5, 0.0, 0.5);
505 bkgBox.draw(dx, dy, PUSTYLE_PLAIN, &col, false, 0);
509 const double SCROLL_PX_SEC = 200.0;
511 void WaypointList::doDragScroll()
513 double dt = (SGTimeStamp::now() - _dragScrollTime).toSecs();
514 _dragScrollTime.stamp();
515 int deltaPx = (int)(dt * SCROLL_PX_SEC);
517 if (_dragScroll == SCROLL_UP) {
518 _scrollPx = _scrollPx - deltaPx;
519 SG_CLAMP_RANGE(_scrollPx, 0, scrollRangePx());
520 _dragTargetRow = firstVisibleRow();
522 _scrollPx = _scrollPx + deltaPx;
523 SG_CLAMP_RANGE(_scrollPx, 0, scrollRangePx());
524 _dragTargetRow = lastFullyVisibleRow() + 1;
527 if (_scrollCallback) {
528 (*_scrollCallback)();
532 int WaypointList::getSelected()
534 return getIntegerValue();
537 void WaypointList::setSelected(int rowIndex)
539 if (rowIndex == getSelected()) {
545 if (rowIndex == -1) {
549 ensureRowVisible(rowIndex);
552 void WaypointList::ensureRowVisible(int rowIndex)
554 if ((rowIndex >= firstFullyVisibleRow()) && (rowIndex <= lastFullyVisibleRow())) {
555 return; // already visible, fine
558 // ideal position would place the desired row in the middle of the
559 // visible section - hence subtract half the visible height.
560 int targetScrollPx = (rowIndex * rowHeightPx()) - (_heightPx / 2);
562 // clamp the scroll value to something valid
563 SG_CLAMP_RANGE(targetScrollPx, 0, scrollRangePx());
564 _scrollPx = targetScrollPx;
567 if (_scrollCallback) { // keep scroll observers in sync
568 (*_scrollCallback)();
572 unsigned int WaypointList::numWaypoints() const
578 return _model->numWaypoints();
581 bool WaypointList::wantsVScroll() const
583 return totalHeightPx() > _heightPx;
586 float WaypointList::getVScrollPercent() const
588 float scrollRange = scrollRangePx();
589 if (scrollRange < 1.0f) {
593 return _scrollPx / scrollRange;
596 float WaypointList::getVScrollThumbPercent() const
598 return _heightPx / (float) totalHeightPx();
601 void WaypointList::setVScrollPercent(float perc)
603 float scrollRange = scrollRangePx();
604 _scrollPx = (int)(scrollRange * perc);
607 int WaypointList::firstVisibleRow() const
609 return _scrollPx / rowHeightPx();
612 int WaypointList::firstFullyVisibleRow() const
614 int rh = rowHeightPx();
615 return (_scrollPx + rh - 1) / rh;
618 int WaypointList::numVisibleRows() const
620 int rh = rowHeightPx();
621 int topOffset = _scrollPx % rh; // pixels of first visible row
622 return (_heightPx - topOffset + rh - 1) / rh;
626 int WaypointList::numFullyVisibleRows() const
628 int rh = rowHeightPx();
629 int topOffset = _scrollPx % rh; // pixels of first visible row
630 return (_heightPx - topOffset) / rh;
633 int WaypointList::rowHeightPx() const
635 return legendFont.getStringHeight() + PUSTR_BGAP;
638 int WaypointList::scrollRangePx() const
640 return std::max(0, totalHeightPx() - _heightPx);
643 int WaypointList::totalHeightPx() const
649 return (int) _model->numWaypoints() * rowHeightPx();
652 int WaypointList::lastFullyVisibleRow() const
654 int row = firstFullyVisibleRow() + numFullyVisibleRows();
655 return std::min(row, (int) _model->numWaypoints() - 1);
658 int WaypointList::lastVisibleRow() const
660 int row = firstVisibleRow() + numVisibleRows();
661 return std::min(row, (int) _model->numWaypoints() - 1);
664 void WaypointList::setModel(Model* model)
671 _model->setUpdateCallback(make_callback(this, &WaypointList::modelUpdateCallback));
676 int WaypointList::checkKey (int key, int updown )
678 if ((updown == PU_UP) || !isVisible () || !isActive () || (window != puGetWindow())) {
682 #ifdef AVOID_FLIGHT_KEYS
693 setSelected(_model->numWaypoints() - 1);
697 case PU_KEY_PAGE_UP :
698 if (getSelected() >= 0) {
699 setSelected(getSelected() - 1);
704 case PU_KEY_PAGE_DOWN : {
705 int newSel = getSelected() + 1;
706 if (newSel >= (int) _model->numWaypoints()) {
715 if (getSelected() >= 0) {
716 Waypt* wp = _model->waypointAt(getSelected());
717 if (wp->flag(WPT_GENERATED)) {
721 if (wp->altitudeRestriction() != RESTRICT_NONE) {
722 int curAlt = (static_cast<int>(wp->altitudeFt()) + 50) / 100;
724 wp->setAltitude(0, RESTRICT_NONE);
726 wp->setAltitude((curAlt - 10) * 100, wp->altitudeRestriction());
733 if (getSelected() >= 0) {
734 flightgear::Waypt* wp = _model->waypointAt(getSelected());
735 if (wp->flag(WPT_GENERATED)) {
739 if (wp->altitudeRestriction() == RESTRICT_NONE) {
740 wp->setAltitude(1000, RESTRICT_AT);
742 int curAlt = (static_cast<int>(wp->altitudeFt()) + 50) / 100;
743 wp->setAltitude((curAlt + 10) * 100, wp->altitudeRestriction());
749 if (getSelected() >= 0) {
750 int index = getSelected();
751 Waypt* wp = _model->waypointAt(getSelected());
752 if (wp->flag(WPT_GENERATED)) {
756 _model->deleteAt(index);
757 setSelected(index - 1);
768 void WaypointList::modelUpdateCallback()
772 if (_updateCallback) {
773 (*_updateCallback)();
777 //////////////////////////////////////////////////////////////////////////////
780 static void handle_scrollbar(puObject* scrollbar)
782 ScrolledWaypointList* self = (ScrolledWaypointList*)scrollbar->getUserData();
783 self->setScrollPercent(scrollbar->getFloatValue());
786 static void waypointListCb(puObject* wpl)
788 ScrolledWaypointList* self = (ScrolledWaypointList*)wpl->getUserData();
789 self->setValue(wpl->getIntegerValue());
790 self->invokeCallback();
793 ScrolledWaypointList::ScrolledWaypointList(int x, int y, int width, int height) :
797 // ensure our type is compound, so fgPopup::applySize doesn't descend into
798 // us, and try to cast our children's user-data to GUIInfo*.
799 type |= PUCLASS_LIST;
804 void ScrolledWaypointList::setValue(float v)
806 puGroup::setValue(v);
810 void ScrolledWaypointList::setValue(int v)
812 puGroup::setValue(v);
816 void ScrolledWaypointList::init(int w, int h)
818 _list = new WaypointList(0, 0, w, h);
819 _list->setUpdateCallback(make_callback(this, &ScrolledWaypointList::modelUpdated));
820 _hasVScroll = _list->wantsVScroll();
821 _list->setUserData(this);
822 _list->setCallback(waypointListCb);
824 _list->setScrollCallback(make_callback(this, &ScrolledWaypointList::updateScroll));
826 _scrollbar = new puaScrollBar(w - _scrollWidth, 0, h,
827 1 /*arrow*/, 1 /* vertical */, _scrollWidth);
828 _scrollbar->setMinValue(0.0);
829 _scrollbar->setMaxValue(1.0);
830 _scrollbar->setUserData(this);
831 _scrollbar->setCallback(handle_scrollbar);
832 close(); // close the group
837 void ScrolledWaypointList::modelUpdated()
841 updateWantsScroll(w, h);
844 void ScrolledWaypointList::setScrollPercent(float v)
846 // slider's min is the bottom, so invert the value
847 _list->setVScrollPercent(1.0f - v);
850 void ScrolledWaypointList::setSize(int w, int h)
852 updateWantsScroll(w, h);
853 puGroup::setSize(w, h);
856 void ScrolledWaypointList::updateWantsScroll(int w, int h)
858 _hasVScroll = _list->wantsVScroll();
861 _scrollbar->reveal();
862 _scrollbar->setPosition(w - _scrollWidth, 0);
863 _scrollbar->setSize(_scrollWidth, h);
864 _list->setSize(w - _scrollWidth, h);
868 _list->setSize(w, h);
872 void ScrolledWaypointList::updateScroll()
874 // _scrollbar->setMaxValue(_list->numWaypoints());
875 _scrollbar->setValue(1.0f - _list->getVScrollPercent());
876 _scrollbar->setSliderFraction(_list->getVScrollThumbPercent());