<commit_before>/*
    KAddressBook version 2

    Copyright (C) 1999 Rik Hemsley rik@kde.org

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program 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 General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

// System includes
#include <stdlib.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <sys/utsname.h>
#include <unistd.h>
#include <iostream.h>

// Qt includes
#include <qdir.h>
#include <qfile.h>
#include <qdatastream.h>

// Local includes
#include "KAddressBookInterface.h"
#include "Entity.h"
#include "Field.h"

int KABUniqueEntityID = 0;

// Addressbook /////////////////////////////////////////////////////////////

KAddressBook::KAddressBook(QString name, QString path)
  : DCOPObject(name.utf8()),
    path_(path)
{
  _init();
}

KAddressBook::~KAddressBook()
{
}

  bool
KAddressBook::process(
  const QCString & fun, const QByteArray & argData,
	QCString & replyType, QByteArray & replyData)
{
  QDataStream argStream   (argData, IO_ReadOnly);
  QDataStream replyStream (replyData, IO_WriteOnly);

  if (fun == "entity(QString)") {
    replyType = "Entity";

    QString arg;
    argStream >> arg;

    Entity retval;
    retval = entity(arg);
    replyStream << retval;

    return true;
  }

  else if (fun == "insert(Entity)") {
    replyType = "QString";

    Entity arg;
    argStream >> arg;

    QString retval;
    retval = insert(arg);
    replyStream << retval;

    return true;
  }

  else if (fun == "remove(QString)") {
    replyType = "bool";

    QString arg;
    argStream >> arg;

    bool retval;
    retval = remove(arg);
    replyStream << retval;

    return true;
  }

  else if (fun == "bool replace(Entity)") {
    replyType = "bool";

    Entity arg;
    argStream >> arg;

    bool retval;
    retval = replace(arg);
    replyStream << retval;

    return true;
  }

  else if (fun == "bool contains(QString)") {
    replyType = "bool";

    QString arg;
    argStream >> arg;

    bool retval;
    retval = contains(arg);
    replyStream << retval;

    return true;
  }

  else {
    qDebug("Unknown function call to KAddressBook::process()");
    return false;
  }
}

  Entity
KAddressBook::entity(QString id)
{
  Entity e;

  if (!index_.contains(id))
    return e;

  QStringList::ConstIterator it;

  for (QStringList::ConstIterator it(index_.begin()); it != index_.end(); ++it)
    if (*it == id) {
      Entity * loaded = _readEntity(*it);
      if (loaded != 0)
        e = *loaded;
      break;
    }

  return e;
}

  bool
KAddressBook::contains(QString id)
{
  return index_.contains(id);
}

  QString
KAddressBook::insert(Entity e)
{
  qDebug("insert entity `" + e.name() + "'");

  e.setID(_generateUniqueID());

  index_.append(e.id());

  bool ok = _writeEntity(e);

  if (!ok)
    return QString::null;

  return e.id();
}

  bool
KAddressBook::remove(QString id)
{
  if (!index_.contains(id))
    return false;

  index_.remove(id);

  _removeEntity(id);

  return true;
}

  bool
KAddressBook::replace(Entity e)
{
  //return index_.contains(e.id());
}

  QString
KAddressBook::_generateUniqueID()
{
  return uniquePartOne_ + "_" + QString().setNum(KABUniqueEntityID++);
}

  void
KAddressBook::_init()
{
  struct utsname utsName;

  if (uname(&utsName) == 0)
    uniquePartOne_ = utsName.nodename;
  else
    uniquePartOne_ = "localhost";

  struct timeval timeVal;
  struct timezone timeZone;
  gettimeofday(&timeVal, &timeZone);

  uniquePartOne_ += "_" + QString().setNum(timeVal.tv_sec);
  uniquePartOne_ += "_" + QString().setNum(getpid());

  _checkDirs();

  _initIndex();
}

  void
KAddressBook::_checkDirs()
{
  QDir base(path_);

  if (!base.exists())
    if (!base.mkdir(path_)) {
      cerr << "Could not create dir `" + path_ + "' - exiting" << endl;
      exit(1);
    }

  QDir tmp(path_ + "/tmp");

  if (!tmp.exists())
    if (!tmp.mkdir(path_ + "/tmp")) {
      cerr << "Could not create dir `" + path_ + "/tmp' - exiting" << endl;
      exit(1);
    }

  QDir entries(path_ + "/entries");

  if (!entries.exists())
    if (!entries.mkdir(path_ + "/entries")) {
      cerr << "Could not create dir `" + path_ + "/entries' - exiting" << endl;
      exit(1);
    }
}

  void
KAddressBook::_initIndex()
{
  QDir d(path_ + "/entries");

  d.setFilter(QDir::Files | QDir::NoSymLinks | QDir::Readable);

  index_ = d.entryList();
}

  bool
KAddressBook::_writeEntity(Entity & e)
{
  QString filename = path_ + "/tmp" + e.id();

  QFile f(filename);

  if (f.exists()) {
    qDebug("File `" + filename + "' exists");
    usleep(2000);
  }

  if (f.exists()) {
    qDebug("File `" + filename + "' still exists");
    return false;
  }

  if (!f.open(IO_WriteOnly)) {
    qDebug("Couldn't open file `" + filename + "' for writing");
    return false;
  }

  QDataStream str(&f);

  str << e;

  f.flush();
  f.close();

  if (f.status() != IO_Ok) {
    qDebug("Couldn't flush file `" + filename + "'");
    f.remove();
    return false;
  }

  QString linkTarget(path_ + "/entries/" + e.id());

  if (::link(QFile::encodeName(filename), QFile::encodeName(linkTarget)) != 0) {
    qDebug("Couldn't successfully link `" + filename +
      "' to `" + linkTarget + "' - giving up");
    return false;
  }

  f.remove();

  return true;
}

  Entity *
KAddressBook::_readEntity(const QString & id)
{
  QString filename = path_ + "/entries/" + id;
  QFile f(filename);

  if (!f.exists()) {
    qDebug("File `" + filename + "' does not exist");
    return 0;
  }

  if (!f.open(IO_ReadOnly)) {
    qDebug("Couldn't open `" + filename + "' for reading");
    return 0;
  }

  QDataStream str(&f);

  Entity * e = new Entity;
  str >> *e;

  return e;
}

  bool
KAddressBook::_removeEntity(const QString & id)
{
  QFile f(path_ + "/entries/" + id);

  if (!f.exists())
    return false;

  if (!f.remove())
    return false;

  index_.remove(id);

  return true;
}

QCString KAddressBook::functions()
{
  return DCOPObject::functions() +
  "entity(QString);"
  "insert(Entity);"
  "remove(QString);"
  "replace(Entity);"
  "contains(QString);"
  ;
}
<commit_msg>include config.h for Tru64<commit_after>/*
    KAddressBook version 2

    Copyright (C) 1999 Rik Hemsley rik@kde.org

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program 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 General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

// System includes
#include <stdlib.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <sys/utsname.h>
#include <unistd.h>
#include <iostream.h>

// Qt includes
#include <qdir.h>
#include <qfile.h>
#include <qdatastream.h>

// Local includes
#include <config.h>
#include "KAddressBookInterface.h"
#include "Entity.h"
#include "Field.h"

int KABUniqueEntityID = 0;

// Addressbook /////////////////////////////////////////////////////////////

KAddressBook::KAddressBook(QString name, QString path)
  : DCOPObject(name.utf8()),
    path_(path)
{
  _init();
}

KAddressBook::~KAddressBook()
{
}

  bool
KAddressBook::process(
  const QCString & fun, const QByteArray & argData,
	QCString & replyType, QByteArray & replyData)
{
  QDataStream argStream   (argData, IO_ReadOnly);
  QDataStream replyStream (replyData, IO_WriteOnly);

  if (fun == "entity(QString)") {
    replyType = "Entity";

    QString arg;
    argStream >> arg;

    Entity retval;
    retval = entity(arg);
    replyStream << retval;

    return true;
  }

  else if (fun == "insert(Entity)") {
    replyType = "QString";

    Entity arg;
    argStream >> arg;

    QString retval;
    retval = insert(arg);
    replyStream << retval;

    return true;
  }

  else if (fun == "remove(QString)") {
    replyType = "bool";

    QString arg;
    argStream >> arg;

    bool retval;
    retval = remove(arg);
    replyStream << retval;

    return true;
  }

  else if (fun == "bool replace(Entity)") {
    replyType = "bool";

    Entity arg;
    argStream >> arg;

    bool retval;
    retval = replace(arg);
    replyStream << retval;

    return true;
  }

  else if (fun == "bool contains(QString)") {
    replyType = "bool";

    QString arg;
    argStream >> arg;

    bool retval;
    retval = contains(arg);
    replyStream << retval;

    return true;
  }

  else {
    qDebug("Unknown function call to KAddressBook::process()");
    return false;
  }
}

  Entity
KAddressBook::entity(QString id)
{
  Entity e;

  if (!index_.contains(id))
    return e;

  QStringList::ConstIterator it;

  for (QStringList::ConstIterator it(index_.begin()); it != index_.end(); ++it)
    if (*it == id) {
      Entity * loaded = _readEntity(*it);
      if (loaded != 0)
        e = *loaded;
      break;
    }

  return e;
}

  bool
KAddressBook::contains(QString id)
{
  return index_.contains(id);
}

  QString
KAddressBook::insert(Entity e)
{
  qDebug("insert entity `" + e.name() + "'");

  e.setID(_generateUniqueID());

  index_.append(e.id());

  bool ok = _writeEntity(e);

  if (!ok)
    return QString::null;

  return e.id();
}

  bool
KAddressBook::remove(QString id)
{
  if (!index_.contains(id))
    return false;

  index_.remove(id);

  _removeEntity(id);

  return true;
}

  bool
KAddressBook::replace(Entity e)
{
  //return index_.contains(e.id());
}

  QString
KAddressBook::_generateUniqueID()
{
  return uniquePartOne_ + "_" + QString().setNum(KABUniqueEntityID++);
}

  void
KAddressBook::_init()
{
  struct utsname utsName;

  if (uname(&utsName) == 0)
    uniquePartOne_ = utsName.nodename;
  else
    uniquePartOne_ = "localhost";

  struct timeval timeVal;
  struct timezone timeZone;
  gettimeofday(&timeVal, &timeZone);

  uniquePartOne_ += "_" + QString().setNum(timeVal.tv_sec);
  uniquePartOne_ += "_" + QString().setNum(getpid());

  _checkDirs();

  _initIndex();
}

  void
KAddressBook::_checkDirs()
{
  QDir base(path_);

  if (!base.exists())
    if (!base.mkdir(path_)) {
      cerr << "Could not create dir `" + path_ + "' - exiting" << endl;
      exit(1);
    }

  QDir tmp(path_ + "/tmp");

  if (!tmp.exists())
    if (!tmp.mkdir(path_ + "/tmp")) {
      cerr << "Could not create dir `" + path_ + "/tmp' - exiting" << endl;
      exit(1);
    }

  QDir entries(path_ + "/entries");

  if (!entries.exists())
    if (!entries.mkdir(path_ + "/entries")) {
      cerr << "Could not create dir `" + path_ + "/entries' - exiting" << endl;
      exit(1);
    }
}

  void
KAddressBook::_initIndex()
{
  QDir d(path_ + "/entries");

  d.setFilter(QDir::Files | QDir::NoSymLinks | QDir::Readable);

  index_ = d.entryList();
}

  bool
KAddressBook::_writeEntity(Entity & e)
{
  QString filename = path_ + "/tmp" + e.id();

  QFile f(filename);

  if (f.exists()) {
    qDebug("File `" + filename + "' exists");
    usleep(2000);
  }

  if (f.exists()) {
    qDebug("File `" + filename + "' still exists");
    return false;
  }

  if (!f.open(IO_WriteOnly)) {
    qDebug("Couldn't open file `" + filename + "' for writing");
    return false;
  }

  QDataStream str(&f);

  str << e;

  f.flush();
  f.close();

  if (f.status() != IO_Ok) {
    qDebug("Couldn't flush file `" + filename + "'");
    f.remove();
    return false;
  }

  QString linkTarget(path_ + "/entries/" + e.id());

  if (::link(QFile::encodeName(filename), QFile::encodeName(linkTarget)) != 0) {
    qDebug("Couldn't successfully link `" + filename +
      "' to `" + linkTarget + "' - giving up");
    return false;
  }

  f.remove();

  return true;
}

  Entity *
KAddressBook::_readEntity(const QString & id)
{
  QString filename = path_ + "/entries/" + id;
  QFile f(filename);

  if (!f.exists()) {
    qDebug("File `" + filename + "' does not exist");
    return 0;
  }

  if (!f.open(IO_ReadOnly)) {
    qDebug("Couldn't open `" + filename + "' for reading");
    return 0;
  }

  QDataStream str(&f);

  Entity * e = new Entity;
  str >> *e;

  return e;
}

  bool
KAddressBook::_removeEntity(const QString & id)
{
  QFile f(path_ + "/entries/" + id);

  if (!f.exists())
    return false;

  if (!f.remove())
    return false;

  index_.remove(id);

  return true;
}

QCString KAddressBook::functions()
{
  return DCOPObject::functions() +
  "entity(QString);"
  "insert(Entity);"
  "remove(QString);"
  "replace(Entity);"
  "contains(QString);"
  ;
}
<|endoftext|>


<commit_before>// Copyright 2015 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 "sky/shell/ui/engine.h"

#include "base/bind.h"
#include "base/trace_event/trace_event.h"
#include "mojo/public/cpp/application/connect.h"
#include "sky/engine/public/platform/WebInputEvent.h"
#include "sky/engine/public/platform/sky_display_metrics.h"
#include "sky/engine/public/platform/sky_display_metrics.h"
#include "sky/engine/public/web/Sky.h"
#include "sky/engine/public/web/WebLocalFrame.h"
#include "sky/engine/public/web/WebSettings.h"
#include "sky/engine/public/web/WebView.h"
#include "sky/services/platform/platform_impl.h"
#include "sky/shell/service_provider.h"
#include "sky/shell/ui/animator.h"
#include "sky/shell/ui/input_event_converter.h"
#include "sky/shell/ui/internals.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkPictureRecorder.h"

namespace sky {
namespace shell {

namespace {

void ConfigureSettings(blink::WebSettings* settings) {
  settings->setDefaultFixedFontSize(13);
  settings->setDefaultFontSize(16);
  settings->setLoadsImagesAutomatically(true);
}

}

Engine::Engine(const Config& config)
    : config_(config),
      animator_(new Animator(config, this)),
      web_view_(nullptr),
      device_pixel_ratio_(1.0f),
      viewport_observer_binding_(this),
      weak_factory_(this) {
}

Engine::~Engine() {
  if (web_view_)
    web_view_->close();
}

base::WeakPtr<Engine> Engine::GetWeakPtr() {
  return weak_factory_.GetWeakPtr();
}

void Engine::Init() {
  TRACE_EVENT0("sky", "Engine::Init");

  service_provider_ = CreateServiceProvider(config_.service_provider_context);
  mojo::NetworkServicePtr network_service;
  mojo::ConnectToService(service_provider_.get(), &network_service);
  platform_impl_.reset(new PlatformImpl(network_service.Pass()));

  blink::initialize(platform_impl_.get());
}

void Engine::BeginFrame(base::TimeTicks frame_time) {
  TRACE_EVENT0("sky", "Engine::BeginFrame");

  double frame_time_sec = (frame_time - base::TimeTicks()).InSecondsF();
  double deadline_sec = frame_time_sec;
  double interval_sec = 1.0 / 60;
  blink::WebBeginFrameArgs args(frame_time_sec, deadline_sec, interval_sec);

  if (sky_view_)
    sky_view_->BeginFrame(frame_time);

  if (web_view_) {
    web_view_->beginFrame(args);
    web_view_->layout();
  }
}

skia::RefPtr<SkPicture> Engine::Paint() {
  TRACE_EVENT0("sky", "Engine::Paint");

  SkRTreeFactory factory;
  SkPictureRecorder recorder;
  auto canvas = skia::SharePtr(recorder.beginRecording(
      physical_size_.width(), physical_size_.height(), &factory,
      SkPictureRecorder::kComputeSaveLayerInfo_RecordFlag));

  if (sky_view_) {
    skia::RefPtr<SkPicture> picture = sky_view_->Paint();
    canvas->clear(SK_ColorBLACK);
    canvas->scale(device_pixel_ratio_, device_pixel_ratio_);
    if (picture)
      canvas->drawPicture(picture.get());
  }

  if (web_view_)
    web_view_->paint(canvas.get(), blink::WebRect(gfx::Rect(physical_size_)));

  return skia::AdoptRef(recorder.endRecordingAsPicture());
}

void Engine::ConnectToViewportObserver(
    mojo::InterfaceRequest<ViewportObserver> request) {
  viewport_observer_binding_.Bind(request.Pass());
}

void Engine::OnAcceleratedWidgetAvailable(gfx::AcceleratedWidget widget) {
  config_.gpu_task_runner->PostTask(
      FROM_HERE, base::Bind(&GPUDelegate::OnAcceleratedWidgetAvailable,
                            config_.gpu_delegate, widget));
  if (web_view_)
    scheduleVisualUpdate();
}

void Engine::OnOutputSurfaceDestroyed() {
  config_.gpu_task_runner->PostTask(
      FROM_HERE,
      base::Bind(&GPUDelegate::OnOutputSurfaceDestroyed, config_.gpu_delegate));
}

void Engine::OnViewportMetricsChanged(int width, int height,
                                      float device_pixel_ratio) {
  physical_size_.SetSize(width, height);
  device_pixel_ratio_ = device_pixel_ratio;

  if (sky_view_) {
    blink::SkyDisplayMetrics metrics;
    metrics.physical_size = physical_size_;
    metrics.device_pixel_ratio = device_pixel_ratio_;
    sky_view_->SetDisplayMetrics(metrics);
  }

  if (web_view_)
    UpdateWebViewSize();
}

void Engine::UpdateWebViewSize()
{
  CHECK(web_view_);
  web_view_->setDeviceScaleFactor(device_pixel_ratio_);
  gfx::SizeF size = gfx::ScaleSize(physical_size_, 1 / device_pixel_ratio_);
  // FIXME: We should be able to set the size of the WebView in floating point
  // because its in logical pixels.
  web_view_->resize(blink::WebSize(size.width(), size.height()));
}

// TODO(eseidel): This is likely not needed anymore.
blink::WebScreenInfo Engine::screenInfo() {
  blink::WebScreenInfo screen;
  screen.rect = blink::WebRect(gfx::Rect(physical_size_));
  screen.availableRect = screen.rect;
  screen.deviceScaleFactor = device_pixel_ratio_;
  return screen;
}

void Engine::OnInputEvent(InputEventPtr event) {
  TRACE_EVENT0("sky", "Engine::OnInputEvent");
  scoped_ptr<blink::WebInputEvent> web_event =
      ConvertEvent(event, device_pixel_ratio_);
  if (!web_event)
    return;
  if (sky_view_)
    sky_view_->HandleInputEvent(*web_event);
  if (web_view_)
    web_view_->handleInputEvent(*web_event);
}

void Engine::LoadURL(const mojo::String& url) {
  if (!WebView::shouldUseWebView(responseURL)) {
    sky_view_ = blink::SkyView::Create(this);
    sky_view_->Load(GURL(url));
    return;
  }

  LOG(WARNING) << ".sky support is deprecated, please use .dart for main()";

  // Something bad happens if you try to call WebView::close and replace
  // the webview.  So for now we just load into the existing one. :/
  if (!web_view_)
    web_view_ = blink::WebView::create(this);
  ConfigureSettings(web_view_->settings());
  web_view_->setMainFrame(blink::WebLocalFrame::create(this));
  UpdateWebViewSize();
  web_view_->mainFrame()->load(GURL(url));
}

void Engine::frameDetached(blink::WebFrame* frame) {
  // |frame| is invalid after here.
  frame->close();
}

void Engine::initializeLayerTreeView() {
}

void Engine::scheduleVisualUpdate() {
  animator_->RequestFrame();
}

void Engine::didCreateIsolate(blink::WebLocalFrame* frame,
                              Dart_Isolate isolate) {
  Internals::Create(isolate,
                    CreateServiceProvider(config_.service_provider_context));
}

void Engine::ScheduleFrame() {
  animator_->RequestFrame();
}

blink::ServiceProvider* Engine::services() {
  return this;
}

mojo::NavigatorHost* Engine::NavigatorHost() {
  return this;
}

void Engine::RequestNavigate(mojo::Target target,
                             mojo::URLRequestPtr request) {
  // Ignoring target for now.
  base::MessageLoop::current()->PostTask(FROM_HERE,
      base::Bind(&Engine::LoadURL, GetWeakPtr(), request->url));
}

void Engine::DidNavigateLocally(const mojo::String& url) {
}

void Engine::RequestNavigateHistory(int32_t delta) {
  NOTIMPLEMENTED();
}

}  // namespace shell
}  // namespace sky
<commit_msg>Fix android build<commit_after>// Copyright 2015 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 "sky/shell/ui/engine.h"

#include "base/bind.h"
#include "base/trace_event/trace_event.h"
#include "mojo/public/cpp/application/connect.h"
#include "sky/engine/public/platform/WebInputEvent.h"
#include "sky/engine/public/platform/sky_display_metrics.h"
#include "sky/engine/public/platform/sky_display_metrics.h"
#include "sky/engine/public/web/Sky.h"
#include "sky/engine/public/web/WebLocalFrame.h"
#include "sky/engine/public/web/WebSettings.h"
#include "sky/engine/public/web/WebView.h"
#include "sky/services/platform/platform_impl.h"
#include "sky/shell/service_provider.h"
#include "sky/shell/ui/animator.h"
#include "sky/shell/ui/input_event_converter.h"
#include "sky/shell/ui/internals.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkPictureRecorder.h"

namespace sky {
namespace shell {

namespace {

void ConfigureSettings(blink::WebSettings* settings) {
  settings->setDefaultFixedFontSize(13);
  settings->setDefaultFontSize(16);
  settings->setLoadsImagesAutomatically(true);
}

}

Engine::Engine(const Config& config)
    : config_(config),
      animator_(new Animator(config, this)),
      web_view_(nullptr),
      device_pixel_ratio_(1.0f),
      viewport_observer_binding_(this),
      weak_factory_(this) {
}

Engine::~Engine() {
  if (web_view_)
    web_view_->close();
}

base::WeakPtr<Engine> Engine::GetWeakPtr() {
  return weak_factory_.GetWeakPtr();
}

void Engine::Init() {
  TRACE_EVENT0("sky", "Engine::Init");

  service_provider_ = CreateServiceProvider(config_.service_provider_context);
  mojo::NetworkServicePtr network_service;
  mojo::ConnectToService(service_provider_.get(), &network_service);
  platform_impl_.reset(new PlatformImpl(network_service.Pass()));

  blink::initialize(platform_impl_.get());
}

void Engine::BeginFrame(base::TimeTicks frame_time) {
  TRACE_EVENT0("sky", "Engine::BeginFrame");

  double frame_time_sec = (frame_time - base::TimeTicks()).InSecondsF();
  double deadline_sec = frame_time_sec;
  double interval_sec = 1.0 / 60;
  blink::WebBeginFrameArgs args(frame_time_sec, deadline_sec, interval_sec);

  if (sky_view_)
    sky_view_->BeginFrame(frame_time);

  if (web_view_) {
    web_view_->beginFrame(args);
    web_view_->layout();
  }
}

skia::RefPtr<SkPicture> Engine::Paint() {
  TRACE_EVENT0("sky", "Engine::Paint");

  SkRTreeFactory factory;
  SkPictureRecorder recorder;
  auto canvas = skia::SharePtr(recorder.beginRecording(
      physical_size_.width(), physical_size_.height(), &factory,
      SkPictureRecorder::kComputeSaveLayerInfo_RecordFlag));

  if (sky_view_) {
    skia::RefPtr<SkPicture> picture = sky_view_->Paint();
    canvas->clear(SK_ColorBLACK);
    canvas->scale(device_pixel_ratio_, device_pixel_ratio_);
    if (picture)
      canvas->drawPicture(picture.get());
  }

  if (web_view_)
    web_view_->paint(canvas.get(), blink::WebRect(gfx::Rect(physical_size_)));

  return skia::AdoptRef(recorder.endRecordingAsPicture());
}

void Engine::ConnectToViewportObserver(
    mojo::InterfaceRequest<ViewportObserver> request) {
  viewport_observer_binding_.Bind(request.Pass());
}

void Engine::OnAcceleratedWidgetAvailable(gfx::AcceleratedWidget widget) {
  config_.gpu_task_runner->PostTask(
      FROM_HERE, base::Bind(&GPUDelegate::OnAcceleratedWidgetAvailable,
                            config_.gpu_delegate, widget));
  if (web_view_)
    scheduleVisualUpdate();
}

void Engine::OnOutputSurfaceDestroyed() {
  config_.gpu_task_runner->PostTask(
      FROM_HERE,
      base::Bind(&GPUDelegate::OnOutputSurfaceDestroyed, config_.gpu_delegate));
}

void Engine::OnViewportMetricsChanged(int width, int height,
                                      float device_pixel_ratio) {
  physical_size_.SetSize(width, height);
  device_pixel_ratio_ = device_pixel_ratio;

  if (sky_view_) {
    blink::SkyDisplayMetrics metrics;
    metrics.physical_size = physical_size_;
    metrics.device_pixel_ratio = device_pixel_ratio_;
    sky_view_->SetDisplayMetrics(metrics);
  }

  if (web_view_)
    UpdateWebViewSize();
}

void Engine::UpdateWebViewSize()
{
  CHECK(web_view_);
  web_view_->setDeviceScaleFactor(device_pixel_ratio_);
  gfx::SizeF size = gfx::ScaleSize(physical_size_, 1 / device_pixel_ratio_);
  // FIXME: We should be able to set the size of the WebView in floating point
  // because its in logical pixels.
  web_view_->resize(blink::WebSize(size.width(), size.height()));
}

// TODO(eseidel): This is likely not needed anymore.
blink::WebScreenInfo Engine::screenInfo() {
  blink::WebScreenInfo screen;
  screen.rect = blink::WebRect(gfx::Rect(physical_size_));
  screen.availableRect = screen.rect;
  screen.deviceScaleFactor = device_pixel_ratio_;
  return screen;
}

void Engine::OnInputEvent(InputEventPtr event) {
  TRACE_EVENT0("sky", "Engine::OnInputEvent");
  scoped_ptr<blink::WebInputEvent> web_event =
      ConvertEvent(event, device_pixel_ratio_);
  if (!web_event)
    return;
  if (sky_view_)
    sky_view_->HandleInputEvent(*web_event);
  if (web_view_)
    web_view_->handleInputEvent(*web_event);
}

void Engine::LoadURL(const mojo::String& mojo_url) {
  GURL url(mojo_url);
  if (!blink::WebView::shouldUseWebView(url)) {
    sky_view_ = blink::SkyView::Create(this);
    sky_view_->Load(url);
    return;
  }

  LOG(WARNING) << ".sky support is deprecated, please use .dart for main()";

  // Something bad happens if you try to call WebView::close and replace
  // the webview.  So for now we just load into the existing one. :/
  if (!web_view_)
    web_view_ = blink::WebView::create(this);
  ConfigureSettings(web_view_->settings());
  web_view_->setMainFrame(blink::WebLocalFrame::create(this));
  UpdateWebViewSize();
  web_view_->mainFrame()->load(url);
}

void Engine::frameDetached(blink::WebFrame* frame) {
  // |frame| is invalid after here.
  frame->close();
}

void Engine::initializeLayerTreeView() {
}

void Engine::scheduleVisualUpdate() {
  animator_->RequestFrame();
}

void Engine::didCreateIsolate(blink::WebLocalFrame* frame,
                              Dart_Isolate isolate) {
  Internals::Create(isolate,
                    CreateServiceProvider(config_.service_provider_context));
}

void Engine::ScheduleFrame() {
  animator_->RequestFrame();
}

blink::ServiceProvider* Engine::services() {
  return this;
}

mojo::NavigatorHost* Engine::NavigatorHost() {
  return this;
}

void Engine::RequestNavigate(mojo::Target target,
                             mojo::URLRequestPtr request) {
  // Ignoring target for now.
  base::MessageLoop::current()->PostTask(FROM_HERE,
      base::Bind(&Engine::LoadURL, GetWeakPtr(), request->url));
}

void Engine::DidNavigateLocally(const mojo::String& url) {
}

void Engine::RequestNavigateHistory(int32_t delta) {
  NOTIMPLEMENTED();
}

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


<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2013-2016.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#ifndef THOR_ACPI_HPP
#define THOR_ACPI_HPP

// This file contains the OS specific layer for ACPICA for thor-os
// It is meant to only be included by thor_acenv

//thor works in 64 bits
#define ACPI_MACHINE_WIDTH 64

// Cannot compile ACPICA without this flag for some reason
#define ACPI_DEBUGGER

// Let APCICA use its own cache
#define ACPI_USE_LOCAL_CACHE

// Limit compatibility to ACPI 5.0
//#define ACPI_REDUCED_HARDWARE TRUE

#endif
<commit_msg>Better configuration<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2013-2016.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#ifndef THOR_ACPI_HPP
#define THOR_ACPI_HPP

// This file contains the OS specific layer for ACPICA for thor-os
// It is meant to only be included by thor_acenv

//thor works in 64 bits
#define ACPI_MACHINE_WIDTH 64

// Don't use the full debugger, only the features for debugging output
#define ACPI_DEBUG_OUTPUT

// Let APCICA use its own cache
#define ACPI_USE_LOCAL_CACHE

// Limit compatibility to ACPI 5.0
//#define ACPI_REDUCED_HARDWARE TRUE

#endif
<|endoftext|>


<commit_before>/*
 * copyright: (c) RDO-Team, 2009
 * filename : main.cpp
 * author   :
 * date     : 14.07.2009
 * bref     :
 * indent   : 4T
 */

