7 #include "WaypointList.hxx"
10 #include <boost/tuple/tuple.hpp>
12 #include <plib/puAux.h>
14 #include <simgear/structure/callback.hxx>
15 #include <simgear/sg_inlines.h>
17 #include <Main/globals.hxx>
18 #include <Main/fg_props.hxx>
20 #include <Navaids/positioned.hxx>
21 #include <Autopilot/route_mgr.hxx>
23 // select if the widget grabs keys necessary to fly aircraft from the keyboard,
24 // or not. See http://code.google.com/p/flightgear-bugs/issues/detail?id=338
25 // for discussion about why / what is going on.
26 #define AVOID_FLIGHT_KEYS 1
28 using namespace flightgear;
36 static const double BLINK_TIME = 0.3;
37 static const int DRAG_START_DISTANCE_PX = 5;
39 class FlightPlanWaypointModel :
40 public WaypointList::Model,
41 public SGPropertyChangeListener
44 FlightPlanWaypointModel(flightgear::FlightPlan* fp) :
47 SGPropertyNode* routeEdited = fgGetNode("/autopilot/route-manager/signals/edited", true);
48 SGPropertyNode* flightplanChanged = fgGetNode("/autopilot/route-manager/signals/flightplan-changed", true);
49 routeEdited->addChangeListener(this);
50 flightplanChanged->addChangeListener(this);
53 ~FlightPlanWaypointModel()
55 SGPropertyNode* routeEdited = fgGetNode("/autopilot/route-manager/signals/edited", true);
56 SGPropertyNode* flightplanChanged = fgGetNode("/autopilot/route-manager/signals/flightplan-changed", true);
57 routeEdited->removeChangeListener(this);
58 flightplanChanged->removeChangeListener(this);
61 // implement WaypointList::Model
62 virtual unsigned int numWaypoints() const
64 return _fp->numLegs();
67 virtual int currentWaypoint() const
69 return _fp->currentIndex();
72 virtual flightgear::Waypt* waypointAt(unsigned int index) const
74 if (index >= numWaypoints()) {
78 return _fp->legAtIndex(index)->waypoint();
81 virtual void deleteAt(unsigned int index)
83 _fp->deleteIndex(index);
86 virtual void moveWaypointToIndex(unsigned int srcIndex, unsigned int destIndex)
88 SG_LOG(SG_GENERAL, SG_INFO, "moveWaypoint: from " << srcIndex << " to " << destIndex);
89 if (destIndex > srcIndex) {
93 unsigned int currentWpIndex = currentWaypoint();
94 WayptRef w(waypointAt(currentWpIndex));
95 _fp->deleteIndex(currentWpIndex);
97 SG_LOG(SG_GENERAL, SG_INFO, "wpt:" << w->ident());
98 _fp->insertWayptAtIndex(w, destIndex);
100 if (srcIndex == currentWpIndex) {
101 // current waypoint was moved
102 _fp->setCurrentIndex(destIndex);
106 virtual void setUpdateCallback(SGCallback* cb)
111 // implement SGPropertyChangeListener
112 void valueChanged(SGPropertyNode *prop)
114 if (prop->getNameString() == "edited") {
120 if (prop->getNameString() == "flightplan-changed") {
122 static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"))->flightPlan();
126 flightgear::FlightPlan* _fp;
130 //////////////////////////////////////////////////////////////////////////////
132 static void drawClippedString(puFont& font, const char* s, int x, int y, int maxWidth)
134 int fullWidth = font.getStringWidth(s);
135 if (fullWidth <= maxWidth) { // common case, easy and efficent
136 font.drawString(s, x, y);
141 int len = buf.size();
144 fullWidth = font.getStringWidth(buf.c_str());
145 } while (fullWidth > maxWidth);
147 font.drawString(buf.c_str(), x, y);
150 //////////////////////////////////////////////////////////////////////////////
152 WaypointList::WaypointList(int x, int y, int width, int height) :
153 puFrame(x, y, width, height),
154 GUI_ID(FGCLASS_WAYPOINTLIST),
157 _dragScroll(SCROLL_NO),
160 _updateCallback(NULL),
161 _scrollCallback(NULL),
164 // pretend to be a list, so fgPopup doesn't mess with our mouse events
165 type |= PUCLASS_LIST;
166 flightgear::FlightPlan* fp =
167 static_cast<FGRouteMgr*>(globals->get_subsystem("route-manager"))->flightPlan();
168 setModel(new FlightPlanWaypointModel(fp));
169 setSize(width, height);
175 WaypointList::~WaypointList()
178 delete _updateCallback;
179 delete _scrollCallback;
182 void WaypointList::setUpdateCallback(SGCallback* cb)
184 _updateCallback = cb;
187 void WaypointList::setScrollCallback(SGCallback* cb)
189 _scrollCallback = cb;
192 void WaypointList::setSize(int width, int height)
194 double scrollP = getVScrollPercent();
196 puFrame::setSize(width, height);
198 if (wantsVScroll()) {
199 setVScrollPercent(scrollP);
205 int WaypointList::checkHit ( int button, int updown, int x, int y )
207 if ( isHit( x, y ) || ( puActiveWidget () == this ) )
209 doHit ( button, updown, x, y ) ;
217 void WaypointList::doHit( int button, int updown, int x, int y )
219 puFrame::doHit(button, updown, x, y);
220 if (updown == PU_DRAG) {
225 if (button != active_mouse_button) {
229 if (updown == PU_UP) {
230 puDeactivateWidget();
235 } else if (updown == PU_DOWN) {
236 puSetActiveWidget(this, x, y);
243 int row = rowForY(y - abox.min[1]);
244 if (row >= (int) _model->numWaypoints()) {
245 row = -1; // 'no selection'
248 if (row == getSelected()) {
249 _showLatLon = !_showLatLon;
257 void WaypointList::handleDrag(int x, int y)
260 // don't start drags immediately, require a certain mouse movement first
261 int manhattanLength = abs(x - _mouseDownX) + abs(y - _mouseDownY);
262 if (manhattanLength < DRAG_START_DISTANCE_PX) {
266 _dragSourceRow = rowForY(y - abox.min[1]);
267 Waypt* wp = _model->waypointAt(_dragSourceRow);
268 if (!wp || wp->flag(WPT_GENERATED)) {
269 return; // don't allow generated points to be dragged
273 _dragScroll = SCROLL_NO;
276 if (y < abox.min[1]) {
277 if (_dragScroll != SCROLL_DOWN) {
278 _dragScroll = SCROLL_DOWN;
279 _dragScrollTime.stamp();
281 } else if (y > abox.max[1]) {
282 if (_dragScroll != SCROLL_UP) {
283 _dragScroll = SCROLL_UP;
284 _dragScrollTime.stamp();
287 _dragScroll = SCROLL_NO;
288 _dragTargetRow = rowForY(y - abox.min[1] - (rowHeightPx() / 2));
292 void WaypointList::doDrop(int x, int y)
295 puDeactivateWidget();
297 SG_LOG(SG_GENERAL, SG_INFO, "doDrop");
299 if ((y < abox.min[1]) || (y >= abox.max[1])) {
300 SG_LOG(SG_GENERAL, SG_INFO, "y out of bounds:" << y);
304 if (_dragSourceRow == _dragTargetRow) {
305 SG_LOG(SG_GENERAL, SG_INFO, "source and target row match");
309 _model->moveWaypointToIndex(_dragSourceRow, _dragTargetRow);
311 // keep row indexes linged up when moving an item down the list
312 if (_dragSourceRow < _dragTargetRow) {
316 setSelected(_dragTargetRow);
319 void WaypointList::invokeDownCallback(void)
322 _dragScroll = SCROLL_NO;
323 SG_LOG(SG_GENERAL, SG_INFO, "cancel drag");
326 int WaypointList::rowForY(int y) const
332 // flip y to increase down, not up (as rows do)
333 int flipY = _heightPx - y;
334 int row = (flipY + _scrollPx) / rowHeightPx();
338 void WaypointList::draw( int dx, int dy )
340 puFrame::draw(dx, dy);
346 if (_dragScroll != SCROLL_NO) {
350 double dt = (SGTimeStamp::now() - _blinkTimer).toSecs();
351 if (dt > BLINK_TIME) {
356 glEnable(GL_SCISSOR_TEST);
357 GLint sx = (int) abox.min[0],
359 GLsizei w = (GLsizei) abox.max[0] - abox.min[0],
362 sx += border_thickness;
363 sy += border_thickness;
364 w -= 2 * border_thickness;
365 h -= 2 * border_thickness;
367 glScissor(sx + dx, sy + dy, w, h);
368 int row = firstVisibleRow(),
369 final = lastVisibleRow(),
370 rowHeight = rowHeightPx(),
373 y -= (_scrollPx % rowHeight); // partially draw the first row
375 _arrowWidth = legendFont.getStringWidth(">");
376 for ( ; row <= final; ++row, y += rowHeight) {
377 drawRow(dx, dy, row, y);
378 } // of row drawing iteration
380 glDisable(GL_SCISSOR_TEST);
383 // draw the insert marker after the rows
384 int insertY = (_dragTargetRow * rowHeight) - _scrollPx;
385 SG_CLAMP_RANGE(insertY, 0, std::min(_heightPx, totalHeightPx()));
387 glColor4f(1.0f, 0.5f, 0.0f, 0.8f);
390 glVertex2f(dx + abox.min[0], dy + abox.max[1] - insertY);
391 glVertex2f(dx + abox.max[0], dy + abox.max[1] - insertY);
396 void WaypointList::drawRow(int dx, int dy, int rowIndex, int y)
398 flightgear::Waypt* wp(_model->waypointAt(rowIndex));
400 bool isSelected = (rowIndex == getSelected());
401 bool isCurrent = (rowIndex == _model->currentWaypoint());
402 bool isDragSource = (_dragging && (rowIndex == _dragSourceRow));
405 bkgBox.min[1] = abox.max[1] - y;
406 bkgBox.max[1] = bkgBox.min[1] + rowHeightPx();
409 puFont* f = &legendFont;
410 bool drawBox = false;
412 if (wp->flag(WPT_MISS)) {
414 puSetColor(col, 1.0, 0.0, 0.0, 0.3); // red
415 } else if (wp->flag(WPT_ARRIVAL) || wp->flag(WPT_DEPARTURE)) {
417 puSetColor(col, 0.0, 0.0, 0.0, 0.3);
418 } else if (wp->flag(WPT_APPROACH)) {
420 puSetColor(col, 0.0, 0.0, 0.1, 0.3);
424 // draw later, on *top* of text string
425 } else if (isSelected) { // -PLAIN means selected, apparently
426 bkgBox.draw(dx, dy, -PUSTYLE_PLAIN, colour, false, 0);
427 } else if (drawBox) {
428 bkgBox.draw(dx, dy, PUSTYLE_PLAIN, &col, false, 0);
432 glColor4f (1.0, 0.5, 0.0, 1.0) ;
434 glColor4fv ( colour [ PUCOL_LEGEND ] ) ;
437 int xx = dx + abox.min[0] + PUSTR_LGAP;
438 int yy = dy + abox.max[1] - y ;
439 yy += 4; // center text in row height
442 f->drawString(">", xx, yy);
446 x += _arrowWidth + PUSTR_LGAP;
451 int count = ::snprintf(buffer, 128, "%03d %-5s", rowIndex, wp->ident().c_str());
453 FGPositioned* src = wp->source();
454 if (src && !src->name().empty() && (src->name() != wp->ident())) {
455 // append name if present, and different to id
456 ::snprintf(buffer + count, 128 - count, " (%s)", src->name().c_str());
459 drawClippedString(legendFont, buffer, x, yy, 300);
460 x += 300 + PUSTR_LGAP;
463 SGGeod p(wp->position());
464 char ns = (p.getLatitudeDeg() > 0.0) ? 'N' : 'S';
465 char ew = (p.getLongitudeDeg() > 0.0) ? 'E' : 'W';
467 ::snprintf(buffer, 128 - count, "%4.2f%c %4.2f%c",
468 fabs(p.getLongitudeDeg()), ew, fabs(p.getLatitudeDeg()), ns);
469 } else if (rowIndex > 0) {
472 Waypt* prev = _model->waypointAt(rowIndex - 1);
473 boost::tie(courseDeg, distanceM) = wp->courseAndDistanceFrom(prev->position());
475 ::snprintf(buffer, 128 - count, "%03.0f %5.1fnm",
476 courseDeg, distanceM * SG_METER_TO_NM);
479 f->drawString(buffer, x, yy);
480 x += 100 + PUSTR_LGAP;
482 if (wp->altitudeRestriction() != RESTRICT_NONE) {
483 int altHundredFt = (wp->altitudeFt() + 50) / 100; // round to nearest 100ft
484 if (altHundredFt < 100) {
485 count = ::snprintf(buffer, 128, "%d'", altHundredFt * 100);
486 } else { // display as a flight-level
487 count = ::snprintf(buffer, 128, "FL%d", altHundredFt);
490 f->drawString(buffer, x, yy);
491 } // of valid wp altitude
492 x += 60 + PUSTR_LGAP;
494 if (wp->speedRestriction() == SPEED_RESTRICT_MACH) {
495 count = ::snprintf(buffer, 126, "%03.2fM", wp->speedMach());
496 f->drawString(buffer, x, yy);
497 } else if (wp->speedRestriction() != RESTRICT_NONE) {
498 count = ::snprintf(buffer, 126, "%dKts", (int) wp->speedKts());
499 f->drawString(buffer, x, yy);
503 puSetColor(col, 1.0, 0.5, 0.0, 0.5);
504 bkgBox.draw(dx, dy, PUSTYLE_PLAIN, &col, false, 0);
508 const double SCROLL_PX_SEC = 200.0;
510 void WaypointList::doDragScroll()
512 double dt = (SGTimeStamp::now() - _dragScrollTime).toSecs();
513 _dragScrollTime.stamp();
514 int deltaPx = (int)(dt * SCROLL_PX_SEC);
516 if (_dragScroll == SCROLL_UP) {
517 _scrollPx = _scrollPx - deltaPx;
518 SG_CLAMP_RANGE(_scrollPx, 0, scrollRangePx());
519 _dragTargetRow = firstVisibleRow();
521 _scrollPx = _scrollPx + deltaPx;
522 SG_CLAMP_RANGE(_scrollPx, 0, scrollRangePx());
523 _dragTargetRow = lastFullyVisibleRow() + 1;
526 if (_scrollCallback) {
527 (*_scrollCallback)();
531 int WaypointList::getSelected()
533 return getIntegerValue();
536 void WaypointList::setSelected(int rowIndex)
538 if (rowIndex == getSelected()) {
544 if (rowIndex == -1) {
548 ensureRowVisible(rowIndex);
551 void WaypointList::ensureRowVisible(int rowIndex)
553 if ((rowIndex >= firstFullyVisibleRow()) && (rowIndex <= lastFullyVisibleRow())) {
554 return; // already visible, fine
557 // ideal position would place the desired row in the middle of the
558 // visible section - hence subtract half the visible height.
559 int targetScrollPx = (rowIndex * rowHeightPx()) - (_heightPx / 2);
561 // clamp the scroll value to something valid
562 SG_CLAMP_RANGE(targetScrollPx, 0, scrollRangePx());
563 _scrollPx = targetScrollPx;
566 if (_scrollCallback) { // keep scroll observers in sync
567 (*_scrollCallback)();
571 unsigned int WaypointList::numWaypoints() const
577 return _model->numWaypoints();
580 bool WaypointList::wantsVScroll() const
582 return totalHeightPx() > _heightPx;
585 float WaypointList::getVScrollPercent() const
587 float scrollRange = scrollRangePx();
588 if (scrollRange < 1.0f) {
592 return _scrollPx / scrollRange;
595 float WaypointList::getVScrollThumbPercent() const
597 return _heightPx / (float) totalHeightPx();
600 void WaypointList::setVScrollPercent(float perc)
602 float scrollRange = scrollRangePx();
603 _scrollPx = (int)(scrollRange * perc);
606 int WaypointList::firstVisibleRow() const
608 return _scrollPx / rowHeightPx();
611 int WaypointList::firstFullyVisibleRow() const
613 int rh = rowHeightPx();
614 return (_scrollPx + rh - 1) / rh;
617 int WaypointList::numVisibleRows() const
619 int rh = rowHeightPx();
620 int topOffset = _scrollPx % rh; // pixels of first visible row
621 return (_heightPx - topOffset + rh - 1) / rh;
625 int WaypointList::numFullyVisibleRows() const
627 int rh = rowHeightPx();
628 int topOffset = _scrollPx % rh; // pixels of first visible row
629 return (_heightPx - topOffset) / rh;
632 int WaypointList::rowHeightPx() const
634 return legendFont.getStringHeight() + PUSTR_BGAP;
637 int WaypointList::scrollRangePx() const
639 return std::max(0, totalHeightPx() - _heightPx);
642 int WaypointList::totalHeightPx() const
648 return (int) _model->numWaypoints() * rowHeightPx();
651 int WaypointList::lastFullyVisibleRow() const
653 int row = firstFullyVisibleRow() + numFullyVisibleRows();
654 return std::min(row, (int) _model->numWaypoints() - 1);
657 int WaypointList::lastVisibleRow() const
659 int row = firstVisibleRow() + numVisibleRows();
660 return std::min(row, (int) _model->numWaypoints() - 1);
663 void WaypointList::setModel(Model* model)
670 _model->setUpdateCallback(make_callback(this, &WaypointList::modelUpdateCallback));
675 int WaypointList::checkKey (int key, int updown )
677 if ((updown == PU_UP) || !isVisible () || !isActive () || (window != puGetWindow())) {
681 #ifdef AVOID_FLIGHT_KEYS
692 setSelected(_model->numWaypoints() - 1);
696 case PU_KEY_PAGE_UP :
697 if (getSelected() >= 0) {
698 setSelected(getSelected() - 1);
703 case PU_KEY_PAGE_DOWN : {
704 int newSel = getSelected() + 1;
705 if (newSel >= (int) _model->numWaypoints()) {
714 if (getSelected() >= 0) {
715 Waypt* wp = _model->waypointAt(getSelected());
716 if (wp->flag(WPT_GENERATED)) {
720 if (wp->altitudeRestriction() != RESTRICT_NONE) {
721 int curAlt = (static_cast<int>(wp->altitudeFt()) + 50) / 100;
723 wp->setAltitude(0, RESTRICT_NONE);
725 wp->setAltitude((curAlt - 10) * 100, wp->altitudeRestriction());
732 if (getSelected() >= 0) {
733 flightgear::Waypt* wp = _model->waypointAt(getSelected());
734 if (wp->flag(WPT_GENERATED)) {
738 if (wp->altitudeRestriction() == RESTRICT_NONE) {
739 wp->setAltitude(1000, RESTRICT_AT);
741 int curAlt = (static_cast<int>(wp->altitudeFt()) + 50) / 100;
742 wp->setAltitude((curAlt + 10) * 100, wp->altitudeRestriction());
748 if (getSelected() >= 0) {
749 int index = getSelected();
750 Waypt* wp = _model->waypointAt(getSelected());
751 if (wp->flag(WPT_GENERATED)) {
755 _model->deleteAt(index);
756 setSelected(index - 1);
767 void WaypointList::modelUpdateCallback()
771 if (_updateCallback) {
772 (*_updateCallback)();
776 //////////////////////////////////////////////////////////////////////////////
779 static void handle_scrollbar(puObject* scrollbar)
781 ScrolledWaypointList* self = (ScrolledWaypointList*)scrollbar->getUserData();
782 self->setScrollPercent(scrollbar->getFloatValue());
785 static void waypointListCb(puObject* wpl)
787 ScrolledWaypointList* self = (ScrolledWaypointList*)wpl->getUserData();
788 self->setValue(wpl->getIntegerValue());
789 self->invokeCallback();
792 ScrolledWaypointList::ScrolledWaypointList(int x, int y, int width, int height) :
796 // ensure our type is compound, so fgPopup::applySize doesn't descend into
797 // us, and try to cast our children's user-data to GUIInfo*.
798 type |= PUCLASS_LIST;
803 void ScrolledWaypointList::setValue(float v)
805 puGroup::setValue(v);
809 void ScrolledWaypointList::setValue(int v)
811 puGroup::setValue(v);
815 void ScrolledWaypointList::init(int w, int h)
817 _list = new WaypointList(0, 0, w, h);
818 _list->setUpdateCallback(make_callback(this, &ScrolledWaypointList::modelUpdated));
819 _hasVScroll = _list->wantsVScroll();
820 _list->setUserData(this);
821 _list->setCallback(waypointListCb);
823 _list->setScrollCallback(make_callback(this, &ScrolledWaypointList::updateScroll));
825 _scrollbar = new puaScrollBar(w - _scrollWidth, 0, h,
826 1 /*arrow*/, 1 /* vertical */, _scrollWidth);
827 _scrollbar->setMinValue(0.0);
828 _scrollbar->setMaxValue(1.0);
829 _scrollbar->setUserData(this);
830 _scrollbar->setCallback(handle_scrollbar);
831 close(); // close the group
836 void ScrolledWaypointList::modelUpdated()
840 updateWantsScroll(w, h);
843 void ScrolledWaypointList::setScrollPercent(float v)
845 // slider's min is the bottom, so invert the value
846 _list->setVScrollPercent(1.0f - v);
849 void ScrolledWaypointList::setSize(int w, int h)
851 updateWantsScroll(w, h);
852 puGroup::setSize(w, h);
855 void ScrolledWaypointList::updateWantsScroll(int w, int h)
857 _hasVScroll = _list->wantsVScroll();
860 _scrollbar->reveal();
861 _scrollbar->setPosition(w - _scrollWidth, 0);
862 _scrollbar->setSize(_scrollWidth, h);
863 _list->setSize(w - _scrollWidth, h);
867 _list->setSize(w, h);
871 void ScrolledWaypointList::updateScroll()
873 // _scrollbar->setMaxValue(_list->numWaypoints());
874 _scrollbar->setValue(1.0f - _list->getVScrollPercent());
875 _scrollbar->setSliderFraction(_list->getVScrollThumbPercent());