<commit_before>/* Copyright 2020 The TensorFlow Quantum Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include <string>

#include "cirq/google/api/v2/program.pb.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/shape_inference.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/lib/core/error_codes.pb.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/core/threadpool.h"
#include "tensorflow_quantum/core/ops/parse_context.h"
#include "tensorflow_quantum/core/ops/tfq_simulate_utils.h"
#include "tensorflow_quantum/core/qsim/mux.h"
#include "tensorflow_quantum/core/qsim/state_space.h"
#include "tensorflow_quantum/core/src/circuit_parser.h"
#include "tensorflow_quantum/core/src/program_resolution.h"

namespace tfq {

using ::cirq::google::api::v2::Program;
using ::tensorflow::Status;
using ::tfq::Circuit;
using ::tfq::CircuitFromProgram;
using ::tfq::qsim::GetStateSpace;
using ::tfq::qsim::StateSpace;

class TfqSimulateStateOp : public tensorflow::OpKernel {
 public:
  explicit TfqSimulateStateOp(tensorflow::OpKernelConstruction *context)
      : OpKernel(context) {}

  void Compute(tensorflow::OpKernelContext *context) override {
    // TODO (mbbrough): add more dimension checks for other inputs here.
    DCHECK_EQ(3, context->num_inputs());

    std::vector<Program> programs;
    std::vector<int> num_qubits;
    OP_REQUIRES_OK(context,
                   GetProgramsAndNumQubits(context, &programs, &num_qubits));
    std::vector<SymbolMap> maps;
    OP_REQUIRES_OK(context, GetSymbolMaps(context, &maps));

    OP_REQUIRES(
        context, maps.size() == programs.size(),
        tensorflow::errors::InvalidArgument(absl::StrCat(
            "Number of circuits and values do not match. Got ", programs.size(),
            " circuits and ", maps.size(), " values.")));

    int max_num_qubits = 0;
    for (const int num : num_qubits) {
      max_num_qubits = std::max(max_num_qubits, num);
    }

    // TODO(pmassey): Investigate creating a matrix that isn't just the maximum
    // required size.
    const int output_dim_size = maps.size();
    tensorflow::TensorShape output_shape;
    output_shape.AddDim(output_dim_size);
    output_shape.AddDim(1 << max_num_qubits);

    tensorflow::Tensor *output = nullptr;
    OP_REQUIRES_OK(context, context->allocate_output(0, output_shape, &output));
    auto output_tensor = output->matrix<std::complex<float>>();

    auto DoWork = [&](int start, int end) {
      std::unique_ptr<StateSpace> state =
          std::unique_ptr<StateSpace>(GetStateSpace(1, 1));
      int old_num_qubits = -1;
      for (int i = start; i < end; i++) {
        Program program = programs[i];
        const int num = num_qubits[i];
        OP_REQUIRES_OK(context, ResolveSymbols(maps[i], &program));

        // QSim work below
        Circuit circuit;
        OP_REQUIRES_OK(context, CircuitFromProgram(program, num, &circuit));

        // TODO(mbbrough): Update this allocation hack so that a StateSpace
        //  object can grow it's memory dynamically to larger and larger size
        //  without ever having to call free (until the very end). This is
        //  tricky to implement because right now certain statespaces can't
        //  simulate all states and we use StateSpaceSlow for smaller circuits.
        if (num != old_num_qubits) {
          state.reset(GetStateSpace(num, 1));
          state->CreateState();
        }
        state->SetStateZero();
        OP_REQUIRES_OK(context, state->Update(circuit));
        uint64_t state_size = state->GetDimension();
        for (uint64_t j = 0; j < state_size; j++) {
          output_tensor(i, j) = state->GetAmpl(j);
        }
        for (uint64_t j = state_size; j < (uint64_t(1) << max_num_qubits);
             j++) {
          output_tensor(i, j) = std::complex<float>(-2, 0);
        }
        old_num_qubits = num;
      }
    };

    const int block_size = GetBlockSize(context, output_dim_size);
    context->device()
        ->tensorflow_cpu_worker_threads()
        ->workers->TransformRangeConcurrently(block_size, output_dim_size,
                                              DoWork);
  }
};

REGISTER_KERNEL_BUILDER(Name("TfqSimulateState").Device(tensorflow::DEVICE_CPU),
                        TfqSimulateStateOp);

REGISTER_OP("TfqSimulateState")
    .Input("programs: string")
    .Input("symbol_names: string")
    .Input("symbol_values: float")
    .Output("wavefunction: complex64")
    .SetShapeFn([](tensorflow::shape_inference::InferenceContext *c) {
      tensorflow::shape_inference::ShapeHandle programs_shape;
      TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 1, &programs_shape));

      tensorflow::shape_inference::ShapeHandle symbol_names_shape;
      TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 1, &symbol_names_shape));

      tensorflow::shape_inference::ShapeHandle symbol_values_shape;
      TF_RETURN_IF_ERROR(c->WithRank(c->input(2), 2, &symbol_values_shape));

      // TODO(pmassey): Which output dimension size matters? Does this allocate
      // any memory or gives hints to the graph building? I apparently just set
      // this as rows in the previous run and that seemed to work.
      tensorflow::shape_inference::DimensionHandle output_rows =
          c->Dim(symbol_values_shape, 0);
      tensorflow::shape_inference::DimensionHandle output_cols =
          c->Dim(symbol_values_shape, 1);
      c->set_output(0, c->Matrix(output_rows, output_cols));

      return tensorflow::Status::OK();
    });

}  // namespace tfq
<commit_msg>Fixed state op shapeinference shaping. (#170)<commit_after>/* Copyright 2020 The TensorFlow Quantum Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include <string>

#include "cirq/google/api/v2/program.pb.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/shape_inference.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/lib/core/error_codes.pb.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/core/threadpool.h"
#include "tensorflow_quantum/core/ops/parse_context.h"
#include "tensorflow_quantum/core/ops/tfq_simulate_utils.h"
#include "tensorflow_quantum/core/qsim/mux.h"
#include "tensorflow_quantum/core/qsim/state_space.h"
#include "tensorflow_quantum/core/src/circuit_parser.h"
#include "tensorflow_quantum/core/src/program_resolution.h"

namespace tfq {

using ::cirq::google::api::v2::Program;
using ::tensorflow::Status;
using ::tfq::Circuit;
using ::tfq::CircuitFromProgram;
using ::tfq::qsim::GetStateSpace;
using ::tfq::qsim::StateSpace;

class TfqSimulateStateOp : public tensorflow::OpKernel {
 public:
  explicit TfqSimulateStateOp(tensorflow::OpKernelConstruction *context)
      : OpKernel(context) {}

  void Compute(tensorflow::OpKernelContext *context) override {
    // TODO (mbbrough): add more dimension checks for other inputs here.
    DCHECK_EQ(3, context->num_inputs());

    std::vector<Program> programs;
    std::vector<int> num_qubits;
    OP_REQUIRES_OK(context,
                   GetProgramsAndNumQubits(context, &programs, &num_qubits));
    std::vector<SymbolMap> maps;
    OP_REQUIRES_OK(context, GetSymbolMaps(context, &maps));

    OP_REQUIRES(
        context, maps.size() == programs.size(),
        tensorflow::errors::InvalidArgument(absl::StrCat(
            "Number of circuits and values do not match. Got ", programs.size(),
            " circuits and ", maps.size(), " values.")));

    int max_num_qubits = 0;
    for (const int num : num_qubits) {
      max_num_qubits = std::max(max_num_qubits, num);
    }

    // TODO(pmassey): Investigate creating a matrix that isn't just the maximum
    // required size.
    const int output_dim_size = maps.size();
    tensorflow::TensorShape output_shape;
    output_shape.AddDim(output_dim_size);
    output_shape.AddDim(1 << max_num_qubits);

    tensorflow::Tensor *output = nullptr;
    OP_REQUIRES_OK(context, context->allocate_output(0, output_shape, &output));
    auto output_tensor = output->matrix<std::complex<float>>();

    auto DoWork = [&](int start, int end) {
      std::unique_ptr<StateSpace> state =
          std::unique_ptr<StateSpace>(GetStateSpace(1, 1));
      int old_num_qubits = -1;
      for (int i = start; i < end; i++) {
        Program program = programs[i];
        const int num = num_qubits[i];
        OP_REQUIRES_OK(context, ResolveSymbols(maps[i], &program));

        // QSim work below
        Circuit circuit;
        OP_REQUIRES_OK(context, CircuitFromProgram(program, num, &circuit));

        // TODO(mbbrough): Update this allocation hack so that a StateSpace
        //  object can grow it's memory dynamically to larger and larger size
        //  without ever having to call free (until the very end). This is
        //  tricky to implement because right now certain statespaces can't
        //  simulate all states and we use StateSpaceSlow for smaller circuits.
        if (num != old_num_qubits) {
          state.reset(GetStateSpace(num, 1));
          state->CreateState();
        }
        state->SetStateZero();
        OP_REQUIRES_OK(context, state->Update(circuit));
        uint64_t state_size = state->GetDimension();
        for (uint64_t j = 0; j < state_size; j++) {
          output_tensor(i, j) = state->GetAmpl(j);
        }
        for (uint64_t j = state_size; j < (uint64_t(1) << max_num_qubits);
             j++) {
          output_tensor(i, j) = std::complex<float>(-2, 0);
        }
        old_num_qubits = num;
      }
    };

    const int block_size = GetBlockSize(context, output_dim_size);
    context->device()
        ->tensorflow_cpu_worker_threads()
        ->workers->TransformRangeConcurrently(block_size, output_dim_size,
                                              DoWork);
  }
};

REGISTER_KERNEL_BUILDER(Name("TfqSimulateState").Device(tensorflow::DEVICE_CPU),
                        TfqSimulateStateOp);

REGISTER_OP("TfqSimulateState")
    .Input("programs: string")
    .Input("symbol_names: string")
    .Input("symbol_values: float")
    .Output("wavefunction: complex64")
    .SetShapeFn([](tensorflow::shape_inference::InferenceContext *c) {
      tensorflow::shape_inference::ShapeHandle programs_shape;
      TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 1, &programs_shape));

      tensorflow::shape_inference::ShapeHandle symbol_names_shape;
      TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 1, &symbol_names_shape));

      tensorflow::shape_inference::ShapeHandle symbol_values_shape;
      TF_RETURN_IF_ERROR(c->WithRank(c->input(2), 2, &symbol_values_shape));

      c->set_output(
          0, c->MakeShape(
                 {c->Dim(programs_shape, 0),
                  tensorflow::shape_inference::InferenceContext::kUnknownDim}));

      return tensorflow::Status::OK();
    });

}  // namespace tfq
<|endoftext|>


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

/*
 * $Log$
 * Revision 1.4  2004/09/08 13:56:47  peiyongz
 * Apache License Version 2.0
 *
 * Revision 1.3  2002/12/24 17:59:07  tng
 * Build with ICU 2.4
 *
 * Revision 1.2  2002/11/04 15:17:01  tng
 * C++ Namespace Support.
 *
 * Revision 1.1.1.1  2002/02/01 22:22:34  peiyongz
 * sane_include
 *
 * Revision 1.2  2001/05/11 13:26:52  tng
 * Copyright update.
 *
 * Revision 1.1  2001/03/02 19:26:51  knoaman
 * Schema: Regular expression handling part II
 *
 */

// ---------------------------------------------------------------------------
//  Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/regx/XMLUniCharacter.hpp>