// ====================================================================== PCH
// ====================================================================== INCLUDES
#include <vector>
#include <list>
#include <iostream>
// ====================================================================== SYNOPSIS
#include "rdo_common/smart_ptr/intrusive_ptr.h"
#include "rdo_common/smart_ptr/interface_ptr.h"
#include "rdo_common/rdodebug.h"
// ===============================================================================

OBJECT(MyClass)
{
DECLARE_FACTORY(MyClass)
public:
	ruint m_i;

protected:
	MyClass()
		: m_i(2)
	{
		int i = 1;
	}

	~MyClass()
	{
		int i = 1;
	}
};

OBJECT_INTERFACE(IMyClass21)
{
	virtual void ifun21() = 0;
};
#define DECLARE_IMyClass21 \
public:                    \
	void ifun21();

class MyClass2: public MyClass, public IMyClass21, public rdo::CounterReferenceReal<MyClass2>
{
DECLARE_FACTORY(MyClass2)
public:
	ruint m_k;

	rbool operator== (CREF(MyClass2) obj) const
	{
		return m_k == obj.m_k;
	}

protected:
	MyClass2()
		: m_k(20)
	{
		int i = 1;
	}

	virtual ~MyClass2()
	{
		int i = 1;
	}
	DECLARE_IMyClass21;
};
DECLARE_POINTER(MyClass2)

