<commit_before>// The MIT License (MIT)

// Copyright (c) 2013-2016 Rapptz, ThePhD and contributors

// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#ifndef SOL_FUNCTION_TYPES_TEMPLATED_HPP
#define SOL_FUNCTION_TYPES_TEMPLATED_HPP

#include "call.hpp"

namespace sol {
	namespace function_detail {
		template <typename F, F fx>
		inline int call_wrapper_variable(std::false_type, lua_State* L) {
			typedef meta::bind_traits<meta::unqualified_t<F>> traits_type;
			typedef typename traits_type::args_list args_list;
			typedef meta::tuple_types<typename traits_type::return_type> return_type;
			return stack::call_into_lua(return_type(), args_list(), L, 1, fx);
		}

		template <typename R, typename V, V, typename T>
		inline int call_set_assignable(std::false_type, T&&, lua_State* L) {
			lua_pop(L, 2);
			return luaL_error(L, "cannot write to this type: copy assignment/constructor not available");
		}

		template <typename R, typename V, V variable, typename T>
		inline int call_set_assignable(std::true_type, lua_State* L, T&& mem) {
			(mem.*variable) = stack::get<R>(L, 2);
			lua_pop(L, 2);
			return 0;
		}

		template <typename R, typename V, V, typename T>
		inline int call_set_variable(std::false_type, lua_State* L, T&&) {
			lua_pop(L, 2);
			return luaL_error(L, "cannot write to a const variable");
		}

		template <typename R, typename V, V variable, typename T>
		inline int call_set_variable(std::true_type, lua_State* L, T&& mem) {
			return call_set_assignable<R, V, variable>(std::is_assignable<std::add_lvalue_reference_t<R>, R>(), L, std::forward<T>(mem));
		}

		template <typename V, V variable>
		inline int call_wrapper_variable(std::true_type, lua_State* L) {
			typedef meta::bind_traits<meta::unqualified_t<V>> traits_type;
			typedef typename traits_type::object_type T;
			typedef typename traits_type::return_type R;
			auto& mem = stack::get<T>(L, 1);
			switch (lua_gettop(L)) {
			case 1: {
				decltype(auto) r = (mem.*variable);
				lua_pop(L, 1);
				stack::push_reference(L, std::forward<decltype(r)>(r));
				return 1; }
			case 2:
				return call_set_variable<R, V, variable>(meta::neg<std::is_const<R>>(), L, mem);
			default:
				return luaL_error(L, "incorrect number of arguments to member variable function call");
			}
		}

		template <typename F, F fx>
		inline int call_wrapper_function(std::false_type, lua_State* L) {
			return call_wrapper_variable<F, fx>(std::is_member_object_pointer<F>(), L);
		}

		template <typename F, F fx>
		inline int call_wrapper_function(std::true_type, lua_State* L) {
			typedef meta::bind_traits<meta::unqualified_t<F>> traits_type;
			typedef typename traits_type::object_type T;
			typedef typename traits_type::args_list args_list;
			typedef typename traits_type::return_type return_type;
			typedef meta::tuple_types<return_type> return_type_list;
			auto mfx = [&](auto&&... args) -> typename traits_type::return_type {
				auto& member = stack::get<T>(L, 1);
				return (member.*fx)(std::forward<decltype(args)>(args)...);
			};
			int n = stack::call_into_lua<1>(return_type_list(), args_list(), L, 2, mfx);
			return n;
		}

		template <typename F, F fx>
		int call_wrapper_entry(lua_State* L) {
			return call_wrapper_function<F, fx>(std::is_member_function_pointer<meta::unqualified_t<F>>(), L);
		}

		template <typename... Fxs>
		struct c_call_matcher {
			template <typename Fx, std::size_t I, typename R, typename... Args>
			int operator()(types<Fx>, index_value<I>, types<R>, types<Args...>, lua_State* L, int, int) const {
				typedef meta::at_in_pack_t<I, Fxs...> target;
				return target::call(L);
			}
		};

	} // function_detail

	template <typename F, F fx>
	inline int c_call(lua_State* L) {
#ifdef __clang__
		return detail::trampoline(L, function_detail::call_wrapper_entry<F, fx>);
#else
		return detail::static_trampoline<(&function_detail::call_wrapper_entry<F, fx>)>(L);
#endif // fuck you clang :c
	}

	template <typename F, F f>
	struct wrap {
		typedef F type;
		typedef wrapper<F> wrapper;

		static int call(lua_State* L) {
			return c_call<type, f>(L);
		}
	};

	template <typename... Fxs>
	inline int c_call(lua_State* L) {
		if (sizeof...(Fxs) < 2) {
			return meta::at_in_pack_t<0, Fxs...>::call(L);
		}
		else {
			return call_detail::overload_match_arity<typename Fxs::type...>(function_detail::c_call_matcher<Fxs...>(), L, lua_gettop(L), 1);
		}
	}

} // sol

#endif // SOL_FUNCTION_TYPES_TEMPLATED_HPP
<commit_msg>SIGH name shadowing<commit_after>// The MIT License (MIT)

// Copyright (c) 2013-2016 Rapptz, ThePhD and contributors

// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#ifndef SOL_FUNCTION_TYPES_TEMPLATED_HPP
#define SOL_FUNCTION_TYPES_TEMPLATED_HPP

#include "call.hpp"

namespace sol {
	namespace function_detail {
		template <typename F, F fx>
		inline int call_wrapper_variable(std::false_type, lua_State* L) {
			typedef meta::bind_traits<meta::unqualified_t<F>> traits_type;
			typedef typename traits_type::args_list args_list;
			typedef meta::tuple_types<typename traits_type::return_type> return_type;
			return stack::call_into_lua(return_type(), args_list(), L, 1, fx);
		}

		template <typename R, typename V, V, typename T>
		inline int call_set_assignable(std::false_type, T&&, lua_State* L) {
			lua_pop(L, 2);
			return luaL_error(L, "cannot write to this type: copy assignment/constructor not available");
		}

		template <typename R, typename V, V variable, typename T>
		inline int call_set_assignable(std::true_type, lua_State* L, T&& mem) {
			(mem.*variable) = stack::get<R>(L, 2);
			lua_pop(L, 2);
			return 0;
		}

		template <typename R, typename V, V, typename T>
		inline int call_set_variable(std::false_type, lua_State* L, T&&) {
			lua_pop(L, 2);
			return luaL_error(L, "cannot write to a const variable");
		}

		template <typename R, typename V, V variable, typename T>
		inline int call_set_variable(std::true_type, lua_State* L, T&& mem) {
			return call_set_assignable<R, V, variable>(std::is_assignable<std::add_lvalue_reference_t<R>, R>(), L, std::forward<T>(mem));
		}

		template <typename V, V variable>
		inline int call_wrapper_variable(std::true_type, lua_State* L) {
			typedef meta::bind_traits<meta::unqualified_t<V>> traits_type;
			typedef typename traits_type::object_type T;
			typedef typename traits_type::return_type R;
			auto& mem = stack::get<T>(L, 1);
			switch (lua_gettop(L)) {
			case 1: {
				decltype(auto) r = (mem.*variable);
				lua_pop(L, 1);
				stack::push_reference(L, std::forward<decltype(r)>(r));
				return 1; }
			case 2:
				return call_set_variable<R, V, variable>(meta::neg<std::is_const<R>>(), L, mem);
			default:
				return luaL_error(L, "incorrect number of arguments to member variable function call");
			}
		}

		template <typename F, F fx>
		inline int call_wrapper_function(std::false_type, lua_State* L) {
			return call_wrapper_variable<F, fx>(std::is_member_object_pointer<F>(), L);
		}

		template <typename F, F fx>
		inline int call_wrapper_function(std::true_type, lua_State* L) {
			typedef meta::bind_traits<meta::unqualified_t<F>> traits_type;
			typedef typename traits_type::object_type T;
			typedef typename traits_type::args_list args_list;
			typedef typename traits_type::return_type return_type;
			typedef meta::tuple_types<return_type> return_type_list;
			auto mfx = [&](auto&&... args) -> typename traits_type::return_type {
				auto& member = stack::get<T>(L, 1);
				return (member.*fx)(std::forward<decltype(args)>(args)...);
			};
			int n = stack::call_into_lua<1>(return_type_list(), args_list(), L, 2, mfx);
			return n;
		}

		template <typename F, F fx>
		int call_wrapper_entry(lua_State* L) {
			return call_wrapper_function<F, fx>(std::is_member_function_pointer<meta::unqualified_t<F>>(), L);
		}

		template <typename... Fxs>
		struct c_call_matcher {
			template <typename Fx, std::size_t I, typename R, typename... Args>
			int operator()(types<Fx>, index_value<I>, types<R>, types<Args...>, lua_State* L, int, int) const {
				typedef meta::at_in_pack_t<I, Fxs...> target;
				return target::call(L);
			}
		};

	} // function_detail

	template <typename F, F fx>
	inline int c_call(lua_State* L) {
#ifdef __clang__
		return detail::trampoline(L, function_detail::call_wrapper_entry<F, fx>);
#else
		return detail::static_trampoline<(&function_detail::call_wrapper_entry<F, fx>)>(L);
#endif // fuck you clang :c
	}

	template <typename F, F f>
	struct wrap {
		typedef F type;

		static int call(lua_State* L) {
			return c_call<type, f>(L);
		}
	};

	template <typename... Fxs>
	inline int c_call(lua_State* L) {
		if (sizeof...(Fxs) < 2) {
			return meta::at_in_pack_t<0, Fxs...>::call(L);
		}
		else {
			return call_detail::overload_match_arity<typename Fxs::type...>(function_detail::c_call_matcher<Fxs...>(), L, lua_gettop(L), 1);
		}
	}

} // sol

#endif // SOL_FUNCTION_TYPES_TEMPLATED_HPP
<|endoftext|>


<commit_before>/* Copyright (c) 2012-present Advanced Micro Devices, Inc.

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE. */

#include "commandqueue.hpp"
#include "thread/monitor.hpp"
#include "device/device.hpp"
#include "platform/context.hpp"

/*!
 * \file commandQueue.cpp
 * \brief  Definitions for HostQueue object.
 *
 * \author Laurent Morichetti
 * \date   October 2008
 */

