<commit_before>// Copyright eeGeo Ltd (2012-2015), All Rights Reserved

#include "InteriorEntityHighlightController.h"
#include "ISearchService.h"
#include "ISearchQueryPerformer.h"
#include "ISearchResultRepository.h"
#include "InteriorInteractionModel.h"
#include "InteriorsModel.h"
#include "InteriorsFloorModel.h"
#include "IInteriorsLabelController.h"
#include "VectorMath.h"
#include "InteriorHighlightRenderable.h"
#include "InteriorsLabelParser.h"
#include "InteriorsFloorCells.h"
#include "InteriorsFloorCell.h"
#include "PlaceNameModel.h"
#include "InteriorsCellResource.h"
#include "InteriorsCellResourceObserver.h"
#include "LabelAnchorFilterModel.h"
#include "IAnchoredLabel.h"
#include "document.h"
#include "IInteriorsHighlightService.h"

namespace ExampleApp
{
    namespace InteriorsExplorer
    {
        namespace SdkModel
        {
            namespace Highlights
            {
                std::vector<std::string> GetEntityIdsFromJsonArray(const rapidjson::Value& jsonArray)
                {
                    assert(jsonArray.IsArray());
                    std::vector<std::string> entities;

                    for (int i  = 0; i < jsonArray.Size(); i++)
                    {
                        assert(jsonArray[i].IsString());
                        entities.push_back(jsonArray[i].GetString());
                    }

                    return entities;
                }

                std::vector<std::string> GetEntityIdsFromSearchResultModel(const Search::SdkModel::SearchResultModel& selectedSearchResult)
                {
                    rapidjson::Document json;
                    std::vector<std::string> entities;

                    if (!json.Parse<0>(selectedSearchResult.GetJsonData().c_str()).HasParseError())
                    {
                        if( json.HasMember("highlight")  )
                        {
                            const rapidjson::Value& area_highlight = json["highlight"];
                            if(area_highlight.IsString())
                            {
                                entities.push_back(json["highlight"].GetString());
                            }
                            else
                            {
                                std::vector<std::string> areaHighlights = GetEntityIdsFromJsonArray(area_highlight);
                                entities.insert(std::end(entities), std::begin(areaHighlights), std::end(areaHighlights));
                            }
                        }

                        if(  json.HasMember("entity_highlight")  )
                        {
                            std::vector<std::string> entityHighlights = GetEntityIdsFromJsonArray(json["entity_highlight"]);
                            entities.insert(std::end(entities), std::begin(entityHighlights), std::end(entityHighlights));
                        }
                    }

                    return entities;
                }

                InteriorEntityHighlightController::InteriorEntityHighlightController(Eegeo::Resources::Interiors::InteriorInteractionModel& interiorInteractionModel,
                                                                                Eegeo::Resources::Interiors::InteriorsCellResourceObserver& interiorsCellResourceObserver,
                                                                                Search::SdkModel::ISearchService& searchService,
                                                                                Search::SdkModel::ISearchQueryPerformer& searchQueryPerformer, Eegeo::Resources::Interiors::Entities::IInteriorsLabelController& legacyLabelController,
                                                                                Eegeo::Labels::ILabelAnchorFilterModel& labelHiddenFilterModel,
                                                                                const Eegeo::Labels::LabelLayer::IdType interiorLabelLayer,
                                                                                ExampleAppMessaging::TMessageBus& messageBus,
                                                                                IHighlightColorMapper& highlightColorMapper,
                                                                                Eegeo::Resources::Interiors::Highlights::IInteriorsHighlightService& interiorsHighlightService)
                : m_interiorInteractionModel(interiorInteractionModel)
                , m_interiorsCellResourceObserver(interiorsCellResourceObserver)
                , m_interiorLabelLayer(interiorLabelLayer)
                , m_labelHiddenFilterModel(labelHiddenFilterModel)
                , m_searchQueryPerformer(searchQueryPerformer)
                , m_highlightColorMapper(highlightColorMapper)
                , m_searchResultsIndex(-1)
                , m_searchQueryResponseHandler(this, &InteriorEntityHighlightController::OnSearchQueryResponseReceived)
                , m_searchResultsClearedHandler(this, &InteriorEntityHighlightController::OnSearchResultCleared)
                , m_handleSearchResultSectionItemSelectedMessageBinding(this, &InteriorEntityHighlightController::OnSearchItemSelected)
                , m_interiorInteractionModelChangedHandler(this, &InteriorEntityHighlightController::OnInteriorChanged)
                , m_interiorCellAddedHandler(this, &InteriorEntityHighlightController::OnInteriorAddedToSceneGraph)
                , m_availabilityChangedHandlerBinding(this, &InteriorEntityHighlightController::OnAvailabilityChanged)
                , m_interiorLabelsBuiltHandler(this, &InteriorEntityHighlightController::OnInteriorLabelsBuilt)
                , m_interiorsHighlightService(interiorsHighlightService)
                , m_messageBus(messageBus)
                , m_hideLabelAlwaysFilter(this, &InteriorEntityHighlightController::HideLabelAlwaysPredicate)
                , m_hideLabelByNameFilter(this, &InteriorEntityHighlightController::HideLabelByNamePredicate)
                {
                    m_messageBus.SubscribeUi(m_searchQueryResponseHandler);
                    m_searchQueryPerformer.InsertOnSearchResultsClearedCallback(m_searchResultsClearedHandler);
                    m_interiorInteractionModel.RegisterModelChangedCallback(m_interiorInteractionModelChangedHandler);

                    m_interiorsCellResourceObserver.RegisterAddedToSceneGraphCallback(m_interiorCellAddedHandler);
                    m_messageBus.SubscribeNative(m_handleSearchResultSectionItemSelectedMessageBinding);
                    m_labelHiddenFilterModel.SetFilter(m_interiorLabelLayer, &m_hideLabelAlwaysFilter);
                }

                InteriorEntityHighlightController::~InteriorEntityHighlightController()
                {
                    m_interiorsCellResourceObserver.UnregisterAddedToSceneGraphCallback(m_interiorCellAddedHandler);

                    m_messageBus.UnsubscribeUi(m_searchQueryResponseHandler);

                    m_searchQueryPerformer.RemoveOnSearchResultsClearedCallback(m_searchResultsClearedHandler);
                    m_interiorInteractionModel.UnregisterModelChangedCallback(m_interiorInteractionModelChangedHandler);

                    m_messageBus.UnsubscribeNative(m_handleSearchResultSectionItemSelectedMessageBinding);
                }

                void InteriorEntityHighlightController::OnAvailabilityChanged()
                {
                }

                void InteriorEntityHighlightController::RemoveHighlights()
                {
                    m_interiorsHighlightService.ClearAllHighlights();

                }

                void InteriorEntityHighlightController::ActivateLabels(bool active)
                {
                    m_labelHiddenFilterModel.SetFilter(m_interiorLabelLayer, active ? NULL : &m_hideLabelByNameFilter);
                }

                void InteriorEntityHighlightController::OnInteriorLabelsBuilt()
                {
                    ApplyHighlightsForCurrentResults();
                    bool hasResults = m_searchResults.size() > 0;
                    ActivateLabels(!hasResults);
                }

                void InteriorEntityHighlightController::OnSearchResultCleared()
                {
                    m_searchResultsIndex = -1;
                    m_searchResults.clear();
                    RemoveHighlights();
                    ApplyHighlightsForCurrentResults();
                    ActivateLabels(true);
                }

                void InteriorEntityHighlightController::OnSearchItemSelected(const SearchResultSection::SearchResultSectionItemSelectedMessage& message)
                {
                    if (message.ItemIndex() >= m_searchResults.size())
                    {
                        m_searchResultsIndex = -1;
                    }
                    else
                    {
                        m_searchResultsIndex = message.ItemIndex();
                    }

                    ApplyHighlightsForCurrentResults();
                }

                void InteriorEntityHighlightController::OnInteriorChanged()
                {
                    namespace EegeoInteriors = Eegeo::Resources::Interiors;
                    namespace EegeoRenderables = Eegeo::Rendering::Renderables;

                    RemoveHighlights();
                    m_currentHighlightRenderables.clear();

                    if (m_interiorInteractionModel.HasInteriorModel())
                    {
                        const EegeoInteriors::InteriorsModel& model = *m_interiorInteractionModel.GetInteriorModel();

                        for (EegeoInteriors::TFloorModelVector::const_iterator floors = model.GetFloors().begin();
                             floors != model.GetFloors().end();
                             ++floors)
                        {
                            const EegeoInteriors::InteriorsFloorCells* floorCells = model.GetFloorCells((*floors)->GetFloorNumber());

                            for (int cellIndex = 0; cellIndex < floorCells->GetCellCount(); ++cellIndex)
                            {
                                const EegeoInteriors::InteriorsFloorCell* cell = floorCells->GetFloorCells()[cellIndex];
                                std::vector<EegeoRenderables::InteriorHighlightRenderable*> renderables = cell->GetHighlightRenderables();

                                for (std::vector<EegeoRenderables::InteriorHighlightRenderable*>::iterator renderableIterator = renderables.begin();
                                     renderableIterator != renderables.end();
                                     ++renderableIterator)
                                {
                                    AddHighlight(**renderableIterator);
                                }
                            }
                        }

                        RemoveHighlights();
                        bool hasResults = m_searchResults.size() > 0;
                        ActivateLabels(!hasResults);
                    }
                    else
                    {
                        RemoveHighlights();
                        m_currentHighlightRenderables.clear();
                    }
                }

                void InteriorEntityHighlightController::OnInteriorAddedToSceneGraph(const Eegeo::Resources::Interiors::InteriorsCellResource& resource)
                {
                    if (m_interiorInteractionModel.HasInteriorModel())
                    {
                        const Eegeo::Resources::Interiors::InteriorsModel& model = *m_interiorInteractionModel.GetInteriorModel();
                        if (model.GetId() == resource.GetInteriorId())
                        {
                            OnInteriorChanged();
                        }
                    }
                }

                void InteriorEntityHighlightController::AddHighlight(Eegeo::Rendering::Renderables::InteriorHighlightRenderable& renderable)
                {
                    static const std::string highlightPrefix = "entity_highlight ";
                    const std::string& id = renderable.GetRenderableId();

                    if (id.compare(0, highlightPrefix.length(), highlightPrefix) == 0)
                    {
                        std::string highlightId = id.substr(highlightPrefix.length());
                        if (m_currentHighlightRenderables.find(highlightId) == m_currentHighlightRenderables.end())
                        {
                            std::vector<Eegeo::Rendering::Renderables::InteriorHighlightRenderable*> highlights;
                            m_currentHighlightRenderables.insert(std::make_pair(highlightId, highlights));
                        }
                        m_currentHighlightRenderables[highlightId].push_back(&renderable);
                    }
                }

                void InteriorEntityHighlightController::OnSearchQueryResponseReceived(const Search::SearchQueryResponseReceivedMessage& message)
                {
                    auto results = message.GetResults();
                    RemoveHighlights();
                    if (m_searchResultsIndex >= 0)
                    {
                        const Search::SdkModel::SearchResultModel& selectedSearchResult = m_searchResults.at(m_searchResultsIndex);

                        const std::vector<Search::SdkModel::SearchResultModel>& newSearchResults = results;

                        std::vector<Search::SdkModel::SearchResultModel>::const_iterator iter = std::find(newSearchResults.begin(), newSearchResults.end(), selectedSearchResult);
                        if (iter == newSearchResults.end())
                        {
                            m_searchResultsIndex = -1;
                        }
                        else
                        {
                            m_searchResultsIndex = static_cast<int>(std::distance(newSearchResults.begin(), iter));
                        }
                    }

                    m_searchResults = results;
                    ApplyHighlightsForCurrentResults();

                    bool hasResults = results.size() > 0;
                    ActivateLabels(!hasResults);
                }

