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

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

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

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

#include "tensorflow/core/platform/path.h"
#include "tensorflow/core/platform/stacktrace_handler.h"
#include "tensorflow/core/platform/test.h"

#define ASSERT_TF_OK(x) ASSERT_EQ(TF_OK, TF_GetCode(x)) << TF_Message(x)
#define EXPECT_TF_OK(x) EXPECT_EQ(TF_OK, TF_GetCode(x)) << TF_Message(x)

namespace tensorflow {
namespace {

class HadoopFileSystemTest : public ::testing::Test {
 public:
  void SetUp() override {
    status_ = TF_NewStatus();
    filesystem_ = new TF_Filesystem;
    tf_hadoop_filesystem::Init(filesystem_, status_);
    ASSERT_TF_OK(status_) << "Could not initialize filesystem. "
                          << TF_Message(status_);
  }
  void TearDown() override {
    TF_DeleteStatus(status_);
    tf_hadoop_filesystem::Cleanup(filesystem_);
    delete filesystem_;
  }

  std::string TmpDir(const std::string& path) {
    char* test_dir = getenv("HADOOP_TEST_TMPDIR");
    if (test_dir != nullptr) {
      return io::JoinPath(std::string(test_dir), path);
    } else {
      return "file://" + io::JoinPath(testing::TmpDir(), path);
    }
  }

  std::unique_ptr<TF_WritableFile, void (*)(TF_WritableFile* file)>
  GetWriter() {
    std::unique_ptr<TF_WritableFile, void (*)(TF_WritableFile * file)> writer(
        new TF_WritableFile, [](TF_WritableFile* file) {
          if (file != nullptr) {
            if (file->plugin_file != nullptr) tf_writable_file::Cleanup(file);
            delete file;
          }
        });
    writer->plugin_file = nullptr;
    return writer;
  }

  std::unique_ptr<TF_RandomAccessFile, void (*)(TF_RandomAccessFile* file)>
  GetReader() {
    std::unique_ptr<TF_RandomAccessFile, void (*)(TF_RandomAccessFile * file)>
        reader(new TF_RandomAccessFile, [](TF_RandomAccessFile* file) {
          if (file != nullptr) {
            if (file->plugin_file != nullptr)
              tf_random_access_file::Cleanup(file);
            delete file;
          }
        });
    reader->plugin_file = nullptr;
    return reader;
  }

  void WriteString(const std::string& path, const std::string& content) {
    auto writer = GetWriter();
    tf_hadoop_filesystem::NewWritableFile(filesystem_, path.c_str(),
                                          writer.get(), status_);
    if (TF_GetCode(status_) != TF_OK) return;
    tf_writable_file::Append(writer.get(), content.c_str(), content.length(),
                             status_);
    if (TF_GetCode(status_) != TF_OK) return;
    tf_writable_file::Close(writer.get(), status_);
    if (TF_GetCode(status_) != TF_OK) return;
  }

  std::string ReadAll(const std::string& path) {
    auto reader = GetReader();
    tf_hadoop_filesystem::NewRandomAccessFile(filesystem_, path.c_str(),
                                              reader.get(), status_);
    if (TF_GetCode(status_) != TF_OK) return "";

    auto file_size =
        tf_hadoop_filesystem::GetFileSize(filesystem_, path.c_str(), status_);
    if (TF_GetCode(status_) != TF_OK) return "";

    std::string content;
    content.resize(file_size);
    auto read = tf_random_access_file::Read(reader.get(), 0, file_size,
                                            &content[0], status_);
    if (TF_GetCode(status_) != TF_OK) return "";
    if (read >= 0) content.resize(read);
    if (file_size != content.size())
      TF_SetStatus(
          status_, TF_DATA_LOSS,
          std::string("expected " + std::to_string(file_size) + " got " +
                      std::to_string(content.size()) + " bytes")
              .c_str());
    return content;
  }

 protected:
  TF_Filesystem* filesystem_;
  TF_Status* status_;
};

TEST_F(HadoopFileSystemTest, RandomAccessFile) {
  const std::string path = TmpDir("RandomAccessFile");
  const std::string content = "abcdefghijklmn";

  WriteString(path, content);
  ASSERT_TF_OK(status_);

  auto reader = GetReader();
  tf_hadoop_filesystem::NewRandomAccessFile(filesystem_, path.c_str(),
                                            reader.get(), status_);
  EXPECT_TF_OK(status_);

  std::string result;
  result.resize(content.size());
  auto read = tf_random_access_file::Read(reader.get(), 0, content.size(),
                                          &result[0], status_);
  result.resize(read);
  EXPECT_TF_OK(status_);
  EXPECT_EQ(content.size(), result.size());
  EXPECT_EQ(content, result);

  result.clear();
  result.resize(4);
  read = tf_random_access_file::Read(reader.get(), 2, 4, &result[0], status_);
  result.resize(read);
  EXPECT_TF_OK(status_);
  EXPECT_EQ(4, result.size());
  EXPECT_EQ(content.substr(2, 4), result);
}

TEST_F(HadoopFileSystemTest, WritableFile) {
  auto writer = GetWriter();
  const std::string path = TmpDir("WritableFile");
  tf_hadoop_filesystem::NewWritableFile(filesystem_, path.c_str(), writer.get(),
                                        status_);
  EXPECT_TF_OK(status_);
  tf_writable_file::Append(writer.get(), "content1,", strlen("content1,"),
                           status_);
  EXPECT_TF_OK(status_);
  auto pos = tf_writable_file::Tell(writer.get(), status_);
  EXPECT_TF_OK(status_);
  EXPECT_EQ(pos, 9);

  tf_writable_file::Append(writer.get(), "content2", strlen("content2"),
                           status_);
  EXPECT_TF_OK(status_);
  tf_writable_file::Flush(writer.get(), status_);
  EXPECT_TF_OK(status_);
  tf_writable_file::Sync(writer.get(), status_);
  EXPECT_TF_OK(status_);
  tf_writable_file::Close(writer.get(), status_);
  EXPECT_TF_OK(status_);

  auto content = ReadAll(path);
  EXPECT_TF_OK(status_);
  EXPECT_EQ("content1,content2", content);
}

TEST_F(HadoopFileSystemTest, PathExists) {
  const std::string path = TmpDir("PathExists");
  tf_hadoop_filesystem::PathExists(filesystem_, path.c_str(), status_);
  EXPECT_EQ(TF_NOT_FOUND, TF_GetCode(status_)) << TF_Message(status_);
  TF_SetStatus(status_, TF_OK, "");
  WriteString(path, "test");
  ASSERT_TF_OK(status_);
  tf_hadoop_filesystem::PathExists(filesystem_, path.c_str(), status_);
  EXPECT_TF_OK(status_);
}

TEST_F(HadoopFileSystemTest, GetChildren) {
  const std::string base = TmpDir("GetChildren");
  tf_hadoop_filesystem::CreateDir(filesystem_, base.c_str(), status_);
  EXPECT_TF_OK(status_);

  const std::string file = io::JoinPath(base, "TestFile.csv");
  WriteString(file, "test");
  EXPECT_TF_OK(status_);

  const std::string subdir = io::JoinPath(base, "SubDir");
  tf_hadoop_filesystem::CreateDir(filesystem_, subdir.c_str(), status_);
  EXPECT_TF_OK(status_);
  const std::string subfile = io::JoinPath(subdir, "TestSubFile.csv");
  WriteString(subfile, "test");
  EXPECT_TF_OK(status_);

  char** entries;
  auto num_entries = tf_hadoop_filesystem::GetChildren(
      filesystem_, base.c_str(), &entries, status_);
  EXPECT_TF_OK(status_);

  std::vector<std::string> childrens;
  for (int i = 0; i < num_entries; ++i) {
    childrens.push_back(entries[i]);
  }
  std::sort(childrens.begin(), childrens.end());
  EXPECT_EQ(std::vector<string>({"SubDir", "TestFile.csv"}), childrens);
}

TEST_F(HadoopFileSystemTest, DeleteFile) {
  const std::string path = TmpDir("DeleteFile");
  WriteString(path, "test");
  ASSERT_TF_OK(status_);
  tf_hadoop_filesystem::DeleteFile(filesystem_, path.c_str(), status_);
  EXPECT_TF_OK(status_);
}

}  // namespace
}  // namespace tensorflow

