<commit_before>// RUN: %check_clang_tidy %s cppcoreguidelines-avoid-goto %t

void noop() {}

int main() {
  noop();
  goto jump_to_me;
  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: avoid using 'goto' for flow control
  // CHECK-MESSAGES: [[@LINE+3]]:1: note: label defined here
  noop();

jump_to_me:;

jump_backwards:;
  noop();
  goto jump_backwards;
  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: avoid using 'goto' for flow control
  // CHECK-MESSAGES: [[@LINE-4]]:1: note: label defined here

  goto jump_in_line;
  ;
jump_in_line:;
  // CHECK-MESSAGES: [[@LINE-3]]:3: warning: avoid using 'goto' for flow control
  // CHECK-MESSAGES: [[@LINE-2]]:1: note: label defined here

  // Test the GNU extension https://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html
some_label:;
  void *dynamic_label = &&some_label;

  // FIXME: `IndirectGotoStmt` is not detected.
  goto *dynamic_label;
}

void forward_jump_out_nested_loop() {
  int array[] = {1, 2, 3, 4, 5};
  for (int i = 0; i < 10; ++i) {
    noop();
    for (int j = 0; j < 10; ++j) {
      noop();
      if (i + j > 10)
        goto early_exit1;
    }
    noop();
  }

  for (int i = 0; i < 10; ++i) {
    noop();
    while (true) {
      noop();
      if (i > 5)
        goto early_exit1;
    }
    noop();
  }

  for (auto value : array) {
    noop();
    for (auto number : array) {
      noop();
      if (number == 5)
        goto early_exit1;
    }
  }

  do {
    noop();
    do {
      noop();
      goto early_exit1;
    } while (true);
  } while (true);

  do {
    for (auto number : array) {
      noop();
      if (number == 2)
        goto early_exit1;
    }
  } while (true);

  // Jumping further results in error, because the variable declaration would
  // be skipped.
early_exit1:;

  int i = 0;
  while (true) {
    noop();
    while (true) {
      noop();
      if (i > 5)
        goto early_exit2;
      i++;
    }
    noop();
  }

  while (true) {
    noop();
    for (int j = 0; j < 10; ++j) {
      noop();
      if (j > 5)
        goto early_exit2;
    }
    noop();
  }

  while (true) {
    noop();
    for (auto number : array) {
      if (number == 1)
        goto early_exit2;
      noop();
    }
  }

  while (true) {
    noop();
    do {
      noop();
      goto early_exit2;
    } while (true);
  }
early_exit2:;
}

void jump_out_backwards() {

before_the_loop:
  noop();

  for (int i = 0; i < 10; ++i) {
    for (int j = 0; j < 10; ++j) {
      if (i * j > 80)
        goto before_the_loop;
      // CHECK-MESSAGES: [[@LINE-1]]:9: warning: avoid using 'goto' for flow control
      // CHECK-MESSAGES: [[@LINE-8]]:1: note: label defined here
    }
  }
}
<commit_msg>[clang-tidy] NFC use CHECK-NOTES in test for cppgoreguidelines-avoid-goto<commit_after>// RUN: %check_clang_tidy %s cppcoreguidelines-avoid-goto %t

void noop() {}

int main() {
  noop();
  goto jump_to_me;
  // CHECK-NOTES: [[@LINE-1]]:3: warning: avoid using 'goto' for flow control
  // CHECK-NOTES: [[@LINE+3]]:1: note: label defined here
  noop();

jump_to_me:;

jump_backwards:;
  noop();
  goto jump_backwards;
  // CHECK-NOTES: [[@LINE-1]]:3: warning: avoid using 'goto' for flow control
  // CHECK-NOTES: [[@LINE-4]]:1: note: label defined here

  goto jump_in_line;
  ;
jump_in_line:;
  // CHECK-NOTES: [[@LINE-3]]:3: warning: avoid using 'goto' for flow control
  // CHECK-NOTES: [[@LINE-2]]:1: note: label defined here

  // Test the GNU extension https://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html
some_label:;
  void *dynamic_label = &&some_label;

  // FIXME: `IndirectGotoStmt` is not detected.
  goto *dynamic_label;
}

void forward_jump_out_nested_loop() {
  int array[] = {1, 2, 3, 4, 5};
  for (int i = 0; i < 10; ++i) {
    noop();
    for (int j = 0; j < 10; ++j) {
      noop();
      if (i + j > 10)
        goto early_exit1;
    }
    noop();
  }

  for (int i = 0; i < 10; ++i) {
    noop();
    while (true) {
      noop();
      if (i > 5)
        goto early_exit1;
    }
    noop();
  }

  for (auto value : array) {
    noop();
    for (auto number : array) {
      noop();
      if (number == 5)
        goto early_exit1;
    }
  }

  do {
    noop();
    do {
      noop();
      goto early_exit1;
    } while (true);
  } while (true);

  do {
    for (auto number : array) {
      noop();
      if (number == 2)
        goto early_exit1;
    }
  } while (true);

  // Jumping further results in error, because the variable declaration would
  // be skipped.
early_exit1:;

  int i = 0;
  while (true) {
    noop();
    while (true) {
      noop();
      if (i > 5)
        goto early_exit2;
      i++;
    }
    noop();
  }

  while (true) {
    noop();
    for (int j = 0; j < 10; ++j) {
      noop();
      if (j > 5)
        goto early_exit2;
    }
    noop();
  }

  while (true) {
    noop();
    for (auto number : array) {
      if (number == 1)
        goto early_exit2;
      noop();
    }
  }

  while (true) {
    noop();
    do {
      noop();
      goto early_exit2;
    } while (true);
  }
early_exit2:;
}

void jump_out_backwards() {

before_the_loop:
  noop();

  for (int i = 0; i < 10; ++i) {
    for (int j = 0; j < 10; ++j) {
      if (i * j > 80)
        goto before_the_loop;
      // CHECK-NOTES: [[@LINE-1]]:9: warning: avoid using 'goto' for flow control
      // CHECK-NOTES: [[@LINE-8]]:1: note: label defined here
    }
  }
}
<|endoftext|>


<commit_before>/****************************************************************************
 *
 *   Copyright (c) 2018-2019 PX4 Development Team. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name PX4 nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

#include "VelocitySmoothing.hpp"

#include <cstdio>
#include <float.h>
#include <mathlib/mathlib.h>

VelocitySmoothing::VelocitySmoothing(float initial_accel, float initial_vel, float initial_pos)
{
	reset(initial_accel, initial_vel, initial_pos);
}

void VelocitySmoothing::reset(float accel, float vel, float pos)
{
	_state.j = 0.f;
	_state.a = accel;
	_state.v = vel;
	_state.x = pos;

	_state_init = _state;
}

float VelocitySmoothing::saturateT1ForAccel(float a0, float j_max, float T1, float a_max)
{
	/* Check maximum acceleration, saturate and recompute T1 if needed */
	float accel_T1 = a0 + j_max * T1;
	float T1_new = T1;

	if (accel_T1 > a_max) {
		T1_new = (a_max - a0) / j_max;

	} else if (accel_T1 < -a_max) {
		T1_new = (-a_max - a0) / j_max;
	}

	return T1_new;
}

float VelocitySmoothing::computeT1(float a0, float v3, float j_max, float a_max)
{
	float delta = 2.f * a0 * a0 + 4.f * j_max * v3;

	if (delta < 0.f) {
		// Solution is not real
		return 0.f;
	}

	float sqrt_delta = sqrtf(delta);
	float T1_plus = (-a0 + 0.5f * sqrt_delta) / j_max;
	float T1_minus = (-a0 - 0.5f * sqrt_delta) / j_max;

	float T3_plus = a0 / j_max + T1_plus;
	float T3_minus = a0 / j_max + T1_minus;

	float T1 = 0.f;

	if (T1_plus >= 0.f && T3_plus >= 0.f) {
		T1 = T1_plus;

	} else if (T1_minus >= 0.f && T3_minus >= 0.f) {
		T1 = T1_minus;
	}

	T1 = saturateT1ForAccel(a0, j_max, T1, a_max);

	return math::max(T1, 0.f);
}

float VelocitySmoothing::computeT1(float T123, float a0, float v3, float j_max, float a_max)
{
	float a = -j_max;
	float b = j_max * T123 - a0;
	float delta = T123 * T123 * j_max * j_max + 2.f * T123 * a0 * j_max - a0 * a0 - 4.f * j_max * v3;

	if (delta < 0.f) {
		// Solution is not real
		return 0.f;
	}

	float sqrt_delta = sqrtf(delta);
	float denominator_inv = 1.f / (2.f * a);
	float T1_plus = math::max((-b + sqrt_delta) * denominator_inv, 0.f);
	float T1_minus = math::max((-b - sqrt_delta) * denominator_inv, 0.f);

	float T3_plus = a0 / j_max + T1_plus;
	float T3_minus = a0 / j_max + T1_minus;

	float T13_plus = T1_plus + T3_plus;
	float T13_minus = T1_minus + T3_minus;

	float T1 = 0.f;

	if (T13_plus > T123) {
		T1 = T1_minus;

	} else if (T13_minus > T123) {
		T1 = T1_plus;
	}

	T1 = saturateT1ForAccel(a0, j_max, T1, a_max);

	return T1;
}

float VelocitySmoothing::computeT2(float T1, float T3, float a0, float v3, float j_max)
{
	float T2 = 0.f;

	float den = a0 + j_max * T1;

	if (math::abs_t(den) > FLT_EPSILON) {
		T2 = (-0.5f * T1 * T1 * j_max - T1 * T3 * j_max - T1 * a0 + 0.5f * T3 * T3 * j_max - T3 * a0 + v3) / den;
	}

	return math::max(T2, 0.f);
}

float VelocitySmoothing::computeT2(float T123, float T1, float T3)
{
	float T2 = T123 - T1 - T3;
	return math::max(T2, 0.f);
}

float VelocitySmoothing::computeT3(float T1, float a0, float j_max)
{
	float T3 = a0 / j_max + T1;
	return math::max(T3, 0.f);
}

void VelocitySmoothing::updateDurations(float vel_setpoint)
{
	_vel_sp = math::constrain(vel_setpoint, -_max_vel, _max_vel);
	_local_time = 0.f;
	_state_init = _state;

	_direction = computeDirection();

	if (_direction != 0) {
		updateDurationsMinimizeTotalTime();

	} else {
		_T1 = _T2 = _T3 = 0.f;
	}
}

int VelocitySmoothing::computeDirection()
{
	// Compute the velocity at which the trajectory will be
	// when the acceleration will be zero
	float vel_zero_acc = computeVelAtZeroAcc();

	/* Depending of the direction, start accelerating positively or negatively */
	int direction = math::sign(_vel_sp - vel_zero_acc);

	if (direction == 0) {
		// If by braking immediately the velocity is exactly
		// the require one with zero acceleration, then brake
		direction = math::sign(_state.a);
	}

	return direction;
}

