<commit_before>//
//  main.cpp
//  test_rapidjson
//
//  Created by Nicolas Seriot on 24.07.17.
//  Copyright © 2017 ch.seriot. All rights reserved.
//

#include <iostream>

#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <dirent.h>
#include <stdio.h>
#include <string.h>
#include "document.h"

typedef enum testStatus {ERROR, PASS, FAIL} TestStatus;

/* Parse text to JSON, then render back to text, and print! */
TestStatus parseData(char *data, int printParsingResults) {
    rapidjson::Document document;
    if (document.Parse(data).HasParseError()) {
        return FAIL;
    }
    return PASS;
}

/* Read a file, parse, render back, etc. */
TestStatus testFile(const char *filename, int printParsingResults) {

    FILE *f=fopen(filename,"rb");
    if(f == NULL) { return ERROR; };
    fseek(f,0,SEEK_END);
    long len=ftell(f);
    fseek(f,0,SEEK_SET);
    char *data=(char*)malloc(len+1);
    fread(data,1,len,f);
    data[len]='\0';
    fclose(f);
    TestStatus status = parseData(data, printParsingResults);
    free(data);
    return status;
}

int main(int argc, const char * argv[]) {

    const char* path = argv[1];

    int printParsingResults = 0;

    int result = testFile(path, printParsingResults);

    if (result == PASS) {
        return 0;
    } else {
        return 1;
    }
}
<commit_msg>added RapidJSON results<commit_after>//
//  main.cpp
//  test_rapidjson
//
//  Created by Nicolas Seriot on 24.07.17.
//  Copyright © 2017 ch.seriot. All rights reserved.
//

#include <iostream>

#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <dirent.h>
#include <stdio.h>
#include <string.h>
#include "document.h"

// RapidJSON does crash when parsing many nested array (stack overflow)
// a flag can prevent this, but is not the default
// https://github.com/miloyip/rapidjson/issues/1027

typedef enum testStatus {ERROR, PASS, FAIL} TestStatus;

TestStatus parseData(char *data, int printParsingResults) {
    rapidjson::Document document;
    if (document.Parse(data).HasParseError()) {
        return FAIL;
    }
    return PASS;
}

TestStatus testFile(const char *filename, int printParsingResults) {
    FILE *f=fopen(filename,"rb");
    if(f == NULL) { return ERROR; };
    fseek(f,0,SEEK_END);
    long len=ftell(f);
    fseek(f,0,SEEK_SET);
    char *data=(char*)malloc(len+1);
    fread(data,1,len,f);
    data[len]='\0';
    fclose(f);
    TestStatus status = parseData(data, printParsingResults);
    free(data);
    return status;
}

int main(int argc, const char * argv[]) {

    const char* path = argv[1];

    int printParsingResults = 0;

    int result = testFile(path, printParsingResults);

    if (result == PASS) {
        return 0;
    } else {
        return 1;
    }
}
<|endoftext|>


<commit_before>#include <iostream>
#include <Halide.h>

#include "recfilter.h"

#define MAX_THREADS    192
#define UNROLL         8
#define TILES_PER_WARP 4

using namespace Halide;

using std::map;
using std::vector;
using std::string;
using std::cerr;
using std::cout;
using std::endl;

int main(int argc, char **argv) {
    Arguments args(argc, argv);

    bool  nocheck = args.nocheck;
    int   width   = args.width;
    int   height  = args.width;
    int   tile    = args.block;
    int   iter    = args.iterations;

    Image<float> random_image = generate_random_image<float>(width,height);

    ImageParam image(type_of<float>(), 2);
    image.set(random_image);

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

    Var x("x");
    Var y("y");

    RDom rx(0, image.width(), "rx");
    RDom ry(0, image.height(),"ry");

    RecFilter filter("SAT");
    filter.setArgs(x, y);
    filter.define(image(clamp(x,0,image.width()-1),clamp(y,0,image.height()-1)));
    filter.addScan(x, rx);
    filter.addScan(y, ry);
    filter.split(tile);

///     filter.transpose_dimensions ("SAT_Intra_Tail_y_1", "xi", "yi");
///     filter.interleave_func("SAT_Intra_Tail_x_0", "SAT_Intra_Tail_y_1", "SAT_Intra_Tail", "xi", 1);
///
///     filter.remove_pure_def("SAT_Intra_CTail_x_0_Sub");
///     filter.remove_pure_def("SAT_Intra_CTail_y_1_Sub");
///
///     cerr << filter << endl;
///
///    // ----------------------------------------------------------------------------------------------
///
///    {
///        Var t("t");
///
///        Var xi("xi"), yi("yi"), rxi("rxi"), rxf("rxf"), rxt("rxt");
///        Var xo("xo"), yo("yo"), ryi("ryi"), ryf("ryf"), ryt("ryt");
///
///        Var rxox("rxo.x$r"), rxoy("rxo.y$r");
///        Var ryox("ryo.x$r"), ryoy("ryo.y$r");
///
///        Func SAT             = filter.func("SAT");
///        Func SAT_Final       = filter.func("SAT_Final");
///        Func SAT_Intra       = filter.func("SAT_Intra");
///        Func SAT_Tail        = filter.func("SAT_Intra_Tail");
///        Func SAT_CTail_x     = filter.func("SAT_Intra_CTail_x_0_Sub");
///        Func SAT_CTail_y     = filter.func("SAT_Intra_CTail_y_1_Sub");
///        Func SAT_CTail_xy    = filter.func("SAT_Intra_CTail_x_0_y_1");
///        Func SAT_CTail_xy_sub= filter.func("SAT_Intra_CTail_x_0_y_1_Sub");
///        Func SAT_Deps_x      = filter.func("SAT_Intra_Deps_x_0");
///        Func SAT_Deps_y      = filter.func("SAT_Intra_Deps_y_1");
///
///        SAT_Intra.compute_at(SAT_Tail, Var::gpu_blocks());
///        SAT_Intra.update(0).split(ryi,yi,t,UNROLL).reorder(t,rxi,yi,xo,yo).gpu_threads(rxi,yi).unroll(t);
///        SAT_Intra.update(1).reorder(rxi,ryi,xo,yo).gpu_threads(ryi).unroll(rxi);
///        SAT_Intra.update(2).reorder(rxt,ryi,xo,yo).gpu_threads(ryi).unroll(rxt);
///        SAT_Intra.update(3).reorder(ryi,rxi,xo,yo).gpu_threads(rxi).unroll(ryi);
///        SAT_Intra.update(4).reorder(ryt,rxi,xo,yo).gpu_threads(rxi).unroll(ryt);
///
///        SAT_Tail.compute_root().reorder_storage(xi,yi,xo,yo);
///        SAT_Tail.split(yi,yi,t,UNROLL).reorder(t,xi,yi,xo,yo).gpu(xo,yo,xi,yi).unroll(t);
///
///        SAT_Tail.compile_to_simplified_lowered_stmt("stmt2.html", 2, width/tile, tile, width/tile, HTML, get_jit_target_from_environment());
///
///        //
///
///        SAT_CTail_x.compute_root().reorder_storage(yi,xi,yo,xo);
///        SAT_CTail_x.update().reorder(rxox,rxoy,yi,yo).fuse(yi,yo,y).gpu_tile(y,MAX_THREADS);
///
///        //
///
///        SAT_CTail_xy_sub.compute_at(SAT_CTail_xy, Var::gpu_blocks());
///        SAT_CTail_xy_sub.split(xo,xo,x,TILES_PER_WARP).reorder(yi,xi,x,xo,yo).gpu_threads(x,yi);
///        SAT_CTail_xy_sub.update().split(xo,xo,x,TILES_PER_WARP).reorder(ryi,rxt,x,xo,yo).gpu_threads(x).unroll(ryi);
///
///        SAT_CTail_xy.compute_root().reorder_storage(yi,xi,yo,xo);
///        SAT_CTail_xy.split(xo,xo,x,TILES_PER_WARP).reorder(yi,xi,x,xo,yo).gpu_threads(x,yi).gpu_blocks(xo,yo);
///
///        //
///
///        SAT_CTail_y.compute_root().reorder_storage(xi,yi,xo,yo);
///        SAT_CTail_y.update().reorder(ryox,ryoy,xi,xo).fuse(xi,xo,x).gpu_tile(x,MAX_THREADS);
///
///        //
///
///        SAT_Deps_x.compute_at(SAT, Var::gpu_blocks()).reorder(xi,yi,xo,yo).gpu_threads(yi);
///        SAT_Deps_y.compute_at(SAT, Var::gpu_blocks()).reorder(xi,yi,xo,yo).gpu_threads(xi);
///
///        SAT_Final.compute_at(SAT, Var::gpu_blocks());
///        SAT_Final.update(0).split(ryi,yi,t,UNROLL).reorder(t,rxi,yi,xo,yo).gpu_threads(rxi,yi).unroll(t);
///        SAT_Final.update(1).reorder(rxt,ryi,xo,yo).gpu_threads(ryi).unroll(rxt);
///        SAT_Final.update(2).reorder(rxf,ryi,xo,yo).gpu_threads(ryi).unroll(rxf);
///        SAT_Final.update(3).reorder(ryt,rxi,xo,yo).gpu_threads(rxi).unroll(ryt);
///        SAT_Final.update(4).reorder(ryf,rxi,xo,yo).gpu_threads(rxi).unroll(ryf);
///
///        SAT.compute_root();
///        SAT.split(x,xo,xi,tile).split(y,yo,yi,tile);
///        SAT.split(yi,yi,t,UNROLL).reorder(t,xi,yi,xo,yo).gpu(xo,yo,xi,yi).unroll(t);
///
///        SAT.bound(x,0,width).bound(y,0,height);
///    }

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

    Target target = get_jit_target_from_environment();

    filter.finalize(target);
    cerr << filter << endl;

    {
        FuncTag ft1 = INTRA_TILE_SCAN;
        FuncTag ft2 = INTER_TILE_SCAN;

        VarTag x   = PURE_DIMENSION;
        VarTag t   = SCHEDULE_INNER;
        VarTag xi  = INNER_PURE_VAR, xit  = INNER_PURE_VAR | TAIL_DIMENSION;
        VarTag xo  = OUTER_PURE_VAR, xot  = OUTER_PURE_VAR | TAIL_DIMENSION;
        VarTag rxi = INNER_SCAN_VAR, rxit = INNER_SCAN_VAR | TAIL_DIMENSION;
        VarTag rxo = OUTER_SCAN_VAR, rxot = OUTER_SCAN_VAR | TAIL_DIMENSION;

        filter.compute_in_shared(ft1);
        filter.reorder(ft1, xit, rxit, xi, rxi, xo);
        filter.unroll (ft1, rxi).unroll(ft1, rxit);
//        filter.gpu_threads(ft1, xi, 1, 6);
        filter.gpu_blocks (ft1, xo);
        filter.reorder_storage(ft1, xit, xi, xo);

        filter.compute_in_global(ft2);
//        filter.reorder(ft2, rxo, , , , );
//        filter.unroll     (ft2, );
//        filter.gpu_threads(ft2, )
//        filter.gpu_blocks (ft2, );
//        filter.reorder_storage(ft2, xot, xi, xo);

        filter.bound(x,0,width).bound(y,0,height);
    }

    cerr << filter << endl;

    cerr << "\nJIT compilation ... " << endl;
    filter.compile_jit(target, "hl_stmt.html");

    cerr << "\nRunning ... " << endl;
    Buffer out(type_of<float>(), width, height);
    filter.realize(out, iter);

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

    if (!nocheck) {
        cerr << "\nChecking difference ... " << endl;
        Image<float> hl_out(out);
        Image<float> ref(width,height);

        for (int y=0; y<height; y++) {
            for (int x=0; x<width; x++) {
                ref(x,y) = random_image(x,y);
            }
        }
        for (int y=0; y<height; y++) {
            for (int x=1; x<width; x++) {
                ref(x,y) += ref(x-1,y);
            }
        }
        for (int y=1; y<height; y++) {
            for (int x=0; x<width; x++) {
                ref(x,y) += ref(x,y-1);
            }
        }

        cout << CheckResult(ref,hl_out) << endl;
    }

    return 0;
}
<commit_msg>Changed scheduling API (broken currently)<commit_after>#include <iostream>
#include <Halide.h>

