<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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 "TestSenderAndReceiver.h"

#include <decaf/lang/Thread.h>
#include <decaf/util/Random.h>
#include <bitset>
#include <stdio.h>

using namespace std;
using namespace decaf;
using namespace decaf::lang;
using namespace decaf::util;
using namespace cmstemplate;

////////////////////////////////////////////////////////////////////////////////
void TestSenderAndReceiver::onMessage(const string& message) {
    int index = (int) message.find(";");
    if (index <= 0) {
        // i for invalid message
        printf("%c", 105);
    } else {
        // Smiley face for good message
        printf("%c", 2);
    }
}

////////////////////////////////////////////////////////////////////////////////
TestSenderAndReceiver::TestSenderAndReceiver(const string& url, const string& queueOrTopicName, bool isTopic,
                                             bool isDeliveryPersistent, int timeToLive, int receiveTimeout) :
    sender(), receiver(), senderThread(), closing(false), sendIndex(0), receiveIndex(0) {

    sender.reset(new Sender(url, queueOrTopicName, isTopic, isDeliveryPersistent, timeToLive));
    receiver.reset(new Receiver(url, queueOrTopicName, isTopic, receiveTimeout, true));

    ErrorCode errorCode = CMS_SUCCESS;

    receiver->registerMessageListener(this, errorCode);
}

////////////////////////////////////////////////////////////////////////////////
TestSenderAndReceiver::~TestSenderAndReceiver() {
    try {
        close();
    } catch(...) {}
}

////////////////////////////////////////////////////////////////////////////////
void TestSenderAndReceiver::initialize() {
    senderThread.reset(new Thread(this, "TestSenderAndReceiver"));
    senderThread->start();
}

////////////////////////////////////////////////////////////////////////////////
void TestSenderAndReceiver::run() {
    ErrorCode errorReturn;
    Random random;
    int i, j;

    j = (int) ((random.nextInt() * 50) / RAND_MAX);

    while (!closing) {
        std::stringstream str;
        str << sendIndex;

        string message;
        str >> message;
        message.append(";");

        // Add variable payload
        j = (int) ((rand() * 1024) / RAND_MAX);
        for (i = 0; i < j; i++) {
            message += string(1, (char) (65 + ((rand() * 26) / RAND_MAX)));
        }

        errorReturn = CMS_SUCCESS;
        sender->SendMessage(message, errorReturn);
        if (errorReturn == CMS_SUCCESS) {
            sendIndex++;
        } else {
            // Exclamation point for error
            printf("%c", 33);
        }

        // Sleep for up to 1 second between sends
        Thread::sleep(((random.nextInt() * 1000) / RAND_MAX));
    }
}

////////////////////////////////////////////////////////////////////////////////
void TestSenderAndReceiver::close() {
    if (!closing) {
        closing = true;

        try {
            if (senderThread.get() != NULL) {
                senderThread->join();
            }
        } catch (Exception& ex) {}

        try {
            if (receiver.get() != NULL) {
                receiver->close();
            }
        } catch (Exception& ex) {}
    }
}
<commit_msg>Use the Random class properly to get consistent behavior cross platform. <commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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 "TestSenderAndReceiver.h"

#include <decaf/lang/Thread.h>
#include <decaf/util/Random.h>
#include <bitset>
#include <stdio.h>

using namespace std;
using namespace decaf;
using namespace decaf::lang;
using namespace decaf::util;
using namespace cmstemplate;

////////////////////////////////////////////////////////////////////////////////
void TestSenderAndReceiver::onMessage(const string& message) {
    int index = (int) message.find(";");
    if (index <= 0) {
        // i for invalid message
        printf("%c", 105);
    } else {
        // Smiley face for good message
        printf("%c", 2);
    }
}

////////////////////////////////////////////////////////////////////////////////
TestSenderAndReceiver::TestSenderAndReceiver(const string& url, const string& queueOrTopicName, bool isTopic,
                                             bool isDeliveryPersistent, int timeToLive, int receiveTimeout) :
    sender(), receiver(), senderThread(), closing(false), sendIndex(0), receiveIndex(0) {

    sender.reset(new Sender(url, queueOrTopicName, isTopic, isDeliveryPersistent, timeToLive));
    receiver.reset(new Receiver(url, queueOrTopicName, isTopic, receiveTimeout, true));

    ErrorCode errorCode = CMS_SUCCESS;

    receiver->registerMessageListener(this, errorCode);
}

////////////////////////////////////////////////////////////////////////////////
TestSenderAndReceiver::~TestSenderAndReceiver() {
    try {
        close();
    } catch(...) {}
}

////////////////////////////////////////////////////////////////////////////////
void TestSenderAndReceiver::initialize() {
    senderThread.reset(new Thread(this, "TestSenderAndReceiver"));
    senderThread->start();
}

////////////////////////////////////////////////////////////////////////////////
void TestSenderAndReceiver::run() {
    ErrorCode errorReturn;
    Random random;
    int i, j;

    j = random.nextInt(100);

    while (!closing) {
        std::stringstream str;
        str << sendIndex;

        string message;
        str >> message;
        message.append(";");

        // Add variable payload
        j = (int) ((rand() * 1024) / RAND_MAX);
        for (i = 0; i < j; i++) {
            message += string(1, (char) (65 + ((rand() * 26) / RAND_MAX)));
        }

        errorReturn = CMS_SUCCESS;
        sender->SendMessage(message, errorReturn);
        if (errorReturn == CMS_SUCCESS) {
            sendIndex++;
        } else {
            // Exclamation point for error
            printf("%c", 33);
        }

        // Sleep for up to 1 second between sends
        Thread::sleep(random.nextInt(500));
    }
}

////////////////////////////////////////////////////////////////////////////////
void TestSenderAndReceiver::close() {
    if (!closing) {
        closing = true;

        try {
            if (senderThread.get() != NULL) {
                senderThread->join();
            }
        } catch (Exception& ex) {}

        try {
            if (receiver.get() != NULL) {
                receiver->close();
            }
        } catch (Exception& ex) {}
    }
}
<|endoftext|>


<commit_before>/*
   Copyright 2015 Brain Research Institute, Melbourne, Australia

   Written by Rami Tabbara, 18/02/15.

   This file is part of MRtrix.

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

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

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

*/

#include "gui/mrview/mode/lightbox.h"

namespace MR
{
namespace GUI
{
namespace MRView
{
namespace Mode
{

bool LightBox::show_grid_lines(true);
size_t LightBox::n_rows(3);
size_t LightBox::n_cols(4);
float LightBox::slice_focus_increment(1.f);

LightBox::LightBox(Window &parent) :
    Slice(parent),
    layout_is_dirty(true),
    current_slice_index((n_rows*n_cols) / 2),
    slices_proj_focusdelta(n_rows*n_cols, proj_focusdelta(projection, 0.f))
{
    image_changed_event();
}

void LightBox::set_rows(size_t rows)
{
    n_rows = rows;
    layout_is_dirty = true;
    updateGL();
}

void LightBox::set_cols(size_t cols)
{
    n_cols = cols;
    layout_is_dirty = true;
    updateGL();
}

void LightBox::set_slice_increment(float inc)
{
    slice_focus_increment = inc;
    update_slices_focusdelta();
    updateGL();
}

void LightBox::set_show_grid(bool show_grid)
{
    show_grid_lines = show_grid;
    updateGL();
}

inline void LightBox::update_layout()
{
    // Can't use std::vector resize() because Projection needs to be assignable
    slices_proj_focusdelta = std::vector<proj_focusdelta>(
                n_cols * n_rows,
                proj_focusdelta(projection, 0.f));
    set_current_slice_index((n_rows * n_cols) / 2);
    update_slices_focusdelta();

    frame_VB.clear();
    frame_VAO.clear();
}

void LightBox::set_current_slice_index(size_t slice_index)
{
    size_t prev_index = current_slice_index;
    current_slice_index = slice_index;

    if(prev_index != current_slice_index)
    {
        const Projection& slice_proj = slices_proj_focusdelta[current_slice_index].first;
        float focus_delta = slices_proj_focusdelta[current_slice_index].second;

        const Point<> slice_focus = move_in_out_displacement(focus_delta, slice_proj);
        set_focus(focus() + slice_focus);
        update_slices_focusdelta();
    }
}

void LightBox::update_slices_focusdelta()
{
    const int current_slice_index_int = current_slice_index;
    for(int i = 0, N = slices_proj_focusdelta.size(); i < N; ++i) {
        slices_proj_focusdelta[i].second =
                slice_focus_increment * (i - current_slice_index_int);
    }
}

void LightBox::draw_plane_primitive (int axis, Displayable::Shader& shader_program, Projection& with_projection)
{
    image()->render3D (shader_program, with_projection, with_projection.depth_of (focus()));
    render_tools (with_projection, false, axis, slice (axis));
}

void LightBox::paint(Projection&)
{
    // Setup OpenGL environment:
    gl::Disable (gl::BLEND);
    gl::Disable (gl::DEPTH_TEST);
    gl::DepthMask (gl::FALSE_);
    gl::ColorMask (gl::TRUE_, gl::TRUE_, gl::TRUE_, gl::TRUE_);

    GLint x = projection.x_position(), y = projection.y_position();
    GLint w = projection.width(), h = projection.height();
    GLint dw = w / n_cols, dh = h / n_rows;

    const Point<> orig_focus = window.focus();

    if(layout_is_dirty)
    {
        update_layout();
        layout_is_dirty = false;
    }

    size_t slice_idx = 0;
    for(size_t row = 0; row < n_rows; ++row)
    {
        for(size_t col = 0; col < n_cols; ++col, ++slice_idx)
        {
            Projection& slice_proj = slices_proj_focusdelta[slice_idx].first;

            // Place the first slice in the top-left corner
            slice_proj.set_viewport(window, x + dw * col, y + h - (dh * (row+1)), dw, dh);

            // We need to setup the modelview/proj matrices before we set the new focus
            // because move_in_out_displacement is reliant on MVP
            setup_draw(plane(), slice_proj);

            float focus_delta = slices_proj_focusdelta[slice_idx].second;
            Point<> slice_focus = move_in_out_displacement(focus_delta, slice_proj);
            set_focus(orig_focus + slice_focus);

            draw_plane_primitive(plane(), slice_shader, slice_proj);

            if(slice_idx == current_slice_index) {
                // Drawing plane may alter the depth test state
                // so need to ensure that crosshairs/labels will be visible
                gl::Disable (gl::DEPTH_TEST);
                draw_crosshairs(slice_proj);
                draw_orientation_labels(slice_proj);
            }
        }
    }

    // Restore view state
    set_focus(orig_focus);
    projection.set_viewport(window, x, y, w, h);

    // Users may want to screen capture without grid lines
    if(show_grid_lines) {
        gl::Disable(gl::DEPTH_TEST);
        draw_grid();
    }
}

void LightBox::draw_grid()
{
    if(n_cols < 1 && n_rows < 1)
        return;

    size_t num_points = ((n_rows - 1) + (n_cols - 1)) * 4;

    GL::mat4 MV = GL::identity();
    GL::mat4 P = GL::ortho (0, width(), 0, height(), -1.0, 1.0);
    projection.set (MV, P);

    gl::LineWidth (2.0);

    if (!frame_VB || !frame_VAO) {
        frame_VB.gen();
        frame_VAO.gen();

        frame_VB.bind (gl::ARRAY_BUFFER);
        frame_VAO.bind();

        gl::EnableVertexAttribArray (0);
        gl::VertexAttribPointer (0, 2, gl::FLOAT, gl::FALSE_, 0, (void*)0);

        GLfloat data[num_points];

        // Grid line stride
        float x_inc = 2.f / n_cols;
        float y_inc = 2.f / n_rows;

        size_t pt_idx = 0;
        // Row grid lines
        for(size_t row = 1; row < n_rows; ++row, pt_idx += 4)
        {
            float y_pos = (y_inc * row) - 1.f;
            data[pt_idx] = -1.f;
            data[pt_idx+1] = y_pos;
            data[pt_idx+2] = 1.f;
            data[pt_idx+3] = y_pos;
        }

        // Column grid lines
        for(size_t col = 1; col < n_cols; ++col, pt_idx += 4)
        {
            float x_pos = (x_inc * col) - 1.f;
            data[pt_idx] = x_pos;
            data[pt_idx+1] = -1.f;
            data[pt_idx+2] = x_pos;
            data[pt_idx+3] = 1.f;
        }

        gl::BufferData (gl::ARRAY_BUFFER, sizeof(data), data, gl::STATIC_DRAW);
    }
    else
        frame_VAO.bind();

    if (!frame_program) {
        GL::Shader::Vertex vertex_shader (
                    "layout(location=0) in vec2 pos;\n"
                    "void main () {\n"
                    "  gl_Position = vec4 (pos, 0.0, 1.0);\n"
                    "}\n");
        GL::Shader::Fragment fragment_shader (
                    "out vec3 color;\n"
                    "void main () {\n"
                    "  color = vec3 (0.1);\n"
                    "}\n");
        frame_program.attach (vertex_shader);
        frame_program.attach (fragment_shader);
        frame_program.link();
    }

    frame_program.start();
    gl::DrawArrays (gl::LINES, 0, num_points / 2);
    frame_program.stop();
}

void LightBox::mouse_press_event()
{
    GLint x = projection.x_position(), y = projection.y_position();
    GLint w = projection.width(), h = projection.height();
    GLint dw = w / n_cols, dh = h / n_rows;

    const auto& mouse_pos = window.mouse_position();

    size_t col = (mouse_pos.x() - x) / dw;
    size_t row = n_rows - (mouse_pos.y() - y) / dh - 1;

    if(col < n_cols && row < n_rows) {
        set_current_slice_index(slice_index(row, col));
    }
}

// Called when we get a mouse move event
void LightBox::set_focus_event()
{
    Base::set_focus_event();
    mouse_press_event();
}

void LightBox::image_changed_event()
{
    Base::image_changed_event();

    if(image())
    {
        const auto& header = image()->header();
        float slice_inc = std::pow (header.vox(0)*header.vox(1)*header.vox(2), 1.f/3.f);
        set_slice_increment(slice_inc);
        emit slice_increment_reset();
    }
}

}
}
}
}
<commit_msg>LightBox: Changing default grid dimensions to 3 x 5<commit_after>/*
   Copyright 2015 Brain Research Institute, Melbourne, Australia

   Written by Rami Tabbara, 18/02/15.

   This file is part of MRtrix.

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

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

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

*/