namespace amd {

HostQueue::HostQueue(Context& context, Device& device, cl_command_queue_properties properties,
                     uint queueRTCUs, Priority priority, const std::vector<uint32_t>& cuMask)
    : CommandQueue(context, device, properties, device.info().queueProperties_, queueRTCUs,
                   priority, cuMask),
      lastEnqueueCommand_(nullptr),
      head_(nullptr),
      tail_(nullptr) {
  if (AMD_DIRECT_DISPATCH) {
    // Initialize the queue
    thread_.Init(this);
  } else {
    if (thread_.state() >= Thread::INITIALIZED) {
      ScopedLock sl(queueLock_);
      thread_.start(this);
      queueLock_.wait();
    }
  }
}

bool HostQueue::terminate() {
  if (AMD_DIRECT_DISPATCH) {
    Command* marker = new Marker(*this, true);
    if (marker != nullptr) {
      marker->enqueue();
      marker->awaitCompletion();
      marker->release();
    }
    thread_.acceptingCommands_ = false;
    thread_.Release();
  } else {
    if (Os::isThreadAlive(thread_)) {
      Command* marker = nullptr;

      // Send a finish if the queue is still accepting commands.
      {
        ScopedLock sl(queueLock_);
        if (thread_.acceptingCommands_) {
          marker = new Marker(*this, false);
          if (marker != nullptr) {
            append(*marker);
            queueLock_.notify();
          }
        }
      }
      if (marker != nullptr) {
        marker->awaitCompletion();
        marker->release();
      }

      // Wake-up the command loop, so it can exit
      {
        ScopedLock sl(queueLock_);
        thread_.acceptingCommands_ = false;
        queueLock_.notify();
      }

      // FIXME_lmoriche: fix termination handshake
      while (thread_.state() < Thread::FINISHED) {
        Os::yield();
      }
    }
  }

  if (Agent::shouldPostCommandQueueEvents()) {
    Agent::postCommandQueueFree(as_cl(this->asCommandQueue()));
  }

  return true;
}

void HostQueue::finish() {
  Command* command = nullptr;
  if (IS_HIP) {
    command = getLastQueuedCommand(true);
  }
  if (nullptr == command) {
    // Send a finish to make sure we finished all commands
    command = new Marker(*this, false);
    if (command == NULL) {
      return;
    }
    ClPrint(LOG_DEBUG, LOG_CMD, "marker is queued");
    command->enqueue();
  }
  // Check HW status of the ROCcrl event. Note: not all ROCclr modes support HW status
  static constexpr bool kWaitCompletion = true;
  if (!device().IsHwEventReady(command->event(), kWaitCompletion)) {
    ClPrint(LOG_DEBUG, LOG_CMD, "HW Event not ready, awaiting completion instead");
    command->awaitCompletion();
  }
  command->release();
  if (IS_HIP) {
    ScopedLock sl(vdev()->execution());
    ScopedLock l(lastCmdLock_);
    if (lastEnqueueCommand_ != nullptr) {
      lastEnqueueCommand_->release();
      lastEnqueueCommand_ = nullptr;
    }
  }
  ClPrint(LOG_DEBUG, LOG_CMD, "All commands finished");
}

void HostQueue::loop(device::VirtualDevice* virtualDevice) {
  // Notify the caller that the queue is ready to accept commands.
  {
    ScopedLock sl(queueLock_);
    thread_.acceptingCommands_ = true;
    queueLock_.notify();
  }
  // Create a command batch with all the commands present in the queue.
  Command* head = NULL;
  Command* tail = NULL;
  while (true) {
    // Get one command from the queue
    Command* command = queue_.dequeue();
    if (command == NULL) {
      ScopedLock sl(queueLock_);
      while ((command = queue_.dequeue()) == NULL) {
        if (!thread_.acceptingCommands_) {
          return;
        }
        queueLock_.wait();
      }
    }

    command->retain();

    // Process the command's event wait list.
    const Command::EventWaitList& events = command->eventWaitList();
    bool dependencyFailed = false;

    for (const auto& it : events) {
      // Only wait if the command is enqueued into another queue.
      if (it->command().queue() != this) {
        // Runtime has to flush the current batch only if the dependent wait is blocking
        if (it->command().status() != CL_COMPLETE) {
          virtualDevice->flush(head, true);
          tail = head = NULL;
          dependencyFailed |= !it->awaitCompletion();
        }
      }
    }

    // Insert the command to the linked list.
    if (NULL == head) {  // if the list is empty
      head = tail = command;
    } else {
      tail->setNext(command);
      tail = command;
    }

    if (dependencyFailed) {
      command->setStatus(CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST);
      continue;
    }

    ClPrint(LOG_DEBUG, LOG_CMD, "command (%s) is submitted: %p", getOclCommandKindString(command->type()), command);

    command->setStatus(CL_SUBMITTED);

    // Submit to the device queue.
    command->submit(*virtualDevice);

    // if this is a user invisible marker command, then flush
    if (0 == command->type()) {
      virtualDevice->flush(head);
      tail = head = NULL;
    }
  }  // while (true) {
}

void HostQueue::append(Command& command) {
  // We retain the command here. It will be released when its status
  // changes to CL_COMPLETE
  if ((command.getWaitBits() & 0x1) != 0) {
    finish();
  }
  command.retain();
  command.setStatus(CL_QUEUED);
  queue_.enqueue(&command);
  if (!IS_HIP) {
    return;
  }

  if (command.waitingEvent() == nullptr) {
    // Set last submitted command
    Command* prevLastEnqueueCommand;
    command.retain();
    {
       // lastCmdLock_ ensures that lastEnqueueCommand() can retain the command before it is swapped
       // out. We want to keep this critical section as short as possible, so the command should be
       // released outside this section.
       ScopedLock l(lastCmdLock_);

       prevLastEnqueueCommand = lastEnqueueCommand_;
       lastEnqueueCommand_ = &command;
    }

    if (prevLastEnqueueCommand != nullptr) {
      prevLastEnqueueCommand->release();
    }
  }
}

bool HostQueue::isEmpty() {
  // Get a snapshot of queue size
  return queue_.empty();
}

Command* HostQueue::getLastQueuedCommand(bool retain) {
  if (AMD_DIRECT_DISPATCH) {
    // The batch update must be lock protected to avoid a race condition
    // when multiple threads submit/flush/update the batch at the same time
    ScopedLock sl(vdev()->execution());
    // Since the lastCmdLock_ is acquired, it is safe to read and retain the lastEnqueueCommand.
    // It is guaranteed that the pointer will not change.
    if (retain && lastEnqueueCommand_ != nullptr) {
      lastEnqueueCommand_->retain();
    }
    return lastEnqueueCommand_;
  } else {
    // Get last submitted command
    ScopedLock l(lastCmdLock_);

    // Since the lastCmdLock_ is acquired, it is safe to read and retain the lastEnqueueCommand.
    // It is guaranteed that the pointer will not change.
    if (retain && lastEnqueueCommand_ != nullptr) {
      lastEnqueueCommand_->retain();
    }
    return lastEnqueueCommand_;
  }
}

DeviceQueue::~DeviceQueue() {
  delete virtualDevice_;
  ScopedLock lock(context().lock());
  context().removeDeviceQueue(device(), this);
}

bool DeviceQueue::create() {
  static const bool InteropQueue = true;
  const bool defaultDeviceQueue = properties().test(CL_QUEUE_ON_DEVICE_DEFAULT);
  bool result = false;

  virtualDevice_ = device().createVirtualDevice(this);
  if (virtualDevice_ != NULL) {
    result = true;
    context().addDeviceQueue(device(), this, defaultDeviceQueue);
  }

  return result;
}

}  // namespace amd
<commit_msg>SWDEV-292018 - Avoid marker if queue is empty<commit_after>/* Copyright (c) 2012-present Advanced Micro Devices, Inc.

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE. */

#include "commandqueue.hpp"
#include "thread/monitor.hpp"
#include "device/device.hpp"
#include "platform/context.hpp"

/*!
 * \file commandQueue.cpp
 * \brief  Definitions for HostQueue object.
 *
 * \author Laurent Morichetti
 * \date   October 2008
 */

namespace amd {

HostQueue::HostQueue(Context& context, Device& device, cl_command_queue_properties properties,
                     uint queueRTCUs, Priority priority, const std::vector<uint32_t>& cuMask)
    : CommandQueue(context, device, properties, device.info().queueProperties_, queueRTCUs,
                   priority, cuMask),
      lastEnqueueCommand_(nullptr),
      head_(nullptr),
      tail_(nullptr) {
  if (AMD_DIRECT_DISPATCH) {
    // Initialize the queue
    thread_.Init(this);
  } else {
    if (thread_.state() >= Thread::INITIALIZED) {
      ScopedLock sl(queueLock_);
      thread_.start(this);
      queueLock_.wait();
    }
  }
}

bool HostQueue::terminate() {
  if (AMD_DIRECT_DISPATCH) {
    Command* marker = new Marker(*this, true);
    if (marker != nullptr) {
      marker->enqueue();
      marker->awaitCompletion();
      marker->release();
    }
    thread_.acceptingCommands_ = false;
    thread_.Release();
  } else {
    if (Os::isThreadAlive(thread_)) {
      Command* marker = nullptr;

      // Send a finish if the queue is still accepting commands.
      {
        ScopedLock sl(queueLock_);
        if (thread_.acceptingCommands_) {
          marker = new Marker(*this, false);
          if (marker != nullptr) {
            append(*marker);
            queueLock_.notify();
          }
        }
      }
      if (marker != nullptr) {
        marker->awaitCompletion();
        marker->release();
      }

      // Wake-up the command loop, so it can exit
      {
        ScopedLock sl(queueLock_);
        thread_.acceptingCommands_ = false;
        queueLock_.notify();
      }

      // FIXME_lmoriche: fix termination handshake
      while (thread_.state() < Thread::FINISHED) {
        Os::yield();
      }
    }
  }

  if (Agent::shouldPostCommandQueueEvents()) {
    Agent::postCommandQueueFree(as_cl(this->asCommandQueue()));
  }

  return true;
}

void HostQueue::finish() {
  Command* command = nullptr;
  if (IS_HIP) {
    command = getLastQueuedCommand(true);
    // Check if the queue has nothing to process and return
    if (command == nullptr) {
      return;
    }
  }
  if (nullptr == command) {
    // Send a finish to make sure we finished all commands
    command = new Marker(*this, false);
    if (command == NULL) {
      return;
    }
    ClPrint(LOG_DEBUG, LOG_CMD, "marker is queued");
    command->enqueue();
  }
  // Check HW status of the ROCcrl event. Note: not all ROCclr modes support HW status
  static constexpr bool kWaitCompletion = true;
  if (!device().IsHwEventReady(command->event(), kWaitCompletion)) {
    ClPrint(LOG_DEBUG, LOG_CMD, "HW Event not ready, awaiting completion instead");
    command->awaitCompletion();
  }
  command->release();
  if (IS_HIP) {
    ScopedLock sl(vdev()->execution());
    ScopedLock l(lastCmdLock_);
    if (lastEnqueueCommand_ != nullptr) {
      lastEnqueueCommand_->release();
      lastEnqueueCommand_ = nullptr;
    }
  }
  ClPrint(LOG_DEBUG, LOG_CMD, "All commands finished");
}

void HostQueue::loop(device::VirtualDevice* virtualDevice) {
  // Notify the caller that the queue is ready to accept commands.
  {
    ScopedLock sl(queueLock_);
    thread_.acceptingCommands_ = true;
    queueLock_.notify();
  }
  // Create a command batch with all the commands present in the queue.
  Command* head = NULL;
  Command* tail = NULL;
  while (true) {
    // Get one command from the queue
    Command* command = queue_.dequeue();
    if (command == NULL) {
      ScopedLock sl(queueLock_);
      while ((command = queue_.dequeue()) == NULL) {
        if (!thread_.acceptingCommands_) {
          return;
        }
        queueLock_.wait();
      }
    }

    command->retain();

    // Process the command's event wait list.
    const Command::EventWaitList& events = command->eventWaitList();
    bool dependencyFailed = false;

    for (const auto& it : events) {
      // Only wait if the command is enqueued into another queue.
      if (it->command().queue() != this) {
        // Runtime has to flush the current batch only if the dependent wait is blocking
        if (it->command().status() != CL_COMPLETE) {
          virtualDevice->flush(head, true);
          tail = head = NULL;
          dependencyFailed |= !it->awaitCompletion();
        }
      }
    }

    // Insert the command to the linked list.
    if (NULL == head) {  // if the list is empty
      head = tail = command;
    } else {
      tail->setNext(command);
      tail = command;
    }

    if (dependencyFailed) {
      command->setStatus(CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST);
      continue;
    }

    ClPrint(LOG_DEBUG, LOG_CMD, "command (%s) is submitted: %p", getOclCommandKindString(command->type()), command);

    command->setStatus(CL_SUBMITTED);

    // Submit to the device queue.
    command->submit(*virtualDevice);

    // if this is a user invisible marker command, then flush
    if (0 == command->type()) {
      virtualDevice->flush(head);
      tail = head = NULL;
    }
  }  // while (true) {
}

void HostQueue::append(Command& command) {
  // We retain the command here. It will be released when its status
  // changes to CL_COMPLETE
  if ((command.getWaitBits() & 0x1) != 0) {
    finish();
  }
  command.retain();
  command.setStatus(CL_QUEUED);
  queue_.enqueue(&command);
  if (!IS_HIP) {
    return;
  }

  if (command.waitingEvent() == nullptr) {
    // Set last submitted command
    Command* prevLastEnqueueCommand;
    command.retain();
    {
       // lastCmdLock_ ensures that lastEnqueueCommand() can retain the command before it is swapped
       // out. We want to keep this critical section as short as possible, so the command should be
       // released outside this section.
       ScopedLock l(lastCmdLock_);

       prevLastEnqueueCommand = lastEnqueueCommand_;
       lastEnqueueCommand_ = &command;
    }

    if (prevLastEnqueueCommand != nullptr) {
      prevLastEnqueueCommand->release();
    }
  }
}

bool HostQueue::isEmpty() {
  // Get a snapshot of queue size
  return queue_.empty();
}

Command* HostQueue::getLastQueuedCommand(bool retain) {
  if (AMD_DIRECT_DISPATCH) {
    // The batch update must be lock protected to avoid a race condition
    // when multiple threads submit/flush/update the batch at the same time
    ScopedLock sl(vdev()->execution());
    // Since the lastCmdLock_ is acquired, it is safe to read and retain the lastEnqueueCommand.
    // It is guaranteed that the pointer will not change.
    if (retain && lastEnqueueCommand_ != nullptr) {
      lastEnqueueCommand_->retain();
    }
    return lastEnqueueCommand_;
  } else {
    // Get last submitted command
    ScopedLock l(lastCmdLock_);

    // Since the lastCmdLock_ is acquired, it is safe to read and retain the lastEnqueueCommand.
    // It is guaranteed that the pointer will not change.
    if (retain && lastEnqueueCommand_ != nullptr) {
      lastEnqueueCommand_->retain();
    }
    return lastEnqueueCommand_;
  }
}

DeviceQueue::~DeviceQueue() {
  delete virtualDevice_;
  ScopedLock lock(context().lock());
  context().removeDeviceQueue(device(), this);
}

bool DeviceQueue::create() {
  static const bool InteropQueue = true;
  const bool defaultDeviceQueue = properties().test(CL_QUEUE_ON_DEVICE_DEFAULT);
  bool result = false;

  virtualDevice_ = device().createVirtualDevice(this);
  if (virtualDevice_ != NULL) {
    result = true;
    context().addDeviceQueue(device(), this, defaultDeviceQueue);
  }

  return result;
}

}  // namespace amd
<|endoftext|>


