<commit_before>#include <iterator>
#include <list>
#include <numeric>
#include <vector>

#include <cassert>

#include "RandomPermuter.h"

namespace fs_testing {
namespace permuter {
using std::advance;
using std::iota;
using std::list;
using std::mt19937;
using std::uniform_int_distribution;
using std::vector;

using fs_testing::utils::disk_write;

namespace {

struct range {
  unsigned int start;
  unsigned int end;
};

}  // namespace

void RandomPermuter::init_data_vector(vector<disk_write> *data) {
  epochs.clear();
  log_length = data->size();
  unsigned int index = 0;
  list<range> overlaps;
  while (index < data->size()) {
    struct epoch current_epoch;
    current_epoch.has_barrier = false;
    current_epoch.overlaps = false;
    current_epoch.length = 0;

    // Get all ops in this epoch and add them to either the sync_op or async_op
    // lists.
    while (index < data->size() && !(data->at(index)).is_barrier_write()) {
      disk_write curr = data->at(index);
      // Find overlapping ranges.
      unsigned int start = curr.metadata.write_sector;
      unsigned int end = start + curr.metadata.size;
      for (auto range_iter = overlaps.begin(); range_iter != overlaps.end();
          range_iter++) {
        range r = *range_iter;
        if ((r.start <= start && r.end >= start)
            || (r.start <= end && r.end >= end)) {
          if (r.start > start) {
            r.start = start;
          }
          if (r.end < end) {
            r.end = end;
          }
          current_epoch.overlaps = true;
          break;
        } else if (r.start > end) {
          // Since this is an ordered list, if the next spot is past where we're
          // looking now then we won't find anything past here. We may as well
          // insert an item here.
          range new_range = {start, end};
          overlaps.insert(range_iter, new_range);
        }
      }

      ++current_epoch.length;
      current_epoch.ops.push_back(data->at(index));
      current_epoch.num_meta += data->at(index).is_meta();
      ++index;
    }

    // Check is the op at the current index is a "barrier." If it is then add it
    // to the special spot in the epoch, otherwise just push the current epoch
    // onto the list and move to the next segment of the log.
    if (index < data->size() && (data->at(index)).is_barrier_write()) {
      ++current_epoch.length;
      current_epoch.ops.push_back(data->at(index));
      current_epoch.num_meta += data->at(index).is_meta();
      current_epoch.has_barrier = true;
      ++index;
    }
    epochs.push_back(current_epoch);
  }
}

RandomPermuter::RandomPermuter() {
  log_length = 0;
  rand = mt19937(42);
}

RandomPermuter::RandomPermuter(vector<disk_write> *data) {
  init_data_vector(data);
  // TODO(ashmrtn): Make a flag to make it random or not.
  rand = mt19937(42);
}

void RandomPermuter::set_data(vector<disk_write> *data) {
  init_data_vector(data);
}

bool RandomPermuter::permute(vector<disk_write>& res) {
  unsigned int total_elements = 0;
  // Find how many elements we will be returning (randomly determined).
  uniform_int_distribution<unsigned int> permute_epochs(1, epochs.size());
  unsigned int num_epochs = permute_epochs(rand);
  // Don't subtract 1 from this size so that we can send a complete epoch if we
  // want.
  uniform_int_distribution<unsigned int> permute_requests(1,
      epochs.at(num_epochs - 1).length);
  unsigned int num_requests = permute_requests(rand);
  // TODO(ashmrtn): Optimize so that we resize to exactly the number of elements
  // we will have, not the number of elements in all the epochs.
  for (unsigned int i = 0; i < num_epochs; ++i) {
    total_elements += epochs.at(i).length;
  }
  res.resize(total_elements);

  int current_index = 0;
  auto curr_iter = res.begin();
  auto cutoff = res.begin();
  for (unsigned int i = 0; i < num_epochs; ++i) {
    auto res_iter = curr_iter;
    // Use a for loop since vector::insert inserts new elements and we resized
    // above to the exact size we will have.
    unsigned int adv = (i == num_epochs - 1) ? num_requests
                                             : epochs.at(i).length;
    auto epoch_end = epochs.at(i).ops.begin();
    advance(epoch_end, adv);
    for (auto epoch_iter = epochs.at(i).ops.begin(); epoch_iter != epoch_end;
        ++epoch_iter) {
      *res_iter = *epoch_iter;
      ++res_iter;
    }
    current_index += epochs.at(i).length;

    /* TODO(ashmrtn): Figure out why we can't set the cutoff iterator up here.
    // Set this here so that we don't have to move it all the way to the start
    // below.
    if (i == num_epochs - 1) {
      std::cout << "setting cutoff itrator" << std::endl;
      cutoff = curr_iter;
    } else {
      advance(curr_iter, epochs.at(i).length);
    }
    */
    advance(curr_iter, epochs.at(i).length);
  }
  // Trim the last epoch to a random number of requests.
  cutoff = res.begin();
  advance(cutoff, total_elements - epochs.at(num_epochs - 1).length);
  advance(cutoff, num_requests - 1);
  // Trim off all requests at or after the one we selected above.
  res.erase(cutoff, res.end());
  //res.erase(curr_iter, res.end());

  return true;
}

void RandomPermuter::permute_epoch(vector<disk_write>& res,
    const int start_index, epoch& epoch) {
  unsigned int slots = epoch.length;

  // Place the barrier operation if it exists since the entire vector already
  // exists (i.e. we won't cause extra shifting when adding the other elements).
  // Decrement out count of empty slots since we have filled one.
  if (epoch.has_barrier) {
    res.at(start_index + slots - 1) = epoch.ops.back();
    --slots;
  }

  // Fill the list with the empty slots, either [0, epoch.length - 1) or
  // [0, epoch.length - 2).
  list<unsigned int> empty_slots(slots);
  iota(empty_slots.begin(), empty_slots.end(), 0);

  for (unsigned int i = 0; i < slots; ++i) {
    // Uniform distribution includes both ends, so we need to subtract 1 from
    // the size.
    uniform_int_distribution<unsigned int> uid(0, empty_slots.size() - 1);
    auto shift = empty_slots.begin();
    advance(shift, uid(rand));
    res.at(start_index + *shift) = epoch.ops.at(i);
    empty_slots.erase(shift);
  }

  assert(empty_slots.empty());
}

}  // namespace permuter
}  // namespace fs_testing

extern "C" fs_testing::permuter::Permuter* permuter_get_instance(
    std::vector<fs_testing::utils::disk_write> *data) {
  return new fs_testing::permuter::RandomPermuter(data);
}

extern "C" void permuter_delete_instance(fs_testing::permuter::Permuter* p) {
  delete p;
}
<commit_msg>Fixup for manually adding items to the vector.<commit_after>#include <iterator>
#include <list>
#include <numeric>
#include <vector>

#include <cassert>

#include "RandomPermuter.h"

namespace fs_testing {
namespace permuter {
using std::advance;
using std::iota;
using std::list;
using std::mt19937;
using std::uniform_int_distribution;
using std::vector;

using fs_testing::utils::disk_write;

namespace {

struct range {
  unsigned int start;
  unsigned int end;
};

}  // namespace

void RandomPermuter::init_data_vector(vector<disk_write> *data) {
  epochs.clear();
  log_length = data->size();
  unsigned int index = 0;
  list<range> overlaps;
  while (index < data->size()) {
    struct epoch current_epoch;
    current_epoch.has_barrier = false;
    current_epoch.overlaps = false;
    current_epoch.length = 0;

    // Get all ops in this epoch and add them to either the sync_op or async_op
    // lists.
    while (index < data->size() && !(data->at(index)).is_barrier_write()) {
      disk_write curr = data->at(index);
      // Find overlapping ranges.
      unsigned int start = curr.metadata.write_sector;
      unsigned int end = start + curr.metadata.size;
      for (auto range_iter = overlaps.begin(); range_iter != overlaps.end();
          range_iter++) {
        range r = *range_iter;
        if ((r.start <= start && r.end >= start)
            || (r.start <= end && r.end >= end)) {
          if (r.start > start) {
            r.start = start;
          }
          if (r.end < end) {
            r.end = end;
          }
          current_epoch.overlaps = true;
          break;
        } else if (r.start > end) {
          // Since this is an ordered list, if the next spot is past where we're
          // looking now then we won't find anything past here. We may as well
          // insert an item here.
          range new_range = {start, end};
          overlaps.insert(range_iter, new_range);
        }
      }

      ++current_epoch.length;
      current_epoch.ops.push_back(data->at(index));
      current_epoch.num_meta += data->at(index).is_meta();
      ++index;
    }

    // Check is the op at the current index is a "barrier." If it is then add it
    // to the special spot in the epoch, otherwise just push the current epoch
    // onto the list and move to the next segment of the log.
    if (index < data->size() && (data->at(index)).is_barrier_write()) {
      ++current_epoch.length;
      current_epoch.ops.push_back(data->at(index));
      current_epoch.num_meta += data->at(index).is_meta();
      current_epoch.has_barrier = true;
      ++index;
    }
    epochs.push_back(current_epoch);
  }
}

RandomPermuter::RandomPermuter() {
  log_length = 0;
  rand = mt19937(42);
}

RandomPermuter::RandomPermuter(vector<disk_write> *data) {
  init_data_vector(data);
  // TODO(ashmrtn): Make a flag to make it random or not.
  rand = mt19937(42);
}

void RandomPermuter::set_data(vector<disk_write> *data) {
  init_data_vector(data);
}

bool RandomPermuter::permute(vector<disk_write>& res) {
  unsigned int total_elements = 0;
  // Find how many elements we will be returning (randomly determined).
  uniform_int_distribution<unsigned int> permute_epochs(1, epochs.size());
  unsigned int num_epochs = permute_epochs(rand);
  // Don't subtract 1 from this size so that we can send a complete epoch if we
  // want.
  uniform_int_distribution<unsigned int> permute_requests(1,
      epochs.at(num_epochs - 1).length);
  unsigned int num_requests = permute_requests(rand);
  // TODO(ashmrtn): Optimize so that we resize to exactly the number of elements
  // we will have, not the number of elements in all the epochs.
  for (unsigned int i = 0; i < num_epochs; ++i) {
    total_elements += epochs.at(i).length;
  }
  res.resize(total_elements);

  int current_index = 0;
  auto curr_iter = res.begin();
  auto cutoff = res.begin();
  for (unsigned int i = 0; i < num_epochs; ++i) {
    if (epochs.at(i).overlaps || i == num_epochs - 1) {
      permute_epoch(res, current_index, epochs.at(i));
    } else {
      auto res_iter = curr_iter;
      // Use a for loop since vector::insert inserts new elements and we resized
      // above to the exact size we will have.
      unsigned int adv = (i == num_epochs - 1) ? num_requests
                                               : epochs.at(i).length;
      auto epoch_end = epochs.at(i).ops.begin();
      advance(epoch_end, adv);
      for (auto epoch_iter = epochs.at(i).ops.begin(); epoch_iter != epoch_end;
          ++epoch_iter) {
        *res_iter = *epoch_iter;
        ++res_iter;
      }
    }
    current_index += epochs.at(i).length;

    advance(curr_iter, epochs.at(i).length);
  }
  // Trim the last epoch to a random number of requests.
  cutoff = res.begin();
  advance(cutoff, total_elements - epochs.at(num_epochs - 1).length
      + num_requests);
  // Trim off all requests at or after the one we selected above.
  res.erase(cutoff, res.end());
  //res.erase(curr_iter, res.end());

  return true;
}

void RandomPermuter::permute_epoch(vector<disk_write>& res,
    const int start_index, epoch& epoch) {
  unsigned int slots = epoch.length;

  // Place the barrier operation if it exists since the entire vector already
  // exists (i.e. we won't cause extra shifting when adding the other elements).
  // Decrement out count of empty slots since we have filled one.
  if (epoch.has_barrier) {
    res.at(start_index + slots - 1) = epoch.ops.back();
    --slots;
  }

  // Fill the list with the empty slots, either [0, epoch.length - 1) or
  // [0, epoch.length - 2).
  list<unsigned int> empty_slots(slots);
  iota(empty_slots.begin(), empty_slots.end(), 0);

  for (unsigned int i = 0; i < slots; ++i) {
    // Uniform distribution includes both ends, so we need to subtract 1 from
    // the size.
    uniform_int_distribution<unsigned int> uid(0, empty_slots.size() - 1);
    auto shift = empty_slots.begin();
    advance(shift, uid(rand));
    res.at(start_index + *shift) = epoch.ops.at(i);
    empty_slots.erase(shift);
  }

  assert(empty_slots.empty());
}

}  // namespace permuter
}  // namespace fs_testing