GTEST_API_ int main(int argc, char** argv) {
  tensorflow::testing::InstallStacktraceHandler();
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<commit_msg>Add test GetFileSize<commit_after>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.

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

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

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

#include "tensorflow/core/platform/path.h"
#include "tensorflow/core/platform/stacktrace_handler.h"
#include "tensorflow/core/platform/test.h"

#define ASSERT_TF_OK(x) ASSERT_EQ(TF_OK, TF_GetCode(x)) << TF_Message(x)
#define EXPECT_TF_OK(x) EXPECT_EQ(TF_OK, TF_GetCode(x)) << TF_Message(x)

namespace tensorflow {
namespace {

class HadoopFileSystemTest : public ::testing::Test {
 public:
  void SetUp() override {
    status_ = TF_NewStatus();
    filesystem_ = new TF_Filesystem;
    tf_hadoop_filesystem::Init(filesystem_, status_);
    ASSERT_TF_OK(status_) << "Could not initialize filesystem. "
                          << TF_Message(status_);
  }
  void TearDown() override {
    TF_DeleteStatus(status_);
    tf_hadoop_filesystem::Cleanup(filesystem_);
    delete filesystem_;
  }

  std::string TmpDir(const std::string& path) {
    char* test_dir = getenv("HADOOP_TEST_TMPDIR");
    if (test_dir != nullptr) {
      return io::JoinPath(std::string(test_dir), path);
    } else {
      return "file://" + io::JoinPath(testing::TmpDir(), path);
    }
  }

  std::unique_ptr<TF_WritableFile, void (*)(TF_WritableFile* file)>
  GetWriter() {
    std::unique_ptr<TF_WritableFile, void (*)(TF_WritableFile * file)> writer(
        new TF_WritableFile, [](TF_WritableFile* file) {
          if (file != nullptr) {
            if (file->plugin_file != nullptr) tf_writable_file::Cleanup(file);
            delete file;
          }
        });
    writer->plugin_file = nullptr;
    return writer;
  }

  std::unique_ptr<TF_RandomAccessFile, void (*)(TF_RandomAccessFile* file)>
  GetReader() {
    std::unique_ptr<TF_RandomAccessFile, void (*)(TF_RandomAccessFile * file)>
        reader(new TF_RandomAccessFile, [](TF_RandomAccessFile* file) {
          if (file != nullptr) {
            if (file->plugin_file != nullptr)
              tf_random_access_file::Cleanup(file);
            delete file;
          }
        });
    reader->plugin_file = nullptr;
    return reader;
  }

  void WriteString(const std::string& path, const std::string& content) {
    auto writer = GetWriter();
    tf_hadoop_filesystem::NewWritableFile(filesystem_, path.c_str(),
                                          writer.get(), status_);
    if (TF_GetCode(status_) != TF_OK) return;
    tf_writable_file::Append(writer.get(), content.c_str(), content.length(),
                             status_);
    if (TF_GetCode(status_) != TF_OK) return;
    tf_writable_file::Close(writer.get(), status_);
    if (TF_GetCode(status_) != TF_OK) return;
  }

  std::string ReadAll(const std::string& path) {
    auto reader = GetReader();
    tf_hadoop_filesystem::NewRandomAccessFile(filesystem_, path.c_str(),
                                              reader.get(), status_);
    if (TF_GetCode(status_) != TF_OK) return "";

    auto file_size =
        tf_hadoop_filesystem::GetFileSize(filesystem_, path.c_str(), status_);
    if (TF_GetCode(status_) != TF_OK) return "";

    std::string content;
    content.resize(file_size);
    auto read = tf_random_access_file::Read(reader.get(), 0, file_size,
                                            &content[0], status_);
    if (TF_GetCode(status_) != TF_OK) return "";
    if (read >= 0) content.resize(read);
    if (file_size != content.size())
      TF_SetStatus(
          status_, TF_DATA_LOSS,
          std::string("expected " + std::to_string(file_size) + " got " +
                      std::to_string(content.size()) + " bytes")
              .c_str());
    return content;
  }

 protected:
  TF_Filesystem* filesystem_;
  TF_Status* status_;
};

TEST_F(HadoopFileSystemTest, RandomAccessFile) {
  const std::string path = TmpDir("RandomAccessFile");
  const std::string content = "abcdefghijklmn";

  WriteString(path, content);
  ASSERT_TF_OK(status_);

  auto reader = GetReader();
  tf_hadoop_filesystem::NewRandomAccessFile(filesystem_, path.c_str(),
                                            reader.get(), status_);
  EXPECT_TF_OK(status_);

  std::string result;
  result.resize(content.size());
  auto read = tf_random_access_file::Read(reader.get(), 0, content.size(),
                                          &result[0], status_);
  result.resize(read);
  EXPECT_TF_OK(status_);
  EXPECT_EQ(content.size(), result.size());
  EXPECT_EQ(content, result);

  result.clear();
  result.resize(4);
  read = tf_random_access_file::Read(reader.get(), 2, 4, &result[0], status_);
  result.resize(read);
  EXPECT_TF_OK(status_);
  EXPECT_EQ(4, result.size());
  EXPECT_EQ(content.substr(2, 4), result);
}

TEST_F(HadoopFileSystemTest, WritableFile) {
  auto writer = GetWriter();
  const std::string path = TmpDir("WritableFile");
  tf_hadoop_filesystem::NewWritableFile(filesystem_, path.c_str(), writer.get(),
                                        status_);
  EXPECT_TF_OK(status_);
  tf_writable_file::Append(writer.get(), "content1,", strlen("content1,"),
                           status_);
  EXPECT_TF_OK(status_);
  auto pos = tf_writable_file::Tell(writer.get(), status_);
  EXPECT_TF_OK(status_);
  EXPECT_EQ(pos, 9);

  tf_writable_file::Append(writer.get(), "content2", strlen("content2"),
                           status_);
  EXPECT_TF_OK(status_);
  tf_writable_file::Flush(writer.get(), status_);
  EXPECT_TF_OK(status_);
  tf_writable_file::Sync(writer.get(), status_);
  EXPECT_TF_OK(status_);
  tf_writable_file::Close(writer.get(), status_);
  EXPECT_TF_OK(status_);

  auto content = ReadAll(path);
  EXPECT_TF_OK(status_);
  EXPECT_EQ("content1,content2", content);
}

TEST_F(HadoopFileSystemTest, PathExists) {
  const std::string path = TmpDir("PathExists");
  tf_hadoop_filesystem::PathExists(filesystem_, path.c_str(), status_);
  EXPECT_EQ(TF_NOT_FOUND, TF_GetCode(status_)) << TF_Message(status_);
  TF_SetStatus(status_, TF_OK, "");
  WriteString(path, "test");
  ASSERT_TF_OK(status_);
  tf_hadoop_filesystem::PathExists(filesystem_, path.c_str(), status_);
  EXPECT_TF_OK(status_);
}

TEST_F(HadoopFileSystemTest, GetChildren) {
  const std::string base = TmpDir("GetChildren");
  tf_hadoop_filesystem::CreateDir(filesystem_, base.c_str(), status_);
  EXPECT_TF_OK(status_);

  const std::string file = io::JoinPath(base, "TestFile.csv");
  WriteString(file, "test");
  EXPECT_TF_OK(status_);

  const std::string subdir = io::JoinPath(base, "SubDir");
  tf_hadoop_filesystem::CreateDir(filesystem_, subdir.c_str(), status_);
  EXPECT_TF_OK(status_);
  const std::string subfile = io::JoinPath(subdir, "TestSubFile.csv");
  WriteString(subfile, "test");
  EXPECT_TF_OK(status_);

  char** entries;
  auto num_entries = tf_hadoop_filesystem::GetChildren(
      filesystem_, base.c_str(), &entries, status_);
  EXPECT_TF_OK(status_);

  std::vector<std::string> childrens;
  for (int i = 0; i < num_entries; ++i) {
    childrens.push_back(entries[i]);
  }
  std::sort(childrens.begin(), childrens.end());
  EXPECT_EQ(std::vector<string>({"SubDir", "TestFile.csv"}), childrens);
}

TEST_F(HadoopFileSystemTest, DeleteFile) {
  const std::string path = TmpDir("DeleteFile");
  WriteString(path, "test");
  ASSERT_TF_OK(status_);
  tf_hadoop_filesystem::DeleteFile(filesystem_, path.c_str(), status_);
  EXPECT_TF_OK(status_);
}

TEST_F(HadoopFileSystemTest, GetFileSize) {
  const std::string path = TmpDir("GetFileSize");
  WriteString(path, "test");
  ASSERT_TF_OK(status_);
  auto file_size =
      tf_hadoop_filesystem::GetFileSize(filesystem_, path.c_str(), status_);
  EXPECT_TF_OK(status_);
  EXPECT_EQ(4, file_size);
}

}  // namespace
}  // namespace tensorflow

GTEST_API_ int main(int argc, char** argv) {
  tensorflow::testing::InstallStacktraceHandler();
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<|endoftext|>


<commit_before>/* File:	tests/BlackBox/butterfly.h
 * Author:	William J. Turner for the LinBox group
 *
 * Run tests on matrix Diagonal
 */

#include <iostream>
#include <vector>
#include <list>
#include <utility>
#include <map>
#include <algorithm>
#include "LinBox/giverror.C"
#include "LinBox/unparam_field.h"
#include "LinBox/param_modular.h"
#include "LinBox/butterfly.h"
#include "LinBox/boolean_switch.h"
#include "LinBox/cekstv_switch.h"

template <class Field> struct comp_w_ind
{
	bool operator() (const std::pair< size_t, typename Field::element >& entry,
			size_t col_in)
	{ return entry.first < col_in; }
};

int main(void)
{
//	typedef LinBox::unparam_field<double> Field;
	typedef LinBox::param_modular Field;
	typedef Field::randIter RandIter;
	typedef Field::element Element;
	typedef std::vector<Element> Vector;  // Only dense vectors allowed

/*
 * There's something wrong with applyTranspose when using param_modular field
 * and cekstv switch.  It appears to be in F.mul, but I can't figure out
 * what's wrong.  This needs to be fixed.
 */
	LinBox::integer modulus; 	// prime modulus
	cout << endl << "Enter a prime number for the modulus of the field: ";
	cin >> modulus;
	Field F(modulus);
/*/
	Field F;
*/

	cout << "Enter an integer size for the set of random numbers: ";
	LinBox::integer size;
	cin >> size;

	cout << "Enter integer seed for random number generator: ";
	LinBox::integer seed;
	cin >> seed;

	Field::randIter r(F, size, seed);

	cout << "Enter the size of the vector to precondition: ";
	size_t n;
	cin >> n;

/*
	std::vector<bool> bools(n, false);

	cout << "Enter the numbers corresponding to the linearly independent rows" << endl
		<< "with the rows numbered from 0 to " << n - 1 << "." << endl
		<< "End with a row number of '-1'." << endl;

	size_t value;
	while (cin >> value)
	{
		if (value == size_t(-1)) break;
		if (value < bools.size()) bools[value] = true;
	}

	cout << "The test vector is:" << endl;
	for (size_t i = 0; i < bools.size(); i++)
		cout << "\tbools[" << i << "] = " << bools[i] << endl;

	cout << "Enter non-negative offset for contiguous block: ";

	cin >> value;

	cout << "The offset is " << value << endl;

	std::vector<bool> s1 = LinBox::set_butterfly(bools, value, cout);
	LinBox::boolean_switch switch1(s1);
*/

	cout << "Enter a vector to be switched by the butterfly matrix." << endl
		<< "Input the vector by entering index and value." << endl
		<< "Remember matrices and vectors are indexed starting at 0." << endl
		<< "End with a index of -1." << endl;

	Element zero;
	F.init(zero, 0);
	Element elem(zero);

	Vector x(n, zero), y(n, zero);
	Vector::iterator x_iter, y_iter;

	size_t i;
	bool found;

	while (cin >> i)
	{
		// return also if row index is not positive
		if(i == size_t(-1)) break;

		F.read(cin, elem);

		// Record element in dense vector
 		x[i] = elem;

	}

	// Calculate number of butterfly switches needed
	size_t s(LinBox::count_butterfly(n));

	cout << "Now testing boolean switches..." << endl << endl;

	std::vector<bool> s1(s, false);

	cout << "There are a total of " << s << " switches that can be set." << endl
		<< "Enter the numbers corresponding to the switches, " << endl
		<< "numbered from 0 to " << s - 1 << " you want set." << endl
		<< "End with a switch number of '-1'." << endl;

	size_t value;
	while (cin >> value)
	{
		if (value == size_t(-1)) break;
		if (value < s) s1[value] = true;
	}

	LinBox::boolean_switch switch1(s1);

	cout << "*** Running tests of hand set boolean switches." << endl;

	cout << "Dense vector x:" << endl;
	i = 0;
	for (x_iter = x.begin(); x_iter != x.end(); x_iter++, i++)
	{
		cout << "\tx[" << i << "] = ";
		F.write(cout, *x_iter);
		cout << endl;
	}

	LinBox::butterfly < Vector, LinBox::boolean_switch >
		B1(x.size(), switch1);
	LinBox::Blackbox_archetype<Vector>& A1 = B1;

	A1.apply(y,x);

	cout << "Using A1.apply(y,x) gives vector y:" << endl;
	i = 0;
	for (y_iter = y.begin(); y_iter != y.end(); y_iter++, i++)
	{
		cout << "\ty[" << i << "] = ";
		F.write(cout, *y_iter);
		cout << endl;
	}

	y = Vector(n, zero);
	y = A1.apply(x);

	cout << "Using y = A1.apply(x) gives vector y:" << endl;
	i = 0;
	for (y_iter = y.begin(); y_iter != y.end(); y_iter++, i++)
	{
		cout << "\ty[" << i << "] = ";
		F.write(cout, *y_iter);
		cout << endl;
	}

	y = x;
	y = A1.applyin(y);

	cout << "Using y = x; y = A1.applyin(y) gives vector y:" << endl;
	i = 0;
	for (y_iter = y.begin(); y_iter != y.end(); y_iter++, i++)
	{
		cout << "\ty[" << i << "] = ";
		F.write(cout, *y_iter);
		cout << endl;
	}

	y = Vector(n, zero);
	A1.applyTranspose(y,x);

	cout << "Using A1.applyTranspose(y,x) gives vector y:" << endl;
	i = 0;
	for (y_iter = y.begin(); y_iter != y.end(); y_iter++, i++)
	{
		cout << "\ty[" << i << "] = ";
		F.write(cout, *y_iter);
		cout << endl;
	}

	y = Vector(n, zero);
	y = A1.applyTranspose(x);

	cout << "Using y = A1.applyTranspose(x) gives vector y:" << endl;
	i = 0;
	for (y_iter = y.begin(); y_iter != y.end(); y_iter++, i++)
	{
		cout << "\ty[" << i << "] = ";
		F.write(cout, *y_iter);
		cout << endl;
	}

	y = x;
	y = A1.applyTransposein(y);

	cout << "Using y = x; y = A1.applyTransposein(y) gives vector y:" << endl;
	i = 0;
	for (y_iter = y.begin(); y_iter != y.end(); y_iter++, i++)
	{
		cout << "\ty[" << i << "] = ";
		F.write(cout, *y_iter);
		cout << endl;
	}

	cout << "Now testing multiplication (CEKSTV) switches..." << endl << endl;

	Vector s2(s, zero);

	cout << "There are a total of " << s << " switches that can be set." << endl
		<< "Enter the numbers corresponding to the switches, " << endl
		<< "numbered from 0 to " << s - 1 << " you want set" << endl
		<< "and then the value of the switch." << endl
		<< "End with a switch number of '-1'." << endl;

	while (cin >> value)
	{
		if (value == size_t(-1)) break;
		F.read(cin, elem);
		if (value < s) s2[value] = elem;
	}

	LinBox::cekstv_switch<Field> switch2(F, s2);

	cout << "*** Running tests of hand set multiplication switches." << endl;

	cout << "Dense vector x:" << endl;
	i = 0;
	for (x_iter = x.begin(); x_iter != x.end(); x_iter++, i++)
	{
		cout << "\tx[" << i << "] = ";
		F.write(cout, *x_iter);
		cout << endl;
	}

	LinBox::butterfly < Vector, LinBox::cekstv_switch<Field> >
		B2(x.size(), switch2);

	LinBox::Blackbox_archetype<Vector>& A2 = B2;

	A2.apply(y,x);

	cout << "Using A2.apply(y,x) gives vector y:" << endl;
	i = 0;
	for (y_iter = y.begin(); y_iter != y.end(); y_iter++, i++)
	{
		cout << "\ty[" << i << "] = ";
		F.write(cout, *y_iter);
		cout << endl;
	}

	y = Vector(n, zero);
	y = A2.apply(x);

	cout << "Using y = A2.apply(x) gives vector y:" << endl;
	i = 0;
	for (y_iter = y.begin(); y_iter != y.end(); y_iter++, i++)
	{
		cout << "\ty[" << i << "] = ";
		F.write(cout, *y_iter);
		cout << endl;
	}

	y = x;
	y = A2.applyin(y);

	cout << "Using y = x; y = A2.applyin(y) gives vector y:" << endl;
	i = 0;
	for (y_iter = y.begin(); y_iter != y.end(); y_iter++, i++)
	{
		cout << "\ty[" << i << "] = ";
		F.write(cout, *y_iter);
		cout << endl;
	}

	y = Vector(n, zero);
	A2.applyTranspose(y,x);

	cout << "Using A2.applyTranspose(y,x) gives vector y:" << endl;
	i = 0;
	for (y_iter = y.begin(); y_iter != y.end(); y_iter++, i++)
	{
		cout << "\ty[" << i << "] = ";
		F.write(cout, *y_iter);
		cout << endl;
	}

	y = Vector(n, zero);
	y = A2.applyTranspose(x);

	cout << "Using y = A2.applyTranspose(x) gives vector y:" << endl;
	i = 0;
	for (y_iter = y.begin(); y_iter != y.end(); y_iter++, i++)
	{
		cout << "\ty[" << i << "] = ";
		F.write(cout, *y_iter);
		cout << endl;
	}

	y = x;
	y = A2.applyTransposein(y);

	cout << "Using y = x; y = A2.applyTransposein(y) gives vector y:" << endl;
	i = 0;
	for (y_iter = y.begin(); y_iter != y.end(); y_iter++, i++)
	{
		cout << "\ty[" << i << "] = ";
		F.write(cout, *y_iter);
		cout << endl;
	}

}
<commit_msg>Removing unneeded code<commit_after>/* File:	tests/BlackBox/butterfly.h
 * Author:	William J. Turner for the LinBox group
 *
 * Run tests on matrix Diagonal
 */

#include <iostream>
#include <vector>
#include "LinBox/giverror.C"
#include "LinBox/param_modular.h"
#include "LinBox/butterfly.h"
#include "LinBox/boolean_switch.h"
#include "LinBox/cekstv_switch.h"

int main(void)
{
	typedef LinBox::param_modular Field;
	typedef Field::randIter RandIter;
	typedef Field::element Element;
	typedef std::vector<Element> Vector;  // Only dense vectors allowed

	LinBox::integer modulus; 	// prime modulus
	cout << endl << "Enter a prime number for the modulus of the field: ";
	cin >> modulus;
	Field F(modulus);

	cout << "Enter an integer size for the set of random numbers: ";
	LinBox::integer size;
	cin >> size;

	cout << "Enter integer seed for random number generator: ";
	LinBox::integer seed;
	cin >> seed;

	Field::randIter r(F, size, seed);

	cout << "Enter the size of the vector to precondition: ";
	size_t n;
	cin >> n;

	cout << "Enter a vector to be switched by the butterfly matrix." << endl
		<< "Input the vector by entering index and value." << endl
		<< "Remember matrices and vectors are indexed starting at 0." << endl
		<< "End with a index of -1." << endl;

	Element zero;
	F.init(zero, 0);
	Element elem(zero);

	Vector x(n, zero), y(n, zero);
	Vector::iterator x_iter, y_iter;

	size_t i;
	bool found;

	while (cin >> i)
	{
		// return also if row index is not positive
		if(i == size_t(-1)) break;

		F.read(cin, elem);

		// Record element in dense vector
 		x[i] = elem;

	}

	// Calculate number of butterfly switches needed
	size_t s(LinBox::count_butterfly(n));

	cout << "Now testing boolean switches..." << endl << endl;

	std::vector<bool> s1(s, false);

	cout << "There are a total of " << s << " switches that can be set." << endl
		<< "Enter the numbers corresponding to the switches, " << endl
		<< "numbered from 0 to " << s - 1 << " you want set." << endl
		<< "End with a switch number of '-1'." << endl;

	size_t value;
	while (cin >> value)
	{
		if (value == size_t(-1)) break;
		if (value < s) s1[value] = true;
	}

	LinBox::boolean_switch switch1(s1);

	cout << "*** Running tests of hand set boolean switches." << endl;

	cout << "Dense vector x:" << endl;
	i = 0;
	for (x_iter = x.begin(); x_iter != x.end(); x_iter++, i++)
	{
		cout << "\tx[" << i << "] = ";
		F.write(cout, *x_iter);
		cout << endl;
	}

	LinBox::butterfly < Vector, LinBox::boolean_switch >
		B1(x.size(), switch1);
	LinBox::Blackbox_archetype<Vector>& A1 = B1;

	A1.apply(y,x);

	cout << "Using A1.apply(y,x) gives vector y:" << endl;
	i = 0;
	for (y_iter = y.begin(); y_iter != y.end(); y_iter++, i++)
	{
		cout << "\ty[" << i << "] = ";
		F.write(cout, *y_iter);
		cout << endl;
	}

	y = Vector(n, zero);
	y = A1.apply(x);

	cout << "Using y = A1.apply(x) gives vector y:" << endl;
	i = 0;
	for (y_iter = y.begin(); y_iter != y.end(); y_iter++, i++)
	{
		cout << "\ty[" << i << "] = ";
		F.write(cout, *y_iter);
		cout << endl;
	}

	y = x;
	y = A1.applyin(y);

	cout << "Using y = x; y = A1.applyin(y) gives vector y:" << endl;
	i = 0;
	for (y_iter = y.begin(); y_iter != y.end(); y_iter++, i++)
	{
		cout << "\ty[" << i << "] = ";
		F.write(cout, *y_iter);
		cout << endl;
	}

	y = Vector(n, zero);
	A1.applyTranspose(y,x);

	cout << "Using A1.applyTranspose(y,x) gives vector y:" << endl;
	i = 0;
	for (y_iter = y.begin(); y_iter != y.end(); y_iter++, i++)
	{
		cout << "\ty[" << i << "] = ";
		F.write(cout, *y_iter);
		cout << endl;
	}

	y = Vector(n, zero);
	y = A1.applyTranspose(x);

	cout << "Using y = A1.applyTranspose(x) gives vector y:" << endl;
	i = 0;
	for (y_iter = y.begin(); y_iter != y.end(); y_iter++, i++)
	{
		cout << "\ty[" << i << "] = ";
		F.write(cout, *y_iter);
		cout << endl;
	}

	y = x;
	y = A1.applyTransposein(y);

	cout << "Using y = x; y = A1.applyTransposein(y) gives vector y:" << endl;
	i = 0;
	for (y_iter = y.begin(); y_iter != y.end(); y_iter++, i++)
	{
		cout << "\ty[" << i << "] = ";
		F.write(cout, *y_iter);
		cout << endl;
	}

	cout << "Now testing multiplication (CEKSTV) switches..." << endl << endl;

	Vector s2(s, zero);

	cout << "There are a total of " << s << " switches that can be set." << endl
		<< "Enter the numbers corresponding to the switches, " << endl
		<< "numbered from 0 to " << s - 1 << " you want set" << endl
		<< "and then the value of the switch." << endl
		<< "End with a switch number of '-1'." << endl;

	while (cin >> value)
	{
		if (value == size_t(-1)) break;
		F.read(cin, elem);
		if (value < s) s2[value] = elem;
	}

	LinBox::cekstv_switch<Field> switch2(F, s2);

	cout << "*** Running tests of hand set multiplication switches." << endl;

	cout << "Dense vector x:" << endl;
	i = 0;
	for (x_iter = x.begin(); x_iter != x.end(); x_iter++, i++)
	{
		cout << "\tx[" << i << "] = ";
		F.write(cout, *x_iter);
		cout << endl;
	}

	LinBox::butterfly < Vector, LinBox::cekstv_switch<Field> >
		B2(x.size(), switch2);

	LinBox::Blackbox_archetype<Vector>& A2 = B2;

	A2.apply(y,x);

	cout << "Using A2.apply(y,x) gives vector y:" << endl;
	i = 0;
	for (y_iter = y.begin(); y_iter != y.end(); y_iter++, i++)
	{
		cout << "\ty[" << i << "] = ";
		F.write(cout, *y_iter);
		cout << endl;
	}

	y = Vector(n, zero);
	y = A2.apply(x);

	cout << "Using y = A2.apply(x) gives vector y:" << endl;
	i = 0;
	for (y_iter = y.begin(); y_iter != y.end(); y_iter++, i++)
	{
		cout << "\ty[" << i << "] = ";
		F.write(cout, *y_iter);
		cout << endl;
	}

	y = x;
	y = A2.applyin(y);

	cout << "Using y = x; y = A2.applyin(y) gives vector y:" << endl;
	i = 0;
	for (y_iter = y.begin(); y_iter != y.end(); y_iter++, i++)
	{
		cout << "\ty[" << i << "] = ";
		F.write(cout, *y_iter);
		cout << endl;
	}

	y = Vector(n, zero);
	A2.applyTranspose(y,x);

	cout << "Using A2.applyTranspose(y,x) gives vector y:" << endl;
	i = 0;
	for (y_iter = y.begin(); y_iter != y.end(); y_iter++, i++)
	{
		cout << "\ty[" << i << "] = ";
		F.write(cout, *y_iter);
		cout << endl;
	}

	y = Vector(n, zero);
	y = A2.applyTranspose(x);

	cout << "Using y = A2.applyTranspose(x) gives vector y:" << endl;
	i = 0;
	for (y_iter = y.begin(); y_iter != y.end(); y_iter++, i++)
	{
		cout << "\ty[" << i << "] = ";
		F.write(cout, *y_iter);
		cout << endl;
	}

	y = x;
	y = A2.applyTransposein(y);

	cout << "Using y = x; y = A2.applyTransposein(y) gives vector y:" << endl;
	i = 0;
	for (y_iter = y.begin(); y_iter != y.end(); y_iter++, i++)
	{
		cout << "\ty[" << i << "] = ";
		F.write(cout, *y_iter);
		cout << endl;
	}

}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: stdtext.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: rt $ $Date: 2007-04-26 09:26:19 $
 *
 *  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_vcl.hxx"

#ifndef _SV_SVIDS_HRC
#include <svids.hrc>
#endif
#ifndef _SV_SVDATA_HXX
#include <svdata.hxx>
#endif
#ifndef _SV_MSGBOX_HXX
#include <msgbox.hxx>
#endif
#ifndef _VCL_STDTEXT_HXX
#include <stdtext.hxx>
#endif

// =======================================================================

XubString GetStandardText( USHORT nStdText )
{
    ResMgr* pResMgr = ImplGetResMgr();
    XubString aText;
    if( pResMgr )
        aText = XubString( ResId( nStdText-STANDARD_TEXT_FIRST+SV_STDTEXT_FIRST, *pResMgr ) );
    return aText;
}

// =======================================================================

void ShowServiceNotAvailableError( Window* pParent,
                                   const XubString& rServiceName, BOOL bError )
{
    XubString aText( GetStandardText( STANDARD_TEXT_SERVICE_NOT_AVAILABLE ) );
    aText.SearchAndReplaceAscii( "%s", rServiceName );
    if ( bError )
    {
        ErrorBox aBox( pParent, WB_OK | WB_DEF_OK, aText );
        aBox.Execute();
    }
    else
    {
        WarningBox aBox( pParent, WB_OK | WB_DEF_OK, aText );
        aBox.Execute();
    }
}
<commit_msg>INTEGRATION: CWS vgbugs07 (1.7.40); FILE MERGED 2007/06/04 13:29:31 vg 1.7.40.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: stdtext.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 20:02:22 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

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

#ifndef _SV_SVIDS_HRC
#include <svids.hrc>
#endif
#ifndef _SV_SVDATA_HXX
#include <vcl/svdata.hxx>
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef _VCL_STDTEXT_HXX
#include <vcl/stdtext.hxx>
#endif

// =======================================================================

XubString GetStandardText( USHORT nStdText )
{
    ResMgr* pResMgr = ImplGetResMgr();
    XubString aText;
    if( pResMgr )
        aText = XubString( ResId( nStdText-STANDARD_TEXT_FIRST+SV_STDTEXT_FIRST, *pResMgr ) );
    return aText;
}

// =======================================================================

void ShowServiceNotAvailableError( Window* pParent,
                                   const XubString& rServiceName, BOOL bError )
{
    XubString aText( GetStandardText( STANDARD_TEXT_SERVICE_NOT_AVAILABLE ) );
    aText.SearchAndReplaceAscii( "%s", rServiceName );
    if ( bError )
    {
        ErrorBox aBox( pParent, WB_OK | WB_DEF_OK, aText );
        aBox.Execute();
    }
    else
    {
        WarningBox aBox( pParent, WB_OK | WB_DEF_OK, aText );
        aBox.Execute();
    }
}
<|endoftext|>


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

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

#include <vcl/unohelp.hxx>

#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#endif

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

#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif

#ifndef _COM_SUN_STAR_TEXT_XBREAKITERATOR_HPP_
#include <com/sun/star/i18n/XBreakIterator.hpp>
#endif

#ifndef _COM_SUN_STAR_I18N_XCHARACTERCLASSIFICATION_HPP_
#include <com/sun/star/i18n/XCharacterClassification.hpp>
#endif

#ifndef _COM_SUN_STAR_UTIL_XCOLLATOR_HPP_
#include <com/sun/star/i18n/XCollator.hpp>
#endif

#ifndef _COM_SUN_STAR_AWT_XEXTENDEDTOOLKIT_HPP_
#include <com/sun/star/awt/XExtendedToolkit.hpp>
#endif

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

#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLESTATETYPE_HPP_
#include <com/sun/star/accessibility/AccessibleStateType.hpp>
#endif

#include <com/sun/star/registry/XImplementationRegistration.hpp>

#include <cppuhelper/servicefactory.hxx>

#include <tools/tempfile.hxx>
#include <osl/file.hxx>

#include <vcl/svdata.hxx>
#include <vcl/svapp.hxx>

using namespace ::com::sun::star;
using namespace ::rtl;

#define DOSTRING( x )                       #x
#define STRING( x )                         DOSTRING( x )

struct VCLRegServiceInfo
{
    const sal_Char*     pLibName;
    sal_Bool            bHasSUPD;
};

static VCLRegServiceInfo aVCLComponentsArray[] =
{
    {"i18n", sal_True},
    {"i18npool", sal_True},
#ifdef UNX
#ifdef MACOSX
    {"dtransaqua", sal_True},
#else
    {"dtransX11", sal_True},
#endif
#endif
#if defined(WNT) || defined(OS2)
    {"sysdtrans", sal_False},
#endif
    {"dtrans", sal_False},
    {"mcnttype", sal_False},
    {"ftransl", sal_False},
    {"dnd", sal_False},
    {NULL, sal_False}
};

uno::Reference< lang::XMultiServiceFactory > vcl::unohelper::GetMultiServiceFactory()
{
    ImplSVData* pSVData = ImplGetSVData();
    if ( !pSVData->maAppData.mxMSF.is() )
    {
        pSVData->maAppData.mxMSF = ::comphelper::getProcessServiceFactory();
    }
    if ( !pSVData->maAppData.mxMSF.is() )
    {
        TempFile aTempFile;
        OUString aTempFileName;
        osl::FileBase::getSystemPathFromFileURL( aTempFile.GetName(), aTempFileName );
        pSVData->maAppData.mpMSFTempFileName = new String(aTempFileName);

        try
        {
            pSVData->maAppData.mxMSF = ::cppu::createRegistryServiceFactory( aTempFileName, rtl::OUString(), sal_False );
            uno::Reference < registry::XImplementationRegistration > xReg(
                pSVData->maAppData.mxMSF->createInstance( OUString::createFromAscii( "com.sun.star.registry.ImplementationRegistration" )), uno::UNO_QUERY );

            if( xReg.is() )
            {
                sal_Int32 nCompCount = 0;
                while ( aVCLComponentsArray[ nCompCount ].pLibName )
                {
                    OUString aComponentPathString = CreateLibraryName( aVCLComponentsArray[ nCompCount ].pLibName,  aVCLComponentsArray[ nCompCount ].bHasSUPD );
                    if (aComponentPathString.getLength() )
                    {
                        try
                        {
                            xReg->registerImplementation(
                                OUString::createFromAscii( "com.sun.star.loader.SharedLibrary" ),aComponentPathString, NULL );
                        }
                        catch( ::com::sun::star::uno::Exception & )
                        {
                        }
                    }
                    nCompCount++;
                }
            }
        }
        catch( ::com::sun::star::uno::Exception & )
        {
            delete pSVData->maAppData.mpMSFTempFileName;
            pSVData->maAppData.mpMSFTempFileName = NULL;
        }
    }
    return pSVData->maAppData.mxMSF;
}

uno::Reference < i18n::XBreakIterator > vcl::unohelper::CreateBreakIterator()
{
    uno::Reference < i18n::XBreakIterator > xB;
    uno::Reference< lang::XMultiServiceFactory > xMSF = GetMultiServiceFactory();
    if ( xMSF.is() )
    {
        uno::Reference < uno::XInterface > xI = xMSF->createInstance( ::rtl::OUString::createFromAscii( "com.sun.star.i18n.BreakIterator" ) );
        if ( xI.is() )
        {
            uno::Any x = xI->queryInterface( ::getCppuType((const uno::Reference< i18n::XBreakIterator >*)0) );
            x >>= xB;
        }
    }
    return xB;
}

uno::Reference < i18n::XCharacterClassification > vcl::unohelper::CreateCharacterClassification()
{
    uno::Reference < i18n::XCharacterClassification > xB;
    uno::Reference< lang::XMultiServiceFactory > xMSF = GetMultiServiceFactory();
    if ( xMSF.is() )
    {
        uno::Reference < uno::XInterface > xI = xMSF->createInstance( ::rtl::OUString::createFromAscii( "com.sun.star.i18n.CharacterClassification" ) );
        if ( xI.is() )
        {
            uno::Any x = xI->queryInterface( ::getCppuType((const uno::Reference< i18n::XCharacterClassification >*)0) );
            x >>= xB;
        }
    }
    return xB;
}

uno::Reference < i18n::XCollator > vcl::unohelper::CreateCollator()
{
    uno::Reference < i18n::XCollator > xB;
    uno::Reference< lang::XMultiServiceFactory > xMSF = GetMultiServiceFactory();
    if ( xMSF.is() )
    {
        uno::Reference < uno::XInterface > xI = xMSF->createInstance( ::rtl::OUString::createFromAscii( "com.sun.star.i18n.Collator" ) );
        if ( xI.is() )
        {
            uno::Any x = xI->queryInterface( ::getCppuType((const uno::Reference< i18n::XCollator >*)0) );
            x >>= xB;
        }
    }
    return xB;
}

::rtl::OUString vcl::unohelper::CreateLibraryName( const sal_Char* pModName, BOOL bSUPD )
{
    // create variable library name suffixes
    OUString aSUPDString( OUString::valueOf( (sal_Int32)SUPD, 10 ));
    OUString aDLLSuffix = OUString::createFromAscii( STRING(DLLPOSTFIX) );

    OUString aLibName;

#if defined( WNT) || defined(OS2)
    aLibName = OUString::createFromAscii( pModName );
    if ( bSUPD )
    {
        aLibName += aSUPDString;
        aLibName += aDLLSuffix;
    }
    aLibName += rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ".dll" ));
#else
    aLibName = OUString( RTL_CONSTASCII_USTRINGPARAM( "lib" ));
    aLibName += OUString::createFromAscii( pModName );
    if ( bSUPD )
    {
        aLibName += aSUPDString;
        aLibName += aDLLSuffix;
    }
#ifdef MACOSX
    aLibName += OUString( RTL_CONSTASCII_USTRINGPARAM( ".dylib" ));
#else
    aLibName += OUString( RTL_CONSTASCII_USTRINGPARAM( ".so" ));
#endif
#endif

    return aLibName;
}

