<commit_before>/*
 * This file is part ServerManager of package
 *
 * (c) Ondřej Záruba <zarubaondra@gmail.com>
 *
 * For the full copyright and license information, please view the license.md
 * file that was distributed with this source code.
 */

#include <string>
#include <fstream>
#include <cstdlib>
#include <sstream>
#include "./Manager.h"
#include "./Configuration.h"
#include "./Console.h"
#include "./Files.h"
#include "./Strings.h"

using namespace ServerManager;
using namespace std;

Manager::Manager(){}

void Manager::setConfiguration(Configuration config)
{
	this->config = config;
}

string Manager::search(string hostName)
{
	string cmd = "cat " + this->config.hosts + " | grep " + hostName;
	Console console(cmd);

	return console.exec();
}

string Manager::getList()
{
	ifstream file(this->config.hosts.c_str());
	string line, result;
	if (file.good()) {
		while(getline(file, line)) {
			istringstream line_string(line);
			string key;
			if (line.find(" ") != std::string::npos) {
				if (getline(line_string, key, ' ')) {
					this->appendLine(&result, key, line);
				}
			} else {
				if (getline(line_string, key, '\t')) {
					this->appendLine(&result, key, line);
				}

			}
		}
		file.close();

		return result;
	} else {
		file.close();
		throw "Invalid path to hosts file or you don't run as administrator(sudo)";
	}
}

string Manager::create(string hostName)
{
	string result;
	Console console("nginx -s stop");
	if (console.exec().empty()) {
		result.append("Stoping nginx");
	}
	ofstream hostsFile(this->config.hosts.c_str(), ios_base::app | ios_base::out);
	if (hostsFile.good()) {
		hostsFile << endl << this->getHostConfig(hostName);
		result.append("\nAdded virtual host into hosts file");
		hostsFile.close();
	} else {
		hostsFile.close();
		throw "Invalid path to hosts file or you don't run as administrator(sudo)";
	}
	string path = this->config.nginx + "/" + hostName + ".conf";
	ofstream nginxConfig(path.c_str());
	if (nginxConfig.good()) {
		nginxConfig << this->getServerConfig(hostName);
		if(nginxConfig.good()) {
			result.append("\nAdded virtual host nginx configuration");
		}
		if(!this->config.project.empty()) {
			Console testGitRepository("git ls-remote " + this->config.project + " --exit-code");
			if(testGitRepository.exec().empty()) {
					Console cloneGitRepository("git clone " + this->config.project + " " + this->config.htdocs + "/" + hostName);
					cloneGitRepository.exec();
					result.append("\nCreated project from git repository");
			} else {
				nginxConfig.close();
				throw "Check if repository of project is valid: " + this->config.project;
			}
		} else {
			Console mkdirLog("mkdir -p " + this->config.htdocs + "/" + hostName + "/" + this->config.log);
			Console mkdirRoot("mkdir -p " + this->config.htdocs + "/" + hostName + "/" + this->config.root);
			if (mkdirLog.exec().empty() && mkdirRoot.exec().empty()) {
				result.append("\nCreated base project directories: ");
				result.append("\n\t-" + this->config.htdocs + "/" + hostName + "/" + this->config.log);
				result.append("\n\t-" + this->config.htdocs + "/" + hostName + "/" + this->config.root);
			}
		}
		nginxConfig.close();
	} else {
		nginxConfig.close();
		throw "Invalid path to nginx sites-enabled directory or you don't run as administrator(sudo)";
	}
	Console nginxStart("nginx");
	if (nginxStart.exec().empty()) {
		result.append("\nStarting nginx");
	}
	Console chmodCmd("chmod -R 0777 " + this->config.htdocs + "/" + hostName);
	if (chmodCmd.exec().empty()) {
		result.append("\nSet chmod");
	}

	return result;
}

string Manager::remove(string hostName)
{
	string result;
	Console console("nginx -s stop");
	if (console.exec().empty()) {
		result.append("Stoping nginx");
	}
	Console rmProject("rm -rf " + this->config.htdocs + "/" + hostName);
	Console rmNginxConf("rm -rf " + this->config.nginx + "/" + hostName + ".conf");
	if (rmProject.exec().empty()) {
		result.append("\nProject directory has been removed");
	} else {
		throw "Invalid path to host(project) directory or you don't run as administrator(sudo)";
	}
	if (rmNginxConf.exec().empty()) {
		result.append("\nNginx configuration has been removed");
	} else {
		throw "Invalid path to nginx sites-enabled directory or you don't run as administrator(sudo)";
	}
	ifstream ihostFile(this->config.hosts.c_str());
	if (ihostFile.good()) {
		string line, newContent = "";
		while(getline(ihostFile, line)) {
			if (line.compare(this->getHostConfig(hostName)) != 0 && !line.empty())  {
				newContent.append(line + "\n");
			}
		}
		ofstream ohostFile(this->config.hosts.c_str());
		ohostFile << newContent;
		result.append("\nVirtual host has been removed from hosts file");
		ihostFile.close();
		ohostFile.close();
	} else {
		throw "Invalid path to hosts file or you don't run as administrator(sudo)";
		ihostFile.close();
	}
	Console nginxStart("nginx");
	if (nginxStart.exec().empty()) {
		result.append("\nStarting nginx");
	}

	return result;
}

void Manager::appendLine(string* result,string key, string line)
{
	if (key.compare("127.0.0.1") == 0) {
		(*result).append(line + "\n");
	}
}

string Manager::getServerConfig(string hostName)
{
	Files files;
	Strings strings;
	string content = files.getString(this->config.serverTemplate);
	string config = strings.replace("%hostName%", hostName, content);
	config = strings.replace("%tld%", this->config.tld, config);
	config = strings.replace("%htdocs%", this->config.htdocs, config);
	config = strings.replace("%root%", this->config.root, config);
	config = strings.replace("%log%", this->config.log, config);

	return config;
}

string Manager::getHostConfig(string hostName)
{
	Files files;
	Strings strings;
	string content = files.getString(this->config.systemTemplate);
	string host = strings.replace("%hostName%", hostName, content);
	host = strings.replace("%tld%", this->config.tld, host);

	return host;
}
<commit_msg>Manager create: do not allow duplicates, throw exception<commit_after>/*
 * This file is part ServerManager of package
 *
 * (c) Ondřej Záruba <zarubaondra@gmail.com>
 *
 * For the full copyright and license information, please view the license.md
 * file that was distributed with this source code.
 */

#include <string>
#include <fstream>
#include <cstdlib>
#include <sstream>
#include "./Manager.h"
#include "./Configuration.h"
#include "./Console.h"
#include "./Files.h"
#include "./Strings.h"

using namespace ServerManager;
using namespace std;

Manager::Manager(){}

void Manager::setConfiguration(Configuration config)
{
	this->config = config;
}

string Manager::search(string hostName)
{
	string cmd = "cat " + this->config.hosts + " | grep " + hostName;
	Console console(cmd);

	return console.exec();
}

string Manager::getList()
{
	ifstream file(this->config.hosts.c_str());
	string line, result;
	if (file.good()) {
		while(getline(file, line)) {
			istringstream line_string(line);
			string key;
			if (line.find(" ") != std::string::npos) {
				if (getline(line_string, key, ' ')) {
					this->appendLine(&result, key, line);
				}
			} else {
				if (getline(line_string, key, '\t')) {
					this->appendLine(&result, key, line);
				}

			}
		}
		file.close();

		return result;
	} else {
		file.close();
		throw "Invalid path to hosts file or you don't run as administrator(sudo)";
	}
}

string Manager::create(string hostName)
{
	string result;

	Console console("nginx -s stop");
	if (console.exec().empty()) {
		result.append("Stoping nginx");
	}

	ofstream hostsFile(this->config.hosts.c_str(), ios_base::app | ios_base::out);
	if (!hostsFile.good()) {
		hostsFile.close();
		throw "Invalid path to hosts file or you don't run as administrator(sudo)";
	}

	if (!this->search(hostName).empty()) {
		hostsFile.close();
		throw "Hostname already exists";
	}

	hostsFile << endl << this->getHostConfig(hostName);
	result.append("\nAdded virtual host into hosts file");
	hostsFile.close();

	string path = this->config.nginx + "/" + hostName + ".conf";
	ofstream nginxConfig(path.c_str());
	if (nginxConfig.good()) {
		nginxConfig << this->getServerConfig(hostName);
		if(nginxConfig.good()) {
			result.append("\nAdded virtual host nginx configuration");
		}
		if(!this->config.project.empty()) {
			Console testGitRepository("git ls-remote " + this->config.project + " --exit-code");
			if(testGitRepository.exec().empty()) {
					Console cloneGitRepository("git clone " + this->config.project + " " + this->config.htdocs + "/" + hostName);
					cloneGitRepository.exec();
					result.append("\nCreated project from git repository");
			} else {
				nginxConfig.close();
				throw "Check if repository of project is valid: " + this->config.project;
			}
		} else {
			Console mkdirLog("mkdir -p " + this->config.htdocs + "/" + hostName + "/" + this->config.log);
			Console mkdirRoot("mkdir -p " + this->config.htdocs + "/" + hostName + "/" + this->config.root);
			if (mkdirLog.exec().empty() && mkdirRoot.exec().empty()) {
				result.append("\nCreated base project directories: ");
				result.append("\n\t-" + this->config.htdocs + "/" + hostName + "/" + this->config.log);
				result.append("\n\t-" + this->config.htdocs + "/" + hostName + "/" + this->config.root);
			}
		}
		nginxConfig.close();
	} else {
		nginxConfig.close();
		throw "Invalid path to nginx sites-enabled directory or you don't run as administrator(sudo)";
	}
	Console nginxStart("nginx");
	if (nginxStart.exec().empty()) {
		result.append("\nStarting nginx");
	}
	Console chmodCmd("chmod -R 0777 " + this->config.htdocs + "/" + hostName);
	if (chmodCmd.exec().empty()) {
		result.append("\nSet chmod");
	}

	return result;
}

string Manager::remove(string hostName)
{
	string result;
	Console console("nginx -s stop");
	if (console.exec().empty()) {
		result.append("Stoping nginx");
	}
	Console rmProject("rm -rf " + this->config.htdocs + "/" + hostName);
	Console rmNginxConf("rm -rf " + this->config.nginx + "/" + hostName + ".conf");
	if (rmProject.exec().empty()) {
		result.append("\nProject directory has been removed");
	} else {
		throw "Invalid path to host(project) directory or you don't run as administrator(sudo)";
	}
	if (rmNginxConf.exec().empty()) {
		result.append("\nNginx configuration has been removed");
	} else {
		throw "Invalid path to nginx sites-enabled directory or you don't run as administrator(sudo)";
	}
	ifstream ihostFile(this->config.hosts.c_str());
	if (ihostFile.good()) {
		string line, newContent = "";
		while(getline(ihostFile, line)) {
			if (line.compare(this->getHostConfig(hostName)) != 0 && !line.empty())  {
				newContent.append(line + "\n");
			}
		}
		ofstream ohostFile(this->config.hosts.c_str());
		ohostFile << newContent;
		result.append("\nVirtual host has been removed from hosts file");
		ihostFile.close();
		ohostFile.close();
	} else {
		throw "Invalid path to hosts file or you don't run as administrator(sudo)";
		ihostFile.close();
	}
	Console nginxStart("nginx");
	if (nginxStart.exec().empty()) {
		result.append("\nStarting nginx");
	}

	return result;
}

void Manager::appendLine(string* result,string key, string line)
{
	if (key.compare("127.0.0.1") == 0) {
		(*result).append(line + "\n");
	}
}

string Manager::getServerConfig(string hostName)
{
	Files files;
	Strings strings;
	string content = files.getString(this->config.serverTemplate);
	string config = strings.replace("%hostName%", hostName, content);
	config = strings.replace("%tld%", this->config.tld, config);
	config = strings.replace("%htdocs%", this->config.htdocs, config);
	config = strings.replace("%root%", this->config.root, config);
	config = strings.replace("%log%", this->config.log, config);

	return config;
}

string Manager::getHostConfig(string hostName)
{
	Files files;
	Strings strings;
	string content = files.getString(this->config.systemTemplate);
	string host = strings.replace("%hostName%", hostName, content);
	host = strings.replace("%tld%", this->config.tld, host);

	return host;
}
<|endoftext|>


<commit_before>/************************************************
 * 该例程讲解用C++11来实现一个ScopeGuard类
************************************************/
#include "ScopeGuard.hpp"
#include <iostream>
#include <functional>

int main()
{
    std::function<void()> func = []
    {
        std::cout << "Cleanup from unnormal exit" << std::endl;
    };

    {
        // 正常退出
        auto ret = makeGuard(func);
        ret.dismiss();
    }

    {
        // 非正常退出，调用func函数
        makeGuard(func);
    }

    return 0;
}
<commit_msg>Update scopeguard<commit_after>/************************************************
 * 该例程讲解用C++11来实现一个ScopeGuard类
************************************************/
#include "ScopeGuard.hpp"
#include <iostream>
#include <functional>

int main()
{
    std::function<void()> func = []
    {
        std::cout << "Cleanup from unnormal exit" << std::endl;
    };

    {
        // 正常退出
        auto ret = makeGuard(func);
        ret.dismiss();
    }

    {
        // 非正常退出，调用func函数
        auto ret = makeGuard(func);
    }

    return 0;
}
<|endoftext|>