extern "C" fs_testing::permuter::Permuter* permuter_get_instance(
    std::vector<fs_testing::utils::disk_write> *data) {
  return new fs_testing::permuter::RandomPermuter(data);
}

extern "C" void permuter_delete_instance(fs_testing::permuter::Permuter* p) {
  delete p;
}
<|endoftext|>


<commit_before>#include <coffee/core/plat/environment/osx/sysinfo.h>

#include <sys/types.h>
#include <sys/sysctl.h>

namespace Coffee{
namespace Environment{
namespace Mac{

/*
 * OS X has a sexy API for retrieving hardware information. Big thumbs up!
 */

static CString _GetSysctlString(const cstring mod_string)
{
    CString target;

    size_t len = 0;
    sysctlbyname(mod_string, nullptr, &len, nullptr, 0);

    if(len > 0)
    {
        target.resize(len+1);
        sysctlbyname(mod_string, &target[0], &len, nullptr, 0);
        target.resize(Mem::Search::ChrFind(&target[0], '\0') - &target[0]);
    }

    return target;
}

static uint64 _GetSysctlInt(const cstring mod_string)
{
    uint64 temp;
    size_t len = sizeof(temp);
    sysctlbyname(mod_string, &temp, &len, nullptr, 0);
    return temp;
}

CString MacSysInfo::GetSystemVersion()
{
    FILE* out = popen("sw_vers -productVersion","r");
    if(out)
    {
        char buf[16];
        char* ptr = fgets(buf, sizeof(buf),out);
        pclose(out);
        CString output = ptr;
        output.resize(Mem::Search::ChrFind((cstring)ptr,'\n')-ptr);
        return output;
    }else
        return "0.0";
}

HWDeviceInfo MacSysInfo::DeviceName()
{
    static const cstring mod_string = "hw.model";
    static const cstring typ_string = "kern.ostype";
    static const cstring rel_string = "kern.osrelease";

    CString target = _GetSysctlString(mod_string);
    CString kern = _GetSysctlString(typ_string);;
    CString osrel = _GetSysctlString(rel_string);;

    return HWDeviceInfo("Apple", target, kern + " " + osrel);
}

HWDeviceInfo MacSysInfo::Processor()
{
    static const cstring ven_string = "machdep.cpu.vendor";
    static const cstring brd_string = "machdep.cpu.brand_string";
    static const cstring mcc_string = "machdep.cpu.microcode_version";

    CString vendor = _GetSysctlString(ven_string);
    CString brand = _GetSysctlString(brd_string);
    uint32 microcode = _GetSysctlInt(mcc_string);

    return HWDeviceInfo(vendor, brand, Mem::StrUtil::hexify(microcode, true));
}

bigscalar MacSysInfo::ProcessorFrequency()
{
    static const cstring frq_string = "machdep.tsc.frequency";
//            "hw.cpufrequency"

    uint32 freq_i = _GetSysctlInt(frq_string);

    return freq_i / (1024. * 1024. * 1024.);
}

CoreCnt MacSysInfo::CpuCount()
{
    static const cstring cpu_string = "hw.packages";

    uint32 c = _GetSysctlInt(cpu_string);

    return c;
}

CoreCnt MacSysInfo::CoreCount()
{
    static const cstring cre_string = "machdep.cpu.core_count";

    uint32 c = _GetSysctlInt(cre_string);

    return c;
}

MemUnit MacSysInfo::MemTotal()
{
    static const cstring mtl_string = "hw.memsize";

    uint64 c = _GetSysctlInt(mtl_string);

    return c;
}

MemUnit MacSysInfo::MemAvailable()
{
    static const cstring mav_string = "hw.usermem";

    uint64 c = _GetSysctlInt(mav_string);

    return MemTotal() - c;
}

bool MacSysInfo::HasFPU()
{
    static const cstring fpu_string = "hw.optional.floatingpoint";

    uint32 c = _GetSysctlInt(fpu_string);

    return c;
}

bool MacSysInfo::HasHyperThreading()
{
    static const cstring thd_string = "machdep.cpu.thread_count";
    uint32 thr_count = _GetSysctlInt(thd_string);

    return thr_count != CoreCount();
}

}
}
}
<commit_msg> - Fix oopsie in TSC conversion<commit_after>#include <coffee/core/plat/environment/osx/sysinfo.h>

#include <sys/types.h>
#include <sys/sysctl.h>

namespace Coffee{
namespace Environment{
namespace Mac{

/*
 * OS X has a sexy API for retrieving hardware information. Big thumbs up!
 */

static CString _GetSysctlString(const cstring mod_string)
{
    CString target;

    size_t len = 0;
    sysctlbyname(mod_string, nullptr, &len, nullptr, 0);

    if(len > 0)
    {
        target.resize(len+1);
        sysctlbyname(mod_string, &target[0], &len, nullptr, 0);
        target.resize(Mem::Search::ChrFind(&target[0], '\0') - &target[0]);
    }

    return target;
}

static uint64 _GetSysctlInt(const cstring mod_string)
{
    uint64 temp;
    size_t len = sizeof(temp);
    sysctlbyname(mod_string, &temp, &len, nullptr, 0);
    return temp;
}

CString MacSysInfo::GetSystemVersion()
{
    FILE* out = popen("sw_vers -productVersion","r");
    if(out)
    {
        char buf[16];
        char* ptr = fgets(buf, sizeof(buf),out);
        pclose(out);
        CString output = ptr;
        output.resize(Mem::Search::ChrFind((cstring)ptr,'\n')-ptr);
        return output;
    }else
        return "0.0";
}

HWDeviceInfo MacSysInfo::DeviceName()
{
    static const cstring mod_string = "hw.model";
    static const cstring typ_string = "kern.ostype";
    static const cstring rel_string = "kern.osrelease";

    CString target = _GetSysctlString(mod_string);
    CString kern = _GetSysctlString(typ_string);;
    CString osrel = _GetSysctlString(rel_string);;

    return HWDeviceInfo("Apple", target, kern + " " + osrel);
}

HWDeviceInfo MacSysInfo::Processor()
{
    static const cstring ven_string = "machdep.cpu.vendor";
    static const cstring brd_string = "machdep.cpu.brand_string";
    static const cstring mcc_string = "machdep.cpu.microcode_version";

    CString vendor = _GetSysctlString(ven_string);
    CString brand = _GetSysctlString(brd_string);
    uint32 microcode = _GetSysctlInt(mcc_string);

    return HWDeviceInfo(vendor, brand, Mem::StrUtil::hexify(microcode, true));
}

bigscalar MacSysInfo::ProcessorFrequency()
{
    static const cstring frq_string = "machdep.tsc.frequency";
//            "hw.cpufrequency"

    uint32 freq_i = _GetSysctlInt(frq_string);

    return freq_i / (1000. * 1000. * 1000.);
}

CoreCnt MacSysInfo::CpuCount()
{
    static const cstring cpu_string = "hw.packages";

    uint32 c = _GetSysctlInt(cpu_string);

    return c;
}

CoreCnt MacSysInfo::CoreCount()
{
    static const cstring cre_string = "machdep.cpu.core_count";

    uint32 c = _GetSysctlInt(cre_string);

    return c;
}

MemUnit MacSysInfo::MemTotal()
{
    static const cstring mtl_string = "hw.memsize";

    uint64 c = _GetSysctlInt(mtl_string);

    return c;
}

MemUnit MacSysInfo::MemAvailable()
{
    static const cstring mav_string = "hw.usermem";

    uint64 c = _GetSysctlInt(mav_string);

    return MemTotal() - c;
}

bool MacSysInfo::HasFPU()
{
    static const cstring fpu_string = "hw.optional.floatingpoint";

    uint32 c = _GetSysctlInt(fpu_string);

    return c;
}

bool MacSysInfo::HasHyperThreading()
{
    static const cstring thd_string = "machdep.cpu.thread_count";
    uint32 thr_count = _GetSysctlInt(thd_string);

    return thr_count != CoreCount();
}

}
}
}
<|endoftext|>


<commit_before>#include <node.h>
#include <node_buffer.h>
#include <string.h>
#include <uv.h>
#include "If_DBR.h"
#include "BarcodeFormat.h"
#include "BarcodeStructs.h"
#include "ErrorCode.h"

using namespace v8;

// Barcode format
const char * GetFormatStr(__int64 format)
{
	if (format == CODE_39)
		return "CODE_39";
	if (format == CODE_128)
		return "CODE_128";
	if (format == CODE_93)
		return "CODE_93";
	if (format == CODABAR)
		return "CODABAR";
	if (format == ITF)
		return "ITF";
	if (format == UPC_A)
		return "UPC_A";
	if (format == UPC_E)
		return "UPC_E";
	if (format == EAN_13)
		return "EAN_13";
	if (format == EAN_8)
		return "EAN_8";
	if (format == INDUSTRIAL_25)
		return "INDUSTRIAL_25";
	if (format == QR_CODE)
		return "QR_CODE";
	if (format == PDF417)
		return "PDF417";
	if (format == DATAMATRIX)
		return "DATAMATRIX";

	return "UNKNOWN";
}

typedef enum {
	NO_BUFFER,
	FILE_STREAM,
	YUYV_BUFFER,
} BufferType;

struct BarcodeWorker
{
    uv_work_t request;              // libuv
	Persistent<Function> callback;	// javascript callback
	__int64 llFormat;				// barcode types
	char filename[128];				// file name
	pBarcodeResultArray pResults;	// result pointer
	unsigned char *buffer;
	int size;						// file size
	int errorCode;					// detection error code
	int width;						// image width
	int height; 					// image height
	BufferType bufferType;			// buffer type
};

bool ConvertCameraGrayDataToDIBBuffer(unsigned char* psrc, int size, int width, int height, unsigned char** ppdist, int *psize)
{
	BITMAPINFOHEADER bitmapInfo;
	memset(&bitmapInfo, 0, sizeof(BITMAPINFOHEADER));

	bitmapInfo.biBitCount = 8;
	bitmapInfo.biWidth = width;
	bitmapInfo.biHeight = height;
	bitmapInfo.biSize = sizeof(BITMAPINFOHEADER);

	int iStride = ((width * 8 + 31) >> 5) << 2;
	int iImageSize = iStride * height;
	if (size < iImageSize)
		return false;

	bitmapInfo.biSizeImage = iImageSize;

	*psize = iImageSize + bitmapInfo.biSize + 1024;
	*ppdist = new unsigned char[*psize];

	//1. copy BITMAPINFOHEADER
	memcpy(*ppdist, &bitmapInfo, sizeof(BITMAPINFOHEADER));

	//2. copy gray color map
	char rgba[1024] = { 0 };
	for (int i = 0; i < 256; ++i)
	{
		rgba[i * 4] = rgba[i * 4 + 1] = rgba[i * 4 + 2] = rgba[i * 4 + 3] = i;
	}
	memcpy(*ppdist + sizeof(BITMAPINFOHEADER), rgba, 1024);

	//3. copy gray data (should be fliped)
	unsigned char* srcptr = psrc + (height - 1)*width;
	unsigned char* dstptr = *ppdist + sizeof(BITMAPINFOHEADER) + 1024;

	for (int j = 0; j < height; ++j, srcptr -= width, dstptr += iStride)
	{
		memcpy(dstptr, srcptr, width);
	}

	return true;
}

