<commit_before>// Copyright (C) 2011 by Toshiro Yamada
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <csignal>
#include <string>
#include <iostream>
#include <boost/tokenizer.hpp>
#include <boost/lexical_cast.hpp>

#include "asset_manager_client.hpp"

// global variables
std::string g_base_address = "";
bool g_use_udp = false;
std::string g_host_address = "127.0.0.1";
bool g_continue = true;

void ProcessArguments(int argc, const char* argv[]);
void ProcessInput(am::AssetManagerClient& am, const std::string& input);
void Signal(int what);

template <class T>
bool from_string(T& t,
    const std::string& s,
    std::ios_base& (*f)(std::ios_base&));

template <class T>
bool from_string(T& t,
    const std::string& s,
    std::ios_base& (*f)(std::ios_base&))
{
  std::istringstream iss(s);
  return !(iss >> f >> t).fail();
}

int main(int argc, const char* argv[])
{
  ProcessArguments(argc, argv);
  std::cout << "Using base address: " << g_base_address << "\n";
  std::cout << "Type \"help\" to list commands\n";

  am::AssetManagerClient am(g_base_address, g_host_address);
  if (g_use_udp) am.SetOption(am::AssetManagerClient::CORE_USE_UDP);
  am.SetOption(am::AssetManagerClient::SEND_UNLOAD_IN_DESTRUCTOR);

  signal(SIGINT, Signal);
#if !defined(_WIN32)
  signal(SIGQUIT, Signal);
#endif

  while (g_continue) {
    std::cout << "-> ";
    std::string input;
    std::getline(std::cin, input);
    if (std::cin.eof() || std::cin.fail()) break;
    ProcessInput(am, input);
  }

  return 0;
}

void ProcessArguments(int argc, const char* argv[])
{
  int i = 1;
  while (i < argc) {
    if (!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help")) {
      goto print_usage;
    } else if (!strcmp(argv[i], "-p") || !strcmp(argv[i], "--protocol")) {
      if (i++ < argc) {
        if (!strcmp(argv[i], "tcp") || !strcmp(argv[i], "TCP")) {
          g_use_udp = false;
        } else if (!strcmp(argv[i], "udp") || !strcmp(argv[i], "UDP")) {
          g_use_udp = true;
        } else {
          printf("Unrecognized protocol: %s\n", argv[i]);
          goto print_usage;
        }
      } else {
        printf("Not enough argument.\n");
        goto print_usage;
      }
    } else if (!strcmp(argv[i], "-i") || !strcmp(argv[i], "--ip")) {
      if (i++ < argc) {
        g_host_address = argv[i];
      } else {
        printf("Not enough argument.\n");
        goto print_usage;
      }
    } else if (i == (argc - 1)) {
      g_base_address = argv[i];
    }
    i++;
  }

  if (g_base_address.empty()) {
    goto print_usage;
  }

  return;

print_usage:
  printf("Usage: am_client [ -i ip ] [ -p port ] base_address", argv[0]);
  printf("\nOptions:");
  printf("\n  -h,--help                "
      "Display this information.");
  printf("\n  -p,--protocol <tcp|udp>  "
      "Use TCP or UDP protocol. Default = tcp.");
  printf("\n  -i,--ip <ip>             "
      "Set Asset Manager's host address. Default = 127.0.0.1");
  printf("\n");
  exit(0);
}

void ProcessInput(am::AssetManagerClient& am, const std::string& input)
{
  boost::char_separator<char> sep(" ");
  boost::tokenizer< boost::char_separator<char> > tok(input, sep);
  boost::tokenizer< boost::char_separator<char> >::iterator it = tok.begin();
  for (; it != tok.end(); ++it) {
    if (!it->compare("load")) {
      am.Load();
    } else if (!it->compare("unload")) {
      am.Unload();
    } else if (!it->compare("system_mute")) {
      if (++it == tok.end()) {
        goto missing_argument;
      } else if (!it->compare("true") || !it->compare("1")) {
        am.SetSystemMute(true);
      } else if (!it->compare("false") || !it->compare("0")) {
        am.SetSystemMute(false);
      } else {
        goto bad_argument;
      }
    } else if (!it->compare("system_volume")) {
      float volume;
      if (++it == tok.end()) {
        goto missing_argument;
      } else if (from_string<float>(volume, *it, std::dec)) {
        am.SetSystemVolume(volume);
      } else {
        goto bad_argument;
      }
    } else if (!it->compare("mute")) {
      if (++it == tok.end()) {
        goto missing_argument;
      } else if (!it->compare("true") || !it->compare("1")) {
        am.SetMute(true);
      } else if (!it->compare("false") || !it->compare("0")) {
        am.SetMute(false);
      } else {
        goto bad_argument;
      }
    } else if (!it->compare("volume")) {
      float volume;
      if (++it == tok.end()) {
        goto missing_argument;
      } else if (from_string<float>(volume, *it, std::dec)) {
        am.SetVolume(volume);
      } else {
        goto bad_argument;
      }
    } else if (!it->compare("help")) {
      std::cout << "load" << std::endl;
      std::cout << "unload" << std::endl;
      std::cout << "system_mute    true|1|false|0" << std::endl;
      std::cout << "system_volume  0-1" << std::endl;
      std::cout << "mute           true|1|false|0" << std::endl;
      std::cout << "volume         0-1" << std::endl;
    } else {
      std::cerr << "Unknown command: " << *it << "\n";
      break;
    }
  }

  return;

bad_argument:
  std::cerr << "Bad argument: " << *it << "\n";
  return;
missing_argument:
  std::cerr << "Missing argument \n";
}

void Signal(int what)
{
  g_continue = false;
  fclose(stdin);
}

<commit_msg>Attempt to fix "unload" not sent on Linux on exit<commit_after>// Copyright (C) 2011 by Toshiro Yamada
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <csignal>
#include <string>
#include <iostream>
#include <boost/tokenizer.hpp>
#include <boost/lexical_cast.hpp>

#include "asset_manager_client.hpp"

// global variables
std::string g_base_address = "";
bool g_use_udp = false;
std::string g_host_address = "127.0.0.1";
bool g_continue = true;

void ProcessArguments(int argc, const char* argv[]);
void ProcessInput(am::AssetManagerClient& am, const std::string& input);
void Signal(int what);

template <class T>
bool from_string(T& t,
    const std::string& s,
    std::ios_base& (*f)(std::ios_base&));

template <class T>
bool from_string(T& t,
    const std::string& s,
    std::ios_base& (*f)(std::ios_base&))
{
  std::istringstream iss(s);
  return !(iss >> f >> t).fail();
}

int main(int argc, const char* argv[])
{
  ProcessArguments(argc, argv);
  std::cout << "Using base address: " << g_base_address << "\n";
  std::cout << "Type \"help\" to list commands\n";

  am::AssetManagerClient am(g_base_address, g_host_address);
  if (g_use_udp) am.SetOption(am::AssetManagerClient::CORE_USE_UDP);
  am.SetOption(am::AssetManagerClient::SEND_UNLOAD_IN_DESTRUCTOR);

  signal(SIGINT, Signal);
#if !defined(_WIN32)
  signal(SIGQUIT, Signal);
#endif

  while (g_continue) {
    std::cout << "-> ";
    std::string input;
    std::getline(std::cin, input);
    if (std::cin.eof() || std::cin.fail()) break;
    ProcessInput(am, input);
  }

  fclose(stdin);
  return 0;
}

void ProcessArguments(int argc, const char* argv[])
{
  int i = 1;
  while (i < argc) {
    if (!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help")) {
      goto print_usage;
    } else if (!strcmp(argv[i], "-p") || !strcmp(argv[i], "--protocol")) {
      if (i++ < argc) {
        if (!strcmp(argv[i], "tcp") || !strcmp(argv[i], "TCP")) {
          g_use_udp = false;
        } else if (!strcmp(argv[i], "udp") || !strcmp(argv[i], "UDP")) {
          g_use_udp = true;
        } else {
          printf("Unrecognized protocol: %s\n", argv[i]);
          goto print_usage;
        }
      } else {
        printf("Not enough argument.\n");
        goto print_usage;
      }
    } else if (!strcmp(argv[i], "-i") || !strcmp(argv[i], "--ip")) {
      if (i++ < argc) {
        g_host_address = argv[i];
      } else {
        printf("Not enough argument.\n");
        goto print_usage;
      }
    } else if (i == (argc - 1)) {
      g_base_address = argv[i];
    }
    i++;
  }

  if (g_base_address.empty()) {
    goto print_usage;
  }

  return;

print_usage:
  printf("Usage: am_client [ -i ip ] [ -p port ] base_address", argv[0]);
  printf("\nOptions:");
  printf("\n  -h,--help                "
      "Display this information.");
  printf("\n  -p,--protocol <tcp|udp>  "
      "Use TCP or UDP protocol. Default = tcp.");
  printf("\n  -i,--ip <ip>             "
      "Set Asset Manager's host address. Default = 127.0.0.1");
  printf("\n");
  exit(0);
}

void ProcessInput(am::AssetManagerClient& am, const std::string& input)
{
  boost::char_separator<char> sep(" ");
  boost::tokenizer< boost::char_separator<char> > tok(input, sep);
  boost::tokenizer< boost::char_separator<char> >::iterator it = tok.begin();
  for (; it != tok.end(); ++it) {
    if (!it->compare("load")) {
      am.Load();
    } else if (!it->compare("unload")) {
      am.Unload();
    } else if (!it->compare("system_mute")) {
      if (++it == tok.end()) {
        goto missing_argument;
      } else if (!it->compare("true") || !it->compare("1")) {
        am.SetSystemMute(true);
      } else if (!it->compare("false") || !it->compare("0")) {
        am.SetSystemMute(false);
      } else {
        goto bad_argument;
      }
    } else if (!it->compare("system_volume")) {
      float volume;
      if (++it == tok.end()) {
        goto missing_argument;
      } else if (from_string<float>(volume, *it, std::dec)) {
        am.SetSystemVolume(volume);
      } else {
        goto bad_argument;
      }
    } else if (!it->compare("mute")) {
      if (++it == tok.end()) {
        goto missing_argument;
      } else if (!it->compare("true") || !it->compare("1")) {
        am.SetMute(true);
      } else if (!it->compare("false") || !it->compare("0")) {
        am.SetMute(false);
      } else {
        goto bad_argument;
      }
    } else if (!it->compare("volume")) {
      float volume;
      if (++it == tok.end()) {
        goto missing_argument;
      } else if (from_string<float>(volume, *it, std::dec)) {
        am.SetVolume(volume);
      } else {
        goto bad_argument;
      }
    } else if (!it->compare("help")) {
      std::cout << "load" << std::endl;
      std::cout << "unload" << std::endl;
      std::cout << "system_mute    true|1|false|0" << std::endl;
      std::cout << "system_volume  0-1" << std::endl;
      std::cout << "mute           true|1|false|0" << std::endl;
      std::cout << "volume         0-1" << std::endl;
    } else {
      std::cerr << "Unknown command: " << *it << "\n";
      break;
    }
  }

  return;

bad_argument:
  std::cerr << "Bad argument: " << *it << "\n";
  return;
missing_argument:
  std::cerr << "Missing argument \n";
}

