<commit_before>#include "stdafx.h"
#include "GUIRenderer.h"

#include "mmcore/CoreInstance.h"
#include "mmcore/param/BoolParam.h"
#include "mmcore/param/ButtonParam.h"
#include "mmcore/param/ColorParam.h"
#include "mmcore/param/EnumParam.h"
#include "mmcore/param/FilePathParam.h"
#include "mmcore/param/FlexEnumParam.h"
#include "mmcore/param/FloatParam.h"
#include "mmcore/param/IntParam.h"
#include "mmcore/param/StringParam.h"
#include "mmcore/param/TernaryParam.h"
#include "mmcore/param/Vector2fParam.h"
#include "mmcore/param/Vector3fParam.h"
#include "mmcore/param/Vector4fParam.h"

#include "vislib/UTF8Encoder.h"

#include <imgui.h>
#include "imgui_impl_opengl3.h"

using namespace megamol;
using namespace megamol::gui;

GUIRenderer::GUIRenderer() : lastViewportTime(0.0) {}

GUIRenderer::~GUIRenderer() { this->Release(); }

bool GUIRenderer::create() {
    ImGui::CreateContext();
    ImGui::GetIO();

    ImGui_ImplOpenGL3_Init("#version 150");

    ImGui::StyleColorsDark();
    return true;
}

void GUIRenderer::release() {}

bool GUIRenderer::Render(core::view::CallRender2D& call) {
    auto viewportWidth = call.GetViewport().Width();
    auto viewportHeight = call.GetViewport().Height();
    auto viewportTime = call.InstanceTime();

    // Start the frame
    ImGuiIO& io = ImGui::GetIO();
    io.DisplaySize = ImVec2(viewportWidth, viewportHeight);
    io.DisplayFramebufferScale = ImVec2(1.0, 1.0);
    io.DeltaTime = viewportTime - lastViewportTime;
    ImGui_ImplOpenGL3_NewFrame();
    ImGui::NewFrame();

    // Construct frame, i.e., geometry and stuff.
    // XXX: drawOtherStuff();
    drawMainMenu();
    drawParameterWindow();

    // Render frame.
    glViewport(0, 0, viewportWidth, viewportHeight);
    ImGui::Render();
    ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());

    lastViewportTime = viewportTime;

    return true;
}

bool megamol::gui::GUIRenderer::OnKey(core::view::Key key, core::view::KeyAction action, core::view::Modifiers mods) {
    return false;
}

bool megamol::gui::GUIRenderer::OnChar(unsigned int codePoint) { return false; }

bool megamol::gui::GUIRenderer::OnMouseButton(
    core::view::MouseButton button, core::view::MouseButtonAction action, core::view::Modifiers mods) {
    return false;
}

bool megamol::gui::GUIRenderer::OnMouseMove(double x, double y) { return false; }

bool megamol::gui::GUIRenderer::OnMouseScroll(double dx, double dy) { return false; }

void GUIRenderer::drawMainMenu() {
    // TODO: this is still mockup stuff...
    bool a, b, c;
    bool d, e, f;
    if (ImGui::BeginMainMenuBar()) {
        if (ImGui::BeginMenu("File")) {
            ImGui::MenuItem("New", nullptr, &a);
            ImGui::MenuItem("Open", nullptr, &a);
            ImGui::EndMenu();
            ImGui::MenuItem("Save", nullptr, &a);
            ImGui::MenuItem("Save as...", nullptr, &a);
            ImGui::EndMenu();
            ImGui::MenuItem("Exit", nullptr, &a);
            ImGui::EndMenu();
        }
        if (ImGui::BeginMenu("Edit")) {
            ImGui::MenuItem("Cut", nullptr, &a);
            ImGui::MenuItem("Copy", nullptr, &a);
            ImGui::MenuItem("Paste", nullptr, &a);
            ImGui::MenuItem("Delete", nullptr, &a);
            ImGui::EndMenu();
        }
        if (ImGui::BeginMenu("View")) {
            ImGui::MenuItem("Parameter inspector", nullptr, &a);
            ImGui::MenuItem("Node editor", nullptr, &b);
            ImGui::MenuItem("Console", nullptr, &c);
            ImGui::Separator();
            ImGui::MenuItem("Settings...", nullptr, &c);
            ImGui::EndMenu();
        }
        if (ImGui::BeginMenu("Help")) {
            ImGui::MenuItem("MegaMol Help...", nullptr, &e);
            ImGui::MenuItem("Report Issue...", nullptr, &e);
            ImGui::Separator();
            ImGui::MenuItem("About...", nullptr, &f);
            ImGui::EndMenu();
        }
        ImGui::EndMainMenuBar();
    }
}

void GUIRenderer::drawParameterWindow() {
    ImGui::Begin("Parameters", &this->parameterWindowActive, ImGuiWindowFlags_AlwaysAutoResize);

    bool currentModOpen = false;
    const core::Module* currentMod = nullptr;
    ImGui::SetNextTreeNodeOpen(true);
    this->GetCoreInstance()->EnumParameters([&](const auto& mod, const auto& slot) {
        if (currentMod != &mod) {
            currentMod = &mod;
            currentModOpen = ImGui::CollapsingHeader(mod.FullName());
        }
        if (currentModOpen) {
            drawParameter(mod, slot);
        }
    });

    ImGui::End();
}

void GUIRenderer::drawParameter(const core::Module& mod, const core::param::ParamSlot& slot) {
    auto param = slot.Parameter();
    if (!param.IsNull()) {
        auto valueBuffer = this->parameterStrings[&slot];
        vislib::StringA valueString;
        vislib::UTF8Encoder::Encode(valueString, param->ValueString());
        memcpy(valueBuffer, valueString, valueString.Length() + 1);

        auto label = slot.Name().PeekBuffer();

        if (auto* p = slot.Param<core::param::BoolParam>()) {
            ImGui::Checkbox(label, reinterpret_cast<bool*>(valueBuffer));
        } else if (auto* p = slot.Param<core::param::ButtonParam>()) {
            ImGui::Button(label);
        } else if (auto* p = slot.Param<core::param::ColorParam>()) {
            ImGui::ColorEdit4(label, reinterpret_cast<float*>(valueBuffer));
        } else if (auto* p = slot.Param<core::param::EnumParam>()) {
            ImGui::BeginCombo(label, "Select...");
            ImGui::EndCombo();
        } else if (auto* p = slot.Param<core::param::FilePathParam>()) {
            // TODO: easier file handling please!
            ImGui::InputText(slot.Name().PeekBuffer(), valueBuffer, IM_ARRAYSIZE(valueBuffer));
        } else if (auto* p = slot.Param<core::param::FlexEnumParam>()) {
            ImGui::BeginCombo(label, "Select...");
            ImGui::EndCombo();
        } else if (auto* p = slot.Param<core::param::FloatParam>()) {
            ImGui::InputFloat(label, reinterpret_cast<float*>(valueBuffer));
        } else if (auto* p = slot.Param<core::param::IntParam>()) {
            ImGui::InputInt(label, reinterpret_cast<int*>(valueBuffer));
        } else if (auto* p = slot.Param<core::param::TernaryParam>()) {
            // TODO: do something smart here?
            ImGui::InputText(slot.Name().PeekBuffer(), valueBuffer, IM_ARRAYSIZE(valueBuffer));
        } else if (auto* p = slot.Param<core::param::Vector2fParam>()) {
            ImGui::InputFloat2(label, reinterpret_cast<float*>(valueBuffer));
        } else if (auto* p = slot.Param<core::param::Vector3fParam>()) {
            ImGui::InputFloat3(label, reinterpret_cast<float*>(valueBuffer));
        } else if (auto* p = slot.Param<core::param::Vector4fParam>()) {
            ImGui::InputFloat4(label, reinterpret_cast<float*>(valueBuffer));
        } else {
            ImGui::InputText(slot.Name().PeekBuffer(), valueBuffer, IM_ARRAYSIZE(valueBuffer));
        }
    }
}
<commit_msg>Input mapping to ImGui<commit_after>#include "stdafx.h"
#include "GUIRenderer.h"

#include "mmcore/CoreInstance.h"
#include "mmcore/param/BoolParam.h"
#include "mmcore/param/ButtonParam.h"
#include "mmcore/param/ColorParam.h"
#include "mmcore/param/EnumParam.h"
#include "mmcore/param/FilePathParam.h"
#include "mmcore/param/FlexEnumParam.h"
#include "mmcore/param/FloatParam.h"
#include "mmcore/param/IntParam.h"
#include "mmcore/param/StringParam.h"
#include "mmcore/param/TernaryParam.h"
#include "mmcore/param/Vector2fParam.h"
#include "mmcore/param/Vector3fParam.h"
#include "mmcore/param/Vector4fParam.h"

#include "vislib/UTF8Encoder.h"

#include <imgui.h>
#include "imgui_impl_opengl3.h"

using namespace megamol;
using namespace megamol::gui;

GUIRenderer::GUIRenderer() : lastViewportTime(0.0) {}

GUIRenderer::~GUIRenderer() { this->Release(); }

bool GUIRenderer::create() {
    ImGui::CreateContext();
    ImGui::GetIO();

    ImGui_ImplOpenGL3_Init("#version 150");

    ImGui::StyleColorsDark();
    return true;
}

void GUIRenderer::release() {}

bool GUIRenderer::Render(core::view::CallRender2D& call) {
    auto viewportWidth = call.GetViewport().Width();
    auto viewportHeight = call.GetViewport().Height();
    auto viewportTime = call.InstanceTime();

    // Start the frame
    ImGuiIO& io = ImGui::GetIO();
    io.DisplaySize = ImVec2(viewportWidth, viewportHeight);
    io.DisplayFramebufferScale = ImVec2(1.0, 1.0);
    io.DeltaTime = viewportTime - lastViewportTime;
    ImGui_ImplOpenGL3_NewFrame();
    ImGui::NewFrame();

    // Construct frame, i.e., geometry and stuff.
    // XXX: drawOtherStuff();
    drawMainMenu();
    drawParameterWindow();

    // Render frame.
    glViewport(0, 0, viewportWidth, viewportHeight);
    ImGui::Render();
    ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());

    lastViewportTime = viewportTime;

    return true;
}

bool megamol::gui::GUIRenderer::OnKey(core::view::Key key, core::view::KeyAction action, core::view::Modifiers mods) {
    ImGuiIO& io = ImGui::GetIO();
    auto keyIndex = static_cast<size_t>(key); // TODO: verify mapping!
    switch (action) {
    case core::view::KeyAction::PRESS:
        io.KeysDown[keyIndex] = true;
        break;
    case core::view::KeyAction::RELEASE:
        io.KeysDown[keyIndex] = false;
        break;
    default:
        break;
    }
    io.KeyCtrl = mods.test(core::view::Modifier::CTRL);
    io.KeyShift = mods.test(core::view::Modifier::SHIFT);
    io.KeyAlt = mods.test(core::view::Modifier::ALT);
    // io.KeySuper =  mods.test(core::view::Modifier::SUPER)
    return true;
}

bool megamol::gui::GUIRenderer::OnChar(unsigned int codePoint) {
    ImGuiIO& io = ImGui::GetIO();
    if (codePoint > 0 && codePoint < 0x10000) io.AddInputCharacter((unsigned short)codePoint);
    return true;
}

bool megamol::gui::GUIRenderer::OnMouseButton(
    core::view::MouseButton button, core::view::MouseButtonAction action, core::view::Modifiers mods) {
    bool down = (action == core::view::MouseButtonAction::PRESS);
    auto buttonIndex = static_cast<size_t>(button);
    ImGuiIO& io = ImGui::GetIO();
    io.MouseDown[buttonIndex] = down;
    return true;
}

bool megamol::gui::GUIRenderer::OnMouseMove(double x, double y) {
    ImGuiIO& io = ImGui::GetIO();
    io.MousePos = ImVec2(x, y);
    return true;
}

bool megamol::gui::GUIRenderer::OnMouseScroll(double dx, double dy) {
    ImGuiIO& io = ImGui::GetIO();
    io.MouseWheelH += (float)dx;
    io.MouseWheel += (float)dy;
    return true;
}

void GUIRenderer::drawMainMenu() {
    // TODO: this is still mockup stuff...
    bool a, b, c;
    bool d, e, f;
    if (ImGui::BeginMainMenuBar()) {
        if (ImGui::BeginMenu("File")) {
            ImGui::MenuItem("New", nullptr, &a);
            ImGui::MenuItem("Open", nullptr, &a);
            ImGui::EndMenu();
            ImGui::MenuItem("Save", nullptr, &a);
            ImGui::MenuItem("Save as...", nullptr, &a);
            ImGui::EndMenu();
            ImGui::MenuItem("Exit", nullptr, &a);
            ImGui::EndMenu();
        }
        if (ImGui::BeginMenu("Edit")) {
            ImGui::MenuItem("Cut", nullptr, &a);
            ImGui::MenuItem("Copy", nullptr, &a);
            ImGui::MenuItem("Paste", nullptr, &a);
            ImGui::MenuItem("Delete", nullptr, &a);
            ImGui::EndMenu();
        }
        if (ImGui::BeginMenu("View")) {
            ImGui::MenuItem("Parameter inspector", nullptr, &a);
            ImGui::MenuItem("Node editor", nullptr, &b);
            ImGui::MenuItem("Console", nullptr, &c);
            ImGui::Separator();
            ImGui::MenuItem("Settings...", nullptr, &c);
            ImGui::EndMenu();
        }
        if (ImGui::BeginMenu("Help")) {
            ImGui::MenuItem("MegaMol Help...", nullptr, &e);
            ImGui::MenuItem("Report Issue...", nullptr, &e);
            ImGui::Separator();
            ImGui::MenuItem("About...", nullptr, &f);
            ImGui::EndMenu();
        }
        ImGui::EndMainMenuBar();
    }
}