<commit_before>#ifndef ref_ptr_hh_INCLUDED
#define ref_ptr_hh_INCLUDED

#include <utility>

namespace Kakoune
{

struct WorstMatch { [[gnu::always_inline]] WorstMatch(...) {} };

[[gnu::always_inline]]
inline void ref_ptr_moved(WorstMatch, void*, void*) noexcept {}

template<typename T, typename TForOverload = T>
struct RefPtr
{
    RefPtr() = default;
    explicit RefPtr(T* ptr) : m_ptr(ptr) { acquire(); }
    ~RefPtr() { release(); }
    RefPtr(const RefPtr& other) : m_ptr(other.m_ptr) { acquire(); }
    RefPtr(RefPtr&& other)
        noexcept(noexcept(std::declval<RefPtr>().moved(nullptr)))
        : m_ptr(other.m_ptr) { other.m_ptr = nullptr; moved(&other); }

    RefPtr& operator=(const RefPtr& other)
    {
        release();
        m_ptr = other.m_ptr;
        acquire();
        return *this;
    }
    RefPtr& operator=(RefPtr&& other)
    {
        release();
        m_ptr = other.m_ptr;
        other.m_ptr = nullptr;
        moved(&other);
        return *this;
    }

    T* operator->() const { return m_ptr; }
    T& operator*() const { return *m_ptr; }

    T* get() const { return m_ptr; }

    explicit operator bool() const { return m_ptr; }

    void reset(T* ptr = nullptr)
    {
        if (ptr == m_ptr)
            return;
        release();
        m_ptr = ptr;
        acquire();
    }

    friend bool operator==(const RefPtr& lhs, const RefPtr& rhs) { return lhs.m_ptr == rhs.m_ptr; }
    friend bool operator!=(const RefPtr& lhs, const RefPtr& rhs) { return lhs.m_ptr != rhs.m_ptr; }

private:
    T* m_ptr = nullptr;

    void acquire()
    {
        if (m_ptr)
            inc_ref_count(static_cast<TForOverload*>(m_ptr), this);
    }

    void release()
    {
        if (m_ptr)
            dec_ref_count(static_cast<TForOverload*>(m_ptr), this);
        m_ptr = nullptr;
    }

    void moved(void* from)
        noexcept(noexcept(ref_ptr_moved(static_cast<TForOverload*>(nullptr), nullptr, nullptr)))
    {
        if (m_ptr)
            ref_ptr_moved(static_cast<TForOverload*>(m_ptr), from, this);
    }
};

}

#endif // ref_ptr_hh_INCLUDED
<commit_msg>Always inline RefPtr::{acquire,release,moved}<commit_after>#ifndef ref_ptr_hh_INCLUDED
#define ref_ptr_hh_INCLUDED

#include <utility>

namespace Kakoune
{

struct WorstMatch { [[gnu::always_inline]] WorstMatch(...) {} };

[[gnu::always_inline]]
inline void ref_ptr_moved(WorstMatch, void*, void*) noexcept {}

template<typename T, typename TForOverload = T>
struct RefPtr
{
    RefPtr() = default;
    explicit RefPtr(T* ptr) : m_ptr(ptr) { acquire(); }
    ~RefPtr() { release(); }
    RefPtr(const RefPtr& other) : m_ptr(other.m_ptr) { acquire(); }
    RefPtr(RefPtr&& other)
        noexcept(noexcept(std::declval<RefPtr>().moved(nullptr)))
        : m_ptr(other.m_ptr) { other.m_ptr = nullptr; moved(&other); }

    RefPtr& operator=(const RefPtr& other)
    {
        release();
        m_ptr = other.m_ptr;
        acquire();
        return *this;
    }
    RefPtr& operator=(RefPtr&& other)
    {
        release();
        m_ptr = other.m_ptr;
        other.m_ptr = nullptr;
        moved(&other);
        return *this;
    }

    T* operator->() const { return m_ptr; }
    T& operator*() const { return *m_ptr; }

    T* get() const { return m_ptr; }

    explicit operator bool() const { return m_ptr; }

    void reset(T* ptr = nullptr)
    {
        if (ptr == m_ptr)
            return;
        release();
        m_ptr = ptr;
        acquire();
    }

    friend bool operator==(const RefPtr& lhs, const RefPtr& rhs) { return lhs.m_ptr == rhs.m_ptr; }
    friend bool operator!=(const RefPtr& lhs, const RefPtr& rhs) { return lhs.m_ptr != rhs.m_ptr; }

private:
    T* m_ptr = nullptr;

    [[gnu::always_inline]]
    void acquire()
    {
        if (m_ptr)
            inc_ref_count(static_cast<TForOverload*>(m_ptr), this);
    }

    [[gnu::always_inline]]
    void release()
    {
        if (m_ptr)
            dec_ref_count(static_cast<TForOverload*>(m_ptr), this);
        m_ptr = nullptr;
    }

    [[gnu::always_inline]]
    void moved(void* from)
        noexcept(noexcept(ref_ptr_moved(static_cast<TForOverload*>(nullptr), nullptr, nullptr)))
    {
        if (m_ptr)
            ref_ptr_moved(static_cast<TForOverload*>(m_ptr), from, this);
    }
};

}

#endif // ref_ptr_hh_INCLUDED
<|endoftext|>


<commit_before>//=============================================================================================================
/**
* @file     test_mne_anonymize.cpp
* @author   Lorenz Esch <lorenzesch@hotmail.com>;
* @version  1.0
* @date     September, 2019
*
* @section  LICENSE
*
* Copyright (C) 2019, Lorenz Esch. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that
* the following conditions are met:
*     * Redistributions of source code must retain the above copyright notice, this list of conditions and the
*       following disclaimer.
*     * 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.
*     * Neither the name of MNE-CPP authors 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.
*
*
* @brief    Test for anonymizing a fiff raw file
*
*/

//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================

#include "../applications/mne_anonymize/fiffanonymizer.h"
#include "../applications/mne_anonymize/settingscontroller.h"

//*************************************************************************************************************
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================

#include <QtTest>
#include <QProcess>
#include <QScopedPointer>

//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================

using namespace FIFFLIB;
using namespace MNEANONYMIZE;

//=============================================================================================================
/**
* DECLARE CLASS TestMneAnonymize
*
* @brief The TestMneAnonymize class provides fiff anonymizing verification tests
*
*/
class TestMneAnonymize: public QObject
{
    Q_OBJECT

public:
    TestMneAnonymize();

private slots:
    void initTestCase();
    void compareData();
    void cleanupTestCase();

private:
    double epsilon;
};

//*************************************************************************************************************

TestMneAnonymize::TestMneAnonymize()
: epsilon(0.000001)
{
}

//*************************************************************************************************************

void TestMneAnonymize::initTestCase()
{
    // Init testing arguments
    QString sFileIn("./mne-cpp-test-data/MEG/sample/sample_audvis_raw_short.fif");
    QString sFileOut("./mne-cpp-test-data/MEG/sample/sample_audvis_raw_short_anonymized.fif");

    qInfo() << "TestMneAnonymize::initTestCase - sFileIn" << sFileIn;
    qInfo() << "TestMneAnonymize::initTestCase - sFileOut" << sFileOut;

    QStringList arguments;
    arguments << "./mne_anonymize";
    arguments << "--in" << sFileIn;
    arguments << "--out" << sFileOut;
    arguments << "--verbose";

    qInfo() << "TestMneAnonymize::initTestCase - arguments" << arguments;

    MNEANONYMIZE::SettingsController controller(arguments, "MNE Anonymize", "1.0");
}

