<commit_before>/**
 * Copyright (c) 2016 zScale Technology GmbH <legal@zscale.io>
 * Authors:
 *   - Paul Asmuth <paul@zscale.io>
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License ("the license") as
 * published by the Free Software Foundation, either version 3 of the License,
 * or any later version.
 *
 * In accordance with Section 7(e) of the license, the licensing of the Program
 * under the license does not imply a trademark license. Therefore any rights,
 * title and interest in our trademarks remain entirely with us.
 *
 * This program 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 license for more details.
 *
 * You can be released from the requirements of the license by purchasing a
 * commercial license. Buying such a license is mandatory as soon as you develop
 * commercial activities involving this program without disclosing the source
 * code of your own applications
 */
#include <eventql/cli/console.h>
#include <eventql/util/inspect.h>
#include "eventql/util/logging.h"
#include "eventql/util/random.h"
#include "eventql/util/util/Base64.h"
#include "eventql/util/thread/eventloop.h"
#include "eventql/util/thread/threadpool.h"
#include "eventql/util/thread/FixedSizeThreadPool.h"
#include "eventql/util/io/TerminalOutputStream.h"
#include "eventql/util/wallclock.h"
#include "eventql/util/json/json.h"
#include "eventql/util/json/jsonrpc.h"
#include "eventql/util/http/httpclient.h"
#include "eventql/util/http/HTTPSSEResponseHandler.h"
#include "eventql/util/cli/CLI.h"
#include "eventql/util/cli/flagparser.h"
#include "eventql/util/cli/term.h"
#include "eventql/server/sql/codec/binary_codec.h"
#include "eventql/sql/result_list.h"
#include "linenoise/linenoise.h"

namespace eventql {
namespace cli {

void Console::startInteractiveShell() {
  char *p;
  while ((p = linenoise("evql> ")) != NULL) {
    String line(p);
    linenoiseFree(p);

    if (line == "quit") {
      return;

    } else {
      runQuery(line);
    }
  }
}

Console::Console(const CLIConfig cli_cfg) : cfg_(cli_cfg) {}

Status Console::runQuery(const String& query) {
  auto stdout_os = OutputStream::getStdout();
  auto stderr_os = TerminalOutputStream::fromStream(OutputStream::getStderr());
  bool line_dirty = false;
  bool is_tty = stderr_os->isTTY();

  bool error = false;
  csql::BinaryResultParser res_parser;
  csql::ResultList results;

  res_parser.onProgress([&stderr_os, &line_dirty, is_tty] (
      const csql::ExecutionStatus& status) {
    auto status_line = StringUtil::format(
        "Query running: $0%",
        status.progress * 100);

    if (is_tty) {
      stderr_os->eraseLine();
      stderr_os->print("\r" + status_line);
      line_dirty = true;
    } else {
      stderr_os->print(status_line + "\n");
    }

  });

  res_parser.onTableHeader([&results] (const Vector<String>& columns) {
    results.addHeader(columns);
  });

  res_parser.onRow([&results] (int argc, const csql::SValue* argv) {
    results.addRow(argv, argc);
  });

  res_parser.onError([&stderr_os, &error] (const String& error_str) {
    stderr_os->print(
        "ERROR:",
        { TerminalStyle::RED, TerminalStyle::UNDERSCORE });

    stderr_os->print(StringUtil::format(" $0\n", error_str));
    error = true;
  });

  try {
    auto url = StringUtil::format(
        "http://$0:$1/api/v1/sql",
        cfg_.getHost(),
        cfg_.getPort());

    auto postdata = StringUtil::format(
          "format=binary&query=$0&database=$1",
          URI::urlEncode(query),
          URI::urlEncode(cfg_.getDatabase()));

    http::HTTPMessage::HeaderList auth_headers;
    if (!cfg_.getAuthToken().isEmpty()) {
      auth_headers.emplace_back(
          "Authorization",
          StringUtil::format("Token $0", cfg_.getAuthToken().get()));
    } else if (!cfg_.getUser().empty()) {
      auth_headers.emplace_back(
          "Authorization",
          StringUtil::format("Basic $0",
              util::Base64::encode(cfg_.getUser() + ":" + cfg_.getPassword())));
    }

    http::HTTPClient http_client(nullptr);
    auto req = http::HTTPRequest::mkPost(url, postdata, auth_headers);
    auto res = http_client.executeRequest(
        req,
        http::StreamingResponseHandler::getFactory(
            std::bind(
                &csql::BinaryResultParser::parse,
                &res_parser,
                std::placeholders::_1,
                std::placeholders::_2)));

    if (!res_parser.eof()) {
      stderr_os->print(
          "ERROR:",
          { TerminalStyle::RED, TerminalStyle::UNDERSCORE });

      stderr_os->print(" connection to server lost");
      return Status(eIOError);
    }
  } catch (const StandardException& e) {
    stderr_os->print(
        "ERROR:",
        { TerminalStyle::RED, TerminalStyle::UNDERSCORE });

    stderr_os->print(StringUtil::format(" $0\n", e.what()));
    return Status(eIOError);
  }

  if (is_tty) {
    stderr_os->eraseLine();
    stderr_os->print("\r");
  }

  if (error) {
    return Status(eIOError);
  }

  results.debugPrint();

  auto num_rows = results.getNumRows();
  auto status_line = StringUtil::format(
      "$0 row$1 returned",
      num_rows,
      num_rows > 1 ? "s" : "");

  if (is_tty) {
    stderr_os->print("\r" + status_line + "\n");
  } else {
    stderr_os->print(status_line + "\n");
  }

  return Status::success();
}

Status Console::runJS(const String& program_source) {
  auto stdout_os = OutputStream::getStdout();
  auto stderr_os = TerminalOutputStream::fromStream(OutputStream::getStderr());

  try {

    bool finished = false;
    bool error = false;
    String error_string;
    bool line_dirty = false;
    bool is_tty = stderr_os->isTTY();

    auto event_handler = [&] (const http::HTTPSSEEvent& ev) {
      if (ev.name.isEmpty()) {
        return;
      }

      if (ev.name.get() == "status") {
        auto obj = json::parseJSON(ev.data);
        auto tasks_completed = json::objectGetUInt64(obj, "num_tasks_completed");
        auto tasks_total = json::objectGetUInt64(obj, "num_tasks_total");
        auto tasks_running = json::objectGetUInt64(obj, "num_tasks_running");
        auto progress = json::objectGetFloat(obj, "progress");

        auto status_line = StringUtil::format(
            "[$0/$1] $2 tasks running ($3%)",
            tasks_completed.isEmpty() ? 0 : tasks_completed.get(),
            tasks_total.isEmpty() ? 0 : tasks_total.get(),
            tasks_running.isEmpty() ? 0 : tasks_running.get(),
            progress.isEmpty() ? 0 : progress.get() * 100);

        if (is_tty) {
          stderr_os->eraseLine();
          stderr_os->print("\r" + status_line);
          line_dirty = true;
        } else {
          stderr_os->print(status_line + "\n");
        }

        return;
      }

      if (line_dirty) {
        stderr_os->eraseLine();
        stderr_os->print("\r");
        line_dirty = false;
      }

      if (ev.name.get() == "job_started") {
        //stderr_os->printYellow(">> Job started\n");
        return;
      }

      if (ev.name.get() == "job_finished") {
        finished = true;
        return;
      }

      if (ev.name.get() == "error") {
        error = true;
        error_string = URI::urlDecode(ev.data);
        return;
      }

      if (ev.name.get() == "result") {
        stdout_os->write(URI::urlDecode(ev.data) + "\n");
        return;
      }

      if (ev.name.get() == "log") {
        stderr_os->print(URI::urlDecode(ev.data) + "\n");
        return;
      }

    };

    auto url = StringUtil::format(
        "http://$0:$1/api/v1/mapreduce/execute",
        cfg_.getHost(),
        cfg_.getPort());

    http::HTTPMessage::HeaderList auth_headers;
    auth_headers.emplace_back(
        "Authorization",
        StringUtil::format("Token $0", cfg_.getAuthToken().get()));

    if (is_tty) {
      stderr_os->print("Launching job...");
      line_dirty = true;
    } else {
      stderr_os->print("Launching job...\n");
    }

    http::HTTPClient http_client(nullptr);
    auto req = http::HTTPRequest::mkPost(url, program_source, auth_headers);
    auto res = http_client.executeRequest(
        req,
        http::HTTPSSEResponseHandler::getFactory(event_handler));

    if (line_dirty) {
      stderr_os->eraseLine();
      stderr_os->print("\r");
    }

    if (res.statusCode() != 200) {
      error = true;
      error_string = "HTTP Error: " + res.body().toString();
    }

    if (!finished && !error) {
      error = true;
      error_string = "connection to server lost";
    }

    if (error) {
      stderr_os->print(
          "ERROR:",
          { TerminalStyle::RED, TerminalStyle::UNDERSCORE });

      stderr_os->print(" " + error_string + "\n");
      return Status(eIOError);
    } else {
      stderr_os->printGreen("Job successfully completed\n");
      return Status::success();
    }
  } catch (const StandardException& e) {
    stderr_os->print(
        "ERROR:",
        { TerminalStyle::RED, TerminalStyle::UNDERSCORE });

    stderr_os->print(StringUtil::format(" $0\n", e.what()));
    return Status(eIOError);
  }

}

} // namespace cli
} // namespace eventql

<commit_msg>console: print empty result<commit_after>/**
 * Copyright (c) 2016 zScale Technology GmbH <legal@zscale.io>
 * Authors:
 *   - Paul Asmuth <paul@zscale.io>
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License ("the license") as
 * published by the Free Software Foundation, either version 3 of the License,
 * or any later version.
 *
 * In accordance with Section 7(e) of the license, the licensing of the Program
 * under the license does not imply a trademark license. Therefore any rights,
 * title and interest in our trademarks remain entirely with us.
 *
 * This program 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 license for more details.
 *
 * You can be released from the requirements of the license by purchasing a
 * commercial license. Buying such a license is mandatory as soon as you develop
 * commercial activities involving this program without disclosing the source
 * code of your own applications
 */
#include <eventql/cli/console.h>
#include <eventql/util/inspect.h>
#include "eventql/util/logging.h"
#include "eventql/util/random.h"
#include "eventql/util/util/Base64.h"
#include "eventql/util/thread/eventloop.h"
#include "eventql/util/thread/threadpool.h"
#include "eventql/util/thread/FixedSizeThreadPool.h"
#include "eventql/util/io/TerminalOutputStream.h"
#include "eventql/util/wallclock.h"
#include "eventql/util/json/json.h"
#include "eventql/util/json/jsonrpc.h"
#include "eventql/util/http/httpclient.h"
#include "eventql/util/http/HTTPSSEResponseHandler.h"
#include "eventql/util/cli/CLI.h"
#include "eventql/util/cli/flagparser.h"
#include "eventql/util/cli/term.h"
#include "eventql/server/sql/codec/binary_codec.h"
#include "eventql/sql/result_list.h"
#include "linenoise/linenoise.h"