<commit_before>/** @file main.cc
 *
 *  Driver file for testing LCC
 *
 *  @author Nishant Mehta (niche)
 */
// example for running program via fx-run on no.cc.gatech.edu:
//   fx-run mnist_lcc /scratch/niche/fastlib-stl/build/bin/mnist_lcc --lambda=0.05, --data_dir=/scratch/niche/fastlib-stl/contrib/niche/discriminative_sparse_coding/mnist --digit1=4, --digit2=9, --n_iterations=1, --n_atoms=50,

#include <fastlib/fastlib.h>
#include <armadillo>

#include "lcc.h"

using namespace arma;
using namespace std;

int main(int argc, char* argv[]) {
  fx_module* root = fx_init(argc, argv, NULL);

  double lambda = fx_param_double_req(NULL, "lambda");

  // if using fx-run, one could just leave results_dir blank
  const char* results_dir = fx_param_str(NULL, "results_dir", "");

  const char* data_dir =
    fx_param_str_req(NULL, "data_dir");

  //const char* initial_dictionary_fullpath =
  //  fx_param_str_req(NULL, "initial_dictionary");

  u32 digit_1 = fx_param_int_req(NULL, "digit1");
  u32 digit_2 = fx_param_int_req(NULL, "digit2");

  u32 n_iterations = fx_param_int_req(NULL, "n_iterations");

  u32 n_atoms = fx_param_int_req(NULL, "n_atoms");

  // Load Data
  char* data_filename = (char*) malloc(320 * sizeof(char));
  sprintf(data_filename,
	  "%s/train%d.arm",
	  data_dir,
	  digit_1);
  mat X_neg;
  X_neg.load(data_filename);
  u32 n_neg_points = X_neg.n_cols;

  sprintf(data_filename,
	  "%s/train%d.arm",
	  data_dir,
	  digit_2);
  mat X_pos;
  X_pos.load(data_filename);
  u32 n_pos_points = X_pos.n_cols;
  free(data_filename);

  mat X = join_rows(X_neg, X_pos);
  u32 n_points = X.n_cols;
  // normalize each column of data
  for(u32 i = 0; i < n_points; i++) {
    X.col(i) /= norm(X.col(i), 2);
  }

  // create a labels vector, NOT so that we can use it for LCC, but so we can save the labels for easy discriminative training upon exit of this program
  vec y = vec(n_points);
  y.subvec(0, n_neg_points - 1).fill(-1);
  y.subvec(n_neg_points, n_points - 1).fill(1);

  // run LCC
  LocalCoordinateCoding lcc;

  //mat initial_D;
  //initial_D.load("/home/niche/fastlib-stl/contrib/niche/local_coordinate_coding/D.dat");
  //initial_D.load(initial_dictionary_fullpath);
  //u32 n_atoms = initial_D.n_cols;

  lcc.Init(X, n_atoms, lambda);
  lcc.DataDependentRandomInitDictionary();

  //printf("n_atoms = %d\n", n_atoms);

  wall_clock timer;
  timer.tic();
  lcc.DoLCC(n_iterations);
  double n_secs = timer.toc();
  cout << "took " << n_secs << " seconds" << endl;

  mat learned_D;
  lcc.GetDictionary(learned_D);

  mat learned_V;
  lcc.GetCoding(learned_V);

  if(strlen(results_dir) == 0) {
    learned_D.save("D.dat", raw_ascii);
    learned_V.save("V.dat", raw_ascii);
    y.save("y.dat", raw_ascii);
  }
  else {
    char* data_fullpath = (char*) malloc(320 * sizeof(char));

    sprintf(data_fullpath, "%s/D.dat", results_dir);
    learned_D.save(data_fullpath, raw_ascii);

    sprintf(data_fullpath, "%s/V.dat", results_dir);
    learned_V.save(data_fullpath, raw_ascii);

    sprintf(data_fullpath, "%s/y.dat", results_dir);
    y.save(data_fullpath, raw_ascii);

    free(data_fullpath);
  }

  fx_done(root);
}
<commit_msg>changed mnist_main to allow specification of initial dictionary<commit_after>/** @file main.cc
 *
 *  Driver file for testing LCC
 *
 *  @author Nishant Mehta (niche)
 */
// example for running program via fx-run on no.cc.gatech.edu:
//   fx-run mnist_lcc /scratch/niche/fastlib-stl/build/bin/mnist_lcc --lambda=0.05, --data_dir=/scratch/niche/fastlib-stl/contrib/niche/discriminative_sparse_coding/mnist --digit1=4, --digit2=9, --n_iterations=1, --n_atoms=50,

#include <fastlib/fastlib.h>
#include <armadillo>

#include "lcc.h"

using namespace arma;
using namespace std;

int main(int argc, char* argv[]) {
  fx_module* root = fx_init(argc, argv, NULL);

  double lambda = fx_param_double_req(NULL, "lambda");

  // if using fx-run, one could just leave results_dir blank
  const char* results_dir = fx_param_str(NULL, "results_dir", "");

  const char* data_dir =
    fx_param_str_req(NULL, "data_dir");

  const char* initial_dictionary_fullpath =
    fx_param_str(NULL, "initial_dictionary", "");

  u32 digit_1 = fx_param_int_req(NULL, "digit1");
  u32 digit_2 = fx_param_int_req(NULL, "digit2");

  u32 n_iterations = fx_param_int_req(NULL, "n_iterations");

  u32 n_atoms = fx_param_int_req(NULL, "n_atoms");

  // Load Data
  char* data_filename = (char*) malloc(320 * sizeof(char));
  sprintf(data_filename,
	  "%s/train%d.arm",
	  data_dir,
	  digit_1);
  mat X_neg;
  X_neg.load(data_filename);
  u32 n_neg_points = X_neg.n_cols;

  sprintf(data_filename,
	  "%s/train%d.arm",
	  data_dir,
	  digit_2);
  mat X_pos;
  X_pos.load(data_filename);
  u32 n_pos_points = X_pos.n_cols;
  free(data_filename);

  mat X = join_rows(X_neg, X_pos);
  u32 n_points = X.n_cols;
  // normalize each column of data
  for(u32 i = 0; i < n_points; i++) {
    X.col(i) /= norm(X.col(i), 2);
  }

  // create a labels vector, NOT so that we can use it for LCC, but so we can save the labels for easy discriminative training upon exit of this program
  vec y = vec(n_points);
  y.subvec(0, n_neg_points - 1).fill(-1);
  y.subvec(n_neg_points, n_points - 1).fill(1);

  // run LCC
  LocalCoordinateCoding lcc;

  lcc.Init(X, n_atoms, lambda);
  if(strlen(initial_dictionary_fullpath) == 0) {
    lcc.DataDependentRandomInitDictionary();
  }
  else {
    mat initial_D;
    initial_D.load(initial_dictionary_fullpath);
    if(initial_D.n_cols != n_atoms) {
      fprintf(stderr, "Error: The specified initial dictionary to load has %d atoms, but the learned dictionary was specified to have %d atoms! Exiting..\n",
	      initial_D.n_cols,
	      n_atoms);
      return EXIT_FAILURE;
    }
    if(initial_D.n_rows != X.n_rows) {
      fprintf(stderr, "Error: The specified initial dictionary to load has %d dimensions, but the specified data has %d dimensions! Exiting..\n",
	      initial_D.n_rows,
	      X.n_rows);
      return EXIT_FAILURE;
    }
    lcc.SetDictionary(initial_D);
  }

  wall_clock timer;
  timer.tic();
  lcc.DoLCC(n_iterations);
  double n_secs = timer.toc();
  cout << "took " << n_secs << " seconds" << endl;

  mat learned_D;
  lcc.GetDictionary(learned_D);

  mat learned_V;
  lcc.GetCoding(learned_V);

  if(strlen(results_dir) == 0) {
    learned_D.save("D.dat", raw_ascii);
    learned_V.save("V.dat", raw_ascii);
    y.save("y.dat", raw_ascii);
  }
  else {
    char* data_fullpath = (char*) malloc(320 * sizeof(char));

    sprintf(data_fullpath, "%s/D.dat", results_dir);
    learned_D.save(data_fullpath, raw_ascii);

    sprintf(data_fullpath, "%s/V.dat", results_dir);
    learned_V.save(data_fullpath, raw_ascii);

    sprintf(data_fullpath, "%s/y.dat", results_dir);
    y.save(data_fullpath, raw_ascii);

    free(data_fullpath);
  }

  fx_done(root);
}
<|endoftext|>


<commit_before>#include "Buffer.h"
#include "System/Common.h"
#include <stdarg.h>
#include <stdlib.h>

Buffer::Buffer()
{
    Init();
}

Buffer::~Buffer()
{
    if (buffer != array && !preallocated)
        free(buffer);
}

void Buffer::SetPreallocated(char* buffer_, unsigned size_)
{
    preallocated = true;
    buffer = buffer_;
    size = size_;
}

int Buffer::Cmp(const Buffer& a, const Buffer& b)
{
    int ret;
    unsigned alen, blen;

    alen = a.length;
    blen = b.length;
    ret = memcmp(a.buffer, b.buffer, MIN(alen, blen));

    if (ret != 0)
        return ret;

    if (alen < blen)
        return -1;
    else if (blen < alen)
        return 1;
    else
        return 0;
}

int Buffer::Cmp(const char* buffer_, unsigned length_)
{
    int ret;
    unsigned alen, blen;

    alen = length;
    blen = length_;
    ret = memcmp(buffer, buffer_, MIN(alen, blen));

    if (ret != 0)
        return ret;

    if (alen < blen)
        return -1;
    else if (blen < alen)
        return 1;
    else
        return 0;
}

int Buffer::Cmp(const char* str)
{
    int ret;
    unsigned alen, blen;

    alen = length;
    blen = strlen(str);
    ret = memcmp(buffer, str, MIN(alen, blen));

    if (ret != 0)
        return ret;

    if (alen < blen)
        return -1;
    else if (blen < alen)
        return 1;
    else
        return 0;
}

void Buffer::Lengthen(unsigned k)
{
    length += k;
}

void Buffer::Shorten(unsigned k)
{
    length -= k;
}

void Buffer::Allocate(unsigned size_, bool keepold)
{
    char*       newbuffer;

    if (size_ <= size)
        return;

    size_ = NextPowerOfTwo(size_);

    if (buffer == array || preallocated)
        newbuffer = (char*) malloc(size_);
    else
        newbuffer = (char*) realloc(buffer, size_);

    ASSERT(newbuffer != NULL);

    if (keepold && length > 0)
    {
        if (buffer == array)
            memcpy(newbuffer, buffer, length);
    }

    buffer = newbuffer;
    size = size_;
    preallocated = false;
}

int Buffer::Readf(const char* format, ...) const
{
    int         read;
    va_list     ap;

    va_start(ap, format);
    read = VReadf(buffer, length, format, ap);
    va_end(ap);

    return read;
}

unsigned Buffer::Writef(const char* fmt, ...)
{
    unsigned required;
    va_list ap;

    while (true)
    {
        va_start(ap, fmt);
        required = VWritef(buffer, size, fmt, ap);
        va_end(ap);

        if (required <= size)
        {
            length = required;
            break;
        }

        Allocate(required, false);
    }

    return length;
}

unsigned Buffer::Appendf(const char* fmt, ...)
{
    unsigned required;
    va_list ap;

    while (true)
    {
        va_start(ap, fmt);
        required = VWritef(GetPosition(), GetRemaining(), fmt, ap);
        va_end(ap);

        // snwritef returns number of bytes required
        if (required <= GetRemaining())
            break;

        Allocate(length + required, true);
    }

    length += required;
    return required;
}

void Buffer::Write(const char* buffer_, unsigned length_)
{
    if (length_ > size)
        Allocate(length_);
    memmove(buffer, buffer_, length_);
    length = length_;
}

void Buffer::Write(const char* str)
{
    Write(str, strlen(str));
}

void Buffer::Write(Buffer& other)
{
    Write(other.GetBuffer(), other.GetLength());
}

void Buffer::Write(ReadBuffer other)
{
    Write(other.GetBuffer(), other.GetLength());
}

void Buffer::Append(char c)
{
    Append(&c, 1);
}

void Buffer::Append(const char* buffer_, unsigned length_)
{
    if (length_ > GetRemaining())
        Allocate(length + length_);
    memcpy(GetPosition(), buffer_, length_);
    Lengthen(length_);
}

void Buffer::Append(const char* str)
{
    Append(str, strlen(str));
}

void Buffer::Append(Buffer& other)
{
    Append(other.GetBuffer(), other.GetLength());
}

void Buffer::Append(ReadBuffer other)
{
    Append(other.GetBuffer(), other.GetLength());
}

void Buffer::AppendLittle16(uint16_t x)
{
    x = ToLittle16(x);
    Append((const char*) &x, sizeof(uint16_t));
}

void Buffer::AppendLittle32(uint32_t x)
{
    x = ToLittle32(x);
    Append((const char*) &x, sizeof(uint32_t));
}

void Buffer::AppendLittle64(uint64_t x)
{
    x = ToLittle64(x);
    Append((const char*) &x, sizeof(uint64_t));
}

