<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2015 Francois Beaune, The appleseedhq Organization
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

// Interface header.
#include "dipolebssrdf.h"

// appleseed.renderer headers.
#include "renderer/modeling/bssrdf/bssrdfsample.h"
#include "renderer/modeling/bssrdf/sss.h"
#include "renderer/modeling/input/inputevaluator.h"

// appleseed.foundation headers.
#include "foundation/math/scalar.h"
#include "foundation/math/vector.h"
#include "foundation/utility/containers/dictionary.h"
#include "foundation/utility/containers/specializedarrays.h"
#include "foundation/utility/memory.h"

// Standard headers.
#include <cmath>
#include <cstddef>

using namespace foundation;
using namespace std;

namespace renderer
{

//
// DipoleBSSRDF class implementation.
//

DipoleBSSRDF::DipoleBSSRDF(
    const char*             name,
    const ParamArray&       params)
  : BSSRDF(name, params)
{
    m_inputs.declare("weight", InputFormatScalar, "1.0");
    m_inputs.declare("reflectance", InputFormatSpectralReflectance);
    m_inputs.declare("reflectance_multiplier", InputFormatScalar, "1.0");
    m_inputs.declare("dmfp", InputFormatScalar, "5.0");
    m_inputs.declare("dmfp_multiplier", InputFormatScalar, "0.1");
    m_inputs.declare("anisotropy", InputFormatScalar);
    m_inputs.declare("outside_ior", InputFormatScalar);
    m_inputs.declare("inside_ior", InputFormatScalar);
}

size_t DipoleBSSRDF::compute_input_data_size(
    const Assembly&         assembly) const
{
    return align(sizeof(DipoleBSSRDFInputValues), 16);
}

void DipoleBSSRDF::evaluate_inputs(
    const ShadingContext&   shading_context,
    InputEvaluator&         input_evaluator,
    const ShadingPoint&     shading_point,
    const size_t            offset) const
{
    BSSRDF::evaluate_inputs(shading_context, input_evaluator, shading_point, offset);

    DipoleBSSRDFInputValues* values =
        reinterpret_cast<DipoleBSSRDFInputValues*>(input_evaluator.data() + offset);

    // Apply multipliers.
    values->m_reflectance *= static_cast<float>(values->m_reflectance_multiplier);
    values->m_dmfp *= values->m_dmfp_multiplier;

    // Clamp reflectance to [0, 1].
    values->m_reflectance = saturate(values->m_reflectance);

#if 1
    // Compute sigma_a and sigma_s from the reflectance and dmfp parameters.
    compute_absorption_and_scattering(
        values->m_reflectance,
        values->m_dmfp,
        values->m_inside_ior / values->m_outside_ior,
        values->m_anisotropy,
        values->m_sigma_a,
        values->m_sigma_s);
#else
    // Skim milk.
    values->m_sigma_a = Color3f(0.0014f, 0.0025f, 0.0142f) * 1000.0f;
    values->m_sigma_s = Color3f(0.70f, 1.22f, 1.90f) * 1000.0f;
    values->m_anisotropy = 0.0;

    // TODO: compute dmfp here!
    /*
    effective_extinction_coefficient(
        values->m_sigma_a,
        values->m_sigma_s,
        values->m_anisotropy,
        values->m_sigma_tr);
    */
#endif

    values->m_max_radius2 = square(dipole_max_radius(1.0 / values->m_dmfp));
}

bool DipoleBSSRDF::sample(
    const void*             data,
    BSSRDFSample&           sample) const
{
    const DipoleBSSRDFInputValues* values =
        reinterpret_cast<const DipoleBSSRDFInputValues*>(data);

    if (values->m_weight == 0.0)
        return false;

    sample.set_eta(values->m_inside_ior / values->m_outside_ior);

    // Select the channel leading to the strongest scattering.
    const size_t channel = min_index(values->m_reflectance);
    sample.set_channel(channel);

    // todo: fix.
    const double reflectance = values->m_reflectance[channel];
    if (reflectance == 0.0)
        return false;

    sample.get_sampling_context().split_in_place(2, 1);
    const Vector2d s = sample.get_sampling_context().next_vector2<2>();

    // Sample a radius.
    const double sigma_tr = 1.0 / values->m_dmfp;
    const double radius = dipole_sample(sigma_tr, s[0]);

    // Set the max radius.
    sample.set_rmax2(values->m_max_radius2);

    // Sample an angle.
    const double phi = TwoPi * s[1];

    // Set the sampled point.
    sample.set_point(Vector2d(radius * cos(phi), radius * sin(phi)));

    return true;
}

double DipoleBSSRDF::evaluate_pdf(
    const void*             data,
    const size_t            channel,
    const double            radius) const
{
    const DipoleBSSRDFInputValues* values =
        reinterpret_cast<const DipoleBSSRDFInputValues*>(data);

    const double reflectance = values->m_reflectance[channel];
    if (reflectance == 0.0)
        return 0.0;

    // PDF of the sampled radius.
    const double sigma_tr = 1.0 / values->m_dmfp;
    const double pdf_radius = dipole_pdf(radius, sigma_tr);

    // PDF of the sampled angle.
    const double pdf_angle = RcpTwoPi;

    // Compute and return the final PDF.
    return pdf_radius * pdf_angle;
}

//
// DipoleBSSRDFFactory class implementation.
//

DictionaryArray DipoleBSSRDFFactory::get_input_metadata() const
{
    DictionaryArray metadata;

    metadata.push_back(
        Dictionary()
            .insert("name", "weight")
            .insert("label", "Weight")
            .insert("type", "colormap")
            .insert("entity_types",
                Dictionary().insert("texture_instance", "Textures"))
            .insert("use", "optional")
            .insert("default", "1.0"));

    metadata.push_back(
        Dictionary()
            .insert("name", "reflectance")
            .insert("label", "Diffuse Surface Reflectance")
            .insert("type", "colormap")
            .insert("entity_types",
                Dictionary()
                    .insert("color", "Colors")
                    .insert("texture_instance", "Textures"))
            .insert("use", "required")
            .insert("default", "0.5"));

    metadata.push_back(
        Dictionary()
            .insert("name", "reflectance_multiplier")
            .insert("label", "Diffuse Surface Reflectance Multiplier")
            .insert("type", "colormap")
            .insert("entity_types",
                Dictionary().insert("texture_instance", "Textures"))
            .insert("use", "optional")
            .insert("default", "1.0"));

    metadata.push_back(
        Dictionary()
            .insert("name", "dmfp")
            .insert("label", "Diffuse Mean Free Path")
            .insert("type", "colormap")
            .insert("entity_types",
                Dictionary()
                    .insert("texture_instance", "Textures"))
            .insert("use", "required")
            .insert("default", "5"));

    metadata.push_back(
        Dictionary()
            .insert("name", "dmfp_multiplier")
            .insert("label", "Diffuse Mean Free Path Multiplier")
            .insert("type", "colormap")
            .insert("entity_types",
                Dictionary().insert("texture_instance", "Textures"))
            .insert("use", "optional")
            .insert("default", "0.1"));

    metadata.push_back(
        Dictionary()
            .insert("name", "anisotropy")
            .insert("label", "Anisotropy")
            .insert("type", "numeric")
            .insert("min_value", "-1.0")
            .insert("max_value", "1.0")
            .insert("use", "required")
            .insert("default", "0.0"));

    metadata.push_back(
        Dictionary()
            .insert("name", "outside_ior")
            .insert("label", "Outside Index of Refraction")
            .insert("type", "numeric")
            .insert("min_value", "0.0")
            .insert("max_value", "5.0")
            .insert("use", "required")
            .insert("default", "1.0"));

    metadata.push_back(
        Dictionary()
            .insert("name", "inside_ior")
            .insert("label", "Inside Index of Refraction")
            .insert("type", "numeric")
            .insert("min_value", "0.0")
            .insert("max_value", "5.0")
            .insert("use", "required")
            .insert("default", "1.3"));

    return metadata;
}

}   // namespace renderer
<commit_msg>No need to sample a channel for dipole BSSRDFs<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2015 Francois Beaune, The appleseedhq Organization
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

// Interface header.
#include "dipolebssrdf.h"

// appleseed.renderer headers.
#include "renderer/modeling/bssrdf/bssrdfsample.h"
#include "renderer/modeling/bssrdf/sss.h"
#include "renderer/modeling/input/inputevaluator.h"

// appleseed.foundation headers.
#include "foundation/math/scalar.h"
#include "foundation/math/vector.h"
#include "foundation/utility/containers/dictionary.h"
#include "foundation/utility/containers/specializedarrays.h"
#include "foundation/utility/memory.h"

// Standard headers.
#include <cmath>
#include <cstddef>

using namespace foundation;
using namespace std;

