<commit_before>/* Copyright 2021 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/lite/kernels/internal/reference/integer_ops/logistic.h"

#include "tensorflow/lite/c/builtin_op_data.h"
#include "tensorflow/lite/c/common.h"
#include "tensorflow/lite/kernels/internal/common.h"
#include "tensorflow/lite/kernels/internal/quantization_util.h"
#include "tensorflow/lite/kernels/internal/reference/logistic.h"
#include "tensorflow/lite/kernels/internal/tensor_ctypes.h"
#include "tensorflow/lite/kernels/kernel_util.h"
#include "tensorflow/lite/kernels/op_macros.h"
#include "tensorflow/lite/micro/kernels/kernel_util.h"
#include "tensorflow/lite/micro/kernels/logistic.h"
#include "tensorflow/lite/micro/kernels/xtensa/xtensa.h"
#include "tensorflow/lite/micro/micro_error_reporter.h"

namespace tflite {
namespace {

void* LogisticInit(TfLiteContext* context, const char* buffer, size_t length) {
  TFLITE_DCHECK(context->AllocatePersistentBuffer != nullptr);
  return context->AllocatePersistentBuffer(context, sizeof(OpDataLogistic));
}

TfLiteStatus LogisticEval(TfLiteContext* context, TfLiteNode* node) {
  const TfLiteEvalTensor* input =
      tflite::micro::GetEvalInput(context, node, kLogisticInputTensor);
  TfLiteEvalTensor* output =
      tflite::micro::GetEvalOutput(context, node, kLogisticOutputTensor);

  TFLITE_DCHECK(node->user_data != nullptr);
  OpDataLogistic* data = static_cast<OpDataLogistic*>(node->user_data);

  if (input->type != output->type) {
    MicroPrintf(
        "Input and output types must be identical. Input %s, output %s.",
        TfLiteTypeGetName(input->type), TfLiteTypeGetName(output->type));
    return kTfLiteError;
  }

  switch (input->type) {
    case kTfLiteFloat32: {
#if HIFI_VFPU && defined(HIFI5)
      const RuntimeShape& input_shape = tflite::micro::GetTensorShape(input);
      const RuntimeShape& output_shape = tflite::micro::GetTensorShape(output);
      const int flat_size = MatchingFlatSize(input_shape, output_shape);

      const float* inp_data_ptr = tflite::micro::GetTensorData<float>(input);
      float* out_data_ptr = tflite::micro::GetTensorData<float>(output);

      TF_LITE_ENSURE_EQ(
          context,
          xa_nn_vec_sigmoid_f32_f32(out_data_ptr, inp_data_ptr, flat_size), 0);
#else
      reference_ops::Logistic(tflite::micro::GetTensorShape(input),
                              tflite::micro::GetTensorData<float>(input),
                              tflite::micro::GetTensorShape(output),
                              tflite::micro::GetTensorData<float>(output));
#endif  // HIFI_VFPU && defined(HIFI5)
      break;
    }
    case kTfLiteInt8: {
#if defined(HIFI5)
      const RuntimeShape& input_shape = tflite::micro::GetTensorShape(input);
      const RuntimeShape& output_shape = tflite::micro::GetTensorShape(output);
      const int flat_size = MatchingFlatSize(input_shape, output_shape);

      const int8_t* input_data_ptr =
          tflite::micro::GetTensorData<int8_t>(input);
      int8_t* output_data_ptr = tflite::micro::GetTensorData<int8_t>(output);

      TF_LITE_ENSURE_EQ(
          context,
          xa_nn_vec_sigmoid_asym8s_asym8s(
              output_data_ptr, input_data_ptr, data->input_zero_point,
              data->input_range_radius, data->input_multiplier,
              data->input_left_shift, flat_size),
          0);
#else
      reference_integer_ops::Logistic(
          data->input_zero_point, data->input_range_radius,
          data->input_multiplier, data->input_left_shift,
          NumElements(input->dims), tflite::micro::GetTensorData<int8_t>(input),
          tflite::micro::GetTensorData<int8_t>(output));
#endif  // defined(HIFI5)
      break;
    }
    case kTfLiteInt16: {
      switch (output->type) {
        case kTfLiteInt16:
          reference_integer_ops::Logistic(
              data->input_multiplier, data->input_left_shift,
              NumElements(input->dims),
              tflite::micro::GetTensorData<int16_t>(input),
              tflite::micro::GetTensorData<int16_t>(output));
          break;
        default:
          MicroPrintf("Input %s, output %s not supported.",
                      TfLiteTypeGetName(input->type),
                      TfLiteTypeGetName(output->type));
          return kTfLiteError;
      }
      break;
    }
    default: {
      MicroPrintf("Input %s, output %s not supported.",
                  TfLiteTypeGetName(input->type),
                  TfLiteTypeGetName(output->type));
      return kTfLiteError;
    }
  }
  return kTfLiteOk;
}

}  // namespace

TfLiteRegistration Register_LOGISTIC() {
  return {/*init=*/LogisticInit,
          /*free=*/nullptr,
          /*prepare=*/LogisticPrepare,
          /*invoke=*/LogisticEval,
          /*profiling_string=*/nullptr,
          /*builtin_code=*/0,
          /*custom_name=*/nullptr,
          /*version=*/0};
}
}  // namespace tflite
<commit_msg>Logistic: Enabled optimized code for HiFi 4. (#1064)<commit_after>/* Copyright 2021 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/lite/kernels/internal/reference/integer_ops/logistic.h"

#include "tensorflow/lite/c/builtin_op_data.h"
#include "tensorflow/lite/c/common.h"
#include "tensorflow/lite/kernels/internal/common.h"
#include "tensorflow/lite/kernels/internal/quantization_util.h"
#include "tensorflow/lite/kernels/internal/reference/logistic.h"
#include "tensorflow/lite/kernels/internal/tensor_ctypes.h"
#include "tensorflow/lite/kernels/kernel_util.h"
#include "tensorflow/lite/kernels/op_macros.h"
#include "tensorflow/lite/micro/kernels/kernel_util.h"
#include "tensorflow/lite/micro/kernels/logistic.h"
#include "tensorflow/lite/micro/kernels/xtensa/xtensa.h"
#include "tensorflow/lite/micro/micro_error_reporter.h"

namespace tflite {
namespace {

void* LogisticInit(TfLiteContext* context, const char* buffer, size_t length) {
  TFLITE_DCHECK(context->AllocatePersistentBuffer != nullptr);
  return context->AllocatePersistentBuffer(context, sizeof(OpDataLogistic));
}

TfLiteStatus LogisticEval(TfLiteContext* context, TfLiteNode* node) {
  const TfLiteEvalTensor* input =
      tflite::micro::GetEvalInput(context, node, kLogisticInputTensor);
  TfLiteEvalTensor* output =
      tflite::micro::GetEvalOutput(context, node, kLogisticOutputTensor);

  TFLITE_DCHECK(node->user_data != nullptr);
  OpDataLogistic* data = static_cast<OpDataLogistic*>(node->user_data);

  if (input->type != output->type) {
    MicroPrintf(
        "Input and output types must be identical. Input %s, output %s.",
        TfLiteTypeGetName(input->type), TfLiteTypeGetName(output->type));
    return kTfLiteError;
  }

  switch (input->type) {
    case kTfLiteFloat32: {
#if HIFI_VFPU && (defined(HIFI4) || defined(HIFI5))
      const RuntimeShape& input_shape = tflite::micro::GetTensorShape(input);
      const RuntimeShape& output_shape = tflite::micro::GetTensorShape(output);
      const int flat_size = MatchingFlatSize(input_shape, output_shape);

      const float* inp_data_ptr = tflite::micro::GetTensorData<float>(input);
      float* out_data_ptr = tflite::micro::GetTensorData<float>(output);

      TF_LITE_ENSURE_EQ(
          context,
          xa_nn_vec_sigmoid_f32_f32(out_data_ptr, inp_data_ptr, flat_size), 0);
#else
      reference_ops::Logistic(tflite::micro::GetTensorShape(input),
                              tflite::micro::GetTensorData<float>(input),
                              tflite::micro::GetTensorShape(output),
                              tflite::micro::GetTensorData<float>(output));
#endif  // HIFI_VFPU && (defined(HIFI4) || defined(HIFI5))
      break;
    }
    case kTfLiteInt8: {
#if defined(HIFI4) || defined(HIFI5)
      const RuntimeShape& input_shape = tflite::micro::GetTensorShape(input);
      const RuntimeShape& output_shape = tflite::micro::GetTensorShape(output);
      const int flat_size = MatchingFlatSize(input_shape, output_shape);

      const int8_t* input_data_ptr =
          tflite::micro::GetTensorData<int8_t>(input);
      int8_t* output_data_ptr = tflite::micro::GetTensorData<int8_t>(output);

      TF_LITE_ENSURE_EQ(
          context,
          xa_nn_vec_sigmoid_asym8s_asym8s(
              output_data_ptr, input_data_ptr, data->input_zero_point,
              data->input_range_radius, data->input_multiplier,
              data->input_left_shift, flat_size),
          0);
#else
      reference_integer_ops::Logistic(
          data->input_zero_point, data->input_range_radius,
          data->input_multiplier, data->input_left_shift,
          NumElements(input->dims), tflite::micro::GetTensorData<int8_t>(input),
          tflite::micro::GetTensorData<int8_t>(output));
#endif  // defined(HIFI4) || defined(HIFI5)
      break;
    }
    case kTfLiteInt16: {
      switch (output->type) {
        case kTfLiteInt16:
          reference_integer_ops::Logistic(
              data->input_multiplier, data->input_left_shift,
              NumElements(input->dims),
              tflite::micro::GetTensorData<int16_t>(input),
              tflite::micro::GetTensorData<int16_t>(output));
          break;
        default:
          MicroPrintf("Input %s, output %s not supported.",
                      TfLiteTypeGetName(input->type),
                      TfLiteTypeGetName(output->type));
          return kTfLiteError;
      }
      break;
    }
    default: {
      MicroPrintf("Input %s, output %s not supported.",
                  TfLiteTypeGetName(input->type),
                  TfLiteTypeGetName(output->type));
      return kTfLiteError;
    }
  }
  return kTfLiteOk;
}

}  // namespace

TfLiteRegistration Register_LOGISTIC() {
  return {/*init=*/LogisticInit,
          /*free=*/nullptr,
          /*prepare=*/LogisticPrepare,
          /*invoke=*/LogisticEval,
          /*profiling_string=*/nullptr,
          /*builtin_code=*/0,
          /*custom_name=*/nullptr,
          /*version=*/0};
}
}  // namespace tflite
<|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/views/app_launcher.h"

#include <string>
#include <vector>

#include "app/resource_bundle.h"
#include "base/command_line.h"
#include "base/message_loop.h"
#include "base/string_util.h"
#include "base/task.h"
#include "chrome/app/chrome_dll_resource.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/view_ids.h"
#include "chrome/browser/views/dom_view.h"
#include "chrome/browser/views/info_bubble.h"
#include "chrome/browser/views/frame/browser_view.h"
#include "chrome/browser/views/location_bar/location_bar_view.h"
#include "chrome/common/url_constants.h"
#include "views/widget/root_view.h"

#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/status/status_area_view.h"
#endif

namespace {

// Padding between the navigation bar and the render view contents.
const int kNavigationBarBottomPadding = 3;

// NavigationBar constants.
const int kNavigationBarBorderThickness = 1;

const SkColor kBorderColor = SkColorSetRGB(205, 201, 201);

// Command line switch for specifying url of the page.
// TODO: nuke when we convert to the real app page. Also nuke code in
// AddNewContents
const wchar_t kURLSwitch[] = L"main-menu-url";

// Returns the URL of the menu.
static GURL GetMenuURL() {
  std::wstring url_string =
      CommandLine::ForCurrentProcess()->GetSwitchValue(kURLSwitch);
  if (!url_string.empty())
    return GURL(WideToUTF8(url_string));
  return GURL(chrome::kChromeUIAppLauncherURL);
}

// Returns the location bar view of |browser|.
static views::View* GetBrowserLocationBar(Browser* browser) {
  BrowserView* browser_view = static_cast<BrowserView*>(browser->window());
  views::RootView* root_view = views::Widget::GetWidgetFromNativeWindow(
      browser_view->GetNativeHandle())->GetRootView();
  return root_view->GetViewByID(VIEW_ID_LOCATION_BAR);
}

}  // namespace

// InfoBubbleContentsView
//
// The view that contains the navigation bar and DOMUI.
// It is displayed in an info-bubble.

class InfoBubbleContentsView : public views::View,
                               public LocationBarView::Delegate,
                               public CommandUpdater::CommandUpdaterDelegate {
 public:
  explicit InfoBubbleContentsView(AppLauncher* app_launcher);
  ~InfoBubbleContentsView();

  // Computes and sets the preferred size for the InfoBubbleContentsView based
  // on the preferred size of the DOMUI contents specified.
  void ComputePreferredSize(const gfx::Size& dom_view_preferred_size);

  // Sets the initial focus.
  // Should be called when the bubble that contains us is shown.
  void BubbleShown();

  // views::View override:
  virtual gfx::Size GetPreferredSize();
  virtual void Layout();
  virtual void ViewHierarchyChanged(bool is_add,
                                    views::View* parent,
                                    views::View* child);

  // LocationBarView::Delegate implementation:
  virtual TabContents* GetTabContents();
  virtual void OnInputInProgress(bool in_progress) {}

  // CommandUpdater::CommandUpdaterDelegate implementation:
  virtual void ExecuteCommand(int id);

 private:
  // The application launcher displaying this info bubble.
  AppLauncher* app_launcher_;

  // The location bar.
  LocationBarView* location_bar_;

  // The view containing the renderer view.
  DOMView* dom_view_;

  // The preferred size for this view (at which it fits its contents).
  gfx::Size preferred_size_;

  // CommandUpdater the location bar sends commands to.
  CommandUpdater command_updater_;

  // The width of the browser's location bar.
  int browser_location_bar_width_;

  DISALLOW_COPY_AND_ASSIGN(InfoBubbleContentsView);
};

InfoBubbleContentsView::InfoBubbleContentsView(AppLauncher* app_launcher)
    : app_launcher_(app_launcher),
      location_bar_(NULL),
      dom_view_(NULL),
      ALLOW_THIS_IN_INITIALIZER_LIST(command_updater_(this)) {
  // Allow the location bar to open URLs.
  command_updater_.UpdateCommandEnabled(IDC_OPEN_CURRENT_URL, true);
  DCHECK(app_launcher);

  browser_location_bar_width_ =
      GetBrowserLocationBar(app_launcher->browser())->width();
}

InfoBubbleContentsView::~InfoBubbleContentsView() {
}

void InfoBubbleContentsView::ComputePreferredSize(
    const gfx::Size& dom_view_preferred_size) {
  preferred_size_ = dom_view_preferred_size;

  // Add the padding and location bar height.
  preferred_size_.Enlarge(
      0, location_bar_->height() + kNavigationBarBottomPadding);

  // Make sure the width is at least the browser location bar width.
  if (preferred_size_.width() < browser_location_bar_width_)
    preferred_size_.set_width(browser_location_bar_width_);
}

void InfoBubbleContentsView::BubbleShown() {
  location_bar_->RequestFocus();
}

void InfoBubbleContentsView::ViewHierarchyChanged(
    bool is_add, views::View* parent, views::View* child) {
  if (!is_add || child != this)
    return;

  DCHECK(!dom_view_);
  dom_view_ = new DOMView();
  AddChildView(dom_view_);
  // We pass NULL for site instance so the renderer uses its own process.
  dom_view_->Init(app_launcher_->browser()->profile(), NULL);
  // We make the AppLauncher the TabContents delegate so we get notifications
  // from the page to open links.
  dom_view_->tab_contents()->set_delegate(app_launcher_);
  GURL url = GetMenuURL();
  std::string ref = url.ref();
  if (!app_launcher_->hash_params().empty()) {
    if (!ref.empty())
      ref += "&";
    ref += app_launcher_->hash_params();

    url_canon::Replacements<char> replacements;
    replacements.SetRef(ref.c_str(), url_parse::Component(0, ref.size()));
    url = url.ReplaceComponents(replacements);
  }
  dom_view_->LoadURL(url);

  Browser* browser = app_launcher_->browser();
  location_bar_ =  new LocationBarView(browser->profile(),
                                       &command_updater_,
                                       browser->toolbar_model(),
                                       this,
                                       LocationBarView::APP_LAUNCHER);

  location_bar_->set_border(
      views::Border::CreateSolidBorder(kNavigationBarBorderThickness,
                                       kBorderColor));
  AddChildView(location_bar_);
  location_bar_->Init();
  // Size the location to its preferred size so ComputePreferredSize() computes
  // the right size.
  location_bar_->SizeToPreferredSize();
  ComputePreferredSize(gfx::Size(browser_location_bar_width_, 0));
  Layout();
}

TabContents* InfoBubbleContentsView::GetTabContents() {
  return app_launcher_->browser()->GetSelectedTabContents();
}

gfx::Size InfoBubbleContentsView::GetPreferredSize() {
  return preferred_size_;
}

void InfoBubbleContentsView::Layout() {
  if (bounds().IsEmpty() || GetChildViewCount() == 0)
    return;

  gfx::Rect bounds = GetLocalBounds(false);
  location_bar_->SetBounds(bounds.x(), bounds.y(), bounds.width(),
                           location_bar_->GetPreferredSize().height());
  int render_y = location_bar_->bounds().bottom() + kNavigationBarBottomPadding;
  dom_view_->SetBounds(0, render_y,
                       width(),
                       std::max(0, bounds.height() - render_y + bounds.y()));
}

void InfoBubbleContentsView::ExecuteCommand(int id) {
  // The user navigated by typing or selecting an entry in the location bar.
  DCHECK_EQ(IDC_OPEN_CURRENT_URL, id);
  GURL url(WideToUTF8(location_bar_->GetInputString()));
  app_launcher_->AddTabWithURL(url, location_bar_->GetPageTransition());
  app_launcher_->Hide();
}

////////////////////////////////////////////////////////////////////////////////
// AppLauncher

AppLauncher::AppLauncher(Browser* browser)
    : browser_(browser),
      info_bubble_(NULL) {
  DCHECK(browser);
  info_bubble_content_ = new InfoBubbleContentsView(this);
}

AppLauncher::~AppLauncher() {
}

// static
AppLauncher* AppLauncher::Show(Browser* browser,
                               const gfx::Rect& bounds,
                               const gfx::Point& bubble_anchor,
                               const std::string& hash_params) {
  AppLauncher* app_launcher = new AppLauncher(browser);
  BrowserView* browser_view = static_cast<BrowserView*>(browser->window());
  app_launcher->hash_params_ = hash_params;
  app_launcher->info_bubble_ =
      PinnedContentsInfoBubble::Show(browser_view->GetWidget(),
          bounds, BubbleBorder::TOP_LEFT, bubble_anchor,
          app_launcher->info_bubble_content_, app_launcher);
  app_launcher->info_bubble_content_->BubbleShown();
  return app_launcher;
}

// static
AppLauncher* AppLauncher::ShowForNewTab(Browser* browser,
                                        const std::string& hash_params) {
  BrowserView* browser_view = static_cast<BrowserView*>(browser->window());
  TabStrip* tabstrip = browser_view->tabstrip()->AsTabStrip();
  if (!tabstrip)
    return NULL;
  gfx::Rect bounds = tabstrip->GetNewTabButtonBounds();
  gfx::Point origin = bounds.origin();
  views::RootView::ConvertPointToScreen(tabstrip, &origin);
  bounds.set_origin(origin);

  // Figure out where the location bar is, so we can pin the bubble to
  // make our url bar appear exactly over it.
  views::View* location_bar = GetBrowserLocationBar(browser);
  gfx::Point location_bar_origin = location_bar->bounds().origin();
  views::RootView::ConvertPointToScreen(location_bar->GetParent(),
                                        &location_bar_origin);

  return Show(browser, bounds, location_bar_origin, hash_params);
}

void AppLauncher::Hide() {
  info_bubble_->Close();
}

void AppLauncher::OpenURLFromTab(TabContents* source,
                                 const GURL& url, const GURL& referrer,
                                 WindowOpenDisposition disposition,
                                 PageTransition::Type transition) {
  // TODO(jcivelli): we should call Browser::OpenApplicationTab(), we would need
  //                 to access the app for this URL.
  // The user clicked an item in the app launcher contents.
  AddTabWithURL(url, PageTransition::AUTO_BOOKMARK);
  Hide();
}

void AppLauncher::AddNewContents(TabContents* source,
                                 TabContents* new_contents,
                                 WindowOpenDisposition disposition,
                                 const gfx::Rect& initial_pos,
                                 bool user_gesture) {
#if defined(OS_CHROMEOS)
  // ChromeOS uses the kURLSwitch to specify a page that opens popups. We need
  // to do this so the popups are opened when the user clicks on the page.
  // TODO: nuke when convert to the real app page.
  new_contents->set_delegate(NULL);
  browser_->GetSelectedTabContents()->AddNewContents(
      new_contents, disposition, initial_pos, user_gesture);
  Hide();
#endif
}

void AppLauncher::UpdatePreferredSize(const gfx::Size& pref_size) {
  if (pref_size.width() == 0 || pref_size.height() == 0)
    return;

  gfx::Size size(pref_size);
  info_bubble_content_->ComputePreferredSize(size);
  info_bubble_->SizeToContents();
}

void AppLauncher::InfoBubbleClosing(InfoBubble* info_bubble,
                                    bool closed_by_escape) {
  // Delay deleting to be safe (we, and our tabcontents may be on the stack).
  // Remove ourself as a delegate as on GTK the Widget destruction is
  // asynchronous and will happen after the AppLauncher has been deleted (and it
  // might notify us after we have been deleted).
  info_bubble_content_->GetTabContents()->set_delegate(NULL);
  MessageLoop::current()->PostTask(FROM_HERE,
                                   new DeleteTask<AppLauncher>(this));
}

void AppLauncher::AddTabWithURL(const GURL& url,
                                PageTransition::Type transition) {
#if defined(OS_CHROMEOS)
  switch (chromeos::StatusAreaView::GetOpenTabsMode()) {
    case chromeos::StatusAreaView::OPEN_TABS_ON_LEFT: {
      // Add the new tab at the first non-pinned location.
      int index = browser_->tabstrip_model()->IndexOfFirstNonMiniTab();
      browser_->AddTabWithURL(url, GURL(), transition, index,
                              Browser::ADD_SELECTED | Browser::ADD_FORCE_INDEX,
                              NULL, std::string());
      break;
    }
    case chromeos::StatusAreaView::OPEN_TABS_CLOBBER: {
      browser_->GetSelectedTabContents()->controller().LoadURL(
          url, GURL(), transition);
      break;
    }
    case chromeos::StatusAreaView::OPEN_TABS_ON_RIGHT: {
      browser_->AddTabWithURL(url, GURL(), transition, -1,
                              Browser::ADD_SELECTED | Browser::ADD_FORCE_INDEX,
                              NULL, std::string());
      break;
    }
  }
#else
  browser_->AddTabWithURL(url, GURL(), transition, -1,
                          Browser::ADD_SELECTED | Browser::ADD_FORCE_INDEX,
                          NULL, std::string());
#endif
}
<commit_msg>The wrong TabContents' delegate was being NULLed when the app launcher was closed (the browser's current tab instead of the app launcher's one). This was causing a crasher with the context menu and possibly way more bad things.<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/views/app_launcher.h"

#include <string>
#include <vector>

#include "app/resource_bundle.h"
#include "base/command_line.h"
#include "base/message_loop.h"
#include "base/string_util.h"
#include "base/task.h"
#include "chrome/app/chrome_dll_resource.h"
#include "chrome/browser/browser.h"
#include "chrome/browser/browser_window.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/tab_contents/tab_contents.h"
#include "chrome/browser/view_ids.h"
#include "chrome/browser/views/dom_view.h"
#include "chrome/browser/views/info_bubble.h"
#include "chrome/browser/views/frame/browser_view.h"
#include "chrome/browser/views/location_bar/location_bar_view.h"
#include "chrome/common/url_constants.h"
#include "views/widget/root_view.h"

#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/status/status_area_view.h"
#endif

namespace {

// Padding between the navigation bar and the render view contents.
const int kNavigationBarBottomPadding = 3;

// NavigationBar constants.
const int kNavigationBarBorderThickness = 1;

const SkColor kBorderColor = SkColorSetRGB(205, 201, 201);

// Command line switch for specifying url of the page.
// TODO: nuke when we convert to the real app page. Also nuke code in
// AddNewContents
const wchar_t kURLSwitch[] = L"main-menu-url";

// Returns the URL of the menu.
static GURL GetMenuURL() {
  std::wstring url_string =
      CommandLine::ForCurrentProcess()->GetSwitchValue(kURLSwitch);
  if (!url_string.empty())
    return GURL(WideToUTF8(url_string));
  return GURL(chrome::kChromeUIAppLauncherURL);
}

// Returns the location bar view of |browser|.
static views::View* GetBrowserLocationBar(Browser* browser) {
  BrowserView* browser_view = static_cast<BrowserView*>(browser->window());
  views::RootView* root_view = views::Widget::GetWidgetFromNativeWindow(
      browser_view->GetNativeHandle())->GetRootView();
  return root_view->GetViewByID(VIEW_ID_LOCATION_BAR);
}

}  // namespace

// InfoBubbleContentsView
//
// The view that contains the navigation bar and DOMUI.
// It is displayed in an info-bubble.

class InfoBubbleContentsView : public views::View,
                               public LocationBarView::Delegate,
                               public CommandUpdater::CommandUpdaterDelegate {
 public:
  explicit InfoBubbleContentsView(AppLauncher* app_launcher);
  ~InfoBubbleContentsView();

  // Computes and sets the preferred size for the InfoBubbleContentsView based
  // on the preferred size of the DOMUI contents specified.
  void ComputePreferredSize(const gfx::Size& dom_view_preferred_size);

  // Sets the initial focus.
  // Should be called when the bubble that contains us is shown.
  void BubbleShown();

  // Returns the TabContents displaying the contents for this bubble.
  TabContents* GetBubbleTabContents();

  // views::View override:
  virtual gfx::Size GetPreferredSize();
  virtual void Layout();
  virtual void ViewHierarchyChanged(bool is_add,
                                    views::View* parent,
                                    views::View* child);

  // LocationBarView::Delegate implementation:

  // WARNING: this is not the TabContents of the bubble!  Use
  // GetBubbleTabContents() to get the bubble's TabContents.
  virtual TabContents* GetTabContents();
  virtual void OnInputInProgress(bool in_progress) {}

  // CommandUpdater::CommandUpdaterDelegate implementation:
  virtual void ExecuteCommand(int id);

 private:
  // The application launcher displaying this info bubble.
  AppLauncher* app_launcher_;

  // The location bar.
  LocationBarView* location_bar_;

  // The view containing the renderer view.
  DOMView* dom_view_;

  // The preferred size for this view (at which it fits its contents).
  gfx::Size preferred_size_;

  // CommandUpdater the location bar sends commands to.
  CommandUpdater command_updater_;

  // The width of the browser's location bar.
  int browser_location_bar_width_;

  DISALLOW_COPY_AND_ASSIGN(InfoBubbleContentsView);
};

InfoBubbleContentsView::InfoBubbleContentsView(AppLauncher* app_launcher)
    : app_launcher_(app_launcher),
      location_bar_(NULL),
      dom_view_(NULL),
      ALLOW_THIS_IN_INITIALIZER_LIST(command_updater_(this)) {
  // Allow the location bar to open URLs.
  command_updater_.UpdateCommandEnabled(IDC_OPEN_CURRENT_URL, true);
  DCHECK(app_launcher);

  browser_location_bar_width_ =
      GetBrowserLocationBar(app_launcher->browser())->width();
}

InfoBubbleContentsView::~InfoBubbleContentsView() {
}

void InfoBubbleContentsView::ComputePreferredSize(
    const gfx::Size& dom_view_preferred_size) {
  preferred_size_ = dom_view_preferred_size;

  // Add the padding and location bar height.
  preferred_size_.Enlarge(
      0, location_bar_->height() + kNavigationBarBottomPadding);

  // Make sure the width is at least the browser location bar width.
  if (preferred_size_.width() < browser_location_bar_width_)
    preferred_size_.set_width(browser_location_bar_width_);
}

void InfoBubbleContentsView::BubbleShown() {
  location_bar_->RequestFocus();
}

TabContents* InfoBubbleContentsView::GetBubbleTabContents() {
  return dom_view_->tab_contents();
}

void InfoBubbleContentsView::ViewHierarchyChanged(
    bool is_add, views::View* parent, views::View* child) {
  if (!is_add || child != this)
    return;

  DCHECK(!dom_view_);
  dom_view_ = new DOMView();
  AddChildView(dom_view_);
  // We pass NULL for site instance so the renderer uses its own process.
  dom_view_->Init(app_launcher_->browser()->profile(), NULL);
  // We make the AppLauncher the TabContents delegate so we get notifications
  // from the page to open links.
  dom_view_->tab_contents()->set_delegate(app_launcher_);
  GURL url = GetMenuURL();
  std::string ref = url.ref();
  if (!app_launcher_->hash_params().empty()) {
    if (!ref.empty())
      ref += "&";
    ref += app_launcher_->hash_params();

    url_canon::Replacements<char> replacements;
    replacements.SetRef(ref.c_str(), url_parse::Component(0, ref.size()));
    url = url.ReplaceComponents(replacements);
  }
  dom_view_->LoadURL(url);

  Browser* browser = app_launcher_->browser();
  location_bar_ =  new LocationBarView(browser->profile(),
                                       &command_updater_,
                                       browser->toolbar_model(),
                                       this,
                                       LocationBarView::APP_LAUNCHER);

  location_bar_->set_border(
      views::Border::CreateSolidBorder(kNavigationBarBorderThickness,
                                       kBorderColor));
  AddChildView(location_bar_);
  location_bar_->Init();
  // Size the location to its preferred size so ComputePreferredSize() computes
  // the right size.
  location_bar_->SizeToPreferredSize();
  ComputePreferredSize(gfx::Size(browser_location_bar_width_, 0));
  Layout();
}

TabContents* InfoBubbleContentsView::GetTabContents() {
  return app_launcher_->browser()->GetSelectedTabContents();
}

gfx::Size InfoBubbleContentsView::GetPreferredSize() {
  return preferred_size_;
}

void InfoBubbleContentsView::Layout() {
  if (bounds().IsEmpty() || GetChildViewCount() == 0)
    return;

  gfx::Rect bounds = GetLocalBounds(false);
  location_bar_->SetBounds(bounds.x(), bounds.y(), bounds.width(),
                           location_bar_->GetPreferredSize().height());
  int render_y = location_bar_->bounds().bottom() + kNavigationBarBottomPadding;
  dom_view_->SetBounds(0, render_y,
                       width(),
                       std::max(0, bounds.height() - render_y + bounds.y()));
}

void InfoBubbleContentsView::ExecuteCommand(int id) {
  // The user navigated by typing or selecting an entry in the location bar.
  DCHECK_EQ(IDC_OPEN_CURRENT_URL, id);
  GURL url(WideToUTF8(location_bar_->GetInputString()));
  app_launcher_->AddTabWithURL(url, location_bar_->GetPageTransition());
  app_launcher_->Hide();
}

////////////////////////////////////////////////////////////////////////////////
// AppLauncher

AppLauncher::AppLauncher(Browser* browser)
    : browser_(browser),
      info_bubble_(NULL) {
  DCHECK(browser);
  info_bubble_content_ = new InfoBubbleContentsView(this);
}

AppLauncher::~AppLauncher() {
}

// static
AppLauncher* AppLauncher::Show(Browser* browser,
                               const gfx::Rect& bounds,
                               const gfx::Point& bubble_anchor,
                               const std::string& hash_params) {
  AppLauncher* app_launcher = new AppLauncher(browser);
  BrowserView* browser_view = static_cast<BrowserView*>(browser->window());
  app_launcher->hash_params_ = hash_params;
  app_launcher->info_bubble_ =
      PinnedContentsInfoBubble::Show(browser_view->GetWidget(),
          bounds, BubbleBorder::TOP_LEFT, bubble_anchor,
          app_launcher->info_bubble_content_, app_launcher);
  app_launcher->info_bubble_content_->BubbleShown();
  return app_launcher;
}

// static
AppLauncher* AppLauncher::ShowForNewTab(Browser* browser,
                                        const std::string& hash_params) {
  BrowserView* browser_view = static_cast<BrowserView*>(browser->window());
  TabStrip* tabstrip = browser_view->tabstrip()->AsTabStrip();
  if (!tabstrip)
    return NULL;
  gfx::Rect bounds = tabstrip->GetNewTabButtonBounds();
  gfx::Point origin = bounds.origin();
  views::RootView::ConvertPointToScreen(tabstrip, &origin);
  bounds.set_origin(origin);

  // Figure out where the location bar is, so we can pin the bubble to
  // make our url bar appear exactly over it.
  views::View* location_bar = GetBrowserLocationBar(browser);
  gfx::Point location_bar_origin = location_bar->bounds().origin();
  views::RootView::ConvertPointToScreen(location_bar->GetParent(),
                                        &location_bar_origin);

  return Show(browser, bounds, location_bar_origin, hash_params);
}

void AppLauncher::Hide() {
  info_bubble_->Close();
}

void AppLauncher::OpenURLFromTab(TabContents* source,
                                 const GURL& url, const GURL& referrer,
                                 WindowOpenDisposition disposition,
                                 PageTransition::Type transition) {
  // TODO(jcivelli): we should call Browser::OpenApplicationTab(), we would need
  //                 to access the app for this URL.
  // The user clicked an item in the app launcher contents.
  AddTabWithURL(url, PageTransition::AUTO_BOOKMARK);
  Hide();
}

void AppLauncher::AddNewContents(TabContents* source,
                                 TabContents* new_contents,
                                 WindowOpenDisposition disposition,
                                 const gfx::Rect& initial_pos,
                                 bool user_gesture) {
#if defined(OS_CHROMEOS)
  // ChromeOS uses the kURLSwitch to specify a page that opens popups. We need
  // to do this so the popups are opened when the user clicks on the page.
  // TODO: nuke when convert to the real app page.
  new_contents->set_delegate(NULL);
  browser_->GetSelectedTabContents()->AddNewContents(
      new_contents, disposition, initial_pos, user_gesture);
  Hide();
#endif
}

void AppLauncher::UpdatePreferredSize(const gfx::Size& pref_size) {
  if (pref_size.width() == 0 || pref_size.height() == 0)
    return;

  gfx::Size size(pref_size);
  info_bubble_content_->ComputePreferredSize(size);
  info_bubble_->SizeToContents();
}

void AppLauncher::InfoBubbleClosing(InfoBubble* info_bubble,
                                    bool closed_by_escape) {
  // Delay deleting to be safe (we, and our tabcontents may be on the stack).
  // Remove ourself as a delegate as on GTK the Widget destruction is
  // asynchronous and will happen after the AppLauncher has been deleted (and it
  // might notify us after we have been deleted).
  info_bubble_content_->GetBubbleTabContents()->set_delegate(NULL);
  MessageLoop::current()->PostTask(FROM_HERE,
                                   new DeleteTask<AppLauncher>(this));
}

void AppLauncher::AddTabWithURL(const GURL& url,
                                PageTransition::Type transition) {
#if defined(OS_CHROMEOS)
  switch (chromeos::StatusAreaView::GetOpenTabsMode()) {
    case chromeos::StatusAreaView::OPEN_TABS_ON_LEFT: {
      // Add the new tab at the first non-pinned location.
      int index = browser_->tabstrip_model()->IndexOfFirstNonMiniTab();
      browser_->AddTabWithURL(url, GURL(), transition, index,
                              Browser::ADD_SELECTED | Browser::ADD_FORCE_INDEX,
                              NULL, std::string());
      break;
    }
    case chromeos::StatusAreaView::OPEN_TABS_CLOBBER: {
      browser_->GetSelectedTabContents()->controller().LoadURL(
          url, GURL(), transition);
      break;
    }
    case chromeos::StatusAreaView::OPEN_TABS_ON_RIGHT: {
      browser_->AddTabWithURL(url, GURL(), transition, -1,
                              Browser::ADD_SELECTED | Browser::ADD_FORCE_INDEX,
                              NULL, std::string());
      break;
    }
  }
#else
  browser_->AddTabWithURL(url, GURL(), transition, -1,
                          Browser::ADD_SELECTED | Browser::ADD_FORCE_INDEX,
                          NULL, std::string());
#endif
}
<|endoftext|>


<commit_before><commit_msg>coverity#1158084 Unchecked dynamic_cast<commit_after><|endoftext|>


<commit_before><commit_msg>INTEGRATION: CWS os8 (1.7.144); FILE MERGED 2003/04/03 07:14:48 os 1.7.144.1: #108583# precompiled headers removed<commit_after><|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 "chromecast/app/cast_main_delegate.h"

#include <string>

#include "base/command_line.h"
#include "base/cpu.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/posix/global_descriptors.h"
#include "chromecast/base/cast_paths.h"
#include "chromecast/browser/cast_content_browser_client.h"
#include "chromecast/common/cast_resource_delegate.h"
#include "chromecast/common/global_descriptors.h"
#include "chromecast/crash/cast_crash_reporter_client.h"
#include "chromecast/renderer/cast_content_renderer_client.h"
#include "components/crash/app/crash_reporter_client.h"
#include "content/public/browser/browser_main_runner.h"
#include "content/public/common/content_switches.h"
#include "ui/base/resource/resource_bundle.h"

#if defined(OS_ANDROID)
#include "chromecast/crash/android/crash_handler.h"
#endif  // defined(OS_ANDROID)

namespace {

#if !defined(OS_ANDROID)
base::LazyInstance<chromecast::CastCrashReporterClient>::Leaky
    g_crash_reporter_client = LAZY_INSTANCE_INITIALIZER;
#endif  // !defined(OS_ANDROID)

}  // namespace

namespace chromecast {
namespace shell {

CastMainDelegate::CastMainDelegate() {
}

CastMainDelegate::~CastMainDelegate() {
}

bool CastMainDelegate::BasicStartupComplete(int* exit_code) {
  RegisterPathProvider();

  logging::LoggingSettings settings;
#if defined(OS_ANDROID)
  base::FilePath log_file;
  PathService::Get(FILE_CAST_ANDROID_LOG, &log_file);
  settings.logging_dest = logging::LOG_TO_ALL;
  settings.log_file = log_file.value().c_str();
  settings.delete_old = logging::DELETE_OLD_LOG_FILE;
#else
  settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG;
#endif  // defined(OS_ANDROID)
  logging::InitLogging(settings);
  // Time, process, and thread ID are available through logcat.
  logging::SetLogItems(true, true, false, false);

  content::SetContentClient(&content_client_);
  return false;
}

void CastMainDelegate::PreSandboxStartup() {
#if defined(ARCH_CPU_ARM_FAMILY) && (defined(OS_ANDROID) || defined(OS_LINUX))
  // Create an instance of the CPU class to parse /proc/cpuinfo and cache the
  // results. This data needs to be cached when file-reading is still allowed,
  // since base::CPU expects to be callable later, when file-reading is no
  // longer allowed.
  base::CPU cpu_info;
#endif

  const base::CommandLine* command_line(base::CommandLine::ForCurrentProcess());
  std::string process_type =
      command_line->GetSwitchValueASCII(switches::kProcessType);

#if defined(OS_ANDROID)
  base::FilePath log_file;
  PathService::Get(FILE_CAST_ANDROID_LOG, &log_file);
  chromecast::CrashHandler::Initialize(process_type, log_file);
#else
  crash_reporter::SetCrashReporterClient(g_crash_reporter_client.Pointer());

  if (process_type != switches::kZygoteProcess) {
    CastCrashReporterClient::InitCrashReporter(process_type);
  }
#endif  // defined(OS_ANDROID)

  InitializeResourceBundle();
}

int CastMainDelegate::RunProcess(
    const std::string& process_type,
    const content::MainFunctionParams& main_function_params) {
#if defined(OS_ANDROID)
  if (!process_type.empty())
    return -1;

  // Note: Android must handle running its own browser process.
  // See ChromeMainDelegateAndroid::RunProcess.
  browser_runner_.reset(content::BrowserMainRunner::Create());
  return browser_runner_->Initialize(main_function_params);
#else
  return -1;
#endif  // defined(OS_ANDROID)
}

#if !defined(OS_ANDROID)
void CastMainDelegate::ZygoteForked() {
  const base::CommandLine* command_line(base::CommandLine::ForCurrentProcess());
  std::string process_type =
      command_line->GetSwitchValueASCII(switches::kProcessType);
  CastCrashReporterClient::InitCrashReporter(process_type);
}
#endif  // !defined(OS_ANDROID)

void CastMainDelegate::InitializeResourceBundle() {
#if defined(OS_ANDROID)
  // On Android, the renderer runs with a different UID and can never access
  // the file system. Use the file descriptor passed in at launch time.
  int pak_fd =
      base::GlobalDescriptors::GetInstance()->MaybeGet(kAndroidPakDescriptor);
  if (pak_fd >= 0) {
    ui::ResourceBundle::InitSharedInstanceWithPakFileRegion(
        base::File(pak_fd), base::MemoryMappedFile::Region::kWholeFile);
    ui::ResourceBundle::GetSharedInstance().AddDataPackFromFile(
        base::File(pak_fd), ui::SCALE_FACTOR_100P);
    return;
  }
#endif  // defined(OS_ANDROID)

  resource_delegate_.reset(new CastResourceDelegate());
  // TODO(gunsch): Use LOAD_COMMON_RESOURCES once ResourceBundle no longer
  // hardcodes resource file names.
  ui::ResourceBundle::InitSharedInstanceWithLocale(
      "en-US",
      resource_delegate_.get(),
      ui::ResourceBundle::DO_NOT_LOAD_COMMON_RESOURCES);

  base::FilePath pak_file;
  CHECK(PathService::Get(FILE_CAST_PAK, &pak_file));
  ui::ResourceBundle::GetSharedInstance().AddDataPackFromPath(
      pak_file,
      ui::SCALE_FACTOR_NONE);
}

content::ContentBrowserClient* CastMainDelegate::CreateContentBrowserClient() {
  browser_client_ = CastContentBrowserClient::Create();
  return browser_client_.get();
}

content::ContentRendererClient*
CastMainDelegate::CreateContentRendererClient() {
  renderer_client_ = CastContentRendererClient::Create();
  return renderer_client_.get();
}

}  // namespace shell
}  // namespace chromecast
<commit_msg>[Chromecast] Only delete log when in browser process for ATV.<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 "chromecast/app/cast_main_delegate.h"

#include <string>

#include "base/command_line.h"
#include "base/cpu.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/path_service.h"
#include "base/posix/global_descriptors.h"
#include "chromecast/base/cast_paths.h"
#include "chromecast/browser/cast_content_browser_client.h"
#include "chromecast/common/cast_resource_delegate.h"
#include "chromecast/common/global_descriptors.h"
#include "chromecast/crash/cast_crash_reporter_client.h"
#include "chromecast/renderer/cast_content_renderer_client.h"
#include "components/crash/app/crash_reporter_client.h"
#include "content/public/browser/browser_main_runner.h"
#include "content/public/common/content_switches.h"
#include "ui/base/resource/resource_bundle.h"

#if defined(OS_ANDROID)
#include "chromecast/crash/android/crash_handler.h"
#endif  // defined(OS_ANDROID)

namespace {

#if !defined(OS_ANDROID)
base::LazyInstance<chromecast::CastCrashReporterClient>::Leaky
    g_crash_reporter_client = LAZY_INSTANCE_INITIALIZER;
#endif  // !defined(OS_ANDROID)

}  // namespace

namespace chromecast {
namespace shell {

CastMainDelegate::CastMainDelegate() {
}

CastMainDelegate::~CastMainDelegate() {
}

bool CastMainDelegate::BasicStartupComplete(int* exit_code) {
  RegisterPathProvider();

  logging::LoggingSettings settings;
#if defined(OS_ANDROID)
  base::FilePath log_file;
  PathService::Get(FILE_CAST_ANDROID_LOG, &log_file);
  settings.logging_dest = logging::LOG_TO_ALL;
  settings.log_file = log_file.value().c_str();
  const base::CommandLine* command_line(base::CommandLine::ForCurrentProcess());
  std::string process_type =
      command_line->GetSwitchValueASCII(switches::kProcessType);
  // Only delete the old logs if the current process is the browser process.
  // Empty process_type signifies browser process.
  settings.delete_old = process_type.empty() ? logging::DELETE_OLD_LOG_FILE
                                             : logging::APPEND_TO_OLD_LOG_FILE;
#else
  settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG;
#endif  // defined(OS_ANDROID)
  logging::InitLogging(settings);
  // Time, process, and thread ID are available through logcat.
  logging::SetLogItems(true, true, false, false);

  content::SetContentClient(&content_client_);
  return false;
}

void CastMainDelegate::PreSandboxStartup() {
#if defined(ARCH_CPU_ARM_FAMILY) && (defined(OS_ANDROID) || defined(OS_LINUX))
  // Create an instance of the CPU class to parse /proc/cpuinfo and cache the
  // results. This data needs to be cached when file-reading is still allowed,
  // since base::CPU expects to be callable later, when file-reading is no
  // longer allowed.
  base::CPU cpu_info;
#endif

  const base::CommandLine* command_line(base::CommandLine::ForCurrentProcess());
  std::string process_type =
      command_line->GetSwitchValueASCII(switches::kProcessType);

#if defined(OS_ANDROID)
  base::FilePath log_file;
  PathService::Get(FILE_CAST_ANDROID_LOG, &log_file);
  chromecast::CrashHandler::Initialize(process_type, log_file);
#else
  crash_reporter::SetCrashReporterClient(g_crash_reporter_client.Pointer());

  if (process_type != switches::kZygoteProcess) {
    CastCrashReporterClient::InitCrashReporter(process_type);
  }
#endif  // defined(OS_ANDROID)

  InitializeResourceBundle();
}

int CastMainDelegate::RunProcess(
    const std::string& process_type,
    const content::MainFunctionParams& main_function_params) {
#if defined(OS_ANDROID)
  if (!process_type.empty())
    return -1;

  // Note: Android must handle running its own browser process.
  // See ChromeMainDelegateAndroid::RunProcess.
  browser_runner_.reset(content::BrowserMainRunner::Create());
  return browser_runner_->Initialize(main_function_params);
#else
  return -1;
#endif  // defined(OS_ANDROID)
}

#if !defined(OS_ANDROID)
void CastMainDelegate::ZygoteForked() {
  const base::CommandLine* command_line(base::CommandLine::ForCurrentProcess());
  std::string process_type =
      command_line->GetSwitchValueASCII(switches::kProcessType);
  CastCrashReporterClient::InitCrashReporter(process_type);
}
#endif  // !defined(OS_ANDROID)

void CastMainDelegate::InitializeResourceBundle() {
#if defined(OS_ANDROID)
  // On Android, the renderer runs with a different UID and can never access
  // the file system. Use the file descriptor passed in at launch time.
  int pak_fd =
      base::GlobalDescriptors::GetInstance()->MaybeGet(kAndroidPakDescriptor);
  if (pak_fd >= 0) {
    ui::ResourceBundle::InitSharedInstanceWithPakFileRegion(
        base::File(pak_fd), base::MemoryMappedFile::Region::kWholeFile);
    ui::ResourceBundle::GetSharedInstance().AddDataPackFromFile(
        base::File(pak_fd), ui::SCALE_FACTOR_100P);
    return;
  }
#endif  // defined(OS_ANDROID)

  resource_delegate_.reset(new CastResourceDelegate());
  // TODO(gunsch): Use LOAD_COMMON_RESOURCES once ResourceBundle no longer
  // hardcodes resource file names.
  ui::ResourceBundle::InitSharedInstanceWithLocale(
      "en-US",
      resource_delegate_.get(),
      ui::ResourceBundle::DO_NOT_LOAD_COMMON_RESOURCES);

  base::FilePath pak_file;
  CHECK(PathService::Get(FILE_CAST_PAK, &pak_file));
  ui::ResourceBundle::GetSharedInstance().AddDataPackFromPath(
      pak_file,
      ui::SCALE_FACTOR_NONE);
}

content::ContentBrowserClient* CastMainDelegate::CreateContentBrowserClient() {
  browser_client_ = CastContentBrowserClient::Create();
  return browser_client_.get();
}

content::ContentRendererClient*
CastMainDelegate::CreateContentRendererClient() {
  renderer_client_ = CastContentRendererClient::Create();
  return renderer_client_.get();
}

}  // namespace shell
}  // namespace chromecast
<|endoftext|>


<commit_before>// RUN: %clang_cc1 %s -triple %itanium_abi_triple -std=c++11 -emit-llvm -o - | FileCheck %s

class A {
  virtual void f();
  virtual void g();
  virtual ~A();
};

void A::f() {}

// CHECK: define void @_ZN1A1fEv({{.*}}) unnamed_addr
// CHECK: declare void @_ZN1A1gEv({{.*}}) unnamed_addr
// CHECK: declare {{.*}} @_ZN1AD1Ev({{.*}}) unnamed_addr
// CHECK: declare void @_ZN1AD0Ev({{.*}}) unnamed_addr
<commit_msg>clang/test/CodeGenCXX/virtual-function-attrs.cpp: Appease i686-mingw32 to expect x86_thiscallcc.<commit_after>// RUN: %clang_cc1 %s -triple %itanium_abi_triple -std=c++11 -emit-llvm -o - | FileCheck %s

class A {
  virtual void f();
  virtual void g();
  virtual ~A();
};

void A::f() {}

// CHECK: define [[CC:(x86_thiscallcc )?]]void @_ZN1A1fEv({{.*}}) unnamed_addr
// CHECK: declare [[CC]]void @_ZN1A1gEv({{.*}}) unnamed_addr
// CHECK: declare {{.*}} @_ZN1AD1Ev({{.*}}) unnamed_addr
// CHECK: declare [[CC]]void @_ZN1AD0Ev({{.*}}) unnamed_addr
<|endoftext|>


<commit_before>// Copyright 2014 the V8 project 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 "src/v8.h"
#include "test/cctest/cctest.h"

#include "src/compiler/code-generator.h"
#include "src/compiler/common-operator.h"
#include "src/compiler/graph.h"
#include "src/compiler/instruction-selector.h"
#include "src/compiler/machine-operator.h"
#include "src/compiler/node.h"
#include "src/compiler/operator.h"
#include "src/compiler/raw-machine-assembler.h"
#include "src/compiler/register-allocator.h"
#include "src/compiler/schedule.h"

#include "src/ast-numbering.h"
#include "src/full-codegen.h"
#include "src/parser.h"
#include "src/rewriter.h"

#include "test/cctest/compiler/c-signature.h"
#include "test/cctest/compiler/function-tester.h"

using namespace v8::internal;
using namespace v8::internal::compiler;

#if V8_TURBOFAN_TARGET

typedef RawMachineAssembler::Label MLabel;
typedef v8::internal::compiler::InstructionSequence TestInstrSeq;

static Handle<JSFunction> NewFunction(const char* source) {
  return v8::Utils::OpenHandle(
      *v8::Handle<v8::Function>::Cast(CompileRun(source)));
}

class DeoptCodegenTester {
 public:
  explicit DeoptCodegenTester(HandleAndZoneScope* scope, const char* src)
      : scope_(scope),
        function(NewFunction(src)),
        info(function, scope->main_zone()),
        bailout_id(-1) {
    CHECK(Parser::Parse(&info));
    info.SetOptimizing(BailoutId::None(), Handle<Code>(function->code()));
    CHECK(Compiler::Analyze(&info));
    CHECK(Compiler::EnsureDeoptimizationSupport(&info));

    DCHECK(info.shared_info()->has_deoptimization_support());

    graph = new (scope_->main_zone()) Graph(scope_->main_zone());
  }

  virtual ~DeoptCodegenTester() { delete code; }

  void GenerateCodeFromSchedule(Schedule* schedule) {
    OFStream os(stdout);
    if (FLAG_trace_turbo) {
      os << *schedule;
    }

    // Initialize the codegen and generate code.
    Linkage* linkage = new (scope_->main_zone()) Linkage(info.zone(), &info);
    InstructionBlocks* instruction_blocks =
        TestInstrSeq::InstructionBlocksFor(scope_->main_zone(), schedule);
    code = new TestInstrSeq::InstructionSequence(scope_->main_zone(),
                                                 instruction_blocks);
    SourcePositionTable source_positions(graph);
    InstructionSelector selector(scope_->main_zone(), graph, linkage, code,
                                 schedule, &source_positions);
    selector.SelectInstructions();

    if (FLAG_trace_turbo) {
      os << "----- Instruction sequence before register allocation -----\n"
         << *code;
    }

    Frame frame;
    RegisterAllocator allocator(RegisterAllocator::PlatformConfig(),
                                scope_->main_zone(), &frame, code);
    CHECK(allocator.Allocate());

    if (FLAG_trace_turbo) {
      os << "----- Instruction sequence after register allocation -----\n"
         << *code;
    }

    compiler::CodeGenerator generator(&frame, linkage, code, &info);
    result_code = generator.GenerateCode();

#ifdef OBJECT_PRINT
    if (FLAG_print_opt_code || FLAG_trace_turbo) {
      result_code->Print();
    }
#endif
  }

  Zone* zone() { return scope_->main_zone(); }

  HandleAndZoneScope* scope_;
  Handle<JSFunction> function;
  CompilationInfo info;
  BailoutId bailout_id;
  Handle<Code> result_code;
  TestInstrSeq* code;
  Graph* graph;
};

class TrivialDeoptCodegenTester : public DeoptCodegenTester {
 public:
  explicit TrivialDeoptCodegenTester(HandleAndZoneScope* scope)
      : DeoptCodegenTester(scope,
                           "function foo() { deopt(); return 42; }; foo") {}

  void GenerateCode() {
    GenerateCodeFromSchedule(BuildGraphAndSchedule(graph));
  }

  Schedule* BuildGraphAndSchedule(Graph* graph) {
    CommonOperatorBuilder common(zone());

    // Manually construct a schedule for the function below:
    // function foo() {
    //   deopt();
    // }

    CSignature1<Object*, Object*> sig;
    RawMachineAssembler m(graph, &sig);

    Handle<JSFunction> deopt_function =
        NewFunction("function deopt() { %DeoptimizeFunction(foo); }; deopt");
    Unique<JSFunction> deopt_fun_constant =
        Unique<JSFunction>::CreateUninitialized(deopt_function);
    Node* deopt_fun_node = m.NewNode(common.HeapConstant(deopt_fun_constant));

    Handle<Context> caller_context(function->context(), CcTest::i_isolate());
    Unique<Context> caller_context_constant =
        Unique<Context>::CreateUninitialized(caller_context);
    Node* caller_context_node =
        m.NewNode(common.HeapConstant(caller_context_constant));

    bailout_id = GetCallBailoutId();
    Node* parameters = m.NewNode(common.StateValues(1), m.UndefinedConstant());
    Node* locals = m.NewNode(common.StateValues(0));
    Node* stack = m.NewNode(common.StateValues(0));

    Node* state_node = m.NewNode(
        common.FrameState(JS_FRAME, bailout_id,
                          OutputFrameStateCombine::Ignore()),
        parameters, locals, stack, caller_context_node, m.UndefinedConstant());

    Handle<Context> context(deopt_function->context(), CcTest::i_isolate());
    Unique<Context> context_constant =
        Unique<Context>::CreateUninitialized(context);
    Node* context_node = m.NewNode(common.HeapConstant(context_constant));

    m.CallJS0(deopt_fun_node, m.UndefinedConstant(), context_node, state_node);

    m.Return(m.UndefinedConstant());

    // Schedule the graph:
    Schedule* schedule = m.Export();

    return schedule;
  }

  BailoutId GetCallBailoutId() {
    ZoneList<Statement*>* body = info.function()->body();
    for (int i = 0; i < body->length(); i++) {
      if (body->at(i)->IsExpressionStatement() &&
          body->at(i)->AsExpressionStatement()->expression()->IsCall()) {
        return body->at(i)->AsExpressionStatement()->expression()->id();
      }
    }
    CHECK(false);
    return BailoutId(-1);
  }
};

TEST(TurboTrivialDeoptCodegen) {
  HandleAndZoneScope scope;
  InitializedHandleScope handles;

  FLAG_allow_natives_syntax = true;
  FLAG_turbo_deoptimization = true;

  TrivialDeoptCodegenTester t(&scope);
  t.GenerateCode();

  DeoptimizationInputData* data =
      DeoptimizationInputData::cast(t.result_code->deoptimization_data());

  // TODO(jarin) Find a way to test the safepoint.

  // Check that we deoptimize to the right AST id.
  CHECK_EQ(1, data->DeoptCount());
  CHECK_EQ(t.bailout_id.ToInt(), data->AstId(0).ToInt());
}

TEST(TurboTrivialDeoptCodegenAndRun) {
  HandleAndZoneScope scope;
  InitializedHandleScope handles;

  FLAG_allow_natives_syntax = true;
  FLAG_turbo_deoptimization = true;

  TrivialDeoptCodegenTester t(&scope);
  t.GenerateCode();

  t.function->ReplaceCode(*t.result_code);
  t.info.context()->native_context()->AddOptimizedCode(*t.result_code);

  Isolate* isolate = scope.main_isolate();
  Handle<Object> result;
  bool has_pending_exception =
      !Execution::Call(isolate, t.function,
                       isolate->factory()->undefined_value(), 0, NULL,
                       false).ToHandle(&result);
  CHECK(!has_pending_exception);
  CHECK(result->SameValue(Smi::FromInt(42)));
}

class TrivialRuntimeDeoptCodegenTester : public DeoptCodegenTester {
 public:
  explicit TrivialRuntimeDeoptCodegenTester(HandleAndZoneScope* scope)
      : DeoptCodegenTester(
            scope,
            "function foo() { %DeoptimizeFunction(foo); return 42; }; foo") {}

  void GenerateCode() {
    GenerateCodeFromSchedule(BuildGraphAndSchedule(graph));
  }

  Schedule* BuildGraphAndSchedule(Graph* graph) {
    CommonOperatorBuilder common(zone());

    // Manually construct a schedule for the function below:
    // function foo() {
    //   %DeoptimizeFunction(foo);
    // }

    CSignature1<Object*, Object*> sig;
    RawMachineAssembler m(graph, &sig);

    Unique<HeapObject> this_fun_constant =
        Unique<HeapObject>::CreateUninitialized(function);
    Node* this_fun_node = m.NewNode(common.HeapConstant(this_fun_constant));

    Handle<Context> context(function->context(), CcTest::i_isolate());
    Unique<HeapObject> context_constant =
        Unique<HeapObject>::CreateUninitialized(context);
    Node* context_node = m.NewNode(common.HeapConstant(context_constant));

    bailout_id = GetCallBailoutId();
    Node* parameters = m.NewNode(common.StateValues(1), m.UndefinedConstant());
    Node* locals = m.NewNode(common.StateValues(0));
    Node* stack = m.NewNode(common.StateValues(0));

    Node* state_node = m.NewNode(
        common.FrameState(JS_FRAME, bailout_id,
                          OutputFrameStateCombine::Ignore()),
        parameters, locals, stack, context_node, m.UndefinedConstant());

    m.CallRuntime1(Runtime::kDeoptimizeFunction, this_fun_node, context_node,
                   state_node);

    m.Return(m.UndefinedConstant());

    // Schedule the graph:
    Schedule* schedule = m.Export();

    return schedule;
  }

  BailoutId GetCallBailoutId() {
    ZoneList<Statement*>* body = info.function()->body();
    for (int i = 0; i < body->length(); i++) {
      if (body->at(i)->IsExpressionStatement() &&
          body->at(i)->AsExpressionStatement()->expression()->IsCallRuntime()) {
        return body->at(i)->AsExpressionStatement()->expression()->id();
      }
    }
    CHECK(false);
    return BailoutId(-1);
  }
};

TEST(TurboTrivialRuntimeDeoptCodegenAndRun) {
  HandleAndZoneScope scope;
  InitializedHandleScope handles;

  FLAG_allow_natives_syntax = true;
  FLAG_turbo_deoptimization = true;

  TrivialRuntimeDeoptCodegenTester t(&scope);
  t.GenerateCode();

  t.function->ReplaceCode(*t.result_code);
  t.info.context()->native_context()->AddOptimizedCode(*t.result_code);

  Isolate* isolate = scope.main_isolate();
  Handle<Object> result;
  bool has_pending_exception =
      !Execution::Call(isolate, t.function,
                       isolate->factory()->undefined_value(), 0, NULL,
                       false).ToHandle(&result);
  CHECK(!has_pending_exception);
  CHECK(result->SameValue(Smi::FromInt(42)));
}

#endif
<commit_msg>build fix after 25072<commit_after>// Copyright 2014 the V8 project 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 "src/v8.h"
#include "test/cctest/cctest.h"

#include "src/compiler/code-generator.h"
#include "src/compiler/common-operator.h"
#include "src/compiler/graph.h"
#include "src/compiler/instruction-selector.h"
#include "src/compiler/machine-operator.h"
#include "src/compiler/node.h"
#include "src/compiler/operator.h"
#include "src/compiler/raw-machine-assembler.h"
#include "src/compiler/register-allocator.h"
#include "src/compiler/schedule.h"

#include "src/ast-numbering.h"
#include "src/full-codegen.h"
#include "src/parser.h"
#include "src/rewriter.h"

#include "test/cctest/compiler/c-signature.h"
#include "test/cctest/compiler/function-tester.h"

using namespace v8::internal;
using namespace v8::internal::compiler;

#if V8_TURBOFAN_TARGET

typedef RawMachineAssembler::Label MLabel;
typedef v8::internal::compiler::InstructionSequence TestInstrSeq;

static Handle<JSFunction> NewFunction(const char* source) {
  return v8::Utils::OpenHandle(
      *v8::Handle<v8::Function>::Cast(CompileRun(source)));
}

class DeoptCodegenTester {
 public:
  explicit DeoptCodegenTester(HandleAndZoneScope* scope, const char* src)
      : scope_(scope),
        function(NewFunction(src)),
        info(function, scope->main_zone()),
        bailout_id(-1) {
    CHECK(Parser::Parse(&info));
    info.SetOptimizing(BailoutId::None(), Handle<Code>(function->code()));
    CHECK(Compiler::Analyze(&info));
    CHECK(Compiler::EnsureDeoptimizationSupport(&info));

    DCHECK(info.shared_info()->has_deoptimization_support());

    graph = new (scope_->main_zone()) Graph(scope_->main_zone());
  }

  virtual ~DeoptCodegenTester() { delete code; }

  void GenerateCodeFromSchedule(Schedule* schedule) {
    OFStream os(stdout);
    if (FLAG_trace_turbo) {
      os << *schedule;
    }

    // Initialize the codegen and generate code.
    Linkage* linkage = new (scope_->main_zone()) Linkage(info.zone(), &info);
    InstructionBlocks* instruction_blocks =
        TestInstrSeq::InstructionBlocksFor(scope_->main_zone(), schedule);
    code = new TestInstrSeq(scope_->main_zone(), instruction_blocks);
    SourcePositionTable source_positions(graph);
    InstructionSelector selector(scope_->main_zone(), graph, linkage, code,
                                 schedule, &source_positions);
    selector.SelectInstructions();

    if (FLAG_trace_turbo) {
      os << "----- Instruction sequence before register allocation -----\n"
         << *code;
    }

    Frame frame;
    RegisterAllocator allocator(RegisterAllocator::PlatformConfig(),
                                scope_->main_zone(), &frame, code);
    CHECK(allocator.Allocate());

    if (FLAG_trace_turbo) {
      os << "----- Instruction sequence after register allocation -----\n"
         << *code;
    }

    compiler::CodeGenerator generator(&frame, linkage, code, &info);
    result_code = generator.GenerateCode();

#ifdef OBJECT_PRINT
    if (FLAG_print_opt_code || FLAG_trace_turbo) {
      result_code->Print();
    }
#endif
  }

  Zone* zone() { return scope_->main_zone(); }

  HandleAndZoneScope* scope_;
  Handle<JSFunction> function;
  CompilationInfo info;
  BailoutId bailout_id;
  Handle<Code> result_code;
  TestInstrSeq* code;
  Graph* graph;
};

class TrivialDeoptCodegenTester : public DeoptCodegenTester {
 public:
  explicit TrivialDeoptCodegenTester(HandleAndZoneScope* scope)
      : DeoptCodegenTester(scope,
                           "function foo() { deopt(); return 42; }; foo") {}

  void GenerateCode() {
    GenerateCodeFromSchedule(BuildGraphAndSchedule(graph));
  }

  Schedule* BuildGraphAndSchedule(Graph* graph) {
    CommonOperatorBuilder common(zone());

    // Manually construct a schedule for the function below:
    // function foo() {
    //   deopt();
    // }

    CSignature1<Object*, Object*> sig;
    RawMachineAssembler m(graph, &sig);

    Handle<JSFunction> deopt_function =
        NewFunction("function deopt() { %DeoptimizeFunction(foo); }; deopt");
    Unique<JSFunction> deopt_fun_constant =
        Unique<JSFunction>::CreateUninitialized(deopt_function);
    Node* deopt_fun_node = m.NewNode(common.HeapConstant(deopt_fun_constant));

    Handle<Context> caller_context(function->context(), CcTest::i_isolate());
    Unique<Context> caller_context_constant =
        Unique<Context>::CreateUninitialized(caller_context);
    Node* caller_context_node =
        m.NewNode(common.HeapConstant(caller_context_constant));

    bailout_id = GetCallBailoutId();
    Node* parameters = m.NewNode(common.StateValues(1), m.UndefinedConstant());
    Node* locals = m.NewNode(common.StateValues(0));
    Node* stack = m.NewNode(common.StateValues(0));

    Node* state_node = m.NewNode(
        common.FrameState(JS_FRAME, bailout_id,
                          OutputFrameStateCombine::Ignore()),
        parameters, locals, stack, caller_context_node, m.UndefinedConstant());

    Handle<Context> context(deopt_function->context(), CcTest::i_isolate());
    Unique<Context> context_constant =
        Unique<Context>::CreateUninitialized(context);
    Node* context_node = m.NewNode(common.HeapConstant(context_constant));

    m.CallJS0(deopt_fun_node, m.UndefinedConstant(), context_node, state_node);

    m.Return(m.UndefinedConstant());

    // Schedule the graph:
    Schedule* schedule = m.Export();

    return schedule;
  }

  BailoutId GetCallBailoutId() {
    ZoneList<Statement*>* body = info.function()->body();
    for (int i = 0; i < body->length(); i++) {
      if (body->at(i)->IsExpressionStatement() &&
          body->at(i)->AsExpressionStatement()->expression()->IsCall()) {
        return body->at(i)->AsExpressionStatement()->expression()->id();
      }
    }
    CHECK(false);
    return BailoutId(-1);
  }
};

TEST(TurboTrivialDeoptCodegen) {
  HandleAndZoneScope scope;
  InitializedHandleScope handles;

  FLAG_allow_natives_syntax = true;
  FLAG_turbo_deoptimization = true;

  TrivialDeoptCodegenTester t(&scope);
  t.GenerateCode();

  DeoptimizationInputData* data =
      DeoptimizationInputData::cast(t.result_code->deoptimization_data());

  // TODO(jarin) Find a way to test the safepoint.

  // Check that we deoptimize to the right AST id.
  CHECK_EQ(1, data->DeoptCount());
  CHECK_EQ(t.bailout_id.ToInt(), data->AstId(0).ToInt());
}

TEST(TurboTrivialDeoptCodegenAndRun) {
  HandleAndZoneScope scope;
  InitializedHandleScope handles;

  FLAG_allow_natives_syntax = true;
  FLAG_turbo_deoptimization = true;

  TrivialDeoptCodegenTester t(&scope);
  t.GenerateCode();

  t.function->ReplaceCode(*t.result_code);
  t.info.context()->native_context()->AddOptimizedCode(*t.result_code);

  Isolate* isolate = scope.main_isolate();
  Handle<Object> result;
  bool has_pending_exception =
      !Execution::Call(isolate, t.function,
                       isolate->factory()->undefined_value(), 0, NULL,
                       false).ToHandle(&result);
  CHECK(!has_pending_exception);
  CHECK(result->SameValue(Smi::FromInt(42)));
}

class TrivialRuntimeDeoptCodegenTester : public DeoptCodegenTester {
 public:
  explicit TrivialRuntimeDeoptCodegenTester(HandleAndZoneScope* scope)
      : DeoptCodegenTester(
            scope,
            "function foo() { %DeoptimizeFunction(foo); return 42; }; foo") {}

  void GenerateCode() {
    GenerateCodeFromSchedule(BuildGraphAndSchedule(graph));
  }

  Schedule* BuildGraphAndSchedule(Graph* graph) {
    CommonOperatorBuilder common(zone());

    // Manually construct a schedule for the function below:
    // function foo() {
    //   %DeoptimizeFunction(foo);
    // }

    CSignature1<Object*, Object*> sig;
    RawMachineAssembler m(graph, &sig);

    Unique<HeapObject> this_fun_constant =
        Unique<HeapObject>::CreateUninitialized(function);
    Node* this_fun_node = m.NewNode(common.HeapConstant(this_fun_constant));

    Handle<Context> context(function->context(), CcTest::i_isolate());
    Unique<HeapObject> context_constant =
        Unique<HeapObject>::CreateUninitialized(context);
    Node* context_node = m.NewNode(common.HeapConstant(context_constant));

    bailout_id = GetCallBailoutId();
    Node* parameters = m.NewNode(common.StateValues(1), m.UndefinedConstant());
    Node* locals = m.NewNode(common.StateValues(0));
    Node* stack = m.NewNode(common.StateValues(0));

    Node* state_node = m.NewNode(
        common.FrameState(JS_FRAME, bailout_id,
                          OutputFrameStateCombine::Ignore()),
        parameters, locals, stack, context_node, m.UndefinedConstant());

    m.CallRuntime1(Runtime::kDeoptimizeFunction, this_fun_node, context_node,
                   state_node);

    m.Return(m.UndefinedConstant());

    // Schedule the graph:
    Schedule* schedule = m.Export();

    return schedule;
  }

  BailoutId GetCallBailoutId() {
    ZoneList<Statement*>* body = info.function()->body();
    for (int i = 0; i < body->length(); i++) {
      if (body->at(i)->IsExpressionStatement() &&
          body->at(i)->AsExpressionStatement()->expression()->IsCallRuntime()) {
        return body->at(i)->AsExpressionStatement()->expression()->id();
      }
    }
    CHECK(false);
    return BailoutId(-1);
  }
};

TEST(TurboTrivialRuntimeDeoptCodegenAndRun) {
  HandleAndZoneScope scope;
  InitializedHandleScope handles;

  FLAG_allow_natives_syntax = true;
  FLAG_turbo_deoptimization = true;

  TrivialRuntimeDeoptCodegenTester t(&scope);
  t.GenerateCode();

  t.function->ReplaceCode(*t.result_code);
  t.info.context()->native_context()->AddOptimizedCode(*t.result_code);

  Isolate* isolate = scope.main_isolate();
  Handle<Object> result;
  bool has_pending_exception =
      !Execution::Call(isolate, t.function,
                       isolate->factory()->undefined_value(), 0, NULL,
                       false).ToHandle(&result);
  CHECK(!has_pending_exception);
  CHECK(result->SameValue(Smi::FromInt(42)));
}

#endif
<|endoftext|>


<commit_before>/*
    This file is part of KDE.

    Copyright (c) 2004 Cornelius Schumacher <schumacher@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.
*/

#include "parser.h"
#include "creator.h"

#include <kode/code.h>
#include <kode/printer.h>
#include <kode/typedef.h>

#include <kaboutdata.h>
#include <kapplication.h>
#include <kdebug.h>
#include <klocale.h>
#include <kcmdlineargs.h>
#include <kglobal.h>
#include <kconfig.h>
#include <ksimpleconfig.h>
#include <kstandarddirs.h>

#include <qfile.h>
#include <qtextstream.h>
#include <qdom.h>
#include <qregexp.h>
#include <qmap.h>

#include <iostream>

static const KCmdLineOptions options[] =
{
  { "d", 0, 0 },
  { "directory <dir>", I18N_NOOP("Directory to generate files in"), "." },
  { "+dtd", I18N_NOOP("DTD of XML file"), 0 },
  { "external-parser", I18N_NOOP("Generate parser in separate source file"),
    0 },
  { "custom-parser", I18N_NOOP("Generate parser customized for schema"), 0 },
  KCmdLineLastOption
};

int main( int argc, char **argv )
{
  KAboutData aboutData( "kxml_compiler", I18N_NOOP("KDE xml compiler"), "0.1",
  	I18N_NOOP("KDE XML Compiler") , KAboutData::License_LGPL );
  aboutData.addAuthor( "Cornelius Schumacher", 0, "schumacher@kde.org" );

  KCmdLineArgs::init( argc, argv, &aboutData );
  KCmdLineArgs::addCmdLineOptions( options );

  KInstance app( &aboutData );

  KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

  if ( args->count() < 1 ) {
    kdError() << "Too few arguments." << endl;
    return 1;
  }
  if ( args->count() > 1 ) {
    kdError() << "Too many arguments." << endl;
    return 1;
  }

  QString baseDir = QFile::decodeName( args->getOption( "directory" ) );
  if ( !baseDir.endsWith( "/" ) ) baseDir.append( "/" );

  QString dtdFilename = args->url( 0 ).path();

  QString baseName = args->url( 0 ).fileName();
  int pos = baseName.findRev( '.' );
  if ( pos > 0 ) baseName = baseName.left( pos );

  QFile dtdFile( dtdFilename );
  if ( !dtdFile.open( IO_ReadOnly ) ) {
    kdError() << "Unable to open '" << dtdFilename << "'" << endl;
    return 1;
  }

  QString errorMsg;
  int errorLine, errorCol;
  QDomDocument doc;
  if ( !doc.setContent( &dtdFile, false, &errorMsg, &errorLine, &errorCol ) ) {
    kdError() << errorMsg << " at " << errorLine << "," << errorCol << endl;
    return 1;
  }

  kdDebug() << "Begin parsing" << endl;

  Parser p;
  Element *start = p.parse( doc.documentElement() );
  if ( !start ) {
    kdError() << "Could not find start element" << endl;
    return 1;
  }

  p.dumpDefinitionMap();

//  return 0;

  p.substituteReferences( start );

#if 0
  std::cout << "--- TREE:" << std::endl;
  p.dumpTree( start );
#endif

  kdDebug() << "Begin creating code" << endl;

  Creator::XmlParserType pt;
  if ( args->isSet( "custom-parser" ) ) {
    pt = Creator::XmlParserCustomExternal;
  } else if ( args->isSet( "external-parser" ) ) {
    pt = Creator::XmlParserDomExternal;
  } else {
    pt = Creator::XmlParserDom;
  }

  Creator c( pt );

  kdDebug() << "Create classes" << endl;
  QValueList<Element *>::ConstIterator it;
  for( it = start->elements.begin(); it != start->elements.end(); ++it ) {
    c.createClass( *it );
  }
  kdDebug() << "Create parser" << endl;
  for( it = start->elements.begin(); it != start->elements.end(); ++it ) {
    c.setExternalClassPrefix( c.upperFirst( (*it)->name ) );
    c.createFileParser( *it );
    c.createFileWriter( *it, dtdFilename.replace( "rng", "dtd" ) );
  }

  c.createListTypedefs();

#if 0
  QValueList<Reference *>::ConstIterator it2;
  for( it2 = start->references.begin(); it2 != start->references.end();
       ++it2 ) {
    Element e;
    e.name = (*it2)->name;
    e.pattern = (*it2)->pattern;
    c.createClass( &e );
  }
#endif

  kdDebug() << "Begin printing code" << endl;

  KODE::File &f = c.file();

  f.setFilename( baseName );

  KODE::Printer printer;
  printer.setCreationWarning( true );
  printer.setGenerator( argv[0] );
  printer.setOutputDirectory( baseDir );
  printer.setSourceFile( args->url( 0 ).fileName() );

  c.printFiles( printer );

  kdDebug() << "Finished." << endl;
}
<commit_msg>That last fix for kxml_compiler didn't really solve the problem; hopefully this one does (works for me, at least).<commit_after>/*
    This file is part of KDE.

    Copyright (c) 2004 Cornelius Schumacher <schumacher@kde.org>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.
*/

#include "parser.h"
#include "creator.h"

#include <kode/code.h>
#include <kode/printer.h>
#include <kode/typedef.h>

#include <kaboutdata.h>
#include <kapplication.h>
#include <kdebug.h>
#include <klocale.h>
#include <kcmdlineargs.h>
#include <kglobal.h>
#include <kconfig.h>
#include <ksimpleconfig.h>
#include <kstandarddirs.h>

#include <qfile.h>
#include <qtextstream.h>
#include <qdom.h>
#include <qregexp.h>
#include <qmap.h>

#include <iostream>

static const KCmdLineOptions options[] =
{
  { "d", 0, 0 },
  { "directory <dir>", I18N_NOOP("Directory to generate files in"), "." },
  { "+dtd", I18N_NOOP("DTD of XML file"), 0 },
  { "external-parser", I18N_NOOP("Generate parser in separate source file"),
    0 },
  { "custom-parser", I18N_NOOP("Generate parser customized for schema"), 0 },
  KCmdLineLastOption
};

int main( int argc, char **argv )
{
  KAboutData aboutData( "kxml_compiler", I18N_NOOP("KDE xml compiler"), "0.1",
  	I18N_NOOP("KDE XML Compiler") , KAboutData::License_LGPL );
  aboutData.addAuthor( "Cornelius Schumacher", 0, "schumacher@kde.org" );

  KCmdLineArgs::init( argc, argv, &aboutData );
  KCmdLineArgs::addCmdLineOptions( options );

  KInstance app( &aboutData );

  KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

  if ( args->count() < 1 ) {
    kdError() << "Too few arguments." << endl;
    return 1;
  }
  if ( args->count() > 1 ) {
    kdError() << "Too many arguments." << endl;
    return 1;
  }

  QString baseDir = QFile::decodeName( args->getOption( "directory" ) );
  if ( !baseDir.endsWith( "/" ) ) baseDir.append( "/" );

  QString dtdFilename = args->url( 0 ).path();

  QString baseName = args->url( 0 ).fileName();
  int pos = baseName.findRev( '.' );
  if ( pos > 0 ) baseName = baseName.left( pos );

  QFile dtdFile( dtdFilename );
  if ( !dtdFile.open( IO_ReadOnly ) ) {
    kdError() << "Unable to open '" << dtdFilename << "'" << endl;
    return 1;
  }

  QString errorMsg;
  int errorLine, errorCol;
  QDomDocument doc;
  if ( !doc.setContent( &dtdFile, false, &errorMsg, &errorLine, &errorCol ) ) {
    kdError() << errorMsg << " at " << errorLine << "," << errorCol << endl;
    return 1;
  }

  kdDebug() << "Begin parsing" << endl;

  Parser p;
  Element *start = p.parse( doc.documentElement() );
  if ( !start ) {
    kdError() << "Could not find start element" << endl;
    return 1;
  }

  p.dumpDefinitionMap();

//  return 0;

  p.substituteReferences( start );

#if 0
  std::cout << "--- TREE:" << std::endl;
  p.dumpTree( start );
#endif

  kdDebug() << "Begin creating code" << endl;

  Creator::XmlParserType pt;
  if ( args->isSet( "custom-parser" ) ) {
    pt = Creator::XmlParserCustomExternal;
  } else if ( args->isSet( "external-parser" ) ) {
    pt = Creator::XmlParserDomExternal;
  } else {
    pt = Creator::XmlParserDom;
  }

  Creator c( pt );

  kdDebug() << "Create classes" << endl;
  QValueList<Element *>::ConstIterator it;
  for( it = start->elements.begin(); it != start->elements.end(); ++it ) {
    c.createClass( *it );
  }
  kdDebug() << "Create parser" << endl;
  for( it = start->elements.begin(); it != start->elements.end(); ++it ) {
    c.setExternalClassPrefix( c.upperFirst( (*it)->name ) );
    c.createFileParser( *it );
    c.createFileWriter( *it, dtdFilename.replace( "rng", "dtd" ) );
  }

  c.createListTypedefs();

#if 0
  QValueList<Reference *>::ConstIterator it2;
  for( it2 = start->references.begin(); it2 != start->references.end();
       ++it2 ) {
    Element e;
    e.name = (*it2)->name;
    e.pattern = (*it2)->pattern;
    c.createClass( &e );
  }
#endif

  kdDebug() << "Begin printing code" << endl;

  KODE::File &f = c.file();

  f.setFilename( baseName );

  KODE::Printer printer;
  printer.setCreationWarning( true );
  printer.setGenerator( KCmdLineArgs::cwd() + KCmdLineArgs::appName() );
  printer.setOutputDirectory( baseDir );
  printer.setSourceFile( args->url( 0 ).fileName() );

  c.printFiles( printer );

  kdDebug() << "Finished." << endl;
}
<|endoftext|>


<commit_before>

#include "TTASimRegion.h"

#include <Memory.hh>

#include "pocl_util.h"

#include <assert.h>

//#define ACCEL_TTASIM_DEBUG

TTASimRegion::TTASimRegion(size_t Address, size_t RegionSize, MemorySystem::MemoryPtr mem) {

#ifdef ACCEL_TTASIM_DEBUG
  POCL_MSG_PRINT_INFO("TTASim: Initializing TTASimRegion with Address %zu "
                      "and Size %zu and memptr %p\n",
                      Address, RegionSize, mem);
#endif
  PhysAddress = Address;
  Size = RegionSize;
  mem_ = mem;
  assert(mem != nullptr &&
         "memory handle NULL, is the sim opened properly?");
}
uint32_t TTASimRegion::Read32(size_t offset) {

#ifdef ACCEL_TTASIM_DEBUG
  POCL_MSG_PRINT_INFO("TTASim: Reading from physical address 0x%zx with "
                      "offset 0x%zx\n",
                      PhysAddress, offset);
#endif
  assert(mem_ != nullptr && "No memory handle; read before mapping?");
  assert(offset < Size && "Attempt to access data outside MMAP'd buffer");

  uint64_t result = 0;
  mem_->read(PhysAddress + offset, 4, result);
  return result;
}

void TTASimRegion::Write32(size_t offset, uint32_t value) {

#ifdef ACCEL_TTASIM_DEBUG
  POCL_MSG_PRINT_INFO("TTASim: Writing to physical address 0x%zx with "
                      "offset 0x%zx\n",
                      PhysAddress, offset);
#endif
  assert(mem_ != nullptr &&
         "No memory handle; write before mapping?");
  assert(offset < Size && "Attempt to access data outside MMAP'd buffer");
  mem_->writeDirectlyLE((uint32_t)(PhysAddress + offset), 4, value);

}

void TTASimRegion::Write16(size_t offset, uint16_t value) {
#ifdef ACCEL_TTASIM_DEBUG
  POCL_MSG_PRINT_INFO("TTASim: Writing to physical address 0x%zx with "
                      "offset 0x%zx\n",
                      PhysAddress, offset);
#endif
  assert(mem_ != nullptr &&
         "No memory handle; write before mapping?");
  assert(offset < Size && "Attempt to access data outside MMAP'd buffer");

  mem_->writeDirectlyLE(PhysAddress + offset, 2, value);
}

uint64_t TTASimRegion::Read64(size_t offset) {
#ifdef ACCEL_TTASIM_DEBUG
  POCL_MSG_PRINT_INFO("TTASim: Reading from physical address 0x%zx with "
                      "offset 0x%zx\n",
                      PhysAddress, offset);
#endif

  assert(mem_ != nullptr &&
         "No memory handle; write before mapping?");
  assert(offset < Size && "Attempt to access data outside MMAP'd buffer");

  uint64_t result = 0;
  mem_->read(PhysAddress + offset, 8, result);
  return result;
}

void TTASimRegion::CopyToMMAP(size_t destination, const void *source,
                               size_t bytes) {
#ifdef ACCEL_TTASIM_DEBUG
  POCL_MSG_PRINT_INFO("TTASim: Writing 0x%zx bytes to buffer at 0x%zx with "
                      "address 0x%zx\n",
                      bytes, PhysAddress, destination);
#endif
  auto src = (uint8_t *)source;
  size_t offset = destination - PhysAddress;
  assert(offset < Size && "Attempt to access data outside MMAP'd buffer");

  for (size_t i = 0; i < bytes; ++i) {
    mem_->writeDirectlyLE(destination + i, 1, (Memory::MAU)src[i]);
  }
}

void TTASimRegion::CopyFromMMAP(void *destination, size_t source,
                                 size_t bytes) {
#ifdef ACCEL_TTASIM_DEBUG
  POCL_MSG_PRINT_INFO("TTASim: Reading 0x%zx bytes from buffer at 0x%zx "
                      "with address 0x%zx\n",
                      bytes, PhysAddress, source);
#endif
  auto dst = (uint8_t *)destination;
  size_t offset = source - PhysAddress;
  assert(offset < Size && "Attempt to access data outside MMAP'd buffer");

  for (size_t i = 0; i < bytes; ++i) {
    dst[i] = mem_->read(source + i);
  }
}

<commit_msg>Fix adressing in accel/TTASimRegion.cc<commit_after>

#include "TTASimRegion.h"

#include <Memory.hh>

#include "pocl_util.h"

#include <assert.h>

//#define ACCEL_TTASIM_DEBUG

TTASimRegion::TTASimRegion(size_t Address, size_t RegionSize, MemorySystem::MemoryPtr mem) {

#ifdef ACCEL_TTASIM_DEBUG
  POCL_MSG_PRINT_INFO("TTASim: Initializing TTASimRegion with Address %zu "
                      "and Size %zu and memptr %p\n",
                      Address, RegionSize, mem.get());
#endif
  PhysAddress = Address;
  Size = RegionSize;
  mem_ = mem;
  assert(mem != nullptr &&
         "memory handle NULL, is the sim opened properly?");
}

uint32_t TTASimRegion::Read32(size_t offset) {

#ifdef ACCEL_TTASIM_DEBUG
  POCL_MSG_PRINT_INFO("TTASim: Reading from physical address 0x%zx with "
                      "offset 0x%zx\n",
                      PhysAddress, offset);
#endif
  assert(mem_ != nullptr && "No memory handle; read before mapping?");
  assert(offset < Size && "Attempt to access data outside MMAP'd buffer");

  uint64_t result = 0;
  mem_->read(offset, 4, result);
  return result;
}

void TTASimRegion::Write32(size_t offset, uint32_t value) {

#ifdef ACCEL_TTASIM_DEBUG
  POCL_MSG_PRINT_INFO("TTASim: Writing to physical address 0x%zx with "
                      "offset 0x%zx\n",
                      PhysAddress, offset);
#endif
  assert(mem_ != nullptr &&
         "No memory handle; write before mapping?");
  assert(offset < Size && "Attempt to access data outside MMAP'd buffer");
  mem_->writeDirectlyLE(offset, 4, value);

}

void TTASimRegion::Write16(size_t offset, uint16_t value) {
#ifdef ACCEL_TTASIM_DEBUG
  POCL_MSG_PRINT_INFO("TTASim: Writing to physical address 0x%zx with "
                      "offset 0x%zx\n",
                      PhysAddress, offset);
#endif
  assert(mem_ != nullptr &&
         "No memory handle; write before mapping?");
  assert(offset < Size && "Attempt to access data outside MMAP'd buffer");

  mem_->writeDirectlyLE(offset, 2, value);
}

uint64_t TTASimRegion::Read64(size_t offset) {
#ifdef ACCEL_TTASIM_DEBUG
  POCL_MSG_PRINT_INFO("TTASim: Reading from physical address 0x%zx with "
                      "offset 0x%zx\n",
                      PhysAddress, offset);
#endif

  assert(mem_ != nullptr &&
         "No memory handle; write before mapping?");
  assert(offset < Size && "Attempt to access data outside MMAP'd buffer");

  uint64_t result = 0;
  mem_->read(PhysAddress + offset, 8, result);
  return result;
}

void TTASimRegion::CopyToMMAP(size_t destination, const void *source,
                               size_t bytes) {
#ifdef ACCEL_TTASIM_DEBUG
  POCL_MSG_PRINT_INFO("TTASim: Writing 0x%zx bytes to buffer at 0x%zx with "
                      "address 0x%zx\n",
                      bytes, PhysAddress, destination);
#endif
  auto src = (uint8_t *)source;
  size_t offset = destination - PhysAddress;
  assert(offset < Size && "Attempt to access data outside MMAP'd buffer");

  for (size_t i = 0; i < bytes; ++i) {
    mem_->writeDirectlyLE(offset + i, 1, (Memory::MAU)src[i]);
  }
}

void TTASimRegion::CopyFromMMAP(void *destination, size_t source,
                                 size_t bytes) {
#ifdef ACCEL_TTASIM_DEBUG
  POCL_MSG_PRINT_INFO("TTASim: Reading 0x%zx bytes from buffer at 0x%zx "
                      "with address 0x%zx\n",
                      bytes, PhysAddress, source);
#endif
  auto dst = (uint8_t *)destination;
  size_t offset = source - PhysAddress;
  assert(offset < Size && "Attempt to access data outside MMAP'd buffer");

  for (size_t i = 0; i < bytes; ++i) {
    dst[i] = mem_->read(offset + i);
  }
}

<|endoftext|>