#if defined (XML_USE_ICU_TRANSCODER)
   #include <unicode/uchar.h>
#else
   #include <xercesc/util/regx/UniCharTable.hpp>
#endif

XERCES_CPP_NAMESPACE_BEGIN

// ---------------------------------------------------------------------------
//  XMLUniCharacter: Public static methods
// ---------------------------------------------------------------------------
unsigned short XMLUniCharacter::getType(const XMLCh ch) {

#if defined (XML_USE_ICU_TRANSCODER)
	return (unsigned short) u_charType(ch);
#else
	return (unsigned short) fgUniCharsTable[ch];
#endif
}

XERCES_CPP_NAMESPACE_END

/**
  * End of file XMLUniCharacter.cpp
  */

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

/*
 * $Log$
 * Revision 1.5  2005/05/19 15:46:32  cargilld
 * 390 update: use ICU table which is present with the uniconv390.
 *
 * Revision 1.4  2004/09/08 13:56:47  peiyongz
 * Apache License Version 2.0
 *
 * Revision 1.3  2002/12/24 17:59:07  tng
 * Build with ICU 2.4
 *
 * Revision 1.2  2002/11/04 15:17:01  tng
 * C++ Namespace Support.
 *
 * Revision 1.1.1.1  2002/02/01 22:22:34  peiyongz
 * sane_include
 *
 * Revision 1.2  2001/05/11 13:26:52  tng
 * Copyright update.
 *
 * Revision 1.1  2001/03/02 19:26:51  knoaman
 * Schema: Regular expression handling part II
 *
 */

// ---------------------------------------------------------------------------
//  Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/regx/XMLUniCharacter.hpp>

#if defined (XML_USE_ICU_TRANSCODER) || defined (XML_USE_UNICONV390_TRANSCODER)
   #include <unicode/uchar.h>
#else
   #include <xercesc/util/regx/UniCharTable.hpp>
#endif

XERCES_CPP_NAMESPACE_BEGIN

// ---------------------------------------------------------------------------
//  XMLUniCharacter: Public static methods
// ---------------------------------------------------------------------------
unsigned short XMLUniCharacter::getType(const XMLCh ch) {

#if defined (XML_USE_ICU_TRANSCODER) || defined (XML_USE_UNICONV390_TRANSCODER)
	return (unsigned short) u_charType(ch);
#else
	return (unsigned short) fgUniCharsTable[ch];
#endif
}

XERCES_CPP_NAMESPACE_END

/**
  * End of file XMLUniCharacter.cpp
  */

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: sdrmediawindow.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: obo $ $Date: 2004-08-12 09:04:25 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _SDR_CONTACT_SDRMEDIAWIMNDOW_HXX

#include <avmedia/mediawindow.hxx>

namespace sdr { namespace contact {

// ------------------
// - SdrMediaWindow -
// ------------------

class ViewObjectContactOfSdrMediaObj;

class SdrMediaWindow : public ::avmedia::MediaWindow
{
public:

                            SdrMediaWindow( Window* pParent, ViewObjectContactOfSdrMediaObj& rViewObjContact );
                            ~SdrMediaWindow();

        virtual void        MouseMove( const MouseEvent& rMEvt );
        virtual void        MouseButtonDown( const MouseEvent& rMEvt );
        virtual void        MouseButtonUp( const MouseEvent& rMEvt );

        virtual void        KeyInput( const KeyEvent& rKEvt );
        virtual void        KeyUp( const KeyEvent& rKEvt );

        virtual void        Command( const CommandEvent& rCEvt );

        virtual sal_Int8    AcceptDrop( const AcceptDropEvent& rEvt );
        virtual sal_Int8    ExecuteDrop( const ExecuteDropEvent& rEvt );

        virtual void        StartDrag( sal_Int8 nAction, const Point& rPosPixel );

private:

    ViewObjectContactOfSdrMediaObj& mrViewObjectContactOfSdrMediaObj;
};

} }

#endif

<commit_msg>INTEGRATION: CWS ooo19126 (1.2.732); FILE MERGED 2005/09/05 14:26:28 rt 1.2.732.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: sdrmediawindow.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 00:03:42 $
 *
 *  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 _SDR_CONTACT_SDRMEDIAWIMNDOW_HXX

#include <avmedia/mediawindow.hxx>

namespace sdr { namespace contact {

// ------------------
// - SdrMediaWindow -
// ------------------

class ViewObjectContactOfSdrMediaObj;

class SdrMediaWindow : public ::avmedia::MediaWindow
{
public:

                            SdrMediaWindow( Window* pParent, ViewObjectContactOfSdrMediaObj& rViewObjContact );
                            ~SdrMediaWindow();

        virtual void        MouseMove( const MouseEvent& rMEvt );
        virtual void        MouseButtonDown( const MouseEvent& rMEvt );
        virtual void        MouseButtonUp( const MouseEvent& rMEvt );

        virtual void        KeyInput( const KeyEvent& rKEvt );
        virtual void        KeyUp( const KeyEvent& rKEvt );

        virtual void        Command( const CommandEvent& rCEvt );

        virtual sal_Int8    AcceptDrop( const AcceptDropEvent& rEvt );
        virtual sal_Int8    ExecuteDrop( const ExecuteDropEvent& rEvt );

        virtual void        StartDrag( sal_Int8 nAction, const Point& rPosPixel );

private:

    ViewObjectContactOfSdrMediaObj& mrViewObjectContactOfSdrMediaObj;
};

} }

#endif

<|endoftext|>


<commit_before>#include "kernel.h"
#include "geometries.h"
#include "ilwisobject.h"
#include "ilwisdata.h"
#include "coordinatesystem.h"
#include "georeference.h"
#include "georefimplementation.h"
#include "simpelgeoreference.h"
#include "cornersgeoreference.h"

using namespace Ilwis;

CornersGeoReference::CornersGeoReference() : SimpelGeoReference("corners")
{

}

GeoRefImplementation *CornersGeoReference::create()
{
    return new CornersGeoReference();
}

void CornersGeoReference::envelope(const Envelope &env)
{
    _envelope = env;
}

bool CornersGeoReference::compute()
{
    bool a = size().isNull();
    bool b = _envelope.isValid();
    if (a || !b)
        return false;

    _a12 = _a21 = 0;
    std::vector<double> vec = _envelope.max_corner() - _envelope.min_corner();

    if (abs(vec[0]) < 1e-6 || abs(vec[1]) < 1e-6) {
        return false;
    }
    if (!_centerOfPixel) { // corners of corner pixels
        _a11  = size().xsize() / vec[0];
        double tempy = size().ysize();
        _a22 = - tempy / vec[1];
        _b1 = - _a11 * _envelope.min_corner().x;
        _b2 = - _a22 * _envelope.max_corner().y;
    }
    else { // center of corner pixels
        _a11 = (size().xsize() - 1) / vec[0];
        double v1 = size().ysize() - 1;
        double v2 = vec[1];
        double v3 = -v1/v2;
        _a22 = v3;
        _b1 = 0.5 - _a11 * _envelope.min_corner().x;
        _b2 = 0.5 - _a22 * _envelope.max_corner().y;
    }
    _det = _a11 * _a22;

    return true;
}

Envelope CornersGeoReference::envelope() const
{
    return _envelope;
}

QString CornersGeoReference::typeName()
{
    return "corners";
}

<commit_msg>some wierdness with the compiler prevented the orignal test to succeed. rewrote it to a working version<commit_after>#include "kernel.h"
#include "geometries.h"
#include "ilwisobject.h"
#include "ilwisdata.h"
#include "coordinatesystem.h"
#include "georeference.h"
#include "georefimplementation.h"
#include "simpelgeoreference.h"
#include "cornersgeoreference.h"

using namespace Ilwis;

CornersGeoReference::CornersGeoReference() : SimpelGeoReference("corners")
{

}

GeoRefImplementation *CornersGeoReference::create()
{
    return new CornersGeoReference();
}

void CornersGeoReference::envelope(const Envelope &env)
{
    _envelope = env;
}

bool CornersGeoReference::compute()
{
    bool a = size().isNull();
    bool b = _envelope.isValid();
    if (a || !b)
        return false;

    _a12 = _a21 = 0;
    std::vector<double> vec = _envelope.max_corner() - _envelope.min_corner();

    bool deltaxSmall = (std::abs(vec[0]) < 0.0000001);
    bool deltaySmall = (std::abs(vec[1]) < 0.0000001);
    if ( deltaxSmall || deltaySmall) {
        return false;
    }
    if (!_centerOfPixel) { // corners of corner pixels
        _a11  = size().xsize() / vec[0];
        double tempy = size().ysize();
        _a22 = - tempy / vec[1];
        _b1 = - _a11 * _envelope.min_corner().x;
        _b2 = - _a22 * _envelope.max_corner().y;
    }
    else { // center of corner pixels
        _a11 = (size().xsize() - 1) / vec[0];
        double v1 = size().ysize() - 1;
        double v2 = vec[1];
        double v3 = -v1/v2;
        _a22 = v3;
        _b1 = 0.5 - _a11 * _envelope.min_corner().x;
        _b2 = 0.5 - _a22 * _envelope.max_corner().y;
    }
    _det = _a11 * _a22;

    return true;
}

Envelope CornersGeoReference::envelope() const
{
    return _envelope;
}

QString CornersGeoReference::typeName()
{
    return "corners";
}

<|endoftext|>


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

#include <pangolin/input_record_repeat.h>

using namespace std;

namespace pangolin
{

InputRecordRepeat::InputRecordRepeat(const std::string& var_record_prefix)
    : record(false), play(false), index(-1)
{
    RegisterGuiVarChangedCallback(&InputRecordRepeat::GuiVarChanged,(void*)this,var_record_prefix);
}

InputRecordRepeat::~InputRecordRepeat()
{

}

void InputRecordRepeat::SetIndex(int id)
{
//    if( id < index )
//        Clear();

    index = id;

    while( !play_queue.empty() && play_queue.front().index < index )
    {
        // 'Play' Frameinput
        FrameInput in = play_queue.front();
        play_queue.pop_front();
        Var<std::string> var(in.var);
        var = in.val;
    }
}

void InputRecordRepeat::Record()
{
    ClearBuffer();
    play = false;
    record = true;
}

void InputRecordRepeat::Stop()
{
    record = false;
    play = false;
}

void InputRecordRepeat::ClearBuffer()
{
    index = -1;
    record_queue.clear();
    play_queue.clear();
}

ostream& operator<<(ostream& os, const FrameInput& fi )
{
    os << fi.index << endl << fi.var << endl << fi.val << endl;
    return os;
}

istream& operator>>(istream& is, FrameInput& fi)
{
    is >> fi.index;
    is.ignore(std::numeric_limits<streamsize>::max(),'\n');
    getline(is,fi.var);
    getline(is,fi.val);
    return is;
}

void InputRecordRepeat::SaveBuffer(const std::string& filename)
{
    ofstream f(filename.c_str());

    for( std::list<FrameInput>::const_iterator i = record_queue.begin(); i!=record_queue.end(); ++i )
    {
        f << *i;
    }
}

void InputRecordRepeat::LoadBuffer(const std::string& filename)
{
    record_queue.clear();

    ifstream f(filename.c_str());
    while(f.good())
    {
        FrameInput fi;
        f >> fi;
        if( f.good() )
            record_queue.push_back(fi);
    }
}

void InputRecordRepeat::PlayBuffer()
{
    play_queue = record_queue;

    record = false;
    play = true;
}

void InputRecordRepeat::PlayBuffer(int start, int end)
{
    std::list<FrameInput>::iterator s = record_queue.begin();
    std::list<FrameInput>::iterator e = record_queue.begin();

    for(int i=0; i<start; i++) s++;
    for(int i=0; i<end; i++) e++;

    play_queue.clear();
    play_queue.insert(play_queue.begin(),s,e);

    record = false;
    play = true;
}

int InputRecordRepeat::Size()
{
    return record_queue.size();
}

void InputRecordRepeat::UpdateVariable(const std::string& name )
{
    Var<std::string> var(name);

    if( record )
    {
        FrameInput input;
        input.index = index;
        input.var = name;
        input.val = var.a->Get();
        record_queue.push_back(input);
    }
}

void InputRecordRepeat::GuiVarChanged(void* data, const std::string& name, _Var& _var)
{
    InputRecordRepeat* thisptr = (InputRecordRepeat*)data;

    if( thisptr->record )
    {
        Var<std::string> var(_var);

        FrameInput input;
        input.index = thisptr->index;
        input.var = name;
        input.val = var.a->Get();

        thisptr->record_queue.push_back(input);
    }
}

}
<commit_msg>Include missing header file.<commit_after>/* This file is part of the Pangolin Project.
 * http://github.com/stevenlovegrove/Pangolin
 *
 * Copyright (c) 2013 Steven Lovegrove
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */

