<commit_before>/**
 * Unit Tests for Piezas
**/

#include <gtest/gtest.h>
#include "Piezas.h"

class PiezasTest : public ::testing::Test
{
    protected:
        PiezasTest(){} //constructor runs before each test
        virtual ~PiezasTest(){} //destructor cleans up after tests
        virtual void SetUp(){} //sets up before each test (after constructor)
        virtual void TearDown(){} //clean up after each test, (before destructor)
};

TEST(PiezasTest, sanityCheck)
{
    ASSERT_TRUE(true);
}

TEST(PiezasTest, blankBoard)
{
    Piezas game;
    Piece board[3][4];
    int count = 0;

    game.reset();

    for(int i = 0; i < 3; i++)
    {
        for(int j = 0; j < 4; j++)
        {
            if(board[i][j] == Blank)
            {
                count++;
            }
        }
    }
    ASSERT_EQ(count, 12);
}<commit_msg>Add files via upload<commit_after>/**
 * Unit Tests for Piezas
**/

#include <gtest/gtest.h>
#include "Piezas.h"

class PiezasTest : public ::testing::Test
{
    protected:
        PiezasTest(){} //constructor runs before each test
        virtual ~PiezasTest(){} //destructor cleans up after tests
        virtual void SetUp(){} //sets up before each test (after constructor)
        virtual void TearDown(){} //clean up after each test, (before destructor)
};

TEST(PiezasTest, sanityCheck)
{
    ASSERT_TRUE(true);
}

TEST(PiezasTest, blankBoard)
{
    Piezas game;
    //Piece board[3][4];
    int count = 0;

    game.reset();

    for(int i = 0; i < 3; i++)
    {
        for(int j = 0; j < 4; j++)
        {
            if(board[i][j] == Blank)
            {
                count++;
            }
        }
    }
    ASSERT_EQ(count, 12);
}<|endoftext|>


<commit_before>/* ************************************************************************
 * Copyright 2016 Advanced Micro Devices, Inc.
 *
 * ************************************************************************ */

#include <stdlib.h>
#include <stdio.h>
#include <vector>

#include "hipblas.hpp"
#include "utility.h"
#include "cblas_interface.h"
#include "norm.h"
#include "unit.h"
#include <complex.h>

using namespace std;

/* ============================================================================================ */

template<typename T>
hipblasStatus_t testing_amax(Arguments argus)
{
    int N = argus.N;
    int incx = argus.incx;

    hipblasStatus_t status_1 = HIPBLAS_STATUS_SUCCESS;
    hipblasStatus_t status_2 = HIPBLAS_STATUS_SUCCESS;
    hipblasStatus_t status_3 = HIPBLAS_STATUS_SUCCESS;

    hipblasHandle_t handle;
    hipblasCreate(&handle);

    T *dx;
    int *d_rocblas_result;

    int cpu_result, rocblas_result1, rocblas_result2;
    int zero = 0;

    //check to prevent undefined memory allocation error
    if( N < 1 || incx <= 0 )
    {
        CHECK_HIP_ERROR(hipMalloc(&dx, 100 * sizeof(T)));
        CHECK_HIP_ERROR(hipMalloc(&d_rocblas_result, sizeof(int)));

        status_1 = hipblasIamax<T>(handle, N, dx, incx, &rocblas_result1);

        unit_check_general<int>(1, 1, 1, &zero, &rocblas_result1);
    }
    else
    {
        int sizeX = N * incx;

        //Naming: dX is in GPU (device) memory. hK is in CPU (host) memory, plz follow this practice
        vector<T> hx(sizeX);

        //allocate memory on device
        CHECK_HIP_ERROR(hipMalloc(&dx, sizeX * sizeof(T)));
        CHECK_HIP_ERROR(hipMalloc(&d_rocblas_result, sizeof(int)));

        //Initial Data on CPU
        srand(1);
        hipblas_init<T>(hx, 1, N, incx);

        //copy data from CPU to device, does not work for incx != 1
        CHECK_HIP_ERROR(hipMemcpy(dx, hx.data(), sizeof(T)*N*incx, hipMemcpyHostToDevice));

         /* =====================================================================
                     HIP BLAS
         =================================================================== */
        // device_pointer for d_rocblas_result
        {

            status_3 = hipblasSetPointerMode(handle, HIPBLAS_POINTER_MODE_DEVICE);

            status_1 = hipblasIamax<T>(handle, N, dx, incx, d_rocblas_result);

            CHECK_HIP_ERROR(hipMemcpy(&rocblas_result1, d_rocblas_result, sizeof(int), hipMemcpyDeviceToHost));
        }
        // host_pointer for rocblas_result2
        if ((status_1 == HIPBLAS_STATUS_SUCCESS) && (status_3 == HIPBLAS_STATUS_SUCCESS))
        {
            status_3 = hipblasSetPointerMode(handle, HIPBLAS_POINTER_MODE_HOST);

            status_2 = hipblasIamax<T>(handle, N, dx, incx, &rocblas_result2);
        }

        if ((status_1 == HIPBLAS_STATUS_SUCCESS) && (status_2 == HIPBLAS_STATUS_SUCCESS) && (status_3 == HIPBLAS_STATUS_SUCCESS))
        {
         /* =====================================================================
                     CPU BLAS
         =================================================================== */
            cblas_iamax<T>(N, hx.data(), incx, &cpu_result);

            unit_check_general<int>(1, 1, 1, &cpu_result, &rocblas_result1);
            unit_check_general<int>(1, 1, 1, &cpu_result, &rocblas_result2);

        }// end of if unit/norm check
    }

    CHECK_HIP_ERROR(hipFree(dx));
    CHECK_HIP_ERROR(hipFree(d_rocblas_result));
    hipblasDestroy(handle);

    if (status_1 != HIPBLAS_STATUS_SUCCESS)
    {
        return status_1;
    }
    else if (status_2 != HIPBLAS_STATUS_SUCCESS)
    {
        return status_2;
    }
    else if (status_3 != HIPBLAS_STATUS_SUCCESS)
    {
        return status_3;
    }
    else
    {
        return HIPBLAS_STATUS_SUCCESS;
    }
}
<commit_msg>correct iXamax tests to 1 based indexing<commit_after>/* ************************************************************************
 * Copyright 2016 Advanced Micro Devices, Inc.
 *
 * ************************************************************************ */

#include <stdlib.h>
#include <stdio.h>
#include <vector>

#include "hipblas.hpp"
#include "utility.h"
#include "cblas_interface.h"
#include "norm.h"
#include "unit.h"
#include <complex.h>

using namespace std;

/* ============================================================================================ */

template<typename T>
hipblasStatus_t testing_amax(Arguments argus)
{
    int N = argus.N;
    int incx = argus.incx;

    hipblasStatus_t status_1 = HIPBLAS_STATUS_SUCCESS;
    hipblasStatus_t status_2 = HIPBLAS_STATUS_SUCCESS;
    hipblasStatus_t status_3 = HIPBLAS_STATUS_SUCCESS;

    hipblasHandle_t handle;
    hipblasCreate(&handle);

    T *dx;
    int *d_rocblas_result;

    int cpu_result, rocblas_result1, rocblas_result2;
    int zero = 0;

    //check to prevent undefined memory allocation error
    if( N < 1 || incx <= 0 )
    {
        CHECK_HIP_ERROR(hipMalloc(&dx, 100 * sizeof(T)));
        CHECK_HIP_ERROR(hipMalloc(&d_rocblas_result, sizeof(int)));

        status_1 = hipblasIamax<T>(handle, N, dx, incx, &rocblas_result1);

        unit_check_general<int>(1, 1, 1, &zero, &rocblas_result1);
    }
    else
    {
        int sizeX = N * incx;

        //Naming: dX is in GPU (device) memory. hK is in CPU (host) memory, plz follow this practice
        vector<T> hx(sizeX);

        //allocate memory on device
        CHECK_HIP_ERROR(hipMalloc(&dx, sizeX * sizeof(T)));
        CHECK_HIP_ERROR(hipMalloc(&d_rocblas_result, sizeof(int)));

        //Initial Data on CPU
        srand(1);
        hipblas_init<T>(hx, 1, N, incx);

        //copy data from CPU to device, does not work for incx != 1
        CHECK_HIP_ERROR(hipMemcpy(dx, hx.data(), sizeof(T)*N*incx, hipMemcpyHostToDevice));

         /* =====================================================================
                     HIP BLAS
         =================================================================== */
        // device_pointer for d_rocblas_result
        {

            status_3 = hipblasSetPointerMode(handle, HIPBLAS_POINTER_MODE_DEVICE);

            status_1 = hipblasIamax<T>(handle, N, dx, incx, d_rocblas_result);

            CHECK_HIP_ERROR(hipMemcpy(&rocblas_result1, d_rocblas_result, sizeof(int), hipMemcpyDeviceToHost));
        }
        // host_pointer for rocblas_result2
        if ((status_1 == HIPBLAS_STATUS_SUCCESS) && (status_3 == HIPBLAS_STATUS_SUCCESS))
        {
            status_3 = hipblasSetPointerMode(handle, HIPBLAS_POINTER_MODE_HOST);

            status_2 = hipblasIamax<T>(handle, N, dx, incx, &rocblas_result2);
        }

        if ((status_1 == HIPBLAS_STATUS_SUCCESS) && (status_2 == HIPBLAS_STATUS_SUCCESS) && (status_3 == HIPBLAS_STATUS_SUCCESS))
        {
         /* =====================================================================
                     CPU BLAS
         =================================================================== */
            cblas_iamax<T>(N, hx.data(), incx, &cpu_result);
            // change to Fortran 1 based indexing as in BLAS standard, not cblas zero based indexing
            cpu_result += 1;

            unit_check_general<int>(1, 1, 1, &cpu_result, &rocblas_result1);
            unit_check_general<int>(1, 1, 1, &cpu_result, &rocblas_result2);

        }// end of if unit/norm check
    }

    CHECK_HIP_ERROR(hipFree(dx));
    CHECK_HIP_ERROR(hipFree(d_rocblas_result));
    hipblasDestroy(handle);

    if (status_1 != HIPBLAS_STATUS_SUCCESS)
    {
        return status_1;
    }
    else if (status_2 != HIPBLAS_STATUS_SUCCESS)
    {
        return status_2;
    }
    else if (status_3 != HIPBLAS_STATUS_SUCCESS)
    {
        return status_3;
    }
    else
    {
        return HIPBLAS_STATUS_SUCCESS;
    }
}
<|endoftext|>