float VelocitySmoothing::computeVelAtZeroAcc()
{
	float vel_zero_acc = _state.v;

	if (fabsf(_state.a) > FLT_EPSILON) {
		float j_zero_acc = -math::sign(_state.a) * _max_jerk; // Required jerk to reduce the acceleration
		float t_zero_acc = -_state.a / j_zero_acc; // Required time to cancel the current acceleration
		vel_zero_acc = _state.v + _state.a * t_zero_acc + 0.5f * j_zero_acc * t_zero_acc * t_zero_acc;
	}

	return vel_zero_acc;
}

void VelocitySmoothing::updateDurationsMinimizeTotalTime()
{
	float jerk_max_T1 = _direction * _max_jerk;
	float delta_v = _vel_sp - _state.v;

	// compute increasing acceleration time
	_T1 = computeT1(_state.a, delta_v, jerk_max_T1, _max_accel);

	// compute decreasing acceleration time
	_T3 = computeT3(_T1, _state.a, jerk_max_T1);

	// compute constant acceleration time
	_T2 = computeT2(_T1, _T3, _state.a, delta_v, jerk_max_T1);
}

Trajectory VelocitySmoothing::evaluatePoly(float j, float a0, float v0, float x0, float t, int d)
{
	Trajectory traj;
	float jt = d * j;
	float t2 = t * t;
	float t3 = t2 * t;

	traj.j = jt;
	traj.a = a0 + jt * t;
	traj.v = v0 + a0 * t + 0.5f * jt * t2;
	traj.x = x0 + v0 * t + 0.5f * a0 * t2 + 1.f / 6.f * jt * t3;

	return traj;
}

void VelocitySmoothing::updateTraj(float dt, float time_stretch)
{
	_local_time += dt * time_stretch;
	float t_remain = _local_time;
	float t[3];

	t[0] = math::min(t_remain, _T1);
	_state = evaluatePoly(_max_jerk, _state_init.a, _state_init.v, _state_init.x, t[0], _direction);
	t_remain -= t[0];

	if (t_remain > 0.f) {
		t[1] = math::min(t_remain, _T2);
		_state = evaluatePoly(0.f, _state.a, _state.v, _state.x, t[1], 0.f);
		t_remain -= t[1];
	}

	if (t_remain > 0.f) {
		t[2] = math::min(t_remain, _T3);
		_state = evaluatePoly(_max_jerk, _state.a, _state.v, _state.x, t[2], -_direction);
		t_remain -= t[2];
	}

	if (t_remain > 0.f) {
		_state = evaluatePoly(0.f, 0.f, _state.v, _state.x, t_remain, 0.f);
	}
}

void VelocitySmoothing::timeSynchronization(VelocitySmoothing *traj, int n_traj)
{
	float desired_time = 0.f;
	int longest_traj_index = 0;

	for (int i = 0; i < n_traj; i++) {
		const float T123 = traj[i].getTotalTime();

		if (T123 > desired_time) {
			desired_time = T123;
			longest_traj_index = i;
		}
	}

	if (desired_time > FLT_EPSILON) {
		for (int i = 0; i < n_traj; i++) {
			if (i != longest_traj_index) {
				traj[i].updateDurationsGivenTotalTime(desired_time);
			}
		}
	}
}

void VelocitySmoothing::updateDurationsGivenTotalTime(float T123)
{
	float jerk_max_T1 = _direction * _max_jerk;
	float delta_v = _vel_sp - _state.v;

	// compute increasing acceleration time
	_T1 = computeT1(T123, _state.a, delta_v, jerk_max_T1, _max_accel);

	// compute decreasing acceleration time
	_T3 = computeT3(_T1, _state.a, jerk_max_T1);

	// compute constant acceleration time
	_T2 = computeT2(T123, _T1, _T3);
}
<commit_msg>VelocitySmoothing: refactor local scope t variables instead of array<commit_after>/****************************************************************************
 *
 *   Copyright (c) 2018-2019 PX4 Development Team. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name PX4 nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

#include "VelocitySmoothing.hpp"

#include <cstdio>
#include <float.h>
#include <mathlib/mathlib.h>

VelocitySmoothing::VelocitySmoothing(float initial_accel, float initial_vel, float initial_pos)
{
	reset(initial_accel, initial_vel, initial_pos);
}

void VelocitySmoothing::reset(float accel, float vel, float pos)
{
	_state.j = 0.f;
	_state.a = accel;
	_state.v = vel;
	_state.x = pos;

	_state_init = _state;
}

float VelocitySmoothing::saturateT1ForAccel(float a0, float j_max, float T1, float a_max)
{
	/* Check maximum acceleration, saturate and recompute T1 if needed */
	float accel_T1 = a0 + j_max * T1;
	float T1_new = T1;

	if (accel_T1 > a_max) {
		T1_new = (a_max - a0) / j_max;

	} else if (accel_T1 < -a_max) {
		T1_new = (-a_max - a0) / j_max;
	}

	return T1_new;
}

float VelocitySmoothing::computeT1(float a0, float v3, float j_max, float a_max)
{
	float delta = 2.f * a0 * a0 + 4.f * j_max * v3;

	if (delta < 0.f) {
		// Solution is not real
		return 0.f;
	}

	float sqrt_delta = sqrtf(delta);
	float T1_plus = (-a0 + 0.5f * sqrt_delta) / j_max;
	float T1_minus = (-a0 - 0.5f * sqrt_delta) / j_max;

	float T3_plus = a0 / j_max + T1_plus;
	float T3_minus = a0 / j_max + T1_minus;

	float T1 = 0.f;

	if (T1_plus >= 0.f && T3_plus >= 0.f) {
		T1 = T1_plus;

	} else if (T1_minus >= 0.f && T3_minus >= 0.f) {
		T1 = T1_minus;
	}

	T1 = saturateT1ForAccel(a0, j_max, T1, a_max);

	return math::max(T1, 0.f);
}

float VelocitySmoothing::computeT1(float T123, float a0, float v3, float j_max, float a_max)
{
	float a = -j_max;
	float b = j_max * T123 - a0;
	float delta = T123 * T123 * j_max * j_max + 2.f * T123 * a0 * j_max - a0 * a0 - 4.f * j_max * v3;

	if (delta < 0.f) {
		// Solution is not real
		return 0.f;
	}

	float sqrt_delta = sqrtf(delta);
	float denominator_inv = 1.f / (2.f * a);
	float T1_plus = math::max((-b + sqrt_delta) * denominator_inv, 0.f);
	float T1_minus = math::max((-b - sqrt_delta) * denominator_inv, 0.f);

	float T3_plus = a0 / j_max + T1_plus;
	float T3_minus = a0 / j_max + T1_minus;

	float T13_plus = T1_plus + T3_plus;
	float T13_minus = T1_minus + T3_minus;

	float T1 = 0.f;

	if (T13_plus > T123) {
		T1 = T1_minus;

	} else if (T13_minus > T123) {
		T1 = T1_plus;
	}

	T1 = saturateT1ForAccel(a0, j_max, T1, a_max);

	return T1;
}

float VelocitySmoothing::computeT2(float T1, float T3, float a0, float v3, float j_max)
{
	float T2 = 0.f;

	float den = a0 + j_max * T1;

	if (math::abs_t(den) > FLT_EPSILON) {
		T2 = (-0.5f * T1 * T1 * j_max - T1 * T3 * j_max - T1 * a0 + 0.5f * T3 * T3 * j_max - T3 * a0 + v3) / den;
	}

	return math::max(T2, 0.f);
}

float VelocitySmoothing::computeT2(float T123, float T1, float T3)
{
	float T2 = T123 - T1 - T3;
	return math::max(T2, 0.f);
}

float VelocitySmoothing::computeT3(float T1, float a0, float j_max)
{
	float T3 = a0 / j_max + T1;
	return math::max(T3, 0.f);
}

void VelocitySmoothing::updateDurations(float vel_setpoint)
{
	_vel_sp = math::constrain(vel_setpoint, -_max_vel, _max_vel);
	_local_time = 0.f;
	_state_init = _state;

	_direction = computeDirection();

	if (_direction != 0) {
		updateDurationsMinimizeTotalTime();

	} else {
		_T1 = _T2 = _T3 = 0.f;
	}
}

int VelocitySmoothing::computeDirection()
{
	// Compute the velocity at which the trajectory will be
	// when the acceleration will be zero
	float vel_zero_acc = computeVelAtZeroAcc();

	/* Depending of the direction, start accelerating positively or negatively */
	int direction = math::sign(_vel_sp - vel_zero_acc);

	if (direction == 0) {
		// If by braking immediately the velocity is exactly
		// the require one with zero acceleration, then brake
		direction = math::sign(_state.a);
	}

	return direction;
}

float VelocitySmoothing::computeVelAtZeroAcc()
{
	float vel_zero_acc = _state.v;

	if (fabsf(_state.a) > FLT_EPSILON) {
		float j_zero_acc = -math::sign(_state.a) * _max_jerk; // Required jerk to reduce the acceleration
		float t_zero_acc = -_state.a / j_zero_acc; // Required time to cancel the current acceleration
		vel_zero_acc = _state.v + _state.a * t_zero_acc + 0.5f * j_zero_acc * t_zero_acc * t_zero_acc;
	}

	return vel_zero_acc;
}

void VelocitySmoothing::updateDurationsMinimizeTotalTime()
{
	float jerk_max_T1 = _direction * _max_jerk;
	float delta_v = _vel_sp - _state.v;

	// compute increasing acceleration time
	_T1 = computeT1(_state.a, delta_v, jerk_max_T1, _max_accel);

	// compute decreasing acceleration time
	_T3 = computeT3(_T1, _state.a, jerk_max_T1);

	// compute constant acceleration time
	_T2 = computeT2(_T1, _T3, _state.a, delta_v, jerk_max_T1);
}

Trajectory VelocitySmoothing::evaluatePoly(float j, float a0, float v0, float x0, float t, int d)
{
	Trajectory traj;
	float jt = d * j;
	float t2 = t * t;
	float t3 = t2 * t;

	traj.j = jt;
	traj.a = a0 + jt * t;
	traj.v = v0 + a0 * t + 0.5f * jt * t2;
	traj.x = x0 + v0 * t + 0.5f * a0 * t2 + 1.f / 6.f * jt * t3;

	return traj;
}

void VelocitySmoothing::updateTraj(float dt, float time_stretch)
{
	_local_time += dt * time_stretch;
	float t_remain = _local_time;

	float t1 = math::min(t_remain, _T1);
	_state = evaluatePoly(_max_jerk, _state_init.a, _state_init.v, _state_init.x, t1, _direction);
	t_remain -= t1;

	if (t_remain > 0.f) {
		float t2 = math::min(t_remain, _T2);
		_state = evaluatePoly(0.f, _state.a, _state.v, _state.x, t2, 0.f);
		t_remain -= t2;
	}

	if (t_remain > 0.f) {
		float t3 = math::min(t_remain, _T3);
		_state = evaluatePoly(_max_jerk, _state.a, _state.v, _state.x, t3, -_direction);
		t_remain -= t3;
	}

	if (t_remain > 0.f) {
		_state = evaluatePoly(0.f, 0.f, _state.v, _state.x, t_remain, 0.f);
	}
}