#include <pangolin/input_record_repeat.h>

#include <limits>

using namespace std;

namespace pangolin
{

InputRecordRepeat::InputRecordRepeat(const std::string& var_record_prefix)
    : record(false), play(false), index(-1)
{
    RegisterGuiVarChangedCallback(&InputRecordRepeat::GuiVarChanged,(void*)this,var_record_prefix);
}

InputRecordRepeat::~InputRecordRepeat()
{

}

void InputRecordRepeat::SetIndex(int id)
{
//    if( id < index )
//        Clear();

    index = id;

    while( !play_queue.empty() && play_queue.front().index < index )
    {
        // 'Play' Frameinput
        FrameInput in = play_queue.front();
        play_queue.pop_front();
        Var<std::string> var(in.var);
        var = in.val;
    }
}

void InputRecordRepeat::Record()
{
    ClearBuffer();
    play = false;
    record = true;
}

void InputRecordRepeat::Stop()
{
    record = false;
    play = false;
}

void InputRecordRepeat::ClearBuffer()
{
    index = -1;
    record_queue.clear();
    play_queue.clear();
}

ostream& operator<<(ostream& os, const FrameInput& fi )
{
    os << fi.index << endl << fi.var << endl << fi.val << endl;
    return os;
}

istream& operator>>(istream& is, FrameInput& fi)
{
    is >> fi.index;
    is.ignore(std::numeric_limits<streamsize>::max(),'\n');
    getline(is,fi.var);
    getline(is,fi.val);
    return is;
}

void InputRecordRepeat::SaveBuffer(const std::string& filename)
{
    ofstream f(filename.c_str());

    for( std::list<FrameInput>::const_iterator i = record_queue.begin(); i!=record_queue.end(); ++i )
    {
        f << *i;
    }
}

void InputRecordRepeat::LoadBuffer(const std::string& filename)
{
    record_queue.clear();

    ifstream f(filename.c_str());
    while(f.good())
    {
        FrameInput fi;
        f >> fi;
        if( f.good() )
            record_queue.push_back(fi);
    }
}

void InputRecordRepeat::PlayBuffer()
{
    play_queue = record_queue;

    record = false;
    play = true;
}

void InputRecordRepeat::PlayBuffer(int start, int end)
{
    std::list<FrameInput>::iterator s = record_queue.begin();
    std::list<FrameInput>::iterator e = record_queue.begin();

    for(int i=0; i<start; i++) s++;
    for(int i=0; i<end; i++) e++;

    play_queue.clear();
    play_queue.insert(play_queue.begin(),s,e);

    record = false;
    play = true;
}

int InputRecordRepeat::Size()
{
    return record_queue.size();
}

void InputRecordRepeat::UpdateVariable(const std::string& name )
{
    Var<std::string> var(name);

    if( record )
    {
        FrameInput input;
        input.index = index;
        input.var = name;
        input.val = var.a->Get();
        record_queue.push_back(input);
    }
}

void InputRecordRepeat::GuiVarChanged(void* data, const std::string& name, _Var& _var)
{
    InputRecordRepeat* thisptr = (InputRecordRepeat*)data;

    if( thisptr->record )
    {
        Var<std::string> var(_var);

        FrameInput input;
        input.index = thisptr->index;
        input.var = name;
        input.val = var.a->Get();

        thisptr->record_queue.push_back(input);
    }
}

}
<|endoftext|>


<commit_before>/* Please refer to license.txt */

#include "interface.hpp"

#include <iostream>

#include "../graphic/2d/2d.hpp"
#include "../graphic/window/window.hpp"

#include "../file/file.hpp"

namespace GEngine
{

namespace mui
{

Interface::Interface()
{
	//d2d = nullptr;
	cegui_system = nullptr;

	cegui_configfile_path = CEGUI_CONFIGFILE_PATH;
	cegui_logfile_path = CEGUI_LOGFILE_PATH;
	cegui_schemes_path = CEGUI_SCHEMES_PATH;
	cegui_imagesets_path = CEGUI_IMAGESETS_PATH;
	cegui_fonts_path = CEGUI_FONTS_PATH;
	cegui_layouts_path = CEGUI_LAYOUTS_PATH;
	cegui_looknfeels_path = CEGUI_LOOKNFEELS_PATH;
	cegui_luascripts_path = CEGUI_LUASCRIPTS_PATH;

	cegui_resourceprovider = nullptr;
	//cegui_root_window = nullptr;
	//cegui_windowmanager = nullptr;
}

Interface::~Interface()
{
	/*if (d2d)
	{
		d2d = nullptr;
	}

	if (cegui_root_window)
	{
		delete cegui_root_window;
	}*/

	cegui_system = nullptr;
	cegui_resourceprovider = nullptr;
}

bool Interface::initialize(mgfx::d2d::D2D &d2d, std::vector<std::string> cegui_schemes)
{
	//d2d = &_d2d;
	//d2d->window->showMouseCursor(false); //CEGUI's default schemes are fugly with the mouse or don't have one at all. Using default sfml mouse. //TODO: Handle mouse.

	try
	{
		CEGUI::OpenGLRenderer& myRenderer = CEGUI::OpenGLRenderer::create();

		std::string log_directory("");
		mfile::FileManager::separatePathFromFilename(cegui_logfile_path, log_directory);
		//Check if the directory the cegui logfile is going to be kept in exists. It not, create it.
		if (!mfile::FileManager::directoryExists(log_directory))
		{
			mfile::FileManager::mkDir(log_directory);
		}

		CEGUI::System::create(myRenderer, nullptr, nullptr, nullptr, nullptr, cegui_configfile_path, cegui_logfile_path);

		//Initialise the required dirs for the CEGUI DefaultResourceProvider.
		cegui_resourceprovider = static_cast<CEGUI::DefaultResourceProvider*>(CEGUI::System::getSingleton().getResourceProvider());
		cegui_resourceprovider->setResourceGroupDirectory("imagesets", cegui_imagesets_path);
		cegui_resourceprovider->setResourceGroupDirectory("fonts", cegui_fonts_path);
		cegui_resourceprovider->setResourceGroupDirectory("layouts", cegui_layouts_path);
		cegui_resourceprovider->setResourceGroupDirectory("looknfeels", cegui_looknfeels_path);
		cegui_resourceprovider->setResourceGroupDirectory("lua_scripts", cegui_luascripts_path);
		cegui_resourceprovider->setResourceGroupDirectory("schemes", cegui_schemes_path);
		//According to the documentation, this is only really needed if you are using Xerces and need to specify the schemas location.
		//cegui_resourceprovider->setResourceGroupDirectory("schemas", "datafiles/xml_schemas/");

		//Set the default resource groups to be used
		CEGUI::ImageManager::setImagesetDefaultResourceGroup("imagesets");
		CEGUI::Font::setDefaultResourceGroup("fonts");
		CEGUI::Scheme::setDefaultResourceGroup("schemes");
		CEGUI::ScriptModule::setDefaultResourceGroup("lua_scripts");
		CEGUI::WidgetLookManager::setDefaultResourceGroup("looknfeels");
		CEGUI::WindowManager::setDefaultResourceGroup("layouts");
		//This is only needed if the resourceprovider's schemas is set.
		//Setup default group for validation schemas.
		//CEGUI::XMLParser* parser = CEGUI::System::getSingleton().getXMLParser();
		//if (parser->isPropertyPresent("SchemaDefaultResourceGroup"))
		//{
		//	parser->setProperty("SchemaDefaultResourceGroup", "schemas");
		//}

		//Load the schemes specified in cegui_schemes.
		for (std::vector<std::string>::iterator i = cegui_schemes.begin(); i != cegui_schemes.end(); ++i) //TODO: Vector iterator.
		{
			CEGUI::SchemeManager::getSingleton().createFromFile(*i + ".scheme");
			loaded_schemes.push_back(*i); //Save it so we know how to access it later, if needed.
		}

		//TODO: Handle the mouse.
		/*CEGUI::System::getSingleton().getDefaultGUIContext().getMouseCursor().setDefaultImage("GlossySerpent/MouseArrow");
		CEGUI::System::getSingleton().getDefaultGUIContext().getMouseCursor().show();*/

		//CEGUI::System::getSingleton().getDefaultGUIContext().setDefaultTooltipType("GlossySerpent/Tooltip"); //TODO: Set in XML, if possible.

		sf::Vector2i coords = sf::Mouse::getPosition(*d2d.window->window2d);
		CEGUI::System::getSingleton().getDefaultGUIContext().injectMousePosition(coords.x, coords.y);

		//Map SFML Key and Mouse stuff to CEGUI stuff for injecting input into CEGUI.
		mapSFMLKeysToCEGUI();
		mapSFMLMouseToCEGUI();

		d2d.cegui_gui_context = &CEGUI::System::getSingleton().getDefaultGUIContext(); //Point this accordingly.
		d2d.cegui_renderer = &myRenderer;
		d2d.default_d2d = true;
	}
	catch(CEGUI::Exception& e)
	{
		std::cout << "CEGUI Exception:" << e.getMessage().c_str() << "\n";
		return false;
	}

	addD2D(d2d); //Add the D2D to the list of D2Ds.

	return true; //Success.
}

bool Interface::loadFont(std::string filepath)
{
	font.loadFromFile(filepath);

	return true;
}

void Interface::update()
{
	std::vector<mgfx::d2d::D2D* >::iterator iter = windows.begin();
	for (int i = 0; iter != windows.end(); ++iter, ++i)
	{
		mgfx::d2d::D2D *d2d = (*iter); //First point to this so I don't have to type crazy things every time.
		CEGUI::GUIContext& context = *d2d->cegui_gui_context; //Next, point to this so that I don't have to type out the full thing every time.

		context.getMouseCursor().draw(); //Force draw it because it doesn't seem to want to work otherwise.

		//Now, handle injecting events into CEGUI.
		for (unsigned int i = 0; i < d2d->window->events.size(); ++i)
		{
			switch (d2d->window->events[i].type)
			{
			case sf::Event::KeyPressed:
				context.injectKeyDown(sfml_cegui_keymap[d2d->window->events[i].key.code]);
				break;
			case sf::Event::KeyReleased:
				context.injectKeyUp(sfml_cegui_keymap[d2d->window->events[i].key.code]);
				break;
			case sf::Event::TextEntered:
				context.injectChar(static_cast<char>(d2d->window->events[i].text.unicode));
				break;
			case sf::Event::MouseMoved:
				{
					sf::Vector2i coords = sf::Mouse::getPosition(*d2d->window->window2d);
					context.injectMousePosition(coords.x, coords.y);
				}
				break;
			case sf::Event::MouseButtonPressed:
				if (sf::Mouse::isButtonPressed(sf::Mouse::Left))
				{
					context.injectMouseButtonDown(CEGUI::LeftButton);
				}
				else if (sf::Mouse::isButtonPressed(sf::Mouse::Middle))
				{
					context.injectMouseButtonDown(CEGUI::MiddleButton);
				}
				else if (sf::Mouse::isButtonPressed(sf::Mouse::Right))
				{
					context.injectMouseButtonDown(CEGUI::RightButton);
				}
				break;
			case sf::Event::MouseButtonReleased:
				switch (d2d->window->events[i].mouseButton.button)
				{
				case sf::Mouse::Left:
					context.injectMouseButtonUp(CEGUI::LeftButton);
					break;
				case sf::Mouse::Middle:
					context.injectMouseButtonUp(CEGUI::MiddleButton);
					break;
				case sf::Mouse::Right:
					context.injectMouseButtonUp(CEGUI::RightButton);
					break;
				}
				break;
			case sf::Event::MouseWheelMoved:
				context.injectMouseWheelChange(d2d->window->events[i].mouseWheel.delta);
				break;
			default:
				break;
			}
		}
	}

	CEGUI::System::getSingleton().renderAllGUIContexts(); //Render all of CEGUI's stuffs.

	/*CEGUI::GUIContext& context = CEGUI::System::getSingleton().getDefaultGUIContext();
	//First, handle injecting events into CEGUI.
	for (unsigned int i = 0; i < d2d->window->events.size(); ++i)
	{
		switch (d2d->window->events[i].type)
		{
		case sf::Event::KeyPressed:
			context.injectKeyDown(sfml_cegui_keymap[d2d->window->events[i].key.code]);
			break;
		case sf::Event::KeyReleased:
			context.injectKeyUp(sfml_cegui_keymap[d2d->window->events[i].key.code]);
			break;
		case sf::Event::TextEntered:
			context.injectChar(static_cast<char>(d2d->window->events[i].text.unicode));
			break;
		case sf::Event::MouseMoved:
			{
				sf::Vector2i coords = sf::Mouse::getPosition(*d2d->window->window2d);
				context.injectMousePosition(coords.x, coords.y);
			}
			break;
		case sf::Event::MouseButtonPressed:
			if (sf::Mouse::isButtonPressed(sf::Mouse::Left))
			{
				context.injectMouseButtonDown(CEGUI::LeftButton);
			}
			else if (sf::Mouse::isButtonPressed(sf::Mouse::Middle))
			{
				context.injectMouseButtonDown(CEGUI::MiddleButton);
			}
			else if (sf::Mouse::isButtonPressed(sf::Mouse::Right))
			{
				context.injectMouseButtonDown(CEGUI::RightButton);
			}
			break;
		case sf::Event::MouseButtonReleased:
			switch (d2d->window->events[i].mouseButton.button)
			{
			case sf::Mouse::Left:
				context.injectMouseButtonUp(CEGUI::LeftButton);
				break;
			case sf::Mouse::Middle:
				context.injectMouseButtonUp(CEGUI::MiddleButton);
				break;
			case sf::Mouse::Right:
				context.injectMouseButtonUp(CEGUI::RightButton);
				break;
			}
			break;
		case sf::Event::MouseWheelMoved:
			context.injectMouseWheelChange(d2d->window->events[i].mouseWheel.delta);
			break;
		default:
			break;
		}
	}

	//onMouseButtonUp //Use this to check if the frame window's button was pressed.

	CEGUI::System::getSingleton().renderAllGUIContexts(); //Render all of CEGUI's stuffs. //TODO: Make this work properly later.
	//CEGUI::System::getSingleton().getDefaultGUIContext().draw();
	//CEGUI::System::getSingleton().getDefaultGUIContext().getRenderTarget().draw();
	CEGUI::System::getSingleton().getDefaultGUIContext().getMouseCursor().draw(); //Force draw it because it doesn't seem to want to work otherwise.*/
}

CEGUI::Window* Interface::getRootWindow(mgfx::d2d::D2D &d2d)
{
	//return cegui_root_window;
	return d2d.getRootWindow();
}

void Interface::setRootWindow(CEGUI::Window *window, mgfx::d2d::D2D &d2d) //Sets the root window.
{
	/*cegui_root_window = window;
	CEGUI::System::getSingleton().getDefaultGUIContext().setRootWindow(cegui_root_window);*/
	d2d.cegui_root_window = window;
	d2d.cegui_gui_context->setRootWindow(d2d.cegui_root_window);
}

CEGUI::Window* Interface::createVirtualWindowFromLayout(std::string layout/*, bool root*/)
{
	CEGUI::Window *window = CEGUI::WindowManager::getSingleton().loadLayoutFromFile(layout);
	/*if (root) //If it's supposed to be the root window...
	{
		setRootWindow(window); //Set it.
	}*/

	return window;
}

void Interface::addD2D(mgfx::d2d::D2D &d2d)
{
	if (!d2d.cegui_renderer)
	{
		d2d.cegui_renderer = &CEGUI::OpenGLRenderer::create();
	}

	if (!d2d.cegui_gui_context)
	{
		d2d.cegui_gui_context = &CEGUI::System::getSingleton().createGUIContext(d2d.cegui_renderer->getDefaultRenderTarget());
	}

	windows.push_back(&d2d);
}

} //namespace mui

} //namespace GEngine
<commit_msg>Debugging something.<commit_after>/* Please refer to license.txt */

