<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 2671
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1566979 by johtaylo@johtaylo-jtincrementor2-increment on 2018/06/12 03:00:06<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 2672
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<|endoftext|>


<commit_before>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 2550
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<commit_msg>P4 to Git Change 1490975 by johtaylo@johtaylo-jtincrementor2-increment on 2017/12/06 03:00:04<commit_after>//
// Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.
//

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 2551
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<|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/browser/sync/notifier/base/async_network_alive.h"

#include <sys/socket.h>
#include <asm/types.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>

#include "base/logging.h"
#include "talk/base/physicalsocketserver.h"

namespace notifier {

class AsyncNetworkAliveLinux : public AsyncNetworkAlive {
 public:
  AsyncNetworkAliveLinux() {
    if (pipe(exit_pipe_) == -1) {
      PLOG(ERROR) << "Could not create pipe for exit signal.";
      exit_pipe_[0] = 0;
      exit_pipe_[1] = 0;
    }
  }

  virtual ~AsyncNetworkAliveLinux() {
    if (exit_pipe_[1]) {
      close(exit_pipe_[1]);
    }
  }

 protected:
  // SignalThread Interface
  virtual void DoWork() {
    if (!exit_pipe_[0]) {
      // If we don't have an exit flag to listen for, set the error flag and
      // abort.
      error_ = true;
      return;
    }

    // This function listens for changes to network interfaces, and link state.
    // It's copied from syncapi.cc.
    struct sockaddr_nl socket_address;

    memset(&socket_address, 0, sizeof(socket_address));
    socket_address.nl_family = AF_NETLINK;
    socket_address.nl_groups = RTMGRP_LINK | RTMGRP_IPV4_IFADDR;

    // NETLINK_ROUTE is the protocol used to update the kernel routing table.
    int fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
    bind(fd, (struct sockaddr *) &socket_address, sizeof(socket_address));

    fd_set rdfs;
    FD_ZERO(&rdfs);
    FD_SET(fd, &rdfs);
    FD_SET(exit_pipe_[0], &rdfs);

    int max_fd = fd > exit_pipe_[0] ? fd : exit_pipe_[0];

    int result = select(max_fd + 1, &rdfs, NULL, NULL, NULL);

    if (result <= 0) {
      error_ = true;
      PLOG(ERROR) << "select() returned unexpected result " << result;
      close(fd);
      close(exit_pipe_[0]);
      return;
    }

    // Since we received a change from the socket, read the change in.
    if (FD_ISSET(fd, &rdfs)) {
      char buf[4096];
      struct iovec iov = { buf, sizeof(buf) };
      struct sockaddr_nl sa;

      struct msghdr msg = { (void *)&sa, sizeof(sa), &iov, 1, NULL, 0, 0 };
      recvmsg(fd, &msg, 0);
    }

    close(fd);

    // If exit_pipe was written to, we must be shutting down.
    if (FD_ISSET(exit_pipe_[0], &rdfs)) {
      alive_ = false;
      error_ = true;
      close(exit_pipe_[0]);
      return;
    }

    // If there is an active connection, check that talk.google.com:5222
    // is reachable.
    talk_base::PhysicalSocketServer physical;
    scoped_ptr<talk_base::Socket> socket(physical.CreateSocket(SOCK_STREAM));
    if (socket->Connect(talk_base::SocketAddress("talk.google.com", 5222))) {
      alive_ = false;
    } else {
      alive_ = true;
    }
  }

  virtual void OnWorkStop() {
    if (exit_pipe_[1]) {
      char data = 0;
      // We can't ignore the return value on write(), since that generates a
      // compile warning.  However, since we're exiting, there's nothing we can
      // do if this fails except to log it.
      if (write(exit_pipe_[1], &data, 1) == -1) {
        PLOG(WARNING) << "Error sending error signal to AsyncNetworkAliveLinux";
      }
    }
  }

 private:
  int exit_pipe_[2];
  DISALLOW_COPY_AND_ASSIGN(AsyncNetworkAliveLinux);
};

AsyncNetworkAlive* AsyncNetworkAlive::Create() {
  return new AsyncNetworkAliveLinux();
}

}  // namespace notifier
<commit_msg>Clean up read FDs in async network alive.  This prevents chrome from eating all FDs.<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/browser/sync/notifier/base/async_network_alive.h"

#include <sys/socket.h>
#include <asm/types.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>

#include "base/logging.h"
#include "talk/base/physicalsocketserver.h"

namespace notifier {

class AsyncNetworkAliveLinux : public AsyncNetworkAlive {
 public:
  AsyncNetworkAliveLinux() {
    if (pipe(exit_pipe_) == -1) {
      PLOG(ERROR) << "Could not create pipe for exit signal.";
      exit_pipe_[0] = 0;
      exit_pipe_[1] = 0;
    }
  }

  virtual ~AsyncNetworkAliveLinux() {
    if (exit_pipe_[1]) {
      // Ensure that we've signalled the thread to quit.
      char data = 0;
      if (write(exit_pipe_[1], &data, 1) == -1) {
        PLOG(WARNING) << "Error sending error signal to AsyncNetworkAliveLinux";
      }
      close(exit_pipe_[1]);
      exit_pipe_[1] = 0;
    }
    if (exit_pipe_[0]) {
      close(exit_pipe_[0]);
      exit_pipe_[0] = 0;
    }
  }

 protected:
  // SignalThread Interface
  virtual void DoWork() {
    if (!exit_pipe_[0]) {
      PLOG(ERROR) << "No exit flag to listen for.";
      // If we don't have an exit flag to listen for, set the error flag and
      // abort.
      error_ = true;
      return;
    }

    // This function listens for changes to network interfaces, and link state.
    // It's copied from syncapi.cc.
    struct sockaddr_nl socket_address;

    memset(&socket_address, 0, sizeof(socket_address));
    socket_address.nl_family = AF_NETLINK;
    socket_address.nl_groups = RTMGRP_LINK | RTMGRP_IPV4_IFADDR;

    // NETLINK_ROUTE is the protocol used to update the kernel routing table.
    int fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
    bind(fd, (struct sockaddr *) &socket_address, sizeof(socket_address));

    fd_set rdfs;
    FD_ZERO(&rdfs);
    FD_SET(fd, &rdfs);
    FD_SET(exit_pipe_[0], &rdfs);

    int max_fd = fd > exit_pipe_[0] ? fd : exit_pipe_[0];

    int result = select(max_fd + 1, &rdfs, NULL, NULL, NULL);

    if (result <= 0) {
      error_ = true;
      PLOG(ERROR) << "select() returned unexpected result " << result;
      close(fd);
      close(exit_pipe_[0]);
      exit_pipe_[0] = 0;
      return;
    }

    // Since we received a change from the socket, read the change in.
    if (FD_ISSET(fd, &rdfs)) {
      char buf[4096];
      struct iovec iov = { buf, sizeof(buf) };
      struct sockaddr_nl sa;

      struct msghdr msg = { (void *)&sa, sizeof(sa), &iov, 1, NULL, 0, 0 };
      recvmsg(fd, &msg, 0);
    }

    close(fd);

    // If exit_pipe was written to, we must be shutting down.
    if (exit_pipe_[0] == 0 || FD_ISSET(exit_pipe_[0], &rdfs)) {
      alive_ = false;
      error_ = true;
      close(exit_pipe_[0]);
      exit_pipe_[0] = 0;
      return;
    }

    // If there is an active connection, check that talk.google.com:5222
    // is reachable.
    talk_base::PhysicalSocketServer physical;
    scoped_ptr<talk_base::Socket> socket(physical.CreateSocket(SOCK_STREAM));
    if (socket->Connect(talk_base::SocketAddress("talk.google.com", 5222))) {
      alive_ = false;
    } else {
      alive_ = true;
    }

    close(exit_pipe_[0]);
    exit_pipe_[0] = 0;
  }

  virtual void OnWorkStop() {
    if (exit_pipe_[1]) {
      char data = 0;
      // We can't ignore the return value on write(), since that generates a
      // compile warning.  However, since we're exiting, there's nothing we can
      // do if this fails except to log it.
      if (write(exit_pipe_[1], &data, 1) == -1) {
        PLOG(WARNING) << "Error sending error signal to AsyncNetworkAliveLinux";
      }
    }
  }

 private:
  int exit_pipe_[2];
  DISALLOW_COPY_AND_ASSIGN(AsyncNetworkAliveLinux);
};

AsyncNetworkAlive* AsyncNetworkAlive::Create() {
  return new AsyncNetworkAliveLinux();
}

}  // namespace notifier
<|endoftext|>


<commit_before>// Copyright (c) 2012 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/tab_contents/chrome_web_contents_view_win_delegate.h"

#include "chrome/browser/browser_shutdown.h"
#include "chrome/browser/tab_contents/web_drag_bookmark_handler_win.h"
#include "chrome/browser/ui/constrained_window_tab_helper.h"
#include "chrome/browser/ui/sad_tab_helper.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/browser/ui/views/constrained_window_views.h"
#include "chrome/browser/ui/views/tab_contents/render_view_context_menu_views.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_view.h"
#include "ui/views/focus/focus_manager.h"
#include "ui/views/focus/view_storage.h"
#include "ui/views/widget/widget.h"

ChromeWebContentsViewWinDelegate::ChromeWebContentsViewWinDelegate(
    content::WebContents* web_contents)
    : web_contents_(web_contents) {
  last_focused_view_storage_id_ =
      views::ViewStorage::GetInstance()->CreateStorageID();
}

ChromeWebContentsViewWinDelegate::~ChromeWebContentsViewWinDelegate() {
  // Makes sure to remove any stored view we may still have in the ViewStorage.
  //
  // It is possible the view went away before us, so we only do this if the
  // view is registered.
  views::ViewStorage* view_storage = views::ViewStorage::GetInstance();
  if (view_storage->RetrieveView(last_focused_view_storage_id_) != NULL)
    view_storage->RemoveView(last_focused_view_storage_id_);

}

content::WebDragDestDelegate*
    ChromeWebContentsViewWinDelegate::GetDragDestDelegate() {
  // We install a chrome specific handler to intercept bookmark drags for the
  // bookmark manager/extension API.
  bookmark_handler_.reset(new WebDragBookmarkHandlerWin);
  return bookmark_handler_.get();
}

bool ChromeWebContentsViewWinDelegate::Focus() {
  TabContentsWrapper* wrapper =
      TabContentsWrapper::GetCurrentWrapperForContents(web_contents_);
  if (wrapper) {
      views::Widget* sad_tab = wrapper->sad_tab_helper()->sad_tab();
    if (sad_tab) {
      sad_tab->GetContentsView()->RequestFocus();
      return true;
    }

    // TODO(erg): TabContents used to own constrained windows, which is why
    // this is here. Eventually this should be ported to a containing view
    // specializing in constrained window management.
    ConstrainedWindowTabHelper* helper =
        wrapper->constrained_window_tab_helper();
    if (helper->constrained_window_count() > 0) {
      ConstrainedWindow* window = *helper->constrained_window_begin();
      DCHECK(window);
      window->FocusConstrainedWindow();
      return true;
    }
  }
  return false;
}

void ChromeWebContentsViewWinDelegate::TakeFocus(bool reverse) {
  GetFocusManager()->AdvanceFocus(reverse);
}

void ChromeWebContentsViewWinDelegate::StoreFocus() {
  views::ViewStorage* view_storage = views::ViewStorage::GetInstance();

  if (view_storage->RetrieveView(last_focused_view_storage_id_) != NULL)
    view_storage->RemoveView(last_focused_view_storage_id_);

  views::View* focused_view = GetFocusManager()->GetFocusedView();
  if (focused_view)
    view_storage->StoreView(last_focused_view_storage_id_, focused_view);
}

