<commit_before>//
// (c) Copyright 2017 DESY,ESS
//
// This file is part of h5pp.
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
// License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library; if not, write to the
// Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor
// Boston, MA  02110-1301 USA
// ===========================================================================
//
// Author: Martin Shetty <martin.shetty@esss.se>
// Created on: Sep 13, 2017
//

/*

 Summary of test results

  hid does not uniquely identify an h5 node

  object_address is stable across all scenarios

  file_number:
     not equal if same file closed and reopened
     identifies the file that owns object, not owner of link (in case of ext link)

  file_name:
     not equal if file opened via symbolic link (h5 allows opening same file twice)
     not equal if object opened via external link vs. original node

  Conclusions:
    file_number adequately reflects identity, unless file has been closed and reopened.
    file_name does not adequately reflect identity. Resolving symbolic link would solve
    part of the problem, but would also need to somehow dereference external links to
    identify the name of the object-owning file.

*/

#include <gtest/gtest.h>

#include <boost/filesystem.hpp>

#include <h5cpp/object_id.hpp>
#include <iostream>

namespace fs = boost::filesystem;

#define FILE1 fs::absolute("file1.h5").string().data()
#define FILE2 fs::absolute("file2.h5").string().data()
#define FILE3 fs::absolute("file3.h5").string().data()

using namespace hdf5;