                std::vector<Search::SdkModel::SearchResultModel> InteriorEntityHighlightController::GetCurrentSearchResults()
                {
                    std::vector<Search::SdkModel::SearchResultModel> results;
                    results.reserve(m_searchResults.size());

                    for (int i = 0; i < m_searchResults.size(); i++)
                    {
                        Search::SdkModel::SearchResultModel pResult = m_searchResults.at(i);
                        results.push_back(pResult);
                    }
                    return results;
                }

                void InteriorEntityHighlightController::ApplyHighlightsForCurrentResults()
                {
                    std::vector<Search::SdkModel::SearchResultModel> results = GetCurrentSearchResults();
                    ApplyHighlights(results);
                }

                void InteriorEntityHighlightController::HighlightSearchResult(const Search::SdkModel::SearchResultModel &searchResult)
                {
                    if (!searchResult.IsInterior())
                    {
                        return;
                    }
                    rapidjson::Document json;
                    std::string highlightedRoomId = "";

                    std::vector<std::string> filteredEntityIds = GetEntityIdsFromSearchResultModel(searchResult);
                    std::vector<Eegeo::v4> highlightColors = m_highlightColorMapper.GetColors(searchResult);

                    if (m_interiorInteractionModel.HasInteriorModel())
                    {
                        const std::string& interiorId = m_interiorInteractionModel.GetInteriorModel()->GetId().Value();
                        m_interiorsHighlightService.SetHighlights(interiorId, filteredEntityIds, highlightColors.front());
                     }
                }

                void InteriorEntityHighlightController::ApplyHighlights(const std::vector<Search::SdkModel::SearchResultModel> &results)
                {
                    RemoveHighlights();

                    if (m_interiorInteractionModel.HasInteriorModel() && m_currentHighlightRenderables.size() == 0)
                    {
                        OnInteriorChanged();
                    }

                    rapidjson::Document json;
                    std::string highlightedRoomId = "";

                    if (m_searchResultsIndex >= 0)
                    {
                        const Search::SdkModel::SearchResultModel& resultsItt = m_searchResults.at(m_searchResultsIndex);
                        HighlightSearchResult(resultsItt);
                    }
                    else
                    {
                        for (std::vector<Search::SdkModel::SearchResultModel>::const_iterator resultsItt = results.begin(); resultsItt != results.end(); ++resultsItt)
                        {
                            HighlightSearchResult(*resultsItt);
                        }
                    }
                }

                bool InteriorEntityHighlightController::HideLabelAlwaysPredicate(const Eegeo::Labels::IAnchoredLabel& anchoredLabel) const
                {
                    return true;
                }

                bool InteriorEntityHighlightController::HideLabelByNamePredicate(const Eegeo::Labels::IAnchoredLabel& anchoredLabel) const
                {
                    const std::string& labelCategoryName = anchoredLabel.GetLabelAnchorCategory().GetId();
                    bool shouldHide =  labelCategoryName != "interior_facility_escalator"
                    && labelCategoryName != "interior_facility_stairs"
                    && labelCategoryName != "interior_facility_elevator"
                    && labelCategoryName != "interior_facility_toilets";
                    return shouldHide;
                }
            }
        }
    }
}
<commit_msg>Add re-highlight after re-render, buddy Salvador G<commit_after>// Copyright eeGeo Ltd (2012-2015), All Rights Reserved

#include "InteriorEntityHighlightController.h"
#include "ISearchService.h"
#include "ISearchQueryPerformer.h"
#include "ISearchResultRepository.h"
#include "InteriorInteractionModel.h"
#include "InteriorsModel.h"
#include "InteriorsFloorModel.h"
#include "IInteriorsLabelController.h"
#include "VectorMath.h"
#include "InteriorHighlightRenderable.h"
#include "InteriorsLabelParser.h"
#include "InteriorsFloorCells.h"
#include "InteriorsFloorCell.h"
#include "PlaceNameModel.h"
#include "InteriorsCellResource.h"
#include "InteriorsCellResourceObserver.h"
#include "LabelAnchorFilterModel.h"
#include "IAnchoredLabel.h"
#include "document.h"
#include "IInteriorsHighlightService.h"

namespace ExampleApp
{
    namespace InteriorsExplorer
    {
        namespace SdkModel
        {
            namespace Highlights
            {
                std::vector<std::string> GetEntityIdsFromJsonArray(const rapidjson::Value& jsonArray)
                {
                    assert(jsonArray.IsArray());
                    std::vector<std::string> entities;

                    for (int i  = 0; i < jsonArray.Size(); i++)
                    {
                        assert(jsonArray[i].IsString());
                        entities.push_back(jsonArray[i].GetString());
                    }

                    return entities;
                }

                std::vector<std::string> GetEntityIdsFromSearchResultModel(const Search::SdkModel::SearchResultModel& selectedSearchResult)
                {
                    rapidjson::Document json;
                    std::vector<std::string> entities;

                    if (!json.Parse<0>(selectedSearchResult.GetJsonData().c_str()).HasParseError())
                    {
                        if( json.HasMember("highlight")  )
                        {
                            const rapidjson::Value& area_highlight = json["highlight"];
                            if(area_highlight.IsString())
                            {
                                entities.push_back(json["highlight"].GetString());
                            }
                            else
                            {
                                std::vector<std::string> areaHighlights = GetEntityIdsFromJsonArray(area_highlight);
                                entities.insert(std::end(entities), std::begin(areaHighlights), std::end(areaHighlights));
                            }
                        }

                        if(  json.HasMember("entity_highlight")  )
                        {
                            std::vector<std::string> entityHighlights = GetEntityIdsFromJsonArray(json["entity_highlight"]);
                            entities.insert(std::end(entities), std::begin(entityHighlights), std::end(entityHighlights));
                        }
                    }

                    return entities;
                }

                InteriorEntityHighlightController::InteriorEntityHighlightController(Eegeo::Resources::Interiors::InteriorInteractionModel& interiorInteractionModel,
                                                                                Eegeo::Resources::Interiors::InteriorsCellResourceObserver& interiorsCellResourceObserver,
                                                                                Search::SdkModel::ISearchService& searchService,
                                                                                Search::SdkModel::ISearchQueryPerformer& searchQueryPerformer, Eegeo::Resources::Interiors::Entities::IInteriorsLabelController& legacyLabelController,
                                                                                Eegeo::Labels::ILabelAnchorFilterModel& labelHiddenFilterModel,
                                                                                const Eegeo::Labels::LabelLayer::IdType interiorLabelLayer,
                                                                                ExampleAppMessaging::TMessageBus& messageBus,
                                                                                IHighlightColorMapper& highlightColorMapper,
                                                                                Eegeo::Resources::Interiors::Highlights::IInteriorsHighlightService& interiorsHighlightService)
                : m_interiorInteractionModel(interiorInteractionModel)
                , m_interiorsCellResourceObserver(interiorsCellResourceObserver)
                , m_interiorLabelLayer(interiorLabelLayer)
                , m_labelHiddenFilterModel(labelHiddenFilterModel)
                , m_searchQueryPerformer(searchQueryPerformer)
                , m_highlightColorMapper(highlightColorMapper)
                , m_searchResultsIndex(-1)
                , m_searchQueryResponseHandler(this, &InteriorEntityHighlightController::OnSearchQueryResponseReceived)
                , m_searchResultsClearedHandler(this, &InteriorEntityHighlightController::OnSearchResultCleared)
                , m_handleSearchResultSectionItemSelectedMessageBinding(this, &InteriorEntityHighlightController::OnSearchItemSelected)
                , m_interiorInteractionModelChangedHandler(this, &InteriorEntityHighlightController::OnInteriorChanged)
                , m_interiorCellAddedHandler(this, &InteriorEntityHighlightController::OnInteriorAddedToSceneGraph)
                , m_availabilityChangedHandlerBinding(this, &InteriorEntityHighlightController::OnAvailabilityChanged)
                , m_interiorLabelsBuiltHandler(this, &InteriorEntityHighlightController::OnInteriorLabelsBuilt)
                , m_interiorsHighlightService(interiorsHighlightService)
                , m_messageBus(messageBus)
                , m_hideLabelAlwaysFilter(this, &InteriorEntityHighlightController::HideLabelAlwaysPredicate)
                , m_hideLabelByNameFilter(this, &InteriorEntityHighlightController::HideLabelByNamePredicate)
                {
                    m_messageBus.SubscribeUi(m_searchQueryResponseHandler);
                    m_searchQueryPerformer.InsertOnSearchResultsClearedCallback(m_searchResultsClearedHandler);
                    m_interiorInteractionModel.RegisterModelChangedCallback(m_interiorInteractionModelChangedHandler);

                    m_interiorsCellResourceObserver.RegisterAddedToSceneGraphCallback(m_interiorCellAddedHandler);
                    m_messageBus.SubscribeNative(m_handleSearchResultSectionItemSelectedMessageBinding);
                    m_labelHiddenFilterModel.SetFilter(m_interiorLabelLayer, &m_hideLabelAlwaysFilter);
                }

                InteriorEntityHighlightController::~InteriorEntityHighlightController()
                {
                    m_interiorsCellResourceObserver.UnregisterAddedToSceneGraphCallback(m_interiorCellAddedHandler);

                    m_messageBus.UnsubscribeUi(m_searchQueryResponseHandler);

                    m_searchQueryPerformer.RemoveOnSearchResultsClearedCallback(m_searchResultsClearedHandler);
                    m_interiorInteractionModel.UnregisterModelChangedCallback(m_interiorInteractionModelChangedHandler);

                    m_messageBus.UnsubscribeNative(m_handleSearchResultSectionItemSelectedMessageBinding);
                }

                void InteriorEntityHighlightController::OnAvailabilityChanged()
                {
                }

                void InteriorEntityHighlightController::RemoveHighlights()
                {
                    m_interiorsHighlightService.ClearAllHighlights();

                }

                void InteriorEntityHighlightController::ActivateLabels(bool active)
                {
                    m_labelHiddenFilterModel.SetFilter(m_interiorLabelLayer, active ? NULL : &m_hideLabelByNameFilter);
                }

                void InteriorEntityHighlightController::OnInteriorLabelsBuilt()
                {
                    ApplyHighlightsForCurrentResults();
                    bool hasResults = m_searchResults.size() > 0;
                    ActivateLabels(!hasResults);
                }

                void InteriorEntityHighlightController::OnSearchResultCleared()
                {
                    m_searchResultsIndex = -1;
                    m_searchResults.clear();
                    RemoveHighlights();
                    ApplyHighlightsForCurrentResults();
                    ActivateLabels(true);
                }

                void InteriorEntityHighlightController::OnSearchItemSelected(const SearchResultSection::SearchResultSectionItemSelectedMessage& message)
                {
                    if (message.ItemIndex() >= m_searchResults.size())
                    {
                        m_searchResultsIndex = -1;
                    }
                    else
                    {
                        m_searchResultsIndex = message.ItemIndex();
                    }

                    ApplyHighlightsForCurrentResults();
                }

