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

//
// wasm-emscripten-finalize console tool
// Performs Emscripten-specific transforms on .wasm files
//

#include <exception>

#include "ir/trapping.h"
#include "support/colors.h"
#include "support/command-line.h"
#include "support/file.h"
#include "wasm-binary.h"
#include "wasm-emscripten.h"
#include "wasm-io.h"
#include "wasm-printing.h"
#include "wasm-validator.h"

using namespace cashew;
using namespace wasm;

int main(int argc, const char *argv[]) {
  std::string infile;
  std::string outfile;
  std::string inputSourceMapFilename;
  std::string outputSourceMapFilename;
  std::string outputSourceMapUrl;
  bool emitBinary = true;
  bool debugInfo = false;
  unsigned numReservedFunctionPointers = 0;
  uint64_t globalBase;
  Options options("wasm-emscripten-finalize",
                  "Performs Emscripten-specific transforms on .wasm files");
  options
      .add("--output", "-o", "Output file",
           Options::Arguments::One,
           [&outfile](Options*, const std::string& argument) {
             outfile = argument;
             Colors::disable();
           })
      .add("--debuginfo", "-g",
           "Emit names section in wasm binary (or full debuginfo in wast)",
           Options::Arguments::Zero,
           [&debugInfo](Options *, const std::string &) {
             debugInfo = true;
           })
      .add("--emit-text", "-S", "Emit text instead of binary for the output file",
           Options::Arguments::Zero,
           [&emitBinary](Options*, const std::string& ) {
             emitBinary = false;
           })
      .add("--emscripten-reserved-function-pointers", "",
           "Number of reserved function pointers for emscripten addFunction "
           "support",
           Options::Arguments::One,
           [&numReservedFunctionPointers](Options *,
                                          const std::string &argument) {
             numReservedFunctionPointers = std::stoi(argument);
           })
      .add("--global-base", "", "Where lld started to place globals",
           Options::Arguments::One,
           [&globalBase](Options*, const std::string&argument ) {
             globalBase = std::stoull(argument);
           })
      .add("--input-source-map", "-ism", "Consume source map from the specified file",
           Options::Arguments::One,
           [&inputSourceMapFilename](Options *o, const std::string& argument) { inputSourceMapFilename = argument; })
      .add("--output-source-map", "-osm", "Emit source map to the specified file",
           Options::Arguments::One,
           [&outputSourceMapFilename](Options *o, const std::string& argument) { outputSourceMapFilename = argument; })
      .add("--output-source-map-url", "-osu", "Emit specified string as source map URL",
           Options::Arguments::One,
           [&outputSourceMapUrl](Options *o, const std::string& argument) { outputSourceMapUrl = argument; })
      .add_positional("INFILE", Options::Arguments::One,
                      [&infile](Options *o, const std::string& argument) {
                        infile = argument;
                      });
  options.parse(argc, argv);

  if (infile == "") {
    Fatal() << "Need to specify an infile\n";
  }
  if (outfile == "" && emitBinary) {
    Fatal() << "Need to specify an outfile, or use text output\n";
  }

  Module wasm;
  ModuleReader reader;
  try {
    reader.read(infile, wasm, inputSourceMapFilename);
  } catch (ParseException& p) {
    p.dump(std::cerr);
    std::cerr << '\n';
    Fatal() << "error in parsing input";
  } catch (MapParseException& p) {
    p.dump(std::cerr);
    std::cerr << '\n';
    Fatal() << "error in parsing wasm source map";
  }

  if (options.debug) {
    std::cerr << "Module before:\n";
    WasmPrinter::printModule(&wasm, std::cerr);
  }

  Export* dataEndExport = wasm.getExport("__data_end");
  if (dataEndExport == nullptr) {
    Fatal() << "__data_end export not found";
  }
  Global* dataEnd = wasm.getGlobal(dataEndExport->value);
  if (dataEnd == nullptr) {
    Fatal() << "__data_end global not found";
  }
  if (dataEnd->type != Type::i32) {
    Fatal() << "__data_end global has wrong type";
  }
  Const* dataEndConst = dataEnd->init->cast<Const>();
  uint32_t dataSize = dataEndConst->value.geti32() - globalBase;

  std::vector<Name> initializerFunctions;
  initializerFunctions.push_back("__wasm_call_ctors");

  EmscriptenGlueGenerator generator(wasm);
  generator.fixInvokeFunctionNames();
  generator.generateRuntimeFunctions();
  generator.generateMemoryGrowthFunction();
  generator.generateDynCallThunks();
  generator.generateJSCallThunks(numReservedFunctionPointers);
  std::string metadata = generator.generateEmscriptenMetadata(dataSize, initializerFunctions, numReservedFunctionPointers);

  if (options.debug) {
    std::cerr << "Module after:\n";
    WasmPrinter::printModule(&wasm, std::cerr);
  }

  auto outputBinaryFlag = emitBinary ? Flags::Binary : Flags::Text;
  Output output(outfile, outputBinaryFlag, Flags::Release);
  ModuleWriter writer;
  writer.setDebug(options.debug);
  writer.setDebugInfo(debugInfo);
  // writer.setSymbolMap(symbolMap);
  writer.setBinary(emitBinary);
  if (outputSourceMapFilename.size()) {
    writer.setSourceMapFilename(outputSourceMapFilename);
    writer.setSourceMapUrl(outputSourceMapUrl);
  }
  writer.write(wasm, output);
  if (emitBinary) {
    std::cout << metadata;
  } else {
    output << ";; METADATA: " << metadata;
  }

  return 0;
}
<commit_msg>wasm-emscripten-finalize: make _wasm_call_ctors optional (#1647)<commit_after>/*
 * Copyright 2017 WebAssembly Community Group participants
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

//
// wasm-emscripten-finalize console tool
// Performs Emscripten-specific transforms on .wasm files
//

#include <exception>

#include "ir/trapping.h"
#include "support/colors.h"
#include "support/command-line.h"
#include "support/file.h"
#include "wasm-binary.h"
#include "wasm-emscripten.h"
#include "wasm-io.h"
#include "wasm-printing.h"
#include "wasm-validator.h"

using namespace cashew;
using namespace wasm;

int main(int argc, const char *argv[]) {
  std::string infile;
  std::string outfile;
  std::string inputSourceMapFilename;
  std::string outputSourceMapFilename;
  std::string outputSourceMapUrl;
  bool emitBinary = true;
  bool debugInfo = false;
  unsigned numReservedFunctionPointers = 0;
  uint64_t globalBase;
  Options options("wasm-emscripten-finalize",
                  "Performs Emscripten-specific transforms on .wasm files");
  options
      .add("--output", "-o", "Output file",
           Options::Arguments::One,
           [&outfile](Options*, const std::string& argument) {
             outfile = argument;
             Colors::disable();
           })
      .add("--debuginfo", "-g",
           "Emit names section in wasm binary (or full debuginfo in wast)",
           Options::Arguments::Zero,
           [&debugInfo](Options *, const std::string &) {
             debugInfo = true;
           })
      .add("--emit-text", "-S", "Emit text instead of binary for the output file",
           Options::Arguments::Zero,
           [&emitBinary](Options*, const std::string& ) {
             emitBinary = false;
           })
      .add("--emscripten-reserved-function-pointers", "",
           "Number of reserved function pointers for emscripten addFunction "
           "support",
           Options::Arguments::One,
           [&numReservedFunctionPointers](Options *,
                                          const std::string &argument) {
             numReservedFunctionPointers = std::stoi(argument);
           })
      .add("--global-base", "", "Where lld started to place globals",
           Options::Arguments::One,
           [&globalBase](Options*, const std::string&argument ) {
             globalBase = std::stoull(argument);
           })
      .add("--input-source-map", "-ism", "Consume source map from the specified file",
           Options::Arguments::One,
           [&inputSourceMapFilename](Options *o, const std::string& argument) { inputSourceMapFilename = argument; })
      .add("--output-source-map", "-osm", "Emit source map to the specified file",
           Options::Arguments::One,
           [&outputSourceMapFilename](Options *o, const std::string& argument) { outputSourceMapFilename = argument; })
      .add("--output-source-map-url", "-osu", "Emit specified string as source map URL",
           Options::Arguments::One,
           [&outputSourceMapUrl](Options *o, const std::string& argument) { outputSourceMapUrl = argument; })
      .add_positional("INFILE", Options::Arguments::One,
                      [&infile](Options *o, const std::string& argument) {
                        infile = argument;
                      });
  options.parse(argc, argv);

  if (infile == "") {
    Fatal() << "Need to specify an infile\n";
  }
  if (outfile == "" && emitBinary) {
    Fatal() << "Need to specify an outfile, or use text output\n";
  }

  Module wasm;
  ModuleReader reader;
  try {
    reader.read(infile, wasm, inputSourceMapFilename);
  } catch (ParseException& p) {
    p.dump(std::cerr);
    std::cerr << '\n';
    Fatal() << "error in parsing input";
  } catch (MapParseException& p) {
    p.dump(std::cerr);
    std::cerr << '\n';
    Fatal() << "error in parsing wasm source map";
  }

  if (options.debug) {
    std::cerr << "Module before:\n";
    WasmPrinter::printModule(&wasm, std::cerr);
  }

  Export* dataEndExport = wasm.getExport("__data_end");
  if (dataEndExport == nullptr) {
    Fatal() << "__data_end export not found";
  }
  Global* dataEnd = wasm.getGlobal(dataEndExport->value);
  if (dataEnd == nullptr) {
    Fatal() << "__data_end global not found";
  }
  if (dataEnd->type != Type::i32) {
    Fatal() << "__data_end global has wrong type";
  }
  Const* dataEndConst = dataEnd->init->cast<Const>();
  uint32_t dataSize = dataEndConst->value.geti32() - globalBase;

  std::vector<Name> initializerFunctions;
  if (wasm.getFunctionOrNull("__wasm_call_ctors")) {
    initializerFunctions.push_back("__wasm_call_ctors");
  }

  EmscriptenGlueGenerator generator(wasm);
  generator.fixInvokeFunctionNames();
  generator.generateRuntimeFunctions();
  generator.generateMemoryGrowthFunction();
  generator.generateDynCallThunks();
  generator.generateJSCallThunks(numReservedFunctionPointers);
  std::string metadata = generator.generateEmscriptenMetadata(dataSize, initializerFunctions, numReservedFunctionPointers);

  if (options.debug) {
    std::cerr << "Module after:\n";
    WasmPrinter::printModule(&wasm, std::cerr);
  }

  auto outputBinaryFlag = emitBinary ? Flags::Binary : Flags::Text;
  Output output(outfile, outputBinaryFlag, Flags::Release);
  ModuleWriter writer;
  writer.setDebug(options.debug);
  writer.setDebugInfo(debugInfo);
  // writer.setSymbolMap(symbolMap);
  writer.setBinary(emitBinary);
  if (outputSourceMapFilename.size()) {
    writer.setSourceMapFilename(outputSourceMapFilename);
    writer.setSourceMapUrl(outputSourceMapUrl);
  }
  writer.write(wasm, output);
  if (emitBinary) {
    std::cout << metadata;
  } else {
    output << ";; METADATA: " << metadata;
  }

  return 0;
}
<|endoftext|>


<commit_before>//
// ulib - a collection of useful classes
// Copyright (C) 2004,2005,2006,2007,2008,2018 Michael Fink
//
/// \file VersionInfoResource.cpp version info resource class
//
#include "stdafx.h"
#include <ulib/win32/VersionInfoResource.hpp>
#include <winbase.h> // for VOS_* constants
#include <winver.h> // for VOS_* constants, when not in winbase.h

#ifndef VOS_WINDOWSCE
#  define VOS_WINDOWSCE 0x00050000L
#endif

#ifndef _WIN32_WCE
#  pragma comment(lib, "version.lib")
#endif

using Win32::FixedFileInfo;
using Win32::VersionInfoResource;
using Win32::LANGANDCODEPAGE;

//
// FixedFileInfo
//

CString FixedFileInfo::GetFileVersion() const
{
   CString text;
   text.Format(_T("%u.%u.%u.%u"),
      HIWORD(dwFileVersionMS), LOWORD(dwFileVersionMS),
      HIWORD(dwFileVersionLS), LOWORD(dwFileVersionLS));
   return text;
}

CString FixedFileInfo::GetProductVersion() const
{
   CString text;
   text.Format(_T("%u.%u.%u.%u"),
      HIWORD(dwProductVersionMS), LOWORD(dwProductVersionMS),
      HIWORD(dwProductVersionLS), LOWORD(dwProductVersionLS));
   return text;
}

CString FixedFileInfo::GetFileOS() const
{
   CString text;

   switch (dwFileOS & 0xFFFF0000)
   {
   case VOS_DOS: // The file was designed for MS-DOS.
      text = _T("VOS_DOS"); break;
   case VOS_OS216: // The file was designed for 16-bit OS/2.
      text = _T("VOS_OS216"); break;
   case VOS_OS232: // The file was designed for 32-bit OS/2.
      text = _T("VOS_OS232"); break;
   case VOS_NT: // The file was designed for Windows NT and Windows 2000.
      text = _T("VOS_NT"); break;
   case VOS_WINDOWSCE:
      text = _T("VOS_WINDOWSCE"); break;
   case VOS_UNKNOWN:
      text = _T("VOS_UNKNOWN"); break;
   default:
      text = _T("unknown"); break;
   }

   switch (dwFileOS & 0x0000FFFF)
   {
   case VOS__WINDOWS16: // The file was designed for 16-bit Windows.
      text += _T(" | VOS__WINDOWS16"); break;
   case VOS__PM16: // The file was designed for 16-bit Presentation Manager.
      text += _T(" | VOS__PM16"); break;
   case VOS__PM32: // The file was designed for 32-bit Presentation Manager.
      text += _T(" | VOS__PM32"); break;
   case VOS__WINDOWS32: // The file was designed for the Win32 API.
      text += _T(" | VOS__WINDOWS32"); break;
   }

   return text;
}

CString FixedFileInfo::GetFileType() const
{
   CString text;
   switch (dwFileType)
   {
   case VFT_UNKNOWN:
      text = _T("VFT_UNKNOWN"); break;
   case VFT_APP:
      text = _T("VFT_APP"); break;
   case VFT_DLL:
      text = _T("VFT_DLL"); break;
   case VFT_DRV:
      text = _T("VFT_DRV"); break;
   case VFT_FONT:
      text = _T("VFT_FONT"); break;
   case VFT_VXD:
      text = _T("VFT_VXD"); break;
   case VFT_STATIC_LIB:
      text = _T("VFT_STATIC_LIB"); break;
   default:
      text = _T("unknown"); break;
   }
   return text;
}

//
// VersionInfoResource
//

VersionInfoResource::VersionInfoResource(LPCTSTR filename)
{
   LPTSTR filename2 = const_cast<LPTSTR>(filename);

   // find out length
   DWORD dummy = 0;
   DWORD dwLen = ::GetFileVersionInfoSize(filename2, &dummy);

   if (dwLen > 0)
   {
      m_versionInfoData.resize(dwLen);

      // get version info
      ::GetFileVersionInfo(filename2, 0, dwLen, &m_versionInfoData[0]);
   }
}

LPVOID VersionInfoResource::QueryValue(LPCTSTR subBlock, UINT* puiSize)
{
   ATLASSERT(IsAvail());

   LPTSTR subBlock2 = const_cast<LPTSTR>(subBlock);

   LPVOID data = NULL;
   UINT uiSize = 0;

   BOOL ret = VerQueryValue(&m_versionInfoData[0],
      subBlock2,
      &data,
      puiSize != NULL ? puiSize : &uiSize);

   return ret == FALSE ? NULL : data;
}

void VersionInfoResource::GetLangAndCodepages(std::vector<LANGANDCODEPAGE>& langAndCodepageList)
{
   ATLASSERT(IsAvail());

   UINT size = 0;
   LPVOID data = QueryValue(_T("\\VarFileInfo\\Translation"), &size);

   ATLASSERT((uiSize % sizeof(LANGANDCODEPAGE)) == 0);

   LANGANDCODEPAGE* langAndCodepage = reinterpret_cast<LANGANDCODEPAGE*>(data);

   for (unsigned int i = 0; i < size / sizeof(LANGANDCODEPAGE); i++)
      langAndCodepageList.push_back(langAndCodepage[i]);
}

CString VersionInfoResource::GetStringValue(const LANGANDCODEPAGE& langAndCodepage, LPCTSTR valueName)
{
   CString buffer;
   buffer.Format(
      _T("\\StringFileInfo\\%04x%04x\\%s"),
      langAndCodepage.wLanguage, langAndCodepage.wCodePage,
      valueName);

   UINT size = 0;
   LPCWSTR text = reinterpret_cast<LPCWSTR>(QueryValue(buffer, &size));

   //   ATLASSERT((uiSize & 1) == 0);
   //   ATLASSERT(pszText[uiSize/sizeof(WCHAR)] == 0);
   ATLASSERT(size == 0 || text[uiSize - 1] == 0);

   return (text == NULL || *text == 0) ? CString(_T("???")) : CString(text);
}
<commit_msg>fixed ASSERT only reporting syntax error when compiling in Debug mode<commit_after>//
// ulib - a collection of useful classes
// Copyright (C) 2004,2005,2006,2007,2008,2018 Michael Fink
//
/// \file VersionInfoResource.cpp version info resource class
//
#include "stdafx.h"
#include <ulib/win32/VersionInfoResource.hpp>
#include <winbase.h> // for VOS_* constants
#include <winver.h> // for VOS_* constants, when not in winbase.h

#ifndef VOS_WINDOWSCE
#  define VOS_WINDOWSCE 0x00050000L
#endif

#ifndef _WIN32_WCE
#  pragma comment(lib, "version.lib")
#endif

using Win32::FixedFileInfo;
using Win32::VersionInfoResource;
using Win32::LANGANDCODEPAGE;

//
// FixedFileInfo
//

CString FixedFileInfo::GetFileVersion() const
{
   CString text;
   text.Format(_T("%u.%u.%u.%u"),
      HIWORD(dwFileVersionMS), LOWORD(dwFileVersionMS),
      HIWORD(dwFileVersionLS), LOWORD(dwFileVersionLS));
   return text;
}

CString FixedFileInfo::GetProductVersion() const
{
   CString text;
   text.Format(_T("%u.%u.%u.%u"),
      HIWORD(dwProductVersionMS), LOWORD(dwProductVersionMS),
      HIWORD(dwProductVersionLS), LOWORD(dwProductVersionLS));
   return text;
}

CString FixedFileInfo::GetFileOS() const
{
   CString text;

   switch (dwFileOS & 0xFFFF0000)
   {
   case VOS_DOS: // The file was designed for MS-DOS.
      text = _T("VOS_DOS"); break;
   case VOS_OS216: // The file was designed for 16-bit OS/2.
      text = _T("VOS_OS216"); break;
   case VOS_OS232: // The file was designed for 32-bit OS/2.
      text = _T("VOS_OS232"); break;
   case VOS_NT: // The file was designed for Windows NT and Windows 2000.
      text = _T("VOS_NT"); break;
   case VOS_WINDOWSCE:
      text = _T("VOS_WINDOWSCE"); break;
   case VOS_UNKNOWN:
      text = _T("VOS_UNKNOWN"); break;
   default:
      text = _T("unknown"); break;
   }

   switch (dwFileOS & 0x0000FFFF)
   {
   case VOS__WINDOWS16: // The file was designed for 16-bit Windows.
      text += _T(" | VOS__WINDOWS16"); break;
   case VOS__PM16: // The file was designed for 16-bit Presentation Manager.
      text += _T(" | VOS__PM16"); break;
   case VOS__PM32: // The file was designed for 32-bit Presentation Manager.
      text += _T(" | VOS__PM32"); break;
   case VOS__WINDOWS32: // The file was designed for the Win32 API.
      text += _T(" | VOS__WINDOWS32"); break;
   }

   return text;
}

CString FixedFileInfo::GetFileType() const
{
   CString text;
   switch (dwFileType)
   {
   case VFT_UNKNOWN:
      text = _T("VFT_UNKNOWN"); break;
   case VFT_APP:
      text = _T("VFT_APP"); break;
   case VFT_DLL:
      text = _T("VFT_DLL"); break;
   case VFT_DRV:
      text = _T("VFT_DRV"); break;
   case VFT_FONT:
      text = _T("VFT_FONT"); break;
   case VFT_VXD:
      text = _T("VFT_VXD"); break;
   case VFT_STATIC_LIB:
      text = _T("VFT_STATIC_LIB"); break;
   default:
      text = _T("unknown"); break;
   }
   return text;
}

//
// VersionInfoResource
//

VersionInfoResource::VersionInfoResource(LPCTSTR filename)
{
   LPTSTR filename2 = const_cast<LPTSTR>(filename);

   // find out length
   DWORD dummy = 0;
   DWORD dwLen = ::GetFileVersionInfoSize(filename2, &dummy);

   if (dwLen > 0)
   {
      m_versionInfoData.resize(dwLen);

      // get version info
      ::GetFileVersionInfo(filename2, 0, dwLen, &m_versionInfoData[0]);
   }
}

LPVOID VersionInfoResource::QueryValue(LPCTSTR subBlock, UINT* puiSize)
{
   ATLASSERT(IsAvail());

   LPTSTR subBlock2 = const_cast<LPTSTR>(subBlock);

   LPVOID data = NULL;
   UINT uiSize = 0;

   BOOL ret = VerQueryValue(&m_versionInfoData[0],
      subBlock2,
      &data,
      puiSize != NULL ? puiSize : &uiSize);

   return ret == FALSE ? NULL : data;
}

void VersionInfoResource::GetLangAndCodepages(std::vector<LANGANDCODEPAGE>& langAndCodepageList)
{
   ATLASSERT(IsAvail());

   UINT size = 0;
   LPVOID data = QueryValue(_T("\\VarFileInfo\\Translation"), &size);

   ATLASSERT((size % sizeof(LANGANDCODEPAGE)) == 0);

   LANGANDCODEPAGE* langAndCodepage = reinterpret_cast<LANGANDCODEPAGE*>(data);

   for (unsigned int i = 0; i < size / sizeof(LANGANDCODEPAGE); i++)
      langAndCodepageList.push_back(langAndCodepage[i]);
}

CString VersionInfoResource::GetStringValue(const LANGANDCODEPAGE& langAndCodepage, LPCTSTR valueName)
{
   CString buffer;
   buffer.Format(
      _T("\\StringFileInfo\\%04x%04x\\%s"),
      langAndCodepage.wLanguage, langAndCodepage.wCodePage,
      valueName);

   UINT size = 0;
   LPCWSTR text = reinterpret_cast<LPCWSTR>(QueryValue(buffer, &size));

   ATLASSERT(size == 0 || text[size - 1] == 0);

   return (text == NULL || *text == 0) ? CString(_T("???")) : CString(text);
}
<|endoftext|>


<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "mscenelayereffectdimview.h"

#include "mscenewindowview_p.h"
#include "mviewcreator.h"
#include "mscenelayereffect.h"
#include "mscenelayereffectmodel.h"

//! \internal
class MSceneLayerEffectDimViewPrivate : public MSceneWindowViewPrivate
{
public:
    MSceneLayerEffect *controller;
};
//! \internal_end

MSceneLayerEffectDimView::MSceneLayerEffectDimView(MSceneLayerEffect *controller) :
    MSceneWindowView(*new MSceneLayerEffectDimViewPrivate, controller)
{
    Q_D(MSceneLayerEffectDimView);
    d->controller = controller;
    d->controller->setFlag(QGraphicsItem::ItemDoesntPropagateOpacityToChildren, true);
}

MSceneLayerEffectDimView::~MSceneLayerEffectDimView()
{
}

void MSceneLayerEffectDimView::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    Q_UNUSED(widget);
    Q_UNUSED(option);

    painter->fillRect(boundingRect(), QColor(0, 0, 0));
}