void vcl::unohelper::NotifyAccessibleStateEventGlobally( const ::com::sun::star::accessibility::AccessibleEventObject& rEventObject )
{
    ::com::sun::star::uno::Reference< ::com::sun::star::awt::XExtendedToolkit > xExtToolkit( Application::GetVCLToolkit(), uno::UNO_QUERY );
    if ( xExtToolkit.is() )
    {
        // Only for focus events
        sal_Int16 nType = ::com::sun::star::accessibility::AccessibleStateType::INVALID;
        rEventObject.NewValue >>= nType;
        if ( nType == ::com::sun::star::accessibility::AccessibleStateType::FOCUSED )
            xExtToolkit->fireFocusGained( rEventObject.Source );
        else
        {
            rEventObject.OldValue >>= nType;
            if ( nType == ::com::sun::star::accessibility::AccessibleStateType::FOCUSED )
                xExtToolkit->fireFocusLost( rEventObject.Source );
        }

    }
}
<commit_msg>INTEGRATION: CWS supdremove02 (1.36.142); FILE MERGED 2008/01/25 15:14:32 rt 1.36.142.1: #i85482# Remove UPD from library names.<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: unohelp.cxx,v $
 *
 *  $Revision: 1.37 $
 *
 *  last change: $Author: obo $ $Date: 2008-02-25 16:54:33 $
 *
 *  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_vcl.hxx"