struct OneFile
{
  OneFile(std::string fname)
  {
    fname_ = fname;
    file = H5Fcreate(fname.data(), H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);
    group1 = H5Gcreate(file, "/group1",
                       H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
    group2 = H5Gcreate(file, "/group2",
                       H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);

    hsize_t dims[2];
    dims[0] = 3;
    dims[1] = 3;
    hid_t dataspace = H5Screate_simple(2, dims, NULL);

    dset1 = H5Dcreate(group1, "dset1", H5T_NATIVE_DOUBLE, dataspace,
                      H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
  }

  ~OneFile()
  {
    H5Dclose(dset1);
    H5Gclose(group1);
    H5Gclose(group2);
    H5Fclose(file);
  }

  std::string fname_;
  hid_t file, group1, group2, dset1;
};

// For h5 hard links (to group):
//   file_name, file_number and address are all equal
TEST(ObjectId,  hard_group )
{
  OneFile file(FILE1);

  H5Lcreate_hard(file.file, "/group1",
                 file.file, "/group3",
                 H5P_DEFAULT, H5P_DEFAULT);
  hid_t group3 = H5Gopen(file.file, "/group3", H5P_DEFAULT);

  ObjectId info1(file.group1);
  ObjectId info2(group3);

  EXPECT_NE(file.group1, group3);
  EXPECT_EQ(info1.file_name(), info2.file_name());
  EXPECT_EQ(info1.file_number(), info2.file_number());
  EXPECT_EQ(info1.object_address(), info1.object_address());

  H5Gclose(group3);
  fs::remove(FILE1);
}

// For h5 hard links (to dataset):
//   file_name, file_number and address are all equal
TEST(ObjectId,  hard_dset )
{
  OneFile file(FILE1);

  H5Lcreate_hard(file.group1, "dset1",
                 file.group2, "dset2",
                 H5P_DEFAULT, H5P_DEFAULT);
  hid_t dset2 = H5Dopen(file.group2, "dset2", H5P_DEFAULT);

  ObjectId info1(file.dset1);
  ObjectId info2(dset2);

  EXPECT_NE(file.dset1, dset2);
  EXPECT_EQ(info1.file_name(), info2.file_name());
  EXPECT_EQ(info1.file_number(), info2.file_number());
  EXPECT_EQ(info1.object_address(), info1.object_address());

  H5Dclose(dset2);
  fs::remove(FILE1);
}

// For h5 soft links (to group):
//   file_name, file_number and address are all equal
TEST(ObjectId,  soft_group )
{
  OneFile file(FILE1);

  H5Lcreate_soft("/group1", file.file, "/group3",
                 H5P_DEFAULT, H5P_DEFAULT);
  hid_t group3 = H5Gopen(file.file, "/group3", H5P_DEFAULT);

  ObjectId info1(file.group1);
  ObjectId info2(group3);

  EXPECT_NE(file.group1, group3);
  EXPECT_EQ(info1.file_name(), info2.file_name());
  EXPECT_EQ(info1.file_number(), info2.file_number());
  EXPECT_EQ(info1.object_address(), info1.object_address());

  H5Gclose(group3);
  fs::remove(FILE1);
}

// For h5 soft links (to dataset):
//   file_name, file_number and address are all equal
TEST(ObjectId,  soft_dset )
{
  OneFile file(FILE1);

  H5Lcreate_soft("/group1/dset1", file.file, "/group2/dset2",
                 H5P_DEFAULT, H5P_DEFAULT);
  hid_t dset2 = H5Dopen(file.group2, "dset2", H5P_DEFAULT);

  ObjectId info1(file.dset1);
  ObjectId info2(dset2);

  EXPECT_NE(file.dset1, dset2);
  EXPECT_EQ(info1.file_name(), info2.file_name());
  EXPECT_EQ(info1.file_number(), info2.file_number());
  EXPECT_EQ(info1.object_address(), info1.object_address());

  H5Dclose(dset2);
  fs::remove(FILE1);
}

// If file copy is made:
//   only object addresses are equal
TEST(ObjectId,  file_copy )
{
  OneFile* file = new OneFile(FILE1);
  delete file;

  fs::copy_file(FILE1, FILE2,
                               fs::copy_option::overwrite_if_exists);

  hid_t file1 = H5Fopen(FILE1, H5F_ACC_RDONLY, H5P_DEFAULT);
  hid_t file2 = H5Fopen(FILE2, H5F_ACC_RDONLY, H5P_DEFAULT);
  hid_t group1 = H5Gopen(file1, "/group1", H5P_DEFAULT);
  hid_t group2 = H5Gopen(file2, "/group1", H5P_DEFAULT);

  ObjectId info1(group1);
  ObjectId info2(group2);

  EXPECT_NE(group1, group2);
  EXPECT_NE(info1.file_name(), info2.file_name());
  EXPECT_NE(info1.file_number(), info2.file_number());
  EXPECT_EQ(info1.object_address(), info1.object_address());

  H5Gclose(group1);
  H5Gclose(group2);
  H5Fclose(file1);
  H5Fclose(file2);
  fs::remove(FILE1);
  fs::remove(FILE2);
}

// If 2 files are created with identical structure:
//   only object addresses are equal
TEST(ObjectId,  file_copy2 )
{
  OneFile* file;
  file = new OneFile(FILE1);
  delete file;

  file = new OneFile(FILE2);
  delete file;

  hid_t file1 = H5Fopen(FILE1, H5F_ACC_RDONLY, H5P_DEFAULT);
  hid_t file2 = H5Fopen(FILE2, H5F_ACC_RDONLY, H5P_DEFAULT);
  hid_t group1 = H5Gopen(file1, "/group1", H5P_DEFAULT);
  hid_t group2 = H5Gopen(file2, "/group1", H5P_DEFAULT);

  ObjectId info1(group1);
  ObjectId info2(group2);

  EXPECT_NE(group1, group2);
  EXPECT_NE(info1.file_name(), info2.file_name());
  EXPECT_NE(info1.file_number(), info2.file_number());
  EXPECT_EQ(info1.object_address(), info1.object_address());

  H5Gclose(group1);
  H5Gclose(group2);
  H5Fclose(file1);
  H5Fclose(file2);
  fs::remove(FILE1);
  fs::remove(FILE2);
}

// Symbolic link (in OS) is made FILE2 -> FILE1
//   only file_number and object_address are equal
//   file_name is not equal
TEST(ObjectId,  symlink_id )
{
  OneFile* file = new OneFile(FILE1);
  delete file;

  // Symlink FILE2 -> FILE1
  fs::create_symlink(FILE1, FILE2);

  hid_t file1 = H5Fopen(FILE1, H5F_ACC_RDONLY, H5P_DEFAULT);
  hid_t file2 = H5Fopen(FILE2, H5F_ACC_RDONLY, H5P_DEFAULT);
  hid_t group1 = H5Gopen(file1, "/group1", H5P_DEFAULT);
  hid_t group2 = H5Gopen(file2, "/group1", H5P_DEFAULT);

  ObjectId info1(group1);
  ObjectId info2(group2);

  EXPECT_NE(group1, group2);
  EXPECT_NE(info1.file_name(), info2.file_name());
  EXPECT_EQ(info1.file_number(), info2.file_number());
  EXPECT_EQ(info1.object_address(), info1.object_address());

  EXPECT_EQ(fs::canonical(FILE1),
                    fs::canonical(FILE2));

  H5Gclose(group1);
  H5Gclose(group2);
  H5Fclose(file1);
  H5Fclose(file2);
  fs::remove(FILE1);
  fs::remove(FILE2);
}

// If external link is made file2/group3 -> File1/group1
// All three parameters are equal
TEST(ObjectId,  file_external_group )
{
  OneFile* file = new OneFile(FILE1);
  delete file;

  OneFile* fileb = new OneFile(FILE2);
  delete fileb;

  // Extlink file2/group3 -> file1/group1
  hid_t file2 = H5Fopen(FILE2, H5F_ACC_RDONLY, H5P_DEFAULT);
  H5Lcreate_external(FILE1, "/group1", file2, "/group3", H5P_DEFAULT, H5P_DEFAULT);
  hid_t group23 = H5Gopen(file2, "/group3", H5P_DEFAULT);

  // Original node
  hid_t file1 = H5Fopen(FILE1, H5F_ACC_RDONLY, H5P_DEFAULT);
  hid_t group11 = H5Gopen(file1, "/group1", H5P_DEFAULT);

  ObjectId info11(group11);
  ObjectId info23(group23);

  EXPECT_NE(group11, group23);
  EXPECT_NE(info11.file_name(), info23.file_name());
  EXPECT_EQ(info11.file_number(), info23.file_number());
  EXPECT_EQ(info11.object_address(), info23.object_address());

  H5Gclose(group11);
  H5Gclose(group23);

  fs::remove(FILE1);
  fs::remove(FILE2);
}

// Symbolic link (in OS) is made FILE3 -> FILE1
// External link is made file2/group3 -> File3/group1
//   only file_number and object_address are equal
//   file_name is not equal
TEST(ObjectId,  file_external_symlink )
{
  OneFile* file = new OneFile(FILE1);
  delete file;

  OneFile* fileb = new OneFile(FILE2);
  delete fileb;

  // Symlink FILE3 -> FILE1
  fs::create_symlink(FILE1, FILE3);

  // Extlink file2/group3 -> file3/group1
  hid_t file2 = H5Fopen(FILE2, H5F_ACC_RDONLY, H5P_DEFAULT);
  H5Lcreate_external(FILE3, "/group1", file2, "/group3", H5P_DEFAULT, H5P_DEFAULT);
  hid_t group23 = H5Gopen(file2, "/group3", H5P_DEFAULT);

  // Original node
  hid_t file1 = H5Fopen(FILE1, H5F_ACC_RDONLY, H5P_DEFAULT);
  hid_t group11 = H5Gopen(file1, "/group1", H5P_DEFAULT);

  // Node in symlinked file
  hid_t file3 = H5Fopen(FILE3, H5F_ACC_RDONLY, H5P_DEFAULT);
  hid_t group31 = H5Gopen(file3, "/group1", H5P_DEFAULT);

  ObjectId info11(group11);
  ObjectId info31(group31);
  ObjectId info23(group23);

  EXPECT_NE(group11, group31);
  EXPECT_NE(group11, group23);
  EXPECT_NE(group23, group31);

  EXPECT_NE(info11.file_name(), info31.file_name());
  EXPECT_NE(info31.file_name(), info23.file_name());
  EXPECT_NE(info11.file_name(), info23.file_name());

  EXPECT_EQ(info11.file_number(), info31.file_number());
  EXPECT_EQ(info11.file_number(), info23.file_number());
  EXPECT_EQ(info31.file_number(), info23.file_number());

  EXPECT_EQ(info11.object_address(), info31.object_address());
  EXPECT_EQ(info11.object_address(), info23.object_address());
  EXPECT_EQ(info31.object_address(), info23.object_address());

  H5Gclose(group11);
  H5Gclose(group31);
  H5Gclose(group23);

  fs::remove(FILE1);
  fs::remove(FILE2);
  fs::remove(FILE3);
}

// If the same file is opened repeatedly:
//   file_name and object_address are equal
//   file_number is not equal
TEST(ObjectId,  repeated_open )
{
  OneFile* file = new OneFile(FILE1);
  ObjectId i1(file->file);
  delete file;

  file = new OneFile(FILE1);
  ObjectId i2(file->file);
  delete file;

  EXPECT_EQ(i1.file_name(), i2.file_name());
  EXPECT_NE(i1.file_number(), i2.file_number());
  EXPECT_EQ(i1.object_address(), i2.object_address());
  std::cout << i1 << "   ??   " << i2 << std::endl;
}
<commit_msg>Added BOOST_NO_CXX11_SCOPED_ENUMS <commit_after>//
// (c) Copyright 2017 DESY,ESS
//
// This file is part of h5pp.
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
// License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library; if not, write to the
// Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor
// Boston, MA  02110-1301 USA
// ===========================================================================
//
// Author: Martin Shetty <martin.shetty@esss.se>
// Created on: Sep 13, 2017
//

/*

 Summary of test results

  hid does not uniquely identify an h5 node

  object_address is stable across all scenarios

  file_number:
     not equal if same file closed and reopened
     identifies the file that owns object, not owner of link (in case of ext link)

  file_name:
     not equal if file opened via symbolic link (h5 allows opening same file twice)
     not equal if object opened via external link vs. original node

  Conclusions:
    file_number adequately reflects identity, unless file has been closed and reopened.
    file_name does not adequately reflect identity. Resolving symbolic link would solve
    part of the problem, but would also need to somehow dereference external links to
    identify the name of the object-owning file.

*/

#include <gtest/gtest.h>

#define BOOST_NO_CXX11_SCOPED_ENUMS
#include <boost/filesystem.hpp>
#undef BOOST_NO_CXX11_SCOPED_ENUMS

#include <h5cpp/object_id.hpp>
#include <iostream>

namespace fs = boost::filesystem;

#define FILE1 fs::absolute("file1.h5").string().data()
#define FILE2 fs::absolute("file2.h5").string().data()
#define FILE3 fs::absolute("file3.h5").string().data()

using namespace hdf5;

struct OneFile
{
  OneFile(std::string fname)
  {
    fname_ = fname;
    file = H5Fcreate(fname.data(), H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT);
    group1 = H5Gcreate(file, "/group1",
                       H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
    group2 = H5Gcreate(file, "/group2",
                       H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);

    hsize_t dims[2];
    dims[0] = 3;
    dims[1] = 3;
    hid_t dataspace = H5Screate_simple(2, dims, NULL);

    dset1 = H5Dcreate(group1, "dset1", H5T_NATIVE_DOUBLE, dataspace,
                      H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
  }

  ~OneFile()
  {
    H5Dclose(dset1);
    H5Gclose(group1);
    H5Gclose(group2);
    H5Fclose(file);
  }

  std::string fname_;
  hid_t file, group1, group2, dset1;
};

// For h5 hard links (to group):
//   file_name, file_number and address are all equal
TEST(ObjectId,  hard_group )
{
  OneFile file(FILE1);

  H5Lcreate_hard(file.file, "/group1",
                 file.file, "/group3",
                 H5P_DEFAULT, H5P_DEFAULT);
  hid_t group3 = H5Gopen(file.file, "/group3", H5P_DEFAULT);

  ObjectId info1(file.group1);
  ObjectId info2(group3);

  EXPECT_NE(file.group1, group3);
  EXPECT_EQ(info1.file_name(), info2.file_name());
  EXPECT_EQ(info1.file_number(), info2.file_number());
  EXPECT_EQ(info1.object_address(), info1.object_address());

  H5Gclose(group3);
  fs::remove(FILE1);
}

// For h5 hard links (to dataset):
//   file_name, file_number and address are all equal
TEST(ObjectId,  hard_dset )
{
  OneFile file(FILE1);

  H5Lcreate_hard(file.group1, "dset1",
                 file.group2, "dset2",
                 H5P_DEFAULT, H5P_DEFAULT);
  hid_t dset2 = H5Dopen(file.group2, "dset2", H5P_DEFAULT);

  ObjectId info1(file.dset1);
  ObjectId info2(dset2);

  EXPECT_NE(file.dset1, dset2);
  EXPECT_EQ(info1.file_name(), info2.file_name());
  EXPECT_EQ(info1.file_number(), info2.file_number());
  EXPECT_EQ(info1.object_address(), info1.object_address());

  H5Dclose(dset2);
  fs::remove(FILE1);
}

// For h5 soft links (to group):
//   file_name, file_number and address are all equal
TEST(ObjectId,  soft_group )
{
  OneFile file(FILE1);

  H5Lcreate_soft("/group1", file.file, "/group3",
                 H5P_DEFAULT, H5P_DEFAULT);
  hid_t group3 = H5Gopen(file.file, "/group3", H5P_DEFAULT);

  ObjectId info1(file.group1);
  ObjectId info2(group3);

  EXPECT_NE(file.group1, group3);
  EXPECT_EQ(info1.file_name(), info2.file_name());
  EXPECT_EQ(info1.file_number(), info2.file_number());
  EXPECT_EQ(info1.object_address(), info1.object_address());

  H5Gclose(group3);
  fs::remove(FILE1);
}

// For h5 soft links (to dataset):
//   file_name, file_number and address are all equal
TEST(ObjectId,  soft_dset )
{
  OneFile file(FILE1);

  H5Lcreate_soft("/group1/dset1", file.file, "/group2/dset2",
                 H5P_DEFAULT, H5P_DEFAULT);
  hid_t dset2 = H5Dopen(file.group2, "dset2", H5P_DEFAULT);

  ObjectId info1(file.dset1);
  ObjectId info2(dset2);

  EXPECT_NE(file.dset1, dset2);
  EXPECT_EQ(info1.file_name(), info2.file_name());
  EXPECT_EQ(info1.file_number(), info2.file_number());
  EXPECT_EQ(info1.object_address(), info1.object_address());

  H5Dclose(dset2);
  fs::remove(FILE1);
}

// If file copy is made:
//   only object addresses are equal
TEST(ObjectId,  file_copy )
{
  OneFile* file = new OneFile(FILE1);
  delete file;

  fs::copy_file(FILE1, FILE2,
                               fs::copy_option::overwrite_if_exists);

  hid_t file1 = H5Fopen(FILE1, H5F_ACC_RDONLY, H5P_DEFAULT);
  hid_t file2 = H5Fopen(FILE2, H5F_ACC_RDONLY, H5P_DEFAULT);
  hid_t group1 = H5Gopen(file1, "/group1", H5P_DEFAULT);
  hid_t group2 = H5Gopen(file2, "/group1", H5P_DEFAULT);

  ObjectId info1(group1);
  ObjectId info2(group2);

  EXPECT_NE(group1, group2);
  EXPECT_NE(info1.file_name(), info2.file_name());
  EXPECT_NE(info1.file_number(), info2.file_number());
  EXPECT_EQ(info1.object_address(), info1.object_address());

  H5Gclose(group1);
  H5Gclose(group2);
  H5Fclose(file1);
  H5Fclose(file2);
  fs::remove(FILE1);
  fs::remove(FILE2);
}

// If 2 files are created with identical structure:
//   only object addresses are equal
TEST(ObjectId,  file_copy2 )
{
  OneFile* file;
  file = new OneFile(FILE1);
  delete file;

  file = new OneFile(FILE2);
  delete file;

  hid_t file1 = H5Fopen(FILE1, H5F_ACC_RDONLY, H5P_DEFAULT);
  hid_t file2 = H5Fopen(FILE2, H5F_ACC_RDONLY, H5P_DEFAULT);
  hid_t group1 = H5Gopen(file1, "/group1", H5P_DEFAULT);
  hid_t group2 = H5Gopen(file2, "/group1", H5P_DEFAULT);

  ObjectId info1(group1);
  ObjectId info2(group2);

  EXPECT_NE(group1, group2);
  EXPECT_NE(info1.file_name(), info2.file_name());
  EXPECT_NE(info1.file_number(), info2.file_number());
  EXPECT_EQ(info1.object_address(), info1.object_address());

  H5Gclose(group1);
  H5Gclose(group2);
  H5Fclose(file1);
  H5Fclose(file2);
  fs::remove(FILE1);
  fs::remove(FILE2);
}

// Symbolic link (in OS) is made FILE2 -> FILE1
//   only file_number and object_address are equal
//   file_name is not equal
TEST(ObjectId,  symlink_id )
{
  OneFile* file = new OneFile(FILE1);
  delete file;

  // Symlink FILE2 -> FILE1
  fs::create_symlink(FILE1, FILE2);

  hid_t file1 = H5Fopen(FILE1, H5F_ACC_RDONLY, H5P_DEFAULT);
  hid_t file2 = H5Fopen(FILE2, H5F_ACC_RDONLY, H5P_DEFAULT);
  hid_t group1 = H5Gopen(file1, "/group1", H5P_DEFAULT);
  hid_t group2 = H5Gopen(file2, "/group1", H5P_DEFAULT);

  ObjectId info1(group1);
  ObjectId info2(group2);

  EXPECT_NE(group1, group2);
  EXPECT_NE(info1.file_name(), info2.file_name());
  EXPECT_EQ(info1.file_number(), info2.file_number());
  EXPECT_EQ(info1.object_address(), info1.object_address());

  EXPECT_EQ(fs::canonical(FILE1),
                    fs::canonical(FILE2));

  H5Gclose(group1);
  H5Gclose(group2);
  H5Fclose(file1);
  H5Fclose(file2);
  fs::remove(FILE1);
  fs::remove(FILE2);
}

// If external link is made file2/group3 -> File1/group1
// All three parameters are equal
TEST(ObjectId,  file_external_group )
{
  OneFile* file = new OneFile(FILE1);
  delete file;

  OneFile* fileb = new OneFile(FILE2);
  delete fileb;

  // Extlink file2/group3 -> file1/group1
  hid_t file2 = H5Fopen(FILE2, H5F_ACC_RDONLY, H5P_DEFAULT);
  H5Lcreate_external(FILE1, "/group1", file2, "/group3", H5P_DEFAULT, H5P_DEFAULT);
  hid_t group23 = H5Gopen(file2, "/group3", H5P_DEFAULT);

  // Original node
  hid_t file1 = H5Fopen(FILE1, H5F_ACC_RDONLY, H5P_DEFAULT);
  hid_t group11 = H5Gopen(file1, "/group1", H5P_DEFAULT);

  ObjectId info11(group11);
  ObjectId info23(group23);

  EXPECT_NE(group11, group23);
  EXPECT_NE(info11.file_name(), info23.file_name());
  EXPECT_EQ(info11.file_number(), info23.file_number());
  EXPECT_EQ(info11.object_address(), info23.object_address());

  H5Gclose(group11);
  H5Gclose(group23);

  fs::remove(FILE1);
  fs::remove(FILE2);
}

// Symbolic link (in OS) is made FILE3 -> FILE1
// External link is made file2/group3 -> File3/group1
//   only file_number and object_address are equal
//   file_name is not equal
TEST(ObjectId,  file_external_symlink )
{
  OneFile* file = new OneFile(FILE1);
  delete file;

  OneFile* fileb = new OneFile(FILE2);
  delete fileb;

  // Symlink FILE3 -> FILE1
  fs::create_symlink(FILE1, FILE3);

  // Extlink file2/group3 -> file3/group1
  hid_t file2 = H5Fopen(FILE2, H5F_ACC_RDONLY, H5P_DEFAULT);
  H5Lcreate_external(FILE3, "/group1", file2, "/group3", H5P_DEFAULT, H5P_DEFAULT);
  hid_t group23 = H5Gopen(file2, "/group3", H5P_DEFAULT);

  // Original node
  hid_t file1 = H5Fopen(FILE1, H5F_ACC_RDONLY, H5P_DEFAULT);
  hid_t group11 = H5Gopen(file1, "/group1", H5P_DEFAULT);

  // Node in symlinked file
  hid_t file3 = H5Fopen(FILE3, H5F_ACC_RDONLY, H5P_DEFAULT);
  hid_t group31 = H5Gopen(file3, "/group1", H5P_DEFAULT);

  ObjectId info11(group11);
  ObjectId info31(group31);
  ObjectId info23(group23);

  EXPECT_NE(group11, group31);
  EXPECT_NE(group11, group23);
  EXPECT_NE(group23, group31);

  EXPECT_NE(info11.file_name(), info31.file_name());
  EXPECT_NE(info31.file_name(), info23.file_name());
  EXPECT_NE(info11.file_name(), info23.file_name());

  EXPECT_EQ(info11.file_number(), info31.file_number());
  EXPECT_EQ(info11.file_number(), info23.file_number());
  EXPECT_EQ(info31.file_number(), info23.file_number());

  EXPECT_EQ(info11.object_address(), info31.object_address());
  EXPECT_EQ(info11.object_address(), info23.object_address());
  EXPECT_EQ(info31.object_address(), info23.object_address());

  H5Gclose(group11);
  H5Gclose(group31);
  H5Gclose(group23);

  fs::remove(FILE1);
  fs::remove(FILE2);
  fs::remove(FILE3);
}

// If the same file is opened repeatedly:
//   file_name and object_address are equal
//   file_number is not equal
TEST(ObjectId,  repeated_open )
{
  OneFile* file = new OneFile(FILE1);
  ObjectId i1(file->file);
  delete file;

  file = new OneFile(FILE1);
  ObjectId i2(file->file);
  delete file;

  EXPECT_EQ(i1.file_name(), i2.file_name());
  EXPECT_NE(i1.file_number(), i2.file_number());
  EXPECT_EQ(i1.object_address(), i2.object_address());
  std::cout << i1 << "   ??   " << i2 << std::endl;
}
<|endoftext|>


<commit_before>#include <iostream>

#include "ace/Reactor.h"

#include "log.h"
#include "version.h"

#include "LocationStore.h"
#include "LocationStoreConfigManager.h"

#include "ace/Time_Value.h"
#include "ace/OS_NS_Time.h"
#include "ace/Date_Time.h"

using namespace std;

// Quick way to switch between plugin debugging, where this main() is run
// by hand, and normal operation.
#define DEBUG 0

int main (int argc, char **argv)
{
  LOG_INFO("AMMO Location Store Gateway Plugin (" << VERSION << " built on " << __DATE__ << " at " << __TIME__ << ")");

  LOG_DEBUG ("Creating location store receiver...");

  LocationStoreReceiver *pushReceiver = new LocationStoreReceiver ();

#if DEBUG

  string uri ("http://battalion/company/platoon/squad.mil");
  string mime_t ("text/plain");
  string origin_user ("gi.joe@usarmy.mil");
  std::vector<char> data (128, 'x');

  pushReceiver->onDataReceived (0, uri, mime_t, data, origin_user);

  delete pushReceiver;

#else

  GatewayConnector *gatewayConnector = new GatewayConnector (pushReceiver);

  LocationStoreConfigManager *config =
	LocationStoreConfigManager::getInstance (pushReceiver, gatewayConnector);

  //Get the process-wide ACE_Reactor (the one the acceptor should have registered with)
  ACE_Reactor *reactor = ACE_Reactor::instance ();
  LOG_DEBUG ("Starting event loop...");
  reactor->run_reactor_event_loop ();

#endif

  return 0;
}
<commit_msg>Correct case on ACE OS_NS_time header<commit_after>#include <iostream>

#include "ace/Reactor.h"

#include "log.h"
#include "version.h"

#include "LocationStore.h"
#include "LocationStoreConfigManager.h"

#include "ace/Time_Value.h"
#include "ace/OS_NS_time.h"
#include "ace/Date_Time.h"

using namespace std;

// Quick way to switch between plugin debugging, where this main() is run
// by hand, and normal operation.
#define DEBUG 0

int main (int argc, char **argv)
{
  LOG_INFO("AMMO Location Store Gateway Plugin (" << VERSION << " built on " << __DATE__ << " at " << __TIME__ << ")");

  LOG_DEBUG ("Creating location store receiver...");

  LocationStoreReceiver *pushReceiver = new LocationStoreReceiver ();

#if DEBUG

  string uri ("http://battalion/company/platoon/squad.mil");
  string mime_t ("text/plain");
  string origin_user ("gi.joe@usarmy.mil");
  std::vector<char> data (128, 'x');

  pushReceiver->onDataReceived (0, uri, mime_t, data, origin_user);

  delete pushReceiver;

#else

  GatewayConnector *gatewayConnector = new GatewayConnector (pushReceiver);

  LocationStoreConfigManager *config =
	LocationStoreConfigManager::getInstance (pushReceiver, gatewayConnector);

  //Get the process-wide ACE_Reactor (the one the acceptor should have registered with)
  ACE_Reactor *reactor = ACE_Reactor::instance ();
  LOG_DEBUG ("Starting event loop...");
  reactor->run_reactor_event_loop ();

#endif

  return 0;
}
<|endoftext|>


<commit_before><commit_msg>INTEGRATION: CWS locales30 (1.14.6); FILE MERGED 2008/02/02 19:46:37 erack 1.14.6.4: #i64095# add tet-TL Tetun (Timor-Leste); mapping for tet-ID Tetun (Indonesia) 2008/01/19 15:50:31 erack 1.14.6.3: #i84912# add Bodo (brx-IN), Dogri (dgo-IN), Maithili (mai-IN), Santali (sat-IN) 2007/12/29 17:58:16 erack 1.14.6.2: #i84582# add Guarani_Paraguay (gug_PY) locale data 2007/12/16 20:15:44 erack 1.14.6.1: #i83565# add Sami, Kildin (Russia) to language list box<commit_after><|endoftext|>


<commit_before><commit_msg>EXT-8628 FIXED Crash in LLVOAvatarSelf::getAttachedPointName().<commit_after><|endoftext|>


<commit_before>/*
 *  Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "testing/gtest/include/gtest/gtest.h"
#include "webrtc/modules/audio_coding/codecs/opus/interface/audio_encoder_opus.h"
#include "webrtc/modules/audio_coding/main/acm2/acm_generic_codec.h"

namespace webrtc {
namespace acm2 {

#ifdef WEBRTC_CODEC_OPUS
namespace {
const CodecInst kDefaultOpusCodecInst = {105, "opus", 48000, 960, 1, 32000};
const int kCngPt = 255;  // Not using CNG in this test.
const int kRedPt = 255;  // Not using RED in this test.
}  // namespace

class AcmGenericCodecOpusTest : public ::testing::Test {
 protected:
  AcmGenericCodecOpusTest() {
    acm_codec_params_ = {kDefaultOpusCodecInst, false, false, VADNormal};
  }

  void CreateCodec() {
    codec_wrapper_.reset(new ACMGenericCodec(
        acm_codec_params_.codec_inst, kCngPt, kCngPt, kCngPt, kCngPt,
        false /* enable RED */, kRedPt));
    ASSERT_TRUE(codec_wrapper_);
    ASSERT_EQ(0, codec_wrapper_->InitEncoder(&acm_codec_params_, true));
  }

