<commit_before>// Copyright 2018 Google LLC
//
// 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
//
//    https://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 <algorithm>

#include "absl/container/flat_hash_set.h"
#include "absl/strings/escaping.h"
#include "absl/strings/str_split.h"
#include "google/protobuf/util/json_util.h"
#include "jwt_verify_lib/jwt.h"
#include "jwt_verify_lib/struct_utils.h"

namespace google {
namespace jwt_verify {

bool isImplemented(absl::string_view alg) {
  static const absl::flat_hash_set<absl::string_view> *implemented_algs =
      new absl::flat_hash_set<absl::string_view>({
          {"ES256"}, {"ES384"}, {"ES512"},
          {"HS256"}, {"HS384"}, {"HS512"},
          {"RS256"}, {"RS384"}, {"RS512"},
          {"PS256"}, {"PS384"}, {"PS512"},
          {"EdDSA"},
        });

  return implemented_algs->find(alg) != implemented_algs->end();
}

Jwt::Jwt(const Jwt& instance) { *this = instance; }

Jwt& Jwt::operator=(const Jwt& rhs) {
  parseFromString(rhs.jwt_);
  return *this;
}

Status Jwt::parseFromString(const std::string& jwt) {
  // jwt must have exactly 2 dots
  if (std::count(jwt.begin(), jwt.end(), '.') != 2) {
    return Status::JwtBadFormat;
  }
  jwt_ = jwt;
  std::vector<absl::string_view> jwt_split =
      absl::StrSplit(jwt, '.', absl::SkipEmpty());
  if (jwt_split.size() != 3) {
    return Status::JwtBadFormat;
  }

  // Parse header json
  header_str_base64url_ = std::string(jwt_split[0]);
  if (!absl::WebSafeBase64Unescape(header_str_base64url_, &header_str_)) {
    return Status::JwtHeaderParseErrorBadBase64;
  }

  ::google::protobuf::util::JsonParseOptions options;
  const auto header_status = ::google::protobuf::util::JsonStringToMessage(
      header_str_, &header_pb_, options);
  if (!header_status.ok()) {
    return Status::JwtHeaderParseErrorBadJson;
  }

  StructUtils header_getter(header_pb_);
  // Header should contain "alg" and should be a string.
  if (header_getter.GetString("alg", &alg_) != StructUtils::OK) {
    return Status::JwtHeaderBadAlg;
  }

  if (!isImplemented(alg_)) {
    return Status::JwtHeaderNotImplementedAlg;
  }

  // Header may contain "kid", should be a string if exists.
  if (header_getter.GetString("kid", &kid_) == StructUtils::WRONG_TYPE) {
    return Status::JwtHeaderBadKid;
  }

  // Parse payload json
  payload_str_base64url_ = std::string(jwt_split[1]);
  if (!absl::WebSafeBase64Unescape(payload_str_base64url_, &payload_str_)) {
    return Status::JwtPayloadParseErrorBadBase64;
  }

  const auto payload_status = ::google::protobuf::util::JsonStringToMessage(
      payload_str_, &payload_pb_, options);
  if (!payload_status.ok()) {
    return Status::JwtPayloadParseErrorBadJson;
  }

  StructUtils payload_getter(payload_pb_);
  if (payload_getter.GetString("iss", &iss_) == StructUtils::WRONG_TYPE) {
    return Status::JwtPayloadParseErrorIssNotString;
  }
  if (payload_getter.GetString("sub", &sub_) == StructUtils::WRONG_TYPE) {
    return Status::JwtPayloadParseErrorSubNotString;
  }

  if (payload_getter.GetInt64("iat", &iat_) == StructUtils::WRONG_TYPE) {
    return Status::JwtPayloadParseErrorIatNotInteger;
  }
  if (payload_getter.GetInt64("nbf", &nbf_) == StructUtils::WRONG_TYPE) {
    return Status::JwtPayloadParseErrorNbfNotInteger;
  }
  if (payload_getter.GetInt64("exp", &exp_) == StructUtils::WRONG_TYPE) {
    return Status::JwtPayloadParseErrorExpNotInteger;
  }

  if (payload_getter.GetString("jti", &jti_) == StructUtils::WRONG_TYPE) {
    return Status::JwtPayloadParseErrorJtiNotString;
  }

  // "aud" can be either string array or string.
  // GetStringList function will try to read as string, if fails,
  // try to read as string array.
  if (payload_getter.GetStringList("aud", &audiences_) ==
      StructUtils::WRONG_TYPE) {
    return Status::JwtPayloadParseErrorAudNotString;
  }

  // Set up signature
  if (!absl::WebSafeBase64Unescape(jwt_split[2], &signature_)) {
    // Signature is a bad Base64url input.
    return Status::JwtSignatureParseErrorBadBase64;
  }
  return Status::Ok;
}

}  // namespace jwt_verify
}  // namespace google
<commit_msg>Add anonymous namespace for isImplemented<commit_after>// Copyright 2018 Google LLC
//
// 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
//
//    https://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 <algorithm>

#include "absl/container/flat_hash_set.h"
#include "absl/strings/escaping.h"
#include "absl/strings/str_split.h"
#include "google/protobuf/util/json_util.h"
#include "jwt_verify_lib/jwt.h"
#include "jwt_verify_lib/struct_utils.h"

namespace google {
namespace jwt_verify {

namespace {

bool isImplemented(absl::string_view alg) {
  static const absl::flat_hash_set<absl::string_view> *implemented_algs =
      new absl::flat_hash_set<absl::string_view>({
          {"ES256"}, {"ES384"}, {"ES512"},
          {"HS256"}, {"HS384"}, {"HS512"},
          {"RS256"}, {"RS384"}, {"RS512"},
          {"PS256"}, {"PS384"}, {"PS512"},
          {"EdDSA"},
        });

  return implemented_algs->find(alg) != implemented_algs->end();
}

}

Jwt::Jwt(const Jwt& instance) { *this = instance; }

Jwt& Jwt::operator=(const Jwt& rhs) {
  parseFromString(rhs.jwt_);
  return *this;
}

Status Jwt::parseFromString(const std::string& jwt) {
  // jwt must have exactly 2 dots
  if (std::count(jwt.begin(), jwt.end(), '.') != 2) {
    return Status::JwtBadFormat;
  }
  jwt_ = jwt;
  std::vector<absl::string_view> jwt_split =
      absl::StrSplit(jwt, '.', absl::SkipEmpty());
  if (jwt_split.size() != 3) {
    return Status::JwtBadFormat;
  }

  // Parse header json
  header_str_base64url_ = std::string(jwt_split[0]);
  if (!absl::WebSafeBase64Unescape(header_str_base64url_, &header_str_)) {
    return Status::JwtHeaderParseErrorBadBase64;
  }

  ::google::protobuf::util::JsonParseOptions options;
  const auto header_status = ::google::protobuf::util::JsonStringToMessage(
      header_str_, &header_pb_, options);
  if (!header_status.ok()) {
    return Status::JwtHeaderParseErrorBadJson;
  }

  StructUtils header_getter(header_pb_);
  // Header should contain "alg" and should be a string.
  if (header_getter.GetString("alg", &alg_) != StructUtils::OK) {
    return Status::JwtHeaderBadAlg;
  }

  if (!isImplemented(alg_)) {
    return Status::JwtHeaderNotImplementedAlg;
  }

  // Header may contain "kid", should be a string if exists.
  if (header_getter.GetString("kid", &kid_) == StructUtils::WRONG_TYPE) {
    return Status::JwtHeaderBadKid;
  }

  // Parse payload json
  payload_str_base64url_ = std::string(jwt_split[1]);
  if (!absl::WebSafeBase64Unescape(payload_str_base64url_, &payload_str_)) {
    return Status::JwtPayloadParseErrorBadBase64;
  }

  const auto payload_status = ::google::protobuf::util::JsonStringToMessage(
      payload_str_, &payload_pb_, options);
  if (!payload_status.ok()) {
    return Status::JwtPayloadParseErrorBadJson;
  }

  StructUtils payload_getter(payload_pb_);
  if (payload_getter.GetString("iss", &iss_) == StructUtils::WRONG_TYPE) {
    return Status::JwtPayloadParseErrorIssNotString;
  }
  if (payload_getter.GetString("sub", &sub_) == StructUtils::WRONG_TYPE) {
    return Status::JwtPayloadParseErrorSubNotString;
  }

  if (payload_getter.GetInt64("iat", &iat_) == StructUtils::WRONG_TYPE) {
    return Status::JwtPayloadParseErrorIatNotInteger;
  }
  if (payload_getter.GetInt64("nbf", &nbf_) == StructUtils::WRONG_TYPE) {
    return Status::JwtPayloadParseErrorNbfNotInteger;
  }
  if (payload_getter.GetInt64("exp", &exp_) == StructUtils::WRONG_TYPE) {
    return Status::JwtPayloadParseErrorExpNotInteger;
  }

  if (payload_getter.GetString("jti", &jti_) == StructUtils::WRONG_TYPE) {
    return Status::JwtPayloadParseErrorJtiNotString;
  }

  // "aud" can be either string array or string.
  // GetStringList function will try to read as string, if fails,
  // try to read as string array.
  if (payload_getter.GetStringList("aud", &audiences_) ==
      StructUtils::WRONG_TYPE) {
    return Status::JwtPayloadParseErrorAudNotString;
  }

  // Set up signature
  if (!absl::WebSafeBase64Unescape(jwt_split[2], &signature_)) {
    // Signature is a bad Base64url input.
    return Status::JwtSignatureParseErrorBadBase64;
  }
  return Status::Ok;
}

}  // namespace jwt_verify
}  // namespace google
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkClearZPass.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/

#include "vtkClearZPass.h"
#include "vtkObjectFactory.h"
#include <cassert>
#include "vtkRenderState.h"
#include "vtkRenderer.h"
#include "vtk_glew.h"

vtkStandardNewMacro(vtkClearZPass);

// ----------------------------------------------------------------------------
vtkClearZPass::vtkClearZPass()
{
  this->Depth=1.0;
}

// ----------------------------------------------------------------------------
vtkClearZPass::~vtkClearZPass()
{
}

// ----------------------------------------------------------------------------
void vtkClearZPass::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);

  os << indent << "Depth:" << this->Depth << endl;
}

// ----------------------------------------------------------------------------
// Description:
// Perform rendering according to a render state \p s.
// \pre s_exists: s!=0
void vtkClearZPass::Render(const vtkRenderState *s)
{
  assert("pre: s_exists" && s!=0);
  (void)s;
  this->NumberOfRenderedProps=0;

  glDepthMask(GL_TRUE);
  glClearDepth(this->Depth);
  glClear(GL_DEPTH_BUFFER_BIT);
}
<commit_msg>Fix clearzpass on opengl ES 2<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkClearZPass.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/

#include "vtkClearZPass.h"
#include "vtkObjectFactory.h"
#include <cassert>
#include "vtkRenderState.h"
#include "vtkRenderer.h"
#include "vtk_glew.h"

