<commit_before>/*
** Author(s):
**  - Cedric GESTES <gestes@aldebaran-robotics.com>
**
** Copyright (C) 2012 Aldebaran Robotics
*/

#include <iostream>
#include <QtCore/qmetatype.h>
#include <QtCore/qbytearray.h>
#include "qimetatype_p.h"
#include "qmetaobjectbuilder_p.h"
#include <qimessaging/signature.hpp>

QString qi_MetatypeToNetworkType(const int metatype)
{
  if (metatype == QMetaType::QString)
    return "s";
  return "FAIL";
}

//QString qi_NetworkTypeToMetatype(const QString &metatype, const QMap<QString, QString> &typemap)
QString qi_NetworkTypeToMetatype(const QString &nettype)
{
  if (nettype == "s")
    return "QString";
  return "FAIL";
}

// string
qi::DataStream& operator>>(qi::DataStream &stream, QString &s)
{
  int len;
  stream >> len;
  QByteArray qbb(len, '0');
  stream.read(qbb.data(), len);
  s.append(qbb);
  return stream;
}

qi::DataStream& operator<<(qi::DataStream &stream, const QString &s)
{
  stream.writeString((const char *)s.toAscii().constData(), s.size());
  return stream;
}

bool qi_MetaTypeStore(qi::DataStream &stream, int metatype, void *data)
{
  if (!data || !QMetaType::isRegistered(metatype))
    return false;

  switch(metatype) {
    case QMetaType::Void:
    case QMetaType::VoidStar:
      return false;

    case QMetaType::Char:
      // force a char to be signed
      stream << *static_cast<const signed char *>(data);
      break;
    case QMetaType::UChar:
      stream << *static_cast<const uchar *>(data);
      break;
    case QMetaType::Bool:
      stream << qint8(*static_cast<const bool *>(data));
      break;

    case QMetaType::Int:
      stream << *static_cast<const int *>(data);
      break;
//    case QMetaType::UInt:
//      stream << *static_cast<const unsigned int *>(data);
//      break;

    case QMetaType::Short:
      stream << *static_cast<const short *>(data);
      break;
//    case QMetaType::UShort:
//      stream << *static_cast<const unsigned short *>(data);
//      break;

//    case QMetaType::Long:
//      stream << qlonglong(*static_cast<const long *>(data));
//      break;
//    case QMetaType::ULong:
//      stream << qulonglong(*static_cast<const ulong *>(data));
//      break;

//    case QMetaType::LongLong:
//      stream << *static_cast<const qlonglong *>(data);
//      break;
//    case QMetaType::ULongLong:
//      stream << *static_cast<const qulonglong *>(data);
//      break;

    case QMetaType::Float:
      stream << *static_cast<const float *>(data);
      break;
    case QMetaType::Double:
      stream << *static_cast<const double *>(data);
      break;

//    case QMetaType::QByteArray:
//      stream << *static_cast<const QByteArray*>(data);
//      break;
    case QMetaType::QString:
      stream << *static_cast<const QString*>(data);
      break;
//    case QMetaType::QStringList:
//      stream << *static_cast<const QStringList*>(data);
//      break;
    default:
      return false;
  }
  return true;
}

bool qi_MetaTypeLoad(qi::DataStream &stream, int metatype, void *data)
{
  if (!data || !QMetaType::isRegistered(metatype))
      return false;

  switch(metatype) {
    case QMetaType::Void:
    case QMetaType::VoidStar:
      return false;

    case QMetaType::Bool: {
      char b;
      stream >> b;
      *static_cast<bool *>(data) = b;
      break;
    }

//    case QMetaType::Char:
//      stream >> *static_cast<signed char *>(data);
//      break;
//    case QMetaType::UChar:
//      stream >> *static_cast<unsigned char *>(data);
//      break;

//    case QMetaType::Short:
//      stream >> *static_cast<short *>(data);
//      break;
//    case QMetaType::UShort:
//      stream >> *static_cast<ushort *>(data);
//      break;

    case QMetaType::Int:
      stream >> *static_cast<int *>(data);
      break;
//    case QMetaType::UInt:
//      stream >> *static_cast<uint *>(data);
//      break;

//    case QMetaType::Long: {
//      qlonglong l;
//      stream >> l;
//      *static_cast<long *>(data) = long(l);
//      break; }
//    case QMetaType::ULong: {
//      qulonglong ul;
//      stream >> ul;
//      *static_cast<ulong *>(data) = ulong(ul);
//      break; }
//    case QMetaType::LongLong:
//      stream >> *static_cast<qlonglong *>(data);
//      break;
//    case QMetaType::ULongLong:
//      stream >> *static_cast<qulonglong *>(data);
//      break;

    case QMetaType::Float:
      stream >> *static_cast<float *>(data);
      break;
    case QMetaType::Double:
      stream >> *static_cast<double *>(data);
      break;

//    case QMetaType::QByteArray:
//      stream >> *static_cast< NS(QByteArray)*>(data);
//      break;
    case QMetaType::QString:
      stream >> *static_cast< QString*>(data);
      break;
    default:
      return false;
  }
  return true;

}

void qi_SignatureToMetaMethod(const std::string &signature, QString *returnSig, QString *funcSig)
{
  std::string retSig;
  std::string parSig;
  std::string funcName;

  int idx1 = signature.find("::");
  if (idx1 != signature.npos)
    funcName = signature.substr(0, idx1);
  int idx2 = signature.find("(", idx1);
  if (idx2 != signature.npos) {
    retSig = signature.substr(idx1 + 2, idx2 - idx1 - 2);
    parSig = signature.substr(idx2);
  }

  qi::Signature rets(retSig);
  qi::Signature funs(parSig);
  *returnSig = QString::fromStdString(rets.toQtSignature(false));
  *funcSig = QString::fromStdString(funcName) + QString::fromStdString(funs.toQtSignature(true));
}

<commit_msg>Fix type mismatch.<commit_after>/*
** Author(s):
**  - Cedric GESTES <gestes@aldebaran-robotics.com>
**
** Copyright (C) 2012 Aldebaran Robotics
*/

#include <iostream>
#include <QtCore/qmetatype.h>
#include <QtCore/qbytearray.h>
#include "qimetatype_p.h"
#include "qmetaobjectbuilder_p.h"
#include <qimessaging/signature.hpp>

QString qi_MetatypeToNetworkType(const int metatype)
{
  if (metatype == QMetaType::QString)
    return "s";
  return "FAIL";
}

//QString qi_NetworkTypeToMetatype(const QString &metatype, const QMap<QString, QString> &typemap)
QString qi_NetworkTypeToMetatype(const QString &nettype)
{
  if (nettype == "s")
    return "QString";
  return "FAIL";
}

// string
qi::DataStream& operator>>(qi::DataStream &stream, QString &s)
{
  int len;
  stream >> len;
  QByteArray qbb(len, '0');
  stream.read(qbb.data(), len);
  s.append(qbb);
  return stream;
}

qi::DataStream& operator<<(qi::DataStream &stream, const QString &s)
{
  stream.writeString((const char *)s.toAscii().constData(), s.size());
  return stream;
}

bool qi_MetaTypeStore(qi::DataStream &stream, int metatype, void *data)
{
  if (!data || !QMetaType::isRegistered(metatype))
    return false;

  switch(metatype) {
    case QMetaType::Void:
    case QMetaType::VoidStar:
      return false;

    case QMetaType::Char:
      // force a char to be signed
      stream << *static_cast<const signed char *>(data);
      break;
    case QMetaType::UChar:
      stream << *static_cast<const uchar *>(data);
      break;
    case QMetaType::Bool:
      stream << qint8(*static_cast<const bool *>(data));
      break;

    case QMetaType::Int:
      stream << *static_cast<const int *>(data);
      break;
//    case QMetaType::UInt:
//      stream << *static_cast<const unsigned int *>(data);
//      break;

    case QMetaType::Short:
      stream << *static_cast<const short *>(data);
      break;
//    case QMetaType::UShort:
//      stream << *static_cast<const unsigned short *>(data);
//      break;

//    case QMetaType::Long:
//      stream << qlonglong(*static_cast<const long *>(data));
//      break;
//    case QMetaType::ULong:
//      stream << qulonglong(*static_cast<const ulong *>(data));
//      break;

//    case QMetaType::LongLong:
//      stream << *static_cast<const qlonglong *>(data);
//      break;
//    case QMetaType::ULongLong:
//      stream << *static_cast<const qulonglong *>(data);
//      break;

    case QMetaType::Float:
      stream << *static_cast<const float *>(data);
      break;
    case QMetaType::Double:
      stream << *static_cast<const double *>(data);
      break;

//    case QMetaType::QByteArray:
//      stream << *static_cast<const QByteArray*>(data);
//      break;
    case QMetaType::QString:
      stream << *static_cast<const QString*>(data);
      break;
//    case QMetaType::QStringList:
//      stream << *static_cast<const QStringList*>(data);
//      break;
    default:
      return false;
  }
  return true;
}

bool qi_MetaTypeLoad(qi::DataStream &stream, int metatype, void *data)
{
  if (!data || !QMetaType::isRegistered(metatype))
      return false;

  switch(metatype) {
    case QMetaType::Void:
    case QMetaType::VoidStar:
      return false;

    case QMetaType::Bool: {
      char b;
      stream >> b;
      *static_cast<bool *>(data) = b;
      break;
    }

//    case QMetaType::Char:
//      stream >> *static_cast<signed char *>(data);
//      break;
//    case QMetaType::UChar:
//      stream >> *static_cast<unsigned char *>(data);
//      break;

//    case QMetaType::Short:
//      stream >> *static_cast<short *>(data);
//      break;
//    case QMetaType::UShort:
//      stream >> *static_cast<ushort *>(data);
//      break;

    case QMetaType::Int:
      stream >> *static_cast<int *>(data);
      break;
//    case QMetaType::UInt:
//      stream >> *static_cast<uint *>(data);
//      break;

//    case QMetaType::Long: {
//      qlonglong l;
//      stream >> l;
//      *static_cast<long *>(data) = long(l);
//      break; }
//    case QMetaType::ULong: {
//      qulonglong ul;
//      stream >> ul;
//      *static_cast<ulong *>(data) = ulong(ul);
//      break; }
//    case QMetaType::LongLong:
//      stream >> *static_cast<qlonglong *>(data);
//      break;
//    case QMetaType::ULongLong:
//      stream >> *static_cast<qulonglong *>(data);
//      break;

    case QMetaType::Float:
      stream >> *static_cast<float *>(data);
      break;
    case QMetaType::Double:
      stream >> *static_cast<double *>(data);
      break;

//    case QMetaType::QByteArray:
//      stream >> *static_cast< NS(QByteArray)*>(data);
//      break;
    case QMetaType::QString:
      stream >> *static_cast< QString*>(data);
      break;
    default:
      return false;
  }
  return true;

}

