<commit_before>/****************************************************************************
 *
 *   (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
 *
 * QGroundControl is licensed according to the terms in the file
 * COPYING.md in the root of the source code directory.
 *
 ****************************************************************************/

#include "FirmwarePlugin.h"
#include "QGCApplication.h"
#include "Generic/GenericAutoPilotPlugin.h"
#include "CameraMetaData.h"
#include "SettingsManager.h"
#include "AppSettings.h"

#include <QDebug>

static FirmwarePluginFactoryRegister* _instance = NULL;

const char* guided_mode_not_supported_by_vehicle = "Guided mode not supported by Vehicle.";

QVariantList FirmwarePlugin::_cameraList;

const char* FirmwarePlugin::px4FollowMeFlightMode = "Follow Me";

FirmwarePluginFactory::FirmwarePluginFactory(void)
{
    FirmwarePluginFactoryRegister::instance()->registerPluginFactory(this);
}

QList<MAV_TYPE> FirmwarePluginFactory::supportedVehicleTypes(void) const
{
    QList<MAV_TYPE> vehicleTypes;
    vehicleTypes << MAV_TYPE_FIXED_WING << MAV_TYPE_QUADROTOR << MAV_TYPE_VTOL_QUADROTOR << MAV_TYPE_GROUND_ROVER << MAV_TYPE_SUBMARINE;
    return vehicleTypes;
}

FirmwarePluginFactoryRegister* FirmwarePluginFactoryRegister::instance(void)
{
    if (!_instance) {
        _instance = new FirmwarePluginFactoryRegister;
    }

    return _instance;
}

AutoPilotPlugin* FirmwarePlugin::autopilotPlugin(Vehicle* vehicle)
{
    return new GenericAutoPilotPlugin(vehicle, vehicle);
}

bool FirmwarePlugin::isCapable(const Vehicle *vehicle, FirmwareCapabilities capabilities)
{
    Q_UNUSED(vehicle);
    Q_UNUSED(capabilities);
    return false;
}

QList<VehicleComponent*> FirmwarePlugin::componentsForVehicle(AutoPilotPlugin* vehicle)
{
    Q_UNUSED(vehicle);

    return QList<VehicleComponent*>();
}

QString FirmwarePlugin::flightMode(uint8_t base_mode, uint32_t custom_mode) const
{
    QString flightMode;

    struct Bit2Name {
        uint8_t     baseModeBit;
        const char* name;
    };
    static const struct Bit2Name rgBit2Name[] = {
    { MAV_MODE_FLAG_MANUAL_INPUT_ENABLED,   "Manual" },
    { MAV_MODE_FLAG_STABILIZE_ENABLED,      "Stabilize" },
    { MAV_MODE_FLAG_GUIDED_ENABLED,         "Guided" },
    { MAV_MODE_FLAG_AUTO_ENABLED,           "Auto" },
    { MAV_MODE_FLAG_TEST_ENABLED,           "Test" },
};

    Q_UNUSED(custom_mode);

    if (base_mode == 0) {
        flightMode = "PreFlight";
    } else if (base_mode & MAV_MODE_FLAG_CUSTOM_MODE_ENABLED) {
        flightMode = QString("Custom:0x%1").arg(custom_mode, 0, 16);
    } else {
        for (size_t i=0; i<sizeof(rgBit2Name)/sizeof(rgBit2Name[0]); i++) {
            if (base_mode & rgBit2Name[i].baseModeBit) {
                if (i != 0) {
                    flightMode += " ";
                }
                flightMode += rgBit2Name[i].name;
            }
        }
    }

    return flightMode;
}

bool FirmwarePlugin::setFlightMode(const QString& flightMode, uint8_t* base_mode, uint32_t* custom_mode)
{
    Q_UNUSED(flightMode);
    Q_UNUSED(base_mode);
    Q_UNUSED(custom_mode);

    qWarning() << "FirmwarePlugin::setFlightMode called on base class, not supported";

    return false;
}

int FirmwarePlugin::manualControlReservedButtonCount(void)
{
    // We don't know whether the firmware is going to used any of these buttons.
    // So reserve them all.
    return -1;
}

int FirmwarePlugin::defaultJoystickTXMode(void)
{
    return 2;
}

bool FirmwarePlugin::supportsThrottleModeCenterZero(void)
{
    // By default, this is supported
    return true;
}

bool FirmwarePlugin::supportsManualControl(void)
{
    return false;
}

bool FirmwarePlugin::supportsRadio(void)
{
    return true;
}

bool FirmwarePlugin::supportsCalibratePressure(void)
{
    return false;
}

bool FirmwarePlugin::supportsMotorInterference(void)
{
    return true;
}

bool FirmwarePlugin::supportsJSButton(void)
{
    return false;
}

bool FirmwarePlugin::adjustIncomingMavlinkMessage(Vehicle* vehicle, mavlink_message_t* message)
{
    Q_UNUSED(vehicle);
    Q_UNUSED(message);
    // Generic plugin does no message adjustment
    return true;
}

void FirmwarePlugin::adjustOutgoingMavlinkMessage(Vehicle* vehicle, LinkInterface* outgoingLink, mavlink_message_t* message)
{
    Q_UNUSED(vehicle);
    Q_UNUSED(outgoingLink);
    Q_UNUSED(message);
    // Generic plugin does no message adjustment
}

void FirmwarePlugin::initializeVehicle(Vehicle* vehicle)
{
    Q_UNUSED(vehicle);

    // Generic Flight Stack is by definition "generic", so no extra work
}

bool FirmwarePlugin::sendHomePositionToVehicle(void)
{
    // Generic stack does not want home position sent in the first position.
    // Subsequent sequence numbers must be adjusted.
    // This is the mavlink spec default.
    return false;
}

QList<MAV_CMD> FirmwarePlugin::supportedMissionCommands(void)
{
    // Generic supports all commands
    return QList<MAV_CMD>();
}

QString FirmwarePlugin::missionCommandOverrides(MAV_TYPE vehicleType) const
{
    switch (vehicleType) {
    case MAV_TYPE_GENERIC:
        return QStringLiteral(":/json/MavCmdInfoCommon.json");
        break;
    case MAV_TYPE_FIXED_WING:
        return QStringLiteral(":/json/MavCmdInfoFixedWing.json");
        break;
    case MAV_TYPE_QUADROTOR:
        return QStringLiteral(":/json/MavCmdInfoMultiRotor.json");
        break;
    case MAV_TYPE_VTOL_QUADROTOR:
        return QStringLiteral(":/json/MavCmdInfoVTOL.json");
        break;
    case MAV_TYPE_SUBMARINE:
        return QStringLiteral(":/json/MavCmdInfoSub.json");
        break;
    case MAV_TYPE_GROUND_ROVER:
        return QStringLiteral(":/json/MavCmdInfoRover.json");
        break;
    default:
        qWarning() << "FirmwarePlugin::missionCommandOverrides called with bad MAV_TYPE:" << vehicleType;
        return QString();
    }
}

void FirmwarePlugin::getParameterMetaDataVersionInfo(const QString& metaDataFile, int& majorVersion, int& minorVersion)
{
    Q_UNUSED(metaDataFile);
    majorVersion = -1;
    minorVersion = -1;
}

bool FirmwarePlugin::isGuidedMode(const Vehicle* vehicle) const
{
    // Not supported by generic vehicle
    Q_UNUSED(vehicle);
    return false;
}

void FirmwarePlugin::setGuidedMode(Vehicle* vehicle, bool guidedMode)
{
    Q_UNUSED(vehicle);
    Q_UNUSED(guidedMode);
    qgcApp()->showMessage(guided_mode_not_supported_by_vehicle);
}

void FirmwarePlugin::pauseVehicle(Vehicle* vehicle)
{
    // Not supported by generic vehicle
    Q_UNUSED(vehicle);
    qgcApp()->showMessage(guided_mode_not_supported_by_vehicle);
}

void FirmwarePlugin::guidedModeRTL(Vehicle* vehicle)
{
    // Not supported by generic vehicle
    Q_UNUSED(vehicle);
    qgcApp()->showMessage(guided_mode_not_supported_by_vehicle);
}

void FirmwarePlugin::guidedModeLand(Vehicle* vehicle)
{
    // Not supported by generic vehicle
    Q_UNUSED(vehicle);
    qgcApp()->showMessage(guided_mode_not_supported_by_vehicle);
}

void FirmwarePlugin::guidedModeTakeoff(Vehicle* vehicle)
{
    // Not supported by generic vehicle
    Q_UNUSED(vehicle);
    qgcApp()->showMessage(guided_mode_not_supported_by_vehicle);
}

void FirmwarePlugin::guidedModeOrbit(Vehicle* /*vehicle*/, const QGeoCoordinate& /*centerCoord*/, double /*radius*/, double /*velocity*/, double /*altitude*/)
{
    // Not supported by generic vehicle
    qgcApp()->showMessage(guided_mode_not_supported_by_vehicle);
}

void FirmwarePlugin::guidedModeGotoLocation(Vehicle* vehicle, const QGeoCoordinate& gotoCoord)
{
    // Not supported by generic vehicle
    Q_UNUSED(vehicle);
    Q_UNUSED(gotoCoord);
    qgcApp()->showMessage(guided_mode_not_supported_by_vehicle);
}

void FirmwarePlugin::guidedModeChangeAltitude(Vehicle* vehicle, double altitudeRel)
{
    // Not supported by generic vehicle
    Q_UNUSED(vehicle);
    Q_UNUSED(altitudeRel);
    qgcApp()->showMessage(guided_mode_not_supported_by_vehicle);
}