char Buffer::GetCharAt(unsigned i)
{
    if (i > length - 1)
        ASSERT_FAIL();

    return *(buffer + i);
}

void Buffer::SetCharAt(unsigned i, char c)
{
    buffer[i] = c;
}

bool Buffer::IsAsciiPrintable()
{
    unsigned    i;

    for (i = 0; i < length; i++)
    {
        if ((unsigned char)buffer[i] < 32 || (unsigned char)buffer[i] > 127)
            return false;
    }

    return true;
}

void Buffer::ToHexadecimal()
{
    unsigned    i;
    unsigned    x;
    Buffer      printable;

    printable.Allocate(length * 3);
    for (i = 0; i < length; i++)
    {
        x = (unsigned char) buffer[i];
        printable.Appendf("%x ", x);
    }

    Write(printable);
}

void Buffer::NullTerminate()
{
    Append("", 1);
}

void Buffer::Zero()
{
    memset(buffer, 0, size);
}

void Buffer::ZeroRest()
{
    memset(buffer + length, 0, size - length);
}

void Buffer::SetLength(unsigned length_)
{
    length = length_;
    if (length > size)
        ASSERT_FAIL();
}

void Buffer::Init()
{
    buffer = array;
    size = SIZE(array);
    length = 0;
    preallocated = false;
    prev = next = this;
}

unsigned Buffer::GetSize()
{
    return size;
}

char* Buffer::GetBuffer()
{
    return buffer;
}

unsigned Buffer::GetLength()
{
    return length;
}

unsigned Buffer::GetRemaining()
{
    return size - length;
}

char* Buffer::GetPosition()
{
    return buffer + length;
}

uint32_t Buffer::GetChecksum()
{
    return ChecksumBuffer(buffer, length);
}

void Buffer::Clear()
{
    length = 0;
}

void Buffer::Reset()
{
    if (buffer != array && !preallocated)
        free(buffer);

    Init();
}

Buffer::Buffer(const Buffer& other)
{
//    ASSERT_FAIL();
    Init();
    *this = other;  // call operator=()
}

Buffer& Buffer::operator=(const Buffer& other)
{
//    ASSERT_FAIL();
    if (other.size != size)
      Allocate(other.size, false);

    memcpy(buffer, other.buffer, other.size);
    length = other.length;
    prev = next = this;

    return *this;
}
<commit_msg>Fixed hex conversion in buffer.<commit_after>#include "Buffer.h"
#include "System/Common.h"
#include <stdarg.h>
#include <stdlib.h>

Buffer::Buffer()
{
    Init();
}

Buffer::~Buffer()
{
    if (buffer != array && !preallocated)
        free(buffer);
}

void Buffer::SetPreallocated(char* buffer_, unsigned size_)
{
    preallocated = true;
    buffer = buffer_;
    size = size_;
}

int Buffer::Cmp(const Buffer& a, const Buffer& b)
{
    int ret;
    unsigned alen, blen;

    alen = a.length;
    blen = b.length;
    ret = memcmp(a.buffer, b.buffer, MIN(alen, blen));

    if (ret != 0)
        return ret;

    if (alen < blen)
        return -1;
    else if (blen < alen)
        return 1;
    else
        return 0;
}

int Buffer::Cmp(const char* buffer_, unsigned length_)
{
    int ret;
    unsigned alen, blen;

    alen = length;
    blen = length_;
    ret = memcmp(buffer, buffer_, MIN(alen, blen));

    if (ret != 0)
        return ret;

    if (alen < blen)
        return -1;
    else if (blen < alen)
        return 1;
    else
        return 0;
}

int Buffer::Cmp(const char* str)
{
    int ret;
    unsigned alen, blen;

    alen = length;
    blen = strlen(str);
    ret = memcmp(buffer, str, MIN(alen, blen));

    if (ret != 0)
        return ret;

    if (alen < blen)
        return -1;
    else if (blen < alen)
        return 1;
    else
        return 0;
}

void Buffer::Lengthen(unsigned k)
{
    length += k;
}

void Buffer::Shorten(unsigned k)
{
    length -= k;
}

void Buffer::Allocate(unsigned size_, bool keepold)
{
    char*       newbuffer;

    if (size_ <= size)
        return;

    size_ = NextPowerOfTwo(size_);

    if (buffer == array || preallocated)
        newbuffer = (char*) malloc(size_);
    else
        newbuffer = (char*) realloc(buffer, size_);

    ASSERT(newbuffer != NULL);

    if (keepold && length > 0)
    {
        if (buffer == array)
            memcpy(newbuffer, buffer, length);
    }

    buffer = newbuffer;
    size = size_;
    preallocated = false;
}

int Buffer::Readf(const char* format, ...) const
{
    int         read;
    va_list     ap;

    va_start(ap, format);
    read = VReadf(buffer, length, format, ap);
    va_end(ap);

    return read;
}

unsigned Buffer::Writef(const char* fmt, ...)
{
    unsigned required;
    va_list ap;

    while (true)
    {
        va_start(ap, fmt);
        required = VWritef(buffer, size, fmt, ap);
        va_end(ap);

        if (required <= size)
        {
            length = required;
            break;
        }

        Allocate(required, false);
    }

    return length;
}

unsigned Buffer::Appendf(const char* fmt, ...)
{
    unsigned required;
    va_list ap;

    while (true)
    {
        va_start(ap, fmt);
        required = VWritef(GetPosition(), GetRemaining(), fmt, ap);
        va_end(ap);

        // snwritef returns number of bytes required
        if (required <= GetRemaining())
            break;

        Allocate(length + required, true);
    }

    length += required;
    return required;
}

void Buffer::Write(const char* buffer_, unsigned length_)
{
    if (length_ > size)
        Allocate(length_);
    memmove(buffer, buffer_, length_);
    length = length_;
}

void Buffer::Write(const char* str)
{
    Write(str, strlen(str));
}

void Buffer::Write(Buffer& other)
{
    Write(other.GetBuffer(), other.GetLength());
}

void Buffer::Write(ReadBuffer other)
{
    Write(other.GetBuffer(), other.GetLength());
}

void Buffer::Append(char c)
{
    Append(&c, 1);
}

void Buffer::Append(const char* buffer_, unsigned length_)
{
    if (length_ > GetRemaining())
        Allocate(length + length_);
    memcpy(GetPosition(), buffer_, length_);
    Lengthen(length_);
}

void Buffer::Append(const char* str)
{
    Append(str, strlen(str));
}

void Buffer::Append(Buffer& other)
{
    Append(other.GetBuffer(), other.GetLength());
}

void Buffer::Append(ReadBuffer other)
{
    Append(other.GetBuffer(), other.GetLength());
}

void Buffer::AppendLittle16(uint16_t x)
{
    x = ToLittle16(x);
    Append((const char*) &x, sizeof(uint16_t));
}

void Buffer::AppendLittle32(uint32_t x)
{
    x = ToLittle32(x);
    Append((const char*) &x, sizeof(uint32_t));
}

void Buffer::AppendLittle64(uint64_t x)
{
    x = ToLittle64(x);
    Append((const char*) &x, sizeof(uint64_t));
}

char Buffer::GetCharAt(unsigned i)
{
    if (i > length - 1)
        ASSERT_FAIL();

    return *(buffer + i);
}

void Buffer::SetCharAt(unsigned i, char c)
{
    buffer[i] = c;
}

bool Buffer::IsAsciiPrintable()
{
    unsigned    i;

    for (i = 0; i < length; i++)
    {
        if ((unsigned char)buffer[i] < 32 || (unsigned char)buffer[i] > 127)
            return false;
    }

    return true;
}

void Buffer::ToHexadecimal()
{
    unsigned        i;
    unsigned char   x;
    Buffer          printable;
    const char      digits[] = "0123456789ABCDEF";

    printable.Allocate(length * 3);
    for (i = 0; i < length; i++)
    {
        x = (unsigned char) buffer[i];
        printable.Append(digits[x / 16]);
        printable.Append(digits[x % 16]);
        if (i != length - 1)
            printable.Append(' ');
    }

    Write(printable);
}

void Buffer::NullTerminate()
{
    Append("", 1);
}

void Buffer::Zero()
{
    memset(buffer, 0, size);
}

void Buffer::ZeroRest()
{
    memset(buffer + length, 0, size - length);
}

void Buffer::SetLength(unsigned length_)
{
    length = length_;
    if (length > size)
        ASSERT_FAIL();
}

void Buffer::Init()
{
    buffer = array;
    size = SIZE(array);
    length = 0;
    preallocated = false;
    prev = next = this;
}

unsigned Buffer::GetSize()
{
    return size;
}

char* Buffer::GetBuffer()
{
    return buffer;
}

unsigned Buffer::GetLength()
{
    return length;
}

unsigned Buffer::GetRemaining()
{
    return size - length;
}

char* Buffer::GetPosition()
{
    return buffer + length;
}

uint32_t Buffer::GetChecksum()
{
    return ChecksumBuffer(buffer, length);
}

void Buffer::Clear()
{
    length = 0;
}

void Buffer::Reset()
{
    if (buffer != array && !preallocated)
        free(buffer);

    Init();
}

Buffer::Buffer(const Buffer& other)
{
//    ASSERT_FAIL();
    Init();
    *this = other;  // call operator=()
}

Buffer& Buffer::operator=(const Buffer& other)
{
//    ASSERT_FAIL();
    if (other.size != size)
      Allocate(other.size, false);

    memcpy(buffer, other.buffer, other.size);
    length = other.length;
    prev = next = this;

    return *this;
}
<|endoftext|>


<commit_before>/* bzflag
 * Copyright (c) 1993 - 2009 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

#include "MacDisplay.h"
#include "BzfEvent.h"

#include <CoreFoundation/CoreFoundation.h>
#include <ApplicationServices/ApplicationServices.h>

bool     MacDisplay::pending;
CGrafPtr    MacDisplay::window;
CGLContextObj  MacDisplay::context;

MacDisplay::MacDisplay() {
  pending = true;

  setPassthroughSize(CGDisplayPixelsWide(kCGDirectMainDisplay),
		     CGDisplayPixelsHigh(kCGDirectMainDisplay));
}

MacDisplay::MacDisplay(const char *, const char *) {
#pragma unused (name, videoFormat)
  is_valid      = true;
  pending       = false;

  cursor_region = CGPathCreateMutable();
  ResInfo** resInfo = NULL;
  resInfo = new ResInfo*[1];
  resInfo[0] = new ResInfo("default",
			   CGDisplayPixelsWide(kCGDirectMainDisplay),
			   CGDisplayPixelsHigh(kCGDirectMainDisplay), 0);
  //numModes = 1;
  //currentMode = 0;

  // register modes
  initResolutions(resInfo, 1, 0);
}

bool MacDisplay::isEventPending() const
{
  ::OSStatus	status		= ::noErr;
  ::EventRef	eventRef	= 0;

  status = ::ReceiveNextEvent(0, NULL, 0, false, &eventRef);
  return (status == ::noErr) ? true : false;
}

bool MacDisplay::peekEvent (BzfEvent &) const
{
  return false;
}

bool MacDisplay::getEvent (BzfEvent &bzf_event) const {
  ::EventRef		eventRef	= 0;
  ::OSStatus		status		= ::noErr;
  ::UInt32		eventClass	= 0;
  ::UInt32		eventKind	= 0;
  ::EventTime		eventTime	= 0;
  ::HIPoint		eventLocation	= {0, 0};
  ::HIPoint		eventDelta	= {0, 0};
  ::UInt32		eventModifiers	= 0;
  ::EventMouseButton	eventButtons	= 0;
  char			eventChar	= 0;
  ::UInt32		eventKeyCode	= 0;
  ::WindowRef		eventWindow	= NULL;
  const ::Boolean	removeEventFromQueue = true;

  /* initialize the event for safety */
  bzf_event.keyDown.chr = 0;

  bzf_event.type = (BzfEvent::Type)-1;

  status = ::ReceiveNextEvent(0, NULL, 0, removeEventFromQueue, &eventRef);
  if(status != ::noErr) {
    return false;
  }

  eventTime = ::GetEventTime(eventRef);
  eventClass = ::GetEventClass(eventRef);
  eventKind = ::GetEventKind(eventRef);

  // make note of any modifiers being pressed
  bzf_event.keyDown.shift = 0;
  status = GetEventParameter(eventRef,
			     ::kEventParamKeyModifiers,
			     ::typeUInt32,
			     NULL,
			     sizeof(::UInt32),
			     NULL,
			     &eventModifiers);
  if (eventModifiers & cmdKey) {
    // command and option both serve as bzflag alt even
    bzf_event.keyDown.shift = BzfKeyEvent::AltKey;
  }
  if (eventModifiers & shiftKey) bzf_event.keyDown.shift = BzfKeyEvent::ShiftKey;
  if (eventModifiers & optionKey) bzf_event.keyDown.shift = BzfKeyEvent::AltKey;
  if (eventModifiers & controlKey) bzf_event.keyDown.shift = BzfKeyEvent::ControlKey;

  switch(eventClass) {
  case ::kEventClassMouse:
    status = GetEventParameter(eventRef,
			       ::kEventParamWindowMouseLocation,
			       ::typeHIPoint,
			       NULL,
			       sizeof(::HIPoint),
			       NULL,
			       &eventLocation);

    status = GetEventParameter(eventRef,
			       ::kEventParamMouseButton,
			       ::typeMouseButton,
			       NULL,
			       sizeof(::EventMouseButton),
			       NULL,
			       &eventButtons);

    status = GetEventParameter(eventRef,
			       ::kEventParamMouseDelta,
			       ::typeHIPoint,
			       NULL,
			       sizeof(::HIPoint),
			       NULL,
			       &eventDelta);

    // handle the main event type
    switch(eventKind) {
    case ::kEventMouseDown:
    case ::kEventMouseUp:
      if(eventKind == ::kEventMouseDown) {
	bzf_event.type = BzfEvent::KeyDown;
      } else {
	bzf_event.type = BzfEvent::KeyUp;
      }
      if(eventButtons > 9) {
	// bzflag only handles 9 buttons for now
	eventButtons = 9;
      }

      switch(eventButtons) {
      case ::kEventMouseButtonSecondary:
	bzf_event.keyDown.button = BzfKeyEvent::RightMouse;
	break;
      case ::kEventMouseButtonTertiary:
	bzf_event.keyDown.button = BzfKeyEvent::MiddleMouse;
	break;
      default:
	/* consistent wth the rest of the mac experience, a command click is
	 * the same as a right click.
	 */
	if (bzf_event.keyDown.shift == BzfKeyEvent::AltKey) {
	  bzf_event.keyDown.shift = 0;
	  bzf_event.keyDown.button = BzfKeyEvent::RightMouse;
	} else {
	  bzf_event.keyDown.button = BzfKeyEvent::LeftMouse + eventButtons - 1;
	}
	break;
      }
      break;

    case ::kEventMouseMoved:
      bzf_event.type = BzfEvent::MouseMove;
      bzf_event.mouseMove.x = static_cast<int>(eventDelta.x);
      bzf_event.mouseMove.y = static_cast<int>(eventDelta.y);
      break;

    case ::kEventMouseWheelMoved:
      break;
    }
    break;

  case ::kEventClassKeyboard:
    status = GetEventParameter(eventRef,
			       ::kEventParamKeyMacCharCodes,
			       ::typeChar,
			       NULL,
			       sizeof(char),
			       NULL,
			       &eventChar);
    status = GetEventParameter(eventRef,
			       ::kEventParamKeyCode,
			       ::typeUInt32,
			       NULL,
			       sizeof(eventKeyCode),
			       NULL,
			       &eventKeyCode);
    switch(eventKind) {
    case ::kEventRawKeyDown:
    case ::kEventRawKeyRepeat:
      bzf_event.type = BzfEvent::KeyDown;
      getKey(bzf_event.keyDown, eventChar, eventKeyCode);
      break;

    case ::kEventRawKeyUp:
      bzf_event.type = BzfEvent::KeyUp;
      getKey(bzf_event.keyUp, eventChar, eventKeyCode);
      break;
    }
    break;

  case ::kEventClassApplication:
    switch(eventKind) {
    case ::kEventAppQuit:
      bzf_event.type = BzfEvent::Quit;
      break;
    }
    break;

  case ::kEventClassWindow:
    status = GetEventParameter(eventRef,
			       ::kEventParamDirectObject,
			       ::typeWindowRef,
			       NULL,
			       sizeof(::WindowRef),
			       NULL,
			       &eventWindow);
    switch(eventKind) {
    case ::kEventWindowUpdate:
    case ::kEventWindowDrawContent:
      bzf_event.type = BzfEvent::Redraw;
      BeginUpdate(eventWindow);
      EndUpdate(eventWindow);
      break;
    }
    break;

  case ::kEventClassCommand:
    switch(eventKind) {
    }
    break;
  }
  ReleaseEvent(eventRef);
  return true;
}

