<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <GL3DBarChart.hxx>

#include <GL/glew.h>

#include <glm/glm.hpp>
#include <glm/gtx/transform.hpp>

#include "3DChartObjects.hxx"
#include "GL3DRenderer.hxx"
#include <ExplicitCategoriesProvider.hxx>
#include <DataSeriesHelper.hxx>

using namespace com::sun::star;

namespace chart {

GL3DBarChart::GL3DBarChart(
    const css::uno::Reference<css::chart2::XChartType>& xChartType,
    const boost::ptr_vector<VDataSeries>& rDataSeries,
    OpenGLWindow& rWindow, ExplicitCategoriesProvider& rCatProvider ) :
    mxChartType(xChartType),
    maDataSeries(rDataSeries),
    mpRenderer(new opengl3D::OpenGL3DRenderer()),
    mrWindow(rWindow),
    mrCatProvider(rCatProvider)
{
}

GL3DBarChart::~GL3DBarChart()
{
}

void GL3DBarChart::create3DShapes()
{
    // Each series of data flows from left to right, and multiple series are
    // stacked vertically along y axis.

    // NOTE: These objects are created and positioned in a totally blind
    // fashion since we don't even have a way to see them on screen.  So, no
    // guarantee they are positioned correctly.  In fact, they are guaranteed
    // to be positioned incorrectly.

    const float nBarSizeX = 10;
    const float nBarSizeY = 10;
    const float nBarDistanceX = nBarSizeX / 2;
    const float nBarDistanceY = nBarSizeY / 2;

    sal_uInt32 nId = 1;

    std::vector<opengl3D::Text*> aYAxisTexts;

    float nYPos = 0.0;

    maShapes.clear();
    maShapes.push_back(new opengl3D::Camera(mpRenderer.get()));
    sal_Int32 nSeriesIndex = 0;
    for (boost::ptr_vector<VDataSeries>::const_iterator itr = maDataSeries.begin(),
            itrEnd = maDataSeries.end(); itr != itrEnd; ++itr)
    {
        nYPos = nSeriesIndex * (nBarSizeY + nBarDistanceY);

        const VDataSeries& rDataSeries = *itr;
        sal_Int32 nPointCount = rDataSeries.getTotalPointCount();

        // Create series name text object.
        OUString aSeriesName =
            DataSeriesHelper::getDataSeriesLabel(
                rDataSeries.getModel(), mxChartType->getRoleOfSequenceForSeriesLabel());

        aYAxisTexts.push_back(new opengl3D::Text(mpRenderer.get(), aSeriesName, nId++));
        opengl3D::Text* p = aYAxisTexts.back();
        Size aTextSize = p->getSize();
        glm::vec3 aTopLeft, aTopRight, aBottomRight;
        aTopLeft.x = aTextSize.getWidth() * -1.0;
        aTopLeft.y = nYPos;
        aTopRight.y = nYPos;
        aBottomRight = aTopRight;
        aBottomRight.y += aTextSize.getHeight();
        p->setPosition(aTopLeft, aTopRight, aBottomRight);

        for(sal_Int32 nIndex = 0; nIndex < nPointCount; ++nIndex)
        {
            float nVal = rDataSeries.getYValue(nIndex);
            float nXPos = nIndex * (nBarSizeX + nBarDistanceX);

            sal_Int32 nColor = COL_BLUE;

            glm::mat4 aBarPosition;
            aBarPosition = glm::scale(aBarPosition, nBarSizeX, nBarSizeY, nVal);
            aBarPosition = glm::translate(aBarPosition, nXPos, nYPos, nVal/2);

            maShapes.push_back(new opengl3D::Bar(mpRenderer.get(), aBarPosition, nColor, nId++));
        }

        ++nSeriesIndex;
    }

    nYPos += nBarSizeY + nBarDistanceY;

    // Create category texts along X-axis at the bottom.
    uno::Sequence<OUString> aCats = mrCatProvider.getSimpleCategories();
    for (sal_Int32 i = 0; i < aCats.getLength(); ++i)
    {
        float nXPos = i * (nBarSizeX + nBarDistanceX);

        maShapes.push_back(new opengl3D::Text(mpRenderer.get(), aCats[i], nId++));
        opengl3D::Text* p = static_cast<opengl3D::Text*>(&maShapes.back());
        Size aTextSize = p->getSize();
        glm::vec3 aTopLeft;
        aTopLeft.x = nXPos;
        aTopLeft.y = nYPos;
        glm::vec3 aTopRight = aTopLeft;
        aTopRight.x += aTextSize.getWidth();
        glm::vec3 aBottomRight = aTopRight;
        aBottomRight.y += aTextSize.getHeight();
        p->setPosition(aTopLeft, aTopRight, aBottomRight);
    }

    // Transfer all Y-axis text objects to the shape collection.
    std::copy(aYAxisTexts.begin(), aYAxisTexts.end(), std::back_inserter(maShapes));
    aYAxisTexts.clear();
}

void GL3DBarChart::render()
{
    mrWindow.getContext()->makeCurrent();
    Size aSize = mrWindow.GetSizePixel();
    mpRenderer->SetSize(aSize);
    mrWindow.getContext()->setWinSize(aSize);
    for(boost::ptr_vector<opengl3D::Renderable3DObject>::iterator itr = maShapes.begin(),
            itrEnd = maShapes.end(); itr != itrEnd; ++itr)
    {
        itr->render();
    }
    mrWindow.getContext()->swapBuffers();
}

}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Try without std::back_inserter. Some tinderboxes don't like that.<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

#include <GL3DBarChart.hxx>

#include <GL/glew.h>

#include <glm/glm.hpp>
#include <glm/gtx/transform.hpp>

#include "3DChartObjects.hxx"
#include "GL3DRenderer.hxx"
#include <ExplicitCategoriesProvider.hxx>
#include <DataSeriesHelper.hxx>

using namespace com::sun::star;

namespace chart {

GL3DBarChart::GL3DBarChart(
    const css::uno::Reference<css::chart2::XChartType>& xChartType,
    const boost::ptr_vector<VDataSeries>& rDataSeries,
    OpenGLWindow& rWindow, ExplicitCategoriesProvider& rCatProvider ) :
    mxChartType(xChartType),
    maDataSeries(rDataSeries),
    mpRenderer(new opengl3D::OpenGL3DRenderer()),
    mrWindow(rWindow),
    mrCatProvider(rCatProvider)
{
}

GL3DBarChart::~GL3DBarChart()
{
}

void GL3DBarChart::create3DShapes()
{
    // Each series of data flows from left to right, and multiple series are
    // stacked vertically along y axis.

    // NOTE: These objects are created and positioned in a totally blind
    // fashion since we don't even have a way to see them on screen.  So, no
    // guarantee they are positioned correctly.  In fact, they are guaranteed
    // to be positioned incorrectly.

    const float nBarSizeX = 10;
    const float nBarSizeY = 10;
    const float nBarDistanceX = nBarSizeX / 2;
    const float nBarDistanceY = nBarSizeY / 2;

    sal_uInt32 nId = 1;

    std::vector<opengl3D::Text*> aYAxisTexts;

    float nYPos = 0.0;

    maShapes.clear();
    maShapes.push_back(new opengl3D::Camera(mpRenderer.get()));
    sal_Int32 nSeriesIndex = 0;
    for (boost::ptr_vector<VDataSeries>::const_iterator itr = maDataSeries.begin(),
            itrEnd = maDataSeries.end(); itr != itrEnd; ++itr)
    {
        nYPos = nSeriesIndex * (nBarSizeY + nBarDistanceY);

        const VDataSeries& rDataSeries = *itr;
        sal_Int32 nPointCount = rDataSeries.getTotalPointCount();

        // Create series name text object.
        OUString aSeriesName =
            DataSeriesHelper::getDataSeriesLabel(
                rDataSeries.getModel(), mxChartType->getRoleOfSequenceForSeriesLabel());

        aYAxisTexts.push_back(new opengl3D::Text(mpRenderer.get(), aSeriesName, nId++));
        opengl3D::Text* p = aYAxisTexts.back();
        Size aTextSize = p->getSize();
        glm::vec3 aTopLeft, aTopRight, aBottomRight;
        aTopLeft.x = aTextSize.getWidth() * -1.0;
        aTopLeft.y = nYPos;
        aTopRight.y = nYPos;
        aBottomRight = aTopRight;
        aBottomRight.y += aTextSize.getHeight();
        p->setPosition(aTopLeft, aTopRight, aBottomRight);

        for(sal_Int32 nIndex = 0; nIndex < nPointCount; ++nIndex)
        {
            float nVal = rDataSeries.getYValue(nIndex);
            float nXPos = nIndex * (nBarSizeX + nBarDistanceX);

            sal_Int32 nColor = COL_BLUE;

            glm::mat4 aBarPosition;
            aBarPosition = glm::scale(aBarPosition, nBarSizeX, nBarSizeY, nVal);
            aBarPosition = glm::translate(aBarPosition, nXPos, nYPos, nVal/2);

            maShapes.push_back(new opengl3D::Bar(mpRenderer.get(), aBarPosition, nColor, nId++));
        }

        ++nSeriesIndex;
    }

    nYPos += nBarSizeY + nBarDistanceY;

    // Create category texts along X-axis at the bottom.
    uno::Sequence<OUString> aCats = mrCatProvider.getSimpleCategories();
    for (sal_Int32 i = 0; i < aCats.getLength(); ++i)
    {
        float nXPos = i * (nBarSizeX + nBarDistanceX);

        maShapes.push_back(new opengl3D::Text(mpRenderer.get(), aCats[i], nId++));
        opengl3D::Text* p = static_cast<opengl3D::Text*>(&maShapes.back());
        Size aTextSize = p->getSize();
        glm::vec3 aTopLeft;
        aTopLeft.x = nXPos;
        aTopLeft.y = nYPos;
        glm::vec3 aTopRight = aTopLeft;
        aTopRight.x += aTextSize.getWidth();
        glm::vec3 aBottomRight = aTopRight;
        aBottomRight.y += aTextSize.getHeight();
        p->setPosition(aTopLeft, aTopRight, aBottomRight);
    }

    {
        // Transfer all Y-axis text objects to the shape collection.
        std::vector<opengl3D::Text*>::iterator itText = aYAxisTexts.begin(), itTextEnd = aYAxisTexts.end();
        for (; itText != itTextEnd; ++itText)
            maShapes.push_back(*itText);
    }

    aYAxisTexts.clear();
}

void GL3DBarChart::render()
{
    mrWindow.getContext()->makeCurrent();
    Size aSize = mrWindow.GetSizePixel();
    mpRenderer->SetSize(aSize);
    mrWindow.getContext()->setWinSize(aSize);
    for(boost::ptr_vector<opengl3D::Renderable3DObject>::iterator itr = maShapes.begin(),
            itrEnd = maShapes.end(); itr != itrEnd; ++itr)
    {
        itr->render();
    }
    mrWindow.getContext()->swapBuffers();
}

}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>#include "gtest/gtest.h"
#include <SessionInfo.h>
#include <CryptokiException.h>

using namespace objck;