void GUIRenderer::drawParameterWindow() {
    ImGui::Begin("Parameters", &this->parameterWindowActive, ImGuiWindowFlags_AlwaysAutoResize);

    bool currentModOpen = false;
    const core::Module* currentMod = nullptr;
    ImGui::SetNextTreeNodeOpen(true);
    this->GetCoreInstance()->EnumParameters([&](const auto& mod, const auto& slot) {
        if (currentMod != &mod) {
            currentMod = &mod;
            currentModOpen = ImGui::CollapsingHeader(mod.FullName());
        }
        if (currentModOpen) {
            drawParameter(mod, slot);
        }
    });

    ImGui::End();
}

void GUIRenderer::drawParameter(const core::Module& mod, const core::param::ParamSlot& slot) {
    auto param = slot.Parameter();
    if (!param.IsNull()) {
        auto valueBuffer = this->parameterStrings[&slot];
        vislib::StringA valueString;
        vislib::UTF8Encoder::Encode(valueString, param->ValueString());
        memcpy(valueBuffer, valueString, valueString.Length() + 1);

        auto label = slot.Name().PeekBuffer();

        if (auto* p = slot.Param<core::param::BoolParam>()) {
            ImGui::Checkbox(label, reinterpret_cast<bool*>(valueBuffer));
        } else if (auto* p = slot.Param<core::param::ButtonParam>()) {
            ImGui::Button(label);
        } else if (auto* p = slot.Param<core::param::ColorParam>()) {
            ImGui::ColorEdit4(label, reinterpret_cast<float*>(valueBuffer));
        } else if (auto* p = slot.Param<core::param::EnumParam>()) {
            ImGui::BeginCombo(label, "Select...");
            ImGui::EndCombo();
        } else if (auto* p = slot.Param<core::param::FilePathParam>()) {
            // TODO: easier file handling please!
            ImGui::InputText(slot.Name().PeekBuffer(), valueBuffer, IM_ARRAYSIZE(valueBuffer));
        } else if (auto* p = slot.Param<core::param::FlexEnumParam>()) {
            ImGui::BeginCombo(label, "Select...");
            ImGui::EndCombo();
        } else if (auto* p = slot.Param<core::param::FloatParam>()) {
            ImGui::InputFloat(label, reinterpret_cast<float*>(valueBuffer));
        } else if (auto* p = slot.Param<core::param::IntParam>()) {
            ImGui::InputInt(label, reinterpret_cast<int*>(valueBuffer));
        } else if (auto* p = slot.Param<core::param::TernaryParam>()) {
            // TODO: do something smart here?
            ImGui::InputText(slot.Name().PeekBuffer(), valueBuffer, IM_ARRAYSIZE(valueBuffer));
        } else if (auto* p = slot.Param<core::param::Vector2fParam>()) {
            ImGui::InputFloat2(label, reinterpret_cast<float*>(valueBuffer));
        } else if (auto* p = slot.Param<core::param::Vector3fParam>()) {
            ImGui::InputFloat3(label, reinterpret_cast<float*>(valueBuffer));
        } else if (auto* p = slot.Param<core::param::Vector4fParam>()) {
            ImGui::InputFloat4(label, reinterpret_cast<float*>(valueBuffer));
        } else {
            ImGui::InputText(slot.Name().PeekBuffer(), valueBuffer, IM_ARRAYSIZE(valueBuffer));
        }
    }
}
<|endoftext|>


<commit_before>/*
 * File:   SimpleFieldColorClassifier.cpp
 * Author: claas
 *
 * Created on 15. Mrz 2011, 15:56
 */

#include "SimpleFieldColorClassifier.h"

// Debug
#include "Tools/Debug/DebugRequest.h"
#include "Tools/Debug/DebugImageDrawings.h"
#include "Tools/Debug/Stopwatch.h"
#include "Tools/Debug/DebugModify.h"
#include "Tools/Debug/DebugBufferedOutput.h"

using namespace std;

SimpleFieldColorClassifier::SimpleFieldColorClassifier()
:
  cameraID(CameraInfo::Bottom),
  uniformGrid(getImage().width(), getImage().height(), 60, 40)
{
  DEBUG_REQUEST_REGISTER("Vision:ColorClassifiers:SimpleFieldColorClassifier:TopCam:markCrClassification", "", false);
  DEBUG_REQUEST_REGISTER("Vision:ColorClassifiers:SimpleFieldColorClassifier:TopCam:markYClassification", "", false);
  DEBUG_REQUEST_REGISTER("Vision:ColorClassifiers:SimpleFieldColorClassifier:BottomCam:markYClassification", "", false);
  DEBUG_REQUEST_REGISTER("Vision:ColorClassifiers:SimpleFieldColorClassifier:BottomCam:markCrClassification", "", false);

  DEBUG_REQUEST_REGISTER("Vision:ColorClassifiers:SimpleFieldColorClassifier:TopCam:mark_green", "", false);
  DEBUG_REQUEST_REGISTER("Vision:ColorClassifiers:SimpleFieldColorClassifier:BottomCam:mark_green", "", false);
}

void SimpleFieldColorClassifier::execute(const CameraInfo::CameraID id)
{
  cameraID = id;
  CANVAS_PX(cameraID);

  // check if a fresh histogram is avaliable
  if(!getColorChannelHistograms().colorChannelIsUptodate) {
    return;
  }

  const Statistics::HistogramX& histY = getColorChannelHistograms().histogramY;
  double start = histY.min;
  double halfSpan = histY.spanWidth / 2.0;
  double quadSpan = histY.spanWidth / 4.0;

  for(int i = 0; i < getColorChannelHistograms().histogramY.size; i++)
  {
    double f = 1.0;
    f =  gauss(parameters.filterFactorY * quadSpan, start + halfSpan, i);

    int val = (int) Math::round(getColorChannelHistograms().histogramY.rawData[i] * f);
    filteredHistogramY.add(i, val);
  }
  filteredHistogramY.calculate();

  double lowBorderY = filteredHistogramY.median - parameters.filterFactorY * filteredHistogramY.sigma;
  double highBorderY = filteredHistogramY.median + parameters.filterFactorY * filteredHistogramY.sigma;
  Pixel pixel;

  for(unsigned int i = 0; i < uniformGrid.size(); i++)
  {
    const Vector2i& point = uniformGrid.getPoint(i);

    getImage().get(point.x, point.y, pixel);

    if(!getBodyContour().isOccupied(point) && lowBorderY < pixel.y && pixel.y < highBorderY)
    {
      filteredHistogramV.add(pixel.v);
    }
  }//end for

  // some usefull precalculations (to speedup the process)
  // the cente of the histogram
  static const int halfChannelWidth = ColorChannelHistograms::VALUE_COUNT / 2;
  static const double histogramStep = 1.0/(double) ColorChannelHistograms::VALUE_COUNT;
  static const double histogramDoubleStep = 2.0*histogramStep;

  STOPWATCH_START("SimpleFieldColorClassifier:Cr_filtering");

  // STEP 1: search for the maximal value in the weighted Cr histogramm
  // CAUTION: the histogram created by the grid provider in the last frame is used
  double maxWeightedCr = 0.0;
  int maxWeightedIndexCr = -1;

  // the histogram is weighted with the function
  // max^2(0,128-i)/128, i.e., we are interested only in the first half of it
  for(int i = 0; i < halfChannelWidth; i++)
  {
    // apply the weght max(0,128-i)/128 = 1-i/128 for i <= 128
    double wCr = 1.0 - i*histogramDoubleStep;
    double weightedCr = wCr * wCr * (double) filteredHistogramV.rawData[i];

    // search for maximum in the wighted Cr channel
    if(weightedCr > maxWeightedCr)
    {
      maxWeightedCr = weightedCr;
      maxWeightedIndexCr = i;
    }
  }

  // no green candidates found
  if(maxWeightedIndexCr < 0) {
    return;
  }
  STOPWATCH_STOP("SimpleFieldColorClassifier:Cr_filtering");

  // Step 3: calculate the Y and Cb histograms based on the points
  //         which satisfy the "green"-condition based on Cr histogram
  STOPWATCH_START("SimpleFieldColorClassifier:GridWalk");
  for(unsigned int i = 0; i < uniformGrid.size(); i++)
  {
    const Vector2i& point = uniformGrid.getPoint(i);
    getImage().get(point.x, point.y, pixel);

    if(!getBodyContour().isOccupied(point) && abs((int)pixel.v-(int)maxWeightedIndexCr) < (int)getParameters().fieldColorMax.v)
    {
      filteredHistogramU.add(pixel.u);
    }
  }
  STOPWATCH_STOP("SimpleFieldColorClassifier:GridWalk");

  STOPWATCH_START("SimpleFieldColorClassifier:Y_filtering");
  double maxWeightedCb = 0;
  int maxWeightedIndexCb = -1;

  for(int i = 0; i < ColorChannelHistograms::VALUE_COUNT; i++)
  {
    // weight based on the mean value  (255 - i)/255
    double wCb = 1.0 - i*histogramStep;
    double weightedCb = wCb * (double) filteredHistogramU.rawData[i];

    // calculate the Cb maximum
    if(weightedCb > maxWeightedCb)
    {
      maxWeightedCb = weightedCb;
      maxWeightedIndexCb = i;
    }
  }
  STOPWATCH_STOP("SimpleFieldColorClassifier:Y_filtering");

  PLOT("SimpleFieldColorClassifier:" + getImage().cameraInfo.getCameraIDName(cameraID) + ":maxWeightedIndexCr", maxWeightedIndexCr);
  PLOT("SimpleFieldColorClassifier:" + getImage().cameraInfo.getCameraIDName(cameraID) + ":maxWeightedIndexCb", maxWeightedIndexCb);

  getFieldColorPercept().range.set(
    (int)lowBorderY,
    (int)maxWeightedIndexCb - (int)getParameters().fieldColorMax.u,
    (int)maxWeightedIndexCr - (int)getParameters().fieldColorMax.v,

    (int)highBorderY,
    (int)maxWeightedIndexCb + (int)getParameters().fieldColorMax.u,
    (int)maxWeightedIndexCr + (int)getParameters().fieldColorMax.v
    );

  getFieldColorPercept().histogramField.y = (unsigned char)Math::clamp(filteredHistogramY.median,0,255);
  getFieldColorPercept().histogramField.u = (unsigned char)Math::clamp(maxWeightedIndexCb,0,255);
  getFieldColorPercept().histogramField.v = (unsigned char)Math::clamp(maxWeightedIndexCr,0,255);

  getFieldColorPercept().lastUpdated = getFrameInfo();

  if(parameters.classifyInBothImages < 1)
  {
    getFieldColorPerceptTop().range.set(
      (int)lowBorderY,
      (int)maxWeightedIndexCb - (int)getParameters().fieldColorMax.u,
      (int)maxWeightedIndexCr - (int)getParameters().fieldColorMax.v,

      (int)highBorderY,
      (int)maxWeightedIndexCb + (int)getParameters().fieldColorMax.u,
      (int)maxWeightedIndexCr + (int)getParameters().fieldColorMax.v
      );

    getFieldColorPerceptTop().lastUpdated = getFrameInfo();
  }

  cameraID = CameraInfo::Bottom;
  CANVAS_PX(cameraID);
  DEBUG_REQUEST("Vision:ColorClassifiers:SimpleFieldColorClassifier:BottomCam:markCrClassification",
    for(unsigned int x = 0; x < getImage().width(); x+=2) {
      for(unsigned int y = 0; y < getImage().height(); y+=2) {
        const Pixel& pixel = getImage().get(x, y);
        if( abs((int)pixel.v-(int)maxWeightedIndexCr) < (int)getParameters().fieldColorMax.v) {
          POINT_PX(ColorClasses::red, x, y);
        }
      }
    }
  );
  cameraID = CameraInfo::Top;
  CANVAS_PX(cameraID);
  DEBUG_REQUEST("Vision:ColorClassifiers:SimpleFieldColorClassifier:TopCam:markCrClassification",
    for(unsigned int x = 0; x < getImage().width(); x+=2) {
      for(unsigned int y = 0; y < getImage().height(); y+=2) {
        const Pixel& pixel = getImage().get(x, y);
        if( abs((int)pixel.v-(int)maxWeightedIndexCr) < (int)getParameters().fieldColorMax.v) {
          POINT_PX(ColorClasses::red, x, y);
        }
      }
    }
  );

}//end execute

double SimpleFieldColorClassifier::gauss(double sigma, double mean, double x)
{
  double exponent = -((x - mean) * (x - mean)) / (2 * sigma * sigma);
  double ret = exp( exponent );
  return Math::isInf(ret) || Math::isNan(ret) ? 0.0 : ret;
}

<commit_msg>restrict time span (total ammount of samples) witchs should have an affect to the histograms used<commit_after>/*
 * File:   SimpleFieldColorClassifier.cpp
 * Author: claas
 *
 * Created on 15. Mrz 2011, 15:56
 */