void MacDisplay::getKey (BzfKeyEvent &bzf_key, char char_code, ::UInt32 keycode) const {
  enum {
    kF1KeyCode	 = 0x7A,	// Undo
    kF2KeyCode	 = 0x78,	// Cut
    kF3KeyCode	 = 0x63,	// Copy
    kF4KeyCode	 = 0x76,	// Paste
    kF5KeyCode	 = 0x60,
    kF6KeyCode	 = 0x61,
    kF7KeyCode	 = 0x62,
    kF8KeyCode	 = 0x64,
    kF9KeyCode	 = 0x65,
    kF10KeyCode	 = 0x6D,
    kF11KeyCode	 = 0x67,
    kF12KeyCode	 = 0x6F,
    kF13KeyCode	 = 0x69,	// Print Screen
    kF14KeyCode	 = 0x6B,	// Scroll Lock
    kF15KeyCode	 = 0x71	// Pause
  };
  bzf_key.chr = 0;
  bzf_key.button = BzfKeyEvent::NoButton;
  switch (char_code) {
  case kUpArrowCharCode   : bzf_key.button = BzfKeyEvent::Up;       break;
  case kDownArrowCharCode : bzf_key.button = BzfKeyEvent::Down;     break;
  case kLeftArrowCharCode : bzf_key.button = BzfKeyEvent::Left;     break;
  case kRightArrowCharCode: bzf_key.button = BzfKeyEvent::Right;    break;
  case kHomeCharCode      : bzf_key.button = BzfKeyEvent::Home;     break;
  case kEndCharCode       : bzf_key.button = BzfKeyEvent::End;      break;
  case kPageUpCharCode    : bzf_key.button = BzfKeyEvent::PageUp;   break;
  case kPageDownCharCode  : bzf_key.button = BzfKeyEvent::PageDown; break;
  case kHelpCharCode      : bzf_key.button = BzfKeyEvent::Insert;   break;
  case kDeleteCharCode    : bzf_key.button = BzfKeyEvent::Delete;   break;
  case kFunctionKeyCharCode:
    switch(keycode) {
      // These are the f-key codes on my apple extended keyboard
    case kF15KeyCode:	bzf_key.button = BzfKeyEvent::Pause; break;
    case kF12KeyCode:	bzf_key.button = BzfKeyEvent::F12;	break;
    case kF11KeyCode:	bzf_key.button = BzfKeyEvent::F11;	break;
    case kF10KeyCode:	bzf_key.button = BzfKeyEvent::F10;	break;
    case kF9KeyCode:	bzf_key.button = BzfKeyEvent::F9;	break;
    case kF8KeyCode:	bzf_key.button = BzfKeyEvent::F8;	break;
    case kF7KeyCode:	bzf_key.button = BzfKeyEvent::F7;	break;
    case kF6KeyCode:	bzf_key.button = BzfKeyEvent::F6;	break;
    case kF5KeyCode:	bzf_key.button = BzfKeyEvent::F5;	break;
    case kF4KeyCode:	bzf_key.button = BzfKeyEvent::F4;	break;
    case kF3KeyCode:	bzf_key.button = BzfKeyEvent::F3;	break;
    case kF2KeyCode:	bzf_key.button = BzfKeyEvent::F2;	break;
    case kF1KeyCode:	bzf_key.button = BzfKeyEvent::F1;	break;
    default:	fprintf(stderr, "Uknown function key code: 0x%lX\n", (long unsigned int) keycode);	break;
    }
    break;
    // standard key; a-z, 0-9 etc
  default:	bzf_key.chr  = char_code;		break;
  }
}

// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>spelling<commit_after>/* bzflag
 * Copyright (c) 1993 - 2009 Tim Riker
 *
 * This package is free software;  you can redistribute it and/or
 * modify it under the terms of the license found in the file
 * named COPYING that should have accompanied this file.
 *
 * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

#include "MacDisplay.h"
#include "BzfEvent.h"

#include <CoreFoundation/CoreFoundation.h>
#include <ApplicationServices/ApplicationServices.h>

bool     MacDisplay::pending;
CGrafPtr    MacDisplay::window;
CGLContextObj  MacDisplay::context;

MacDisplay::MacDisplay() {
  pending = true;

  setPassthroughSize(CGDisplayPixelsWide(kCGDirectMainDisplay),
		     CGDisplayPixelsHigh(kCGDirectMainDisplay));
}

MacDisplay::MacDisplay(const char *, const char *) {
#pragma unused (name, videoFormat)
  is_valid      = true;
  pending       = false;

  cursor_region = CGPathCreateMutable();
  ResInfo** resInfo = NULL;
  resInfo = new ResInfo*[1];
  resInfo[0] = new ResInfo("default",
			   CGDisplayPixelsWide(kCGDirectMainDisplay),
			   CGDisplayPixelsHigh(kCGDirectMainDisplay), 0);
  //numModes = 1;
  //currentMode = 0;

  // register modes
  initResolutions(resInfo, 1, 0);
}

bool MacDisplay::isEventPending() const
{
  ::OSStatus	status		= ::noErr;
  ::EventRef	eventRef	= 0;

  status = ::ReceiveNextEvent(0, NULL, 0, false, &eventRef);
  return (status == ::noErr) ? true : false;
}

bool MacDisplay::peekEvent (BzfEvent &) const
{
  return false;
}

bool MacDisplay::getEvent (BzfEvent &bzf_event) const {
  ::EventRef		eventRef	= 0;
  ::OSStatus		status		= ::noErr;
  ::UInt32		eventClass	= 0;
  ::UInt32		eventKind	= 0;
  ::EventTime		eventTime	= 0;
  ::HIPoint		eventLocation	= {0, 0};
  ::HIPoint		eventDelta	= {0, 0};
  ::UInt32		eventModifiers	= 0;
  ::EventMouseButton	eventButtons	= 0;
  char			eventChar	= 0;
  ::UInt32		eventKeyCode	= 0;
  ::WindowRef		eventWindow	= NULL;
  const ::Boolean	removeEventFromQueue = true;

  /* initialize the event for safety */
  bzf_event.keyDown.chr = 0;

  bzf_event.type = (BzfEvent::Type)-1;

  status = ::ReceiveNextEvent(0, NULL, 0, removeEventFromQueue, &eventRef);
  if(status != ::noErr) {
    return false;
  }

  eventTime = ::GetEventTime(eventRef);
  eventClass = ::GetEventClass(eventRef);
  eventKind = ::GetEventKind(eventRef);

  // make note of any modifiers being pressed
  bzf_event.keyDown.shift = 0;
  status = GetEventParameter(eventRef,
			     ::kEventParamKeyModifiers,
			     ::typeUInt32,
			     NULL,
			     sizeof(::UInt32),
			     NULL,
			     &eventModifiers);
  if (eventModifiers & cmdKey) {
    // command and option both serve as bzflag alt even
    bzf_event.keyDown.shift = BzfKeyEvent::AltKey;
  }
  if (eventModifiers & shiftKey) bzf_event.keyDown.shift = BzfKeyEvent::ShiftKey;
  if (eventModifiers & optionKey) bzf_event.keyDown.shift = BzfKeyEvent::AltKey;
  if (eventModifiers & controlKey) bzf_event.keyDown.shift = BzfKeyEvent::ControlKey;

  switch(eventClass) {
  case ::kEventClassMouse:
    status = GetEventParameter(eventRef,
			       ::kEventParamWindowMouseLocation,
			       ::typeHIPoint,
			       NULL,
			       sizeof(::HIPoint),
			       NULL,
			       &eventLocation);

    status = GetEventParameter(eventRef,
			       ::kEventParamMouseButton,
			       ::typeMouseButton,
			       NULL,
			       sizeof(::EventMouseButton),
			       NULL,
			       &eventButtons);

    status = GetEventParameter(eventRef,
			       ::kEventParamMouseDelta,
			       ::typeHIPoint,
			       NULL,
			       sizeof(::HIPoint),
			       NULL,
			       &eventDelta);

    // handle the main event type
    switch(eventKind) {
    case ::kEventMouseDown:
    case ::kEventMouseUp:
      if(eventKind == ::kEventMouseDown) {
	bzf_event.type = BzfEvent::KeyDown;
      } else {
	bzf_event.type = BzfEvent::KeyUp;
      }
      if(eventButtons > 9) {
	// bzflag only handles 9 buttons for now
	eventButtons = 9;
      }

      switch(eventButtons) {
      case ::kEventMouseButtonSecondary:
	bzf_event.keyDown.button = BzfKeyEvent::RightMouse;
	break;
      case ::kEventMouseButtonTertiary:
	bzf_event.keyDown.button = BzfKeyEvent::MiddleMouse;
	break;
      default:
	/* consistent wth the rest of the mac experience, a command click is
	 * the same as a right click.
	 */
	if (bzf_event.keyDown.shift == BzfKeyEvent::AltKey) {
	  bzf_event.keyDown.shift = 0;
	  bzf_event.keyDown.button = BzfKeyEvent::RightMouse;
	} else {
	  bzf_event.keyDown.button = BzfKeyEvent::LeftMouse + eventButtons - 1;
	}
	break;
      }
      break;

    case ::kEventMouseMoved:
      bzf_event.type = BzfEvent::MouseMove;
      bzf_event.mouseMove.x = static_cast<int>(eventDelta.x);
      bzf_event.mouseMove.y = static_cast<int>(eventDelta.y);
      break;

    case ::kEventMouseWheelMoved:
      break;
    }
    break;

  case ::kEventClassKeyboard:
    status = GetEventParameter(eventRef,
			       ::kEventParamKeyMacCharCodes,
			       ::typeChar,
			       NULL,
			       sizeof(char),
			       NULL,
			       &eventChar);
    status = GetEventParameter(eventRef,
			       ::kEventParamKeyCode,
			       ::typeUInt32,
			       NULL,
			       sizeof(eventKeyCode),
			       NULL,
			       &eventKeyCode);
    switch(eventKind) {
    case ::kEventRawKeyDown:
    case ::kEventRawKeyRepeat:
      bzf_event.type = BzfEvent::KeyDown;
      getKey(bzf_event.keyDown, eventChar, eventKeyCode);
      break;

    case ::kEventRawKeyUp:
      bzf_event.type = BzfEvent::KeyUp;
      getKey(bzf_event.keyUp, eventChar, eventKeyCode);
      break;
    }
    break;

  case ::kEventClassApplication:
    switch(eventKind) {
    case ::kEventAppQuit:
      bzf_event.type = BzfEvent::Quit;
      break;
    }
    break;

  case ::kEventClassWindow:
    status = GetEventParameter(eventRef,
			       ::kEventParamDirectObject,
			       ::typeWindowRef,
			       NULL,
			       sizeof(::WindowRef),
			       NULL,
			       &eventWindow);
    switch(eventKind) {
    case ::kEventWindowUpdate:
    case ::kEventWindowDrawContent:
      bzf_event.type = BzfEvent::Redraw;
      BeginUpdate(eventWindow);
      EndUpdate(eventWindow);
      break;
    }
    break;

  case ::kEventClassCommand:
    switch(eventKind) {
    }
    break;
  }
  ReleaseEvent(eventRef);
  return true;
}

