<commit_before>#include "lutgen.hpp"

#include <cmath>
#include <iomanip>
#include <sstream>

#include "export_params.hpp"
#include "fileutils.hpp"
#include "logger.hpp"
#include "scanner.hpp"
#include "shared.hpp"

const std::map<std::string, LutFunc> function_map =
{
    {"cos", LutFunc(cos, true)},
    {"sin", LutFunc(sin, true)},
    {"tan", LutFunc(tan, true)},
    {"acos", LutFunc(acos, false, true)},
    {"asin", LutFunc(asin, false, true)},
    {"atan", LutFunc(atan, false, true)},
    {"cosh", LutFunc(cosh, true)},
    {"sinh", LutFunc(sinh, true)},
    {"tanh", LutFunc(tanh, true)},
    {"acosh", LutFunc(acosh, false, true)},
    {"asinh", LutFunc(asinh, false, true)},
    {"atanh", LutFunc(atanh, false, true)},
    {"exp", exp},
    {"log", log},
    {"log10", log10},
    {"log2", log2},
    {"exp2", exp2},
    {"expm1", expm1},
    {"log1p", log1p},
    {"sqrt", sqrt},
    {"cbrt", cbrt},
    {"erf", erf},
    {"erfc", erfc},
    {"tgamma", tgamma},
    {"lgamma", lgamma},
};

const std::map<std::string, LutType> type_map = {
    {"char",  LutType::CHAR},
    {"byte",  LutType::CHAR},
    {"short", LutType::SHORT},
    {"int",   LutType::INT},
    {"long",  LutType::LONG},
};

const std::map<LutType, std::string> type_map_rev = {
    {LutType::CHAR, "char"},
    {LutType::SHORT, "short"},
    {LutType::INT, "int"},
    {LutType::LONG, "long"},
};

std::string form_fixed_string(int64_t fixed, const LutIOType& lut_type)
{
    std::stringstream str;
    int pad = (lut_type.GetLength() + 3) / 4;
    if (pad == 0) pad = 1;
    uint64_t mask = (1L << lut_type.GetLength()) - 1;
    if (lut_type.GetLength() > 0)
        str << "((" << (fixed >> lut_type.GetLength()) << " << " << lut_type.GetLength() << ") | 0x" << std::setfill('0')
            << std::setw(pad) << std::hex << (fixed & mask) << ")";
    else
        str << fixed;
    return str.str();
}

LutSpecification::LutSpecification(const std::string& spec)
{
    Scanner scan(spec, ",");
    if (!scan.Next(function))
        FatalLog("Could not parse function name %s", spec.c_str());
    if (!scan.Next(type))
        FatalLog("Could not parse type %s", spec.c_str());
    if (!scan.Next(begin))
        FatalLog("Could not parse begin %s", spec.c_str());
    if (!scan.Next(end))
        FatalLog("Could not parse end %s", spec.c_str());
    if (!scan.Next(step))
        FatalLog("Could not parse step %s", spec.c_str());
    if (scan.HasMoreTokens())
    {
        if (!scan.Next(in_degrees))
            FatalLog("Could not parse in_degrees %s", spec.c_str());
    }
}

std::string LutSpecification::str() const
{
    std::stringstream out;
    out << "Function: " << function << " Type: " << type << " Range: [" << begin << ", " << end << "] Step: " << step;
    return out.str();
}

LutFunc::LutFunc(MathFunction func, bool in_radians, bool out_radians) : function(func), input_radians(in_radians), output_radians(out_radians)
{
}

double LutFunc::operator()(double value, bool in_degrees) const
{
    // If function accepts radians and value given is in degrees
    if (input_radians && in_degrees)
        value *= PI / 180;
    double out = function(value);
    // If function outputs radians and value we want to be in degrees
    if (output_radians && in_degrees)
        out *= 180 / PI;
    return out;
}

LutIOType::LutIOType(const std::string& type_spec) : fixed_length(0)
{
    Scanner scan(type_spec, ".");
    std::string type_str;

    if (!scan.Next(type_str))
        FatalLog("Unable to parse type string %s", type_spec.c_str());

    if (scan.HasMoreTokens())
    {
        if (!scan.Next(fixed_length))
            FatalLog("Unable to parse type string %s", type_str.c_str());
    }

    if (type_map.find(type_str) == type_map.end())
        FatalLog("Valid data types are char, byte, short, int, and long. %s given", type_str.c_str());
    type = type_map.at(type_str);

    unsigned int num_bits = 1 << ((unsigned int)type + 3);
    if (fixed_length >= num_bits)
        FatalLog("Invalid number given for fixed point %d given >= %d bits", fixed_length, num_bits);
}

double LutIOType::ConvertToDouble(int64_t fixed) const
{
    ///TODO fix this
    double answer = fixed >> fixed_length;
    int64_t fractional = fixed & ((1 << fixed_length) - 1);
    double current = 1.0;
    for (int i = fixed_length; i >= 0; i--)
    {
        current /= 2;
        if (fractional & (1 << i))
            answer += current;
    }
    return answer;
}

int64_t LutIOType::ConvertToFixed(double fpoint) const
{
    bool negate = fpoint < 0;
    fpoint = fabs(fpoint);
    int64_t integral = ((int64_t)fpoint) << fixed_length;
    int64_t fractional = 0;
    // fpoint should be a decimal
    fpoint -= (int64_t)fpoint;
    double current = 1.0;
    for (unsigned int i = 0; i < fixed_length; i++)
    {
        fractional <<= 1;
        current /= 2;
        if (fpoint >= current)
        {
            fpoint -= current;
            fractional |= 1;
        }
    }
    uint64_t num_bits = 1 << ((unsigned int)type + 3);
    int64_t answer = integral | fractional;
    if (negate) answer = (-answer) & ((1L << num_bits) - 1);
    return answer;
}

LutGenerator::LutGenerator(const std::string& name, const std::string& function_name, bool _in_degrees) : Exportable(name), in_degrees(_in_degrees)
{
    if (function_map.find(function_name) == function_map.end())
        FatalLog("No function named %s can not export LUT", function_name.c_str());

    function = function_map.at(function_name);
}

FixedLutGenerator::FixedLutGenerator(const std::string& name, const std::string& function, double _begin, double _end, double _step,
                                     const std::string& output, bool in_degrees) :
                                     LutGenerator(name, function, in_degrees), type(output), begin(_begin), end(_end), step(_step)
{
    if (step == 0)
        FatalLog("Step must be a nonzero value");
    if (begin >= end)
        FatalLog("Begin must be less than end");
    if ((end - begin) / step > LUT_ENTRIES_MAX && !params.force)
        FatalLog("Will generate %d entries in look up table. If you are sure about this use -force.", end - begin / step);
}

FixedLutGenerator::~FixedLutGenerator()
{

}

void FixedLutGenerator::WriteExport(std::ostream& file) const
{
    unsigned long num_entries = (end - begin) / step + 1;
    WriteExtern(file, "const " + type_map_rev.at(type.GetType()), name, "", num_entries);
    WriteDefine(file, name, "_LENGTH", num_entries);
    WriteDefine(file, name, "_FIXED_LENGTH", type.GetLength());
    WriteDefine(file, name, "_BEGIN", form_fixed_string(type.ConvertToFixed(begin), type));
    WriteDefine(file, name, "_END", form_fixed_string(type.ConvertToFixed(end), type));
    WriteDefine(file, name, "_STEP", form_fixed_string(type.ConvertToFixed(step), type));
    WriteNewLine(file);
}

void FixedLutGenerator::WriteData(std::ostream& file) const
{
    unsigned int size = (end - begin) / step + 1;
    double current = begin;
    file << "const " << type_map_rev.at(type.GetType()) << " " << name << "[" << size << "] =\n{\n\t";
    for (unsigned int i = 0; i < size; i++)
    {
        current = fma(i, step, begin);
        double out = function(current, in_degrees);
        int64_t out_value = type.ConvertToFixed(out);
        VerboseLog("%s(%f) => %f => %ld in_degrees:%d", name.c_str(), current, out, out_value, in_degrees);
        WriteElement(file, form_fixed_string(out_value, type), size, i, 10);
    }
    file << "\n};\n";
    WriteNewLine(file);
}
<commit_msg>Fix error when compiling with -pedantic for lut generators, apparently doesn't like bitwise expressions which overflow into the sign bit<commit_after>#include "lutgen.hpp"

#include <cmath>
#include <iomanip>
#include <sstream>

#include "export_params.hpp"
#include "fileutils.hpp"
#include "logger.hpp"
#include "scanner.hpp"
#include "shared.hpp"

const std::map<std::string, LutFunc> function_map =
{
    {"cos", LutFunc(cos, true)},
    {"sin", LutFunc(sin, true)},
    {"tan", LutFunc(tan, true)},
    {"acos", LutFunc(acos, false, true)},
    {"asin", LutFunc(asin, false, true)},
    {"atan", LutFunc(atan, false, true)},
    {"cosh", LutFunc(cosh, true)},
    {"sinh", LutFunc(sinh, true)},
    {"tanh", LutFunc(tanh, true)},
    {"acosh", LutFunc(acosh, false, true)},
    {"asinh", LutFunc(asinh, false, true)},
    {"atanh", LutFunc(atanh, false, true)},
    {"exp", exp},
    {"log", log},
    {"log10", log10},
    {"log2", log2},
    {"exp2", exp2},
    {"expm1", expm1},
    {"log1p", log1p},
    {"sqrt", sqrt},
    {"cbrt", cbrt},
    {"erf", erf},
    {"erfc", erfc},
    {"tgamma", tgamma},
    {"lgamma", lgamma},
};

const std::map<std::string, LutType> type_map = {
    {"char",  LutType::CHAR},
    {"byte",  LutType::CHAR},
    {"short", LutType::SHORT},
    {"int",   LutType::INT},
    {"long",  LutType::LONG},
};

const std::map<LutType, std::string> type_map_rev = {
    {LutType::CHAR, "char"},
    {LutType::SHORT, "short"},
    {LutType::INT, "int"},
    {LutType::LONG, "long"},
};

std::string form_fixed_string(int64_t fixed, const LutIOType& lut_type)
{
    std::stringstream str;
    int pad = (lut_type.GetLength() + 3) / 4;
    if (pad == 0) pad = 1;
    //uint64_t mask = (1L << lut_type.GetLength()) - 1;
    if (lut_type.GetLength() > 0)
        str << "0x" << std::setfill('0') << std::setw(pad) << std::hex << fixed;
    // Causes a bug with -pedantic turned on if the number is negative.
    //    str << "((" << (fixed >> lut_type.GetLength()) << " << " << lut_type.GetLength() << ") | 0x" << std::setfill('0')
    //        << std::setw(pad) << std::hex << (fixed & mask) << ")";
    else
        str << fixed;
    return str.str();
}