#include "SimpleFieldColorClassifier.h"

// Debug
#include "Tools/Debug/DebugRequest.h"
#include "Tools/Debug/DebugImageDrawings.h"
#include "Tools/Debug/Stopwatch.h"
#include "Tools/Debug/DebugModify.h"
#include "Tools/Debug/DebugBufferedOutput.h"

using namespace std;

SimpleFieldColorClassifier::SimpleFieldColorClassifier()
:
  cameraID(CameraInfo::Bottom),
  uniformGrid(getImage().width(), getImage().height(), 60, 40)
{
  DEBUG_REQUEST_REGISTER("Vision:ColorClassifiers:SimpleFieldColorClassifier:TopCam:markCrClassification", "", false);
  DEBUG_REQUEST_REGISTER("Vision:ColorClassifiers:SimpleFieldColorClassifier:TopCam:markYClassification", "", false);
  DEBUG_REQUEST_REGISTER("Vision:ColorClassifiers:SimpleFieldColorClassifier:BottomCam:markYClassification", "", false);
  DEBUG_REQUEST_REGISTER("Vision:ColorClassifiers:SimpleFieldColorClassifier:BottomCam:markCrClassification", "", false);

  DEBUG_REQUEST_REGISTER("Vision:ColorClassifiers:SimpleFieldColorClassifier:TopCam:mark_green", "", false);
  DEBUG_REQUEST_REGISTER("Vision:ColorClassifiers:SimpleFieldColorClassifier:BottomCam:mark_green", "", false);

  //collect only last 20 seconds of histogram data
  filteredHistogramY.setMaxTotalSum(uniformGrid.size() * 30 * 20);
  filteredHistogramU.setMaxTotalSum(uniformGrid.size() * 30 * 20);
  filteredHistogramV.setMaxTotalSum(uniformGrid.size() * 30 * 20);
}

void SimpleFieldColorClassifier::execute(const CameraInfo::CameraID id)
{
  cameraID = id;
  CANVAS_PX(cameraID);

  // check if a fresh histogram is avaliable
  if(!getColorChannelHistograms().colorChannelIsUptodate) {
    return;
  }

  const Statistics::HistogramX& histY = getColorChannelHistograms().histogramY;
  double start = histY.min;
  double halfSpan = histY.spanWidth / 2.0;
  double quadSpan = histY.spanWidth / 4.0;

  for(int i = 0; i < getColorChannelHistograms().histogramY.size; i++)
  {
    double f = 1.0;
    f =  gauss(parameters.filterFactorY * quadSpan, start + halfSpan, i);

    int val = (int) Math::round(getColorChannelHistograms().histogramY.rawData[i] * f);
    filteredHistogramY.add(i, val);
  }
  filteredHistogramY.calculate();

  double lowBorderY = filteredHistogramY.median - parameters.filterFactorY * filteredHistogramY.sigma;
  double highBorderY = filteredHistogramY.median + parameters.filterFactorY * filteredHistogramY.sigma;
  Pixel pixel;

  for(unsigned int i = 0; i < uniformGrid.size(); i++)
  {
    const Vector2i& point = uniformGrid.getPoint(i);

    getImage().get(point.x, point.y, pixel);

    if(!getBodyContour().isOccupied(point) && lowBorderY < pixel.y && pixel.y < highBorderY)
    {
      filteredHistogramV.add(pixel.v);
    }
  }//end for

  // some usefull precalculations (to speedup the process)
  // the cente of the histogram
  static const int halfChannelWidth = ColorChannelHistograms::VALUE_COUNT / 2;
  static const double histogramStep = 1.0/(double) ColorChannelHistograms::VALUE_COUNT;
  static const double histogramDoubleStep = 2.0*histogramStep;

  STOPWATCH_START("SimpleFieldColorClassifier:Cr_filtering");

  // STEP 1: search for the maximal value in the weighted Cr histogramm
  // CAUTION: the histogram created by the grid provider in the last frame is used
  double maxWeightedCr = 0.0;
  int maxWeightedIndexCr = -1;

  // the histogram is weighted with the function
  // max^2(0,128-i)/128, i.e., we are interested only in the first half of it
  for(int i = 0; i < halfChannelWidth; i++)
  {
    // apply the weght max(0,128-i)/128 = 1-i/128 for i <= 128
    double wCr = 1.0 - i*histogramDoubleStep;
    double weightedCr = wCr * wCr * (double) filteredHistogramV.rawData[i];

    // search for maximum in the wighted Cr channel
    if(weightedCr > maxWeightedCr)
    {
      maxWeightedCr = weightedCr;
      maxWeightedIndexCr = i;
    }
  }

  // no green candidates found
  if(maxWeightedIndexCr < 0) {
    return;
  }
  STOPWATCH_STOP("SimpleFieldColorClassifier:Cr_filtering");

  // Step 3: calculate the Y and Cb histograms based on the points
  //         which satisfy the "green"-condition based on Cr histogram
  STOPWATCH_START("SimpleFieldColorClassifier:GridWalk");
  for(unsigned int i = 0; i < uniformGrid.size(); i++)
  {
    const Vector2i& point = uniformGrid.getPoint(i);
    getImage().get(point.x, point.y, pixel);

    if(!getBodyContour().isOccupied(point) && abs((int)pixel.v-(int)maxWeightedIndexCr) < (int)getParameters().fieldColorMax.v)
    {
      filteredHistogramU.add(pixel.u);
    }
  }
  STOPWATCH_STOP("SimpleFieldColorClassifier:GridWalk");

  STOPWATCH_START("SimpleFieldColorClassifier:Y_filtering");
  double maxWeightedCb = 0;
  int maxWeightedIndexCb = -1;

  for(int i = 0; i < ColorChannelHistograms::VALUE_COUNT; i++)
  {
    // weight based on the mean value  (255 - i)/255
    double wCb = 1.0 - i*histogramStep;
    double weightedCb = wCb * (double) filteredHistogramU.rawData[i];

    // calculate the Cb maximum
    if(weightedCb > maxWeightedCb)
    {
      maxWeightedCb = weightedCb;
      maxWeightedIndexCb = i;
    }
  }
  STOPWATCH_STOP("SimpleFieldColorClassifier:Y_filtering");

  PLOT("SimpleFieldColorClassifier:" + getImage().cameraInfo.getCameraIDName(cameraID) + ":maxWeightedIndexCr", maxWeightedIndexCr);
  PLOT("SimpleFieldColorClassifier:" + getImage().cameraInfo.getCameraIDName(cameraID) + ":maxWeightedIndexCb", maxWeightedIndexCb);

  getFieldColorPercept().range.set(
    (int)lowBorderY,
    (int)maxWeightedIndexCb - (int)getParameters().fieldColorMax.u,
    (int)maxWeightedIndexCr - (int)getParameters().fieldColorMax.v,

    (int)highBorderY,
    (int)maxWeightedIndexCb + (int)getParameters().fieldColorMax.u,
    (int)maxWeightedIndexCr + (int)getParameters().fieldColorMax.v
    );

  getFieldColorPercept().histogramField.y = (unsigned char)Math::clamp(filteredHistogramY.median,0,255);
  getFieldColorPercept().histogramField.u = (unsigned char)Math::clamp(maxWeightedIndexCb,0,255);
  getFieldColorPercept().histogramField.v = (unsigned char)Math::clamp(maxWeightedIndexCr,0,255);

  getFieldColorPercept().lastUpdated = getFrameInfo();

  if(parameters.classifyInBothImages < 1)
  {
    getFieldColorPerceptTop().range.set(
      (int)lowBorderY,
      (int)maxWeightedIndexCb - (int)getParameters().fieldColorMax.u,
      (int)maxWeightedIndexCr - (int)getParameters().fieldColorMax.v,

      (int)highBorderY,
      (int)maxWeightedIndexCb + (int)getParameters().fieldColorMax.u,
      (int)maxWeightedIndexCr + (int)getParameters().fieldColorMax.v
      );

    getFieldColorPerceptTop().lastUpdated = getFrameInfo();
  }

  cameraID = CameraInfo::Bottom;
  CANVAS_PX(cameraID);
  DEBUG_REQUEST("Vision:ColorClassifiers:SimpleFieldColorClassifier:BottomCam:markCrClassification",
    for(unsigned int x = 0; x < getImage().width(); x+=2) {
      for(unsigned int y = 0; y < getImage().height(); y+=2) {
        const Pixel& pixel = getImage().get(x, y);
        if( abs((int)pixel.v-(int)maxWeightedIndexCr) < (int)getParameters().fieldColorMax.v) {
          POINT_PX(ColorClasses::red, x, y);
        }
      }
    }
  );
  cameraID = CameraInfo::Top;
  CANVAS_PX(cameraID);
  DEBUG_REQUEST("Vision:ColorClassifiers:SimpleFieldColorClassifier:TopCam:markCrClassification",
    for(unsigned int x = 0; x < getImage().width(); x+=2) {
      for(unsigned int y = 0; y < getImage().height(); y+=2) {
        const Pixel& pixel = getImage().get(x, y);
        if( abs((int)pixel.v-(int)maxWeightedIndexCr) < (int)getParameters().fieldColorMax.v) {
          POINT_PX(ColorClasses::red, x, y);
        }
      }
    }
  );

}//end execute

double SimpleFieldColorClassifier::gauss(double sigma, double mean, double x)
{
  double exponent = -((x - mean) * (x - mean)) / (2 * sigma * sigma);
  double ret = exp( exponent );
  return Math::isInf(ret) || Math::isNan(ret) ? 0.0 : ret;
}

<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

// $Id$

/// \ingroup macros
/// \file MUONChamberMaterialBudget.C
/// \brief Utility macro to check tracking chamber material properties.
///
/// \author Philippe Pillot, Subatech, Oct. 2009

#if !defined(__CINT__) || defined(__MAKECINT__)

#include <Riostream.h>
#include <TH2F.h>
#include <TFile.h>
#include <TStyle.h>
#include <TBox.h>
#include <TString.h>
#include <TMath.h>
#include <TGeoManager.h>
#include <TGeoNode.h>
#include <TGeoMaterial.h>
#include <TGeoShape.h>

#endif

