<commit_before>// @(#)root/eve:$Id$
// Author: Matevz Tadel

// Demonstrates usage of class TEvePointSet.

#ifndef __CINT__

#include <TEveManager.h>
#include <TEvePointSet.h>
#include <TEveRGBAPalette.h>
#include <TColor.h>
#include <TRandom.h>

#endif

TEvePointSet* pointset(Int_t npoints = 512, TEveElement* parent=0)
{
   TEveManager::Create();

   if (!gRandom)
      gRandom = new TRandom(0);
   TRandom& r= *gRandom;

   Float_t s = 100;

   TEvePointSet* ps = new TEvePointSet();
   ps->SetOwnIds(kTRUE);

   for(Int_t i = 0; i<npoints; i++)
   {
      ps->SetNextPoint(r.Uniform(-s,s), r.Uniform(-s,s), r.Uniform(-s,s));
      ps->SetPointId(new TNamed(Form("Point %d", i), ""));
   }

   ps->SetMarkerColor(TMath::Nint(r.Uniform(2, 9)));
   ps->SetMarkerSize(r.Uniform(1, 2));
   ps->SetMarkerStyle(4);

   if (parent)
   {
      parent->AddElement(ps);
   }
   else
   {
      gEve->AddElement(ps);
      gEve->Redraw3D();
   }

   return ps;
}

TEvePointSet*
pointset_hierarchy(Int_t level=3, Int_t nps=1, Int_t fac=2,
                        Int_t npoints=512, TEveElement* parent=0)
{
   // This only works in compiled mode!

   TEvePointSet* ps = 0;
   --level;
   for (Int_t i=0; i<nps; ++i)
   {
      printf("level=%d nps=%d i=%d\n", level, nps, i);
      ps = pointset(npoints, parent);
      if (level)
      {
         pointset_hierarchy(level, nps*fac, fac, npoints/fac, ps);
      }
   }
   return ps;
}

TEvePointSetArray* pointsetarray()
{
   TEveManager::Create();

   TRandom r(0);

   TEvePointSetArray* l = new TEvePointSetArray("TPC hits - Charge Slices", "");
   l->SetSourceCS(TEvePointSelectorConsumer::kTVT_RPhiZ);
   l->SetMarkerColor(3);
   l->SetMarkerStyle(4); // antialiased circle
   l->SetMarkerSize(0.8);

   gEve->AddElement(l);
   l->InitBins("Charge", 9, 10, 100);

   TColor::SetPalette(1, 0); // Spectrum palette
   const Int_t nCol = TColor::GetNumberOfColors();
   for (Int_t i = 1; i <= 9; ++i)
      l->GetBin(i)->SetMainColor(TColor::GetColorPalette(i * nCol / 10));

   l->GetBin(0) ->SetMainColor(kGray);
   l->GetBin(10)->SetMainColor(kWhite);

   Double_t rad, phi, z;
   for (Int_t i = 0; i < 10000; ++i)
   {
      rad = r.Uniform(60, 180);
      phi = r.Uniform(0, TMath::TwoPi());
      z   = r.Uniform(-250, 250);
      l->Fill(rad*TMath::Cos(phi), rad*TMath::Sin(phi), z,
              r.Uniform(0, 110));
   }

   l->CloseBins();

   gEve->Redraw3D();

   return l;
}
<commit_msg>Add missing include for running with aclic.<commit_after>// @(#)root/eve:$Id$
// Author: Matevz Tadel

// Demonstrates usage of class TEvePointSet.

#ifndef __CINT__

#include <TEveManager.h>
#include <TEvePointSet.h>
#include <TEveRGBAPalette.h>
#include <TColor.h>
#include <TRandom.h>
#include <TMath.h>

#endif

TEvePointSet* pointset(Int_t npoints = 512, TEveElement* parent=0)
{
   TEveManager::Create();

   if (!gRandom)
      gRandom = new TRandom(0);
   TRandom& r= *gRandom;

   Float_t s = 100;

   TEvePointSet* ps = new TEvePointSet();
   ps->SetOwnIds(kTRUE);

   for(Int_t i = 0; i<npoints; i++)
   {
      ps->SetNextPoint(r.Uniform(-s,s), r.Uniform(-s,s), r.Uniform(-s,s));
      ps->SetPointId(new TNamed(Form("Point %d", i), ""));
   }

   ps->SetMarkerColor(TMath::Nint(r.Uniform(2, 9)));
   ps->SetMarkerSize(r.Uniform(1, 2));
   ps->SetMarkerStyle(4);

   if (parent)
   {
      parent->AddElement(ps);
   }
   else
   {
      gEve->AddElement(ps);
      gEve->Redraw3D();
   }

   return ps;
}

TEvePointSet*
pointset_hierarchy(Int_t level=3, Int_t nps=1, Int_t fac=2,
                        Int_t npoints=512, TEveElement* parent=0)
{
   // This only works in compiled mode!

   TEvePointSet* ps = 0;
   --level;
   for (Int_t i=0; i<nps; ++i)
   {
      printf("level=%d nps=%d i=%d\n", level, nps, i);
      ps = pointset(npoints, parent);
      if (level)
      {
         pointset_hierarchy(level, nps*fac, fac, npoints/fac, ps);
      }
   }
   return ps;
}

TEvePointSetArray* pointsetarray()
{
   TEveManager::Create();

   TRandom r(0);

   TEvePointSetArray* l = new TEvePointSetArray("TPC hits - Charge Slices", "");
   l->SetSourceCS(TEvePointSelectorConsumer::kTVT_RPhiZ);
   l->SetMarkerColor(3);
   l->SetMarkerStyle(4); // antialiased circle
   l->SetMarkerSize(0.8);

   gEve->AddElement(l);
   l->InitBins("Charge", 9, 10, 100);

   TColor::SetPalette(1, 0); // Spectrum palette
   const Int_t nCol = TColor::GetNumberOfColors();
   for (Int_t i = 1; i <= 9; ++i)
      l->GetBin(i)->SetMainColor(TColor::GetColorPalette(i * nCol / 10));

   l->GetBin(0) ->SetMainColor(kGray);
   l->GetBin(10)->SetMainColor(kWhite);

   Double_t rad, phi, z;
   for (Int_t i = 0; i < 10000; ++i)
   {
      rad = r.Uniform(60, 180);
      phi = r.Uniform(0, TMath::TwoPi());
      z   = r.Uniform(-250, 250);
      l->Fill(rad*TMath::Cos(phi), rad*TMath::Sin(phi), z,
              r.Uniform(0, 110));
   }

   l->CloseBins();

   gEve->Redraw3D();

   return l;
}
<|endoftext|>


<commit_before>//===-- AMDGPUAlwaysInlinePass.cpp - Promote Allocas ----------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
/// \file
/// This pass marks all internal functions as always_inline and creates
/// duplicates of all other functions a marks the duplicates as always_inline.
//
//===----------------------------------------------------------------------===//

#include "AMDGPU.h"
#include "llvm/IR/Module.h"
#include "llvm/Transforms/Utils/Cloning.h"

using namespace llvm;

namespace {

class AMDGPUAlwaysInline : public ModulePass {
  bool GlobalOpt;

public:
  static char ID;

  AMDGPUAlwaysInline(bool GlobalOpt = false) :
    ModulePass(ID), GlobalOpt(GlobalOpt) { }
  bool runOnModule(Module &M) override;
  StringRef getPassName() const override { return "AMDGPU Always Inline Pass"; }
};

} // End anonymous namespace

INITIALIZE_PASS(AMDGPUAlwaysInline, "amdgpu-always-inline",
                "AMDGPU Inline All Functions", false, false)

char AMDGPUAlwaysInline::ID = 0;

bool AMDGPUAlwaysInline::runOnModule(Module &M) {
  std::vector<GlobalAlias*> AliasesToRemove;
  std::vector<Function *> FuncsToClone;

  for (GlobalAlias &A : M.aliases()) {
    if (Function* F = dyn_cast<Function>(A.getAliasee())) {
      A.replaceAllUsesWith(F);
      AliasesToRemove.push_back(&A);
    }
  }

  if (GlobalOpt) {
    for (GlobalAlias* A : AliasesToRemove) {
      A->eraseFromParent();
    }
  }

  for (Function &F : M) {
    if (!F.hasLocalLinkage() && !F.isDeclaration() && !F.use_empty() &&
        !F.hasFnAttribute(Attribute::NoInline))
      FuncsToClone.push_back(&F);
  }

  for (Function *F : FuncsToClone) {
    ValueToValueMapTy VMap;
    Function *NewFunc = CloneFunction(F, VMap);
    NewFunc->setLinkage(GlobalValue::InternalLinkage);
    F->replaceAllUsesWith(NewFunc);
  }

  for (Function &F : M) {
    if (F.hasLocalLinkage() && !F.hasFnAttribute(Attribute::NoInline)) {
      F.addFnAttr(Attribute::AlwaysInline);
    }
  }
  return false;
}

ModulePass *llvm::createAMDGPUAlwaysInlinePass(bool GlobalOpt) {
  return new AMDGPUAlwaysInline(GlobalOpt);
}
<commit_msg>    [AMDGPU] Testing commit access only, no real change<commit_after>//===-- AMDGPUAlwaysInlinePass.cpp - Promote Allocas ----------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
/// \file
/// This pass marks all internal functions as always_inline and creates
/// duplicates of all other functions and marks the duplicates as always_inline.
//
//===----------------------------------------------------------------------===//

#include "AMDGPU.h"
#include "llvm/IR/Module.h"
#include "llvm/Transforms/Utils/Cloning.h"

using namespace llvm;

namespace {

class AMDGPUAlwaysInline : public ModulePass {
  bool GlobalOpt;

public:
  static char ID;

  AMDGPUAlwaysInline(bool GlobalOpt = false) :
    ModulePass(ID), GlobalOpt(GlobalOpt) { }
  bool runOnModule(Module &M) override;
  StringRef getPassName() const override { return "AMDGPU Always Inline Pass"; }
};

} // End anonymous namespace

INITIALIZE_PASS(AMDGPUAlwaysInline, "amdgpu-always-inline",
                "AMDGPU Inline All Functions", false, false)

char AMDGPUAlwaysInline::ID = 0;

bool AMDGPUAlwaysInline::runOnModule(Module &M) {
  std::vector<GlobalAlias*> AliasesToRemove;
  std::vector<Function *> FuncsToClone;

  for (GlobalAlias &A : M.aliases()) {
    if (Function* F = dyn_cast<Function>(A.getAliasee())) {
      A.replaceAllUsesWith(F);
      AliasesToRemove.push_back(&A);
    }
  }

  if (GlobalOpt) {
    for (GlobalAlias* A : AliasesToRemove) {
      A->eraseFromParent();
    }
  }

  for (Function &F : M) {
    if (!F.hasLocalLinkage() && !F.isDeclaration() && !F.use_empty() &&
        !F.hasFnAttribute(Attribute::NoInline))
      FuncsToClone.push_back(&F);
  }

  for (Function *F : FuncsToClone) {
    ValueToValueMapTy VMap;
    Function *NewFunc = CloneFunction(F, VMap);
    NewFunc->setLinkage(GlobalValue::InternalLinkage);
    F->replaceAllUsesWith(NewFunc);
  }

  for (Function &F : M) {
    if (F.hasLocalLinkage() && !F.hasFnAttribute(Attribute::NoInline)) {
      F.addFnAttr(Attribute::AlwaysInline);
    }
  }
  return false;
}

ModulePass *llvm::createAMDGPUAlwaysInlinePass(bool GlobalOpt) {
  return new AMDGPUAlwaysInline(GlobalOpt);
}
<|endoftext|>