namespace renderer
{

//
// DipoleBSSRDF class implementation.
//

DipoleBSSRDF::DipoleBSSRDF(
    const char*             name,
    const ParamArray&       params)
  : BSSRDF(name, params)
{
    m_inputs.declare("weight", InputFormatScalar, "1.0");
    m_inputs.declare("reflectance", InputFormatSpectralReflectance);
    m_inputs.declare("reflectance_multiplier", InputFormatScalar, "1.0");
    m_inputs.declare("dmfp", InputFormatScalar, "5.0");
    m_inputs.declare("dmfp_multiplier", InputFormatScalar, "0.1");
    m_inputs.declare("anisotropy", InputFormatScalar);
    m_inputs.declare("outside_ior", InputFormatScalar);
    m_inputs.declare("inside_ior", InputFormatScalar);
}

size_t DipoleBSSRDF::compute_input_data_size(
    const Assembly&         assembly) const
{
    return align(sizeof(DipoleBSSRDFInputValues), 16);
}

void DipoleBSSRDF::evaluate_inputs(
    const ShadingContext&   shading_context,
    InputEvaluator&         input_evaluator,
    const ShadingPoint&     shading_point,
    const size_t            offset) const
{
    BSSRDF::evaluate_inputs(shading_context, input_evaluator, shading_point, offset);

    DipoleBSSRDFInputValues* values =
        reinterpret_cast<DipoleBSSRDFInputValues*>(input_evaluator.data() + offset);

    // Apply multipliers.
    values->m_reflectance *= static_cast<float>(values->m_reflectance_multiplier);
    values->m_dmfp *= values->m_dmfp_multiplier;

    // Clamp reflectance to [0.001, 1].
    values->m_reflectance = clamp(values->m_reflectance, 0.001f, 1.0f);

#if 1
    // Compute sigma_a and sigma_s from the reflectance and dmfp parameters.
    compute_absorption_and_scattering(
        values->m_reflectance,
        values->m_dmfp,
        values->m_inside_ior / values->m_outside_ior,
        values->m_anisotropy,
        values->m_sigma_a,
        values->m_sigma_s);
#else
    // Skim milk.
    values->m_sigma_a = Color3f(0.0014f, 0.0025f, 0.0142f) * 1000.0f;
    values->m_sigma_s = Color3f(0.70f, 1.22f, 1.90f) * 1000.0f;
    values->m_anisotropy = 0.0;

    // TODO: compute dmfp here!
    /*
    effective_extinction_coefficient(
        values->m_sigma_a,
        values->m_sigma_s,
        values->m_anisotropy,
        values->m_sigma_tr);
    */
#endif

    values->m_max_radius2 = square(dipole_max_radius(1.0 / values->m_dmfp));
}

bool DipoleBSSRDF::sample(
    const void*             data,
    BSSRDFSample&           sample) const
{
    const DipoleBSSRDFInputValues* values =
        reinterpret_cast<const DipoleBSSRDFInputValues*>(data);

    if (values->m_weight == 0.0)
        return false;

    sample.set_eta(values->m_inside_ior / values->m_outside_ior);
    sample.set_channel(0);

    sample.get_sampling_context().split_in_place(2, 1);
    const Vector2d s = sample.get_sampling_context().next_vector2<2>();

    // Sample a radius.
    const double sigma_tr = 1.0 / values->m_dmfp;
    const double radius = dipole_sample(sigma_tr, s[0]);

    // Set the max radius.
    sample.set_rmax2(values->m_max_radius2);

    // Sample an angle.
    const double phi = TwoPi * s[1];

    // Set the sampled point.
    sample.set_point(Vector2d(radius * cos(phi), radius * sin(phi)));

    return true;
}

double DipoleBSSRDF::evaluate_pdf(
    const void*             data,
    const size_t            channel,
    const double            radius) const
{
    const DipoleBSSRDFInputValues* values =
        reinterpret_cast<const DipoleBSSRDFInputValues*>(data);

    const double reflectance = values->m_reflectance[channel];
    if (reflectance == 0.0)
        return 0.0;

    // PDF of the sampled radius.
    const double sigma_tr = 1.0 / values->m_dmfp;
    const double pdf_radius = dipole_pdf(radius, sigma_tr);

    // PDF of the sampled angle.
    const double pdf_angle = RcpTwoPi;

    // Compute and return the final PDF.
    return pdf_radius * pdf_angle;
}

//
// DipoleBSSRDFFactory class implementation.
//

DictionaryArray DipoleBSSRDFFactory::get_input_metadata() const
{
    DictionaryArray metadata;

    metadata.push_back(
        Dictionary()
            .insert("name", "weight")
            .insert("label", "Weight")
            .insert("type", "colormap")
            .insert("entity_types",
                Dictionary().insert("texture_instance", "Textures"))
            .insert("use", "optional")
            .insert("default", "1.0"));

    metadata.push_back(
        Dictionary()
            .insert("name", "reflectance")
            .insert("label", "Diffuse Surface Reflectance")
            .insert("type", "colormap")
            .insert("entity_types",
                Dictionary()
                    .insert("color", "Colors")
                    .insert("texture_instance", "Textures"))
            .insert("use", "required")
            .insert("default", "0.5"));

    metadata.push_back(
        Dictionary()
            .insert("name", "reflectance_multiplier")
            .insert("label", "Diffuse Surface Reflectance Multiplier")
            .insert("type", "colormap")
            .insert("entity_types",
                Dictionary().insert("texture_instance", "Textures"))
            .insert("use", "optional")
            .insert("default", "1.0"));

    metadata.push_back(
        Dictionary()
            .insert("name", "dmfp")
            .insert("label", "Diffuse Mean Free Path")
            .insert("type", "colormap")
            .insert("entity_types",
                Dictionary()
                    .insert("texture_instance", "Textures"))
            .insert("use", "required")
            .insert("default", "5"));

    metadata.push_back(
        Dictionary()
            .insert("name", "dmfp_multiplier")
            .insert("label", "Diffuse Mean Free Path Multiplier")
            .insert("type", "colormap")
            .insert("entity_types",
                Dictionary().insert("texture_instance", "Textures"))
            .insert("use", "optional")
            .insert("default", "0.1"));

    metadata.push_back(
        Dictionary()
            .insert("name", "anisotropy")
            .insert("label", "Anisotropy")
            .insert("type", "numeric")
            .insert("min_value", "-1.0")
            .insert("max_value", "1.0")
            .insert("use", "required")
            .insert("default", "0.0"));

    metadata.push_back(
        Dictionary()
            .insert("name", "outside_ior")
            .insert("label", "Outside Index of Refraction")
            .insert("type", "numeric")
            .insert("min_value", "0.0")
            .insert("max_value", "5.0")
            .insert("use", "required")
            .insert("default", "1.0"));

    metadata.push_back(
        Dictionary()
            .insert("name", "inside_ior")
            .insert("label", "Inside Index of Refraction")
            .insert("type", "numeric")
            .insert("min_value", "0.0")
            .insert("max_value", "5.0")
            .insert("use", "required")
            .insert("default", "1.3"));

    return metadata;
}

}   // namespace renderer
<|endoftext|>


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

#include <lib/core/CHIPCore.h>

#include <ChipShellCollection.h>

#if CONFIG_DEVICE_LAYER
#include <platform/CHIPDeviceLayer.h>
#endif

#if CHIP_ENABLE_OPENTHREAD

#include <stdio.h>

#include <lib/shell/Engine.h>
#include <lib/support/CHIPArgParser.hpp>
#include <lib/support/CHIPMem.h>
#include <lib/support/CodeUtils.h>
#include <platform/ThreadStackManager.h>

#if CHIP_TARGET_STYLE_EMBEDDED
#include <openthread/cli.h>
#include <openthread/instance.h>
#include <openthread/ip6.h>
#include <openthread/link.h>
#include <openthread/thread.h>
#if OPENTHREAD_API_VERSION >= 85
#ifndef SHELL_OTCLI_TX_BUFFER_SIZE
#define SHELL_OTCLI_TX_BUFFER_SIZE 1024
#endif
static char sTxBuffer[SHELL_OTCLI_TX_BUFFER_SIZE];
static constexpr uint16_t sTxLength = SHELL_OTCLI_TX_BUFFER_SIZE;
#endif
#else
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#endif

using namespace chip;
using namespace chip::Shell;
using namespace chip::Platform;
using namespace chip::DeviceLayer;
using namespace chip::Logging;
using namespace chip::ArgParser;

static chip::Shell::Engine sShellOtcliSubcommands;

CHIP_ERROR cmd_otcli_help_iterator(shell_command_t * command, void * arg)
{
    streamer_printf(streamer_get(), "  %-15s %s\n\r", command->cmd_name, command->cmd_help);
    return CHIP_NO_ERROR;
}

CHIP_ERROR cmd_otcli_help(int argc, char ** argv)
{
    sShellOtcliSubcommands.ForEachCommand(cmd_otcli_help_iterator, nullptr);
    return CHIP_NO_ERROR;
}

#if CHIP_TARGET_STYLE_EMBEDDED

CHIP_ERROR cmd_otcli_dispatch(int argc, char ** argv)
{
    CHIP_ERROR error = CHIP_NO_ERROR;

// From OT CLI internal lib, kMaxLineLength = 128
#define kMaxLineLength 128
    char buff[kMaxLineLength] = { 0 };
    char * buff_ptr           = buff;
    int i                     = 0;

    VerifyOrExit(argc > 0, error = CHIP_ERROR_INVALID_ARGUMENT);

    for (i = 0; i < argc; i++)
    {
        size_t arg_len = strlen(argv[i]);

        /* Make sure that the next argument won't overflow the buffer */
        VerifyOrExit(buff_ptr + arg_len < buff + kMaxLineLength, error = CHIP_ERROR_BUFFER_TOO_SMALL);

        strncpy(buff_ptr, argv[i], arg_len);
        buff_ptr += arg_len;

        /* Make sure that there is enough buffer for a space char */
        if (buff_ptr + sizeof(char) < buff + kMaxLineLength)
        {
            strncpy(buff_ptr, " ", sizeof(char));
            buff_ptr++;
        }
    }
    buff_ptr = 0;
#if OPENTHREAD_API_VERSION >= 85
    otCliInputLine(buff);
#else
    otCliConsoleInputLine(buff, buff_ptr - buff);
#endif
exit:
    return error;
}

#elif CHIP_TARGET_STYLE_UNIX

CHIP_ERROR cmd_otcli_dispatch(int argc, char ** argv)
{
    int pid;
    uid_t euid         = geteuid();
    char ctl_command[] = "/usr/local/sbin/ot-ctl";

    // Must run as sudo.
    if (euid != 0)
    {
        streamer_printf(streamer_get(), "Error otcli: requires running chip-shell as sudo\n\r");
        return CHIP_ERROR_INCORRECT_STATE;
    }

    VerifyOrReturnError(argc > 0, CHIP_ERROR_INVALID_ARGUMENT);

    // Fork and execute the command.
    pid = fork();
    VerifyOrReturnError(pid != -1, CHIP_ERROR_INCORRECT_STATE);

    if (pid == 0)
    {
        // Child process to execute the command with provided arguments
        --argv; // Restore access to entry [0] containing the command;
        argv[0] = ctl_command;
        if (execvp(ctl_command, argv) < 0)
        {
            streamer_printf(streamer_get(), "Error exec %s: %s\n", ctl_command, strerror(errno));
        }
        exit(errno);
    }
    else
    {
        // Parent process to wait on child.
        int status;
        wait(&status);
        return (status) ? CHIP_ERROR_INCORRECT_STATE : CHIP_NO_ERROR;
    }
}

#endif // CHIP_TARGET_STYLE_UNIX

static const shell_command_t cmds_otcli_root = { &cmd_otcli_dispatch, "otcli", "Dispatch OpenThread CLI command" };

#if CHIP_TARGET_STYLE_EMBEDDED
#if OPENTHREAD_API_VERSION >= 85
static int OnOtCliOutput(void * aContext, const char * aFormat, va_list aArguments)
{
    int rval = vsnprintf(sTxBuffer, sTxLength, aFormat, aArguments);
    VerifyOrExit(rval >= 0 && rval < sTxLength, rval = CHIP_ERROR_BUFFER_TOO_SMALL.AsInteger());
    return streamer_write(streamer_get(), (const char *) sTxBuffer, rval);
exit:
    return rval;
}
#else
static int OnOtCliOutput(const char * aBuf, uint16_t aBufLength, void * aContext)
{
    return streamer_write(streamer_get(), aBuf, aBufLength);
}
#endif
#endif