#include <vcl/unohelp.hxx>

#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#endif

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

#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif

#ifndef _COM_SUN_STAR_TEXT_XBREAKITERATOR_HPP_
#include <com/sun/star/i18n/XBreakIterator.hpp>
#endif

#ifndef _COM_SUN_STAR_I18N_XCHARACTERCLASSIFICATION_HPP_
#include <com/sun/star/i18n/XCharacterClassification.hpp>
#endif

#ifndef _COM_SUN_STAR_UTIL_XCOLLATOR_HPP_
#include <com/sun/star/i18n/XCollator.hpp>
#endif

#ifndef _COM_SUN_STAR_AWT_XEXTENDEDTOOLKIT_HPP_
#include <com/sun/star/awt/XExtendedToolkit.hpp>
#endif

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

#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLESTATETYPE_HPP_
#include <com/sun/star/accessibility/AccessibleStateType.hpp>
#endif

#include <com/sun/star/registry/XImplementationRegistration.hpp>

#include <cppuhelper/servicefactory.hxx>

#include <tools/tempfile.hxx>
#include <osl/file.hxx>

#include <vcl/svdata.hxx>
#include <vcl/svapp.hxx>

using namespace ::com::sun::star;
using namespace ::rtl;

#define DOSTRING( x )                       #x
#define STRING( x )                         DOSTRING( x )