//*************************************************************************************************************

void TestMneAnonymize::compareData()
{
    // Open anonymized file
    QFile inFile("./mne-cpp-test-data/MEG/sample/sample_audvis_raw_short_anonymized.fif");

    if(inFile.open(QIODevice::ReadOnly)) {
        qInfo() << "TestMneAnonymize::compareData - Anonymized file opened correctly " << inFile.fileName();
    } else {
        QFAIL("Anonymized file could not be loaded.");
    }

    // Create crc checksum and compare to reference
    QByteArray inData(inFile.readAll());

    quint16 crc = qChecksum(inData.data(),static_cast<uint>(inData.size()));
    qInfo() << "TestMneAnonymize::compareData - crc for anonymized file" << crc;

    QVERIFY(17542 == crc);
}

//*************************************************************************************************************

void TestMneAnonymize::cleanupTestCase()
{
}

//*************************************************************************************************************
//=============================================================================================================
// MAIN
//=============================================================================================================

QTEST_APPLESS_MAIN(TestMneAnonymize)
#include "test_mne_anonymize.moc"
<commit_msg>test mne_anonymize behaviour<commit_after>//=============================================================================================================
/**
* @file     test_mne_anonymize.cpp
* @author   Lorenz Esch <lorenzesch@hotmail.com>;
* @version  1.0
* @date     September, 2019
*
* @section  LICENSE
*
* Copyright (C) 2019, Lorenz Esch. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that
* the following conditions are met:
*     * Redistributions of source code must retain the above copyright notice, this list of conditions and the
*       following disclaimer.
*     * 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.
*     * Neither the name of MNE-CPP authors 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.
*
*
* @brief    Test for anonymizing a fiff raw file
*
*/

//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================

#include "../applications/mne_anonymize/fiffanonymizer.h"
#include "../applications/mne_anonymize/settingscontroller.h"

//*************************************************************************************************************
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================

#include <QtTest>
#include <QProcess>
#include <QScopedPointer>

//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================

using namespace FIFFLIB;
using namespace MNEANONYMIZE;

//=============================================================================================================
/**
* DECLARE CLASS TestMneAnonymize
*
* @brief The TestMneAnonymize class provides fiff anonymizing verification tests
*
*/
class TestMneAnonymize: public QObject
{
    Q_OBJECT

public:
    TestMneAnonymize();

private slots:
    //test app behaviour
    void initTestCase();
    void testDefaultOutput();
    void testDeleteInputFile();
    void testInOutSameName();
    void testInOutSameNameAndDeleteInFile();

    //test anonymization
    void testDefaultAnonymizationOfTags();

    void compareBirthdayOffsetOption();
    void cleanupTestCase();

private:
    double epsilon;
    void searchForTag(FIFFLIB::FiffStream &outStream,
                     FIFFLIB::fiff_int_t ThisKind,
                     FiffTag::SPtr inTag);
    void verifyCRC(const QString file,
                   const quint16 validatedCRC);
};

//*************************************************************************************************************

TestMneAnonymize::TestMneAnonymize()
: epsilon(0.000001)
{
}

//*************************************************************************************************************

void TestMneAnonymize::initTestCase()
{

}

//*************************************************************************************************************

void TestMneAnonymize::testDefaultOutput()
{
    // Init testing arguments
    QString sFileIn("./mne-cpp-test-data/MEG/sample/sample_audvis_raw_short.fif");
    QString sFileOut("./mne-cpp-test-data/MEG/sample/sample_audvis_raw_short_anonymized.fif");

    qInfo() << "TestMneAnonymize::initTestCase - sFileIn" << sFileIn;

    QStringList arguments;
    arguments << "./mne_anonymize";
    arguments << "--in" << sFileIn;

    qInfo() << "TestMneAnonymize::initTestCase - arguments" << arguments;

    MNEANONYMIZE::SettingsController controller(arguments, "MNE Anonymize - Testing", "1.0");

    verifyCRC(sFileOut,17542);

}

//*************************************************************************************************************

void TestMneAnonymize::testDeleteInputFile()
{
    // Init testing arguments
    QString sFileIn("./mne-cpp-test-data/MEG/sample/sample_audvis_raw_short.fif");
    QString sFileInTest("./mne-cpp-test-data/MEG/sample/testing.fif");
    QString sFileOutTest("./mne-cpp-test-data/MEG/sample/testing_filename_output.fif");

    qInfo() << "TestMneAnonymize::testDeleteInputFile - sFileIn" << sFileIn;

    QFile::copy(sFileIn,sFileInTest);
    QVERIFY(QFile::exists(sFileInTest));

    QStringList arguments;
    arguments << "./mne_anonymize";
    arguments << "--in" << sFileInTest;
    arguments << "--out" << sFileOutTest;
    arguments << "delete_input_file_after";
    arguments << "avoid_delete_confirmation";

    qInfo() << "TestMneAnonymize::initTestCase - arguments" << arguments;

    MNEANONYMIZE::SettingsController controller(arguments, "MNE Anonymize - Testing", "1.0");

    QVERIFY(!QFile::exists(sFileInTest )); //delete input file, remember?
    QVERIFY( QFile::exists(sFileOutTest));

    verifyCRC(sFileOutTest,17542);
}

//*************************************************************************************************************

void TestMneAnonymize::testInOutSameName()
{
    // Init testing arguments
    QString sFileIn("./mne-cpp-test-data/MEG/sample/sample_audvis_raw_short.fif");
    QString sFileInTest("./mne-cpp-test-data/MEG/sample/testing.fif");
    QString sFileOutTest("./mne-cpp-test-data/MEG/sample/testing.fif");

    qInfo() << "TestMneAnonymize::testInOutSameName - sFileIn" << sFileIn;

    QFile::copy(sFileIn,sFileInTest);
    QVERIFY(QFile::exists(sFileInTest));

    QStringList arguments;
    arguments << "./mne_anonymize";
    arguments << "--in" << sFileInTest;
    arguments << "--out" << sFileOutTest;

    qInfo() << "TestMneAnonymize::testInOutSameName - arguments" << arguments;

    MNEANONYMIZE::SettingsController controller(arguments, "MNE Anonymize - Testing", "1.0");

    QVERIFY( QFile::exists(sFileOutTest));

    verifyCRC(sFileOutTest,17542);
}

//*************************************************************************************************************

void TestMneAnonymize::testInOutSameNameAndDeleteInFile()
{
    // Init testing arguments
    QString sFileIn("./mne-cpp-test-data/MEG/sample/sample_audvis_raw_short.fif");
    QString sFileInTest("./mne-cpp-test-data/MEG/sample/testing.fif");
    QString sFileOutTest("./mne-cpp-test-data/MEG/sample/testing.fif");

    qInfo() << "TestMneAnonymize::testInOutSameNameAndDelete - sFileIn" << sFileIn;

    QFile::copy(sFileIn,sFileInTest);
    QVERIFY(QFile::exists(sFileInTest));

    QStringList arguments;
    arguments << "./mne_anonymize";
    arguments << "--in" << sFileInTest;
    arguments << "--out" << sFileOutTest;
    arguments << "delete_input_file_after";
    arguments << "avoid_delete_confirmation";

    qInfo() << "TestMneAnonymize::testInOutSameNameAndDelete - arguments" << arguments;

    MNEANONYMIZE::SettingsController controller(arguments, "MNE Anonymize - Testing", "1.0");

    QVERIFY( QFile::exists(sFileOutTest));

    verifyCRC(sFileOutTest,17542);
}

//*************************************************************************************************************

void TestMneAnonymize::testDefaultAnonymizationOfTags()
{
    QString sFileIn("./mne-cpp-test-data/MEG/sample/sample_audvis_raw_short.fif");
    QString sFileOut("./mne-cpp-test-data/MEG/sample/sample_audvis_raw_short_anonymized.fif");
    qInfo() << "TestMneAnonymize::testDefaultAnonymizationOfTags - sFileIn" << sFileIn;

    QStringList arguments;
    arguments << "./mne_anonymize";
    arguments << "--in" << sFileIn;

    qInfo() << "TestMneAnonymize::testDefaultAnonymizationOfTags - arguments" << arguments;

    MNEANONYMIZE::SettingsController controller(arguments, "MNE Anonymize", "1.0");

    QFile fFileIn(sFileIn);
    FIFFLIB::FiffStream inStream(&fFileIn);
    if(inStream.open(QIODevice::ReadOnly))
    {
        qInfo() << "TestMneAnonymize::testDefaultAnonymizationOfTags - Input file opened correctly " << sFileIn;
    } else {
        QFAIL("Input file could not be loaded.");
    }

    QFile fFileOut(sFileOut);
    FIFFLIB::FiffStream outStream(&fFileOut);
    if(outStream.open(QIODevice::ReadOnly))
    {
        qInfo() << "TestMneAnonymize::testDefaultAnonymizationOfTags - output file opened correctly " << sFileIn;
    } else {
        QFAIL("Output file could not be loaded.");
    }

    FiffTag::SPtr pTag = FiffTag::SPtr::create();
    searchForTag(inStream,FIFF_FILE_ID,pTag);

}

//*************************************************************************************************************

void TestMneAnonymize::compareBirthdayOffsetOption()
{
    // Init testing arguments
    QString sFileIn("./mne-cpp-test-data/MEG/sample/sample_audvis_raw_short.fif");
    QString sFileOut("./mne-cpp-test-data/MEG/sample/sample_audvis_raw_short_anonymized.fif");

    qInfo() << "TestMneAnonymize::initTestCase - sFileIn" << sFileIn;
    qInfo() << "TestMneAnonymize::initTestCase - sFileOut" << sFileOut;

    QStringList arguments;
    arguments << "./mne_anonymize";
    arguments << "--in" << sFileIn;
    arguments << "--verbose";

    qInfo() << "TestMneAnonymize::initTestCase - arguments" << arguments;

    MNEANONYMIZE::SettingsController controller(arguments, "MNE Anonymize", "1.0");

}

//*************************************************************************************************************

void TestMneAnonymize::cleanupTestCase()
{

}

//*************************************************************************************************************

void TestMneAnonymize::verifyCRC(const QString file,
                                 const quint16 validatedCRC)
{
    QFile fFileIn(file);

    if(fFileIn.open(QIODevice::ReadOnly)) {
        qInfo() << "TestMneAnonymize::verifyCRC - Anonymized file opened correctly " << fFileIn.fileName();
    } else {
        QFAIL("Anonymized file could not be loaded.");
    }

    // Create crc checksum and compare to reference
    QByteArray inData(fFileIn.readAll());
    fFileIn.close();

    quint16 crc = qChecksum(inData.data(),static_cast<uint>(inData.size()));
    qInfo() << "TestMneAnonymize::compareData - crc expected value: " << validatedCRC;
    qInfo() << "TestMneAnonymize::compareData - crc obtained value:" << crc;

    QVERIFY(validatedCRC == crc);
}

//*************************************************************************************************************