TEST(SessionInfo_test, constructor) {
	CK_SESSION_INFO info = {
		37,
		CKS_RW_PUBLIC_SESSION,
		CKF_SERIAL_SESSION,
		2
	};

	SessionInfo sInfo(info);

	EXPECT_EQ(sInfo.slotId(), 37);
	EXPECT_EQ(sInfo.state(), CKS_RW_PUBLIC_SESSION);
	EXPECT_EQ(sInfo.flags(), SessionInfo::SessionFlags::SERIAL_SESSION);
	EXPECT_EQ(sInfo.deviceError(), 2);

	CK_SESSION_INFO recoveredInfo = sInfo.getSessionInfo();
	EXPECT_EQ(recoveredInfo.slotID, info.slotID);
	EXPECT_EQ(recoveredInfo.state, info.state);
	EXPECT_EQ(recoveredInfo.flags, info.flags);
	EXPECT_EQ(recoveredInfo.ulDeviceError, info.ulDeviceError);
}
<commit_msg>Testing empty and unknown cases for SessionInfo<commit_after>#include "gtest/gtest.h"
#include <SessionInfo.h>
#include <CryptokiException.h>

using namespace objck;

TEST(SessionInfo_test, constructor) {
	CK_SESSION_INFO info = {
		37,
		CKS_RW_PUBLIC_SESSION,
		CKF_SERIAL_SESSION,
		2
	};

	SessionInfo sInfo(info);

	EXPECT_EQ(sInfo.slotId(), 37);
	EXPECT_EQ(sInfo.state(), CKS_RW_PUBLIC_SESSION);
	EXPECT_EQ(sInfo.flags(), SessionInfo::SessionFlags::SERIAL_SESSION);
	EXPECT_EQ(sInfo.deviceError(), 2);

	CK_SESSION_INFO recoveredInfo = sInfo.getSessionInfo();
	EXPECT_EQ(recoveredInfo.slotID, info.slotID);
	EXPECT_EQ(recoveredInfo.state, info.state);
	EXPECT_EQ(recoveredInfo.flags, info.flags);
	EXPECT_EQ(recoveredInfo.ulDeviceError, info.ulDeviceError);
}

TEST(SessionInfo_test, empty_and_unknown_flags) {
	CK_SESSION_INFO info = { 0, 0, 0, 0 };
	SessionInfo sInfo(info);

	EXPECT_EQ(sInfo.flags(), SessionInfo::SessionFlags::EMPTY);

	info.flags = 8;
	sInfo = SessionInfo(info);
	EXPECT_EQ(sInfo.flags(), SessionInfo::SessionFlags::UNKNOWN);
}
<|endoftext|>


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

#include "chrome/browser/ui/webui/new_profile_handler.h"

#include "base/string_number_conversions.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_info_cache.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/common/url_constants.h"
#include "content/browser/tab_contents/tab_contents.h"

NewProfileHandler::NewProfileHandler() {
}

void NewProfileHandler::RegisterMessages() {
  web_ui_->RegisterMessageCallback("create",
      NewCallback(this, &NewProfileHandler::HandleCreate));
  web_ui_->RegisterMessageCallback("cancel",
      NewCallback(this, &NewProfileHandler::HandleCancel));
  web_ui_->RegisterMessageCallback("requestProfileInfo",
      NewCallback(this, &NewProfileHandler::HandleRequestProfileInfo));
}

void NewProfileHandler::HandleCreate(const ListValue* args) {
  string16 profile_name;
  bool ret = args->GetString(0, &profile_name);
  if (!ret || profile_name.empty())
    return;

  std::string string_index;
  ret = args->GetString(1, &string_index);
  if (!ret || string_index.empty())
    return;
  int profile_avatar_index;
  if (!base::StringToInt(string_index, &profile_avatar_index))
    return;

  ProfileInfoCache& cache =
      g_browser_process->profile_manager()->GetProfileInfoCache();
  size_t index = cache.GetIndexOfProfileWithPath(
      web_ui_->GetProfile()->GetPath());
  if (index != std::string::npos) {
    cache.SetNameOfProfileAtIndex(index, profile_name);
    cache.SetAvatarIconOfProfileAtIndex(index, profile_avatar_index);
  }

  web_ui_->tab_contents()->OpenURL(GURL(chrome::kChromeUINewTabURL),
                                   GURL(), CURRENT_TAB,
                                   PageTransition::LINK);
}

void NewProfileHandler::HandleCancel(const ListValue* args) {
  // TODO(sail): delete this profile.
}

void NewProfileHandler::HandleRequestProfileInfo(const ListValue* args) {
  SendDefaultAvatarImages();
  SendProfileInfo();
}

void NewProfileHandler::SendDefaultAvatarImages() {
  ListValue image_url_list;
  for (size_t i = 0; i < ProfileInfoCache::GetDefaultAvatarIconCount(); i++) {
    std::string url = ProfileInfoCache::GetDefaultAvatarIconUrl(i);
    image_url_list.Append(Value::CreateStringValue(url));
  }
  web_ui_->CallJavascriptFunction("newProfile.setDefaultAvatarImages",
                                  image_url_list);
}

void NewProfileHandler::SendProfileInfo() {
  ProfileInfoCache& cache =
      g_browser_process->profile_manager()->GetProfileInfoCache();
  size_t index = cache.GetIndexOfProfileWithPath(
      web_ui_->GetProfile()->GetPath());
  if (index != std::string::npos) {
    StringValue profile_name(cache.GetNameOfProfileAtIndex(index));
    FundamentalValue profile_icon_index(static_cast<int>(
        cache.GetAvatarIconIndexOfProfileAtIndex(index)));
    web_ui_->CallJavascriptFunction("newProfile.setProfileInfo",
                                    profile_name,
                                    profile_icon_index);
  }
}
<commit_msg>Multi-Profiles: Hook up cancel button in chrome://newprofile<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/webui/new_profile_handler.h"

#include "base/string_number_conversions.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_info_cache.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/common/url_constants.h"
#include "content/browser/tab_contents/tab_contents.h"

NewProfileHandler::NewProfileHandler() {
}

void NewProfileHandler::RegisterMessages() {
  web_ui_->RegisterMessageCallback("create",
      NewCallback(this, &NewProfileHandler::HandleCreate));
  web_ui_->RegisterMessageCallback("cancel",
      NewCallback(this, &NewProfileHandler::HandleCancel));
  web_ui_->RegisterMessageCallback("requestProfileInfo",
      NewCallback(this, &NewProfileHandler::HandleRequestProfileInfo));
}

void NewProfileHandler::HandleCreate(const ListValue* args) {
  string16 profile_name;
  bool ret = args->GetString(0, &profile_name);
  if (!ret || profile_name.empty())
    return;

  std::string string_index;
  ret = args->GetString(1, &string_index);
  if (!ret || string_index.empty())
    return;
  int profile_avatar_index;
  if (!base::StringToInt(string_index, &profile_avatar_index))
    return;

  ProfileInfoCache& cache =
      g_browser_process->profile_manager()->GetProfileInfoCache();
  size_t index = cache.GetIndexOfProfileWithPath(
      web_ui_->GetProfile()->GetPath());
  if (index != std::string::npos) {
    cache.SetNameOfProfileAtIndex(index, profile_name);
    cache.SetAvatarIconOfProfileAtIndex(index, profile_avatar_index);
  }

  web_ui_->tab_contents()->OpenURL(GURL(chrome::kChromeUINewTabURL),
                                   GURL(), CURRENT_TAB,
                                   PageTransition::LINK);
}

void NewProfileHandler::HandleCancel(const ListValue* args) {
  g_browser_process->profile_manager()->ScheduleProfileForDeletion(
      web_ui_->GetProfile()->GetPath());
}

void NewProfileHandler::HandleRequestProfileInfo(const ListValue* args) {
  SendDefaultAvatarImages();
  SendProfileInfo();
}

void NewProfileHandler::SendDefaultAvatarImages() {
  ListValue image_url_list;
  for (size_t i = 0; i < ProfileInfoCache::GetDefaultAvatarIconCount(); i++) {
    std::string url = ProfileInfoCache::GetDefaultAvatarIconUrl(i);
    image_url_list.Append(Value::CreateStringValue(url));
  }
  web_ui_->CallJavascriptFunction("newProfile.setDefaultAvatarImages",
                                  image_url_list);
}

void NewProfileHandler::SendProfileInfo() {
  ProfileInfoCache& cache =
      g_browser_process->profile_manager()->GetProfileInfoCache();
  size_t index = cache.GetIndexOfProfileWithPath(
      web_ui_->GetProfile()->GetPath());
  if (index != std::string::npos) {
    StringValue profile_name(cache.GetNameOfProfileAtIndex(index));
    FundamentalValue profile_icon_index(static_cast<int>(
        cache.GetAvatarIconIndexOfProfileAtIndex(index)));
    web_ui_->CallJavascriptFunction("newProfile.setProfileInfo",
                                    profile_name,
                                    profile_icon_index);
  }
}
<|endoftext|>


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

#include <dwmapi.h>

#include "chrome/browser/views/frame/aero_glass_frame.h"

#include "chrome/app/theme/theme_resources.h"
#include "chrome/browser/frame_util.h"
#include "chrome/browser/views/frame/browser_view2.h"
#include "chrome/browser/views/frame/aero_glass_non_client_view.h"
#include "chrome/common/resource_bundle.h"
#include "chrome/views/window_delegate.h"

// static

// The width of the sizing borders.
static const int kResizeBorder = 8;
// By how much the toolbar overlaps with the tab strip.
static const int kToolbarOverlapVertOffset = 5;
// This is the width of the default client edge provided by Windows. In some
// circumstances we provide our own client edge, so we use this width to
// remove it.
static const int kWindowsDWMBevelSize = 2;

///////////////////////////////////////////////////////////////////////////////
// AeroGlassFrame, public:

AeroGlassFrame::AeroGlassFrame(BrowserView2* browser_view)
    : Window(browser_view),
      browser_view_(browser_view),
      frame_initialized_(false) {
  non_client_view_ = new AeroGlassNonClientView(this, browser_view);
  browser_view_->set_frame(this);
}

AeroGlassFrame::~AeroGlassFrame() {
}

void AeroGlassFrame::Init(const gfx::Rect& bounds) {
  Window::Init(NULL, bounds);
}

int AeroGlassFrame::GetMinimizeButtonOffset() const {
  TITLEBARINFOEX titlebar_info;
  titlebar_info.cbSize = sizeof(TITLEBARINFOEX);
  SendMessage(GetHWND(), WM_GETTITLEBARINFOEX, 0, (WPARAM)&titlebar_info);

  RECT wr;
  GetWindowRect(&wr);

  return wr.right - titlebar_info.rgrect[2].left;
}

///////////////////////////////////////////////////////////////////////////////
// AeroGlassFrame, BrowserFrame implementation:

gfx::Rect AeroGlassFrame::GetWindowBoundsForClientBounds(
    const gfx::Rect& client_bounds) {
  RECT rect = client_bounds.ToRECT();
  AdjustWindowRectEx(&rect, window_style(), FALSE, window_ex_style());
  return gfx::Rect(rect);
}

