<commit_before>#include "Moves/En_Passant.h"

#include "Moves/Direction.h"
#include "Moves/Pawn_Capture.h"
#include "Game/Board.h"

//! Create an en passant move.
//
//! \param color The color of the moving pawn.
//! \param dir The direction of the capture.
//! \param file_start The file of the square where the pawn starts.
En_Passant::En_Passant(Color color, Direction dir, char file_start) :
    Pawn_Capture(color, dir, file_start, color == WHITE ? 5 : 4)
{
    is_en_passant_move = true;
}

//! The pawn must end up on the square that was skipped by an immediately preceding Pawn_Double_Move.
//
//! \param board The board state just prior to the move.
//! \returns Whether the end square is a valid en passant target.
bool En_Passant::move_specific_legal(const Board& board) const
{
    return board.is_en_passant_targetable(end());
}

//! Implement capturing the pawn on the square to the side of the starting square.
//
//! \param board The board on which the capture is occurring.
void En_Passant::side_effects(Board& board) const
{
    board.remove_piece({end().file(), start().rank()});
    Pawn_Move::side_effects(board);
}
<commit_msg>Use immediate base class method<commit_after>#include "Moves/En_Passant.h"

#include "Moves/Direction.h"
#include "Moves/Pawn_Capture.h"
#include "Game/Board.h"

//! Create an en passant move.
//
//! \param color The color of the moving pawn.
//! \param dir The direction of the capture.
//! \param file_start The file of the square where the pawn starts.
En_Passant::En_Passant(Color color, Direction dir, char file_start) :
    Pawn_Capture(color, dir, file_start, color == WHITE ? 5 : 4)
{
    is_en_passant_move = true;
}

//! The pawn must end up on the square that was skipped by an immediately preceding Pawn_Double_Move.
//
//! \param board The board state just prior to the move.
//! \returns Whether the end square is a valid en passant target.
bool En_Passant::move_specific_legal(const Board& board) const
{
    return board.is_en_passant_targetable(end());
}

//! Implement capturing the pawn on the square to the side of the starting square.
//
//! \param board The board on which the capture is occurring.
void En_Passant::side_effects(Board& board) const
{
    board.remove_piece({end().file(), start().rank()});
    Pawn_Capture::side_effects(board);
}
<|endoftext|>


<commit_before>/*
 * Launch and manage WAS child processes.
 *
 * author: Max Kellermann <mk@cm4all.com>
 */

#include "was_stock.hxx"
#include "was_quark.h"
#include "was_launch.hxx"
#include "stock/MapStock.hxx"
#include "stock/Stock.hxx"
#include "stock/Class.hxx"
#include "stock/Item.hxx"
#include "child_manager.hxx"
#include "async.hxx"
#include "net/ConnectSocket.hxx"
#include "spawn/ChildOptions.hxx"
#include "pool.hxx"
#include "event/Event.hxx"
#include "event/Callback.hxx"
#include "util/ConstBuffer.hxx"
#include "util/Cast.hxx"

#include <daemon/log.h>

#include <glib.h>
#include <assert.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <signal.h>
#include <stdlib.h>

struct WasChildParams {
    const char *executable_path;

    ConstBuffer<const char *> args;

    const ChildOptions &options;

    WasChildParams(const char *_executable_path,
                   ConstBuffer<const char *> _args,
                   const ChildOptions &_options)
        :executable_path(_executable_path), args(_args),
         options(_options) {}

    const char *GetStockKey(struct pool &pool) const;
};

struct WasChild final : PoolStockItem {
    WasProcess process;
    Event event;

    explicit WasChild(struct pool &_pool, CreateStockItem c)
        :PoolStockItem(_pool, c) {}

    ~WasChild() override;

    void EventCallback(evutil_socket_t fd, short events);

    /* virtual methods from class StockItem */
    bool Borrow(gcc_unused void *ctx) override {
        event.Delete();
        return true;
    }

    bool Release(gcc_unused void *ctx) override {
        static constexpr struct timeval tv = {
            .tv_sec = 300,
            .tv_usec = 0,
        };

        event.Add(tv);
        return true;
    }
};

const char *
WasChildParams::GetStockKey(struct pool &pool) const
{
    const char *key = executable_path;
    for (auto i : args)
        key = p_strcat(&pool, key, " ", i, nullptr);

    for (auto i : options.env)
        key = p_strcat(&pool, key, "$", i, nullptr);

    char options_buffer[4096];
    *options.MakeId(options_buffer) = 0;
    if (*options_buffer != 0)
        key = p_strcat(&pool, key, options_buffer, nullptr);

    return key;
}

static void
was_child_callback(gcc_unused int status, void *ctx)
{
    WasChild *child = (WasChild *)ctx;

    child->process.pid = -1;
}

/*
 * libevent callback
 *
 */

inline void
WasChild::EventCallback(evutil_socket_t fd, short events)
{
    assert(fd == process.control_fd);

    if ((events & EV_TIMEOUT) == 0) {
        char buffer;
        ssize_t nbytes = recv(fd, &buffer, sizeof(buffer), MSG_DONTWAIT);
        if (nbytes < 0)
            daemon_log(2, "error on idle WAS control connection: %s\n",
                       strerror(errno));
        else if (nbytes > 0)
            daemon_log(2, "unexpected data from idle WAS control connection\n");
    }

    InvokeIdleDisconnect();
    pool_commit();
}

/*
 * stock class
 *
 */

static void
was_stock_create(gcc_unused void *ctx,
                 struct pool &parent_pool, CreateStockItem c,
                 void *info,
                 gcc_unused struct pool &caller_pool,
                 gcc_unused struct async_operation_ref &async_ref)
{
    WasChildParams *params = (WasChildParams *)info;

    auto &pool = *pool_new_linear(&parent_pool, "was_child", 2048);
    auto *child = NewFromPool<WasChild>(pool, pool, c);

    assert(params != nullptr);
    assert(params->executable_path != nullptr);

    GError *error = nullptr;
    if (!was_launch(&child->process, params->executable_path,
                    params->args,
                    params->options,
                    &error)) {
        child->InvokeCreateError(error);
        return;
    }

    child_register(child->process.pid, child->GetStockName(),
                   was_child_callback, child);

    child->event.Set(child->process.control_fd, EV_READ|EV_TIMEOUT,
                     MakeEventCallback(WasChild, EventCallback), child);

    child->InvokeCreateSuccess();
}

WasChild::~WasChild()
{
    if (process.pid >= 0)
        child_kill(process.pid);

    if (process.control_fd >= 0)
        event.Delete();

    process.Close();
}

static constexpr StockClass was_stock_class = {
    .create = was_stock_create,
};

/*
 * interface
 *
 */

StockMap *
was_stock_new(struct pool *pool, unsigned limit, unsigned max_idle)
{
    return hstock_new(*pool, was_stock_class, nullptr, limit, max_idle);
}

void
was_stock_get(StockMap *hstock, struct pool *pool,
              const ChildOptions &options,
              const char *executable_path,
              ConstBuffer<const char *> args,
              StockGetHandler &handler,
              struct async_operation_ref &async_ref)
{
    auto params = NewFromPool<WasChildParams>(*pool, executable_path, args,
                                              options);

    hstock_get(*hstock, *pool, params->GetStockKey(*pool), params,
               handler, async_ref);
}

const WasProcess &
was_stock_item_get(const StockItem &item)
{
    auto *child = (const WasChild *)&item;

    return child->process;
}
<commit_msg>was/stock: switch to HeapStockItem<commit_after>/*
 * Launch and manage WAS child processes.
 *
 * author: Max Kellermann <mk@cm4all.com>
 */

#include "was_stock.hxx"
#include "was_quark.h"
#include "was_launch.hxx"
#include "stock/MapStock.hxx"
#include "stock/Stock.hxx"
#include "stock/Class.hxx"
#include "stock/Item.hxx"
#include "child_manager.hxx"
#include "async.hxx"
#include "net/ConnectSocket.hxx"
#include "spawn/ChildOptions.hxx"
#include "pool.hxx"
#include "event/Event.hxx"
#include "event/Callback.hxx"
#include "util/ConstBuffer.hxx"
#include "util/Cast.hxx"

#include <daemon/log.h>

#include <glib.h>
#include <assert.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <signal.h>
#include <stdlib.h>

struct WasChildParams {
    const char *executable_path;

    ConstBuffer<const char *> args;

    const ChildOptions &options;

    WasChildParams(const char *_executable_path,
                   ConstBuffer<const char *> _args,
                   const ChildOptions &_options)
        :executable_path(_executable_path), args(_args),
         options(_options) {}

    const char *GetStockKey(struct pool &pool) const;
};

struct WasChild final : HeapStockItem {
    WasProcess process;
    Event event;

    explicit WasChild(CreateStockItem c)
        :HeapStockItem(c) {}

    ~WasChild() override;

    void EventCallback(evutil_socket_t fd, short events);

    /* virtual methods from class StockItem */
    bool Borrow(gcc_unused void *ctx) override {
        event.Delete();
        return true;
    }

    bool Release(gcc_unused void *ctx) override {
        static constexpr struct timeval tv = {
            .tv_sec = 300,
            .tv_usec = 0,
        };

        event.Add(tv);
        return true;
    }
};

const char *
WasChildParams::GetStockKey(struct pool &pool) const
{
    const char *key = executable_path;
    for (auto i : args)
        key = p_strcat(&pool, key, " ", i, nullptr);

    for (auto i : options.env)
        key = p_strcat(&pool, key, "$", i, nullptr);

    char options_buffer[4096];
    *options.MakeId(options_buffer) = 0;
    if (*options_buffer != 0)
        key = p_strcat(&pool, key, options_buffer, nullptr);

    return key;
}

static void
was_child_callback(gcc_unused int status, void *ctx)
{
    WasChild *child = (WasChild *)ctx;

    child->process.pid = -1;
}

/*
 * libevent callback
 *
 */