vtkStandardNewMacro(vtkClearZPass);

// ----------------------------------------------------------------------------
vtkClearZPass::vtkClearZPass()
{
  this->Depth=1.0;
}

// ----------------------------------------------------------------------------
vtkClearZPass::~vtkClearZPass()
{
}

// ----------------------------------------------------------------------------
void vtkClearZPass::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);

  os << indent << "Depth:" << this->Depth << endl;
}

// ----------------------------------------------------------------------------
// Description:
// Perform rendering according to a render state \p s.
// \pre s_exists: s!=0
void vtkClearZPass::Render(const vtkRenderState *s)
{
  assert("pre: s_exists" && s!=0);
  (void)s;
  this->NumberOfRenderedProps=0;

  glDepthMask(GL_TRUE);
#if GL_ES_VERSION_2_0 != 1
  glClearDepth(this->Depth);
#else
  glClearDepthf(static_cast<GLclampf>(this->Depth));
#endif
  glClear(GL_DEPTH_BUFFER_BIT);
}
<|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** 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.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/

#include "basetextmark.h"
#include "itexteditor.h"
#include "basetextdocument.h"
#include "texteditorplugin.h"

#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/documentmanager.h>
#include <extensionsystem/pluginmanager.h>
#include <utils/qtcassert.h>

using namespace TextEditor;
using namespace TextEditor::Internal;

BaseTextMarkRegistry::BaseTextMarkRegistry(QObject *parent)
    : QObject(parent)
{
    Core::EditorManager *em = Core::EditorManager::instance();
    connect(em, SIGNAL(editorOpened(Core::IEditor*)),
        SLOT(editorOpened(Core::IEditor*)));

    Core::DocumentManager *dm = Core::DocumentManager::instance();
    connect(dm, SIGNAL(allDocumentsRenamed(QString,QString)),
            this, SLOT(allDocumentsRenamed(QString,QString)));
    connect(dm, SIGNAL(documentRenamed(Core::IDocument*,QString,QString)),
            this, SLOT(documentRenamed(Core::IDocument*,QString,QString)));
}

void BaseTextMarkRegistry::add(BaseTextMark *mark)
{
    m_marks[Utils::FileName::fromString(mark->fileName())].insert(mark);
    Core::EditorManager *em = Core::EditorManager::instance();
    foreach (Core::IEditor *editor, em->editorsForFileName(mark->fileName())) {
        if (ITextEditor *textEditor = qobject_cast<ITextEditor *>(editor)) {
            ITextMarkable *markableInterface = textEditor->markableInterface();
            if (markableInterface->addMark(mark)) {
                break;
            }
        }
    }
}

bool BaseTextMarkRegistry::remove(BaseTextMark *mark)
{
    return m_marks[Utils::FileName::fromString(mark->fileName())].remove(mark);
}

void BaseTextMarkRegistry::editorOpened(Core::IEditor *editor)
{
    ITextEditor *textEditor = qobject_cast<ITextEditor *>(editor);
    if (!textEditor)
        return;
    if (!m_marks.contains(Utils::FileName::fromString(editor->document()->fileName())))
        return;

    foreach (BaseTextMark *mark, m_marks.value(Utils::FileName::fromString(editor->document()->fileName()))) {
        ITextMarkable *markableInterface = textEditor->markableInterface();
        markableInterface->addMark(mark);
    }
}

void BaseTextMarkRegistry::documentRenamed(Core::IDocument *document, const
                                           QString &oldName, const QString &newName)
{
    TextEditor::BaseTextDocument *baseTextDocument
            = qobject_cast<TextEditor::BaseTextDocument *>(document);
    if (!document)
        return;
    Utils::FileName oldFileName = Utils::FileName::fromString(oldName);
    Utils::FileName newFileName = Utils::FileName::fromString(newName);
    if (!m_marks.contains(oldFileName))
        return;

    QSet<BaseTextMark *> toBeMoved;
    foreach (ITextMark *mark, baseTextDocument->documentMarker()->marks())
        if (BaseTextMark *baseTextMark = dynamic_cast<BaseTextMark *>(mark))
            toBeMoved.insert(baseTextMark);

    m_marks[oldFileName].subtract(toBeMoved);
    m_marks[newFileName].unite(toBeMoved);

    foreach (BaseTextMark *mark, toBeMoved)
        mark->updateFileName(newName);
}

void BaseTextMarkRegistry::allDocumentsRenamed(const QString &oldName, const QString &newName)
{
    Utils::FileName oldFileName = Utils::FileName::fromString(oldName);
    Utils::FileName newFileName = Utils::FileName::fromString(newName);
    if (!m_marks.contains(oldFileName))
        return;

    QSet<BaseTextMark *> oldFileNameMarks = m_marks.value(oldFileName);

    m_marks[newFileName].unite(oldFileNameMarks);
    m_marks[oldFileName].clear();

    foreach (BaseTextMark *mark, oldFileNameMarks)
        mark->updateFileName(newName);
}

BaseTextMark::BaseTextMark(const QString &fileName, int lineNumber)
    : ITextMark(lineNumber), m_fileName(fileName)
{
}

// we need two phase initilization, since we are calling virtual methods
// of BaseTextMark in add() and also accessing widthFactor
// which might be set in the derived constructor
void BaseTextMark::init()
{
    Internal::TextEditorPlugin::instance()->baseTextMarkRegistry()->add(this);
}

BaseTextMark::~BaseTextMark()
{
    // oha we are deleted
    bool b = Internal::TextEditorPlugin::instance()->baseTextMarkRegistry()->remove(this);
    // If you get a assertion in this line, init() was never called
    QTC_CHECK(b)
}

void BaseTextMark::updateFileName(const QString &fileName)
{
    m_fileName = fileName;
}
<commit_msg>Compile fix<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** 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.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/

#include "basetextmark.h"
#include "itexteditor.h"
#include "basetextdocument.h"
#include "texteditorplugin.h"

#include <coreplugin/editormanager/editormanager.h>
#include <coreplugin/documentmanager.h>
#include <extensionsystem/pluginmanager.h>
#include <utils/qtcassert.h>

using namespace TextEditor;
using namespace TextEditor::Internal;

BaseTextMarkRegistry::BaseTextMarkRegistry(QObject *parent)
    : QObject(parent)
{
    Core::EditorManager *em = Core::EditorManager::instance();
    connect(em, SIGNAL(editorOpened(Core::IEditor*)),
        SLOT(editorOpened(Core::IEditor*)));

    Core::DocumentManager *dm = Core::DocumentManager::instance();
    connect(dm, SIGNAL(allDocumentsRenamed(QString,QString)),
            this, SLOT(allDocumentsRenamed(QString,QString)));
    connect(dm, SIGNAL(documentRenamed(Core::IDocument*,QString,QString)),
            this, SLOT(documentRenamed(Core::IDocument*,QString,QString)));
}

void BaseTextMarkRegistry::add(BaseTextMark *mark)
{
    m_marks[Utils::FileName::fromString(mark->fileName())].insert(mark);
    Core::EditorManager *em = Core::EditorManager::instance();
    foreach (Core::IEditor *editor, em->editorsForFileName(mark->fileName())) {
        if (ITextEditor *textEditor = qobject_cast<ITextEditor *>(editor)) {
            ITextMarkable *markableInterface = textEditor->markableInterface();
            if (markableInterface->addMark(mark)) {
                break;
            }
        }
    }
}

bool BaseTextMarkRegistry::remove(BaseTextMark *mark)
{
    return m_marks[Utils::FileName::fromString(mark->fileName())].remove(mark);
}

void BaseTextMarkRegistry::editorOpened(Core::IEditor *editor)
{
    ITextEditor *textEditor = qobject_cast<ITextEditor *>(editor);
    if (!textEditor)
        return;
    if (!m_marks.contains(Utils::FileName::fromString(editor->document()->fileName())))
        return;

    foreach (BaseTextMark *mark, m_marks.value(Utils::FileName::fromString(editor->document()->fileName()))) {
        ITextMarkable *markableInterface = textEditor->markableInterface();
        markableInterface->addMark(mark);
    }
}

void BaseTextMarkRegistry::documentRenamed(Core::IDocument *document, const
                                           QString &oldName, const QString &newName)
{
    TextEditor::BaseTextDocument *baseTextDocument
            = qobject_cast<TextEditor::BaseTextDocument *>(document);
    if (!document)
        return;
    Utils::FileName oldFileName = Utils::FileName::fromString(oldName);
    Utils::FileName newFileName = Utils::FileName::fromString(newName);
    if (!m_marks.contains(oldFileName))
        return;

    QSet<BaseTextMark *> toBeMoved;
    foreach (ITextMark *mark, baseTextDocument->documentMarker()->marks())
        if (BaseTextMark *baseTextMark = dynamic_cast<BaseTextMark *>(mark))
            toBeMoved.insert(baseTextMark);

    m_marks[oldFileName].subtract(toBeMoved);
    m_marks[newFileName].unite(toBeMoved);

    foreach (BaseTextMark *mark, toBeMoved)
        mark->updateFileName(newName);
}

void BaseTextMarkRegistry::allDocumentsRenamed(const QString &oldName, const QString &newName)
{
    Utils::FileName oldFileName = Utils::FileName::fromString(oldName);
    Utils::FileName newFileName = Utils::FileName::fromString(newName);
    if (!m_marks.contains(oldFileName))
        return;

    QSet<BaseTextMark *> oldFileNameMarks = m_marks.value(oldFileName);

    m_marks[newFileName].unite(oldFileNameMarks);
    m_marks[oldFileName].clear();

    foreach (BaseTextMark *mark, oldFileNameMarks)
        mark->updateFileName(newName);
}

BaseTextMark::BaseTextMark(const QString &fileName, int lineNumber)
    : ITextMark(lineNumber), m_fileName(fileName)
{
}

// we need two phase initilization, since we are calling virtual methods
// of BaseTextMark in add() and also accessing widthFactor
// which might be set in the derived constructor
void BaseTextMark::init()
{
    Internal::TextEditorPlugin::instance()->baseTextMarkRegistry()->add(this);
}

BaseTextMark::~BaseTextMark()
{
    // oha we are deleted
    bool b = Internal::TextEditorPlugin::instance()->baseTextMarkRegistry()->remove(this);
    // If you get a assertion in this line, init() was never called
    QTC_CHECK(b);
}

void BaseTextMark::updateFileName(const QString &fileName)
{
    m_fileName = fileName;
}
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* libvisio
 * Version: MPL 1.1 / GPLv2+ / LGPLv2+
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License or as specified alternatively below. You may obtain a copy of
 * the License at http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * Major Contributor(s):
 * Copyright (C) 2011 Fridrich Strba <fridrich.strba@bluewin.ch>
 * Copyright (C) 2011 Eilidh McAdam <tibbylickle@gmail.com>
 *
 *
 * All Rights Reserved.
 *
 * For minor contributions see the git repository.
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPLv2+"), or
 * the GNU Lesser General Public License Version 2 or later (the "LGPLv2+"),
 * in which case the provisions of the GPLv2+ or the LGPLv2+ are applicable
 * instead of those above.
 */