void AeroGlassFrame::SizeToContents(const gfx::Rect& contents_bounds) {
  // TODO(beng): implement me.
}

gfx::Rect AeroGlassFrame::GetBoundsForTabStrip(TabStrip* tabstrip) const {
  return GetAeroGlassNonClientView()->GetBoundsForTabStrip(tabstrip);
}

ChromeViews::Window* AeroGlassFrame::GetWindow() {
  return this;
}

///////////////////////////////////////////////////////////////////////////////
// AeroGlassFrame, ChromeViews::Window overrides:

void AeroGlassFrame::UpdateWindowIcon() {
  Window::UpdateWindowIcon();
  // TODO(beng): do something in the non-client view when this builds on Vista.
}

///////////////////////////////////////////////////////////////////////////////
// AeroGlassFrame, ChromeViews::HWNDViewContainer implementation:

void AeroGlassFrame::OnInitMenuPopup(HMENU menu, UINT position,
                                     BOOL is_system_menu) {
  browser_view_->PrepareToRunSystemMenu(menu);
}

void AeroGlassFrame::OnEndSession(BOOL ending, UINT logoff) {
  FrameUtil::EndSession();
}

void AeroGlassFrame::OnExitMenuLoop(bool is_track_popup_menu) {
  browser_view_->SystemMenuEnded();
}

LRESULT AeroGlassFrame::OnMouseActivate(HWND window, UINT hittest_code,
                                        UINT message) {
  return browser_view_->ActivateAppModalDialog() ? MA_NOACTIVATEANDEAT
                                                 : MA_ACTIVATE;
}

void AeroGlassFrame::OnMove(const CPoint& point) {
  browser_view_->WindowMoved();
}

void AeroGlassFrame::OnMoving(UINT param, const RECT* new_bounds) {
  browser_view_->WindowMoved();
}

LRESULT AeroGlassFrame::OnNCActivate(BOOL active) {
  if (browser_view_->ActivateAppModalDialog())
    return TRUE;

  if (!frame_initialized_) {
    ::SetWindowPos(GetHWND(), NULL, 0, 0, 0, 0,
                   SWP_NOSIZE | SWP_NOMOVE | SWP_FRAMECHANGED);
    UpdateDWMFrame();
    frame_initialized_ = true;
  }
  browser_view_->ActivationChanged(!!active);
  return TRUE;
}

LRESULT AeroGlassFrame::OnNCCalcSize(BOOL mode, LPARAM l_param) {
  // By default the client side is set to the window size which is what
  // we want.
  if (browser_view_->IsToolbarVisible() && mode == TRUE) {
    // To be on the safe side and avoid side-effects, we only adjust the client
    // size to non-standard values when we must - i.e. when we're showing a
    // TabStrip.
    if (browser_view_->IsTabStripVisible()) {
      // Calculate new NCCALCSIZE_PARAMS based on custom NCA inset.
      NCCALCSIZE_PARAMS* params = reinterpret_cast<NCCALCSIZE_PARAMS*>(l_param);

      // Hack necessary to stop black background flicker, we cut out
      // resizeborder here to save us from having to do too much
      // addition and subtraction in Layout(). We don't cut off the
      // top + titlebar as that prevents the window controls from
      // highlighting.
      params->rgrc[0].left += kResizeBorder;
      params->rgrc[0].right -= kResizeBorder;
      params->rgrc[0].bottom -= kResizeBorder;

      SetMsgHandled(TRUE);
    } else {
      // We don't adjust the client size for detached popups, so we need to
      // tell Windows we didn't handle the message here so that it doesn't
      // screw up the non-client area.
      SetMsgHandled(FALSE);
    }

    // We need to reset the frame, as Vista resets it whenever it changes
    // composition modes (and NCCALCSIZE is the closest thing we get to
    // a reliable message about the change).
    UpdateDWMFrame();

    return 0;
  }
  SetMsgHandled(FALSE);
  return 0;
}

LRESULT AeroGlassFrame::OnNCHitTest(const CPoint& pt) {
  LRESULT result;
  if (DwmDefWindowProc(GetHWND(), WM_NCHITTEST, 0, MAKELPARAM(pt.x, pt.y),
                       &result)) {
    return result;
  }
  return Window::OnNCHitTest(pt);
}

///////////////////////////////////////////////////////////////////////////////
// AeroGlassFrame, ChromeViews::HWNDViewContainer overrides:

bool AeroGlassFrame::AcceleratorPressed(
    ChromeViews::Accelerator* accelerator) {
  return browser_view_->AcceleratorPressed(*accelerator);
}

bool AeroGlassFrame::GetAccelerator(int cmd_id,
                                    ChromeViews::Accelerator* accelerator) {
  return browser_view_->GetAccelerator(cmd_id, accelerator);
}

///////////////////////////////////////////////////////////////////////////////
// AeroGlassFrame, private:

void AeroGlassFrame::UpdateDWMFrame() {
  // Nothing to do yet.
  if (!client_view())
    return;

  // TODO(beng): when TabStrip is hooked up, obtain this offset from its
  //             bounds.
  int toolbar_y = 36;

  // We only adjust the DWM's glass rendering when we're a browser window or a
  // detached popup. App windows get the standard client edge.
  if (browser_view_->IsTabStripVisible() ||
      browser_view_->IsToolbarVisible()) {
    // By default, we just want to adjust the glass by the width of the inner
    // bevel that aero renders to demarcate the client area. We supply our own
    // client edge for the browser window and detached popups, so we don't want
    // to show the default one.
    int client_edge_left_width = kWindowsDWMBevelSize;
    int client_edge_right_width = kWindowsDWMBevelSize;
    int client_edge_bottom_height = kWindowsDWMBevelSize;
    int client_edge_top_height = kWindowsDWMBevelSize;
    if (browser_view_->IsTabStripVisible()) {
      client_edge_top_height =
          client_view()->GetY() + kToolbarOverlapVertOffset + toolbar_y;
    }

    // Now poke the DWM.
    MARGINS margins = { client_edge_left_width, client_edge_right_width,
                        client_edge_top_height, client_edge_bottom_height };
    // Note: we don't use DwmEnableBlurBehindWindow because any region not
    // included in the glass region is composited source over. This means
    // that anything drawn directly with GDI appears fully transparent.
    DwmExtendFrameIntoClientArea(GetHWND(), &margins);
  }
}

AeroGlassNonClientView* AeroGlassFrame::GetAeroGlassNonClientView() const {
  // We can safely assume that this conversion is true.
  return static_cast<AeroGlassNonClientView*>(non_client_view_);
}

<commit_msg>Fix the include order in aero_glass_frame.cc. This was causing issues with WPO enabled. Review URL: http://codereview.chromium.org/430<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/views/frame/aero_glass_frame.h"

#include <dwmapi.h>

#include "chrome/app/theme/theme_resources.h"
#include "chrome/browser/frame_util.h"
#include "chrome/browser/views/frame/browser_view2.h"
#include "chrome/browser/views/frame/aero_glass_non_client_view.h"
#include "chrome/common/resource_bundle.h"
#include "chrome/views/window_delegate.h"

// static

// The width of the sizing borders.
static const int kResizeBorder = 8;
// By how much the toolbar overlaps with the tab strip.
static const int kToolbarOverlapVertOffset = 5;
// This is the width of the default client edge provided by Windows. In some
// circumstances we provide our own client edge, so we use this width to
// remove it.
static const int kWindowsDWMBevelSize = 2;

///////////////////////////////////////////////////////////////////////////////
// AeroGlassFrame, public:

AeroGlassFrame::AeroGlassFrame(BrowserView2* browser_view)
    : Window(browser_view),
      browser_view_(browser_view),
      frame_initialized_(false) {
  non_client_view_ = new AeroGlassNonClientView(this, browser_view);
  browser_view_->set_frame(this);
}

AeroGlassFrame::~AeroGlassFrame() {
}

void AeroGlassFrame::Init(const gfx::Rect& bounds) {
  Window::Init(NULL, bounds);
}

int AeroGlassFrame::GetMinimizeButtonOffset() const {
  TITLEBARINFOEX titlebar_info;
  titlebar_info.cbSize = sizeof(TITLEBARINFOEX);
  SendMessage(GetHWND(), WM_GETTITLEBARINFOEX, 0, (WPARAM)&titlebar_info);

  RECT wr;
  GetWindowRect(&wr);

  return wr.right - titlebar_info.rgrect[2].left;
}

///////////////////////////////////////////////////////////////////////////////
// AeroGlassFrame, BrowserFrame implementation:

gfx::Rect AeroGlassFrame::GetWindowBoundsForClientBounds(
    const gfx::Rect& client_bounds) {
  RECT rect = client_bounds.ToRECT();
  AdjustWindowRectEx(&rect, window_style(), FALSE, window_ex_style());
  return gfx::Rect(rect);
}

void AeroGlassFrame::SizeToContents(const gfx::Rect& contents_bounds) {
  // TODO(beng): implement me.
}

gfx::Rect AeroGlassFrame::GetBoundsForTabStrip(TabStrip* tabstrip) const {
  return GetAeroGlassNonClientView()->GetBoundsForTabStrip(tabstrip);
}

ChromeViews::Window* AeroGlassFrame::GetWindow() {
  return this;
}

///////////////////////////////////////////////////////////////////////////////
// AeroGlassFrame, ChromeViews::Window overrides:

void AeroGlassFrame::UpdateWindowIcon() {
  Window::UpdateWindowIcon();
  // TODO(beng): do something in the non-client view when this builds on Vista.
}

///////////////////////////////////////////////////////////////////////////////
// AeroGlassFrame, ChromeViews::HWNDViewContainer implementation:

void AeroGlassFrame::OnInitMenuPopup(HMENU menu, UINT position,
                                     BOOL is_system_menu) {
  browser_view_->PrepareToRunSystemMenu(menu);
}

void AeroGlassFrame::OnEndSession(BOOL ending, UINT logoff) {
  FrameUtil::EndSession();
}

void AeroGlassFrame::OnExitMenuLoop(bool is_track_popup_menu) {
  browser_view_->SystemMenuEnded();
}

LRESULT AeroGlassFrame::OnMouseActivate(HWND window, UINT hittest_code,
                                        UINT message) {
  return browser_view_->ActivateAppModalDialog() ? MA_NOACTIVATEANDEAT
                                                 : MA_ACTIVATE;
}

void AeroGlassFrame::OnMove(const CPoint& point) {
  browser_view_->WindowMoved();
}

void AeroGlassFrame::OnMoving(UINT param, const RECT* new_bounds) {
  browser_view_->WindowMoved();
}

LRESULT AeroGlassFrame::OnNCActivate(BOOL active) {
  if (browser_view_->ActivateAppModalDialog())
    return TRUE;

  if (!frame_initialized_) {
    ::SetWindowPos(GetHWND(), NULL, 0, 0, 0, 0,
                   SWP_NOSIZE | SWP_NOMOVE | SWP_FRAMECHANGED);
    UpdateDWMFrame();
    frame_initialized_ = true;
  }
  browser_view_->ActivationChanged(!!active);
  return TRUE;
}