<commit_before>/*
 Tests of the C++ interface to POSIX functions

 Copyright (c) 2015, Victor Zverovich
 All rights reserved.

 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.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER OR CONTRIBUTORS 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 <cstdlib>  // std::exit
#include <cstring>

#include "fmt/posix.h"
#include "gtest-extra.h"
#include "util.h"

#ifdef fileno
# undef fileno
#endif

using fmt::BufferedFile;
using fmt::ErrorCode;
using fmt::File;

using testing::internal::scoped_ptr;

// Checks if the file is open by reading one character from it.
bool isopen(int fd) {
  char buffer;
  return FMT_POSIX(read(fd, &buffer, 1)) == 1;
}

bool isclosed(int fd) {
  char buffer;
  std::streamsize result = 0;
  SUPPRESS_ASSERT(result = FMT_POSIX(read(fd, &buffer, 1)));
  return result == -1 && errno == EBADF;
}

// Opens a file for reading.
File open_file() {
  File read_end, write_end;
  File::pipe(read_end, write_end);
  write_end.write(FILE_CONTENT, std::strlen(FILE_CONTENT));
  write_end.close();
  return read_end;
}

// Attempts to write a string to a file.
void write(File &f, fmt::StringRef s) {
  std::size_t num_chars_left = s.size();
  const char *ptr = s.data();
  do {
    std::size_t count = f.write(ptr, num_chars_left);
    ptr += count;
    // We can't write more than size_t bytes since num_chars_left
    // has type size_t.
    num_chars_left -= static_cast<std::size_t>(count);
  } while (num_chars_left != 0);
}

TEST(BufferedFileTest, DefaultCtor) {
  BufferedFile f;
  EXPECT_TRUE(f.get() == 0);
}

TEST(BufferedFileTest, MoveCtor) {
  BufferedFile bf = open_buffered_file();
  FILE *fp = bf.get();
  EXPECT_TRUE(fp != 0);
  BufferedFile bf2(std::move(bf));
  EXPECT_EQ(fp, bf2.get());
  EXPECT_TRUE(bf.get() == 0);
}

TEST(BufferedFileTest, MoveAssignment) {
  BufferedFile bf = open_buffered_file();
  FILE *fp = bf.get();
  EXPECT_TRUE(fp != 0);
  BufferedFile bf2;
  bf2 = std::move(bf);
  EXPECT_EQ(fp, bf2.get());
  EXPECT_TRUE(bf.get() == 0);
}

TEST(BufferedFileTest, MoveAssignmentClosesFile) {
  BufferedFile bf = open_buffered_file();
  BufferedFile bf2 = open_buffered_file();
  int old_fd = bf2.fileno();
  bf2 = std::move(bf);
  EXPECT_TRUE(isclosed(old_fd));
}

TEST(BufferedFileTest, MoveFromTemporaryInCtor) {
  FILE *fp = 0;
  BufferedFile f(open_buffered_file(&fp));
  EXPECT_EQ(fp, f.get());
}

TEST(BufferedFileTest, MoveFromTemporaryInAssignment) {
  FILE *fp = 0;
  BufferedFile f;
  f = open_buffered_file(&fp);
  EXPECT_EQ(fp, f.get());
}

TEST(BufferedFileTest, MoveFromTemporaryInAssignmentClosesFile) {
  BufferedFile f = open_buffered_file();
  int old_fd = f.fileno();
  f = open_buffered_file();
  EXPECT_TRUE(isclosed(old_fd));
}

TEST(BufferedFileTest, CloseFileInDtor) {
  int fd = 0;
  {
    BufferedFile f = open_buffered_file();
    fd = f.fileno();
  }
  EXPECT_TRUE(isclosed(fd));
}

TEST(BufferedFileTest, CloseErrorInDtor) {
  scoped_ptr<BufferedFile> f(new BufferedFile(open_buffered_file()));
  EXPECT_WRITE(stderr, {
      // The close function must be called inside EXPECT_WRITE, otherwise
      // the system may recycle closed file descriptor when redirecting the
      // output in EXPECT_STDERR and the second close will break output
      // redirection.
      FMT_POSIX(close(f->fileno()));
      SUPPRESS_ASSERT(f.reset());
  }, format_system_error(EBADF, "cannot close file") + "\n");
}

TEST(BufferedFileTest, Close) {
  BufferedFile f = open_buffered_file();
  int fd = f.fileno();
  f.close();
  EXPECT_TRUE(f.get() == 0);
  EXPECT_TRUE(isclosed(fd));
}

TEST(BufferedFileTest, CloseError) {
  BufferedFile f = open_buffered_file();
  FMT_POSIX(close(f.fileno()));
  EXPECT_SYSTEM_ERROR_NOASSERT(f.close(), EBADF, "cannot close file");
  EXPECT_TRUE(f.get() == 0);
}

TEST(BufferedFileTest, Fileno) {
  BufferedFile f;
#ifndef __COVERITY__
  // fileno on a null FILE pointer either crashes or returns an error.
  // Disable Coverity because this is intentional.
  EXPECT_DEATH_IF_SUPPORTED({
    try {
      f.fileno();
    } catch (fmt::SystemError) {
      std::exit(1);
    }
  }, "");
#endif
  f = open_buffered_file();
  EXPECT_TRUE(f.fileno() != -1);
  File copy = File::dup(f.fileno());
  EXPECT_READ(copy, FILE_CONTENT);
}

TEST(FileTest, DefaultCtor) {
  File f;
  EXPECT_EQ(-1, f.descriptor());
}

TEST(FileTest, OpenBufferedFileInCtor) {
  FILE *fp = safe_fopen("test-file", "w");
  std::fputs(FILE_CONTENT, fp);
  std::fclose(fp);
  File f("test-file", File::RDONLY);
  ASSERT_TRUE(isopen(f.descriptor()));
}

TEST(FileTest, OpenBufferedFileError) {
  EXPECT_SYSTEM_ERROR(File("nonexistent", File::RDONLY),
      ENOENT, "cannot open file nonexistent");
}

TEST(FileTest, MoveCtor) {
  File f = open_file();
  int fd = f.descriptor();
  EXPECT_NE(-1, fd);
  File f2(std::move(f));
  EXPECT_EQ(fd, f2.descriptor());
  EXPECT_EQ(-1, f.descriptor());
}

TEST(FileTest, MoveAssignment) {
  File f = open_file();
  int fd = f.descriptor();
  EXPECT_NE(-1, fd);
  File f2;
  f2 = std::move(f);
  EXPECT_EQ(fd, f2.descriptor());
  EXPECT_EQ(-1, f.descriptor());
}

TEST(FileTest, MoveAssignmentClosesFile) {
  File f = open_file();
  File f2 = open_file();
  int old_fd = f2.descriptor();
  f2 = std::move(f);
  EXPECT_TRUE(isclosed(old_fd));
}

File OpenBufferedFile(int &fd) {
  File f = open_file();
  fd = f.descriptor();
  return std::move(f);
}

TEST(FileTest, MoveFromTemporaryInCtor) {
  int fd = 0xdead;
  File f(OpenBufferedFile(fd));
  EXPECT_EQ(fd, f.descriptor());
}

TEST(FileTest, MoveFromTemporaryInAssignment) {
  int fd = 0xdead;
  File f;
  f = OpenBufferedFile(fd);
  EXPECT_EQ(fd, f.descriptor());
}

TEST(FileTest, MoveFromTemporaryInAssignmentClosesFile) {
  int fd = 0xdead;
  File f = open_file();
  int old_fd = f.descriptor();
  f = OpenBufferedFile(fd);
  EXPECT_TRUE(isclosed(old_fd));
}

TEST(FileTest, CloseFileInDtor) {
  int fd = 0;
  {
    File f = open_file();
    fd = f.descriptor();
  }
  EXPECT_TRUE(isclosed(fd));
}

TEST(FileTest, CloseErrorInDtor) {
  scoped_ptr<File> f(new File(open_file()));
  EXPECT_WRITE(stderr, {
      // The close function must be called inside EXPECT_WRITE, otherwise
      // the system may recycle closed file descriptor when redirecting the
      // output in EXPECT_STDERR and the second close will break output
      // redirection.
      FMT_POSIX(close(f->descriptor()));
      SUPPRESS_ASSERT(f.reset());
  }, format_system_error(EBADF, "cannot close file") + "\n");
}

TEST(FileTest, Close) {
  File f = open_file();
  int fd = f.descriptor();
  f.close();
  EXPECT_EQ(-1, f.descriptor());
  EXPECT_TRUE(isclosed(fd));
}

TEST(FileTest, CloseError) {
  File f = open_file();
  FMT_POSIX(close(f.descriptor()));
  EXPECT_SYSTEM_ERROR_NOASSERT(f.close(), EBADF, "cannot close file");
  EXPECT_EQ(-1, f.descriptor());
}

TEST(FileTest, Read) {
  File f = open_file();
  EXPECT_READ(f, FILE_CONTENT);
}

TEST(FileTest, ReadError) {
  File f("test-file", File::WRONLY);
  char buf;
  // We intentionally read from a file opened in the write-only mode to
  // cause error.
  EXPECT_SYSTEM_ERROR(f.read(&buf, 1), EBADF, "cannot read from file");
}

TEST(FileTest, Write) {
  File read_end, write_end;
  File::pipe(read_end, write_end);
  write(write_end, "test");
  write_end.close();
  EXPECT_READ(read_end, "test");
}

TEST(FileTest, WriteError) {
  File f("test-file", File::RDONLY);
  // We intentionally write to a file opened in the read-only mode to
  // cause error.
  EXPECT_SYSTEM_ERROR(f.write(" ", 1), EBADF, "cannot write to file");
}

TEST(FileTest, Dup) {
  File f = open_file();
  File copy = File::dup(f.descriptor());
  EXPECT_NE(f.descriptor(), copy.descriptor());
  EXPECT_EQ(FILE_CONTENT, read(copy, std::strlen(FILE_CONTENT)));
}

#ifndef __COVERITY__
TEST(FileTest, DupError) {
  int value = -1;
  EXPECT_SYSTEM_ERROR_NOASSERT(File::dup(value),
      EBADF, "cannot duplicate file descriptor -1");
}
#endif

TEST(FileTest, Dup2) {
  File f = open_file();
  File copy = open_file();
  f.dup2(copy.descriptor());
  EXPECT_NE(f.descriptor(), copy.descriptor());
  EXPECT_READ(copy, FILE_CONTENT);
}

TEST(FileTest, Dup2Error) {
  File f = open_file();
  EXPECT_SYSTEM_ERROR_NOASSERT(f.dup2(-1), EBADF,
    fmt::format("cannot duplicate file descriptor {} to -1", f.descriptor()));
}

TEST(FileTest, Dup2NoExcept) {
  File f = open_file();
  File copy = open_file();
  ErrorCode ec;
  f.dup2(copy.descriptor(), ec);
  EXPECT_EQ(0, ec.get());
  EXPECT_NE(f.descriptor(), copy.descriptor());
  EXPECT_READ(copy, FILE_CONTENT);
}

TEST(FileTest, Dup2NoExceptError) {
  File f = open_file();
  ErrorCode ec;
  SUPPRESS_ASSERT(f.dup2(-1, ec));
  EXPECT_EQ(EBADF, ec.get());
}

TEST(FileTest, Pipe) {
  File read_end, write_end;
  File::pipe(read_end, write_end);
  EXPECT_NE(-1, read_end.descriptor());
  EXPECT_NE(-1, write_end.descriptor());
  write(write_end, "test");
  EXPECT_READ(read_end, "test");
}

TEST(FileTest, Fdopen) {
  File read_end, write_end;
  File::pipe(read_end, write_end);
  int read_fd = read_end.descriptor();
  EXPECT_EQ(read_fd, FMT_POSIX(fileno(read_end.fdopen("r").get())));
}

TEST(FileTest, FdopenError) {
  File f;
  EXPECT_SYSTEM_ERROR_NOASSERT(
      f.fdopen("r"), EBADF, "cannot associate stream with file descriptor");
}

#ifdef FMT_LOCALE
TEST(LocaleTest, Strtod) {
  fmt::Locale locale;
  const char *start = "4.2", *ptr = start;
  EXPECT_EQ(4.2, locale.strtod(ptr));
  EXPECT_EQ(start + 3, ptr);
}
#endif
<commit_msg>Fix -Wpessimizing-move<commit_after>/*
 Tests of the C++ interface to POSIX functions

 Copyright (c) 2015, Victor Zverovich
 All rights reserved.

 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.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER OR CONTRIBUTORS 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 <cstdlib>  // std::exit
#include <cstring>

#include "fmt/posix.h"
#include "gtest-extra.h"
#include "util.h"

#ifdef fileno
# undef fileno
#endif

using fmt::BufferedFile;
using fmt::ErrorCode;
using fmt::File;

using testing::internal::scoped_ptr;

// Checks if the file is open by reading one character from it.
bool isopen(int fd) {
  char buffer;
  return FMT_POSIX(read(fd, &buffer, 1)) == 1;
}

bool isclosed(int fd) {
  char buffer;
  std::streamsize result = 0;
  SUPPRESS_ASSERT(result = FMT_POSIX(read(fd, &buffer, 1)));
  return result == -1 && errno == EBADF;
}

// Opens a file for reading.
File open_file() {
  File read_end, write_end;
  File::pipe(read_end, write_end);
  write_end.write(FILE_CONTENT, std::strlen(FILE_CONTENT));
  write_end.close();
  return read_end;
}

// Attempts to write a string to a file.
void write(File &f, fmt::StringRef s) {
  std::size_t num_chars_left = s.size();
  const char *ptr = s.data();
  do {
    std::size_t count = f.write(ptr, num_chars_left);
    ptr += count;
    // We can't write more than size_t bytes since num_chars_left
    // has type size_t.
    num_chars_left -= static_cast<std::size_t>(count);
  } while (num_chars_left != 0);
}

TEST(BufferedFileTest, DefaultCtor) {
  BufferedFile f;
  EXPECT_TRUE(f.get() == 0);
}

TEST(BufferedFileTest, MoveCtor) {
  BufferedFile bf = open_buffered_file();
  FILE *fp = bf.get();
  EXPECT_TRUE(fp != 0);
  BufferedFile bf2(std::move(bf));
  EXPECT_EQ(fp, bf2.get());
  EXPECT_TRUE(bf.get() == 0);
}

TEST(BufferedFileTest, MoveAssignment) {
  BufferedFile bf = open_buffered_file();
  FILE *fp = bf.get();
  EXPECT_TRUE(fp != 0);
  BufferedFile bf2;
  bf2 = std::move(bf);
  EXPECT_EQ(fp, bf2.get());
  EXPECT_TRUE(bf.get() == 0);
}

TEST(BufferedFileTest, MoveAssignmentClosesFile) {
  BufferedFile bf = open_buffered_file();
  BufferedFile bf2 = open_buffered_file();
  int old_fd = bf2.fileno();
  bf2 = std::move(bf);
  EXPECT_TRUE(isclosed(old_fd));
}

TEST(BufferedFileTest, MoveFromTemporaryInCtor) {
  FILE *fp = 0;
  BufferedFile f(open_buffered_file(&fp));
  EXPECT_EQ(fp, f.get());
}

TEST(BufferedFileTest, MoveFromTemporaryInAssignment) {
  FILE *fp = 0;
  BufferedFile f;
  f = open_buffered_file(&fp);
  EXPECT_EQ(fp, f.get());
}

TEST(BufferedFileTest, MoveFromTemporaryInAssignmentClosesFile) {
  BufferedFile f = open_buffered_file();
  int old_fd = f.fileno();
  f = open_buffered_file();
  EXPECT_TRUE(isclosed(old_fd));
}

TEST(BufferedFileTest, CloseFileInDtor) {
  int fd = 0;
  {
    BufferedFile f = open_buffered_file();
    fd = f.fileno();
  }
  EXPECT_TRUE(isclosed(fd));
}

TEST(BufferedFileTest, CloseErrorInDtor) {
  scoped_ptr<BufferedFile> f(new BufferedFile(open_buffered_file()));
  EXPECT_WRITE(stderr, {
      // The close function must be called inside EXPECT_WRITE, otherwise
      // the system may recycle closed file descriptor when redirecting the
      // output in EXPECT_STDERR and the second close will break output
      // redirection.
      FMT_POSIX(close(f->fileno()));
      SUPPRESS_ASSERT(f.reset());
  }, format_system_error(EBADF, "cannot close file") + "\n");
}

TEST(BufferedFileTest, Close) {
  BufferedFile f = open_buffered_file();
  int fd = f.fileno();
  f.close();
  EXPECT_TRUE(f.get() == 0);
  EXPECT_TRUE(isclosed(fd));
}

TEST(BufferedFileTest, CloseError) {
  BufferedFile f = open_buffered_file();
  FMT_POSIX(close(f.fileno()));
  EXPECT_SYSTEM_ERROR_NOASSERT(f.close(), EBADF, "cannot close file");
  EXPECT_TRUE(f.get() == 0);
}

TEST(BufferedFileTest, Fileno) {
  BufferedFile f;
#ifndef __COVERITY__
  // fileno on a null FILE pointer either crashes or returns an error.
  // Disable Coverity because this is intentional.
  EXPECT_DEATH_IF_SUPPORTED({
    try {
      f.fileno();
    } catch (fmt::SystemError) {
      std::exit(1);
    }
  }, "");
#endif
  f = open_buffered_file();
  EXPECT_TRUE(f.fileno() != -1);
  File copy = File::dup(f.fileno());
  EXPECT_READ(copy, FILE_CONTENT);
}

TEST(FileTest, DefaultCtor) {
  File f;
  EXPECT_EQ(-1, f.descriptor());
}

TEST(FileTest, OpenBufferedFileInCtor) {
  FILE *fp = safe_fopen("test-file", "w");
  std::fputs(FILE_CONTENT, fp);
  std::fclose(fp);
  File f("test-file", File::RDONLY);
  ASSERT_TRUE(isopen(f.descriptor()));
}

TEST(FileTest, OpenBufferedFileError) {
  EXPECT_SYSTEM_ERROR(File("nonexistent", File::RDONLY),
      ENOENT, "cannot open file nonexistent");
}

TEST(FileTest, MoveCtor) {
  File f = open_file();
  int fd = f.descriptor();
  EXPECT_NE(-1, fd);
  File f2(std::move(f));
  EXPECT_EQ(fd, f2.descriptor());
  EXPECT_EQ(-1, f.descriptor());
}

TEST(FileTest, MoveAssignment) {
  File f = open_file();
  int fd = f.descriptor();
  EXPECT_NE(-1, fd);
  File f2;
  f2 = std::move(f);
  EXPECT_EQ(fd, f2.descriptor());
  EXPECT_EQ(-1, f.descriptor());
}

TEST(FileTest, MoveAssignmentClosesFile) {
  File f = open_file();
  File f2 = open_file();
  int old_fd = f2.descriptor();
  f2 = std::move(f);
  EXPECT_TRUE(isclosed(old_fd));
}

File OpenBufferedFile(int &fd) {
  File f = open_file();
  fd = f.descriptor();
  return f;
}

TEST(FileTest, MoveFromTemporaryInCtor) {
  int fd = 0xdead;
  File f(OpenBufferedFile(fd));
  EXPECT_EQ(fd, f.descriptor());
}

TEST(FileTest, MoveFromTemporaryInAssignment) {
  int fd = 0xdead;
  File f;
  f = OpenBufferedFile(fd);
  EXPECT_EQ(fd, f.descriptor());
}

TEST(FileTest, MoveFromTemporaryInAssignmentClosesFile) {
  int fd = 0xdead;
  File f = open_file();
  int old_fd = f.descriptor();
  f = OpenBufferedFile(fd);
  EXPECT_TRUE(isclosed(old_fd));
}

TEST(FileTest, CloseFileInDtor) {
  int fd = 0;
  {
    File f = open_file();
    fd = f.descriptor();
  }
  EXPECT_TRUE(isclosed(fd));
}

TEST(FileTest, CloseErrorInDtor) {
  scoped_ptr<File> f(new File(open_file()));
  EXPECT_WRITE(stderr, {
      // The close function must be called inside EXPECT_WRITE, otherwise
      // the system may recycle closed file descriptor when redirecting the
      // output in EXPECT_STDERR and the second close will break output
      // redirection.
      FMT_POSIX(close(f->descriptor()));
      SUPPRESS_ASSERT(f.reset());
  }, format_system_error(EBADF, "cannot close file") + "\n");
}

TEST(FileTest, Close) {
  File f = open_file();
  int fd = f.descriptor();
  f.close();
  EXPECT_EQ(-1, f.descriptor());
  EXPECT_TRUE(isclosed(fd));
}

TEST(FileTest, CloseError) {
  File f = open_file();
  FMT_POSIX(close(f.descriptor()));
  EXPECT_SYSTEM_ERROR_NOASSERT(f.close(), EBADF, "cannot close file");
  EXPECT_EQ(-1, f.descriptor());
}

TEST(FileTest, Read) {
  File f = open_file();
  EXPECT_READ(f, FILE_CONTENT);
}

TEST(FileTest, ReadError) {
  File f("test-file", File::WRONLY);
  char buf;
  // We intentionally read from a file opened in the write-only mode to
  // cause error.
  EXPECT_SYSTEM_ERROR(f.read(&buf, 1), EBADF, "cannot read from file");
}

TEST(FileTest, Write) {
  File read_end, write_end;
  File::pipe(read_end, write_end);
  write(write_end, "test");
  write_end.close();
  EXPECT_READ(read_end, "test");
}

TEST(FileTest, WriteError) {
  File f("test-file", File::RDONLY);
  // We intentionally write to a file opened in the read-only mode to
  // cause error.
  EXPECT_SYSTEM_ERROR(f.write(" ", 1), EBADF, "cannot write to file");
}

TEST(FileTest, Dup) {
  File f = open_file();
  File copy = File::dup(f.descriptor());
  EXPECT_NE(f.descriptor(), copy.descriptor());
  EXPECT_EQ(FILE_CONTENT, read(copy, std::strlen(FILE_CONTENT)));
}

#ifndef __COVERITY__
TEST(FileTest, DupError) {
  int value = -1;
  EXPECT_SYSTEM_ERROR_NOASSERT(File::dup(value),
      EBADF, "cannot duplicate file descriptor -1");
}
#endif

TEST(FileTest, Dup2) {
  File f = open_file();
  File copy = open_file();
  f.dup2(copy.descriptor());
  EXPECT_NE(f.descriptor(), copy.descriptor());
  EXPECT_READ(copy, FILE_CONTENT);
}

TEST(FileTest, Dup2Error) {
  File f = open_file();
  EXPECT_SYSTEM_ERROR_NOASSERT(f.dup2(-1), EBADF,
    fmt::format("cannot duplicate file descriptor {} to -1", f.descriptor()));
}

TEST(FileTest, Dup2NoExcept) {
  File f = open_file();
  File copy = open_file();
  ErrorCode ec;
  f.dup2(copy.descriptor(), ec);
  EXPECT_EQ(0, ec.get());
  EXPECT_NE(f.descriptor(), copy.descriptor());
  EXPECT_READ(copy, FILE_CONTENT);
}

TEST(FileTest, Dup2NoExceptError) {
  File f = open_file();
  ErrorCode ec;
  SUPPRESS_ASSERT(f.dup2(-1, ec));
  EXPECT_EQ(EBADF, ec.get());
}

TEST(FileTest, Pipe) {
  File read_end, write_end;
  File::pipe(read_end, write_end);
  EXPECT_NE(-1, read_end.descriptor());
  EXPECT_NE(-1, write_end.descriptor());
  write(write_end, "test");
  EXPECT_READ(read_end, "test");
}

TEST(FileTest, Fdopen) {
  File read_end, write_end;
  File::pipe(read_end, write_end);
  int read_fd = read_end.descriptor();
  EXPECT_EQ(read_fd, FMT_POSIX(fileno(read_end.fdopen("r").get())));
}

TEST(FileTest, FdopenError) {
  File f;
  EXPECT_SYSTEM_ERROR_NOASSERT(
      f.fdopen("r"), EBADF, "cannot associate stream with file descriptor");
}

#ifdef FMT_LOCALE
TEST(LocaleTest, Strtod) {
  fmt::Locale locale;
  const char *start = "4.2", *ptr = start;
  EXPECT_EQ(4.2, locale.strtod(ptr));
  EXPECT_EQ(start + 3, ptr);
}
#endif
<|endoftext|>


<commit_before>#include "rampancy/CLIPSFunctions.h"
#include "rampancy/Cortex.h"
extern "C" {
   #include "clips.h"
}

extern "C" void CompileFileIntoKnowledge(void* env);
extern "C" void InterpretCodeIntoKnowledge(void* env);
extern "C" void SetupRampancyExpertSystemInterfaces(void* env) {
   EnvDefineFunction(env, "rampancy-compile", 'v',
         PTIEF CompileFileIntoKnowledge, "CompileFileIntoKnowledge");
   EnvDefineFunction(env, "rampancy-interpret", 'v',
         PTIEF InterpretCodeIntoKnowledge, "InterpretCodeIntoKnowledge");
}

extern "C" void CompileFileIntoKnowledge(void* env) {
   rampancy::Cortex* globalCortex = rampancy::Cortex::getRampantCortex();
   globalCortex->compileToKnowledge(env);
}

extern "C" void InterpretCodeIntoKnowledge(void* env) {
   rampancy::Cortex* globalCortex = rampancy::Cortex::getRampantCortex();
   globalCortex->interpretToKnowledge(env);
}
<commit_msg>Added support for saving modules to a bitcode representation on disk<commit_after>#include "rampancy/CLIPSFunctions.h"
#include "rampancy/Cortex.h"
#include "llvm/Pass.h"
#include "llvm/PassManager.h"
#include "llvm/PassRegistry.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Target/TargetLibraryInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/LinkAllPasses.h"
#include "llvm/LinkAllVMCore.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/Assembly/PrintModulePass.h"
#include "ExpertSystem/Types.h"
extern "C" {
#include "clips.h"
}
#define rampancy_compile (char*)"rampancy-compile"
#define rampancy_interpret (char*)"rampancy-interpret"
#define rampancy_save_module (char*)"rampancy-save-llvm-module"
#define msg(x) (char*) x

extern "C" void CompileFileIntoKnowledge(void* env) {
	rampancy::Cortex* globalCortex = rampancy::Cortex::getRampantCortex();
	globalCortex->compileToKnowledge(env);
}

extern "C" void InterpretCodeIntoKnowledge(void* env) {
	rampancy::Cortex* globalCortex = rampancy::Cortex::getRampantCortex();
	globalCortex->interpretToKnowledge(env);
}

extern "C" void* SaveModuleToFile(void* env) {
	DATA_OBJECT addrDO,
					saveAsBitcodeDO,
					pathDO;
	char *saveAsBitcodeStr,
		  *pathStr;
	bool saveAsBitcode;
	if(EnvArgCountCheck(env, rampancy_save_module, EXACTLY, 3) == -1) {
		return FalseSymbol();
	}

	if(EnvArgTypeCheck(env, rampancy_save_module, 1, INTEGER, &addrDO) == FALSE) {
		return FalseSymbol();
	}
	if(EnvArgTypeCheck(env, rampancy_save_module, 2, SYMBOL_OR_STRING, &saveAsBitcodeDO) == FALSE) {
		return FalseSymbol();
	}
	if(EnvArgTypeCheck(env, rampancy_save_module, 3, SYMBOL_OR_STRING, &pathDO) == FALSE) {
		return FalseSymbol();
	}
	llvm::Module* module = (llvm::Module*)(PointerAddress)DOToLong(addrDO);
	saveAsBitcodeStr = DOToString(saveAsBitcodeDO);
	if(strcmp(saveAsBitcodeStr, "TRUE") == 0) {
		saveAsBitcode = TRUE;
	} else {
		saveAsBitcode = FALSE;
	}
	pathStr = DOToString(pathDO);
	std::string tmp(pathStr);
	llvm::PassManager pm;
	std::string ErrorInfo;
	llvm::raw_fd_ostream OS(tmp.c_str(), ErrorInfo, llvm::raw_fd_ostream::F_Binary);

	if(saveAsBitcode) {
		pm.add(llvm::createBitcodeWriterPass(OS));
	} else {
		pm.add(llvm::createPrintModulePass(&OS));
	}
	pm.run(*module);
	return TrueSymbol();
}

extern "C" void SetupRampancyExpertSystemInterfaces(void* env) {
	EnvDefineFunction(env, rampancy_compile, 'v',
			PTIEF CompileFileIntoKnowledge,
			msg("CompileFileIntoKnowledge"));
	EnvDefineFunction(env, rampancy_interpret, 'v',
			PTIEF InterpretCodeIntoKnowledge,
			msg("InterpretCodeIntoKnowledge"));
	EnvDefineFunction(env, rampancy_save_module, 'b',
			PTIEF SaveModuleToFile,
			msg("SaveModuleToFile"));
}

#undef rampancy_compile
#undef rampancy_interpret
#undef rampancy_save_module
#undef msg
<|endoftext|>


<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "quiche/quic/tools/quic_server.h"

#include <memory>

#include "absl/base/macros.h"
#include "quiche/quic/core/crypto/quic_random.h"
#include "quiche/quic/core/io/quic_default_event_loop.h"
#include "quiche/quic/core/io/quic_event_loop.h"
#include "quiche/quic/core/quic_default_clock.h"
#include "quiche/quic/core/quic_default_connection_helper.h"
#include "quiche/quic/core/quic_default_packet_writer.h"
#include "quiche/quic/core/quic_utils.h"
#include "quiche/quic/platform/api/quic_flags.h"
#include "quiche/quic/platform/api/quic_logging.h"
#include "quiche/quic/platform/api/quic_socket_address.h"
#include "quiche/quic/platform/api/quic_test.h"
#include "quiche/quic/platform/api/quic_test_loopback.h"
#include "quiche/quic/test_tools/crypto_test_utils.h"
#include "quiche/quic/test_tools/mock_quic_dispatcher.h"
#include "quiche/quic/test_tools/quic_server_peer.h"
#include "quiche/quic/tools/quic_memory_cache_backend.h"
#include "quiche/quic/tools/quic_simple_crypto_server_stream_helper.h"

namespace quic {
namespace test {

using ::testing::_;

namespace {

class MockQuicSimpleDispatcher : public QuicSimpleDispatcher {
 public:
  MockQuicSimpleDispatcher(
      const QuicConfig* config, const QuicCryptoServerConfig* crypto_config,
      QuicVersionManager* version_manager,
      std::unique_ptr<QuicConnectionHelperInterface> helper,
      std::unique_ptr<QuicCryptoServerStreamBase::Helper> session_helper,
      std::unique_ptr<QuicAlarmFactory> alarm_factory,
      QuicSimpleServerBackend* quic_simple_server_backend)
      : QuicSimpleDispatcher(
            config, crypto_config, version_manager, std::move(helper),
            std::move(session_helper), std::move(alarm_factory),
            quic_simple_server_backend, kQuicDefaultConnectionIdLength) {}
  ~MockQuicSimpleDispatcher() override = default;

  MOCK_METHOD(void, OnCanWrite, (), (override));
  MOCK_METHOD(bool, HasPendingWrites, (), (const, override));
  MOCK_METHOD(bool, HasChlosBuffered, (), (const, override));
  MOCK_METHOD(void, ProcessBufferedChlos, (size_t), (override));
};

class TestQuicServer : public QuicServer {
 public:
  explicit TestQuicServer(QuicEventLoopFactory* event_loop_factory)
      : QuicServer(crypto_test_utils::ProofSourceForTesting(),
                   &quic_simple_server_backend_),
        event_loop_factory_(event_loop_factory) {}

  ~TestQuicServer() override = default;

  MockQuicSimpleDispatcher* mock_dispatcher() { return mock_dispatcher_; }

 protected:
  QuicDispatcher* CreateQuicDispatcher() override {
    mock_dispatcher_ = new MockQuicSimpleDispatcher(
        &config(), &crypto_config(), version_manager(),
        std::make_unique<QuicDefaultConnectionHelper>(),
        std::unique_ptr<QuicCryptoServerStreamBase::Helper>(
            new QuicSimpleCryptoServerStreamHelper()),
        event_loop()->CreateAlarmFactory(), &quic_simple_server_backend_);
    return mock_dispatcher_;
  }

  std::unique_ptr<QuicEventLoop> CreateEventLoop() override {
    return event_loop_factory_->Create(QuicDefaultClock::Get());
  }

  MockQuicSimpleDispatcher* mock_dispatcher_ = nullptr;
  QuicMemoryCacheBackend quic_simple_server_backend_;
  QuicEventLoopFactory* event_loop_factory_;
};

class QuicServerEpollInTest : public QuicTestWithParam<QuicEventLoopFactory*> {
 public:
  QuicServerEpollInTest()
      : server_address_(TestLoopback(), 0), server_(GetParam()) {}

  void StartListening() {
    server_.CreateUDPSocketAndListen(server_address_);
    server_address_ = QuicSocketAddress(server_address_.host(), server_.port());

    ASSERT_TRUE(QuicServerPeer::SetSmallSocket(&server_));

    if (!server_.overflow_supported()) {
      QUIC_LOG(WARNING) << "Overflow not supported.  Not testing.";
      return;
    }
  }

 protected:
  QuicSocketAddress server_address_;
  TestQuicServer server_;
};

std::string GetTestParamName(
    ::testing::TestParamInfo<QuicEventLoopFactory*> info) {
  return EscapeTestParamName(info.param->GetName());
}

INSTANTIATE_TEST_SUITE_P(QuicServerEpollInTests, QuicServerEpollInTest,
                         ::testing::ValuesIn(GetAllSupportedEventLoops()),
                         GetTestParamName);

// Tests that if dispatcher has CHLOs waiting for connection creation, EPOLLIN
// event should try to create connections for them. And set epoll mask with
// EPOLLIN if there are still CHLOs remaining at the end of epoll event.
TEST_P(QuicServerEpollInTest, ProcessBufferedCHLOsOnEpollin) {
  // Given an EPOLLIN event, try to create session for buffered CHLOs. In first
  // event, dispatcher can't create session for all of CHLOs. So listener should
  // register another EPOLLIN event by itself. Even without new packet arrival,
  // the rest CHLOs should be process in next epoll event.
  StartListening();
  bool more_chlos = true;
  MockQuicSimpleDispatcher* dispatcher_ = server_.mock_dispatcher();
  QUICHE_DCHECK(dispatcher_ != nullptr);
  EXPECT_CALL(*dispatcher_, OnCanWrite()).Times(testing::AnyNumber());
  EXPECT_CALL(*dispatcher_, ProcessBufferedChlos(_)).Times(2);
  EXPECT_CALL(*dispatcher_, HasPendingWrites()).Times(testing::AnyNumber());
  // Expect there are still CHLOs buffered after 1st event. But not any more
  // after 2nd event.
  EXPECT_CALL(*dispatcher_, HasChlosBuffered())
      .WillOnce(testing::Return(true))
      .WillOnce(
          DoAll(testing::Assign(&more_chlos, false), testing::Return(false)));

  // Send a packet to trigger epoll event.
  int fd = socket(
      AddressFamilyUnderTest() == IpAddressFamily::IP_V4 ? AF_INET : AF_INET6,
      SOCK_DGRAM | SOCK_NONBLOCK, IPPROTO_UDP);
  ASSERT_LT(0, fd);

  char buf[1024];
  memset(buf, 0, ABSL_ARRAYSIZE(buf));
  sockaddr_storage storage = server_address_.generic_address();
  int rc = sendto(fd, buf, ABSL_ARRAYSIZE(buf), 0,
                  reinterpret_cast<sockaddr*>(&storage), sizeof(storage));
  if (rc < 0) {
    QUIC_DLOG(INFO) << errno << " " << strerror(errno);
  }

  while (more_chlos) {
    server_.WaitForEvents();
  }
}

class QuicServerDispatchPacketTest : public QuicTest {
 public:
  QuicServerDispatchPacketTest()
      : crypto_config_("blah", QuicRandom::GetInstance(),
                       crypto_test_utils::ProofSourceForTesting(),
                       KeyExchangeSource::Default()),
        version_manager_(AllSupportedVersions()),
        event_loop_(GetDefaultEventLoop()->Create(QuicDefaultClock::Get())),
        dispatcher_(&config_, &crypto_config_, &version_manager_,
                    std::make_unique<QuicDefaultConnectionHelper>(),
                    std::make_unique<QuicSimpleCryptoServerStreamHelper>(),
                    event_loop_->CreateAlarmFactory(),
                    &quic_simple_server_backend_) {
    dispatcher_.InitializeWithWriter(new QuicDefaultPacketWriter(1234));
  }

  void DispatchPacket(const QuicReceivedPacket& packet) {
    QuicSocketAddress client_addr, server_addr;
    dispatcher_.ProcessPacket(server_addr, client_addr, packet);
  }

 protected:
  QuicConfig config_;
  QuicCryptoServerConfig crypto_config_;
  QuicVersionManager version_manager_;
  std::unique_ptr<QuicEventLoop> event_loop_;
  QuicMemoryCacheBackend quic_simple_server_backend_;
  MockQuicDispatcher dispatcher_;
};

TEST_F(QuicServerDispatchPacketTest, DispatchPacket) {
  // clang-format off
  unsigned char valid_packet[] = {
    // public flags (8 byte connection_id)
    0x3C,
    // connection_id
    0x10, 0x32, 0x54, 0x76,
    0x98, 0xBA, 0xDC, 0xFE,
    // packet number
    0xBC, 0x9A, 0x78, 0x56,
    0x34, 0x12,
    // private flags
    0x00
  };
  // clang-format on
  QuicReceivedPacket encrypted_valid_packet(
      reinterpret_cast<char*>(valid_packet), ABSL_ARRAYSIZE(valid_packet),
      QuicTime::Zero(), false);

  EXPECT_CALL(dispatcher_, ProcessPacket(_, _, _)).Times(1);
  DispatchPacket(encrypted_valid_packet);
}

}  // namespace
}  // namespace test
}  // namespace quic
<commit_msg>Fix a memory destruction ordering issue in Quic test code<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "quiche/quic/tools/quic_server.h"

#include <memory>

#include "absl/base/macros.h"
#include "quiche/quic/core/crypto/quic_random.h"
#include "quiche/quic/core/io/quic_default_event_loop.h"
#include "quiche/quic/core/io/quic_event_loop.h"
#include "quiche/quic/core/quic_default_clock.h"
#include "quiche/quic/core/quic_default_connection_helper.h"
#include "quiche/quic/core/quic_default_packet_writer.h"
#include "quiche/quic/core/quic_utils.h"
#include "quiche/quic/platform/api/quic_flags.h"
#include "quiche/quic/platform/api/quic_logging.h"
#include "quiche/quic/platform/api/quic_socket_address.h"
#include "quiche/quic/platform/api/quic_test.h"
#include "quiche/quic/platform/api/quic_test_loopback.h"
#include "quiche/quic/test_tools/crypto_test_utils.h"
#include "quiche/quic/test_tools/mock_quic_dispatcher.h"
#include "quiche/quic/test_tools/quic_server_peer.h"
#include "quiche/quic/tools/quic_memory_cache_backend.h"
#include "quiche/quic/tools/quic_simple_crypto_server_stream_helper.h"

namespace quic {
namespace test {

using ::testing::_;

namespace {

class MockQuicSimpleDispatcher : public QuicSimpleDispatcher {
 public:
  MockQuicSimpleDispatcher(
      const QuicConfig* config, const QuicCryptoServerConfig* crypto_config,
      QuicVersionManager* version_manager,
      std::unique_ptr<QuicConnectionHelperInterface> helper,
      std::unique_ptr<QuicCryptoServerStreamBase::Helper> session_helper,
      std::unique_ptr<QuicAlarmFactory> alarm_factory,
      QuicSimpleServerBackend* quic_simple_server_backend)
      : QuicSimpleDispatcher(
            config, crypto_config, version_manager, std::move(helper),
            std::move(session_helper), std::move(alarm_factory),
            quic_simple_server_backend, kQuicDefaultConnectionIdLength) {}
  ~MockQuicSimpleDispatcher() override = default;

  MOCK_METHOD(void, OnCanWrite, (), (override));
  MOCK_METHOD(bool, HasPendingWrites, (), (const, override));
  MOCK_METHOD(bool, HasChlosBuffered, (), (const, override));
  MOCK_METHOD(void, ProcessBufferedChlos, (size_t), (override));
};

class TestQuicServer : public QuicServer {
 public:
  explicit TestQuicServer(QuicEventLoopFactory* event_loop_factory,
                          QuicMemoryCacheBackend* quic_simple_server_backend)
      : QuicServer(crypto_test_utils::ProofSourceForTesting(),
                   quic_simple_server_backend),
        quic_simple_server_backend_(quic_simple_server_backend),
        event_loop_factory_(event_loop_factory) {}

  ~TestQuicServer() override = default;

  MockQuicSimpleDispatcher* mock_dispatcher() { return mock_dispatcher_; }

 protected:
  QuicDispatcher* CreateQuicDispatcher() override {
    mock_dispatcher_ = new MockQuicSimpleDispatcher(
        &config(), &crypto_config(), version_manager(),
        std::make_unique<QuicDefaultConnectionHelper>(),
        std::unique_ptr<QuicCryptoServerStreamBase::Helper>(
            new QuicSimpleCryptoServerStreamHelper()),
        event_loop()->CreateAlarmFactory(), quic_simple_server_backend_);
    return mock_dispatcher_;
  }

  std::unique_ptr<QuicEventLoop> CreateEventLoop() override {
    return event_loop_factory_->Create(QuicDefaultClock::Get());
  }

  MockQuicSimpleDispatcher* mock_dispatcher_ = nullptr;
  QuicMemoryCacheBackend* quic_simple_server_backend_;
  QuicEventLoopFactory* event_loop_factory_;
};

class QuicServerEpollInTest : public QuicTestWithParam<QuicEventLoopFactory*> {
 public:
  QuicServerEpollInTest()
      : server_address_(TestLoopback(), 0),
        server_(GetParam(), &quic_simple_server_backend_) {}

  void StartListening() {
    server_.CreateUDPSocketAndListen(server_address_);
    server_address_ = QuicSocketAddress(server_address_.host(), server_.port());

    ASSERT_TRUE(QuicServerPeer::SetSmallSocket(&server_));

    if (!server_.overflow_supported()) {
      QUIC_LOG(WARNING) << "Overflow not supported.  Not testing.";
      return;
    }
  }

 protected:
  QuicSocketAddress server_address_;
  QuicMemoryCacheBackend quic_simple_server_backend_;
  TestQuicServer server_;
};

std::string GetTestParamName(
    ::testing::TestParamInfo<QuicEventLoopFactory*> info) {
  return EscapeTestParamName(info.param->GetName());
}

INSTANTIATE_TEST_SUITE_P(QuicServerEpollInTests, QuicServerEpollInTest,
                         ::testing::ValuesIn(GetAllSupportedEventLoops()),
                         GetTestParamName);

// Tests that if dispatcher has CHLOs waiting for connection creation, EPOLLIN
// event should try to create connections for them. And set epoll mask with
// EPOLLIN if there are still CHLOs remaining at the end of epoll event.
TEST_P(QuicServerEpollInTest, ProcessBufferedCHLOsOnEpollin) {
  // Given an EPOLLIN event, try to create session for buffered CHLOs. In first
  // event, dispatcher can't create session for all of CHLOs. So listener should
  // register another EPOLLIN event by itself. Even without new packet arrival,
  // the rest CHLOs should be process in next epoll event.
  StartListening();
  bool more_chlos = true;
  MockQuicSimpleDispatcher* dispatcher_ = server_.mock_dispatcher();
  QUICHE_DCHECK(dispatcher_ != nullptr);
  EXPECT_CALL(*dispatcher_, OnCanWrite()).Times(testing::AnyNumber());
  EXPECT_CALL(*dispatcher_, ProcessBufferedChlos(_)).Times(2);
  EXPECT_CALL(*dispatcher_, HasPendingWrites()).Times(testing::AnyNumber());
  // Expect there are still CHLOs buffered after 1st event. But not any more
  // after 2nd event.
  EXPECT_CALL(*dispatcher_, HasChlosBuffered())
      .WillOnce(testing::Return(true))
      .WillOnce(
          DoAll(testing::Assign(&more_chlos, false), testing::Return(false)));

  // Send a packet to trigger epoll event.
  int fd = socket(
      AddressFamilyUnderTest() == IpAddressFamily::IP_V4 ? AF_INET : AF_INET6,
      SOCK_DGRAM | SOCK_NONBLOCK, IPPROTO_UDP);
  ASSERT_LT(0, fd);

  char buf[1024];
  memset(buf, 0, ABSL_ARRAYSIZE(buf));
  sockaddr_storage storage = server_address_.generic_address();
  int rc = sendto(fd, buf, ABSL_ARRAYSIZE(buf), 0,
                  reinterpret_cast<sockaddr*>(&storage), sizeof(storage));
  if (rc < 0) {
    QUIC_DLOG(INFO) << errno << " " << strerror(errno);
  }

  while (more_chlos) {
    server_.WaitForEvents();
  }
}

class QuicServerDispatchPacketTest : public QuicTest {
 public:
  QuicServerDispatchPacketTest()
      : crypto_config_("blah", QuicRandom::GetInstance(),
                       crypto_test_utils::ProofSourceForTesting(),
                       KeyExchangeSource::Default()),
        version_manager_(AllSupportedVersions()),
        event_loop_(GetDefaultEventLoop()->Create(QuicDefaultClock::Get())),
        dispatcher_(&config_, &crypto_config_, &version_manager_,
                    std::make_unique<QuicDefaultConnectionHelper>(),
                    std::make_unique<QuicSimpleCryptoServerStreamHelper>(),
                    event_loop_->CreateAlarmFactory(),
                    &quic_simple_server_backend_) {
    dispatcher_.InitializeWithWriter(new QuicDefaultPacketWriter(1234));
  }

  void DispatchPacket(const QuicReceivedPacket& packet) {
    QuicSocketAddress client_addr, server_addr;
    dispatcher_.ProcessPacket(server_addr, client_addr, packet);
  }

 protected:
  QuicConfig config_;
  QuicCryptoServerConfig crypto_config_;
  QuicVersionManager version_manager_;
  std::unique_ptr<QuicEventLoop> event_loop_;
  QuicMemoryCacheBackend quic_simple_server_backend_;
  MockQuicDispatcher dispatcher_;
};

TEST_F(QuicServerDispatchPacketTest, DispatchPacket) {
  // clang-format off
  unsigned char valid_packet[] = {
    // public flags (8 byte connection_id)
    0x3C,
    // connection_id
    0x10, 0x32, 0x54, 0x76,
    0x98, 0xBA, 0xDC, 0xFE,
    // packet number
    0xBC, 0x9A, 0x78, 0x56,
    0x34, 0x12,
    // private flags
    0x00
  };
  // clang-format on
  QuicReceivedPacket encrypted_valid_packet(
      reinterpret_cast<char*>(valid_packet), ABSL_ARRAYSIZE(valid_packet),
      QuicTime::Zero(), false);

  EXPECT_CALL(dispatcher_, ProcessPacket(_, _, _)).Times(1);
  DispatchPacket(encrypted_valid_packet);
}

}  // namespace
}  // namespace test
}  // namespace quic
<|endoftext|>


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

#ifndef SD_EDIT_WINDOW_HXX
#define SD_EDIT_WINDOW_HXX

#ifndef _SV_WINDOW_HXX
#include <vcl/window.hxx>
#endif
#ifndef _TRANSFER_HXX
#include <svtools/transfer.hxx>
#endif
#ifndef _SV_TIMER_HXX
#include <vcl/timer.hxx>
#endif
#ifndef _MyEDITDATA_HXX
#include <svx/editdata.hxx>
#endif
#ifndef INCLUDED_SVTOOLS_COLORCFG_HXX
#include <svtools/colorcfg.hxx>
#endif

class EditEngine;
class EditStatus;
class EditView;
class Menu;
class ScrollBar;
class ScrollBarBox;
class SfxItemPool;
class Timer;

namespace sd { namespace notes {

class EditWindow
    : public Window,
      public DropTargetHelper
{
public:
    EditWindow (Window* pParentWindow, SfxItemPool* pItemPool);
    ~EditWindow (void);

    void InsertText (const String &rText);

    using Window::GetText;
private:
    EditView* mpEditView;
    EditEngine* mpEditEngine;
    SfxItemPool* mpEditEngineItemPool;
    ScrollBar* mpHorizontalScrollBar;
    ScrollBar* mpVerticalScrollBar;
    ScrollBarBox* mpScrollBox;
    Timer maModifyTimer;
    Timer maCursorMoveTimer;
    ESelection maOldSelection;

    virtual void KeyInput(const KeyEvent& rKEvt);
    virtual void Command(const CommandEvent& rCEvt);
    DECL_LINK(MenuSelectHdl, Menu *);

    virtual void DataChanged( const DataChangedEvent& );
    virtual void Resize();
    virtual void MouseMove(const MouseEvent &rEvt);
    virtual void MouseButtonUp(const MouseEvent &rEvt);
    virtual void MouseButtonDown(const MouseEvent &rEvt);

    virtual sal_Int8    AcceptDrop( const AcceptDropEvent& rEvt );
    virtual sal_Int8    ExecuteDrop( const ExecuteDropEvent& rEvt );
    virtual void Paint(const Rectangle& rRect);

    DECL_LINK(EditStatusHdl ,EditStatus *);
    DECL_LINK(ScrollHdl, ScrollBar *);

    void        CreateEditView();

    Rectangle   AdjustScrollBars();
    void        SetScrollBarRanges();
    void        InitScrollBars();

    //    SmDocShell *    GetDoc();
    //    SmViewShell *   GetView();
    EditView* GetEditView (void);
    EditEngine* GetEditEngine (void);
    EditEngine* CreateEditEngine (void);

    // Window
    virtual void        SetText(const XubString &rText);
    virtual XubString   GetText();
    virtual void        GetFocus();
    virtual void        LoseFocus();

    ESelection          GetSelection() const;
    void                SetSelection(const ESelection &rSel);

    BOOL                IsEmpty() const;
    BOOL                IsSelected() const;
    BOOL                IsAllSelected() const;
    void                Cut();
    void                Copy();
    void                Paste();
    void                Delete();
    void                SelectAll();
    void                MarkError(const Point &rPos);
    void                SelNextMark();
    void                SelPrevMark();
    BOOL                HasMark(const String &rText) const;

    void ApplyColorConfigValues( const svtools::ColorConfig &rColorCfg );
};

} } // end of namespace ::sd::notes

#endif

<commit_msg>INTEGRATION: CWS changefileheader (1.4.298); FILE MERGED 2008/04/01 15:35:48 thb 1.4.298.2: #i85898# Stripping all external header guards 2008/03/31 13:58:42 rt 1.4.298.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: EditWindow.hxx,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef SD_EDIT_WINDOW_HXX
#define SD_EDIT_WINDOW_HXX

#include <vcl/window.hxx>
#include <svtools/transfer.hxx>
#include <vcl/timer.hxx>
#include <svx/editdata.hxx>
#include <svtools/colorcfg.hxx>

class EditEngine;
class EditStatus;
class EditView;
class Menu;
class ScrollBar;
class ScrollBarBox;
class SfxItemPool;
class Timer;

namespace sd { namespace notes {

class EditWindow
    : public Window,
      public DropTargetHelper
{
public:
    EditWindow (Window* pParentWindow, SfxItemPool* pItemPool);
    ~EditWindow (void);

    void InsertText (const String &rText);

    using Window::GetText;
private:
    EditView* mpEditView;
    EditEngine* mpEditEngine;
    SfxItemPool* mpEditEngineItemPool;
    ScrollBar* mpHorizontalScrollBar;
    ScrollBar* mpVerticalScrollBar;
    ScrollBarBox* mpScrollBox;
    Timer maModifyTimer;
    Timer maCursorMoveTimer;
    ESelection maOldSelection;

    virtual void KeyInput(const KeyEvent& rKEvt);
    virtual void Command(const CommandEvent& rCEvt);
    DECL_LINK(MenuSelectHdl, Menu *);

    virtual void DataChanged( const DataChangedEvent& );
    virtual void Resize();
    virtual void MouseMove(const MouseEvent &rEvt);
    virtual void MouseButtonUp(const MouseEvent &rEvt);
    virtual void MouseButtonDown(const MouseEvent &rEvt);

    virtual sal_Int8    AcceptDrop( const AcceptDropEvent& rEvt );
    virtual sal_Int8    ExecuteDrop( const ExecuteDropEvent& rEvt );
    virtual void Paint(const Rectangle& rRect);

    DECL_LINK(EditStatusHdl ,EditStatus *);
    DECL_LINK(ScrollHdl, ScrollBar *);

    void        CreateEditView();

    Rectangle   AdjustScrollBars();
    void        SetScrollBarRanges();
    void        InitScrollBars();

    //    SmDocShell *    GetDoc();
    //    SmViewShell *   GetView();
    EditView* GetEditView (void);
    EditEngine* GetEditEngine (void);
    EditEngine* CreateEditEngine (void);

    // Window
    virtual void        SetText(const XubString &rText);
    virtual XubString   GetText();
    virtual void        GetFocus();
    virtual void        LoseFocus();

    ESelection          GetSelection() const;
    void                SetSelection(const ESelection &rSel);

    BOOL                IsEmpty() const;
    BOOL                IsSelected() const;
    BOOL                IsAllSelected() const;
    void                Cut();
    void                Copy();
    void                Paste();
    void                Delete();
    void                SelectAll();
    void                MarkError(const Point &rPos);
    void                SelNextMark();
    void                SelPrevMark();
    BOOL                HasMark(const String &rText) const;

    void ApplyColorConfigValues( const svtools::ColorConfig &rColorCfg );
};

} } // end of namespace ::sd::notes

#endif

<|endoftext|>


<commit_before>/// \file libuobject/uvar.cc

#include <libport/escape.hh>

#include <urbi/uobject.hh>
#include <urbi/ublend-type.hh>
#include <urbi/uexternal.hh>
#include <urbi/usyncclient.hh>

class UVariable {};

namespace urbi
{
  class UVardata
  {
  public:
    UVardata()
    {
    }
    ~UVardata()
    {
    }
  };

  //! UVar initialization
  void
  UVar::__init()
  {
    (*varmap)[name].push_back(this);
    URBI_SEND_COMMAND("if (!isdef(" << name << ")) var " << name);
    vardata = 0; // unused. For internal softdevices only
    this->owned = false;
    assert (dummyUObject);

    createUCallback(dummyUObject->__name,
		    "var",
		    dummyUObject, &UObject::voidfun, name, monitormap, false);
  }

  //! UVar out value (read mode)
  ufloat&
  UVar::out()
  {
    return value.val;
  }

  //! UVar in value (write mode)
  ufloat&
  UVar::in()
  {
    return value.val;
  }

  void
  UVar::setProp(UProperty p, const UValue& v)
  {
    URBI_SEND_COMMAND(name << "->" << urbi::name(p) << "=" << v);
  }

  void
  UVar::setProp(UProperty p, const char* v)
  {
    URBI_SEND_COMMAND(name << "->" << urbi::name(p) << "=" << v);
  }

  void
  UVar::setProp(UProperty p, double v)
  {
    // FIXME: This is not the right way to do it.  Generalize
    // conversions between enums and strings.
    int i = static_cast<int>(v);
    if (p == PROP_BLEND && is_blendtype(i))
      URBI_SEND_COMMAND(name << "->"<< urbi::name(p) << "="
			<< urbi::name(static_cast<UBlendType>(i)));
    else
      URBI_SEND_COMMAND(name << "->"<< urbi::name(p) << "=" << v);
  }

  UValue
  UVar::getProp(UProperty p)
  {
    UMessage* m=
      ((USyncClient&)URBI(())).syncGet("%s->%s",
				       name.c_str(), urbi::name (p));
    UValue v = *m->value;
    delete m;
    return v;
  }

  /*
    UBlendType
    UVar::blend()
    {
    echo("Properties not implemented in remote mode yet.\n");
    return UNORMAL;
    }
  */

  //! UVar destructor.
  UVar::~UVar()
  {
    UVarTable::iterator varmapfind = varmap->find(name);

    if (varmapfind != varmap->end())
      {
	for (std::list<UVar*>::iterator it = varmapfind->second.begin();
	     it != varmapfind->second.end();)
	  if (*it == this)
	    it=varmapfind->second.erase(it);
	  else
	    ++it;

	if (varmapfind->second.empty())
	  varmap->erase(varmapfind);
      }
  }

  //! Set the UVar in "zombie" mode  (the attached UVariable is dead)
  void
  UVar::setZombie ()
  {
    // no effect in remote mode.
  }

  //! Return the internal variable.
  UVariable*
  UVar::variable()
  {
    return 0;
  }

  //! UVar reset  (deep assignement)
  void
  UVar::reset (ufloat n)
  {
    *this = n;
  }

  //! UVar float assignment
  void
  UVar::operator = (ufloat n)
  {
    URBI_SEND_COMMAND(name << "=" << n);
  }

  //! UVar string assignment
  void
  UVar::operator= (const std::string& s)
  {
    URBI_SEND_COMMAND(name << "=\"" << libport::escape(s, '"') << '"');
  }

  //! UVar binary assignment
  void
  UVar::operator = (const UBinary& b)
  {
    getDefaultClient()->sendBin(b.common.data, b.common.size,
				"%s=BIN %d %s;",
				name.c_str(), b.common.size,
				b.getMessage().c_str());
  }

  void
  UVar::operator= (const UImage& i)
  {
    //we don't use UBinary Image ctor because it copies data
    UBinary b;
    b.type = BINARY_IMAGE;
    b.image = i;
    (*this) = b;
    b.common.data = 0; //required, dtor frees data
  }

  void
  UVar::operator= (const USound& i)
  {
    //we don't use UBinary Image ctor because it copies data
    UBinary b;
    b.type = BINARY_SOUND;
    b.sound = i;
    (*this) = b;
    b.common.data = 0; //required, dtor frees data
  }

  void
  UVar::operator= (const UList& l)
  {
    UValue v;
    v.type = DATA_LIST;
    v.list = &const_cast<UList&>(l);
    URBI_SEND_COMMAND(name << "=" << v);
    v.type = DATA_VOID;
    v.list = 0;
  }

  UVar::operator int ()
  {
    return (int) value;
  };

  UVar::operator ufloat ()
  {
    return (ufloat) value;
  };

  UVar::operator std::string ()
  {
    return (std::string) value;
  };

  UVar::operator UBinary()
  {
    return value;
  };

  UVar::operator UBinary*()
  {
    return new UBinary(value.operator UBinary());
  };

  UVar::operator UImage()
  {
    return (UImage) value;
  };

  UVar::operator USound()
  {
    return (USound) value;
  };

  UVar::operator UList()
  {
    return (UList) value;
  };

  //! UVar update
  void
  UVar::__update(UValue& v)
  {
# ifdef LIBURBIDEBUG
    std::cout << "  Variable " << name << " updated to : ";

    switch (v.type)
      {
      case DATA_DOUBLE:
	std::cout << (double)v << std::endl;
	break;
      case DATA_STRING:
	std::cout << (std::string)v << std::endl;
	break;
      case DATA_BINARY:
      case DATA_LIST:
      case DATA_OBJECT:
      case DATA_VOID:
	break;
      }
# endif
    value = v;
  }

  //! set own mode
  void
  UVar::setOwned()
  {
    owned = true;
  }

  //! Get Uvalue type
  UDataType
  UVar::type () const
  {
    return value.type;
  }

  void
  UVar::requestValue()
  {
    //build a getvalue message  that will be parsed and returned by the server
    URBI_SEND_COMMAND(externalModuleTag << "<<"
		      <<'[' << UEM_ASSIGNVALUE << ","
		      << '"' << name << '"' << ',' << name << ']');
  }

  void
  UVar::syncValue ()
  {
    USyncClient&	client = dynamic_cast<USyncClient&> (URBI(()));
    UMessage*		m;
    char		tag[32];

    client.makeUniqueTag(tag);
    m = client.syncGetTag("if (isdef (%s) && !isvoid (%s)) { %s<<%s } else { %s<<1/0 };",
                     tag, 0, name.c_str (), name.c_str (), tag, name.c_str (), tag);
    if (m->type == MESSAGE_DATA)
      __update (*m->value);
  }

} //namespace urbi
<commit_msg>Fix a syntax error in generated code.<commit_after>/// \file libuobject/uvar.cc