LutSpecification::LutSpecification(const std::string& spec)
{
    Scanner scan(spec, ",");
    if (!scan.Next(function))
        FatalLog("Could not parse function name %s", spec.c_str());
    if (!scan.Next(type))
        FatalLog("Could not parse type %s", spec.c_str());
    if (!scan.Next(begin))
        FatalLog("Could not parse begin %s", spec.c_str());
    if (!scan.Next(end))
        FatalLog("Could not parse end %s", spec.c_str());
    if (!scan.Next(step))
        FatalLog("Could not parse step %s", spec.c_str());
    if (scan.HasMoreTokens())
    {
        if (!scan.Next(in_degrees))
            FatalLog("Could not parse in_degrees %s", spec.c_str());
    }
}

std::string LutSpecification::str() const
{
    std::stringstream out;
    out << "Function: " << function << " Type: " << type << " Range: [" << begin << ", " << end << "] Step: " << step;
    return out.str();
}

LutFunc::LutFunc(MathFunction func, bool in_radians, bool out_radians) : function(func), input_radians(in_radians), output_radians(out_radians)
{
}

double LutFunc::operator()(double value, bool in_degrees) const
{
    // If function accepts radians and value given is in degrees
    if (input_radians && in_degrees)
        value *= PI / 180;
    double out = function(value);
    // If function outputs radians and value we want to be in degrees
    if (output_radians && in_degrees)
        out *= 180 / PI;
    return out;
}

LutIOType::LutIOType(const std::string& type_spec) : fixed_length(0)
{
    Scanner scan(type_spec, ".");
    std::string type_str;

    if (!scan.Next(type_str))
        FatalLog("Unable to parse type string %s", type_spec.c_str());

    if (scan.HasMoreTokens())
    {
        if (!scan.Next(fixed_length))
            FatalLog("Unable to parse type string %s", type_str.c_str());
    }

    if (type_map.find(type_str) == type_map.end())
        FatalLog("Valid data types are char, byte, short, int, and long. %s given", type_str.c_str());
    type = type_map.at(type_str);

    unsigned int num_bits = 1 << ((unsigned int)type + 3);
    if (fixed_length >= num_bits)
        FatalLog("Invalid number given for fixed point %d given >= %d bits", fixed_length, num_bits);
}

double LutIOType::ConvertToDouble(int64_t fixed) const
{
    ///TODO fix this
    double answer = fixed >> fixed_length;
    int64_t fractional = fixed & ((1 << fixed_length) - 1);
    double current = 1.0;
    for (int i = fixed_length; i >= 0; i--)
    {
        current /= 2;
        if (fractional & (1 << i))
            answer += current;
    }
    return answer;
}

int64_t LutIOType::ConvertToFixed(double fpoint) const
{
    bool negate = fpoint < 0;
    fpoint = fabs(fpoint);
    int64_t integral = ((int64_t)fpoint) << fixed_length;
    int64_t fractional = 0;
    // fpoint should be a decimal
    fpoint -= (int64_t)fpoint;
    double current = 1.0;
    for (unsigned int i = 0; i < fixed_length; i++)
    {
        fractional <<= 1;
        current /= 2;
        if (fpoint >= current)
        {
            fpoint -= current;
            fractional |= 1;
        }
    }
    uint64_t num_bits = 1 << ((unsigned int)type + 3);
    int64_t answer = integral | fractional;
    if (negate) answer = (-answer) & ((1L << num_bits) - 1);
    return answer;
}

LutGenerator::LutGenerator(const std::string& name, const std::string& function_name, bool _in_degrees) : Exportable(name), in_degrees(_in_degrees)
{
    if (function_map.find(function_name) == function_map.end())
        FatalLog("No function named %s can not export LUT", function_name.c_str());

    function = function_map.at(function_name);
}

FixedLutGenerator::FixedLutGenerator(const std::string& name, const std::string& function, double _begin, double _end, double _step,
                                     const std::string& output, bool in_degrees) :
                                     LutGenerator(name, function, in_degrees), type(output), begin(_begin), end(_end), step(_step)
{
    if (step == 0)
        FatalLog("Step must be a nonzero value");
    if (begin >= end)
        FatalLog("Begin must be less than end");
    if ((end - begin) / step > LUT_ENTRIES_MAX && !params.force)
        FatalLog("Will generate %d entries in look up table. If you are sure about this use -force.", end - begin / step);
}

FixedLutGenerator::~FixedLutGenerator()
{

}

void FixedLutGenerator::WriteExport(std::ostream& file) const
{
    unsigned long num_entries = (end - begin) / step + 1;
    WriteExtern(file, "const " + type_map_rev.at(type.GetType()), name, "", num_entries);
    WriteDefine(file, name, "_LENGTH", num_entries);
    WriteDefine(file, name, "_FIXED_LENGTH", type.GetLength());
    WriteDefine(file, name, "_BEGIN", form_fixed_string(type.ConvertToFixed(begin), type));
    WriteDefine(file, name, "_END", form_fixed_string(type.ConvertToFixed(end), type));
    WriteDefine(file, name, "_STEP", form_fixed_string(type.ConvertToFixed(step), type));
    WriteNewLine(file);
}

void FixedLutGenerator::WriteData(std::ostream& file) const
{
    unsigned int size = (end - begin) / step + 1;
    double current = begin;
    file << "const " << type_map_rev.at(type.GetType()) << " " << name << "[" << size << "] =\n{\n\t";
    for (unsigned int i = 0; i < size; i++)
    {
        current = fma(i, step, begin);
        double out = function(current, in_degrees);
        int64_t out_value = type.ConvertToFixed(out);
        VerboseLog("%s(%f) => %f => %ld in_degrees:%d", name.c_str(), current, out, out_value, in_degrees);
        WriteElement(file, form_fixed_string(out_value, type), size, i, 10);
    }
    file << "\n};\n";
    WriteNewLine(file);
}
<|endoftext|>


<commit_before>// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "flutter/lib/ui/painting/picture.h"

#include "flutter/fml/make_copyable.h"
#include "flutter/lib/ui/painting/canvas.h"
#include "flutter/lib/ui/ui_dart_state.h"
#include "third_party/skia/include/core/SkImage.h"
#include "third_party/tonic/converter/dart_converter.h"
#include "third_party/tonic/dart_args.h"
#include "third_party/tonic/dart_binding_macros.h"
#include "third_party/tonic/dart_library_natives.h"
#include "third_party/tonic/dart_persistent_value.h"
#include "third_party/tonic/logging/dart_invoke.h"

