Files

1201 lines
42 KiB
C++

/**
* @file include/ActivMiddleware/ActivFramework/UiIo.h
*
* @brief Header file for the ui io class.
*/
#if (!defined ACTIV_FRAMEWORK_UI_IO_H)
#define ACTIV_FRAMEWORK_UI_IO_H
#include "ActivMiddleware/ActivFramework/External.h"
#include "ActivMiddleware/ActivBase/ConsoleWindow.h"
#include "ActivMiddleware/ActivBase/StatusCodeException.h"
#include "ActivMiddleware/CxxYZ/string_view.h"
#include "ActivMiddleware/CxxYZ/functional.h"
#include ACTIV_BOOST_INCLUDE(range/algorithm/for_each.hpp)
#include ACTIV_BOOST_INCLUDE(scoped_array.hpp)
#include ACTIV_BOOST_INCLUDE(scoped_ptr.hpp)
#include <map>
#include <vector>
#include <iostream>
#include <cstdarg>
//! Activ namespace.
namespace Activ
{
class Address;
class IpAddress;
class UiUser;
class UiMenu;
class UiComponentMap;
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Ui io class. Provides methods to get input from and post input to a user.
*/
class UiIo : private Boost::noncopyable
{
public:
typedef std::map<String, String> CompletionList;
typedef std::vector<CompletionList::const_iterator> CompletionIteratorList;
class StaticCompletionHelper;
class DeferredStaticCompletionHelper;
class DynamicCompletionHelper;
/**
* @brief Base class to handle tab-completion in the ui.
*
* You probably won't need to use this class directly - instead see StaticCompletionHelper and DynamicCompletionHelper.
* Tab-completion is available via a UiIo::GetString() overload.
*/
class CompletionHelper
{
public:
/**
* @brief Constructor.
*
* @param isCaseSensitive whether to do case-sensitive tab-completion.
*/
ACTIV_FRAMEWORK_API CompletionHelper(const bool isCaseSensitive);
/**
* @brief Destructor.
*/
ACTIV_FRAMEWORK_API virtual ~CompletionHelper();
/**
* @brief Add a string to the list of possible completions.
*
* @param completion the string to add.
*/
ACTIV_FRAMEWORK_API void AddCompletion(const String &completion);
/**
* @brief Add a list of strings to the list of possible completions.
*
* @param begin iterator to the first string in a range of possible completions.
* @param end iterator to beyond the last string in a range of possible completions.
*/
template<typename T>
void AddCompletions(const T &begin, const T &end);
/**
* @brief Add a list of strings to the list of possible completions.
*
* @param stringRange Boost range of iterators to the strings in a range of possible completions.
*/
template<typename T>
void AddCompletions(const T &stringRange);
private:
/**
* @brief Populate the list of possible completions.
*
* @param partialInput current partial input the user has entered, that can optionally be used
* to intelligently populate the list of possible completion strings.
*/
virtual void PopulateCompletionList(const String &partialInput) = 0;
const bool m_isCaseSensitive; ///< Whether to do case-sensitive completions.
CompletionList m_completionList; ///< List of completions.
friend class UiIo;
friend class StaticCompletionHelper;
friend class DeferredStaticCompletionHelper;
friend class DynamicCompletionHelper;
};
/**
* @brief Class to handle tab-completion with a fixed list of strings.
*/
class StaticCompletionHelper : public CompletionHelper
{
public:
/**
* @brief Default constructor.
*
* The completion helper will be initialized without any completion strings.
* You must call AddCompletion() or AddCompletions() to populate the object before using it.
*
* @param isCaseSensitive whether to do case-sensitive tab-completion.
*/
StaticCompletionHelper(const bool isCaseSensitive);
/**
* @brief Constructor.
*
* @param begin iterator to the first string in a range of all possible completions.
* @param end iterator to beyond the last string in a range of all possible completions.
* @param isCaseSensitive whether to do case-sensitive tab-completion.
*/
template<typename T>
StaticCompletionHelper(const T &begin, const T &end, const bool isCaseSensitive);
/**
* @brief Constructor.
*
* @param stringRange Boost range of iterators to the strings in a range of possible completions.
* @param isCaseSensitive whether to do case-sensitive tab-completion.
*/
template<typename T>
StaticCompletionHelper(const T &stringRange, const bool isCaseSensitive);
private:
ACTIV_FRAMEWORK_API virtual void PopulateCompletionList(const String &partialInput) ACTIV_OVERRIDE;
};
/**
* @brief Class to handle tab-completion with a fixed list of strings. Initializing the list is deferred until tab is hit.
*/
class DeferredStaticCompletionHelper : public CompletionHelper
{
public:
/**
* @brief Constructor. Invokes the OnPopulateCompletionList() virtual function when tab is hit.
*
* @param isCaseSensitive whether to do case-sensitive tab-completion.
*/
ACTIV_FRAMEWORK_API DeferredStaticCompletionHelper(const bool isCaseSensitive);
/**
* @brief Constructor. Invokes the provided function when tab is hit.
*
* @param populateCompletionList function to invoke when tab is hit; see PopulateCompletionListFn typedef.
* @param isCaseSensitive whether to do case-sensitive tab-completion.
*/
template<typename T>
DeferredStaticCompletionHelper(const T &populateCompletionList, const bool isCaseSensitive);
protected:
/**
* @brief Callback to populate list of possible completions. This callback is invoked the first time the user hits tab.
*
* Override this to set the possible completions (via AddCompletion() or AddCompletions()) when the user hits tab.
*/
ACTIV_FRAMEWORK_API virtual void OnPopulateCompletionList();
private:
typedef CxxYZ::function<void (DeferredStaticCompletionHelper &completionHelper)> PopulateCompletionListFn;
ACTIV_FRAMEWORK_API virtual void PopulateCompletionList(const String &partialInput) ACTIV_OVERRIDE;
const PopulateCompletionListFn m_populateCompletionList;
};
/**
* @brief Class to handle tab-completion with a dynamic list of strings that may be different each time tab is hit.
*/
class DynamicCompletionHelper : public CompletionHelper
{
public:
/**
* @brief Constructor.
*
* @param isCaseSensitive whether to do case-sensitive tab-completion.
*/
ACTIV_FRAMEWORK_API DynamicCompletionHelper(const bool isCaseSensitive);
/**
* @brief Constructor. Invokes the provided function when tab is hit.
*
* @param populateCompletionList function to invoke when tab is hit; see PopulateCompletionListFn typedef.
* @param isCaseSensitive whether to do case-sensitive tab-completion.
*/
template<typename T>
DynamicCompletionHelper(const T &populateCompletionList, const bool isCaseSensitive);
protected:
/**
* @brief Callback to populate list of possible completions from partial user input.
*
* Override this to set the possible completions (via AddCompletion() or AddCompletions()) when the user hits tab.
*
* @param partialInput the user's partial input at the moment tab was hit.
*/
ACTIV_FRAMEWORK_API virtual void OnPopulateCompletionList(const String &partialInput);
private:
typedef CxxYZ::function<void (DynamicCompletionHelper &completionHelper, const String &partialInput)>
PopulateCompletionListFn;
ACTIV_FRAMEWORK_API virtual void PopulateCompletionList(const String &partialInput) ACTIV_OVERRIDE;
const PopulateCompletionListFn m_populateCompletionList;
};
/**
* @brief Helper class to calculate the column sizes to display a number of items.
*/
class Columnizer
{
public:
/**
* @brief Constructor.
*
* m_columnWidth will be set to 0 if longestItemWidth is longer than the available display size.
*
* @param uiIo reference to a UiIo object for the current ui session.
* @param numberOfLeadingSpaces number blank spaces to put at the front of each line.
* @param numberOfItems the number of items that are to be displayed in columns.
* @param longestItemWidth the width of the longest item that will be displayed.
*/
ACTIV_FRAMEWORK_API Columnizer(const UiIo &uiIo, const size_t numberOfLeadingSpaces, const size_t numberOfItems,
const size_t longestItemWidth);
size_t m_columnSpacing; ///< number of spaces between columns
size_t m_numberOfColumns; ///< number of columns required
size_t m_numberOfLines; ///< number of lines required
};
/**
* @brief ANSI display attribute wrapper.
*/
class Attribute
{
public:
/**
* @brief Or operator.
*
* @param attribute reference to an Attribute to or with this object.
*
* @return Attribute object that is (*this | attribute).
*/
ACTIV_FRAMEWORK_API Attribute operator|(const Attribute &attribute) const;
/**
* @brief Or operator.
*
* @param attribute reference to an Attribute to or with this object.
*
* @return *this having been orred with @a attribute.
*/
ACTIV_FRAMEWORK_API Attribute &operator|(const Attribute &attribute);
/**
* @brief Cast to String operator.
*
* @return String containing the ANSI control sequence for the set of attributes represented by this object.
*/
ACTIV_FRAMEWORK_API operator String() const;
/**
* @brief Create ANSI control sequence.
*
* @return String containing the ANSI control sequence for the set of attributes represented by this object.
*/
ACTIV_FRAMEWORK_API String ToString() const;
private:
/**
* @brief Constructor.
*
* @param type ANSI display attribute type.
*/
Attribute(const uint32_t type);
String m_sequence;
friend class UiIo;
};
//! Helper to set an attribute whilst in scope.
class ScopedAttribute
{
public:
/**
* @brief Constructor.
*
* @param uiIo UiIo to set the attribute on.
* @param attribute
*/
ScopedAttribute(const UiIo &uiIo, const UiIo::Attribute &attribute);
/**
* @brief Destructor.
*
* UiIo::Normal is implicitly set on the UiIo.
*/
~ScopedAttribute();
private:
const UiIo &m_uiIo;
};
//! Reset menu exception. Can be thrown to drop out of current ui option back to the current menu. Prompt is redisplayed.
class UiResetMenuException
{
};
/**
* @brief Put a string.
*
* @param str the string to write.
*
* @retval STATUS_CODE_SUCCESS.
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode PutString(const String &str) const;
/**
* @brief Put a string.
*
* @param str the string to write.
*
* @retval STATUS_CODE_SUCCESS.
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode PutString(const CxxYZ::string_view &str) const;
/**
* @brief Put a string from a boost format object.
*
* @param formatter boost formatter object to create the string from.
*
* @retval STATUS_CODE_SUCCESS.
* @retval ...
*/
ACTIV_FRAMEWORK_API StatusCode PutString(const BoostFormat &formatter) const;
/**
* @brief Put a variable argument string.
*
* @param format printf style format string.
* @param ... variable arguments to write.
*
* @retval STATUS_CODE_SUCCESS.
* @retval ...
*/
ACTIV_PRINTF_FUNCTION(printf, 2, 3)
ACTIV_FRAMEWORK_API StatusCode PutString(const char * const format, ...) const;
/**
* @brief Put a variable argument string.
*
* @param format printf style format string.
* @param args variable arguments to write.
*
* @retval STATUS_CODE_SUCCESS.
* @retval ...
*/
ACTIV_PRINTF_FUNCTION(printf, 2, 0)
ACTIV_FRAMEWORK_API StatusCode PutStringV(const char * const format, std::va_list args) const;
/**
* @brief Put a range of strings.
*
* Will display in columns if possible given the size of the display.
*
* @param stringList the list of strings to display.
* @param numberOfLeadingSpaces number blank spaces to put at the front of each line.
*
* @retval STATUS_CODE_SUCCESS.
* @retval ...
*/
template<typename T>
StatusCode PutStringList(const T &stringRange, const size_t numberOfLeadingSpaces) const;
/**
* @brief Get a string.
*
* @param prompt the prompt to display. Pass empty string to display no prompt.
* @param str the string to read into, or the already initialized default.
* @param isInitializedWithDefault whether the string is initialized with a default.
* @param timeout how long to wait for input, in ms.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_FAILURE
* @retval STATUS_CODE_UNCHANGED
* @retval STATUS_CODE_TIMEOUT
*/
ACTIV_FRAMEWORK_API StatusCode GetString(const String &prompt, String &str,
const bool isInitializedWithDefault = false, const TimeoutPeriod timeout = ACTIV_WAIT_INFINITE) const;
/**
* @brief Get a string with tab-completion.
*
* @param prompt the prompt to display. Pass empty string to display no prompt.
* @param completionHelper reference to a CompletionHelper object to handle tab-completion.
* @param str the string to read into, or the already initialized default.
* @param isInitializedWithDefault whether the string is initialized with a default.
* @param timeout how long to wait for input, in ms.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_FAILURE
* @retval STATUS_CODE_UNCHANGED
* @retval STATUS_CODE_TIMEOUT
*/
ACTIV_FRAMEWORK_API StatusCode GetString(const String &prompt, CompletionHelper &completionHelper, String &str,
const bool isInitializedWithDefault = false, const TimeoutPeriod timeout = ACTIV_WAIT_INFINITE) const;
/**
* @brief Get a string within bounds.
*
* @param prompt the prompt to display. Pass empty string to display no prompt.
* @param lower the lower bound value.
* @param upper the upper bound value.
* @param str the string to read into, or the already initialized default.
* @param isInitializedWithDefault whether the string is initialized with a default.
* @param timeout how long to wait for input, in ms.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_FAILURE
* @retval STATUS_CODE_UNCHANGED
* @retval STATUS_CODE_TIMEOUT
*/
ACTIV_FRAMEWORK_API StatusCode GetString(const String &prompt, const byte_t lower, const byte_t upper, String &str,
const bool isInitializedWithDefault = false, const TimeoutPeriod timeout = ACTIV_WAIT_INFINITE) const;
/**
* @brief Get a character.
*
* @param prompt the prompt to display. Pass empty string to display no prompt.
* @param ch the character to read into, or the already initialized default.
* @param isInitializedWithDefault whether the character is initialized with a default.
* @param timeout how long to wait for input, in ms.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_FAILURE
* @retval STATUS_CODE_UNCHANGED
* @retval STATUS_CODE_TIMEOUT
*/
ACTIV_FRAMEWORK_API StatusCode GetChar(const String &prompt, char &ch, const bool isInitializedWithDefault = false,
const TimeoutPeriod timeout = ACTIV_WAIT_INFINITE) const;
/**
* @brief Get a character and validate that it is present in the valid character string.
*
* @param prompt the prompt to display. Pass empty string to display no prompt.
* @param validChars a string containing the valid characters.
* @param ch the character to read into, or the already initialized default.
* @param isInitializedWithDefault whether the character is initialized with a default.
* @param timeout how long to wait for input, in ms.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_FAILURE
* @retval STATUS_CODE_UNCHANGED
* @retval STATUS_CODE_TIMEOUT
*/
ACTIV_FRAMEWORK_API StatusCode GetChar(const String &prompt, const String &validChars, char &ch,
const bool isInitializedWithDefault = false, const TimeoutPeriod timeout = ACTIV_WAIT_INFINITE) const;
/**
* @brief Get a character and validate that it is present in the valid character string, case-insensitively.
*
* @param prompt the prompt to display. Pass empty string to display no prompt.
* @param validChars a string containing the valid characters.
* @param ch the character to read into, or the already initialized default.
* @param isInitializedWithDefault whether the character is initialized with a default.
* @param timeout how long to wait for input, in ms.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_FAILURE
* @retval STATUS_CODE_UNCHANGED
* @retval STATUS_CODE_TIMEOUT
*/
ACTIV_FRAMEWORK_API StatusCode GetCaseInsensitiveChar(const String &prompt, const String &validChars, char &ch,
const bool isInitializedWithDefault = false, const TimeoutPeriod timeout = ACTIV_WAIT_INFINITE) const;
/**
* @brief Get an unsigned integral of a given type.
*
* @param prompt the prompt to display. Pass empty string to display no prompt.
* @param value the value to read into, or the already initialized default.
* @param isInitializedWithDefault whether the value is initialized with a default.
* @param timeout how long to wait for input, in ms.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_FAILURE
* @retval STATUS_CODE_UNCHANGED
* @retval STATUS_CODE_TIMEOUT
*/
template<typename T>
ACTIV_TEMPLATE_API(ACTIV_FRAMEWORK_API) StatusCode GetUnsignedIntegral(const String &prompt, T &value,
const bool isInitializedWithDefault = false, const TimeoutPeriod timeout = ACTIV_WAIT_INFINITE) const;
/**
* @brief Get an unsigned integral of a given type within a range.
*
* @param prompt the prompt to display. Pass empty string to display no prompt.
* @param lower the lower bound value.
* @param upper the upper bound value.
* @param value the value to read into, or the already initialized default.
* @param isInitializedWithDefault whether the value is initialized with a default.
* @param timeout how long to wait for input, in ms.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_FAILURE
* @retval STATUS_CODE_UNCHANGED
* @retval STATUS_CODE_TIMEOUT
*/
template<typename T>
ACTIV_TEMPLATE_API(ACTIV_FRAMEWORK_API) StatusCode GetUnsignedIntegral(const String &prompt, const uint64_t lower,
const uint64_t upper, T &value, const bool isInitializedWithDefault = false,
const TimeoutPeriod timeout = ACTIV_WAIT_INFINITE) const;
/**
* @brief Get a signed integral of a given type.
*
* @param prompt the prompt to display. Pass empty string to display no prompt.
* @param value the value to read into, or the already initialized default.
* @param isInitializedWithDefault whether the value is initialized with a default.
* @param timeout how long to wait for input, in ms.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_FAILURE
* @retval STATUS_CODE_UNCHANGED
* @retval STATUS_CODE_TIMEOUT
*/
template<typename T>
ACTIV_TEMPLATE_API(ACTIV_FRAMEWORK_API) StatusCode GetSignedIntegral(const String &prompt, T &value,
const bool isInitializedWithDefault = false, const TimeoutPeriod timeout = ACTIV_WAIT_INFINITE) const;
/**
* @brief Get a signed integral of a given type within a range.
*
* @param prompt the prompt to display. Pass empty string to display no prompt.
* @param lower the lower bound value.
* @param upper the upper bound value.
* @param value the value to read into, or the already initialized default.
* @param isInitializedWithDefault whether the value is initialized with a default.
* @param timeout how long to wait for input, in ms.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_FAILURE
* @retval STATUS_CODE_UNCHANGED
* @retval STATUS_CODE_TIMEOUT
*/
template<typename T>
ACTIV_TEMPLATE_API(ACTIV_FRAMEWORK_API) StatusCode GetSignedIntegral(const String &prompt, const int64_t lower,
const int64_t upper, T &value, const bool isInitializedWithDefault = false,
const TimeoutPeriod timeout = ACTIV_WAIT_INFINITE) const;
/**
* @brief Get a field type of a given type.
*
* @param prompt the prompt to display. Pass empty string to display no prompt.
* @param value the value to read into, or the already initialized default.
* @param isInitializedWithDefault whether the value is initialized with a default.
* @param timeout how long to wait for input, in ms.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_FAILURE
* @retval STATUS_CODE_UNCHANGED
* @retval STATUS_CODE_TIMEOUT
*/
template<typename T>
ACTIV_TEMPLATE_API(ACTIV_FRAMEWORK_API) StatusCode GetFieldType(const String &prompt, T &value,
const bool isInitializedWithDefault = false, const TimeoutPeriod timeout = ACTIV_WAIT_INFINITE) const;
/**
* @brief Get a system address.
*
* @param prompt the prompt to display. Pass empty string to display no prompt.
* @param address the address to read into, or the already initialized default.
* @param isInitializedWithDefault whether the address is initialized with a default.
* @param timeout how long to wait for input, in ms.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_FAILURE
* @retval STATUS_CODE_UNCHANGED
* @retval STATUS_CODE_TIMEOUT
*/
ACTIV_FRAMEWORK_API StatusCode GetAddress(const String &prompt, Address &address,
const bool isInitializedWithDefault = false, const TimeoutPeriod timeout = ACTIV_WAIT_INFINITE) const;
/**
* @brief Get confirmation (Y/y or N/n) from user.
*
* @param prompt the prompt to display. Pass empty string to display default prompt.
* @param positiveDefault should the default be positive ('y') or negative ('n')?
* @param timeout how long to wait for input, in ms.
*
* @retval STATUS_CODE_SUCCESS user entered 'y', 'Y'
* @retval STATUS_CODE_FAILURE user entered 'n', 'N'
* @retval STATUS_CODE_TIMEOUT
*/
ACTIV_FRAMEWORK_API StatusCode GetConfirmation(const String &prompt, const bool positiveDefault = false,
const TimeoutPeriod timeout = ACTIV_WAIT_INFINITE) const;
/**
* @brief Get confirmation. The user needs to enter a random confirmation response.
*
* @param prompt the prompt to display. Pass empty string to display default prompt.
* @param timeout how long to wait for input, in ms.
*
* @retval STATUS_CODE_SUCCESS user confirmed
* @retval STATUS_CODE_FAILURE
* @retval STATUS_CODE_TIMEOUT
*/
ACTIV_FRAMEWORK_API StatusCode GetRandomConfirmation(const String &prompt,
const TimeoutPeriod timeout = ACTIV_WAIT_INFINITE) const;
/**
* @brief Toggle a boolean with y/n confirmation.
*
* @param prompt the prompt to display. Pass empty string to display default prompt.
* @param option reference to a boolean to be toggled.
* @param positiveDefault should the default be positive ('y') or negative ('n')?
* @param timeout how long to wait for input, in ms.
*
* @retval STATUS_CODE_SUCCESS user changed the value of \a option
* @retval STATUS_CODE_FAILURE user did not change the value of \a option
* @retval STATUS_CODE_TIMEOUT
*/
ACTIV_FRAMEWORK_API StatusCode EnableDisable(const String &prompt, bool &option, const bool positiveDefault = false,
const TimeoutPeriod timeout = ACTIV_WAIT_INFINITE) const;
/**
* @brief Toggle a boolean with random confirmation.
*
* @param prompt the prompt to display. Pass empty string to display default prompt.
* @param option reference to a boolean to be toggled.
* @param timeout how long to wait for input, in ms.
*
* @retval STATUS_CODE_SUCCESS user changed the value of \a option
* @retval STATUS_CODE_FAILURE user did not change the value of \a option
* @retval STATUS_CODE_TIMEOUT
*/
ACTIV_FRAMEWORK_API StatusCode EnableDisableRandomConfirmation(const String &prompt, bool &option,
const TimeoutPeriod timeout = ACTIV_WAIT_INFINITE) const;
/**
* @brief Get ip address.
*
* @param prompt the prompt to display. Pass empty string to display no prompt.
* @param ipAddress the address to read into, or the already initialized default.
* @param isInitializedWithDefault whether the address is initialized with a default.
* @param timeout how long to wait for input, in ms.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_FAILURE
* @retval STATUS_CODE_UNCHANGED
* @retval STATUS_CODE_TIMEOUT
*/
ACTIV_FRAMEWORK_API StatusCode GetIpAddress(const String &prompt, IpAddress &ipAddress,
const bool isInitializedWithDefault = false, const TimeoutPeriod timeout = ACTIV_WAIT_INFINITE) const;
/**
* @brief Get a filename from the user with tab-completion.
*
* Note although tab-completion support is provided, the user can still enter a filename that doesn't exist.
*
* @param prompt the prompt to display. Pass empty string to display no prompt.
* @param fileName the string to put the filename into, or the already initialized default.
* @param isInitializedWithDefault whether @a fileName is initialized with a default.
* @param timeout how long to wait for input, in ms.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_FAILURE
* @retval STATUS_CODE_UNCHANGED
* @retval STATUS_CODE_TIMEOUT
*/
ACTIV_FRAMEWORK_API StatusCode GetFileName(const String &prompt, String &fileName,
const bool isInitializedWithDefault = false, const TimeoutPeriod timeout = ACTIV_WAIT_INFINITE) const;
/**
* @brief Get a directory name from the user with tab-completion.
*
* Note although tab-completion support is provided, the user can still enter a directory name that doesn't exist.
*
* @param prompt the prompt to display. Pass empty string to display no prompt.
* @param directoryName the string to put the directory name into, or the already initialized default.
* @param isInitializedWithDefault whether @a directoryName is initialized with a default.
* @param timeout how long to wait for input, in ms.
*
* @retval STATUS_CODE_SUCCESS
* @retval STATUS_CODE_FAILURE
* @retval STATUS_CODE_UNCHANGED
* @retval STATUS_CODE_TIMEOUT
*/
ACTIV_FRAMEWORK_API StatusCode GetDirectoryName(const String &prompt, String &directoryName,
const bool isInitializedWithDefault = false, const TimeoutPeriod timeout = ACTIV_WAIT_INFINITE) const;
/**
* @brief Get the terminal window size.
*
* Note if either window size dimension is unknown, it will be set to 0.
*
* @param windowSize to receive the terminal window size (in characters).
*/
ACTIV_FRAMEWORK_API void GetWindowSize(ConsoleWindow::Coord &windowSize) const;
/**
* @brief Get address of UiUser.
*
* @return UiUser address.
*/
ACTIV_FRAMEWORK_API const Address &GetUiUserAddress() const;
//! Suspend the UI fiber for a number of milliseconds.
ACTIV_FRAMEWORK_API bool Suspend(const TimeoutPeriod timeout) const;
/**
* @brief Get storage area specific to this user and the current menu.
*
* T should be a default constructible type. The first call to GetMenuLocalStorage() for the current user and menu
* will new a T and return a reference to it. Successive calls for the same user and menu will return the same T reference.
*
* If a different type T is passed after an initial call to GetMenuLocalStorage(), a StatusCodeException is thrown.
*
* When the calling user exits the current menu (by way of moving up a menu level, ctrl-c, ctrl-z, or a ui operation
* throwing an exception), the menu-local T is destroyed.
*
* @return T reference local to this user and menu.
*
* @throw StatusCodeException if T does not match a previous call to GetMenuLocalStorage().
*/
template<typename T>
T &GetMenuLocalStorage() const;
ACTIV_FRAMEWORK_API static const Attribute Normal;
ACTIV_FRAMEWORK_API static const Attribute Bold;
ACTIV_FRAMEWORK_API static const Attribute Underscore;
ACTIV_FRAMEWORK_API static const Attribute Blink;
ACTIV_FRAMEWORK_API static const Attribute Reverse;
ACTIV_FRAMEWORK_API static const Attribute Concealed;
ACTIV_FRAMEWORK_API static const Attribute BlackFg;
ACTIV_FRAMEWORK_API static const Attribute RedFg;
ACTIV_FRAMEWORK_API static const Attribute GreenFg;
ACTIV_FRAMEWORK_API static const Attribute YellowFg;
ACTIV_FRAMEWORK_API static const Attribute BlueFg;
ACTIV_FRAMEWORK_API static const Attribute MagentaFg;
ACTIV_FRAMEWORK_API static const Attribute CyanFg;
ACTIV_FRAMEWORK_API static const Attribute WhiteFg;
ACTIV_FRAMEWORK_API static const Attribute BlackBg;
ACTIV_FRAMEWORK_API static const Attribute RedBg;
ACTIV_FRAMEWORK_API static const Attribute GreenBg;
ACTIV_FRAMEWORK_API static const Attribute YellowBg;
ACTIV_FRAMEWORK_API static const Attribute BlueBg;
ACTIV_FRAMEWORK_API static const Attribute MagentaBg;
ACTIV_FRAMEWORK_API static const Attribute CyanBg;
ACTIV_FRAMEWORK_API static const Attribute WhiteBg;
private:
/**
* @brief Constructor.
*
* @param uiMenu current menu.
* @param uiUser current user of \a uiMenu.
*/
UiIo(UiMenu &uiMenu, UiUser &uiUser);
/**
* @brief Display available completion choices.
*
* @param completionIteratorList list of iterators to CompletionList entries to display.
* @param maxCompletionLength the length of the longest string referenced in @a completionIteratorList.
* @param partialInput current partial input line.
*/
void DisplayCompletionChoices(const CompletionIteratorList &completionIteratorList, const size_t maxCompletionLength,
const String &partialInput) const;
/**
* @brief Display available completion choices in columns.
*
* @param completionIteratorList list of iterators to CompletionList entries to display.
* @param maxCompletionLength the length of the longest string referenced in @a completionIteratorList.
* @param columnizer
*/
void DisplayCompletionChoicesColumns(const CompletionIteratorList &completionIteratorList, const size_t maxCompletionLength,
const Columnizer &columnizer) const;
/**
* @brief Base for local storage.
*/
class IStorage
{
public:
virtual ~IStorage()
{
}
};
/**
* @brief User defined storage.
*
* T is a type provided by the user.
*/
template<typename T>
class Storage : public IStorage
{
public:
T m_value;
};
UiMenu & m_uiMenu; ///< Current menu.
UiUser & m_uiUser; ///< Current user.
mutable Boost::scoped_ptr<IStorage> m_pStorage; ///< User+menu local storage.
friend class UiMenu; ///< Allow UiMenu to construct UiIo objects.
friend class UiMainComponent; ///< Main component needs access to user.
friend class UiComponentMap;
friend class UiPaginator;
};
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T>
T &UiIo::GetMenuLocalStorage() const
{
Storage<T> *pStorage;
if (!m_pStorage)
{
pStorage = new Storage<T>;
m_pStorage.reset(pStorage);
}
else
{
pStorage = dynamic_cast<Storage<T> *>(m_pStorage.get());
if (0 == pStorage)
ACTIV_THROW(StatusCodeException, STATUS_CODE_INVALID_PARAMETER);
}
return pStorage->m_value;
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T>
void UiIo::CompletionHelper::AddCompletions(const T &begin, const T &end)
{
std::for_each(begin, end, CxxYZ::bind(&CompletionHelper::AddCompletion, this, CxxYZ::_1));
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T>
void UiIo::CompletionHelper::AddCompletions(const T &stringRange)
{
Boost::for_each(stringRange, CxxYZ::bind(&CompletionHelper::AddCompletion, this, CxxYZ::_1));
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
inline UiIo::StaticCompletionHelper::StaticCompletionHelper(const bool isCaseSensitive) :
CompletionHelper(isCaseSensitive)
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T>
UiIo::StaticCompletionHelper::StaticCompletionHelper(const T &begin, const T &end, const bool isCaseSensitive) :
CompletionHelper(isCaseSensitive)
{
AddCompletions(begin, end);
}
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T>
UiIo::StaticCompletionHelper::StaticCompletionHelper(const T &stringRange, const bool isCaseSensitive) :
CompletionHelper(isCaseSensitive)
{
AddCompletions(stringRange);
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T>
UiIo::DeferredStaticCompletionHelper::DeferredStaticCompletionHelper(const T &populateCompletionList, const bool isCaseSensitive) :
CompletionHelper(isCaseSensitive),
m_populateCompletionList(populateCompletionList)
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T>
UiIo::DynamicCompletionHelper::DynamicCompletionHelper(const T &populateCompletionList, const bool isCaseSensitive) :
CompletionHelper(isCaseSensitive),
m_populateCompletionList(populateCompletionList)
{
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
inline UiIo::ScopedAttribute::ScopedAttribute(const UiIo &uiIo, const UiIo::Attribute &attribute) :
m_uiIo(uiIo)
{
(void) m_uiIo.PutString(attribute.ToString());
}
// ---------------------------------------------------------------------------------------------------------------------------------
inline UiIo::ScopedAttribute::~ScopedAttribute()
{
(void) m_uiIo.PutString(UiIo::Normal.ToString());
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Paging helper for ui output.
*
* Example usage using default prompt after each page of output:
*
* UiPaginator uiPaginator(uiIo);
*
* for (size_t i = 0; i < 100; ++i)
* {
* uiIo.PutString(Fmt::Format("{}\n", i));
* }
*
* If the UiPaginator is not wrapped in a try-catch(UiPaginator::QuitException &), if the user says "no" at a next-page
* prompt, or the prompt times out, it is as if ctrl-z has been hit (drop out of current menu option without redisplaying menu).
* The user can check if the prompt has timed out by checking the m_hasTimedOut variable inside the exception.
*
* Additionally, the prompt used after each page can be overridden. This also demonstrates catching UiPaginator::QuitException to
* do something different than dropping out of the menu option entirely:
*
* class MyPager : public UiPaginator::Pager
* {
* public:
* virtual StatusCode Do(const UiIo &uiIo)
* {
* // Make sure to use a timeout on any prompt.
* switch (uiIo.GetString("Enter something or enter to continue", m_input, false, 30000))
* {
* case STATUS_CODE_SUCCESS:
* return STATUS_CODE_SUCCESS;
*
* // Enter was hit with no input; return STATUS_CODE_CONTINUE to display another page.
* case STATUS_CODE_UNCHANGED:
* return STATUS_CODE_CONTINUE;
*
* case STATUS_CODE_TIMEOUT:
* return STATUS_CODE_TIMEOUT;
*
* default:
* return STATUS_CODE_QUIT;
* }
*
* String m_input;
* };
*
* MyPager myPager(uiIo);
* try
* {
* UiPaginator uiPaginator(uiIo, myPager);
*
* for (size_t i = 0; i < 100; ++i)
* {
* uiIo.PutString(Fmt::Format("{}\n", i));
* }
* }
* catch (const UiPaginator::InputException &)
* {
* // User has entered something at the paging prompt and dropped out.
* uiIo.PutString("You entered: %s\n") % myPager.m_input);
* }
* catch (UiPaginator::QuitException &)
* {
* // User has not continued, or timed out at a paging prompt.
* }
*
* Only one instance of a UiPaginator should be in scope for a given ui user at any once time. Successive UiPaginators will be
* ignored.
*
* The destructor for UiPaginator *may* request input from the user. As such, the same caveats about validity of objects on
* the stack after a UiIo::GetString() type call hold. Whilst waiting for input, the UI fiber is switched out and the main
* fiber may have deleted an object that something on the UI fiber's stack refers to.
*
* UiPaginator instances should be stack based, not dynamically allocated.
*/
class UiPaginator ACTIV_FINAL : private Boost::noncopyable
{
public:
const static size_t m_defaultTimeoutPeriod = 30000;
//! Thrown if the user wants to drop out of the paging early.
class QuitException
{
public:
QuitException(const bool hasTimedOut) : m_hasTimedOut(hasTimedOut)
{
}
const bool m_hasTimedOut; ///< Whether it's a timeout exception.
};
//! Thrown if the user wants to drop out of the paging early and has entered something at a prompt.
class InputException
{
};
//! Base for writing a custom paging prompt.
class Pager : private Boost::noncopyable
{
public:
//! Destructor.
virtual ~Pager()
{
}
/**
* @brief Called when a page's worth of output has been displayed.
*
* @param uiIo
*
* @retval STATUS_CODE_SUCCESS drop out of the paging display and throw InputException, meaning the user has
* entered something at the paging prompt.
* @retval STATUS_CODE_CONTINUE continue to show another page of output.
* @retval STATUS_CODE_TIMEOUT timeout hit whilst waiting for user input at paging prompt. QuitException is thrown.
* @retval STATUS_CODE_EXIT drop out of the paging display and throw QuitException, meaning the user hasn't entered
* anything but wants to stop the paging display.
* @retval ... anything else is treated as STATUS_CODE_EXIT.
*/
virtual StatusCode Do(const UiIo &uiIo) = 0;
};
/**
* @brief Constructor.
*
* This uses a default paging prompt "Continue". If the user enters no at a prompt, or the prompt times out,
* QuitException is thrown.
*
* @param uiIo
* @param header header to display at the start of each page.
* @param timeoutPeriod how long the default paging prompt will wait for input.
*/
ACTIV_FRAMEWORK_API UiPaginator(const UiIo &uiIo, const String &header = String(),
const TimeoutPeriod timeoutPeriod = m_defaultTimeoutPeriod);
/**
* @brief Constructor.
*
* This uses a custom paging prompt as provided by the Pager::Do() function.
* If the user enters no at a prompt, QuitException is thrown. If the user enters something, InputException is thrown.
*
* @param uiIo
* @param pager handling the paging prompt.
* @param shouldPromptAtEnd whether to display the prompt when all output has been displayed, as well as between pages.
* @param header header to display at the start of each page.
*/
ACTIV_FRAMEWORK_API UiPaginator(const UiIo &uiIo, Pager &pager, const bool shouldPromptAtEnd,
const String &header = String());
/**
* @brief Destructor.
*
* When the UiPaginator is destroyed, any output buffered whilst it was in scope is displayed a page at a time.
*/
ACTIV_FRAMEWORK_API ~UiPaginator() ACTIV_BOOST_NOEXCEPT_IF(false);
private:
//! Show the standard prompt or call through to the user's custom prompt. Return values as for Pager::Do().
StatusCode DoPage();
// Insufficient, but try to stop dynamic allocation.
void *operator new(size_t) ACTIV_DELETE;
void *operator new(size_t, const std::nothrow_t &) ACTIV_DELETE;
void *operator new(size_t, void *) ACTIV_DELETE;
void *operator new[](size_t) ACTIV_DELETE;
void *operator new[](size_t, const std::nothrow_t &) ACTIV_DELETE;
void *operator new[](size_t, void *) ACTIV_DELETE;
const UiIo & m_uiIo;
const String m_header;
const size_t m_numberOfHeaderLines;
Pager * const m_pPager;
const TimeoutPeriod m_timeoutPeriod;
const bool m_shouldPromptAtEnd;
friend class UiUser;
};
// ---------------------------------------------------------------------------------------------------------------------------------
template<typename T>
StatusCode UiIo::PutStringList(const T &stringRange, const size_t numberOfLeadingSpaces) const
{
size_t numberOfStrings = 0;
size_t longestStringLength = 0;
for (typename T::const_iterator iter = stringRange.begin(), iterEnd = stringRange.end(); iter != iterEnd;
++iter, ++numberOfStrings)
{
const size_t thisLength(iter->length());
if (thisLength > longestStringLength)
longestStringLength = thisLength;
}
UiIo::Columnizer columnizer(*this, numberOfLeadingSpaces, numberOfStrings, longestStringLength);
if (columnizer.m_numberOfColumns <= 1)
{
// Don't bother trimming in this case.
for (typename T::const_iterator iter = stringRange.begin(), iterEnd = stringRange.end(); iter != iterEnd; ++iter)
{
ACTIV_RETURN_RESULT_IF(STATUS_CODE_SUCCESS, !=, PutString("%-*.*s%s\n",
static_cast<int>(numberOfLeadingSpaces), static_cast<int>(numberOfLeadingSpaces), "", iter->c_str()));
}
}
else
{
const size_t bufferSize = longestStringLength + columnizer.m_columnSpacing + 1;
Boost::scoped_array<char> pLineBuffer(new char[bufferSize]);
typename T::const_iterator stringIter = stringRange.begin();
for (size_t line = 0; line < columnizer.m_numberOfLines; ++line)
{
String str(numberOfLeadingSpaces, ' ');
for (size_t j = 0; j < columnizer.m_numberOfColumns; ++j)
{
const String &string((stringIter != stringRange.end()) ? *stringIter++ : "");
// No need for trailing spaces on last column.
const size_t thisColumnSpacing = (j == (columnizer.m_numberOfColumns - 1)) ? 0 : columnizer.m_columnSpacing;
(void) Snprintf(pLineBuffer.get(), bufferSize, "%-*.*s",
static_cast<int>(longestStringLength + thisColumnSpacing),
static_cast<int>(longestStringLength + thisColumnSpacing),
string.c_str());
str.append(pLineBuffer.get());
}
str.append("\n");
ACTIV_RETURN_RESULT_IF(STATUS_CODE_SUCCESS, !=, PutString(str));
}
}
return STATUS_CODE_SUCCESS;
}
// ---------------------------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------------------------
/**
* @brief Stream insertion operator for UiIo::Attribute.
*
* NB for some reason, BoostFormat can't resolve this if it's in the global namespace (where it should probably really be),
* so it is in the Activ namespace.
*
* @param os the ostream to insert into.
* @param attribute the attribute to insert.
*
* @return os.
*/
ACTIV_FRAMEWORK_API std::ostream &operator<<(std::ostream &os, const UiIo::Attribute &attribute);
} // namespace Activ
#endif // (!defined ACTIV_FRAMEWORK_UI_IO_H)