<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 "MissionCommandTree.h"
#include "FactMetaData.h"
#include "Vehicle.h"
#include "FirmwarePluginManager.h"
#include "QGCApplication.h"
#include "QGroundControlQmlGlobal.h"
#include "MissionCommandUIInfo.h"
#include "MissionCommandList.h"

#include <QQmlEngine>

MissionCommandTree::MissionCommandTree(QGCApplication* app, bool unitTest)
    : QGCTool(app)
    , _unitTest(unitTest)
{
}

void MissionCommandTree::setToolbox(QGCToolbox* toolbox)
{
    QGCTool::setToolbox(toolbox);

#ifdef UNITTEST_BUILD
    if (_unitTest) {
        // Load unit testing tree
        _staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_GENERIC] =           new MissionCommandList(":/json/unittest/MavCmdInfoCommon.json", true, this);
        _staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_FIXED_WING] =        new MissionCommandList(":/json/unittest/MavCmdInfoFixedWing.json", false, this);
        _staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_QUADROTOR] =         new MissionCommandList(":/json/unittest/MavCmdInfoMultiRotor.json", false, this);
        _staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_VTOL_QUADROTOR] =    new MissionCommandList(":/json/unittest/MavCmdInfoVTOL.json", false, this);
        _staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_SUBMARINE] =         new MissionCommandList(":/json/unittest/MavCmdInfoSub.json", false, this);
        _staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_GROUND_ROVER] =      new MissionCommandList(":/json/unittest/MavCmdInfoRover.json", false, this);
    } else {
#endif
        // Load all levels of hierarchy
        foreach (MAV_AUTOPILOT firmwareType, _toolbox->firmwarePluginManager()->knownFirmwareTypes()) {
            FirmwarePlugin* plugin = _toolbox->firmwarePluginManager()->firmwarePluginForAutopilot(firmwareType, MAV_TYPE_QUADROTOR);

            QList<MAV_TYPE> vehicleTypes;
            vehicleTypes << MAV_TYPE_GENERIC << MAV_TYPE_FIXED_WING << MAV_TYPE_QUADROTOR << MAV_TYPE_VTOL_QUADROTOR << MAV_TYPE_GROUND_ROVER << MAV_TYPE_SUBMARINE;

            foreach(MAV_TYPE vehicleType, vehicleTypes) {
                QString overrideFile = plugin->missionCommandOverrides(vehicleType);
                if (!overrideFile.isEmpty()) {
                    _staticCommandTree[firmwareType][vehicleType] = new MissionCommandList(overrideFile, firmwareType == MAV_AUTOPILOT_GENERIC && vehicleType == MAV_TYPE_GENERIC /* baseCommandList */, this);
                }
            }
        }
#ifdef UNITTEST_BUILD
    }
#endif
}

MAV_AUTOPILOT MissionCommandTree::_baseFirmwareType(MAV_AUTOPILOT firmwareType) const
{
    if (qgcApp()->toolbox()->firmwarePluginManager()->knownFirmwareTypes().contains(firmwareType)) {
        return firmwareType;
    } else {
        return MAV_AUTOPILOT_GENERIC;
    }

}

MAV_TYPE MissionCommandTree::_baseVehicleType(MAV_TYPE mavType) const
{
    if (QGCMAVLink::isFixedWing(mavType)) {
        return MAV_TYPE_FIXED_WING;
    } else if (QGCMAVLink::isMultiRotor(mavType)) {
        return MAV_TYPE_QUADROTOR;
    } else if (QGCMAVLink::isVTOL(mavType)) {
        return MAV_TYPE_VTOL_QUADROTOR;
    } else if (QGCMAVLink::isRover(mavType)) {
        return MAV_TYPE_GROUND_ROVER;
    } else if (QGCMAVLink::isSub(mavType)) {
        return MAV_TYPE_SUBMARINE;
    } else {
        return MAV_TYPE_GENERIC;
    }
}

/// Add the next level of the hierarchy to a collapsed tree.
///     @param vehicle Collapsed tree is for this vehicle
///     @param cmdList List of mission commands to collapse into ui info
///     @param collapsedTree Tree we are collapsing into
void MissionCommandTree::_collapseHierarchy(Vehicle*                                vehicle,
                                            const MissionCommandList*               cmdList,
                                            QMap<MAV_CMD, MissionCommandUIInfo*>&   collapsedTree)
{
    MAV_AUTOPILOT   baseFirmwareType;
    MAV_TYPE        baseVehicleType;

    _baseVehicleInfo(vehicle, baseFirmwareType, baseVehicleType);

    foreach (MAV_CMD command, cmdList->commandIds()) {
        MissionCommandUIInfo* uiInfo = cmdList->getUIInfo(command);
        if (uiInfo) {
            if (collapsedTree.contains(command)) {
                collapsedTree[command]->_overrideInfo(uiInfo);
            } else {
                collapsedTree[command] = new MissionCommandUIInfo(*uiInfo);
            }
        }
    }
}

void MissionCommandTree::_buildAvailableCommands(Vehicle* vehicle)
{
    MAV_AUTOPILOT   baseFirmwareType;
    MAV_TYPE        baseVehicleType;

    _baseVehicleInfo(vehicle, baseFirmwareType, baseVehicleType);

    if (_availableCommands.contains(baseFirmwareType) &&
            _availableCommands[baseFirmwareType].contains(baseVehicleType)) {
        // Available commands list already built
        return;
    }

    // Build new available commands list

    QMap<MAV_CMD, MissionCommandUIInfo*>& collapsedTree = _availableCommands[baseFirmwareType][baseVehicleType];

    // Any Firmware, Any Vehicle
    _collapseHierarchy(vehicle, _staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_GENERIC], collapsedTree);

    // Any Firmware, Specific Vehicle
    if (baseVehicleType != MAV_TYPE_GENERIC) {
        _collapseHierarchy(vehicle, _staticCommandTree[MAV_AUTOPILOT_GENERIC][baseVehicleType], collapsedTree);
    }

    // Known Firmware, Any Vehicle
    if (baseFirmwareType != MAV_AUTOPILOT_GENERIC) {
        _collapseHierarchy(vehicle, _staticCommandTree[baseFirmwareType][MAV_TYPE_GENERIC], collapsedTree);

        // Known Firmware, Specific Vehicle
        if (baseVehicleType != MAV_TYPE_GENERIC) {
            _collapseHierarchy(vehicle, _staticCommandTree[baseFirmwareType][baseVehicleType], collapsedTree);
        }
    }

    // Build category list
    QMapIterator<MAV_CMD, MissionCommandUIInfo*> iter(collapsedTree);
    while (iter.hasNext()) {
        iter.next();
        QString newCategory = iter.value()->category();
        if (!_availableCategories[baseFirmwareType][baseVehicleType].contains(newCategory)) {
            _availableCategories[baseFirmwareType][baseVehicleType].append(newCategory);
        }
    }
}

QStringList MissionCommandTree::_availableCategoriesForVehicle(Vehicle* vehicle)
{
    MAV_AUTOPILOT   baseFirmwareType;
    MAV_TYPE        baseVehicleType;

    _baseVehicleInfo(vehicle, baseFirmwareType, baseVehicleType);
    _buildAvailableCommands(vehicle);

    return _availableCategories[baseFirmwareType][baseVehicleType];
}

QString MissionCommandTree::friendlyName(MAV_CMD command)
{
    MissionCommandList *    commandList =   _staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_GENERIC];
    MissionCommandUIInfo*   uiInfo =        commandList->getUIInfo(command);

    if (uiInfo) {
        return uiInfo->friendlyName();
    } else {
        return QString("MAV_CMD(%1)").arg((int)command);
    }
}

QString MissionCommandTree::rawName(MAV_CMD command)
{
    MissionCommandList *    commandList =   _staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_GENERIC];
    MissionCommandUIInfo*   uiInfo =        commandList->getUIInfo(command);

    if (uiInfo) {
        return uiInfo->rawName();
    } else {
        return QString("MAV_CMD(%1)").arg((int)command);
    }
}

const QList<MAV_CMD>& MissionCommandTree::allCommandIds(void) const
{
    return _staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_GENERIC]->commandIds();
}

const MissionCommandUIInfo* MissionCommandTree::getUIInfo(Vehicle* vehicle, MAV_CMD command)
{
    MAV_AUTOPILOT   baseFirmwareType;
    MAV_TYPE        baseVehicleType;

    _baseVehicleInfo(vehicle, baseFirmwareType, baseVehicleType);
    _buildAvailableCommands(vehicle);

    const QMap<MAV_CMD, MissionCommandUIInfo*>& infoMap = _availableCommands[baseFirmwareType][baseVehicleType];
    if (infoMap.contains(command)) {
        return infoMap[command];
    } else {
        return NULL;
    }
}

QVariantList MissionCommandTree::getCommandsForCategory(Vehicle* vehicle, const QString& category)
{
    MAV_AUTOPILOT   baseFirmwareType;
    MAV_TYPE        baseVehicleType;

    _baseVehicleInfo(vehicle, baseFirmwareType, baseVehicleType);
    _buildAvailableCommands(vehicle);

    QVariantList list;
    QMap<MAV_CMD, MissionCommandUIInfo*> commandMap = _availableCommands[baseFirmwareType][baseVehicleType];
    foreach (MAV_CMD command, commandMap.keys()) {
        MissionCommandUIInfo* uiInfo = commandMap[command];
        if (uiInfo->category() == category) {
            list.append(QVariant::fromValue(uiInfo));
        }
    }

    return list;
}

void MissionCommandTree::_baseVehicleInfo(Vehicle* vehicle, MAV_AUTOPILOT& baseFirmwareType, MAV_TYPE& baseVehicleType) const
{
    if (vehicle) {
        baseFirmwareType = _baseFirmwareType(vehicle->firmwareType());
        baseVehicleType = _baseVehicleType(vehicle->vehicleType());
    } else {
        // No Vehicle means offline editing
        baseFirmwareType = _baseFirmwareType((MAV_AUTOPILOT)QGroundControlQmlGlobal::offlineEditingFirmwareType()->rawValue().toInt());
        baseVehicleType = _baseVehicleType((MAV_TYPE)QGroundControlQmlGlobal::offlineEditingVehicleType()->rawValue().toInt());
    }
}
<commit_msg>Only add supported commands<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 "MissionCommandTree.h"
#include "FactMetaData.h"
#include "Vehicle.h"
#include "FirmwarePluginManager.h"
#include "QGCApplication.h"
#include "QGroundControlQmlGlobal.h"
#include "MissionCommandUIInfo.h"
#include "MissionCommandList.h"

#include <QQmlEngine>

MissionCommandTree::MissionCommandTree(QGCApplication* app, bool unitTest)
    : QGCTool(app)
    , _unitTest(unitTest)
{
}

void MissionCommandTree::setToolbox(QGCToolbox* toolbox)
{
    QGCTool::setToolbox(toolbox);

#ifdef UNITTEST_BUILD
    if (_unitTest) {
        // Load unit testing tree
        _staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_GENERIC] =           new MissionCommandList(":/json/unittest/MavCmdInfoCommon.json", true, this);
        _staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_FIXED_WING] =        new MissionCommandList(":/json/unittest/MavCmdInfoFixedWing.json", false, this);
        _staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_QUADROTOR] =         new MissionCommandList(":/json/unittest/MavCmdInfoMultiRotor.json", false, this);
        _staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_VTOL_QUADROTOR] =    new MissionCommandList(":/json/unittest/MavCmdInfoVTOL.json", false, this);
        _staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_SUBMARINE] =         new MissionCommandList(":/json/unittest/MavCmdInfoSub.json", false, this);
        _staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_GROUND_ROVER] =      new MissionCommandList(":/json/unittest/MavCmdInfoRover.json", false, this);
    } else {
#endif
        // Load all levels of hierarchy
        foreach (MAV_AUTOPILOT firmwareType, _toolbox->firmwarePluginManager()->knownFirmwareTypes()) {
            FirmwarePlugin* plugin = _toolbox->firmwarePluginManager()->firmwarePluginForAutopilot(firmwareType, MAV_TYPE_QUADROTOR);

            QList<MAV_TYPE> vehicleTypes;
            vehicleTypes << MAV_TYPE_GENERIC << MAV_TYPE_FIXED_WING << MAV_TYPE_QUADROTOR << MAV_TYPE_VTOL_QUADROTOR << MAV_TYPE_GROUND_ROVER << MAV_TYPE_SUBMARINE;

            foreach(MAV_TYPE vehicleType, vehicleTypes) {
                QString overrideFile = plugin->missionCommandOverrides(vehicleType);
                if (!overrideFile.isEmpty()) {
                    _staticCommandTree[firmwareType][vehicleType] = new MissionCommandList(overrideFile, firmwareType == MAV_AUTOPILOT_GENERIC && vehicleType == MAV_TYPE_GENERIC /* baseCommandList */, this);
                }
            }
        }
#ifdef UNITTEST_BUILD
    }