#include "recfilter.h"

#define MAX_THREADS    192
#define UNROLL         8
#define TILES_PER_WARP 4

using namespace Halide;

using std::map;
using std::vector;
using std::string;
using std::cerr;
using std::cout;
using std::endl;

int main(int argc, char **argv) {
    Arguments args(argc, argv);

    bool  nocheck = args.nocheck;
    int   width   = args.width;
    int   height  = args.width;
    int   tile    = args.block;
    int   iter    = args.iterations;

    Image<float> random_image = generate_random_image<float>(width,height);

    ImageParam image(type_of<float>(), 2);
    image.set(random_image);

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

    Var x("x");
    Var y("y");

    RDom rx(0, image.width(), "rx");
    RDom ry(0, image.height(),"ry");

    RecFilter filter("SAT");
    filter.setArgs(x, y);
    filter.define(image(clamp(x,0,image.width()-1),clamp(y,0,image.height()-1)));
    filter.addScan(x, rx);
    filter.addScan(y, ry);
    filter.split(tile);

///     filter.transpose_dimensions ("SAT_Intra_Tail_y_1", "xi", "yi");
///     filter.interleave_func("SAT_Intra_Tail_x_0", "SAT_Intra_Tail_y_1", "SAT_Intra_Tail", "xi", 1);
///
///     filter.remove_pure_def("SAT_Intra_CTail_x_0_Sub");
///     filter.remove_pure_def("SAT_Intra_CTail_y_1_Sub");
///
///     cerr << filter << endl;
///
///    // ----------------------------------------------------------------------------------------------
///
///    {
///        Var t("t");
///
///        Var xi("xi"), yi("yi"), rxi("rxi"), rxf("rxf"), rxt("rxt");
///        Var xo("xo"), yo("yo"), ryi("ryi"), ryf("ryf"), ryt("ryt");
///
///        Var rxox("rxo.x$r"), rxoy("rxo.y$r");
///        Var ryox("ryo.x$r"), ryoy("ryo.y$r");
///
///        Func SAT             = filter.func("SAT");
///        Func SAT_Final       = filter.func("SAT_Final");
///        Func SAT_Intra       = filter.func("SAT_Intra");
///        Func SAT_Tail        = filter.func("SAT_Intra_Tail");
///        Func SAT_CTail_x     = filter.func("SAT_Intra_CTail_x_0_Sub");
///        Func SAT_CTail_y     = filter.func("SAT_Intra_CTail_y_1_Sub");
///        Func SAT_CTail_xy    = filter.func("SAT_Intra_CTail_x_0_y_1");
///        Func SAT_CTail_xy_sub= filter.func("SAT_Intra_CTail_x_0_y_1_Sub");
///        Func SAT_Deps_x      = filter.func("SAT_Intra_Deps_x_0");
///        Func SAT_Deps_y      = filter.func("SAT_Intra_Deps_y_1");
///
///        SAT_Intra.compute_at(SAT_Tail, Var::gpu_blocks());
///        SAT_Intra.update(0).split(ryi,yi,t,UNROLL).reorder(t,rxi,yi,xo,yo).gpu_threads(rxi,yi).unroll(t);
///        SAT_Intra.update(1).reorder(rxi,ryi,xo,yo).gpu_threads(ryi).unroll(rxi);
///        SAT_Intra.update(2).reorder(rxt,ryi,xo,yo).gpu_threads(ryi).unroll(rxt);
///        SAT_Intra.update(3).reorder(ryi,rxi,xo,yo).gpu_threads(rxi).unroll(ryi);
///        SAT_Intra.update(4).reorder(ryt,rxi,xo,yo).gpu_threads(rxi).unroll(ryt);
///
///        SAT_Tail.compute_root().reorder_storage(xi,yi,xo,yo);
///        SAT_Tail.split(yi,yi,t,UNROLL).reorder(t,xi,yi,xo,yo).gpu(xo,yo,xi,yi).unroll(t);
///
///        SAT_Tail.compile_to_simplified_lowered_stmt("stmt2.html", 2, width/tile, tile, width/tile, HTML, get_jit_target_from_environment());
///
///        //
///
///        SAT_CTail_x.compute_root().reorder_storage(yi,xi,yo,xo);
///        SAT_CTail_x.update().reorder(rxox,rxoy,yi,yo).fuse(yi,yo,y).gpu_tile(y,MAX_THREADS);
///
///        //
///
///        SAT_CTail_xy_sub.compute_at(SAT_CTail_xy, Var::gpu_blocks());
///        SAT_CTail_xy_sub.split(xo,xo,x,TILES_PER_WARP).reorder(yi,xi,x,xo,yo).gpu_threads(x,yi);
///        SAT_CTail_xy_sub.update().split(xo,xo,x,TILES_PER_WARP).reorder(ryi,rxt,x,xo,yo).gpu_threads(x).unroll(ryi);
///
///        SAT_CTail_xy.compute_root().reorder_storage(yi,xi,yo,xo);
///        SAT_CTail_xy.split(xo,xo,x,TILES_PER_WARP).reorder(yi,xi,x,xo,yo).gpu_threads(x,yi).gpu_blocks(xo,yo);
///
///        //
///
///        SAT_CTail_y.compute_root().reorder_storage(xi,yi,xo,yo);
///        SAT_CTail_y.update().reorder(ryox,ryoy,xi,xo).fuse(xi,xo,x).gpu_tile(x,MAX_THREADS);
///
///        //
///
///        SAT_Deps_x.compute_at(SAT, Var::gpu_blocks()).reorder(xi,yi,xo,yo).gpu_threads(yi);
///        SAT_Deps_y.compute_at(SAT, Var::gpu_blocks()).reorder(xi,yi,xo,yo).gpu_threads(xi);
///
///        SAT_Final.compute_at(SAT, Var::gpu_blocks());
///        SAT_Final.update(0).split(ryi,yi,t,UNROLL).reorder(t,rxi,yi,xo,yo).gpu_threads(rxi,yi).unroll(t);
///        SAT_Final.update(1).reorder(rxt,ryi,xo,yo).gpu_threads(ryi).unroll(rxt);
///        SAT_Final.update(2).reorder(rxf,ryi,xo,yo).gpu_threads(ryi).unroll(rxf);
///        SAT_Final.update(3).reorder(ryt,rxi,xo,yo).gpu_threads(rxi).unroll(ryt);
///        SAT_Final.update(4).reorder(ryf,rxi,xo,yo).gpu_threads(rxi).unroll(ryf);
///
///        SAT.compute_root();
///        SAT.split(x,xo,xi,tile).split(y,yo,yi,tile);
///        SAT.split(yi,yi,t,UNROLL).reorder(t,xi,yi,xo,yo).gpu(xo,yo,xi,yi).unroll(t);
///
///        SAT.bound(x,0,width).bound(y,0,height);
///    }

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

    Target target = get_jit_target_from_environment();

    filter.finalize(target);
    cerr << filter << endl;

    {
        VarTag xi  = INNER_PURE_VAR, xit  = INNER_PURE_VAR | TAIL_DIMENSION;
        VarTag xo  = OUTER_PURE_VAR, xot  = OUTER_PURE_VAR | TAIL_DIMENSION;
        VarTag rxi = INNER_SCAN_VAR, rxit = INNER_SCAN_VAR | TAIL_DIMENSION;
        VarTag rxo = OUTER_SCAN_VAR, rxot = OUTER_SCAN_VAR | TAIL_DIMENSION;

        RecFilterSchedule s_handle_inner = filter.schedule_handle(INTRA_TILE_SCAN);
        RecFilterSchedule s_handle_outer = filter.schedule_handle(INTER_TILE_SCAN);

        s_handle_inner.compute_in_shared(ft1)
            .reorder_storage(ft1, xit, xi, xo)
            .reorder(xit, rxit, xi, rxi, xo)
            .unroll(rxi).unroll(rxit)
            .gpu_threads(xi, 1, 6).gpu_blocks(xo);

        s_handle_outer.compute_in_global()
            .reorder_storage(xi, xit, xo)
            .reorder(xot, xi, xo)
            .unroll(rxo).unroll(rxot)
            .gpu_threads(xi).gpu_blocks(xo);

        filter.bound(x,0,width).bound(y,0,height);
    }

    cerr << filter << endl;

    cerr << "\nJIT compilation ... " << endl;
    filter.compile_jit(target, "hl_stmt.html");

    cerr << "\nRunning ... " << endl;
    Buffer out(type_of<float>(), width, height);
    filter.realize(out, iter);

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

    if (!nocheck) {
        cerr << "\nChecking difference ... " << endl;
        Image<float> hl_out(out);
        Image<float> ref(width,height);

        for (int y=0; y<height; y++) {
            for (int x=0; x<width; x++) {
                ref(x,y) = random_image(x,y);
            }
        }
        for (int y=0; y<height; y++) {
            for (int x=1; x<width; x++) {
                ref(x,y) += ref(x-1,y);
            }
        }
        for (int y=1; y<height; y++) {
            for (int x=0; x<width; x++) {
                ref(x,y) += ref(x,y-1);
            }
        }

        cout << CheckResult(ref,hl_out) << endl;
    }

    return 0;
}
<|endoftext|>


<commit_before>// ======================================================================== //
// Copyright 2009-2018 Intel Corporation                                    //
//                                                                          //
// 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.                                           //
// ======================================================================== //

// ospcommon
#include "ospcommon/tasking/parallel_for.h"
#include "ospcommon/utility/StringManip.h"
// sg
#include "../common/Data.h"
#include "Generator.h"
// vtk
#include <vtkImageData.h>
#include <vtkMarchingCubes.h>
#include <vtkRTAnalyticSource.h>
#include <vtkSmartPointer.h>

namespace ospray {
  namespace sg {