  const AudioEncoderOpus* GetAudioEncoderOpus() {
    const AudioEncoderOpus* ptr = static_cast<const AudioEncoderOpus*>(
        codec_wrapper_->GetAudioEncoder());
    EXPECT_NE(nullptr, ptr);
    return ptr;
  }
  WebRtcACMCodecParams acm_codec_params_;
  rtc::scoped_ptr<ACMGenericCodec> codec_wrapper_;
};

TEST_F(AcmGenericCodecOpusTest, DefaultApplicationModeMono) {
  acm_codec_params_.codec_inst.channels = 1;
  CreateCodec();
  EXPECT_EQ(AudioEncoderOpus::kVoip, GetAudioEncoderOpus()->application());
}

TEST_F(AcmGenericCodecOpusTest, DefaultApplicationModeStereo) {
  acm_codec_params_.codec_inst.channels = 2;
  CreateCodec();
  EXPECT_EQ(AudioEncoderOpus::kAudio, GetAudioEncoderOpus()->application());
}

TEST_F(AcmGenericCodecOpusTest, ChangeApplicationMode) {
  // Create a stereo encoder.
  acm_codec_params_.codec_inst.channels = 2;
  CreateCodec();
  // Verify that the mode is kAudio.
  const AudioEncoderOpus* opus_ptr = GetAudioEncoderOpus();
  EXPECT_EQ(AudioEncoderOpus::kAudio, opus_ptr->application());

  // Change mode.
  EXPECT_EQ(0, codec_wrapper_->SetOpusApplication(kVoip, false));
  // Verify that the AudioEncoder object was changed.
  EXPECT_NE(opus_ptr, GetAudioEncoderOpus());
  EXPECT_EQ(AudioEncoderOpus::kVoip, GetAudioEncoderOpus()->application());
}

TEST_F(AcmGenericCodecOpusTest, ResetWontChangeApplicationMode) {
  // Create a stereo encoder.
  acm_codec_params_.codec_inst.channels = 2;
  CreateCodec();
  const AudioEncoderOpus* opus_ptr = GetAudioEncoderOpus();
  // Verify that the mode is kAudio.
  EXPECT_EQ(AudioEncoderOpus::kAudio, opus_ptr->application());

  // Trigger a reset.
  ASSERT_EQ(0, codec_wrapper_->InitEncoder(&acm_codec_params_, false));
  // Verify that the AudioEncoder object changed.
  EXPECT_NE(opus_ptr, GetAudioEncoderOpus());
  // Verify that the mode is still kAudio.
  EXPECT_EQ(AudioEncoderOpus::kAudio, GetAudioEncoderOpus()->application());

  // Now change to kVoip.
  EXPECT_EQ(0, codec_wrapper_->SetOpusApplication(kVoip, false));
  EXPECT_EQ(AudioEncoderOpus::kVoip, GetAudioEncoderOpus()->application());

  opus_ptr = GetAudioEncoderOpus();
  // Trigger a reset again.
  ASSERT_EQ(0, codec_wrapper_->InitEncoder(&acm_codec_params_, false));
  // Verify that the AudioEncoder object changed.
  EXPECT_NE(opus_ptr, GetAudioEncoderOpus());
  // Verify that the mode is still kVoip.
  EXPECT_EQ(AudioEncoderOpus::kVoip, GetAudioEncoderOpus()->application());
}

TEST_F(AcmGenericCodecOpusTest, ToggleDtx) {
  // Create a stereo encoder.
  acm_codec_params_.codec_inst.channels = 2;
  CreateCodec();
  // Verify that the mode is still kAudio.
  EXPECT_EQ(AudioEncoderOpus::kAudio, GetAudioEncoderOpus()->application());

  // DTX is not allowed in audio mode, if mode forcing flag is false.
  EXPECT_EQ(-1, codec_wrapper_->EnableOpusDtx(false));
  EXPECT_EQ(AudioEncoderOpus::kAudio, GetAudioEncoderOpus()->application());

  // DTX will be on, if mode forcing flag is true. Then application mode is
  // switched to kVoip.
  EXPECT_EQ(0, codec_wrapper_->EnableOpusDtx(true));
  EXPECT_EQ(AudioEncoderOpus::kVoip, GetAudioEncoderOpus()->application());

  // Audio mode is not allowed when DTX is on, and DTX forcing flag is false.
  EXPECT_EQ(-1, codec_wrapper_->SetOpusApplication(kAudio, false));
  EXPECT_EQ(true, GetAudioEncoderOpus()->dtx_enabled());

  // Audio mode will be set, if DTX forcing flag is true. Then DTX is switched
  // off.
  EXPECT_EQ(0, codec_wrapper_->SetOpusApplication(kAudio, true));
  EXPECT_EQ(false, GetAudioEncoderOpus()->dtx_enabled());

  // Now we set VOIP mode. The DTX forcing flag has no effect.
  EXPECT_EQ(0, codec_wrapper_->SetOpusApplication(kVoip, true));
  EXPECT_EQ(false, GetAudioEncoderOpus()->dtx_enabled());

  // In VOIP mode, we can enable DTX with mode forcing flag being false.
  EXPECT_EQ(0, codec_wrapper_->EnableOpusDtx(false));

  // Turn off DTX.
  EXPECT_EQ(0, codec_wrapper_->DisableOpusDtx());

  // When DTX is off, we can set Audio mode with DTX forcing flag being false.
  EXPECT_EQ(0, codec_wrapper_->SetOpusApplication(kAudio, false));
}
#endif  // WEBRTC_CODEC_OPUS

}  // namespace acm2
}  // namespace webrtc
<commit_msg>Fixing r8698.<commit_after>/*
 *  Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "testing/gtest/include/gtest/gtest.h"
#include "webrtc/modules/audio_coding/codecs/opus/interface/audio_encoder_opus.h"
#include "webrtc/modules/audio_coding/main/acm2/acm_generic_codec.h"

namespace webrtc {
namespace acm2 {

#ifdef WEBRTC_CODEC_OPUS
namespace {
const CodecInst kDefaultOpusCodecInst = {105, "opus", 48000, 960, 1, 32000};
const int kCngPt = 255;  // Not using CNG in this test.
const int kRedPt = 255;  // Not using RED in this test.
}  // namespace

class AcmGenericCodecOpusTest : public ::testing::Test {
 protected:
  AcmGenericCodecOpusTest() {
    acm_codec_params_ = {kDefaultOpusCodecInst, false, false, VADNormal};
  }

  void CreateCodec() {
    codec_wrapper_.reset(new ACMGenericCodec(
        acm_codec_params_.codec_inst, kCngPt, kCngPt, kCngPt, kCngPt,
        false /* enable RED */, kRedPt));
    ASSERT_TRUE(codec_wrapper_);
    ASSERT_EQ(0, codec_wrapper_->InitEncoder(&acm_codec_params_, true));
  }

  const AudioEncoderOpus* GetAudioEncoderOpus() {
    const AudioEncoderOpus* ptr = static_cast<const AudioEncoderOpus*>(
        codec_wrapper_->GetAudioEncoder());
    EXPECT_NE(nullptr, ptr);
    return ptr;
  }
  WebRtcACMCodecParams acm_codec_params_;
  rtc::scoped_ptr<ACMGenericCodec> codec_wrapper_;
};

TEST_F(AcmGenericCodecOpusTest, DefaultApplicationModeMono) {
  acm_codec_params_.codec_inst.channels = 1;
  CreateCodec();
  EXPECT_EQ(AudioEncoderOpus::kVoip, GetAudioEncoderOpus()->application());
}

TEST_F(AcmGenericCodecOpusTest, DefaultApplicationModeStereo) {
  acm_codec_params_.codec_inst.channels = 2;
  CreateCodec();
  EXPECT_EQ(AudioEncoderOpus::kAudio, GetAudioEncoderOpus()->application());
}

TEST_F(AcmGenericCodecOpusTest, ChangeApplicationMode) {
  // Create a stereo encoder.
  acm_codec_params_.codec_inst.channels = 2;
  CreateCodec();
  // Verify that the mode is kAudio.
  const AudioEncoderOpus* opus_ptr = GetAudioEncoderOpus();
  EXPECT_EQ(AudioEncoderOpus::kAudio, opus_ptr->application());

  // Change mode.
  EXPECT_EQ(0, codec_wrapper_->SetOpusApplication(kVoip, false));
  // Verify that the AudioEncoder object was changed.
  EXPECT_NE(opus_ptr, GetAudioEncoderOpus());
  EXPECT_EQ(AudioEncoderOpus::kVoip, GetAudioEncoderOpus()->application());
}

