<commit_before>#define DEBUG 1
/**
 * File    : F.cpp
 * Author  : Kazune Takahashi
 * Created : 2/22/2020, 9:38:37 PM
 * Powered by Visual Studio Code
 */
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::multiprecision::cpp_int;
using ll = long long;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1000000007LL};
// constexpr ll MOD{998244353LL}; // be careful
constexpr ll MAX_SIZE{3000010LL};
// constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
void ch_max(T &left, T right)
{
  if (left < right)
  {
    left = right;
  }
}
template <typename T>
void ch_min(T &left, T right)
{
  if (left > right)
  {
    left = right;
  }
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
  ll x;
  Mint() : x{0LL} {}
  Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
  Mint operator-() const { return x ? MOD - x : 0; }
  Mint &operator+=(const Mint &a)
  {
    if ((x += a.x) >= MOD)
    {
      x -= MOD;
    }
    return *this;
  }
  Mint &operator-=(const Mint &a) { return *this += -a; }
  Mint &operator++() { return *this += 1; }
  Mint &operator++(int)
  {
    Mint tmp{*this};
    ++*this;
    return tmp;
  }
  Mint &operator--() { return *this -= 1; }
  Mint &operator--(int)
  {
    Mint tmp{*this};
    --*this;
    return tmp;
  }
  Mint &operator*=(const Mint &a)
  {
    (x *= a.x) %= MOD;
    return *this;
  }
  Mint &operator/=(const Mint &a)
  {
    Mint b{a};
    return *this *= b.power(MOD - 2);
  }
  Mint operator+(const Mint &a) const { return Mint(*this) += a; }
  Mint operator-(const Mint &a) const { return Mint(*this) -= a; }
  Mint operator*(const Mint &a) const { return Mint(*this) *= a; }
  Mint operator/(const Mint &a) const { return Mint(*this) /= a; }
  bool operator<(const Mint &a) const { return x < a.x; }
  bool operator<=(const Mint &a) const { return x <= a.x; }
  bool operator>(const Mint &a) const { return x > a.x; }
  bool operator>=(const Mint &a) const { return x >= a.x; }
  bool operator==(const Mint &a) const { return x == a.x; }
  bool operator!=(const Mint &a) const { return !(*this == a); }
  const Mint power(ll N)
  {
    if (N == 0)
    {
      return 1;
    }
    else if (N % 2 == 1)
    {
      return *this * power(N - 1);
    }
    else
    {
      Mint half = power(N / 2);
      return half * half;
    }
  }
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)
{
  return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)
{
  return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)
{
  return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs)
{
  return Mint<MOD>{lhs} / rhs;
}
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a)
{
  return stream >> a.x;
}
template <ll MOD>
ostream &operator<<(ostream &stream, const Mint<MOD> &a)
{
  return stream << a.x;
}
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
  vector<Mint<MOD>> inv, fact, factinv;
  Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
  {
    inv[1] = 1;
    for (auto i = 2LL; i < MAX_SIZE; i++)
    {
      inv[i] = (-inv[MOD % i]) * (MOD / i);
    }
    fact[0] = factinv[0] = 1;
    for (auto i = 1LL; i < MAX_SIZE; i++)
    {
      fact[i] = Mint<MOD>(i) * fact[i - 1];
      factinv[i] = inv[i] * factinv[i - 1];
    }
  }
  Mint<MOD> operator()(int n, int k)
  {
    if (n >= 0 && k >= 0 && n - k >= 0)
    {
      return fact[n] * factinv[k] * factinv[n - k];
    }
    return 0;
  }
  Mint<MOD> catalan(int x, int y)
  {
    return (*this)(x + y, y) - (*this)(x + y, y - 1);
  }
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
template <typename T>
T gcd(T x, T y) { return y ? gcd(y, x % y) : x; }
template <typename T>
T lcm(T x, T y) { return x / gcd(x, y) * y; }
// ----- for C++17 -----
template <typename T>
int popcount(T x) // C++20
{
  int ans{0};
  while (x != 0)
  {
    ans += x & 1;
    x >>= 1;
  }
  return ans;
}
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1000000000000000LL}; // or
// constexpr int infty{1'000'000'010};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
  cout << "Yes" << endl;
  exit(0);
}
void No()
{
  cout << "No" << endl;
  exit(0);
}
// ----- main() -----

ll k, q;
vector<ll> d;
vector<ll> e;
vector<ll> N, X, M;

ll solve(ll n, ll x, ll m)
{
  for (auto i = 0; i < k; ++i)
  {
    e[i] = d[i] % m;
#if DEBUG == 1
    cerr << "e[" << i << "] = " << e[i] << endl;
#endif
  }
  ll cnt{0};
  for (auto i = 0; i < k; ++i)
  {
    if (e[i] == 0)
    {
      ++cnt;
    }
  }
  ll S{accumulate(e.begin(), e.end(), 0LL)};
  ll T{n / k};
  ll U{n % k};
  ll A{S * T + x};
#if DEBUG == 1
  cerr << "T = " << T << endl;
  cerr << "U = " << U << endl;
  cerr << "A = " << A << endl;
#endif

  ll Y{cnt * T};
  for (auto i = 0; i < U; ++i)
  {
    A += e[i];
    if (e[i] == 0)
    {
      ++Y;
    }
  }
  ll Z{A / m};
#if DEBUG == 1
  cerr << "Y = " << Y << endl;
  cerr << "Z = " << Z << endl;
#endif
  return n - 1 - Y - Z;
}

int main()
{
  cin >> k >> q;
  d.resize(k);
  e.resize(k);
  for (auto i = 0; i < k; ++i)
  {
    cin >> d[i];
  }
  N.resize(q);
  X.resize(q);
  M.resize(q);
  for (auto i = 0; i < q; ++i)
  {
    cin >> N[i] >> X[i] >> M[i];
  }
  for (auto i = 0; i < q; ++i)
  {
    cout << solve(N[i], X[i], M[i]) << endl;
  }
}
<commit_msg>tried F.cpp to 'F'<commit_after>#define DEBUG 1
/**
 * File    : F.cpp
 * Author  : Kazune Takahashi
 * Created : 2/22/2020, 9:38:37 PM
 * Powered by Visual Studio Code
 */
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::multiprecision::cpp_int;
using ll = long long;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1000000007LL};
// constexpr ll MOD{998244353LL}; // be careful
constexpr ll MAX_SIZE{3000010LL};
// constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
void ch_max(T &left, T right)
{
  if (left < right)
  {
    left = right;
  }
}
template <typename T>
void ch_min(T &left, T right)
{
  if (left > right)
  {
    left = right;
  }
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
  ll x;
  Mint() : x{0LL} {}
  Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
  Mint operator-() const { return x ? MOD - x : 0; }
  Mint &operator+=(const Mint &a)
  {
    if ((x += a.x) >= MOD)
    {
      x -= MOD;
    }
    return *this;
  }
  Mint &operator-=(const Mint &a) { return *this += -a; }
  Mint &operator++() { return *this += 1; }
  Mint &operator++(int)
  {
    Mint tmp{*this};
    ++*this;
    return tmp;
  }
  Mint &operator--() { return *this -= 1; }
  Mint &operator--(int)
  {
    Mint tmp{*this};
    --*this;
    return tmp;
  }
  Mint &operator*=(const Mint &a)
  {
    (x *= a.x) %= MOD;
    return *this;
  }
  Mint &operator/=(const Mint &a)
  {
    Mint b{a};
    return *this *= b.power(MOD - 2);
  }
  Mint operator+(const Mint &a) const { return Mint(*this) += a; }
  Mint operator-(const Mint &a) const { return Mint(*this) -= a; }
  Mint operator*(const Mint &a) const { return Mint(*this) *= a; }
  Mint operator/(const Mint &a) const { return Mint(*this) /= a; }
  bool operator<(const Mint &a) const { return x < a.x; }
  bool operator<=(const Mint &a) const { return x <= a.x; }
  bool operator>(const Mint &a) const { return x > a.x; }
  bool operator>=(const Mint &a) const { return x >= a.x; }
  bool operator==(const Mint &a) const { return x == a.x; }
  bool operator!=(const Mint &a) const { return !(*this == a); }
  const Mint power(ll N)
  {
    if (N == 0)
    {
      return 1;
    }
    else if (N % 2 == 1)
    {
      return *this * power(N - 1);
    }
    else
    {
      Mint half = power(N / 2);
      return half * half;
    }
  }
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs)
{
  return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)
{
  return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)
{
  return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs)
{
  return Mint<MOD>{lhs} / rhs;
}
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a)
{
  return stream >> a.x;
}
template <ll MOD>
ostream &operator<<(ostream &stream, const Mint<MOD> &a)
{
  return stream << a.x;
}
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
  vector<Mint<MOD>> inv, fact, factinv;
  Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
  {
    inv[1] = 1;
    for (auto i = 2LL; i < MAX_SIZE; i++)
    {
      inv[i] = (-inv[MOD % i]) * (MOD / i);
    }
    fact[0] = factinv[0] = 1;
    for (auto i = 1LL; i < MAX_SIZE; i++)
    {
      fact[i] = Mint<MOD>(i) * fact[i - 1];
      factinv[i] = inv[i] * factinv[i - 1];
    }
  }
  Mint<MOD> operator()(int n, int k)
  {
    if (n >= 0 && k >= 0 && n - k >= 0)
    {
      return fact[n] * factinv[k] * factinv[n - k];
    }
    return 0;
  }
  Mint<MOD> catalan(int x, int y)
  {
    return (*this)(x + y, y) - (*this)(x + y, y - 1);
  }
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
template <typename T>
T gcd(T x, T y) { return y ? gcd(y, x % y) : x; }
template <typename T>
T lcm(T x, T y) { return x / gcd(x, y) * y; }
// ----- for C++17 -----
template <typename T>
int popcount(T x) // C++20
{
  int ans{0};
  while (x != 0)
  {
    ans += x & 1;
    x >>= 1;
  }
  return ans;
}
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1000000000000000LL}; // or
// constexpr int infty{1'000'000'010};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
  cout << "Yes" << endl;
  exit(0);
}
void No()
{
  cout << "No" << endl;
  exit(0);
}
// ----- main() -----

ll k, q;
vector<ll> d;
vector<ll> e;
vector<ll> N, X, M;

ll solve(ll n, ll x, ll m)
{
  for (auto i = 0; i < k; ++i)
  {
    e[i] = d[i] % m;
#if DEBUG == 1
    cerr << "e[" << i << "] = " << e[i] << endl;
#endif
  }
  ll cnt{0};
  for (auto i = 0; i < k; ++i)
  {
    if (e[i] == 0)
    {
      ++cnt;
    }
  }
  ll S{accumulate(e.begin(), e.end(), 0LL)};
  ll T{(n - 1) / k};
  ll U{(n - 1) % k};
  ll A{S * T + x};
#if DEBUG == 1
  cerr << "T = " << T << endl;
  cerr << "U = " << U << endl;
  cerr << "A = " << A << endl;
#endif

  ll Y{cnt * T};
  for (auto i = 0; i < U; ++i)
  {
    A += e[i];
    if (e[i] == 0)
    {
      ++Y;
    }
  }
  ll Z{A / m};
#if DEBUG == 1
  cerr << "Y = " << Y << endl;
  cerr << "Z = " << Z << endl;
#endif
  return n - 1 - Y - Z;
}

int main()
{
  cin >> k >> q;
  d.resize(k);
  e.resize(k);
  for (auto i = 0; i < k; ++i)
  {
    cin >> d[i];
  }
  N.resize(q);
  X.resize(q);
  M.resize(q);
  for (auto i = 0; i < q; ++i)
  {
    cin >> N[i] >> X[i] >> M[i];
  }
  for (auto i = 0; i < q; ++i)
  {
    cout << solve(N[i], X[i], M[i]) << endl;
  }
}
<|endoftext|>


<commit_before>#include "master.hpp"

