<commit_before>/*
 * PrimeSieve.cpp -- This file is part of primesieve
 *
 * Copyright (C) 2011 Kim Walisch, <kim.walisch@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
 */

#include "PrimeSieve.h"
#include "defs.h"
#include "ParallelPrimeSieve.h"
#include "pmath.h"
#include "ResetSieve.h"
#include "PrimeNumberFinder.h"
#include "PrimeNumberGenerator.h"

#include <stdexcept>
#include <iostream>
#include <string>
#include <vector>
#include <cstdlib>
#include <ctime>

PrimeSieve::PrimeSieve() :
  startNumber_(0), stopNumber_(0),
    sieveSize_(defs::SIEVESIZE_PRIMENUMBERFINDER), flags_(COUNT_PRIMES),
    timeElapsed_(0.0) {
  parent_ = this;
  this->reset();
}

/**
 * Is used by ParallelPrimeSieve which uses multiple PrimeSieve
 * objects and threads to sieve primes in parallel.
 * @see ParallelPrimeSieve::sieve()
 */
PrimeSieve::PrimeSieve(uint64_t startNumber, uint64_t stopNumber,
    ParallelPrimeSieve* parent) :
  sieveSize_(parent->sieveSize_), flags_(parent->flags_), timeElapsed_(0.0),
    callback_imp(parent->callback_imp),
    callback_oop(parent->callback_oop),
    cbObj_(parent->cbObj_),
    parent_(parent) {
  this->setStartNumber(startNumber);
  this->setStopNumber(stopNumber);
  this->reset();
}

uint64_t PrimeSieve::getStartNumber() const {
  return startNumber_;
}

uint64_t PrimeSieve::getStopNumber() const {
  return stopNumber_;
}

uint32_t PrimeSieve::getSieveSize() const {
  return sieveSize_ / 1024;
}

uint32_t PrimeSieve::getFlags() const {
  return flags_;
}

/**
 * Generate the prime numbers between startNumber and stopNumber and
 * call a callback function for each prime.
 */
void PrimeSieve::generatePrimes(uint64_t startNumber, uint64_t stopNumber,
    void (*callback)(uint64_t)) {
  if (callback == NULL)
    throw std::invalid_argument("callback must not be NULL");
  this->setStartNumber(startNumber);
  this->setStopNumber(stopNumber);
  this->setFlags(CALLBACK_PRIMES_IMP);
  callback_imp = callback;
  this->sieve();
}

/**
 * Generate the prime numbers between startNumber and stopNumber and
 * call an OOP style callback function for each prime.
 */
void PrimeSieve::generatePrimes(uint64_t startNumber, uint64_t stopNumber,
    void (*callback)(uint64_t, void*), void* cbObj) {
  if (callback == NULL)
    throw std::invalid_argument("callback must not be NULL");
  this->setStartNumber(startNumber);
  this->setStopNumber(stopNumber);
  this->setFlags(CALLBACK_PRIMES_OOP);
  callback_oop = callback;
  cbObj_ = cbObj;
  this->sieve();
}

/**
 * Get the count of prime numbers between startNumber and stopNumber.
 */
uint64_t PrimeSieve::getPrimeCount(uint64_t startNumber, uint64_t stopNumber) {
  this->setStartNumber(startNumber);
  this->setStopNumber(stopNumber);
  this->setFlags(COUNT_PRIMES);
  this->sieve();
  return this->getPrimeCount();
}

/**
 * Get the count of prime numbers between startNumber and stopNumber
 * after having called sieve().
 */
uint64_t PrimeSieve::getPrimeCount() const {
  return counts_[0];
}

/**
 * Get the count of twin primes between startNumber and stopNumber
 * after having called sieve().
 */
uint64_t PrimeSieve::getTwinCount() const {
  return counts_[1];
}

/**
 * Get the count of prime triplets between startNumber and stopNumber
 * after having called sieve().
 */
uint64_t PrimeSieve::getTripletCount() const {
  return counts_[2];
}

/**
 * Get the count of prime quadruplets between startNumber and
 * stopNumber after having called sieve().
 */
uint64_t PrimeSieve::getQuadrupletCount() const {
  return counts_[3];
}

/**
 * Get the count of prime quintuplets between startNumber and
 * stopNumber after having called sieve().
 */
uint64_t PrimeSieve::getQuintupletCount() const {
  return counts_[4];
}

/**
 * Get the count of prime sextuplets between startNumber and
 * stopNumber after having called sieve().
 */
uint64_t PrimeSieve::getSextupletCount() const {
  return counts_[5];
}

/**
 * Get the count of prime septuplets between startNumber and
 * stopNumber after having called sieve().
 */
uint64_t PrimeSieve::getSeptupletCount() const {
  return counts_[6];
}

/**
 * Get the count of prime numbers or prime k-tuplets between
 * startNumber and stopNumber after having called sieve().
 * e.g type = 0 for prime numbers,
 *     type = 1 for twin primes,
 *     type = 2 for prime triplets,
 *     ...
 * @param type <= 7
 */
uint64_t PrimeSieve::getCounts(uint32_t type) const {
  if (type >= COUNTS_SIZE)
    throw std::out_of_range("getCounts(uint32_t) type out of range");
  return counts_[type];
}

/**
 * Get the time elapsed in seconds of the last sieve session.
 */
double PrimeSieve::getTimeElapsed() const {
  return timeElapsed_;
}

/**
 * Set a start number for sieving.
 * @pre startNumber < (2^64-1) - (2^32-1) * 10
 */
void PrimeSieve::setStartNumber(uint64_t startNumber) {
  // EratBig and EratMedium stopNumber limit
  if (startNumber >= UINT64_MAX - UINT32_MAX * UINT64_C(10))
    throw std::invalid_argument("START must be < (2^64-1) - (2^32-1) * 10");
  startNumber_ = startNumber;
}

/**
 * Set a stop number for sieving.
 * @pre stopNumber < (2^64-1) - (2^32-1) * 10
 */
void PrimeSieve::setStopNumber(uint64_t stopNumber) {
  // EratBig and EratMedium stopNumber limit
  if (stopNumber >= UINT64_MAX - UINT32_MAX * UINT64_C(10))
    throw std::invalid_argument("STOP must be < (2^64-1) - (2^32-1) * 10");
  stopNumber_ = stopNumber;
}

/**
 * Set the size (in KiloBytes) of the sieve of Eratosthenes array.
 * The best performance is achieved with a sieve size that matches
 * the CPU's L1 cache size (usually 32 or 64 KB) when sieving < 10^14
 * and a sieve size of your CPU's L2 cache size above.
 *
 * Default sieveSize = 64 KiloBytes
 *
 * @pre sieveSize must be a power of 2,
 *      sieveSize >= 1 KiloByte,
 *      sieveSize <= 8192 KiloBytes.
 */
void PrimeSieve::setSieveSize(uint32_t sieveSize) {
  // SieveOfEratosthenes lower sieve size limit AND
  // EratBig upper sieveSize limit
  if (sieveSize < 1 || sieveSize > 8192)
    throw std::invalid_argument("sieve size must be >= 1 and <= 8192 KiloBytes");
  // EratBig requires a power of 2 sieve size
  if (!isPowerOf2(sieveSize))
    throw std::invalid_argument("sieve size must be a power of 2");
  // convert to Bytes
  sieveSize_ = sieveSize * 1024;
}

/**
 * Set the flags (settings) of PrimeSieve.
 * @param flags
 *   COUNT_PRIMES      OR (bitwise '|')
 *   COUNT_TWINS       OR
 *   COUNT_TRIPLETS    OR
 *   COUNT_QUADRUPLETS OR
 *   COUNT_QUINTUPLETS OR
 *   COUNT_SEXTUPLETS  OR
 *   COUNT_SEPTUPLETS  OR
 *   PRINT_PRIMES      OR
 *   PRINT_TWINS       OR
 *   PRINT_TRIPLETS    OR
 *   PRINT_QUADRUPLETS OR
 *   PRINT_QUINTUPLETS OR
 *   PRINT_SEXTUPLETS  OR
 *   PRINT_SEPTUPLETS  OR
 *   PRINT_STATUS.
 */
void PrimeSieve::setFlags(uint32_t flags) {
  flags_ = flags;
}

void PrimeSieve::reset() {
  segments_ = 0;
  for (uint32_t i = 0; i < COUNTS_SIZE; i++)
    counts_[i] = 0;
  status_ = -1.0;
  parent_->doStatus(0);
}