#include <libport/escape.hh>

#include <urbi/uobject.hh>
#include <urbi/ublend-type.hh>
#include <urbi/uexternal.hh>
#include <urbi/usyncclient.hh>

class UVariable {};

namespace urbi
{
  class UVardata
  {
  public:
    UVardata()
    {
    }
    ~UVardata()
    {
    }
  };

  //! UVar initialization
  void
  UVar::__init()
  {
    (*varmap)[name].push_back(this);
    URBI_SEND_COMMAND("if (!isdef(" << name << ")) var " << name);
    vardata = 0; // unused. For internal softdevices only
    this->owned = false;
    assert (dummyUObject);

    createUCallback(dummyUObject->__name,
		    "var",
		    dummyUObject, &UObject::voidfun, name, monitormap, false);
  }

  //! UVar out value (read mode)
  ufloat&
  UVar::out()
  {
    return value.val;
  }

  //! UVar in value (write mode)
  ufloat&
  UVar::in()
  {
    return value.val;
  }

  void
  UVar::setProp(UProperty p, const UValue& v)
  {
    URBI_SEND_COMMAND(name << "->" << urbi::name(p) << "=" << v);
  }

  void
  UVar::setProp(UProperty p, const char* v)
  {
    URBI_SEND_COMMAND(name << "->" << urbi::name(p) << "=" << v);
  }