#include <libwpd-stream/libwpd-stream.h>
#include <locale.h>
#include <sstream>
#include <string>
#include "libvisio_utils.h"
#include "VSD5Parser.h"
#include "VSDInternalStream.h"
#include "VSDDocumentStructure.h"
#include "VSDContentCollector.h"
#include "VSDStylesCollector.h"

libvisio::VSD5Parser::VSD5Parser(WPXInputStream *input, libwpg::WPGPaintInterface *painter)
  : VSD6Parser(input, painter)
{}

libvisio::VSD5Parser::~VSD5Parser()
{}

void libvisio::VSD5Parser::readPointer(WPXInputStream *input, Pointer &ptr)
{
  ptr.Type = readU16(input);
  ptr.Format = readU16(input);
  input->seek(4, WPX_SEEK_CUR); // Skip dword
  ptr.Offset = readU32(input);
  ptr.Length = readU32(input);
}

void libvisio::VSD5Parser::readPointerInfo(WPXInputStream *input, unsigned ptrType, unsigned shift, unsigned &listSize, unsigned &pointerCount)
{
  VSD_DEBUG_MSG(("VSD5Parser::readPointerInfo\n"));
  input->seek(shift+0x6, WPX_SEEK_SET);
  listSize = readU16(input);
  switch (ptrType)
  {
  case VSD_TRAILER_STREAM:
    input->seek(shift+0x82, WPX_SEEK_SET);
    break;
  case VSD_STENCILS:
    input->seek(shift+0x1e, WPX_SEEK_SET);
    break;
  case VSD_STENCIL_PAGE:
    input->seek(shift+0x36, WPX_SEEK_SET);
    break;
  default:
    input->seek(shift+0xa, WPX_SEEK_SET);
    break;
  }
  pointerCount = readU16(input);
  VSD_DEBUG_MSG(("VSD5Parser::readPointerInfo ptrType %u shift %u listSize 0x%x pointerCount 0x%x\n", ptrType, shift, listSize, pointerCount));
}

bool libvisio::VSD5Parser::getChunkHeader(WPXInputStream *input)
{
  unsigned char tmpChar = 0;
  while (!input->atEOS() && !tmpChar)
    tmpChar = readU8(input);

  if (input->atEOS())
    return false;
  else
    input->seek(-1, WPX_SEEK_CUR);

  m_header.chunkType = readU16(input);
  m_header.id = readU16(input);
  m_header.level = readU8(input);
  m_header.unknown = readU8(input);

  m_header.list = readU16(input);

  // Certain chunk types seem to always have a trailer
  m_header.trailer = 0;
  if (m_header.list != 0 || m_header.chunkType == 0x76 || m_header.chunkType == 0x73 ||
      m_header.chunkType == 0x72 || m_header.chunkType == 0x71 || m_header.chunkType == 0x70 ||
      m_header.chunkType == 0x6f || m_header.chunkType == 0x6e || m_header.chunkType == 0x6d ||
      m_header.chunkType == 0x6c || m_header.chunkType == 0x6b || m_header.chunkType == 0x6a ||
      m_header.chunkType == 0x69 || m_header.chunkType == 0x68 || m_header.chunkType == 0x67 ||
      m_header.chunkType == 0x66 || m_header.chunkType == 0x65 || m_header.chunkType == 0x64 ||
      m_header.chunkType == 0x2c || m_header.chunkType == 0xd)
    m_header.trailer += 8; // 8 byte trailer

  m_header.dataLength = readU32(input);

  // 0x1f (OLE data) and 0xc9 (Name ID) never have trailer
  if (m_header.chunkType == 0x1f || m_header.chunkType == 0xc9)
  {
    m_header.trailer = 0;
  }
  return true;
}

/* vim:set shiftwidth=2 softtabstop=2 expandtab: */
<commit_msg>Extend the parsing capacity to versions 1 - 5<commit_after>/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* libvisio
 * Version: MPL 1.1 / GPLv2+ / LGPLv2+
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License or as specified alternatively below. You may obtain a copy of
 * the License at http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * Major Contributor(s):
 * Copyright (C) 2011 Fridrich Strba <fridrich.strba@bluewin.ch>
 * Copyright (C) 2011 Eilidh McAdam <tibbylickle@gmail.com>
 *
 *
 * All Rights Reserved.
 *
 * For minor contributions see the git repository.
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPLv2+"), or
 * the GNU Lesser General Public License Version 2 or later (the "LGPLv2+"),
 * in which case the provisions of the GPLv2+ or the LGPLv2+ are applicable
 * instead of those above.
 */

#include <libwpd-stream/libwpd-stream.h>
#include <locale.h>
#include <sstream>
#include <string>
#include "libvisio_utils.h"
#include "VSD5Parser.h"
#include "VSDInternalStream.h"
#include "VSDDocumentStructure.h"
#include "VSDContentCollector.h"
#include "VSDStylesCollector.h"

libvisio::VSD5Parser::VSD5Parser(WPXInputStream *input, libwpg::WPGPaintInterface *painter)
  : VSD6Parser(input, painter)
{}

libvisio::VSD5Parser::~VSD5Parser()
{}

void libvisio::VSD5Parser::readPointer(WPXInputStream *input, Pointer &ptr)
{
  ptr.Type = readU16(input) & 0x00ff;
  ptr.Format = readU16(input) & 0x00ff;
  input->seek(4, WPX_SEEK_CUR); // Skip dword
  ptr.Offset = readU32(input);
  ptr.Length = readU32(input);
}

void libvisio::VSD5Parser::readPointerInfo(WPXInputStream *input, unsigned ptrType, unsigned shift, unsigned &listSize, unsigned &pointerCount)
{
  VSD_DEBUG_MSG(("VSD5Parser::readPointerInfo\n"));
  switch (ptrType)
  {
  case VSD_TRAILER_STREAM:
    input->seek(shift+0x82, WPX_SEEK_SET);
    break;
  case VSD_PAGE:
    input->seek(shift+0x42, WPX_SEEK_SET);
    break;
  case VSD_FONT_LIST:
    input->seek(shift+0x2e, WPX_SEEK_SET);
    break;
  case VSD_STYLES:
    input->seek(shift+0x12, WPX_SEEK_SET);
    break;
  case VSD_STENCILS:
    input->seek(shift+0x1e, WPX_SEEK_SET);
    break;
  case VSD_STENCIL_PAGE:
    input->seek(shift+0x36, WPX_SEEK_SET);
    break;
  default:
    input->seek(shift+0xa, WPX_SEEK_SET);
    break;
  }
  pointerCount = readU16(input);
  VSD_DEBUG_MSG(("VSD5Parser::readPointerInfo ptrType %u shift %u listSize 0x%x pointerCount 0x%x\n", ptrType, shift, listSize, pointerCount));
}

bool libvisio::VSD5Parser::getChunkHeader(WPXInputStream *input)
{
  unsigned char tmpChar = 0;
  while (!input->atEOS() && !tmpChar)
    tmpChar = readU8(input);

  if (input->atEOS())
    return false;
  else
    input->seek(-1, WPX_SEEK_CUR);

  m_header.chunkType = readU16(input);
  m_header.id = readU16(input);
  m_header.level = readU8(input);
  m_header.unknown = readU8(input);

  m_header.list = readU16(input);

  // Certain chunk types seem to always have a trailer
  m_header.trailer = 0;
  if (m_header.list != 0 || m_header.chunkType == 0x76 || m_header.chunkType == 0x73 ||
      m_header.chunkType == 0x72 || m_header.chunkType == 0x71 || m_header.chunkType == 0x70 ||
      m_header.chunkType == 0x6f || m_header.chunkType == 0x6e || m_header.chunkType == 0x6d ||
      m_header.chunkType == 0x6c || m_header.chunkType == 0x6b || m_header.chunkType == 0x6a ||
      m_header.chunkType == 0x69 || m_header.chunkType == 0x68 || m_header.chunkType == 0x67 ||
      m_header.chunkType == 0x66 || m_header.chunkType == 0x65 || m_header.chunkType == 0x64 ||
      m_header.chunkType == 0x2c || m_header.chunkType == 0xd)
    m_header.trailer += 8; // 8 byte trailer

  m_header.dataLength = readU32(input);

  // 0x1f (OLE data) and 0xc9 (Name ID) never have trailer
  if (m_header.chunkType == 0x1f || m_header.chunkType == 0xc9)
  {
    m_header.trailer = 0;
  }
  return true;
}

/* vim:set shiftwidth=2 softtabstop=2 expandtab: */
<|endoftext|>


<commit_before>//
// Matirx.hpp
// ~~~~~~~~~~
//
// Copyright (c) 2014 Rick Yang (rick68 at gmail dot com)
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
//

#ifndef EIGENJS_MATRIX_HPP
#define EIGENJS_MATRIX_HPP

#include <node.h>
#include <v8.h>

#include <nan.h>

#include <eigen3/Eigen/Dense>

#include <sstream>

#define EIGENJS_MATRIX_BINARY_OPERATOR( NAME, OP )                             \
static NAN_METHOD( NAME ) {                                                    \
  const Matrix* obj = node::ObjectWrap::Unwrap<Matrix>( args.This() );         \
  NanScope();                                                                  \
                                                                               \
  if ( args.Length() == 1 && args[0]->IsObject() ) {                           \
    const Matrix* rhs_obj =                                                    \
        node::ObjectWrap::Unwrap<Matrix>( args[0]->ToObject() );               \
                                                                               \
    if ( is_nonconformate_argument( obj, rhs_obj ) ) {                         \
      NanReturnUndefined();                                                    \
    }                                                                          \
                                                                               \
    const matrix_type::Index& rows = obj->matrix_.rows();                      \
    const matrix_type::Index& cols = obj->matrix_.cols();                      \
                                                                               \
    v8::Local<v8::Function> ctr = NanNew( constructor );                       \
    v8::Local<v8::Value> argv[] = {                                            \
        NanNew<v8::Integer>( rows )                                            \
      , NanNew<v8::Integer>( cols )                                            \
    };                                                                         \
                                                                               \
    v8::Local<v8::Object> new_matrix = ctr->NewInstance(                       \
        sizeof( argv ) / sizeof( v8::Local<v8::Value> )                        \
      , argv                                                                   \
    );                                                                         \
                                                                               \
    Matrix* new_obj = node::ObjectWrap::Unwrap<Matrix>( new_matrix );          \
    new_obj->matrix_ = obj->matrix_ OP rhs_obj->matrix_;                       \
                                                                               \
    NanReturnValue( new_matrix );                                              \
  }                                                                            \
                                                                               \
  NanReturnUndefined();                                                        \
}                                                                              \
/**/