void Signal(int what)
{
  g_continue = false;
}

<|endoftext|>


<commit_before>#include <QQuickWindow>

#include "myfilesavedialog.h"

MyFileSaveDialog::MyFileSaveDialog(QQuickItem *parent) :
    QQuickItem(parent)
  , m_modality(Qt::WindowModal)
  , m_options(QSharedPointer<QFileDialogOptions>(new QFileDialogOptions()))
{
    m_dlgHelper = init_helper();

    connect(m_dlgHelper, SIGNAL(accept()), this, SLOT(accept()));
    connect(m_dlgHelper, SIGNAL(reject()), this, SLOT(reject()));
}

MyFileSaveDialog::~MyFileSaveDialog()
{
    if (m_dlgHelper)
        m_dlgHelper->hide();
    delete m_dlgHelper;
}

QUrl MyFileSaveDialog::fileUrl() const
{
    return fileUrl_;
}

void MyFileSaveDialog::setFileUrl(QUrl fileUrl)
{
    if (fileUrl_ != fileUrl)
    {
        fileUrl_ = fileUrl;
        emit fileUrlChanged();
    }
}

QString MyFileSaveDialog::filename() const
{
    return filename_;
}

void MyFileSaveDialog::setFilename(QString filename)
{
    if (filename_ != filename)
    {
        filename_ = filename;
        emit filenameChanged();
    }
}

QString MyFileSaveDialog::title() const
{
    return title_;
}

void MyFileSaveDialog::setTitle(QString title)
{
    if (title_ != title)
    {
        title_ = title;
        emit titleChanged();
    }
}

QPlatformFileDialogHelper* MyFileSaveDialog::init_helper()
{
    m_dlgHelper = static_cast<QPlatformFileDialogHelper*>(QGuiApplicationPrivate::platformTheme()->createPlatformDialogHelper(QPlatformTheme::FileDialog));
    if (!m_dlgHelper)
        return NULL;

    return m_dlgHelper;
}

void MyFileSaveDialog::open()
{
    QQuickItem *me = this;
    Q_ASSERT(me);

    QQuickItem *parent = me->parentItem();
    Q_ASSERT(parent);

    QQuickWindow *window = parent->window();
    Q_ASSERT(window);

    m_parentWindow = window;

    m_options->setFileMode(QFileDialogOptions::AnyFile);
    m_options->setAcceptMode(QFileDialogOptions::AcceptSave);
    m_options->setWindowTitle(title());

    QString homePath = QDir::homePath();
#if (QT_VERSION >= QT_VERSION_CHECK(5, 2, 0))
    QUrl homeUrl = QUrl::fromLocalFile(homePath);
    m_dlgHelper->setDirectory(homeUrl);
#else
    m_dlgHelper->setDirectory(homePath);
#endif

#ifndef Q_OS_LINUX
    #if (QT_VERSION >= QT_VERSION_CHECK(5, 2, 0))
        m_dlgHelper->selectFile(QUrl(filename()));
    #else
        m_dlgHelper->selectFile(filename());
    #endif
#endif

    m_dlgHelper->setOptions(m_options);
    m_dlgHelper->setFilter(); // applyOptions();

    Qt::WindowFlags flags = Qt::Dialog;
    if (!title().isEmpty()) flags |= Qt::WindowTitleHint;

    m_visible = m_dlgHelper->show(flags, m_modality, m_parentWindow);
}

void MyFileSaveDialog::close()
{
    m_dlgHelper->hide();
    m_visible = false;
}

void MyFileSaveDialog::accept()
{
    m_dlgHelper->hide();

#if (QT_VERSION >= QT_VERSION_CHECK(5, 2, 0))
    QList<QUrl> selectedUrls = m_dlgHelper->selectedFiles();
    if ( selectedUrls.count() )
    {
        setFileUrl(selectedUrls.at(0));
    }
#else
    QStringList selectedFiles = m_dlgHelper->selectedFiles();
    if ( selectedFiles.count() )
    {
        setFileUrl(QUrl::fromLocalFile(selectedFiles.at(0)));
    }
#endif

    emit accepted();
}

void MyFileSaveDialog::reject()
{
    m_dlgHelper->hide();
    emit rejected();
}
<commit_msg>Add Qt version debug output (Qt 5.1/Qt 5.2)<commit_after>#include <QQuickWindow>
#include <QDebug>

#include "myfilesavedialog.h"

MyFileSaveDialog::MyFileSaveDialog(QQuickItem *parent) :
    QQuickItem(parent)
  , m_modality(Qt::WindowModal)
  , m_options(QSharedPointer<QFileDialogOptions>(new QFileDialogOptions()))
{
#if (QT_VERSION >= QT_VERSION_CHECK(5, 2, 0))
    qDebug() << "Working with Qt 5.2";
#else
    qDebug() << "Working with Qt 5.1";
#endif

    m_dlgHelper = init_helper();

    connect(m_dlgHelper, SIGNAL(accept()), this, SLOT(accept()));
    connect(m_dlgHelper, SIGNAL(reject()), this, SLOT(reject()));
}

MyFileSaveDialog::~MyFileSaveDialog()
{
    if (m_dlgHelper)
        m_dlgHelper->hide();
    delete m_dlgHelper;
}

QUrl MyFileSaveDialog::fileUrl() const
{
    return fileUrl_;
}

void MyFileSaveDialog::setFileUrl(QUrl fileUrl)
{
    if (fileUrl_ != fileUrl)
    {
        fileUrl_ = fileUrl;
        emit fileUrlChanged();
    }
}

QString MyFileSaveDialog::filename() const
{
    return filename_;
}

void MyFileSaveDialog::setFilename(QString filename)
{
    if (filename_ != filename)
    {
        filename_ = filename;
        emit filenameChanged();
    }
}

QString MyFileSaveDialog::title() const
{
    return title_;
}

void MyFileSaveDialog::setTitle(QString title)
{
    if (title_ != title)
    {
        title_ = title;
        emit titleChanged();
    }
}

QPlatformFileDialogHelper* MyFileSaveDialog::init_helper()
{
    m_dlgHelper = static_cast<QPlatformFileDialogHelper*>(QGuiApplicationPrivate::platformTheme()->createPlatformDialogHelper(QPlatformTheme::FileDialog));
    if (!m_dlgHelper)
        return NULL;

    return m_dlgHelper;
}

void MyFileSaveDialog::open()
{
    QQuickItem *me = this;
    Q_ASSERT(me);

    QQuickItem *parent = me->parentItem();
    Q_ASSERT(parent);

    QQuickWindow *window = parent->window();
    Q_ASSERT(window);

    m_parentWindow = window;

    m_options->setFileMode(QFileDialogOptions::AnyFile);
    m_options->setAcceptMode(QFileDialogOptions::AcceptSave);
    m_options->setWindowTitle(title());

    QString homePath = QDir::homePath();
#if (QT_VERSION >= QT_VERSION_CHECK(5, 2, 0))
    QUrl homeUrl = QUrl::fromLocalFile(homePath);
    m_dlgHelper->setDirectory(homeUrl);
#else
    m_dlgHelper->setDirectory(homePath);
#endif

#ifndef Q_OS_LINUX
    #if (QT_VERSION >= QT_VERSION_CHECK(5, 2, 0))
        m_dlgHelper->selectFile(QUrl(filename()));
    #else
        m_dlgHelper->selectFile(filename());
    #endif
#endif

    m_dlgHelper->setOptions(m_options);
    m_dlgHelper->setFilter(); // applyOptions();

    Qt::WindowFlags flags = Qt::Dialog;
    if (!title().isEmpty()) flags |= Qt::WindowTitleHint;

    m_visible = m_dlgHelper->show(flags, m_modality, m_parentWindow);
}

void MyFileSaveDialog::close()
{
    m_dlgHelper->hide();
    m_visible = false;
}

void MyFileSaveDialog::accept()
{
    m_dlgHelper->hide();

#if (QT_VERSION >= QT_VERSION_CHECK(5, 2, 0))
    QList<QUrl> selectedUrls = m_dlgHelper->selectedFiles();
    if ( selectedUrls.count() )
    {
        setFileUrl(selectedUrls.at(0));
    }
#else
    QStringList selectedFiles = m_dlgHelper->selectedFiles();
    if ( selectedFiles.count() )
    {
        setFileUrl(QUrl::fromLocalFile(selectedFiles.at(0)));
    }
#endif

    emit accepted();
}

void MyFileSaveDialog::reject()
{
    m_dlgHelper->hide();
    emit rejected();
}
<|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 "flutter/flow/layers/picture_layer.h"

#include "flutter/flow/raster_cache.h"
#include "lib/ftl/logging.h"

namespace flow {

PictureLayer::PictureLayer() {}

PictureLayer::~PictureLayer() {}

void PictureLayer::Preroll(PrerollContext* context, const SkMatrix& matrix) {
  image_ = context->raster_cache.GetPrerolledImage(
      context->gr_context, picture_.get(), matrix, is_complex_, will_change_);
  context->child_paint_bounds =
      picture_->cullRect().makeOffset(offset_.x(), offset_.y());
}

void PictureLayer::Paint(PaintContext& context) {
  FTL_DCHECK(picture_);

  TRACE_EVENT1("flutter", "PictureLayer::Paint", "image",
               image_ ? "prerolled" : "normal");

  SkAutoCanvasRestore save(&context.canvas, true);
  context.canvas.translate(offset_.x(), offset_.y());

  if (image_) {
    context.canvas.drawImage(image_.get(), 0, 0);
  } else {
    context.canvas.drawPicture(picture_.get());
  }
}

}  // namespace flow
<commit_msg>Scale picture layers to the picture's cull rect (#2967)<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 "flutter/flow/layers/picture_layer.h"