void FirmwarePlugin::startMission(Vehicle* vehicle)
{
    // Not supported by generic vehicle
    Q_UNUSED(vehicle);
    qgcApp()->showMessage(guided_mode_not_supported_by_vehicle);
}

const FirmwarePlugin::remapParamNameMajorVersionMap_t& FirmwarePlugin::paramNameRemapMajorVersionMap(void) const
{
    static const remapParamNameMajorVersionMap_t remap;

    return remap;
}

int FirmwarePlugin::remapParamNameHigestMinorVersionNumber(int majorVersionNumber) const
{
    Q_UNUSED(majorVersionNumber);
    return 0;
}

QString FirmwarePlugin::vehicleImageOpaque(const Vehicle* vehicle) const
{
    Q_UNUSED(vehicle);
    return QStringLiteral("/qmlimages/vehicleArrowOpaque.svg");
}

QString FirmwarePlugin::vehicleImageOutline(const Vehicle* vehicle) const
{
    Q_UNUSED(vehicle);
    return QStringLiteral("/qmlimages/vehicleArrowOutline.svg");
}

QString FirmwarePlugin::vehicleImageCompass(const Vehicle* vehicle) const
{
    Q_UNUSED(vehicle);
    return QStringLiteral("/qmlimages/compassInstrumentArrow.svg");
}

const QVariantList &FirmwarePlugin::toolBarIndicators(const Vehicle* vehicle)
{
    Q_UNUSED(vehicle);
    //-- Default list of indicators for all vehicles.
    if(_toolBarIndicatorList.size() == 0) {
        _toolBarIndicatorList.append(QVariant::fromValue(QUrl::fromUserInput("qrc:/toolbar/MessageIndicator.qml")));
        _toolBarIndicatorList.append(QVariant::fromValue(QUrl::fromUserInput("qrc:/toolbar/GPSIndicator.qml")));
        _toolBarIndicatorList.append(QVariant::fromValue(QUrl::fromUserInput("qrc:/toolbar/TelemetryRSSIIndicator.qml")));
        _toolBarIndicatorList.append(QVariant::fromValue(QUrl::fromUserInput("qrc:/toolbar/RCRSSIIndicator.qml")));
        _toolBarIndicatorList.append(QVariant::fromValue(QUrl::fromUserInput("qrc:/toolbar/BatteryIndicator.qml")));
        _toolBarIndicatorList.append(QVariant::fromValue(QUrl::fromUserInput("qrc:/toolbar/ModeIndicator.qml")));
        _toolBarIndicatorList.append(QVariant::fromValue(QUrl::fromUserInput("qrc:/toolbar/ArmedIndicator.qml")));
    }
    return _toolBarIndicatorList;
}

const QVariantList& FirmwarePlugin::cameraList(const Vehicle* vehicle)
{
    Q_UNUSED(vehicle);

    if (_cameraList.size() == 0) {
        CameraMetaData* metaData;

        metaData = new CameraMetaData(tr("Typhoon H CGO3+"),    // Camera name
                                      6.264,                    // sensorWidth
                                      4.698,                    // sensorHeight
                                      4000,                     // imageWidth
                                      3000,                     // imageHeight
                                      14,                       // focalLength
                                      true,                     // landscape orientation
                                      true,                     // camera orientation is fixed
                                      this);                    // parent
        _cameraList.append(QVariant::fromValue(metaData));

        metaData = new CameraMetaData(tr("Sony ILCE-QX1"),  //http://www.sony.co.uk/electronics/interchangeable-lens-cameras/ilce-qx1-body-kit/specifications
                                      23.2,                 //http://www.sony.com/electronics/camera-lenses/sel16f28/specifications
                                      15.4,
                                      5456,
                                      3632,
                                      16,
                                      true,
                                      false,
                                      this);
        _cameraList.append(QVariant::fromValue(metaData));

        metaData = new CameraMetaData(tr("Canon S100 PowerShot"),
                                      7.6,
                                      5.7,
                                      4000,
                                      3000,
                                      5.2,
                                      true,
                                      false,
                                      this);
        _cameraList.append(QVariant::fromValue(metaData));

        metaData = new CameraMetaData(tr("Canon G9 X PowerShot"),
                                      13.2,
                                      8.8,
                                      5488,
                                      3680,
                                      10.2,
                                      true,
                                      false,
                                      this);
        _cameraList.append(QVariant::fromValue(metaData));

        metaData = new CameraMetaData(tr("Canon SX260 HS PowerShot"),
                                      6.17,
                                      4.55,
                                      4000,
                                      3000,
                                      4.5,
                                      true,
                                      false,
                                      this);

        metaData = new CameraMetaData(tr("Canon EOS-M 22mm"),
                                      22.3,
                                      14.9,
                                      5184,
                                      3456,
                                      22,
                                      true,
                                      false,
                                      this);
        _cameraList.append(QVariant::fromValue(metaData));

        metaData = new CameraMetaData(tr("Sony a6000 16mm"),    //http://www.sony.co.uk/electronics/interchangeable-lens-cameras/ilce-6000-body-kit#product_details_default
                                      23.5,
                                      15.6,
                                      6000,
                                      4000,
                                      16,
                                      true,
                                      false,
                                      this);
        _cameraList.append(QVariant::fromValue(metaData));
    }

    return _cameraList;
}

bool FirmwarePlugin::vehicleYawsToNextWaypointInMission(const Vehicle* vehicle) const
{
    return vehicle->multiRotor() ? false : true;
}

bool FirmwarePlugin::_armVehicleAndValidate(Vehicle* vehicle)
{
    if (vehicle->armed()) {
        return true;
    }

    bool armedChanged = false;

    // We try arming 3 times
    for (int retries=0; retries<3; retries++) {
        vehicle->setArmed(true);

        // Wait for vehicle to return armed state for 3 seconds
        for (int i=0; i<30; i++) {
            if (vehicle->armed()) {
                armedChanged = true;
                break;
            }
            QGC::SLEEP::msleep(100);
            qgcApp()->processEvents(QEventLoop::ExcludeUserInputEvents);
        }
        if (armedChanged) {
            break;
        }
    }

    return armedChanged;
}

bool FirmwarePlugin::_setFlightModeAndValidate(Vehicle* vehicle, const QString& flightMode)
{
    if (vehicle->flightMode() == flightMode) {
        return true;
    }

    bool flightModeChanged = false;

    // We try 3 times
    for (int retries=0; retries<3; retries++) {
        vehicle->setFlightMode(flightMode);

        // Wait for vehicle to return flight mode
        for (int i=0; i<30; i++) {
            if (vehicle->flightMode() == flightMode) {
                flightModeChanged = true;
                break;
            }
            QGC::SLEEP::msleep(100);
            qgcApp()->processEvents(QEventLoop::ExcludeUserInputEvents);
        }
        if (flightModeChanged) {
            break;
        }
    }

    return flightModeChanged;
}

void FirmwarePlugin::batteryConsumptionData(Vehicle* vehicle, int& mAhBattery, double& hoverAmps, double& cruiseAmps) const
{
    Q_UNUSED(vehicle);
    mAhBattery = 0;
    hoverAmps = 0;
    cruiseAmps = 0;
}

QString FirmwarePlugin::autoDisarmParameter(Vehicle* vehicle)
{
    Q_UNUSED(vehicle);
    return QString();
}

bool FirmwarePlugin::hasGimbal(Vehicle* vehicle, bool& rollSupported, bool& pitchSupported, bool& yawSupported)
{
    Q_UNUSED(vehicle);
    rollSupported = false;
    pitchSupported = false;
    yawSupported = false;
    return false;
}
<commit_msg>Remove Typhoon Camera<commit_after>/****************************************************************************
 *
 *   (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
 *
 * QGroundControl is licensed according to the terms in the file
 * COPYING.md in the root of the source code directory.
 *
 ****************************************************************************/

#include "FirmwarePlugin.h"
#include "QGCApplication.h"
#include "Generic/GenericAutoPilotPlugin.h"
#include "CameraMetaData.h"
#include "SettingsManager.h"
#include "AppSettings.h"

#include <QDebug>

static FirmwarePluginFactoryRegister* _instance = NULL;

const char* guided_mode_not_supported_by_vehicle = "Guided mode not supported by Vehicle.";

QVariantList FirmwarePlugin::_cameraList;

const char* FirmwarePlugin::px4FollowMeFlightMode = "Follow Me";

FirmwarePluginFactory::FirmwarePluginFactory(void)
{
    FirmwarePluginFactoryRegister::instance()->registerPluginFactory(this);
}

QList<MAV_TYPE> FirmwarePluginFactory::supportedVehicleTypes(void) const
{
    QList<MAV_TYPE> vehicleTypes;
    vehicleTypes << MAV_TYPE_FIXED_WING << MAV_TYPE_QUADROTOR << MAV_TYPE_VTOL_QUADROTOR << MAV_TYPE_GROUND_ROVER << MAV_TYPE_SUBMARINE;
    return vehicleTypes;
}

FirmwarePluginFactoryRegister* FirmwarePluginFactoryRegister::instance(void)
{
    if (!_instance) {
        _instance = new FirmwarePluginFactoryRegister;
    }

    return _instance;
}

AutoPilotPlugin* FirmwarePlugin::autopilotPlugin(Vehicle* vehicle)
{
    return new GenericAutoPilotPlugin(vehicle, vehicle);
}

bool FirmwarePlugin::isCapable(const Vehicle *vehicle, FirmwareCapabilities capabilities)
{
    Q_UNUSED(vehicle);
    Q_UNUSED(capabilities);
    return false;
}