#define EIGENJS_MATRIX_BINARY_OPERATOR_COMMUTATIVE( NAME, OP )                 \
static NAN_METHOD( NAME ) {                                                    \
  Matrix* obj = node::ObjectWrap::Unwrap<Matrix>( args.This() );               \
  NanScope();                                                                  \
                                                                               \
  if ( args.Length() == 1 && args[0]->IsObject() ) {                           \
    const Matrix* rhs_obj =                                                    \
        node::ObjectWrap::Unwrap<Matrix>( args[0]->ToObject() );               \
                                                                               \
    if ( is_nonconformate_argument( obj, rhs_obj ) ) {                         \
      NanReturnUndefined();                                                    \
    }                                                                          \
                                                                               \
    obj->matrix_ OP##= rhs_obj->matrix_;                                       \
                                                                               \
    NanReturnValue( args.This() );                                             \
  }                                                                            \
                                                                               \
  NanReturnUndefined();                                                        \
}                                                                              \
/**/

namespace EigenJS {

class Matrix : public node::ObjectWrap {
 public:
  static void Init(v8::Handle<v8::Object> exports) {
    NanScope();

    v8::Local<v8::FunctionTemplate> tpl = NanNew<v8::FunctionTemplate>(New);
    tpl->SetClassName(NanNew("Matrix"));
    tpl->InstanceTemplate()->SetInternalFieldCount(1);

    NODE_SET_PROTOTYPE_METHOD(tpl, "rows", rows);
    NODE_SET_PROTOTYPE_METHOD(tpl, "cols", cols);
    NODE_SET_PROTOTYPE_METHOD(tpl, "set", set);
    NODE_SET_PROTOTYPE_METHOD(tpl, "get", get);

    NODE_SET_PROTOTYPE_METHOD(tpl, "add", add);
    NODE_SET_PROTOTYPE_METHOD(tpl, "adda", adda);
    NODE_SET_PROTOTYPE_METHOD(tpl, "sub", sub);
    NODE_SET_PROTOTYPE_METHOD(tpl, "suba", suba);

    NODE_SET_PROTOTYPE_METHOD(tpl, "toString", toString);

    NanAssignPersistent(constructor, tpl->GetFunction());
    exports->Set(NanNew("Matrix"), tpl->GetFunction());
  }

  static NAN_METHOD(rows) {
    const Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
    NanScope();

    NanReturnValue(NanNew<v8::Integer>(obj->matrix_.rows()));
  }

  static NAN_METHOD(cols) {
    const Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
    NanScope();

    NanReturnValue(NanNew<v8::Integer>(obj->matrix_.cols()));
  }

  static NAN_METHOD(set) {
    Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
    NanScope();

    if (args.Length() == 1 && args[0]->IsArray()) {
      v8::Local<v8::Array> array = args[0].As<v8::Array>();
      uint32_t len = array->Length();
      const matrix_type::Index& rows = obj->matrix_.rows();
      const matrix_type::Index& cols = obj->matrix_.cols();
      const matrix_type::Index& elems = rows * cols;

      if (len != elems) {
        len < rows * cols
          ? NanThrowError("Too few coefficients passed to Matrix")
          : NanThrowError("Too many coefficients passed to Matrix");
        NanReturnUndefined();
      }

      for (uint32_t i = 0; i < len; ++i) {
        v8::Local<v8::Value> elem = array->Get(i);
        obj->matrix_(i / cols, i % cols) = elem->NumberValue();
      }
    } else if (
        args.Length() == 3 &&
        args[0]->IsNumber() &&
        args[1]->IsNumber() &&
        args[2]->IsNumber()) {
      const matrix_type::Index& row = args[0]->Uint32Value();
      const matrix_type::Index& col = args[1]->Uint32Value();
      const element_type& value = args[2]->NumberValue();

      if (is_out_of_range(obj->matrix_, row, col))
        NanReturnUndefined();

      obj->matrix_(row, col) = value;
    }

    NanReturnValue(NanNew(args.This()));
  }

  static NAN_METHOD(get) {
    const Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
    NanScope();

    if (args.Length() == 2 &&
        args[0]->IsNumber() &&
        args[1]->IsNumber()) {
      matrix_type::Index row = args[0]->Uint32Value();
      matrix_type::Index col = args[1]->Uint32Value();

      if (is_out_of_range(obj->matrix_, row, col))
        NanReturnUndefined();

      element_type value = obj->matrix_(row, col);
      NanReturnValue(NanNew(value));
    }

    NanReturnUndefined();
  }

  EIGENJS_MATRIX_BINARY_OPERATOR(add, +)
  EIGENJS_MATRIX_BINARY_OPERATOR_COMMUTATIVE(adda, +)

  EIGENJS_MATRIX_BINARY_OPERATOR(sub, -)
  EIGENJS_MATRIX_BINARY_OPERATOR_COMMUTATIVE(suba, -)

  static NAN_METHOD(toString) {
    const Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
    NanScope();

    std::ostringstream result;
    result << obj->matrix_;

    NanReturnValue(NanNew(result.str().c_str()));
  }

 private:
  typedef double element_type;
  typedef Eigen::Matrix<
      element_type
    , Eigen::Dynamic
    , Eigen::Dynamic
  > matrix_type;

  Matrix(matrix_type::Index rows, matrix_type::Index cols)
    : matrix_(matrix_type::Zero(rows, cols))
  {}
  ~Matrix() {}

  static NAN_METHOD(New) {
    NanScope();

    if (args.Length() < 2) {
      NanThrowError("Tried creating matrix without rows and columns arguments");
      NanReturnUndefined();
    }

    if (args.IsConstructCall()) {
      matrix_type::Index rows = args[0]->Uint32Value();
      matrix_type::Index columns = args[1]->Uint32Value();
      Matrix* obj = new Matrix(rows, columns);
      obj->Wrap(args.This());
      NanReturnValue(args.This());
    } else {
      v8::Local<v8::Function> ctr = NanNew(constructor);
      v8::Local<v8::Value> argv[] = {args[0], args[1]};
      NanReturnValue(
        ctr->NewInstance(
              sizeof(argv) / sizeof(v8::Local<v8::Value>)
            , argv
          )
      );
    }
  }

  static v8::Persistent<v8::Function> constructor;

 private:
  static bool is_out_of_range(
      const matrix_type& matrix
    , const matrix_type::Index& row
    , const matrix_type::Index& col) {
    return row < 0 || row >= matrix.rows() || col < 0 || col >= matrix.cols()
      ? NanThrowError("Row or column numbers are out of range"), true
      : false;
  }

  static bool is_nonconformate_argument(
      const Matrix* const& op1
    , const Matrix* const& op2) {
    return op1->matrix_.rows() != op2->matrix_.rows() ||
           op1->matrix_.cols() != op2->matrix_.cols()
      ? NanThrowError("Nonconformant arguments"), true
      : false;
  }

 private:
  matrix_type matrix_;
};

v8::Persistent<v8::Function> Matrix::constructor;

}  // namespace EigenJS

#undef EIGENJS_MATRIX_BINARY_OPERATOR

#endif  // EIGENJS_MATRIX_HPP
<commit_msg>src: improved to check Matrix itself<commit_after>//
// Matirx.hpp
// ~~~~~~~~~~
//
// Copyright (c) 2014 Rick Yang (rick68 at gmail dot com)
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
//

#ifndef EIGENJS_MATRIX_HPP
#define EIGENJS_MATRIX_HPP

#include <node.h>
#include <v8.h>

#include <nan.h>

#include <eigen3/Eigen/Dense>

#include <sstream>

#define EIGENJS_MATRIX_BINARY_OPERATOR( NAME, OP )                             \
static NAN_METHOD( NAME ) {                                                    \
  const Matrix* obj = node::ObjectWrap::Unwrap<Matrix>( args.This() );         \
  NanScope();                                                                  \
                                                                               \
  if ( args.Length() == 1 && HasInstance( args[0] ) ) {                        \
    const Matrix* rhs_obj =                                                    \
        node::ObjectWrap::Unwrap<Matrix>( args[0]->ToObject() );               \
                                                                               \
    if ( is_nonconformate_argument( obj, rhs_obj ) ) {                         \
      NanReturnUndefined();                                                    \
    }                                                                          \
                                                                               \
    const matrix_type::Index& rows = obj->matrix_.rows();                      \
    const matrix_type::Index& cols = obj->matrix_.cols();                      \
                                                                               \
    v8::Local<v8::Function> ctr = NanNew( constructor );                       \
    v8::Local<v8::Value> argv[] = {                                            \
        NanNew<v8::Integer>( rows )                                            \
      , NanNew<v8::Integer>( cols )                                            \
    };                                                                         \
                                                                               \
    v8::Local<v8::Object> new_matrix = ctr->NewInstance(                       \
        sizeof( argv ) / sizeof( v8::Local<v8::Value> )                        \
      , argv                                                                   \
    );                                                                         \
                                                                               \
    Matrix* new_obj = node::ObjectWrap::Unwrap<Matrix>( new_matrix );          \
    new_obj->matrix_ = obj->matrix_ OP rhs_obj->matrix_;                       \
                                                                               \
    NanReturnValue( new_matrix );                                              \
  }                                                                            \
                                                                               \
  NanReturnUndefined();                                                        \
}                                                                              \
/**/

#define EIGENJS_MATRIX_BINARY_OPERATOR_COMMUTATIVE( NAME, OP )                 \
static NAN_METHOD( NAME ) {                                                    \
  Matrix* obj = node::ObjectWrap::Unwrap<Matrix>( args.This() );               \
  NanScope();                                                                  \
                                                                               \
  if ( args.Length() == 1 && HasInstance( args[0] ) ) {                        \
    const Matrix* rhs_obj =                                                    \
        node::ObjectWrap::Unwrap<Matrix>( args[0]->ToObject() );               \
                                                                               \
    if ( is_nonconformate_argument( obj, rhs_obj ) ) {                         \
      NanReturnUndefined();                                                    \
    }                                                                          \
                                                                               \
    obj->matrix_ OP##= rhs_obj->matrix_;                                       \
                                                                               \
    NanReturnValue( args.This() );                                             \
  }                                                                            \
                                                                               \
  NanReturnUndefined();                                                        \
}                                                                              \
/**/

namespace EigenJS {

class Matrix : public node::ObjectWrap {
 public:
  static void Init(v8::Handle<v8::Object> exports) {
    NanScope();

    v8::Local<v8::FunctionTemplate> tpl = NanNew<v8::FunctionTemplate>(New);
    tpl->SetClassName(NanNew("Matrix"));
    tpl->InstanceTemplate()->SetInternalFieldCount(1);

    NODE_SET_PROTOTYPE_METHOD(tpl, "rows", rows);
    NODE_SET_PROTOTYPE_METHOD(tpl, "cols", cols);
    NODE_SET_PROTOTYPE_METHOD(tpl, "set", set);
    NODE_SET_PROTOTYPE_METHOD(tpl, "get", get);

    NODE_SET_PROTOTYPE_METHOD(tpl, "add", add);
    NODE_SET_PROTOTYPE_METHOD(tpl, "adda", adda);
    NODE_SET_PROTOTYPE_METHOD(tpl, "sub", sub);
    NODE_SET_PROTOTYPE_METHOD(tpl, "suba", suba);

    NODE_SET_PROTOTYPE_METHOD(tpl, "toString", toString);

    NanAssignPersistent(constructor, tpl->GetFunction());
    exports->Set(NanNew("Matrix"), tpl->GetFunction());

    NanAssignPersistent(function_template, tpl);
  }