                void InteriorEntityHighlightController::OnInteriorChanged()
                {
                    namespace EegeoInteriors = Eegeo::Resources::Interiors;
                    namespace EegeoRenderables = Eegeo::Rendering::Renderables;

                    RemoveHighlights();
                    m_currentHighlightRenderables.clear();

                    if (m_interiorInteractionModel.HasInteriorModel())
                    {
                        const EegeoInteriors::InteriorsModel& model = *m_interiorInteractionModel.GetInteriorModel();

                        for (EegeoInteriors::TFloorModelVector::const_iterator floors = model.GetFloors().begin();
                             floors != model.GetFloors().end();
                             ++floors)
                        {
                            const EegeoInteriors::InteriorsFloorCells* floorCells = model.GetFloorCells((*floors)->GetFloorNumber());

                            for (int cellIndex = 0; cellIndex < floorCells->GetCellCount(); ++cellIndex)
                            {
                                const EegeoInteriors::InteriorsFloorCell* cell = floorCells->GetFloorCells()[cellIndex];
                                std::vector<EegeoRenderables::InteriorHighlightRenderable*> renderables = cell->GetHighlightRenderables();

                                for (std::vector<EegeoRenderables::InteriorHighlightRenderable*>::iterator renderableIterator = renderables.begin();
                                     renderableIterator != renderables.end();
                                     ++renderableIterator)
                                {
                                    AddHighlight(**renderableIterator);
                                }
                            }
                        }

                        RemoveHighlights();
                        bool hasResults = m_searchResults.size() > 0;
                        ActivateLabels(!hasResults);
                    }
                    else
                    {
                        RemoveHighlights();
                        m_currentHighlightRenderables.clear();
                    }
                }

                void InteriorEntityHighlightController::OnInteriorAddedToSceneGraph(const Eegeo::Resources::Interiors::InteriorsCellResource& resource)
                {
                    if (m_interiorInteractionModel.HasInteriorModel())
                    {
                        const Eegeo::Resources::Interiors::InteriorsModel& model = *m_interiorInteractionModel.GetInteriorModel();
                        if (model.GetId() == resource.GetInteriorId())
                        {
                            OnInteriorChanged();
                            ApplyHighlightsForCurrentResults();
                        }
                    }
                }

                void InteriorEntityHighlightController::AddHighlight(Eegeo::Rendering::Renderables::InteriorHighlightRenderable& renderable)
                {
                    static const std::string highlightPrefix = "entity_highlight ";
                    const std::string& id = renderable.GetRenderableId();

                    if (id.compare(0, highlightPrefix.length(), highlightPrefix) == 0)
                    {
                        std::string highlightId = id.substr(highlightPrefix.length());
                        if (m_currentHighlightRenderables.find(highlightId) == m_currentHighlightRenderables.end())
                        {
                            std::vector<Eegeo::Rendering::Renderables::InteriorHighlightRenderable*> highlights;
                            m_currentHighlightRenderables.insert(std::make_pair(highlightId, highlights));
                        }
                        m_currentHighlightRenderables[highlightId].push_back(&renderable);
                    }
                }

                void InteriorEntityHighlightController::OnSearchQueryResponseReceived(const Search::SearchQueryResponseReceivedMessage& message)
                {
                    auto results = message.GetResults();
                    RemoveHighlights();
                    if (m_searchResultsIndex >= 0)
                    {
                        const Search::SdkModel::SearchResultModel& selectedSearchResult = m_searchResults.at(m_searchResultsIndex);

                        const std::vector<Search::SdkModel::SearchResultModel>& newSearchResults = results;

                        std::vector<Search::SdkModel::SearchResultModel>::const_iterator iter = std::find(newSearchResults.begin(), newSearchResults.end(), selectedSearchResult);
                        if (iter == newSearchResults.end())
                        {
                            m_searchResultsIndex = -1;
                        }
                        else
                        {
                            m_searchResultsIndex = static_cast<int>(std::distance(newSearchResults.begin(), iter));
                        }
                    }

                    m_searchResults = results;
                    ApplyHighlightsForCurrentResults();

                    bool hasResults = results.size() > 0;
                    ActivateLabels(!hasResults);
                }

                std::vector<Search::SdkModel::SearchResultModel> InteriorEntityHighlightController::GetCurrentSearchResults()
                {
                    std::vector<Search::SdkModel::SearchResultModel> results;
                    results.reserve(m_searchResults.size());

                    for (int i = 0; i < m_searchResults.size(); i++)
                    {
                        Search::SdkModel::SearchResultModel pResult = m_searchResults.at(i);
                        results.push_back(pResult);
                    }
                    return results;
                }

                void InteriorEntityHighlightController::ApplyHighlightsForCurrentResults()
                {
                    std::vector<Search::SdkModel::SearchResultModel> results = GetCurrentSearchResults();
                    ApplyHighlights(results);
                }

                void InteriorEntityHighlightController::HighlightSearchResult(const Search::SdkModel::SearchResultModel &searchResult)
                {
                    if (!searchResult.IsInterior())
                    {
                        return;
                    }
                    rapidjson::Document json;
                    std::string highlightedRoomId = "";

                    std::vector<std::string> filteredEntityIds = GetEntityIdsFromSearchResultModel(searchResult);
                    std::vector<Eegeo::v4> highlightColors = m_highlightColorMapper.GetColors(searchResult);

                    if (m_interiorInteractionModel.HasInteriorModel())
                    {
                        const std::string& interiorId = m_interiorInteractionModel.GetInteriorModel()->GetId().Value();
                        m_interiorsHighlightService.SetHighlights(interiorId, filteredEntityIds, highlightColors.front());
                     }
                }

                void InteriorEntityHighlightController::ApplyHighlights(const std::vector<Search::SdkModel::SearchResultModel> &results)
                {
                    RemoveHighlights();

                    if (m_interiorInteractionModel.HasInteriorModel() && m_currentHighlightRenderables.size() == 0)
                    {
                        OnInteriorChanged();
                    }

                    rapidjson::Document json;
                    std::string highlightedRoomId = "";

                    if (m_searchResultsIndex >= 0)
                    {
                        const Search::SdkModel::SearchResultModel& resultsItt = m_searchResults.at(m_searchResultsIndex);
                        HighlightSearchResult(resultsItt);
                    }
                    else
                    {
                        for (std::vector<Search::SdkModel::SearchResultModel>::const_iterator resultsItt = results.begin(); resultsItt != results.end(); ++resultsItt)
                        {
                            HighlightSearchResult(*resultsItt);
                        }
                    }
                }

                bool InteriorEntityHighlightController::HideLabelAlwaysPredicate(const Eegeo::Labels::IAnchoredLabel& anchoredLabel) const
                {
                    return true;
                }

                bool InteriorEntityHighlightController::HideLabelByNamePredicate(const Eegeo::Labels::IAnchoredLabel& anchoredLabel) const
                {
                    const std::string& labelCategoryName = anchoredLabel.GetLabelAnchorCategory().GetId();
                    bool shouldHide =  labelCategoryName != "interior_facility_escalator"
                    && labelCategoryName != "interior_facility_stairs"
                    && labelCategoryName != "interior_facility_elevator"
                    && labelCategoryName != "interior_facility_toilets";
                    return shouldHide;
                }
            }
        }
    }
}
<|endoftext|>