QList<VehicleComponent*> FirmwarePlugin::componentsForVehicle(AutoPilotPlugin* vehicle)
{
    Q_UNUSED(vehicle);

    return QList<VehicleComponent*>();
}

QString FirmwarePlugin::flightMode(uint8_t base_mode, uint32_t custom_mode) const
{
    QString flightMode;

    struct Bit2Name {
        uint8_t     baseModeBit;
        const char* name;
    };
    static const struct Bit2Name rgBit2Name[] = {
    { MAV_MODE_FLAG_MANUAL_INPUT_ENABLED,   "Manual" },
    { MAV_MODE_FLAG_STABILIZE_ENABLED,      "Stabilize" },
    { MAV_MODE_FLAG_GUIDED_ENABLED,         "Guided" },
    { MAV_MODE_FLAG_AUTO_ENABLED,           "Auto" },
    { MAV_MODE_FLAG_TEST_ENABLED,           "Test" },
};

    Q_UNUSED(custom_mode);

    if (base_mode == 0) {
        flightMode = "PreFlight";
    } else if (base_mode & MAV_MODE_FLAG_CUSTOM_MODE_ENABLED) {
        flightMode = QString("Custom:0x%1").arg(custom_mode, 0, 16);
    } else {
        for (size_t i=0; i<sizeof(rgBit2Name)/sizeof(rgBit2Name[0]); i++) {
            if (base_mode & rgBit2Name[i].baseModeBit) {
                if (i != 0) {
                    flightMode += " ";
                }
                flightMode += rgBit2Name[i].name;
            }
        }
    }

    return flightMode;
}

bool FirmwarePlugin::setFlightMode(const QString& flightMode, uint8_t* base_mode, uint32_t* custom_mode)
{
    Q_UNUSED(flightMode);
    Q_UNUSED(base_mode);
    Q_UNUSED(custom_mode);

    qWarning() << "FirmwarePlugin::setFlightMode called on base class, not supported";

    return false;
}

int FirmwarePlugin::manualControlReservedButtonCount(void)
{
    // We don't know whether the firmware is going to used any of these buttons.
    // So reserve them all.
    return -1;
}

int FirmwarePlugin::defaultJoystickTXMode(void)
{
    return 2;
}

bool FirmwarePlugin::supportsThrottleModeCenterZero(void)
{
    // By default, this is supported
    return true;
}

bool FirmwarePlugin::supportsManualControl(void)
{
    return false;
}

bool FirmwarePlugin::supportsRadio(void)
{
    return true;
}

bool FirmwarePlugin::supportsCalibratePressure(void)
{
    return false;
}

bool FirmwarePlugin::supportsMotorInterference(void)
{
    return true;
}

bool FirmwarePlugin::supportsJSButton(void)
{
    return false;
}

bool FirmwarePlugin::adjustIncomingMavlinkMessage(Vehicle* vehicle, mavlink_message_t* message)
{
    Q_UNUSED(vehicle);
    Q_UNUSED(message);
    // Generic plugin does no message adjustment
    return true;
}

void FirmwarePlugin::adjustOutgoingMavlinkMessage(Vehicle* vehicle, LinkInterface* outgoingLink, mavlink_message_t* message)
{
    Q_UNUSED(vehicle);
    Q_UNUSED(outgoingLink);
    Q_UNUSED(message);
    // Generic plugin does no message adjustment
}

void FirmwarePlugin::initializeVehicle(Vehicle* vehicle)
{
    Q_UNUSED(vehicle);

    // Generic Flight Stack is by definition "generic", so no extra work
}

bool FirmwarePlugin::sendHomePositionToVehicle(void)
{
    // Generic stack does not want home position sent in the first position.
    // Subsequent sequence numbers must be adjusted.
    // This is the mavlink spec default.
    return false;
}

QList<MAV_CMD> FirmwarePlugin::supportedMissionCommands(void)
{
    // Generic supports all commands
    return QList<MAV_CMD>();
}

QString FirmwarePlugin::missionCommandOverrides(MAV_TYPE vehicleType) const
{
    switch (vehicleType) {
    case MAV_TYPE_GENERIC:
        return QStringLiteral(":/json/MavCmdInfoCommon.json");
        break;
    case MAV_TYPE_FIXED_WING:
        return QStringLiteral(":/json/MavCmdInfoFixedWing.json");
        break;
    case MAV_TYPE_QUADROTOR:
        return QStringLiteral(":/json/MavCmdInfoMultiRotor.json");
        break;
    case MAV_TYPE_VTOL_QUADROTOR:
        return QStringLiteral(":/json/MavCmdInfoVTOL.json");
        break;
    case MAV_TYPE_SUBMARINE:
        return QStringLiteral(":/json/MavCmdInfoSub.json");
        break;
    case MAV_TYPE_GROUND_ROVER:
        return QStringLiteral(":/json/MavCmdInfoRover.json");
        break;
    default:
        qWarning() << "FirmwarePlugin::missionCommandOverrides called with bad MAV_TYPE:" << vehicleType;
        return QString();
    }
}

void FirmwarePlugin::getParameterMetaDataVersionInfo(const QString& metaDataFile, int& majorVersion, int& minorVersion)
{
    Q_UNUSED(metaDataFile);
    majorVersion = -1;
    minorVersion = -1;
}

bool FirmwarePlugin::isGuidedMode(const Vehicle* vehicle) const
{
    // Not supported by generic vehicle
    Q_UNUSED(vehicle);
    return false;
}

void FirmwarePlugin::setGuidedMode(Vehicle* vehicle, bool guidedMode)
{
    Q_UNUSED(vehicle);
    Q_UNUSED(guidedMode);
    qgcApp()->showMessage(guided_mode_not_supported_by_vehicle);
}

void FirmwarePlugin::pauseVehicle(Vehicle* vehicle)
{
    // Not supported by generic vehicle
    Q_UNUSED(vehicle);
    qgcApp()->showMessage(guided_mode_not_supported_by_vehicle);
}

void FirmwarePlugin::guidedModeRTL(Vehicle* vehicle)
{
    // Not supported by generic vehicle
    Q_UNUSED(vehicle);
    qgcApp()->showMessage(guided_mode_not_supported_by_vehicle);
}

void FirmwarePlugin::guidedModeLand(Vehicle* vehicle)
{
    // Not supported by generic vehicle
    Q_UNUSED(vehicle);
    qgcApp()->showMessage(guided_mode_not_supported_by_vehicle);
}

void FirmwarePlugin::guidedModeTakeoff(Vehicle* vehicle)
{
    // Not supported by generic vehicle
    Q_UNUSED(vehicle);
    qgcApp()->showMessage(guided_mode_not_supported_by_vehicle);
}

void FirmwarePlugin::guidedModeOrbit(Vehicle* /*vehicle*/, const QGeoCoordinate& /*centerCoord*/, double /*radius*/, double /*velocity*/, double /*altitude*/)
{
    // Not supported by generic vehicle
    qgcApp()->showMessage(guided_mode_not_supported_by_vehicle);
}

void FirmwarePlugin::guidedModeGotoLocation(Vehicle* vehicle, const QGeoCoordinate& gotoCoord)
{
    // Not supported by generic vehicle
    Q_UNUSED(vehicle);
    Q_UNUSED(gotoCoord);
    qgcApp()->showMessage(guided_mode_not_supported_by_vehicle);
}

void FirmwarePlugin::guidedModeChangeAltitude(Vehicle* vehicle, double altitudeRel)
{
    // Not supported by generic vehicle
    Q_UNUSED(vehicle);
    Q_UNUSED(altitudeRel);
    qgcApp()->showMessage(guided_mode_not_supported_by_vehicle);
}

void FirmwarePlugin::startMission(Vehicle* vehicle)
{
    // Not supported by generic vehicle
    Q_UNUSED(vehicle);
    qgcApp()->showMessage(guided_mode_not_supported_by_vehicle);
}

const FirmwarePlugin::remapParamNameMajorVersionMap_t& FirmwarePlugin::paramNameRemapMajorVersionMap(void) const
{
    static const remapParamNameMajorVersionMap_t remap;

    return remap;
}

int FirmwarePlugin::remapParamNameHigestMinorVersionNumber(int majorVersionNumber) const
{
    Q_UNUSED(majorVersionNumber);
    return 0;
}

QString FirmwarePlugin::vehicleImageOpaque(const Vehicle* vehicle) const
{
    Q_UNUSED(vehicle);
    return QStringLiteral("/qmlimages/vehicleArrowOpaque.svg");
}

QString FirmwarePlugin::vehicleImageOutline(const Vehicle* vehicle) const
{
    Q_UNUSED(vehicle);
    return QStringLiteral("/qmlimages/vehicleArrowOutline.svg");
}

QString FirmwarePlugin::vehicleImageCompass(const Vehicle* vehicle) const
{
    Q_UNUSED(vehicle);
    return QStringLiteral("/qmlimages/compassInstrumentArrow.svg");
}

const QVariantList &FirmwarePlugin::toolBarIndicators(const Vehicle* vehicle)
{
    Q_UNUSED(vehicle);
    //-- Default list of indicators for all vehicles.
    if(_toolBarIndicatorList.size() == 0) {
        _toolBarIndicatorList.append(QVariant::fromValue(QUrl::fromUserInput("qrc:/toolbar/MessageIndicator.qml")));
        _toolBarIndicatorList.append(QVariant::fromValue(QUrl::fromUserInput("qrc:/toolbar/GPSIndicator.qml")));
        _toolBarIndicatorList.append(QVariant::fromValue(QUrl::fromUserInput("qrc:/toolbar/TelemetryRSSIIndicator.qml")));
        _toolBarIndicatorList.append(QVariant::fromValue(QUrl::fromUserInput("qrc:/toolbar/RCRSSIIndicator.qml")));
        _toolBarIndicatorList.append(QVariant::fromValue(QUrl::fromUserInput("qrc:/toolbar/BatteryIndicator.qml")));
        _toolBarIndicatorList.append(QVariant::fromValue(QUrl::fromUserInput("qrc:/toolbar/ModeIndicator.qml")));
        _toolBarIndicatorList.append(QVariant::fromValue(QUrl::fromUserInput("qrc:/toolbar/ArmedIndicator.qml")));
    }
    return _toolBarIndicatorList;
}