QRectF MSceneLayerEffectDimView::boundingRect() const
{
    Q_D(const MSceneLayerEffectDimView);
    return QRectF(QPointF(0, 0), d->controller->size());
}

void MSceneLayerEffectDimView::applyStyle()
{
    Q_D(MSceneLayerEffectDimView);

    MSceneWindowView::applyStyle();

    d->controller->setOpacity(style()->opacity());
}

M_REGISTER_VIEW_NEW(MSceneLayerEffectDimView, MSceneLayerEffect)
<commit_msg>Fixes: NB#210256 - Background goes blank on changing orientation<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "mscenelayereffectdimview.h"

#include "mscenewindowview_p.h"
#include "mviewcreator.h"
#include "mscenelayereffect.h"
#include "mscenelayereffectmodel.h"

//! \internal
class MSceneLayerEffectDimViewPrivate : public MSceneWindowViewPrivate
{
public:
    MSceneLayerEffect *controller;
};
//! \internal_end

MSceneLayerEffectDimView::MSceneLayerEffectDimView(MSceneLayerEffect *controller) :
    MSceneWindowView(*new MSceneLayerEffectDimViewPrivate, controller)
{
    Q_D(MSceneLayerEffectDimView);
    d->controller = controller;
    d->controller->setFlag(QGraphicsItem::ItemDoesntPropagateOpacityToChildren, true);
}