namespace eventql {
namespace cli {

void Console::startInteractiveShell() {
  char *p;
  while ((p = linenoise("evql> ")) != NULL) {
    String line(p);
    linenoiseFree(p);

    if (line == "quit") {
      return;

    } else {
      runQuery(line);
    }
  }
}

Console::Console(const CLIConfig cli_cfg) : cfg_(cli_cfg) {}

Status Console::runQuery(const String& query) {
  auto stdout_os = OutputStream::getStdout();
  auto stderr_os = TerminalOutputStream::fromStream(OutputStream::getStderr());
  bool line_dirty = false;
  bool is_tty = stderr_os->isTTY();

  bool error = false;
  csql::BinaryResultParser res_parser;
  csql::ResultList results;

  res_parser.onProgress([&stderr_os, &line_dirty, is_tty] (
      const csql::ExecutionStatus& status) {
    auto status_line = StringUtil::format(
        "Query running: $0%",
        status.progress * 100);

    if (is_tty) {
      stderr_os->eraseLine();
      stderr_os->print("\r" + status_line);
      line_dirty = true;
    } else {
      stderr_os->print(status_line + "\n");
    }

  });

  res_parser.onTableHeader([&results] (const Vector<String>& columns) {
    results.addHeader(columns);
  });

  res_parser.onRow([&results] (int argc, const csql::SValue* argv) {
    results.addRow(argv, argc);
  });

  res_parser.onError([&stderr_os, &error] (const String& error_str) {
    stderr_os->print(
        "ERROR:",
        { TerminalStyle::RED, TerminalStyle::UNDERSCORE });

    stderr_os->print(StringUtil::format(" $0\n", error_str));
    error = true;
  });

  try {
    auto url = StringUtil::format(
        "http://$0:$1/api/v1/sql",
        cfg_.getHost(),
        cfg_.getPort());

    auto postdata = StringUtil::format(
          "format=binary&query=$0&database=$1",
          URI::urlEncode(query),
          URI::urlEncode(cfg_.getDatabase()));

    http::HTTPMessage::HeaderList auth_headers;
    if (!cfg_.getAuthToken().isEmpty()) {
      auth_headers.emplace_back(
          "Authorization",
          StringUtil::format("Token $0", cfg_.getAuthToken().get()));
    } else if (!cfg_.getUser().empty()) {
      auth_headers.emplace_back(
          "Authorization",
          StringUtil::format("Basic $0",
              util::Base64::encode(cfg_.getUser() + ":" + cfg_.getPassword())));
    }

    http::HTTPClient http_client(nullptr);
    auto req = http::HTTPRequest::mkPost(url, postdata, auth_headers);
    auto res = http_client.executeRequest(
        req,
        http::StreamingResponseHandler::getFactory(
            std::bind(
                &csql::BinaryResultParser::parse,
                &res_parser,
                std::placeholders::_1,
                std::placeholders::_2)));

    if (!res_parser.eof()) {
      stderr_os->print(
          "ERROR:",
          { TerminalStyle::RED, TerminalStyle::UNDERSCORE });

      stderr_os->print(" connection to server lost");
      return Status(eIOError);
    }
  } catch (const StandardException& e) {
    stderr_os->print(
        "ERROR:",
        { TerminalStyle::RED, TerminalStyle::UNDERSCORE });

    stderr_os->print(StringUtil::format(" $0\n", e.what()));
    return Status(eIOError);
  }

  if (is_tty) {
    stderr_os->eraseLine();
    stderr_os->print("\r");
  }

  if (error) {
    return Status(eIOError);
  }

  if (results.getNumRows() == 0) {
    String line;
    if (is_tty) {
      line = "\r";
    }

    if (results.getNumColumns() == 0) {
      line += "Query OK \n\n";
    } else {
      line += "Empty set \n\n";
    }

    stderr_os->print(line);
    return Status::success();
  }

  results.debugPrint();

  auto num_rows = results.getNumRows();
  auto status_line = StringUtil::format(
      "$0 row$1 returned",
      num_rows,
      num_rows > 1 ? "s" : "");

  if (is_tty) {
    stderr_os->print("\r" + status_line + "\n\n");
  } else {
    stderr_os->print(status_line + "\n\n");
  }

  return Status::success();
}

Status Console::runJS(const String& program_source) {
  auto stdout_os = OutputStream::getStdout();
  auto stderr_os = TerminalOutputStream::fromStream(OutputStream::getStderr());

  try {

    bool finished = false;
    bool error = false;
    String error_string;
    bool line_dirty = false;
    bool is_tty = stderr_os->isTTY();

    auto event_handler = [&] (const http::HTTPSSEEvent& ev) {
      if (ev.name.isEmpty()) {
        return;
      }

      if (ev.name.get() == "status") {
        auto obj = json::parseJSON(ev.data);
        auto tasks_completed = json::objectGetUInt64(obj, "num_tasks_completed");
        auto tasks_total = json::objectGetUInt64(obj, "num_tasks_total");
        auto tasks_running = json::objectGetUInt64(obj, "num_tasks_running");
        auto progress = json::objectGetFloat(obj, "progress");

        auto status_line = StringUtil::format(
            "[$0/$1] $2 tasks running ($3%)",
            tasks_completed.isEmpty() ? 0 : tasks_completed.get(),
            tasks_total.isEmpty() ? 0 : tasks_total.get(),
            tasks_running.isEmpty() ? 0 : tasks_running.get(),
            progress.isEmpty() ? 0 : progress.get() * 100);

        if (is_tty) {
          stderr_os->eraseLine();
          stderr_os->print("\r" + status_line);
          line_dirty = true;
        } else {
          stderr_os->print(status_line + "\n");
        }

        return;
      }

      if (line_dirty) {
        stderr_os->eraseLine();
        stderr_os->print("\r");
        line_dirty = false;
      }

      if (ev.name.get() == "job_started") {
        //stderr_os->printYellow(">> Job started\n");
        return;
      }

      if (ev.name.get() == "job_finished") {
        finished = true;
        return;
      }

      if (ev.name.get() == "error") {
        error = true;
        error_string = URI::urlDecode(ev.data);
        return;
      }

      if (ev.name.get() == "result") {
        stdout_os->write(URI::urlDecode(ev.data) + "\n");
        return;
      }

      if (ev.name.get() == "log") {
        stderr_os->print(URI::urlDecode(ev.data) + "\n");
        return;
      }

    };

    auto url = StringUtil::format(
        "http://$0:$1/api/v1/mapreduce/execute",
        cfg_.getHost(),
        cfg_.getPort());

    http::HTTPMessage::HeaderList auth_headers;
    auth_headers.emplace_back(
        "Authorization",
        StringUtil::format("Token $0", cfg_.getAuthToken().get()));

    if (is_tty) {
      stderr_os->print("Launching job...");
      line_dirty = true;
    } else {
      stderr_os->print("Launching job...\n");
    }

    http::HTTPClient http_client(nullptr);
    auto req = http::HTTPRequest::mkPost(url, program_source, auth_headers);
    auto res = http_client.executeRequest(
        req,
        http::HTTPSSEResponseHandler::getFactory(event_handler));

    if (line_dirty) {
      stderr_os->eraseLine();
      stderr_os->print("\r");
    }

    if (res.statusCode() != 200) {
      error = true;
      error_string = "HTTP Error: " + res.body().toString();
    }

    if (!finished && !error) {
      error = true;
      error_string = "connection to server lost";
    }

    if (error) {
      stderr_os->print(
          "ERROR:",
          { TerminalStyle::RED, TerminalStyle::UNDERSCORE });

      stderr_os->print(" " + error_string + "\n");
      return Status(eIOError);
    } else {
      stderr_os->printGreen("Job successfully completed\n");
      return Status::success();
    }
  } catch (const StandardException& e) {
    stderr_os->print(
        "ERROR:",
        { TerminalStyle::RED, TerminalStyle::UNDERSCORE });

    stderr_os->print(StringUtil::format(" $0\n", e.what()));
    return Status(eIOError);
  }

}

} // namespace cli
} // namespace eventql

<|endoftext|>


<commit_before>#include <jni.h>
#include <errno.h>
#include <iostream>
#include <fstream>
#include <string>

#include <android/log.h>
#include <android/native_activity.h>
#include <android_native_app_glue.h>
#include <android/asset_manager.h>

#include "../../test_all.hpp"
#include "../../util/test_path.hpp"

#define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, "native-activity", __VA_ARGS__))
#define LOGW(...) ((void)__android_log_print(ANDROID_LOG_WARN, "native-activity", __VA_ARGS__))

void android_main(struct android_app* state) {

	// Make sure glue isn't stripped.
	app_dummy();

	ANativeActivity* nativeActivity = state->activity;
	const char* externalDataPath = nativeActivity->externalDataPath;
	const char* internalDataPath = nativeActivity->internalDataPath;
	std::string inDataPath(internalDataPath);
	std::string exDataPath(externalDataPath);

	LOGI("Copying asset files...");
	const int buffer_size = 255;
	AAssetManager* assetManager = state->activity->assetManager;
	AAssetDir* assetDir = AAssetManager_openDir(assetManager, "");
    const char* filename = (const char*)NULL;
    while ((filename = AAssetDir_getNextFileName(assetDir)) != NULL) {
    	LOGI("Asset file: %s", filename);
		AAsset* asset = AAssetManager_open(assetManager, filename, AASSET_MODE_STREAMING);
		char buf[buffer_size];
		int nb_read = 0;
		std::string filename_str(filename);
		std::string filepath = inDataPath + "/" + filename_str;
		FILE* out = fopen(filepath.c_str(), "w");
		while ((nb_read = AAsset_read(asset, buf, buffer_size)) > 0)
		    fwrite(buf, nb_read, 1, out);
		fclose(out);
		AAsset_close(asset);
    }
    AAssetDir_close(assetDir);
    LOGI("Copying of asset files completed");

	tightdb::test_util::PlatformConfig* platform_config = tightdb::test_util::PlatformConfig::Instance();
	platform_config->set_path(inDataPath + "/");
	platform_config->set_resource_path(inDataPath + "/");

	LOGI("Starting unit tests...");

	test_all(0,0);

	LOGI("Done running unit tests...");

	LOGI("Copying the test results in the external storage");
	std::string source = inDataPath + "/unit-test-report.xml";
	std::string destination = exDataPath + "/unit-test-report.xml";
	std::ifstream src(source.c_str(), std::ios::binary);
    std::ofstream dst(destination.c_str(), std::ios::binary);
	dst << src.rdbuf();
	LOGI("The XML file is located in %s", destination.c_str());

	ANativeActivity_finish(nativeActivity);

	return;
}
<commit_msg>Fix indentation<commit_after>#include <jni.h>
#include <errno.h>
#include <iostream>
#include <fstream>
#include <string>

#include <android/log.h>
#include <android/native_activity.h>
#include <android_native_app_glue.h>
#include <android/asset_manager.h>

#include "../../test_all.hpp"
#include "../../util/test_path.hpp"

#define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, "native-activity", __VA_ARGS__))
#define LOGW(...) ((void)__android_log_print(ANDROID_LOG_WARN, "native-activity", __VA_ARGS__))

void android_main(struct android_app* state) {

    // Make sure glue isn't stripped.
    app_dummy();

    ANativeActivity* nativeActivity = state->activity;
    const char* externalDataPath = nativeActivity->externalDataPath;
    const char* internalDataPath = nativeActivity->internalDataPath;
    std::string inDataPath(internalDataPath);
    std::string exDataPath(externalDataPath);

    LOGI("Copying asset files...");
    const int buffer_size = 255;
    AAssetManager* assetManager = state->activity->assetManager;
    AAssetDir* assetDir = AAssetManager_openDir(assetManager, "");
    const char* filename = (const char*)NULL;
    while ((filename = AAssetDir_getNextFileName(assetDir)) != NULL) {
        LOGI("Asset file: %s", filename);
        AAsset* asset = AAssetManager_open(assetManager, filename, AASSET_MODE_STREAMING);
        char buf[buffer_size];
        int nb_read = 0;
        std::string filename_str(filename);
        std::string filepath = inDataPath + "/" + filename_str;
        FILE* out = fopen(filepath.c_str(), "w");
        while ((nb_read = AAsset_read(asset, buf, buffer_size)) > 0)
            fwrite(buf, nb_read, 1, out);
        fclose(out);
        AAsset_close(asset);
    }
    AAssetDir_close(assetDir);
    LOGI("Copying of asset files completed");

    tightdb::test_util::PlatformConfig* platform_config = tightdb::test_util::PlatformConfig::Instance();
    platform_config->set_path(inDataPath + "/");
    platform_config->set_resource_path(inDataPath + "/");

    LOGI("Starting unit tests...");

    test_all(0,0);

    LOGI("Done running unit tests...");

    LOGI("Copying the test results in the external storage");
    std::string source = inDataPath + "/unit-test-report.xml";
    std::string destination = exDataPath + "/unit-test-report.xml";
    std::ifstream src(source.c_str(), std::ios::binary);
    std::ofstream dst(destination.c_str(), std::ios::binary);
    dst << src.rdbuf();
    LOGI("The XML file is located in %s", destination.c_str());

    ANativeActivity_finish(nativeActivity);

    return;
}
<|endoftext|>


<commit_before>// -----------------------------------------------------------------------
// pion-common: a collection of common libraries used by the Pion Platform
// -----------------------------------------------------------------------
// Copyright (C) 2007-2008 Atomic Labs, Inc.  (http://www.atomiclabs.com)
//
// Distributed under the Boost Software License, Version 1.0.
// See http://www.boost.org/LICENSE_1_0.txt
//

#include <pion/PionConfig.hpp>
#include <pion/PionCounter.hpp>
#include <pion/PionUnitTestDefs.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/mpl/list.hpp>

using namespace pion;

class NewPionCounter_F : public PionCounter {
public:
	NewPionCounter_F() {
	}
	~NewPionCounter_F() {
	}

private:
};

BOOST_AUTO_TEST_SUITE_FIXTURE_TEMPLATE(NewPionCounter_S, boost::mpl::list<NewPionCounter_F>)

BOOST_AUTO_TEST_CASE_FIXTURE_TEMPLATE(checkGetValueReturnsZero) {
	BOOST_CHECK_EQUAL(getValue(), static_cast<unsigned long long>(0));
}

BOOST_AUTO_TEST_CASE_FIXTURE_TEMPLATE(checkGetValueAfterIncrement) {
	increment();
	BOOST_CHECK_EQUAL(getValue(), static_cast<unsigned long long>(1));
}

BOOST_AUTO_TEST_CASE_FIXTURE_TEMPLATE(checkGetValueAfterDecrement) {
	decrement();
	BOOST_CHECK_EQUAL(getValue(), static_cast<unsigned long long>(-1));
}

BOOST_AUTO_TEST_CASE_FIXTURE_TEMPLATE(checkGetValueAfterReset) {
	reset();
	BOOST_CHECK_EQUAL(getValue(), static_cast<unsigned long long>(0));
}

BOOST_AUTO_TEST_SUITE_END()