#endif // CHIP_ENABLE_OPENTHREAD

void cmd_otcli_init()
{
#if CHIP_ENABLE_OPENTHREAD
#if CHIP_TARGET_STYLE_EMBEDDED
#if OPENTHREAD_API_VERSION >= 85
    otCliInit(otInstanceInitSingle(), &OnOtCliOutput, NULL);
#else
    otCliConsoleInit(otInstanceInitSingle(), &OnOtCliOutput, NULL);
#endif
#endif

    // Register the root otcli command with the top-level shell.
    Engine::Root().RegisterCommands(&cmds_otcli_root, 1);
#endif // CHIP_ENABLE_OPENTHREAD
}
<commit_msg>cli: lock Thread stack when calling OpenThread API (#13806)<commit_after>/*
 *
 *    Copyright (c) 2020 Project CHIP Authors
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

#include <lib/core/CHIPCore.h>

#include <ChipShellCollection.h>

#if CONFIG_DEVICE_LAYER
#include <platform/CHIPDeviceLayer.h>
#endif

#if CHIP_ENABLE_OPENTHREAD

#include <stdio.h>

#include <lib/shell/Engine.h>
#include <lib/support/CHIPArgParser.hpp>
#include <lib/support/CHIPMem.h>
#include <lib/support/CodeUtils.h>
#include <platform/ThreadStackManager.h>

#if CHIP_TARGET_STYLE_EMBEDDED
#include <openthread/cli.h>
#include <openthread/instance.h>
#include <openthread/ip6.h>
#include <openthread/link.h>
#include <openthread/thread.h>
#if OPENTHREAD_API_VERSION >= 85
#ifndef SHELL_OTCLI_TX_BUFFER_SIZE
#define SHELL_OTCLI_TX_BUFFER_SIZE 1024
#endif
static char sTxBuffer[SHELL_OTCLI_TX_BUFFER_SIZE];
static constexpr uint16_t sTxLength = SHELL_OTCLI_TX_BUFFER_SIZE;
#endif
#else
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#endif

using namespace chip;
using namespace chip::Shell;
using namespace chip::Platform;
using namespace chip::DeviceLayer;
using namespace chip::Logging;
using namespace chip::ArgParser;

static chip::Shell::Engine sShellOtcliSubcommands;

CHIP_ERROR cmd_otcli_help_iterator(shell_command_t * command, void * arg)
{
    streamer_printf(streamer_get(), "  %-15s %s\n\r", command->cmd_name, command->cmd_help);
    return CHIP_NO_ERROR;
}

CHIP_ERROR cmd_otcli_help(int argc, char ** argv)
{
    sShellOtcliSubcommands.ForEachCommand(cmd_otcli_help_iterator, nullptr);
    return CHIP_NO_ERROR;
}

#if CHIP_TARGET_STYLE_EMBEDDED

CHIP_ERROR cmd_otcli_dispatch(int argc, char ** argv)
{
    CHIP_ERROR error = CHIP_NO_ERROR;

// From OT CLI internal lib, kMaxLineLength = 128
#define kMaxLineLength 128
    char buff[kMaxLineLength] = { 0 };
    char * buff_ptr           = buff;
    int i                     = 0;

    VerifyOrExit(argc > 0, error = CHIP_ERROR_INVALID_ARGUMENT);

    for (i = 0; i < argc; i++)
    {
        size_t arg_len = strlen(argv[i]);

        /* Make sure that the next argument won't overflow the buffer */
        VerifyOrExit(buff_ptr + arg_len < buff + kMaxLineLength, error = CHIP_ERROR_BUFFER_TOO_SMALL);

        strncpy(buff_ptr, argv[i], arg_len);
        buff_ptr += arg_len;

        /* Make sure that there is enough buffer for a space char */
        if (buff_ptr + sizeof(char) < buff + kMaxLineLength)
        {
            strncpy(buff_ptr, " ", sizeof(char));
            buff_ptr++;
        }
    }
    buff_ptr = 0;
    chip::DeviceLayer::ThreadStackMgr().LockThreadStack();
#if OPENTHREAD_API_VERSION >= 85
    otCliInputLine(buff);
#else
    otCliConsoleInputLine(buff, buff_ptr - buff);
#endif
    chip::DeviceLayer::ThreadStackMgr().UnlockThreadStack();
exit:
    return error;
}

#elif CHIP_TARGET_STYLE_UNIX

CHIP_ERROR cmd_otcli_dispatch(int argc, char ** argv)
{
    int pid;
    uid_t euid         = geteuid();
    char ctl_command[] = "/usr/local/sbin/ot-ctl";

    // Must run as sudo.
    if (euid != 0)
    {
        streamer_printf(streamer_get(), "Error otcli: requires running chip-shell as sudo\n\r");
        return CHIP_ERROR_INCORRECT_STATE;
    }

    VerifyOrReturnError(argc > 0, CHIP_ERROR_INVALID_ARGUMENT);

    // Fork and execute the command.
    pid = fork();
    VerifyOrReturnError(pid != -1, CHIP_ERROR_INCORRECT_STATE);

    if (pid == 0)
    {
        // Child process to execute the command with provided arguments
        --argv; // Restore access to entry [0] containing the command;
        argv[0] = ctl_command;
        if (execvp(ctl_command, argv) < 0)
        {
            streamer_printf(streamer_get(), "Error exec %s: %s\n", ctl_command, strerror(errno));
        }
        exit(errno);
    }
    else
    {
        // Parent process to wait on child.
        int status;
        wait(&status);
        return (status) ? CHIP_ERROR_INCORRECT_STATE : CHIP_NO_ERROR;
    }
}

#endif // CHIP_TARGET_STYLE_UNIX

static const shell_command_t cmds_otcli_root = { &cmd_otcli_dispatch, "otcli", "Dispatch OpenThread CLI command" };

#if CHIP_TARGET_STYLE_EMBEDDED
#if OPENTHREAD_API_VERSION >= 85
static int OnOtCliOutput(void * aContext, const char * aFormat, va_list aArguments)
{
    int rval = vsnprintf(sTxBuffer, sTxLength, aFormat, aArguments);
    VerifyOrExit(rval >= 0 && rval < sTxLength, rval = CHIP_ERROR_BUFFER_TOO_SMALL.AsInteger());
    return streamer_write(streamer_get(), (const char *) sTxBuffer, rval);
exit:
    return rval;
}
#else
static int OnOtCliOutput(const char * aBuf, uint16_t aBufLength, void * aContext)
{
    return streamer_write(streamer_get(), aBuf, aBufLength);
}
#endif
#endif

#endif // CHIP_ENABLE_OPENTHREAD

void cmd_otcli_init()
{
#if CHIP_ENABLE_OPENTHREAD
#if CHIP_TARGET_STYLE_EMBEDDED
#if OPENTHREAD_API_VERSION >= 85
    otCliInit(otInstanceInitSingle(), &OnOtCliOutput, NULL);
#else
    otCliConsoleInit(otInstanceInitSingle(), &OnOtCliOutput, NULL);
#endif
#endif

    // Register the root otcli command with the top-level shell.
    Engine::Root().RegisterCommands(&cmds_otcli_root, 1);
#endif // CHIP_ENABLE_OPENTHREAD
}
<|endoftext|>


<commit_before>/*  Copyright (c) MediaArea.net SARL. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license that can
 *  be found in the License.html file in the root of the source tree.
 */

//---------------------------------------------------------------------------
// Pre-compilation
#include "MediaInfo/PreComp.h"
#ifdef __BORLANDC__
    #pragma hdrstop
#endif
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/Setup.h"
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#if defined(MEDIAINFO_DCP_YES)
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/Multiple/File_DcpCpl.h"
#include "MediaInfo/MediaInfo.h"
#include "MediaInfo/MediaInfo_Internal.h"
#include "MediaInfo/Multiple/File__ReferenceFilesHelper.h"
#include "MediaInfo/Multiple/File_DcpPkl.h"
#include "MediaInfo/Multiple/File_Mxf.h"
#include "ZenLib/Dir.h"
#include "ZenLib/FileName.h"
#include "tinyxml2.h"
#include <list>
using namespace tinyxml2;
using namespace std;
//---------------------------------------------------------------------------

namespace MediaInfoLib
{

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

//---------------------------------------------------------------------------
extern void DcpCpl_MergeFromPkl(File__ReferenceFilesHelper* FromCpl, File__ReferenceFilesHelper* FromPkl)
{
    struct info
    {
        Ztring FileName;
        File__ReferenceFilesHelper::references::iterator Reference;
    };
    map<Ztring, info> Map;
    list<File__ReferenceFilesHelper::references::iterator> List;
    ZtringList ExtraFiles_Name;
    for (File__ReferenceFilesHelper::references::iterator Reference=FromPkl->References.begin(); Reference!=FromPkl->References.end(); Reference++)
    {
        map<string, Ztring>::iterator UniqueID=Reference->Infos.find("UniqueID");
        for (size_t Pos=0; Pos<Reference->FileNames.size(); Pos++)
            if (UniqueID!=Reference->Infos.end())
            {
                Map[UniqueID->second].FileName=Reference->FileNames[Pos];
                Map[UniqueID->second].Reference=Reference;
            }
        List.push_back(Reference);
    }

    for (File__ReferenceFilesHelper::references::iterator Reference=FromCpl->References.begin(); Reference!=FromCpl->References.end(); Reference++)
        for (size_t Pos=0; Pos<Reference->FileNames.size(); Pos++)
        {
            map<Ztring, info>::iterator Map_Item=Map.find(Reference->FileNames[Pos]);
            if (Map_Item!=Map.end())
            {
                Reference->FileNames[Pos]=Map_Item->second.FileName;
                for (list<File__ReferenceFilesHelper::references::iterator>::iterator Reference2=List.begin(); Reference2!=List.end(); Reference2++)
                    if (*Reference2==Map_Item->second.Reference)
                    {
                        List.erase(Reference2);
                        break;
                    }
            }
        }

    for (list<File__ReferenceFilesHelper::references::iterator>::iterator Reference=List.begin(); Reference!=List.end(); Reference++)
    {
        FromCpl->References.push_back(**Reference);
        FromCpl->References[FromCpl->References.size()-1].StreamID=FromCpl->References.size()-1;
    }
}

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

//---------------------------------------------------------------------------
File_DcpCpl::File_DcpCpl()
:File__Analyze()
{
    #if MEDIAINFO_EVENTS
        ParserIDs[0]=MediaInfo_Parser_DcpCpl;
        StreamIDs_Width[0]=sizeof(size_t)*2;
    #endif //MEDIAINFO_EVENTS
    #if MEDIAINFO_DEMUX
        Demux_EventWasSent_Accept_Specific=true;
    #endif //MEDIAINFO_DEMUX

    //Temp
    ReferenceFiles=NULL;
}

//---------------------------------------------------------------------------
File_DcpCpl::~File_DcpCpl()
{
    delete ReferenceFiles; //ReferenceFiles=NULL;
}

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

//---------------------------------------------------------------------------
void File_DcpCpl::Streams_Finish()
{
    if (Config->File_IsReferenced_Get() || ReferenceFiles==NULL)
        return;

    ReferenceFiles->ParseReferences();
}

//***************************************************************************
// Buffer - Global
//***************************************************************************

//---------------------------------------------------------------------------
#if MEDIAINFO_SEEK
size_t File_DcpCpl::Read_Buffer_Seek (size_t Method, int64u Value, int64u ID)
{
    if (Config->File_IsReferenced_Get() || ReferenceFiles==NULL)
        return 0;

    return ReferenceFiles->Read_Buffer_Seek(Method, Value, ID);
}
#endif //MEDIAINFO_SEEK

//***************************************************************************
// Buffer - File header
//***************************************************************************

//---------------------------------------------------------------------------
bool File_DcpCpl::FileHeader_Begin()
{
    XMLDocument document;
    if (!FileHeader_Begin_XML(document))
       return false;

    bool IsDcp=false, IsImf=false;

    XMLElement* Root=document.FirstChildElement("CompositionPlaylist");
    if (!Root)
    {
        Reject("DcpCpl");
        return false;
    }

    const char* Attribute=Root->Attribute("xmlns");
    if (!Attribute)
    {
        Reject("DcpCpl");
        return false;
    }

    if (!strcmp(Attribute, "http://www.digicine.com/PROTO-ASDCP-CPL-20040511#"))
        IsDcp=true;
    if (!strcmp(Attribute, "http://www.smpte-ra.org/schemas/2067-3/XXXX") //Some muxers use XXXX instead of year
     || !strcmp(Attribute, "http://www.smpte-ra.org/schemas/2067-3/2013"))
        IsImf=true;

    if (!IsDcp && !IsImf)
    {
        Reject("DcpCpl");
        return false;
    }

    Accept("DcpCpl");
    Fill(Stream_General, 0, General_Format, IsDcp?"DCP CPL":"IMF CPL");
    Config->File_ID_OnlyRoot_Set(false);

    ReferenceFiles=new File__ReferenceFilesHelper(this, Config);

    //Parsing main elements
    for (XMLElement* Root_Item=Root->FirstChildElement(); Root_Item; Root_Item=Root_Item->NextSiblingElement())
    {
        //ReelList / SegmentList
        if ((IsDcp && !strcmp(Root_Item->Value(), "ReelList"))
         || (IsImf && !strcmp(Root_Item->Value(), "SegmentList")))
        {
            for (XMLElement* ReelList_Item=Root_Item->FirstChildElement(); ReelList_Item; ReelList_Item=ReelList_Item->NextSiblingElement())
            {
                //Reel
                if ((IsDcp && !strcmp(ReelList_Item->Value(), "Reel"))
                 || (IsImf && !strcmp(ReelList_Item->Value(), "Segment")))
                {
                    for (XMLElement* Reel_Item=ReelList_Item->FirstChildElement(); Reel_Item; Reel_Item=Reel_Item->NextSiblingElement())
                    {
                        //AssetList
                        if ((IsDcp && !strcmp(Reel_Item->Value(), "AssetList"))
                         || (IsImf && !strcmp(Reel_Item->Value(), "SequenceList")))
                        {
                            for (XMLElement* AssetList_Item=Reel_Item->FirstChildElement(); AssetList_Item; AssetList_Item=AssetList_Item->NextSiblingElement())
                            {
                                //File
                                //if ((IsDcp && (!strcmp(AssetList_Item->Value(), "MainPicture") || !strcmp(AssetList_Item->Value(), "MainSound")))
                                // || (IsImf && (!strcmp(AssetList_Item->Value(), "cc:MainImageSequence") || !strcmp(AssetList_Item->Value(), "cc:MainImage"))))
                                {
                                    File__ReferenceFilesHelper::reference ReferenceFile;
                                    Ztring Id;

                                    if ((IsDcp && !strcmp(AssetList_Item->Value(), "MainPicture"))
                                     || (IsImf && !strcmp(AssetList_Item->Value(), "cc:MainImageSequence")))
                                        ReferenceFile.StreamKind=Stream_Video;
                                    if ((IsDcp && !strcmp(AssetList_Item->Value(), "MainSound"))
                                     || (IsImf && !strcmp(AssetList_Item->Value(), "cc:MainAudioSequence")))
                                        ReferenceFile.StreamKind=Stream_Audio;

                                    for (XMLElement* File_Item=AssetList_Item->FirstChildElement(); File_Item; File_Item=File_Item->NextSiblingElement())
                                    {
                                        //Id
                                        if (!strcmp(File_Item->Value(), "Id") && Id.empty())
                                            Id.From_UTF8(File_Item->GetText());

                                        //ResourceList
                                        if (IsImf && !strcmp(File_Item->Value(), "ResourceList"))
                                        {
                                            for (XMLElement* ResourceList_Item=File_Item->FirstChildElement(); ResourceList_Item; ResourceList_Item=ResourceList_Item->NextSiblingElement())
                                            {
                                                //Resource
                                                if (!strcmp(ResourceList_Item->Value(), "Resource"))
                                                {
                                                    for (XMLElement* Resource_Item=ResourceList_Item->FirstChildElement(); Resource_Item; Resource_Item=Resource_Item->NextSiblingElement())
                                                    {
                                                        //TrackFileId
                                                        if (!strcmp(Resource_Item->Value(), "TrackFileId"))
                                                            ReferenceFile.FileNames.push_back(Resource_Item->GetText());
                                                    }
                                                }
                                            }
                                        }
                                    }

                                    if (ReferenceFile.FileNames.empty())
                                        ReferenceFile.FileNames.push_back(Id);
                                    ReferenceFile.StreamID=ReferenceFiles->References.size()+1;
                                    ReferenceFiles->References.push_back(ReferenceFile);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    Element_Offset=File_Size;

    //Getting files names
    if (!Config->File_IsReferenced_Get())
    {
        FileName Directory(File_Name);
        ZtringList List;
        if (IsDcp)
            List=Dir::GetAllFileNames(Directory.Path_Get()+PathSeparator+__T("*_pkl.xml"), Dir::Include_Files);
        if (IsImf)
            List=Dir::GetAllFileNames(Directory.Path_Get()+PathSeparator+__T("PKL_*.xml"), Dir::Include_Files);
        for (size_t Pos=0; Pos<List.size(); Pos++)
        {
            MediaInfo_Internal MI;
            MI.Option(__T("File_KeepInfo"), __T("1"));
            Ztring ParseSpeed_Save=MI.Option(__T("ParseSpeed_Get"), __T(""));
            Ztring Demux_Save=MI.Option(__T("Demux_Get"), __T(""));
            MI.Option(__T("ParseSpeed"), __T("0"));
            MI.Option(__T("Demux"), Ztring());
            MI.Option(__T("File_IsReferenced"), __T("1"));
            size_t MiOpenResult=MI.Open(List[Pos]);
            MI.Option(__T("ParseSpeed"), ParseSpeed_Save); //This is a global value, need to reset it. TODO: local value
            MI.Option(__T("Demux"), Demux_Save); //This is a global value, need to reset it. TODO: local value
            if (MiOpenResult
             && ((IsDcp && MI.Get(Stream_General, 0, General_Format)==__T("DCP PKL"))
              || (IsImf && MI.Get(Stream_General, 0, General_Format)==__T("IMF PKL"))))
            {
                DcpCpl_MergeFromPkl(ReferenceFiles, ((File_DcpCpl*)MI.Info)->ReferenceFiles);
            }
        }
    }

    //All should be OK...
    return true;
}

} //NameSpace

#endif //MEDIAINFO_DCP_YES

<commit_msg>Prefer the prefix ++ operator.<commit_after>/*  Copyright (c) MediaArea.net SARL. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license that can
 *  be found in the License.html file in the root of the source tree.
 */

//---------------------------------------------------------------------------
// Pre-compilation
#include "MediaInfo/PreComp.h"
#ifdef __BORLANDC__
    #pragma hdrstop
#endif
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/Setup.h"
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#if defined(MEDIAINFO_DCP_YES)
//---------------------------------------------------------------------------

//---------------------------------------------------------------------------
#include "MediaInfo/Multiple/File_DcpCpl.h"
#include "MediaInfo/MediaInfo.h"
#include "MediaInfo/MediaInfo_Internal.h"
#include "MediaInfo/Multiple/File__ReferenceFilesHelper.h"
#include "MediaInfo/Multiple/File_DcpPkl.h"
#include "MediaInfo/Multiple/File_Mxf.h"
#include "ZenLib/Dir.h"
#include "ZenLib/FileName.h"
#include "tinyxml2.h"
#include <list>
using namespace tinyxml2;
using namespace std;
//---------------------------------------------------------------------------

namespace MediaInfoLib
{

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

//---------------------------------------------------------------------------
extern void DcpCpl_MergeFromPkl(File__ReferenceFilesHelper* FromCpl, File__ReferenceFilesHelper* FromPkl)
{
    struct info
    {
        Ztring FileName;
        File__ReferenceFilesHelper::references::iterator Reference;
    };
    map<Ztring, info> Map;
    list<File__ReferenceFilesHelper::references::iterator> List;
    ZtringList ExtraFiles_Name;
    for (File__ReferenceFilesHelper::references::iterator Reference=FromPkl->References.begin(); Reference!=FromPkl->References.end(); ++Reference)
    {
        map<string, Ztring>::iterator UniqueID=Reference->Infos.find("UniqueID");
        for (size_t Pos=0; Pos<Reference->FileNames.size(); Pos++)
            if (UniqueID!=Reference->Infos.end())
            {
                Map[UniqueID->second].FileName=Reference->FileNames[Pos];
                Map[UniqueID->second].Reference=Reference;
            }
        List.push_back(Reference);
    }

    for (File__ReferenceFilesHelper::references::iterator Reference=FromCpl->References.begin(); Reference!=FromCpl->References.end(); ++Reference)
        for (size_t Pos=0; Pos<Reference->FileNames.size(); Pos++)
        {
            map<Ztring, info>::iterator Map_Item=Map.find(Reference->FileNames[Pos]);
            if (Map_Item!=Map.end())
            {
                Reference->FileNames[Pos]=Map_Item->second.FileName;
                for (list<File__ReferenceFilesHelper::references::iterator>::iterator Reference2=List.begin(); Reference2!=List.end(); ++Reference2)
                    if (*Reference2==Map_Item->second.Reference)
                    {
                        List.erase(Reference2);
                        break;
                    }
            }
        }

    for (list<File__ReferenceFilesHelper::references::iterator>::iterator Reference=List.begin(); Reference!=List.end(); ++Reference)
    {
        FromCpl->References.push_back(**Reference);
        FromCpl->References[FromCpl->References.size()-1].StreamID=FromCpl->References.size()-1;
    }
}

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

//---------------------------------------------------------------------------
File_DcpCpl::File_DcpCpl()
:File__Analyze()
{
    #if MEDIAINFO_EVENTS
        ParserIDs[0]=MediaInfo_Parser_DcpCpl;
        StreamIDs_Width[0]=sizeof(size_t)*2;
    #endif //MEDIAINFO_EVENTS
    #if MEDIAINFO_DEMUX
        Demux_EventWasSent_Accept_Specific=true;
    #endif //MEDIAINFO_DEMUX

    //Temp
    ReferenceFiles=NULL;
}

//---------------------------------------------------------------------------
File_DcpCpl::~File_DcpCpl()
{
    delete ReferenceFiles; //ReferenceFiles=NULL;
}

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

//---------------------------------------------------------------------------
void File_DcpCpl::Streams_Finish()
{
    if (Config->File_IsReferenced_Get() || ReferenceFiles==NULL)
        return;

    ReferenceFiles->ParseReferences();
}

//***************************************************************************
// Buffer - Global
//***************************************************************************

//---------------------------------------------------------------------------
#if MEDIAINFO_SEEK
size_t File_DcpCpl::Read_Buffer_Seek (size_t Method, int64u Value, int64u ID)
{
    if (Config->File_IsReferenced_Get() || ReferenceFiles==NULL)
        return 0;

    return ReferenceFiles->Read_Buffer_Seek(Method, Value, ID);
}
#endif //MEDIAINFO_SEEK

//***************************************************************************
// Buffer - File header
//***************************************************************************

//---------------------------------------------------------------------------
bool File_DcpCpl::FileHeader_Begin()
{
    XMLDocument document;
    if (!FileHeader_Begin_XML(document))
       return false;

    bool IsDcp=false, IsImf=false;

    XMLElement* Root=document.FirstChildElement("CompositionPlaylist");
    if (!Root)
    {
        Reject("DcpCpl");
        return false;
    }

    const char* Attribute=Root->Attribute("xmlns");
    if (!Attribute)
    {
        Reject("DcpCpl");
        return false;
    }

    if (!strcmp(Attribute, "http://www.digicine.com/PROTO-ASDCP-CPL-20040511#"))
        IsDcp=true;
    if (!strcmp(Attribute, "http://www.smpte-ra.org/schemas/2067-3/XXXX") //Some muxers use XXXX instead of year
     || !strcmp(Attribute, "http://www.smpte-ra.org/schemas/2067-3/2013"))
        IsImf=true;

    if (!IsDcp && !IsImf)
    {
        Reject("DcpCpl");
        return false;
    }

    Accept("DcpCpl");
    Fill(Stream_General, 0, General_Format, IsDcp?"DCP CPL":"IMF CPL");
    Config->File_ID_OnlyRoot_Set(false);

    ReferenceFiles=new File__ReferenceFilesHelper(this, Config);

    //Parsing main elements
    for (XMLElement* Root_Item=Root->FirstChildElement(); Root_Item; Root_Item=Root_Item->NextSiblingElement())
    {
        //ReelList / SegmentList
        if ((IsDcp && !strcmp(Root_Item->Value(), "ReelList"))
         || (IsImf && !strcmp(Root_Item->Value(), "SegmentList")))
        {
            for (XMLElement* ReelList_Item=Root_Item->FirstChildElement(); ReelList_Item; ReelList_Item=ReelList_Item->NextSiblingElement())
            {
                //Reel
                if ((IsDcp && !strcmp(ReelList_Item->Value(), "Reel"))
                 || (IsImf && !strcmp(ReelList_Item->Value(), "Segment")))
                {
                    for (XMLElement* Reel_Item=ReelList_Item->FirstChildElement(); Reel_Item; Reel_Item=Reel_Item->NextSiblingElement())
                    {
                        //AssetList
                        if ((IsDcp && !strcmp(Reel_Item->Value(), "AssetList"))
                         || (IsImf && !strcmp(Reel_Item->Value(), "SequenceList")))
                        {
                            for (XMLElement* AssetList_Item=Reel_Item->FirstChildElement(); AssetList_Item; AssetList_Item=AssetList_Item->NextSiblingElement())
                            {
                                //File
                                //if ((IsDcp && (!strcmp(AssetList_Item->Value(), "MainPicture") || !strcmp(AssetList_Item->Value(), "MainSound")))
                                // || (IsImf && (!strcmp(AssetList_Item->Value(), "cc:MainImageSequence") || !strcmp(AssetList_Item->Value(), "cc:MainImage"))))
                                {
                                    File__ReferenceFilesHelper::reference ReferenceFile;
                                    Ztring Id;

                                    if ((IsDcp && !strcmp(AssetList_Item->Value(), "MainPicture"))
                                     || (IsImf && !strcmp(AssetList_Item->Value(), "cc:MainImageSequence")))
                                        ReferenceFile.StreamKind=Stream_Video;
                                    if ((IsDcp && !strcmp(AssetList_Item->Value(), "MainSound"))
                                     || (IsImf && !strcmp(AssetList_Item->Value(), "cc:MainAudioSequence")))
                                        ReferenceFile.StreamKind=Stream_Audio;

                                    for (XMLElement* File_Item=AssetList_Item->FirstChildElement(); File_Item; File_Item=File_Item->NextSiblingElement())
                                    {
                                        //Id
                                        if (!strcmp(File_Item->Value(), "Id") && Id.empty())
                                            Id.From_UTF8(File_Item->GetText());

                                        //ResourceList
                                        if (IsImf && !strcmp(File_Item->Value(), "ResourceList"))
                                        {
                                            for (XMLElement* ResourceList_Item=File_Item->FirstChildElement(); ResourceList_Item; ResourceList_Item=ResourceList_Item->NextSiblingElement())
                                            {
                                                //Resource
                                                if (!strcmp(ResourceList_Item->Value(), "Resource"))
                                                {
                                                    for (XMLElement* Resource_Item=ResourceList_Item->FirstChildElement(); Resource_Item; Resource_Item=Resource_Item->NextSiblingElement())
                                                    {
                                                        //TrackFileId
                                                        if (!strcmp(Resource_Item->Value(), "TrackFileId"))
                                                            ReferenceFile.FileNames.push_back(Resource_Item->GetText());
                                                    }
                                                }
                                            }
                                        }
                                    }

                                    if (ReferenceFile.FileNames.empty())
                                        ReferenceFile.FileNames.push_back(Id);
                                    ReferenceFile.StreamID=ReferenceFiles->References.size()+1;
                                    ReferenceFiles->References.push_back(ReferenceFile);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    Element_Offset=File_Size;

    //Getting files names
    if (!Config->File_IsReferenced_Get())
    {
        FileName Directory(File_Name);
        ZtringList List;
        if (IsDcp)
            List=Dir::GetAllFileNames(Directory.Path_Get()+PathSeparator+__T("*_pkl.xml"), Dir::Include_Files);
        if (IsImf)
            List=Dir::GetAllFileNames(Directory.Path_Get()+PathSeparator+__T("PKL_*.xml"), Dir::Include_Files);
        for (size_t Pos=0; Pos<List.size(); Pos++)
        {
            MediaInfo_Internal MI;
            MI.Option(__T("File_KeepInfo"), __T("1"));
            Ztring ParseSpeed_Save=MI.Option(__T("ParseSpeed_Get"), __T(""));
            Ztring Demux_Save=MI.Option(__T("Demux_Get"), __T(""));
            MI.Option(__T("ParseSpeed"), __T("0"));
            MI.Option(__T("Demux"), Ztring());
            MI.Option(__T("File_IsReferenced"), __T("1"));
            size_t MiOpenResult=MI.Open(List[Pos]);
            MI.Option(__T("ParseSpeed"), ParseSpeed_Save); //This is a global value, need to reset it. TODO: local value
            MI.Option(__T("Demux"), Demux_Save); //This is a global value, need to reset it. TODO: local value
            if (MiOpenResult
             && ((IsDcp && MI.Get(Stream_General, 0, General_Format)==__T("DCP PKL"))
              || (IsImf && MI.Get(Stream_General, 0, General_Format)==__T("IMF PKL"))))
            {
                DcpCpl_MergeFromPkl(ReferenceFiles, ((File_DcpCpl*)MI.Info)->ReferenceFiles);
            }
        }
    }

    //All should be OK...
    return true;
}

} //NameSpace

#endif //MEDIAINFO_DCP_YES

<|endoftext|>


<commit_before>#include "addcomputerscientist.h"
#include "ui_addcomputerscientist.h"

AddComputerScientist::AddComputerScientist(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::AddComputerScientist)
{
    ui->setupUi(this);

    // getCurrent year   (year is the currentyear)
    time_t timeNow = time(0);
    tm *ltm = localtime(&timeNow);
    int year = ltm->tm_year + 1900;

    // Validation for year of birth & year of death
    QIntValidator *yearValidator = new QIntValidator(0,year);
    ui->lineEdit_Addscientist_yearofbirth->setValidator(yearValidator);
    ui->lineEdit_Addscientist_deathYear->setValidator(yearValidator);

}

AddComputerScientist::~AddComputerScientist()
{
    delete ui;
}

void AddComputerScientist::on_pushButton_Addscientist_save_clicked()
{
    // While loop conditions
    bool exitLoop;
    bool validInput;

    // Gender options
    bool male = false;
    bool female = false;
    bool other = false;

    QString name = "";
    // isAlive is connected to the checkbox
    bool isAlive;
    QString gender;
    QString comment;
    QString birthYear;
    QString deathYear;

    // Taka inn mynd

    bool canCreatePerson = true;

    name = ui->lineEdit_Addscientist_name->text();
    qDebug() << name;
    birthYear = ui->lineEdit_Addscientist_yearofbirth->text();
    qDebug() << birthYear;
    isAlive = ui->checkBox_Addscientist_isPersonAlive->isChecked();
    if(isAlive)
    {
        qDebug() << "This person is still alive";
    }
    else if(isAlive == false)
    {
        deathYear = ui->lineEdit_Addscientist_deathYear->selectedText();
        qDebug() << "This person died in the year" << deathYear;
    }

    // If name or birthYear are empty strings
    if(name == "" || birthYear == "")
    {
        canCreatePerson = false;
    }

    if(isAlive == false && deathYear == "")
    {
        canCreatePerson = false;
    }

    // 1 denotes success 0 denotes failure
    if(canCreatePerson == true)
    {
        CSPerson createdPerson;
        _newPerson = createdPerson;
        //setResult(QDialog::Accepted);
    }
    else
    {
        //setResult(QDialog::Rejected);
    }

}
<commit_msg>progress made on addComputerScientist<commit_after>#include "addcomputerscientist.h"
#include "ui_addcomputerscientist.h"

AddComputerScientist::AddComputerScientist(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::AddComputerScientist)
{
    ui->setupUi(this);

    // getCurrent year   (year is the currentyear)
    time_t timeNow = time(0);
    tm *ltm = localtime(&timeNow);
    int year = ltm->tm_year + 1900;

    // Validation for year of birth & year of death
    QIntValidator *yearValidator = new QIntValidator(0,year);
    ui->lineEdit_Addscientist_yearofbirth->setValidator(yearValidator);
    ui->lineEdit_Addscientist_deathYear->setValidator(yearValidator);

}

AddComputerScientist::~AddComputerScientist()
{
    delete ui;
}

void AddComputerScientist::on_pushButton_Addscientist_save_clicked()
{
    // If validation fails these are used
    bool nameFail = false;
    bool genderFail = false;
    bool birthYearFail = false;
    bool deathYearFail = false;

    // If validation fails this is set as false
    bool canCreatePerson = true;

    // Gender options
    bool male = false;
    bool female = false;
    bool other = false;

    QString name = "";
    QString comment = "";
    QString birthYear = "";
    QString deathYear = "";
    QString gender = "";

    // isAlive is connected to the checkbox
    bool isAlive;

    // Taka inn mynd

    name = ui->lineEdit_Addscientist_name->text();
    birthYear = ui->lineEdit_Addscientist_yearofbirth->text();
    comment = ui->lineEdit_Addscientist_comment->text();
    isAlive = ui->checkBox_Addscientist_isPersonAlive->isChecked();

    if(isAlive == true)
    {
        qDebug() << "This person is still alive";
    }
    else if(isAlive == false)
    {
        deathYear = ui->lineEdit_Addscientist_deathYear->text();
    }

    if(ui->radioButton_Addscientist_male->isChecked())
    {
        gender = "Male";
        qDebug() << "Gender selected Male";
    }
    if(ui->radioButton_Addscientist_female->isChecked())
    {
        gender = "Female";
        qDebug() << "Gender selected Female";
    }
    if(ui->radioButton_Addscientist_otherGender->isChecked())
    {
        gender = "Other";
        qDebug() << "Gender selected Other";
    }

    // Validations

    if(name == "" || birthYear == "")
    {
        canCreatePerson = false;
        nameFail = true;
    }

    if(birthYear == "")
    {
        canCreatePerson = false;
        birthYearFail = true;
    }

    if(isAlive == false && deathYear == "")
    {
        canCreatePerson = false;
        deathYearFail = true;
    }

    if(gender == "")
    {
        canCreatePerson = false;
        genderFail = true;
    }

    // 1 denotes success 0 denotes failure
    if(canCreatePerson == true)
    {
        CSPerson createdPerson;
        _newPerson = createdPerson;
        //setResult(QDialog::Accepted);
    }
    else
    {
        //setResult(QDialog::Rejected);
    }

}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: SlsPageDescriptor.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: kz $ $Date: 2004-10-04 18:38:08 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#ifndef SD_SLIDESORTER_PAGE_DESCRIPTOR_HXX
#define SD_SLIDESORTER_PAGE_DESCRIPTOR_HXX

#ifndef _SV_GEN_HXX
#include <tools/gen.hxx>
#endif
#include <tools/link.hxx>
#include <vcl/bitmap.hxx>
#include <sfx2/viewfrm.hxx>

class SdPage;

#include <memory>

namespace sdr { namespace contact {
class ObjectContact;
} }

namespace sd { namespace slidesorter { namespace view {
class PageObject;
class PageObjectViewObjectContact;
} } }

namespace sd { namespace slidesorter { namespace controller {
class PageObjectFactory;
} } }

namespace sd { namespace slidesorter { namespace model {

class SlideSorterView;
class SlideRenderer;

/** Each PageDescriptor object represents the preview of one draw page,
    slide, or master page of a Draw or Impress document as they are displayed
    in the slide sorter.  This class gives access to some associated
    information like prerendered preview or position on the screen.

Bounding boxes of page objects come in four varieties:
    Model and screen/pixel coordinates and the bounding boxes of the actual
    page objects and the larger bounding boxes that include page names and
    fade symbol.

*/
class PageDescriptor
{
public:
    PageDescriptor (
        SdPage& rPage,
        const controller::PageObjectFactory& rPageObjectFactory);
    ~PageDescriptor (void);

    /** Return the page that is represented by the descriptor.
    */
    SdPage* GetPage (void) const;

    /** Return the page shape that is used for visualizing the page.
    */
    view::PageObject* GetPageObject (void);
    void ReleasePageObject (void);

    /** Return <TRUE/> when the page object is fully or parially visible. */
    bool IsVisible (void) const;

    /** Set the visible state that is returned by the IsVisible() method.
        This method is typically called by the view who renders the object
        onto the screen.
    */
    void SetVisible (bool bVisible);

    /** Make sure that the page is selected and return whether the
        selection state changed.
    */
    bool Select (void);
    /** Make sure that the page is not selected and return whether the
        selection state changed.
    */
    bool Deselect (void);

    /** Return whether the page is selected (and thus bypasses the internal
        mbIsSelected flag.
    */
    bool IsSelected (void) const;

    /** Set the internal mbIsSelected flag to the selection state of the
        page.  Use this method to synchornize a page descriptor with the
        page it describes and determine whether a redraw to update the
        selection indicator is necessary.
        @return
            When the two selection states were different <TRUE/> is
            returned.  When they were the same this method returns
            <FALSE/>.
    */
    bool UpdateSelection (void);

    bool IsFocused (void) const;
    void SetFocus (void);
    void RemoveFocus (void);

    view::PageObjectViewObjectContact* GetViewObjectContact (void) const;

    void SetViewObjectContact (
        view::PageObjectViewObjectContact* pViewObjectContact);

    /** Return the currently used page object factory.
    */
    const controller::PageObjectFactory& GetPageObjectFactory (void) const;

    /** Replace the current page object factory by the given one.
    */
    void SetPageObjectFactory (const controller::PageObjectFactory& rFactory);

    void SetModelBorder (const SvBorder& rBorder);
    SvBorder GetModelBorder (void) const;

    void SetPageNumberAreaModelSize (const Size& rSize);
    Size GetPageNumberAreaModelSize (void) const;

private:
    SdPage& mrPage;

    /// The factory that is used to create PageObject objects.
    const controller::PageObjectFactory* mpPageObjectFactory;

    /** The page object will be destroyed by the page into which it has
        been inserted.
    */
    view::PageObject* mpPageObject;

    bool mbIsSelected;
    bool mbVisible;
    bool mbFocused;

    view::PageObjectViewObjectContact* mpViewObjectContact;

    /// The borders in model coordinates arround the page object.
    SvBorder maModelBorder;

    /// The size of the page number area in model coordinates.
    Size maPageNumberAreaModelSize;

    // Do not use the copy constructor operator.  It is not implemented.
    PageDescriptor (const PageDescriptor& rDescriptor);

    // Do not use the assignment operator.  It is not implemented
    // (mrPage can not be assigned).
    PageDescriptor& operator= (const PageDescriptor& rDescriptor);
};

} } } // end of namespace ::sd::slidesorter::model

#endif
<commit_msg>INTEGRATION: CWS impress62 (1.4.306); FILE MERGED 2005/06/29 08:31:44 af 1.4.306.1: #i47134# Added a comment for SetPageNumberAreaModelSize().<commit_after>/*************************************************************************
 *
 *  $RCSfile: SlsPageDescriptor.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: obo $ $Date: 2005-07-07 13:37:05 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#ifndef SD_SLIDESORTER_PAGE_DESCRIPTOR_HXX
#define SD_SLIDESORTER_PAGE_DESCRIPTOR_HXX

#ifndef _SV_GEN_HXX
#include <tools/gen.hxx>
#endif
#include <tools/link.hxx>
#include <vcl/bitmap.hxx>
#include <sfx2/viewfrm.hxx>

class SdPage;

#include <memory>

namespace sdr { namespace contact {
class ObjectContact;
} }

namespace sd { namespace slidesorter { namespace view {
class PageObject;
class PageObjectViewObjectContact;
} } }

namespace sd { namespace slidesorter { namespace controller {
class PageObjectFactory;
} } }

namespace sd { namespace slidesorter { namespace model {

class SlideSorterView;
class SlideRenderer;

/** Each PageDescriptor object represents the preview of one draw page,
    slide, or master page of a Draw or Impress document as they are displayed
    in the slide sorter.  This class gives access to some associated
    information like prerendered preview or position on the screen.

Bounding boxes of page objects come in four varieties:
    Model and screen/pixel coordinates and the bounding boxes of the actual
    page objects and the larger bounding boxes that include page names and
    fade symbol.

*/
class PageDescriptor
{
public:
    PageDescriptor (
        SdPage& rPage,
        const controller::PageObjectFactory& rPageObjectFactory);
    ~PageDescriptor (void);

    /** Return the page that is represented by the descriptor.
    */
    SdPage* GetPage (void) const;

    /** Return the page shape that is used for visualizing the page.
    */
    view::PageObject* GetPageObject (void);
    void ReleasePageObject (void);

    /** Return <TRUE/> when the page object is fully or parially visible. */
    bool IsVisible (void) const;

    /** Set the visible state that is returned by the IsVisible() method.
        This method is typically called by the view who renders the object
        onto the screen.
    */
    void SetVisible (bool bVisible);

    /** Make sure that the page is selected and return whether the
        selection state changed.
    */
    bool Select (void);
    /** Make sure that the page is not selected and return whether the
        selection state changed.
    */
    bool Deselect (void);

    /** Return whether the page is selected (and thus bypasses the internal
        mbIsSelected flag.
    */
    bool IsSelected (void) const;

    /** Set the internal mbIsSelected flag to the selection state of the
        page.  Use this method to synchornize a page descriptor with the
        page it describes and determine whether a redraw to update the
        selection indicator is necessary.
        @return
            When the two selection states were different <TRUE/> is
            returned.  When they were the same this method returns
            <FALSE/>.
    */
    bool UpdateSelection (void);

    bool IsFocused (void) const;
    void SetFocus (void);
    void RemoveFocus (void);

    view::PageObjectViewObjectContact* GetViewObjectContact (void) const;

    void SetViewObjectContact (
        view::PageObjectViewObjectContact* pViewObjectContact);

    /** Return the currently used page object factory.
    */
    const controller::PageObjectFactory& GetPageObjectFactory (void) const;

    /** Replace the current page object factory by the given one.
    */
    void SetPageObjectFactory (const controller::PageObjectFactory& rFactory);

    void SetModelBorder (const SvBorder& rBorder);
    SvBorder GetModelBorder (void) const;

    /** The size of the area in which the page number is displayed is
        calculated by the SlideSorterView and then stored in the page
        descriptors so that the contact objects can access them.  The
        contact objects can not calculate them on demand because the total
        number of slides is needed to do that and this number is not known
        to the contact objects.
    */
    void SetPageNumberAreaModelSize (const Size& rSize);
    Size GetPageNumberAreaModelSize (void) const;

private:
    SdPage& mrPage;

    /// The factory that is used to create PageObject objects.
    const controller::PageObjectFactory* mpPageObjectFactory;

    /** The page object will be destroyed by the page into which it has
        been inserted.
    */
    view::PageObject* mpPageObject;

    bool mbIsSelected;
    bool mbVisible;
    bool mbFocused;

    view::PageObjectViewObjectContact* mpViewObjectContact;

    /// The borders in model coordinates arround the page object.
    SvBorder maModelBorder;

    /// The size of the page number area in model coordinates.
    Size maPageNumberAreaModelSize;

    // Do not use the copy constructor operator.  It is not implemented.
    PageDescriptor (const PageDescriptor& rDescriptor);

    // Do not use the assignment operator.  It is not implemented
    // (mrPage can not be assigned).
    PageDescriptor& operator= (const PageDescriptor& rDescriptor);
};

} } } // end of namespace ::sd::slidesorter::model

#endif
<|endoftext|>


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

#include "itkPhysicalPointImageSource.h"

#include "itkImageFileWriter.h"

#include "itkVectorImage.h"
#include "itkVectorIndexSelectionCastImageFilter.h"

namespace {
template< typename TImageType >
int itkPhysicalPointImageSourceTest(  const std::string &fname,
                                      typename TImageType::SizeType &size,
                                      typename TImageType::SpacingType &spacing,
                                      typename TImageType::PointType &origin,
                                      typename TImageType::DirectionType &direction)
{

  typedef TImageType ImageType;

  typedef itk::PhysicalPointImageSource< ImageType > PointerSourceType;

  typename PointerSourceType::Pointer source = PointerSourceType::New();
  source->SetSize(size);
  source->SetSpacing(spacing);
  source->SetOrigin(origin);
  source->SetDirection( direction );

  try
    {
    source->UpdateLargestPossibleRegion();
     }
   catch (itk::ExceptionObject & err)
     {
     std::cout << "Exception in filter execution!" << std::endl;
     std::cout << err << std::endl;
     return EXIT_FAILURE;
     }

  typedef itk::Image< typename itk::NumericTraits< typename ImageType::PixelType >::ValueType, ImageType::ImageDimension> ValueImageType;

  typedef itk::VectorIndexSelectionCastImageFilter< ImageType, ValueImageType > ValueImageCastFilter;
  typename ValueImageCastFilter::Pointer vif = ValueImageCastFilter::New();
  vif->SetInput( source->GetOutput() );
  vif->SetIndex(0);

    typedef itk::ImageFileWriter<ValueImageType> WriterType;
   typename WriterType::Pointer writer = WriterType::New();
   writer->SetFileName( fname );
   writer->SetInput( vif->GetOutput() );
   try
     {
     std::cout << "Writing image to " << fname << std::endl;
     writer->Update();
     }
   catch (itk::ExceptionObject & err)
     {
     std::cout << "Exception in writing!" << std::endl;
     std::cout << err << std::endl;
     return EXIT_FAILURE;
     }
   return EXIT_SUCCESS;
}

}
int itkPhysicalPointImageSourceTest( int argc, char *argv[] )
{
  double theta = 0;
  const unsigned int ImageDimension = 2;

  if ( argc < 3 )
    {
    std::cout << "Usage: " << argv[0] << " outputImage whichTest [ theta ]" << std::endl;
    return EXIT_FAILURE;
    }
  if ( argc >= 4 )
    {
    theta = atof( argv[3] );
    }

  itk::Size<ImageDimension> size;
  size.Fill(64);

  typedef itk::Image<unsigned char,ImageDimension> ImageType;
  ImageType::SpacingType spacing(1.0);
  ImageType::PointType origin(0.0);
  ImageType::DirectionType direction;

  direction.SetIdentity();

  int test;
  if ( atoi( argv[2] ) == 0 )
    {
    test = itkPhysicalPointImageSourceTest<itk::Image<itk::Point<double, ImageDimension>, ImageDimension > >( std::string( argv[1] ), size, spacing, origin, direction );
    }
  else if ( atoi( argv[2] ) == 1 )
    {
    test = itkPhysicalPointImageSourceTest<itk::VectorImage<double, ImageDimension> >( std::string( argv[1] ), size, spacing, origin, direction );
    }
  else if ( atoi( argv[2] ) == 2 )
    {
    spacing.Fill( 1.123 );
    origin.Fill( -0.987 );
    test = itkPhysicalPointImageSourceTest<itk::Image<itk::Point<float, ImageDimension>, ImageDimension > >( std::string( argv[1] ), size, spacing, origin, direction );
    }
  else
    {
    itk::SpacePrecisionType M[] = { std::cos( theta ), -std::sin( theta ),
                    std::sin( theta ), std::cos( theta ) };

    direction = vnl_matrix<itk::SpacePrecisionType>( M, 2, 2);
    test = itkPhysicalPointImageSourceTest< itk::VectorImage<float, ImageDimension> >( std::string( argv[1] ), size, spacing, origin, direction );
    }

  return test;
}
<commit_msg>ENH: Improve itkPhysicalPointImageSource class coverage.<commit_after>/*=========================================================================
 *
 *  Copyright Insight Software Consortium
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *=========================================================================*/

#include "itkPhysicalPointImageSource.h"

#include "itkImageFileWriter.h"

#include "itkVectorImage.h"
#include "itkVectorIndexSelectionCastImageFilter.h"
#include "itkTestingMacros.h"

namespace {
template< typename TImageType >
int itkPhysicalPointImageSourceTest( const std::string &fname,
                                     typename TImageType::SizeType &size,
                                     typename TImageType::SpacingType &spacing,
                                     typename TImageType::PointType &origin,
                                     typename TImageType::DirectionType &direction )
{

  typedef TImageType ImageType;

  typedef itk::PhysicalPointImageSource< ImageType > PointerSourceType;

  typename PointerSourceType::Pointer source = PointerSourceType::New();
  source->SetSize(size);
  source->SetSpacing(spacing);
  source->SetOrigin(origin);
  source->SetDirection( direction );

  TRY_EXPECT_NO_EXCEPTION( source->UpdateLargestPossibleRegion() );

  typedef itk::Image< typename itk::NumericTraits< typename ImageType::PixelType >::ValueType, ImageType::ImageDimension >
    ValueImageType;

  typedef itk::VectorIndexSelectionCastImageFilter< ImageType, ValueImageType > ValueImageCastFilter;
  typename ValueImageCastFilter::Pointer vif = ValueImageCastFilter::New();
  vif->SetInput( source->GetOutput() );
  vif->SetIndex(0);

   typedef itk::ImageFileWriter< ValueImageType > WriterType;
   typename WriterType::Pointer writer = WriterType::New();
   writer->SetFileName( fname );
   writer->SetInput( vif->GetOutput() );

  TRY_EXPECT_NO_EXCEPTION( writer->Update() );

   return EXIT_SUCCESS;
}

}
int itkPhysicalPointImageSourceTest( int argc, char *argv[] )
{
  double theta = 0;
  const unsigned int ImageDimension = 2;

  if ( argc < 3 )
    {
    std::cout << "Usage: " << argv[0] << " outputImage whichTest [ theta ]" << std::endl;
    return EXIT_FAILURE;
    }
  if ( argc >= 4 )
    {
    theta = atof( argv[3] );
    }

  itk::Size<ImageDimension> size;
  size.Fill(64);

  typedef itk::Image< unsigned char, ImageDimension > ImageType;
  ImageType::SpacingType spacing(1.0);
  ImageType::PointType origin(0.0);
  ImageType::DirectionType direction;

  direction.SetIdentity();

  // Exercise basic object methods
  // Done outside the helper function in the test because GCC is limited
  // when calling overloaded base class functions.
  typedef itk::PhysicalPointImageSource< itk::Image< itk::Point< double, ImageDimension >, ImageDimension > >
    PointerSourceType;
  PointerSourceType::Pointer source = PointerSourceType::New();

  EXERCISE_BASIC_OBJECT_METHODS( source, PhysicalPointImageSource, GenerateImageSource );

  int test = EXIT_SUCCESS;
  if ( atoi( argv[2] ) == 0 )
    {
    test =
      itkPhysicalPointImageSourceTest< itk::Image< itk::Point< double, ImageDimension >, ImageDimension > >(
      std::string( argv[1] ), size, spacing, origin, direction );
    }
  else if ( atoi( argv[2] ) == 1 )
    {
    test = itkPhysicalPointImageSourceTest< itk::VectorImage< double, ImageDimension > >(
      std::string( argv[1] ), size, spacing, origin, direction );
    }
  else if ( atoi( argv[2] ) == 2 )
    {
    spacing.Fill( 1.123 );
    origin.Fill( -0.987 );
    test =
      itkPhysicalPointImageSourceTest< itk::Image< itk::Point< float, ImageDimension>, ImageDimension > >(
      std::string( argv[1] ), size, spacing, origin, direction );
    }
  else
    {
    itk::SpacePrecisionType M[] = { std::cos( theta ), -std::sin( theta ),
      std::sin( theta ), std::cos( theta ) };

    direction = vnl_matrix< itk::SpacePrecisionType >( M, 2, 2 );
    test = itkPhysicalPointImageSourceTest< itk::VectorImage< float, ImageDimension > >(
      std::string( argv[1] ), size, spacing, origin, direction );
    }

  return test;
}
<|endoftext|>


<commit_before>#include "SDL.hh"
#include "Logger.hh"
using namespace RAGE;
using namespace RAGE::SDL;

Logger Log("Test Video");

//Defining UserInput
class MyUserInput : public Keyboard
{
public:

    virtual bool handleKeyEvent (const Sym &s, bool pressed)
    {
        bool res = false;
            switch( s.getKey() )
            {
                case KEscape:
                if (pressed==false)
                {
#ifdef DEBUG
                    Log << nl << "Quit requested !" << std::endl;
#endif

                    _quitRequested=true;
                    res=true;
                }
                break;
                case KF5:
                if (pressed==true)
                    App::getInstance().getWindow()->iconify();
                res = true;
                break;
				case KF6:
                if (pressed==true)
                    App::getInstance().getWindow()->setFullscreen(!App::getInstance().getWindow()->isFullscreen());
                res = true;
                break;
                default:
                res = false;
            }
        return res;
    }
};

class MyEngine : public DefaultEngine
{

public:

	RGBSurface loadedimage;
	Point imagepos;

	MyEngine( const std::string & imagefilename) : loadedimage(imagefilename),imagepos()
	{}

    virtual ~MyEngine(){}

    bool init(int width, int height)
	{
		imagepos.setx( (width - loadedimage.getWidth()) /2);
		imagepos.sety( (height - loadedimage.getHeight()) /2);
		return DefaultEngine::init(width,height);
	}

	bool resize(int width, int height)
	{
		imagepos.setx( (width - loadedimage.getWidth()) /2);
		imagepos.sety( (height - loadedimage.getHeight()) /2);
		return DefaultEngine::resize(width,height);
	}

	void render(VideoSurface & screen) const
    {
		screen.blit(loadedimage, imagepos );
		DefaultEngine::render(screen);
    }
};

//Main Program
int main(int argc, char** argv)
{

    Logger testlog("Test Log");

    //Setup example

    testlog << nl << " Enabling SDL Video... " << std::endl;
    App::getInstance().initVideo(false,false,true,false);

	App::getInstance().setName ("RAGE::SDL test - Video");

    testlog << nl << " Creating the User Interface... " << std::endl;
    //UI Creation
    MyUserInput ui;
    App::getInstance().getWindow()->getEventManager()->setKeyboard(&ui);

    App::getInstance().getWindow()->setBGColor(Color (64,0,0));

	//if argument we load the image in the test engine
	if ( argc > 1)
		App::getInstance().getWindow()->setEngine(new MyEngine(std::string(argv[1])));
	//otherwise we use the default engine only.

    if (! (App::getInstance().getWindow()->resetDisplay()))
    {
        testlog << nl << "Display Creation FAILED !"<< std::endl;
        exit(0);
    }
    else
    {
        App::getInstance().getWindow()->mainLoop(2);
		//think about automatic exit after timeout...
    }
    return 0;
}

<commit_msg>changed a bit the test to tests colorkey transparency also<commit_after>#include "SDL.hh"
#include "Logger.hh"
using namespace RAGE;
using namespace RAGE::SDL;

Logger Log("Test Video");

//Defining UserInput
class MyUserInput : public Keyboard
{
public:

    virtual bool handleKeyEvent (const Sym &s, bool pressed)
    {
        bool res = false;
            switch( s.getKey() )
            {
                case KEscape:
                if (pressed==false)
                {
#ifdef DEBUG
                    Log << nl << "Quit requested !" << std::endl;
#endif

                    _quitRequested=true;
                    res=true;
                }
                break;
                case KF5:
                if (pressed==true)
                    App::getInstance().getWindow()->iconify();
                res = true;
                break;
				case KF6:
                if (pressed==true)
                    App::getInstance().getWindow()->setFullscreen(!App::getInstance().getWindow()->isFullscreen());
                res = true;
                break;
                default:
                res = false;
            }
        return res;
    }
};

class MyEngine : public DefaultEngine
{

public:

	RGBSurface loadedimage;
	Point imagepos;

	MyEngine( const std::string & imagefilename) : loadedimage(imagefilename,Color(0,0,0)),imagepos()
	{}

    virtual ~MyEngine(){}

    bool init(int width, int height)
	{
		imagepos.setx( (width - loadedimage.getWidth()) /2);
		imagepos.sety( (height - loadedimage.getHeight()) /2);
		return DefaultEngine::init(width,height);
	}

	bool resize(int width, int height)
	{
		imagepos.setx( (width - loadedimage.getWidth()) /2);
		imagepos.sety( (height - loadedimage.getHeight()) /2);
		return DefaultEngine::resize(width,height);
	}

	void render(VideoSurface & screen) const
    {
		screen.blit(loadedimage, imagepos );
		DefaultEngine::render(screen);
    }
};

//Main Program
int main(int argc, char** argv)
{

    Logger testlog("Test Log");

    //Setup example

    testlog << nl << " Enabling SDL Video... " << std::endl;
    App::getInstance().initVideo(false,false,true,false);

	App::getInstance().setName ("RAGE::SDL test - Video");

    testlog << nl << " Creating the User Interface... " << std::endl;
    //UI Creation
    MyUserInput ui;
    App::getInstance().getWindow()->getEventManager()->setKeyboard(&ui);

    App::getInstance().getWindow()->setBGColor(Color (64,0,0));

	//if argument we load the image in the test engine
	if ( argc > 1)
		App::getInstance().getWindow()->setEngine(new MyEngine(std::string(argv[1])));
	//otherwise we use the default engine only.

    if (! (App::getInstance().getWindow()->resetDisplay()))
    {
        testlog << nl << "Display Creation FAILED !"<< std::endl;
        exit(0);
    }
    else
    {
        App::getInstance().getWindow()->mainLoop(2);
	//think about automatic exit after timeout...
    }
    return 0;
}

<|endoftext|>


<commit_before>#include <memory>
#include <riak/message.hxx>
#include <riak/object_access_parameters.hxx>
#include <riak/request_failure_parameters.hxx>
#include <riak/response_handlers.hxx>
#include <riak/sibling_resolution.hxx>
#include <riak/transport.hxx>

namespace boost {
    namespace asio { class io_service; }
}

//=============================================================================
namespace riak {
//=============================================================================

/*!
 * A client is the primary point at which a Riak store is accessed. As it is insufficient to
 * allocate such a client on the stack, such an object must be created using riak::make_client.
 */
class client
      : public std::enable_shared_from_this<client>
{
  public:
    /*! Defaults that allow total control to the database administrators. */
    static const object_access_parameters access_override_defaults;

    /*! A sane set of failure defaults; someone who doesn't care to tune their application won't touch these. */
    static const request_failure_parameters failure_defaults;

    /*! Yields the object access defaults with which this client was instantiated. */
    const object_access_parameters& object_access_override_defaults () const;

    void get_object (const key& bucket, const key& k, get_response_handler);
    // void put_object (const key& bucket, const key& k, put_response_handler);
    void delete_object (const key& bucket, const key& k, delete_response_handler h);

  private:
    transport::delivery_provider deliver_request_;
    sibling_resolution resolve_siblings_;
    const object_access_parameters access_overrides_;
    const request_failure_parameters request_failure_defaults_;
    boost::asio::io_service& ios_;

  protected:
    friend std::shared_ptr<client> make_client (
            transport::delivery_provider,
            sibling_resolution sr,
            boost::asio::io_service&,
            const request_failure_parameters&,
            const object_access_parameters&);

    client (transport::delivery_provider& d,
            sibling_resolution sr,
            boost::asio::io_service& ios,
            const request_failure_parameters& = failure_defaults,
            const object_access_parameters& = access_override_defaults);
};

/*!
 * \param dp will be used to deliver requests.
 * \param sr will be applied as a default to all cases of sibling resolution.
 * \param ios will be burdened with query transmission and reception events.
 * \return a new Riak client which is ready to access shared resources.
 */
std::shared_ptr<client> make_client (
        transport::delivery_provider dp,
        sibling_resolution sr,
        boost::asio::io_service& ios,
        const request_failure_parameters& = client::failure_defaults,
        const object_access_parameters& = client::access_override_defaults);

//=============================================================================
}   // namespace riak
//=============================================================================
<commit_msg>Removing dead code; put is implemented only after a get.<commit_after>#include <memory>
#include <riak/message.hxx>
#include <riak/object_access_parameters.hxx>
#include <riak/request_failure_parameters.hxx>
#include <riak/response_handlers.hxx>
#include <riak/sibling_resolution.hxx>
#include <riak/transport.hxx>

namespace boost {
    namespace asio { class io_service; }
}

//=============================================================================
namespace riak {
//=============================================================================

/*!
 * A client is the primary point at which a Riak store is accessed. As it is insufficient to
 * allocate such a client on the stack, such an object must be created using riak::make_client.
 */
class client
      : public std::enable_shared_from_this<client>
{
  public:
    /*! Defaults that allow total control to the database administrators. */
    static const object_access_parameters access_override_defaults;

    /*! A sane set of failure defaults; someone who doesn't care to tune their application won't touch these. */
    static const request_failure_parameters failure_defaults;

    /*! Yields the object access defaults with which this client was instantiated. */
    const object_access_parameters& object_access_override_defaults () const;

    void get_object (const key& bucket, const key& k, get_response_handler);
    void delete_object (const key& bucket, const key& k, delete_response_handler h);

  private:
    transport::delivery_provider deliver_request_;
    sibling_resolution resolve_siblings_;
    const object_access_parameters access_overrides_;
    const request_failure_parameters request_failure_defaults_;
    boost::asio::io_service& ios_;

  protected:
    friend std::shared_ptr<client> make_client (
            transport::delivery_provider,
            sibling_resolution sr,
            boost::asio::io_service&,
            const request_failure_parameters&,
            const object_access_parameters&);

    client (transport::delivery_provider& d,
            sibling_resolution sr,
            boost::asio::io_service& ios,
            const request_failure_parameters& = failure_defaults,
            const object_access_parameters& = access_override_defaults);
};

/*!
 * \param dp will be used to deliver requests.
 * \param sr will be applied as a default to all cases of sibling resolution.
 * \param ios will be burdened with query transmission and reception events.
 * \return a new Riak client which is ready to access shared resources.
 */
std::shared_ptr<client> make_client (
        transport::delivery_provider dp,
        sibling_resolution sr,
        boost::asio::io_service& ios,
        const request_failure_parameters& = client::failure_defaults,
        const object_access_parameters& = client::access_override_defaults);

//=============================================================================
}   // namespace riak
//=============================================================================
<|endoftext|>