/**
 * Print the status (in percent) of the sieving process
 * to the standard output.
 */
void PrimeSieve::doStatus(uint64_t segment) {
  segments_ += segment;
  double old = status_;
  status_ = static_cast<double> (segments_) /
            static_cast<double> (1 + stopNumber_ - startNumber_) * 100.0;
  if (static_cast<int> (status_) > 99)
    status_ = 100.0;
  if ((flags_ & PRINT_STATUS) &&
      static_cast<int> (status_) > static_cast<int> (old)) {
    std::cout << '\r' << static_cast<int> (status_) << '%' << std::flush;
  }
}

void PrimeSieve::doSmallPrime(uint32_t low, uint32_t high, uint32_t type,
    std::string prime) {
  if (startNumber_ <= low && stopNumber_ >= high) {
    if (flags_ & (COUNT_PRIMES << type))
      counts_[type]++;
    if (flags_ & (PRINT_PRIMES << type))
      std::cout << prime << std::endl;
    else if (flags_ & CALLBACK_PRIMES_IMP)
      this->callback_imp(prime[0]-'0');
    else if (flags_ & CALLBACK_PRIMES_OOP)
      this->callback_oop(prime[0]-'0', cbObj_);
  }
}

/**
 * Sieve the prime numbers and/or prime k-tuplets between startNumber
 * and stopNumber.
 */
void PrimeSieve::sieve() {
  if (stopNumber_ < startNumber_)
    throw std::invalid_argument("STOP must be >= START");
  timeElapsed_ = static_cast<double> (std::clock());
  this->reset();

  // small primes have to be examined manually
  if (startNumber_ <= 5) {
    this->doSmallPrime(2,  2, 0, "2");
    this->doSmallPrime(3,  3, 0, "3");
    this->doSmallPrime(5,  5, 0, "5");
    this->doSmallPrime(3,  5, 1, "(3, 5)");
    this->doSmallPrime(5,  7, 1, "(5, 7)");
    this->doSmallPrime(5, 11, 2, "(5, 7, 11)");
    this->doSmallPrime(5, 13, 3, "(5, 7, 11, 13)");
    this->doSmallPrime(5, 17, 4, "(5, 7, 11, 13, 17)");
  }

  if (stopNumber_ >= 7) {
    // needed by primeNumberGenerator and primeNumberFinder to
    // reset their sieve arrays
    ResetSieve resetSieve(this);
    // used to sieve the prime numbers and prime k-tuplets between
    // startNumber_ and stopNumber_
    PrimeNumberFinder primeNumberFinder(this, resetSieve);

    if (isqrt(stopNumber_) > resetSieve.getEliminateUpTo()) {
      // used to generate the prime numbers up to sqrt(stopNumber_)
      // needed for sieving by primeNumberFinder
      PrimeNumberGenerator primeNumberGenerator(&primeNumberFinder);
      std::vector<uint32_t> primes16Bit;
      primes16Bit.push_back(3);
      uint32_t stop = isqrt(primeNumberGenerator.getStopNumber());
      uint32_t keep = isqrt(stop);
      // the following trial division algorithm is used to generate the
      // prime numbers up to stopNumber_^0.25 needed for sieving by
      // primeNumberGenerator. Although the algorithm is never
      // used > 65536 it finds the prime numbers up to 10^7 in 1 second
      // on an Intel Core i5-670 3.46GHz
      for (uint32_t n = 5; n <= stop; n += 2) {
        uint32_t s = isqrt(n);
        uint32_t i = 0;
        for (; primes16Bit[i] <= s && (n % primes16Bit[i]) != 0; i++)
          ;
        if (primes16Bit[i] > s) {
          if (primes16Bit[i] <= keep)
            primes16Bit.push_back(n);
          if (n > resetSieve.getEliminateUpTo())
            // generate the prime numbers up to n^2 and call
            // primeNumberFinder.sieve(p) for each generated prime
            primeNumberGenerator.sieve(n);
        }
      }
      primeNumberGenerator.finish();
    }
    primeNumberFinder.finish();
  }

  // set status_ to 100.0 (percent)
  parent_->doStatus(10);
  timeElapsed_ = (static_cast<double> (std::clock()) - timeElapsed_) /
      static_cast<double> (CLOCKS_PER_SEC);
}
<commit_msg>ResetSieve API has changed<commit_after>/*
 * PrimeSieve.cpp -- This file is part of primesieve
 *
 * Copyright (C) 2011 Kim Walisch, <kim.walisch@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
 */

#include "PrimeSieve.h"
#include "defs.h"
#include "ParallelPrimeSieve.h"
#include "pmath.h"
#include "ResetSieve.h"
#include "PrimeNumberFinder.h"
#include "PrimeNumberGenerator.h"

#include <stdexcept>
#include <iostream>
#include <string>
#include <vector>
#include <cstdlib>
#include <ctime>

PrimeSieve::PrimeSieve() :
  startNumber_(0), stopNumber_(0),
    sieveSize_(defs::SIEVESIZE_PRIMENUMBERFINDER), flags_(COUNT_PRIMES),
    timeElapsed_(0.0) {
  parent_ = this;
  this->reset();
}

/**
 * Is used by ParallelPrimeSieve which uses multiple PrimeSieve
 * objects and threads to sieve primes in parallel.
 * @see ParallelPrimeSieve::sieve()
 */
PrimeSieve::PrimeSieve(uint64_t startNumber, uint64_t stopNumber,
    ParallelPrimeSieve* parent) :
  sieveSize_(parent->sieveSize_), flags_(parent->flags_), timeElapsed_(0.0),
    callback_imp(parent->callback_imp),
    callback_oop(parent->callback_oop),
    cbObj_(parent->cbObj_),
    parent_(parent) {
  this->setStartNumber(startNumber);
  this->setStopNumber(stopNumber);
  this->reset();
}

uint64_t PrimeSieve::getStartNumber() const {
  return startNumber_;
}

uint64_t PrimeSieve::getStopNumber() const {
  return stopNumber_;
}

uint32_t PrimeSieve::getSieveSize() const {
  return sieveSize_ / 1024;
}

uint32_t PrimeSieve::getFlags() const {
  return flags_;
}

/**
 * Generate the prime numbers between startNumber and stopNumber and
 * call a callback function for each prime.
 */
void PrimeSieve::generatePrimes(uint64_t startNumber, uint64_t stopNumber,
    void (*callback)(uint64_t)) {
  if (callback == NULL)
    throw std::invalid_argument("callback must not be NULL");
  this->setStartNumber(startNumber);
  this->setStopNumber(stopNumber);
  this->setFlags(CALLBACK_PRIMES_IMP);
  callback_imp = callback;
  this->sieve();
}

/**
 * Generate the prime numbers between startNumber and stopNumber and
 * call an OOP style callback function for each prime.
 */
void PrimeSieve::generatePrimes(uint64_t startNumber, uint64_t stopNumber,
    void (*callback)(uint64_t, void*), void* cbObj) {
  if (callback == NULL)
    throw std::invalid_argument("callback must not be NULL");
  this->setStartNumber(startNumber);
  this->setStopNumber(stopNumber);
  this->setFlags(CALLBACK_PRIMES_OOP);
  callback_oop = callback;
  cbObj_ = cbObj;
  this->sieve();
}

/**
 * Get the count of prime numbers between startNumber and stopNumber.
 */
uint64_t PrimeSieve::getPrimeCount(uint64_t startNumber, uint64_t stopNumber) {
  this->setStartNumber(startNumber);
  this->setStopNumber(stopNumber);
  this->setFlags(COUNT_PRIMES);
  this->sieve();
  return this->getPrimeCount();
}

/**
 * Get the count of prime numbers between startNumber and stopNumber
 * after having called sieve().
 */
uint64_t PrimeSieve::getPrimeCount() const {
  return counts_[0];
}

/**
 * Get the count of twin primes between startNumber and stopNumber
 * after having called sieve().
 */
uint64_t PrimeSieve::getTwinCount() const {
  return counts_[1];
}

/**
 * Get the count of prime triplets between startNumber and stopNumber
 * after having called sieve().
 */
uint64_t PrimeSieve::getTripletCount() const {
  return counts_[2];
}

/**
 * Get the count of prime quadruplets between startNumber and
 * stopNumber after having called sieve().
 */