namespace factor
{

void factor_vm::dispatch_signal_handler(cell *sp, cell *pc, cell handler)
{
	if (!code->seg->in_segment_p(*pc) || *sp < ctx->callstack_seg->start + stack_reserved)
	{
		/* Fault came from foreign code or a callstack overflow, or we don't
		have enough callstack room to try the resumable handler. Cut the
		callstack down to the shallowest Factor stack frame that leaves room for
		the signal handler to do its thing, and launch the handler without going
		through the resumable subprimitive. */
		signal_resumable = false;
		void *frame_top = (void*)ctx->callstack_top;

		while(frame_top < ctx->callstack_bottom
			&& (cell)frame_top < ctx->callstack_seg->start + stack_reserved)
		{
			frame_top = frame_predecessor(frame_top);
		}

		*sp = (cell)frame_top;
		ctx->callstack_top = frame_top;
		*pc = handler;
	} else {
		signal_resumable = true;
		// Fault came from Factor, and we've got a good callstack. Route the signal
		// handler through the resumable signal handler subprimitive.
		cell offset = *sp % 16;

		signal_handler_addr = handler;
		tagged<word> handler_word = tagged<word>(special_objects[SIGNAL_HANDLER_WORD]);

		/* True stack frames are always 16-byte aligned. Leaf procedures
		that don't create a stack frame will be out of alignment by sizeof(cell)
		bytes. */
		/* On architectures with a link register we would have to check for leafness
		by matching the PC to a word. We should also use FRAME_RETURN_ADDRESS instead
		of assuming the stack pointer is the right place to put the resume address. */
		if (offset == 0)
		{
			cell newsp = *sp - sizeof(cell);
			*sp = newsp;
			*(cell*)newsp = *pc;
		}
		else if (offset == 16 - sizeof(cell))
		{
			// Make a fake frame for the leaf procedure
			code_block *leaf_block = code->code_block_for_address(*pc);
			FACTOR_ASSERT(leaf_block != NULL);

			cell newsp = *sp - LEAF_FRAME_SIZE;
			*(cell*)(newsp + 3*sizeof(cell)) = 4*sizeof(cell);
			*(cell*)(newsp + 2*sizeof(cell)) = (cell)leaf_block->entry_point();
			*(cell*) newsp                   = *pc;
			*sp = newsp;
			handler_word = tagged<word>(special_objects[LEAF_SIGNAL_HANDLER_WORD]);
		}
		else
			FACTOR_ASSERT(false);

		*pc = (cell)handler_word->entry_point;
	}
}

}
<commit_msg>vm: don't scribble memory handling leaf signals<commit_after>#include "master.hpp"

namespace factor
{

void factor_vm::dispatch_signal_handler(cell *sp, cell *pc, cell handler)
{
	if (!code->seg->in_segment_p(*pc) || *sp < ctx->callstack_seg->start + stack_reserved)
	{
		/* Fault came from foreign code or a callstack overflow, or we don't
		have enough callstack room to try the resumable handler. Cut the
		callstack down to the shallowest Factor stack frame that leaves room for
		the signal handler to do its thing, and launch the handler without going
		through the resumable subprimitive. */
		signal_resumable = false;
		void *frame_top = (void*)ctx->callstack_top;

		while(frame_top < ctx->callstack_bottom
			&& (cell)frame_top < ctx->callstack_seg->start + stack_reserved)
		{
			frame_top = frame_predecessor(frame_top);
		}

		*sp = (cell)frame_top;
		ctx->callstack_top = frame_top;
		*pc = handler;
	} else {
		signal_resumable = true;
		// Fault came from Factor, and we've got a good callstack. Route the signal
		// handler through the resumable signal handler subprimitive.
		cell offset = *sp % 16;

		signal_handler_addr = handler;
		tagged<word> handler_word = tagged<word>(special_objects[SIGNAL_HANDLER_WORD]);

		/* True stack frames are always 16-byte aligned. Leaf procedures
		that don't create a stack frame will be out of alignment by sizeof(cell)
		bytes. */
		/* On architectures with a link register we would have to check for leafness
		by matching the PC to a word. We should also use FRAME_RETURN_ADDRESS instead
		of assuming the stack pointer is the right place to put the resume address. */
		if (offset == 0)
		{
			cell newsp = *sp - sizeof(cell);
			*sp = newsp;
			*(cell*)newsp = *pc;
		}
		else if (offset == 16 - sizeof(cell))
		{
			// Make a fake frame for the leaf procedure
			FACTOR_ASSERT(code->code_block_for_address(*pc) != NULL);

			cell newsp = *sp - LEAF_FRAME_SIZE;
			*(cell*)newsp = *pc;
			*sp = newsp;
			handler_word = tagged<word>(special_objects[LEAF_SIGNAL_HANDLER_WORD]);
		}
		else
			FACTOR_ASSERT(false);

		*pc = (cell)handler_word->entry_point;
	}
}

}
<|endoftext|>


<commit_before>/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */

/*
 *  Main authors:
 *     Guido Tack <guido.tack@monash.edu>
 */

/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include <iostream>
#include <fstream>

#include <minizinc/model.hh>
#include <minizinc/parser.hh>
#include <minizinc/prettyprinter.hh>
#include <minizinc/typecheck.hh>
#include <minizinc/exception.hh>

#include <minizinc/flatten.hh>
#include <minizinc/optimize.hh>
#include <minizinc/builtins.hh>

using namespace MiniZinc;
using namespace std;

int main(int argc, char** argv) {
  int i=1;
  string filename;
  vector<string> datafiles;
  vector<string> includePaths;
  bool flag_ignoreStdlib = false;
  bool flag_typecheck = true;
  bool flag_eval = true;
  bool flag_output = true;
  bool flag_outputFundecls = false;
  bool flag_verbose = false;
  bool flag_allSolutions = false;
  bool flag_newfzn = false;
  bool flag_free_search = false;
  bool flag_optimize = true;
  int nbThreads = 1;
  if (argc < 2)
    goto error;

  GC::init();

  for (;;) {
    if (string(argv[i])==string("-I")) {
      i++;
      if (i==argc) {
        goto error;
      }
      includePaths.push_back(argv[i]+string("/"));
    } else if (string(argv[i])==string("--ignore-stdlib")) {
      flag_ignoreStdlib = true;
    } else if (string(argv[i])==string("--no-output")) {
      flag_output = false;
    } else if (string(argv[i])==string("--no-fundecl-output")) {
      flag_outputFundecls = false;
    } else if (string(argv[i])==string("--no-typecheck")) {
      flag_typecheck = false; flag_eval=false;
    } else if (string(argv[i])==string("--no-eval")) {
      flag_eval = false;
    } else if (string(argv[i])==string("--verbose")) {
      flag_verbose = true;
    } else if (string(argv[i])==string("--newfzn")) {
      flag_newfzn = true;
    } else if (string(argv[i])==string("--no-optimize")) {
      flag_optimize = false;
    } else if (string(argv[i])==string("-a")) {
      flag_allSolutions = true;
    } else if (string(argv[i])==string("-f")) {
      flag_free_search = true;
    } else if (string(argv[i])==string("-p")) {
      i++;
      nbThreads = atoi(argv[i]);
    } else {
      break;
    }
    i++;
  }

  if (i==argc) {
    goto error;
  }
  filename = argv[i++];

  while (i<argc)
    datafiles.push_back(argv[i++]);

  {
    if (Model* m = parse(filename, datafiles, includePaths, flag_ignoreStdlib,
                         std::cerr)) {
      try {
        if (flag_verbose)
          std::cerr << "parsing " << filename << std::endl;
        if (flag_typecheck) {
          MiniZinc::typecheck(m);
          MiniZinc::registerBuiltins(m);
          Model* flat = flatten(m);
          if (flag_optimize)
            optimize(flat);
          if (!flag_newfzn)
            oldflatzinc(flat);
          Printer p;
          p.print(flat,std::cout);
        }
      } catch (LocationException& e) {
        std::cerr << e.what() << ": " << e.msg() << std::endl;
        std::cerr << e.loc() << std::endl;
        exit(EXIT_FAILURE);
      } catch (Exception& e) {
        std::cerr << e.what() << ": " << e.msg() << std::endl;
        exit(EXIT_FAILURE);
      }
      delete m;
    }
  }
  return 0;

error:
  std::cerr << "Usage: "<< argv[0]
            << " [--ignore-stdlib] [-I <include path>] <model>.mzn [<data>.dzn ...]" << std::endl;
  exit(EXIT_FAILURE);
}
<commit_msg>Add options to usage instructions<commit_after>/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */

/*
 *  Main authors:
 *     Guido Tack <guido.tack@monash.edu>
 */

/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include <iostream>
#include <fstream>

#include <minizinc/model.hh>
#include <minizinc/parser.hh>
#include <minizinc/prettyprinter.hh>
#include <minizinc/typecheck.hh>
#include <minizinc/exception.hh>

#include <minizinc/flatten.hh>
#include <minizinc/optimize.hh>
#include <minizinc/builtins.hh>

using namespace MiniZinc;
using namespace std;

int main(int argc, char** argv) {
  int i=1;
  string filename;
  vector<string> datafiles;
  vector<string> includePaths;
  bool flag_ignoreStdlib = false;
  bool flag_typecheck = true;
  bool flag_eval = true;
  bool flag_output = true;
  bool flag_outputFundecls = false;
  bool flag_verbose = false;
  bool flag_allSolutions = false;
  bool flag_newfzn = false;
  bool flag_free_search = false;
  bool flag_optimize = true;
  int nbThreads = 1;
  if (argc < 2)
    goto error;

  GC::init();

  for (;;) {
    if (string(argv[i])==string("-I")) {
      i++;
      if (i==argc) {
        goto error;
      }
      includePaths.push_back(argv[i]+string("/"));
    } else if (string(argv[i])==string("--ignore-stdlib")) {
      flag_ignoreStdlib = true;
    } else if (string(argv[i])==string("--no-output")) {
      flag_output = false;
    } else if (string(argv[i])==string("--no-fundecl-output")) {
      flag_outputFundecls = false;
    } else if (string(argv[i])==string("--no-typecheck")) {
      flag_typecheck = false; flag_eval=false;
    } else if (string(argv[i])==string("--no-eval")) {
      flag_eval = false;
    } else if (string(argv[i])==string("--verbose")) {
      flag_verbose = true;
    } else if (string(argv[i])==string("--newfzn")) {
      flag_newfzn = true;
    } else if (string(argv[i])==string("--no-optimize")) {
      flag_optimize = false;
    } else if (string(argv[i])==string("-a")) {
      flag_allSolutions = true;
    } else if (string(argv[i])==string("-f")) {
      flag_free_search = true;
    } else if (string(argv[i])==string("-p")) {
      i++;
      nbThreads = atoi(argv[i]);
    } else {
      break;
    }
    i++;
  }

  if (i==argc) {
    goto error;
  }
  filename = argv[i++];

  while (i<argc)
    datafiles.push_back(argv[i++]);

  {
    if (Model* m = parse(filename, datafiles, includePaths, flag_ignoreStdlib,
                         std::cerr)) {
      try {
        if (flag_verbose)
          std::cerr << "parsing " << filename << std::endl;
        if (flag_typecheck) {
          MiniZinc::typecheck(m);
          MiniZinc::registerBuiltins(m);
          Model* flat = flatten(m);
          if (flag_optimize)
            optimize(flat);

          if (flag_output) {
            if (!flag_newfzn)
              oldflatzinc(flat);
            Printer p;
            p.print(flat,std::cout);
          }
        }
      } catch (LocationException& e) {
        std::cerr << e.what() << ": " << e.msg() << std::endl;
        std::cerr << e.loc() << std::endl;
        exit(EXIT_FAILURE);
      } catch (Exception& e) {
        std::cerr << e.what() << ": " << e.msg() << std::endl;
        exit(EXIT_FAILURE);
      }
      delete m;
    }
  }
  return 0;

error:
  std::cerr << "Usage: "<< argv[0]
            << " [<options>] [-I <include path>] <model>.mzn [<data>.dzn ...]" << std::endl
            << std::endl
            << "Options:" << std::endl
            << "\t--ignore-stdlib\tIgnore the standard libraries stdlib.mzn and builtins.mzn" << std::endl
            << "\t--newfzn\tOutput in the new FlatZinc format" << std::endl
            << "\t--verbose\tPrint progress statements" << std::endl
            << "\t--no-typecheck\tDo not typecheck (implies --no-eval)" << std::endl
            << "\t--no-eval\tDo not evaluate" << std::endl
            << "\t--no-optimize\tDo not optimize the FlatZinc (may speed up large instances)" << std::endl
            << "\t--no-output\tDo not print the output" << std::endl;

  exit(EXIT_FAILURE);
}
<|endoftext|>


<commit_before>#if defined TARGET_HAS_ThirdPartyUSBFirstAmpAPI

#include "ovasCDriverBrainProductsVAmp.h"
#include "ovasCConfigurationBrainProductsVAmp.h"
#include "ovasCHeaderBrainProductsVAmp.h"

#include <system/Time.h>
#include <windows.h>

#include <cstdlib>
#include <cstring>

#include <iostream>
#include <vector>

using namespace OpenViBEAcquisitionServer;
using namespace OpenViBE;
using namespace OpenViBE::Kernel;
using namespace std;