#include "interface.hpp"

#include <iostream>

#include "../graphic/2d/2d.hpp"
#include "../graphic/window/window.hpp"

#include "../file/file.hpp"

namespace GEngine
{

namespace mui
{

Interface::Interface()
{
	//d2d = nullptr;
	cegui_system = nullptr;

	cegui_configfile_path = CEGUI_CONFIGFILE_PATH;
	cegui_logfile_path = CEGUI_LOGFILE_PATH;
	cegui_schemes_path = CEGUI_SCHEMES_PATH;
	cegui_imagesets_path = CEGUI_IMAGESETS_PATH;
	cegui_fonts_path = CEGUI_FONTS_PATH;
	cegui_layouts_path = CEGUI_LAYOUTS_PATH;
	cegui_looknfeels_path = CEGUI_LOOKNFEELS_PATH;
	cegui_luascripts_path = CEGUI_LUASCRIPTS_PATH;

	cegui_resourceprovider = nullptr;
	//cegui_root_window = nullptr;
	//cegui_windowmanager = nullptr;
}

Interface::~Interface()
{
	/*if (d2d)
	{
		d2d = nullptr;
	}

	if (cegui_root_window)
	{
		delete cegui_root_window;
	}*/

	cegui_system = nullptr;
	cegui_resourceprovider = nullptr;
}

bool Interface::initialize(mgfx::d2d::D2D &d2d, std::vector<std::string> cegui_schemes)
{
	//d2d = &_d2d;
	//d2d->window->showMouseCursor(false); //CEGUI's default schemes are fugly with the mouse or don't have one at all. Using default sfml mouse. //TODO: Handle mouse.

	try
	{
		CEGUI::OpenGLRenderer& myRenderer = CEGUI::OpenGLRenderer::create();

		std::string log_directory("");
		mfile::FileManager::separatePathFromFilename(cegui_logfile_path, log_directory);
		//Check if the directory the cegui logfile is going to be kept in exists. It not, create it.
		if (!mfile::FileManager::directoryExists(log_directory))
		{
			mfile::FileManager::mkDir(log_directory);
		}

		CEGUI::System::create(myRenderer, nullptr, nullptr, nullptr, nullptr, cegui_configfile_path, cegui_logfile_path);

		//Initialise the required dirs for the CEGUI DefaultResourceProvider.
		cegui_resourceprovider = static_cast<CEGUI::DefaultResourceProvider*>(CEGUI::System::getSingleton().getResourceProvider());
		cegui_resourceprovider->setResourceGroupDirectory("imagesets", cegui_imagesets_path);
		cegui_resourceprovider->setResourceGroupDirectory("fonts", cegui_fonts_path);
		cegui_resourceprovider->setResourceGroupDirectory("layouts", cegui_layouts_path);
		cegui_resourceprovider->setResourceGroupDirectory("looknfeels", cegui_looknfeels_path);
		cegui_resourceprovider->setResourceGroupDirectory("lua_scripts", cegui_luascripts_path);
		cegui_resourceprovider->setResourceGroupDirectory("schemes", cegui_schemes_path);
		//According to the documentation, this is only really needed if you are using Xerces and need to specify the schemas location.
		//cegui_resourceprovider->setResourceGroupDirectory("schemas", "datafiles/xml_schemas/");

		//Set the default resource groups to be used
		CEGUI::ImageManager::setImagesetDefaultResourceGroup("imagesets");
		CEGUI::Font::setDefaultResourceGroup("fonts");
		CEGUI::Scheme::setDefaultResourceGroup("schemes");
		CEGUI::ScriptModule::setDefaultResourceGroup("lua_scripts");
		CEGUI::WidgetLookManager::setDefaultResourceGroup("looknfeels");
		CEGUI::WindowManager::setDefaultResourceGroup("layouts");
		//This is only needed if the resourceprovider's schemas is set.
		//Setup default group for validation schemas.
		//CEGUI::XMLParser* parser = CEGUI::System::getSingleton().getXMLParser();
		//if (parser->isPropertyPresent("SchemaDefaultResourceGroup"))
		//{
		//	parser->setProperty("SchemaDefaultResourceGroup", "schemas");
		//}

		//Load the schemes specified in cegui_schemes.
		for (std::vector<std::string>::iterator i = cegui_schemes.begin(); i != cegui_schemes.end(); ++i) //TODO: Vector iterator.
		{
			CEGUI::SchemeManager::getSingleton().createFromFile(*i + ".scheme");
			loaded_schemes.push_back(*i); //Save it so we know how to access it later, if needed.
		}

		//TODO: Handle the mouse.
		/*CEGUI::System::getSingleton().getDefaultGUIContext().getMouseCursor().setDefaultImage("GlossySerpent/MouseArrow");
		CEGUI::System::getSingleton().getDefaultGUIContext().getMouseCursor().show();*/

		//CEGUI::System::getSingleton().getDefaultGUIContext().setDefaultTooltipType("GlossySerpent/Tooltip"); //TODO: Set in XML, if possible.

		sf::Vector2i coords = sf::Mouse::getPosition(*d2d.window->window2d);
		CEGUI::System::getSingleton().getDefaultGUIContext().injectMousePosition(coords.x, coords.y);

		//Map SFML Key and Mouse stuff to CEGUI stuff for injecting input into CEGUI.
		mapSFMLKeysToCEGUI();
		mapSFMLMouseToCEGUI();

		d2d.cegui_gui_context = &CEGUI::System::getSingleton().getDefaultGUIContext(); //Point this accordingly.
		d2d.cegui_renderer = &myRenderer;
		d2d.default_d2d = true;
	}
	catch(CEGUI::Exception& e)
	{
		std::cout << "CEGUI Exception:" << e.getMessage().c_str() << "\n";
		return false;
	}

	addD2D(d2d); //Add the D2D to the list of D2Ds.

	return true; //Success.
}

bool Interface::loadFont(std::string filepath)
{
	font.loadFromFile(filepath);

	return true;
}

void Interface::update()
{
	std::vector<mgfx::d2d::D2D* >::iterator iter = windows.begin();
	//for (int i = 0; iter != windows.end(); ++iter, ++i)
	for (int i = 0; i < windows.size(); ++i)
	{
		//mgfx::d2d::D2D *d2d = (*iter); //First point to this so I don't have to type crazy things every time.
		mgfx::d2d::D2D *d2d = windows[i]; //First point to this so I don't have to type crazy things every time.
		CEGUI::GUIContext& context = *d2d->cegui_gui_context; //Next, point to this so that I don't have to type out the full thing every time.

		context.getMouseCursor().draw(); //Force draw it because it doesn't seem to want to work otherwise.

		//Now, handle injecting events into CEGUI.
		for (unsigned int i = 0; i < d2d->window->events.size(); ++i)
		{
			switch (d2d->window->events[i].type)
			{
			case sf::Event::KeyPressed:
				context.injectKeyDown(sfml_cegui_keymap[d2d->window->events[i].key.code]);
				break;
			case sf::Event::KeyReleased:
				context.injectKeyUp(sfml_cegui_keymap[d2d->window->events[i].key.code]);
				break;
			case sf::Event::TextEntered:
				context.injectChar(static_cast<char>(d2d->window->events[i].text.unicode));
				break;
			case sf::Event::MouseMoved:
				{
					sf::Vector2i coords = sf::Mouse::getPosition(*d2d->window->window2d);
					context.injectMousePosition(coords.x, coords.y);
				}
				break;
			case sf::Event::MouseButtonPressed:
				if (sf::Mouse::isButtonPressed(sf::Mouse::Left))
				{
					context.injectMouseButtonDown(CEGUI::LeftButton);
				}
				else if (sf::Mouse::isButtonPressed(sf::Mouse::Middle))
				{
					context.injectMouseButtonDown(CEGUI::MiddleButton);
				}
				else if (sf::Mouse::isButtonPressed(sf::Mouse::Right))
				{
					context.injectMouseButtonDown(CEGUI::RightButton);
				}
				break;
			case sf::Event::MouseButtonReleased:
				switch (d2d->window->events[i].mouseButton.button)
				{
				case sf::Mouse::Left:
					context.injectMouseButtonUp(CEGUI::LeftButton);
					break;
				case sf::Mouse::Middle:
					context.injectMouseButtonUp(CEGUI::MiddleButton);
					break;
				case sf::Mouse::Right:
					context.injectMouseButtonUp(CEGUI::RightButton);
					break;
				}
				break;
			case sf::Event::MouseWheelMoved:
				context.injectMouseWheelChange(d2d->window->events[i].mouseWheel.delta);
				break;
			default:
				break;
			}
		}
	}

	CEGUI::System::getSingleton().renderAllGUIContexts(); //Render all of CEGUI's stuffs.

	/*CEGUI::GUIContext& context = CEGUI::System::getSingleton().getDefaultGUIContext();
	//First, handle injecting events into CEGUI.
	for (unsigned int i = 0; i < d2d->window->events.size(); ++i)
	{
		switch (d2d->window->events[i].type)
		{
		case sf::Event::KeyPressed:
			context.injectKeyDown(sfml_cegui_keymap[d2d->window->events[i].key.code]);
			break;
		case sf::Event::KeyReleased:
			context.injectKeyUp(sfml_cegui_keymap[d2d->window->events[i].key.code]);
			break;
		case sf::Event::TextEntered:
			context.injectChar(static_cast<char>(d2d->window->events[i].text.unicode));
			break;
		case sf::Event::MouseMoved:
			{
				sf::Vector2i coords = sf::Mouse::getPosition(*d2d->window->window2d);
				context.injectMousePosition(coords.x, coords.y);
			}
			break;
		case sf::Event::MouseButtonPressed:
			if (sf::Mouse::isButtonPressed(sf::Mouse::Left))
			{
				context.injectMouseButtonDown(CEGUI::LeftButton);
			}
			else if (sf::Mouse::isButtonPressed(sf::Mouse::Middle))
			{
				context.injectMouseButtonDown(CEGUI::MiddleButton);
			}
			else if (sf::Mouse::isButtonPressed(sf::Mouse::Right))
			{
				context.injectMouseButtonDown(CEGUI::RightButton);
			}
			break;
		case sf::Event::MouseButtonReleased:
			switch (d2d->window->events[i].mouseButton.button)
			{
			case sf::Mouse::Left:
				context.injectMouseButtonUp(CEGUI::LeftButton);
				break;
			case sf::Mouse::Middle:
				context.injectMouseButtonUp(CEGUI::MiddleButton);
				break;
			case sf::Mouse::Right:
				context.injectMouseButtonUp(CEGUI::RightButton);
				break;
			}
			break;
		case sf::Event::MouseWheelMoved:
			context.injectMouseWheelChange(d2d->window->events[i].mouseWheel.delta);
			break;
		default:
			break;
		}
	}

	//onMouseButtonUp //Use this to check if the frame window's button was pressed.

	CEGUI::System::getSingleton().renderAllGUIContexts(); //Render all of CEGUI's stuffs. //TODO: Make this work properly later.
	//CEGUI::System::getSingleton().getDefaultGUIContext().draw();
	//CEGUI::System::getSingleton().getDefaultGUIContext().getRenderTarget().draw();
	CEGUI::System::getSingleton().getDefaultGUIContext().getMouseCursor().draw(); //Force draw it because it doesn't seem to want to work otherwise.*/
}

CEGUI::Window* Interface::getRootWindow(mgfx::d2d::D2D &d2d)
{
	//return cegui_root_window;
	return d2d.getRootWindow();
}

void Interface::setRootWindow(CEGUI::Window *window, mgfx::d2d::D2D &d2d) //Sets the root window.
{
	/*cegui_root_window = window;
	CEGUI::System::getSingleton().getDefaultGUIContext().setRootWindow(cegui_root_window);*/
	d2d.cegui_root_window = window;
	d2d.cegui_gui_context->setRootWindow(d2d.cegui_root_window);
}

CEGUI::Window* Interface::createVirtualWindowFromLayout(std::string layout/*, bool root*/)
{
	CEGUI::Window *window = CEGUI::WindowManager::getSingleton().loadLayoutFromFile(layout);
	/*if (root) //If it's supposed to be the root window...
	{
		setRootWindow(window); //Set it.
	}*/

	return window;
}

void Interface::addD2D(mgfx::d2d::D2D &d2d)
{
	if (!d2d.cegui_renderer)
	{
		d2d.cegui_renderer = &CEGUI::OpenGLRenderer::create();
	}

	if (!d2d.cegui_gui_context)
	{
		d2d.cegui_gui_context = &CEGUI::System::getSingleton().createGUIContext(d2d.cegui_renderer->getDefaultRenderTarget());
	}

	windows.push_back(&d2d);
}

} //namespace mui

} //namespace GEngine
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: printdlg.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2008-01-29 16:11: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 _SV_PRINTDLG_HXX_
#define _SV_PRINTDLG_HXX_