  void
  UVar::setProp(UProperty p, double v)
  {
    // FIXME: This is not the right way to do it.  Generalize
    // conversions between enums and strings.
    int i = static_cast<int>(v);
    if (p == PROP_BLEND && is_blendtype(i))
      URBI_SEND_COMMAND(name << "->"<< urbi::name(p) << "="
			<< urbi::name(static_cast<UBlendType>(i)));
    else
      URBI_SEND_COMMAND(name << "->"<< urbi::name(p) << "=" << v);
  }

  UValue
  UVar::getProp(UProperty p)
  {
    UMessage* m=
      ((USyncClient&)URBI(())).syncGet("%s->%s",
				       name.c_str(), urbi::name (p));
    UValue v = *m->value;
    delete m;
    return v;
  }

  /*
    UBlendType
    UVar::blend()
    {
    echo("Properties not implemented in remote mode yet.\n");
    return UNORMAL;
    }
  */

  //! UVar destructor.
  UVar::~UVar()
  {
    UVarTable::iterator varmapfind = varmap->find(name);

    if (varmapfind != varmap->end())
      {
	for (std::list<UVar*>::iterator it = varmapfind->second.begin();
	     it != varmapfind->second.end();)
	  if (*it == this)
	    it=varmapfind->second.erase(it);
	  else
	    ++it;

	if (varmapfind->second.empty())
	  varmap->erase(varmapfind);
      }
  }