#define boolean OpenViBE::boolean

//___________________________________________________________________//
//                                                                   //

CDriverBrainProductsVAmp::CDriverBrainProductsVAmp(IDriverContext& rDriverContext)
	:IDriver(rDriverContext)
	,m_pCallback(NULL)
	,m_ui32SampleCountPerSentBlock(0)
	,m_ui32TotalSampleCount(0)
	,m_pSample(NULL)
	,m_bFirstStart(false)
{
	m_oHeader.setChannelCount(16);
	m_oHeader.setSamplingFrequency(2000);

	t_faDataModeSettings l_tFastModeSettings;
	l_tFastModeSettings.Mode20kHz4Channels.ChannelsPos[0] = 7;
	l_tFastModeSettings.Mode20kHz4Channels.ChannelsNeg[0] = -1;
	l_tFastModeSettings.Mode20kHz4Channels.ChannelsPos[1] = 8;
	l_tFastModeSettings.Mode20kHz4Channels.ChannelsNeg[1] = -1;
	l_tFastModeSettings.Mode20kHz4Channels.ChannelsPos[2] = 9;
	l_tFastModeSettings.Mode20kHz4Channels.ChannelsNeg[2] = -1;
	l_tFastModeSettings.Mode20kHz4Channels.ChannelsPos[3] = 10;
	l_tFastModeSettings.Mode20kHz4Channels.ChannelsNeg[3] = -1;

	m_oHeader.setFastModeSettings(l_tFastModeSettings);
	m_oHeader.setDataMode(dmNormal);

	m_oHeader.setDeviceId(FA_ID_INVALID);
}

CDriverBrainProductsVAmp::~CDriverBrainProductsVAmp(void)
{
}

const char* CDriverBrainProductsVAmp::getName(void)
{
	return "Brain Products V-Amp";
}

//___________________________________________________________________//
//                                                                   //

boolean CDriverBrainProductsVAmp::initialize(
	const uint32 ui32SampleCountPerSentBlock,
	IDriverCallback& rCallback)
{
	m_rDriverContext.getLogManager() << LogLevel_Trace << "INIT called.\n";
	if(m_rDriverContext.isConnected())
	{
		m_rDriverContext.getLogManager() << LogLevel_Error << "[INIT] VAmp Driver: Driver already initialized.\n";
		return false;
	}

	if(!m_oHeader.isChannelCountSet()
	 ||!m_oHeader.isSamplingFrequencySet())
	{
		m_rDriverContext.getLogManager() << LogLevel_Error << "[INIT] VAmp Driver: Channel count or frequency not set.\n";
		return false;
	}

	// Builds up a buffer to store acquired samples. This buffer will be sent to the acquisition server later.
	m_pSample=new float32[m_oHeader.getChannelCount()*ui32SampleCountPerSentBlock];
	if(!m_pSample)
	{
		delete [] m_pSample;
		m_pSample=NULL;
		m_rDriverContext.getLogManager() << LogLevel_Error << "[INIT] VAmp Driver: Samples allocation failed.\n";
		return false;
	}

	int32 l_i32DeviceId = m_oHeader.getDeviceId();
	//__________________________________
	// Hardware initialization

	// if no device selected with the properties dialog
	// we take the last device connected
	if(l_i32DeviceId == FA_ID_INVALID)
	{
		// We try to get the last opened device,
		uint32 l_uint32LastOpenedDeviceID = faGetCount(); // Get the last opened Device id.

		if (l_uint32LastOpenedDeviceID == FA_ID_INVALID) // failed
		{
			m_rDriverContext.getLogManager() << LogLevel_Error << "[INIT] VAmp Driver: faGetCount failed to get last opened device.\n";
			return false;
		}

		l_i32DeviceId = faGetId(l_uint32LastOpenedDeviceID -1);
		m_oHeader.setDeviceId(l_i32DeviceId);
	}

	if (l_i32DeviceId != FA_ID_INVALID)
	{
		m_rDriverContext.getLogManager() << LogLevel_Trace << "[INIT] VAmp Driver: Active device ID(" << m_oHeader.getDeviceId() << ").\n";
	}
	else
	{
		m_rDriverContext.getLogManager() << LogLevel_Error << "[INIT] VAmp Driver: No device connected !\n";
		return false;
	}

	// Open the device.
	uint32 l_uint32OpenReturn = faOpen(l_i32DeviceId);
	if (l_uint32OpenReturn != FA_ERR_OK)
	{
		m_rDriverContext.getLogManager() << LogLevel_Error << "[INIT] VAmp Driver: faOpen(" << l_i32DeviceId << ") FAILED(" << l_uint32OpenReturn << ").\n";
		return false;
	}

    if(m_oHeader.getDataMode() == dm20kHz4Channels)
    {
        faSetDataMode(l_i32DeviceId, dm20kHz4Channels, &(m_oHeader.getFastModeSettings()));
    }
    else
    {
        faSetDataMode(l_i32DeviceId, dmNormal, NULL);
    }

    uint32 l_uint32ErrorCode = faStart(l_i32DeviceId);

    if (l_uint32ErrorCode != FA_ERR_OK)
    {
        m_rDriverContext.getLogManager() << LogLevel_Error << "[START] VAmp Driver: faStart FAILED(" << l_uint32ErrorCode << "). Closing device.\n";
        faClose(l_i32DeviceId);
        return false;
    }

	//__________________________________
	// Saves parameters
	m_pCallback=&rCallback;
	m_ui32SampleCountPerSentBlock=ui32SampleCountPerSentBlock;

	return true;
}