/*
 *	uv_work_cb
 */
static void DetectionWorking(uv_work_t *req)
{
	// get the reference to BarcodeWorker
    BarcodeWorker *worker = static_cast<BarcodeWorker *>(req->data);

	// initialize Dynamsoft Barcode Reader
	int iMaxCount = 0x7FFFFFFF;
	ReaderOptions ro = {0};
	pBarcodeResultArray pResults = NULL;
	ro.llBarcodeFormat = worker->llFormat;
	ro.iMaxBarcodesNumPerPage = iMaxCount;

	// decode barcode image
	int ret = 0;
	switch(worker->bufferType)
	{
		case FILE_STREAM:
			{
				if (worker->buffer)
					ret = DBR_DecodeStream(worker->buffer, worker->size, &ro, &pResults);
			}
			break;
		case YUYV_BUFFER:
			{
				if (worker->buffer)
				{
					unsigned char* pdibdata = NULL;
					int dibsize = 0;
					int width = worker->width, height = worker->height;
					int size = width * height;
					int index = 0;
					unsigned char* data = new unsigned char[size];
					// get Y from YUYV
					for (int i = 0; i < size; i++)
					{
						data[i] = worker->buffer[index];
						index += 2;
					}
					// gray conversion
					ConvertCameraGrayDataToDIBBuffer(data, size, width, height, &pdibdata, &dibsize);
					// read barcode
					ret = DBR_DecodeBuffer(pdibdata, dibsize, &ro, &pResults);
					// release memory
					delete []data, data=NULL;
					delete []pdibdata, pdibdata=NULL;
				}
			}
			break;
		default:
			{
				ret = DBR_DecodeFile(worker->filename, &ro, &pResults);
			}
	}

	if (ret)
		printf("Detection error code: %d\n", ret);

	// save results to BarcodeWorker
	worker->errorCode = ret;
	worker->pResults = pResults;
}

/*
 *	uv_after_work_cb
 */
static void DetectionDone(uv_work_t *req,int status)
{
	Isolate* isolate = Isolate::GetCurrent();
	HandleScope scope(isolate);

    // get the reference to BarcodeWorker
    BarcodeWorker *worker = static_cast<BarcodeWorker *>(req->data);

	// get barcode results
	pBarcodeResultArray pResults = worker->pResults;
	int errorCode = worker->errorCode;
	int count = pResults->iBarcodeCount;
	pBarcodeResult* ppBarcodes = pResults->ppBarcodes;
	pBarcodeResult tmp = NULL;

	// array for storing barcode results
	Local<Array> barcodeResults = Array::New(isolate);

	for (int i = 0; i < count; i++)
	{
		tmp = ppBarcodes[i];

		Local<Object> result = Object::New(isolate);
		result->Set(String::NewFromUtf8(isolate, "format"), String::NewFromUtf8(isolate, GetFormatStr(tmp->llFormat)));
		result->Set(String::NewFromUtf8(isolate, "value"), String::NewFromUtf8(isolate, tmp->pBarcodeData));
		barcodeResults->Set(Number::New(isolate, i), result);
	}

	// release memory of barcode results
	DBR_FreeBarcodeResults(&pResults);

    // run the callback
	const unsigned argc = 1;
	Local<Value> argv[argc] = {barcodeResults};
	Local<Function> cb = Local<Function>::New(isolate, worker->callback);
    cb->Call(isolate->GetCurrentContext()->Global(), argc, argv);

	// release memory of BarcodeWorker
    delete worker;
}

/*
 *	initLicense(license)
 */
void InitLicense(const FunctionCallbackInfo<Value>& args) {

	String::Utf8Value license(args[0]->ToString());
	char *pszLicense = *license;
	DBR_InitLicense(pszLicense);
}

/*
 *	decodeFile(fileName, barcodeTypes, callback)
 */
void DecodeFile(const FunctionCallbackInfo<Value>& args) {

	Isolate* isolate = Isolate::GetCurrent();
	HandleScope scope(isolate);

	// get arguments
	String::Utf8Value fileName(args[0]->ToString()); // convert v8 string to char *
	char *pFileName = *fileName; // file name
	__int64 llFormat = args[1]->IntegerValue();	// barcode types
	Local<Function> cb = Local<Function>::Cast(args[2]); // javascript callback function

	// initialize Dynamsoft Barcode Reader
	int iMaxCount = 0x7FFFFFFF;
	ReaderOptions ro = {0};
	pBarcodeResultArray pResults = NULL;
	ro.llBarcodeFormat = llFormat;
	ro.iMaxBarcodesNumPerPage = iMaxCount;

	// decode barcode image
	int ret = DBR_DecodeFile(pFileName, &ro, &pResults);
	if (ret)
		printf("Detection error code: %d\n", ret);

	int count = pResults->iBarcodeCount;
	pBarcodeResult* ppBarcodes = pResults->ppBarcodes;
	pBarcodeResult tmp = NULL;

	// array for storing barcode results
	Local<Array> barcodeResults = Array::New(isolate);

	for (int i = 0; i < count; i++)
	{
		tmp = ppBarcodes[i];

		Local<Object> result = Object::New(isolate);
		result->Set(String::NewFromUtf8(isolate, "format"), String::NewFromUtf8(isolate, GetFormatStr(tmp->llFormat)));
		result->Set(String::NewFromUtf8(isolate, "value"), String::NewFromUtf8(isolate, tmp->pBarcodeData));
		barcodeResults->Set(Number::New(isolate, i), result);
	}

	// release memory of barcode results
	DBR_FreeBarcodeResults(&pResults);

	// run the callback
	const unsigned argc = 1;
	Local<Value> argv[argc] = { barcodeResults };
	cb->Call(isolate->GetCurrentContext()->Global(), argc, argv);
}

/*
 *	decodeFileAsync(fileName, barcodeTypes, callback)
 */
void DecodeFileAsync(const FunctionCallbackInfo<Value>& args) {
	Isolate* isolate = Isolate::GetCurrent();
	HandleScope scope(isolate);

	// get arguments
	String::Utf8Value fileName(args[0]->ToString()); // file name
	char *pFileName = *fileName;
	__int64 llFormat = args[1]->IntegerValue(); // barcode types
	Local<Function> cb = Local<Function>::Cast(args[2]); // javascript callback function

	// initialize BarcodeWorker
	BarcodeWorker *worker = new BarcodeWorker;
	worker->request.data = worker;
	strcpy(worker->filename, pFileName);
	worker->callback.Reset(isolate, cb);
	worker->llFormat = llFormat;
	worker->pResults = NULL;
	worker->buffer = NULL;
	worker->bufferType = NO_BUFFER;

	uv_queue_work(uv_default_loop(), &worker->request, (uv_work_cb)DetectionWorking, (uv_after_work_cb)DetectionDone);
}

/*
 *	decodeFileStreamAsync(fileStream, fileSize, barcodeTypes, callback)
 */
void DecodeFileStreamAsync(const FunctionCallbackInfo<Value>& args) {
	Isolate* isolate = Isolate::GetCurrent();
	HandleScope scope(isolate);

	// get arguments
	unsigned char* buffer = (unsigned char*) node::Buffer::Data(args[0]->ToObject()); // file stream
	int fileSize = args[1]->IntegerValue();	// file size
	__int64 llFormat = args[2]->IntegerValue(); // barcode types
	Local<Function> cb = Local<Function>::Cast(args[3]); // javascript callback function

	// initialize BarcodeWorker
	BarcodeWorker *worker = new BarcodeWorker;
	worker->request.data = worker;
	worker->callback.Reset(isolate, cb);
	worker->llFormat = llFormat;
	worker->pResults = NULL;
	worker->buffer = buffer;
	worker->size = fileSize;
	worker->bufferType = FILE_STREAM;

	uv_queue_work(uv_default_loop(), &worker->request, (uv_work_cb)DetectionWorking, (uv_after_work_cb)DetectionDone);
}

/*
 *	decodeYUYVAsync(buffer, width, height, barcodeTypes, callback)
 */
void DecodeYUYVAsync(const FunctionCallbackInfo<Value>& args) {
	Isolate* isolate = Isolate::GetCurrent();
	HandleScope scope(isolate);

	// get arguments
	unsigned char* buffer = (unsigned char*) node::Buffer::Data(args[0]->ToObject()); // file stream
	int width = args[1]->IntegerValue();	// image width
	int height = args[2]->IntegerValue();	// image height
	__int64 llFormat = args[3]->IntegerValue(); // barcode types
	Local<Function> cb = Local<Function>::Cast(args[4]); // javascript callback function

	// initialize BarcodeWorker
	BarcodeWorker *worker = new BarcodeWorker;
	worker->request.data = worker;
	worker->callback.Reset(isolate, cb);
	worker->llFormat = llFormat;
	worker->pResults = NULL;
	worker->buffer = buffer;
	worker->width = width;
	worker->height = height;
	worker->bufferType = YUYV_BUFFER;

	uv_queue_work(uv_default_loop(), &worker->request, (uv_work_cb)DetectionWorking, (uv_after_work_cb)DetectionDone);
}

void Init(Handle<Object> exports) {
	NODE_SET_METHOD(exports, "decodeYUYVAsync", DecodeYUYVAsync);
	NODE_SET_METHOD(exports, "decodeFileStreamAsync", DecodeFileStreamAsync);
	NODE_SET_METHOD(exports, "initLicense", InitLicense);
	NODE_SET_METHOD(exports, "decodeFile", DecodeFile);
	NODE_SET_METHOD(exports, "decodeFileAsync", DecodeFileAsync);
}

NODE_MODULE(dbr, Init)
<commit_msg>add BITMAPINFOHEADER definition<commit_after>#include <node.h>
#include <node_buffer.h>
#include <string.h>
#include <uv.h>
#include "If_DBR.h"
#include "BarcodeFormat.h"
#include "BarcodeStructs.h"
#include "ErrorCode.h"

using namespace v8;

typedef unsigned long DWORD;
typedef long LONG;
typedef unsigned short WORD;

typedef struct tagBITMAPINFOHEADER {
  DWORD biSize;
  LONG biWidth;
  LONG biHeight;
  WORD biPlanes;
  WORD biBitCount;
  DWORD biCompression;
  DWORD biSizeImage;
  LONG biXPelsPerMeter;
  LONG biYPelsPerMeter;
  DWORD biClrUsed;
  DWORD biClrImportant;
} BITMAPINFOHEADER;

// Barcode format
const char * GetFormatStr(__int64 format)
{
	if (format == CODE_39)
		return "CODE_39";
	if (format == CODE_128)
		return "CODE_128";
	if (format == CODE_93)
		return "CODE_93";
	if (format == CODABAR)
		return "CODABAR";
	if (format == ITF)
		return "ITF";
	if (format == UPC_A)
		return "UPC_A";
	if (format == UPC_E)
		return "UPC_E";
	if (format == EAN_13)
		return "EAN_13";
	if (format == EAN_8)
		return "EAN_8";
	if (format == INDUSTRIAL_25)
		return "INDUSTRIAL_25";
	if (format == QR_CODE)
		return "QR_CODE";
	if (format == PDF417)
		return "PDF417";
	if (format == DATAMATRIX)
		return "DATAMATRIX";

	return "UNKNOWN";
}

typedef enum {
	NO_BUFFER,
	FILE_STREAM,
	YUYV_BUFFER,
} BufferType;

struct BarcodeWorker
{
    uv_work_t request;              // libuv
	Persistent<Function> callback;	// javascript callback
	__int64 llFormat;				// barcode types
	char filename[128];				// file name
	pBarcodeResultArray pResults;	// result pointer
	unsigned char *buffer;
	int size;						// file size
	int errorCode;					// detection error code
	int width;						// image width
	int height; 					// image height
	BufferType bufferType;			// buffer type
};