namespace blink {

IMPLEMENT_WRAPPERTYPEINFO(ui, Picture);

#define FOR_EACH_BINDING(V) \
  V(Picture, toImage)       \
  V(Picture, dispose)       \
  V(Picture, GetAllocationSize)

DART_BIND_ALL(Picture, FOR_EACH_BINDING)

fml::RefPtr<Picture> Picture::Create(flow::SkiaGPUObject<SkPicture> picture) {
  return fml::MakeRefCounted<Picture>(std::move(picture));
}

Picture::Picture(flow::SkiaGPUObject<SkPicture> picture)
    : picture_(std::move(picture)) {}

Picture::~Picture() = default;

Dart_Handle Picture::toImage(uint32_t width,
                             uint32_t height,
                             Dart_Handle raw_image_callback) {
  if (!picture_.get()) {
    return tonic::ToDart("Picture is null");
  }

  return RasterizeToImage(picture_.get(), width, height, raw_image_callback);
}

void Picture::dispose() {
  ClearDartWrapper();
}

size_t Picture::GetAllocationSize() {
  if (auto picture = picture_.get()) {
    return picture->approximateBytesUsed();
  } else {
    return sizeof(Picture);
  }
}

Dart_Handle Picture::RasterizeToImage(sk_sp<SkPicture> picture,
                                      uint32_t width,
                                      uint32_t height,
                                      Dart_Handle raw_image_callback) {
  if (Dart_IsNull(raw_image_callback) || !Dart_IsClosure(raw_image_callback)) {
    return tonic::ToDart("Image callback was invalid");
  }

  if (width == 0 || height == 0) {
    return tonic::ToDart("Image dimensions for scene were invalid.");
  }

  auto* dart_state = UIDartState::Current();
  auto image_callback = std::make_unique<tonic::DartPersistentValue>(
      dart_state, raw_image_callback);
  auto unref_queue = dart_state->GetSkiaUnrefQueue();
  auto ui_task_runner = dart_state->GetTaskRunners().GetUITaskRunner();
  auto gpu_task_runner = dart_state->GetTaskRunners().GetGPUTaskRunner();
  auto snapshot_delegate = dart_state->GetSnapshotDelegate();

  // We can't create an image on this task runner because we don't have a
  // graphics context. Even if we did, it would be slow anyway. Also, this
  // thread owns the sole reference to the layer tree. So we flatten the layer
  // tree into a picture and use that as the thread transport mechanism.

  auto picture_bounds = SkISize::Make(width, height);

  auto ui_task = fml::MakeCopyable(
      [ui_task_runner, image_callback = std::move(image_callback),
       unref_queue](sk_sp<SkImage> raster_image) mutable {
        // Send the raster image back to the UI thread for submission to the
        // framework.
        fml::TaskRunner::RunNowOrPostTask(
            ui_task_runner,
            fml::MakeCopyable([raster_image,
                               image_callback = std::move(image_callback),
                               unref_queue]() mutable {
              auto dart_state = image_callback->dart_state().lock();
              if (!dart_state) {
                // The root isolate could have died in the meantime.
                return;
              }
              tonic::DartState::Scope scope(dart_state);

              if (!raster_image) {
                tonic::DartInvoke(image_callback->Get(), {Dart_Null()});
                return;
              }

              auto dart_image = CanvasImage::Create();
              dart_image->set_image(
                  {std::move(raster_image), std::move(unref_queue)});
              auto* raw_dart_image = tonic::ToDart(std::move(dart_image));

              // All done!
              tonic::DartInvoke(image_callback->Get(), {raw_dart_image});
            }));
      });

  auto gpu_task = fml::MakeCopyable([gpu_task_runner, picture, picture_bounds,
                                     snapshot_delegate, ui_task]() {
    fml::TaskRunner::RunNowOrPostTask(gpu_task_runner, [snapshot_delegate,
                                                        picture, picture_bounds,
                                                        ui_task]() {
      // Snapshot the picture on the GPU thread. This thread has access to the
      // GPU contexts that may contain the sole references to texture backed
      // images in the picture.
      ui_task(snapshot_delegate->MakeRasterSnapshot(picture, picture_bounds));
    });
  });

  // Kick things off on the GPU.
  gpu_task();

  return Dart_Null();
}

}  // namespace blink
<commit_msg>Ensure that Picture::RasterizeToImage destroys Dart persistent values on the UI thread (#8182)<commit_after>// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "flutter/lib/ui/painting/picture.h"

#include "flutter/fml/make_copyable.h"
#include "flutter/lib/ui/painting/canvas.h"
#include "flutter/lib/ui/ui_dart_state.h"
#include "third_party/skia/include/core/SkImage.h"
#include "third_party/tonic/converter/dart_converter.h"
#include "third_party/tonic/dart_args.h"
#include "third_party/tonic/dart_binding_macros.h"
#include "third_party/tonic/dart_library_natives.h"
#include "third_party/tonic/dart_persistent_value.h"
#include "third_party/tonic/logging/dart_invoke.h"

namespace blink {

IMPLEMENT_WRAPPERTYPEINFO(ui, Picture);

#define FOR_EACH_BINDING(V) \
  V(Picture, toImage)       \
  V(Picture, dispose)       \
  V(Picture, GetAllocationSize)

DART_BIND_ALL(Picture, FOR_EACH_BINDING)

fml::RefPtr<Picture> Picture::Create(flow::SkiaGPUObject<SkPicture> picture) {
  return fml::MakeRefCounted<Picture>(std::move(picture));
}

Picture::Picture(flow::SkiaGPUObject<SkPicture> picture)
    : picture_(std::move(picture)) {}

Picture::~Picture() = default;

Dart_Handle Picture::toImage(uint32_t width,
                             uint32_t height,
                             Dart_Handle raw_image_callback) {
  if (!picture_.get()) {
    return tonic::ToDart("Picture is null");
  }

  return RasterizeToImage(picture_.get(), width, height, raw_image_callback);
}

void Picture::dispose() {
  ClearDartWrapper();
}

size_t Picture::GetAllocationSize() {
  if (auto picture = picture_.get()) {
    return picture->approximateBytesUsed();
  } else {
    return sizeof(Picture);
  }
}

Dart_Handle Picture::RasterizeToImage(sk_sp<SkPicture> picture,
                                      uint32_t width,
                                      uint32_t height,
                                      Dart_Handle raw_image_callback) {
  if (Dart_IsNull(raw_image_callback) || !Dart_IsClosure(raw_image_callback)) {
    return tonic::ToDart("Image callback was invalid");
  }

  if (width == 0 || height == 0) {
    return tonic::ToDart("Image dimensions for scene were invalid.");
  }

  auto* dart_state = UIDartState::Current();
  tonic::DartPersistentValue* image_callback =
      new tonic::DartPersistentValue(dart_state, raw_image_callback);
  auto unref_queue = dart_state->GetSkiaUnrefQueue();
  auto ui_task_runner = dart_state->GetTaskRunners().GetUITaskRunner();
  auto gpu_task_runner = dart_state->GetTaskRunners().GetGPUTaskRunner();
  auto snapshot_delegate = dart_state->GetSnapshotDelegate();

  // We can't create an image on this task runner because we don't have a
  // graphics context. Even if we did, it would be slow anyway. Also, this
  // thread owns the sole reference to the layer tree. So we flatten the layer
  // tree into a picture and use that as the thread transport mechanism.

  auto picture_bounds = SkISize::Make(width, height);

  auto ui_task = fml::MakeCopyable([image_callback, unref_queue](
                                       sk_sp<SkImage> raster_image) mutable {
    auto dart_state = image_callback->dart_state().lock();
    if (!dart_state) {
      // The root isolate could have died in the meantime.
      return;
    }
    tonic::DartState::Scope scope(dart_state);

    if (!raster_image) {
      tonic::DartInvoke(image_callback->Get(), {Dart_Null()});
      return;
    }

    auto dart_image = CanvasImage::Create();
    dart_image->set_image({std::move(raster_image), std::move(unref_queue)});
    auto* raw_dart_image = tonic::ToDart(std::move(dart_image));

    // All done!
    tonic::DartInvoke(image_callback->Get(), {raw_dart_image});

    // image_callback is associated with the Dart isolate and must be deleted
    // on the UI thread
    delete image_callback;
  });

  // Kick things off on the GPU.
  fml::TaskRunner::RunNowOrPostTask(
      gpu_task_runner,
      [ui_task_runner, snapshot_delegate, picture, picture_bounds, ui_task] {
        sk_sp<SkImage> raster_image =
            snapshot_delegate->MakeRasterSnapshot(picture, picture_bounds);

        fml::TaskRunner::RunNowOrPostTask(
            ui_task_runner,
            [ui_task, raster_image]() { ui_task(raster_image); });
      });

  return Dart_Null();
}

}  // namespace blink
<|endoftext|>


<commit_before>#include "DefaultReporter.h"
#include <cstdio>
#include <iostream>
#include "TestDetails.h"

namespace xUnitpp
{

namespace DefaultReporter
{
    void ReportStart(const TestDetails &, int)
    {
    }

    void ReportFailure(const TestDetails &testDetails, int dataIndex, const std::string &msg)
    {
        if (dataIndex < 0)
        {
            std::cerr << (testDetails.Filename + "(" + std::to_string(testDetails.Line) +
                "): error " + testDetails.Name + ": " + msg + "\n");
        }
        else
        {
            std::cerr << (testDetails.Filename + "(" + std::to_string(testDetails.Line) +
                "): error " + testDetails.Name + "(" + std::to_string(dataIndex) + "): " + msg + "\n");
        }
    }

    void ReportFinish(const TestDetails &, int, std::chrono::milliseconds)
    {
    }

    void ReportAllTestsComplete(size_t testCount, size_t failureCount, size_t skipped, std::chrono::milliseconds totalTime)
    {
        std::string total = std::to_string(testCount) + " tests, ";
        std::string failures = std::to_string(failureCount) + " failed, ";
        std::string skips = std::to_string(skipped) + " skipped.\n";

        std::string header;

        if (failureCount > 0)
        {
            header = "FAILURE: ";
        }
        else if (skipped > 0)
        {
            header = "WARNING: ";
        }
        else
        {
            header = "Success: ";
        }

        std::cout << (header + total + failures + skips);

        header = "Test time: ";
        std::cout << (header + std::to_string(totalTime.count()) + " milliseconds.\n");
    }

}

}
<commit_msg>improved wording in ouput for failed tests<commit_after>#include "DefaultReporter.h"
#include <cstdio>
#include <iostream>
#include "TestDetails.h"

namespace xUnitpp
{

namespace DefaultReporter
{
    void ReportStart(const TestDetails &, int)
    {
    }

    void ReportFailure(const TestDetails &testDetails, int dataIndex, const std::string &msg)
    {
        if (dataIndex < 0)
        {
            std::cerr << (testDetails.Filename + "(" + std::to_string(testDetails.Line) +
                "): error in " + testDetails.Name + ": " + msg + "\n");
        }
        else
        {
            std::cerr << (testDetails.Filename + "(" + std::to_string(testDetails.Line) +
                "): error in " + testDetails.Name + "(" + std::to_string(dataIndex) + "): " + msg + "\n");
        }
    }

    void ReportFinish(const TestDetails &, int, std::chrono::milliseconds)
    {
    }

    void ReportAllTestsComplete(size_t testCount, size_t failureCount, size_t skipped, std::chrono::milliseconds totalTime)
    {
        std::string total = std::to_string(testCount) + " tests, ";
        std::string failures = std::to_string(failureCount) + " failed, ";
        std::string skips = std::to_string(skipped) + " skipped.\n";

        std::string header;

        if (failureCount > 0)
        {
            header = "FAILURE: ";
        }
        else if (skipped > 0)
        {
            header = "WARNING: ";
        }
        else
        {
            header = "Success: ";
        }

        std::cout << (header + total + failures + skips);

        header = "Test time: ";
        std::cout << (header + std::to_string(totalTime.count()) + " milliseconds.\n");
    }

}

}
<|endoftext|>


<commit_before>/*!
  \copyright (c) RDO-Team, 2013
  \file      init_struct_db.cpp
  \authors     (cerevra@gmail.com)
  \authors     (rdo@rk9.bmstu.ru)
  \date      25.01.2013
  \brief
  \indent    4T
*/

// ---------------------------------------------------------------------------- PCH
// ----------------------------------------------------------------------- INCLUDES
// ----------------------------------------------------------------------- SYNOPSIS
#include "simulator\runtime\src\db\init_struct_db.h"
// --------------------------------------------------------------------------------

InitSructDB::InitSructDB()
{
	generateCreateDBQuery();
	queryExec(m_queryList);
}

void InitSructDB::dropDB()
{
	{
		GeneralDB dbTemp("localhost", "postgres", "postgres", "rdo", 5432);
		dbTemp.queryExec("DROP DATABASE IF EXISTS rdo;");
	}
	QSqlDatabase::removeDatabase("qt_sql_default_connection");
}

void InitSructDB::createDB()
{
	{
		GeneralDB dbTemp("localhost", "postgres", "postgres", "rdo", 5432);
		dbTemp.queryExec("CREATE DATABASE rdo;");
	}
	QSqlDatabase::removeDatabase("qt_sql_default_connection");
}

void InitSructDB::rdoValueTable(QString tableName, QString dataType)
{
	m_queryList.push_back(QString(
		"CREATE TABLE %1("
		"id integer NOT NULL DEFAULT nextval('rdo_value_seq'),"
		"vv %2 NOT NULL,"
		"PRIMARY KEY (id)"
		");")
		.arg(tableName)
		.arg(dataType));

	trigger(tableName,"copy_rdo_value_id");
}

void InitSructDB::dataTypeTable(QString tableName)
{
	m_queryList.push_back(QString(
		"CREATE TABLE %1("
		"id      integer NOT NULL DEFAULT nextval('type_of_param_seq'),"
		"def_val integer,"
		"PRIMARY KEY (id),"
		"FOREIGN KEY (def_val) REFERENCES %1_rv(id)"
		");")
		.arg(tableName));

	trigger(tableName,"copy_type_id");
}

void InitSructDB::trigger(QString tableName, QString functionName)
{
	m_queryList.push_back(QString(
		"CREATE TRIGGER %1_trig "
		"AFTER INSERT ON %1 "
		"FOR EACH ROW "
		"EXECUTE PROCEDURE %2();")
		.arg(tableName)
		.arg(functionName));
}

void InitSructDB::generateCreateDBQuery()
{
	m_queryList.push_back(
		"CREATE TABLE rtp("
		"id       serial,"
		"rtp_name VARCHAR(40) NOT NULL,"
		"rtp_perm boolean NOT NULL,"
		"PRIMARY KEY (id)"
		");");

	m_queryList.push_back(
		"CREATE TABLE list_of_types_of_params("
		"type_id  integer,"
		"table_id integer NOT NULL,"
		"PRIMARY KEY (type_id)"
		");");

	m_queryList.push_back(
		"CREATE TABLE param_of_type("
		"id          serial,"
		"param_name  VARCHAR(40) NOT NULL,"
		"rtp_id      integer,"
		"type_id     integer NOT NULL,"
		"PRIMARY KEY (id,rtp_id),"
		"FOREIGN KEY (rtp_id) REFERENCES rtp(id),"
		"FOREIGN KEY (type_id) REFERENCES list_of_types_of_params"
		");");
//------------------------

//------------------------
	m_queryList.push_back("CREATE SEQUENCE type_of_param_seq;");

	m_queryList.push_back(
		"CREATE FUNCTION copy_type_id() RETURNS TRIGGER AS $trig$ "
		"BEGIN "
		"INSERT INTO list_of_types_of_params VALUES "
		"(NEW.id, NEW.tableoid); "
		"RETURN NULL; "
		"END; "
		"$trig$ LANGUAGE plpgsql; ");
//------------------------

//------------------------
	m_queryList.push_back(
		"CREATE TABLE rdo_value("
		"value_id  integer,"
		"table_id integer NOT NULL,"
		"PRIMARY KEY (value_id)"
		");");

	m_queryList.push_back("CREATE SEQUENCE rdo_value_seq;");

	m_queryList.push_back(
		"CREATE FUNCTION copy_rdo_value_id() RETURNS TRIGGER AS $trig$ "
		"BEGIN "
		"INSERT INTO rdo_value VALUES "
		"(NEW.id, NEW.tableoid); "
		"RETURN NULL; "
		"END; "
		"$trig$ LANGUAGE plpgsql; ");

	rdoValueTable("real_rv","real");
	rdoValueTable("int_rv","integer");
	rdoValueTable("identificator_rv","VARCHAR(40)");
	rdoValueTable("bool_rv","boolean");
	rdoValueTable("string_rv","VARCHAR(40)");
	rdoValueTable("enum_rv","VARCHAR(40)");

	m_queryList.push_back(
		"CREATE TABLE array_rv("
		"id  integer NOT NULL DEFAULT nextval('rdo_value_seq'),"
		"PRIMARY KEY (id)"
		");");

	trigger("array_rv","copy_rdo_value_id");

	m_queryList.push_back(
		"CREATE TABLE array_value("
		"array_id      integer,"
		"array_elem_id serial,"
		"vv_id         integer NOT NULL,"
		"PRIMARY KEY   (array_id, vv_id),"
		"FOREIGN KEY   (array_id) REFERENCES array_rv"
		");");
//------------------------

//------------------------
	m_queryList.push_back(
		"CREATE TABLE real("
		"id          integer NOT NULL DEFAULT nextval('type_of_param_seq'),"
		"def_val     integer,"
		"min         real,"
		"max         real,"
		"PRIMARY KEY (id),"
		"FOREIGN KEY (def_val) REFERENCES real_rv(id)"
		");");

	trigger("real","copy_type_id");
//------------------------

//------------------------
	m_queryList.push_back(
		"CREATE TABLE enum("
		"id          integer NOT NULL DEFAULT nextval('type_of_param_seq'),"
		"def_val     integer,"
		"PRIMARY KEY (id),"
		"FOREIGN KEY (def_val) REFERENCES enum_rv(id)"
		");");

	trigger("enum","copy_type_id");

	m_queryList.push_back(
		"CREATE TABLE enum_valid_value("
		"enum_id     integer,"
		"vv_id       serial,"
		"vv_str      VARCHAR(40) NOT NULL,"
		"vv_int      integer NOT NULL,"
		"PRIMARY KEY (enum_id, vv_id),"
		"FOREIGN KEY (enum_id) REFERENCES enum"
		");");
//------------------------

//------------------------
	m_queryList.push_back(
		"CREATE TABLE int("
		"id          integer NOT NULL DEFAULT nextval('type_of_param_seq'),"
		"def_val     integer,"
		"min         integer,"
		"max         integer,"
		"PRIMARY KEY (id),"
		"FOREIGN KEY (def_val) REFERENCES int_rv(id)"
		");");

	trigger("int","copy_type_id");
//------------------------

//------------------------
	m_queryList.push_back(
		"CREATE TABLE void("
		"id      integer NOT NULL DEFAULT nextval('type_of_param_seq'),"
		"PRIMARY KEY (id)"
		");");

	trigger("void","copy_type_id");
//------------------------

	dataTypeTable("identificator");
	dataTypeTable("bool");
	dataTypeTable("string");
}
<commit_msg> - структура БД: теперь диапазон значений - RDOValue<commit_after>/*!
  \copyright (c) RDO-Team, 2013
  \file      init_struct_db.cpp
  \authors     (cerevra@gmail.com)
  \authors     (rdo@rk9.bmstu.ru)
  \date      25.01.2013
  \brief
  \indent    4T
*/

// ---------------------------------------------------------------------------- PCH
// ----------------------------------------------------------------------- INCLUDES
// ----------------------------------------------------------------------- SYNOPSIS
#include "simulator\runtime\src\db\init_struct_db.h"
// --------------------------------------------------------------------------------

InitSructDB::InitSructDB()
{
	generateCreateDBQuery();
	queryExec(m_queryList);
}

void InitSructDB::dropDB()
{
	{
		GeneralDB dbTemp("localhost", "postgres", "postgres", "rdo", 5432);
		dbTemp.queryExec("DROP DATABASE IF EXISTS rdo;");
	}
	QSqlDatabase::removeDatabase("qt_sql_default_connection");
}

void InitSructDB::createDB()
{
	{
		GeneralDB dbTemp("localhost", "postgres", "postgres", "rdo", 5432);
		dbTemp.queryExec("CREATE DATABASE rdo;");
	}
	QSqlDatabase::removeDatabase("qt_sql_default_connection");
}

void InitSructDB::rdoValueTable(QString tableName, QString dataType)
{
	m_queryList.push_back(QString(
		"CREATE TABLE %1("
		"id integer NOT NULL DEFAULT nextval('rdo_value_seq'),"
		"vv %2 NOT NULL,"
		"PRIMARY KEY (id)"
		");")
		.arg(tableName)
		.arg(dataType));

	trigger(tableName,"copy_rdo_value_id");
}

void InitSructDB::dataTypeTable(QString tableName)
{
	m_queryList.push_back(QString(
		"CREATE TABLE %1("
		"id      integer NOT NULL DEFAULT nextval('type_of_param_seq'),"
		"def_val integer,"
		"PRIMARY KEY (id),"
		"FOREIGN KEY (def_val) REFERENCES %1_rv(id)"
		");")
		.arg(tableName));

	trigger(tableName,"copy_type_id");
}

void InitSructDB::trigger(QString tableName, QString functionName)
{
	m_queryList.push_back(QString(
		"CREATE TRIGGER %1_trig "
		"AFTER INSERT ON %1 "
		"FOR EACH ROW "
		"EXECUTE PROCEDURE %2();")
		.arg(tableName)
		.arg(functionName));
}

void InitSructDB::generateCreateDBQuery()
{
	m_queryList.push_back(
		"CREATE TABLE rtp("
		"id       serial,"
		"rtp_name VARCHAR(40) NOT NULL,"
		"rtp_perm boolean NOT NULL,"
		"PRIMARY KEY (id)"
		");");

	m_queryList.push_back(
		"CREATE TABLE list_of_types_of_params("
		"type_id  integer,"
		"table_id integer NOT NULL,"
		"PRIMARY KEY (type_id)"
		");");

	m_queryList.push_back(
		"CREATE TABLE param_of_type("
		"id          serial,"
		"param_name  VARCHAR(40) NOT NULL,"
		"rtp_id      integer,"
		"type_id     integer NOT NULL,"
		"PRIMARY KEY (id,rtp_id),"
		"FOREIGN KEY (rtp_id) REFERENCES rtp(id),"
		"FOREIGN KEY (type_id) REFERENCES list_of_types_of_params"
		");");
//------------------------

//------------------------
	m_queryList.push_back("CREATE SEQUENCE type_of_param_seq;");

	m_queryList.push_back(
		"CREATE FUNCTION copy_type_id() RETURNS TRIGGER AS $trig$ "
		"BEGIN "
		"INSERT INTO list_of_types_of_params VALUES "
		"(NEW.id, NEW.tableoid); "
		"RETURN NULL; "
		"END; "
		"$trig$ LANGUAGE plpgsql; ");
//------------------------

//------------------------
	m_queryList.push_back(
		"CREATE TABLE rdo_value("
		"value_id  integer,"
		"table_id integer NOT NULL,"
		"PRIMARY KEY (value_id)"
		");");

	m_queryList.push_back("CREATE SEQUENCE rdo_value_seq;");

	m_queryList.push_back(
		"CREATE FUNCTION copy_rdo_value_id() RETURNS TRIGGER AS $trig$ "
		"BEGIN "
		"INSERT INTO rdo_value VALUES "
		"(NEW.id, NEW.tableoid); "
		"RETURN NULL; "
		"END; "
		"$trig$ LANGUAGE plpgsql; ");

	rdoValueTable("real_rv","real");
	rdoValueTable("int_rv","integer");
	rdoValueTable("identificator_rv","VARCHAR(40)");
	rdoValueTable("bool_rv","boolean");
	rdoValueTable("string_rv","VARCHAR(40)");
	rdoValueTable("enum_rv","VARCHAR(40)");

	m_queryList.push_back(
		"CREATE TABLE array_rv("
		"id  integer NOT NULL DEFAULT nextval('rdo_value_seq'),"
		"PRIMARY KEY (id)"
		");");

	trigger("array_rv","copy_rdo_value_id");

	m_queryList.push_back(
		"CREATE TABLE array_value("
		"array_id      integer,"
		"array_elem_id serial,"
		"vv_id         integer NOT NULL,"
		"PRIMARY KEY   (array_id, vv_id),"
		"FOREIGN KEY   (array_id) REFERENCES array_rv"
		");");
//------------------------

//------------------------
	m_queryList.push_back(
		"CREATE TABLE real("
		"id          integer NOT NULL DEFAULT nextval('type_of_param_seq'),"
		"def_val     integer,"
		"min         integer,"
		"max         integer,"
		"PRIMARY KEY (id),"
		"FOREIGN KEY (def_val) REFERENCES real_rv(id),"
		"FOREIGN KEY (min) REFERENCES real_rv(id),"
		"FOREIGN KEY (max) REFERENCES real_rv(id)"
		");");

	trigger("real","copy_type_id");
//------------------------

//------------------------
	m_queryList.push_back(
		"CREATE TABLE enum("
		"id          integer NOT NULL DEFAULT nextval('type_of_param_seq'),"
		"def_val     integer,"
		"PRIMARY KEY (id),"
		"FOREIGN KEY (def_val) REFERENCES enum_rv(id)"
		");");

	trigger("enum","copy_type_id");

	m_queryList.push_back(
		"CREATE TABLE enum_valid_value("
		"enum_id     integer,"
		"vv_id       serial,"
		"vv_str      VARCHAR(40) NOT NULL,"
		"vv_int      integer NOT NULL,"
		"PRIMARY KEY (enum_id, vv_id),"
		"FOREIGN KEY (enum_id) REFERENCES enum"
		");");
//------------------------

//------------------------
	m_queryList.push_back(
		"CREATE TABLE int("
		"id          integer NOT NULL DEFAULT nextval('type_of_param_seq'),"
		"def_val     integer,"
		"min         integer,"
		"max         integer,"
		"PRIMARY KEY (id),"
		"FOREIGN KEY (def_val) REFERENCES int_rv(id),"
		"FOREIGN KEY (min) REFERENCES int_rv(id),"
		"FOREIGN KEY (max) REFERENCES int_rv(id)"
		");");

	trigger("int","copy_type_id");
//------------------------

//------------------------
	m_queryList.push_back(
		"CREATE TABLE void("
		"id      integer NOT NULL DEFAULT nextval('type_of_param_seq'),"
		"PRIMARY KEY (id)"
		");");

	trigger("void","copy_type_id");
//------------------------

	dataTypeTable("identificator");
	dataTypeTable("bool");
	dataTypeTable("string");
}
<|endoftext|>


<commit_before>#include "xchainer/python/routines.h"

#include <cassert>
#include <cstdint>
#include <string>
#include <vector>

#include <nonstd/optional.hpp>

#include "xchainer/array.h"
#include "xchainer/context.h"
#include "xchainer/device.h"
#include "xchainer/dtype.h"
#include "xchainer/error.h"
#include "xchainer/routines/creation.h"
#include "xchainer/routines/linalg.h"
#include "xchainer/routines/logic.h"
#include "xchainer/routines/manipulation.h"
#include "xchainer/routines/math.h"
#include "xchainer/scalar.h"

#include "xchainer/python/array.h"
#include "xchainer/python/array_index.h"
#include "xchainer/python/common.h"
#include "xchainer/python/device.h"
#include "xchainer/python/shape.h"
#include "xchainer/python/strides.h"

namespace xchainer {
namespace python {
namespace internal {

namespace py = pybind11;

namespace {

ArrayBodyPtr MakeArray(const py::list& list, const nonstd::optional<Dtype>& dtype, Device& device) {
    // TODO(sonots): Determine dtype (bool or int64, or float64) seeing values of list.
    // TODO(sonots): Support nested list
    py::tuple shape_tup{1};
    shape_tup[0] = list.size();
    return internal::MakeArray(shape_tup, dtype.value_or(Dtype::kFloat64), list, device);
}

}  // namespace
void InitXchainerRoutines(pybind11::module& m) {
    // creation routines
    m.def("array",
          [](const py::list& list, const nonstd::optional<Dtype>& dtype, const nonstd::optional<std::string>& device_id) {
              return MakeArray(list, dtype, GetDevice(device_id));
          },
          py::arg("object"),
          py::arg("dtype") = nullptr,
          py::arg("device") = nullptr);
    m.def("array",
          [](const py::list& list, const nonstd::optional<Dtype>& dtype, Device& device) { return MakeArray(list, dtype, device); },
          py::arg("object"),
          py::arg("dtype") = nullptr,
          py::arg("device"));
    m.def("array",
          [](const py::array& array, const nonstd::optional<std::string>& device_id) { return MakeArray(array, GetDevice(device_id)); },
          py::arg("object"),
          py::arg("device") = nullptr);
    m.def("array", [](const py::array& array, Device& device) { return MakeArray(array, device); }, py::arg("object"), py::arg("device"));
    m.def("array",
          [](const ArrayBodyPtr& array, const nonstd::optional<std::string>& device_id) {
              if (device_id) {
                  return Array{array}.ToDevice(GetDevice(device_id)).move_body();
              }
              return Array{array}.MakeView().move_body();
          },
          py::arg("object"),
          py::arg("device") = nullptr);
    m.def("array",
          [](const ArrayBodyPtr& array, Device& device) { return Array{array}.ToDevice(device).move_body(); },
          py::arg("object"),
          py::arg("device"));
    m.def("empty",
          [](py::tuple shape, Dtype dtype, const nonstd::optional<std::string>& device_id) {
              return Array::Empty(ToShape(shape), dtype, GetDevice(device_id)).move_body();
          },
          py::arg("shape"),
          py::arg("dtype"),
          py::arg("device") = nullptr);
    m.def("empty",
          [](py::tuple shape, Dtype dtype, Device& device) { return Array::Empty(ToShape(shape), dtype, device).move_body(); },
          py::arg("shape"),
          py::arg("dtype"),
          py::arg("device"));
    m.def("full",
          [](py::tuple shape, Scalar fill_value, Dtype dtype, const nonstd::optional<std::string>& device_id) {
              return Array::Full(ToShape(shape), fill_value, dtype, GetDevice(device_id)).move_body();
          },
          py::arg("shape"),
          py::arg("fill_value"),
          py::arg("dtype"),
          py::arg("device") = nullptr);
    m.def("full",
          [](py::tuple shape, Scalar fill_value, Dtype dtype, Device& device) {
              return Array::Full(ToShape(shape), fill_value, dtype, device).move_body();
          },
          py::arg("shape"),
          py::arg("fill_value"),
          py::arg("dtype"),
          py::arg("device"));
    m.def("full",
          [](py::tuple shape, Scalar fill_value, const nonstd::optional<std::string>& device_id) {
              return Array::Full(ToShape(shape), fill_value, GetDevice(device_id)).move_body();
          },
          py::arg("shape"),
          py::arg("fill_value"),
          py::arg("device") = nullptr);
    m.def("full",
          [](py::tuple shape, Scalar fill_value, Device& device) { return Array::Full(ToShape(shape), fill_value, device).move_body(); },
          py::arg("shape"),
          py::arg("fill_value"),
          py::arg("device"));
    m.def("zeros",
          [](py::tuple shape, Dtype dtype, const nonstd::optional<std::string>& device_id) {
              return Array::Zeros(ToShape(shape), dtype, GetDevice(device_id)).move_body();
          },
          py::arg("shape"),
          py::arg("dtype"),
          py::arg("device") = nullptr);
    m.def("zeros",
          [](py::tuple shape, Dtype dtype, Device& device) { return Array::Zeros(ToShape(shape), dtype, device).move_body(); },
          py::arg("shape"),
          py::arg("dtype"),
          py::arg("device"));
    m.def("ones",
          [](py::tuple shape, Dtype dtype, const nonstd::optional<std::string>& device_id) {
              return Array::Ones(ToShape(shape), dtype, GetDevice(device_id)).move_body();
          },
          py::arg("shape"),
          py::arg("dtype"),
          py::arg("device") = nullptr);
    m.def("ones",
          [](py::tuple shape, Dtype dtype, Device& device) { return Array::Ones(ToShape(shape), dtype, device).move_body(); },
          py::arg("shape"),
          py::arg("dtype"),
          py::arg("device"));
    m.def("empty_like",
          [](const ArrayBodyPtr& a, const nonstd::optional<std::string>& device_id) {
              return Array::EmptyLike(Array{a}, GetDevice(device_id)).move_body();
          },
          py::arg("a"),
          py::arg("device") = nullptr);
    m.def("empty_like",
          [](const ArrayBodyPtr& a, Device& device) { return Array::EmptyLike(Array{a}, device).move_body(); },
          py::arg("a"),
          py::arg("device"));
    m.def("full_like",
          [](const ArrayBodyPtr& a, Scalar value, const nonstd::optional<std::string>& device_id) {
              return Array::FullLike(Array{a}, value, GetDevice(device_id)).move_body();
          },
          py::arg("a"),
          py::arg("fill_value"),
          py::arg("device") = nullptr);
    m.def("full_like",
          [](const ArrayBodyPtr& a, Scalar value, Device& device) { return Array::FullLike(Array{a}, value, device).move_body(); },
          py::arg("a"),
          py::arg("fill_value"),
          py::arg("device"));
    m.def("zeros_like",
          [](const ArrayBodyPtr& a, const nonstd::optional<std::string>& device_id) {
              return Array::ZerosLike(Array{a}, GetDevice(device_id)).move_body();
          },
          py::arg("a"),
          py::arg("device") = nullptr);
    m.def("zeros_like",
          [](const ArrayBodyPtr& a, Device& device) { return Array::ZerosLike(Array{a}, device).move_body(); },
          py::arg("a"),
          py::arg("device"));
    m.def("ones_like",
          [](const ArrayBodyPtr& a, const nonstd::optional<std::string>& device_id) {
              return Array::OnesLike(Array{a}, GetDevice(device_id)).move_body();
          },
          py::arg("a"),
          py::arg("device") = nullptr);
    m.def("ones_like",
          [](const ArrayBodyPtr& a, Device& device) { return Array::OnesLike(Array{a}, device).move_body(); },
          py::arg("a"),
          py::arg("device"));
    m.def("copy", [](const ArrayBodyPtr& a) { return Copy(Array{a}).move_body(); }, py::arg("a"));

    // linalg routines
    m.def("dot",
          [](const ArrayBodyPtr& a, const ArrayBodyPtr& b) { return Dot(Array{a}, Array{b}).move_body(); },
          py::arg("a"),
          py::arg("b"));

    // logic routines
    m.def("equal",
          [](const ArrayBodyPtr& x1, const ArrayBodyPtr& x2) { return Equal(Array{x1}, Array{x2}).move_body(); },
          py::arg("x1"),
          py::arg("x2"));

    // manipulation routines
    m.def("asscalar",
          [](const ArrayBodyPtr& a) -> py::object {
              Scalar s = AsScalar(Array{a});
              switch (GetKind(s.dtype())) {
                  case DtypeKind::kBool:
                      return py::bool_{static_cast<bool>(s)};
                  case DtypeKind::kInt:
                      // fallthrough
                  case DtypeKind::kUInt:
                      return py::int_{static_cast<int64_t>(s)};
                  case DtypeKind::kFloat:
                      return py::float_{static_cast<double>(s)};
                  default:
                      assert(false);  // never reach
              }
          },
          py::arg("a"));
    m.def("transpose", [](const ArrayBodyPtr& a) { return Transpose(Array{a}).move_body(); }, py::arg("a"));
    m.def("reshape",
          [](const ArrayBodyPtr& a, py::tuple newshape) { return Reshape(Array{a}, ToShape(newshape)).move_body(); },
          py::arg("a"),
          py::arg("newshape"));
    m.def("reshape",
          [](const ArrayBodyPtr& a, const std::vector<int64_t>& newshape) {
              return Reshape(Array{a}, {newshape.begin(), newshape.end()}).move_body();
          },
          py::arg("a"),
          py::arg("newshape"));
    m.def("squeeze",
          [](const ArrayBodyPtr& a, const nonstd::optional<std::vector<int8_t>>& axis) { return Squeeze(Array{a}, axis).move_body(); },
          py::arg("a"),
          py::arg("axis") = nullptr);
    m.def("squeeze",
          [](const ArrayBodyPtr& a, int8_t axis) { return Squeeze(Array{a}, std::vector<int8_t>{axis}).move_body(); },
          py::arg("a"),
          py::arg("axis"));
    m.def("broadcast_to",
          [](const ArrayBodyPtr& array, py::tuple shape) { return Array{array}.BroadcastTo(ToShape(shape)).move_body(); },
          py::arg("array"),
          py::arg("shape"));
    m.def("broadcast_to",
          [](const ArrayBodyPtr& array, py::tuple shape) { return Array{array}.BroadcastTo(ToShape(shape)).move_body(); },
          py::arg("array"),
          py::arg("shape"));

    // math routines
    m.def("add",
          [](const ArrayBodyPtr& x1, const ArrayBodyPtr& x2) { return (Array{x1} + Array{x2}).move_body(); },
          py::arg("x1"),
          py::arg("x2"));
    m.def("multiply",
          [](const ArrayBodyPtr& x1, const ArrayBodyPtr& x2) { return (Array{x1} * Array{x2}).move_body(); },
          py::arg("x1"),
          py::arg("x2"));
    m.def("multiply", [](const ArrayBodyPtr& x1, Scalar x2) { return Multiply(Array{x1}, x2).move_body(); }, py::arg("x1"), py::arg("x2"));
    m.def("multiply", [](Scalar x1, const ArrayBodyPtr& x2) { return Multiply(x1, Array{x2}).move_body(); }, py::arg("x1"), py::arg("x2"));
    m.def("sum",
          [](const ArrayBodyPtr& a, int8_t axis, bool keepdims) { return Sum(Array{a}, std::vector<int8_t>{axis}, keepdims).move_body(); },
          py::arg("a"),
          py::arg("axis"),
          py::arg("keepdims") = false);
    m.def("sum",
          [](const ArrayBodyPtr& a, nonstd::optional<std::vector<int8_t>> axis, bool keepdims) {
              return Sum(Array{a}, axis, keepdims).move_body();
          },
          py::arg("a"),
          py::arg("axis") = nullptr,
          py::arg("keepdims") = false);
    m.def("maximum", [](const ArrayBodyPtr& x1, Scalar x2) { return Maximum(Array{x1}, x2).move_body(); }, py::arg("x1"), py::arg("x2"));
    m.def("maximum", [](Scalar x1, const ArrayBodyPtr& x2) { return Maximum(x1, Array{x2}).move_body(); }, py::arg("x1"), py::arg("x2"));
}

}  // namespace internal
}  // namespace python
}  // namespace xchainer
<commit_msg>Add comment for xchainer.array(xchainer.Array)<commit_after>#include "xchainer/python/routines.h"

#include <cassert>
#include <cstdint>
#include <string>
#include <vector>

#include <nonstd/optional.hpp>

#include "xchainer/array.h"
#include "xchainer/context.h"
#include "xchainer/device.h"
#include "xchainer/dtype.h"
#include "xchainer/error.h"
#include "xchainer/routines/creation.h"
#include "xchainer/routines/linalg.h"
#include "xchainer/routines/logic.h"
#include "xchainer/routines/manipulation.h"
#include "xchainer/routines/math.h"
#include "xchainer/scalar.h"

#include "xchainer/python/array.h"
#include "xchainer/python/array_index.h"
#include "xchainer/python/common.h"
#include "xchainer/python/device.h"
#include "xchainer/python/shape.h"
#include "xchainer/python/strides.h"

namespace xchainer {
namespace python {
namespace internal {

namespace py = pybind11;

namespace {

ArrayBodyPtr MakeArray(const py::list& list, const nonstd::optional<Dtype>& dtype, Device& device) {
    // TODO(sonots): Determine dtype (bool or int64, or float64) seeing values of list.
    // TODO(sonots): Support nested list
    py::tuple shape_tup{1};
    shape_tup[0] = list.size();
    return internal::MakeArray(shape_tup, dtype.value_or(Dtype::kFloat64), list, device);
}

}  // namespace
void InitXchainerRoutines(pybind11::module& m) {
    // creation routines
    m.def("array",
          [](const py::list& list, const nonstd::optional<Dtype>& dtype, const nonstd::optional<std::string>& device_id) {
              return MakeArray(list, dtype, GetDevice(device_id));
          },
          py::arg("object"),
          py::arg("dtype") = nullptr,
          py::arg("device") = nullptr);
    m.def("array",
          [](const py::list& list, const nonstd::optional<Dtype>& dtype, Device& device) { return MakeArray(list, dtype, device); },
          py::arg("object"),
          py::arg("dtype") = nullptr,
          py::arg("device"));
    m.def("array",
          [](const py::array& array, const nonstd::optional<std::string>& device_id) { return MakeArray(array, GetDevice(device_id)); },
          py::arg("object"),
          py::arg("device") = nullptr);
    m.def("array", [](const py::array& array, Device& device) { return MakeArray(array, device); }, py::arg("object"), py::arg("device"));
    m.def("array",
          // Returns a view of an array if device argument is not specified.
          // Returns a new array transferred to the given device if device argument is specified. Note that the graph is connected.
          [](const ArrayBodyPtr& array, const nonstd::optional<std::string>& device_id) {
              if (device_id) {
                  return Array{array}.ToDevice(GetDevice(device_id)).move_body();
              }
              return Array{array}.MakeView().move_body();
          },
          py::arg("object"),
          py::arg("device") = nullptr);
    m.def("array",
          [](const ArrayBodyPtr& array, Device& device) { return Array{array}.ToDevice(device).move_body(); },
          py::arg("object"),
          py::arg("device"));
    m.def("empty",
          [](py::tuple shape, Dtype dtype, const nonstd::optional<std::string>& device_id) {
              return Array::Empty(ToShape(shape), dtype, GetDevice(device_id)).move_body();
          },
          py::arg("shape"),
          py::arg("dtype"),
          py::arg("device") = nullptr);
    m.def("empty",
          [](py::tuple shape, Dtype dtype, Device& device) { return Array::Empty(ToShape(shape), dtype, device).move_body(); },
          py::arg("shape"),
          py::arg("dtype"),
          py::arg("device"));
    m.def("full",
          [](py::tuple shape, Scalar fill_value, Dtype dtype, const nonstd::optional<std::string>& device_id) {
              return Array::Full(ToShape(shape), fill_value, dtype, GetDevice(device_id)).move_body();
          },
          py::arg("shape"),
          py::arg("fill_value"),
          py::arg("dtype"),
          py::arg("device") = nullptr);
    m.def("full",
          [](py::tuple shape, Scalar fill_value, Dtype dtype, Device& device) {
              return Array::Full(ToShape(shape), fill_value, dtype, device).move_body();
          },
          py::arg("shape"),
          py::arg("fill_value"),
          py::arg("dtype"),
          py::arg("device"));
    m.def("full",
          [](py::tuple shape, Scalar fill_value, const nonstd::optional<std::string>& device_id) {
              return Array::Full(ToShape(shape), fill_value, GetDevice(device_id)).move_body();
          },
          py::arg("shape"),
          py::arg("fill_value"),
          py::arg("device") = nullptr);
    m.def("full",
          [](py::tuple shape, Scalar fill_value, Device& device) { return Array::Full(ToShape(shape), fill_value, device).move_body(); },
          py::arg("shape"),
          py::arg("fill_value"),
          py::arg("device"));
    m.def("zeros",
          [](py::tuple shape, Dtype dtype, const nonstd::optional<std::string>& device_id) {
              return Array::Zeros(ToShape(shape), dtype, GetDevice(device_id)).move_body();
          },
          py::arg("shape"),
          py::arg("dtype"),
          py::arg("device") = nullptr);
    m.def("zeros",
          [](py::tuple shape, Dtype dtype, Device& device) { return Array::Zeros(ToShape(shape), dtype, device).move_body(); },
          py::arg("shape"),
          py::arg("dtype"),
          py::arg("device"));
    m.def("ones",
          [](py::tuple shape, Dtype dtype, const nonstd::optional<std::string>& device_id) {
              return Array::Ones(ToShape(shape), dtype, GetDevice(device_id)).move_body();
          },
          py::arg("shape"),
          py::arg("dtype"),
          py::arg("device") = nullptr);
    m.def("ones",
          [](py::tuple shape, Dtype dtype, Device& device) { return Array::Ones(ToShape(shape), dtype, device).move_body(); },
          py::arg("shape"),
          py::arg("dtype"),
          py::arg("device"));
    m.def("empty_like",
          [](const ArrayBodyPtr& a, const nonstd::optional<std::string>& device_id) {
              return Array::EmptyLike(Array{a}, GetDevice(device_id)).move_body();
          },
          py::arg("a"),
          py::arg("device") = nullptr);
    m.def("empty_like",
          [](const ArrayBodyPtr& a, Device& device) { return Array::EmptyLike(Array{a}, device).move_body(); },
          py::arg("a"),
          py::arg("device"));
    m.def("full_like",
          [](const ArrayBodyPtr& a, Scalar value, const nonstd::optional<std::string>& device_id) {
              return Array::FullLike(Array{a}, value, GetDevice(device_id)).move_body();
          },
          py::arg("a"),
          py::arg("fill_value"),
          py::arg("device") = nullptr);
    m.def("full_like",
          [](const ArrayBodyPtr& a, Scalar value, Device& device) { return Array::FullLike(Array{a}, value, device).move_body(); },
          py::arg("a"),
          py::arg("fill_value"),
          py::arg("device"));
    m.def("zeros_like",
          [](const ArrayBodyPtr& a, const nonstd::optional<std::string>& device_id) {
              return Array::ZerosLike(Array{a}, GetDevice(device_id)).move_body();
          },
          py::arg("a"),
          py::arg("device") = nullptr);
    m.def("zeros_like",
          [](const ArrayBodyPtr& a, Device& device) { return Array::ZerosLike(Array{a}, device).move_body(); },
          py::arg("a"),
          py::arg("device"));
    m.def("ones_like",
          [](const ArrayBodyPtr& a, const nonstd::optional<std::string>& device_id) {
              return Array::OnesLike(Array{a}, GetDevice(device_id)).move_body();
          },
          py::arg("a"),
          py::arg("device") = nullptr);
    m.def("ones_like",
          [](const ArrayBodyPtr& a, Device& device) { return Array::OnesLike(Array{a}, device).move_body(); },
          py::arg("a"),
          py::arg("device"));
    m.def("copy", [](const ArrayBodyPtr& a) { return Copy(Array{a}).move_body(); }, py::arg("a"));

    // linalg routines
    m.def("dot",
          [](const ArrayBodyPtr& a, const ArrayBodyPtr& b) { return Dot(Array{a}, Array{b}).move_body(); },
          py::arg("a"),
          py::arg("b"));

    // logic routines
    m.def("equal",
          [](const ArrayBodyPtr& x1, const ArrayBodyPtr& x2) { return Equal(Array{x1}, Array{x2}).move_body(); },
          py::arg("x1"),
          py::arg("x2"));

    // manipulation routines
    m.def("asscalar",
          [](const ArrayBodyPtr& a) -> py::object {
              Scalar s = AsScalar(Array{a});
              switch (GetKind(s.dtype())) {
                  case DtypeKind::kBool:
                      return py::bool_{static_cast<bool>(s)};
                  case DtypeKind::kInt:
                      // fallthrough
                  case DtypeKind::kUInt:
                      return py::int_{static_cast<int64_t>(s)};
                  case DtypeKind::kFloat:
                      return py::float_{static_cast<double>(s)};
                  default:
                      assert(false);  // never reach
              }
          },
          py::arg("a"));
    m.def("transpose", [](const ArrayBodyPtr& a) { return Transpose(Array{a}).move_body(); }, py::arg("a"));
    m.def("reshape",
          [](const ArrayBodyPtr& a, py::tuple newshape) { return Reshape(Array{a}, ToShape(newshape)).move_body(); },
          py::arg("a"),
          py::arg("newshape"));
    m.def("reshape",
          [](const ArrayBodyPtr& a, const std::vector<int64_t>& newshape) {
              return Reshape(Array{a}, {newshape.begin(), newshape.end()}).move_body();
          },
          py::arg("a"),
          py::arg("newshape"));
    m.def("squeeze",
          [](const ArrayBodyPtr& a, const nonstd::optional<std::vector<int8_t>>& axis) { return Squeeze(Array{a}, axis).move_body(); },
          py::arg("a"),
          py::arg("axis") = nullptr);
    m.def("squeeze",
          [](const ArrayBodyPtr& a, int8_t axis) { return Squeeze(Array{a}, std::vector<int8_t>{axis}).move_body(); },
          py::arg("a"),
          py::arg("axis"));
    m.def("broadcast_to",
          [](const ArrayBodyPtr& array, py::tuple shape) { return Array{array}.BroadcastTo(ToShape(shape)).move_body(); },
          py::arg("array"),
          py::arg("shape"));
    m.def("broadcast_to",
          [](const ArrayBodyPtr& array, py::tuple shape) { return Array{array}.BroadcastTo(ToShape(shape)).move_body(); },
          py::arg("array"),
          py::arg("shape"));

    // math routines
    m.def("add",
          [](const ArrayBodyPtr& x1, const ArrayBodyPtr& x2) { return (Array{x1} + Array{x2}).move_body(); },
          py::arg("x1"),
          py::arg("x2"));
    m.def("multiply",
          [](const ArrayBodyPtr& x1, const ArrayBodyPtr& x2) { return (Array{x1} * Array{x2}).move_body(); },
          py::arg("x1"),
          py::arg("x2"));
    m.def("multiply", [](const ArrayBodyPtr& x1, Scalar x2) { return Multiply(Array{x1}, x2).move_body(); }, py::arg("x1"), py::arg("x2"));
    m.def("multiply", [](Scalar x1, const ArrayBodyPtr& x2) { return Multiply(x1, Array{x2}).move_body(); }, py::arg("x1"), py::arg("x2"));
    m.def("sum",
          [](const ArrayBodyPtr& a, int8_t axis, bool keepdims) { return Sum(Array{a}, std::vector<int8_t>{axis}, keepdims).move_body(); },
          py::arg("a"),
          py::arg("axis"),
          py::arg("keepdims") = false);
    m.def("sum",
          [](const ArrayBodyPtr& a, nonstd::optional<std::vector<int8_t>> axis, bool keepdims) {
              return Sum(Array{a}, axis, keepdims).move_body();
          },
          py::arg("a"),
          py::arg("axis") = nullptr,
          py::arg("keepdims") = false);
    m.def("maximum", [](const ArrayBodyPtr& x1, Scalar x2) { return Maximum(Array{x1}, x2).move_body(); }, py::arg("x1"), py::arg("x2"));
    m.def("maximum", [](Scalar x1, const ArrayBodyPtr& x2) { return Maximum(x1, Array{x2}).move_body(); }, py::arg("x1"), py::arg("x2"));
}

}  // namespace internal
}  // namespace python
}  // namespace xchainer
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: pkgcontentcaps.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: kso $ $Date: 2001-04-27 13:19:44 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): Kai Sommerfeld ( kso@sun.com )
 *
 *
 ************************************************************************/