void VelocitySmoothing::timeSynchronization(VelocitySmoothing *traj, int n_traj)
{
	float desired_time = 0.f;
	int longest_traj_index = 0;

	for (int i = 0; i < n_traj; i++) {
		const float T123 = traj[i].getTotalTime();

		if (T123 > desired_time) {
			desired_time = T123;
			longest_traj_index = i;
		}
	}

	if (desired_time > FLT_EPSILON) {
		for (int i = 0; i < n_traj; i++) {
			if (i != longest_traj_index) {
				traj[i].updateDurationsGivenTotalTime(desired_time);
			}
		}
	}
}

void VelocitySmoothing::updateDurationsGivenTotalTime(float T123)
{
	float jerk_max_T1 = _direction * _max_jerk;
	float delta_v = _vel_sp - _state.v;

	// compute increasing acceleration time
	_T1 = computeT1(T123, _state.a, delta_v, jerk_max_T1, _max_accel);

	// compute decreasing acceleration time
	_T3 = computeT3(_T1, _state.a, jerk_max_T1);

	// compute constant acceleration time
	_T2 = computeT2(T123, _T1, _T3);
}
<|endoftext|>


<commit_before>// __BEGIN_LICENSE__
// Copyright (C) 2006-2009 United States Government as represented by
// the Administrator of the National Aeronautics and Space Administration.
// All Rights Reserved.
// __END_LICENSE__

#include <vw/Mosaic/GigapanQuadTreeConfig.h>

#include <boost/bind.hpp>

#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/filesystem/convenience.hpp>
namespace fs = boost::filesystem;

namespace vw {
namespace mosaic {

  struct GigapanQuadTreeConfigData {
    BBox2 m_longlat_bbox;

    std::vector<std::pair<std::string,vw::BBox2i> > branch_func( QuadTreeGenerator const&, std::string const& name, BBox2i const& region ) const;
    void metadata_func( QuadTreeGenerator const&, QuadTreeGenerator::TileInfo const& info ) const;

    public:
      GigapanQuadTreeConfigData() : m_longlat_bbox(0, 0, 0, 0) {}
  };

  GigapanQuadTreeConfig::GigapanQuadTreeConfig()
    : m_data( new GigapanQuadTreeConfigData() )
  {}

  std::string GigapanQuadTreeConfig::image_path( QuadTreeGenerator const& qtree, std::string const& name ) {
    return QuadTreeGenerator::tiered_image_path()(qtree, name);
  }

  void GigapanQuadTreeConfig::configure( QuadTreeGenerator& qtree ) const {
    qtree.set_image_path_func( &image_path );
    qtree.set_cull_images( true );
    qtree.set_metadata_func( boost::bind(&GigapanQuadTreeConfigData::metadata_func,m_data,_1,_2) );

    if (m_data->m_longlat_bbox.width() != 0 || m_data->m_longlat_bbox.height() != 0) {
      qtree.set_branch_func( boost::bind(&GigapanQuadTreeConfigData::branch_func,m_data,_1,_2,_3) );
    }
  }

  void GigapanQuadTreeConfig::set_longlat_bbox( BBox2 const& bbox ) {
    m_data->m_longlat_bbox = bbox;
  }

  std::vector<std::pair<std::string,vw::BBox2i> > GigapanQuadTreeConfigData::branch_func( QuadTreeGenerator const& qtree, std::string const& name, BBox2i const& region ) const {
    std::vector<std::pair<std::string,vw::BBox2i> > children;
    if( region.height() > qtree.get_tile_size() ) {

      Vector2i dims = qtree.get_dimensions();
      double aspect_ratio = 2 * (region.width()/region.height()) * ( (m_longlat_bbox.width()/dims.x()) / (m_longlat_bbox.height()/dims.y()) );

      double bottom_lat = m_longlat_bbox.max().y() - region.max().y()*m_longlat_bbox.height() / dims.y();
      double top_lat = m_longlat_bbox.max().y() - region.min().y()*m_longlat_bbox.height() / dims.y();
      bool top_merge = ( bottom_lat > 0 ) && ( ( 1.0 / cos(M_PI/180 * bottom_lat) ) > aspect_ratio );
      bool bottom_merge = ( top_lat < 0 ) && ( ( 1.0 / cos(M_PI/180 * top_lat) ) > aspect_ratio );

      if( top_merge ) {
        children.push_back( std::make_pair( name + "4", BBox2i( region.min(), region.max() - Vector2i(0,region.height()/2) ) ) );
      }
      else {
        children.push_back( std::make_pair( name + "0", BBox2i( (region + region.min()) / 2 ) ) );
        children.push_back( std::make_pair( name + "1", BBox2i( (region + Vector2i(region.max().x(),region.min().y())) / 2 ) ) );
      }
      if( bottom_merge ) {
        children.push_back( std::make_pair( name + "5", BBox2i( region.min() + Vector2i(0,region.height()/2), region.max() ) ) );
      }
      else {
        children.push_back( std::make_pair( name + "2", BBox2i( (region + Vector2i(region.min().x(),region.max().y())) / 2 ) ) );
        children.push_back( std::make_pair( name + "3", BBox2i( (region + region.max()) / 2 ) ) );
      }
    }
    return children;
  }

  void GigapanQuadTreeConfigData::metadata_func( QuadTreeGenerator const& qtree, QuadTreeGenerator::TileInfo const& info ) const {
    bool root_node = ( info.name.size() == 0 );

    if ( root_node) {
      std::ostringstream json;
      fs::path file_path( info.filepath, fs::native );
      int base_len = file_path.branch_path().native_file_string().size() + 1;
      fs::path json_path = change_extension( file_path, ".json" );

      // TODO: Make this an actual json file
      json << "<begin>" << std::endl;
      json << "Num levels: " << qtree.get_tree_levels() << std::endl;
      json << "Dimensions: " << qtree.get_dimensions() << std::endl;
      json << "<end>" << std::endl;
      fs::ofstream jsonfs(json_path);
      jsonfs << json.str();
    }
  }
} // namespace mosaic
} // namespace vw
<commit_msg>now writing real json for gigapan output<commit_after>// __BEGIN_LICENSE__
// Copyright (C) 2006-2009 United States Government as represented by
// the Administrator of the National Aeronautics and Space Administration.
// All Rights Reserved.
// __END_LICENSE__

#include <vw/Mosaic/GigapanQuadTreeConfig.h>

#include <boost/bind.hpp>

#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/filesystem/convenience.hpp>
namespace fs = boost::filesystem;

namespace vw {
namespace mosaic {

  struct GigapanQuadTreeConfigData {
    BBox2 m_longlat_bbox;

    std::vector<std::pair<std::string,vw::BBox2i> > branch_func( QuadTreeGenerator const&, std::string const& name, BBox2i const& region ) const;
    void metadata_func( QuadTreeGenerator const&, QuadTreeGenerator::TileInfo const& info ) const;

    public:
      GigapanQuadTreeConfigData() : m_longlat_bbox(0, 0, 0, 0) {}
  };

  GigapanQuadTreeConfig::GigapanQuadTreeConfig()
    : m_data( new GigapanQuadTreeConfigData() )
  {}

  std::string GigapanQuadTreeConfig::image_path( QuadTreeGenerator const& qtree, std::string const& name ) {
    return QuadTreeGenerator::tiered_image_path()(qtree, name);
  }

  void GigapanQuadTreeConfig::configure( QuadTreeGenerator& qtree ) const {
    qtree.set_image_path_func( &image_path );
    qtree.set_cull_images( true );
    qtree.set_metadata_func( boost::bind(&GigapanQuadTreeConfigData::metadata_func,m_data,_1,_2) );

    if (m_data->m_longlat_bbox.width() != 0 || m_data->m_longlat_bbox.height() != 0) {
      qtree.set_branch_func( boost::bind(&GigapanQuadTreeConfigData::branch_func,m_data,_1,_2,_3) );
    }
  }

  void GigapanQuadTreeConfig::set_longlat_bbox( BBox2 const& bbox ) {
    m_data->m_longlat_bbox = bbox;
  }

  std::vector<std::pair<std::string,vw::BBox2i> > GigapanQuadTreeConfigData::branch_func( QuadTreeGenerator const& qtree, std::string const& name, BBox2i const& region ) const {
    std::vector<std::pair<std::string,vw::BBox2i> > children;
    if( region.height() > qtree.get_tile_size() ) {

      Vector2i dims = qtree.get_dimensions();
      double aspect_ratio = 2 * (region.width()/region.height()) * ( (m_longlat_bbox.width()/dims.x()) / (m_longlat_bbox.height()/dims.y()) );

      double bottom_lat = m_longlat_bbox.max().y() - region.max().y()*m_longlat_bbox.height() / dims.y();
      double top_lat = m_longlat_bbox.max().y() - region.min().y()*m_longlat_bbox.height() / dims.y();
      bool top_merge = ( bottom_lat > 0 ) && ( ( 1.0 / cos(M_PI/180 * bottom_lat) ) > aspect_ratio );
      bool bottom_merge = ( top_lat < 0 ) && ( ( 1.0 / cos(M_PI/180 * top_lat) ) > aspect_ratio );

      if( top_merge ) {
        children.push_back( std::make_pair( name + "4", BBox2i( region.min(), region.max() - Vector2i(0,region.height()/2) ) ) );
      }
      else {
        children.push_back( std::make_pair( name + "0", BBox2i( (region + region.min()) / 2 ) ) );
        children.push_back( std::make_pair( name + "1", BBox2i( (region + Vector2i(region.max().x(),region.min().y())) / 2 ) ) );
      }
      if( bottom_merge ) {
        children.push_back( std::make_pair( name + "5", BBox2i( region.min() + Vector2i(0,region.height()/2), region.max() ) ) );
      }
      else {
        children.push_back( std::make_pair( name + "2", BBox2i( (region + Vector2i(region.min().x(),region.max().y())) / 2 ) ) );
        children.push_back( std::make_pair( name + "3", BBox2i( (region + region.max()) / 2 ) ) );
      }
    }
    return children;
  }

  void GigapanQuadTreeConfigData::metadata_func( QuadTreeGenerator const& qtree, QuadTreeGenerator::TileInfo const& info ) const {
    bool root_node = ( info.name.size() == 0 );

    if ( root_node) {
      std::ostringstream json;
      fs::path file_path( info.filepath, fs::native );
      int base_len = file_path.branch_path().native_file_string().size() + 1;
      fs::path json_path = change_extension( file_path, ".json" );

      json << "{" << std::endl
           << "  width: " << qtree.get_dimensions()[0] << std::endl
           << "  height: " << qtree.get_dimensions()[1] << std::endl
           << "  nlevels: " << qtree.get_tree_levels() << std::endl
           << "}" << std::endl;

      fs::ofstream jsonfs(json_path);
      jsonfs << json.str();
    }
  }
} // namespace mosaic
} // namespace vw
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the  "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#if !defined(VCPPDEFINITIONS_HEADER_GUARD_1357924680)
#define VCPPDEFINITIONS_HEADER_GUARD_1357924680