void MacDisplay::getKey (BzfKeyEvent &bzf_key, char char_code, ::UInt32 keycode) const {
  enum {
    kF1KeyCode	 = 0x7A,	// Undo
    kF2KeyCode	 = 0x78,	// Cut
    kF3KeyCode	 = 0x63,	// Copy
    kF4KeyCode	 = 0x76,	// Paste
    kF5KeyCode	 = 0x60,
    kF6KeyCode	 = 0x61,
    kF7KeyCode	 = 0x62,
    kF8KeyCode	 = 0x64,
    kF9KeyCode	 = 0x65,
    kF10KeyCode	 = 0x6D,
    kF11KeyCode	 = 0x67,
    kF12KeyCode	 = 0x6F,
    kF13KeyCode	 = 0x69,	// Print Screen
    kF14KeyCode	 = 0x6B,	// Scroll Lock
    kF15KeyCode	 = 0x71	// Pause
  };
  bzf_key.chr = 0;
  bzf_key.button = BzfKeyEvent::NoButton;
  switch (char_code) {
  case kUpArrowCharCode   : bzf_key.button = BzfKeyEvent::Up;       break;
  case kDownArrowCharCode : bzf_key.button = BzfKeyEvent::Down;     break;
  case kLeftArrowCharCode : bzf_key.button = BzfKeyEvent::Left;     break;
  case kRightArrowCharCode: bzf_key.button = BzfKeyEvent::Right;    break;
  case kHomeCharCode      : bzf_key.button = BzfKeyEvent::Home;     break;
  case kEndCharCode       : bzf_key.button = BzfKeyEvent::End;      break;
  case kPageUpCharCode    : bzf_key.button = BzfKeyEvent::PageUp;   break;
  case kPageDownCharCode  : bzf_key.button = BzfKeyEvent::PageDown; break;
  case kHelpCharCode      : bzf_key.button = BzfKeyEvent::Insert;   break;
  case kDeleteCharCode    : bzf_key.button = BzfKeyEvent::Delete;   break;
  case kFunctionKeyCharCode:
    switch(keycode) {
      // These are the f-key codes on my apple extended keyboard
    case kF15KeyCode:	bzf_key.button = BzfKeyEvent::Pause; break;
    case kF12KeyCode:	bzf_key.button = BzfKeyEvent::F12;	break;
    case kF11KeyCode:	bzf_key.button = BzfKeyEvent::F11;	break;
    case kF10KeyCode:	bzf_key.button = BzfKeyEvent::F10;	break;
    case kF9KeyCode:	bzf_key.button = BzfKeyEvent::F9;	break;
    case kF8KeyCode:	bzf_key.button = BzfKeyEvent::F8;	break;
    case kF7KeyCode:	bzf_key.button = BzfKeyEvent::F7;	break;
    case kF6KeyCode:	bzf_key.button = BzfKeyEvent::F6;	break;
    case kF5KeyCode:	bzf_key.button = BzfKeyEvent::F5;	break;
    case kF4KeyCode:	bzf_key.button = BzfKeyEvent::F4;	break;
    case kF3KeyCode:	bzf_key.button = BzfKeyEvent::F3;	break;
    case kF2KeyCode:	bzf_key.button = BzfKeyEvent::F2;	break;
    case kF1KeyCode:	bzf_key.button = BzfKeyEvent::F1;	break;
    default:	fprintf(stderr, "Unknown function key code: 0x%lX\n", (long unsigned int) keycode);	break;
    }
    break;
    // standard key; a-z, 0-9 etc
  default:	bzf_key.chr  = char_code;		break;
  }
}

// Local Variables: ***
// mode: C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|>


<commit_before>/*
 * Request.cpp
 *
 * Copyright (C) 2009-12 by RStudio, Inc.
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#include <core/http/Request.hpp>

#include <boost/tokenizer.hpp>
#include <boost/asio/buffer.hpp>
#include <boost/algorithm/string/predicate.hpp>

#include <core/Log.hpp>
#include <core/Thread.hpp>

namespace rstudio {
namespace core {
namespace http {

Request::Request()
   : remoteUid_(-1),
     parsedCookies_(false),
     parsedFormFields_(false),
     parsedQueryParams_(false)
{
}

Request::~Request()
{
}

std::string Request::absoluteUri() const
{
   std::string scheme = "http";
   std::string forwardedScheme = headerValue("X-Forwarded-Proto");
   if (!forwardedScheme.empty())
      scheme = forwardedScheme;

   return scheme + "://" + host() + uri();
}

bool Request::acceptsContentType(const std::string& contentType) const
{
   return headerValue("Accept").find(contentType) != std::string::npos;
}

bool Request::acceptsEncoding(const std::string& encoding) const
{
   // read , separated fields
   using namespace boost ;
   char_separator<char> comma(",");
   tokenizer<char_separator<char> > tokens(acceptEncoding(), comma);
   return std::find(tokens.begin(), tokens.end(), encoding) != tokens.end();
}

boost::posix_time::ptime Request::ifModifiedSince() const
{
   using namespace boost::posix_time;

   std::string modifiedSinceDate = headerValue("If-Modified-Since");
   if (!modifiedSinceDate.empty())
   {
      return util::parseHttpDate(modifiedSinceDate);
   }
   else
   {
      return ptime(not_a_date_time);
   }

}

std::string Request::path() const
{
   std::string::size_type pos = uri().find('?');
   if (pos != std::string::npos)
      return uri().substr(0, pos);
   else
      return uri();
}

std::string Request::queryString() const
{
   // find ? in uri()
   std::string::size_type pos = uri().find('?');
   if (pos != std::string::npos)
   {
      std::string::size_type qsPos = pos + 1;
      if (uri().length() > qsPos)
         return uri().substr(qsPos);
      else
         return std::string();
   }
   else
   {
      return std::string();
   }
}

const Fields& Request::queryParams() const
{
   if (!parsedQueryParams_)
   {
      util::parseQueryString(queryString(), &queryParams_);
      parsedQueryParams_ = true;
   }

   return queryParams_;
}

std::string Request::cookieValue(const std::string& name) const
{
   // parse cookies on demand
   if ( !parsedCookies_ )
   {
      for (Headers::const_iterator it =
            headers().begin(); it != headers().end(); ++it )
      {
         scanHeaderForCookie(it->name, it->value) ;
      }
      parsedCookies_ = true ;
   }

   // lookup the cookie
   return util::fieldValue(cookies_, name);
}

std::string Request::formFieldValue(const std::string& name) const
{
   ensureFormFieldsParsed();

   // lookup the form field
   return util::fieldValue(formFields_, name);
}

const Fields& Request::formFields() const
{
   ensureFormFieldsParsed();

   return formFields_ ;
}

const File& Request::uploadedFile(const std::string& name) const
{
   ensureFormFieldsParsed();

   // lookup the file
   for (Files::const_iterator it = files_.begin(); it != files_.end(); ++it)
   {
      if (it->first == name)
         return it->second;
   }

   // not found
   return emptyFile_;
}

std::string Request::queryParamValue(const std::string& name) const
{
   // lookup the query param
   return util::fieldValue(queryParams(), name);
}

void Request::setBody(const std::string& body)
{
   body_ = body;
   setContentLength(body_.length());
}

void Request::debugPrintUri(const std::string& caption) const
{
   static boost::mutex printMutex;
   LOCK_MUTEX(printMutex)
   {
      std::cerr << caption << ": " << uri() << std::endl;
   }
   END_LOCK_MUTEX
}

void Request::resetMembers()
{
   method_.clear() ;
   uri_.clear() ;
   parsedCookies_ = false ;
   cookies_.clear() ;
   parsedFormFields_ = false ;
   formFields_.clear() ;
   parsedQueryParams_ = false;
   queryParams_.clear();
}

void Request::appendFirstLineBuffers(
      std::vector<boost::asio::const_buffer>& buffers) const
{
   using boost::asio::buffer ;

   // request line
   buffers.push_back(buffer(method_)) ;
   appendSpaceBuffer(buffers) ;
   buffers.push_back(buffer(uri_)) ;
   appendSpaceBuffer(buffers) ;
   appendHttpVersionBuffers(buffers) ;
}

void Request::ensureFormFieldsParsed() const
{
   // parase form fields on demand
   if ( !parsedFormFields_ )
   {
      std::string contentType = headerValue("Content-Type");
      if (contentType == "application/x-www-form-urlencoded")
      {
         util::parseFields(body(),
                           "&",
                           "=",
                           &formFields_,
                           util::FieldDecodeForm);
      }
      else if (contentType.find("multipart/form-data") == 0)
      {
         util::parseMultipartForm(contentType, body(), &formFields_, &files_);
      }
      else
      {
         // no form fields available
      }

      parsedFormFields_ = true ;
   }
}

void Request::scanHeaderForCookie(const std::string& name,
                                  const std::string& value) const
{
   if (boost::iequals(name, "cookie"))
      util::parseFields(value, ";, ", "= ", &cookies_, util::FieldDecodeNone) ;
}

std::ostream& operator << (std::ostream& stream, const Request& r)
{
   // output request line
   stream << r.method() << " "
          << r.uri()
          << " HTTP/" << r.httpVersionMajor() << "." << r.httpVersionMinor()
          << std::endl ;

   // output headers and body
   const Message& m = r ;
   stream << m ;

   return stream ;
}

} // namespacce http
} // namespace core
} // namespace rstudio

<commit_msg>fix potential memory error<commit_after>/*
 * Request.cpp
 *
 * Copyright (C) 2009-12 by RStudio, Inc.
 *
 * Unless you have received this program directly from RStudio pursuant
 * to the terms of a commercial license agreement with RStudio, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#include <core/http/Request.hpp>

#include <boost/tokenizer.hpp>
#include <boost/asio/buffer.hpp>
#include <boost/algorithm/string/predicate.hpp>

#include <core/Log.hpp>
#include <core/Thread.hpp>

namespace rstudio {
namespace core {
namespace http {

Request::Request()
   : remoteUid_(-1),
     parsedCookies_(false),
     parsedFormFields_(false),
     parsedQueryParams_(false)
{
}

Request::~Request()
{
}

std::string Request::absoluteUri() const
{
   std::string scheme = "http";
   std::string forwardedScheme = headerValue("X-Forwarded-Proto");
   if (!forwardedScheme.empty())
      scheme = forwardedScheme;

   return scheme + "://" + host() + uri();
}

bool Request::acceptsContentType(const std::string& contentType) const
{
   return headerValue("Accept").find(contentType) != std::string::npos;
}

bool Request::acceptsEncoding(const std::string& encoding) const
{
   // read , separated fields
   using namespace boost ;
   char_separator<char> comma(",");
   std::string accepted = acceptEncoding();
   tokenizer<char_separator<char>> tokens(accepted, comma);
   return std::find(tokens.begin(), tokens.end(), encoding) != tokens.end();
}

boost::posix_time::ptime Request::ifModifiedSince() const
{
   using namespace boost::posix_time;

   std::string modifiedSinceDate = headerValue("If-Modified-Since");
   if (!modifiedSinceDate.empty())
   {
      return util::parseHttpDate(modifiedSinceDate);
   }
   else
   {
      return ptime(not_a_date_time);
   }

}

std::string Request::path() const
{
   std::string::size_type pos = uri().find('?');
   if (pos != std::string::npos)
      return uri().substr(0, pos);
   else
      return uri();
}

std::string Request::queryString() const
{
   // find ? in uri()
   std::string::size_type pos = uri().find('?');
   if (pos != std::string::npos)
   {
      std::string::size_type qsPos = pos + 1;
      if (uri().length() > qsPos)
         return uri().substr(qsPos);
      else
         return std::string();
   }
   else
   {
      return std::string();
   }
}

const Fields& Request::queryParams() const
{
   if (!parsedQueryParams_)
   {
      util::parseQueryString(queryString(), &queryParams_);
      parsedQueryParams_ = true;
   }

   return queryParams_;
}

std::string Request::cookieValue(const std::string& name) const
{
   // parse cookies on demand
   if ( !parsedCookies_ )
   {
      for (Headers::const_iterator it =
            headers().begin(); it != headers().end(); ++it )
      {
         scanHeaderForCookie(it->name, it->value) ;
      }
      parsedCookies_ = true ;
   }

   // lookup the cookie
   return util::fieldValue(cookies_, name);
}

std::string Request::formFieldValue(const std::string& name) const
{
   ensureFormFieldsParsed();

   // lookup the form field
   return util::fieldValue(formFields_, name);
}

const Fields& Request::formFields() const
{
   ensureFormFieldsParsed();

   return formFields_ ;
}

const File& Request::uploadedFile(const std::string& name) const
{
   ensureFormFieldsParsed();

   // lookup the file
   for (Files::const_iterator it = files_.begin(); it != files_.end(); ++it)
   {
      if (it->first == name)
         return it->second;
   }

   // not found
   return emptyFile_;
}

std::string Request::queryParamValue(const std::string& name) const
{
   // lookup the query param
   return util::fieldValue(queryParams(), name);
}

void Request::setBody(const std::string& body)
{
   body_ = body;
   setContentLength(body_.length());
}

void Request::debugPrintUri(const std::string& caption) const
{
   static boost::mutex printMutex;
   LOCK_MUTEX(printMutex)
   {
      std::cerr << caption << ": " << uri() << std::endl;
   }
   END_LOCK_MUTEX
}

void Request::resetMembers()
{
   method_.clear() ;
   uri_.clear() ;
   parsedCookies_ = false ;
   cookies_.clear() ;
   parsedFormFields_ = false ;
   formFields_.clear() ;
   parsedQueryParams_ = false;
   queryParams_.clear();
}

void Request::appendFirstLineBuffers(
      std::vector<boost::asio::const_buffer>& buffers) const
{
   using boost::asio::buffer ;

   // request line
   buffers.push_back(buffer(method_)) ;
   appendSpaceBuffer(buffers) ;
   buffers.push_back(buffer(uri_)) ;
   appendSpaceBuffer(buffers) ;
   appendHttpVersionBuffers(buffers) ;
}

void Request::ensureFormFieldsParsed() const
{
   // parase form fields on demand
   if ( !parsedFormFields_ )
   {
      std::string contentType = headerValue("Content-Type");
      if (contentType == "application/x-www-form-urlencoded")
      {
         util::parseFields(body(),
                           "&",
                           "=",
                           &formFields_,
                           util::FieldDecodeForm);
      }
      else if (contentType.find("multipart/form-data") == 0)
      {
         util::parseMultipartForm(contentType, body(), &formFields_, &files_);
      }
      else
      {
         // no form fields available
      }

      parsedFormFields_ = true ;
   }
}

void Request::scanHeaderForCookie(const std::string& name,
                                  const std::string& value) const
{
   if (boost::iequals(name, "cookie"))
      util::parseFields(value, ";, ", "= ", &cookies_, util::FieldDecodeNone) ;
}

std::ostream& operator << (std::ostream& stream, const Request& r)
{
   // output request line
   stream << r.method() << " "
          << r.uri()
          << " HTTP/" << r.httpVersionMajor() << "." << r.httpVersionMinor()
          << std::endl ;

   // output headers and body
   const Message& m = r ;
   stream << m ;

   return stream ;
}

} // namespacce http
} // namespace core
} // namespace rstudio

<|endoftext|>


<commit_before>
#include "lcio.h"

#include "IO/LCWriter.h"
#include "EVENT/LCIO.h"
#include "DATA/LCFloatVec.h"
#include "DATA/LCIntVec.h"

#include "IMPL/LCEventImpl.h"
#include "IMPL/LCRunHeaderImpl.h"
#include "IMPL/LCCollectionVec.h"
#include "IMPL/SimCalorimeterHitImpl.h"
#include "IMPL/SimTrackerHitImpl.h"
#include "IMPL/MCParticleImpl.h"
#include "IMPL/LCFlagImpl.h"
#include "IMPL/LCTOOLS.h"

#include <cstdlib>
#include <iostream>
#include <sstream>

using namespace std ;
using namespace lcio ;

static const int NRUN = 10 ;
static const int NEVENT = 10 ; // events
static const int NMCPART = 10 ;  // mc particles per event
static const int NHITS = 50 ;  // calorimeter hits per event

static string FILEN = "simjob.slcio" ;

/** Simple test program to demonstrate writing of data with lcio.
 */