TEST_F(AcmGenericCodecOpusTest, ResetWontChangeApplicationMode) {
  // Create a stereo encoder.
  acm_codec_params_.codec_inst.channels = 2;
  CreateCodec();
  const AudioEncoderOpus* opus_ptr = GetAudioEncoderOpus();
  // Verify that the mode is kAudio.
  EXPECT_EQ(AudioEncoderOpus::kAudio, opus_ptr->application());

  // Trigger a reset.
  ASSERT_EQ(0, codec_wrapper_->InitEncoder(&acm_codec_params_, false));
  // Verify that the AudioEncoder object changed.
  EXPECT_NE(opus_ptr, GetAudioEncoderOpus());
  // Verify that the mode is still kAudio.
  EXPECT_EQ(AudioEncoderOpus::kAudio, GetAudioEncoderOpus()->application());

  // Now change to kVoip.
  EXPECT_EQ(0, codec_wrapper_->SetOpusApplication(kVoip, false));
  EXPECT_EQ(AudioEncoderOpus::kVoip, GetAudioEncoderOpus()->application());

  opus_ptr = GetAudioEncoderOpus();
  // Trigger a reset again.
  ASSERT_EQ(0, codec_wrapper_->InitEncoder(&acm_codec_params_, false));
  // Verify that the AudioEncoder object changed.
  EXPECT_NE(opus_ptr, GetAudioEncoderOpus());
  // Verify that the mode is still kVoip.
  EXPECT_EQ(AudioEncoderOpus::kVoip, GetAudioEncoderOpus()->application());
}

TEST_F(AcmGenericCodecOpusTest, ToggleDtx) {
  // Create a stereo encoder.
  acm_codec_params_.codec_inst.channels = 2;
  CreateCodec();
  // Verify that the mode is still kAudio.
  EXPECT_EQ(AudioEncoderOpus::kAudio, GetAudioEncoderOpus()->application());

  // DTX is not allowed in audio mode, if mode forcing flag is false.
  EXPECT_EQ(-1, codec_wrapper_->EnableOpusDtx(false));
  EXPECT_EQ(AudioEncoderOpus::kAudio, GetAudioEncoderOpus()->application());

  // DTX will be on, if mode forcing flag is true. Then application mode is
  // switched to kVoip.
  EXPECT_EQ(0, codec_wrapper_->EnableOpusDtx(true));
  EXPECT_EQ(AudioEncoderOpus::kVoip, GetAudioEncoderOpus()->application());

  // Audio mode is not allowed when DTX is on, and DTX forcing flag is false.
  EXPECT_EQ(-1, codec_wrapper_->SetOpusApplication(kAudio, false));
  EXPECT_TRUE(GetAudioEncoderOpus()->dtx_enabled());

  // Audio mode will be set, if DTX forcing flag is true. Then DTX is switched
  // off.
  EXPECT_EQ(0, codec_wrapper_->SetOpusApplication(kAudio, true));
  EXPECT_FALSE(GetAudioEncoderOpus()->dtx_enabled());

  // Now we set VOIP mode. The DTX forcing flag has no effect.
  EXPECT_EQ(0, codec_wrapper_->SetOpusApplication(kVoip, true));
  EXPECT_FALSE(GetAudioEncoderOpus()->dtx_enabled());

  // In VOIP mode, we can enable DTX with mode forcing flag being false.
  EXPECT_EQ(0, codec_wrapper_->EnableOpusDtx(false));

  // Turn off DTX.
  EXPECT_EQ(0, codec_wrapper_->DisableOpusDtx());

  // When DTX is off, we can set Audio mode with DTX forcing flag being false.
  EXPECT_EQ(0, codec_wrapper_->SetOpusApplication(kAudio, false));
}
#endif  // WEBRTC_CODEC_OPUS

}  // namespace acm2
}  // namespace webrtc
<|endoftext|>


<commit_before>#include <jni.h>
#include <signal.h>

#include "au/ThreadManager.h"
#include "comscore/common.h"
#include "comscore/SamsonComscoreDictionary.h"
#include "logMsg/logMsg.h"

#include "es_tid_bdp_profile_dictionary_comscore_CSDictionaryJNIInterface.h"

using namespace std;

typedef samson::comscore::uint uint;

class CSDict : public samson::comscore::SamsonComscoreDictionary {
    public:
	vector<string> getAllCategoryNames() {
	    vector<string> names;
	    samson::comscore::Id2Id* category = categories.v;
	    for (size_t i = 0; i < categories.size; i++) {
		names.push_back(getCategoryName(category->first));
		category++;
	    }
	    return names;
	}
};

CSDict dictionary;

// TODO: Bug workaround remove when its fixed in Samson
extern char *progName;

JNIEXPORT jboolean JNICALL Java_es_tid_bdp_profile_dictionary_comscore_CSDictionaryJNIInterface_loadCSDictionary
  (JNIEnv *env, jobject jobj, jstring jdictionary_name) {
    if (progName == NULL) {
        LmStatus status = lmInitX((char *)"ComscoreDict", NULL, NULL, NULL);
        // TODO: Bug workaround remove when its fixed in Samson
        progName = strdup(progName);
        if (status != LmsOk) {
            std::cerr << "LM failed with status " << status << std::endl;
            return false;
        }
    }

    jboolean isCopy;
    const char *dictionary_file_name =
                env->GetStringUTFChars(jdictionary_name, &isCopy);
    dictionary.read(dictionary_file_name);
    env->ReleaseStringUTFChars(jdictionary_name, dictionary_file_name);

    return true;
}

JNIEXPORT jintArray JNICALL Java_es_tid_bdp_profile_dictionary_comscore_CSDictionaryJNIInterface_lookupCategories
  (JNIEnv *env, jobject jobj, jstring jurl) {
    jboolean isCopy;
    const char *url = env->GetStringUTFChars(jurl, &isCopy);
    std::vector<uint> categories =
            dictionary.getCategories(url);
    env->ReleaseStringUTFChars(jurl, url);

    jintArray jcategories = env->NewIntArray(categories.size());
    jint *pjcat= env->GetIntArrayElements(jcategories, &isCopy);
    for (size_t i = 0; i < categories.size(); ++i) {
        pjcat[i] = categories[i];
    }
    env->ReleaseIntArrayElements(jcategories, pjcat, 0);

    return jcategories;
}

JNIEXPORT jstring JNICALL Java_es_tid_bdp_profile_dictionary_comscore_CSDictionaryJNIInterface_getCategoryName
  (JNIEnv *env, jobject jobj, jint jcategory) {
    const char *name = dictionary.getCategoryName(jcategory);
    return env->NewStringUTF(name);
}

JNIEXPORT jobjectArray JNICALL Java_es_tid_bdp_profile_dictionary_comscore_CSDictionaryJNIInterface_getAllCategoryNames
  (JNIEnv *env, jobject jobj) {
    vector<string> names = dictionary.getAllCategoryNames();
    jobjectArray jnames = env->NewObjectArray(names.size(),
	    env->FindClass("java/lang/String"), NULL);
    for (size_t i = 0; i < names.size(); ++i) {
	env->SetObjectArrayElement(jnames, i,
		env->NewStringUTF(names[i].c_str()));
    }
    return jnames;
}
<commit_msg>Style fixes<commit_after>#include <jni.h>
#include <signal.h>

#include "au/ThreadManager.h"
#include "comscore/common.h"
#include "comscore/SamsonComscoreDictionary.h"
#include "logMsg/logMsg.h"

#include "es_tid_bdp_profile_dictionary_comscore_CSDictionaryJNIInterface.h"

using namespace std;

typedef samson::comscore::uint uint;

class CSDict : public samson::comscore::SamsonComscoreDictionary {
    public:
        vector<string> getAllCategoryNames() {
            vector<string> names;
            samson::comscore::Id2Id* category = categories.v;
            for (size_t i = 0; i < categories.size; ++i) {
                names.push_back(getCategoryName(category->first));
                category++;
            }
            return names;
        }
};

CSDict dictionary;

// TODO: Bug workaround remove when its fixed in Samson
extern char *progName;

JNIEXPORT jboolean JNICALL Java_es_tid_bdp_profile_dictionary_comscore_CSDictionaryJNIInterface_loadCSDictionary
  (JNIEnv *env, jobject jobj, jstring jdictionary_name) {
    if (progName == NULL) {
        LmStatus status = lmInitX((char *)"ComscoreDict", NULL, NULL, NULL);
        // TODO: Bug workaround remove when its fixed in Samson
        progName = strdup(progName);
        if (status != LmsOk) {
            std::cerr << "LM failed with status " << status << std::endl;
            return false;
        }
    }

    jboolean isCopy;
    const char *dictionary_file_name =
                env->GetStringUTFChars(jdictionary_name, &isCopy);
    dictionary.read(dictionary_file_name);
    env->ReleaseStringUTFChars(jdictionary_name, dictionary_file_name);

    return true;
}

JNIEXPORT jintArray JNICALL Java_es_tid_bdp_profile_dictionary_comscore_CSDictionaryJNIInterface_lookupCategories
  (JNIEnv *env, jobject jobj, jstring jurl) {
    jboolean isCopy;
    const char *url = env->GetStringUTFChars(jurl, &isCopy);
    std::vector<uint> categories =
            dictionary.getCategories(url);
    env->ReleaseStringUTFChars(jurl, url);

    jintArray jcategories = env->NewIntArray(categories.size());
    jint *pjcat= env->GetIntArrayElements(jcategories, &isCopy);
    for (size_t i = 0; i < categories.size(); ++i) {
        pjcat[i] = categories[i];
    }
    env->ReleaseIntArrayElements(jcategories, pjcat, 0);

    return jcategories;
}

JNIEXPORT jstring JNICALL Java_es_tid_bdp_profile_dictionary_comscore_CSDictionaryJNIInterface_getCategoryName
  (JNIEnv *env, jobject jobj, jint jcategory) {
    const char *name = dictionary.getCategoryName(jcategory);
    return env->NewStringUTF(name);
}

JNIEXPORT jobjectArray JNICALL Java_es_tid_bdp_profile_dictionary_comscore_CSDictionaryJNIInterface_getAllCategoryNames
  (JNIEnv *env, jobject jobj) {
    vector<string> names = dictionary.getAllCategoryNames();
    jobjectArray jnames = env->NewObjectArray(names.size(),
            env->FindClass("java/lang/String"), NULL);
    for (size_t i = 0; i < names.size(); ++i) {
        env->SetObjectArrayElement(jnames, i,
                env->NewStringUTF(names[i].c_str()));
    }
    return jnames;
}
<|endoftext|>


<commit_before>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_FUNCTIONALS_SWIPDG_HH
#define DUNE_GDT_FUNCTIONALS_SWIPDG_HH

#include <dune/stuff/functions/interfaces.hh>
#include <dune/stuff/grid/boundaryinfo.hh>

#include <dune/gdt/localfunctional/codim1.hh>
#include <dune/gdt/localevaluation/swipdg.hh>
#include <dune/gdt/assembler/system.hh>

#include "base.hh"