void MUONChamberMaterialBudget(Bool_t warn = kFALSE)
{
  /// draw the local chamber thickness over x0 (x/x0) used in the computation of Multiple Coulomb Scattering effets.
  /// Compute <x> and <x/x0> in a limited area (displayed on the histograms) to avoid edge effets.

  Double_t OneOverX0MeanCh[10] = {0.,0.,0.,0.,0.,0.,0.,0.,0.,0.};
  Double_t totalLengthCh[10] = {0.,0.,0.,0.,0.,0.,0.,0.,0.,0.};
  Double_t OneOverX0Mean = 0.;
  Double_t totalLength = 0.;

  // Import TGeo geometry
  if (!gGeoManager) {
    TGeoManager::Import("geometry.root");
    if (!gGeoManager) {
      cout<<"getting geometry from file geometry.root failed"<<endl;
      return;
    }
  }

  // z intervals where to find the stations
  Double_t zIn[5] = {-510., -600., -850., -1250., -1350.};
  Double_t zOut[5] = {-600., -750., -1150., -1350., -1470.};

  // transverse area where to compute locally x and x/x0
  Double_t xIn0[5] = {0., 0., 0., 0., 0.};
  Double_t yIn0[5] = {0., 0., 0., 0., 0.};
  Int_t ixMax[5] = {90, 120, 180, 240, 270};
  Int_t iyMax[5] = {90, 120, 180, 240, 270};

  // transverse area where to compute <x> and <x/x0> for each chamber
  Double_t xIn0ForMean[5] = { 5.,  0.,  40.,  45.,  50.};
  Double_t yIn0ForMean[5] = {21., 30.,   0.,   0.,   0.};
  Int_t ixMaxForMean[5] = {  50,  70,   80,  115,  150 };
  Int_t iyMaxForMean[5] = {  60,  70,  110,  150,  150 };

  // define output histograms
  gStyle->SetPalette(1);
  TFile *f = TFile::Open("MaterialBudget.root","RECREATE");
  TH2F* hXOverX0[10];
  TBox* bXOverX0[10];
  for (Int_t i=0; i<10; i++) {
    Int_t st = i/2;
    hXOverX0[i] = new TH2F(Form("hXOverX0_%d",i+1), Form("x/x0 on ch %d (%%)",i+1),
			   ixMax[st], xIn0[st], xIn0[st]+ixMax[st],
			   iyMax[st], yIn0[st], yIn0[st]+iyMax[st]);
    hXOverX0[i]->SetOption("COLZ");
    bXOverX0[i] = new TBox(xIn0ForMean[st], yIn0ForMean[st],
			   xIn0ForMean[st]+ixMaxForMean[st], yIn0ForMean[st]+iyMaxForMean[st]);
    bXOverX0[i]->SetLineStyle(2);
    bXOverX0[i]->SetLineWidth(2);
    bXOverX0[i]->SetFillStyle(0);
    hXOverX0[i]->GetListOfFunctions()->Add(bXOverX0[i]);
  }

  // loop over stations
  for (Int_t ist=0; ist<5; ist++) {

    Int_t nPoints = 0;

    // loop over position in non bending direction (by step of 1cm)
    for (Int_t ix=0; ix<ixMax[ist]; ix++) {

      Double_t xIn = xIn0[ist] + 1.*ix;

      // loop over position in bending direction (by step of 1cm)
      for (Int_t iy=0; iy<iyMax[ist]; iy++) {

	Double_t yIn = yIn0[ist] + 1.*iy;

	// Initialize starting point and direction
	Double_t trackXYZIn[3] = {xIn, yIn, zIn[ist]};
	Double_t trackXYZOut[3] = {1.000001*xIn, 1.000001*yIn, zOut[ist]};
	//  Double_t trackXYZIn[3] = {35., -45., -510.};
	//  Double_t trackXYZOut[3] = {100., -138., -1500.};
	Double_t pathLength = TMath::Sqrt((trackXYZOut[0] - trackXYZIn[0])*(trackXYZOut[0] - trackXYZIn[0])+
					  (trackXYZOut[1] - trackXYZIn[1])*(trackXYZOut[1] - trackXYZIn[1])+
					  (trackXYZOut[2] - trackXYZIn[2])*(trackXYZOut[2] - trackXYZIn[2]));
	Double_t b[3];
	b[0] = (trackXYZOut[0] - trackXYZIn[0]) / pathLength;
	b[1] = (trackXYZOut[1] - trackXYZIn[1]) / pathLength;
	b[2] = (trackXYZOut[2] - trackXYZIn[2]) / pathLength;
	TGeoNode *currentnode = gGeoManager->InitTrack(trackXYZIn, b);
	if (!currentnode) {
	  if (warn) cout<<"start point out of geometry"<<endl;
	  break;
	}

	Bool_t OK = kTRUE;
	Double_t x0 = 0.;  // radiation-length (cm-1)
	Double_t localOneOverX0MeanCh[10] = {0.,0.,0.,0.,0.,0.,0.,0.,0.,0.};
	Double_t localTotalLengthCh[10] = {0.,0.,0.,0.,0.,0.,0.,0.,0.,0.};
	Double_t localPathLength = 0.;
	Double_t remainingPathLength = pathLength;
	Int_t chId = 2*ist;
	Bool_t enterCh = kFALSE;
	do {
	  // Get material properties
	  TGeoMaterial *material = currentnode->GetVolume()->GetMedium()->GetMaterial();
	  TString mName(material->GetName());
	  mName.ToUpper();
	  x0 = material->GetRadLen();

	  // Get path length within this material
	  gGeoManager->FindNextBoundary(remainingPathLength);
	  localPathLength = gGeoManager->GetStep() + 1.e-6;
	  // Check if boundary within remaining path length. If so, make sure to cross the boundary to prepare the next step
	  if (localPathLength >= remainingPathLength) localPathLength = remainingPathLength;
	  else {
	    currentnode = gGeoManager->Step();
	    if (!currentnode) {
	      if (warn) cout<<"navigation failed(1)"<<endl;
	      OK = kFALSE;
	      break;
	    }
	    if (!gGeoManager->IsEntering()) {
	      // make another small step to try to enter in new absorber slice
	      gGeoManager->SetStep(0.001);
	      currentnode = gGeoManager->Step();
	      if (!gGeoManager->IsEntering() || !currentnode) {
		if (warn) cout<<"navigation failed(2)"<<endl;
		OK = kFALSE;
		break;
	      }
	      localPathLength += 0.001;
	    }
	  }

	  // check if entering a new chamber
	  if (localPathLength > 10.) {
	    if(!mName.Contains("AIR")) {
	      if (warn) {
		material->Print();
	        cout<<"changing chamber while crossing material"<<endl;
	      }
	      OK = kFALSE;
	      break;
	    }
	    if (enterCh) chId++;
	    //if (chId > 2*ist+1) break;
	    enterCh = kFALSE;
	    remainingPathLength -= localPathLength;
	    continue;
	  } else {
	    enterCh = kTRUE;
	  }

	  // print parameters
	  if(!mName.Contains("AIR")) {
	    if(mName.Contains("DIPO")) {
	      if (warn) cout<<"the track cross the dipole"<<endl;
	      OK = kFALSE;
	      break;
	    }
	    //material->Print();
	    //cout<<"localPathLength = "<<localPathLength<<endl;
	    if (chId <= 2*ist+1) {
	      localOneOverX0MeanCh[chId] += localPathLength / x0;
	      localTotalLengthCh[chId] += localPathLength;
	    }
	  }

	  // prepare next step
	  remainingPathLength -= localPathLength;
	} while (remainingPathLength > TGeoShape::Tolerance());

	// account for the local material characteristic if computed successfully
	if (OK && (chId == 2*ist+2)) {

	  // fill histograms in the full space
	  hXOverX0[2*ist]->Fill(xIn,yIn,100.*localOneOverX0MeanCh[2*ist]);
	  hXOverX0[2*ist+1]->Fill(xIn,yIn,100.*localOneOverX0MeanCh[2*ist+1]);

	  // limit the chamber region for the computation of <x> and <x/x0>
	  if (xIn > xIn0ForMean[ist]-0.5 && xIn < xIn0ForMean[ist]+1.*ixMaxForMean[ist]-0.5 &&
	      yIn > yIn0ForMean[ist]-0.5 && yIn < yIn0ForMean[ist]+1.*iyMaxForMean[ist]-0.5) {
	    nPoints++;
	    OneOverX0MeanCh[2*ist] += localOneOverX0MeanCh[2*ist];
	    OneOverX0MeanCh[2*ist+1] += localOneOverX0MeanCh[2*ist+1];
	    totalLengthCh[2*ist] += localTotalLengthCh[2*ist];
	    totalLengthCh[2*ist+1] += localTotalLengthCh[2*ist+1];
	  }

	}

      }

    }

    // normalize <x> and <x/x0> to the number of data points
    for (Int_t i=2*ist; i<=2*ist+1; i++) {
      OneOverX0MeanCh[i] /= (Double_t) nPoints;
      totalLengthCh[i] /= (Double_t) nPoints;
    }

  }

  // print results
  cout<<endl<<endl;
  cout<<"chamber   thickness (cm)    x/x0 (%)"<<endl;
  cout<<"------------------------------------"<<endl;
  for (Int_t i=0; i<10; i++) {
    printf("  %2d          %4.2f            %4.2f\n",i+1,totalLengthCh[i],100.*OneOverX0MeanCh[i]);
    totalLength += totalLengthCh[i];
    OneOverX0Mean += OneOverX0MeanCh[i];
  }
  cout<<"------------------------------------"<<endl;
  printf("  tot         %4.1f            %4.1f\n",totalLength,100.*OneOverX0Mean);
  cout<<endl;

  // save histograms
  f->Write();
  f->Close();

}

<commit_msg>In MUONChamberMaterialBudget.C  - Use the name of the mother volumes instead of the position to select    material belonging to a given chamber - The resolution can be changed by changing the sementation level:    resolution = 1 cm / segmentationLevel (Philippe P.)<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

// $Id$

/// \ingroup macros
/// \file MUONChamberMaterialBudget.C
/// \brief Utility macro to check tracking chamber material properties.
///
/// \author Philippe Pillot, Subatech, Oct. 2009

#if !defined(__CINT__) || defined(__MAKECINT__)

#include <Riostream.h>
#include <TH2F.h>
#include <TFile.h>
#include <TStyle.h>
#include <TBox.h>
#include <TString.h>
#include <TMath.h>
#include <TGeoManager.h>
#include <TGeoNode.h>
#include <TGeoMaterial.h>
#include <TGeoShape.h>

#endif

void MUONChamberMaterialBudget(const char* geoFilename = "geometry.root", Int_t segmentationLevel = 1)
{
  /// Draw the local chamber thickness over x0 (x/x0) used in the computation of Multiple Coulomb Scattering effets.
  /// Compute <x> and <x/x0> in a limited area (displayed on the histograms) to avoid edge effets.
  /// The resolution can be changed by changing the sementation level: resolution = 1 cm / segmentationLevel.

  const char* chamberName[10] = {"SC01", "SC02", "SC03", "SC04", "SC05", "SC06", "SC07", "SC08", "SC09", "SC10"};
  Double_t OneOverX0MeanCh[10] = {0.,0.,0.,0.,0.,0.,0.,0.,0.,0.};
  Double_t totalLengthCh[10] = {0.,0.,0.,0.,0.,0.,0.,0.,0.,0.};
  Double_t OneOverX0Mean = 0.;
  Double_t totalLength = 0.;

  // Import TGeo geometry
  if (!gGeoManager) {
    TGeoManager::Import(geoFilename);
    if (!gGeoManager) {
      cout<<"getting geometry from file geometry.root failed"<<endl;
      return;
    }
  }

  // z intervals where to find the stations
  Double_t zIn[5] =  {-510., -600.,  -800., -1150., -1350.};
  Double_t zOut[5] = {-600., -800., -1150., -1350., -1470.};

  // transverse area where to compute locally x and x/x0
  Double_t xIn0[5] = {0., 0., 0., 0., 0.};
  Double_t yIn0[5] = {0., 0., 0., 0., 0.};
  Int_t ixMax[5] = {90, 120, 165, 250, 260};
  Int_t iyMax[5] = {90, 120, 180, 250, 270};

  // transverse area where to compute <x> and <x/x0> for each chamber
  Double_t xIn0ForMean[5] = { 5.,  5.,  35.,  40.,  40.};
  Double_t yIn0ForMean[5] = {20., 25.,   0.,   0.,   0.};
  Int_t ixMaxForMean[5] = {  50,  65,   85,  120,  160 };
  Int_t iyMaxForMean[5] = {  60,  70,  110,  150,  150 };

  // define output histograms
  gStyle->SetPalette(1);
  TFile *f = TFile::Open("MaterialBudget.root","RECREATE");
  TH2F* hXOverX0[10];
  TBox* bXOverX0[10];
  for (Int_t i=0; i<10; i++) {
    Int_t st = i/2;
    hXOverX0[i] = new TH2F(Form("hXOverX0_%d",i+1), Form("x/x0 on ch %d (%%)",i+1),
			   segmentationLevel*ixMax[st], xIn0[st], xIn0[st]+ixMax[st],
			   segmentationLevel*iyMax[st], yIn0[st], yIn0[st]+iyMax[st]);
    hXOverX0[i]->SetOption("COLZ");
    hXOverX0[i]->SetStats(kFALSE);
    bXOverX0[i] = new TBox(xIn0ForMean[st], yIn0ForMean[st],
			   xIn0ForMean[st]+ixMaxForMean[st], yIn0ForMean[st]+iyMaxForMean[st]);
    bXOverX0[i]->SetLineStyle(2);
    bXOverX0[i]->SetLineWidth(2);
    bXOverX0[i]->SetFillStyle(0);
    hXOverX0[i]->GetListOfFunctions()->Add(bXOverX0[i]);
  }

  // loop over stations
  for (Int_t ist=0; ist<5; ist++) {

    Int_t nPoints = 0;

    // loop over position in non bending direction (by step of 1cm)
    for (Int_t ix=0; ix<segmentationLevel*ixMax[ist]; ix++) {

      Double_t xIn = xIn0[ist] + ((Double_t)ix+0.5) / ((Double_t)segmentationLevel);

      // loop over position in bending direction (by step of 1cm)
      for (Int_t iy=0; iy<segmentationLevel*iyMax[ist]; iy++) {
	Int_t permilDone = 1000 * (ix * segmentationLevel*iyMax[ist] + iy + 1) /
	                   (segmentationLevel*segmentationLevel*ixMax[ist]*iyMax[ist]);
	if (permilDone%10 == 0) cout<<"\rStation "<<ist+1<<": processing... "<<permilDone/10<<"%"<<flush;

	Double_t yIn = yIn0[ist] + ((Double_t)iy+0.5) / ((Double_t)segmentationLevel);

	// Initialize starting point and direction
	Double_t trackXYZIn[3] = {xIn, yIn, zIn[ist]};
	Double_t trackXYZOut[3] = {1.000001*xIn, 1.000001*yIn, zOut[ist]};
	Double_t pathLength = TMath::Sqrt((trackXYZOut[0] - trackXYZIn[0])*(trackXYZOut[0] - trackXYZIn[0])+
					  (trackXYZOut[1] - trackXYZIn[1])*(trackXYZOut[1] - trackXYZIn[1])+
					  (trackXYZOut[2] - trackXYZIn[2])*(trackXYZOut[2] - trackXYZIn[2]));
	Double_t b[3];
	b[0] = (trackXYZOut[0] - trackXYZIn[0]) / pathLength;
	b[1] = (trackXYZOut[1] - trackXYZIn[1]) / pathLength;
	b[2] = (trackXYZOut[2] - trackXYZIn[2]) / pathLength;
	TGeoNode *currentnode = gGeoManager->InitTrack(trackXYZIn, b);
	if (!currentnode) break;

	Bool_t OK = kTRUE;
	Double_t x0 = 0.;  // radiation-length (cm-1)
	Double_t localOneOverX0MeanCh[10] = {0.,0.,0.,0.,0.,0.,0.,0.,0.,0.};
	Double_t localTotalLengthCh[10] = {0.,0.,0.,0.,0.,0.,0.,0.,0.,0.};
	Double_t localPathLength = 0.;
	Double_t remainingPathLength = pathLength;
	do {
	  // Get material properties
	  TGeoMaterial *material = currentnode->GetVolume()->GetMedium()->GetMaterial();
	  TString currentNodePath(gGeoManager->GetPath());
	  x0 = material->GetRadLen();

	  // Get path length within this material
	  gGeoManager->FindNextBoundary(remainingPathLength);
	  localPathLength = gGeoManager->GetStep() + 1.e-6;

	  // Check if boundary within remaining path length.
	  // If so, make sure to cross the boundary to prepare the next step
	  if (localPathLength >= remainingPathLength) localPathLength = remainingPathLength;
	  else {
	    currentnode = gGeoManager->Step();
	    if (!currentnode) { OK = kFALSE; break; }
	    if (!gGeoManager->IsEntering()) {
	      // make another small step to try to enter in new slice
	      gGeoManager->SetStep(0.001);
	      currentnode = gGeoManager->Step();
	      if (!gGeoManager->IsEntering() || !currentnode) { OK = kFALSE; break; }
	      localPathLength += 0.001;
	    }
	  }
	  remainingPathLength -= localPathLength;

	  // check if entering a chamber of the current station or go to next step
	  Int_t chId;
	  if (currentNodePath.Contains(chamberName[2*ist])) chId = 2*ist;
	  else if (currentNodePath.Contains(chamberName[2*ist+1])) chId = 2*ist+1;
	  else continue;

	  // add current material budget
	  localOneOverX0MeanCh[chId] += localPathLength / x0;
	  localTotalLengthCh[chId] += localPathLength;

	} while (remainingPathLength > TGeoShape::Tolerance());

	// account for the local material characteristic if computed successfully
	if (OK) {

	  // fill histograms in the full space
	  hXOverX0[2*ist]->Fill(xIn,yIn,100.*localOneOverX0MeanCh[2*ist]);
	  hXOverX0[2*ist+1]->Fill(xIn,yIn,100.*localOneOverX0MeanCh[2*ist+1]);

	  // computation of <x> and <x/x0> in a limited chamber region
	  if (xIn > xIn0ForMean[ist] && xIn < xIn0ForMean[ist]+1.*ixMaxForMean[ist] &&
	      yIn > yIn0ForMean[ist] && yIn < yIn0ForMean[ist]+1.*iyMaxForMean[ist]) {
	    nPoints++;
	    OneOverX0MeanCh[2*ist] += localOneOverX0MeanCh[2*ist];
	    OneOverX0MeanCh[2*ist+1] += localOneOverX0MeanCh[2*ist+1];
	    totalLengthCh[2*ist] += localTotalLengthCh[2*ist];
	    totalLengthCh[2*ist+1] += localTotalLengthCh[2*ist+1];
	  }

	}

      }

    }
    cout<<"\rStation "<<ist+1<<": processing... 100%"<<endl;

    // normalize <x> and <x/x0> to the number of data points
    for (Int_t i=2*ist; i<=2*ist+1; i++) {
      OneOverX0MeanCh[i] /= (Double_t) nPoints;
      totalLengthCh[i] /= (Double_t) nPoints;
    }

  }

  // print results
  cout<<endl<<endl;
  cout<<"chamber   thickness (cm)    x/x0 (%)"<<endl;
  cout<<"------------------------------------"<<endl;
  for (Int_t i=0; i<10; i++) {
    printf("  %2d          %4.2f            %4.2f\n",i+1,totalLengthCh[i],100.*OneOverX0MeanCh[i]);
    totalLength += totalLengthCh[i];
    OneOverX0Mean += OneOverX0MeanCh[i];
  }
  cout<<"------------------------------------"<<endl;
  printf("  tot         %4.1f            %4.1f\n",totalLength,100.*OneOverX0Mean);
  cout<<endl;

  // save histograms
  f->Write();
  f->Close();

}