MSceneLayerEffectDimView::~MSceneLayerEffectDimView()
{
}

void MSceneLayerEffectDimView::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    Q_UNUSED(widget);
    Q_UNUSED(option);

    qreal oldOpacity = painter->opacity();
    qreal opacity = d_ptr->controller->effectiveOpacity() * style()->opacity();
    painter->setOpacity(opacity);
    painter->fillRect(boundingRect(), QColor(0, 0, 0));
    painter->setOpacity(oldOpacity);
}

QRectF MSceneLayerEffectDimView::boundingRect() const
{
    Q_D(const MSceneLayerEffectDimView);
    return QRectF(QPointF(0, 0), d->controller->size());
}

void MSceneLayerEffectDimView::applyStyle()
{
    MSceneWindowView::applyStyle();
}

M_REGISTER_VIEW_NEW(MSceneLayerEffectDimView, MSceneLayerEffect)
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2001-2002 The Apache Software Foundation.  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. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
 * ITS 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 2001, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/*
 * $Id$
 */

#include <xercesc/util/XercesDefs.hpp>
#include <xercesc/dom/DOMException.hpp>
#include <xercesc/dom/DOMNode.hpp>

#include "DOMDocumentImpl.hpp"
#include "DOMNodeListImpl.hpp"
#include "DOMRangeImpl.hpp"
#include "DOMParentNode.hpp"
#include "DOMCasts.hpp"

DOMParentNode::DOMParentNode(DOMDocument *ownerDoc)
    : fOwnerDocument(ownerDoc), fChildNodeList(castToNode(this))
{
    fFirstChild = 0;
};

// This only makes a shallow copy, cloneChildren must also be called for a
// deep clone
DOMParentNode::DOMParentNode(const DOMParentNode &other)  :
    fChildNodeList(castToNode(this))
{
    this->fOwnerDocument = other.fOwnerDocument;

    // Need to break the association w/ original kids
    this->fFirstChild = 0;
};

void DOMParentNode::changed()
{
    DOMDocumentImpl *doc = (DOMDocumentImpl *)(castToNodeImpl(this)->getOwnerDocument());
    doc->changed();
}

int DOMParentNode::changes() const
{
    DOMDocumentImpl *doc = (DOMDocumentImpl *)(castToNodeImpl(this)->getOwnerDocument());
    return doc->changes();
};

DOMNode * DOMParentNode::appendChild(DOMNode *newChild)
{
    return insertBefore(newChild, 0);
};

void DOMParentNode::cloneChildren(const DOMNode *other) {
  //    for (DOMNode *mykid = other.getFirstChild();
    for (DOMNode *mykid = other->getFirstChild();
         mykid != 0;
         mykid = mykid->getNextSibling())
    {
        appendChild(mykid->cloneNode(true));
    }
}

DOMDocument * DOMParentNode::getOwnerDocument() const {
    return fOwnerDocument;
}

// unlike getOwnerDocument this is not overriden by DocumentImpl to return 0
DOMDocument * DOMParentNode::getDocument() const {
    return fOwnerDocument;
}

void DOMParentNode::setOwnerDocument(DOMDocument* doc) {
    fOwnerDocument = doc;
}

DOMNodeList *DOMParentNode::getChildNodes() const {
    const DOMNodeList *ret = &fChildNodeList;
    return (DOMNodeList *)ret;   // cast off const.
};

DOMNode * DOMParentNode::getFirstChild() const {
    return fFirstChild;
};

DOMNode * DOMParentNode::getLastChild() const
{
    return lastChild();
};

DOMNode * DOMParentNode::lastChild() const
{
    // last child is stored as the previous sibling of first child
    if (fFirstChild == 0) {
        return 0;
    }

    DOMChildNode *firstChild = castToChildImpl(fFirstChild);
    DOMNode *ret = firstChild->previousSibling;
    return ret;
};

//
//  revisit.  Is this function used anywhere?  I don't see it.
//
void DOMParentNode::lastChild(DOMNode *node) {
    // store lastChild as previous sibling of first child
    if (fFirstChild != 0) {
        DOMChildNode *firstChild = castToChildImpl(fFirstChild);
        firstChild->previousSibling = node;
    }
}

bool DOMParentNode::hasChildNodes() const
{
    return fFirstChild!=0;
};

DOMNode *DOMParentNode::insertBefore(DOMNode *newChild, DOMNode *refChild) {
    DOMNodeImpl *thisNodeImpl = castToNodeImpl(this);
    if (thisNodeImpl->isReadOnly())
        throw DOMException(DOMException::NO_MODIFICATION_ALLOWED_ERR, 0);

    if (newChild->getOwnerDocument() != fOwnerDocument)
        throw DOMException(DOMException::WRONG_DOCUMENT_ERR, 0);

    // Prevent cycles in the tree
    bool treeSafe=true;
    for(DOMNode *a=castToNode(this)->getParentNode();
        treeSafe && a!=0;
        a=a->getParentNode())
        treeSafe=(newChild!=a);
    if(!treeSafe)
        throw DOMException(DOMException::HIERARCHY_REQUEST_ERR,0);

    // refChild must in fact be a child of this node (or 0)
    if (refChild!=0 && refChild->getParentNode() != castToNode(this))
        throw DOMException(DOMException::NOT_FOUND_ERR,0);

    if (newChild->getNodeType() == DOMNode::DOCUMENT_FRAGMENT_NODE)
    {
        // SLOW BUT SAFE: We could insert the whole subtree without
        // juggling so many next/previous pointers. (Wipe out the
        // parent's child-list, patch the parent pointers, set the
        // ends of the list.) But we know some subclasses have special-
        // case behavior they add to insertBefore(), so we don't risk it.
        // This approch also takes fewer bytecodes.

        // NOTE: If one of the children is not a legal child of this
        // node, throw HIERARCHY_REQUEST_ERR before _any_ of the children
        // have been transferred. (Alternative behaviors would be to
        // reparent up to the first failure point or reparent all those
        // which are acceptable to the target node, neither of which is
        // as robust. PR-DOM-0818 isn't entirely clear on which it
        // recommends?????

        // No need to check kids for right-document; if they weren't,
        // they wouldn't be kids of that DocFrag.
        for(DOMNode *kid=newChild->getFirstChild(); // Prescan
              kid!=0;
              kid=kid->getNextSibling())
        {
            if (!DOMDocumentImpl::isKidOK(castToNode(this), kid))
              throw DOMException(DOMException::HIERARCHY_REQUEST_ERR,0);
        }
        while(newChild->hasChildNodes())     // Move
            insertBefore(newChild->getFirstChild(),refChild);
    }

    else if (!DOMDocumentImpl::isKidOK(castToNode(this), newChild))
        throw DOMException(DOMException::HIERARCHY_REQUEST_ERR,0);

    else
    {
        DOMNode *oldparent=newChild->getParentNode();
        if(oldparent!=0)
            oldparent->removeChild(newChild);

        // Attach up
        castToNodeImpl(newChild)->fOwnerNode = castToNode(this);
        castToNodeImpl(newChild)->isOwned(true);

        // Attach before and after
        // Note: fFirstChild.previousSibling == lastChild!!
        if (fFirstChild == 0) {
            // this our first and only child
            fFirstChild = newChild;
            castToNodeImpl(newChild)->isFirstChild(true);
            // castToChildImpl(newChild)->previousSibling = newChild;
            DOMChildNode *newChild_ci = castToChildImpl(newChild);
            newChild_ci->previousSibling = newChild;
        } else {
            if (refChild == 0) {
                // this is an append
                DOMNode *lastChild = castToChildImpl(fFirstChild)->previousSibling;
                castToChildImpl(lastChild)->nextSibling = newChild;
                castToChildImpl(newChild)->previousSibling = lastChild;
                castToChildImpl(fFirstChild)->previousSibling = newChild;
            } else {
                // this is an insert
                if (refChild == fFirstChild) {
                    // at the head of the list
                    castToNodeImpl(fFirstChild)->isFirstChild(false);
                    castToChildImpl(newChild)->nextSibling = fFirstChild;
                    castToChildImpl(newChild)->previousSibling = castToChildImpl(fFirstChild)->previousSibling;
                    castToChildImpl(fFirstChild)->previousSibling = newChild;
                    fFirstChild = newChild;
                    castToNodeImpl(newChild)->isFirstChild(true);
                } else {
                    // somewhere in the middle
                    DOMNode *prev = castToChildImpl(refChild)->previousSibling;
                    castToChildImpl(newChild)->nextSibling = refChild;
                    castToChildImpl(prev)->nextSibling = newChild;
                    castToChildImpl(refChild)->previousSibling = newChild;
                    castToChildImpl(newChild)->previousSibling = prev;
                }
            }
        }
    }

    changed();

    if (this->getOwnerDocument() != 0) {
        Ranges* ranges = ((DOMDocumentImpl *)this->getOwnerDocument())->getRanges();
        if ( ranges != 0) {
            XMLSize_t sz = ranges->size();
            if (sz != 0) {
                for (XMLSize_t i =0; i<sz; i++) {
                    ranges->elementAt(i)->updateRangeForInsertedNode(newChild);
                }
            }
        }
    }

    return newChild;
};

DOMNode *DOMParentNode::removeChild(DOMNode *oldChild)
{
    if (castToNodeImpl(this)->isReadOnly())
        throw DOMException(
        DOMException::NO_MODIFICATION_ALLOWED_ERR, 0);

    if (oldChild != 0 && oldChild->getParentNode() != castToNode(this))
        throw DOMException(DOMException::NOT_FOUND_ERR, 0);

    //fix other ranges for change before deleting the node
    if (this->getOwnerDocument() !=  0  ) {
        Ranges* ranges = ((DOMDocumentImpl *)this->getOwnerDocument())->getRanges();
        if (ranges != 0) {
            XMLSize_t sz = ranges->size();
            if (sz != 0) {
                for (XMLSize_t i =0; i<sz; i++) {
                    if (ranges->elementAt(i) != 0)
                        ranges->elementAt(i)->updateRangeForDeletedNode(oldChild);
                }
            }
        }
    }

    // Patch linked list around oldChild
    // Note: lastChild == fFirstChild->previousSibling
    if (oldChild == fFirstChild) {
        // removing first child
        castToNodeImpl(oldChild)->isFirstChild(false);
        fFirstChild = castToChildImpl(oldChild)->nextSibling;
        if (fFirstChild != 0) {
            castToNodeImpl(fFirstChild)->isFirstChild(true);
            castToChildImpl(fFirstChild)->previousSibling = castToChildImpl(oldChild)->previousSibling;
        }
    } else {
        DOMNode *prev = castToChildImpl(oldChild)->previousSibling;
        DOMNode *next = castToChildImpl(oldChild)->nextSibling;
        castToChildImpl(prev)->nextSibling = next;
        if (next == 0) {
            // removing last child
            castToChildImpl(fFirstChild)->previousSibling = prev;
        } else {
            // removing some other child in the middle
            castToChildImpl(next)->previousSibling = prev;
        }
    }

    // Remove oldChild's references to tree
    castToNodeImpl(oldChild)->fOwnerNode = fOwnerDocument;
    castToNodeImpl(oldChild)->isOwned(false);
    castToChildImpl(oldChild)->nextSibling = 0;
    castToChildImpl(oldChild)->previousSibling = 0;

    changed();

    return oldChild;
};

DOMNode *DOMParentNode::replaceChild(DOMNode *newChild, DOMNode *oldChild)
{
    insertBefore(newChild, oldChild);
    // changed() already done.
    return removeChild(oldChild);
};

//Introduced in DOM Level 2