/**************************************************************************
                                TODO
 **************************************************************************

    Props/Commands:

                        folder  stream
    ------------------------------------
    ContentType           x       x
    IsDocument            x       x
    IsFolder              x       x
    MediaType            (x)      x
    Title                 x       x
    Size                          x
#if SUPD>614
    Compressed                    x
    Encrypted                     x
#endif

    getCommandInfo        x       x
    getPropertySetInfo    x       x
    getPropertyValues     x       x
    setPropertyValues     x       x
    insert                x       x
    delete                x       x
    open                  x       x
    transfer              x
    flush                 x

 *************************************************************************/

#ifndef _COM_SUN_STAR_BEANS_PROPERTY_HPP_
#include <com/sun/star/beans/Property.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_COMMANDINFO_HPP_
#include <com/sun/star/ucb/CommandInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_OPENCOMMANDARGUMENT2_HPP_
#include <com/sun/star/ucb/OpenCommandArgument2.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_TRANSFERINFO_HPP_
#include <com/sun/star/ucb/TransferInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif

#ifndef _PKGCONTENT_HXX
#include "pkgcontent.hxx"
#endif

using namespace com::sun::star::beans;
using namespace com::sun::star::uno;
using namespace com::sun::star::ucb;
using namespace rtl;

using namespace package_ucp;