#include "gui/mrview/mode/lightbox.h"

namespace MR
{
namespace GUI
{
namespace MRView
{
namespace Mode
{

bool LightBox::show_grid_lines(true);
size_t LightBox::n_rows(3);
size_t LightBox::n_cols(5);
float LightBox::slice_focus_increment(1.f);

LightBox::LightBox(Window &parent) :
    Slice(parent),
    layout_is_dirty(true),
    current_slice_index((n_rows*n_cols) / 2),
    slices_proj_focusdelta(n_rows*n_cols, proj_focusdelta(projection, 0.f))
{
    image_changed_event();
}

void LightBox::set_rows(size_t rows)
{
    n_rows = rows;
    layout_is_dirty = true;
    updateGL();
}

void LightBox::set_cols(size_t cols)
{
    n_cols = cols;
    layout_is_dirty = true;
    updateGL();
}

void LightBox::set_slice_increment(float inc)
{
    slice_focus_increment = inc;
    update_slices_focusdelta();
    updateGL();
}

void LightBox::set_show_grid(bool show_grid)
{
    show_grid_lines = show_grid;
    updateGL();
}

inline void LightBox::update_layout()
{
    // Can't use std::vector resize() because Projection needs to be assignable
    slices_proj_focusdelta = std::vector<proj_focusdelta>(
                n_cols * n_rows,
                proj_focusdelta(projection, 0.f));
    set_current_slice_index((n_rows * n_cols) / 2);
    update_slices_focusdelta();

    frame_VB.clear();
    frame_VAO.clear();
}

void LightBox::set_current_slice_index(size_t slice_index)
{
    size_t prev_index = current_slice_index;
    current_slice_index = slice_index;

    if(prev_index != current_slice_index)
    {
        const Projection& slice_proj = slices_proj_focusdelta[current_slice_index].first;
        float focus_delta = slices_proj_focusdelta[current_slice_index].second;

        const Point<> slice_focus = move_in_out_displacement(focus_delta, slice_proj);
        set_focus(focus() + slice_focus);
        update_slices_focusdelta();
    }
}

void LightBox::update_slices_focusdelta()
{
    const int current_slice_index_int = current_slice_index;
    for(int i = 0, N = slices_proj_focusdelta.size(); i < N; ++i) {
        slices_proj_focusdelta[i].second =
                slice_focus_increment * (i - current_slice_index_int);
    }
}

void LightBox::draw_plane_primitive (int axis, Displayable::Shader& shader_program, Projection& with_projection)
{
    image()->render3D (shader_program, with_projection, with_projection.depth_of (focus()));
    render_tools (with_projection, false, axis, slice (axis));
}

void LightBox::paint(Projection&)
{
    // Setup OpenGL environment:
    gl::Disable (gl::BLEND);
    gl::Disable (gl::DEPTH_TEST);
    gl::DepthMask (gl::FALSE_);
    gl::ColorMask (gl::TRUE_, gl::TRUE_, gl::TRUE_, gl::TRUE_);

    GLint x = projection.x_position(), y = projection.y_position();
    GLint w = projection.width(), h = projection.height();
    GLint dw = w / n_cols, dh = h / n_rows;

    const Point<> orig_focus = window.focus();

    if(layout_is_dirty)
    {
        update_layout();
        layout_is_dirty = false;
    }

    size_t slice_idx = 0;
    for(size_t row = 0; row < n_rows; ++row)
    {
        for(size_t col = 0; col < n_cols; ++col, ++slice_idx)
        {
            Projection& slice_proj = slices_proj_focusdelta[slice_idx].first;

            // Place the first slice in the top-left corner
            slice_proj.set_viewport(window, x + dw * col, y + h - (dh * (row+1)), dw, dh);

            // We need to setup the modelview/proj matrices before we set the new focus
            // because move_in_out_displacement is reliant on MVP
            setup_draw(plane(), slice_proj);

            float focus_delta = slices_proj_focusdelta[slice_idx].second;
            Point<> slice_focus = move_in_out_displacement(focus_delta, slice_proj);
            set_focus(orig_focus + slice_focus);

            draw_plane_primitive(plane(), slice_shader, slice_proj);

            if(slice_idx == current_slice_index) {
                // Drawing plane may alter the depth test state
                // so need to ensure that crosshairs/labels will be visible
                gl::Disable (gl::DEPTH_TEST);
                draw_crosshairs(slice_proj);
                draw_orientation_labels(slice_proj);
            }
        }
    }

    // Restore view state
    set_focus(orig_focus);
    projection.set_viewport(window, x, y, w, h);

    // Users may want to screen capture without grid lines
    if(show_grid_lines) {
        gl::Disable(gl::DEPTH_TEST);
        draw_grid();
    }
}

void LightBox::draw_grid()
{
    if(n_cols < 1 && n_rows < 1)
        return;

    size_t num_points = ((n_rows - 1) + (n_cols - 1)) * 4;

    GL::mat4 MV = GL::identity();
    GL::mat4 P = GL::ortho (0, width(), 0, height(), -1.0, 1.0);
    projection.set (MV, P);

    gl::LineWidth (2.0);

    if (!frame_VB || !frame_VAO) {
        frame_VB.gen();
        frame_VAO.gen();

        frame_VB.bind (gl::ARRAY_BUFFER);
        frame_VAO.bind();

        gl::EnableVertexAttribArray (0);
        gl::VertexAttribPointer (0, 2, gl::FLOAT, gl::FALSE_, 0, (void*)0);

        GLfloat data[num_points];

        // Grid line stride
        float x_inc = 2.f / n_cols;
        float y_inc = 2.f / n_rows;

        size_t pt_idx = 0;
        // Row grid lines
        for(size_t row = 1; row < n_rows; ++row, pt_idx += 4)
        {
            float y_pos = (y_inc * row) - 1.f;
            data[pt_idx] = -1.f;
            data[pt_idx+1] = y_pos;
            data[pt_idx+2] = 1.f;
            data[pt_idx+3] = y_pos;
        }

        // Column grid lines
        for(size_t col = 1; col < n_cols; ++col, pt_idx += 4)
        {
            float x_pos = (x_inc * col) - 1.f;
            data[pt_idx] = x_pos;
            data[pt_idx+1] = -1.f;
            data[pt_idx+2] = x_pos;
            data[pt_idx+3] = 1.f;
        }

        gl::BufferData (gl::ARRAY_BUFFER, sizeof(data), data, gl::STATIC_DRAW);
    }
    else
        frame_VAO.bind();

    if (!frame_program) {
        GL::Shader::Vertex vertex_shader (
                    "layout(location=0) in vec2 pos;\n"
                    "void main () {\n"
                    "  gl_Position = vec4 (pos, 0.0, 1.0);\n"
                    "}\n");
        GL::Shader::Fragment fragment_shader (
                    "out vec3 color;\n"
                    "void main () {\n"
                    "  color = vec3 (0.1);\n"
                    "}\n");
        frame_program.attach (vertex_shader);
        frame_program.attach (fragment_shader);
        frame_program.link();
    }

    frame_program.start();
    gl::DrawArrays (gl::LINES, 0, num_points / 2);
    frame_program.stop();
}

void LightBox::mouse_press_event()
{
    GLint x = projection.x_position(), y = projection.y_position();
    GLint w = projection.width(), h = projection.height();
    GLint dw = w / n_cols, dh = h / n_rows;

    const auto& mouse_pos = window.mouse_position();

    size_t col = (mouse_pos.x() - x) / dw;
    size_t row = n_rows - (mouse_pos.y() - y) / dh - 1;

    if(col < n_cols && row < n_rows) {
        set_current_slice_index(slice_index(row, col));
    }
}

// Called when we get a mouse move event
void LightBox::set_focus_event()
{
    Base::set_focus_event();
    mouse_press_event();
}

void LightBox::image_changed_event()
{
    Base::image_changed_event();

    if(image())
    {
        const auto& header = image()->header();
        float slice_inc = std::pow (header.vox(0)*header.vox(1)*header.vox(2), 1.f/3.f);
        set_slice_increment(slice_inc);
        emit slice_increment_reset();
    }
}

}
}
}
}
<|endoftext|>