<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of meegotouch-controlpanelapplets.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "ut_usbapplet.h"
#include "usbapplet.h"
#include "usbview.h"
#include "usbbrief.h"

#ifdef HAVE_QMSYSTEM
#  include "qmusbmode.h"
#  ifndef QMUSBMODE_STUB_H
#    error "The QmUSBMode is not stubbed, can not continue."
#  endif
using namespace MeeGo;
#endif

#include <dcpwidgettypes.h>
#include <dcpbrief.h>

#include <mdesktopentry.h>
#include <MApplication>
#include <MAction>
#include <MNotification>

#include <QVector>
#include <QList>
#include <QMap>

#define DEBUG
#include "../../src/debug.h"

/******************************************************************************
 * The translations for the USBApplet contains special characters (like %1) so
 * we need to stub the qtTrId() method here.
 */
static QMap<QString, QString> catalog;
static bool                   catalogInitialized = false;

void
initializeCatalog ()
{
    if (catalogInitialized)
        return;

    catalog["qtn_usb_ask_active"] = "qtn_usb_ask_active - %1";
    catalog["qtn_usb_active_mode"] = "qtn_usb_active_mode %1";
}

QString
qtTrId (
        const char  *id,
        int          n)
{
    QString retVal;

    Q_UNUSED (n);
    initializeCatalog ();

    retVal = catalog[id];
    if (retVal.isEmpty())
        retVal = id;

    //SYS_DEBUG ("*** id          = %s", id);
    //SYS_DEBUG ("*** translation = %s", SYS_STR(retVal));

    return retVal;
}

/******************************************************************************
 * Stubbing MNotification
 */
static QString lastPublishedNotification;

bool
MNotification::publish()
{
    //SYS_DEBUG ("*** body() = %s", SYS_STR(body()));
    lastPublishedNotification = body();
    return true;
}

/******************************************************************************
 * Ut_UsbApplet implementation.
 */
void
Ut_UsbApplet::init()
{
}

void
Ut_UsbApplet::cleanup()
{
}

static int argc = 1;
static char *app_name = (char*) "./Ut_UsbApplet";

void
Ut_UsbApplet::initTestCase()
{
    m_App = new MApplication (argc, &app_name);
    m_Applet = new UsbApplet;

    QVERIFY (!m_Applet->m_MainWidget);
    m_Applet->init ();

    /*
     * Testing if the widget is not created yet.
     */
    QVERIFY (!m_Applet->m_MainWidget);
}

void
Ut_UsbApplet::cleanupTestCase()
{
    delete m_Applet;
    m_App->deleteLater ();
}

void
Ut_UsbApplet::testTitle ()
{
    QString title = m_Applet->title();
    QVERIFY (!title.isEmpty());
}

void
Ut_UsbApplet::testConstructWidget ()
{
    #ifdef HAVE_QMSYSTEM
    UsbView                 *widget;
    bool                     backAccepted;
    QList<QmUSBMode::Mode>   availableModes;

    availableModes <<
            QmUSBMode::Connected <<
            QmUSBMode::DataInUse <<
            QmUSBMode::Disconnected <<
            QmUSBMode::MassStorage <<
            QmUSBMode::ChargingOnly <<
            QmUSBMode::OviSuite <<
            QmUSBMode::ModeRequest <<
            QmUSBMode::Ask <<
            QmUSBMode::Undefined;

    /*
     * Testing if the applet creates a widget the first time.
     */
    widget = (UsbView *) m_Applet->constructWidget (0);
    QVERIFY (widget);
    QVERIFY (m_Applet->m_MainWidget == widget);

    /*
     * Testing if the widget accepts the back. Our applets always accept back.
     */
    backAccepted = widget->back();
    QVERIFY (backAccepted);

    /*
     * For all default modes and modes we try to change to all the modes.
     */
    foreach (QmUSBMode::Mode mode, availableModes) {
        foreach (QmUSBMode::Mode defaultMode, availableModes) {
            m_Applet->m_logic->setDefaultMode (defaultMode);
            m_Applet->m_logic->setMode (mode);

            for (int id = 0; id < 3; ++id) {
                lastPublishedNotification = "";
                widget->usbModeActivated (id);

                if (id == defaultMode) {
                    // If we want to change to the current mode nothing happens.
                    QVERIFY (lastPublishedNotification.isEmpty());
                } else if (mode == QmUSBMode::MassStorage ||
                           mode == QmUSBMode::OviSuite)  {

                    switch (defaultMode) {
                        case QmUSBMode::OviSuite:
                        case QmUSBMode::MassStorage:
                        case QmUSBMode::Ask:
                            /* check only ^^ these cased for notification... */
                            break;
                        default:
                            continue;
                    }

                    // If we are connected and try to change the mode we got the
                    // error message and we stay in the same mode we were in.
                    QCOMPARE (lastPublishedNotification,
                              qtTrId ("qtn_usb_change_incorrect"));
                    QCOMPARE (m_Applet->m_logic->getDefaultMode(), defaultMode);
                    QCOMPARE (m_Applet->m_logic->getMode(), mode);
                } else {
                    // Otherwise we should have reached the new mode.
                    //QVERIFY (lastPublishedNotification.isEmpty());
                    //QCOMPARE ((int)m_Applet->m_logic->getDefaultMode(), id);
                    // FIXME: There are the QmUSBMode::ChargingOnly case might
                    // be tested here along with the signal.
                }

            }
        }
    }

    /*
     * Testing if the applet knows about the destruction of the widget.
     */
    delete widget;
    QVERIFY (!m_Applet->m_MainWidget);
    #endif
}

void
Ut_UsbApplet::testMenuItems ()
{
    QVector<MAction*> items = m_Applet->viewMenuItems ();

    //QVERIFY (items.size() == 1);
    SYS_DEBUG ("items.size() = %d", items.size());
}

void
Ut_UsbApplet::testConstructbrief ()
{
    #ifdef HAVE_QMSYSTEM
    UsbBrief *brief1 = (UsbBrief *) m_Applet->constructBrief(0);
    QList<QmUSBMode::Mode>   availableModes;
    QString   iconName;
    QString   text;

    availableModes <<
            QmUSBMode::Connected <<
            QmUSBMode::DataInUse <<
            QmUSBMode::Disconnected <<
            QmUSBMode::MassStorage <<
            QmUSBMode::ChargingOnly <<
            QmUSBMode::OviSuite <<
            QmUSBMode::ModeRequest <<
            QmUSBMode::Ask <<
            QmUSBMode::Undefined;
    /*
     * Getting the brief and checking its properties.
     */
    QVERIFY (brief1);
    QVERIFY (brief1->widgetTypeID() == DcpWidgetType::Label);
    iconName = brief1->icon ();
    QVERIFY (iconName.isEmpty());

    /*
     * Testing all the combinations when the default mode is QmUSBMode::Ask.
     */
    foreach (QmUSBMode::Mode mode, availableModes) {
        foreach (QmUSBMode::Mode defaultMode, availableModes) {
            m_Applet->m_logic->setDefaultMode (defaultMode);
            m_Applet->m_logic->setMode (mode);

            text = brief1->valueText ();
            //SYS_DEBUG ("*** text        = %s", SYS_STR(text));
            //SYS_DEBUG ("*** mode        = %d", mode);
            //SYS_DEBUG ("*** defaultMode = %d", defaultMode);

            if (defaultMode == QmUSBMode::Ask &&
                    mode == QmUSBMode::MassStorage)
                QVERIFY (text == "qtn_usb_ask_active - qtn_usb_mass_storage");
            else if (defaultMode == QmUSBMode::Ask &&
                    mode == QmUSBMode::OviSuite)
                QVERIFY (text == "qtn_usb_ask_active - qtn_usb_ovi_suite");
            else if (defaultMode == QmUSBMode::Ask)
                QVERIFY (text == "qtn_usb_always_ask");
            else if (defaultMode == QmUSBMode::OviSuite &&
                    mode == QmUSBMode::OviSuite)
                QVERIFY (text == "qtn_usb_active_mode qtn_usb_ovi_suite");
            else if (defaultMode == QmUSBMode::MassStorage &&
                    mode == QmUSBMode::MassStorage)
                QVERIFY (text == "qtn_usb_active_mode qtn_usb_mass_storage");
            else if (defaultMode == QmUSBMode::OviSuite)
                QVERIFY (text == "qtn_usb_ovi_suite");
            else if (defaultMode == QmUSBMode::MassStorage)
                QVERIFY (text == "qtn_usb_mass_storage");
            else {
                QVERIFY (text == "qtn_usb_always_ask");
            }
        }
    }

    /*
     * FIXME: These should be tested somehow.
     */
    brief1->settingsChanged ();
    brief1->retranslateUi ();

    delete brief1;
    #endif
}

QTEST_APPLESS_MAIN(Ut_UsbApplet)

<commit_msg>Fixes: broken testcase: ut_usbapplet<commit_after>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of meegotouch-controlpanelapplets.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "ut_usbapplet.h"
#include "usbapplet.h"
#include "usbview.h"
#include "usbbrief.h"

#ifdef HAVE_QMSYSTEM
#  include "qmusbmode.h"
#  ifndef QMUSBMODE_STUB_H
#    error "The QmUSBMode is not stubbed, can not continue."
#  endif
using namespace MeeGo;
#endif

#include <dcpwidgettypes.h>
#include <dcpbrief.h>

#include <mdesktopentry.h>
#include <MApplication>
#include <MAction>
#include <MNotification>

#include <QVector>
#include <QList>
#include <QMap>

#define DEBUG
#include "../../src/debug.h"

#ifdef HAVE_QMSYSTEM
static QmUSBMode::Mode usbModes[3] =
       { QmUSBMode::Ask,
         QmUSBMode::MassStorage,
         QmUSBMode::OviSuite };