void ChromeWebContentsViewWinDelegate::RestoreFocus() {
  views::ViewStorage* view_storage = views::ViewStorage::GetInstance();
  views::View* last_focused_view =
      view_storage->RetrieveView(last_focused_view_storage_id_);

  if (!last_focused_view) {
    SetInitialFocus();
  } else {
    if (last_focused_view->IsFocusable() &&
        GetFocusManager()->ContainsView(last_focused_view)) {
      last_focused_view->RequestFocus();
    } else {
      // The focused view may not belong to the same window hierarchy (e.g.
      // if the location bar was focused and the tab is dragged out), or it may
      // no longer be focusable (e.g. if the location bar was focused and then
      // we switched to fullscreen mode).  In that case we default to the
      // default focus.
      SetInitialFocus();
    }
    view_storage->RemoveView(last_focused_view_storage_id_);
  }
}

void ChromeWebContentsViewWinDelegate::ShowContextMenu(
    const content::ContextMenuParams& params) {
  context_menu_.reset(new RenderViewContextMenuViews(web_contents_, params));
  context_menu_->Init();

  // Don't show empty menus.
  if (context_menu_->menu_model().GetItemCount() == 0)
    return;

  gfx::Point screen_point(params.x, params.y);

  POINT temp = screen_point.ToPOINT();
  ClientToScreen(web_contents_->GetView()->GetNativeView(), &temp);
  screen_point = temp;

  // Enable recursive tasks on the message loop so we can get updates while
  // the context menu is being displayed.
  MessageLoop::ScopedNestableTaskAllower allow(MessageLoop::current());
  context_menu_->RunMenuAt(
      GetTopLevelWidget(), screen_point.x(), screen_point.y());
}

void ChromeWebContentsViewWinDelegate::SizeChanged(const gfx::Size& size) {
  TabContentsWrapper* wrapper =
      TabContentsWrapper::GetCurrentWrapperForContents(web_contents_);
  if (!wrapper)
    return;
  views::Widget* sad_tab = wrapper->sad_tab_helper()->sad_tab();
  if (sad_tab)
    sad_tab->SetBounds(gfx::Rect(size));
}

views::Widget* ChromeWebContentsViewWinDelegate::GetTopLevelWidget() {
  HWND top_level_window = web_contents_->GetView()->GetTopLevelNativeWindow();
  if (!top_level_window)
    return NULL;
  return views::Widget::GetWidgetForNativeWindow(top_level_window);
}

views::FocusManager*
    ChromeWebContentsViewWinDelegate::GetFocusManager() {
  views::Widget* toplevel_widget = GetTopLevelWidget();
  return toplevel_widget ? toplevel_widget->GetFocusManager() : NULL;
}

void ChromeWebContentsViewWinDelegate::SetInitialFocus() {
  if (web_contents_->FocusLocationBarByDefault()) {
    web_contents_->SetFocusToLocationBar(false);
  } else {
    web_contents_->GetView()->Focus();
  }
}
<commit_msg>Fix Win builder dbg, RenderViewContextMenuViews::RunMenuAt now has only two parameters.<commit_after>// Copyright (c) 2012 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/tab_contents/chrome_web_contents_view_win_delegate.h"

#include "chrome/browser/browser_shutdown.h"
#include "chrome/browser/tab_contents/web_drag_bookmark_handler_win.h"
#include "chrome/browser/ui/constrained_window_tab_helper.h"
#include "chrome/browser/ui/sad_tab_helper.h"
#include "chrome/browser/ui/tab_contents/tab_contents_wrapper.h"
#include "chrome/browser/ui/views/constrained_window_views.h"
#include "chrome/browser/ui/views/tab_contents/render_view_context_menu_views.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_view.h"
#include "ui/views/focus/focus_manager.h"
#include "ui/views/focus/view_storage.h"
#include "ui/views/widget/widget.h"

ChromeWebContentsViewWinDelegate::ChromeWebContentsViewWinDelegate(
    content::WebContents* web_contents)
    : web_contents_(web_contents) {
  last_focused_view_storage_id_ =
      views::ViewStorage::GetInstance()->CreateStorageID();
}

ChromeWebContentsViewWinDelegate::~ChromeWebContentsViewWinDelegate() {
  // Makes sure to remove any stored view we may still have in the ViewStorage.
  //
  // It is possible the view went away before us, so we only do this if the
  // view is registered.
  views::ViewStorage* view_storage = views::ViewStorage::GetInstance();
  if (view_storage->RetrieveView(last_focused_view_storage_id_) != NULL)
    view_storage->RemoveView(last_focused_view_storage_id_);

}

content::WebDragDestDelegate*
    ChromeWebContentsViewWinDelegate::GetDragDestDelegate() {
  // We install a chrome specific handler to intercept bookmark drags for the
  // bookmark manager/extension API.
  bookmark_handler_.reset(new WebDragBookmarkHandlerWin);
  return bookmark_handler_.get();
}

bool ChromeWebContentsViewWinDelegate::Focus() {
  TabContentsWrapper* wrapper =
      TabContentsWrapper::GetCurrentWrapperForContents(web_contents_);
  if (wrapper) {
      views::Widget* sad_tab = wrapper->sad_tab_helper()->sad_tab();
    if (sad_tab) {
      sad_tab->GetContentsView()->RequestFocus();
      return true;
    }

    // TODO(erg): TabContents used to own constrained windows, which is why
    // this is here. Eventually this should be ported to a containing view
    // specializing in constrained window management.
    ConstrainedWindowTabHelper* helper =
        wrapper->constrained_window_tab_helper();
    if (helper->constrained_window_count() > 0) {
      ConstrainedWindow* window = *helper->constrained_window_begin();
      DCHECK(window);
      window->FocusConstrainedWindow();
      return true;
    }
  }
  return false;
}

void ChromeWebContentsViewWinDelegate::TakeFocus(bool reverse) {
  GetFocusManager()->AdvanceFocus(reverse);
}

void ChromeWebContentsViewWinDelegate::StoreFocus() {
  views::ViewStorage* view_storage = views::ViewStorage::GetInstance();

  if (view_storage->RetrieveView(last_focused_view_storage_id_) != NULL)
    view_storage->RemoveView(last_focused_view_storage_id_);

  views::View* focused_view = GetFocusManager()->GetFocusedView();
  if (focused_view)
    view_storage->StoreView(last_focused_view_storage_id_, focused_view);
}

void ChromeWebContentsViewWinDelegate::RestoreFocus() {
  views::ViewStorage* view_storage = views::ViewStorage::GetInstance();
  views::View* last_focused_view =
      view_storage->RetrieveView(last_focused_view_storage_id_);

  if (!last_focused_view) {
    SetInitialFocus();
  } else {
    if (last_focused_view->IsFocusable() &&
        GetFocusManager()->ContainsView(last_focused_view)) {
      last_focused_view->RequestFocus();
    } else {
      // The focused view may not belong to the same window hierarchy (e.g.
      // if the location bar was focused and the tab is dragged out), or it may
      // no longer be focusable (e.g. if the location bar was focused and then
      // we switched to fullscreen mode).  In that case we default to the
      // default focus.
      SetInitialFocus();
    }
    view_storage->RemoveView(last_focused_view_storage_id_);
  }
}

void ChromeWebContentsViewWinDelegate::ShowContextMenu(
    const content::ContextMenuParams& params) {
  context_menu_.reset(new RenderViewContextMenuViews(web_contents_, params));
  context_menu_->Init();

  // Don't show empty menus.
  if (context_menu_->menu_model().GetItemCount() == 0)
    return;

  gfx::Point screen_point(params.x, params.y);

  POINT temp = screen_point.ToPOINT();
  ClientToScreen(web_contents_->GetView()->GetNativeView(), &temp);
  screen_point = temp;

  // Enable recursive tasks on the message loop so we can get updates while
  // the context menu is being displayed.
  MessageLoop::ScopedNestableTaskAllower allow(MessageLoop::current());
  context_menu_->RunMenuAt(GetTopLevelWidget(), screen_point);
}

void ChromeWebContentsViewWinDelegate::SizeChanged(const gfx::Size& size) {
  TabContentsWrapper* wrapper =
      TabContentsWrapper::GetCurrentWrapperForContents(web_contents_);
  if (!wrapper)
    return;
  views::Widget* sad_tab = wrapper->sad_tab_helper()->sad_tab();
  if (sad_tab)
    sad_tab->SetBounds(gfx::Rect(size));
}

views::Widget* ChromeWebContentsViewWinDelegate::GetTopLevelWidget() {
  HWND top_level_window = web_contents_->GetView()->GetTopLevelNativeWindow();
  if (!top_level_window)
    return NULL;
  return views::Widget::GetWidgetForNativeWindow(top_level_window);
}

views::FocusManager*
    ChromeWebContentsViewWinDelegate::GetFocusManager() {
  views::Widget* toplevel_widget = GetTopLevelWidget();
  return toplevel_widget ? toplevel_widget->GetFocusManager() : NULL;
}

void ChromeWebContentsViewWinDelegate::SetInitialFocus() {
  if (web_contents_->FocusLocationBarByDefault()) {
    web_contents_->SetFocusToLocationBar(false);
  } else {
    web_contents_->GetView()->Focus();
  }
}
<|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/views/tab_contents/native_tab_contents_view_win.h"

#include "chrome/browser/renderer_host/render_widget_host_view_win.h"
#include "chrome/browser/tab_contents/web_drop_target_win.h"
#include "chrome/browser/ui/views/tab_contents/tab_contents_drag_win.h"
#include "chrome/browser/ui/views/tab_contents/native_tab_contents_view_delegate.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/browser/tab_contents/tab_contents_view.h"

namespace {

// Tabs must be created as child widgets, otherwise they will be given
// a FocusManager which will conflict with the FocusManager of the
// window they eventually end up attached to.
//
// A tab will not have a parent HWND whenever it is not active in its
// host window - for example at creation time and when it's in the
// background, so we provide a default widget to host them.
//
// It may be tempting to use GetDesktopWindow() instead, but this is
// problematic as the shell sends messages to children of the desktop
// window that interact poorly with us.
//
// See: http://crbug.com/16476
HWND GetHiddenTabHostWindow() {
  static views::Widget* widget = NULL;

  if (!widget) {
    widget = new views::Widget;
    // We don't want this widget to be closed automatically, this causes
    // problems in tests that close the last non-secondary window.
    widget->set_is_secondary_widget(false);
    views::Widget::InitParams params(views::Widget::InitParams::TYPE_POPUP);
    widget->Init(params);
    // If a background window requests focus, the hidden tab host will
    // be activated to focus the tab.  Use WS_DISABLED to prevent
    // this.
    EnableWindow(widget->GetNativeView(), FALSE);
  }

  return widget->GetNativeView();
}

}  // namespace

////////////////////////////////////////////////////////////////////////////////
// NativeTabContentsViewWin, public:

NativeTabContentsViewWin::NativeTabContentsViewWin(
    internal::NativeTabContentsViewDelegate* delegate)
    : views::NativeWidgetWin(delegate->AsNativeWidgetDelegate()),
      delegate_(delegate) {
}

NativeTabContentsViewWin::~NativeTabContentsViewWin() {
  CloseNow();
}

TabContents* NativeTabContentsViewWin::GetTabContents() const {
  return delegate_->GetTabContents();
}

void NativeTabContentsViewWin::EndDragging() {
  delegate_->OnNativeTabContentsViewDraggingEnded();
  drag_handler_ = NULL;
}

////////////////////////////////////////////////////////////////////////////////
// NativeTabContentsViewWin, NativeTabContentsView implementation:

void NativeTabContentsViewWin::InitNativeTabContentsView() {
  views::Widget::InitParams params(views::Widget::InitParams::TYPE_CONTROL);
  params.native_widget = this;
  params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
  params.parent = GetHiddenTabHostWindow();
  GetWidget()->Init(params);

  // Remove the root view drop target so we can register our own.
  RevokeDragDrop(GetNativeView());
  drop_target_ = new WebDropTarget(GetNativeView(),
                                   delegate_->GetTabContents());
}

void NativeTabContentsViewWin::Unparent() {
  // Note that we do not DCHECK on focus_manager_ as it may be NULL when used
  // with an external tab container.
  views::Widget::ReparentNativeView(GetNativeView(), GetHiddenTabHostWindow());
}

RenderWidgetHostView* NativeTabContentsViewWin::CreateRenderWidgetHostView(
    RenderWidgetHost* render_widget_host) {
  RenderWidgetHostViewWin* view =
      new RenderWidgetHostViewWin(render_widget_host);
  view->CreateWnd(GetNativeView());
  view->ShowWindow(SW_SHOW);
  return view;
}

gfx::NativeWindow NativeTabContentsViewWin::GetTopLevelNativeWindow() const {
  return ::GetAncestor(GetNativeView(), GA_ROOT);
}

void NativeTabContentsViewWin::SetPageTitle(const std::wstring& title) {
  // It's possible to get this after the hwnd has been destroyed.
  if (GetNativeView())
    ::SetWindowText(GetNativeView(), title.c_str());
}

void NativeTabContentsViewWin::StartDragging(const WebDropData& drop_data,
                                             WebKit::WebDragOperationsMask ops,
                                             const SkBitmap& image,
                                             const gfx::Point& image_offset) {
  drag_handler_ = new TabContentsDragWin(this);
  drag_handler_->StartDragging(drop_data, ops, image, image_offset);
}

void NativeTabContentsViewWin::CancelDrag() {
  drag_handler_->CancelDrag();
}

bool NativeTabContentsViewWin::IsDoingDrag() const {
  return drag_handler_.get() != NULL;
}

void NativeTabContentsViewWin::SetDragCursor(
    WebKit::WebDragOperation operation) {
  drop_target_->set_drag_cursor(operation);
}

views::NativeWidget* NativeTabContentsViewWin::AsNativeWidget() {
  return this;
}

////////////////////////////////////////////////////////////////////////////////
// NativeTabContentsViewWin, views::NativeWidgetWin overrides:

void NativeTabContentsViewWin::OnDestroy() {
  if (drop_target_.get()) {
    RevokeDragDrop(GetNativeView());
    drop_target_ = NULL;
  }

  NativeWidgetWin::OnDestroy();
}

void NativeTabContentsViewWin::OnHScroll(int scroll_type,
                                         short position,
                                         HWND scrollbar) {
  ScrollCommon(WM_HSCROLL, scroll_type, position, scrollbar);
}

LRESULT NativeTabContentsViewWin::OnMouseRange(UINT msg,
                                               WPARAM w_param,
                                               LPARAM l_param) {
  if (delegate_->IsShowingSadTab())
    return NativeWidgetWin::OnMouseRange(msg, w_param, l_param);

  switch (msg) {
    case WM_LBUTTONDOWN:
    case WM_MBUTTONDOWN:
    case WM_RBUTTONDOWN: {
      delegate_->OnNativeTabContentsViewMouseDown();
      break;
    }
    case WM_MOUSEMOVE:
      delegate_->OnNativeTabContentsViewMouseMove(true);
      break;
    default:
      break;
  }
  return 0;
}

// A message is reflected here from view().
// Return non-zero to indicate that it is handled here.
// Return 0 to allow view() to further process it.
LRESULT NativeTabContentsViewWin::OnReflectedMessage(UINT msg,
                                                     WPARAM w_param,
                                                     LPARAM l_param) {
  MSG* message = reinterpret_cast<MSG*>(l_param);
  switch (message->message) {
    case WM_MOUSEWHEEL:
      // This message is reflected from the view() to this window.
      if (GET_KEYSTATE_WPARAM(message->wParam) & MK_CONTROL) {
        delegate_->OnNativeTabContentsViewWheelZoom(
            GET_WHEEL_DELTA_WPARAM(message->wParam) > 0);
        return 1;
      }
      break;
    case WM_HSCROLL:
    case WM_VSCROLL:
      if (ScrollZoom(LOWORD(message->wParam)))
        return 1;
    default:
      break;
  }

  return 0;
}

void NativeTabContentsViewWin::OnVScroll(int scroll_type,
                                         short position,
                                         HWND scrollbar) {
  ScrollCommon(WM_VSCROLL, scroll_type, position, scrollbar);
}

void NativeTabContentsViewWin::OnWindowPosChanged(WINDOWPOS* window_pos) {
  if (window_pos->flags & SWP_HIDEWINDOW) {
    delegate_->OnNativeTabContentsViewHidden();
  } else {
    // The TabContents was shown by a means other than the user selecting a
    // Tab, e.g. the window was minimized then restored.
    if (window_pos->flags & SWP_SHOWWINDOW)
      delegate_->OnNativeTabContentsViewShown();

    // Unless we were specifically told not to size, cause the renderer to be
    // sized to the new bounds, which forces a repaint. Not required for the
    // simple minimize-restore case described above, for example, since the
    // size hasn't changed.
    if (!(window_pos->flags & SWP_NOSIZE)) {
      delegate_->OnNativeTabContentsViewSized(
          gfx::Size(window_pos->cx, window_pos->cy));
    }
  }
  NativeWidgetWin::OnWindowPosChanged(window_pos);
}

void NativeTabContentsViewWin::OnSize(UINT param, const CSize& size) {
  // NOTE: Because TabContentsViewViews handles OnWindowPosChanged without
  // calling DefWindowProc, OnSize is NOT called on window resize. This handler
  // is called only once when the window is created.

  // Don't call base class OnSize to avoid useless layout for 0x0 size.
  // We will get OnWindowPosChanged later and layout root view in WasSized.

  // Hack for ThinkPad touch-pad driver.
  // Set fake scrollbars so that we can get scroll messages,
  SCROLLINFO si = {0};
  si.cbSize = sizeof(si);
  si.fMask = SIF_ALL;

  si.nMin = 1;
  si.nMax = 100;
  si.nPage = 10;
  si.nPos = 50;

  ::SetScrollInfo(GetNativeView(), SB_HORZ, &si, FALSE);
  ::SetScrollInfo(GetNativeView(), SB_VERT, &si, FALSE);
}

LRESULT NativeTabContentsViewWin::OnNCCalcSize(BOOL w_param, LPARAM l_param) {
  // Hack for ThinkPad mouse wheel driver. We have set the fake scroll bars
  // to receive scroll messages from ThinkPad touch-pad driver. Suppress
  // painting of scrollbars by returning 0 size for them.
  return 0;
}

void NativeTabContentsViewWin::OnNCPaint(HRGN rgn) {
  // Suppress default WM_NCPAINT handling. We don't need to do anything
  // here since the view will draw everything correctly.
}

////////////////////////////////////////////////////////////////////////////////
// NativeTabContentsViewWin, private:

void NativeTabContentsViewWin::ScrollCommon(UINT message, int scroll_type,
                                            short position, HWND scrollbar) {
  // This window can receive scroll events as a result of the ThinkPad's
  // touch-pad scroll wheel emulation.
  if (!ScrollZoom(scroll_type)) {
    // Reflect scroll message to the view() to give it a chance
    // to process scrolling.
    SendMessage(delegate_->GetTabContents()->view()->GetContentNativeView(),
                message, MAKELONG(scroll_type, position),
                reinterpret_cast<LPARAM>(scrollbar));
  }
}

bool NativeTabContentsViewWin::ScrollZoom(int scroll_type) {
  // If ctrl is held, zoom the UI.  There are three issues with this:
  // 1) Should the event be eaten or forwarded to content?  We eat the event,
  //    which is like Firefox and unlike IE.
  // 2) Should wheel up zoom in or out?  We zoom in (increase font size), which
  //    is like IE and Google maps, but unlike Firefox.
  // 3) Should the mouse have to be over the content area?  We zoom as long as
  //    content has focus, although FF and IE require that the mouse is over
  //    content.  This is because all events get forwarded when content has
  //    focus.
  if (GetAsyncKeyState(VK_CONTROL) & 0x8000) {
    int distance = 0;
    switch (scroll_type) {
      case SB_LINEUP:
        distance = WHEEL_DELTA;
        break;
      case SB_LINEDOWN:
        distance = -WHEEL_DELTA;
        break;
        // TODO(joshia): Handle SB_PAGEUP, SB_PAGEDOWN, SB_THUMBPOSITION,
        // and SB_THUMBTRACK for completeness
      default:
        break;
    }

    delegate_->OnNativeTabContentsViewWheelZoom(distance > 0);
    return true;
  }
  return false;
}

////////////////////////////////////////////////////////////////////////////////
// NativeTabContentsView, public:

// static
NativeTabContentsView* NativeTabContentsView::CreateNativeTabContentsView(
    internal::NativeTabContentsViewDelegate* delegate) {
  return new NativeTabContentsViewWin(delegate);
}
<commit_msg>Use a Window instead of a Widget for the hidden tab host window.<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/views/tab_contents/native_tab_contents_view_win.h"

#include "chrome/browser/renderer_host/render_widget_host_view_win.h"
#include "chrome/browser/tab_contents/web_drop_target_win.h"
#include "chrome/browser/ui/views/tab_contents/native_tab_contents_view_delegate.h"
#include "chrome/browser/ui/views/tab_contents/tab_contents_drag_win.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "content/browser/tab_contents/tab_contents_view.h"
#include "views/widget/widget.h"

namespace {

// Tabs must be created as child widgets, otherwise they will be given
// a FocusManager which will conflict with the FocusManager of the
// window they eventually end up attached to.
//
// A tab will not have a parent HWND whenever it is not active in its
// host window - for example at creation time and when it's in the
// background, so we provide a default widget to host them.
//
// It may be tempting to use GetDesktopWindow() instead, but this is
// problematic as the shell sends messages to children of the desktop
// window that interact poorly with us.
//
// See: http://crbug.com/16476
class HiddenTabHostWindow : public views::Widget {
 public:
  static HWND Instance();

 private:
  HiddenTabHostWindow() {}

  ~HiddenTabHostWindow() {
    instance_ = NULL;
  }

  // Do nothing when asked to close.  External applications (notably
  // installers) try to close Chrome by sending WM_CLOSE to Chrome's
  // top level windows.  We don't want the tab host to close due to
  // those messages.  Instead the browser will close when the browser
  // window receives a WM_CLOSE.
  virtual void Close() OVERRIDE {}

  static HiddenTabHostWindow* instance_;

  DISALLOW_COPY_AND_ASSIGN(HiddenTabHostWindow);
};

HiddenTabHostWindow* HiddenTabHostWindow::instance_ = NULL;

HWND HiddenTabHostWindow::Instance() {
  if (instance_ == NULL) {
    instance_ = new HiddenTabHostWindow;
    // We don't want this widget to be closed automatically, this causes
    // problems in tests that close the last non-secondary window.
    instance_->set_is_secondary_widget(false);
    views::Widget::InitParams params(views::Widget::InitParams::TYPE_POPUP);
    instance_->Init(params);
    // If a background window requests focus, the hidden tab host will
    // be activated to focus the tab.  Disable the window to prevent
    // this.
    EnableWindow(instance_->GetNativeView(), FALSE);
  }

  return instance_->GetNativeView();
}
}  // namespace

////////////////////////////////////////////////////////////////////////////////
// NativeTabContentsViewWin, public:

NativeTabContentsViewWin::NativeTabContentsViewWin(
    internal::NativeTabContentsViewDelegate* delegate)
    : views::NativeWidgetWin(delegate->AsNativeWidgetDelegate()),
      delegate_(delegate) {
}