inline void
WasChild::EventCallback(evutil_socket_t fd, short events)
{
    assert(fd == process.control_fd);

    if ((events & EV_TIMEOUT) == 0) {
        char buffer;
        ssize_t nbytes = recv(fd, &buffer, sizeof(buffer), MSG_DONTWAIT);
        if (nbytes < 0)
            daemon_log(2, "error on idle WAS control connection: %s\n",
                       strerror(errno));
        else if (nbytes > 0)
            daemon_log(2, "unexpected data from idle WAS control connection\n");
    }

    InvokeIdleDisconnect();
    pool_commit();
}

/*
 * stock class
 *
 */

static void
was_stock_create(gcc_unused void *ctx,
                 gcc_unused struct pool &parent_pool, CreateStockItem c,
                 void *info,
                 gcc_unused struct pool &caller_pool,
                 gcc_unused struct async_operation_ref &async_ref)
{
    WasChildParams *params = (WasChildParams *)info;

    auto *child = new WasChild(c);

    assert(params != nullptr);
    assert(params->executable_path != nullptr);

    GError *error = nullptr;
    if (!was_launch(&child->process, params->executable_path,
                    params->args,
                    params->options,
                    &error)) {
        child->InvokeCreateError(error);
        return;
    }

    child_register(child->process.pid, child->GetStockName(),
                   was_child_callback, child);

    child->event.Set(child->process.control_fd, EV_READ|EV_TIMEOUT,
                     MakeEventCallback(WasChild, EventCallback), child);

    child->InvokeCreateSuccess();
}

WasChild::~WasChild()
{
    if (process.pid >= 0)
        child_kill(process.pid);

    if (process.control_fd >= 0)
        event.Delete();

    process.Close();
}

static constexpr StockClass was_stock_class = {
    .create = was_stock_create,
};

/*
 * interface
 *
 */

StockMap *
was_stock_new(struct pool *pool, unsigned limit, unsigned max_idle)
{
    return hstock_new(*pool, was_stock_class, nullptr, limit, max_idle);
}

void
was_stock_get(StockMap *hstock, struct pool *pool,
              const ChildOptions &options,
              const char *executable_path,
              ConstBuffer<const char *> args,
              StockGetHandler &handler,
              struct async_operation_ref &async_ref)
{
    auto params = NewFromPool<WasChildParams>(*pool, executable_path, args,
                                              options);

    hstock_get(*hstock, *pool, params->GetStockKey(*pool), params,
               handler, async_ref);
}

const WasProcess &
was_stock_item_get(const StockItem &item)
{
    auto *child = (const WasChild *)&item;

    return child->process;
}
<|endoftext|>


<commit_before>#include "Moves/En_Passant.h"
#include "Moves/Pawn_Capture.h"
#include "Pieces/Piece.h"
#include "Game/Board.h"

En_Passant::En_Passant(Color color, char dir) : Pawn_Capture(color, dir)
{
}

En_Passant::~En_Passant()
{
}

bool En_Passant::move_specific_legal(const Board& board, char file_start, int rank_start) const
{
    char file_end = file_start + file_change();
    int rank_end = rank_start + rank_change();
    auto attacking_piece = board.piece_on_square(file_start, rank_start);
    auto attacked_piece  = board.piece_on_square(file_end,   rank_start);
    return board.is_en_passant_targetable(file_end, rank_end)
           && attacked_piece
           && attacking_piece->color() != attacked_piece->color();
}

void En_Passant::side_effects(Board& board, char file_start, int rank_start) const
{
    board.place_piece(nullptr, file_start + d_file, rank_start);
    Pawn_Move::side_effects(board, file_start, rank_start);
}

std::string En_Passant::name() const
{
    return "En Passant";
}
<commit_msg>Use methods instead of data member in En_Passant::side_effects()<commit_after>#include "Moves/En_Passant.h"
#include "Moves/Pawn_Capture.h"
#include "Pieces/Piece.h"
#include "Game/Board.h"

En_Passant::En_Passant(Color color, char dir) : Pawn_Capture(color, dir)
{
}

En_Passant::~En_Passant()
{
}

bool En_Passant::move_specific_legal(const Board& board, char file_start, int rank_start) const
{
    char file_end = file_start + file_change();
    int rank_end = rank_start + rank_change();
    auto attacking_piece = board.piece_on_square(file_start, rank_start);
    auto attacked_piece  = board.piece_on_square(file_end,   rank_start);
    return board.is_en_passant_targetable(file_end, rank_end)
           && attacked_piece
           && attacking_piece->color() != attacked_piece->color();
}

void En_Passant::side_effects(Board& board, char file_start, int rank_start) const
{
    board.place_piece(nullptr, file_start + file_change(), rank_start);
    Pawn_Move::side_effects(board, file_start, rank_start);
}

std::string En_Passant::name() const
{
    return "En Passant";
}
<|endoftext|>


<commit_before>/*
 * ProcessLauncher.cpp
 *
 *  Created on: Sep 14, 2014
 *      Author: matheus
 */

#include "ProcessLauncher.hpp"

#include <cstdlib>
#include <sys/shm.h>
#include <unistd.h>
#include <cstring>
#include <list>

#include "defines.hpp"

using namespace std;

ProcessLauncher::ProcessLauncher(int argc, char** argv) : argv(NULL) {
  char* tmpdir = getcwd(NULL, 0);

  // calculating buffer size
  bufsiz = strlen(tmpdir) + 1; // working directory
  for (int i = 3; i < argc; i++) {
    bufsiz += (strlen(argv[i]) + 1); // arguments
  }
  bufsiz++; // null termination of arguments array

  // allocating shared memory
  key = KEY_EXECPROCD + 1;
  do {
    shmid = shmget(key, bufsiz, (IPC_CREAT | IPC_EXCL) | 0777);
    if (shmid < 0) {
      key++;
    }
  } while (shmid < 0);
  buf = (char*)shmat(shmid, NULL, 0);

  // copying launch information
  size_t ind = 0;
  for (size_t i = 0; i < strlen(tmpdir); i++) { // working directory
    buf[ind++] = tmpdir[i];
  }
  buf[ind++] = '\0';
  for (int i = 3; i < argc; i++) { // arguments
    for (size_t j = 0; j < strlen(argv[i]); j++) {
      buf[ind++] = argv[i][j];
    }
    buf[ind++] = '\0';
  }
  buf[ind++] = '\0'; // null termination of arguments array

  free(tmpdir);
}

ProcessLauncher::ProcessLauncher(size_t bufsiz, key_t key) : bufsiz(0), key(0) {
  // getting shared memory
  shmid = shmget(key, bufsiz, 0);
  buf = (char*)shmat(shmid, NULL, 0);

  // copying launch information
  size_t i = 0;
  for (; buf[i] != '\0'; i++) { // working directory
    dir += buf[i];
  }
  i++;
  list<string> args;
  while (buf[i] != '\0') { // arguments to temporary args buffer
    string tmp;
    for (; buf[i] != '\0'; i++) {
      tmp += buf[i];
    }
    i++;
    args.push_back(tmp);
  }

  // copying arguments from temporary buffer to execv syscall format buffers
  argv = new char*[args.size() + 1];
  i = 0;
  for (list<string>::iterator it = args.begin(); it != args.end(); it++) {
    argv[i] = new char[it->size() + 1];
    strcpy(argv[i++], it->c_str());
  }
  argv[i++] = NULL;

  // detach shared memory
  closeshm();
}

ProcessLauncher::~ProcessLauncher() {
  closeshm();
  freeargv();
}

void ProcessLauncher::closeshm() {
  if (buf) {
    shmdt(buf);
    buf = NULL;
    if (key) {
      shmctl(shmid, IPC_RMID, NULL);
    }
  }
}

void ProcessLauncher::freeargv() {
  if (argv) {
    for (size_t i = 0; argv[i] != NULL; i++) {
      delete[] argv[i];
    }
    delete[] argv;
    argv = NULL;
  }
}
<commit_msg>Changing default key<commit_after>/*
 * ProcessLauncher.cpp
 *
 *  Created on: Sep 14, 2014
 *      Author: matheus
 */

#include "ProcessLauncher.hpp"

#include <cstdlib>
#include <sys/shm.h>
#include <unistd.h>
#include <cstring>
#include <list>

#include "defines.hpp"

using namespace std;

ProcessLauncher::ProcessLauncher(int argc, char** argv) : argv(NULL) {
  char* tmpdir = getcwd(NULL, 0);

  // calculating buffer size
  bufsiz = strlen(tmpdir) + 1; // working directory
  for (int i = 3; i < argc; i++) {
    bufsiz += (strlen(argv[i]) + 1); // arguments
  }
  bufsiz++; // null termination of arguments array

  // allocating shared memory
  key = KEY_EXECPROCD;
  do {
    shmid = shmget(key, bufsiz, (IPC_CREAT | IPC_EXCL) | 0777);
    if (shmid < 0) {
      key++;
    }
  } while (shmid < 0);
  buf = (char*)shmat(shmid, NULL, 0);

  // copying launch information
  size_t ind = 0;
  for (size_t i = 0; i < strlen(tmpdir); i++) { // working directory
    buf[ind++] = tmpdir[i];
  }
  buf[ind++] = '\0';
  for (int i = 3; i < argc; i++) { // arguments
    for (size_t j = 0; j < strlen(argv[i]); j++) {
      buf[ind++] = argv[i][j];
    }
    buf[ind++] = '\0';
  }
  buf[ind++] = '\0'; // null termination of arguments array

  free(tmpdir);
}

ProcessLauncher::ProcessLauncher(size_t bufsiz, key_t key) : bufsiz(0), key(0) {
  // getting shared memory
  shmid = shmget(key, bufsiz, 0);
  buf = (char*)shmat(shmid, NULL, 0);

  // copying launch information
  size_t i = 0;
  for (; buf[i] != '\0'; i++) { // working directory
    dir += buf[i];
  }
  i++;
  list<string> args;
  while (buf[i] != '\0') { // arguments to temporary args buffer
    string tmp;
    for (; buf[i] != '\0'; i++) {
      tmp += buf[i];
    }
    i++;
    args.push_back(tmp);
  }

  // copying arguments from temporary buffer to execv syscall format buffers
  argv = new char*[args.size() + 1];
  i = 0;
  for (list<string>::iterator it = args.begin(); it != args.end(); it++) {
    argv[i] = new char[it->size() + 1];
    strcpy(argv[i++], it->c_str());
  }
  argv[i++] = NULL;

  // detach shared memory
  closeshm();
}