void MyClass2::ifun21()
{
	int i = 1;
}

OBJECT(MyClass3)
{
public:
	ruint m_i;

	MyClass3()
		: m_i(3)
	{
		int i = 1;
	}

	~MyClass3()
	{
		int i = 1;
	}

	LPMyClass3 fun()
	{
		return this;
	}
};

class MyClass4: public MyClass2
{
DECLARE_FACTORY(MyClass4)
public:
	ruint m_a;

private:
	MyClass4()
		: m_a(24)
	{
		int i = 1;
	}

	virtual ~MyClass4()
	{
		int i = 1;
	}
};
DECLARE_POINTER(MyClass4)

void main()
{
	ruint size1 = sizeof(MyClass);
	ruint size2 = sizeof(LPMyClass);

	{ //!

		LPMyClass pMyClass = rdo::Factory<MyClass>::create();
		{
			LPMyClass pMyClass2 = pMyClass;
		}
		pMyClass->m_i = 3;
	}

	{ //!  -,    rbool,  ,

		LPMyClass pMyClass1;
		ASSERT(!pMyClass1);
		LPMyClass pMyClass2 = rdo::Factory<MyClass>::create();
		ASSERT(pMyClass2);
		pMyClass1 = pMyClass2;
		ASSERT(pMyClass1);

		LPMyClass pMyClass3 = rdo::Factory<MyClass>::create();
		pMyClass2 = NULL;
		pMyClass1 = pMyClass3;
	}

	{ //!     (   ),    this
		PTR(MyClass3) pMyClass3 = new MyClass3();
		LPMyClass3    pMyClass4(pMyClass3);
		LPMyClass3    pMyClass5 = pMyClass4->fun();
	}

	{ //!

		LPMyClass2 pMyClass2 = rdo::Factory<MyClass2>::create();
		pMyClass2->m_i = 10;
		pMyClass2->m_k = 22;
		LPMyClass  pMyClass = pMyClass2.object_cast<MyClass>();
		pMyClass->m_i = 11;
	}

	{ //!

		LPMyClass2 pMyClass2 = rdo::Factory<MyClass2>::create();
		LPIMyClass21 pMyClass21 = pMyClass2.interface_cast<IMyClass21>();
		pMyClass2 = NULL;
		pMyClass21 = LPIMyClass21();
	}

	{ //!     ,

		LPMyClass4 pMyClass4 = rdo::Factory<MyClass4>::create();
		LPIMyClass21 pMyClass21 = pMyClass4.interface_cast<IMyClass21>();
		pMyClass4 = NULL;
		pMyClass21 = LPIMyClass21();
	}

	{ //!

		LPMyClass2 pMyClass1 = rdo::Factory<MyClass2>::create();
		LPMyClass  pMyClass2 = pMyClass1.object_cast<MyClass>();
		ASSERT(pMyClass1 == pMyClass2);
		ASSERT(!(pMyClass1 != pMyClass2));

		LPMyClass3 pMyClass3 = rdo::Factory<MyClass3>::create();
		ASSERT(pMyClass1 != pMyClass3);
		ASSERT(!(pMyClass1 == pMyClass3));
	}

	{ //!

		LPMyClass2 pMyClass1 = rdo::Factory<MyClass2>::create();
		LPMyClass2 pMyClass2 = rdo::Factory<MyClass2>::create();
		ASSERT(pMyClass1.compare(pMyClass2));
		pMyClass2->m_k++;
		ASSERT(!pMyClass1.compare(pMyClass2));
	}

	int i = 1;
}
<commit_msg> - исправлена ошибка после переименования метода кастинга  - исправлена ошибка описания класса<commit_after>/*
 * copyright: (c) RDO-Team, 2009
 * filename : main.cpp
 * author   :
 * date     : 14.07.2009
 * bref     :
 * indent   : 4T
 */

// ====================================================================== PCH
// ====================================================================== INCLUDES
#include <vector>
#include <list>
#include <iostream>
// ====================================================================== SYNOPSIS
#include "rdo_common/smart_ptr/intrusive_ptr.h"
#include "rdo_common/smart_ptr/interface_ptr.h"
#include "rdo_common/rdodebug.h"
// ===============================================================================

OBJECT(MyClass)
{
DECLARE_FACTORY(MyClass)
public:
	ruint m_i;

protected:
	MyClass()
		: m_i(2)
	{
		int i = 1;
	}

	~MyClass()
	{
		int i = 1;
	}
};

OBJECT_INTERFACE(IMyClass21)
{
	virtual void ifun21() = 0;
};
#define DECLARE_IMyClass21 \
public:                    \
	void ifun21();

CLASS(MyClass2):
	    IMPLEMENTATION_OF(IMyClass21)
	AND INSTANCE_OF      (MyClass   )
{
DECLARE_FACTORY(MyClass2)
public:
	ruint m_k;

	rbool operator== (CREF(MyClass2) obj) const
	{
		return m_k == obj.m_k;
	}

protected:
	MyClass2()
		: m_k(20)
	{
		int i = 1;
	}

	virtual ~MyClass2()
	{
		int i = 1;
	}
	DECLARE_IMyClass21;
};
DECLARE_POINTER(MyClass2)

void MyClass2::ifun21()
{
	int i = 1;
}

OBJECT(MyClass3)
{
public:
	ruint m_i;

	MyClass3()
		: m_i(3)
	{
		int i = 1;
	}

	~MyClass3()
	{
		int i = 1;
	}

	LPMyClass3 fun()
	{
		return this;
	}
};

CLASS(MyClass4): INSTANCE_OF(MyClass2)
{
DECLARE_FACTORY(MyClass4)
public:
	ruint m_a;

private:
	MyClass4()
		: m_a(24)
	{
		int i = 1;
	}

	virtual ~MyClass4()
	{
		int i = 1;
	}
};
DECLARE_POINTER(MyClass4)

