<commit_before>#include "test_process_reader.h"
#include "logic/process_reader.h"
#include "logic/settings.h"
#include "test.h"
#include "ui/mainwindow.h"

#include <QProcess>
#include <QString>
#include <QStringList>
#include <fstream>

void test_args_construction() {
	struct Test_cases {
		QString arg_text;
		QStringList args;
	} test_cases[] = {
		{"", {}},
		{"test", {"test"}},
		{R"("test")", {"test"}},
		{"multi arg", {"multi", "arg"}},
		{"many multi arg", {"many", "multi", "arg"}},
		{R"("multi arg")", {"multi arg"}},
		{R"(many "multi arg" things)", {"many", "multi arg", "things"}},
		{R"("many multi" "arg things")", {"many multi", "arg things"}},
	};

	for (const auto &test_case : test_cases) {
		assert_equal(detail::create_arguments_list(test_case.arg_text), test_case.args);
	}
}

void test_process_reading() {
	struct Test_cases {
		Tool tool;
		std::string_view code;
		std::string_view expected_output;
		std::string_view expected_error;
	} test_cases[] = {
		{.tool = {}, .code = R"(int main(){})"},                                                                                //
		{.tool = {}, .code = R"(#include <iostream>
							 int main(){
								std::cout << "test";
							 })", .expected_output = "test"},                                                                        //
		{.tool = {}, .code = R"(#include <iostream>
							 int main(){
								std::cerr << "test";
							 })", .expected_output = "", .expected_error = "test"},                                                  //
		{.tool = {}, .code = R"(#include <iostream>
							 int main(){
								 std::cout << "multi\nline\ntest\noutput\n";
								 std::cerr << "multi\nline\ntest\nerror\n";
							 })", .expected_output = "multi\nline\ntest\noutput\n", .expected_error = "multi\nline\ntest\nerror\n"}, //
		{.tool = {}, .code = R"(#include <iostream>
							 #include <thread>
							 #include <chrono>

							 int main(){
								 std::cout << "Hello" << std::flush;
								 std::this_thread::sleep_for(std::chrono::milliseconds{500});
								 std::cout << "World";
							 })", .expected_output = "HelloWorld"},                                                                  //
	};

	for (auto &test_case : test_cases) {
		const auto cpp_file = "/tmp/SCE_test_process_code.cpp";
		const auto exe_file = "/tmp/SCE_test_process_exe";
		assert_true(std::ofstream{cpp_file} << test_case.code);
		assert_equal(QProcess::execute("g++", {"-std=c++17", cpp_file, "-o", exe_file}), 0);
		test_case.tool.path = exe_file;
		Process_reader p{test_case.tool};
		assert_equal(p.get_output(), test_case.expected_output);
		assert_equal(p.get_error(), test_case.expected_error);
	}
}

void test_process_reader() {
	test_args_construction();
	test_process_reading();
}
<commit_msg>Refactored process reader test cases.<commit_after>#include "test_process_reader.h"
#include "logic/process_reader.h"
#include "logic/settings.h"
#include "test.h"
#include "ui/mainwindow.h"

#include <QProcess>
#include <QString>
#include <QStringList>
#include <fstream>

void test_args_construction() {
	struct Test_cases {
		QString arg_text;
		QStringList args;
	} test_cases[] = {
		{"", {}},
		{"test", {"test"}},
		{R"("test")", {"test"}},
		{"multi arg", {"multi", "arg"}},
		{"many multi arg", {"many", "multi", "arg"}},
		{R"("multi arg")", {"multi arg"}},
		{R"(many "multi arg" things)", {"many", "multi arg", "things"}},
		{R"("many multi" "arg things")", {"many multi", "arg things"}},
	};

	for (const auto &test_case : test_cases) {
		assert_equal(detail::create_arguments_list(test_case.arg_text), test_case.args);
	}
}

void test_process_reading() {
	struct Test_cases {
		std::string_view code;
		std::string_view expected_output;
		std::string_view expected_error;
	} test_cases[] = {
		{.code = R"(int main(){})"},
		{.code = R"(#include <iostream>
				 int main(){
					std::cout << "test";
				 })",
		 .expected_output = "test"},
		{.code = R"(#include <iostream>
				 int main(){
					std::cerr << "test";
				 })",
		 .expected_output = "",
		 .expected_error = "test"},
		{.code = R"(#include <iostream>
				 int main(){
					 std::cout << "multi\nline\ntest\noutput\n";
					 std::cerr << "multi\nline\ntest\nerror\n";
				 })",
		 .expected_output = "multi\nline\ntest\noutput\n",
		 .expected_error = "multi\nline\ntest\nerror\n"},
		{.code = R"(#include <iostream>
				 #include <thread>
				 #include <chrono>

				 int main(){
					 std::cout << "Hello" << std::flush;
					 std::this_thread::sleep_for(std::chrono::milliseconds{500});
					 std::cout << "World";
				 })",
		 .expected_output = "HelloWorld"},
	};

	for (auto &test_case : test_cases) {
		const auto cpp_file = "/tmp/SCE_test_process_code.cpp";
		const auto exe_file = "/tmp/SCE_test_process_exe";
		assert_true(std::ofstream{cpp_file} << test_case.code);
		assert_equal(QProcess::execute("g++", {"-std=c++17", cpp_file, "-o", exe_file}), 0);
		Tool tool;
		tool.path = exe_file;
		Process_reader p{tool};
		assert_equal(p.get_output(), test_case.expected_output);
		assert_equal(p.get_error(), test_case.expected_error);
	}
}

void test_process_reader() {
	test_args_construction();
	test_process_reading();
}
<|endoftext|>


<commit_before>/*
*  Author(s):
*  - Chris  Kilner <ckilner@aldebaran-robotics.com>
*  - Cedric Gestes <gestes@aldebaran-robotics.com>
*
*  Copyright (C) 2010 Aldebaran Robotics
*/

#include <qi/transport/src/zmq/zmq_poll_client.hpp>
#include <qi/exceptions/exceptions.hpp>
#include <iostream>
#include <qi/log.hpp>

namespace qi {
  namespace transport {
    namespace detail {
      ZMQPollClient::ZMQPollClient(zmq::socket_t &socket)
        : _zsocket(socket),
          _first_time(1)
      {
        _items[0].socket  = _zsocket;
        _items[0].fd      = 0;
        _items[0].events  = ZMQ_POLLIN;
        _items[0].revents = 0;
      }

      //return -1 on error, 0 otherwise
      int ZMQPollClient::pollRecv(long timeout) {
        int             rc = 0;

        rc = zmq::poll(_items, 1, timeout);
        qisDebug << "ZMQPollClient: timeout:" << timeout << std::endl;
        if ((rc <= 0) || (!(_items[0].revents & ZMQ_POLLIN)))
          return -1;
        return 0;
      }

      void ZMQPollClient::recv(zmq::message_t *msg, long usTimeout)
      {
        if (_first_time) {
          int rc = 0;
          long elapsed = 0;
          _first_time = 0;
          do {
            rc = pollRecv(1000);
            elapsed += 1;
          } while (rc < 0 && elapsed < usTimeout);
          if (rc < 0)
            throw qi::transport::Exception("no response");
        }
        else
        {
          pollRecv(usTimeout);
        }
        _zsocket.recv(msg);
      }
    }
  }
}

<commit_msg>transport: zmq: poll: do not call recv if poll failed<commit_after>/*
*  Author(s):
*  - Chris  Kilner <ckilner@aldebaran-robotics.com>
*  - Cedric Gestes <gestes@aldebaran-robotics.com>
*
*  Copyright (C) 2010 Aldebaran Robotics
*/

#include <qi/transport/src/zmq/zmq_poll_client.hpp>
#include <qi/exceptions/exceptions.hpp>
#include <iostream>
#include <qi/log.hpp>

namespace qi {
  namespace transport {
    namespace detail {
      ZMQPollClient::ZMQPollClient(zmq::socket_t &socket)
        : _zsocket(socket),
          _first_time(1)
      {
        _items[0].socket  = _zsocket;
        _items[0].fd      = 0;
        _items[0].events  = ZMQ_POLLIN;
        _items[0].revents = 0;
      }

      //return -1 on error, 0 otherwise
      int ZMQPollClient::pollRecv(long timeout) {
        int             rc = 0;

        rc = zmq::poll(_items, 1, timeout);
        qisDebug << "ZMQPollClient: timeout:" << timeout << std::endl;
        if ((rc <= 0) || (!(_items[0].revents & ZMQ_POLLIN)))
          return -1;
        return 0;
      }

      void ZMQPollClient::recv(zmq::message_t *msg, long usTimeout)
      {
        if (_first_time) {
          int rc = 0;
          long elapsed = 0;
          _first_time = 0;
          do {
            rc = pollRecv(1000);
            elapsed += 1;
          } while (rc < 0 && elapsed < usTimeout);
          if (rc < 0)
            throw qi::transport::Exception("no response");
        }
        else
        {
          if (pollRecv(usTimeout) < 0)
            throw qi::transport::Exception("no response");
        }
        _zsocket.recv(msg);
      }
    }
  }
}

<|endoftext|>


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

#include <Urho3D/IO/FileSystem.h>
#include <Urho3D/IO/Log.h>
#include <Urho3D/Core/ProcessUtils.h>

#include "Project.h"
#include "Pipeline/Asset.h"
#include "Pipeline/Importers/ModelImporter.h"