void qi_SignatureToMetaMethod(const std::string &signature, QString *returnSig, QString *funcSig)
{
  std::string retSig;
  std::string parSig;
  std::string funcName;

  size_t idx1 = signature.find("::");
  if (idx1 != signature.npos)
    funcName = signature.substr(0, idx1);
  size_t idx2 = signature.find("(", idx1);
  if (idx2 != signature.npos) {
    retSig = signature.substr(idx1 + 2, idx2 - idx1 - 2);
    parSig = signature.substr(idx2);
  }

  qi::Signature rets(retSig);
  qi::Signature funs(parSig);
  *returnSig = QString::fromStdString(rets.toQtSignature(false));
  *funcSig = QString::fromStdString(funcName) + QString::fromStdString(funs.toQtSignature(true));
}

<|endoftext|>


<commit_before>// Copyright 2014 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/extensions/extension_action_platform_delegate_views.h"

#include "base/logging.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/extensions/api/commands/command_service.h"
#include "chrome/browser/extensions/api/extension_action/extension_action_api.h"
#include "chrome/browser/extensions/extension_action.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/sessions/session_tab_helper.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/extensions/accelerator_priority.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/browser/ui/views/toolbar/browser_actions_container.h"
#include "chrome/browser/ui/views/toolbar/toolbar_action_view_delegate_views.h"
#include "chrome/browser/ui/views/toolbar/toolbar_view.h"
#include "chrome/common/extensions/api/extension_action/action_info.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_source.h"
#include "extensions/browser/notification_types.h"
#include "extensions/common/extension.h"
#include "extensions/common/manifest_constants.h"
#include "ui/gfx/image/image_skia.h"
#include "ui/gfx/image/image_skia_operations.h"
#include "ui/views/controls/menu/menu_controller.h"
#include "ui/views/controls/menu/menu_runner.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"

using extensions::ActionInfo;
using extensions::CommandService;

namespace {

// The ExtensionActionPlatformDelegateViews which is currently showing its
// context menu, if any.
// Since only one context menu can be shown (even across browser windows), it's
// safe to have this be a global singleton.
ExtensionActionPlatformDelegateViews* context_menu_owner = NULL;

}  // namespace

// static
scoped_ptr<ExtensionActionPlatformDelegate>
ExtensionActionPlatformDelegate::Create(
    ExtensionActionViewController* controller) {
  return make_scoped_ptr(new ExtensionActionPlatformDelegateViews(controller));
}

ExtensionActionPlatformDelegateViews::ExtensionActionPlatformDelegateViews(
    ExtensionActionViewController* controller)
    : controller_(controller),
      popup_(nullptr),
      weak_factory_(this) {
  content::NotificationSource notification_source = content::Source<Profile>(
      controller_->browser()->profile()->GetOriginalProfile());
  registrar_.Add(this,
                 extensions::NOTIFICATION_EXTENSION_COMMAND_ADDED,
                 notification_source);
  registrar_.Add(this,
                 extensions::NOTIFICATION_EXTENSION_COMMAND_REMOVED,
                 notification_source);
}

ExtensionActionPlatformDelegateViews::~ExtensionActionPlatformDelegateViews() {
  DCHECK(!popup_);  // We should never have a visible popup at shutdown.
  if (context_menu_owner == this)
    context_menu_owner = nullptr;
  UnregisterCommand(false);
}

gfx::NativeView ExtensionActionPlatformDelegateViews::GetPopupNativeView() {
  return popup_ ? popup_->GetWidget()->GetNativeView() : nullptr;
}

bool ExtensionActionPlatformDelegateViews::IsMenuRunning() const {
  return menu_runner_.get() != NULL;
}

void ExtensionActionPlatformDelegateViews::RegisterCommand() {
  // If we've already registered, do nothing.
  if (action_keybinding_.get())
    return;

  extensions::Command extension_command;
  views::FocusManager* focus_manager =
      GetDelegateViews()->GetFocusManagerForAccelerator();
  if (focus_manager && controller_->GetExtensionCommand(&extension_command)) {
    action_keybinding_.reset(
        new ui::Accelerator(extension_command.accelerator()));
    focus_manager->RegisterAccelerator(
        *action_keybinding_,
        GetAcceleratorPriority(extension_command.accelerator(),
                               controller_->extension()),
        this);
  }
}

void ExtensionActionPlatformDelegateViews::OnDelegateSet() {
  GetDelegateViews()->GetAsView()->set_context_menu_controller(this);
}

void ExtensionActionPlatformDelegateViews::CloseActivePopup() {
  if (controller_->extension_action()->action_type() ==
          ActionInfo::TYPE_BROWSER) {
    BrowserView::GetBrowserViewForBrowser(controller_->browser())->toolbar()->
        browser_actions()->HideActivePopup();
  } else {
    DCHECK_EQ(ActionInfo::TYPE_PAGE,
              controller_->extension_action()->action_type());
    // Page actions only know how to close their own popups.
    controller_->HidePopup();
  }
}

void ExtensionActionPlatformDelegateViews::CloseOwnPopup() {
  // It's possible that the popup is already in the process of destroying.
  if (popup_)
    CleanupPopup(true);
}

extensions::ExtensionViewHost*
ExtensionActionPlatformDelegateViews::ShowPopupWithUrl(
    ExtensionActionViewController::PopupShowAction show_action,
    const GURL& popup_url,
    bool grant_tab_permissions) {
  // TOP_RIGHT is correct for both RTL and LTR, because the views platform
  // performs the flipping in RTL cases.
  views::BubbleBorder::Arrow arrow = views::BubbleBorder::TOP_RIGHT;

  views::View* reference_view = GetDelegateViews()->GetReferenceViewForPopup();

  ExtensionPopup::ShowAction popup_show_action =
      show_action == ExtensionActionViewController::SHOW_POPUP ?
          ExtensionPopup::SHOW : ExtensionPopup::SHOW_AND_INSPECT;
  popup_ = ExtensionPopup::ShowPopup(popup_url,
                                     controller_->browser(),
                                     reference_view,
                                     arrow,
                                     popup_show_action);
  popup_->GetWidget()->AddObserver(this);

  return popup_->host();
}

void ExtensionActionPlatformDelegateViews::Observe(
    int type,
    const content::NotificationSource& source,
    const content::NotificationDetails& details) {
  DCHECK(type == extensions::NOTIFICATION_EXTENSION_COMMAND_ADDED ||
         type == extensions::NOTIFICATION_EXTENSION_COMMAND_REMOVED);
  extensions::ExtensionCommandRemovedDetails* payload =
      content::Details<extensions::ExtensionCommandRemovedDetails>(details)
          .ptr();
  if (controller_->extension()->id() == payload->extension_id &&
      (payload->command_name ==
           extensions::manifest_values::kBrowserActionCommandEvent ||
       payload->command_name ==
           extensions::manifest_values::kPageActionCommandEvent)) {
    if (type == extensions::NOTIFICATION_EXTENSION_COMMAND_ADDED)
      RegisterCommand();
    else
      UnregisterCommand(true);
  }
}

bool ExtensionActionPlatformDelegateViews::AcceleratorPressed(
    const ui::Accelerator& accelerator) {
  // We shouldn't be handling any accelerators if the view is hidden, unless
  // this is a browser action.
  DCHECK(controller_->extension_action()->action_type() ==
             ActionInfo::TYPE_BROWSER ||
         GetDelegateViews()->GetAsView()->visible());

  // Normal priority shortcuts must be handled via standard browser commands to
  // be processed at the proper time.
  if (GetAcceleratorPriority(accelerator, controller_->extension()) ==
      ui::AcceleratorManager::kNormalPriority)
    return false;

  controller_->ExecuteAction(true);
  return true;
}

bool ExtensionActionPlatformDelegateViews::CanHandleAccelerators() const {
  // Page actions can only handle accelerators when they are visible.
  // Browser actions can handle accelerators even when not visible, since they
  // might be hidden in an overflow menu.
  return controller_->extension_action()->action_type() ==
      ActionInfo::TYPE_PAGE ? GetDelegateViews()->GetAsView()->visible() :
          true;
}

void ExtensionActionPlatformDelegateViews::OnWidgetDestroying(
    views::Widget* widget) {
  DCHECK(popup_);
  DCHECK_EQ(popup_->GetWidget(), widget);
  CleanupPopup(false);
}

void ExtensionActionPlatformDelegateViews::ShowContextMenuForView(
    views::View* source,
    const gfx::Point& point,
    ui::MenuSourceType source_type) {
  // If there's another active menu that won't be dismissed by opening this one,
  // then we can't show this one right away, since we can only show one nested
  // menu at a time.
  // If the other menu is an extension action's context menu, then we'll run
  // this one after that one closes. If it's a different type of menu, then we
  // close it and give up, for want of a better solution. (Luckily, this is
  // rare).
  // TODO(devlin): Update this when views code no longer runs menus in a nested
  // loop.
  if (context_menu_owner) {
    context_menu_owner->followup_context_menu_task_ =
        base::Bind(&ExtensionActionPlatformDelegateViews::DoShowContextMenu,
                   weak_factory_.GetWeakPtr(),
                   source_type);
  }
  if (CloseActiveMenuIfNeeded())
    return;

  // Otherwise, no other menu is showing, and we can proceed normally.
  DoShowContextMenu(source_type);
}