    void generateVTKWaveletVolume(const std::shared_ptr<Node> &world,
                                  const std::vector<string_pair> &params)
    {
      auto volume_node = createNode("wavelet", "StructuredVolume");
      auto iso_node    = createNode("wavelet_isosurface", "TriangleMesh");

      // get generator parameters

      vec3i dims(256, 256, 256);
      std::vector<float> isoValues;

      for (auto &p : params) {
        if (p.first == "dimensions" || p.first == "dims") {
          auto string_dims = ospcommon::utility::split(p.second, 'x');
          if (string_dims.size() != 3) {
            std::cout << "WARNING: ignoring incorrect 'dimensions' parameter,"
                      << " it must be of the form 'dimensions=XxYxZ'"
                      << std::endl;
            continue;
          }

          dims = vec3i(std::atoi(string_dims[0].c_str()),
                       std::atoi(string_dims[1].c_str()),
                       std::atoi(string_dims[2].c_str()));
        } else if (p.first == "isosurfaces" || p.first == "isovalues") {
          auto string_isos = ospcommon::utility::split(p.second, '/');
          for (const auto &s : string_isos)
            isoValues.push_back(std::atof(s.c_str()));
        } else {
          std::cout << "WARNING: unknown wavelet generator parameter '"
                    << p.first << "' with value '" << p.second << "'"
                    << std::endl;
        }
      }

      bool computeIsosurface = !isoValues.empty();

      // generate volume data

      std::cout << "...generating wavelet volume with dims=" << dims << "..."
                << std::endl;

      auto halfDims = dims / 2;

      vtkSmartPointer<vtkRTAnalyticSource> wavelet = vtkRTAnalyticSource::New();
      wavelet->SetWholeExtent(-halfDims.x, halfDims.x-1,
                              -halfDims.y, halfDims.y-1,
                              -halfDims.z, halfDims.z-1);

      wavelet->SetCenter(0, 0, 0);
      wavelet->SetMaximum(255);
      wavelet->SetStandardDeviation(.5);
      wavelet->SetXFreq(60);
      wavelet->SetYFreq(30);
      wavelet->SetZFreq(40);
      wavelet->SetXMag(10);
      wavelet->SetYMag(18);
      wavelet->SetZMag(5);
      wavelet->SetSubsampleRate(1);

      wavelet->Update();

      auto imageData = wavelet->GetOutput();

      // generate isosurface

      vtkSmartPointer<vtkMarchingCubes> mc =
        vtkSmartPointer<vtkMarchingCubes>::New();

      if (computeIsosurface) {
        std::cout << "...creating isosurfaces with wavelet volume data..."
                  << std::endl;

        mc->SetInputConnection(wavelet->GetOutputPort());
        mc->ComputeNormalsOn();
        mc->ComputeGradientsOn();
        mc->SetNumberOfContours(int(isoValues.size()));

        for (int i = 0; i < int(isoValues.size()); ++i)
          mc->SetValue(i, isoValues[i]);

        mc->Update();
      }

      std::cout << "...data generated, now creating scene graph objects..."
                << std::endl;

      // validate expected outputs

      std::string voxelType = imageData->GetScalarTypeAsString();

      if (voxelType != "float")
        throw std::runtime_error("wavelet not floats? got '" + voxelType + "'");

      auto dimentionality = imageData->GetDataDimension();

      if (dimentionality != 3)
        throw std::runtime_error("wavelet not 3 dimentional?");

      if (computeIsosurface) {
        // import isosurface data into sg nodes
        auto polyData = mc->GetOutput();

        auto vertices =
              createNode("vertex", "DataVector3f")->nodeAs<DataVector3f>();
        auto indices =
              createNode("index", "DataVector3i")->nodeAs<DataVector3i>();

        int numberOfCells  = polyData->GetNumberOfCells();
        int numberOfPoints = polyData->GetNumberOfPoints();

        double point[3];
        for (int i = 0; i < numberOfPoints; i++) {
          polyData->GetPoint(i, point);
          vertices->push_back(vec3f(point[0], point[1], point[2]));
        }

        for (int i = 0; i < numberOfCells; i++) {
          vtkCell *cell = polyData->GetCell(i);

          if (cell->GetCellType() == VTK_TRIANGLE) {
            indices->push_back(vec3i(cell->GetPointId(0),
                                     cell->GetPointId(1),
                                     cell->GetPointId(2)));
          }
        }

        iso_node->add(vertices);
        iso_node->add(indices);

        // add isosurface to world
        world->add(iso_node);
      } else {
        // import volume data into sg nodes

        dims = vec3i(imageData->GetDimensions()[0],
                     imageData->GetDimensions()[1],
                     imageData->GetDimensions()[2]);

        auto numVoxels = dims.product();

        auto *voxels_ptr = (float*)imageData->GetScalarPointer();

        auto voxel_data = std::make_shared<DataArray1f>(voxels_ptr, numVoxels);

        voxel_data->setName("voxelData");

        volume_node->add(voxel_data);

        // volume attributes

        volume_node->child("voxelType")  = voxelType;
        volume_node->child("dimensions") = dims;

        volume_node->createChild("stashed_vtk_source", "Node", wavelet);

        // add volume to world
        world->add(volume_node);
      }

      std::cout << "...finished!" << std::endl;
    }

    OSPSG_REGISTER_GENERATE_FUNCTION(generateVTKWaveletVolume, vtkWavelet);

  }  // ::ospray::sg
}  // ::ospray
<commit_msg>adding missing include in vtk generator<commit_after>// ======================================================================== //
// Copyright 2009-2018 Intel Corporation                                    //
//                                                                          //
// 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.                                           //
// ======================================================================== //

// ospcommon
#include "ospcommon/tasking/parallel_for.h"
#include "ospcommon/utility/StringManip.h"
// sg
#include "../common/Data.h"
#include "Generator.h"
// vtk
#include <vtkImageData.h>
#include <vtkMarchingCubes.h>
#include <vtkRTAnalyticSource.h>
#include <vtkSmartPointer.h>
#include <vtkCell.h>

namespace ospray {
  namespace sg {

    void generateVTKWaveletVolume(const std::shared_ptr<Node> &world,
                                  const std::vector<string_pair> &params)
    {
      auto volume_node = createNode("wavelet", "StructuredVolume");
      auto iso_node    = createNode("wavelet_isosurface", "TriangleMesh");

      // get generator parameters

      vec3i dims(256, 256, 256);
      std::vector<float> isoValues;

      for (auto &p : params) {
        if (p.first == "dimensions" || p.first == "dims") {
          auto string_dims = ospcommon::utility::split(p.second, 'x');
          if (string_dims.size() != 3) {
            std::cout << "WARNING: ignoring incorrect 'dimensions' parameter,"
                      << " it must be of the form 'dimensions=XxYxZ'"
                      << std::endl;
            continue;
          }

          dims = vec3i(std::atoi(string_dims[0].c_str()),
                       std::atoi(string_dims[1].c_str()),
                       std::atoi(string_dims[2].c_str()));
        } else if (p.first == "isosurfaces" || p.first == "isovalues") {
          auto string_isos = ospcommon::utility::split(p.second, '/');
          for (const auto &s : string_isos)
            isoValues.push_back(std::atof(s.c_str()));
        } else {
          std::cout << "WARNING: unknown wavelet generator parameter '"
                    << p.first << "' with value '" << p.second << "'"
                    << std::endl;
        }
      }

      bool computeIsosurface = !isoValues.empty();

      // generate volume data

      std::cout << "...generating wavelet volume with dims=" << dims << "..."
                << std::endl;

      auto halfDims = dims / 2;

      vtkSmartPointer<vtkRTAnalyticSource> wavelet = vtkRTAnalyticSource::New();
      wavelet->SetWholeExtent(-halfDims.x, halfDims.x-1,
                              -halfDims.y, halfDims.y-1,
                              -halfDims.z, halfDims.z-1);

      wavelet->SetCenter(0, 0, 0);
      wavelet->SetMaximum(255);
      wavelet->SetStandardDeviation(.5);
      wavelet->SetXFreq(60);
      wavelet->SetYFreq(30);
      wavelet->SetZFreq(40);
      wavelet->SetXMag(10);
      wavelet->SetYMag(18);
      wavelet->SetZMag(5);
      wavelet->SetSubsampleRate(1);

      wavelet->Update();

      auto imageData = wavelet->GetOutput();

      // generate isosurface

      vtkSmartPointer<vtkMarchingCubes> mc =
        vtkSmartPointer<vtkMarchingCubes>::New();

      if (computeIsosurface) {
        std::cout << "...creating isosurfaces with wavelet volume data..."
                  << std::endl;

        mc->SetInputConnection(wavelet->GetOutputPort());
        mc->ComputeNormalsOn();
        mc->ComputeGradientsOn();
        mc->SetNumberOfContours(int(isoValues.size()));

        for (int i = 0; i < int(isoValues.size()); ++i)
          mc->SetValue(i, isoValues[i]);

        mc->Update();
      }

      std::cout << "...data generated, now creating scene graph objects..."
                << std::endl;

      // validate expected outputs

      std::string voxelType = imageData->GetScalarTypeAsString();

      if (voxelType != "float")
        throw std::runtime_error("wavelet not floats? got '" + voxelType + "'");

      auto dimentionality = imageData->GetDataDimension();

      if (dimentionality != 3)
        throw std::runtime_error("wavelet not 3 dimentional?");

      if (computeIsosurface) {
        // import isosurface data into sg nodes
        auto polyData = mc->GetOutput();

        auto vertices =
              createNode("vertex", "DataVector3f")->nodeAs<DataVector3f>();
        auto indices =
              createNode("index", "DataVector3i")->nodeAs<DataVector3i>();

        int numberOfCells  = polyData->GetNumberOfCells();
        int numberOfPoints = polyData->GetNumberOfPoints();

        double point[3];
        for (int i = 0; i < numberOfPoints; i++) {
          polyData->GetPoint(i, point);
          vertices->push_back(vec3f(point[0], point[1], point[2]));
        }

        for (int i = 0; i < numberOfCells; i++) {
          vtkCell *cell = polyData->GetCell(i);

          if (cell->GetCellType() == VTK_TRIANGLE) {
            indices->push_back(vec3i(cell->GetPointId(0),
                                     cell->GetPointId(1),
                                     cell->GetPointId(2)));
          }
        }

        iso_node->add(vertices);
        iso_node->add(indices);

        // add isosurface to world
        world->add(iso_node);
      } else {
        // import volume data into sg nodes

        dims = vec3i(imageData->GetDimensions()[0],
                     imageData->GetDimensions()[1],
                     imageData->GetDimensions()[2]);

        auto numVoxels = dims.product();

        auto *voxels_ptr = (float*)imageData->GetScalarPointer();

        auto voxel_data = std::make_shared<DataArray1f>(voxels_ptr, numVoxels);

        voxel_data->setName("voxelData");

        volume_node->add(voxel_data);

        // volume attributes

        volume_node->child("voxelType")  = voxelType;
        volume_node->child("dimensions") = dims;

        volume_node->createChild("stashed_vtk_source", "Node", wavelet);

        // add volume to world
        world->add(volume_node);
      }

      std::cout << "...finished!" << std::endl;
    }

    OSPSG_REGISTER_GENERATE_FUNCTION(generateVTKWaveletVolume, vtkWavelet);

  }  // ::ospray::sg
}  // ::ospray
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: accessibleeventnotifier.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: vg $ $Date: 2003-04-24 17:25:35 $
 *
 *  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 COMPHELPER_ACCESSIBLE_EVENT_NOTIFIER
#define COMPHELPER_ACCESSIBLE_EVENT_NOTIFIER

#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEEVENTOBJECT_HPP_
#include <com/sun/star/accessibility/AccessibleEventObject.hpp>
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLEEVENTLISTENER_HPP_
#include <com/sun/star/accessibility/XAccessibleEventListener.hpp>
#endif

#ifndef _THREAD_HXX_
#include <osl/thread.hxx>
#endif
#ifndef _OSL_CONDITN_HXX_
#include <osl/conditn.hxx>
#endif
#ifndef _CPPUHELPER_INTERFACECONTAINER_H_
#include <cppuhelper/interfacecontainer.h>
#endif

#include <map>
#include <list>

//.........................................................................
namespace comphelper
{
//.........................................................................

    //=====================================================================
    //= AccessibleEventNotifier
    //=====================================================================
    class AccessibleEventNotifier
    {
    // typedefs
    public:
        typedef sal_uInt32  TClientId;