const QVariantList& FirmwarePlugin::cameraList(const Vehicle* vehicle)
{
    Q_UNUSED(vehicle);

    if (_cameraList.size() == 0) {
        CameraMetaData* metaData;

        metaData = new CameraMetaData(tr("Sony ILCE-QX1"),  //http://www.sony.co.uk/electronics/interchangeable-lens-cameras/ilce-qx1-body-kit/specifications
                                      23.2,                 //http://www.sony.com/electronics/camera-lenses/sel16f28/specifications
                                      15.4,
                                      5456,
                                      3632,
                                      16,
                                      true,
                                      false,
                                      this);
        _cameraList.append(QVariant::fromValue(metaData));

        metaData = new CameraMetaData(tr("Canon S100 PowerShot"),
                                      7.6,
                                      5.7,
                                      4000,
                                      3000,
                                      5.2,
                                      true,
                                      false,
                                      this);
        _cameraList.append(QVariant::fromValue(metaData));

        metaData = new CameraMetaData(tr("Canon G9 X PowerShot"),
                                      13.2,
                                      8.8,
                                      5488,
                                      3680,
                                      10.2,
                                      true,
                                      false,
                                      this);
        _cameraList.append(QVariant::fromValue(metaData));

        metaData = new CameraMetaData(tr("Canon SX260 HS PowerShot"),
                                      6.17,
                                      4.55,
                                      4000,
                                      3000,
                                      4.5,
                                      true,
                                      false,
                                      this);

        metaData = new CameraMetaData(tr("Canon EOS-M 22mm"),
                                      22.3,
                                      14.9,
                                      5184,
                                      3456,
                                      22,
                                      true,
                                      false,
                                      this);
        _cameraList.append(QVariant::fromValue(metaData));

        metaData = new CameraMetaData(tr("Sony a6000 16mm"),    //http://www.sony.co.uk/electronics/interchangeable-lens-cameras/ilce-6000-body-kit#product_details_default
                                      23.5,
                                      15.6,
                                      6000,
                                      4000,
                                      16,
                                      true,
                                      false,
                                      this);
        _cameraList.append(QVariant::fromValue(metaData));
    }

    return _cameraList;
}

bool FirmwarePlugin::vehicleYawsToNextWaypointInMission(const Vehicle* vehicle) const
{
    return vehicle->multiRotor() ? false : true;
}

bool FirmwarePlugin::_armVehicleAndValidate(Vehicle* vehicle)
{
    if (vehicle->armed()) {
        return true;
    }

    bool armedChanged = false;

    // We try arming 3 times
    for (int retries=0; retries<3; retries++) {
        vehicle->setArmed(true);

        // Wait for vehicle to return armed state for 3 seconds
        for (int i=0; i<30; i++) {
            if (vehicle->armed()) {
                armedChanged = true;
                break;
            }
            QGC::SLEEP::msleep(100);
            qgcApp()->processEvents(QEventLoop::ExcludeUserInputEvents);
        }
        if (armedChanged) {
            break;
        }
    }

    return armedChanged;
}

bool FirmwarePlugin::_setFlightModeAndValidate(Vehicle* vehicle, const QString& flightMode)
{
    if (vehicle->flightMode() == flightMode) {
        return true;
    }

    bool flightModeChanged = false;

    // We try 3 times
    for (int retries=0; retries<3; retries++) {
        vehicle->setFlightMode(flightMode);

        // Wait for vehicle to return flight mode
        for (int i=0; i<30; i++) {
            if (vehicle->flightMode() == flightMode) {
                flightModeChanged = true;
                break;
            }
            QGC::SLEEP::msleep(100);
            qgcApp()->processEvents(QEventLoop::ExcludeUserInputEvents);
        }
        if (flightModeChanged) {
            break;
        }
    }

    return flightModeChanged;
}

void FirmwarePlugin::batteryConsumptionData(Vehicle* vehicle, int& mAhBattery, double& hoverAmps, double& cruiseAmps) const
{
    Q_UNUSED(vehicle);
    mAhBattery = 0;
    hoverAmps = 0;
    cruiseAmps = 0;
}

QString FirmwarePlugin::autoDisarmParameter(Vehicle* vehicle)
{
    Q_UNUSED(vehicle);
    return QString();
}

bool FirmwarePlugin::hasGimbal(Vehicle* vehicle, bool& rollSupported, bool& pitchSupported, bool& yawSupported)
{
    Q_UNUSED(vehicle);
    rollSupported = false;
    pitchSupported = false;
    yawSupported = false;
    return false;
}
<|endoftext|>


<commit_before>// mathtext - A TeX/LaTeX compatible rendering library. Copyright (C)
// 2008-2012 Yue Shi Lai <ylai@users.sourceforge.net>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation; either version 2.1 of
// the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
// 02110-1301 USA

#include "../inc/fontembed.h"
#include <string.h>
#include <stdio.h>
#ifdef WIN32
#define snprintf _snprintf
#endif

// ROOT integration
#include "RConfig.h"
#ifdef R__BYTESWAP
#ifndef LITTLE_ENDIAN
#define LITTLE_ENDIAN 1
#endif // LITTLE_ENDIAN
#include "Byteswap.h"
#define bswap_16(x)   Rbswap_16((x))
#define bswap_32(x)   Rbswap_32((x))
#else // R__BYTESWAP
#ifdef LITTLE_ENDIAN
#undef LITTLE_ENDIAN
#endif // LITTLE_ENDIAN
#endif // R__BYTESWAP

// References:
//
// Adobe Systems, Inc., PostScript language Document Structuring
// Convention specification (Adobe Systems, Inc., San Jose, CA, 1992),
// version 3.0, section 5.1.
//
// Adobe Systems, Inc., PostScript language reference manual
// (Addison-Wesley, Reading, MA, 1999), 3rd edition, section 5.8.1.
//
// Adobe Systems, Inc., Adobe Type 1 Font Format (Addison-Wesley,
// Reading, MA, 1993), version 1.1
//
// Adobe Systems, Inc., The Compact Font Format specification, Adobe
// Technical Note 5176 (Adobe, Mountain View, CA, 2003), 4 December
// 2003 document
//
// Adobe Systems, Inc., Type 2 charstring format, Adobe Technical Note
// 5177 (Adobe, San Jose, CA, 2000), 16 March 2000 document

namespace mathtext {

   void font_embed_postscript_t::append_asciihex(
                                                 std::string &ascii, const unsigned char *buffer,
                                                 const size_t length)
   {
      const int width = 64;
      int column = 0;

      for(size_t i = 0; i < length; i++) {
         char str[3];

         snprintf(str, 3, "%02hhX", buffer[i]);
         ascii.append(str, 2);
         column += 2;
         if(column >= width) {
            ascii.append(1, '\n');
            column = 0;
         }
      }
   }

   unsigned int font_embed_postscript_t::ascii85_line_count(
                                                            const uint8_t *buffer, const size_t length)
   {
      const unsigned int width = 64;
      unsigned int column = 0;
      unsigned int line = 0;

      if (length >= 4) {
         for (size_t i = 0; i < length - 3; i += 4) {
            unsigned int b = reinterpret_cast<
            const unsigned int *>(buffer)[i >> 2];

            if (b == 0) {
               column++;
               if (column == width - 1) {
                  line++;
                  column = 0;
               }
            }
            else {
               if (column + 5 >= width) {
                  column += 5 - width;
                  line++;
               }
               else {
                  column += 5;
               }
            }
         }
      }
      if (column + (length & 3) + 3 >= width) {
         line++;
      }

      return line;
   }

   void font_embed_postscript_t::append_ascii85(
                                                std::string &ascii, const uint8_t *buffer,
                                                const size_t length)
   {
      const int width = 64;
      int column = 0;

      if (length >= 4) {
         for (size_t i = 0; i < length - 3; i += 4) {
            unsigned int dword = reinterpret_cast<
            const unsigned int *>(buffer)[i >> 2];

            if (dword == 0) {
               ascii.append(1, 'z');
               column++;
               if (column == width - 1) {
                  ascii.append(1, '\n');
                  column = 0;
               }
            }
            else {
#ifdef LITTLE_ENDIAN
               dword = bswap_32(dword);
#endif // LITTLE_ENDIAN

               char str[5];

               str[4] = static_cast<char>(dword % 85 + '!');
               dword /= 85;
               str[3] = static_cast<char>(dword % 85 + '!');
               dword /= 85;
               str[2] = static_cast<char>(dword % 85 + '!');
               dword /= 85;
               str[1] = static_cast<char>(dword % 85 + '!');
               dword /= 85;
               str[0] = static_cast<char>(dword % 85 + '!');
               for (size_t j = 0; j < 5; j++) {
                  ascii.append(1, str[j]);
                  column++;
                  if(column == width) {
                     ascii.append(1, '\n');
                     column = 0;
                  }
               }
            }
         }
      }

      int k = length & 3;

      if(k > 0) {
         unsigned int dword = 0;

         memcpy(&dword, buffer + (length & ~3), k);
#ifdef LITTLE_ENDIAN
         dword = bswap_32(dword);
#endif // LITTLE_ENDIAN

         char str[5];

         str[4] = static_cast<char>(dword % 85 + '!');
         dword /= 85;
         str[3] = static_cast<char>(dword % 85 + '!');
         dword /= 85;
         str[2] = static_cast<char>(dword % 85 + '!');
         dword /= 85;
         str[1] = static_cast<char>(dword % 85 + '!');
         dword /= 85;
         str[0] = static_cast<char>(dword % 85 + '!');
         for(int j = 0; j < k + 1; j++) {
            ascii.append(1, str[j]);
            column++;
            if(column == width) {
               ascii.append(1, '\n');
               column = 0;
            }
         }

      }
      if(column > width - 2)
         ascii.append(1, '\n');
      ascii.append("~>");
   }