#ifndef INCLUDED_SVTDLLAPI_H
#include "svtools/svtdllapi.h"
#endif

#ifndef _VCL_DIALOG_HXX
#include <vcl/dialog.hxx>
#endif
#ifndef _VCL_FIXED_HXX
#include <vcl/fixed.hxx>
#endif
#ifndef _VCL_BUTTON_HXX
#include <vcl/button.hxx>
#endif
#ifndef _VCL_GROUP_HXX
#include <vcl/group.hxx>
#endif
#ifndef _VCL_FIELD_HXX
#include <vcl/field.hxx>
#endif
#ifndef _VCL_EDIT_HXX
#include <vcl/edit.hxx>
#endif
#ifndef _VCL_LSTBOX_HXX
#include <vcl/lstbox.hxx>
#endif
#ifndef _STDCTRL_HXX
#include <svtools/stdctrl.hxx>
#endif

class Printer;
class QueueInfo;
struct SvtPrinterImpl;

// ---------------------
// - PrintDialog-Types -
// ---------------------

enum PrintDialogRange{
    PRINTDIALOG_ALL, PRINTDIALOG_SELECTION, PRINTDIALOG_FROMTO, PRINTDIALOG_RANGE };

enum PrintSheetRange
{
    PRINTSHEETS_ALL,
    PRINTSHEETS_SELECTED_SHEETS,
    PRINTSHEETS_SELECTED_CELLS
};

// ---------------
// - PrintDialog -
// ---------------

class SVT_DLLPUBLIC PrintDialog : public ModalDialog
{
private:
    FixedLine           maFlPrinter;
    FixedText           maFtName;
    ListBox             maLbName;
    PushButton          maBtnProperties;
    FixedText           maFtStatus;
    FixedInfo           maFiStatus;
    FixedText           maFtType;
    FixedInfo           maFiType;
    FixedText           maFtLocation;
    FixedInfo           maFiLocation;
    FixedText           maFtComment;
    FixedInfo           maFiComment;

    // "Print to file" or "Fax number"
    CheckBox            maCbxFilePrint;
    FixedInfo           maFiPrintFile;
    FixedText           maFiFaxNo;
    Edit                maEdtFaxNo;
    //PushButton         maBtnBrowse_nomore;

    // "Print"
    FixedLine           maFlPrint;
    RadioButton         maRbtAllSheets;
    RadioButton         maRbtSelectedSheets;
    RadioButton         maRbtSelectedCells;

    // "Print range"
    FixedLine           maFlPrintRange;
    RadioButton         maRbtAll;
    RadioButton         maRbtPages;
    RadioButton         maRbtSelection;
    Edit                maEdtPages;

    FixedLine           maFlSepCopiesRange;

    // "Copies"
    FixedLine           maFlCopies;
    FixedText           maFtCopies;
    NumericField        maNumCopies;
    FixedImage          maImgCollate;
    FixedImage          maImgNotCollate;
    CheckBox            maCbxCollate;

    FixedLine           maFlSepButtonLine;
    PushButton          maBtnOptions;
    OKButton            maBtnOK;
    CancelButton        maBtnCancel;
    HelpButton          maBtnHelp;

    AutoTimer           maStatusTimer;
    Printer*            mpPrinter;
    SvtPrinterImpl*     mpPrinterImpl;

    XubString           maRangeText;
    USHORT              mnCopyCount;
    USHORT              mnFirstPage;
    USHORT              mnLastPage;
    USHORT              mnMinPage;
    USHORT              mnMaxPage;
    PrintDialogRange    meCheckRange;
    BOOL                mbAll;
    BOOL                mbSelection;
    BOOL                mbFromTo;
    BOOL                mbRange;
    BOOL                mbCollate;
    BOOL                mbCollateCheck;
    BOOL                mbOptions;
    bool                mbWithSheetsAndCells;
    Link                maOptionsHdlLink; // Link zum Options-Handler
    Link                maOKHdlLink;      // Link zum OK-Handler

    String              maAllFilterStr;

    SVT_DLLPRIVATE void     ImplCheckOK();
    SVT_DLLPRIVATE void     ImplInitControls();
    SVT_DLLPRIVATE void     ImplFillDialogData();
    SVT_DLLPRIVATE void     ImplSetInfo();
    SVT_DLLPRIVATE void     ImplSetImages();
    SVT_DLLPRIVATE bool     ImplGetFilename();