<commit_before>//shit to do
//Do checks to make sure it doesn't crash (make sure creators exists, that the resource creation didn't fail)
//Make AddType Template in the .inl file//And creators isn't attached to anything. You're supposed to be initialising the static creators in ResourceFactory.
//And finally, you don't need to put static in definitions

////////////////////////////////////////////////////////////
//
// The MIT License (MIT)
//
// Copyright (c) 2014 stevehalliwell
//
// 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.
//
////////////////////////////////////////////////////////////

#ifndef RESOURCE_FACTORY_HPP
#define RESOURCE_FACTORY_HPP

////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <ResourceMananger/BaseResource.hpp>
#include <ResourceManager/ResourceCreator.hpp>
#include <ResourceManager/ResourceManager.hpp>
#include <map>

////////////////////////////////////////////////////////////
/// \breif Resource Factory that serves as the creation location
///  for all resources
///
////////////////////////////////////////////////////////////

namespace rm
{

class ResourceFactory
{
 public:

    ////////////////////////////////////////////////////////////
    /// \brief Looks up the ResouceCreatorInterface needed to create
    /// The resource based on the type and calls create on it to make a
    /// A new resource of the specified type
    ///
    /// \parma string to path location of the file and string for file
    /// Type to determine how it is loaded
    ///
    /// \return Shared Pointer of the newly Created Resouce
    ///
    ////////////////////////////////////////////////////////////
    static std::shared_ptr<BaseResource> createResource(const std::string& path, const std::string& type);

	////////////////////////////////////////////////////////////
    /// \brief Creates a new ResouceCreatorInterface based on the passed
	/// resource type. Gets the type name from the resourceType class and stores
	/// The created resourceCreatorInterface is stored in creators
    ///
    ////////////////////////////////////////////////////////////
    template <class T>
    static void addType();

 private:

	////////////////////////////////////////////////////////////
    /// \brief A Strandard Map to hold all the resource type
    /// classes that define how they are created
    ///
    /// Example: It could hold a image ResourceCreatorInterface
    /// that will define how to create an image
    ///
    ////////////////////////////////////////////////////////////
    std::map<std::string, std::shared_ptr<ResourceCreatorInterface>> creators;
};

}

#endif //RESOURCE_FACTORY_HPP<commit_msg>Fixed some Resource Factory typos<commit_after>//shit to do
//Do checks to make sure it doesn't crash (make sure creators exists, that the resource creation didn't fail)
//Make AddType Template in the .inl file//And creators isn't attached to anything. You're supposed to be initialising the static creators in ResourceFactory.
//And finally, you don't need to put static in definitions

////////////////////////////////////////////////////////////
//
// The MIT License (MIT)
//
// Copyright (c) 2014 stevehalliwell
//
// 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.
//
////////////////////////////////////////////////////////////

#ifndef RESOURCE_FACTORY_HPP
#define RESOURCE_FACTORY_HPP

////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <ResourceManager/BaseResource.hpp>
#include <ResourceManager/ResourceCreator.hpp>
#include <ResourceManager/ResourceManager.hpp>
#include <map>

////////////////////////////////////////////////////////////
/// \breif Resource Factory that serves as the creation location
///  for all resources
///
////////////////////////////////////////////////////////////

namespace rm
{

class ResourceFactory
{
 public:

    ////////////////////////////////////////////////////////////
    /// \brief Looks up the ResouceCreatorInterface needed to create
    /// The resource based on the type and calls create on it to make a
    /// A new resource of the specified type
    ///
    /// \parma string to path location of the file and string for file
    /// Type to determine how it is loaded
    ///
    /// \return Shared Pointer of the newly Created Resource
    ///
    ////////////////////////////////////////////////////////////
    static std::shared_ptr<BaseResource> createResource(const std::string& path, const std::string& type);

	////////////////////////////////////////////////////////////
    /// \brief Creates a new ResouceCreatorInterface based on the passed
	/// resource type. Gets the type name from the resourceType class and stores
	/// The created resourceCreatorInterface is stored in creators
    ///
    ////////////////////////////////////////////////////////////
    template <class T>
    static void addType();

 private:

	////////////////////////////////////////////////////////////
    /// \brief A Standard Map to hold all the resource type
    /// classes that define how they are created
    ///
    /// Example: It could hold a image ResourceCreatorInterface
    /// that will define how to create an image
    ///
    ////////////////////////////////////////////////////////////
    std::map<std::string, std::shared_ptr<ResourceCreatorInterface>> creators;
};

}

#endif //RESOURCE_FACTORY_HPP<|endoftext|>


<commit_before>#ifndef AUTOCHECK_GENERATOR_COMBINATORS_HPP
#define AUTOCHECK_GENERATOR_COMBINATORS_HPP

#include <type_traits>
#include <limits>

namespace autocheck {

  namespace detail {

    /* Wrappers used by combinators. */

    template <typename Func, typename Gen>
    class mapped_generator {
      public:
        typedef
          typename std::result_of<
            Func(typename Gen::result_type&&, size_t)
          >::type
          result_type;

      private:
        Func func;
        Gen  gen;

      public:
        mapped_generator(const Func& func, const Gen& gen) :
          func(func), gen(gen) {}

        result_type operator() (size_t size = 0) {
          return func(gen(size), size);
        }
    };

    template <typename Pred, typename Gen>
    class filtered_generator {
      public:
        typedef typename Gen::result_type result_type;

      private:
        Pred pred;
        Gen  gen;

      public:
        filtered_generator(const Pred& pred, const Gen& gen) :
          pred(pred), gen(gen) {}

        result_type operator() (size_t size = 0) {
          while (true) {
            result_type rv(gen(size));
            if (pred(rv)) return rv;
          }
        }
    };

    template <typename Resize, typename Gen>
    class resized_generator {
      public:
        typedef typename Gen::result_type result_type;

      private:
        Resize resizer;
        Gen    gen;

      public:
        resized_generator(const Resize& resizer, const Gen& gen) :
          resizer(resizer), gen(gen) {}

        result_type operator() (size_t size = 0) {
          return gen(resizer(size));
        }
    };

    template <typename Gen>
    class fixed_size_generator {
      private:
        size_t size;
        Gen    gen;

      public:
        typedef typename Gen::result_type result_type;

        fixed_size_generator(size_t size, const Gen& gen) :
          size(size), gen(gen) {}

        result_type operator() (size_t = 0) {
          return gen(size);
        }
    };

  }

  /* Generator combinators. */

  template <typename Func, typename Gen>
  detail::mapped_generator<Func, Gen> map(const Func& func, const Gen& gen) {
    return detail::mapped_generator<Func, Gen>(func, gen);
  }

  template <typename Pred, typename Gen>
  detail::filtered_generator<Pred, Gen> such_that(const Pred& pred,
      const Gen& gen)
  {
    return detail::filtered_generator<Pred, Gen>(pred, gen);
  }

  template <typename Resize, typename Gen>
  detail::resized_generator<Resize, Gen> resize(const Resize& resizer,
      const Gen& gen)
  {
    return detail::resized_generator<Resize, Gen>(resizer, gen);
  }

  template <typename Gen>
  detail::fixed_size_generator<Gen> fix(size_t size, const Gen& gen) {
    return detail::fixed_size_generator<Gen>(size, gen);
  }

}

#endif

<commit_msg>Removed superfluous header.<commit_after>#ifndef AUTOCHECK_GENERATOR_COMBINATORS_HPP
#define AUTOCHECK_GENERATOR_COMBINATORS_HPP

#include <type_traits>

namespace autocheck {

  namespace detail {

    /* Wrappers used by combinators. */

    template <typename Func, typename Gen>
    class mapped_generator {
      public:
        typedef
          typename std::result_of<
            Func(typename Gen::result_type&&, size_t)
          >::type
          result_type;

      private:
        Func func;
        Gen  gen;

      public:
        mapped_generator(const Func& func, const Gen& gen) :
          func(func), gen(gen) {}

        result_type operator() (size_t size = 0) {
          return func(gen(size), size);
        }
    };

    template <typename Pred, typename Gen>
    class filtered_generator {
      public:
        typedef typename Gen::result_type result_type;

      private:
        Pred pred;
        Gen  gen;

      public:
        filtered_generator(const Pred& pred, const Gen& gen) :
          pred(pred), gen(gen) {}

        result_type operator() (size_t size = 0) {
          while (true) {
            result_type rv(gen(size));
            if (pred(rv)) return rv;
          }
        }
    };

    template <typename Resize, typename Gen>
    class resized_generator {
      public:
        typedef typename Gen::result_type result_type;

      private:
        Resize resizer;
        Gen    gen;

      public:
        resized_generator(const Resize& resizer, const Gen& gen) :
          resizer(resizer), gen(gen) {}

        result_type operator() (size_t size = 0) {
          return gen(resizer(size));
        }
    };

    template <typename Gen>
    class fixed_size_generator {
      private:
        size_t size;
        Gen    gen;

      public:
        typedef typename Gen::result_type result_type;

        fixed_size_generator(size_t size, const Gen& gen) :
          size(size), gen(gen) {}

        result_type operator() (size_t = 0) {
          return gen(size);
        }
    };

  }

  /* Generator combinators. */

  template <typename Func, typename Gen>
  detail::mapped_generator<Func, Gen> map(const Func& func, const Gen& gen) {
    return detail::mapped_generator<Func, Gen>(func, gen);
  }

  template <typename Pred, typename Gen>
  detail::filtered_generator<Pred, Gen> such_that(const Pred& pred,
      const Gen& gen)
  {
    return detail::filtered_generator<Pred, Gen>(pred, gen);
  }