uint64_t PrimeSieve::getQuadrupletCount() const {
  return counts_[3];
}

/**
 * Get the count of prime quintuplets between startNumber and
 * stopNumber after having called sieve().
 */
uint64_t PrimeSieve::getQuintupletCount() const {
  return counts_[4];
}

/**
 * Get the count of prime sextuplets between startNumber and
 * stopNumber after having called sieve().
 */
uint64_t PrimeSieve::getSextupletCount() const {
  return counts_[5];
}

/**
 * Get the count of prime septuplets between startNumber and
 * stopNumber after having called sieve().
 */
uint64_t PrimeSieve::getSeptupletCount() const {
  return counts_[6];
}

/**
 * Get the count of prime numbers or prime k-tuplets between
 * startNumber and stopNumber after having called sieve().
 * e.g type = 0 for prime numbers,
 *     type = 1 for twin primes,
 *     type = 2 for prime triplets,
 *     ...
 * @param type <= 7
 */
uint64_t PrimeSieve::getCounts(uint32_t type) const {
  if (type >= COUNTS_SIZE)
    throw std::out_of_range("getCounts(uint32_t) type out of range");
  return counts_[type];
}

/**
 * Get the time elapsed in seconds of the last sieve session.
 */
double PrimeSieve::getTimeElapsed() const {
  return timeElapsed_;
}

/**
 * Set a start number for sieving.
 * @pre startNumber < (2^64-1) - (2^32-1) * 10
 */
void PrimeSieve::setStartNumber(uint64_t startNumber) {
  // EratBig and EratMedium stopNumber limit
  if (startNumber >= UINT64_MAX - UINT32_MAX * UINT64_C(10))
    throw std::invalid_argument("START must be < (2^64-1) - (2^32-1) * 10");
  startNumber_ = startNumber;
}

/**
 * Set a stop number for sieving.
 * @pre stopNumber < (2^64-1) - (2^32-1) * 10
 */
void PrimeSieve::setStopNumber(uint64_t stopNumber) {
  // EratBig and EratMedium stopNumber limit
  if (stopNumber >= UINT64_MAX - UINT32_MAX * UINT64_C(10))
    throw std::invalid_argument("STOP must be < (2^64-1) - (2^32-1) * 10");
  stopNumber_ = stopNumber;
}

/**
 * Set the size (in KiloBytes) of the sieve of Eratosthenes array.
 * The best performance is achieved with a sieve size that matches
 * the CPU's L1 cache size (usually 32 or 64 KB) when sieving < 10^14
 * and a sieve size of your CPU's L2 cache size above.
 *
 * Default sieveSize = 64 KiloBytes
 *
 * @pre sieveSize must be a power of 2,
 *      sieveSize >= 1 KiloByte,
 *      sieveSize <= 8192 KiloBytes.
 */
void PrimeSieve::setSieveSize(uint32_t sieveSize) {
  // SieveOfEratosthenes lower sieve size limit AND
  // EratBig upper sieveSize limit
  if (sieveSize < 1 || sieveSize > 8192)
    throw std::invalid_argument("sieve size must be >= 1 and <= 8192 KiloBytes");
  // EratBig requires a power of 2 sieve size
  if (!isPowerOf2(sieveSize))
    throw std::invalid_argument("sieve size must be a power of 2");
  // convert to Bytes
  sieveSize_ = sieveSize * 1024;
}

/**
 * Set the flags (settings) of PrimeSieve.
 * @param flags
 *   COUNT_PRIMES      OR (bitwise '|')
 *   COUNT_TWINS       OR
 *   COUNT_TRIPLETS    OR
 *   COUNT_QUADRUPLETS OR
 *   COUNT_QUINTUPLETS OR
 *   COUNT_SEXTUPLETS  OR
 *   COUNT_SEPTUPLETS  OR
 *   PRINT_PRIMES      OR
 *   PRINT_TWINS       OR
 *   PRINT_TRIPLETS    OR
 *   PRINT_QUADRUPLETS OR
 *   PRINT_QUINTUPLETS OR
 *   PRINT_SEXTUPLETS  OR
 *   PRINT_SEPTUPLETS  OR
 *   PRINT_STATUS.
 */
void PrimeSieve::setFlags(uint32_t flags) {
  flags_ = flags;
}

void PrimeSieve::reset() {
  segments_ = 0;
  for (uint32_t i = 0; i < COUNTS_SIZE; i++)
    counts_[i] = 0;
  status_ = -1.0;
  parent_->doStatus(0);
}

/**
 * Print the status (in percent) of the sieving process
 * to the standard output.
 */
void PrimeSieve::doStatus(uint64_t segment) {
  segments_ += segment;
  double old = status_;
  status_ = static_cast<double> (segments_) /
            static_cast<double> (1 + stopNumber_ - startNumber_) * 100.0;
  if (static_cast<int> (status_) > 99)
    status_ = 100.0;
  if ((flags_ & PRINT_STATUS) &&
      static_cast<int> (status_) > static_cast<int> (old)) {
    std::cout << '\r' << static_cast<int> (status_) << '%' << std::flush;
  }
}

void PrimeSieve::doSmallPrime(uint32_t low, uint32_t high, uint32_t type,
    std::string prime) {
  if (startNumber_ <= low && stopNumber_ >= high) {
    if (flags_ & (COUNT_PRIMES << type))
      counts_[type]++;
    if (flags_ & (PRINT_PRIMES << type))
      std::cout << prime << std::endl;
    else if (flags_ & CALLBACK_PRIMES_IMP)
      this->callback_imp(prime[0]-'0');
    else if (flags_ & CALLBACK_PRIMES_OOP)
      this->callback_oop(prime[0]-'0', cbObj_);
  }
}

/**
 * Sieve the prime numbers and/or prime k-tuplets between startNumber
 * and stopNumber.
 */
void PrimeSieve::sieve() {
  if (stopNumber_ < startNumber_)
    throw std::invalid_argument("STOP must be >= START");
  timeElapsed_ = static_cast<double> (std::clock());
  this->reset();

  // small primes have to be examined manually
  if (startNumber_ <= 5) {
    this->doSmallPrime(2,  2, 0, "2");
    this->doSmallPrime(3,  3, 0, "3");
    this->doSmallPrime(5,  5, 0, "5");
    this->doSmallPrime(3,  5, 1, "(3, 5)");
    this->doSmallPrime(5,  7, 1, "(5, 7)");
    this->doSmallPrime(5, 11, 2, "(5, 7, 11)");
    this->doSmallPrime(5, 13, 3, "(5, 7, 11, 13)");
    this->doSmallPrime(5, 17, 4, "(5, 7, 11, 13, 17)");
  }

  if (stopNumber_ >= 7) {
    // needed by primeNumberGenerator and primeNumberFinder to
    // reset their sieve arrays
    ResetSieve resetSieve(this);
    // used to sieve the prime numbers and prime k-tuplets between
    // startNumber_ and stopNumber_
    PrimeNumberFinder primeNumberFinder(this, resetSieve);

    if (isqrt(stopNumber_) > resetSieve.getLimit()) {
      // used to generate the prime numbers up to sqrt(stopNumber_)
      // needed for sieving by primeNumberFinder
      PrimeNumberGenerator primeNumberGenerator(&primeNumberFinder);
      std::vector<uint32_t> primes16Bit;
      primes16Bit.push_back(3);
      uint32_t stop = isqrt(primeNumberGenerator.getStopNumber());
      uint32_t keep = isqrt(stop);
      // the following trial division algorithm is used to generate the
      // prime numbers up to stopNumber_^0.25 needed for sieving by
      // primeNumberGenerator. Although the algorithm is never
      // used > 65536 it finds the prime numbers up to 10^7 in 1 second
      // on an Intel Core i5-670 3.46GHz
      for (uint32_t n = 5; n <= stop; n += 2) {
        uint32_t s = isqrt(n);
        uint32_t i = 0;
        for (; primes16Bit[i] <= s && (n % primes16Bit[i]) != 0; i++)
          ;
        if (primes16Bit[i] > s) {
          if (primes16Bit[i] <= keep)
            primes16Bit.push_back(n);
          if (n > resetSieve.getLimit())
            // generate the prime numbers up to n^2 and call
            // primeNumberFinder.sieve(p) for each generated prime
            primeNumberGenerator.sieve(n);
        }
      }
      primeNumberGenerator.finish();
    }
    primeNumberFinder.finish();
  }

  // set status_ to 100.0 (percent)
  parent_->doStatus(10);
  timeElapsed_ = (static_cast<double> (std::clock()) - timeElapsed_) /
      static_cast<double> (CLOCKS_PER_SEC);
}
<|endoftext|>


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