LRESULT AeroGlassFrame::OnNCCalcSize(BOOL mode, LPARAM l_param) {
  // By default the client side is set to the window size which is what
  // we want.
  if (browser_view_->IsToolbarVisible() && mode == TRUE) {
    // To be on the safe side and avoid side-effects, we only adjust the client
    // size to non-standard values when we must - i.e. when we're showing a
    // TabStrip.
    if (browser_view_->IsTabStripVisible()) {
      // Calculate new NCCALCSIZE_PARAMS based on custom NCA inset.
      NCCALCSIZE_PARAMS* params = reinterpret_cast<NCCALCSIZE_PARAMS*>(l_param);

      // Hack necessary to stop black background flicker, we cut out
      // resizeborder here to save us from having to do too much
      // addition and subtraction in Layout(). We don't cut off the
      // top + titlebar as that prevents the window controls from
      // highlighting.
      params->rgrc[0].left += kResizeBorder;
      params->rgrc[0].right -= kResizeBorder;
      params->rgrc[0].bottom -= kResizeBorder;

      SetMsgHandled(TRUE);
    } else {
      // We don't adjust the client size for detached popups, so we need to
      // tell Windows we didn't handle the message here so that it doesn't
      // screw up the non-client area.
      SetMsgHandled(FALSE);
    }

    // We need to reset the frame, as Vista resets it whenever it changes
    // composition modes (and NCCALCSIZE is the closest thing we get to
    // a reliable message about the change).
    UpdateDWMFrame();

    return 0;
  }
  SetMsgHandled(FALSE);
  return 0;
}

LRESULT AeroGlassFrame::OnNCHitTest(const CPoint& pt) {
  LRESULT result;
  if (DwmDefWindowProc(GetHWND(), WM_NCHITTEST, 0, MAKELPARAM(pt.x, pt.y),
                       &result)) {
    return result;
  }
  return Window::OnNCHitTest(pt);
}

///////////////////////////////////////////////////////////////////////////////
// AeroGlassFrame, ChromeViews::HWNDViewContainer overrides:

bool AeroGlassFrame::AcceleratorPressed(
    ChromeViews::Accelerator* accelerator) {
  return browser_view_->AcceleratorPressed(*accelerator);
}

bool AeroGlassFrame::GetAccelerator(int cmd_id,
                                    ChromeViews::Accelerator* accelerator) {
  return browser_view_->GetAccelerator(cmd_id, accelerator);
}

///////////////////////////////////////////////////////////////////////////////
// AeroGlassFrame, private:

void AeroGlassFrame::UpdateDWMFrame() {
  // Nothing to do yet.
  if (!client_view())
    return;

  // TODO(beng): when TabStrip is hooked up, obtain this offset from its
  //             bounds.
  int toolbar_y = 36;

  // We only adjust the DWM's glass rendering when we're a browser window or a
  // detached popup. App windows get the standard client edge.
  if (browser_view_->IsTabStripVisible() ||
      browser_view_->IsToolbarVisible()) {
    // By default, we just want to adjust the glass by the width of the inner
    // bevel that aero renders to demarcate the client area. We supply our own
    // client edge for the browser window and detached popups, so we don't want
    // to show the default one.
    int client_edge_left_width = kWindowsDWMBevelSize;
    int client_edge_right_width = kWindowsDWMBevelSize;
    int client_edge_bottom_height = kWindowsDWMBevelSize;
    int client_edge_top_height = kWindowsDWMBevelSize;
    if (browser_view_->IsTabStripVisible()) {
      client_edge_top_height =
          client_view()->GetY() + kToolbarOverlapVertOffset + toolbar_y;
    }

    // Now poke the DWM.
    MARGINS margins = { client_edge_left_width, client_edge_right_width,
                        client_edge_top_height, client_edge_bottom_height };
    // Note: we don't use DwmEnableBlurBehindWindow because any region not
    // included in the glass region is composited source over. This means
    // that anything drawn directly with GDI appears fully transparent.
    DwmExtendFrameIntoClientArea(GetHWND(), &margins);
  }
}

AeroGlassNonClientView* AeroGlassFrame::GetAeroGlassNonClientView() const {
  // We can safely assume that this conversion is true.
  return static_cast<AeroGlassNonClientView*>(non_client_view_);
}

<|endoftext|>


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

#include "chrome/renderer/pepper_plugin_delegate_impl.h"

#include "app/surface/transport_dib.h"
#include "base/logging.h"
#include "base/scoped_ptr.h"
#include "chrome/common/render_messages.h"
#include "chrome/renderer/audio_message_filter.h"
#include "chrome/renderer/render_view.h"
#include "third_party/WebKit/WebKit/chromium/public/WebFileChooserCompletion.h"
#include "third_party/WebKit/WebKit/chromium/public/WebFileChooserParams.h"
#include "webkit/glue/plugins/pepper_plugin_instance.h"

#if defined(OS_MACOSX)
#include "chrome/common/render_messages.h"
#include "chrome/renderer/render_thread.h"
#endif

namespace {

// Implements the Image2D using a TransportDIB.
class PlatformImage2DImpl : public pepper::PluginDelegate::PlatformImage2D {
 public:
  // This constructor will take ownership of the dib pointer.
  PlatformImage2DImpl(int width, int height, TransportDIB* dib)
      : width_(width),
        height_(height),
        dib_(dib) {
  }

  virtual skia::PlatformCanvas* Map() {
    return dib_->GetPlatformCanvas(width_, height_);
  }

  virtual intptr_t GetSharedMemoryHandle() const {
    return reinterpret_cast<intptr_t>(dib_.get());
  }

 private:
  int width_;
  int height_;
  scoped_ptr<TransportDIB> dib_;

  DISALLOW_COPY_AND_ASSIGN(PlatformImage2DImpl);
};

class PlatformAudioImpl
    : public pepper::PluginDelegate::PlatformAudio,
      public AudioMessageFilter::Delegate {
 public:
  explicit PlatformAudioImpl(scoped_refptr<AudioMessageFilter> filter)
      : client_(NULL), filter_(filter), stream_id_(0) {
    DCHECK(filter_);
  }

  virtual ~PlatformAudioImpl() {
    // Make sure we have been shut down.
    DCHECK_EQ(0, stream_id_);
    DCHECK(!client_);
  }

  // Initialize this audio context. StreamCreated() will be called when the
  // stream is created.
  bool Initialize(uint32_t sample_rate, uint32_t sample_count,
       pepper::PluginDelegate::PlatformAudio::Client* client);

  virtual bool StartPlayback() {
    return filter_ && filter_->Send(
        new ViewHostMsg_PlayAudioStream(0, stream_id_));
  }

  virtual bool StopPlayback() {
    return filter_ && filter_->Send(
        new ViewHostMsg_PauseAudioStream(0, stream_id_));
  }

  virtual void ShutDown();

 private:
  virtual void OnRequestPacket(uint32 bytes_in_buffer,
                               const base::Time& message_timestamp) {
    LOG(FATAL) << "Should never get OnRequestPacket in PlatformAudioImpl";
  }

  virtual void OnStateChanged(const ViewMsg_AudioStreamState_Params& state) { }

  virtual void OnCreated(base::SharedMemoryHandle handle, uint32 length) {
    LOG(FATAL) << "Should never get OnCreated in PlatformAudioImpl";
  }

  virtual void OnLowLatencyCreated(base::SharedMemoryHandle handle,
                                   base::SyncSocket::Handle socket_handle,
                                   uint32 length);

  virtual void OnVolume(double volume) { }

  // The client to notify when the stream is created.
  pepper::PluginDelegate::PlatformAudio::Client* client_;
  // MessageFilter used to send/receive IPC.
  scoped_refptr<AudioMessageFilter> filter_;
  // Our ID on the MessageFilter.
  int32 stream_id_;

  DISALLOW_COPY_AND_ASSIGN(PlatformAudioImpl);
};

bool PlatformAudioImpl::Initialize(
    uint32_t sample_rate, uint32_t sample_count,
    pepper::PluginDelegate::PlatformAudio::Client* client) {

  DCHECK(client);
  // Make sure we don't call init more than once.
  DCHECK_EQ(0, stream_id_);

  client_ = client;

  ViewHostMsg_Audio_CreateStream_Params params;
  params.format = AudioManager::AUDIO_PCM_LINEAR;
  params.channels = 2;
  params.sample_rate = sample_rate;
  params.bits_per_sample = 16;

  params.packet_size = sample_count * params.channels *
      (params.bits_per_sample >> 3);

  stream_id_ = filter_->AddDelegate(this);
  return filter_->Send(new ViewHostMsg_CreateAudioStream(0, stream_id_, params,
                                                         true));
}

void PlatformAudioImpl::OnLowLatencyCreated(
    base::SharedMemoryHandle handle, base::SyncSocket::Handle socket_handle,
    uint32 length) {
#if defined(OS_WIN)
  DCHECK(handle);
  DCHECK(socket_handle);
#else
  DCHECK_NE(-1, handle.fd);
  DCHECK_NE(-1, socket_handle);
#endif
  DCHECK(length);

  client_->StreamCreated(handle, length, socket_handle);
}

void PlatformAudioImpl::ShutDown() {
  // Make sure we don't call shutdown more than once.
  if (!stream_id_) {
    return;
  }
  filter_->Send(new ViewHostMsg_CloseAudioStream(0, stream_id_));
  filter_->RemoveDelegate(stream_id_);
  stream_id_ = 0;
  client_ = NULL;
}

// Implements the VideoDecoder.
class PlatformVideoDecoderImpl
    : public pepper::PluginDelegate::PlatformVideoDecoder {
 public:
  PlatformVideoDecoderImpl()
      : input_buffer_size_(0),
        next_dib_id_(0),
        dib_(NULL) {
    memset(&flush_callback_, 0, sizeof(flush_callback_));
  }

  virtual bool Init(const PP_VideoDecoderConfig& decoder_config) {
    decoder_config_ = decoder_config;
    input_buffer_size_ = 1024 << 4;

    // Allocate the transport DIB.
    TransportDIB* dib = TransportDIB::Create(input_buffer_size_,
                                             next_dib_id_++);
    if (!dib)
      return false;

    // TODO(wjia): Create video decoder in GPU process.

    return true;
  }

  virtual bool Decode(PP_VideoCompressedDataBuffer& input_buffer) {
    // TODO(wjia): Implement me!
    NOTIMPLEMENTED();

    input_buffers_.push(&input_buffer);

    // Copy input data to dib_ and send it to GPU video decoder.

    return false;
  }

  virtual int32_t Flush(PP_CompletionCallback& callback) {
    // TODO(wjia): Implement me!
    NOTIMPLEMENTED();

    // Do nothing if there is a flush pending.
    if (flush_callback_.func)
      return PP_ERROR_BADARGUMENT;

    flush_callback_ = callback;

    // Call GPU video decoder to flush.

    return PP_ERROR_WOULDBLOCK;
  }

  virtual bool ReturnUncompressedDataBuffer(
      PP_VideoUncompressedDataBuffer& buffer) {
    // TODO(wjia): Implement me!
    NOTIMPLEMENTED();

    // Deliver the buffer to GPU video decoder.

    return false;
  }

  void OnFlushDone() {
    if (!flush_callback_.func)
      return;

    flush_callback_.func(flush_callback_.user_data, PP_OK);
    flush_callback_.func = NULL;
  }

  virtual intptr_t GetSharedMemoryHandle() const {
    return reinterpret_cast<intptr_t>(dib_.get());
  }

 private:
  size_t input_buffer_size_;
  int next_dib_id_;
  scoped_ptr<TransportDIB> dib_;
  PP_VideoDecoderConfig decoder_config_;
  std::queue<PP_VideoCompressedDataBuffer*> input_buffers_;
  PP_CompletionCallback flush_callback_;

  DISALLOW_COPY_AND_ASSIGN(PlatformVideoDecoderImpl);
};

}  // namespace