#pragma warning(disable: 4127 4251 4351 4511 4512 4514 4702 4710 4711 4786 4097 4503 4786; error: 4150 4172 4238 4239 4715)

// ---------------------------------------------------------------------------
//  A define in the build for each project is also used to control whether
//  the export keyword is from the project's viewpoint or the client's.
//  These defines provide the platform specific keywords that they need
//  to do this.
// ---------------------------------------------------------------------------
#define XALAN_PLATFORM_EXPORT     __declspec(dllexport)
#define XALAN_PLATFORM_IMPORT     __declspec(dllimport)
#define XALAN_PLATFORM_EXPORT_FUNCTION(T) XALAN_PLATFORM_EXPORT T
#define XALAN_PLATFORM_IMPORT_FUNCTION(T) XALAN_PLATFORM_IMPORT T

#if _MSC_VER >= 1300
  #define XALAN_INLINE_INITIALIZATION
  #if !defined(__INTEL_COMPILER)
    #define XALAN_INLINE_INITIALIZATION_IS_DEFINITION_BUG
    #if _MSC_VER >= 1400
      #define XALAN_AUTO_PTR_REQUIRES_DEFINITION
    #endif
   #endif
  #define XALAN_NEW_STD_ALLOCATOR
  #define XALAN_HAS_STD_ITERATORS
  #if _MSC_VER == 1300
    #define XALAN_VCPP_USE_PTRIT
  #endif
#else
  #define XALAN_REQUIRES_QUALIFIED_DESTRUCTOR
  #define XALAN_NO_COVARIANT_RETURN_TYPE
#endif

#define XALAN_LSTRSUPPORT
#define XALAN_NEWLINE_IS_CRLF
#define XALAN_HAS_CPP_NAMESPACE
#define XALAN_HAS_STD_DISTANCE
#define XALAN_NO_REENTRANT_TIME_FUNCTIONS

#endif	// VCPPDEFINITIONS_HEADER_GUARD_1357924680
<commit_msg>Disable spurious warning about change in behavior in Visual C++.<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the  "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#if !defined(VCPPDEFINITIONS_HEADER_GUARD_1357924680)
#define VCPPDEFINITIONS_HEADER_GUARD_1357924680

#pragma warning(disable: 4127 4251 4345 4351 4511 4512 4514 4702 4710 4711 4786 4097 4503 4786; error: 4150 4172 4238 4239 4715)

// ---------------------------------------------------------------------------
//  A define in the build for each project is also used to control whether
//  the export keyword is from the project's viewpoint or the client's.
//  These defines provide the platform specific keywords that they need
//  to do this.
// ---------------------------------------------------------------------------
#define XALAN_PLATFORM_EXPORT     __declspec(dllexport)
#define XALAN_PLATFORM_IMPORT     __declspec(dllimport)
#define XALAN_PLATFORM_EXPORT_FUNCTION(T) XALAN_PLATFORM_EXPORT T
#define XALAN_PLATFORM_IMPORT_FUNCTION(T) XALAN_PLATFORM_IMPORT T

#if _MSC_VER >= 1300
  #define XALAN_INLINE_INITIALIZATION
  #if !defined(__INTEL_COMPILER)
    #define XALAN_INLINE_INITIALIZATION_IS_DEFINITION_BUG
    #if _MSC_VER >= 1400
      #define XALAN_AUTO_PTR_REQUIRES_DEFINITION
    #endif
   #endif
  #define XALAN_NEW_STD_ALLOCATOR
  #define XALAN_HAS_STD_ITERATORS
  #if _MSC_VER == 1300
    #define XALAN_VCPP_USE_PTRIT
  #endif
#else
  #define XALAN_REQUIRES_QUALIFIED_DESTRUCTOR
  #define XALAN_NO_COVARIANT_RETURN_TYPE
#endif

#define XALAN_LSTRSUPPORT
#define XALAN_NEWLINE_IS_CRLF
#define XALAN_HAS_CPP_NAMESPACE
#define XALAN_HAS_STD_DISTANCE
#define XALAN_NO_REENTRANT_TIME_FUNCTIONS

#endif	// VCPPDEFINITIONS_HEADER_GUARD_1357924680
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: crarray.cxx,v $
 *
 *  $Revision: 1.1.1.1 $
 *
 *  last change: $Author: hr $ $Date: 2000-09-18 15:29:33 $
 *
 *  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 _TYPELIB_TYPEDESCRIPTION_H_
#include <typelib/typedescription.h>
#endif
#ifndef _UNO_DATA_H_
#include <uno/data.h>
#endif

#include "base.hxx"

namespace stoc_corefl
{

// XInterface
//__________________________________________________________________________________________________
Any ArrayIdlClassImpl::queryInterface( const Type & rType )
    throw(::com::sun::star::uno::RuntimeException)
{
    Any aRet( ::cppu::queryInterface( rType, static_cast< XIdlArray * >( this ) ) );
    return (aRet.hasValue() ? aRet : IdlClassImpl::queryInterface( rType ));
}
//__________________________________________________________________________________________________
void ArrayIdlClassImpl::acquire() throw()
{
    IdlClassImpl::acquire();
}
//__________________________________________________________________________________________________
void ArrayIdlClassImpl::release() throw()
{
    IdlClassImpl::release();
}

// XTypeProvider
//__________________________________________________________________________________________________
Sequence< Type > ArrayIdlClassImpl::getTypes()
    throw (::com::sun::star::uno::RuntimeException)
{
    static OTypeCollection * s_pTypes = 0;
    if (! s_pTypes)
    {
        MutexGuard aGuard( getMutexAccess() );
        if (! s_pTypes)
        {
            static OTypeCollection s_aTypes(
                ::getCppuType( (const Reference< XIdlArray > *)0 ),
                IdlClassImpl::getTypes() );
            s_pTypes = &s_aTypes;
        }
    }
    return s_pTypes->getTypes();
}
//__________________________________________________________________________________________________
Sequence< sal_Int8 > ArrayIdlClassImpl::getImplementationId()
    throw (::com::sun::star::uno::RuntimeException)
{
    static OImplementationId * s_pId = 0;
    if (! s_pId)
    {
        MutexGuard aGuard( getMutexAccess() );
        if (! s_pId)
        {
            static OImplementationId s_aId;
            s_pId = &s_aId;
        }
    }
    return s_pId->getImplementationId();
}

// XIdlArray
//__________________________________________________________________________________________________
void ArrayIdlClassImpl::realloc( Any & rArray, sal_Int32 nLen )
    throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException)
{
    TypeClass eTC = rArray.getValueTypeClass();
    if (eTC != TypeClass_SEQUENCE && eTC != TypeClass_ARRAY)
    {
        throw IllegalArgumentException(
            OUString( RTL_CONSTASCII_USTRINGPARAM("no sequence given!") ),
            (XWeak *)(OWeakObject *)this, 0 );
    }
    if (nLen < 0)
    {
        throw IllegalArgumentException(
            OUString( RTL_CONSTASCII_USTRINGPARAM("illegal length given!") ),
            (XWeak *)(OWeakObject *)this, 1 );
    }

    uno_Sequence ** ppSeq = (uno_Sequence **)rArray.getValue();
    uno_sequence_realloc( ppSeq, (typelib_TypeDescription *)getTypeDescr(),
                          nLen, cpp_acquire, cpp_release );
    rArray.pData = ppSeq;
}
//__________________________________________________________________________________________________
sal_Int32 ArrayIdlClassImpl::getLen( const Any & rArray )
    throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException)
{
    TypeClass eTC = rArray.getValueTypeClass();
    if (eTC != TypeClass_SEQUENCE && eTC != TypeClass_ARRAY)
    {
        throw IllegalArgumentException(
            OUString( RTL_CONSTASCII_USTRINGPARAM("no sequence given!") ),
            (XWeak *)(OWeakObject *)this, 0 );
    }

    return (*(uno_Sequence **)rArray.getValue())->nElements;
}
//__________________________________________________________________________________________________
Any ArrayIdlClassImpl::get( const Any & rArray, sal_Int32 nIndex )
    throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::ArrayIndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException)
{
    TypeClass eTC = rArray.getValueTypeClass();
    if (eTC != TypeClass_SEQUENCE && eTC != TypeClass_ARRAY)
    {
        throw IllegalArgumentException(
            OUString( RTL_CONSTASCII_USTRINGPARAM("no sequence given!") ),
            (XWeak *)(OWeakObject *)this, 0 );
    }

    uno_Sequence * pSeq = *(uno_Sequence **)rArray.getValue();
    if (pSeq->nElements <= nIndex)
    {
        throw ArrayIndexOutOfBoundsException(
            OUString( RTL_CONSTASCII_USTRINGPARAM("illegal index given!") ),
            (XWeak *)(OWeakObject *)this );
    }

    Any aRet;
    typelib_TypeDescription * pElemTypeDescr = 0;
    TYPELIB_DANGER_GET( &pElemTypeDescr, getTypeDescr()->pType );
    uno_any_destruct( &aRet, cpp_release );
    uno_any_construct( &aRet, &pSeq->elements[nIndex * pElemTypeDescr->nSize],
                       pElemTypeDescr, cpp_acquire );
    TYPELIB_DANGER_RELEASE( pElemTypeDescr );
    return aRet;
}

//__________________________________________________________________________________________________
void ArrayIdlClassImpl::set( Any & rArray, sal_Int32 nIndex, const Any & rNewValue )
    throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::ArrayIndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException)
{
    TypeClass eTC = rArray.getValueTypeClass();
    if (eTC != TypeClass_SEQUENCE && eTC != TypeClass_ARRAY)
    {
        throw IllegalArgumentException(
            OUString( RTL_CONSTASCII_USTRINGPARAM("no sequence given!") ),
            (XWeak *)(OWeakObject *)this, 0 );
    }

    uno_Sequence * pSeq = *(uno_Sequence **)rArray.getValue();
    if (pSeq->nElements <= nIndex)
    {
        throw ArrayIndexOutOfBoundsException(
            OUString( RTL_CONSTASCII_USTRINGPARAM("illegal index given!") ),
            (XWeak *)(OWeakObject *)this );
    }

    uno_Sequence ** ppSeq = (uno_Sequence **)rArray.getValue();
    uno_sequence_reference2One( ppSeq, (typelib_TypeDescription *)getTypeDescr(), cpp_acquire, cpp_release );
    rArray.pData = ppSeq;
    pSeq = *ppSeq;

    typelib_TypeDescription * pElemTypeDescr = 0;
    TYPELIB_DANGER_GET( &pElemTypeDescr, getTypeDescr()->pType );

    if (! coerce_assign( &pSeq->elements[nIndex * pElemTypeDescr->nSize],
                         pElemTypeDescr, rNewValue, getReflection() ))
    {
        TYPELIB_DANGER_RELEASE( pElemTypeDescr );
        throw IllegalArgumentException(
            OUString( RTL_CONSTASCII_USTRINGPARAM("sequence element is not assignable by given value!") ),
            (XWeak *)(OWeakObject *)this, 2 );
    }
    TYPELIB_DANGER_RELEASE( pElemTypeDescr );
}