//=========================================================================
//
// Content implementation.
//
//=========================================================================

//=========================================================================
//
// IMPORTENT: If any property data ( name / type / ... ) are changed, then
//            Content::getPropertyValues(...) must be adapted too!
//
//=========================================================================

// virtual
Sequence< Property > Content::getProperties(
                            const Reference< XCommandEnvironment > & xEnv )
{
    osl::Guard< osl::Mutex > aGuard( m_aMutex );

    if ( isFolder() )
    {
        //=================================================================
        //
        // Folder: Supported properties
        //
        //=================================================================

        static Property aFolderPropertyInfoTable[] =
        {
            ///////////////////////////////////////////////////////////////
            // Required properties
            ///////////////////////////////////////////////////////////////
            Property(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "ContentType" ) ),
                -1,
                getCppuType( static_cast< const OUString * >( 0 ) ),
                PropertyAttribute::BOUND | PropertyAttribute::READONLY
            ),
            Property(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "IsDocument" ) ),
                -1,
                getCppuBooleanType(),
                PropertyAttribute::BOUND | PropertyAttribute::READONLY
            ),
            Property(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "IsFolder" ) ),
                -1,
                getCppuBooleanType(),
                PropertyAttribute::BOUND | PropertyAttribute::READONLY
            ),
            Property(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "Title" ) ),
                -1,
                getCppuType( static_cast< const OUString * >( 0 ) ),
                PropertyAttribute::BOUND
            ),
            ///////////////////////////////////////////////////////////////
            // Optional standard properties
            ///////////////////////////////////////////////////////////////
            Property(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "MediaType" ) ),
                -1,
                getCppuType( static_cast< const OUString * >( 0 ) ),
                PropertyAttribute::BOUND
            )
            ///////////////////////////////////////////////////////////////
            // New properties
            ///////////////////////////////////////////////////////////////
        };
        return Sequence< Property >( aFolderPropertyInfoTable, 6 );
    }
    else
    {
        //=================================================================
        //
        // Stream: Supported properties
        //
        //=================================================================

        static Property aStreamPropertyInfoTable[] =
        {
            ///////////////////////////////////////////////////////////////
            // Required properties
            ///////////////////////////////////////////////////////////////
            Property(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "ContentType" ) ),
                -1,
                getCppuType( static_cast< const OUString * >( 0 ) ),
                PropertyAttribute::BOUND | PropertyAttribute::READONLY
            ),
            Property(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "IsDocument" ) ),
                -1,
                getCppuBooleanType(),
                PropertyAttribute::BOUND | PropertyAttribute::READONLY
            ),
            Property(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "IsFolder" ) ),
                -1,
                getCppuBooleanType(),
                PropertyAttribute::BOUND | PropertyAttribute::READONLY
            ),
            Property(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "Title" ) ),
                -1,
                getCppuType( static_cast< const OUString * >( 0 ) ),
                PropertyAttribute::BOUND
            ),
            ///////////////////////////////////////////////////////////////
            // Optional standard properties
            ///////////////////////////////////////////////////////////////
            Property(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "MediaType" ) ),
                -1,
                getCppuType( static_cast< const OUString * >( 0 ) ),
                PropertyAttribute::BOUND
            ),
            Property(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "Size" ) ),
                -1,
                getCppuType( static_cast< const sal_Int64 * >( 0 ) ),
                PropertyAttribute::BOUND | PropertyAttribute::READONLY