struct VCLRegServiceInfo
{
    const sal_Char*     pLibName;
    sal_Bool            bHasSUPD;
};

static VCLRegServiceInfo aVCLComponentsArray[] =
{
    {"i18n", sal_True},
    {"i18npool", sal_True},
#ifdef UNX
#ifdef MACOSX
    {"dtransaqua", sal_True},
#else
    {"dtransX11", sal_True},
#endif
#endif
#if defined(WNT) || defined(OS2)
    {"sysdtrans", sal_False},
#endif
    {"dtrans", sal_False},
    {"mcnttype", sal_False},
    {"ftransl", sal_False},
    {"dnd", sal_False},
    {NULL, sal_False}
};

uno::Reference< lang::XMultiServiceFactory > vcl::unohelper::GetMultiServiceFactory()
{
    ImplSVData* pSVData = ImplGetSVData();
    if ( !pSVData->maAppData.mxMSF.is() )
    {
        pSVData->maAppData.mxMSF = ::comphelper::getProcessServiceFactory();
    }
    if ( !pSVData->maAppData.mxMSF.is() )
    {
        TempFile aTempFile;
        OUString aTempFileName;
        osl::FileBase::getSystemPathFromFileURL( aTempFile.GetName(), aTempFileName );
        pSVData->maAppData.mpMSFTempFileName = new String(aTempFileName);

        try
        {
            pSVData->maAppData.mxMSF = ::cppu::createRegistryServiceFactory( aTempFileName, rtl::OUString(), sal_False );
            uno::Reference < registry::XImplementationRegistration > xReg(
                pSVData->maAppData.mxMSF->createInstance( OUString::createFromAscii( "com.sun.star.registry.ImplementationRegistration" )), uno::UNO_QUERY );

            if( xReg.is() )
            {
                sal_Int32 nCompCount = 0;
                while ( aVCLComponentsArray[ nCompCount ].pLibName )
                {
                    OUString aComponentPathString = CreateLibraryName( aVCLComponentsArray[ nCompCount ].pLibName,  aVCLComponentsArray[ nCompCount ].bHasSUPD );
                    if (aComponentPathString.getLength() )
                    {
                        try
                        {
                            xReg->registerImplementation(
                                OUString::createFromAscii( "com.sun.star.loader.SharedLibrary" ),aComponentPathString, NULL );
                        }
                        catch( ::com::sun::star::uno::Exception & )
                        {
                        }
                    }
                    nCompCount++;
                }
            }
        }
        catch( ::com::sun::star::uno::Exception & )
        {
            delete pSVData->maAppData.mpMSFTempFileName;
            pSVData->maAppData.mpMSFTempFileName = NULL;
        }
    }
    return pSVData->maAppData.mxMSF;
}

uno::Reference < i18n::XBreakIterator > vcl::unohelper::CreateBreakIterator()
{
    uno::Reference < i18n::XBreakIterator > xB;
    uno::Reference< lang::XMultiServiceFactory > xMSF = GetMultiServiceFactory();
    if ( xMSF.is() )
    {
        uno::Reference < uno::XInterface > xI = xMSF->createInstance( ::rtl::OUString::createFromAscii( "com.sun.star.i18n.BreakIterator" ) );
        if ( xI.is() )
        {
            uno::Any x = xI->queryInterface( ::getCppuType((const uno::Reference< i18n::XBreakIterator >*)0) );
            x >>= xB;
        }
    }
    return xB;
}

uno::Reference < i18n::XCharacterClassification > vcl::unohelper::CreateCharacterClassification()
{
    uno::Reference < i18n::XCharacterClassification > xB;
    uno::Reference< lang::XMultiServiceFactory > xMSF = GetMultiServiceFactory();
    if ( xMSF.is() )
    {
        uno::Reference < uno::XInterface > xI = xMSF->createInstance( ::rtl::OUString::createFromAscii( "com.sun.star.i18n.CharacterClassification" ) );
        if ( xI.is() )
        {
            uno::Any x = xI->queryInterface( ::getCppuType((const uno::Reference< i18n::XCharacterClassification >*)0) );
            x >>= xB;
        }
    }
    return xB;
}