<commit_before>// Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "iceoryx_posh/internal/roudi_environment/roudi_environment.hpp"
#include "iceoryx_posh/runtime/posh_runtime.hpp"
#include "test.hpp"

using namespace ::testing;
using namespace iox::runtime;
using iox::roudi::RouDiEnvironment;

class PoshRuntime_test : public Test
{
  public:
    PoshRuntime_test()
    {
    }

    virtual ~PoshRuntime_test()
    {
    }

    virtual void SetUp(){};
    virtual void TearDown(){};

    void InterOpWait()
    {
        std::this_thread::sleep_for(std::chrono::milliseconds(200));
    }

    RouDiEnvironment m_roudiEnv{iox::RouDiConfig_t().setDefaults()};
    const std::string m_appName = "/sender";
    iox::runtime::PoshRuntime* m_senderRuntime{&iox::runtime::PoshRuntime::getInstance("/sender")};
    iox::runtime::PoshRuntime* m_receiverRuntime{&iox::runtime::PoshRuntime::getInstance("/receiver")};
    iox::runtime::MqMessage m_sendBuffer;
    iox::runtime::MqMessage m_receiveBuffer;
    const iox::cxx::CString100& m_runnableName = iox::cxx::CString100("testRunnable");
    const iox::cxx::CString100& m_invalidRunnableName = iox::cxx::CString100("invalidRunnable,");
};

TEST_F(PoshRuntime_test, SendMessageToRouDi)
{
    m_sendBuffer << mqMessageTypeToString(MqMessageType::IMPL_INTERFACE) << m_appName
                 << static_cast<uint32_t>(iox::capro::Interfaces::INTERNAL) << m_runnableName;

    auto status = m_senderRuntime->sendMessageToRouDi(m_sendBuffer);

    EXPECT_EQ(true, status);
}

TEST_F(PoshRuntime_test, SendMessageToRouDiInvalidMessage)
{
    m_sendBuffer << mqMessageTypeToString(MqMessageType::IMPL_INTERFACE) << std::string()
                 << static_cast<uint32_t>(iox::capro::Interfaces::INTERNAL) << m_invalidRunnableName;

    auto status = m_senderRuntime->sendMessageToRouDi(m_sendBuffer);

    EXPECT_EQ(false, status);
}

TEST_F(PoshRuntime_test, SendMessageToRouDiEmptyMessage)
{
    auto status = m_senderRuntime->sendMessageToRouDi(m_sendBuffer);

    EXPECT_EQ(true, status);
}

TEST_F(PoshRuntime_test, SendRequestToRouDi)
{
    m_sendBuffer << mqMessageTypeToString(MqMessageType::IMPL_INTERFACE) << m_appName
                 << static_cast<uint32_t>(iox::capro::Interfaces::INTERNAL) << m_runnableName;

    auto status = m_senderRuntime->sendRequestToRouDi(m_sendBuffer, m_receiveBuffer);

    EXPECT_EQ(true, status);
}

TEST_F(PoshRuntime_test, SendRequestToRouDiInvalidMessage)
{
    m_sendBuffer << mqMessageTypeToString(MqMessageType::IMPL_INTERFACE) << m_appName
                 << static_cast<uint32_t>(iox::capro::Interfaces::INTERNAL) << m_invalidRunnableName;

    auto status = m_senderRuntime->sendRequestToRouDi(m_sendBuffer, m_receiveBuffer);

    EXPECT_EQ(false, status);
}

TEST_F(PoshRuntime_test, GetMiddlewareSender)
{
    iox::capro::ServiceDescription serviceDescription{99, 1, 20};
    iox::runtime::PortConfigInfo portConfg(11, 22, 33);

    auto senderPort = m_senderRuntime->getMiddlewareSender(serviceDescription, m_runnableName, portConfg);

    EXPECT_EQ(99, senderPort->m_serviceDescription.getServiceID());
    EXPECT_EQ(1, senderPort->m_serviceDescription.getEventID());
    EXPECT_EQ(20, senderPort->m_serviceDescription.getInstanceID());
    EXPECT_EQ(22, senderPort->m_memoryInfo.deviceId);
    EXPECT_EQ(33, senderPort->m_memoryInfo.memoryType);
}

TEST_F(PoshRuntime_test, GetMiddlewareSenderDefaultArgs)
{
    iox::capro::ServiceDescription serviceDescription{99, 1, 20};

    auto senderPort = m_senderRuntime->getMiddlewareSender(serviceDescription);

    EXPECT_EQ(0, senderPort->m_memoryInfo.deviceId);
    EXPECT_EQ(0, senderPort->m_memoryInfo.memoryType);
}

TEST_F(PoshRuntime_test, GetMiddlewareReceiver)
{
    iox::capro::ServiceDescription serviceDescription{99, 1, 20};
    iox::runtime::PortConfigInfo portConfg(11, 22, 33);

    auto receiverPort = m_receiverRuntime->getMiddlewareReceiver(serviceDescription, m_runnableName, portConfg);

    EXPECT_EQ(99, receiverPort->m_serviceDescription.getServiceID());
    EXPECT_EQ(1, receiverPort->m_serviceDescription.getEventID());
    EXPECT_EQ(20, receiverPort->m_serviceDescription.getInstanceID());
    EXPECT_EQ(22, receiverPort->m_memoryInfo.deviceId);
    EXPECT_EQ(33, receiverPort->m_memoryInfo.memoryType);
}

TEST_F(PoshRuntime_test, GetMiddlewareReceiverDefaultArgs)
{
    iox::capro::ServiceDescription serviceDescription{99, 1, 20};

    auto receiverPort = m_receiverRuntime->getMiddlewareReceiver(serviceDescription);

    EXPECT_EQ(0, receiverPort->m_memoryInfo.deviceId);
    EXPECT_EQ(0, receiverPort->m_memoryInfo.memoryType);
}

TEST_F(PoshRuntime_test, CreateRunnable)
{
    uint64_t runnableDeviceIdentifier = 0u;
    iox::runtime::RunnableProperty runnableProperty(iox::cxx::CString100("testRunnable"), runnableDeviceIdentifier);

    auto runableData = m_senderRuntime->createRunnable(runnableProperty);

    EXPECT_EQ(runnableDeviceIdentifier, runableData->m_runnableDeviceIdentifier);
    EXPECT_EQ(m_appName, runableData->m_process);
    EXPECT_EQ(iox::cxx::CString100("testRunnable"), runableData->m_runnable);
}
<commit_msg>iox-#177 added unit testcases for posh_runtime<commit_after>// Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "iceoryx_posh/internal/roudi_environment/roudi_environment.hpp"
#include "iceoryx_posh/runtime/posh_runtime.hpp"
#include "test.hpp"

using namespace ::testing;
using namespace iox::runtime;
using iox::roudi::RouDiEnvironment;

class PoshRuntime_test : public Test
{
  public:
    PoshRuntime_test()
    {
    }

    virtual ~PoshRuntime_test()
    {
    }

    virtual void SetUp(){};
    virtual void TearDown(){};

    void InterOpWait()
    {
        std::this_thread::sleep_for(std::chrono::milliseconds(200));
    }

    RouDiEnvironment m_roudiEnv{iox::RouDiConfig_t().setDefaults()};
    const std::string m_appName = "/sender";
    PoshRuntime* m_receiverRuntime{&iox::runtime::PoshRuntime::getInstance("/receiver")};
    PoshRuntime* m_senderRuntime{&iox::runtime::PoshRuntime::getInstance("/sender")};
    MqMessage m_sendBuffer;
    MqMessage m_receiveBuffer;
    const iox::cxx::CString100 m_runnableName = iox::cxx::CString100("testRunnable");
    const iox::cxx::CString100 m_invalidRunnableName = iox::cxx::CString100("invalidRunnable,");
};

TEST_F(PoshRuntime_test, SendMessageToRouDi)
{
    m_sendBuffer << mqMessageTypeToString(MqMessageType::IMPL_INTERFACE) << m_appName
                 << static_cast<uint32_t>(iox::capro::Interfaces::INTERNAL) << m_runnableName;

    auto status = m_senderRuntime->sendMessageToRouDi(m_sendBuffer);

    EXPECT_EQ(true, status);
}

TEST_F(PoshRuntime_test, SendMessageToRouDiInvalidMessage)
{
    m_sendBuffer << mqMessageTypeToString(MqMessageType::IMPL_INTERFACE) << std::string()
                 << static_cast<uint32_t>(iox::capro::Interfaces::INTERNAL) << m_invalidRunnableName;

    auto status = m_senderRuntime->sendMessageToRouDi(m_sendBuffer);

    EXPECT_EQ(false, status);
}

TEST_F(PoshRuntime_test, SendMessageToRouDiEmptyMessage)
{
    const auto status = m_senderRuntime->sendMessageToRouDi(m_sendBuffer);

    EXPECT_EQ(true, status);
}

TEST_F(PoshRuntime_test, SendRequestToRouDi)
{
    m_sendBuffer << mqMessageTypeToString(MqMessageType::IMPL_INTERFACE) << m_appName
                 << static_cast<uint32_t>(iox::capro::Interfaces::INTERNAL) << m_runnableName;

    const auto status = m_senderRuntime->sendRequestToRouDi(m_sendBuffer, m_receiveBuffer);

    EXPECT_EQ(true, status);
}

TEST_F(PoshRuntime_test, SendRequestToRouDiInvalidMessage)
{
    m_sendBuffer << mqMessageTypeToString(MqMessageType::IMPL_INTERFACE) << m_appName
                 << static_cast<uint32_t>(iox::capro::Interfaces::INTERNAL) << m_invalidRunnableName;

    const auto status = m_senderRuntime->sendRequestToRouDi(m_sendBuffer, m_receiveBuffer);

    EXPECT_EQ(false, status);
}

TEST_F(PoshRuntime_test, GetMiddlewareSender)
{
    iox::capro::ServiceDescription serviceDescription{99, 1, 20};
    iox::runtime::PortConfigInfo portConfg(11, 22, 33);

    auto senderPort = m_senderRuntime->getMiddlewareSender(serviceDescription, m_runnableName, portConfg);

    EXPECT_EQ(99, senderPort->m_serviceDescription.getServiceID());
    EXPECT_EQ(1, senderPort->m_serviceDescription.getEventID());
    EXPECT_EQ(20, senderPort->m_serviceDescription.getInstanceID());
    EXPECT_EQ(22, senderPort->m_memoryInfo.deviceId);
    EXPECT_EQ(33, senderPort->m_memoryInfo.memoryType);
}

TEST_F(PoshRuntime_test, GetMiddlewareSenderDefaultArgs)
{
    iox::capro::ServiceDescription serviceDescription{99, 1, 20};

    auto senderPort = m_senderRuntime->getMiddlewareSender(serviceDescription);

    EXPECT_EQ(0, senderPort->m_memoryInfo.deviceId);
    EXPECT_EQ(0, senderPort->m_memoryInfo.memoryType);
}

TEST_F(PoshRuntime_test, GetMiddlewareReceiver)
{
    iox::capro::ServiceDescription serviceDescription{99, 1, 20};
    iox::runtime::PortConfigInfo portConfg(11, 22, 33);

    auto receiverPort = m_receiverRuntime->getMiddlewareReceiver(serviceDescription, m_runnableName, portConfg);

    EXPECT_EQ(99, receiverPort->m_serviceDescription.getServiceID());
    EXPECT_EQ(1, receiverPort->m_serviceDescription.getEventID());
    EXPECT_EQ(20, receiverPort->m_serviceDescription.getInstanceID());
    EXPECT_EQ(22, receiverPort->m_memoryInfo.deviceId);
    EXPECT_EQ(33, receiverPort->m_memoryInfo.memoryType);
}