  static NAN_METHOD(rows) {
    const Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
    NanScope();

    NanReturnValue(NanNew<v8::Integer>(obj->matrix_.rows()));
  }

  static NAN_METHOD(cols) {
    const Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
    NanScope();

    NanReturnValue(NanNew<v8::Integer>(obj->matrix_.cols()));
  }

  static NAN_METHOD(set) {
    Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
    NanScope();

    if (args.Length() == 1 && args[0]->IsArray()) {
      v8::Local<v8::Array> array = args[0].As<v8::Array>();
      uint32_t len = array->Length();
      const matrix_type::Index& rows = obj->matrix_.rows();
      const matrix_type::Index& cols = obj->matrix_.cols();
      const matrix_type::Index& elems = rows * cols;

      if (len != elems) {
        len < rows * cols
          ? NanThrowError("Too few coefficients passed to Matrix")
          : NanThrowError("Too many coefficients passed to Matrix");
        NanReturnUndefined();
      }

      for (uint32_t i = 0; i < len; ++i) {
        v8::Local<v8::Value> elem = array->Get(i);
        obj->matrix_(i / cols, i % cols) = elem->NumberValue();
      }
    } else if (
        args.Length() == 3 &&
        args[0]->IsNumber() &&
        args[1]->IsNumber() &&
        args[2]->IsNumber()) {
      const matrix_type::Index& row = args[0]->Uint32Value();
      const matrix_type::Index& col = args[1]->Uint32Value();
      const element_type& value = args[2]->NumberValue();

      if (is_out_of_range(obj->matrix_, row, col))
        NanReturnUndefined();

      obj->matrix_(row, col) = value;
    }

    NanReturnValue(NanNew(args.This()));
  }

  static NAN_METHOD(get) {
    const Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
    NanScope();

    if (args.Length() == 2 &&
        args[0]->IsNumber() &&
        args[1]->IsNumber()) {
      matrix_type::Index row = args[0]->Uint32Value();
      matrix_type::Index col = args[1]->Uint32Value();

      if (is_out_of_range(obj->matrix_, row, col))
        NanReturnUndefined();

      element_type value = obj->matrix_(row, col);
      NanReturnValue(NanNew(value));
    }

    NanReturnUndefined();
  }

  EIGENJS_MATRIX_BINARY_OPERATOR(add, +)
  EIGENJS_MATRIX_BINARY_OPERATOR_COMMUTATIVE(adda, +)

  EIGENJS_MATRIX_BINARY_OPERATOR(sub, -)
  EIGENJS_MATRIX_BINARY_OPERATOR_COMMUTATIVE(suba, -)

  static NAN_METHOD(toString) {
    const Matrix* obj = node::ObjectWrap::Unwrap<Matrix>(args.This());
    NanScope();

    std::ostringstream result;
    result << obj->matrix_;

    NanReturnValue(NanNew(result.str().c_str()));
  }

 private:
  typedef double element_type;
  typedef Eigen::Matrix<
      element_type
    , Eigen::Dynamic
    , Eigen::Dynamic
  > matrix_type;

  Matrix(matrix_type::Index rows, matrix_type::Index cols)
    : matrix_(matrix_type::Zero(rows, cols))
  {}
  ~Matrix() {}

  static NAN_METHOD(New) {
    NanScope();

    if (args.Length() < 2) {
      NanThrowError("Tried creating matrix without rows and columns arguments");
      NanReturnUndefined();
    }

    if (args.IsConstructCall()) {
      matrix_type::Index rows = args[0]->Uint32Value();
      matrix_type::Index columns = args[1]->Uint32Value();
      Matrix* obj = new Matrix(rows, columns);
      obj->Wrap(args.This());
      NanReturnValue(args.This());
    } else {
      v8::Local<v8::Function> ctr = NanNew(constructor);
      v8::Local<v8::Value> argv[] = {args[0], args[1]};
      NanReturnValue(
        ctr->NewInstance(
              sizeof(argv) / sizeof(v8::Local<v8::Value>)
            , argv
          )
      );
    }
  }

  static bool HasInstance(const v8::Handle<v8::Value>& value) {
    return function_template->HasInstance(value);
  }

  static v8::Persistent<v8::FunctionTemplate> function_template;
  static v8::Persistent<v8::Function> constructor;

 private:
  static bool is_out_of_range(
      const matrix_type& matrix
    , const matrix_type::Index& row
    , const matrix_type::Index& col) {
    return row < 0 || row >= matrix.rows() || col < 0 || col >= matrix.cols()
      ? NanThrowError("Row or column numbers are out of range"), true
      : false;
  }

  static bool is_nonconformate_argument(
      const Matrix* const& op1
    , const Matrix* const& op2) {
    return op1->matrix_.rows() != op2->matrix_.rows() ||
           op1->matrix_.cols() != op2->matrix_.cols()
      ? NanThrowError("Nonconformant arguments"), true
      : false;
  }

 private:
  matrix_type matrix_;
};

v8::Persistent<v8::FunctionTemplate> Matrix::function_template;
v8::Persistent<v8::Function> Matrix::constructor;

}  // namespace EigenJS

#undef EIGENJS_MATRIX_BINARY_OPERATOR

#endif  // EIGENJS_MATRIX_HPP
<|endoftext|>


<commit_before>#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <cstring>
#include <string>
#include <vector>
#include <iomanip>
#include <cmath>
#include <list>
#include <bitset>

using namespace std;

#define ll long long
#define lson l,mid,id<<1
#define rson mid+1,r,id<<1|1

typedef pair<int, int>pii;
typedef pair<ll, ll>pll;
typedef pair<double, double>pdd;

const double eps = 1e-6;
const ll  LINF = 0x3f3f3f3f3f3f3f3fLL;
const int INF = 0x3f3f3f3f;
const double FINF = 1e18;

#define x first
#define y second

#define REP(i,j,k) for(int i =(j);i<=(k);i++)
#define REPD(i,j,k) for(int i =(j);i>=(k);i--)
#define print(x) cout<<(x)<<endl;
#define IOS ios::sync_with_stdio(0);cin.tie(0);

int p[50]={0};

void Init(){

	p[2]=p[3]=p[5]=p[7]=p[11]=p[13]=p[17]=p[23]=p[29]=p[31]=1;

	return ;
}

int a[30]={0};
int count1;
int m;
int add(int cur,int i){

	int sum=0;

	REP(i,0,m-1){
		sum+=a[cur-i];
	}
	if(p[sum]==1){
		return 1;
	}
	else{
		return 0;
	}

}
int n;

int dfs(int cur){
	REP(i,0,9){
		if(add(cur,i)){
			if(cur==n+5){
				count1++;
			}else{
				a[cur++]=i;
				dfs(cur);
			}

		}
	}
}
void Solve(){
	scanf("%d%d",&n,&m);
	dfs(5);
	cout<<count1<<endl;
	return ;
}

int main(){
#ifdef LOCAL
	freopen("uoj18025.in","r",stdin);
#endif

 	int t;
 	scanf("%d",&t);
	Init(),Solve();
	return 0;
}<commit_msg>update uoj18025<commit_after>#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <cstring>
#include <string>
#include <vector>
#include <iomanip>
#include <cmath>
#include <list>
#include <bitset>

using namespace std;

#define ll long long
#define lson l,mid,id<<1
#define rson mid+1,r,id<<1|1

typedef pair<int, int>pii;
typedef pair<ll, ll>pll;
typedef pair<double, double>pdd;

const double eps = 1e-6;
const ll  LINF = 0x3f3f3f3f3f3f3f3fLL;
const int INF = 0x3f3f3f3f;
const double FINF = 1e18;

#define x first
#define y second

#define REP(i,j,k) for(int i =(j);i<=(k);i++)
#define REPD(i,j,k) for(int i =(j);i>=(k);i--)
#define print(x) cout<<(x)<<endl;
#define IOS ios::sync_with_stdio(0);cin.tie(0);

int p[50]={0};

void Init(){

	p[2]=p[3]=p[5]=p[7]=p[11]=p[13]=p[17]=p[23]=p[29]=p[31]=1;

	return ;
}

int a[30]={0};
int count1;
int m;
int add(int cur,int i){

	int sum=0;

	REP(i,0,m-1){
		sum+=a[cur-i];
	}
	if(p[sum]==1){
		return 1;
	}
	else{
		return 0;
	}

}
int n;

int dfs(int cur){
	REP(i,0,9){
		if(add(cur,i)){
			print(i);
			if(cur==n+5){
				count1++;
			}else{
				a[cur++]=i;
				dfs(cur);
			}

		}
	}
}
void Solve(){
	scanf("%d%d",&n,&m);
	dfs(5);
	cout<<count1<<endl;
	return ;
}

int main(){
#ifdef LOCAL
	freopen("uoj18025.in","r",stdin);
#endif

 	int t;
 	scanf("%d",&t);
	Init(),Solve();
	return 0;
}<|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2015, Image Engine Design Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//      * Redistributions of source code must retain the above
//        copyright notice, this list of conditions and the following
//        disclaimer.
//
//      * 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.
//
//      * Neither the name of John Haddon nor the names of
//        any other contributors to this software may be used to endorse or
//        promote products derived from this software without specific prior
//        written permission.
//
//  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.
//
//////////////////////////////////////////////////////////////////////////

#include "StringPlugBinding.h"

#include "GafferBindings/ValuePlugBinding.h"

#include "Gaffer/StringPlug.h"

#include "IECorePython/ScopedGILRelease.h"

using namespace boost::python;
using namespace Gaffer;
using namespace GafferBindings;