<commit_before>/***************************************************************************
                          knnntpaccount.cpp  -  description
                             -------------------

    copyright            : (C) 2000 by Christian Thurner
    email                : cthurner@freepage.de
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

#include <ksimpleconfig.h>
#include <kstddirs.h>

#include "utilities.h"
#include "knnntpaccount.h"

KNNntpAccount::KNNntpAccount()
  : KNCollection(0), KNServerInfo(), u_nsentCount(0), f_etchDescriptions(true)
{
  l_astNewFetch = QDate::currentDate();
}

KNNntpAccount::~KNNntpAccount()
{
}

// trys to read information, returns false if it fails to do so
bool KNNntpAccount::readInfo(const QString &confPath)
{
  KSimpleConfig conf(confPath);

  n_ame = conf.readEntry("name");
  u_nsentCount = conf.readNumEntry("unsentCnt", 0);
  f_etchDescriptions = conf.readBoolEntry("fetchDescriptions", true);
  l_astNewFetch = conf.readDateTimeEntry("lastNewFetch").date();

  KNServerInfo::readConf(&conf);
  return true;
  if (n_ame.isEmpty() || s_erver.isEmpty() || i_d == -1)
    return false;
  else
    return true;
}

void KNNntpAccount::saveInfo()
{
  QString dir(path());
  if (dir == QString::null)
    return;

  KSimpleConfig conf(dir+"info");

  conf.writeEntry("name", n_ame);
  conf.writeEntry("unsentCnt", u_nsentCount);
  conf.writeEntry("fetchDescriptions", f_etchDescriptions);
  conf.writeEntry("lastNewFetch", QDateTime(l_astNewFetch));
  KNServerInfo::saveConf(&conf);      // save not KNNntpAccount specific settings
}

void KNNntpAccount::syncInfo()
{
  QString dir(path());
  if (dir == QString::null)
    return;
  KSimpleConfig conf(dir+"info");
  conf.writeEntry("unsentCnt", u_nsentCount);
}

QString KNNntpAccount::path()
{
  QString dir(KGlobal::dirs()->saveLocation("appdata",QString("nntp.%1/").arg(i_d)));
  if (dir==QString::null)
    displayInternalFileError();
  return (dir);
}

<commit_msg>arghhh, my fault, I comitted this in june. should fix the "ghost" accounts (#8846)<commit_after>/***************************************************************************
                          knnntpaccount.cpp  -  description
                             -------------------

    copyright            : (C) 2000 by Christian Thurner
    email                : cthurner@freepage.de
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

#include <ksimpleconfig.h>
#include <kstddirs.h>

#include "utilities.h"
#include "knnntpaccount.h"

KNNntpAccount::KNNntpAccount()
  : KNCollection(0), KNServerInfo(), u_nsentCount(0), f_etchDescriptions(true)
{
  l_astNewFetch = QDate::currentDate();
}

KNNntpAccount::~KNNntpAccount()
{
}

// trys to read information, returns false if it fails to do so
bool KNNntpAccount::readInfo(const QString &confPath)
{
  KSimpleConfig conf(confPath);

  n_ame = conf.readEntry("name");
  u_nsentCount = conf.readNumEntry("unsentCnt", 0);
  f_etchDescriptions = conf.readBoolEntry("fetchDescriptions", true);
  l_astNewFetch = conf.readDateTimeEntry("lastNewFetch").date();

  KNServerInfo::readConf(&conf);

  if (n_ame.isEmpty() || s_erver.isEmpty() || i_d == -1)
    return false;
  else
    return true;
}

void KNNntpAccount::saveInfo()
{
  QString dir(path());
  if (dir == QString::null)
    return;

  KSimpleConfig conf(dir+"info");

  conf.writeEntry("name", n_ame);
  conf.writeEntry("unsentCnt", u_nsentCount);
  conf.writeEntry("fetchDescriptions", f_etchDescriptions);
  conf.writeEntry("lastNewFetch", QDateTime(l_astNewFetch));
  KNServerInfo::saveConf(&conf);      // save not KNNntpAccount specific settings
}

void KNNntpAccount::syncInfo()
{
  QString dir(path());
  if (dir == QString::null)
    return;
  KSimpleConfig conf(dir+"info");
  conf.writeEntry("unsentCnt", u_nsentCount);
}

QString KNNntpAccount::path()
{
  QString dir(KGlobal::dirs()->saveLocation("appdata",QString("nntp.%1/").arg(i_d)));
  if (dir==QString::null)
    displayInternalFileError();
  return (dir);
}

<|endoftext|>


<commit_before><commit_msg>Update BinaryTree.cpp<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "media/audio/mac/audio_low_latency_output_mac.h"

#include <CoreServices/CoreServices.h>

#include "base/basictypes.h"
#include "base/logging.h"
#include "media/audio/audio_util.h"
#include "media/audio/mac/audio_manager_mac.h"

using media::SwizzleCoreAudioLayout5_1;

// Overview of operation:
// 1) An object of AUAudioOutputStream is created by the AudioManager
// factory: audio_man->MakeAudioStream().
// 2) Next some thread will call Open(), at that point the underlying
// default output Audio Unit is created and configured.
// 3) Then some thread will call Start(source).
// Then the Audio Unit is started which creates its own thread which
// periodically will call the source for more data as buffers are being
// consumed.
// 4) At some point some thread will call Stop(), which we handle by directly
// stopping the default output Audio Unit.
// 6) The same thread that called stop will call Close() where we cleanup
// and notify the audio manager, which likely will destroy this object.

AUAudioOutputStream::AUAudioOutputStream(
    AudioManagerMac* manager, AudioParameters params)
    : manager_(manager),
      source_(NULL),
      output_unit_(0),
      volume_(1) {
  // We must have a manager.
  DCHECK(manager_);
  // A frame is one sample across all channels. In interleaved audio the per
  // frame fields identify the set of n |channels|. In uncompressed audio, a
  // packet is always one frame.
  format_.mSampleRate = params.sample_rate;
  format_.mFormatID = kAudioFormatLinearPCM;
  format_.mFormatFlags = kLinearPCMFormatFlagIsPacked |
                         kLinearPCMFormatFlagIsSignedInteger;
  format_.mBitsPerChannel = params.bits_per_sample;
  format_.mChannelsPerFrame = params.channels;
  format_.mFramesPerPacket = 1;
  format_.mBytesPerPacket = (format_.mBitsPerChannel * params.channels) / 8;
  format_.mBytesPerFrame = format_.mBytesPerPacket;

  // Calculate the number of sample frames per callback.
  number_of_frames_ = params.GetPacketSize() / format_.mBytesPerPacket;
}

AUAudioOutputStream::~AUAudioOutputStream() {
}

bool AUAudioOutputStream::Open() {
  // Open and initialize the DefaultOutputUnit.
  Component comp;
  ComponentDescription desc;

  desc.componentType = kAudioUnitType_Output;
  desc.componentSubType = kAudioUnitSubType_DefaultOutput;
  desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  desc.componentFlags = 0;
  desc.componentFlagsMask = 0;
  comp = FindNextComponent(0, &desc);
  DCHECK(comp);

  OSStatus result = OpenAComponent(comp, &output_unit_);
  DCHECK_EQ(result, 0);
  if (result)
    return false;

  result = AudioUnitInitialize(output_unit_);

  DCHECK_EQ(result, 0);
  if (result)
    return false;

  return Configure();
}

bool AUAudioOutputStream::Configure() {
  // Set the render callback.
  AURenderCallbackStruct input;
  input.inputProc = InputProc;
  input.inputProcRefCon = this;
  OSStatus result = AudioUnitSetProperty(
      output_unit_,
      kAudioUnitProperty_SetRenderCallback,
      kAudioUnitScope_Global,
      0,
      &input,
      sizeof(input));

  DCHECK_EQ(result, 0);
  if (result)
    return false;

  // Set the stream format.
  result = AudioUnitSetProperty(
      output_unit_,
      kAudioUnitProperty_StreamFormat,
      kAudioUnitScope_Input,
      0,
      &format_,
      sizeof(format_));
  DCHECK_EQ(result, 0);
  if (result)
    return false;

  // Set the buffer frame size.
  UInt32 buffer_size = number_of_frames_;
  result = AudioUnitSetProperty(
      output_unit_,
      kAudioDevicePropertyBufferFrameSize,
      kAudioUnitScope_Output,
      0,
      &buffer_size,
      sizeof(buffer_size));
  DCHECK_EQ(result, 0);
  if (result)
    return false;

  return true;
}

void AUAudioOutputStream::Close() {
  if (output_unit_)
    CloseComponent(output_unit_);

  // Inform the audio manager that we have been closed. This can cause our
  // destruction.
  manager_->ReleaseOutputStream(this);
}

void AUAudioOutputStream::Start(AudioSourceCallback* callback) {
  DCHECK(callback);
  source_ = callback;

  AudioOutputUnitStart(output_unit_);
}

void AUAudioOutputStream::Stop() {
  // We request a synchronous stop, so the next call can take some time. In
  // the windows implementation we block here as well.
  source_ = NULL;

  AudioOutputUnitStop(output_unit_);
}

void AUAudioOutputStream::SetVolume(double volume) {
  if (!output_unit_)
    return;
  volume_ = static_cast<float>(volume);

  // TODO(crogers): set volume property
}

void AUAudioOutputStream::GetVolume(double* volume) {
  if (!output_unit_)
    return;
  *volume = volume_;
}

// Pulls on our provider to get rendered audio stream.
// Note to future hackers of this function: Do not add locks here because this
// is running on a real-time thread (for low-latency).
OSStatus AUAudioOutputStream::Render(UInt32 number_of_frames,
                                     AudioBufferList* io_data) {
  AudioBuffer& buffer = io_data->mBuffers[0];
  uint8* audio_data = reinterpret_cast<uint8*>(buffer.mData);
  uint32 filled = source_->OnMoreData(
      this, audio_data, buffer.mDataByteSize, AudioBuffersState(0, 0));

  // Handle channel order for 5.1 audio.
  if (format_.mChannelsPerFrame == 6) {
    if (format_.mBitsPerChannel == 8) {
      SwizzleCoreAudioLayout5_1(reinterpret_cast<uint8*>(audio_data), filled);
    } else if (format_.mBitsPerChannel == 16) {
      SwizzleCoreAudioLayout5_1(reinterpret_cast<int16*>(audio_data), filled);
    } else if (format_.mBitsPerChannel == 32) {
      SwizzleCoreAudioLayout5_1(reinterpret_cast<int32*>(audio_data), filled);
    }
  }

  return noErr;
}

// DefaultOutputUnit callback
OSStatus AUAudioOutputStream::InputProc(void* user_data,
                                        AudioUnitRenderActionFlags*,
                                        const AudioTimeStamp*,
                                        UInt32,
                                        UInt32 number_of_frames,
                                        AudioBufferList* io_data) {
  AUAudioOutputStream* audio_output =
      static_cast<AUAudioOutputStream*>(user_data);
  DCHECK(audio_output);
  if (!audio_output)
    return -1;

  return audio_output->Render(number_of_frames, io_data);
}

double AUAudioOutputStream::HardwareSampleRate() {
  // Determine the default output device's sample-rate.
  AudioDeviceID device_id = kAudioDeviceUnknown;
  UInt32 info_size = sizeof(device_id);

  AudioObjectPropertyAddress default_input_device_address = {
      kAudioHardwarePropertyDefaultInputDevice,
      kAudioObjectPropertyScopeGlobal,
      kAudioObjectPropertyElementMaster
  };
  OSStatus result = AudioObjectGetPropertyData(kAudioObjectSystemObject,
                                               &default_input_device_address,
                                               0,
                                               0,
                                               &info_size,
                                               &device_id);
  DCHECK_EQ(result, 0);
  if (result)
    return 0.0;  // error

  Float64 nominal_sample_rate;
  info_size = sizeof(nominal_sample_rate);

  AudioObjectPropertyAddress nominal_sample_rate_address = {
      kAudioDevicePropertyNominalSampleRate,
      kAudioObjectPropertyScopeGlobal,
      kAudioObjectPropertyElementMaster
  };
  result = AudioObjectGetPropertyData(device_id,
                                      &nominal_sample_rate_address,
                                      0,
                                      0,
                                      &info_size,
                                      &nominal_sample_rate);
  DCHECK_EQ(result, 0);
  if (result)
    return 0.0;  // error

  return nominal_sample_rate;
}
<commit_msg>Use default "output" rather than "input" device when querying hardware sample-rate BUG=none TEST=none (tested locally on Mac OS X to verify that hardware sample-rate is correctly retrieved) Review URL: http://codereview.chromium.org/6721001<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "media/audio/mac/audio_low_latency_output_mac.h"

#include <CoreServices/CoreServices.h>

#include "base/basictypes.h"
#include "base/logging.h"
#include "media/audio/audio_util.h"
#include "media/audio/mac/audio_manager_mac.h"

using media::SwizzleCoreAudioLayout5_1;

// Overview of operation:
// 1) An object of AUAudioOutputStream is created by the AudioManager
// factory: audio_man->MakeAudioStream().
// 2) Next some thread will call Open(), at that point the underlying
// default output Audio Unit is created and configured.
// 3) Then some thread will call Start(source).
// Then the Audio Unit is started which creates its own thread which
// periodically will call the source for more data as buffers are being
// consumed.
// 4) At some point some thread will call Stop(), which we handle by directly
// stopping the default output Audio Unit.
// 6) The same thread that called stop will call Close() where we cleanup
// and notify the audio manager, which likely will destroy this object.

AUAudioOutputStream::AUAudioOutputStream(
    AudioManagerMac* manager, AudioParameters params)
    : manager_(manager),
      source_(NULL),
      output_unit_(0),
      volume_(1) {
  // We must have a manager.
  DCHECK(manager_);
  // A frame is one sample across all channels. In interleaved audio the per
  // frame fields identify the set of n |channels|. In uncompressed audio, a
  // packet is always one frame.
  format_.mSampleRate = params.sample_rate;
  format_.mFormatID = kAudioFormatLinearPCM;
  format_.mFormatFlags = kLinearPCMFormatFlagIsPacked |
                         kLinearPCMFormatFlagIsSignedInteger;
  format_.mBitsPerChannel = params.bits_per_sample;
  format_.mChannelsPerFrame = params.channels;
  format_.mFramesPerPacket = 1;
  format_.mBytesPerPacket = (format_.mBitsPerChannel * params.channels) / 8;
  format_.mBytesPerFrame = format_.mBytesPerPacket;

  // Calculate the number of sample frames per callback.
  number_of_frames_ = params.GetPacketSize() / format_.mBytesPerPacket;
}

AUAudioOutputStream::~AUAudioOutputStream() {
}

bool AUAudioOutputStream::Open() {
  // Open and initialize the DefaultOutputUnit.
  Component comp;
  ComponentDescription desc;

  desc.componentType = kAudioUnitType_Output;
  desc.componentSubType = kAudioUnitSubType_DefaultOutput;
  desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  desc.componentFlags = 0;
  desc.componentFlagsMask = 0;
  comp = FindNextComponent(0, &desc);
  DCHECK(comp);

  OSStatus result = OpenAComponent(comp, &output_unit_);
  DCHECK_EQ(result, 0);
  if (result)
    return false;

  result = AudioUnitInitialize(output_unit_);

  DCHECK_EQ(result, 0);
  if (result)
    return false;

  return Configure();
}

bool AUAudioOutputStream::Configure() {
  // Set the render callback.
  AURenderCallbackStruct input;
  input.inputProc = InputProc;
  input.inputProcRefCon = this;
  OSStatus result = AudioUnitSetProperty(
      output_unit_,
      kAudioUnitProperty_SetRenderCallback,
      kAudioUnitScope_Global,
      0,
      &input,
      sizeof(input));

  DCHECK_EQ(result, 0);
  if (result)
    return false;

  // Set the stream format.
  result = AudioUnitSetProperty(
      output_unit_,
      kAudioUnitProperty_StreamFormat,
      kAudioUnitScope_Input,
      0,
      &format_,
      sizeof(format_));
  DCHECK_EQ(result, 0);
  if (result)
    return false;

  // Set the buffer frame size.
  UInt32 buffer_size = number_of_frames_;
  result = AudioUnitSetProperty(
      output_unit_,
      kAudioDevicePropertyBufferFrameSize,
      kAudioUnitScope_Output,
      0,
      &buffer_size,
      sizeof(buffer_size));
  DCHECK_EQ(result, 0);
  if (result)
    return false;

  return true;
}

void AUAudioOutputStream::Close() {
  if (output_unit_)
    CloseComponent(output_unit_);

  // Inform the audio manager that we have been closed. This can cause our
  // destruction.
  manager_->ReleaseOutputStream(this);
}

void AUAudioOutputStream::Start(AudioSourceCallback* callback) {
  DCHECK(callback);
  source_ = callback;

  AudioOutputUnitStart(output_unit_);
}

void AUAudioOutputStream::Stop() {
  // We request a synchronous stop, so the next call can take some time. In
  // the windows implementation we block here as well.
  source_ = NULL;

  AudioOutputUnitStop(output_unit_);
}

void AUAudioOutputStream::SetVolume(double volume) {
  if (!output_unit_)
    return;
  volume_ = static_cast<float>(volume);

  // TODO(crogers): set volume property
}

void AUAudioOutputStream::GetVolume(double* volume) {
  if (!output_unit_)
    return;
  *volume = volume_;
}

// Pulls on our provider to get rendered audio stream.
// Note to future hackers of this function: Do not add locks here because this
// is running on a real-time thread (for low-latency).
OSStatus AUAudioOutputStream::Render(UInt32 number_of_frames,
                                     AudioBufferList* io_data) {
  AudioBuffer& buffer = io_data->mBuffers[0];
  uint8* audio_data = reinterpret_cast<uint8*>(buffer.mData);
  uint32 filled = source_->OnMoreData(
      this, audio_data, buffer.mDataByteSize, AudioBuffersState(0, 0));

  // Handle channel order for 5.1 audio.
  if (format_.mChannelsPerFrame == 6) {
    if (format_.mBitsPerChannel == 8) {
      SwizzleCoreAudioLayout5_1(reinterpret_cast<uint8*>(audio_data), filled);
    } else if (format_.mBitsPerChannel == 16) {
      SwizzleCoreAudioLayout5_1(reinterpret_cast<int16*>(audio_data), filled);
    } else if (format_.mBitsPerChannel == 32) {
      SwizzleCoreAudioLayout5_1(reinterpret_cast<int32*>(audio_data), filled);
    }
  }

  return noErr;
}

// DefaultOutputUnit callback
OSStatus AUAudioOutputStream::InputProc(void* user_data,
                                        AudioUnitRenderActionFlags*,
                                        const AudioTimeStamp*,
                                        UInt32,
                                        UInt32 number_of_frames,
                                        AudioBufferList* io_data) {
  AUAudioOutputStream* audio_output =
      static_cast<AUAudioOutputStream*>(user_data);
  DCHECK(audio_output);
  if (!audio_output)
    return -1;

  return audio_output->Render(number_of_frames, io_data);
}

double AUAudioOutputStream::HardwareSampleRate() {
  // Determine the default output device's sample-rate.
  AudioDeviceID device_id = kAudioDeviceUnknown;
  UInt32 info_size = sizeof(device_id);

  AudioObjectPropertyAddress default_output_device_address = {
      kAudioHardwarePropertyDefaultOutputDevice,
      kAudioObjectPropertyScopeGlobal,
      kAudioObjectPropertyElementMaster
  };
  OSStatus result = AudioObjectGetPropertyData(kAudioObjectSystemObject,
                                               &default_output_device_address,
                                               0,
                                               0,
                                               &info_size,
                                               &device_id);
  DCHECK_EQ(result, 0);
  if (result)
    return 0.0;  // error

  Float64 nominal_sample_rate;
  info_size = sizeof(nominal_sample_rate);

  AudioObjectPropertyAddress nominal_sample_rate_address = {
      kAudioDevicePropertyNominalSampleRate,
      kAudioObjectPropertyScopeGlobal,
      kAudioObjectPropertyElementMaster
  };
  result = AudioObjectGetPropertyData(device_id,
                                      &nominal_sample_rate_address,
                                      0,
                                      0,
                                      &info_size,
                                      &nominal_sample_rate);
  DCHECK_EQ(result, 0);
  if (result)
    return 0.0;  // error

  return nominal_sample_rate;
}
<|endoftext|>


<commit_before>/***********************************************************************************************************************
 **
 ** Copyright (c) 2011, 2015 ETH Zurich
 ** All rights reserved.
 **
 ** 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 the ETH Zurich 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 HOLDER 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 OUT OF THE USE
 ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 **
 **********************************************************************************************************************/