   std::string font_embed_postscript_t::font_embed_type_1(
                                                          std::string &font_name,
                                                          const std::vector<unsigned char> &font_data)
   {
      // Embed font type 1

      struct pfb_segment_header_s {
         char always_128;
         char type;
         unsigned int length;
      };
      enum {
         TYPE_ASCII = 1,
         TYPE_BINARY,
         TYPE_EOF
      };

      char magic_number[2];
      std::string ret;

      memcpy(magic_number, &font_data[0], 2);
      if(magic_number[0] == '\200') {
         // IBM PC format printer font binary

         // FIXME: Maybe the real name can be parsed out of the
         // file
         font_name = "";

         struct pfb_segment_header_s segment_header;
         size_t offset = 0;

         segment_header.type = 0;
         while (segment_header.type != TYPE_EOF) {
            // The two char elements of struct
            // pfb_segment_header_s are most likely aligned to
            // larger than 1 byte boundaries, so copy all the
            // elements individually
            segment_header.always_128 = font_data[offset];
            segment_header.type = font_data[offset + 1];
            memcpy(&segment_header.length, &font_data[offset + 2],
                   sizeof(unsigned int));
            offset += sizeof(unsigned int) + 2;
#ifdef LITTLE_ENDIAN
            segment_header.length =
            bswap_32(segment_header.length);
#endif // LITTLE_ENDIAN
            char *buffer = new char[segment_header.length];

            memcpy(buffer, &font_data[offset],
                   segment_header.length);
            offset += segment_header.length;

            switch(segment_header.type) {
               case TYPE_ASCII:
                  // Simple CR -> LF conversion
                  for (int i = 0;
                       i < (int)(segment_header.length) - 1; i++) {
                     if(buffer[i] == '\r' &&
                        buffer[i + 1] != '\n') {
                        buffer[i] = '\n';
                     }
                  }
                  if (buffer[segment_header.length - 1] == '\r') {
                     buffer[segment_header.length - 1] = '\n';
                  }
                  ret.append(buffer, segment_header.length);
                  break;
               case TYPE_BINARY:
                  append_asciihex(
                                  ret, reinterpret_cast<uint8_t *>(buffer),
                                  segment_header.length);
                  break;
               default:
               {}
            }

            delete [] buffer;
         }

         return ret;
      }
      else if(strncmp(magic_number, "%!", 2) == 0) {
         // Printer font ASCII
         fprintf(stderr, "%s:%d: Printer font ASCII is not "
                 "implemented\n", __FILE__, __LINE__);
         return std::string();
      }

      return std::string();
   }

   std::string font_embed_postscript_t::font_embed_type_2(
                                                          std::string &font_name,
                                                          const std::vector<unsigned char> &font_data)
   {
      // Embed an OpenType CFF (Type 2) file in ASCII85 encoding
      // with the PostScript syntax

      unsigned short cid_encoding_id;
      unsigned int cff_offset;
      unsigned int cff_length;

      if (!parse_otf_cff_header(font_name, cid_encoding_id,
                                cff_offset, cff_length,
                                font_data)) {
         return std::string();
      }

      std::vector<unsigned char> cff;

      cff.resize(cff_length + 10);
      memcpy(&cff[0], "StartData\r", 10);
      memcpy(&cff[10], &font_data[cff_offset], cff_length);

      char linebuf[BUFSIZ];
      std::string ret;

      snprintf(linebuf, BUFSIZ, "%%%%BeginResource: FontSet (%s)\n",
               font_name.c_str());
      ret.append(linebuf);
      ret.append("%%VMusage: 0 0\n");
      ret.append("/FontSetInit /ProcSet findresource begin\n");
      snprintf(linebuf, BUFSIZ, "%%%%BeginData: %u ASCII Lines\n",
               ascii85_line_count(&cff[0], cff_length) + 2);
      ret.append(linebuf);
      snprintf(linebuf, BUFSIZ,
               "/%s %u currentfile /ASCII85Decode filter cvx exec\n",
               font_name.c_str(), cff_length);
      ret.append(linebuf);
      append_ascii85(ret, &cff[0], cff_length + 10);
      ret.append(1, '\n');
      ret.append("%%EndData\n");
      ret.append("%%EndResource\n");

      return ret;
   }

   std::string font_embed_postscript_t::font_embed_type_42(
                                                           std::string &font_name,
                                                           const std::vector<unsigned char> &font_data)
   {
      // Embed an TrueType as Type 42 with the PostScript syntax

      double font_bbox[4];
      std::map<wchar_t, uint16_t> cid_map;
      std::vector<std::string> char_strings;

      if (!parse_ttf_header(font_name, font_bbox, cid_map,
                            char_strings, font_data)) {
         fprintf(stderr, "%s:%d:\n", __FILE__, __LINE__);
         return std::string();
      }

      char linebuf[BUFSIZ];
      std::string ret;

      snprintf(linebuf, BUFSIZ, "%%%%BeginResource: FontSet (%s)\n",
               font_name.c_str());
      ret.append(linebuf);
      ret.append("%%VMusage: 0 0\n");
      ret.append("11 dict begin\n");
      snprintf(linebuf, BUFSIZ, "/FontName /%s def\n",
               font_name.c_str());
      ret.append(linebuf);
      ret.append("/Encoding 256 array\n");
      snprintf(linebuf, BUFSIZ,
               "0 1 255 { 1 index exch /%s put } for\n",
               char_strings[0].c_str());
      ret.append(linebuf);
      for (unsigned int code_point = 0; code_point < 256;
           code_point++) {
         unsigned int glyph_index = cid_map[code_point];

         if (char_strings[glyph_index] != ".notdef" &&
             char_strings[glyph_index] != "") {
            snprintf(linebuf, BUFSIZ, "dup %u /%s put\n",
                     code_point,
                     char_strings[glyph_index].c_str());
            ret.append(linebuf);
         }
      }
      ret.append("readonly def\n");
      ret.append("/PaintType 0 def\n");   // 0 for filled, 2 for stroked
      ret.append("/FontMatrix [1 0 0 1 0 0] def\n");
      snprintf(linebuf, BUFSIZ, "/FontBBox [%f %f %f %f] def\n",
               font_bbox[0], font_bbox[1], font_bbox[2], font_bbox[3]);
      ret.append(linebuf);
      ret.append("/FontType 42 def\n");
      // FIXME: XUID generation using the font data's MD5
      ret.append("/sfnts [\n");

      const size_t block_size = 32262;
      size_t offset = 0;

      while (offset < font_data.size()) {
         const size_t output_length =
         std::min(block_size, font_data.size() - offset);

         ret.append("<\n");
         append_asciihex(ret, &font_data[offset], output_length);
         ret.append(">\n");
         offset += output_length;
      }
      ret.append("] def\n");

      unsigned int char_strings_count = 0;

      for (std::vector<std::string>::const_iterator iterator =
           char_strings.begin();
           iterator < char_strings.end(); iterator++) {
         if (!iterator->empty()) {
            char_strings_count++;
         }
      }

      snprintf(linebuf, BUFSIZ, "/CharStrings %u dict dup begin\n",
               char_strings_count);
      ret.append(linebuf);
      for (unsigned int glyph_index = 0;
           glyph_index < char_strings.size(); glyph_index++) {
         if (!char_strings[glyph_index].empty()) {
            snprintf(linebuf, BUFSIZ, "/%s %u def\n",
                     char_strings[glyph_index].c_str(),
                     glyph_index);
            ret.append(linebuf);
         }
      }
      ret.append("end readonly def\n");
      ret.append("FontName currentdict end definefont pop\n");
      ret.append("%%EndResource\n");

      return ret;
   }
}
<commit_msg>Add missing #include <algorithm><commit_after>// mathtext - A TeX/LaTeX compatible rendering library. Copyright (C)
// 2008-2012 Yue Shi Lai <ylai@users.sourceforge.net>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation; either version 2.1 of
// the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
// 02110-1301 USA

#include "../inc/fontembed.h"
#include <string.h>
#include <stdio.h>
#include <algorithm>
#ifdef WIN32
#define snprintf _snprintf
#endif

// ROOT integration
#include "RConfig.h"
#ifdef R__BYTESWAP
#ifndef LITTLE_ENDIAN
#define LITTLE_ENDIAN 1
#endif // LITTLE_ENDIAN
#include "Byteswap.h"
#define bswap_16(x)   Rbswap_16((x))
#define bswap_32(x)   Rbswap_32((x))
#else // R__BYTESWAP
#ifdef LITTLE_ENDIAN
#undef LITTLE_ENDIAN
#endif // LITTLE_ENDIAN
#endif // R__BYTESWAP