namespace Dune {
namespace GDT {
namespace Functionals {

template< class DiffusionFactorType, class DirichletType,
          class VectorImp,
          class SpaceImp, class GridViewImp = typename SpaceImp::GridViewType,
          class DiffusionTensorType = void >
class DirichletBoundarySWIPDG;

namespace internal {

template< class DiffusionFactorType, class DirichletType,
          class VectorImp,
          class SpaceImp, class GridViewImp,
          class DiffusionTensorType >
class DirichletBoundarySWIPDGTraits
{
  static_assert(std::is_base_of< Stuff::Tags::LocalizableFunction, DiffusionFactorType >::value,
                "DiffusionFactorType has to be derived from Stuff::LocalizableFunctionInterface!");
  static_assert(std::is_base_of< Stuff::Tags::LocalizableFunction, DiffusionTensorType >::value,
                "DiffusionTensorType has to be derived from Stuff::LocalizableFunctionInterface!");
  static_assert(std::is_base_of< Stuff::Tags::LocalizableFunction, DirichletType >::value,
                "DirichletType has to be derived from Stuff::LocalizableFunctionInterface!");
  static_assert(std::is_base_of< SpaceInterface< typename SpaceImp::Traits,
                                                 typename SpaceImp::dimDomain,
                                                 typename SpaceImp::dimRange,
                                                 typename SpaceImp::dimRangeCols >,
                                 SpaceImp >::value,
                "SpaceImp has to be derived from SpaceInterface!");
public:
  typedef DirichletBoundarySWIPDG
      < DiffusionFactorType, DirichletType, VectorImp, SpaceImp, GridViewImp, DiffusionTensorType > derived_type;
  typedef VectorImp   VectorType;
  typedef SpaceImp    SpaceType;
  typedef GridViewImp GridViewType;
  typedef typename VectorType::ScalarType ScalarType;
}; // class DirichletBoundarySWIPDGTraits

template< class DiffusionType, class DirichletType, class VectorImp, class SpaceImp, class GridViewImp >
class DirichletBoundarySWIPDGTraits< DiffusionType, DirichletType, VectorImp, SpaceImp, GridViewImp, void >
{
  static_assert(std::is_base_of< Stuff::Tags::LocalizableFunction, DiffusionType >::value,
                "DiffusionType has to be derived from Stuff::LocalizableFunctionInterface!");
  static_assert(std::is_base_of< Stuff::Tags::LocalizableFunction, DirichletType >::value,
                "DirichletType has to be derived from Stuff::LocalizableFunctionInterface!");
  static_assert(std::is_base_of< SpaceInterface< typename SpaceImp::Traits,
                                                 typename SpaceImp::dimDomain,
                                                 typename SpaceImp::dimRange,
                                                 typename SpaceImp::dimRangeCols >,
                                 SpaceImp >::value,
                "SpaceImp has to be derived from SpaceInterface!");
public:
  typedef DirichletBoundarySWIPDG< DiffusionType, DirichletType, VectorImp, SpaceImp, GridViewImp, void > derived_type;
  typedef VectorImp   VectorType;
  typedef SpaceImp    SpaceType;
  typedef GridViewImp GridViewType;
  typedef typename VectorType::ScalarType ScalarType;
}; // class DirichletBoundarySWIPDGTraits< ..., void >

} // namespace internal

template< class DiffusionType, class DirichletType, class VectorImp, class SpaceImp, class GridViewImp >
class DirichletBoundarySWIPDG< DiffusionType, DirichletType, VectorImp, SpaceImp, GridViewImp, void >
  : public Functionals::VectorBased< internal::DirichletBoundarySWIPDGTraits< DiffusionType, DirichletType, VectorImp
                                                                            , SpaceImp, GridViewImp, void > >
  , public SystemAssembler< SpaceImp, GridViewImp, SpaceImp >
{
  typedef Functionals::VectorBased< internal::DirichletBoundarySWIPDGTraits< DiffusionType, DirichletType, VectorImp
                                                                           , SpaceImp, GridViewImp, void > >
      FunctionalBaseType;
  typedef SystemAssembler< SpaceImp, GridViewImp, SpaceImp > AssemblerBaseType;

  typedef LocalFunctional::Codim1Integral< LocalEvaluation::SWIPDG::BoundaryRHS< DiffusionType, DirichletType > >
      LocalFunctionalType;
  typedef LocalAssembler::Codim1Vector< LocalFunctionalType > LocalAssemblerType;

  typedef typename VectorImp::ScalarType ScalarType;

public:
  typedef internal::DirichletBoundarySWIPDGTraits
      < DiffusionType, DirichletType, VectorImp, SpaceImp, GridViewImp, void > Traits;

  typedef typename Traits::VectorType VectorType;
  typedef typename Traits::SpaceType  SpaceType;
  typedef typename Traits::GridViewType GridViewType;

  typedef Stuff::Grid::BoundaryInfoInterface< typename GridViewType::Intersection > BoundaryInfoType;

  DirichletBoundarySWIPDG(const DiffusionType& diffusion,
                          const DirichletType& dirichlet,
                          const BoundaryInfoType& boundary_info,
                          VectorType& vector,
                          const SpaceType& space,
                          const GridViewType& grid_view,
                          const ScalarType beta = LocalEvaluation::SWIPDG::internal::default_beta(GridViewType::dimension))
    : FunctionalBaseType(vector, space, grid_view)
    , AssemblerBaseType(space, grid_view)
    , diffusion_(diffusion)
    , dirichlet_(dirichlet)
    , boundary_info_(boundary_info)
    , local_functional_(diffusion_, dirichlet_, beta)
    , local_assembler_(local_functional_)
  {
    setup();
  }

  DirichletBoundarySWIPDG(const DiffusionType& diffusion,
                          const DirichletType& dirichlet,
                          const BoundaryInfoType& boundary_info,
                          VectorType& vector,
                          const SpaceType& space,
                          const ScalarType beta = LocalEvaluation::SWIPDG::internal::default_beta(GridViewType::dimension))
    : FunctionalBaseType(vector, space)
    , AssemblerBaseType(space)
    , diffusion_(diffusion)
    , dirichlet_(dirichlet)
    , boundary_info_(boundary_info)
    , local_functional_(diffusion_, dirichlet_, beta)
    , local_assembler_(local_functional_)
  {
    setup();
  }

  virtual void assemble() override final
  {
    AssemblerBaseType::assemble();
  }

private:
  void setup()
  {
    this->add(local_assembler_, this->vector(), new Stuff::Grid::ApplyOn::DirichletIntersections< GridViewType >(boundary_info_));
  }

  const DiffusionType& diffusion_;
  const DirichletType& dirichlet_;
  const BoundaryInfoType& boundary_info_;
  const LocalFunctionalType local_functional_;
  const LocalAssemblerType local_assembler_;
}; // class DirichletBoundarySWIPDG

} // namespace Functionals
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_FUNCTIONALS_SWIPDG_HH
<commit_msg>[functionals.swipdg] remove unnecessary typenames, refs #14<commit_after>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_FUNCTIONALS_SWIPDG_HH
#define DUNE_GDT_FUNCTIONALS_SWIPDG_HH

#include <dune/stuff/functions/interfaces.hh>
#include <dune/stuff/grid/boundaryinfo.hh>

#include <dune/gdt/localfunctional/codim1.hh>
#include <dune/gdt/localevaluation/swipdg.hh>
#include <dune/gdt/assembler/system.hh>

#include "base.hh"

namespace Dune {
namespace GDT {
namespace Functionals {

template< class DiffusionFactorType, class DirichletType,
          class VectorImp,
          class SpaceImp, class GridViewImp = typename SpaceImp::GridViewType,
          class DiffusionTensorType = void >
class DirichletBoundarySWIPDG;

namespace internal {

template< class DiffusionFactorType, class DirichletType,
          class VectorImp,
          class SpaceImp, class GridViewImp,
          class DiffusionTensorType >
class DirichletBoundarySWIPDGTraits
{
  static_assert(std::is_base_of< Stuff::Tags::LocalizableFunction, DiffusionFactorType >::value,
                "DiffusionFactorType has to be derived from Stuff::LocalizableFunctionInterface!");
  static_assert(std::is_base_of< Stuff::Tags::LocalizableFunction, DiffusionTensorType >::value,
                "DiffusionTensorType has to be derived from Stuff::LocalizableFunctionInterface!");
  static_assert(std::is_base_of< Stuff::Tags::LocalizableFunction, DirichletType >::value,
                "DirichletType has to be derived from Stuff::LocalizableFunctionInterface!");
  static_assert(std::is_base_of< SpaceInterface< typename SpaceImp::Traits,
                                                 SpaceImp::dimDomain,
                                                 SpaceImp::dimRange,
                                                 SpaceImp::dimRangeCols >,
                                 SpaceImp >::value,
                "SpaceImp has to be derived from SpaceInterface!");
public:
  typedef DirichletBoundarySWIPDG
      < DiffusionFactorType, DirichletType, VectorImp, SpaceImp, GridViewImp, DiffusionTensorType > derived_type;
  typedef VectorImp   VectorType;
  typedef SpaceImp    SpaceType;
  typedef GridViewImp GridViewType;
  typedef typename VectorType::ScalarType ScalarType;
}; // class DirichletBoundarySWIPDGTraits

template< class DiffusionType, class DirichletType, class VectorImp, class SpaceImp, class GridViewImp >
class DirichletBoundarySWIPDGTraits< DiffusionType, DirichletType, VectorImp, SpaceImp, GridViewImp, void >
{
  static_assert(std::is_base_of< Stuff::Tags::LocalizableFunction, DiffusionType >::value,
                "DiffusionType has to be derived from Stuff::LocalizableFunctionInterface!");
  static_assert(std::is_base_of< Stuff::Tags::LocalizableFunction, DirichletType >::value,
                "DirichletType has to be derived from Stuff::LocalizableFunctionInterface!");
  static_assert(std::is_base_of< SpaceInterface< typename SpaceImp::Traits,
                                                 SpaceImp::dimDomain,
                                                 SpaceImp::dimRange,
                                                 SpaceImp::dimRangeCols >,
                                 SpaceImp >::value,
                "SpaceImp has to be derived from SpaceInterface!");
public:
  typedef DirichletBoundarySWIPDG< DiffusionType, DirichletType, VectorImp, SpaceImp, GridViewImp, void > derived_type;
  typedef VectorImp   VectorType;
  typedef SpaceImp    SpaceType;
  typedef GridViewImp GridViewType;
  typedef typename VectorType::ScalarType ScalarType;
}; // class DirichletBoundarySWIPDGTraits< ..., void >

} // namespace internal

template< class DiffusionType, class DirichletType, class VectorImp, class SpaceImp, class GridViewImp >
class DirichletBoundarySWIPDG< DiffusionType, DirichletType, VectorImp, SpaceImp, GridViewImp, void >
  : public Functionals::VectorBased< internal::DirichletBoundarySWIPDGTraits< DiffusionType, DirichletType, VectorImp
                                                                            , SpaceImp, GridViewImp, void > >
  , public SystemAssembler< SpaceImp, GridViewImp, SpaceImp >
{
  typedef Functionals::VectorBased< internal::DirichletBoundarySWIPDGTraits< DiffusionType, DirichletType, VectorImp
                                                                           , SpaceImp, GridViewImp, void > >
      FunctionalBaseType;
  typedef SystemAssembler< SpaceImp, GridViewImp, SpaceImp > AssemblerBaseType;

  typedef LocalFunctional::Codim1Integral< LocalEvaluation::SWIPDG::BoundaryRHS< DiffusionType, DirichletType > >
      LocalFunctionalType;
  typedef LocalAssembler::Codim1Vector< LocalFunctionalType > LocalAssemblerType;

  typedef typename VectorImp::ScalarType ScalarType;

public:
  typedef internal::DirichletBoundarySWIPDGTraits
      < DiffusionType, DirichletType, VectorImp, SpaceImp, GridViewImp, void > Traits;

  typedef typename Traits::VectorType VectorType;
  typedef typename Traits::SpaceType  SpaceType;
  typedef typename Traits::GridViewType GridViewType;

  typedef Stuff::Grid::BoundaryInfoInterface< typename GridViewType::Intersection > BoundaryInfoType;

  DirichletBoundarySWIPDG(const DiffusionType& diffusion,
                          const DirichletType& dirichlet,
                          const BoundaryInfoType& boundary_info,
                          VectorType& vector,
                          const SpaceType& space,
                          const GridViewType& grid_view,
                          const ScalarType beta = LocalEvaluation::SWIPDG::internal::default_beta(GridViewType::dimension))
    : FunctionalBaseType(vector, space, grid_view)
    , AssemblerBaseType(space, grid_view)
    , diffusion_(diffusion)
    , dirichlet_(dirichlet)
    , boundary_info_(boundary_info)
    , local_functional_(diffusion_, dirichlet_, beta)
    , local_assembler_(local_functional_)
  {
    setup();
  }

  DirichletBoundarySWIPDG(const DiffusionType& diffusion,
                          const DirichletType& dirichlet,
                          const BoundaryInfoType& boundary_info,
                          VectorType& vector,
                          const SpaceType& space,
                          const ScalarType beta = LocalEvaluation::SWIPDG::internal::default_beta(GridViewType::dimension))
    : FunctionalBaseType(vector, space)
    , AssemblerBaseType(space)
    , diffusion_(diffusion)
    , dirichlet_(dirichlet)
    , boundary_info_(boundary_info)
    , local_functional_(diffusion_, dirichlet_, beta)
    , local_assembler_(local_functional_)
  {
    setup();
  }

  virtual void assemble() override final
  {
    AssemblerBaseType::assemble();
  }

private:
  void setup()
  {
    this->add(local_assembler_, this->vector(), new Stuff::Grid::ApplyOn::DirichletIntersections< GridViewType >(boundary_info_));
  }

  const DiffusionType& diffusion_;
  const DirichletType& dirichlet_;
  const BoundaryInfoType& boundary_info_;
  const LocalFunctionalType local_functional_;
  const LocalAssemblerType local_assembler_;
}; // class DirichletBoundarySWIPDG

} // namespace Functionals
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_FUNCTIONALS_SWIPDG_HH
<|endoftext|>


<commit_before>#include <QtGui/QApplication>

#include <QFileDialog>
#include <QSettings>

#include "mainwindow.h"
#include "glut.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    glutInit(&argc,argv);
    QString filename;
    //inithome directory
    QDir directory=QDir::home();

    //load settings from qsetings ini
    QCoreApplication::setOrganizationName("Klampt");
    QCoreApplication::setOrganizationDomain("klampt.org");
    QCoreApplication::setApplicationName("RobotTest");
    QCoreApplication::setApplicationVersion("0.6");
    QSettings ini(QSettings::IniFormat, QSettings::UserScope,
          QCoreApplication::organizationName(),
          QCoreApplication::applicationName());
    QString dir = QFileInfo(ini.fileName()).absolutePath();
    if(argc==1){
        QFileDialog f;
        QString openDir = ini.value("last_open_scenario_directory",".").toString();
        filename = f.getOpenFileName(0,"Open Robot",openDir,"Robot (*.rob);;Scenario (*.xml);;All Files (*)");
        if(filename.isNull()) return 0;
        ini.setValue("last_open_scenario_directory",QFileInfo(filename).absolutePath());
      }
      MainWindow w;
      if(argc==1){
          string s = filename.toStdString();
          const char* c = s.c_str();
          const char* args[3] = {"RobotTest",c,""};
          w.Initialize(2,(const char**)args);
      }
      else
          w.Initialize(argc,(const char**)argv);
      w.directory=directory;
    w.show();
    return a.exec();
}
<commit_msg>Fixed GLUT include<commit_after>#include <QtGui/QApplication>

#include <QFileDialog>
#include <QSettings>

#include "mainwindow.h"
#include <GL/glut.h>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    glutInit(&argc,argv);
    QString filename;
    //inithome directory
    QDir directory=QDir::home();