int main(int argc, char** argv ){

  try{
    // create sio writer
    LCWriter* lcWrt = LCFactory::getInstance()->createLCWriter() ;

    if( argc > 1 ) { FILEN = argv[1] ; }

    try{  lcWrt->open( FILEN ) ;
    }
    catch( IOException& e ){
      cout << e.what() << endl ;
      return 0 ;
    }
//     int status ;
//     if( (status = lcWrt->open( FILEN ))  != LCIO::SUCCESS ) {
//       cout << " couldn't open file  : " << FILEN << " status: " << status << endl ;
//       return 0 ;
//     }

    // loop over runs
    for(int rn=0;rn<NRUN;rn++){

      LCRunHeaderImpl* runHdr = new LCRunHeaderImpl ;
      runHdr->setRunNumber( rn ) ;

      string detName("D09TileHcal")  ;
      runHdr->setDetectorName( detName ) ;

      stringstream description ;
      description << " run: " << rn <<" just for testing lcio  - no physics !" ;
      runHdr->setDescription( description.str()  ) ;

      string ecalName("ECAL007") ;
      runHdr->addActiveSubdetector( ecalName ) ;

      string tpcName("TPC4711") ;
      runHdr->addActiveSubdetector( tpcName ) ;

      lcWrt->writeRunHeader( runHdr ) ;

      // EventLoop - create some events and write them to the file
      for(int i=0;i<NEVENT;i++){

	// we need to use the implementation classes here
	LCEventImpl*  evt = new LCEventImpl() ;

	evt->setRunNumber(  rn   ) ;
	evt->setEventNumber( i ) ;
	evt->setDetectorName( detName ) ;

	// create and add some mc particles
	LCCollectionVec* mcVec = new LCCollectionVec( LCIO::MCPARTICLE )  ;

	MCParticleImpl* mom = new MCParticleImpl ;
	mom->setPDG( 1  ) ;
	float p0[3] = { 0. , 0. , 1000. } ;
	mom->setMomentum( p0 ) ;

	for(int j=0;j<NMCPART;j++){

	  MCParticleImpl* mcp = new MCParticleImpl ;

	  mcp->setPDG( 1000 * (j+1)  ) ;
	  float p[3] = { j*1. , 4./1024. , 8./1024. } ;
	  mcp->setMomentum( p ) ;

	  // create and add some daughters
	  for(int k=0;k<3;k++){
	    MCParticleImpl* d1 = new MCParticleImpl ;

	    d1->setPDG( 1000 * (j+1) + 100 * (k+1)  ) ;
	    float pd1[3] = { k*1. , 4.1 , 8.1 } ;
	    d1->setMomentum( pd1 ) ;

	    for(int l=0;l<2;l++){
	      MCParticleImpl* d2 = new MCParticleImpl ;

	      d2->setPDG( 1000 * (j+1) + 100 * (k+1) + 10 *  (l+1)  ) ;
	      float pd2[3] = { l*1. , 0.41 , 4.1 } ;
	      d2->setMomentum( pd2 ) ;

	      d2->setParent( d1 );
	      d1->addDaughter( d2 ) ;
	      mcVec->push_back( d2 ) ;
	    }
	    d1->setParent( mcp );
	    mcp->addDaughter( d1 ) ;
	    mcVec->push_back( d1 ) ;
	  }

	  mcp->setParent( mom );
	  mom->addDaughter( mcp ) ;
	  mcVec->push_back( mcp ) ;
	}
	mcVec->push_back( mom ) ;

	// now add some calorimeter hits
	LCCollectionVec* calVec = new LCCollectionVec( LCIO::SIMCALORIMETERHIT )  ;

	// set flag for long format (including position )
	// and PDG
	LCFlagImpl chFlag(0) ;
	chFlag.setBit( LCIO::CHBIT_LONG ) ;
	chFlag.setBit( LCIO::CHBIT_PDG ) ;
	calVec->setFlag( chFlag.getFlag()  ) ;

	for(int j=0;j<NHITS;j++){

	  SimCalorimeterHitImpl* hit = new SimCalorimeterHitImpl ;

	  hit->setEnergy( 3.1415 * rand()/RAND_MAX   )  ;

	  float pos[3] = { 1.1* rand()/RAND_MAX , 2.2* rand()/RAND_MAX , 3.3* rand()/RAND_MAX } ;

	  hit->setPosition( pos ) ;

	  calVec->push_back( hit ) ;

	  // assign the hits randomly to MC particles
	  float rn =  .99999*rand()/RAND_MAX ;
	  int mcIndx = static_cast<int>( NMCPART * rn ) ;

	  // in order to access a MCParticle,  we need a dynamic cast as the
	  // LCCollection returns an LCIOObject - this is like vectors in Java
	  hit->addMCParticleContribution(  dynamic_cast<const MCParticle*>(mcVec->getElementAt( mcIndx )) ,
					   0.314159, 0.1155 ) ; // no pdg

	}

	// we can modify hits that already exist in a collection, e.g. in a simulation step function ...
	// we need a non const pointer to the hit and use the std::vector::operator[]() instead of the
	// LCCollection::getElementAt(i)
	for(int j=0;j<NHITS;j++){
	  SimCalorimeterHitImpl* existingHit = dynamic_cast<SimCalorimeterHitImpl*>( (*calVec)[j] ) ;

	  existingHit->addMCParticleContribution( dynamic_cast<const MCParticle*>
						  (mcVec->getElementAt(0)),
						  0.1, 0. ) ;
	}

	// and finally some tracker hits
	// with some user extensions (4 floats and 2 ints) per track:
	// we just create parallel collections of float and int vectors
	LCCollectionVec* trkVec = new LCCollectionVec( LCIO::SIMTRACKERHIT )  ;
	LCCollectionVec* extFVec = new LCCollectionVec( LCIO::LCFLOATVEC )  ;
	LCCollectionVec* extIVec = new LCCollectionVec( LCIO::LCINTVEC )  ;

	for(int j=0;j<NHITS;j++){

	  SimTrackerHitImpl* hit = new SimTrackerHitImpl ;
	  LCFloatVec* extF = new LCFloatVec ;
	  LCIntVec*   extI = new LCIntVec ;

	  hit->setdEdx( 30e-9 ) ;

	  double pos[3] = { 1.1* rand()/RAND_MAX , 2.2* rand()/RAND_MAX , 3.3* rand()/RAND_MAX } ;

	  hit->setPosition( pos ) ;

	  // assign the hits randomly to MC particles
	  float rn =  .99999*rand()/RAND_MAX ;
	  int mcIndx = static_cast<int>( NMCPART * rn ) ;

	  hit->setMCParticle( dynamic_cast<const MCParticle*>(mcVec->getElementAt( mcIndx ) ) ) ;

	  // fill the extension vectors (4 floats, 2 ints)
	  extF->push_back( 3.14159 ) ;
	  for(int k=0;k<3;k++) extF->push_back(  pos[k] * 0.1  ) ;

	  extI->push_back( 123456789 ) ;
	  extI->push_back( mcIndx ) ;

	  // add the hit and the extensions to their corresponding collections
	  trkVec->push_back( hit ) ;
	  extFVec->push_back( extF ) ;
	  extIVec->push_back( extI ) ;
	}

	// add all collection to the event
	evt->addCollection( (LCCollection*) mcVec , "MCParticle" ) ;
	evt->addCollection( (LCCollection*) calVec , ecalName ) ;
	evt->addCollection( (LCCollection*) trkVec , tpcName ) ;
	evt->addCollection( (LCCollection*) extFVec , tpcName+"UserFloatExtensionTPC" ) ;
	evt->addCollection( (LCCollection*) extIVec , tpcName+"UserIntExtensionTPC" ) ;

	// test: add a collection for one event only:
	if( rn == NRUN-1 && i == 0 ) { // first event o last run
	  LCCollectionVec* addExtVec = new LCCollectionVec( LCIO::LCFLOATVEC )  ;
	  LCFloatVec* addExt = new LCFloatVec ;
	  addExt->push_back( 1. );
	  addExt->push_back( 2. );
	  addExt->push_back( 3. );
	  addExt->push_back( 4. );
	  addExtVec->push_back( addExt ) ;
	  evt->addCollection( (LCCollection*) addExtVec , "AdditionalExtension" ) ;
	}

	// write the event to the file
	lcWrt->writeEvent( evt ) ;

	// dump the event to the screen
	LCTOOLS::dumpEvent( evt ) ;
	//	LCTOOLS::printMCParticles( mcVec ) ;

	// we created the event so we need to take care of deleting it ...
	delete evt ;

	if( ! (i%100) ) cout << ". " << flush  ;

      } // evt loop
    } // run loop

    cout << endl
	 << " created  " << NRUN << " runs with  " << NRUN*NEVENT << " events"
	 << endl << endl ;

    lcWrt->close() ;

  } catch( Exception& ex){

    cout << " an excpetion occured: " << endl ;
    cout << "  " << ex.what() << endl ;
    return 1 ;
  }

  return 0 ;
}