// References:
//
// Adobe Systems, Inc., PostScript language Document Structuring
// Convention specification (Adobe Systems, Inc., San Jose, CA, 1992),
// version 3.0, section 5.1.
//
// Adobe Systems, Inc., PostScript language reference manual
// (Addison-Wesley, Reading, MA, 1999), 3rd edition, section 5.8.1.
//
// Adobe Systems, Inc., Adobe Type 1 Font Format (Addison-Wesley,
// Reading, MA, 1993), version 1.1
//
// Adobe Systems, Inc., The Compact Font Format specification, Adobe
// Technical Note 5176 (Adobe, Mountain View, CA, 2003), 4 December
// 2003 document
//
// Adobe Systems, Inc., Type 2 charstring format, Adobe Technical Note
// 5177 (Adobe, San Jose, CA, 2000), 16 March 2000 document

namespace mathtext {

   void font_embed_postscript_t::append_asciihex(
                                                 std::string &ascii, const unsigned char *buffer,
                                                 const size_t length)
   {
      const int width = 64;
      int column = 0;

      for(size_t i = 0; i < length; i++) {
         char str[3];

         snprintf(str, 3, "%02hhX", buffer[i]);
         ascii.append(str, 2);
         column += 2;
         if(column >= width) {
            ascii.append(1, '\n');
            column = 0;
         }
      }
   }

   unsigned int font_embed_postscript_t::ascii85_line_count(
                                                            const uint8_t *buffer, const size_t length)
   {
      const unsigned int width = 64;
      unsigned int column = 0;
      unsigned int line = 0;

      if (length >= 4) {
         for (size_t i = 0; i < length - 3; i += 4) {
            unsigned int b = reinterpret_cast<
            const unsigned int *>(buffer)[i >> 2];

            if (b == 0) {
               column++;
               if (column == width - 1) {
                  line++;
                  column = 0;
               }
            }
            else {
               if (column + 5 >= width) {
                  column += 5 - width;
                  line++;
               }
               else {
                  column += 5;
               }
            }
         }
      }
      if (column + (length & 3) + 3 >= width) {
         line++;
      }

      return line;
   }

   void font_embed_postscript_t::append_ascii85(
                                                std::string &ascii, const uint8_t *buffer,
                                                const size_t length)
   {
      const int width = 64;
      int column = 0;

      if (length >= 4) {
         for (size_t i = 0; i < length - 3; i += 4) {
            unsigned int dword = reinterpret_cast<
            const unsigned int *>(buffer)[i >> 2];

            if (dword == 0) {
               ascii.append(1, 'z');
               column++;
               if (column == width - 1) {
                  ascii.append(1, '\n');
                  column = 0;
               }
            }
            else {
#ifdef LITTLE_ENDIAN
               dword = bswap_32(dword);
#endif // LITTLE_ENDIAN

               char str[5];

               str[4] = static_cast<char>(dword % 85 + '!');
               dword /= 85;
               str[3] = static_cast<char>(dword % 85 + '!');
               dword /= 85;
               str[2] = static_cast<char>(dword % 85 + '!');
               dword /= 85;
               str[1] = static_cast<char>(dword % 85 + '!');
               dword /= 85;
               str[0] = static_cast<char>(dword % 85 + '!');
               for (size_t j = 0; j < 5; j++) {
                  ascii.append(1, str[j]);
                  column++;
                  if(column == width) {
                     ascii.append(1, '\n');
                     column = 0;
                  }
               }
            }
         }
      }

      int k = length & 3;

      if(k > 0) {
         unsigned int dword = 0;

         memcpy(&dword, buffer + (length & ~3), k);
#ifdef LITTLE_ENDIAN
         dword = bswap_32(dword);
#endif // LITTLE_ENDIAN

         char str[5];

         str[4] = static_cast<char>(dword % 85 + '!');
         dword /= 85;
         str[3] = static_cast<char>(dword % 85 + '!');
         dword /= 85;
         str[2] = static_cast<char>(dword % 85 + '!');
         dword /= 85;
         str[1] = static_cast<char>(dword % 85 + '!');
         dword /= 85;
         str[0] = static_cast<char>(dword % 85 + '!');
         for(int j = 0; j < k + 1; j++) {
            ascii.append(1, str[j]);
            column++;
            if(column == width) {
               ascii.append(1, '\n');
               column = 0;
            }
         }

      }
      if(column > width - 2)
         ascii.append(1, '\n');
      ascii.append("~>");
   }

   std::string font_embed_postscript_t::font_embed_type_1(
                                                          std::string &font_name,
                                                          const std::vector<unsigned char> &font_data)
   {
      // Embed font type 1

      struct pfb_segment_header_s {
         char always_128;
         char type;
         unsigned int length;
      };
      enum {
         TYPE_ASCII = 1,
         TYPE_BINARY,
         TYPE_EOF
      };

      char magic_number[2];
      std::string ret;

      memcpy(magic_number, &font_data[0], 2);
      if(magic_number[0] == '\200') {
         // IBM PC format printer font binary

         // FIXME: Maybe the real name can be parsed out of the
         // file
         font_name = "";

         struct pfb_segment_header_s segment_header;
         size_t offset = 0;

         segment_header.type = 0;
         while (segment_header.type != TYPE_EOF) {
            // The two char elements of struct
            // pfb_segment_header_s are most likely aligned to
            // larger than 1 byte boundaries, so copy all the
            // elements individually
            segment_header.always_128 = font_data[offset];
            segment_header.type = font_data[offset + 1];
            memcpy(&segment_header.length, &font_data[offset + 2],
                   sizeof(unsigned int));
            offset += sizeof(unsigned int) + 2;
#ifdef LITTLE_ENDIAN
            segment_header.length =
            bswap_32(segment_header.length);
#endif // LITTLE_ENDIAN
            char *buffer = new char[segment_header.length];

            memcpy(buffer, &font_data[offset],
                   segment_header.length);
            offset += segment_header.length;

            switch(segment_header.type) {
               case TYPE_ASCII:
                  // Simple CR -> LF conversion
                  for (int i = 0;
                       i < (int)(segment_header.length) - 1; i++) {
                     if(buffer[i] == '\r' &&
                        buffer[i + 1] != '\n') {
                        buffer[i] = '\n';
                     }
                  }
                  if (buffer[segment_header.length - 1] == '\r') {
                     buffer[segment_header.length - 1] = '\n';
                  }
                  ret.append(buffer, segment_header.length);
                  break;
               case TYPE_BINARY:
                  append_asciihex(
                                  ret, reinterpret_cast<uint8_t *>(buffer),
                                  segment_header.length);
                  break;
               default:
               {}
            }

            delete [] buffer;
         }

         return ret;
      }
      else if(strncmp(magic_number, "%!", 2) == 0) {
         // Printer font ASCII
         fprintf(stderr, "%s:%d: Printer font ASCII is not "
                 "implemented\n", __FILE__, __LINE__);
         return std::string();
      }

      return std::string();
   }

   std::string font_embed_postscript_t::font_embed_type_2(
                                                          std::string &font_name,
                                                          const std::vector<unsigned char> &font_data)
   {
      // Embed an OpenType CFF (Type 2) file in ASCII85 encoding
      // with the PostScript syntax

      unsigned short cid_encoding_id;
      unsigned int cff_offset;
      unsigned int cff_length;

      if (!parse_otf_cff_header(font_name, cid_encoding_id,
                                cff_offset, cff_length,
                                font_data)) {
         return std::string();
      }

      std::vector<unsigned char> cff;

      cff.resize(cff_length + 10);
      memcpy(&cff[0], "StartData\r", 10);
      memcpy(&cff[10], &font_data[cff_offset], cff_length);

      char linebuf[BUFSIZ];
      std::string ret;

      snprintf(linebuf, BUFSIZ, "%%%%BeginResource: FontSet (%s)\n",
               font_name.c_str());
      ret.append(linebuf);
      ret.append("%%VMusage: 0 0\n");
      ret.append("/FontSetInit /ProcSet findresource begin\n");
      snprintf(linebuf, BUFSIZ, "%%%%BeginData: %u ASCII Lines\n",
               ascii85_line_count(&cff[0], cff_length) + 2);
      ret.append(linebuf);
      snprintf(linebuf, BUFSIZ,
               "/%s %u currentfile /ASCII85Decode filter cvx exec\n",
               font_name.c_str(), cff_length);
      ret.append(linebuf);
      append_ascii85(ret, &cff[0], cff_length + 10);
      ret.append(1, '\n');
      ret.append("%%EndData\n");
      ret.append("%%EndResource\n");

      return ret;
   }