    private:
        typedef ::std::pair< TClientId, ::com::sun::star::accessibility::AccessibleEventObject >
                                                                                ClientEvent;

        typedef ::cppu::OInterfaceContainerHelper                                   EventListeners;
        typedef ::std::map< TClientId, EventListeners*, ::std::less< TClientId > >  ClientMap;

    // members
    private:
        // client administration
        static ::osl::Mutex     s_aMutex;
        static ClientMap        s_aClients;

    protected:
        AccessibleEventNotifier( );     // never implemented
        ~AccessibleEventNotifier( );    // never implemented

    private:
        AccessibleEventNotifier( const AccessibleEventNotifier& );              // never implemented!
        AccessibleEventNotifier& operator=( const AccessibleEventNotifier& );   // never implemented!

    public:
        /** registers a client of this class, means a broadcaster of AccessibleEvents

No precaution is taken to care for disposal of this component. When the component
            dies, it must call <member>revokeClient</member> or <member>revokeClientNotifyDisposing</member>
            explicitly itself.

        */
        static  TClientId   registerClient( );

        /** revokes a broadcaster of AccessibleEvents

Note that no disposing event is fired when you use this method, the client is simply revoked.
            You can for instance revoke a client if the last listener for it is revoked, but the client
            itself is not disposed.

            When the client is disposed, you should prefer <member>revokeClientNotifyDisposing</member>

Any possibly pending events for this client are removed from the queue.

            @seealso revokeClientNotifyDisposing
        */
        static  void        revokeClient( const TClientId _nClient );

        /** revokes a client, with additionally notifying a disposing event to all listeners registered for
            this client

Any other possibly pending events for this client are removed from the queue

            @param _nClient
                the id of the client which should be revoked
            @param _rxEventSource
                the source to be notified together with the <member scope="com.sun.star.lang">XComponent::disposing</member>
                call.
        */
        static  void        revokeClientNotifyDisposing(
                        const TClientId _nClient,
                        const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxEventSource
                    ) SAL_THROW( ( ) );

        /** registers a listener for the given client

            @param _nClient
                the id of the client for which a listener should be registered
            @return
                the number of event listeners currently registered for this client
        */
        static sal_Int32 addEventListener(
                        const TClientId _nClient,
                        const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleEventListener >& _rxListener
                    ) SAL_THROW( ( ) );

        /** revokes a listener for the given client

            @param _nClient
                the id of the client for which a listener should be revoked
            @return
                the number of event listeners currently registered for this client
        */
        static sal_Int32 removeEventListener(
                        const TClientId _nClient,
                        const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleEventListener >& _rxListener
                    ) SAL_THROW( ( ) );

        /** retrieves the set of listeners registered for a given client
        */
        static ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > >
                        getEventListeners( const TClientId _nClient ) SAL_THROW( ( ) );

        /** adds an event, which is to be braodcasted, to the queue

            @param _nClient
                the id of the client which needs to broadcast the event
        */
        static void addEvent(
                        const TClientId _nClient,
                        const ::com::sun::star::accessibility::AccessibleEventObject& _rEvent
                    ) SAL_THROW( ( ) );

    private:
        /// generates a new client id
        static  TClientId   generateId();

        /** looks up a client in our client map, asserts if it cannot find it or no event thread is present

            @precond
                to be called with our mutex locked

            @param _nClient
                the id of the client to loopup
            @param _rPos
                out-parameter for the position of the client in the client map

            @return
                <TRUE/> if and only if the client could be found and <arg>_rPos</arg> has been filled with
                it's position
        */
        static  sal_Bool    implLookupClient( const TClientId _nClient, ClientMap::iterator& _rPos );
    };

//.........................................................................
}   // namespace comphelper
//.........................................................................

#endif // COMPHELPER_ACCESSIBLE_EVENT_NOTIFIER

<commit_msg>INTEGRATION: CWS tune04 (1.4.128); FILE MERGED 2004/06/14 09:16:47 cmc 1.4.128.1: #i29636# turn global objects into local static data protected with swishy double-locked templated template<commit_after>/*************************************************************************
 *
 *  $RCSfile: accessibleeventnotifier.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: hjs $ $Date: 2004-06-25 17:20:13 $
 *
 *  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 COMPHELPER_ACCESSIBLE_EVENT_NOTIFIER
#define COMPHELPER_ACCESSIBLE_EVENT_NOTIFIER

#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEEVENTOBJECT_HPP_
#include <com/sun/star/accessibility/AccessibleEventObject.hpp>
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLEEVENTLISTENER_HPP_
#include <com/sun/star/accessibility/XAccessibleEventListener.hpp>
#endif

#ifndef _THREAD_HXX_
#include <osl/thread.hxx>
#endif
#ifndef _OSL_CONDITN_HXX_
#include <osl/conditn.hxx>
#endif
#ifndef _CPPUHELPER_INTERFACECONTAINER_H_
#include <cppuhelper/interfacecontainer.h>
#endif

#include <map>
#include <list>

//.........................................................................
namespace comphelper
{
//.........................................................................

    //=====================================================================
    //= AccessibleEventNotifier
    //=====================================================================
    class AccessibleEventNotifier
    {
    // typedefs
    public:
        typedef sal_uInt32  TClientId;

        typedef ::std::pair< TClientId, ::com::sun::star::accessibility::AccessibleEventObject >
                                                                                ClientEvent;

        typedef ::cppu::OInterfaceContainerHelper                                   EventListeners;
        typedef ::std::map< TClientId, EventListeners*, ::std::less< TClientId > >  ClientMap;

    protected:
        AccessibleEventNotifier( );     // never implemented
        ~AccessibleEventNotifier( );    // never implemented

    private:
        AccessibleEventNotifier( const AccessibleEventNotifier& );              // never implemented!
        AccessibleEventNotifier& operator=( const AccessibleEventNotifier& );   // never implemented!

    public:
        /** registers a client of this class, means a broadcaster of AccessibleEvents

No precaution is taken to care for disposal of this component. When the component
            dies, it must call <member>revokeClient</member> or <member>revokeClientNotifyDisposing</member>
            explicitly itself.

        */
        static  TClientId   registerClient( );

        /** revokes a broadcaster of AccessibleEvents

Note that no disposing event is fired when you use this method, the client is simply revoked.
            You can for instance revoke a client if the last listener for it is revoked, but the client
            itself is not disposed.

            When the client is disposed, you should prefer <member>revokeClientNotifyDisposing</member>

Any possibly pending events for this client are removed from the queue.

            @seealso revokeClientNotifyDisposing
        */
        static  void        revokeClient( const TClientId _nClient );

        /** revokes a client, with additionally notifying a disposing event to all listeners registered for
            this client

Any other possibly pending events for this client are removed from the queue

            @param _nClient
                the id of the client which should be revoked
            @param _rxEventSource
                the source to be notified together with the <member scope="com.sun.star.lang">XComponent::disposing</member>
                call.
        */
        static  void        revokeClientNotifyDisposing(
                        const TClientId _nClient,
                        const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxEventSource
                    ) SAL_THROW( ( ) );

        /** registers a listener for the given client

            @param _nClient
                the id of the client for which a listener should be registered
            @return
                the number of event listeners currently registered for this client
        */
        static sal_Int32 addEventListener(
                        const TClientId _nClient,
                        const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleEventListener >& _rxListener
                    ) SAL_THROW( ( ) );

        /** revokes a listener for the given client

            @param _nClient
                the id of the client for which a listener should be revoked
            @return
                the number of event listeners currently registered for this client
        */
        static sal_Int32 removeEventListener(
                        const TClientId _nClient,
                        const ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleEventListener >& _rxListener
                    ) SAL_THROW( ( ) );

        /** retrieves the set of listeners registered for a given client
        */
        static ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > >
                        getEventListeners( const TClientId _nClient ) SAL_THROW( ( ) );

        /** adds an event, which is to be braodcasted, to the queue

            @param _nClient
                the id of the client which needs to broadcast the event
        */
        static void addEvent(
                        const TClientId _nClient,
                        const ::com::sun::star::accessibility::AccessibleEventObject& _rEvent
                    ) SAL_THROW( ( ) );

    private:
        /// generates a new client id
        static  TClientId   generateId();

        /** looks up a client in our client map, asserts if it cannot find it or no event thread is present

            @precond
                to be called with our mutex locked

            @param _nClient
                the id of the client to loopup
            @param _rPos
                out-parameter for the position of the client in the client map

            @return
                <TRUE/> if and only if the client could be found and <arg>_rPos</arg> has been filled with
                it's position
        */
        static  sal_Bool    implLookupClient( const TClientId _nClient, ClientMap::iterator& _rPos );
    };

//.........................................................................
}   // namespace comphelper
//.........................................................................

#endif // COMPHELPER_ACCESSIBLE_EVENT_NOTIFIER

<|endoftext|>


<commit_before>#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <string>

#include "io_interface.h"

const int BUF_SIZE = 512 * PAGE_SIZE;
const size_t DATA_SIZE = 10L * 1024 * 1024 * 1024;

ssize_t complete_read(int fd, char *buf, size_t count)
{
	ssize_t bytes = 0;
	do {
		ssize_t ret = read(fd, buf, count);
		if (ret < 0)
			return ret;
		if (ret == 0)
			return bytes;
		bytes += ret;
		count -= ret;
		buf += ret;
	} while (count > 0);
	return bytes;
}

int verify_bytes(const char *bs1, const char *bs2, int size)
{
	for (int i = 0; i < size; i++) {
		assert(bs1[i] == bs2[i]);
	}
	return 0;
}

class data_source
{
public:
	virtual ssize_t get_data(off_t off, size_t size, char *buf) const = 0;
	virtual size_t get_size() const = 0;
};

class file_data_source: public data_source
{
	int fd;
	size_t file_size;
public:
	file_data_source(const std::string &ext_file) {
		fd = open(ext_file.c_str(), O_RDONLY);
		if (fd < 0) {
			perror("open");
			exit(-1);
		}
		file_size = get_file_size(ext_file.c_str());
	}

	virtual ssize_t get_data(off_t off, size_t size, char *buf) const {
		long new_off = lseek(fd, off, SEEK_SET);
		assert(new_off == off);
		ssize_t ret = complete_read(fd, buf, size);
		if (ret < 0) {
			perror("complete_read");
			exit(-1);
		}
		return ret;
	}

	virtual size_t get_size() const {
		return file_size;
	}
};

class synthetic_data_source: public data_source
{
	size_t size;
public:
	synthetic_data_source(size_t size) {
		this->size = size;
	}

	virtual ssize_t get_data(off_t off, size_t size, char *buf) const {
		off_t *long_pointer = (off_t *) buf;
		int num_longs = size / sizeof(off_t);
		long value = off / sizeof(off_t);
		for (int i = 0; i < num_longs; i++, value++) {
			long_pointer[i] = value;
		}
		return size;
	}

	virtual size_t get_size() const {
		return size;
	}
};

class verify_callback: public callback
{
	char *orig_buf;
	data_source *source;
public:
	verify_callback(data_source *source) {
		this->source = source;
		orig_buf = (char *) malloc(BUF_SIZE);
	}

	~verify_callback() {
		free(orig_buf);
	}