#endif
}

MAV_AUTOPILOT MissionCommandTree::_baseFirmwareType(MAV_AUTOPILOT firmwareType) const
{
    if (qgcApp()->toolbox()->firmwarePluginManager()->knownFirmwareTypes().contains(firmwareType)) {
        return firmwareType;
    } else {
        return MAV_AUTOPILOT_GENERIC;
    }

}

MAV_TYPE MissionCommandTree::_baseVehicleType(MAV_TYPE mavType) const
{
    if (QGCMAVLink::isFixedWing(mavType)) {
        return MAV_TYPE_FIXED_WING;
    } else if (QGCMAVLink::isMultiRotor(mavType)) {
        return MAV_TYPE_QUADROTOR;
    } else if (QGCMAVLink::isVTOL(mavType)) {
        return MAV_TYPE_VTOL_QUADROTOR;
    } else if (QGCMAVLink::isRover(mavType)) {
        return MAV_TYPE_GROUND_ROVER;
    } else if (QGCMAVLink::isSub(mavType)) {
        return MAV_TYPE_SUBMARINE;
    } else {
        return MAV_TYPE_GENERIC;
    }
}

/// Add the next level of the hierarchy to a collapsed tree.
///     @param vehicle Collapsed tree is for this vehicle
///     @param cmdList List of mission commands to collapse into ui info
///     @param collapsedTree Tree we are collapsing into
void MissionCommandTree::_collapseHierarchy(Vehicle*                                vehicle,
                                            const MissionCommandList*               cmdList,
                                            QMap<MAV_CMD, MissionCommandUIInfo*>&   collapsedTree)
{
    MAV_AUTOPILOT   baseFirmwareType;
    MAV_TYPE        baseVehicleType;

    _baseVehicleInfo(vehicle, baseFirmwareType, baseVehicleType);

    foreach (MAV_CMD command, cmdList->commandIds()) {
        // Only add supported command to tree (MAV_CMD_NAV_LAST is used for planned home position)
        if (!vehicle->firmwarePlugin()->supportedMissionCommands().contains(command) && command != MAV_CMD_NAV_LAST) {
            continue;
        }

        MissionCommandUIInfo* uiInfo = cmdList->getUIInfo(command);
        if (uiInfo) {
            if (collapsedTree.contains(command)) {
                collapsedTree[command]->_overrideInfo(uiInfo);
            } else {
                collapsedTree[command] = new MissionCommandUIInfo(*uiInfo);
            }
        }
    }
}

void MissionCommandTree::_buildAvailableCommands(Vehicle* vehicle)
{
    MAV_AUTOPILOT   baseFirmwareType;
    MAV_TYPE        baseVehicleType;

    _baseVehicleInfo(vehicle, baseFirmwareType, baseVehicleType);

    if (_availableCommands.contains(baseFirmwareType) &&
            _availableCommands[baseFirmwareType].contains(baseVehicleType)) {
        // Available commands list already built
        return;
    }

    // Build new available commands list

    QMap<MAV_CMD, MissionCommandUIInfo*>& collapsedTree = _availableCommands[baseFirmwareType][baseVehicleType];

    // Any Firmware, Any Vehicle
    _collapseHierarchy(vehicle, _staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_GENERIC], collapsedTree);

    // Any Firmware, Specific Vehicle
    if (baseVehicleType != MAV_TYPE_GENERIC) {
        _collapseHierarchy(vehicle, _staticCommandTree[MAV_AUTOPILOT_GENERIC][baseVehicleType], collapsedTree);
    }

    // Known Firmware, Any Vehicle
    if (baseFirmwareType != MAV_AUTOPILOT_GENERIC) {
        _collapseHierarchy(vehicle, _staticCommandTree[baseFirmwareType][MAV_TYPE_GENERIC], collapsedTree);

        // Known Firmware, Specific Vehicle
        if (baseVehicleType != MAV_TYPE_GENERIC) {
            _collapseHierarchy(vehicle, _staticCommandTree[baseFirmwareType][baseVehicleType], collapsedTree);
        }
    }

    // Build category list
    QMapIterator<MAV_CMD, MissionCommandUIInfo*> iter(collapsedTree);
    while (iter.hasNext()) {
        iter.next();
        QString newCategory = iter.value()->category();
        if (!_availableCategories[baseFirmwareType][baseVehicleType].contains(newCategory)) {
            _availableCategories[baseFirmwareType][baseVehicleType].append(newCategory);
        }
    }
}

QStringList MissionCommandTree::_availableCategoriesForVehicle(Vehicle* vehicle)
{
    MAV_AUTOPILOT   baseFirmwareType;
    MAV_TYPE        baseVehicleType;

    _baseVehicleInfo(vehicle, baseFirmwareType, baseVehicleType);
    _buildAvailableCommands(vehicle);

    return _availableCategories[baseFirmwareType][baseVehicleType];
}

QString MissionCommandTree::friendlyName(MAV_CMD command)
{
    MissionCommandList *    commandList =   _staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_GENERIC];
    MissionCommandUIInfo*   uiInfo =        commandList->getUIInfo(command);

    if (uiInfo) {
        return uiInfo->friendlyName();
    } else {
        return QString("MAV_CMD(%1)").arg((int)command);
    }
}

QString MissionCommandTree::rawName(MAV_CMD command)
{
    MissionCommandList *    commandList =   _staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_GENERIC];
    MissionCommandUIInfo*   uiInfo =        commandList->getUIInfo(command);

    if (uiInfo) {
        return uiInfo->rawName();
    } else {
        return QString("MAV_CMD(%1)").arg((int)command);
    }
}

const QList<MAV_CMD>& MissionCommandTree::allCommandIds(void) const
{
    return _staticCommandTree[MAV_AUTOPILOT_GENERIC][MAV_TYPE_GENERIC]->commandIds();
}

const MissionCommandUIInfo* MissionCommandTree::getUIInfo(Vehicle* vehicle, MAV_CMD command)
{
    MAV_AUTOPILOT   baseFirmwareType;
    MAV_TYPE        baseVehicleType;

    _baseVehicleInfo(vehicle, baseFirmwareType, baseVehicleType);
    _buildAvailableCommands(vehicle);

    const QMap<MAV_CMD, MissionCommandUIInfo*>& infoMap = _availableCommands[baseFirmwareType][baseVehicleType];
    if (infoMap.contains(command)) {
        return infoMap[command];
    } else {
        return NULL;
    }
}

QVariantList MissionCommandTree::getCommandsForCategory(Vehicle* vehicle, const QString& category)
{
    MAV_AUTOPILOT   baseFirmwareType;
    MAV_TYPE        baseVehicleType;

    _baseVehicleInfo(vehicle, baseFirmwareType, baseVehicleType);
    _buildAvailableCommands(vehicle);

    QVariantList list;
    QMap<MAV_CMD, MissionCommandUIInfo*> commandMap = _availableCommands[baseFirmwareType][baseVehicleType];
    foreach (MAV_CMD command, commandMap.keys()) {
        MissionCommandUIInfo* uiInfo = commandMap[command];
        if (uiInfo->category() == category) {
            list.append(QVariant::fromValue(uiInfo));
        }
    }

    return list;
}