  template <typename Resize, typename Gen>
  detail::resized_generator<Resize, Gen> resize(const Resize& resizer,
      const Gen& gen)
  {
    return detail::resized_generator<Resize, Gen>(resizer, gen);
  }

  template <typename Gen>
  detail::fixed_size_generator<Gen> fix(size_t size, const Gen& gen) {
    return detail::fixed_size_generator<Gen>(size, gen);
  }

}

#endif

<|endoftext|>


<commit_before>/*
 * Copyright 2007-2018 Content Management AG
 * All rights reserved.
 *
 * author: Max Kellermann <mk@cm4all.com>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * - Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *
 * - Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the
 * distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
 * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * Which headers should be forwarded to/from remote HTTP servers?
 */

#pragma once

#include "http/Status.h"

#include <beng-proxy/Headers.hxx>

struct HeaderForwardSettings {
    BengProxy::HeaderForwardMode modes[size_t(BengProxy::HeaderGroup::MAX)];

    HeaderForwardSettings() = default;

    static constexpr HeaderForwardSettings AllNo() noexcept {
        static_assert(BengProxy::HeaderForwardMode::NO == BengProxy::HeaderForwardMode(),
                      "Wrong default value");

        return HeaderForwardSettings{BengProxy::HeaderForwardMode::NO};
    }

    constexpr auto &operator[](BengProxy::HeaderGroup group) noexcept {
        return modes[size_t(group)];
    }

    constexpr const auto &operator[](BengProxy::HeaderGroup group) const noexcept {
        return modes[size_t(group)];
    }
};

struct pool;
class StringMap;
struct RealmSession;

/**
 * @param exclude_host suppress the "Host" header?  The "Host" request
 * header must not be forwarded to another HTTP server, because we
 * need to generate a new one
 * @param forward_range forward the "Range" request header?
 */
StringMap
forward_request_headers(struct pool &pool, const StringMap &src,
                        const char *local_host, const char *remote_host,
                        bool exclude_host,
                        bool with_body, bool forward_charset,
                        bool forward_encoding,
                        bool forward_range,
                        const HeaderForwardSettings &settings,
                        const char *session_cookie,
                        const RealmSession *session,
                        const char *host_and_port, const char *uri) noexcept;

StringMap
forward_response_headers(struct pool &pool, http_status_t status,
                         const StringMap &src,
                         const char *local_host,
                         const char *session_cookie,
                         const char *(*relocate)(const char *uri, void *ctx),
                         void *relocate_ctx,
                         const HeaderForwardSettings &settings) noexcept;

/**
 * Generate a X-CM4all-BENG-User header (if available)_.
 */
void
forward_reveal_user(StringMap &headers,
                    const RealmSession *session) noexcept;
<commit_msg>bp/ForwardHeaders: add `using` declarations<commit_after>/*
 * Copyright 2007-2018 Content Management AG
 * All rights reserved.
 *
 * author: Max Kellermann <mk@cm4all.com>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * - Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *
 * - Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the
 * distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
 * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * Which headers should be forwarded to/from remote HTTP servers?
 */

#pragma once

#include "http/Status.h"

#include <beng-proxy/Headers.hxx>

struct HeaderForwardSettings {
    using Group = BengProxy::HeaderGroup;
    using Mode = BengProxy::HeaderForwardMode;

    Mode modes[size_t(Group::MAX)];

    HeaderForwardSettings() = default;

    static constexpr HeaderForwardSettings AllNo() noexcept {
        static_assert(Mode::NO == Mode(),
                      "Wrong default value");

        return HeaderForwardSettings{Mode::NO};
    }

    constexpr auto &operator[](Group group) noexcept {
        return modes[size_t(group)];
    }

    constexpr const auto &operator[](Group group) const noexcept {
        return modes[size_t(group)];
    }
};

struct pool;
class StringMap;
struct RealmSession;

/**
 * @param exclude_host suppress the "Host" header?  The "Host" request
 * header must not be forwarded to another HTTP server, because we
 * need to generate a new one
 * @param forward_range forward the "Range" request header?
 */
StringMap
forward_request_headers(struct pool &pool, const StringMap &src,
                        const char *local_host, const char *remote_host,
                        bool exclude_host,
                        bool with_body, bool forward_charset,
                        bool forward_encoding,
                        bool forward_range,
                        const HeaderForwardSettings &settings,
                        const char *session_cookie,
                        const RealmSession *session,
                        const char *host_and_port, const char *uri) noexcept;

StringMap
forward_response_headers(struct pool &pool, http_status_t status,
                         const StringMap &src,
                         const char *local_host,
                         const char *session_cookie,
                         const char *(*relocate)(const char *uri, void *ctx),
                         void *relocate_ctx,
                         const HeaderForwardSettings &settings) noexcept;

/**
 * Generate a X-CM4all-BENG-User header (if available)_.
 */
void
forward_reveal_user(StringMap &headers,
                    const RealmSession *session) noexcept;
<|endoftext|>


<commit_before><commit_msg>proper -l flag formatting. currently trying to repair -laR flag<commit_after><|endoftext|>


<commit_before>#include "TGLViewer.h"

namespace Alieve {
class MUONData;
class Event;
}

Alieve::MUONData* g_muon_data = 0;
Alieve::Event*    g_muon_last_event = 0;

Int_t g_currentEvent = -1;
Bool_t g_fromRaw = kFALSE;

void MUON_digits(Bool_t fromRaw = kFALSE, Bool_t showTracks = kTRUE)
{

  TTree* dt = 0;

  if (Alieve::gEvent == 0) {
    printf("No alieve event: use alieve_init(...) \n");
    return;
  }

  if (g_currentEvent == Alieve::gEvent->GetEventId()) {
    if (g_fromRaw == fromRaw) {
      printf("Same event... \n");
      return;
    } else {
      if (g_fromRaw) {
	printf("Same event with digits.\n");
	Alieve::gEvent->GotoEvent(g_currentEvent);
      } else {
	printf("Same event with raw.\n");
	Alieve::gEvent->GotoEvent(g_currentEvent);
      }
    }
  }

  g_fromRaw = fromRaw;

  AliRunLoader* rl =  Alieve::Event::AssertRunLoader();
  TString fileName = rl->GetFileName();
  Int_t length = fileName.Length();
  fileName.Resize(length-11);
  fileName.Append("raw.root");

  g_muon_data = new Alieve::MUONData;

  if (!fromRaw) {
    rl->LoadDigits("MUON");
    dt = rl->GetTreeD("MUON", false);
    if (dt == 0) {
      cout << "No digits produced!" << endl;
    } else {
      cout << "Display aliroot digits!" << endl;
      g_muon_data->LoadDigits(dt);
    }
  } else {
    if (gSystem->AccessPathName(fileName.Data(),kFileExists)) {
      cout << "No raw data produced!" << endl;
    } else {
      cout << "Display raw digits!" << endl;
      g_muon_data->LoadRaw(fileName.Data());
    }
  }

  g_muon_last_event = Alieve::gEvent;

  g_currentEvent = g_muon_last_event->GetEventId();

  gStyle->SetPalette(1, 0);

  gReve->DisableRedraw();

  Reve::RenderElementList* l = new Reve::RenderElementList("MUONChambers");
  l->SetTitle("MUON chambers");
  l->SetMainColor(Color_t(2));
  gReve->AddRenderElement(l);

  for (Int_t ic = 0; ic < 14; ic++) {

    Alieve::MUONChamber* mucha = new Alieve::MUONChamber();

    mucha->SetFrameColor(2);
    mucha->SetChamberID(ic);
    mucha->SetDataSource(g_muon_data);

    gReve->AddRenderElement(l,mucha);

  }

  if (showTracks) MUON_tracks();

  gReve->EnableRedraw();

  TGLViewer* view = dynamic_cast<TGLViewer*>(gReve->GetGLCanvas()->GetViewer3D());
  view->ResetCamerasAfterNextUpdate();
  gReve->GetGLCanvas()->Modified();
  gReve->GetGLCanvas()->Update();

}