	int invoke(io_request *rqs[], int num) {
		size_t read_bytes = min(rqs[0]->get_size(),
				source->get_size() - rqs[0]->get_offset());
		assert(read_bytes > 0);
		size_t ret = source->get_data(rqs[0]->get_offset(), read_bytes, orig_buf);
		fprintf(stderr, "verify block %lx of %ld bytes\n", rqs[0]->get_offset(), read_bytes);
		assert(ret == read_bytes);
		verify_bytes(rqs[0]->get_buf(), orig_buf, read_bytes);
	}
};

void comm_verify_file(int argc, char *argv[])
{
	if (argc < 1) {
		fprintf(stderr, "verify file_name [ext_file]");
		fprintf(stderr, "file_name is the file name in the SA-FS file system\n");
		fprintf(stderr, "ext_file is the file in the external file system\n");
		exit(-1);
	}

	std::string int_file_name = argv[0];
	std::string ext_file;
	if (argc >= 2)
		ext_file = argv[1];

	file_io_factory *factory = create_io_factory(int_file_name, REMOTE_ACCESS);
	thread *curr_thread = thread::represent_thread(0);
	io_interface *io = factory->create_io(curr_thread);
	data_source *source;
	if (ext_file.empty())
		source = new synthetic_data_source(DATA_SIZE);
	else
		source = new file_data_source(ext_file);
	io->set_callback(new verify_callback(source));

	size_t file_size = source->get_size();
	assert(factory->get_file_size() >= file_size);
	file_size = ROUNDUP(file_size, BUF_SIZE);
	char *buf = (char *) valloc(BUF_SIZE);
	for (off_t off = 0; off < file_size; off += BUF_SIZE) {
		io_request req(buf, off, BUF_SIZE, READ, io, 0);
		io->access(&req, 1);
		io->wait4complete(1);
	}
	printf("verify all data\n");

	io->cleanup();
	delete io->get_callback();
	factory->destroy_io(io);
}

void comm_load_file2fs(int argc, char *argv[])
{
	if (argc < 1) {
		fprintf(stderr, "load file_name [ext_file]\n");
		fprintf(stderr, "file_name is the file name in the SA-FS file system\n");
		fprintf(stderr, "ext_file is the file in the external file system\n");
		exit(-1);
	}

	std::string int_file_name = argv[0];
	std::string ext_file;
	if (argc >= 2)
		ext_file = argv[1];

	file_io_factory *factory = create_io_factory(int_file_name, REMOTE_ACCESS);
	thread *curr_thread = thread::represent_thread(0);
	io_interface *io = factory->create_io(curr_thread);

	data_source *source;
	if (ext_file.empty()) {
		printf("use synthetic data\n");
		source = new synthetic_data_source(DATA_SIZE);
	}
	else {
		printf("use file %s\n", ext_file.c_str());
		source = new file_data_source(ext_file);
	}
	assert(factory->get_file_size() >= source->get_size());
	printf("source size: %ld\n", source->get_size());

	char *buf = (char *) valloc(BUF_SIZE);
	off_t off = 0;

	while (off < source->get_size()) {
		size_t size = min<size_t>(BUF_SIZE, source->get_size() - off);
		size_t ret = source->get_data(off, size, buf);
		assert(ret == size);
		ssize_t write_bytes = ROUNDUP(ret, 512);
		io_request req(buf, off, write_bytes, WRITE, io, 0);
		io->access(&req, 1);
		io->wait4complete(1);
		off += write_bytes;
	}
	printf("write all data\n");

	io->cleanup();
	factory->destroy_io(io);
}

/**
 * This is a utility tool for the SA-FS.
 */

int main(int argc, char *argv[])
{
	if (argc < 3) {
		fprintf(stderr, "util conf_file command ...\n");
		exit(-1);
	}

	std::string conf_file = argv[1];
	std::string command = argv[2];

	config_map configs(conf_file);
	init_io_system(configs);

	if (command == "load") {
		comm_load_file2fs(argc - 3, argv + 3);
	}
	else if (command == "verify") {
		comm_verify_file(argc - 3, argv + 3);
	}
}
<commit_msg>Fix a bug in SAFS-util.<commit_after>#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <string>

#include "io_interface.h"

const int BUF_SIZE = 512 * PAGE_SIZE;
const size_t DATA_SIZE = 10L * 1024 * 1024 * 1024;

ssize_t complete_read(int fd, char *buf, size_t count)
{
	ssize_t bytes = 0;
	do {
		ssize_t ret = read(fd, buf, count);
		if (ret < 0)
			return ret;
		if (ret == 0)
			return bytes;
		bytes += ret;
		count -= ret;
		buf += ret;
	} while (count > 0);
	return bytes;
}

int verify_bytes(const char *bs1, const char *bs2, int size)
{
	for (int i = 0; i < size; i++) {
		assert(bs1[i] == bs2[i]);
	}
	return 0;
}

class data_source
{
public:
	virtual ssize_t get_data(off_t off, size_t size, char *buf) const = 0;
	virtual size_t get_size() const = 0;
};

class file_data_source: public data_source
{
	int fd;
	size_t file_size;
public:
	file_data_source(const std::string &ext_file) {
		fd = open(ext_file.c_str(), O_RDONLY);
		if (fd < 0) {
			perror("open");
			exit(-1);
		}
		file_size = get_file_size(ext_file.c_str());
	}

	virtual ssize_t get_data(off_t off, size_t size, char *buf) const {
		long new_off = lseek(fd, off, SEEK_SET);
		assert(new_off == off);
		ssize_t ret = complete_read(fd, buf, size);
		if (ret < 0) {
			perror("complete_read");
			exit(-1);
		}
		return ret;
	}

	virtual size_t get_size() const {
		return file_size;
	}
};

class synthetic_data_source: public data_source
{
	size_t size;
public:
	synthetic_data_source(size_t size) {
		this->size = size;
	}

	virtual ssize_t get_data(off_t off, size_t size, char *buf) const {
		off_t *long_pointer = (off_t *) buf;
		int num_longs = size / sizeof(off_t);
		long value = off / sizeof(off_t);
		for (int i = 0; i < num_longs; i++, value++) {
			long_pointer[i] = value;
		}
		return size;
	}

	virtual size_t get_size() const {
		return size;
	}
};

class verify_callback: public callback
{
	char *orig_buf;
	data_source *source;
public:
	verify_callback(data_source *source) {
		this->source = source;
		orig_buf = (char *) malloc(BUF_SIZE);
	}

	~verify_callback() {
		free(orig_buf);
	}

	int invoke(io_request *rqs[], int num) {
		size_t read_bytes = min<size_t>(rqs[0]->get_size(),
				source->get_size() - rqs[0]->get_offset());
		assert(read_bytes > 0);
		size_t ret = source->get_data(rqs[0]->get_offset(), read_bytes, orig_buf);
		fprintf(stderr, "verify block %lx of %ld bytes\n", rqs[0]->get_offset(), read_bytes);
		assert(ret == read_bytes);
		verify_bytes(rqs[0]->get_buf(), orig_buf, read_bytes);
	}
};

void comm_verify_file(int argc, char *argv[])
{
	if (argc < 1) {
		fprintf(stderr, "verify file_name [ext_file]");
		fprintf(stderr, "file_name is the file name in the SA-FS file system\n");
		fprintf(stderr, "ext_file is the file in the external file system\n");
		exit(-1);
	}

	std::string int_file_name = argv[0];
	std::string ext_file;
	if (argc >= 2)
		ext_file = argv[1];

	file_io_factory *factory = create_io_factory(int_file_name, REMOTE_ACCESS);
	thread *curr_thread = thread::represent_thread(0);
	io_interface *io = factory->create_io(curr_thread);
	data_source *source;
	if (ext_file.empty())
		source = new synthetic_data_source(DATA_SIZE);
	else
		source = new file_data_source(ext_file);
	io->set_callback(new verify_callback(source));

	size_t file_size = source->get_size();
	assert(factory->get_file_size() >= file_size);
	file_size = ROUNDUP(file_size, BUF_SIZE);
	char *buf = (char *) valloc(BUF_SIZE);
	for (off_t off = 0; off < file_size; off += BUF_SIZE) {
		io_request req(buf, off, BUF_SIZE, READ, io, 0);
		io->access(&req, 1);
		io->wait4complete(1);
	}
	printf("verify all data\n");

	io->cleanup();
	delete io->get_callback();
	factory->destroy_io(io);
}

void comm_load_file2fs(int argc, char *argv[])
{
	if (argc < 1) {
		fprintf(stderr, "load file_name [ext_file]\n");
		fprintf(stderr, "file_name is the file name in the SA-FS file system\n");
		fprintf(stderr, "ext_file is the file in the external file system\n");
		exit(-1);
	}

	std::string int_file_name = argv[0];
	std::string ext_file;
	if (argc >= 2)
		ext_file = argv[1];

	file_io_factory *factory = create_io_factory(int_file_name, REMOTE_ACCESS);
	thread *curr_thread = thread::represent_thread(0);
	io_interface *io = factory->create_io(curr_thread);

	data_source *source;
	if (ext_file.empty()) {
		printf("use synthetic data\n");
		source = new synthetic_data_source(DATA_SIZE);
	}
	else {
		printf("use file %s\n", ext_file.c_str());
		source = new file_data_source(ext_file);
	}
	assert(factory->get_file_size() >= source->get_size());
	printf("source size: %ld\n", source->get_size());

	char *buf = (char *) valloc(BUF_SIZE);
	off_t off = 0;

	while (off < source->get_size()) {
		size_t size = min<size_t>(BUF_SIZE, source->get_size() - off);
		size_t ret = source->get_data(off, size, buf);
		assert(ret == size);
		ssize_t write_bytes = ROUNDUP(ret, 512);
		io_request req(buf, off, write_bytes, WRITE, io, 0);
		io->access(&req, 1);
		io->wait4complete(1);
		off += write_bytes;
	}
	printf("write all data\n");

	io->cleanup();
	factory->destroy_io(io);
}

/**
 * This is a utility tool for the SA-FS.
 */

int main(int argc, char *argv[])
{
	if (argc < 3) {
		fprintf(stderr, "util conf_file command ...\n");
		exit(-1);
	}

	std::string conf_file = argv[1];
	std::string command = argv[2];

	config_map configs(conf_file);
	init_io_system(configs);

	if (command == "load") {
		comm_load_file2fs(argc - 3, argv + 3);
	}
	else if (command == "verify") {
		comm_verify_file(argc - 3, argv + 3);
	}
}
<|endoftext|>