#ifndef _FRM_EVENT_THREAD_HXX_
#include "EventThread.hxx"
#endif

#ifndef _TOOLS_DEBUG_HXX //autogen
#include <tools/debug.hxx>
#endif

//.........................................................................
namespace frm
{
//.........................................................................
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::awt;
using namespace ::com::sun::star::lang;

DBG_NAME( OComponentEventThread );
OComponentEventThread::OComponentEventThread( ::cppu::OComponentHelper* pCompImpl ) :
    m_pCompImpl( pCompImpl )
{
    DBG_CTOR( OComponentEventThread, NULL );

    increment(m_refCount);

    // Eine Referenz des Controls halten
    {
        InterfaceRef xIFace(static_cast<XWeak*>(pCompImpl));
        query_interface(xIFace, m_xComp);
    }

    // und uns an dem Control anmelden
    {
        Reference<XEventListener> xEvtLstnr = static_cast<XEventListener*>(this);
        m_xComp->addEventListener( xEvtLstnr );
    }

    decrement(m_refCount);
}

OComponentEventThread::~OComponentEventThread()
{
    DBG_DTOR( OComponentEventThread, NULL );

    DBG_ASSERT( m_aEvents.size() == 0,
        "OComponentEventThread::~OComponentEventThread: Kein dispose gerufen?" );
    while (m_aEvents.size())
        delete *m_aEvents.erase(m_aEvents.begin());
}

Any SAL_CALL OComponentEventThread::queryInterface(const Type& _rType) throw (RuntimeException)
{
    Any aReturn;

    aReturn = OWeakObject::queryInterface(_rType);

    if (!aReturn.hasValue())
        aReturn = ::cppu::queryInterface(_rType,
            static_cast<XEventListener*>(this)
        );

    return aReturn;
}

void OComponentEventThread::disposing( const EventObject& evt )
{
    if( evt.Source == m_xComp )
    {
        ::osl::MutexGuard aGuard( m_aMutex );

        // Event-Listener abmelden
        Reference<XEventListener>  xEvtLstnr = static_cast<XEventListener*>(this);
        m_xComp->removeEventListener( xEvtLstnr );

        // Event-Queue loeschen
        while (m_aEvents.size())
            delete *m_aEvents.erase(m_aEvents.begin());
        m_aControls.erase(m_aControls.begin(), m_aControls.end());
        m_aFlags.erase(m_aFlags.begin(), m_aFlags.end());

        // Das Control loslassen und pCompImpl auf 0 setzen, damit der
        // Thread weiss, dass er sich beenden soll.
        m_xComp = 0;
        m_pCompImpl = 0;

        // Den Thread aufwecken und beenden.
        m_aCond.set();
        terminate();
    }
}

void OComponentEventThread::addEvent( const EventObject* _pEvt, sal_Bool bFlag )
{
    Reference<XControl>  xTmp;
    addEvent( _pEvt, xTmp, bFlag );
}

void OComponentEventThread::addEvent( const EventObject* _pEvt,
                                   const Reference<XControl>& rControl,
                                   sal_Bool bFlag )
{
    ::osl::MutexGuard aGuard( m_aMutex );

    // Daten in die Queue stellen
    m_aEvents.push_back( cloneEvent( _pEvt ) );

    Reference<XWeak>        xWeakControl(rControl, UNO_QUERY);
    Reference<XAdapter> xControlAdapter = xWeakControl.is() ? xWeakControl->queryAdapter() : Reference<XAdapter>();
    m_aControls.push_back( xControlAdapter );

    m_aFlags.push_back( bFlag );

    // Thread aufwecken
    m_aCond.set();
}

//---------------------------------------------------------------------
//--- 22.08.01 15:48:15 -----------------------------------------------

void OComponentEventThread::implStarted( )
{
    acquire( );
}

//---------------------------------------------------------------------
//--- 22.08.01 15:48:16 -----------------------------------------------

void OComponentEventThread::implTerminated( )
{
    release( );
}

//---------------------------------------------------------------------
//--- 22.08.01 15:47:31 -----------------------------------------------

void SAL_CALL OComponentEventThread::kill()
{
    OComponentEventThread_TBASE::kill();

    implTerminated( );
}

//---------------------------------------------------------------------
//--- 22.08.01 15:47:33 -----------------------------------------------

void SAL_CALL OComponentEventThread::onTerminated()
{
    OComponentEventThread_TBASE::onTerminated();

    implTerminated( );
}

void OComponentEventThread::run()
{
    implStarted( );

    // uns selbst festhalten, damit wir nicht geloescht werden,
    // wenn zwischendrinne mal ein dispose gerufen wird.
    InterfaceRef xThis(static_cast<XWeak*>(this));

    do
    {
        ::osl::MutexGuard aGuard(m_aMutex);

        while( m_aEvents.size() > 0 )
        {
            // Das Control holen und festhalten, damit es waehrend des
            // actionPerformed nicht geloescht werden kann.
            Reference<XComponent>  xComp = m_xComp;
            ::cppu::OComponentHelper *pCompImpl = m_pCompImpl;

            EventObject* pEvt = *m_aEvents.erase( m_aEvents.begin() );
            Reference<XAdapter> xControlAdapter = *m_aControls.erase( m_aControls.begin() );
            sal_Bool bFlag = *m_aFlags.erase( m_aFlags.begin() );

            {
                MutexRelease aReleaseOnce(m_aMutex);
                // Weil ein queryHardRef eine Exception schmeissen kann sollte
                // es nicht bei gelocktem Mutex aufgerufen werden.
                Reference<XControl>  xControl;
                if ( xControlAdapter.is() )
                    query_interface(xControlAdapter->queryAdapted(), xControl);

                if( xComp.is() )
                    processEvent( pCompImpl, pEvt, xControl, bFlag );
            }

            delete pEvt;
        };

        // Nach einem dispose kennen wir das Control nicht mehr. Dann darf
        // auch nicht gewartet werden.
        if( !m_xComp.is() )
            return;

        // Warte-Bedingung zuruecksetzen
        m_aCond.reset();
        {
            MutexRelease aReleaseOnce(m_aMutex);
            // und warten ... falls nicht zwischenzeitlich doch noch ein
            // Event eingetroffen ist.
            m_aCond.wait();
        }
    }
    while( sal_True );
}

//.........................................................................
}   // namespace frm
//.........................................................................

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

#ifndef _FRM_EVENT_THREAD_HXX_
#include "EventThread.hxx"
#endif

#ifndef _TOOLS_DEBUG_HXX //autogen
#include <tools/debug.hxx>
#endif