void main()
{
	ruint size1 = sizeof(MyClass);
	ruint size2 = sizeof(LPMyClass);

	{ //!

		LPMyClass pMyClass = rdo::Factory<MyClass>::create();
		{
			LPMyClass pMyClass2 = pMyClass;
		}
		pMyClass->m_i = 3;
	}

	{ //!  -,    rbool,  ,

		LPMyClass pMyClass1;
		ASSERT(!pMyClass1);
		LPMyClass pMyClass2 = rdo::Factory<MyClass>::create();
		ASSERT(pMyClass2);
		pMyClass1 = pMyClass2;
		ASSERT(pMyClass1);

		LPMyClass pMyClass3 = rdo::Factory<MyClass>::create();
		pMyClass2 = NULL;
		pMyClass1 = pMyClass3;
	}

	{ //!     (   ),    this
		PTR(MyClass3) pMyClass3 = new MyClass3();
		LPMyClass3    pMyClass4(pMyClass3);
		LPMyClass3    pMyClass5 = pMyClass4->fun();
	}

	{ //!

		LPMyClass2 pMyClass2 = rdo::Factory<MyClass2>::create();
		pMyClass2->m_i = 10;
		pMyClass2->m_k = 22;
		LPMyClass  pMyClass = pMyClass2.object_static_cast<MyClass>();
		pMyClass->m_i = 11;
	}

	{ //!

		LPMyClass2 pMyClass2 = rdo::Factory<MyClass2>::create();
		LPIMyClass21 pMyClass21 = pMyClass2.interface_cast<IMyClass21>();
		pMyClass2 = NULL;
		pMyClass21 = LPIMyClass21();
	}

	{ //!     ,

		LPMyClass4 pMyClass4 = rdo::Factory<MyClass4>::create();
		LPIMyClass21 pMyClass21 = pMyClass4.interface_cast<IMyClass21>();
		pMyClass4 = NULL;
		pMyClass21 = LPIMyClass21();
	}

	{ //!

		LPMyClass2 pMyClass1 = rdo::Factory<MyClass2>::create();
		LPMyClass  pMyClass2 = pMyClass1.object_static_cast<MyClass>();
		ASSERT(pMyClass1 == pMyClass2);
		ASSERT(!(pMyClass1 != pMyClass2));

		LPMyClass3 pMyClass3 = rdo::Factory<MyClass3>::create();
		ASSERT(pMyClass1 != pMyClass3);
		ASSERT(!(pMyClass1 == pMyClass3));
	}

	{ //!

		LPMyClass2 pMyClass1 = rdo::Factory<MyClass2>::create();
		LPMyClass2 pMyClass2 = rdo::Factory<MyClass2>::create();
		ASSERT(pMyClass1.compare(pMyClass2));
		pMyClass2->m_k++;
		ASSERT(!pMyClass1.compare(pMyClass2));
	}

	int i = 1;
}
<|endoftext|>


<commit_before>// This unit test will test the spawning mechanisms of the simulator

#include <stdio.h>
#include <unistd.h>
#include <assert.h>
#include "carbon_user.h"

void* thread_func(void *threadid);
void* thread_func_simple(void *threadid);

void do_a_sim()
{
   const unsigned int numThreads = 5;
   int threads[numThreads];

   for(unsigned int j = 0; j < numThreads; j++)
       threads[j] = CarbonSpawnThread(thread_func, (void *) (j + 1));

   for(unsigned int j = 0; j < numThreads; j++)
       CarbonJoinThread(threads[j]);

}

int main(int argc, char **argv)
{
   int i = 0;
   CarbonStartSim(argc, argv);

   for(i = 0; i < 20; i++)
   {
       fprintf(stderr, "%d...", i);
       do_a_sim();
   }
   CarbonStopSim();

   fprintf(stderr, "done.\n");
   i++;
   return 0;
}

void* thread_func(void *threadid)
{
//   int tid = CarbonSpawnThread(thread_func_simple, (void*)1);
//   CarbonJoinThread(tid);
   printf("Hi I'm thread %d\n", *((unsigned int*) threadid));
   return 0;
}

void* thread_func_simple(void *threadid)
{
//   usleep(250);
   return 0;
}
<commit_msg>[tests] Corrected small bug in the spawn unit test<commit_after>// This unit test will test the spawning mechanisms of the simulator

#include <stdio.h>
#include <unistd.h>
#include <assert.h>
#include "carbon_user.h"

void* thread_func(void *threadid);
void* thread_func_simple(void *threadid);

void do_a_sim()
{
   const unsigned int numThreads = 5;
   int threads[numThreads];

   for(unsigned int j = 0; j < numThreads; j++)
       threads[j] = CarbonSpawnThread(thread_func, (void *) (j + 1));

   for(unsigned int j = 0; j < numThreads; j++)
       CarbonJoinThread(threads[j]);

}

int main(int argc, char **argv)
{
   int i = 0;
   CarbonStartSim(argc, argv);

   for(i = 0; i < 20; i++)
   {
       fprintf(stderr, "%d...", i);
       do_a_sim();
   }
   CarbonStopSim();

   fprintf(stderr, "done.\n");
   i++;
   return 0;
}

void* thread_func(void *threadid)
{
//   int tid = CarbonSpawnThread(thread_func_simple, (void*)1);
//   CarbonJoinThread(tid);
   printf("Hi I'm thread %d\n", ((int) (long int) threadid));
   return 0;
}

void* thread_func_simple(void *threadid)
{
//   usleep(250);
   return 0;
}
<|endoftext|>


<commit_before>#ifndef TELEGRAMQT_TEST_UTILS_HPP
#define TELEGRAMQT_TEST_UTILS_HPP

#include <qtestcase.h>

#ifndef TEST_TIMEOUT
#define TEST_TIMEOUT 200
#endif

#define TRY_COMPARE(expr, expected) QTRY_COMPARE_WITH_TIMEOUT(expr, expected, TEST_TIMEOUT)
#define TRY_VERIFY(expr) QTRY_VERIFY_WITH_TIMEOUT(expr, TEST_TIMEOUT)
#define TRY_VERIFY2(expr, messageExpression) QTRY_VERIFY2_WITH_TIMEOUT(expr, messageExpression, TEST_TIMEOUT)

#endif // TELEGRAMQT_TEST_UTILS_HPP
<commit_msg>TestUtils: Include the right header<commit_after>#ifndef TELEGRAMQT_TEST_UTILS_HPP
#define TELEGRAMQT_TEST_UTILS_HPP

#include <QTest>

#ifndef TEST_TIMEOUT
#define TEST_TIMEOUT 200
#endif

#define TRY_COMPARE(expr, expected) QTRY_COMPARE_WITH_TIMEOUT(expr, expected, TEST_TIMEOUT)
#define TRY_VERIFY(expr) QTRY_VERIFY_WITH_TIMEOUT(expr, TEST_TIMEOUT)
#define TRY_VERIFY2(expr, messageExpression) QTRY_VERIFY2_WITH_TIMEOUT(expr, messageExpression, TEST_TIMEOUT)

#endif // TELEGRAMQT_TEST_UTILS_HPP
<|endoftext|>


<commit_before>// Copyright 2016 Alex Silva Torres
//
// 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 "runner.h"

#include <cstdlib>

#include <string>
#include <memory>
#include <iostream>
#include <fstream>
#include <functional>
#include <readline/readline.h>
#include <readline/history.h>
#include <boost/filesystem.hpp>

#include "env-shell.h"
#include "objects/str-object.h"
#include "utils/dir.h"

namespace shpp {

static sigjmp_buf ctrlc_buf;

void HandleSignals(int signo) {
  if (signo == SIGINT) {
    std::cout << "\n";
    siglongjmp(ctrlc_buf, 1);
  }
}

Runner::Runner() {
  using namespace internal;

  internal::EnvShell::instance()->InitShell();
}

void Runner::Exec(std::string name, std::vector<std::string>&& args) {
  try {
    internal::ScriptStream file(name);

    if (!file.IsOpen()) {
      throw RunTimeError(RunTimeError::ErrorCode::INTERPRETER_FILE,
                         boost::format("can't open file: %1%")%name,
                         internal::Position{0, 0});
    }

    interpreter_.Exec(file, std::move(args));
  } catch (RunTimeError& e) {
    std::cout << "Error: " << e.pos().line << ": " << e.pos().col
              << ": " << e.what() << "\n\n";

    for (auto& msg: e.messages()) {
      std::cout << "Error: " << msg.line() << ": " << msg.pos()
                << ": " << msg.msg() << "\n";
    }
  }
}

void Runner::ExecInterative() {
  namespace fs = boost::filesystem;
  using std::placeholders::_1;

  if (signal(SIGINT, HandleSignals) == SIG_ERR) {
    std::cerr << "failed to register interrupts with kernel\n";
    exit(-1);
  }

  fs::path path_rc = fs::path(internal::GetHome() + "/.shpprc");

  if (fs::exists(path_rc)) {
    Exec(path_rc.string());
  }

  while (true) {
    try {
      interpreter_.ExecInterative([&](internal::Executor* exec, bool concat) {
        char *input;
        std::string str_source;
        std::string prompt;

        if (concat) {
          prompt = "| ";

          internal::ObjectPtr obj_func = interpreter_.LookupSymbol("PS2");

          if (obj_func) {
            std::vector<internal::ObjectPtr> params;
            internal::ObjectPtr obj = obj_func->Call(exec, std::move(params));

            if (obj->type() == internal::Object::ObjectType::STRING) {
              prompt = static_cast<internal::StringObject&>(*obj).value();
            }
          }
        } else {
          prompt = "> ";

          internal::ObjectPtr obj_func = interpreter_.LookupSymbol("PS1");

          if (obj_func) {
            std::vector<internal::ObjectPtr> params;
            internal::ObjectPtr obj = obj_func->Call(exec, std::move(params));

            if (obj->type() == internal::Object::ObjectType::STRING) {
              prompt = static_cast<internal::StringObject&>(*obj).value();
            }
          }
        }

        while (sigsetjmp(ctrlc_buf, 1) != 0 );

        input = readline(prompt.c_str());

        if (input == nullptr) {
          exit(0);
        }

        str_source = input;
        add_history(input);
        free(input);
        return str_source;
      });
    } catch (RunTimeError& e) {
      std::cout << "Error: " << e.pos().line << ": " << e.pos().col
                << ": " << e.what() << "\n\n";

      for (auto& msg: e.messages()) {
        std::cout << "Error: " << msg.line() << ": " << msg.pos()
                  << ": " << msg.msg() << "\n";
      }
    }
  }
}

}
<commit_msg>fix initialization of  __main__ variable<commit_after>// Copyright 2016 Alex Silva Torres
//
// 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 "runner.h"

#include <cstdlib>

#include <string>
#include <memory>
#include <iostream>
#include <fstream>
#include <functional>
#include <readline/readline.h>
#include <readline/history.h>
#include <boost/filesystem.hpp>

#include "env-shell.h"
#include "objects/str-object.h"
#include "utils/dir.h"

namespace shpp {

static sigjmp_buf ctrlc_buf;

void HandleSignals(int signo) {
  if (signo == SIGINT) {
    std::cout << "\n";
    siglongjmp(ctrlc_buf, 1);
  }
}

Runner::Runner(): interpreter_(true) {
  using namespace internal;

  internal::EnvShell::instance()->InitShell();
}

void Runner::Exec(std::string name, std::vector<std::string>&& args) {
  try {
    internal::ScriptStream file(name);

    if (!file.IsOpen()) {
      throw RunTimeError(RunTimeError::ErrorCode::INTERPRETER_FILE,
                         boost::format("can't open file: %1%")%name,
                         internal::Position{0, 0});
    }

    interpreter_.Exec(file, std::move(args));
  } catch (RunTimeError& e) {
    std::cout << "Error: " << e.pos().line << ": " << e.pos().col
              << ": " << e.what() << "\n\n";

    for (auto& msg: e.messages()) {
      std::cout << "Error: " << msg.line() << ": " << msg.pos()
                << ": " << msg.msg() << "\n";
    }
  }
}

void Runner::ExecInterative() {
  namespace fs = boost::filesystem;
  using std::placeholders::_1;

  if (signal(SIGINT, HandleSignals) == SIG_ERR) {
    std::cerr << "failed to register interrupts with kernel\n";
    exit(-1);
  }

  fs::path path_rc = fs::path(internal::GetHome() + "/.shpprc");

  if (fs::exists(path_rc)) {
    Exec(path_rc.string());
  }

  while (true) {
    try {
      interpreter_.ExecInterative([&](internal::Executor* exec, bool concat) {
        char *input;
        std::string str_source;
        std::string prompt;

        if (concat) {
          prompt = "| ";

          internal::ObjectPtr obj_func = interpreter_.LookupSymbol("PS2");

          if (obj_func) {
            std::vector<internal::ObjectPtr> params;
            internal::ObjectPtr obj = obj_func->Call(exec, std::move(params));

            if (obj->type() == internal::Object::ObjectType::STRING) {
              prompt = static_cast<internal::StringObject&>(*obj).value();
            }
          }
        } else {
          prompt = "> ";

          internal::ObjectPtr obj_func = interpreter_.LookupSymbol("PS1");

          if (obj_func) {
            std::vector<internal::ObjectPtr> params;
            internal::ObjectPtr obj = obj_func->Call(exec, std::move(params));

            if (obj->type() == internal::Object::ObjectType::STRING) {
              prompt = static_cast<internal::StringObject&>(*obj).value();
            }
          }
        }

        while (sigsetjmp(ctrlc_buf, 1) != 0 );

        input = readline(prompt.c_str());

        if (input == nullptr) {
          exit(0);
        }

        str_source = input;
        add_history(input);
        free(input);
        return str_source;
      });
    } catch (RunTimeError& e) {
      std::cout << "Error: " << e.pos().line << ": " << e.pos().col
                << ": " << e.what() << "\n\n";

      for (auto& msg: e.messages()) {
        std::cout << "Error: " << msg.line() << ": " << msg.pos()
                  << ": " << msg.msg() << "\n";
      }
    }
  }
}

}
<|endoftext|>