void DOMParentNode::normalize()
{
    DOMNode *kid, *next;
    for (kid = fFirstChild; kid != 0; kid = next)
    {
        next = castToChildImpl(kid)->nextSibling;

        // If kid and next are both Text nodes (but _not_ CDATASection,
        // which is a subclass of Text), they can be merged.
        if (next != 0 &&
            kid->getNodeType() == DOMNode::TEXT_NODE   &&
            next->getNodeType() == DOMNode::TEXT_NODE )
        {
            ((DOMTextImpl *) kid)->appendData(((DOMTextImpl *) next)->getData());
            // revisit:
            //   should I release the removed node?
            //   not released in case user still referencing it externally
            removeChild(next);
            next = kid; // Don't advance; there might be another.
        }

        // Otherwise it might be an Element, which is handled recursively
        else
            if (kid->getNodeType() == DOMNode::ELEMENT_NODE)
                kid->normalize();
    };

    // changed() will have occurred when the removeChild() was done,
    // so does not have to be reissued.
};

//Introduced in DOM Level 3

bool DOMParentNode::isEqualNode(const DOMNode* arg)
{
    if (arg && castToNodeImpl(this)->isSameNode(arg))
        return true;

    if (arg && castToNodeImpl(this)->isEqualNode(arg))
    {
        DOMNode *kid, *argKid;
        for (kid = fFirstChild, argKid = arg->getFirstChild();
             kid != 0 && argKid != 0;
             kid = kid->getNextSibling(), argKid = argKid->getNextSibling())
        {
            if (!kid->isEqualNode(argKid))
                return false;
        }
        return (kid || argKid) ? false : true;
    }
    return false;
}

//Non-standard extension
void DOMParentNode::release()
{
    DOMNode *kid, *next;
    for (kid = fFirstChild; kid != 0; kid = next)
    {
        next = castToChildImpl(kid)->nextSibling;

        // set is Owned false before releasing its child
        castToNodeImpl(kid)->isToBeReleased(true);
        kid->release();
    }
}

<commit_msg>Performance: use fParent's ownerdocument directly<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 2001-2002 The Apache Software Foundation.  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. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xerces" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache\@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
 * ITS 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.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation, and was
 * originally based on software copyright (c) 2001, International
 * Business Machines, Inc., http://www.ibm.com .  For more information
 * on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */

/*
 * $Id$
 */

#include <xercesc/util/XercesDefs.hpp>
#include <xercesc/dom/DOMException.hpp>
#include <xercesc/dom/DOMNode.hpp>

#include "DOMDocumentImpl.hpp"
#include "DOMNodeListImpl.hpp"
#include "DOMRangeImpl.hpp"
#include "DOMParentNode.hpp"
#include "DOMCasts.hpp"

DOMParentNode::DOMParentNode(DOMDocument *ownerDoc)
    : fOwnerDocument(ownerDoc), fChildNodeList(castToNode(this))
{
    fFirstChild = 0;
};

// This only makes a shallow copy, cloneChildren must also be called for a
// deep clone
DOMParentNode::DOMParentNode(const DOMParentNode &other)  :
    fChildNodeList(castToNode(this))
{
    this->fOwnerDocument = other.fOwnerDocument;

    // Need to break the association w/ original kids
    this->fFirstChild = 0;
};

void DOMParentNode::changed()
{
    DOMDocumentImpl *doc = (DOMDocumentImpl *)this->getOwnerDocument();
    doc->changed();
}

int DOMParentNode::changes() const
{
    DOMDocumentImpl *doc = (DOMDocumentImpl *)this->getOwnerDocument();
    return doc->changes();
};

DOMNode * DOMParentNode::appendChild(DOMNode *newChild)
{
    return insertBefore(newChild, 0);
};

void DOMParentNode::cloneChildren(const DOMNode *other) {
  //    for (DOMNode *mykid = other.getFirstChild();
    for (DOMNode *mykid = other->getFirstChild();
         mykid != 0;
         mykid = mykid->getNextSibling())
    {
        appendChild(mykid->cloneNode(true));
    }
}

DOMDocument * DOMParentNode::getOwnerDocument() const {
    return fOwnerDocument;
}

// unlike getOwnerDocument this is not overriden by DocumentImpl to return 0
DOMDocument * DOMParentNode::getDocument() const {
    return fOwnerDocument;
}

void DOMParentNode::setOwnerDocument(DOMDocument* doc) {
    fOwnerDocument = doc;
}

DOMNodeList *DOMParentNode::getChildNodes() const {
    const DOMNodeList *ret = &fChildNodeList;
    return (DOMNodeList *)ret;   // cast off const.
};

DOMNode * DOMParentNode::getFirstChild() const {
    return fFirstChild;
};

DOMNode * DOMParentNode::getLastChild() const
{
    return lastChild();
};

DOMNode * DOMParentNode::lastChild() const
{
    // last child is stored as the previous sibling of first child
    if (fFirstChild == 0) {
        return 0;
    }

    DOMChildNode *firstChild = castToChildImpl(fFirstChild);
    DOMNode *ret = firstChild->previousSibling;
    return ret;
};

//
//  revisit.  Is this function used anywhere?  I don't see it.
//
void DOMParentNode::lastChild(DOMNode *node) {
    // store lastChild as previous sibling of first child
    if (fFirstChild != 0) {
        DOMChildNode *firstChild = castToChildImpl(fFirstChild);
        firstChild->previousSibling = node;
    }
}

bool DOMParentNode::hasChildNodes() const
{
    return fFirstChild!=0;
};

DOMNode *DOMParentNode::insertBefore(DOMNode *newChild, DOMNode *refChild) {
    DOMNodeImpl *thisNodeImpl = castToNodeImpl(this);
    if (thisNodeImpl->isReadOnly())
        throw DOMException(DOMException::NO_MODIFICATION_ALLOWED_ERR, 0);

    if (newChild->getOwnerDocument() != fOwnerDocument)
        throw DOMException(DOMException::WRONG_DOCUMENT_ERR, 0);

    // Prevent cycles in the tree
    bool treeSafe=true;
    for(DOMNode *a=castToNode(this)->getParentNode();
        treeSafe && a!=0;
        a=a->getParentNode())
        treeSafe=(newChild!=a);
    if(!treeSafe)
        throw DOMException(DOMException::HIERARCHY_REQUEST_ERR,0);

    // refChild must in fact be a child of this node (or 0)
    if (refChild!=0 && refChild->getParentNode() != castToNode(this))
        throw DOMException(DOMException::NOT_FOUND_ERR,0);

    if (newChild->getNodeType() == DOMNode::DOCUMENT_FRAGMENT_NODE)
    {
        // SLOW BUT SAFE: We could insert the whole subtree without
        // juggling so many next/previous pointers. (Wipe out the
        // parent's child-list, patch the parent pointers, set the
        // ends of the list.) But we know some subclasses have special-
        // case behavior they add to insertBefore(), so we don't risk it.
        // This approch also takes fewer bytecodes.

        // NOTE: If one of the children is not a legal child of this
        // node, throw HIERARCHY_REQUEST_ERR before _any_ of the children
        // have been transferred. (Alternative behaviors would be to
        // reparent up to the first failure point or reparent all those
        // which are acceptable to the target node, neither of which is
        // as robust. PR-DOM-0818 isn't entirely clear on which it
        // recommends?????

        // No need to check kids for right-document; if they weren't,
        // they wouldn't be kids of that DocFrag.
        for(DOMNode *kid=newChild->getFirstChild(); // Prescan
              kid!=0;
              kid=kid->getNextSibling())
        {
            if (!DOMDocumentImpl::isKidOK(castToNode(this), kid))
              throw DOMException(DOMException::HIERARCHY_REQUEST_ERR,0);
        }
        while(newChild->hasChildNodes())     // Move
            insertBefore(newChild->getFirstChild(),refChild);
    }

    else if (!DOMDocumentImpl::isKidOK(castToNode(this), newChild))
        throw DOMException(DOMException::HIERARCHY_REQUEST_ERR,0);

    else
    {
        DOMNode *oldparent=newChild->getParentNode();
        if(oldparent!=0)
            oldparent->removeChild(newChild);

        // Attach up
        castToNodeImpl(newChild)->fOwnerNode = castToNode(this);
        castToNodeImpl(newChild)->isOwned(true);

        // Attach before and after
        // Note: fFirstChild.previousSibling == lastChild!!
        if (fFirstChild == 0) {
            // this our first and only child
            fFirstChild = newChild;
            castToNodeImpl(newChild)->isFirstChild(true);
            // castToChildImpl(newChild)->previousSibling = newChild;
            DOMChildNode *newChild_ci = castToChildImpl(newChild);
            newChild_ci->previousSibling = newChild;
        } else {
            if (refChild == 0) {
                // this is an append
                DOMNode *lastChild = castToChildImpl(fFirstChild)->previousSibling;
                castToChildImpl(lastChild)->nextSibling = newChild;
                castToChildImpl(newChild)->previousSibling = lastChild;
                castToChildImpl(fFirstChild)->previousSibling = newChild;
            } else {
                // this is an insert
                if (refChild == fFirstChild) {
                    // at the head of the list
                    castToNodeImpl(fFirstChild)->isFirstChild(false);
                    castToChildImpl(newChild)->nextSibling = fFirstChild;
                    castToChildImpl(newChild)->previousSibling = castToChildImpl(fFirstChild)->previousSibling;
                    castToChildImpl(fFirstChild)->previousSibling = newChild;
                    fFirstChild = newChild;
                    castToNodeImpl(newChild)->isFirstChild(true);
                } else {
                    // somewhere in the middle
                    DOMNode *prev = castToChildImpl(refChild)->previousSibling;
                    castToChildImpl(newChild)->nextSibling = refChild;
                    castToChildImpl(prev)->nextSibling = newChild;
                    castToChildImpl(refChild)->previousSibling = newChild;
                    castToChildImpl(newChild)->previousSibling = prev;
                }
            }
        }
    }

    changed();

    if (this->getOwnerDocument() != 0) {
        Ranges* ranges = ((DOMDocumentImpl *)this->getOwnerDocument())->getRanges();
        if ( ranges != 0) {
            XMLSize_t sz = ranges->size();
            if (sz != 0) {
                for (XMLSize_t i =0; i<sz; i++) {
                    ranges->elementAt(i)->updateRangeForInsertedNode(newChild);
                }
            }
        }
    }

    return newChild;
};

DOMNode *DOMParentNode::removeChild(DOMNode *oldChild)
{
    if (castToNodeImpl(this)->isReadOnly())
        throw DOMException(
        DOMException::NO_MODIFICATION_ALLOWED_ERR, 0);

    if (oldChild != 0 && oldChild->getParentNode() != castToNode(this))
        throw DOMException(DOMException::NOT_FOUND_ERR, 0);

    //fix other ranges for change before deleting the node
    if (this->getOwnerDocument() !=  0  ) {
        Ranges* ranges = ((DOMDocumentImpl *)this->getOwnerDocument())->getRanges();
        if (ranges != 0) {
            XMLSize_t sz = ranges->size();
            if (sz != 0) {
                for (XMLSize_t i =0; i<sz; i++) {
                    if (ranges->elementAt(i) != 0)
                        ranges->elementAt(i)->updateRangeForDeletedNode(oldChild);
                }
            }
        }
    }

    // Patch linked list around oldChild
    // Note: lastChild == fFirstChild->previousSibling
    if (oldChild == fFirstChild) {
        // removing first child
        castToNodeImpl(oldChild)->isFirstChild(false);
        fFirstChild = castToChildImpl(oldChild)->nextSibling;
        if (fFirstChild != 0) {
            castToNodeImpl(fFirstChild)->isFirstChild(true);
            castToChildImpl(fFirstChild)->previousSibling = castToChildImpl(oldChild)->previousSibling;
        }
    } else {
        DOMNode *prev = castToChildImpl(oldChild)->previousSibling;
        DOMNode *next = castToChildImpl(oldChild)->nextSibling;
        castToChildImpl(prev)->nextSibling = next;
        if (next == 0) {
            // removing last child
            castToChildImpl(fFirstChild)->previousSibling = prev;
        } else {
            // removing some other child in the middle
            castToChildImpl(next)->previousSibling = prev;
        }
    }

    // Remove oldChild's references to tree
    castToNodeImpl(oldChild)->fOwnerNode = fOwnerDocument;
    castToNodeImpl(oldChild)->isOwned(false);
    castToChildImpl(oldChild)->nextSibling = 0;
    castToChildImpl(oldChild)->previousSibling = 0;

    changed();

    return oldChild;
};

DOMNode *DOMParentNode::replaceChild(DOMNode *newChild, DOMNode *oldChild)
{
    insertBefore(newChild, oldChild);
    // changed() already done.
    return removeChild(oldChild);
};

//Introduced in DOM Level 2