   std::string font_embed_postscript_t::font_embed_type_42(
                                                           std::string &font_name,
                                                           const std::vector<unsigned char> &font_data)
   {
      // Embed an TrueType as Type 42 with the PostScript syntax

      double font_bbox[4];
      std::map<wchar_t, uint16_t> cid_map;
      std::vector<std::string> char_strings;

      if (!parse_ttf_header(font_name, font_bbox, cid_map,
                            char_strings, font_data)) {
         fprintf(stderr, "%s:%d:\n", __FILE__, __LINE__);
         return std::string();
      }

      char linebuf[BUFSIZ];
      std::string ret;

      snprintf(linebuf, BUFSIZ, "%%%%BeginResource: FontSet (%s)\n",
               font_name.c_str());
      ret.append(linebuf);
      ret.append("%%VMusage: 0 0\n");
      ret.append("11 dict begin\n");
      snprintf(linebuf, BUFSIZ, "/FontName /%s def\n",
               font_name.c_str());
      ret.append(linebuf);
      ret.append("/Encoding 256 array\n");
      snprintf(linebuf, BUFSIZ,
               "0 1 255 { 1 index exch /%s put } for\n",
               char_strings[0].c_str());
      ret.append(linebuf);
      for (unsigned int code_point = 0; code_point < 256;
           code_point++) {
         unsigned int glyph_index = cid_map[code_point];

         if (char_strings[glyph_index] != ".notdef" &&
             char_strings[glyph_index] != "") {
            snprintf(linebuf, BUFSIZ, "dup %u /%s put\n",
                     code_point,
                     char_strings[glyph_index].c_str());
            ret.append(linebuf);
         }
      }
      ret.append("readonly def\n");
      ret.append("/PaintType 0 def\n");   // 0 for filled, 2 for stroked
      ret.append("/FontMatrix [1 0 0 1 0 0] def\n");
      snprintf(linebuf, BUFSIZ, "/FontBBox [%f %f %f %f] def\n",
               font_bbox[0], font_bbox[1], font_bbox[2], font_bbox[3]);
      ret.append(linebuf);
      ret.append("/FontType 42 def\n");
      // FIXME: XUID generation using the font data's MD5
      ret.append("/sfnts [\n");

      const size_t block_size = 32262;
      size_t offset = 0;

      while (offset < font_data.size()) {
         const size_t output_length =
         std::min(block_size, font_data.size() - offset);

         ret.append("<\n");
         append_asciihex(ret, &font_data[offset], output_length);
         ret.append(">\n");
         offset += output_length;
      }
      ret.append("] def\n");

      unsigned int char_strings_count = 0;

      for (std::vector<std::string>::const_iterator iterator =
           char_strings.begin();
           iterator < char_strings.end(); iterator++) {
         if (!iterator->empty()) {
            char_strings_count++;
         }
      }

      snprintf(linebuf, BUFSIZ, "/CharStrings %u dict dup begin\n",
               char_strings_count);
      ret.append(linebuf);
      for (unsigned int glyph_index = 0;
           glyph_index < char_strings.size(); glyph_index++) {
         if (!char_strings[glyph_index].empty()) {
            snprintf(linebuf, BUFSIZ, "/%s %u def\n",
                     char_strings[glyph_index].c_str(),
                     glyph_index);
            ret.append(linebuf);
         }
      }
      ret.append("end readonly def\n");
      ret.append("FontName currentdict end definefont pop\n");
      ret.append("%%EndResource\n");

      return ret;
   }
}
<|endoftext|>


<commit_before>/******************************************************************************
 *                   ____     ______   ____     __  __                        *
 *                  /\  _`\  /\  _  \ /\  _`\  /\ \/\ \                       *
 *                  \ \,\L\_\\ \ \L\ \\ \,\L\_\\ \ \_\ \                      *
 *                   \/_\__ \ \ \  __ \\/_\__ \ \ \  _  \                     *
 *                     /\ \L\ \\ \ \/\ \ /\ \L\ \\ \ \ \ \                    *
 *                     \ `\____\\ \_\ \_\\ `\____\\ \_\ \_\                   *
 *                      \/_____/ \/_/\/_/ \/_____/ \/_/\/_/                   *
 *                                                                            *
 *                                                                            *
 * Copyright (c) 2014                                                         *
 * Matthias Vallentin <vallentin (at) icir.org>                               *
 * Dominik Charousset <dominik.charousset (at) haw-hamburg.de>                *
 *                                                                            *
 * Distributed under the Boost Software License, Version 1.0. See             *
 * accompanying file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt  *
\******************************************************************************/

#ifndef SASH_MODE_HPP
#define SASH_MODE_HPP

#include <tuple>
#include <memory>
#include <string>

#include "sash/color.hpp"
#include "sash/command.hpp"

namespace sash {

/// A command-line context with its own commands, history, and prompt.
template<class Backend, class Command>
class mode
{
  mode(mode const&) = delete;
  mode& operator=(mode const&) = delete;

public:
  /// The type for our completion context.
  using completer_type = typename Backend::completer_type;

  /// A callback for CLI completions.
  using completion_cb = typename completer_type::callback_type;

  /// A smart pointer to a command.
  using command_ptr = std::shared_ptr<Command>;

  /// A callback for commands.
  using command_cb = typename Command::callback_type;

  /// Constructs a mode.
  /// @param name The name of the mode.
  /// @param prompt The prompt string.
  /// @param prompt_color The color of *prompt*.
  /// @param history_file The file where to store the mode history.
  mode(std::string name,
       std::string history_file,
       int history_size = 1000,
       bool unique_history = true,
       std::string prompt = ">",
       char const* prompt_color = color::none,
       char const* shell_name = "sash",
       char const* completion_key = "\t")
    : backend_{shell_name, std::move(history_file),
          history_size, unique_history, completion_key},
      root_{std::make_shared<Command>(nullptr, backend_.get_completer(),
                                      std::move(name), std::string{})}
  {
    backend_.set_prompt(std::move(prompt), prompt_color);
  }

  /// Adds a sub-command to this mode.
  /// @param name The name of the command.
  /// @param desc A one-line description of the command.
  /// @returns If successful, a valid pointer to the newly created command.
  command_ptr add(std::string name, std::string desc)
  {
    return root_->add(std::move(name), std::move(desc));
  }

  /// Adds a sub-command with handler to this mode.
  /// @param name The name of the command.
  /// @param desc A one-line description of the command.
  /// @param func A functor to handle the new command.
  /// @returns If successful, a valid pointer to the newly created command.
  template<typename F>
  command_ptr add(std::string name, std::string desc, F func)
  {
    auto ptr = root_->add(std::move(name), std::move(desc));
    if (ptr)
      ptr->on(std::move(func));
    return ptr;
  }

  using cmd_clause = std::tuple<std::string, std::string, command_cb>;

  void add_all(std::vector<cmd_clause> clauses)
  {
    for (auto& clause : clauses)
      add(std::get<0>(clause), std::get<1>(clause), std::get<2>(clause));
  }

  /// Assigns a callback handler for unknown commands.
  /// @param f The function to execute for unknown commands.
  void on_unknown_command(command_cb f)
  {
    root_->on(std::move(f));
  }

  /// Assigns a callback handler for unknown commands.
  /// @param f The function to execute for unknown commands.
  void on_complete(completion_cb f)
  {
    backend_.get_completer()->on_completion(std::move(f));
  }

  /// Registers a completion with this mode.
  /// @param The string to register.
  void add_completion(std::string str)
  {
    backend_.get_completer()->add_completion(std::move(str));
  }

  /// Replaces the completions associated with a set of new ones.
  /// @param completiosn The new completions.
  void replace_completions(std::vector<std::string> completions)
  {
    backend_.get_completer()->replace_completions(std::move(completions));
  }

  /// Execute a command line.
  command_result execute(std::string& err, std::string const& line) const
  {
    return root_->execute(err, line);
  }

  /// Retrieves the name of this mode.
  /// @returns The name of this mode
  std::string const& name() const
  {
    return root_->name();
  }

  /// Retrieves the autogenerated help string for this mode.
  /// @param indent The number of spaces to indent the help text.
  /// @returns The help string for this mode.
  std::string help(size_t indent = 0) const
  {
    return root_->help(indent);
  }

  /// Returns a reference to the CLI backend used by this mode.
  Backend& backend()
  {
    return backend_;
  }

private:
  Backend backend_;
  command_ptr root_;
};

} // namespace sash

#endif // SASH_MODE_HPP
<commit_msg>Work around stupid C++ committee desicision<commit_after>/******************************************************************************
 *                   ____     ______   ____     __  __                        *
 *                  /\  _`\  /\  _  \ /\  _`\  /\ \/\ \                       *
 *                  \ \,\L\_\\ \ \L\ \\ \,\L\_\\ \ \_\ \                      *
 *                   \/_\__ \ \ \  __ \\/_\__ \ \ \  _  \                     *
 *                     /\ \L\ \\ \ \/\ \ /\ \L\ \\ \ \ \ \                    *
 *                     \ `\____\\ \_\ \_\\ `\____\\ \_\ \_\                   *
 *                      \/_____/ \/_/\/_/ \/_____/ \/_/\/_/                   *
 *                                                                            *
 *                                                                            *
 * Copyright (c) 2014                                                         *
 * Matthias Vallentin <vallentin (at) icir.org>                               *
 * Dominik Charousset <dominik.charousset (at) haw-hamburg.de>                *
 *                                                                            *
 * Distributed under the Boost Software License, Version 1.0. See             *
 * accompanying file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt  *
\******************************************************************************/

#ifndef SASH_MODE_HPP
#define SASH_MODE_HPP

#include <tuple>
#include <memory>
#include <string>

#include "sash/color.hpp"
#include "sash/command.hpp"

namespace sash {

/// A command-line context with its own commands, history, and prompt.
template<class Backend, class Command>
class mode
{
  mode(mode const&) = delete;
  mode& operator=(mode const&) = delete;

public:
  /// The type for our completion context.
  using completer_type = typename Backend::completer_type;

  /// A callback for CLI completions.
  using completion_cb = typename completer_type::callback_type;

  /// A smart pointer to a command.
  using command_ptr = std::shared_ptr<Command>;

  /// A callback for commands.
  using command_cb = typename Command::callback_type;

  /// Constructs a mode.
  /// @param name The name of the mode.
  /// @param prompt The prompt string.
  /// @param prompt_color The color of *prompt*.
  /// @param history_file The file where to store the mode history.
  mode(std::string name,
       std::string history_file,
       int history_size = 1000,
       bool unique_history = true,
       std::string prompt = ">",
       char const* prompt_color = color::none,
       char const* shell_name = "sash",
       char const* completion_key = "\t")
    : backend_{shell_name, std::move(history_file),
          history_size, unique_history, completion_key},
      root_{std::make_shared<Command>(nullptr, backend_.get_completer(),
                                      std::move(name), std::string{})}
  {
    backend_.set_prompt(std::move(prompt), prompt_color);
  }