#include "CppExporter.h"

#include "OOModel/src/declarations/Project.h"

#include "Export/src/writer/Exporter.h"
#include "Export/src/writer/FragmentLayouter.h"
#include "Export/src/tree/CompositeFragment.h"
#include "ModelBase/src/model/TreeManager.h"

#include "../CodeUnit.h"
#include "../CodeComposite.h"
#include "../Config.h"

namespace CppExport {

QList<Export::ExportError> CppExporter::exportTree(Model::TreeManager* treeManager,
																	const QString& pathToProjectContainerDirectory)
{
	QList<CodeUnit*> codeUnits;
	units(treeManager->root(), "", codeUnits);

	QList<CodeUnitPart*> allHeaderParts;
	for (auto unit : codeUnits)
	{
		unit->calculateSourceFragments();
		allHeaderParts.append(unit->headerPart());
	}
	for (auto unit : codeUnits) unit->calculateDependencies(allHeaderParts);

	auto directory = new Export::SourceDir(nullptr, pathToProjectContainerDirectory + "/src");
	for (auto codeComposite : mergeUnits(codeUnits))
	{
		codeComposite->sortUnits();
		createFileFromFragment(directory, codeComposite->name() + ".h", codeComposite->headerFragment());
		createFileFromFragment(directory, codeComposite->name() + ".h", addPragmaOnce(codeComposite->headerFragment()));
		createFileFromFragment(directory, codeComposite->name() + ".cpp", codeComposite->sourceFragment());
	}
	auto layout = layouter();
	Export::Exporter::exportToFileSystem("", directory, &layout);

	return {};

}

void CppExporter::createFileFromFragment(Export::SourceDir* directory, const QString& fileName,
													  Export::SourceFragment* sourceFragment)
{
	auto file = &directory->file(fileName);
	file->append(sourceFragment);
}

void CppExporter::units(Model::Node* current, QString namespaceName, QList<CodeUnit*>& result)
{
	if (auto ooModule = DCast<OOModel::Module>(current))
	{
		if (ooModule->classes()->size() > 0)
			namespaceName = ooModule->name();
		else
		{
			// macro file
			// TODO: handle non class units
			//result.append(new CodeUnit((namespaceName.isEmpty() ? "" : namespaceName + "/") + ooModule->name(), current));
			return;
		}
	}
	else if (auto ooClass = DCast<OOModel::Class>(current))
	{
		result.append(new CodeUnit((namespaceName.isEmpty() ? "" : namespaceName + "/") + ooClass->name(), current));
		return;
	}

	for (auto child : current->children())
		units(child, namespaceName, result);
}

QList<CodeComposite*> CppExporter::mergeUnits(QList<CodeUnit*>& units)
{
	QHash<QString, QString> mergeMap = Config::instance().dependencyUnitMergeMap();

	QHash<QString, CodeComposite*> nameToCompositeMap;
	for (auto unit : units)
	{
		auto it = mergeMap.find(unit->name());
		auto compositeName = it != mergeMap.end() ? *it : unit->name();

		auto cIt = nameToCompositeMap.find(compositeName);
		if (cIt != nameToCompositeMap.end())
			// case A: the composite that unit is a part of already exists => merge
			(*cIt)->addUnit(unit);
		else
		{
			// case B: the composite that unit is a part of does not yet exist
			auto composite = new CodeComposite(compositeName);
			composite->addUnit(unit);
			nameToCompositeMap.insert(composite->name(), composite);
		}
	}

	return nameToCompositeMap.values();
}

Export::FragmentLayouter CppExporter::layouter()
{
	auto result = Export::FragmentLayouter{"\t"};
	result.addRule("enumerators", Export::FragmentLayouter::SpaceAfterSeparator, "", ",", "");
	result.addRule("vertical", Export::FragmentLayouter::NoIndentation, "", "\n", "");
	result.addRule("sections", Export::FragmentLayouter::NoIndentation, "", "\n", "");
	result.addRule("spacedSections", Export::FragmentLayouter::NoIndentation, "", "\n\n", "");
	result.addRule("accessorSections", Export::FragmentLayouter::IndentChildFragments, "", "\n", "");
	result.addRule("bodySections", Export::FragmentLayouter::NewLineBefore
						  | Export::FragmentLayouter::IndentChildFragments | Export::FragmentLayouter::NewLineAfterPrefix
						  | Export::FragmentLayouter::NewLineBeforePostfix, "{", "\n", "}");
	result.addRule("space", Export::FragmentLayouter::SpaceAtEnd, "", " ", "");
	result.addRule("comma", Export::FragmentLayouter::SpaceAfterSeparator, "", ",", "");
	result.addRule("baseClasses", Export::FragmentLayouter::SpaceAfterSeparator, " : public ", ",", "");
	result.addRule("initializerList", Export::FragmentLayouter::SpaceAfterSeparator, "{", ",", "}");
	result.addRule("argsList", Export::FragmentLayouter::SpaceAfterSeparator, "(", ",", ")");
	result.addRule("typeArgsList", Export::FragmentLayouter::SpaceAfterSeparator, "<", ",", ">");
	result.addRule("templateArgsList", Export::FragmentLayouter::SpaceAfterSeparator
							| Export::FragmentLayouter::NewLineAfterPostfix, "template<", ",", ">");

	result.addRule("body", Export::FragmentLayouter::NewLineBefore | Export::FragmentLayouter::IndentChildFragments
							| Export::FragmentLayouter::NewLineAfterPrefix | Export::FragmentLayouter::NewLineBeforePostfix,
							"{", "\n", "}");

	return result;
}

Export::ExportMapContainer& CppExporter::exportMaps()
{
	static Export::ExportMapContainer* container = new Export::ExportMapContainer();
	return *container;
}

}
<commit_msg>remove extra code<commit_after>/***********************************************************************************************************************
 **
 ** Copyright (c) 2011, 2015 ETH Zurich
 ** All rights reserved.
 **
 ** 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 the ETH Zurich 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 HOLDER 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 OUT OF THE USE
 ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 **
 **********************************************************************************************************************/

#include "CppExporter.h"

#include "OOModel/src/declarations/Project.h"

#include "Export/src/writer/Exporter.h"
#include "Export/src/writer/FragmentLayouter.h"
#include "Export/src/tree/CompositeFragment.h"
#include "ModelBase/src/model/TreeManager.h"

#include "../CodeUnit.h"
#include "../CodeComposite.h"
#include "../Config.h"