    //load settings from qsetings ini
    QCoreApplication::setOrganizationName("Klampt");
    QCoreApplication::setOrganizationDomain("klampt.org");
    QCoreApplication::setApplicationName("RobotTest");
    QCoreApplication::setApplicationVersion("0.6");
    QSettings ini(QSettings::IniFormat, QSettings::UserScope,
          QCoreApplication::organizationName(),
          QCoreApplication::applicationName());
    QString dir = QFileInfo(ini.fileName()).absolutePath();
    if(argc==1){
        QFileDialog f;
        QString openDir = ini.value("last_open_scenario_directory",".").toString();
        filename = f.getOpenFileName(0,"Open Robot",openDir,"Robot (*.rob);;Scenario (*.xml);;All Files (*)");
        if(filename.isNull()) return 0;
        ini.setValue("last_open_scenario_directory",QFileInfo(filename).absolutePath());
      }
      MainWindow w;
      if(argc==1){
          string s = filename.toStdString();
          const char* c = s.c_str();
          const char* args[3] = {"RobotTest",c,""};
          w.Initialize(2,(const char**)args);
      }
      else
          w.Initialize(argc,(const char**)argv);
      w.directory=directory;
    w.show();
    return a.exec();
}
<|endoftext|>


<commit_before>#include "Interface/UserInterface.h"
#include "Interface/SimRobotInterface.h"
#include "SimViewProgram.h"
#include <utils/AnyCollection.h>
#include <GL/glui.h>
#include <fstream>
using namespace Math3D;
using namespace GLDraw;
#ifdef CYGWIN
#undef WIN32
#endif // CYGWIN

enum {
  SIMULATE_BUTTON_ID,
  RESET_BUTTON_ID,
  UI_LISTBOX_ID
};

//planner update time step
double dt=0.01;
//coefficient for the path duration cost in RealTimePlannerBase
double timeCostCoeff = 0.0;

class SafeSerialProgram : public SimViewProgram
{
public:
  WorldPlannerSettings plannerSettings;
  string initialState;

  SimRobotInterface robotInterface;
  vector<SmartPointer<RobotUserInterface> > uis;
  SmartPointer<InputProcessorBase> serialInputProcessor;
  int currentUI,oldUI;

  //GUI state
  GLUI* glui;
  GLUI_Listbox* ui_listbox;

  int drawCommanded,drawDesired,drawPath,drawUI,drawContacts;

  SafeSerialProgram(RobotWorld* world)
    :SimViewProgram(world),/*context(1),*/robotInterface(&sim)
  {
    //setup the settings
    AnyCollection settings;
    ifstream in("safeserialclient.settings",ios::in);
    bool readsettings = false;
    if(in) {
      in>>settings;
      if(in)
	readsettings = true;
      else
	cerr<<"Error reading settings from safeserialclient.settings"<<endl;
    }
    if(!readsettings) {
      fprintf(stderr,"Need safeserialclient.settings file, copy and paste the following lines into the file.\n");
      settings = AnyCollection();
      settings["objective_address"]=string("tcp://localhost:3456");
      settings["objective_filter"]=string("objective");
      settings["time_publish_address"]=string("tcp://*:3457");
      cerr<<settings<<endl;
      exit(-1);
    }
    string objsubaddr = settings["objective_address"];
    string objfilter = settings["objective_filter"];
    string timepubaddr = settings["time_publish_address"];
    SocketObjectiveProcessor* processor = new SocketObjectiveProcessor(objsubaddr.c_str());
    serialInputProcessor = processor;
  }

  virtual bool Initialize()
  {
    drawCommanded = 0;
    drawDesired = 1;
    drawPath = 0;
    drawUI = 1;
    drawContacts = 1;

    plannerSettings.InitializeDefault(*world);
    uis.resize(0);
    uis.push_back(new IKPlannerCommandInterface);
    uis.push_back(new RRTCommandInterface);
#ifndef WIN32
    uis.push_back(new MTIKPlannerCommandInterface);
    uis.push_back(new MTRRTCommandInterface);
#endif //WIN32
    for(size_t i=0;i<uis.size();i++) {
      uis[i]->world = world;
      uis[i]->robotInterface = &robotInterface;
      uis[i]->viewport = &viewport;
      uis[i]->settings = &plannerSettings;
      dynamic_cast<InputProcessingInterface*>((RobotUserInterface*)uis[i])->SetProcessor(serialInputProcessor);
    }
    currentUI = oldUI = 0;

    //activate current UI
    string res=uis[currentUI]->ActivateEvent(true);

    if(!WorldViewProgram::Initialize()) return false;

    glui = GLUI_Master.create_glui_subwindow(main_window,GLUI_SUBWINDOW_RIGHT);
    glui->set_main_gfx_window(main_window);
    glui->add_button("Simulate",SIMULATE_BUTTON_ID,ControlFunc);
    glui->add_button("Reset",RESET_BUTTON_ID,ControlFunc);
    ui_listbox = glui->add_listbox("UI",&currentUI,UI_LISTBOX_ID,ControlFunc);
    for(size_t i=0;i<uis.size();i++) {
      char buf[256];
      strcpy(buf,uis[i]->Description().c_str());
      ui_listbox->add_item(i,buf);
    }

    glui->add_checkbox("Draw commanded",&drawCommanded);
    glui->add_checkbox("Draw desired",&drawDesired);
    glui->add_checkbox("Draw UI",&drawUI);
    glui->add_checkbox("Draw path",&drawPath);
    glui->add_checkbox("Draw contacts",&drawContacts);

    printf("Done initializing...\n");
    return true;
  }

  virtual void RenderWorld()
  {
    Robot* robot=world->robots[0].robot;
    RobotController* rc=sim.robotControllers[0];

    SimViewProgram::RenderWorld();

    //draw current commanded configuration -- transparent
    if(drawCommanded) {
      GLColor newColor(0,1,0,0.5);
      world->robots[0].view.SetColors(newColor);
      Config q;
      sim.controlSimulators[0].GetCommandedConfig(q);
      robot->UpdateConfig(q);
      world->robots[0].view.Draw();
    }

    if(drawDesired) {
      Config curBest;
      robotInterface.GetEndConfig(curBest);
      robot->UpdateConfig(curBest);
      world->robots[0].view.SetColors(GLColor(1,1,0,0.5));
      world->robots[0].view.Draw();

      Real tstart = robotInterface.GetCurTime();
      Real tend = robotInterface.GetEndTime();
      Real dt = 0.05;
      //draw end effector path
      glColor3f(1,1,0);
      glLineWidth(2.0);
      glBegin(GL_LINES);
      int istart=(int)Ceil(tstart/dt);
      int iend=(int)Ceil(tend/dt);
      for(int i=istart;i<iend;i++) {
	Real t1=i*dt;
	Real t2=t2+0.5*dt;
	robotInterface.GetConfig(t1,robot->q);
	robot->UpdateFrames();
	glVertex3v(robot->links.back().T_World.t);
	robotInterface.GetConfig(t2,robot->q);
	robot->UpdateFrames();
	glVertex3v(robot->links.back().T_World.t);
      }
      glEnd();
    }
    if(drawUI) {
      cout<<"DrawUI"<<endl;
      uis[currentUI]->DrawGL();
    }

    //draw desired path
    if(drawPath) {
      RobotController* rc=sim.robotControllers[0];
      for(size_t i=0;i<robot->drivers.size();i++) {
	robot->SetDriverValue(i,rc->command->actuators[i].qdes);
      }
      robot->UpdateFrames();
      world->robots[0].view.SetColors(GLColor(0,1,0,0.5));
      world->robots[0].view.Draw();
    }

    //draw collision feedback
    if(drawContacts) {
      DrawContacts();
    }
  }

  virtual void RenderScreen()
  {
    void* fontface = GLUT_BITMAP_TIMES_ROMAN_24;
    const int fontheight = 24;
    const int lineSpacing = 36;
    const int margin = 5;
    int x,y;

    glDisable(GL_LIGHTING);
    glDisable(GL_DEPTH_TEST);

    x = 20;
    y = 40;

    if(!simulate) {
      glColor3f(1,1,0);
      glRasterPos2i(x,y);
      glutBitmapString(fontface,"Select a desired UI mode");
      y += lineSpacing;
      glRasterPos2i(x,y);
      glutBitmapString(fontface,"Press Simulate when you are ready");
    }
    else {
      glColor3f(1,1,1);
      glRasterPos2i(x,y);
      glutBitmapString(fontface,uis[currentUI]->Instructions().c_str());
      y += lineSpacing;
    }

    glEnable(GL_DEPTH_TEST);
  }

  virtual void Handle_Control(int id)
  {
    switch(id) {
    case SIMULATE_BUTTON_ID:
      if(simulate) {
	simulate=0;
	SleepIdleCallback();
      }
      else {
	simulate=1;
	SleepIdleCallback(0);
      }
      break;
    case RESET_BUTTON_ID:
      simulate = 0;
      ResetSim();
      break;
    case UI_LISTBOX_ID:
      {
	string res=uis[oldUI]->ActivateEvent(false);
	res=uis[currentUI]->ActivateEvent(true);
	oldUI=currentUI;
      }
      break;
    }
  }

  void BeginDrag(int x,int y,int button,int modifiers)
  {
    if(button == GLUT_RIGHT_BUTTON) {
    }
    else {
      WorldViewProgram::BeginDrag(x,y,button,modifiers);
    }
  }

  void EndDrag(int x,int y,int button,int modifiers)
  {
    if(button == GLUT_RIGHT_BUTTON) {
      string res=uis[currentUI]->MouseInputEvent(0,0,true);
    }
  }

  virtual void DoFreeDrag(int dx,int dy,int button)
  {
    if(button == GLUT_LEFT_BUTTON)  DragRotate(dx,dy);
    else if(button == GLUT_RIGHT_BUTTON) {
      string res=uis[currentUI]->MouseInputEvent(dx,dy,true);
    }
  }

  virtual void DoCtrlDrag(int dx,int dy,int button)
  {
    if(button == GLUT_LEFT_BUTTON)  DragPan(dx,dy);
  }

  virtual void DoAltDrag(int dx,int dy,int button)
  {
    if(button == GLUT_LEFT_BUTTON)  DragZoom(dx,dy);
  }

  virtual void DoShiftDrag(int dx,int dy,int button)
  {
    if(button == GLUT_LEFT_BUTTON) { camera.dist *= (1 + 0.01*Real(dy)); }
  }

  virtual void Handle_Motion(int x,int y)
  {
    string res=uis[currentUI]->MouseInputEvent(x,y,false);
    Refresh();
  }

  virtual void Handle_Keypress(unsigned char key,int x,int y)
  {
    string res=uis[currentUI]->KeypressEvent(key,x,y);
    Refresh();
  }

  virtual void Handle_Idle() {
    if(simulate) {
      Timer timer;
      string res=uis[currentUI]->UpdateEvent();

      sim.Advance(dt);
      Refresh();

      SleepIdleCallback(int(Max(0.0,dt-timer.ElapsedTime())*1000.0));
    }
    WorldViewProgram::Handle_Idle();
  }
};

int main(int argc, const char** argv)
{
  if(argc < 2) {
    printf("USAGE: SafeSerialClient XML_file\n");
    return 0;
  }
  RobotWorld world;
  world.lights.resize(1);
  world.lights[0].setColor(GLColor(1,1,1));
  world.lights[0].setDirectionalLight(Vector3(0.2,-0.4,1));
  world.lights[0].setColor(GLColor(1,1,1));

  SafeSerialProgram program(&world);
  program.LoadAndInitSim(argc,argv);
  return program.Run();
}
<commit_msg>SafeSerialClient now draws the path<commit_after>#include "Interface/UserInterface.h"
#include "Interface/SimRobotInterface.h"
#include "SimViewProgram.h"
#include <utils/AnyCollection.h>
#include <GL/glui.h>
#include <fstream>
using namespace Math3D;
using namespace GLDraw;
#ifdef CYGWIN
#undef WIN32
#endif // CYGWIN

enum {
  SIMULATE_BUTTON_ID,
  RESET_BUTTON_ID,
  UI_LISTBOX_ID
};

//planner update time step
double dt=0.01;
//coefficient for the path duration cost in RealTimePlannerBase
double timeCostCoeff = 0.0;

class SafeSerialProgram : public SimViewProgram
{
public:
  WorldPlannerSettings plannerSettings;
  string initialState;

  SimRobotInterface robotInterface;
  vector<SmartPointer<RobotUserInterface> > uis;
  SmartPointer<InputProcessorBase> serialInputProcessor;
  int currentUI,oldUI;

  //GUI state
  GLUI* glui;
  GLUI_Listbox* ui_listbox;

  int drawCommanded,drawDesired,drawPath,drawUI,drawContacts;