NativeTabContentsViewWin::~NativeTabContentsViewWin() {
  CloseNow();
}

TabContents* NativeTabContentsViewWin::GetTabContents() const {
  return delegate_->GetTabContents();
}

void NativeTabContentsViewWin::EndDragging() {
  delegate_->OnNativeTabContentsViewDraggingEnded();
  drag_handler_ = NULL;
}

////////////////////////////////////////////////////////////////////////////////
// NativeTabContentsViewWin, NativeTabContentsView implementation:

void NativeTabContentsViewWin::InitNativeTabContentsView() {
  views::Widget::InitParams params(views::Widget::InitParams::TYPE_CONTROL);
  params.native_widget = this;
  params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET;
  params.parent = HiddenTabHostWindow::Instance();
  GetWidget()->Init(params);

  // Remove the root view drop target so we can register our own.
  RevokeDragDrop(GetNativeView());
  drop_target_ = new WebDropTarget(GetNativeView(),
                                   delegate_->GetTabContents());
}

void NativeTabContentsViewWin::Unparent() {
  // Note that we do not DCHECK on focus_manager_ as it may be NULL when used
  // with an external tab container.
  views::Widget::ReparentNativeView(GetNativeView(),
                                    HiddenTabHostWindow::Instance());
}

RenderWidgetHostView* NativeTabContentsViewWin::CreateRenderWidgetHostView(
    RenderWidgetHost* render_widget_host) {
  RenderWidgetHostViewWin* view =
      new RenderWidgetHostViewWin(render_widget_host);
  view->CreateWnd(GetNativeView());
  view->ShowWindow(SW_SHOW);
  return view;
}

gfx::NativeWindow NativeTabContentsViewWin::GetTopLevelNativeWindow() const {
  return ::GetAncestor(GetNativeView(), GA_ROOT);
}

void NativeTabContentsViewWin::SetPageTitle(const std::wstring& title) {
  // It's possible to get this after the hwnd has been destroyed.
  if (GetNativeView())
    ::SetWindowText(GetNativeView(), title.c_str());
}

void NativeTabContentsViewWin::StartDragging(const WebDropData& drop_data,
                                             WebKit::WebDragOperationsMask ops,
                                             const SkBitmap& image,
                                             const gfx::Point& image_offset) {
  drag_handler_ = new TabContentsDragWin(this);
  drag_handler_->StartDragging(drop_data, ops, image, image_offset);
}

void NativeTabContentsViewWin::CancelDrag() {
  drag_handler_->CancelDrag();
}

bool NativeTabContentsViewWin::IsDoingDrag() const {
  return drag_handler_.get() != NULL;
}

void NativeTabContentsViewWin::SetDragCursor(
    WebKit::WebDragOperation operation) {
  drop_target_->set_drag_cursor(operation);
}

views::NativeWidget* NativeTabContentsViewWin::AsNativeWidget() {
  return this;
}

////////////////////////////////////////////////////////////////////////////////
// NativeTabContentsViewWin, views::NativeWidgetWin overrides:

void NativeTabContentsViewWin::OnDestroy() {
  if (drop_target_.get()) {
    RevokeDragDrop(GetNativeView());
    drop_target_ = NULL;
  }

  NativeWidgetWin::OnDestroy();
}

void NativeTabContentsViewWin::OnHScroll(int scroll_type,
                                         short position,
                                         HWND scrollbar) {
  ScrollCommon(WM_HSCROLL, scroll_type, position, scrollbar);
}

LRESULT NativeTabContentsViewWin::OnMouseRange(UINT msg,
                                               WPARAM w_param,
                                               LPARAM l_param) {
  if (delegate_->IsShowingSadTab())
    return NativeWidgetWin::OnMouseRange(msg, w_param, l_param);

  switch (msg) {
    case WM_LBUTTONDOWN:
    case WM_MBUTTONDOWN:
    case WM_RBUTTONDOWN: {
      delegate_->OnNativeTabContentsViewMouseDown();
      break;
    }
    case WM_MOUSEMOVE:
      delegate_->OnNativeTabContentsViewMouseMove(true);
      break;
    default:
      break;
  }
  return 0;
}

// A message is reflected here from view().
// Return non-zero to indicate that it is handled here.
// Return 0 to allow view() to further process it.
LRESULT NativeTabContentsViewWin::OnReflectedMessage(UINT msg,
                                                     WPARAM w_param,
                                                     LPARAM l_param) {
  MSG* message = reinterpret_cast<MSG*>(l_param);
  switch (message->message) {
    case WM_MOUSEWHEEL:
      // This message is reflected from the view() to this window.
      if (GET_KEYSTATE_WPARAM(message->wParam) & MK_CONTROL) {
        delegate_->OnNativeTabContentsViewWheelZoom(
            GET_WHEEL_DELTA_WPARAM(message->wParam) > 0);
        return 1;
      }
      break;
    case WM_HSCROLL:
    case WM_VSCROLL:
      if (ScrollZoom(LOWORD(message->wParam)))
        return 1;
    default:
      break;
  }

  return 0;
}

void NativeTabContentsViewWin::OnVScroll(int scroll_type,
                                         short position,
                                         HWND scrollbar) {
  ScrollCommon(WM_VSCROLL, scroll_type, position, scrollbar);
}

void NativeTabContentsViewWin::OnWindowPosChanged(WINDOWPOS* window_pos) {
  if (window_pos->flags & SWP_HIDEWINDOW) {
    delegate_->OnNativeTabContentsViewHidden();
  } else {
    // The TabContents was shown by a means other than the user selecting a
    // Tab, e.g. the window was minimized then restored.
    if (window_pos->flags & SWP_SHOWWINDOW)
      delegate_->OnNativeTabContentsViewShown();

    // Unless we were specifically told not to size, cause the renderer to be
    // sized to the new bounds, which forces a repaint. Not required for the
    // simple minimize-restore case described above, for example, since the
    // size hasn't changed.
    if (!(window_pos->flags & SWP_NOSIZE)) {
      delegate_->OnNativeTabContentsViewSized(
          gfx::Size(window_pos->cx, window_pos->cy));
    }
  }
  NativeWidgetWin::OnWindowPosChanged(window_pos);
}

void NativeTabContentsViewWin::OnSize(UINT param, const CSize& size) {
  // NOTE: Because TabContentsViewViews handles OnWindowPosChanged without
  // calling DefWindowProc, OnSize is NOT called on window resize. This handler
  // is called only once when the window is created.

  // Don't call base class OnSize to avoid useless layout for 0x0 size.
  // We will get OnWindowPosChanged later and layout root view in WasSized.

  // Hack for ThinkPad touch-pad driver.
  // Set fake scrollbars so that we can get scroll messages,
  SCROLLINFO si = {0};
  si.cbSize = sizeof(si);
  si.fMask = SIF_ALL;

  si.nMin = 1;
  si.nMax = 100;
  si.nPage = 10;
  si.nPos = 50;

  ::SetScrollInfo(GetNativeView(), SB_HORZ, &si, FALSE);
  ::SetScrollInfo(GetNativeView(), SB_VERT, &si, FALSE);
}

LRESULT NativeTabContentsViewWin::OnNCCalcSize(BOOL w_param, LPARAM l_param) {
  // Hack for ThinkPad mouse wheel driver. We have set the fake scroll bars
  // to receive scroll messages from ThinkPad touch-pad driver. Suppress
  // painting of scrollbars by returning 0 size for them.
  return 0;
}

void NativeTabContentsViewWin::OnNCPaint(HRGN rgn) {
  // Suppress default WM_NCPAINT handling. We don't need to do anything
  // here since the view will draw everything correctly.
}

////////////////////////////////////////////////////////////////////////////////
// NativeTabContentsViewWin, private:

void NativeTabContentsViewWin::ScrollCommon(UINT message, int scroll_type,
                                            short position, HWND scrollbar) {
  // This window can receive scroll events as a result of the ThinkPad's
  // touch-pad scroll wheel emulation.
  if (!ScrollZoom(scroll_type)) {
    // Reflect scroll message to the view() to give it a chance
    // to process scrolling.
    SendMessage(delegate_->GetTabContents()->view()->GetContentNativeView(),
                message, MAKELONG(scroll_type, position),
                reinterpret_cast<LPARAM>(scrollbar));
  }
}

bool NativeTabContentsViewWin::ScrollZoom(int scroll_type) {
  // If ctrl is held, zoom the UI.  There are three issues with this:
  // 1) Should the event be eaten or forwarded to content?  We eat the event,
  //    which is like Firefox and unlike IE.
  // 2) Should wheel up zoom in or out?  We zoom in (increase font size), which
  //    is like IE and Google maps, but unlike Firefox.
  // 3) Should the mouse have to be over the content area?  We zoom as long as
  //    content has focus, although FF and IE require that the mouse is over
  //    content.  This is because all events get forwarded when content has
  //    focus.
  if (GetAsyncKeyState(VK_CONTROL) & 0x8000) {
    int distance = 0;
    switch (scroll_type) {
      case SB_LINEUP:
        distance = WHEEL_DELTA;
        break;
      case SB_LINEDOWN:
        distance = -WHEEL_DELTA;
        break;
        // TODO(joshia): Handle SB_PAGEUP, SB_PAGEDOWN, SB_THUMBPOSITION,
        // and SB_THUMBTRACK for completeness
      default:
        break;
    }

    delegate_->OnNativeTabContentsViewWheelZoom(distance > 0);
    return true;
  }
  return false;
}

////////////////////////////////////////////////////////////////////////////////
// NativeTabContentsView, public:

// static
NativeTabContentsView* NativeTabContentsView::CreateNativeTabContentsView(
    internal::NativeTabContentsViewDelegate* delegate) {
  return new NativeTabContentsViewWin(delegate);
}
<|endoftext|>


<commit_before>// Copyright (c) 2012 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/views/website_settings/permission_selector_view.h"

#include "base/utf_string_conversions.h"
#include "chrome/browser/ui/website_settings/website_settings_ui.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/models/simple_menu_model.h"
#include "ui/gfx/image/image.h"
#include "ui/views/controls/button/menu_button.h"
#include "ui/views/controls/image_view.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/menu/menu_model_adapter.h"
#include "ui/views/controls/menu/menu_runner.h"
#include "ui/views/layout/grid_layout.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"

namespace {

// Left icon margin.
const int kPermissionIconMarginLeft = 6;
// The width of the column that contains the permissions icons.
const int kPermissionIconColumnWidth = 20;

// An array with |ContentSetting|s ordered by CommandID. The array is used to
// lookup a content setting for a given command id.
const ContentSetting kSettingsForCommandIDs[] = {
  CONTENT_SETTING_DEFAULT,  // COMMAND_SET_TO_DEFAULT
  CONTENT_SETTING_ALLOW,    // COMMAND_SET_TO_ALLOW
  CONTENT_SETTING_BLOCK,    // COMMAND_SET_TO_BLOCK
};

}  // namespace