class PionCounterSetTo5_F : public PionCounter {
public:
	PionCounterSetTo5_F() {
		assign(5);
	}
	~PionCounterSetTo5_F() {
	}

private:
};

BOOST_AUTO_TEST_SUITE_FIXTURE_TEMPLATE(PionCounterSetTo5_S, boost::mpl::list<PionCounterSetTo5_F>)

BOOST_AUTO_TEST_CASE_FIXTURE_TEMPLATE(checkGetValueReturns5) {
	BOOST_CHECK_EQUAL(getValue(), static_cast<unsigned long long>(5));
}

BOOST_AUTO_TEST_CASE_FIXTURE_TEMPLATE(checkGetValueAfterIncrement) {
	increment();
	BOOST_CHECK_EQUAL(getValue(), static_cast<unsigned long long>(6));
}

BOOST_AUTO_TEST_CASE_FIXTURE_TEMPLATE(checkGetValueAfterDecrement) {
	decrement();
	BOOST_CHECK_EQUAL(getValue(), static_cast<unsigned long long>(4));
}

BOOST_AUTO_TEST_CASE_FIXTURE_TEMPLATE(checkGetValueAfterReset) {
	reset();
	BOOST_CHECK_EQUAL(getValue(), static_cast<unsigned long long>(0));
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Reverting the last change to PionCounterTests.cpp, because gcc is complaining, and the changes aren't needed.<commit_after>// -----------------------------------------------------------------------
// pion-common: a collection of common libraries used by the Pion Platform
// -----------------------------------------------------------------------
// Copyright (C) 2007-2008 Atomic Labs, Inc.  (http://www.atomiclabs.com)
//
// Distributed under the Boost Software License, Version 1.0.
// See http://www.boost.org/LICENSE_1_0.txt
//

#include <pion/PionConfig.hpp>
#include <pion/PionCounter.hpp>
#include <boost/test/unit_test.hpp>

using namespace pion;

class NewPionCounter_F : public PionCounter {
public:
	NewPionCounter_F() {
	}
	~NewPionCounter_F() {
	}

private:
};

BOOST_FIXTURE_TEST_SUITE(NewPionCounter_S, NewPionCounter_F)

BOOST_AUTO_TEST_CASE(checkGetValueReturnsZero) {
	BOOST_CHECK_EQUAL(getValue(), static_cast<unsigned long long>(0));
}

BOOST_AUTO_TEST_CASE(checkGetValueAfterIncrement) {
	increment();
	BOOST_CHECK_EQUAL(getValue(), static_cast<unsigned long long>(1));
}

BOOST_AUTO_TEST_CASE(checkGetValueAfterDecrement) {
	decrement();
	BOOST_CHECK_EQUAL(getValue(), static_cast<unsigned long long>(-1));
}

BOOST_AUTO_TEST_CASE(checkGetValueAfterReset) {
	reset();
	BOOST_CHECK_EQUAL(getValue(), static_cast<unsigned long long>(0));
}

BOOST_AUTO_TEST_SUITE_END()

class PionCounterSetTo5_F : public PionCounter {
public:
	PionCounterSetTo5_F() {
		assign(5);
	}
	~PionCounterSetTo5_F() {
	}

private:
};

BOOST_FIXTURE_TEST_SUITE(PionCounterSetTo5_S, PionCounterSetTo5_F)

BOOST_AUTO_TEST_CASE(checkGetValueReturns5) {
	BOOST_CHECK_EQUAL(getValue(), static_cast<unsigned long long>(5));
}

BOOST_AUTO_TEST_CASE(checkGetValueAfterIncrement) {
	increment();
	BOOST_CHECK_EQUAL(getValue(), static_cast<unsigned long long>(6));
}

BOOST_AUTO_TEST_CASE(checkGetValueAfterDecrement) {
	decrement();
	BOOST_CHECK_EQUAL(getValue(), static_cast<unsigned long long>(4));
}

BOOST_AUTO_TEST_CASE(checkGetValueAfterReset) {
	reset();
	BOOST_CHECK_EQUAL(getValue(), static_cast<unsigned long long>(0));
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>#include "rendering.h"
#include "../events/events.h"

class Renderer
{
private:
	Int32				m_bInitComplete;
	SDL_Window*			m_Window;
	Events::Mailbox*	m_pMailbox;

	GLeffect			m_eftMesh;
	GLbuffer			m_bufPerMesh;
	GLbuffer			m_bufPerFrame;

	GLmesh				m_glmArena;

	GLmesh				m_glmKart;

public:
	int Init( SDL_Window* win );
	int Update( float fElapseSec );
	int Render();

	Renderer();
	~Renderer();
};

Renderer* g_pRenderer = 0;

int InitRendering( SDL_Window* win )
{
	if( g_pRenderer ) return 0;
	g_pRenderer = new Renderer();
	return g_pRenderer ? g_pRenderer->Init( win ) : 0;
}

int UpdateRendering( float fElapseSec )
{
	return g_pRenderer ? g_pRenderer->Update( fElapseSec ) : 0;
}

int Render()
{
	return g_pRenderer ? g_pRenderer->Render() : 0;
}

int ShutdownRendering()
{
	if( !g_pRenderer ) return 0;
	delete g_pRenderer;
	return 1;
}

Renderer::Renderer()
{
	m_bInitComplete = 0;
}

Renderer::~Renderer()
{
	glhDestroyBuffer( m_bufPerMesh );
	glhDestroyBuffer( m_bufPerFrame );
	glhUnloadEffect( m_eftMesh );
}

int Renderer::Init( SDL_Window* win )
{
	m_Window = win;
	m_pMailbox = new Events::Mailbox();

	if( glewInit() != GLEW_OK )
		return 1;

	// OpenGL Test Info
	const GLubyte* strVendor = glGetString( GL_VENDOR );
	GLint major, minor;
	glGetIntegerv( GL_MAJOR_VERSION, &major );
	glGetIntegerv( GL_MINOR_VERSION, &minor );

	// OpenGL State Init
	glClearDepth( 1.0f );
	glEnable( GL_DEPTH_TEST );
	glEnable( GL_CULL_FACE );
	glCullFace( GL_FRONT );
	glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST );
	glEnable( GL_MULTISAMPLE );

	// Load Standard Effects
	const GLchar* aryHeaders[] = { "component/rendering/ShaderStructs.glsl" };
	m_eftMesh = glhLoadEffect( "component/rendering/VShader.glsl", NULL, "component/rendering/PShader.glsl", aryHeaders, 1 );
	if( !m_eftMesh.program )
		return 0;

	glhCreateBuffer( m_eftMesh, "cstPerMesh", sizeof(cstPerMesh), &m_bufPerMesh );
	glhCreateBuffer( m_eftMesh, "cstPerFrame", sizeof(cstPerFrame), &m_bufPerFrame );

	{
		GLchar* pData;
		Int32 nSize;
		if( !glhReadFile( "assets/Arena.msh", pData, nSize ) )
			return 0;

		SEG::Mesh meshdata;
		GetMutState()->bttmArena = new btTriangleMesh();
		if( !meshdata.ReadData( (Byte*)pData, nSize, 0, GetMutState()->bttmArena ) )
			return 0;

		free( pData );

		if( !glhCreateMesh( m_glmArena, meshdata ) )
			return 0;
	}

	{
		GLchar* pData;
		Int32 nSize;
		if( !glhReadFile( "assets/RedBox.msh", pData, nSize ) )
			return 0;

		SEG::Mesh meshdata;
		if( !meshdata.ReadData( (Byte*)pData, nSize ) )
			return 0;

		free( pData );

		if( !glhCreateMesh( m_glmKart, meshdata ) )
			return 0;
	}

	m_pMailbox->request( Events::EventType::StateUpdate );

	m_bInitComplete = 1;

	return 1;
}

int Renderer::Update( float fElapseSec )
{
	if( !m_bInitComplete )
		return 0;

	const std::vector<Events::Event*> aryEvents = m_pMailbox->checkMail();
	for( int i = 0; i < aryEvents.size(); i++ )
	{
		switch( aryEvents[i]->type )
		{
		case Events::EventType::StateUpdate:
			{
				//DEBUGOUT( "I GOT HERE!" );
			}
			break;
		}
	}

	cstPerFrame& perFrame = *(cstPerFrame*)m_bufPerFrame.data;

	Int32 nWinWidth, nWinHeight;
	SDL_GetWindowSize( m_Window, &nWinWidth, &nWinHeight );

	Vector3 vFocus = GetState().Camera.vFocus;
	perFrame.vEyePos = GetState().Camera.vPos;
	perFrame.vEyeDir = Vector3( vFocus - perFrame.vEyePos.xyz() ).Normalize();
	perFrame.matProj.Perspective( DEGTORAD( 60.0f ), (Real)nWinWidth/nWinHeight, 0.1f, 100.0f );
	perFrame.matView.LookAt( perFrame.vEyePos.xyz(), vFocus, Vector3( 0, 1, 0 ) );
	perFrame.matViewProj = perFrame.matView * perFrame.matProj;
	glhUpdateBuffer( m_eftMesh, m_bufPerFrame );

	return 1;
}

int Renderer::Render()
{
	if( !m_bInitComplete )
		return 0;

	cstPerMesh& perMesh = *(cstPerMesh*)m_bufPerMesh.data;
	cstPerFrame& perFrame = *(cstPerFrame*)m_bufPerFrame.data;

	perMesh.matWorld.Identity();
	perMesh.matWorldViewProj = perMesh.matWorld * perFrame.matViewProj;
	glhUpdateBuffer( m_eftMesh, m_bufPerMesh );
	glhDrawMesh( m_eftMesh, m_glmArena );

	perMesh.matWorld = Matrix::GetScale( 0.3f, 0.3f, 0.5f ) *
		Matrix::GetRotateQuaternion( GetState().Karts[0].qOrient ) *
		Matrix::GetTranslate( GetState().Karts[0].vPos );
	perMesh.matWorldViewProj = perMesh.matWorld * perFrame.matViewProj;
	glhUpdateBuffer( m_eftMesh, m_bufPerMesh );
	glhDrawMesh( m_eftMesh, m_glmKart );

	SDL_GL_SwapWindow( m_Window );

	return 1;
}
<commit_msg>Change rendering to receive input<commit_after>#include "rendering.h"
#include "../events/events.h"

class Renderer
{
private:
	Int32				m_bInitComplete;
	SDL_Window*			m_Window;
	Events::Mailbox*	m_pMailbox;

	GLeffect			m_eftMesh;
	GLbuffer			m_bufPerMesh;
	GLbuffer			m_bufPerFrame;

	GLmesh				m_glmArena;

	GLmesh				m_glmKart;

public:
	int Init( SDL_Window* win );
	int Update( float fElapseSec );
	int Render();

	Renderer();
	~Renderer();
};

Renderer* g_pRenderer = 0;

int InitRendering( SDL_Window* win )
{
	if( g_pRenderer ) return 0;
	g_pRenderer = new Renderer();
	return g_pRenderer ? g_pRenderer->Init( win ) : 0;
}

int UpdateRendering( float fElapseSec )
{
	return g_pRenderer ? g_pRenderer->Update( fElapseSec ) : 0;
}

int Render()
{
	return g_pRenderer ? g_pRenderer->Render() : 0;
}

int ShutdownRendering()
{
	if( !g_pRenderer ) return 0;
	delete g_pRenderer;
	return 1;
}

Renderer::Renderer()
{
	m_bInitComplete = 0;
}

Renderer::~Renderer()
{
	glhDestroyBuffer( m_bufPerMesh );
	glhDestroyBuffer( m_bufPerFrame );
	glhUnloadEffect( m_eftMesh );
}

int Renderer::Init( SDL_Window* win )
{
	m_Window = win;
	m_pMailbox = new Events::Mailbox();
	m_pMailbox->request(Events::EventType::Input);

	if( glewInit() != GLEW_OK )
		return 1;

	// OpenGL Test Info
	const GLubyte* strVendor = glGetString( GL_VENDOR );
	GLint major, minor;
	glGetIntegerv( GL_MAJOR_VERSION, &major );
	glGetIntegerv( GL_MINOR_VERSION, &minor );

	// OpenGL State Init
	glClearDepth( 1.0f );
	glEnable( GL_DEPTH_TEST );
	glEnable( GL_CULL_FACE );
	glCullFace( GL_FRONT );
	glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST );
	glEnable( GL_MULTISAMPLE );

	// Load Standard Effects
	const GLchar* aryHeaders[] = { "component/rendering/ShaderStructs.glsl" };
	m_eftMesh = glhLoadEffect( "component/rendering/VShader.glsl", NULL, "component/rendering/PShader.glsl", aryHeaders, 1 );
	if( !m_eftMesh.program )
		return 0;

	glhCreateBuffer( m_eftMesh, "cstPerMesh", sizeof(cstPerMesh), &m_bufPerMesh );
	glhCreateBuffer( m_eftMesh, "cstPerFrame", sizeof(cstPerFrame), &m_bufPerFrame );

	{
		GLchar* pData;
		Int32 nSize;
		if( !glhReadFile( "assets/Arena.msh", pData, nSize ) )
			return 0;

		SEG::Mesh meshdata;
		GetMutState()->bttmArena = new btTriangleMesh();
		if( !meshdata.ReadData( (Byte*)pData, nSize, 0, GetMutState()->bttmArena ) )
			return 0;

		free( pData );

		if( !glhCreateMesh( m_glmArena, meshdata ) )
			return 0;
	}

	{
		GLchar* pData;
		Int32 nSize;
		if( !glhReadFile( "assets/RedBox.msh", pData, nSize ) )
			return 0;

		SEG::Mesh meshdata;
		if( !meshdata.ReadData( (Byte*)pData, nSize ) )
			return 0;

		free( pData );

		if( !glhCreateMesh( m_glmKart, meshdata ) )
			return 0;
	}

	m_pMailbox->request( Events::EventType::StateUpdate );

	m_bInitComplete = 1;

	return 1;
}

