Skip to content

7GUIs Flight Booker#

Example's page

This page describes an example listed in 7guis category.

Flight Booker.

Challenge: Constraints.

The task is to build a frame containing a combobox C with the two options “one-way flight” and “return flight”, two textfields T1 and T2 representing the start and return date, respectively, and a button B for submitting the selected flight. T2 is enabled iff C’s value is “return flight”. When C has the value “return flight” and T2’s date is strictly before T1’s then B is disabled. When a non-disabled textfield T has an ill-formatted date then T is colored red and B is disabled. When clicking B a message is displayed informing the user of his selection (e.g. “You have booked a one-way flight on 04.04.2014.”). Initially, C has the value “one-way flight” and T1 as well as T2 have the same (arbitrary) date (it is implied that T2 is disabled).

The focus of Flight Booker lies on modelling constraints between widgets on the one hand and modelling constraints within a widget on the other hand. Such constraints are very common in everyday interactions with GUI applications. A good solution for Flight Booker will make the constraints clear, succinct and explicit in the source code and not hidden behind a lot of scaffolding.

Regex Library#

For validation in this example, we've chosen using regex technology, as it's fairly simple and extensible way to make parsers.

Despite STL provides regex implementation, it varies from compiler to compiler, compiles the regex expression at runtime only, and some platforms may even lack builtin regex library. To avoid possible issues, custom implementation should be used.

Although AUI does not provide a regex parser on its own, nothing stops you from using AUI.Boot in order to pull awesome 3rdparty implementation of your choice that suits your exact needs. For this example, we've chosen ctre, as it evaluates the regex expression at compile-time, emitting effective code, as if we were validating the string manually.

Source Code#

Repository

CMakeLists.txt#

1
2
3
4
5
auib_import(ctre https://github.com/hanickadot/compile-time-regular-expressions
            VERSION v3.9.0)

aui_executable(aui.example.flight_booker)
aui_link(aui.example.flight_booker PRIVATE aui::views ctre::ctre)

src/main.cpp#

#include <ctre.hpp>
#include <AUI/Platform/Entry.h>
#include <AUI/Platform/AWindow.h>
#include <AUI/Util/UIBuildingHelpers.h>
#include "AUI/View/ADropdownList.h"
#include "AUI/Model/AListModel.h"
#include "AUI/View/ATextField.h"
#include "AUI/Platform/AMessageBox.h"

using namespace declarative;
using namespace std::chrono;

constexpr auto REGEX_DATE = ctre::match<"([0-9]+)\\.([0-9]+)\\.([0-9]{4})">;

struct DateTextFieldState {
    AProperty<AOptional<system_clock::time_point>> parsed;
};

auto formatDate(system_clock::time_point date) { return "{0:%d}.{0:%m}.{0:%G}"_format(date); }

auto dateTextField(DateTextFieldState& state) {
    return _new<ATextField>() AUI_LET {
        AObject::biConnect(
            state.parsed.biProjected(aui::lambda_overloaded {
              [](const AOptional<system_clock::time_point>& v) -> AString {
                  if (!v) {
                      return "";
                  }
                  return formatDate(*v);
              },
              [](const AString& s) -> AOptional<system_clock::time_point> {
                  auto std = s.toStdString();
                  auto match = REGEX_DATE.match(std);
                  if (!match) {
                      return std::nullopt;
                  }
                  year_month_day ymd(
                      year(std::stoi(match.get<3>().str())), month(std::stoi(match.get<2>().str())),
                      day(std::stoi(match.get<1>().str())));
                  if (!ymd.ok()) {
                      return std::nullopt;
                  }
                  return sys_days(ymd);
              },
            }),
            it->text());
        it & state.parsed > [](AView& textField, const AOptional<system_clock::time_point>& value) {
            textField.setAssName(".red", !value.hasValue());
        };
    };
}

class FlightBookerWindow : public AWindow {
public:
    FlightBookerWindow() : AWindow("AUI - 7GUIs - Book Flight", 150_dp, 50_dp) {
        setExtraStylesheet(AStylesheet { {
          ass::c(".red"),
          ass::BackgroundSolid { AColor::RED },
        } });
        setContents(Centered {
          Vertical {
            _new<ADropdownList>(AListModel<AString>::make({ "one-way flight", "return flight" })) AUI_LET {
                    connect(it->selectionId().readProjected([](int selectionId) { return selectionId == 1; }),
                            mIsReturnFlight);
                },
            dateTextField(mDepartureDate),
            dateTextField(mReturnDate) AUI_LET { connect(mIsReturnFlight, AUI_SLOT(it)::setEnabled); },
            _new<AButton>("Book") AUI_LET {
                    connect(it->clicked, me::book);
                    connect(mIsValid, AUI_SLOT(it)::setEnabled);
                },
          },
        });
    }

private:
    DateTextFieldState mDepartureDate { system_clock::now() }, mReturnDate { system_clock::now() };
    AProperty<bool> mIsReturnFlight;
    APropertyPrecomputed<bool> mIsValid = [&] {
        if (!mDepartureDate.parsed->hasValue()) {
            return false;
        }
        if (!mIsReturnFlight) {
            return true;
        }
        if (!mReturnDate.parsed->hasValue()) {
            return false;
        }
        if (mDepartureDate.parsed->value() > mReturnDate.parsed->value()) {
            return false;
        }
        return true;
    };

    void book() {
        AString msg = "Departure - {}"_format(formatDate(mDepartureDate.parsed->value()));
        if (mIsReturnFlight) {
            msg += "\nReturn - {}"_format(formatDate(mReturnDate.parsed->value()));
        }
        AMessageBox::show(this, "You've booked the flight", msg);
    }
};

AUI_ENTRY {
    _new<FlightBookerWindow>()->show();
    return 0;
}