namespace
{

void setValue( StringPlug *plug, const std::string& value )
{
	// we use a GIL release here to prevent a lock in the case where this triggers a graph
	// evaluation which decides to go back into python on another thread:
	IECorePython::ScopedGILRelease r;
	plug->setValue( value );
}

std::string getValue( const StringPlug *plug, const IECore::MurmurHash *precomputedHash )
{
	// Must release GIL in case computation spawns threads which need
	// to reenter Python.
	IECorePython::ScopedGILRelease r;
	return plug->getValue( precomputedHash );
}

std::string substitutionsRepr( unsigned substitutions )
{
	static const IECore::StringAlgo::Substitutions values[] = {
		IECore::StringAlgo::FrameSubstitutions,
		IECore::StringAlgo::VariableSubstitutions,
		IECore::StringAlgo::EscapeSubstitutions,
		IECore::StringAlgo::TildeSubstitutions,
		IECore::StringAlgo::NoSubstitutions
	};
	static const char *names[] = { "FrameSubstitutions", "VariableSubstitutions", "EscapeSubstitutions", "TildeSubstitutions", nullptr };

	if( substitutions == IECore::StringAlgo::AllSubstitutions )
	{
		return "IECore.StringAlgo.Substitutions.AllSubstitutions";
	}
	else if( substitutions == IECore::StringAlgo::NoSubstitutions )
	{
		return "IECore.StringAlgo.Substitutions.NoSubstitutions";
	}

	std::string result;
	for( int i = 0; names[i]; ++i )
	{
		if( substitutions & values[i] )
		{
			if( result.size() )
			{
				result += " | ";
			}
			result += "IECore.StringAlgo.Substitutions." + std::string( names[i] );
		}
	}

	return result;
}

std::string serialisationRepr( const Gaffer::StringPlug *plug, Serialisation *serialisation )
{
	std::string extraArguments;
	if( plug->substitutions() != IECore::StringAlgo::AllSubstitutions )
	{
		extraArguments = "substitutions = " + substitutionsRepr( plug->substitutions() );
	}
	return ValuePlugSerialiser::repr( plug, extraArguments, serialisation );
}

std::string repr( const Gaffer::StringPlug *plug )
{
	return serialisationRepr( plug, nullptr );
}

class StringPlugSerialiser : public ValuePlugSerialiser
{

	public :

		std::string constructor( const Gaffer::GraphComponent *graphComponent, Serialisation &serialisation ) const override
		{
			return serialisationRepr( static_cast<const StringPlug *>( graphComponent ), &serialisation );
		}

};

} // namespace

void GafferModule::bindStringPlug()
{

	PlugClass<StringPlug>()
		.def(
			boost::python::init<const std::string &, Gaffer::Plug::Direction, const std::string &, unsigned, unsigned>(
				(
					boost::python::arg_( "name" )=Gaffer::GraphComponent::defaultName<StringPlug>(),
					boost::python::arg_( "direction" )=Gaffer::Plug::In,
					boost::python::arg_( "defaultValue" )="",
					boost::python::arg_( "flags" )=Gaffer::Plug::Default,
					boost::python::arg_( "substitutions" )=IECore::StringAlgo::AllSubstitutions
				)
			)
		)
		.def( "__repr__", &repr )
		.def( "substitutions", &StringPlug::substitutions )
		.def( "defaultValue", &StringPlug::defaultValue, return_value_policy<boost::python::copy_const_reference>() )
		.def( "setValue", &setValue )
		.def( "getValue", &getValue, ( boost::python::arg( "_precomputedHash" ) = object() ) )
	;

	Serialisation::registerSerialiser( StringPlug::staticTypeId(), new StringPlugSerialiser );

}
<commit_msg>StringPlugBinding : Add missing import to serialisation<commit_after>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2015, Image Engine Design Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//      * Redistributions of source code must retain the above
//        copyright notice, this list of conditions and the following
//        disclaimer.
//
//      * 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.
//
//      * Neither the name of John Haddon nor the names of
//        any other contributors to this software may be used to endorse or
//        promote products derived from this software without specific prior
//        written permission.
//
//  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.
//
//////////////////////////////////////////////////////////////////////////

#include "StringPlugBinding.h"

#include "GafferBindings/ValuePlugBinding.h"

#include "Gaffer/StringPlug.h"

#include "IECorePython/ScopedGILRelease.h"

using namespace boost::python;
using namespace Gaffer;
using namespace GafferBindings;

namespace
{

void setValue( StringPlug *plug, const std::string& value )
{
	// we use a GIL release here to prevent a lock in the case where this triggers a graph
	// evaluation which decides to go back into python on another thread:
	IECorePython::ScopedGILRelease r;
	plug->setValue( value );
}

std::string getValue( const StringPlug *plug, const IECore::MurmurHash *precomputedHash )
{
	// Must release GIL in case computation spawns threads which need
	// to reenter Python.
	IECorePython::ScopedGILRelease r;
	return plug->getValue( precomputedHash );
}

std::string substitutionsRepr( unsigned substitutions )
{
	static const IECore::StringAlgo::Substitutions values[] = {
		IECore::StringAlgo::FrameSubstitutions,
		IECore::StringAlgo::VariableSubstitutions,
		IECore::StringAlgo::EscapeSubstitutions,
		IECore::StringAlgo::TildeSubstitutions,
		IECore::StringAlgo::NoSubstitutions
	};
	static const char *names[] = { "FrameSubstitutions", "VariableSubstitutions", "EscapeSubstitutions", "TildeSubstitutions", nullptr };

	if( substitutions == IECore::StringAlgo::AllSubstitutions )
	{
		return "IECore.StringAlgo.Substitutions.AllSubstitutions";
	}
	else if( substitutions == IECore::StringAlgo::NoSubstitutions )
	{
		return "IECore.StringAlgo.Substitutions.NoSubstitutions";
	}

	std::string result;
	for( int i = 0; names[i]; ++i )
	{
		if( substitutions & values[i] )
		{
			if( result.size() )
			{
				result += " | ";
			}
			result += "IECore.StringAlgo.Substitutions." + std::string( names[i] );
		}
	}

	return result;
}

std::string serialisationRepr( const Gaffer::StringPlug *plug, Serialisation *serialisation )
{
	std::string extraArguments;
	if( plug->substitutions() != IECore::StringAlgo::AllSubstitutions )
	{
		extraArguments = "substitutions = " + substitutionsRepr( plug->substitutions() );
		if( serialisation )
		{
			serialisation->addModule( "IECore" );
		}
	}
	return ValuePlugSerialiser::repr( plug, extraArguments, serialisation );
}

std::string repr( const Gaffer::StringPlug *plug )
{
	return serialisationRepr( plug, nullptr );
}

class StringPlugSerialiser : public ValuePlugSerialiser
{

	public :

		std::string constructor( const Gaffer::GraphComponent *graphComponent, Serialisation &serialisation ) const override
		{
			return serialisationRepr( static_cast<const StringPlug *>( graphComponent ), &serialisation );
		}

};

} // namespace

void GafferModule::bindStringPlug()
{

	PlugClass<StringPlug>()
		.def(
			boost::python::init<const std::string &, Gaffer::Plug::Direction, const std::string &, unsigned, unsigned>(
				(
					boost::python::arg_( "name" )=Gaffer::GraphComponent::defaultName<StringPlug>(),
					boost::python::arg_( "direction" )=Gaffer::Plug::In,
					boost::python::arg_( "defaultValue" )="",
					boost::python::arg_( "flags" )=Gaffer::Plug::Default,
					boost::python::arg_( "substitutions" )=IECore::StringAlgo::AllSubstitutions
				)
			)
		)
		.def( "__repr__", &repr )
		.def( "substitutions", &StringPlug::substitutions )
		.def( "defaultValue", &StringPlug::defaultValue, return_value_policy<boost::python::copy_const_reference>() )
		.def( "setValue", &setValue )
		.def( "getValue", &getValue, ( boost::python::arg( "_precomputedHash" ) = object() ) )
	;

	Serialisation::registerSerialiser( StringPlug::staticTypeId(), new StringPlugSerialiser );

}
<|endoftext|>


<commit_before>/*
  This file is part of Ingen.
  Copyright 2007-2015 David Robillard <http://drobilla.net/>

  Ingen is free software: you can redistribute it and/or modify it under the
  terms of the GNU Affero General Public License as published by the Free
  Software Foundation, either version 3 of the License, or any later version.

  Ingen 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 Affero General Public License for details.

  You should have received a copy of the GNU Affero General Public License
  along with Ingen.  If not, see <http://www.gnu.org/licenses/>.
*/

#ifndef INGEN_URIMAP_HPP
#define INGEN_URIMAP_HPP

#include <cstdint>
#include <mutex>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>

#include "ingen/LV2Features.hpp"
#include "ingen/ingen.h"
#include "ingen/types.hpp"
#include "lv2/lv2plug.in/ns/ext/urid/urid.h"
#include "lv2/lv2plug.in/ns/lv2core/lv2.h"
#include "raul/Noncopyable.hpp"

namespace Ingen {

class Log;
class Node;
class World;

/** URI to integer map and implementation of LV2 URID extension.
 * @ingroup IngenShared
 */
class INGEN_API URIMap : public Raul::Noncopyable {
public:
	URIMap(Log& log, LV2_URID_Map* map, LV2_URID_Unmap* unmap);

	uint32_t    map_uri(const char* uri);
	uint32_t    map_uri(const std::string& uri) { return map_uri(uri.c_str()); }
	const char* unmap_uri(uint32_t urid) const;

	class Feature : public LV2Features::Feature {
	public:
		Feature(const char* URI, void* data) {
			_feature.URI  = URI;
			_feature.data = data;
		}

		const char* uri() const override { return _feature.URI; }

		SPtr<LV2_Feature> feature(World*, Node*) override {
			return SPtr<LV2_Feature>(&_feature, NullDeleter<LV2_Feature>);
		}

	private:
		LV2_Feature _feature;
	};

	struct URIDMapFeature : public Feature {
		URIDMapFeature(URIMap* map, LV2_URID_Map* impl, Log& log);
		LV2_URID        map(const char* uri);
		static LV2_URID default_map(LV2_URID_Map_Handle h, const char* c_uri);
		LV2_URID_Map urid_map;
		Log&         log;
	};

	struct URIDUnmapFeature : public Feature {
		URIDUnmapFeature(URIMap* map, LV2_URID_Unmap* impl);
		const char*        unmap(const LV2_URID urid);
		static const char* default_unmap(LV2_URID_Map_Handle h, LV2_URID urid);
		LV2_URID_Unmap urid_unmap;
	};

	SPtr<URIDMapFeature>   urid_map_feature()   { return _urid_map_feature; }
	SPtr<URIDUnmapFeature> urid_unmap_feature() { return _urid_unmap_feature; }

private:
	friend class URIDMapFeature;
	friend class URIDUnMapFeature;

	SPtr<URIDMapFeature>   _urid_map_feature;
	SPtr<URIDUnmapFeature> _urid_unmap_feature;

	std::mutex                                _mutex;
	std::unordered_map<std::string, LV2_URID> _map;
	std::vector<std::string>                  _unmap;
};

} // namespace Ingen

#endif // INGEN_URIMAP_HPP
<commit_msg>Fix mismatched struct/class declarations<commit_after>/*
  This file is part of Ingen.
  Copyright 2007-2015 David Robillard <http://drobilla.net/>

  Ingen is free software: you can redistribute it and/or modify it under the
  terms of the GNU Affero General Public License as published by the Free
  Software Foundation, either version 3 of the License, or any later version.

  Ingen 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 Affero General Public License for details.

  You should have received a copy of the GNU Affero General Public License
  along with Ingen.  If not, see <http://www.gnu.org/licenses/>.
*/

#ifndef INGEN_URIMAP_HPP
#define INGEN_URIMAP_HPP

#include <cstdint>
#include <mutex>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>