int Renderer::Update( float fElapseSec )
{
	if( !m_bInitComplete )
		return 0;

	const std::vector<Events::Event*> aryEvents = m_pMailbox->checkMail();
	for( int i = 0; i < aryEvents.size(); i++ )
	{
		switch( aryEvents[i]->type )
		{
		case Events::EventType::StateUpdate:
			{
				//DEBUGOUT( "I GOT HERE!" );
			}
			break;
		case Events::EventType::Input:
			{
				Events::InputEvent* input = (Events::InputEvent*)aryEvents[i];

			}
			break;
		}
	}

	cstPerFrame& perFrame = *(cstPerFrame*)m_bufPerFrame.data;

	Int32 nWinWidth, nWinHeight;
	SDL_GetWindowSize( m_Window, &nWinWidth, &nWinHeight );

	Vector3 vFocus = GetState().Camera.vFocus;
	perFrame.vEyePos = GetState().Camera.vPos;
	perFrame.vEyeDir = Vector3( vFocus - perFrame.vEyePos.xyz() ).Normalize();
	perFrame.matProj.Perspective( DEGTORAD( 60.0f ), (Real)nWinWidth/nWinHeight, 0.1f, 100.0f );
	perFrame.matView.LookAt( perFrame.vEyePos.xyz(), vFocus, Vector3( 0, 1, 0 ) );
	perFrame.matViewProj = perFrame.matView * perFrame.matProj;
	glhUpdateBuffer( m_eftMesh, m_bufPerFrame );

	return 1;
}

int Renderer::Render()
{
	if( !m_bInitComplete )
		return 0;

	cstPerMesh& perMesh = *(cstPerMesh*)m_bufPerMesh.data;
	cstPerFrame& perFrame = *(cstPerFrame*)m_bufPerFrame.data;

	perMesh.matWorld.Identity();
	perMesh.matWorldViewProj = perMesh.matWorld * perFrame.matViewProj;
	glhUpdateBuffer( m_eftMesh, m_bufPerMesh );
	glhDrawMesh( m_eftMesh, m_glmArena );

	perMesh.matWorld = Matrix::GetScale( 0.3f, 0.3f, 0.5f ) *
		Matrix::GetRotateQuaternion( GetState().Karts[0].qOrient ) *
		Matrix::GetTranslate( GetState().Karts[0].vPos );
	perMesh.matWorldViewProj = perMesh.matWorld * perFrame.matViewProj;
	glhUpdateBuffer( m_eftMesh, m_bufPerMesh );
	glhDrawMesh( m_eftMesh, m_glmKart );

	SDL_GL_SwapWindow( m_Window );

	return 1;
}
<|endoftext|>


<commit_before>#include <highgui.h>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/features2d/features2d.hpp>
#include <iostream>
#include <fstream>

using namespace std;
using namespace cv;

void warpPerspectiveRand( const Mat& src, Mat& dst, Mat& H, RNG& rng )
{
    H.create(3, 3, CV_32FC1);
    H.at<float>(0,0) = rng.uniform( 0.8f, 1.2f);
    H.at<float>(0,1) = rng.uniform(-0.1f, 0.1f);
    H.at<float>(0,2) = rng.uniform(-0.1f, 0.1f)*src.cols;
    H.at<float>(1,0) = rng.uniform(-0.1f, 0.1f);
    H.at<float>(1,1) = rng.uniform( 0.8f, 1.2f);
    H.at<float>(1,2) = rng.uniform(-0.1f, 0.1f)*src.rows;
    H.at<float>(2,0) = rng.uniform( -1e-4f, 1e-4f);
    H.at<float>(2,1) = rng.uniform( -1e-4f, 1e-4f);
    H.at<float>(2,2) = rng.uniform( 0.8f, 1.2f);

    warpPerspective( src, dst, H, src.size() );
}

int main( int argc, char **argv )
{
    #if 0
    if( argc != 4 && argc != 3 )
    {
        cout << "Format:" << endl <<
                "   classifier(xml to write) test_image file_with_train_images_filenames(txt)" <<
                "   or" << endl <<
                "   classifier(xml to read) test_image" << endl;
        return -1;
    }

    CalonderClassifier classifier;
    if( argc == 4 ) // Train
    {
        // Read train images and test image
        ifstream fst( argv[3], ifstream::in );
        vector<Mat> trainImgs;
        while( !fst.eof() )
        {
            string str;
            getline( fst, str );
            if (str.empty()) break;
            Mat img = imread( str, CV_LOAD_IMAGE_GRAYSCALE );
            if( !img.empty() )
                trainImgs.push_back( img );
        }
        if( trainImgs.empty() )
        {
            cout << "All train images can not be read." << endl;
            return -1;
        }
        cout << trainImgs.size() << " train images were read." << endl;

        // Extract keypoints from train images
        SurfFeatureDetector detector;
        vector<vector<Point2f> > trainPoints( trainImgs.size() );
        for( size_t i = 0; i < trainImgs.size(); i++ )
        {
            vector<KeyPoint> kps;
            detector.detect( trainImgs[i], kps );
            KeyPoint::convert( kps, trainPoints[i] );
        }

        // Train Calonder classifier on extracted points
        classifier.setVerbose( true);
        classifier.train( trainPoints, trainImgs );

        // Write Calonder classifier
        FileStorage fs( argv[1], FileStorage::WRITE );
        if( fs.isOpened() ) classifier.write( fs );
    }
    else
    {
        // Read Calonder classifier
        FileStorage fs( argv[1], FileStorage::READ );
        if( fs.isOpened() ) classifier.read( fs.root() );
    }

    if( classifier.empty() )
    {
        cout << "Calonder classifier is empty" << endl;
        return -1;
    }

    // Test Calonder classifier on test image and warped one
    Mat testImg1 = imread( argv[2], CV_LOAD_IMAGE_GRAYSCALE ), testImg2, H12;
    if( testImg1.empty() )
    {
        cout << "Test image can not be read." << endl;
        return -1;
    }
    warpPerspectiveRand( testImg1, testImg2, H12, theRNG() );

    // Exstract keypoints from test images
    SurfFeatureDetector detector;
    vector<KeyPoint> testKeypoints1; detector.detect( testImg1, testKeypoints1 );
    vector<KeyPoint> testKeypoints2; detector.detect( testImg2, testKeypoints2 );
    vector<Point2f> testPoints1; KeyPoint::convert( testKeypoints1, testPoints1 );
    vector<Point2f> testPoints2; KeyPoint::convert( testKeypoints2, testPoints2 );

    // Calculate Calonder descriptors
    int signatureSize = classifier.getSignatureSize();
    vector<float> r1(testPoints1.size()*signatureSize), r2(testPoints2.size()*signatureSize);
    vector<float>::iterator rit = r1.begin();
    for( size_t i = 0; i < testPoints1.size(); i++ )
    {
        vector<float> s;
        classifier( testImg1, testPoints1[i], s );
        copy( s.begin(), s.end(), rit );
        rit += s.size();
    }
    rit = r2.begin();
    for( size_t i = 0; i < testPoints2.size(); i++ )
    {
        vector<float> s;
        classifier( testImg2, testPoints2[i], s );
        copy( s.begin(), s.end(), rit );
        rit += s.size();
    }

    Mat descriptors1(testPoints1.size(), classifier.getSignatureSize(), CV_32FC1, &r1[0] ),
        descriptors2(testPoints2.size(), classifier.getSignatureSize(), CV_32FC1, &r2[0] );

    // Match descriptors
    BruteForceMatcher<L1<float> > matcher;
    matcher.add( descriptors2 );
    vector<int> matches;
    matcher.match( descriptors1, matches );

    // Draw results
    // Prepare inlier mask
    vector<char> matchesMask( matches.size(), 0 );
    Mat points1t; perspectiveTransform(Mat(testPoints1), points1t, H12);
    vector<int>::const_iterator mit = matches.begin();
    for( size_t mi = 0; mi < matches.size(); mi++ )
    {
        if( norm(testPoints2[matches[mi]] - points1t.at<Point2f>(mi,0)) < 4 ) // inlier
            matchesMask[mi] = 1;
    }
    // Draw
    Mat drawImg;
    drawMatches( testImg1, testKeypoints1, testImg2, testKeypoints2, matches, drawImg, CV_RGB(0, 255, 0), CV_RGB(0, 0, 255), matchesMask  );
    string winName = "Matches";
    namedWindow( winName, WINDOW_AUTOSIZE );
    imshow( winName, drawImg );
    waitKey();
#endif
    return 0;
}
<commit_msg>modified sample find_obj_calonder<commit_after>#include <highgui.h>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/features2d/features2d.hpp>
#include <iostream>
#include <fstream>

using namespace std;
using namespace cv;

/*
 * Generates random perspective transform of image
 */
void warpPerspectiveRand( const Mat& src, Mat& dst, Mat& H, RNG& rng )
{
    H.create(3, 3, CV_32FC1);
    H.at<float>(0,0) = rng.uniform( 0.8f, 1.2f);
    H.at<float>(0,1) = rng.uniform(-0.1f, 0.1f);
    H.at<float>(0,2) = rng.uniform(-0.1f, 0.1f)*src.cols;
    H.at<float>(1,0) = rng.uniform(-0.1f, 0.1f);
    H.at<float>(1,1) = rng.uniform( 0.8f, 1.2f);
    H.at<float>(1,2) = rng.uniform(-0.1f, 0.1f)*src.rows;
    H.at<float>(2,0) = rng.uniform( -1e-4f, 1e-4f);
    H.at<float>(2,1) = rng.uniform( -1e-4f, 1e-4f);
    H.at<float>(2,2) = rng.uniform( 0.8f, 1.2f);

    warpPerspective( src, dst, H, src.size() );
}

/*
 * Trains Calonder classifier and writes trained classifier in file:
 *      imgFilename - name of .txt file which contains list of full filenames of train images,
 *      classifierFilename - name of binary file in which classifier will be written.
 *
 * To train Calonder classifier RTreeClassifier class need to be used.
 */
void trainCalonderClassifier( const string& classifierFilename, const string& imgFilename )
{
    // Reads train images
    ifstream is( imgFilename.c_str(), ifstream::in );
    vector<Mat> trainImgs;
    while( !is.eof() )
    {
        string str;
        getline( is, str );
        if (str.empty()) break;
        Mat img = imread( str, CV_LOAD_IMAGE_GRAYSCALE );
        if( !img.empty() )
            trainImgs.push_back( img );
    }
    if( trainImgs.empty() )
    {
        cout << "All train images can not be read." << endl;
        exit(-1);
    }
    cout << trainImgs.size() << " train images were read." << endl;

    // Extracts keypoints from train images
    SurfFeatureDetector detector;
    vector<BaseKeypoint> trainPoints;
    vector<IplImage> iplTrainImgs(trainImgs.size());
    for( size_t imgIdx = 0; imgIdx < trainImgs.size(); imgIdx++ )
    {
        iplTrainImgs[imgIdx] = trainImgs[imgIdx];
        vector<KeyPoint> kps; detector.detect( trainImgs[imgIdx], kps );

        for( size_t pointIdx = 0; pointIdx < kps.size(); pointIdx++ )
        {
            Point2f p = kps[pointIdx].pt;
            trainPoints.push_back( BaseKeypoint(cvRound(p.x), cvRound(p.y), &iplTrainImgs[imgIdx]) );
        }
    }

    // Trains Calonder classifier on extracted points
    RTreeClassifier classifier;
    classifier.train( trainPoints, theRNG(), 48, 9, 100 );
    // Writes classifier
    classifier.write( classifierFilename.c_str() );
}

/*
 * Test Calonder classifier to match keypoints on given image:
 *      classifierFilename - name of file from which classifier will be read,
 *      imgFilename - test image filename.
 *
 * To calculate keypoint descriptors you may use RTreeClassifier class (as to train),
 * but it is convenient to use CalonderDescriptorExtractor class which is wrapper of
 * RTreeClassifier.
 */