#if SUPD>614
            ),
            ///////////////////////////////////////////////////////////////
            // New properties
            ///////////////////////////////////////////////////////////////
            Property(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "Compressed" ) ),
                -1,
                getCppuType( static_cast< const sal_Bool * >( 0 ) ),
                PropertyAttribute::BOUND
            ),
            Property(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "Encrypted" ) ),
                -1,
                getCppuType( static_cast< const sal_Bool * >( 0 ) ),
                PropertyAttribute::BOUND
#endif
            )
        };
#if SUPD>614
        return Sequence< Property >( aStreamPropertyInfoTable, 8 );
#else
        return Sequence< Property >( aStreamPropertyInfoTable, 6 );
#endif
    }
}

//=========================================================================
// virtual
Sequence< CommandInfo > Content::getCommands(
                            const Reference< XCommandEnvironment > & xEnv )
{
    osl::Guard< osl::Mutex > aGuard( m_aMutex );

    if ( isFolder() )
    {
        //=================================================================
        //
        // Folder: Supported commands
        //
        //=================================================================

        static CommandInfo aFolderCommandInfoTable[] =
        {
            ///////////////////////////////////////////////////////////////
            // Required commands
            ///////////////////////////////////////////////////////////////
            CommandInfo(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "getCommandInfo" ) ),
                -1,
                getCppuVoidType()
            ),
            CommandInfo(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "getPropertySetInfo" ) ),
                -1,
                getCppuVoidType()
            ),
            CommandInfo(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "getPropertyValues" ) ),
                -1,
                getCppuType( static_cast< Sequence< Property > * >( 0 ) )
            ),
            CommandInfo(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "setPropertyValues" ) ),
                -1,
                getCppuType( static_cast< Sequence< PropertyValue > * >( 0 ) )
            ),
            ///////////////////////////////////////////////////////////////
            // Optional standard commands
            ///////////////////////////////////////////////////////////////
            CommandInfo(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "delete" ) ),
                -1,
                getCppuBooleanType()
            ),
            CommandInfo(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "insert" ) ),
                -1,
                getCppuVoidType()
            ),
            CommandInfo(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "open" ) ),
                -1,
                getCppuType( static_cast< OpenCommandArgument2 * >( 0 ) )
            ),
            CommandInfo(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "transfer" ) ),
                -1,
                getCppuType( static_cast< TransferInfo * >( 0 ) )
            ),
            ///////////////////////////////////////////////////////////////
            // New commands
            ///////////////////////////////////////////////////////////////
            CommandInfo(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "flush" ) ),
                -1,
                getCppuVoidType()
            )
        };

        return Sequence< CommandInfo >( aFolderCommandInfoTable, 9 );
    }
    else
    {
        //=================================================================
        //
        // Stream: Supported commands
        //
        //=================================================================

        static CommandInfo aStreamCommandInfoTable[] =
        {
            ///////////////////////////////////////////////////////////////
            // Required commands
            ///////////////////////////////////////////////////////////////
            CommandInfo(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "getCommandInfo" ) ),
                -1,
                getCppuVoidType()
            ),
            CommandInfo(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "getPropertySetInfo" ) ),
                -1,
                getCppuVoidType()
            ),
            CommandInfo(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "getPropertyValues" ) ),
                -1,
                getCppuType( static_cast< Sequence< Property > * >( 0 ) )
            ),
            CommandInfo(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "setPropertyValues" ) ),
                -1,
                getCppuType( static_cast< Sequence< PropertyValue > * >( 0 ) )
            ),
            ///////////////////////////////////////////////////////////////
            // Optional standard commands
            ///////////////////////////////////////////////////////////////
            CommandInfo(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "delete" ) ),
                -1,
                getCppuBooleanType()
            ),
            CommandInfo(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "insert" ) ),
                -1,
                getCppuVoidType()
            ),
            CommandInfo(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "open" ) ),
                -1,
                getCppuType( static_cast< OpenCommandArgument2 * >( 0 ) )
            )
            ///////////////////////////////////////////////////////////////
            // New commands
            ///////////////////////////////////////////////////////////////
        };

        return Sequence< CommandInfo >( aStreamCommandInfoTable, 7 );
    }
}