inline int
usbModeIndex (QmUSBMode::Mode mode)
{
    int ret = 0;
    for (int i = 0; i < 3; i++)
        if (usbModes[i] == mode)
        {
            ret = i;
            break;
        }
    return ret;
}
#endif

/******************************************************************************
 * The translations for the USBApplet contains special characters (like %1) so
 * we need to stub the qtTrId() method here.
 */
static QMap<QString, QString> catalog;
static bool                   catalogInitialized = false;

void
initializeCatalog ()
{
    if (catalogInitialized)
        return;

    catalog["qtn_usb_ask_active"] = "qtn_usb_ask_active - %1";
    catalog["qtn_usb_active_mode"] = "qtn_usb_active_mode %1";
}

QString
qtTrId (
        const char  *id,
        int          n)
{
    QString retVal;

    Q_UNUSED (n);
    initializeCatalog ();

    retVal = catalog[id];
    if (retVal.isEmpty())
        retVal = id;

    //SYS_DEBUG ("*** id          = %s", id);
    //SYS_DEBUG ("*** translation = %s", SYS_STR(retVal));

    return retVal;
}

/******************************************************************************
 * Stubbing MNotification
 */
static QString lastPublishedNotification;

bool
MNotification::publish()
{
    //SYS_DEBUG ("*** body() = %s", SYS_STR(body()));
    lastPublishedNotification = body();
    return true;
}

/******************************************************************************
 * Ut_UsbApplet implementation.
 */
void
Ut_UsbApplet::init()
{
}

void
Ut_UsbApplet::cleanup()
{
}

static int argc = 1;
static char *app_name = (char*) "./ut_usbapplet";

void
Ut_UsbApplet::initTestCase()
{
    m_App = new MApplication (argc, &app_name);
    m_Applet = new UsbApplet;

    QVERIFY (!m_Applet->m_MainWidget);
    m_Applet->init ();

    /*
     * Testing if the widget is not created yet.
     */
    QVERIFY (!m_Applet->m_MainWidget);
}

void
Ut_UsbApplet::cleanupTestCase()
{
    delete m_Applet;
    m_App->deleteLater ();
}

void
Ut_UsbApplet::testTitle ()
{
    QString title = m_Applet->title();
    QVERIFY (!title.isEmpty());
}

void
Ut_UsbApplet::testConstructWidget ()
{
    #ifdef HAVE_QMSYSTEM
    UsbView                 *widget;
    bool                     backAccepted;
    QList<QmUSBMode::Mode>   availableModes;

    availableModes <<
            QmUSBMode::Connected <<
            QmUSBMode::DataInUse <<
            QmUSBMode::Disconnected <<
            QmUSBMode::MassStorage <<
            QmUSBMode::ChargingOnly <<
            QmUSBMode::OviSuite <<
            QmUSBMode::ModeRequest <<
            QmUSBMode::Ask <<
            QmUSBMode::Undefined;

    /*
     * Testing if the applet creates a widget the first time.
     */
    widget = (UsbView *) m_Applet->constructWidget (0);
    QVERIFY (widget);
    QVERIFY (m_Applet->m_MainWidget == widget);

    /*
     * Testing if the widget accepts the back. Our applets always accept back.
     */
    backAccepted = widget->back();
    QVERIFY (backAccepted);

    /*
     * For all default modes and modes we try to change to all the modes.
     */
    foreach (QmUSBMode::Mode mode, availableModes) {
        foreach (QmUSBMode::Mode defaultMode, availableModes) {
            m_Applet->m_logic->setDefaultMode (defaultMode);
            m_Applet->m_logic->setMode (mode);

            for (int id = 0; id < 3; ++id) {
                lastPublishedNotification = "";
                widget->usbModeActivated (id);

                if (usbModes[id] == defaultMode) {
                    // If we want to change to the current mode nothing happens.
                    QVERIFY (lastPublishedNotification.isEmpty());
                } else if (mode == QmUSBMode::MassStorage ||
                           mode == QmUSBMode::OviSuite)  {

                    switch (defaultMode) {
                        case QmUSBMode::OviSuite:
                        case QmUSBMode::MassStorage:
                        case QmUSBMode::Ask:
                            /* check only ^^ these cases for notification... */
                            break;
                        default:
                            continue;
                    }

                    // If we are connected and try to change the mode we got the
                    // error message and we stay in the same mode we were in.
                    QCOMPARE (lastPublishedNotification,
                              qtTrId ("qtn_usb_change_incorrect"));
                    QCOMPARE (m_Applet->m_logic->getDefaultMode(), defaultMode);
                    QCOMPARE (m_Applet->m_logic->getMode(), mode);
                } else {
                    // Otherwise we should have reached the new mode.
                    //QVERIFY (lastPublishedNotification.isEmpty());
                    //QCOMPARE ((int)m_Applet->m_logic->getDefaultMode(), id);
                    // FIXME: There are the QmUSBMode::ChargingOnly case might
                    // be tested here along with the signal.
                }

            }
        }
    }

    /*
     * Testing if the applet knows about the destruction of the widget.
     */
    delete widget;
    QVERIFY (!m_Applet->m_MainWidget);
    #endif
}

void
Ut_UsbApplet::testMenuItems ()
{
    QVector<MAction*> items = m_Applet->viewMenuItems ();

    //QVERIFY (items.size() == 1);
    SYS_DEBUG ("items.size() = %d", items.size());
}

void
Ut_UsbApplet::testConstructbrief ()
{
    #ifdef HAVE_QMSYSTEM
    UsbBrief *brief1 = (UsbBrief *) m_Applet->constructBrief(0);
    QList<QmUSBMode::Mode>   availableModes;
    QString   iconName;
    QString   text;

    availableModes <<
            QmUSBMode::Connected <<
            QmUSBMode::DataInUse <<
            QmUSBMode::Disconnected <<
            QmUSBMode::MassStorage <<
            QmUSBMode::ChargingOnly <<
            QmUSBMode::OviSuite <<
            QmUSBMode::ModeRequest <<
            QmUSBMode::Ask <<
            QmUSBMode::Undefined;
    /*
     * Getting the brief and checking its properties.
     */
    QVERIFY (brief1);
    QVERIFY (brief1->widgetTypeID() == DcpWidgetType::Label);
    iconName = brief1->icon ();
    QVERIFY (iconName.isEmpty());

    /*
     * Testing all the combinations when the default mode is QmUSBMode::Ask.
     */
    foreach (QmUSBMode::Mode mode, availableModes) {
        foreach (QmUSBMode::Mode defaultMode, availableModes) {
            m_Applet->m_logic->setDefaultMode (defaultMode);
            m_Applet->m_logic->setMode (mode);

            text = brief1->valueText ();
            //SYS_DEBUG ("*** text        = %s", SYS_STR(text));
            //SYS_DEBUG ("*** mode        = %d", mode);
            //SYS_DEBUG ("*** defaultMode = %d", defaultMode);

            if (defaultMode == QmUSBMode::Ask &&
                    mode == QmUSBMode::MassStorage)
                QVERIFY (text == "qtn_usb_ask_active - qtn_usb_mass_storage");
            else if (defaultMode == QmUSBMode::Ask &&
                    mode == QmUSBMode::OviSuite)
                QVERIFY (text == "qtn_usb_ask_active - qtn_usb_ovi_suite");
            else if (defaultMode == QmUSBMode::Ask)
                QVERIFY (text == "qtn_usb_always_ask");
            else if (defaultMode == QmUSBMode::OviSuite &&
                    mode == QmUSBMode::OviSuite)
                QVERIFY (text == "qtn_usb_active_mode qtn_usb_ovi_suite");
            else if (defaultMode == QmUSBMode::MassStorage &&
                    mode == QmUSBMode::MassStorage)
                QVERIFY (text == "qtn_usb_active_mode qtn_usb_mass_storage");
            else if (defaultMode == QmUSBMode::OviSuite)
                QVERIFY (text == "qtn_usb_ovi_suite");
            else if (defaultMode == QmUSBMode::MassStorage)
                QVERIFY (text == "qtn_usb_mass_storage");
            else {
                QVERIFY (text == "qtn_usb_always_ask");
            }
        }
    }

    /*
     * FIXME: These should be tested somehow.
     */
    brief1->settingsChanged ();
    brief1->retranslateUi ();

    delete brief1;
    #endif
}

QTEST_APPLESS_MAIN(Ut_UsbApplet)

<|endoftext|>


<commit_before>/* bzflag
 * Copyright (c) 1993 - 2008 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

// logDetail.cpp : Plugin module for logging server events to stdout
//

#include <iostream>
#include <sstream>
#include "bzfsAPI.h"

BZ_GET_PLUGIN_VERSION

enum action {join , auth , part};

class LogDetail:public bz_EventHandler
{
public:
  LogDetail();
  virtual ~LogDetail();
  virtual void process(bz_EventData *eventData);
private:
  std::string displayPlayerPrivs(int playerID);
  std::string displayCallsign(bz_ApiString callsign);
  std::string displayCallsign(int playerID);
  std::string displayBZid(int playerID);
  std::string displayTeam(bz_eTeamType team);
  virtual void listPlayers(action act, bz_PlayerJoinPartEventData_V1 *data);
};

LogDetail logDetailHandler;

BZF_PLUGIN_CALL int bz_Load(const char * /*commandLine */ )
{
  bz_registerEvent(bz_eSlashCommandEvent, &logDetailHandler);
  bz_registerEvent(bz_eRawChatMessageEvent, &logDetailHandler);
  bz_registerEvent(bz_eServerMsgEvent, &logDetailHandler);
  bz_registerEvent(bz_ePlayerJoinEvent, &logDetailHandler);
  bz_registerEvent(bz_ePlayerPartEvent, &logDetailHandler);
  bz_registerEvent(bz_ePlayerAuthEvent, &logDetailHandler);
  bz_registerEvent(bz_eMessageFilteredEvent, &logDetailHandler);
  bz_debugMessage(4, "logDetail plugin loaded");
  return 0;
}

BZF_PLUGIN_CALL int bz_Unload(void)
{
  bz_removeEvent(bz_eSlashCommandEvent, &logDetailHandler);
  bz_removeEvent(bz_eRawChatMessageEvent, &logDetailHandler);
  bz_removeEvent(bz_eServerMsgEvent, &logDetailHandler);
  bz_removeEvent(bz_ePlayerJoinEvent, &logDetailHandler);
  bz_removeEvent(bz_ePlayerPartEvent, &logDetailHandler);
  bz_removeEvent(bz_ePlayerAuthEvent, &logDetailHandler);
  bz_removeEvent(bz_eMessageFilteredEvent, &logDetailHandler);
  bz_debugMessage(4, "logDetail plugin unloaded");
  return 0;
}

LogDetail::LogDetail()
{
  bz_debugMessage(0, "SERVER-STATUS Running");
  bz_debugMessagef(0, "SERVER-MAPNAME %s", bz_getPublicDescription().c_str());
  listPlayers(join , NULL);
}

LogDetail::~LogDetail()
{
  listPlayers(part, NULL);
  bz_debugMessage(0, "SERVER-STATUS Stopped");
}