void ExtensionActionPlatformDelegateViews::DoShowContextMenu(
    ui::MenuSourceType source_type) {
  ui::MenuModel* context_menu_model = controller_->GetContextMenu();
  // It's possible the extension doesn't have a context menu.
  if (!context_menu_model)
    return;

  DCHECK(!context_menu_owner);
  context_menu_owner = this;

  // We shouldn't have both a popup and a context menu showing.
  CloseActivePopup();

  gfx::Point screen_loc;
  views::View::ConvertPointToScreen(GetDelegateViews()->GetAsView(),
                                    &screen_loc);

  int run_types =
      views::MenuRunner::HAS_MNEMONICS | views::MenuRunner::CONTEXT_MENU;
  if (GetDelegateViews()->IsShownInMenu())
    run_types |= views::MenuRunner::IS_NESTED;

  views::Widget* parent = GetDelegateViews()->GetParentForContextMenu();

  menu_runner_.reset(new views::MenuRunner(context_menu_model, run_types));

  if (menu_runner_->RunMenuAt(
          parent,
          GetDelegateViews()->GetContextMenuButton(),
          gfx::Rect(screen_loc, GetDelegateViews()->GetAsView()->size()),
          views::MENU_ANCHOR_TOPLEFT,
          source_type) == views::MenuRunner::MENU_DELETED) {
    return;
  }

  context_menu_owner = NULL;
  menu_runner_.reset();

  // If another extension action wants to show its context menu, allow it to.
  if (!followup_context_menu_task_.is_null()) {
    base::Closure task = followup_context_menu_task_;
    followup_context_menu_task_ = base::Closure();
    task.Run();
  }
}

void ExtensionActionPlatformDelegateViews::UnregisterCommand(
    bool only_if_removed) {
  views::FocusManager* focus_manager =
      GetDelegateViews()->GetFocusManagerForAccelerator();
  if (!focus_manager || !action_keybinding_.get())
    return;

  // If |only_if_removed| is true, it means that we only need to unregister
  // ourselves as an accelerator if the command was removed. Otherwise, we need
  // to unregister ourselves no matter what (likely because we are shutting
  // down).
  extensions::Command extension_command;
  if (!only_if_removed ||
      !controller_->GetExtensionCommand(&extension_command)) {
    focus_manager->UnregisterAccelerator(*action_keybinding_, this);
    action_keybinding_.reset();
  }
}

bool ExtensionActionPlatformDelegateViews::CloseActiveMenuIfNeeded() {
  // If this view is shown inside another menu, there's a possibility that there
  // is another context menu showing that we have to close before we can
  // activate a different menu.
  if (GetDelegateViews()->IsShownInMenu()) {
    views::MenuController* menu_controller =
        views::MenuController::GetActiveInstance();
    // If this is shown inside a menu, then there should always be an active
    // menu controller.
    DCHECK(menu_controller);
    if (menu_controller->in_nested_run()) {
      // There is another menu showing. Close the outermost menu (since we are
      // shown in the same menu, we don't want to close the whole thing).
      menu_controller->Cancel(views::MenuController::EXIT_OUTERMOST);
      return true;
    }
  }

  return false;
}

void ExtensionActionPlatformDelegateViews::CleanupPopup(bool close_widget) {
  DCHECK(popup_);
  popup_->GetWidget()->RemoveObserver(this);
  if (close_widget)
    popup_->GetWidget()->Close();
  popup_ = nullptr;
}

ToolbarActionViewDelegateViews*
ExtensionActionPlatformDelegateViews::GetDelegateViews() const {
  return static_cast<ToolbarActionViewDelegateViews*>(
      controller_->view_delegate());
}
<commit_msg>[Extensions Toolbar] Ensure popup is closed at shutdown<commit_after>// Copyright 2014 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/extensions/extension_action_platform_delegate_views.h"

#include "base/logging.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/extensions/api/commands/command_service.h"
#include "chrome/browser/extensions/api/extension_action/extension_action_api.h"
#include "chrome/browser/extensions/extension_action.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/sessions/session_tab_helper.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/extensions/accelerator_priority.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/browser/ui/views/toolbar/browser_actions_container.h"
#include "chrome/browser/ui/views/toolbar/toolbar_action_view_delegate_views.h"
#include "chrome/browser/ui/views/toolbar/toolbar_view.h"
#include "chrome/common/extensions/api/extension_action/action_info.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_source.h"
#include "extensions/browser/notification_types.h"
#include "extensions/common/extension.h"
#include "extensions/common/manifest_constants.h"
#include "ui/gfx/image/image_skia.h"
#include "ui/gfx/image/image_skia_operations.h"
#include "ui/views/controls/menu/menu_controller.h"
#include "ui/views/controls/menu/menu_runner.h"
#include "ui/views/view.h"
#include "ui/views/widget/widget.h"

using extensions::ActionInfo;
using extensions::CommandService;

namespace {

// The ExtensionActionPlatformDelegateViews which is currently showing its
// context menu, if any.
// Since only one context menu can be shown (even across browser windows), it's
// safe to have this be a global singleton.
ExtensionActionPlatformDelegateViews* context_menu_owner = NULL;

}  // namespace

// static
scoped_ptr<ExtensionActionPlatformDelegate>
ExtensionActionPlatformDelegate::Create(
    ExtensionActionViewController* controller) {
  return make_scoped_ptr(new ExtensionActionPlatformDelegateViews(controller));
}

ExtensionActionPlatformDelegateViews::ExtensionActionPlatformDelegateViews(
    ExtensionActionViewController* controller)
    : controller_(controller),
      popup_(nullptr),
      weak_factory_(this) {
  content::NotificationSource notification_source = content::Source<Profile>(
      controller_->browser()->profile()->GetOriginalProfile());
  registrar_.Add(this,
                 extensions::NOTIFICATION_EXTENSION_COMMAND_ADDED,
                 notification_source);
  registrar_.Add(this,
                 extensions::NOTIFICATION_EXTENSION_COMMAND_REMOVED,
                 notification_source);
}

ExtensionActionPlatformDelegateViews::~ExtensionActionPlatformDelegateViews() {
  DCHECK(!popup_);  // We should never have a visible popup at shutdown.
  if (context_menu_owner == this)
    context_menu_owner = nullptr;
  // Since the popup close process is asynchronous, it might not be fully closed
  // at shutdown. We still need to cleanup, though.
  if (popup_)
    CleanupPopup(true);
  UnregisterCommand(false);
}

gfx::NativeView ExtensionActionPlatformDelegateViews::GetPopupNativeView() {
  return popup_ ? popup_->GetWidget()->GetNativeView() : nullptr;
}

bool ExtensionActionPlatformDelegateViews::IsMenuRunning() const {
  return menu_runner_.get() != NULL;
}

void ExtensionActionPlatformDelegateViews::RegisterCommand() {
  // If we've already registered, do nothing.
  if (action_keybinding_.get())
    return;

  extensions::Command extension_command;
  views::FocusManager* focus_manager =
      GetDelegateViews()->GetFocusManagerForAccelerator();
  if (focus_manager && controller_->GetExtensionCommand(&extension_command)) {
    action_keybinding_.reset(
        new ui::Accelerator(extension_command.accelerator()));
    focus_manager->RegisterAccelerator(
        *action_keybinding_,
        GetAcceleratorPriority(extension_command.accelerator(),
                               controller_->extension()),
        this);
  }
}

void ExtensionActionPlatformDelegateViews::OnDelegateSet() {
  GetDelegateViews()->GetAsView()->set_context_menu_controller(this);
}

void ExtensionActionPlatformDelegateViews::CloseActivePopup() {
  if (controller_->extension_action()->action_type() ==
          ActionInfo::TYPE_BROWSER) {
    BrowserView::GetBrowserViewForBrowser(controller_->browser())->toolbar()->
        browser_actions()->HideActivePopup();
  } else {
    DCHECK_EQ(ActionInfo::TYPE_PAGE,
              controller_->extension_action()->action_type());
    // Page actions only know how to close their own popups.
    controller_->HidePopup();
  }
}

void ExtensionActionPlatformDelegateViews::CloseOwnPopup() {
  // It's possible that the popup is already in the process of destroying.
  if (popup_)
    CleanupPopup(true);
}

extensions::ExtensionViewHost*
ExtensionActionPlatformDelegateViews::ShowPopupWithUrl(
    ExtensionActionViewController::PopupShowAction show_action,
    const GURL& popup_url,
    bool grant_tab_permissions) {
  // TOP_RIGHT is correct for both RTL and LTR, because the views platform
  // performs the flipping in RTL cases.
  views::BubbleBorder::Arrow arrow = views::BubbleBorder::TOP_RIGHT;

  views::View* reference_view = GetDelegateViews()->GetReferenceViewForPopup();

  ExtensionPopup::ShowAction popup_show_action =
      show_action == ExtensionActionViewController::SHOW_POPUP ?
          ExtensionPopup::SHOW : ExtensionPopup::SHOW_AND_INSPECT;
  popup_ = ExtensionPopup::ShowPopup(popup_url,
                                     controller_->browser(),
                                     reference_view,
                                     arrow,
                                     popup_show_action);
  popup_->GetWidget()->AddObserver(this);

  return popup_->host();
}

void ExtensionActionPlatformDelegateViews::Observe(
    int type,
    const content::NotificationSource& source,
    const content::NotificationDetails& details) {
  DCHECK(type == extensions::NOTIFICATION_EXTENSION_COMMAND_ADDED ||
         type == extensions::NOTIFICATION_EXTENSION_COMMAND_REMOVED);
  extensions::ExtensionCommandRemovedDetails* payload =
      content::Details<extensions::ExtensionCommandRemovedDetails>(details)
          .ptr();
  if (controller_->extension()->id() == payload->extension_id &&
      (payload->command_name ==
           extensions::manifest_values::kBrowserActionCommandEvent ||
       payload->command_name ==
           extensions::manifest_values::kPageActionCommandEvent)) {
    if (type == extensions::NOTIFICATION_EXTENSION_COMMAND_ADDED)
      RegisterCommand();
    else
      UnregisterCommand(true);
  }
}