//_____________________________________________________________________________
void MUON_tracks() {

  AliRunLoader* rl =  Alieve::Event::AssertRunLoader();
  rl->LoadTracks("MUON");
  TTree* tt = rl->GetTreeT("MUON", false);

  TClonesArray *tracks = 0;
  tt->SetBranchAddress("MUONTrack",&tracks);
  tt->GetEntry(0);

  Int_t ntracks = tracks->GetEntriesFast();
  //printf("Found %d tracks. \n",ntracks);

  Reve::TrackList* lt = new Reve::TrackList("M-Tracks");
  lt->SetMainColor(Color_t(6));

  gReve->AddRenderElement(lt);

  TMatrixD smatrix(2,2);
  TMatrixD sums(2,1);
  TMatrixD res(2,1);

  Float_t xRec, xRec0;
  Float_t yRec, yRec0;
  Float_t zRec, zRec0;

  Float_t zg[4] = { -1603.5, -1620.5, -1703.5, -1720.5 };

  AliMUONTrack *mt;
  Reve::RecTrack  rt;
  Int_t count;
  for (Int_t n = 0; n < ntracks; n++) {

    count = 0;

    mt = (AliMUONTrack*) tracks->At(n);

    //printf("Match trigger %d \n",mt->GetMatchTrigger());

    rt.label = n;

    Reve::Track* track = new Reve::Track(&rt, lt->GetRnrStyle());

    //PH The line below is replaced waiting for a fix in Root
    //PH which permits to use variable siza arguments in CINT
    //PH on some platforms (alphalinuxgcc, solariscc5, etc.)
    char form[1000];
    if (mt->GetMatchTrigger()) {
      //PH      track->SetName(Form("MUONTrack %2d (MT)", rt.label));
      sprintf(form,"MUONTrack %2d (MT)", rt.label);
      track->SetName(form);
      track->SetLineColor(7);
    } else {
      //PH      track->SetName(Form("MUONTrack %2d     ", rt.label));
      sprintf(form,"MUONTrack %2d     ", rt.label);
      track->SetName(form);
      track->SetLineColor(6);
    }

    AliMUONTrackParam *trackParam = mt->GetTrackParamAtVertex();
    xRec0  = trackParam->GetNonBendingCoor();
    yRec0  = trackParam->GetBendingCoor();
    zRec0  = trackParam->GetZ();

    track->SetPoint(count,xRec0,yRec0,zRec0);
    count++;

    Float_t xr[20], yr[20], zr[20];
    for (Int_t i = 0; i < 10; i++) xr[i]=yr[i]=zr[i]=0.0;

    Int_t nTrackHits = mt->GetNTrackHits();
    //printf("Nhits = %d \n",nTrackHits);
    TClonesArray* trackParamAtHit;
    for (Int_t iHit = 0; iHit < nTrackHits; iHit++){
      trackParamAtHit = mt->GetTrackParamAtHit();
      trackParam = (AliMUONTrackParam*) trackParamAtHit->At(iHit);
      xRec  = trackParam->GetNonBendingCoor();
      yRec  = trackParam->GetBendingCoor();
      zRec  = trackParam->GetZ();

      //printf("Hit %d x %f y %f z %f \n",iHit,xRec,yRec,zRec);

      xr[iHit] = xRec;
      yr[iHit] = yRec;
      zr[iHit] = zRec;

      track->SetPoint(count,xRec,yRec,zRec);
      count++;

    }

    Float_t xrc[20], yrc[20], zrc[20];
    Int_t nrc = 0;
    if (mt->GetMatchTrigger() && 1) {

      for (Int_t i = 0; i < nTrackHits; i++) {
	if (TMath::Abs(zr[i]) > 1000.0) {
	  //printf("Hit %d x %f y %f z %f \n",iHit,xr[i],yr[i],zr[i]);
	  xrc[nrc] = xr[i];
	  yrc[nrc] = yr[i];
	  zrc[nrc] = zr[i];
	  nrc++;
	}
      }

      Double_t xv, yv;
      Float_t ax, bx, ay, by;

      if (nrc < 2) continue;

      // fit x-z
      smatrix.Zero();
      sums.Zero();
      for (Int_t i = 0; i < nrc; i++) {
	xv = (Double_t)zrc[i];
	yv = (Double_t)xrc[i];
	//printf("x-z: xv %f yv %f \n",xv,yv);
	smatrix(0,0) += 1.0;
	smatrix(1,1) += xv*xv;
	smatrix(0,1) += xv;
	smatrix(1,0) += xv;
	sums(0,0)    += yv;
	sums(1,0)    += xv*yv;
      }
      res = smatrix.Invert() * sums;
      ax = res(0,0);
      bx = res(1,0);

      // fit y-z
      smatrix.Zero();
      sums.Zero();
      for (Int_t i = 0; i < nrc; i++) {
	xv = (Double_t)zrc[i];
	yv = (Double_t)yrc[i];
	//printf("y-z: xv %f yv %f \n",xv,yv);
	smatrix(0,0) += 1.0;
	smatrix(1,1) += xv*xv;
	smatrix(0,1) += xv;
	smatrix(1,0) += xv;
	sums(0,0)    += yv;
	sums(1,0)    += xv*yv;
      }
      res = smatrix.Invert() * sums;
      ay = res(0,0);
      by = res(1,0);

      Float_t xtc, ytc, ztc;
      for (Int_t ii = 0; ii < 4; ii++) {

	ztc = zg[ii];
	ytc = ay+by*zg[ii];
	xtc = ax+bx*zg[ii];

	//printf("tc: x %f y %f z %f \n",xtc,ytc,ztc);

	track->SetPoint(count,xtc,ytc,ztc);
	count++;

      }

    }  // end match trigger

    gReve->AddRenderElement(lt, track);

  }

}

<commit_msg>From Bogdan: removed macro file.<commit_after><|endoftext|>


<commit_before>#ifndef GUARD_MLOPEN_OCL_KERNEL_HPP_
#define GUARD_MLOPEN_OCL_KERNEL_HPP_

#include <sstream>
#include <array>
#include <utility>
#include <vector>
#include <mlopen.h>
#include <cassert>
#include <functional>
#include <array>
#include <memory>
#include <algorithm>

#include <mlopen/errors.hpp>
#include <mlopen/each_args.hpp>
#include <mlopen/clhelper.hpp>

namespace mlopen {

using SharedKernelPtr = std::shared_ptr<typename std::remove_pointer<cl_kernel>::type>;
using SharedProgramPtr = std::shared_ptr<typename std::remove_pointer<cl_program>::type>;

struct LocalMemArg
{
	LocalMemArg(size_t _size) : size(_size) {}
	size_t GetSize() const { return size; }

	private:
	size_t size;
};

struct OCLSetKernelArg
{
	template<class I, class T>
	void operator()(cl_kernel kernel, I i, const T& x) const
	{
		cl_int status = clSetKernelArg(kernel, i, sizeof(T), reinterpret_cast<const void*>(&x));
		if (status != CL_SUCCESS) { MLOPEN_THROW("Error setting argument to kernel: " + std::to_string(status));
}
	}

	template<class I>
	void operator()(cl_kernel kernel, I i, const LocalMemArg& lmem) const
	{
		cl_int status = clSetKernelArg(kernel, i, lmem.GetSize(), NULL);
		if (status != CL_SUCCESS) { MLOPEN_THROW("Error setting argument to kernel: " + std::to_string(status));
}
	}
};

struct OCLKernelInvoke
{
	cl_command_queue queue;
	SharedKernelPtr kernel;
	size_t work_dim;
	std::array<size_t, 3> global_work_offset;
	std::array<size_t, 3> global_work_dim;
	std::array<size_t, 3> local_work_dim;
	std::function<void(cl_event&)> callback;

	template<class... Ts>
	void operator()(const Ts&... xs) const
	{
		each_args_i(std::bind(OCLSetKernelArg{}, kernel.get(), std::placeholders::_1, std::placeholders::_2), xs...);
		run();
	}

	void run() const;
};

class OCLKernel {

public:
	OCLKernel() {}
	OCLKernel(ClKernelPtr k) : kernel(std::move(k)) {}
	OCLKernel(ClKernelPtr k,
			std::vector<size_t> local_dims,
			std::vector<size_t> global_dims)
	: kernel(std::move(k)), ldims(std::move(local_dims)), gdims(std::move(global_dims))
	{
		assert(ldims.size() == gdims.size());
		assert(!ldims.empty() && ldims.size() <= 3);
	}

	OCLKernel(SharedProgramPtr p,
			const std::string& kernel_name,
			std::vector<size_t> local_dims,
			std::vector<size_t> global_dims)
	: program(p), kernel(CreateKernel(p.get(), kernel_name)), ldims(std::move(local_dims)), gdims(std::move(global_dims))
	{
		assert(!gdims.empty() && gdims.size() <= 3);
		assert(!ldims.empty() && ldims.size() <= 3);
		if(std::accumulate(ldims.begin(), ldims.end(), 1, std::multiplies<size_t>{}) > 256)
		{
			std::fill(ldims.begin(), ldims.end(), 0);
		}
	}

	OCLKernelInvoke Invoke(cl_command_queue q, std::function<void(cl_event&)> callback=nullptr);

	cl_kernel GetKernel() { return kernel.get(); }

	std::string GetName() const;

	inline const std::vector<size_t>& GetLocalDims() const { return ldims; }
	inline const std::vector<size_t>& GetGlobalDims() const { return gdims; }

private:
	SharedProgramPtr program;
	SharedKernelPtr kernel;
	std::vector<size_t> ldims;
	std::vector<size_t> gdims;
};

}  // namespace mlopen

#endif // GUARD_MLOPEN_OCL_KERNEL_HPP_
<commit_msg>added numeric header<commit_after>#ifndef GUARD_MLOPEN_OCL_KERNEL_HPP_
#define GUARD_MLOPEN_OCL_KERNEL_HPP_

#include <sstream>
#include <array>
#include <utility>
#include <vector>
#include <mlopen.h>
#include <cassert>
#include <functional>
#include <array>
#include <memory>
#include <algorithm>
#include <numeric>

#include <mlopen/errors.hpp>
#include <mlopen/each_args.hpp>
#include <mlopen/clhelper.hpp>

namespace mlopen {

using SharedKernelPtr = std::shared_ptr<typename std::remove_pointer<cl_kernel>::type>;
using SharedProgramPtr = std::shared_ptr<typename std::remove_pointer<cl_program>::type>;

struct LocalMemArg
{
	LocalMemArg(size_t _size) : size(_size) {}
	size_t GetSize() const { return size; }

	private:
	size_t size;
};

struct OCLSetKernelArg
{
	template<class I, class T>
	void operator()(cl_kernel kernel, I i, const T& x) const
	{
		cl_int status = clSetKernelArg(kernel, i, sizeof(T), reinterpret_cast<const void*>(&x));
		if (status != CL_SUCCESS) { MLOPEN_THROW("Error setting argument to kernel: " + std::to_string(status));
}
	}

	template<class I>
	void operator()(cl_kernel kernel, I i, const LocalMemArg& lmem) const
	{
		cl_int status = clSetKernelArg(kernel, i, lmem.GetSize(), NULL);
		if (status != CL_SUCCESS) { MLOPEN_THROW("Error setting argument to kernel: " + std::to_string(status));
}
	}
};

struct OCLKernelInvoke
{
	cl_command_queue queue;
	SharedKernelPtr kernel;
	size_t work_dim;
	std::array<size_t, 3> global_work_offset;
	std::array<size_t, 3> global_work_dim;
	std::array<size_t, 3> local_work_dim;
	std::function<void(cl_event&)> callback;

	template<class... Ts>
	void operator()(const Ts&... xs) const
	{
		each_args_i(std::bind(OCLSetKernelArg{}, kernel.get(), std::placeholders::_1, std::placeholders::_2), xs...);
		run();
	}

	void run() const;
};

class OCLKernel {

public:
	OCLKernel() {}
	OCLKernel(ClKernelPtr k) : kernel(std::move(k)) {}
	OCLKernel(ClKernelPtr k,
			std::vector<size_t> local_dims,
			std::vector<size_t> global_dims)
	: kernel(std::move(k)), ldims(std::move(local_dims)), gdims(std::move(global_dims))
	{
		assert(ldims.size() == gdims.size());
		assert(!ldims.empty() && ldims.size() <= 3);
	}

	OCLKernel(SharedProgramPtr p,
			const std::string& kernel_name,
			std::vector<size_t> local_dims,
			std::vector<size_t> global_dims)
	: program(p), kernel(CreateKernel(p.get(), kernel_name)), ldims(std::move(local_dims)), gdims(std::move(global_dims))
	{
		assert(!gdims.empty() && gdims.size() <= 3);
		assert(!ldims.empty() && ldims.size() <= 3);
		if(std::accumulate(ldims.begin(), ldims.end(), 1, std::multiplies<size_t>{}) > 256)
		{
			std::fill(ldims.begin(), ldims.end(), 0);
		}
	}

	OCLKernelInvoke Invoke(cl_command_queue q, std::function<void(cl_event&)> callback=nullptr);

	cl_kernel GetKernel() { return kernel.get(); }

	std::string GetName() const;

	inline const std::vector<size_t>& GetLocalDims() const { return ldims; }
	inline const std::vector<size_t>& GetGlobalDims() const { return gdims; }

private:
	SharedProgramPtr program;
	SharedKernelPtr kernel;
	std::vector<size_t> ldims;
	std::vector<size_t> gdims;
};

}  // namespace mlopen