namespace CppExport {

QList<Export::ExportError> CppExporter::exportTree(Model::TreeManager* treeManager,
																	const QString& pathToProjectContainerDirectory)
{
	QList<CodeUnit*> codeUnits;
	units(treeManager->root(), "", codeUnits);

	QList<CodeUnitPart*> allHeaderParts;
	for (auto unit : codeUnits)
	{
		unit->calculateSourceFragments();
		allHeaderParts.append(unit->headerPart());
	}
	for (auto unit : codeUnits) unit->calculateDependencies(allHeaderParts);

	auto directory = new Export::SourceDir(nullptr, pathToProjectContainerDirectory + "/src");
	for (auto codeComposite : mergeUnits(codeUnits))
	{
		codeComposite->sortUnits();
		createFileFromFragment(directory, codeComposite->name() + ".h", codeComposite->headerFragment());
		createFileFromFragment(directory, codeComposite->name() + ".cpp", codeComposite->sourceFragment());
	}
	auto layout = layouter();
	Export::Exporter::exportToFileSystem("", directory, &layout);

	return {};

}

void CppExporter::createFileFromFragment(Export::SourceDir* directory, const QString& fileName,
													  Export::SourceFragment* sourceFragment)
{
	auto file = &directory->file(fileName);
	file->append(sourceFragment);
}

void CppExporter::units(Model::Node* current, QString namespaceName, QList<CodeUnit*>& result)
{
	if (auto ooModule = DCast<OOModel::Module>(current))
	{
		if (ooModule->classes()->size() > 0)
			namespaceName = ooModule->name();
		else
		{
			// macro file
			// TODO: handle non class units
			//result.append(new CodeUnit((namespaceName.isEmpty() ? "" : namespaceName + "/") + ooModule->name(), current));
			return;
		}
	}
	else if (auto ooClass = DCast<OOModel::Class>(current))
	{
		result.append(new CodeUnit((namespaceName.isEmpty() ? "" : namespaceName + "/") + ooClass->name(), current));
		return;
	}

	for (auto child : current->children())
		units(child, namespaceName, result);
}

QList<CodeComposite*> CppExporter::mergeUnits(QList<CodeUnit*>& units)
{
	QHash<QString, QString> mergeMap = Config::instance().dependencyUnitMergeMap();

	QHash<QString, CodeComposite*> nameToCompositeMap;
	for (auto unit : units)
	{
		auto it = mergeMap.find(unit->name());
		auto compositeName = it != mergeMap.end() ? *it : unit->name();

		auto cIt = nameToCompositeMap.find(compositeName);
		if (cIt != nameToCompositeMap.end())
			// case A: the composite that unit is a part of already exists => merge
			(*cIt)->addUnit(unit);
		else
		{
			// case B: the composite that unit is a part of does not yet exist
			auto composite = new CodeComposite(compositeName);
			composite->addUnit(unit);
			nameToCompositeMap.insert(composite->name(), composite);
		}
	}

	return nameToCompositeMap.values();
}

Export::FragmentLayouter CppExporter::layouter()
{
	auto result = Export::FragmentLayouter{"\t"};
	result.addRule("enumerators", Export::FragmentLayouter::SpaceAfterSeparator, "", ",", "");
	result.addRule("vertical", Export::FragmentLayouter::NoIndentation, "", "\n", "");
	result.addRule("sections", Export::FragmentLayouter::NoIndentation, "", "\n", "");
	result.addRule("spacedSections", Export::FragmentLayouter::NoIndentation, "", "\n\n", "");
	result.addRule("accessorSections", Export::FragmentLayouter::IndentChildFragments, "", "\n", "");
	result.addRule("bodySections", Export::FragmentLayouter::NewLineBefore
						  | Export::FragmentLayouter::IndentChildFragments | Export::FragmentLayouter::NewLineAfterPrefix
						  | Export::FragmentLayouter::NewLineBeforePostfix, "{", "\n", "}");
	result.addRule("space", Export::FragmentLayouter::SpaceAtEnd, "", " ", "");
	result.addRule("comma", Export::FragmentLayouter::SpaceAfterSeparator, "", ",", "");
	result.addRule("baseClasses", Export::FragmentLayouter::SpaceAfterSeparator, " : public ", ",", "");
	result.addRule("initializerList", Export::FragmentLayouter::SpaceAfterSeparator, "{", ",", "}");
	result.addRule("argsList", Export::FragmentLayouter::SpaceAfterSeparator, "(", ",", ")");
	result.addRule("typeArgsList", Export::FragmentLayouter::SpaceAfterSeparator, "<", ",", ">");
	result.addRule("templateArgsList", Export::FragmentLayouter::SpaceAfterSeparator
							| Export::FragmentLayouter::NewLineAfterPostfix, "template<", ",", ">");

	result.addRule("body", Export::FragmentLayouter::NewLineBefore | Export::FragmentLayouter::IndentChildFragments
							| Export::FragmentLayouter::NewLineAfterPrefix | Export::FragmentLayouter::NewLineBeforePostfix,
							"{", "\n", "}");

	return result;
}

Export::ExportMapContainer& CppExporter::exportMaps()
{
	static Export::ExportMapContainer* container = new Export::ExportMapContainer();
	return *container;
}

}
<|endoftext|>


<commit_before>/*
    kimifaceimpl.cpp - Kopete DCOP Interface

    Copyright (c) 2004 by Will Stephenson     <lists@stevello.free-online.co.uk>

    Kopete    (c) 2002-2004      by the Kopete developers  <kopete-devel@kde.org>

    *************************************************************************
    *                                                                       *
    * This program is free software; you can redistribute it and/or modify  *
    * it under the terms of the GNU General Public License as published by  *
    * the Free Software Foundation; either version 2 of the License, or     *
    * (at your option) any later version.                                   *
    *                                                                       *
    *************************************************************************
*/

#include <qstringlist.h>

#include <dcopclient.h>
#include <kapplication.h>
#include <kiconloader.h>
#include <klocale.h>
#include <kplugininfo.h>

#include "kopeteaccount.h"
#include "kopeteaccountmanager.h"
#include "kopetecontactlist.h"
#include "kopetemetacontact.h"
#include "kopeteprotocol.h"
#include "kopetepluginmanager.h"

#include "kimifaceimpl.h"

KIMIfaceImpl::KIMIfaceImpl() : QObject(), DCOPObject( "KIMIface" )
{
	connect( KopeteContactList::contactList(),
		SIGNAL( metaContactAdded( KopeteMetaContact * ) ),
		SLOT( slotMetaContactAdded( KopeteMetaContact * ) ) );
}

KIMIfaceImpl::~KIMIfaceImpl()
{
}

QStringList KIMIfaceImpl::allContacts()
{
	QStringList result;
	QPtrList<KopeteMetaContact> list = KopeteContactList::contactList()->metaContacts();
	QPtrListIterator<KopeteMetaContact> it( list );
	for( ; it.current(); ++it )
	{
		if ( !it.current()->metaContactId().isNull() )
			result.append( it.current()->metaContactId() );
	}

	return result;
}

QStringList KIMIfaceImpl::reachableContacts()
{
	QStringList result;
	QPtrList<KopeteMetaContact> list = KopeteContactList::contactList()->metaContacts();
	QPtrListIterator<KopeteMetaContact> it( list );
	for( ; it.current(); ++it )
	{
		if ( it.current()->isReachable() && !it.current()->metaContactId().isNull() )
			result.append( it.current()->metaContactId() );
	}

	return result;
}

QStringList KIMIfaceImpl::onlineContacts()
{
	QStringList result;
	QPtrList<KopeteMetaContact> list = KopeteContactList::contactList()->metaContacts();
	QPtrListIterator<KopeteMetaContact> it( list );
	for( ; it.current(); ++it )
	{
		if ( it.current()->isOnline() && !it.current()->metaContactId().isNull() )
			result.append( it.current()->metaContactId() );
	}

	return result;
}

QStringList KIMIfaceImpl::fileTransferContacts()
{
	QStringList result;
	QPtrList<KopeteMetaContact> list = KopeteContactList::contactList()->metaContacts();
	QPtrListIterator<KopeteMetaContact> it( list );
	for( ; it.current(); ++it )
	{
		if ( it.current()->canAcceptFiles() && !it.current()->metaContactId().isNull() )
			result.append( it.current()->metaContactId() );
	}

	return result;
}

bool KIMIfaceImpl::isPresent( const QString & uid )
{
	KopeteMetaContact *mc;
	mc = KopeteContactList::contactList()->metaContact( uid );

	return ( mc != 0 );
}

int KIMIfaceImpl::presenceStatus( const QString & uid )
{
	int p = -1;
	KopeteMetaContact *m = KopeteContactList::contactList()->metaContact( uid );
	if ( m )
	{
		KopeteOnlineStatus status = m->status();
		switch ( status.status() )
		{
			case KopeteOnlineStatus::Unknown:
				p = 0;
			break;
			case KopeteOnlineStatus::Offline:
				p = 1;
			break;
			case KopeteOnlineStatus::Connecting:
				p = 2;
			break;
			case KopeteOnlineStatus::Away:
				p = 3;
			break;
			case KopeteOnlineStatus::Online:
				p = 4;
			break;
		}
	}
	return p;
}

QString KIMIfaceImpl::presenceString( const QString & uid )
{
	QString p;
	KopeteMetaContact *m = KopeteContactList::contactList()->metaContact( uid );
	if ( m )
	{
		KopeteOnlineStatus status = m->status();
			p = status.description();
	}
	else
	{
		p = i18n("Error: could not discover presence.");
	}
	return p;
}

bool KIMIfaceImpl::canReceiveFiles( const QString & uid )
{
	KopeteMetaContact *mc;
	mc = KopeteContactList::contactList()->metaContact( uid );

	if ( mc )
		return mc->canAcceptFiles();
	else
		return false;
}

bool KIMIfaceImpl::canRespond( const QString & uid )
{
	KopeteMetaContact *mc;
	mc = KopeteContactList::contactList()->metaContact( uid );

	if ( mc )
	{
		QPtrList<KopeteContact> list = mc->contacts();
		QPtrListIterator<KopeteContact> it( list );
		KopeteContact *contact;
		while ( ( contact = it.current() ) != 0 )
		{
			++it;
			if ( contact->isOnline() && contact->protocol()->pluginId() != "SMSProtocol" )
			return true;
		}
	}
	return false;
}

QString KIMIfaceImpl::locate( const QString & contactId, const QString & protocolId )
{
	KopeteMetaContact *mc = locateProtocolContact( contactId, protocolId );
	if ( mc )
		return mc->metaContactId();
	else
		return QString();
}

KopeteMetaContact * KIMIfaceImpl::locateProtocolContact( const QString & contactId, const QString & protocolId )
{
	KopeteMetaContact *mc = 0;
	// find a matching protocol
	KopeteProtocol *protocol = dynamic_cast<KopeteProtocol*>( KopetePluginManager::self()->plugin( protocolId ) );

	if ( protocol )
	{
		// find its accounts
		QDict<KopeteAccount> accounts = KopeteAccountManager::manager()->accounts( protocol );
		QDictIterator<KopeteAccount> it( accounts );
		for( ; it.current(); ++it )
		{
			mc = KopeteContactList::contactList()->findContact( protocolId, it.currentKey(), contactId  );
			if (mc)
				break;
		}
	}
	return mc;
}

QPixmap KIMIfaceImpl::icon( const QString & uid )
{
	KopeteMetaContact *m = KopeteContactList::contactList()->metaContact( uid );
	QPixmap p;
	if ( m )
		p = SmallIcon( m->statusIcon() );
	return p;
}

QString KIMIfaceImpl::context( const QString & uid )
{
	// TODO: support context
	// shush warning
	QString myUid = uid;

	return QString( "Home" );
}

QStringList KIMIfaceImpl::protocols()
{
	QValueList<KPluginInfo *> protocols = KopetePluginManager::self()->availablePlugins( "Protocols" );
	QStringList protocolList;
	for ( QValueList<KPluginInfo *>::Iterator it = protocols.begin(); it != protocols.end(); ++it )
		protocolList.append( (*it)->name() );

	return protocolList;
}

void KIMIfaceImpl::messageContact( const QString &uid, const QString& messageText )
{
	// TODO: make it possible to specify the message here
	KopeteMetaContact *m = KopeteContactList::contactList()->metaContact( uid );
	if ( m )
		m->sendMessage();
}

void KIMIfaceImpl::messageNewContact( const QString &protocol, const QString &contactId )
{
	KopeteMetaContact *mc = locateProtocolContact( contactId, protocol );
	if ( mc )
		mc->sendMessage();
}

void KIMIfaceImpl::chatWithContact( const QString &uid )
{
	KopeteMetaContact *m = KopeteContactList::contactList()->metaContact( uid );
	if ( m )
		m->execute();
}

void KIMIfaceImpl::sendFile(const QString &uid, const KURL &sourceURL,
		const QString &altFileName, uint fileSize)
{
	KopeteMetaContact *m = KopeteContactList::contactList()->metaContact( uid );
	if ( m )
		m->sendFile( sourceURL, altFileName, fileSize );
}

bool KIMIfaceImpl::addContact( const QString &protocolId, const QString &contactId )
{
	// find a matching protocol
	KopeteProtocol *protocol = dynamic_cast<KopeteProtocol*>( KopetePluginManager::self()->plugin( protocolId ) );

	if ( protocol )
	{
		// find its accounts
		QDict<KopeteAccount> accounts = KopeteAccountManager::manager()->accounts( protocol );
		QDictIterator<KopeteAccount> it( accounts );
		KopeteAccount *ac = it.toFirst();
		if ( ac )
		{
			ac->addContact( contactId );
			return true;
		}
	}
	return false;
}

