Dataset Viewer
Auto-converted to Parquet Duplicate
text
string
size
int64
token_count
int64
/* Copyright (c) 2012 Cheese and Bacon Games, LLC */ /* This file is licensed under the MIT License. */ /* See the file docs/LICENSE.txt for the full license text. */ #include "game.h" #include "android_leaderboard.h" #include <button_events.h> #include <window_manager.h> #include <game_manager.h> #include <android.h> #include <gui_manager.h> #include <boost/algorithm/string.hpp> using namespace std; bool Button_Events::handle_button_event_game (string button_event, Window* parent_window, bool& window_opened_on_top) { if (button_event == "game_over") { Window_Manager::close_all_windows(); if (Game::is_score_high()) { Window_Manager::get_window("input_name")->toggle_on(); GUI_Manager::confirm_gui_object(); } else { Android_Leaderboard::submit_highscore(Android_Leaderboard::HIGH_SCORES, Game::get_score()); Android_Leaderboard::submit_highscore(Android_Leaderboard::BEST_KILL_COUNT, Game::get_kills()); Android_Leaderboard::submit_highscore(Android_Leaderboard::DEBRIS_DODGED, Game::get_dodges()); Game_Manager::stop(); Window_Manager::get_window("main_menu")->toggle_on(); Window_Manager::get_window("high_scores")->toggle_on(); } window_opened_on_top = true; return true; } else if (button_event == "gpg_toggle_sign_in") { if (Android::gpg_is_silent_sign_in_attempt_complete()) { if (!Android::gpg_is_signed_in()) { Android::gpg_sign_in(); Game::android_gpg_signing_in(); } else { Android::gpg_sign_out(); } } return true; } else if (boost::algorithm::starts_with(button_event, "gpg_show_leaderboard_")) { boost::algorithm::erase_first(button_event, "gpg_show_leaderboard_"); if (Android::gpg_is_signed_in()) { Android::gpg_show_leaderboard(button_event); } return true; } else if (button_event == "gpg_show_all_leaderboards") { if (Android::gpg_is_signed_in()) { Android::gpg_show_all_leaderboards(); } return true; } else if (button_event == "gpg_show_achievements") { if (Android::gpg_is_signed_in()) { Android::gpg_show_achievements(); } return true; } else if (button_event == "name") { Window_Manager::close_all_windows(); if (parent_window != 0) { Game::add_high_score(parent_window->get_info_text(0)); Android_Leaderboard::submit_highscore(Android_Leaderboard::HIGH_SCORES, Game::get_score()); Android_Leaderboard::submit_highscore(Android_Leaderboard::BEST_KILL_COUNT, Game::get_kills()); Android_Leaderboard::submit_highscore(Android_Leaderboard::DEBRIS_DODGED, Game::get_dodges()); } Game_Manager::stop(); Window_Manager::get_window("main_menu")->toggle_on(); Window_Manager::get_window("high_scores")->toggle_on(); window_opened_on_top = true; return true; } else if (boost::algorithm::starts_with(button_event, "select_upgrade_")) { boost::algorithm::erase_first(button_event, "select_upgrade_"); Window_Manager::close_all_windows(); Game::player_add_upgrade(button_event); Game::complete_contract(); return true; } else if (button_event == "skip_upgrade") { Window_Manager::close_all_windows(); Game::restore_hull_from_contract(); Game::complete_contract(); return true; } return false; }
3,639
1,187
#include "Variant.hpp" #include <gdnative/variant.h> #include "CoreTypes.hpp" #include "Defs.hpp" #include "GodotGlobal.hpp" #include "Object.hpp" #include <iostream> #include <stdexcept> #ifndef NO_IMPORT_ARRAY #define NO_IMPORT_ARRAY #endif #include "PythonGlobal.hpp" #include <_lib/godot/core/types.hpp> namespace godot { Variant::Variant() { godot::api->godot_variant_new_nil(&_godot_variant); } Variant::Variant(const Variant &v) { godot::api->godot_variant_new_copy(&_godot_variant, &v._godot_variant); } Variant::Variant(bool p_bool) { godot::api->godot_variant_new_bool(&_godot_variant, p_bool); } Variant::Variant(signed int p_int) // real one { godot::api->godot_variant_new_int(&_godot_variant, p_int); } Variant::Variant(unsigned int p_int) { godot::api->godot_variant_new_uint(&_godot_variant, p_int); } Variant::Variant(signed short p_short) // real one { godot::api->godot_variant_new_int(&_godot_variant, (int)p_short); } Variant::Variant(int64_t p_char) // real one { godot::api->godot_variant_new_int(&_godot_variant, p_char); } Variant::Variant(uint64_t p_char) { godot::api->godot_variant_new_uint(&_godot_variant, p_char); } Variant::Variant(float p_float) { godot::api->godot_variant_new_real(&_godot_variant, p_float); } Variant::Variant(double p_double) { godot::api->godot_variant_new_real(&_godot_variant, p_double); } Variant::Variant(const String &p_string) { godot::api->godot_variant_new_string(&_godot_variant, (godot_string *)&p_string); } Variant::Variant(const char *const p_cstring) { String s = String(p_cstring); godot::api->godot_variant_new_string(&_godot_variant, (godot_string *)&s); } Variant::Variant(const wchar_t *p_wstring) { String s = p_wstring; godot::api->godot_variant_new_string(&_godot_variant, (godot_string *)&s); } Variant::Variant(const Vector2 &p_vector2) { godot::api->godot_variant_new_vector2(&_godot_variant, (godot_vector2 *)&p_vector2); } Variant::Variant(const Rect2 &p_rect2) { godot::api->godot_variant_new_rect2(&_godot_variant, (godot_rect2 *)&p_rect2); } Variant::Variant(const Vector3 &p_vector3) { godot::api->godot_variant_new_vector3(&_godot_variant, (godot_vector3 *)&p_vector3); } Variant::Variant(const Plane &p_plane) { godot::api->godot_variant_new_plane(&_godot_variant, (godot_plane *)&p_plane); } Variant::Variant(const AABB &p_aabb) { godot::api->godot_variant_new_aabb(&_godot_variant, (godot_aabb *)&p_aabb); } Variant::Variant(const Quat &p_quat) { godot::api->godot_variant_new_quat(&_godot_variant, (godot_quat *)&p_quat); } Variant::Variant(const Basis &p_transform) { godot::api->godot_variant_new_basis(&_godot_variant, (godot_basis *)&p_transform); } Variant::Variant(const Transform2D &p_transform) { godot::api->godot_variant_new_transform2d(&_godot_variant, (godot_transform2d *)&p_transform); } Variant::Variant(const Transform &p_transform) { godot::api->godot_variant_new_transform(&_godot_variant, (godot_transform *)&p_transform); } Variant::Variant(const Color &p_color) { godot::api->godot_variant_new_color(&_godot_variant, (godot_color *)&p_color); } Variant::Variant(const NodePath &p_path) { godot::api->godot_variant_new_node_path(&_godot_variant, (godot_node_path *)&p_path); } Variant::Variant(const RID &p_rid) { godot::api->godot_variant_new_rid(&_godot_variant, (godot_rid *)&p_rid); } Variant::Variant(const Object *p_object) { if (p_object) godot::api->godot_variant_new_object(&_godot_variant, p_object->_owner); else godot::api->godot_variant_new_nil(&_godot_variant); } Variant::Variant(const Dictionary &p_dictionary) { godot::api->godot_variant_new_dictionary(&_godot_variant, (godot_dictionary *)&p_dictionary); } Variant::Variant(const Array &p_array) { godot::api->godot_variant_new_array(&_godot_variant, (godot_array *)&p_array); } Variant::Variant(const PoolByteArray &p_raw_array) { godot::api->godot_variant_new_pool_byte_array(&_godot_variant, (godot_pool_byte_array *)&p_raw_array); } Variant::Variant(const PoolIntArray &p_int_array) { godot::api->godot_variant_new_pool_int_array(&_godot_variant, (godot_pool_int_array *)&p_int_array); } Variant::Variant(const PoolRealArray &p_real_array) { godot::api->godot_variant_new_pool_real_array(&_godot_variant, (godot_pool_real_array *)&p_real_array); } Variant::Variant(const PoolStringArray &p_string_array) { godot::api->godot_variant_new_pool_string_array(&_godot_variant, (godot_pool_string_array *)&p_string_array); } Variant::Variant(const PoolVector2Array &p_vector2_array) { godot::api->godot_variant_new_pool_vector2_array(&_godot_variant, (godot_pool_vector2_array *)&p_vector2_array); } Variant::Variant(const PoolVector3Array &p_vector3_array) { godot::api->godot_variant_new_pool_vector3_array(&_godot_variant, (godot_pool_vector3_array *)&p_vector3_array); } Variant::Variant(const PoolColorArray &p_color_array) { godot::api->godot_variant_new_pool_color_array(&_godot_variant, (godot_pool_color_array *)&p_color_array); } Variant::Variant(const PyObject *p_python_object) { if (p_python_object == Py_None) { // Py_XDECREF(p_python_object); // XXX godot::api->godot_variant_new_nil(&_godot_variant); } else if (PyBool_Check(p_python_object)) { godot::api->godot_variant_new_bool(&_godot_variant, PyLong_AsLong((PyObject *)p_python_object)); } else if (PyLong_Check(p_python_object)) { godot::api->godot_variant_new_int(&_godot_variant, PyLong_AsLong((PyObject *)p_python_object)); } else if (PyFloat_Check(p_python_object)) { const double p_double = PyFloat_AsDouble((PyObject *)p_python_object); godot::api->godot_variant_new_real(&_godot_variant, p_double); } else if (PyUnicode_Check(p_python_object) || PyBytes_Check(p_python_object)) { String s = String(p_python_object); godot::api->godot_variant_new_string(&_godot_variant, (godot_string *)&s); } else if (PyByteArray_Check(p_python_object)) { godot_pool_byte_array *p; godot::api->godot_pool_byte_array_new(p); godot::api->godot_pool_byte_array_resize(p, PyByteArray_GET_SIZE(p_python_object)); godot_pool_byte_array_write_access *_write_access = godot::api->godot_pool_byte_array_write(p); const uint8_t *ptr = godot::api->godot_pool_byte_array_write_access_ptr(_write_access); memcpy((void *)ptr, (void *)PyByteArray_AS_STRING(p_python_object), PyByteArray_GET_SIZE(p_python_object)); godot::api->godot_variant_new_pool_byte_array(&_godot_variant, p); godot::api->godot_pool_byte_array_write_access_destroy(_write_access); godot::api->godot_pool_byte_array_destroy(p); } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_AABB) { godot_aabb *p = _python_wrapper_to_aabb((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_aabb(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_Array) { godot_array *p = _python_wrapper_to_godot_array((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_array(&_godot_variant, p); } else { godot::api->godot_variant_new_nil(&_godot_variant); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_Basis) { godot_basis *p = _python_wrapper_to_basis((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_basis(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_Color) { godot_color *p = _python_wrapper_to_color((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_color(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_Dictionary) { godot_dictionary *p = _python_wrapper_to_godot_dictionary((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_dictionary(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_NodePath) { godot_node_path *p = _python_wrapper_to_nodepath((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_node_path(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_Plane) { godot_plane *p = _python_wrapper_to_plane((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_plane(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_PoolByteArray) { godot_pool_byte_array *p = _python_wrapper_to_poolbytearray((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_pool_byte_array(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_PoolIntArray) { godot_pool_int_array *p = _python_wrapper_to_poolintarray((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_pool_int_array(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_PoolRealArray) { godot_pool_real_array *p = _python_wrapper_to_poolrealarray((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_pool_real_array(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_PoolStringArray) { godot_pool_string_array *p = _python_wrapper_to_poolstringarray((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_pool_string_array(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_PoolVector2Array) { godot_pool_vector2_array *p = _python_wrapper_to_poolvector2array((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_pool_vector2_array(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_PoolVector3Array) { godot_pool_vector3_array *p = _python_wrapper_to_poolvector3array((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_pool_vector3_array(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_PoolColorArray) { godot_pool_color_array *p = _python_wrapper_to_poolcolorarray((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_pool_color_array(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_Quat) { godot_quat *p = _python_wrapper_to_quat((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_quat(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_Rect2) { godot_rect2 *p = _python_wrapper_to_rect2((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_rect2(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_RID) { godot_rid *p = _python_wrapper_to_rid((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_rid(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_String) { godot_string *p = _python_wrapper_to_godot_string((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_string(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_Transform) { godot_transform *p = _python_wrapper_to_transform((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_transform(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_Transform2D) { godot_transform2d *p = _python_wrapper_to_transform2d((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_transform2d(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_Vector2) { godot_vector2 *p = _python_wrapper_to_vector2((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_vector2(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (Py_TYPE(p_python_object) == PyGodotWrapperType_Vector3) { godot_vector3 *p = _python_wrapper_to_vector3((PyObject *)p_python_object); if (p) { godot::api->godot_variant_new_vector3(&_godot_variant, p); } else { throw std::invalid_argument("could not convert Python object to Variant"); } } else if (PyObject_IsInstance((PyObject *)p_python_object, (PyObject *)PyGodotType__Wrapped)) { godot_object *p = _cython_binding_to_godot_object((PyObject *)p_python_object); godot::api->godot_variant_new_object(&_godot_variant, p); // TODO: dict -> Dictionary, other iterables -> Array, array.Array -> PoolArray*, numpy.array -> PoolArray* } else if (PyArray_Check((PyObject *)p_python_object)) { PyArrayObject *arr = (PyArrayObject *)p_python_object; if (PyArray_NDIM(arr) == 1 && PyArray_TYPE(arr) == NPY_UINT8) { PoolByteArray _arr = PoolByteArray(arr); godot::api->godot_variant_new_pool_byte_array(&_godot_variant, (godot_pool_byte_array *)&_arr); } else if (PyArray_NDIM(arr) == 1 && PyArray_ISINTEGER(arr)) { PoolIntArray _arr(arr); godot::api->godot_variant_new_pool_int_array(&_godot_variant, (godot_pool_int_array *)&_arr); } else if (PyArray_NDIM(arr) == 1 && PyArray_ISFLOAT(arr)) { PoolRealArray _arr(arr); godot::api->godot_variant_new_pool_real_array(&_godot_variant, (godot_pool_real_array *)&_arr); } else if (PyArray_NDIM(arr) == 1 && PyArray_ISSTRING(arr)) { PoolStringArray _arr(arr); godot::api->godot_variant_new_pool_string_array(&_godot_variant, (godot_pool_string_array *)&_arr); } else if (PyArray_NDIM(arr) == 1) { Array _arr; for (int idx = 0; idx < PyArray_SIZE(arr); idx++) { PyObject *item = PyArray_GETITEM(arr, (const char *)PyArray_GETPTR1(arr, idx)); // TODO: Check NULL pointer _arr.append(Variant(item)); } godot::api->godot_variant_new_array(&_godot_variant, (godot_array *)&_arr); } else if (PyArray_NDIM(arr) == 2 && PyArray_ISNUMBER(arr) && PyArray_DIM(arr, 1) == 2) { PoolVector2Array _arr = PoolVector2Array(arr); godot::api->godot_variant_new_pool_vector2_array(&_godot_variant, (godot_pool_vector2_array *)&_arr); } else if (PyArray_NDIM(arr) == 2 && PyArray_ISNUMBER(arr) && PyArray_DIM(arr, 1) == 3) { PoolVector3Array _arr = PoolVector3Array(arr); godot::api->godot_variant_new_pool_vector3_array(&_godot_variant, (godot_pool_vector3_array *)&_arr); } else if (PyArray_NDIM(arr) == 2 && PyArray_ISNUMBER(arr) && PyArray_DIM(arr, 1) == 4) { PoolColorArray _arr = PoolColorArray(arr); godot::api->godot_variant_new_pool_color_array(&_godot_variant, (godot_pool_color_array *)&_arr); } else { throw std::invalid_argument("could not convert NumPy array"); } } else if (PySequence_Check((PyObject *)p_python_object)) { Array arr = Array(p_python_object); godot::api->godot_variant_new_array(&_godot_variant, (godot_array *)&arr); } else if (PyMapping_Check((PyObject *)p_python_object)) { Dictionary dict = Dictionary(p_python_object); godot::api->godot_variant_new_dictionary(&_godot_variant, (godot_dictionary *)&dict); } else if (PyIndex_Check((PyObject *)p_python_object)) { const Py_ssize_t p_num = PyNumber_AsSsize_t((PyObject *)p_python_object, NULL); godot::api->godot_variant_new_int(&_godot_variant, p_num); } else if (PyNumber_Check((PyObject *)p_python_object)) { PyObject *p_num = PyNumber_Float((PyObject *)p_python_object); const double p_double = PyFloat_AsDouble((PyObject *)p_num); godot::api->godot_variant_new_real(&_godot_variant, p_double); } else if (PyObject_CheckBuffer((PyObject *)p_python_object)) { throw std::invalid_argument("generic Python buffer support is not implemented yet"); } else { // raises ValueError in Cython/Python context throw std::invalid_argument("could not cast Python object to Godot Variant"); } } Variant &Variant::operator=(const Variant &v) { godot::api->godot_variant_new_copy(&_godot_variant, &v._godot_variant); return *this; } Variant::operator bool() const { return booleanize(); } Variant::operator signed int() const { return godot::api->godot_variant_as_int(&_godot_variant); } Variant::operator unsigned int() const // this is the real one { return godot::api->godot_variant_as_uint(&_godot_variant); } Variant::operator signed short() const { return godot::api->godot_variant_as_int(&_godot_variant); } Variant::operator unsigned short() const { return godot::api->godot_variant_as_uint(&_godot_variant); } Variant::operator signed char() const { return godot::api->godot_variant_as_int(&_godot_variant); } Variant::operator unsigned char() const { return godot::api->godot_variant_as_uint(&_godot_variant); } Variant::operator int64_t() const { return godot::api->godot_variant_as_int(&_godot_variant); } Variant::operator uint64_t() const { return godot::api->godot_variant_as_uint(&_godot_variant); } Variant::operator wchar_t() const { return godot::api->godot_variant_as_int(&_godot_variant); } Variant::operator float() const { return godot::api->godot_variant_as_real(&_godot_variant); } Variant::operator double() const { return godot::api->godot_variant_as_real(&_godot_variant); } Variant::operator String() const { String ret; *(godot_string *)&ret = godot::api->godot_variant_as_string(&_godot_variant); return ret; } Variant::operator Vector2() const { godot_vector2 s = godot::api->godot_variant_as_vector2(&_godot_variant); return *(Vector2 *)&s; } Variant::operator Rect2() const { godot_rect2 s = godot::api->godot_variant_as_rect2(&_godot_variant); return *(Rect2 *)&s; } Variant::operator Vector3() const { godot_vector3 s = godot::api->godot_variant_as_vector3(&_godot_variant); return *(Vector3 *)&s; } Variant::operator Plane() const { godot_plane s = godot::api->godot_variant_as_plane(&_godot_variant); return *(Plane *)&s; } Variant::operator AABB() const { godot_aabb s = godot::api->godot_variant_as_aabb(&_godot_variant); return *(AABB *)&s; } Variant::operator Quat() const { godot_quat s = godot::api->godot_variant_as_quat(&_godot_variant); return *(Quat *)&s; } Variant::operator Basis() const { godot_basis s = godot::api->godot_variant_as_basis(&_godot_variant); return *(Basis *)&s; } Variant::operator Transform() const { godot_transform s = godot::api->godot_variant_as_transform(&_godot_variant); return *(Transform *)&s; } Variant::operator Transform2D() const { godot_transform2d s = godot::api->godot_variant_as_transform2d(&_godot_variant); return *(Transform2D *)&s; } Variant::operator Color() const { godot_color s = godot::api->godot_variant_as_color(&_godot_variant); return *(Color *)&s; } Variant::operator NodePath() const { NodePath ret; *(godot_node_path *)&ret = godot::api->godot_variant_as_node_path(&_godot_variant); return ret; } Variant::operator RID() const { godot_rid s = godot::api->godot_variant_as_rid(&_godot_variant); return *(RID *)&s; } Variant::operator Dictionary() const { Dictionary ret; *(godot_dictionary *)&ret = godot::api->godot_variant_as_dictionary(&_godot_variant); return ret; } Variant::operator Array() const { Array ret; *(godot_array *)&ret = godot::api->godot_variant_as_array(&_godot_variant); return ret; } Variant::operator PoolByteArray() const { PoolByteArray ret; *(godot_pool_byte_array *)&ret = godot::api->godot_variant_as_pool_byte_array(&_godot_variant); return ret; } Variant::operator PoolIntArray() const { PoolIntArray ret; *(godot_pool_int_array *)&ret = godot::api->godot_variant_as_pool_int_array(&_godot_variant); return ret; } Variant::operator PoolRealArray() const { PoolRealArray ret; *(godot_pool_real_array *)&ret = godot::api->godot_variant_as_pool_real_array(&_godot_variant); return ret; } Variant::operator PoolStringArray() const { PoolStringArray ret; *(godot_pool_string_array *)&ret = godot::api->godot_variant_as_pool_string_array(&_godot_variant); return ret; } Variant::operator PoolVector2Array() const { PoolVector2Array ret; *(godot_pool_vector2_array *)&ret = godot::api->godot_variant_as_pool_vector2_array(&_godot_variant); return ret; } Variant::operator PoolVector3Array() const { PoolVector3Array ret; *(godot_pool_vector3_array *)&ret = godot::api->godot_variant_as_pool_vector3_array(&_godot_variant); return ret; } Variant::operator PoolColorArray() const { PoolColorArray ret; *(godot_pool_color_array *)&ret = godot::api->godot_variant_as_pool_color_array(&_godot_variant); return ret; } Variant::operator godot_object *() const { return godot::api->godot_variant_as_object(&_godot_variant); } Variant::operator PyObject *() const { PyObject *obj; switch (get_type()) { case NIL: obj = Py_None; break; case BOOL: obj = booleanize() ? Py_True : Py_False; break; case INT: obj = PyLong_FromSsize_t(godot::api->godot_variant_as_int(&_godot_variant)); break; case REAL: obj = PyFloat_FromDouble(godot::api->godot_variant_as_real(&_godot_variant)); break; case STRING: { String s = *this; obj = PyUnicode_FromWideChar(s.unicode_str(), s.length()); break; } case VECTOR2: { Vector2 cpp_obj = *this; return _vector2_to_python_wrapper(cpp_obj); } case RECT2: { Rect2 cpp_obj = *this; return _rect2_to_python_wrapper(cpp_obj); } case VECTOR3: { Vector3 cpp_obj = *this; return _vector3_to_python_wrapper(cpp_obj); } case TRANSFORM2D: { Transform2D cpp_obj = *this; return _transform2d_to_python_wrapper(cpp_obj); } case PLANE: { Plane cpp_obj = *this; return _plane_to_python_wrapper(cpp_obj); } case QUAT: { Quat cpp_obj = *this; return _quat_to_python_wrapper(cpp_obj); } case RECT3: { AABB cpp_obj = *this; return _aabb_to_python_wrapper(cpp_obj); } case BASIS: { Basis cpp_obj = *this; return _basis_to_python_wrapper(cpp_obj); } case TRANSFORM: { Transform cpp_obj = *this; return _transform_to_python_wrapper(cpp_obj); } case COLOR: { Color cpp_obj = *this; return _color_to_python_wrapper(cpp_obj); } case NODE_PATH: { NodePath cpp_obj = *this; return _nodepath_to_python_wrapper(cpp_obj); } case _RID: { RID cpp_obj = *this; return _rid_to_python_wrapper(cpp_obj); } case OBJECT: { godot_object *c_obj = godot::api->godot_variant_as_object(&_godot_variant); return _godot_object_to_python_binding(c_obj); } case DICTIONARY: { const Dictionary dict = *this; const Array keys = dict.keys(); obj = PyDict_New(); for (int i = 0; i < keys.size(); i++) { Variant _key = keys[i]; PyObject *key = _key; PyObject *val = dict[_key]; // TODO: Check unlikely NULL pointers PyDict_SetItem(obj, key, val); } break; } case ARRAY: { const Array arr = *this; obj = PyTuple_New(arr.size()); for (int i = 0; i < arr.size(); i++) { PyObject *item = arr[i]; // TODO: Check unlikely NULL pointers PyTuple_SET_ITEM(obj, i, item); } break; } case POOL_BYTE_ARRAY: { PoolByteArray cpp_obj = *this; return _poolbytearray_to_python_wrapper(cpp_obj); } case POOL_INT_ARRAY: { PoolIntArray cpp_obj = *this; return _poolintarray_to_python_wrapper(cpp_obj); } case POOL_REAL_ARRAY: { PoolRealArray cpp_obj = *this; return _poolrealarray_to_python_wrapper(cpp_obj); } case POOL_STRING_ARRAY: { PoolStringArray cpp_obj = *this; return _poolstringarray_to_numpy(cpp_obj); } case POOL_VECTOR2_ARRAY: { PoolVector2Array cpp_obj = *this; return _poolvector2array_to_python_wrapper(cpp_obj); } case POOL_VECTOR3_ARRAY: { PoolVector3Array cpp_obj = *this; return _poolvector3array_to_python_wrapper(cpp_obj); } case POOL_COLOR_ARRAY: { PoolColorArray cpp_obj = *this; return _poolcolorarray_to_python_wrapper(cpp_obj); } default: // raises ValueError in Cython/Python context throw std::invalid_argument("could not cast Python object to Godot Variant"); } Py_XINCREF(obj); return obj; } Variant::Type Variant::get_type() const { return (Type)godot::api->godot_variant_get_type(&_godot_variant); } Variant Variant::call(const String &method, const Variant **args, const int arg_count) { Variant v; *(godot_variant *)&v = godot::api->godot_variant_call(&_godot_variant, (godot_string *)&method, (const godot_variant **)args, arg_count, nullptr); return v; } bool Variant::has_method(const String &method) { return godot::api->godot_variant_has_method(&_godot_variant, (godot_string *)&method); } bool Variant::operator==(const Variant &b) const { return godot::api->godot_variant_operator_equal(&_godot_variant, &b._godot_variant); } bool Variant::operator!=(const Variant &b) const { return !(*this == b); } bool Variant::operator<(const Variant &b) const { return godot::api->godot_variant_operator_less(&_godot_variant, &b._godot_variant); } bool Variant::operator<=(const Variant &b) const { return (*this < b) || (*this == b); } bool Variant::operator>(const Variant &b) const { return !(*this <= b); } bool Variant::operator>=(const Variant &b) const { return !(*this < b); } bool Variant::hash_compare(const Variant &b) const { return godot::api->godot_variant_hash_compare(&_godot_variant, &b._godot_variant); } bool Variant::booleanize() const { return godot::api->godot_variant_booleanize(&_godot_variant); } Variant::~Variant() { godot::api->godot_variant_destroy(&_godot_variant); } } // namespace godot
26,803
10,739
/********************************************************************** Audacity: A Digital Audio Editor SelectHandle.cpp Paul Licameli split from TrackPanel.cpp **********************************************************************/ #include "../../Audacity.h" #include "SelectHandle.h" #include "../../Experimental.h" #include "Scrubbing.h" #include "TrackView.h" #include "../../AColor.h" #include "../../FreqWindow.h" #include "../../NumberScale.h" #include "../../Project.h" #include "../../ProjectAudioIO.h" #include "../../ProjectHistory.h" #include "../../ProjectSettings.h" #include "../../ProjectWindow.h" #include "../../RefreshCode.h" #include "../../SelectUtilities.h" #include "../../SelectionState.h" #include "../../TrackArtist.h" #include "../../TrackPanel.h" #include "../../TrackPanelDrawingContext.h" #include "../../TrackPanelMouseEvent.h" #include "../../ViewInfo.h" #include "../../WaveClip.h" #include "../../WaveTrack.h" #include "../../ondemand/ODManager.h" #include "../../prefs/SpectrogramSettings.h" #include "../../../images/Cursors.h" #include <wx/event.h> // Only for definition of SonifyBeginModifyState: //#include "../../NoteTrack.h" enum { //This constant determines the size of the horizontal region (in pixels) around //the right and left selection bounds that can be used for horizontal selection adjusting //(or, vertical distance around top and bottom bounds in spectrograms, // for vertical selection adjusting) SELECTION_RESIZE_REGION = 3, // Seems 4 is too small to work at the top. Why? FREQ_SNAP_DISTANCE = 10, }; // #define SPECTRAL_EDITING_ESC_KEY bool SelectHandle::IsClicked() const { return mSelectionStateChanger.get() != NULL; } namespace { // If we're in OnDemand mode, we may change the tip. void MaySetOnDemandTip(const Track * t, wxString &tip) { wxASSERT(t); //For OD regions, we need to override and display the percent complete for this task. //first, make sure it's a wavetrack. t->TypeSwitch( [&](const WaveTrack *wt) { //see if the wavetrack exists in the ODManager (if the ODManager exists) if (!ODManager::IsInstanceCreated()) return; //ask the wavetrack for the corresponding tip - it may not change tip, but that's fine. ODManager::Instance()->FillTipForWaveTrack(wt, tip); }); } /// Converts a frequency to screen y position. wxInt64 FrequencyToPosition(const WaveTrack *wt, double frequency, wxInt64 trackTopEdge, int trackHeight) { const SpectrogramSettings &settings = wt->GetSpectrogramSettings(); float minFreq, maxFreq; wt->GetSpectrumBounds(&minFreq, &maxFreq); const NumberScale numberScale(settings.GetScale(minFreq, maxFreq)); const float p = numberScale.ValueToPosition(frequency); return trackTopEdge + wxInt64((1.0 - p) * trackHeight); } /// Converts a position (mouse Y coordinate) to /// frequency, in Hz. double PositionToFrequency(const WaveTrack *wt, bool maySnap, wxInt64 mouseYCoordinate, wxInt64 trackTopEdge, int trackHeight) { const double rate = wt->GetRate(); // Handle snapping if (maySnap && mouseYCoordinate - trackTopEdge < FREQ_SNAP_DISTANCE) return rate; if (maySnap && trackTopEdge + trackHeight - mouseYCoordinate < FREQ_SNAP_DISTANCE) return -1; const SpectrogramSettings &settings = wt->GetSpectrogramSettings(); float minFreq, maxFreq; wt->GetSpectrumBounds(&minFreq, &maxFreq); const NumberScale numberScale(settings.GetScale(minFreq, maxFreq)); const double p = double(mouseYCoordinate - trackTopEdge) / trackHeight; return numberScale.PositionToValue(1.0 - p); } template<typename T> inline void SetIfNotNull(T * pValue, const T Value) { if (pValue == NULL) return; *pValue = Value; } // This returns true if we're a spectral editing track. inline bool isSpectralSelectionTrack(const Track *pTrack) { return pTrack && pTrack->TypeSwitch< bool >( [&](const WaveTrack *wt) { const SpectrogramSettings &settings = wt->GetSpectrogramSettings(); const int display = wt->GetDisplay(); return (display == WaveTrackViewConstants::Spectrum) && settings.SpectralSelectionEnabled(); }); } enum SelectionBoundary { SBNone, SBLeft, SBRight, #ifdef EXPERIMENTAL_SPECTRAL_EDITING SBBottom, SBTop, SBCenter, SBWidth, #endif }; SelectionBoundary ChooseTimeBoundary ( const double t0, const double t1, const ViewInfo &viewInfo, double selend, bool onlyWithinSnapDistance, wxInt64 *pPixelDist, double *pPinValue) { const wxInt64 posS = viewInfo.TimeToPosition(selend); const wxInt64 pos0 = viewInfo.TimeToPosition(t0); wxInt64 pixelDist = std::abs(posS - pos0); bool chooseLeft = true; if (t1<=t0) // Special case when selection is a point, and thus left // and right distances are the same chooseLeft = (selend < t0); else { const wxInt64 pos1 = viewInfo.TimeToPosition(t1); const wxInt64 rightDist = std::abs(posS - pos1); if (rightDist < pixelDist) chooseLeft = false, pixelDist = rightDist; } SetIfNotNull(pPixelDist, pixelDist); if (onlyWithinSnapDistance && pixelDist >= SELECTION_RESIZE_REGION) { SetIfNotNull(pPinValue, -1.0); return SBNone; } else if (chooseLeft) { SetIfNotNull(pPinValue, t1); return SBLeft; } else { SetIfNotNull(pPinValue, t0); return SBRight; } } SelectionBoundary ChooseBoundary (const ViewInfo &viewInfo, wxCoord xx, wxCoord yy, const Track *pTrack, const wxRect &rect, bool mayDragWidth, bool onlyWithinSnapDistance, double *pPinValue = NULL) { // Choose one of four boundaries to adjust, or the center frequency. // May choose frequencies only if in a spectrogram view and // within the time boundaries. // May choose no boundary if onlyWithinSnapDistance is true. // Otherwise choose the eligible boundary nearest the mouse click. const double selend = viewInfo.PositionToTime(xx, rect.x); wxInt64 pixelDist = 0; const double t0 = viewInfo.selectedRegion.t0(); const double t1 = viewInfo.selectedRegion.t1(); SelectionBoundary boundary = ChooseTimeBoundary(t0,t1,viewInfo, selend, onlyWithinSnapDistance, &pixelDist, pPinValue); #ifdef EXPERIMENTAL_SPECTRAL_EDITING //const double t0 = viewInfo.selectedRegion.t0(); //const double t1 = viewInfo.selectedRegion.t1(); const double f0 = viewInfo.selectedRegion.f0(); const double f1 = viewInfo.selectedRegion.f1(); const double fc = viewInfo.selectedRegion.fc(); double ratio = 0; bool chooseTime = true; bool chooseBottom = true; bool chooseCenter = false; // Consider adjustment of frequencies only if mouse is // within the time boundaries if (!viewInfo.selectedRegion.isPoint() && t0 <= selend && selend < t1 && isSpectralSelectionTrack(pTrack)) { // Spectral selection track is always wave const WaveTrack *const wt = static_cast<const WaveTrack*>(pTrack); const wxInt64 bottomSel = (f0 >= 0) ? FrequencyToPosition(wt, f0, rect.y, rect.height) : rect.y + rect.height; const wxInt64 topSel = (f1 >= 0) ? FrequencyToPosition(wt, f1, rect.y, rect.height) : rect.y; wxInt64 signedBottomDist = (int)(yy - bottomSel); wxInt64 verticalDist = std::abs(signedBottomDist); if (bottomSel == topSel) // Top and bottom are too close to resolve on screen chooseBottom = (signedBottomDist >= 0); else { const wxInt64 topDist = std::abs((int)(yy - topSel)); if (topDist < verticalDist) chooseBottom = false, verticalDist = topDist; } if (fc > 0 #ifdef SPECTRAL_EDITING_ESC_KEY && mayDragWidth #endif ) { const wxInt64 centerSel = FrequencyToPosition(wt, fc, rect.y, rect.height); const wxInt64 centerDist = abs((int)(yy - centerSel)); if (centerDist < verticalDist) chooseCenter = true, verticalDist = centerDist, ratio = f1 / fc; } if (verticalDist >= 0 && verticalDist < pixelDist) { pixelDist = verticalDist; chooseTime = false; } } if (!chooseTime) { // PRL: Seems I need a larger tolerance to make snapping work // at top of track, not sure why if (onlyWithinSnapDistance && pixelDist >= FREQ_SNAP_DISTANCE) { SetIfNotNull(pPinValue, -1.0); return SBNone; } else if (chooseCenter) { SetIfNotNull(pPinValue, ratio); return SBCenter; } else if (mayDragWidth && fc > 0) { SetIfNotNull(pPinValue, fc); return SBWidth; } else if (chooseBottom) { SetIfNotNull(pPinValue, f1); return SBBottom; } else { SetIfNotNull(pPinValue, f0); return SBTop; } } else #endif { return boundary; } } wxCursor *SelectCursor() { static auto selectCursor = ::MakeCursor(wxCURSOR_IBEAM, IBeamCursorXpm, 17, 16); return &*selectCursor; } wxCursor *EnvelopeCursor() { // This one doubles as the center frequency cursor for spectral selection: static auto envelopeCursor = ::MakeCursor(wxCURSOR_ARROW, EnvCursorXpm, 16, 16); return &*envelopeCursor; } void SetTipAndCursorForBoundary (SelectionBoundary boundary, bool frequencySnapping, wxString &tip, wxCursor *&pCursor) { static wxCursor adjustLeftSelectionCursor{ wxCURSOR_POINT_LEFT }; static wxCursor adjustRightSelectionCursor{ wxCURSOR_POINT_RIGHT }; static auto bottomFrequencyCursor = ::MakeCursor(wxCURSOR_ARROW, BottomFrequencyCursorXpm, 16, 16); static auto topFrequencyCursor = ::MakeCursor(wxCURSOR_ARROW, TopFrequencyCursorXpm, 16, 16); static auto bandWidthCursor = ::MakeCursor(wxCURSOR_ARROW, BandWidthCursorXpm, 16, 16); switch (boundary) { case SBNone: pCursor = SelectCursor(); break; case SBLeft: tip = _("Click and drag to move left selection boundary."); pCursor = &adjustLeftSelectionCursor; break; case SBRight: tip = _("Click and drag to move right selection boundary."); pCursor = &adjustRightSelectionCursor; break; #ifdef EXPERIMENTAL_SPECTRAL_EDITING case SBBottom: tip = _("Click and drag to move bottom selection frequency."); pCursor = &*bottomFrequencyCursor; break; case SBTop: tip = _("Click and drag to move top selection frequency."); pCursor = &*topFrequencyCursor; break; case SBCenter: { #ifndef SPECTRAL_EDITING_ESC_KEY tip = frequencySnapping ? _("Click and drag to move center selection frequency to a spectral peak.") : _("Click and drag to move center selection frequency."); #else shiftDown; tip = _("Click and drag to move center selection frequency."); #endif pCursor = EnvelopeCursor(); } break; case SBWidth: tip = _("Click and drag to adjust frequency bandwidth."); pCursor = &*bandWidthCursor; break; #endif default: wxASSERT(false); } // switch // Falls through the switch if there was no boundary found. } } UIHandlePtr SelectHandle::HitTest (std::weak_ptr<SelectHandle> &holder, const TrackPanelMouseState &st, const AudacityProject *pProject, const std::shared_ptr<Track> &pTrack) { // This handle is a little special because there may be some state to // preserve during movement before the click. auto old = holder.lock(); bool oldUseSnap = true; if (old) { // It should not have started listening to timer events if( old->mTimerHandler ) { wxASSERT(false); // Handle this eventuality anyway, don't leave a dangling back-pointer // in the attached event handler. old->mTimerHandler.reset(); } oldUseSnap = old->mUseSnap; } const auto &viewInfo = ViewInfo::Get( *pProject ); auto result = std::make_shared<SelectHandle>( pTrack, oldUseSnap, TrackList::Get( *pProject ), st, viewInfo ); result = AssignUIHandlePtr(holder, result); //Make sure we are within the selected track // Adjusting the selection edges can be turned off in // the preferences... if (!pTrack->GetSelected() || !viewInfo.bAdjustSelectionEdges) { return result; } { const wxRect &rect = st.rect; wxInt64 leftSel = viewInfo.TimeToPosition(viewInfo.selectedRegion.t0(), rect.x); wxInt64 rightSel = viewInfo.TimeToPosition(viewInfo.selectedRegion.t1(), rect.x); // Something is wrong if right edge comes before left edge wxASSERT(!(rightSel < leftSel)); static_cast<void>(leftSel); // Suppress unused variable warnings if not in debug-mode static_cast<void>(rightSel); } return result; } UIHandle::Result SelectHandle::NeedChangeHighlight (const SelectHandle &oldState, const SelectHandle &newState) { auto useSnap = oldState.mUseSnap; // This is guaranteed when constructing the NEW handle: wxASSERT( useSnap == newState.mUseSnap ); if (!useSnap) return 0; auto &oldSnapState = oldState.mSnapStart; auto &newSnapState = newState.mSnapStart; if ( oldSnapState.Snapped() == newSnapState.Snapped() && (!oldSnapState.Snapped() || oldSnapState.outCoord == newSnapState.outCoord) ) return 0; return RefreshCode::RefreshAll; } SelectHandle::SelectHandle ( const std::shared_ptr<Track> &pTrack, bool useSnap, const TrackList &trackList, const TrackPanelMouseState &st, const ViewInfo &viewInfo ) : mpTrack{ pTrack } , mSnapManager{ std::make_shared<SnapManager>(&trackList, &viewInfo) } { const wxMouseState &state = st.state; mRect = st.rect; auto time = std::max(0.0, viewInfo.PositionToTime(state.m_x, mRect.x)); mSnapStart = mSnapManager->Snap(pTrack.get(), time, false); if (mSnapStart.snappedPoint) mSnapStart.outCoord += mRect.x; else mSnapStart.outCoord = -1; mUseSnap = useSnap; } SelectHandle::~SelectHandle() { } namespace { // Is the distance between A and B less than D? template < class A, class B, class DIST > bool within(A a, B b, DIST d) { return (a > b - d) && (a < b + d); } inline double findMaxRatio(double center, double rate) { const double minFrequency = 1.0; const double maxFrequency = (rate / 2.0); const double frequency = std::min(maxFrequency, std::max(minFrequency, center)); return std::min(frequency / minFrequency, maxFrequency / frequency); } } void SelectHandle::Enter(bool) { SetUseSnap(true); } void SelectHandle::SetUseSnap(bool use) { mUseSnap = use; bool hasSnap = HasSnap(); if (hasSnap) // Repaint to turn the snap lines on or off mChangeHighlight = RefreshCode::RefreshAll; if (IsClicked()) { // Readjust the moving selection end AssignSelection( ViewInfo::Get( *::GetActiveProject() ), mUseSnap ? mSnapEnd.outTime : mSnapEnd.timeSnappedTime, nullptr); mChangeHighlight |= RefreshCode::UpdateSelection; } } bool SelectHandle::HasSnap() const { return (IsClicked() ? mSnapEnd : mSnapStart).snappedPoint; } bool SelectHandle::HasEscape() const { return HasSnap() && mUseSnap; } bool SelectHandle::Escape() { if (SelectHandle::HasEscape()) { SetUseSnap(false); return true; } return false; } UIHandle::Result SelectHandle::Click (const TrackPanelMouseEvent &evt, AudacityProject *pProject) { /// This method gets called when we're handling selection /// and the mouse was just clicked. using namespace RefreshCode; wxMouseEvent &event = evt.event; const auto sTrack = TrackList::Get( *pProject ).Lock(mpTrack); const auto pTrack = sTrack.get(); auto &viewInfo = ViewInfo::Get( *pProject ); mMostRecentX = event.m_x; mMostRecentY = event.m_y; auto &trackPanel = TrackPanel::Get( *pProject ); bool selectChange = ( event.LeftDown() && event.ControlDown() && pTrack->TypeSwitch<bool>( [&](LabelTrack *){ // We should reach this, only in default of other hits on glyphs or // text boxes. bool bShift = event.ShiftDown(); bool unsafe = ProjectAudioIO::Get( *pProject ).IsAudioActive(); SelectUtilities::DoListSelection( *pProject, pTrack, bShift, true, !unsafe); return true; } ) ); if ( selectChange ) // Do not start a drag return RefreshAll | Cancelled; auto &selectionState = SelectionState::Get( *pProject ); const auto &settings = ProjectSettings::Get( *pProject ); if (event.LeftDClick() && !event.ShiftDown()) { auto &trackList = TrackList::Get( *pProject ); // Deselect all other tracks and select this one. selectionState.SelectNone( trackList ); selectionState.SelectTrack( *pTrack, true, true ); // Default behavior: select whole track SelectionState::SelectTrackLength ( viewInfo, *pTrack, settings.IsSyncLocked() ); // Special case: if we're over a clip in a WaveTrack, // select just that clip pTrack->TypeSwitch( [&] ( WaveTrack *wt ) { WaveClip *const selectedClip = wt->GetClipAtX(event.m_x); if (selectedClip) { viewInfo.selectedRegion.setTimes( selectedClip->GetOffset(), selectedClip->GetEndTime()); } } ); ProjectHistory::Get( *pProject ).ModifyState(false); // Do not start a drag return RefreshAll | UpdateSelection | Cancelled; } else if (!event.LeftDown()) return Cancelled; mInitialSelection = viewInfo.selectedRegion; auto &trackList = TrackList::Get( *pProject ); mSelectionStateChanger = std::make_shared< SelectionStateChanger >( selectionState, trackList ); mSelectionBoundary = 0; bool bShiftDown = event.ShiftDown(); bool bCtrlDown = event.ControlDown(); mSelStart = mUseSnap ? mSnapStart.outTime : mSnapStart.timeSnappedTime; auto xx = viewInfo.TimeToPosition(mSelStart, mRect.x); // I. Shift-click adjusts an existing selection if (bShiftDown || bCtrlDown) { if (bShiftDown) selectionState.ChangeSelectionOnShiftClick( trackList, *pTrack ); if( bCtrlDown ){ //Commented out bIsSelected toggles, as in Track Control Panel. //bool bIsSelected = pTrack->GetSelected(); //Actual bIsSelected will always add. bool bIsSelected = false; // Don't toggle away the last selected track. if( !bIsSelected || trackPanel.GetSelectedTrackCount() > 1 ) selectionState.SelectTrack( *pTrack, !bIsSelected, true ); } double value; // Shift-click, choose closest boundary SelectionBoundary boundary = ChooseBoundary(viewInfo, xx, event.m_y, pTrack, mRect, false, false, &value); mSelectionBoundary = boundary; switch (boundary) { case SBLeft: case SBRight: { #ifdef EXPERIMENTAL_SPECTRAL_EDITING // If drag starts, change time selection only // (also exit frequency snapping) mFreqSelMode = FREQ_SEL_INVALID; #endif mSelStartValid = true; mSelStart = value; mSnapStart = SnapResults{}; AdjustSelection(pProject, viewInfo, event.m_x, mRect.x, pTrack); break; } #ifdef EXPERIMENTAL_SPECTRAL_EDITING case SBBottom: case SBTop: { mFreqSelTrack = pTrack->SharedPointer<const WaveTrack>(); mFreqSelPin = value; mFreqSelMode = (boundary == SBBottom) ? FREQ_SEL_BOTTOM_FREE : FREQ_SEL_TOP_FREE; // Drag frequency only, not time: mSelStartValid = false; AdjustFreqSelection( static_cast<WaveTrack*>(pTrack), viewInfo, event.m_y, mRect.y, mRect.height); break; } case SBCenter: { const auto wt = static_cast<const WaveTrack*>(pTrack); HandleCenterFrequencyClick(viewInfo, true, wt, value); break; } #endif default: wxASSERT(false); }; // For persistence of the selection change: ProjectHistory::Get( *pProject ).ModifyState(false); // Get timer events so we can auto-scroll Connect(pProject); // Full refresh since the label area may need to indicate // newly selected tracks. return RefreshAll | UpdateSelection; } // II. Unmodified click starts a NEW selection //Make sure you are within the selected track bool startNewSelection = true; if (pTrack && pTrack->GetSelected()) { // Adjusting selection edges can be turned off in the // preferences now if (viewInfo.bAdjustSelectionEdges) { #ifdef EXPERIMENTAL_SPECTRAL_EDITING if (mFreqSelMode == FREQ_SEL_SNAPPING_CENTER && isSpectralSelectionTrack(pTrack)) { // This code is no longer reachable, but it had a place in the // spectral selection prototype. It used to be that you could be // in a center-frequency-snapping mode that was not a mouse drag // but responded to mouse movements. Click exited that and dragged // width instead. PRL. // Ignore whether we are inside the time selection. // Exit center-snapping, start dragging the width. mFreqSelMode = FREQ_SEL_PINNED_CENTER; mFreqSelTrack = pTrack->SharedPointer<const WaveTrack>(); mFreqSelPin = viewInfo.selectedRegion.fc(); // Do not adjust time boundaries mSelStartValid = false; AdjustFreqSelection( static_cast<WaveTrack*>(pTrack), viewInfo, event.m_y, mRect.y, mRect.height); // For persistence of the selection change: ProjectHistory::Get( *pProject ).ModifyState(false); mSelectionBoundary = SBWidth; return UpdateSelection; } else #endif { // Not shift-down, choose boundary only within snapping double value; SelectionBoundary boundary = ChooseBoundary(viewInfo, xx, event.m_y, pTrack, mRect, true, true, &value); mSelectionBoundary = boundary; switch (boundary) { case SBNone: // startNewSelection remains true break; case SBLeft: case SBRight: startNewSelection = false; #ifdef EXPERIMENTAL_SPECTRAL_EDITING // Disable frequency selection mFreqSelMode = FREQ_SEL_INVALID; #endif mSelStartValid = true; mSelStart = value; mSnapStart = SnapResults{}; break; #ifdef EXPERIMENTAL_SPECTRAL_EDITING case SBBottom: case SBTop: case SBWidth: startNewSelection = false; // Disable time selection mSelStartValid = false; mFreqSelTrack = pTrack->SharedPointer<const WaveTrack>(); mFreqSelPin = value; mFreqSelMode = (boundary == SBWidth) ? FREQ_SEL_PINNED_CENTER : (boundary == SBBottom) ? FREQ_SEL_BOTTOM_FREE : FREQ_SEL_TOP_FREE; break; case SBCenter: { const auto wt = static_cast<const WaveTrack*>(pTrack); HandleCenterFrequencyClick(viewInfo, false, wt, value); startNewSelection = false; break; } #endif default: wxASSERT(false); } } } // bAdjustSelectionEdges } // III. Common case for starting a NEW selection if (startNewSelection) { // If we didn't move a selection boundary, start a NEW selection selectionState.SelectNone( trackList ); #ifdef EXPERIMENTAL_SPECTRAL_EDITING StartFreqSelection (viewInfo, event.m_y, mRect.y, mRect.height, pTrack); #endif StartSelection(pProject); selectionState.SelectTrack( *pTrack, true, true ); trackPanel.SetFocusedTrack(pTrack); //On-Demand: check to see if there is an OD thing associated with this track. pTrack->TypeSwitch( [&](WaveTrack *wt) { if(ODManager::IsInstanceCreated()) ODManager::Instance()->DemandTrackUpdate(wt,mSelStart); }); Connect(pProject); return RefreshAll | UpdateSelection; } else { Connect(pProject); return RefreshAll; } } UIHandle::Result SelectHandle::Drag (const TrackPanelMouseEvent &evt, AudacityProject *pProject) { using namespace RefreshCode; auto &viewInfo = ViewInfo::Get( *pProject ); const wxMouseEvent &event = evt.event; int x = mAutoScrolling ? mMostRecentX : event.m_x; int y = mAutoScrolling ? mMostRecentY : event.m_y; mMostRecentX = x; mMostRecentY = y; /// AS: If we're dragging to adjust a selection (or actually, /// if the screen is scrolling while you're selecting), we /// handle it here. // Fuhggeddaboudit if we're not dragging and not autoscrolling. if (!event.Dragging() && !mAutoScrolling) return RefreshNone; if (event.CmdDown()) { // Ctrl-drag has no meaning, fuhggeddaboudit // JKC YES it has meaning. //return RefreshNone; } // Also fuhggeddaboudit if not in a track. auto pTrack = TrackList::Get( *pProject ).Lock(mpTrack); if (!pTrack) return RefreshNone; // JKC: Logic to prevent a selection smaller than 5 pixels to // prevent accidental dragging when selecting. // (if user really wants a tiny selection, they should zoom in). // Can someone make this value of '5' configurable in // preferences? enum { minimumSizedSelection = 5 }; //measured in pixels // Might be dragging frequency bounds only, test if (mSelStartValid) { wxInt64 SelStart = viewInfo.TimeToPosition(mSelStart, mRect.x); //cvt time to pixels. // Abandon this drag if selecting < 5 pixels. if (wxLongLong(SelStart - x).Abs() < minimumSizedSelection) return RefreshNone; } if (evt.pCell) { if ( auto clickedTrack = static_cast<CommonTrackPanelCell*>(evt.pCell.get())->FindTrack() ) { // Handle which tracks are selected Track *sTrack = pTrack.get(); Track *eTrack = clickedTrack.get(); auto &trackList = TrackList::Get( *pProject ); if ( sTrack && eTrack && !event.ControlDown() ) { auto &selectionState = SelectionState::Get( *pProject ); selectionState.SelectRangeOfTracks( trackList, *sTrack, *eTrack ); } #ifdef EXPERIMENTAL_SPECTRAL_EDITING #ifndef SPECTRAL_EDITING_ESC_KEY if (mFreqSelMode == FREQ_SEL_SNAPPING_CENTER && !viewInfo.selectedRegion.isPoint()) MoveSnappingFreqSelection (pProject, viewInfo, y, mRect.y, mRect.height, pTrack.get()); else #endif if ( TrackList::Get( *pProject ).Lock(mFreqSelTrack) == pTrack ) AdjustFreqSelection( static_cast<WaveTrack*>(pTrack.get()), viewInfo, y, mRect.y, mRect.height); #endif AdjustSelection(pProject, viewInfo, x, mRect.x, clickedTrack.get()); } } return RefreshNone // If scrubbing does not use the helper poller thread, then // don't refresh at every mouse event, because it slows down seek-scrub. // Instead, let OnTimer do it, which is often enough. // And even if scrubbing does use the thread, then skipping refresh does not // bring that advantage, but it is probably still a good idea anyway. // | UpdateSelection ; } HitTestPreview SelectHandle::Preview (const TrackPanelMouseState &st, const AudacityProject *pProject) { if (!HasSnap() && !mUseSnap) // Moved out of snapping; revert to un-escaped state mUseSnap = true; auto pTrack = mpTrack.lock(); if (!pTrack) return {}; wxString tip; wxCursor *pCursor = SelectCursor(); if ( IsClicked() ) // Use same cursor as at the clck SetTipAndCursorForBoundary (SelectionBoundary(mSelectionBoundary), (mFreqSelMode == FREQ_SEL_SNAPPING_CENTER), tip, pCursor); else { // Choose one of many cursors for mouse-over auto &viewInfo = ViewInfo::Get( *pProject ); auto &state = st.state; auto time = mUseSnap ? mSnapStart.outTime : mSnapStart.timeSnappedTime; auto xx = viewInfo.TimeToPosition(time, mRect.x); const bool bMultiToolMode = (ToolCodes::multiTool == ProjectSettings::Get( *pProject ).GetTool()); //In Multi-tool mode, give multitool prompt if no-special-hit. if (bMultiToolMode) { // Look up the current key binding for Preferences. // (Don't assume it's the default!) auto keyStr = CommandManager::Get( *pProject ).GetKeyFromName(wxT("Preferences")) .Display( true ); if (keyStr.empty()) // No keyboard preference defined for opening Preferences dialog /* i18n-hint: These are the names of a menu and a command in that menu */ keyStr = _("Edit, Preferences..."); /* i18n-hint: %s is usually replaced by "Ctrl+P" for Windows/Linux, "Command+," for Mac */ tip = wxString::Format( _("Multi-Tool Mode: %s for Mouse and Keyboard Preferences."), keyStr); // Later in this function we may point to some other string instead. if (!pTrack->GetSelected() || !viewInfo.bAdjustSelectionEdges) ; else { const wxRect &rect = st.rect; const bool bShiftDown = state.ShiftDown(); const bool bCtrlDown = state.ControlDown(); const bool bModifierDown = bShiftDown || bCtrlDown; // If not shift-down and not snapping center, then // choose boundaries only in snapping tolerance, // and may choose center. SelectionBoundary boundary = ChooseBoundary(viewInfo, xx, state.m_y, pTrack.get(), rect, !bModifierDown, !bModifierDown); SetTipAndCursorForBoundary(boundary, !bShiftDown, tip, pCursor); } } #if 0 // This is a vestige of an idea in the prototype version. // Center would snap without mouse button down, click would pin the center // and drag width. #ifdef EXPERIMENTAL_SPECTRAL_EDITING if ((mFreqSelMode == FREQ_SEL_SNAPPING_CENTER) && isSpectralSelectionTrack(pTrack)) { // Not shift-down, but center frequency snapping toggle is on tip = _("Click and drag to set frequency bandwidth."); pCursor = &*envelopeCursor; return {}; } #endif #endif if (!pTrack->GetSelected() || !viewInfo.bAdjustSelectionEdges) ; else { const wxRect &rect = st.rect; const bool bShiftDown = state.ShiftDown(); const bool bCtrlDown = state.ControlDown(); const bool bModifierDown = bShiftDown || bCtrlDown; SelectionBoundary boundary = ChooseBoundary( viewInfo, xx, state.m_y, pTrack.get(), rect, !bModifierDown, !bModifierDown); SetTipAndCursorForBoundary(boundary, !bShiftDown, tip, pCursor); } MaySetOnDemandTip(pTrack.get(), tip); } if (tip.empty()) { tip = _("Click and drag to select audio"); } if (HasEscape() && mUseSnap) { tip += wxT(" ") + /* i18n-hint: "Snapping" means automatic alignment of selection edges to any nearby label or clip boundaries */ _("(snapping)"); } return { tip, pCursor }; } UIHandle::Result SelectHandle::Release (const TrackPanelMouseEvent &, AudacityProject *pProject, wxWindow *) { using namespace RefreshCode; ProjectHistory::Get( *pProject ).ModifyState(false); mFrequencySnapper.reset(); mSnapManager.reset(); if (mSelectionStateChanger) { mSelectionStateChanger->Commit(); mSelectionStateChanger.reset(); } if (mUseSnap && (mSnapStart.outCoord != -1 || mSnapEnd.outCoord != -1)) return RefreshAll; else return RefreshNone; } UIHandle::Result SelectHandle::Cancel(AudacityProject *pProject) { mSelectionStateChanger.reset(); ViewInfo::Get( *pProject ).selectedRegion = mInitialSelection; return RefreshCode::RefreshAll; } void SelectHandle::Draw( TrackPanelDrawingContext &context, const wxRect &rect, unsigned iPass ) { if ( iPass == TrackArtist::PassSnapping ) { auto &dc = context.dc; // Draw snap guidelines if we have any if ( mSnapManager ) { auto coord1 = (mUseSnap || IsClicked()) ? mSnapStart.outCoord : -1; auto coord2 = (!mUseSnap || !IsClicked()) ? -1 : mSnapEnd.outCoord; mSnapManager->Draw( &dc, coord1, coord2 ); } } } wxRect SelectHandle::DrawingArea( const wxRect &rect, const wxRect &panelRect, unsigned iPass ) { if ( iPass == TrackArtist::PassSnapping ) return MaximizeHeight( rect, panelRect ); else return rect; } void SelectHandle::Connect(AudacityProject *pProject) { mTimerHandler = std::make_shared<TimerHandler>( this, pProject ); } class SelectHandle::TimerHandler : public wxEvtHandler { public: TimerHandler( SelectHandle *pParent, AudacityProject *pProject ) : mParent{ pParent } , mConnectedProject{ pProject } { if (mConnectedProject) mConnectedProject->Bind(EVT_TRACK_PANEL_TIMER, &SelectHandle::TimerHandler::OnTimer, this); } // Receives timer event notifications, to implement auto-scroll void OnTimer(wxCommandEvent &event); private: SelectHandle *mParent; AudacityProject *mConnectedProject; }; void SelectHandle::TimerHandler::OnTimer(wxCommandEvent &event) { event.Skip(); // AS: If the user is dragging the mouse and there is a track that // has captured the mouse, then scroll the screen, as necessary. /// We check on each timer tick to see if we need to scroll. // DM: If we're "autoscrolling" (which means that we're scrolling // because the user dragged from inside to outside the window, // not because the user clicked in the scroll bar), then // the selection code needs to be handled slightly differently. // We set this flag ("mAutoScrolling") to tell the selecting // code that we didn't get here as a result of a mouse event, // and therefore it should ignore the event, // and instead use the last known mouse position. Setting // this flag also causes the Mac to redraw immediately rather // than waiting for the next update event; this makes scrolling // smoother on MacOS 9. const auto project = mConnectedProject; const auto &trackPanel = TrackPanel::Get( *project ); auto &window = ProjectWindow::Get( *project ); if (mParent->mMostRecentX >= mParent->mRect.x + mParent->mRect.width) { mParent->mAutoScrolling = true; window.TP_ScrollRight(); } else if (mParent->mMostRecentX < mParent->mRect.x) { mParent->mAutoScrolling = true; window.TP_ScrollLeft(); } else { // Bug1387: enable autoscroll during drag, if the pointer is at either // extreme x coordinate of the screen, even if that is still within the // track area. int xx = mParent->mMostRecentX, yy = 0; trackPanel.ClientToScreen(&xx, &yy); if (xx == 0) { mParent->mAutoScrolling = true; window.TP_ScrollLeft(); } else { int width, height; ::wxDisplaySize(&width, &height); if (xx == width - 1) { mParent->mAutoScrolling = true; window.TP_ScrollRight(); } } } auto pTrack = mParent->mpTrack.lock(); // TrackList::Lock() ? if (mParent->mAutoScrolling && pTrack) { // AS: To keep the selection working properly as we scroll, // we fake a mouse event (remember, this method is called // from a timer tick). // AS: For some reason, GCC won't let us pass this directly. wxMouseEvent evt(wxEVT_MOTION); const auto size = trackPanel.GetSize(); mParent->Drag( TrackPanelMouseEvent{ evt, mParent->mRect, size, TrackView::Get( *pTrack ).shared_from_this() }, project ); mParent->mAutoScrolling = false; TrackPanel::Get( *mConnectedProject ).Refresh(false); } } /// Reset our selection markers. void SelectHandle::StartSelection( AudacityProject *pProject ) { auto &viewInfo = ViewInfo::Get( *pProject ); mSelStartValid = true; viewInfo.selectedRegion.setTimes(mSelStart, mSelStart); // PRL: commented out the Sonify stuff with the TrackPanel refactor. // It was no-op anyway. //SonifyBeginModifyState(); ProjectHistory::Get( *pProject ).ModifyState(false); //SonifyEndModifyState(); } /// Extend or contract the existing selection void SelectHandle::AdjustSelection (AudacityProject *pProject, ViewInfo &viewInfo, int mouseXCoordinate, int trackLeftEdge, Track *track) { if (!mSelStartValid) // Must be dragging frequency bounds only. return; double selend = std::max(0.0, viewInfo.PositionToTime(mouseXCoordinate, trackLeftEdge)); double origSelend = selend; auto pTrack = Track::SharedPointer( track ); if (!pTrack) pTrack = TrackList::Get( *pProject ).Lock(mpTrack); if (pTrack && mSnapManager.get()) { bool rightEdge = (selend > mSelStart); mSnapEnd = mSnapManager->Snap(pTrack.get(), selend, rightEdge); if (mSnapEnd.Snapped()) { if (mUseSnap) selend = mSnapEnd.outTime; if (mSnapEnd.snappedPoint) mSnapEnd.outCoord += trackLeftEdge; } if (!mSnapEnd.snappedPoint) mSnapEnd.outCoord = -1; // Check if selection endpoints are too close together to snap (unless // using snap-to-time -- then we always accept the snap results) if (mSnapStart.outCoord >= 0 && mSnapEnd.outCoord >= 0 && std::abs(mSnapStart.outCoord - mSnapEnd.outCoord) < 3) { if(!mSnapEnd.snappedTime) selend = origSelend; mSnapEnd.outCoord = -1; } } AssignSelection(viewInfo, selend, pTrack.get()); } void SelectHandle::AssignSelection (ViewInfo &viewInfo, double selend, Track *pTrack) { double sel0, sel1; if (mSelStart < selend) { sel0 = mSelStart; sel1 = selend; } else { sel1 = mSelStart; sel0 = selend; } viewInfo.selectedRegion.setTimes(sel0, sel1); //On-Demand: check to see if there is an OD thing associated with this track. If so we want to update the focal point for the task. if (pTrack && ODManager::IsInstanceCreated()) pTrack->TypeSwitch( [&](WaveTrack *wt) { ODManager::Instance()->DemandTrackUpdate(wt, sel0); //sel0 is sometimes less than mSelStart }); } void SelectHandle::StartFreqSelection(ViewInfo &viewInfo, int mouseYCoordinate, int trackTopEdge, int trackHeight, Track *pTrack) { mFreqSelTrack.reset(); mFreqSelMode = FREQ_SEL_INVALID; mFreqSelPin = SelectedRegion::UndefinedFrequency; if (isSpectralSelectionTrack(pTrack)) { // Spectral selection track is always wave auto shTrack = pTrack->SharedPointer<const WaveTrack>(); mFreqSelTrack = shTrack; mFreqSelMode = FREQ_SEL_FREE; mFreqSelPin = PositionToFrequency(shTrack.get(), false, mouseYCoordinate, trackTopEdge, trackHeight); viewInfo.selectedRegion.setFrequencies(mFreqSelPin, mFreqSelPin); } } void SelectHandle::AdjustFreqSelection( const WaveTrack *wt, ViewInfo &viewInfo, int mouseYCoordinate, int trackTopEdge, int trackHeight) { if (mFreqSelMode == FREQ_SEL_INVALID || mFreqSelMode == FREQ_SEL_SNAPPING_CENTER) return; // Extension happens only when dragging in the same track in which we // started, and that is of a spectrogram display type. const double rate = wt->GetRate(); const double frequency = PositionToFrequency(wt, true, mouseYCoordinate, trackTopEdge, trackHeight); // Dragging center? if (mFreqSelMode == FREQ_SEL_DRAG_CENTER) { if (frequency == rate || frequency < 1.0) // snapped to top or bottom viewInfo.selectedRegion.setFrequencies( SelectedRegion::UndefinedFrequency, SelectedRegion::UndefinedFrequency); else { // mFreqSelPin holds the ratio of top to center const double maxRatio = findMaxRatio(frequency, rate); const double ratio = std::min(maxRatio, mFreqSelPin); viewInfo.selectedRegion.setFrequencies( frequency / ratio, frequency * ratio); } } else if (mFreqSelMode == FREQ_SEL_PINNED_CENTER) { if (mFreqSelPin >= 0) { // Change both upper and lower edges leaving centre where it is. if (frequency == rate || frequency < 1.0) // snapped to top or bottom viewInfo.selectedRegion.setFrequencies( SelectedRegion::UndefinedFrequency, SelectedRegion::UndefinedFrequency); else { // Given center and mouse position, find ratio of the larger to the // smaller, limit that to the frequency scale bounds, and adjust // top and bottom accordingly. const double maxRatio = findMaxRatio(mFreqSelPin, rate); double ratio = frequency / mFreqSelPin; if (ratio < 1.0) ratio = 1.0 / ratio; ratio = std::min(maxRatio, ratio); viewInfo.selectedRegion.setFrequencies( mFreqSelPin / ratio, mFreqSelPin * ratio); } } } else { // Dragging of upper or lower. const bool bottomDefined = !(mFreqSelMode == FREQ_SEL_TOP_FREE && mFreqSelPin < 0); const bool topDefined = !(mFreqSelMode == FREQ_SEL_BOTTOM_FREE && mFreqSelPin < 0); if (!bottomDefined || (topDefined && mFreqSelPin < frequency)) { // Adjust top if (frequency == rate) // snapped high; upper frequency is undefined viewInfo.selectedRegion.setF1(SelectedRegion::UndefinedFrequency); else viewInfo.selectedRegion.setF1(std::max(1.0, frequency)); viewInfo.selectedRegion.setF0(mFreqSelPin); } else { // Adjust bottom if (frequency < 1.0) // snapped low; lower frequency is undefined viewInfo.selectedRegion.setF0(SelectedRegion::UndefinedFrequency); else viewInfo.selectedRegion.setF0(std::min(rate / 2.0, frequency)); viewInfo.selectedRegion.setF1(mFreqSelPin); } } } void SelectHandle::HandleCenterFrequencyClick (const ViewInfo &viewInfo, bool shiftDown, const WaveTrack *pTrack, double value) { if (shiftDown) { // Disable time selection mSelStartValid = false; mFreqSelTrack = pTrack->SharedPointer<const WaveTrack>(); mFreqSelPin = value; mFreqSelMode = FREQ_SEL_DRAG_CENTER; } else { #ifndef SPECTRAL_EDITING_ESC_KEY // Start center snapping // Turn center snapping on (the only way to do this) mFreqSelMode = FREQ_SEL_SNAPPING_CENTER; // Disable time selection mSelStartValid = false; mFrequencySnapper = std::make_shared<SpectrumAnalyst>(); StartSnappingFreqSelection(*mFrequencySnapper, viewInfo, pTrack); #endif } } void SelectHandle::StartSnappingFreqSelection (SpectrumAnalyst &analyst, const ViewInfo &viewInfo, const WaveTrack *pTrack) { static const size_t minLength = 8; const double rate = pTrack->GetRate(); // Grab samples, just for this track, at these times std::vector<float> frequencySnappingData; const auto start = pTrack->TimeToLongSamples(viewInfo.selectedRegion.t0()); const auto end = pTrack->TimeToLongSamples(viewInfo.selectedRegion.t1()); const auto length = std::min(frequencySnappingData.max_size(), limitSampleBufferSize(10485760, // as in FreqWindow.cpp end - start)); const auto effectiveLength = std::max(minLength, length); frequencySnappingData.resize(effectiveLength, 0.0f); pTrack->Get( reinterpret_cast<samplePtr>(&frequencySnappingData[0]), floatSample, start, length, fillZero, // Don't try to cope with exceptions, just read zeroes instead. false); // Use same settings as are now used for spectrogram display, // except, shrink the window as needed so we get some answers const SpectrogramSettings &settings = pTrack->GetSpectrogramSettings(); auto windowSize = settings.GetFFTLength(); while(windowSize > effectiveLength) windowSize >>= 1; const int windowType = settings.windowType; analyst.Calculate( SpectrumAnalyst::Spectrum, windowType, windowSize, rate, &frequencySnappingData[0], length); // We can now throw away the sample data but we keep the spectrum. } void SelectHandle::MoveSnappingFreqSelection (AudacityProject *pProject, ViewInfo &viewInfo, int mouseYCoordinate, int trackTopEdge, int trackHeight, Track *pTrack) { if (pTrack && pTrack->GetSelected() && isSpectralSelectionTrack(pTrack)) { // Spectral selection track is always wave WaveTrack *const wt = static_cast<WaveTrack*>(pTrack); // PRL: // What would happen if center snapping selection began in one spectrogram track, // then continues inside another? We do not then recalculate // the spectrum (as was done in StartSnappingFreqSelection) // but snap according to the peaks in the old track. // But if we always supply the original clicked track here that doesn't matter. const double rate = wt->GetRate(); const double frequency = PositionToFrequency(wt, false, mouseYCoordinate, trackTopEdge, trackHeight); const double snappedFrequency = mFrequencySnapper->FindPeak(frequency, NULL); const double maxRatio = findMaxRatio(snappedFrequency, rate); double ratio = 2.0; // An arbitrary octave on each side, at most { const double f0 = viewInfo.selectedRegion.f0(); const double f1 = viewInfo.selectedRegion.f1(); if (f1 >= f0 && f0 >= 0) // Preserve already chosen ratio instead ratio = sqrt(f1 / f0); } ratio = std::min(ratio, maxRatio); mFreqSelPin = snappedFrequency; viewInfo.selectedRegion.setFrequencies( snappedFrequency / ratio, snappedFrequency * ratio); // A change here would affect what AdjustFreqSelection() does // in the prototype version where you switch from moving center to // dragging width with a click. No effect now. mFreqSelTrack = wt->SharedPointer<const WaveTrack>(); // SelectNone(); // SelectTrack(pTrack, true); TrackPanel::Get( *pProject ).SetFocusedTrack(pTrack); } } void SelectHandle::SnapCenterOnce (SpectrumAnalyst &analyst, ViewInfo &viewInfo, const WaveTrack *pTrack, bool up) { const SpectrogramSettings &settings = pTrack->GetSpectrogramSettings(); const auto windowSize = settings.GetFFTLength(); const double rate = pTrack->GetRate(); const double nyq = rate / 2.0; const double binFrequency = rate / windowSize; double f1 = viewInfo.selectedRegion.f1(); double centerFrequency = viewInfo.selectedRegion.fc(); if (centerFrequency <= 0) { centerFrequency = up ? binFrequency : nyq; f1 = centerFrequency * sqrt(2.0); } double ratio = f1 / centerFrequency; const int originalBin = floor(0.5 + centerFrequency / binFrequency); const int limitingBin = up ? floor(0.5 + nyq / binFrequency) : 1; // This is crude and wasteful, doing the FFT each time the command is called. // It would be better to cache the data, but then invalidation of the cache would // need doing in all places that change the time selection. StartSnappingFreqSelection(analyst, viewInfo, pTrack); double snappedFrequency = centerFrequency; int bin = originalBin; if (up) { while (snappedFrequency <= centerFrequency && bin < limitingBin) snappedFrequency = analyst.FindPeak(++bin * binFrequency, NULL); } else { while (snappedFrequency >= centerFrequency && bin > limitingBin) snappedFrequency = analyst.FindPeak(--bin * binFrequency, NULL); } // PRL: added these two lines with the big TrackPanel refactor const double maxRatio = findMaxRatio(snappedFrequency, rate); ratio = std::min(ratio, maxRatio); viewInfo.selectedRegion.setFrequencies (snappedFrequency / ratio, snappedFrequency * ratio); } #if 0 // unused void SelectHandle::ResetFreqSelectionPin (const ViewInfo &viewInfo, double hintFrequency, bool logF) { switch (mFreqSelMode) { case FREQ_SEL_INVALID: case FREQ_SEL_SNAPPING_CENTER: mFreqSelPin = -1.0; break; case FREQ_SEL_PINNED_CENTER: mFreqSelPin = viewInfo.selectedRegion.fc(); break; case FREQ_SEL_DRAG_CENTER: { // Re-pin the width const double f0 = viewInfo.selectedRegion.f0(); const double f1 = viewInfo.selectedRegion.f1(); if (f0 >= 0 && f1 >= 0) mFreqSelPin = sqrt(f1 / f0); else mFreqSelPin = -1.0; } break; case FREQ_SEL_FREE: // Pin which? Farther from the hint which is the presumed // mouse position. { // If this function finds use again, the following should be // generalized using NumberScale const double f0 = viewInfo.selectedRegion.f0(); const double f1 = viewInfo.selectedRegion.f1(); if (logF) { if (f1 < 0) mFreqSelPin = f0; else { const double logf1 = log(std::max(1.0, f1)); const double logf0 = log(std::max(1.0, f0)); const double logHint = log(std::max(1.0, hintFrequency)); if (std::abs(logHint - logf1) < std::abs(logHint - logf0)) mFreqSelPin = f0; else mFreqSelPin = f1; } } else { if (f1 < 0 || std::abs(hintFrequency - f1) < std::abs(hintFrequency - f0)) mFreqSelPin = f0; else mFreqSelPin = f1; } } break; case FREQ_SEL_TOP_FREE: mFreqSelPin = viewInfo.selectedRegion.f0(); break; case FREQ_SEL_BOTTOM_FREE: mFreqSelPin = viewInfo.selectedRegion.f1(); break; default: wxASSERT(false); } } #endif
51,908
16,047
/// Copyright (c) 2020 xiw /// /// MIT License /// \author Wang Xi #include "logging/log_stream.h" #include <thread> #include <sstream> namespace logging { void LogStream::buf(char** p_buf, size_t* size) { *p_buf = buf_; *size = buf_pointer_; } LogStream &LogStream::operator<<(bool arg) { if(arg) append("true"); else append("false"); return *this; } LogStream &LogStream::operator<<(char arg) { char str[2] = {arg,'\0'}; append(str); return *this; } LogStream &LogStream::operator<<(int16_t arg) { auto str = std::to_string(arg); append(str.c_str()); return *this; } LogStream &LogStream::operator<<(uint16_t arg) { auto str = std::to_string(arg); append(str.c_str()); return *this; } LogStream &LogStream::operator<<(int32_t arg) { auto str = std::to_string(arg); append(str.c_str()); return *this; } LogStream &LogStream::operator<<(uint32_t arg) { auto str = std::to_string(arg); append(str.c_str()); return *this; } LogStream &LogStream::operator<<(int64_t arg) { auto str = std::to_string(arg); append(str.c_str()); return *this; } LogStream &LogStream::operator<<(uint64_t arg) { auto str = std::to_string(arg); append(str.c_str()); return *this; } LogStream &LogStream::operator<<(float arg) { auto str = std::to_string(arg); append(str.c_str()); return *this; } LogStream &LogStream::operator<<(double arg) { auto str = std::to_string(arg); append(str.c_str()); return *this; } LogStream &LogStream::operator<<(const char *arg) { append(arg); return *this; } LogStream &LogStream::operator<<(const string &arg) { append(arg.c_str()); return *this; } void LogStream::append(const char *s) { auto buf_left = buf_size_ - buf_pointer_ > 0 ? buf_size_ - buf_pointer_ : 0; buf_pointer_ += ::snprintf(buf_ + buf_pointer_, buf_left, "%s", s); } /// global output std::function<void(const char*, size_t)> g_out = [](const char* buf, size_t size){ ::fwrite(buf, 1, size, ::stdout); }; /// global flush std::function<void()> g_flush = [](){ ::fflush(::stdout); }; } // namespace logging
2,114
833
#include "LFFD_ncnn.h" LFFD::LFFD(int scale_num, int num_thread_) { num_output_scales = scale_num; num_thread = num_thread_; if (num_output_scales == 5) { param_file_name = "symbol_10_320_20L_5scales_v2_deploy.param"; bin_file_name = "train_10_320_20L_5scales_v2_iter_1000000.bin"; receptive_field_list = { 20, 40, 80, 160, 320 }; receptive_field_stride = { 4, 8, 16, 32, 64 }; bbox_small_list = { 10, 20, 40, 80, 160 }; bbox_large_list = { 20, 40, 80, 160, 320 }; receptive_field_center_start = { 3, 7, 15, 31, 63 }; for (size_t i = 0; i < receptive_field_list.size(); i++) { constant.push_back(receptive_field_list[i] / 2); } output_blob_names = { "softmax0","conv8_3_bbox", "softmax1","conv11_3_bbox", "softmax2","conv14_3_bbox", "softmax3","conv17_3_bbox", "softmax4","conv20_3_bbox" }; } else if (num_output_scales == 8) { param_file_name = "symbol_10_560_25L_8scales_v1_deploy.param"; bin_file_name = "train_10_560_25L_8scales_v1_iter_1400000.bin"; receptive_field_list = { 15, 20, 40, 70, 110, 250, 400, 560 }; receptive_field_stride = { 4, 4, 8, 8, 16, 32, 32, 32 }; bbox_small_list = { 10, 15, 20, 40, 70, 110, 250, 400 }; bbox_large_list = { 15, 20, 40, 70, 110, 250, 400, 560 }; receptive_field_center_start = { 3, 3, 7, 7, 15, 31, 31, 31 }; for (size_t i = 0; i < receptive_field_list.size(); i++) { constant.push_back(receptive_field_list[i] / 2); } output_blob_names={ "softmax0","conv8_3_bbox", "softmax1","conv10_3_bbox", "softmax2","conv13_3_bbox", "softmax3","conv15_3_bbox", "softmax4","conv18_3_bbox", "softmax5","conv21_3_bbox", "softmax6","conv23_3_bbox", "softmax7","conv25_3_bbox" }; } lffd.load_param(param_file_name.data()); lffd.load_model(bin_file_name.data()); } LFFD::~LFFD() { lffd.clear(); } int LFFD::detect(ncnn::Mat& img, std::vector<FaceInfo>& face_list, int resize_h, int resize_w, float score_threshold, float nms_threshold, int top_k, std::vector<int> skip_scale_branch_list) { if (img.empty()) { std::cout << "image is empty ,please check!" << std::endl; return -1; } image_h = img.h; image_w = img.w; ncnn::Mat in; ncnn::resize_bilinear(img,in,resize_w,resize_h); float ratio_w=(float)image_w/in.w; float ratio_h=(float)image_h/in.h; ncnn::Mat ncnn_img = in; ncnn_img.substract_mean_normalize(mean_vals, norm_vals); std::vector<FaceInfo> bbox_collection; ncnn::Extractor ex = lffd.create_extractor(); ex.set_num_threads(num_thread); ex.input("data", ncnn_img); for (int i = 0; i <num_output_scales; i++) { ncnn::Mat conf; ncnn::Mat reg; ex.extract(output_blob_names[2*i].c_str(), conf); ex.extract(output_blob_names[2 * i+1].c_str(), reg); generateBBox(bbox_collection, conf, reg, score_threshold, conf.w, conf.h, in.w, in.h, i); } std::vector<FaceInfo> valid_input; get_topk_bbox(bbox_collection, valid_input, top_k); nms(valid_input, face_list, nms_threshold); for(size_t i=0;i<face_list.size();i++){ face_list[i].x1*=ratio_w; face_list[i].y1*=ratio_h; face_list[i].x2*=ratio_w; face_list[i].y2*=ratio_h; float w,h,maxSize; float cenx,ceny; w=face_list[i].x2-face_list[i].x1; h=face_list[i].y2-face_list[i].y1; maxSize = w > h ? w : h; cenx=face_list[i].x1+w/2; ceny=face_list[i].y1+h/2; face_list[i].x1=cenx-maxSize/2>0? cenx - maxSize / 2:0; face_list[i].y1=ceny-maxSize/2>0? ceny - maxSize / 2:0; face_list[i].x2=cenx+maxSize/2>image_w? image_w-1: cenx + maxSize / 2; face_list[i].y2=ceny+maxSize/2> image_h? image_h-1: ceny + maxSize / 2; } return 0; } void LFFD::generateBBox(std::vector<FaceInfo>& bbox_collection, ncnn::Mat score_map, ncnn::Mat box_map, float score_threshold, int fea_w, int fea_h, int cols, int rows, int scale_id) { float* RF_center_Xs = new float[fea_w]; float* RF_center_Xs_mat = new float[fea_w * fea_h]; float* RF_center_Ys = new float[fea_h]; float* RF_center_Ys_mat = new float[fea_h * fea_w]; for (int x = 0; x < fea_w; x++) { RF_center_Xs[x] = receptive_field_center_start[scale_id] + receptive_field_stride[scale_id] * x; } for (int x = 0; x < fea_h; x++) { for (int y = 0; y < fea_w; y++) { RF_center_Xs_mat[x * fea_w + y] = RF_center_Xs[y]; } } for (int x = 0; x < fea_h; x++) { RF_center_Ys[x] = receptive_field_center_start[scale_id] + receptive_field_stride[scale_id] * x; for (int y = 0; y < fea_w; y++) { RF_center_Ys_mat[x * fea_w + y] = RF_center_Ys[x]; } } float* x_lt_mat = new float[fea_h * fea_w]; float* y_lt_mat = new float[fea_h * fea_w]; float* x_rb_mat = new float[fea_h * fea_w]; float* y_rb_mat = new float[fea_h * fea_w]; //x-left-top float mid_value = 0; for (int j = 0; j < fea_h * fea_w; j++) { mid_value = RF_center_Xs_mat[j] - box_map.channel(0)[j] * constant[scale_id]; x_lt_mat[j] = mid_value < 0 ? 0 : mid_value; } //y-left-top for (int j = 0; j < fea_h * fea_w; j++) { mid_value = RF_center_Ys_mat[j] - box_map.channel(1)[j] * constant[scale_id]; y_lt_mat[j] = mid_value < 0 ? 0 : mid_value; } //x-right-bottom for (int j = 0; j < fea_h * fea_w; j++) { mid_value = RF_center_Xs_mat[j] - box_map.channel(2)[j] * constant[scale_id]; x_rb_mat[j] = mid_value > cols - 1 ? cols - 1 : mid_value; } //y-right-bottom for (int j = 0; j < fea_h * fea_w; j++) { mid_value = RF_center_Ys_mat[j] - box_map.channel(3)[j] * constant[scale_id]; y_rb_mat[j] = mid_value > rows - 1 ? rows - 1 : mid_value; } for (int k = 0; k < fea_h * fea_w; k++) { if (score_map.channel(0)[k] > score_threshold) { FaceInfo faceinfo; faceinfo.x1 = x_lt_mat[k]; faceinfo.y1 = y_lt_mat[k]; faceinfo.x2 = x_rb_mat[k]; faceinfo.y2 = y_rb_mat[k]; faceinfo.score = score_map[k]; faceinfo.area = (faceinfo.x2 - faceinfo.x1) * (faceinfo.y2 - faceinfo.y1); bbox_collection.push_back(faceinfo); } } delete[] RF_center_Xs; RF_center_Xs = NULL; delete[] RF_center_Ys; RF_center_Ys = NULL; delete[] RF_center_Xs_mat; RF_center_Xs_mat = NULL; delete[] RF_center_Ys_mat; RF_center_Ys_mat = NULL; delete[] x_lt_mat; x_lt_mat = NULL; delete[] y_lt_mat; y_lt_mat = NULL; delete[] x_rb_mat; x_rb_mat = NULL; delete[] y_rb_mat; y_rb_mat = NULL; } void LFFD::get_topk_bbox(std::vector<FaceInfo>& input, std::vector<FaceInfo>& output, int top_k) { std::sort(input.begin(), input.end(), [](const FaceInfo& a, const FaceInfo& b) { return a.score > b.score; }); if (input.size() > size_t(top_k)) { for (int k = 0; k < top_k; k++) { output.push_back(input[k]); } } else { output = input; } } void LFFD::nms(std::vector<FaceInfo>& input, std::vector<FaceInfo>& output, float threshold, int type) { if(input.empty()) return; std::sort(input.begin(), input.end(), [](const FaceInfo& a, const FaceInfo& b) { return a.score > b.score; }); int box_num = input.size(); std::vector<int> merged(box_num, 0); for (int i = 0; i < box_num; i++) { if (merged[i]) continue; output.push_back(input[i]); for (int j = i + 1; j < box_num; j++) { if (merged[j]) continue; float inner_x0 = input[i].x1 > input[j].x1 ? input[i].x1 : input[j].x1;//std::max(input[i].x1, input[j].x1); float inner_y0 = input[i].y1 > input[j].y1 ? input[i].y1 : input[j].y1; float inner_x1 = input[i].x2 < input[j].x2 ? input[i].x2 : input[j].x2; //bug fixed ,sorry float inner_y1 = input[i].y2 < input[j].y2 ? input[i].y2 : input[j].y2; float inner_h = inner_y1 - inner_y0 + 1; float inner_w = inner_x1 - inner_x0 + 1; if (inner_h <= 0 || inner_w <= 0) continue; float inner_area = inner_h * inner_w; float h1 = input[j].y2 - input[j].y1 + 1; float w1 = input[j].x2 - input[j].x1 + 1; float area1 = h1 * w1; float score= inner_area/area1; if (score > threshold) merged[j] = 1; } } }
8,179
3,999
/* #include<stdio.h> #include<assert.h> #include<iostream> #include<typeinfo> #include "Create.h" #include "Read.h" */ #include "core/Pipeline.h" //#include "TransformEvaluator.h" //#include "TransformEvaluate.h" #include "Source/UnboundedInMemEvaluator_Join.h" //#include "SimpleMapperEvaluator.h" #include "Join/JoinEvaluator1.h" #include "Sink/RecordBitmapBundleSinkEvaluator.h" #include <tuple> #include "test-common.h" /* * +--- SimpleMapper -- (KVPair)--\ * Unbound -(long)-> + Join --> (KVPai * +--- SimpleMapper -- (KVPair)--/ * */ /* template<class T> auto operator<<(std::ostream& os, const T& t) -> decltype(t.print(os), os) { t.print(os); return os; } */ template<class T> using BundleT = RecordBitmapBundle<T>; #ifdef DEBUG pipeline_config config = { .records_per_interval = 1000 * 1000, .target_tput = (1000 * 500), .record_size = sizeof(long), //.input_file = "/ssd/1g.txt", .input_file = "/tmp/test-digit.txt", }; #else pipeline_config config = { .records_per_interval = 1000 * 1000, //.target_tput = (10 * 1000 * 1000), .target_tput = 2000 * 1000, //k2: 2000 should be fine .record_size = sizeof(long), //.input_file = "/ssd/1g.txt", .input_file = "/tmp/test-digit.txt", }; #endif int main(int ac, char *av[]) { parse_options(ac, av, &config); print_config(); // create a new Bounded transform //UnboundedInMem<long, BundleT> unbound ("[unbounded]", 50, 0); //UnboundedInMem_Join<long, BundleT> unbound ("[unbounded]", UnboundedInMem_Join unbound ("[unbounded]", config.input_file.c_str(), config.records_per_interval , /* records per wm interval */ config.target_tput, /* target tput (rec/sec) */ config.record_size, 0 //XXX session_gap_ms = ???? ); // create a new pipeline Pipeline* p = Pipeline::create(NULL); /* vector<PCollection*> o2 = p->apply2(&unbound); o2[0]->_name = "src_out0"; o2[1]->_name = "src_out1"; SimpleMapper<long, pair<long, long>> mapper0 ("[mapper0]"); SimpleMapper<long, pair<long, long>> mapper1 ("[mapper1]"); connect_transform(unbound, mapper0); connect_transform(unbound, mapper1); */ /* old design vector<PCollection*> o2 = p->apply2(&unbound); o2[0]->_name = "src_out0"; o2[1]->_name = "src_out1"; SimpleMapper<long, pair<long, long>> mapper0 ("[mapper0]"); auto c11 = dynamic_cast<PCollection *>(o2[0]->apply1(&mapper0)); c11->_name = "mapper0_out"; mapper0.set_side_info(1); //left side SimpleMapper<long, pair<long, long>> mapper1 ("[mapper1]"); auto c12 = dynamic_cast<PCollection *>(o2[1]->apply1(&mapper1)); c12->_name = "mapper1_out"; mapper1.set_side_info(2); //right side */ PCollection *unbound_output = dynamic_cast<PCollection *>(p->apply1(&unbound)); unbound_output->_name = "unbound_output"; Join<pair<long,long>> join("[join]", seconds(1)); auto c2 = dynamic_cast<PCollection *>(unbound_output->apply1(&join)); //auto c3 = dynamic_cast<PCollection *>(c12->apply1(&join)); ///c2 = c2; //assert(c2 == c3); // same output. join.set_side_info(3); RecordBitmapBundleSink<pair<long, vector<long>>> sink("[sink]"); auto c4 = dynamic_cast<PCollection *>(c2->apply1(&sink)); c4 = c4; assert(c4); //just for fixing warning sink.set_side_info(4); RecordBitmapBundleSink<pair<long, vector<long>>> sink1("[sink1]"); auto c5 = dynamic_cast<PCollection *>(c4->apply1(&sink1)); c5 = c5; assert(c5); //just for fixing warning //assert(false && "set RecordBitmapBundleSink side_info to 4!!"); sink1.set_side_info(5); EvaluationBundleContext eval(1, config.cores); //XXX target_wm_delta_secs?? eval.runSimple(p); return 0; }
3,686
1,507
// Copyright (c) 2019 Graphcore Ltd. All rights reserved. #include "RandomUtils.hpp" using namespace poplar; namespace poprand { class SetSeedSupervisor : public SupervisorVertexIf<ASM_CODELETS_ENABLED> { public: SetSeedSupervisor(); Input<Vector<unsigned, ONE_PTR, 8>> seed; const uint32_t seedModifierUser; const uint32_t seedModifierHw; IS_EXTERNAL_CODELET(true); bool compute() { return true; } }; } // namespace poprand
444
164
"// Licensed to the .NET Foundation under one or more agreements.\n// The .NET Foundation licenses t(...TRUNCATED)
145,119
48,687
"// FileDialog.cpp\n//\n// Dialog that allows selection of a file or directory. May be used for open(...TRUNCATED)
24,265
9,125
"// ==========================================================\r\n// Multi-Page functions\r\n//\r\n/(...TRUNCATED)
24,573
9,982
End of preview. Expand in Data Studio

No dataset card yet

Downloads last month
5