<commit_before>#include "rapid_pbd/world.h"

#include <string>
#include <vector>

#include "rapid_pbd_msgs/Action.h"
#include "rapid_pbd_msgs/Landmark.h"
#include "rapid_pbd_msgs/Program.h"
#include "rapid_pbd_msgs/Step.h"

#include "rapid_pbd/joint_state.h"

namespace msgs = rapid_pbd_msgs;

namespace rapid {
namespace pbd {
void GetWorld(const msgs::Program& program, size_t step_id, World* world) {
  world->scene_id = "";
  JointState js(program.start_joint_state);
  world->joint_state = js;
  world->surface_box_landmarks.clear();

  for (size_t i = 0; i <= std::min(step_id, program.steps.size() - 1); ++i) {
    const msgs::Step& step = program.steps[i];
    if (step.scene_id != "") {
      world->scene_id = step.scene_id;
    }

    for (size_t action_i = 0; action_i < step.actions.size(); ++action_i) {
      const msgs::Action& action = step.actions[action_i];
      if (action.type == msgs::Action::ACTUATE_GRIPPER) {
        // TODO: fill this in.
      } else if (action.type == msgs::Action::MOVE_TO_JOINT_GOAL) {
        const trajectory_msgs::JointTrajectory& trajectory =
            action.joint_trajectory;
        if (trajectory.points.size() == 0) {
          continue;
        }
        for (size_t i = 0; i < trajectory.joint_names.size(); ++i) {
          const std::string& name = trajectory.joint_names[i];
          double position = trajectory.points[0].positions[i];
          world->joint_state.SetPosition(name, position);
        }
      } else if (action.type == msgs::Action::MOVE_TO_CARTESIAN_GOAL) {
        // TODO: fill this in.
      }
    }

    std::vector<msgs::Landmark> surface_boxes;
    for (size_t landmark_i = 0; landmark_i < step.landmarks.size();
         ++landmark_i) {
      const msgs::Landmark& landmark = step.landmarks[landmark_i];
      if (landmark.type == msgs::Landmark::SURFACE_BOX) {
        surface_boxes.push_back(landmark);
      }
      // Deal with other landmark types here
    }
    // Replace all surface objects if there are any.
    if (surface_boxes.size() > 0) {
      world->surface_box_landmarks = surface_boxes;
    }
  }
}
}  // namespace pbd
}  // namespace rapid
<commit_msg>Fixed size_t wraparound issue.<commit_after>#include "rapid_pbd/world.h"

#include <string>
#include <vector>

#include "rapid_pbd_msgs/Action.h"
#include "rapid_pbd_msgs/Landmark.h"
#include "rapid_pbd_msgs/Program.h"
#include "rapid_pbd_msgs/Step.h"

#include "rapid_pbd/joint_state.h"

namespace msgs = rapid_pbd_msgs;

namespace rapid {
namespace pbd {
void GetWorld(const msgs::Program& program, size_t step_id, World* world) {
  world->scene_id = "";
  JointState js(program.start_joint_state);
  world->joint_state = js;
  world->surface_box_landmarks.clear();

  for (size_t i = 0; i <= step_id; ++i) {
    if (program.steps.size() == 0) {
      break;
    }
    const msgs::Step& step = program.steps[i];
    if (step.scene_id != "") {
      world->scene_id = step.scene_id;
    }

    for (size_t action_i = 0; action_i < step.actions.size(); ++action_i) {
      const msgs::Action& action = step.actions[action_i];
      if (action.type == msgs::Action::ACTUATE_GRIPPER) {
        // TODO: fill this in.
      } else if (action.type == msgs::Action::MOVE_TO_JOINT_GOAL) {
        const trajectory_msgs::JointTrajectory& trajectory =
            action.joint_trajectory;
        if (trajectory.points.size() == 0) {
          continue;
        }
        for (size_t i = 0; i < trajectory.joint_names.size(); ++i) {
          const std::string& name = trajectory.joint_names[i];
          double position = trajectory.points[0].positions[i];
          world->joint_state.SetPosition(name, position);
        }
      } else if (action.type == msgs::Action::MOVE_TO_CARTESIAN_GOAL) {
        // TODO: fill this in.
      }
    }

    std::vector<msgs::Landmark> surface_boxes;
    for (size_t landmark_i = 0; landmark_i < step.landmarks.size();
         ++landmark_i) {
      const msgs::Landmark& landmark = step.landmarks[landmark_i];
      if (landmark.type == msgs::Landmark::SURFACE_BOX) {
        surface_boxes.push_back(landmark);
      }
      // Deal with other landmark types here
    }
    // Replace all surface objects if there are any.
    if (surface_boxes.size() > 0) {
      world->surface_box_landmarks = surface_boxes;
    }
  }
}
}  // namespace pbd
}  // namespace rapid
<|endoftext|>


<commit_before>#include "test_common.h"

using namespace XXX;
using namespace std;

void test_WS_destroyed_before_kernel(int port)
{
  cout << "---------- "<< __FUNCTION__ <<" ----------\n";

  callback_status = e_callback_not_invoked;

  {
    unique_ptr<kernel> the_kernel( new kernel({}, logger::nolog() ) );

    unique_ptr<tcp_socket> sock (new tcp_socket(the_kernel.get()));

    /* attempt to connect the socket */
    cout << "attemping socket connection ...\n";
    auto fut = sock->connect("127.0.0.1", port);

    auto connect_status = fut.wait_for(chrono::milliseconds(100));
    if (connect_status == future_status::timeout)
    {
      cout << "    failed to connect\n";
      return;
    }
    cout << "    got socket connection\n";

    /* attempt to create a session */
    cout << "attemping session creation ...\n";
    shared_ptr<wamp_session> session = wamp_session::create<rawsocket_protocol>(
      the_kernel.get(),
      std::move(sock),
      session_cb, {});

    cout << "    got session\n";

    cout << "calling: session->close().wait()\n";
    session->close().wait();
    cout << "trigger ~wamp_session\n";
    session.reset();
    cout << "exiting scope (will trigger kernel, io_loop, ev_loop destruction)...\n";

  }

  // ensure callback was invoked
  assert(callback_status == e_close_callback_with_sp);

  cout << "test success\n";
}

int main(int argc, char** argv)
{
  try
  {
    int starting_port_number = 21000;

    if (argc>1)
      starting_port_number = atoi(argv[1]);

    // share a common internal_server
    for (int i = 0; i < 50; i++)
    {
      internal_server iserver;
      int port = iserver.start(starting_port_number++);

      cout << "using shared iserver\n";
      for (int j=0; j < 100; j++) {
        test_WS_destroyed_before_kernel(port);
      }
    }

    // use one internal_server per test
    for (int i = 0; i < 5000; i++)
    {
      cout << "using dedicated iserver\n";
      internal_server iserver;
      int port = iserver.start(starting_port_number++);
      test_WS_destroyed_before_kernel(port);
    }

    return 0;
  }
  catch (exception& e)
  {
    cout << e.what() << endl;
    return 1;
  }

}
<commit_msg>more logging<commit_after>#include "test_common.h"

using namespace XXX;
using namespace std;

void test_WS_destroyed_before_kernel(int port)
{
  cout << "---------- "<< __FUNCTION__ <<" ----------\n";

  callback_status = e_callback_not_invoked;

  {
    unique_ptr<kernel> the_kernel( new kernel({}, logger::nolog() ) );

    unique_ptr<tcp_socket> sock (new tcp_socket(the_kernel.get()));

    /* attempt to connect the socket */
    cout << "attemping socket connection ...\n";
    auto fut = sock->connect("127.0.0.1", port);

    auto connect_status = fut.wait_for(chrono::milliseconds(100));
    if (connect_status == future_status::timeout)
    {
      cout << "    failed to connect\n";
      return;
    }
    cout << "    got socket connection\n";

    /* attempt to create a session */
    cout << "attemping session creation ...\n";
    shared_ptr<wamp_session> session = wamp_session::create<rawsocket_protocol>(
      the_kernel.get(),
      std::move(sock),
      session_cb, {});

    cout << "    got session\n";

    cout << "calling: session->close().wait()\n";
    session->close().wait();
    cout << "trigger ~wamp_session for " << session->unique_id() << "\n";
    session.reset();
    cout << "exiting scope (will trigger kernel, io_loop, ev_loop destruction)...\n";

  }

  // ensure callback was invoked
  assert(callback_status == e_close_callback_with_sp);

  cout << "test success\n";
}

int main(int argc, char** argv)
{
  try
  {
    int starting_port_number = 21000;

    if (argc>1)
      starting_port_number = atoi(argv[1]);

    // share a common internal_server
    for (int i = 0; i < 50; i++)
    {
      internal_server iserver;
      int port = iserver.start(starting_port_number++);

      cout << "using shared iserver\n";
      for (int j=0; j < 100; j++) {
        test_WS_destroyed_before_kernel(port);
      }
    }

    // use one internal_server per test
    for (int i = 0; i < 5000; i++)
    {
      cout << "using dedicated iserver\n";
      internal_server iserver;
      int port = iserver.start(starting_port_number++);
      test_WS_destroyed_before_kernel(port);
    }

    return 0;
  }
  catch (exception& e)
  {
    cout << e.what() << endl;
    return 1;
  }

}
<|endoftext|>


<commit_before>/*Copyright (c) 2011, Edgar Solomonik, all rights reserved.*/

/** \addtogroup examples
  * @{
  * \defgroup endomorphism endomorphism
  * @{
  * \brief tests custom element-wise functions by implementing division elementwise on 4D tensors
  */

#include <ctf.hpp>
using namespace CTF;

double fdbl(double a){
  //return a*a*a;
  return a;
}

int endomorphism(int     n,
                 World & dw){

  int shapeN4[] = {NS,NS,NS,NS};
  int sizeN4[] = {n,n,n,n};

  Tensor<> A(1, sizeN4, shapeN4, dw);

  A.fill_random(-.5, .5);

  double * all_start_data;
  int64_t nall;
  A.read_all(&nall, &all_start_data);

  CTF::Endomorphism<> endo(&fdbl);
  // below is equivalent to A.scale(1.0, "ijkl", endo);
  endo(A["ijkl"]);

  double * all_end_data;
  int64_t nall2;
  A.read_all(&nall2, &all_end_data);

  int pass = (nall == nall2);
  if (pass){
    for (int64_t i=0; i<nall; i++){
      if (fabs(fdbl(all_start_data[i])-all_end_data[i])>=1.E-6) pass =0;
    }
  }
  if (dw.rank == 0){
    MPI_Reduce(MPI_IN_PLACE, &pass, 1, MPI_INT, MPI_MIN, 0, MPI_COMM_WORLD);
    if (pass){
      printf("{ A[\"ijkl\"] = A[\"ijkl\"]^3 } passed\n");
    } else {
      printf("{ A[\"ijkl\"] = A[\"ijkl\"]^3 } failed\n");
    }
  } else
    MPI_Reduce(&pass, MPI_IN_PLACE, 1, MPI_INT, MPI_MIN, 0, MPI_COMM_WORLD);

  free(all_start_data);
  free(all_end_data);

  return pass;
}

#ifndef TEST_SUITE

char* getCmdOption(char ** begin,
                   char ** end,
                   const   std::string & option){
  char ** itr = std::find(begin, end, option);
  if (itr != end && ++itr != end){
    return *itr;
  }
  return 0;
}