//.........................................................................
namespace frm
{
//.........................................................................
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::awt;
using namespace ::com::sun::star::lang;

DBG_NAME( OComponentEventThread )
OComponentEventThread::OComponentEventThread( ::cppu::OComponentHelper* pCompImpl ) :
    m_pCompImpl( pCompImpl )
{
    DBG_CTOR( OComponentEventThread, NULL );

    increment(m_refCount);

    // Eine Referenz des Controls halten
    {
        InterfaceRef xIFace(static_cast<XWeak*>(pCompImpl));
        query_interface(xIFace, m_xComp);
    }

    // und uns an dem Control anmelden
    {
        Reference<XEventListener> xEvtLstnr = static_cast<XEventListener*>(this);
        m_xComp->addEventListener( xEvtLstnr );
    }

    decrement(m_refCount);
}

OComponentEventThread::~OComponentEventThread()
{
    DBG_DTOR( OComponentEventThread, NULL );

    DBG_ASSERT( m_aEvents.size() == 0,
        "OComponentEventThread::~OComponentEventThread: Kein dispose gerufen?" );
    while (m_aEvents.size())
        delete *m_aEvents.erase(m_aEvents.begin());
}

Any SAL_CALL OComponentEventThread::queryInterface(const Type& _rType) throw (RuntimeException)
{
    Any aReturn;

    aReturn = OWeakObject::queryInterface(_rType);

    if (!aReturn.hasValue())
        aReturn = ::cppu::queryInterface(_rType,
            static_cast<XEventListener*>(this)
        );

    return aReturn;
}

void OComponentEventThread::disposing( const EventObject& evt )
{
    if( evt.Source == m_xComp )
    {
        ::osl::MutexGuard aGuard( m_aMutex );

        // Event-Listener abmelden
        Reference<XEventListener>  xEvtLstnr = static_cast<XEventListener*>(this);
        m_xComp->removeEventListener( xEvtLstnr );

        // Event-Queue loeschen
        while (m_aEvents.size())
            delete *m_aEvents.erase(m_aEvents.begin());
        m_aControls.erase(m_aControls.begin(), m_aControls.end());
        m_aFlags.erase(m_aFlags.begin(), m_aFlags.end());

        // Das Control loslassen und pCompImpl auf 0 setzen, damit der
        // Thread weiss, dass er sich beenden soll.
        m_xComp = 0;
        m_pCompImpl = 0;

        // Den Thread aufwecken und beenden.
        m_aCond.set();
        terminate();
    }
}

void OComponentEventThread::addEvent( const EventObject* _pEvt, sal_Bool bFlag )
{
    Reference<XControl>  xTmp;
    addEvent( _pEvt, xTmp, bFlag );
}

void OComponentEventThread::addEvent( const EventObject* _pEvt,
                                   const Reference<XControl>& rControl,
                                   sal_Bool bFlag )
{
    ::osl::MutexGuard aGuard( m_aMutex );

    // Daten in die Queue stellen
    m_aEvents.push_back( cloneEvent( _pEvt ) );

    Reference<XWeak>        xWeakControl(rControl, UNO_QUERY);
    Reference<XAdapter> xControlAdapter = xWeakControl.is() ? xWeakControl->queryAdapter() : Reference<XAdapter>();
    m_aControls.push_back( xControlAdapter );

    m_aFlags.push_back( bFlag );

    // Thread aufwecken
    m_aCond.set();
}

//---------------------------------------------------------------------
//--- 22.08.01 15:48:15 -----------------------------------------------

void OComponentEventThread::implStarted( )
{
    acquire( );
}

//---------------------------------------------------------------------
//--- 22.08.01 15:48:16 -----------------------------------------------

void OComponentEventThread::implTerminated( )
{
    release( );
}

//---------------------------------------------------------------------
//--- 22.08.01 15:47:31 -----------------------------------------------

void SAL_CALL OComponentEventThread::kill()
{
    OComponentEventThread_TBASE::kill();

    implTerminated( );
}

//---------------------------------------------------------------------
//--- 22.08.01 15:47:33 -----------------------------------------------

void SAL_CALL OComponentEventThread::onTerminated()
{
    OComponentEventThread_TBASE::onTerminated();

    implTerminated( );
}

void OComponentEventThread::run()
{
    implStarted( );

    // uns selbst festhalten, damit wir nicht geloescht werden,
    // wenn zwischendrinne mal ein dispose gerufen wird.
    InterfaceRef xThis(static_cast<XWeak*>(this));

    do
    {
        ::osl::MutexGuard aGuard(m_aMutex);

        while( m_aEvents.size() > 0 )
        {
            // Das Control holen und festhalten, damit es waehrend des
            // actionPerformed nicht geloescht werden kann.
            Reference<XComponent>  xComp = m_xComp;
            ::cppu::OComponentHelper *pCompImpl = m_pCompImpl;

            EventObject* pEvt = *m_aEvents.erase( m_aEvents.begin() );
            Reference<XAdapter> xControlAdapter = *m_aControls.erase( m_aControls.begin() );
            sal_Bool bFlag = *m_aFlags.erase( m_aFlags.begin() );

            {
                MutexRelease aReleaseOnce(m_aMutex);
                // Weil ein queryHardRef eine Exception schmeissen kann sollte
                // es nicht bei gelocktem Mutex aufgerufen werden.
                Reference<XControl>  xControl;
                if ( xControlAdapter.is() )
                    query_interface(xControlAdapter->queryAdapted(), xControl);

                if( xComp.is() )
                    processEvent( pCompImpl, pEvt, xControl, bFlag );
            }

            delete pEvt;
        };

        // Nach einem dispose kennen wir das Control nicht mehr. Dann darf
        // auch nicht gewartet werden.
        if( !m_xComp.is() )
            return;

        // Warte-Bedingung zuruecksetzen
        m_aCond.reset();
        {
            MutexRelease aReleaseOnce(m_aMutex);
            // und warten ... falls nicht zwischenzeitlich doch noch ein
            // Event eingetroffen ist.
            m_aCond.wait();
        }
    }
    while( sal_True );
}

//.........................................................................
}   // namespace frm
//.........................................................................

<|endoftext|>


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

#ifndef __FRAMEWORK_DISPATCH_INTERACTION_HXX_
#define __FRAMEWORK_DISPATCH_INTERACTION_HXX_

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_TASK_XINTERACTIONREQUEST_HPP_
#include <com/sun/star/task/XInteractionRequest.hpp>
#endif

#ifndef _COM_SUN_STAR_TASK_XINTERACTIONCONTINUATION_HPP_
#include <com/sun/star/task/XInteractionContinuation.hpp>
#endif

#ifndef _COM_SUN_STAR_TASK_XINTERACTIONABORT_HPP_
#include <com/sun/star/task/XInteractionAbort.hpp>
#endif

#ifndef _COM_SUN_STAR_TASK_XINTERACTIONAPPROVE_HPP_
#include <com/sun/star/task/XInteractionApprove.hpp>
#endif

#ifndef _COM_SUN_STAR_TASK_XINTERACTIONDISAPPROVE_HPP_
#include <com/sun/star/task/XInteractionDisapprove.hpp>
#endif

#ifndef _COM_SUN_STAR_TASK_XINTERACTIONRETRY_HPP_
#include <com/sun/star/task/XInteractionRetry.hpp>
#endif

#ifndef _COM_SUN_STAR_DOCUMENT_XINTERACTIONFILTERSELECT_HPP_
#include <com/sun/star/document/XInteractionFilterSelect.hpp>
#endif

#ifndef _COM_SUN_STAR_DOCUMENT_NOSUCHFILTERREQUEST_HPP_
#include <com/sun/star/document/NoSuchFilterRequest.hpp>
#endif

#ifndef _COM_SUN_STAR_DOCUMENT_AMBIGOUSFILTERREQUEST_HPP_
#include <com/sun/star/document/AmbigousFilterRequest.hpp>
#endif

#ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HPP_
#include <com/sun/star/uno/RuntimeException.hpp>
#endif

//_________________________________________________________________________________________________________________
//  includes of other projects
//_________________________________________________________________________________________________________________

#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif

#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif

#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif

#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif

//_________________________________________________________________________________________________________________
//  namespace
//_________________________________________________________________________________________________________________

namespace framework{

//_________________________________________________________________________________________________________________
//  non exported const
//_________________________________________________________________________________________________________________

//_________________________________________________________________________________________________________________
//  non exported definitions
//_________________________________________________________________________________________________________________

//_________________________________________________________________________________________________________________
//  declarations
//_________________________________________________________________________________________________________________

/*-************************************************************************************************************//**
    @short          base for continuation classes
    @descr          An interaction continuation could be used on XInteractionHandler/XInteractionRequest
                    to abort or react for it.
                    Base functionality is everytime the same - handler mark right continuation by calling
                    interface method "select()". User of interaction can detect it by testing c++ method "isSelected()"!
                    Superclasses can add additional interfaces or methods to support additional features ...
                    but selection of it is supported here!

    @implements     XInterface
                    XTypeProvider (supported by WeakImplHelper!)
                    XInteractionContinuation

    @base           WeakImplHelper1

    @devstatus      ready to use
    @threadsafe     no (used on once position only!)
*//*-*************************************************************************************************************/
template< class TContinuationType >
class ContinuationBase : public ::cppu::WeakImplHelper1< TContinuationType >
{
    // c++ interface
    public:

        //---------------------------------------------------------------------------------------------------------
        // initialize continuation with right start values
        //---------------------------------------------------------------------------------------------------------
        ContinuationBase()
            :   m_bSelected( sal_False )
        {
        }

        //---------------------------------------------------------------------------------------------------------
        // was continuation selected by handler?
        //---------------------------------------------------------------------------------------------------------
        sal_Bool isSelected() const
        {
            return m_bSelected;
        }

        //---------------------------------------------------------------------------------------------------------
        // make using more then once possible
        //---------------------------------------------------------------------------------------------------------
        void reset()
        {
            m_bSelected = sal_False;
        }