bool ConvertCameraGrayDataToDIBBuffer(unsigned char* psrc, int size, int width, int height, unsigned char** ppdist, int *psize)
{
	BITMAPINFOHEADER bitmapInfo;
	memset(&bitmapInfo, 0, sizeof(BITMAPINFOHEADER));

	bitmapInfo.biBitCount = 8;
	bitmapInfo.biWidth = width;
	bitmapInfo.biHeight = height;
	bitmapInfo.biSize = sizeof(BITMAPINFOHEADER);

	int iStride = ((width * 8 + 31) >> 5) << 2;
	int iImageSize = iStride * height;
	if (size < iImageSize)
		return false;

	bitmapInfo.biSizeImage = iImageSize;

	*psize = iImageSize + bitmapInfo.biSize + 1024;
	*ppdist = new unsigned char[*psize];

	//1. copy BITMAPINFOHEADER
	memcpy(*ppdist, &bitmapInfo, sizeof(BITMAPINFOHEADER));

	//2. copy gray color map
	char rgba[1024] = { 0 };
	for (int i = 0; i < 256; ++i)
	{
		rgba[i * 4] = rgba[i * 4 + 1] = rgba[i * 4 + 2] = rgba[i * 4 + 3] = i;
	}
	memcpy(*ppdist + sizeof(BITMAPINFOHEADER), rgba, 1024);

	//3. copy gray data (should be fliped)
	unsigned char* srcptr = psrc + (height - 1)*width;
	unsigned char* dstptr = *ppdist + sizeof(BITMAPINFOHEADER) + 1024;

	for (int j = 0; j < height; ++j, srcptr -= width, dstptr += iStride)
	{
		memcpy(dstptr, srcptr, width);
	}

	return true;
}

// //Assign camera related data to:
// //1.pcamdata---camera gray raw data
// //2.camsize----camera raw data length
// //3.width------camera horizontal resolution
// //4.height-----camera vertical resolution
// ConvertCameraGrayDataToDIBBuffer(pcamdata, camsize, width, height, &pdibdata, &dibsize);

// iRet = reader.DecodeBuffer(pdibdata, dibsize);
// delete []pdibdata, pdibdata=NULL;

/*
 *	uv_work_cb
 */
static void DetectionWorking(uv_work_t *req)
{
	// get the reference to BarcodeWorker
    BarcodeWorker *worker = static_cast<BarcodeWorker *>(req->data);

	// initialize Dynamsoft Barcode Reader
	int iMaxCount = 0x7FFFFFFF;
	ReaderOptions ro = {0};
	pBarcodeResultArray pResults = NULL;
	ro.llBarcodeFormat = worker->llFormat;
	ro.iMaxBarcodesNumPerPage = iMaxCount;

	// decode barcode image
	int ret = 0;
	switch(worker->bufferType)
	{
		case FILE_STREAM:
			{
				if (worker->buffer)
					ret = DBR_DecodeStream(worker->buffer, worker->size, &ro, &pResults);
			}
			break;
		case YUYV_BUFFER:
			{
				if (worker->buffer)
				{
					unsigned char* pdibdata = NULL;
					int dibsize = 0;
					int width = worker->width, height = worker->height;
					int size = width * height;
					int index = 0;
					unsigned char* data = new unsigned char[size];
					// get Y from YUYV
					for (int i = 0; i < size; i++)
					{
						data[i] = worker->buffer[index];
						index += 2;
					}
					// gray conversion
					ConvertCameraGrayDataToDIBBuffer(data, size, width, height, &pdibdata, &dibsize);
					// read barcode
					ret = DBR_DecodeBuffer(pdibdata, dibsize, &ro, &pResults);
					// release memory
					delete []data, data=NULL;
					delete []pdibdata, pdibdata=NULL;
				}
			}
			break;
		default:
			{
				ret = DBR_DecodeFile(worker->filename, &ro, &pResults);
			}
	}

	if (ret)
		printf("Detection error code: %d\n", ret);

	// save results to BarcodeWorker
	worker->errorCode = ret;
	worker->pResults = pResults;
}

/*
 *	uv_after_work_cb
 */
static void DetectionDone(uv_work_t *req,int status)
{
	Isolate* isolate = Isolate::GetCurrent();
	HandleScope scope(isolate);

    // get the reference to BarcodeWorker
    BarcodeWorker *worker = static_cast<BarcodeWorker *>(req->data);

	// get barcode results
	pBarcodeResultArray pResults = worker->pResults;
	int errorCode = worker->errorCode;
	int count = pResults->iBarcodeCount;
	pBarcodeResult* ppBarcodes = pResults->ppBarcodes;
	pBarcodeResult tmp = NULL;

	// array for storing barcode results
	Local<Array> barcodeResults = Array::New(isolate);

	for (int i = 0; i < count; i++)
	{
		tmp = ppBarcodes[i];

		Local<Object> result = Object::New(isolate);
		result->Set(String::NewFromUtf8(isolate, "format"), String::NewFromUtf8(isolate, GetFormatStr(tmp->llFormat)));
		result->Set(String::NewFromUtf8(isolate, "value"), String::NewFromUtf8(isolate, tmp->pBarcodeData));
		barcodeResults->Set(Number::New(isolate, i), result);
	}

	// release memory of barcode results
	DBR_FreeBarcodeResults(&pResults);

    // run the callback
	const unsigned argc = 1;
	Local<Value> argv[argc] = {barcodeResults};
	Local<Function> cb = Local<Function>::New(isolate, worker->callback);
    cb->Call(isolate->GetCurrentContext()->Global(), argc, argv);

	// release memory of BarcodeWorker
    delete worker;
}

/*
 *	initLicense(license)
 */
void InitLicense(const FunctionCallbackInfo<Value>& args) {

	String::Utf8Value license(args[0]->ToString());
	char *pszLicense = *license;
	DBR_InitLicense(pszLicense);
}

/*
 *	decodeFile(fileName, barcodeTypes, callback)
 */
void DecodeFile(const FunctionCallbackInfo<Value>& args) {

	Isolate* isolate = Isolate::GetCurrent();
	HandleScope scope(isolate);

	// get arguments
	String::Utf8Value fileName(args[0]->ToString()); // convert v8 string to char *
	char *pFileName = *fileName; // file name
	__int64 llFormat = args[1]->IntegerValue();	// barcode types
	Local<Function> cb = Local<Function>::Cast(args[2]); // javascript callback function

	// initialize Dynamsoft Barcode Reader
	int iMaxCount = 0x7FFFFFFF;
	ReaderOptions ro = {0};
	pBarcodeResultArray pResults = NULL;
	ro.llBarcodeFormat = llFormat;
	ro.iMaxBarcodesNumPerPage = iMaxCount;

	// decode barcode image
	int ret = DBR_DecodeFile(pFileName, &ro, &pResults);
	if (ret)
		printf("Detection error code: %d\n", ret);

	int count = pResults->iBarcodeCount;
	pBarcodeResult* ppBarcodes = pResults->ppBarcodes;
	pBarcodeResult tmp = NULL;

	// array for storing barcode results
	Local<Array> barcodeResults = Array::New(isolate);

	for (int i = 0; i < count; i++)
	{
		tmp = ppBarcodes[i];

		Local<Object> result = Object::New(isolate);
		result->Set(String::NewFromUtf8(isolate, "format"), String::NewFromUtf8(isolate, GetFormatStr(tmp->llFormat)));
		result->Set(String::NewFromUtf8(isolate, "value"), String::NewFromUtf8(isolate, tmp->pBarcodeData));
		barcodeResults->Set(Number::New(isolate, i), result);
	}

	// release memory of barcode results
	DBR_FreeBarcodeResults(&pResults);

	// run the callback
	const unsigned argc = 1;
	Local<Value> argv[argc] = { barcodeResults };
	cb->Call(isolate->GetCurrentContext()->Global(), argc, argv);
}

/*
 *	decodeFileAsync(fileName, barcodeTypes, callback)
 */
void DecodeFileAsync(const FunctionCallbackInfo<Value>& args) {
	Isolate* isolate = Isolate::GetCurrent();
	HandleScope scope(isolate);

	// get arguments
	String::Utf8Value fileName(args[0]->ToString()); // file name
	char *pFileName = *fileName;
	__int64 llFormat = args[1]->IntegerValue(); // barcode types
	Local<Function> cb = Local<Function>::Cast(args[2]); // javascript callback function

	// initialize BarcodeWorker
	BarcodeWorker *worker = new BarcodeWorker;
	worker->request.data = worker;
	strcpy(worker->filename, pFileName);
	worker->callback.Reset(isolate, cb);
	worker->llFormat = llFormat;
	worker->pResults = NULL;
	worker->buffer = NULL;
	worker->bufferType = NO_BUFFER;

	uv_queue_work(uv_default_loop(), &worker->request, (uv_work_cb)DetectionWorking, (uv_after_work_cb)DetectionDone);
}

/*
 *	decodeFileStreamAsync(fileStream, fileSize, barcodeTypes, callback)
 */
void DecodeFileStreamAsync(const FunctionCallbackInfo<Value>& args) {
	Isolate* isolate = Isolate::GetCurrent();
	HandleScope scope(isolate);

	// get arguments
	unsigned char* buffer = (unsigned char*) node::Buffer::Data(args[0]->ToObject()); // file stream
	int fileSize = args[1]->IntegerValue();	// file size
	__int64 llFormat = args[2]->IntegerValue(); // barcode types
	Local<Function> cb = Local<Function>::Cast(args[3]); // javascript callback function

	// initialize BarcodeWorker
	BarcodeWorker *worker = new BarcodeWorker;
	worker->request.data = worker;
	worker->callback.Reset(isolate, cb);
	worker->llFormat = llFormat;
	worker->pResults = NULL;
	worker->buffer = buffer;
	worker->size = fileSize;
	worker->bufferType = FILE_STREAM;

	uv_queue_work(uv_default_loop(), &worker->request, (uv_work_cb)DetectionWorking, (uv_after_work_cb)DetectionDone);
}

/*
 *	decodeYUYVAsync(buffer, width, height, barcodeTypes, callback)
 */
void DecodeYUYVAsync(const FunctionCallbackInfo<Value>& args) {
	Isolate* isolate = Isolate::GetCurrent();
	HandleScope scope(isolate);

	// get arguments
	unsigned char* buffer = (unsigned char*) node::Buffer::Data(args[0]->ToObject()); // file stream
	int width = args[1]->IntegerValue();	// image width
	int height = args[2]->IntegerValue();	// image height
	__int64 llFormat = args[3]->IntegerValue(); // barcode types
	Local<Function> cb = Local<Function>::Cast(args[4]); // javascript callback function

	// initialize BarcodeWorker
	BarcodeWorker *worker = new BarcodeWorker;
	worker->request.data = worker;
	worker->callback.Reset(isolate, cb);
	worker->llFormat = llFormat;
	worker->pResults = NULL;
	worker->buffer = buffer;
	worker->width = width;
	worker->height = height;
	worker->bufferType = YUYV_BUFFER;

	uv_queue_work(uv_default_loop(), &worker->request, (uv_work_cb)DetectionWorking, (uv_after_work_cb)DetectionDone);
}

void Init(Handle<Object> exports) {
	NODE_SET_METHOD(exports, "decodeYUYVAsync", DecodeYUYVAsync);
	NODE_SET_METHOD(exports, "decodeFileStreamAsync", DecodeFileStreamAsync);
	NODE_SET_METHOD(exports, "initLicense", InitLicense);
	NODE_SET_METHOD(exports, "decodeFile", DecodeFile);
	NODE_SET_METHOD(exports, "decodeFileAsync", DecodeFileAsync);
}

NODE_MODULE(dbr, Init)
<|endoftext|>