int main(int argc, char ** argv){
  int rank, np, n;
  int const in_num = argc;
  char ** input_str = argv;

  MPI_Init(&argc, &argv);
  MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  MPI_Comm_size(MPI_COMM_WORLD, &np);

  if (getCmdOption(input_str, input_str+in_num, "-n")){
    n = atoi(getCmdOption(input_str, input_str+in_num, "-n"));
    if (n < 0) n = 5;
  } else n = 5;

  {
    World dw(MPI_COMM_WORLD, argc, argv);

    if (rank == 0){
      printf("Computing endomorphism A_ijkl = f(A_ijkl)\n");
    }
    endomorphism(n, dw);
  }

  MPI_Finalize();
  return 0;
}

/**
 * @}
 * @}
 */

#endif
<commit_msg>Trivial commit, started extending endomorphism example<commit_after>/*Copyright (c) 2011, Edgar Solomonik, all rights reserved.*/

/** \addtogroup examples
  * @{
  * \defgroup endomorphism endomorphism
  * @{
  * \brief tests custom element-wise functions by implementing division elementwise on 4D tensors
  */

#include <ctf.hpp>
using namespace CTF;

double fdbl(double a){
  //return a*a*a;
  return a;
}

int endomorphism(int     n,
                 World & dw){

  int shapeN4[] = {NS,NS,NS,NS};
  int sizeN4[] = {n,n,n,n};

  Tensor<> A(1, sizeN4, shapeN4, dw);

  A.fill_random(-.5, .5);

  double * all_start_data;
  int64_t nall;
  A.read_all(&nall, &all_start_data);

  CTF::Endomorphism<> endo(&fdbl);
  // below is equivalent to A.scale(1.0, "ijkl", endo);
  endo(A["ijkl"]);

  double * all_end_data;
  int64_t nall2;
  A.read_all(&nall2, &all_end_data);

  int pass = (nall == nall2);
  if (pass){
    for (int64_t i=0; i<nall; i++){
      if (fabs(fdbl(all_start_data[i])-all_end_data[i])>=1.E-6) pass =0;
    }
  }
  MPI_Allreduce(MPI_IN_PLACE, &pass, 1, MPI_INT, MPI_MIN, 0, MPI_COMM_WORLD);
  if (pass){

  }

  if (dw.rank == 0){
    if (pass){
      printf("{ A[\"ijkl\"] = A[\"ijkl\"]^3 } passed\n");
    } else {
      printf("{ A[\"ijkl\"] = A[\"ijkl\"]^3 } failed\n");
    }
  }
  free(all_start_data);
  free(all_end_data);

  return pass;
}

#ifndef TEST_SUITE

char* getCmdOption(char ** begin,
                   char ** end,
                   const   std::string & option){
  char ** itr = std::find(begin, end, option);
  if (itr != end && ++itr != end){
    return *itr;
  }
  return 0;
}

int main(int argc, char ** argv){
  int rank, np, n;
  int const in_num = argc;
  char ** input_str = argv;

  MPI_Init(&argc, &argv);
  MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  MPI_Comm_size(MPI_COMM_WORLD, &np);

  if (getCmdOption(input_str, input_str+in_num, "-n")){
    n = atoi(getCmdOption(input_str, input_str+in_num, "-n"));
    if (n < 0) n = 5;
  } else n = 5;

  {
    World dw(MPI_COMM_WORLD, argc, argv);

    if (rank == 0){
      printf("Computing endomorphism A_ijkl = f(A_ijkl)\n");
    }
    endomorphism(n, dw);
  }

  MPI_Finalize();
  return 0;
}

/**
 * @}
 * @}
 */

#endif
<|endoftext|>


<commit_before>#include "test_common.h"

using namespace XXX;
using namespace std;

void test_WS_destroyed_before_kernel(int port)
{
  cout << "---------- test_WS_destroyed_before_kernel ----------\n";

  callback_status = e_callback_not_invoked;

  {
    unique_ptr<kernel> the_kernel( new kernel({}, logger::nolog() ) );

    unique_ptr<tcp_socket> sock (new tcp_socket(the_kernel.get()));

    /* attempt to connect the socket */
    cout << "attemping socket connection ...\n";
    auto fut = sock->connect("127.0.0.1", port);

    auto connect_status = fut.wait_for(chrono::milliseconds(100));
    if (connect_status == future_status::timeout)
    {
      cout << "    failed to connect\n";
      return;
    }
    cout << "    got socket connection\n";

    /* attempt to create a session */
    cout << "attemping session creation ...\n";
    shared_ptr<wamp_session> session = wamp_session::create<rawsocket_protocol>(
      the_kernel.get(),
      std::move(sock),
      session_cb, {});

    cout << "    got session\n";

    cout << "calling: session->close().wait()\n";
    session->close().wait();
    cout << "trigger ~wamp_session\n";
    session.reset();
    cout << "exiting scope (will trigger kernel, io_loop, ev_loop destruction)...\n";

  }

  // ensure callback was invoked
  assert(callback_status == e_close_callback_with_sp);

  cout << "test success\n";
}

int main(int argc, char** argv)
{
  try
  {
    int starting_port_number = 21000;

    if (argc>1)
      starting_port_number = atoi(argv[1]);

    // share a common internal_server
    for (int i = 0; i < 50; i++)
    {
      internal_server iserver;
      int port = iserver.start(starting_port_number++);

      for (int j=0; j < 100; j++) {
        cout << "using shared iserver\n";
        test_WS_destroyed_before_kernel(port);
      }
    }

    // use one internal_server per test
    for (int i = 0; i < 5000; i++)
    {
      cout << "using dedicated iserver\n";
      internal_server iserver;
      int port = iserver.start(starting_port_number++);
      test_WS_destroyed_before_kernel(port);
    }

    return 0;
  }
  catch (exception& e)
  {
    cout << e.what() << endl;
    return 1;
  }

}
<commit_msg>minor logging change<commit_after>#include "test_common.h"

using namespace XXX;
using namespace std;

void test_WS_destroyed_before_kernel(int port)
{
  cout << "---------- "<< __FUNCTION__ <<" ----------\n";

  callback_status = e_callback_not_invoked;

  {
    unique_ptr<kernel> the_kernel( new kernel({}, logger::nolog() ) );

    unique_ptr<tcp_socket> sock (new tcp_socket(the_kernel.get()));

    /* attempt to connect the socket */
    cout << "attemping socket connection ...\n";
    auto fut = sock->connect("127.0.0.1", port);

    auto connect_status = fut.wait_for(chrono::milliseconds(100));
    if (connect_status == future_status::timeout)
    {
      cout << "    failed to connect\n";
      return;
    }
    cout << "    got socket connection\n";

    /* attempt to create a session */
    cout << "attemping session creation ...\n";
    shared_ptr<wamp_session> session = wamp_session::create<rawsocket_protocol>(
      the_kernel.get(),
      std::move(sock),
      session_cb, {});

    cout << "    got session\n";

    cout << "calling: session->close().wait()\n";
    session->close().wait();
    cout << "trigger ~wamp_session\n";
    session.reset();
    cout << "exiting scope (will trigger kernel, io_loop, ev_loop destruction)...\n";

  }

  // ensure callback was invoked
  assert(callback_status == e_close_callback_with_sp);

  cout << "test success\n";
}

int main(int argc, char** argv)
{
  try
  {
    int starting_port_number = 21000;

    if (argc>1)
      starting_port_number = atoi(argv[1]);

    // share a common internal_server
    for (int i = 0; i < 50; i++)
    {
      internal_server iserver;
      int port = iserver.start(starting_port_number++);

      cout << "using shared iserver\n";
      for (int j=0; j < 100; j++) {
        test_WS_destroyed_before_kernel(port);
      }
    }

    // use one internal_server per test
    for (int i = 0; i < 5000; i++)
    {
      cout << "using dedicated iserver\n";
      internal_server iserver;
      int port = iserver.start(starting_port_number++);
      test_WS_destroyed_before_kernel(port);
    }

    return 0;
  }
  catch (exception& e)
  {
    cout << e.what() << endl;
    return 1;
  }

}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtTest/QtTest>
#include <QtGui/qgraphicseffect.h>
#include <QtGui/qgraphicsview.h>
#include <QtGui/qgraphicsscene.h>
#include <QtGui/qgraphicsitem.h>
#include <QtGui/qstyleoption.h>

//TESTED_CLASS=
//TESTED_FILES=

class CustomItem : public QGraphicsRectItem
{
public:
    CustomItem(qreal x, qreal y, qreal width, qreal height)
        : QGraphicsRectItem(x, y, width, height), numRepaints(0),
          m_painter(0), m_styleOption(0)
    {}

    void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
    {
        m_painter = painter;
        m_styleOption = option;
        ++numRepaints;
        QGraphicsRectItem::paint(painter, option, widget);
    }

    void reset()
    {
        numRepaints = 0;
        m_painter = 0;
        m_styleOption = 0;
    }

    int numRepaints;
    QPainter *m_painter;
    const QStyleOption *m_styleOption;
};

class CustomEffect : public QGraphicsEffect
{
public:
    CustomEffect()
        : QGraphicsEffect(), numRepaints(0), m_margin(10), m_sourceChanged(false),
          m_sourceBoundingRectChanged(false), doNothingInDraw(false),
          storeDeviceDependentStuff(false),
          m_painter(0), m_styleOption(0), m_source(0)
    {}

    QRectF boundingRectFor(const QRectF &rect) const
    { return rect.adjusted(-m_margin, -m_margin, m_margin, m_margin); }

    void reset()
    {
        numRepaints = 0;
        m_sourceChanged = false;
        m_sourceBoundingRectChanged = false;
        m_painter = 0;
        m_styleOption = 0;
        m_source = 0;
        deviceCoordinatesPixmap = QPixmap();
        deviceRect = QRect();
        sourceDeviceBoundingRect = QRectF();
    }

    void setMargin(int margin)
    {
        m_margin = margin;
        updateBoundingRect();
    }

    int margin() const
    { return m_margin; }

    void draw(QPainter *painter, QGraphicsEffectSource *source)
    {
        ++numRepaints;
        if (storeDeviceDependentStuff) {
            deviceCoordinatesPixmap = source->pixmap(Qt::DeviceCoordinates);
            deviceRect = source->deviceRect();
            sourceDeviceBoundingRect = source->boundingRect(Qt::DeviceCoordinates);
        }
        if (doNothingInDraw)
            return;
        m_source = source;
        m_painter = painter;
        m_styleOption = source->styleOption();
        source->draw(painter);
    }

    void sourceChanged()
    { m_sourceChanged = true; }

    void sourceBoundingRectChanged()
    { m_sourceBoundingRectChanged = true; }

    int numRepaints;
    int m_margin;
    bool m_sourceChanged;
    bool m_sourceBoundingRectChanged;
    bool doNothingInDraw;
    bool storeDeviceDependentStuff;
    QPainter *m_painter;
    const QStyleOption *m_styleOption;
    QGraphicsEffectSource *m_source;
    QPixmap deviceCoordinatesPixmap;
    QRect deviceRect;
    QRectF sourceDeviceBoundingRect;
};

class tst_QGraphicsEffectSource : public QObject
{
    Q_OBJECT
public slots:
    void initTestCase();
    void cleanupTestCase();
    void init();

private slots:
    void graphicsItem();
    void styleOption();
    void isPixmap();
    void draw();
    void update();
    void boundingRect();
    void deviceRect();
    void pixmap();

    void pixmapPadding_data();
    void pixmapPadding();

private:
    QGraphicsView *view;
    QGraphicsScene *scene;
    CustomItem *item;
    CustomEffect *effect;
};

void tst_QGraphicsEffectSource::initTestCase()
{
    scene = new QGraphicsScene;
    item = new CustomItem(0, 0, 100, 100);
    effect = new CustomEffect;
    item->setGraphicsEffect(effect);
    scene->addItem(item);
    view = new QGraphicsView(scene);
    view->show();
#ifdef Q_WS_X11
    qt_x11_wait_for_window_manager(view);
#endif
    QTest::qWait(200);
}

void tst_QGraphicsEffectSource::cleanupTestCase()
{
    delete view;
}

void tst_QGraphicsEffectSource::init()
{
    QVERIFY(effect);
    QVERIFY(item);
    QVERIFY(effect->source());
    effect->reset();
    effect->storeDeviceDependentStuff = false;
    effect->doNothingInDraw = false;
    item->reset();
}

void tst_QGraphicsEffectSource::graphicsItem()
{
    QVERIFY(effect->source());
    QCOMPARE(effect->source()->graphicsItem(), item);
}

void tst_QGraphicsEffectSource::styleOption()
{
    // We don't have style options unless the source is drawing.
    QVERIFY(effect->source());
    QVERIFY(!effect->source()->styleOption());

    // Trigger an update and check that the style option in QGraphicsEffect::draw
    // was the same as the one in QGraphicsItem::paint.
    QCOMPARE(item->numRepaints, 0);
    QCOMPARE(effect->numRepaints, 0);
    item->update();
    QTest::qWait(50);
    QCOMPARE(item->numRepaints, 1);
    QCOMPARE(effect->numRepaints, 1);
    QVERIFY(effect->m_styleOption);
    QCOMPARE(effect->m_styleOption, item->m_styleOption);
}