  SafeSerialProgram(RobotWorld* world)
    :SimViewProgram(world),/*context(1),*/robotInterface(&sim)
  {
    //setup the settings
    AnyCollection settings;
    ifstream in("safeserialclient.settings",ios::in);
    bool readsettings = false;
    if(in) {
      in>>settings;
      if(in)
	readsettings = true;
      else
	cerr<<"Error reading settings from safeserialclient.settings"<<endl;
    }
    if(!readsettings) {
      fprintf(stderr,"Need safeserialclient.settings file, copy and paste the following lines into the file.\n");
      settings = AnyCollection();
      settings["objective_address"]=string("tcp://localhost:3456");
      settings["objective_filter"]=string("objective");
      settings["time_publish_address"]=string("tcp://*:3457");
      cerr<<settings<<endl;
      exit(-1);
    }
    string objsubaddr = settings["objective_address"];
    string objfilter = settings["objective_filter"];
    string timepubaddr = settings["time_publish_address"];
    SocketObjectiveProcessor* processor = new SocketObjectiveProcessor(objsubaddr.c_str());
    serialInputProcessor = processor;
  }

  virtual bool Initialize()
  {
    drawCommanded = 0;
    drawDesired = 1;
    drawPath = 0;
    drawUI = 1;
    drawContacts = 1;

    plannerSettings.InitializeDefault(*world);
    uis.resize(0);
    uis.push_back(new IKPlannerCommandInterface);
    uis.push_back(new RRTCommandInterface);
#ifndef WIN32
    uis.push_back(new MTIKPlannerCommandInterface);
    uis.push_back(new MTRRTCommandInterface);
#endif //WIN32
    for(size_t i=0;i<uis.size();i++) {
      uis[i]->world = world;
      uis[i]->robotInterface = &robotInterface;
      uis[i]->viewport = &viewport;
      uis[i]->settings = &plannerSettings;
      dynamic_cast<InputProcessingInterface*>((RobotUserInterface*)uis[i])->SetProcessor(serialInputProcessor);
    }
    currentUI = oldUI = 0;

    //activate current UI
    string res=uis[currentUI]->ActivateEvent(true);

    if(!WorldViewProgram::Initialize()) return false;

    glui = GLUI_Master.create_glui_subwindow(main_window,GLUI_SUBWINDOW_RIGHT);
    glui->set_main_gfx_window(main_window);
    glui->add_button("Simulate",SIMULATE_BUTTON_ID,ControlFunc);
    glui->add_button("Reset",RESET_BUTTON_ID,ControlFunc);
    ui_listbox = glui->add_listbox("UI",&currentUI,UI_LISTBOX_ID,ControlFunc);
    for(size_t i=0;i<uis.size();i++) {
      char buf[256];
      strcpy(buf,uis[i]->Description().c_str());
      ui_listbox->add_item(i,buf);
    }

    glui->add_checkbox("Draw commanded",&drawCommanded);
    glui->add_checkbox("Draw desired",&drawDesired);
    glui->add_checkbox("Draw UI",&drawUI);
    glui->add_checkbox("Draw path",&drawPath);
    glui->add_checkbox("Draw contacts",&drawContacts);

    printf("Done initializing...\n");
    return true;
  }

  virtual void RenderWorld()
  {
    Robot* robot=world->robots[0].robot;
    RobotController* rc=sim.robotControllers[0];

    SimViewProgram::RenderWorld();

    //draw current commanded configuration -- transparent
    if(drawCommanded) {
      GLColor newColor(0,1,0,0.5);
      world->robots[0].view.SetColors(newColor);
      Config q;
      sim.controlSimulators[0].GetCommandedConfig(q);
      robot->UpdateConfig(q);
      world->robots[0].view.Draw();
    }

    if(drawDesired) {
      Config curBest;
      robotInterface.GetEndConfig(curBest);
      robot->UpdateConfig(curBest);
      world->robots[0].view.SetColors(GLColor(1,1,0,0.5));
      world->robots[0].view.Draw();

      Real tstart = robotInterface.GetCurTime();
      Real tend = robotInterface.GetEndTime();
      Real dt = 0.05;
      //draw end effector path
      glColor3f(1,1,0);
      glLineWidth(2.0);
      glBegin(GL_LINES);
      int istart=(int)Ceil(tstart/dt);
      int iend=(int)Ceil(tend/dt);
      for(int i=istart;i<iend;i++) {
	Real t1=i*dt;
	Real t2=t2+0.5*dt;
	robotInterface.GetConfig(t1,robot->q);
	robot->UpdateFrames();
	glVertex3v(robot->links.back().T_World.t);
	robotInterface.GetConfig(t2,robot->q);
	robot->UpdateFrames();
	glVertex3v(robot->links.back().T_World.t);
      }
      glEnd();
    }
    if(drawUI) {
      cout<<"DrawUI"<<endl;
      uis[currentUI]->DrawGL();
    }

    //draw desired path
    if(drawPath) {
      Real tstart = robotInterface.GetCurTime();
      Real tend = robotInterface.GetEndTime();
      Real dt = 0.05;
      //draw end effector path
      glColor3f(1,1,0);
      glLineWidth(2.0);
      glBegin(GL_LINES);
      int istart=(int)Ceil(tstart/dt);
      int iend=(int)Ceil(tend/dt);
      for(int i=istart;i<iend;i++) {
	Real t1=i*dt;
	Real t2=t1+0.5*dt;
	robotInterface.GetConfig(t1,robot->q);
	robot->UpdateFrames();
	glVertex3v(robot->links.back().T_World.t);
	robotInterface.GetConfig(t2,robot->q);
	robot->UpdateFrames();
	glVertex3v(robot->links.back().T_World.t);
      }
      glEnd();
    }

    //draw collision feedback
    if(drawContacts) {
      DrawContacts();
    }
  }

  virtual void RenderScreen()
  {
    void* fontface = GLUT_BITMAP_TIMES_ROMAN_24;
    const int fontheight = 24;
    const int lineSpacing = 36;
    const int margin = 5;
    int x,y;

    glDisable(GL_LIGHTING);
    glDisable(GL_DEPTH_TEST);

    x = 20;
    y = 40;

    if(!simulate) {
      glColor3f(1,1,0);
      glRasterPos2i(x,y);
      glutBitmapString(fontface,"Select a desired UI mode");
      y += lineSpacing;
      glRasterPos2i(x,y);
      glutBitmapString(fontface,"Press Simulate when you are ready");
    }
    else {
      glColor3f(1,1,1);
      glRasterPos2i(x,y);
      glutBitmapString(fontface,uis[currentUI]->Instructions().c_str());
      y += lineSpacing;
    }

    glEnable(GL_DEPTH_TEST);
  }

  virtual void Handle_Control(int id)
  {
    switch(id) {
    case SIMULATE_BUTTON_ID:
      if(simulate) {
	simulate=0;
	SleepIdleCallback();
      }
      else {
	simulate=1;
	SleepIdleCallback(0);
      }
      break;
    case RESET_BUTTON_ID:
      simulate = 0;
      ResetSim();
      break;
    case UI_LISTBOX_ID:
      {
	string res=uis[oldUI]->ActivateEvent(false);
	res=uis[currentUI]->ActivateEvent(true);
	oldUI=currentUI;
      }
      break;
    }
  }

  void BeginDrag(int x,int y,int button,int modifiers)
  {
    if(button == GLUT_RIGHT_BUTTON) {
    }
    else {
      WorldViewProgram::BeginDrag(x,y,button,modifiers);
    }
  }

  void EndDrag(int x,int y,int button,int modifiers)
  {
    if(button == GLUT_RIGHT_BUTTON) {
      string res=uis[currentUI]->MouseInputEvent(0,0,true);
    }
  }

  virtual void DoFreeDrag(int dx,int dy,int button)
  {
    if(button == GLUT_LEFT_BUTTON)  DragRotate(dx,dy);
    else if(button == GLUT_RIGHT_BUTTON) {
      string res=uis[currentUI]->MouseInputEvent(dx,dy,true);
    }
  }

  virtual void DoCtrlDrag(int dx,int dy,int button)
  {
    if(button == GLUT_LEFT_BUTTON)  DragPan(dx,dy);
  }

  virtual void DoAltDrag(int dx,int dy,int button)
  {
    if(button == GLUT_LEFT_BUTTON)  DragZoom(dx,dy);
  }

  virtual void DoShiftDrag(int dx,int dy,int button)
  {
    if(button == GLUT_LEFT_BUTTON) { camera.dist *= (1 + 0.01*Real(dy)); }
  }

  virtual void Handle_Motion(int x,int y)
  {
    string res=uis[currentUI]->MouseInputEvent(x,y,false);
    Refresh();
  }

  virtual void Handle_Keypress(unsigned char key,int x,int y)
  {
    string res=uis[currentUI]->KeypressEvent(key,x,y);
    Refresh();
  }