TEST_F(PoshRuntime_test, GetMiddlewareReceiverDefaultArgs)
{
    iox::capro::ServiceDescription serviceDescription{99, 1, 20};

    auto receiverPort = m_receiverRuntime->getMiddlewareReceiver(serviceDescription);

    EXPECT_EQ(0, receiverPort->m_memoryInfo.deviceId);
    EXPECT_EQ(0, receiverPort->m_memoryInfo.memoryType);
}

TEST_F(PoshRuntime_test, GetServiceRegistryChangeCounter)
{
    const uint64_t runnableDeviceIdentifier = 0u;
    iox::runtime::RunnableProperty runnableProperty(iox::cxx::CString100("testRunnable"), runnableDeviceIdentifier);

    auto runnableData = m_senderRuntime->getServiceRegistryChangeCounter();

    // Roudi internally will call 5 servieces
    EXPECT_EQ(5, *runnableData);
}

TEST_F(PoshRuntime_test, GetServiceRegistryChangeCounter_OfferStopOfferService)
{
    const uint64_t runnableDeviceIdentifier = 0u;
    iox::runtime::RunnableProperty runnableProperty(iox::cxx::CString100("testRunnable"), runnableDeviceIdentifier);

    m_senderRuntime->offerService({"service1", "instance1"});
    this->InterOpWait();
    auto runnableData = m_senderRuntime->getServiceRegistryChangeCounter();

    EXPECT_EQ(6, *runnableData);

    m_senderRuntime->stopOfferService({"service1", "instance1"});
    this->InterOpWait();

    EXPECT_EQ(7, *runnableData);
}

TEST_F(PoshRuntime_test, GetMiddlewareSender_SenderlistOverflow)
{
    std::vector<iox::popo::SenderPort::MemberType_t*> senderPorts;
    iox::runtime::PoshRuntime* senderRuntime{&iox::runtime::PoshRuntime::getInstance("/sender")};

    auto errorHandlerCalled{false};
    auto errorHandlerGuard = iox::ErrorHandler::SetTemporaryErrorHandler(
        [&errorHandlerCalled](const iox::Error, const std::function<void()>, const iox::ErrorLevel) {
            errorHandlerCalled = true;
        });

    for (uint64_t i = 0; i < iox::MAX_PORT_NUMBER; ++i)
    {
        const auto senderPortData = senderRuntime->getMiddlewareSender(iox::capro::ServiceDescription(i, i + 1, i + 2));
        senderPorts.push_back(senderPortData);
    }

    EXPECT_TRUE(errorHandlerCalled);
}

TEST_F(PoshRuntime_test, CreateRunnable)
{
    const uint64_t runnableDeviceIdentifier = 11u;
    iox::runtime::RunnableProperty runnableProperty(iox::cxx::CString100("testRunnable"), runnableDeviceIdentifier);

    auto runableData = m_senderRuntime->createRunnable(runnableProperty);

    EXPECT_EQ(runnableDeviceIdentifier, runableData->m_runnableDeviceIdentifier);
    EXPECT_EQ(m_appName, runableData->m_process);
    EXPECT_EQ(iox::cxx::CString100("testRunnable"), runableData->m_runnable);
}