ProcessLauncher::~ProcessLauncher() {
  closeshm();
  freeargv();
}

void ProcessLauncher::closeshm() {
  if (buf) {
    shmdt(buf);
    buf = NULL;
    if (key) {
      shmctl(shmid, IPC_RMID, NULL);
    }
  }
}

void ProcessLauncher::freeargv() {
  if (argv) {
    for (size_t i = 0; argv[i] != NULL; i++) {
      delete[] argv[i];
    }
    delete[] argv;
    argv = NULL;
  }
}
<|endoftext|>


<commit_before><commit_msg>coverity#984151 Uninitialized pointer field<commit_after><|endoftext|>


<commit_before>//@author A0094446X
#include "stdafx.h"
#include "CppUnitTest.h"
#include "You-GUI\main_window.h"
#include "You-GUI\system_tray_manager.h"
#include "You-QueryEngine\api.h"
#include "You-GUI\task_panel_manager.h"

using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert;
using Task = You::Controller::Task;
using TaskList = You::Controller::TaskList;
using Date = boost::gregorian::date;
namespace You {
namespace GUI {
namespace UnitTests {
QApplication *app;
// Simulate running the main() function
// Sets up the logging facility and the Qt event loop

TEST_MODULE_INITIALIZE(ModuleInitialize) {
	int argc = 1;
	char *argv[] = { "You.exe" };
	app = new QApplication(argc, argv);
}

// Cleans up what we set up
TEST_MODULE_CLEANUP(ModuleCleanup) {
	app->quit();
	delete app;
}

TEST_CLASS(MainWindowTests) {
public:
	/// These are generic tests for component visibility/invisibility
	TEST_METHOD(visibilityTest) {
		MainWindow w;
		bool visibilityTest =
			w.isVisible() &&
			w.ui.centralWidget->isVisible() &&
			w.ui.taskTreePanel->isVisible() &&
			w.ui.commandEnterButton->isVisible() &&
			w.ui.statusBar->isVisible() &&
			w.ui.statusIcon->isVisible() &&
			w.ui.statusMessage->isVisible() &&
			!w.ui.mainToolBar->isVisible() &&
			!w.ui.menuBar->isVisible();
		Assert::IsTrue(visibilityTest);
	}

	/// Basic task addition test
	TEST_METHOD(addSingleTask) {
		MainWindow w;
		w.clearTasks();
		w.commandTextBox->setPlainText(QString("/add test by Nov 99"));
		w.commandEnterPressed();

		QTreeWidgetItem item = *w.ui.taskTreePanel->topLevelItem(0);
		int column1 = QString::compare(item.text(0), QString("0"));
		int column2 = QString::compare(item.text(2), QString("test"));
		int column3 = QString::compare(
			item.text(3),
			QString("Overdue (1999-Nov-01)"));
		int column4 = QString::compare(item.text(4), QString("Normal"));

		Assert::IsTrue(w.ui.taskTreePanel->topLevelItemCount() == 1 &&
			(column1 == 0) && (column2 == 0) &&
			(column3 == 0) && (column4 == 0));
	}

	/// Boundary test case for the equivalence partition for the lower
	/// bound of the valid zone for testing if a task is due today
	TEST_METHOD(testDueToday1) {
		MainWindow w;
		Task::Time dl = boost::posix_time::second_clock::local_time();
		Assert::IsTrue(MainWindow::TaskPanelManager::isDueAfter(dl, 0));
	}

	/// Generic test case for testing if a task is due today (deadline ahead)
	TEST_METHOD(testDueToday2) {
		MainWindow w;
		Task::Time dl = boost::posix_time::second_clock::local_time();
		dl += boost::posix_time::hours(24) + boost::posix_time::minutes(1);
		Assert::IsFalse(MainWindow::TaskPanelManager::isDueAfter(dl, 0));
	}

	/// Generic test case for testing if a task is due today (deadline before)
	TEST_METHOD(testDueToday3) {
		MainWindow w;
		Task::Time dl = boost::posix_time::second_clock::local_time();
		dl -= (boost::posix_time::hours(24) + boost::posix_time::minutes(1));
		Assert::IsFalse(MainWindow::TaskPanelManager::isDueAfter(dl, 0));
	}

	/// Generic test case for testing if a task is due
	/// tomorrow (deadline after)
	TEST_METHOD(testDueTomorrow1) {
		MainWindow w;
		Task::Time dl = boost::posix_time::second_clock::local_time();
		dl += boost::posix_time::hours(24);
		Assert::IsTrue(MainWindow::TaskPanelManager::isDueAfter(dl, 1));
	}

	/// Boundary test case for the equivalence partition for the upper
	/// bound of the lower invalid zone for testing if a task is overdue
	TEST_METHOD(testPastDue1) {
		MainWindow w;
		Task::Time dl = boost::posix_time::second_clock::local_time();
		dl -= boost::posix_time::minutes(1);
		Assert::IsTrue(MainWindow::TaskPanelManager::isPastDue(dl));
	}

	/// Generic test case for testing if a task is overdue
	TEST_METHOD(testPastDue2) {
		MainWindow w;
		Task::Time dl = boost::posix_time::second_clock::local_time();
		dl -= (boost::posix_time::hours(24) + boost::posix_time::minutes(1));
		Assert::IsTrue(MainWindow::TaskPanelManager::isPastDue(dl));
	}

	/// Test if is past due, on the same time
	TEST_METHOD(testPastDue3) {
		MainWindow w;
		Task::Time dl = boost::posix_time::second_clock::local_time();
		Assert::IsFalse(MainWindow::TaskPanelManager::isPastDue(dl));
	}

	/// Test if is past due, with deadline 1 minute after
	TEST_METHOD(testPastDue4) {
		MainWindow w;
		Task::Time dl = boost::posix_time::second_clock::local_time();
		dl += boost::posix_time::minutes(1);
		Assert::IsFalse(MainWindow::TaskPanelManager::isPastDue(dl));
	}

	/// Generic task deletion test
	TEST_METHOD(deleteSingleTaskCount) {
		MainWindow w;
		w.clearTasks();
		w.commandTextBox->setPlainText(QString("/add test by Nov 20"));
		w.commandEnterPressed();
		w.commandTextBox->setPlainText(QString("/add test2 by Nov 20"));
		w.commandEnterPressed();
		w.commandTextBox->setPlainText(QString("/delete 1"));
		w.commandEnterPressed();
		Assert::IsTrue(w.ui.taskTreePanel->topLevelItemCount() == 1);
	}

	/// Generic task deletion test
	TEST_METHOD(deleteSingleTaskFind) {
		MainWindow w;
		w.clearTasks();
		w.commandTextBox->setPlainText(QString("/add test by Nov 20"));
		w.commandEnterPressed();
		w.commandTextBox->setPlainText(QString("/add test2 by Nov 20"));
		w.commandEnterPressed();
		w.commandTextBox->setPlainText(QString("/delete 1"));
		w.commandEnterPressed();
		Assert::IsTrue(w.ui.taskTreePanel->findItems(
			QString("1"), Qt::MatchExactly, 1).size() == 0);
	}

	TEST_METHOD(editSingleTask) {
		MainWindow w;
		w.clearTasks();
		w.commandTextBox->setPlainText(QString("/add test by Nov 99"));
		w.commandEnterPressed();
		w.commandTextBox->setPlainText(
			QString("/edit 0 set description = 'abc'"));
		w.commandEnterButtonClicked();
		QTreeWidgetItem item = *w.ui.taskTreePanel->topLevelItem(0);
		int column1 = QString::compare(item.text(0), QString("0"));
		int column2 = QString::compare(item.text(2), QString("abc"));
		int column3 = QString::compare(
			item.text(3),
			QString("Overdue (1999-Nov-01)"));
		int column4 = QString::compare(item.text(4), QString("Normal"));

		Assert::IsTrue(w.ui.taskTreePanel->topLevelItemCount() == 1 &&
			(column1 == 0) && (column2 == 0) &&
			(column3 == 0) && (column4 == 0));
	}

	TEST_METHOD(toggleTrayIcon) {
		MainWindow w;
		w.clearTasks();
		Assert::IsTrue(true);
	}
};
}  // namespace UnitTests
}  // namespace GUI
}  // namespace You
<commit_msg>Fix GUI tests.<commit_after>//@author A0094446X
#include "stdafx.h"
#include "CppUnitTest.h"
#include "You-GUI\main_window.h"
#include "You-GUI\system_tray_manager.h"
#include "You-QueryEngine\api.h"
#include "You-GUI\task_panel_manager.h"