<commit_before>/*
 * This file is part of TelepathyQt4
 *
 * Copyright (C) 2008 Collabora Ltd. <http://www.collabora.co.uk/>
 * Copyright (C) 2008 Nokia Corporation
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "cli-channel.h"

#include "_gen/cli-channel-body.hpp"
#include "_gen/cli-channel.moc.hpp"
#include "cli-channel.moc.hpp"

#include <QQueue>

#include "cli-dbus.h"
#include "constants.h"
#include "debug.hpp"

namespace Telepathy
{
namespace Client
{

struct Channel::Private
{
    // Public object
    Channel& parent;

    // Optional interface proxies
    DBus::PropertiesInterface properties;

    // Introspection
    Readiness readiness;
    QStringList interfaces;
    QQueue<void (Private::*)()> introspectQueue;

    // Introspected properties
    QString channelType;
    uint targetHandleType;
    uint targetHandle;

    Private(Channel& parent)
        : parent(parent),
          properties(parent)
    {
        debug() << "Creating new Channel";

        readiness = ReadinessJustCreated;

        debug() << "Connecting to Channel::Closed()";
        parent.connect(&parent,
                       SIGNAL(Closed()),
                       SLOT(onClosed()));

        introspectQueue.enqueue(&Private::introspectMain);
        continueIntrospection();
    }

    void introspectMain()
    {
        debug() << "Calling Properties::GetAll(Channel)";
        QDBusPendingCallWatcher* watcher =
            new QDBusPendingCallWatcher(
                    properties.GetAll(TELEPATHY_INTERFACE_CHANNEL), &parent);
        parent.connect(watcher,
                       SIGNAL(finished(QDBusPendingCallWatcher*)),
                       SLOT(gotMainProperties(QDBusPendingCallWatcher*)));
    }

    void introspectMainFallbackChannelType()
    {
        debug() << "Calling Channel::GetChannelType()";
        QDBusPendingCallWatcher* watcher =
            new QDBusPendingCallWatcher(parent.GetChannelType(), &parent);
        parent.connect(watcher,
                       SIGNAL(finished(QDBusPendingCallWatcher*)),
                       SLOT(gotChannelType(QDBusPendingCallWatcher*)));
    }

    void introspectMainFallbackHandle()
    {
        debug() << "Calling Channel::GetHandle()";
        QDBusPendingCallWatcher* watcher =
            new QDBusPendingCallWatcher(parent.GetHandle(), &parent);
        parent.connect(watcher,
                       SIGNAL(finished(QDBusPendingCallWatcher*)),
                       SLOT(gotHandle(QDBusPendingCallWatcher*)));
    }

    void introspectMainFallbackInterfaces()
    {
        debug() << "Calling Channel::GetInterfaces()";
        QDBusPendingCallWatcher* watcher =
            new QDBusPendingCallWatcher(parent.GetInterfaces(), &parent);
        parent.connect(watcher,
                       SIGNAL(finished(QDBusPendingCallWatcher*)),
                       SLOT(gotInterfaces(QDBusPendingCallWatcher*)));
    }

    void continueIntrospection()
    {
        if (introspectQueue.isEmpty()) {
            if (readiness < ReadinessFull)
                changeReadiness(ReadinessFull);
        } else {
            (this->*introspectQueue.dequeue())();
        }
    }

    void nowHaveInterfaces()
    {
        debug() << "Channel has" << interfaces.size() << "optional interfaces:" << interfaces;

        for (QStringList::const_iterator i = interfaces.begin();
                                         i != interfaces.end();
                                         ++i) {
            // Enqueue introspection of any optional interfaces here
        }

        continueIntrospection();
    }

    void changeReadiness(Readiness newReadiness)
    {
        Q_ASSERT(newReadiness != readiness);

        switch (readiness) {
            case ReadinessJustCreated:
                break;
            case ReadinessFull:
                Q_ASSERT(newReadiness == ReadinessDead);
                break;
            case ReadinessDead:
            default:
                Q_ASSERT(false);
                break;
        }

        debug() << "Channel readiness changed from" << readiness << "to" << newReadiness;

        if (newReadiness == ReadinessFull) {
            debug() << "Channel fully ready";
            debug() << " Channel type" << channelType;
            debug() << " Target handle" << targetHandle;
            debug() << " Target handle type" << targetHandleType;
        } else {
            debug() << "R.I.P. Channel.";
        }

        readiness = newReadiness;
        emit parent.readinessChanged(newReadiness);
    }
};

Channel::Channel(const QString& serviceName,
                 const QString& objectPath,
                 QObject* parent)
    : ChannelInterface(serviceName, objectPath, parent),
      mPriv(new Private(*this))
{
}

Channel::Channel(const QDBusConnection& connection,
                 const QString& serviceName,
                 const QString& objectPath,
                 QObject* parent)
    : ChannelInterface(connection, serviceName, objectPath, parent),
      mPriv(new Private(*this))
{
}

Channel::~Channel()
{
    delete mPriv;
}

Channel::Readiness Channel::readiness() const
{
    return mPriv->readiness;
}

QStringList Channel::interfaces() const
{
    return mPriv->interfaces;
}

QString Channel::channelType() const
{
    return mPriv->channelType;
}

uint Channel::targetHandleType() const
{
    return mPriv->targetHandleType;
}

uint Channel::targetHandle() const
{
    return mPriv->targetHandle;
}

void Channel::gotMainProperties(QDBusPendingCallWatcher* watcher)
{
    QDBusPendingReply<QVariantMap> reply = *watcher;
    QVariantMap props;

    if (!reply.isError())
        props = reply.value();

    QList<bool> conditions;

    conditions << (props.size() >= 4);
    conditions << (props.contains("ChannelType") && !qdbus_cast<QString>(props["ChannelType"]).isEmpty());
    conditions << props.contains("Interfaces");
    conditions << props.contains("TargetHandle");
    conditions << props.contains("TargetHandleType");

    if (conditions.contains(false)) {
        if (reply.isError())
            warning().nospace() << "Properties::GetAll(Channel) failed with " << reply.error().name() << ": " << reply.error().message();
        else
            warning() << "Reply to Properties::GetAll(Channel) didn't contain the expected properties";

        warning() << "Assuming a pre-0.17.7-spec service, falling back to serial inspection";

        mPriv->introspectQueue.enqueue(&Private::introspectMainFallbackChannelType);
        mPriv->introspectQueue.enqueue(&Private::introspectMainFallbackHandle);
        mPriv->introspectQueue.enqueue(&Private::introspectMainFallbackInterfaces);

        mPriv->continueIntrospection();
        return;
    }

    debug() << "Got reply to Properties::GetAll(Channel)";
    mPriv->channelType = qdbus_cast<QString>(props["ChannelType"]);
    mPriv->interfaces = qdbus_cast<QStringList>(props["Interfaces"]);
    mPriv->targetHandle = qdbus_cast<uint>(props["TargetHandle"]);
    mPriv->targetHandleType = qdbus_cast<uint>(props["TargetHandleType"]);
    mPriv->nowHaveInterfaces();
}

void Channel::gotChannelType(QDBusPendingCallWatcher* watcher)
{
    QDBusPendingReply<QString> reply = *watcher;

    if (reply.isError()) {
        warning().nospace() << "Channel::GetChannelType() failed with " << reply.error().name() << ": " << reply.error().message() << ", Channel officially dead";
        if (mPriv->readiness != ReadinessDead)
            mPriv->changeReadiness(ReadinessDead);
        return;
    }

    debug() << "Got reply to fallback Channel::GetChannelType()";
    mPriv->channelType = reply.value();
    mPriv->continueIntrospection();
}

void Channel::gotHandle(QDBusPendingCallWatcher* watcher)
{
    QDBusPendingReply<uint, uint> reply = *watcher;

    if (reply.isError()) {
        warning().nospace() << "Channel::GetHandle() failed with " << reply.error().name() << ": " << reply.error().message() << ", Channel officially dead";
        if (mPriv->readiness != ReadinessDead)
            mPriv->changeReadiness(ReadinessDead);
        return;
    }

    debug() << "Got reply to fallback Channel::GetHandle()";
    mPriv->targetHandleType = reply.argumentAt<0>();
    mPriv->targetHandle = reply.argumentAt<1>();
    mPriv->continueIntrospection();
}

void Channel::gotInterfaces(QDBusPendingCallWatcher* watcher)
{
    QDBusPendingReply<QStringList> reply = *watcher;

    if (reply.isError()) {
        warning().nospace() << "Channel::GetInterfaces() failed with " << reply.error().name() << ": " << reply.error().message() << ", Channel officially dead";
        if (mPriv->readiness != ReadinessDead)
            mPriv->changeReadiness(ReadinessDead);
        return;
    }

    debug() << "Got reply to fallback Channel::GetInterfaces()";
    mPriv->interfaces = reply.value();
    mPriv->nowHaveInterfaces();
}

void Channel::onClosed()
{
    debug() << "Got Channel::Closed";

    if (mPriv->readiness != ReadinessDead)
        mPriv->changeReadiness(ReadinessDead);
}

}
}
<commit_msg>Adapt to debug.hpp->debug-internal.hpp change in cli-channel.cpp<commit_after>/*
 * This file is part of TelepathyQt4
 *
 * Copyright (C) 2008 Collabora Ltd. <http://www.collabora.co.uk/>
 * Copyright (C) 2008 Nokia Corporation
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "cli-channel.h"

#include "_gen/cli-channel-body.hpp"
#include "_gen/cli-channel.moc.hpp"
#include "cli-channel.moc.hpp"

#include <QQueue>

#include "cli-dbus.h"
#include "constants.h"
#include "debug-internal.hpp"

namespace Telepathy
{
namespace Client
{

struct Channel::Private
{
    // Public object
    Channel& parent;

    // Optional interface proxies
    DBus::PropertiesInterface properties;

    // Introspection
    Readiness readiness;
    QStringList interfaces;
    QQueue<void (Private::*)()> introspectQueue;

    // Introspected properties
    QString channelType;
    uint targetHandleType;
    uint targetHandle;

    Private(Channel& parent)
        : parent(parent),
          properties(parent)
    {
        debug() << "Creating new Channel";

        readiness = ReadinessJustCreated;

        debug() << "Connecting to Channel::Closed()";
        parent.connect(&parent,
                       SIGNAL(Closed()),
                       SLOT(onClosed()));

        introspectQueue.enqueue(&Private::introspectMain);
        continueIntrospection();
    }

    void introspectMain()
    {
        debug() << "Calling Properties::GetAll(Channel)";
        QDBusPendingCallWatcher* watcher =
            new QDBusPendingCallWatcher(
                    properties.GetAll(TELEPATHY_INTERFACE_CHANNEL), &parent);
        parent.connect(watcher,
                       SIGNAL(finished(QDBusPendingCallWatcher*)),
                       SLOT(gotMainProperties(QDBusPendingCallWatcher*)));
    }

    void introspectMainFallbackChannelType()
    {
        debug() << "Calling Channel::GetChannelType()";
        QDBusPendingCallWatcher* watcher =
            new QDBusPendingCallWatcher(parent.GetChannelType(), &parent);
        parent.connect(watcher,
                       SIGNAL(finished(QDBusPendingCallWatcher*)),
                       SLOT(gotChannelType(QDBusPendingCallWatcher*)));
    }

    void introspectMainFallbackHandle()
    {
        debug() << "Calling Channel::GetHandle()";
        QDBusPendingCallWatcher* watcher =
            new QDBusPendingCallWatcher(parent.GetHandle(), &parent);
        parent.connect(watcher,
                       SIGNAL(finished(QDBusPendingCallWatcher*)),
                       SLOT(gotHandle(QDBusPendingCallWatcher*)));
    }

    void introspectMainFallbackInterfaces()
    {
        debug() << "Calling Channel::GetInterfaces()";
        QDBusPendingCallWatcher* watcher =
            new QDBusPendingCallWatcher(parent.GetInterfaces(), &parent);
        parent.connect(watcher,
                       SIGNAL(finished(QDBusPendingCallWatcher*)),
                       SLOT(gotInterfaces(QDBusPendingCallWatcher*)));
    }

    void continueIntrospection()
    {
        if (introspectQueue.isEmpty()) {
            if (readiness < ReadinessFull)
                changeReadiness(ReadinessFull);
        } else {
            (this->*introspectQueue.dequeue())();
        }
    }

    void nowHaveInterfaces()
    {
        debug() << "Channel has" << interfaces.size() << "optional interfaces:" << interfaces;

        for (QStringList::const_iterator i = interfaces.begin();
                                         i != interfaces.end();
                                         ++i) {
            // Enqueue introspection of any optional interfaces here
        }

        continueIntrospection();
    }

    void changeReadiness(Readiness newReadiness)
    {
        Q_ASSERT(newReadiness != readiness);

        switch (readiness) {
            case ReadinessJustCreated:
                break;
            case ReadinessFull:
                Q_ASSERT(newReadiness == ReadinessDead);
                break;
            case ReadinessDead:
            default:
                Q_ASSERT(false);
                break;
        }

        debug() << "Channel readiness changed from" << readiness << "to" << newReadiness;

        if (newReadiness == ReadinessFull) {
            debug() << "Channel fully ready";
            debug() << " Channel type" << channelType;
            debug() << " Target handle" << targetHandle;
            debug() << " Target handle type" << targetHandleType;
        } else {
            debug() << "R.I.P. Channel.";
        }

        readiness = newReadiness;
        emit parent.readinessChanged(newReadiness);
    }
};

Channel::Channel(const QString& serviceName,
                 const QString& objectPath,
                 QObject* parent)
    : ChannelInterface(serviceName, objectPath, parent),
      mPriv(new Private(*this))
{
}

Channel::Channel(const QDBusConnection& connection,
                 const QString& serviceName,
                 const QString& objectPath,
                 QObject* parent)
    : ChannelInterface(connection, serviceName, objectPath, parent),
      mPriv(new Private(*this))
{
}

Channel::~Channel()
{
    delete mPriv;
}

Channel::Readiness Channel::readiness() const
{
    return mPriv->readiness;
}

QStringList Channel::interfaces() const
{
    return mPriv->interfaces;
}

QString Channel::channelType() const
{
    return mPriv->channelType;
}

uint Channel::targetHandleType() const
{
    return mPriv->targetHandleType;
}

uint Channel::targetHandle() const
{
    return mPriv->targetHandle;
}

void Channel::gotMainProperties(QDBusPendingCallWatcher* watcher)
{
    QDBusPendingReply<QVariantMap> reply = *watcher;
    QVariantMap props;

    if (!reply.isError())
        props = reply.value();

    QList<bool> conditions;

    conditions << (props.size() >= 4);
    conditions << (props.contains("ChannelType") && !qdbus_cast<QString>(props["ChannelType"]).isEmpty());
    conditions << props.contains("Interfaces");
    conditions << props.contains("TargetHandle");
    conditions << props.contains("TargetHandleType");

    if (conditions.contains(false)) {
        if (reply.isError())
            warning().nospace() << "Properties::GetAll(Channel) failed with " << reply.error().name() << ": " << reply.error().message();
        else
            warning() << "Reply to Properties::GetAll(Channel) didn't contain the expected properties";

        warning() << "Assuming a pre-0.17.7-spec service, falling back to serial inspection";

        mPriv->introspectQueue.enqueue(&Private::introspectMainFallbackChannelType);
        mPriv->introspectQueue.enqueue(&Private::introspectMainFallbackHandle);
        mPriv->introspectQueue.enqueue(&Private::introspectMainFallbackInterfaces);

        mPriv->continueIntrospection();
        return;
    }

    debug() << "Got reply to Properties::GetAll(Channel)";
    mPriv->channelType = qdbus_cast<QString>(props["ChannelType"]);
    mPriv->interfaces = qdbus_cast<QStringList>(props["Interfaces"]);
    mPriv->targetHandle = qdbus_cast<uint>(props["TargetHandle"]);
    mPriv->targetHandleType = qdbus_cast<uint>(props["TargetHandleType"]);
    mPriv->nowHaveInterfaces();
}

void Channel::gotChannelType(QDBusPendingCallWatcher* watcher)
{
    QDBusPendingReply<QString> reply = *watcher;

    if (reply.isError()) {
        warning().nospace() << "Channel::GetChannelType() failed with " << reply.error().name() << ": " << reply.error().message() << ", Channel officially dead";
        if (mPriv->readiness != ReadinessDead)
            mPriv->changeReadiness(ReadinessDead);
        return;
    }

    debug() << "Got reply to fallback Channel::GetChannelType()";
    mPriv->channelType = reply.value();
    mPriv->continueIntrospection();
}

void Channel::gotHandle(QDBusPendingCallWatcher* watcher)
{
    QDBusPendingReply<uint, uint> reply = *watcher;

    if (reply.isError()) {
        warning().nospace() << "Channel::GetHandle() failed with " << reply.error().name() << ": " << reply.error().message() << ", Channel officially dead";
        if (mPriv->readiness != ReadinessDead)
            mPriv->changeReadiness(ReadinessDead);
        return;
    }

    debug() << "Got reply to fallback Channel::GetHandle()";
    mPriv->targetHandleType = reply.argumentAt<0>();
    mPriv->targetHandle = reply.argumentAt<1>();
    mPriv->continueIntrospection();
}

void Channel::gotInterfaces(QDBusPendingCallWatcher* watcher)
{
    QDBusPendingReply<QStringList> reply = *watcher;

    if (reply.isError()) {
        warning().nospace() << "Channel::GetInterfaces() failed with " << reply.error().name() << ": " << reply.error().message() << ", Channel officially dead";
        if (mPriv->readiness != ReadinessDead)
            mPriv->changeReadiness(ReadinessDead);
        return;
    }

    debug() << "Got reply to fallback Channel::GetInterfaces()";
    mPriv->interfaces = reply.value();
    mPriv->nowHaveInterfaces();
}

void Channel::onClosed()
{
    debug() << "Got Channel::Closed";

    if (mPriv->readiness != ReadinessDead)
        mPriv->changeReadiness(ReadinessDead);
}

}
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: MNSINIParser.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-20 01:47:00 $
 *
 *  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 __MNSINIPARSER_HXX__
#define __MNSINIPARSER_HXX__

#include <rtl/ustring.hxx>
#include <com/sun/star/io/IOException.hpp>
#ifndef _OSL_PROCESS_H_
#include <osl/process.h>
#endif
using namespace rtl;

#include <map>
#include <list>

#if OSL_DEBUG_LEVEL > 0
#include <stdio.h>
#endif

struct ini_NameValue
{
    rtl::OUString sName;
    rtl::OUString sValue;

    inline ini_NameValue() SAL_THROW( () )
        {}
    inline ini_NameValue(
        OUString const & name, OUString const & value ) SAL_THROW( () )
        : sName( name ),
          sValue( value )
        {}
};

typedef std::list<
    ini_NameValue
> NameValueList;

struct ini_Section
{
    rtl::OUString sName;
    NameValueList lList;
};
typedef std::map<rtl::OUString,
                ini_Section
                >IniSectionMap;

class IniParser
{
    IniSectionMap mAllSection;
public:
    IniSectionMap * getAllSection(){return &mAllSection;};
    ini_Section *  getSection(OUString const & secName);
    IniParser(OUString const & rIniName) throw(com::sun::star::io::IOException );
#if OSL_DEBUG_LEVEL > 0
    void Dump();
#endif

};

#endif

<commit_msg>INTEGRATION: CWS changefileheader (1.4.276); FILE MERGED 2008/04/01 15:08:59 thb 1.4.276.2: #i85898# Stripping all external header guards 2008/03/28 15:23:54 rt 1.4.276.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: MNSINIParser.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 __MNSINIPARSER_HXX__
#define __MNSINIPARSER_HXX__

#include <rtl/ustring.hxx>
#include <com/sun/star/io/IOException.hpp>
#include <osl/process.h>
using namespace rtl;

#include <map>
#include <list>

#if OSL_DEBUG_LEVEL > 0
#include <stdio.h>
#endif

struct ini_NameValue
{
    rtl::OUString sName;
    rtl::OUString sValue;

    inline ini_NameValue() SAL_THROW( () )
        {}
    inline ini_NameValue(
        OUString const & name, OUString const & value ) SAL_THROW( () )
        : sName( name ),
          sValue( value )
        {}
};

typedef std::list<
    ini_NameValue
> NameValueList;

struct ini_Section
{
    rtl::OUString sName;
    NameValueList lList;
};
typedef std::map<rtl::OUString,
                ini_Section
                >IniSectionMap;

class IniParser
{
    IniSectionMap mAllSection;
public:
    IniSectionMap * getAllSection(){return &mAllSection;};
    ini_Section *  getSection(OUString const & secName);
    IniParser(OUString const & rIniName) throw(com::sun::star::io::IOException );
#if OSL_DEBUG_LEVEL > 0
    void Dump();
#endif

};

#endif

<|endoftext|>


<commit_before>#include <fstream>
#include <iostream>

#include "Include/HelloWorldScene.h"
#include "Include/GridManager.h"
#include "Include/Taotromino.h"

USING_NS_CC;

Scene* HelloWorld::createScene()
{
    // 'scene' is an autorelease object
    auto scene = Scene::create();

    // 'layer' is an autorelease object
    auto layer = HelloWorld::create();

    // add layer as a child to scene
    scene->addChild(layer);

    // return the scene
    return scene;
}

// on "init" you need to initialize your instance
bool HelloWorld::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !Layer::init() )
    {
        return false;
    }

    Size visibleSize = Director::getInstance()->getVisibleSize();
    Vec2 origin = Director::getInstance()->getVisibleOrigin();

    auto grids = new GridManager();

    // Using an empty node to maintain all of the game sprites
    auto spriteNode = Node::create();

    auto background = Sprite::createWithSpriteFrameName("background.png");
    background->setAnchorPoint(Vec2(0, 0));
    background->setPosition(0, 0);

    // Loading SquareBro from the SpriteSheet
    auto daSquareBro = Sprite::createWithSpriteFrameName("daSquareBro.png");
    daSquareBro->setPosition(0, 90);
    daSquareBro->setAnchorPoint(Vec2(0, 0));

    auto daSquareSis = Sprite::createWithSpriteFrameName("daSquareSisBig.png");
    daSquareSis->setPosition(225, 225);
    daSquareSis->setScale(1,1);

    // Adding spriteNode
    this->addChild(spriteNode,-1);
    this->addChild(grids, -9);
    this->addChild(background, -10);

    // Adding Squares to the spriteNode
    spriteNode->addChild(daSquareBro,0);
    spriteNode->addChild(daSquareSis,0);

    std::cout << "Creating Taotromino" << std::endl;
    currentTao = new Taotromino(Taotromino::Line);
     std::cout << "Setting Location" << std::endl;
    currentTao->setPosition((90 + 90*16) - 45, (90 + 90*5) - 45);

     std::cout << "Adding Taotromino to scene" << std::endl;
    spriteNode->addChild(currentTao, 2);
     std::cout << "End" << std::endl;

    return true;
}

void HelloWorld::update(float delta){

}

void HelloWorld::menuCloseCallback(Ref* pSender)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
	MessageBox("You pressed the close button. Windows Store Apps do not implement a close button.","Alert");
    return;
#endif

    Director::getInstance()->end();

#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
    exit(0);
#endif
}
<commit_msg>Added a Taotromino<commit_after>#include <fstream>
#include <iostream>

#include "Include/HelloWorldScene.h"
#include "Include/GridManager.h"
#include "Include/Taotromino.h"

USING_NS_CC;

Scene* HelloWorld::createScene()
{
    // 'scene' is an autorelease object
    auto scene = Scene::create();

    // 'layer' is an autorelease object
    auto layer = HelloWorld::create();

    // add layer as a child to scene
    scene->addChild(layer);

    // return the scene
    return scene;
}

// on "init" you need to initialize your instance
bool HelloWorld::init()
{
    //////////////////////////////
    // 1. super init first
    if ( !Layer::init() )
    {
        return false;
    }

    Size visibleSize = Director::getInstance()->getVisibleSize();
    Vec2 origin = Director::getInstance()->getVisibleOrigin();

    auto grids = new GridManager();

    // Using an empty node to maintain all of the game sprites
    auto spriteNode = Node::create();

    auto background = Sprite::createWithSpriteFrameName("background.png");
    background->setAnchorPoint(Vec2(0, 0));
    background->setPosition(0, 0);

    // Loading SquareBro from the SpriteSheet
    auto daSquareBro = Sprite::createWithSpriteFrameName("daSquareBro.png");
    daSquareBro->setPosition(0, 90);
    daSquareBro->setAnchorPoint(Vec2(0, 0));

    auto daSquareSis = Sprite::createWithSpriteFrameName("daSquareSisBig.png");
    daSquareSis->setPosition(225, 225);
    daSquareSis->setScale(1,1);

    // Adding spriteNode
    this->addChild(spriteNode,-1);
    this->addChild(grids, -9);
    this->addChild(background, -10);

    // Adding Squares to the spriteNode
    spriteNode->addChild(daSquareBro,0);
    spriteNode->addChild(daSquareSis,0);

    std::cout << "Creating Taotromino" << std::endl;
    currentTao = new Taotromino(Taotromino::Line);
     std::cout << "Setting Location" << std::endl;
    currentTao->setPosition((90 + 90*16) - 45, (90 + 90*5) - 45);
    currentTao->setRotation(90.0);

     std::cout << "Adding Taotromino to scene" << std::endl;
    spriteNode->addChild(currentTao, 2);
     std::cout << "End" << std::endl;

    return true;
}

void HelloWorld::update(float delta){

}

void HelloWorld::menuCloseCallback(Ref* pSender)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT)
	MessageBox("You pressed the close button. Windows Store Apps do not implement a close button.","Alert");
    return;
#endif

    Director::getInstance()->end();

#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
    exit(0);
#endif
}
<|endoftext|>


<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Karoliina T. Salminen <karoliina.t.salminen@nokia.com>
**
** This file is part of duicontrolpanel.
**
**
** This program is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include <QObject>
#include <QGraphicsSceneMouseEvent>

#include <dcpmaincategory.h>

#include "ut_dcpmaincategory.h"

void Ut_DcpMainCategory::init()
{
    m_subject = new DcpMainCategory();
}

void Ut_DcpMainCategory::cleanup()
{
    delete m_subject;
    m_subject = 0;
}

void Ut_DcpMainCategory::initTestCase()
{
}

void Ut_DcpMainCategory::cleanupTestCase()
{
}
void Ut_DcpMainCategory::testCreation()
{
    QVERIFY(m_subject->layout() != 0);
}

void Ut_DcpMainCategory::testAppendWidget()
{
    QGraphicsWidget *component1 = new QGraphicsWidget();
    QGraphicsLayoutItem *item1 = 0;
    m_subject->appendWidget(component1);
    item1 = m_subject->layout()->itemAt(0);
    QCOMPARE((void*)component1, (void*)(QGraphicsWidget*)item1);
    delete component1;
}

void Ut_DcpMainCategory::testGetItemCount()
{
    QCOMPARE(m_subject->getItemCount(), 0);

    QGraphicsWidget* component1 = new QGraphicsWidget();
    QGraphicsWidget* component2 = new QGraphicsWidget();
    QGraphicsWidget* component3 = new QGraphicsWidget();
    m_subject->appendWidget(component1);
    QCOMPARE(m_subject->getItemCount(), 1);

    m_subject->appendWidget(component2);
    QCOMPARE(m_subject->getItemCount(), 2);

    m_subject->appendWidget(component3);
    QCOMPARE(m_subject->getItemCount(), 3);

    delete component1;
    delete component2;
    delete component3;
}

void Ut_DcpMainCategory::testMLayout()
{
    QVERIFY(m_subject->mLayout());
    QCOMPARE((void*)m_subject->mLayout(), (void*)m_subject->layout());
}

void Ut_DcpMainCategory::testDeleteItems()
{
    QGraphicsWidget *component1 = new QGraphicsWidget();
    m_subject->appendWidget(component1);
    QGraphicsWidget *component2 = new QGraphicsWidget();
    m_subject->appendWidget(component2);
    QVERIFY(m_subject->layout()->count() != 0);
    m_subject->deleteItems();
    QCOMPARE(m_subject->layout()->count(), 0);
}

QTEST_APPLESS_MAIN(Ut_DcpMainCategory)
<commit_msg>Some tests for ut_dcpmaincategory<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Karoliina T. Salminen <karoliina.t.salminen@nokia.com>
**
** This file is part of duicontrolpanel.
**
**
** This program is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include <QObject>
#include <QGraphicsSceneMouseEvent>

#include <dcpmaincategory.h>

#include "ut_dcpmaincategory.h"

void Ut_DcpMainCategory::init()
{
    m_subject = new DcpMainCategory();
}

void Ut_DcpMainCategory::cleanup()
{
    delete m_subject;
    m_subject = 0;
}

void Ut_DcpMainCategory::initTestCase()
{
}

void Ut_DcpMainCategory::cleanupTestCase()
{
}
void Ut_DcpMainCategory::testCreation()
{
    QVERIFY(m_subject->layout() != 0);
}

void Ut_DcpMainCategory::testAppendWidget()
{
    QGraphicsWidget *component1 = new QGraphicsWidget();
    QGraphicsLayoutItem *item1 = 0;
    m_subject->appendWidget(component1);
    item1 = m_subject->layout()->itemAt(0);
    QCOMPARE((void*)component1, (void*)(QGraphicsWidget*)item1);
    item1 = m_subject->widgetAt(0);
    QCOMPARE((void*)component1, (void*)(QGraphicsWidget*)item1);

    delete component1;
}

void Ut_DcpMainCategory::testGetItemCount()
{
    QCOMPARE(m_subject->getItemCount(), 0);

    QGraphicsWidget* component1 = new QGraphicsWidget();
    QGraphicsWidget* component2 = new QGraphicsWidget();
    QGraphicsWidget* component3 = new QGraphicsWidget();
    m_subject->appendWidget(component1);
    QCOMPARE(m_subject->getItemCount(), 1);

    m_subject->appendWidget(component2);
    QCOMPARE(m_subject->getItemCount(), 2);

    m_subject->appendWidget(component3);
    QCOMPARE(m_subject->getItemCount(), 3);

    delete component1;
    delete component2;
    delete component3;
}

void Ut_DcpMainCategory::testMLayout()
{
    QVERIFY(m_subject->mLayout());
    QCOMPARE((void*)m_subject->mLayout(), (void*)m_subject->layout());
}

void Ut_DcpMainCategory::testDeleteItems()
{
    QGraphicsWidget *component1 = new QGraphicsWidget();
    m_subject->appendWidget(component1);
    QGraphicsWidget *component2 = new QGraphicsWidget();
    m_subject->appendWidget(component2);
    QVERIFY(m_subject->layout()->count() != 0);
    m_subject->deleteItems();
    QCOMPARE(m_subject->layout()->count(), 0);
}

QTEST_APPLESS_MAIN(Ut_DcpMainCategory)
<|endoftext|>


<commit_before>// $Id$
//
//  Copyright (C) 2001-2006 Greg Landrum and Rational Discovery LLC
//
//   @@ All Rights Reserved  @@
//
#include <GraphMol/QueryAtom.h>
#include <GraphMol/QueryOps.h>

namespace RDKit{

QueryAtom::~QueryAtom(){
  if( dp_query ){
    delete dp_query;
    dp_query=0;
  }
};

Atom *QueryAtom::copy() const {
  QueryAtom *res = new QueryAtom(*this);
  return static_cast<Atom *>(res);
}

void QueryAtom::expandQuery(QUERYATOM_QUERY *what,
			    Queries::CompositeQueryType how,
			    bool maintainOrder) {
  QUERYATOM_QUERY *origQ = dp_query;
  std::string descrip;
  switch(how) {
  case Queries::COMPOSITE_AND:
    dp_query = new ATOM_AND_QUERY;
    descrip = "AtomAnd";
    break;
  case Queries::COMPOSITE_OR:
    dp_query = new ATOM_OR_QUERY;
    descrip = "AtomOr";
    break;
  case Queries::COMPOSITE_XOR:
    dp_query = new ATOM_XOR_QUERY;
    descrip = "AtomXor";
    break;
  default:
    UNDER_CONSTRUCTION("unrecognized combination query");
  }
  dp_query->setDescription(descrip);
  if(maintainOrder){
    dp_query->addChild(QUERYATOM_QUERY::CHILD_TYPE(origQ));
    dp_query->addChild(QUERYATOM_QUERY::CHILD_TYPE(what));
  } else {
    dp_query->addChild(QUERYATOM_QUERY::CHILD_TYPE(what));
    dp_query->addChild(QUERYATOM_QUERY::CHILD_TYPE(origQ));
  }
}

// FIX: the const crap here is all mucked up.
bool QueryAtom::Match(const Atom::ATOM_SPTR what) const {
  return Match(what.get());
}

bool QueryAtom::Match(Atom const *what) const {
  PRECONDITION(dp_query,"no query set");
  return dp_query->Match(what);
}

}; // end o' namespace
<commit_msg>add a precondition<commit_after>// $Id$
//
//  Copyright (C) 2001-2006 Greg Landrum and Rational Discovery LLC
//
//   @@ All Rights Reserved  @@
//
#include <GraphMol/QueryAtom.h>
#include <GraphMol/QueryOps.h>

namespace RDKit{

QueryAtom::~QueryAtom(){
  if( dp_query ){
    delete dp_query;
    dp_query=0;
  }
};

Atom *QueryAtom::copy() const {
  QueryAtom *res = new QueryAtom(*this);
  return static_cast<Atom *>(res);
}

void QueryAtom::expandQuery(QUERYATOM_QUERY *what,
			    Queries::CompositeQueryType how,
			    bool maintainOrder) {
  QUERYATOM_QUERY *origQ = dp_query;
  std::string descrip;
  switch(how) {
  case Queries::COMPOSITE_AND:
    dp_query = new ATOM_AND_QUERY;
    descrip = "AtomAnd";
    break;
  case Queries::COMPOSITE_OR:
    dp_query = new ATOM_OR_QUERY;
    descrip = "AtomOr";
    break;
  case Queries::COMPOSITE_XOR:
    dp_query = new ATOM_XOR_QUERY;
    descrip = "AtomXor";
    break;
  default:
    UNDER_CONSTRUCTION("unrecognized combination query");
  }
  dp_query->setDescription(descrip);
  if(maintainOrder){
    dp_query->addChild(QUERYATOM_QUERY::CHILD_TYPE(origQ));
    dp_query->addChild(QUERYATOM_QUERY::CHILD_TYPE(what));
  } else {
    dp_query->addChild(QUERYATOM_QUERY::CHILD_TYPE(what));
    dp_query->addChild(QUERYATOM_QUERY::CHILD_TYPE(origQ));
  }
}

// FIX: the const crap here is all mucked up.
bool QueryAtom::Match(const Atom::ATOM_SPTR what) const {
  return Match(what.get());
}

bool QueryAtom::Match(Atom const *what) const {
  PRECONDITION(what,"bad query atom");
  PRECONDITION(dp_query,"no query set");
  return dp_query->Match(what);
}

}; // end o' namespace
<|endoftext|>