PepperPluginDelegateImpl::PepperPluginDelegateImpl(RenderView* render_view)
    : render_view_(render_view) {
}

void PepperPluginDelegateImpl::ViewInitiatedPaint() {
  // Notify all of our instances that we started painting. This is used for
  // internal bookkeeping only, so we know that the set can not change under
  // us.
  for (std::set<pepper::PluginInstance*>::iterator i =
           active_instances_.begin();
       i != active_instances_.end(); ++i)
    (*i)->ViewInitiatedPaint();
}

void PepperPluginDelegateImpl::ViewFlushedPaint() {
  // Notify all instances that we painted. This will call into the plugin, and
  // we it may ask to close itself as a result. This will, in turn, modify our
  // set, possibly invalidating the iterator. So we iterate on a copy that
  // won't change out from under us.
  std::set<pepper::PluginInstance*> plugins = active_instances_;
  for (std::set<pepper::PluginInstance*>::iterator i = plugins.begin();
       i != plugins.end(); ++i) {
    // The copy above makes sure our iterator is never invalid if some plugins
    // are destroyed. But some plugin may decide to close all of its views in
    // response to a paint in one of them, so we need to make sure each one is
    // still "current" before using it.
    //
    // It's possible that a plugin was destroyed, but another one was created
    // with the same address. In this case, we'll call ViewFlushedPaint on that
    // new plugin. But that's OK for this particular case since we're just
    // notifying all of our instances that the view flushed, and the new one is
    // one of our instances.
    //
    // What about the case where a new one is created in a callback at a new
    // address and we don't issue the callback? We're still OK since this
    // callback is used for flush callbacks and we could not have possibly
    // started a new paint (ViewInitiatedPaint) for the new plugin while
    // processing a previous paint for an existing one.
    if (active_instances_.find(*i) != active_instances_.end())
      (*i)->ViewFlushedPaint();
  }
}

void PepperPluginDelegateImpl::InstanceCreated(
    pepper::PluginInstance* instance) {
  active_instances_.insert(instance);
}

void PepperPluginDelegateImpl::InstanceDeleted(
    pepper::PluginInstance* instance) {
  active_instances_.erase(instance);
}

pepper::PluginDelegate::PlatformImage2D*
PepperPluginDelegateImpl::CreateImage2D(int width, int height) {
  uint32 buffer_size = width * height * 4;

  // Allocate the transport DIB and the PlatformCanvas pointing to it.
#if defined(OS_MACOSX)
  // On the Mac, shared memory has to be created in the browser in order to
  // work in the sandbox.  Do this by sending a message to the browser
  // requesting a TransportDIB (see also
  // chrome/renderer/webplugin_delegate_proxy.cc, method
  // WebPluginDelegateProxy::CreateBitmap() for similar code).  Note that the
  // TransportDIB is _not_ cached in the browser; this is because this memory
  // gets flushed by the renderer into another TransportDIB that represents the
  // page, which is then in turn flushed to the screen by the browser process.
  // When |transport_dib_| goes out of scope in the dtor, all of its shared
  // memory gets reclaimed.
  TransportDIB::Handle dib_handle;
  IPC::Message* msg = new ViewHostMsg_AllocTransportDIB(buffer_size,
                                                        false,
                                                        &dib_handle);
  if (!RenderThread::current()->Send(msg))
    return NULL;
  if (!TransportDIB::is_valid(dib_handle))
    return NULL;

  TransportDIB* dib = TransportDIB::Map(dib_handle);
#else
  static int next_dib_id = 0;
  TransportDIB* dib = TransportDIB::Create(buffer_size, next_dib_id++);
  if (!dib)
    return NULL;
#endif

  return new PlatformImage2DImpl(width, height, dib);
}

pepper::PluginDelegate::PlatformVideoDecoder*
PepperPluginDelegateImpl::CreateVideoDecoder(
    const PP_VideoDecoderConfig& decoder_config) {
  scoped_ptr<PlatformVideoDecoderImpl> decoder(new PlatformVideoDecoderImpl());

  if (!decoder->Init(decoder_config))
    return NULL;

  return decoder.release();
}

void PepperPluginDelegateImpl::DidChangeNumberOfFindResults(int identifier,
                                                           int total,
                                                           bool final_result) {
  if (total == 0) {
    render_view_->ReportNoFindInPageResults(identifier);
  } else {
    render_view_->reportFindInPageMatchCount(identifier, total, final_result);
  }
}

void PepperPluginDelegateImpl::DidChangeSelectedFindResult(int identifier,
                                                          int index) {
  render_view_->reportFindInPageSelection(
      identifier, index + 1, WebKit::WebRect());
}

pepper::PluginDelegate::PlatformAudio* PepperPluginDelegateImpl::CreateAudio(
    uint32_t sample_rate, uint32_t sample_count,
    pepper::PluginDelegate::PlatformAudio::Client* client) {
  scoped_ptr<PlatformAudioImpl> audio(
      new PlatformAudioImpl(render_view_->audio_message_filter()));
  if (audio->Initialize(sample_rate, sample_count, client)) {
    return audio.release();
  } else {
    return NULL;
  }
}

bool PepperPluginDelegateImpl::RunFileChooser(
    const WebKit::WebFileChooserParams& params,
    WebKit::WebFileChooserCompletion* chooser_completion) {
  return render_view_->runFileChooser(params, chooser_completion);
}
<commit_msg>Initialize member struct in Pepper plugin.<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/renderer/pepper_plugin_delegate_impl.h"

#include "app/surface/transport_dib.h"
#include "base/logging.h"
#include "base/scoped_ptr.h"
#include "chrome/common/render_messages.h"
#include "chrome/renderer/audio_message_filter.h"
#include "chrome/renderer/render_view.h"
#include "third_party/WebKit/WebKit/chromium/public/WebFileChooserCompletion.h"
#include "third_party/WebKit/WebKit/chromium/public/WebFileChooserParams.h"
#include "webkit/glue/plugins/pepper_plugin_instance.h"

#if defined(OS_MACOSX)
#include "chrome/common/render_messages.h"
#include "chrome/renderer/render_thread.h"
#endif

namespace {

// Implements the Image2D using a TransportDIB.
class PlatformImage2DImpl : public pepper::PluginDelegate::PlatformImage2D {
 public:
  // This constructor will take ownership of the dib pointer.
  PlatformImage2DImpl(int width, int height, TransportDIB* dib)
      : width_(width),
        height_(height),
        dib_(dib) {
  }

  virtual skia::PlatformCanvas* Map() {
    return dib_->GetPlatformCanvas(width_, height_);
  }

  virtual intptr_t GetSharedMemoryHandle() const {
    return reinterpret_cast<intptr_t>(dib_.get());
  }

 private:
  int width_;
  int height_;
  scoped_ptr<TransportDIB> dib_;

  DISALLOW_COPY_AND_ASSIGN(PlatformImage2DImpl);
};

class PlatformAudioImpl
    : public pepper::PluginDelegate::PlatformAudio,
      public AudioMessageFilter::Delegate {
 public:
  explicit PlatformAudioImpl(scoped_refptr<AudioMessageFilter> filter)
      : client_(NULL), filter_(filter), stream_id_(0) {
    DCHECK(filter_);
  }

  virtual ~PlatformAudioImpl() {
    // Make sure we have been shut down.
    DCHECK_EQ(0, stream_id_);
    DCHECK(!client_);
  }

  // Initialize this audio context. StreamCreated() will be called when the
  // stream is created.
  bool Initialize(uint32_t sample_rate, uint32_t sample_count,
       pepper::PluginDelegate::PlatformAudio::Client* client);

  virtual bool StartPlayback() {
    return filter_ && filter_->Send(
        new ViewHostMsg_PlayAudioStream(0, stream_id_));
  }

  virtual bool StopPlayback() {
    return filter_ && filter_->Send(
        new ViewHostMsg_PauseAudioStream(0, stream_id_));
  }

  virtual void ShutDown();

 private:
  virtual void OnRequestPacket(uint32 bytes_in_buffer,
                               const base::Time& message_timestamp) {
    LOG(FATAL) << "Should never get OnRequestPacket in PlatformAudioImpl";
  }

  virtual void OnStateChanged(const ViewMsg_AudioStreamState_Params& state) { }

  virtual void OnCreated(base::SharedMemoryHandle handle, uint32 length) {
    LOG(FATAL) << "Should never get OnCreated in PlatformAudioImpl";
  }

  virtual void OnLowLatencyCreated(base::SharedMemoryHandle handle,
                                   base::SyncSocket::Handle socket_handle,
                                   uint32 length);

  virtual void OnVolume(double volume) { }

  // The client to notify when the stream is created.
  pepper::PluginDelegate::PlatformAudio::Client* client_;
  // MessageFilter used to send/receive IPC.
  scoped_refptr<AudioMessageFilter> filter_;
  // Our ID on the MessageFilter.
  int32 stream_id_;

  DISALLOW_COPY_AND_ASSIGN(PlatformAudioImpl);
};

bool PlatformAudioImpl::Initialize(
    uint32_t sample_rate, uint32_t sample_count,
    pepper::PluginDelegate::PlatformAudio::Client* client) {

  DCHECK(client);
  // Make sure we don't call init more than once.
  DCHECK_EQ(0, stream_id_);

  client_ = client;

  ViewHostMsg_Audio_CreateStream_Params params;
  params.format = AudioManager::AUDIO_PCM_LINEAR;
  params.channels = 2;
  params.sample_rate = sample_rate;
  params.bits_per_sample = 16;

  params.packet_size = sample_count * params.channels *
      (params.bits_per_sample >> 3);

  stream_id_ = filter_->AddDelegate(this);
  return filter_->Send(new ViewHostMsg_CreateAudioStream(0, stream_id_, params,
                                                         true));
}

void PlatformAudioImpl::OnLowLatencyCreated(
    base::SharedMemoryHandle handle, base::SyncSocket::Handle socket_handle,
    uint32 length) {
#if defined(OS_WIN)
  DCHECK(handle);
  DCHECK(socket_handle);
#else
  DCHECK_NE(-1, handle.fd);
  DCHECK_NE(-1, socket_handle);
#endif
  DCHECK(length);

  client_->StreamCreated(handle, length, socket_handle);
}

void PlatformAudioImpl::ShutDown() {
  // Make sure we don't call shutdown more than once.
  if (!stream_id_) {
    return;
  }
  filter_->Send(new ViewHostMsg_CloseAudioStream(0, stream_id_));
  filter_->RemoveDelegate(stream_id_);
  stream_id_ = 0;
  client_ = NULL;
}

// Implements the VideoDecoder.
class PlatformVideoDecoderImpl
    : public pepper::PluginDelegate::PlatformVideoDecoder {
 public:
  PlatformVideoDecoderImpl()
      : input_buffer_size_(0),
        next_dib_id_(0),
        dib_(NULL) {
    memset(&decoder_config_, 0, sizeof(decoder_config_));
    memset(&flush_callback_, 0, sizeof(flush_callback_));
  }

  virtual bool Init(const PP_VideoDecoderConfig& decoder_config) {
    decoder_config_ = decoder_config;
    input_buffer_size_ = 1024 << 4;

    // Allocate the transport DIB.
    TransportDIB* dib = TransportDIB::Create(input_buffer_size_,
                                             next_dib_id_++);
    if (!dib)
      return false;

    // TODO(wjia): Create video decoder in GPU process.

    return true;
  }

  virtual bool Decode(PP_VideoCompressedDataBuffer& input_buffer) {
    // TODO(wjia): Implement me!
    NOTIMPLEMENTED();

    input_buffers_.push(&input_buffer);

    // Copy input data to dib_ and send it to GPU video decoder.

    return false;
  }

  virtual int32_t Flush(PP_CompletionCallback& callback) {
    // TODO(wjia): Implement me!
    NOTIMPLEMENTED();

    // Do nothing if there is a flush pending.
    if (flush_callback_.func)
      return PP_ERROR_BADARGUMENT;

    flush_callback_ = callback;

    // Call GPU video decoder to flush.

    return PP_ERROR_WOULDBLOCK;
  }

  virtual bool ReturnUncompressedDataBuffer(
      PP_VideoUncompressedDataBuffer& buffer) {
    // TODO(wjia): Implement me!
    NOTIMPLEMENTED();

    // Deliver the buffer to GPU video decoder.

    return false;
  }

  void OnFlushDone() {
    if (!flush_callback_.func)
      return;

    flush_callback_.func(flush_callback_.user_data, PP_OK);
    flush_callback_.func = NULL;
  }

  virtual intptr_t GetSharedMemoryHandle() const {
    return reinterpret_cast<intptr_t>(dib_.get());
  }

 private:
  size_t input_buffer_size_;
  int next_dib_id_;
  scoped_ptr<TransportDIB> dib_;
  PP_VideoDecoderConfig decoder_config_;
  std::queue<PP_VideoCompressedDataBuffer*> input_buffers_;
  PP_CompletionCallback flush_callback_;

  DISALLOW_COPY_AND_ASSIGN(PlatformVideoDecoderImpl);
};

}  // namespace