boolean CDriverBrainProductsVAmp::start(void)
{
	m_rDriverContext.getLogManager() << LogLevel_Trace << "START called.\n";
	if(!m_rDriverContext.isConnected())
	{
		return false;
	}

	if(m_rDriverContext.isStarted())
	{
		return false;
	}

	m_bFirstStart = true;
	//The bonus...
	HBITMAP l_bitmap = (HBITMAP) LoadImage(NULL, "../share/openvibe-applications/acquisition-server/vamp.bmp",IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
	if(l_bitmap == NULL || faSetBitmap(m_oHeader.getDeviceId(),l_bitmap ) != FA_ERR_OK)
	{
		m_rDriverContext.getLogManager() << LogLevel_Warning << "[START] VAmp Driver: BMP load failed.\n";
	}

	return true;

}

boolean CDriverBrainProductsVAmp::loop(void)
{
	if(!m_rDriverContext.isConnected())
	{
		return false;
	}

    t_faDataModel16 l_DataBufferNormalMode; // buffer for the next block in normal mode
    uint32 l_uint32ReadLengthNormalMode = sizeof(t_faDataModel16);

    t_faDataFormatMode20kHz l_DataBufferFastMode; // buffer for fast mode acquisition
    uint32 l_uint32ReadLengthFastMode = sizeof(t_faDataFormatMode20kHz);

    int32 l_i32DeviceId = m_oHeader.getDeviceId();

	if(m_rDriverContext.isStarted())
	{
		//uint32 l_i32Timeout = 1000; // 1 second timeout
		uint32 l_i32ReceivedSamples=0;
		//uint32 l_ui32StartTime=System::Time::getTime();

#if DEBUG
		uint32 l_uint32ReadErrorCount = 0;
		uint32 l_uint32ReadSuccessCount = 0;
		uint32 l_uint32ReadZeroCount = 0;
#endif
		//------------------------------------------
 		if(m_bFirstStart)
 		{
 			int32 l_i32ReturnValue = 1;
			int32 l_i32BufferCount = 0;
 			while(l_i32ReturnValue > 0)
 			{
 				if(m_oHeader.getDataMode() == dmNormal)
 				{
 					l_i32ReturnValue = faGetData(l_i32DeviceId, &l_DataBufferNormalMode, l_uint32ReadLengthNormalMode);
 				}

 				if(m_oHeader.getDataMode() == dm20kHz4Channels)
 				{
 					l_i32ReturnValue = faGetData(l_i32DeviceId, &l_DataBufferFastMode, l_uint32ReadLengthFastMode);
 				}
				if(l_i32ReturnValue>0) l_i32BufferCount+=l_i32ReturnValue;
 			}
			m_rDriverContext.getLogManager() << LogLevel_Trace << "[LOOP] cleaning buffer ("<<l_i32BufferCount<<" bytes). \n";
 			m_bFirstStart = false;
 		}

		while(l_i32ReceivedSamples < m_ui32SampleCountPerSentBlock /*&& System::Time::getTime()-l_ui32StartTime < l_i32Timeout*/)
		{
			// we need to "getData" with the right output structure according to acquisition mode

			int32 l_i32ReturnLength = 0;
			if(m_oHeader.getDataMode() == dmNormal)
			{
				l_i32ReturnLength = faGetData(l_i32DeviceId, &l_DataBufferNormalMode, l_uint32ReadLengthNormalMode);
			}

			if(m_oHeader.getDataMode() == dm20kHz4Channels)
			{
				l_i32ReturnLength = faGetData(l_i32DeviceId, &l_DataBufferFastMode, l_uint32ReadLengthFastMode);
			}

			if(l_i32ReturnLength > 0)
			{
#if DEBUG
				l_uint32ReadSuccessCount++;
#endif
				//we just received one set of samples from device, one sample per channel
				if(m_oHeader.getDataMode() == dmNormal)
				{
					for (uint32 i=0; i < m_oHeader.getChannelCount(); i++)
					{
						m_pSample[i*m_ui32SampleCountPerSentBlock+l_i32ReceivedSamples] = (float32)(l_DataBufferNormalMode.Main[i]*m_oHeader.getChannelGain(i));
					}
				}
				// 4 pairs, not related to channel count
				if(m_oHeader.getDataMode() == dm20kHz4Channels)
				{
					for (uint32 i=0; i < m_oHeader.getChannelCount(); i++) // channel count returns the pair count is that case
					{
						m_pSample[i*m_ui32SampleCountPerSentBlock+l_i32ReceivedSamples] = (float32)(l_DataBufferFastMode.Main[i]*m_oHeader.getChannelGain(i));
					}
				}

				l_i32ReceivedSamples++;
			}
#if DEBUG
			if(l_i32ReturnLength < 0)
			{

				l_uint32ReadErrorCount++;

			}
			if(l_i32ReturnLength == 0)
			{
				l_uint32ReadZeroCount++;

			}
#endif
		}// while received < m_ui32SampleCountPerSentBlock
#if DEBUG
        m_rDriverContext.getLogManager() << LogLevel_Debug << "[LOOP] VAmp Driver: stats for the current block : Success="<<l_uint32ReadSuccessCount<<" Error="<<l_uint32ReadErrorCount<<" Zero="<<l_uint32ReadZeroCount<<"\n";
#endif
		//____________________________

		// no stimulations received from hardware, the set is empty
		CStimulationSet l_oStimulationSet;

		m_pCallback->setSamples(m_pSample);

		m_pCallback->setStimulationSet(l_oStimulationSet);
	}

	return true;
}

boolean CDriverBrainProductsVAmp::stop(void)
{

	m_rDriverContext.getLogManager() << LogLevel_Trace << "STOP called.\n";
	if(!m_rDriverContext.isConnected())
	{
		return false;
	}

	if(!m_rDriverContext.isStarted())
	{
		return false;
	}

	m_bFirstStart = false;

	return true;
}

boolean CDriverBrainProductsVAmp::uninitialize(void)
{
	if(!m_rDriverContext.isConnected())
	{
		return false;
	}

	if(m_rDriverContext.isStarted())
	{
		return false;
	}

	uint32 l_uint32ErrorCode = faStop(m_oHeader.getDeviceId());
	if (l_uint32ErrorCode != FA_ERR_OK)
	{
		m_rDriverContext.getLogManager() << LogLevel_Error << "[STOP] VAmp Driver: faStop FAILED(" << l_uint32ErrorCode << ").\n";
		faClose(m_oHeader.getDeviceId());
		return false;
	}

	m_rDriverContext.getLogManager() << LogLevel_Trace << "Uninitialize called. Closing the device.\n";

	l_uint32ErrorCode = faClose(m_oHeader.getDeviceId());
	if (l_uint32ErrorCode != FA_ERR_OK)
	{
		m_rDriverContext.getLogManager() << LogLevel_Error << "[UINIT] VAmp Driver: faClose FAILED(" << l_uint32ErrorCode << ").\n";
		faClose(m_oHeader.getDeviceId());
		return false;
	}
	delete [] m_pSample;
	m_pSample=NULL;
	m_pCallback=NULL;

	return true;
}

//___________________________________________________________________//
//                                                                   //

boolean CDriverBrainProductsVAmp::isConfigurable(void)
{
	return true;
}

boolean CDriverBrainProductsVAmp::configure(void)
{
	CConfigurationBrainProductsVAmp m_oConfiguration(m_rDriverContext, "../share/openvibe-applications/acquisition-server/interface-BrainProducts-VAmp.glade", &m_oHeader); // the specific header is passed into the specific configuration

	if(!m_oConfiguration.configure(*(m_oHeader.getBasicHeader()))) // the basic configure will use the basic header
	{
		return false;
	}

	if(m_oHeader.getDataMode() == dm20kHz4Channels)
	{
		m_rDriverContext.getLogManager() << LogLevel_Trace << "Pair names :\n";
		for(uint32 i = 0; i < m_oHeader.getPairCount();i++)
		{
			m_rDriverContext.getLogManager() << LogLevel_Trace << "  Pair " << i << " > " << m_oHeader.getPairName(i) << "\n";
		}
	}

	return true;
}

#endif // TARGET_HAS_ThirdPartyUSBFirstAmpAPI
<commit_msg><commit_after>#if defined TARGET_HAS_ThirdPartyUSBFirstAmpAPI

#include "ovasCDriverBrainProductsVAmp.h"
#include "ovasCConfigurationBrainProductsVAmp.h"
#include "ovasCHeaderBrainProductsVAmp.h"

#include <system/Time.h>
#include <windows.h>

#include <cstdlib>
#include <cstring>

#include <iostream>
#include <vector>

using namespace OpenViBEAcquisitionServer;
using namespace OpenViBE;
using namespace OpenViBE::Kernel;
using namespace std;

#define boolean OpenViBE::boolean

//___________________________________________________________________//
//                                                                   //

CDriverBrainProductsVAmp::CDriverBrainProductsVAmp(IDriverContext& rDriverContext)
	:IDriver(rDriverContext)
	,m_pCallback(NULL)
	,m_ui32SampleCountPerSentBlock(0)
	,m_ui32TotalSampleCount(0)
	,m_pSample(NULL)
	,m_bFirstStart(false)
{
	m_oHeader.setChannelCount(16);
	m_oHeader.setSamplingFrequency(2000);

	t_faDataModeSettings l_tFastModeSettings;
	l_tFastModeSettings.Mode20kHz4Channels.ChannelsPos[0] = 7;
	l_tFastModeSettings.Mode20kHz4Channels.ChannelsNeg[0] = -1;
	l_tFastModeSettings.Mode20kHz4Channels.ChannelsPos[1] = 8;
	l_tFastModeSettings.Mode20kHz4Channels.ChannelsNeg[1] = -1;
	l_tFastModeSettings.Mode20kHz4Channels.ChannelsPos[2] = 9;
	l_tFastModeSettings.Mode20kHz4Channels.ChannelsNeg[2] = -1;
	l_tFastModeSettings.Mode20kHz4Channels.ChannelsPos[3] = 10;
	l_tFastModeSettings.Mode20kHz4Channels.ChannelsNeg[3] = -1;

	m_oHeader.setFastModeSettings(l_tFastModeSettings);
	m_oHeader.setDataMode(dmNormal);

	m_oHeader.setDeviceId(FA_ID_INVALID);
}

CDriverBrainProductsVAmp::~CDriverBrainProductsVAmp(void)
{
}

const char* CDriverBrainProductsVAmp::getName(void)
{
	return "Brain Products V-Amp";
}

//___________________________________________________________________//
//                                                                   //

boolean CDriverBrainProductsVAmp::initialize(
	const uint32 ui32SampleCountPerSentBlock,
	IDriverCallback& rCallback)
{
	m_rDriverContext.getLogManager() << LogLevel_Trace << "INIT called.\n";
	if(m_rDriverContext.isConnected())
	{
		m_rDriverContext.getLogManager() << LogLevel_Error << "[INIT] VAmp Driver: Driver already initialized.\n";
		return false;
	}

	if(!m_oHeader.isChannelCountSet()
	 ||!m_oHeader.isSamplingFrequencySet())
	{
		m_rDriverContext.getLogManager() << LogLevel_Error << "[INIT] VAmp Driver: Channel count or frequency not set.\n";
		return false;
	}

	// Builds up a buffer to store acquired samples. This buffer will be sent to the acquisition server later.
	m_pSample=new float32[m_oHeader.getChannelCount()*ui32SampleCountPerSentBlock];
	if(!m_pSample)
	{
		delete [] m_pSample;
		m_pSample=NULL;
		m_rDriverContext.getLogManager() << LogLevel_Error << "[INIT] VAmp Driver: Samples allocation failed.\n";
		return false;
	}

	int32 l_i32DeviceId = m_oHeader.getDeviceId();
	//__________________________________
	// Hardware initialization

	// if no device selected with the properties dialog
	// we take the last device connected
	if(l_i32DeviceId == FA_ID_INVALID)
	{
		// We try to get the last opened device,
		uint32 l_uint32LastOpenedDeviceID = faGetCount(); // Get the last opened Device id.

		if (l_uint32LastOpenedDeviceID == FA_ID_INVALID) // failed
		{
			m_rDriverContext.getLogManager() << LogLevel_Error << "[INIT] VAmp Driver: faGetCount failed to get last opened device.\n";
			return false;
		}

		l_i32DeviceId = faGetId(l_uint32LastOpenedDeviceID -1);
		m_oHeader.setDeviceId(l_i32DeviceId);
	}

	if (l_i32DeviceId != FA_ID_INVALID)
	{
		m_rDriverContext.getLogManager() << LogLevel_Trace << "[INIT] VAmp Driver: Active device ID(" << m_oHeader.getDeviceId() << ").\n";
	}
	else
	{
		m_rDriverContext.getLogManager() << LogLevel_Error << "[INIT] VAmp Driver: No device connected !\n";
		return false;
	}

	// Open the device.
	uint32 l_uint32OpenReturn = faOpen(l_i32DeviceId);
	if (l_uint32OpenReturn != FA_ERR_OK)
	{
		m_rDriverContext.getLogManager() << LogLevel_Error << "[INIT] VAmp Driver: faOpen(" << l_i32DeviceId << ") FAILED(" << l_uint32OpenReturn << ").\n";
		return false;
	}

    if(m_oHeader.getDataMode() == dm20kHz4Channels)
    {
        faSetDataMode(l_i32DeviceId, dm20kHz4Channels, &(m_oHeader.getFastModeSettings()));
    }
    else
    {
        faSetDataMode(l_i32DeviceId, dmNormal, NULL);
    }

    uint32 l_uint32ErrorCode = faStart(l_i32DeviceId);

    if (l_uint32ErrorCode != FA_ERR_OK)
    {
        m_rDriverContext.getLogManager() << LogLevel_Error << "[START] VAmp Driver: faStart FAILED(" << l_uint32ErrorCode << "). Closing device.\n";
        faClose(l_i32DeviceId);
        return false;
    }

	//__________________________________
	// Saves parameters
	m_pCallback=&rCallback;
	m_ui32SampleCountPerSentBlock=ui32SampleCountPerSentBlock;

	return true;
}

boolean CDriverBrainProductsVAmp::start(void)
{
	m_rDriverContext.getLogManager() << LogLevel_Trace << "START called.\n";
	if(!m_rDriverContext.isConnected())
	{
		return false;
	}

	if(m_rDriverContext.isStarted())
	{
		return false;
	}

	m_bFirstStart = true;
	//The bonus...
	HBITMAP l_bitmap = (HBITMAP) LoadImage(NULL, "../share/openvibe-applications/acquisition-server/vamp.bmp",IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE);
	if(l_bitmap == NULL || faSetBitmap(m_oHeader.getDeviceId(),l_bitmap ) != FA_ERR_OK)
	{
		m_rDriverContext.getLogManager() << LogLevel_Warning << "[START] VAmp Driver: BMP load failed.\n";
	}

	return true;

}

boolean CDriverBrainProductsVAmp::loop(void)
{
	if(!m_rDriverContext.isConnected())
	{
		return false;
	}

    t_faDataModel16 l_DataBufferNormalMode; // buffer for the next block in normal mode
    uint32 l_uint32ReadLengthNormalMode = sizeof(t_faDataModel16);

    t_faDataFormatMode20kHz l_DataBufferFastMode; // buffer for fast mode acquisition
    uint32 l_uint32ReadLengthFastMode = sizeof(t_faDataFormatMode20kHz);

    int32 l_i32DeviceId = m_oHeader.getDeviceId();

	if(m_rDriverContext.isStarted())
	{
		//uint32 l_i32Timeout = 1000; // 1 second timeout
		uint32 l_i32ReceivedSamples=0;
		//uint32 l_ui32StartTime=System::Time::getTime();

#if DEBUG
		uint32 l_uint32ReadErrorCount = 0;
		uint32 l_uint32ReadSuccessCount = 0;
		uint32 l_uint32ReadZeroCount = 0;
#endif
		//------------------------------------------
 		if(m_bFirstStart)
 		{
 			int32 l_i32ReturnValue = 1;
			int32 l_i32BufferCount = 0;
 			while(l_i32ReturnValue > 0)
 			{
 				if(m_oHeader.getDataMode() == dmNormal)
 				{
 					l_i32ReturnValue = faGetData(l_i32DeviceId, &l_DataBufferNormalMode, l_uint32ReadLengthNormalMode);
 				}

 				if(m_oHeader.getDataMode() == dm20kHz4Channels)
 				{
 					l_i32ReturnValue = faGetData(l_i32DeviceId, &l_DataBufferFastMode, l_uint32ReadLengthFastMode);
 				}
				if(l_i32ReturnValue>0) l_i32BufferCount+=l_i32ReturnValue;
 			}
			m_rDriverContext.getLogManager() << LogLevel_Trace << "[LOOP] cleaning buffer ("<<l_i32BufferCount<<" bytes). \n";
 			m_bFirstStart = false;
 		}

		while(l_i32ReceivedSamples < m_ui32SampleCountPerSentBlock /*&& System::Time::getTime()-l_ui32StartTime < l_i32Timeout*/)
		{
			// we need to "getData" with the right output structure according to acquisition mode

			int32 l_i32ReturnLength = 0;
			if(m_oHeader.getDataMode() == dmNormal)
			{
				l_i32ReturnLength = faGetData(l_i32DeviceId, &l_DataBufferNormalMode, l_uint32ReadLengthNormalMode);
			}

			if(m_oHeader.getDataMode() == dm20kHz4Channels)
			{
				l_i32ReturnLength = faGetData(l_i32DeviceId, &l_DataBufferFastMode, l_uint32ReadLengthFastMode);
			}

			if(l_i32ReturnLength > 0)
			{
#if DEBUG
				l_uint32ReadSuccessCount++;
#endif
				//we just received one set of samples from device, one sample per channel
				if(m_oHeader.getDataMode() == dmNormal)
				{
					for (uint32 i=0; i < m_oHeader.getChannelCount(); i++)
					{
						m_pSample[i*m_ui32SampleCountPerSentBlock+l_i32ReceivedSamples] = (float32)(l_DataBufferNormalMode.Main[i]*m_oHeader.getChannelGain(i));
					}
				}
				// 4 pairs, not related to channel count
				if(m_oHeader.getDataMode() == dm20kHz4Channels)
				{
					for (uint32 i=0; i < m_oHeader.getChannelCount(); i++) // channel count returns the pair count is that case
					{
						m_pSample[i*m_ui32SampleCountPerSentBlock+l_i32ReceivedSamples] = (float32)(l_DataBufferFastMode.Main[i]*m_oHeader.getChannelGain(i));
					}
				}

				l_i32ReceivedSamples++;
			}
#if DEBUG
			if(l_i32ReturnLength < 0)
			{

				l_uint32ReadErrorCount++;

			}
			if(l_i32ReturnLength == 0)
			{
				l_uint32ReadZeroCount++;

			}
#endif
		}// while received < m_ui32SampleCountPerSentBlock
#if DEBUG
        m_rDriverContext.getLogManager() << LogLevel_Debug << "[LOOP] VAmp Driver: stats for the current block : Success="<<l_uint32ReadSuccessCount<<" Error="<<l_uint32ReadErrorCount<<" Zero="<<l_uint32ReadZeroCount<<"\n";
#endif
		//____________________________

		// no stimulations received from hardware, the set is empty
		// CStimulationSet l_oStimulationSet;
		m_pCallback->setSamples(m_pSample);
		// m_pCallback->setStimulationSet(l_oStimulationSet);
		m_rDriverContext.correctJitterSampleCount(m_rDriverContext.getSuggestedJitterCorrectionSampleCount());
	}

	return true;
}

boolean CDriverBrainProductsVAmp::stop(void)
{

	m_rDriverContext.getLogManager() << LogLevel_Trace << "STOP called.\n";
	if(!m_rDriverContext.isConnected())
	{
		return false;
	}

	if(!m_rDriverContext.isStarted())
	{
		return false;
	}

	m_bFirstStart = false;

	return true;
}

boolean CDriverBrainProductsVAmp::uninitialize(void)
{
	if(!m_rDriverContext.isConnected())
	{
		return false;
	}

	if(m_rDriverContext.isStarted())
	{
		return false;
	}

	uint32 l_uint32ErrorCode = faStop(m_oHeader.getDeviceId());
	if (l_uint32ErrorCode != FA_ERR_OK)
	{
		m_rDriverContext.getLogManager() << LogLevel_Error << "[STOP] VAmp Driver: faStop FAILED(" << l_uint32ErrorCode << ").\n";
		faClose(m_oHeader.getDeviceId());
		return false;
	}

	m_rDriverContext.getLogManager() << LogLevel_Trace << "Uninitialize called. Closing the device.\n";

	l_uint32ErrorCode = faClose(m_oHeader.getDeviceId());
	if (l_uint32ErrorCode != FA_ERR_OK)
	{
		m_rDriverContext.getLogManager() << LogLevel_Error << "[UINIT] VAmp Driver: faClose FAILED(" << l_uint32ErrorCode << ").\n";
		faClose(m_oHeader.getDeviceId());
		return false;
	}
	delete [] m_pSample;
	m_pSample=NULL;
	m_pCallback=NULL;

	return true;
}

//___________________________________________________________________//
//                                                                   //

boolean CDriverBrainProductsVAmp::isConfigurable(void)
{
	return true;
}

boolean CDriverBrainProductsVAmp::configure(void)
{
	CConfigurationBrainProductsVAmp m_oConfiguration(m_rDriverContext, "../share/openvibe-applications/acquisition-server/interface-BrainProducts-VAmp.glade", &m_oHeader); // the specific header is passed into the specific configuration

	if(!m_oConfiguration.configure(*(m_oHeader.getBasicHeader()))) // the basic configure will use the basic header
	{
		return false;
	}

	if(m_oHeader.getDataMode() == dm20kHz4Channels)
	{
		m_rDriverContext.getLogManager() << LogLevel_Trace << "Pair names :\n";
		for(uint32 i = 0; i < m_oHeader.getPairCount();i++)
		{
			m_rDriverContext.getLogManager() << LogLevel_Trace << "  Pair " << i << " > " << m_oHeader.getPairName(i) << "\n";
		}
	}

	return true;
}

#endif // TARGET_HAS_ThirdPartyUSBFirstAmpAPI
<|endoftext|>


<commit_before>// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: jmarantz@google.com (Joshua Marantz)

#include "net/instaweb/apache/apache_slurp.h"

// Must precede any Apache includes, for now, due a conflict in
// the use of 'OK" as an Instaweb enum and as an Apache #define.
#include "net/instaweb/apache/header_util.h"
#include "net/instaweb/apache/apache_config.h"
#include "net/instaweb/apache/instaweb_context.h"

// TODO(jmarantz): serf_url_async_fetcher evidently sets
// 'gzip' unconditionally, and the response includes the 'gzip'
// encoding header, but serf unzips the response itself.
//
// I think the correct behavior is that our async fetcher should
// transmit the 'gzip' request header if it was specified in the call
// to StreamingFetch.  This would be easy to fix.
//
// Unfortunately, serf 0.31 appears to unzip the content for us, which
// is not what we are asking for.  And it leaves the 'gzip' response
// header in despite having unzipped it itself.  I have tried later
// versions of serf, but the API is not compatible (easy to deal with)
// but the resulting binary has unresolved symbols.  I am wondering
// whether we will have to go to libcurl.
//
// For now use wget when slurping additional files.

#include "base/logging.h"
#include "net/instaweb/apache/apache_server_context.h"
#include "net/instaweb/apache/apache_writer.h"
#include "net/instaweb/http/public/async_fetch.h"
#include "net/instaweb/http/public/http_dump_url_fetcher.h"
#include "net/instaweb/http/public/meta_data.h"
#include "net/instaweb/http/public/request_context.h"
#include "net/instaweb/http/public/request_headers.h"
#include "net/instaweb/http/public/response_headers.h"
#include "net/instaweb/http/public/url_async_fetcher.h"
#include "net/instaweb/public/global_constants.h"
#include "net/instaweb/rewriter/public/domain_lawyer.h"
#include "net/instaweb/rewriter/public/rewrite_query.h"
#include "net/instaweb/util/public/abstract_mutex.h"
#include "net/instaweb/util/public/basictypes.h"
#include "net/instaweb/util/public/chunking_writer.h"
#include "net/instaweb/util/public/condvar.h"
#include "net/instaweb/util/public/google_url.h"
#include "net/instaweb/util/public/message_handler.h"
#include "net/instaweb/util/public/query_params.h"
#include "net/instaweb/util/public/scoped_ptr.h"
#include "net/instaweb/util/public/string.h"
#include "net/instaweb/util/public/string_util.h"
#include "net/instaweb/util/public/thread_system.h"
#include "net/instaweb/util/public/timer.h"

// The Apache headers must be after instaweb headers.  Otherwise, the
// compiler will complain
//   "strtoul_is_not_a_portable_function_use_strtol_instead".
#include "http_protocol.h"
#include "httpd.h"

namespace net_instaweb {

namespace {

// Default handler when the file is not found
void SlurpDefaultHandler(request_rec* r) {
  ap_set_content_type(r, "text/html; charset=utf-8");
  GoogleString buf = StringPrintf(
      "<title>Slurp Error</title>"
      "
Slurp failed
\n"
      "
host=%s\n"
      "
uri=%s\n"
      "",
      r->hostname, r->unparsed_uri);
  ap_rputs(buf.c_str(), r);
  r->status = HttpStatus::kNotFound;
  r->status_line = "Not Found";
}

// Remove any mod-pagespeed-specific modifiers before we go to our slurped
// fetcher.
//
// TODO(jmarantz): share the string constants from mod_instaweb.cc and
// formalize the prefix-matching assumed here.
GoogleString RemoveModPageSpeedQueryParams(
    const GoogleString& uri, const char* query_param_string) {
  QueryParams query_params, stripped_query_params;
  query_params.Parse(query_param_string);
  bool rewrite_query_params = false;

  for (int i = 0; i < query_params.size(); ++i) {
    StringPiece name = query_params.name(i);
    if (name.starts_with(RewriteQuery::kModPagespeed)) {
      rewrite_query_params = true;
    } else {
      const GoogleString* value = query_params.value(i);
      StringPiece value_piece;  // NULL data by default.
      if (value != NULL) {
        value_piece = *value;
      }
      stripped_query_params.Add(name, value_piece);
    }
  }

  GoogleString stripped_url;
  if (rewrite_query_params) {
    // TODO(jmarantz): It would be nice to use GoogleUrl to do this but
    // it's not clear how it would help.  Instead just hack the string.
    GoogleString::size_type question_mark = uri.find('?');
    CHECK(question_mark != GoogleString::npos);
    stripped_url.append(uri.data(), question_mark);  // does not include "?" yet
    if (stripped_query_params.size() != 0) {
      StrAppend(&stripped_url, "?", stripped_query_params.ToString());
    }
  } else {
    stripped_url = uri;
  }
  return stripped_url;
}

// Some of the sites we are trying to slurp have pagespeed enabled already.
// We actually want to start with the non-pagespeed-enabled site.  But we'd
// rather not send ModPagespeed=off to servers that are not expecting it.
// TODO(sligocki): Perhaps we should just send the "ModPagespeed: off" header
// which seems less intrusive.
class StrippingFetch : public StringAsyncFetch {
 public:
  StrippingFetch(const GoogleString& url_input,
                 const DomainLawyer* lawyer,
                 UrlAsyncFetcher* fetcher,
                 ThreadSystem* thread_system,
                 const RequestContextPtr& ctx,
                 MessageHandler* message_handler)
      : StringAsyncFetch(ctx),
        fetcher_(fetcher),
        lawyer_(lawyer),
        url_(url_input),
        message_handler_(message_handler),
        stripped_(false),
        mutex_(thread_system->NewMutex()),
        condvar_(mutex_->NewCondvar()) {
  }

  // Blocking fetch.
  bool Fetch() {
    // To test sharding domains from a slurp of a site that does not support
    // sharded domains, we apply mapping origin domain here.  Simply map all
    // the shards back into the origin domain in pagespeed.conf.
    GoogleString origin_url;
    bool is_proxy = false;
    if (lawyer_->MapOrigin(url_, &origin_url, &is_proxy)) {
      url_ = origin_url;
      GoogleUrl gurl(url_);
      request_headers()->Replace(HttpAttributes::kHost, gurl.Host());
    }

    fetcher_->Fetch(url_, message_handler_, this);
    {
      ScopedMutex lock(mutex_.get());
      while (!done()) {
        condvar_->TimedWait(Timer::kSecondMs);
      }
    }
    return success();
  }

  virtual void HandleDone(bool success) {
    bool done = true;
    if (!success) {
      set_success(false);
    } else if (stripped_) {
      // Second pass -- declare completion.
      set_success(true);
    // TODO(sligocki): Check for kPageSpeedHeader as well.
    } else if (response_headers()->Lookup1(kModPagespeedHeader) != NULL) {
      // First pass -- the slurped site evidently had mod_pagespeed already
      // enabled.  Turn it off and re-fetch.
      LOG(ERROR) << "URL " << url_ << " already has mod_pagespeed.  Stripping.";
      Reset();  // Clears output buffer and response_headers.
      GoogleString::size_type question = url_.find('?');
      if (question == GoogleString::npos) {
        url_ += "?ModPagespeed=off";
      } else {
        url_ += "&ModPagespeed=off";
      }
      stripped_ = true;
      // TODO(sligocki): This currently allows infinite looping behavior if
      // someone returns X-Mod-Pagespeed headers unexpectedly.
      fetcher_->Fetch(url_, message_handler_, this);
      done = false;
    } else {
      // First-pass -- the origin site did not have mod_pagespeed so no need
      // for a second pass.
      set_success(true);
    }
    if (done) {
      ScopedMutex lock(mutex_.get());
      set_done(true);
      condvar_->Signal();
      // Don't "delete this" -- this is allocated on the stack in ApacheSlurp.
    }
  }

 private:
  UrlAsyncFetcher* fetcher_;
  const DomainLawyer* lawyer_;

  GoogleString url_;
  MessageHandler* message_handler_;

  bool stripped_;

  scoped_ptr<ThreadSystem::CondvarCapableMutex> mutex_;
  scoped_ptr<ThreadSystem::Condvar> condvar_;

  DISALLOW_COPY_AND_ASSIGN(StrippingFetch);
};

}  // namespace

void SlurpUrl(ApacheServerContext* server_context, request_rec* r) {
  const char* url =
      InstawebContext::MakeRequestUrl(*server_context->global_options(), r);
  GoogleString stripped_url = RemoveModPageSpeedQueryParams(
      url, r->parsed_uri.query);

  // Figure out if we should be using a slurp fetcher rather than the default
  // system fetcher.
  UrlAsyncFetcher* fetcher = server_context->DefaultSystemFetcher();
  scoped_ptr<HttpDumpUrlFetcher> slurp_fetcher;

  ApacheConfig* config = server_context->config();
  if (config->test_proxy() && !config->test_proxy_slurp().empty()) {
    slurp_fetcher.reset(new HttpDumpUrlFetcher(
        config->test_proxy_slurp(), server_context->file_system(),
        server_context->timer()));
    fetcher = slurp_fetcher.get();
  }

  MessageHandler* handler = server_context->message_handler();
  RequestContextPtr request_context(
      new RequestContext(server_context->thread_system()->NewMutex(),
                         server_context->timer()));
  StrippingFetch fetch(stripped_url, server_context->config()->domain_lawyer(),
                       fetcher, server_context->thread_system(),
                       request_context, handler);
  ApacheRequestToRequestHeaders(*r, fetch.request_headers());

  if (fetch.Fetch()) {
    // We always disable downstream header filters when sending out
    // slurped resources, since we've captured them from the origin
    // in the fetch we did to write the slurp.
    ApacheWriter apache_writer(r);
    apache_writer.set_disable_downstream_header_filters(true);
    ChunkingWriter chunking_writer(
        &apache_writer, server_context->config()->slurp_flush_limit());
    apache_writer.OutputHeaders(fetch.response_headers());
    chunking_writer.Write(fetch.buffer(), handler);
  } else {
    handler->Message(kInfo, "mod_pagespeed: slurp of url %s failed.\n"
                     "Request Headers: %s\n\nResponse Headers: %s",
                     stripped_url.c_str(),
                     fetch.request_headers()->ToString().c_str(),
                     fetch.response_headers()->ToString().c_str());
    SlurpDefaultHandler(r);
  }
}

}  // namespace net_instaweb
<commit_msg>Re-slurp with ?ModPagespeed=off for ngx_pagespeed & PSS results.<commit_after>// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: jmarantz@google.com (Joshua Marantz)

#include "net/instaweb/apache/apache_slurp.h"

// Must precede any Apache includes, for now, due a conflict in
// the use of 'OK" as an Instaweb enum and as an Apache #define.
#include "net/instaweb/apache/header_util.h"
#include "net/instaweb/apache/apache_config.h"
#include "net/instaweb/apache/instaweb_context.h"

// TODO(jmarantz): serf_url_async_fetcher evidently sets
// 'gzip' unconditionally, and the response includes the 'gzip'
// encoding header, but serf unzips the response itself.
//
// I think the correct behavior is that our async fetcher should
// transmit the 'gzip' request header if it was specified in the call
// to StreamingFetch.  This would be easy to fix.
//
// Unfortunately, serf 0.31 appears to unzip the content for us, which
// is not what we are asking for.  And it leaves the 'gzip' response
// header in despite having unzipped it itself.  I have tried later
// versions of serf, but the API is not compatible (easy to deal with)
// but the resulting binary has unresolved symbols.  I am wondering
// whether we will have to go to libcurl.
//
// For now use wget when slurping additional files.

#include "base/logging.h"
#include "net/instaweb/apache/apache_server_context.h"
#include "net/instaweb/apache/apache_writer.h"
#include "net/instaweb/http/public/async_fetch.h"
#include "net/instaweb/http/public/http_dump_url_fetcher.h"
#include "net/instaweb/http/public/meta_data.h"
#include "net/instaweb/http/public/request_context.h"
#include "net/instaweb/http/public/request_headers.h"
#include "net/instaweb/http/public/response_headers.h"
#include "net/instaweb/http/public/url_async_fetcher.h"
#include "net/instaweb/public/global_constants.h"
#include "net/instaweb/rewriter/public/domain_lawyer.h"
#include "net/instaweb/rewriter/public/rewrite_query.h"
#include "net/instaweb/util/public/abstract_mutex.h"
#include "net/instaweb/util/public/basictypes.h"
#include "net/instaweb/util/public/chunking_writer.h"
#include "net/instaweb/util/public/condvar.h"
#include "net/instaweb/util/public/google_url.h"
#include "net/instaweb/util/public/message_handler.h"
#include "net/instaweb/util/public/query_params.h"
#include "net/instaweb/util/public/scoped_ptr.h"
#include "net/instaweb/util/public/string.h"
#include "net/instaweb/util/public/string_util.h"
#include "net/instaweb/util/public/thread_system.h"
#include "net/instaweb/util/public/timer.h"

// The Apache headers must be after instaweb headers.  Otherwise, the
// compiler will complain
//   "strtoul_is_not_a_portable_function_use_strtol_instead".
#include "http_protocol.h"
#include "httpd.h"

namespace net_instaweb {

namespace {

// Default handler when the file is not found
void SlurpDefaultHandler(request_rec* r) {
  ap_set_content_type(r, "text/html; charset=utf-8");
  GoogleString buf = StringPrintf(
      "<title>Slurp Error</title>"
      "
Slurp failed
\n"
      "
host=%s\n"
      "
uri=%s\n"
      "",
      r->hostname, r->unparsed_uri);
  ap_rputs(buf.c_str(), r);
  r->status = HttpStatus::kNotFound;
  r->status_line = "Not Found";
}

// Remove any mod-pagespeed-specific modifiers before we go to our slurped
// fetcher.
//
// TODO(jmarantz): share the string constants from mod_instaweb.cc and
// formalize the prefix-matching assumed here.
GoogleString RemoveModPageSpeedQueryParams(
    const GoogleString& uri, const char* query_param_string) {
  QueryParams query_params, stripped_query_params;
  query_params.Parse(query_param_string);
  bool rewrite_query_params = false;

  for (int i = 0; i < query_params.size(); ++i) {
    StringPiece name = query_params.name(i);
    if (name.starts_with(RewriteQuery::kModPagespeed)) {
      rewrite_query_params = true;
    } else {
      const GoogleString* value = query_params.value(i);
      StringPiece value_piece;  // NULL data by default.
      if (value != NULL) {
        value_piece = *value;
      }
      stripped_query_params.Add(name, value_piece);
    }
  }

  GoogleString stripped_url;
  if (rewrite_query_params) {
    // TODO(jmarantz): It would be nice to use GoogleUrl to do this but
    // it's not clear how it would help.  Instead just hack the string.
    GoogleString::size_type question_mark = uri.find('?');
    CHECK(question_mark != GoogleString::npos);
    stripped_url.append(uri.data(), question_mark);  // does not include "?" yet
    if (stripped_query_params.size() != 0) {
      StrAppend(&stripped_url, "?", stripped_query_params.ToString());
    }
  } else {
    stripped_url = uri;
  }
  return stripped_url;
}

// Some of the sites we are trying to slurp have pagespeed enabled already.
// We actually want to start with the non-pagespeed-enabled site.  But we'd
// rather not send ModPagespeed=off to servers that are not expecting it.
// TODO(sligocki): Perhaps we should just send the "ModPagespeed: off" header
// which seems less intrusive.
class StrippingFetch : public StringAsyncFetch {
 public:
  StrippingFetch(const GoogleString& url_input,
                 const DomainLawyer* lawyer,
                 UrlAsyncFetcher* fetcher,
                 ThreadSystem* thread_system,
                 const RequestContextPtr& ctx,
                 MessageHandler* message_handler)
      : StringAsyncFetch(ctx),
        fetcher_(fetcher),
        lawyer_(lawyer),
        url_(url_input),
        message_handler_(message_handler),
        stripped_(false),
        mutex_(thread_system->NewMutex()),
        condvar_(mutex_->NewCondvar()) {
  }

  // Blocking fetch.
  bool Fetch() {
    // To test sharding domains from a slurp of a site that does not support
    // sharded domains, we apply mapping origin domain here.  Simply map all
    // the shards back into the origin domain in pagespeed.conf.
    GoogleString origin_url;
    bool is_proxy = false;
    if (lawyer_->MapOrigin(url_, &origin_url, &is_proxy)) {
      url_ = origin_url;
      GoogleUrl gurl(url_);
      request_headers()->Replace(HttpAttributes::kHost, gurl.Host());
    }

    fetcher_->Fetch(url_, message_handler_, this);
    {
      ScopedMutex lock(mutex_.get());
      while (!done()) {
        condvar_->TimedWait(Timer::kSecondMs);
      }
    }
    return success();
  }

  virtual void HandleDone(bool success) {
    bool done = true;
    if (!success) {
      set_success(false);
    } else if (stripped_) {
      // Second pass -- declare completion.
      set_success(true);
    // TODO(sligocki): Check for kPageSpeedHeader as well.
    } else if ((response_headers()->Lookup1(kModPagespeedHeader) != NULL) ||
               (response_headers()->Lookup1(kPageSpeedHeader) != NULL)) {
      // First pass -- the slurped site evidently had mod_pagespeed already
      // enabled.  Turn it off and re-fetch.
      LOG(ERROR) << "URL " << url_ << " already has mod_pagespeed.  Stripping.";
      Reset();  // Clears output buffer and response_headers.
      GoogleString::size_type question = url_.find('?');
      if (question == GoogleString::npos) {
        url_ += "?ModPagespeed=off";
      } else {
        url_ += "&ModPagespeed=off";
      }
      stripped_ = true;
      // TODO(sligocki): This currently allows infinite looping behavior if
      // someone returns X-Mod-Pagespeed headers unexpectedly.
      fetcher_->Fetch(url_, message_handler_, this);
      done = false;
    } else {
      // First-pass -- the origin site did not have mod_pagespeed so no need
      // for a second pass.
      set_success(true);
    }
    if (done) {
      ScopedMutex lock(mutex_.get());
      set_done(true);
      condvar_->Signal();
      // Don't "delete this" -- this is allocated on the stack in ApacheSlurp.
    }
  }

 private:
  UrlAsyncFetcher* fetcher_;
  const DomainLawyer* lawyer_;

  GoogleString url_;
  MessageHandler* message_handler_;

  bool stripped_;

  scoped_ptr<ThreadSystem::CondvarCapableMutex> mutex_;
  scoped_ptr<ThreadSystem::Condvar> condvar_;

  DISALLOW_COPY_AND_ASSIGN(StrippingFetch);
};

}  // namespace

void SlurpUrl(ApacheServerContext* server_context, request_rec* r) {
  const char* url =
      InstawebContext::MakeRequestUrl(*server_context->global_options(), r);
  GoogleString stripped_url = RemoveModPageSpeedQueryParams(
      url, r->parsed_uri.query);

  // Figure out if we should be using a slurp fetcher rather than the default
  // system fetcher.
  UrlAsyncFetcher* fetcher = server_context->DefaultSystemFetcher();
  scoped_ptr<HttpDumpUrlFetcher> slurp_fetcher;

  ApacheConfig* config = server_context->config();
  if (config->test_proxy() && !config->test_proxy_slurp().empty()) {
    slurp_fetcher.reset(new HttpDumpUrlFetcher(
        config->test_proxy_slurp(), server_context->file_system(),
        server_context->timer()));
    fetcher = slurp_fetcher.get();
  }

  MessageHandler* handler = server_context->message_handler();
  RequestContextPtr request_context(
      new RequestContext(server_context->thread_system()->NewMutex(),
                         server_context->timer()));
  StrippingFetch fetch(stripped_url, server_context->config()->domain_lawyer(),
                       fetcher, server_context->thread_system(),
                       request_context, handler);
  ApacheRequestToRequestHeaders(*r, fetch.request_headers());

  if (fetch.Fetch()) {
    // We always disable downstream header filters when sending out
    // slurped resources, since we've captured them from the origin
    // in the fetch we did to write the slurp.
    ApacheWriter apache_writer(r);
    apache_writer.set_disable_downstream_header_filters(true);
    ChunkingWriter chunking_writer(
        &apache_writer, server_context->config()->slurp_flush_limit());
    apache_writer.OutputHeaders(fetch.response_headers());
    chunking_writer.Write(fetch.buffer(), handler);
  } else {
    handler->Message(kInfo, "mod_pagespeed: slurp of url %s failed.\n"
                     "Request Headers: %s\n\nResponse Headers: %s",
                     stripped_url.c_str(),
                     fetch.request_headers()->ToString().c_str(),
                     fetch.response_headers()->ToString().c_str());
    SlurpDefaultHandler(r);
  }
}

}  // namespace net_instaweb
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2008-2010 The QXmpp developers
 *
 * Author:
 *	Manjeet Dahiya
 *
 * Source:
 *	http://code.google.com/p/qxmpp
 *
 * This file is a part of QXmpp library.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 */

#include <QtGui/QApplication>
#include <QDir>
#include "chatDialog.h"
#include "chatGraphicsView.h"
#include "chatGraphicsScene.h"
#include "mainDialog.h"
#include "statusTextWidget.h"
#include "utils.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QApplication::setOrganizationName("QXmpp");
    QApplication::setApplicationName("GuiClient");

    QDir dir;
    if(!dir.exists(getSettingsDir()))
        dir.mkpath(getSettingsDir());

    mainDialog cw;
    cw.show();
    return a.exec();
}
<commit_msg>remove unnecessary includes from main.cpp<commit_after>/*
 * Copyright (C) 2008-2010 The QXmpp developers
 *
 * Author:
 *	Manjeet Dahiya
 *
 * Source:
 *	http://code.google.com/p/qxmpp
 *
 * This file is a part of QXmpp library.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 */