#endif // GUARD_MLOPEN_OCL_KERNEL_HPP_
<|endoftext|>


<commit_before><commit_msg>Flick the switch back to PATCH_PROTOCOL while sorting out a few failing unit tests on the builder.<commit_after><|endoftext|>


<commit_before>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2015.  All rights reserved
 */
#include    "../StroikaPreComp.h"

#include    "Instruments/LoadAverage.h"
#include    "Instruments/MountedFilesystemUsage.h"
#include    "Instruments/NetworkInterfaces.h"
#include    "Instruments/ProcessDetails.h"
#include    "Instruments/SystemTimes.h"

#include    "AllInstruments.h"

using   namespace   Stroika::Foundation;
using   namespace   Stroika::Foundation::Containers;
using   namespace   Stroika::Foundation::Memory;

using   namespace   Stroika::Frameworks;
using   namespace   Stroika::Frameworks::SystemPerformance;

/*
 ********************************************************************************
 ******************* SystemPerformance::GetAllInstruments ***********************
 ********************************************************************************
 */
InstrumentSet   SystemPerformance::GetAllInstruments ()
{
    // OK to cache - copyable - but construct AFTER main (only when called here)
    static  InstrumentSet   kInstruments_ = {
#if     qSupport_SystemPerformance_Instruments_LoadAverage
        Instruments::LoadAverage::GetInstrument (),
#endif
#if     qSupport_SystemPerformance_Instruments_SystemTimes
        Instruments::SystemTimes::GetInstrument (),
#endif
        Instruments::NetworkInterfaces::GetInstrument (),
        Instruments::ProcessDetails::GetInstrument (),
        Instruments::MountedFilesystemUsage::GetInstrument (),
    };
    return kInstruments_;
}
<commit_msg>include  Instruments::SystemCPU::GetInstrument ()  in AllInstruments<commit_after>/*
 * Copyright(c) Sophist Solutions, Inc. 1990-2015.  All rights reserved
 */
#include    "../StroikaPreComp.h"

#include    "Instruments/LoadAverage.h"
#include    "Instruments/MountedFilesystemUsage.h"
#include    "Instruments/NetworkInterfaces.h"
#include    "Instruments/ProcessDetails.h"
#include    "Instruments/SystemCPU.h"
#include    "Instruments/SystemTimes.h"

#include    "AllInstruments.h"

using   namespace   Stroika::Foundation;
using   namespace   Stroika::Foundation::Containers;
using   namespace   Stroika::Foundation::Memory;

using   namespace   Stroika::Frameworks;
using   namespace   Stroika::Frameworks::SystemPerformance;

/*
 ********************************************************************************
 ******************* SystemPerformance::GetAllInstruments ***********************
 ********************************************************************************
 */
InstrumentSet   SystemPerformance::GetAllInstruments ()
{
    // OK to cache - copyable - but construct AFTER main (only when called here)
    static  InstrumentSet   kInstruments_ = {
#if     qSupport_SystemPerformance_Instruments_LoadAverage
        Instruments::LoadAverage::GetInstrument (),
#endif
#if     qSupport_SystemPerformance_Instruments_SystemTimes
        Instruments::SystemTimes::GetInstrument (),
#endif
        Instruments::NetworkInterfaces::GetInstrument (),
        Instruments::ProcessDetails::GetInstrument (),
        Instruments::MountedFilesystemUsage::GetInstrument (),
        Instruments::SystemCPU::GetInstrument (),
    };
    return kInstruments_;
}
<|endoftext|>


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

#include "WrappedPropertySet.hxx"
#include "ServiceMacros.hxx"

#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase2.hxx>
#endif
#ifndef _COMPHELPER_UNO3_HXX_
#include <comphelper/uno3.hxx>
#endif
#ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_
#include <cppuhelper/interfacecontainer.hxx>
#endif

#ifndef _COM_SUN_STAR_DRAWING_XSHAPE_HPP_
#include <com/sun/star/drawing/XShape.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif

#ifndef _COM_SUN_STAR_CHART2_XDIAGRAM_HPP_
#include <com/sun/star/chart2/XDiagram.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_
#include <com/sun/star/uno/XComponentContext.hpp>
#endif

#include <boost/shared_ptr.hpp>

namespace chart
{

namespace wrapper
{

class Chart2ModelContact;

class GridWrapper : public ::cppu::ImplInheritanceHelper2<
                      WrappedPropertySet
                    , com::sun::star::lang::XComponent
                    , com::sun::star::lang::XServiceInfo
                    >
{
public:
    enum tGridType
    {
        X_MAIN_GRID,
        Y_MAIN_GRID,
        Z_MAIN_GRID,
        X_SUB_GRID,
        Y_SUB_GRID,
        Z_SUB_GRID,
    };

    GridWrapper( tGridType eType, ::boost::shared_ptr< Chart2ModelContact > spChart2ModelContact );
    virtual ~GridWrapper();

    static void getDimensionAndSubGridBool( tGridType eType, sal_Int32& rnDimensionIndex, bool& rbSubGrid );

    /// XServiceInfo declarations
    APPHELPER_XSERVICEINFO_DECL()

    // ____ XComponent ____
    virtual void SAL_CALL dispose()
        throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference<
                                            ::com::sun::star::lang::XEventListener >& xListener )
        throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference<
                                               ::com::sun::star::lang::XEventListener >& aListener )
        throw (::com::sun::star::uno::RuntimeException);

protected:
    // ____ WrappedPropertySet ____
    virtual const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& getPropertySequence();
    virtual const std::vector< WrappedProperty* > createWrappedProperties();
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > getInnerPropertySet();

private:
    ::boost::shared_ptr< Chart2ModelContact >   m_spChart2ModelContact;
    ::cppu::OInterfaceContainerHelper           m_aEventListenerContainer;

    tGridType           m_eType;
};

} //  namespace wrapper
} //  namespace chart

// CHART_GRIDWRAPPER_HXX
#endif
<commit_msg>INTEGRATION: CWS chart11 (1.2.38); FILE MERGED 2007/08/01 06:10:36 bm 1.2.38.1: #i79522# warning removed (unxsoli4)<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: GridWrapper.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: vg $ $Date: 2007-09-18 14:52:46 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef CHART_GRIDWRAPPER_HXX
#define CHART_GRIDWRAPPER_HXX

#include "WrappedPropertySet.hxx"
#include "ServiceMacros.hxx"

#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase2.hxx>
#endif
#ifndef _COMPHELPER_UNO3_HXX_
#include <comphelper/uno3.hxx>
#endif
#ifndef _CPPUHELPER_INTERFACECONTAINER_HXX_
#include <cppuhelper/interfacecontainer.hxx>
#endif

#ifndef _COM_SUN_STAR_DRAWING_XSHAPE_HPP_
#include <com/sun/star/drawing/XShape.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XCOMPONENT_HPP_
#include <com/sun/star/lang/XComponent.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif

#ifndef _COM_SUN_STAR_CHART2_XDIAGRAM_HPP_
#include <com/sun/star/chart2/XDiagram.hpp>
#endif
#ifndef _COM_SUN_STAR_UNO_XCOMPONENTCONTEXT_HPP_
#include <com/sun/star/uno/XComponentContext.hpp>
#endif

#include <boost/shared_ptr.hpp>