#include "flutter/flow/raster_cache.h"
#include "lib/ftl/logging.h"

namespace flow {

PictureLayer::PictureLayer() {}

PictureLayer::~PictureLayer() {}

void PictureLayer::Preroll(PrerollContext* context, const SkMatrix& matrix) {
  image_ = context->raster_cache.GetPrerolledImage(
      context->gr_context, picture_.get(), matrix, is_complex_, will_change_);
  context->child_paint_bounds =
      picture_->cullRect().makeOffset(offset_.x(), offset_.y());
}

void PictureLayer::Paint(PaintContext& context) {
  FTL_DCHECK(picture_);

  TRACE_EVENT1("flutter", "PictureLayer::Paint", "image",
               image_ ? "prerolled" : "normal");

  SkAutoCanvasRestore save(&context.canvas, true);
  context.canvas.translate(offset_.x(), offset_.y());

  if (image_) {
    context.canvas.drawImageRect(image_.get(), picture_->cullRect(), nullptr,
                                 SkCanvas::kFast_SrcRectConstraint);
  } else {
    context.canvas.drawPicture(picture_.get());
  }
}

}  // namespace flow
<|endoftext|>


<commit_before>/*-
 * SPDX-License-Identifier: BSD-2-Clause
 *
 * Copyright (c) 2021 NKI/AVL, Netherlands Cancer Institute
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#define BOOST_TEST_ALTERNATIVE_INIT_API
#include <boost/test/included/unit_test.hpp>

#include <stdexcept>

#include "cif++/Cif++.hpp"
#include "cif++/Structure.hpp"

// --------------------------------------------------------------------

cif::File operator""_cf(const char* text, size_t length)
{
    struct membuf : public std::streambuf
    {
        membuf(char* text, size_t length)
        {
            this->setg(text, text, text + length);
        }
    } buffer(const_cast<char*>(text), length);

    std::istream is(&buffer);
    return cif::File(is);
}

// --------------------------------------------------------------------

std::filesystem::path gTestDir = std::filesystem::current_path();

bool init_unit_test()
{
    cif::VERBOSE = 1;

	// not a test, just initialize test dir
	if (boost::unit_test::framework::master_test_suite().argc == 2)
		gTestDir = boost::unit_test::framework::master_test_suite().argv[1];

	// do this now, avoids the need for installing
	cif::addFileResource("mmcif_pdbx_v50.dic", gTestDir / ".." / "rsrc" / "mmcif_pdbx_v50.dic");

	// initialize CCD location
	cif::addFileResource("components.cif", gTestDir / ".." / "data" / "ccd-subset.cif");

	mmcif::CompoundFactory::instance().pushDictionary(gTestDir / "HEM.cif");

	return true;
}

// --------------------------------------------------------------------

BOOST_AUTO_TEST_CASE(create_nonpoly_1)
{
    cif::VERBOSE = 1;

	mmcif::File file;
	file.loadDictionary("mmcif_pdbx_v50.dic");
	file.emplace("TEST");	// create a datablock

	mmcif::Structure structure(file);

	std::string entity_id = structure.createNonPolyEntity("HEM");

	auto atoms = R"(
data_HEM
loop_
_atom_site.group_PDB
_atom_site.type_symbol
_atom_site.label_atom_id
_atom_site.label_alt_id
_atom_site.pdbx_PDB_ins_code
_atom_site.Cartn_x
_atom_site.Cartn_y
_atom_site.Cartn_z
_atom_site.occupancy
_atom_site.B_iso_or_equiv
_atom_site.pdbx_formal_charge
HETATM C  CHA . ? -5.248  39.769 -0.250  1.00 7.67  ?
HETATM C  CHB . ? -3.774  36.790 3.280   1.00 7.05  ?
HETATM C  CHC . ? -2.879  33.328 0.013   1.00 7.69  ?
HETATM C  CHD . ? -4.342  36.262 -3.536  1.00 8.00  ?
# that's enough to test with
)"_cf;

	auto &hem_data = atoms["HEM"];
	auto &atom_site = hem_data["atom_site"];

	auto hem_atoms = atom_site.rows();
	std::vector<mmcif::Atom> atom_data;
	for (auto &hem_atom: hem_atoms)
		atom_data.emplace_back(hem_data, hem_atom);

	structure.createNonpoly(entity_id, atom_data);

	auto expected = R"(
data_TEST
#
_pdbx_nonpoly_scheme.asym_id         A
_pdbx_nonpoly_scheme.ndb_seq_num     1
_pdbx_nonpoly_scheme.entity_id       1
_pdbx_nonpoly_scheme.mon_id          HEM
_pdbx_nonpoly_scheme.pdb_seq_num     1
_pdbx_nonpoly_scheme.auth_seq_num    1
_pdbx_nonpoly_scheme.pdb_mon_id      HEM
_pdbx_nonpoly_scheme.auth_mon_id     HEM
_pdbx_nonpoly_scheme.pdb_strand_id   A
_pdbx_nonpoly_scheme.pdb_ins_code    .
#
loop_
_atom_site.id
_atom_site.auth_asym_id
_atom_site.label_alt_id
_atom_site.label_asym_id
_atom_site.label_atom_id
_atom_site.label_comp_id
_atom_site.label_entity_id
_atom_site.label_seq_id
_atom_site.type_symbol
_atom_site.group_PDB
_atom_site.pdbx_PDB_ins_code
_atom_site.Cartn_x
_atom_site.Cartn_y
_atom_site.Cartn_z
_atom_site.occupancy
_atom_site.B_iso_or_equiv
_atom_site.pdbx_formal_charge
_atom_site.auth_seq_id
_atom_site.auth_comp_id
_atom_site.auth_atom_id
_atom_site.pdbx_PDB_model_num
1 A ? A CHA HEM 1 . C HETATM ? -5.248 39.769 -0.250 1.00 7.67 ? 1 HEM CHA 1
2 A ? A CHB HEM 1 . C HETATM ? -3.774 36.790 3.280  1.00 7.05 ? 1 HEM CHB 1
3 A ? A CHC HEM 1 . C HETATM ? -2.879 33.328 0.013  1.00 7.69 ? 1 HEM CHC 1
4 A ? A CHD HEM 1 . C HETATM ? -4.342 36.262 -3.536 1.00 8.00 ? 1 HEM CHD 1
#
_chem_comp.id               HEM
_chem_comp.type             NON-POLYMER
_chem_comp.name             'PROTOPORPHYRIN IX CONTAINING FE'
_chem_comp.formula          'C34 H32 Fe N4 O4'
_chem_comp.formula_weight   616.487000
#
_pdbx_entity_nonpoly.entity_id   1
_pdbx_entity_nonpoly.name        'PROTOPORPHYRIN IX CONTAINING FE'
_pdbx_entity_nonpoly.comp_id     HEM
#
_entity.id                 1
_entity.type               non-polymer
_entity.pdbx_description   'PROTOPORPHYRIN IX CONTAINING FE'
_entity.formula_weight     616.487000
#
_struct_asym.id                            A
_struct_asym.entity_id                     1
_struct_asym.pdbx_blank_PDB_chainid_flag   N
_struct_asym.pdbx_modified                 N
_struct_asym.details                       ?
#
)"_cf;

	expected.loadDictionary("mmcif_pdbx_v50.dic");

	if (not (expected.firstDatablock() == structure.datablock()))
	{
		BOOST_TEST(false);
		std::cout << expected.firstDatablock() << std::endl
				<< std::endl
				<< structure.datablock() << std::endl;
	}
}

// // --------------------------------------------------------------------

// BOOST_AUTO_TEST_CASE(test_load_1)
// {
// 	mmcif::File cf(gTestDir / "5v3g.cif.gz");
// 	mmcif::Structure s(cf);

// 	for (auto &poly : s.polymers())
// 	{
// 		std::cout << std::string(80, '=') << std::endl;
// 		for (auto &res : poly)
// 		{
// 			std::cout << res << std::endl;

// 			for (auto &atom : res.atoms())
// 				std::cout << "  " << atom << std::endl;
// 		}
// 	}
// }
<commit_msg>Add test for loading<commit_after>/*-
 * SPDX-License-Identifier: BSD-2-Clause
 *
 * Copyright (c) 2021 NKI/AVL, Netherlands Cancer Institute
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#define BOOST_TEST_ALTERNATIVE_INIT_API
#include <boost/test/included/unit_test.hpp>

#include <stdexcept>

#include "cif++/Cif++.hpp"
#include "cif++/Structure.hpp"

// --------------------------------------------------------------------

cif::File operator""_cf(const char* text, size_t length)
{
    struct membuf : public std::streambuf
    {
        membuf(char* text, size_t length)
        {
            this->setg(text, text, text + length);
        }
    } buffer(const_cast<char*>(text), length);

    std::istream is(&buffer);
    return cif::File(is);
}

// --------------------------------------------------------------------

std::filesystem::path gTestDir = std::filesystem::current_path();

bool init_unit_test()
{
    cif::VERBOSE = 1;

	// not a test, just initialize test dir
	if (boost::unit_test::framework::master_test_suite().argc == 2)
		gTestDir = boost::unit_test::framework::master_test_suite().argv[1];

	// do this now, avoids the need for installing
	cif::addFileResource("mmcif_pdbx_v50.dic", gTestDir / ".." / "rsrc" / "mmcif_pdbx_v50.dic");

	// initialize CCD location
	cif::addFileResource("components.cif", gTestDir / ".." / "data" / "ccd-subset.cif");

	mmcif::CompoundFactory::instance().pushDictionary(gTestDir / "HEM.cif");

	return true;
}

// --------------------------------------------------------------------

BOOST_AUTO_TEST_CASE(create_nonpoly_1)
{
    cif::VERBOSE = 1;

	mmcif::File file;
	file.loadDictionary("mmcif_pdbx_v50.dic");
	file.emplace("TEST");	// create a datablock

	mmcif::Structure structure(file);

	std::string entity_id = structure.createNonPolyEntity("HEM");

	auto atoms = R"(
data_HEM
loop_
_atom_site.group_PDB
_atom_site.type_symbol
_atom_site.label_atom_id
_atom_site.label_alt_id
_atom_site.pdbx_PDB_ins_code
_atom_site.Cartn_x
_atom_site.Cartn_y
_atom_site.Cartn_z
_atom_site.occupancy
_atom_site.B_iso_or_equiv
_atom_site.pdbx_formal_charge
HETATM C  CHA . ? -5.248  39.769 -0.250  1.00 7.67  ?
HETATM C  CHB . ? -3.774  36.790 3.280   1.00 7.05  ?
HETATM C  CHC . ? -2.879  33.328 0.013   1.00 7.69  ?
HETATM C  CHD . ? -4.342  36.262 -3.536  1.00 8.00  ?
# that's enough to test with
)"_cf;

	auto &hem_data = atoms["HEM"];
	auto &atom_site = hem_data["atom_site"];

	auto hem_atoms = atom_site.rows();
	std::vector<mmcif::Atom> atom_data;
	for (auto &hem_atom: hem_atoms)
		atom_data.emplace_back(hem_data, hem_atom);

	structure.createNonpoly(entity_id, atom_data);

	auto expected = R"(
data_TEST
#
_pdbx_nonpoly_scheme.asym_id         A
_pdbx_nonpoly_scheme.ndb_seq_num     1
_pdbx_nonpoly_scheme.entity_id       1
_pdbx_nonpoly_scheme.mon_id          HEM
_pdbx_nonpoly_scheme.pdb_seq_num     1
_pdbx_nonpoly_scheme.auth_seq_num    1
_pdbx_nonpoly_scheme.pdb_mon_id      HEM
_pdbx_nonpoly_scheme.auth_mon_id     HEM
_pdbx_nonpoly_scheme.pdb_strand_id   A
_pdbx_nonpoly_scheme.pdb_ins_code    .
#
loop_
_atom_site.id
_atom_site.auth_asym_id
_atom_site.label_alt_id
_atom_site.label_asym_id
_atom_site.label_atom_id
_atom_site.label_comp_id
_atom_site.label_entity_id
_atom_site.label_seq_id
_atom_site.type_symbol
_atom_site.group_PDB
_atom_site.pdbx_PDB_ins_code
_atom_site.Cartn_x
_atom_site.Cartn_y
_atom_site.Cartn_z
_atom_site.occupancy
_atom_site.B_iso_or_equiv
_atom_site.pdbx_formal_charge
_atom_site.auth_seq_id
_atom_site.auth_comp_id
_atom_site.auth_atom_id
_atom_site.pdbx_PDB_model_num
1 A ? A CHA HEM 1 . C HETATM ? -5.248 39.769 -0.250 1.00 7.67 ? 1 HEM CHA 1
2 A ? A CHB HEM 1 . C HETATM ? -3.774 36.790 3.280  1.00 7.05 ? 1 HEM CHB 1
3 A ? A CHC HEM 1 . C HETATM ? -2.879 33.328 0.013  1.00 7.69 ? 1 HEM CHC 1
4 A ? A CHD HEM 1 . C HETATM ? -4.342 36.262 -3.536 1.00 8.00 ? 1 HEM CHD 1
#
_chem_comp.id               HEM
_chem_comp.type             NON-POLYMER
_chem_comp.name             'PROTOPORPHYRIN IX CONTAINING FE'
_chem_comp.formula          'C34 H32 Fe N4 O4'
_chem_comp.formula_weight   616.487000
#
_pdbx_entity_nonpoly.entity_id   1
_pdbx_entity_nonpoly.name        'PROTOPORPHYRIN IX CONTAINING FE'
_pdbx_entity_nonpoly.comp_id     HEM
#
_entity.id                 1
_entity.type               non-polymer
_entity.pdbx_description   'PROTOPORPHYRIN IX CONTAINING FE'
_entity.formula_weight     616.487000
#
_struct_asym.id                            A
_struct_asym.entity_id                     1
_struct_asym.pdbx_blank_PDB_chainid_flag   N
_struct_asym.pdbx_modified                 N
_struct_asym.details                       ?
#
)"_cf;

	expected.loadDictionary("mmcif_pdbx_v50.dic");

	if (not (expected.firstDatablock() == structure.datablock()))
	{
		BOOST_TEST(false);
		std::cout << expected.firstDatablock() << std::endl
				<< std::endl
				<< structure.datablock() << std::endl;
	}
}

// --------------------------------------------------------------------

BOOST_AUTO_TEST_CASE(test_load_1)
{
	using namespace cif::literals;

	const std::filesystem::path example(gTestDir / ".." / "examples" / "1cbs.cif.gz");
	mmcif::File file(example.string());

	auto &db = file.data();

	mmcif::Structure s(file);

	BOOST_CHECK(s.polymers().size() == 1);

	auto &pdbx_poly_seq_scheme = db["pdbx_poly_seq_scheme"];

	for (auto &poly : s.polymers())
	{
		BOOST_CHECK_EQUAL(poly.size(), pdbx_poly_seq_scheme.find("asym_id"_key == poly.asymID()).size());
	}
}
<|endoftext|>


<commit_before><commit_msg>tried E3.cpp to 'E'<commit_after><|endoftext|>


<commit_before><commit_msg>FHE parameter for Chi2<commit_after><|endoftext|>


<commit_before>#include "depthai/depthai.hpp"

int main(int argc, char** argv) {
    bool res = false;
    dai::DeviceInfo info;
    std::tie(res, info) = dai::DeviceBootloader::getFirstAvailableDevice();
    std::string path;

    if(res) {
        std::cout << "Found device with name: " << info.desc.name << std::endl;
        dai::DeviceBootloader bl(info, path);
        std::cout << "Version: " << bl.getVersion().toString() << std::endl;
    } else {
        std::cout << "No devices found" << std::endl;
    }

    return 0;
}<commit_msg>Fix bootloader version example<commit_after>#include "depthai/depthai.hpp"

int main(int argc, char** argv) {
    bool res = false;
    dai::DeviceInfo info;
    std::tie(res, info) = dai::DeviceBootloader::getFirstAvailableDevice();

    if(res) {
        std::cout << "Found device with name: " << info.desc.name << std::endl;
        dai::DeviceBootloader bl(info);
        std::cout << "Version: " << bl.getVersion().toString() << std::endl;
    } else {
        std::cout << "No devices found" << std::endl;
    }

    return 0;
}<|endoftext|>


<commit_before>#include <iostream>
#include <typeinfo>

#include "viennagrid/config/default_configs.hpp"
#include "viennagrid/mesh/element_creation.hpp"
#include "viennagrid/mesh/element_deletion.hpp"
#include "viennagrid/mesh/coboundary_iteration.hpp"
#include "viennagrid/io/vtk_writer.hpp"

int main()
{
    typedef viennagrid::triangular_2d_mesh MeshType;
    typedef viennagrid::triangular_2d_segmentation SegmentationType;
    typedef viennagrid::triangular_2d_segment_handle SegmentHandleType;

    typedef viennagrid::result_of::point<MeshType>::type point_type;

    typedef viennagrid::result_of::vertex_handle<MeshType>::type VertexHandleType;
//     typedef viennagrid::result_of::vertex<MeshType>::type vertex_type;

//     typedef viennagrid::result_of::line<MeshType>::type line_type;

//     typedef viennagrid::result_of::triangle_handle<MeshType>::type TriangleHandleType;
//     typedef viennagrid::result_of::triangle<MeshType>::type triangle_type;

    MeshType mesh;
    SegmentationType segmentation(mesh);

    VertexHandleType v00 = viennagrid::make_vertex(mesh, point_type(0.0, 0.0));
    VertexHandleType v10 = viennagrid::make_vertex(mesh, point_type(1.0, 0.0));
    VertexHandleType v20 = viennagrid::make_vertex(mesh, point_type(2.0, 0.0));
    VertexHandleType v01 = viennagrid::make_vertex(mesh, point_type(0.0, 1.0));
    VertexHandleType v11 = viennagrid::make_vertex(mesh, point_type(1.0, 1.0));
    VertexHandleType v21 = viennagrid::make_vertex(mesh, point_type(2.0, 1.0));
    VertexHandleType v02 = viennagrid::make_vertex(mesh, point_type(0.0, 2.0));
    VertexHandleType v12 = viennagrid::make_vertex(mesh, point_type(1.0, 2.0));
    VertexHandleType v22 = viennagrid::make_vertex(mesh, point_type(2.0, 2.0));

    viennagrid::make_triangle(mesh, v00, v01, v11);
    viennagrid::make_triangle(mesh, v00, v10, v11);
    viennagrid::make_triangle(mesh, v10, v11, v20);
    viennagrid::make_triangle(mesh, v11, v20, v21);
    viennagrid::make_triangle(mesh, v11, v21, v22);
    viennagrid::make_triangle(mesh, v12, v11, v22);
    viennagrid::make_triangle(mesh, v02, v11, v12);
    viennagrid::make_triangle(mesh, v01, v11, v02);

    typedef viennagrid::result_of::triangle_range<MeshType>::type triangle_range_type;
    typedef viennagrid::result_of::iterator<triangle_range_type>::type triangle_range_iterator;

    std::cout << viennagrid::triangles(mesh).size() << std::endl;

    typedef viennagrid::result_of::mesh_view<MeshType>::type mesh_view_type;
    mesh_view_type elements_to_erase = viennagrid::make_view(mesh);
    viennagrid::mark_erase_elements( mesh, elements_to_erase, v22 );
    viennagrid::mark_erase_elements( mesh, elements_to_erase, v21 );

    viennagrid::erase_elements(mesh, elements_to_erase);

    std::cout << viennagrid::triangles(mesh).size() << std::endl;

    {
        viennagrid::io::vtk_writer<viennagrid::triangular_2d_mesh> vtk_writer;
        vtk_writer(mesh, "triangle_mesh");
    }

    return 0;
}
<commit_msg>Code cleanup<commit_after>#include <iostream>
#include <typeinfo>

#include "viennagrid/config/default_configs.hpp"
#include "viennagrid/mesh/element_creation.hpp"
#include "viennagrid/mesh/element_deletion.hpp"
#include "viennagrid/mesh/coboundary_iteration.hpp"
#include "viennagrid/io/vtk_writer.hpp"

int main()
{
    typedef viennagrid::triangular_2d_mesh MeshType;

    typedef viennagrid::result_of::point<MeshType>::type point_type;

    typedef viennagrid::result_of::vertex_handle<MeshType>::type VertexHandleType;

    MeshType mesh;

    VertexHandleType v00 = viennagrid::make_vertex(mesh, point_type(0.0, 0.0));
    VertexHandleType v10 = viennagrid::make_vertex(mesh, point_type(1.0, 0.0));
    VertexHandleType v20 = viennagrid::make_vertex(mesh, point_type(2.0, 0.0));
    VertexHandleType v01 = viennagrid::make_vertex(mesh, point_type(0.0, 1.0));
    VertexHandleType v11 = viennagrid::make_vertex(mesh, point_type(1.0, 1.0));
    VertexHandleType v21 = viennagrid::make_vertex(mesh, point_type(2.0, 1.0));
    VertexHandleType v02 = viennagrid::make_vertex(mesh, point_type(0.0, 2.0));
    VertexHandleType v12 = viennagrid::make_vertex(mesh, point_type(1.0, 2.0));
    VertexHandleType v22 = viennagrid::make_vertex(mesh, point_type(2.0, 2.0));

    viennagrid::make_triangle(mesh, v00, v01, v11);
    viennagrid::make_triangle(mesh, v00, v10, v11);
    viennagrid::make_triangle(mesh, v10, v11, v20);
    viennagrid::make_triangle(mesh, v11, v20, v21);
    viennagrid::make_triangle(mesh, v11, v21, v22);
    viennagrid::make_triangle(mesh, v12, v11, v22);
    viennagrid::make_triangle(mesh, v02, v11, v12);
    viennagrid::make_triangle(mesh, v01, v11, v02);

    typedef viennagrid::result_of::triangle_range<MeshType>::type triangle_range_type;
    typedef viennagrid::result_of::iterator<triangle_range_type>::type triangle_range_iterator;

    std::cout << viennagrid::triangles(mesh).size() << std::endl;

    typedef viennagrid::result_of::mesh_view<MeshType>::type mesh_view_type;
    mesh_view_type elements_to_erase = viennagrid::make_view(mesh);
    viennagrid::mark_erase_elements( mesh, elements_to_erase, v22 );
    viennagrid::mark_erase_elements( mesh, elements_to_erase, v21 );

    viennagrid::erase_elements(mesh, elements_to_erase);

    std::cout << viennagrid::triangles(mesh).size() << std::endl;

    {
        viennagrid::io::vtk_writer<viennagrid::triangular_2d_mesh> vtk_writer;
        vtk_writer(mesh, "triangle_mesh");
    }

    return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/browser/window_list.h"

#include <algorithm>

#include "atom/browser/native_window.h"
#include "atom/browser/window_list_observer.h"
#include "base/logging.h"

namespace atom {

// static
base::LazyInstance<base::ObserverList<WindowListObserver>>::Leaky
    WindowList::observers_ = LAZY_INSTANCE_INITIALIZER;

// static
WindowList* WindowList::instance_ = nullptr;

// static
WindowList* WindowList::GetInstance() {
  if (!instance_)
    instance_ = new WindowList;
  return instance_;
}

// static
void WindowList::AddWindow(NativeWindow* window) {
  DCHECK(window);
  // Push |window| on the appropriate list instance.
  WindowVector& windows = GetInstance()->windows_;
  windows.push_back(window);

  for (WindowListObserver& observer : observers_)
    observer.OnWindowAdded(window);
}

// static
void WindowList::RemoveWindow(NativeWindow* window) {
  WindowVector& windows = GetInstance()->windows_;
  windows.erase(std::remove(windows.begin(), windows.end(), window),
                windows.end());

  for (WindowListObserver& observer : observers_)
    observer.OnWindowRemoved(window);

  if (windows.size() == 0)
    for (WindowListObserver& observer : observers_)
      observer.OnWindowAllClosed();
}

// static
void WindowList::WindowCloseCancelled(NativeWindow* window) {
  for (WindowListObserver& observer : observers_)
    observer.OnWindowCloseCancelled(window);
}

// static
void WindowList::AddObserver(WindowListObserver* observer) {
  observers_.Get().AddObserver(observer);
}

// static
void WindowList::RemoveObserver(WindowListObserver* observer) {
  observers_.Get().RemoveObserver(observer);
}

// static
void WindowList::CloseAllWindows() {
  WindowVector windows = GetInstance()->windows_;
  for (const auto& window : windows)
    window->Close();
}

WindowList::WindowList() {
}

WindowList::~WindowList() {
}

}  // namespace atom
<commit_msg>Fix LazyInstance error of df0a3c68a4eaee82bee2539cf419c2d0e17be79e<commit_after>// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.

#include "atom/browser/window_list.h"

#include <algorithm>

#include "atom/browser/native_window.h"
#include "atom/browser/window_list_observer.h"
#include "base/logging.h"

namespace atom {

// static
base::LazyInstance<base::ObserverList<WindowListObserver>>::Leaky
    WindowList::observers_ = LAZY_INSTANCE_INITIALIZER;

// static
WindowList* WindowList::instance_ = nullptr;

// static
WindowList* WindowList::GetInstance() {
  if (!instance_)
    instance_ = new WindowList;
  return instance_;
}

// static
void WindowList::AddWindow(NativeWindow* window) {
  DCHECK(window);
  // Push |window| on the appropriate list instance.
  WindowVector& windows = GetInstance()->windows_;
  windows.push_back(window);

  for (WindowListObserver& observer : observers_.Get())
    observer.OnWindowAdded(window);
}

// static
void WindowList::RemoveWindow(NativeWindow* window) {
  WindowVector& windows = GetInstance()->windows_;
  windows.erase(std::remove(windows.begin(), windows.end(), window),
                windows.end());

  for (WindowListObserver& observer : observers_.Get())
    observer.OnWindowRemoved(window);

  if (windows.size() == 0)
    for (WindowListObserver& observer : observers_.Get())
      observer.OnWindowAllClosed();
}

// static
void WindowList::WindowCloseCancelled(NativeWindow* window) {
  for (WindowListObserver& observer : observers_.Get())
    observer.OnWindowCloseCancelled(window);
}

// static
void WindowList::AddObserver(WindowListObserver* observer) {
  observers_.Get().AddObserver(observer);
}

// static
void WindowList::RemoveObserver(WindowListObserver* observer) {
  observers_.Get().RemoveObserver(observer);
}

// static
void WindowList::CloseAllWindows() {
  WindowVector windows = GetInstance()->windows_;
  for (const auto& window : windows)
    window->Close();
}

WindowList::WindowList() {
}

WindowList::~WindowList() {
}

}  // namespace atom
<|endoftext|>


<commit_before>/*
 * Unit tests for libkvkontakte.
 * Copyright (C) 2015  Alexander Potashev <aspotashev@gmail.com>
 *
 * 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.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include "test_userinfo.h"
#include "vkapi.h"

#include <libkvkontakte/userinfofulljob.h>

#include <qtest_kde.h>

#include <QtCore/QList>
#include <QtGui/QMainWindow>

#define VK_APP_ID   "2446321"

using namespace Vkontakte;

TestUserInfo::TestUserInfo()
    : m_vkapi(0)
{
}

void TestUserInfo::initTestCase()
{
    QMainWindow *parentWidget = new QMainWindow();

    m_vkapi = new KIPIVkontaktePlugin::VkAPI(parentWidget);
    m_vkapi->setAppId(VK_APP_ID); // TODO: library should better not crash if setAppId is not called
    m_vkapi->startAuthentication(false);

    // Wait for authentication
    QEventLoop loop;
    // TODO: Wait for any outcome of the authentication process, including failure
    connect(m_vkapi, SIGNAL(authenticated()), &loop, SLOT(quit()));
    loop.exec();

    QVERIFY(m_vkapi->isAuthenticated());
}

void TestUserInfo::testUserInfoJob()
{
    Vkontakte::UserInfoJob* const job = new Vkontakte::UserInfoJob(
        m_vkapi->accessToken(), 1);

    job->exec();

    QList<UserInfoPtr> res = job->userInfo();
    QCOMPARE(res.size(), 1);

    UserInfoPtr user = res.first();
    QCOMPARE(user->domain(), QString("durov"));
    QCOMPARE(user->firstName(), QString::fromUtf8("Павел"));
}

void TestUserInfo::testUserInfoFullJob()
{
    Vkontakte::UserInfoFullJob* const job = new Vkontakte::UserInfoFullJob(
        m_vkapi->accessToken(), 1, true, true);

    job->exec();

    QList<UserInfoPtr> res = job->userInfo();
    QCOMPARE(res.size(), 1);

    UserInfoPtr user = res.first();
    QCOMPARE(user->domain(), QString("durov"));
    QCOMPARE(user->firstName(), QString::fromUtf8("Павел"));
    QCOMPARE(user->countryString(), QString::fromUtf8("Россия"));
    QCOMPARE(user->cityString(), QString::fromUtf8("Санкт-Петербург"));
}

QTEST_KDEMAIN(TestUserInfo, GUI)
#include "test_userinfo.moc"
<commit_msg>autotests: VkAPI does not need a parent widget<commit_after>/*
 * Unit tests for libkvkontakte.
 * Copyright (C) 2015  Alexander Potashev <aspotashev@gmail.com>
 *
 * 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.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include "test_userinfo.h"
#include "vkapi.h"

#include <libkvkontakte/userinfofulljob.h>

#include <qtest_kde.h>

#include <QtCore/QList>

#define VK_APP_ID   "2446321"

using namespace Vkontakte;

TestUserInfo::TestUserInfo()
    : m_vkapi(0)
{
}

void TestUserInfo::initTestCase()
{
    m_vkapi = new KIPIVkontaktePlugin::VkAPI(0);
    m_vkapi->setAppId(VK_APP_ID); // TODO: library should better not crash if setAppId is not called
    m_vkapi->startAuthentication(false);

    // Wait for authentication
    QEventLoop loop;
    // TODO: Wait for any outcome of the authentication process, including failure
    connect(m_vkapi, SIGNAL(authenticated()), &loop, SLOT(quit()));
    loop.exec();

    QVERIFY(m_vkapi->isAuthenticated());
}

void TestUserInfo::testUserInfoJob()
{
    Vkontakte::UserInfoJob* const job = new Vkontakte::UserInfoJob(
        m_vkapi->accessToken(), 1);

    job->exec();

    QList<UserInfoPtr> res = job->userInfo();
    QCOMPARE(res.size(), 1);

    UserInfoPtr user = res.first();
    QCOMPARE(user->domain(), QString("durov"));
    QCOMPARE(user->firstName(), QString::fromUtf8("Павел"));
}

void TestUserInfo::testUserInfoFullJob()
{
    Vkontakte::UserInfoFullJob* const job = new Vkontakte::UserInfoFullJob(
        m_vkapi->accessToken(), 1, true, true);

    job->exec();

    QList<UserInfoPtr> res = job->userInfo();
    QCOMPARE(res.size(), 1);

    UserInfoPtr user = res.first();
    QCOMPARE(user->domain(), QString("durov"));
    QCOMPARE(user->firstName(), QString::fromUtf8("Павел"));
    QCOMPARE(user->countryString(), QString::fromUtf8("Россия"));
    QCOMPARE(user->cityString(), QString::fromUtf8("Санкт-Петербург"));
}

QTEST_KDEMAIN(TestUserInfo, GUI)
#include "test_userinfo.moc"
<|endoftext|>


<commit_before>/*
  This file is part of the kblog library.

  Copyright (c) 2007 Christian Weilbach <christian_weilbach@web.de>

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

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  Library General Public License for more details.

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

#include <QtTest>
#include <QtCore>

#include <QTest>
#include "kblog/blogmedia.h"
#include "qurl.h"

Q_DECLARE_METATYPE(KBlog::BlogMedia::Status)

using namespace KBlog;

class testBlogMedia: public QObject
{
    Q_OBJECT
private Q_SLOTS:
    void testValidity();
    void testValidity_data();
};

#include "testblogmedia.moc"

void testBlogMedia::testValidity_data()
{
    QTest::addColumn<QString>("name");
    QTest::addColumn<QUrl>("url");
    QTest::addColumn<QString>("mimetype");
    QTest::addColumn<QByteArray>("data");
    QTest::addColumn<BlogMedia::Status>("status");
    QTest::addColumn<QString>("error");

    QTest::newRow("SimpleTest")
            << QString::fromLatin1("FancyMedia")
            << QUrl(QLatin1String("http://my.link/in/outer/space/fancyMedia.jpg"))
            << QString::fromLatin1("text/xml")
            << QByteArray("Tags 1 2")
            << BlogMedia::New
            << QString::fromLatin1("Error");
}

void testBlogMedia::testValidity()
{
    BlogMedia p;

    QFETCH(QString, name);
    QFETCH(QUrl, url);
    QFETCH(QString, mimetype);
    QFETCH(QByteArray, data);
    QFETCH(BlogMedia::Status, status);
    QFETCH(QString, error);

    p.setName(name);
    p.setUrl(url);
    p.setMimetype(mimetype);
    p.setData(data);
    p.setStatus(status);
    p.setError(error);

    QCOMPARE(p.name(), name);
    QCOMPARE(p.url(), url);
    QCOMPARE(p.mimetype(), mimetype);
    QCOMPARE(p.data(), data);
    QCOMPARE(p.status(), status);
    QCOMPARE(p.error(), error);

}

QTEST_GUILESS_MAIN(testBlogMedia)
<commit_msg>remove <QtTest> which includes all of <QtCore><commit_after>/*
  This file is part of the kblog library.

  Copyright (c) 2007 Christian Weilbach <christian_weilbach@web.de>

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

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  Library General Public License for more details.

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

#include <QTest>
#include <QtCore>

#include <QTest>
#include "kblog/blogmedia.h"
#include "qurl.h"

Q_DECLARE_METATYPE(KBlog::BlogMedia::Status)

using namespace KBlog;

class testBlogMedia: public QObject
{
    Q_OBJECT
private Q_SLOTS:
    void testValidity();
    void testValidity_data();
};

#include "testblogmedia.moc"

void testBlogMedia::testValidity_data()
{
    QTest::addColumn<QString>("name");
    QTest::addColumn<QUrl>("url");
    QTest::addColumn<QString>("mimetype");
    QTest::addColumn<QByteArray>("data");
    QTest::addColumn<BlogMedia::Status>("status");
    QTest::addColumn<QString>("error");

    QTest::newRow("SimpleTest")
            << QString::fromLatin1("FancyMedia")
            << QUrl(QLatin1String("http://my.link/in/outer/space/fancyMedia.jpg"))
            << QString::fromLatin1("text/xml")
            << QByteArray("Tags 1 2")
            << BlogMedia::New
            << QString::fromLatin1("Error");
}

void testBlogMedia::testValidity()
{
    BlogMedia p;

    QFETCH(QString, name);
    QFETCH(QUrl, url);
    QFETCH(QString, mimetype);
    QFETCH(QByteArray, data);
    QFETCH(BlogMedia::Status, status);
    QFETCH(QString, error);

    p.setName(name);
    p.setUrl(url);
    p.setMimetype(mimetype);
    p.setData(data);
    p.setStatus(status);
    p.setError(error);

    QCOMPARE(p.name(), name);
    QCOMPARE(p.url(), url);
    QCOMPARE(p.mimetype(), mimetype);
    QCOMPARE(p.data(), data);
    QCOMPARE(p.status(), status);
    QCOMPARE(p.error(), error);

}

QTEST_GUILESS_MAIN(testBlogMedia)
<|endoftext|>


<commit_before>#include <SDL/SDL.h>
#include "InitScreen.hpp"

using namespace rd;

int main()
{
    InitScreen screen;

    for (int i = 0; i < 200; i++)
    {
        screen.show();
        SDL_Delay(20); //Wait a bit :)
    }
}
<commit_msg>testInitScreen updated to new RdScreen interface<commit_after>#include <SDL/SDL.h>
#include "SDLUtils.hpp"
#include "InitScreen.hpp"

using namespace rd;

int main()
{
    initSDL();

    InitScreen screen;
    screen.init();

    for (int i = 0; i < 200; i++)
    {
        screen.show();
        SDL_Delay(20); //Wait a bit :)
    }
    screen.cleanup();

    cleanupSDL();
}
<|endoftext|>


<commit_before>/*
 * Copyright 2016 Facebook, Inc.
 *
 * 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 <folly/portability/SysUio.h>

#include <errno.h>
#include <stdio.h>

#include <folly/ScopeGuard.h>
#include <folly/portability/SysFile.h>
#include <folly/portability/Unistd.h>

template <class F, class... Args>
static int wrapPositional(F f, int fd, off_t offset, Args... args) {
  off_t origLoc = lseek(fd, 0, SEEK_CUR);
  if (origLoc == off_t(-1)) {
    return -1;
  }
  if (lseek(fd, offset, SEEK_SET) == off_t(-1)) {
    return -1;
  }

  int res = (int)f(fd, args...);

  int curErrNo = errno;
  if (lseek(fd, origLoc, SEEK_SET) == off_t(-1)) {
    if (res == -1) {
      errno = curErrNo;
    }
    return -1;
  }
  errno = curErrNo;

  return res;
}

#if !FOLLY_HAVE_PREADV
extern "C" ssize_t preadv(int fd, const iovec* iov, int count, off_t offset) {
  return wrapPositional(readv, fd, offset, iov, count);
}
#endif

#if !FOLLY_HAVE_PWRITEV
extern "C" ssize_t pwritev(int fd, const iovec* iov, int count, off_t offset) {
  return wrapPositional(writev, fd, offset, iov, count);
}
#endif

#ifdef _WIN32
template <bool isRead>
static ssize_t doVecOperation(int fd, const iovec* iov, int count) {
  if (!count) {
    return 0;
  }
  if (count < 0 || count > folly::kIovMax) {
    errno = EINVAL;
    return -1;
  }

  if (lockf(fd, F_LOCK, 0) == -1) {
    return -1;
  }
  SCOPE_EXIT { lockf(fd, F_ULOCK, 0); };

  ssize_t bytesProcessed = 0;
  int curIov = 0;
  void* curBase = iov[0].iov_base;
  size_t curLen = iov[0].iov_len;
  while (curIov < count) {
    int res = 0;
    if (isRead) {
      res = read(fd, curBase, (unsigned int)curLen);
      if (res == 0 && curLen != 0) {
        break; // End of File
      }
    } else {
      res = write(fd, curBase, (unsigned int)curLen);
      // Write of zero bytes is fine.
    }

    if (res == -1) {
      return -1;
    }

    if (res == curLen) {
      curIov++;
      if (curIov < count) {
        curBase = iov[curIov].iov_base;
        curLen = iov[curIov].iov_len;
      }
    } else {
      curBase += (void*)((char*)curBase + res);
      curLen -= res;
    }

    if (bytesProcessed + res < 0) {
      // Overflow
      errno = EINVAL;
      return -1;
    }
    bytesProcessed += res;
  }

  return bytesProcessed;
}

extern "C" ssize_t readv(int fd, const iovec* iov, int count) {
  return doVecOperation<true>(fd, iov, count);
}

extern "C" ssize_t writev(int fd, const iovec* iov, int count) {
  return doVecOperation<false>(fd, iov, count);
}
#endif
<commit_msg>Fix doVecOperation in the SysUio portability header<commit_after>/*
 * Copyright 2016 Facebook, Inc.
 *
 * 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 <folly/portability/SysUio.h>

#include <errno.h>
#include <stdio.h>

#include <folly/ScopeGuard.h>
#include <folly/portability/SysFile.h>
#include <folly/portability/Unistd.h>

template <class F, class... Args>
static int wrapPositional(F f, int fd, off_t offset, Args... args) {
  off_t origLoc = lseek(fd, 0, SEEK_CUR);
  if (origLoc == off_t(-1)) {
    return -1;
  }
  if (lseek(fd, offset, SEEK_SET) == off_t(-1)) {
    return -1;
  }

  int res = (int)f(fd, args...);

  int curErrNo = errno;
  if (lseek(fd, origLoc, SEEK_SET) == off_t(-1)) {
    if (res == -1) {
      errno = curErrNo;
    }
    return -1;
  }
  errno = curErrNo;

  return res;
}

#if !FOLLY_HAVE_PREADV
extern "C" ssize_t preadv(int fd, const iovec* iov, int count, off_t offset) {
  return wrapPositional(readv, fd, offset, iov, count);
}
#endif

#if !FOLLY_HAVE_PWRITEV
extern "C" ssize_t pwritev(int fd, const iovec* iov, int count, off_t offset) {
  return wrapPositional(writev, fd, offset, iov, count);
}
#endif

#ifdef _WIN32
template <bool isRead>
static ssize_t doVecOperation(int fd, const iovec* iov, int count) {
  if (!count) {
    return 0;
  }
  if (count < 0 || count > folly::kIovMax) {
    errno = EINVAL;
    return -1;
  }

  if (lockf(fd, F_LOCK, 0) == -1) {
    return -1;
  }
  SCOPE_EXIT { lockf(fd, F_ULOCK, 0); };

  ssize_t bytesProcessed = 0;
  int curIov = 0;
  void* curBase = iov[0].iov_base;
  size_t curLen = iov[0].iov_len;
  while (curIov < count) {
    int res = 0;
    if (isRead) {
      res = read(fd, curBase, (unsigned int)curLen);
      if (res == 0 && curLen != 0) {
        break; // End of File
      }
    } else {
      res = write(fd, curBase, (unsigned int)curLen);
      // Write of zero bytes is fine.
    }

    if (res == -1) {
      return -1;
    }

    if (res == curLen) {
      curIov++;
      if (curIov < count) {
        curBase = iov[curIov].iov_base;
        curLen = iov[curIov].iov_len;
      }
    } else {
      curBase = (void*)((char*)curBase + res);
      curLen -= res;
    }

    if (bytesProcessed + res < 0) {
      // Overflow
      errno = EINVAL;
      return -1;
    }
    bytesProcessed += res;
  }

  return bytesProcessed;
}

extern "C" ssize_t readv(int fd, const iovec* iov, int count) {
  return doVecOperation<true>(fd, iov, count);
}

extern "C" ssize_t writev(int fd, const iovec* iov, int count) {
  return doVecOperation<false>(fd, iov, count);
}
#endif
<|endoftext|>


<commit_before>// File_Exr - Info for EXR files
// Copyright (C) 2011-2011 MediaArea.net SARL, Info@MediaArea.net
//
// 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 3 of the License, or
// any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library. If not, see <http://www.gnu.org/licenses/>.
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

//---------------------------------------------------------------------------
// Compilation conditions
#include "MediaInfo/Setup.h"
#ifdef __BORLANDC__
    #pragma hdrstop
#endif
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#if defined(MEDIAINFO_EXR_YES)
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/Image/File_Exr.h"
#if MEDIAINFO_DEMUX
    #include "MediaInfo/MediaInfo_Config_MediaInfo.h"
#endif //MEDIAINFO_DEMUX
//---------------------------------------------------------------------------

namespace MediaInfoLib
{

//***************************************************************************
// Infos
//***************************************************************************

//***************************************************************************
// Const
//***************************************************************************

enum Elements
{
    Pos_FileInformation,
    Pos_GenericSection,
    Pos_IndustrySpecific,
    Pos_UserDefined,
    Pos_Padding,
    Pos_ImageData,
};

//***************************************************************************
// Constructor/Destructor
//***************************************************************************

//---------------------------------------------------------------------------
File_Exr::File_Exr()
:File__Analyze()
{
    //Configuration
    ParserName=_T("EXR");
}

//***************************************************************************
// Streams management
//***************************************************************************

//---------------------------------------------------------------------------
void File_Exr::Streams_Accept()
{
    Fill(Stream_General, 0, General_Format, "EXR");
    Stream_Prepare(Stream_Image);
    Fill(Stream_Image, 0, Image_Format, "EXR");

    //Configuration
    Buffer_MaximumSize=64*1024*1024;
    Frame_Count_NotParsedIncluded=0;
}

//---------------------------------------------------------------------------
void File_Exr::Streams_Finish()
{
}

//***************************************************************************
// Buffer - Demux
//***************************************************************************

//---------------------------------------------------------------------------
#if MEDIAINFO_DEMUX
bool File_Exr::Demux_UnpacketizeContainer_Test()
{
    if (Buffer_Size<File_Size)
    {
        size_t* File_Buffer_Size_Hint_Pointer=Config->File_Buffer_Size_Hint_Pointer_Get();
        if (File_Buffer_Size_Hint_Pointer)
            (*File_Buffer_Size_Hint_Pointer)=File_Size;
        return false;
    }

    if (Config->Demux_Rate_Get())
    {
        if (Frame_Count_NotParsedIncluded!=(int64u)-1)
            FrameInfo.DTS=float64_int64s(Frame_Count_NotParsedIncluded*1000000000/Config->Demux_Rate_Get());
        else
            FrameInfo.DTS=(int64u)-1;
        FrameInfo.PTS=FrameInfo.DTS;
        FrameInfo.DUR=float64_int64s(1000000000/Config->Demux_Rate_Get());
    }
    size_t Buffer_Offset_Save=Buffer_Offset;
    Buffer_Offset=0; //File header must be included in the packet
    Demux_Offset=Buffer_Size;
    Demux_UnpacketizeContainer_Demux();
    Buffer_Offset=Buffer_Offset_Save;

    return true;
}
#endif //MEDIAINFO_DEMUX

//***************************************************************************
// Buffer
//***************************************************************************

//---------------------------------------------------------------------------
bool File_Exr::FileHeader_Begin()
{
    //Element_Size
    if (Buffer_Size<4)
        return false; //Must wait for more data

    if (CC4(Buffer)!=0x762F3101) //"v/1"+1
    {
        Reject();
        return false;
    }

    //All should be OK...
    Accept();

    //Testing if parsing is needed
    if (Count_Get(Stream_Video))
    {
        //In a video stream, no need to parse all frames)
        GoToFromEnd(0);
        return true;
    }

    return true;
}

//---------------------------------------------------------------------------
void File_Exr::FileHeader_Parse()
{
    //Element_Size
    if (Buffer_Size<8)
    {
        Element_WaitForMoreData();
        return;
    }

    //Parsing
    int32u Flags;
    int8u Version;
    Skip_L4(                                                    "Magic number");
    Get_L1 (Version,                                            "Version field");
    Get_L3 (Flags,                                              "Flags");

    //Filling
    Fill(Stream_General, 0, General_Format_Version, _T("Version ")+Ztring::ToZtring(Version));
    Fill(Stream_Image, 0, Image_Format_Version, _T("Version ")+Ztring::ToZtring(Version));
    Fill(Stream_Image, 0, Image_Format_Profile, (Flags&0x02)?"Tile":"Line");
}

//***************************************************************************
// Buffer - Per element
//***************************************************************************

//---------------------------------------------------------------------------
bool File_Exr::Header_Begin()
{
    //Name
    name_End=0;
    while (Buffer_Offset+name_End<Buffer_Size)
    {
        if (Buffer[Buffer_Offset+name_End]=='\0')
            break;
        if (name_End==31)
            break;
        name_End++;
    }
    if (Buffer_Offset+name_End>=Buffer_Size)
        return false;
    if (name_End>=31)
    {
        Reject();
        return false;
    }
    if (name_End==0)
    {
        Frame_Count_NotParsedIncluded++;
        Finish();
        return false;
    }

    //Type
    type_End=0;
    while (Buffer_Offset+name_End+1+type_End<Buffer_Size)
    {
        if (Buffer[Buffer_Offset+name_End+1+type_End]=='\0')
            break;
        if (type_End==31)
            break;
        type_End++;
    }

    if (Buffer_Offset+name_End+1+type_End>=Buffer_Size)
        return false;
    if (type_End>=31)
    {
        Reject();
        return false;
    }

    if (Buffer_Offset+name_End+1+type_End+1+4>=Buffer_Size)
        return false;

    return true;
}

//---------------------------------------------------------------------------
void File_Exr::Header_Parse()
{
    int32u size;
    Get_String(name_End, name,                                  "name");
    Element_Offset++; //Null byte
    Get_String(type_End, type,                                  "type");
    Element_Offset++; //Null byte
    Get_L4 (size,                                               "size");

    //Filling
    Header_Fill_Code(0, Ztring().From_Local(name.c_str()));
    Header_Fill_Size(name_End+1+type_End+1+4+size);
}

//---------------------------------------------------------------------------
void File_Exr::Data_Parse()
{
         if (name=="comments" && type=="string")
        comments();
    else if (name=="compression" && type=="compression" && Element_Size==1)
        compression();
    else if (name=="dataWindow" && type=="box2i" && Element_Size==16)
        dataWindow();
    else if (name=="displayWindow" && type=="box2i" && Element_Size==16)
        displayWindow();
    else if (name=="pixelAspectRatio" && type=="float" && Element_Size==4)
        pixelAspectRatio();
    else
        Skip_XX(Element_Size,                                   "value");
}

//---------------------------------------------------------------------------
void File_Exr::comments ()
{
    //Parsing
    Ztring value;
    Get_Local(Element_Size, value,                              "value");

    //Filling
    Fill(Stream_Image, 0, General_Comment, value);
}

//---------------------------------------------------------------------------
void File_Exr::compression ()
{
    //Parsing
    int8u value;
    Get_L1 (value,                                              "value");

    //Filling
    std::string Compression;
    switch (value)
    {
        case 0x00 : Compression="raw"; break;
        case 0x01 : Compression="RLZ"; break;
        case 0x02 : Compression="ZIPS"; break;
        case 0x03 : Compression="ZIP"; break;
        case 0x04 : Compression="PIZ"; break;
        case 0x05 : Compression="PXR24"; break;
        case 0x06 : Compression="B44"; break;
        case 0x07 : Compression="B44A"; break;
        default   : ;
    }
    Fill(Stream_Image, 0, Image_Format_Compression, Compression.c_str());
}

//---------------------------------------------------------------------------
void File_Exr::dataWindow ()
{
    //Parsing
    int32u xMin, yMin, xMax, yMax;
    Get_L4 (xMin,                                               "xMin");
    Get_L4 (yMin,                                               "yMin");
    Get_L4 (xMax,                                               "xMax");
    Get_L4 (yMax,                                               "yMax");
}

//---------------------------------------------------------------------------
void File_Exr::displayWindow ()
{
    //Parsing
    int32u xMin, yMin, xMax, yMax;
    Get_L4 (xMin,                                               "xMin");
    Get_L4 (yMin,                                               "yMin");
    Get_L4 (xMax,                                               "xMax");
    Get_L4 (yMax,                                               "yMax");

    //Filling
    Fill(Stream_Image, 0, Image_Width, xMax-xMin);
    Fill(Stream_Image, 0, Image_Height, yMax-yMin);
}

//---------------------------------------------------------------------------
void File_Exr::pixelAspectRatio ()
{
    //Parsing
    float value;
    Get_LF4(value,                                              "value");

    //Filling
    Fill(Stream_Image, 0, Image_PixelAspectRatio, value?value:1, 3);
}

} //NameSpace

#endif //MEDIAINFO_EXR_YES
<commit_msg>x EXR: Width/Height were 1 less than real value<commit_after>// File_Exr - Info for EXR files
// Copyright (C) 2011-2011 MediaArea.net SARL, Info@MediaArea.net
//
// 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 3 of the License, or
// any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library. If not, see <http://www.gnu.org/licenses/>.
//
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

//---------------------------------------------------------------------------
// Compilation conditions
#include "MediaInfo/Setup.h"
#ifdef __BORLANDC__
    #pragma hdrstop
#endif
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#if defined(MEDIAINFO_EXR_YES)
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/Image/File_Exr.h"
#if MEDIAINFO_DEMUX
    #include "MediaInfo/MediaInfo_Config_MediaInfo.h"
#endif //MEDIAINFO_DEMUX
//---------------------------------------------------------------------------

namespace MediaInfoLib
{

//***************************************************************************
// Infos
//***************************************************************************

//***************************************************************************
// Const
//***************************************************************************

enum Elements
{
    Pos_FileInformation,
    Pos_GenericSection,
    Pos_IndustrySpecific,
    Pos_UserDefined,
    Pos_Padding,
    Pos_ImageData,
};

//***************************************************************************
// Constructor/Destructor
//***************************************************************************

//---------------------------------------------------------------------------
File_Exr::File_Exr()
:File__Analyze()
{
    //Configuration
    ParserName=_T("EXR");
}

//***************************************************************************
// Streams management
//***************************************************************************

//---------------------------------------------------------------------------
void File_Exr::Streams_Accept()
{
    Fill(Stream_General, 0, General_Format, "EXR");
    Stream_Prepare(Stream_Image);
    Fill(Stream_Image, 0, Image_Format, "EXR");

    //Configuration
    Buffer_MaximumSize=64*1024*1024;
    Frame_Count_NotParsedIncluded=0;
}

//---------------------------------------------------------------------------
void File_Exr::Streams_Finish()
{
}

//***************************************************************************
// Buffer - Demux
//***************************************************************************

//---------------------------------------------------------------------------
#if MEDIAINFO_DEMUX
bool File_Exr::Demux_UnpacketizeContainer_Test()
{
    if (Buffer_Size<File_Size)
    {
        size_t* File_Buffer_Size_Hint_Pointer=Config->File_Buffer_Size_Hint_Pointer_Get();
        if (File_Buffer_Size_Hint_Pointer)
            (*File_Buffer_Size_Hint_Pointer)=File_Size;
        return false;
    }

    if (Config->Demux_Rate_Get())
    {
        if (Frame_Count_NotParsedIncluded!=(int64u)-1)
            FrameInfo.DTS=float64_int64s(Frame_Count_NotParsedIncluded*1000000000/Config->Demux_Rate_Get());
        else
            FrameInfo.DTS=(int64u)-1;
        FrameInfo.PTS=FrameInfo.DTS;
        FrameInfo.DUR=float64_int64s(1000000000/Config->Demux_Rate_Get());
    }
    size_t Buffer_Offset_Save=Buffer_Offset;
    Buffer_Offset=0; //File header must be included in the packet
    Demux_Offset=Buffer_Size;
    Demux_UnpacketizeContainer_Demux();
    Buffer_Offset=Buffer_Offset_Save;

    return true;
}
#endif //MEDIAINFO_DEMUX

//***************************************************************************
// Buffer
//***************************************************************************

//---------------------------------------------------------------------------
bool File_Exr::FileHeader_Begin()
{
    //Element_Size
    if (Buffer_Size<4)
        return false; //Must wait for more data

    if (CC4(Buffer)!=0x762F3101) //"v/1"+1
    {
        Reject();
        return false;
    }

    //All should be OK...
    Accept();

    //Testing if parsing is needed
    if (Count_Get(Stream_Video))
    {
        //In a video stream, no need to parse all frames)
        GoToFromEnd(0);
        return true;
    }

    return true;
}

//---------------------------------------------------------------------------
void File_Exr::FileHeader_Parse()
{
    //Element_Size
    if (Buffer_Size<8)
    {
        Element_WaitForMoreData();
        return;
    }

    //Parsing
    int32u Flags;
    int8u Version;
    Skip_L4(                                                    "Magic number");
    Get_L1 (Version,                                            "Version field");
    Get_L3 (Flags,                                              "Flags");

    //Filling
    Fill(Stream_General, 0, General_Format_Version, _T("Version ")+Ztring::ToZtring(Version));
    Fill(Stream_Image, 0, Image_Format_Version, _T("Version ")+Ztring::ToZtring(Version));
    Fill(Stream_Image, 0, Image_Format_Profile, (Flags&0x02)?"Tile":"Line");
}

//***************************************************************************
// Buffer - Per element
//***************************************************************************

//---------------------------------------------------------------------------
bool File_Exr::Header_Begin()
{
    //Name
    name_End=0;
    while (Buffer_Offset+name_End<Buffer_Size)
    {
        if (Buffer[Buffer_Offset+name_End]=='\0')
            break;
        if (name_End==31)
            break;
        name_End++;
    }
    if (Buffer_Offset+name_End>=Buffer_Size)
        return false;
    if (name_End>=31)
    {
        Reject();
        return false;
    }
    if (name_End==0)
    {
        Frame_Count_NotParsedIncluded++;
        Finish();
        return false;
    }

    //Type
    type_End=0;
    while (Buffer_Offset+name_End+1+type_End<Buffer_Size)
    {
        if (Buffer[Buffer_Offset+name_End+1+type_End]=='\0')
            break;
        if (type_End==31)
            break;
        type_End++;
    }

    if (Buffer_Offset+name_End+1+type_End>=Buffer_Size)
        return false;
    if (type_End>=31)
    {
        Reject();
        return false;
    }

    if (Buffer_Offset+name_End+1+type_End+1+4>=Buffer_Size)
        return false;

    return true;
}

//---------------------------------------------------------------------------
void File_Exr::Header_Parse()
{
    int32u size;
    Get_String(name_End, name,                                  "name");
    Element_Offset++; //Null byte
    Get_String(type_End, type,                                  "type");
    Element_Offset++; //Null byte
    Get_L4 (size,                                               "size");

    //Filling
    Header_Fill_Code(0, Ztring().From_Local(name.c_str()));
    Header_Fill_Size(name_End+1+type_End+1+4+size);
}

//---------------------------------------------------------------------------
void File_Exr::Data_Parse()
{
         if (name=="comments" && type=="string")
        comments();
    else if (name=="compression" && type=="compression" && Element_Size==1)
        compression();
    else if (name=="dataWindow" && type=="box2i" && Element_Size==16)
        dataWindow();
    else if (name=="displayWindow" && type=="box2i" && Element_Size==16)
        displayWindow();
    else if (name=="pixelAspectRatio" && type=="float" && Element_Size==4)
        pixelAspectRatio();
    else
        Skip_XX(Element_Size,                                   "value");
}

//---------------------------------------------------------------------------
void File_Exr::comments ()
{
    //Parsing
    Ztring value;
    Get_Local(Element_Size, value,                              "value");

    //Filling
    Fill(Stream_Image, 0, General_Comment, value);
}

//---------------------------------------------------------------------------
void File_Exr::compression ()
{
    //Parsing
    int8u value;
    Get_L1 (value,                                              "value");

    //Filling
    std::string Compression;
    switch (value)
    {
        case 0x00 : Compression="raw"; break;
        case 0x01 : Compression="RLZ"; break;
        case 0x02 : Compression="ZIPS"; break;
        case 0x03 : Compression="ZIP"; break;
        case 0x04 : Compression="PIZ"; break;
        case 0x05 : Compression="PXR24"; break;
        case 0x06 : Compression="B44"; break;
        case 0x07 : Compression="B44A"; break;
        default   : ;
    }
    Fill(Stream_Image, 0, Image_Format_Compression, Compression.c_str());
}

//---------------------------------------------------------------------------
void File_Exr::dataWindow ()
{
    //Parsing
    int32u xMin, yMin, xMax, yMax;
    Get_L4 (xMin,                                               "xMin");
    Get_L4 (yMin,                                               "yMin");
    Get_L4 (xMax,                                               "xMax");
    Get_L4 (yMax,                                               "yMax");
}

//---------------------------------------------------------------------------
void File_Exr::displayWindow ()
{
    //Parsing
    int32u xMin, yMin, xMax, yMax;
    Get_L4 (xMin,                                               "xMin");
    Get_L4 (yMin,                                               "yMin");
    Get_L4 (xMax,                                               "xMax");
    Get_L4 (yMax,                                               "yMax");

    //Filling
    Fill(Stream_Image, 0, Image_Width, xMax-xMin+1);
    Fill(Stream_Image, 0, Image_Height, yMax-yMin+1);
}

//---------------------------------------------------------------------------
void File_Exr::pixelAspectRatio ()
{
    //Parsing
    float value;
    Get_LF4(value,                                              "value");

    //Filling
    Fill(Stream_Image, 0, Image_PixelAspectRatio, value?value:1, 3);
}

} //NameSpace

#endif //MEDIAINFO_EXR_YES
<|endoftext|>