#include <QtGui/QApplication>
#include <QDir>

#include "mainDialog.h"
#include "utils.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QApplication::setOrganizationName("QXmpp");
    QApplication::setApplicationName("GuiClient");

    QDir dir;
    if(!dir.exists(getSettingsDir()))
        dir.mkpath(getSettingsDir());

    mainDialog cw;
    cw.show();
    return a.exec();
}
<|endoftext|>


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

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

#ifdef SVX_DLLIMPLEMENTATION
#undef SVX_DLLIMPLEMENTATION
#endif

#ifndef _OFFAPP_INTERNATIONALOPTIONS_HXX_
#include "internationaloptions.hxx"
#endif
#ifndef _OFFAPP_INTERNATIONALOPTIONS_HRC_
#include "internationaloptions.hrc"
#endif

#ifndef _SFXENUMITEM_HXX
#include <svtools/eitem.hxx>
#endif

#include <svx/dialogs.hrc>
#include "helpid.hrc"
#include <svx/dialmgr.hxx>

namespace offapp
{

    struct InternationalOptionsPage::IMPL
    {
        FixedLine           m_aFL_DefaultTextDirection;
        RadioButton         m_aRB_TxtDirLeft2Right;
        RadioButton         m_aRB_TxtDirRight2Left;
        FixedLine           m_aFL_SheetView;
        CheckBox            m_aCB_ShtVwRight2Left;
        CheckBox            m_aCB_ShtVwCurrentDocOnly;