namespace internal {

class PermissionMenuModel : public ui::SimpleMenuModel,
                            public ui::SimpleMenuModel::Delegate {
 public:
  PermissionMenuModel(ContentSettingsType site_permission,
                      ContentSetting default_setting,
                      ContentSetting current_setting,
                      PermissionSelectorView* selector);

  ContentSettingsType site_permission() const { return site_permission_; }
  ContentSetting default_setting() const { return default_setting_; }
  ContentSetting current_setting() const { return current_setting_; }

  // Overridden from ui::SimpleMenuModel::Delegate:
  virtual bool IsCommandIdChecked(int command_id) const OVERRIDE;
  virtual bool IsCommandIdEnabled(int command_id) const OVERRIDE;
  virtual bool GetAcceleratorForCommandId(
      int command_id,
      ui::Accelerator* accelerator) OVERRIDE;
  virtual void ExecuteCommand(int command_id) OVERRIDE;

 private:
  enum CommandID {
    COMMAND_SET_TO_DEFAULT,
    COMMAND_SET_TO_ALLOW,
    COMMAND_SET_TO_BLOCK,
  };

  // The site permission (the |ContentSettingsType|) for which the menu model
  // provides settings.
  ContentSettingsType site_permission_;

  // The global default setting for the |site_permission_|.
  ContentSetting default_setting_;

  // The currently active setting for the |site_permission|.
  ContentSetting current_setting_;

  // The |permission_selector_|s SelectionChanged method is called whenever the
  // |current_setting_| is changed.
  PermissionSelectorView* permission_selector_;  // Owned by views hierarchy.

  DISALLOW_COPY_AND_ASSIGN(PermissionMenuModel);
};

// The |PermissionMenuButton| provides a menu for selecting a setting a
// permissions type.
class PermissionMenuButton : public views::MenuButton,
                             public views::MenuButtonListener {
 public:
  // Creates a new |PermissionMenuButton| with the passed |text|. The ownership
  // of the |model| remains with the caller and is not transfered to the
  // |PermissionMenuButton|. If the |show_menu_marker| flag is true, then a
  // small icon is be displayed next to the button |text|, indicating that the
  // button opens a drop down menu.
  PermissionMenuButton(const string16& text,
                       PermissionMenuModel* model,
                       bool show_menu_marker);
  virtual ~PermissionMenuButton();

  // Overridden from views::MenuButton.
  virtual gfx::Size GetPreferredSize() OVERRIDE;

  // Overridden from views::TextButton.
  virtual void SetText(const string16& text) OVERRIDE;

 private:
  // Overridden from views::MenuButtonListener.
  virtual void OnMenuButtonClicked(View* source,
                                   const gfx::Point& point) OVERRIDE;

  PermissionMenuModel* menu_model_;  // Owned by |PermissionSelectorView|.
  scoped_ptr<views::MenuRunner> menu_runner_;

  DISALLOW_COPY_AND_ASSIGN(PermissionMenuButton);
};

///////////////////////////////////////////////////////////////////////////////
// PermissionMenuModel
///////////////////////////////////////////////////////////////////////////////

PermissionMenuModel::PermissionMenuModel(
    ContentSettingsType site_permission,
    ContentSetting default_setting,
    ContentSetting current_setting,
    PermissionSelectorView* parent)
    : ALLOW_THIS_IN_INITIALIZER_LIST(ui::SimpleMenuModel(this)),
      site_permission_(site_permission),
      default_setting_(default_setting),
      current_setting_(current_setting),
      permission_selector_(parent) {
  string16 label;
  switch (default_setting_) {
    case CONTENT_SETTING_ALLOW:
      label = l10n_util::GetStringUTF16(
          IDS_WEBSITE_SETTINGS_MENU_ITEM_DEFAULT_ALLOW);
      break;
    case CONTENT_SETTING_BLOCK:
      label = l10n_util::GetStringUTF16(
          IDS_WEBSITE_SETTINGS_MENU_ITEM_DEFAULT_BLOCK);
      break;
    case CONTENT_SETTING_ASK:
      label = l10n_util::GetStringUTF16(
          IDS_WEBSITE_SETTINGS_MENU_ITEM_DEFAULT_ASK);
      break;
    default:
      break;
  }
  AddCheckItem(COMMAND_SET_TO_DEFAULT, label);

  label = l10n_util::GetStringUTF16(
      IDS_WEBSITE_SETTINGS_MENU_ITEM_ALLOW);
  AddCheckItem(COMMAND_SET_TO_ALLOW, label);

  if (site_permission != CONTENT_SETTINGS_TYPE_FULLSCREEN) {
    label = l10n_util::GetStringUTF16(
        IDS_WEBSITE_SETTINGS_MENU_ITEM_BLOCK);
    AddCheckItem(COMMAND_SET_TO_BLOCK, label);
  }
}

bool PermissionMenuModel::IsCommandIdChecked(int command_id) const {
  return current_setting_ == kSettingsForCommandIDs[command_id];
}

bool PermissionMenuModel::IsCommandIdEnabled(int command_id) const {
  return true;
}

bool PermissionMenuModel::GetAcceleratorForCommandId(
    int command_id,
    ui::Accelerator* accelerator) {
  // Accelerators are not supported.
  return false;
}

void PermissionMenuModel::ExecuteCommand(int command_id) {
  current_setting_ = kSettingsForCommandIDs[command_id];
  permission_selector_->SelectionChanged();
}

///////////////////////////////////////////////////////////////////////////////
// PermissionMenuButton
///////////////////////////////////////////////////////////////////////////////

PermissionMenuButton::PermissionMenuButton(const string16& text,
                                           PermissionMenuModel* model,
                                           bool show_menu_marker)
    : ALLOW_THIS_IN_INITIALIZER_LIST(MenuButton(NULL, text, this,
                                                show_menu_marker)),
      menu_model_(model) {
  SetEnabledColor(ui::NativeTheme::instance()->GetSystemColor(
      ui::NativeTheme::kColorId_LabelEnabledColor));
  SetHoverColor(ui::NativeTheme::instance()->GetSystemColor(
      ui::NativeTheme::kColorId_LabelEnabledColor));
  SetDisabledColor(ui::NativeTheme::instance()->GetSystemColor(
      ui::NativeTheme::kColorId_LabelDisabledColor));
}

PermissionMenuButton::~PermissionMenuButton() {
}

gfx::Size PermissionMenuButton::GetPreferredSize() {
  gfx::Insets insets = GetInsets();
  // Scale the button to the current text size.
  gfx::Size prefsize(text_size_.width() + insets.width(),
                     text_size_.height() + insets.height());
  if (max_width_ > 0)
    prefsize.set_width(std::min(max_width_, prefsize.width()));
  if (show_menu_marker()) {
    prefsize.Enlarge(menu_marker()->width() +
                         views::MenuButton::kMenuMarkerPaddingLeft +
                         views::MenuButton::kMenuMarkerPaddingRight,
                     0);
  }
  return prefsize;
}

void PermissionMenuButton::SetText(const string16& text) {
  MenuButton::SetText(text);
  SizeToPreferredSize();
}

void PermissionMenuButton::OnMenuButtonClicked(View* source,
                                               const gfx::Point& point) {
  views::MenuModelAdapter menu_model_adapter(menu_model_);
  menu_runner_.reset(new views::MenuRunner(menu_model_adapter.CreateMenu()));

  gfx::Point p(point);
  p.Offset(-source->width(), 0);
  if (menu_runner_->RunMenuAt(
          source->GetWidget()->GetTopLevelWidget(),
          this,
          gfx::Rect(p, gfx::Size()),
          views::MenuItemView::TOPLEFT,
          views::MenuRunner::HAS_MNEMONICS) == views::MenuRunner::MENU_DELETED)
    return;
}

}  // namespace internal

///////////////////////////////////////////////////////////////////////////////
// PermissionSelectorView
///////////////////////////////////////////////////////////////////////////////

PermissionSelectorView::PermissionSelectorView(
    ContentSettingsType type,
    ContentSetting default_setting,
    ContentSetting current_setting,
    content_settings::SettingSource source)
    : icon_(NULL),
      menu_button_(NULL) {
  views::GridLayout* layout = new views::GridLayout(this);
  SetLayoutManager(layout);
  const int column_set_id = 0;
  views::ColumnSet* column_set = layout->AddColumnSet(column_set_id);
  column_set->AddColumn(views::GridLayout::FILL,
                        views::GridLayout::FILL,
                        1,
                        views::GridLayout::FIXED,
                        kPermissionIconColumnWidth,
                        0);
  column_set->AddPaddingColumn(0, kPermissionIconMarginLeft);
  column_set->AddColumn(views::GridLayout::FILL,
                        views::GridLayout::FILL,
                        1,
                        views::GridLayout::USE_PREF,
                        0,
                        0);
  column_set->AddColumn(views::GridLayout::FILL,
                        views::GridLayout::FILL,
                        1,
                        views::GridLayout::USE_PREF,
                        0,
                        0);

  layout->StartRow(1, column_set_id);
  // Create the permission icon.
  icon_ = new views::ImageView();
  ContentSetting setting = current_setting;
  if (setting == CONTENT_SETTING_DEFAULT)
    setting = default_setting;
  const gfx::Image& image = WebsiteSettingsUI::GetPermissionIcon(type, setting);
  icon_->SetImage(image.ToImageSkia());
  layout->AddView(icon_,
                  1,
                  1,
                  views::GridLayout::CENTER,
                  views::GridLayout::CENTER);
  // Create the label that displays the permission type.
  views::Label* label = new views::Label(
      l10n_util::GetStringFUTF16(
          IDS_WEBSITE_SETTINGS_PERMISSION_TYPE,
          WebsiteSettingsUI::PermissionTypeToUIString(type)));
  layout->AddView(label,
                  1,
                  1,
                  views::GridLayout::LEADING,
                  views::GridLayout::CENTER);
  // Create the permission menu button.
  menu_button_model_.reset(new internal::PermissionMenuModel(
      type, default_setting, current_setting, this));
  bool button_enabled = source == content_settings::SETTING_SOURCE_USER;
  menu_button_ = new internal::PermissionMenuButton(
      WebsiteSettingsUI::PermissionActionToUIString(current_setting,
                                                    default_setting,
                                                    source),
      menu_button_model_.get(),
      button_enabled);
  menu_button_->SetEnabled(button_enabled);
  layout->AddView(menu_button_);
}

void PermissionSelectorView::AddObserver(
    PermissionSelectorViewObserver* observer) {
  observer_list_.AddObserver(observer);
}

void PermissionSelectorView::SelectionChanged() {
  // Update the icon to reflect the new setting.
  ContentSetting effective_setting = menu_button_model_->current_setting();
  if (effective_setting == CONTENT_SETTING_DEFAULT)
    effective_setting = menu_button_model_->default_setting();
  const gfx::Image& image = WebsiteSettingsUI::GetPermissionIcon(
      menu_button_model_->site_permission(), effective_setting);
  icon_->SetImage(image.ToImageSkia());

  // Update the menu button text to reflect the new setting.
  menu_button_->SetText(WebsiteSettingsUI::PermissionActionToUIString(
      menu_button_model_->current_setting(),
      menu_button_model_->default_setting(),
      content_settings::SETTING_SOURCE_USER));

  FOR_EACH_OBSERVER(PermissionSelectorViewObserver,
                    observer_list_,
                    OnPermissionChanged(this));
}

ContentSetting PermissionSelectorView::GetSelectedSetting() const {
  return menu_button_model_->current_setting();
}

ContentSettingsType PermissionSelectorView::GetPermissionType() const {
  return menu_button_model_->site_permission();
}

void PermissionSelectorView::ChildPreferredSizeChanged(View* child) {
  SizeToPreferredSize();
  // FIXME: The parent is only a plain |View| that is used as a
  // container/box/panel. The SizeToPreferredSize method of the parent is
  // called here directly in order not to implement a custom |View| class with
  // its own implementation of the ChildPreferredSizeChanged method.
  parent()->SizeToPreferredSize();
}

PermissionSelectorView::~PermissionSelectorView() {
}
<commit_msg>[Views] Make the permissions menus on the Website Settings UI focusable by the TAB key and provuide accasability information.<commit_after>// Copyright (c) 2012 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/views/website_settings/permission_selector_view.h"

#include "base/utf_string_conversions.h"
#include "chrome/browser/ui/website_settings/website_settings_ui.h"
#include "grit/generated_resources.h"
#include "ui/base/accessibility/accessible_view_state.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/models/simple_menu_model.h"
#include "ui/gfx/image/image.h"
#include "ui/views/controls/button/menu_button.h"
#include "ui/views/controls/image_view.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/menu/menu_model_adapter.h"
#include "ui/views/controls/menu/menu_runner.h"
#include "ui/views/layout/grid_layout.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"