void testCalonderClassifier( const string& classifierFilename, const string& imgFilename )
{
    Mat img1 = imread( imgFilename, CV_LOAD_IMAGE_GRAYSCALE ), img2, H12;
    if( img1.empty() )
    {
        cout << "Test image can not be read." << endl;
        exit(-1);
    }
    warpPerspectiveRand( img1, img2, H12, theRNG() );

    // Exstract keypoints from test images
    SurfFeatureDetector detector;
    vector<KeyPoint> keypoints1; detector.detect( img1, keypoints1 );
    vector<KeyPoint> keypoints2; detector.detect( img2, keypoints2 );

    // Compute descriptors
    CalonderDescriptorExtractor<float> de( classifierFilename );
    Mat descriptors1;  de.compute( img1, keypoints1, descriptors1 );
    Mat descriptors2;  de.compute( img2, keypoints2, descriptors2 );

    // Match descriptors
    BruteForceMatcher<L1<float> > matcher;
    matcher.add( descriptors2 );
    vector<int> matches;
    matcher.match( descriptors1, matches );

    // Prepare inlier mask
    vector<char> matchesMask( matches.size(), 0 );
    vector<Point2f> points1; KeyPoint::convert( keypoints1, points1 );
    vector<Point2f> points2; KeyPoint::convert( keypoints2, points2 );
    Mat points1t; perspectiveTransform(Mat(points1), points1t, H12);
    vector<int>::const_iterator mit = matches.begin();
    for( size_t mi = 0; mi < matches.size(); mi++ )
    {
        if( norm(points2[matches[mi]] - points1t.at<Point2f>(mi,0)) < 4 ) // inlier
            matchesMask[mi] = 1;
    }

    // Draw
    Mat drawImg;
    drawMatches( img1, keypoints1, img2, keypoints2, matches, drawImg, CV_RGB(0, 255, 0), CV_RGB(0, 0, 255), matchesMask );
    string winName = "Matches";
    namedWindow( winName, WINDOW_AUTOSIZE );
    imshow( winName, drawImg );
    waitKey();
}

int main( int argc, char **argv )
{
    if( argc != 4 && argc != 3 )
    {
        cout << "Format:" << endl <<
                "   classifier_file(to write) test_image file_with_train_images_filenames(txt)" <<
                "   or" << endl <<
                "   classifier_file(to read) test_image" << endl;
        return -1;
    }

    if( argc == 4 )
        trainCalonderClassifier( argv[1], argv[3] );

    testCalonderClassifier( argv[1], argv[2] );

    return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2009 libmv authors.
//
// 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 "libmv/image/image.h"
#include "libmv/image/image_drawing.h"
#include "libmv/logging/logging.h"
#include "testing/testing.h"

using namespace libmv;

namespace {

// Horizontal / Vertical scanlines
// Assert that pixels was drawn at the good place
TEST(ImageDrawing, Scanlines) {

  const int w = 10, h = 10;
  Array3Du image(h,w);
  image.Fill(0);

  // horizontal scanline
  //  __________
  //  |         |
  //  |__here___|
  //  |         |
  //  |_________|
  const int y = 5;
  DrawLine( 0, y, w-1, y, 255, &image);
  for(int i=0; i < w; ++i)
    EXPECT_EQ( image(y,i), 255);

  image.Fill(0);

  // Vertical scanline
  //  __________
  //  |    h|   |
  //  |    e|   |
  //  |    r|   |
  //  |____e|___|
  const int x = 5;
  DrawLine( x, 0, x, h-1, 255, &image);
  for (int i = 0; i < h; ++i)
    EXPECT_EQ(image(i,y), 255);
}

// Lines with a given angle +/-45°
// Assert that pixels was drawn at the good place
TEST(ImageDrawing, Lines45) {

  const int w = 10, h = 10;
  Array3Du image(h,w);
  image.Fill(0);

  //  _____
  //  |\  |
  //  | \ |
  //  |__\|

  DrawLine(0, 0, w-1, h-1, 255, &image);
  for (int i = 0; i < w; ++i)
    EXPECT_EQ(image(i,i), 255);

  image.Fill(0);

  //  _____
  //  |  / |
  //  | /  |
  //  |/___|_
  DrawLine(0, h-1, w-1, 0, 255, &image);
  for (int i = 0; i < h; ++i)
    EXPECT_EQ(image(h-1-i,i), 255);
}

// Draw a circle in an image and assert that all the points are
// at a distance equal to the radius.
TEST(ImageDrawing, Circle) {

  Array3Du image(10,10);
  image.Fill(0);

  const int radius = 3;
  const int x = 5, y = 5;

  DrawCircle(x, y, radius, (unsigned char)255, &image);

  // Distance checking :
  for ( int j = 0; j < image.Height(); ++j)
  for ( int i = 0; i < image.Width(); ++i) {
    if (image(j, i) == 255)  {
      const float distance =  sqrt((j-y)*(j-y) + (i-x)*(i-x));
      EXPECT_NEAR(radius, distance, 1.0f);
      // Due to discretisation we cannot expect better precision
    }
  }
}

}
<commit_msg>- fix on windows with sqrt (expect float or double or long double but no integer).<commit_after>// Copyright (c) 2009 libmv authors.
//
// 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 "libmv/image/image.h"
#include "libmv/image/image_drawing.h"
#include "libmv/logging/logging.h"
#include "testing/testing.h"

using namespace libmv;

namespace {

// Horizontal / Vertical scanlines
// Assert that pixels was drawn at the good place
TEST(ImageDrawing, Scanlines) {

  const int w = 10, h = 10;
  Array3Du image(h,w);
  image.Fill(0);

  // horizontal scanline
  //  __________
  //  |         |
  //  |__here___|
  //  |         |
  //  |_________|
  const int y = 5;
  DrawLine( 0, y, w-1, y, 255, &image);
  for(int i=0; i < w; ++i)
    EXPECT_EQ( image(y,i), 255);

  image.Fill(0);

  // Vertical scanline
  //  __________
  //  |    h|   |
  //  |    e|   |
  //  |    r|   |
  //  |____e|___|
  const int x = 5;
  DrawLine( x, 0, x, h-1, 255, &image);
  for (int i = 0; i < h; ++i)
    EXPECT_EQ(image(i,y), 255);
}

// Lines with a given angle +/-45°
// Assert that pixels was drawn at the good place
TEST(ImageDrawing, Lines45) {

  const int w = 10, h = 10;
  Array3Du image(h,w);
  image.Fill(0);

  //  _____
  //  |\  |
  //  | \ |
  //  |__\|

  DrawLine(0, 0, w-1, h-1, 255, &image);
  for (int i = 0; i < w; ++i)
    EXPECT_EQ(image(i,i), 255);

  image.Fill(0);

  //  _____
  //  |  / |
  //  | /  |
  //  |/___|_
  DrawLine(0, h-1, w-1, 0, 255, &image);
  for (int i = 0; i < h; ++i)
    EXPECT_EQ(image(h-1-i,i), 255);
}

// Draw a circle in an image and assert that all the points are
// at a distance equal to the radius.
TEST(ImageDrawing, Circle) {

  Array3Du image(10,10);
  image.Fill(0);

  const int radius = 3;
  const int x = 5, y = 5;

  DrawCircle(x, y, radius, (unsigned char)255, &image);

  // Distance checking :
  for ( int j = 0; j < image.Height(); ++j)
  for ( int i = 0; i < image.Width(); ++i) {
    if (image(j, i) == 255)  {
      const float distance =  sqrt((float)((j-y)*(j-y) + (i-x)*(i-x)));
      EXPECT_NEAR(radius, distance, 1.0f);
      // Due to discretisation we cannot expect better precision
    }
  }
}

}
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
 *   All Rights Reserved.
 *
 * This file is CONFIDENTIAL -- Distribution or duplication of this material or
 * the information contained herein is strictly forbidden unless prior written
 * permission is obtained.
 */
#include "stx/SHA1.h"
#include "stx/protobuf/msg.h"
#include "logjoin/stages/TSDBUploadStage.h"
#include "logjoin/common.h"
#include "tsdb/RecordEnvelope.pb.h"
#include "tsdb/TimeWindowPartitioner.h"

using namespace stx;

namespace cm {

void TSDBUploadStage::process(
    RefPtr<TrackedSessionContext> ctx,
    const String& tsdb_addr,
    http::HTTPConnectionPool* http) {
  tsdb::RecordEnvelopeList records;

  auto time = ctx->joined_session.last_seen_time();
  auto record_id = SHA1::compute(ctx->tracked_session.uid);
  auto stream_key = "web.sessions";
  auto partition_key = tsdb::TimeWindowPartitioner::partitionKeyFor(
      stream_key,
      time,
      4 * kMicrosPerHour);

  auto record_data = msg::encode(ctx->joined_session);

  auto r = records.add_records();
  r->set_tsdb_namespace(ctx->tracked_session.customer_key);
  r->set_stream_key(stream_key);
  r->set_partition_key(partition_key.toString());
  r->set_record_id(record_id.toString());
  r->set_record_data(record_data->data(), record_data->size());

  URI uri(StringUtil::format("http://$0/tsdb/insert", tsdb_addr));
  http::HTTPRequest req(http::HTTPMessage::M_POST, uri.pathAndQuery());
  req.addHeader("Host", uri.hostAndPort());
  req.addHeader("Content-Type", "application/fnord-msg");
  req.addBody(*msg::encode(records));

  auto res = http->executeRequest(req);
  res.wait();

  if (res.get().statusCode() != 201) {
    RAISEF(
        kRuntimeError,
        "received non-201 response: $0",
        res.get().body().toString());
  }
}

} // namespace cm

<commit_msg>TSDBUploadStage...<commit_after>/**
 * Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
 *   All Rights Reserved.
 *
 * This file is CONFIDENTIAL -- Distribution or duplication of this material or
 * the information contained herein is strictly forbidden unless prior written
 * permission is obtained.
 */
#include "stx/SHA1.h"
#include "stx/protobuf/msg.h"
#include "logjoin/stages/TSDBUploadStage.h"
#include "logjoin/common.h"
#include "tsdb/RecordEnvelope.pb.h"
#include "tsdb/TimeWindowPartitioner.h"

using namespace stx;

namespace cm {

void TSDBUploadStage::process(
    RefPtr<TrackedSessionContext> ctx,
    const String& tsdb_addr,
    http::HTTPConnectionPool* http) {
  tsdb::RecordEnvelopeList records;

  auto time = ctx->joined_session.last_seen_time() * kMicrosPerSecond;
  auto record_id = SHA1::compute(ctx->tracked_session.uid);
  auto stream_key = "web.sessions";
  auto partition_key = tsdb::TimeWindowPartitioner::partitionKeyFor(
      stream_key,
      time,
      4 * kMicrosPerHour);

  auto record_data = msg::encode(ctx->joined_session);

  auto r = records.add_records();
  r->set_tsdb_namespace(ctx->tracked_session.customer_key);
  r->set_stream_key(stream_key);
  r->set_partition_key(partition_key.toString());
  r->set_record_id(record_id.toString());
  r->set_record_data(record_data->data(), record_data->size());

  URI uri(StringUtil::format("http://$0/tsdb/insert", tsdb_addr));
  http::HTTPRequest req(http::HTTPMessage::M_POST, uri.pathAndQuery());
  req.addHeader("Host", uri.hostAndPort());
  req.addHeader("Content-Type", "application/fnord-msg");
  req.addBody(*msg::encode(records));

  auto res = http->executeRequest(req);
  res.wait();

  if (res.get().statusCode() != 201) {
    RAISEF(
        kRuntimeError,
        "received non-201 response: $0",
        res.get().body().toString());
  }
}

} // namespace cm

<|endoftext|>


<commit_before>/*
 * Copyright 2010-2017 Branimir Karadzic. All rights reserved.
 * License: https://github.com/bkaradzic/bx#license-bsd-2-clause
 */

#include <bx/process.h>

#include <stdio.h>

#ifndef BX_CONFIG_CRT_PROCESS
#	define BX_CONFIG_CRT_PROCESS !(0  \
			|| BX_CRT_NONE            \
			|| BX_PLATFORM_EMSCRIPTEN \
			|| BX_PLATFORM_PS4        \
			|| BX_PLATFORM_WINRT      \
			|| BX_PLATFORM_XBOXONE    \
			)
#endif // BX_CONFIG_CRT_PROCESS

namespace bx
{
#if BX_CONFIG_CRT_PROCESS

#if BX_CRT_MSVC
#	define popen  _popen
#	define pclose _pclose
#endif // BX_CRT_MSVC

	ProcessReader::ProcessReader()
		: m_file(NULL)
	{
	}

	ProcessReader::~ProcessReader()
	{
		BX_CHECK(NULL == m_file, "Process not closed!");
	}

	bool ProcessReader::open(const FilePath& _filePath, const StringView& _args, Error* _err)
	{
		BX_CHECK(NULL != _err, "Reader/Writer interface calling functions must handle errors.");

		if (NULL != m_file)
		{
			BX_ERROR_SET(_err, BX_ERROR_READERWRITER_ALREADY_OPEN, "ProcessReader: File is already open.");
			return false;
		}

		char tmp[kMaxFilePath*2];
		strCopy(tmp, BX_COUNTOF(tmp), _filePath.get() );
		strCat(tmp, BX_COUNTOF(tmp), " ");
		strCat(tmp, BX_COUNTOF(tmp), _args);

		m_file = popen(tmp, "r");
		if (NULL == m_file)
		{
			BX_ERROR_SET(_err, BX_ERROR_READERWRITER_OPEN, "ProcessReader: Failed to open process.");
			return false;
		}

		return true;
	}