using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert;
using Task = You::Controller::Task;
using TaskList = You::Controller::TaskList;
using Date = boost::gregorian::date;
namespace You {
namespace GUI {
namespace UnitTests {
QApplication *app;
// Simulate running the main() function
// Sets up the logging facility and the Qt event loop

TEST_MODULE_INITIALIZE(ModuleInitialize) {
	int argc = 1;
	char *argv[] = { "You.exe" };
	app = new QApplication(argc, argv);
}

// Cleans up what we set up
TEST_MODULE_CLEANUP(ModuleCleanup) {
	app->quit();
	delete app;
}

TEST_CLASS(MainWindowTests) {
public:
	/// These are generic tests for component visibility/invisibility
	TEST_METHOD(visibilityTest) {
		MainWindow w;
		bool visibilityTest =
			w.isVisible() &&
			w.ui.centralWidget->isVisible() &&
			w.ui.taskTreePanel->isVisible() &&
			w.ui.commandEnterButton->isVisible() &&
			w.ui.statusBar->isVisible() &&
			w.ui.statusIcon->isVisible() &&
			w.ui.statusMessage->isVisible() &&
			!w.ui.mainToolBar->isVisible() &&
			!w.ui.menuBar->isVisible();
		Assert::IsTrue(visibilityTest);
	}

	/// Basic task addition test
	TEST_METHOD(addSingleTask) {
		MainWindow w;
		w.clearTasks();
		w.commandTextBox->setPlainText(QString("/add test by Nov 99"));
		w.commandEnterPressed();

		QTreeWidgetItem item = *w.ui.taskTreePanel->topLevelItem(0);
		int column1 = QString::compare(item.text(0), QString("1"));
		int column2 = QString::compare(item.text(2), QString("test"));
		int column3 = QString::compare(
			item.text(3),
			QString("Overdue (1999-Nov-01)"));
		int column4 = QString::compare(item.text(4), QString("Normal"));

		Assert::IsTrue(w.ui.taskTreePanel->topLevelItemCount() == 1 &&
			(column1 == 0) && (column2 == 0) &&
			(column3 == 0) && (column4 == 0));
	}

	/// Boundary test case for the equivalence partition for the lower
	/// bound of the valid zone for testing if a task is due today
	TEST_METHOD(testDueToday1) {
		MainWindow w;
		Task::Time dl = boost::posix_time::second_clock::local_time();
		Assert::IsTrue(MainWindow::TaskPanelManager::isDueAfter(dl, 0));
	}

	/// Generic test case for testing if a task is due today (deadline ahead)
	TEST_METHOD(testDueToday2) {
		MainWindow w;
		Task::Time dl = boost::posix_time::second_clock::local_time();
		dl += boost::posix_time::hours(24) + boost::posix_time::minutes(1);
		Assert::IsFalse(MainWindow::TaskPanelManager::isDueAfter(dl, 0));
	}

	/// Generic test case for testing if a task is due today (deadline before)
	TEST_METHOD(testDueToday3) {
		MainWindow w;
		Task::Time dl = boost::posix_time::second_clock::local_time();
		dl -= (boost::posix_time::hours(24) + boost::posix_time::minutes(1));
		Assert::IsFalse(MainWindow::TaskPanelManager::isDueAfter(dl, 0));
	}

	/// Generic test case for testing if a task is due
	/// tomorrow (deadline after)
	TEST_METHOD(testDueTomorrow1) {
		MainWindow w;
		Task::Time dl = boost::posix_time::second_clock::local_time();
		dl += boost::posix_time::hours(24);
		Assert::IsTrue(MainWindow::TaskPanelManager::isDueAfter(dl, 1));
	}

	/// Boundary test case for the equivalence partition for the upper
	/// bound of the lower invalid zone for testing if a task is overdue
	TEST_METHOD(testPastDue1) {
		MainWindow w;
		Task::Time dl = boost::posix_time::second_clock::local_time();
		dl -= boost::posix_time::minutes(1);
		Assert::IsTrue(MainWindow::TaskPanelManager::isPastDue(dl));
	}

	/// Generic test case for testing if a task is overdue
	TEST_METHOD(testPastDue2) {
		MainWindow w;
		Task::Time dl = boost::posix_time::second_clock::local_time();
		dl -= (boost::posix_time::hours(24) + boost::posix_time::minutes(1));
		Assert::IsTrue(MainWindow::TaskPanelManager::isPastDue(dl));
	}

	/// Test if is past due, on the same time
	TEST_METHOD(testPastDue3) {
		MainWindow w;
		Task::Time dl = boost::posix_time::second_clock::local_time();
		Assert::IsFalse(MainWindow::TaskPanelManager::isPastDue(dl));
	}

	/// Test if is past due, with deadline 1 minute after
	TEST_METHOD(testPastDue4) {
		MainWindow w;
		Task::Time dl = boost::posix_time::second_clock::local_time();
		dl += boost::posix_time::minutes(1);
		Assert::IsFalse(MainWindow::TaskPanelManager::isPastDue(dl));
	}

	/// Generic task deletion test
	TEST_METHOD(deleteSingleTaskCount) {
		MainWindow w;
		w.clearTasks();
		w.commandTextBox->setPlainText(QString("/add test by Nov 20"));
		w.commandEnterPressed();
		w.commandTextBox->setPlainText(QString("/add test2 by Nov 20"));
		w.commandEnterPressed();
		w.commandTextBox->setPlainText(QString("/delete 1"));
		w.commandEnterPressed();
		Assert::IsTrue(w.ui.taskTreePanel->topLevelItemCount() == 1);
	}

	/// Generic task deletion test
	TEST_METHOD(deleteSingleTaskFind) {
		MainWindow w;
		w.clearTasks();
		w.commandTextBox->setPlainText(QString("/add test by Nov 20"));
		w.commandEnterPressed();
		w.commandTextBox->setPlainText(QString("/add test2 by Nov 20"));
		w.commandEnterPressed();
		w.commandTextBox->setPlainText(QString("/delete 1"));
		w.commandEnterPressed();
		Assert::IsTrue(w.ui.taskTreePanel->findItems(
			QString("1"), Qt::MatchExactly, 1).size() == 0);
	}

	TEST_METHOD(editSingleTask) {
		MainWindow w;
		w.clearTasks();
		w.commandTextBox->setPlainText(QString("/add test by Nov 99"));
		w.commandEnterPressed();
		w.commandTextBox->setPlainText(
			QString("/edit 0 set description = 'abc'"));
		w.commandEnterButtonClicked();
		QTreeWidgetItem item = *w.ui.taskTreePanel->topLevelItem(0);
		int column1 = QString::compare(item.text(0), QString("1"));
		int column2 = QString::compare(item.text(2), QString("abc"));
		int column3 = QString::compare(
			item.text(3),
			QString("Overdue (1999-Nov-01)"));
		int column4 = QString::compare(item.text(4), QString("Normal"));

		Assert::IsTrue(w.ui.taskTreePanel->topLevelItemCount() == 1 &&
			(column1 == 0) && (column2 == 0) &&
			(column3 == 0) && (column4 == 0));
	}

	TEST_METHOD(toggleTrayIcon) {
		MainWindow w;
		w.clearTasks();
		Assert::IsTrue(true);
	}
};
}  // namespace UnitTests
}  // namespace GUI
}  // namespace You
<|endoftext|>


<commit_before><commit_msg>simplify conditionals<commit_after><|endoftext|>


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

using namespace connectivity;
//**************************************************************
//************ Class: java.sql.Array
//**************************************************************

jclass java_sql_Array::theClass = 0;

java_sql_Array::~java_sql_Array()
{}

jclass java_sql_Array::getMyClass()
{
    // die Klasse muss nur einmal geholt werden, daher statisch
    if( !theClass ){
        SDBThreadAttach t;
        if( !t.pEnv ) return (jclass)NULL;
        jclass tempClass = t.pEnv->FindClass( "java/sql/Array" );
        jclass globClass = (jclass)t.pEnv->NewGlobalRef( tempClass );
        t.pEnv->DeleteLocalRef( tempClass );
        saveClassRef( globClass );
    }
    return theClass;
}

void java_sql_Array::saveClassRef( jclass pClass )
{
    if( pClass==NULL  )
        return;
    // der uebergebe Klassen-Handle ist schon global, daher einfach speichern
    theClass = pClass;
}
::rtl::OUString SAL_CALL java_sql_Array::getBaseTypeName(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
{
    SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment gelscht worden!");
    ::rtl::OUString aStr;
    if( t.pEnv ){
        // temporaere Variable initialisieren
        static char * cSignature = "(I)Ljava/lang/String;";
        static char * cMethodName = "getBaseTypeName";
        // Java-Call absetzen
        static jmethodID mID = NULL;
        if ( !mID  )
            mID  = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );
        if( mID ){
            jstring out = (jstring)t.pEnv->CallObjectMethod( object, mID);
            ThrowSQLException(t.pEnv,*this);
            aStr = JavaString2String(t.pEnv,out);
            // und aufraeumen
        } //mID
    } //t.pEnv
    // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
    return  aStr;
}

sal_Int32 SAL_CALL java_sql_Array::getBaseType(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
{
    jint out(0);
    SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment gelscht worden!");
    if( t.pEnv )
    {
        // temporaere Variable initialisieren
        static char * cSignature = "()I";
        static char * cMethodName = "getBaseType";
        // Java-Call absetzen
        static jmethodID mID = NULL;
        if ( !mID  )
            mID  = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );
        if( mID ){
            out = t.pEnv->CallIntMethod( object, mID );
            ThrowSQLException(t.pEnv,*this);
            // und aufraeumen
        } //mID
    } //t.pEnv
    return (sal_Int32)out;
}

::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any > SAL_CALL java_sql_Array::getArray( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& typeMap ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
{
    jobjectArray out(0);
    SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment gelscht worden!");
    if( t.pEnv )
    {
        jobject obj = XNameAccess2Map(t.pEnv,typeMap);
        static char * cSignature = "(Ljava/util/Map;)[Ljava/lang/Object;";
        static char * cMethodName = "getArray";
        // Java-Call absetzen
        static jmethodID mID = NULL;
        if ( !mID  )
            mID  = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );
        if( mID ){
            out = (jobjectArray)t.pEnv->CallObjectMethod( object, mID, obj);
            ThrowSQLException(t.pEnv,*this);
            // und aufraeumen
            t.pEnv->DeleteLocalRef(obj);
        } //mID
    } //t.pEnv
    return ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >();//copyArrayAndDelete< ::com::sun::star::uno::Any,jobject>(t.pEnv,out);
}

::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any > SAL_CALL java_sql_Array::getArrayAtIndex( sal_Int32 index, sal_Int32 count, const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& typeMap ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
{
    jobjectArray out(0);
    SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment gelscht worden!");
    if( t.pEnv )
    {
        jobject obj = XNameAccess2Map(t.pEnv,typeMap);
        static char * cSignature = "(IILjava/util/Map;)[Ljava/lang/Object;";
        static char * cMethodName = "getArray";
        // Java-Call absetzen
        static jmethodID mID = NULL;
        if ( !mID  )
            mID  = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );
        if( mID ){
            out = (jobjectArray)t.pEnv->CallObjectMethod( object, mID, index,count,obj);
            ThrowSQLException(t.pEnv,*this);
            // und aufraeumen
            t.pEnv->DeleteLocalRef(obj);
        } //mID
    } //t.pEnv
    return ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >();//copyArrayAndDelete< ::com::sun::star::uno::Any,jobject>(t.pEnv,out);
}