void MissionCommandTree::_baseVehicleInfo(Vehicle* vehicle, MAV_AUTOPILOT& baseFirmwareType, MAV_TYPE& baseVehicleType) const
{
    if (vehicle) {
        baseFirmwareType = _baseFirmwareType(vehicle->firmwareType());
        baseVehicleType = _baseVehicleType(vehicle->vehicleType());
    } else {
        // No Vehicle means offline editing
        baseFirmwareType = _baseFirmwareType((MAV_AUTOPILOT)QGroundControlQmlGlobal::offlineEditingFirmwareType()->rawValue().toInt());
        baseVehicleType = _baseVehicleType((MAV_TYPE)QGroundControlQmlGlobal::offlineEditingVehicleType()->rawValue().toInt());
    }
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2015, 2016, 2017, 2018, Intel Corporation
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in
 *       the documentation and/or other materials provided with the
 *       distribution.
 *
 *     * Neither the name of Intel Corporation nor the names of its
 *       contributors may be used to endorse or promote products derived
 *       from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY LOG OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef APPLICATIONIO_HPP_INCLUDE
#define APPLICATIONIO_HPP_INCLUDE

#include <cstdint>
#include <set>
#include <string>
#include <memory>
#include <vector>
#include <map>
#include <list>

#include "geopm_message.h"

namespace geopm
{
    class Comm;

    class IApplicationIO
    {
        public:
            IApplicationIO() = default;
            virtual ~IApplicationIO() = default;
            /// @brief Connect to the application via
            ///        shared memory.
            virtual void connect(void) = 0;
            /// @brief Returns true if the application has indicated
            ///        it is shutting down.
            virtual bool do_shutdown(void) const = 0;
            /// @brief Returns the path to the report file.
            virtual std::string report_name(void) const = 0;
            /// @brief Returns the profile name to be used in the
            ///        report.
            virtual std::string profile_name(void) const = 0;
            /// @brief Returns the set of region names recorded by the
            ///        application.
            virtual std::set<std::string> region_name_set(void) const = 0;
            /// @brief Returns the total runtime for a region.
            /// @param [in] region_id The region ID.
            virtual double total_region_runtime(uint64_t region_id) const = 0;
            /// @brief Returns the total time spent in MPI for a
            ///        region.
            /// @param [in] region_id The region ID.
            virtual double total_region_mpi_runtime(uint64_t region_id) const = 0;
            /// @brief Returns the total application runtime.
            virtual double total_app_runtime(void) const = 0;
            /// @brief Returns the total application package energy.
            virtual double total_app_energy_pkg(void) const = 0;
            /// @brief Returns the total application dram energy.
            virtual double total_app_energy_dram(void) const = 0;
            /// @brief Returns the total time spent in MPI for the
            ///        application.
            virtual double total_app_mpi_runtime(void) const = 0;
            /// @brief Returns the total time spent in ignored regions
            ///        for the application after the first call to epoch.
            virtual double total_epoch_ignore_runtime(void) const = 0;
            /// @brief Returns the total runtime after the first epoch
            ///        call.
            virtual double total_epoch_runtime(void) const = 0;
            /// @brief Returns the total time spent in MPI after the
            ///        first epoch call.
            virtual double total_epoch_mpi_runtime(void) const = 0;
            /// @brief Returns the total package energy since the
            ///        first epoch call.
            virtual double total_epoch_energy_pkg(void) const = 0;
            /// @brief Returns the total dram energy since the
            ///        first epoch call.
            virtual double total_epoch_energy_dram(void) const = 0;
            /// @brief Returns the total number of times a region was
            ///        entered and exited.
            /// @param [in] region_id The region ID.
            virtual int total_count(uint64_t region_id) const = 0;
            /// @brief Check for updates from the application and
            ///        adjust totals accordingly.
            /// @param [in] comm Shared pointer to the comm used by
            ///        the Controller.
            virtual void update(std::shared_ptr<Comm> comm) = 0;
            /// @brief Returns the list of all regions entered or
            ///        exited since the last call to
            ///        clear_region_info().
            virtual std::list<geopm_region_info_s> region_info(void) const = 0;
            /// @brief Resets the internal list of region entries and
            ///        exits.
            virtual void clear_region_info(void) = 0;
            /// @brief Signal to the application that the Controller
            ///        is ready to begin receiving samples.
            virtual void controller_ready(void) = 0;
            /// @brief Signal to the application that the Controller
            ///        has failed critically.
            virtual void abort(void) = 0;
    };

    class IProfileSampler;
    class IEpochRuntimeRegulator;
    class IKprofileIOSample;
    class IPlatformIO;
    class IPlatformTopo;

    class ApplicationIO : public IApplicationIO
    {
        public:
            ApplicationIO(const std::string &shm_key);
            ApplicationIO(const std::string &shm_key,
                          std::unique_ptr<IProfileSampler> sampler,
                          std::shared_ptr<IKprofileIOSample> pio_sample,
                          std::unique_ptr<IEpochRuntimeRegulator>,
                          IPlatformIO &platform_io,
                          IPlatformTopo &platform_topo);
            virtual ~ApplicationIO();
            void connect(void) override;
            bool do_shutdown(void) const override;
            std::string report_name(void) const override;
            std::string profile_name(void) const override;
            std::set<std::string> region_name_set(void) const override;
            double total_region_runtime(uint64_t region_id) const override;
            double total_region_mpi_runtime(uint64_t region_id) const override;
            double total_app_runtime(void) const override;
            double total_app_energy_pkg(void) const override;
            double total_app_energy_dram(void) const override;
            double total_app_mpi_runtime(void) const override;
            double total_epoch_ignore_runtime(void) const override;
            double total_epoch_runtime(void) const override;
            double total_epoch_mpi_runtime(void) const override;
            double total_epoch_energy_pkg(void) const override;
            double total_epoch_energy_dram(void) const override;
            int total_count(uint64_t region_id) const override;
            void update(std::shared_ptr<Comm> comm) override;
            std::list<geopm_region_info_s> region_info(void) const override;
            void clear_region_info(void) override;
            void controller_ready(void) override;
            void abort(void) override;
        private:
            static constexpr size_t M_SHMEM_REGION_SIZE = 12288;

            double current_energy_pkg(void) const;
            double current_energy_dram(void) const;

            std::unique_ptr<IProfileSampler> m_sampler;
            std::shared_ptr<IKprofileIOSample> m_profile_io_sample;
            std::vector<std::pair<uint64_t, struct geopm_prof_message_s> > m_prof_sample;
            IPlatformIO &m_platform_io;
            IPlatformTopo &m_platform_topo;
            std::vector<uint64_t> m_region_id;
            // Per rank vector counting number of entries into MPI.
            std::vector<uint64_t> m_num_mpi_enter;
            std::vector<bool> m_is_epoch_changed;
            bool m_is_connected;
            int m_rank_per_node;
            std::unique_ptr<IEpochRuntimeRegulator> m_epoch_regulator;
            double m_start_energy_pkg;
            double m_start_energy_dram;
    };
}

#endif
<commit_msg>Increase shmem table size to 2MB per rank.<commit_after>/*
 * Copyright (c) 2015, 2016, 2017, 2018, Intel Corporation
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in
 *       the documentation and/or other materials provided with the
 *       distribution.
 *
 *     * Neither the name of Intel Corporation nor the names of its
 *       contributors may be used to endorse or promote products derived
 *       from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY LOG OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef APPLICATIONIO_HPP_INCLUDE
#define APPLICATIONIO_HPP_INCLUDE

#include <cstdint>
#include <set>
#include <string>
#include <memory>
#include <vector>
#include <map>
#include <list>

#include "geopm_message.h"

namespace geopm
{
    class Comm;

    class IApplicationIO
    {
        public:
            IApplicationIO() = default;
            virtual ~IApplicationIO() = default;
            /// @brief Connect to the application via
            ///        shared memory.
            virtual void connect(void) = 0;
            /// @brief Returns true if the application has indicated
            ///        it is shutting down.
            virtual bool do_shutdown(void) const = 0;
            /// @brief Returns the path to the report file.
            virtual std::string report_name(void) const = 0;
            /// @brief Returns the profile name to be used in the
            ///        report.
            virtual std::string profile_name(void) const = 0;
            /// @brief Returns the set of region names recorded by the
            ///        application.
            virtual std::set<std::string> region_name_set(void) const = 0;
            /// @brief Returns the total runtime for a region.
            /// @param [in] region_id The region ID.
            virtual double total_region_runtime(uint64_t region_id) const = 0;
            /// @brief Returns the total time spent in MPI for a
            ///        region.
            /// @param [in] region_id The region ID.
            virtual double total_region_mpi_runtime(uint64_t region_id) const = 0;
            /// @brief Returns the total application runtime.
            virtual double total_app_runtime(void) const = 0;
            /// @brief Returns the total application package energy.
            virtual double total_app_energy_pkg(void) const = 0;
            /// @brief Returns the total application dram energy.
            virtual double total_app_energy_dram(void) const = 0;
            /// @brief Returns the total time spent in MPI for the
            ///        application.
            virtual double total_app_mpi_runtime(void) const = 0;
            /// @brief Returns the total time spent in ignored regions
            ///        for the application after the first call to epoch.
            virtual double total_epoch_ignore_runtime(void) const = 0;
            /// @brief Returns the total runtime after the first epoch
            ///        call.
            virtual double total_epoch_runtime(void) const = 0;
            /// @brief Returns the total time spent in MPI after the
            ///        first epoch call.
            virtual double total_epoch_mpi_runtime(void) const = 0;
            /// @brief Returns the total package energy since the
            ///        first epoch call.
            virtual double total_epoch_energy_pkg(void) const = 0;
            /// @brief Returns the total dram energy since the
            ///        first epoch call.
            virtual double total_epoch_energy_dram(void) const = 0;
            /// @brief Returns the total number of times a region was
            ///        entered and exited.
            /// @param [in] region_id The region ID.
            virtual int total_count(uint64_t region_id) const = 0;
            /// @brief Check for updates from the application and
            ///        adjust totals accordingly.
            /// @param [in] comm Shared pointer to the comm used by
            ///        the Controller.
            virtual void update(std::shared_ptr<Comm> comm) = 0;
            /// @brief Returns the list of all regions entered or
            ///        exited since the last call to
            ///        clear_region_info().
            virtual std::list<geopm_region_info_s> region_info(void) const = 0;
            /// @brief Resets the internal list of region entries and
            ///        exits.
            virtual void clear_region_info(void) = 0;
            /// @brief Signal to the application that the Controller
            ///        is ready to begin receiving samples.
            virtual void controller_ready(void) = 0;
            /// @brief Signal to the application that the Controller
            ///        has failed critically.
            virtual void abort(void) = 0;
    };

    class IProfileSampler;
    class IEpochRuntimeRegulator;
    class IKprofileIOSample;
    class IPlatformIO;
    class IPlatformTopo;

    class ApplicationIO : public IApplicationIO
    {
        public:
            ApplicationIO(const std::string &shm_key);
            ApplicationIO(const std::string &shm_key,
                          std::unique_ptr<IProfileSampler> sampler,
                          std::shared_ptr<IKprofileIOSample> pio_sample,
                          std::unique_ptr<IEpochRuntimeRegulator>,
                          IPlatformIO &platform_io,
                          IPlatformTopo &platform_topo);
            virtual ~ApplicationIO();
            void connect(void) override;
            bool do_shutdown(void) const override;
            std::string report_name(void) const override;
            std::string profile_name(void) const override;
            std::set<std::string> region_name_set(void) const override;
            double total_region_runtime(uint64_t region_id) const override;
            double total_region_mpi_runtime(uint64_t region_id) const override;
            double total_app_runtime(void) const override;
            double total_app_energy_pkg(void) const override;
            double total_app_energy_dram(void) const override;
            double total_app_mpi_runtime(void) const override;
            double total_epoch_ignore_runtime(void) const override;
            double total_epoch_runtime(void) const override;
            double total_epoch_mpi_runtime(void) const override;
            double total_epoch_energy_pkg(void) const override;
            double total_epoch_energy_dram(void) const override;
            int total_count(uint64_t region_id) const override;
            void update(std::shared_ptr<Comm> comm) override;
            std::list<geopm_region_info_s> region_info(void) const override;
            void clear_region_info(void) override;
            void controller_ready(void) override;
            void abort(void) override;
        private:
            static constexpr size_t M_SHMEM_REGION_SIZE = 2*1024*1024;

            double current_energy_pkg(void) const;
            double current_energy_dram(void) const;

            std::unique_ptr<IProfileSampler> m_sampler;
            std::shared_ptr<IKprofileIOSample> m_profile_io_sample;
            std::vector<std::pair<uint64_t, struct geopm_prof_message_s> > m_prof_sample;
            IPlatformIO &m_platform_io;
            IPlatformTopo &m_platform_topo;
            std::vector<uint64_t> m_region_id;
            // Per rank vector counting number of entries into MPI.
            std::vector<uint64_t> m_num_mpi_enter;
            std::vector<bool> m_is_epoch_changed;
            bool m_is_connected;
            int m_rank_per_node;
            std::unique_ptr<IEpochRuntimeRegulator> m_epoch_regulator;
            double m_start_energy_pkg;
            double m_start_energy_dram;
    };
}

#endif
<|endoftext|>


<commit_before>/*
***************************************
*   Asylum Project @ 2013-12-09
***************************************
*/

#ifndef __ASYLUM_HPP__
#define __ASYLUM_HPP__

#include "defs.h"

/* System Filter */
#if !defined(_CR_SYS32_) && \
    !defined(_CR_SYS64_)
    #error "asylum.hpp: system not supported!"
#endif
#if !defined(_CR_CC_MSC_) && \
    !defined(_CR_CC_GCC_)
    #error "asylum.hpp: compiler not supported!"
#endif
#if !defined(_CR_OS_UNIX_) && \
    !defined(_CR_OS_WIN32_) && \
    !defined(_CR_OS_WIN64_)
    #error "asylum.hpp: os type not supported!"
#endif

/* Import CrHack Library */
#ifndef ASY_NO_CRHACK
    #ifndef _CR_NO_PRAGMA_LIB_
        #ifndef ASY_USE_STATIC
            #pragma comment (lib, "CrH_CORE.lib")
        #else
            #pragma comment (lib, "COREs.lib")
        #endif
    #endif
#else
    #include <stdlib.h>
    #include <string.h>
    /* ======================================= */
    cr_inline void_t mem_free (const void_t* ptr)
    {
        ::free((void*)ptr);
    }

    #if defined(_CR_NO_STDC_)
        #define mem_set     ::memset
        #define mem_cpy     ::memcpy
        #define mem_cmp     ::memcmp
        #define mem_mov     ::memmove
    #endif
    #define mem_malloc      ::malloc
    #define mem_calloc      ::calloc
    #define mem_malloc32    ::malloc
    #define mem_calloc32    ::calloc
    #define mem_realloc     ::realloc

#ifndef _CR_SYS32_
    #define mem_malloc64    ::malloc
    #define mem_calloc64    ::calloc
#else
    /* ====================================== */
    cr_inline void_t* mem_malloc64 (int64u size)
    {
        if (size > CR_ULL(0xFFFFFFFF))
            return (NULL);
        return (mem_malloc32((int32u)size));
    }

    /* ================================================== */
    cr_inline void_t* mem_calloc64 (int64u num, size_t size)
    {
        if (num > CR_ULL(0xFFFFFFFF))
            return (NULL);
        return (mem_calloc32((int32u)num, size));
    }
#endif  /* !_CR_SYS32_ */
#endif  /* !ASY_NO_CRHACK */

#include "crhack.h"

/* Include */
#if defined(_CR_CC_MSC_)
    #include <intrin.h>
    typedef dist_t  ssize_t;
#endif
#if defined(_CR_OS_MSWIN_)
    #include <process.h>
    #include <windows.h>
#else
    #include <time.h>
    #include <errno.h>
    #include <sched.h>
    #include <pthread.h>
#endif

/* BASIC STUFF */
#include "basic/basic.hpp"
#include "basic/defer.hpp"
#include "basic/safer.hpp"

/* CPU STUFF */
#include "cpu/thread.hpp"
#include "cpu/atomic.hpp"
#include "cpu/crisec.hpp"
#include "cpu/events.hpp"
#include "cpu/exlock.hpp"
#include "cpu/mtlock.hpp"
#include "cpu/nolock.hpp"
#include "cpu/rwlock.hpp"
#include "cpu/splock.hpp"
#include "cpu/doonce.hpp"
#include "cpu/mtpool.hpp"

/* CrHack C++ Wrapper */
#include "crhack/ascall.hpp"
#include "crhack/iports.hpp"
#if defined(ASY_USE_GDI)
    #include "gfx2/gdiwin.h"
    #include "crhack/gfx2_gdi.hpp"
#endif
#if defined(ASY_USE_DX8)
    #include "gfx2/dx8win.h"
    #include "crhack/gfx2_dx8.hpp"
#endif
#if defined(ASY_USE_DX9)
    #include "gfx2/dx9win.h"
    #include "crhack/gfx2_dx9.hpp"
#endif

/* Yet Another Wheel */
#include "yaw/array.hpp"
#include "yaw/bring.hpp"
#include "yaw/list2.hpp"
#include "yaw/map2d.hpp"
#include "yaw/map_a.hpp"
#include "yaw/map_l.hpp"
#include "yaw/oring.hpp"
#include "yaw/table.hpp"
#include "yaw/tree_a.hpp"
#include "yaw/tree_l.hpp"
#include "yaw/map_acs.hpp"

/* Misaka Network */

/* Asylum3D */
#include "draw3d/asylum3d.hpp"
#if defined(ASY_USE_DX9)
    #include "draw3d/crh3d9/crh3d9_main.hpp"
    #include "draw3d/crh3d9/crh3d9_shader.hpp"
    #include "draw3d/crh3d9/crh3d9_texture.hpp"
    #include "draw3d/crh3d9/crh3d9_graph.hpp"
    #ifndef ASY_USE_STATIC
        #pragma comment (lib, "CrH_GFX3.lib")
    #else
        #pragma comment (lib, "GFX3s.lib")
    #endif
#endif

#endif  /* __ASYLUM_HPP__ */
<commit_msg>Asylum: 修正编译错误<commit_after>/*
***************************************
*   Asylum Project @ 2013-12-09
***************************************
*/

#ifndef __ASYLUM_HPP__
#define __ASYLUM_HPP__

#include "defs.h"

/* System Filter */
#if !defined(_CR_SYS32_) && \
    !defined(_CR_SYS64_)
    #error "asylum.hpp: system not supported!"
#endif
#if !defined(_CR_CC_MSC_) && \
    !defined(_CR_CC_GCC_)
    #error "asylum.hpp: compiler not supported!"
#endif
#if !defined(_CR_OS_UNIX_) && \
    !defined(_CR_OS_WIN32_) && \
    !defined(_CR_OS_WIN64_)
    #error "asylum.hpp: os type not supported!"
#endif

/* Import CrHack Library */
#ifndef ASY_NO_CRHACK
    #ifndef _CR_NO_PRAGMA_LIB_
        #ifndef ASY_USE_STATIC
            #pragma comment (lib, "CrH_CORE.lib")
        #else
            #pragma comment (lib, "COREs.lib")
        #endif
    #endif
#else
    #include <stdlib.h>
    #include <string.h>
    /* ======================================= */
    cr_inline void_t mem_free (const void_t* ptr)
    {
        ::free((void*)ptr);
    }

    #if defined(_CR_NO_STDC_)
        #define mem_set     ::memset
        #define mem_cpy     ::memcpy
        #define mem_cmp     ::memcmp
        #define mem_mov     ::memmove
    #endif
    #define mem_malloc      ::malloc
    #define mem_calloc      ::calloc
    #define mem_malloc32    ::malloc
    #define mem_calloc32    ::calloc
    #define mem_realloc     ::realloc

#ifndef _CR_SYS32_
    #define mem_malloc64    ::malloc
    #define mem_calloc64    ::calloc
#else
    /* ====================================== */
    cr_inline void_t* mem_malloc64 (int64u size)
    {
        if (size > CR_ULL(0xFFFFFFFF))
            return (NULL);
        return (mem_malloc32((int32u)size));
    }

    /* ================================================== */
    cr_inline void_t* mem_calloc64 (int64u num, size_t size)
    {
        if (num > CR_ULL(0xFFFFFFFF))
            return (NULL);
        return (mem_calloc32((int32u)num, size));
    }
#endif  /* !_CR_SYS32_ */
#endif  /* !ASY_NO_CRHACK */

#include "crhack.h"

/* Include */
#if defined(_CR_CC_MSC_)
    #include <intrin.h>
    typedef dist_t  ssize_t;
#endif
#if defined(_CR_OS_MSWIN_)
    #include <process.h>
    #include <windows.h>
#else
    #include <time.h>
    #include <errno.h>
    #include <sched.h>
    #include <pthread.h>
#endif

/* BASIC STUFF */
#include "basic/basic.hpp"
#include "basic/defer.hpp"
#include "basic/safer.hpp"

/* CPU STUFF */
#include "cpu/thread.hpp"
#include "cpu/atomic.hpp"
#include "cpu/crisec.hpp"
#include "cpu/events.hpp"
#include "cpu/exlock.hpp"
#include "cpu/mtlock.hpp"
#include "cpu/nolock.hpp"
#include "cpu/rwlock.hpp"
#include "cpu/splock.hpp"
#include "cpu/doonce.hpp"
#include "cpu/mtpool.hpp"

/* CrHack C++ Wrapper */
#include "crhack/ascall.hpp"
#include "crhack/iports.hpp"
#if defined(ASY_USE_GDI)
    #include "gfx2/gdiwin.h"
    #include "crhack/gfx2_gdi.hpp"
#endif
#if defined(ASY_USE_DX8)
    #include "gfx2/dx8win.h"
    #include "crhack/gfx2_dx8.hpp"
#endif
#if defined(ASY_USE_DX9)
    #include "gfx2/dx9win.h"
    #include "crhack/gfx2_dx9.hpp"
#endif

/* Yet Another Wheel */
#include "yaw/array.hpp"
#include "yaw/bring.hpp"
#include "yaw/list2.hpp"
#include "yaw/map2d.hpp"
#include "yaw/map_a.hpp"
#include "yaw/map_l.hpp"
#include "yaw/oring.hpp"
#include "yaw/table.hpp"
#include "yaw/tree_a.hpp"
#include "yaw/tree_l.hpp"
#include "yaw/map_acs.hpp"

/* Misaka Network */

/* Asylum3D */
#include "draw3d/asylum3d.hpp"
#if defined(ASY_USE_DX9)
    #include "draw3d/crh3d9/crh3d9_main.hpp"
    #include "draw3d/crh3d9/crh3d9_shader.hpp"
    #include "draw3d/crh3d9/crh3d9_texture.hpp"
    #include "draw3d/crh3d9/crh3d9_graph.hpp"
    #ifndef _CR_NO_PRAGMA_LIB_
        #ifndef ASY_USE_STATIC
            #pragma comment (lib, "CrH_GFX3.lib")
        #else
            #pragma comment (lib, "GFX3s.lib")
        #endif
    #endif
#endif

#endif  /* __ASYLUM_HPP__ */
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9a/procedures/hwp/memory/p9a_mss_freq.C $   */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2018,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
<commit_msg>Add L1 procedures for p9a and makefiles<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9a/procedures/hwp/memory/p9a_mss_freq.C $   */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2018,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file p9a_mss_freq.C
/// @brief Calculate and save off DIMM frequencies
///
// *HWP HWP Owner: Andre Marin <aamarin@us.ibm.com>
// *HWP HWP Backup: Louis Stermole <stermole@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 1
// *HWP Consumed by: FSP:HB

// fapi2
#include <p9a_mss_freq.H>

///
/// @brief Calculate and save off DIMM frequencies
/// @param[in] i_target port target
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode p9a_mss_freq( const fapi2::Target<fapi2::TARGET_TYPE_MEM_PORT>& i_target )
{
    return fapi2::FAPI2_RC_SUCCESS;
}
<|endoftext|>


<commit_before>/**
* CinematicView.cpp
*/

#include "stdafx.h"
#include "CinematicView.h"
#include "CallCinematicCamera.h"
#include "CameraParamsOverride.h"
#include "mmcore/param/BoolParam.h"
#include "mmcore/param/EnumParam.h"
#include "mmcore/view/CallRender3D.h"

using namespace megamol;
using namespace megamol::core;
using namespace cinematiccamera;

CinematicView::CinematicView(void) : View3D(),
		keyframeKeeperSlot("keyframeKeeper", "Connects to the Keyframe Keeper."),
		selectedKeyframeParam("cinematicCam::selectedKeyframeParam", "render selected Keyframe if true. render keyframe at animationtime if false"),
		selectedSkyboxSideParam("cinematicCam::skyboxSide", "Skybox side rendering"),
		autoLoadKeyframes("keyframeAutoLoad","shall the keyframes be loaded automatically from the file provided in the keyframe-keeper?"),
		autoSetTotalTime("totalTimeAutoSet", "shall the total animation time be determined automatically?"),
        paramEdit("edit", "Do not overwrite the camera such that the selected key frame can be edited."),
		firstframe(true) {

	this->keyframeKeeperSlot.SetCompatibleCall<CallCinematicCameraDescription>();
	this->MakeSlotAvailable(&this->keyframeKeeperSlot);

	this->selectedKeyframeParam << new core::param::BoolParam(true);
	this->MakeSlotAvailable(&this->selectedKeyframeParam);

	this->autoLoadKeyframes.SetParameter(new core::param::BoolParam(false));
	this->MakeSlotAvailable(&this->autoLoadKeyframes);

	this->autoSetTotalTime.SetParameter(new core::param::BoolParam(true));
	this->MakeSlotAvailable(&this->autoSetTotalTime);

	param::EnumParam *sbs = new param::EnumParam(SKYBOX_NONE);
	sbs->SetTypePair(SKYBOX_NONE,   "None");
	sbs->SetTypePair(SKYBOX_FRONT,	"Front");
	sbs->SetTypePair(SKYBOX_BACK,	"Back");
	sbs->SetTypePair(SKYBOX_LEFT,	"Left");
	sbs->SetTypePair(SKYBOX_RIGHT,	"Right");
	sbs->SetTypePair(SKYBOX_UP,		"Up");
	sbs->SetTypePair(SKYBOX_DOWN,	"Down");
	this->selectedSkyboxSideParam << sbs;
	this->MakeSlotAvailable(&this->selectedSkyboxSideParam);

    this->paramEdit << new core::param::BoolParam(false);
    this->MakeSlotAvailable(&this->paramEdit);
}

megamol::cinematiccamera::CinematicView::~CinematicView() {}

void megamol::cinematiccamera::CinematicView::Render(const mmcRenderViewContext& context) {
	auto cr3d = this->rendererSlot.CallAs<core::view::CallRender3D>();
	(*cr3d)(1); // get extents

	auto kfc = this->keyframeKeeperSlot.CallAs<CallCinematicCamera>();
	if (!kfc) {
		vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_ERROR, "KeyframeKeeper slot not connected!");
	}

	if (firstframe) {
		if (autoLoadKeyframes.Param<param::BoolParam>()->Value()) {
			(*kfc)(CallCinematicCamera::CallForLoadKeyframe);
		}
		if (autoSetTotalTime.Param<param::BoolParam>()->Value()) {
			kfc->setTotalTime(static_cast<float>(cr3d->TimeFramesCount()));
			(*kfc)(CallCinematicCamera::CallForSetTotalTime);
		}
		firstframe = false;
	}

    bool isSelectedKeyFrame = this->selectedKeyframeParam.Param<core::param::BoolParam>()->Value();
    if (isSelectedKeyFrame) {
        // Preview the currently selected key frame.

        if ((*kfc)(CallCinematicCamera::CallForGetSelectedKeyframe)) {
            auto id = kfc->getSelectedKeyframe().getID();
            bool isEdit = this->paramEdit.Param<core::param::BoolParam>()->Value();

            switch (id) {
                case -2:
                    // There is no key frame yet.
                    break;

                case -1:
                    // An interpolated position was selected.
                    kfc->getInterpolatedKeyframe().putCamParameters(this->cam.Parameters());
                    break;

                default:
                    // A key frame was selected.
                    if (!isEdit) {
                        kfc->getSelectedKeyframe().putCamParameters(this->cam.Parameters());
                    }
                    break;
            }

            Base::Render(context);

            if (this->paramEdit.IsDirty()) {
                if (!isEdit && isSelectedKeyFrame && (id >= 0)) {
                    vislib::sys::Log::DefaultLog.WriteInfo("Updating key frame %d ...", id);
                    kfc->setCameraForNewKeyframe(cr3d->GetCameraParameters());
                    if ((*kfc)(CallCinematicCamera::CallForKeyFrameUpdate)) {
                        vislib::sys::Log::DefaultLog.WriteInfo("Key frame %d was updated.", id);
                    }
                }
                this->paramEdit.ResetDirty();
            }

        } else {
            vislib::sys::Log::DefaultLog.WriteError("CallForGetSelectedKeyframe failed!");
        }

	} else {
        // Select the key frame based on the current animation time.

		kfc->setTimeofKeyframeToGet(static_cast<float>(context.Time));
		if ((*kfc)(CallCinematicCamera::CallForGetKeyframeAtTime)){
			kfc->getInterpolatedKeyframe().putCamParameters(this->cam.Parameters());

		}

		vislib::SmartPtr<vislib::graphics::CameraParameters> cp = this->cam.Parameters();
		vislib::math::Point<float, 3> camPos = cp->Position();
		vislib::math::Vector<float, 3> camRight = cp->Right();
		vislib::math::Vector<float, 3> camUp = cp->Up();
		vislib::math::Vector<float, 3> camFront = cp->Front();
		float tmpDist = cp->FocalDistance();
		// adjust cam to selected skybox side
		SkyboxSides side = static_cast<SkyboxSides>(this->selectedSkyboxSideParam.Param<param::EnumParam>()->Value());
		if (side != SKYBOX_NONE) {
			// set aperture angle to 90 deg
			cp->SetApertureAngle(90.0f);
			if (side == SKYBOX_BACK) {
				cp->SetView(camPos, camPos - camFront * tmpDist, camUp);
			}
			else if (side == SKYBOX_RIGHT) {
				cp->SetView(camPos, camPos + camRight * tmpDist, camUp);
			}
			else if (side == SKYBOX_LEFT) {
				cp->SetView(camPos, camPos - camRight * tmpDist, camUp);
			}
			else if (side == SKYBOX_UP) {
				cp->SetView(camPos, camPos + camUp * tmpDist, -camFront);
			}
			else if (side == SKYBOX_DOWN) {
				cp->SetView(camPos, camPos - camUp * tmpDist, camFront);
			}

		}

		Base::Render(context);

		// reset cam (in case some skybox side was rendered)
		//if (side != SKYBOX_NONE) {
		//	cp->SetView(camPos, camPos + camFront * tmpDist, camUp);
		//}

	}

}<commit_msg>Fixor.<commit_after>/**
* CinematicView.cpp
*/