void tst_QGraphicsEffectSource::isPixmap()
{
    // Current source is a CustomItem (which is not a pixmap item).
    QVERIFY(!effect->source()->isPixmap());

    // Make sure isPixmap() returns true for QGraphicsPixmapItem.
    QGraphicsPixmapItem *pixmapItem = new QGraphicsPixmapItem;
    CustomEffect *anotherEffect = new CustomEffect;
    pixmapItem->setGraphicsEffect(anotherEffect);
    QVERIFY(anotherEffect->source());
    QCOMPARE(anotherEffect->source()->graphicsItem(), static_cast<QGraphicsItem *>(pixmapItem));
    QVERIFY(anotherEffect->source()->isPixmap());
    delete pixmapItem;
}

void tst_QGraphicsEffectSource::draw()
{
    // The source can only draw as a result of QGraphicsEffect::draw.
    QTest::ignoreMessage(QtWarningMsg, "QGraphicsEffectSource::draw: Can only begin as a result of QGraphicsEffect::draw");
    QPixmap dummyPixmap(10, 10);
    QPainter dummyPainter(&dummyPixmap);
    effect->source()->draw(&dummyPainter);
}

void tst_QGraphicsEffectSource::update()
{
    QCOMPARE(item->numRepaints, 0);
    QCOMPARE(effect->numRepaints, 0);

    effect->source()->update();
    QTest::qWait(50);

    QCOMPARE(item->numRepaints, 1);
    QCOMPARE(effect->numRepaints, 1);
}

void tst_QGraphicsEffectSource::boundingRect()
{
    QTest::ignoreMessage(QtWarningMsg, "QGraphicsEffectSource::boundingRect: Not yet implemented, lacking device context");
    QCOMPARE(effect->source()->boundingRect(Qt::DeviceCoordinates), QRectF());

    QRectF itemBoundingRect = item->boundingRect();
    if (!item->children().isEmpty())
        itemBoundingRect |= item->childrenBoundingRect();

    // We can at least check that the device bounding rect was correct in QGraphicsEffect::draw.
    effect->storeDeviceDependentStuff = true;
    effect->source()->update();
    QTest::qWait(50);
    const QTransform deviceTransform = item->deviceTransform(view->viewportTransform());
    QCOMPARE(effect->sourceDeviceBoundingRect, deviceTransform.mapRect(itemBoundingRect));

    // Bounding rect in logical coordinates is of course fine.
    QCOMPARE(effect->source()->boundingRect(Qt::LogicalCoordinates), itemBoundingRect);
    // Make sure default value is Qt::LogicalCoordinates.
    QCOMPARE(effect->source()->boundingRect(), itemBoundingRect);
}

void tst_QGraphicsEffectSource::deviceRect()
{
    QTest::ignoreMessage(QtWarningMsg, "QGraphicsEffectSource::deviceRect: Not yet implemented, lacking device context");
    QCOMPARE(effect->source()->deviceRect(), QRect());

    // We can at least check that the rect was correct in QGraphicsEffect::draw.
    effect->storeDeviceDependentStuff = true;
    effect->source()->update();
    QTest::qWait(50);
    QCOMPARE(effect->deviceRect, view->viewport()->rect());
}

void tst_QGraphicsEffectSource::pixmap()
{
    QTest::ignoreMessage(QtWarningMsg, "QGraphicsEffectSource::pixmap: Not yet implemented, lacking device context");
    QCOMPARE(effect->source()->pixmap(Qt::DeviceCoordinates), QPixmap());

    // We can at least verify a valid pixmap from QGraphicsEffect::draw.
    effect->storeDeviceDependentStuff = true;
    effect->source()->update();
    QTest::qWait(50);
    QVERIFY(!effect->deviceCoordinatesPixmap.isNull());

    // Pixmaps in logical coordinates we can do fine.
    QPixmap pixmap1 = effect->source()->pixmap(Qt::LogicalCoordinates);
    QVERIFY(!pixmap1.isNull());

    // Make sure default value is Qt::LogicalCoordinates.
    QPixmap pixmap2 = effect->source()->pixmap();
    QCOMPARE(pixmap1, pixmap2);
}

class PaddingEffect : public QGraphicsEffect
{
public:
    PaddingEffect(QObject *parent) : QGraphicsEffect(parent)
    {
    }

    QRectF boundingRectFor(const QRectF &src) const {
        return src.adjusted(-10, -10, 10, 10);
    }

    void draw(QPainter *, QGraphicsEffectSource *source) {
        pix = source->pixmap(coordinateMode, &offset, padMode);
    }

    QPixmap pix;
    QPoint offset;
    QGraphicsEffectSource::PixmapPadMode padMode;
    Qt::CoordinateSystem coordinateMode;
};

void tst_QGraphicsEffectSource::pixmapPadding_data()
{
    QTest::addColumn<int>("coordinateMode");
    QTest::addColumn<int>("padMode");
    QTest::addColumn<QSize>("size");
    QTest::addColumn<QPoint>("offset");
    QTest::addColumn<uint>("ulPixel");

    QTest::newRow("log,nopad") << int(Qt::LogicalCoordinates)
                               << int(QGraphicsEffectSource::NoExpandPadMode)
                               << QSize(10, 10) << QPoint(0, 0)
                               << 0xffff0000u;

    QTest::newRow("log,transparent") << int(Qt::LogicalCoordinates)
                                     << int(QGraphicsEffectSource::ExpandToTransparentBorderPadMode)
                                     << QSize(14, 14) << QPoint(-2, -2)
                                     << 0x00000000u;

    QTest::newRow("log,effectrect") << int(Qt::LogicalCoordinates)
                                    << int(QGraphicsEffectSource::ExpandToEffectRectPadMode)
                                    << QSize(30, 30) << QPoint(-10, -10)
                                    << 0x00000000u;

    QTest::newRow("dev,nopad") << int(Qt::DeviceCoordinates)
                               << int(QGraphicsEffectSource::NoExpandPadMode)
                               << QSize(20, 20) << QPoint(40, 40)
                               << 0xffff0000u;

    QTest::newRow("dev,transparent") << int(Qt::DeviceCoordinates)
                                     << int(QGraphicsEffectSource::ExpandToTransparentBorderPadMode)
                                     << QSize(24, 24) << QPoint(38, 38)
                                     << 0x00000000u;

    QTest::newRow("dev,effectrect") << int(Qt::DeviceCoordinates)
                                    << int(QGraphicsEffectSource::ExpandToEffectRectPadMode)
                                    << QSize(40, 40) << QPoint(30, 30)
                                    << 0x00000000u;

}

void tst_QGraphicsEffectSource::pixmapPadding()
{
    QPixmap dummyTarget(100, 100);
    QPainter dummyPainter(&dummyTarget);
    dummyPainter.translate(40, 40);
    dummyPainter.scale(2, 2);

    QPixmap pm(10, 10);
    pm.fill(Qt::red);

    QGraphicsScene *scene = new QGraphicsScene();
    PaddingEffect *effect = new PaddingEffect(scene);
    QGraphicsPixmapItem *pmItem = new QGraphicsPixmapItem(pm);
    scene->addItem(pmItem);
    pmItem->setGraphicsEffect(effect);

    QFETCH(int, coordinateMode);
    QFETCH(int, padMode);
    QFETCH(QPoint, offset);
    QFETCH(QSize, size);
    QFETCH(uint, ulPixel);

    effect->padMode = (QGraphicsEffectSource::PixmapPadMode) padMode;
    effect->coordinateMode = (Qt::CoordinateSystem) coordinateMode;

    scene->render(&dummyPainter, scene->itemsBoundingRect(), scene->itemsBoundingRect());

    QCOMPARE(effect->pix.size(), size);
    QCOMPARE(effect->offset, offset);
    QCOMPARE(effect->pix.toImage().pixel(0, 0), ulPixel);

    // ### Fix corruption in scene destruction, then enable...
    // delete scene;
}

QTEST_MAIN(tst_QGraphicsEffectSource)
#include "tst_qgraphicseffectsource.moc"

<commit_msg>Fixed QGraphicsEffectSource autotest after graphics effect API changes. (cherry picked from commit 1a36403e3c21a60f81cd0244b84f21223b4216e9)<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include <QtTest/QtTest>
#include <QtGui/qgraphicseffect.h>
#include <QtGui/qgraphicsview.h>
#include <QtGui/qgraphicsscene.h>
#include <QtGui/qgraphicsitem.h>
#include <QtGui/qstyleoption.h>

#include <private/qgraphicseffect_p.h>

//TESTED_CLASS=
//TESTED_FILES=

class CustomItem : public QGraphicsRectItem
{
public:
    CustomItem(qreal x, qreal y, qreal width, qreal height)
        : QGraphicsRectItem(x, y, width, height), numRepaints(0),
          m_painter(0)
    {}

    void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
    {
        m_painter = painter;
        ++numRepaints;
        QGraphicsRectItem::paint(painter, option, widget);
    }

    void reset()
    {
        numRepaints = 0;
        m_painter = 0;
    }

    int numRepaints;
    QPainter *m_painter;
};

class CustomEffect : public QGraphicsEffect
{
public:
    CustomEffect()
        : QGraphicsEffect(), numRepaints(0), m_margin(10), m_sourceChanged(false),
          m_sourceBoundingRectChanged(false), doNothingInDraw(false),
          storeDeviceDependentStuff(false),
          m_painter(0), m_source(0)
    {}

    QRectF boundingRectFor(const QRectF &rect) const
    { return rect.adjusted(-m_margin, -m_margin, m_margin, m_margin); }

    void reset()
    {
        numRepaints = 0;
        m_sourceChanged = false;
        m_sourceBoundingRectChanged = false;
        m_painter = 0;
        m_source = 0;
        deviceCoordinatesPixmap = QPixmap();
        deviceRect = QRect();
        sourceDeviceBoundingRect = QRectF();
    }

    void setMargin(int margin)
    {
        m_margin = margin;
        updateBoundingRect();
    }

    int margin() const
    { return m_margin; }

    void draw(QPainter *painter)
    {
        ++numRepaints;
        if (storeDeviceDependentStuff) {
            deviceCoordinatesPixmap = source()->pixmap(Qt::DeviceCoordinates);
            deviceRect = QRect(0, 0, painter->device()->width(), painter->device()->height());
            sourceDeviceBoundingRect = source()->boundingRect(Qt::DeviceCoordinates);
        }
        if (doNothingInDraw)
            return;
        m_source = source();
        m_painter = painter;
        source()->draw(painter);
    }

    void sourceChanged()
    { m_sourceChanged = true; }

    void sourceBoundingRectChanged()
    { m_sourceBoundingRectChanged = true; }

    int numRepaints;
    int m_margin;
    bool m_sourceChanged;
    bool m_sourceBoundingRectChanged;
    bool doNothingInDraw;
    bool storeDeviceDependentStuff;
    QPainter *m_painter;
    QGraphicsEffectSource *m_source;
    QPixmap deviceCoordinatesPixmap;
    QRect deviceRect;
    QRectF sourceDeviceBoundingRect;
};

class tst_QGraphicsEffectSource : public QObject
{
    Q_OBJECT
public slots:
    void initTestCase();
    void cleanupTestCase();
    void init();

private slots:
    void graphicsItem();
    void styleOption();
    void isPixmap();
    void draw();
    void update();
    void boundingRect();
    void deviceRect();
    void pixmap();

    void pixmapPadding_data();
    void pixmapPadding();

private:
    QGraphicsView *view;
    QGraphicsScene *scene;
    CustomItem *item;
    CustomEffect *effect;
};

void tst_QGraphicsEffectSource::initTestCase()
{
    scene = new QGraphicsScene;
    item = new CustomItem(0, 0, 100, 100);
    effect = new CustomEffect;
    item->setGraphicsEffect(effect);
    scene->addItem(item);
    view = new QGraphicsView(scene);
    view->show();
#ifdef Q_WS_X11
    qt_x11_wait_for_window_manager(view);
#endif
    QTest::qWait(200);
}

void tst_QGraphicsEffectSource::cleanupTestCase()
{
    delete view;
}

void tst_QGraphicsEffectSource::init()
{
    QVERIFY(effect);
    QVERIFY(item);
    QVERIFY(effect->source());
    effect->reset();
    effect->storeDeviceDependentStuff = false;
    effect->doNothingInDraw = false;
    item->reset();
}