  //! Set the UVar in "zombie" mode  (the attached UVariable is dead)
  void
  UVar::setZombie ()
  {
    // no effect in remote mode.
  }

  //! Return the internal variable.
  UVariable*
  UVar::variable()
  {
    return 0;
  }

  //! UVar reset  (deep assignement)
  void
  UVar::reset (ufloat n)
  {
    *this = n;
  }

  //! UVar float assignment
  void
  UVar::operator = (ufloat n)
  {
    URBI_SEND_COMMAND(name << "=" << n);
  }

  //! UVar string assignment
  void
  UVar::operator= (const std::string& s)
  {
    URBI_SEND_COMMAND(name << "=\"" << libport::escape(s, '"') << '"');
  }

  //! UVar binary assignment
  void
  UVar::operator = (const UBinary& b)
  {
    getDefaultClient()->sendBin(b.common.data, b.common.size,
				"%s=BIN %d %s;",
				name.c_str(), b.common.size,
				b.getMessage().c_str());
  }

  void
  UVar::operator= (const UImage& i)
  {
    //we don't use UBinary Image ctor because it copies data
    UBinary b;
    b.type = BINARY_IMAGE;
    b.image = i;
    (*this) = b;
    b.common.data = 0; //required, dtor frees data
  }

  void
  UVar::operator= (const USound& i)
  {
    //we don't use UBinary Image ctor because it copies data
    UBinary b;
    b.type = BINARY_SOUND;
    b.sound = i;
    (*this) = b;
    b.common.data = 0; //required, dtor frees data
  }