    DECL_DLLPRIVATE_LINK(   ImplPropertiesHdl, void* );
    DECL_DLLPRIVATE_LINK(   ImplChangePrinterHdl, void* );
    DECL_DLLPRIVATE_LINK(   ImplModifyControlHdl, void* );
    DECL_DLLPRIVATE_LINK(   ImplStatusHdl, Timer* );

public:
    PrintDialog( Window* pWindow, bool bWithSheetsAndCells );
    ~PrintDialog();

    virtual long        OK();
    virtual long        ClickOptionsHdl();

    void                SetPrinter( Printer* pNewPrinter ) { mpPrinter = pNewPrinter; }
    Printer*            GetPrinter() const { return mpPrinter; }

    inline bool         IsSheetRangeAvailable() const { return mbWithSheetsAndCells; }
    void                EnableSheetRange( bool bEnable, PrintSheetRange eRange );
    bool                IsSheetRangeEnabled( PrintSheetRange eRange ) const;
    void                CheckSheetRange( PrintSheetRange eRange );
    PrintSheetRange     GetCheckedSheetRange() const;
    bool                IsSheetRangeChecked( PrintSheetRange eRange ) const;

    void                EnableRange( PrintDialogRange eRange );
    void                DisableRange( PrintDialogRange eRange );
    BOOL                IsRangeEnabled( PrintDialogRange eRange ) const;

    void                CheckRange( PrintDialogRange eRange = PRINTDIALOG_ALL )
                            { meCheckRange = eRange; }
    PrintDialogRange    GetCheckedRange() const { return meCheckRange; }
    BOOL                IsRangeChecked( PrintDialogRange eRange ) const;

    void                SetRangeText( const XubString& rRange ) { maRangeText = rRange; }
    const XubString&    GetRangeText() const { return maRangeText; }

    void                SetFirstPage( USHORT nPage = 0 );
    USHORT              GetFirstPage() const { return mnFirstPage; }
    void                SetLastPage( USHORT nPage = 0 );
    USHORT              GetLastPage() const { return mnLastPage; }

    void                SetMinPage( USHORT nPage = 1 ) { mnMinPage = nPage; }
    USHORT              GetMinPage() const { return mnMinPage; }
    void                SetMaxPage( USHORT nPage = 65535 ) { mnMaxPage = nPage; }
    USHORT              GetMaxPage() const { return mnMaxPage; }

    void                SetCopyCount( USHORT nCopies = 1 ) { mnCopyCount = nCopies; }
    USHORT              GetCopyCount() const { return mnCopyCount; }

    void                EnableCollate( BOOL bEnable = TRUE )
                            { mbCollate = bEnable; }
    BOOL                IsCollateEnabled() const { return mbCollate; }
    void                CheckCollate( BOOL bCheck = TRUE )
                            { mbCollateCheck = bCheck; }
    BOOL                IsCollateChecked() const { return mbCollateCheck; }

    void                ShowOptionsButton( BOOL bShow = TRUE )
                            { mbOptions = bShow; }
    BOOL                IsOptionsButtonVisible() const { return mbOptions; }

    void                SetOptionsHdl( const Link& rLink ) { maOptionsHdlLink = rLink; }
    const Link&         GetOptionsHdl() const { return maOptionsHdlLink; }

    void                SetOKHdl( const Link& rLink ) { maOKHdlLink = rLink; }
    const Link&         GetOKHdl() const { return maOKHdlLink; }

    virtual void        DataChanged( const DataChangedEvent& rDCEvt );
    virtual long        Notify( NotifyEvent& rNEvt );

    virtual short       Execute();

    void                DisableHelp();
};

inline void PrintDialog::EnableRange( PrintDialogRange eRange )
{
    if ( eRange == PRINTDIALOG_ALL )
        mbAll = TRUE;
    else if ( eRange == PRINTDIALOG_SELECTION )
        mbSelection = TRUE;
    else if ( eRange == PRINTDIALOG_FROMTO )
        mbFromTo = TRUE;
    else
        mbRange = TRUE;
}

inline void PrintDialog::DisableRange( PrintDialogRange eRange )
{
    if ( eRange == PRINTDIALOG_ALL )
        mbAll = FALSE;
    else if ( eRange == PRINTDIALOG_SELECTION )
        mbSelection = FALSE;
    else if ( eRange == PRINTDIALOG_FROMTO )
        mbFromTo = FALSE;
    else
        mbRange = FALSE;
}

inline BOOL PrintDialog::IsRangeEnabled( PrintDialogRange eRange ) const
{
    BOOL bRet;

    if ( eRange == PRINTDIALOG_ALL )
        bRet = mbAll;
    else if ( eRange == PRINTDIALOG_SELECTION )
        bRet = mbSelection;
    else if ( eRange == PRINTDIALOG_FROMTO )
        bRet = mbFromTo;
    else
        bRet = mbRange;

    return bRet;
}

inline BOOL PrintDialog::IsRangeChecked( PrintDialogRange eRange ) const
{
    if ( eRange == meCheckRange )
        return TRUE;
    else
        return FALSE;
}

inline void PrintDialog::SetFirstPage( USHORT nPage )
{
    mnFirstPage = nPage;
    if ( nPage && (nPage < mnMinPage) )
        mnMinPage = nPage;
}

inline void PrintDialog::SetLastPage( USHORT nPage )
{
    mnLastPage = nPage;
    if ( nPage && (nPage > mnMaxPage) )
        mnMaxPage = nPage;
}

#endif // _SV_PRINTDLG_HXX_

<commit_msg>INTEGRATION: CWS changefileheader (1.4.74); FILE MERGED 2008/04/01 12:43:14 thb 1.4.74.2: #i85898# Stripping all external header guards 2008/03/31 13:01:07 rt 1.4.74.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: printdlg.hxx,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef _SV_PRINTDLG_HXX_
#define _SV_PRINTDLG_HXX_

#include "svtools/svtdllapi.h"

#ifndef _VCL_DIALOG_HXX
#include <vcl/dialog.hxx>
#endif
#ifndef _VCL_FIXED_HXX
#include <vcl/fixed.hxx>
#endif
#ifndef _VCL_BUTTON_HXX
#include <vcl/button.hxx>
#endif
#ifndef _VCL_GROUP_HXX
#include <vcl/group.hxx>
#endif
#ifndef _VCL_FIELD_HXX
#include <vcl/field.hxx>
#endif
#ifndef _VCL_EDIT_HXX
#include <vcl/edit.hxx>
#endif
#ifndef _VCL_LSTBOX_HXX
#include <vcl/lstbox.hxx>
#endif
#include <svtools/stdctrl.hxx>

class Printer;
class QueueInfo;
struct SvtPrinterImpl;

// ---------------------
// - PrintDialog-Types -
// ---------------------

enum PrintDialogRange{
    PRINTDIALOG_ALL, PRINTDIALOG_SELECTION, PRINTDIALOG_FROMTO, PRINTDIALOG_RANGE };

enum PrintSheetRange
{
    PRINTSHEETS_ALL,
    PRINTSHEETS_SELECTED_SHEETS,
    PRINTSHEETS_SELECTED_CELLS
};

// ---------------
// - PrintDialog -
// ---------------

class SVT_DLLPUBLIC PrintDialog : public ModalDialog
{
private:
    FixedLine           maFlPrinter;
    FixedText           maFtName;
    ListBox             maLbName;
    PushButton          maBtnProperties;
    FixedText           maFtStatus;
    FixedInfo           maFiStatus;
    FixedText           maFtType;
    FixedInfo           maFiType;
    FixedText           maFtLocation;
    FixedInfo           maFiLocation;
    FixedText           maFtComment;
    FixedInfo           maFiComment;

    // "Print to file" or "Fax number"
    CheckBox            maCbxFilePrint;
    FixedInfo           maFiPrintFile;
    FixedText           maFiFaxNo;
    Edit                maEdtFaxNo;
    //PushButton         maBtnBrowse_nomore;

    // "Print"
    FixedLine           maFlPrint;
    RadioButton         maRbtAllSheets;
    RadioButton         maRbtSelectedSheets;
    RadioButton         maRbtSelectedCells;

    // "Print range"
    FixedLine           maFlPrintRange;
    RadioButton         maRbtAll;
    RadioButton         maRbtPages;
    RadioButton         maRbtSelection;
    Edit                maEdtPages;

    FixedLine           maFlSepCopiesRange;

    // "Copies"
    FixedLine           maFlCopies;
    FixedText           maFtCopies;
    NumericField        maNumCopies;
    FixedImage          maImgCollate;
    FixedImage          maImgNotCollate;
    CheckBox            maCbxCollate;

    FixedLine           maFlSepButtonLine;
    PushButton          maBtnOptions;
    OKButton            maBtnOK;
    CancelButton        maBtnCancel;
    HelpButton          maBtnHelp;

    AutoTimer           maStatusTimer;
    Printer*            mpPrinter;
    SvtPrinterImpl*     mpPrinterImpl;

    XubString           maRangeText;
    USHORT              mnCopyCount;
    USHORT              mnFirstPage;
    USHORT              mnLastPage;
    USHORT              mnMinPage;
    USHORT              mnMaxPage;
    PrintDialogRange    meCheckRange;
    BOOL                mbAll;
    BOOL                mbSelection;
    BOOL                mbFromTo;
    BOOL                mbRange;
    BOOL                mbCollate;
    BOOL                mbCollateCheck;
    BOOL                mbOptions;
    bool                mbWithSheetsAndCells;
    Link                maOptionsHdlLink; // Link zum Options-Handler
    Link                maOKHdlLink;      // Link zum OK-Handler

    String              maAllFilterStr;

    SVT_DLLPRIVATE void     ImplCheckOK();
    SVT_DLLPRIVATE void     ImplInitControls();
    SVT_DLLPRIVATE void     ImplFillDialogData();
    SVT_DLLPRIVATE void     ImplSetInfo();
    SVT_DLLPRIVATE void     ImplSetImages();
    SVT_DLLPRIVATE bool     ImplGetFilename();

    DECL_DLLPRIVATE_LINK(   ImplPropertiesHdl, void* );
    DECL_DLLPRIVATE_LINK(   ImplChangePrinterHdl, void* );
    DECL_DLLPRIVATE_LINK(   ImplModifyControlHdl, void* );
    DECL_DLLPRIVATE_LINK(   ImplStatusHdl, Timer* );

public:
    PrintDialog( Window* pWindow, bool bWithSheetsAndCells );
    ~PrintDialog();

    virtual long        OK();
    virtual long        ClickOptionsHdl();

    void                SetPrinter( Printer* pNewPrinter ) { mpPrinter = pNewPrinter; }
    Printer*            GetPrinter() const { return mpPrinter; }

    inline bool         IsSheetRangeAvailable() const { return mbWithSheetsAndCells; }
    void                EnableSheetRange( bool bEnable, PrintSheetRange eRange );
    bool                IsSheetRangeEnabled( PrintSheetRange eRange ) const;
    void                CheckSheetRange( PrintSheetRange eRange );
    PrintSheetRange     GetCheckedSheetRange() const;
    bool                IsSheetRangeChecked( PrintSheetRange eRange ) const;

    void                EnableRange( PrintDialogRange eRange );
    void                DisableRange( PrintDialogRange eRange );
    BOOL                IsRangeEnabled( PrintDialogRange eRange ) const;

    void                CheckRange( PrintDialogRange eRange = PRINTDIALOG_ALL )
                            { meCheckRange = eRange; }
    PrintDialogRange    GetCheckedRange() const { return meCheckRange; }
    BOOL                IsRangeChecked( PrintDialogRange eRange ) const;