::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL java_sql_Array::getResultSet( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& typeMap ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
{
    jobject out(0);
    SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment gelscht worden!");
    if( t.pEnv ){
        // Parameter konvertieren
        jobject obj = XNameAccess2Map(t.pEnv,typeMap);
        // temporaere Variable initialisieren
        static char * cSignature = "(Ljava/util/Map;)Ljava/sql/ResultSet;";
        static char * cMethodName = "getResultSet";
        // Java-Call absetzen
        static jmethodID mID = NULL;
        if ( !mID  )
            mID  = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );
        if( mID ){
            out = t.pEnv->CallObjectMethod( object, mID, obj);
            ThrowSQLException(t.pEnv,*this);
            // und aufraeumen
            t.pEnv->DeleteLocalRef(obj);
        } //mID
    } //t.pEnv
    // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
    //  return out==0 ? 0 : new java_sql_ResultSet( t.pEnv, out );
    return NULL;
}

::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL java_sql_Array::getResultSetAtIndex( sal_Int32 index, sal_Int32 count, const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& typeMap ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
{
    jobject out(0);
    SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment gelscht worden!");
    if( t.pEnv ){
        // Parameter konvertieren
        jobject obj = XNameAccess2Map(t.pEnv,typeMap);
        // temporaere Variable initialisieren
        static char * cSignature = "(Ljava/util/Map;)Ljava/sql/ResultSet;";
        static char * cMethodName = "getResultSetAtIndex";
        // Java-Call absetzen
        static jmethodID mID = NULL;
        if ( !mID  )
            mID  = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );
        if( mID ){
            out = t.pEnv->CallObjectMethod( object, mID, index,count,obj);
            ThrowSQLException(t.pEnv,*this);
            // und aufraeumen
            t.pEnv->DeleteLocalRef(obj);
        } //mID
    } //t.pEnv
    // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
    //  return out==0 ? 0 : new java_sql_ResultSet( t.pEnv, out );
    return NULL;
}

<commit_msg>INTEGRATION: CWS dr33 (1.5.36); FILE MERGED 2005/02/14 16:38:54 dr 1.5.36.1: #i42367# remove non-ASCII characters from C++ sources<commit_after>/*************************************************************************
 *
 *  $RCSfile: Array.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: vg $ $Date: 2005-02-16 17:27:00 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _CONNECTIVITY_JAVA_SQL_ARRAY_HXX_
#include "java/sql/Array.hxx"
#endif
#ifndef _CONNECTIVITY_JAVA_TOOLS_HXX_
#include "java/tools.hxx"
#endif
#ifndef _CONNECTIVITY_JAVA_SQL_RESULTSET_HXX_
#include "java/sql/ResultSet.hxx"
#endif

using namespace connectivity;
//**************************************************************
//************ Class: java.sql.Array
//**************************************************************

jclass java_sql_Array::theClass = 0;

java_sql_Array::~java_sql_Array()
{}

jclass java_sql_Array::getMyClass()
{
    // die Klasse muss nur einmal geholt werden, daher statisch
    if( !theClass ){
        SDBThreadAttach t;
        if( !t.pEnv ) return (jclass)NULL;
        jclass tempClass = t.pEnv->FindClass( "java/sql/Array" );
        jclass globClass = (jclass)t.pEnv->NewGlobalRef( tempClass );
        t.pEnv->DeleteLocalRef( tempClass );
        saveClassRef( globClass );
    }
    return theClass;
}

void java_sql_Array::saveClassRef( jclass pClass )
{
    if( pClass==NULL  )
        return;
    // der uebergebe Klassen-Handle ist schon global, daher einfach speichern
    theClass = pClass;
}
::rtl::OUString SAL_CALL java_sql_Array::getBaseTypeName(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
{
    SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!");
    ::rtl::OUString aStr;
    if( t.pEnv ){
        // temporaere Variable initialisieren
        static char * cSignature = "(I)Ljava/lang/String;";
        static char * cMethodName = "getBaseTypeName";
        // Java-Call absetzen
        static jmethodID mID = NULL;
        if ( !mID  )
            mID  = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );
        if( mID ){
            jstring out = (jstring)t.pEnv->CallObjectMethod( object, mID);
            ThrowSQLException(t.pEnv,*this);
            aStr = JavaString2String(t.pEnv,out);
            // und aufraeumen
        } //mID
    } //t.pEnv
    // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
    return  aStr;
}

sal_Int32 SAL_CALL java_sql_Array::getBaseType(  ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
{
    jint out(0);
    SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!");
    if( t.pEnv )
    {
        // temporaere Variable initialisieren
        static char * cSignature = "()I";
        static char * cMethodName = "getBaseType";
        // Java-Call absetzen
        static jmethodID mID = NULL;
        if ( !mID  )
            mID  = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );
        if( mID ){
            out = t.pEnv->CallIntMethod( object, mID );
            ThrowSQLException(t.pEnv,*this);
            // und aufraeumen
        } //mID
    } //t.pEnv
    return (sal_Int32)out;
}

::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any > SAL_CALL java_sql_Array::getArray( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& typeMap ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
{
    jobjectArray out(0);
    SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!");
    if( t.pEnv )
    {
        jobject obj = XNameAccess2Map(t.pEnv,typeMap);
        static char * cSignature = "(Ljava/util/Map;)[Ljava/lang/Object;";
        static char * cMethodName = "getArray";
        // Java-Call absetzen
        static jmethodID mID = NULL;
        if ( !mID  )
            mID  = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );
        if( mID ){
            out = (jobjectArray)t.pEnv->CallObjectMethod( object, mID, obj);
            ThrowSQLException(t.pEnv,*this);
            // und aufraeumen
            t.pEnv->DeleteLocalRef(obj);
        } //mID
    } //t.pEnv
    return ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >();//copyArrayAndDelete< ::com::sun::star::uno::Any,jobject>(t.pEnv,out);
}

::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any > SAL_CALL java_sql_Array::getArrayAtIndex( sal_Int32 index, sal_Int32 count, const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& typeMap ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
{
    jobjectArray out(0);
    SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!");
    if( t.pEnv )
    {
        jobject obj = XNameAccess2Map(t.pEnv,typeMap);
        static char * cSignature = "(IILjava/util/Map;)[Ljava/lang/Object;";
        static char * cMethodName = "getArray";
        // Java-Call absetzen
        static jmethodID mID = NULL;
        if ( !mID  )
            mID  = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );
        if( mID ){
            out = (jobjectArray)t.pEnv->CallObjectMethod( object, mID, index,count,obj);
            ThrowSQLException(t.pEnv,*this);
            // und aufraeumen
            t.pEnv->DeleteLocalRef(obj);
        } //mID
    } //t.pEnv
    return ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Any >();//copyArrayAndDelete< ::com::sun::star::uno::Any,jobject>(t.pEnv,out);
}

::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL java_sql_Array::getResultSet( const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& typeMap ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
{
    jobject out(0);
    SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!");
    if( t.pEnv ){
        // Parameter konvertieren
        jobject obj = XNameAccess2Map(t.pEnv,typeMap);
        // temporaere Variable initialisieren
        static char * cSignature = "(Ljava/util/Map;)Ljava/sql/ResultSet;";
        static char * cMethodName = "getResultSet";
        // Java-Call absetzen
        static jmethodID mID = NULL;
        if ( !mID  )
            mID  = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );
        if( mID ){
            out = t.pEnv->CallObjectMethod( object, mID, obj);
            ThrowSQLException(t.pEnv,*this);
            // und aufraeumen
            t.pEnv->DeleteLocalRef(obj);
        } //mID
    } //t.pEnv
    // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
    //  return out==0 ? 0 : new java_sql_ResultSet( t.pEnv, out );
    return NULL;
}

::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XResultSet > SAL_CALL java_sql_Array::getResultSetAtIndex( sal_Int32 index, sal_Int32 count, const ::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess >& typeMap ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException)
{
    jobject out(0);
    SDBThreadAttach t; OSL_ENSURE(t.pEnv,"Java Enviroment geloescht worden!");
    if( t.pEnv ){
        // Parameter konvertieren
        jobject obj = XNameAccess2Map(t.pEnv,typeMap);
        // temporaere Variable initialisieren
        static char * cSignature = "(Ljava/util/Map;)Ljava/sql/ResultSet;";
        static char * cMethodName = "getResultSetAtIndex";
        // Java-Call absetzen
        static jmethodID mID = NULL;
        if ( !mID  )
            mID  = t.pEnv->GetMethodID( getMyClass(), cMethodName, cSignature );
        if( mID ){
            out = t.pEnv->CallObjectMethod( object, mID, index,count,obj);
            ThrowSQLException(t.pEnv,*this);
            // und aufraeumen
            t.pEnv->DeleteLocalRef(obj);
        } //mID
    } //t.pEnv
    // ACHTUNG: der Aufrufer wird Eigentuemer des zurueckgelieferten Zeigers !!!
    //  return out==0 ? 0 : new java_sql_ResultSet( t.pEnv, out );
    return NULL;
}

<|endoftext|>


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

#ifndef _CONNECTIVITY_ADABAS_BDRIVER_HXX_
#define _CONNECTIVITY_ADABAS_BDRIVER_HXX_

#ifndef _COM_SUN_STAR_SDBC_XDRIVER_HPP_
#include <com/sun/star/sdbc/XDriver.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XDATADEFINITIONSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XDataDefinitionSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XTABLESSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XTablesSupplier.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _CONNECTIVITY_OFUNCTIONDEFS_HXX_
#include "odbc/OFunctiondefs.hxx"
#endif
#ifndef _CONNECTIVITY_ODBC_ODRIVER_HXX_
#include "odbc/ODriver.hxx"
#endif

namespace connectivity
{
    namespace adabas
    {
        ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL ODriver_CreateInstance(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory) throw( ::com::sun::star::uno::Exception );

        typedef odbc::ODBCDriver ODriver_BASE;