<commit_msg>#86409# - Fixed folder properties table (index out of bounds).<commit_after>/*************************************************************************
 *
 *  $RCSfile: pkgcontentcaps.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: kso $ $Date: 2001-04-27 14:55:16 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 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
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): Kai Sommerfeld ( kso@sun.com )
 *
 *
 ************************************************************************/

/**************************************************************************
                                TODO
 **************************************************************************

    Props/Commands:

                        folder  stream
    ------------------------------------
    ContentType           x       x
    IsDocument            x       x
    IsFolder              x       x
    MediaType            (x)      x
    Title                 x       x
    Size                          x
#if SUPD>614
    Compressed                    x
    Encrypted                     x
#endif

    getCommandInfo        x       x
    getPropertySetInfo    x       x
    getPropertyValues     x       x
    setPropertyValues     x       x
    insert                x       x
    delete                x       x
    open                  x       x
    transfer              x
    flush                 x

 *************************************************************************/

#ifndef _COM_SUN_STAR_BEANS_PROPERTY_HPP_
#include <com/sun/star/beans/Property.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_
#include <com/sun/star/beans/PropertyAttribute.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_COMMANDINFO_HPP_
#include <com/sun/star/ucb/CommandInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_OPENCOMMANDARGUMENT2_HPP_
#include <com/sun/star/ucb/OpenCommandArgument2.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_TRANSFERINFO_HPP_
#include <com/sun/star/ucb/TransferInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif

#ifndef _PKGCONTENT_HXX
#include "pkgcontent.hxx"
#endif

using namespace com::sun::star::beans;
using namespace com::sun::star::uno;
using namespace com::sun::star::ucb;
using namespace rtl;

using namespace package_ucp;

//=========================================================================
//
// Content implementation.
//
//=========================================================================

//=========================================================================
//
// IMPORTENT: If any property data ( name / type / ... ) are changed, then
//            Content::getPropertyValues(...) must be adapted too!
//
//=========================================================================

// virtual
Sequence< Property > Content::getProperties(
                            const Reference< XCommandEnvironment > & xEnv )
{
    osl::Guard< osl::Mutex > aGuard( m_aMutex );

    if ( isFolder() )
    {
        //=================================================================
        //
        // Folder: Supported properties
        //
        //=================================================================

        static Property aFolderPropertyInfoTable[] =
        {
            ///////////////////////////////////////////////////////////////
            // Required properties
            ///////////////////////////////////////////////////////////////
            Property(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "ContentType" ) ),
                -1,
                getCppuType( static_cast< const OUString * >( 0 ) ),
                PropertyAttribute::BOUND | PropertyAttribute::READONLY
            ),
            Property(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "IsDocument" ) ),
                -1,
                getCppuBooleanType(),
                PropertyAttribute::BOUND | PropertyAttribute::READONLY
            ),
            Property(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "IsFolder" ) ),
                -1,
                getCppuBooleanType(),
                PropertyAttribute::BOUND | PropertyAttribute::READONLY
            ),
            Property(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "Title" ) ),
                -1,
                getCppuType( static_cast< const OUString * >( 0 ) ),
                PropertyAttribute::BOUND
            ),
            ///////////////////////////////////////////////////////////////
            // Optional standard properties
            ///////////////////////////////////////////////////////////////
            Property(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "MediaType" ) ),
                -1,
                getCppuType( static_cast< const OUString * >( 0 ) ),
                PropertyAttribute::BOUND
            )
            ///////////////////////////////////////////////////////////////
            // New properties
            ///////////////////////////////////////////////////////////////
        };
        return Sequence< Property >( aFolderPropertyInfoTable, 5 );
    }
    else
    {
        //=================================================================
        //
        // Stream: Supported properties
        //
        //=================================================================

        static Property aStreamPropertyInfoTable[] =
        {
            ///////////////////////////////////////////////////////////////
            // Required properties
            ///////////////////////////////////////////////////////////////
            Property(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "ContentType" ) ),
                -1,
                getCppuType( static_cast< const OUString * >( 0 ) ),
                PropertyAttribute::BOUND | PropertyAttribute::READONLY
            ),
            Property(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "IsDocument" ) ),
                -1,
                getCppuBooleanType(),
                PropertyAttribute::BOUND | PropertyAttribute::READONLY
            ),
            Property(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "IsFolder" ) ),
                -1,
                getCppuBooleanType(),
                PropertyAttribute::BOUND | PropertyAttribute::READONLY
            ),
            Property(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "Title" ) ),
                -1,
                getCppuType( static_cast< const OUString * >( 0 ) ),
                PropertyAttribute::BOUND
            ),
            ///////////////////////////////////////////////////////////////
            // Optional standard properties
            ///////////////////////////////////////////////////////////////
            Property(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "MediaType" ) ),
                -1,
                getCppuType( static_cast< const OUString * >( 0 ) ),
                PropertyAttribute::BOUND
            ),
            Property(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "Size" ) ),
                -1,
                getCppuType( static_cast< const sal_Int64 * >( 0 ) ),
                PropertyAttribute::BOUND | PropertyAttribute::READONLY
#if SUPD>614
            ),
            ///////////////////////////////////////////////////////////////
            // New properties
            ///////////////////////////////////////////////////////////////
            Property(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "Compressed" ) ),
                -1,
                getCppuType( static_cast< const sal_Bool * >( 0 ) ),
                PropertyAttribute::BOUND
            ),
            Property(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "Encrypted" ) ),
                -1,
                getCppuType( static_cast< const sal_Bool * >( 0 ) ),
                PropertyAttribute::BOUND
#endif
            )
        };
#if SUPD>614
        return Sequence< Property >( aStreamPropertyInfoTable, 8 );
#else
        return Sequence< Property >( aStreamPropertyInfoTable, 6 );
#endif
    }
}

//=========================================================================
// virtual
Sequence< CommandInfo > Content::getCommands(
                            const Reference< XCommandEnvironment > & xEnv )
{
    osl::Guard< osl::Mutex > aGuard( m_aMutex );

    if ( isFolder() )
    {
        //=================================================================
        //
        // Folder: Supported commands
        //
        //=================================================================

        static CommandInfo aFolderCommandInfoTable[] =
        {
            ///////////////////////////////////////////////////////////////
            // Required commands
            ///////////////////////////////////////////////////////////////
            CommandInfo(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "getCommandInfo" ) ),
                -1,
                getCppuVoidType()
            ),
            CommandInfo(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "getPropertySetInfo" ) ),
                -1,
                getCppuVoidType()
            ),
            CommandInfo(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "getPropertyValues" ) ),
                -1,
                getCppuType( static_cast< Sequence< Property > * >( 0 ) )
            ),
            CommandInfo(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "setPropertyValues" ) ),
                -1,
                getCppuType( static_cast< Sequence< PropertyValue > * >( 0 ) )
            ),
            ///////////////////////////////////////////////////////////////
            // Optional standard commands
            ///////////////////////////////////////////////////////////////
            CommandInfo(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "delete" ) ),
                -1,
                getCppuBooleanType()
            ),
            CommandInfo(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "insert" ) ),
                -1,
                getCppuVoidType()
            ),
            CommandInfo(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "open" ) ),
                -1,
                getCppuType( static_cast< OpenCommandArgument2 * >( 0 ) )
            ),
            CommandInfo(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "transfer" ) ),
                -1,
                getCppuType( static_cast< TransferInfo * >( 0 ) )
            ),
            ///////////////////////////////////////////////////////////////
            // New commands
            ///////////////////////////////////////////////////////////////
            CommandInfo(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "flush" ) ),
                -1,
                getCppuVoidType()
            )
        };

        return Sequence< CommandInfo >( aFolderCommandInfoTable, 9 );
    }
    else
    {
        //=================================================================
        //
        // Stream: Supported commands
        //
        //=================================================================

        static CommandInfo aStreamCommandInfoTable[] =
        {
            ///////////////////////////////////////////////////////////////
            // Required commands
            ///////////////////////////////////////////////////////////////
            CommandInfo(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "getCommandInfo" ) ),
                -1,
                getCppuVoidType()
            ),
            CommandInfo(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "getPropertySetInfo" ) ),
                -1,
                getCppuVoidType()
            ),
            CommandInfo(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "getPropertyValues" ) ),
                -1,
                getCppuType( static_cast< Sequence< Property > * >( 0 ) )
            ),
            CommandInfo(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "setPropertyValues" ) ),
                -1,
                getCppuType( static_cast< Sequence< PropertyValue > * >( 0 ) )
            ),
            ///////////////////////////////////////////////////////////////
            // Optional standard commands
            ///////////////////////////////////////////////////////////////
            CommandInfo(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "delete" ) ),
                -1,
                getCppuBooleanType()
            ),
            CommandInfo(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "insert" ) ),
                -1,
                getCppuVoidType()
            ),
            CommandInfo(
                OUString( RTL_CONSTASCII_USTRINGPARAM( "open" ) ),
                -1,
                getCppuType( static_cast< OpenCommandArgument2 * >( 0 ) )
            )
            ///////////////////////////////////////////////////////////////
            // New commands
            ///////////////////////////////////////////////////////////////
        };

        return Sequence< CommandInfo >( aStreamCommandInfoTable, 7 );
    }
}

<|endoftext|>