void KIMIfaceImpl::slotMetaContactAdded( KopeteMetaContact *mc )
{
	connect( mc, SIGNAL( onlineStatusChanged( KopeteMetaContact *, KopeteOnlineStatus::OnlineStatus ) ),
		SLOT( slotContactStatusChanged( KopeteMetaContact * ) ) );
}

void KIMIfaceImpl::slotContactStatusChanged( KopeteMetaContact *mc )
{
	if ( !mc->metaContactId().isNull() )
	{
		// tell anyone who's listening over DCOP
		QByteArray params;
		QDataStream stream(params, IO_WriteOnly);
		stream << mc->metaContactId();
		kapp->dcopClient()->emitDCOPSignal( "contactStatusChanged(QString)", params );
	}
}
<commit_msg>CVS_SILENT Include moc<commit_after>/*
    kimifaceimpl.cpp - Kopete DCOP Interface

    Copyright (c) 2004 by Will Stephenson     <lists@stevello.free-online.co.uk>

    Kopete    (c) 2002-2004      by the Kopete developers  <kopete-devel@kde.org>

    *************************************************************************
    *                                                                       *
    * This program is free software; you can redistribute it and/or modify  *
    * it under the terms of the GNU General Public License as published by  *
    * the Free Software Foundation; either version 2 of the License, or     *
    * (at your option) any later version.                                   *
    *                                                                       *
    *************************************************************************
*/

#include <qstringlist.h>

#include <dcopclient.h>
#include <kapplication.h>
#include <kiconloader.h>
#include <klocale.h>
#include <kplugininfo.h>

#include "kopeteaccount.h"
#include "kopeteaccountmanager.h"
#include "kopetecontactlist.h"
#include "kopetemetacontact.h"
#include "kopeteprotocol.h"
#include "kopetepluginmanager.h"

#include "kimifaceimpl.h"

KIMIfaceImpl::KIMIfaceImpl() : QObject(), DCOPObject( "KIMIface" )
{
	connect( KopeteContactList::contactList(),
		SIGNAL( metaContactAdded( KopeteMetaContact * ) ),
		SLOT( slotMetaContactAdded( KopeteMetaContact * ) ) );
}

KIMIfaceImpl::~KIMIfaceImpl()
{
}

QStringList KIMIfaceImpl::allContacts()
{
	QStringList result;
	QPtrList<KopeteMetaContact> list = KopeteContactList::contactList()->metaContacts();
	QPtrListIterator<KopeteMetaContact> it( list );
	for( ; it.current(); ++it )
	{
		if ( !it.current()->metaContactId().isNull() )
			result.append( it.current()->metaContactId() );
	}

	return result;
}

QStringList KIMIfaceImpl::reachableContacts()
{
	QStringList result;
	QPtrList<KopeteMetaContact> list = KopeteContactList::contactList()->metaContacts();
	QPtrListIterator<KopeteMetaContact> it( list );
	for( ; it.current(); ++it )
	{
		if ( it.current()->isReachable() && !it.current()->metaContactId().isNull() )
			result.append( it.current()->metaContactId() );
	}

	return result;
}

QStringList KIMIfaceImpl::onlineContacts()
{
	QStringList result;
	QPtrList<KopeteMetaContact> list = KopeteContactList::contactList()->metaContacts();
	QPtrListIterator<KopeteMetaContact> it( list );
	for( ; it.current(); ++it )
	{
		if ( it.current()->isOnline() && !it.current()->metaContactId().isNull() )
			result.append( it.current()->metaContactId() );
	}

	return result;
}

QStringList KIMIfaceImpl::fileTransferContacts()
{
	QStringList result;
	QPtrList<KopeteMetaContact> list = KopeteContactList::contactList()->metaContacts();
	QPtrListIterator<KopeteMetaContact> it( list );
	for( ; it.current(); ++it )
	{
		if ( it.current()->canAcceptFiles() && !it.current()->metaContactId().isNull() )
			result.append( it.current()->metaContactId() );
	}

	return result;
}

bool KIMIfaceImpl::isPresent( const QString & uid )
{
	KopeteMetaContact *mc;
	mc = KopeteContactList::contactList()->metaContact( uid );

	return ( mc != 0 );
}

int KIMIfaceImpl::presenceStatus( const QString & uid )
{
	int p = -1;
	KopeteMetaContact *m = KopeteContactList::contactList()->metaContact( uid );
	if ( m )
	{
		KopeteOnlineStatus status = m->status();
		switch ( status.status() )
		{
			case KopeteOnlineStatus::Unknown:
				p = 0;
			break;
			case KopeteOnlineStatus::Offline:
				p = 1;
			break;
			case KopeteOnlineStatus::Connecting:
				p = 2;
			break;
			case KopeteOnlineStatus::Away:
				p = 3;
			break;
			case KopeteOnlineStatus::Online:
				p = 4;
			break;
		}
	}
	return p;
}

QString KIMIfaceImpl::presenceString( const QString & uid )
{
	QString p;
	KopeteMetaContact *m = KopeteContactList::contactList()->metaContact( uid );
	if ( m )
	{
		KopeteOnlineStatus status = m->status();
			p = status.description();
	}
	else
	{
		p = i18n("Error: could not discover presence.");
	}
	return p;
}

bool KIMIfaceImpl::canReceiveFiles( const QString & uid )
{
	KopeteMetaContact *mc;
	mc = KopeteContactList::contactList()->metaContact( uid );

	if ( mc )
		return mc->canAcceptFiles();
	else
		return false;
}

bool KIMIfaceImpl::canRespond( const QString & uid )
{
	KopeteMetaContact *mc;
	mc = KopeteContactList::contactList()->metaContact( uid );

	if ( mc )
	{
		QPtrList<KopeteContact> list = mc->contacts();
		QPtrListIterator<KopeteContact> it( list );
		KopeteContact *contact;
		while ( ( contact = it.current() ) != 0 )
		{
			++it;
			if ( contact->isOnline() && contact->protocol()->pluginId() != "SMSProtocol" )
			return true;
		}
	}
	return false;
}

QString KIMIfaceImpl::locate( const QString & contactId, const QString & protocolId )
{
	KopeteMetaContact *mc = locateProtocolContact( contactId, protocolId );
	if ( mc )
		return mc->metaContactId();
	else
		return QString();
}

KopeteMetaContact * KIMIfaceImpl::locateProtocolContact( const QString & contactId, const QString & protocolId )
{
	KopeteMetaContact *mc = 0;
	// find a matching protocol
	KopeteProtocol *protocol = dynamic_cast<KopeteProtocol*>( KopetePluginManager::self()->plugin( protocolId ) );

	if ( protocol )
	{
		// find its accounts
		QDict<KopeteAccount> accounts = KopeteAccountManager::manager()->accounts( protocol );
		QDictIterator<KopeteAccount> it( accounts );
		for( ; it.current(); ++it )
		{
			mc = KopeteContactList::contactList()->findContact( protocolId, it.currentKey(), contactId  );
			if (mc)
				break;
		}
	}
	return mc;
}

QPixmap KIMIfaceImpl::icon( const QString & uid )
{
	KopeteMetaContact *m = KopeteContactList::contactList()->metaContact( uid );
	QPixmap p;
	if ( m )
		p = SmallIcon( m->statusIcon() );
	return p;
}

QString KIMIfaceImpl::context( const QString & uid )
{
	// TODO: support context
	// shush warning
	QString myUid = uid;

	return QString( "Home" );
}

QStringList KIMIfaceImpl::protocols()
{
	QValueList<KPluginInfo *> protocols = KopetePluginManager::self()->availablePlugins( "Protocols" );
	QStringList protocolList;
	for ( QValueList<KPluginInfo *>::Iterator it = protocols.begin(); it != protocols.end(); ++it )
		protocolList.append( (*it)->name() );

	return protocolList;
}

void KIMIfaceImpl::messageContact( const QString &uid, const QString& messageText )
{
	// TODO: make it possible to specify the message here
	KopeteMetaContact *m = KopeteContactList::contactList()->metaContact( uid );
	if ( m )
		m->sendMessage();
}

void KIMIfaceImpl::messageNewContact( const QString &protocol, const QString &contactId )
{
	KopeteMetaContact *mc = locateProtocolContact( contactId, protocol );
	if ( mc )
		mc->sendMessage();
}

void KIMIfaceImpl::chatWithContact( const QString &uid )
{
	KopeteMetaContact *m = KopeteContactList::contactList()->metaContact( uid );
	if ( m )
		m->execute();
}

void KIMIfaceImpl::sendFile(const QString &uid, const KURL &sourceURL,
		const QString &altFileName, uint fileSize)
{
	KopeteMetaContact *m = KopeteContactList::contactList()->metaContact( uid );
	if ( m )
		m->sendFile( sourceURL, altFileName, fileSize );
}

bool KIMIfaceImpl::addContact( const QString &protocolId, const QString &contactId )
{
	// find a matching protocol
	KopeteProtocol *protocol = dynamic_cast<KopeteProtocol*>( KopetePluginManager::self()->plugin( protocolId ) );

	if ( protocol )
	{
		// find its accounts
		QDict<KopeteAccount> accounts = KopeteAccountManager::manager()->accounts( protocol );
		QDictIterator<KopeteAccount> it( accounts );
		KopeteAccount *ac = it.toFirst();
		if ( ac )
		{
			ac->addContact( contactId );
			return true;
		}
	}
	return false;
}

void KIMIfaceImpl::slotMetaContactAdded( KopeteMetaContact *mc )
{
	connect( mc, SIGNAL( onlineStatusChanged( KopeteMetaContact *, KopeteOnlineStatus::OnlineStatus ) ),
		SLOT( slotContactStatusChanged( KopeteMetaContact * ) ) );
}

void KIMIfaceImpl::slotContactStatusChanged( KopeteMetaContact *mc )
{
	if ( !mc->metaContactId().isNull() )
	{
		// tell anyone who's listening over DCOP
		QByteArray params;
		QDataStream stream(params, IO_WriteOnly);
		stream << mc->metaContactId();
		kapp->dcopClient()->emitDCOPSignal( "contactStatusChanged(QString)", params );
	}
}

#include "kimifaceimpl.moc"
<|endoftext|>


<commit_before>//
//  File: GraphicsAPI.cpp
//  Author: Hongtae Kim (tiff2766@gmail.com)
//
//  Copyright (c) 2004-2017 Hongtae Kim. All rights reserved.
//

#include <initializer_list>
#include "../DKPropertySet.h"
#include "../Interface/DKGraphicsDeviceInterface.h"
#include "GraphicsAPI.h"

namespace DKFramework
{
	namespace Private
	{
#if DKGL_USE_METAL
		namespace Metal
		{
			DKGraphicsDeviceInterface* CreateInterface(void);
		}
#endif
#if DKGL_USE_VULKAN
		namespace Vulkan
		{
			DKGraphicsDeviceInterface* CreateInterface(void);
		}
#endif
#if DKGL_USE_DIRECT3D
		namespace Direct3D
		{
			DKGraphicsDeviceInterface* CreateInterface(void);
		}
#endif
#if DKGL_USE_OPENGL
		namespace OpenGL
		{
			DKGraphicsDeviceInterface* CreateInterface(void);
		}
#endif
	}