// ArrayIdlClassImpl
//__________________________________________________________________________________________________
sal_Bool ArrayIdlClassImpl::isAssignableFrom( const Reference< XIdlClass > & xType )
    throw(::com::sun::star::uno::RuntimeException)
{
    return (xType.is() &&
            (equals( xType ) ||
             (xType->getTypeClass() == getTypeClass() && // must be sequence|array
              getComponentType()->isAssignableFrom( xType->getComponentType() ))));
}
//__________________________________________________________________________________________________
Reference< XIdlClass > ArrayIdlClassImpl::getComponentType()
    throw(::com::sun::star::uno::RuntimeException)
{
    return getReflection()->forType( getTypeDescr()->pType );
}
//__________________________________________________________________________________________________
Reference< XIdlArray > ArrayIdlClassImpl::getArray()
    throw(::com::sun::star::uno::RuntimeException)
{
    return this;
}

}

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

#ifndef _TYPELIB_TYPEDESCRIPTION_H_
#include <typelib/typedescription.h>
#endif
#ifndef _UNO_DATA_H_
#include <uno/data.h>
#endif

#include "base.hxx"

namespace stoc_corefl
{

// XInterface
//__________________________________________________________________________________________________
Any ArrayIdlClassImpl::queryInterface( const Type & rType )
    throw(::com::sun::star::uno::RuntimeException)
{
    Any aRet( ::cppu::queryInterface( rType, static_cast< XIdlArray * >( this ) ) );
    return (aRet.hasValue() ? aRet : IdlClassImpl::queryInterface( rType ));
}
//__________________________________________________________________________________________________
void ArrayIdlClassImpl::acquire() throw()
{
    IdlClassImpl::acquire();
}
//__________________________________________________________________________________________________
void ArrayIdlClassImpl::release() throw()
{
    IdlClassImpl::release();
}

// XTypeProvider
//__________________________________________________________________________________________________
Sequence< Type > ArrayIdlClassImpl::getTypes()
    throw (::com::sun::star::uno::RuntimeException)
{
    static OTypeCollection * s_pTypes = 0;
    if (! s_pTypes)
    {
        MutexGuard aGuard( getMutexAccess() );
        if (! s_pTypes)
        {
            static OTypeCollection s_aTypes(
                ::getCppuType( (const Reference< XIdlArray > *)0 ),
                IdlClassImpl::getTypes() );
            s_pTypes = &s_aTypes;
        }
    }
    return s_pTypes->getTypes();
}
//__________________________________________________________________________________________________
Sequence< sal_Int8 > ArrayIdlClassImpl::getImplementationId()
    throw (::com::sun::star::uno::RuntimeException)
{
    static OImplementationId * s_pId = 0;
    if (! s_pId)
    {
        MutexGuard aGuard( getMutexAccess() );
        if (! s_pId)
        {
            static OImplementationId s_aId;
            s_pId = &s_aId;
        }
    }
    return s_pId->getImplementationId();
}

// XIdlArray
//__________________________________________________________________________________________________
void ArrayIdlClassImpl::realloc( Any & rArray, sal_Int32 nLen )
    throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException)
{
    TypeClass eTC = rArray.getValueTypeClass();
    if (eTC != TypeClass_SEQUENCE && eTC != TypeClass_ARRAY)
    {
        throw IllegalArgumentException(
            OUString( RTL_CONSTASCII_USTRINGPARAM("no sequence given!") ),
            (XWeak *)(OWeakObject *)this, 0 );
    }
    if (nLen < 0)
    {
        throw IllegalArgumentException(
            OUString( RTL_CONSTASCII_USTRINGPARAM("illegal length given!") ),
            (XWeak *)(OWeakObject *)this, 1 );
    }

    uno_Sequence ** ppSeq = (uno_Sequence **)rArray.getValue();
    uno_sequence_realloc( ppSeq, (typelib_TypeDescription *)getTypeDescr(),
                          nLen, cpp_acquire, cpp_release );
    rArray.pData = ppSeq;
}
//__________________________________________________________________________________________________
sal_Int32 ArrayIdlClassImpl::getLen( const Any & rArray )
    throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException)
{
    TypeClass eTC = rArray.getValueTypeClass();
    if (eTC != TypeClass_SEQUENCE && eTC != TypeClass_ARRAY)
    {
        throw IllegalArgumentException(
            OUString( RTL_CONSTASCII_USTRINGPARAM("no sequence given!") ),
            (XWeak *)(OWeakObject *)this, 0 );
    }

    return (*(uno_Sequence **)rArray.getValue())->nElements;
}
//__________________________________________________________________________________________________
Any ArrayIdlClassImpl::get( const Any & rArray, sal_Int32 nIndex )
    throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::ArrayIndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException)
{
    TypeClass eTC = rArray.getValueTypeClass();
    if (eTC != TypeClass_SEQUENCE && eTC != TypeClass_ARRAY)
    {
        throw IllegalArgumentException(
            OUString( RTL_CONSTASCII_USTRINGPARAM("no sequence given!") ),
            (XWeak *)(OWeakObject *)this, 0 );
    }

    uno_Sequence * pSeq = *(uno_Sequence **)rArray.getValue();
    if (pSeq->nElements <= nIndex)
    {
        throw ArrayIndexOutOfBoundsException(
            OUString( RTL_CONSTASCII_USTRINGPARAM("illegal index given!") ),
            (XWeak *)(OWeakObject *)this );
    }

    Any aRet;
    typelib_TypeDescription * pElemTypeDescr = 0;
    TYPELIB_DANGER_GET( &pElemTypeDescr, getTypeDescr()->pType );
    uno_any_destruct( &aRet, cpp_release );
    uno_any_construct( &aRet, &pSeq->elements[nIndex * pElemTypeDescr->nSize],
                       pElemTypeDescr, cpp_acquire );
    TYPELIB_DANGER_RELEASE( pElemTypeDescr );
    return aRet;
}

//__________________________________________________________________________________________________
void ArrayIdlClassImpl::set( Any & rArray, sal_Int32 nIndex, const Any & rNewValue )
    throw(::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::ArrayIndexOutOfBoundsException, ::com::sun::star::uno::RuntimeException)
{
    TypeClass eTC = rArray.getValueTypeClass();
    if (eTC != TypeClass_SEQUENCE && eTC != TypeClass_ARRAY)
    {
        throw IllegalArgumentException(
            OUString( RTL_CONSTASCII_USTRINGPARAM("no sequence given!") ),
            (XWeak *)(OWeakObject *)this, 0 );
    }

    uno_Sequence * pSeq = *(uno_Sequence **)rArray.getValue();
    if (pSeq->nElements <= nIndex)
    {
        throw ArrayIndexOutOfBoundsException(
            OUString( RTL_CONSTASCII_USTRINGPARAM("illegal index given!") ),
            (XWeak *)(OWeakObject *)this );
    }

    uno_Sequence ** ppSeq = (uno_Sequence **)rArray.getValue();
    uno_sequence_reference2One( ppSeq, (typelib_TypeDescription *)getTypeDescr(), cpp_acquire, cpp_release );
    rArray.pData = ppSeq;
    pSeq = *ppSeq;

    typelib_TypeDescription * pElemTypeDescr = 0;
    TYPELIB_DANGER_GET( &pElemTypeDescr, getTypeDescr()->pType );

    if (! coerce_assign( &pSeq->elements[nIndex * pElemTypeDescr->nSize],
                         pElemTypeDescr, rNewValue, getReflection() ))
    {
        TYPELIB_DANGER_RELEASE( pElemTypeDescr );
        throw IllegalArgumentException(
            OUString( RTL_CONSTASCII_USTRINGPARAM("sequence element is not assignable by given value!") ),
            (XWeak *)(OWeakObject *)this, 2 );
    }
    TYPELIB_DANGER_RELEASE( pElemTypeDescr );
}

// ArrayIdlClassImpl
//__________________________________________________________________________________________________
sal_Bool ArrayIdlClassImpl::isAssignableFrom( const Reference< XIdlClass > & xType )
    throw(::com::sun::star::uno::RuntimeException)
{
    return (xType.is() &&
            (equals( xType ) ||
             (xType->getTypeClass() == getTypeClass() && // must be sequence|array
              getComponentType()->isAssignableFrom( xType->getComponentType() ))));
}
//__________________________________________________________________________________________________
Reference< XIdlClass > ArrayIdlClassImpl::getComponentType()
    throw(::com::sun::star::uno::RuntimeException)
{
    return getReflection()->forType( getTypeDescr()->pType );
}
//__________________________________________________________________________________________________
Reference< XIdlArray > ArrayIdlClassImpl::getArray()
    throw(::com::sun::star::uno::RuntimeException)
{
    return this;
}

}

<|endoftext|>


<commit_before>/* This file is part of the KDE project
 * Copyright (C) 2007 Aaron Seigo <aseigo@kde.org>
 * Copyright (C) 2004 Bram Schoenmakers <bramschoenmakers@kde.nl>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation version 2.
 *
 * This program is distributed in the hope that
t it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; see the file COPYING.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 *
 */

#include "icsendanalyzer.h"

#include <kcal/calendarlocal.h>
#include <kcal/icalformat.h>
#include <kcal/vcalformat.h>
#include <kcal/todo.h>

#include <strigi/fieldtypes.h>
#include <strigi/analysisresult.h>
#include <strigi/streamendanalyzer.h>

//#include <KDebug>

using namespace KCal;

IcsEndAnalyzer::IcsEndAnalyzer( const IcsEndAnalyzerFactory* f )
  : m_factory( f )
{
}

bool IcsEndAnalyzer::checkHeader( const char* header, int32_t headersize ) const
{
  const char* magic = "BEGIN:VCALENDAR";
  int32_t magicLength = strlen( magic );

  return headersize >= magicLength && !strncmp( magic, header, magicLength );
}

/*
I chose to use libkcal instead of reading the calendar manually. It's easier to
maintain this way.
*/
char IcsEndAnalyzer::analyze( Strigi::AnalysisResult& idx, Strigi::InputStream* in )
{
  CalendarLocal cal( QString::fromLatin1( "UTC" ) );

  const char* data;
  //FIXME: large calendars will exhaust memory; incremental loading would be nice
  if ( in->read( data, 1, in->size() ) < 0 ) {
    //kDebug() <<"Reading data from input stream failed";
    return Strigi::Error;
  }

  ICalFormat ical;
  if ( !ical.fromRawString( &cal, data ) ) {
    VCalFormat vcal;
    if ( !vcal.fromRawString( &cal, data ) ) {
      //kDebug() <<"Could not load calendar";
      return Strigi::Error;
    }
  }

  idx.addValue( m_factory->field( ProductId ), cal.productId().toUtf8().data() );
  idx.addValue( m_factory->field( Events ), cal.events().count() );
  idx.addValue( m_factory->field( Journals ), cal.journals().count() );
  Todo::List todos = cal.todos();

  // count completed and overdue
  int completed = 0;
  int overdue = 0;
  foreach ( const Todo* todo, todos ) {
    if ( todo->isCompleted() ) {
      ++completed;
    } else if ( todo->hasDueDate() && todo->dtDue().date() < QDate::currentDate() ) {
      ++overdue;
    }
  }

  idx.addValue( m_factory->field( Todos ), todos.count() );
  idx.addValue( m_factory->field( TodosCompleted ), completed );
  idx.addValue( m_factory->field( TodosOverdue ), overdue );

  cal.close();

  return Strigi::Ok;
}