    // uno interface
    public:

        //---------------------------------------------------------------------------------------------------------
        // called by handler to mark continuation as the only possible solution for started interaction
        //---------------------------------------------------------------------------------------------------------
        virtual void SAL_CALL select() throw( ::com::sun::star::uno::RuntimeException )
        {
            m_bSelected = sal_True;
        }

    // member
    private:

        sal_Bool m_bSelected;

};  // class ContinuationBase

/*-************************************************************************************************************//**
    @short          declaration of some simple continuations
    @descr          These derived classes implements some simple continuations, which doesnt need and additional
                    interfaces or methods. Her selected state is the only neccessary feature. User of it can
                    distinguish by type between different functionality!

    @implements     -

    @base           ContinuationBase

    @devstatus      ready to use
    @threadsafe     no (used on once position only!)
*//*-*************************************************************************************************************/
typedef ContinuationBase< ::com::sun::star::task::XInteractionAbort > ContinuationAbort;
typedef ContinuationBase< ::com::sun::star::task::XInteractionApprove > ContinuationApprove;
typedef ContinuationBase< ::com::sun::star::task::XInteractionDisapprove > ContinuationDisapprove;
typedef ContinuationBase< ::com::sun::star::task::XInteractionRetry > ContinuationRetry;

/*-************************************************************************************************************//**
    @short          declaration of special continuation for filter selection
    @descr          Sometimes filter detection during loading document failed. Then we need a possibility
                    to ask user for his decision. These continuation transport selected filter by user to
                    code user of interaction.

    @attention      This implementation could be used one times only. We don't support a resetable continuation yet!
                    Why? Normaly interaction should show a filter selection dialog and ask user for his decision.
                    He can select any filter - then instances of these class will be called by handler ... or user
                    close dialog without any selection. Then another continuation should be slected by handler to
                    abort continuations ... Retrying isn't very usefull here ... I think.

    @implements     XInteractionFilterSelect

    @base           ImplInheritanceHelper1
                    ContinuationBase

    @devstatus      ready to use
    @threadsafe     no (used on once position only!)
*//*-*************************************************************************************************************/
class ContinuationFilterSelect : public ContinuationBase< ::com::sun::star::document::XInteractionFilterSelect >
{
    // c++ interface
    public:
        ContinuationFilterSelect();

    // uno interface
    public:
        virtual void            SAL_CALL setFilter( const ::rtl::OUString& sFilter ) throw( ::com::sun::star::uno::RuntimeException );
        virtual ::rtl::OUString SAL_CALL getFilter(                                ) throw( ::com::sun::star::uno::RuntimeException );

    // member
    private:
        ::rtl::OUString m_sFilter;

};  // class ContinuationFilterSelect

/*-************************************************************************************************************//**
    @short          special request for interaction to ask user for right filter
    @descr          These helper can be used to ask user for right filter, if filter detection failed.
                    It capsulate communication with any interaction handler and supports an easy
                    access on interaction results for user of these class.
                    Use it and forget complex mechanism of interaction ...

    @example        RequestFilterSelect*             pRequest = new RequestFilterSelect;
                    Reference< XInteractionRequest > xRequest ( pRequest );
                    xInteractionHandler->handle( xRequest );
                    if( ! pRequest.isAbort() )
                    {
                        OUString sFilter = pRequest->getFilter();
                    }

    @implements     XInteractionRequest

    @base           WeakImplHelper1

    @devstatus      ready to use
    @threadsafe     no (used on once position only!)
*//*-*************************************************************************************************************/
class RequestFilterSelect : public ::cppu::WeakImplHelper1< ::com::sun::star::task::XInteractionRequest >
{
    // c++ interface
    public:
        RequestFilterSelect( const ::rtl::OUString& sURL );
        sal_Bool        isAbort  () const;
        ::rtl::OUString getFilter() const;

    // uno interface
    public:
        virtual ::com::sun::star::uno::Any                                                                                SAL_CALL getRequest      () throw( ::com::sun::star::uno::RuntimeException );
        virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation > > SAL_CALL getContinuations() throw( ::com::sun::star::uno::RuntimeException );

    // member
    private:
        ::com::sun::star::uno::Any                                                                                m_aRequest      ;
        ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation > >    m_lContinuations;
        ContinuationAbort*                                                                                m_pAbort        ;
        ContinuationFilterSelect*                                                                                m_pFilter       ;

};  // class RequestFilterSelect

/*-************************************************************************************************************//**
    @short          special request for interaction
    @descr          User must decide between a preselected and another detected filter.
                    It capsulate communication with any interaction handler and supports an easy
                    access on interaction results for user of these class.

    @implements     XInteractionRequest

    @base           WeakImplHelper1

    @devstatus      ready to use
    @threadsafe     no (used on once position only!)
*//*-*************************************************************************************************************/
class RequestAmbigousFilter : public ::cppu::WeakImplHelper1< ::com::sun::star::task::XInteractionRequest >
{
    // c++ interface
    public:
        RequestAmbigousFilter( const ::rtl::OUString& sURL            ,
                               const ::rtl::OUString& sSelectedFilter ,
                               const ::rtl::OUString& sDetectedFilter );
        sal_Bool        isAbort  () const;
        ::rtl::OUString getFilter() const;

    // uno interface
    public:
        virtual ::com::sun::star::uno::Any                                                                                SAL_CALL getRequest      () throw( ::com::sun::star::uno::RuntimeException );
        virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation > > SAL_CALL getContinuations() throw( ::com::sun::star::uno::RuntimeException );

    // member
    private:
        ::com::sun::star::uno::Any                                                                                m_aRequest      ;
        ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation > >    m_lContinuations;
        ContinuationAbort*                                                                                m_pAbort        ;
        ContinuationFilterSelect*                                                                                m_pFilter       ;

};  // class RequestFilterSelect

/*-************************************************************************************************************//**
    @short          special request for interaction
    @descr          User must decide between a preselected and another detected filter.
                    It capsulate communication with any interaction handler and supports an easy
                    access on interaction results for user of these class.

    @implements     XInteractionRequest

    @base           WeakImplHelper1

    @devstatus      ready to use
    @threadsafe     no (used on once position only!)
*//*-*************************************************************************************************************/
class InteractionRequest : public ::cppu::WeakImplHelper1< ::com::sun::star::task::XInteractionRequest >
{
    // c++ interface
    public:
        InteractionRequest( const ::com::sun::star::uno::Any&                                                                                aRequest       ,
                            const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation > > lContinuations )
        {
            m_aRequest       = aRequest      ;
            m_lContinuations = lContinuations;
        }

    // uno interface
    public:
        virtual ::com::sun::star::uno::Any SAL_CALL getRequest()
            throw( ::com::sun::star::uno::RuntimeException )
            {
                return m_aRequest;
            }

        virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation > > SAL_CALL getContinuations()
            throw( ::com::sun::star::uno::RuntimeException )
            {
                return m_lContinuations;
            }

    // member
    private:
        ::com::sun::star::uno::Any                                                                                m_aRequest      ;
        ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation > >    m_lContinuations;

};  // class RequestFilterSelect

#endif  // #define __FRAMEWORK_DISPATCH_INTERACTION_HXX_

}       //  namespace framework
<commit_msg>INTEGRATION: CWS ooo19126 (1.4.502); FILE MERGED 2005/09/05 13:04:40 rt 1.4.502.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: interaction.hxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 00:12:50 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef __FRAMEWORK_DISPATCH_INTERACTION_HXX_
#define __FRAMEWORK_DISPATCH_INTERACTION_HXX_

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

#ifndef _COM_SUN_STAR_TASK_XINTERACTIONREQUEST_HPP_
#include <com/sun/star/task/XInteractionRequest.hpp>
#endif

#ifndef _COM_SUN_STAR_TASK_XINTERACTIONCONTINUATION_HPP_
#include <com/sun/star/task/XInteractionContinuation.hpp>
#endif

#ifndef _COM_SUN_STAR_TASK_XINTERACTIONABORT_HPP_
#include <com/sun/star/task/XInteractionAbort.hpp>
#endif

#ifndef _COM_SUN_STAR_TASK_XINTERACTIONAPPROVE_HPP_
#include <com/sun/star/task/XInteractionApprove.hpp>
#endif