bool ExtensionActionPlatformDelegateViews::AcceleratorPressed(
    const ui::Accelerator& accelerator) {
  // We shouldn't be handling any accelerators if the view is hidden, unless
  // this is a browser action.
  DCHECK(controller_->extension_action()->action_type() ==
             ActionInfo::TYPE_BROWSER ||
         GetDelegateViews()->GetAsView()->visible());

  // Normal priority shortcuts must be handled via standard browser commands to
  // be processed at the proper time.
  if (GetAcceleratorPriority(accelerator, controller_->extension()) ==
      ui::AcceleratorManager::kNormalPriority)
    return false;

  controller_->ExecuteAction(true);
  return true;
}

bool ExtensionActionPlatformDelegateViews::CanHandleAccelerators() const {
  // Page actions can only handle accelerators when they are visible.
  // Browser actions can handle accelerators even when not visible, since they
  // might be hidden in an overflow menu.
  return controller_->extension_action()->action_type() ==
      ActionInfo::TYPE_PAGE ? GetDelegateViews()->GetAsView()->visible() :
          true;
}

void ExtensionActionPlatformDelegateViews::OnWidgetDestroying(
    views::Widget* widget) {
  DCHECK(popup_);
  DCHECK_EQ(popup_->GetWidget(), widget);
  CleanupPopup(false);
}

void ExtensionActionPlatformDelegateViews::ShowContextMenuForView(
    views::View* source,
    const gfx::Point& point,
    ui::MenuSourceType source_type) {
  // If there's another active menu that won't be dismissed by opening this one,
  // then we can't show this one right away, since we can only show one nested
  // menu at a time.
  // If the other menu is an extension action's context menu, then we'll run
  // this one after that one closes. If it's a different type of menu, then we
  // close it and give up, for want of a better solution. (Luckily, this is
  // rare).
  // TODO(devlin): Update this when views code no longer runs menus in a nested
  // loop.
  if (context_menu_owner) {
    context_menu_owner->followup_context_menu_task_ =
        base::Bind(&ExtensionActionPlatformDelegateViews::DoShowContextMenu,
                   weak_factory_.GetWeakPtr(),
                   source_type);
  }
  if (CloseActiveMenuIfNeeded())
    return;

  // Otherwise, no other menu is showing, and we can proceed normally.
  DoShowContextMenu(source_type);
}

void ExtensionActionPlatformDelegateViews::DoShowContextMenu(
    ui::MenuSourceType source_type) {
  ui::MenuModel* context_menu_model = controller_->GetContextMenu();
  // It's possible the extension doesn't have a context menu.
  if (!context_menu_model)
    return;

  DCHECK(!context_menu_owner);
  context_menu_owner = this;

  // We shouldn't have both a popup and a context menu showing.
  CloseActivePopup();

  gfx::Point screen_loc;
  views::View::ConvertPointToScreen(GetDelegateViews()->GetAsView(),
                                    &screen_loc);

  int run_types =
      views::MenuRunner::HAS_MNEMONICS | views::MenuRunner::CONTEXT_MENU;
  if (GetDelegateViews()->IsShownInMenu())
    run_types |= views::MenuRunner::IS_NESTED;

  views::Widget* parent = GetDelegateViews()->GetParentForContextMenu();

  menu_runner_.reset(new views::MenuRunner(context_menu_model, run_types));

  if (menu_runner_->RunMenuAt(
          parent,
          GetDelegateViews()->GetContextMenuButton(),
          gfx::Rect(screen_loc, GetDelegateViews()->GetAsView()->size()),
          views::MENU_ANCHOR_TOPLEFT,
          source_type) == views::MenuRunner::MENU_DELETED) {
    return;
  }

  context_menu_owner = NULL;
  menu_runner_.reset();

  // If another extension action wants to show its context menu, allow it to.
  if (!followup_context_menu_task_.is_null()) {
    base::Closure task = followup_context_menu_task_;
    followup_context_menu_task_ = base::Closure();
    task.Run();
  }
}

void ExtensionActionPlatformDelegateViews::UnregisterCommand(
    bool only_if_removed) {
  views::FocusManager* focus_manager =
      GetDelegateViews()->GetFocusManagerForAccelerator();
  if (!focus_manager || !action_keybinding_.get())
    return;

  // If |only_if_removed| is true, it means that we only need to unregister
  // ourselves as an accelerator if the command was removed. Otherwise, we need
  // to unregister ourselves no matter what (likely because we are shutting
  // down).
  extensions::Command extension_command;
  if (!only_if_removed ||
      !controller_->GetExtensionCommand(&extension_command)) {
    focus_manager->UnregisterAccelerator(*action_keybinding_, this);
    action_keybinding_.reset();
  }
}

bool ExtensionActionPlatformDelegateViews::CloseActiveMenuIfNeeded() {
  // If this view is shown inside another menu, there's a possibility that there
  // is another context menu showing that we have to close before we can
  // activate a different menu.
  if (GetDelegateViews()->IsShownInMenu()) {
    views::MenuController* menu_controller =
        views::MenuController::GetActiveInstance();
    // If this is shown inside a menu, then there should always be an active
    // menu controller.
    DCHECK(menu_controller);
    if (menu_controller->in_nested_run()) {
      // There is another menu showing. Close the outermost menu (since we are
      // shown in the same menu, we don't want to close the whole thing).
      menu_controller->Cancel(views::MenuController::EXIT_OUTERMOST);
      return true;
    }
  }

  return false;
}

void ExtensionActionPlatformDelegateViews::CleanupPopup(bool close_widget) {
  DCHECK(popup_);
  popup_->GetWidget()->RemoveObserver(this);
  if (close_widget)
    popup_->GetWidget()->Close();
  popup_ = nullptr;
}

ToolbarActionViewDelegateViews*
ExtensionActionPlatformDelegateViews::GetDelegateViews() const {
  return static_cast<ToolbarActionViewDelegateViews*>(
      controller_->view_delegate());
}
<|endoftext|>