        BOOL                m_bEnable_SheetView_Opt : 1;

        inline              IMPL( Window* _pParent );

        inline void         EnableOption_SheetView( BOOL _bEnable = TRUE );
        void                ShowOption_SheetView( BOOL _bShow = TRUE );

        BOOL                FillItemSet( SfxItemSet& _rSet );
        void                Reset( const SfxItemSet& _rSet );
    };

    inline InternationalOptionsPage::IMPL::IMPL( Window* _pParent ) :
        m_aFL_DefaultTextDirection  ( _pParent, SVX_RES( FL_DEFTXTDIRECTION ) )
        ,m_aRB_TxtDirLeft2Right     ( _pParent, SVX_RES( RB_TXTDIR_LEFT2RIGHT ) )
        ,m_aRB_TxtDirRight2Left     ( _pParent, SVX_RES( RB_TXTDIR_RIGHT2LEFT ) )
        ,m_aFL_SheetView            ( _pParent, SVX_RES( FL_SHEETVIEW ) )
        ,m_aCB_ShtVwRight2Left      ( _pParent, SVX_RES( CB_SHTVW_RIGHT2LEFT ) )
        ,m_aCB_ShtVwCurrentDocOnly  ( _pParent, SVX_RES( CB_SHTVW_CURRENTDOCONLY ) )