void LogDetail::process(bz_EventData *eventData)
{
  bz_ChatEventData_V1 *chatData = (bz_ChatEventData_V1 *) eventData;
  bz_ServerMsgEventData_V1 *serverMsgData = (bz_ServerMsgEventData_V1 *) eventData;
  bz_SlashCommandEventData_V1 *cmdData = (bz_SlashCommandEventData_V1 *) eventData;
  bz_PlayerJoinPartEventData_V1 *joinPartData = (bz_PlayerJoinPartEventData_V1 *) eventData;
  bz_PlayerAuthEventData_V1 *authData = (bz_PlayerAuthEventData_V1 *) eventData;
  bz_MessageFilteredEventData_V1 *filteredData = (bz_MessageFilteredEventData_V1 *) eventData;
  char temp[9] = { 0 };

  if (eventData) {
    switch (eventData->eventType) {
    case bz_eSlashCommandEvent:
      // Slash commands are case insensitive
      // Tokenize the stream and check the first word
      // /report -> MSG-REPORT
      // anything -> MSG-COMMAND

      strncpy(temp, cmdData->message.c_str(), 8);

      if (strcasecmp(temp, "/REPORT ") == 0) {
	bz_debugMessagef(0, "MSG-REPORT %s %s",
			 displayCallsign(cmdData->from).c_str(),
			 cmdData->message.c_str()+8);
      } else {
	bz_debugMessagef(0, "MSG-COMMAND %s %s",
			 displayCallsign(cmdData->from).c_str(),
			 cmdData->message.c_str()+1);
      }
      break;
    case bz_eRawChatMessageEvent:
      if ((chatData->to == BZ_ALLUSERS) && (chatData->team == eNoTeam)) {
	bz_debugMessagef(0, "MSG-BROADCAST %s %s",
			 displayCallsign(chatData->from).c_str(),
			 chatData->message.c_str());
      } else if (chatData->to == BZ_NULLUSER) {
	if (chatData->team == eAdministrators) {
	  bz_debugMessagef(0, "MSG-ADMIN %s %s",
			   displayCallsign(chatData->from).c_str(),
			   chatData->message.c_str());
	} else {
	  bz_debugMessagef(0, "MSG-TEAM %s %s %s",
			   displayCallsign(chatData->from).c_str(),
			   displayTeam(chatData->team).c_str(),
			   chatData->message.c_str());
	}
      } else {
	  bz_debugMessagef(0, "MSG-DIRECT %s %s %s",
			   displayCallsign(chatData->from).c_str(),
			   displayCallsign(chatData->to).c_str(),
			   chatData->message.c_str());
      }
      break;
    case bz_eMessageFilteredEvent:
      bz_debugMessagef(0, "MSG-FILTERED %s %s",
		       displayCallsign(filteredData->player).c_str(),
		       filteredData->filteredMessage.c_str());
      break;
    case bz_eServerMsgEvent:
      if ((serverMsgData->to == BZ_ALLUSERS) && (serverMsgData->team == eNoTeam)) {
	bz_debugMessagef(0, "MSG-BROADCAST 6:SERVER %s",
			 serverMsgData->message.c_str());
      } else if (serverMsgData->to == BZ_NULLUSER) {
	if (serverMsgData->team == eAdministrators) {
	  bz_debugMessagef(0, "MSG-ADMIN 6:SERVER %s",
			   serverMsgData->message.c_str());
	} else {
	  bz_debugMessagef(0, "MSG-TEAM 6:SERVER %s %s",
			   displayTeam(serverMsgData->team ).c_str(),
			   chatData->message.c_str());
	}
      } else {
	bz_debugMessagef(0, "MSG-DIRECT 6:SERVER %s %s",
			 displayCallsign(serverMsgData->to ).c_str(),
			 serverMsgData->message.c_str());
      }
      break;
    case bz_ePlayerJoinEvent:
      {
	if (joinPartData->record) {
	  bz_debugMessagef(0, "PLAYER-JOIN %s #%d%s %s %s",
			   displayCallsign(joinPartData->record->callsign).c_str(),
			   joinPartData->playerID,
			   displayBZid(joinPartData->playerID).c_str(),
			   displayTeam(joinPartData->record->team).c_str(),
			   displayPlayerPrivs(joinPartData->playerID).c_str());
	  listPlayers(join, joinPartData);
	}
      }
      break;
    case bz_ePlayerPartEvent:
      bz_debugMessagef(0, "PLAYER-PART %s #%d%s %s",
		       displayCallsign(joinPartData->playerID).c_str(),
		       joinPartData->playerID,
		       displayBZid(joinPartData->playerID).c_str(),
		       joinPartData->reason.c_str());
      listPlayers(part, joinPartData);
      break;
    case bz_ePlayerAuthEvent:
      bz_debugMessagef(0, "PLAYER-AUTH %s %s",
		       displayCallsign(authData->playerID).c_str(),
		       displayPlayerPrivs(authData->playerID).c_str()),
	listPlayers(join, joinPartData);
      break;
    default:
      break;
    }
  }
}

std::string LogDetail::displayBZid(int playerID)
{
  std::ostringstream bzid;

  bz_BasePlayerRecord *player = bz_getPlayerByIndex(playerID);
  if (player) {
    if (player->globalUser)
      bzid << " BZid:" << player->bzID.c_str();
    bz_freePlayerRecord( player );
  }

  return bzid.str();
}

std::string LogDetail::displayPlayerPrivs(int playerID)
{
  std::ostringstream playerPrivs;

  bz_BasePlayerRecord *player = bz_getPlayerByIndex(playerID);
  if (player) {
    playerPrivs << "IP:" << player->ipAddress.c_str();
    if (player->verified) playerPrivs << " VERIFIED";
    if (player->globalUser) playerPrivs << " GLOBALUSER";
    if (player->admin) playerPrivs << " ADMIN";
    if (player->op) playerPrivs << " OPERATOR";
    bz_freePlayerRecord(player);
  } else {
    playerPrivs << "IP:0.0.0.0";
  }

  return playerPrivs.str();
}

std::string LogDetail::displayCallsign(bz_ApiString callsign)
{
  std::ostringstream result;

  result << (unsigned int)strlen(callsign.c_str()) << ":" << callsign.c_str();

  return result.str();
}

std::string LogDetail::displayCallsign(int playerID)
{
  std::ostringstream callsign;
  bz_BasePlayerRecord *player = bz_getPlayerByIndex(playerID);
  if (player) {
    callsign << (unsigned int)strlen(player->callsign.c_str()) << ":";
    callsign << player->callsign.c_str();
    bz_freePlayerRecord(player);
  } else {
    callsign << "7:UNKNOWN";
  }
  return callsign.str();
}

std::string LogDetail::displayTeam(bz_eTeamType team)
{
  // Display the player team
  switch (team) {
    case eRogueTeam:
      return std::string("ROGUE");
    case eRedTeam:
      return std::string("RED");
    case eGreenTeam:
      return std::string("GREEN");
    case eBlueTeam:
      return std::string("BLUE");
    case ePurpleTeam:
      return std::string("PURPLE");
    case eRabbitTeam:
      return std::string("RABBIT");
    case eHunterTeam:
      return std::string("HUNTER");
    case eObservers:
      return std::string("OBSERVER");
    default :
      return std::string("NOTEAM");
  }
}

void LogDetail::listPlayers(action act, bz_PlayerJoinPartEventData_V1 * data)
{
  bz_APIIntList *playerList = bz_newIntList();
  bz_BasePlayerRecord *player;
  std::ostringstream msg;
  char playerStatus;
  int numPlayers;

  bz_getPlayerIndexList(playerList);

  bz_debugMessage(4, "Players:");
  //
  // Count number of players
  //
  numPlayers = 0;
  for (unsigned int i = 0; i < playerList->size(); i++) {
    player = bz_getPlayerByIndex(playerList->get(i));
    if (player) {
      if ((player->callsign != "") && (act == join || act == auth || (data && (player->playerID != data->playerID))))
	numPlayers++;
      bz_freePlayerRecord(player);
    }
  }

  //
  // Display number of players, callsign, and email string in the following format:
  //
  // PLAYERS (nn) [G]cc:callsign(ee:emailstring)
  // nn - number of players
  // G  - global auth identifier (+|-| |@)
  // cc - count of characters in player callsign
  // callsign - player callsign
  // ee - count of characters in email string
  // emailstring - player email string
  //
  // eg.
  // PLAYERS (2) [@]7:Thumper(16:me@somewhere.net) [ ]3:xxx()
  //
  msg.str("");
  msg << "PLAYERS (" << numPlayers << ") ";
  for (unsigned int i = 0; i < playerList->size(); i++) {
    player = bz_getPlayerByIndex(playerList->get(i));
    if (player) {
      if ((player->callsign != "") && (act == join || act == auth || (data && (player->playerID != data->playerID)))) {
	playerStatus = ' ';
	if (player->globalUser)
	  playerStatus = '+';
	if (player->verified)
	  playerStatus = '+';
	if (player->admin && ! bz_hasPerm(player->playerID, bz_perm_hideAdmin))
	  playerStatus = '@';
	msg << "[" << playerStatus << "]";
	msg << player->callsign.size() << ':';
	msg << player->callsign.c_str();
	msg << "(";
	if (player->email != "")
	  msg << player->email.size() << ":" << player->email.c_str();
	msg << ") ";
      }
      bz_freePlayerRecord(player);
    }
  }
  bz_debugMessage(0, msg.str().c_str());

  bz_deleteIntList(playerList);
}

// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>Whitespace<commit_after>/* bzflag
 * Copyright (c) 1993 - 2008 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

// logDetail.cpp : Plugin module for logging server events to stdout
//

#include <iostream>
#include <sstream>
#include "bzfsAPI.h"

BZ_GET_PLUGIN_VERSION

enum action {join , auth , part};

class LogDetail:public bz_EventHandler
{
public:
  LogDetail();
  virtual ~LogDetail();
  virtual void process(bz_EventData *eventData);
private:
  std::string displayPlayerPrivs(int playerID);
  std::string displayCallsign(bz_ApiString callsign);
  std::string displayCallsign(int playerID);
  std::string displayBZid(int playerID);
  std::string displayTeam(bz_eTeamType team);
  virtual void listPlayers(action act, bz_PlayerJoinPartEventData_V1 *data);
};

LogDetail logDetailHandler;

BZF_PLUGIN_CALL int bz_Load(const char * /*commandLine */ )
{
  bz_registerEvent(bz_eSlashCommandEvent, &logDetailHandler);
  bz_registerEvent(bz_eRawChatMessageEvent, &logDetailHandler);
  bz_registerEvent(bz_eServerMsgEvent, &logDetailHandler);
  bz_registerEvent(bz_ePlayerJoinEvent, &logDetailHandler);
  bz_registerEvent(bz_ePlayerPartEvent, &logDetailHandler);
  bz_registerEvent(bz_ePlayerAuthEvent, &logDetailHandler);
  bz_registerEvent(bz_eMessageFilteredEvent, &logDetailHandler);
  bz_debugMessage(4, "logDetail plugin loaded");
  return 0;
}

BZF_PLUGIN_CALL int bz_Unload(void)
{
  bz_removeEvent(bz_eSlashCommandEvent, &logDetailHandler);
  bz_removeEvent(bz_eRawChatMessageEvent, &logDetailHandler);
  bz_removeEvent(bz_eServerMsgEvent, &logDetailHandler);
  bz_removeEvent(bz_ePlayerJoinEvent, &logDetailHandler);
  bz_removeEvent(bz_ePlayerPartEvent, &logDetailHandler);
  bz_removeEvent(bz_ePlayerAuthEvent, &logDetailHandler);
  bz_removeEvent(bz_eMessageFilteredEvent, &logDetailHandler);
  bz_debugMessage(4, "logDetail plugin unloaded");
  return 0;
}

LogDetail::LogDetail()
{
  bz_debugMessage(0, "SERVER-STATUS Running");
  bz_debugMessagef(0, "SERVER-MAPNAME %s", bz_getPublicDescription().c_str());
  listPlayers(join, NULL);
}

LogDetail::~LogDetail()
{
  listPlayers(part, NULL);
  bz_debugMessage(0, "SERVER-STATUS Stopped");
}

void LogDetail::process(bz_EventData *eventData)
{
  bz_ChatEventData_V1 *chatData = (bz_ChatEventData_V1 *) eventData;
  bz_ServerMsgEventData_V1 *serverMsgData = (bz_ServerMsgEventData_V1 *) eventData;
  bz_SlashCommandEventData_V1 *cmdData = (bz_SlashCommandEventData_V1 *) eventData;
  bz_PlayerJoinPartEventData_V1 *joinPartData = (bz_PlayerJoinPartEventData_V1 *) eventData;
  bz_PlayerAuthEventData_V1 *authData = (bz_PlayerAuthEventData_V1 *) eventData;
  bz_MessageFilteredEventData_V1 *filteredData = (bz_MessageFilteredEventData_V1 *) eventData;
  char temp[9] = { 0 };

  if (eventData) {
    switch (eventData->eventType) {
    case bz_eSlashCommandEvent:
      // Slash commands are case insensitive
      // Tokenize the stream and check the first word
      // /report -> MSG-REPORT
      // anything -> MSG-COMMAND

      strncpy(temp, cmdData->message.c_str(), 8);

      if (strcasecmp(temp, "/REPORT ") == 0) {
	bz_debugMessagef(0, "MSG-REPORT %s %s",
			 displayCallsign(cmdData->from).c_str(),
			 cmdData->message.c_str()+8);
      } else {
	bz_debugMessagef(0, "MSG-COMMAND %s %s",
			 displayCallsign(cmdData->from).c_str(),
			 cmdData->message.c_str()+1);
      }
      break;
    case bz_eRawChatMessageEvent:
      if ((chatData->to == BZ_ALLUSERS) && (chatData->team == eNoTeam)) {
	bz_debugMessagef(0, "MSG-BROADCAST %s %s",
			 displayCallsign(chatData->from).c_str(),
			 chatData->message.c_str());
      } else if (chatData->to == BZ_NULLUSER) {
	if (chatData->team == eAdministrators) {
	  bz_debugMessagef(0, "MSG-ADMIN %s %s",
			   displayCallsign(chatData->from).c_str(),
			   chatData->message.c_str());
	} else {
	  bz_debugMessagef(0, "MSG-TEAM %s %s %s",
			   displayCallsign(chatData->from).c_str(),
			   displayTeam(chatData->team).c_str(),
			   chatData->message.c_str());
	}
      } else {
	  bz_debugMessagef(0, "MSG-DIRECT %s %s %s",
			   displayCallsign(chatData->from).c_str(),
			   displayCallsign(chatData->to).c_str(),
			   chatData->message.c_str());
      }
      break;
    case bz_eMessageFilteredEvent:
      bz_debugMessagef(0, "MSG-FILTERED %s %s",
		       displayCallsign(filteredData->player).c_str(),
		       filteredData->filteredMessage.c_str());
      break;
    case bz_eServerMsgEvent:
      if ((serverMsgData->to == BZ_ALLUSERS) && (serverMsgData->team == eNoTeam)) {
	bz_debugMessagef(0, "MSG-BROADCAST 6:SERVER %s",
			 serverMsgData->message.c_str());
      } else if (serverMsgData->to == BZ_NULLUSER) {
	if (serverMsgData->team == eAdministrators) {
	  bz_debugMessagef(0, "MSG-ADMIN 6:SERVER %s",
			   serverMsgData->message.c_str());
	} else {
	  bz_debugMessagef(0, "MSG-TEAM 6:SERVER %s %s",
			   displayTeam(serverMsgData->team ).c_str(),
			   chatData->message.c_str());
	}
      } else {
	bz_debugMessagef(0, "MSG-DIRECT 6:SERVER %s %s",
			 displayCallsign(serverMsgData->to ).c_str(),
			 serverMsgData->message.c_str());
      }
      break;
    case bz_ePlayerJoinEvent:
      {
	if (joinPartData->record) {
	  bz_debugMessagef(0, "PLAYER-JOIN %s #%d%s %s %s",
			   displayCallsign(joinPartData->record->callsign).c_str(),
			   joinPartData->playerID,
			   displayBZid(joinPartData->playerID).c_str(),
			   displayTeam(joinPartData->record->team).c_str(),
			   displayPlayerPrivs(joinPartData->playerID).c_str());
	  listPlayers(join, joinPartData);
	}
      }
      break;
    case bz_ePlayerPartEvent:
      bz_debugMessagef(0, "PLAYER-PART %s #%d%s %s",
		       displayCallsign(joinPartData->playerID).c_str(),
		       joinPartData->playerID,
		       displayBZid(joinPartData->playerID).c_str(),
		       joinPartData->reason.c_str());
      listPlayers(part, joinPartData);
      break;
    case bz_ePlayerAuthEvent:
      bz_debugMessagef(0, "PLAYER-AUTH %s %s",
		       displayCallsign(authData->playerID).c_str(),
		       displayPlayerPrivs(authData->playerID).c_str()),
	listPlayers(join, joinPartData);
      break;
    default:
      break;
    }
  }
}