#include "stdafx.h"
#include "CinematicView.h"
#include "CallCinematicCamera.h"
#include "CameraParamsOverride.h"
#include "mmcore/param/BoolParam.h"
#include "mmcore/param/EnumParam.h"
#include "mmcore/view/CallRender3D.h"

using namespace megamol;
using namespace megamol::core;
using namespace cinematiccamera;

CinematicView::CinematicView(void) : View3D(),
		keyframeKeeperSlot("keyframeKeeper", "Connects to the Keyframe Keeper."),
		selectedKeyframeParam("cinematicCam::selectedKeyframeParam", "render selected Keyframe if true. render keyframe at animationtime if false"),
		selectedSkyboxSideParam("cinematicCam::skyboxSide", "Skybox side rendering"),
		autoLoadKeyframes("keyframeAutoLoad","shall the keyframes be loaded automatically from the file provided in the keyframe-keeper?"),
		autoSetTotalTime("totalTimeAutoSet", "shall the total animation time be determined automatically?"),
        paramEdit("cinematicCam::edit", "Do not overwrite the camera such that the selected key frame can be edited."),
		firstframe(true) {

	this->keyframeKeeperSlot.SetCompatibleCall<CallCinematicCameraDescription>();
	this->MakeSlotAvailable(&this->keyframeKeeperSlot);

	this->selectedKeyframeParam << new core::param::BoolParam(true);
	this->MakeSlotAvailable(&this->selectedKeyframeParam);

	this->autoLoadKeyframes.SetParameter(new core::param::BoolParam(false));
	this->MakeSlotAvailable(&this->autoLoadKeyframes);

	this->autoSetTotalTime.SetParameter(new core::param::BoolParam(true));
	this->MakeSlotAvailable(&this->autoSetTotalTime);

	param::EnumParam *sbs = new param::EnumParam(SKYBOX_NONE);
	sbs->SetTypePair(SKYBOX_NONE,   "None");
	sbs->SetTypePair(SKYBOX_FRONT,	"Front");
	sbs->SetTypePair(SKYBOX_BACK,	"Back");
	sbs->SetTypePair(SKYBOX_LEFT,	"Left");
	sbs->SetTypePair(SKYBOX_RIGHT,	"Right");
	sbs->SetTypePair(SKYBOX_UP,		"Up");
	sbs->SetTypePair(SKYBOX_DOWN,	"Down");
	this->selectedSkyboxSideParam << sbs;
	this->MakeSlotAvailable(&this->selectedSkyboxSideParam);

    this->paramEdit << new core::param::BoolParam(false);
    this->MakeSlotAvailable(&this->paramEdit);
}