uno::Reference < i18n::XCollator > vcl::unohelper::CreateCollator()
{
    uno::Reference < i18n::XCollator > xB;
    uno::Reference< lang::XMultiServiceFactory > xMSF = GetMultiServiceFactory();
    if ( xMSF.is() )
    {
        uno::Reference < uno::XInterface > xI = xMSF->createInstance( ::rtl::OUString::createFromAscii( "com.sun.star.i18n.Collator" ) );
        if ( xI.is() )
        {
            uno::Any x = xI->queryInterface( ::getCppuType((const uno::Reference< i18n::XCollator >*)0) );
            x >>= xB;
        }
    }
    return xB;
}

::rtl::OUString vcl::unohelper::CreateLibraryName( const sal_Char* pModName, BOOL bSUPD )
{
    // create variable library name suffixes
    OUString aDLLSuffix = OUString::createFromAscii( STRING(DLLPOSTFIX) );

    OUString aLibName;

#if defined( WNT) || defined(OS2)
    aLibName = OUString::createFromAscii( pModName );
    if ( bSUPD )
    {
        aLibName += aDLLSuffix;
    }
    aLibName += rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ".dll" ));
#else
    aLibName = OUString( RTL_CONSTASCII_USTRINGPARAM( "lib" ));
    aLibName += OUString::createFromAscii( pModName );
    if ( bSUPD )
    {
        aLibName += aDLLSuffix;
    }
#ifdef MACOSX
    aLibName += OUString( RTL_CONSTASCII_USTRINGPARAM( ".dylib" ));
#else
    aLibName += OUString( RTL_CONSTASCII_USTRINGPARAM( ".so" ));
#endif
#endif

    return aLibName;
}

void vcl::unohelper::NotifyAccessibleStateEventGlobally( const ::com::sun::star::accessibility::AccessibleEventObject& rEventObject )
{
    ::com::sun::star::uno::Reference< ::com::sun::star::awt::XExtendedToolkit > xExtToolkit( Application::GetVCLToolkit(), uno::UNO_QUERY );
    if ( xExtToolkit.is() )
    {
        // Only for focus events
        sal_Int16 nType = ::com::sun::star::accessibility::AccessibleStateType::INVALID;
        rEventObject.NewValue >>= nType;
        if ( nType == ::com::sun::star::accessibility::AccessibleStateType::FOCUSED )
            xExtToolkit->fireFocusGained( rEventObject.Source );
        else
        {
            rEventObject.OldValue >>= nType;
            if ( nType == ::com::sun::star::accessibility::AccessibleStateType::FOCUSED )
                xExtToolkit->fireFocusLost( rEventObject.Source );
        }

    }
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: unohelp.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: pluby $ $Date: 2000-11-30 17:43:58 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#pragma hdrstop

#include <unohelp.hxx>

#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#endif

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

#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif

#include <com/sun/star/registry/XRegistryKey.hpp>
#include <cppuhelper/factory.hxx>

#include <uno/environment.h>
#include <uno/mapping.hxx>
#include <rtl/ustring.hxx>
#include <osl/module.h>

#ifndef _COM_SUN_STAR_TEXT_XBREAKITERATOR_HPP_
#include <com/sun/star/i18n/XBreakIterator.hpp>
#endif

#ifndef _COM_SUN_STAR_I18N_XCHARACTERCLASSIFICATION_HPP_
#include <com/sun/star/i18n/XCharacterClassification.hpp>
#endif

#ifndef _COM_SUN_STAR_UTIL_XCOLLATOR_HPP_
#include <com/sun/star/i18n/XCollator.hpp>
#endif

#ifdef DBG_UTIL
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _STRING_HXX
#include <tools/string.hxx>
#endif
#ifndef _OSL_THREAD_H_
#include <osl/thread.h>
#endif
#endif

using namespace ::com::sun::star;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::i18n;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::registry;
using namespace ::rtl;

#define DOSTRING( x )                       #x
#define STRING( x )                         DOSTRING( x )

#define DOCONCAT4( x, y, z, a )             x##y##z##a
#define CONCAT4( x, y, z, a )               DOCONCAT4(x,y,z,a)
#define DOCONCAT5( x, y, z, a, b )          x##y##z##a##b
#define CONCAT5( x, y, z, a, b )            DOCONCAT5(x,y,z,a,b)

#ifdef UNX
#ifdef MACOSX
#define LIBNAME(name)                       STRING(CONCAT5(lib,name,SUPD, DLLSUFFIX,.dylib.framework))
#else
#define LIBNAME(name)                       STRING(CONCAT5(lib,name,SUPD, DLLSUFFIX,.so))
#endif
#else
#define LIBNAME(name)                       STRING(CONCAT4( name, SUPD, DLLSUFFIX, .dll))
#endif

Reference< XSingleServiceFactory > ImplLoadLibComponentFactory(
    const OUString & rLibName, const OUString & rImplName,
    const Reference< XMultiServiceFactory > & xSF, const Reference< XRegistryKey > & xKey )
{
    Reference< XSingleServiceFactory > xRet;

    oslModule lib = osl_loadModule( rLibName.pData, SAL_LOADMODULE_LAZY | SAL_LOADMODULE_GLOBAL );
#ifdef DBG_UTIL
    ByteString aMsg( "Cannot load module " );
    aMsg += ByteString( String( rLibName ), osl_getThreadTextEncoding() );
    DBG_ASSERT( lib, aMsg.GetBuffer() )
#endif
    if (lib)
    {
        void * pSym;

        // ========================= LATEST VERSION =========================
        OUString aGetEnvName( RTL_CONSTASCII_USTRINGPARAM(COMPONENT_GETENV) );
        if (pSym = osl_getSymbol( lib, aGetEnvName.pData ))
        {
            uno_Environment * pCurrentEnv = 0;
            uno_Environment * pEnv = 0;
            const sal_Char * pEnvTypeName = 0;
            (*((component_getImplementationEnvironmentFunc)pSym))( &pEnvTypeName, &pEnv );

            sal_Bool bNeedsMapping =
                (pEnv || 0 != rtl_str_compare( pEnvTypeName, CPPU_CURRENT_LANGUAGE_BINDING_NAME ));

            OUString aEnvTypeName( OUString::createFromAscii( pEnvTypeName ) );

            if (bNeedsMapping)
            {
                if (! pEnv)
                    uno_getEnvironment( &pEnv, aEnvTypeName.pData, 0 );
                if (pEnv)
                {
                    OUString aCppEnvTypeName( RTL_CONSTASCII_USTRINGPARAM(CPPU_CURRENT_LANGUAGE_BINDING_NAME) );
                    uno_getEnvironment( &pCurrentEnv, aCppEnvTypeName.pData, 0 );
                    if (pCurrentEnv)
                        bNeedsMapping = (pEnv != pCurrentEnv);
                }
            }

            OUString aGetFactoryName( RTL_CONSTASCII_USTRINGPARAM(COMPONENT_GETFACTORY) );
            if (pSym = osl_getSymbol( lib, aGetFactoryName.pData ))
            {
                OString aImplName( OUStringToOString( rImplName, RTL_TEXTENCODING_ASCII_US ) );

                if (bNeedsMapping)
                {
                    if (pEnv && pCurrentEnv)
                    {
                        Mapping aCurrent2Env( pCurrentEnv, pEnv );
                        Mapping aEnv2Current( pEnv, pCurrentEnv );

                        if (aCurrent2Env.is() && aEnv2Current.is())
                        {
                            void * pSMgr = aCurrent2Env.mapInterface(
                                xSF.get(), ::getCppuType( (const Reference< XMultiServiceFactory > *)0 ) );
                            void * pKey = aCurrent2Env.mapInterface(
                                xKey.get(), ::getCppuType( (const Reference< XRegistryKey > *)0 ) );

                            void * pSSF = (*((component_getFactoryFunc)pSym))(
                                aImplName.getStr(), pSMgr, pKey );

                            if (pKey)
                                (*pEnv->pExtEnv->releaseInterface)( pEnv->pExtEnv, pKey );
                            if (pSMgr)
                                (*pEnv->pExtEnv->releaseInterface)( pEnv->pExtEnv, pSMgr );

                            if (pSSF)
                            {
                                aEnv2Current.mapInterface(
                                    reinterpret_cast< void ** >( &xRet ),
                                    pSSF, ::getCppuType( (const Reference< XSingleServiceFactory > *)0 ) );
                                (*pEnv->pExtEnv->releaseInterface)( pEnv->pExtEnv, pSSF );
                            }
                        }
                    }
                }
                else
                {
                    XSingleServiceFactory * pRet = (XSingleServiceFactory *)
                        (*((component_getFactoryFunc)pSym))(
                            aImplName.getStr(), xSF.get(), xKey.get() );
                    if (pRet)
                    {
                        xRet = pRet;
                        pRet->release();
                    }
                }
            }

            if (pEnv)
                (*pEnv->release)( pEnv );
            if (pCurrentEnv)
                (*pCurrentEnv->release)( pCurrentEnv );
        }

        if (! xRet.is())
            osl_unloadModule( lib );
    }

    return xRet;
}

uno::Reference < i18n::XBreakIterator > vcl::unohelper::CreateBreakIterator()
{
    uno::Reference < i18n::XBreakIterator > xB;
    uno::Reference< lang::XMultiServiceFactory > xMSF = ::comphelper::getProcessServiceFactory();
    if ( xMSF.is() )
    {
        uno::Reference < uno::XInterface > xI = xMSF->createInstance( ::rtl::OUString::createFromAscii( "com.sun.star.i18n.BreakIterator" ) );
        if ( xI.is() )
        {
            uno::Any x = xI->queryInterface( ::getCppuType((const uno::Reference< i18n::XBreakIterator >*)0) );
            x >>= xB;
        }
    }
    if( !xB.is() )
    {
        uno::Reference< lang::XSingleServiceFactory > xSSF = ImplLoadLibComponentFactory(
            OUString( RTL_CONSTASCII_USTRINGPARAM( LIBNAME( int ) ) ), OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.i18n.BreakIterator" ) ),
            Reference< XMultiServiceFactory >(), Reference< XRegistryKey >() );

        uno::Reference < uno::XInterface > xI = xSSF->createInstance();
        if ( xI.is() )
        {
            uno::Any x = xI->queryInterface( ::getCppuType((const uno::Reference< i18n::XBreakIterator >*)0) );
            x >>= xB;
        }
    }
    return xB;
}

uno::Reference < i18n::XCharacterClassification > vcl::unohelper::CreateCharacterClassification()
{
    uno::Reference < i18n::XCharacterClassification > xB;
    uno::Reference< lang::XMultiServiceFactory > xMSF = ::comphelper::getProcessServiceFactory();
    if ( xMSF.is() )
    {
        uno::Reference < uno::XInterface > xI = xMSF->createInstance( ::rtl::OUString::createFromAscii( "com.sun.star.i18n.CharacterClassification" ) );
        if ( xI.is() )
        {
            uno::Any x = xI->queryInterface( ::getCppuType((const uno::Reference< i18n::XCharacterClassification >*)0) );
            x >>= xB;
        }
    }
    if( !xB.is() )
    {
        uno::Reference< lang::XSingleServiceFactory > xSSF = ImplLoadLibComponentFactory(
            OUString( RTL_CONSTASCII_USTRINGPARAM( LIBNAME( int ) ) ), OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.i18n.CharacterClassification" ) ),
            Reference< XMultiServiceFactory >(), Reference< XRegistryKey >() );

        uno::Reference < uno::XInterface > xI = xSSF->createInstance();
        if ( xI.is() )
        {
            uno::Any x = xI->queryInterface( ::getCppuType((const uno::Reference< i18n::XCharacterClassification >*)0) );
            x >>= xB;
        }
    }
    return xB;
}

uno::Reference < i18n::XCollator > vcl::unohelper::CreateCollator()
{
    uno::Reference < i18n::XCollator > xB;
    uno::Reference< lang::XMultiServiceFactory > xMSF = ::comphelper::getProcessServiceFactory();
    if ( xMSF.is() )
    {
        uno::Reference < uno::XInterface > xI = xMSF->createInstance( ::rtl::OUString::createFromAscii( "com.sun.star.i18n.Collator" ) );
        if ( xI.is() )
        {
            uno::Any x = xI->queryInterface( ::getCppuType((const uno::Reference< i18n::XCollator >*)0) );
            x >>= xB;
        }
    }
    if( !xB.is() )
    {
        uno::Reference< lang::XSingleServiceFactory > xSSF = ImplLoadLibComponentFactory(
            OUString( RTL_CONSTASCII_USTRINGPARAM( LIBNAME( int ) ) ),
            OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.i18n.GNUcollator" ) ),
            Reference< XMultiServiceFactory >(), Reference< XRegistryKey >() );

        if (xSSF.is())
        {
            uno::Reference < uno::XInterface > xI = xSSF->createInstance();
            if ( xI.is() )
            {
                uno::Any x = xI->queryInterface( ::getCppuType((const uno::Reference< i18n::XCollator >*)0) );
                x >>= xB;
            }
        }
    }
    if( !xB.is() )
    {
        uno::Reference< lang::XSingleServiceFactory > xSSF = ImplLoadLibComponentFactory(
            OUString( RTL_CONSTASCII_USTRINGPARAM( LIBNAME( int ) ) ),
            OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.i18n.SimpleCollator" ) ),
            Reference< XMultiServiceFactory >(), Reference< XRegistryKey >() );

        if (xSSF.is())
        {
            uno::Reference < uno::XInterface > xI = xSSF->createInstance();
            if ( xI.is() )
            {
                uno::Any x = xI->queryInterface( ::getCppuType((const uno::Reference< i18n::XCollator >*)0) );
                x >>= xB;
            }
        }
    }

    return xB;
}

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

#pragma hdrstop

#include <unohelp.hxx>

#ifndef _COM_SUN_STAR_LANG_XSINGLESERVICEFACTORY_HPP_
#include <com/sun/star/lang/XSingleServiceFactory.hpp>
#endif

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

#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif

#ifndef _COM_SUN_STAR_TEXT_XBREAKITERATOR_HPP_
#include <com/sun/star/i18n/XBreakIterator.hpp>
#endif

#ifndef _COM_SUN_STAR_I18N_XCHARACTERCLASSIFICATION_HPP_
#include <com/sun/star/i18n/XCharacterClassification.hpp>
#endif

#ifndef _COM_SUN_STAR_UTIL_XCOLLATOR_HPP_
#include <com/sun/star/i18n/XCollator.hpp>
#endif

#include <com/sun/star/registry/XImplementationRegistration.hpp>

#include <cppuhelper/servicefactory.hxx>

#include <tools/tempfile.hxx>
#include <osl/file.hxx>

#include <svdata.hxx>

using namespace ::com::sun::star;
using namespace ::rtl;

#define DOSTRING( x )                       #x
#define STRING( x )                         DOSTRING( x )

struct VCLRegServiceInfo
{
    sal_Char*   pLibName;
    sal_Bool    bHasSUPD;
};

static VCLRegServiceInfo aVCLComponentsArray[] =
{
    {"int",             sal_True},
#ifdef UNIX
    {"dtransX11",       sal_True},
#endif
#ifdef WNT
    {"sysdtrans",       sal_False},
#endif
    {NULL,              sal_False}
};

uno::Reference< lang::XMultiServiceFactory > ImplGetMultiServiceFactory()
{
    ImplSVData* pSVData = ImplGetSVData();
    if ( !pSVData->maAppData.mxMSF.is() )
    {
        pSVData->maAppData.mxMSF = ::comphelper::getProcessServiceFactory();
    }
    if ( !pSVData->maAppData.mxMSF.is() )
    {
        TempFile aTempFile;
        OUString aTempFileName;
        osl::FileBase::getNormalizedPathFromFileURL( aTempFile.GetName(), aTempFileName );
        pSVData->maAppData.mpMSFTempFileName = new String(aTempFileName);

        pSVData->maAppData.mxMSF = ::cppu::createRegistryServiceFactory( aTempFileName, rtl::OUString(), sal_False );

        uno::Reference < registry::XImplementationRegistration > xReg(
            pSVData->maAppData.mxMSF->createInstance( OUString::createFromAscii( "com.sun.star.registry.ImplementationRegistration" )), uno::UNO_QUERY );

        sal_Int32 nCompCount = 0;

        // create variable library name suffixes
        OUString aSUPDString( OUString::valueOf( (sal_Int32)SUPD, 10 ));
        OUString aDLLSuffix = OUString::createFromAscii( STRING(DLLSUFFIX) );

        while ( aVCLComponentsArray[ nCompCount ].pLibName )
        {
            OUString aComponentPathString;

#ifdef WNT
            aComponentPathString = OUString::createFromAscii( aVCLComponentsArray[ nCompCount ].pLibName );
            if ( aVCLComponentsArray[ nCompCount ].bHasSUPD )
            {
                aComponentPathString += aSUPDString;
                aComponentPathString += aDLLSuffix;
            }
            aComponentPathString += rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ".dll" ));
#else
            aComponentPathString = OUString( RTL_CONSTASCII_USTRINGPARAM( "lib" ));
            aComponentPathString += OUString::createFromAscii( aVCLComponentsArray[ nCompCount ].pLibName );
            if ( aVCLComponentsArray[ nCompCount ].bHasSUPD )
            {
                aComponentPathString += aSUPDString;
                aComponentPathString += aDLLSuffix;
            }
            aComponentPathString += OUString( RTL_CONSTASCII_USTRINGPARAM( ".so" ));
#endif

            if (aComponentPathString.getLength() )
            {
                try
                {
                    xReg->registerImplementation(
                        OUString::createFromAscii( "com.sun.star.loader.SharedLibrary" ),aComponentPathString, NULL );
                }
                catch( ::com::sun::star::uno::Exception & )
                {
                }
            }
            nCompCount++;
        }
    }
    return pSVData->maAppData.mxMSF;
}