  void
  UVar::operator= (const UList& l)
  {
    UValue v;
    v.type = DATA_LIST;
    v.list = &const_cast<UList&>(l);
    URBI_SEND_COMMAND(name << "=" << v);
    v.type = DATA_VOID;
    v.list = 0;
  }

  UVar::operator int ()
  {
    return (int) value;
  };

  UVar::operator ufloat ()
  {
    return (ufloat) value;
  };

  UVar::operator std::string ()
  {
    return (std::string) value;
  };

  UVar::operator UBinary()
  {
    return value;
  };

  UVar::operator UBinary*()
  {
    return new UBinary(value.operator UBinary());
  };

  UVar::operator UImage()
  {
    return (UImage) value;
  };

  UVar::operator USound()
  {
    return (USound) value;
  };

  UVar::operator UList()
  {
    return (UList) value;
  };

  //! UVar update
  void
  UVar::__update(UValue& v)
  {
# ifdef LIBURBIDEBUG
    std::cout << "  Variable " << name << " updated to : ";

    switch (v.type)
      {
      case DATA_DOUBLE:
	std::cout << (double)v << std::endl;
	break;
      case DATA_STRING:
	std::cout << (std::string)v << std::endl;
	break;
      case DATA_BINARY:
      case DATA_LIST:
      case DATA_OBJECT:
      case DATA_VOID:
	break;
      }
# endif
    value = v;
  }

  //! set own mode
  void
  UVar::setOwned()
  {
    owned = true;
  }

  //! Get Uvalue type
  UDataType
  UVar::type () const
  {
    return value.type;
  }

  void
  UVar::requestValue()
  {
    //build a getvalue message  that will be parsed and returned by the server
    URBI_SEND_COMMAND(externalModuleTag << "<<"
		      <<'[' << UEM_ASSIGNVALUE << ","
		      << '"' << name << '"' << ',' << name << ']');
  }

  void
  UVar::syncValue ()
  {
    USyncClient&	client = dynamic_cast<USyncClient&> (URBI(()));
    UMessage*		m;
    char		tag[32];

    client.makeUniqueTag(tag);
    m = client.syncGetTag("{if (isdef (%s) && !isvoid (%s)) { %s<<%s } else { %s<<1/0 }};",
                     tag, 0, name.c_str (), name.c_str (), tag, name.c_str (), tag);
    if (m->type == MESSAGE_DATA)
      __update (*m->value);
  }

} //namespace urbi
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2007-2010, Gostai S.A.S.
 *
 * This software is provided "as is" without warranty of any kind,
 * either expressed or implied, including but not limited to the
 * implied warranties of fitness for a particular purpose.
 *
 * See the LICENSE file for more information.
 */

#include <libport/lexical-cast.hh>

#include <libport/cli.hh>
#include <libport/debug.hh>
#include <libport/foreach.hh>
#include <libport/sysexits.hh>

#include <urbi/uabstractclient.hh>
#include <urbi/uclient.hh>
#include <urbi/usyncclient.hh>

#include <bin/tests.hh>

GD_INIT();

// Use this semaphore in tests that require one.  dump() takes it.
libport::Semaphore dumpSem;

static
void
usage()
{
  std::cout <<
    "Usage: " << program_name() << " [OPTION]... TEST...\n"
    "\n"
    "Options:\n"
    "  -h, --help            display this message and exit\n"
    "  -H, --host ADDR   the host running the Urbi server"
              << " [" << urbi::UClient::default_host() << "]\n"
    "  -p, --port PORT       tcp port URBI will listen to"
              << " [" << urbi::UClient::URBI_PORT << "]\n"
    "  -r, --port-file FILE  file containing the port to listen to\n"
              << libport::exit(EX_OK);
}