	void ProcessReader::close()
	{
		BX_CHECK(NULL != m_file, "Process not open!");
		FILE* file = (FILE*)m_file;
		m_exitCode = pclose(file);
		m_file = NULL;
	}

	int32_t ProcessReader::read(void* _data, int32_t _size, Error* _err)
	{
		BX_CHECK(NULL != _err, "Reader/Writer interface calling functions must handle errors."); BX_UNUSED(_err);

		FILE* file = (FILE*)m_file;
		int32_t size = (int32_t)fread(_data, 1, _size, file);
		if (size != _size)
		{
			if (0 != feof(file) )
			{
				BX_ERROR_SET(_err, BX_ERROR_READERWRITER_EOF, "ProcessReader: EOF.");
			}
			else if (0 != ferror(file) )
			{
				BX_ERROR_SET(_err, BX_ERROR_READERWRITER_READ, "ProcessReader: read error.");
			}

			return size >= 0 ? size : 0;
		}

		return size;
	}

	int32_t ProcessReader::getExitCode() const
	{
		return m_exitCode;
	}

	ProcessWriter::ProcessWriter()
		: m_file(NULL)
	{
	}

	ProcessWriter::~ProcessWriter()
	{
		BX_CHECK(NULL == m_file, "Process not closed!");
	}

	bool ProcessWriter::open(const FilePath& _filePath, const StringView& _args, Error* _err)
	{
		BX_CHECK(NULL != _err, "Reader/Writer interface calling functions must handle errors.");

		if (NULL != m_file)
		{
			BX_ERROR_SET(_err, BX_ERROR_READERWRITER_ALREADY_OPEN, "ProcessWriter: File is already open.");
			return false;
		}

		char tmp[kMaxFilePath*2];
		strCopy(tmp, BX_COUNTOF(tmp), _filePath.get() );
		strCat(tmp, BX_COUNTOF(tmp), " ");
		strCat(tmp, BX_COUNTOF(tmp), _args);

		m_file = popen(tmp, "w");
		if (NULL == m_file)
		{
			BX_ERROR_SET(_err, BX_ERROR_READERWRITER_OPEN, "ProcessWriter: Failed to open process.");
			return false;
		}

		return true;
	}

	void ProcessWriter::close()
	{
		BX_CHECK(NULL != m_file, "Process not open!");
		FILE* file = (FILE*)m_file;
		m_exitCode = pclose(file);
		m_file = NULL;
	}

	int32_t ProcessWriter::write(const void* _data, int32_t _size, Error* _err)
	{
		BX_CHECK(NULL != _err, "Reader/Writer interface calling functions must handle errors."); BX_UNUSED(_err);

		FILE* file = (FILE*)m_file;
		int32_t size = (int32_t)fwrite(_data, 1, _size, file);
		if (size != _size)
		{
			if (0 != ferror(file) )
			{
				BX_ERROR_SET(_err, BX_ERROR_READERWRITER_WRITE, "ProcessWriter: write error.");
			}

			return size >= 0 ? size : 0;
		}

		return size;
	}

	int32_t ProcessWriter::getExitCode() const
	{
		return m_exitCode;
	}
#endif // BX_CONFIG_CRT_PROCESS

} // namespace bx
<commit_msg>Quote executable name in case there are spaces.<commit_after>/*
 * Copyright 2010-2017 Branimir Karadzic. All rights reserved.
 * License: https://github.com/bkaradzic/bx#license-bsd-2-clause
 */

#include <bx/process.h>

#include <stdio.h>

#ifndef BX_CONFIG_CRT_PROCESS
#	define BX_CONFIG_CRT_PROCESS !(0  \
			|| BX_CRT_NONE            \
			|| BX_PLATFORM_EMSCRIPTEN \
			|| BX_PLATFORM_PS4        \
			|| BX_PLATFORM_WINRT      \
			|| BX_PLATFORM_XBOXONE    \
			)
#endif // BX_CONFIG_CRT_PROCESS

namespace bx
{
#if BX_CONFIG_CRT_PROCESS

#if BX_CRT_MSVC
#	define popen  _popen
#	define pclose _pclose
#endif // BX_CRT_MSVC

	ProcessReader::ProcessReader()
		: m_file(NULL)
	{
	}

	ProcessReader::~ProcessReader()
	{
		BX_CHECK(NULL == m_file, "Process not closed!");
	}

	bool ProcessReader::open(const FilePath& _filePath, const StringView& _args, Error* _err)
	{
		BX_CHECK(NULL != _err, "Reader/Writer interface calling functions must handle errors.");

		if (NULL != m_file)
		{
			BX_ERROR_SET(_err, BX_ERROR_READERWRITER_ALREADY_OPEN, "ProcessReader: File is already open.");
			return false;
		}

		char tmp[kMaxFilePath*2] = "\"";
		strCat(tmp, BX_COUNTOF(tmp), _filePath.get() );
		strCat(tmp, BX_COUNTOF(tmp), "\" ");
		strCat(tmp, BX_COUNTOF(tmp), _args);

		m_file = popen(tmp, "r");
		if (NULL == m_file)
		{
			BX_ERROR_SET(_err, BX_ERROR_READERWRITER_OPEN, "ProcessReader: Failed to open process.");
			return false;
		}

		return true;
	}

	void ProcessReader::close()
	{
		BX_CHECK(NULL != m_file, "Process not open!");
		FILE* file = (FILE*)m_file;
		m_exitCode = pclose(file);
		m_file = NULL;
	}

	int32_t ProcessReader::read(void* _data, int32_t _size, Error* _err)
	{
		BX_CHECK(NULL != _err, "Reader/Writer interface calling functions must handle errors."); BX_UNUSED(_err);

		FILE* file = (FILE*)m_file;
		int32_t size = (int32_t)fread(_data, 1, _size, file);
		if (size != _size)
		{
			if (0 != feof(file) )
			{
				BX_ERROR_SET(_err, BX_ERROR_READERWRITER_EOF, "ProcessReader: EOF.");
			}
			else if (0 != ferror(file) )
			{
				BX_ERROR_SET(_err, BX_ERROR_READERWRITER_READ, "ProcessReader: read error.");
			}

			return size >= 0 ? size : 0;
		}

		return size;
	}

	int32_t ProcessReader::getExitCode() const
	{
		return m_exitCode;
	}

	ProcessWriter::ProcessWriter()
		: m_file(NULL)
	{
	}

	ProcessWriter::~ProcessWriter()
	{
		BX_CHECK(NULL == m_file, "Process not closed!");
	}

	bool ProcessWriter::open(const FilePath& _filePath, const StringView& _args, Error* _err)
	{
		BX_CHECK(NULL != _err, "Reader/Writer interface calling functions must handle errors.");

		if (NULL != m_file)
		{
			BX_ERROR_SET(_err, BX_ERROR_READERWRITER_ALREADY_OPEN, "ProcessWriter: File is already open.");
			return false;
		}

		char tmp[kMaxFilePath*2] = "\"";
		strCat(tmp, BX_COUNTOF(tmp), _filePath.get() );
		strCat(tmp, BX_COUNTOF(tmp), "\" ");
		strCat(tmp, BX_COUNTOF(tmp), _args);

		m_file = popen(tmp, "w");
		if (NULL == m_file)
		{
			BX_ERROR_SET(_err, BX_ERROR_READERWRITER_OPEN, "ProcessWriter: Failed to open process.");
			return false;
		}

		return true;
	}

	void ProcessWriter::close()
	{
		BX_CHECK(NULL != m_file, "Process not open!");
		FILE* file = (FILE*)m_file;
		m_exitCode = pclose(file);
		m_file = NULL;
	}

	int32_t ProcessWriter::write(const void* _data, int32_t _size, Error* _err)
	{
		BX_CHECK(NULL != _err, "Reader/Writer interface calling functions must handle errors."); BX_UNUSED(_err);

		FILE* file = (FILE*)m_file;
		int32_t size = (int32_t)fwrite(_data, 1, _size, file);
		if (size != _size)
		{
			if (0 != ferror(file) )
			{
				BX_ERROR_SET(_err, BX_ERROR_READERWRITER_WRITE, "ProcessWriter: write error.");
			}

			return size >= 0 ? size : 0;
		}

		return size;
	}

	int32_t ProcessWriter::getExitCode() const
	{
		return m_exitCode;
	}
#endif // BX_CONFIG_CRT_PROCESS

} // namespace bx
<|endoftext|>


<commit_before>#include "../common.h"

#include <fstream>

#include <FreeImagePlus.h>
#include <physfs.h>

#include "fileservice.h"

#include "gamefw.h"

using namespace gamefw;

FileService::FileService()
{
    FreeImage_Initialise( 0 );
    if (!PHYSFS_isInit())
        PHYSFS_init(NULL);
    PHYSFS_setSaneConfig("config", PROJECT_NAME, "ob", 0, 1);

    m_dirseparator.assign(PHYSFS_getDirSeparator());

    // Find the project directory
    string basedir(PHYSFS_getBaseDir());

    string project_name(PROJECT_NAME);

    int project_path_pos = basedir.find(project_name);
    if (project_path_pos == basedir.npos) {
        LOG(logFATAL) << "Project " << project_name <<
        " root directory not found from " << basedir;
    }
    basedir.erase(project_path_pos + project_name.length());

    PHYSFS_mount(basedir.c_str(), NULL, 0); // Mount to root.

    m_entity_factory = new EntityFactory();
}

FileService::~FileService()
{
    delete m_entity_factory;
    PHYSFS_deinit();
    FreeImage_DeInitialise();
}

const char* FileNotFoundException::what() const throw()
{
    return "File not found.";
}

const char* FileService::fileToBuffer(const string& filename ) const
{
    const string realpath(getRealPath(filename));

    // Open file at end.
    ifstream file( realpath.c_str(), ios::in | ios::ate );

    if ( file.is_open() ) {
        uint size = (uint) file.tellg(); // Get file size.
        // The +1 is for '\0'.
        char* buffer = new char[size + 1];
        file.seekg( 0, ios::beg ); // Back to start.
        char* c = buffer;
        // Read the file to buffer.
        while (file.good()) {
            file.get(*c);
            c++;
        }

        file.close();

        *(c - 1) = '\0'; // Delete EOF.

        LOG( logINFO ) << filename << " loaded into buffer.";

        return buffer;
    }

    LOG( logERROR ) << filename << " not found.";
    throw FileNotFoundException();
}

GLuint FileService::makeTexture( const string& name ) const
{
    fipImage* image = readImage( name );

    assert( image->isValid() );

    int width = image->getWidth();
    int height = image->getHeight();
    void* pixels = (void*) image->accessPixels();
    GLuint texture;

    glGenTextures( 1, &texture );
    glBindTexture( GL_TEXTURE_2D, texture );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
    glTexImage2D(
        GL_TEXTURE_2D, 0,           // target, level
        GL_RGB8,                    // internal format
        width, height, 0,           // width, height, border
        GL_BGR, GL_UNSIGNED_BYTE,   // external format, type
        pixels                      // pixels
    );

    image->clear();
    delete image;

    return texture;

}

fipImage* FileService::readImage( const string& name ) const
{
    string filename = "assets/images/" + name + ".png";

    string realpath(getRealPath(filename));

    fipImage* image = new fipImage;

    if ( !image->load( realpath.c_str() ) ) {
        assert(false); // Shouldn't fail.
    }
    image->convertTo24Bits();

    LOG( logINFO ) << filename << " loaded to texture.";
    return image;
}

const string FileService::getRealPath(const string& path) const
{
    if (!PHYSFS_exists(path.c_str())) {
        LOG( logERROR ) << path << " not found.";
        throw FileNotFoundException();
    }
    string realpath(PHYSFS_getRealDir(path.c_str()));
    realpath += m_dirseparator + path;
    return realpath;
}

Entity FileService::createEntity(const string& name) const
{
    string path = "assets/entities/" + name + ".xml";
    string realpath(getRealPath(path));
    return m_entity_factory->createEntity(realpath);
}

const std::string gamefw::FileService::getDirSeparator() const
{
    return m_dirseparator;
}
<commit_msg>Add fallback base directory name "obsbul" in Fileservice.<commit_after>#include "../common.h"

#include <fstream>

#include <FreeImagePlus.h>
#include <physfs.h>

#include "fileservice.h"

#include "gamefw.h"

using namespace gamefw;