namespace {

// Left icon margin.
const int kPermissionIconMarginLeft = 6;
// The width of the column that contains the permissions icons.
const int kPermissionIconColumnWidth = 20;

// An array with |ContentSetting|s ordered by CommandID. The array is used to
// lookup a content setting for a given command id.
const ContentSetting kSettingsForCommandIDs[] = {
  CONTENT_SETTING_DEFAULT,  // COMMAND_SET_TO_DEFAULT
  CONTENT_SETTING_ALLOW,    // COMMAND_SET_TO_ALLOW
  CONTENT_SETTING_BLOCK,    // COMMAND_SET_TO_BLOCK
};

}  // namespace

namespace internal {

class PermissionMenuModel : public ui::SimpleMenuModel,
                            public ui::SimpleMenuModel::Delegate {
 public:
  PermissionMenuModel(ContentSettingsType site_permission,
                      ContentSetting default_setting,
                      ContentSetting current_setting,
                      PermissionSelectorView* selector);

  ContentSettingsType site_permission() const { return site_permission_; }
  ContentSetting default_setting() const { return default_setting_; }
  ContentSetting current_setting() const { return current_setting_; }

  // Overridden from ui::SimpleMenuModel::Delegate:
  virtual bool IsCommandIdChecked(int command_id) const OVERRIDE;
  virtual bool IsCommandIdEnabled(int command_id) const OVERRIDE;
  virtual bool GetAcceleratorForCommandId(
      int command_id,
      ui::Accelerator* accelerator) OVERRIDE;
  virtual void ExecuteCommand(int command_id) OVERRIDE;

 private:
  enum CommandID {
    COMMAND_SET_TO_DEFAULT,
    COMMAND_SET_TO_ALLOW,
    COMMAND_SET_TO_BLOCK,
  };

  // The site permission (the |ContentSettingsType|) for which the menu model
  // provides settings.
  ContentSettingsType site_permission_;

  // The global default setting for the |site_permission_|.
  ContentSetting default_setting_;

  // The currently active setting for the |site_permission|.
  ContentSetting current_setting_;

  // The |permission_selector_|s SelectionChanged method is called whenever the
  // |current_setting_| is changed.
  PermissionSelectorView* permission_selector_;  // Owned by views hierarchy.

  DISALLOW_COPY_AND_ASSIGN(PermissionMenuModel);
};

// The |PermissionMenuButton| provides a menu for selecting a setting a
// permissions type.
class PermissionMenuButton : public views::MenuButton,
                             public views::MenuButtonListener {
 public:
  // Creates a new |PermissionMenuButton| with the passed |text|. The ownership
  // of the |model| remains with the caller and is not transfered to the
  // |PermissionMenuButton|. If the |show_menu_marker| flag is true, then a
  // small icon is be displayed next to the button |text|, indicating that the
  // button opens a drop down menu.
  PermissionMenuButton(const string16& text,
                       PermissionMenuModel* model,
                       bool show_menu_marker);
  virtual ~PermissionMenuButton();

  // Overridden from views::MenuButton.
  virtual gfx::Size GetPreferredSize() OVERRIDE;

  // Overridden from views::TextButton.
  virtual void SetText(const string16& text) OVERRIDE;

  // Overridden from views::View.
  virtual void GetAccessibleState(ui::AccessibleViewState* state) OVERRIDE;

 private:
  // Overridden from views::MenuButtonListener.
  virtual void OnMenuButtonClicked(View* source,
                                   const gfx::Point& point) OVERRIDE;

  PermissionMenuModel* menu_model_;  // Owned by |PermissionSelectorView|.
  scoped_ptr<views::MenuRunner> menu_runner_;

  DISALLOW_COPY_AND_ASSIGN(PermissionMenuButton);
};

///////////////////////////////////////////////////////////////////////////////
// PermissionMenuModel
///////////////////////////////////////////////////////////////////////////////

PermissionMenuModel::PermissionMenuModel(
    ContentSettingsType site_permission,
    ContentSetting default_setting,
    ContentSetting current_setting,
    PermissionSelectorView* parent)
    : ALLOW_THIS_IN_INITIALIZER_LIST(ui::SimpleMenuModel(this)),
      site_permission_(site_permission),
      default_setting_(default_setting),
      current_setting_(current_setting),
      permission_selector_(parent) {
  string16 label;
  switch (default_setting_) {
    case CONTENT_SETTING_ALLOW:
      label = l10n_util::GetStringUTF16(
          IDS_WEBSITE_SETTINGS_MENU_ITEM_DEFAULT_ALLOW);
      break;
    case CONTENT_SETTING_BLOCK:
      label = l10n_util::GetStringUTF16(
          IDS_WEBSITE_SETTINGS_MENU_ITEM_DEFAULT_BLOCK);
      break;
    case CONTENT_SETTING_ASK:
      label = l10n_util::GetStringUTF16(
          IDS_WEBSITE_SETTINGS_MENU_ITEM_DEFAULT_ASK);
      break;
    default:
      break;
  }
  AddCheckItem(COMMAND_SET_TO_DEFAULT, label);

  label = l10n_util::GetStringUTF16(
      IDS_WEBSITE_SETTINGS_MENU_ITEM_ALLOW);
  AddCheckItem(COMMAND_SET_TO_ALLOW, label);

  if (site_permission != CONTENT_SETTINGS_TYPE_FULLSCREEN) {
    label = l10n_util::GetStringUTF16(
        IDS_WEBSITE_SETTINGS_MENU_ITEM_BLOCK);
    AddCheckItem(COMMAND_SET_TO_BLOCK, label);
  }
}

bool PermissionMenuModel::IsCommandIdChecked(int command_id) const {
  return current_setting_ == kSettingsForCommandIDs[command_id];
}

bool PermissionMenuModel::IsCommandIdEnabled(int command_id) const {
  return true;
}

bool PermissionMenuModel::GetAcceleratorForCommandId(
    int command_id,
    ui::Accelerator* accelerator) {
  // Accelerators are not supported.
  return false;
}

void PermissionMenuModel::ExecuteCommand(int command_id) {
  current_setting_ = kSettingsForCommandIDs[command_id];
  permission_selector_->SelectionChanged();
}

///////////////////////////////////////////////////////////////////////////////
// PermissionMenuButton
///////////////////////////////////////////////////////////////////////////////

PermissionMenuButton::PermissionMenuButton(const string16& text,
                                           PermissionMenuModel* model,
                                           bool show_menu_marker)
    : ALLOW_THIS_IN_INITIALIZER_LIST(MenuButton(NULL, text, this,
                                                show_menu_marker)),
      menu_model_(model) {
  SetEnabledColor(ui::NativeTheme::instance()->GetSystemColor(
      ui::NativeTheme::kColorId_LabelEnabledColor));
  SetHoverColor(ui::NativeTheme::instance()->GetSystemColor(
      ui::NativeTheme::kColorId_LabelEnabledColor));
  SetDisabledColor(ui::NativeTheme::instance()->GetSystemColor(
      ui::NativeTheme::kColorId_LabelDisabledColor));
}

PermissionMenuButton::~PermissionMenuButton() {
}

gfx::Size PermissionMenuButton::GetPreferredSize() {
  gfx::Insets insets = GetInsets();
  // Scale the button to the current text size.
  gfx::Size prefsize(text_size_.width() + insets.width(),
                     text_size_.height() + insets.height());
  if (max_width_ > 0)
    prefsize.set_width(std::min(max_width_, prefsize.width()));
  if (show_menu_marker()) {
    prefsize.Enlarge(menu_marker()->width() +
                         views::MenuButton::kMenuMarkerPaddingLeft +
                         views::MenuButton::kMenuMarkerPaddingRight,
                     0);
  }
  return prefsize;
}

void PermissionMenuButton::SetText(const string16& text) {
  MenuButton::SetText(text);
  SizeToPreferredSize();
}

void PermissionMenuButton::GetAccessibleState(ui::AccessibleViewState* state) {
  MenuButton::GetAccessibleState(state);
  state->value = text();
}

void PermissionMenuButton::OnMenuButtonClicked(View* source,
                                               const gfx::Point& point) {
  views::MenuModelAdapter menu_model_adapter(menu_model_);
  menu_runner_.reset(new views::MenuRunner(menu_model_adapter.CreateMenu()));

  gfx::Point p(point);
  p.Offset(-source->width(), 0);
  if (menu_runner_->RunMenuAt(
          source->GetWidget()->GetTopLevelWidget(),
          this,
          gfx::Rect(p, gfx::Size()),
          views::MenuItemView::TOPLEFT,
          views::MenuRunner::HAS_MNEMONICS) == views::MenuRunner::MENU_DELETED)
    return;
}

}  // namespace internal

///////////////////////////////////////////////////////////////////////////////
// PermissionSelectorView
///////////////////////////////////////////////////////////////////////////////

PermissionSelectorView::PermissionSelectorView(
    ContentSettingsType type,
    ContentSetting default_setting,
    ContentSetting current_setting,
    content_settings::SettingSource source)
    : icon_(NULL),
      menu_button_(NULL) {
  views::GridLayout* layout = new views::GridLayout(this);
  SetLayoutManager(layout);
  const int column_set_id = 0;
  views::ColumnSet* column_set = layout->AddColumnSet(column_set_id);
  column_set->AddColumn(views::GridLayout::FILL,
                        views::GridLayout::FILL,
                        1,
                        views::GridLayout::FIXED,
                        kPermissionIconColumnWidth,
                        0);
  column_set->AddPaddingColumn(0, kPermissionIconMarginLeft);
  column_set->AddColumn(views::GridLayout::FILL,
                        views::GridLayout::FILL,
                        1,
                        views::GridLayout::USE_PREF,
                        0,
                        0);
  column_set->AddColumn(views::GridLayout::FILL,
                        views::GridLayout::FILL,
                        1,
                        views::GridLayout::USE_PREF,
                        0,
                        0);

  layout->StartRow(1, column_set_id);
  // Create the permission icon.
  icon_ = new views::ImageView();
  ContentSetting setting = current_setting;
  if (setting == CONTENT_SETTING_DEFAULT)
    setting = default_setting;
  const gfx::Image& image = WebsiteSettingsUI::GetPermissionIcon(type, setting);
  icon_->SetImage(image.ToImageSkia());
  layout->AddView(icon_,
                  1,
                  1,
                  views::GridLayout::CENTER,
                  views::GridLayout::CENTER);
  // Create the label that displays the permission type.
  views::Label* label = new views::Label(
      l10n_util::GetStringFUTF16(
          IDS_WEBSITE_SETTINGS_PERMISSION_TYPE,
          WebsiteSettingsUI::PermissionTypeToUIString(type)));
  layout->AddView(label,
                  1,
                  1,
                  views::GridLayout::LEADING,
                  views::GridLayout::CENTER);
  // Create the permission menu button.
  menu_button_model_.reset(new internal::PermissionMenuModel(
      type, default_setting, current_setting, this));
  bool button_enabled = source == content_settings::SETTING_SOURCE_USER;
  menu_button_ = new internal::PermissionMenuButton(
      WebsiteSettingsUI::PermissionActionToUIString(current_setting,
                                                    default_setting,
                                                    source),
      menu_button_model_.get(),
      button_enabled);
  menu_button_->SetEnabled(button_enabled);
  menu_button_->set_focusable(button_enabled);
  menu_button_->SetAccessibleName(
      WebsiteSettingsUI::PermissionTypeToUIString(type));
  layout->AddView(menu_button_);
}