static char
char_of(urbi::UMessageType t)
{
  switch (t)
  {
    case urbi::MESSAGE_DATA:   return 'D';
    case urbi::MESSAGE_ERROR:  return 'E';
    case urbi::MESSAGE_SYSTEM: return 'S';
    default:                   return '?';
  }
}

urbi::UCallbackAction
log(const urbi::UMessage& msg)
{
  VERBOSE("Recv: " << msg);
  return urbi::URBI_CONTINUE;
}

urbi::UCallbackAction
dump(const urbi::UMessage& msg)
{
  log(msg);

  std::cout << char_of(msg.type) << ' ' << msg.tag << ' ';
  switch (msg.type)
  {
    case urbi::MESSAGE_DATA:
      std::cout << *msg.value << std::endl;
      break;

    case urbi::MESSAGE_ERROR:
    case urbi::MESSAGE_SYSTEM:
      std::cout << msg.message << std::endl;
      break;
  }

  dumpSem++;
  return urbi::URBI_CONTINUE;
}

urbi::UCallbackAction
removeOnZero(const urbi::UMessage& msg)
{
  VERBOSE("removeOnZero");
  dump(msg);
  if (msg.type == urbi::MESSAGE_DATA
      && msg.value->type == urbi::DATA_DOUBLE
      && msg.value->val == 0)
    return urbi::URBI_REMOVE;
  return urbi::URBI_CONTINUE;
}

std::string
sget_error(urbi::USyncClient& c, const std::string& msg)
{
  VERBOSE("sget_error: Asking " << msg);
  urbi::UMessage* m = c.syncGet(msg);
  aver(m && m->type == urbi::MESSAGE_ERROR);
  std::string res(m->message);
  delete m;
  return res;
}

int
main(int argc, char* argv[])
{
  // argv[0] = basename(argv[0]).
  const char* argv0 = argv[0];
  if (char* cp = strrchr(argv[0], '/'))
    argv[0] = cp + 1;
  libport::program_initialize(argc, argv);
  std::string host = urbi::UClient::default_host();
  int port = urbi::UAbstractClient::URBI_PORT;

  VERBOSE("This is " << argv0);
  VERBOSE("Processing option");
  for (int i = 1; i < argc; ++i)
  {
    std::string arg = argv[i];
    if (arg == "--help" || arg == "-h")
      usage();
    else if (arg == "--host" || arg == "-H")
      host = libport::convert_argument<std::string>(arg, argv[++i]);
    else if (arg == "--port" || arg == "-P")
      port = libport::convert_argument<unsigned>(arg, argv[++i]);
    else if (arg == "--port-file" || arg == "-r")
      port =
        (libport::file_contents_get<int>
         (libport::convert_argument<const char*>(arg, argv[++i])));
    else
      libport::invalid_option(arg);
  }

  urbi::UClient client(host, port);
  VERBOSE("client(" << host << ", " << port << ") @ " << &client);
  client.setErrorCallback(urbi::callback(&log));
  client.setCallback(urbi::callback(&log), "log");
  if (client.error())
    std::cerr << "Failed to set up properly the client" << std::endl
              << libport::exit(EX_SOFTWARE);

  urbi::USyncClient syncClient(host, port);
  VERBOSE("syncClient(" << host << ", " << port << ") @ " << &syncClient);
  syncClient.setErrorCallback(urbi::callback(&log));
  syncClient.setCallback(urbi::callback(&log), "log");
  if (syncClient.error())
    std::cerr << "Failed to set up properly the syncClient" << std::endl
              << libport::exit(EX_SOFTWARE);

  VERBOSE("Starting");

  test(client, syncClient);

  VERBOSE("Epilogue, Sleep 3s");
  sleep(3);

  VERBOSE("Shutting down");
  // Handle the case when the other connection is down.
  SSEND("disown({ sleep(0.5); shutdown })|; quit;");
  SEND("shutdown;");

  // Don't close the connection too soon, as it may result in the
  // "shutdown" messages to be dropped when the connection is cut.
  // FIXME: rather, wait for the deconnection from the server.
  sleep(1);
  VERBOSE("End");
}
<commit_msg>SDK Remote: tests: determinism.<commit_after>/*
 * Copyright (C) 2007-2011, Gostai S.A.S.
 *
 * This software is provided "as is" without warranty of any kind,
 * either expressed or implied, including but not limited to the
 * implied warranties of fitness for a particular purpose.
 *
 * See the LICENSE file for more information.
 */

#include <libport/lexical-cast.hh>

#include <libport/cli.hh>
#include <libport/debug.hh>
#include <libport/foreach.hh>
#include <libport/sysexits.hh>

#include <urbi/uabstractclient.hh>
#include <urbi/uclient.hh>
#include <urbi/usyncclient.hh>

#include <bin/tests.hh>

GD_INIT();

// Use this semaphore in tests that require one.  dump() takes it.
libport::Semaphore dumpSem;

static
void
usage()
{
  std::cout <<
    "Usage: " << program_name() << " [OPTION]... TEST...\n"
    "\n"
    "Options:\n"
    "  -h, --help            display this message and exit\n"
    "  -H, --host ADDR   the host running the Urbi server"
              << " [" << urbi::UClient::default_host() << "]\n"
    "  -p, --port PORT       tcp port URBI will listen to"
              << " [" << urbi::UClient::URBI_PORT << "]\n"
    "  -r, --port-file FILE  file containing the port to listen to\n"
              << libport::exit(EX_OK);
}

static char
char_of(urbi::UMessageType t)
{
  switch (t)
  {
    case urbi::MESSAGE_DATA:   return 'D';
    case urbi::MESSAGE_ERROR:  return 'E';
    case urbi::MESSAGE_SYSTEM: return 'S';
    default:                   return '?';
  }
}

urbi::UCallbackAction
log(const urbi::UMessage& msg)
{
  VERBOSE("Recv: " << msg);
  return urbi::URBI_CONTINUE;
}

urbi::UCallbackAction
dump(const urbi::UMessage& msg)
{
  log(msg);

  std::cout << char_of(msg.type) << ' ' << msg.tag << ' ';
  switch (msg.type)
  {
    case urbi::MESSAGE_DATA:
      std::cout << *msg.value << std::endl;
      break;

    case urbi::MESSAGE_ERROR:
    case urbi::MESSAGE_SYSTEM:
      std::cout << msg.message << std::endl;
      break;
  }

  dumpSem++;
  return urbi::URBI_CONTINUE;
}

urbi::UCallbackAction
removeOnZero(const urbi::UMessage& msg)
{
  VERBOSE("removeOnZero");
  dump(msg);
  if (msg.type == urbi::MESSAGE_DATA
      && msg.value->type == urbi::DATA_DOUBLE
      && msg.value->val == 0)
    return urbi::URBI_REMOVE;
  return urbi::URBI_CONTINUE;
}

std::string
sget_error(urbi::USyncClient& c, const std::string& msg)
{
  VERBOSE("sget_error: Asking " << msg);
  urbi::UMessage* m = c.syncGet(msg);
  aver(m && m->type == urbi::MESSAGE_ERROR);
  std::string res(m->message);
  delete m;
  return res;
}