FileService::FileService()
{
    FreeImage_Initialise( 0 );
    if (!PHYSFS_isInit())
        PHYSFS_init(NULL);
    PHYSFS_setSaneConfig("config", PROJECT_NAME, "ob", 0, 1);

    m_dirseparator.assign(PHYSFS_getDirSeparator());

    // Find the project directory
    string basedir(PHYSFS_getBaseDir());

    string project_name(PROJECT_NAME);

    int project_path_pos = basedir.find(project_name);
    int fallback_path_pos = basedir.find(project_name);
    if (project_path_pos == basedir.npos) {
        if (fallback_path_pos == basedir.npos) {
            LOG(logFATAL) << "Project " << project_name <<
                " root directory not found from " << basedir;
		}
		project_path_pos = fallback_path_pos;
    }
    basedir.erase(project_path_pos + project_name.length());

    PHYSFS_mount(basedir.c_str(), NULL, 0); // Mount to root.

    m_entity_factory = new EntityFactory();
}

FileService::~FileService()
{
    delete m_entity_factory;
    PHYSFS_deinit();
    FreeImage_DeInitialise();
}

const char* FileNotFoundException::what() const throw()
{
    return "File not found.";
}

const char* FileService::fileToBuffer(const string& filename ) const
{
    const string realpath(getRealPath(filename));

    // Open file at end.
    ifstream file( realpath.c_str(), ios::in | ios::ate );

    if ( file.is_open() ) {
        uint size = (uint) file.tellg(); // Get file size.
        // The +1 is for '\0'.
        char* buffer = new char[size + 1];
        file.seekg( 0, ios::beg ); // Back to start.
        char* c = buffer;
        // Read the file to buffer.
        while (file.good()) {
            file.get(*c);
            c++;
        }

        file.close();

        *(c - 1) = '\0'; // Delete EOF.

        LOG( logINFO ) << filename << " loaded into buffer.";

        return buffer;
    }

    LOG( logERROR ) << filename << " not found.";
    throw FileNotFoundException();
}

GLuint FileService::makeTexture( const string& name ) const
{
    fipImage* image = readImage( name );

    assert( image->isValid() );

    int width = image->getWidth();
    int height = image->getHeight();
    void* pixels = (void*) image->accessPixels();
    GLuint texture;

    glGenTextures( 1, &texture );
    glBindTexture( GL_TEXTURE_2D, texture );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT );
    glTexImage2D(
        GL_TEXTURE_2D, 0,           // target, level
        GL_RGB8,                    // internal format
        width, height, 0,           // width, height, border
        GL_BGR, GL_UNSIGNED_BYTE,   // external format, type
        pixels                      // pixels
    );

    image->clear();
    delete image;

    return texture;

}

fipImage* FileService::readImage( const string& name ) const
{
    string filename = "assets/images/" + name + ".png";

    string realpath(getRealPath(filename));

    fipImage* image = new fipImage;

    if ( !image->load( realpath.c_str() ) ) {
        assert(false); // Shouldn't fail.
    }
    image->convertTo24Bits();

    LOG( logINFO ) << filename << " loaded to texture.";
    return image;
}

const string FileService::getRealPath(const string& path) const
{
    if (!PHYSFS_exists(path.c_str())) {
        LOG( logERROR ) << path << " not found.";
        throw FileNotFoundException();
    }
    string realpath(PHYSFS_getRealDir(path.c_str()));
    realpath += m_dirseparator + path;
    return realpath;
}

Entity FileService::createEntity(const string& name) const
{
    string path = "assets/entities/" + name + ".xml";
    string realpath(getRealPath(path));
    return m_entity_factory->createEntity(realpath);
}