  virtual void Handle_Idle() {
    if(simulate) {
      Timer timer;
      string res=uis[currentUI]->UpdateEvent();

      sim.Advance(dt);
      Refresh();

      SleepIdleCallback(int(Max(0.0,dt-timer.ElapsedTime())*1000.0));
    }
    WorldViewProgram::Handle_Idle();
  }
};

int main(int argc, const char** argv)
{
  if(argc < 2) {
    printf("USAGE: SafeSerialClient XML_file\n");
    return 0;
  }
  RobotWorld world;
  world.lights.resize(1);
  world.lights[0].setColor(GLColor(1,1,1));
  world.lights[0].setDirectionalLight(Vector3(0.2,-0.4,1));
  world.lights[0].setColor(GLColor(1,1,1));

  SafeSerialProgram program(&world);
  program.LoadAndInitSim(argc,argv);
  return program.Run();
}
<|endoftext|>


<commit_before>/*
 * libjingle
 * Copyright 2004--2010, Google Inc.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *  1. Redistributions of source code must retain the above copyright notice,
 *     this list of conditions and the following disclaimer.
 *  2. Redistributions in binary form must reproduce the above copyright notice,
 *     this list of conditions and the following disclaimer in the documentation
 *     and/or other materials provided with the distribution.
 *  3. The name of the author may not be used to endorse or promote products
 *     derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "webrtc/modules/audio_device/linux/latebindingsymboltable_linux.h"

#ifdef WEBRTC_LINUX
#include <dlfcn.h>
#endif

// TODO(grunell): Either put inside webrtc namespace or use webrtc:: instead.
using namespace webrtc;

namespace webrtc_adm_linux {

inline static const char *GetDllError() {
#ifdef WEBRTC_LINUX
  char *err = dlerror();
  if (err) {
    return err;
  } else {
    return "No error";
  }
#else
#error Not implemented
#endif
}

DllHandle InternalLoadDll(const char dll_name[]) {
#ifdef WEBRTC_LINUX
  DllHandle handle = dlopen(dll_name, RTLD_NOW);
#else
#error Not implemented
#endif
  if (handle == kInvalidDllHandle) {
    WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, -1,
               "Can't load %s : %s", dll_name, GetDllError());
  }
  return handle;
}

void InternalUnloadDll(DllHandle handle) {
#ifdef WEBRTC_LINUX
  if (dlclose(handle) != 0) {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, -1,
               "%s", GetDllError());
  }
#else
#error Not implemented
#endif
}

static bool LoadSymbol(DllHandle handle,
                       const char *symbol_name,
                       void **symbol) {
#ifdef WEBRTC_LINUX
  *symbol = dlsym(handle, symbol_name);
  char *err = dlerror();
  if (err) {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, -1,
               "Error loading symbol %s : %d", symbol_name, err);
    return false;
  } else if (!*symbol) {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, -1,
               "Symbol %s is NULL", symbol_name);
    return false;
  }
  return true;
#else
#error Not implemented
#endif
}

// This routine MUST assign SOME value for every symbol, even if that value is
// NULL, or else some symbols may be left with uninitialized data that the
// caller may later interpret as a valid address.
bool InternalLoadSymbols(DllHandle handle,
                         int num_symbols,
                         const char *const symbol_names[],
                         void *symbols[]) {
#ifdef WEBRTC_LINUX
  // Clear any old errors.
  dlerror();
#endif
  for (int i = 0; i < num_symbols; ++i) {
    if (!LoadSymbol(handle, symbol_names[i], &symbols[i])) {
      return false;
    }
  }
  return true;
}

}  // namespace webrtc_adm_linux
<commit_msg>Skip dlclose() on AddressSanitizer.<commit_after>/*
 * libjingle
 * Copyright 2004--2010, Google Inc.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *  1. Redistributions of source code must retain the above copyright notice,
 *     this list of conditions and the following disclaimer.
 *  2. Redistributions in binary form must reproduce the above copyright notice,
 *     this list of conditions and the following disclaimer in the documentation
 *     and/or other materials provided with the distribution.
 *  3. The name of the author may not be used to endorse or promote products
 *     derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "webrtc/modules/audio_device/linux/latebindingsymboltable_linux.h"

#ifdef WEBRTC_LINUX
#include <dlfcn.h>
#endif

// TODO(grunell): Either put inside webrtc namespace or use webrtc:: instead.
using namespace webrtc;

namespace webrtc_adm_linux {

inline static const char *GetDllError() {
#ifdef WEBRTC_LINUX
  char *err = dlerror();
  if (err) {
    return err;
  } else {
    return "No error";
  }
#else
#error Not implemented
#endif
}

DllHandle InternalLoadDll(const char dll_name[]) {
#ifdef WEBRTC_LINUX
  DllHandle handle = dlopen(dll_name, RTLD_NOW);
#else
#error Not implemented
#endif
  if (handle == kInvalidDllHandle) {
    WEBRTC_TRACE(kTraceWarning, kTraceAudioDevice, -1,
               "Can't load %s : %s", dll_name, GetDllError());
  }
  return handle;
}

void InternalUnloadDll(DllHandle handle) {
#ifdef WEBRTC_LINUX
// TODO(pbos): Remove this dlclose() exclusion when leaks and suppressions from
// here are gone (or AddressSanitizer can display them properly).
//
// Skip dlclose() on AddressSanitizer as leaks including this module in the
// stack trace gets displayed as <unknown module> instead of the actual library
// -> it can not be suppressed.
// https://code.google.com/p/address-sanitizer/issues/detail?id=89
#if !defined(ADDRESS_SANITIZER)
  if (dlclose(handle) != 0) {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, -1,
               "%s", GetDllError());
  }
#endif  // !defined(ADDRESS_SANITIZER)
#else
#error Not implemented
#endif
}

static bool LoadSymbol(DllHandle handle,
                       const char *symbol_name,
                       void **symbol) {
#ifdef WEBRTC_LINUX
  *symbol = dlsym(handle, symbol_name);
  char *err = dlerror();
  if (err) {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, -1,
               "Error loading symbol %s : %d", symbol_name, err);
    return false;
  } else if (!*symbol) {
    WEBRTC_TRACE(kTraceError, kTraceAudioDevice, -1,
               "Symbol %s is NULL", symbol_name);
    return false;
  }
  return true;
#else
#error Not implemented
#endif
}

// This routine MUST assign SOME value for every symbol, even if that value is
// NULL, or else some symbols may be left with uninitialized data that the
// caller may later interpret as a valid address.
bool InternalLoadSymbols(DllHandle handle,
                         int num_symbols,
                         const char *const symbol_names[],
                         void *symbols[]) {
#ifdef WEBRTC_LINUX
  // Clear any old errors.
  dlerror();
#endif
  for (int i = 0; i < num_symbols; ++i) {
    if (!LoadSymbol(handle, symbol_names[i], &symbols[i])) {
      return false;
    }
  }
  return true;
}

}  // namespace webrtc_adm_linux
<|endoftext|>


<commit_before>//===========================================
//  Lumina-DE source code
//  Copyright (c) 2014, Ken Moore
//  Available under the 3-clause BSD license
//  See the LICENSE file for full details
//===========================================
#include "LTaskManagerPlugin.h"
#include "../../LSession.h"

LTaskManagerPlugin::LTaskManagerPlugin(QWidget *parent, QString id, bool horizontal) : LPPlugin(parent, id, horizontal){
  timer = new QTimer(this);
	timer->setSingleShot(true);
	timer->setInterval(10); // 1/100 second
	connect(timer, SIGNAL(timeout()), this, SLOT(UpdateButtons()) );
  usegroups = true; //backwards-compatible default value
  if(id.contains("-nogroups")){ usegroups = false; }
  connect(LSession::handle(), SIGNAL(WindowListEvent()), this, SLOT(checkWindows()) );
  connect(LSession::handle(), SIGNAL(WindowListEvent(WId)), this, SLOT(UpdateButton(WId)) );
  this->layout()->setContentsMargins(0,0,0,0);
  QTimer::singleShot(0,this, SLOT(UpdateButtons()) ); //perform an initial sync
  //QTimer::singleShot(100,this, SLOT(OrientationChange()) ); //perform an initial sync
}

LTaskManagerPlugin::~LTaskManagerPlugin(){

}

//==============
//    PRIVATE SLOTS
//==============
void LTaskManagerPlugin::UpdateButtons(){
  updating = QDateTime::currentDateTime(); //global time stamp
  QDateTime ctime = updating; //current thread time stamp

  //Get the current window list
  QList<WId> winlist = LSession::handle()->XCB->WindowList();
  //Do not change the status of the previously active window if it just changed to a non-visible window
  //WId activeWin = LSession::handle()->XCB->ActiveWindow();
  //bool skipActive = !winlist.contains(activeWin);
  //qDebug() << "Update Buttons:" << winlist;
  if(updating > ctime){ return; } //another thread kicked off already - stop this one
  //Now go through all the current buttons first
  for(int i=0; i<BUTTONS.length(); i++){
    //Get the windows managed in this button
    QList<WId> WI = BUTTONS[i]->windows();
    bool updated=false;
    if(updating > ctime){ return; } //another thread kicked off already - stop this one
    //Loop over all the windows for this button
    for(int w=0; w<WI.length(); w++){
      if(updating > ctime){ return; } //another thread kicked off already - stop this one
      if( winlist.contains( WI[w] ) ){
        //Still current window - update it later
	winlist.removeAll(WI[w] ); //remove this window from the list since it is done
      }else{
	//Window was closed - remove it
	if(WI.length()==1){
	  //Remove the entire button
	  //qDebug() << "Window Closed: Remove Button" ;
	  this->layout()->takeAt(i); //remove from the layout
	  BUTTONS.takeAt(i)->deleteLater();
	  i--;
	  updated = true; //prevent updating a removed button
	  break; //break out of the button->window loop
	}else{
	  //qDebug() << "Window Closed: Remove from button:" << WI[w].windowID() << "Button:" << w;
	  BUTTONS[i]->rmWindow(WI[w]); // one of the multiple windows for the button
	  WI.removeAt(w); //remove this window from the list
	  w--;
	}
	updated=true; //button already changed
      }
      if(updating > ctime){ return; } //another thread kicked off already - stop this one
    }
    if(!updated){
      //qDebug() << "Update Button:" << i;
      if(updating > ctime){ return; } //another thread kicked off already - stop this one
      //if(!skipActive || !BUTTONS[i]->isActive()){
        QTimer::singleShot(1,BUTTONS[i], SLOT(UpdateButton()) ); //keep moving on
      //}
    }
  }
  //Now go through the remaining windows
  for(int i=0; i<winlist.length(); i++){
    //New windows, create buttons for each (add grouping later)
    if(updating > ctime){ return; } //another thread kicked off already - stop this one
    //Check for a button that this can just be added to
    QString ctxt = LSession::handle()->XCB->WindowClass(winlist[i]);
    bool found = false;
    for(int b=0; b<BUTTONS.length(); b++){
      if(updating > ctime){ return; } //another thread kicked off already - stop this one
      if(BUTTONS[b]->classname()== ctxt && usegroups){
	//This adds a window to an existing group
        found = true;
	//qDebug() << "Add Window to Button:" << b;
	BUTTONS[b]->addWindow(winlist[i]);
	break;
      }
    }
    if(!found){
      if(updating > ctime){ return; } //another thread kicked off already - stop this one
      //No group, create a new button
      //qDebug() << "New Button";
      LTaskButton *but = new LTaskButton(this, usegroups);
        but->addWindow( winlist[i] );
	if(this->layout()->direction()==QBoxLayout::LeftToRight){
	    but->setIconSize(QSize(this->height(), this->height()));
	}else{
	    but->setIconSize(QSize(this->width(), this->width()));
	}
      this->layout()->addWidget(but);
      connect(but, SIGNAL(MenuClosed()), this, SIGNAL(MenuClosed()));
      BUTTONS << but;
    }
  }
}

void LTaskManagerPlugin::UpdateButton(WId win){
  for(int i=0; i<BUTTONS.length(); i++){
    if(BUTTONS[i]->windows().contains(win)){
      qDebug() << "Update Task Manager Button (single window ping)";
      QTimer::singleShot(0,BUTTONS[i], SLOT(UpdateButton()) );
      break;
    }
  }
}

void LTaskManagerPlugin::checkWindows(){
  timer->start();
}
<commit_msg>Skip windows with SKIP_TASKBAR state in task manager<commit_after>//===========================================
//  Lumina-DE source code
//  Copyright (c) 2014, Ken Moore
//  Available under the 3-clause BSD license
//  See the LICENSE file for full details
//===========================================
#include "LTaskManagerPlugin.h"
#include "../../LSession.h"

LTaskManagerPlugin::LTaskManagerPlugin(QWidget *parent, QString id, bool horizontal) : LPPlugin(parent, id, horizontal){
  timer = new QTimer(this);
	timer->setSingleShot(true);
	timer->setInterval(10); // 1/100 second
	connect(timer, SIGNAL(timeout()), this, SLOT(UpdateButtons()) );
  usegroups = true; //backwards-compatible default value
  if(id.contains("-nogroups")){ usegroups = false; }
  connect(LSession::handle(), SIGNAL(WindowListEvent()), this, SLOT(checkWindows()) );
  connect(LSession::handle(), SIGNAL(WindowListEvent(WId)), this, SLOT(UpdateButton(WId)) );
  this->layout()->setContentsMargins(0,0,0,0);
  QTimer::singleShot(0,this, SLOT(UpdateButtons()) ); //perform an initial sync
  //QTimer::singleShot(100,this, SLOT(OrientationChange()) ); //perform an initial sync
}

LTaskManagerPlugin::~LTaskManagerPlugin(){

}

//==============
//    PRIVATE SLOTS
//==============
void LTaskManagerPlugin::UpdateButtons(){
  updating = QDateTime::currentDateTime(); //global time stamp
  QDateTime ctime = updating; //current thread time stamp

  //Get the current window list
  QList<WId> winlist = LSession::handle()->XCB->WindowList();
  // Ignore the windows which don't want to be listed
  for (int i = 0; i < winlist.length(); i++) {
    QList<LXCB::WINDOWSTATE> states = LSession::handle()->XCB->WM_Get_Window_States(winlist[i]);
    for (int j = 0; j < states.length(); j++) {
      if (states[j] == LXCB::S_SKIP_TASKBAR) {
        // Skip taskbar window
        winlist.removeAt(i);
        i--;
        break;
      }
    }
  }
  //Do not change the status of the previously active window if it just changed to a non-visible window
  //WId activeWin = LSession::handle()->XCB->ActiveWindow();
  //bool skipActive = !winlist.contains(activeWin);
  //qDebug() << "Update Buttons:" << winlist;
  if(updating > ctime){ return; } //another thread kicked off already - stop this one
  //Now go through all the current buttons first
  for(int i=0; i<BUTTONS.length(); i++){
    //Get the windows managed in this button
    QList<WId> WI = BUTTONS[i]->windows();
    bool updated=false;
    if(updating > ctime){ return; } //another thread kicked off already - stop this one
    //Loop over all the windows for this button
    for(int w=0; w<WI.length(); w++){
      if(updating > ctime){ return; } //another thread kicked off already - stop this one
      if( winlist.contains( WI[w] ) ){
        //Still current window - update it later
	winlist.removeAll(WI[w] ); //remove this window from the list since it is done
      }else{
	//Window was closed - remove it
	if(WI.length()==1){
	  //Remove the entire button
	  //qDebug() << "Window Closed: Remove Button" ;
	  this->layout()->takeAt(i); //remove from the layout
	  BUTTONS.takeAt(i)->deleteLater();
	  i--;
	  updated = true; //prevent updating a removed button
	  break; //break out of the button->window loop
	}else{
	  //qDebug() << "Window Closed: Remove from button:" << WI[w].windowID() << "Button:" << w;
	  BUTTONS[i]->rmWindow(WI[w]); // one of the multiple windows for the button
	  WI.removeAt(w); //remove this window from the list
	  w--;
	}
	updated=true; //button already changed
      }
      if(updating > ctime){ return; } //another thread kicked off already - stop this one
    }
    if(!updated){
      //qDebug() << "Update Button:" << i;
      if(updating > ctime){ return; } //another thread kicked off already - stop this one
      //if(!skipActive || !BUTTONS[i]->isActive()){
        QTimer::singleShot(1,BUTTONS[i], SLOT(UpdateButton()) ); //keep moving on
      //}
    }
  }
  //Now go through the remaining windows
  for(int i=0; i<winlist.length(); i++){
    //New windows, create buttons for each (add grouping later)
    if(updating > ctime){ return; } //another thread kicked off already - stop this one
    //Check for a button that this can just be added to
    QString ctxt = LSession::handle()->XCB->WindowClass(winlist[i]);
    bool found = false;
    for(int b=0; b<BUTTONS.length(); b++){
      if(updating > ctime){ return; } //another thread kicked off already - stop this one
      if(BUTTONS[b]->classname()== ctxt && usegroups){
	//This adds a window to an existing group
        found = true;
	//qDebug() << "Add Window to Button:" << b;
	BUTTONS[b]->addWindow(winlist[i]);
	break;
      }
    }
    if(!found){
      if(updating > ctime){ return; } //another thread kicked off already - stop this one
      //No group, create a new button
      //qDebug() << "New Button";
      LTaskButton *but = new LTaskButton(this, usegroups);
        but->addWindow( winlist[i] );
	if(this->layout()->direction()==QBoxLayout::LeftToRight){
	    but->setIconSize(QSize(this->height(), this->height()));
	}else{
	    but->setIconSize(QSize(this->width(), this->width()));
	}
      this->layout()->addWidget(but);
      connect(but, SIGNAL(MenuClosed()), this, SIGNAL(MenuClosed()));
      BUTTONS << but;
    }
  }
}

void LTaskManagerPlugin::UpdateButton(WId win){
  for(int i=0; i<BUTTONS.length(); i++){
    if(BUTTONS[i]->windows().contains(win)){
      qDebug() << "Update Task Manager Button (single window ping)";
      QTimer::singleShot(0,BUTTONS[i], SLOT(UpdateButton()) );
      break;
    }
  }
}

void LTaskManagerPlugin::checkWindows(){
  timer->start();
}
<|endoftext|>