void TestMneAnonymize::searchForTag(FIFFLIB::FiffStream &stream,
                                   FIFFLIB::fiff_int_t thisKind,
                                   FiffTag::SPtr pTag)
{
    stream.device()->seek(0);
    do
    {
        stream.read_tag(pTag);
    }while(pTag->kind != thisKind);
}

//=============================================================================================================
// MAIN
//=============================================================================================================

QTEST_APPLESS_MAIN(TestMneAnonymize)
#include "test_mne_anonymize.moc"

<|endoftext|>


<commit_before>//===-- ValueObjectChild.cpp ------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "lldb/Core/ValueObjectChild.h"

#include "lldb/Core/Module.h"
#include "lldb/Core/ValueObjectList.h"

#include "lldb/Symbol/CompilerType.h"
#include "lldb/Symbol/ObjectFile.h"
#include "lldb/Symbol/SymbolContext.h"
#include "lldb/Symbol/Type.h"
#include "lldb/Symbol/Variable.h"

#include "lldb/Target/ExecutionContext.h"
#include "lldb/Target/Process.h"
#include "lldb/Target/Target.h"

using namespace lldb_private;

ValueObjectChild::ValueObjectChild
(
    ValueObject &parent,
    const CompilerType &compiler_type,
    const ConstString &name,
    uint64_t byte_size,
    int32_t byte_offset,
    uint32_t bitfield_bit_size,
    uint32_t bitfield_bit_offset,
    bool is_base_class,
    bool is_deref_of_parent,
    AddressType child_ptr_or_ref_addr_type,
    uint64_t language_flags
) :
    ValueObject (parent),
    m_compiler_type (compiler_type),
    m_byte_size (byte_size),
    m_byte_offset (byte_offset),
    m_bitfield_bit_size (bitfield_bit_size),
    m_bitfield_bit_offset (bitfield_bit_offset),
    m_is_base_class (is_base_class),
    m_is_deref_of_parent (is_deref_of_parent),
    m_can_update_with_invalid_exe_ctx()
{
    m_name = name;
    SetAddressTypeOfChildren(child_ptr_or_ref_addr_type);
    SetLanguageFlags(language_flags);
}

ValueObjectChild::~ValueObjectChild()
{
}

lldb::ValueType
ValueObjectChild::GetValueType() const
{
    return m_parent->GetValueType();
}

size_t
ValueObjectChild::CalculateNumChildren(uint32_t max)
{
    auto children_count = GetCompilerType().GetNumChildren (true);
    return children_count <= max ? children_count : max;
}

static void
AdjustForBitfieldness(ConstString& name,
                      uint8_t bitfield_bit_size)
{
    if (name && bitfield_bit_size)
    {
        const char *compiler_type_name = name.AsCString();
        if (compiler_type_name)
        {
            std::vector<char> bitfield_type_name (strlen(compiler_type_name) + 32, 0);
            ::snprintf (&bitfield_type_name.front(), bitfield_type_name.size(), "%s:%u", compiler_type_name, bitfield_bit_size);
            name.SetCString(&bitfield_type_name.front());
        }
    }
}

ConstString
ValueObjectChild::GetTypeName()
{
    if (m_type_name.IsEmpty())
    {
        m_type_name = GetCompilerType().GetConstTypeName ();
        AdjustForBitfieldness(m_type_name, m_bitfield_bit_size);
    }
    return m_type_name;
}

ConstString
ValueObjectChild::GetQualifiedTypeName()
{
    ConstString qualified_name = GetCompilerType().GetConstTypeName();
    AdjustForBitfieldness(qualified_name, m_bitfield_bit_size);
    return qualified_name;
}

ConstString
ValueObjectChild::GetDisplayTypeName()
{
    ConstString display_name = GetCompilerType().GetDisplayTypeName();
    AdjustForBitfieldness(display_name, m_bitfield_bit_size);
    return display_name;
}

LazyBool
ValueObjectChild::CanUpdateWithInvalidExecutionContext ()
{
    if (m_can_update_with_invalid_exe_ctx.hasValue())
        return m_can_update_with_invalid_exe_ctx.getValue();
    if (m_parent)
    {
        ValueObject *opinionated_parent = m_parent->FollowParentChain([] (ValueObject* valobj) -> bool {
            return (valobj->CanUpdateWithInvalidExecutionContext() == eLazyBoolCalculate);
        });
        if (opinionated_parent)
            return (m_can_update_with_invalid_exe_ctx = opinionated_parent->CanUpdateWithInvalidExecutionContext()).getValue();
    }
    return (m_can_update_with_invalid_exe_ctx = this->ValueObject::CanUpdateWithInvalidExecutionContext()).getValue();
}

bool
ValueObjectChild::UpdateValue ()
{
    m_error.Clear();
    SetValueIsValid (false);
    ValueObject* parent = m_parent;
    if (parent)
    {
        if (parent->UpdateValueIfNeeded(false))
        {
            m_value.SetCompilerType(GetCompilerType());

            // Copy the parent scalar value and the scalar value type
            m_value.GetScalar() = parent->GetValue().GetScalar();
            Value::ValueType value_type = parent->GetValue().GetValueType();
            m_value.SetValueType (value_type);

            if (parent->GetCompilerType().ShouldTreatScalarValueAsAddress())
            {
                lldb::addr_t addr = parent->GetPointerValue ();
                m_value.GetScalar() = addr;

                if (addr == LLDB_INVALID_ADDRESS)
                {
                    m_error.SetErrorString ("parent address is invalid.");
                }
                else if (addr == 0)
                {
                    m_error.SetErrorString ("parent is NULL");
                }
                else
                {
                    m_value.GetScalar() += m_byte_offset;
                    AddressType addr_type = parent->GetAddressTypeOfChildren();

                    switch (addr_type)
                    {
                        case eAddressTypeFile:
                            {
                                lldb::ProcessSP process_sp (GetProcessSP());
                                if (process_sp && process_sp->IsAlive() == true)
                                    m_value.SetValueType (Value::eValueTypeLoadAddress);
                                else
                                    m_value.SetValueType(Value::eValueTypeFileAddress);
                            }
                            break;
                        case eAddressTypeLoad:
                            m_value.SetValueType (Value::eValueTypeLoadAddress);
                            break;
                        case eAddressTypeHost:
                            m_value.SetValueType(Value::eValueTypeHostAddress);
                            break;
                        case eAddressTypeInvalid:
                            // TODO: does this make sense?
                            m_value.SetValueType(Value::eValueTypeScalar);
                            break;
                    }
                }
            }
            else
            {
                switch (value_type)
                {
                case Value::eValueTypeLoadAddress:
                case Value::eValueTypeFileAddress:
                case Value::eValueTypeHostAddress:
                    {
                        lldb::addr_t addr = m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
                        if (addr == LLDB_INVALID_ADDRESS)
                        {
                            m_error.SetErrorString ("parent address is invalid.");
                        }
                        else if (addr == 0)
                        {
                            m_error.SetErrorString ("parent is NULL");
                        }
                        else
                        {
                            // Set this object's scalar value to the address of its
                            // value by adding its byte offset to the parent address
                            m_value.GetScalar() += GetByteOffset();
                        }
                    }
                    break;

                case Value::eValueTypeScalar:
                    // TODO: What if this is a register value? Do we try and
                    // extract the child value from within the parent data?
                    // Probably...
                default:
                    m_error.SetErrorString ("parent has invalid value.");
                    break;
                }
            }

            if (m_error.Success())
            {
                const bool thread_and_frame_only_if_stopped = true;
                ExecutionContext exe_ctx (GetExecutionContextRef().Lock(thread_and_frame_only_if_stopped));
                if (GetCompilerType().GetTypeInfo() & lldb::eTypeHasValue)
                    m_error = m_value.GetValueAsData (&exe_ctx, m_data, 0, GetModule().get());
                else
                    m_error.Clear(); // No value so nothing to read...
            }
        }
        else
        {
            m_error.SetErrorStringWithFormat("parent failed to evaluate: %s", parent->GetError().AsCString());
        }
    }
    else
    {
        m_error.SetErrorString("ValueObjectChild has a NULL parent ValueObject.");
    }

    return m_error.Success();
}

bool
ValueObjectChild::IsInScope ()
{
    ValueObject* root(GetRoot());
    if (root)
        return root->IsInScope ();
    return false;
}
<commit_msg>More rework of the updating logic for ValueObjectChild. Still just refactoring with no feature change<commit_after>//===-- ValueObjectChild.cpp ------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "lldb/Core/ValueObjectChild.h"

#include "lldb/Core/Module.h"
#include "lldb/Core/ValueObjectList.h"

#include "lldb/Symbol/CompilerType.h"
#include "lldb/Symbol/ObjectFile.h"
#include "lldb/Symbol/SymbolContext.h"
#include "lldb/Symbol/Type.h"
#include "lldb/Symbol/Variable.h"

#include "lldb/Target/ExecutionContext.h"
#include "lldb/Target/Process.h"
#include "lldb/Target/Target.h"

using namespace lldb_private;

ValueObjectChild::ValueObjectChild
(
    ValueObject &parent,
    const CompilerType &compiler_type,
    const ConstString &name,
    uint64_t byte_size,
    int32_t byte_offset,
    uint32_t bitfield_bit_size,
    uint32_t bitfield_bit_offset,
    bool is_base_class,
    bool is_deref_of_parent,
    AddressType child_ptr_or_ref_addr_type,
    uint64_t language_flags
) :
    ValueObject (parent),
    m_compiler_type (compiler_type),
    m_byte_size (byte_size),
    m_byte_offset (byte_offset),
    m_bitfield_bit_size (bitfield_bit_size),
    m_bitfield_bit_offset (bitfield_bit_offset),
    m_is_base_class (is_base_class),
    m_is_deref_of_parent (is_deref_of_parent),
    m_can_update_with_invalid_exe_ctx()
{
    m_name = name;
    SetAddressTypeOfChildren(child_ptr_or_ref_addr_type);
    SetLanguageFlags(language_flags);
}

ValueObjectChild::~ValueObjectChild()
{
}

lldb::ValueType
ValueObjectChild::GetValueType() const
{
    return m_parent->GetValueType();
}

size_t
ValueObjectChild::CalculateNumChildren(uint32_t max)
{
    auto children_count = GetCompilerType().GetNumChildren (true);
    return children_count <= max ? children_count : max;
}

static void
AdjustForBitfieldness(ConstString& name,
                      uint8_t bitfield_bit_size)
{
    if (name && bitfield_bit_size)
    {
        const char *compiler_type_name = name.AsCString();
        if (compiler_type_name)
        {
            std::vector<char> bitfield_type_name (strlen(compiler_type_name) + 32, 0);
            ::snprintf (&bitfield_type_name.front(), bitfield_type_name.size(), "%s:%u", compiler_type_name, bitfield_bit_size);
            name.SetCString(&bitfield_type_name.front());
        }
    }
}

ConstString
ValueObjectChild::GetTypeName()
{
    if (m_type_name.IsEmpty())
    {
        m_type_name = GetCompilerType().GetConstTypeName ();
        AdjustForBitfieldness(m_type_name, m_bitfield_bit_size);
    }
    return m_type_name;
}