namespace Urho3D
{

static const char* MODEL_IMPORTER_OUTPUT_ANIM = "Output animations";
static const char* MODEL_IMPORTER_OUTPUT_MAT = "Output materials";
static const char* MODEL_IMPORTER_OUTPUT_MAT_TEX = "Output material textures";
static const char* MODEL_IMPORTER_USE_MAT_DIFFUSE = "Use material diffuse color";
static const char* MODEL_IMPORTER_FIX_INFACING_NORMALS = "Fix in-facing normals";
static const char* MODEL_IMPORTER_MAX_BONES = "Max number of bones";
static const char* MODEL_IMPORTER_ANIM_TICK = "Animation tick frequency";
static const char* MODEL_IMPORTER_EMISSIVE_AO = "Emissive is ambient occlusion";
static const char* MODEL_IMPORTER_FBX_PIVOT = "Suppress $fbx pivot nodes";

ModelImporter::ModelImporter(Context* context)
    : AssetImporter(context)
{
}

void ModelImporter::RegisterObject(Context* context)
{
    context->RegisterFactory<ModelImporter>();
    URHO3D_COPY_BASE_ATTRIBUTES(AssetImporter);
    URHO3D_ATTRIBUTE(MODEL_IMPORTER_OUTPUT_ANIM, bool, outputAnimations_, true, AM_DEFAULT);
    URHO3D_ATTRIBUTE(MODEL_IMPORTER_OUTPUT_MAT, bool, outputMaterials_, true, AM_DEFAULT);
    URHO3D_ATTRIBUTE(MODEL_IMPORTER_OUTPUT_MAT_TEX, bool, outputMaterialTextures_, true, AM_DEFAULT);
    URHO3D_ATTRIBUTE(MODEL_IMPORTER_USE_MAT_DIFFUSE, bool, useMaterialDiffuse_, true, AM_DEFAULT);
    URHO3D_ATTRIBUTE(MODEL_IMPORTER_FIX_INFACING_NORMALS, bool, fixInFacingNormals_, true, AM_DEFAULT);
    URHO3D_ATTRIBUTE(MODEL_IMPORTER_MAX_BONES, int, maxBones_, 64, AM_DEFAULT);
    URHO3D_ATTRIBUTE(MODEL_IMPORTER_ANIM_TICK, int, animationTick_, 4800, AM_DEFAULT);
    URHO3D_ATTRIBUTE(MODEL_IMPORTER_EMISSIVE_AO, bool, emissiveIsAmbientOcclusion_, false, AM_DEFAULT);
    URHO3D_ATTRIBUTE(MODEL_IMPORTER_FBX_PIVOT, bool, noFbxPivot_, false, AM_DEFAULT);
}

void ModelImporter::RenderInspector(const char* filter)
{
    BaseClassName::RenderInspector(filter);
}

bool ModelImporter::Execute(Urho3D::Asset* input, const ea::string& outputPath)
{
    // outputPath - absolute path to Cache or Cache/{flavor} folder.
    if (!BaseClassName::Execute(input, outputPath))
        return false;

    auto* fs = GetFileSystem();
    auto* project = GetSubsystem<Project>();

    // A path mimicking structure of cache directory, but with byproducts of this import procedure only. It serves us to allow easy
    // detection of all byproducts of this import procedure.
    ea::string tempPath = project->GetProjectPath() + "Temp." + GenerateUUID() + "/";
    // Actual output destination AssetImporter will be writing.
    ea::string resourceBaseName = GetPath(input->GetName()) + GetFileName(input->GetName()) + "/";  // Strips file extension
    ea::string tempOutput = tempPath + resourceBaseName;
    fs->CreateDirsRecursive(tempOutput);

    ea::string output = tempOutput + "Model.mdl";
    ea::vector<ea::string> args{"model", input->GetResourcePath(), output};

    if (!GetAttribute(MODEL_IMPORTER_OUTPUT_ANIM).GetBool())
        args.emplace_back("-na");

    if (!GetAttribute(MODEL_IMPORTER_OUTPUT_MAT).GetBool())
        args.emplace_back("-nm");

    if (!GetAttribute(MODEL_IMPORTER_OUTPUT_MAT_TEX).GetBool())
        args.emplace_back("-nt");

    if (!GetAttribute(MODEL_IMPORTER_USE_MAT_DIFFUSE).GetBool())
        args.emplace_back("-nc");

    if (!GetAttribute(MODEL_IMPORTER_FIX_INFACING_NORMALS).GetBool())
        args.emplace_back("-nf");

    args.emplace_back("-pp");
    args.emplace_back(resourceBaseName);

    args.emplace_back("-mb");
    args.emplace_back(ea::to_string(GetAttribute(MODEL_IMPORTER_MAX_BONES).GetBool()));

    args.emplace_back("-f");
    args.emplace_back(ea::to_string(GetAttribute(MODEL_IMPORTER_ANIM_TICK).GetInt()));

    if (!GetAttribute(MODEL_IMPORTER_EMISSIVE_AO).GetBool())
        args.emplace_back("-eao");

    if (!GetAttribute(MODEL_IMPORTER_FBX_PIVOT).GetBool())
        args.emplace_back("-np");

    int result = fs->SystemRun(fs->GetProgramDir() + "AssetImporter", args);

    if (result != 0)
    {
        URHO3D_LOGERROR("Importing asset '{}' failed.", input->GetName());
        return false;
    }

    unsigned mtime = fs->GetLastModifiedTime(input->GetResourcePath());

    StringVector tmpByproducts;
    fs->ScanDir(tmpByproducts, tempPath, "*.*", SCAN_FILES, true);
    tmpByproducts.erase_first(".");
    tmpByproducts.erase_first("..");

    for (const ea::string& byproduct : tmpByproducts)
    {
        ea::string byproductPath = tempPath + byproduct;
        ea::string moveTo = outputPath + byproduct;
        if (fs->FileExists(moveTo))
            fs->Delete(moveTo);
        else if (fs->DirExists(moveTo))
            fs->RemoveDir(moveTo, true);
        fs->CreateDirsRecursive(GetPath(moveTo));
        fs->Rename(byproductPath, moveTo);
        fs->SetLastModifiedTime(moveTo, mtime);
        AddByproduct(byproduct);
    }

    fs->RemoveDir(tempPath, true);
    return !tmpByproducts.empty();
}

bool ModelImporter::Accepts(const ea::string& path) const
{
    if (path.ends_with(".fbx"))
        return true;
    if (path.ends_with(".blend"))
        return true;
    return false;
}

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

#include <Urho3D/IO/FileSystem.h>
#include <Urho3D/IO/Log.h>
#include <Urho3D/Core/ProcessUtils.h>

#include "Project.h"
#include "Pipeline/Asset.h"
#include "Pipeline/Importers/ModelImporter.h"

namespace Urho3D
{

static const char* MODEL_IMPORTER_OUTPUT_ANIM = "Output animations";
static const char* MODEL_IMPORTER_OUTPUT_MAT = "Output materials";
static const char* MODEL_IMPORTER_OUTPUT_MAT_TEX = "Output material textures";
static const char* MODEL_IMPORTER_USE_MAT_DIFFUSE = "Use material diffuse color";
static const char* MODEL_IMPORTER_FIX_INFACING_NORMALS = "Fix in-facing normals";
static const char* MODEL_IMPORTER_MAX_BONES = "Max number of bones";
static const char* MODEL_IMPORTER_ANIM_TICK = "Animation tick frequency";
static const char* MODEL_IMPORTER_EMISSIVE_AO = "Emissive is ambient occlusion";
static const char* MODEL_IMPORTER_FBX_PIVOT = "Suppress $fbx pivot nodes";

ModelImporter::ModelImporter(Context* context)
    : AssetImporter(context)
{
}

void ModelImporter::RegisterObject(Context* context)
{
    context->RegisterFactory<ModelImporter>();
    URHO3D_COPY_BASE_ATTRIBUTES(AssetImporter);
    URHO3D_ATTRIBUTE(MODEL_IMPORTER_OUTPUT_ANIM, bool, outputAnimations_, true, AM_DEFAULT);
    URHO3D_ATTRIBUTE(MODEL_IMPORTER_OUTPUT_MAT, bool, outputMaterials_, true, AM_DEFAULT);
    URHO3D_ATTRIBUTE(MODEL_IMPORTER_OUTPUT_MAT_TEX, bool, outputMaterialTextures_, true, AM_DEFAULT);
    URHO3D_ATTRIBUTE(MODEL_IMPORTER_USE_MAT_DIFFUSE, bool, useMaterialDiffuse_, true, AM_DEFAULT);
    URHO3D_ATTRIBUTE(MODEL_IMPORTER_FIX_INFACING_NORMALS, bool, fixInFacingNormals_, true, AM_DEFAULT);
    URHO3D_ATTRIBUTE(MODEL_IMPORTER_MAX_BONES, int, maxBones_, 64, AM_DEFAULT);
    URHO3D_ATTRIBUTE(MODEL_IMPORTER_ANIM_TICK, int, animationTick_, 4800, AM_DEFAULT);
    URHO3D_ATTRIBUTE(MODEL_IMPORTER_EMISSIVE_AO, bool, emissiveIsAmbientOcclusion_, false, AM_DEFAULT);
    URHO3D_ATTRIBUTE(MODEL_IMPORTER_FBX_PIVOT, bool, noFbxPivot_, false, AM_DEFAULT);
}

void ModelImporter::RenderInspector(const char* filter)
{
    BaseClassName::RenderInspector(filter);
}

bool ModelImporter::Execute(Urho3D::Asset* input, const ea::string& outputPath)
{
    // outputPath - absolute path to Cache or Cache/{flavor} folder.
    if (!BaseClassName::Execute(input, outputPath))
        return false;

    auto* fs = GetFileSystem();
    auto* project = GetSubsystem<Project>();

    // A path mimicking structure of cache directory, but with byproducts of this import procedure only. It serves us to allow easy
    // detection of all byproducts of this import procedure.
    ea::string tempPath = project->GetProjectPath() + "Temp." + GenerateUUID() + "/";
    // Actual output destination AssetImporter will be writing.
    ea::string resourceBaseName = GetPath(input->GetName()) + GetFileName(input->GetName()) + "/";  // Strips file extension
    ea::string tempOutput = tempPath + resourceBaseName;
    fs->CreateDirsRecursive(tempOutput);

    ea::string output = tempOutput + "Model.mdl";
    ea::vector<ea::string> args{"model", input->GetResourcePath(), output};

    if (!GetAttribute(MODEL_IMPORTER_OUTPUT_ANIM).GetBool())
        args.emplace_back("-na");

    if (!GetAttribute(MODEL_IMPORTER_OUTPUT_MAT).GetBool())
        args.emplace_back("-nm");

    if (!GetAttribute(MODEL_IMPORTER_OUTPUT_MAT_TEX).GetBool())
        args.emplace_back("-nt");

    if (!GetAttribute(MODEL_IMPORTER_USE_MAT_DIFFUSE).GetBool())
        args.emplace_back("-nc");

    if (!GetAttribute(MODEL_IMPORTER_FIX_INFACING_NORMALS).GetBool())
        args.emplace_back("-nf");

    args.emplace_back("-pp");
    args.emplace_back(resourceBaseName);

    args.emplace_back("-mb");
    args.emplace_back(ea::to_string(GetAttribute(MODEL_IMPORTER_MAX_BONES).GetBool()));

    args.emplace_back("-f");
    args.emplace_back(ea::to_string(GetAttribute(MODEL_IMPORTER_ANIM_TICK).GetInt()));

    if (!GetAttribute(MODEL_IMPORTER_EMISSIVE_AO).GetBool())
        args.emplace_back("-eao");

    if (!GetAttribute(MODEL_IMPORTER_FBX_PIVOT).GetBool())
        args.emplace_back("-np");

    int result = fs->SystemRun(fs->GetProgramDir() + "AssetImporter", args);

    if (result != 0)
    {
        URHO3D_LOGERROR("Importing asset 'res://{}' failed.", input->GetName());
        return false;
    }

    unsigned mtime = fs->GetLastModifiedTime(input->GetResourcePath());

    StringVector tmpByproducts;
    fs->ScanDir(tmpByproducts, tempPath, "*.*", SCAN_FILES, true);
    tmpByproducts.erase_first(".");
    tmpByproducts.erase_first("..");

    for (const ea::string& byproduct : tmpByproducts)
    {
        ea::string byproductPath = tempPath + byproduct;
        ea::string moveTo = outputPath + byproduct;
        if (fs->FileExists(moveTo))
            fs->Delete(moveTo);
        else if (fs->DirExists(moveTo))
            fs->RemoveDir(moveTo, true);
        fs->CreateDirsRecursive(GetPath(moveTo));
        fs->Rename(byproductPath, moveTo);
        fs->SetLastModifiedTime(moveTo, mtime);
        AddByproduct(byproduct);
    }

    fs->RemoveDir(tempPath, true);
    return !tmpByproducts.empty();
}

bool ModelImporter::Accepts(const ea::string& path) const
{
    if (path.ends_with(".fbx"))
        return true;
    if (path.ends_with(".blend"))
        return true;
    return false;
}

}
<|endoftext|>


<commit_before>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#define CATCH_CONFIG_RUNNER
#include "catch.hpp"
#include "mfem.hpp"
#include <fstream>
#include <iostream>
#include "../../../fem/libceed/ceed.hpp"

using namespace mfem;

namespace ceed_test
{

double coeff_function(const Vector &x)
{
   return 1 + x[0]*x[0];
}

static std::string getString(AssemblyLevel assembly)
{
   switch (assembly)
   {
   case AssemblyLevel::NONE:
      return "NONE";
      break;
   case AssemblyLevel::PARTIAL:
      return "PARTIAL";
      break;
   case AssemblyLevel::ELEMENT:
      return "ELEMENT";
      break;
   case AssemblyLevel::FULL:
      return "FULL";
      break;
   case AssemblyLevel::LEGACYFULL:
      return "LEGACYFULL";
      break;
   }
}

static std::string getString(CeedCoeff coeff_type)
{
   switch (coeff_type)
   {
   case CeedCoeff::Const:
      return "Const";
      break;
   case CeedCoeff::Grid:
      return "Grid";
      break;
   case CeedCoeff::Quad:
      return "Quad";
      break;
   }
}

enum class Problem {Mass, Diffusion, VectorMass, VectorDiffusion};

static std::string getString(Problem pb)
{
   switch (pb)
   {
   case Problem::Mass:
      return "Mass";
      break;
   case Problem::Diffusion:
      return "Diffusion";
      break;
   case Problem::VectorMass:
      return "VectorMass";
      break;
   case Problem::VectorDiffusion:
      return "VectorDiffusion";
      break;
   }
}

void test_ceed_operator(const char* input, int order, const CeedCoeff coeff_type,
                        const Problem pb, const AssemblyLevel assembly)
{
   std::string section = "assembly: " + getString(assembly) + "\n" +
                         "coeff_type: " + getString(coeff_type) + "\n" +
                         "pb: " + getString(pb) + "\n" +
                         "order: " + std::to_string(order) + "\n" +
                         "mesh: " + input;
   INFO(section);
   Mesh mesh(input, 1, 1);
   mesh.EnsureNodes();
   int dim = mesh.Dimension();

   H1_FECollection fec(order, dim);
   bool vecOp = pb == Problem::VectorMass || pb == Problem::VectorDiffusion;
   const int vdim = vecOp ? dim : 1;
   FiniteElementSpace fespace(&mesh, &fec, vdim);

   BilinearForm k_test(&fespace);
   BilinearForm k_ref(&fespace);

   GridFunction gf(&fespace);
   FunctionCoefficient f_coeff(coeff_function);

   Coefficient *coeff = nullptr;
   switch (coeff_type)
   {
      case CeedCoeff::Const:
         coeff = new ConstantCoefficient(1.0);
         break;
      case CeedCoeff::Grid:
         gf.ProjectCoefficient(f_coeff);
         coeff = new GridFunctionCoefficient(&gf);
         break;
      case CeedCoeff::Quad:
         coeff = &f_coeff;
         break;
      default:
         mfem_error("Unexpected coefficient type.");
         break;
   }

   switch (pb)
   {
   case Problem::Mass:
      k_ref.AddDomainIntegrator(new MassIntegrator(*coeff));
      k_test.AddDomainIntegrator(new MassIntegrator(*coeff));
      break;
   case Problem::Diffusion:
      k_ref.AddDomainIntegrator(new DiffusionIntegrator(*coeff));
      k_test.AddDomainIntegrator(new DiffusionIntegrator(*coeff));
      break;
   case Problem::VectorMass:
      k_ref.AddDomainIntegrator(new VectorMassIntegrator(*coeff));
      k_test.AddDomainIntegrator(new VectorMassIntegrator(*coeff));
      break;
   case Problem::VectorDiffusion:
      k_ref.AddDomainIntegrator(new VectorDiffusionIntegrator(*coeff));
      k_test.AddDomainIntegrator(new VectorDiffusionIntegrator(*coeff));
      break;
   }

   k_ref.Assemble();
   k_ref.Finalize();

   k_test.SetAssemblyLevel(assembly);
   k_test.Assemble();

   GridFunction x(&fespace), y_ref(&fespace), y_test(&fespace);

   x.Randomize(1);

   k_ref.Mult(x,y_ref);
   k_test.Mult(x,y_test);

   y_test -= y_ref;

   REQUIRE(y_test.Norml2() < 1.e-12);
}

TEST_CASE("CEED", "[CEED]")
{
   auto assembly = GENERATE(AssemblyLevel::PARTIAL);
   auto coeff_type = GENERATE(CeedCoeff::Const,CeedCoeff::Grid,CeedCoeff::Quad);
   auto pb = GENERATE(Problem::Mass,Problem::Diffusion,
                      Problem::VectorMass,Problem::VectorDiffusion);
   auto order = GENERATE(4);
   auto mesh = GENERATE("../../data/inline-quad.mesh","../../data/star-q3.mesh",
                        "../../data/inline-hex.mesh","../../data/fichera-q3.mesh",
                        "../../data/amr-quad.mesh","../../data/fichera-amr.mesh");
   test_ceed_operator(mesh, order, coeff_type, pb, assembly);
} // test case

} // namespace ceed_test

int main(int argc, char *argv[])
{
   // There must be exactly one instance.
   Catch::Session session;

   const char *device_str = (argc == 1) ? "ceed-cpu" : argv[argc-1];

   // Apply provided command line arguments.
   int r = session.applyCommandLine((argc == 1) ? argc : argc - 1, argv);
   if (r != 0)
   {
      return r;
   }

   Device device(device_str);

   int result = session.run();

   return result;
}
<commit_msg>Modiify test_ceed for Vector Mass and Diffusion.<commit_after>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#define CATCH_CONFIG_RUNNER
#include "catch.hpp"
#include "mfem.hpp"
#include <fstream>
#include <iostream>
#include "../../../fem/libceed/ceed.hpp"

using namespace mfem;

namespace ceed_test
{

double coeff_function(const Vector &x)
{
   return 1.0 + x[0]*x[0];
}

static std::string getString(AssemblyLevel assembly)
{
   switch (assembly)
   {
   case AssemblyLevel::NONE:
      return "NONE";
      break;
   case AssemblyLevel::PARTIAL:
      return "PARTIAL";
      break;
   case AssemblyLevel::ELEMENT:
      return "ELEMENT";
      break;
   case AssemblyLevel::FULL:
      return "FULL";
      break;
   case AssemblyLevel::LEGACYFULL:
      return "LEGACYFULL";
      break;
   }
}

static std::string getString(CeedCoeff coeff_type)
{
   switch (coeff_type)
   {
   case CeedCoeff::Const:
      return "Const";
      break;
   case CeedCoeff::Grid:
      return "Grid";
      break;
   case CeedCoeff::Quad:
      return "Quad";
      break;
   }
}

enum class Problem {Mass, Diffusion, VectorMass, VectorDiffusion};

static std::string getString(Problem pb)
{
   switch (pb)
   {
   case Problem::Mass:
      return "Mass";
      break;
   case Problem::Diffusion:
      return "Diffusion";
      break;
   case Problem::VectorMass:
      return "VectorMass";
      break;
   case Problem::VectorDiffusion:
      return "VectorDiffusion";
      break;
   }
}

void test_ceed_operator(const char* input, int order, const CeedCoeff coeff_type,
                        const Problem pb, const AssemblyLevel assembly)
{
   std::string section = "assembly: " + getString(assembly) + "\n" +
                         "coeff_type: " + getString(coeff_type) + "\n" +
                         "pb: " + getString(pb) + "\n" +
                         "order: " + std::to_string(order) + "\n" +
                         "mesh: " + input;
   INFO(section);
   Mesh mesh(input, 1, 1);
   mesh.EnsureNodes();
   int dim = mesh.Dimension();

   H1_FECollection fec(order, dim);
   bool vecOp = pb == Problem::VectorMass || pb == Problem::VectorDiffusion;
   const int vdim = vecOp ? dim : 1;
   FiniteElementSpace fes(&mesh, &fec, vdim);

   BilinearForm k_test(&fes);
   BilinearForm k_ref(&fes);

   FiniteElementSpace coeff_fes(&mesh, &fec);
   GridFunction gf(&coeff_fes);
   FunctionCoefficient f_coeff(coeff_function);

   Coefficient *coeff = nullptr;
   switch (coeff_type)
   {
      case CeedCoeff::Const:
         coeff = new ConstantCoefficient(1.0);
         break;
      case CeedCoeff::Grid:
         gf.ProjectCoefficient(f_coeff);
         coeff = new GridFunctionCoefficient(&gf);
         break;
      case CeedCoeff::Quad:
         coeff = &f_coeff;
         break;
   }

   switch (pb)
   {
   case Problem::Mass:
      k_ref.AddDomainIntegrator(new MassIntegrator(*coeff));
      k_test.AddDomainIntegrator(new MassIntegrator(*coeff));
      break;
   case Problem::Diffusion:
      k_ref.AddDomainIntegrator(new DiffusionIntegrator(*coeff));
      k_test.AddDomainIntegrator(new DiffusionIntegrator(*coeff));
      break;
   case Problem::VectorMass:
      k_ref.AddDomainIntegrator(new VectorMassIntegrator(*coeff));
      k_test.AddDomainIntegrator(new VectorMassIntegrator(*coeff));
      break;
   case Problem::VectorDiffusion:
      k_ref.AddDomainIntegrator(new VectorDiffusionIntegrator(*coeff));
      k_test.AddDomainIntegrator(new VectorDiffusionIntegrator(*coeff));
      break;
   }

   k_ref.Assemble();
   k_ref.Finalize();

   k_test.SetAssemblyLevel(assembly);
   k_test.Assemble();

   GridFunction x(&fes), y_ref(&fes), y_test(&fes);

   x.Randomize(1);

   k_ref.Mult(x,y_ref);
   k_test.Mult(x,y_test);

   y_test -= y_ref;

   REQUIRE(y_test.Norml2() < 1.e-12);
}

TEST_CASE("CEED", "[CEED]")
{
   auto assembly = GENERATE(AssemblyLevel::PARTIAL);
   auto coeff_type = GENERATE(CeedCoeff::Const,CeedCoeff::Grid,CeedCoeff::Quad);
   auto pb = GENERATE(Problem::Mass,Problem::Diffusion,
                      Problem::VectorMass,Problem::VectorDiffusion);
   auto order = GENERATE(1,2,4);
   auto mesh = GENERATE("../../data/inline-quad.mesh","../../data/inline-hex.mesh",
                        "../../data/star.mesh","../../data/fichera.mesh",
                        // "../../data/star-q3.mesh","../../data/fichera-q3.mesh",
                        "../../data/amr-quad.mesh","../../data/fichera-amr.mesh");
   test_ceed_operator(mesh, order, coeff_type, pb, assembly);
} // test case

} // namespace ceed_test

int main(int argc, char *argv[])
{
   // There must be exactly one instance.
   Catch::Session session;

   const char *device_str = (argc == 1) ? "ceed-cpu" : argv[argc-1];

   // Apply provided command line arguments.
   int r = session.applyCommandLine((argc == 1) ? argc : argc - 1, argv);
   if (r != 0)
   {
      return r;
   }

   Device device(device_str);

   int result = session.run();

   return result;
}
<|endoftext|>


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

#include "CustomPaintWidget.h"
#include <math.h>
#include <QPainter>
#include "Code/Interface/QRDInterface.h"

CustomPaintWidget::CustomPaintWidget(QWidget *parent) : QWidget(parent)
{
  m_Ctx = NULL;
  m_Output = NULL;
  setAttribute(Qt::WA_OpaquePaintEvent);
  setMouseTracking(true);
  m_Tag = QFormatStr("custompaint%1").arg((uintptr_t) this);
}

CustomPaintWidget::CustomPaintWidget(ICaptureContext *c, QWidget *parent) : QWidget(parent)
{
  m_Ctx = c;
  m_Output = NULL;
  setAttribute(Qt::WA_OpaquePaintEvent);
  if(c)
    setAttribute(Qt::WA_PaintOnScreen);
  setMouseTracking(true);
  m_Tag = QFormatStr("custompaint%1").arg((uintptr_t) this);
}

CustomPaintWidget::~CustomPaintWidget()
{
}

void CustomPaintWidget::mousePressEvent(QMouseEvent *e)
{
  emit clicked(e);
}

void CustomPaintWidget::mouseDoubleClickEvent(QMouseEvent *event)
{
  emit(doubleClicked(event));
}

void CustomPaintWidget::mouseMoveEvent(QMouseEvent *e)
{
  emit mouseMove(e);
}

void CustomPaintWidget::wheelEvent(QWheelEvent *e)
{
  emit mouseWheel(e);
}

void CustomPaintWidget::resizeEvent(QResizeEvent *e)
{
  emit resize(e);
}

void CustomPaintWidget::keyPressEvent(QKeyEvent *e)
{
  emit keyPress(e);
}

void CustomPaintWidget::keyReleaseEvent(QKeyEvent *e)
{
  emit keyRelease(e);
}

void CustomPaintWidget::paintEvent(QPaintEvent *e)
{
  if(m_Ctx)
  {
    if(m_Output != NULL)
      m_Ctx->Replay().AsyncInvoke(m_Tag, [this](IReplayController *r) { m_Output->Display(); });
  }
  else if(m_Dark == m_Light)
  {
    QPainter p(this);
    p.fillRect(rect(), m_Dark);
  }
  else
  {
    int numX = (int)ceil((float)rect().width() / 64.0f);
    int numY = (int)ceil((float)rect().height() / 64.0f);

    QPainter p(this);
    for(int x = 0; x < numX; x++)
    {
      for(int y = 0; y < numY; y++)
      {
        QColor &col = ((x % 2) == (y % 2)) ? m_Dark : m_Light;

        p.fillRect(QRect(x * 64, y * 64, 64, 64), col);
      }
    }
  }
}

#if defined(RENDERDOC_PLATFORM_APPLE)
bool CustomPaintWidget::event(QEvent *e)
{
  if(m_Ctx && e->type() == QEvent::UpdateRequest)
    paintEvent(NULL);
  return QWidget::event(e);
}
#endif
<commit_msg>Include "QEvent"<commit_after>/******************************************************************************
 * The MIT License (MIT)
 *
 * Copyright (c) 2019-2020 Baldur Karlsson
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 ******************************************************************************/

#include "CustomPaintWidget.h"
#include <math.h>
#include <QEvent>
#include <QPainter>
#include "Code/Interface/QRDInterface.h"

CustomPaintWidget::CustomPaintWidget(QWidget *parent) : QWidget(parent)
{
  m_Ctx = NULL;
  m_Output = NULL;
  setAttribute(Qt::WA_OpaquePaintEvent);
  setMouseTracking(true);
  m_Tag = QFormatStr("custompaint%1").arg((uintptr_t) this);
}

CustomPaintWidget::CustomPaintWidget(ICaptureContext *c, QWidget *parent) : QWidget(parent)
{
  m_Ctx = c;
  m_Output = NULL;
  setAttribute(Qt::WA_OpaquePaintEvent);
  if(c)
    setAttribute(Qt::WA_PaintOnScreen);
  setMouseTracking(true);
  m_Tag = QFormatStr("custompaint%1").arg((uintptr_t) this);
}

CustomPaintWidget::~CustomPaintWidget()
{
}

void CustomPaintWidget::mousePressEvent(QMouseEvent *e)
{
  emit clicked(e);
}

void CustomPaintWidget::mouseDoubleClickEvent(QMouseEvent *event)
{
  emit(doubleClicked(event));
}

void CustomPaintWidget::mouseMoveEvent(QMouseEvent *e)
{
  emit mouseMove(e);
}

void CustomPaintWidget::wheelEvent(QWheelEvent *e)
{
  emit mouseWheel(e);
}

void CustomPaintWidget::resizeEvent(QResizeEvent *e)
{
  emit resize(e);
}

void CustomPaintWidget::keyPressEvent(QKeyEvent *e)
{
  emit keyPress(e);
}

void CustomPaintWidget::keyReleaseEvent(QKeyEvent *e)
{
  emit keyRelease(e);
}

void CustomPaintWidget::paintEvent(QPaintEvent *e)
{
  if(m_Ctx)
  {
    if(m_Output != NULL)
      m_Ctx->Replay().AsyncInvoke(m_Tag, [this](IReplayController *r) { m_Output->Display(); });
  }
  else if(m_Dark == m_Light)
  {
    QPainter p(this);
    p.fillRect(rect(), m_Dark);
  }
  else
  {
    int numX = (int)ceil((float)rect().width() / 64.0f);
    int numY = (int)ceil((float)rect().height() / 64.0f);

    QPainter p(this);
    for(int x = 0; x < numX; x++)
    {
      for(int y = 0; y < numY; y++)
      {
        QColor &col = ((x % 2) == (y % 2)) ? m_Dark : m_Light;

        p.fillRect(QRect(x * 64, y * 64, 64, 64), col);
      }
    }
  }
}

#if defined(RENDERDOC_PLATFORM_APPLE)
bool CustomPaintWidget::event(QEvent *e)
{
  if(m_Ctx && e->type() == QEvent::UpdateRequest)
    paintEvent(NULL);
  return QWidget::event(e);
}
#endif
<|endoftext|>


<commit_before>#include "pch.h"
#include <iostream>

int
_cdecl
wmain(
    __in              ULONG argc,
    __in_ecount(argc) PWCHAR argv[]
    )
{
    PrintMessage(L"viogpuap.exe built on %ws %ws\n", _CRT_WIDE(__DATE__) , _CRT_WIDE(__TIME__));

    PipeClient* pClient = NULL;
    if (argc == 2 && iswdigit(argv[1][0]))
    {
        std::wstring pipename = PIPE_NAME;
        pipename.append(argv[1]);
        if (pipename.length()) {
            pClient = new PipeClient(pipename);
            pClient->Init();
        }
    }

    GpuAdaptersMgr* m_pMgr;
    m_pMgr = new GpuAdaptersMgr();
    if (!m_pMgr || !m_pMgr->Init()) {
        ErrorHandler("Start GpuAdaptersMgr", GetLastError());
        return 0;
    }

    if (pClient) {
        pClient->WaitRunning();
    }
    else {
        while (getchar() != 'q');
    }

    m_pMgr->Close();
    delete m_pMgr;

    if (pClient) {
        pClient->Close();
        delete pClient;
        pClient = NULL;
    }
}
<commit_msg>[viogpudo] fix a problem reported by Coverity Scan (which for some reason expects int main function to be returning a value explicitly)<commit_after>#include "pch.h"
#include <iostream>

int
_cdecl
wmain(
    __in              ULONG argc,
    __in_ecount(argc) PWCHAR argv[]
    )
{
    PrintMessage(L"viogpuap.exe built on %ws %ws\n", _CRT_WIDE(__DATE__) , _CRT_WIDE(__TIME__));

    PipeClient* pClient = NULL;
    if (argc == 2 && iswdigit(argv[1][0]))
    {
        std::wstring pipename = PIPE_NAME;
        pipename.append(argv[1]);
        if (pipename.length()) {
            pClient = new PipeClient(pipename);
            pClient->Init();
        }
    }

    GpuAdaptersMgr* m_pMgr;
    m_pMgr = new GpuAdaptersMgr();
    if (!m_pMgr || !m_pMgr->Init()) {
        ErrorHandler("Start GpuAdaptersMgr", GetLastError());
        return 0;
    }

    if (pClient) {
        pClient->WaitRunning();
    }
    else {
        while (getchar() != 'q');
    }

    m_pMgr->Close();
    delete m_pMgr;
    m_pMgr = NULL;

    if (pClient) {
        pClient->Close();
        delete pClient;
        pClient = NULL;
    }
    return 0;
}
<|endoftext|>


<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (testabilitydriver@nokia.com)
**
** This file is part of Testability Driver Qt Agent
**
** If you have questions regarding the use of this file, please contact
** Nokia at testabilitydriver@nokia.com .
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include <QDebug>
#include <QProcess>
#include <QCoreApplication>

#include <taslogger.h>
#include <tascoreutils.h>
#include <tasdatashare.h>

#include "tasdeviceutils.h"
#include "tasclientmanager.h"

#include "startappservice.h"

#if (defined(Q_OS_WIN32) || defined(Q_OS_WINCE))
#include <windows.h>

#elif (defined(Q_OS_UNIX) || defined(Q_OS_WS_MAC))
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "private/qcore_unix_p.h"
#endif

const char* const SET_PARAMS_ONLY = "set_params_only";
const char* const DETACH_MODE = "detached";
const char* const NO_WAIT = "noWait";

StartAppService::StartAppService()
{}

StartAppService::~StartAppService()
{}

bool StartAppService::executeService(TasCommandModel& model, TasResponse& response)
{
    if(model.service() == serviceName() ){
        // Turn screen on.
        TasDeviceUtils::resetInactivity();

        TasCommand* command = getCommandParameters(model, "Run");
        if(command){
            startApplication(*command, response);
        }
        else{
            TasLogger::logger()->error("StartAppService::executeService no Run command found!");
            response.setErrorMessage("Could not parse Run command from the request!");
        }
        return true;
    }
    else{
        return false;
    }
}

/*!
  Attempts to start a process using the application path send in the command model.
 */
void StartAppService::startApplication(TasCommand& command, TasResponse& response)
{
    QString applicationPath = command.parameter("application_path");
    QString args = command.parameter("arguments");
    QString envs = command.parameter("environment");
    TasLogger::logger()->debug(QString("TasServer::startApplication: '%1'").arg(applicationPath));
    TasLogger::logger()->debug(QString("TasServer::startApplication: Arguments: '%1'").arg(args));
    TasLogger::logger()->debug(QString("TasServer::startApplication: Environment: '%1'").arg(envs));
    QStringList arguments = args.split(",");
    QStringList environmentVars = envs.split(" ");

    setRuntimeParams(command);

    if(arguments.contains(SET_PARAMS_ONLY)){
        // do not start app, just need to set the parameters
        response.requester()->sendResponse(response.messageId(), QString("0"));
    }
    else{
        arguments.removeAll(DETACH_MODE);
        arguments.removeAll(NO_WAIT);
        launchDetached(applicationPath, arguments, environmentVars, response);
    }
}

void StartAppService::setRuntimeParams(TasCommand& command)
{
    QString applicationPath = command.parameter("application_path");
    QString eventList = command.parameter("events_to_listen");
    QString signalList = command.parameter("signals_to_listen");
    TasLogger::logger()->debug("StartAppService::setRuntimeParams signals: " + signalList);
    if(!eventList.isEmpty() || !signalList.isEmpty()){
        TasSharedData startupData(eventList.split(","), signalList.split(","));
        QString identifier = TasCoreUtils::parseExecutable(applicationPath);
        if(!TasClientManager::instance()->writeStartupData(identifier, startupData)){
            TasLogger::logger()->error("StartAppService::setRuntimeParams could not set run time params for identifier: " + identifier + "!");
        }
        else {
            TasLogger::logger()->error("StartAppService::setRuntimeParams set with identifier: " + identifier);
        }
    }
}

QHash<QString, QString> StartAppService::parseEnvironmentVariables(const QString& env) {
    QHash<QString,QString> vars;
    QStringList var = env.split(" ");
    foreach(QString str, var) {
        QStringList key = str.split("=");
        if (key.size() == 2) {
            vars[key.at(0)] = key.at(1);
        }
    }
    return vars;
}

#ifdef Q_OS_SYMBIAN
//Qt startDetach seems to leak memory so need to do it for now.
//to be removed when fix in qt
static void qt_create_symbian_commandline(
    const QStringList &arguments, const QString &nativeArguments, QString &commandLine)
{
    for (int i = 0; i < arguments.size(); ++i) {
        QString tmp = arguments.at(i);
        tmp.replace(QLatin1String("\\\""), QLatin1String("\\\\\""));
        tmp.replace(QLatin1String("\""), QLatin1String("\\\""));
        if (tmp.isEmpty() || tmp.contains(QLatin1Char(' ')) || tmp.contains(QLatin1Char('\t'))) {
            QString endQuote(QLatin1String("\""));
            int i = tmp.length();
            while (i > 0 && tmp.at(i - 1) == QLatin1Char('\\')) {
                --i;
                endQuote += QLatin1String("\\");
            }
            commandLine += QLatin1String("\"") + tmp.left(i) + endQuote + QLatin1Char(' ');
        } else {
            commandLine += tmp + QLatin1Char(' ');
        }
    }

    if (!nativeArguments.isEmpty())
        commandLine += nativeArguments;
    else if (!commandLine.isEmpty()) // Chop the extra trailing space if any arguments were appended
        commandLine.chop(1);
}
#endif

void StartAppService::launchDetached(const QString& applicationPath, const QStringList& arguments, const QStringList& environmentVars, TasResponse& response)
{

#ifdef Q_OS_SYMBIAN
//Qt startDetach seems to leak memory so need to do it for now.
//to be removed when fix in qt
    qint64 pid;
    QString commandLine;
    QString nativeArguments;
    qt_create_symbian_commandline(arguments, nativeArguments, commandLine);
    TPtrC program_ptr(reinterpret_cast<const TText*>(applicationPath.constData()));
    TPtrC cmdline_ptr(reinterpret_cast<const TText*>(commandLine.constData()));
    RProcess process;
    if( process.Create(program_ptr, cmdline_ptr) == KErrNone){
        process.Resume();
        pid = process.Id().Id();
        process.Close();
        TasClientManager::instance()->addStartedApp(applicationPath, QDateTime::currentDateTime().toString("yyyyMMddhhmmsszzz"));
        response.setData(QString::number(pid));
    }require 'tdriver'
@sut = TDriver.sut(:Id => 'sut_qt')
@app = @sut.run(:name => '/usr/bin/calculator')

#elif (defined(Q_OS_WIN32) || defined(Q_OS_WINCE))

    STARTUPINFO si;
    PROCESS_INFORMATION pi;

    ZeroMemory( &si, sizeof(si) );
    si.cb = sizeof(si);
    ZeroMemory( &pi, sizeof(pi) );

    // Arguments
    QString argv = applicationPath + arguments.join(" ");

    // Environment bloc variable
    QStringList envList = QProcess::systemEnvironment() << environmentVars;

    WCHAR envp[envList.join(" ").length() + 2]; // just counting memory in cluding the NULL (\0) string ends and binal NULL block end
    LPTSTR env = (LPTSTR) envp;

    for (int i = 0; i < envList.length(); i++)
    {
        env = lstrcpy( env, (LPTSTR) envList[i].utf16() );
        env += lstrlen( (LPTSTR) envList[i].utf16() ) +1;
    }
    *env = (WCHAR) NULL;

    // DEBUG
//    LPTSTR lpszVariable = envp;
//    while (*lpszVariable) //while not null
//    {
//        TasLogger::logger()->debug( QString("TasServer::launchDetached: ENV: %1").arg(QString::fromUtf16((ushort *) lpszVariable)) );
//        lpszVariable += lstrlen(lpszVariable) + 1;
//    }

    // Start the child process.
    if( CreateProcess( NULL,   // No module name (use command line)
        (WCHAR *) argv.utf16(),           // Command line
        NULL,           // Process handle not inheritable
        NULL,           // Thread handle not inheritable
        FALSE,          // Set handle inheritance to FALSE
        CREATE_UNICODE_ENVIRONMENT,              // 0 for no creation flags
        (LPVOID) envp,           // Use parent's environment block
        NULL,           // Use parent's starting directory
        &si,            // Pointer to STARTUPINFO structure
        &pi )           // Pointer to PROCESS_INFORMATION structure
    )
    {
        QString pid = QString::number(pi.dwProcessId);
        CloseHandle( pi.hProcess );
        CloseHandle( pi.hThread );
        TasLogger::logger()->debug( QString("TasServer::launchDetached: Child PID: %1").arg(pid) );
        response.setData(pid);

    }

#elif (defined(Q_OS_UNIX) || defined(Q_OS_WS_MAC))

    pid_t pid, sid, grandpid;

    int pidPipeDesc[2];
    qt_safe_pipe(pidPipeDesc);

    // Create Arguments ARRAY (application path to executable on first element)
    QStringList paramList;
    paramList << applicationPath;
    paramList << arguments;
    char **paramListArray = new char*[ paramList.length() + 1 ];
    for( int i = 0; i < paramList.length(); i++)
    {
        QByteArray variable = ((QString) paramList[i]).toLocal8Bit();
        char *const variablePtr = new char[variable.length() + 1];
        strcpy(variablePtr, variable.data());
        paramListArray[i] = variablePtr;
    }
     paramListArray[paramList.length()] = NULL;

    // Create environment Array with NULL end element
    QStringList envList = QProcess::systemEnvironment() << environmentVars;
    //TasLogger::logger()->debug(QString("TasServer::startApplication: ALL '%1'").arg(envList.join(",")));
    //TasLogger::logger()->debug(QString("TasServer::startApplication: USER '%1'").arg(environmentVars.join(",")));

    char **envListArray = new char*[ envList.length() + 1 ];
    for( int i = 0; i < envList.length(); i++)
    {
        QByteArray variable = ((QString) envList[i]).toLocal8Bit();
        char *const variablePtr = new char[variable.length() + 1];
        strcpy(variablePtr, variable.data());
        envListArray[i] = variablePtr;
    }
    envListArray[envList.length()] = NULL;

    // START MAKING CHILDREN HERE :D
    // Child
    if ( (pid = fork()) == 0) {

        // We are only going to write on the pipe for papa
        qt_safe_close(pidPipeDesc[0]);

        // Create new session for the process (detatch from parent process group)
        sid = setsid();
        if ( sid < 0 )
        {
            TasLogger::logger()->error( QString("TasServer::launchDetached:Failed to detach child."));
            exit(1);
        }

        // Grandchild
        if ( ( grandpid = fork() ) == 0 )
        {
            // Try see if we don't need path
            execve( paramListArray[0], paramListArray, envListArray);

            // Try also on all path directories if above fails
            const QString path = QString::fromLocal8Bit(::getenv("PATH"));
            const QString file = QString::fromLocal8Bit(paramListArray[0]);
            if (!path.isEmpty())
            {
                QStringList pathEntries = path.split(QLatin1Char(':'));
                for (int k = 0; k < pathEntries.size(); ++k) {
                    QByteArray tmp = QFile::encodeName(pathEntries.at(k));
                    if (!tmp.endsWith('/')) tmp += '/';
                    tmp += QFile::encodeName(file);
                    paramListArray[0] = tmp.data();
                    TasLogger::logger()->error( QString("TasServer::launchDetached: PATH = '%1'").arg((char *) paramListArray[0]));
                    execve( paramListArray[0], paramListArray, envListArray);

                }
             }

            TasLogger::logger()->error( QString("TasServer::launchDetached: Granhild process died straight away."));
        }

        // Child exit in order to end detachment of grandchild
        else if( grandpid > 0)
        {
            qt_safe_write(pidPipeDesc[1], &grandpid, sizeof(pid_t));
            qt_safe_close(pidPipeDesc[1]);
            _exit(0);
        }

    }

    // Parent
    else if (pid > 0) {

        // We are only going to read from the pipe from child
        qt_safe_close(pidPipeDesc[1]);
        pid_t actualpid = 0;
        qt_safe_read(pidPipeDesc[0], &actualpid, sizeof(pid_t));
        qt_safe_close(pidPipeDesc[0]);
        pid = actualpid;

        // Free memory
        for (int i = 0; i < paramList.length(); i++ )
        {
            delete [] paramListArray[i];
        }
        delete [] paramListArray;

        for (int i = 0; i < envList.length(); i++ )
        {
            delete [] envListArray[i];
        }
        delete [] envListArray;

        TasLogger::logger()->debug( QString("TasServer::launchDetached: Child PID: %1").arg((int)pid) );
        response.setData(QString::number((int) pid));
    }

#else
    qint64 pid;
    if(QProcess::startDetached(applicationPath, arguments, ".", &pid)){

	    TasClientManager::instance()->addStartedApp(applicationPath, QDateTime::currentDateTime().toString("yyyyMMddhhmmsszzz"));
        response.setData(QString::number(pid));
    }
#endif
    else{
        TasLogger::logger()->error("TasServer::launchDetached: Could not start the application " + applicationPath);
        response.setErrorMessage("Could not start the application " + applicationPath);
    }
}

<commit_msg>Rolled back changes on startapp service<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (testabilitydriver@nokia.com)
**
** This file is part of Testability Driver Qt Agent
**
** If you have questions regarding the use of this file, please contact
** Nokia at testabilitydriver@nokia.com .
**
** 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
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include <QDebug>
#include <QProcess>
#include <QCoreApplication>

#include <taslogger.h>
#include <tascoreutils.h>
#include <tasdatashare.h>

#include "tasdeviceutils.h"
#include "tasclientmanager.h"

#include "startappservice.h"

#if (defined(Q_OS_WIN32) || defined(Q_OS_WINCE))
#include <windows.h>

#elif (defined(Q_OS_UNIX) || defined(Q_OS_WS_MAC))
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "private/qcore_unix_p.h"
#endif

const char* const SET_PARAMS_ONLY = "set_params_only";
const char* const DETACH_MODE = "detached";
const char* const NO_WAIT = "noWait";

StartAppService::StartAppService()
{}

StartAppService::~StartAppService()
{}

bool StartAppService::executeService(TasCommandModel& model, TasResponse& response)
{
    if(model.service() == serviceName() ){
        // Turn screen on.
        TasDeviceUtils::resetInactivity();

        TasCommand* command = getCommandParameters(model, "Run");
        if(command){
            startApplication(*command, response);
        }
        else{
            TasLogger::logger()->error("StartAppService::executeService no Run command found!");
            response.setErrorMessage("Could not parse Run command from the request!");
        }
        return true;
    }
    else{
        return false;
    }
}

/*!
  Attempts to start a process using the application path send in the command model.
 */
void StartAppService::startApplication(TasCommand& command, TasResponse& response)
{
    QString applicationPath = command.parameter("application_path");
    QString args = command.parameter("arguments");
    QString envs = command.parameter("environment");
    TasLogger::logger()->debug(QString("TasServer::startApplication: '%1'").arg(applicationPath));
    TasLogger::logger()->debug(QString("TasServer::startApplication: Arguments: '%1'").arg(args));
    TasLogger::logger()->debug(QString("TasServer::startApplication: Environment: '%1'").arg(envs));
    QStringList arguments = args.split(",");
    QStringList environmentVars = envs.split(" ");

    setRuntimeParams(command);

    if(arguments.contains(SET_PARAMS_ONLY)){
        // do not start app, just need to set the parameters
        response.requester()->sendResponse(response.messageId(), QString("0"));
    }
    else{
        arguments.removeAll(DETACH_MODE);
        arguments.removeAll(NO_WAIT);
        launchDetached(applicationPath, arguments, environmentVars, response);
    }
}

void StartAppService::setRuntimeParams(TasCommand& command)
{
    QString applicationPath = command.parameter("application_path");
    QString eventList = command.parameter("events_to_listen");
    QString signalList = command.parameter("signals_to_listen");
    TasLogger::logger()->debug("StartAppService::setRuntimeParams signals: " + signalList);
    if(!eventList.isEmpty() || !signalList.isEmpty()){
        TasSharedData startupData(eventList.split(","), signalList.split(","));
        QString identifier = TasCoreUtils::parseExecutable(applicationPath);
        if(!TasClientManager::instance()->writeStartupData(identifier, startupData)){
            TasLogger::logger()->error("StartAppService::setRuntimeParams could not set run time params for identifier: " + identifier + "!");
        }
        else {
            TasLogger::logger()->error("StartAppService::setRuntimeParams set with identifier: " + identifier);
        }
    }
}

QHash<QString, QString> StartAppService::parseEnvironmentVariables(const QString& env) {
    QHash<QString,QString> vars;
    QStringList var = env.split(" ");
    foreach(QString str, var) {
        QStringList key = str.split("=");
        if (key.size() == 2) {
            vars[key.at(0)] = key.at(1);
        }
    }
    return vars;
}

#ifdef Q_OS_SYMBIAN
//Qt startDetach seems to leak memory so need to do it for now.
//to be removed when fix in qt
static void qt_create_symbian_commandline(
    const QStringList &arguments, const QString &nativeArguments, QString &commandLine)
{
    for (int i = 0; i < arguments.size(); ++i) {
        QString tmp = arguments.at(i);
        tmp.replace(QLatin1String("\\\""), QLatin1String("\\\\\""));
        tmp.replace(QLatin1String("\""), QLatin1String("\\\""));
        if (tmp.isEmpty() || tmp.contains(QLatin1Char(' ')) || tmp.contains(QLatin1Char('\t'))) {
            QString endQuote(QLatin1String("\""));
            int i = tmp.length();
            while (i > 0 && tmp.at(i - 1) == QLatin1Char('\\')) {
                --i;
                endQuote += QLatin1String("\\");
            }
            commandLine += QLatin1String("\"") + tmp.left(i) + endQuote + QLatin1Char(' ');
        } else {
            commandLine += tmp + QLatin1Char(' ');
        }
    }

    if (!nativeArguments.isEmpty())
        commandLine += nativeArguments;
    else if (!commandLine.isEmpty()) // Chop the extra trailing space if any arguments were appended
        commandLine.chop(1);
}
#endif

void StartAppService::launchDetached(const QString& applicationPath, const QStringList& arguments, const QStringList& environmentVars, TasResponse& response)
{

#ifdef Q_OS_SYMBIAN
//Qt startDetach seems to leak memory so need to do it for now.
//to be removed when fix in qt
    qint64 pid;
    QString commandLine;
    QString nativeArguments;
    qt_create_symbian_commandline(arguments, nativeArguments, commandLine);
    TPtrC program_ptr(reinterpret_cast<const TText*>(applicationPath.constData()));
    TPtrC cmdline_ptr(reinterpret_cast<const TText*>(commandLine.constData()));
    RProcess process;
    if( process.Create(program_ptr, cmdline_ptr) == KErrNone){
        process.Resume();
        pid = process.Id().Id();
        process.Close();
        TasClientManager::instance()->addStartedApp(applicationPath, QDateTime::currentDateTime().toString("yyyyMMddhhmmsszzz"));
        response.setData(QString::number(pid));
    }require 'tdriver'
@sut = TDriver.sut(:Id => 'sut_qt')
@app = @sut.run(:name => '/usr/bin/calculator')

#elif (defined(Q_OS_WIN32) && defined(Q_OS_WINCE) && defined(Q_OS_UNIX)) //ignore untill fixed

    STARTUPINFO si;
    PROCESS_INFORMATION pi;

    ZeroMemory( &si, sizeof(si) );
    si.cb = sizeof(si);
    ZeroMemory( &pi, sizeof(pi) );

    // Arguments
    QString argv = applicationPath + arguments.join(" ");

    // Environment bloc variable
    QStringList envList = QProcess::systemEnvironment() << environmentVars;

    WCHAR envp[envList.join(" ").length() + 2]; // just counting memory in cluding the NULL (\0) string ends and binal NULL block end
    LPTSTR env = (LPTSTR) envp;

    for (int i = 0; i < envList.length(); i++)
    {
        env = lstrcpy( env, (LPTSTR) envList[i].utf16() );
        env += lstrlen( (LPTSTR) envList[i].utf16() ) +1;
    }
    *env = (WCHAR) NULL;

    // DEBUG
//    LPTSTR lpszVariable = envp;
//    while (*lpszVariable) //while not null
//    {
//        TasLogger::logger()->debug( QString("TasServer::launchDetached: ENV: %1").arg(QString::fromUtf16((ushort *) lpszVariable)) );
//        lpszVariable += lstrlen(lpszVariable) + 1;
//    }

    // Start the child process.
    if( CreateProcess( NULL,   // No module name (use command line)
        (WCHAR *) argv.utf16(),           // Command line
        NULL,           // Process handle not inheritable
        NULL,           // Thread handle not inheritable
        FALSE,          // Set handle inheritance to FALSE
        CREATE_UNICODE_ENVIRONMENT,              // 0 for no creation flags
        (LPVOID) envp,           // Use parent's environment block
        NULL,           // Use parent's starting directory
        &si,            // Pointer to STARTUPINFO structure
        &pi )           // Pointer to PROCESS_INFORMATION structure
    )
    {
        QString pid = QString::number(pi.dwProcessId);
        CloseHandle( pi.hProcess );
        CloseHandle( pi.hThread );
        TasLogger::logger()->debug( QString("TasServer::launchDetached: Child PID: %1").arg(pid) );
        response.setData(pid);

    }

#elif (defined(Q_OS_UNIX) && defined(Q_OS_WS_MAC) && defined(Q_OS_WIN32) )

    pid_t pid, sid, grandpid;

    int pidPipeDesc[2];
    qt_safe_pipe(pidPipeDesc);

    // Create Arguments ARRAY (application path to executable on first element)
    QStringList paramList;
    paramList << applicationPath;
    paramList << arguments;
    char **paramListArray = new char*[ paramList.length() + 1 ];
    for( int i = 0; i < paramList.length(); i++)
    {
        QByteArray variable = ((QString) paramList[i]).toLocal8Bit();
        char *const variablePtr = new char[variable.length() + 1];
        strcpy(variablePtr, variable.data());
        paramListArray[i] = variablePtr;
    }
     paramListArray[paramList.length()] = NULL;

    // Create environment Array with NULL end element
    QStringList envList = QProcess::systemEnvironment() << environmentVars;
    //TasLogger::logger()->debug(QString("TasServer::startApplication: ALL '%1'").arg(envList.join(",")));
    //TasLogger::logger()->debug(QString("TasServer::startApplication: USER '%1'").arg(environmentVars.join(",")));

    char **envListArray = new char*[ envList.length() + 1 ];
    for( int i = 0; i < envList.length(); i++)
    {
        QByteArray variable = ((QString) envList[i]).toLocal8Bit();
        char *const variablePtr = new char[variable.length() + 1];
        strcpy(variablePtr, variable.data());
        envListArray[i] = variablePtr;
    }
    envListArray[envList.length()] = NULL;

    // START MAKING CHILDREN HERE :D
    // Child
    if ( (pid = fork()) == 0) {

        // We are only going to write on the pipe for papa
        qt_safe_close(pidPipeDesc[0]);

        // Create new session for the process (detatch from parent process group)
        sid = setsid();
        if ( sid < 0 )
        {
            TasLogger::logger()->error( QString("TasServer::launchDetached:Failed to detach child."));
            exit(1);
        }

        // Grandchild
        if ( ( grandpid = fork() ) == 0 )
        {
            // Try see if we don't need path
            execve( paramListArray[0], paramListArray, envListArray);

            // Try also on all path directories if above fails
            const QString path = QString::fromLocal8Bit(::getenv("PATH"));
            const QString file = QString::fromLocal8Bit(paramListArray[0]);
            if (!path.isEmpty())
            {
                QStringList pathEntries = path.split(QLatin1Char(':'));
                for (int k = 0; k < pathEntries.size(); ++k) {
                    QByteArray tmp = QFile::encodeName(pathEntries.at(k));
                    if (!tmp.endsWith('/')) tmp += '/';
                    tmp += QFile::encodeName(file);
                    paramListArray[0] = tmp.data();
                    TasLogger::logger()->error( QString("TasServer::launchDetached: PATH = '%1'").arg((char *) paramListArray[0]));
                    execve( paramListArray[0], paramListArray, envListArray);

                }
             }

            TasLogger::logger()->error( QString("TasServer::launchDetached: Granhild process died straight away."));
        }

        // Child exit in order to end detachment of grandchild
        else if( grandpid > 0)
        {
            qt_safe_write(pidPipeDesc[1], &grandpid, sizeof(pid_t));
            qt_safe_close(pidPipeDesc[1]);
            _exit(0);
        }

    }

    // Parent
    else if (pid > 0) {

        // We are only going to read from the pipe from child
        qt_safe_close(pidPipeDesc[1]);
        pid_t actualpid = 0;
        qt_safe_read(pidPipeDesc[0], &actualpid, sizeof(pid_t));
        qt_safe_close(pidPipeDesc[0]);
        pid = actualpid;

        // Free memory
        for (int i = 0; i < paramList.length(); i++ )
        {
            delete [] paramListArray[i];
        }
        delete [] paramListArray;

        for (int i = 0; i < envList.length(); i++ )
        {
            delete [] envListArray[i];
        }
        delete [] envListArray;

        TasLogger::logger()->debug( QString("TasServer::launchDetached: Child PID: %1").arg((int)pid) );
        response.setData(QString::number((int) pid));
    }

#else
    qint64 pid;
    if(QProcess::startDetached(applicationPath, arguments, ".", &pid)){

	    TasClientManager::instance()->addStartedApp(applicationPath, QDateTime::currentDateTime().toString("yyyyMMddhhmmsszzz"));
        response.setData(QString::number(pid));
    }
#endif
    else{
        TasLogger::logger()->error("TasServer::launchDetached: Could not start the application " + applicationPath);
        response.setErrorMessage("Could not start the application " + applicationPath);
    }
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: exsrcbrw.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: hr $ $Date: 2004-05-10 13:08:04 $
 *
 *  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 _SBA_EXTCTRLR_HXX
#define _SBA_EXTCTRLR_HXX

#ifndef _SBA_BWRCTRLR_HXX
#include "brwctrlr.hxx"
#endif
#ifndef _COM_SUN_STAR_FORM_XFORMCONTROLLER_HPP_
#include <com/sun/star/form/XFormController.hpp>
#endif
#ifndef _COMPHELPER_UNO3_HXX_
#include <comphelper/uno3.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase2.hxx>
#endif
//==============================================================================
//= SbaExternalSourceBrowser
//==============================================================================

namespace dbaui
{
    class SbaXFormAdapter;
    class SbaExternalSourceBrowser
                :public SbaXDataBrowserController
                ,public ::com::sun::star::util::XModifyBroadcaster
    {
        ::cppu::OInterfaceContainerHelper   m_aModifyListeners;
            // for multiplexing the modify events
        SbaXFormAdapter*                    m_pDataSourceImpl;
        sal_Bool                            m_bInQueryDispatch;
            // our queryDispatch will ask our frame, which first will ask our queryDispatch, so we need to protect against
            // recursion

    public:
        SbaExternalSourceBrowser(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM);

        static ::rtl::OUString getImplementationName_Static() throw( ::com::sun::star::uno::RuntimeException );
        static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_Static(void) throw( ::com::sun::star::uno::RuntimeException );
        static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >
                SAL_CALL Create(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >&);

        // UNO
        DECLARE_UNO3_DEFAULTS(SbaExternalSourceBrowser, OGenericUnoController);
        virtual ::com::sun::star::uno::Any  SAL_CALL queryInterface(const ::com::sun::star::uno::Type& _rType) throw (::com::sun::star::uno::RuntimeException);
        //  virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::reflection::XIdlClass > >  getIdlClasses(void);

        //  static ::com::sun::star::uno::Reference< ::com::sun::star::reflection::XIdlClass >  getStaticIdlClass();

        // ::com::sun::star::frame::XDispatch
        virtual void SAL_CALL dispatch(const ::com::sun::star::util::URL& aURL, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue>& aArgs) throw(::com::sun::star::uno::RuntimeException);

        // ::com::sun::star::frame::XDispatchProvider
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch >  SAL_CALL queryDispatch(const ::com::sun::star::util::URL& aURL, const ::rtl::OUString& aTargetFrameName, sal_Int32 nSearchFlags) throw( ::com::sun::star::uno::RuntimeException );

        // ::com::sun::star::util::XModifyListener
        virtual void SAL_CALL modified(const ::com::sun::star::lang::EventObject& aEvent) throw( ::com::sun::star::uno::RuntimeException );

        // ::com::sun::star::util::XModifyBroadcaster
        virtual void SAL_CALL addModifyListener(const ::com::sun::star::uno::Reference< ::com::sun::star::util::XModifyListener > & aListener) throw( ::com::sun::star::uno::RuntimeException );
        virtual void SAL_CALL removeModifyListener(const ::com::sun::star::uno::Reference< ::com::sun::star::util::XModifyListener > & aListener) throw( ::com::sun::star::uno::RuntimeException );

        // ::com::sun::star::lang::XComponent
        virtual void SAL_CALL disposing();

        // ::com::sun::star::form::XLoadListener
        virtual void SAL_CALL unloading(const ::com::sun::star::lang::EventObject& aEvent) throw( ::com::sun::star::uno::RuntimeException );

        // ::com::sun::star::lang::XEventListener
        virtual void SAL_CALL disposing(const ::com::sun::star::lang::EventObject& Source) throw( ::com::sun::star::uno::RuntimeException );

        // XServiceInfo
        virtual ::rtl::OUString SAL_CALL getImplementationName() throw(::com::sun::star::uno::RuntimeException);
        virtual ::comphelper::StringSequence SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException);

    protected:
        ~SbaExternalSourceBrowser();

        virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRowSet >  CreateForm();
        virtual sal_Bool InitializeForm(const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRowSet > & xForm);

        virtual sal_Bool LoadForm();

        void Attach(const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRowSet > & xMaster);

        void ClearView();

        void startListening();
        void stopListening();
    };
}

#endif // _SBA_EXTCTRLR_HXX
<commit_msg>INTEGRATION: CWS ooo19126 (1.7.236); FILE MERGED 2005/09/05 17:34:52 rt 1.7.236.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: exsrcbrw.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 15:54:24 $
 *
 *  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 _SBA_EXTCTRLR_HXX
#define _SBA_EXTCTRLR_HXX

#ifndef _SBA_BWRCTRLR_HXX
#include "brwctrlr.hxx"
#endif
#ifndef _COM_SUN_STAR_FORM_XFORMCONTROLLER_HPP_
#include <com/sun/star/form/XFormController.hpp>
#endif
#ifndef _COMPHELPER_UNO3_HXX_
#include <comphelper/uno3.hxx>
#endif
#ifndef _CPPUHELPER_IMPLBASE2_HXX_
#include <cppuhelper/implbase2.hxx>
#endif
//==============================================================================
//= SbaExternalSourceBrowser
//==============================================================================

namespace dbaui
{
    class SbaXFormAdapter;
    class SbaExternalSourceBrowser
                :public SbaXDataBrowserController
                ,public ::com::sun::star::util::XModifyBroadcaster
    {
        ::cppu::OInterfaceContainerHelper   m_aModifyListeners;
            // for multiplexing the modify events
        SbaXFormAdapter*                    m_pDataSourceImpl;
        sal_Bool                            m_bInQueryDispatch;
            // our queryDispatch will ask our frame, which first will ask our queryDispatch, so we need to protect against
            // recursion

    public:
        SbaExternalSourceBrowser(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rM);

        static ::rtl::OUString getImplementationName_Static() throw( ::com::sun::star::uno::RuntimeException );
        static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_Static(void) throw( ::com::sun::star::uno::RuntimeException );
        static ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >
                SAL_CALL Create(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >&);

        // UNO
        DECLARE_UNO3_DEFAULTS(SbaExternalSourceBrowser, OGenericUnoController);
        virtual ::com::sun::star::uno::Any  SAL_CALL queryInterface(const ::com::sun::star::uno::Type& _rType) throw (::com::sun::star::uno::RuntimeException);
        //  virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::reflection::XIdlClass > >  getIdlClasses(void);

        //  static ::com::sun::star::uno::Reference< ::com::sun::star::reflection::XIdlClass >  getStaticIdlClass();

        // ::com::sun::star::frame::XDispatch
        virtual void SAL_CALL dispatch(const ::com::sun::star::util::URL& aURL, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue>& aArgs) throw(::com::sun::star::uno::RuntimeException);

        // ::com::sun::star::frame::XDispatchProvider
        virtual ::com::sun::star::uno::Reference< ::com::sun::star::frame::XDispatch >  SAL_CALL queryDispatch(const ::com::sun::star::util::URL& aURL, const ::rtl::OUString& aTargetFrameName, sal_Int32 nSearchFlags) throw( ::com::sun::star::uno::RuntimeException );

        // ::com::sun::star::util::XModifyListener
        virtual void SAL_CALL modified(const ::com::sun::star::lang::EventObject& aEvent) throw( ::com::sun::star::uno::RuntimeException );

        // ::com::sun::star::util::XModifyBroadcaster
        virtual void SAL_CALL addModifyListener(const ::com::sun::star::uno::Reference< ::com::sun::star::util::XModifyListener > & aListener) throw( ::com::sun::star::uno::RuntimeException );
        virtual void SAL_CALL removeModifyListener(const ::com::sun::star::uno::Reference< ::com::sun::star::util::XModifyListener > & aListener) throw( ::com::sun::star::uno::RuntimeException );

        // ::com::sun::star::lang::XComponent
        virtual void SAL_CALL disposing();

        // ::com::sun::star::form::XLoadListener
        virtual void SAL_CALL unloading(const ::com::sun::star::lang::EventObject& aEvent) throw( ::com::sun::star::uno::RuntimeException );

        // ::com::sun::star::lang::XEventListener
        virtual void SAL_CALL disposing(const ::com::sun::star::lang::EventObject& Source) throw( ::com::sun::star::uno::RuntimeException );

        // XServiceInfo
        virtual ::rtl::OUString SAL_CALL getImplementationName() throw(::com::sun::star::uno::RuntimeException);
        virtual ::comphelper::StringSequence SAL_CALL getSupportedServiceNames() throw(::com::sun::star::uno::RuntimeException);

    protected:
        ~SbaExternalSourceBrowser();

        virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRowSet >  CreateForm();
        virtual sal_Bool InitializeForm(const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRowSet > & xForm);

        virtual sal_Bool LoadForm();

        void Attach(const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XRowSet > & xMaster);

        void ClearView();

        void startListening();
        void stopListening();
    };
}

#endif // _SBA_EXTCTRLR_HXX
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: admindlg.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 07:33:40 $
 *
 *  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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_dbaccess.hxx"

#ifndef _DBU_REGHELPER_HXX_
#include "dbu_reghelper.hxx"
#endif
#ifndef _DBAUI_ADMINDLG_HXX
#include "admindlg.hxx"
#endif
#ifndef _DBAUI_DBADMIN_HXX_
#include "dbadmin.hxx"
#endif

using namespace dbaui;

extern "C" void SAL_CALL createRegistryInfo_ODataSourcePropertyDialog()
{
    static OMultiInstanceAutoRegistration< ODataSourcePropertyDialog > aAutoRegistration;
}

//.........................................................................
namespace dbaui
{
//.........................................................................

    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::lang;
    using namespace ::com::sun::star::beans;

//=========================================================================
//-------------------------------------------------------------------------
ODataSourcePropertyDialog::ODataSourcePropertyDialog(const Reference< XMultiServiceFactory >& _rxORB)
    :ODatabaseAdministrationDialog(_rxORB)
{
}
//-------------------------------------------------------------------------
Sequence<sal_Int8> SAL_CALL ODataSourcePropertyDialog::getImplementationId(  ) throw(RuntimeException)
{
    static ::cppu::OImplementationId aId;
    return aId.getImplementationId();
}

//-------------------------------------------------------------------------
Reference< XInterface > SAL_CALL ODataSourcePropertyDialog::Create(const Reference< XMultiServiceFactory >& _rxFactory)
{
    return *(new ODataSourcePropertyDialog(_rxFactory));
}

//-------------------------------------------------------------------------
::rtl::OUString SAL_CALL ODataSourcePropertyDialog::getImplementationName() throw(RuntimeException)
{
    return getImplementationName_Static();
}

//-------------------------------------------------------------------------
::rtl::OUString ODataSourcePropertyDialog::getImplementationName_Static() throw(RuntimeException)
{
    return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("org.openoffice.comp.dbu.ODatasourceAdministrationDialog"));
}

//-------------------------------------------------------------------------
::comphelper::StringSequence SAL_CALL ODataSourcePropertyDialog::getSupportedServiceNames() throw(RuntimeException)
{
    return getSupportedServiceNames_Static();
}

//-------------------------------------------------------------------------
::comphelper::StringSequence ODataSourcePropertyDialog::getSupportedServiceNames_Static() throw(RuntimeException)
{
    ::comphelper::StringSequence aSupported(1);
    aSupported.getArray()[0] = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.sdb.DatasourceAdministrationDialog"));
    return aSupported;
}

//-------------------------------------------------------------------------
Reference<XPropertySetInfo>  SAL_CALL ODataSourcePropertyDialog::getPropertySetInfo() throw(RuntimeException)
{
    Reference<XPropertySetInfo>  xInfo( createPropertySetInfo( getInfoHelper() ) );
    return xInfo;
}

//-------------------------------------------------------------------------
::cppu::IPropertyArrayHelper& ODataSourcePropertyDialog::getInfoHelper()
{
    return *const_cast<ODataSourcePropertyDialog*>(this)->getArrayHelper();
}

//------------------------------------------------------------------------------
::cppu::IPropertyArrayHelper* ODataSourcePropertyDialog::createArrayHelper( ) const
{
    Sequence< Property > aProps;
    describeProperties(aProps);
    return new ::cppu::OPropertyArrayHelper(aProps);
}
//------------------------------------------------------------------------------
Dialog* ODataSourcePropertyDialog::createDialog(Window* _pParent)
{

    ODbAdminDialog* pDialog = new ODbAdminDialog(_pParent, m_pDatasourceItems, m_xORB);

    // the initial selection
    if ( m_aInitialSelection.hasValue() )
        pDialog->selectDataSource(m_aInitialSelection);

    return pDialog;
}

//.........................................................................
}   // namespace dbaui
//.........................................................................