megamol::cinematiccamera::CinematicView::~CinematicView() {}

void megamol::cinematiccamera::CinematicView::Render(const mmcRenderViewContext& context) {
	auto cr3d = this->rendererSlot.CallAs<core::view::CallRender3D>();
	(*cr3d)(1); // get extents

	auto kfc = this->keyframeKeeperSlot.CallAs<CallCinematicCamera>();
	if (!kfc) {
		vislib::sys::Log::DefaultLog.WriteMsg(vislib::sys::Log::LEVEL_ERROR, "KeyframeKeeper slot not connected!");
	}

	if (firstframe) {
		if (autoLoadKeyframes.Param<param::BoolParam>()->Value()) {
			(*kfc)(CallCinematicCamera::CallForLoadKeyframe);
		}
		if (autoSetTotalTime.Param<param::BoolParam>()->Value()) {
			kfc->setTotalTime(static_cast<float>(cr3d->TimeFramesCount()));
			(*kfc)(CallCinematicCamera::CallForSetTotalTime);
		}
		firstframe = false;
	}

    bool isSelectedKeyFrame = this->selectedKeyframeParam.Param<core::param::BoolParam>()->Value();
    if (isSelectedKeyFrame) {
        // Preview the currently selected key frame.

        if ((*kfc)(CallCinematicCamera::CallForGetSelectedKeyframe)) {
            auto id = kfc->getSelectedKeyframe().getID();
            bool isEdit = this->paramEdit.Param<core::param::BoolParam>()->Value();

            switch (id) {
                case -2:
                    // There is no key frame yet.
                    break;

                case -1:
                    // An interpolated position was selected.
                    kfc->getInterpolatedKeyframe().putCamParameters(this->cam.Parameters());
                    break;

                default:
                    // A key frame was selected.
                    if (!isEdit) {
                        kfc->getSelectedKeyframe().putCamParameters(this->cam.Parameters());
                    }
                    break;
            }

            Base::Render(context);

            if (this->paramEdit.IsDirty()) {
                if (!isEdit && isSelectedKeyFrame && (id >= 0)) {
                    vislib::sys::Log::DefaultLog.WriteInfo("Updating key frame %d ...", id);
                    kfc->setCameraForNewKeyframe(this->cam.Parameters());
                    if ((*kfc)(CallCinematicCamera::CallForKeyFrameUpdate)) {
                        vislib::sys::Log::DefaultLog.WriteInfo("Key frame %d was updated.", id);
                    }
                }
                this->paramEdit.ResetDirty();
            }

        } else {
            vislib::sys::Log::DefaultLog.WriteError("CallForGetSelectedKeyframe failed!");
        }

	} else {
        // Select the key frame based on the current animation time.

		kfc->setTimeofKeyframeToGet(static_cast<float>(context.Time));
		if ((*kfc)(CallCinematicCamera::CallForGetKeyframeAtTime)){
			kfc->getInterpolatedKeyframe().putCamParameters(this->cam.Parameters());

		}

		vislib::SmartPtr<vislib::graphics::CameraParameters> cp = this->cam.Parameters();
		vislib::math::Point<float, 3> camPos = cp->Position();
		vislib::math::Vector<float, 3> camRight = cp->Right();
		vislib::math::Vector<float, 3> camUp = cp->Up();
		vislib::math::Vector<float, 3> camFront = cp->Front();
		float tmpDist = cp->FocalDistance();
		// adjust cam to selected skybox side
		SkyboxSides side = static_cast<SkyboxSides>(this->selectedSkyboxSideParam.Param<param::EnumParam>()->Value());
		if (side != SKYBOX_NONE) {
			// set aperture angle to 90 deg
			cp->SetApertureAngle(90.0f);
			if (side == SKYBOX_BACK) {
				cp->SetView(camPos, camPos - camFront * tmpDist, camUp);
			}
			else if (side == SKYBOX_RIGHT) {
				cp->SetView(camPos, camPos + camRight * tmpDist, camUp);
			}
			else if (side == SKYBOX_LEFT) {
				cp->SetView(camPos, camPos - camRight * tmpDist, camUp);
			}
			else if (side == SKYBOX_UP) {
				cp->SetView(camPos, camPos + camUp * tmpDist, -camFront);
			}
			else if (side == SKYBOX_DOWN) {
				cp->SetView(camPos, camPos - camUp * tmpDist, camFront);
			}

		}

		Base::Render(context);

		// reset cam (in case some skybox side was rendered)
		//if (side != SKYBOX_NONE) {
		//	cp->SetView(camPos, camPos + camFront * tmpDist, camUp);
		//}

	}

}<|endoftext|>


<commit_before>//..............................................................................
//
//  This file is part of the Jancy toolkit.
//
//  Jancy is distributed under the MIT license.
//  For details see accompanying license.txt file,
//  the public copy of which is also available at:
//  http://tibbo.com/downloads/archive/jancy/license.txt
//
//..............................................................................

#include "pch.h"
#include "jnc_ct_CdeclCallConv_msc64.h"
#include "jnc_ct_Module.h"