    void                SetRangeText( const XubString& rRange ) { maRangeText = rRange; }
    const XubString&    GetRangeText() const { return maRangeText; }

    void                SetFirstPage( USHORT nPage = 0 );
    USHORT              GetFirstPage() const { return mnFirstPage; }
    void                SetLastPage( USHORT nPage = 0 );
    USHORT              GetLastPage() const { return mnLastPage; }

    void                SetMinPage( USHORT nPage = 1 ) { mnMinPage = nPage; }
    USHORT              GetMinPage() const { return mnMinPage; }
    void                SetMaxPage( USHORT nPage = 65535 ) { mnMaxPage = nPage; }
    USHORT              GetMaxPage() const { return mnMaxPage; }

    void                SetCopyCount( USHORT nCopies = 1 ) { mnCopyCount = nCopies; }
    USHORT              GetCopyCount() const { return mnCopyCount; }

    void                EnableCollate( BOOL bEnable = TRUE )
                            { mbCollate = bEnable; }
    BOOL                IsCollateEnabled() const { return mbCollate; }
    void                CheckCollate( BOOL bCheck = TRUE )
                            { mbCollateCheck = bCheck; }
    BOOL                IsCollateChecked() const { return mbCollateCheck; }

    void                ShowOptionsButton( BOOL bShow = TRUE )
                            { mbOptions = bShow; }
    BOOL                IsOptionsButtonVisible() const { return mbOptions; }

    void                SetOptionsHdl( const Link& rLink ) { maOptionsHdlLink = rLink; }
    const Link&         GetOptionsHdl() const { return maOptionsHdlLink; }

    void                SetOKHdl( const Link& rLink ) { maOKHdlLink = rLink; }
    const Link&         GetOKHdl() const { return maOKHdlLink; }

    virtual void        DataChanged( const DataChangedEvent& rDCEvt );
    virtual long        Notify( NotifyEvent& rNEvt );

    virtual short       Execute();

    void                DisableHelp();
};

inline void PrintDialog::EnableRange( PrintDialogRange eRange )
{
    if ( eRange == PRINTDIALOG_ALL )
        mbAll = TRUE;
    else if ( eRange == PRINTDIALOG_SELECTION )
        mbSelection = TRUE;
    else if ( eRange == PRINTDIALOG_FROMTO )
        mbFromTo = TRUE;
    else
        mbRange = TRUE;
}

inline void PrintDialog::DisableRange( PrintDialogRange eRange )
{
    if ( eRange == PRINTDIALOG_ALL )
        mbAll = FALSE;
    else if ( eRange == PRINTDIALOG_SELECTION )
        mbSelection = FALSE;
    else if ( eRange == PRINTDIALOG_FROMTO )
        mbFromTo = FALSE;
    else
        mbRange = FALSE;
}

inline BOOL PrintDialog::IsRangeEnabled( PrintDialogRange eRange ) const
{
    BOOL bRet;

    if ( eRange == PRINTDIALOG_ALL )
        bRet = mbAll;
    else if ( eRange == PRINTDIALOG_SELECTION )
        bRet = mbSelection;
    else if ( eRange == PRINTDIALOG_FROMTO )
        bRet = mbFromTo;
    else
        bRet = mbRange;

    return bRet;
}

inline BOOL PrintDialog::IsRangeChecked( PrintDialogRange eRange ) const
{
    if ( eRange == meCheckRange )
        return TRUE;
    else
        return FALSE;
}

inline void PrintDialog::SetFirstPage( USHORT nPage )
{
    mnFirstPage = nPage;
    if ( nPage && (nPage < mnMinPage) )
        mnMinPage = nPage;
}

inline void PrintDialog::SetLastPage( USHORT nPage )
{
    mnLastPage = nPage;
    if ( nPage && (nPage > mnMaxPage) )
        mnMaxPage = nPage;
}

#endif // _SV_PRINTDLG_HXX_

<|endoftext|>


<commit_before>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/core/framework/resource_mgr.h"

#include "tensorflow/core/framework/device_attributes.pb.h"
#include "tensorflow/core/framework/node_def.pb.h"
#include "tensorflow/core/framework/node_def_util.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/gtl/map_util.h"
#include "tensorflow/core/lib/strings/scanner.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/lib/strings/stringprintf.h"
#include "tensorflow/core/platform/demangle.h"

namespace tensorflow {
ResourceHandle MakeResourceHandle(OpKernelContext* ctx, const string& container,
                                  const string& name,
                                  const TypeIndex& type_index) {
  ResourceHandle result;
  result.set_device(ctx->device()->attributes().name());
  string actual_container;
  if (!container.empty()) {
    actual_container = container;
  } else {
    actual_container = ctx->resource_manager()->default_container();
  }
  result.set_container(actual_container);
  result.set_name(name);
  result.set_hash_code(type_index.hash_code());
  result.set_maybe_type_name(type_index.name());
  return result;
}

Status MakeResourceHandleToOutput(OpKernelContext* context, int output_index,
                                  const string& container, const string& name,
                                  const TypeIndex& type_index) {
  Tensor* handle;
  TF_RETURN_IF_ERROR(
      context->allocate_output(output_index, TensorShape({}), &handle));
  handle->scalar<ResourceHandle>()() =
      MakeResourceHandle(context, container, name, type_index);
  return Status::OK();
}

namespace internal {

Status ValidateDevice(OpKernelContext* ctx, const ResourceHandle& p) {
  if (ctx->device()->attributes().name() != p.device()) {
    return errors::InvalidArgument(
        "Trying to access resource ", p.name(), " located in device ",
        p.device(), " from device ", ctx->device()->attributes().name());
  }
  return Status::OK();
}

}  // end namespace internal

Status ResourceMgr::InsertDebugTypeName(uint64 hash_code,
                                        const string& type_name) {
  auto iter = debug_type_names_.emplace(hash_code, type_name);
  if (iter.first->second != type_name) {
    return errors::AlreadyExists("Duplicate hash code found for type ",
                                 type_name);
  }
  return Status::OK();
}

const char* ResourceMgr::DebugTypeName(uint64 hash_code) const {
  auto type_name_iter = debug_type_names_.find(hash_code);
  if (type_name_iter == debug_type_names_.end()) {
    return "<unknown>";
  } else {
    return type_name_iter->second.c_str();
  }
}

ResourceMgr::ResourceMgr() : default_container_("localhost") {}

ResourceMgr::ResourceMgr(const string& default_container)
    : default_container_(default_container) {}

ResourceMgr::~ResourceMgr() { Clear(); }

void ResourceMgr::Clear() {
  mutex_lock l(mu_);
  for (const auto& p : containers_) {
    for (const auto& q : *p.second) {
      q.second->Unref();
    }
    delete p.second;
  }
  containers_.clear();
}

string ResourceMgr::DebugString() const {
  mutex_lock l(mu_);
  struct Line {
    const string* container;
    const string type;
    const string* resource;
    const string detail;
  };
  std::vector<Line> lines;
  for (const auto& p : containers_) {
    const string& container = p.first;
    for (const auto& q : *p.second) {
      const Key& key = q.first;
      const char* type = DebugTypeName(key.first);
      const string& resource = key.second;
      Line l{&container, port::Demangle(type), &resource,
             q.second->DebugString()};
      lines.push_back(l);
    }
  }
  std::vector<string> text;
  text.reserve(lines.size());
  for (const Line& line : lines) {
    text.push_back(strings::Printf(
        "%-20s | %-40s | %-40s | %-s", line.container->c_str(),
        line.type.c_str(), line.resource->c_str(), line.detail.c_str()));
  }
  std::sort(text.begin(), text.end());
  return str_util::Join(text, "\n");
}

Status ResourceMgr::DoCreate(const string& container, TypeIndex type,
                             const string& name, ResourceBase* resource) {
  Container** b = &containers_[container];
  if (*b == nullptr) {
    *b = new Container;
  }
  if ((*b)->insert({{type.hash_code(), name}, resource}).second) {
    TF_RETURN_IF_ERROR(InsertDebugTypeName(type.hash_code(), type.name()));
    return Status::OK();
  }
  resource->Unref();
  return errors::AlreadyExists("Resource ", container, "/", name, "/",
                               type.name());
}

Status ResourceMgr::DoLookup(const string& container, TypeIndex type,
                             const string& name,
                             ResourceBase** resource) const {
  const Container* b = gtl::FindPtrOrNull(containers_, container);
  if (b == nullptr) {
    return errors::NotFound("Container ", container,
                            " does not exist. (Could not find resource: ",
                            container, "/", name, ")");
  }
  auto r = gtl::FindPtrOrNull(*b, {type.hash_code(), name});
  if (r == nullptr) {
    return errors::NotFound("Resource ", container, "/", name, "/", type.name(),
                            " does not exist.");
  }
  *resource = const_cast<ResourceBase*>(r);
  (*resource)->Ref();
  return Status::OK();
}

Status ResourceMgr::DoDelete(const string& container, uint64 type_hash_code,
                             const string& resource_name,
                             const string& type_name) {
  ResourceBase* base = nullptr;
  {
    mutex_lock l(mu_);
    Container* b = gtl::FindPtrOrNull(containers_, container);
    if (b == nullptr) {
      return errors::NotFound("Container ", container, " does not exist.");
    }
    auto iter = b->find({type_hash_code, resource_name});
    if (iter == b->end()) {
      return errors::NotFound("Resource ", container, "/", resource_name, "/",
                              type_name, " does not exist.");
    }
    base = iter->second;
    b->erase(iter);
  }
  CHECK(base != nullptr);
  base->Unref();
  return Status::OK();
}

Status ResourceMgr::DoDelete(const string& container, TypeIndex type,
                             const string& resource_name) {
  return DoDelete(container, type.hash_code(), resource_name, type.name());
}

Status ResourceMgr::Delete(const ResourceHandle& handle) {
  return DoDelete(handle.container(), handle.hash_code(), handle.name(),
                  "<unknown>");
}

Status ResourceMgr::Cleanup(const string& container) {
  Container* b = nullptr;
  {
    mutex_lock l(mu_);
    auto iter = containers_.find(container);
    if (iter == containers_.end()) {
      // Nothing to cleanup, it's OK.
      return Status::OK();
    }
    b = iter->second;
    containers_.erase(iter);
  }
  CHECK(b != nullptr);
  for (const auto& p : *b) {
    p.second->Unref();
  }
  delete b;
  return Status::OK();
}

static bool IsValidContainerName(StringPiece s) {
  using ::tensorflow::strings::Scanner;
  return Scanner(s)
      .One(Scanner::LETTER_DIGIT_DOT)
      .Any(Scanner::LETTER_DIGIT_DASH_DOT_SLASH)
      .Eos()
      .GetResult();
}

Status ContainerInfo::Init(ResourceMgr* rmgr, const NodeDef& ndef,
                           bool use_node_name_as_default) {
  CHECK(rmgr);
  rmgr_ = rmgr;
  string attr_container;
  TF_RETURN_IF_ERROR(GetNodeAttr(ndef, "container", &attr_container));
  if (!attr_container.empty() && !IsValidContainerName(attr_container)) {
    return errors::InvalidArgument("container contains invalid characters: ",
                                   attr_container);
  }
  string attr_shared_name;
  TF_RETURN_IF_ERROR(GetNodeAttr(ndef, "shared_name", &attr_shared_name));
  if (!attr_shared_name.empty() && (attr_shared_name[0] == '_')) {
    return errors::InvalidArgument("shared_name cannot start with '_':",
                                   attr_shared_name);
  }
  if (!attr_container.empty()) {
    container_ = attr_container;
  } else {
    container_ = rmgr_->default_container();
  }
  if (!attr_shared_name.empty()) {
    name_ = attr_shared_name;
  } else if (use_node_name_as_default) {
    name_ = ndef.name();
  } else {
    resource_is_private_to_kernel_ = true;
    static std::atomic<int64> counter(0);
    name_ = strings::StrCat("_", counter.fetch_add(1), "_", ndef.name());
  }
  return Status::OK();
}

string ContainerInfo::DebugString() const {
  return strings::StrCat("[", container(), ",", name(), ",",
                         resource_is_private_to_kernel() ? "private" : "public",
                         "]");
}

const ResourceHandle& HandleFromInput(OpKernelContext* ctx, int input) {
  return ctx->input(input).flat<ResourceHandle>()(0);
}

Status HandleFromInput(OpKernelContext* ctx, StringPiece input,
                       ResourceHandle* handle) {
  const Tensor* tensor;
  TF_RETURN_IF_ERROR(ctx->input(input, &tensor));
  *handle = tensor->flat<ResourceHandle>()(0);
  return Status::OK();
}

Status DeleteResource(OpKernelContext* ctx, const ResourceHandle& p) {
  TF_RETURN_IF_ERROR(internal::ValidateDevice(ctx, p));
  return ctx->resource_manager()->Delete(p);
}

Status ResourceHandlesShape(shape_inference::InferenceContext* c) {
  int n;
  TF_RETURN_IF_ERROR(c->GetAttr("N", &n));
  for (int i = 0; i < n; ++i) {
    c->set_output(i, c->Scalar());
  }
  return Status::OK();
}

}  //  end namespace tensorflow
<commit_msg>[Perf] Use a shared lock to avoid slow paths<commit_after>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include "tensorflow/core/framework/resource_mgr.h"