#include "ingen/LV2Features.hpp"
#include "ingen/ingen.h"
#include "ingen/types.hpp"
#include "lv2/lv2plug.in/ns/ext/urid/urid.h"
#include "lv2/lv2plug.in/ns/lv2core/lv2.h"
#include "raul/Noncopyable.hpp"

namespace Ingen {

class Log;
class Node;
class World;

/** URI to integer map and implementation of LV2 URID extension.
 * @ingroup IngenShared
 */
class INGEN_API URIMap : public Raul::Noncopyable {
public:
	URIMap(Log& log, LV2_URID_Map* map, LV2_URID_Unmap* unmap);

	uint32_t    map_uri(const char* uri);
	uint32_t    map_uri(const std::string& uri) { return map_uri(uri.c_str()); }
	const char* unmap_uri(uint32_t urid) const;

	class Feature : public LV2Features::Feature {
	public:
		Feature(const char* URI, void* data) {
			_feature.URI  = URI;
			_feature.data = data;
		}

		const char* uri() const override { return _feature.URI; }

		SPtr<LV2_Feature> feature(World*, Node*) override {
			return SPtr<LV2_Feature>(&_feature, NullDeleter<LV2_Feature>);
		}

	private:
		LV2_Feature _feature;
	};

	struct URIDMapFeature : public Feature {
		URIDMapFeature(URIMap* map, LV2_URID_Map* impl, Log& log);
		LV2_URID        map(const char* uri);
		static LV2_URID default_map(LV2_URID_Map_Handle h, const char* c_uri);
		LV2_URID_Map urid_map;
		Log&         log;
	};

	struct URIDUnmapFeature : public Feature {
		URIDUnmapFeature(URIMap* map, LV2_URID_Unmap* impl);
		const char*        unmap(const LV2_URID urid);
		static const char* default_unmap(LV2_URID_Map_Handle h, LV2_URID urid);
		LV2_URID_Unmap urid_unmap;
	};

	SPtr<URIDMapFeature>   urid_map_feature()   { return _urid_map_feature; }
	SPtr<URIDUnmapFeature> urid_unmap_feature() { return _urid_unmap_feature; }

private:
	friend struct URIDMapFeature;
	friend struct URIDUnMapFeature;

	SPtr<URIDMapFeature>   _urid_map_feature;
	SPtr<URIDUnmapFeature> _urid_unmap_feature;

	std::mutex                                _mutex;
	std::unordered_map<std::string, LV2_URID> _map;
	std::vector<std::string>                  _unmap;
};

} // namespace Ingen

#endif // INGEN_URIMAP_HPP
<|endoftext|>


<commit_before>/**
 * @file
 *
 * @brief Tests for yamlcpp plugin
 *
 * @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
 *
 */

// -- Imports ------------------------------------------------------------------------------------------------------------------------------

#include "yamlcpp.hpp"

#include <kdbmodule.h>
#include <kdbprivate.h>

#include <tests.h>
#include <tests.hpp>

using ckdb::keyNew;

using CppKeySet = kdb::KeySet;
using CppKey = kdb::Key;

// -- Macros -------------------------------------------------------------------------------------------------------------------------------

#define OPEN_PLUGIN(parentName, filepath)                                                                                \
	CppKeySet modules{ 0, KS_END };                                                                                \
	CppKeySet config{ 0, KS_END };                                                                                \
	elektraModulesInit (modules.getKeySet (), 0);                                                                                \
	CppKey parent{ parentName, KEY_VALUE, filepath, KEY_END };                                                                         \
	Plugin * plugin = elektraPluginOpen ("yamlcpp", modules.getKeySet (), config.getKeySet (), *parent);                               \
	exit_if_fail (plugin != NULL, "Could not open yamlcpp plugin")

#define CLOSE_PLUGIN()                                                                                \
	elektraPluginClose (plugin, 0);                                                                                \
	elektraModulesClose (modules.getKeySet (), 0);                                                                                \
	ksDel (modules.release ());                                                                                \
	config.release ()

/* We use this prefix in all header files that contain test data. */
#define PREFIX "user/examples/yamlcpp/"

// -- Functions ----------------------------------------------------------------------------------------------------------------------------

TEST (yamlcpp, contract)
{
	OPEN_PLUGIN ("system/elektra/modules/yamlcpp", "file/path");

	CppKeySet keys;
	succeed_if_same (plugin->kdbGet (plugin, keys.getKeySet (), *parent), ELEKTRA_PLUGIN_STATUS_SUCCESS,
			 "Unable to retrieve plugin contract");

	CLOSE_PLUGIN ();
}

static void test_read (string const & filename, CppKeySet expected, int const status = ELEKTRA_PLUGIN_STATUS_SUCCESS)
#ifdef __llvm__
	__attribute__ ((annotate ("oclint:suppress")))
#endif
{
	string filepath = srcdir_file (filename.c_str ());

	OPEN_PLUGIN (PREFIX, filepath.c_str ());

	CppKeySet keys;
	succeed_if_same (plugin->kdbGet (plugin, keys.getKeySet (), *parent), status, parent.getMeta<string> ("error/reason"));
	compare_keyset (keys, expected);

	CLOSE_PLUGIN ();
}

static void test_write_read (CppKeySet expected)
#ifdef __llvm__
	__attribute__ ((annotate ("oclint:suppress")))
#endif
{
	string filepath = elektraFilename ();

	OPEN_PLUGIN (PREFIX, filepath.c_str ());

	// Write key set to file
	succeed_if_same (plugin->kdbSet (plugin, expected.getKeySet (), *parent), ELEKTRA_PLUGIN_STATUS_SUCCESS,
			 parent.getMeta<string> ("error/reason"));

	// Read written data
	CppKeySet keySetRead;
	succeed_if_same (plugin->kdbGet (plugin, keySetRead.getKeySet (), *parent), ELEKTRA_PLUGIN_STATUS_SUCCESS,
			 parent.getMeta<string> ("error/reason"));

	// Compare data
	compare_keyset (keySetRead, expected);

	// Clean up
	CLOSE_PLUGIN ();
}

TEST (yamlcpp, flat)
{
	test_read ("yamlcpp/flat_block_mapping.yaml",
#include "yamlcpp/flat_block_mapping.hpp"
	);
	test_write_read (
#include "yamlcpp/flat_block_mapping.hpp"
	);

	test_read ("yamlcpp/flat_flow_mapping.yaml",
#include "yamlcpp/flat_flow_mapping.hpp"
	);
	test_write_read (
#include "yamlcpp/flat_flow_mapping.hpp"
	);
}

TEST (yamlcpp, nested)
{
	test_read ("yamlcpp/nested_block_mapping.yaml",
#include "yamlcpp/nested_block_mapping.hpp"
	);
	test_write_read (
#include "yamlcpp/nested_block_mapping.hpp"
	);
	test_read ("yamlcpp/nested_mixed_mapping.yaml",
#include "yamlcpp/nested_mixed_mapping.hpp"
	);
	test_write_read (
#include "yamlcpp/nested_mixed_mapping.hpp"
	);
}

TEST (yamlcpp, array)
{
	test_read ("yamlcpp/simple_sequence.yaml",
#include "yamlcpp/simple_sequence.hpp"
	);
	test_write_read (
#include "yamlcpp/simple_sequence.hpp"
	);

	test_read ("yamlcpp/nested_sequences.yaml",
#include "yamlcpp/nested_sequences.hpp"
	);
	test_write_read (
#include "yamlcpp/nested_sequences.hpp"
	);
	test_write_read (
#include "yamlcpp/mapping_with_array_key.hpp"
	);
	test_write_read (
#include "yamlcpp/mixed.hpp"
	);
}

// -- Main ---------------------------------------------------------------------------------------------------------------------------------

int main (int argc, char * argv[])
{
	init (argc, argv); // Required for `srcdir_file` to work properly
	::testing::InitGoogleTest (&argc, argv);
	return RUN_ALL_TESTS ();
}
<commit_msg>YAML CPP: Remove `using` statements from test code<commit_after>/**
 * @file
 *
 * @brief Tests for yamlcpp plugin
 *
 * @copyright BSD License (see LICENSE.md or https://www.libelektra.org)
 *
 */

// -- Imports ------------------------------------------------------------------------------------------------------------------------------

#include "yamlcpp.hpp"

#include <kdbmodule.h>
#include <kdbprivate.h>

#include <tests.h>
#include <tests.hpp>

using ckdb::keyNew;

// -- Macros -------------------------------------------------------------------------------------------------------------------------------

#define OPEN_PLUGIN(parentName, filepath)                                                                                \
	kdb::KeySet modules{ 0, KS_END };                                                                                \
	kdb::KeySet config{ 0, KS_END };                                                                                \
	elektraModulesInit (modules.getKeySet (), 0);                                                                                \
	kdb::Key parent{ parentName, KEY_VALUE, filepath, KEY_END };                                                                       \
	Plugin * plugin = elektraPluginOpen ("yamlcpp", modules.getKeySet (), config.getKeySet (), *parent);                               \
	exit_if_fail (plugin != NULL, "Could not open yamlcpp plugin")

#define CLOSE_PLUGIN()                                                                                \
	elektraPluginClose (plugin, 0);                                                                                \
	elektraModulesClose (modules.getKeySet (), 0);                                                                                \
	ksDel (modules.release ());                                                                                \
	config.release ()

/* We use this prefix in all header files that contain test data. */
#define PREFIX "user/examples/yamlcpp/"

// -- Functions ----------------------------------------------------------------------------------------------------------------------------

TEST (yamlcpp, contract)
{
	OPEN_PLUGIN ("system/elektra/modules/yamlcpp", "file/path");

	kdb::KeySet keys;
	succeed_if_same (plugin->kdbGet (plugin, keys.getKeySet (), *parent), ELEKTRA_PLUGIN_STATUS_SUCCESS,
			 "Unable to retrieve plugin contract");

	CLOSE_PLUGIN ();
}

static void test_read (string const & filename, kdb::KeySet expected, int const status = ELEKTRA_PLUGIN_STATUS_SUCCESS)
#ifdef __llvm__
	__attribute__ ((annotate ("oclint:suppress")))
#endif
{
	string filepath = srcdir_file (filename.c_str ());

	OPEN_PLUGIN (PREFIX, filepath.c_str ());

	kdb::KeySet keys;
	succeed_if_same (plugin->kdbGet (plugin, keys.getKeySet (), *parent), status, parent.getMeta<string> ("error/reason"));
	compare_keyset (keys, expected);

	CLOSE_PLUGIN ();
}

static void test_write_read (kdb::KeySet expected)
#ifdef __llvm__
	__attribute__ ((annotate ("oclint:suppress")))