void PermissionSelectorView::AddObserver(
    PermissionSelectorViewObserver* observer) {
  observer_list_.AddObserver(observer);
}

void PermissionSelectorView::SelectionChanged() {
  // Update the icon to reflect the new setting.
  ContentSetting effective_setting = menu_button_model_->current_setting();
  if (effective_setting == CONTENT_SETTING_DEFAULT)
    effective_setting = menu_button_model_->default_setting();
  const gfx::Image& image = WebsiteSettingsUI::GetPermissionIcon(
      menu_button_model_->site_permission(), effective_setting);
  icon_->SetImage(image.ToImageSkia());

  // Update the menu button text to reflect the new setting.
  menu_button_->SetText(WebsiteSettingsUI::PermissionActionToUIString(
      menu_button_model_->current_setting(),
      menu_button_model_->default_setting(),
      content_settings::SETTING_SOURCE_USER));

  FOR_EACH_OBSERVER(PermissionSelectorViewObserver,
                    observer_list_,
                    OnPermissionChanged(this));
}

ContentSetting PermissionSelectorView::GetSelectedSetting() const {
  return menu_button_model_->current_setting();
}

ContentSettingsType PermissionSelectorView::GetPermissionType() const {
  return menu_button_model_->site_permission();
}

void PermissionSelectorView::ChildPreferredSizeChanged(View* child) {
  SizeToPreferredSize();
  // FIXME: The parent is only a plain |View| that is used as a
  // container/box/panel. The SizeToPreferredSize method of the parent is
  // called here directly in order not to implement a custom |View| class with
  // its own implementation of the ChildPreferredSizeChanged method.
  parent()->SizeToPreferredSize();
}

PermissionSelectorView::~PermissionSelectorView() {
}
<|endoftext|>


<commit_before>/*
  Copyright (C) 2016 Michal Kosciesza <michal@mkiol.net>

  This file is part of Zimpedia application.

  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 <QDir>
#include <QFileInfoList>
#include <QFile>
#include <QStandardPaths>

#include "filemodel.h"

FileFinder::FileFinder(QObject *parent) : QThread(parent)
{
}

void FileFinder::run()
{
    // Start search for ZIM files
    const QStringList homeLocation = QStandardPaths::standardLocations(QStandardPaths::HomeLocation);
    QString homePath = homeLocation.isEmpty() ? "/home/nemo" : homeLocation.first();
    findFiles(homePath);
}

void FileFinder::findFiles(const QString &dirName)
{
    QDir dir(dirName);

    //qDebug() << "dirName" << dirName;

    if (dir.exists(dirName)) {
        QFileInfoList infoList = dir.entryInfoList(QStringList("*.zim"),QDir::NoDotAndDotDot | QDir::System | QDir::Hidden  | QDir::AllDirs | QDir::Files, QDir::DirsFirst);

        Q_FOREACH(QFileInfo info, infoList) {
            if (info.isDir())
                findFiles(info.absoluteFilePath());
            else
                emit fileFound(info);
        }
    }
}

FileModel::FileModel(QObject *parent) :
    ListModel(new FileItem, parent), finder(parent)
{
    connect(&finder, SIGNAL(fileFound(QFileInfo)), this, SLOT(fileFoundHandler(QFileInfo)));
    connect(&finder, SIGNAL(finished()), this, SLOT(finderStatusHandler()));
    connect(&finder, SIGNAL(started()), this, SLOT(finderStatusHandler()));
    finder.start(QThread::IdlePriority);
}

bool FileModel::getSearching()
{
    return finder.isRunning();
}

void FileModel::fileFoundHandler(const QFileInfo &fileInfo)
{
    appendRow(new FileItem(fileInfo.absoluteFilePath(), fileInfo.fileName(), fileInfo.filePath()));
}

void FileModel::finderStatusHandler()
{
    emit searchingChanged();
}

void FileModel::clear()
{
    if(rowCount()>0) removeRows(0,rowCount());
}

FileItem::FileItem(const QString &id,
                   const QString &name,
                   const QString &dir,
                   QObject *parent) :
    ListItem(parent),
    m_id(id),
    m_name(name),
    m_dir(dir)
{}

QHash<int, QByteArray> FileItem::roleNames() const
{
    QHash<int, QByteArray> names;
    names[IdRole] = "id";
    names[NameRole] = "name";
    names[DirRole] = "dir";
    return names;
}

QVariant FileItem::data(int role) const
{
    switch(role) {
    case IdRole:
        return id();
    case NameRole:
        return name();
    case DirRole:
        return dir();
    default:
        return QVariant();
    }
}

<commit_msg>SD card dir as possible ZIM files location<commit_after>/*
  Copyright (C) 2016 Michal Kosciesza <michal@mkiol.net>

  This file is part of Zimpedia application.

  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 <QDir>
#include <QFileInfoList>
#include <QFile>
#include <QStandardPaths>

#include "filemodel.h"

FileFinder::FileFinder(QObject *parent) : QThread(parent)
{
}

void FileFinder::run()
{
    // Start search for ZIM files

    // All dirs under home directory
    const QStringList homeLocation = QStandardPaths::standardLocations(QStandardPaths::HomeLocation);
    findFiles(homeLocation.isEmpty() ? "/home/nemo" : homeLocation.first());

    // All dirs on SD card
    findFiles("/media/sdcard");
}

void FileFinder::findFiles(const QString &dirName)
{
    QDir dir(dirName);

    //qDebug() << "dirName" << dirName;

    if (dir.exists(dirName)) {
        QFileInfoList infoList = dir.entryInfoList(QStringList("*.zim"),QDir::NoDotAndDotDot | QDir::System | QDir::Hidden  | QDir::AllDirs | QDir::Files, QDir::DirsFirst);

        Q_FOREACH(QFileInfo info, infoList) {
            if (info.isDir())
                findFiles(info.absoluteFilePath());
            else
                emit fileFound(info);
        }
    }
}

FileModel::FileModel(QObject *parent) :
    ListModel(new FileItem, parent), finder(parent)
{
    connect(&finder, SIGNAL(fileFound(QFileInfo)), this, SLOT(fileFoundHandler(QFileInfo)));
    connect(&finder, SIGNAL(finished()), this, SLOT(finderStatusHandler()));
    connect(&finder, SIGNAL(started()), this, SLOT(finderStatusHandler()));
    finder.start(QThread::IdlePriority);
}

bool FileModel::getSearching()
{
    return finder.isRunning();
}

void FileModel::fileFoundHandler(const QFileInfo &fileInfo)
{
    appendRow(new FileItem(fileInfo.absoluteFilePath(), fileInfo.fileName(), fileInfo.filePath()));
}

void FileModel::finderStatusHandler()
{
    emit searchingChanged();
}

void FileModel::clear()
{
    if(rowCount()>0) removeRows(0,rowCount());
}

FileItem::FileItem(const QString &id,
                   const QString &name,
                   const QString &dir,
                   QObject *parent) :
    ListItem(parent),
    m_id(id),
    m_name(name),
    m_dir(dir)
{}

QHash<int, QByteArray> FileItem::roleNames() const
{
    QHash<int, QByteArray> names;
    names[IdRole] = "id";
    names[NameRole] = "name";
    names[DirRole] = "dir";
    return names;
}

QVariant FileItem::data(int role) const
{
    switch(role) {
    case IdRole:
        return id();
    case NameRole:
        return name();
    case DirRole:
        return dir();
    default:
        return QVariant();
    }
}

<|endoftext|>


<commit_before>#include <stdio.h>

#include <rtl/process.h>
#include <rtl/bootstrap.hxx>
#include <rtl/string.hxx>
#include <rtl/byteseq.hxx>

#include <osl/process.h>

using namespace ::rtl;

int main( int argc, char *argv[] )
{
    sal_Int32 nCount = rtl_getAppCommandArgCount();

#if OSL_DEBUG_LEVEL > 1
    fprintf( stdout, "rtl-commandargs (%d) real args:%i ", nCount, argc);
    for( sal_Int32 i = 0 ; i < nCount ; i ++ )
    {
        OUString data;
        rtl_getAppCommandArg( i , &(data.pData) );
        OString o = OUStringToOString( data, RTL_TEXTENCODING_ASCII_US );
        fprintf( stdout, " %s", o.getStr() );
    }
    fprintf( stdout, "\n" );
#endif

    if( nCount == 0 )
    {
        printf( "usage : testbootstrap <checkedValueOfMyBootstrapValue>\n" );
          exit( 1 );
    }

    OUString iniName;
    Bootstrap::get(OUString(RTL_CONSTASCII_USTRINGPARAM("iniName")), iniName, OUString());

#if OSL_DEBUG_LEVEL > 1
     if(iniName.getLength())
    {
        OString tmp_iniName = OUStringToOString(iniName, RTL_TEXTENCODING_ASCII_US);
        fprintf(stderr, "using ini: %s\n", tmp_iniName.getStr());
    }
#endif

    Bootstrap bootstrap(iniName);

    OUString name( RTL_CONSTASCII_USTRINGPARAM( "MYBOOTSTRAPTESTVALUE" ));
    OUString myDefault( RTL_CONSTASCII_USTRINGPARAM("$Default"));

    OUString value;
    sal_Bool useDefault;

    OUString aDummy;
    useDefault = bootstrap.getFrom(OUString(RTL_CONSTASCII_USTRINGPARAM("USEDEFAULT")), aDummy);

    sal_Bool result = sal_False;
    sal_Bool found  = sal_True;

    if(useDefault)
        bootstrap.getFrom(name, value, myDefault);

    else
        found = bootstrap.getFrom(name, value);

    if(found)
    {
        OUString para(OUString::createFromAscii( argv[1] ));

        result = para == value;

        if(!result)
        {
            OString para_tmp = OUStringToOString(para, RTL_TEXTENCODING_ASCII_US);
            OString value_tmp = OUStringToOString(value, RTL_TEXTENCODING_ASCII_US);

            fprintf(stderr, "para(%s) != value(%s)\n", para_tmp.getStr(), value_tmp.getStr());
        }
    }
    else
        fprintf(stderr, "bootstrap parameter couldn't be found\n");

    // test the default case
    name = OUString( RTL_CONSTASCII_USTRINGPARAM( "no_one_has_set_this_name" ) );
      OSL_ASSERT( ! bootstrap.getFrom( name, value ) );
    result = result && !bootstrap.getFrom( name, value );

    myDefault = OUString( RTL_CONSTASCII_USTRINGPARAM( "1" ) );
    OUString myDefault2 = OUString( RTL_CONSTASCII_USTRINGPARAM( "2" ) );

    bootstrap.getFrom( name, value, myDefault );
      OSL_ASSERT( value == myDefault );
    result = result && (value == myDefault);

    bootstrap.getFrom( name, value, myDefault2 );
      OSL_ASSERT( value == myDefault2 );
    result = result && (value == myDefault2);

    return result;
}
<commit_msg>INTEGRATION: CWS valgrind02 (1.8.234); FILE MERGED 2004/10/18 17:30:52 mhu 1.8.234.1: #i35209# Added call to 'osl_setCommandArgs()'.<commit_after>#include <stdio.h>

#include <rtl/process.h>
#include <rtl/bootstrap.hxx>
#include <rtl/string.hxx>
#include <rtl/byteseq.hxx>

#include <osl/process.h>

using namespace ::rtl;

int main( int argc, char *argv[] )
{
    osl_setCommandArgs (argc, argv);

    sal_Int32 nCount = rtl_getAppCommandArgCount();

#if OSL_DEBUG_LEVEL > 1
    fprintf( stdout, "rtl-commandargs (%d) real args:%i ", nCount, argc);
    for( sal_Int32 i = 0 ; i < nCount ; i ++ )
    {
        OUString data;
        rtl_getAppCommandArg( i , &(data.pData) );
        OString o = OUStringToOString( data, RTL_TEXTENCODING_ASCII_US );
        fprintf( stdout, " %s", o.getStr() );
    }
    fprintf( stdout, "\n" );
#endif

    if( nCount == 0 )
    {
        printf( "usage : testbootstrap <checkedValueOfMyBootstrapValue>\n" );
          exit( 1 );
    }

    OUString iniName;
    Bootstrap::get(OUString(RTL_CONSTASCII_USTRINGPARAM("iniName")), iniName, OUString());

#if OSL_DEBUG_LEVEL > 1
     if(iniName.getLength())
    {
        OString tmp_iniName = OUStringToOString(iniName, RTL_TEXTENCODING_ASCII_US);
        fprintf(stderr, "using ini: %s\n", tmp_iniName.getStr());
    }
#endif

    Bootstrap bootstrap(iniName);

    OUString name( RTL_CONSTASCII_USTRINGPARAM( "MYBOOTSTRAPTESTVALUE" ));
    OUString myDefault( RTL_CONSTASCII_USTRINGPARAM("$Default"));

    OUString value;
    sal_Bool useDefault;

    OUString aDummy;
    useDefault = bootstrap.getFrom(OUString(RTL_CONSTASCII_USTRINGPARAM("USEDEFAULT")), aDummy);

    sal_Bool result = sal_False;
    sal_Bool found  = sal_True;

    if(useDefault)
        bootstrap.getFrom(name, value, myDefault);

    else
        found = bootstrap.getFrom(name, value);

    if(found)
    {
        OUString para(OUString::createFromAscii( argv[1] ));

        result = para == value;

        if(!result)
        {
            OString para_tmp = OUStringToOString(para, RTL_TEXTENCODING_ASCII_US);
            OString value_tmp = OUStringToOString(value, RTL_TEXTENCODING_ASCII_US);

            fprintf(stderr, "para(%s) != value(%s)\n", para_tmp.getStr(), value_tmp.getStr());
        }
    }
    else
        fprintf(stderr, "bootstrap parameter couldn't be found\n");

    // test the default case
    name = OUString( RTL_CONSTASCII_USTRINGPARAM( "no_one_has_set_this_name" ) );
      OSL_ASSERT( ! bootstrap.getFrom( name, value ) );
    result = result && !bootstrap.getFrom( name, value );

    myDefault = OUString( RTL_CONSTASCII_USTRINGPARAM( "1" ) );
    OUString myDefault2 = OUString( RTL_CONSTASCII_USTRINGPARAM( "2" ) );

    bootstrap.getFrom( name, value, myDefault );
      OSL_ASSERT( value == myDefault );
    result = result && (value == myDefault);

    bootstrap.getFrom( name, value, myDefault2 );
      OSL_ASSERT( value == myDefault2 );
    result = result && (value == myDefault2);

    return result;
}
<|endoftext|>


<commit_before>/*
   Includes the Model and IModelObserver class declarations.

   The Model has the items necessary to construct a modified OptiX image.

   In normal use, one or more IModelObserver objects are registered
   to the model.  Specific observers or viewers may inherit from
   IModelObservers.

   A controller updates the model and calls the model notifyObservers
   function which calls the modelUpdated function of each of the
   observers registered to the model.

*/