ConstString
ValueObjectChild::GetQualifiedTypeName()
{
    ConstString qualified_name = GetCompilerType().GetConstTypeName();
    AdjustForBitfieldness(qualified_name, m_bitfield_bit_size);
    return qualified_name;
}

ConstString
ValueObjectChild::GetDisplayTypeName()
{
    ConstString display_name = GetCompilerType().GetDisplayTypeName();
    AdjustForBitfieldness(display_name, m_bitfield_bit_size);
    return display_name;
}

LazyBool
ValueObjectChild::CanUpdateWithInvalidExecutionContext ()
{
    if (m_can_update_with_invalid_exe_ctx.hasValue())
        return m_can_update_with_invalid_exe_ctx.getValue();
    if (m_parent)
    {
        ValueObject *opinionated_parent = m_parent->FollowParentChain([] (ValueObject* valobj) -> bool {
            return (valobj->CanUpdateWithInvalidExecutionContext() == eLazyBoolCalculate);
        });
        if (opinionated_parent)
            return (m_can_update_with_invalid_exe_ctx = opinionated_parent->CanUpdateWithInvalidExecutionContext()).getValue();
    }
    return (m_can_update_with_invalid_exe_ctx = this->ValueObject::CanUpdateWithInvalidExecutionContext()).getValue();
}

bool
ValueObjectChild::UpdateValue ()
{
    m_error.Clear();
    SetValueIsValid (false);
    ValueObject* parent = m_parent;
    if (parent)
    {
        if (parent->UpdateValueIfNeeded(false))
        {
            m_value.SetCompilerType(GetCompilerType());

            CompilerType parent_type(parent->GetCompilerType());
            // Copy the parent scalar value and the scalar value type
            m_value.GetScalar() = parent->GetValue().GetScalar();
            Value::ValueType value_type = parent->GetValue().GetValueType();
            m_value.SetValueType (value_type);

            Flags parent_type_flags(parent_type.GetTypeInfo());
            const bool is_instance_ptr_base = ((m_is_base_class == true) && (parent_type_flags.AnySet(lldb::eTypeInstanceIsPointer)));

            if (parent->GetCompilerType().ShouldTreatScalarValueAsAddress())
            {
                lldb::addr_t addr = parent->GetPointerValue ();
                m_value.GetScalar() = addr;

                if (addr == LLDB_INVALID_ADDRESS)
                {
                    m_error.SetErrorString ("parent address is invalid.");
                }
                else if (addr == 0)
                {
                    m_error.SetErrorString ("parent is NULL");
                }
                else
                {
                    m_value.GetScalar() += m_byte_offset;
                    AddressType addr_type = parent->GetAddressTypeOfChildren();

                    switch (addr_type)
                    {
                        case eAddressTypeFile:
                        {
                            lldb::ProcessSP process_sp (GetProcessSP());
                            if (process_sp && process_sp->IsAlive() == true)
                                m_value.SetValueType (Value::eValueTypeLoadAddress);
                            else
                                m_value.SetValueType(Value::eValueTypeFileAddress);
                        }
                            break;
                        case eAddressTypeLoad:
                            m_value.SetValueType (is_instance_ptr_base ? Value::eValueTypeScalar: Value::eValueTypeLoadAddress);
                            break;
                        case eAddressTypeHost:
                            m_value.SetValueType(Value::eValueTypeHostAddress);
                            break;
                        case eAddressTypeInvalid:
                            // TODO: does this make sense?
                            m_value.SetValueType(Value::eValueTypeScalar);
                            break;
                    }
                }
            }
            else
            {
                switch (value_type)
                {
                    case Value::eValueTypeLoadAddress:
                    case Value::eValueTypeFileAddress:
                    case Value::eValueTypeHostAddress:
                    {
                        lldb::addr_t addr = m_value.GetScalar().ULongLong(LLDB_INVALID_ADDRESS);
                        if (addr == LLDB_INVALID_ADDRESS)
                        {
                            m_error.SetErrorString ("parent address is invalid.");
                        }
                        else if (addr == 0)
                        {
                            m_error.SetErrorString ("parent is NULL");
                        }
                        else
                        {
                            // Set this object's scalar value to the address of its
                            // value by adding its byte offset to the parent address
                            m_value.GetScalar() += GetByteOffset();
                        }
                    }
                        break;

                    case Value::eValueTypeScalar:
                        // try to extract the child value from the parent's scalar value
                    {
                        Scalar scalar(m_value.GetScalar());
                        if (m_bitfield_bit_size)
                            scalar.ExtractBitfield(m_bitfield_bit_size, m_bitfield_bit_offset);
                        else
                            scalar.ExtractBitfield(8*m_byte_size, 8*m_byte_offset);
                        m_value.GetScalar() = scalar;
                    }
                        break;
                    default:
                        m_error.SetErrorString ("parent has invalid value.");
                        break;
                }
            }

            if (m_error.Success())
            {
                const bool thread_and_frame_only_if_stopped = true;
                ExecutionContext exe_ctx (GetExecutionContextRef().Lock(thread_and_frame_only_if_stopped));
                if (GetCompilerType().GetTypeInfo() & lldb::eTypeHasValue)
                {
                    if (!is_instance_ptr_base)
                        m_error = m_value.GetValueAsData (&exe_ctx, m_data, 0, GetModule().get());
                    else
                        m_error = m_parent->GetValue().GetValueAsData (&exe_ctx, m_data, 0, GetModule().get());
                }
                else
                {
                    m_error.Clear(); // No value so nothing to read...
                }
            }

        }
        else
        {
            m_error.SetErrorStringWithFormat("parent failed to evaluate: %s", parent->GetError().AsCString());
        }
    }
    else
    {
        m_error.SetErrorString("ValueObjectChild has a NULL parent ValueObject.");
    }

    return m_error.Success();
}

bool
ValueObjectChild::IsInScope ()
{
    ValueObject* root(GetRoot());
    if (root)
        return root->IsInScope ();
    return false;
}
<|endoftext|>


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

#include "config.h"

#include <objidl.h>

#pragma warning(push, 0)
#include "ClipboardWin.h"
#include "COMPtr.h"
#include "DragData.h"
#include "Frame.h"
#include "HitTestResult.h"
#include "Image.h"
#include "KURL.h"
#pragma warning(pop)
#undef LOG

#include "webkit/glue/dragclient_impl.h"

#include "base/logging.h"
#include "base/string_util.h"
#include "webkit/glue/context_node_types.h"
#include "webkit/glue/glue_util.h"
#include "webkit/glue/webdropdata.h"
#include "webkit/glue/webview_delegate.h"
#include "webkit/glue/webview_impl.h"

void DragClientImpl::willPerformDragDestinationAction(
    WebCore::DragDestinationAction,
    WebCore::DragData*) {
  // FIXME
}

void DragClientImpl::willPerformDragSourceAction(
    WebCore::DragSourceAction,
    const WebCore::IntPoint&,
    WebCore::Clipboard*) {
  // FIXME
}

WebCore::DragDestinationAction DragClientImpl::actionMaskForDrag(
    WebCore::DragData*) {
  return WebCore::DragDestinationActionAny;
}

WebCore::DragSourceAction DragClientImpl::dragSourceActionMaskForPoint(
    const WebCore::IntPoint& window_point) {
  // We want to handle drag operations for all source types.
  return WebCore::DragSourceActionAny;
}

void DragClientImpl::startDrag(WebCore::DragImageRef drag_image,
                               const WebCore::IntPoint& drag_image_origin,
                               const WebCore::IntPoint& event_pos,
                               WebCore::Clipboard* clipboard,
                               WebCore::Frame* frame,
                               bool is_link_drag) {
  // Add a ref to the frame just in case a load occurs mid-drag.
  RefPtr<WebCore::Frame> frame_protector = frame;

  COMPtr<IDataObject> data_object(
      static_cast<WebCore::ClipboardWin*>(clipboard)->dataObject());
  DCHECK(data_object.get());
  WebDropData drop_data;
  WebDropData::PopulateWebDropData(data_object.get(), &drop_data);

  webview_->StartDragging(drop_data);
}

WebCore::DragImageRef DragClientImpl::createDragImageForLink(
    WebCore::KURL&,
    const WebCore::String& label,
    WebCore::Frame*) {
  // FIXME
  return 0;
}

void DragClientImpl::dragControllerDestroyed() {
  delete this;
}

<commit_msg>ifdef around windows code Review URL: http://codereview.chromium.org/249<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "config.h"

#include "build/build_config.h"

#if defined(OS_WIN)
#include <objidl.h>
#endif

#pragma warning(push, 0)
#if defined(OS_WIN)
#include "ClipboardWin.h"
#include "COMPtr.h"
#endif
#include "DragData.h"
#include "Frame.h"
#include "HitTestResult.h"
#include "Image.h"
#include "KURL.h"
#pragma warning(pop)
#undef LOG

#include "webkit/glue/dragclient_impl.h"

#include "base/logging.h"
#include "base/string_util.h"
#include "webkit/glue/context_node_types.h"
#include "webkit/glue/glue_util.h"
#include "webkit/glue/webdropdata.h"
#include "webkit/glue/webview_delegate.h"
#include "webkit/glue/webview_impl.h"

void DragClientImpl::willPerformDragDestinationAction(
    WebCore::DragDestinationAction,
    WebCore::DragData*) {
  // FIXME
}

void DragClientImpl::willPerformDragSourceAction(
    WebCore::DragSourceAction,
    const WebCore::IntPoint&,
    WebCore::Clipboard*) {
  // FIXME
}

WebCore::DragDestinationAction DragClientImpl::actionMaskForDrag(
    WebCore::DragData*) {
  return WebCore::DragDestinationActionAny;
}

WebCore::DragSourceAction DragClientImpl::dragSourceActionMaskForPoint(
    const WebCore::IntPoint& window_point) {
  // We want to handle drag operations for all source types.
  return WebCore::DragSourceActionAny;
}

void DragClientImpl::startDrag(WebCore::DragImageRef drag_image,
                               const WebCore::IntPoint& drag_image_origin,
                               const WebCore::IntPoint& event_pos,
                               WebCore::Clipboard* clipboard,
                               WebCore::Frame* frame,
                               bool is_link_drag) {
  // Add a ref to the frame just in case a load occurs mid-drag.
  RefPtr<WebCore::Frame> frame_protector = frame;

#if defined(OS_WIN)
  COMPtr<IDataObject> data_object(
      static_cast<WebCore::ClipboardWin*>(clipboard)->dataObject());
  DCHECK(data_object.get());
  WebDropData::PopulateWebDropData(data_object.get(), &drop_data);
#elif defined(OS_MACOSX) || defined(OS_LINUX)
  WebDropData drop_data;
#endif

  webview_->StartDragging(drop_data);
}

WebCore::DragImageRef DragClientImpl::createDragImageForLink(
    WebCore::KURL&,
    const WebCore::String& label,
    WebCore::Frame*) {
  // FIXME
  return 0;
}

void DragClientImpl::dragControllerDestroyed() {
  delete this;
}

<|endoftext|>