const std::string gamefw::FileService::getDirSeparator() const
{
    return m_dirseparator;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: hd_docu.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: ihi $ $Date: 2006-08-24 10:44:27 $
 *
 *  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
 *
 ************************************************************************/

#include <precomp.h>
#include "hd_docu.hxx"

// NOT FULLY DEFINED SERVICES
#include <ary/cpp/c_namesp.hxx>
#include <ary/cpp/c_class.hxx>
#include <ary/cpp/c_enum.hxx>
#include <ary/cpp/c_tydef.hxx>
#include <ary/cpp/c_funct.hxx>
#include <ary/cpp/c_vari.hxx>
#include <ary/cpp/c_enuval.hxx>
#include <ary/info/codeinfo.hxx>
#include <ary/info/all_tags.hxx>
#include <ary/info/all_dts.hxx>
#include <adc_cl.hxx>
#include "html_kit.hxx"

using namespace ary::info;
using namespace csi;

using html::DefList;
using html::DefListTerm;
using html::DefListDefinition;
using html::Headline;
using html::Link;

const char *
C_sTagHeadlines[ ary::info::C_eAtTag_NrOfClasses ] =
    {
        "ATTENTION!",   "Author",       "Changes",      "Collaborators",
                                                                        "Contact",  // Contact may be unused
        "Copyright",    "Deprecated",   "Description",  "Date of Documentation",
                                                                        "How to Derive from this Class",
        "Heap object - owner is responsible for deletion.",
                        "Important Instances",
                                        "Interface Only",
                                                        "Invariant",    "Lifecycle",
        "Multiplicity", "On Error",     "Persistency",  "Postcondition",
                                                                        "Precondition",
        "Responsibilities",
                        "Return",       "Summary",      "Todos",        "Version",
        "Base Classes", "Exceptions",   "Implements",   "Keywords",     "Parameters",
        "See Also",     "Template Parameters",
                                        "",             "Since "
    };

Docu_Display::Docu_Display( OuputPage_Environment & io_rEnv )
    :   HtmlDisplay_Impl(io_rEnv),
        bUseHtmlInDocuTokens(false),
        pCurClassOverwrite(0)
{
}

Docu_Display::~Docu_Display()
{
}

void
Docu_Display::Assign_Out( csi::xml::Element & o_rOut )
{
    Easy().Enter(o_rOut);
}

void
Docu_Display::Unassign_Out()
{
    Easy().Leave();
}

void
Docu_Display::Display_Namespace( const ary::cpp::Namespace & i_rData )
{
    i_rData.Info().StoreAt( *this );
}

void
Docu_Display::Display_Class( const ary::cpp::Class & i_rData )
{
    pCurClassOverwrite = &i_rData;
    i_rData.Info().StoreAt( *this );
    pCurClassOverwrite = 0;
}

void
Docu_Display::Display_Enum( const ary::cpp::Enum & i_rData )
{
    i_rData.Info().StoreAt( *this );
}

void
Docu_Display::Display_Typedef( const ary::cpp::Typedef & i_rData )
{
    i_rData.Info().StoreAt( *this );
}

void
Docu_Display::Display_Function( const ary::cpp::Function & i_rData )
{
    i_rData.Info().StoreAt( *this );
}

void
Docu_Display::Display_Variable( const ary::cpp::Variable & i_rData )
{
    i_rData.Info().StoreAt( *this );
}

// --------------       Interface ary::info::DocuDisplay  ------------------ //

void
Docu_Display::Display_CodeInfo( const CodeInfo & i_rData )
{
    Start_DocuBlock();

    if ( i_rData.IsObsolete() )
    {
        CurOut()
            >> *new html::DefListTerm
                >> *new html::Strong
                    << "D E P R E C A T E D";

    }

    CodeInfo::TagList::const_iterator itEnd = i_rData.Tags().end();
    for ( CodeInfo::TagList::const_iterator it = i_rData.Tags().begin();
          it != itEnd;
          ++it )
    {
         (*it)->StoreAt( *this );
    }

    Finish_DocuBlock();
}

void
Docu_Display::Display_StdTag( const StdTag & i_rData )
{
    csv_assert( int(i_rData.Std_Id()) < int(ary::info::C_eAtTag_NrOfClasses) );

    const ary::info::DocuText::TokenList &
        rText = i_rData.CText().Tokens();
    typedef ary::info::DocuText::TokenList::const_iterator TokenIterator;

    if ( rText.empty() )
        return;
    else if ( rText.size() < 3 )
    {
        bool bIsWhite = true;
        for ( TokenIterator it = rText.begin();
              it != rText.end();
              ++it )
        {
            if (bIsWhite)
                bIsWhite = (*it)->IsWhite();
        }
        if (bIsWhite)
            return;
    }

    Write_TagTitle( C_sTagHeadlines[i_rData.Std_Id()] );
    Write_TagContents( i_rData.CText() );
}

void
Docu_Display::Display_BaseTag( const BaseTag & )
{

}

void
Docu_Display::Display_ExceptionTag( const ExceptionTag & )
{
}

void
Docu_Display::Display_ImplementsTag( const ImplementsTag & )
{
}

void
Docu_Display::Display_KeywordTag( const KeywordTag & )
{
}

void
Docu_Display::Display_ParameterTag( const ParameterTag & i_rData )
{
    Write_TagTitle( "Parameters" );

    adcdisp::ExplanationTable
        aParams( CurOut() >> *new DefListDefinition );

    for ( const ParameterTag * pParam = &i_rData;
          pParam != 0;
          pParam = pParam->GetNext() )   // KORR_FUTURE
    {
        aParams.AddEntry( pParam->ParamName().c_str() );

        Easy().Enter( aParams.Def() );
        Write_Text( pParam->CText() );
        Easy().Leave();
    }   // end for
}

void
Docu_Display::Display_SeeTag( const SeeTag & i_rData )
{
    Write_TagTitle( "See Also" );

    DefListDefinition * dpDef = new DefListDefinition;
    CurOut() << dpDef;
    Easy().Enter(*dpDef);

    for ( std::vector< ary::QualifiedName >::const_iterator
            it = i_rData.References().begin();
          it != i_rData.References().end();
          ++it )
    {
        Write_LinkableText( (*it) );
        CurOut() << new html::LineBreak;
    }

    Easy().Leave();
}

void
Docu_Display::Display_TemplateTag( const TemplateTag & i_rData )
{
    Write_TagTitle( "Template Parameters" );

    adcdisp::ExplanationTable
        aTplParams( CurOut() >> *new DefListDefinition );

    for ( const TemplateTag * pTplParam = &i_rData;
          pTplParam != 0;
          pTplParam = pTplParam->GetNext() )
    {
        aTplParams.AddEntry( pTplParam->TplParamName().c_str() );

        Easy().Enter( aTplParams.Def() );
        Write_Text( pTplParam->CText() );
        Easy().Leave();
    }   // end for
}

void
Docu_Display::Display_LabelTag( const LabelTag & )
{
}

void
Docu_Display::Display_SinceTag( const ary::info::SinceTag & i_rData )
{
    if ( i_rData.Version().empty() )
    {
         return;
    }

    // Transform the value of the @since tag into the text to be displayed.
    String sDisplay;
    if ( autodoc::CommandLine::Get_().DoesTransform_SinceTag() )
    {
        sDisplay = autodoc::CommandLine::Get_()
                        .DisplayOf_SinceTagValue( i_rData.Version() );
    }
    else
    {
        sDisplay = i_rData.Version();
    }

    if (sDisplay.empty())
        return;

    Write_TagTitle( "Since " );

    DefListDefinition * dpDef = new DefListDefinition;
    CurOut() << dpDef;

    Easy().Enter(*dpDef);
    CurOut() << sDisplay;
    Easy().Leave();
}

void
Docu_Display::Display_DT_Text( const DT_Text & i_rData )
{
    Write_TextToken(  i_rData.Text() );
}

void
Docu_Display::Display_DT_MaybeLink( const DT_MaybeLink & i_rData )
{
    // KORR_FUTURE
    Write_TextToken(  i_rData.Text() );
}

void
Docu_Display::Display_DT_Whitespace( const DT_Whitespace & i_rData )
{
    static char sSpace[300] =
        "                                         "
        "                                         "
        "                                         "
        "                                         "
        "                                         "
        "                                        ";
    UINT8 nLength = i_rData.Length();
    sSpace[nLength] = NULCH;
    CurOut() << sSpace;
    sSpace[nLength] = ' ';
}

void
Docu_Display::Display_DT_Eol( const DT_Eol & )
{
    CurOut() << new html::Sbr;
}

void
Docu_Display::Display_DT_Xml( const ary::info::DT_Xml & i_rData )
{
    CurOut() << new xml::XmlCode( i_rData.Text() );
}

void
Docu_Display::Start_DocuBlock()
{
    DYN DefList * dpDefList = new DefList;
    CurOut() << dpDefList;
    Easy().Enter( *dpDefList );
}

void
Docu_Display::Finish_DocuBlock()
{
    Easy().Leave();
}

void
Docu_Display::Write_TagTitle( const char *        i_sText,
                              const char *        )
{
    if ( strcmp(i_sText,"ATTENTION!") == 0 )
    {
        CurOut()
            >> *new html::DefListTerm
                << new html::ClassAttr("attention")
                << i_sText;
    }
    else
    {
        CurOut()
            >> *new html::DefListTerm
                << i_sText;
    }
}

void
Docu_Display::Write_TagContents( const DocuText & i_rDocuText )
{
    DefListDefinition * dpDef = new DefListDefinition;
    CurOut() << dpDef;

    Easy().Enter(*dpDef);
    Write_Text(i_rDocuText);
    Easy().Leave();
}

void
Docu_Display::Write_Text( const ary::info::DocuText & i_rDocuText )
{
    if ( i_rDocuText.IsNoHtml() )
    {
        CurOut()
            << new xml::XmlCode("<pre>");
        bUseHtmlInDocuTokens = false;
    }
    else
    {
         bUseHtmlInDocuTokens = true;
    }
    i_rDocuText.StoreAt( *this );
    if ( i_rDocuText.IsNoHtml() )
    {
        CurOut()
            << new xml::XmlCode("</pre>");
    }
}

void
Docu_Display::Write_TextToken( const udmstri & i_sText )
{
     if ( bUseHtmlInDocuTokens )
        CurOut() << new xml::XmlCode(i_sText);
    else
        CurOut() << i_sText;
}

void
Docu_Display::Write_LinkableText( const ary::QualifiedName & i_sQuName )
{
    const ary::CodeEntity *
        pCe = FindUnambiguousCe( Env(), i_sQuName, pCurClassOverwrite );
    if ( pCe != 0 )
    {
        csi::xml::Element *
            pLink = new csi::html::Link( Link2Ce(Env(), *pCe) );
        CurOut() << pLink;
        Easy().Enter(*pLink);
        Write_QualifiedName(i_sQuName);
        Easy().Leave();
    }
    else
    {
        Write_QualifiedName(i_sQuName);
    }
    CurOut() << " ";
}

void
Docu_Display::Write_QualifiedName( const ary::QualifiedName & i_sQuName )
{
    if ( i_sQuName.IsAbsolute() )
        CurOut() << "::";
    for ( ary::QualifiedName::namespace_iterator it = i_sQuName.first_namespace();
          it != i_sQuName.end_namespace();
          ++it )
    {
        CurOut() <<  (*it) << "::";
    }
    CurOut() << i_sQuName.LocalName();
    if ( i_sQuName.IsFunction() )
        CurOut() << "()";
}

<commit_msg>INTEGRATION: CWS pchfix02 (1.7.6); FILE MERGED 2006/09/01 17:15:31 kaib 1.7.6.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: hd_docu.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-16 16:41:28 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

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

#include <precomp.h>
#include "hd_docu.hxx"

// NOT FULLY DEFINED SERVICES
#include <ary/cpp/c_namesp.hxx>
#include <ary/cpp/c_class.hxx>
#include <ary/cpp/c_enum.hxx>
#include <ary/cpp/c_tydef.hxx>
#include <ary/cpp/c_funct.hxx>
#include <ary/cpp/c_vari.hxx>
#include <ary/cpp/c_enuval.hxx>
#include <ary/info/codeinfo.hxx>
#include <ary/info/all_tags.hxx>
#include <ary/info/all_dts.hxx>
#include <adc_cl.hxx>
#include "html_kit.hxx"

using namespace ary::info;
using namespace csi;

using html::DefList;
using html::DefListTerm;
using html::DefListDefinition;
using html::Headline;
using html::Link;

const char *
C_sTagHeadlines[ ary::info::C_eAtTag_NrOfClasses ] =
    {
        "ATTENTION!",   "Author",       "Changes",      "Collaborators",
                                                                        "Contact",  // Contact may be unused
        "Copyright",    "Deprecated",   "Description",  "Date of Documentation",
                                                                        "How to Derive from this Class",
        "Heap object - owner is responsible for deletion.",
                        "Important Instances",
                                        "Interface Only",
                                                        "Invariant",    "Lifecycle",
        "Multiplicity", "On Error",     "Persistency",  "Postcondition",
                                                                        "Precondition",
        "Responsibilities",
                        "Return",       "Summary",      "Todos",        "Version",
        "Base Classes", "Exceptions",   "Implements",   "Keywords",     "Parameters",
        "See Also",     "Template Parameters",
                                        "",             "Since "
    };

Docu_Display::Docu_Display( OuputPage_Environment & io_rEnv )
    :   HtmlDisplay_Impl(io_rEnv),
        bUseHtmlInDocuTokens(false),
        pCurClassOverwrite(0)
{
}

Docu_Display::~Docu_Display()
{
}

void
Docu_Display::Assign_Out( csi::xml::Element & o_rOut )
{
    Easy().Enter(o_rOut);
}

void
Docu_Display::Unassign_Out()
{
    Easy().Leave();
}

void
Docu_Display::Display_Namespace( const ary::cpp::Namespace & i_rData )
{
    i_rData.Info().StoreAt( *this );
}

void
Docu_Display::Display_Class( const ary::cpp::Class & i_rData )
{
    pCurClassOverwrite = &i_rData;
    i_rData.Info().StoreAt( *this );
    pCurClassOverwrite = 0;
}

void
Docu_Display::Display_Enum( const ary::cpp::Enum & i_rData )
{
    i_rData.Info().StoreAt( *this );
}

void
Docu_Display::Display_Typedef( const ary::cpp::Typedef & i_rData )
{
    i_rData.Info().StoreAt( *this );
}

void
Docu_Display::Display_Function( const ary::cpp::Function & i_rData )
{
    i_rData.Info().StoreAt( *this );
}

void
Docu_Display::Display_Variable( const ary::cpp::Variable & i_rData )
{
    i_rData.Info().StoreAt( *this );
}

// --------------       Interface ary::info::DocuDisplay  ------------------ //

void
Docu_Display::Display_CodeInfo( const CodeInfo & i_rData )
{
    Start_DocuBlock();

    if ( i_rData.IsObsolete() )
    {
        CurOut()
            >> *new html::DefListTerm
                >> *new html::Strong
                    << "D E P R E C A T E D";

    }

    CodeInfo::TagList::const_iterator itEnd = i_rData.Tags().end();
    for ( CodeInfo::TagList::const_iterator it = i_rData.Tags().begin();
          it != itEnd;
          ++it )
    {
         (*it)->StoreAt( *this );
    }

    Finish_DocuBlock();
}

void
Docu_Display::Display_StdTag( const StdTag & i_rData )
{
    csv_assert( int(i_rData.Std_Id()) < int(ary::info::C_eAtTag_NrOfClasses) );

    const ary::info::DocuText::TokenList &
        rText = i_rData.CText().Tokens();
    typedef ary::info::DocuText::TokenList::const_iterator TokenIterator;

    if ( rText.empty() )
        return;
    else if ( rText.size() < 3 )
    {
        bool bIsWhite = true;
        for ( TokenIterator it = rText.begin();
              it != rText.end();
              ++it )
        {
            if (bIsWhite)
                bIsWhite = (*it)->IsWhite();
        }
        if (bIsWhite)
            return;
    }

    Write_TagTitle( C_sTagHeadlines[i_rData.Std_Id()] );
    Write_TagContents( i_rData.CText() );
}

void
Docu_Display::Display_BaseTag( const BaseTag & )
{

}

void
Docu_Display::Display_ExceptionTag( const ExceptionTag & )
{
}

void
Docu_Display::Display_ImplementsTag( const ImplementsTag & )
{
}

void
Docu_Display::Display_KeywordTag( const KeywordTag & )
{
}

void
Docu_Display::Display_ParameterTag( const ParameterTag & i_rData )
{
    Write_TagTitle( "Parameters" );

    adcdisp::ExplanationTable
        aParams( CurOut() >> *new DefListDefinition );

    for ( const ParameterTag * pParam = &i_rData;
          pParam != 0;
          pParam = pParam->GetNext() )   // KORR_FUTURE
    {
        aParams.AddEntry( pParam->ParamName().c_str() );

        Easy().Enter( aParams.Def() );
        Write_Text( pParam->CText() );
        Easy().Leave();
    }   // end for
}

void
Docu_Display::Display_SeeTag( const SeeTag & i_rData )
{
    Write_TagTitle( "See Also" );

    DefListDefinition * dpDef = new DefListDefinition;
    CurOut() << dpDef;
    Easy().Enter(*dpDef);

    for ( std::vector< ary::QualifiedName >::const_iterator
            it = i_rData.References().begin();
          it != i_rData.References().end();
          ++it )
    {
        Write_LinkableText( (*it) );
        CurOut() << new html::LineBreak;
    }

    Easy().Leave();
}

void
Docu_Display::Display_TemplateTag( const TemplateTag & i_rData )
{
    Write_TagTitle( "Template Parameters" );

    adcdisp::ExplanationTable
        aTplParams( CurOut() >> *new DefListDefinition );

    for ( const TemplateTag * pTplParam = &i_rData;
          pTplParam != 0;
          pTplParam = pTplParam->GetNext() )
    {
        aTplParams.AddEntry( pTplParam->TplParamName().c_str() );

        Easy().Enter( aTplParams.Def() );
        Write_Text( pTplParam->CText() );
        Easy().Leave();
    }   // end for
}

void
Docu_Display::Display_LabelTag( const LabelTag & )
{
}

void
Docu_Display::Display_SinceTag( const ary::info::SinceTag & i_rData )
{
    if ( i_rData.Version().empty() )
    {
         return;
    }

    // Transform the value of the @since tag into the text to be displayed.
    String sDisplay;
    if ( autodoc::CommandLine::Get_().DoesTransform_SinceTag() )
    {
        sDisplay = autodoc::CommandLine::Get_()
                        .DisplayOf_SinceTagValue( i_rData.Version() );
    }
    else
    {
        sDisplay = i_rData.Version();
    }

    if (sDisplay.empty())
        return;

    Write_TagTitle( "Since " );

    DefListDefinition * dpDef = new DefListDefinition;
    CurOut() << dpDef;

    Easy().Enter(*dpDef);
    CurOut() << sDisplay;
    Easy().Leave();
}

void
Docu_Display::Display_DT_Text( const DT_Text & i_rData )
{
    Write_TextToken(  i_rData.Text() );
}

void
Docu_Display::Display_DT_MaybeLink( const DT_MaybeLink & i_rData )
{
    // KORR_FUTURE
    Write_TextToken(  i_rData.Text() );
}

void
Docu_Display::Display_DT_Whitespace( const DT_Whitespace & i_rData )
{
    static char sSpace[300] =
        "                                         "
        "                                         "
        "                                         "
        "                                         "
        "                                         "
        "                                        ";
    UINT8 nLength = i_rData.Length();
    sSpace[nLength] = NULCH;
    CurOut() << sSpace;
    sSpace[nLength] = ' ';
}

void
Docu_Display::Display_DT_Eol( const DT_Eol & )
{
    CurOut() << new html::Sbr;
}

void
Docu_Display::Display_DT_Xml( const ary::info::DT_Xml & i_rData )
{
    CurOut() << new xml::XmlCode( i_rData.Text() );
}

void
Docu_Display::Start_DocuBlock()
{
    DYN DefList * dpDefList = new DefList;
    CurOut() << dpDefList;
    Easy().Enter( *dpDefList );
}

void
Docu_Display::Finish_DocuBlock()
{
    Easy().Leave();
}

void
Docu_Display::Write_TagTitle( const char *        i_sText,
                              const char *        )
{
    if ( strcmp(i_sText,"ATTENTION!") == 0 )
    {
        CurOut()
            >> *new html::DefListTerm
                << new html::ClassAttr("attention")
                << i_sText;
    }
    else
    {
        CurOut()
            >> *new html::DefListTerm
                << i_sText;
    }
}

void
Docu_Display::Write_TagContents( const DocuText & i_rDocuText )
{
    DefListDefinition * dpDef = new DefListDefinition;
    CurOut() << dpDef;

    Easy().Enter(*dpDef);
    Write_Text(i_rDocuText);
    Easy().Leave();
}

void
Docu_Display::Write_Text( const ary::info::DocuText & i_rDocuText )
{
    if ( i_rDocuText.IsNoHtml() )
    {
        CurOut()
            << new xml::XmlCode("<pre>");
        bUseHtmlInDocuTokens = false;
    }
    else
    {
         bUseHtmlInDocuTokens = true;
    }
    i_rDocuText.StoreAt( *this );
    if ( i_rDocuText.IsNoHtml() )
    {
        CurOut()
            << new xml::XmlCode("</pre>");
    }
}

void
Docu_Display::Write_TextToken( const udmstri & i_sText )
{
     if ( bUseHtmlInDocuTokens )
        CurOut() << new xml::XmlCode(i_sText);
    else
        CurOut() << i_sText;
}

void
Docu_Display::Write_LinkableText( const ary::QualifiedName & i_sQuName )
{
    const ary::CodeEntity *
        pCe = FindUnambiguousCe( Env(), i_sQuName, pCurClassOverwrite );
    if ( pCe != 0 )
    {
        csi::xml::Element *
            pLink = new csi::html::Link( Link2Ce(Env(), *pCe) );
        CurOut() << pLink;
        Easy().Enter(*pLink);
        Write_QualifiedName(i_sQuName);
        Easy().Leave();
    }
    else
    {
        Write_QualifiedName(i_sQuName);
    }
    CurOut() << " ";
}

void
Docu_Display::Write_QualifiedName( const ary::QualifiedName & i_sQuName )
{
    if ( i_sQuName.IsAbsolute() )
        CurOut() << "::";
    for ( ary::QualifiedName::namespace_iterator it = i_sQuName.first_namespace();
          it != i_sQuName.end_namespace();
          ++it )
    {
        CurOut() <<  (*it) << "::";
    }
    CurOut() << i_sQuName.LocalName();
    if ( i_sQuName.IsFunction() )
        CurOut() << "()";
}

<|endoftext|>