<commit_before>#ifndef TIMEFUNCTION_HH
#define TIMEFUNCTION_HH

#include <dune/fem/function/common/function.hh>

namespace Dune {
	template < class FunctionSpaceImp, class FunctionImp, class TimeProviderImp >
	class TimeFunction :
				public BartonNackmanInterface< TimeFunction < FunctionSpaceImp, FunctionImp, TimeProviderImp >,
									   FunctionImp >,
				public Function < FunctionSpaceImp , TimeFunction < FunctionSpaceImp, FunctionImp, TimeProviderImp > >
	{
		protected:
			typedef TimeFunction< FunctionSpaceImp, FunctionImp, TimeProviderImp >
				ThisType;
			typedef Function < FunctionSpaceImp , ThisType >
				BaseType;
			typedef BartonNackmanInterface< ThisType, FunctionImp >
				Interface;

			const TimeProviderImp& timeProvider_;

			using Interface::asImp;

		public:
			TimeFunction(const TimeProviderImp& timeProvider, const FunctionSpaceImp& space )
			  :BaseType( space ),
			  timeProvider_( timeProvider )
			{}

			~TimeFunction()
			{}

			virtual inline void evaluate( const typename BaseType::DomainType& x, typename BaseType::RangeType& ret ) const
			{
				const double t = timeProvider_.subTime();
				CHECK_AND_CALL_INTERFACE_IMPLEMENTATION( asImp().evaluateTime( t, x, ret ) );
			}

			/** \brief evaluate the Jacobian of the function
			 *
			 *  \param[in]  x    evaluation point
			 *  \param[out] ret  value of the Jacobian in x
			 */
			inline void jacobian ( const typename BaseType::DomainType &x,
								   typename BaseType::JacobianRangeType &ret ) const
			{
			  CHECK_AND_CALL_INTERFACE_IMPLEMENTATION( asImp().jacobian( x, ret ) );
			}

			/** \brief evaluate a derivative of the function
			 *
			 *  \param[in]  diffVariable  vector describing the partial derivative to
			 *                            evaluate
			 *  \param[in]  x             evaluation point
			 *  \param[out] ret           value of the derivative in x
			 */
			template< int diffOrder >
			inline void evaluate ( const FieldVector< deriType, diffOrder > &diffVariable,
								   const typename BaseType::DomainType &x,
								   typename BaseType::RangeType &ret ) const
			{
			  CHECK_AND_CALL_INTERFACE_IMPLEMENTATION
				( asImp().evaluate( diffVariable, x, ret ) );
			}

	};

}

#endif // TIMEFUNCTION_HH
<commit_msg>throw an excpetion when not implemented function's called<commit_after>#ifndef TIMEFUNCTION_HH
#define TIMEFUNCTION_HH

#include <dune/fem/function/common/function.hh>

namespace Dune {
	template < class FunctionSpaceImp, class FunctionImp, class TimeProviderImp >
	class TimeFunction :
				public BartonNackmanInterface< TimeFunction < FunctionSpaceImp, FunctionImp, TimeProviderImp >,
									   FunctionImp >,
				public Function < FunctionSpaceImp , TimeFunction < FunctionSpaceImp, FunctionImp, TimeProviderImp > >
	{
		protected:
			typedef TimeFunction< FunctionSpaceImp, FunctionImp, TimeProviderImp >
				ThisType;
			typedef Function < FunctionSpaceImp , ThisType >
				BaseType;
			typedef BartonNackmanInterface< ThisType, FunctionImp >
				Interface;

			const TimeProviderImp& timeProvider_;

			using Interface::asImp;

		public:
			TimeFunction(const TimeProviderImp& timeProvider, const FunctionSpaceImp& space )
			  :BaseType( space ),
			  timeProvider_( timeProvider )
			{}

			~TimeFunction()
			{}

			virtual inline void evaluate( const typename BaseType::DomainType& x, typename BaseType::RangeType& ret ) const
			{
				const double t = timeProvider_.subTime();
				CHECK_AND_CALL_INTERFACE_IMPLEMENTATION( asImp().evaluateTime( t, x, ret ) );
			}

			/** \brief evaluate the Jacobian of the function
			 *
			 *  \param[in]  x    evaluation point
			 *  \param[out] ret  value of the Jacobian in x
			 */
			inline void jacobian ( const typename BaseType::DomainType &x,
								   typename BaseType::JacobianRangeType &ret ) const
			{
				DUNE_THROW( Dune::NotImplemented, "needs to be extended to allow time dependent jacobian" );
			  CHECK_AND_CALL_INTERFACE_IMPLEMENTATION( asImp().jacobian( x, ret ) );
			}

			/** \brief evaluate a derivative of the function
			 *
			 *  \param[in]  diffVariable  vector describing the partial derivative to
			 *                            evaluate
			 *  \param[in]  x             evaluation point
			 *  \param[out] ret           value of the derivative in x
			 */
			template< int diffOrder >
			inline void evaluate ( const FieldVector< deriType, diffOrder > &diffVariable,
								   const typename BaseType::DomainType &x,
								   typename BaseType::RangeType &ret ) const
			{
			  CHECK_AND_CALL_INTERFACE_IMPLEMENTATION
				( asImp().evaluate( diffVariable, x, ret ) );
			}

	};

}

#endif // TIMEFUNCTION_HH
<|endoftext|>


<commit_before><commit_msg>Delete class.cpp<commit_after><|endoftext|>


<commit_before>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "itkExceptionObject.h"
#include "itkFixedArray.h"
#include "otbLandsatTMIndices.h"

int otbLandsatTMIndexVis(int argc, char * argv[])
{
  typedef double                           OutputPixelType;
  typedef itk::FixedArray< double, 8 >     InputPixelType;

  typedef otb::Functor::LandsatTM::Vis<InputPixelType, OutputPixelType> FunctorType;

  FunctorType visFunct = FunctorType();

  double TM1 = (::atof(argv[1]));
  double TM2 = (::atof(argv[2]));
  double TM3 = (::atof(argv[3]));
  double TM4 = (::atof(argv[4]));
  double TM5 = (::atof(argv[5]));
  double TM61 = (::atof(argv[6]));
  double TM62 = (::atof(argv[7]));
  double TM7 = (::atof(argv[8]));

  double goodResult = (TM1+TM2+TM3)/3.0;

  std::cout << goodResult ;

  InputPixelType pixel;
  pixel[0] = TM1;
  pixel[1] = TM2;
  pixel[2] = TM3;
  pixel[3] = TM4;
  pixel[4] = TM5;
  pixel[5] = TM61;
  pixel[6] = TM62;
  pixel[7] = TM7;

  double result = visFunct(pixel);

  std::cout << " " << result << std::endl;

  if( result!=goodResult ) return EXIT_FAILURE;

  return EXIT_SUCCESS;
}
<commit_msg>TEST: Landsat TM MIR1 test<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "itkExceptionObject.h"
#include "itkFixedArray.h"
#include "otbLandsatTMIndices.h"