#include "tensorflow/core/framework/device_attributes.pb.h"
#include "tensorflow/core/framework/node_def.pb.h"
#include "tensorflow/core/framework/node_def_util.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/gtl/map_util.h"
#include "tensorflow/core/lib/strings/scanner.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/lib/strings/stringprintf.h"
#include "tensorflow/core/platform/demangle.h"

namespace tensorflow {
ResourceHandle MakeResourceHandle(OpKernelContext* ctx, const string& container,
                                  const string& name,
                                  const TypeIndex& type_index) {
  ResourceHandle result;
  result.set_device(ctx->device()->attributes().name());
  string actual_container;
  if (!container.empty()) {
    actual_container = container;
  } else {
    actual_container = ctx->resource_manager()->default_container();
  }
  result.set_container(actual_container);
  result.set_name(name);
  result.set_hash_code(type_index.hash_code());
  result.set_maybe_type_name(type_index.name());
  return result;
}

Status MakeResourceHandleToOutput(OpKernelContext* context, int output_index,
                                  const string& container, const string& name,
                                  const TypeIndex& type_index) {
  Tensor* handle;
  TF_RETURN_IF_ERROR(
      context->allocate_output(output_index, TensorShape({}), &handle));
  handle->scalar<ResourceHandle>()() =
      MakeResourceHandle(context, container, name, type_index);
  return Status::OK();
}

namespace internal {

Status ValidateDevice(OpKernelContext* ctx, const ResourceHandle& p) {
  if (ctx->device()->attributes().name() != p.device()) {
    return errors::InvalidArgument(
        "Trying to access resource ", p.name(), " located in device ",
        p.device(), " from device ", ctx->device()->attributes().name());
  }
  return Status::OK();
}

}  // end namespace internal

Status ResourceMgr::InsertDebugTypeName(uint64 hash_code,
                                        const string& type_name) {
  auto iter = debug_type_names_.emplace(hash_code, type_name);
  if (iter.first->second != type_name) {
    return errors::AlreadyExists("Duplicate hash code found for type ",
                                 type_name);
  }
  return Status::OK();
}

const char* ResourceMgr::DebugTypeName(uint64 hash_code) const {
  auto type_name_iter = debug_type_names_.find(hash_code);
  if (type_name_iter == debug_type_names_.end()) {
    return "<unknown>";
  } else {
    return type_name_iter->second.c_str();
  }
}

ResourceMgr::ResourceMgr() : default_container_("localhost") {}

ResourceMgr::ResourceMgr(const string& default_container)
    : default_container_(default_container) {}

ResourceMgr::~ResourceMgr() { Clear(); }

void ResourceMgr::Clear() {
  mutex_lock l(mu_);
  for (const auto& p : containers_) {
    for (const auto& q : *p.second) {
      q.second->Unref();
    }
    delete p.second;
  }
  containers_.clear();
}

string ResourceMgr::DebugString() const {
  mutex_lock l(mu_);
  struct Line {
    const string* container;
    const string type;
    const string* resource;
    const string detail;
  };
  std::vector<Line> lines;
  for (const auto& p : containers_) {
    const string& container = p.first;
    for (const auto& q : *p.second) {
      const Key& key = q.first;
      const char* type = DebugTypeName(key.first);
      const string& resource = key.second;
      Line l{&container, port::Demangle(type), &resource,
             q.second->DebugString()};
      lines.push_back(l);
    }
  }
  std::vector<string> text;
  text.reserve(lines.size());
  for (const Line& line : lines) {
    text.push_back(strings::Printf(
        "%-20s | %-40s | %-40s | %-s", line.container->c_str(),
        line.type.c_str(), line.resource->c_str(), line.detail.c_str()));
  }
  std::sort(text.begin(), text.end());
  return str_util::Join(text, "\n");
}

Status ResourceMgr::DoCreate(const string& container, TypeIndex type,
                             const string& name, ResourceBase* resource) {
  Container** b = &containers_[container];
  if (*b == nullptr) {
    *b = new Container;
  }
  if ((*b)->insert({{type.hash_code(), name}, resource}).second) {
    TF_RETURN_IF_ERROR(InsertDebugTypeName(type.hash_code(), type.name()));
    return Status::OK();
  }
  resource->Unref();
  return errors::AlreadyExists("Resource ", container, "/", name, "/",
                               type.name());
}

Status ResourceMgr::DoLookup(const string& container, TypeIndex type,
                             const string& name,
                             ResourceBase** resource) const {
  const Container* b = gtl::FindPtrOrNull(containers_, container);
  if (b == nullptr) {
    return errors::NotFound("Container ", container,
                            " does not exist. (Could not find resource: ",
                            container, "/", name, ")");
  }
  auto r = gtl::FindPtrOrNull(*b, {type.hash_code(), name});
  if (r == nullptr) {
    return errors::NotFound("Resource ", container, "/", name, "/", type.name(),
                            " does not exist.");
  }
  *resource = const_cast<ResourceBase*>(r);
  (*resource)->Ref();
  return Status::OK();
}

Status ResourceMgr::DoDelete(const string& container, uint64 type_hash_code,
                             const string& resource_name,
                             const string& type_name) {
  ResourceBase* base = nullptr;
  {
    mutex_lock l(mu_);
    Container* b = gtl::FindPtrOrNull(containers_, container);
    if (b == nullptr) {
      return errors::NotFound("Container ", container, " does not exist.");
    }
    auto iter = b->find({type_hash_code, resource_name});
    if (iter == b->end()) {
      return errors::NotFound("Resource ", container, "/", resource_name, "/",
                              type_name, " does not exist.");
    }
    base = iter->second;
    b->erase(iter);
  }
  CHECK(base != nullptr);
  base->Unref();
  return Status::OK();
}

Status ResourceMgr::DoDelete(const string& container, TypeIndex type,
                             const string& resource_name) {
  return DoDelete(container, type.hash_code(), resource_name, type.name());
}

Status ResourceMgr::Delete(const ResourceHandle& handle) {
  return DoDelete(handle.container(), handle.hash_code(), handle.name(),
                  "<unknown>");
}

Status ResourceMgr::Cleanup(const string& container) {
  {
    tf_shared_lock l(mu_);
    if (!gtl::FindOrNull(containers_, container)) {
      // Nothing to cleanup.
      return Status::OK();
    }
  }
  Container* b = nullptr;
  {
    mutex_lock l(mu_);
    auto iter = containers_.find(container);
    if (iter == containers_.end()) {
      // Nothing to cleanup, it's OK (concurrent cleanup).
      return Status::OK();
    }
    b = iter->second;
    containers_.erase(iter);
  }
  CHECK(b != nullptr);
  for (const auto& p : *b) {
    p.second->Unref();
  }
  delete b;
  return Status::OK();
}

static bool IsValidContainerName(StringPiece s) {
  using ::tensorflow::strings::Scanner;
  return Scanner(s)
      .One(Scanner::LETTER_DIGIT_DOT)
      .Any(Scanner::LETTER_DIGIT_DASH_DOT_SLASH)
      .Eos()
      .GetResult();
}

Status ContainerInfo::Init(ResourceMgr* rmgr, const NodeDef& ndef,
                           bool use_node_name_as_default) {
  CHECK(rmgr);
  rmgr_ = rmgr;
  string attr_container;
  TF_RETURN_IF_ERROR(GetNodeAttr(ndef, "container", &attr_container));
  if (!attr_container.empty() && !IsValidContainerName(attr_container)) {
    return errors::InvalidArgument("container contains invalid characters: ",
                                   attr_container);
  }
  string attr_shared_name;
  TF_RETURN_IF_ERROR(GetNodeAttr(ndef, "shared_name", &attr_shared_name));
  if (!attr_shared_name.empty() && (attr_shared_name[0] == '_')) {
    return errors::InvalidArgument("shared_name cannot start with '_':",
                                   attr_shared_name);
  }
  if (!attr_container.empty()) {
    container_ = attr_container;
  } else {
    container_ = rmgr_->default_container();
  }
  if (!attr_shared_name.empty()) {
    name_ = attr_shared_name;
  } else if (use_node_name_as_default) {
    name_ = ndef.name();
  } else {
    resource_is_private_to_kernel_ = true;
    static std::atomic<int64> counter(0);
    name_ = strings::StrCat("_", counter.fetch_add(1), "_", ndef.name());
  }
  return Status::OK();
}

string ContainerInfo::DebugString() const {
  return strings::StrCat("[", container(), ",", name(), ",",
                         resource_is_private_to_kernel() ? "private" : "public",
                         "]");
}

const ResourceHandle& HandleFromInput(OpKernelContext* ctx, int input) {
  return ctx->input(input).flat<ResourceHandle>()(0);
}

Status HandleFromInput(OpKernelContext* ctx, StringPiece input,
                       ResourceHandle* handle) {
  const Tensor* tensor;
  TF_RETURN_IF_ERROR(ctx->input(input, &tensor));
  *handle = tensor->flat<ResourceHandle>()(0);
  return Status::OK();
}

Status DeleteResource(OpKernelContext* ctx, const ResourceHandle& p) {
  TF_RETURN_IF_ERROR(internal::ValidateDevice(ctx, p));
  return ctx->resource_manager()->Delete(p);
}

Status ResourceHandlesShape(shape_inference::InferenceContext* c) {
  int n;
  TF_RETURN_IF_ERROR(c->GetAttr("N", &n));
  for (int i = 0; i < n; ++i) {
    c->set_output(i, c->Scalar());
  }
  return Status::OK();
}

}  //  end namespace tensorflow
<|endoftext|>