uno::Reference < i18n::XBreakIterator > vcl::unohelper::CreateBreakIterator()
{
    uno::Reference < i18n::XBreakIterator > xB;
    uno::Reference< lang::XMultiServiceFactory > xMSF = ImplGetMultiServiceFactory();
    if ( xMSF.is() )
    {
        uno::Reference < uno::XInterface > xI = xMSF->createInstance( ::rtl::OUString::createFromAscii( "com.sun.star.i18n.BreakIterator" ) );
        if ( xI.is() )
        {
            uno::Any x = xI->queryInterface( ::getCppuType((const uno::Reference< i18n::XBreakIterator >*)0) );
            x >>= xB;
        }
    }
    return xB;
}

uno::Reference < i18n::XCharacterClassification > vcl::unohelper::CreateCharacterClassification()
{
    uno::Reference < i18n::XCharacterClassification > xB;
    uno::Reference< lang::XMultiServiceFactory > xMSF = ImplGetMultiServiceFactory();
    if ( xMSF.is() )
    {
        uno::Reference < uno::XInterface > xI = xMSF->createInstance( ::rtl::OUString::createFromAscii( "com.sun.star.i18n.CharacterClassification" ) );
        if ( xI.is() )
        {
            uno::Any x = xI->queryInterface( ::getCppuType((const uno::Reference< i18n::XCharacterClassification >*)0) );
            x >>= xB;
        }
    }
    return xB;
}

uno::Reference < i18n::XCollator > vcl::unohelper::CreateCollator()
{
    uno::Reference < i18n::XCollator > xB;
    uno::Reference< lang::XMultiServiceFactory > xMSF = ImplGetMultiServiceFactory();
    if ( xMSF.is() )
    {
        uno::Reference < uno::XInterface > xI = xMSF->createInstance( ::rtl::OUString::createFromAscii( "com.sun.star.i18n.Collator" ) );
        if ( xI.is() )
        {
            uno::Any x = xI->queryInterface( ::getCppuType((const uno::Reference< i18n::XCollator >*)0) );
            x >>= xB;
        }
    }
    return xB;
}

<|endoftext|>


<commit_before><commit_msg>reduce scope of many variables<commit_after><|endoftext|>


<commit_before>// Copyright (c) 2020 by Robert Bosch GmbH, Apex.AI Inc. All rights reserved.
// Copyright (c) 2020 - 2021 by Apex.AI Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
#ifndef IOX_UTILS_CXX_VARIANT_QUEUE_HPP
#define IOX_UTILS_CXX_VARIANT_QUEUE_HPP