std::string LogDetail::displayBZid(int playerID)
{
  std::ostringstream bzid;

  bz_BasePlayerRecord *player = bz_getPlayerByIndex(playerID);
  if (player) {
    if (player->globalUser)
      bzid << " BZid:" << player->bzID.c_str();
    bz_freePlayerRecord( player );
  }

  return bzid.str();
}

std::string LogDetail::displayPlayerPrivs(int playerID)
{
  std::ostringstream playerPrivs;

  bz_BasePlayerRecord *player = bz_getPlayerByIndex(playerID);
  if (player) {
    playerPrivs << "IP:" << player->ipAddress.c_str();
    if (player->verified) playerPrivs << " VERIFIED";
    if (player->globalUser) playerPrivs << " GLOBALUSER";
    if (player->admin) playerPrivs << " ADMIN";
    if (player->op) playerPrivs << " OPERATOR";
    bz_freePlayerRecord(player);
  } else {
    playerPrivs << "IP:0.0.0.0";
  }

  return playerPrivs.str();
}

std::string LogDetail::displayCallsign(bz_ApiString callsign)
{
  std::ostringstream result;

  result << (unsigned int)strlen(callsign.c_str()) << ":" << callsign.c_str();

  return result.str();
}

std::string LogDetail::displayCallsign(int playerID)
{
  std::ostringstream callsign;
  bz_BasePlayerRecord *player = bz_getPlayerByIndex(playerID);
  if (player) {
    callsign << (unsigned int)strlen(player->callsign.c_str()) << ":";
    callsign << player->callsign.c_str();
    bz_freePlayerRecord(player);
  } else {
    callsign << "7:UNKNOWN";
  }
  return callsign.str();
}

std::string LogDetail::displayTeam(bz_eTeamType team)
{
  // Display the player team
  switch (team) {
    case eRogueTeam:
      return std::string("ROGUE");
    case eRedTeam:
      return std::string("RED");
    case eGreenTeam:
      return std::string("GREEN");
    case eBlueTeam:
      return std::string("BLUE");
    case ePurpleTeam:
      return std::string("PURPLE");
    case eRabbitTeam:
      return std::string("RABBIT");
    case eHunterTeam:
      return std::string("HUNTER");
    case eObservers:
      return std::string("OBSERVER");
    default :
      return std::string("NOTEAM");
  }
}

void LogDetail::listPlayers(action act, bz_PlayerJoinPartEventData_V1 * data)
{
  bz_APIIntList *playerList = bz_newIntList();
  bz_BasePlayerRecord *player;
  std::ostringstream msg;
  char playerStatus;
  int numPlayers;

  bz_getPlayerIndexList(playerList);

  bz_debugMessage(4, "Players:");
  //
  // Count number of players
  //
  numPlayers = 0;
  for (unsigned int i = 0; i < playerList->size(); i++) {
    player = bz_getPlayerByIndex(playerList->get(i));
    if (player) {
      if ((player->callsign != "") && (act == join || act == auth || (data && (player->playerID != data->playerID))))
	numPlayers++;
      bz_freePlayerRecord(player);
    }
  }

  //
  // Display number of players, callsign, and email string in the following format:
  //
  // PLAYERS (nn) [G]cc:callsign(ee:emailstring)
  // nn - number of players
  // G  - global auth identifier (+|-| |@)
  // cc - count of characters in player callsign
  // callsign - player callsign
  // ee - count of characters in email string
  // emailstring - player email string
  //
  // eg.
  // PLAYERS (2) [@]7:Thumper(16:me@somewhere.net) [ ]3:xxx()
  //
  msg.str("");
  msg << "PLAYERS (" << numPlayers << ") ";
  for (unsigned int i = 0; i < playerList->size(); i++) {
    player = bz_getPlayerByIndex(playerList->get(i));
    if (player) {
      if ((player->callsign != "") && (act == join || act == auth || (data && (player->playerID != data->playerID)))) {
	playerStatus = ' ';
	if (player->globalUser)
	  playerStatus = '+';
	if (player->verified)
	  playerStatus = '+';
	if (player->admin && ! bz_hasPerm(player->playerID, bz_perm_hideAdmin))
	  playerStatus = '@';
	msg << "[" << playerStatus << "]";
	msg << player->callsign.size() << ':';
	msg << player->callsign.c_str();
	msg << "(";
	if (player->email != "")
	  msg << player->email.size() << ":" << player->email.c_str();
	msg << ") ";
      }
      bz_freePlayerRecord(player);
    }
  }
  bz_debugMessage(0, msg.str().c_str());

  bz_deleteIntList(playerList);
}

// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>


<commit_before>/*
 -----------------------------------------------------------------------------
 This source file is part of OGRE
 (Object-oriented Graphics Rendering Engine)
 For the latest info, see http://www.ogre3d.org/

 Copyright (c) 2000-2009 Torus Knot Software Ltd

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 -----------------------------------------------------------------------------
 */
#include "FileSystemLayerImpl.h"
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <shlobj.h>
#include <io.h>

namespace OgreBites
{
	void FileSystemLayerImpl::getConfigPaths()
	{
		// try to determine the application's path
		DWORD bufsize = 256;
		char* resolved = 0;
		do
		{
			char* buf = OGRE_ALLOC_T(char, bufsize, Ogre::MEMCATEGORY_GENERAL);
			DWORD retval = GetModuleFileName(NULL, buf, bufsize);
			if (retval == 0)
			{
				// failed
				OGRE_FREE(buf, Ogre::MEMCATEGORY_GENERAL);
				break;
			}

			if (retval < bufsize)
			{
				// operation was successful.
				resolved = buf;
			}
			else
			{
				// buffer was too small, grow buffer and try again
				OGRE_FREE(buf, Ogre::MEMCATEGORY_GENERAL);
				bufsize <<= 1;
			}
		} while (!resolved);

		Ogre::String appPath = resolved;
		if (resolved)
			OGRE_FREE(resolved, Ogre::MEMCATEGORY_GENERAL);
		if (!appPath.empty())
		{
			// need to strip the application filename from the path
			Ogre::String::size_type pos = appPath.rfind('\\');
			if (pos != Ogre::String::npos)
				appPath.erase(pos);
		}
		else
		{
			// fall back to current working dir
			appPath = ".";
		}

		// use application path as config search path
		mConfigPaths.push_back(appPath + '\\');
	}
    //---------------------------------------------------------------------
	void FileSystemLayerImpl::prepareUserHome(const Ogre::String& subdir)
	{
		TCHAR path[MAX_PATH];
		if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_PERSONAL|CSIDL_FLAG_CREATE, NULL, 0, path)))
		{
			mHomePath = path;
			// create Ogre subdir
			mHomePath += "\\Ogre\\";
			if (! CreateDirectory(mHomePath.c_str(), NULL) && GetLastError() != ERROR_ALREADY_EXISTS)
			{
				// couldn't create directory, fall back to current working dir
				mHomePath.clear();
			}
			else
			{
				mHomePath += subdir + '\\';
				// create release subdir
				if (! CreateDirectory(mHomePath.c_str(), NULL) && GetLastError() != ERROR_ALREADY_EXISTS)
				{
					// couldn't create directory, fall back to current working dir
					mHomePath.clear();
				}
			}
		}

		if (mHomePath.empty())
		{
			// couldn't create dir in home directory, fall back to cwd
			mHomePath = "";
		}
	}
    //---------------------------------------------------------------------
	const bool FileSystemLayerImpl::fileExists(const Ogre::String& path) const
	{
		return _access(path.c_str(), 00) == 0;
	}
}
<commit_msg>[3078774] Convert home path to OEM codepage in FileSystemLayerImpl_Win32<commit_after>/*
 -----------------------------------------------------------------------------
 This source file is part of OGRE
 (Object-oriented Graphics Rendering Engine)
 For the latest info, see http://www.ogre3d.org/

 Copyright (c) 2000-2009 Torus Knot Software Ltd

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 -----------------------------------------------------------------------------
 */
#include "FileSystemLayerImpl.h"
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <shlobj.h>
#include <io.h>

namespace OgreBites
{
	void FileSystemLayerImpl::getConfigPaths()
	{
		// try to determine the application's path
		DWORD bufsize = 256;
		char* resolved = 0;
		do
		{
			char* buf = OGRE_ALLOC_T(char, bufsize, Ogre::MEMCATEGORY_GENERAL);
			DWORD retval = GetModuleFileName(NULL, buf, bufsize);
			if (retval == 0)
			{
				// failed
				OGRE_FREE(buf, Ogre::MEMCATEGORY_GENERAL);
				break;
			}

			if (retval < bufsize)
			{
				// operation was successful.
				resolved = buf;
			}
			else
			{
				// buffer was too small, grow buffer and try again
				OGRE_FREE(buf, Ogre::MEMCATEGORY_GENERAL);
				bufsize <<= 1;
			}
		} while (!resolved);

		Ogre::String appPath = resolved;
		if (resolved)
			OGRE_FREE(resolved, Ogre::MEMCATEGORY_GENERAL);
		if (!appPath.empty())
		{
			// need to strip the application filename from the path
			Ogre::String::size_type pos = appPath.rfind('\\');
			if (pos != Ogre::String::npos)
				appPath.erase(pos);
		}
		else
		{
			// fall back to current working dir
			appPath = ".";
		}

		// use application path as config search path
		mConfigPaths.push_back(appPath + '\\');
	}
    //---------------------------------------------------------------------
	void FileSystemLayerImpl::prepareUserHome(const Ogre::String& subdir)
	{
		TCHAR path[MAX_PATH];
		if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_PERSONAL|CSIDL_FLAG_CREATE, NULL, 0, path)))
		{
			// need to convert to OEM codepage so that fstream can use
			// it properly on international systems.
			TCHAR oemPath[MAX_PATH];
			CharToOem(path, oemPath);
			mHomePath = oemPath;
			// create Ogre subdir
			mHomePath += "\\Ogre\\";
			if (! CreateDirectory(mHomePath.c_str(), NULL) && GetLastError() != ERROR_ALREADY_EXISTS)
			{
				// couldn't create directory, fall back to current working dir
				mHomePath.clear();
			}
			else
			{
				mHomePath += subdir + '\\';
				// create release subdir
				if (! CreateDirectory(mHomePath.c_str(), NULL) && GetLastError() != ERROR_ALREADY_EXISTS)
				{
					// couldn't create directory, fall back to current working dir
					mHomePath.clear();
				}
			}
		}

		if (mHomePath.empty())
		{
			// couldn't create dir in home directory, fall back to cwd
			mHomePath = "";
		}
	}
    //---------------------------------------------------------------------
	const bool FileSystemLayerImpl::fileExists(const Ogre::String& path) const
	{
		return _access(path.c_str(), 00) == 0;
	}
}
<|endoftext|>


<commit_before>// @(#)root/base:$Name:  $:$Id: TBrowserImp.cxx,v 1.1.1.1 2000/05/16 17:00:38 rdm Exp $
// Author: Fons Rademakers   15/11/95

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//________________________________________________________________________
//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TBrowserImp                                                          //
//                                                                      //
// ABC describing GUI independent browser implementation protocol.      //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TBrowserImp.h"

ClassImp(TBrowserImp)

void SetDrawOption(Option_t * /*option*/) {}
<commit_msg>Forgot classname in constructor!<commit_after>// @(#)root/base:$Name:  $:$Id: TBrowserImp.cxx,v 1.2 2004/06/25 10:10:11 brun Exp $
// Author: Fons Rademakers   15/11/95

/*************************************************************************
 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

//________________________________________________________________________
//////////////////////////////////////////////////////////////////////////
//                                                                      //
// TBrowserImp                                                          //
//                                                                      //
// ABC describing GUI independent browser implementation protocol.      //
//                                                                      //
//////////////////////////////////////////////////////////////////////////

#include "TBrowserImp.h"

ClassImp(TBrowserImp)

void TBrowserImp::SetDrawOption(Option_t * /*option*/) {}
<|endoftext|>