        class ODriver : public ODriver_BASE,
                        public ::com::sun::star::sdbcx::XDataDefinitionSupplier
        {
        protected:
            virtual SQLHANDLE EnvironmentHandle(::rtl::OUString &_rPath);
            virtual ~ODriver();
        public:
            DECLARE_SERVICE_INFO();

            ODriver(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory);

            virtual void* getOdbcFunction(sal_Int32 _nIndex)  const;
            // OComponentHelper
            virtual void SAL_CALL disposing(void);
            // XInterface
            static ::rtl::OUString getImplementationName_Static(  ) throw(::com::sun::star::uno::RuntimeException);
            static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_Static(  ) throw (::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL acquire() throw();
            virtual void SAL_CALL release() throw();

            // XDriver
            ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > SAL_CALL connect( const ::rtl::OUString& url, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& info ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Bool SAL_CALL acceptsURL( const ::rtl::OUString& url ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Sequence< ::com::sun::star::sdbc::DriverPropertyInfo > SAL_CALL getPropertyInfo( const ::rtl::OUString& url, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& info ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Int32 SAL_CALL getMajorVersion(  ) throw(::com::sun::star::uno::RuntimeException);
            virtual sal_Int32 SAL_CALL getMinorVersion(  ) throw(::com::sun::star::uno::RuntimeException);

            // XDataDefinitionSupplier
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XTablesSupplier > SAL_CALL getDataDefinitionByConnection( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& connection ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XTablesSupplier > SAL_CALL getDataDefinitionByURL( const ::rtl::OUString& url, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& info ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        };
    }

}
#endif //_CONNECTIVITY_ADABAS_BDRIVER_HXX_

<commit_msg>INTEGRATION: CWS ooo19126 (1.9.320); FILE MERGED 2005/09/05 17:24:53 rt 1.9.320.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: BDriver.hxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 06:42:52 $
 *
 *  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 _CONNECTIVITY_ADABAS_BDRIVER_HXX_
#define _CONNECTIVITY_ADABAS_BDRIVER_HXX_

#ifndef _COM_SUN_STAR_SDBC_XDRIVER_HPP_
#include <com/sun/star/sdbc/XDriver.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XDATADEFINITIONSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XDataDefinitionSupplier.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBCX_XTABLESSUPPLIER_HPP_
#include <com/sun/star/sdbcx/XTablesSupplier.hpp>
#endif
#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif
#ifndef _CONNECTIVITY_OFUNCTIONDEFS_HXX_
#include "odbc/OFunctiondefs.hxx"
#endif
#ifndef _CONNECTIVITY_ODBC_ODRIVER_HXX_
#include "odbc/ODriver.hxx"
#endif

namespace connectivity
{
    namespace adabas
    {
        ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL ODriver_CreateInstance(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory) throw( ::com::sun::star::uno::Exception );

        typedef odbc::ODBCDriver ODriver_BASE;

        class ODriver : public ODriver_BASE,
                        public ::com::sun::star::sdbcx::XDataDefinitionSupplier
        {
        protected:
            virtual SQLHANDLE EnvironmentHandle(::rtl::OUString &_rPath);
            virtual ~ODriver();
        public:
            DECLARE_SERVICE_INFO();

            ODriver(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory);

            virtual void* getOdbcFunction(sal_Int32 _nIndex)  const;
            // OComponentHelper
            virtual void SAL_CALL disposing(void);
            // XInterface
            static ::rtl::OUString getImplementationName_Static(  ) throw(::com::sun::star::uno::RuntimeException);
            static ::com::sun::star::uno::Sequence< ::rtl::OUString > getSupportedServiceNames_Static(  ) throw (::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);
            virtual void SAL_CALL acquire() throw();
            virtual void SAL_CALL release() throw();

            // XDriver
            ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > SAL_CALL connect( const ::rtl::OUString& url, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& info ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Bool SAL_CALL acceptsURL( const ::rtl::OUString& url ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Sequence< ::com::sun::star::sdbc::DriverPropertyInfo > SAL_CALL getPropertyInfo( const ::rtl::OUString& url, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& info ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual sal_Int32 SAL_CALL getMajorVersion(  ) throw(::com::sun::star::uno::RuntimeException);
            virtual sal_Int32 SAL_CALL getMinorVersion(  ) throw(::com::sun::star::uno::RuntimeException);

            // XDataDefinitionSupplier
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XTablesSupplier > SAL_CALL getDataDefinitionByConnection( const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection >& connection ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbcx::XTablesSupplier > SAL_CALL getDataDefinitionByURL( const ::rtl::OUString& url, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& info ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
        };
    }

}
#endif //_CONNECTIVITY_ADABAS_BDRIVER_HXX_

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: BTables.hxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 06:46:46 $
 *
 *  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 _CONNECTIVITY_ADABAS_TABLES_HXX_
#define _CONNECTIVITY_ADABAS_TABLES_HXX_

#ifndef _CONNECTIVITY_SDBCX_COLLECTION_HXX_
#include "connectivity/sdbcx/VCollection.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XDATABASEMETADATA_HPP_
#include <com/sun/star/sdbc/XDatabaseMetaData.hpp>
#endif
namespace connectivity
{
    namespace adabas
    {
        class OTables : public sdbcx::OCollection
        {
            ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData >       m_xMetaData;
            //  OCatalog*                                           m_pParent;
        protected:
            virtual sdbcx::ObjectType createObject(const ::rtl::OUString& _rName);
            virtual void impl_refresh() throw(::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > createEmptyObject();
            virtual void appendObject( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& descriptor );
            virtual void dropObject(sal_Int32 _nPos,const ::rtl::OUString _sElementName);

            void setComments(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& descriptor ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            void createTable( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& descriptor );

            virtual ::rtl::OUString getNameForObject(const sdbcx::ObjectType& _xObject);
        public:
            OTables(const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData >& _rMetaData,::cppu::OWeakObject& _rParent, ::osl::Mutex& _rMutex,
                const TStringVector &_rVector) : sdbcx::OCollection(_rParent,sal_True,_rMutex,_rVector)
                ,m_xMetaData(_rMetaData)
            {}

            // only the name is identical to ::cppu::OComponentHelper
            virtual void SAL_CALL disposing(void);

            // XDrop
            void appendNew(const ::rtl::OUString& _rsNewTable);
            // some helper functions
            /**
                returns a sql string which contains the column definition part for create or alter statements
            */
            static ::rtl::OUString getColumnSqlType(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxColProp);
            /**
                returns the "not null" part or the default part of the table statement
            */
            static ::rtl::OUString getColumnSqlNotNullDefault(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxColProp);
            /**
                returns the corresponding typename
                can contain () which have to filled with values
            */
            static ::rtl::OUString getTypeString(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxColProp);
        };
    }
}
#endif // _CONNECTIVITY_ADABAS_TABLES_HXX_

<commit_msg>INTEGRATION: CWS qiq (1.9.104); FILE MERGED 2006/06/16 11:32:35 fs 1.9.104.1: during #i51143#:<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: BTables.hxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: obo $ $Date: 2006-07-10 14:33:09 $
 *
 *  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 _CONNECTIVITY_ADABAS_TABLES_HXX_
#define _CONNECTIVITY_ADABAS_TABLES_HXX_

#ifndef _CONNECTIVITY_SDBCX_COLLECTION_HXX_
#include "connectivity/sdbcx/VCollection.hxx"
#endif
#ifndef _COM_SUN_STAR_SDBC_XDATABASEMETADATA_HPP_
#include <com/sun/star/sdbc/XDatabaseMetaData.hpp>
#endif
namespace connectivity
{
    namespace adabas
    {
        class OTables : public sdbcx::OCollection
        {
            ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData >       m_xMetaData;
            //  OCatalog*                                           m_pParent;
        protected:
            virtual sdbcx::ObjectType createObject(const ::rtl::OUString& _rName);
            virtual void impl_refresh() throw(::com::sun::star::uno::RuntimeException);
            virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet > createDescriptor();
            virtual sdbcx::ObjectType appendObject( const ::rtl::OUString& _rForName, const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& descriptor );
            virtual void dropObject(sal_Int32 _nPos,const ::rtl::OUString _sElementName);

            void setComments(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& descriptor ) throw(::com::sun::star::sdbc::SQLException, ::com::sun::star::uno::RuntimeException);
            void createTable( const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& descriptor );

            virtual ::rtl::OUString getNameForObject(const sdbcx::ObjectType& _xObject);
        public:
            OTables(const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData >& _rMetaData,::cppu::OWeakObject& _rParent, ::osl::Mutex& _rMutex,
                const TStringVector &_rVector) : sdbcx::OCollection(_rParent,sal_True,_rMutex,_rVector)
                ,m_xMetaData(_rMetaData)
            {}

            // only the name is identical to ::cppu::OComponentHelper
            virtual void SAL_CALL disposing(void);

            // XDrop
            void appendNew(const ::rtl::OUString& _rsNewTable);
            // some helper functions
            /**
                returns a sql string which contains the column definition part for create or alter statements
            */
            static ::rtl::OUString getColumnSqlType(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxColProp);
            /**
                returns the "not null" part or the default part of the table statement
            */
            static ::rtl::OUString getColumnSqlNotNullDefault(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxColProp);
            /**
                returns the corresponding typename
                can contain () which have to filled with values
            */
            static ::rtl::OUString getTypeString(const ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet >& _rxColProp);
        };
    }
}
#endif // _CONNECTIVITY_ADABAS_TABLES_HXX_

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: DCatalog.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 07:01:16 $
 *
 *  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 _CONNECTIVITY_DBASE_CATALOG_HXX_
#define _CONNECTIVITY_DBASE_CATALOG_HXX_

#ifndef _CONNECTIVITY_FILE_CATALOG_HXX_
#include "file/FCatalog.hxx"
#endif

namespace connectivity
{
    namespace dbase
    {
        class ODbaseConnection;
        class ODbaseCatalog : public file::OFileCatalog
        {
    public:
            virtual void refreshTables();

        public:
            ODbaseCatalog(ODbaseConnection* _pCon);
        };
    }
}
#endif // _CONNECTIVITY_DBASE_CATALOG_HXX_

<commit_msg>INTEGRATION: CWS changefileheader (1.2.372); FILE MERGED 2008/04/01 10:53:24 thb 1.2.372.2: #i85898# Stripping all external header guards 2008/03/28 15:24:17 rt 1.2.372.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: DCatalog.hxx,v $
 * $Revision: 1.3 $
 *
 * 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 _CONNECTIVITY_DBASE_CATALOG_HXX_
#define _CONNECTIVITY_DBASE_CATALOG_HXX_

#include "file/FCatalog.hxx"

namespace connectivity
{
    namespace dbase
    {
        class ODbaseConnection;
        class ODbaseCatalog : public file::OFileCatalog
        {
    public:
            virtual void refreshTables();

        public:
            ODbaseCatalog(ODbaseConnection* _pCon);
        };
    }
}
#endif // _CONNECTIVITY_DBASE_CATALOG_HXX_

<|endoftext|>


<commit_before>// RemoveOrAddTool.cpp
// Copyright (c) 2009, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.

#include "stdafx.h"

#include "RemoveOrAddTool.h"
#include "../interface/HeeksObj.h"
#include "MarkedList.h"

RemoveOrAddTool::RemoveOrAddTool(HeeksObj *object, HeeksObj *owner, HeeksObj *prev_object) : m_belongs_to_owner(false)
{
	m_object = object;
	m_owner = owner;
	m_prev_object = prev_object;
}

RemoveOrAddTool::~RemoveOrAddTool()
{
	if(m_owner == NULL)return;
	if(!m_belongs_to_owner)delete m_object;
}

static wxString string_for_GetTitle;

const wxChar* AddObjectTool::GetTitle()
{
	string_for_GetTitle.assign(_("Add "));
	string_for_GetTitle.append(m_object->GetShortStringOrTypeString());
	return string_for_GetTitle.c_str();
}

void RemoveOrAddTool::Add()
{

	if (wxGetApp().m_doing_rollback && (m_owner == NULL))
	{
		m_owner = NULL;
	}

	if (m_owner == NULL)
	{
		wxMessageBox(_T("Can't Have NULL owner!"));
		return;
	}

	m_owner->Add(m_object, m_prev_object);

	wxGetApp().WasAdded(m_object);
	wxGetApp().WasModified(m_owner);

	m_belongs_to_owner = true;
}

void RemoveOrAddTool::Remove()
{
	while (m_object->Owner())
	{
		m_owner = m_object->Owner();
		m_object->Owner()->Remove(m_object);
		wxGetApp().WasRemoved(m_object);
		wxGetApp().WasModified(m_owner);
		m_object->RemoveOwner(m_object->Owner());
	}
	m_belongs_to_owner = false;
}

void AddObjectTool::Run()
{
	Add();
}

void AddObjectTool::RollBack()
{
	Remove();
}

RemoveObjectTool::RemoveObjectTool(HeeksObj *object):RemoveOrAddTool(object, NULL, NULL)
{
	if(object)m_owner = object->Owner();
	else m_owner = NULL;
}

void RemoveObjectTool::Run()
{
	Remove();
}

void RemoveObjectTool::RollBack()
{
	Add();
}

ManyRemoveOrAddTool::~ManyRemoveOrAddTool()
{
	if(!m_belongs_to_owner){
		std::list<HeeksObj*>::iterator It;
		for(It = m_objects.begin(); It != m_objects.end(); It++){
			HeeksObj* object = *It;
            delete object;
		}
	}
}

void ManyRemoveOrAddTool::Add()
{
	if (m_owner == NULL)
	{
		wxMessageBox(_T("Can't have NULL owner!"));
		return;
	}

	std::list<HeeksObj*>::iterator It;
	for(It = m_objects.begin(); It != m_objects.end(); It++){
		HeeksObj* object = *It;
		m_owner->Add(object, NULL);
	}

	wxGetApp().WereAdded(m_objects);
	wxGetApp().WasModified(m_owner);

	m_belongs_to_owner = true;
}

void ManyRemoveOrAddTool::Remove()
{
	std::list<HeeksObj*>::iterator It;
	for(It = m_objects.begin(); It != m_objects.end(); It++){
		HeeksObj* object = *It;
		if(m_owner)
			m_owner->Remove(object);
		wxGetApp().m_marked_list->Remove(object, false);
	}

	wxGetApp().WereRemoved(m_objects);
	wxGetApp().WasModified(m_owner);
	for(It = m_objects.begin(); It != m_objects.end(); It++){
		HeeksObj* object = *It;
		object->RemoveOwners();
	}

	m_belongs_to_owner = false;
}

const wxChar* AddObjectsTool::GetTitle()
{
	return _("Add Objects");
}

void AddObjectsTool::Run()
{
	Add();
}

void AddObjectsTool::RollBack()
{
	Remove();
}

const wxChar* RemoveObjectsTool::GetTitle()
{
	return _("Remove Objects");
}

void RemoveObjectsTool::Run()
{
	Remove();
}

void RemoveObjectsTool::RollBack()
{
	Add();
}

void ChangeOwnerTool::Run()
{
	// to do
}

void ChangeOwnerTool::RollBack()
{
	// to do
}

ManyChangeOwnerTool::ManyChangeOwnerTool(const std::list<HeeksObj*> &list, HeeksObj* new_owner): m_objects(list), m_new_owner(new_owner)
{
	for(std::list<HeeksObj*>::iterator It = m_objects.begin(); It != m_objects.end(); It++){
		HeeksObj* object = *It;
		m_prev_owners.push_back(object->Owner());
	}
}

void ManyChangeOwnerTool::Run()
{
	for(std::list<HeeksObj*>::iterator It = m_objects.begin(); It != m_objects.end(); It++){
		HeeksObj* object = *It;
		object->Owner()->Remove(object);
		wxGetApp().m_marked_list->Remove(object, false);
	}

	wxGetApp().WereRemoved(m_objects);
	wxGetApp().WereModified(m_prev_owners);

	for(std::list<HeeksObj*>::iterator It = m_objects.begin(); It != m_objects.end(); It++){
		HeeksObj* object = *It;
		m_new_owner->Add(object, NULL);
	}

	wxGetApp().WereAdded(m_objects);
	wxGetApp().WasModified(m_new_owner);
}

void ManyChangeOwnerTool::RollBack()
{
	for(std::list<HeeksObj*>::iterator It = m_objects.begin(); It != m_objects.end(); It++){
		HeeksObj* object = *It;
		m_new_owner->Remove(object);
		wxGetApp().m_marked_list->Remove(object, false);
	}

	wxGetApp().WereRemoved(m_objects);
	wxGetApp().WasModified(m_new_owner);

	std::list<HeeksObj*>::iterator PrevIt = m_objects.begin();
	for(std::list<HeeksObj*>::iterator It = m_objects.begin(); It != m_objects.end(); It++, PrevIt++){
		HeeksObj* object = *It;
		HeeksObj* prev_owner = *PrevIt;
		prev_owner->Add(object, NULL);
	}

	wxGetApp().WereAdded(m_objects);
	wxGetApp().WereModified(m_prev_owners);
}
<commit_msg>I fixed a problem < create two points, select them, do "Group", they don't appear in the group in the tree >. This problem appeared after Jon Pry's multiple parents change. This doesn't fix celeron55's < if I copy & paste a group, it will do it, but the result is an empty group and copies of the solids in it >, which I will fix before the end of this day.<commit_after>// RemoveOrAddTool.cpp
// Copyright (c) 2009, Dan Heeks
// This program is released under the BSD license. See the file COPYING for details.

#include "stdafx.h"

#include "RemoveOrAddTool.h"
#include "../interface/HeeksObj.h"
#include "MarkedList.h"

RemoveOrAddTool::RemoveOrAddTool(HeeksObj *object, HeeksObj *owner, HeeksObj *prev_object) : m_belongs_to_owner(false)
{
	m_object = object;
	m_owner = owner;
	m_prev_object = prev_object;
}

RemoveOrAddTool::~RemoveOrAddTool()
{
	if(m_owner == NULL)return;
	if(!m_belongs_to_owner)delete m_object;
}

static wxString string_for_GetTitle;

const wxChar* AddObjectTool::GetTitle()
{
	string_for_GetTitle.assign(_("Add "));
	string_for_GetTitle.append(m_object->GetShortStringOrTypeString());
	return string_for_GetTitle.c_str();
}

void RemoveOrAddTool::Add()
{

	if (wxGetApp().m_doing_rollback && (m_owner == NULL))
	{
		m_owner = NULL;
	}

	if (m_owner == NULL)
	{
		wxMessageBox(_T("Can't Have NULL owner!"));
		return;
	}

	m_owner->Add(m_object, m_prev_object);

	wxGetApp().WasAdded(m_object);
	wxGetApp().WasModified(m_owner);

	m_belongs_to_owner = true;
}

void RemoveOrAddTool::Remove()
{
	while (m_object->Owner())
	{
		m_owner = m_object->Owner();
		m_object->Owner()->Remove(m_object);
		wxGetApp().WasRemoved(m_object);
		wxGetApp().WasModified(m_owner);
		m_object->RemoveOwner(m_object->Owner());
	}
	m_belongs_to_owner = false;
}

void AddObjectTool::Run()
{
	Add();
}

void AddObjectTool::RollBack()
{
	Remove();
}

RemoveObjectTool::RemoveObjectTool(HeeksObj *object):RemoveOrAddTool(object, NULL, NULL)
{
	if(object)m_owner = object->Owner();
	else m_owner = NULL;
}

void RemoveObjectTool::Run()
{
	Remove();
}

void RemoveObjectTool::RollBack()
{
	Add();
}

ManyRemoveOrAddTool::~ManyRemoveOrAddTool()
{
	if(!m_belongs_to_owner){
		std::list<HeeksObj*>::iterator It;
		for(It = m_objects.begin(); It != m_objects.end(); It++){
			HeeksObj* object = *It;
            delete object;
		}
	}
}

void ManyRemoveOrAddTool::Add()
{
	if (m_owner == NULL)
	{
		wxMessageBox(_T("Can't have NULL owner!"));
		return;
	}

	std::list<HeeksObj*>::iterator It;
	for(It = m_objects.begin(); It != m_objects.end(); It++){
		HeeksObj* object = *It;
		m_owner->Add(object, NULL);
	}

	wxGetApp().WereAdded(m_objects);
	wxGetApp().WasModified(m_owner);

	m_belongs_to_owner = true;
}

void ManyRemoveOrAddTool::Remove()
{
	std::list<HeeksObj*>::iterator It;
	for(It = m_objects.begin(); It != m_objects.end(); It++){
		HeeksObj* object = *It;
		if(m_owner)
			m_owner->Remove(object);
		wxGetApp().m_marked_list->Remove(object, false);
	}

	wxGetApp().WereRemoved(m_objects);
	wxGetApp().WasModified(m_owner);
	for(It = m_objects.begin(); It != m_objects.end(); It++){
		HeeksObj* object = *It;
		object->RemoveOwners();
	}

	m_belongs_to_owner = false;
}

const wxChar* AddObjectsTool::GetTitle()
{
	return _("Add Objects");
}

void AddObjectsTool::Run()
{
	Add();
}

void AddObjectsTool::RollBack()
{
	Remove();
}

const wxChar* RemoveObjectsTool::GetTitle()
{
	return _("Remove Objects");
}

void RemoveObjectsTool::Run()
{
	Remove();
}

void RemoveObjectsTool::RollBack()
{
	Add();
}

void ChangeOwnerTool::Run()
{
	// to do
}

void ChangeOwnerTool::RollBack()
{
	// to do
}

ManyChangeOwnerTool::ManyChangeOwnerTool(const std::list<HeeksObj*> &list, HeeksObj* new_owner): m_objects(list), m_new_owner(new_owner)
{
	for(std::list<HeeksObj*>::iterator It = m_objects.begin(); It != m_objects.end(); It++){
		HeeksObj* object = *It;
		m_prev_owners.push_back(object->Owner());
	}
}

void ManyChangeOwnerTool::Run()
{
	for(std::list<HeeksObj*>::iterator It = m_objects.begin(); It != m_objects.end(); It++){
		HeeksObj* object = *It;
		object->Owner()->Remove(object);
		wxGetApp().m_marked_list->Remove(object, false);
	}

	wxGetApp().WereRemoved(m_objects);
	wxGetApp().WereModified(m_prev_owners);

	for(std::list<HeeksObj*>::iterator It = m_objects.begin(); It != m_objects.end(); It++){
		HeeksObj* object = *It;
		object->RemoveOwner(object->Owner());
		m_new_owner->Add(object, NULL);
	}

	wxGetApp().WereAdded(m_objects);
	wxGetApp().WasModified(m_new_owner);
}

void ManyChangeOwnerTool::RollBack()
{
	for(std::list<HeeksObj*>::iterator It = m_objects.begin(); It != m_objects.end(); It++){
		HeeksObj* object = *It;
		m_new_owner->Remove(object);
		wxGetApp().m_marked_list->Remove(object, false);
	}

	wxGetApp().WereRemoved(m_objects);
	wxGetApp().WasModified(m_new_owner);

	std::list<HeeksObj*>::iterator PrevIt = m_objects.begin();
	for(std::list<HeeksObj*>::iterator It = m_objects.begin(); It != m_objects.end(); It++, PrevIt++){
		HeeksObj* object = *It;
		HeeksObj* prev_owner = *PrevIt;
		prev_owner->Add(object, NULL);
	}

	wxGetApp().WereAdded(m_objects);
	wxGetApp().WereModified(m_prev_owners);
}
<|endoftext|>


<commit_before>/*
Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/

#include "Types.h"
#include "ResourceManager.h"
#include "ResourceLoader.h"
#include "String.h"
#include "Hash.h"
#include "Path.h"
#include <algorithm>

namespace crown
{

//-----------------------------------------------------------------------------
ResourceManager::ResourceManager(Filesystem* filesystem) :
	m_resource_loader(this, filesystem),
	m_resources(m_allocator)
{
}

//-----------------------------------------------------------------------------
ResourceManager::~ResourceManager()
{
}

//-----------------------------------------------------------------------------
ResourceId ResourceManager::load(const char* name)
{
	char basename[512];
	char extension[512];

	path::basename(name, basename, 512);
	path::extension(name, extension, 512);

	uint32_t name_hash = hash::fnv1a_32(basename, string::strlen(basename));
	uint32_t type_hash = hash::fnv1a_32(extension, string::strlen(extension));

	return load(name_hash, type_hash);
}

//-----------------------------------------------------------------------------
ResourceId ResourceManager::load(uint32_t name, uint32_t type)
{
	// Search for an already existent resource
	ResourceEntry* entry = std::find(m_resources.begin(), m_resources.end(), name);

	// If resource not found, create a new one
	if (entry == m_resources.end())
	{
		ResourceId id;
		id.name = name;
		id.type = type;
		id.index = m_resources.size();

		ResourceEntry entry;
		entry.id = id;
		entry.state = RS_UNLOADED;
		entry.references = 1;
		entry.resource = NULL;

		m_resources.push_back(entry);

		m_resource_loader.load(id);

		return id;
	}

	// Else, increment its reference count
	entry->references++;

	return entry->id;
}

//-----------------------------------------------------------------------------
void ResourceManager::unload(ResourceId name)
{
	assert(has(name));

	ResourceEntry& entry = m_resources[name.index];

	entry.references--;

	if (entry.references == 0)
	{
		entry.state = RS_UNLOADED;
		entry.resource = NULL;

		m_resource_loader.unload(name);
	}
}

//-----------------------------------------------------------------------------
void ResourceManager::reload(ResourceId name)
{
	assert(has(name));

	ResourceEntry& entry = m_resources[name.index];

	if (entry.state == RS_LOADED)
	{
		// FIXME
	}
}

//-----------------------------------------------------------------------------
bool ResourceManager::has(ResourceId name)
{
	if (m_resources.size() > name.index)
	{
		return (m_resources[name.index].id.name == name.name);
	}

	return false;
}

//-----------------------------------------------------------------------------
void* ResourceManager::data(ResourceId name)
{
	assert(has(name));

	return m_resources[name.index].resource;
}

//-----------------------------------------------------------------------------
bool ResourceManager::is_loaded(ResourceId name)
{
	if (has(name))
	{
		return m_resources[name.index].state == RS_LOADED;
	}

	return false;
}

//-----------------------------------------------------------------------------
void ResourceManager::loading(ResourceId name)
{
	assert(has(name) == true);

	m_resources[name.index].state = RS_LOADING;
}

//-----------------------------------------------------------------------------
void ResourceManager::online(ResourceId name, void* resource)
{
	assert(has(name) == true);
	//assert(resource != NULL);

	ResourceEntry& entry = m_resources[name.index];

	entry.resource = resource;
	entry.state = RS_LOADED;
}

} // namespace crown

<commit_msg>Use filename_without_extension to identify resource name<commit_after>/*
Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/

#include "Types.h"
#include "ResourceManager.h"
#include "ResourceLoader.h"
#include "String.h"
#include "Hash.h"
#include "Path.h"
#include <algorithm>

namespace crown
{

//-----------------------------------------------------------------------------
ResourceManager::ResourceManager(Filesystem* filesystem) :
	m_resource_loader(this, filesystem),
	m_resources(m_allocator)
{
}

//-----------------------------------------------------------------------------
ResourceManager::~ResourceManager()
{
}

//-----------------------------------------------------------------------------
ResourceId ResourceManager::load(const char* name)
{
	char basename[512];
	char extension[512];

	path::filename_without_extension(name, basename, 512);
	path::extension(name, extension, 512);

	uint32_t name_hash = hash::fnv1a_32(basename, string::strlen(basename));
	uint32_t type_hash = hash::fnv1a_32(extension, string::strlen(extension));

	return load(name_hash, type_hash);
}

//-----------------------------------------------------------------------------
ResourceId ResourceManager::load(uint32_t name, uint32_t type)
{
	// Search for an already existent resource
	ResourceEntry* entry = std::find(m_resources.begin(), m_resources.end(), name);

	// If resource not found, create a new one
	if (entry == m_resources.end())
	{
		ResourceId id;
		id.name = name;
		id.type = type;
		id.index = m_resources.size();

		ResourceEntry entry;
		entry.id = id;
		entry.state = RS_UNLOADED;
		entry.references = 1;
		entry.resource = NULL;

		m_resources.push_back(entry);

		m_resource_loader.load(id);

		return id;
	}

	// Else, increment its reference count
	entry->references++;

	return entry->id;
}

//-----------------------------------------------------------------------------
void ResourceManager::unload(ResourceId name)
{
	assert(has(name));

	ResourceEntry& entry = m_resources[name.index];

	entry.references--;

	if (entry.references == 0)
	{
		entry.state = RS_UNLOADED;
		entry.resource = NULL;

		m_resource_loader.unload(name);
	}
}

//-----------------------------------------------------------------------------
void ResourceManager::reload(ResourceId name)
{
	assert(has(name));

	ResourceEntry& entry = m_resources[name.index];

	if (entry.state == RS_LOADED)
	{
		// FIXME
	}
}

//-----------------------------------------------------------------------------
bool ResourceManager::has(ResourceId name)
{
	if (m_resources.size() > name.index)
	{
		return (m_resources[name.index].id.name == name.name);
	}

	return false;
}

//-----------------------------------------------------------------------------
void* ResourceManager::data(ResourceId name)
{
	assert(has(name));

	return m_resources[name.index].resource;
}

//-----------------------------------------------------------------------------
bool ResourceManager::is_loaded(ResourceId name)
{
	if (has(name))
	{
		return m_resources[name.index].state == RS_LOADED;
	}

	return false;
}

//-----------------------------------------------------------------------------
void ResourceManager::loading(ResourceId name)
{
	assert(has(name) == true);

	m_resources[name.index].state = RS_LOADING;
}

//-----------------------------------------------------------------------------
void ResourceManager::online(ResourceId name, void* resource)
{
	assert(has(name) == true);
	//assert(resource != NULL);

	ResourceEntry& entry = m_resources[name.index];

	entry.resource = resource;
	entry.state = RS_LOADED;
}

} // namespace crown

<|endoftext|>