<commit_msg>INTEGRATION: CWS changefileheader (1.4.258); FILE MERGED 2008/03/31 13:28:10 rt 1.4.258.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: admindlg.cxx,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.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_dbaccess.hxx"

#ifndef _DBU_REGHELPER_HXX_
#include "dbu_reghelper.hxx"
#endif
#ifndef _DBAUI_ADMINDLG_HXX
#include "admindlg.hxx"
#endif
#ifndef _DBAUI_DBADMIN_HXX_
#include "dbadmin.hxx"
#endif

using namespace dbaui;

extern "C" void SAL_CALL createRegistryInfo_ODataSourcePropertyDialog()
{
    static OMultiInstanceAutoRegistration< ODataSourcePropertyDialog > aAutoRegistration;
}

//.........................................................................
namespace dbaui
{
//.........................................................................

    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::lang;
    using namespace ::com::sun::star::beans;

//=========================================================================
//-------------------------------------------------------------------------
ODataSourcePropertyDialog::ODataSourcePropertyDialog(const Reference< XMultiServiceFactory >& _rxORB)
    :ODatabaseAdministrationDialog(_rxORB)
{
}
//-------------------------------------------------------------------------
Sequence<sal_Int8> SAL_CALL ODataSourcePropertyDialog::getImplementationId(  ) throw(RuntimeException)
{
    static ::cppu::OImplementationId aId;
    return aId.getImplementationId();
}

//-------------------------------------------------------------------------
Reference< XInterface > SAL_CALL ODataSourcePropertyDialog::Create(const Reference< XMultiServiceFactory >& _rxFactory)
{
    return *(new ODataSourcePropertyDialog(_rxFactory));
}

//-------------------------------------------------------------------------
::rtl::OUString SAL_CALL ODataSourcePropertyDialog::getImplementationName() throw(RuntimeException)
{
    return getImplementationName_Static();
}

//-------------------------------------------------------------------------
::rtl::OUString ODataSourcePropertyDialog::getImplementationName_Static() throw(RuntimeException)
{
    return ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("org.openoffice.comp.dbu.ODatasourceAdministrationDialog"));
}