<commit_msg>changed name of extension collections.<commit_after>
#include "lcio.h"

#include "IO/LCWriter.h"
#include "EVENT/LCIO.h"
#include "DATA/LCFloatVec.h"
#include "DATA/LCIntVec.h"

#include "IMPL/LCEventImpl.h"
#include "IMPL/LCRunHeaderImpl.h"
#include "IMPL/LCCollectionVec.h"
#include "IMPL/SimCalorimeterHitImpl.h"
#include "IMPL/SimTrackerHitImpl.h"
#include "IMPL/MCParticleImpl.h"
#include "IMPL/LCFlagImpl.h"
#include "IMPL/LCTOOLS.h"

#include <cstdlib>
#include <iostream>
#include <sstream>

using namespace std ;
using namespace lcio ;

static const int NRUN = 10 ;
static const int NEVENT = 10 ; // events
static const int NMCPART = 10 ;  // mc particles per event
static const int NHITS = 50 ;  // calorimeter hits per event

static string FILEN = "simjob.slcio" ;

/** Simple test program to demonstrate writing of data with lcio.
 */

int main(int argc, char** argv ){

  try{
    // create sio writer
    LCWriter* lcWrt = LCFactory::getInstance()->createLCWriter() ;

    if( argc > 1 ) { FILEN = argv[1] ; }

    try{  lcWrt->open( FILEN ) ;
    }
    catch( IOException& e ){
      cout << e.what() << endl ;
      return 0 ;
    }
//     int status ;
//     if( (status = lcWrt->open( FILEN ))  != LCIO::SUCCESS ) {
//       cout << " couldn't open file  : " << FILEN << " status: " << status << endl ;
//       return 0 ;
//     }

    // loop over runs
    for(int rn=0;rn<NRUN;rn++){

      LCRunHeaderImpl* runHdr = new LCRunHeaderImpl ;
      runHdr->setRunNumber( rn ) ;

      string detName("D09TileHcal")  ;
      runHdr->setDetectorName( detName ) ;

      stringstream description ;
      description << " run: " << rn <<" just for testing lcio  - no physics !" ;
      runHdr->setDescription( description.str()  ) ;

      string ecalName("ECAL007") ;
      runHdr->addActiveSubdetector( ecalName ) ;

      string tpcName("TPC4711") ;
      runHdr->addActiveSubdetector( tpcName ) ;

      lcWrt->writeRunHeader( runHdr ) ;

      // EventLoop - create some events and write them to the file
      for(int i=0;i<NEVENT;i++){

	// we need to use the implementation classes here
	LCEventImpl*  evt = new LCEventImpl() ;

	evt->setRunNumber(  rn   ) ;
	evt->setEventNumber( i ) ;
	evt->setDetectorName( detName ) ;

	// create and add some mc particles
	LCCollectionVec* mcVec = new LCCollectionVec( LCIO::MCPARTICLE )  ;

	MCParticleImpl* mom = new MCParticleImpl ;
	mom->setPDG( 1  ) ;
	float p0[3] = { 0. , 0. , 1000. } ;
	mom->setMomentum( p0 ) ;

	for(int j=0;j<NMCPART;j++){

	  MCParticleImpl* mcp = new MCParticleImpl ;

	  mcp->setPDG( 1000 * (j+1)  ) ;
	  float p[3] = { j*1. , 4./1024. , 8./1024. } ;
	  mcp->setMomentum( p ) ;

	  // create and add some daughters
	  for(int k=0;k<3;k++){
	    MCParticleImpl* d1 = new MCParticleImpl ;

	    d1->setPDG( 1000 * (j+1) + 100 * (k+1)  ) ;
	    float pd1[3] = { k*1. , 4.1 , 8.1 } ;
	    d1->setMomentum( pd1 ) ;

	    for(int l=0;l<2;l++){
	      MCParticleImpl* d2 = new MCParticleImpl ;

	      d2->setPDG( 1000 * (j+1) + 100 * (k+1) + 10 *  (l+1)  ) ;
	      float pd2[3] = { l*1. , 0.41 , 4.1 } ;
	      d2->setMomentum( pd2 ) ;

	      d2->setParent( d1 );
	      d1->addDaughter( d2 ) ;
	      mcVec->push_back( d2 ) ;
	    }
	    d1->setParent( mcp );
	    mcp->addDaughter( d1 ) ;
	    mcVec->push_back( d1 ) ;
	  }

	  mcp->setParent( mom );
	  mom->addDaughter( mcp ) ;
	  mcVec->push_back( mcp ) ;
	}
	mcVec->push_back( mom ) ;

	// now add some calorimeter hits
	LCCollectionVec* calVec = new LCCollectionVec( LCIO::SIMCALORIMETERHIT )  ;

	// set flag for long format (including position )
	// and PDG
	LCFlagImpl chFlag(0) ;
	chFlag.setBit( LCIO::CHBIT_LONG ) ;
	chFlag.setBit( LCIO::CHBIT_PDG ) ;
	calVec->setFlag( chFlag.getFlag()  ) ;

	for(int j=0;j<NHITS;j++){

	  SimCalorimeterHitImpl* hit = new SimCalorimeterHitImpl ;

	  hit->setEnergy( 3.1415 * rand()/RAND_MAX   )  ;

	  float pos[3] = { 1.1* rand()/RAND_MAX , 2.2* rand()/RAND_MAX , 3.3* rand()/RAND_MAX } ;

	  hit->setPosition( pos ) ;

	  calVec->push_back( hit ) ;

	  // assign the hits randomly to MC particles
	  float rn =  .99999*rand()/RAND_MAX ;
	  int mcIndx = static_cast<int>( NMCPART * rn ) ;

	  // in order to access a MCParticle,  we need a dynamic cast as the
	  // LCCollection returns an LCIOObject - this is like vectors in Java
	  hit->addMCParticleContribution(  dynamic_cast<const MCParticle*>(mcVec->getElementAt( mcIndx )) ,
					   0.314159, 0.1155 ) ; // no pdg

	}

	// we can modify hits that already exist in a collection, e.g. in a simulation step function ...
	// we need a non const pointer to the hit and use the std::vector::operator[]() instead of the
	// LCCollection::getElementAt(i)
	for(int j=0;j<NHITS;j++){
	  SimCalorimeterHitImpl* existingHit = dynamic_cast<SimCalorimeterHitImpl*>( (*calVec)[j] ) ;

	  existingHit->addMCParticleContribution( dynamic_cast<const MCParticle*>
						  (mcVec->getElementAt(0)),
						  0.1, 0. ) ;
	}

	// and finally some tracker hits
	// with some user extensions (4 floats and 2 ints) per track:
	// we just create parallel collections of float and int vectors
	LCCollectionVec* trkVec = new LCCollectionVec( LCIO::SIMTRACKERHIT )  ;
	LCCollectionVec* extFVec = new LCCollectionVec( LCIO::LCFLOATVEC )  ;
	LCCollectionVec* extIVec = new LCCollectionVec( LCIO::LCINTVEC )  ;

	for(int j=0;j<NHITS;j++){

	  SimTrackerHitImpl* hit = new SimTrackerHitImpl ;
	  LCFloatVec* extF = new LCFloatVec ;
	  LCIntVec*   extI = new LCIntVec ;

	  hit->setdEdx( 30e-9 ) ;

	  double pos[3] = { 1.1* rand()/RAND_MAX , 2.2* rand()/RAND_MAX , 3.3* rand()/RAND_MAX } ;

	  hit->setPosition( pos ) ;

	  // assign the hits randomly to MC particles
	  float rn =  .99999*rand()/RAND_MAX ;
	  int mcIndx = static_cast<int>( NMCPART * rn ) ;

	  hit->setMCParticle( dynamic_cast<const MCParticle*>(mcVec->getElementAt( mcIndx ) ) ) ;

	  // fill the extension vectors (4 floats, 2 ints)
	  extF->push_back( 3.14159 ) ;
	  for(int k=0;k<3;k++) extF->push_back(  pos[k] * 0.1  ) ;

	  extI->push_back( 123456789 ) ;
	  extI->push_back( mcIndx ) ;

	  // add the hit and the extensions to their corresponding collections
	  trkVec->push_back( hit ) ;
	  extFVec->push_back( extF ) ;
	  extIVec->push_back( extI ) ;
	}

	// add all collection to the event
	evt->addCollection( (LCCollection*) mcVec , "MCParticle" ) ;
	evt->addCollection( (LCCollection*) calVec , ecalName ) ;
	evt->addCollection( (LCCollection*) trkVec , tpcName ) ;
	evt->addCollection( (LCCollection*) extFVec , tpcName+"UserFloatExtension" ) ;
	evt->addCollection( (LCCollection*) extIVec , tpcName+"UserIntExtension" ) ;

	// test: add a collection for one event only:
	if( rn == NRUN-1 && i == 0 ) { // first event o last run
	  LCCollectionVec* addExtVec = new LCCollectionVec( LCIO::LCFLOATVEC )  ;
	  LCFloatVec* addExt = new LCFloatVec ;
	  addExt->push_back( 1. );
	  addExt->push_back( 2. );
	  addExt->push_back( 3. );
	  addExt->push_back( 4. );
	  addExtVec->push_back( addExt ) ;
	  evt->addCollection( (LCCollection*) addExtVec , "AdditionalExtension" ) ;
	}

	// write the event to the file
	lcWrt->writeEvent( evt ) ;

	// dump the event to the screen
	LCTOOLS::dumpEvent( evt ) ;
	//	LCTOOLS::printMCParticles( mcVec ) ;

	// we created the event so we need to take care of deleting it ...
	delete evt ;

	if( ! (i%100) ) cout << ". " << flush  ;

      } // evt loop
    } // run loop

    cout << endl
	 << " created  " << NRUN << " runs with  " << NRUN*NEVENT << " events"
	 << endl << endl ;

    lcWrt->close() ;

  } catch( Exception& ex){

    cout << " an excpetion occured: " << endl ;
    cout << "  " << ex.what() << endl ;
    return 1 ;
  }

  return 0 ;
}

<|endoftext|>


<commit_before>#include <cppunit/XmlOutputterHook.h>

#if !defined(CPPUNIT_NO_TESTPLUGIN)
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/plugin/PlugInManager.h>
#include <cppunit/plugin/TestPlugIn.h>
#include <cppunit/plugin/DynamicLibraryManager.h>

CPPUNIT_NS_BEGIN

PlugInManager::PlugInManager()
{
}

PlugInManager::~PlugInManager()
{
  for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )
    unload( *it );
}

void
PlugInManager::load( const std::string &libraryFileName,
                     const PlugInParameters &parameters )
{
  PlugInInfo info;
  info.m_fileName = libraryFileName;
  info.m_manager = new DynamicLibraryManager( libraryFileName );

  TestPlugInSignature plug = (TestPlugInSignature)info.m_manager->findSymbol(
        CPPUNIT_STRINGIZE( CPPUNIT_PLUGIN_EXPORTED_NAME ) );
  info.m_interface = (*plug)();

  m_plugIns.push_back( info );

  info.m_interface->initialize( &TestFactoryRegistry::getRegistry(), parameters );
}

void
PlugInManager::unload( const std::string &libraryFileName )
{
  for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )
  {
    if ( it->m_fileName == libraryFileName )
    {
      unload( *it );
      m_plugIns.erase( it );
      break;
    }
  }
}

void
PlugInManager::addListener( TestResult *eventManager )
{
  for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )
    it->m_interface->addListener( eventManager );
}

void
PlugInManager::removeListener( TestResult *eventManager )
{
  for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )
    it->m_interface->removeListener( eventManager );
}

void
PlugInManager::unload( PlugInInfo &plugIn )
{
  try
  {
    plugIn.m_interface->uninitialize( &TestFactoryRegistry::getRegistry() );
    delete plugIn.m_manager;
  }
  catch (...)
  {
    delete plugIn.m_manager;
    plugIn.m_manager = NULL;
    throw;
  }
}

void
PlugInManager::addXmlOutputterHooks( XmlOutputter *outputter )
{
  for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )
    it->m_interface->addXmlOutputterHooks( outputter );
}

void
PlugInManager::removeXmlOutputterHooks()
{
  for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )
    it->m_interface->removeXmlOutputterHooks();
}

CPPUNIT_NS_END

#endif // !defined(CPPUNIT_NO_TESTPLUGIN)
<commit_msg>Dereferencing fix for SUN4<commit_after>#include <cppunit/XmlOutputterHook.h>

#if !defined(CPPUNIT_NO_TESTPLUGIN)
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/plugin/PlugInManager.h>
#include <cppunit/plugin/TestPlugIn.h>
#include <cppunit/plugin/DynamicLibraryManager.h>

CPPUNIT_NS_BEGIN

PlugInManager::PlugInManager()
{
}

PlugInManager::~PlugInManager()
{
  for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )
    unload( *it );
}