<commit_before>// $Id: LineBasedFile_test.C,v 1.9 2000/10/19 20:04:04 amoll Exp $
#include <BALL/CONCEPT/classTest.h>

///////////////////////////
#include <BALL/FORMAT/lineBasedFile.h>
///////////////////////////

START_TEST(class_name, "$Id: LineBasedFile_test.C,v 1.9 2000/10/19 20:04:04 amoll Exp $")

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

using namespace BALL;

CHECK(BALL_CREATE(LineBasedFile))
  //BAUSTELLE
RESULT

LineBasedFile* fl;

CHECK(LineBasedFile() throw())
	fl = new LineBasedFile;
	TEST_NOT_EQUAL(fl, 0)
RESULT

CHECK(~LineBasedFile() throw())
	delete fl;
RESULT

CHECK(LineBasedFile(const String& filename, File::OpenMode open_mode = File::IN)
			throw(Exception::FileNotFound))
	LineBasedFile f1("data/LineBasedFile_test.txt");
	TEST_EQUAL(f1.getLineNumber(), 0)
	TEST_EQUAL(f1.getLine(), "")
	f1.readLine();
	TEST_EQUAL(f1.getLineNumber(), 1)
	TEST_EQUAL(f1.getLine(), "line1")

	TEST_EXCEPTION(Exception::FileNotFound, LineBasedFile f2("XXXXXXXX.txt"))
RESULT

LineBasedFile fx;

CHECK(LineBasedFile(const LineBasedFile& f) throw())
	LineBasedFile f1("data/LineBasedFile_test.txt");
	TEST_EQUAL(f1.readLine(), true)
	TEST_EQUAL(f1.getLine(), "line1")
	f1.close();

	LineBasedFile f2(f1);
	TEST_EQUAL(f2.getLineNumber(), 1)
	TEST_EQUAL(f2.getLine(), "line1")
	TEST_EQUAL(f2.readLine(), true)
	TEST_EQUAL(f2.getLine(), "/0/ /1/ /2 2//3/")

	LineBasedFile f3;
	LineBasedFile f4(f3);
RESULT

CHECK(LineBasedFile& operator = (const LineBasedFile& file) throw())
	LineBasedFile f1("data/LineBasedFile_test.txt");
	f1.readLine();
	TEST_EQUAL(f1.getLine(), "line1")

	LineBasedFile f2;
	f2 = f1;
	TEST_EQUAL(f2.getLineNumber(), 1)
	TEST_EQUAL(f2.getLine(), "line1")
RESULT

CHECK(clear() throw())
	LineBasedFile f1("data/LineBasedFile_test.txt");
	f1.readLine();
	f1.clear();
	TEST_EQUAL(f1.getLineNumber(), 0)
	TEST_EQUAL(f1.getLine(), "")

	fx.clear();
RESULT

CHECK(getLineNumber() const  throw())
	LineBasedFile f1("data/LineBasedFile_test.txt");
	TEST_EQUAL(f1.getLineNumber(), 0)
	f1.readLine();
	TEST_EQUAL(f1.getLineNumber(), 1)

	TEST_EQUAL(fx.getLineNumber(), 0)
RESULT

LineBasedFile f1("data/LineBasedFile_test.txt");

CHECK(getLine() const  throw())
	TEST_EQUAL(f1.getLine(), "")
	f1.readLine();
	TEST_EQUAL(f1.getLine(), "line1")

	TEST_EQUAL(fx.getLine(), "")
RESULT

CHECK(getField(Position pos = 0, const String& quotes = "",
			const String& delimiters = String::CHARACTER_CLASS__WHITESPACE)
			const  throw(Exception::IndexUnderflow))

	TEST_EQUAL(f1.getField(), "line1")
	TEST_EQUAL(f1.getField(1), "")
	TEST_EXCEPTION(Exception::IndexUnderflow, f1.getField(-99))
	f1.readLine();
	TEST_EQUAL(f1.getField(), "/0/")
	TEST_EQUAL(f1.getField(1), "/1/")
	TEST_EQUAL(f1.getField(2), "/2")
	TEST_EQUAL(f1.getField(0, "/"), "0")
	TEST_EQUAL(f1.getField(1, "/"), "1")
	TEST_EQUAL(f1.getField(2, "/"), "2 23")
	TEST_EQUAL(f1.getField(3, "/"), "")

	TEST_EQUAL(fx.getField(), "")
RESULT

CHECK(startsWith(const String& text) const  throw())
	TEST_EQUAL(f1.startsWith("/0/"), true)
	TEST_EQUAL(f1.startsWith("/0/ /1/ /2 2//3/"), true)
	TEST_EQUAL(f1.startsWith("/0/ /1/ /2 2//3/X"), false)

	TEST_EQUAL(fx.startsWith(""), true)
RESULT

CHECK(has(const String& text) const  throw())
	TEST_EQUAL(f1.has("/0/"), true)
	TEST_EQUAL(f1.has("/"), true)
	TEST_EQUAL(f1.has("/1/"), true)
	TEST_EQUAL(f1.has("/3/"), true)
	TEST_EQUAL(f1.has("X"), false)

	TEST_EQUAL(fx.has("X"), false)
	TEST_EQUAL(fx.has(""), true)
RESULT

CHECK(search(const String& text, bool return_to_point) throw())
	TEST_EQUAL(f1.search("line3"), true)
	TEST_EQUAL(f1.search("line4-"), true)
	TEST_EQUAL(f1.search("line4-"), false)
	TEST_EQUAL(f1.getLine(), "line7-")
  f1.rewind();

	f1.skipLines(2);
	TEST_EQUAL(f1.getLine(), "line3-")
	TEST_EQUAL(f1.search("XXX", true), false)
	TEST_EQUAL(f1.getLine(), "line3-")

  f1.rewind();
	TEST_EQUAL(f1.search("#"), true)
	TEST_EQUAL(f1.getLine(), "###########")

	TEST_EXCEPTION(LineBasedFile::LineBasedFileError, fx.search("line4-"))
RESULT

CHECK(search(const String& text, const String& stop, bool return_to_point) throw())
  f1.rewind();
	TEST_EQUAL(f1.search("line3", "line4", true), true)
	TEST_EQUAL(f1.getLine(), "line3-")
	TEST_EQUAL(f1.getLineNumber(), 3)

  f1.rewind();
	TEST_EQUAL(f1.search("line4", "line3", false), false)
	TEST_EQUAL(f1.getLine(), "line3-")
	TEST_EQUAL(f1.getLineNumber(), 3)

  f1.rewind();
	TEST_EQUAL(f1.search("/", "l", false), false)
	TEST_EQUAL(f1.getLine(), "line1")
	TEST_EQUAL(f1.getLineNumber(), 1)

  f1.rewind();
	f1.readLine();
	f1.readLine();
	TEST_EQUAL(f1.getLine(), "/0/ /1/ /2 2//3/")
	bool  erg = f1.search("line4", "line3", true);
	TEST_EQUAL(erg, false)
	TEST_EQUAL(f1.getLine(), "/0/ /1/ /2 2//3/")
	TEST_EQUAL(f1.getLineNumber(), 2)

  f1.rewind();
	f1.skipLines(2);
	TEST_EQUAL(f1.getLine(), "line3-")
	TEST_EQUAL(f1.search("XXX", "ZZZZZ", true), false)
	TEST_EQUAL(f1.getLine(), "line3-")

  f1.rewind();
	erg = f1.search("#", "l", false);
	TEST_EQUAL(erg, false)
	TEST_EQUAL(f1.getLine(), "line1")

  f1.rewind();
	erg = f1.search("#", "l", true);
	TEST_EQUAL(erg, false)
	TEST_EQUAL(f1.getLineNumber(), 0)

  f1.rewind();
	erg = f1.search("line7", "#", false);
	TEST_EQUAL(erg, false)
	TEST_EQUAL(f1.getLine(), "###########")

	TEST_EXCEPTION(LineBasedFile::LineBasedFileError, fx.search("line4", "line3"))
RESULT

CHECK(switchString(const std::vector<String>& data) const  throw())
  f1.rewind();
	f1.readLine();

	vector<String> vec;
	vec.push_back("line");
	vec.push_back("line1");
	vec.push_back("line2");
	vec.push_back("");

	TEST_EQUAL(f1.switchString(vec), 1)
	f1.readLine();
	TEST_EQUAL(f1.switchString(vec), -1)

	TEST_EQUAL(fx.switchString(vec), 3)
RESULT

CHECK(test(const char* file, int line, bool condition, const String& msg)
			const  throw(LineBasedFileError))
	f1.test(__FILE__, __LINE__, true, "test");
	TEST_EXCEPTION(LineBasedFile::LineBasedFileError, f1.test(__FILE__, __LINE__, false, "test") )
	fx.test(__FILE__, __LINE__, true, "test");
RESULT

CHECK(readLine() throw(LineBasedFileError))
  f1.rewind();
	f1.readLine();

	TEST_EQUAL(f1.getLine(), "line1")

	TEST_EXCEPTION(LineBasedFile::LineBasedFileError, fx.readLine())
	TEST_EQUAL(fx.getLine(), "")
RESULT

CHECK(skipLines(Size number = 1) throw(Exception::IndexUnderflow, LineBasedFileError))
  f1.rewind();
	TEST_EQUAL(f1.skipLines(2), true)
	TEST_EQUAL(f1.getLine(), "line3-")
	TEST_EQUAL(f1.getLineNumber(), 3)
	TEST_EQUAL(f1.skipLines(5), false)

	TEST_EXCEPTION(LineBasedFile::LineBasedFileError, fx.skipLines(2))
	TEST_EQUAL(fx.getLine(), "")
	TEST_EQUAL(fx.getLineNumber(), 0)
RESULT

CHECK(rewind() throw(LineBasedFileError))
  f1.rewind();
	TEST_EQUAL(f1.getLine(), "")
	TEST_EQUAL(f1.getLineNumber(), 0)

  TEST_EXCEPTION(LineBasedFile::LineBasedFileError,fx.rewind())
	TEST_EQUAL(fx.getLine(), "")
	TEST_EQUAL(fx.getLineNumber(), 0)
RESULT

CHECK(goToLine(Position line_number) throw(LineBasedFileError))
  f1.rewind();
	f1.skipLines(4);
	TEST_EQUAL(f1.goToLine(3), true)
	TEST_EQUAL(f1.getLine(), "line3-" )
	TEST_EQUAL(f1.getLineNumber(), 3)

	TEST_EQUAL(f1.goToLine(5), true)
	TEST_EQUAL(f1.getLine(), "line5-" )
	TEST_EQUAL(f1.getLineNumber(), 5)

	TEST_EQUAL(f1.goToLine(8), false)
	TEST_EQUAL(f1.getLine(), "line7-" )
	TEST_EQUAL(f1.getLineNumber(), 7)

  TEST_EXCEPTION(LineBasedFile::LineBasedFileError,fx.goToLine(2))
	TEST_EQUAL(fx.getLine(), "")
	TEST_EQUAL(fx.getLineNumber(), 0)
RESULT

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<commit_msg>added: test for BALL_CREATE<commit_after>// $Id: LineBasedFile_test.C,v 1.10 2001/02/10 19:07:52 amoll Exp $
#include <BALL/CONCEPT/classTest.h>