  /// Adds a sub-command to this mode.
  /// @param name The name of the command.
  /// @param desc A one-line description of the command.
  /// @returns If successful, a valid pointer to the newly created command.
  command_ptr add(std::string name, std::string desc)
  {
    return root_->add(std::move(name), std::move(desc));
  }

  /// Adds a sub-command with handler to this mode.
  /// @param name The name of the command.
  /// @param desc A one-line description of the command.
  /// @param func A functor to handle the new command.
  /// @returns If successful, a valid pointer to the newly created command.
  template<typename F>
  command_ptr add(std::string name, std::string desc, F func)
  {
    auto ptr = root_->add(std::move(name), std::move(desc));
    if (ptr)
      ptr->on(std::move(func));
    return ptr;
  }

  // The natural thing to use here would be std::tuple, right?
  // Wrong! The committeee once more delivered an epic failure by
  // making the constructor for std::tuple explicit! Meaning that
  // our preferred syntax add_all({{"a", "b", fun}, ...}) isn't doable.
  // We work around this nonsene by using pairs... At least they don't
  // have explicit constructors.
  struct cmd_clause
  {
    std::string cmd_name;
    std::string cmd_desc;
    command_cb  cmd_fun;
  };

  void add_all(std::vector<cmd_clause> clauses)
  {
    for (auto& clause : clauses)
      add(clause.cmd_name, clause.cmd_desc, clause.cmd_fun);
  }

  /// Assigns a callback handler for unknown commands.
  /// @param f The function to execute for unknown commands.
  void on_unknown_command(command_cb f)
  {
    root_->on(std::move(f));
  }

  /// Assigns a callback handler for unknown commands.
  /// @param f The function to execute for unknown commands.
  void on_complete(completion_cb f)
  {
    backend_.get_completer()->on_completion(std::move(f));
  }

  /// Registers a completion with this mode.
  /// @param The string to register.
  void add_completion(std::string str)
  {
    backend_.get_completer()->add_completion(std::move(str));
  }

  /// Replaces the completions associated with a set of new ones.
  /// @param completiosn The new completions.
  void replace_completions(std::vector<std::string> completions)
  {
    backend_.get_completer()->replace_completions(std::move(completions));
  }

  /// Execute a command line.
  command_result execute(std::string& err, std::string const& line) const
  {
    return root_->execute(err, line);
  }

  /// Retrieves the name of this mode.
  /// @returns The name of this mode
  std::string const& name() const
  {
    return root_->name();
  }

  /// Retrieves the autogenerated help string for this mode.
  /// @param indent The number of spaces to indent the help text.
  /// @returns The help string for this mode.
  std::string help(size_t indent = 0) const
  {
    return root_->help(indent);
  }

  /// Returns a reference to the CLI backend used by this mode.
  Backend& backend()
  {
    return backend_;
  }

private:
  Backend backend_;
  command_ptr root_;
};

} // namespace sash

#endif // SASH_MODE_HPP
<|endoftext|>


<commit_before>// 4.exercise.07.cpp
//
//  Modify the "mini calculator" from exercise 5 to accept (just)
//  single digit numbers written as either digits or spelled out
//
//  Comments:
//      Taking detailed care of input could meake the program extremely
//      complicated. So, the main loop is stopped by forcing it (Ctrl+C)
//      as clearing cin somehow gets rid of end of input (Ctrl+D, Ctrl+Z)
//      and I really have been stuck with this exercise too much time
//      to investigate further.
//      And we cheat, just like in exeercise 5, by using cin.clear().
//      I expand the cheat by using cin.ignore() to discard input after a
//      bad read.

#include "std_lib_facilities.h"

const vector<string> names {"zero",
    "one", "two", "three", "four",
    "five", "six", "seven", "eight",
    "nine"};

int get_number()
{
    string name;
    int number;
    int result {-1};

    if (cin >> number)
        // It's an integer number. Read about size_t below.
        if (number<0 || size_t(number) >= names.size())
            cout << "Operand " << number << " is not a single digit number\n";
        else
            result = number;
    else {
        // Clear cin state to be able to re-read
        cin.clear();
        //It's not an integer so we read it as string
        cin >> name;
        // cheat, cheat, cheat. size_t is an integer unsigned type for "sizes",
        // so I use it here as gcc with -Wall warnings about comparing signed
        // and unsigned integer expressions if I define i as int.
        for (size_t i = 0; i < names.size(); ++i)
            if (names[i] == name) result = i;
        if (result == -1)
            cout << "The name <" << name
                << "> do not correspond to any single digit number.\n";
    }

    return result;
}

int main()
{
    char oper {' '};
    int op_a {0};
    int op_b {0};

    cout << "The Single Digit Calculator ...\n"
        << "Insert two operands (from 0 to 9, on digits or spelled out)"
        << "separated by an operation (+,-,*,/):\n";

    while (true) {
        // I'm not actually proud of the structure of this code.
        // I feel it could have been done better.
        op_a = get_number();
        if (op_a == -1) {
            // Clear error and discard the rest of the input
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
            cout << "Try again:\n";
        }
        else {
            cin >> oper;
            op_b = get_number();
            if (op_b == -1) {
                // Clear error and discard the rest of the input
                cin.clear();
                cin.ignore(numeric_limits<streamsize>::max(), '\n');
                cout << "Try again:\n";
            }
            else {

                switch (oper) {
                    case '+':
                        cout << "The sum of " << op_a << " and " << op_b
                            << " is " << op_a+op_b << '\n';
                        break;;
                    case '-':
                        cout << "The difference of " << op_a << " and " << op_b
                            << " is " << op_a-op_b << '\n';
                        break;;
                    case '*':
                        cout << "The product of " << op_a << " and " << op_b
                            << " is " << op_a*op_b << '\n';
                        break;;
                    case '/':
                        if (op_b == 0)
                            cout << "ERROR: Division by zero\n";
                        else
                            cout << "The division of " << op_a << " and " << op_b
                                << " is " << op_a/op_b << '\n';
                        break;;
                    default:
                        cout << "The operator " << oper << " is not supported!\n";
                        break;;
                }
            }
        }
    }

    return 0;
}
<commit_msg>Small typo on exercise 7 from chapter 4<commit_after>// 4.exercise.07.cpp
//
//  Modify the "mini calculator" from exercise 5 to accept (just)
//  single digit numbers written as either digits or spelled out
//
//  Comments:
//      Taking detailed care of input could meake the program extremely
//      complicated. So, the main loop is stopped by forcing it (Ctrl+C)
//      as clearing cin somehow gets rid of end of input (Ctrl+D, Ctrl+Z)
//      and I really have been stuck with this exercise too much time
//      to investigate further.
//      And we cheat, just like in exeercise 5, by using cin.clear().
//      I expand the cheat by using cin.ignore() to discard input after a
//      bad read.

#include "std_lib_facilities.h"

const vector<string> names {"zero",
    "one", "two", "three", "four",
    "five", "six", "seven", "eight",
    "nine"};

int get_number()
{
    string name;
    int number;
    int result {-1};

    if (cin >> number)
        // It's an integer number. Read about size_t below.
        if (number<0 || size_t(number) >= names.size())
            cout << "Operand " << number << " is not a single digit number\n";
        else
            result = number;
    else {
        // Clear cin state to be able to re-read
        cin.clear();
        //It's not an integer so we read it as string
        cin >> name;
        // cheat, cheat, cheat. size_t is an integer unsigned type for "sizes",
        // so I use it here as gcc with -Wall warnings about comparing signed
        // and unsigned integer expressions if I define i as int.
        for (size_t i = 0; i < names.size(); ++i)
            if (names[i] == name) result = i;
        if (result == -1)
            cout << "The name <" << name
                << "> do not correspond to any single digit number.\n";
    }

    return result;
}

int main()
{
    char oper {' '};
    int op_a {0};
    int op_b {0};

    cout << "The Single Digit Calculator ...\n"
        << "Insert two operands (from 0 to 9, on digits or spelled out) "
        << "separated by an operation (+,-,*,/):\n";

    while (true) {
        // I'm not actually proud of the structure of this code.
        // I feel it could have been done better.
        op_a = get_number();
        if (op_a == -1) {
            // Clear error and discard the rest of the input
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
            cout << "Try again:\n";
        }
        else {
            cin >> oper;
            op_b = get_number();
            if (op_b == -1) {
                // Clear error and discard the rest of the input
                cin.clear();
                cin.ignore(numeric_limits<streamsize>::max(), '\n');
                cout << "Try again:\n";
            }
            else {

                switch (oper) {
                    case '+':
                        cout << "The sum of " << op_a << " and " << op_b
                            << " is " << op_a+op_b << '\n';
                        break;;
                    case '-':
                        cout << "The difference of " << op_a << " and " << op_b
                            << " is " << op_a-op_b << '\n';
                        break;;
                    case '*':
                        cout << "The product of " << op_a << " and " << op_b
                            << " is " << op_a*op_b << '\n';
                        break;;
                    case '/':
                        if (op_b == 0)
                            cout << "ERROR: Division by zero\n";
                        else
                            cout << "The division of " << op_a << " and " << op_b
                                << " is " << op_a/op_b << '\n';
                        break;;
                    default:
                        cout << "The operator " << oper << " is not supported!\n";
                        break;;
                }
            }
        }
    }

    return 0;
}
<|endoftext|>