PepperPluginDelegateImpl::PepperPluginDelegateImpl(RenderView* render_view)
    : render_view_(render_view) {
}

void PepperPluginDelegateImpl::ViewInitiatedPaint() {
  // Notify all of our instances that we started painting. This is used for
  // internal bookkeeping only, so we know that the set can not change under
  // us.
  for (std::set<pepper::PluginInstance*>::iterator i =
           active_instances_.begin();
       i != active_instances_.end(); ++i)
    (*i)->ViewInitiatedPaint();
}

void PepperPluginDelegateImpl::ViewFlushedPaint() {
  // Notify all instances that we painted. This will call into the plugin, and
  // we it may ask to close itself as a result. This will, in turn, modify our
  // set, possibly invalidating the iterator. So we iterate on a copy that
  // won't change out from under us.
  std::set<pepper::PluginInstance*> plugins = active_instances_;
  for (std::set<pepper::PluginInstance*>::iterator i = plugins.begin();
       i != plugins.end(); ++i) {
    // The copy above makes sure our iterator is never invalid if some plugins
    // are destroyed. But some plugin may decide to close all of its views in
    // response to a paint in one of them, so we need to make sure each one is
    // still "current" before using it.
    //
    // It's possible that a plugin was destroyed, but another one was created
    // with the same address. In this case, we'll call ViewFlushedPaint on that
    // new plugin. But that's OK for this particular case since we're just
    // notifying all of our instances that the view flushed, and the new one is
    // one of our instances.
    //
    // What about the case where a new one is created in a callback at a new
    // address and we don't issue the callback? We're still OK since this
    // callback is used for flush callbacks and we could not have possibly
    // started a new paint (ViewInitiatedPaint) for the new plugin while
    // processing a previous paint for an existing one.
    if (active_instances_.find(*i) != active_instances_.end())
      (*i)->ViewFlushedPaint();
  }
}

void PepperPluginDelegateImpl::InstanceCreated(
    pepper::PluginInstance* instance) {
  active_instances_.insert(instance);
}

void PepperPluginDelegateImpl::InstanceDeleted(
    pepper::PluginInstance* instance) {
  active_instances_.erase(instance);
}

pepper::PluginDelegate::PlatformImage2D*
PepperPluginDelegateImpl::CreateImage2D(int width, int height) {
  uint32 buffer_size = width * height * 4;

  // Allocate the transport DIB and the PlatformCanvas pointing to it.
#if defined(OS_MACOSX)
  // On the Mac, shared memory has to be created in the browser in order to
  // work in the sandbox.  Do this by sending a message to the browser
  // requesting a TransportDIB (see also
  // chrome/renderer/webplugin_delegate_proxy.cc, method
  // WebPluginDelegateProxy::CreateBitmap() for similar code).  Note that the
  // TransportDIB is _not_ cached in the browser; this is because this memory
  // gets flushed by the renderer into another TransportDIB that represents the
  // page, which is then in turn flushed to the screen by the browser process.
  // When |transport_dib_| goes out of scope in the dtor, all of its shared
  // memory gets reclaimed.
  TransportDIB::Handle dib_handle;
  IPC::Message* msg = new ViewHostMsg_AllocTransportDIB(buffer_size,
                                                        false,
                                                        &dib_handle);
  if (!RenderThread::current()->Send(msg))
    return NULL;
  if (!TransportDIB::is_valid(dib_handle))
    return NULL;

  TransportDIB* dib = TransportDIB::Map(dib_handle);
#else
  static int next_dib_id = 0;
  TransportDIB* dib = TransportDIB::Create(buffer_size, next_dib_id++);
  if (!dib)
    return NULL;
#endif

  return new PlatformImage2DImpl(width, height, dib);
}

pepper::PluginDelegate::PlatformVideoDecoder*
PepperPluginDelegateImpl::CreateVideoDecoder(
    const PP_VideoDecoderConfig& decoder_config) {
  scoped_ptr<PlatformVideoDecoderImpl> decoder(new PlatformVideoDecoderImpl());

  if (!decoder->Init(decoder_config))
    return NULL;

  return decoder.release();
}

void PepperPluginDelegateImpl::DidChangeNumberOfFindResults(int identifier,
                                                           int total,
                                                           bool final_result) {
  if (total == 0) {
    render_view_->ReportNoFindInPageResults(identifier);
  } else {
    render_view_->reportFindInPageMatchCount(identifier, total, final_result);
  }
}

void PepperPluginDelegateImpl::DidChangeSelectedFindResult(int identifier,
                                                          int index) {
  render_view_->reportFindInPageSelection(
      identifier, index + 1, WebKit::WebRect());
}

pepper::PluginDelegate::PlatformAudio* PepperPluginDelegateImpl::CreateAudio(
    uint32_t sample_rate, uint32_t sample_count,
    pepper::PluginDelegate::PlatformAudio::Client* client) {
  scoped_ptr<PlatformAudioImpl> audio(
      new PlatformAudioImpl(render_view_->audio_message_filter()));
  if (audio->Initialize(sample_rate, sample_count, client)) {
    return audio.release();
  } else {
    return NULL;
  }
}

bool PepperPluginDelegateImpl::RunFileChooser(
    const WebKit::WebFileChooserParams& params,
    WebKit::WebFileChooserCompletion* chooser_completion) {
  return render_view_->runFileChooser(params, chooser_completion);
}
<|endoftext|>


<commit_before>/**
 * The handler always needs to know what the previous node/way/relation
 * in the file looked like to answer questions like "what is the
 * valid_from date of the current entity" or "is this the last version
 * of that entity". The EntityTracker takes care of keeping the
 * current and the previous entity, free them as required and do basic
 * comparations.
 */

#ifndef IMPORTER_ENTITYTRACKER_HPP
#define IMPORTER_ENTITYTRACKER_HPP

/**
 * Tracks a previous and a current entity, provides a method to make the
 * current entity the previous one and manages freeing of the entities.
 * It is templated to allow nodes, ways and relations as child objects.
 */
template <class TObject>
class EntityTracker {

private:
    /**
     * pointer to the previous entity
     */
    shared_ptr<TObject const> m_prev;

    /**
     * pointer to the current entity
     */
    shared_ptr<TObject const> m_cur;

public:
    /**
     * get the pointer to the previous entity
     */
    const shared_ptr<TObject const> prev() {
        return m_prev;
    }

    /**
     * get the pointer to the current entity
     */
    const shared_ptr<TObject const> cur() {
        return m_cur;
    }

    /**
     * returns if the tracker currently tracks a previous entity
     */
    bool has_prev() {
        return m_prev;
    }

    /**
     * returns if the tracker currently tracks a current entity
     */
    bool has_cur() {
        return m_cur;
    }

    /**
     * returns if the tracker currently tracks a previous and a current
     * entity with the same id
     */
    bool cur_is_same_entity() {
        return has_prev() && has_cur() && (prev()->id() == cur()->id());
    }

    /**
     * feed in a new object as the current one
     *
     * if a current one still exists, the program will abort with an
     * assertation error, because the current enity needs to be swapped
     * away using the swap-method below, before feeding in a new one.
     */
    void feed(const shared_ptr<TObject const> obj) {
        assert(!m_cur);
        m_cur = obj;
    }

    /**
     * make the current entity the previous and delete the previous entity
     */
    void swap() {
        m_prev = m_cur;
        m_cur.reset();
    }
};

#endif // IMPORTER_ENTITYTRACKER_HPP
<commit_msg>explain upcoming changes<commit_after>/**
 * The handler always needs to know what the next node/way/relation
 * in the file lookes like to answer questions like "what is the
 * valid_to date of the current entity" or "is this the last version
 * of that entity". It also sometimes needs to know hot the previous
 * entity looks like to answer questions like "was this an area or a line
 * before it got deleted". The EntityTracker takes care of keeping the
 * previous, current and next entity, frees them as required and does
 * basic comparations.
 */

#ifndef IMPORTER_ENTITYTRACKER_HPP
#define IMPORTER_ENTITYTRACKER_HPP

/**
 * Tracks the previous, the current and the next entity, provides
 * a method to shift the entities into the next state and manages
 * freeing of the entities. It is templated to allow nodes, ways
 * and relations as child objects.
 */
template <class TObject>
class EntityTracker {

private:
    /**
     * pointer to the previous entity
     */
    shared_ptr<TObject const> m_prev;