void DOMParentNode::normalize()
{
    DOMNode *kid, *next;
    for (kid = fFirstChild; kid != 0; kid = next)
    {
        next = castToChildImpl(kid)->nextSibling;

        // If kid and next are both Text nodes (but _not_ CDATASection,
        // which is a subclass of Text), they can be merged.
        if (next != 0 &&
            kid->getNodeType() == DOMNode::TEXT_NODE   &&
            next->getNodeType() == DOMNode::TEXT_NODE )
        {
            ((DOMTextImpl *) kid)->appendData(((DOMTextImpl *) next)->getData());
            // revisit:
            //   should I release the removed node?
            //   not released in case user still referencing it externally
            removeChild(next);
            next = kid; // Don't advance; there might be another.
        }

        // Otherwise it might be an Element, which is handled recursively
        else
            if (kid->getNodeType() == DOMNode::ELEMENT_NODE)
                kid->normalize();
    };

    // changed() will have occurred when the removeChild() was done,
    // so does not have to be reissued.
};

//Introduced in DOM Level 3

bool DOMParentNode::isEqualNode(const DOMNode* arg)
{
    if (arg && castToNodeImpl(this)->isSameNode(arg))
        return true;

    if (arg && castToNodeImpl(this)->isEqualNode(arg))
    {
        DOMNode *kid, *argKid;
        for (kid = fFirstChild, argKid = arg->getFirstChild();
             kid != 0 && argKid != 0;
             kid = kid->getNextSibling(), argKid = argKid->getNextSibling())
        {
            if (!kid->isEqualNode(argKid))
                return false;
        }
        return (kid || argKid) ? false : true;
    }
    return false;
}

//Non-standard extension
void DOMParentNode::release()
{
    DOMNode *kid, *next;
    for (kid = fFirstChild; kid != 0; kid = next)
    {
        next = castToChildImpl(kid)->nextSibling;

        // set is Owned false before releasing its child
        castToNodeImpl(kid)->isToBeReleased(true);
        kid->release();
    }
}

<|endoftext|>


<commit_before>#ifndef STAN_MATH_PRIM_MAT_FUN_TO_ARRAY_1D_HPP
#define STAN_MATH_PRIM_MAT_FUN_TO_ARRAY_1D_HPP

#include <stan/math/prim/mat/fun/Eigen.hpp>
#include <stan/math/prim/scal/meta/scalar_type.hpp>
#include <vector>

namespace stan {
  namespace math {

    // real[] to_array_1d(matrix)
    // real[] to_array_1d(row_std::vector)
    // real[] to_array_1d(std::vector)
    template <typename T, int R, int C>
    inline std::vector<T> to_array_1d(
      const Eigen::Matrix<T, R, C> & matrix
    ) {
      const T* datap = matrix.data();
      int size = matrix.size();
      std::vector<T> result(size);
      for (int i=0; i < size; i++)
        result[i] = datap[i];
      return result;
    }

    // real[] to_array_1d(...)
    template <typename T>
    inline std::vector<T>
    to_array_1d(const std::vector<T> & x) {
      return x;
    }

    // real[] to_array_1d(...)
    template <typename T>
    inline std::vector<typename scalar_type<T>::type>
    to_array_1d(const std::vector< std::vector<T> > & x) {
      size_t size1 = x.size();
      size_t size2 = 0;
      if (size1 != 0)
        size2 = x[0].size();
      std::vector<T> y(size1*size2);
      for (size_t i = 0, ij = 0; i < size1; i++)
        for (size_t j = 0; j < size2; j++, ij++)
          y[ij] = x[i][j];
      return to_array_1d(y);
    }

  }
}
#endif
<commit_msg>Fixing accidental sed on comments.<commit_after>#ifndef STAN_MATH_PRIM_MAT_FUN_TO_ARRAY_1D_HPP
#define STAN_MATH_PRIM_MAT_FUN_TO_ARRAY_1D_HPP

#include <stan/math/prim/mat/fun/Eigen.hpp>
#include <stan/math/prim/scal/meta/scalar_type.hpp>
#include <vector>

namespace stan {
  namespace math {

    // real[] to_array_1d(matrix)
    // real[] to_array_1d(row_vector)
    // real[] to_array_1d(vector)
    template <typename T, int R, int C>
    inline std::vector<T> to_array_1d(
      const Eigen::Matrix<T, R, C> & matrix
    ) {
      const T* datap = matrix.data();
      int size = matrix.size();
      std::vector<T> result(size);
      for (int i=0; i < size; i++)
        result[i] = datap[i];
      return result;
    }

    // real[] to_array_1d(...)
    template <typename T>
    inline std::vector<T>
    to_array_1d(const std::vector<T> & x) {
      return x;
    }

    // real[] to_array_1d(...)
    template <typename T>
    inline std::vector<typename scalar_type<T>::type>
    to_array_1d(const std::vector< std::vector<T> > & x) {
      size_t size1 = x.size();
      size_t size2 = 0;
      if (size1 != 0)
        size2 = x[0].size();
      std::vector<T> y(size1*size2);
      for (size_t i = 0, ij = 0; i < size1; i++)
        for (size_t j = 0; j < size2; j++, ij++)
          y[ij] = x[i][j];
      return to_array_1d(y);
    }

  }
}
#endif
<|endoftext|>


<commit_before>#include <stan/version.hpp>
#include <gtest/gtest.h>

TEST(Stan, macro) {
  EXPECT_EQ(2, STAN_MAJOR);
  EXPECT_EQ(6, STAN_MINOR);
  EXPECT_EQ(3, STAN_PATCH);
}

TEST(Stan, version) {
  EXPECT_EQ("2", stan::MAJOR_VERSION);
  EXPECT_EQ("6", stan::MINOR_VERSION);
  EXPECT_EQ("3", stan::PATCH_VERSION);
}
<commit_msg>updating version test<commit_after>#include <stan/version.hpp>
#include <gtest/gtest.h>

TEST(Stan, macro) {
  EXPECT_EQ(2, STAN_MAJOR);
  EXPECT_EQ(7, STAN_MINOR);
  EXPECT_EQ(0, STAN_PATCH);
}

TEST(Stan, version) {
  EXPECT_EQ("2", stan::MAJOR_VERSION);
  EXPECT_EQ("7", stan::MINOR_VERSION);
  EXPECT_EQ("0", stan::PATCH_VERSION);
}
<|endoftext|>


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

#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE CudaPipeline_test

// Standard includes
#include <string>

// Third party includes
#include <boost/test/unit_test.hpp>

// Local VOTCA includes
#include "votca/xtp/cudapipeline.h"
#include "votca/xtp/eigen.h"

using namespace votca::xtp;

BOOST_AUTO_TEST_SUITE(CudaPipeline_test)

BOOST_AUTO_TEST_CASE(matmul) {
  // Call the class to handle GPU resources
  CudaPipeline cuda_pip(0);

  Eigen::MatrixXd A = Eigen::MatrixXd::Random(6, 10);
  Eigen::MatrixXd B = Eigen::MatrixXd::Random(10, 6);

  Eigen::MatrixXd C = Eigen::MatrixXd::Zero(6, 6);

  CudaMatrix Ag{A, cuda_pip.get_stream()};
  CudaMatrix Bg{B, cuda_pip.get_stream()};
  CudaMatrix Cg{C, cuda_pip.get_stream()};

  cuda_pip.gemm(Ag, Bg, Cg);

  Eigen::MatrixXd GPU_result = Cg;
  Eigen::MatrixXd CPU_result = A * B;
  bool check = CPU_result.isApprox(GPU_result, 1e-9);
  BOOST_CHECK_EQUAL(check, true);
  if (!check) {
    std::cout << "CPU\n" << CPU_result << std::endl;
    std::cout << "GPU\n" << GPU_result << std::endl;
  }
}

BOOST_AUTO_TEST_CASE(matmul_Cb) {
  // Call the class to handle GPU resources
  CudaPipeline cuda_pip(0);

  Eigen::MatrixXd A = Eigen::MatrixXd::Random(6, 10);
  Eigen::MatrixXd B = Eigen::MatrixXd::Random(10, 6);

  Eigen::MatrixXd C = Eigen::MatrixXd::Zero(8, 10);

  CudaMatrix Ag{A, cuda_pip.get_stream()};
  CudaMatrix Bg{B, cuda_pip.get_stream()};
  CudaMatrix Cg{C, cuda_pip.get_stream()};

  cuda_pip.gemm(Ag, Bg, Cg.block(1, 2, 6, 6));

  Eigen::MatrixXd GPU_result = Cg;
  Eigen::MatrixXd CPU_result = A * B;
  bool check = CPU_result.isApprox(GPU_result.block(1, 2, 6, 6), 1e-9);
  BOOST_CHECK_EQUAL(check, true);
  if (!check) {
    std::cout << "CPU\n" << CPU_result << std::endl;
    std::cout << "GPU\n" << GPU_result << std::endl;
  }
}

BOOST_AUTO_TEST_CASE(matmul_ABb) {
  // Call the class to handle GPU resources
  CudaPipeline cuda_pip(0);

  Eigen::MatrixXd A = Eigen::MatrixXd::Random(6, 10);
  Eigen::MatrixXd B = Eigen::MatrixXd::Random(15, 10);

  Eigen::MatrixXd C = Eigen::MatrixXd::Zero(6, 6);

  CudaMatrix Ag{A, cuda_pip.get_stream()};
  CudaMatrix Bg{B, cuda_pip.get_stream()};
  CudaMatrix Cg{C, cuda_pip.get_stream()};

  cuda_pip.gemm(Ag, Bg.block(2, 3, 10, 6), Cg);

  Eigen::MatrixXd GPU_result = Cg;
  Eigen::MatrixXd CPU_result = A * B.block(2, 3, 10, 6);
  bool check = CPU_result.isApprox(GPU_result, 1e-9);
  BOOST_CHECK_EQUAL(check, true);
  if (!check) {
    std::cout << "CPU\n" << CPU_result << std::endl;
    std::cout << "GPU\n" << GPU_result << std::endl;
  }
}

BOOST_AUTO_TEST_CASE(matmul_AbB) {
  // Call the class to handle GPU resources
  CudaPipeline cuda_pip(0);

  Eigen::MatrixXd A = Eigen::MatrixXd::Random(10, 15);
  Eigen::MatrixXd B = Eigen::MatrixXd::Random(10, 6);

  Eigen::MatrixXd C = Eigen::MatrixXd::Zero(6, 6);

  CudaMatrix Ag{A, cuda_pip.get_stream()};
  CudaMatrix Bg{B, cuda_pip.get_stream()};
  CudaMatrix Cg{C, cuda_pip.get_stream()};

  cuda_pip.gemm(Ag.block(2, 3, 6, 10), Bg, Cg);

  Eigen::MatrixXd GPU_result = Cg;
  Eigen::MatrixXd CPU_result = A.block(2, 3, 6, 10) * B;
  bool check = CPU_result.isApprox(GPU_result, 1e-9);
  BOOST_CHECK_EQUAL(check, true);
  if (!check) {
    std::cout << "CPU\n" << CPU_result << std::endl;
    std::cout << "GPU\n" << GPU_result << std::endl;
  }
}

BOOST_AUTO_TEST_CASE(matmul_add) {
  // Call the class to handle GPU resources
  CudaPipeline cuda_pip(0);

  Eigen::MatrixXd A = Eigen::MatrixXd::Random(6, 10);
  Eigen::MatrixXd B = Eigen::MatrixXd::Random(10, 6);

  Eigen::MatrixXd C = Eigen::MatrixXd::Random(6, 6);

  CudaMatrix Ag{A, cuda_pip.get_stream()};
  CudaMatrix Bg{B, cuda_pip.get_stream()};
  CudaMatrix Cg{C, cuda_pip.get_stream()};

  cuda_pip.gemm(Ag, Bg, Cg, 2.0);

  Eigen::MatrixXd GPU_result = Cg;
  Eigen::MatrixXd CPU_result = A * B + 2 * C;
  bool check = CPU_result.isApprox(GPU_result, 1e-9);
  BOOST_CHECK_EQUAL(check, true);
  if (!check) {
    std::cout << "CPU\n" << CPU_result << std::endl;
    std::cout << "GPU\n" << GPU_result << std::endl;
  }
}