#ifndef _COM_SUN_STAR_TASK_XINTERACTIONDISAPPROVE_HPP_
#include <com/sun/star/task/XInteractionDisapprove.hpp>
#endif

#ifndef _COM_SUN_STAR_TASK_XINTERACTIONRETRY_HPP_
#include <com/sun/star/task/XInteractionRetry.hpp>
#endif

#ifndef _COM_SUN_STAR_DOCUMENT_XINTERACTIONFILTERSELECT_HPP_
#include <com/sun/star/document/XInteractionFilterSelect.hpp>
#endif

#ifndef _COM_SUN_STAR_DOCUMENT_NOSUCHFILTERREQUEST_HPP_
#include <com/sun/star/document/NoSuchFilterRequest.hpp>
#endif

#ifndef _COM_SUN_STAR_DOCUMENT_AMBIGOUSFILTERREQUEST_HPP_
#include <com/sun/star/document/AmbigousFilterRequest.hpp>
#endif

#ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HPP_
#include <com/sun/star/uno/RuntimeException.hpp>
#endif

//_________________________________________________________________________________________________________________
//  includes of other projects
//_________________________________________________________________________________________________________________

#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif

#ifndef _CPPUHELPER_IMPLBASE1_HXX_
#include <cppuhelper/implbase1.hxx>
#endif

#ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_
#include <com/sun/star/uno/Reference.hxx>
#endif

#ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_
#include <com/sun/star/uno/Sequence.hxx>
#endif

//_________________________________________________________________________________________________________________
//  namespace
//_________________________________________________________________________________________________________________

namespace framework{

//_________________________________________________________________________________________________________________
//  non exported const
//_________________________________________________________________________________________________________________

//_________________________________________________________________________________________________________________
//  non exported definitions
//_________________________________________________________________________________________________________________

//_________________________________________________________________________________________________________________
//  declarations
//_________________________________________________________________________________________________________________

/*-************************************************************************************************************//**
    @short          base for continuation classes
    @descr          An interaction continuation could be used on XInteractionHandler/XInteractionRequest
                    to abort or react for it.
                    Base functionality is everytime the same - handler mark right continuation by calling
                    interface method "select()". User of interaction can detect it by testing c++ method "isSelected()"!
                    Superclasses can add additional interfaces or methods to support additional features ...
                    but selection of it is supported here!

    @implements     XInterface
                    XTypeProvider (supported by WeakImplHelper!)
                    XInteractionContinuation

    @base           WeakImplHelper1

    @devstatus      ready to use
    @threadsafe     no (used on once position only!)
*//*-*************************************************************************************************************/
template< class TContinuationType >
class ContinuationBase : public ::cppu::WeakImplHelper1< TContinuationType >
{
    // c++ interface
    public:

        //---------------------------------------------------------------------------------------------------------
        // initialize continuation with right start values
        //---------------------------------------------------------------------------------------------------------
        ContinuationBase()
            :   m_bSelected( sal_False )
        {
        }

        //---------------------------------------------------------------------------------------------------------
        // was continuation selected by handler?
        //---------------------------------------------------------------------------------------------------------
        sal_Bool isSelected() const
        {
            return m_bSelected;
        }

        //---------------------------------------------------------------------------------------------------------
        // make using more then once possible
        //---------------------------------------------------------------------------------------------------------
        void reset()
        {
            m_bSelected = sal_False;
        }

    // uno interface
    public:

        //---------------------------------------------------------------------------------------------------------
        // called by handler to mark continuation as the only possible solution for started interaction
        //---------------------------------------------------------------------------------------------------------
        virtual void SAL_CALL select() throw( ::com::sun::star::uno::RuntimeException )
        {
            m_bSelected = sal_True;
        }

    // member
    private:

        sal_Bool m_bSelected;

};  // class ContinuationBase

/*-************************************************************************************************************//**
    @short          declaration of some simple continuations
    @descr          These derived classes implements some simple continuations, which doesnt need and additional
                    interfaces or methods. Her selected state is the only neccessary feature. User of it can
                    distinguish by type between different functionality!

    @implements     -

    @base           ContinuationBase

    @devstatus      ready to use
    @threadsafe     no (used on once position only!)
*//*-*************************************************************************************************************/
typedef ContinuationBase< ::com::sun::star::task::XInteractionAbort > ContinuationAbort;
typedef ContinuationBase< ::com::sun::star::task::XInteractionApprove > ContinuationApprove;
typedef ContinuationBase< ::com::sun::star::task::XInteractionDisapprove > ContinuationDisapprove;
typedef ContinuationBase< ::com::sun::star::task::XInteractionRetry > ContinuationRetry;

/*-************************************************************************************************************//**
    @short          declaration of special continuation for filter selection
    @descr          Sometimes filter detection during loading document failed. Then we need a possibility
                    to ask user for his decision. These continuation transport selected filter by user to
                    code user of interaction.

    @attention      This implementation could be used one times only. We don't support a resetable continuation yet!
                    Why? Normaly interaction should show a filter selection dialog and ask user for his decision.
                    He can select any filter - then instances of these class will be called by handler ... or user
                    close dialog without any selection. Then another continuation should be slected by handler to
                    abort continuations ... Retrying isn't very usefull here ... I think.

    @implements     XInteractionFilterSelect

    @base           ImplInheritanceHelper1
                    ContinuationBase

    @devstatus      ready to use
    @threadsafe     no (used on once position only!)
*//*-*************************************************************************************************************/
class ContinuationFilterSelect : public ContinuationBase< ::com::sun::star::document::XInteractionFilterSelect >
{
    // c++ interface
    public:
        ContinuationFilterSelect();

    // uno interface
    public:
        virtual void            SAL_CALL setFilter( const ::rtl::OUString& sFilter ) throw( ::com::sun::star::uno::RuntimeException );
        virtual ::rtl::OUString SAL_CALL getFilter(                                ) throw( ::com::sun::star::uno::RuntimeException );

    // member
    private:
        ::rtl::OUString m_sFilter;

};  // class ContinuationFilterSelect

/*-************************************************************************************************************//**
    @short          special request for interaction to ask user for right filter
    @descr          These helper can be used to ask user for right filter, if filter detection failed.
                    It capsulate communication with any interaction handler and supports an easy
                    access on interaction results for user of these class.
                    Use it and forget complex mechanism of interaction ...

    @example        RequestFilterSelect*             pRequest = new RequestFilterSelect;
                    Reference< XInteractionRequest > xRequest ( pRequest );
                    xInteractionHandler->handle( xRequest );
                    if( ! pRequest.isAbort() )
                    {
                        OUString sFilter = pRequest->getFilter();
                    }

    @implements     XInteractionRequest

    @base           WeakImplHelper1

    @devstatus      ready to use
    @threadsafe     no (used on once position only!)
*//*-*************************************************************************************************************/
class RequestFilterSelect : public ::cppu::WeakImplHelper1< ::com::sun::star::task::XInteractionRequest >
{
    // c++ interface
    public:
        RequestFilterSelect( const ::rtl::OUString& sURL );
        sal_Bool        isAbort  () const;
        ::rtl::OUString getFilter() const;

    // uno interface
    public:
        virtual ::com::sun::star::uno::Any                                                                                SAL_CALL getRequest      () throw( ::com::sun::star::uno::RuntimeException );
        virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation > > SAL_CALL getContinuations() throw( ::com::sun::star::uno::RuntimeException );

    // member
    private:
        ::com::sun::star::uno::Any                                                                                m_aRequest      ;
        ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation > >    m_lContinuations;
        ContinuationAbort*                                                                                m_pAbort        ;
        ContinuationFilterSelect*                                                                                m_pFilter       ;

};  // class RequestFilterSelect

/*-************************************************************************************************************//**
    @short          special request for interaction
    @descr          User must decide between a preselected and another detected filter.
                    It capsulate communication with any interaction handler and supports an easy
                    access on interaction results for user of these class.

    @implements     XInteractionRequest

    @base           WeakImplHelper1

    @devstatus      ready to use
    @threadsafe     no (used on once position only!)
*//*-*************************************************************************************************************/
class RequestAmbigousFilter : public ::cppu::WeakImplHelper1< ::com::sun::star::task::XInteractionRequest >
{
    // c++ interface
    public:
        RequestAmbigousFilter( const ::rtl::OUString& sURL            ,
                               const ::rtl::OUString& sSelectedFilter ,
                               const ::rtl::OUString& sDetectedFilter );
        sal_Bool        isAbort  () const;
        ::rtl::OUString getFilter() const;