///////////////////////////
#include <BALL/FORMAT/lineBasedFile.h>
///////////////////////////

START_TEST(class_name, "$Id: LineBasedFile_test.C,v 1.10 2001/02/10 19:07:52 amoll Exp $")

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

using namespace BALL;

LineBasedFile* fl;

CHECK(LineBasedFile() throw())
	fl = new LineBasedFile;
	TEST_NOT_EQUAL(fl, 0)
RESULT

CHECK(~LineBasedFile() throw())
	delete fl;
RESULT

CHECK(BALL_CREATE(LineBasedFile))
	LineBasedFile c;
	LineBasedFile* ptr = (LineBasedFile*)c.create(false, true);
	TEST_NOT_EQUAL(ptr, 0)
RESULT

CHECK(LineBasedFile(const String& filename, File::OpenMode open_mode = File::IN)
			throw(Exception::FileNotFound))
	LineBasedFile f1("data/LineBasedFile_test.txt");
	TEST_EQUAL(f1.getLineNumber(), 0)
	TEST_EQUAL(f1.getLine(), "")
	f1.readLine();
	TEST_EQUAL(f1.getLineNumber(), 1)
	TEST_EQUAL(f1.getLine(), "line1")

	TEST_EXCEPTION(Exception::FileNotFound, LineBasedFile f2("XXXXXXXX.txt"))
RESULT

LineBasedFile fx;

CHECK(LineBasedFile(const LineBasedFile& f) throw())
	LineBasedFile f1("data/LineBasedFile_test.txt");
	TEST_EQUAL(f1.readLine(), true)
	TEST_EQUAL(f1.getLine(), "line1")
	f1.close();

	LineBasedFile f2(f1);
	TEST_EQUAL(f2.getLineNumber(), 1)
	TEST_EQUAL(f2.getLine(), "line1")
	TEST_EQUAL(f2.readLine(), true)
	TEST_EQUAL(f2.getLine(), "/0/ /1/ /2 2//3/")

	LineBasedFile f3;
	LineBasedFile f4(f3);
RESULT

CHECK(LineBasedFile& operator = (const LineBasedFile& file) throw())
	LineBasedFile f1("data/LineBasedFile_test.txt");
	f1.readLine();
	TEST_EQUAL(f1.getLine(), "line1")

	LineBasedFile f2;
	f2 = f1;
	TEST_EQUAL(f2.getLineNumber(), 1)
	TEST_EQUAL(f2.getLine(), "line1")
RESULT

CHECK(clear() throw())
	LineBasedFile f1("data/LineBasedFile_test.txt");
	f1.readLine();
	f1.clear();
	TEST_EQUAL(f1.getLineNumber(), 0)
	TEST_EQUAL(f1.getLine(), "")

	fx.clear();
RESULT

CHECK(getLineNumber() const  throw())
	LineBasedFile f1("data/LineBasedFile_test.txt");
	TEST_EQUAL(f1.getLineNumber(), 0)
	f1.readLine();
	TEST_EQUAL(f1.getLineNumber(), 1)

	TEST_EQUAL(fx.getLineNumber(), 0)
RESULT

LineBasedFile f1("data/LineBasedFile_test.txt");

CHECK(getLine() const  throw())
	TEST_EQUAL(f1.getLine(), "")
	f1.readLine();
	TEST_EQUAL(f1.getLine(), "line1")

	TEST_EQUAL(fx.getLine(), "")
RESULT

CHECK(getField(Position pos = 0, const String& quotes = "",
			const String& delimiters = String::CHARACTER_CLASS__WHITESPACE)
			const  throw(Exception::IndexUnderflow))

	TEST_EQUAL(f1.getField(), "line1")
	TEST_EQUAL(f1.getField(1), "")
	TEST_EXCEPTION(Exception::IndexUnderflow, f1.getField(-99))
	f1.readLine();
	TEST_EQUAL(f1.getField(), "/0/")
	TEST_EQUAL(f1.getField(1), "/1/")
	TEST_EQUAL(f1.getField(2), "/2")
	TEST_EQUAL(f1.getField(0, "/"), "0")
	TEST_EQUAL(f1.getField(1, "/"), "1")
	TEST_EQUAL(f1.getField(2, "/"), "2 23")
	TEST_EQUAL(f1.getField(3, "/"), "")

	TEST_EQUAL(fx.getField(), "")
RESULT

CHECK(startsWith(const String& text) const  throw())
	TEST_EQUAL(f1.startsWith("/0/"), true)
	TEST_EQUAL(f1.startsWith("/0/ /1/ /2 2//3/"), true)
	TEST_EQUAL(f1.startsWith("/0/ /1/ /2 2//3/X"), false)

	TEST_EQUAL(fx.startsWith(""), true)
RESULT

CHECK(has(const String& text) const  throw())
	TEST_EQUAL(f1.has("/0/"), true)
	TEST_EQUAL(f1.has("/"), true)
	TEST_EQUAL(f1.has("/1/"), true)
	TEST_EQUAL(f1.has("/3/"), true)
	TEST_EQUAL(f1.has("X"), false)

	TEST_EQUAL(fx.has("X"), false)
	TEST_EQUAL(fx.has(""), true)
RESULT

CHECK(search(const String& text, bool return_to_point) throw())
	TEST_EQUAL(f1.search("line3"), true)
	TEST_EQUAL(f1.search("line4-"), true)
	TEST_EQUAL(f1.search("line4-"), false)
	TEST_EQUAL(f1.getLine(), "line7-")
  f1.rewind();

	f1.skipLines(2);
	TEST_EQUAL(f1.getLine(), "line3-")
	TEST_EQUAL(f1.search("XXX", true), false)
	TEST_EQUAL(f1.getLine(), "line3-")

  f1.rewind();
	TEST_EQUAL(f1.search("#"), true)
	TEST_EQUAL(f1.getLine(), "###########")

	TEST_EXCEPTION(LineBasedFile::LineBasedFileError, fx.search("line4-"))
RESULT

CHECK(search(const String& text, const String& stop, bool return_to_point) throw())
  f1.rewind();
	TEST_EQUAL(f1.search("line3", "line4", true), true)
	TEST_EQUAL(f1.getLine(), "line3-")
	TEST_EQUAL(f1.getLineNumber(), 3)

  f1.rewind();
	TEST_EQUAL(f1.search("line4", "line3", false), false)
	TEST_EQUAL(f1.getLine(), "line3-")
	TEST_EQUAL(f1.getLineNumber(), 3)

  f1.rewind();
	TEST_EQUAL(f1.search("/", "l", false), false)
	TEST_EQUAL(f1.getLine(), "line1")
	TEST_EQUAL(f1.getLineNumber(), 1)

  f1.rewind();
	f1.readLine();
	f1.readLine();
	TEST_EQUAL(f1.getLine(), "/0/ /1/ /2 2//3/")
	bool  erg = f1.search("line4", "line3", true);
	TEST_EQUAL(erg, false)
	TEST_EQUAL(f1.getLine(), "/0/ /1/ /2 2//3/")
	TEST_EQUAL(f1.getLineNumber(), 2)

  f1.rewind();
	f1.skipLines(2);
	TEST_EQUAL(f1.getLine(), "line3-")
	TEST_EQUAL(f1.search("XXX", "ZZZZZ", true), false)
	TEST_EQUAL(f1.getLine(), "line3-")

  f1.rewind();
	erg = f1.search("#", "l", false);
	TEST_EQUAL(erg, false)
	TEST_EQUAL(f1.getLine(), "line1")

  f1.rewind();
	erg = f1.search("#", "l", true);
	TEST_EQUAL(erg, false)
	TEST_EQUAL(f1.getLineNumber(), 0)

  f1.rewind();
	erg = f1.search("line7", "#", false);
	TEST_EQUAL(erg, false)
	TEST_EQUAL(f1.getLine(), "###########")

	TEST_EXCEPTION(LineBasedFile::LineBasedFileError, fx.search("line4", "line3"))
RESULT

CHECK(switchString(const std::vector<String>& data) const  throw())
  f1.rewind();
	f1.readLine();

	vector<String> vec;
	vec.push_back("line");
	vec.push_back("line1");
	vec.push_back("line2");
	vec.push_back("");

	TEST_EQUAL(f1.switchString(vec), 1)
	f1.readLine();
	TEST_EQUAL(f1.switchString(vec), -1)

	TEST_EQUAL(fx.switchString(vec), 3)
RESULT

CHECK(test(const char* file, int line, bool condition, const String& msg)
			const  throw(LineBasedFileError))
	f1.test(__FILE__, __LINE__, true, "test");
	TEST_EXCEPTION(LineBasedFile::LineBasedFileError, f1.test(__FILE__, __LINE__, false, "test") )
	fx.test(__FILE__, __LINE__, true, "test");
RESULT

CHECK(readLine() throw(LineBasedFileError))
  f1.rewind();
	f1.readLine();

	TEST_EQUAL(f1.getLine(), "line1")

	TEST_EXCEPTION(LineBasedFile::LineBasedFileError, fx.readLine())
	TEST_EQUAL(fx.getLine(), "")
RESULT

CHECK(skipLines(Size number = 1) throw(Exception::IndexUnderflow, LineBasedFileError))
  f1.rewind();
	TEST_EQUAL(f1.skipLines(2), true)
	TEST_EQUAL(f1.getLine(), "line3-")
	TEST_EQUAL(f1.getLineNumber(), 3)
	TEST_EQUAL(f1.skipLines(5), false)

	TEST_EXCEPTION(LineBasedFile::LineBasedFileError, fx.skipLines(2))
	TEST_EQUAL(fx.getLine(), "")
	TEST_EQUAL(fx.getLineNumber(), 0)
RESULT

CHECK(rewind() throw(LineBasedFileError))
  f1.rewind();
	TEST_EQUAL(f1.getLine(), "")
	TEST_EQUAL(f1.getLineNumber(), 0)

  TEST_EXCEPTION(LineBasedFile::LineBasedFileError,fx.rewind())
	TEST_EQUAL(fx.getLine(), "")
	TEST_EQUAL(fx.getLineNumber(), 0)
RESULT

CHECK(goToLine(Position line_number) throw(LineBasedFileError))
  f1.rewind();
	f1.skipLines(4);
	TEST_EQUAL(f1.goToLine(3), true)
	TEST_EQUAL(f1.getLine(), "line3-" )
	TEST_EQUAL(f1.getLineNumber(), 3)

	TEST_EQUAL(f1.goToLine(5), true)
	TEST_EQUAL(f1.getLine(), "line5-" )
	TEST_EQUAL(f1.getLineNumber(), 5)

	TEST_EQUAL(f1.goToLine(8), false)
	TEST_EQUAL(f1.getLine(), "line7-" )
	TEST_EQUAL(f1.getLineNumber(), 7)

  TEST_EXCEPTION(LineBasedFile::LineBasedFileError,fx.goToLine(2))
	TEST_EQUAL(fx.getLine(), "")
	TEST_EQUAL(fx.getLineNumber(), 0)
RESULT

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<|endoftext|>