int otbLandsatTMIndexMIR1(int argc, char * argv[])
{
  typedef double                           OutputPixelType;
  typedef itk::FixedArray< double, 8 >     InputPixelType;

  typedef otb::Functor::LandsatTM::MIR1<InputPixelType, OutputPixelType> FunctorType;

  FunctorType mir1Funct = FunctorType();

  double TM1 = (::atof(argv[1]));
  double TM2 = (::atof(argv[2]));
  double TM3 = (::atof(argv[3]));
  double TM4 = (::atof(argv[4]));
  double TM5 = (::atof(argv[5]));
  double TM61 = (::atof(argv[6]));
  double TM62 = (::atof(argv[7]));
  double TM7 = (::atof(argv[8]));

  double goodResult = TM5;

  std::cout << goodResult ;

  InputPixelType pixel;
  pixel[0] = TM1;
  pixel[1] = TM2;
  pixel[2] = TM3;
  pixel[3] = TM4;
  pixel[4] = TM5;
  pixel[5] = TM61;
  pixel[6] = TM62;
  pixel[7] = TM7;

  double result = visFunct(pixel);

  std::cout << " " << result << std::endl;

  if( result!=goodResult ) return EXIT_FAILURE;

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: TableWindowAccess.cxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: oj $ $Date: 2002-11-26 12:45:47 $
 *
 *  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 DBACCESS_TABLEWINDOWACCESS_HXX
#include "TableWindowAccess.hxx"
#endif
#ifndef DBACCESS_JACCESS_HXX
#include "JAccess.hxx"
#endif
#ifndef DBAUI_TABLEWINDOW_HXX
#include "TableWindow.hxx"
#endif
#ifndef DBAUI_TABLEWINDOWLISTBOX_HXX
#include "TableWindowListBox.hxx"
#endif
#ifndef DBAUI_JOINDESIGNVIEW_HXX
#include "JoinDesignView.hxx"
#endif
#ifndef DBAUI_JOINCONTROLLER_HXX
#include "JoinController.hxx"
#endif
#ifndef DBAUI_JOINTABLEVIEW_HXX
#include "JoinTableView.hxx"
#endif
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEROLE_HPP_
#include <drafts/com/sun/star/accessibility/AccessibleRole.hpp>
#endif
#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLERELATIONTYPE_HPP_
#include <drafts/com/sun/star/accessibility/AccessibleRelationType.hpp>
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif
#ifndef _DBU_QRY_HRC_
#include "dbu_qry.hrc"
#endif

namespace dbaui
{
    using namespace ::drafts::com::sun::star::accessibility;
    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::beans;
    using namespace ::com::sun::star::lang;
    //  using namespace ::com::sun::star::awt;
    using namespace ::com::sun::star;

    OTableWindowAccess::OTableWindowAccess(const Reference< XAccessible>& _xParent,
                                            OTableWindow* _pTable)
        :OAccessibleBase(_pTable,_xParent)
        ,m_pTable(_pTable)
    {
        OSL_ENSURE(m_pTable,"Table isn't valid!");
    }
    // -----------------------------------------------------------------------------
    void SAL_CALL OTableWindowAccess::disposing()
    {
        m_pTable = NULL;
        OAccessibleBase::disposing();
    }
    // -----------------------------------------------------------------------------
    Any SAL_CALL OTableWindowAccess::queryInterface( const Type& aType ) throw (RuntimeException)
    {
        Any aRet(OAccessibleBase::queryInterface( aType ));
        return aRet.hasValue() ? aRet : OTableWindowAccess_BASE::queryInterface( aType );
    }
    // -----------------------------------------------------------------------------
    Sequence< Type > SAL_CALL OTableWindowAccess::getTypes(  ) throw (RuntimeException)
    {
        return ::comphelper::concatSequences(OAccessibleBase::getTypes(),OTableWindowAccess_BASE::getTypes());
    }
    // -----------------------------------------------------------------------------
    ::rtl::OUString SAL_CALL OTableWindowAccess::getImplementationName() throw(RuntimeException)
    {
        return getImplementationName_Static();
    }
    // -----------------------------------------------------------------------------
    Sequence< ::rtl::OUString > SAL_CALL OTableWindowAccess::getSupportedServiceNames() throw(RuntimeException)
    {
        return getSupportedServiceNames_Static();
    }
    // -----------------------------------------------------------------------------
    // XServiceInfo - static methods
    Sequence< ::rtl::OUString > OTableWindowAccess::getSupportedServiceNames_Static(void) throw( RuntimeException )
    {
        Sequence< ::rtl::OUString > aSupported(2);
        aSupported[0] = ::rtl::OUString::createFromAscii("drafts.com.sun.star.accessibility.Accessible");
        aSupported[1] = ::rtl::OUString::createFromAscii("drafts.com.sun.star.accessibility.AccessibleContext");
        return aSupported;
    }
    // -----------------------------------------------------------------------------
    ::rtl::OUString OTableWindowAccess::getImplementationName_Static(void) throw( RuntimeException )
    {
        return ::rtl::OUString::createFromAscii("org.openoffice.comp.dbu.TableWindowAccessibility");
    }
    // -----------------------------------------------------------------------------
    // XAccessibleContext
    sal_Int32 SAL_CALL OTableWindowAccess::getAccessibleChildCount(  ) throw (RuntimeException)
    {
        return 2;
    }
    // -----------------------------------------------------------------------------
    Reference< XAccessible > SAL_CALL OTableWindowAccess::getAccessibleChild( sal_Int32 i ) throw (IndexOutOfBoundsException,RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        Reference< XAccessible > aRet;
        if(i == 0 && m_pTable)
            aRet = m_pTable->GetTitleCtrl()->GetAccessible();
        else if(i == 1 && m_pTable)
            aRet = m_pTable->GetListBox()->GetAccessible();
        else
            throw IndexOutOfBoundsException();
        return aRet;
    }
    // -----------------------------------------------------------------------------
    sal_Int32 SAL_CALL OTableWindowAccess::getAccessibleIndexInParent(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        sal_Int32 nIndex = -1;
        if( m_pTable )
        {
            // search the postion of our table window in the table window map
            OJoinTableView::OTableWindowMap* pMap = m_pTable->getTableView()->GetTabWinMap();
            OJoinTableView::OTableWindowMap::iterator aIter = pMap->begin();
            for (nIndex = 0; aIter != pMap->end() && aIter->second != m_pTable; ++nIndex,++aIter)
                ;
            nIndex = aIter != pMap->end() ? nIndex : -1;
        }
        return nIndex;
    }
    // -----------------------------------------------------------------------------
    sal_Int16 SAL_CALL OTableWindowAccess::getAccessibleRole(  ) throw (RuntimeException)
    {
        return AccessibleRole::PANEL; // ? or may be an AccessibleRole::WINDOW
    }
    // -----------------------------------------------------------------------------
    Reference< XAccessibleRelationSet > SAL_CALL OTableWindowAccess::getAccessibleRelationSet(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        return this;
    }
    // -----------------------------------------------------------------------------
    // XAccessibleComponent
    Reference< XAccessible > SAL_CALL OTableWindowAccess::getAccessibleAt( const awt::Point& _aPoint ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        Reference< XAccessible > aRet;
        if( m_pTable )
        {
            Point aPoint(_aPoint.X,_aPoint.Y);
            Rectangle aRect(m_pTable->GetDesktopRectPixel());
            if( aRect.IsInside(aPoint) )
                aRet = this;
            else if( m_pTable->GetListBox()->GetDesktopRectPixel().IsInside(aPoint))
                aRet = m_pTable->GetListBox()->GetAccessible();
        }
        return aRet;
    }
    // -----------------------------------------------------------------------------
    sal_Int32 SAL_CALL OTableWindowAccess::getRelationCount(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        return m_pTable ? m_pTable->getTableView()->getConnectionCount(m_pTable) : sal_Int32(0);
    }
    // -----------------------------------------------------------------------------
    AccessibleRelation SAL_CALL OTableWindowAccess::getRelation( sal_Int32 nIndex ) throw (IndexOutOfBoundsException, RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        if( nIndex < 0 || nIndex >= getRelationCount() )
            throw IndexOutOfBoundsException();

        AccessibleRelation aRet;
        if( m_pTable )
        {
            OJoinTableView* pView = m_pTable->getTableView();
            ::std::vector<OTableConnection*>::const_iterator aIter = pView->getTableConnections(m_pTable) + nIndex;
            aRet.TargetSet.realloc(1);
            aRet.TargetSet[0] = m_xParentContext->getAccessibleChild(aIter - pView->getTableConnections()->begin());
            aRet.RelationType = AccessibleRelationType::CONTROLLER_FOR;
        }
        return aRet;
    }
    // -----------------------------------------------------------------------------
    sal_Bool SAL_CALL OTableWindowAccess::containsRelation( sal_Int16 aRelationType ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        return      AccessibleRelationType::CONTROLLER_FOR == aRelationType
                &&  m_pTable->getTableView()->ExistsAConn(m_pTable);
    }
    // -----------------------------------------------------------------------------
    AccessibleRelation SAL_CALL OTableWindowAccess::getRelationByType( sal_Int16 aRelationType ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        if( AccessibleRelationType::CONTROLLER_FOR == aRelationType && m_pTable)
        {
            OJoinTableView* pView = m_pTable->getTableView();
            const ::std::vector<OTableConnection*>* pConnectionList = pView->getTableConnections();

            ::std::vector<OTableConnection*>::const_iterator aIter = pView->getTableConnections(m_pTable);
            ::std::vector< Reference<XInterface> > aRelations;
            aRelations.reserve(5); // just guessing
            for (; aIter != pConnectionList->end() ; ++aIter )
                aRelations.push_back(m_xParentContext->getAccessibleChild(aIter - pConnectionList->begin()));

            Sequence< Reference<XInterface> > aSeq(aRelations.begin(),aRelations.size());
            return AccessibleRelation(AccessibleRelationType::CONTROLLER_FOR,aSeq);
        }
        return AccessibleRelation();
    }
    // -----------------------------------------------------------------------------
    sal_Bool OTableWindowAccess::isEditable() const
    {
        return m_pTable && !m_pTable->getTableView()->getDesignView()->getController()->isReadOnly();
    }
    // -----------------------------------------------------------------------------
    ::rtl::OUString SAL_CALL OTableWindowAccess::getTitledBorderText(  ) throw (RuntimeException)
    {
        return getAccessibleName(  );
    }
    // -----------------------------------------------------------------------------
    ::rtl::OUString SAL_CALL OTableWindowAccess::getAccessibleName(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        ::rtl::OUString sAccessibleName;
        if ( m_pTable )
            sAccessibleName = m_pTable->getTitle();
        return sAccessibleName;
    }
    // -----------------------------------------------------------------------------
}
// -----------------------------------------------------------------------------

<commit_msg>INTEGRATION: CWS uaa02 (1.6.64); FILE MERGED 2003/04/11 16:18:51 mt 1.6.64.1: #108656# Moved accessibility from drafts to final<commit_after>/*************************************************************************
 *
 *  $RCSfile: TableWindowAccess.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: vg $ $Date: 2003-04-24 17:22:58 $
 *
 *  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 DBACCESS_TABLEWINDOWACCESS_HXX
#include "TableWindowAccess.hxx"
#endif
#ifndef DBACCESS_JACCESS_HXX
#include "JAccess.hxx"
#endif
#ifndef DBAUI_TABLEWINDOW_HXX
#include "TableWindow.hxx"
#endif
#ifndef DBAUI_TABLEWINDOWLISTBOX_HXX
#include "TableWindowListBox.hxx"
#endif
#ifndef DBAUI_JOINDESIGNVIEW_HXX
#include "JoinDesignView.hxx"
#endif
#ifndef DBAUI_JOINCONTROLLER_HXX
#include "JoinController.hxx"
#endif
#ifndef DBAUI_JOINTABLEVIEW_HXX
#include "JoinTableView.hxx"
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLEROLE_HPP_
#include <com/sun/star/accessibility/AccessibleRole.hpp>
#endif
#ifndef _COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLERELATIONTYPE_HPP_
#include <com/sun/star/accessibility/AccessibleRelationType.hpp>
#endif
#ifndef _COMPHELPER_SEQUENCE_HXX_
#include <comphelper/sequence.hxx>
#endif
#ifndef _DBU_QRY_HRC_
#include "dbu_qry.hrc"
#endif

namespace dbaui
{
    using namespace ::com::sun::star::accessibility;
    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::beans;
    using namespace ::com::sun::star::lang;
    //  using namespace ::com::sun::star::awt;
    using namespace ::com::sun::star;

    OTableWindowAccess::OTableWindowAccess(const Reference< XAccessible>& _xParent,
                                            OTableWindow* _pTable)
        :OAccessibleBase(_pTable,_xParent)
        ,m_pTable(_pTable)
    {
        OSL_ENSURE(m_pTable,"Table isn't valid!");
    }
    // -----------------------------------------------------------------------------
    void SAL_CALL OTableWindowAccess::disposing()
    {
        m_pTable = NULL;
        OAccessibleBase::disposing();
    }
    // -----------------------------------------------------------------------------
    Any SAL_CALL OTableWindowAccess::queryInterface( const Type& aType ) throw (RuntimeException)
    {
        Any aRet(OAccessibleBase::queryInterface( aType ));
        return aRet.hasValue() ? aRet : OTableWindowAccess_BASE::queryInterface( aType );
    }
    // -----------------------------------------------------------------------------
    Sequence< Type > SAL_CALL OTableWindowAccess::getTypes(  ) throw (RuntimeException)
    {
        return ::comphelper::concatSequences(OAccessibleBase::getTypes(),OTableWindowAccess_BASE::getTypes());
    }
    // -----------------------------------------------------------------------------
    ::rtl::OUString SAL_CALL OTableWindowAccess::getImplementationName() throw(RuntimeException)
    {
        return getImplementationName_Static();
    }
    // -----------------------------------------------------------------------------
    Sequence< ::rtl::OUString > SAL_CALL OTableWindowAccess::getSupportedServiceNames() throw(RuntimeException)
    {
        return getSupportedServiceNames_Static();
    }
    // -----------------------------------------------------------------------------
    // XServiceInfo - static methods
    Sequence< ::rtl::OUString > OTableWindowAccess::getSupportedServiceNames_Static(void) throw( RuntimeException )
    {
        Sequence< ::rtl::OUString > aSupported(2);
        aSupported[0] = ::rtl::OUString::createFromAscii("com.sun.star.accessibility.Accessible");
        aSupported[1] = ::rtl::OUString::createFromAscii("com.sun.star.accessibility.AccessibleContext");
        return aSupported;
    }
    // -----------------------------------------------------------------------------
    ::rtl::OUString OTableWindowAccess::getImplementationName_Static(void) throw( RuntimeException )
    {
        return ::rtl::OUString::createFromAscii("org.openoffice.comp.dbu.TableWindowAccessibility");
    }
    // -----------------------------------------------------------------------------
    // XAccessibleContext
    sal_Int32 SAL_CALL OTableWindowAccess::getAccessibleChildCount(  ) throw (RuntimeException)
    {
        return 2;
    }
    // -----------------------------------------------------------------------------
    Reference< XAccessible > SAL_CALL OTableWindowAccess::getAccessibleChild( sal_Int32 i ) throw (IndexOutOfBoundsException,RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        Reference< XAccessible > aRet;
        if(i == 0 && m_pTable)
            aRet = m_pTable->GetTitleCtrl()->GetAccessible();
        else if(i == 1 && m_pTable)
            aRet = m_pTable->GetListBox()->GetAccessible();
        else
            throw IndexOutOfBoundsException();
        return aRet;
    }
    // -----------------------------------------------------------------------------
    sal_Int32 SAL_CALL OTableWindowAccess::getAccessibleIndexInParent(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        sal_Int32 nIndex = -1;
        if( m_pTable )
        {
            // search the postion of our table window in the table window map
            OJoinTableView::OTableWindowMap* pMap = m_pTable->getTableView()->GetTabWinMap();
            OJoinTableView::OTableWindowMap::iterator aIter = pMap->begin();
            for (nIndex = 0; aIter != pMap->end() && aIter->second != m_pTable; ++nIndex,++aIter)
                ;
            nIndex = aIter != pMap->end() ? nIndex : -1;
        }
        return nIndex;
    }
    // -----------------------------------------------------------------------------
    sal_Int16 SAL_CALL OTableWindowAccess::getAccessibleRole(  ) throw (RuntimeException)
    {
        return AccessibleRole::PANEL; // ? or may be an AccessibleRole::WINDOW
    }
    // -----------------------------------------------------------------------------
    Reference< XAccessibleRelationSet > SAL_CALL OTableWindowAccess::getAccessibleRelationSet(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        return this;
    }
    // -----------------------------------------------------------------------------
    // XAccessibleComponent
    Reference< XAccessible > SAL_CALL OTableWindowAccess::getAccessibleAtPoint( const awt::Point& _aPoint ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        Reference< XAccessible > aRet;
        if( m_pTable )
        {
            Point aPoint(_aPoint.X,_aPoint.Y);
            Rectangle aRect(m_pTable->GetDesktopRectPixel());
            if( aRect.IsInside(aPoint) )
                aRet = this;
            else if( m_pTable->GetListBox()->GetDesktopRectPixel().IsInside(aPoint))
                aRet = m_pTable->GetListBox()->GetAccessible();
        }
        return aRet;
    }
    // -----------------------------------------------------------------------------
    sal_Int32 SAL_CALL OTableWindowAccess::getRelationCount(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        return m_pTable ? m_pTable->getTableView()->getConnectionCount(m_pTable) : sal_Int32(0);
    }
    // -----------------------------------------------------------------------------
    AccessibleRelation SAL_CALL OTableWindowAccess::getRelation( sal_Int32 nIndex ) throw (IndexOutOfBoundsException, RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        if( nIndex < 0 || nIndex >= getRelationCount() )
            throw IndexOutOfBoundsException();

        AccessibleRelation aRet;
        if( m_pTable )
        {
            OJoinTableView* pView = m_pTable->getTableView();
            ::std::vector<OTableConnection*>::const_iterator aIter = pView->getTableConnections(m_pTable) + nIndex;
            aRet.TargetSet.realloc(1);
            aRet.TargetSet[0] = m_xParentContext->getAccessibleChild(aIter - pView->getTableConnections()->begin());
            aRet.RelationType = AccessibleRelationType::CONTROLLER_FOR;
        }
        return aRet;
    }
    // -----------------------------------------------------------------------------
    sal_Bool SAL_CALL OTableWindowAccess::containsRelation( sal_Int16 aRelationType ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        return      AccessibleRelationType::CONTROLLER_FOR == aRelationType
                &&  m_pTable->getTableView()->ExistsAConn(m_pTable);
    }
    // -----------------------------------------------------------------------------
    AccessibleRelation SAL_CALL OTableWindowAccess::getRelationByType( sal_Int16 aRelationType ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        if( AccessibleRelationType::CONTROLLER_FOR == aRelationType && m_pTable)
        {
            OJoinTableView* pView = m_pTable->getTableView();
            const ::std::vector<OTableConnection*>* pConnectionList = pView->getTableConnections();

            ::std::vector<OTableConnection*>::const_iterator aIter = pView->getTableConnections(m_pTable);
            ::std::vector< Reference<XInterface> > aRelations;
            aRelations.reserve(5); // just guessing
            for (; aIter != pConnectionList->end() ; ++aIter )
                aRelations.push_back(m_xParentContext->getAccessibleChild(aIter - pConnectionList->begin()));

            Sequence< Reference<XInterface> > aSeq(aRelations.begin(),aRelations.size());
            return AccessibleRelation(AccessibleRelationType::CONTROLLER_FOR,aSeq);
        }
        return AccessibleRelation();
    }
    // -----------------------------------------------------------------------------
    sal_Bool OTableWindowAccess::isEditable() const
    {
        return m_pTable && !m_pTable->getTableView()->getDesignView()->getController()->isReadOnly();
    }
    // -----------------------------------------------------------------------------
    ::rtl::OUString SAL_CALL OTableWindowAccess::getTitledBorderText(  ) throw (RuntimeException)
    {
        return getAccessibleName(  );
    }
    // -----------------------------------------------------------------------------
    ::rtl::OUString SAL_CALL OTableWindowAccess::getAccessibleName(  ) throw (RuntimeException)
    {
        ::osl::MutexGuard aGuard( m_aMutex  );
        ::rtl::OUString sAccessibleName;
        if ( m_pTable )
            sAccessibleName = m_pTable->getTitle();
        return sAccessibleName;
    }
    // -----------------------------------------------------------------------------
}
// -----------------------------------------------------------------------------

<|endoftext|>


<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "webkit/plugins/ppapi/ppb_url_request_info_impl.h"

#include "base/logging.h"
#include "base/string_util.h"
#include "googleurl/src/gurl.h"
#include "net/http/http_util.h"
#include "ppapi/c/pp_var.h"
#include "third_party/WebKit/WebKit/chromium/public/WebData.h"
#include "third_party/WebKit/WebKit/chromium/public/WebDocument.h"
#include "third_party/WebKit/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/WebKit/chromium/public/WebHTTPBody.h"
#include "third_party/WebKit/WebKit/chromium/public/WebURL.h"
#include "third_party/WebKit/WebKit/chromium/public/WebURLRequest.h"
#include "webkit/plugins/ppapi/common.h"
#include "webkit/plugins/ppapi/plugin_module.h"
#include "webkit/plugins/ppapi/ppb_file_ref_impl.h"
#include "webkit/plugins/ppapi/string.h"
#include "webkit/plugins/ppapi/var.h"
#include "webkit/glue/webkit_glue.h"

using WebKit::WebData;
using WebKit::WebHTTPBody;
using WebKit::WebString;
using WebKit::WebFrame;
using WebKit::WebURL;
using WebKit::WebURLRequest;

namespace webkit {
namespace ppapi {

namespace {

// If any of these request headers are specified, they will not be sent.
// TODO(darin): Add more based on security considerations?
const char* const kIgnoredRequestHeaders[] = {
  "content-length"
};

PP_Bool IsIgnoredRequestHeader(const std::string& name) {
  for (size_t i = 0; i < arraysize(kIgnoredRequestHeaders); ++i) {
    if (LowerCaseEqualsASCII(name, kIgnoredRequestHeaders[i]))
      return PP_TRUE;
  }
  return PP_FALSE;
}

PP_Resource Create(PP_Module module_id) {
  PluginModule* module = ResourceTracker::Get()->GetModule(module_id);
  if (!module)
    return 0;

  PPB_URLRequestInfo_Impl* request = new PPB_URLRequestInfo_Impl(module);

  return request->GetReference();
}

PP_Bool IsURLRequestInfo(PP_Resource resource) {
  return BoolToPPBool(!!Resource::GetAs<PPB_URLRequestInfo_Impl>(resource));
}

PP_Bool SetProperty(PP_Resource request_id,
                    PP_URLRequestProperty property,
                    PP_Var var) {
  scoped_refptr<PPB_URLRequestInfo_Impl> request(
      Resource::GetAs<PPB_URLRequestInfo_Impl>(request_id));
  if (!request)
    return PP_FALSE;

  if (var.type == PP_VARTYPE_BOOL) {
    return BoolToPPBool(
        request->SetBooleanProperty(property,
                                    PPBoolToBool(var.value.as_bool)));
  }

  if (var.type == PP_VARTYPE_STRING) {
    scoped_refptr<StringVar> string(StringVar::FromPPVar(var));
    if (string) {
      return BoolToPPBool(request->SetStringProperty(property,
                                                     string->value()));
    }
  }

  return PP_FALSE;
}

PP_Bool AppendDataToBody(PP_Resource request_id,
                         const char* data,
                         uint32_t len) {
  scoped_refptr<PPB_URLRequestInfo_Impl> request(
      Resource::GetAs<PPB_URLRequestInfo_Impl>(request_id));
  if (!request)
    return PP_FALSE;

  return BoolToPPBool(request->AppendDataToBody(std::string(data, len)));
}

PP_Bool AppendFileToBody(PP_Resource request_id,
                      PP_Resource file_ref_id,
                      int64_t start_offset,
                      int64_t number_of_bytes,
                      PP_Time expected_last_modified_time) {
  scoped_refptr<PPB_URLRequestInfo_Impl> request(
      Resource::GetAs<PPB_URLRequestInfo_Impl>(request_id));
  if (!request)
    return PP_FALSE;

  scoped_refptr<PPB_FileRef_Impl> file_ref(
      Resource::GetAs<PPB_FileRef_Impl>(file_ref_id));
  if (!file_ref)
    return PP_FALSE;

  return BoolToPPBool(request->AppendFileToBody(file_ref,
                                                start_offset,
                                                number_of_bytes,
                                                expected_last_modified_time));
}

const PPB_URLRequestInfo ppb_urlrequestinfo = {
  &Create,
  &IsURLRequestInfo,
  &SetProperty,
  &AppendDataToBody,
  &AppendFileToBody
};

}  // namespace

struct PPB_URLRequestInfo_Impl::BodyItem {
  BodyItem(const std::string& data)
      : data(data),
        start_offset(0),
        number_of_bytes(-1),
        expected_last_modified_time(0.0) {
  }

  BodyItem(PPB_FileRef_Impl* file_ref,
           int64_t start_offset,
           int64_t number_of_bytes,
           PP_Time expected_last_modified_time)
      : file_ref(file_ref),
        start_offset(start_offset),
        number_of_bytes(number_of_bytes),
        expected_last_modified_time(expected_last_modified_time) {
  }

  std::string data;
  scoped_refptr<PPB_FileRef_Impl> file_ref;
  int64_t start_offset;
  int64_t number_of_bytes;
  PP_Time expected_last_modified_time;
};

PPB_URLRequestInfo_Impl::PPB_URLRequestInfo_Impl(PluginModule* module)
    : Resource(module),
      stream_to_file_(false),
      follow_redirects_(true),
      record_download_progress_(false),
      record_upload_progress_(false) {
}

PPB_URLRequestInfo_Impl::~PPB_URLRequestInfo_Impl() {
}

// static
const PPB_URLRequestInfo* PPB_URLRequestInfo_Impl::GetInterface() {
  return &ppb_urlrequestinfo;
}

PPB_URLRequestInfo_Impl* PPB_URLRequestInfo_Impl::AsPPB_URLRequestInfo_Impl() {
  return this;
}

bool PPB_URLRequestInfo_Impl::SetBooleanProperty(PP_URLRequestProperty property,
                                                 bool value) {
  switch (property) {
    case PP_URLREQUESTPROPERTY_STREAMTOFILE:
      stream_to_file_ = value;
      return true;
    case PP_URLREQUESTPROPERTY_FOLLOWREDIRECTS:
      follow_redirects_ = value;
      return true;
    case PP_URLREQUESTPROPERTY_RECORDDOWNLOADPROGRESS:
      record_download_progress_ = value;
      return true;
    case PP_URLREQUESTPROPERTY_RECORDUPLOADPROGRESS:
      record_upload_progress_ = value;
      return true;
    default:
      //NOTIMPLEMENTED();  // TODO(darin): Implement me!
      return false;
  }
}

bool PPB_URLRequestInfo_Impl::SetStringProperty(PP_URLRequestProperty property,
                                                const std::string& value) {
  // TODO(darin): Validate input.  Perhaps at a different layer?
  switch (property) {
    case PP_URLREQUESTPROPERTY_URL:
      url_ = value;  // NOTE: This may be a relative URL.
      return true;
    case PP_URLREQUESTPROPERTY_METHOD:
      method_ = value;
      return true;
    case PP_URLREQUESTPROPERTY_HEADERS:
      headers_ = value;
      return true;
    default:
      return false;
  }
}

bool PPB_URLRequestInfo_Impl::AppendDataToBody(const std::string& data) {
  if (!data.empty())
    body_.push_back(BodyItem(data));
  return true;
}

bool PPB_URLRequestInfo_Impl::AppendFileToBody(
    PPB_FileRef_Impl* file_ref,
    int64_t start_offset,
    int64_t number_of_bytes,
    PP_Time expected_last_modified_time) {
  // Ignore a call to append nothing.
  if (number_of_bytes == 0)
    return true;

  // Check for bad values.  (-1 means read until end of file.)
  if (start_offset < 0 || number_of_bytes < -1)
    return false;

  body_.push_back(BodyItem(file_ref,
                           start_offset,
                           number_of_bytes,
                           expected_last_modified_time));
  return true;
}

WebURLRequest PPB_URLRequestInfo_Impl::ToWebURLRequest(WebFrame* frame) const {
  WebURLRequest web_request;
  web_request.initialize();
  web_request.setURL(frame->document().completeURL(WebString::fromUTF8(url_)));
  web_request.setDownloadToFile(stream_to_file_);

  if (!method_.empty())
    web_request.setHTTPMethod(WebString::fromUTF8(method_));

  if (!headers_.empty()) {
    net::HttpUtil::HeadersIterator it(headers_.begin(), headers_.end(), "\n");
    while (it.GetNext()) {
      if (!IsIgnoredRequestHeader(it.name())) {
        web_request.addHTTPHeaderField(
            WebString::fromUTF8(it.name()),
            WebString::fromUTF8(it.values()));
      }
    }
  }

  if (!body_.empty()) {
    WebHTTPBody http_body;
    http_body.initialize();
    for (size_t i = 0; i < body_.size(); ++i) {
      if (body_[i].file_ref) {
        http_body.appendFileRange(
            webkit_glue::FilePathToWebString(
                body_[i].file_ref->GetSystemPath()),
            body_[i].start_offset,
            body_[i].number_of_bytes,
            body_[i].expected_last_modified_time);
      } else {
        DCHECK(!body_[i].data.empty());
        http_body.appendData(WebData(body_[i].data));
      }
    }
    web_request.setHTTPBody(http_body);
  }

  frame->setReferrerForRequest(web_request, WebURL());  // Use default.
  return web_request;
}

}  // namespace ppapi
}  // namespace webkit

<commit_msg>Restrict HTTP headers by checking in URLRequestInfo::SetProperty. BUG=47354 TEST=none Review URL: http://codereview.chromium.org/5138010<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "webkit/plugins/ppapi/ppb_url_request_info_impl.h"

#include "base/logging.h"
#include "base/string_util.h"
#include "googleurl/src/gurl.h"
#include "net/http/http_util.h"
#include "ppapi/c/pp_var.h"
#include "third_party/WebKit/WebKit/chromium/public/WebData.h"
#include "third_party/WebKit/WebKit/chromium/public/WebDocument.h"
#include "third_party/WebKit/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/WebKit/chromium/public/WebHTTPBody.h"
#include "third_party/WebKit/WebKit/chromium/public/WebURL.h"
#include "third_party/WebKit/WebKit/chromium/public/WebURLRequest.h"
#include "webkit/plugins/ppapi/common.h"
#include "webkit/plugins/ppapi/plugin_module.h"
#include "webkit/plugins/ppapi/ppb_file_ref_impl.h"
#include "webkit/plugins/ppapi/string.h"
#include "webkit/plugins/ppapi/var.h"
#include "webkit/glue/webkit_glue.h"

using WebKit::WebData;
using WebKit::WebHTTPBody;
using WebKit::WebString;
using WebKit::WebFrame;
using WebKit::WebURL;
using WebKit::WebURLRequest;

namespace webkit {
namespace ppapi {

namespace {

// A header string containing any of the following fields will cause
// an error. The list comes from the XMLHttpRequest standard.
// http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader-method
const char* const kForbiddenHeaderFields[] = {
  "accept-charset",
  "accept-encoding",
  "connection",
  "content-length",
  "cookie",
  "cookie2",
  "content-transfer-encoding",
  "date",
  "expect",
  "host",
  "keep-alive",
  "origin",
  "referer",
  "te",
  "trailer",
  "transfer-encoding",
  "upgrade",
  "user-agent",
  "via",
};

bool IsValidHeaderField(const std::string& name) {
  for (size_t i = 0; i < arraysize(kForbiddenHeaderFields); ++i) {
    if (LowerCaseEqualsASCII(name, kForbiddenHeaderFields[i]))
      return false;
  }
  if (StartsWithASCII(name, "proxy-", false))
    return false;
  if (StartsWithASCII(name, "sec-", false))
    return false;

  return true;
}

bool AreValidHeaders(const std::string& headers) {
  net::HttpUtil::HeadersIterator it(headers.begin(), headers.end(), "\n");
  while (it.GetNext()) {
    if (!IsValidHeaderField(it.name()))
      return false;
  }
  return true;
}

PP_Resource Create(PP_Module module_id) {
  PluginModule* module = ResourceTracker::Get()->GetModule(module_id);
  if (!module)
    return 0;

  PPB_URLRequestInfo_Impl* request = new PPB_URLRequestInfo_Impl(module);

  return request->GetReference();
}

PP_Bool IsURLRequestInfo(PP_Resource resource) {
  return BoolToPPBool(!!Resource::GetAs<PPB_URLRequestInfo_Impl>(resource));
}

PP_Bool SetProperty(PP_Resource request_id,
                    PP_URLRequestProperty property,
                    PP_Var var) {
  scoped_refptr<PPB_URLRequestInfo_Impl> request(
      Resource::GetAs<PPB_URLRequestInfo_Impl>(request_id));
  if (!request)
    return PP_FALSE;

  if (var.type == PP_VARTYPE_BOOL) {
    return BoolToPPBool(
        request->SetBooleanProperty(property,
                                    PPBoolToBool(var.value.as_bool)));
  }

  if (var.type == PP_VARTYPE_STRING) {
    scoped_refptr<StringVar> string(StringVar::FromPPVar(var));
    if (string) {
      return BoolToPPBool(request->SetStringProperty(property,
                                                     string->value()));
    }
  }

  return PP_FALSE;
}

PP_Bool AppendDataToBody(PP_Resource request_id,
                         const char* data,
                         uint32_t len) {
  scoped_refptr<PPB_URLRequestInfo_Impl> request(
      Resource::GetAs<PPB_URLRequestInfo_Impl>(request_id));
  if (!request)
    return PP_FALSE;

  return BoolToPPBool(request->AppendDataToBody(std::string(data, len)));
}

PP_Bool AppendFileToBody(PP_Resource request_id,
                      PP_Resource file_ref_id,
                      int64_t start_offset,
                      int64_t number_of_bytes,
                      PP_Time expected_last_modified_time) {
  scoped_refptr<PPB_URLRequestInfo_Impl> request(
      Resource::GetAs<PPB_URLRequestInfo_Impl>(request_id));
  if (!request)
    return PP_FALSE;

  scoped_refptr<PPB_FileRef_Impl> file_ref(
      Resource::GetAs<PPB_FileRef_Impl>(file_ref_id));
  if (!file_ref)
    return PP_FALSE;

  return BoolToPPBool(request->AppendFileToBody(file_ref,
                                                start_offset,
                                                number_of_bytes,
                                                expected_last_modified_time));
}

const PPB_URLRequestInfo ppb_urlrequestinfo = {
  &Create,
  &IsURLRequestInfo,
  &SetProperty,
  &AppendDataToBody,
  &AppendFileToBody
};

}  // namespace

struct PPB_URLRequestInfo_Impl::BodyItem {
  BodyItem(const std::string& data)
      : data(data),
        start_offset(0),
        number_of_bytes(-1),
        expected_last_modified_time(0.0) {
  }

  BodyItem(PPB_FileRef_Impl* file_ref,
           int64_t start_offset,
           int64_t number_of_bytes,
           PP_Time expected_last_modified_time)
      : file_ref(file_ref),
        start_offset(start_offset),
        number_of_bytes(number_of_bytes),
        expected_last_modified_time(expected_last_modified_time) {
  }

  std::string data;
  scoped_refptr<PPB_FileRef_Impl> file_ref;
  int64_t start_offset;
  int64_t number_of_bytes;
  PP_Time expected_last_modified_time;
};

PPB_URLRequestInfo_Impl::PPB_URLRequestInfo_Impl(PluginModule* module)
    : Resource(module),
      stream_to_file_(false),
      follow_redirects_(true),
      record_download_progress_(false),
      record_upload_progress_(false) {
}

PPB_URLRequestInfo_Impl::~PPB_URLRequestInfo_Impl() {
}

// static
const PPB_URLRequestInfo* PPB_URLRequestInfo_Impl::GetInterface() {
  return &ppb_urlrequestinfo;
}

PPB_URLRequestInfo_Impl* PPB_URLRequestInfo_Impl::AsPPB_URLRequestInfo_Impl() {
  return this;
}

bool PPB_URLRequestInfo_Impl::SetBooleanProperty(PP_URLRequestProperty property,
                                                 bool value) {
  switch (property) {
    case PP_URLREQUESTPROPERTY_STREAMTOFILE:
      stream_to_file_ = value;
      return true;
    case PP_URLREQUESTPROPERTY_FOLLOWREDIRECTS:
      follow_redirects_ = value;
      return true;
    case PP_URLREQUESTPROPERTY_RECORDDOWNLOADPROGRESS:
      record_download_progress_ = value;
      return true;
    case PP_URLREQUESTPROPERTY_RECORDUPLOADPROGRESS:
      record_upload_progress_ = value;
      return true;
    default:
      return false;
  }
}

bool PPB_URLRequestInfo_Impl::SetStringProperty(PP_URLRequestProperty property,
                                                const std::string& value) {
  // TODO(darin): Validate input.  Perhaps at a different layer?
  switch (property) {
    case PP_URLREQUESTPROPERTY_URL:
      url_ = value;  // NOTE: This may be a relative URL.
      return true;
    case PP_URLREQUESTPROPERTY_METHOD:
      method_ = value;
      return true;
    case PP_URLREQUESTPROPERTY_HEADERS:
      if (!AreValidHeaders(value))
        return false;
      headers_ = value;
      return true;
    default:
      return false;
  }
}

bool PPB_URLRequestInfo_Impl::AppendDataToBody(const std::string& data) {
  if (!data.empty())
    body_.push_back(BodyItem(data));
  return true;
}

bool PPB_URLRequestInfo_Impl::AppendFileToBody(
    PPB_FileRef_Impl* file_ref,
    int64_t start_offset,
    int64_t number_of_bytes,
    PP_Time expected_last_modified_time) {
  // Ignore a call to append nothing.
  if (number_of_bytes == 0)
    return true;

  // Check for bad values.  (-1 means read until end of file.)
  if (start_offset < 0 || number_of_bytes < -1)
    return false;

  body_.push_back(BodyItem(file_ref,
                           start_offset,
                           number_of_bytes,
                           expected_last_modified_time));
  return true;
}

WebURLRequest PPB_URLRequestInfo_Impl::ToWebURLRequest(WebFrame* frame) const {
  WebURLRequest web_request;
  web_request.initialize();
  web_request.setURL(frame->document().completeURL(WebString::fromUTF8(url_)));
  web_request.setDownloadToFile(stream_to_file_);

  if (!method_.empty())
    web_request.setHTTPMethod(WebString::fromUTF8(method_));

  if (!headers_.empty()) {
    net::HttpUtil::HeadersIterator it(headers_.begin(), headers_.end(), "\n");
    while (it.GetNext()) {
      web_request.addHTTPHeaderField(
          WebString::fromUTF8(it.name()),
          WebString::fromUTF8(it.values()));
    }
  }

  if (!body_.empty()) {
    WebHTTPBody http_body;
    http_body.initialize();
    for (size_t i = 0; i < body_.size(); ++i) {
      if (body_[i].file_ref) {
        http_body.appendFileRange(
            webkit_glue::FilePathToWebString(
                body_[i].file_ref->GetSystemPath()),
            body_[i].start_offset,
            body_[i].number_of_bytes,
            body_[i].expected_last_modified_time);
      } else {
        DCHECK(!body_[i].data.empty());
        http_body.appendData(WebData(body_[i].data));
      }
    }
    web_request.setHTTPBody(http_body);
  }

  frame->setReferrerForRequest(web_request, WebURL());  // Use default.
  return web_request;
}

}  // namespace ppapi
}  // namespace webkit

<|endoftext|>