// Cannot make a template here, as we would like to return by copy.
# define MAKE_CLIENT(Type, Name)                                        \
  urbi::Type Name(host, port);                                          \
  VERBOSE(#Name "(" << host << ", " << port << ") @ " << &Name);        \
  Name.setErrorCallback(urbi::callback(&log));                          \
  Name.setCallback(urbi::callback(&log), "log");                        \
  if (Name.error())                                                     \
    std::cerr << "Failed to set up properly the " #Name << std::endl    \
              << libport::exit(EX_SOFTWARE);                            \
  /* Wait to be set up. */                                              \
  Name.waitForKernelVersion();                                          \
  VERBOSE(#Name " received Kernel Version")

int
main(int argc, char* argv[])
{
  // argv[0] = basename(argv[0]).
  const char* argv0 = argv[0];
  if (char* cp = strrchr(argv[0], '/'))
    argv[0] = cp + 1;
  libport::program_initialize(argc, argv);
  std::string host = urbi::UClient::default_host();
  int port = urbi::UAbstractClient::URBI_PORT;

  VERBOSE("This is " << argv0);
  VERBOSE("Processing option");
  for (int i = 1; i < argc; ++i)
  {
    std::string arg = argv[i];
    if (arg == "--help" || arg == "-h")
      usage();
    else if (arg == "--host" || arg == "-H")
      host = libport::convert_argument<std::string>(arg, argv[++i]);
    else if (arg == "--port" || arg == "-P")
      port = libport::convert_argument<unsigned>(arg, argv[++i]);
    else if (arg == "--port-file" || arg == "-r")
      port =
        (libport::file_contents_get<int>
         (libport::convert_argument<const char*>(arg, argv[++i])));
    else
      libport::invalid_option(arg);
  }

  MAKE_CLIENT(UClient, client);
  MAKE_CLIENT(USyncClient, syncClient);

  VERBOSE("Starting");
  test(client, syncClient);

  VERBOSE("Epilogue, Sleep 3s");
  sleep(3);

  VERBOSE("Shutting down");
  // Handle the case when the other connection is down.
  SSEND("disown({ sleep(0.5); shutdown })|; quit;");
  SEND("shutdown;");

  // Don't close the connection too soon, as it may result in the
  // "shutdown" messages to be dropped when the connection is cut.
  // FIXME: rather, wait for the deconnection from the server.
  sleep(1);
  VERBOSE("End");
}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Monteverdi2
  Language:  C++

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See Copyright.txt for details.

  Monteverdi2 is distributed under the CeCILL licence version 2. See
  Licence_CeCILL_V2-en.txt or
  http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more details.

  This software is distributed WITHOUT ANY WARRANTY; without even
  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "mvdI18nApplication.h"

//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.

//
// System includes (sorted by alphabetic order)

//
// OTB includes (sorted by alphabetic order)

//
// Monteverdi includes (sorted by alphabetic order)

//
// Class implementation.
namespace mvd
{
/*
  TRANSLATOR mvd::I18nApplication

  Necessary for lupdate to be aware of C++ namespaces.

  Context comment for translator.
*/

/*******************************************************************************/
I18nApplication
::I18nApplication( int& argc, char** argv ) :
  QApplication( argc, argv ),
  m_IsRunningFromBuildDir( false )
{
  InitializeLocale();
}

/*******************************************************************************/
I18nApplication
::~I18nApplication()
{
}

/*******************************************************************************/
void
I18nApplication
::InitializeLocale()
{
  QTextCodec::setCodecForTr( QTextCodec::codecForName( "utf8" ) );

  //
  // 1. default UI language is english (no translation).
  QLocale sys_lc( QLocale::system() );
  if( sys_lc.language() == QLocale::C ||
      ( sys_lc.language() == QLocale::English &&
        sys_lc.country() == QLocale::UnitedStates ) )
    {
    return;
    }

  //
  // 2. Choose i18n path between build dir and install dir.
  QDir i18n_dir;
  QDir bin_dir( QDir::cleanPath( QCoreApplication::applicationDirPath() ) );
  QDir build_i18n_dir( bin_dir );

  // If build dir is identified...
  if( build_i18n_dir.exists( "../i18n" )
         && build_i18n_dir.cd( "../i18n" )
         && build_i18n_dir.exists( "../" Monteverdi2_CONFIGURE_FILE )
       || build_i18n_dir.exists( "../../i18n" )
         && build_i18n_dir.cd( "../../i18n" )
         && build_i18n_dir.exists( "../" Monteverdi2_CONFIGURE_FILE ) )
    {
    m_IsRunningFromBuildDir = true;

    // ...use build dir as prioritary load path for translation.
    i18n_dir = build_i18n_dir;

    // TODO: Use log system to trace message.
    qDebug()
      << tr( "Running from build directory '%1'." ).arg( bin_dir.path() );
    }
  // Otherwise...
  else
    {
    m_IsRunningFromBuildDir = false;

    QDir install_i18n_dir( QDir::cleanPath( Monteverdi2_INSTALL_DATA_I18N_DIR ) );
    // ...if install data dir is identified
    if( install_i18n_dir.exists() )
      {
      // ...use install data dir as load path for translation.
      i18n_dir = install_i18n_dir;

      // TODO: Use log system to trace message.
      qDebug()
        << tr( "Running from install directory '%1'." ).arg( Monteverdi2_INSTALL_BIN_DIR );
      }
    // Otherwise
    else
      {
      QString message(
        tr( "Failed to access translation-files directory '%1'." )
        .arg( install_i18n_dir.path() )
      );

      // TODO: Use log system to trace error while loading locale translation file.

      qDebug() << message;

      // TODO: morph into better HMI design.
      QMessageBox::critical( NULL, tr( "Critical error!" ), message );

      return;
      }
    }

  //
  // 3.1 Stack Qt translator.
  LoadAndInstallTranslator(
    "qt_" + sys_lc.name(),
    QLibraryInfo::location( QLibraryInfo::TranslationsPath  )
  );

  //
  // 3.2 Stack Monteverdi2 translator as prioritary over Qt translator.
  LoadAndInstallTranslator( sys_lc.name(), i18n_dir.path() );

  // TODO: Record locale translation filename(s) used in UI component (e.g.
  // AboutDialog, Settings dialog, Information dialog etc.)
}

/*******************************************************************************/
bool
I18nApplication
::LoadAndInstallTranslator(const QString& filename,
                           const QString& directory,
                           const QString& searchDelimiters,
                           const QString& suffix )
{
  QString filename_ext(
    filename +
    ( suffix.isNull()
      ? ".qm"
      : suffix )
  );

  // (a) Do need to new QTranslator() here!
  QTranslator* lc_translator = new QTranslator( this );

  if( !lc_translator->load( filename, directory, searchDelimiters, suffix ) )
    {
    QString message(
      tr( "Failed to load '%1' translation file from '%2'." )
      .arg( filename_ext )
      .arg( directory )
    );

    // TODO: Use log system to trace error while loading locale translation file.

    qWarning() << message;

    // TODO: morph into better HMI design.
    QMessageBox::warning( NULL, tr( "Warning!" ), message );

    return false;
    }

  // (a) ...because QTranslator needs to be alive during the whole
  // lifespan of the application.
  QCoreApplication::installTranslator( lc_translator );

  QString message(
    tr( "Successfully loaded '%1' translation file from '%2'." )
    .arg( filename_ext )
    .arg( directory )
  );

  // TODO: Log locale translation filename used.

  qDebug() << message;

  return true;
}

/*******************************************************************************/
/* SLOTS                                                                       */
/*******************************************************************************/

} // end namespace 'mvd'
<commit_msg>WRG: add parentheses to keep compiler quiet<commit_after>/*=========================================================================

  Program:   Monteverdi2
  Language:  C++

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See Copyright.txt for details.

  Monteverdi2 is distributed under the CeCILL licence version 2. See
  Licence_CeCILL_V2-en.txt or
  http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more details.

  This software is distributed WITHOUT ANY WARRANTY; without even
  the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
  PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "mvdI18nApplication.h"

//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.

//
// System includes (sorted by alphabetic order)

//
// OTB includes (sorted by alphabetic order)

//
// Monteverdi includes (sorted by alphabetic order)

//
// Class implementation.
namespace mvd
{
/*
  TRANSLATOR mvd::I18nApplication

  Necessary for lupdate to be aware of C++ namespaces.

  Context comment for translator.
*/

/*******************************************************************************/
I18nApplication
::I18nApplication( int& argc, char** argv ) :
  QApplication( argc, argv ),
  m_IsRunningFromBuildDir( false )
{
  InitializeLocale();
}

/*******************************************************************************/
I18nApplication
::~I18nApplication()
{
}

/*******************************************************************************/
void
I18nApplication
::InitializeLocale()
{
  QTextCodec::setCodecForTr( QTextCodec::codecForName( "utf8" ) );

  //
  // 1. default UI language is english (no translation).
  QLocale sys_lc( QLocale::system() );
  if( sys_lc.language() == QLocale::C ||
      ( sys_lc.language() == QLocale::English &&
        sys_lc.country() == QLocale::UnitedStates ) )
    {
    return;
    }

  //
  // 2. Choose i18n path between build dir and install dir.
  QDir i18n_dir;
  QDir bin_dir( QDir::cleanPath( QCoreApplication::applicationDirPath() ) );
  QDir build_i18n_dir( bin_dir );

  // If build dir is identified...
  if( (build_i18n_dir.exists( "../i18n" )
         && build_i18n_dir.cd( "../i18n" )
         && build_i18n_dir.exists( "../" Monteverdi2_CONFIGURE_FILE ))
       || (build_i18n_dir.exists( "../../i18n" )
         && build_i18n_dir.cd( "../../i18n" )
         && build_i18n_dir.exists( "../" Monteverdi2_CONFIGURE_FILE )) )
    {
    m_IsRunningFromBuildDir = true;

    // ...use build dir as prioritary load path for translation.
    i18n_dir = build_i18n_dir;

    // TODO: Use log system to trace message.
    qDebug()
      << tr( "Running from build directory '%1'." ).arg( bin_dir.path() );
    }
  // Otherwise...
  else
    {
    m_IsRunningFromBuildDir = false;

    QDir install_i18n_dir( QDir::cleanPath( Monteverdi2_INSTALL_DATA_I18N_DIR ) );
    // ...if install data dir is identified
    if( install_i18n_dir.exists() )
      {
      // ...use install data dir as load path for translation.
      i18n_dir = install_i18n_dir;

      // TODO: Use log system to trace message.
      qDebug()
        << tr( "Running from install directory '%1'." ).arg( Monteverdi2_INSTALL_BIN_DIR );
      }
    // Otherwise
    else
      {
      QString message(
        tr( "Failed to access translation-files directory '%1'." )
        .arg( install_i18n_dir.path() )
      );

      // TODO: Use log system to trace error while loading locale translation file.

      qDebug() << message;

      // TODO: morph into better HMI design.
      QMessageBox::critical( NULL, tr( "Critical error!" ), message );

      return;
      }
    }

  //
  // 3.1 Stack Qt translator.
  LoadAndInstallTranslator(
    "qt_" + sys_lc.name(),
    QLibraryInfo::location( QLibraryInfo::TranslationsPath  )
  );

  //
  // 3.2 Stack Monteverdi2 translator as prioritary over Qt translator.
  LoadAndInstallTranslator( sys_lc.name(), i18n_dir.path() );

  // TODO: Record locale translation filename(s) used in UI component (e.g.
  // AboutDialog, Settings dialog, Information dialog etc.)
}

/*******************************************************************************/
bool
I18nApplication
::LoadAndInstallTranslator(const QString& filename,
                           const QString& directory,
                           const QString& searchDelimiters,
                           const QString& suffix )
{
  QString filename_ext(
    filename +
    ( suffix.isNull()
      ? ".qm"
      : suffix )
  );

  // (a) Do need to new QTranslator() here!
  QTranslator* lc_translator = new QTranslator( this );

  if( !lc_translator->load( filename, directory, searchDelimiters, suffix ) )
    {
    QString message(
      tr( "Failed to load '%1' translation file from '%2'." )
      .arg( filename_ext )
      .arg( directory )
    );

    // TODO: Use log system to trace error while loading locale translation file.

    qWarning() << message;

    // TODO: morph into better HMI design.
    QMessageBox::warning( NULL, tr( "Warning!" ), message );

    return false;
    }

  // (a) ...because QTranslator needs to be alive during the whole
  // lifespan of the application.
  QCoreApplication::installTranslator( lc_translator );

  QString message(
    tr( "Successfully loaded '%1' translation file from '%2'." )
    .arg( filename_ext )
    .arg( directory )
  );

  // TODO: Log locale translation filename used.

  qDebug() << message;

  return true;
}

/*******************************************************************************/
/* SLOTS                                                                       */
/*******************************************************************************/

} // end namespace 'mvd'
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkGDCMSeriesFileNames.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#ifndef _itkGDCMSeriesFileNames_h
#define _itkGDCMSeriesFileNames_h

#include "itkGDCMSeriesFileNames.h"
#include <gdcm.h>
#include <itksys/SystemTools.hxx>

#include <vector>
#include <string>

namespace itk
{

const std::vector<std::string> &GDCMSeriesFileNames::GetInputFileNames()
{
  // Get the DICOM filenames from the directory
  gdcmSerieHeaderHelper *helper = new gdcmSerieHeaderHelper();
  helper->SetDirectory( m_InputDirectory.c_str() );
  helper->OrderGdcmFileList();
  //We assume that there is only one study / one serie

  std::list<gdcmHeaderHelper*> flist = helper->GetGdcmFileList();
  if( flist.size() )
    {
    for(std::list<gdcmHeaderHelper*>::iterator it = flist.begin();
        it != flist.end(); ++it )
      {
      std::string foo = (*it)->GetFileName();
      m_InputFileNames.push_back( foo );
      }
    }
  else
    {
    itkDebugMacro(<<"No files were found");
    }
  delete helper;

  return m_InputFileNames;
}

const std::vector<std::string> &GDCMSeriesFileNames::GetOutputFileNames()
{
  // We are trying to extract the original filename and compose it with a path:

  //There is two different approach if directory does not exist:
  // 1. Exit
  // 2. Mkdir
  //bool SystemTools::FileExists(const char* filename)
  //bool SystemTools::FileIsDirectory(const char* name)

  if( m_OutputDirectory.empty() )
    {
    itkDebugMacro(<<"No output directory was specified");
    m_OutputFileNames.clear();
    return m_OutputFileNames;
    }

  itksys::SystemTools::ConvertToUnixSlashes( m_OutputDirectory );
  if(m_OutputDirectory[m_OutputDirectory.size()-1] != '/')
    {
    m_OutputDirectory += '/';
    }

  if( m_InputFileNames.size() )
    {
    for(std::vector<std::string>::const_iterator it = m_InputFileNames.begin();
        it != m_InputFileNames.end(); ++it )
        {
        std::string filename =
          m_OutputDirectory + itksys::SystemTools::GetFilenameName( *it );

        //std::cerr << "filename:" << filename << std::endl;
        m_OutputFileNames.push_back( filename );
        }
      }
    else
      {
      itkDebugMacro(<<"No files were found.");
      m_OutputFileNames.clear();
      }

  return m_OutputFileNames;
}

void GDCMSeriesFileNames::PrintSelf(std::ostream& os, Indent indent) const
{
  Superclass::PrintSelf(os, indent);

  unsigned int i;
  os << indent << "InputDirectory: " << m_InputDirectory << std::endl;
  for (i = 0; i < m_InputFileNames.size(); i++)
    {
    os << indent << "InputFilenames[" << i << "]: " << m_InputFileNames[i] << std::endl;
    }

  os << indent << "OutputDirectory: " << m_OutputDirectory << std::endl;
  for (i = 0; i < m_OutputFileNames.size(); i++)
    {
    os << indent << "OutputFilenames[" << i << "]: " << m_OutputFileNames[i] << std::endl;
    }
}
} //namespace ITK

#endif
<commit_msg>BUG: Temporary leave a mem  leak<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkGDCMSeriesFileNames.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#ifndef _itkGDCMSeriesFileNames_h
#define _itkGDCMSeriesFileNames_h

#include "itkGDCMSeriesFileNames.h"
#include <gdcm.h>
#include <itksys/SystemTools.hxx>

#include <vector>
#include <string>

namespace itk
{

const std::vector<std::string> &GDCMSeriesFileNames::GetInputFileNames()
{
  // Get the DICOM filenames from the directory
  gdcmSerieHeaderHelper *helper = new gdcmSerieHeaderHelper();
  helper->SetDirectory( m_InputDirectory.c_str() );
  helper->OrderGdcmFileList();
  //We assume that there is only one study / one serie

  std::list<gdcmHeaderHelper*> flist = helper->GetGdcmFileList();
  if( flist.size() )
    {
    for(std::list<gdcmHeaderHelper*>::iterator it = flist.begin();
        it != flist.end(); ++it )
      {
      std::string foo = (*it)->GetFileName();
      m_InputFileNames.push_back( foo );
      }
    }
  else
    {
    itkDebugMacro(<<"No files were found");
    }
  //delete helper;

  return m_InputFileNames;
}

const std::vector<std::string> &GDCMSeriesFileNames::GetOutputFileNames()
{
  // We are trying to extract the original filename and compose it with a path:

  //There is two different approach if directory does not exist:
  // 1. Exit
  // 2. Mkdir
  //bool SystemTools::FileExists(const char* filename)
  //bool SystemTools::FileIsDirectory(const char* name)

  if( m_OutputDirectory.empty() )
    {
    itkDebugMacro(<<"No output directory was specified");
    m_OutputFileNames.clear();
    return m_OutputFileNames;
    }

  itksys::SystemTools::ConvertToUnixSlashes( m_OutputDirectory );
  if(m_OutputDirectory[m_OutputDirectory.size()-1] != '/')
    {
    m_OutputDirectory += '/';
    }

  if( m_InputFileNames.size() )
    {
    for(std::vector<std::string>::const_iterator it = m_InputFileNames.begin();
        it != m_InputFileNames.end(); ++it )
        {
        std::string filename =
          m_OutputDirectory + itksys::SystemTools::GetFilenameName( *it );

        //std::cerr << "filename:" << filename << std::endl;
        m_OutputFileNames.push_back( filename );
        }
      }
    else
      {
      itkDebugMacro(<<"No files were found.");
      m_OutputFileNames.clear();
      }

  return m_OutputFileNames;
}

void GDCMSeriesFileNames::PrintSelf(std::ostream& os, Indent indent) const
{
  Superclass::PrintSelf(os, indent);

  unsigned int i;
  os << indent << "InputDirectory: " << m_InputDirectory << std::endl;
  for (i = 0; i < m_InputFileNames.size(); i++)
    {
    os << indent << "InputFilenames[" << i << "]: " << m_InputFileNames[i] << std::endl;
    }

  os << indent << "OutputDirectory: " << m_OutputDirectory << std::endl;
  for (i = 0; i < m_OutputFileNames.size(); i++)
    {
    os << indent << "OutputFilenames[" << i << "]: " << m_OutputFileNames[i] << std::endl;
    }
}
} //namespace ITK

#endif
<|endoftext|>