namespace jnc {
namespace ct {

//..............................................................................

void
CdeclCallConv_msc64::prepareFunctionType (FunctionType* functionType)
{
	Type* returnType = functionType->getReturnType ();
	sl::Array <FunctionArg*> argArray = functionType->getArgArray ();
	size_t argCount = argArray.getCount ();

	char buffer [256];
	sl::Array <llvm::Type*> llvmArgTypeArray (ref::BufKind_Stack, buffer, sizeof (buffer));
	llvmArgTypeArray.setCount (argCount);

	size_t j = 0;

	if (returnType->getFlags () & TypeFlag_StructRet)
	{
		if (returnType->getSize () <= sizeof (uint64_t))
		{
			returnType = m_module->m_typeMgr.getPrimitiveType (TypeKind_Int64);
		}
		else
		{
			returnType = returnType->getDataPtrType_c ();

			argCount++;
			llvmArgTypeArray.setCount (argCount);
			llvmArgTypeArray [0] = returnType->getLlvmType ();
			j = 1;
		}
	}

	bool hasCoercedArgs = false;

	for (size_t i = 0; j < argCount; i++, j++)
	{
		Type* type = argArray [i]->getType ();
		if (!(type->getFlags () & TypeFlag_StructRet))
		{
			llvmArgTypeArray [j] = type->getLlvmType ();
		}
		else if (type->getSize () <= sizeof (uint64_t))
		{
			llvmArgTypeArray [j] = m_module->m_typeMgr.getPrimitiveType (TypeKind_Int64)->getLlvmType ();
			hasCoercedArgs = true;
		}
		else
		{
			llvmArgTypeArray [j] = type->getDataPtrType_c ()->getLlvmType ();
			hasCoercedArgs = true;
		}
	}

	if (hasCoercedArgs)
		functionType->m_flags |= FunctionTypeFlag_CoercedArgs;

	functionType->m_llvmType = llvm::FunctionType::get (
		returnType->getLlvmType (),
		llvm::ArrayRef <llvm::Type*> (llvmArgTypeArray, argCount),
		(functionType->getFlags () & FunctionTypeFlag_VarArg) != 0
		);
}

void
CdeclCallConv_msc64::call (
	const Value& calleeValue,
	FunctionType* functionType,
	sl::BoxList <Value>* argValueList,
	Value* resultValue
	)
{
	Type* returnType = functionType->getReturnType ();

	if (!(functionType->getFlags () & FunctionTypeFlag_CoercedArgs) &&
		!(returnType->getFlags () & TypeFlag_StructRet))
	{
		CallConv::call (calleeValue, functionType, argValueList, resultValue);
		return;
	}

	Value tmpReturnValue;

	if (returnType->getFlags () & TypeFlag_StructRet)
	{
		m_module->m_llvmIrBuilder.createAlloca (
			returnType,
			"tmpRetVal",
			returnType->getDataPtrType_c (),
			&tmpReturnValue
			);

		if (returnType->getSize () > sizeof (uint64_t))
			argValueList->insertHead (tmpReturnValue);
	}

	if (functionType->getFlags () & FunctionTypeFlag_CoercedArgs)
	{
		sl::BoxIterator <Value> it = argValueList->getHead ();
		for (; it; it++)
		{
			Type* type = it->getType ();
			if (!(type->getFlags () & TypeFlag_StructRet))
				continue;

			if (type->getSize () > sizeof (uint64_t))
			{
				Value tmpValue;
				m_module->m_llvmIrBuilder.createAlloca (type, "tmpArg", NULL, &tmpValue);
				m_module->m_llvmIrBuilder.createStore (*it, tmpValue);
				*it = tmpValue;
			}
			else
			{
				Type* coerceType = m_module->m_typeMgr.getPrimitiveType (TypeKind_Int64);

				Value tmpValue, tmpValue2;
				m_module->m_llvmIrBuilder.createAlloca (coerceType, "tmpArg", NULL, &tmpValue);
				m_module->m_llvmIrBuilder.createBitCast (tmpValue, type->getDataPtrType_c (), &tmpValue2);
				m_module->m_llvmIrBuilder.createStore (*it, tmpValue2);
				m_module->m_llvmIrBuilder.createLoad (tmpValue, NULL, &tmpValue);
				*it = tmpValue;
			}
		}
	}

	m_module->m_llvmIrBuilder.createCall (
		calleeValue,
		functionType,
		*argValueList,
		resultValue
		);

	if (returnType->getFlags () & TypeFlag_StructRet)
	{
		if (returnType->getSize () <= sizeof (uint64_t))
		{
			Value tmpValue;
			Type* type = m_module->m_typeMgr.getPrimitiveType (TypeKind_Int64)->getDataPtrType_c ();
			m_module->m_llvmIrBuilder.createBitCast (tmpReturnValue, type, &tmpValue);
			m_module->m_llvmIrBuilder.createStore (*resultValue, tmpValue);
		}

		m_module->m_llvmIrBuilder.createLoad (tmpReturnValue, returnType, resultValue);
	}
}

void
CdeclCallConv_msc64::ret (
	Function* function,
	const Value& value
	)
{
	Type* returnType = function->getType ()->getReturnType ();
	if (!(returnType->getFlags () & TypeFlag_StructRet))
	{
		CallConv::ret (function, value);
		return;
	}

	if (returnType->getSize () > sizeof (uint64_t))
	{
		Value returnPtrValue (&*function->getLlvmFunction ()->arg_begin());

		m_module->m_llvmIrBuilder.createStore (value, returnPtrValue);
		m_module->m_llvmIrBuilder.createRet (returnPtrValue);
	}
	else
	{
		Type* type = m_module->m_typeMgr.getPrimitiveType (TypeKind_Int64)->getDataPtrType_c ();

		Value tmpValue, tmpValue2;
		m_module->m_llvmIrBuilder.createAlloca (type, "tmpRetVal", NULL, &tmpValue);
		m_module->m_llvmIrBuilder.createBitCast (tmpValue, returnType->getDataPtrType_c (), &tmpValue2);
		m_module->m_llvmIrBuilder.createStore (value, tmpValue2);
		m_module->m_llvmIrBuilder.createLoad (tmpValue, NULL, &tmpValue);
		m_module->m_llvmIrBuilder.createRet (tmpValue);
	}
}

Value
CdeclCallConv_msc64::getThisArgValue (Function* function)
{
	ASSERT (function->isMember ());

	FunctionType* functionType = function->getType ();
	Type* returnType = functionType->getReturnType ();

	llvm::Function::arg_iterator llvmArg = function->getLlvmFunction ()->arg_begin ();
	if ((returnType->getFlags () & TypeFlag_StructRet) &&
		returnType->getSize () > sizeof (uint64_t))
		llvmArg++;

	return getArgValue (&*llvmArg, functionType, 0);
}

Value
CdeclCallConv_msc64::getArgValue (
	llvm::Value* llvmValue,
	FunctionType* functionType,
	size_t argIdx
	)
{
	Type* type = functionType->m_argArray [argIdx]->getType ();

	if (!(type->getFlags () & TypeFlag_StructRet))
		return Value (llvmValue, type);

	if (type->getSize () > sizeof (uint64_t))
	{
		Value value;
		m_module->m_llvmIrBuilder.createLoad (llvmValue, type, &value);
		return value;
	}

	Type* int64Type = m_module->m_typeMgr.getPrimitiveType (TypeKind_Int64);

	Value value;
	m_module->m_llvmIrBuilder.createAlloca (int64Type, "tmpArg", NULL, &value);
	m_module->m_llvmIrBuilder.createStore (llvmValue, value);
	m_module->m_llvmIrBuilder.createBitCast (value, type->getDataPtrType_c (), &value);
	m_module->m_llvmIrBuilder.createLoad (value, type, &value);

	return value;
}

void
CdeclCallConv_msc64::createArgVariables (Function* function)
{
	Type* returnType = function->getType ()->getReturnType ();

	llvm::Function::arg_iterator llvmArg = function->getLlvmFunction ()->arg_begin ();
	if ((returnType->getFlags () & TypeFlag_StructRet) &&
		returnType->getSize () > sizeof (uint64_t))
		llvmArg++;

	size_t i = 0;
	if (function->isMember ()) // skip this
	{
		i++;
		llvmArg++;
	}

	sl::Array <FunctionArg*> argArray = function->getType ()->getArgArray ();
	size_t argCount = argArray.getCount ();
	for (; i < argCount; i++, llvmArg++)
	{
		FunctionArg* arg = argArray [i];
		if (!arg->isNamed ())
			continue;

		Type* type = arg->getType ();
		llvm::Value* llvmArgValue = &*llvmArg;

		if (!(type->getFlags () & TypeFlag_StructRet))
		{
			Variable* argVariable = m_module->m_variableMgr.createArgVariable (arg, i);
			function->getScope ()->addItem (argVariable);

			m_module->m_llvmIrBuilder.createStore (llvmArgValue, argVariable);
		}
		else
		{
			Variable* argVariable = m_module->m_variableMgr.createArgVariable (arg, i);
			function->getScope ()->addItem (argVariable);

			if (type->getSize () > sizeof (uint64_t))
			{
				Value tmpValue;
				m_module->m_llvmIrBuilder.createLoad (llvmArgValue, NULL, &tmpValue);
				m_module->m_llvmIrBuilder.createStore (tmpValue, argVariable);
			}
			else
			{
				Type* int64Type = m_module->m_typeMgr.getPrimitiveType (TypeKind_Int64);

				Value tmpValue;
				m_module->m_llvmIrBuilder.createAlloca (int64Type, "tmpArg", NULL, &tmpValue);
				m_module->m_llvmIrBuilder.createStore (llvmArgValue, tmpValue);

				m_module->m_llvmIrBuilder.createBitCast (tmpValue, type->getDataPtrType_c (), &tmpValue);
				m_module->m_llvmIrBuilder.createLoad (tmpValue, NULL, &tmpValue);
				m_module->m_llvmIrBuilder.createStore (tmpValue, argVariable);
			}
		}
	}
}

//..............................................................................

} // namespace ct
} // namespace jnc
<commit_msg>[jnc_ct] typo fix in CdeclCallConv_msc64::ret (int64* was used instead of int64)<commit_after>//..............................................................................
//
//  This file is part of the Jancy toolkit.
//
//  Jancy is distributed under the MIT license.
//  For details see accompanying license.txt file,
//  the public copy of which is also available at:
//  http://tibbo.com/downloads/archive/jancy/license.txt
//
//..............................................................................

#include "pch.h"
#include "jnc_ct_CdeclCallConv_msc64.h"
#include "jnc_ct_Module.h"

namespace jnc {
namespace ct {

//..............................................................................

void
CdeclCallConv_msc64::prepareFunctionType (FunctionType* functionType)
{
	Type* returnType = functionType->getReturnType ();
	sl::Array <FunctionArg*> argArray = functionType->getArgArray ();
	size_t argCount = argArray.getCount ();

	char buffer [256];
	sl::Array <llvm::Type*> llvmArgTypeArray (ref::BufKind_Stack, buffer, sizeof (buffer));
	llvmArgTypeArray.setCount (argCount);

	size_t j = 0;

	if (returnType->getFlags () & TypeFlag_StructRet)
	{
		if (returnType->getSize () <= sizeof (uint64_t))
		{
			returnType = m_module->m_typeMgr.getPrimitiveType (TypeKind_Int64);
		}
		else
		{
			returnType = returnType->getDataPtrType_c ();

			argCount++;
			llvmArgTypeArray.setCount (argCount);
			llvmArgTypeArray [0] = returnType->getLlvmType ();
			j = 1;
		}
	}

	bool hasCoercedArgs = false;

	for (size_t i = 0; j < argCount; i++, j++)
	{
		Type* type = argArray [i]->getType ();
		if (!(type->getFlags () & TypeFlag_StructRet))
		{
			llvmArgTypeArray [j] = type->getLlvmType ();
		}
		else if (type->getSize () <= sizeof (uint64_t))
		{
			llvmArgTypeArray [j] = m_module->m_typeMgr.getPrimitiveType (TypeKind_Int64)->getLlvmType ();
			hasCoercedArgs = true;
		}
		else
		{
			llvmArgTypeArray [j] = type->getDataPtrType_c ()->getLlvmType ();
			hasCoercedArgs = true;
		}
	}

	if (hasCoercedArgs)
		functionType->m_flags |= FunctionTypeFlag_CoercedArgs;

	functionType->m_llvmType = llvm::FunctionType::get (
		returnType->getLlvmType (),
		llvm::ArrayRef <llvm::Type*> (llvmArgTypeArray, argCount),
		(functionType->getFlags () & FunctionTypeFlag_VarArg) != 0
		);
}

void
CdeclCallConv_msc64::call (
	const Value& calleeValue,
	FunctionType* functionType,
	sl::BoxList <Value>* argValueList,
	Value* resultValue
	)
{
	Type* returnType = functionType->getReturnType ();

	if (!(functionType->getFlags () & FunctionTypeFlag_CoercedArgs) &&
		!(returnType->getFlags () & TypeFlag_StructRet))
	{
		CallConv::call (calleeValue, functionType, argValueList, resultValue);
		return;
	}

	Value tmpReturnValue;

	if (returnType->getFlags () & TypeFlag_StructRet)
	{
		m_module->m_llvmIrBuilder.createAlloca (
			returnType,
			"tmpRetVal",
			returnType->getDataPtrType_c (),
			&tmpReturnValue
			);

		if (returnType->getSize () > sizeof (uint64_t))
			argValueList->insertHead (tmpReturnValue);
	}

	if (functionType->getFlags () & FunctionTypeFlag_CoercedArgs)
	{
		sl::BoxIterator <Value> it = argValueList->getHead ();
		for (; it; it++)
		{
			Type* type = it->getType ();
			if (!(type->getFlags () & TypeFlag_StructRet))
				continue;

			if (type->getSize () > sizeof (uint64_t))
			{
				Value tmpValue;
				m_module->m_llvmIrBuilder.createAlloca (type, "tmpArg", NULL, &tmpValue);
				m_module->m_llvmIrBuilder.createStore (*it, tmpValue);
				*it = tmpValue;
			}
			else
			{
				Type* coerceType = m_module->m_typeMgr.getPrimitiveType (TypeKind_Int64);

				Value tmpValue, tmpValue2;
				m_module->m_llvmIrBuilder.createAlloca (coerceType, "tmpArg", NULL, &tmpValue);
				m_module->m_llvmIrBuilder.createBitCast (tmpValue, type->getDataPtrType_c (), &tmpValue2);
				m_module->m_llvmIrBuilder.createStore (*it, tmpValue2);
				m_module->m_llvmIrBuilder.createLoad (tmpValue, NULL, &tmpValue);
				*it = tmpValue;
			}
		}
	}

	m_module->m_llvmIrBuilder.createCall (
		calleeValue,
		functionType,
		*argValueList,
		resultValue
		);

	if (returnType->getFlags () & TypeFlag_StructRet)
	{
		if (returnType->getSize () <= sizeof (uint64_t))
		{
			Value tmpValue;
			Type* type = m_module->m_typeMgr.getPrimitiveType (TypeKind_Int64)->getDataPtrType_c ();
			m_module->m_llvmIrBuilder.createBitCast (tmpReturnValue, type, &tmpValue);
			m_module->m_llvmIrBuilder.createStore (*resultValue, tmpValue);
		}

		m_module->m_llvmIrBuilder.createLoad (tmpReturnValue, returnType, resultValue);
	}
}

void
CdeclCallConv_msc64::ret (
	Function* function,
	const Value& value
	)
{
	Type* returnType = function->getType ()->getReturnType ();
	if (!(returnType->getFlags () & TypeFlag_StructRet))
	{
		CallConv::ret (function, value);
		return;
	}

	if (returnType->getSize () > sizeof (uint64_t))
	{
		Value returnPtrValue (&*function->getLlvmFunction ()->arg_begin());

		m_module->m_llvmIrBuilder.createStore (value, returnPtrValue);
		m_module->m_llvmIrBuilder.createRet (returnPtrValue);
	}
	else
	{
		Type* type = m_module->m_typeMgr.getPrimitiveType (TypeKind_Int64);

		Value tmpValue, tmpValue2;
		m_module->m_llvmIrBuilder.createAlloca (type, "tmpRetVal", NULL, &tmpValue);
		m_module->m_llvmIrBuilder.createBitCast (tmpValue, returnType->getDataPtrType_c (), &tmpValue2);
		m_module->m_llvmIrBuilder.createStore (value, tmpValue2);
		m_module->m_llvmIrBuilder.createLoad (tmpValue, NULL, &tmpValue);
		m_module->m_llvmIrBuilder.createRet (tmpValue);
	}
}

Value
CdeclCallConv_msc64::getThisArgValue (Function* function)
{
	ASSERT (function->isMember ());

	FunctionType* functionType = function->getType ();
	Type* returnType = functionType->getReturnType ();

	llvm::Function::arg_iterator llvmArg = function->getLlvmFunction ()->arg_begin ();
	if ((returnType->getFlags () & TypeFlag_StructRet) &&
		returnType->getSize () > sizeof (uint64_t))
		llvmArg++;

	return getArgValue (&*llvmArg, functionType, 0);
}

Value
CdeclCallConv_msc64::getArgValue (
	llvm::Value* llvmValue,
	FunctionType* functionType,
	size_t argIdx
	)
{
	Type* type = functionType->m_argArray [argIdx]->getType ();

	if (!(type->getFlags () & TypeFlag_StructRet))
		return Value (llvmValue, type);

	if (type->getSize () > sizeof (uint64_t))
	{
		Value value;
		m_module->m_llvmIrBuilder.createLoad (llvmValue, type, &value);
		return value;
	}

	Type* int64Type = m_module->m_typeMgr.getPrimitiveType (TypeKind_Int64);

	Value value;
	m_module->m_llvmIrBuilder.createAlloca (int64Type, "tmpArg", NULL, &value);
	m_module->m_llvmIrBuilder.createStore (llvmValue, value);
	m_module->m_llvmIrBuilder.createBitCast (value, type->getDataPtrType_c (), &value);
	m_module->m_llvmIrBuilder.createLoad (value, type, &value);

	return value;
}

void
CdeclCallConv_msc64::createArgVariables (Function* function)
{
	Type* returnType = function->getType ()->getReturnType ();

	llvm::Function::arg_iterator llvmArg = function->getLlvmFunction ()->arg_begin ();
	if ((returnType->getFlags () & TypeFlag_StructRet) &&
		returnType->getSize () > sizeof (uint64_t))
		llvmArg++;

	size_t i = 0;
	if (function->isMember ()) // skip this
	{
		i++;
		llvmArg++;
	}

	sl::Array <FunctionArg*> argArray = function->getType ()->getArgArray ();
	size_t argCount = argArray.getCount ();
	for (; i < argCount; i++, llvmArg++)
	{
		FunctionArg* arg = argArray [i];
		if (!arg->isNamed ())
			continue;

		Type* type = arg->getType ();
		llvm::Value* llvmArgValue = &*llvmArg;

		if (!(type->getFlags () & TypeFlag_StructRet))
		{
			Variable* argVariable = m_module->m_variableMgr.createArgVariable (arg, i);
			function->getScope ()->addItem (argVariable);

			m_module->m_llvmIrBuilder.createStore (llvmArgValue, argVariable);
		}
		else
		{
			Variable* argVariable = m_module->m_variableMgr.createArgVariable (arg, i);
			function->getScope ()->addItem (argVariable);

			if (type->getSize () > sizeof (uint64_t))
			{
				Value tmpValue;
				m_module->m_llvmIrBuilder.createLoad (llvmArgValue, NULL, &tmpValue);
				m_module->m_llvmIrBuilder.createStore (tmpValue, argVariable);
			}
			else
			{
				Type* int64Type = m_module->m_typeMgr.getPrimitiveType (TypeKind_Int64);

				Value tmpValue;
				m_module->m_llvmIrBuilder.createAlloca (int64Type, "tmpArg", NULL, &tmpValue);
				m_module->m_llvmIrBuilder.createStore (llvmArgValue, tmpValue);

				m_module->m_llvmIrBuilder.createBitCast (tmpValue, type->getDataPtrType_c (), &tmpValue);
				m_module->m_llvmIrBuilder.createLoad (tmpValue, NULL, &tmpValue);
				m_module->m_llvmIrBuilder.createStore (tmpValue, argVariable);
			}
		}
	}
}

//..............................................................................

} // namespace ct
} // namespace jnc
<|endoftext|>