        ,m_bEnable_SheetView_Opt    ( FALSE )
    {
        ShowOption_SheetView( m_bEnable_SheetView_Opt );
    }

    inline void InternationalOptionsPage::IMPL::EnableOption_SheetView( BOOL _bEnable )
    {
        if( m_bEnable_SheetView_Opt != _bEnable )
        {
            ShowOption_SheetView( _bEnable );

            m_bEnable_SheetView_Opt = _bEnable;
        }
    }

    void InternationalOptionsPage::IMPL::ShowOption_SheetView( BOOL _bShow )
    {
        m_aFL_SheetView.Show( _bShow );
        m_aCB_ShtVwRight2Left.Show( _bShow );
        m_aCB_ShtVwCurrentDocOnly.Show( _bShow );
    }

    BOOL InternationalOptionsPage::IMPL::FillItemSet( SfxItemSet& _rSet )
    {
        DBG_ASSERT( _rSet.GetPool(), "-InternationalOptionsPage::FillItemSet(): no pool gives rums!" );

        // handling of DefaultTextDirection stuff
        _rSet.Put(  SfxBoolItem(    _rSet.GetPool()->GetWhich( SID_ATTR_PARA_LEFT_TO_RIGHT ),
                                    m_aRB_TxtDirLeft2Right.IsChecked() ),
                    SID_ATTR_PARA_LEFT_TO_RIGHT );

        // handling of SheetView stuff
//      if( m_bEnable_SheetView_Opt )
//      {
//      }

        return TRUE;
    }

    void InternationalOptionsPage::IMPL::Reset( const SfxItemSet& _rSet )
    {
        // handling of DefaultTextDirection stuff
        const SfxBoolItem*  pLeft2RightItem = static_cast< const SfxBoolItem* >( GetItem( _rSet, SID_ATTR_PARA_LEFT_TO_RIGHT ) );

        DBG_ASSERT( pLeft2RightItem, "+InternationalOptionsPage::Reset(): SID_ATTR_PARA_LEFT_TO_RIGHT not set!" );

        BOOL                bLeft2Right = pLeft2RightItem? pLeft2RightItem->GetValue() : TRUE;
        m_aRB_TxtDirLeft2Right.Check( bLeft2Right );

        // handling of SheetView stuff
//      if( m_bEnable_SheetView_Opt )
//      {
//          m_aCB_ShtVwRight2Left.Check( FALSE );
//
//          m_aCB_ShtVwCurrentDocOnly.Check( FALSE );
//      }
    }

    InternationalOptionsPage::InternationalOptionsPage( Window* _pParent, const SfxItemSet& _rAttrSet ) :
        SfxTabPage  ( _pParent, SVX_RES( RID_OFA_TP_INTERNATIONAL ), _rAttrSet )

        ,m_pImpl    ( new IMPL( this ) )
    {
        FreeResource();
    }

    SfxTabPage* InternationalOptionsPage::CreateSd( Window* _pParent, const SfxItemSet& _rAttrSet )
    {
        return new InternationalOptionsPage( _pParent, _rAttrSet );
    }

    SfxTabPage* InternationalOptionsPage::CreateSc( Window* _pParent, const SfxItemSet& _rAttrSet )
    {
        InternationalOptionsPage*   p = new InternationalOptionsPage( _pParent, _rAttrSet );
//      p->m_pImpl->EnableOption_SheetView();
        return p;
    }

    InternationalOptionsPage::~InternationalOptionsPage()
    {
        DELETEZ( m_pImpl );
    }

    BOOL InternationalOptionsPage::FillItemSet( SfxItemSet& _rSet )
    {
        return m_pImpl->FillItemSet( _rSet );
    }

    void InternationalOptionsPage::Reset( const SfxItemSet& _rSet )
    {
        m_pImpl->Reset( _rSet );
    }

}   // /namespace offapp

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

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

#ifdef SVX_DLLIMPLEMENTATION
#undef SVX_DLLIMPLEMENTATION
#endif
#include "internationaloptions.hxx"
#ifndef _OFFAPP_INTERNATIONALOPTIONS_HRC_
#include "internationaloptions.hrc"
#endif
#include <svtools/eitem.hxx>

#include <svx/dialogs.hrc>
#include "helpid.hrc"
#include <svx/dialmgr.hxx>

namespace offapp
{

    struct InternationalOptionsPage::IMPL
    {
        FixedLine           m_aFL_DefaultTextDirection;
        RadioButton         m_aRB_TxtDirLeft2Right;
        RadioButton         m_aRB_TxtDirRight2Left;
        FixedLine           m_aFL_SheetView;
        CheckBox            m_aCB_ShtVwRight2Left;
        CheckBox            m_aCB_ShtVwCurrentDocOnly;

        BOOL                m_bEnable_SheetView_Opt : 1;

        inline              IMPL( Window* _pParent );

        inline void         EnableOption_SheetView( BOOL _bEnable = TRUE );
        void                ShowOption_SheetView( BOOL _bShow = TRUE );

        BOOL                FillItemSet( SfxItemSet& _rSet );
        void                Reset( const SfxItemSet& _rSet );
    };

    inline InternationalOptionsPage::IMPL::IMPL( Window* _pParent ) :
        m_aFL_DefaultTextDirection  ( _pParent, SVX_RES( FL_DEFTXTDIRECTION ) )
        ,m_aRB_TxtDirLeft2Right     ( _pParent, SVX_RES( RB_TXTDIR_LEFT2RIGHT ) )
        ,m_aRB_TxtDirRight2Left     ( _pParent, SVX_RES( RB_TXTDIR_RIGHT2LEFT ) )
        ,m_aFL_SheetView            ( _pParent, SVX_RES( FL_SHEETVIEW ) )
        ,m_aCB_ShtVwRight2Left      ( _pParent, SVX_RES( CB_SHTVW_RIGHT2LEFT ) )
        ,m_aCB_ShtVwCurrentDocOnly  ( _pParent, SVX_RES( CB_SHTVW_CURRENTDOCONLY ) )

        ,m_bEnable_SheetView_Opt    ( FALSE )
    {
        ShowOption_SheetView( m_bEnable_SheetView_Opt );
    }

    inline void InternationalOptionsPage::IMPL::EnableOption_SheetView( BOOL _bEnable )
    {
        if( m_bEnable_SheetView_Opt != _bEnable )
        {
            ShowOption_SheetView( _bEnable );

            m_bEnable_SheetView_Opt = _bEnable;
        }
    }

    void InternationalOptionsPage::IMPL::ShowOption_SheetView( BOOL _bShow )
    {
        m_aFL_SheetView.Show( _bShow );
        m_aCB_ShtVwRight2Left.Show( _bShow );
        m_aCB_ShtVwCurrentDocOnly.Show( _bShow );
    }

    BOOL InternationalOptionsPage::IMPL::FillItemSet( SfxItemSet& _rSet )
    {
        DBG_ASSERT( _rSet.GetPool(), "-InternationalOptionsPage::FillItemSet(): no pool gives rums!" );

        // handling of DefaultTextDirection stuff
        _rSet.Put(  SfxBoolItem(    _rSet.GetPool()->GetWhich( SID_ATTR_PARA_LEFT_TO_RIGHT ),
                                    m_aRB_TxtDirLeft2Right.IsChecked() ),
                    SID_ATTR_PARA_LEFT_TO_RIGHT );

        // handling of SheetView stuff
//      if( m_bEnable_SheetView_Opt )
//      {
//      }

        return TRUE;
    }

    void InternationalOptionsPage::IMPL::Reset( const SfxItemSet& _rSet )
    {
        // handling of DefaultTextDirection stuff
        const SfxBoolItem*  pLeft2RightItem = static_cast< const SfxBoolItem* >( GetItem( _rSet, SID_ATTR_PARA_LEFT_TO_RIGHT ) );

        DBG_ASSERT( pLeft2RightItem, "+InternationalOptionsPage::Reset(): SID_ATTR_PARA_LEFT_TO_RIGHT not set!" );

        BOOL                bLeft2Right = pLeft2RightItem? pLeft2RightItem->GetValue() : TRUE;
        m_aRB_TxtDirLeft2Right.Check( bLeft2Right );

        // handling of SheetView stuff
//      if( m_bEnable_SheetView_Opt )
//      {
//          m_aCB_ShtVwRight2Left.Check( FALSE );
//
//          m_aCB_ShtVwCurrentDocOnly.Check( FALSE );
//      }
    }

    InternationalOptionsPage::InternationalOptionsPage( Window* _pParent, const SfxItemSet& _rAttrSet ) :
        SfxTabPage  ( _pParent, SVX_RES( RID_OFA_TP_INTERNATIONAL ), _rAttrSet )

        ,m_pImpl    ( new IMPL( this ) )
    {
        FreeResource();
    }

    SfxTabPage* InternationalOptionsPage::CreateSd( Window* _pParent, const SfxItemSet& _rAttrSet )
    {
        return new InternationalOptionsPage( _pParent, _rAttrSet );
    }

    SfxTabPage* InternationalOptionsPage::CreateSc( Window* _pParent, const SfxItemSet& _rAttrSet )
    {
        InternationalOptionsPage*   p = new InternationalOptionsPage( _pParent, _rAttrSet );
//      p->m_pImpl->EnableOption_SheetView();
        return p;
    }

    InternationalOptionsPage::~InternationalOptionsPage()
    {
        DELETEZ( m_pImpl );
    }

    BOOL InternationalOptionsPage::FillItemSet( SfxItemSet& _rSet )
    {
        return m_pImpl->FillItemSet( _rSet );
    }

    void InternationalOptionsPage::Reset( const SfxItemSet& _rSet )
    {
        m_pImpl->Reset( _rSet );
    }

}   // /namespace offapp

<|endoftext|>


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

#ifndef _NUMBERINGTYPELISTBOX_HXX
#include <numberingtypelistbox.hxx>
#endif
#ifndef _MISC_HRC
#include <misc.hrc>
#endif
#ifndef _CNTTAB_HXX
#include <cnttab.hxx>
#endif
#ifndef _COM_SUN_STAR_STYLE_NUMBERINGTYPE_HPP_
#include <com/sun/star/style/NumberingType.hpp>
#endif
#ifndef _COM_SUN_STAR_TEXT_XDEFAULTNUMBERINGPROVIDER_HPP_
#include <com/sun/star/text/XDefaultNumberingProvider.hpp>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _COM_SUN_STAR_TEXT_XNUMBERINGTYPEINFO_HPP_
#include <com/sun/star/text/XNumberingTypeInfo.hpp>
#endif