namespace chart
{

namespace wrapper
{

class Chart2ModelContact;

class GridWrapper : public ::cppu::ImplInheritanceHelper2<
                      WrappedPropertySet
                    , com::sun::star::lang::XComponent
                    , com::sun::star::lang::XServiceInfo
                    >
{
public:
    enum tGridType
    {
        X_MAIN_GRID,
        Y_MAIN_GRID,
        Z_MAIN_GRID,
        X_SUB_GRID,
        Y_SUB_GRID,
        Z_SUB_GRID
    };

    GridWrapper( tGridType eType, ::boost::shared_ptr< Chart2ModelContact > spChart2ModelContact );
    virtual ~GridWrapper();

    static void getDimensionAndSubGridBool( tGridType eType, sal_Int32& rnDimensionIndex, bool& rbSubGrid );

    /// XServiceInfo declarations
    APPHELPER_XSERVICEINFO_DECL()

    // ____ XComponent ____
    virtual void SAL_CALL dispose()
        throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL addEventListener( const ::com::sun::star::uno::Reference<
                                            ::com::sun::star::lang::XEventListener >& xListener )
        throw (::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL removeEventListener( const ::com::sun::star::uno::Reference<
                                               ::com::sun::star::lang::XEventListener >& aListener )
        throw (::com::sun::star::uno::RuntimeException);

protected:
    // ____ WrappedPropertySet ____
    virtual const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& getPropertySequence();
    virtual const std::vector< WrappedProperty* > createWrappedProperties();
    virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > getInnerPropertySet();

private:
    ::boost::shared_ptr< Chart2ModelContact >   m_spChart2ModelContact;
    ::cppu::OInterfaceContainerHelper           m_aEventListenerContainer;

    tGridType           m_eType;
};

} //  namespace wrapper
} //  namespace chart

// CHART_GRIDWRAPPER_HXX
#endif
<|endoftext|>


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

#include "MultipleItemConverter.hxx"

#ifndef _COM_SUN_STAR_AWT_SIZE_HPP_
#include <com/sun/star/awt/Size.hpp>
#endif

#include <memory>

class SdrModel;

namespace chart
{
namespace wrapper
{

class AllAxisItemConverter : public ::comphelper::MultipleItemConverter
{
public:
    AllAxisItemConverter(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::frame::XModel > & xChartModel,
        SfxItemPool& rItemPool,
        SdrModel& rDrawModel,
        ::std::auto_ptr< ::com::sun::star::awt::Size > pRefSize =
            ::std::auto_ptr< ::com::sun::star::awt::Size >() );
    virtual ~AllAxisItemConverter();

protected:
    virtual const USHORT * GetWhichPairs() const;
};

class AllGridItemConverter : public ::comphelper::MultipleItemConverter
{
public:
    AllGridItemConverter(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::frame::XModel > & xChartModel,
        SfxItemPool& rItemPool,
        SdrModel& rDrawModel  );
    virtual ~AllGridItemConverter();

protected:
    virtual const USHORT * GetWhichPairs() const;
};

class AllDataLabelItemConverter : public ::comphelper::MultipleItemConverter
{
public:
    AllDataLabelItemConverter(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::frame::XModel > & xChartModel,
        SfxItemPool& rItemPool,
        SdrModel& rDrawModel,
        ::std::auto_ptr< ::com::sun::star::awt::Size > pRefSize =
            ::std::auto_ptr< ::com::sun::star::awt::Size >() );
    virtual ~AllDataLabelItemConverter();

protected:
    virtual const USHORT * GetWhichPairs() const;
};

class AllTitleItemConverter : public ::comphelper::MultipleItemConverter
{
public:
    AllTitleItemConverter(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::frame::XModel > & xChartModel,
        SfxItemPool& rItemPool,
        SdrModel& rDrawModel,
        ::std::auto_ptr< ::com::sun::star::awt::Size > pRefSize =
            ::std::auto_ptr< ::com::sun::star::awt::Size >() );
    virtual ~AllTitleItemConverter();

protected:
    virtual const USHORT * GetWhichPairs() const;
};

class AllSeriesStatisticsConverter : public ::comphelper::MultipleItemConverter
{
public:
    AllSeriesStatisticsConverter(
        const ::com::sun::star::uno::Reference<
        ::com::sun::star::frame::XModel > & xChartModel,
        SfxItemPool& rItemPool );
    virtual ~AllSeriesStatisticsConverter();

protected:
    virtual const USHORT * GetWhichPairs() const;
};

} //  namespace wrapper
} //  namespace chart

// CHART2_MULTIPLECHARTCONVERTERS_HXX
#endif
<commit_msg>INTEGRATION: CWS chart2mst3 (1.4.4); FILE MERGED 2005/10/07 11:26:57 bm 1.4.4.2: RESYNC: (1.4-1.5); FILE MERGED 2005/07/12 12:56:59 bm 1.4.4.1: use named properties for gradients etc. in chart model<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: MultipleChartConverters.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: vg $ $Date: 2007-05-22 17:54:37 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef CHART2_MULTIPLECHARTCONVERTERS_HXX
#define CHART2_MULTIPLECHARTCONVERTERS_HXX

#include "MultipleItemConverter.hxx"

#ifndef _COM_SUN_STAR_AWT_SIZE_HPP_
#include <com/sun/star/awt/Size.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

#include <memory>

class SdrModel;

namespace chart
{
namespace wrapper
{

class AllAxisItemConverter : public ::comphelper::MultipleItemConverter
{
public:
    AllAxisItemConverter(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::frame::XModel > & xChartModel,
        SfxItemPool& rItemPool,
        SdrModel& rDrawModel,
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::lang::XMultiServiceFactory > & xNamedPropertyContainerFactory,
        ::std::auto_ptr< ::com::sun::star::awt::Size > pRefSize =
            ::std::auto_ptr< ::com::sun::star::awt::Size >() );
    virtual ~AllAxisItemConverter();

protected:
    virtual const USHORT * GetWhichPairs() const;
};

class AllGridItemConverter : public ::comphelper::MultipleItemConverter
{
public:
    AllGridItemConverter(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::frame::XModel > & xChartModel,
        SfxItemPool& rItemPool,
        SdrModel& rDrawModel,
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::lang::XMultiServiceFactory > & xNamedPropertyContainerFactory );
    virtual ~AllGridItemConverter();

protected:
    virtual const USHORT * GetWhichPairs() const;
};

class AllDataLabelItemConverter : public ::comphelper::MultipleItemConverter
{
public:
    AllDataLabelItemConverter(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::frame::XModel > & xChartModel,
        SfxItemPool& rItemPool,
        SdrModel& rDrawModel,
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::lang::XMultiServiceFactory > & xNamedPropertyContainerFactory,
        ::std::auto_ptr< ::com::sun::star::awt::Size > pRefSize =
            ::std::auto_ptr< ::com::sun::star::awt::Size >() );
    virtual ~AllDataLabelItemConverter();

protected:
    virtual const USHORT * GetWhichPairs() const;
};

class AllTitleItemConverter : public ::comphelper::MultipleItemConverter
{
public:
    AllTitleItemConverter(
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::frame::XModel > & xChartModel,
        SfxItemPool& rItemPool,
        SdrModel& rDrawModel,
        const ::com::sun::star::uno::Reference<
            ::com::sun::star::lang::XMultiServiceFactory > & xNamedPropertyContainerFactory,
        ::std::auto_ptr< ::com::sun::star::awt::Size > pRefSize =
            ::std::auto_ptr< ::com::sun::star::awt::Size >() );
    virtual ~AllTitleItemConverter();

protected:
    virtual const USHORT * GetWhichPairs() const;
};

class AllSeriesStatisticsConverter : public ::comphelper::MultipleItemConverter
{
public:
    AllSeriesStatisticsConverter(
        const ::com::sun::star::uno::Reference<
        ::com::sun::star::frame::XModel > & xChartModel,
        SfxItemPool& rItemPool );
    virtual ~AllSeriesStatisticsConverter();

protected:
    virtual const USHORT * GetWhichPairs() const;
};

} //  namespace wrapper
} //  namespace chart

// CHART2_MULTIPLECHARTCONVERTERS_HXX
#endif
<|endoftext|>


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

#include "chrome/browser/android/compositor/layer/content_layer.h"

#include "cc/layers/layer.h"
#include "cc/layers/layer_lists.h"
#include "chrome/browser/android/compositor/layer/thumbnail_layer.h"
#include "chrome/browser/android/compositor/tab_content_manager.h"
#include "ui/gfx/geometry/size.h"

namespace chrome {
namespace android {

// static
scoped_refptr<ContentLayer> ContentLayer::Create(
    TabContentManager* tab_content_manager) {
  return make_scoped_refptr(new ContentLayer(tab_content_manager));
}

static void SetOpacityOnLeaf(scoped_refptr<cc::Layer> layer, float alpha) {
  const cc::LayerList& children = layer->children();
  if (children.size() > 0) {
    layer->SetOpacity(1.0f);
    for (uint i = 0; i < children.size(); ++i)
      SetOpacityOnLeaf(children[i], alpha);
  } else {
    layer->SetOpacity(alpha);
  }
}

static bool DoesLeafDrawContents(scoped_refptr<cc::Layer> layer) {
  if (!layer.get())
    return false;

  // TODO: Remove the need for this logic. We can't really guess from
  // an opaque layer type whether it has valid live contents, or for example
  // just a background color placeholder. Need to get this from somewhere else
  // like ContentViewCore or RWHV.
  if (layer->DrawsContent() && !layer->hide_layer_and_subtree() &&
      !layer->background_color()) {
    return true;
  }

  const cc::LayerList& children = layer->children();
  for (unsigned i = 0; i < children.size(); i++) {
    if (DoesLeafDrawContents(children[i]))
      return true;
  }
  return false;
}

static gfx::Size GetLeafBounds(scoped_refptr<cc::Layer> layer) {
  if (layer->children().size() > 0)
    return GetLeafBounds(layer->children()[0]);
  return layer->bounds();
}

void ContentLayer::SetProperties(int id,
                                 bool can_use_live_layer,
                                 bool can_use_ntp_fallback,
                                 float static_to_view_blend,
                                 bool should_override_content_alpha,
                                 float content_alpha_override,
                                 float saturation,
                                 const gfx::Rect& desired_bounds,
                                 const gfx::Size& content_size) {
  scoped_refptr<cc::Layer> content_layer =
      tab_content_manager_->GetLiveLayer(id);
  ClipContentLayer(content_layer, desired_bounds, content_size);
  bool content_layer_draws = DoesLeafDrawContents(content_layer);

  scoped_refptr<ThumbnailLayer> static_layer =
      tab_content_manager_->GetStaticLayer(id, !content_layer_draws);

  ClipStaticLayer(static_layer, desired_bounds);

  // Reset the attachment logic if the number of children doesn't match the
  // boolean flags. At some point while a tab is in the background one or more
  // layers may be removed from this tree.
  // Note that this needs to be checked *after* we access TabContentManager, as
  // that class might remove layers internally, messing up our own tracking.
  unsigned int expected_layers = 0;
  expected_layers += content_attached_ ? 1 : 0;
  expected_layers += static_attached_ ? 1 : 0;
  if (layer_->children().size() != expected_layers) {
    content_attached_ = false;
    static_attached_ = false;
    const cc::LayerList& layer_children = layer_->children();
    for (unsigned i = 0; i < layer_children.size(); i++)
      layer_children[i]->RemoveFromParent();
  }

  gfx::Size content_bounds(0, 0);
  if (!content_layer.get() || !can_use_live_layer) {
    SetContentLayer(nullptr);
    SetStaticLayer(static_layer);
    if (static_layer.get())
      content_bounds = static_layer->layer()->bounds();
    else
      content_bounds.set_width(content_size.width());
  } else {
    SetContentLayer(content_layer);
    content_bounds = content_layer->bounds();

    if (static_to_view_blend == 0.0f && !content_layer_draws)
      static_to_view_blend = 1.0f;

    if (static_to_view_blend != 0.0f && static_layer.get()) {
      static_layer->layer()->SetOpacity(static_to_view_blend);
      SetStaticLayer(static_layer);
      if (content_bounds.GetArea() == 0 || !content_layer_draws)
        content_bounds = static_layer->layer()->bounds();
    } else {
      SetStaticLayer(nullptr);
    }
  }

  if (should_override_content_alpha) {
    for (unsigned int i = 0; i < layer_->children().size(); ++i)
      SetOpacityOnLeaf(layer_->children()[i], content_alpha_override);
  }

  if (!content_layer_draws && !static_attached_)
    content_bounds = gfx::Size(0, 0);

  layer_->SetBounds(content_bounds);

  // Only worry about saturation on the static layer
  if (static_layer.get()) {
    if (saturation != saturation_) {
      saturation_ = saturation;
      cc::FilterOperations filters;
      if (saturation_ < 1.0f)
        filters.Append(cc::FilterOperation::CreateSaturateFilter(saturation_));
      static_layer->layer()->SetFilters(filters);
    }
  }
}

gfx::Size ContentLayer::GetContentSize() {
  if (content_attached_ && DoesLeafDrawContents(layer()->children()[0]))
    return layer_->children()[0]->bounds();
  return gfx::Size(0, 0);
}

scoped_refptr<cc::Layer> ContentLayer::layer() {
  return layer_;
}

ContentLayer::ContentLayer(TabContentManager* tab_content_manager)
    : layer_(cc::Layer::Create()),
      content_attached_(false),
      static_attached_(false),
      saturation_(1.0f),
      tab_content_manager_(tab_content_manager) {
}

ContentLayer::~ContentLayer() {
}

void ContentLayer::SetContentLayer(scoped_refptr<cc::Layer> layer) {
  // Check indices
  // content_attached_, expect at least 1 child.
  DCHECK(!content_attached_ || layer_->children().size() > 0);

  if (!layer.get()) {
    if (content_attached_)
      layer_->child_at(0)->RemoveFromParent();
    content_attached_ = false;
    return;
  }

  bool new_layer = false;
  if (content_attached_ && layer_->child_at(0)->id() != layer->id()) {
    layer_->ReplaceChild(layer_->child_at(0), layer);
    new_layer = true;
  } else if (!content_attached_) {
    layer_->InsertChild(layer, 0);
    new_layer = true;
  }

  // If this is a new layer, reset it's opacity.
  if (new_layer)
    SetOpacityOnLeaf(layer, 1.0f);

  content_attached_ = true;
}

void ContentLayer::SetStaticLayer(
    scoped_refptr<ThumbnailLayer> new_static_layer) {
  // Make sure child access will be valid.
  // !content_attached_ AND !static_attached_, expect 0 children.
  // content_attached_ XOR static_attached_, expect 1 child.
  // content_attached_ AND static_attached_, expect 2 children.
  DCHECK((!content_attached_ && !static_attached_) ||
         (content_attached_ != static_attached_ &&
          layer_->children().size() >= 1) ||
         (content_attached_ && static_attached_ &&
          layer_->children().size() >= 2));

  if (!new_static_layer.get()) {
    if (static_layer_.get()) {
      static_layer_->layer()->RemoveFromParent();
      static_layer_ = nullptr;
    }
    static_attached_ = false;
    return;
  }
  static_layer_ = new_static_layer;
  static_layer_->AddSelfToParentOrReplaceAt(layer_, content_attached_ ? 1 : 0);
  saturation_ = -1.0f;
  static_layer_->layer()->SetIsDrawable(true);
  static_attached_ = true;
}

void ContentLayer::ClipContentLayer(scoped_refptr<cc::Layer> content_layer,
                                    gfx::Rect clipping,
                                    gfx::Size content_size) {
  if (!content_layer.get())
    return;

  gfx::Size bounds(GetLeafBounds(content_layer));
  content_layer->SetMasksToBounds(true);
  gfx::Size clamped_bounds(bounds);
  clamped_bounds.SetToMin(clipping.size());
  content_layer->SetBounds(clamped_bounds);

  if (content_layer->children().size() > 0) {
    gfx::PointF offset(
        std::min(content_size.width() - bounds.width() - clipping.x(), 0),
        std::min(content_size.height() - bounds.height() - clipping.y(), 0));
    content_layer->children()[0]->SetPosition(offset);
  }
}

void ContentLayer::ClipStaticLayer(scoped_refptr<ThumbnailLayer> static_layer,
                                   gfx::Rect clipping) {
  if (!static_layer.get())
    return;
  static_layer->Clip(clipping);
}

}  //  namespace android
}  //  namespace chrome
<commit_msg>Set force_disk_read when live layer isn't valid<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/android/compositor/layer/content_layer.h"

#include "cc/layers/layer.h"
#include "cc/layers/layer_lists.h"
#include "chrome/browser/android/compositor/layer/thumbnail_layer.h"
#include "chrome/browser/android/compositor/tab_content_manager.h"
#include "ui/gfx/geometry/size.h"

namespace chrome {
namespace android {

// static
scoped_refptr<ContentLayer> ContentLayer::Create(
    TabContentManager* tab_content_manager) {
  return make_scoped_refptr(new ContentLayer(tab_content_manager));
}

static void SetOpacityOnLeaf(scoped_refptr<cc::Layer> layer, float alpha) {
  const cc::LayerList& children = layer->children();
  if (children.size() > 0) {
    layer->SetOpacity(1.0f);
    for (uint i = 0; i < children.size(); ++i)
      SetOpacityOnLeaf(children[i], alpha);
  } else {
    layer->SetOpacity(alpha);
  }
}

static bool DoesLeafDrawContents(scoped_refptr<cc::Layer> layer) {
  if (!layer.get())
    return false;

  // TODO: Remove the need for this logic. We can't really guess from
  // an opaque layer type whether it has valid live contents, or for example
  // just a background color placeholder. Need to get this from somewhere else
  // like ContentViewCore or RWHV.
  if (layer->DrawsContent() && !layer->hide_layer_and_subtree() &&
      !layer->background_color()) {
    return true;
  }

  const cc::LayerList& children = layer->children();
  for (unsigned i = 0; i < children.size(); i++) {
    if (DoesLeafDrawContents(children[i]))
      return true;
  }
  return false;
}

static gfx::Size GetLeafBounds(scoped_refptr<cc::Layer> layer) {
  if (layer->children().size() > 0)
    return GetLeafBounds(layer->children()[0]);
  return layer->bounds();
}

void ContentLayer::SetProperties(int id,
                                 bool can_use_live_layer,
                                 bool can_use_ntp_fallback,
                                 float static_to_view_blend,
                                 bool should_override_content_alpha,
                                 float content_alpha_override,
                                 float saturation,
                                 const gfx::Rect& desired_bounds,
                                 const gfx::Size& content_size) {
  scoped_refptr<cc::Layer> content_layer =
      tab_content_manager_->GetLiveLayer(id);
  ClipContentLayer(content_layer, desired_bounds, content_size);
  bool content_layer_draws = DoesLeafDrawContents(content_layer);

  scoped_refptr<ThumbnailLayer> static_layer =
      tab_content_manager_->GetStaticLayer(
          id, !(can_use_live_layer && content_layer_draws));

  ClipStaticLayer(static_layer, desired_bounds);

  // Reset the attachment logic if the number of children doesn't match the
  // boolean flags. At some point while a tab is in the background one or more
  // layers may be removed from this tree.
  // Note that this needs to be checked *after* we access TabContentManager, as
  // that class might remove layers internally, messing up our own tracking.
  unsigned int expected_layers = 0;
  expected_layers += content_attached_ ? 1 : 0;
  expected_layers += static_attached_ ? 1 : 0;
  if (layer_->children().size() != expected_layers) {
    content_attached_ = false;
    static_attached_ = false;
    const cc::LayerList& layer_children = layer_->children();
    for (unsigned i = 0; i < layer_children.size(); i++)
      layer_children[i]->RemoveFromParent();
  }

  gfx::Size content_bounds(0, 0);
  if (!content_layer.get() || !can_use_live_layer) {
    SetContentLayer(nullptr);
    SetStaticLayer(static_layer);
    if (static_layer.get())
      content_bounds = static_layer->layer()->bounds();
    else
      content_bounds.set_width(content_size.width());
  } else {
    SetContentLayer(content_layer);
    content_bounds = content_layer->bounds();

    if (static_to_view_blend == 0.0f && !content_layer_draws)
      static_to_view_blend = 1.0f;

    if (static_to_view_blend != 0.0f && static_layer.get()) {
      static_layer->layer()->SetOpacity(static_to_view_blend);
      SetStaticLayer(static_layer);
      if (content_bounds.GetArea() == 0 || !content_layer_draws)
        content_bounds = static_layer->layer()->bounds();
    } else {
      SetStaticLayer(nullptr);
    }
  }

  if (should_override_content_alpha) {
    for (unsigned int i = 0; i < layer_->children().size(); ++i)
      SetOpacityOnLeaf(layer_->children()[i], content_alpha_override);
  }

  if (!content_layer_draws && !static_attached_)
    content_bounds = gfx::Size(0, 0);

  layer_->SetBounds(content_bounds);

  // Only worry about saturation on the static layer
  if (static_layer.get()) {
    if (saturation != saturation_) {
      saturation_ = saturation;
      cc::FilterOperations filters;
      if (saturation_ < 1.0f)
        filters.Append(cc::FilterOperation::CreateSaturateFilter(saturation_));
      static_layer->layer()->SetFilters(filters);
    }
  }
}

gfx::Size ContentLayer::GetContentSize() {
  if (content_attached_ && DoesLeafDrawContents(layer()->children()[0]))
    return layer_->children()[0]->bounds();
  return gfx::Size(0, 0);
}

scoped_refptr<cc::Layer> ContentLayer::layer() {
  return layer_;
}

ContentLayer::ContentLayer(TabContentManager* tab_content_manager)
    : layer_(cc::Layer::Create()),
      content_attached_(false),
      static_attached_(false),
      saturation_(1.0f),
      tab_content_manager_(tab_content_manager) {
}

ContentLayer::~ContentLayer() {
}

void ContentLayer::SetContentLayer(scoped_refptr<cc::Layer> layer) {
  // Check indices
  // content_attached_, expect at least 1 child.
  DCHECK(!content_attached_ || layer_->children().size() > 0);

  if (!layer.get()) {
    if (content_attached_)
      layer_->child_at(0)->RemoveFromParent();
    content_attached_ = false;
    return;
  }

  bool new_layer = false;
  if (content_attached_ && layer_->child_at(0)->id() != layer->id()) {
    layer_->ReplaceChild(layer_->child_at(0), layer);
    new_layer = true;
  } else if (!content_attached_) {
    layer_->InsertChild(layer, 0);
    new_layer = true;
  }

  // If this is a new layer, reset it's opacity.
  if (new_layer)
    SetOpacityOnLeaf(layer, 1.0f);

  content_attached_ = true;
}

void ContentLayer::SetStaticLayer(
    scoped_refptr<ThumbnailLayer> new_static_layer) {
  // Make sure child access will be valid.
  // !content_attached_ AND !static_attached_, expect 0 children.
  // content_attached_ XOR static_attached_, expect 1 child.
  // content_attached_ AND static_attached_, expect 2 children.
  DCHECK((!content_attached_ && !static_attached_) ||
         (content_attached_ != static_attached_ &&
          layer_->children().size() >= 1) ||
         (content_attached_ && static_attached_ &&
          layer_->children().size() >= 2));

  if (!new_static_layer.get()) {
    if (static_layer_.get()) {
      static_layer_->layer()->RemoveFromParent();
      static_layer_ = nullptr;
    }
    static_attached_ = false;
    return;
  }
  static_layer_ = new_static_layer;
  static_layer_->AddSelfToParentOrReplaceAt(layer_, content_attached_ ? 1 : 0);
  saturation_ = -1.0f;
  static_layer_->layer()->SetIsDrawable(true);
  static_attached_ = true;
}

void ContentLayer::ClipContentLayer(scoped_refptr<cc::Layer> content_layer,
                                    gfx::Rect clipping,
                                    gfx::Size content_size) {
  if (!content_layer.get())
    return;

  gfx::Size bounds(GetLeafBounds(content_layer));
  content_layer->SetMasksToBounds(true);
  gfx::Size clamped_bounds(bounds);
  clamped_bounds.SetToMin(clipping.size());
  content_layer->SetBounds(clamped_bounds);

  if (content_layer->children().size() > 0) {
    gfx::PointF offset(
        std::min(content_size.width() - bounds.width() - clipping.x(), 0),
        std::min(content_size.height() - bounds.height() - clipping.y(), 0));
    content_layer->children()[0]->SetPosition(offset);
  }
}

void ContentLayer::ClipStaticLayer(scoped_refptr<ThumbnailLayer> static_layer,
                                   gfx::Rect clipping) {
  if (!static_layer.get())
    return;
  static_layer->Clip(clipping);
}

}  //  namespace android
}  //  namespace chrome
<|endoftext|>