//-------------------------------------------------------------------------
::comphelper::StringSequence SAL_CALL ODataSourcePropertyDialog::getSupportedServiceNames() throw(RuntimeException)
{
    return getSupportedServiceNames_Static();
}

//-------------------------------------------------------------------------
::comphelper::StringSequence ODataSourcePropertyDialog::getSupportedServiceNames_Static() throw(RuntimeException)
{
    ::comphelper::StringSequence aSupported(1);
    aSupported.getArray()[0] = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("com.sun.star.sdb.DatasourceAdministrationDialog"));
    return aSupported;
}

//-------------------------------------------------------------------------
Reference<XPropertySetInfo>  SAL_CALL ODataSourcePropertyDialog::getPropertySetInfo() throw(RuntimeException)
{
    Reference<XPropertySetInfo>  xInfo( createPropertySetInfo( getInfoHelper() ) );
    return xInfo;
}

//-------------------------------------------------------------------------
::cppu::IPropertyArrayHelper& ODataSourcePropertyDialog::getInfoHelper()
{
    return *const_cast<ODataSourcePropertyDialog*>(this)->getArrayHelper();
}

//------------------------------------------------------------------------------
::cppu::IPropertyArrayHelper* ODataSourcePropertyDialog::createArrayHelper( ) const
{
    Sequence< Property > aProps;
    describeProperties(aProps);
    return new ::cppu::OPropertyArrayHelper(aProps);
}
//------------------------------------------------------------------------------
Dialog* ODataSourcePropertyDialog::createDialog(Window* _pParent)
{

    ODbAdminDialog* pDialog = new ODbAdminDialog(_pParent, m_pDatasourceItems, m_xORB);

    // the initial selection
    if ( m_aInitialSelection.hasValue() )
        pDialog->selectDataSource(m_aInitialSelection);

    return pDialog;
}

//.........................................................................
}   // namespace dbaui
//.........................................................................

<|endoftext|>