    /**
     * pointer to the current entity
     */
    shared_ptr<TObject const> m_cur;

public:
    /**
     * get the pointer to the previous entity
     */
    const shared_ptr<TObject const> prev() {
        return m_prev;
    }

    /**
     * get the pointer to the current entity
     */
    const shared_ptr<TObject const> cur() {
        return m_cur;
    }

    /**
     * returns if the tracker currently tracks a previous entity
     */
    bool has_prev() {
        return m_prev;
    }

    /**
     * returns if the tracker currently tracks a current entity
     */
    bool has_cur() {
        return m_cur;
    }

    /**
     * returns if the tracker currently tracks a previous and a current
     * entity with the same id
     */
    bool cur_is_same_entity() {
        return has_prev() && has_cur() && (prev()->id() == cur()->id());
    }

    /**
     * feed in a new object as the current one
     *
     * if a current one still exists, the program will abort with an
     * assertation error, because the current enity needs to be swapped
     * away using the swap-method below, before feeding in a new one.
     */
    void feed(const shared_ptr<TObject const> obj) {
        assert(!m_cur);
        m_cur = obj;
    }

    /**
     * make the current entity the previous and delete the previous entity
     */
    void swap() {
        m_prev = m_cur;
        m_cur.reset();
    }
};

#endif // IMPORTER_ENTITYTRACKER_HPP
<|endoftext|>


<commit_before>#include "PanelComponents.h"
#include "Application.h"
#include "ModuleWindow.h"
#include "GameObject.h"
#include "ComponentTransformation.h"
#include "ComponentMesh.h"
#include "ComponentMaterial.h"
#include "ComponentCamera.h"
#include "ModuleCamera3D.h"
#include "ModuleRenderer3D.h"
#include "ModuleGOManager.h"
#include "Mesh.h"
#include "ImGui/imgui.h"

PanelComponents::PanelComponents() : Panel("Components")
{
	active = false;
	set_size = true;

	last_go = nullptr;
}

PanelComponents::~PanelComponents()
{

}

void PanelComponents::Draw(GameObject* selected_go)
{
	if (selected_go != nullptr)
	{
		ImGui::SetNextWindowPos(ImVec2(((App->window->GetWindowSize().x - 335)), 25));

		if (set_size == true)
		{
			ImGui::SetNextWindowSize(ImVec2(330, 610));
			set_size = false;
		}

		ImGui::Begin("Components", &active);

		ImGui::TextColored(ImVec4(0.90f, 0.90f, 0.00f, 1.00f), "GameObject: ");
		ImGui::SameLine();
		ImGui::Text(selected_go->GetName());

		if (ImGui::BeginMenu("Add component"))
		{
			if (ImGui::MenuItem("Camera"))
			{
				selected_go->CreateComponent(Component::Type::Camera);
			}

			ImGui::EndMenu();
		}

		if (ImGui::Button("Center view"))
		{
			App->camera->LookAt(selected_go->transform->GetPosition());
		}

		if (ImGui::Checkbox("Static test", &selected_go->static_go))
		{
			if (selected_go->children.size() != 0)
			{
				static_ask = selected_go->static_go;
			}
		}

		if (static_ask)
		{
			ImGuiWindowFlags window_flags = (ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_ShowBorders);
			ImGui::SetNextWindowPos(ImVec2((App->window->GetWindowSize().x / 2) - 190, (App->window->GetWindowSize().y / 2) - 50));
			ImGui::Begin("Hierarchy problem", nullptr, window_flags);
			ImGui::Text("Convert all %s children to static?", selected_go->GetName());

			ImVec2 size = ImVec2(80.0f, 20.0f);
			ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.0f, 0.5f, 0.0f, 0.75f));
			ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.0f, 0.75f, 0.0f, 0.75f));
			ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0.0f, 0.75f, 0.0f, 1.0f));
			if (ImGui::Button("Yes", size))
			{
				selected_go->static_children = true;
				static_ask = false;
			}
			ImGui::PopStyleColor(3);

			ImGui::SameLine(0.0f, 100.0f);

			ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.5f, 0.0f, 0.0f, 0.75f));
			ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.75f, 0.0f, 0.0f, 0.75f));
			ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0.75f, 0.0f, 0.0f, 1.0f));
			if (ImGui::Button("No", size))
			{
				selected_go->static_children = false;
				static_ask = false;
			}
			ImGui::PopStyleColor(3);

			ImGui::End();
		}

		//If actual game object is diferent of last one it must to set transformation
		if (last_go != selected_go || selected_go->static_go == true)
		{
			pos.Set(selected_go->transform->GetPosition().x, selected_go->transform->GetPosition().y, selected_go->transform->GetPosition().z);
			sca.Set(selected_go->transform->GetScale().x, selected_go->transform->GetScale().y, selected_go->transform->GetScale().z);
			rot.Set(selected_go->transform->GetRotation().x, selected_go->transform->GetRotation().y, selected_go->transform->GetRotation().z);
		}

		DrawTransformation(selected_go->transform, selected_go);

		for (std::vector<Component*>::iterator tmp = selected_go->components.begin(); tmp != selected_go->components.end(); tmp++)
		{
			if ((*tmp)->GetType() == Component::Type::Geometry)
			{
				if (last_go == selected_go)
				{
					((ComponentMesh*)(*tmp))->wirefr = true;
				}
				else
				{
					if (last_go != nullptr)
					{
						if (last_go->GetComponentByType(Component::Type::Geometry) != nullptr)
						{
							((ComponentMesh*)last_go->GetComponentByType(Component::Type::Geometry))->wirefr = false;
						}
					}
				}

				DrawMesh(((ComponentMesh*)(*tmp)), selected_go);
			}

			if ((*tmp)->GetType() == Component::Type::Material)
			{
				DrawMaterial(((ComponentMaterial*)(*tmp)), selected_go);
			}

			if ((*tmp)->GetType() == Component::Type::Camera)
			{
				DrawCamera(((ComponentCamera*)(*tmp)), selected_go);
			}
		}
		last_go = selected_go;
		ImGui::End();
	}
	else
	{
		if (last_go != nullptr)
		{
			if (last_go->GetComponentByType(Component::Type::Geometry) != nullptr)
			{
				((ComponentMesh*)last_go->GetComponentByType(Component::Type::Geometry))->wirefr = false;
			}
		}
	}
}

void PanelComponents::DrawTransformation(ComponentTransformation* go_transform, GameObject* go_selected)
{
	if (ImGui::CollapsingHeader(go_transform->name.c_str()))
	{
		ImGui::TextColored(ImVec4(1.0f, 0.5, 0.0f, 1.0f), "Component ID: ");
		ImGui::SameLine();
		ImGui::Text("%d", go_transform->GetID());
		ImGui::Separator();

		if (ImGui::DragFloat3("Postion", pos.ptr()))
		{
			go_transform->SetPos(pos.x, pos.y, pos.z);
		}
		if (ImGui::DragFloat3("Scale", sca.ptr(), 0.01f))
		{
			go_transform->SetScale(sca.x, sca.y, sca.z);
		}
		if (ImGui::DragFloat3("Rotation", rot.ptr()))
		{
			go_transform->SetRotEuler(rot.x, rot.y, rot.z);
		}
	}
}

void PanelComponents::DrawMesh(ComponentMesh* go_mesh, GameObject* go_selected)
{
	if (ImGui::CollapsingHeader(go_mesh->name.c_str()))
	{
		ImGui::TextColored(ImVec4(1.0f, 0.5, 0.0f, 1.0f), "Component ID: ");
		ImGui::SameLine();
		ImGui::Text("%d", (go_mesh->GetID()));
		ImGui::Separator();

		ImGui::SameLine(ImGui::GetWindowWidth() - 105);
		ImGui::Text("Active:");
		ImGui::SameLine(ImGui::GetWindowWidth() - 50);
		ImGui::Checkbox(go_mesh->is_active.c_str(), &go_mesh->active);

		ImGui::Checkbox(go_mesh->wire.c_str(), &go_mesh->wirefr);

		ImGui::Checkbox("AABB", &go_selected->aabb_debug);
		ImGui::Checkbox("OBB", &go_selected->obb_debug);
		ImGui::Separator();

		ImGui::Text("Number of vertex(Indices): %d", go_mesh->GetMesh()->num_indices);
		ImGui::Text("Number of vertex in memory: %d", go_mesh->GetMesh()->num_vertices);
		ImGui::Text("Number of normals: %d", go_mesh->GetMesh()->num_normals);
		ImGui::Text("Number of texture coordinates: %d", go_mesh->GetMesh()->num_tex_coord);
	}
}

void PanelComponents::DrawMaterial(ComponentMaterial* go_material, GameObject* go_selected)
{
	if (ImGui::CollapsingHeader(go_material->name.c_str()))
	{
		ImGui::TextColored(ImVec4(1.0f, 0.5, 0.0f, 1.0f), "Component ID: ");
		ImGui::SameLine();
		ImGui::Text("%d", go_material->GetID());

		ImGui::Separator();
		ImGui::Image((ImTextureID*)go_material->GetTexture(), ImVec2(200, 200), ImVec2(0, 0), ImVec2(1, 1), ImVec4(1, 1, 1, 1), ImVec4(0.0f, 0.6f, 0.6f, 1.0f));
		ImGui::Text("%s%s", "Texture path: ", go_material->tex_path.c_str());
	}
}

void PanelComponents::DrawCamera(ComponentCamera* go_camera, GameObject* go_selected)
{
	if (ImGui::CollapsingHeader(go_camera->name.c_str()))
	{
		near_plane = go_camera->GetNearPlane();
		far_plane = go_camera->GetFarPlane();
		field_of_view = go_camera->GetFOV();
		aspect_ratio = go_camera->GetAspectRatio();

		ImGui::TextColored(ImVec4(1.0f, 0.5, 0.0f, 1.0f), "Component ID: ");
		ImGui::SameLine();
		ImGui::Text("%d", go_camera->GetID());
		ImGui::Separator();

		ImGui::Checkbox("Camera frustrum", &go_camera->debug_draw);
		if (ImGui::Checkbox("Camera culling", &go_camera->frustum_culling))
		{
			App->go_manager->AddCameraCulling(go_camera, go_camera->frustum_culling);
		}

		if (ImGui::Checkbox("Use camera", &render_camera))
		{
			App->renderer3D->camera = go_camera;
			App->renderer3D->update_proj_matrix = true;
			App->camera->controls_disabled = true;
		}

		if (render_camera == false)
		{
			App->renderer3D->camera = App->camera->GetCamera();
			App->camera->controls_disabled = false;
			App->renderer3D->update_proj_matrix = true;
		}

		if (ImGui::DragFloat("Near plane", &near_plane, 0.1f))
		{
			go_camera->SetNearPlane(near_plane);
			if (render_camera)
			{
				App->renderer3D->update_proj_matrix = true;
			}
		}
		if (ImGui::DragFloat("Far plane", &far_plane, 0.1f))
		{
			go_camera->SetFarPlane(far_plane);
			if (render_camera)
			{
				App->renderer3D->update_proj_matrix = true;
			}
		}
		if (ImGui::DragFloat("Field of view", &field_of_view, 0.1f))
		{
			go_camera->SetFOV(field_of_view);
			if (render_camera)
			{
				App->renderer3D->update_proj_matrix = true;
			}
		}
		if (ImGui::DragFloat("Aspect ratio", &aspect_ratio, 0.01f))
		{
			go_camera->SetAspectRatio(aspect_ratio);
			if (render_camera)
			{
				App->renderer3D->update_proj_matrix = true;
			}
		}
	}
}<commit_msg>Little material color indicator on panel components, material.<commit_after>#include "PanelComponents.h"
#include "Application.h"
#include "ModuleWindow.h"
#include "GameObject.h"
#include "ComponentTransformation.h"
#include "ComponentMesh.h"
#include "ComponentMaterial.h"
#include "ComponentCamera.h"
#include "ModuleCamera3D.h"
#include "ModuleRenderer3D.h"
#include "ModuleGOManager.h"
#include "Mesh.h"
#include "ImGui/imgui.h"