void tst_QGraphicsEffectSource::graphicsItem()
{
    QVERIFY(effect->source());
    QCOMPARE(effect->source()->graphicsItem(), item);
}

void tst_QGraphicsEffectSource::styleOption()
{
    // We don't have style options unless the source is drawing.
    QVERIFY(effect->source());
    QVERIFY(!effect->source()->styleOption());

    // Trigger an update and check that the style option in QGraphicsEffect::draw
    // was the same as the one in QGraphicsItem::paint.
    QCOMPARE(item->numRepaints, 0);
    QCOMPARE(effect->numRepaints, 0);
    item->update();
    QTest::qWait(50);
    QCOMPARE(item->numRepaints, 1);
    QCOMPARE(effect->numRepaints, 1);
}

void tst_QGraphicsEffectSource::isPixmap()
{
    // Current source is a CustomItem (which is not a pixmap item).
    QVERIFY(!effect->source()->isPixmap());

    // Make sure isPixmap() returns true for QGraphicsPixmapItem.
    QGraphicsPixmapItem *pixmapItem = new QGraphicsPixmapItem;
    CustomEffect *anotherEffect = new CustomEffect;
    pixmapItem->setGraphicsEffect(anotherEffect);
    QVERIFY(anotherEffect->source());
    QCOMPARE(anotherEffect->source()->graphicsItem(), static_cast<QGraphicsItem *>(pixmapItem));
    QVERIFY(anotherEffect->source()->isPixmap());
    delete pixmapItem;
}

void tst_QGraphicsEffectSource::draw()
{
    // The source can only draw as a result of QGraphicsEffect::draw.
    QTest::ignoreMessage(QtWarningMsg, "QGraphicsEffectSource::draw: Can only begin as a result of QGraphicsEffect::draw");
    QPixmap dummyPixmap(10, 10);
    QPainter dummyPainter(&dummyPixmap);
    effect->source()->draw(&dummyPainter);
}

void tst_QGraphicsEffectSource::update()
{
    QCOMPARE(item->numRepaints, 0);
    QCOMPARE(effect->numRepaints, 0);

    effect->source()->update();
    QTest::qWait(50);

    QCOMPARE(item->numRepaints, 1);
    QCOMPARE(effect->numRepaints, 1);
}

void tst_QGraphicsEffectSource::boundingRect()
{
    QTest::ignoreMessage(QtWarningMsg, "QGraphicsEffectSource::boundingRect: Not yet implemented, lacking device context");
    QCOMPARE(effect->source()->boundingRect(Qt::DeviceCoordinates), QRectF());

    QRectF itemBoundingRect = item->boundingRect();
    if (!item->children().isEmpty())
        itemBoundingRect |= item->childrenBoundingRect();

    // We can at least check that the device bounding rect was correct in QGraphicsEffect::draw.
    effect->storeDeviceDependentStuff = true;
    effect->source()->update();
    QTest::qWait(50);
    const QTransform deviceTransform = item->deviceTransform(view->viewportTransform());
    QCOMPARE(effect->sourceDeviceBoundingRect, deviceTransform.mapRect(itemBoundingRect));

    // Bounding rect in logical coordinates is of course fine.
    QCOMPARE(effect->source()->boundingRect(Qt::LogicalCoordinates), itemBoundingRect);
    // Make sure default value is Qt::LogicalCoordinates.
    QCOMPARE(effect->source()->boundingRect(), itemBoundingRect);
}

void tst_QGraphicsEffectSource::deviceRect()
{
    effect->storeDeviceDependentStuff = true;
    effect->source()->update();
    QTest::qWait(50);
    QCOMPARE(effect->deviceRect, view->viewport()->rect());
}

void tst_QGraphicsEffectSource::pixmap()
{
    QTest::ignoreMessage(QtWarningMsg, "QGraphicsEffectSource::pixmap: Not yet implemented, lacking device context");
    QCOMPARE(effect->source()->pixmap(Qt::DeviceCoordinates), QPixmap());

    // We can at least verify a valid pixmap from QGraphicsEffect::draw.
    effect->storeDeviceDependentStuff = true;
    effect->source()->update();
    QTest::qWait(50);
    QVERIFY(!effect->deviceCoordinatesPixmap.isNull());

    // Pixmaps in logical coordinates we can do fine.
    QPixmap pixmap1 = effect->source()->pixmap(Qt::LogicalCoordinates);
    QVERIFY(!pixmap1.isNull());

    // Make sure default value is Qt::LogicalCoordinates.
    QPixmap pixmap2 = effect->source()->pixmap();
    QCOMPARE(pixmap1, pixmap2);
}

class PaddingEffect : public QGraphicsEffect
{
public:
    PaddingEffect(QObject *parent) : QGraphicsEffect(parent)
    {
    }

    QRectF boundingRectFor(const QRectF &src) const {
        return src.adjusted(-10, -10, 10, 10);
    }

    void draw(QPainter *) {
        pix = source()->pixmap(coordinateMode, &offset, padMode);
    }

    QPixmap pix;
    QPoint offset;
    QGraphicsEffect::PixmapPadMode padMode;
    Qt::CoordinateSystem coordinateMode;
};

void tst_QGraphicsEffectSource::pixmapPadding_data()
{
    QTest::addColumn<int>("coordinateMode");
    QTest::addColumn<int>("padMode");
    QTest::addColumn<QSize>("size");
    QTest::addColumn<QPoint>("offset");
    QTest::addColumn<uint>("ulPixel");

    QTest::newRow("log,nopad") << int(Qt::LogicalCoordinates)
                               << int(QGraphicsEffect::NoPad)
                               << QSize(10, 10) << QPoint(0, 0)
                               << 0xffff0000u;

    QTest::newRow("log,transparent") << int(Qt::LogicalCoordinates)
                                     << int(QGraphicsEffect::PadToTransparentBorder)
                                     << QSize(14, 14) << QPoint(-2, -2)
                                     << 0x00000000u;

    QTest::newRow("log,effectrect") << int(Qt::LogicalCoordinates)
                                    << int(QGraphicsEffect::PadToEffectiveBoundingRect)
                                    << QSize(30, 30) << QPoint(-10, -10)
                                    << 0x00000000u;

    QTest::newRow("dev,nopad") << int(Qt::DeviceCoordinates)
                               << int(QGraphicsEffect::NoPad)
                               << QSize(20, 20) << QPoint(40, 40)
                               << 0xffff0000u;

    QTest::newRow("dev,transparent") << int(Qt::DeviceCoordinates)
                                     << int(QGraphicsEffect::PadToTransparentBorder)
                                     << QSize(24, 24) << QPoint(38, 38)
                                     << 0x00000000u;

    QTest::newRow("dev,effectrect") << int(Qt::DeviceCoordinates)
                                    << int(QGraphicsEffect::PadToEffectiveBoundingRect)
                                    << QSize(40, 40) << QPoint(30, 30)
                                    << 0x00000000u;

}

void tst_QGraphicsEffectSource::pixmapPadding()
{
    QPixmap dummyTarget(100, 100);
    QPainter dummyPainter(&dummyTarget);
    dummyPainter.translate(40, 40);
    dummyPainter.scale(2, 2);

    QPixmap pm(10, 10);
    pm.fill(Qt::red);

    QGraphicsScene *scene = new QGraphicsScene();
    PaddingEffect *effect = new PaddingEffect(scene);
    QGraphicsPixmapItem *pmItem = new QGraphicsPixmapItem(pm);
    scene->addItem(pmItem);
    pmItem->setGraphicsEffect(effect);

    QFETCH(int, coordinateMode);
    QFETCH(int, padMode);
    QFETCH(QPoint, offset);
    QFETCH(QSize, size);
    QFETCH(uint, ulPixel);

    effect->padMode = (QGraphicsEffect::PixmapPadMode) padMode;
    effect->coordinateMode = (Qt::CoordinateSystem) coordinateMode;

    scene->render(&dummyPainter, scene->itemsBoundingRect(), scene->itemsBoundingRect());

    QCOMPARE(effect->pix.size(), size);
    QCOMPARE(effect->offset, offset);
    QCOMPARE(effect->pix.toImage().pixel(0, 0), ulPixel);

    // ### Fix corruption in scene destruction, then enable...
    // delete scene;
}

QTEST_MAIN(tst_QGraphicsEffectSource)
#include "tst_qgraphicseffectsource.moc"

<|endoftext|>


<commit_before>/*
 * Copyright (C) 2010-2014 Jeremy Lainé
 * Contact: https://github.com/jlaine/qdjango
 *
 * This file is part of the QDjango Library.
 *
 * 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.1 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.
 */

#include <QDateTime>
#include <QtTest>

#include "QDjangoHttpController.h"

/** Test QDjangoHttpController class.
 */
class tst_QDjangoHttpController : public QObject
{
    Q_OBJECT

private slots:
    void testDateTime();
};

void tst_QDjangoHttpController::testDateTime()
{
    const QDateTime dt(QDate(2014, 7, 14), QTime(11, 22, 33), Qt::UTC);
    QCOMPARE(QDjangoHttpController::httpDateTime(dt), QString("Mon, 14 Jul 2014 11:22:33 GMT"));
    QCOMPARE(QDjangoHttpController::httpDateTime("Mon, 14 Jul 2014 11:22:33 GMT"), dt);
}

QTEST_MAIN(tst_QDjangoHttpController)
#include "tst_qdjangohttpcontroller.moc"
<commit_msg>add some tests for QDjangoHttpController<commit_after>/*
 * Copyright (C) 2010-2014 Jeremy Lainé
 * Contact: https://github.com/jlaine/qdjango
 *
 * This file is part of the QDjango Library.
 *
 * 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.1 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.
 */

#include <QDateTime>
#include <QtTest>

#include "QDjangoHttpController.h"
#include "QDjangoHttpRequest.h"
#include "QDjangoHttpResponse.h"

/** Test QDjangoHttpController class.
 */
class tst_QDjangoHttpController : public QObject
{
    Q_OBJECT

private slots:
    void testBasicAuth();
    void testDateTime();
    void testServeAuthorizationRequired();
    void testServeBadRequest();
    void testServeInternalServerError();
    void testServeNotFound();
    void testServeRedirect();
};

void tst_QDjangoHttpController::testBasicAuth()
{
    QDjangoHttpRequest request;

    QString username, password;
    QCOMPARE(QDjangoHttpController::getBasicAuth(request, username, password), false);
}

void tst_QDjangoHttpController::testDateTime()
{
    const QDateTime dt(QDate(2014, 7, 14), QTime(11, 22, 33), Qt::UTC);
    QCOMPARE(QDjangoHttpController::httpDateTime(dt), QString("Mon, 14 Jul 2014 11:22:33 GMT"));
    QCOMPARE(QDjangoHttpController::httpDateTime("Mon, 14 Jul 2014 11:22:33 GMT"), dt);
}

void tst_QDjangoHttpController::testServeAuthorizationRequired()
{
    QDjangoHttpRequest request;
    QDjangoHttpResponse *response = QDjangoHttpController::serveAuthorizationRequired(request);
    QCOMPARE(response->statusCode(), 401);
    QCOMPARE(response->header("www-authenticate"), QString("Basic realm=\"Secure Area\""));
    delete response;
}

void tst_QDjangoHttpController::testServeBadRequest()
{
    QDjangoHttpRequest request;
    QDjangoHttpResponse *response = QDjangoHttpController::serveBadRequest(request);
    QCOMPARE(response->statusCode(), 400);
    delete response;
}

void tst_QDjangoHttpController::testServeInternalServerError()
{
    QDjangoHttpRequest request;
    QDjangoHttpResponse *response = QDjangoHttpController::serveInternalServerError(request);
    QCOMPARE(response->statusCode(), 500);
    delete response;
}

void tst_QDjangoHttpController::testServeNotFound()
{
    QDjangoHttpRequest request;
    QDjangoHttpResponse *response = QDjangoHttpController::serveNotFound(request);
    QCOMPARE(response->statusCode(), 404);
    delete response;
}

void tst_QDjangoHttpController::testServeRedirect()
{
    QDjangoHttpRequest request;

    QDjangoHttpResponse *response = QDjangoHttpController::serveRedirect(request, QUrl("/bye"), false);
    QCOMPARE(response->statusCode(), 302);
    QCOMPARE(response->header("location"), QString("/bye"));
    delete response;

    response = QDjangoHttpController::serveRedirect(request, QUrl("/bye"), true);
    QCOMPARE(response->statusCode(), 301);
    QCOMPARE(response->header("location"), QString("/bye"));
    delete response;
}

QTEST_MAIN(tst_QDjangoHttpController)
#include "tst_qdjangohttpcontroller.moc"
<|endoftext|>