#pragma once

#include <set>
#include <vector>
#include <ostream>

namespace grt {

	class Position
	{
		public:
			float x;
			float y;
			float z;

			friend std::ostream & operator<<(std::ostream & _out, const Position & pos)
			{
				_out << "position: x= "  << pos.x << ", y= " << pos.y << ", z= " << pos.z;
				return _out;
			}
	};

	class Color
	{
		public:
			float r;
			float g;
			float b;

			friend std::ostream & operator<<(std::ostream & _out, const Color & c)
			{
				_out << "color: r=" << c.r << ", g=" << c.g << ", b= " << c.b;
				return _out;
			}
	};

	class Light
	{
		public:
			Position position; // x, y, z position
			Color color; // R G B color

			friend std::ostream & operator<<(std::ostream & _out, const Light & light)
			{
				_out << "Light: " << light.position << " " << light.color;
				return _out;
			}
	};

	class Camera
	{
		public:
			Position position;
			float fieldOfView;
	};

	// May become a shape
	class Box
	{
		public:
			Position minPosition;
			Position maxPosition;
			std::string material;
			friend std::ostream & operator<<(std::ostream & _out, const Box & box)
			{
				_out << "minPosition= " << box.minPosition << ", maxPosition= "<<box.maxPosition << ", material= " << box.material;
				return _out;
			}
	};

	// May become a shape
	class Sphere
	{
		public:
			Position position;
			float radius;
			std::string material;
			friend std::ostream & operator<<(std::ostream & _out, const Sphere & sphere)
			{
				_out << "position= " << sphere.position << ", radius= " << sphere.radius << ", material= " << sphere.material << std::endl;
				return _out;
			}
	};

	// May become a shape
	class Chull
	{
		public:
			Position position;
			float radius;
			float min;
			float max;
			int nsides;
			std::string material;
			friend std::ostream & operator<<(std::ostream & _out, const Chull & chull)
			{
				_out << "position= " << chull.position << ", radius= " << chull.radius << ", material= " << chull.material << ", min = " << chull.min << ",max = " << chull.max << std::endl;
				return _out;
			}
	};

	// May become a shape
	class Parallelogram
	{
		public:
			// how specify? vec1, vec2, anchor, Material?
	};

	class Model;

	class IModelObserver {
		public:
			virtual void modelUpdated(const Model &) = 0;
	};

	class Model {
		std::set<IModelObserver*> observers;

		public:
			std::string imageTitle;

			float totalBrightness;

			// Lights
			std::vector< Light > lights;

			// Boxes
			std::vector< Box > boxes;

			// Spheres
			std::vector< Sphere > spheres;

			// Chulls
			std::vector< Chull > chulls;

			/* Rest is not yet ready
			// Camera information
			Camera camera;

			// Parallelogram shapes (includes floor)
			std::vector< Parallelogram > parallelogram;
			*/

			// Constructor
			Model()
				: imageTitle("GPURayTracer")
			{ }

			void registerObserver(IModelObserver * _obs) {
				observers.insert(_obs);
			}

			void unregisterObserver(IModelObserver * _obs) {
				observers.erase(_obs);
			}

			void notifyObservers() {
				for (std::set<IModelObserver*>::iterator ob_it = observers.begin(); ob_it != observers.end(); ++ob_it) {
					(*ob_it)->modelUpdated(*this);
				}
			}

			friend std::ostream & operator<<(std::ostream & _out, const Model & model)
			{
				_out << "imageTitle = " << model.imageTitle << std::endl;
				_out << "totalBrightness = " << model.totalBrightness << std::endl;
				for (int i=0; i<(int)model.lights.size(); ++i)
					_out << "Light: " << (i+1) << " - " << model.lights[i] << std::endl;
				for (int i=0; i<(int)model.boxes.size(); ++i)
					_out << "Box: " << (i+1) << " - " << model.boxes[i] << std::endl;
				for (int i=0; i<(int)model.spheres.size(); ++i)
					_out << "Sphere:" << (i+1) << " - " << model.spheres[i] << std::endl;
				return _out;
			}
	};

}; // grt

<commit_msg>Added missing chull print<commit_after>/*
   Includes the Model and IModelObserver class declarations.

   The Model has the items necessary to construct a modified OptiX image.

   In normal use, one or more IModelObserver objects are registered
   to the model.  Specific observers or viewers may inherit from
   IModelObservers.

   A controller updates the model and calls the model notifyObservers
   function which calls the modelUpdated function of each of the
   observers registered to the model.

*/

#pragma once

#include <set>
#include <vector>
#include <ostream>

namespace grt {

	class Position
	{
		public:
			float x;
			float y;
			float z;

			friend std::ostream & operator<<(std::ostream & _out, const Position & pos)
			{
				_out << "position: x= "  << pos.x << ", y= " << pos.y << ", z= " << pos.z;
				return _out;
			}
	};

	class Color
	{
		public:
			float r;
			float g;
			float b;

			friend std::ostream & operator<<(std::ostream & _out, const Color & c)
			{
				_out << "color: r=" << c.r << ", g=" << c.g << ", b= " << c.b;
				return _out;
			}
	};

	class Light
	{
		public:
			Position position; // x, y, z position
			Color color; // R G B color

			friend std::ostream & operator<<(std::ostream & _out, const Light & light)
			{
				_out << "Light: " << light.position << " " << light.color;
				return _out;
			}
	};

	class Camera
	{
		public:
			Position position;
			float fieldOfView;
	};

	// May become a shape
	class Box
	{
		public:
			Position minPosition;
			Position maxPosition;
			std::string material;
			friend std::ostream & operator<<(std::ostream & _out, const Box & box)
			{
				_out << "minPosition= " << box.minPosition << ", maxPosition= "<<box.maxPosition << ", material= " << box.material;
				return _out;
			}
	};

	// May become a shape
	class Sphere
	{
		public:
			Position position;
			float radius;
			std::string material;
			friend std::ostream & operator<<(std::ostream & _out, const Sphere & sphere)
			{
				_out << "position= " << sphere.position << ", radius= " << sphere.radius << ", material= " << sphere.material << std::endl;
				return _out;
			}
	};

	// May become a shape
	class Chull
	{
		public:
			Position position;
			float radius;
			float min;
			float max;
			int nsides;
			std::string material;
			friend std::ostream & operator<<(std::ostream & _out, const Chull & chull)
			{
				_out << "position= " << chull.position << ", radius= " << chull.radius << ", material= " << chull.material << ", min = " << chull.min << ",max = " << chull.max << std::endl;
				return _out;
			}
	};

	// May become a shape
	class Parallelogram
	{
		public:
			// how specify? vec1, vec2, anchor, Material?
	};

	class Model;

	class IModelObserver {
		public:
			virtual void modelUpdated(const Model &) = 0;
	};

	class Model {
		std::set<IModelObserver*> observers;

		public:
			std::string imageTitle;

			float totalBrightness;

			// Lights
			std::vector< Light > lights;

			// Boxes
			std::vector< Box > boxes;

			// Spheres
			std::vector< Sphere > spheres;

			// Chulls
			std::vector< Chull > chulls;

			/* Rest is not yet ready
			// Camera information
			Camera camera;

			// Parallelogram shapes (includes floor)
			std::vector< Parallelogram > parallelogram;
			*/

			// Constructor
			Model()
				: imageTitle("GPURayTracer")
			{ }

			void registerObserver(IModelObserver * _obs) {
				observers.insert(_obs);
			}

			void unregisterObserver(IModelObserver * _obs) {
				observers.erase(_obs);
			}

			void notifyObservers() {
				for (std::set<IModelObserver*>::iterator ob_it = observers.begin(); ob_it != observers.end(); ++ob_it) {
					(*ob_it)->modelUpdated(*this);
				}
			}

			friend std::ostream & operator<<(std::ostream & _out, const Model & model)
			{
				_out << "imageTitle = " << model.imageTitle << std::endl;
				_out << "totalBrightness = " << model.totalBrightness << std::endl;
				for (int i=0; i<(int)model.lights.size(); ++i)
					_out << "Light: " << (i+1) << " - " << model.lights[i] << std::endl;
				for (int i=0; i<(int)model.boxes.size(); ++i)
					_out << "Box: " << (i+1) << " - " << model.boxes[i] << std::endl;
				for (int i=0; i<(int)model.spheres.size(); ++i)
					_out << "Sphere:" << (i+1) << " - " << model.spheres[i] << std::endl;
				for (int i=0; i<(int)model.chulls.size(); ++i)
					_out << "Chull:" << (i+1) << " - " << model.chulls[i] << std::endl;
				return _out;
			}
	};

}; // grt

<|endoftext|>