PanelComponents::PanelComponents() : Panel("Components")
{
	active = false;
	set_size = true;

	last_go = nullptr;
}

PanelComponents::~PanelComponents()
{

}

void PanelComponents::Draw(GameObject* selected_go)
{
	if (selected_go != nullptr)
	{
		ImGui::SetNextWindowPos(ImVec2(((App->window->GetWindowSize().x - 335)), 25));

		if (set_size == true)
		{
			ImGui::SetNextWindowSize(ImVec2(330, 610));
			set_size = false;
		}

		ImGui::Begin("Components", &active);

		ImGui::TextColored(ImVec4(0.90f, 0.90f, 0.00f, 1.00f), "GameObject: ");
		ImGui::SameLine();
		ImGui::Text(selected_go->GetName());

		if (ImGui::BeginMenu("Add component"))
		{
			if (ImGui::MenuItem("Camera"))
			{
				selected_go->CreateComponent(Component::Type::Camera);
			}

			ImGui::EndMenu();
		}

		if (ImGui::Button("Center view"))
		{
			App->camera->LookAt(selected_go->transform->GetPosition());
		}

		if (ImGui::Checkbox("Static test", &selected_go->static_go))
		{
			if (selected_go->children.size() != 0)
			{
				static_ask = selected_go->static_go;
			}
		}

		if (static_ask)
		{
			ImGuiWindowFlags window_flags = (ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_ShowBorders);
			ImGui::SetNextWindowPos(ImVec2((App->window->GetWindowSize().x / 2) - 190, (App->window->GetWindowSize().y / 2) - 50));
			ImGui::Begin("Hierarchy problem", nullptr, window_flags);
			ImGui::Text("Convert all %s children to static?", selected_go->GetName());

			ImVec2 size = ImVec2(80.0f, 20.0f);
			ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.0f, 0.5f, 0.0f, 0.75f));
			ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.0f, 0.75f, 0.0f, 0.75f));
			ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0.0f, 0.75f, 0.0f, 1.0f));
			if (ImGui::Button("Yes", size))
			{
				selected_go->static_children = true;
				static_ask = false;
			}
			ImGui::PopStyleColor(3);

			ImGui::SameLine(0.0f, 100.0f);

			ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.5f, 0.0f, 0.0f, 0.75f));
			ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(0.75f, 0.0f, 0.0f, 0.75f));
			ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0.75f, 0.0f, 0.0f, 1.0f));
			if (ImGui::Button("No", size))
			{
				selected_go->static_children = false;
				static_ask = false;
			}
			ImGui::PopStyleColor(3);

			ImGui::End();
		}

		//If actual game object is diferent of last one it must to set transformation
		if (last_go != selected_go || selected_go->static_go == true)
		{
			pos.Set(selected_go->transform->GetPosition().x, selected_go->transform->GetPosition().y, selected_go->transform->GetPosition().z);
			sca.Set(selected_go->transform->GetScale().x, selected_go->transform->GetScale().y, selected_go->transform->GetScale().z);
			rot.Set(selected_go->transform->GetRotation().x, selected_go->transform->GetRotation().y, selected_go->transform->GetRotation().z);
		}

		DrawTransformation(selected_go->transform, selected_go);

		for (std::vector<Component*>::iterator tmp = selected_go->components.begin(); tmp != selected_go->components.end(); tmp++)
		{
			if ((*tmp)->GetType() == Component::Type::Geometry)
			{
				if (last_go == selected_go)
				{
					((ComponentMesh*)(*tmp))->wirefr = true;
				}
				else
				{
					if (last_go != nullptr)
					{
						if (last_go->GetComponentByType(Component::Type::Geometry) != nullptr)
						{
							((ComponentMesh*)last_go->GetComponentByType(Component::Type::Geometry))->wirefr = false;
						}
					}
				}

				DrawMesh(((ComponentMesh*)(*tmp)), selected_go);
			}

			if ((*tmp)->GetType() == Component::Type::Material)
			{
				DrawMaterial(((ComponentMaterial*)(*tmp)), selected_go);
			}

			if ((*tmp)->GetType() == Component::Type::Camera)
			{
				DrawCamera(((ComponentCamera*)(*tmp)), selected_go);
			}
		}
		last_go = selected_go;
		ImGui::End();
	}
	else
	{
		if (last_go != nullptr)
		{
			if (last_go->GetComponentByType(Component::Type::Geometry) != nullptr)
			{
				((ComponentMesh*)last_go->GetComponentByType(Component::Type::Geometry))->wirefr = false;
			}
		}
	}
}

void PanelComponents::DrawTransformation(ComponentTransformation* go_transform, GameObject* go_selected)
{
	if (ImGui::CollapsingHeader(go_transform->name.c_str()))
	{
		ImGui::TextColored(ImVec4(1.0f, 0.5, 0.0f, 1.0f), "Component ID: ");
		ImGui::SameLine();
		ImGui::Text("%d", go_transform->GetID());
		ImGui::Separator();

		if (ImGui::DragFloat3("Postion", pos.ptr()))
		{
			go_transform->SetPos(pos.x, pos.y, pos.z);
		}
		if (ImGui::DragFloat3("Scale", sca.ptr(), 0.01f))
		{
			go_transform->SetScale(sca.x, sca.y, sca.z);
		}
		if (ImGui::DragFloat3("Rotation", rot.ptr()))
		{
			go_transform->SetRotEuler(rot.x, rot.y, rot.z);
		}
	}
}

void PanelComponents::DrawMesh(ComponentMesh* go_mesh, GameObject* go_selected)
{
	if (ImGui::CollapsingHeader(go_mesh->name.c_str()))
	{
		ImGui::TextColored(ImVec4(1.0f, 0.5, 0.0f, 1.0f), "Component ID: ");
		ImGui::SameLine();
		ImGui::Text("%d", (go_mesh->GetID()));
		ImGui::Separator();

		ImGui::SameLine(ImGui::GetWindowWidth() - 105);
		ImGui::Text("Active:");
		ImGui::SameLine(ImGui::GetWindowWidth() - 50);
		ImGui::Checkbox(go_mesh->is_active.c_str(), &go_mesh->active);

		ImGui::Checkbox(go_mesh->wire.c_str(), &go_mesh->wirefr);

		ImGui::Checkbox("AABB", &go_selected->aabb_debug);
		ImGui::Checkbox("OBB", &go_selected->obb_debug);
		ImGui::Separator();

		ImGui::Text("Number of vertex(Indices): %d", go_mesh->GetMesh()->num_indices);
		ImGui::Text("Number of vertex in memory: %d", go_mesh->GetMesh()->num_vertices);
		ImGui::Text("Number of normals: %d", go_mesh->GetMesh()->num_normals);
		ImGui::Text("Number of texture coordinates: %d", go_mesh->GetMesh()->num_tex_coord);
	}
}

void PanelComponents::DrawMaterial(ComponentMaterial* go_material, GameObject* go_selected)
{
	if (ImGui::CollapsingHeader(go_material->name.c_str()))
	{
		ImGui::TextColored(ImVec4(1.0f, 0.5, 0.0f, 1.0f), "Component ID: ");
		ImGui::SameLine();
		ImGui::Text("%d", go_material->GetID());

		ImGui::Separator();
		ImGui::Image((ImTextureID*)go_material->GetTexture(), ImVec2(200, 200), ImVec2(0, 0), ImVec2(1, 1), ImVec4(1, 1, 1, 1), ImVec4(0.0f, 0.6f, 0.6f, 1.0f));
		ImGui::Text("%s%s", "Texture path: ", go_material->tex_path.c_str());
		ImGui::Text("Material color:");
		ImGui::SameLine(120, 0);
		ImGui::ColorButton(ImVec4(go_material->GetMaterialColor().r, go_material->GetMaterialColor().g, go_material->GetMaterialColor().b, go_material->GetMaterialColor().a));
	}
}

void PanelComponents::DrawCamera(ComponentCamera* go_camera, GameObject* go_selected)
{
	if (ImGui::CollapsingHeader(go_camera->name.c_str()))
	{
		near_plane = go_camera->GetNearPlane();
		far_plane = go_camera->GetFarPlane();
		field_of_view = go_camera->GetFOV();
		aspect_ratio = go_camera->GetAspectRatio();

		ImGui::TextColored(ImVec4(1.0f, 0.5, 0.0f, 1.0f), "Component ID: ");
		ImGui::SameLine();
		ImGui::Text("%d", go_camera->GetID());
		ImGui::Separator();

		ImGui::Checkbox("Camera frustrum", &go_camera->debug_draw);
		if (ImGui::Checkbox("Camera culling", &go_camera->frustum_culling))
		{
			App->go_manager->AddCameraCulling(go_camera, go_camera->frustum_culling);
		}

		if (ImGui::Checkbox("Use camera", &render_camera))
		{
			App->renderer3D->camera = go_camera;
			App->renderer3D->update_proj_matrix = true;
			App->camera->controls_disabled = true;
		}

		if (render_camera == false)
		{
			App->renderer3D->camera = App->camera->GetCamera();
			App->camera->controls_disabled = false;
			App->renderer3D->update_proj_matrix = true;
		}

		if (ImGui::DragFloat("Near plane", &near_plane, 0.1f))
		{
			go_camera->SetNearPlane(near_plane);
			if (render_camera)
			{
				App->renderer3D->update_proj_matrix = true;
			}
		}
		if (ImGui::DragFloat("Far plane", &far_plane, 0.1f))
		{
			go_camera->SetFarPlane(far_plane);
			if (render_camera)
			{
				App->renderer3D->update_proj_matrix = true;
			}
		}
		if (ImGui::DragFloat("Field of view", &field_of_view, 0.1f))
		{
			go_camera->SetFOV(field_of_view);
			if (render_camera)
			{
				App->renderer3D->update_proj_matrix = true;
			}
		}
		if (ImGui::DragFloat("Aspect ratio", &aspect_ratio, 0.01f))
		{
			go_camera->SetAspectRatio(aspect_ratio);
			if (render_camera)
			{
				App->renderer3D->update_proj_matrix = true;
			}
		}
	}
}<|endoftext|>