const Strigi::RegisteredField* IcsEndAnalyzerFactory::field( IcsEndAnalyzer::Field f ) const
{
  switch ( f ) {
    case IcsEndAnalyzer::ProductId:
      return productIdField;
      break;
    case IcsEndAnalyzer::Events:
      return eventsField;
      break;
    case IcsEndAnalyzer::Journals:
      return journalsField;
      break;
    case IcsEndAnalyzer::Todos:
      return todosField;
      break;
    case IcsEndAnalyzer::TodosCompleted:
      return todosCompletedField;
      break;
    case IcsEndAnalyzer::TodosOverdue:
    default:
      return todosOverdueField;
      break;
  }
}

void IcsEndAnalyzerFactory::registerFields( Strigi::FieldRegister& reg ) {
  productIdField = reg.registerField("Product Id", Strigi::FieldRegister::stringType, 1, 0 );
  eventsField = reg.registerField("Events", Strigi::FieldRegister::integerType, 1, 0 );
  journalsField = reg.registerField("Journals", Strigi::FieldRegister::integerType, 1, 0 );
  todosField = reg.registerField("Todos", Strigi::FieldRegister::integerType, 1, 0 );
  todosCompletedField = reg.registerField("Todos Completed", Strigi::FieldRegister::integerType, 1, 0 );
  todosOverdueField = reg.registerField("Todos Overdue", Strigi::FieldRegister::integerType, 1, 0 );
}

<commit_msg>cast to uint32_t in order to fix ambiguity for overloaded methods (msvc)<commit_after>/* This file is part of the KDE project
 * Copyright (C) 2007 Aaron Seigo <aseigo@kde.org>
 * Copyright (C) 2004 Bram Schoenmakers <bramschoenmakers@kde.nl>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation version 2.
 *
 * This program is distributed in the hope that
t it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; see the file COPYING.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 *
 */

#include "icsendanalyzer.h"

#include <kcal/calendarlocal.h>
#include <kcal/icalformat.h>
#include <kcal/vcalformat.h>
#include <kcal/todo.h>

#include <strigi/fieldtypes.h>
#include <strigi/analysisresult.h>
#include <strigi/streamendanalyzer.h>

//#include <KDebug>

using namespace KCal;

IcsEndAnalyzer::IcsEndAnalyzer( const IcsEndAnalyzerFactory* f )
  : m_factory( f )
{
}

bool IcsEndAnalyzer::checkHeader( const char* header, int32_t headersize ) const
{
  const char* magic = "BEGIN:VCALENDAR";
  int32_t magicLength = strlen( magic );

  return headersize >= magicLength && !strncmp( magic, header, magicLength );
}

/*
I chose to use libkcal instead of reading the calendar manually. It's easier to
maintain this way.
*/
char IcsEndAnalyzer::analyze( Strigi::AnalysisResult& idx, Strigi::InputStream* in )
{
  CalendarLocal cal( QString::fromLatin1( "UTC" ) );

  const char* data;
  //FIXME: large calendars will exhaust memory; incremental loading would be nice
  if ( in->read( data, 1, in->size() ) < 0 ) {
    //kDebug() <<"Reading data from input stream failed";
    return Strigi::Error;
  }

  ICalFormat ical;
  if ( !ical.fromRawString( &cal, data ) ) {
    VCalFormat vcal;
    if ( !vcal.fromRawString( &cal, data ) ) {
      //kDebug() <<"Could not load calendar";
      return Strigi::Error;
    }
  }

  idx.addValue( m_factory->field( ProductId ), cal.productId().toUtf8().data() );
  idx.addValue( m_factory->field( Events ), (uint32_t)cal.events().count() );
  idx.addValue( m_factory->field( Journals ), (uint32_t)cal.journals().count() );
  Todo::List todos = cal.todos();

  // count completed and overdue
  int completed = 0;
  int overdue = 0;
  foreach ( const Todo* todo, todos ) {
    if ( todo->isCompleted() ) {
      ++completed;
    } else if ( todo->hasDueDate() && todo->dtDue().date() < QDate::currentDate() ) {
      ++overdue;
    }
  }

  idx.addValue( m_factory->field( Todos ), (uint32_t)todos.count() );
  idx.addValue( m_factory->field( TodosCompleted ), (uint32_t)completed );
  idx.addValue( m_factory->field( TodosOverdue ), (uint32_t)overdue );

  cal.close();

  return Strigi::Ok;
}

const Strigi::RegisteredField* IcsEndAnalyzerFactory::field( IcsEndAnalyzer::Field f ) const
{
  switch ( f ) {
    case IcsEndAnalyzer::ProductId:
      return productIdField;
      break;
    case IcsEndAnalyzer::Events:
      return eventsField;
      break;
    case IcsEndAnalyzer::Journals:
      return journalsField;
      break;
    case IcsEndAnalyzer::Todos:
      return todosField;
      break;
    case IcsEndAnalyzer::TodosCompleted:
      return todosCompletedField;
      break;
    case IcsEndAnalyzer::TodosOverdue:
    default:
      return todosOverdueField;
      break;
  }
}