    // uno interface
    public:
        virtual ::com::sun::star::uno::Any                                                                                SAL_CALL getRequest      () throw( ::com::sun::star::uno::RuntimeException );
        virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation > > SAL_CALL getContinuations() throw( ::com::sun::star::uno::RuntimeException );

    // member
    private:
        ::com::sun::star::uno::Any                                                                                m_aRequest      ;
        ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation > >    m_lContinuations;
        ContinuationAbort*                                                                                m_pAbort        ;
        ContinuationFilterSelect*                                                                                m_pFilter       ;

};  // class RequestFilterSelect

/*-************************************************************************************************************//**
    @short          special request for interaction
    @descr          User must decide between a preselected and another detected filter.
                    It capsulate communication with any interaction handler and supports an easy
                    access on interaction results for user of these class.

    @implements     XInteractionRequest

    @base           WeakImplHelper1

    @devstatus      ready to use
    @threadsafe     no (used on once position only!)
*//*-*************************************************************************************************************/
class InteractionRequest : public ::cppu::WeakImplHelper1< ::com::sun::star::task::XInteractionRequest >
{
    // c++ interface
    public:
        InteractionRequest( const ::com::sun::star::uno::Any&                                                                                aRequest       ,
                            const ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation > > lContinuations )
        {
            m_aRequest       = aRequest      ;
            m_lContinuations = lContinuations;
        }

    // uno interface
    public:
        virtual ::com::sun::star::uno::Any SAL_CALL getRequest()
            throw( ::com::sun::star::uno::RuntimeException )
            {
                return m_aRequest;
            }

        virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation > > SAL_CALL getContinuations()
            throw( ::com::sun::star::uno::RuntimeException )
            {
                return m_lContinuations;
            }

    // member
    private:
        ::com::sun::star::uno::Any                                                                                m_aRequest      ;
        ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::task::XInteractionContinuation > >    m_lContinuations;

};  // class RequestFilterSelect

#endif  // #define __FRAMEWORK_DISPATCH_INTERACTION_HXX_

}       //  namespace framework
<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 *
 * 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.
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

//$Id: connection.hpp 17 2005-03-08 23:58:43Z pavlenko $

#ifndef CONNECTION_HPP
#define CONNECTION_HPP

#include <mapnik/datasource.hpp>

extern "C"
{
#include "libpq-fe.h"
}

#include "resultset.hpp"

class ResultSet;
class Connection
{
   private:
      PGconn *conn_;
      int cursorId;
      bool closed_;
   public:
      Connection(std::string const& connection_str)
         :cursorId(0),
         closed_(false)
      {
         conn_=PQconnectdb(connection_str.c_str());
         if (PQstatus(conn_) != CONNECTION_OK)
         {
             std::ostringstream s("Postgis Plugin: PSQL error");
             if (conn_ )
             {
                 std::string msg = PQerrorMessage( conn_ );
                 if ( ! msg.empty() )
                 {
                     s << ":\n" << msg.substr( 0, msg.size() - 1 );
                 }
             }
             throw mapnik::datasource_exception( s.str() );
         }
      }

      bool execute(const std::string& sql) const
      {
         PGresult *result=PQexec(conn_,sql.c_str());
         bool ok=(result && PQresultStatus(result)==PGRES_COMMAND_OK);
         PQclear(result);
         return ok;
      }

      boost::shared_ptr<ResultSet> executeQuery(const std::string& sql,int type=0) const
      {
         PGresult *result=0;
         if (type==1)
         {
             result=PQexecParams(conn_,sql.c_str(),0,0,0,0,0,1);
         }
         else
         {
             result=PQexec(conn_,sql.c_str());
         }
         if(!result || PQresultStatus(result) != PGRES_TUPLES_OK)
         {
             std::ostringstream s("Postgis Plugin: PSQL error");
             if (conn_ )
             {
                 std::string msg = PQerrorMessage( conn_ );
                 if ( ! msg.empty() )
                 {
                     s << ":" << std::endl << msg.substr( 0, msg.size() - 1 );
                 }

                 s << std::endl << "Full sql was: '" + sql + "'" << std::endl;
             }
             throw mapnik::datasource_exception( s.str() );
         }

         return boost::shared_ptr<ResultSet>(new ResultSet(result));
      }

      std::string client_encoding() const
      {
         return PQparameterStatus(conn_,"client_encoding");
      }

      bool isOK() const
      {
         return (PQstatus(conn_)!=CONNECTION_BAD);
      }

      void close()
      {
         if (!closed_)
         {
             PQfinish(conn_);
#ifdef MAPNIK_DEBUG
             std::clog << "PostGIS: datasource closed, also closing connection - " << conn_ << std::endl;
#endif
             closed_ = true;
         }
      }

      std::string new_cursor_name()
      {
          std::ostringstream s;
          s << "mapnik_" << (cursorId++);
          return s.str();
      }

      ~Connection()
      {
         if (!closed_)
         {
             PQfinish(conn_);
#ifdef MAPNIK_DEBUG
             std::clog << "PostGIS: postgresql connection closed - " << conn_ << std::endl;
#endif
             closed_ = true;
         }
      }
};

#endif //CONNECTION_HPP
<commit_msg>+ reset head<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 *
 * 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.
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/

//$Id: connection.hpp 17 2005-03-08 23:58:43Z pavlenko $

#ifndef CONNECTION_HPP
#define CONNECTION_HPP

#include <mapnik/datasource.hpp>

extern "C"
{
#include "libpq-fe.h"
}

#include "resultset.hpp"

class ResultSet;
class Connection
{
   private:
      PGconn *conn_;
      int cursorId;
      bool closed_;
   public:
      Connection(std::string const& connection_str)
         :cursorId(0),
         closed_(false)
      {
         conn_=PQconnectdb(connection_str.c_str());
         if (PQstatus(conn_) != CONNECTION_OK)
         {
             std::ostringstream s("Postgis Plugin: PSQL error");
             if (conn_ )
             {
                 std::string msg = PQerrorMessage( conn_ );
                 if ( ! msg.empty() )
                 {
                     s << ":\n" << msg.substr( 0, msg.size() - 1 );
                 }
             }
             throw mapnik::datasource_exception( s.str() );
         }
      }

      bool execute(const std::string& sql) const
      {
         PGresult *result=PQexec(conn_,sql.c_str());
         bool ok=(result && PQresultStatus(result)==PGRES_COMMAND_OK);
         PQclear(result);
         return ok;
      }

      boost::shared_ptr<ResultSet> executeQuery(const std::string& sql,int type=0) const
      {
         PGresult *result=0;
         if (type==1)
         {
             result=PQexecParams(conn_,sql.c_str(),0,0,0,0,0,1);
         }
         else
         {
             result=PQexec(conn_,sql.c_str());
         }
         if(!result || PQresultStatus(result) != PGRES_TUPLES_OK)
         {
             std::ostringstream s("Postgis Plugin: PSQL error");
             if (conn_ )
             {
                 std::string msg = PQerrorMessage( conn_ );
                 if ( ! msg.empty() )
                 {
                     s << ":\n" <<  msg.substr( 0, msg.size() - 1 );
                 }

                 s << "\nFull sql was: '" <<  sql << "'\n";
             }
             throw mapnik::datasource_exception( s.str() );
         }

         return boost::shared_ptr<ResultSet>(new ResultSet(result));
      }

      std::string client_encoding() const
      {
         return PQparameterStatus(conn_,"client_encoding");
      }

      bool isOK() const
      {
         return (PQstatus(conn_)!=CONNECTION_BAD);
      }

      void close()
      {
         if (!closed_)
         {
             PQfinish(conn_);
#ifdef MAPNIK_DEBUG
             std::clog << "PostGIS: datasource closed, also closing connection - " << conn_ << std::endl;
#endif
             closed_ = true;
         }
      }

      std::string new_cursor_name()
      {
          std::ostringstream s;
          s << "mapnik_" << (cursorId++);
          return s.str();
      }

      ~Connection()
      {
         if (!closed_)
         {
             PQfinish(conn_);
#ifdef MAPNIK_DEBUG
             std::clog << "PostGIS: postgresql connection closed - " << conn_ << std::endl;
#endif
             closed_ = true;
         }
      }
};

#endif //CONNECTION_HPP
<|endoftext|>