<commit_before>/*
* this file is part of the oxygen gtk engine
* Copyright (c) 2010 Hugo Pereira Da Costa <hugo@oxygen-icons.org>
* Copyright (c) 2010 Ruslan Kabatsayev <b7.10110111@gmail.com>
*
* inspired notably from kdelibs/kdeui/color/kcolorutils.h
* Copyright (C) 2007 Matthew Woehlke <mw_triad@users.sourceforge.net>
* Copyright (C) 2007 Thomas Zander <zander@kde.org>
* Copyright (C) 2007 Zack Rusin <zack@kde.org>
*
* This  library is free  software; you can  redistribute it and/or
* modify it  under  the terms  of the  GNU Lesser  General  Public
* License  as published  by the Free  Software  Foundation; either
* version 2 of the License, or( at your option ) any later version.
*
* This library is distributed  in the hope that it will be useful,
* but  WITHOUT ANY WARRANTY; without even  the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License  along  with  this library;  if not,  write to  the Free
* Software Foundation, Inc., 51  Franklin St, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/

#include "oxygenshadowconfiguration.h"
#include "config.h"

#include <cassert>

namespace Oxygen
{

    //_________________________________________________________
    ShadowConfiguration::ShadowConfiguration( Palette::Group group ):
        _colorGroup(group),
        _enabled(true)
    {
        assert(group==Palette::Active||group==Palette::Inactive);

        if( _colorGroup == Palette::Active )
        {

            _shadowSize = 40;
            _horizontalOffset = 0;
            _verticalOffset = 0.1;

            _innerColor = ColorUtils::Rgba( 0.44, 0.94, 1.0 );
            _outerColor = ColorUtils::Rgba( 0.33, 0.64, 0.94 );
            _useOuterColor = true;

        } else {

            _shadowSize = 40;
            _horizontalOffset = 0;
            _verticalOffset = 0.2;

            _innerColor = ColorUtils::Rgba::black();
            _outerColor = _innerColor;
            _useOuterColor = false;

        }

    }

    //_________________________________________________________
    void ShadowConfiguration::initialize( const OptionMap& options )
    {

        #if OXYGEN_DEBUG
        std::cerr << "Oxygen::ShadowConfiguration::initialize - " << (_colorGroup == Palette::Active ? "Active": "Inactive" ) << std::endl;
        #endif

        if( _colorGroup == Palette::Active)
        {

            _innerColor = ColorUtils::Rgba::fromKdeOption( options.getValue( "[ActiveShadow]", "InnerColor", "112,241,255" ) );
            _outerColor = ColorUtils::Rgba::fromKdeOption( options.getValue( "[ActiveShadow]", "OuterColor", "84,167,240" ) );

            _shadowSize = options.getOption( "[ActiveShadow]","Size" ).toVariant<double>(40);
            _verticalOffset = options.getOption( "[ActiveShadow]","VerticalOffset" ).toVariant<double>(0.1);
            _useOuterColor = options.getOption( "[ActiveShadow]","UseOuterColor" ).toVariant<std::string>("true") == "true";

        } else {

            _innerColor = ColorUtils::Rgba::fromKdeOption( options.getValue( "[InactiveShadow]", "InnerColor", "0,0,0" ) );
            _outerColor = ColorUtils::Rgba::fromKdeOption( options.getValue( "[InactiveShadow]", "OuterColor", "0,0,0" ) );

            _shadowSize = options.getOption( "[InactiveShadow]","Size" ).toVariant<double>(40);
            _verticalOffset = options.getOption( "[InactiveShadow]","VerticalOffset" ).toVariant<double>(0.2);
            _useOuterColor = options.getOption( "[InactiveShadow]", "UseOuterColor" ).toVariant<std::string>("false") == "true";

        }

    }

    //_________________________________________________________
    std::ostream& operator << (std::ostream& out, const ShadowConfiguration& configuration )
    {
        out << "Oxygen::ShadowConfiguration - (" << (configuration._colorGroup == Palette::Active ? "Active": "Inactive" ) << ")" << std::endl;
        out << "  enabled: " << (configuration._enabled ? "true":"false" ) << std::endl;
        out << "  size: " << configuration._shadowSize << std::endl;
        out << "  offset: " << configuration._verticalOffset << std::endl;
        out << "  innerColor: " << configuration._innerColor << std::endl;
        out << "  outerColor: ";
        if( configuration._useOuterColor ) out << "unused";
        else out <<  configuration._outerColor;
        out << std::endl;
        return out;
    }
}
<commit_msg>Make use of "UseOuterColor" oxygenrc option<commit_after>/*
* this file is part of the oxygen gtk engine
* Copyright (c) 2010 Hugo Pereira Da Costa <hugo@oxygen-icons.org>
* Copyright (c) 2010 Ruslan Kabatsayev <b7.10110111@gmail.com>
*
* inspired notably from kdelibs/kdeui/color/kcolorutils.h
* Copyright (C) 2007 Matthew Woehlke <mw_triad@users.sourceforge.net>
* Copyright (C) 2007 Thomas Zander <zander@kde.org>
* Copyright (C) 2007 Zack Rusin <zack@kde.org>
*
* This  library is free  software; you can  redistribute it and/or
* modify it  under  the terms  of the  GNU Lesser  General  Public
* License  as published  by the Free  Software  Foundation; either
* version 2 of the License, or( at your option ) any later version.
*
* This library is distributed  in the hope that it will be useful,
* but  WITHOUT ANY WARRANTY; without even  the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License  along  with  this library;  if not,  write to  the Free
* Software Foundation, Inc., 51  Franklin St, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/

#include "oxygenshadowconfiguration.h"
#include "config.h"

#include <cassert>

namespace Oxygen
{

    //_________________________________________________________
    ShadowConfiguration::ShadowConfiguration( Palette::Group group ):
        _colorGroup(group),
        _enabled(true)
    {
        assert(group==Palette::Active||group==Palette::Inactive);

        if( _colorGroup == Palette::Active )
        {

            _shadowSize = 40;
            _horizontalOffset = 0;
            _verticalOffset = 0.1;

            _innerColor = ColorUtils::Rgba( 0.44, 0.94, 1.0 );
            _outerColor = ColorUtils::Rgba( 0.33, 0.64, 0.94 );
            _useOuterColor = true;

        } else {

            _shadowSize = 40;
            _horizontalOffset = 0;
            _verticalOffset = 0.2;

            _innerColor = ColorUtils::Rgba::black();
            _outerColor = _innerColor;
            _useOuterColor = false;

        }

    }

    //_________________________________________________________
    void ShadowConfiguration::initialize( const OptionMap& options )
    {

        #if OXYGEN_DEBUG
        std::cerr << "Oxygen::ShadowConfiguration::initialize - " << (_colorGroup == Palette::Active ? "Active": "Inactive" ) << std::endl;
        #endif

        if( _colorGroup == Palette::Active)
        {

            _innerColor = ColorUtils::Rgba::fromKdeOption( options.getValue( "[ActiveShadow]", "InnerColor", "112,241,255" ) );
            _outerColor = ColorUtils::Rgba::fromKdeOption( options.getValue( "[ActiveShadow]", "OuterColor", "84,167,240" ) );

            _shadowSize = options.getOption( "[ActiveShadow]","Size" ).toVariant<double>(40);
            _verticalOffset = options.getOption( "[ActiveShadow]","VerticalOffset" ).toVariant<double>(0.1);
            _useOuterColor = options.getOption( "[ActiveShadow]","UseOuterColor" ).toVariant<std::string>("true") == "true";

        } else {

            _innerColor = ColorUtils::Rgba::fromKdeOption( options.getValue( "[InactiveShadow]", "InnerColor", "0,0,0" ) );
            _outerColor = ColorUtils::Rgba::fromKdeOption( options.getValue( "[InactiveShadow]", "OuterColor", "0,0,0" ) );

            _shadowSize = options.getOption( "[InactiveShadow]","Size" ).toVariant<double>(40);
            _verticalOffset = options.getOption( "[InactiveShadow]","VerticalOffset" ).toVariant<double>(0.2);
            _useOuterColor = options.getOption( "[InactiveShadow]", "UseOuterColor" ).toVariant<std::string>("false") == "true";

        }

        // NOTE: doing just like in oxygen-qt.
        // Might need to implement calcOuterColor() if its logic becomes more complicated in oxygen-qt.
        if(!_useOuterColor)
            _outerColor=_innerColor;

    }

    //_________________________________________________________
    std::ostream& operator << (std::ostream& out, const ShadowConfiguration& configuration )
    {
        out << "Oxygen::ShadowConfiguration - (" << (configuration._colorGroup == Palette::Active ? "Active": "Inactive" ) << ")" << std::endl;
        out << "  enabled: " << (configuration._enabled ? "true":"false" ) << std::endl;
        out << "  size: " << configuration._shadowSize << std::endl;
        out << "  offset: " << configuration._verticalOffset << std::endl;
        out << "  innerColor: " << configuration._innerColor << std::endl;
        out << "  outerColor: ";
        if( configuration._useOuterColor ) out << "unused";
        else out <<  configuration._outerColor;
        out << std::endl;
        return out;
    }
}
<|endoftext|>


<commit_before>// Time Complexity: O(logn)
// Space Complexity: O(1)

class Solution {
    public:
        int divide(int dividend, int divisor) {
            long long a = dividend >= 0 ? dividend : -(long long)dividend;
            long long b = divisor >= 0 ? divisor : -(long long)divisor;

            long long result = 0;
            while(a >= b) {
                long long c = b;
                int i = 0;
                for(; a >= c; c <<= 1, ++i);
                if(i > 0) {
                    a -= c >> 1;
                    result += 1 << (i - 1);
                }
            }

            return ((dividend ^ divisor) >> 31)? -result : result;
        }
};
<commit_msg>Update divide.cpp<commit_after>// Time:  O(logn) = O(1)
// Space: O(1)

// Only using integer type.
class Solution {
public:
    int divide(int dividend, int divisor) {
        // Handle corner case.
        if (dividend == numeric_limits<int>::min() && divisor == -1) {
            return numeric_limits<int>::max();
        }

        int a = dividend > 0 ? -dividend : dividend;
        int b = divisor > 0 ? -divisor : divisor;

        int shift = 0;
        while (b << shift < 0 && shift < 32) {
            ++shift;
        }
        shift -= 1;

        int result = 0;
        while (shift >= 0) {
            if (a <= b << shift) {
                a -= b << shift;
                result += 1 << shift;
            }
            --shift;
        }

        result =  (dividend ^ divisor) >> 31 ? -result : result;
        return result;
    }
};

// Time:  O(logn) = O(1)
// Space: O(1)
// Using long long type.
class Solution2 {
public:
    int divide(int dividend, int divisor) {
        long long result = 0;
        long long a = llabs(dividend);
        long long b = llabs(divisor);

        int shift = 31;
        while (shift >= 0) {
            if (a >= b << shift) {
                a -= b << shift;
                result += 1LL << shift;
            }
            --shift;
        }

        result = ((dividend ^ divisor) >> 31) ? -result : result;
        return min(result, static_cast<long long>(numeric_limits<int>::max()));
    }
};

// Time:  O(logn) = O(1)
// Space: O(1)
// a / b = exp^(ln(a) - ln(b))
class Solution3 {
public:
    int divide(int dividend, int divisor) {
        if (dividend == 0) {
            return 0;
        }
        if (divisor == 0) {
            return numeric_limits<int>::max();
        }

        long long result = exp(log(fabs(dividend)) - log(fabs(divisor)));

        result = ((dividend ^ divisor) >> 31) ? -result : result;
        return min(result, static_cast<long long>(numeric_limits<int>::max()));
    }
};
<|endoftext|>


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

#include "src/profiling/memory/unwinding.h"

#include <sys/types.h>
#include <unistd.h>

#include <unwindstack/MachineArm.h>
#include <unwindstack/MachineArm64.h>
#include <unwindstack/MachineMips.h>
#include <unwindstack/MachineMips64.h>
#include <unwindstack/MachineX86.h>
#include <unwindstack/MachineX86_64.h>
#include <unwindstack/Maps.h>
#include <unwindstack/Memory.h>
#include <unwindstack/Regs.h>
#include <unwindstack/RegsArm.h>
#include <unwindstack/RegsArm64.h>
#include <unwindstack/RegsMips.h>
#include <unwindstack/RegsMips64.h>
#include <unwindstack/RegsX86.h>
#include <unwindstack/RegsX86_64.h>
#include <unwindstack/Unwinder.h>
#include <unwindstack/UserArm.h>
#include <unwindstack/UserArm64.h>
#include <unwindstack/UserMips.h>
#include <unwindstack/UserMips64.h>
#include <unwindstack/UserX86.h>
#include <unwindstack/UserX86_64.h>

#include <procinfo/process_map.h>

#include "perfetto/base/file_utils.h"
#include "perfetto/base/logging.h"
#include "perfetto/base/scoped_file.h"
#include "perfetto/base/string_utils.h"
#include "src/profiling/memory/wire_protocol.h"

namespace perfetto {
namespace profiling {
namespace {

size_t kMaxFrames = 1000;

#pragma GCC diagnostic push
// We do not care about deterministic destructor order.
#pragma GCC diagnostic ignored "-Wglobal-constructors"
#pragma GCC diagnostic ignored "-Wexit-time-destructors"
static std::vector<std::string> kSkipMaps{"heapprofd_client.so"};
#pragma GCC diagnostic pop

std::unique_ptr<unwindstack::Regs> CreateFromRawData(unwindstack::ArchEnum arch,
                                                     void* raw_data) {
  std::unique_ptr<unwindstack::Regs> ret;
  // unwindstack::RegsX::Read returns a raw ptr which we are expected to free.
  switch (arch) {
    case unwindstack::ARCH_X86:
      ret.reset(unwindstack::RegsX86::Read(raw_data));
      break;
    case unwindstack::ARCH_X86_64:
      ret.reset(unwindstack::RegsX86_64::Read(raw_data));
      break;
    case unwindstack::ARCH_ARM:
      ret.reset(unwindstack::RegsArm::Read(raw_data));
      break;
    case unwindstack::ARCH_ARM64:
      ret.reset(unwindstack::RegsArm64::Read(raw_data));
      break;
    case unwindstack::ARCH_MIPS:
      ret.reset(unwindstack::RegsMips::Read(raw_data));
      break;
    case unwindstack::ARCH_MIPS64:
      ret.reset(unwindstack::RegsMips64::Read(raw_data));
      break;
    case unwindstack::ARCH_UNKNOWN:
      ret.reset(nullptr);
      break;
  }
  return ret;
}

// Behaves as a pread64, emulating it if not already exposed by the standard
// library. Safe to use on 32bit platforms for addresses with the top bit set.
// Clobbers the |fd| seek position if emulating.
ssize_t ReadAtOffsetClobberSeekPos(int fd,
                                   void* buf,
                                   size_t count,
                                   uint64_t addr) {
#ifdef __BIONIC__
  return pread64(fd, buf, count, static_cast<off64_t>(addr));
#else
  if (lseek64(fd, static_cast<off64_t>(addr), SEEK_SET) == -1)
    return -1;
  return read(fd, buf, count);
#endif
}

}  // namespace

StackOverlayMemory::StackOverlayMemory(std::shared_ptr<unwindstack::Memory> mem,
                                       uint64_t sp,
                                       uint8_t* stack,
                                       size_t size)
    : mem_(std::move(mem)), sp_(sp), stack_end_(sp + size), stack_(stack) {}

size_t StackOverlayMemory::Read(uint64_t addr, void* dst, size_t size) {
  if (addr >= sp_ && addr + size <= stack_end_ && addr + size > sp_) {
    size_t offset = static_cast<size_t>(addr - sp_);
    memcpy(dst, stack_ + offset, size);
    return size;
  }

  return mem_->Read(addr, dst, size);
}

FDMemory::FDMemory(base::ScopedFile mem_fd) : mem_fd_(std::move(mem_fd)) {}

size_t FDMemory::Read(uint64_t addr, void* dst, size_t size) {
  ssize_t rd = ReadAtOffsetClobberSeekPos(*mem_fd_, dst, size, addr);
  if (rd == -1) {
    PERFETTO_DPLOG("read at offset");
    return 0;
  }
  return static_cast<size_t>(rd);
}

FileDescriptorMaps::FileDescriptorMaps(base::ScopedFile fd)
    : fd_(std::move(fd)) {}

bool FileDescriptorMaps::Parse() {
  // If the process has already exited, lseek or ReadFileDescriptor will
  // return false.
  if (lseek(*fd_, 0, SEEK_SET) == -1)
    return false;

  std::string content;
  if (!base::ReadFileDescriptor(*fd_, &content))
    return false;
  return android::procinfo::ReadMapFileContent(
      &content[0], [&](uint64_t start, uint64_t end, uint16_t flags,
                       uint64_t pgoff, ino_t, const char* name) {
        // Mark a device map in /dev/ and not in /dev/ashmem/ specially.
        if (strncmp(name, "/dev/", 5) == 0 &&
            strncmp(name + 5, "ashmem/", 7) != 0) {
          flags |= unwindstack::MAPS_FLAGS_DEVICE_MAP;
        }
        maps_.push_back(
            new unwindstack::MapInfo(nullptr, start, end, pgoff, flags, name));
      });
}

void FileDescriptorMaps::Reset() {
  for (unwindstack::MapInfo* info : maps_)
    delete info;
  maps_.clear();
}

bool DoUnwind(WireMessage* msg, UnwindingMetadata* metadata, AllocRecord* out) {
  AllocMetadata* alloc_metadata = msg->alloc_header;
  std::unique_ptr<unwindstack::Regs> regs(
      CreateFromRawData(alloc_metadata->arch, alloc_metadata->register_data));
  if (regs == nullptr) {
    unwindstack::FrameData frame_data{};
    frame_data.function_name = "ERROR READING REGISTERS";
    frame_data.map_name = "ERROR";

    out->frames.emplace_back(frame_data, "");
    PERFETTO_DLOG("regs");
    return false;
  }
  uint8_t* stack = reinterpret_cast<uint8_t*>(msg->payload);
  std::shared_ptr<unwindstack::Memory> mems =
      std::make_shared<StackOverlayMemory>(metadata->fd_mem,
                                           alloc_metadata->stack_pointer, stack,
                                           msg->payload_size);

  unwindstack::Unwinder unwinder(kMaxFrames, &metadata->maps, regs.get(), mems);
#if PERFETTO_BUILDFLAG(PERFETTO_ANDROID_BUILD)
  unwinder.SetJitDebug(metadata->jit_debug.get(), regs->Arch());
  unwinder.SetDexFiles(metadata->dex_files.get(), regs->Arch());
#endif
  // Surpress incorrect "variable may be uninitialized" error for if condition
  // after this loop. error_code = LastErrorCode gets run at least once.
  uint8_t error_code = 0;
  for (int attempt = 0; attempt < 2; ++attempt) {
    if (attempt > 0) {
      metadata->ReparseMaps();
#if PERFETTO_BUILDFLAG(PERFETTO_ANDROID_BUILD)
      unwinder.SetJitDebug(metadata->jit_debug.get(), regs->Arch());
      unwinder.SetDexFiles(metadata->dex_files.get(), regs->Arch());
#endif
    }
    unwinder.Unwind(&kSkipMaps, nullptr);
    error_code = unwinder.LastErrorCode();
    if (error_code != unwindstack::ERROR_INVALID_MAP)
      break;
  }
  std::vector<unwindstack::FrameData> frames = unwinder.ConsumeFrames();
  for (unwindstack::FrameData& fd : frames) {
    std::string build_id;
    if (fd.map_name != "") {
      unwindstack::MapInfo* map_info = metadata->maps.Find(fd.pc);
      if (map_info)
        build_id = map_info->GetBuildID();
    }

    out->frames.emplace_back(std::move(fd), std::move(build_id));
  }

  if (error_code != 0) {
    unwindstack::FrameData frame_data{};
    frame_data.function_name = "ERROR " + std::to_string(error_code);
    frame_data.map_name = "ERROR";

    out->frames.emplace_back(frame_data, "");
    PERFETTO_DLOG("unwinding failed %" PRIu8, error_code);
  }

  return true;
}

bool HandleUnwindingRecord(UnwindingRecord* rec, BookkeepingRecord* out) {
  WireMessage msg;
  if (!ReceiveWireMessage(reinterpret_cast<char*>(rec->data.get()), rec->size,
                          &msg))
    return false;
  if (msg.record_type == RecordType::Malloc) {
    std::shared_ptr<UnwindingMetadata> metadata = rec->metadata.lock();
    if (!metadata) {
      // Process has already gone away.
      return false;
    }

    out->alloc_record.alloc_metadata = *msg.alloc_header;
    out->pid = rec->pid;
    out->client_generation = msg.alloc_header->client_generation;
    out->record_type = BookkeepingRecord::Type::Malloc;
    DoUnwind(&msg, metadata.get(), &out->alloc_record);
    return true;
  } else if (msg.record_type == RecordType::Free) {
    out->record_type = BookkeepingRecord::Type::Free;
    out->pid = rec->pid;
    out->client_generation = msg.free_header->client_generation;
    // We need to keep this alive, because msg.free_header is a pointer into
    // this.
    out->free_record.free_data = std::move(rec->data);
    out->free_record.metadata = msg.free_header;
    return true;
  } else {
    PERFETTO_DFATAL("Invalid record type.");
    return false;
  }
}

void UnwindingMainLoop(BoundedQueue<UnwindingRecord>* input_queue,
                       BoundedQueue<BookkeepingRecord>* output_queue) {
  for (;;) {
    UnwindingRecord rec;
    if (!input_queue->Get(&rec))
      return;
    BookkeepingRecord out;
    if (HandleUnwindingRecord(&rec, &out))
      output_queue->Add(std::move(out));
  }
}

}  // namespace profiling
}  // namespace perfetto
<commit_msg>Use emplace_back over push_back to support unique_ptr. am: 5abc126b07<commit_after>/*
 * Copyright (C) 2018 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "src/profiling/memory/unwinding.h"

#include <sys/types.h>
#include <unistd.h>

#include <unwindstack/MachineArm.h>
#include <unwindstack/MachineArm64.h>
#include <unwindstack/MachineMips.h>
#include <unwindstack/MachineMips64.h>
#include <unwindstack/MachineX86.h>
#include <unwindstack/MachineX86_64.h>
#include <unwindstack/Maps.h>
#include <unwindstack/Memory.h>
#include <unwindstack/Regs.h>
#include <unwindstack/RegsArm.h>
#include <unwindstack/RegsArm64.h>
#include <unwindstack/RegsMips.h>
#include <unwindstack/RegsMips64.h>
#include <unwindstack/RegsX86.h>
#include <unwindstack/RegsX86_64.h>
#include <unwindstack/Unwinder.h>
#include <unwindstack/UserArm.h>
#include <unwindstack/UserArm64.h>
#include <unwindstack/UserMips.h>
#include <unwindstack/UserMips64.h>
#include <unwindstack/UserX86.h>
#include <unwindstack/UserX86_64.h>

#include <procinfo/process_map.h>

#include "perfetto/base/file_utils.h"
#include "perfetto/base/logging.h"
#include "perfetto/base/scoped_file.h"
#include "perfetto/base/string_utils.h"
#include "src/profiling/memory/wire_protocol.h"

namespace perfetto {
namespace profiling {
namespace {

size_t kMaxFrames = 1000;

#pragma GCC diagnostic push
// We do not care about deterministic destructor order.
#pragma GCC diagnostic ignored "-Wglobal-constructors"
#pragma GCC diagnostic ignored "-Wexit-time-destructors"
static std::vector<std::string> kSkipMaps{"heapprofd_client.so"};
#pragma GCC diagnostic pop

std::unique_ptr<unwindstack::Regs> CreateFromRawData(unwindstack::ArchEnum arch,
                                                     void* raw_data) {
  std::unique_ptr<unwindstack::Regs> ret;
  // unwindstack::RegsX::Read returns a raw ptr which we are expected to free.
  switch (arch) {
    case unwindstack::ARCH_X86:
      ret.reset(unwindstack::RegsX86::Read(raw_data));
      break;
    case unwindstack::ARCH_X86_64:
      ret.reset(unwindstack::RegsX86_64::Read(raw_data));
      break;
    case unwindstack::ARCH_ARM:
      ret.reset(unwindstack::RegsArm::Read(raw_data));
      break;
    case unwindstack::ARCH_ARM64:
      ret.reset(unwindstack::RegsArm64::Read(raw_data));
      break;
    case unwindstack::ARCH_MIPS:
      ret.reset(unwindstack::RegsMips::Read(raw_data));
      break;
    case unwindstack::ARCH_MIPS64:
      ret.reset(unwindstack::RegsMips64::Read(raw_data));
      break;
    case unwindstack::ARCH_UNKNOWN:
      ret.reset(nullptr);
      break;
  }
  return ret;
}

// Behaves as a pread64, emulating it if not already exposed by the standard
// library. Safe to use on 32bit platforms for addresses with the top bit set.
// Clobbers the |fd| seek position if emulating.
ssize_t ReadAtOffsetClobberSeekPos(int fd,
                                   void* buf,
                                   size_t count,
                                   uint64_t addr) {
#ifdef __BIONIC__
  return pread64(fd, buf, count, static_cast<off64_t>(addr));
#else
  if (lseek64(fd, static_cast<off64_t>(addr), SEEK_SET) == -1)
    return -1;
  return read(fd, buf, count);
#endif
}

}  // namespace

StackOverlayMemory::StackOverlayMemory(std::shared_ptr<unwindstack::Memory> mem,
                                       uint64_t sp,
                                       uint8_t* stack,
                                       size_t size)
    : mem_(std::move(mem)), sp_(sp), stack_end_(sp + size), stack_(stack) {}

size_t StackOverlayMemory::Read(uint64_t addr, void* dst, size_t size) {
  if (addr >= sp_ && addr + size <= stack_end_ && addr + size > sp_) {
    size_t offset = static_cast<size_t>(addr - sp_);
    memcpy(dst, stack_ + offset, size);
    return size;
  }

  return mem_->Read(addr, dst, size);
}

FDMemory::FDMemory(base::ScopedFile mem_fd) : mem_fd_(std::move(mem_fd)) {}

size_t FDMemory::Read(uint64_t addr, void* dst, size_t size) {
  ssize_t rd = ReadAtOffsetClobberSeekPos(*mem_fd_, dst, size, addr);
  if (rd == -1) {
    PERFETTO_DPLOG("read at offset");
    return 0;
  }
  return static_cast<size_t>(rd);
}

FileDescriptorMaps::FileDescriptorMaps(base::ScopedFile fd)
    : fd_(std::move(fd)) {}

bool FileDescriptorMaps::Parse() {
  // If the process has already exited, lseek or ReadFileDescriptor will
  // return false.
  if (lseek(*fd_, 0, SEEK_SET) == -1)
    return false;

  std::string content;
  if (!base::ReadFileDescriptor(*fd_, &content))
    return false;
  return android::procinfo::ReadMapFileContent(
      &content[0], [&](uint64_t start, uint64_t end, uint16_t flags,
                       uint64_t pgoff, ino_t, const char* name) {
        // Mark a device map in /dev/ and not in /dev/ashmem/ specially.
        if (strncmp(name, "/dev/", 5) == 0 &&
            strncmp(name + 5, "ashmem/", 7) != 0) {
          flags |= unwindstack::MAPS_FLAGS_DEVICE_MAP;
        }
        maps_.emplace_back(
            new unwindstack::MapInfo(nullptr, start, end, pgoff, flags, name));
      });
}

void FileDescriptorMaps::Reset() {
  maps_.clear();
}

bool DoUnwind(WireMessage* msg, UnwindingMetadata* metadata, AllocRecord* out) {
  AllocMetadata* alloc_metadata = msg->alloc_header;
  std::unique_ptr<unwindstack::Regs> regs(
      CreateFromRawData(alloc_metadata->arch, alloc_metadata->register_data));
  if (regs == nullptr) {
    unwindstack::FrameData frame_data{};
    frame_data.function_name = "ERROR READING REGISTERS";
    frame_data.map_name = "ERROR";

    out->frames.emplace_back(frame_data, "");
    PERFETTO_DLOG("regs");
    return false;
  }
  uint8_t* stack = reinterpret_cast<uint8_t*>(msg->payload);
  std::shared_ptr<unwindstack::Memory> mems =
      std::make_shared<StackOverlayMemory>(metadata->fd_mem,
                                           alloc_metadata->stack_pointer, stack,
                                           msg->payload_size);

  unwindstack::Unwinder unwinder(kMaxFrames, &metadata->maps, regs.get(), mems);
#if PERFETTO_BUILDFLAG(PERFETTO_ANDROID_BUILD)
  unwinder.SetJitDebug(metadata->jit_debug.get(), regs->Arch());
  unwinder.SetDexFiles(metadata->dex_files.get(), regs->Arch());
#endif
  // Surpress incorrect "variable may be uninitialized" error for if condition
  // after this loop. error_code = LastErrorCode gets run at least once.
  uint8_t error_code = 0;
  for (int attempt = 0; attempt < 2; ++attempt) {
    if (attempt > 0) {
      metadata->ReparseMaps();
#if PERFETTO_BUILDFLAG(PERFETTO_ANDROID_BUILD)
      unwinder.SetJitDebug(metadata->jit_debug.get(), regs->Arch());
      unwinder.SetDexFiles(metadata->dex_files.get(), regs->Arch());
#endif
    }
    unwinder.Unwind(&kSkipMaps, nullptr);
    error_code = unwinder.LastErrorCode();
    if (error_code != unwindstack::ERROR_INVALID_MAP)
      break;
  }
  std::vector<unwindstack::FrameData> frames = unwinder.ConsumeFrames();
  for (unwindstack::FrameData& fd : frames) {
    std::string build_id;
    if (fd.map_name != "") {
      unwindstack::MapInfo* map_info = metadata->maps.Find(fd.pc);
      if (map_info)
        build_id = map_info->GetBuildID();
    }

    out->frames.emplace_back(std::move(fd), std::move(build_id));
  }

  if (error_code != 0) {
    unwindstack::FrameData frame_data{};
    frame_data.function_name = "ERROR " + std::to_string(error_code);
    frame_data.map_name = "ERROR";

    out->frames.emplace_back(frame_data, "");
    PERFETTO_DLOG("unwinding failed %" PRIu8, error_code);
  }

  return true;
}

bool HandleUnwindingRecord(UnwindingRecord* rec, BookkeepingRecord* out) {
  WireMessage msg;
  if (!ReceiveWireMessage(reinterpret_cast<char*>(rec->data.get()), rec->size,
                          &msg))
    return false;
  if (msg.record_type == RecordType::Malloc) {
    std::shared_ptr<UnwindingMetadata> metadata = rec->metadata.lock();
    if (!metadata) {
      // Process has already gone away.
      return false;
    }

    out->alloc_record.alloc_metadata = *msg.alloc_header;
    out->pid = rec->pid;
    out->client_generation = msg.alloc_header->client_generation;
    out->record_type = BookkeepingRecord::Type::Malloc;
    DoUnwind(&msg, metadata.get(), &out->alloc_record);
    return true;
  } else if (msg.record_type == RecordType::Free) {
    out->record_type = BookkeepingRecord::Type::Free;
    out->pid = rec->pid;
    out->client_generation = msg.free_header->client_generation;
    // We need to keep this alive, because msg.free_header is a pointer into
    // this.
    out->free_record.free_data = std::move(rec->data);
    out->free_record.metadata = msg.free_header;
    return true;
  } else {
    PERFETTO_DFATAL("Invalid record type.");
    return false;
  }
}

void UnwindingMainLoop(BoundedQueue<UnwindingRecord>* input_queue,
                       BoundedQueue<BookkeepingRecord>* output_queue) {
  for (;;) {
    UnwindingRecord rec;
    if (!input_queue->Get(&rec))
      return;
    BookkeepingRecord out;
    if (HandleUnwindingRecord(&rec, &out))
      output_queue->Add(std::move(out));
  }
}

}  // namespace profiling
}  // namespace perfetto
<|endoftext|>


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

#include "app.hxx"
#include "wrapper.hxx"

#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif

#include <offmgr/app.hxx>
#include <comphelper/processfactory.hxx>
#ifndef _UTL_CONFIGMGR_HXX_
#include <unotools/configmgr.hxx>
#endif

#include <setup2/installer.hxx>
#include <svtools/pathoptions.hxx>

#define DEFINE_CONST_UNICODE(CONSTASCII)        UniString(RTL_CONSTASCII_USTRINGPARAM(CONSTASCII##))

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;

Desktop aDesktop;

Desktop::Desktop()
{
}

void Desktop::Main()
{
    SetAppName( DEFINE_CONST_UNICODE("soffice") );

    Installer* pInstaller = new Installer;
    pInstaller->InitializeInstallation( Application::GetAppFileName() );
    delete pInstaller;

    SvtPathOptions* pPathOptions = new SvtPathOptions;
    RegisterServices();
    OfficeWrapper* pWrapper = new OfficeWrapper( ::comphelper::getProcessServiceFactory() );
//    Reference < XComponent > xWrapper( ::utl::getProcessServiceFactory()->createInstance( DEFINE_CONST_UNICODE("com.sun.star.office.OfficeWrapper" ) ), UNO_QUERY );
    SfxApplicationClass::Main();
//    xWrapper->dispose();

    if( pWrapper!=NULL)
    {
        delete pWrapper;
        pWrapper=NULL;
    }

    delete pPathOptions;
    utl::ConfigManager::RemoveConfigManager();
}

void Desktop::SystemSettingsChanging( AllSettings& rSettings, Window* pFrame )
{
    OFF_APP()->SystemSettingsChanging( rSettings, pFrame );
}

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

#include "app.hxx"
#include "wrapper.hxx"

#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif

#include <offmgr/app.hxx>
#include <comphelper/processfactory.hxx>
#ifndef _UTL_CONFIGMGR_HXX_
#include <unotools/configmgr.hxx>
#endif

#include <setup2/installer.hxx>
#include <svtools/pathoptions.hxx>
#include <unotools/configmgr.hxx>

#define DEFINE_CONST_UNICODE(CONSTASCII)        UniString(RTL_CONSTASCII_USTRINGPARAM(CONSTASCII##))

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;

void ReplaceStringHookProc( UniString& rStr )
{
    static String aBrandName;
    if ( !aBrandName.Len() )
    {
        Any aRet = ::utl::ConfigManager::GetDirectConfigProperty( ::utl::ConfigManager::PRODUCTNAME );
        rtl::OUString aTmp;
        aRet >>= aTmp;
        aBrandName = aTmp;
    }

    rStr.SearchAndReplaceAscii( "%PRODUCTNAME", aBrandName );
}

Desktop aDesktop;

Desktop::Desktop()
{
}

void Desktop::Main()
{
    ResMgr::SetReadStringHook( ReplaceStringHookProc );
    SetAppName( DEFINE_CONST_UNICODE("soffice") );

    Installer* pInstaller = new Installer;
    pInstaller->InitializeInstallation( Application::GetAppFileName() );
    delete pInstaller;

    SvtPathOptions* pPathOptions = new SvtPathOptions;
    RegisterServices();
    OfficeWrapper* pWrapper = new OfficeWrapper( ::comphelper::getProcessServiceFactory() );
//    Reference < XComponent > xWrapper( ::utl::getProcessServiceFactory()->createInstance( DEFINE_CONST_UNICODE("com.sun.star.office.OfficeWrapper" ) ), UNO_QUERY );
    SfxApplicationClass::Main();
//    xWrapper->dispose();

    if( pWrapper!=NULL)
    {
        delete pWrapper;
        pWrapper=NULL;
    }

    delete pPathOptions;
    utl::ConfigManager::RemoveConfigManager();
}

void Desktop::SystemSettingsChanging( AllSettings& rSettings, Window* pFrame )
{
    OFF_APP()->SystemSettingsChanging( rSettings, pFrame );
}

<|endoftext|>


<commit_before>#include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;
int main()
{
    double x[] = {10.2,11.4,11.5,12.5,13.1,13.4,13.6,15,15.2,15.3,15.6,16.4,16.5,17,17.1};
    double y[] = {69.81,82.75,81.75,80.38,85.89,75.32,69.81,78.54,81.29,99.2,86.35,110.23,106.55,85.50,90.02};
    int i,j,k,n;
    cout<<"\n Cuantos partes de datos ingresaran?\n";
    cin>>n;
    double a0,a1,error,EE;
    //cout<<"\n Pon los valores X\n";
    //for (i=0;i<n;i++)
       // cin>>x[i];
    //cout<<"\n Pon los valores Y\n";
    //for (i=0;i<n;i++)
        //cin>>y[i];
    double xsum=0,x2sum=0,ysum=0,xysum=0,mediaX,mediaY;
    for (i=0;i<n;i++)
    {
        xsum=xsum+x[i];
        ysum=ysum+y[i];
        x2sum=x2sum+pow(x[i],2);
        xysum=xysum+x[i]*y[i];
    }
        mediaX=xsum/n;
        mediaY=ysum/n;
        a1=(n*xysum-xsum*ysum)/(n*x2sum-xsum*xsum); // pendiente
        a0=(mediaY-a1*mediaX); // interseccion

    cout<<"La regresion linear es y= "<<a1<<"x + "<<a0<<endl;

    //coeficiente de correlación
        double st,sr;
        pxy=sx2=sr=divisionAbajo=0.0;
        for(int i=0; i<n; i++){
            sr+=pow((y[i]-a0-a1*x[i]),2);
            st+=(y[i]-mediaY)*(y[i]-mediaY);
        }

    cout<<"\n Coeficiente de la relacion: "<<sqrt((st-sr)/st)<<"\n";

    EE=sqrt(sr/(n - 2));

    cout<<"\n Error estandar "<<  EE;
    return 0;

}
<commit_msg>Update linearRegresion.cpp<commit_after>#include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;
int main()
{
    double x[] = {10.2,11.4,11.5,12.5,13.1,13.4,13.6,15,15.2,15.3,15.6,16.4,16.5,17,17.1};
    double y[] = {69.81,82.75,81.75,80.38,85.89,75.32,69.81,78.54,81.29,99.2,86.35,110.23,106.55,85.50,90.02};
    int i,j,k,n;
    cout<<"\n Cuantos pares de datos ingresaran?\n";
    cin>>n;
    double a0=0,a1=0,error=0,EE=0,xsum=0,x2sum=0,ysum=0,xysum=0,mediaX=0,mediaY=0;

    for (i=0;i<n;i++)
    {
        xsum=xsum+x[i];
        ysum=ysum+y[i];
        x2sum=x2sum+pow(x[i],2);
        xysum=xysum+x[i]*y[i];
    }
        mediaX=xsum/n;
        mediaY=ysum/n;
        a1=(n*xysum-xsum*ysum)/(n*x2sum-xsum*xsum); // pendiente
        a0=(mediaY-a1*mediaX); // interseccion

    cout<<"La regresion linear es y= "<<a1<<"x + "<<a0<<endl;

    //coeficiente de correlación
        double st,sr;
        pxy=sx2=sr=divisionAbajo=0.0;
        for(int i=0; i<n; i++){
            sr+=pow((y[i]-a0-a1*x[i]),2);
            st+=(y[i]-mediaY)*(y[i]-mediaY);
        }

    cout<<"\n Coeficiente de la relacion: "<<sqrt((st-sr)/st)<<"\n";

    EE=sqrt(sr/(n - 2));

    cout<<"\n Error estandar "<<  EE;
    return 0;

}
<|endoftext|>


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

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

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

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

#include "tensorflow/core/kernels/cwise_ops_common.h"

namespace tensorflow {

REGISTER5(BinaryOp, CPU, "Mul", functor::mul, float, Eigen::half, double,
          uint8, int32);

#if TENSORFLOW_USE_SYCL
#define REGISTER_SYCL_KERNEL(TYPE)                                    \
  REGISTER_KERNEL_BUILDER(                                            \
                          Name("Mul")                                 \
                          .Device(DEVICE_SYCL)                        \
                          .TypeConstraint<TYPE>("T"),                 \
                          BinaryOp<SYCLDevice, functor::mul<TYPE>>);
REGISTER_SYCL_KERNEL(float)
REGISTER_SYCL_KERNEL(double)
#undef REGISTER_SYCL_KERNEL
REGISTER_KERNEL_BUILDER(Name("Mul")
                            .Device(DEVICE_SYCL)
                            .HostMemory("x")
                            .HostMemory("y")
                            .HostMemory("z")
                            .TypeConstraint<int32>("T"),
                        BinaryOp<CPUDevice, functor::mul<int32>>);
#endif // TENSORFLOW_USE_SYCL
#if GOOGLE_CUDA
REGISTER4(BinaryOp, GPU, "Mul", functor::mul, float, Eigen::half, double,
           uint8);
// A special GPU kernel for int32.
// TODO(b/25387198): Also enable int32 in device memory. This kernel
// registration requires all int32 inputs and outputs to be in host memory.
REGISTER_KERNEL_BUILDER(Name("Mul")
                            .Device(DEVICE_GPU)
                            .HostMemory("x")
                            .HostMemory("y")
                            .HostMemory("z")
                            .TypeConstraint<int32>("T"),
                        BinaryOp<CPUDevice, functor::mul<int32>>);
#endif

}  // namespace tensorflow
<commit_msg>Add int32 version of Mul kernel to the slim kernels. Change: 151267767<commit_after>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.

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

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

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

#include "tensorflow/core/kernels/cwise_ops_common.h"

namespace tensorflow {

REGISTER5(BinaryOp, CPU, "Mul", functor::mul, float, Eigen::half, double,
          uint8, int32);
#if defined(__ANDROID_TYPES_SLIM__)
// We only register the first type when we have multi-argument calls in the
// case where we're trying to reduce executable size, but it turns out that the
// int32 version of this op is needed, so explicitly include it.
REGISTER(BinaryOp, CPU, "Mul", functor::mul, int32);
#endif  // __ANDROID_TYPES_SLIM__

#if TENSORFLOW_USE_SYCL
#define REGISTER_SYCL_KERNEL(TYPE)                                    \
  REGISTER_KERNEL_BUILDER(                                            \
                          Name("Mul")                                 \
                          .Device(DEVICE_SYCL)                        \
                          .TypeConstraint<TYPE>("T"),                 \
                          BinaryOp<SYCLDevice, functor::mul<TYPE>>);
REGISTER_SYCL_KERNEL(float)
REGISTER_SYCL_KERNEL(double)
#undef REGISTER_SYCL_KERNEL
REGISTER_KERNEL_BUILDER(Name("Mul")
                            .Device(DEVICE_SYCL)
                            .HostMemory("x")
                            .HostMemory("y")
                            .HostMemory("z")
                            .TypeConstraint<int32>("T"),
                        BinaryOp<CPUDevice, functor::mul<int32>>);
#endif // TENSORFLOW_USE_SYCL
#if GOOGLE_CUDA
REGISTER4(BinaryOp, GPU, "Mul", functor::mul, float, Eigen::half, double,
           uint8);
// A special GPU kernel for int32.
// TODO(b/25387198): Also enable int32 in device memory. This kernel
// registration requires all int32 inputs and outputs to be in host memory.
REGISTER_KERNEL_BUILDER(Name("Mul")
                            .Device(DEVICE_GPU)
                            .HostMemory("x")
                            .HostMemory("y")
                            .HostMemory("z")
                            .TypeConstraint<int32>("T"),
                        BinaryOp<CPUDevice, functor::mul<int32>>);
#endif

}  // namespace tensorflow
<|endoftext|>