void IcsEndAnalyzerFactory::registerFields( Strigi::FieldRegister& reg ) {
  productIdField = reg.registerField("Product Id", Strigi::FieldRegister::stringType, 1, 0 );
  eventsField = reg.registerField("Events", Strigi::FieldRegister::integerType, 1, 0 );
  journalsField = reg.registerField("Journals", Strigi::FieldRegister::integerType, 1, 0 );
  todosField = reg.registerField("Todos", Strigi::FieldRegister::integerType, 1, 0 );
  todosCompletedField = reg.registerField("Todos Completed", Strigi::FieldRegister::integerType, 1, 0 );
  todosOverdueField = reg.registerField("Todos Overdue", Strigi::FieldRegister::integerType, 1, 0 );
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: stringtransfer.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: obr $ $Date: 2001-05-21 09:19:00 $
 *
 *  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 EXPRESS 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 _SVTOOLS_STRINGTRANSFER_HXX_
#include "stringtransfer.hxx"
#endif

//........................................................................
namespace svt
{
//........................................................................

    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::datatransfer;

    //====================================================================
    //= OStringTransferable
    //====================================================================
    //--------------------------------------------------------------------
    OStringTransferable::OStringTransferable(const ::rtl::OUString& _rContent)
        :TransferableHelper()
        ,m_sContent( _rContent )
    {
    }

    //--------------------------------------------------------------------
    void OStringTransferable::AddSupportedFormats()
    {
        AddFormat(SOT_FORMAT_STRING);
    }

    //--------------------------------------------------------------------
    sal_Bool OStringTransferable::GetData( const DataFlavor& _rFlavor )
    {
        sal_uInt32 nFormat = SotExchange::GetFormat( _rFlavor );
        if (SOT_FORMAT_STRING == nFormat)
            return SetString( m_sContent, _rFlavor );

        return sal_False;
    }

    //====================================================================
    //= OStringTransfer
    //====================================================================
    //--------------------------------------------------------------------
    void OStringTransfer::CopyString( const ::rtl::OUString& _rContent, Window* _pWindow )
    {
        OStringTransferable* pTransferable = new OStringTransferable( _rContent );
        Reference< XTransferable > xTransfer = pTransferable;
        pTransferable->CopyToClipboard( _pWindow );
    }

    //--------------------------------------------------------------------
    sal_Bool OStringTransfer::PasteString( ::rtl::OUString& _rContent, Window* _pWindow )
    {
        TransferableDataHelper aClipboardData = TransferableDataHelper::CreateFromSystemClipboard( _pWindow );

        // check for a string format
        const DataFlavorExVector& rFormats = aClipboardData.GetDataFlavorExVector();
        for (   DataFlavorExVector::const_iterator aSearch = rFormats.begin();
                aSearch != rFormats.end();
                ++aSearch
            )
        {
            if (SOT_FORMAT_STRING == aSearch->mnSotId)
            {
                String sContent;
                sal_Bool bSuccess = aClipboardData.GetString( SOT_FORMAT_STRING, sContent );
                _rContent = sContent;
                return bSuccess;
            }
        }

        return sal_False;
    }

    //--------------------------------------------------------------------
    void OStringTransfer::StartStringDrag( const ::rtl::OUString& _rContent, Window* _pWindow, sal_Int8 _nDragSourceActions )
    {
        OStringTransferable* pTransferable = new OStringTransferable( _rContent );
        Reference< XTransferable > xTransfer = pTransferable;
        pTransferable->StartDrag(_pWindow, _nDragSourceActions);
    }

//........................................................................
}   // namespace svt
//........................................................................

/*************************************************************************
 * history:
 *  $Log: not supported by cvs2svn $
 *  Revision 1.2  2001/03/28 08:18:15  fs
 *  +StartStringDrag
 *
 *  Revision 1.1  2001/03/27 14:35:35  fs
 *  initial checkin - helper classes for clipboard handling of strings
 *
 *
 *  Revision 1.0 27.03.01 14:43:33  fs
 ************************************************************************/

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

#ifndef _SVTOOLS_STRINGTRANSFER_HXX_
#include "stringtransfer.hxx"
#endif

//........................................................................
namespace svt
{
//........................................................................

    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::datatransfer;

    //====================================================================
    //= OStringTransferable
    //====================================================================
    //--------------------------------------------------------------------
    OStringTransferable::OStringTransferable(const ::rtl::OUString& _rContent)
        :TransferableHelper()
        ,m_sContent( _rContent )
    {
    }

    //--------------------------------------------------------------------
    void OStringTransferable::AddSupportedFormats()
    {
        AddFormat(SOT_FORMAT_STRING);
    }

    //--------------------------------------------------------------------
    sal_Bool OStringTransferable::GetData( const DataFlavor& _rFlavor )
    {
        sal_uInt32 nFormat = SotExchange::GetFormat( _rFlavor );
        if (SOT_FORMAT_STRING == nFormat)
            return SetString( m_sContent, _rFlavor );

        return sal_False;
    }

    //====================================================================
    //= OStringTransfer
    //====================================================================
    //--------------------------------------------------------------------
    void OStringTransfer::CopyString( const ::rtl::OUString& _rContent, Window* _pWindow )
    {
        OStringTransferable* pTransferable = new OStringTransferable( _rContent );
        Reference< XTransferable > xTransfer = pTransferable;
        pTransferable->CopyToClipboard( _pWindow );
    }

    //--------------------------------------------------------------------
    sal_Bool OStringTransfer::PasteString( ::rtl::OUString& _rContent, Window* _pWindow )
    {
        TransferableDataHelper aClipboardData = TransferableDataHelper::CreateFromSystemClipboard( _pWindow );

        // check for a string format
        const DataFlavorExVector& rFormats = aClipboardData.GetDataFlavorExVector();
        for (   DataFlavorExVector::const_iterator aSearch = rFormats.begin();
                aSearch != rFormats.end();
                ++aSearch
            )
        {
            if (SOT_FORMAT_STRING == aSearch->mnSotId)
            {
                String sContent;
                sal_Bool bSuccess = aClipboardData.GetString( SOT_FORMAT_STRING, sContent );
                _rContent = sContent;
                return bSuccess;
            }
        }

        return sal_False;
    }

    //--------------------------------------------------------------------
    void OStringTransfer::StartStringDrag( const ::rtl::OUString& _rContent, Window* _pWindow, sal_Int8 _nDragSourceActions )
    {
        OStringTransferable* pTransferable = new OStringTransferable( _rContent );
        Reference< XTransferable > xTransfer = pTransferable;
        pTransferable->StartDrag(_pWindow, _nDragSourceActions);
    }

//........................................................................
}   // namespace svt
//........................................................................

/*************************************************************************
 * history:
 *  $Log: not supported by cvs2svn $
 *  Revision 1.3.1096.1  2005/09/05 14:53:40  rt
 *  #i54170# Change license header: remove SISSL
 *
 *  Revision 1.3  2001/05/21 09:19:00  obr
 *  #81916# copy and paste only with window
 *
 *  Revision 1.2  2001/03/28 08:18:15  fs
 *  +StartStringDrag
 *
 *  Revision 1.1  2001/03/27 14:35:35  fs
 *  initial checkin - helper classes for clipboard handling of strings
 *
 *
 *  Revision 1.0 27.03.01 14:43:33  fs
 ************************************************************************/

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: swunohelper.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: hr $ $Date: 2003-03-27 15:41:21 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#pragma hdrstop

#define _SVSTDARR_STRINGS

#ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_
#include <com/sun/star/uno/Sequence.h>
#endif
#ifndef _COM_SUN_STAR_UNO_EXCEPTION_HPP_
#include <com/sun/star/uno/Exception.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_XCONTENTIDENTIFIER_HPP_
#include <com/sun/star/ucb/XContentIdentifier.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_XCONTENTPROVIDER_HPP_
#include <com/sun/star/ucb/XContentProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_XCOMMANDENVIRONMENT_HPP_
#include <com/sun/star/ucb/XCommandEnvironment.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_TRANSFERINFO_HPP_
#include <com/sun/star/ucb/TransferInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_NAMECLASH_HDL_
#include <com/sun/star/ucb/NameClash.hdl>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_DATETIME_HPP_
#include <com/sun/star/util/DateTime.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#ifndef _DATETIME_HXX
#include <tools/datetime.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _UCBHELPER_CONTENTIDENTIFIER_HXX
#include <ucbhelper/contentidentifier.hxx>
#endif
#ifndef _UCBHELPER_CONTENTBROKER_HXX
#include <ucbhelper/contentbroker.hxx>
#endif
#ifndef _UCBHELPER_CONTENT_HXX
#include <ucbhelper/content.hxx>
#endif
#include <svtools/svstdarr.hxx>

#ifndef _SWUNOHELPER_HXX
#include <swunohelper.hxx>
#endif
#ifndef _SWUNODEF_HXX
#include <swunodef.hxx>
#endif
#ifndef _ERRHDL_HXX
#include <errhdl.hxx>
#endif

namespace SWUnoHelper {

sal_Int32 GetEnumAsInt32( const UNO_NMSPC::Any& rVal )
{
    sal_Int32 eVal;
    try
    {
        eVal = comphelper::getEnumAsINT32( rVal );
    }
    catch( UNO_NMSPC::Exception & )
    {
        eVal = 0;
        ASSERT( FALSE, "can't get EnumAsInt32" );
    }
    return eVal;
}

// methods for UCB actions
BOOL UCB_DeleteFile( const String& rURL )
{
    BOOL bRemoved;
    try
    {
        ucb::Content aTempContent( rURL,
                                STAR_REFERENCE( ucb::XCommandEnvironment )());
        aTempContent.executeCommand(
                        rtl::OUString::createFromAscii( "delete" ),
                        UNO_NMSPC::makeAny( sal_Bool( sal_True ) ) );
        bRemoved = TRUE;
    }
    catch( UNO_NMSPC::Exception& )
    {
        bRemoved = FALSE;
        ASSERT( FALSE, "Exeception from executeCommand( delete )" );
    }
    return bRemoved;
}

BOOL UCB_CopyFile( const String& rURL, const String& rNewURL, BOOL bCopyIsMove )
{
    BOOL bCopyCompleted = TRUE;
    try
    {
        INetURLObject aURL( rNewURL );
        String sName( aURL.GetName() );
        aURL.removeSegment();
        String sMainURL( aURL.GetMainURL(INetURLObject::NO_DECODE) );

        ucb::Content aTempContent( sMainURL,
                                STAR_REFERENCE( ucb::XCommandEnvironment )());

        UNO_NMSPC::Any aAny;
        STAR_NMSPC::ucb::TransferInfo aInfo;
        aInfo.NameClash = STAR_NMSPC::ucb::NameClash::ERROR;
        aInfo.NewTitle = sName;
        aInfo.SourceURL = rURL;
        aInfo.MoveData = bCopyIsMove;
        aAny <<= aInfo;
        aTempContent.executeCommand(
                            rtl::OUString::createFromAscii( "transfer" ),
                            aAny );
    }
    catch( UNO_NMSPC::Exception& )
    {
        ASSERT( FALSE, "Exeception from executeCommand( transfer )" );
        bCopyCompleted = FALSE;
    }
    return bCopyCompleted;
}

BOOL UCB_IsCaseSensitiveFileName( const String& rURL )
{
    BOOL bCaseSensitive;
    try
    {
        STAR_REFERENCE( lang::XMultiServiceFactory ) xMSF =
                                    comphelper::getProcessServiceFactory();

        INetURLObject aTempObj( rURL );
        aTempObj.SetBase( aTempObj.GetBase().ToLowerAscii() );
        STAR_REFERENCE( ucb::XContentIdentifier ) xRef1 = new
                ucb::ContentIdentifier( xMSF,
                            aTempObj.GetMainURL( INetURLObject::NO_DECODE ));

        aTempObj.SetBase(aTempObj.GetBase().ToUpperAscii());
        STAR_REFERENCE( ucb::XContentIdentifier ) xRef2 = new
                ucb::ContentIdentifier( xMSF,
                            aTempObj.GetMainURL( INetURLObject::NO_DECODE ));

        STAR_REFERENCE( ucb::XContentProvider ) xProv =
                ucb::ContentBroker::get()->getContentProviderInterface();

        sal_Int32 nCompare = xProv->compareContentIds( xRef1, xRef2 );
        bCaseSensitive = 0 != nCompare;
    }
    catch( UNO_NMSPC::Exception& )
    {
        bCaseSensitive = FALSE;
        ASSERT( FALSE, "Exeception from compareContentIds()" );
    }
    return bCaseSensitive;
}

BOOL UCB_IsReadOnlyFileName( const String& rURL )
{
    BOOL bIsReadOnly = FALSE;
    try
    {
        ucb::Content aCnt( rURL, STAR_REFERENCE( ucb::XCommandEnvironment )());
        UNO_NMSPC::Any aAny = aCnt.getPropertyValue(
                            rtl::OUString::createFromAscii( "IsReadOnly" ));
        if(aAny.hasValue())
            bIsReadOnly = *(sal_Bool*)aAny.getValue();
    }
    catch( UNO_NMSPC::Exception& )
    {
        bIsReadOnly = FALSE;
    }
    return bIsReadOnly;
}

BOOL UCB_IsFile( const String& rURL )
{
    BOOL bExists = FALSE;
    try
    {
        ::ucb::Content aContent( rURL, STAR_REFERENCE( ucb::XCommandEnvironment )() );
        bExists = aContent.isDocument();
    }
    catch (UNO_NMSPC::Exception &)
    {
    }
    return bExists;
}

BOOL UCB_IsDirectory( const String& rURL )
{
    BOOL bExists = FALSE;
    try
    {
        ::ucb::Content aContent( rURL, STAR_REFERENCE( ucb::XCommandEnvironment )() );
        bExists = aContent.isFolder();
    }
    catch (UNO_NMSPC::Exception &)
    {
    }
    return bExists;
}

    // get a list of files from the folder of the URL
    // options: pExtension = 0 -> all, else this specific extension
    //          pDateTime != 0 -> returns also the modified date/time of
    //                       the files in a SvPtrarr -->
    //                       !! objects must be deleted from the caller!!
BOOL UCB_GetFileListOfFolder( const String& rURL, SvStrings& rList,
                                const String* pExtension,
                                SvPtrarr* pDateTimeList )
{
    BOOL bOk = FALSE;
    try
    {
        ucb::Content aCnt( rURL, STAR_REFERENCE( ucb::XCommandEnvironment )());
        STAR_REFERENCE( sdbc::XResultSet ) xResultSet;

        USHORT nSeqSize = pDateTimeList ? 2 : 1;
        UNO_NMSPC::Sequence < rtl::OUString > aProps( nSeqSize );
        rtl::OUString* pProps = aProps.getArray();
        pProps[ 0 ] = rtl::OUString::createFromAscii( "Title" );
        if( pDateTimeList )
            pProps[ 1 ] = rtl::OUString::createFromAscii( "DateModified" );

        try
        {
            xResultSet = aCnt.createCursor( aProps, ::ucb::INCLUDE_DOCUMENTS_ONLY );
        }
        catch( UNO_NMSPC::Exception& )
        {
            DBG_ERRORFILE( "create cursor failed!" );
        }

        if( xResultSet.is() )
        {
            STAR_REFERENCE( sdbc::XRow ) xRow( xResultSet, UNO_NMSPC::UNO_QUERY );
            xub_StrLen nExtLen = pExtension ? pExtension->Len() : 0;
            try
            {
                if( xResultSet->first() )
                {
                    do {
                        String sTitle( xRow->getString( 1 ) );
                        if( !nExtLen ||
                            ( sTitle.Len() > nExtLen &&
                              sTitle.Equals( *pExtension,
                                          sTitle.Len() - nExtLen, nExtLen )) )
                        {
                            String* pStr = new String( sTitle );
                            rList.Insert( pStr, rList.Count() );

                            if( pDateTimeList )
                            {
                                STAR_NMSPC::util::DateTime aStamp = xRow->getTimestamp(2);
                                ::DateTime* pDateTime = new ::DateTime(
                                        ::Date( aStamp.Day,
                                                aStamp.Month,
                                                aStamp.Year ),
                                        ::Time( aStamp.Hours,
                                                aStamp.Minutes,
                                                aStamp.Seconds,
                                                aStamp.HundredthSeconds ));
                                void* p = pDateTime;
                                pDateTimeList->Insert( p,
                                                    pDateTimeList->Count() );
                            }
                        }

                    } while( xResultSet->next() );
                }
                bOk = TRUE;
            }
            catch( UNO_NMSPC::Exception& )
            {
                DBG_ERRORFILE( "Exception caught!" );
            }
        }
    }
    catch( UNO_NMSPC::Exception& )
    {
        DBG_ERRORFILE( "Exception caught!" );
        bOk = FALSE;
    }
    return bOk;
}

}
<commit_msg>INTEGRATION: CWS tune05 (1.2.602); FILE MERGED 2004/07/20 15:53:52 cmc 1.2.602.1: #i30554# unused UCB_IsFile<commit_after>/*************************************************************************
 *
 *  $RCSfile: swunohelper.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: obo $ $Date: 2004-08-12 12:41:56 $
 *
 *  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): _______________________________________
 *
 *
 ************************************************************************/