TEST_F(PoshRuntime_test, ApplicationPort)
{
    m_senderRuntime->offerService({"service1", "instance1"});
    this->InterOpWait();
    auto applicationPortData = m_receiverRuntime->getMiddlewareApplication();
    iox::popo::ApplicationPort applicationPort(applicationPortData);
    iox::capro::CaproMessage caproMessage;
    this->InterOpWait();

    bool serviceFound = false;
    while (applicationPort.getCaProMessage(caproMessage))
    {
        if ((caproMessage.m_serviceDescription.getServiceIDString() == IdString("service1"))
            && (caproMessage.m_serviceDescription.getInstanceIDString() == IdString("instance1"))
            && ((caproMessage.m_serviceDescription.getEventIDString() == IdString(iox::capro::AnyEventString))))
        {
            serviceFound = true;
            break;
        }
    }

    EXPECT_THAT(serviceFound, Eq(true));
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: objshimp.hxx,v $
 *
 *  $Revision: 1.23 $
 *
 *  last change: $Author: rt $ $Date: 2005-01-11 13:32:31 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _SFX_OBJSHIMP_HXX
#define _SFX_OBJSHIMP_HXX

//#include <hash_map>

#ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_
#include <com/sun/star/frame/XModel.hpp>
#endif
#ifndef _DATETIME_HXX
#include <tools/datetime.hxx>
#endif

#include <svtools/securityoptions.hxx>
#include "objsh.hxx"
#include "bitset.hxx"

namespace svtools { class AsynchronLink; }

//====================================================================

DBG_NAMEEX(SfxObjectShell);

class SfxViewFrame;
struct MarkData_Impl
{
    String aMark;
    String aUserData;
    SfxViewFrame* pFrame;
};

class SfxFrame;
class SfxDialogLibraryContainer;
class SfxScriptLibraryContainer;
class SfxToolBoxConfig;
class SfxAcceleratorManager;
struct SfxObjectShell_Impl
{
    ::comphelper::EmbeddedObjectContainer* mpObjectContainer;
    SfxAcceleratorManager*  pAccMgr;
    SfxDocumentInfo*    pDocInfo;
    SfxConfigManager*   pCfgMgr;
    BasicManager*       pBasicMgr;          // Doc-BASIC oder 0
    SfxScriptLibraryContainer* pBasicLibContainer;
    SfxDialogLibraryContainer* pDialogLibContainer;
    SfxProgress*        pProgress;
    String              aTitle;
    String              aTempName;
    DateTime            nTime;
    sal_uInt16          nVisualDocumentNumber;
    sal_Int16           nDocumentSignatureState;
    sal_Int16           nScriptingSignatureState;
    sal_Bool            bTemplateConfig:1,
                        bInList:1,          // ob per First/Next erreichbar
                        bClosing:1,         // sal_True w"aehrend Close(), um Benachrichtigungs-Rekursionen zu verhindern
                        bSetInPlaceObj:1,   // sal_True, falls bereits versucht wurde pInPlaceObject zu casten
                        bIsSaving:1,
                        bPasswd:1,
                        bIsTmp:1,
                        bIsNamedVisible:1,
                        bIsTemplate:1,
                        bIsAbortingImport:1,  // Importvorgang soll abgebrochen werden.
                        bImportDone : 1, //Import schon fertig? Fuer AutoReload von Docs.
                        bInPrepareClose : 1,
                        bPreparedForClose : 1,
                        bWaitingForPicklist : 1,// Muss noch in die Pickliste
                        bModuleSearched : 1,
                        bIsBasicDefault : 1,
                        bIsHelpObjSh : 1,
                        bForbidCaching : 1,
                        bForbidReload : 1,
                        bSupportsEventMacros: 1,
                        bLoadingWindows: 1,
                        bBasicInitialized :1,
                        bHidden :1, // indicates a hidden view shell
                        bIsPrintJobCancelable :1, // Stampit disable/enable cancel button for print jobs ... default = true = enable!
                        bOwnsStorage:1,
                        bNoBaseURL:1;

    String              aNewName;  // Der Name, unter dem das Doc gespeichert
                                   // werden soll
    IndexBitSet         aBitSet;
    sal_uInt32               lErr;
    sal_uInt16              nEventId;           // falls vor Activate noch ein
                                            // Open/Create gesendet werden mu/s
    sal_Bool                bDoNotTouchDocInfo;

    AutoReloadTimer_Impl *pReloadTimer;
    MarkData_Impl*      pMarkData;
    sal_uInt16              nLoadedFlags;
    String              aMark;
    Size                aViewSize;          // wird leider vom Writer beim
    sal_Bool                bInFrame;           // HTML-Import gebraucht
    sal_Bool                bModalMode;
    sal_Bool                bRunningMacro;
    sal_Bool                bReloadAvailable;
    sal_uInt16              nAutoLoadLocks;
    SfxModule*              pModule;
    SfxFrame*               pFrame;
    SfxToolBoxConfig*       pTbxConfig;
    SfxEventConfigItem_Impl* pEventConfig;
    SfxObjectShellFlags     eFlags;
    svtools::AsynchronLink* pCloser;
    String                  aBaseURL;
    sal_Bool                bReadOnlyUI;
    SvRefBaseRef            xHeaderAttributes;
    sal_Bool                bHiddenLockedByAPI;
    sal_Bool                bInCloseEvent;
    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel >             xModel;
    sal_uInt16              nStyleFilter;
    sal_Int16                nMacroMode;
    sal_Bool                bDisposing;

    sal_Bool                m_bEnableSetModified;
    sal_Bool                m_bIsModified;

    Rectangle               m_aVisArea;
    MapUnit                 m_nMapUnit;

    sal_Bool                m_bCreateTempStor;
    ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage > m_xDocStorage;

    sal_Bool                m_bIsInit;

    SfxObjectShell_Impl() :
        pAccMgr(0),
        nTime(),
        bIsTmp( sal_False),
        bClosing( sal_False),
        bSetInPlaceObj( sal_False),
        bPasswd( sal_False),
        pBasicMgr( 0),
        pBasicLibContainer( 0 ),
        pDialogLibContainer( 0 ),
        pProgress( 0),
        nVisualDocumentNumber( USHRT_MAX),
        nDocumentSignatureState( SIGNATURESTATE_UNKNOWN ),
        nScriptingSignatureState( SIGNATURESTATE_UNKNOWN ),
        bIsSaving( sal_False),
        bIsNamedVisible( sal_False),
        pCfgMgr( 0),
        bTemplateConfig( sal_False),
        bIsBasicDefault( sal_True ),
        bIsTemplate(sal_False),
        lErr(ERRCODE_NONE),
        nEventId ( 0),
        pDocInfo ( 0),
        bIsAbortingImport ( sal_False),
        bInList ( sal_False),
        bImportDone ( sal_False),
        pReloadTimer ( 0),
        nLoadedFlags ( SFX_LOADED_MAINDOCUMENT ),
        pMarkData( 0 ),
        bInFrame( sal_False ),
        bModalMode( sal_False ),
        bRunningMacro( sal_False ),
        bReloadAvailable( sal_False ),
        nAutoLoadLocks( 0 ),
        bInPrepareClose( sal_False ),
        bPreparedForClose( sal_False ),
        bWaitingForPicklist( sal_False ),
        pModule( 0 ),
        bModuleSearched( sal_False ),
        pFrame( 0 ),
        pTbxConfig( 0 ),
        pEventConfig(NULL),
        bIsHelpObjSh( sal_False ),
        bForbidCaching( sal_False ),
        bDoNotTouchDocInfo( sal_False ),
        bForbidReload( sal_False ),
        bBasicInitialized( sal_False ),
        eFlags( SFXOBJECTSHELL_UNDEFINED ),
        pCloser( 0 ),
        bSupportsEventMacros( sal_True ),
        bReadOnlyUI( sal_False ),
        bHiddenLockedByAPI( sal_False ),
        bInCloseEvent( sal_False ),
        bLoadingWindows( sal_False ),
        bHidden( sal_False )
        , nStyleFilter( 0 )
        , nMacroMode( -1 )
        , bDisposing( sal_False )
        , bIsPrintJobCancelable( sal_True )
        , m_bEnableSetModified( sal_True )
        , m_bIsModified( sal_False )
        , m_nMapUnit( MAP_100TH_MM )
        , m_bCreateTempStor( sal_False )
        , m_bIsInit( sal_False )
        , mpObjectContainer(0)
        , bOwnsStorage( sal_True )
        , bNoBaseURL( sal_False )
    {}
    ~SfxObjectShell_Impl();

};

#endif

<commit_msg>INTEGRATION: CWS fwkfinal1 (1.23.120); FILE MERGED 2005/03/15 16:20:04 mba 1.23.120.1: #i43920#: new events<commit_after>/*************************************************************************
 *
 *  $RCSfile: objshimp.hxx,v $
 *
 *  $Revision: 1.24 $
 *
 *  last change: $Author: vg $ $Date: 2005-03-23 14:25:42 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _SFX_OBJSHIMP_HXX
#define _SFX_OBJSHIMP_HXX

//#include <hash_map>

#ifndef _COM_SUN_STAR_FRAME_XMODEL_HPP_
#include <com/sun/star/frame/XModel.hpp>
#endif
#ifndef _DATETIME_HXX
#include <tools/datetime.hxx>
#endif

#include <svtools/securityoptions.hxx>
#include "objsh.hxx"
#include "bitset.hxx"

namespace svtools { class AsynchronLink; }

//====================================================================

DBG_NAMEEX(SfxObjectShell);

class SfxViewFrame;
struct MarkData_Impl
{
    String aMark;
    String aUserData;
    SfxViewFrame* pFrame;
};

class SfxFrame;
class SfxDialogLibraryContainer;
class SfxScriptLibraryContainer;
class SfxToolBoxConfig;
class SfxAcceleratorManager;
struct SfxObjectShell_Impl
{
    ::comphelper::EmbeddedObjectContainer* mpObjectContainer;
    SfxAcceleratorManager*  pAccMgr;
    SfxDocumentInfo*    pDocInfo;
    SfxConfigManager*   pCfgMgr;
    BasicManager*       pBasicMgr;          // Doc-BASIC oder 0
    SfxScriptLibraryContainer* pBasicLibContainer;
    SfxDialogLibraryContainer* pDialogLibContainer;
    SfxProgress*        pProgress;
    String              aTitle;
    String              aTempName;
    DateTime            nTime;
    sal_uInt16          nVisualDocumentNumber;
    sal_Int16           nDocumentSignatureState;
    sal_Int16           nScriptingSignatureState;
    sal_Bool            bTemplateConfig:1,
                        bInList:1,          // ob per First/Next erreichbar
                        bClosing:1,         // sal_True w"aehrend Close(), um Benachrichtigungs-Rekursionen zu verhindern
                        bSetInPlaceObj:1,   // sal_True, falls bereits versucht wurde pInPlaceObject zu casten
                        bIsSaving:1,
                        bPasswd:1,
                        bIsTmp:1,
                        bIsNamedVisible:1,
                        bIsTemplate:1,
                        bIsAbortingImport:1,  // Importvorgang soll abgebrochen werden.
                        bImportDone : 1, //Import schon fertig? Fuer AutoReload von Docs.
                        bInPrepareClose : 1,
                        bPreparedForClose : 1,
                        bWaitingForPicklist : 1,// Muss noch in die Pickliste
                        bModuleSearched : 1,
                        bIsBasicDefault : 1,
                        bIsHelpObjSh : 1,
                        bForbidCaching : 1,
                        bForbidReload : 1,
                        bSupportsEventMacros: 1,
                        bLoadingWindows: 1,
                        bBasicInitialized :1,
                        bHidden :1, // indicates a hidden view shell
                        bIsPrintJobCancelable :1, // Stampit disable/enable cancel button for print jobs ... default = true = enable!
                        bOwnsStorage:1,
                        bNoBaseURL:1,
                        bInitialized:1;

    String              aNewName;  // Der Name, unter dem das Doc gespeichert
                                   // werden soll
    IndexBitSet         aBitSet;
    sal_uInt32               lErr;
    sal_uInt16              nEventId;           // falls vor Activate noch ein
                                            // Open/Create gesendet werden mu/s
    sal_Bool                bDoNotTouchDocInfo;

    AutoReloadTimer_Impl *pReloadTimer;
    MarkData_Impl*      pMarkData;
    sal_uInt16              nLoadedFlags;
    String              aMark;
    Size                aViewSize;          // wird leider vom Writer beim
    sal_Bool                bInFrame;           // HTML-Import gebraucht
    sal_Bool                bModalMode;
    sal_Bool                bRunningMacro;
    sal_Bool                bReloadAvailable;
    sal_uInt16              nAutoLoadLocks;
    SfxModule*              pModule;
    SfxFrame*               pFrame;
    SfxToolBoxConfig*       pTbxConfig;
    SfxEventConfigItem_Impl* pEventConfig;
    SfxObjectShellFlags     eFlags;
    svtools::AsynchronLink* pCloser;
    String                  aBaseURL;
    sal_Bool                bReadOnlyUI;
    SvRefBaseRef            xHeaderAttributes;
    sal_Bool                bHiddenLockedByAPI;
    sal_Bool                bInCloseEvent;
    ::com::sun::star::uno::Reference< ::com::sun::star::frame::XModel >             xModel;
    sal_uInt16              nStyleFilter;
    sal_Int16                nMacroMode;
    sal_Bool                bDisposing;

    sal_Bool                m_bEnableSetModified;
    sal_Bool                m_bIsModified;

    Rectangle               m_aVisArea;
    MapUnit                 m_nMapUnit;

    sal_Bool                m_bCreateTempStor;
    ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage > m_xDocStorage;

    sal_Bool                m_bIsInit;

    SfxObjectShell_Impl() :
        pAccMgr(0),
        nTime(),
        bIsTmp( sal_False),
        bClosing( sal_False),
        bSetInPlaceObj( sal_False),
        bPasswd( sal_False),
        pBasicMgr( 0),
        pBasicLibContainer( 0 ),
        pDialogLibContainer( 0 ),
        pProgress( 0),
        nVisualDocumentNumber( USHRT_MAX),
        nDocumentSignatureState( SIGNATURESTATE_UNKNOWN ),
        nScriptingSignatureState( SIGNATURESTATE_UNKNOWN ),
        bIsSaving( sal_False),
        bIsNamedVisible( sal_False),
        pCfgMgr( 0),
        bTemplateConfig( sal_False),
        bIsBasicDefault( sal_True ),
        bIsTemplate(sal_False),
        lErr(ERRCODE_NONE),
        nEventId ( 0),
        pDocInfo ( 0),
        bIsAbortingImport ( sal_False),
        bInList ( sal_False),
        bImportDone ( sal_False),
        pReloadTimer ( 0),
        nLoadedFlags ( SFX_LOADED_MAINDOCUMENT ),
        pMarkData( 0 ),
        bInFrame( sal_False ),
        bModalMode( sal_False ),
        bRunningMacro( sal_False ),
        bReloadAvailable( sal_False ),
        nAutoLoadLocks( 0 ),
        bInPrepareClose( sal_False ),
        bPreparedForClose( sal_False ),
        bWaitingForPicklist( sal_False ),
        pModule( 0 ),
        bModuleSearched( sal_False ),
        pFrame( 0 ),
        pTbxConfig( 0 ),
        pEventConfig(NULL),
        bIsHelpObjSh( sal_False ),
        bForbidCaching( sal_False ),
        bDoNotTouchDocInfo( sal_False ),
        bForbidReload( sal_False ),
        bBasicInitialized( sal_False ),
        eFlags( SFXOBJECTSHELL_UNDEFINED ),
        pCloser( 0 ),
        bSupportsEventMacros( sal_True ),
        bReadOnlyUI( sal_False ),
        bHiddenLockedByAPI( sal_False ),
        bInCloseEvent( sal_False ),
        bLoadingWindows( sal_False ),
        bHidden( sal_False )
        , nStyleFilter( 0 )
        , nMacroMode( -1 )
        , bDisposing( sal_False )
        , bIsPrintJobCancelable( sal_True )
        , m_bEnableSetModified( sal_True )
        , m_bIsModified( sal_False )
        , m_nMapUnit( MAP_100TH_MM )
        , m_bCreateTempStor( sal_False )
        , m_bIsInit( sal_False )
        , mpObjectContainer(0)
        , bOwnsStorage( sal_True )
        , bNoBaseURL( sal_False )
        , bInitialized( sal_False )
    {}
    ~SfxObjectShell_Impl();

};

#endif

<|endoftext|>


<commit_before>// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#if !defined(_WIN32)
#include "iceoryx_utils/internal/posix_wrapper/message_queue.hpp"
#include "iceoryx_utils/internal/posix_wrapper/unix_domain_socket.hpp"

#include "test.hpp"

#include <chrono>

using namespace ::testing;
using namespace iox;
using namespace iox::posix;

#if defined(__APPLE__)
using IpcChannelTypes = Types<UnixDomainSocket>;
#else
using IpcChannelTypes = Types<MessageQueue, UnixDomainSocket>;
#endif

constexpr char goodName[] = "channel_test";
constexpr char anotherGoodName[] = "horst";
constexpr char theUnknown[] = "WhoeverYouAre";

template <typename T>
class IpcChannel_test : public Test
{
  public:
    using IpcChannelType = T;

    void SetUp()
    {
        auto serverResult = IpcChannelType::create(
            goodName, IpcChannelMode::BLOCKING, IpcChannelSide::SERVER, MaxMsgSize, MaxMsgNumber);
        ASSERT_THAT(serverResult.has_error(), Eq(false));
        server = std::move(serverResult.value());
        internal::CaptureStderr();

        auto clientResult = IpcChannelType::create(
            goodName, IpcChannelMode::BLOCKING, IpcChannelSide::CLIENT, MaxMsgSize, MaxMsgNumber);
        ASSERT_THAT(clientResult.has_error(), Eq(false));
        client = std::move(clientResult.value());
    }

    void TearDown()
    {
        std::string output = internal::GetCapturedStderr();
        if (Test::HasFailure())
        {
            std::cout << output << std::endl;
        }
    }

    ~IpcChannel_test()
    {
    }

    static const size_t MaxMsgSize;
    static constexpr uint64_t MaxMsgNumber = 10U;
    IpcChannelType server;
    IpcChannelType client;
};

template <typename T>
const size_t IpcChannel_test<T>::MaxMsgSize = IpcChannelType::MAX_MESSAGE_SIZE;
template <typename T>
constexpr uint64_t IpcChannel_test<T>::MaxMsgNumber;

/// we require TYPED_TEST since we support gtest 1.8 for our safety targets
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
TYPED_TEST_CASE(IpcChannel_test, IpcChannelTypes);
#pragma GCC diagnostic pop

TYPED_TEST(IpcChannel_test, createNoName)
{
    auto serverResult = TestFixture::IpcChannelType::create("", IpcChannelMode::BLOCKING, IpcChannelSide::SERVER);
    EXPECT_TRUE(serverResult.has_error());
    ASSERT_THAT(serverResult.get_error(), Eq(IpcChannelError::INVALID_CHANNEL_NAME));
}

TYPED_TEST(IpcChannel_test, createAgain)
{
    // if there is a leftover from a crashed channel, we can create a new one. This is simulated by creating twice
    auto first = TestFixture::IpcChannelType::create(anotherGoodName, IpcChannelMode::BLOCKING, IpcChannelSide::SERVER);
    EXPECT_FALSE(first.has_error());
    auto second =
        TestFixture::IpcChannelType::create(anotherGoodName, IpcChannelMode::BLOCKING, IpcChannelSide::SERVER);
    EXPECT_FALSE(second.has_error());
}

TYPED_TEST(IpcChannel_test, createAgainAndEmpty)
{
    using namespace iox::units;
    using namespace std::chrono;

    auto serverResult =
        TestFixture::IpcChannelType::create(anotherGoodName, IpcChannelMode::BLOCKING, IpcChannelSide::SERVER);
    EXPECT_FALSE(serverResult.has_error());
    auto server = std::move(serverResult.value());

    auto clientResult =
        TestFixture::IpcChannelType::create(anotherGoodName, IpcChannelMode::BLOCKING, IpcChannelSide::CLIENT);
    EXPECT_FALSE(clientResult.has_error());
    auto client = std::move(clientResult.value());

    // send and receive as usual
    std::string message = "Hey, I'm talking to you";
    bool sent = client.send(message).has_error();
    EXPECT_FALSE(sent);

    auto receivedMessage = server.receive();
    ASSERT_THAT(receivedMessage.has_error(), Eq(false));
    EXPECT_EQ(message, *receivedMessage);

    // send a message, create the server again and there is no message
    std::string newMessage = "I'm still talking to you brother";
    sent = client.send(newMessage).has_error();
    EXPECT_FALSE(sent);

    auto second =
        TestFixture::IpcChannelType::create(anotherGoodName, IpcChannelMode::BLOCKING, IpcChannelSide::SERVER);
    EXPECT_FALSE(second.has_error());
    server = std::move(second.value());

    Duration timeout = 100_ms;
    auto received = server.timedReceive(timeout);
    ASSERT_TRUE(received.has_error());
    ASSERT_THAT(received.get_error(), Eq(IpcChannelError::TIMEOUT));
}

TYPED_TEST(IpcChannel_test, clientWithoutServerFails)
{
    auto clientResult =
        TestFixture::IpcChannelType::create(anotherGoodName, IpcChannelMode::BLOCKING, IpcChannelSide::CLIENT);
    EXPECT_TRUE(clientResult.has_error());
    ASSERT_THAT(clientResult.get_error(), Eq(IpcChannelError::NO_SUCH_CHANNEL));
}

TYPED_TEST(IpcChannel_test, NotOutdatedOne)
{
    auto serverResult =
        TestFixture::IpcChannelType::create(anotherGoodName, IpcChannelMode::BLOCKING, IpcChannelSide::SERVER);
    EXPECT_FALSE(serverResult.has_error());
    auto server = std::move(serverResult.value());

    auto clientResult =
        TestFixture::IpcChannelType::create(anotherGoodName, IpcChannelMode::BLOCKING, IpcChannelSide::CLIENT);
    EXPECT_FALSE(clientResult.has_error());
    auto client = std::move(clientResult.value());

    auto outdated = client.isOutdated();
    EXPECT_FALSE(outdated.has_error());
    EXPECT_FALSE(outdated.value());
}

TYPED_TEST(IpcChannel_test, OutdatedOne)
{
    if (std::is_same<typename TestFixture::IpcChannelType, UnixDomainSocket>::value)
    {
        // isOutdated cannot be realized for unix domain sockets
        return;
    }

    auto serverResult =
        TestFixture::IpcChannelType::create(anotherGoodName, IpcChannelMode::BLOCKING, IpcChannelSide::SERVER);
    EXPECT_FALSE(serverResult.has_error());
    auto server = std::move(serverResult.value());

    auto clientResult =
        TestFixture::IpcChannelType::create(anotherGoodName, IpcChannelMode::BLOCKING, IpcChannelSide::CLIENT);
    EXPECT_FALSE(clientResult.has_error());
    auto client = std::move(clientResult.value());

    // destroy the server and the client is outdated
    auto dest = server.destroy();
    ASSERT_FALSE(dest.has_error());

    auto outdated = client.isOutdated();
    EXPECT_FALSE(outdated.has_error());
    EXPECT_TRUE(outdated.value());
}

TYPED_TEST(IpcChannel_test, unlinkExistingOne)
{
    auto first = TestFixture::IpcChannelType::create(anotherGoodName, IpcChannelMode::BLOCKING, IpcChannelSide::SERVER);
    EXPECT_FALSE(first.has_error());
    auto ret = TestFixture::IpcChannelType::unlinkIfExists(anotherGoodName);
    EXPECT_FALSE(ret.has_error());
    EXPECT_TRUE(ret.value());
}

TYPED_TEST(IpcChannel_test, unlinkNonExistingOne)
{
    auto ret = TestFixture::IpcChannelType::unlinkIfExists(theUnknown);
    EXPECT_FALSE(ret.has_error());
    EXPECT_FALSE(ret.value());
}

TYPED_TEST(IpcChannel_test, sendAndReceive)
{
    std::string message = "Hey, I'm talking to you";
    bool sent = this->client.send(message).has_error();
    EXPECT_FALSE(sent);

    std::string anotherMessage = "This is a message";
    sent = this->client.send(anotherMessage).has_error();
    EXPECT_FALSE(sent);

    auto receivedMessage = this->server.receive();
    ASSERT_THAT(receivedMessage.has_error(), Eq(false));
    EXPECT_EQ(message, *receivedMessage);

    receivedMessage = this->server.receive();
    ASSERT_THAT(receivedMessage.has_error(), Eq(false));
    EXPECT_EQ(anotherMessage, *receivedMessage);
}

TYPED_TEST(IpcChannel_test, invalidAfterDestroy)
{
    this->client.destroy();
    ASSERT_FALSE(this->client.isInitialized());
    this->server.destroy();
    ASSERT_FALSE(this->server.isInitialized());
}

TYPED_TEST(IpcChannel_test, sendAfterClientDestroy)
{
    auto dest = this->client.destroy();
    ASSERT_FALSE(dest.has_error());

    std::string message = "Should never be sent";
    bool sendError = this->client.send(message).has_error();
    EXPECT_TRUE(sendError);
}

TYPED_TEST(IpcChannel_test, sendAfterServerDestroy)
{
    if (std::is_same<typename TestFixture::IpcChannelType, MessageQueue>::value)
    {
        // We still can send to the message queue is we destroy the server
        // it would be outdated, this is checked in another test
        return;
    }

    auto dest = this->server.destroy();
    ASSERT_FALSE(dest.has_error());

    std::string message = "Try to send me";
    auto sendResult = this->client.send(message);
    EXPECT_TRUE(sendResult.has_error());
}

TYPED_TEST(IpcChannel_test, receiveAfterServerDestroy)
{
    std::string message = "hello world!";
    bool sendError = this->client.send(message).has_error();
    EXPECT_FALSE(sendError);

    auto dest = this->server.destroy();
    ASSERT_FALSE(dest.has_error());

    bool receiveError = this->server.receive().has_error();
    EXPECT_THAT(receiveError, Eq(true));
}

TYPED_TEST(IpcChannel_test, sendMoreThanAllowed)
{
    std::string shortMessage = "Iceoryx rules.";
    ASSERT_THAT(this->client.send(shortMessage).has_error(), Eq(false));

    std::string longMessage(this->server.MAX_MESSAGE_SIZE + 8, 'x');
    ASSERT_THAT(this->client.send(longMessage).has_error(), Eq(true));

    auto receivedMessage = this->server.receive();
    ASSERT_THAT(receivedMessage.has_error(), Eq(false));
    EXPECT_EQ(shortMessage, receivedMessage.value());
}

TYPED_TEST(IpcChannel_test, sendMaxMessageSize)
{
    std::string message(this->MaxMsgSize - 1, 'x');
    auto clientReturn = this->client.send(message);
    ASSERT_THAT(clientReturn.has_error(), Eq(false));

    auto receivedMessage = this->server.receive();
    ASSERT_THAT(receivedMessage.has_error(), Eq(false));
    EXPECT_EQ(message, receivedMessage.value());
}

TYPED_TEST(IpcChannel_test, wildCreate)
{
    auto result = TestFixture::IpcChannelType::create();
    ASSERT_THAT(result.has_error(), Eq(true));
}

#if !defined(__APPLE__)
TYPED_TEST(IpcChannel_test, timedSend)
{
    using namespace iox::units;
    using namespace std::chrono;

    std::string msg = "ISG rules. And some more                                                                        "
                      "data to have a bit                                                                              "
                      "longer message";

    Duration maxTimeout = 100_ms;
    Duration minTimeoutTolerance = 10_ms;
    Duration maxTimeoutTolerance = 20_ms;

    // send till it breaks
    for (;;)
    {
        auto before = system_clock::now();
        auto result = this->client.timedSend(msg, maxTimeout);
        auto after = system_clock::now();
        if (result.has_error())
        {
            ASSERT_THAT(result.get_error(), Eq(IpcChannelError::TIMEOUT));
            // Do not exceed timeout
            auto timeDiff_ms = duration_cast<milliseconds>(after - before);
            EXPECT_LT(timeDiff_ms.count(), (maxTimeout + maxTimeoutTolerance).milliSeconds<int64_t>());

            // Check if timedSend has blocked for ~maxTimeout and has not returned immediately
            EXPECT_GT(timeDiff_ms.count(), (maxTimeout - minTimeoutTolerance).milliSeconds<int64_t>());

            break;
        }
    }
}
#endif

TYPED_TEST(IpcChannel_test, timedReceive)
{
    using namespace iox::units;
    using namespace std::chrono;

    std::string msg = "very useful text for tranmission";
    Duration timeout = 100_ms;
    Duration minTimeoutTolerance = 10_ms;
    Duration maxTimeoutTolerance = 20_ms;

    this->client.send(msg);

    auto received = this->server.timedReceive(timeout);
    ASSERT_FALSE(received.has_error());

    EXPECT_EQ(received.value(), msg);

    auto before = system_clock::now();
    received = this->server.timedReceive(timeout);
    auto after = system_clock::now();

    ASSERT_TRUE(received.has_error());
    ASSERT_THAT(received.get_error(), Eq(IpcChannelError::TIMEOUT));

    // Do not exceed timeout
    auto timeDiff_ms = duration_cast<milliseconds>(after - before);
    EXPECT_LT(timeDiff_ms.count(), (timeout + maxTimeoutTolerance).milliSeconds<int64_t>());

    // Check if timedReceive has blocked for ~timeout and has not returned immediately
    EXPECT_GT(timeDiff_ms.count(), (timeout - minTimeoutTolerance).milliSeconds<int64_t>());
}
#endif
<commit_msg>iox-#381 add testcase for slash<commit_after>// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#if !defined(_WIN32)
#include "iceoryx_utils/internal/posix_wrapper/message_queue.hpp"
#include "iceoryx_utils/internal/posix_wrapper/unix_domain_socket.hpp"

#include "test.hpp"

#include <chrono>

using namespace ::testing;
using namespace iox;
using namespace iox::posix;

#if defined(__APPLE__)
using IpcChannelTypes = Types<UnixDomainSocket>;
#else
using IpcChannelTypes = Types<MessageQueue, UnixDomainSocket>;
#endif

constexpr char goodName[] = "channel_test";
constexpr char anotherGoodName[] = "horst";
constexpr char theUnknown[] = "WhoeverYouAre";
constexpr char slashName[] = "/miau";

template <typename T>
class IpcChannel_test : public Test
{
  public:
    using IpcChannelType = T;

    void SetUp()
    {
        auto serverResult = IpcChannelType::create(
            goodName, IpcChannelMode::BLOCKING, IpcChannelSide::SERVER, MaxMsgSize, MaxMsgNumber);
        ASSERT_THAT(serverResult.has_error(), Eq(false));
        server = std::move(serverResult.value());
        internal::CaptureStderr();

        auto clientResult = IpcChannelType::create(
            goodName, IpcChannelMode::BLOCKING, IpcChannelSide::CLIENT, MaxMsgSize, MaxMsgNumber);
        ASSERT_THAT(clientResult.has_error(), Eq(false));
        client = std::move(clientResult.value());
    }

    void TearDown()
    {
        std::string output = internal::GetCapturedStderr();
        if (Test::HasFailure())
        {
            std::cout << output << std::endl;
        }
    }

    ~IpcChannel_test()
    {
    }

    static const size_t MaxMsgSize;
    static constexpr uint64_t MaxMsgNumber = 10U;
    IpcChannelType server;
    IpcChannelType client;
};

template <typename T>
const size_t IpcChannel_test<T>::MaxMsgSize = IpcChannelType::MAX_MESSAGE_SIZE;
template <typename T>
constexpr uint64_t IpcChannel_test<T>::MaxMsgNumber;

/// we require TYPED_TEST since we support gtest 1.8 for our safety targets
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
TYPED_TEST_CASE(IpcChannel_test, IpcChannelTypes);
#pragma GCC diagnostic pop

TYPED_TEST(IpcChannel_test, createNoName)
{
    auto serverResult = TestFixture::IpcChannelType::create("", IpcChannelMode::BLOCKING, IpcChannelSide::SERVER);
    EXPECT_TRUE(serverResult.has_error());
    ASSERT_THAT(serverResult.get_error(), Eq(IpcChannelError::INVALID_CHANNEL_NAME));
}

TYPED_TEST(IpcChannel_test, createWithLeadingSlash)
{
    auto serverResult = TestFixture::IpcChannelType::create(slashName, IpcChannelMode::BLOCKING, IpcChannelSide::SERVER);
    EXPECT_FALSE(serverResult.has_error());
}

TYPED_TEST(IpcChannel_test, createAgain)
{
    // if there is a leftover from a crashed channel, we can create a new one. This is simulated by creating twice
    auto first = TestFixture::IpcChannelType::create(anotherGoodName, IpcChannelMode::BLOCKING, IpcChannelSide::SERVER);
    EXPECT_FALSE(first.has_error());
    auto second =
        TestFixture::IpcChannelType::create(anotherGoodName, IpcChannelMode::BLOCKING, IpcChannelSide::SERVER);
    EXPECT_FALSE(second.has_error());
}

TYPED_TEST(IpcChannel_test, createAgainAndEmpty)
{
    using namespace iox::units;
    using namespace std::chrono;

    auto serverResult =
        TestFixture::IpcChannelType::create(anotherGoodName, IpcChannelMode::BLOCKING, IpcChannelSide::SERVER);
    EXPECT_FALSE(serverResult.has_error());
    auto server = std::move(serverResult.value());

    auto clientResult =
        TestFixture::IpcChannelType::create(anotherGoodName, IpcChannelMode::BLOCKING, IpcChannelSide::CLIENT);
    EXPECT_FALSE(clientResult.has_error());
    auto client = std::move(clientResult.value());

    // send and receive as usual
    std::string message = "Hey, I'm talking to you";
    bool sent = client.send(message).has_error();
    EXPECT_FALSE(sent);

    auto receivedMessage = server.receive();
    ASSERT_THAT(receivedMessage.has_error(), Eq(false));
    EXPECT_EQ(message, *receivedMessage);

    // send a message, create the server again and there is no message
    std::string newMessage = "I'm still talking to you brother";
    sent = client.send(newMessage).has_error();
    EXPECT_FALSE(sent);

    auto second =
        TestFixture::IpcChannelType::create(anotherGoodName, IpcChannelMode::BLOCKING, IpcChannelSide::SERVER);
    EXPECT_FALSE(second.has_error());
    server = std::move(second.value());

    Duration timeout = 100_ms;
    auto received = server.timedReceive(timeout);
    ASSERT_TRUE(received.has_error());
    ASSERT_THAT(received.get_error(), Eq(IpcChannelError::TIMEOUT));
}

TYPED_TEST(IpcChannel_test, clientWithoutServerFails)
{
    auto clientResult =
        TestFixture::IpcChannelType::create(anotherGoodName, IpcChannelMode::BLOCKING, IpcChannelSide::CLIENT);
    EXPECT_TRUE(clientResult.has_error());
    ASSERT_THAT(clientResult.get_error(), Eq(IpcChannelError::NO_SUCH_CHANNEL));
}

TYPED_TEST(IpcChannel_test, NotOutdatedOne)
{
    auto serverResult =
        TestFixture::IpcChannelType::create(anotherGoodName, IpcChannelMode::BLOCKING, IpcChannelSide::SERVER);
    EXPECT_FALSE(serverResult.has_error());
    auto server = std::move(serverResult.value());

    auto clientResult =
        TestFixture::IpcChannelType::create(anotherGoodName, IpcChannelMode::BLOCKING, IpcChannelSide::CLIENT);
    EXPECT_FALSE(clientResult.has_error());
    auto client = std::move(clientResult.value());

    auto outdated = client.isOutdated();
    EXPECT_FALSE(outdated.has_error());
    EXPECT_FALSE(outdated.value());
}

TYPED_TEST(IpcChannel_test, OutdatedOne)
{
    if (std::is_same<typename TestFixture::IpcChannelType, UnixDomainSocket>::value)
    {
        // isOutdated cannot be realized for unix domain sockets
        return;
    }

    auto serverResult =
        TestFixture::IpcChannelType::create(anotherGoodName, IpcChannelMode::BLOCKING, IpcChannelSide::SERVER);
    EXPECT_FALSE(serverResult.has_error());
    auto server = std::move(serverResult.value());

    auto clientResult =
        TestFixture::IpcChannelType::create(anotherGoodName, IpcChannelMode::BLOCKING, IpcChannelSide::CLIENT);
    EXPECT_FALSE(clientResult.has_error());
    auto client = std::move(clientResult.value());

    // destroy the server and the client is outdated
    auto dest = server.destroy();
    ASSERT_FALSE(dest.has_error());

    auto outdated = client.isOutdated();
    EXPECT_FALSE(outdated.has_error());
    EXPECT_TRUE(outdated.value());
}

TYPED_TEST(IpcChannel_test, unlinkExistingOne)
{
    auto first = TestFixture::IpcChannelType::create(anotherGoodName, IpcChannelMode::BLOCKING, IpcChannelSide::SERVER);
    EXPECT_FALSE(first.has_error());
    auto ret = TestFixture::IpcChannelType::unlinkIfExists(anotherGoodName);
    EXPECT_FALSE(ret.has_error());
    EXPECT_TRUE(ret.value());
}

TYPED_TEST(IpcChannel_test, unlinkNonExistingOne)
{
    auto ret = TestFixture::IpcChannelType::unlinkIfExists(theUnknown);
    EXPECT_FALSE(ret.has_error());
    EXPECT_FALSE(ret.value());
}

TYPED_TEST(IpcChannel_test, sendAndReceive)
{
    std::string message = "Hey, I'm talking to you";
    bool sent = this->client.send(message).has_error();
    EXPECT_FALSE(sent);

    std::string anotherMessage = "This is a message";
    sent = this->client.send(anotherMessage).has_error();
    EXPECT_FALSE(sent);

    auto receivedMessage = this->server.receive();
    ASSERT_THAT(receivedMessage.has_error(), Eq(false));
    EXPECT_EQ(message, *receivedMessage);

    receivedMessage = this->server.receive();
    ASSERT_THAT(receivedMessage.has_error(), Eq(false));
    EXPECT_EQ(anotherMessage, *receivedMessage);
}

TYPED_TEST(IpcChannel_test, invalidAfterDestroy)
{
    this->client.destroy();
    ASSERT_FALSE(this->client.isInitialized());
    this->server.destroy();
    ASSERT_FALSE(this->server.isInitialized());
}

TYPED_TEST(IpcChannel_test, sendAfterClientDestroy)
{
    auto dest = this->client.destroy();
    ASSERT_FALSE(dest.has_error());

    std::string message = "Should never be sent";
    bool sendError = this->client.send(message).has_error();
    EXPECT_TRUE(sendError);
}

TYPED_TEST(IpcChannel_test, sendAfterServerDestroy)
{
    if (std::is_same<typename TestFixture::IpcChannelType, MessageQueue>::value)
    {
        // We still can send to the message queue is we destroy the server
        // it would be outdated, this is checked in another test
        return;
    }

    auto dest = this->server.destroy();
    ASSERT_FALSE(dest.has_error());

    std::string message = "Try to send me";
    auto sendResult = this->client.send(message);
    EXPECT_TRUE(sendResult.has_error());
}

TYPED_TEST(IpcChannel_test, receiveAfterServerDestroy)
{
    std::string message = "hello world!";
    bool sendError = this->client.send(message).has_error();
    EXPECT_FALSE(sendError);

    auto dest = this->server.destroy();
    ASSERT_FALSE(dest.has_error());

    bool receiveError = this->server.receive().has_error();
    EXPECT_THAT(receiveError, Eq(true));
}

TYPED_TEST(IpcChannel_test, sendMoreThanAllowed)
{
    std::string shortMessage = "Iceoryx rules.";
    ASSERT_THAT(this->client.send(shortMessage).has_error(), Eq(false));

    std::string longMessage(this->server.MAX_MESSAGE_SIZE + 8, 'x');
    ASSERT_THAT(this->client.send(longMessage).has_error(), Eq(true));

    auto receivedMessage = this->server.receive();
    ASSERT_THAT(receivedMessage.has_error(), Eq(false));
    EXPECT_EQ(shortMessage, receivedMessage.value());
}

TYPED_TEST(IpcChannel_test, sendMaxMessageSize)
{
    std::string message(this->MaxMsgSize - 1, 'x');
    auto clientReturn = this->client.send(message);
    ASSERT_THAT(clientReturn.has_error(), Eq(false));

    auto receivedMessage = this->server.receive();
    ASSERT_THAT(receivedMessage.has_error(), Eq(false));
    EXPECT_EQ(message, receivedMessage.value());
}

TYPED_TEST(IpcChannel_test, wildCreate)
{
    auto result = TestFixture::IpcChannelType::create();
    ASSERT_THAT(result.has_error(), Eq(true));
}

#if !defined(__APPLE__)
TYPED_TEST(IpcChannel_test, timedSend)
{
    using namespace iox::units;
    using namespace std::chrono;

    std::string msg = "ISG rules. And some more                                                                        "
                      "data to have a bit                                                                              "
                      "longer message";

    Duration maxTimeout = 100_ms;
    Duration minTimeoutTolerance = 10_ms;
    Duration maxTimeoutTolerance = 20_ms;

    // send till it breaks
    for (;;)
    {
        auto before = system_clock::now();
        auto result = this->client.timedSend(msg, maxTimeout);
        auto after = system_clock::now();
        if (result.has_error())
        {
            ASSERT_THAT(result.get_error(), Eq(IpcChannelError::TIMEOUT));
            // Do not exceed timeout
            auto timeDiff_ms = duration_cast<milliseconds>(after - before);
            EXPECT_LT(timeDiff_ms.count(), (maxTimeout + maxTimeoutTolerance).milliSeconds<int64_t>());

            // Check if timedSend has blocked for ~maxTimeout and has not returned immediately
            EXPECT_GT(timeDiff_ms.count(), (maxTimeout - minTimeoutTolerance).milliSeconds<int64_t>());

            break;
        }
    }
}
#endif

TYPED_TEST(IpcChannel_test, timedReceive)
{
    using namespace iox::units;
    using namespace std::chrono;

    std::string msg = "very useful text for tranmission";
    Duration timeout = 100_ms;
    Duration minTimeoutTolerance = 10_ms;
    Duration maxTimeoutTolerance = 20_ms;

    this->client.send(msg);

    auto received = this->server.timedReceive(timeout);
    ASSERT_FALSE(received.has_error());

    EXPECT_EQ(received.value(), msg);

    auto before = system_clock::now();
    received = this->server.timedReceive(timeout);
    auto after = system_clock::now();

    ASSERT_TRUE(received.has_error());
    ASSERT_THAT(received.get_error(), Eq(IpcChannelError::TIMEOUT));

    // Do not exceed timeout
    auto timeDiff_ms = duration_cast<milliseconds>(after - before);
    EXPECT_LT(timeDiff_ms.count(), (timeout + maxTimeoutTolerance).milliSeconds<int64_t>());

    // Check if timedReceive has blocked for ~timeout and has not returned immediately
    EXPECT_GT(timeDiff_ms.count(), (timeout - minTimeoutTolerance).milliSeconds<int64_t>());
}
#endif
<|endoftext|>


<commit_before>// Copyright 2013 The Flutter 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 "impeller/entity/contents/runtime_effect_contents.h"

#include <future>
#include <memory>

#include "flutter/fml/logging.h"
#include "flutter/fml/make_copyable.h"
#include "impeller/base/validation.h"
#include "impeller/entity/contents/clip_contents.h"
#include "impeller/entity/contents/content_context.h"
#include "impeller/entity/runtime_effect.vert.h"
#include "impeller/renderer/formats.h"
#include "impeller/renderer/pipeline_library.h"
#include "impeller/renderer/render_pass.h"
#include "impeller/renderer/sampler_library.h"
#include "impeller/renderer/shader_function.h"
#include "impeller/renderer/shader_types.h"

namespace impeller {

void RuntimeEffectContents::SetRuntimeStage(
    std::shared_ptr<RuntimeStage> runtime_stage) {
  runtime_stage_ = std::move(runtime_stage);
}

void RuntimeEffectContents::SetUniformData(
    std::shared_ptr<std::vector<uint8_t>> uniform_data) {
  uniform_data_ = std::move(uniform_data);
}

void RuntimeEffectContents::SetTextureInputs(
    std::vector<TextureInput> texture_inputs) {
  texture_inputs_ = std::move(texture_inputs);
}

bool RuntimeEffectContents::Render(const ContentContext& renderer,
                                   const Entity& entity,
                                   RenderPass& pass) const {
  auto context = renderer.GetContext();
  auto library = context->GetShaderLibrary();

  //--------------------------------------------------------------------------
  /// Get or register shader.
  ///

  // TODO(113719): Register the shader function earlier.

  std::shared_ptr<const ShaderFunction> function = library->GetFunction(
      runtime_stage_->GetEntrypoint(), ShaderStage::kFragment);

  if (function && runtime_stage_->IsDirty()) {
    context->GetPipelineLibrary()->RemovePipelinesWithEntryPoint(function);
    library->UnregisterFunction(runtime_stage_->GetEntrypoint(),
                                ShaderStage::kFragment);

    function = nullptr;
  }

  if (!function) {
    std::promise<bool> promise;
    auto future = promise.get_future();

    library->RegisterFunction(
        runtime_stage_->GetEntrypoint(),
        ToShaderStage(runtime_stage_->GetShaderStage()),
        runtime_stage_->GetCodeMapping(),
        fml::MakeCopyable([promise = std::move(promise)](bool result) mutable {
          promise.set_value(result);
        }));

    if (!future.get()) {
      VALIDATION_LOG << "Failed to build runtime effect (entry point: "
                     << runtime_stage_->GetEntrypoint() << ")";
      return false;
    }

    function = library->GetFunction(runtime_stage_->GetEntrypoint(),
                                    ShaderStage::kFragment);
    if (!function) {
      VALIDATION_LOG
          << "Failed to fetch runtime effect function immediately after "
             "registering it (entry point: "
          << runtime_stage_->GetEntrypoint() << ")";
      return false;
    }

    runtime_stage_->SetClean();
  }

  //--------------------------------------------------------------------------
  /// Resolve geometry.
  ///

  auto geometry_result =
      GetGeometry()->GetPositionBuffer(renderer, entity, pass);

  //--------------------------------------------------------------------------
  /// Get or create runtime stage pipeline.
  ///

  using VS = RuntimeEffectVertexShader;
  PipelineDescriptor desc;
  desc.SetLabel("Runtime Stage");
  desc.AddStageEntrypoint(
      library->GetFunction(VS::kEntrypointName, ShaderStage::kVertex));
  desc.AddStageEntrypoint(library->GetFunction(runtime_stage_->GetEntrypoint(),
                                               ShaderStage::kFragment));
  auto vertex_descriptor = std::make_shared<VertexDescriptor>();
  if (!vertex_descriptor->SetStageInputs(VS::kAllShaderStageInputs)) {
    VALIDATION_LOG << "Failed to set stage inputs for runtime effect pipeline.";
  }
  desc.SetVertexDescriptor(std::move(vertex_descriptor));
  desc.SetColorAttachmentDescriptor(0u, {.format = PixelFormat::kDefaultColor});
  desc.SetStencilAttachmentDescriptors({});
  desc.SetStencilPixelFormat(PixelFormat::kDefaultStencil);

  auto options = OptionsFromPassAndEntity(pass, entity);
  if (geometry_result.prevent_overdraw) {
    options.stencil_compare = CompareFunction::kEqual;
    options.stencil_operation = StencilOperation::kIncrementClamp;
  }
  options.primitive_type = geometry_result.type;
  options.ApplyToPipelineDescriptor(desc);

  auto pipeline = context->GetPipelineLibrary()->GetPipeline(desc).Get();
  if (!pipeline) {
    VALIDATION_LOG << "Failed to get or create runtime effect pipeline.";
    return false;
  }

  Command cmd;
  cmd.label = "RuntimeEffectContents";
  cmd.pipeline = pipeline;
  cmd.stencil_reference = entity.GetStencilDepth();
  cmd.BindVertices(geometry_result.vertex_buffer);

  //--------------------------------------------------------------------------
  /// Vertex stage uniforms.
  ///

  VS::VertInfo frame_info;
  frame_info.mvp = Matrix::MakeOrthographic(pass.GetRenderTargetSize()) *
                   entity.GetTransformation();
  VS::BindVertInfo(cmd, pass.GetTransientsBuffer().EmplaceUniform(frame_info));

  //--------------------------------------------------------------------------
  /// Fragment stage uniforms.
  ///

  size_t buffer_index = 0;
  size_t sampler_index = 0;
  for (auto uniform : runtime_stage_->GetUniforms()) {
    // TODO(113715): Populate this metadata once GLES is able to handle
    //               non-struct uniform names.
    ShaderMetadata metadata;

    switch (uniform.type) {
      case kSampledImage: {
        FML_DCHECK(sampler_index < texture_inputs_.size());
        auto& input = texture_inputs_[sampler_index];

        auto sampler =
            context->GetSamplerLibrary()->GetSampler(input.sampler_descriptor);

        SampledImageSlot image_slot;
        image_slot.name = uniform.name.c_str();
        image_slot.texture_index = sampler_index;
        image_slot.sampler_index = sampler_index;
        cmd.BindResource(ShaderStage::kFragment, image_slot, metadata,
                         input.texture, sampler);

        sampler_index++;
        break;
      }
      case kFloat: {
        size_t alignment =
            std::max(uniform.bit_width / 8, DefaultUniformAlignment());
        auto buffer_view = pass.GetTransientsBuffer().Emplace(
            uniform_data_->data() + uniform.location * sizeof(float),
            uniform.GetSize(), alignment);

        ShaderUniformSlot uniform_slot;
        uniform_slot.name = uniform.name.c_str();
        uniform_slot.ext_res_0 = buffer_index;
        cmd.BindResource(ShaderStage::kFragment, uniform_slot, metadata,
                         buffer_view);
        break;
      }
      case kBoolean:
      case kSignedByte:
      case kUnsignedByte:
      case kSignedShort:
      case kUnsignedShort:
      case kSignedInt:
      case kUnsignedInt:
      case kSignedInt64:
      case kUnsignedInt64:
      case kHalfFloat:
      case kDouble:
        VALIDATION_LOG << "Unsupported uniform type for " << uniform.name
                       << ".";
        return true;
    }

    buffer_index++;
  }

  pass.AddCommand(std::move(cmd));

  if (geometry_result.prevent_overdraw) {
    return ClipRestoreContents().Render(renderer, entity, pass);
  }
  return true;
}

}  // namespace impeller
<commit_msg>[Impeller] enable blending on RuntimeEffectsContents (#37509)<commit_after>// Copyright 2013 The Flutter 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 "impeller/entity/contents/runtime_effect_contents.h"

#include <future>
#include <memory>

#include "flutter/fml/logging.h"
#include "flutter/fml/make_copyable.h"
#include "impeller/base/validation.h"
#include "impeller/entity/contents/clip_contents.h"
#include "impeller/entity/contents/content_context.h"
#include "impeller/entity/runtime_effect.vert.h"
#include "impeller/renderer/formats.h"
#include "impeller/renderer/pipeline_library.h"
#include "impeller/renderer/render_pass.h"
#include "impeller/renderer/sampler_library.h"
#include "impeller/renderer/shader_function.h"
#include "impeller/renderer/shader_types.h"

namespace impeller {

void RuntimeEffectContents::SetRuntimeStage(
    std::shared_ptr<RuntimeStage> runtime_stage) {
  runtime_stage_ = std::move(runtime_stage);
}

void RuntimeEffectContents::SetUniformData(
    std::shared_ptr<std::vector<uint8_t>> uniform_data) {
  uniform_data_ = std::move(uniform_data);
}

void RuntimeEffectContents::SetTextureInputs(
    std::vector<TextureInput> texture_inputs) {
  texture_inputs_ = std::move(texture_inputs);
}

bool RuntimeEffectContents::Render(const ContentContext& renderer,
                                   const Entity& entity,
                                   RenderPass& pass) const {
  auto context = renderer.GetContext();
  auto library = context->GetShaderLibrary();

  //--------------------------------------------------------------------------
  /// Get or register shader.
  ///

  // TODO(113719): Register the shader function earlier.

  std::shared_ptr<const ShaderFunction> function = library->GetFunction(
      runtime_stage_->GetEntrypoint(), ShaderStage::kFragment);

  if (function && runtime_stage_->IsDirty()) {
    context->GetPipelineLibrary()->RemovePipelinesWithEntryPoint(function);
    library->UnregisterFunction(runtime_stage_->GetEntrypoint(),
                                ShaderStage::kFragment);

    function = nullptr;
  }

  if (!function) {
    std::promise<bool> promise;
    auto future = promise.get_future();

    library->RegisterFunction(
        runtime_stage_->GetEntrypoint(),
        ToShaderStage(runtime_stage_->GetShaderStage()),
        runtime_stage_->GetCodeMapping(),
        fml::MakeCopyable([promise = std::move(promise)](bool result) mutable {
          promise.set_value(result);
        }));

    if (!future.get()) {
      VALIDATION_LOG << "Failed to build runtime effect (entry point: "
                     << runtime_stage_->GetEntrypoint() << ")";
      return false;
    }

    function = library->GetFunction(runtime_stage_->GetEntrypoint(),
                                    ShaderStage::kFragment);
    if (!function) {
      VALIDATION_LOG
          << "Failed to fetch runtime effect function immediately after "
             "registering it (entry point: "
          << runtime_stage_->GetEntrypoint() << ")";
      return false;
    }

    runtime_stage_->SetClean();
  }

  //--------------------------------------------------------------------------
  /// Resolve geometry.
  ///

  auto geometry_result =
      GetGeometry()->GetPositionBuffer(renderer, entity, pass);

  //--------------------------------------------------------------------------
  /// Get or create runtime stage pipeline.
  ///

  using VS = RuntimeEffectVertexShader;
  PipelineDescriptor desc;
  desc.SetLabel("Runtime Stage");
  desc.AddStageEntrypoint(
      library->GetFunction(VS::kEntrypointName, ShaderStage::kVertex));
  desc.AddStageEntrypoint(library->GetFunction(runtime_stage_->GetEntrypoint(),
                                               ShaderStage::kFragment));
  auto vertex_descriptor = std::make_shared<VertexDescriptor>();
  if (!vertex_descriptor->SetStageInputs(VS::kAllShaderStageInputs)) {
    VALIDATION_LOG << "Failed to set stage inputs for runtime effect pipeline.";
  }
  desc.SetVertexDescriptor(std::move(vertex_descriptor));
  desc.SetColorAttachmentDescriptor(
      0u, {.format = PixelFormat::kDefaultColor, .blending_enabled = true});
  desc.SetStencilAttachmentDescriptors({});
  desc.SetStencilPixelFormat(PixelFormat::kDefaultStencil);

  auto options = OptionsFromPassAndEntity(pass, entity);
  if (geometry_result.prevent_overdraw) {
    options.stencil_compare = CompareFunction::kEqual;
    options.stencil_operation = StencilOperation::kIncrementClamp;
  }
  options.primitive_type = geometry_result.type;
  options.ApplyToPipelineDescriptor(desc);

  auto pipeline = context->GetPipelineLibrary()->GetPipeline(desc).Get();
  if (!pipeline) {
    VALIDATION_LOG << "Failed to get or create runtime effect pipeline.";
    return false;
  }

  Command cmd;
  cmd.label = "RuntimeEffectContents";
  cmd.pipeline = pipeline;
  cmd.stencil_reference = entity.GetStencilDepth();
  cmd.BindVertices(geometry_result.vertex_buffer);

  //--------------------------------------------------------------------------
  /// Vertex stage uniforms.
  ///

  VS::VertInfo frame_info;
  frame_info.mvp = Matrix::MakeOrthographic(pass.GetRenderTargetSize()) *
                   entity.GetTransformation();
  VS::BindVertInfo(cmd, pass.GetTransientsBuffer().EmplaceUniform(frame_info));

  //--------------------------------------------------------------------------
  /// Fragment stage uniforms.
  ///

  size_t buffer_index = 0;
  size_t sampler_index = 0;
  for (auto uniform : runtime_stage_->GetUniforms()) {
    // TODO(113715): Populate this metadata once GLES is able to handle
    //               non-struct uniform names.
    ShaderMetadata metadata;

    switch (uniform.type) {
      case kSampledImage: {
        FML_DCHECK(sampler_index < texture_inputs_.size());
        auto& input = texture_inputs_[sampler_index];

        auto sampler =
            context->GetSamplerLibrary()->GetSampler(input.sampler_descriptor);

        SampledImageSlot image_slot;
        image_slot.name = uniform.name.c_str();
        image_slot.texture_index = sampler_index;
        image_slot.sampler_index = sampler_index;
        cmd.BindResource(ShaderStage::kFragment, image_slot, metadata,
                         input.texture, sampler);

        sampler_index++;
        break;
      }
      case kFloat: {
        size_t alignment =
            std::max(uniform.bit_width / 8, DefaultUniformAlignment());
        auto buffer_view = pass.GetTransientsBuffer().Emplace(
            uniform_data_->data() + uniform.location * sizeof(float),
            uniform.GetSize(), alignment);

        ShaderUniformSlot uniform_slot;
        uniform_slot.name = uniform.name.c_str();
        uniform_slot.ext_res_0 = buffer_index;
        cmd.BindResource(ShaderStage::kFragment, uniform_slot, metadata,
                         buffer_view);
        break;
      }
      case kBoolean:
      case kSignedByte:
      case kUnsignedByte:
      case kSignedShort:
      case kUnsignedShort:
      case kSignedInt:
      case kUnsignedInt:
      case kSignedInt64:
      case kUnsignedInt64:
      case kHalfFloat:
      case kDouble:
        VALIDATION_LOG << "Unsupported uniform type for " << uniform.name
                       << ".";
        return true;
    }

    buffer_index++;
  }

  pass.AddCommand(std::move(cmd));

  if (geometry_result.prevent_overdraw) {
    return ClipRestoreContents().Render(renderer, entity, pass);
  }
  return true;
}

}  // namespace impeller
<|endoftext|>


<commit_before>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/core/common_runtime/device.h"
#include "tensorflow/core/common_runtime/gpu/gpu_util.h"
#include "tensorflow/core/common_runtime/gpu_device_context.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/platform/stream_executor.h"

namespace tensorflow {

void GPUDeviceContext::CopyCPUTensorToDevice(const Tensor* cpu_tensor,
                                             Device* device,
                                             Tensor* device_tensor,
                                             StatusCallback done) const {
  //std::cout<<"\nCopyCPUTensorToDevice\n\n";
  std::cout<<"\n>\n";
  GPUUtil::CopyCPUTensorToGPU(cpu_tensor, this, device, device_tensor, done);
}

void GPUDeviceContext::CopyDeviceTensorToCPU(const Tensor* device_tensor,
                                             StringPiece tensor_name,
                                             Device* device, Tensor* cpu_tensor,
                                             StatusCallback done) {
  //std::cout<<"\nCopyDeviceTensorToCPU\n\n";
  std::cout<<"\n<\n";
  GPUUtil::CopyGPUTensorToCPU(device, this, device_tensor, cpu_tensor, done);
}

}  // namespace tensorflow
<commit_msg>modify 換行符號<commit_after>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/core/common_runtime/device.h"
#include "tensorflow/core/common_runtime/gpu/gpu_util.h"
#include "tensorflow/core/common_runtime/gpu_device_context.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/platform/stream_executor.h"

namespace tensorflow {

void GPUDeviceContext::CopyCPUTensorToDevice(const Tensor* cpu_tensor,
                                             Device* device,
                                             Tensor* device_tensor,
                                             StatusCallback done) const {
  //std::cout<<"\nCopyCPUTensorToDevice\n\n";
  std::cout<<">\n";
  GPUUtil::CopyCPUTensorToGPU(cpu_tensor, this, device, device_tensor, done);
}

void GPUDeviceContext::CopyDeviceTensorToCPU(const Tensor* device_tensor,
                                             StringPiece tensor_name,
                                             Device* device, Tensor* cpu_tensor,
                                             StatusCallback done) {
  //std::cout<<"\nCopyDeviceTensorToCPU\n\n";
  std::cout<<"<\n";
  GPUUtil::CopyGPUTensorToCPU(device, this, device_tensor, cpu_tensor, done);
}

}  // namespace tensorflow
<|endoftext|>


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

#include "dlgGoogleDataConf.h"
#include <QPushButton>

dlgGoogleDataConf::dlgGoogleDataConf(QWidget *parent): QDialog(parent)
{
	setupUi(this);

	connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
	connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
        connect(eAccount, SIGNAL(textChanged ( const QString &)),this,SLOT(accountChanged(const QString&)));
        accountChanged(eAccount->text());
}

void dlgGoogleDataConf::accountChanged(const QString& text)
{
        buttonBox->button(QDialogButtonBox::Ok)->setEnabled(!text.isEmpty());
}
<commit_msg>Normalize signals/slots<commit_after>/***********************************************************************/
/* googledata.h 						       */
/* 								       */
/* Copyright (C) 2009  Adenilson Cavalcanti <savagobr@yahoo.com>       */
/* 								       */
/* This library is free software; you can redistribute it and/or       */
/* modify it under the terms of the GNU Lesser General Public	       */
/* License as published by the Free Software Foundation; either	       */
/* version 2.1 of the License, or (at your option) any later version.  */
/*   								       */
/* This library is distributed in the hope that it will be useful,     */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of      */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU   */
/* Lesser General Public License for more details.		       */
/*  								       */
/* You should have received a copy of the GNU Lesser General Public    */
/* License along with this library; if not, write to the Free Software */
/* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA       */
/* 02110-1301  USA						       */
/***********************************************************************/

#include "dlgGoogleDataConf.h"
#include <QPushButton>

dlgGoogleDataConf::dlgGoogleDataConf(QWidget *parent): QDialog(parent)
{
	setupUi(this);

	connect(buttonBox, SIGNAL(accepted()), this, SLOT(accept()));
	connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
        connect(eAccount, SIGNAL(textChanged(QString)),this,SLOT(accountChanged(QString)));
        accountChanged(eAccount->text());
}

void dlgGoogleDataConf::accountChanged(const QString& text)
{
        buttonBox->button(QDialogButtonBox::Ok)->setEnabled(!text.isEmpty());
}
<|endoftext|>


<commit_before>#ifndef SIGMA_SHADER_TECHNIQUE_COMPILER_HPP
#define SIGMA_SHADER_TECHNIQUE_COMPILER_HPP

#include <sigma/graphics/shader_technique.hpp>

#include <json/json-forwards.h>

namespace sigma {
template <class T>
void compile_shader_technique(T& technique, const Json::Value& technique_data)
{
    for (auto it = technique_data.begin(); it != technique_data.end(); ++it) {
        const auto& value = *it;
        if (it.key() == "vertex") {
            technique.shaders[sigma::graphics::shader_type::vertex] = sigma::resource::identifier{ "vertex", value.asString() }; // TODO warn if tring to set shader more that once
        } else if (it.key() == "fragment") {
            technique.shaders[sigma::graphics::shader_type::fragment] = sigma::resource::identifier{ "fragment", value.asString() }; // TODO warn if tring to set shader more that once
        } else if (it.key() == "geometry") {
            technique.shaders[sigma::graphics::shader_type::geometry] = sigma::resource::identifier{ "geometry", value.asString() }; // TODO warn if tring to set shader more that once
        } else if (it.key() == "textures") {
            const auto& texture_object = *it;
            for (auto it2 = texture_object.begin(); it2 != texture_object.end(); ++it2)
                technique.textures[it2.key().asString()] = sigma::resource::identifier{ "texture", (*it2).asString() }; // TODO warn if tring to set texture more than once
        } else if (it.key() == "cubemaps") {
            const auto& cubemap_object = *it;
            for (auto it2 = cubemap_object.begin(); it2 != cubemap_object.end(); ++it2)
                technique.cubemaps[it2.key().asString()] = sigma::resource::identifier{ "cubemap", (*it2).asString() }; // TODO warn if tring to set cubemap more than once
        }
    }

    // TODO check for errors like no vertex or fragment shader
}
}

#endif // SIGMA_SHADER_TECHNIQUE_COMPILER_HPP
<commit_msg>Include fix.<commit_after>#ifndef SIGMA_SHADER_TECHNIQUE_COMPILER_HPP
#define SIGMA_SHADER_TECHNIQUE_COMPILER_HPP

#include <sigma/graphics/shader_technique.hpp>

#include <json/json.h>

namespace sigma {
template <class T>
void compile_shader_technique(T& technique, const Json::Value& technique_data)
{
    for (auto it = technique_data.begin(); it != technique_data.end(); ++it) {
        const auto& value = *it;
        if (it.key() == "vertex") {
            technique.shaders[sigma::graphics::shader_type::vertex] = sigma::resource::identifier{ "vertex", value.asString() }; // TODO warn if tring to set shader more that once
        } else if (it.key() == "fragment") {
            technique.shaders[sigma::graphics::shader_type::fragment] = sigma::resource::identifier{ "fragment", value.asString() }; // TODO warn if tring to set shader more that once
        } else if (it.key() == "geometry") {
            technique.shaders[sigma::graphics::shader_type::geometry] = sigma::resource::identifier{ "geometry", value.asString() }; // TODO warn if tring to set shader more that once
        } else if (it.key() == "textures") {
            const auto& texture_object = *it;
            for (auto it2 = texture_object.begin(); it2 != texture_object.end(); ++it2)
                technique.textures[it2.key().asString()] = sigma::resource::identifier{ "texture", (*it2).asString() }; // TODO warn if tring to set texture more than once
        } else if (it.key() == "cubemaps") {
            const auto& cubemap_object = *it;
            for (auto it2 = cubemap_object.begin(); it2 != cubemap_object.end(); ++it2)
                technique.cubemaps[it2.key().asString()] = sigma::resource::identifier{ "cubemap", (*it2).asString() }; // TODO warn if tring to set cubemap more than once
        }
    }

    // TODO check for errors like no vertex or fragment shader
}
}

#endif // SIGMA_SHADER_TECHNIQUE_COMPILER_HPP
<|endoftext|>