#endif
{
	string filepath = elektraFilename ();

	OPEN_PLUGIN (PREFIX, filepath.c_str ());

	// Write key set to file
	succeed_if_same (plugin->kdbSet (plugin, expected.getKeySet (), *parent), ELEKTRA_PLUGIN_STATUS_SUCCESS,
			 parent.getMeta<string> ("error/reason"));

	// Read written data
	kdb::KeySet keySetRead;
	succeed_if_same (plugin->kdbGet (plugin, keySetRead.getKeySet (), *parent), ELEKTRA_PLUGIN_STATUS_SUCCESS,
			 parent.getMeta<string> ("error/reason"));

	// Compare data
	compare_keyset (keySetRead, expected);

	// Clean up
	CLOSE_PLUGIN ();
}

TEST (yamlcpp, flat)
{
	test_read ("yamlcpp/flat_block_mapping.yaml",
#include "yamlcpp/flat_block_mapping.hpp"
	);
	test_write_read (
#include "yamlcpp/flat_block_mapping.hpp"
	);

	test_read ("yamlcpp/flat_flow_mapping.yaml",
#include "yamlcpp/flat_flow_mapping.hpp"
	);
	test_write_read (
#include "yamlcpp/flat_flow_mapping.hpp"
	);
}

TEST (yamlcpp, nested)
{
	test_read ("yamlcpp/nested_block_mapping.yaml",
#include "yamlcpp/nested_block_mapping.hpp"
	);
	test_write_read (
#include "yamlcpp/nested_block_mapping.hpp"
	);
	test_read ("yamlcpp/nested_mixed_mapping.yaml",
#include "yamlcpp/nested_mixed_mapping.hpp"
	);
	test_write_read (
#include "yamlcpp/nested_mixed_mapping.hpp"
	);
}

TEST (yamlcpp, array)
{
	test_read ("yamlcpp/simple_sequence.yaml",
#include "yamlcpp/simple_sequence.hpp"
	);
	test_write_read (
#include "yamlcpp/simple_sequence.hpp"
	);

	test_read ("yamlcpp/nested_sequences.yaml",
#include "yamlcpp/nested_sequences.hpp"
	);
	test_write_read (
#include "yamlcpp/nested_sequences.hpp"
	);
	test_write_read (
#include "yamlcpp/mapping_with_array_key.hpp"
	);
	test_write_read (
#include "yamlcpp/mixed.hpp"
	);
}

// -- Main ---------------------------------------------------------------------------------------------------------------------------------

int main (int argc, char * argv[])
{
	init (argc, argv); // Required for `srcdir_file` to work properly
	::testing::InitGoogleTest (&argc, argv);
	return RUN_ALL_TESTS ();
}
<|endoftext|>


<commit_before>/*
 For more information, please see: http://software.sci.utah.edu

 The MIT License

 Copyright (c) 2015 Scientific Computing and Imaging Institute,
 University of Utah.

 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 <Interface/Application/ShortcutsInterface.h>

using namespace SCIRun;
using namespace SCIRun::Gui;

ShortcutsInterface::ShortcutsInterface(QWidget* parent) : QDialog(parent)
{
  setupUi( this );

  Qt::WindowFlags flags = windowFlags();
  Qt::WindowFlags helpFlag = Qt::WindowContextHelpButtonHint;
  flags = flags & ( ~helpFlag );
  setWindowFlags( flags );

  updateFontsAndText();
  if (minimumWidth() > 0 && minimumHeight() > 0)
  {
    setFixedSize(minimumWidth(), minimumHeight());
  }

  // Python Shortcut visible
#ifdef BUILD_WITH_PYTHON
  this->private_->ui_.python_shortcut_label_->show();
#endif
}

void ShortcutsInterface::updateFontsAndText()
{

// ShortCut keys on Mac are different: CTRL becomes command key and we need to fix the font size
// on mac as it is too large. Default fonts on Mac and Windows are set differently.
// This function fixes the appearance

  for (auto& child : findChildren<QLabel*>())
  {
    QString text_temp = child->text();
#ifdef __APPLE__
    const QString splat = QChar(0x2318);
    text_temp.replace("CTRL", splat, Qt::CaseInsensitive );
    const QString shift = QChar(0x21E7);
    text_temp.replace("SHIFT", shift, Qt::CaseInsensitive );
    text_temp.replace("META_KEY", "^", Qt::CaseInsensitive );
    const QString option = QChar(0x2325);
    text_temp.replace("ALT", option, Qt::CaseInsensitive );
    text_temp.replace("+", "", Qt::CaseInsensitive );
    text_temp.replace("PLUS", "+", Qt::CaseInsensitive );

    QFont font = child->font();
    font.setPointSize( 11 );
    child->setFont( font );
#else
    const QString caps = QChar(0x21EA);
    text_temp.replace("META_KEY", caps, Qt::CaseInsensitive );
#endif
    child->setText( text_temp );
  }

}
<commit_msg>Windows improvements<commit_after>/*
 For more information, please see: http://software.sci.utah.edu

 The MIT License

 Copyright (c) 2015 Scientific Computing and Imaging Institute,
 University of Utah.

 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 <Interface/Application/ShortcutsInterface.h>

using namespace SCIRun;
using namespace SCIRun::Gui;

ShortcutsInterface::ShortcutsInterface(QWidget* parent) : QDialog(parent)
{
  setupUi( this );

  Qt::WindowFlags flags = windowFlags();
  Qt::WindowFlags helpFlag = Qt::WindowContextHelpButtonHint;
  flags = flags & ( ~helpFlag );
  setWindowFlags( flags );

  updateFontsAndText();
  if (minimumWidth() > 0 && minimumHeight() > 0)
  {
    setFixedSize(minimumWidth(), minimumHeight());
  }

  // Python Shortcut visible
#ifdef BUILD_WITH_PYTHON
  this->private_->ui_.python_shortcut_label_->show();
#endif
}

void ShortcutsInterface::updateFontsAndText()
{

// ShortCut keys on Mac are different: CTRL becomes command key and we need to fix the font size
// on mac as it is too large. Default fonts on Mac and Windows are set differently.
// This function fixes the appearance

  for (auto& child : findChildren<QLabel*>())
  {
    QString text_temp = child->text();
#ifdef __APPLE__
    const QString splat = QChar(0x2318);
    text_temp.replace("CTRL", splat, Qt::CaseInsensitive );
    const QString shift = QChar(0x21E7);
    text_temp.replace("SHIFT", shift, Qt::CaseInsensitive );
    text_temp.replace("META_KEY", "^", Qt::CaseInsensitive );
    const QString option = QChar(0x2325);
    text_temp.replace("ALT", option, Qt::CaseInsensitive );
    text_temp.replace("+", "", Qt::CaseInsensitive );

    QFont font = child->font();
    font.setPointSize( 11 );
    child->setFont( font );
#else
    //const QString caps = QChar(0x21EA);
    text_temp.replace("META_KEY", "Caps Lock", Qt::CaseInsensitive );
    text_temp.replace("CTRL", "Ctrl", Qt::CaseInsensitive);
    text_temp.replace("SHIFT", "Shift", Qt::CaseInsensitive);
    text_temp.replace("ALT", "Alt", Qt::CaseInsensitive);
#endif
    text_temp.replace("PLUS", "+", Qt::CaseInsensitive);
    child->setText( text_temp );
  }

}
<|endoftext|>


<commit_before>// Copyright 2008, Google Inc. All rights reserved.
//
// 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.
//  3. Neither the name of Google Inc. nor the names of its contributors may be
//     used to endorse or promote products derived from this software without
//     specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.

#include "kml/base/time_util.h"
#include <cstddef>  // NULL
#ifdef WIN32
#include <windows.h>
#include <winsock.h>
#include <time.h>
#else
#include <sys/time.h>
#endif

namespace kmlbase {

#ifdef WIN32
// http://forums.msdn.microsoft.com/en/vcgeneral/thread/430449b3-f6dd-4e18-84de-eebd26a8d668/
#if defined(_MSC_VER) || defined(_MSC_EXTENSIONS)
#define DELTA_EPOCH_IN_MICROSECS  11644473600000000Ui64
#else
#define DELTA_EPOCH_IN_MICROSECS  11644473600000000ULL
#endif
//
void gettimeofday(struct timeval* tv, void *) {
  FILETIME file_time;
  GetSystemTimeAsFileTime(&file_time);

  // First covert file_time to a single 64 bit value.
  unsigned __int64 file_time64 = 0;
  file_time64 |= file_time.dwHighDateTime;
  file_time64 <<= 32;
  file_time64 |= file_time.dwLowDateTime;

  /* Now convert file_time64 to unix time. */
  file_time64 /= 10;  /* Convert into microseconds. */
  file_time64 -= DELTA_EPOCH_IN_MICROSECS;
  tv->tv_sec = (long)(file_time64 / 1000000UL);
  tv->tv_usec = (long)(file_time64 % 1000000UL);
}
#endif

// This is here because Windows has no gettimeofday().
double GetMicroTime() {
  struct timeval now_tv;
  gettimeofday(&now_tv, NULL);
  // Make this one double with secs.microseconds.
  return (double)now_tv.tv_sec + (double)now_tv.tv_usec/1000000;
}

}  // end namespace kmlbase
<commit_msg>Include winsock2.h before windows.h. Fixes bug 31.<commit_after>// Copyright 2008, Google Inc. All rights reserved.
//
// 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.
//  3. Neither the name of Google Inc. nor the names of its contributors may be
//     used to endorse or promote products derived from this software without
//     specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.

#include "kml/base/time_util.h"
#include <cstddef>  // NULL
#ifdef WIN32
#include <winsock2.h>  // This header MUST come before windows.h. See
#include <windows.h>   // http://code.google.com/p/libkml/issues/detail?id=31
#include <time.h>
#else
#include <sys/time.h>
#endif

namespace kmlbase {

#ifdef WIN32
// http://forums.msdn.microsoft.com/en/vcgeneral/thread/430449b3-f6dd-4e18-84de-eebd26a8d668/
#if defined(_MSC_VER) || defined(_MSC_EXTENSIONS)
#define DELTA_EPOCH_IN_MICROSECS  11644473600000000Ui64
#else
#define DELTA_EPOCH_IN_MICROSECS  11644473600000000ULL
#endif
//
void gettimeofday(struct timeval* tv, void *) {
  FILETIME file_time;
  GetSystemTimeAsFileTime(&file_time);

  // First covert file_time to a single 64 bit value.
  unsigned __int64 file_time64 = 0;
  file_time64 |= file_time.dwHighDateTime;
  file_time64 <<= 32;
  file_time64 |= file_time.dwLowDateTime;

  /* Now convert file_time64 to unix time. */
  file_time64 /= 10;  /* Convert into microseconds. */
  file_time64 -= DELTA_EPOCH_IN_MICROSECS;
  tv->tv_sec = (long)(file_time64 / 1000000UL);
  tv->tv_usec = (long)(file_time64 % 1000000UL);
}
#endif

// This is here because Windows has no gettimeofday().
double GetMicroTime() {
  struct timeval now_tv;
  gettimeofday(&now_tv, NULL);
  // Make this one double with secs.microseconds.
  return (double)now_tv.tv_sec + (double)now_tv.tv_usec/1000000;
}

}  // end namespace kmlbase
<|endoftext|>