void
PlugInManager::load( const std::string &libraryFileName,
                     const PlugInParameters &parameters )
{
  PlugInInfo info;
  info.m_fileName = libraryFileName;
  info.m_manager = new DynamicLibraryManager( libraryFileName );

  TestPlugInSignature plug = (TestPlugInSignature)info.m_manager->findSymbol(
        CPPUNIT_STRINGIZE( CPPUNIT_PLUGIN_EXPORTED_NAME ) );
  info.m_interface = (*plug)();

  m_plugIns.push_back( info );

  info.m_interface->initialize( &TestFactoryRegistry::getRegistry(), parameters );
}

void
PlugInManager::unload( const std::string &libraryFileName )
{
  for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )
  {
    if ( (*it).m_fileName == libraryFileName )
    {
      unload( *it );
      m_plugIns.erase( it );
      break;
    }
  }
}

void
PlugInManager::addListener( TestResult *eventManager )
{
  for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )
    (*it).m_interface->addListener( eventManager );
}

void
PlugInManager::removeListener( TestResult *eventManager )
{
  for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )
    (*it).m_interface->removeListener( eventManager );
}

void
PlugInManager::unload( PlugInInfo &plugIn )
{
  try
  {
    plugIn.m_interface->uninitialize( &TestFactoryRegistry::getRegistry() );
    delete plugIn.m_manager;
  }
  catch (...)
  {
    delete plugIn.m_manager;
    plugIn.m_manager = NULL;
    throw;
  }
}

void
PlugInManager::addXmlOutputterHooks( XmlOutputter *outputter )
{
  for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )
    (*it).m_interface->addXmlOutputterHooks( outputter );
}

void
PlugInManager::removeXmlOutputterHooks()
{
  for ( PlugIns::iterator it = m_plugIns.begin(); it != m_plugIns.end(); ++it )
    (*it).m_interface->removeXmlOutputterHooks();
}

CPPUNIT_NS_END

#endif // !defined(CPPUNIT_NO_TESTPLUGIN)
<|endoftext|>


<commit_before>//-----------------------------------------------------------------------------
//@file
//	WeaveArray.cpp
//
//@author
//	ab5tract
//
//@brief
//	Implementation of the WeaveArray class.
//
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
// includes
//-----------------------------------------------------------------------------
#include "WeaveArray.h"

//----------------------------------------------------------------------------
// create, general info and destroy methodes
//----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
// Create
void CreateModule (void* &pModule, AnsiCharPtr optionalString, LongBool Flag, MasterInfo* pMasterInfo, AnsiCharPtr optionalContent)
{
	pModule = new WeaveArray ();
}

//-----------------------------------------------------------------------------
// destroy
void DestroyModule (void* pModule)
{
    // cast is important to call the good destructor
	delete ((WeaveArray*)pModule);
}

//-----------------------------------------------------------------------------
// module description
void WeaveArray::onGetModuleInfo (MasterInfo* pMasterInfo, ModuleInfo* pModuleInfo)
{

	//identification of the module
	pModuleInfo->Name				= "weave array";
	pModuleInfo->Description		= "Weave Arrays";
	pModuleInfo->ModuleType         = mtSimple;
	pModuleInfo->BackColor          = sdkGetUsineColor(clDataModuleColor);
	pModuleInfo->NumberOfParams     = 3;
	pModuleInfo->Version			= "1.0";
	pModuleInfo->DontProcess		= TRUE;
}

//-----------------------------------------------------------------------------
// query system and init methodes
//-----------------------------------------------------------------------------
// query system not used

//void WeaveArray::onInitModule (MasterInfo* pMasterInfo, ModuleInfo* pModuleInfo)
//{
//}

//----------------------------------------------------------------------------
// parameters and process
//----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
// Parameters description
void WeaveArray::onGetParamInfo (int ParamIndex, TParamInfo* pParamInfo)
{
	// all parameters declared in the module class
	switch (ParamIndex)
	{
	// waInput1
	case 0:
		pParamInfo->ParamType		= ptArray;
		pParamInfo->Caption			= "array 1";
		pParamInfo->IsInput			= TRUE;
		pParamInfo->IsOutput		= FALSE;
        pParamInfo->MinValue		= - FLT_MAX;
        pParamInfo->MaxValue		= FLT_MAX;
		pParamInfo->CallBackType	= ctImmediate;
		break;

	// waInput2
	case 1:
		pParamInfo->ParamType		= ptArray;
		pParamInfo->Caption			= "array 2";
		pParamInfo->IsInput			= TRUE;
		pParamInfo->IsOutput		= FALSE;
        pParamInfo->MinValue		= - FLT_MAX;
        pParamInfo->MaxValue		= FLT_MAX;
		pParamInfo->CallBackType	= ctImmediate;
		break;

	// waOutput
	case 2:
		pParamInfo->ParamType		= ptArray;
		pParamInfo->Caption			= "output";
		pParamInfo->IsInput			= FALSE;
		pParamInfo->IsOutput		= TRUE;
        pParamInfo->MinValue		= - FLT_MAX;
        pParamInfo->MaxValue		= FLT_MAX;
        pParamInfo->CallBackType	= ctImmediate;
		break;

	// default case
	default:
		break;
	}
}

//-----------------------------------------------------------------------------
// set the parameters events address
void WeaveArray::onSetEventAddress (int ParamIndex, UsineEventPtr pEvent)
{

	//Initialyse all events adress declared in your module class
	switch (ParamIndex)
    {
	// waInput1
	case 0:
		waInput1 = pEvent;
		break;

	// waInput2
	case 1:
		waInput2 = pEvent;
		break;

	// waOutput
	case 2:
		waOutput = pEvent;
		break;

	// default case
	default:
		break;

	}
}

//-----------------------------------------------------------------------------
// Parameters callback
void WeaveArray::onCallBack (UsineMessage* Message)
{
	try
	{
        if (Message->message == NOTIFY_MSG_USINE_CALLBACK)
        {
            int paramIndex = (int)Message->wParam;

            if((paramIndex == 0 || paramIndex == 1) && Message->lParam == MSG_CHANGE)
            {
                /*
                int tmp1,tmp2;
                tmp1 = sdkGetEvtSize(waInput1);
                tmp2 = sdkGetEvtSize(waInput2);
                if (tmp1 != input1Length || tmp2 != input2Length)
                {
                    input1Length = tmp1;
                    input2Length = tmp2;
                    outputLength = input1Length + input2Length;
                    for( int i=0; i < outputLength; i++)
                    {
                        sdkSetEvtArrayData(waOutput, i, 0);
                    }
                }
                */
                input1Length = sdkGetEvtSize(waInput1);
                input2Length = sdkGetEvtSize(waInput2);
                outputLength = input1Length + input2Length;
                writeOutput();
            }
        }
	}
	catch (...)
	{
		//sdkTraceErrorChar("error");
	}
}

void WeaveArray::writeOutput()
{
    sdkSetEvtSize(waOutput, outputLength);
    int i;
    int r = 0;

    if ( input1Length <= input2Length )
    {
        for ( i=0; i < input1Length; i++ )
        {
            sdkSetEvtArrayData(waOutput, r++, sdkGetEvtArrayData(waInput1, i));
            sdkSetEvtArrayData(waOutput, r++, sdkGetEvtArrayData(waInput2, i));
        }

        for ( i=input1Length; i < input2Length; i++ )
        {
            sdkSetEvtArrayData(waOutput, r++, sdkGetEvtArrayData(waInput2,i));
        }
    }
    else
    {
        for ( i=0; i < input2Length; i++ )
        {
            sdkSetEvtArrayData(waOutput, r++, sdkGetEvtArrayData(waInput1, i));
            sdkSetEvtArrayData(waOutput, r++, sdkGetEvtArrayData(waInput2, i));
        }

        for ( i=input2Length; i < input1Length; i++ )
        {
            sdkSetEvtArrayData(waOutput, r++, sdkGetEvtArrayData(waInput1,i));
        }
    }
}
<commit_msg>remove unnecessary code<commit_after>//-----------------------------------------------------------------------------
//@file
//	WeaveArray.cpp
//
//@author
//	ab5tract
//
//@brief
//	Implementation of the WeaveArray class.
//
//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
// includes
//-----------------------------------------------------------------------------
#include "WeaveArray.h"

//----------------------------------------------------------------------------
// create, general info and destroy methodes
//----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
// Create
void CreateModule (void* &pModule, AnsiCharPtr optionalString, LongBool Flag, MasterInfo* pMasterInfo, AnsiCharPtr optionalContent)
{
	pModule = new WeaveArray ();
}

//-----------------------------------------------------------------------------
// destroy
void DestroyModule (void* pModule)
{
    // cast is important to call the good destructor
	delete ((WeaveArray*)pModule);
}

//-----------------------------------------------------------------------------
// module description
void WeaveArray::onGetModuleInfo (MasterInfo* pMasterInfo, ModuleInfo* pModuleInfo)
{

	//identification of the module
	pModuleInfo->Name				= "weave array";
	pModuleInfo->Description		= "Weave Arrays";
	pModuleInfo->ModuleType         = mtSimple;
	pModuleInfo->BackColor          = sdkGetUsineColor(clDataModuleColor);
	pModuleInfo->NumberOfParams     = 3;
	pModuleInfo->Version			= "1.0";
	pModuleInfo->DontProcess		= TRUE;
}

//-----------------------------------------------------------------------------
// query system and init methodes
//-----------------------------------------------------------------------------
// query system not used

//void WeaveArray::onInitModule (MasterInfo* pMasterInfo, ModuleInfo* pModuleInfo)
//{
//}

//----------------------------------------------------------------------------
// parameters and process
//----------------------------------------------------------------------------

//-----------------------------------------------------------------------------
// Parameters description
void WeaveArray::onGetParamInfo (int ParamIndex, TParamInfo* pParamInfo)
{
	// all parameters declared in the module class
	switch (ParamIndex)
	{
	// waInput1
	case 0:
		pParamInfo->ParamType		= ptArray;
		pParamInfo->Caption			= "array 1";
		pParamInfo->IsInput			= TRUE;
		pParamInfo->IsOutput		= FALSE;
        pParamInfo->MinValue		= - FLT_MAX;
        pParamInfo->MaxValue		= FLT_MAX;
		pParamInfo->CallBackType	= ctImmediate;
		break;

	// waInput2
	case 1:
		pParamInfo->ParamType		= ptArray;
		pParamInfo->Caption			= "array 2";
		pParamInfo->IsInput			= TRUE;
		pParamInfo->IsOutput		= FALSE;
        pParamInfo->MinValue		= - FLT_MAX;
        pParamInfo->MaxValue		= FLT_MAX;
		pParamInfo->CallBackType	= ctImmediate;
		break;

	// waOutput
	case 2:
		pParamInfo->ParamType		= ptArray;
		pParamInfo->Caption			= "output";
		pParamInfo->IsInput			= FALSE;
		pParamInfo->IsOutput		= TRUE;
        pParamInfo->MinValue		= - FLT_MAX;
        pParamInfo->MaxValue		= FLT_MAX;
        pParamInfo->CallBackType	= ctImmediate;
		break;

	// default case
	default:
		break;
	}
}

//-----------------------------------------------------------------------------
// set the parameters events address
void WeaveArray::onSetEventAddress (int ParamIndex, UsineEventPtr pEvent)
{

	//Initialyse all events adress declared in your module class
	switch (ParamIndex)
    {
	// waInput1
	case 0:
		waInput1 = pEvent;
		break;

	// waInput2
	case 1:
		waInput2 = pEvent;
		break;

	// waOutput
	case 2:
		waOutput = pEvent;
		break;

	// default case
	default:
		break;

	}
}

//-----------------------------------------------------------------------------
// Parameters callback
void WeaveArray::onCallBack (UsineMessage* Message)
{
	try
	{
        if (Message->message == NOTIFY_MSG_USINE_CALLBACK)
        {
            int paramIndex = (int)Message->wParam;

            if((paramIndex == 0 || paramIndex == 1) && Message->lParam == MSG_CHANGE)
            {
                input1Length = sdkGetEvtSize(waInput1);
                input2Length = sdkGetEvtSize(waInput2);
                outputLength = input1Length + input2Length;
                writeOutput();
            }
        }
	}
	catch (...)
	{
		//sdkTraceErrorChar("error");
	}
}

void WeaveArray::writeOutput()
{
    sdkSetEvtSize(waOutput, outputLength);
    int i;
    int r = 0;

    if ( input1Length <= input2Length )
    {
        for ( i=0; i < input1Length; i++ )
        {
            sdkSetEvtArrayData(waOutput, r++, sdkGetEvtArrayData(waInput1, i));
            sdkSetEvtArrayData(waOutput, r++, sdkGetEvtArrayData(waInput2, i));
        }

        for ( i=input1Length; i < input2Length; i++ )
        {
            sdkSetEvtArrayData(waOutput, r++, sdkGetEvtArrayData(waInput2,i));
        }
    }
    else
    {
        for ( i=0; i < input2Length; i++ )
        {
            sdkSetEvtArrayData(waOutput, r++, sdkGetEvtArrayData(waInput1, i));
            sdkSetEvtArrayData(waOutput, r++, sdkGetEvtArrayData(waInput2, i));
        }

        for ( i=input2Length; i < input1Length; i++ )
        {
            sdkSetEvtArrayData(waOutput, r++, sdkGetEvtArrayData(waInput1,i));
        }
    }
}
<|endoftext|>