<commit_before>#include "boundingrecthighlighter.h"
#include "qdeclarativedesignview.h"
#include "qmlviewerconstants.h"

#include <QGraphicsPolygonItem>
#include <QTimer>
#include <QObject>

#include <QDebug>

namespace QmlViewer {

const qreal AnimDelta = 0.025f;
const int AnimInterval = 30;
const int AnimFrames = 10;

BoundingBox::BoundingBox(QGraphicsObject *itemToHighlight, QGraphicsItem *parentItem, QObject *parent)
    : QObject(parent),
      highlightedObject(itemToHighlight),
      highlightPolygon(0),
      highlightPolygonEdge(0)
{
    highlightPolygon = new BoundingBoxPolygonItem(parentItem);
    highlightPolygonEdge = new BoundingBoxPolygonItem(parentItem);

    highlightPolygon->setPen(QPen(QColor(0, 22, 159)));
    highlightPolygonEdge->setPen(QPen(QColor(158, 199, 255)));

    highlightPolygon->setFlag(QGraphicsItem::ItemIsSelectable, false);
    highlightPolygonEdge->setFlag(QGraphicsItem::ItemIsSelectable, false);
}

BoundingBox::~BoundingBox()
{
    highlightedObject.clear();
}

BoundingBoxPolygonItem::BoundingBoxPolygonItem(QGraphicsItem *item) : QGraphicsPolygonItem(item)
{
    QPen pen;
    pen.setColor(QColor(108, 141, 221));
    setPen(pen);
}

int BoundingBoxPolygonItem::type() const
{
    return Constants::EditorItemType;
}

BoundingRectHighlighter::BoundingRectHighlighter(QDeclarativeDesignView *view) :
    LayerItem(view->scene()),
    m_view(view),
    m_animFrame(0)
{
    m_animTimer = new QTimer(this);
    m_animTimer->setInterval(AnimInterval);
    connect(m_animTimer, SIGNAL(timeout()), SLOT(animTimeout()));
}

BoundingRectHighlighter::~BoundingRectHighlighter()
{

}

void BoundingRectHighlighter::animTimeout()
{
    ++m_animFrame;
    if (m_animFrame == AnimFrames) {
        m_animTimer->stop();
    }

    qreal alpha = m_animFrame / float(AnimFrames);

    foreach(BoundingBox *box, m_boxes) {
        box->highlightPolygonEdge->setOpacity(alpha);
    }
}

void BoundingRectHighlighter::clear()
{
    if (m_boxes.length()) {
        m_animTimer->stop();

        foreach(BoundingBox *box, m_boxes) {
            freeBoundingBox(box);
        }
    }
}

BoundingBox *BoundingRectHighlighter::boxFor(QGraphicsObject *item) const
{
    foreach(BoundingBox *box, m_boxes) {
        if (box->highlightedObject.data() == item) {
            return box;
        }
    }
    return 0;
}

void BoundingRectHighlighter::highlight(QList<QGraphicsObject*> items)
{
    if (items.isEmpty())
        return;

    bool animate = false;

    QList<BoundingBox *> newBoxes;
    foreach(QGraphicsObject *itemToHighlight, items) {
        BoundingBox *box = boxFor(itemToHighlight);
        if (!box) {
            box = createBoundingBox(itemToHighlight);
            animate = true;
        }

        newBoxes << box;
    }
    qSort(newBoxes);

    if (newBoxes != m_boxes) {
        clear();
        m_boxes << newBoxes;
    }

    highlightAll(animate);
}

void BoundingRectHighlighter::highlight(QGraphicsObject* itemToHighlight)
{
    if (!itemToHighlight)
        return;

    bool animate = false;

    BoundingBox *box = boxFor(itemToHighlight);
    if (!box) {
        box = createBoundingBox(itemToHighlight);
        m_boxes << box;
        animate = true;
        qSort(m_boxes);
    }

    highlightAll(animate);
}

BoundingBox *BoundingRectHighlighter::createBoundingBox(QGraphicsObject *itemToHighlight)
{
    if (!m_freeBoxes.isEmpty()) {
        BoundingBox *box = m_freeBoxes.last();
        if (box->highlightedObject.isNull()) {
            box->highlightedObject = itemToHighlight;
            box->highlightPolygon->show();
            box->highlightPolygonEdge->show();
            m_freeBoxes.removeLast();
            return box;
        }
    }

    BoundingBox *box = new BoundingBox(itemToHighlight, this, this);

    connect(itemToHighlight, SIGNAL(xChanged()), this, SLOT(refresh()));
    connect(itemToHighlight, SIGNAL(yChanged()), this, SLOT(refresh()));
    connect(itemToHighlight, SIGNAL(widthChanged()), this, SLOT(refresh()));
    connect(itemToHighlight, SIGNAL(heightChanged()), this, SLOT(refresh()));
    connect(itemToHighlight, SIGNAL(rotationChanged()), this, SLOT(refresh()));
    connect(itemToHighlight, SIGNAL(destroyed(QObject*)), this, SLOT(itemDestroyed(QObject*)));

    return box;
}

void BoundingRectHighlighter::removeBoundingBox(BoundingBox *box)
{
    delete box;
    box = 0;
}

void BoundingRectHighlighter::freeBoundingBox(BoundingBox *box)
{
    if (!box->highlightedObject.isNull()) {
        disconnect(box->highlightedObject.data(), SIGNAL(xChanged()), this, SLOT(refresh()));
        disconnect(box->highlightedObject.data(), SIGNAL(yChanged()), this, SLOT(refresh()));
        disconnect(box->highlightedObject.data(), SIGNAL(widthChanged()), this, SLOT(refresh()));
        disconnect(box->highlightedObject.data(), SIGNAL(heightChanged()), this, SLOT(refresh()));
        disconnect(box->highlightedObject.data(), SIGNAL(rotationChanged()), this, SLOT(refresh()));
    }

    box->highlightedObject.clear();
    box->highlightPolygon->hide();
    box->highlightPolygonEdge->hide();
    m_boxes.removeOne(box);
    m_freeBoxes << box;
}

void BoundingRectHighlighter::itemDestroyed(QObject *obj)
{
    foreach(BoundingBox *box, m_boxes) {
        if (box->highlightedObject.data() == obj) {
            freeBoundingBox(box);
            break;
        }
    }
}

void BoundingRectHighlighter::highlightAll(bool animate)
{
    foreach(BoundingBox *box, m_boxes) {
        if (box && box->highlightedObject.isNull()) {
            // clear all highlights
            clear();
            return;
        }
        QGraphicsObject *item = box->highlightedObject.data();
        QRectF itemAndChildRect = item->boundingRect() | item->childrenBoundingRect();

        QPolygonF boundingRectInSceneSpace(item->mapToScene(itemAndChildRect));
        QPolygonF boundingRectInLayerItemSpace = mapFromScene(boundingRectInSceneSpace);
        QRectF bboxRect = m_view->adjustToScreenBoundaries(boundingRectInLayerItemSpace.boundingRect());
        QRectF edgeRect = bboxRect;
        edgeRect.adjust(-1, -1, 1, 1);

        box->highlightPolygon->setPolygon(QPolygonF(bboxRect));
        box->highlightPolygonEdge->setPolygon(QPolygonF(edgeRect));

        if (animate)
            box->highlightPolygonEdge->setOpacity(0);
    }

    if (animate) {
        m_animFrame = 0;
        m_animTimer->start();
    }
}

void BoundingRectHighlighter::refresh()
{
    if (!m_boxes.isEmpty())
        highlightAll(true);
}

} // namespace QmlViewer
<commit_msg>qml observer: set default pen size to 1<commit_after>#include "boundingrecthighlighter.h"
#include "qdeclarativedesignview.h"
#include "qmlviewerconstants.h"