#include "iceoryx_utils/concurrent/resizeable_lockfree_queue.hpp"
#include "iceoryx_utils/cxx/expected.hpp"
#include "iceoryx_utils/cxx/optional.hpp"
#include "iceoryx_utils/cxx/variant.hpp"
#include "iceoryx_utils/internal/concurrent/fifo.hpp"
#include "iceoryx_utils/internal/concurrent/sofi.hpp"
#include "iceoryx_utils/internal/concurrent/trigger_queue.hpp"

#include <cstdint>

namespace iox
{
namespace cxx
{
/// @brief list of the supported underlying queue types
/// @note  if a new queue type is added the following steps have to be
///         performed:
///         1. add queue type here
///         2. add queue type in m_fifo data member variant type
///         3. increase numberOfQueueTypes in test_cxx_variant_queue test
enum class VariantQueueTypes : uint64_t
{
    FiFo_SingleProducerSingleConsumer = 0,
    SoFi_SingleProducerSingleConsumer = 1,
    FiFo_MultiProducerSingleConsumer = 2,
    SoFi_MultiProducerSingleConsumer = 3,
};

// remark: we need to consider to support the non-resizable queue as well
//         since it should have performance benefits if resize is not actually needed
//         for now we just use the most general variant, which allows resizing

/// @brief wrapper of multiple fifo's
/// @param[in] ValueType type which should be stored
/// @param[in] Capacity capacity of the underlying fifo
/// @code
///     cxx::VariantQueue<int, 5> nonOverflowingQueue(cxx::VariantQueueTypes::FiFo_SingleProducerSingleConsumer);
///     cxx::VariantQueue<int, 5> overflowingQueue(cxx::VariantQueueTypes::SoFi_SingleProducerSingleConsumer);
///
///     // overflow case
///     auto status = nonOverflowingQueue.push(123);
///     if ( !status ) {
///         std::cout << "queue is full" << std::endl;
///     }
///
///     auto overriddenElement = overflowingQueue.push(123);
///     if ( overriddenElement->has_value() ) {
///         std::cout << "element " << overriddenElement->value() << " was overridden\n";
///     }
/// @endcode
template <typename ValueType, uint64_t Capacity>
class VariantQueue
{
  public:
    using fifo_t = variant<concurrent::FiFo<ValueType, Capacity>,
                           concurrent::SoFi<ValueType, Capacity>,
                           concurrent::ResizeableLockFreeQueue<ValueType, Capacity>,
                           concurrent::ResizeableLockFreeQueue<ValueType, Capacity>,
                           concurrent::TriggerQueue<ValueType, Capacity, concurrent::FiFo>,
                           concurrent::TriggerQueue<ValueType, Capacity, concurrent::ResizeableLockFreeQueue>>;

    /// @brief Constructor of a VariantQueue
    /// @param[in] type type of the underlying queue
    VariantQueue(const VariantQueueTypes type) noexcept;

    /// @brief pushs an element into the fifo
    /// @param[in] value value which should be added in the fifo
    /// @return if the underlying queue has an overflow the optional will contain
    ///         the value which was overridden (SOFI) or which was dropped (FIFO)
    ///         otherwise the optional contains nullopt_t
    optional<ValueType> push(const ValueType& value) noexcept;

    /// @brief pops an element from the fifo
    /// @return if the fifo did contain an element it is returned inside the optional
    ///         otherwise the optional contains nullopt_t
    optional<ValueType> pop() noexcept;

    /// @brief returns true if empty otherwise true
    bool empty() const noexcept;

    /// @brief get the current size of the queue. Caution, another thread can have changed the size just after reading
    /// it
    /// @return queue size
    uint64_t size() noexcept;

    /// @brief set the capacity of the queue
    /// @param[in] newCapacity valid values are 0 < newCapacity < MAX_SUBSCRIBER_QUEUE_CAPACITY
    /// @return true if setting the new capacity succeeded, false otherwise
    /// @pre it is important that no pop or push calls occur during
    ///         this call
    /// @note depending on the internal queue used, concurrent pushes and pops are possible
    ///       (for FiFo_MultiProducerSingleConsumer and SoFi_MultiProducerSingleConsumer)
    /// @concurrent not thread safe
    bool setCapacity(const uint64_t newCapacity) noexcept;

    /// @brief get the capacity of the queue.
    /// @return queue size
    uint64_t capacity() const noexcept;

    /// @brief returns reference to the underlying fifo
    /// @code
    ///    VariantQueueTypes<int, 10> myFifo(VariantQueueTypes::FiFo_SingleProducerSingleConsumer);
    ///
    ///    // access the underlying fifo directly and call empty on it
    ///    myFifo.getUnderlyingFiFo().template
    ///    get_at_index<VariantQueueTypes::FiFo_SingleProducerSingleConsumer>()->empty();
    /// @endcode
    fifo_t& getUnderlyingFiFo() noexcept;

  private:
    VariantQueueTypes m_type;
    fifo_t m_fifo;
};
} // namespace cxx
} // namespace iox

#include "iceoryx_utils/internal/cxx/variant_queue.inl"

#endif // IOX_UTILS_CXX_VARIANT_QUEUE_HPP
<commit_msg>iox-#615 remove remainders of blocking options from variant queue<commit_after>// Copyright (c) 2020 by Robert Bosch GmbH. All rights reserved.
// Copyright (c) 2020 - 2021 by Apex.AI Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
#ifndef IOX_UTILS_CXX_VARIANT_QUEUE_HPP
#define IOX_UTILS_CXX_VARIANT_QUEUE_HPP

#include "iceoryx_utils/concurrent/resizeable_lockfree_queue.hpp"
#include "iceoryx_utils/cxx/expected.hpp"
#include "iceoryx_utils/cxx/optional.hpp"
#include "iceoryx_utils/cxx/variant.hpp"
#include "iceoryx_utils/internal/concurrent/fifo.hpp"
#include "iceoryx_utils/internal/concurrent/sofi.hpp"

#include <cstdint>

namespace iox
{
namespace cxx
{
/// @brief list of the supported underlying queue types
/// @note  if a new queue type is added the following steps have to be
///         performed:
///         1. add queue type here
///         2. add queue type in m_fifo data member variant type
///         3. increase numberOfQueueTypes in test_cxx_variant_queue test
enum class VariantQueueTypes : uint64_t
{
    FiFo_SingleProducerSingleConsumer = 0,
    SoFi_SingleProducerSingleConsumer = 1,
    FiFo_MultiProducerSingleConsumer = 2,
    SoFi_MultiProducerSingleConsumer = 3
};

// remark: we need to consider to support the non-resizable queue as well
//         since it should have performance benefits if resize is not actually needed
//         for now we just use the most general variant, which allows resizing

/// @brief wrapper of multiple fifo's
/// @param[in] ValueType type which should be stored
/// @param[in] Capacity capacity of the underlying fifo
/// @code
///     cxx::VariantQueue<int, 5> nonOverflowingQueue(cxx::VariantQueueTypes::FiFo_SingleProducerSingleConsumer);
///     cxx::VariantQueue<int, 5> overflowingQueue(cxx::VariantQueueTypes::SoFi_SingleProducerSingleConsumer);
///
///     // overflow case
///     auto status = nonOverflowingQueue.push(123);
///     if ( !status ) {
///         std::cout << "queue is full" << std::endl;
///     }
///
///     auto overriddenElement = overflowingQueue.push(123);
///     if ( overriddenElement->has_value() ) {
///         std::cout << "element " << overriddenElement->value() << " was overridden\n";
///     }
/// @endcode
template <typename ValueType, uint64_t Capacity>
class VariantQueue
{
  public:
    using fifo_t = variant<concurrent::FiFo<ValueType, Capacity>,
                           concurrent::SoFi<ValueType, Capacity>,
                           concurrent::ResizeableLockFreeQueue<ValueType, Capacity>,
                           concurrent::ResizeableLockFreeQueue<ValueType, Capacity>>;

    /// @brief Constructor of a VariantQueue
    /// @param[in] type type of the underlying queue
    VariantQueue(const VariantQueueTypes type) noexcept;

    /// @brief pushs an element into the fifo
    /// @param[in] value value which should be added in the fifo
    /// @return if the underlying queue has an overflow the optional will contain
    ///         the value which was overridden (SOFI) or which was dropped (FIFO)
    ///         otherwise the optional contains nullopt_t
    optional<ValueType> push(const ValueType& value) noexcept;

    /// @brief pops an element from the fifo
    /// @return if the fifo did contain an element it is returned inside the optional
    ///         otherwise the optional contains nullopt_t
    optional<ValueType> pop() noexcept;

    /// @brief returns true if empty otherwise true
    bool empty() const noexcept;

    /// @brief get the current size of the queue. Caution, another thread can have changed the size just after reading
    /// it
    /// @return queue size
    uint64_t size() noexcept;

    /// @brief set the capacity of the queue
    /// @param[in] newCapacity valid values are 0 < newCapacity < MAX_SUBSCRIBER_QUEUE_CAPACITY
    /// @return true if setting the new capacity succeeded, false otherwise
    /// @pre it is important that no pop or push calls occur during
    ///         this call
    /// @note depending on the internal queue used, concurrent pushes and pops are possible
    ///       (for FiFo_MultiProducerSingleConsumer and SoFi_MultiProducerSingleConsumer)
    /// @concurrent not thread safe
    bool setCapacity(const uint64_t newCapacity) noexcept;

    /// @brief get the capacity of the queue.
    /// @return queue size
    uint64_t capacity() const noexcept;

    /// @brief returns reference to the underlying fifo
    /// @code
    ///    VariantQueueTypes<int, 10> myFifo(VariantQueueTypes::FiFo_SingleProducerSingleConsumer);
    ///
    ///    // access the underlying fifo directly and call empty on it
    ///    myFifo.getUnderlyingFiFo().template
    ///    get_at_index<VariantQueueTypes::FiFo_SingleProducerSingleConsumer>()->empty();
    /// @endcode
    fifo_t& getUnderlyingFiFo() noexcept;

  private:
    VariantQueueTypes m_type;
    fifo_t m_fifo;
};
} // namespace cxx
} // namespace iox

#include "iceoryx_utils/internal/cxx/variant_queue.inl"

#endif // IOX_UTILS_CXX_VARIANT_QUEUE_HPP
<|endoftext|>


<commit_before><commit_msg>Resolves: fdo#84809 crash when button is too short for text<commit_after><|endoftext|>