BOOST_AUTO_TEST_CASE(matmul_ABt) {
  // Call the class to handle GPU resources
  CudaPipeline cuda_pip(0);

  Eigen::MatrixXd A = Eigen::MatrixXd::Random(6, 10);
  Eigen::MatrixXd B = Eigen::MatrixXd::Random(6, 10);

  Eigen::MatrixXd C = Eigen::MatrixXd::Zero(6, 6);

  CudaMatrix Ag{A, cuda_pip.get_stream()};
  CudaMatrix Bg{B, cuda_pip.get_stream()};
  CudaMatrix Cg{C, cuda_pip.get_stream()};

  cuda_pip.gemm(Ag, Bg.transpose(), Cg);

  Eigen::MatrixXd GPU_result = Cg;
  Eigen::MatrixXd CPU_result = A * B.transpose();
  bool check = CPU_result.isApprox(GPU_result, 1e-9);
  BOOST_CHECK_EQUAL(check, true);
  if (!check) {
    std::cout << "CPU\n" << CPU_result << std::endl;
    std::cout << "GPU\n" << GPU_result << std::endl;
  }
}

BOOST_AUTO_TEST_CASE(matmul_AtB) {
  // Call the class to handle GPU resources
  CudaPipeline cuda_pip(0);

  Eigen::MatrixXd A = Eigen::MatrixXd::Random(10, 6);
  Eigen::MatrixXd B = Eigen::MatrixXd::Random(10, 6);

  Eigen::MatrixXd C = Eigen::MatrixXd::Zero(6, 6);

  CudaMatrix Ag{A, cuda_pip.get_stream()};
  CudaMatrix Bg{B, cuda_pip.get_stream()};
  CudaMatrix Cg{C, cuda_pip.get_stream()};

  cuda_pip.gemm(Ag.transpose(), Bg, Cg);

  Eigen::MatrixXd GPU_result = Cg;
  Eigen::MatrixXd CPU_result = A.transpose() * B;
  bool check = CPU_result.isApprox(GPU_result, 1e-9);
  BOOST_CHECK_EQUAL(check, true);
  if (!check) {
    std::cout << "CPU\n" << CPU_result << std::endl;
    std::cout << "GPU\n" << GPU_result << std::endl;
  }
}

BOOST_AUTO_TEST_CASE(matmul_AtBt) {
  // Call the class to handle GPU resources
  CudaPipeline cuda_pip(0);

  Eigen::MatrixXd A = Eigen::MatrixXd::Random(10, 6);
  Eigen::MatrixXd B = Eigen::MatrixXd::Random(6, 10);

  Eigen::MatrixXd C = Eigen::MatrixXd::Zero(6, 6);

  CudaMatrix Ag{A, cuda_pip.get_stream()};
  CudaMatrix Bg{B, cuda_pip.get_stream()};
  CudaMatrix Cg{C, cuda_pip.get_stream()};

  cuda_pip.gemm(Ag.transpose(), Bg.transpose(), Cg);

  Eigen::MatrixXd GPU_result = Cg;
  Eigen::MatrixXd CPU_result = A.transpose() * B.transpose();
  bool check = CPU_result.isApprox(GPU_result, 1e-9);
  BOOST_CHECK_EQUAL(check, true);
  if (!check) {
    std::cout << "CPU\n" << CPU_result << std::endl;
    std::cout << "GPU\n" << GPU_result << std::endl;
  }
}

BOOST_AUTO_TEST_CASE(diag_matrix_mul) {
  // Call the class to handle GPU resources
  CudaPipeline cuda_pip(0);

  Eigen::MatrixXd A = Eigen::MatrixXd::Random(6, 10);
  Eigen::VectorXd b = Eigen::VectorXd::Random(10);

  Eigen::MatrixXd C = Eigen::MatrixXd::Zero(6, 10);

  CudaMatrix Ag{A, cuda_pip.get_stream()};
  CudaMatrix bg{b, cuda_pip.get_stream()};
  CudaMatrix Cg{C, cuda_pip.get_stream()};

  cuda_pip.diag_gemm(Ag, bg, Cg);

  Eigen::MatrixXd GPU_result = Cg;
  Eigen::MatrixXd CPU_result =  A*b.asDiagonal();
  bool check = CPU_result.isApprox(GPU_result, 1e-9);
  BOOST_CHECK_EQUAL(check, true);
  if (!check) {
    std::cout << "CPU\n" << CPU_result << std::endl;
    std::cout << "GPU\n" << GPU_result << std::endl;
  }
}

BOOST_AUTO_TEST_CASE(diag_matrix_mul) {
  // Call the class to handle GPU resources
  CudaPipeline cuda_pip(0);

  Eigen::MatrixXd A = Eigen::MatrixXd::Random(10, 6);
  Eigen::VectorXd b = Eigen::VectorXd::Random(10);

  Eigen::MatrixXd C = Eigen::MatrixXd::Zero(10, 6);

  CudaMatrix Ag{A, cuda_pip.get_stream()};
  CudaMatrix bg{b, cuda_pip.get_stream()};
  CudaMatrix Cg{C, cuda_pip.get_stream()};

  cuda_pip.diag_gemm(Ag.transpose(), bg, Cg);

  Eigen::MatrixXd GPU_result = Cg;
  Eigen::MatrixXd CPU_result = b.asDiagonal() * A;
  bool check = CPU_result.isApprox(GPU_result, 1e-9);
  BOOST_CHECK_EQUAL(check, true);
  if (!check) {
    std::cout << "CPU\n" << CPU_result << std::endl;
    std::cout << "GPU\n" << GPU_result << std::endl;
  }
}

BOOST_AUTO_TEST_CASE(diag_matrix_mul_onemat) {
  // Call the class to handle GPU resources
  CudaPipeline cuda_pip(0);

  Eigen::MatrixXd A = Eigen::MatrixXd::Random(10, 6);
  Eigen::VectorXd b = Eigen::VectorXd::Random(10);

  CudaMatrix Ag{A, cuda_pip.get_stream()};
  CudaMatrix bg{b, cuda_pip.get_stream()};

  cuda_pip.diag_gemm(Ag.transpose(), bg, Ag);

  Eigen::MatrixXd GPU_result = Ag;
  Eigen::MatrixXd CPU_result = b.asDiagonal() * A;
  bool check = CPU_result.isApprox(GPU_result, 1e-9);
  BOOST_CHECK_EQUAL(check, true);
  if (!check) {
    std::cout << "CPU\n" << CPU_result << std::endl;
    std::cout << "GPU\n" << GPU_result << std::endl;
  }
}