	DKGraphicsDeviceInterface* DKGraphicsDeviceInterface::CreateInterface(void)
	{
		DKString defaultAPI =
#if DKGL_USE_METAL
		"Metal";
#elif DKGL_USE_DIRECT3D
		"Direct3D";
#elif DKGL_USE_VULKAN
		"Vulkan";
#elif DKGL_USE_OPENGL
		"OpenGL";
#else
		"";
#endif
		struct APISet
		{
			const char* name;
			DKGraphicsDeviceInterface* (*fn)(void);
		};

		DKArray<APISet> apis = {
#if DKGL_USE_METAL
			{ "Metal", Private::Metal::CreateInterface },
#endif
#if DKGL_USE_DIRECT3D
			{ "Direct3D", Private::Direct3D::CreateInterface },
#endif
#if DKGL_USE_VULKAN
			{ "Vulkan", Private::Vulkan::CreateInterface },
#endif
#if DKGL_USE_OPENGL
			{ "OpenGL", Private::OpenGL::CreateInterface },
#endif
		};

		for (size_t i = 0; i < apis.Count(); ++i)
		{
			if (defaultAPI.CompareNoCase(apis.Value(i).name) == 0)
			{
				if (i > 0)
				{
					APISet api = apis.Value(i);
					apis.Remove(i);
					apis.Insert(api, 0);
				}
				break;
			}
		}

		// get user preferred API name.
		bool tryPreferredApiFirst = true;
		if (tryPreferredApiFirst)
		{
			const char* key = "GraphicsAPI";
			DKPropertySet& config = DKPropertySet::SystemConfig();
			if (config.HasValue(key))
			{
				const DKVariant& var = config.Value(key);
				if (var.ValueType() == DKVariant::TypeString)
				{
					DKString selectAPI = DKStringU8(var.String());

					for (size_t i = 0; i < apis.Count(); ++i)
					{
						if (selectAPI.CompareNoCase(apis.Value(i).name) == 0)
						{
							if (i > 0)
							{
								APISet api = apis.Value(i);
								apis.Remove(i);
								apis.Insert(api, 0);
							}
							break;
						}
					}
				}
			}
		}

		bool printApiSet = true;
		if (printApiSet)
		{
			int index = 0;
			for (const APISet& as : apis)
			{
				DKLog(" GraphicsAPI[%d]: %s", index, as.name);
				index++;
			}
			if (index == 0)
				DKLog(" No Graphics API available.");
		}

		for (const APISet& as : apis)
		{
			try {
				DKGraphicsDeviceInterface* device = as.fn();
				if (device)
				{
					DKLog("Graphics API \"%s\" selected.", as.name);
					return device;
				}
				else
				{
					DKLog("Graphics API \"%s\" not supported.", as.name);
				}
			}
			catch (DKError& e)
			{
				DKLog("Graphics API \"%s\" Failed: %ls", as.name, (const wchar_t*)e.Description());
			}
			catch (std::exception& e)
			{
				DKLog("Graphics API \"%s\" Failed: %s", as.name, e.what());
			}
		}

		DKLog("ERROR: No Graphics device found.");
		return NULL;
	}
}
<commit_msg>no message<commit_after>//
//  File: GraphicsAPI.cpp
//  Author: Hongtae Kim (tiff2766@gmail.com)
//
//  Copyright (c) 2004-2017 Hongtae Kim. All rights reserved.
//

#include <initializer_list>
#include "../DKPropertySet.h"
#include "../Interface/DKGraphicsDeviceInterface.h"
#include "GraphicsAPI.h"

namespace DKFramework
{
	namespace Private
	{
#if DKGL_USE_METAL
		namespace Metal
		{
			DKGraphicsDeviceInterface* CreateInterface(void);
		}
#endif
#if DKGL_USE_VULKAN
		namespace Vulkan
		{
			DKGraphicsDeviceInterface* CreateInterface(void);
		}
#endif
#if DKGL_USE_DIRECT3D
		namespace Direct3D
		{
			DKGraphicsDeviceInterface* CreateInterface(void);
		}
#endif
#if DKGL_USE_OPENGL
		namespace OpenGL
		{
			DKGraphicsDeviceInterface* CreateInterface(void);
		}
#endif
	}

	DKGraphicsDeviceInterface* DKGraphicsDeviceInterface::CreateInterface(void)
	{
		DKString defaultAPI =
#if DKGL_USE_METAL
		"Metal";
#elif DKGL_USE_DIRECT3D
		"Direct3D";
#elif DKGL_USE_VULKAN
		"Vulkan";
#elif DKGL_USE_OPENGL
		"OpenGL";
#else
		"";
#endif
		struct APISet
		{
			const char* name;
			DKGraphicsDeviceInterface* (*fn)(void);
		};

		DKArray<APISet> apis = {
#if DKGL_USE_METAL
			{ "Metal", Private::Metal::CreateInterface },
#endif
#if DKGL_USE_DIRECT3D
			{ "Direct3D", Private::Direct3D::CreateInterface },
#endif
#if DKGL_USE_VULKAN
			{ "Vulkan", Private::Vulkan::CreateInterface },
#endif
#if DKGL_USE_OPENGL
			{ "OpenGL", Private::OpenGL::CreateInterface },
#endif
		};

		for (size_t i = 0; i < apis.Count(); ++i)
		{
			if (defaultAPI.CompareNoCase(apis.Value(i).name) == 0)
			{
				if (i > 0)
				{
					APISet api = apis.Value(i);
					apis.Remove(i);
					apis.Insert(api, 0);
				}
				break;
			}
		}

		// get user preferred API name.
		bool tryPreferredApiFirst = true;
		if (tryPreferredApiFirst)
		{
			const char* key = "GraphicsAPI";
			DKPropertySet& config = DKPropertySet::SystemConfig();
			if (config.HasValue(key))
			{
				const DKVariant& var = config.Value(key);
				if (var.ValueType() == DKVariant::TypeString)
				{
					DKString selectAPI = (DKString)DKStringU8(var.String());

					for (size_t i = 0; i < apis.Count(); ++i)
					{
						if (selectAPI.CompareNoCase(apis.Value(i).name) == 0)
						{
							if (i > 0)
							{
								APISet api = apis.Value(i);
								apis.Remove(i);
								apis.Insert(api, 0);
							}
							break;
						}
					}
				}
			}
		}

		bool printApiSet = true;
		if (printApiSet)
		{
			int index = 0;
			for (const APISet& as : apis)
			{
				DKLog(" GraphicsAPI[%d]: %s", index, as.name);
				index++;
			}
			if (index == 0)
				DKLog(" No Graphics API available.");
		}

		for (const APISet& as : apis)
		{
			try {
				DKGraphicsDeviceInterface* device = as.fn();
				if (device)
				{
					DKLog("Graphics API \"%s\" selected.", as.name);
					return device;
				}
				else
				{
					DKLog("Graphics API \"%s\" not supported.", as.name);
				}
			}
			catch (DKError& e)
			{
				DKLog("Graphics API \"%s\" Failed: %ls", as.name, (const wchar_t*)e.Description());
			}
			catch (std::exception& e)
			{
				DKLog("Graphics API \"%s\" Failed: %s", as.name, e.what());
			}
		}

		DKLog("ERROR: No Graphics device found.");
		return NULL;
	}
}
<|endoftext|>


<commit_before>// RUN: clang-cc -fsyntax-only -faccess-control -verify %s

namespace T1 {

class A {
  virtual int f(); // expected-note{{overridden virtual function is here}}
};

class B : A {
  virtual void f(); // expected-error{{virtual function 'f' has a different return type ('void') than the function it overrides (which has return type 'int')}}
};

}

namespace T2 {

struct a { };
struct b { };

class A {
  virtual a* f(); // expected-note{{overridden virtual function is here}}
};

class B : A {
  virtual b* f(); // expected-error{{return type of virtual function 'f' is not covariant with the return type of the function it overrrides ('struct T2::b *' is not derived from 'struct T2::a *')}}
};

}

namespace T3 {

struct a { };
struct b : private a { }; // expected-note{{'private' inheritance specifier here}}

class A {
  virtual a* f(); // expected-note{{overridden virtual function is here}}
};

class B : A {
  virtual b* f(); // expected-error{{return type of virtual function 'f' is not covariant with the return type of the function it overrides (conversion from 'struct T3::b' to inaccessible base class 'struct T3::a')}}
};

}

namespace T4 {

struct a { };
struct a1 : a { };
struct b : a, a1 { };

class A {
  virtual a* f(); // expected-note{{overridden virtual function is here}}
};

class B : A {
  virtual b* f(); // expected-error{{return type of virtual function 'f' is not covariant with the return type of the function it overrides (ambiguous conversion from derived class 'struct T4::b' to base class 'struct T4::a':\n\
    struct T4::b -> struct T4::a\n\
    struct T4::b -> struct T4::a1 -> struct T4::a)}}
};

}

namespace T5 {

struct a { };

class A {
  virtual a* const f();
  virtual a* const g(); // expected-note{{overridden virtual function is here}}
};

class B : A {
  virtual a* const f();
  virtual a* g(); // expected-error{{return type of virtual function 'g' is not covariant with the return type of the function it overrides ('struct T5::a *' has different qualifiers than 'struct T5::a *const')}}
};

}

namespace T6 {

struct a { };

class A {
  virtual const a* f();
  virtual a* g(); // expected-note{{overridden virtual function is here}}
};

class B : A {
  virtual a* f();
  virtual const a* g(); // expected-error{{return type of virtual function 'g' is not covariant with the return type of the function it overrides (class type 'struct T6::a const *' is more qualified than class type 'struct T6::a *'}}
};

}
<commit_msg>Fix the same speling error in the test case (Duh).<commit_after>// RUN: clang-cc -fsyntax-only -faccess-control -verify %s

namespace T1 {

class A {
  virtual int f(); // expected-note{{overridden virtual function is here}}
};

class B : A {
  virtual void f(); // expected-error{{virtual function 'f' has a different return type ('void') than the function it overrides (which has return type 'int')}}
};

}

namespace T2 {

struct a { };
struct b { };

class A {
  virtual a* f(); // expected-note{{overridden virtual function is here}}
};

class B : A {
  virtual b* f(); // expected-error{{return type of virtual function 'f' is not covariant with the return type of the function it overrides ('struct T2::b *' is not derived from 'struct T2::a *')}}
};

}

namespace T3 {

struct a { };
struct b : private a { }; // expected-note{{'private' inheritance specifier here}}

class A {
  virtual a* f(); // expected-note{{overridden virtual function is here}}
};

class B : A {
  virtual b* f(); // expected-error{{return type of virtual function 'f' is not covariant with the return type of the function it overrides (conversion from 'struct T3::b' to inaccessible base class 'struct T3::a')}}
};

}

namespace T4 {

struct a { };
struct a1 : a { };
struct b : a, a1 { };

class A {
  virtual a* f(); // expected-note{{overridden virtual function is here}}
};

class B : A {
  virtual b* f(); // expected-error{{return type of virtual function 'f' is not covariant with the return type of the function it overrides (ambiguous conversion from derived class 'struct T4::b' to base class 'struct T4::a':\n\
    struct T4::b -> struct T4::a\n\
    struct T4::b -> struct T4::a1 -> struct T4::a)}}
};

}

namespace T5 {

struct a { };

class A {
  virtual a* const f();
  virtual a* const g(); // expected-note{{overridden virtual function is here}}
};

class B : A {
  virtual a* const f();
  virtual a* g(); // expected-error{{return type of virtual function 'g' is not covariant with the return type of the function it overrides ('struct T5::a *' has different qualifiers than 'struct T5::a *const')}}
};

}

namespace T6 {

struct a { };

class A {
  virtual const a* f();
  virtual a* g(); // expected-note{{overridden virtual function is here}}
};

class B : A {
  virtual a* f();
  virtual const a* g(); // expected-error{{return type of virtual function 'g' is not covariant with the return type of the function it overrides (class type 'struct T6::a const *' is more qualified than class type 'struct T6::a *'}}
};

}
<|endoftext|>


<commit_before><commit_msg>Use new startsWith() method of OString<commit_after><|endoftext|>