#include <QGraphicsPolygonItem>
#include <QTimer>
#include <QObject>

#include <QDebug>

namespace QmlViewer {

const qreal AnimDelta = 0.025f;
const int AnimInterval = 30;
const int AnimFrames = 10;

BoundingBox::BoundingBox(QGraphicsObject *itemToHighlight, QGraphicsItem *parentItem, QObject *parent)
    : QObject(parent),
      highlightedObject(itemToHighlight),
      highlightPolygon(0),
      highlightPolygonEdge(0)
{
    highlightPolygon = new BoundingBoxPolygonItem(parentItem);
    highlightPolygonEdge = new BoundingBoxPolygonItem(parentItem);

    highlightPolygon->setPen(QPen(QColor(0, 22, 159)));
    highlightPolygonEdge->setPen(QPen(QColor(158, 199, 255)));

    highlightPolygon->setFlag(QGraphicsItem::ItemIsSelectable, false);
    highlightPolygonEdge->setFlag(QGraphicsItem::ItemIsSelectable, false);
}

BoundingBox::~BoundingBox()
{
    highlightedObject.clear();
}

BoundingBoxPolygonItem::BoundingBoxPolygonItem(QGraphicsItem *item) : QGraphicsPolygonItem(item)
{
    QPen pen;
    pen.setColor(QColor(108, 141, 221));
    pen.setWidth(1);
    setPen(pen);
}

int BoundingBoxPolygonItem::type() const
{
    return Constants::EditorItemType;
}

BoundingRectHighlighter::BoundingRectHighlighter(QDeclarativeDesignView *view) :
    LayerItem(view->scene()),
    m_view(view),
    m_animFrame(0)
{
    m_animTimer = new QTimer(this);
    m_animTimer->setInterval(AnimInterval);
    connect(m_animTimer, SIGNAL(timeout()), SLOT(animTimeout()));
}

BoundingRectHighlighter::~BoundingRectHighlighter()
{

}

void BoundingRectHighlighter::animTimeout()
{
    ++m_animFrame;
    if (m_animFrame == AnimFrames) {
        m_animTimer->stop();
    }

    qreal alpha = m_animFrame / float(AnimFrames);

    foreach(BoundingBox *box, m_boxes) {
        box->highlightPolygonEdge->setOpacity(alpha);
    }
}

void BoundingRectHighlighter::clear()
{
    if (m_boxes.length()) {
        m_animTimer->stop();

        foreach(BoundingBox *box, m_boxes) {
            freeBoundingBox(box);
        }
    }
}

BoundingBox *BoundingRectHighlighter::boxFor(QGraphicsObject *item) const
{
    foreach(BoundingBox *box, m_boxes) {
        if (box->highlightedObject.data() == item) {
            return box;
        }
    }
    return 0;
}

void BoundingRectHighlighter::highlight(QList<QGraphicsObject*> items)
{
    if (items.isEmpty())
        return;

    bool animate = false;

    QList<BoundingBox *> newBoxes;
    foreach(QGraphicsObject *itemToHighlight, items) {
        BoundingBox *box = boxFor(itemToHighlight);
        if (!box) {
            box = createBoundingBox(itemToHighlight);
            animate = true;
        }

        newBoxes << box;
    }
    qSort(newBoxes);

    if (newBoxes != m_boxes) {
        clear();
        m_boxes << newBoxes;
    }

    highlightAll(animate);
}

void BoundingRectHighlighter::highlight(QGraphicsObject* itemToHighlight)
{
    if (!itemToHighlight)
        return;

    bool animate = false;

    BoundingBox *box = boxFor(itemToHighlight);
    if (!box) {
        box = createBoundingBox(itemToHighlight);
        m_boxes << box;
        animate = true;
        qSort(m_boxes);
    }

    highlightAll(animate);
}

BoundingBox *BoundingRectHighlighter::createBoundingBox(QGraphicsObject *itemToHighlight)
{
    if (!m_freeBoxes.isEmpty()) {
        BoundingBox *box = m_freeBoxes.last();
        if (box->highlightedObject.isNull()) {
            box->highlightedObject = itemToHighlight;
            box->highlightPolygon->show();
            box->highlightPolygonEdge->show();
            m_freeBoxes.removeLast();
            return box;
        }
    }

    BoundingBox *box = new BoundingBox(itemToHighlight, this, this);

    connect(itemToHighlight, SIGNAL(xChanged()), this, SLOT(refresh()));
    connect(itemToHighlight, SIGNAL(yChanged()), this, SLOT(refresh()));
    connect(itemToHighlight, SIGNAL(widthChanged()), this, SLOT(refresh()));
    connect(itemToHighlight, SIGNAL(heightChanged()), this, SLOT(refresh()));
    connect(itemToHighlight, SIGNAL(rotationChanged()), this, SLOT(refresh()));
    connect(itemToHighlight, SIGNAL(destroyed(QObject*)), this, SLOT(itemDestroyed(QObject*)));

    return box;
}

void BoundingRectHighlighter::removeBoundingBox(BoundingBox *box)
{
    delete box;
    box = 0;
}

void BoundingRectHighlighter::freeBoundingBox(BoundingBox *box)
{
    if (!box->highlightedObject.isNull()) {
        disconnect(box->highlightedObject.data(), SIGNAL(xChanged()), this, SLOT(refresh()));
        disconnect(box->highlightedObject.data(), SIGNAL(yChanged()), this, SLOT(refresh()));
        disconnect(box->highlightedObject.data(), SIGNAL(widthChanged()), this, SLOT(refresh()));
        disconnect(box->highlightedObject.data(), SIGNAL(heightChanged()), this, SLOT(refresh()));
        disconnect(box->highlightedObject.data(), SIGNAL(rotationChanged()), this, SLOT(refresh()));
    }

    box->highlightedObject.clear();
    box->highlightPolygon->hide();
    box->highlightPolygonEdge->hide();
    m_boxes.removeOne(box);
    m_freeBoxes << box;
}

void BoundingRectHighlighter::itemDestroyed(QObject *obj)
{
    foreach(BoundingBox *box, m_boxes) {
        if (box->highlightedObject.data() == obj) {
            freeBoundingBox(box);
            break;
        }
    }
}

void BoundingRectHighlighter::highlightAll(bool animate)
{
    foreach(BoundingBox *box, m_boxes) {
        if (box && box->highlightedObject.isNull()) {
            // clear all highlights
            clear();
            return;
        }
        QGraphicsObject *item = box->highlightedObject.data();
        QRectF itemAndChildRect = item->boundingRect() | item->childrenBoundingRect();

        QPolygonF boundingRectInSceneSpace(item->mapToScene(itemAndChildRect));
        QPolygonF boundingRectInLayerItemSpace = mapFromScene(boundingRectInSceneSpace);
        QRectF bboxRect = m_view->adjustToScreenBoundaries(boundingRectInLayerItemSpace.boundingRect());
        QRectF edgeRect = bboxRect;
        edgeRect.adjust(-1, -1, 1, 1);

        box->highlightPolygon->setPolygon(QPolygonF(bboxRect));
        box->highlightPolygonEdge->setPolygon(QPolygonF(edgeRect));

        if (animate)
            box->highlightPolygonEdge->setOpacity(0);
    }

    if (animate) {
        m_animFrame = 0;
        m_animTimer->start();
    }
}

void BoundingRectHighlighter::refresh()
{
    if (!m_boxes.isEmpty())
        highlightAll(true);
}

} // namespace QmlViewer
<|endoftext|>


<commit_before>#include <iostream>
#include <seqan/sequence.h>
#include <seqan/file.h>

using namespace seqan;
// Function to print simple alignment between two sequences with the same length
template <typename TText1, typename TText2>
void printAlign(TText1 const & genomeFragment, TText2 const & read)
{
        std::cout <<  "Alignment " << std::endl;
        std::cout << "  genome : " << genomeFragment << std::endl;
        std::cout << "  read   : " << read << std::endl;
}
int main(int, char const **)
{
    // Build reads and genomes
    DnaString chr1 = "TATAATATTGCTATCGCGATATCGCTAGCTAGCTACGGATTATGCGCTCTGCGATATATCGCGCTAGATGTGCAGCTCGATCGAATGCACGTGTGTGCGATCGATTAGCGTCGATCATCGATCTATATTAGCGCGCGGTATCGGACGATCATATTAGCGGTCTAGCATTTAG";
    // Build List containing all reads
    typedef String<DnaString> DnaList;
    DnaList readList;
    resize(readList, 4);
    readList[0] = "TTGCTATCGCGATATCGCTAGCTAGCTACGGATTATGCGCTCTGCGATATATCGCGCT";
    readList[1] = "TCGATTAGCGTCGATCATCGATCTATATTAGCGCGCGGTATCGGACGATCATATTAGCGGTCTAGCATT";
    readList[2] = "AGCCTGCGTACGTTGCAGTGCGTGCGTAGACTGTTGCAAGCCGGGGGTTCATGTGCGCTGAAGCACACATGCACA";
    readList[3] = "CGTGCACTGCTGACGTCGTGGTTGTCACATCGTCGTGCGTGCGTACTGCTGCTGACA";
    // Append a second chromosome sequence fragment to chr1
    DnaString chr2 = "AGCCTGCGTACGTTGCAGTGCGTGCGTAGACTGTTGCAAGCCGGGGGTTCATGTGCGCTGAAGCACACATGCACACGTCTCTGTGTTCCGACGTGTGTCACGTGCACTGCTGACGTCGTGGTTGTCACATCGTCGTGCGTGCGTACTGCTGCTGACACATGCTGCTG";
    append(chr1, chr2);
    // Print readlist
    std::cout << " \n Read list: " << std::endl;
    for(unsigned i = 0; i < length(readList); ++i)
        std::cout << readList[i] << std::endl;
    // Assume we have mapped the 4 reads to chr1 (and chr2) and now have the mapping start positions (no gaps).
    // Store the start position in a String: 7, 100, 172, 272
    String<unsigned> alignPosList;
    resize(alignPosList, 4);
    alignPosList[0] = 7;
    alignPosList[1] = 100;
    alignPosList[2] = 172;
    alignPosList[3] = 272;
    // Print alignments using Segment
    std::cout << " \n Print alignment using Segment: " << std::endl;
    for(unsigned i = 0; i < length(readList); ++i)
    {
        // Begin and end position of a given alignment between the read and the genome
        unsigned beginPosition = alignPosList[i];
        unsigned endPosition = beginPosition + length(readList[i]);
        // Build infix
        Infix<DnaString>::Type genomeFragment = infix(chr1, beginPosition, endPosition);
        // Call of our function to print the simple alignment
        printAlign(genomeFragment, readList[i]);
    }
    // Iterators :)
    // Print alignments using Iterators: Do the same as above, but use Iterators to iterate over the read list.
    // First, use Standard Iterators.
    Iterator<DnaList>::Type it = begin(readList);
    Iterator<DnaList, Standard>::Type itEnd = end(readList); //same Iterator as above

    std::cout << " \n Print alignment using Standard Iterators: " << std::endl;
    for(; it != itEnd; goNext(it))
    {
        // Get the right index for alignPosList
        int i = position(it, readList);
        // Begin and end position of a given alignment between the read and the genome
        unsigned beginPosition = alignPosList[i];
        unsigned endPosition = beginPosition + length(value(it));
        // Build Infix
        Infix<DnaString>::Type genomeFragment = infix(chr1, beginPosition, endPosition);
        // Call of our function to print the simple alignment
        printAlign(genomeFragment, value(it));
    }
    // Now, use Rooted Iterators.
    Iterator<DnaList, Rooted>::Type it2 = begin(readList);
    std::cout << " \n Print alignment using Rooted Iterators: " << std::endl;
    for(; !atEnd(it2); goNext(it2))
    {
        int i = position(it2);
        // Begin and end position of a given alignment between the read and the genome
        unsigned beginPosition = alignPosList[i];
        unsigned endPosition = beginPosition + length(value(it2));
        // Build Infix
        Infix<DnaString>::Type genomeFragment = infix(chr1, beginPosition, endPosition);
        // Call of our function to print the simple alignment
        printAlign(genomeFragment, value(it2));
    }
    return 1;
}
<commit_msg>[DOC] Deleted tutorial file.<commit_after><|endoftext|>