BOOST_AUTO_TEST_CASE(axpy) {
  // Call the class to handle GPU resources
  CudaPipeline cuda_pip(0);

  Eigen::MatrixXd A = Eigen::MatrixXd::Random(8, 10);
  Eigen::MatrixXd B = Eigen::MatrixXd::Random(8, 10);

  CudaMatrix Ag{A, cuda_pip.get_stream()};
  CudaMatrix Bg{B, cuda_pip.get_stream()};

  cuda_pip.axpy(Ag, Bg, 3.0);

  Eigen::MatrixXd GPU_result = Bg;
  Eigen::MatrixXd CPU_result = B + 3.0 * A;
  bool check = CPU_result.isApprox(GPU_result, 1e-9);
  BOOST_CHECK_EQUAL(check, true);
  if (!check) {
    std::cout << "CPU\n" << CPU_result << std::endl;
    std::cout << "GPU\n" << GPU_result << std::endl;
  }
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>fixed name<commit_after>/*
 * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE CudaPipeline_test

// Standard includes
#include <string>

// Third party includes
#include <boost/test/unit_test.hpp>

// Local VOTCA includes
#include "votca/xtp/cudapipeline.h"
#include "votca/xtp/eigen.h"

using namespace votca::xtp;

BOOST_AUTO_TEST_SUITE(CudaPipeline_test)

BOOST_AUTO_TEST_CASE(matmul) {
  // Call the class to handle GPU resources
  CudaPipeline cuda_pip(0);

  Eigen::MatrixXd A = Eigen::MatrixXd::Random(6, 10);
  Eigen::MatrixXd B = Eigen::MatrixXd::Random(10, 6);

  Eigen::MatrixXd C = Eigen::MatrixXd::Zero(6, 6);

  CudaMatrix Ag{A, cuda_pip.get_stream()};
  CudaMatrix Bg{B, cuda_pip.get_stream()};
  CudaMatrix Cg{C, cuda_pip.get_stream()};

  cuda_pip.gemm(Ag, Bg, Cg);

  Eigen::MatrixXd GPU_result = Cg;
  Eigen::MatrixXd CPU_result = A * B;
  bool check = CPU_result.isApprox(GPU_result, 1e-9);
  BOOST_CHECK_EQUAL(check, true);
  if (!check) {
    std::cout << "CPU\n" << CPU_result << std::endl;
    std::cout << "GPU\n" << GPU_result << std::endl;
  }
}

BOOST_AUTO_TEST_CASE(matmul_Cb) {
  // Call the class to handle GPU resources
  CudaPipeline cuda_pip(0);

  Eigen::MatrixXd A = Eigen::MatrixXd::Random(6, 10);
  Eigen::MatrixXd B = Eigen::MatrixXd::Random(10, 6);

  Eigen::MatrixXd C = Eigen::MatrixXd::Zero(8, 10);

  CudaMatrix Ag{A, cuda_pip.get_stream()};
  CudaMatrix Bg{B, cuda_pip.get_stream()};
  CudaMatrix Cg{C, cuda_pip.get_stream()};

  cuda_pip.gemm(Ag, Bg, Cg.block(1, 2, 6, 6));

  Eigen::MatrixXd GPU_result = Cg;
  Eigen::MatrixXd CPU_result = A * B;
  bool check = CPU_result.isApprox(GPU_result.block(1, 2, 6, 6), 1e-9);
  BOOST_CHECK_EQUAL(check, true);
  if (!check) {
    std::cout << "CPU\n" << CPU_result << std::endl;
    std::cout << "GPU\n" << GPU_result << std::endl;
  }
}

BOOST_AUTO_TEST_CASE(matmul_ABb) {
  // Call the class to handle GPU resources
  CudaPipeline cuda_pip(0);

  Eigen::MatrixXd A = Eigen::MatrixXd::Random(6, 10);
  Eigen::MatrixXd B = Eigen::MatrixXd::Random(15, 10);

  Eigen::MatrixXd C = Eigen::MatrixXd::Zero(6, 6);

  CudaMatrix Ag{A, cuda_pip.get_stream()};
  CudaMatrix Bg{B, cuda_pip.get_stream()};
  CudaMatrix Cg{C, cuda_pip.get_stream()};

  cuda_pip.gemm(Ag, Bg.block(2, 3, 10, 6), Cg);

  Eigen::MatrixXd GPU_result = Cg;
  Eigen::MatrixXd CPU_result = A * B.block(2, 3, 10, 6);
  bool check = CPU_result.isApprox(GPU_result, 1e-9);
  BOOST_CHECK_EQUAL(check, true);
  if (!check) {
    std::cout << "CPU\n" << CPU_result << std::endl;
    std::cout << "GPU\n" << GPU_result << std::endl;
  }
}

BOOST_AUTO_TEST_CASE(matmul_AbB) {
  // Call the class to handle GPU resources
  CudaPipeline cuda_pip(0);

  Eigen::MatrixXd A = Eigen::MatrixXd::Random(10, 15);
  Eigen::MatrixXd B = Eigen::MatrixXd::Random(10, 6);

  Eigen::MatrixXd C = Eigen::MatrixXd::Zero(6, 6);

  CudaMatrix Ag{A, cuda_pip.get_stream()};
  CudaMatrix Bg{B, cuda_pip.get_stream()};
  CudaMatrix Cg{C, cuda_pip.get_stream()};

  cuda_pip.gemm(Ag.block(2, 3, 6, 10), Bg, Cg);

  Eigen::MatrixXd GPU_result = Cg;
  Eigen::MatrixXd CPU_result = A.block(2, 3, 6, 10) * B;
  bool check = CPU_result.isApprox(GPU_result, 1e-9);
  BOOST_CHECK_EQUAL(check, true);
  if (!check) {
    std::cout << "CPU\n" << CPU_result << std::endl;
    std::cout << "GPU\n" << GPU_result << std::endl;
  }
}

BOOST_AUTO_TEST_CASE(matmul_add) {
  // Call the class to handle GPU resources
  CudaPipeline cuda_pip(0);

  Eigen::MatrixXd A = Eigen::MatrixXd::Random(6, 10);
  Eigen::MatrixXd B = Eigen::MatrixXd::Random(10, 6);

  Eigen::MatrixXd C = Eigen::MatrixXd::Random(6, 6);

  CudaMatrix Ag{A, cuda_pip.get_stream()};
  CudaMatrix Bg{B, cuda_pip.get_stream()};
  CudaMatrix Cg{C, cuda_pip.get_stream()};

  cuda_pip.gemm(Ag, Bg, Cg, 2.0);

  Eigen::MatrixXd GPU_result = Cg;
  Eigen::MatrixXd CPU_result = A * B + 2 * C;
  bool check = CPU_result.isApprox(GPU_result, 1e-9);
  BOOST_CHECK_EQUAL(check, true);
  if (!check) {
    std::cout << "CPU\n" << CPU_result << std::endl;
    std::cout << "GPU\n" << GPU_result << std::endl;
  }
}

BOOST_AUTO_TEST_CASE(matmul_ABt) {
  // Call the class to handle GPU resources
  CudaPipeline cuda_pip(0);

  Eigen::MatrixXd A = Eigen::MatrixXd::Random(6, 10);
  Eigen::MatrixXd B = Eigen::MatrixXd::Random(6, 10);

  Eigen::MatrixXd C = Eigen::MatrixXd::Zero(6, 6);

  CudaMatrix Ag{A, cuda_pip.get_stream()};
  CudaMatrix Bg{B, cuda_pip.get_stream()};
  CudaMatrix Cg{C, cuda_pip.get_stream()};

  cuda_pip.gemm(Ag, Bg.transpose(), Cg);

  Eigen::MatrixXd GPU_result = Cg;
  Eigen::MatrixXd CPU_result = A * B.transpose();
  bool check = CPU_result.isApprox(GPU_result, 1e-9);
  BOOST_CHECK_EQUAL(check, true);
  if (!check) {
    std::cout << "CPU\n" << CPU_result << std::endl;
    std::cout << "GPU\n" << GPU_result << std::endl;
  }
}

BOOST_AUTO_TEST_CASE(matmul_AtB) {
  // Call the class to handle GPU resources
  CudaPipeline cuda_pip(0);

  Eigen::MatrixXd A = Eigen::MatrixXd::Random(10, 6);
  Eigen::MatrixXd B = Eigen::MatrixXd::Random(10, 6);

  Eigen::MatrixXd C = Eigen::MatrixXd::Zero(6, 6);

  CudaMatrix Ag{A, cuda_pip.get_stream()};
  CudaMatrix Bg{B, cuda_pip.get_stream()};
  CudaMatrix Cg{C, cuda_pip.get_stream()};

  cuda_pip.gemm(Ag.transpose(), Bg, Cg);

  Eigen::MatrixXd GPU_result = Cg;
  Eigen::MatrixXd CPU_result = A.transpose() * B;
  bool check = CPU_result.isApprox(GPU_result, 1e-9);
  BOOST_CHECK_EQUAL(check, true);
  if (!check) {
    std::cout << "CPU\n" << CPU_result << std::endl;
    std::cout << "GPU\n" << GPU_result << std::endl;
  }
}

BOOST_AUTO_TEST_CASE(matmul_AtBt) {
  // Call the class to handle GPU resources
  CudaPipeline cuda_pip(0);

  Eigen::MatrixXd A = Eigen::MatrixXd::Random(10, 6);
  Eigen::MatrixXd B = Eigen::MatrixXd::Random(6, 10);

  Eigen::MatrixXd C = Eigen::MatrixXd::Zero(6, 6);

  CudaMatrix Ag{A, cuda_pip.get_stream()};
  CudaMatrix Bg{B, cuda_pip.get_stream()};
  CudaMatrix Cg{C, cuda_pip.get_stream()};

  cuda_pip.gemm(Ag.transpose(), Bg.transpose(), Cg);

  Eigen::MatrixXd GPU_result = Cg;
  Eigen::MatrixXd CPU_result = A.transpose() * B.transpose();
  bool check = CPU_result.isApprox(GPU_result, 1e-9);
  BOOST_CHECK_EQUAL(check, true);
  if (!check) {
    std::cout << "CPU\n" << CPU_result << std::endl;
    std::cout << "GPU\n" << GPU_result << std::endl;
  }
}

BOOST_AUTO_TEST_CASE(diag_matrix_mul) {
  // Call the class to handle GPU resources
  CudaPipeline cuda_pip(0);

  Eigen::MatrixXd A = Eigen::MatrixXd::Random(6, 10);
  Eigen::VectorXd b = Eigen::VectorXd::Random(10);

  Eigen::MatrixXd C = Eigen::MatrixXd::Zero(6, 10);

  CudaMatrix Ag{A, cuda_pip.get_stream()};
  CudaMatrix bg{b, cuda_pip.get_stream()};
  CudaMatrix Cg{C, cuda_pip.get_stream()};

  cuda_pip.diag_gemm(Ag, bg, Cg);

  Eigen::MatrixXd GPU_result = Cg;
  Eigen::MatrixXd CPU_result =  A*b.asDiagonal();
  bool check = CPU_result.isApprox(GPU_result, 1e-9);
  BOOST_CHECK_EQUAL(check, true);
  if (!check) {
    std::cout << "CPU\n" << CPU_result << std::endl;
    std::cout << "GPU\n" << GPU_result << std::endl;
  }
}

BOOST_AUTO_TEST_CASE(diag_matrix_mulT) {
  // Call the class to handle GPU resources
  CudaPipeline cuda_pip(0);

  Eigen::MatrixXd A = Eigen::MatrixXd::Random(10, 6);
  Eigen::VectorXd b = Eigen::VectorXd::Random(10);

  Eigen::MatrixXd C = Eigen::MatrixXd::Zero(10, 6);

  CudaMatrix Ag{A, cuda_pip.get_stream()};
  CudaMatrix bg{b, cuda_pip.get_stream()};
  CudaMatrix Cg{C, cuda_pip.get_stream()};

  cuda_pip.diag_gemm(Ag.transpose(), bg, Cg);

  Eigen::MatrixXd GPU_result = Cg;
  Eigen::MatrixXd CPU_result = b.asDiagonal() * A;
  bool check = CPU_result.isApprox(GPU_result, 1e-9);
  BOOST_CHECK_EQUAL(check, true);
  if (!check) {
    std::cout << "CPU\n" << CPU_result << std::endl;
    std::cout << "GPU\n" << GPU_result << std::endl;
  }
}

BOOST_AUTO_TEST_CASE(diag_matrix_mul_onemat) {
  // Call the class to handle GPU resources
  CudaPipeline cuda_pip(0);

  Eigen::MatrixXd A = Eigen::MatrixXd::Random(10, 6);
  Eigen::VectorXd b = Eigen::VectorXd::Random(10);

  CudaMatrix Ag{A, cuda_pip.get_stream()};
  CudaMatrix bg{b, cuda_pip.get_stream()};

  cuda_pip.diag_gemm(Ag.transpose(), bg, Ag);

  Eigen::MatrixXd GPU_result = Ag;
  Eigen::MatrixXd CPU_result = b.asDiagonal() * A;
  bool check = CPU_result.isApprox(GPU_result, 1e-9);
  BOOST_CHECK_EQUAL(check, true);
  if (!check) {
    std::cout << "CPU\n" << CPU_result << std::endl;
    std::cout << "GPU\n" << GPU_result << std::endl;
  }
}

BOOST_AUTO_TEST_CASE(axpy) {
  // Call the class to handle GPU resources
  CudaPipeline cuda_pip(0);

  Eigen::MatrixXd A = Eigen::MatrixXd::Random(8, 10);
  Eigen::MatrixXd B = Eigen::MatrixXd::Random(8, 10);

  CudaMatrix Ag{A, cuda_pip.get_stream()};
  CudaMatrix Bg{B, cuda_pip.get_stream()};

  cuda_pip.axpy(Ag, Bg, 3.0);

  Eigen::MatrixXd GPU_result = Bg;
  Eigen::MatrixXd CPU_result = B + 3.0 * A;
  bool check = CPU_result.isApprox(GPU_result, 1e-9);
  BOOST_CHECK_EQUAL(check, true);
  if (!check) {
    std::cout << "CPU\n" << CPU_result << std::endl;
    std::cout << "GPU\n" << GPU_result << std::endl;
  }
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: svgwriter.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 21:57:21 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef SVGWRITER_HXX
#define SVGWRITER_HXX

#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#ifndef __RTL_USTRING_
#include <rtl/ustring>
#endif
#ifndef _DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _STREAM_HXX
#include <tools/stream.hxx>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#ifndef _STACK_HXX
#include <tools/stack.hxx>
#endif
#ifndef _SALBTYPE_HXX
#include <vcl/salbtype.hxx>
#endif
#ifndef _GDIMTF_HXX
#include <vcl/gdimtf.hxx>
#endif
#ifndef _METAACT_HXX
#include <vcl/metaact.hxx>
#endif
#ifndef _METAACT_HXX
#include <vcl/metric.hxx>
#endif
#ifndef _VIRDEV_HXX
#include <vcl/virdev.hxx>
#endif
#ifndef _CVTGRF_HXX
#include <vcl/cvtgrf.hxx>
#endif
#ifndef _XMLOFF_XMLEXP_HXX
#include <xmloff/xmlexp.hxx>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif

#include <com/sun/star/uno/Reference.h>
#include <com/sun/star/uno/RuntimeException.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/registry/XRegistryKey.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/io/XInputStream.hpp>
#include <com/sun/star/io/XOutputStream.hpp>
#include <com/sun/star/xml/sax/XDocumentHandler.hpp>
#include <com/sun/star/xml/sax/XExtendedDocumentHandler.hpp>

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

#define _SVG_USE_NATIVE_TEXTDECORATION
#define _SVG_USE_TSPANS 1
#undef  _SVG_WRITE_EXTENTS
#define _SVG_EMBED_FONTS 1

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

#define NMSP_CPPU               cppu
#define NMSP_RTL                rtl
#define NMSP_UNO                com::sun::star::uno
#define NMSP_LANG               com::sun::star::lang
#define NMSP_SAX                com::sun::star::xml::sax
#define NMSP_SVG                com::sun::star::svg
#define NMSP_REGISTRY           com::sun::star::registry

#define REF( _def_Obj )         NMSP_UNO::Reference< _def_Obj >
#define SEQ( _def_Obj )         NMSP_UNO::Sequence< _def_Obj >
#define B2UCONST( _def_pChar )  (NMSP_RTL::OUString(RTL_CONSTASCII_USTRINGPARAM(_def_pChar )))
#define SVG_DTD_STRING          B2UCONST( "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">" )

#define SVGWRITER_WRITE_NONE    0x00000000
#define SVGWRITER_WRITE_FILL    0x00000001
#define SVGWRITER_WRITE_TEXT    0x00000002
#define SVGWRITER_WRITE_ALL     0xFFFFFFFF

// --------------
// - FastString -
// --------------

class FastString
{
private:

    rtl::OUString               maString;
    sal_Unicode*                mpBuffer;
    sal_uInt32                  mnBufLen;
    sal_uInt32                  mnCurLen;
    sal_uInt32                  mnBufInc;
    sal_uInt32                  mnPartPos;

public:

                                FastString( sal_uInt32 nInitLen = 2048, sal_uInt32 nIncrement = 2048 );
                                FastString( sal_Char* pBufferForBase64Encoding, sal_uInt32 nBufLen );
                                ~FastString();

    FastString&                 operator+=( const ::rtl::OUString& rStr );

    const ::rtl::OUString&      GetString() const;
    sal_Bool                    GetFirstPartString( const sal_uInt32 nPartLen, ::rtl::OUString& rPartString );
    sal_Bool                    GetNextPartString( const sal_uInt32 nPartLen, ::rtl::OUString& rPartString );

    sal_uInt32                  GetLength() const { return mnCurLen; }
    void                        Clear() { mnCurLen = 0, maString = ::rtl::OUString(); }
};

// ----------------------
// - SVGAttributeWriter -
// ----------------------

class SVGActionWriter;
class SVGFontExport;

class SVGAttributeWriter
{
private:

    Font                    maCurFont;
    Color                   maCurLineColor;
    Color                   maCurFillColor;
    SvXMLExport&            mrExport;
    SVGFontExport&          mrFontExport;
    SvXMLElementExport*     mpElemFont;
    SvXMLElementExport*     mpElemPaint;

                            SVGAttributeWriter();

public:

                            SVGAttributeWriter( SvXMLExport& rExport, SVGFontExport& rFontExport );
    virtual                 ~SVGAttributeWriter();

    ::rtl::OUString         GetFontStyle( const Font& rFont );
    ::rtl::OUString         GetPaintStyle( const Color& rLineColor, const Color& rFillColor );

    void                    SetFontAttr( const Font& rFont );
    void                    SetPaintAttr( const Color& rLineColor, const Color& rFillColor );
};

// -------------------
// - SVGActionWriter -
// -------------------

class SVGAttributeWriter;
class SvXMLExport;
class GDIMetaFile;

class SVGActionWriter
{
private:

    Stack                   maContextStack;
    SvXMLExport&            mrExport;
    SVGFontExport&          mrFontExport;
    SVGAttributeWriter*     mpContext;
    VirtualDevice*          mpVDev;
    MapMode                 maTargetMapMode;
    sal_Int32               mnCurClipId;
    sal_Bool                mbDestroyVDev;
    sal_Bool                mbPaintAttrChanged;
    sal_Bool                mbFontAttrChanged;
    sal_Bool                mbClipAttrChanged;

    SVGAttributeWriter*     ImplAcquireContext() { maContextStack.Push( mpContext = new SVGAttributeWriter( mrExport, mrFontExport ) ); return mpContext; }
    void                    ImplReleaseContext() { delete (SVGAttributeWriter*) maContextStack.Pop(); mpContext = (SVGAttributeWriter*) maContextStack.Top(); }

    long                    ImplMap( sal_Int32 nVal ) const;
    Point                   ImplMap( const Point& rPt ) const;
    Size                    ImplMap( const Size& rSz ) const;
    inline Rectangle        ImplMap( const Rectangle& rRect ) const { return Rectangle( ImplMap( rRect.TopLeft() ), ImplMap( rRect.GetSize() ) ); }

    void                    ImplWriteLine( const Point& rPt1, const Point& rPt2, const Color* pLineColor = NULL, const ::rtl::OUString* pStyle = NULL );
    void                    ImplWriteRect( const Rectangle& rRect, long nRadX = 0, long nRadY = 0, const ::rtl::OUString* pStyle = NULL );
    void                    ImplWriteEllipse( const Point& rCenter, long nRadX, long nRadY, const ::rtl::OUString* pStyle = NULL );
    void                    ImplWritePolyPolygon( const PolyPolygon& rPolyPoly, sal_Bool bLineOnly, const ::rtl::OUString* pStyle = NULL );
    void                    ImplWriteGradientEx( const PolyPolygon& rPolyPoly, const Gradient& rGradient, const ::rtl::OUString* pStyle, sal_uInt32 nWriteFlags );
    void                    ImplWriteText( const Point& rPos, const String& rText, const long* pDXArray, long nWidth, const ::rtl::OUString* pStyle = NULL );
    void                    ImplWriteBmp( const BitmapEx& rBmpEx, const Point& rPt, const Size& rSz, const Point& rSrcPt, const Size& rSrcSz, const ::rtl::OUString* pStyle = NULL );

    void                    ImplCheckFontAttributes();
    void                    ImplCheckPaintAttributes();

    void                    ImplWriteActions( const GDIMetaFile& rMtf, const ::rtl::OUString* pStyle, sal_uInt32 nWriteFlags );
    sal_Int32               ImplGetNextClipId() { return mnCurClipId++; }

public:

    static ::rtl::OUString  GetValueString( sal_Int32 nVal );
    static ::rtl::OUString  GetPathString( const PolyPolygon& rPolyPoly, sal_Bool bLine );

public:

                            SVGActionWriter( SvXMLExport& rExport, SVGFontExport& rFontExport );
    virtual                 ~SVGActionWriter();

    void                    WriteMetaFile( const Point& rPos100thmm,
                                           const Size& rSize100thmm,
                                           const GDIMetaFile& rMtf,
                                           sal_uInt32 nWriteFlags = SVGWRITER_WRITE_ALL );
};

#endif
<commit_msg>INTEGRATION: CWS dxarray (1.4.6); FILE MERGED 2005/09/19 11:41:24 kendy 1.4.6.1: #i54697# "long *pDXArray" -> "sal_Int32 *pDXArray" patches extracted from ooo64bit02 to conform the declaration in VCL.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: svgwriter.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: kz $ $Date: 2005-10-05 12:54:10 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef SVGWRITER_HXX
#define SVGWRITER_HXX

#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#ifndef __RTL_USTRING_
#include <rtl/ustring>
#endif
#ifndef _DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _STREAM_HXX
#include <tools/stream.hxx>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#ifndef _STACK_HXX
#include <tools/stack.hxx>
#endif
#ifndef _SALBTYPE_HXX
#include <vcl/salbtype.hxx>
#endif
#ifndef _GDIMTF_HXX
#include <vcl/gdimtf.hxx>
#endif
#ifndef _METAACT_HXX
#include <vcl/metaact.hxx>
#endif
#ifndef _METAACT_HXX
#include <vcl/metric.hxx>
#endif
#ifndef _VIRDEV_HXX
#include <vcl/virdev.hxx>
#endif
#ifndef _CVTGRF_HXX
#include <vcl/cvtgrf.hxx>
#endif
#ifndef _XMLOFF_XMLEXP_HXX
#include <xmloff/xmlexp.hxx>
#endif
#ifndef _XMLOFF_NMSPMAP_HXX
#include <xmloff/nmspmap.hxx>
#endif

#include <com/sun/star/uno/Reference.h>
#include <com/sun/star/uno/RuntimeException.hpp>
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/registry/XRegistryKey.hpp>
#include <com/sun/star/lang/XComponent.hpp>
#include <com/sun/star/io/XInputStream.hpp>
#include <com/sun/star/io/XOutputStream.hpp>
#include <com/sun/star/xml/sax/XDocumentHandler.hpp>
#include <com/sun/star/xml/sax/XExtendedDocumentHandler.hpp>

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

#define _SVG_USE_NATIVE_TEXTDECORATION
#define _SVG_USE_TSPANS 1
#undef  _SVG_WRITE_EXTENTS
#define _SVG_EMBED_FONTS 1

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

#define NMSP_CPPU               cppu
#define NMSP_RTL                rtl
#define NMSP_UNO                com::sun::star::uno
#define NMSP_LANG               com::sun::star::lang
#define NMSP_SAX                com::sun::star::xml::sax
#define NMSP_SVG                com::sun::star::svg
#define NMSP_REGISTRY           com::sun::star::registry

#define REF( _def_Obj )         NMSP_UNO::Reference< _def_Obj >
#define SEQ( _def_Obj )         NMSP_UNO::Sequence< _def_Obj >
#define B2UCONST( _def_pChar )  (NMSP_RTL::OUString(RTL_CONSTASCII_USTRINGPARAM(_def_pChar )))
#define SVG_DTD_STRING          B2UCONST( "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">" )

#define SVGWRITER_WRITE_NONE    0x00000000
#define SVGWRITER_WRITE_FILL    0x00000001
#define SVGWRITER_WRITE_TEXT    0x00000002
#define SVGWRITER_WRITE_ALL     0xFFFFFFFF

// --------------
// - FastString -
// --------------

class FastString
{
private:

    rtl::OUString               maString;
    sal_Unicode*                mpBuffer;
    sal_uInt32                  mnBufLen;
    sal_uInt32                  mnCurLen;
    sal_uInt32                  mnBufInc;
    sal_uInt32                  mnPartPos;

public:

                                FastString( sal_uInt32 nInitLen = 2048, sal_uInt32 nIncrement = 2048 );
                                FastString( sal_Char* pBufferForBase64Encoding, sal_uInt32 nBufLen );
                                ~FastString();

    FastString&                 operator+=( const ::rtl::OUString& rStr );

    const ::rtl::OUString&      GetString() const;
    sal_Bool                    GetFirstPartString( const sal_uInt32 nPartLen, ::rtl::OUString& rPartString );
    sal_Bool                    GetNextPartString( const sal_uInt32 nPartLen, ::rtl::OUString& rPartString );

    sal_uInt32                  GetLength() const { return mnCurLen; }
    void                        Clear() { mnCurLen = 0, maString = ::rtl::OUString(); }
};

// ----------------------
// - SVGAttributeWriter -
// ----------------------

class SVGActionWriter;
class SVGFontExport;

class SVGAttributeWriter
{
private:

    Font                    maCurFont;
    Color                   maCurLineColor;
    Color                   maCurFillColor;
    SvXMLExport&            mrExport;
    SVGFontExport&          mrFontExport;
    SvXMLElementExport*     mpElemFont;
    SvXMLElementExport*     mpElemPaint;

                            SVGAttributeWriter();

public:

                            SVGAttributeWriter( SvXMLExport& rExport, SVGFontExport& rFontExport );
    virtual                 ~SVGAttributeWriter();

    ::rtl::OUString         GetFontStyle( const Font& rFont );
    ::rtl::OUString         GetPaintStyle( const Color& rLineColor, const Color& rFillColor );

    void                    SetFontAttr( const Font& rFont );
    void                    SetPaintAttr( const Color& rLineColor, const Color& rFillColor );
};

// -------------------
// - SVGActionWriter -
// -------------------

class SVGAttributeWriter;
class SvXMLExport;
class GDIMetaFile;

class SVGActionWriter
{
private:

    Stack                   maContextStack;
    SvXMLExport&            mrExport;
    SVGFontExport&          mrFontExport;
    SVGAttributeWriter*     mpContext;
    VirtualDevice*          mpVDev;
    MapMode                 maTargetMapMode;
    sal_Int32               mnCurClipId;
    sal_Bool                mbDestroyVDev;
    sal_Bool                mbPaintAttrChanged;
    sal_Bool                mbFontAttrChanged;
    sal_Bool                mbClipAttrChanged;

    SVGAttributeWriter*     ImplAcquireContext() { maContextStack.Push( mpContext = new SVGAttributeWriter( mrExport, mrFontExport ) ); return mpContext; }
    void                    ImplReleaseContext() { delete (SVGAttributeWriter*) maContextStack.Pop(); mpContext = (SVGAttributeWriter*) maContextStack.Top(); }

    long                    ImplMap( sal_Int32 nVal ) const;
    Point                   ImplMap( const Point& rPt ) const;
    Size                    ImplMap( const Size& rSz ) const;
    inline Rectangle        ImplMap( const Rectangle& rRect ) const { return Rectangle( ImplMap( rRect.TopLeft() ), ImplMap( rRect.GetSize() ) ); }

    void                    ImplWriteLine( const Point& rPt1, const Point& rPt2, const Color* pLineColor = NULL, const ::rtl::OUString* pStyle = NULL );
    void                    ImplWriteRect( const Rectangle& rRect, long nRadX = 0, long nRadY = 0, const ::rtl::OUString* pStyle = NULL );
    void                    ImplWriteEllipse( const Point& rCenter, long nRadX, long nRadY, const ::rtl::OUString* pStyle = NULL );
    void                    ImplWritePolyPolygon( const PolyPolygon& rPolyPoly, sal_Bool bLineOnly, const ::rtl::OUString* pStyle = NULL );
    void                    ImplWriteGradientEx( const PolyPolygon& rPolyPoly, const Gradient& rGradient, const ::rtl::OUString* pStyle, sal_uInt32 nWriteFlags );
    void                    ImplWriteText( const Point& rPos, const String& rText, const sal_Int32* pDXArray, long nWidth, const ::rtl::OUString* pStyle = NULL );
    void                    ImplWriteBmp( const BitmapEx& rBmpEx, const Point& rPt, const Size& rSz, const Point& rSrcPt, const Size& rSrcSz, const ::rtl::OUString* pStyle = NULL );

    void                    ImplCheckFontAttributes();
    void                    ImplCheckPaintAttributes();

    void                    ImplWriteActions( const GDIMetaFile& rMtf, const ::rtl::OUString* pStyle, sal_uInt32 nWriteFlags );
    sal_Int32               ImplGetNextClipId() { return mnCurClipId++; }

public:

    static ::rtl::OUString  GetValueString( sal_Int32 nVal );
    static ::rtl::OUString  GetPathString( const PolyPolygon& rPolyPoly, sal_Bool bLine );

public:

                            SVGActionWriter( SvXMLExport& rExport, SVGFontExport& rFontExport );
    virtual                 ~SVGActionWriter();

    void                    WriteMetaFile( const Point& rPos100thmm,
                                           const Size& rSize100thmm,
                                           const GDIMetaFile& rMtf,
                                           sal_uInt32 nWriteFlags = SVGWRITER_WRITE_ALL );
};

#endif
<|endoftext|>