//#ifndef _SVTOOLS_LANGUAGEOPTIONS_HXX
//#include <svtools/languageoptions.hxx>
//#endif

using namespace com::sun::star::uno;
using namespace com::sun::star::text;
using namespace com::sun::star::lang;
using namespace com::sun::star::style;
using namespace rtl;

#define C2S(cChar) UniString::CreateFromAscii(cChar)
/* -----------------------------01.03.01 16:04--------------------------------

 ---------------------------------------------------------------------------*/
struct SwNumberingTypeListBox_Impl
{
    Reference<XNumberingTypeInfo> xInfo;
};
/* -----------------------------01.03.01 14:46--------------------------------

 ---------------------------------------------------------------------------*/
SwNumberingTypeListBox::SwNumberingTypeListBox( Window* pWin, const ResId& rResId,
        USHORT nTypeFlags ) :
    ListBox(pWin, rResId),
    pImpl(new SwNumberingTypeListBox_Impl)
{
    Reference< XMultiServiceFactory > xMSF = ::comphelper::getProcessServiceFactory();
    Reference < XInterface > xI = xMSF->createInstance(
        ::rtl::OUString::createFromAscii( "com.sun.star.text.DefaultNumberingProvider" ) );
    Reference<XDefaultNumberingProvider> xDefNum(xI, UNO_QUERY);
    DBG_ASSERT(xDefNum.is(), "service missing: \"com.sun.star.text.DefaultNumberingProvider\"")

    pImpl->xInfo = Reference<XNumberingTypeInfo>(xDefNum, UNO_QUERY);
    Reload(nTypeFlags);
}
/* -----------------------------01.03.01 14:46--------------------------------

 ---------------------------------------------------------------------------*/
SwNumberingTypeListBox::~SwNumberingTypeListBox()
{
    delete pImpl;
}
/* -----------------------------01.03.01 16:02--------------------------------

 ---------------------------------------------------------------------------*/
void SwNumberingTypeListBox::Reload(USHORT nTypeFlags)
{
    Clear();
    Sequence<sal_Int16> aTypes;
    const sal_Int16* pTypes = NULL;
    if(0 != (nTypeFlags&INSERT_NUM_EXTENDED_TYPES) )
    {
        if(pImpl->xInfo.is())
        {
            aTypes = pImpl->xInfo->getSupportedNumberingTypes();
            pTypes = aTypes.getConstArray();
        }
    }
    SwOLENames aNames(SW_RES(STRRES_NUMTYPES));
    ResStringArray& rNames = aNames.GetNames();
    for(sal_uInt16 i = 0; i < rNames.Count(); i++)
    {
        long nValue = rNames.GetValue(i);
        sal_Bool bInsert = sal_True;
        USHORT nPos = LISTBOX_APPEND;
        switch(nValue)
        {
            case  NumberingType::NUMBER_NONE:
                bInsert = 0 != (nTypeFlags&INSERT_NUM_TYPE_NO_NUMBERING);
                nPos = 0;
             break;
            case  NumberingType::CHAR_SPECIAL:  bInsert = 0 != (nTypeFlags&INSERT_NUM_TYPE_BULLET); break;
            case  NumberingType::PAGE_DESCRIPTOR:bInsert = 0 != (nTypeFlags&INSERT_NUM_TYPE_PAGE_STYLE_NUMBERING); break;
            case  NumberingType::BITMAP:bInsert = 0 != (nTypeFlags&INSERT_NUM_TYPE_BITMAP ); break;
            default:
                if (nValue >  NumberingType::CHARS_LOWER_LETTER_N)
                {
                    // Insert only if offered by i18n framework per configuration.
                    bInsert = sal_False;
                    if (pTypes)
                    {
                        for(sal_Int32 nType = 0; nType < aTypes.getLength(); nType++)
                        {
                            if (pTypes[nType] == nValue)
                            {
                                bInsert = sal_True;
                                break;  // for
                            }
                        }
                    }
                }
        }
        if(bInsert)
        {
            USHORT nEntry = InsertEntry(rNames.GetString(i), nPos);
            SetEntryData( nEntry, (void*)nValue );
        }
    }
    if(0 != (nTypeFlags&INSERT_NUM_EXTENDED_TYPES) )
    {
        if(pTypes)
        {
            for(sal_Int32 nType = 0; nType < aTypes.getLength(); nType++)
            {
                sal_Int16 nCurrent = pTypes[nType];
                if(nCurrent > NumberingType::CHARS_LOWER_LETTER_N)
                {
                    if(LISTBOX_ENTRY_NOTFOUND == GetEntryPos((void*)(ULONG)nCurrent))
                    {
                        OUString aIdent = pImpl->xInfo->getNumberingIdentifier( nCurrent );
                        USHORT nPos = InsertEntry(aIdent);
                        SetEntryData(nPos,(void*)(ULONG)nCurrent);
                    }
                }
            }
        }
        SelectEntryPos(0);
    }
}
/* -----------------------------01.03.01 14:46--------------------------------

 ---------------------------------------------------------------------------*/
sal_Int16   SwNumberingTypeListBox::GetSelectedNumberingType()
{
    sal_Int16 nRet = 0;
    USHORT nSelPos = GetSelectEntryPos();
    if(LISTBOX_ENTRY_NOTFOUND != nSelPos)
        nRet = (sal_Int16)(ULONG)GetEntryData(nSelPos);
#ifdef DBG_UTIL
    else
        DBG_ERROR("SwNumberingTypeListBox not selected")
#endif
    return nRet;
}
/* -----------------------------01.03.01 14:46--------------------------------

 ---------------------------------------------------------------------------*/
sal_Bool    SwNumberingTypeListBox::SelectNumberingType(sal_Int16 nType)
{
    USHORT nPos = GetEntryPos((void*)(ULONG)nType);
    SelectEntryPos( nPos );
    return LISTBOX_ENTRY_NOTFOUND != nPos;
}

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

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

#ifndef _NUMBERINGTYPELISTBOX_HXX
#include <numberingtypelistbox.hxx>
#endif
#ifndef _MISC_HRC
#include <misc.hrc>
#endif
#ifndef _CNTTAB_HXX
#include <cnttab.hxx>
#endif
#ifndef _COM_SUN_STAR_STYLE_NUMBERINGTYPE_HPP_
#include <com/sun/star/style/NumberingType.hpp>
#endif
#ifndef _COM_SUN_STAR_TEXT_XDEFAULTNUMBERINGPROVIDER_HPP_
#include <com/sun/star/text/XDefaultNumberingProvider.hpp>
#endif
#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _COM_SUN_STAR_TEXT_XNUMBERINGTYPEINFO_HPP_
#include <com/sun/star/text/XNumberingTypeInfo.hpp>
#endif

//#ifndef _SVTOOLS_LANGUAGEOPTIONS_HXX
//#include <svtools/languageoptions.hxx>
//#endif

using namespace com::sun::star::uno;
using namespace com::sun::star::text;
using namespace com::sun::star::lang;
using namespace com::sun::star::style;
using namespace rtl;

#define C2S(cChar) UniString::CreateFromAscii(cChar)
/* -----------------------------01.03.01 16:04--------------------------------

 ---------------------------------------------------------------------------*/
struct SwNumberingTypeListBox_Impl
{
    Reference<XNumberingTypeInfo> xInfo;
};
/* -----------------------------01.03.01 14:46--------------------------------

 ---------------------------------------------------------------------------*/
SwNumberingTypeListBox::SwNumberingTypeListBox( Window* pWin, const ResId& rResId,
        USHORT nTypeFlags ) :
    ListBox(pWin, rResId),
    pImpl(new SwNumberingTypeListBox_Impl)
{
    Reference< XMultiServiceFactory > xMSF = ::comphelper::getProcessServiceFactory();
    Reference < XInterface > xI = xMSF->createInstance(
        ::rtl::OUString::createFromAscii( "com.sun.star.text.DefaultNumberingProvider" ) );
    Reference<XDefaultNumberingProvider> xDefNum(xI, UNO_QUERY);
    DBG_ASSERT(xDefNum.is(), "service missing: \"com.sun.star.text.DefaultNumberingProvider\"")

    pImpl->xInfo = Reference<XNumberingTypeInfo>(xDefNum, UNO_QUERY);
    Reload(nTypeFlags);
}
/* -----------------------------01.03.01 14:46--------------------------------

 ---------------------------------------------------------------------------*/
SwNumberingTypeListBox::~SwNumberingTypeListBox()
{
    delete pImpl;
}
/* -----------------------------01.03.01 16:02--------------------------------

 ---------------------------------------------------------------------------*/
void SwNumberingTypeListBox::Reload(USHORT nTypeFlags)
{
    Clear();
    Sequence<sal_Int16> aTypes;
    const sal_Int16* pTypes = NULL;
    if(0 != (nTypeFlags&INSERT_NUM_EXTENDED_TYPES) )
    {
        if(pImpl->xInfo.is())
        {
            aTypes = pImpl->xInfo->getSupportedNumberingTypes();
            pTypes = aTypes.getConstArray();
        }
    }
    SwOLENames aNames(SW_RES(STRRES_NUMTYPES));
    ResStringArray& rNames = aNames.GetNames();
    for(sal_uInt16 i = 0; i < rNames.Count(); i++)
    {
        long nValue = rNames.GetValue(i);
        sal_Bool bInsert = sal_True;
        USHORT nPos = LISTBOX_APPEND;
        switch(nValue)
        {
            case  NumberingType::NUMBER_NONE:
                bInsert = 0 != (nTypeFlags&INSERT_NUM_TYPE_NO_NUMBERING);
                nPos = 0;
             break;
            case  NumberingType::CHAR_SPECIAL:  bInsert = 0 != (nTypeFlags&INSERT_NUM_TYPE_BULLET); break;
            case  NumberingType::PAGE_DESCRIPTOR:bInsert = 0 != (nTypeFlags&INSERT_NUM_TYPE_PAGE_STYLE_NUMBERING); break;
            case  NumberingType::BITMAP:bInsert = 0 != (nTypeFlags&INSERT_NUM_TYPE_BITMAP ); break;
            default:
                if (nValue >  NumberingType::CHARS_LOWER_LETTER_N)
                {
                    // Insert only if offered by i18n framework per configuration.
                    bInsert = sal_False;
                    if (pTypes)
                    {
                        for(sal_Int32 nType = 0; nType < aTypes.getLength(); nType++)
                        {
                            if (pTypes[nType] == nValue)
                            {
                                bInsert = sal_True;
                                break;  // for
                            }
                        }
                    }
                }
        }
        if(bInsert)
        {
            USHORT nEntry = InsertEntry(rNames.GetString(i), nPos);
            SetEntryData( nEntry, (void*)nValue );
        }
    }
    if(0 != (nTypeFlags&INSERT_NUM_EXTENDED_TYPES) )
    {
        if(pTypes)
        {
            for(sal_Int32 nType = 0; nType < aTypes.getLength(); nType++)
            {
                sal_Int16 nCurrent = pTypes[nType];
                if(nCurrent > NumberingType::CHARS_LOWER_LETTER_N)
                {
                    if(LISTBOX_ENTRY_NOTFOUND == GetEntryPos((void*)(ULONG)nCurrent))
                    {
                        OUString aIdent = pImpl->xInfo->getNumberingIdentifier( nCurrent );
                        USHORT nPos = InsertEntry(aIdent);
                        SetEntryData(nPos,(void*)(ULONG)nCurrent);
                    }
                }
            }
        }
        SelectEntryPos(0);
    }
}
/* -----------------------------01.03.01 14:46--------------------------------

 ---------------------------------------------------------------------------*/
sal_Int16   SwNumberingTypeListBox::GetSelectedNumberingType()
{
    sal_Int16 nRet = 0;
    USHORT nSelPos = GetSelectEntryPos();
    if(LISTBOX_ENTRY_NOTFOUND != nSelPos)
        nRet = (sal_Int16)(ULONG)GetEntryData(nSelPos);
#ifdef DBG_UTIL
    else
        DBG_ERROR("SwNumberingTypeListBox not selected")
#endif
    return nRet;
}
/* -----------------------------01.03.01 14:46--------------------------------

 ---------------------------------------------------------------------------*/
sal_Bool    SwNumberingTypeListBox::SelectNumberingType(sal_Int16 nType)
{
    USHORT nPos = GetEntryPos((void*)(ULONG)nType);
    SelectEntryPos( nPos );
    return LISTBOX_ENTRY_NOTFOUND != nPos;
}

<|endoftext|>