#pragma hdrstop

#define _SVSTDARR_STRINGS

#ifndef _COM_SUN_STAR_UNO_SEQUENCE_H_
#include <com/sun/star/uno/Sequence.h>
#endif
#ifndef _COM_SUN_STAR_UNO_EXCEPTION_HPP_
#include <com/sun/star/uno/Exception.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_XCONTENTIDENTIFIER_HPP_
#include <com/sun/star/ucb/XContentIdentifier.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_XCONTENTPROVIDER_HPP_
#include <com/sun/star/ucb/XContentProvider.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_XCOMMANDENVIRONMENT_HPP_
#include <com/sun/star/ucb/XCommandEnvironment.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_TRANSFERINFO_HPP_
#include <com/sun/star/ucb/TransferInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_UCB_NAMECLASH_HDL_
#include <com/sun/star/ucb/NameClash.hdl>
#endif
#ifndef _COM_SUN_STAR_SDBC_XRESULTSET_HPP_
#include <com/sun/star/sdbc/XResultSet.hpp>
#endif
#ifndef _COM_SUN_STAR_SDBC_XROW_HPP_
#include <com/sun/star/sdbc/XRow.hpp>
#endif
#ifndef _COM_SUN_STAR_UTIL_DATETIME_HPP_
#include <com/sun/star/util/DateTime.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif

#ifndef _COMPHELPER_PROCESSFACTORY_HXX_
#include <comphelper/processfactory.hxx>
#endif
#ifndef _COMPHELPER_TYPES_HXX_
#include <comphelper/types.hxx>
#endif
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#ifndef _DATETIME_HXX
#include <tools/datetime.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _UCBHELPER_CONTENTIDENTIFIER_HXX
#include <ucbhelper/contentidentifier.hxx>
#endif
#ifndef _UCBHELPER_CONTENTBROKER_HXX
#include <ucbhelper/contentbroker.hxx>
#endif
#ifndef _UCBHELPER_CONTENT_HXX
#include <ucbhelper/content.hxx>
#endif
#include <svtools/svstdarr.hxx>

#ifndef _SWUNOHELPER_HXX
#include <swunohelper.hxx>
#endif
#ifndef _SWUNODEF_HXX
#include <swunodef.hxx>
#endif
#ifndef _ERRHDL_HXX
#include <errhdl.hxx>
#endif

namespace SWUnoHelper {

sal_Int32 GetEnumAsInt32( const UNO_NMSPC::Any& rVal )
{
    sal_Int32 eVal;
    try
    {
        eVal = comphelper::getEnumAsINT32( rVal );
    }
    catch( UNO_NMSPC::Exception & )
    {
        eVal = 0;
        ASSERT( FALSE, "can't get EnumAsInt32" );
    }
    return eVal;
}

// methods for UCB actions
BOOL UCB_DeleteFile( const String& rURL )
{
    BOOL bRemoved;
    try
    {
        ucb::Content aTempContent( rURL,
                                STAR_REFERENCE( ucb::XCommandEnvironment )());
        aTempContent.executeCommand(
                        rtl::OUString::createFromAscii( "delete" ),
                        UNO_NMSPC::makeAny( sal_Bool( sal_True ) ) );
        bRemoved = TRUE;
    }
    catch( UNO_NMSPC::Exception& )
    {
        bRemoved = FALSE;
        ASSERT( FALSE, "Exeception from executeCommand( delete )" );
    }
    return bRemoved;
}

BOOL UCB_CopyFile( const String& rURL, const String& rNewURL, BOOL bCopyIsMove )
{
    BOOL bCopyCompleted = TRUE;
    try
    {
        INetURLObject aURL( rNewURL );
        String sName( aURL.GetName() );
        aURL.removeSegment();
        String sMainURL( aURL.GetMainURL(INetURLObject::NO_DECODE) );

        ucb::Content aTempContent( sMainURL,
                                STAR_REFERENCE( ucb::XCommandEnvironment )());

        UNO_NMSPC::Any aAny;
        STAR_NMSPC::ucb::TransferInfo aInfo;
        aInfo.NameClash = STAR_NMSPC::ucb::NameClash::ERROR;
        aInfo.NewTitle = sName;
        aInfo.SourceURL = rURL;
        aInfo.MoveData = bCopyIsMove;
        aAny <<= aInfo;
        aTempContent.executeCommand(
                            rtl::OUString::createFromAscii( "transfer" ),
                            aAny );
    }
    catch( UNO_NMSPC::Exception& )
    {
        ASSERT( FALSE, "Exeception from executeCommand( transfer )" );
        bCopyCompleted = FALSE;
    }
    return bCopyCompleted;
}

BOOL UCB_IsCaseSensitiveFileName( const String& rURL )
{
    BOOL bCaseSensitive;
    try
    {
        STAR_REFERENCE( lang::XMultiServiceFactory ) xMSF =
                                    comphelper::getProcessServiceFactory();

        INetURLObject aTempObj( rURL );
        aTempObj.SetBase( aTempObj.GetBase().ToLowerAscii() );
        STAR_REFERENCE( ucb::XContentIdentifier ) xRef1 = new
                ucb::ContentIdentifier( xMSF,
                            aTempObj.GetMainURL( INetURLObject::NO_DECODE ));

        aTempObj.SetBase(aTempObj.GetBase().ToUpperAscii());
        STAR_REFERENCE( ucb::XContentIdentifier ) xRef2 = new
                ucb::ContentIdentifier( xMSF,
                            aTempObj.GetMainURL( INetURLObject::NO_DECODE ));

        STAR_REFERENCE( ucb::XContentProvider ) xProv =
                ucb::ContentBroker::get()->getContentProviderInterface();

        sal_Int32 nCompare = xProv->compareContentIds( xRef1, xRef2 );
        bCaseSensitive = 0 != nCompare;
    }
    catch( UNO_NMSPC::Exception& )
    {
        bCaseSensitive = FALSE;
        ASSERT( FALSE, "Exeception from compareContentIds()" );
    }
    return bCaseSensitive;
}

BOOL UCB_IsReadOnlyFileName( const String& rURL )
{
    BOOL bIsReadOnly = FALSE;
    try
    {
        ucb::Content aCnt( rURL, STAR_REFERENCE( ucb::XCommandEnvironment )());
        UNO_NMSPC::Any aAny = aCnt.getPropertyValue(
                            rtl::OUString::createFromAscii( "IsReadOnly" ));
        if(aAny.hasValue())
            bIsReadOnly = *(sal_Bool*)aAny.getValue();
    }
    catch( UNO_NMSPC::Exception& )
    {
        bIsReadOnly = FALSE;
    }
    return bIsReadOnly;
}

BOOL UCB_IsDirectory( const String& rURL )
{
    BOOL bExists = FALSE;
    try
    {
        ::ucb::Content aContent( rURL, STAR_REFERENCE( ucb::XCommandEnvironment )() );
        bExists = aContent.isFolder();
    }
    catch (UNO_NMSPC::Exception &)
    {
    }
    return bExists;
}

    // get a list of files from the folder of the URL
    // options: pExtension = 0 -> all, else this specific extension
    //          pDateTime != 0 -> returns also the modified date/time of
    //                       the files in a SvPtrarr -->
    //                       !! objects must be deleted from the caller!!
BOOL UCB_GetFileListOfFolder( const String& rURL, SvStrings& rList,
                                const String* pExtension,
                                SvPtrarr* pDateTimeList )
{
    BOOL bOk = FALSE;
    try
    {
        ucb::Content aCnt( rURL, STAR_REFERENCE( ucb::XCommandEnvironment )());
        STAR_REFERENCE( sdbc::XResultSet ) xResultSet;

        USHORT nSeqSize = pDateTimeList ? 2 : 1;
        UNO_NMSPC::Sequence < rtl::OUString > aProps( nSeqSize );
        rtl::OUString* pProps = aProps.getArray();
        pProps[ 0 ] = rtl::OUString::createFromAscii( "Title" );
        if( pDateTimeList )
            pProps[ 1 ] = rtl::OUString::createFromAscii( "DateModified" );

        try
        {
            xResultSet = aCnt.createCursor( aProps, ::ucb::INCLUDE_DOCUMENTS_ONLY );
        }
        catch( UNO_NMSPC::Exception& )
        {
            DBG_ERRORFILE( "create cursor failed!" );
        }

        if( xResultSet.is() )
        {
            STAR_REFERENCE( sdbc::XRow ) xRow( xResultSet, UNO_NMSPC::UNO_QUERY );
            xub_StrLen nExtLen = pExtension ? pExtension->Len() : 0;
            try
            {
                if( xResultSet->first() )
                {
                    do {
                        String sTitle( xRow->getString( 1 ) );
                        if( !nExtLen ||
                            ( sTitle.Len() > nExtLen &&
                              sTitle.Equals( *pExtension,
                                          sTitle.Len() - nExtLen, nExtLen )) )
                        {
                            String* pStr = new String( sTitle );
                            rList.Insert( pStr, rList.Count() );

                            if( pDateTimeList )
                            {
                                STAR_NMSPC::util::DateTime aStamp = xRow->getTimestamp(2);
                                ::DateTime* pDateTime = new ::DateTime(
                                        ::Date( aStamp.Day,
                                                aStamp.Month,
                                                aStamp.Year ),
                                        ::Time( aStamp.Hours,
                                                aStamp.Minutes,
                                                aStamp.Seconds,
                                                aStamp.HundredthSeconds ));
                                void* p = pDateTime;
                                pDateTimeList->Insert( p,
                                                    pDateTimeList->Count() );
                            }
                        }

                    } while( xResultSet->next() );
                }
                bOk = TRUE;
            }
            catch( UNO_NMSPC::Exception& )
            {
                DBG_ERRORFILE( "Exception caught!" );
            }
        }
    }
    catch( UNO_NMSPC::Exception& )
    {
        DBG_ERRORFILE( "Exception caught!" );
        bOk = FALSE;
    }
    return bOk;
}

}
<|endoftext|>