id
int64
0
755k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
65
repo_stars
int64
100
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
9 values
repo_extraction_date
stringclasses
92 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
34,162
utils.hpp
supercollider_supercollider/server/supernova/utilities/utils.hpp
// utility functions // Copyright (C) 2005-2012 Tim Blechmann // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. #pragma once #include <cstddef> #include <cassert> #include <type_traits> #include <boost/checked_delete.hpp> #include <boost/intrusive_ptr.hpp> #include <boost/noncopyable.hpp> #include <boost/detail/atomic_count.hpp> #include "branch_hints.hpp" typedef unsigned int uint; #include "function_attributes.h" namespace nova { /* we're using some member of the boost namespace */ using boost::intrusive_ptr; /* some basic math functions */ inline bool ispoweroftwo(int i) { return (i & (i - 1)) == 0; } template <unsigned int n> struct is_power_of_two { static const bool val = (n % 2 == 0) && (is_power_of_two<(n >> 1)>::val); }; template <> struct is_power_of_two<2> { static const bool val = true; }; inline int log2(int n) { if (unlikely(n <= 0)) return (0); #ifdef __GNUC__ return sizeof(int) * __CHAR_BIT__ - 1 - __builtin_clz(n); #else int r = -1; while (n) { r++; n >>= 1; } return r; #endif } inline int nextpoweroftwo(int n) { n = n - 1; const uint bitspace = sizeof(int) * 8 / 2; for (uint i = 1; i != bitspace; i *= 2) n = n | (n >> i); return n + 1; } using std::size_t; /** \brief base class for a callback function */ template <typename t> class runnable { public: virtual ~runnable(void) = default; virtual t run(void) = 0; }; template <class T> struct default_deleter { void operator()(T* t) { delete t; } }; struct delayed_deleter { template <typename T> inline void operator()(T*); }; struct checked_deleter { template <class T> void operator()(T* x) const { boost::checked_delete(x); } }; template <typename deleter = checked_deleter> struct intrusive_refcountable : public deleter { intrusive_refcountable(void): use_count_(0) {} intrusive_refcountable(intrusive_refcountable const& rhs) = delete; intrusive_refcountable& operator=(intrusive_refcountable const& rhs) = delete; virtual ~intrusive_refcountable(void) = default; void add_ref(void) { ++use_count_; } void release(void) { if (--use_count_ == 0) deleter::operator()(this); } inline friend void intrusive_ptr_add_ref(intrusive_refcountable* p) { p->add_ref(); } inline friend void intrusive_ptr_release(intrusive_refcountable* p) { p->release(); } boost::detail::atomic_count use_count_; }; template <class t, class compare = std::less<t>> struct compare_by_instance { bool operator()(const t* lhs, const t* rhs) { assert(lhs and rhs); compare cmp; return cmp(*lhs, *rhs); } }; PURE inline std::size_t string_hash(const char* str) { std::size_t ret = 0; // sdbm hash ... later try another function! int c; while ((c = *str++)) ret = c + (ret << 6) + (ret << 16) - ret; return ret; } struct linear_allocator { linear_allocator(char* chunk): chunk(chunk) {} template <typename T> T* alloc(int count = 1) { T* ret = reinterpret_cast<T*>(chunk); chunk += count * sizeof(T); return ret; } private: char* chunk; }; } /* namespace nova */
3,929
C++
.h
114
30.842105
94
0.665695
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,163
aligned_class.hpp
supercollider_supercollider/server/supernova/utilities/aligned_class.hpp
// base class for aligned classes // Copyright (C) 2011 Tim Blechmann // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. #pragma once #include "malloc_aligned.hpp" namespace nova { struct aligned_class { inline void* operator new(std::size_t size) { return malloc_aligned(size); } inline void operator delete(void* p) { free_aligned(p); } }; } /* namespace nova */
1,086
C++
.h
25
41.84
80
0.740987
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,164
static_allocator.hpp
supercollider_supercollider/server/supernova/utilities/static_allocator.hpp
// static allocator class // Copyright (C) 2008 Tim Blechmann // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. #pragma once extern "C" { #include "tlsf.h" } #include <exception> #include <array> #include "nova-tt/spin_lock.hpp" #include "nova-tt/dummy_mutex.hpp" namespace nova { /** constant-sized, pooled memory allocator based on TLSF allocator * * \todo this violates the allocator requirement in 20.1.5, paragraph 4 * objects have to be freed using the same instance that was used * to allocate them. * * */ template <class T, std::size_t count, bool blocking = false> class static_allocator { static const std::size_t bytes = 2 * count * sizeof(T) + 4096 * 2; static_assert(bytes % sizeof(long) == 0, "static_allocator: bytes not an integer mutiple of sizeof(long)"); static const std::size_t poolsize = bytes / sizeof(long); typedef typename boost::mpl::if_c<blocking, spin_lock, dummy_mutex>::type mutex_type; typedef typename mutex_type::scoped_lock scoped_lock; struct data : mutex_type { #if 0 data(void){} data(data const & rhs) { pool = rhs.pool; } #endif std::array<long, poolsize> pool; }; public: typedef std::size_t size_type; typedef std::ptrdiff_t difference_type; typedef T* pointer; typedef const T* const_pointer; typedef T& reference; typedef const T& const_reference; typedef T value_type; template <class U> struct rebind { typedef static_allocator<U, count, blocking> other; }; static_allocator(void) throw() { data_.pool.assign(0); init_memory_pool(bytes, data_.pool.begin()); } static_allocator(static_allocator const&) = delete; #if 0 template <class U, std::size_t bytes_, bool b> static_allocator(static_allocator<U, bytes_, b> const & rhs) throw() { data_.pool.assign(0); init_memory_pool(bytes, data_.pool.begin()); } #endif ~static_allocator() throw() { destroy_memory_pool(data_.pool.begin()); } pointer address(reference x) const { return &x; } const_pointer address(const_reference x) const { return &x; } pointer allocate(size_type n, const_pointer hint = 0) { scoped_lock lock(data_); pointer ret = static_cast<pointer>(malloc_ex(n * sizeof(T), data_.pool.begin())); if (ret == 0) throw std::bad_alloc(); return ret; } void deallocate(pointer p, size_type n) { scoped_lock lock(data_); free_ex(p, data_.pool.begin()); } size_type max_size() const throw() { return count; } void construct(pointer p, const T& val) { ::new (p) T(val); } void destroy(pointer p) { p->~T(); } private: data data_; }; template <typename T, std::size_t ts, bool tb, typename U, std::size_t us, bool ub> bool operator==(static_allocator<T, ts, tb> const& left, static_allocator<U, us, ub> const& right) { return !(left != right); } template <typename T, std::size_t ts, bool tb, typename U, std::size_t us, bool ub> bool operator!=(static_allocator<T, ts, tb> const& left, static_allocator<U, us, ub> const& right) { return true; } } /* namespace nova */
3,919
C++
.h
100
34.94
111
0.673362
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,165
branch_hints.hpp
supercollider_supercollider/server/supernova/utilities/branch_hints.hpp
// branch hints // Copyright (C) 2007-2015 Tim Blechmann // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. #pragma once #include <boost/config.hpp> #define likely(x) BOOST_LIKELY(x) #define unlikely(x) BOOST_UNLIKELY(x)
930
C++
.h
21
43.142857
72
0.751656
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,166
sized_array.hpp
supercollider_supercollider/server/supernova/utilities/sized_array.hpp
// templated sized array class // Copyright (C) 2009 Tim Blechmann // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. #pragma once #include <algorithm> #include <cassert> #include <memory> /* std::allocator */ #include <type_traits> #include <boost/mpl/if.hpp> namespace nova { /** dynamically sized array * * array class, inspired by boost.array, where the size is specified * during the time of the construction. * in contrary to std::vector, it is guaranteed to use continuous * memory. the memory is allocated in the constructor an freed in the * destructor, these are the only places, where the allocator * functions are called. * * */ template <typename T, class Alloc = std::allocator<T>> class sized_array : private Alloc::template rebind<T>::other { typedef typename Alloc::template rebind<T>::other Allocator; public: // types typedef T value_type; typedef T* iterator; typedef const T* const_iterator; typedef std::reverse_iterator<iterator> reverse_iterator; typedef std::reverse_iterator<const_iterator> const_reverse_iterator; typedef T& reference; typedef const T& const_reference; typedef std::size_t size_type; typedef std::ptrdiff_t difference_type; // construct/copy/destruct explicit sized_array(size_type size = 0, T const& def = T()): data_(size ? Allocator::allocate(size) : nullptr), size_(size) { for (size_type i = 0; i != size; ++i) Allocator::construct(data_ + i, def); } sized_array(sized_array& arg) = delete; sized_array& operator=(sized_array& arg) = delete; private: template <typename int_type> void init_from_int(int_type size) { data_ = Allocator::allocate(size); size_ = size; for (size_type i = 0; i != size_; ++i) Alloc::construct(data_ + i, T()); } template <typename Container> void init_from_container(Container const& container) { data_ = Allocator::allocate(container.size()); size_ = container.size(); size_type index = 0; typedef typename Container::const_iterator iterator; for (iterator it = container.begin(); it != container.end(); ++it) Allocator::construct(data_ + index++, *it); assert(index == size()); } struct call_int_ctor { template <typename int_type> static void init(sized_array& array, int_type const& i) { array.init_from_int<int_type>(i); } }; struct call_container_ctor { template <typename Container> static void init(sized_array& array, Container const& c) { array.init_from_container<Container>(c); } }; public: template <typename Constructor_arg> explicit sized_array(Constructor_arg const& arg) { typedef typename boost::mpl::if_<std::is_integral<Constructor_arg>, call_int_ctor, call_container_ctor>::type ctor; ctor::init(*this, arg); } explicit sized_array(sized_array&& arg) { data_ = arg.data_; size_ = arg.size(); arg.data_ = 0; arg.size_ = 0; } /** move assignment */ sized_array& operator=(sized_array&& arg) { data_ = arg.data_; size_ = arg.size(); arg.data_ = 0; arg.size_ = 0; return *this; } ~sized_array(void) { for (size_type i = 0; i != size(); ++i) Allocator::destroy(data_ + i); if (size()) Allocator::deallocate(data_, size()); } // iterator support iterator begin() { return data_; } const_iterator begin() const { return data_; } iterator end() { return data_ + size(); } const_iterator end() const { return data_ + size(); } // reverse iterator support reverse_iterator rbegin() { return reverse_iterator(data_ + size()); } const_reverse_iterator rbegin() const { return const_reverse_iterator(data_ + size()); } reverse_iterator rend() { return reverse_iterator(data_); } const_reverse_iterator rend() const { return const_reverse_iterator(data_); } // capacity size_type size() const { return size_; } bool empty() const { return size_ == 0; } size_type max_size() const { return size_; } // element access reference operator[](size_type i) { assert(i < size()); return data_[i]; } const_reference operator[](size_type i) const { assert(i < size()); return data_[i]; } reference at(size_type i) { assert(i < size()); return data_[i]; } const_reference at(size_type i) const { assert(i < size()); return data_[i]; } reference front() { return data_[0]; } const_reference front() const { return data_[0]; } reference back() { return data_[size_ - 1]; } const_reference back() const { return data_[size_ - 1]; } const T* data() const { return data_; } T* c_array() { return data_; } // modifiers void assign(const T& t) { for (size_type i = 0; i != size_; ++i) data_[i] = t; } void resize(size_type new_size, T const& t = T()) { T* new_data = Allocator::allocate(new_size); for (size_type i = 0; i != new_size; ++i) Allocator::construct(new_data + i, t); std::copy(data_, data_ + (std::min)(new_size, size_), new_data); T* old_data = data_; data_ = new_data; for (size_type i = 0; i != size_; ++i) Allocator::destroy(old_data + i); if (size_) Allocator::deallocate(old_data, size_); size_ = new_size; } private: T* data_; size_type size_; }; } /* namespace nova */
6,409
C++
.h
168
32.136905
119
0.624597
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,167
static_pool.hpp
supercollider_supercollider/server/supernova/utilities/static_pool.hpp
// static pool class // Copyright (C) 2009 Tim Blechmann // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. #pragma once extern "C" { #include "tlsf.h" } #include <array> #include <mutex> #include "nova-tt/spin_lock.hpp" #include "nova-tt/dummy_mutex.hpp" #include "nova-tt/mlock.hpp" namespace nova { template <std::size_t bytes, bool blocking = false> class static_pool { static_assert(bytes % sizeof(long) == 0, "static_pool: bytes not an integer mutiple of sizeof(long)"); static const std::size_t poolsize = bytes / sizeof(long); typedef typename boost::mpl::if_c<blocking, std::mutex, dummy_mutex>::type mutex_type; typedef typename std::lock_guard<mutex_type> scoped_lock; struct data : mutex_type { std::array<long, poolsize> pool; }; void lock_memory(void) { mlock(data_.pool.data(), poolsize * sizeof(long)); } public: static_pool(bool lock = false) throw() { /* first lock, then assign */ if (lock) lock_memory(); data_.pool.fill(0); std::size_t status = init_memory_pool(bytes, data_.pool.data()); assert(status > 0); } static_pool(static_pool const&) = delete; ~static_pool() throw() { scoped_lock lock(data_); destroy_memory_pool(data_.pool.data()); } void* malloc(std::size_t size) { scoped_lock lock(data_); return malloc_ex(size, data_.pool.data()); } void free(void* p) { scoped_lock lock(data_); free_ex(p, data_.pool.data()); } std::size_t get_max_size(void) { return ::get_max_size(data_.pool.begin()); } private: data data_; }; } /* namespace nova */
2,379
C++
.h
63
33.587302
106
0.671167
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,168
exists.hpp
supercollider_supercollider/server/supernova/utilities/exists.hpp
// templated exists // Copyright (C) 2008 Tim Blechmann // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. #pragma once namespace nova { template <typename container> bool inline exists(container const& c, typename container::key_type const& k) { return c.find(k) != c.end(); } } /* namespace nova */
1,015
C++
.h
23
42.782609
109
0.742915
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,169
time_tag.hpp
supercollider_supercollider/server/supernova/utilities/time_tag.hpp
// server scheduler // Copyright (C) 2008 Tim Blechmann // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. #pragma once #include <cstdint> #include <cmath> #include "boost/date_time/posix_time/posix_time_types.hpp" #include "boost/date_time/gregorian/gregorian_types.hpp" namespace nova { /** time_tag class, compatible to osc time tags */ class time_tag { typedef std::uint32_t uint32; typedef std::uint64_t uint64; typedef union { uint64 packed; uint32 unpacked[2]; } cast_union; static const uint32 ntp_offset = 2208988800UL; /* seconds between 01-01-1900 and 01-01-1970 */ public: static const uint64 fraction_steps = uint64(1) << 32; time_tag(void): data_(0) {} time_tag(time_tag const& rhs): data_(rhs.data_) {} time_tag(uint64 timetag): data_(timetag) {} time_tag(uint32 secs, uint32 fraction) { cast_union cu; cu.unpacked[1] = secs; cu.unpacked[0] = fraction; data_ = cu.packed; } uint32 get_secs(void) const { return reinterpret_cast<const cast_union*>(&data_)->unpacked[1]; } uint32 get_fraction(void) const { return reinterpret_cast<const cast_union*>(&data_)->unpacked[0]; } double get_nanoseconds(void) const { return get_fractional_seconds() * 1e9; } double get_fractional_seconds(void) const { return get_fraction() / double(fraction_steps); } bool operator<(time_tag const& rhs) const { return data_ < rhs.data_; } bool operator<=(time_tag const& rhs) const { return data_ <= rhs.data_; } bool operator==(time_tag const& rhs) const { return data_ == rhs.data_; } bool operator!=(time_tag const& rhs) const { return !operator==(rhs); } time_tag& operator+=(time_tag const& rhs) { data_ += rhs.data_; return *this; } time_tag operator+(time_tag const& rhs) const { time_tag ret(*this); ret += rhs; return ret; } time_tag& operator-=(time_tag const& rhs) { data_ -= rhs.data_; return *this; } time_tag operator-(time_tag const& rhs) const { time_tag ret(*this); ret -= rhs; return ret; } template <typename float_t> static time_tag from_ns(float_t ns) { const float_t units_per_ns = float_t(fraction_steps) / 1e9; if (ns < 1e9) return time_tag(0, ns * units_per_ns); else { float_t secs = std::floor(ns / 1e9); ns = std::fmod(ns, 1e9); return time_tag(secs, ns * units_per_ns); } } static time_tag from_samples_small(unsigned int sample_count, float samplerate) { assert(sample_count < samplerate); const float units_per_sample = float(fraction_steps) / samplerate; return time_tag(0, sample_count * units_per_sample); } static time_tag from_samples(unsigned int sample_count, float samplerate) { const float_t units_per_sample = float_t(fraction_steps) / samplerate; if (sample_count < samplerate) return from_samples_small(sample_count, samplerate); else { float_t secs = std::floor(sample_count / samplerate); float_t samples = std::fmod(sample_count, samplerate); return time_tag(secs, samples * units_per_sample); } } float to_samples(float samplerate) { float seconds = get_fractional_seconds(); uint32_t secs = get_secs(); if (secs == 0) seconds += (float)secs; return seconds * samplerate; } double to_seconds() { double seconds = get_fractional_seconds(); uint32_t secs = get_secs(); if (secs == 0) seconds += (double)secs; return seconds; } bool is_immediate() { return data_ == 1; } static time_tag from_ptime(boost::posix_time::ptime const& pt) { using namespace boost::gregorian; using namespace boost::posix_time; const date base(1970, Jan, 1); time_duration diff = pt - ptime(base); uint32 secs = diff.total_seconds() + ntp_offset; double fraction = double(diff.fractional_seconds()); if (diff.resolution() == boost::date_time::nano) fraction /= 1000000000; else if (diff.resolution() == boost::date_time::micro) fraction /= 1000000; else if (diff.resolution() == boost::date_time::milli) fraction /= 1000; else assert(false); assert(fraction < 1.0 && fraction >= 0); uint32 fraction_units = std::floor(fraction * double(std::numeric_limits<uint32>::max())); return time_tag(secs, fraction_units); } boost::posix_time::ptime to_ptime(void) const { using namespace boost::gregorian; using namespace boost::posix_time; const date base(1970, Jan, 1); #ifdef BOOST_DATE_TIME_POSIX_TIME_STD_CONFIG time_duration offset = seconds(get_secs() - ntp_offset) + nanoseconds(get_nanoseconds()); #else time_duration offset = seconds(get_secs() - ntp_offset) + microseconds(static_cast<long>(get_nanoseconds() / 1000)); #endif return ptime(base, offset); } private: uint64 data_; }; } /* namespace nova */
5,958
C++
.h
144
34.597222
105
0.637183
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,170
osc_server.hpp
supercollider_supercollider/server/supernova/utilities/osc_server.hpp
// osc responder class // Copyright (C) 2008 Tim Blechmann // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. #pragma once #include <thread> // AppleClang workaround #if defined(__apple_build_version__) && __apple_build_version__ > 10000000 # define BOOST_ASIO_HAS_STD_STRING_VIEW 1 #endif // libc++ workaround #if defined(_LIBCPP_VERSION) && _LIBCPP_VERSION >= 7000 && _LIBCPP_VERSION < 9000 # define BOOST_ASIO_HAS_STD_STRING_VIEW 1 #endif #include <boost/asio/io_service.hpp> #include <boost/asio/ip/udp.hpp> #include "branch_hints.hpp" #include "nova-tt/semaphore.hpp" #include "nova-tt/thread_priority.hpp" #include "nova-tt/name_thread.hpp" namespace nova { namespace detail { using namespace boost::asio; using namespace boost::asio::ip; class network_thread { public: void start_receive(void) { thread_ = std::thread([this] { /* NB: on macOS we just keep the default thread priority */ #ifdef NOVA_TT_PRIORITY_RT thread_set_priority_rt(thread_priority_interval_rt().first); #endif name_thread("Network Receive"); sem.post(); io_service::work work(io_service_); io_service_.run(); }); sem.wait(); } ~network_thread(void) { if (!thread_.joinable()) return; io_service_.stop(); thread_.join(); } io_service& get_io_service(void) { return io_service_; } void send_udp(const char* data, unsigned int size, udp::endpoint const& receiver) { udp::socket socket(io_service_); socket.open(udp::v4()); socket.send_to(boost::asio::buffer(data, size), receiver); } protected: io_service io_service_; private: semaphore sem; std::thread thread_; }; } /* namespace */ using detail::network_thread; } /* namespace nova */
2,538
C++
.h
73
30.863014
87
0.685481
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,171
template_functions.hpp
supercollider_supercollider/server/supernova/utilities/template_functions.hpp
// basic arithmetic objects // Copyright (C) 2005, 2006, 2007, 2008 Tim Blechmann // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. #pragma once #include <cmath> #include <algorithm> // for std::min & std::max #include <boost/math/special_functions/fpclassify.hpp> #include "force_inline.hpp" namespace nova { template <typename T> always_inline T identity(T arg) { return arg; } template <typename T> always_inline T plus(T lhs, T rhs) { return lhs + rhs; } template <typename T> always_inline T minus(T lhs, T rhs) { return lhs - rhs; } template <typename F> always_inline F inv_minus(F lhs, F rhs) { return rhs - lhs; } template <typename T> always_inline T times(T lhs, T rhs) { return lhs * rhs; } template <typename T> always_inline T over(T lhs, T rhs) { return lhs / rhs; } template <typename F> always_inline F inv_over(F lhs, F rhs) { return rhs / lhs; } template <typename F> always_inline F fmod(F lhs, F rhs) { return std::fmod(lhs, rhs); } template <typename F> always_inline F less(F lhs, F rhs) { return F(lhs < rhs); } template <typename F> always_inline F less_equal(F lhs, F rhs) { return F(lhs <= rhs); } template <typename F> always_inline F equal(F lhs, F rhs) { return F(lhs == rhs); } template <typename F> always_inline F notequal(F lhs, F rhs) { return F(lhs != rhs); } template <typename F> always_inline F greater(F lhs, F rhs) { return F(lhs > rhs); } template <typename F> always_inline F greater_equal(F lhs, F rhs) { return F(lhs >= rhs); } using std::max; using std::min; template <typename F> always_inline F nova_max(F lhs, F rhs) { return max(lhs, rhs); } template <typename F> always_inline F nova_min(F lhs, F rhs) { return min(lhs, rhs); } template <typename F> always_inline F sign(F arg) { if (arg > 0) return F(1); if (arg < 0) return F(-1); return F(0); } template <typename F> always_inline F and_bool(F lhs, F rhs) { return F(bool(lhs) and bool(rhs)); } template <typename F> always_inline F and_bitwise(F lhs, F rhs) { return F(long(lhs) & long(rhs)); } template <typename F> always_inline F or_bool(F lhs, F rhs) { return F(bool(lhs) or bool(rhs)); } template <typename F> always_inline F or_bitwise(F lhs, F rhs) { return F(long(lhs) | long(rhs)); } template <typename F> always_inline F shift_left(F lhs, F rhs) { return F(long(lhs) << long(rhs)); } template <typename F> always_inline F shift_right(F lhs, F rhs) { return F(long(lhs) >> long(rhs)); } template <typename F> always_inline F inv_pow(F lhs, F rhs) { return std::pow(rhs, lhs); } template <typename F> always_inline F square(F arg) { return arg * arg; } template <typename T> always_inline T pow2(T const& arg) { return square(arg); } template <typename T> always_inline T cube(T arg) { return arg * arg * arg; } template <typename T> always_inline T pow3(T const& arg) { return cube(arg); } using std::sqrt; template <typename F> always_inline F rsqrt(F arg) { return F(1) / std::sqrt(arg); } template <typename F> always_inline F rcp(F arg) { return F(1) / arg; } using std::abs; template <typename F> always_inline F isnormal(F arg) { #ifdef __INTEL_COMPILER /* intel compiler workaround */ return boost::math::isnormal(arg); #else return std::isnormal(arg); #endif } template <typename F1, typename F2, typename F3> always_inline F1 clip(F1 t, F2 low, F3 hi) { if (t < low) return low; else if (t > hi) return hi; else return t; } template <typename F> always_inline F modulo(F lhs, F rhs) { F ret = fmod(lhs, rhs); if (ret < 0) ret += rhs; return ret; } template <typename I> always_inline I wrap_optimistic(I val, const I mod) { if (unlikely(val >= mod)) do val -= mod; while (unlikely(val >= mod)); else while (unlikely(val < I(0))) val += mod; return val; } template <typename I> always_inline I scale_linear(I in, I const& low_in, I const& high_in, I const& low_out, I const& high_out) { return (in - low_in) / (high_in - low_in) * (high_out - low_out) + low_out; } template <typename I> always_inline I scale_linear_clipped(I in, I const& low_in, I const& high_in, I const& low_out, I const& high_out) { return (in - low_in) / (high_in - low_in) * (high_out - low_out) + low_out; } } /* namespace nova */
5,045
C++
.h
103
45.941748
116
0.681316
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,172
freelist.hpp
supercollider_supercollider/server/supernova/utilities/freelist.hpp
// nova freelist class // Copyright (C) 2009 Tim Blechmann // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. #pragma once #include <boost/lockfree/detail/tagged_ptr.hpp> #include <atomic> namespace nova { /** * simple freelist implementation without any memory allocation features * */ class freelist { struct freelist_node { boost::lockfree::detail::tagged_ptr<freelist_node> next; }; typedef boost::lockfree::detail::tagged_ptr<freelist_node> tagged_ptr; public: freelist(void): pool_(tagged_ptr(nullptr)) {} freelist(freelist const& rhs) = delete; freelist& operator=(freelist const& rhs) = delete; void* pop(void) { for (;;) { tagged_ptr old_pool = pool_.load(std::memory_order_consume); if (!old_pool.get_ptr()) return nullptr; freelist_node* new_pool_ptr = old_pool->next.get_ptr(); tagged_ptr new_pool(new_pool_ptr, old_pool.get_tag() + 1); if (pool_.compare_exchange_weak(old_pool, new_pool)) { void* ptr = old_pool.get_ptr(); return reinterpret_cast<void*>(ptr); } } } void push(void* n) { void* node = n; for (;;) { tagged_ptr old_pool = pool_.load(std::memory_order_consume); freelist_node* new_pool_ptr = reinterpret_cast<freelist_node*>(node); tagged_ptr new_pool(new_pool_ptr, old_pool.get_tag() + 1); new_pool->next.set_ptr(old_pool.get_ptr()); if (pool_.compare_exchange_weak(old_pool, new_pool)) return; } } private: std::atomic<tagged_ptr> pool_; }; } /* namespace nova */
2,406
C++
.h
61
33.393443
81
0.646326
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,173
asynchronous_log.hpp
supercollider_supercollider/server/supernova/utilities/asynchronous_log.hpp
// class for asynchronous logging // Copyright (C) 2011 Tim Blechmann // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. #pragma once #include <array> #include <cstring> #include <cstdio> #include <cstdarg> #include <thread> #include <boost/lockfree/spsc_queue.hpp> #include <boost/mpl/if.hpp> #include <boost/sync/semaphore.hpp> namespace nova { namespace asynchronous_log_impl { struct asynchronous_log : boost::noncopyable { bool log_printf(const char* fmt, ...) { va_list vargs; va_start(vargs, fmt); bool result = log_printf(fmt, vargs); va_end(vargs); return result; } bool log_printf(const char* fmt, va_list vargs) { std::array<char, 4096> scratchpad; size_t print_result = vsnprintf(scratchpad.data(), scratchpad.size(), fmt, vargs); if (print_result >= scratchpad.size()) fprintf(stderr, "warning: log message truncated"); return log(scratchpad.data(), print_result); } bool log(const char* string) { size_t length = strlen(string); return log(string, length); } bool log(const char* string, size_t length) { size_t total_enqueued = buffer.push(string, length); if (total_enqueued == 0) return false; sem.post(); if (total_enqueued == length) return true; string += total_enqueued; length -= total_enqueued; for (;;) { size_t enqueued = buffer.push(string, length); if (enqueued == 0) continue; sem.post(); if (enqueued == length) break; string += enqueued; length -= enqueued; } return true; } size_t read_log(char* out_buffer, size_t size) { if (sem.try_wait()) return read(out_buffer, size); else return 0; } size_t read_log_waiting(char* out_buffer, size_t size) { sem.wait(); return read(out_buffer, size); } size_t read(char* out_buffer, size_t size) { return buffer.pop(out_buffer, size); } void interrrupt(void) { sem.post(); } private: boost::lockfree::spsc_queue<char, boost::lockfree::capacity<262144>> buffer; boost::sync::semaphore sem; }; struct asynchronous_log_thread : asynchronous_log { public: asynchronous_log_thread(void): running_flag(true), thread_(std::bind(&asynchronous_log_thread::run, this)) {} ~asynchronous_log_thread(void) { running_flag = false; interrrupt(); thread_.join(); } void run(void) { while (running_flag.load()) { size_t read_chars = read_log_waiting(out_buffer.data(), out_buffer.size()); post_outbuffer(read_chars); while (read_chars == out_buffer.size()) { read_chars = read(out_buffer.data(), out_buffer.size()); post_outbuffer(read_chars); } } size_t read_chars = read_log(out_buffer.data(), out_buffer.size()); post_outbuffer(read_chars); } void post_outbuffer(size_t read_chars) { for (size_t i = 0; i != read_chars; ++i) putchar(out_buffer[i]); fflush(stdout); } private: std::atomic_bool running_flag; std::thread thread_; std::array<char, 4096> out_buffer; }; } /* namespace asynchronous_log_impl */ using asynchronous_log_impl::asynchronous_log; using asynchronous_log_impl::asynchronous_log_thread; } /* namespace nova */
4,251
C++
.h
118
29.449153
113
0.630154
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,174
callback_interpreter.hpp
supercollider_supercollider/server/supernova/utilities/callback_interpreter.hpp
// templated callback system // Copyright (C) 2008, 2009 Tim Blechmann // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. #pragma once #include <atomic> #include <thread> #include "branch_hints.hpp" #include "callback_system.hpp" #include "nova-tt/thread_priority.hpp" #include <boost/checked_delete.hpp> #include <boost/sync/semaphore.hpp> namespace nova { namespace detail { struct nop_functor { void operator()() const {} }; } /* namespace detail */ template <class callback_type, bool mpmc = true, class callback_deleter = boost::checked_deleter<callback_type>> class callback_interpreter : callback_system<callback_type, mpmc, callback_deleter> { typedef callback_system<callback_type, mpmc, callback_deleter> super_t; typedef boost::sync::semaphore semaphore; public: callback_interpreter(void): sem(0), running(false) {} void add_callback(callback_type* cb) { super_t::add_callback(cb); sem.post(); } void run(void) { running.store(true, std::memory_order_relaxed); perform(); } void terminate(void) { running.store(false, std::memory_order_relaxed); sem.post(); } protected: void run(semaphore& sync_sem) { running.store(true, std::memory_order_relaxed); sync_sem.post(); perform(); } private: void perform(void) { do { sem.wait(); super_t::run_callbacks(); } while (likely(running.load(std::memory_order_relaxed))); } protected: boost::sync::semaphore sem; std::atomic<bool> running; }; template <class callback_type, class init_functor = detail::nop_functor, class callback_deleter = boost::checked_deleter<callback_type>> class threaded_callback_interpreter : public callback_interpreter<callback_type, true, callback_deleter>, init_functor { typedef callback_interpreter<callback_type, true, callback_deleter> super; typedef boost::sync::semaphore semaphore; std::thread callback_thread; public: threaded_callback_interpreter(void) {} ~threaded_callback_interpreter(void) { if (super::running.load()) join_thread(); } void start_thread(void) { semaphore sync_sem; std::thread thr([&]() { this->run_thread(sync_sem); }); callback_thread = move(thr); sync_sem.wait(); } void run_thread(semaphore& sync_sem) { init_functor::operator()(); super::run(sync_sem); } void join_thread(void) { if (super::running.load()) { super::terminate(); callback_thread.join(); } } }; template <class callback_type, class init_functor = detail::nop_functor, class callback_deleter = boost::checked_deleter<callback_type>> class callback_interpreter_threadpool : public callback_interpreter<callback_type, true, callback_deleter>, init_functor { typedef callback_interpreter<callback_type, true, callback_deleter> super; typedef boost::sync::semaphore semaphore; public: callback_interpreter_threadpool(uint16_t worker_thread_count, bool rt, uint16_t priority): worker_thread_count_(worker_thread_count), priority(priority), rt(rt) { semaphore sync_sem; using namespace std; for (uint16_t i = 0; i != worker_thread_count; ++i) threads.emplace_back([&]() { this->run(sync_sem); }); for (uint16_t i = 0; i != worker_thread_count; ++i) sync_sem.wait(); } ~callback_interpreter_threadpool(void) { if (super::running.load()) join_threads(); } void join_threads(void) { super::running.store(false); for (uint16_t i = 0; i != worker_thread_count_; ++i) super::sem.post(); for (std::thread& thread : threads) thread.join(); } private: void run(semaphore& sync_sem) { #ifdef NOVA_TT_PRIORITY_RT if (rt) thread_set_priority_rt(priority); else #endif thread_set_priority(priority); init_functor::operator()(); super::run(sync_sem); } std::vector<std::thread> threads; const uint16_t worker_thread_count_; const uint16_t priority; const bool rt; }; } /* namespace nova */
5,048
C++
.h
141
29.893617
120
0.658311
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,175
force_inline.hpp
supercollider_supercollider/server/supernova/utilities/force_inline.hpp
// small header for forced inlining // Copyright (C) 2007, 2009 Tim Blechmann // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. #pragma once #ifndef always_inline # if defined(__GNUC__) && defined(NDEBUG) # define always_inline inline __attribute__((always_inline)) # else # define always_inline inline # endif /* __GNUC__ */ #endif /* always_inline */
1,087
C++
.h
25
42.32
72
0.724008
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
true
false
34,176
tl_allocator.hpp
supercollider_supercollider/server/supernova/utilities/tl_allocator.hpp
// thread-local real-time safe allocator class // Copyright (C) 2008 Tim Blechmann // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. #pragma once extern "C" { #include "tlsf.h" } #include <exception> #include <cstring> #include <array> #include <boost/thread/tss.hpp> #include "branch_hints.hpp" namespace nova { namespace detail { #ifdef __GNUC__ template <std::size_t bytes> class tl_allocator { static_assert(bytes % sizeof(long) == 0, "tl_allocator: bytes not an integer mutiple of sizeof(long)"); public: static const std::size_t poolsize = bytes / sizeof(long); typedef std::size_t size_type; typedef std::ptrdiff_t difference_type; tl_allocator(void) throw() { if (likely(initialized)) return; memset(pool, bytes, 0); init_memory_pool(bytes, pool); } void* allocate(size_type n) { void* ret = malloc_ex(n, pool); if (ret == 0) throw std::bad_alloc(); return ret; } void deallocate(void* p) { free_ex(p, pool); } size_type max_size() const throw() { return bytes; } static __thread long pool[poolsize]; static __thread bool initialized; }; template <std::size_t bytes> long __thread tl_allocator<bytes>::pool[]; template <std::size_t bytes> bool __thread tl_allocator<bytes>::initialized = false; #else template <std::size_t bytes> class tl_allocator { static_assert(bytes % sizeof(long) == 0, "tl_allocator: bytes not an integer mutiple of sizeof(long)"); static const std::size_t poolsize = bytes / sizeof(long); struct pool_t { pool_t(void) { pool.assign(0); init_memory_pool(bytes, pool.begin()); } ~pool_t(void) { destroy_memory_pool(pool.begin()); } std::array<long, poolsize> pool; }; public: typedef std::size_t size_type; typedef std::ptrdiff_t difference_type; tl_allocator(void) throw() { if (likely(pool.get())) return; pool.reset(new pool_t()); } tl_allocator(tl_allocator const& rhs) throw() {} void* allocate(size_type n) { void* ret = malloc_ex(n, pool->pool.begin()); if (ret == 0) throw std::bad_alloc(); return ret; } void deallocate(void* p) { free_ex(p, pool->pool.begin()); } size_type max_size() const throw() { return bytes; } typedef boost::thread_specific_ptr<pool_t> pool_ptr; static pool_ptr pool; }; template <std::size_t bytes> typename tl_allocator<bytes>::pool_ptr tl_allocator<bytes>::pool; #endif } /** * * realtime allocator: * allocates from a thread-local memory pool via the malloc implementation of tlsf * * it is not completely stl compliant * memory allocated from one instance can be deallocated from each other instance * of this class as long as it is done from the same thread * * */ template <typename T, std::size_t bytes = 8 * 1024 * 1024> class tl_allocator { public: typedef std::size_t size_type; typedef std::ptrdiff_t difference_type; typedef T* pointer; typedef const T* const_pointer; typedef T& reference; typedef const T& const_reference; typedef T value_type; template <class U> struct rebind { typedef tl_allocator<U, bytes> other; }; tl_allocator(void) throw() {} template <class U, std::size_t bytes_> tl_allocator(tl_allocator<U, bytes_> const& rhs) throw() {} pointer address(reference x) const { return &x; } const_pointer address(const_reference x) const { return &x; } pointer allocate(size_type n, const_pointer hint = 0) { return static_cast<pointer>(allocator.allocate(n * sizeof(T))); } void deallocate(pointer p, size_type n) { allocator.deallocate(p); } size_type max_size() const throw() { return bytes; } void construct(pointer p, const T& val) { ::new (p) T(val); } void destroy(pointer p) { p->~T(); } private: detail::tl_allocator<bytes> allocator; }; } /* namespace nova */
4,707
C++
.h
124
33.395161
107
0.672695
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,177
static_pooled_class.hpp
supercollider_supercollider/server/supernova/utilities/static_pooled_class.hpp
// static pooled class // Copyright (C) 2009 Tim Blechmann // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. #pragma once #include <cstddef> #include <boost/mpl/if.hpp> #include "freelist.hpp" #include "static_pool.hpp" namespace nova { /** * base class for a class, which uses a static memory pool for * memory allocation. * * memory is allocated from a static pool and freed to a lock-free * freelist, which is freed during the memory allocation routine. * this way, the derived class can be allocated and freed from * different threads, while all the access to the pool is done from * the allocating thread. * * \tparam pool_locking specifies the locking policy for the object * pool (default: nonblocking) * * \tparam recover_count limits the number of objects to be disposed * from the freelist to avoid (default: dispose all objects * of freelist) * * \todo we could allocate one word more and store the size of the * chunk just before the object. if a disposed object is large * enough for a request, it wouldn't need to be added to the * memory pool. * * */ template <typename tag, std::size_t pool_size, bool pool_locking = false, unsigned int recover_count = 0> class static_pooled_class { protected: static_pooled_class(void) = default; static_pooled_class(static_pooled_class const& rhs) = default; ~static_pooled_class(void) = default; private: /** free one object from freelist * * \return true if freelist is empty * * */ static inline bool free_one_disposed_object(void) { void* chunk = disposed_objects.pop(); if (chunk == nullptr) return true; object_pool.free(chunk); return false; } struct disposing_allocator { static void* allocate(std::size_t size) { free_disposed_objects(); return object_pool.malloc(size); } }; struct dispose_n_object_allocator { static void* allocate(std::size_t size) { for (unsigned int i = 0; i != recover_count; ++i) { bool freelist_empty = free_one_disposed_object(); if (freelist_empty) break; } for (;;) { void* ret = object_pool.malloc(size); if (ret) return ret; if (free_one_disposed_object()) return nullptr; /* no object in freelist, we */ } } }; typedef typename boost::mpl::if_c<(recover_count > 0), dispose_n_object_allocator, disposing_allocator>::type allocator; public: static inline void* allocate(std::size_t size) { #ifndef NOVA_MEMORY_DEBUGGING size = std::max(2 * sizeof(void*), size); /* size requirement for lockfree freelist */ return allocator::allocate(size); #else return malloc(size); #endif } inline void* operator new(std::size_t size) { return allocate(size); } static inline void free_disposed_objects(void) { for (;;) { if (free_one_disposed_object()) return; } } static inline void deallocate(void* p) { #ifndef NOVA_MEMORY_DEBUGGING disposed_objects.push(p); #else free(p); #endif } inline void operator delete(void* p) { deallocate(p); } typedef static_pool<pool_size, pool_locking> object_pool_type; static object_pool_type object_pool; static freelist disposed_objects; }; template <typename tag, std::size_t pool_size, bool pool_locking, unsigned int recover_count> typename static_pooled_class<tag, pool_size, pool_locking, recover_count>::object_pool_type static_pooled_class<tag, pool_size, pool_locking, recover_count>::object_pool(true); template <typename tag, std::size_t pool_size, bool pool_locking, unsigned int recover_count> freelist static_pooled_class<tag, pool_size, pool_locking, recover_count>::disposed_objects; } /* namespace nova */
4,734
C++
.h
123
33.121951
120
0.667175
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,178
callback_system.hpp
supercollider_supercollider/server/supernova/utilities/callback_system.hpp
// templated callback system // Copyright (C) 2008, 2009 Tim Blechmann // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. #pragma once #include <memory> #include <exception> #include <iostream> #include <boost/checked_delete.hpp> #include <boost/lockfree/spsc_queue.hpp> #include <boost/lockfree/queue.hpp> namespace nova { /** \brief simple templated callback system, using a lockfree fifo */ template <class callback_type, bool mpmc = true, class callback_deleter = boost::checked_deleter<callback_type>> class callback_system : private callback_deleter { typedef typename boost::mpl::if_c<mpmc, boost::lockfree::queue<callback_type*>, boost::lockfree::spsc_queue<callback_type*>>::type queue_type; public: callback_system(size_t element_count = 2048): callbacks(element_count) {} /** \brief adds a new Callback to the Scheduler, threadsafe */ inline void add_callback(callback_type* cb) { callbacks.push(cb); } /** \brief run all callbacks */ inline void run_callbacks(void) { callbacks.consume_all([this](callback_type* cb) { run_callback(cb); }); } /** \brief run one callback * * assumes, that the queue contains at least one callback * * */ void run_callback(void) { callbacks.consume_one([this](callback_type* cb) { run_callback(cb); }); } private: /** run a callback, handle exceptions */ bool run_callback(callback_type* runme) { bool ret; try { runme->run(); ret = true; } catch (std::exception const& e) { std::cout << "unhandled exception while running callback: " << e.what() << std::endl; ret = false; } callback_deleter::operator()(runme); return ret; } protected: queue_type callbacks; /**< \brief fifo for callbacks */ }; } /* namespace nova */
2,609
C++
.h
64
36.015625
112
0.677598
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,180
named_hash_entry.hpp
supercollider_supercollider/server/supernova/utilities/named_hash_entry.hpp
// Copyright (C) 2011-2012 Tim Blechmann // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. #pragma once #include <string> #include <boost/intrusive/unordered_set_hook.hpp> #include <boost/unordered_set.hpp> #include "utils.hpp" #include "nova-tt/nova-tt/rw_mutex.hpp" #include "malloc_aligned.hpp" namespace nova { namespace bi = boost::intrusive; PURE inline bool strequal(const char* lhs, const char* rhs) { for (;; ++lhs, ++rhs) { if (*lhs == 0) { if (*rhs == 0) return true; else return false; } if (*rhs == 0) return false; if (*lhs != *rhs) return false; } } // thread-safe symbol // warning: don't use from different DSOs struct symbol { private: static const char* duplicate_string(const char* str, std::size_t length) { assert(strlen(str) == length); length += 1; // for terminating \0 char* string = malloc_aligned<char>(length); strncpy(string, str, length); return string; } struct symbol_data { explicit symbol_data(const char* str): str(str), hash(string_hash(str)) {} explicit symbol_data(const char* str, size_t hash): str(str), hash(hash) {} symbol_data(symbol_data const& rhs) = default; symbol_data& operator=(symbol_data const& rhs) = default; friend size_t hash_value(symbol_data const& value) { return value.hash; } bool operator==(symbol_data const& rhs) const { return str == rhs.str; } const char* str; size_t hash; }; struct hash_by_string { size_t operator()(const char* str) const { return string_hash(str); } size_t operator()(symbol_data const& data) const { return data.hash; } }; struct equal_by_string { static const char* get_string(const char* arg) { return arg; } static const char* get_string(symbol_data const& arg) { return arg.str; } template <typename T1, typename T2> bool operator()(T1 const& lhs, T2 const& rhs) const { return strequal(get_string(lhs), get_string(rhs)); } }; class symbol_table { typedef boost::unordered_set<symbol_data> table_type; typedef std::pair<table_type::const_iterator, bool> lookup_result_type; public: symbol_table(void) {} symbol_data const& find(const char* str, size_t strlen) { mutex.lock_shared(); lookup_result_type lookup_result = symbol_lookup(str); mutex.unlock_shared(); if (lookup_result.second) return *lookup_result.first; boost::unique_lock<nova::nonrecursive_rw_mutex> lock(mutex); lookup_result = symbol_lookup(str); if (lookup_result.second) return *lookup_result.first; std::pair<table_type::iterator, bool> inserted = table.insert(symbol_data(duplicate_string(str, strlen))); assert(inserted.second); return *inserted.first; } private: lookup_result_type symbol_lookup(const char* str) const { table_type::iterator it = table.find(str, hash_by_string(), equal_by_string()); return std::make_pair(it, it != table.end()); } table_type table = table_type(16384); nova::nonrecursive_rw_mutex mutex; }; symbol_data lookup_string(const char* str, std::size_t length) { static symbol_table table; return table.find(str, length); } symbol_data lookup_string(const char* str) { return lookup_string(str, strlen(str)); } public: symbol() {} explicit symbol(const char* str): data(lookup_string(str)) {} explicit symbol(std::string const& str): data(lookup_string(str.c_str(), str.size())) {} symbol(const char* str, std::size_t length): data(lookup_string(str, length)) {} symbol(symbol const& rhs) = default; symbol& operator=(symbol const& rhs) = default; const char* c_str(void) const { return data.str; } friend std::size_t hash_value(symbol const& value) { return value.data.hash; } friend bool operator==(symbol const& lhs, symbol const& rhs) { return lhs.data == rhs.data; } friend bool operator<(symbol const& lhs, symbol const& rhs) { return lhs.data.str < rhs.data.str; } symbol_data data = symbol_data(nullptr, 0); }; class named_hash_entry : public bi::unordered_set_base_hook<> { const symbol name_; public: named_hash_entry(const char* name): name_(name) {} named_hash_entry(symbol const& name): name_(name) {} named_hash_entry(std::string const& name): name_(name.c_str(), name.size()) {} const char* name(void) const { return name_.c_str(); } friend std::size_t hash_value(named_hash_entry const& that) { return that.hash(); } std::size_t hash(void) const { return name_.data.hash; } friend bool operator==(named_hash_entry const& a, named_hash_entry const& b) { return a.name_ == b.name_; } }; struct named_hash_equal { template <typename def> bool operator()(def const& lhs, std::string const& rhs) const { return operator()(lhs.name(), rhs.c_str()); } template <typename def> bool operator()(std::string const& lhs, def const& rhs) const { return operator()(lhs.c_str(), rhs.name()); } template <typename def> bool operator()(def const& lhs, symbol const& rhs) const { return operator()(lhs.name(), rhs.c_str()); } template <typename def> bool operator()(symbol const& lhs, def const& rhs) const { return operator()(lhs.c_str(), rhs.name()); } template <typename def> bool operator()(const char* lhs, def const& rhs) const { return operator()(lhs, rhs.name()); } template <typename def> bool operator()(def const& lhs, const char* rhs) const { return operator()(lhs.name(), rhs); } bool operator()(const char* lhs, const char* rhs) const { return strequal(rhs, lhs); } }; struct named_hash_hash { template <typename def> std::size_t operator()(def const& arg) { return hash_value(arg); } std::size_t operator()(const char* str) { return string_hash(str); } std::size_t operator()(std::string const& str) { return string_hash(str.c_str()); } }; }
7,007
C++
.h
154
38.954545
118
0.645327
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,181
simple_pool.hpp
supercollider_supercollider/server/supernova/utilities/simple_pool.hpp
// simple pool class // Copyright (C) 2009, 2010 Tim Blechmann // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. #pragma once extern "C" { #include "tlsf.h" } #include <cstdlib> #include <cstring> /* for std::memset */ #include "nova-tt/spin_lock.hpp" #include "nova-tt/dummy_mutex.hpp" #include "nova-tt/mlock.hpp" #include "function_attributes.h" namespace nova { /** * simple memory pool class, based on tlsf. * * its size has to be set at runtime before it can be used. * * */ template <bool blocking = false> class simple_pool { typedef typename boost::mpl::if_c<blocking, spin_lock, dummy_mutex>::type mutex_type; typedef typename mutex_type::scoped_lock scoped_lock; struct data : mutex_type { data(void): pool(nullptr) {} void init(std::size_t size, bool lock) { pool = (char*)operator new(size); mlock(pool, size); std::memset(pool, 0, size); init_memory_pool(size, pool); pool_size = size; } ~data(void) { scoped_lock lock(*this); if (pool) { destroy_memory_pool(pool); operator delete(pool); } } char* pool; size_t pool_size; }; public: simple_pool(void) {} simple_pool(simple_pool const& rhs) = delete; simple_pool& operator=(simple_pool const& rhs) = delete; simple_pool(std::size_t size, bool lock = false) { init(size, lock); } void init(std::size_t size, bool lock = false) { #ifndef NOVA_MEMORY_DEBUGGING assert(size % sizeof(long) == 0); data_.init(size, lock); #endif } ~simple_pool() throw() {} #ifdef NOVA_MEMORY_DEBUGGING void* MALLOC malloc(std::size_t size) { return ::malloc(size); } void* MALLOC realloc(void* p, std::size_t size) { return ::realloc(p, size); } void free(void* p) { return ::free(p); } std::size_t get_max_size(void) { return std::numeric_limits<std::size_t>::max(); } #else void* MALLOC ASSUME_ALIGNED(32) malloc(std::size_t size) { scoped_lock lock(data_); return malloc_ex(size, data_.pool); } void* MALLOC ASSUME_ALIGNED(32) realloc(void* p, std::size_t size) { scoped_lock lock(data_); return realloc_ex(p, size, data_.pool); } void free(void* p) { scoped_lock lock(data_); free_ex(p, data_.pool); } std::size_t get_pool_size(void) { return data_.pool_size; } std::size_t get_max_size(void) { return ::get_max_size(data_.pool); } std::size_t get_used_size(void) { return ::get_used_size(data_.pool); } #endif private: data data_; }; } /* namespace nova */
3,391
C++
.h
94
31.031915
89
0.644037
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
34,182
sample_types.hpp
supercollider_supercollider/server/supernova/server/sample_types.hpp
// basic types for the ugen system // Copyright (C) 2009 Tim Blechmann // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. #pragma once #ifdef __GNUC__ # define RESTRICTED_POINTERS # define ALIGNED_POINTERS #endif namespace nova { typedef float sample; #ifndef RESTRICTED_POINTERS # define __restrict__ /*__restrict__*/ #endif /* RESTRICTED_POINTERS */ #ifdef ALIGNED_POINTERS typedef sample aligned_sample __attribute__((aligned(4 * sizeof(sample)))); #else typedef sample aligned_sample; #endif /* ALIGNED_POINTERS */ typedef aligned_sample* __restrict__ restricted_sample_ptr; typedef const aligned_sample* __restrict__ const_restricted_sample_ptr; typedef aligned_sample* aligned_sample_ptr; typedef const aligned_sample* const_aligned_sample_ptr; } /* namespace nova */
1,497
C++
.h
37
39.243243
75
0.757576
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,183
server_args.hpp
supercollider_supercollider/server/supernova/server/server_args.hpp
// server arguments // Copyright (C) 2009, 2010 Tim Blechmann // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. #pragma once #include <stdint.h> #include <string> #include <vector> #include <memory> #include <boost/asio.hpp> namespace nova { class server_arguments { server_arguments(int argc, char* argv[]); public: static server_arguments const& initialize(int argc, char* argv[]) { instance_.reset(new server_arguments(argc, argv)); return instance(); } static server_arguments const& instance(void) { return *instance_; } /** set the sample rate (from the audio backend) */ static void set_samplerate(uint32_t samplerate) { instance_->samplerate = samplerate; } uint32_t port(void) const { if (udp_port) return udp_port; else return tcp_port; } uint32_t udp_port, tcp_port; std::string socket_address_str; boost::asio::ip::address socket_address; uint32_t control_busses, audio_busses; uint32_t blocksize, samplerate; int32_t hardware_buffer_size; uint32_t buffers, max_nodes, max_synthdefs; uint16_t use_system_clock; uint32_t rt_pool_size; uint32_t wires, rng_count; uint16_t load_synthdefs; int16_t verbosity; bool dump_version; std::vector<std::string> hw_name; bool memory_locking; uint16_t threads; bool thread_pinning; std::vector<std::string> ugen_paths, restrict_paths; uint16_t input_channels, output_channels; std::string server_password; #ifdef __APPLE__ float safety_clip_threshold; #endif /* for non-rt synthesis */ bool non_rt; std::string command_file, input_file, output_file, header_format, sample_format; private: static std::unique_ptr<server_arguments> instance_; }; } /* namespace nova */
2,528
C++
.h
70
32.171429
91
0.707787
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
34,184
audio_bus_manager.hpp
supercollider_supercollider/server/supernova/server/audio_bus_manager.hpp
// nova server, audio bus // Copyright (C) 2009 Tim Blechmann // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. #pragma once #include <cstdint> #include "sample_types.hpp" #include "malloc_aligned.hpp" #include "nova-tt/rw_spinlock.hpp" namespace nova { class audio_bus_manager { typedef std::uint16_t uint16_t; public: audio_bus_manager(void) = default; audio_bus_manager(audio_bus_manager const&) = delete; audio_bus_manager& operator=(audio_bus_manager const&) = delete; void initialize(uint16_t c, uint16_t b) { count = c; blocksize = b; buffers = calloc_aligned<sample>(count * blocksize); locks = new padded_rw_spinlock[count]; } ~audio_bus_manager(void) { free_aligned(buffers); delete[] locks; } sample* acquire_bus(uint16_t index) { locks[index].lock(); return get_bus(index); } sample* get_bus(uint16_t index) { assert(index < count); return buffers + index * blocksize; } void release_bus(uint16_t index) { locks[index].unlock(); } private: friend class sc_plugin_interface; uint16_t count = 0; uint16_t blocksize = 0; sample* buffers = nullptr; padded_rw_spinlock* locks = nullptr; }; } /* namespace nova */
1,993
C++
.h
56
31.625
72
0.691108
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,185
group.hpp
supercollider_supercollider/server/supernova/server/group.hpp
// group // Copyright (C) 2008, 2009, 2010, 2011 Tim Blechmann // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. #pragma once #include "memory_pool.hpp" #include "node_types.hpp" #include "dsp_thread_queue_node.hpp" #include "dsp_thread_queue/dsp_thread_queue.hpp" #include "utilities/exists.hpp" namespace nova { typedef nova::dsp_queue_node<rt_pool_allocator<void*>> queue_node; typedef nova::dsp_thread_queue_item<dsp_queue_node<rt_pool_allocator<void*>>, rt_pool_allocator<void*>> thread_queue_item; typedef nova::dsp_thread_queue<dsp_queue_node<rt_pool_allocator<void*>>, rt_pool_allocator<void*>> thread_queue; struct abstract_group_tag; typedef bi::list_base_hook<bi::link_mode<bi::auto_unlink>, bi::tag<abstract_group_tag>> group_list_hook; typedef boost::intrusive::list<class abstract_group, bi::constant_time_size<false>, bi::base_hook<group_list_hook>> group_list; class abstract_group : public server_node, public group_list_hook { friend class dependency_graph_generator; protected: server_node_list child_nodes; group_list child_groups; const bool group_is_parallel; abstract_group(int node_id, bool is_parallel): server_node(node_id, false), group_is_parallel(is_parallel) {} public: virtual ~abstract_group(void); bool is_parallel(void) const { return group_is_parallel; } public: /* count the tail nodes to get activation count */ virtual int tail_nodes(void) const = 0; /* @{ */ /** pause/resume handling (set pause/resume on children) */ virtual void pause(void) override; virtual void resume(void) override; /* @} */ /* @{ */ /** child management */ void add_child(server_node* node); virtual void add_child(server_node* node, node_position_constraint const&) = 0; virtual void add_child(server_node* node, node_position) = 0; void replace_child(server_node* node, server_node* node_to_replace); bool has_child(const server_node* node) const; bool empty(void) const { return child_nodes.empty(); } /* returns true, if this or any of the child group has synth children */ bool has_synth_children(void) const { if (child_synth_count) return true; for (const auto& elem : child_groups) if (elem.has_synth_children()) return true; return false; } bool has_parallel_group_children(void) const { if (is_parallel()) return true; for (const auto& elem : child_groups) if (elem.has_parallel_group_children()) return true; return false; } std::size_t child_count(void) const { assert(child_group_count == child_groups.size()); assert(child_synth_count + child_group_count == child_nodes.size()); return child_synth_count + child_group_count; } template <typename functor> void apply_on_children(functor const& f) { for (auto& elem : child_nodes) f(elem); } template <typename functor> void apply_deep_on_children(functor const& f) { for (auto& elem : child_nodes) { if (elem.is_group()) { abstract_group& grp = static_cast<abstract_group&>(elem); grp.apply_deep_on_children(f); } f(elem); } } template <typename functor> void apply_on_children(functor const& f) const { for (const auto& elem : child_nodes) f(elem); } /* @} */ /* @{ */ void register_as_child(void) { parent_->child_groups.push_back(*this); } void unregister_as_child(void) { group_list_hook::unlink(); } /* @} */ public: server_node* next_node(server_node* node) { assert(has_child(node)); server_node_list::iterator next = ++server_node_list::s_iterator_to(*node); if (unlikely(next == child_nodes.end())) return nullptr; else return &(*next); } server_node* previous_node(server_node* node) { assert(has_child(node)); server_node_list::iterator it = server_node_list::s_iterator_to(*node); if (unlikely(it == child_nodes.begin())) return nullptr; else return &(*--it); } void free_children(void) { child_nodes.clear_and_dispose(std::mem_fn(&server_node::clear_parent)); assert(child_synth_count == 0); assert(child_group_count == 0); } void free_synths_deep(void) { child_nodes.remove_and_dispose_if(std::mem_fn(&server_node::is_synth), std::mem_fn(&server_node::clear_parent)); /* now there are only group classes */ for (auto& elem : child_nodes) { abstract_group* group = static_cast<abstract_group*>(&elem); group->free_synths_deep(); } assert(child_synth_count == 0); } /** remove node from child_nodes, clear node->parent */ void remove_child(server_node* node); /* @} */ void set(slot_index_t slot_id, float val) override; void set(const char* slot_str, float val) override; void set(const char* slot_str, size_t hashed_str, float val) override; void set_control_array(slot_index_t slot_str, size_t count, float* val) override; void set_control_array(const char* slot_str, size_t count, float* val) override; void set_control_array(const char* slot_str, size_t hashed_str, size_t count, float* val) override; void set_control_array_element(slot_index_t slot_str, size_t count, float val) override; void set_control_array_element(const char* slot_str, size_t count, float val) override; void set_control_array_element(const char* slot_str, size_t hashed_str, size_t count, float val) override; /* move node to head or tail of target */ template <node_position Position> static void move_to_head_or_tail(server_node* node, abstract_group* target) { assert((Position == head) || (Position == tail)); server_node_list::const_iterator target_iterator = (Position == head) ? target->child_nodes.begin() : target->child_nodes.end(); server_node_list::const_iterator node_iterator = server_node_list::s_iterator_to(*node); abstract_group* node_parent = node->get_parent(); if (node_parent != target) { if (node->is_synth()) { node_parent->child_synth_count -= 1; target->child_synth_count += 1; } else { node_parent->child_group_count -= 1; target->child_group_count += 1; group_list::const_iterator group_target_iterator = (Position == head) ? target->child_groups.begin() : target->child_groups.end(); abstract_group* node_as_group = static_cast<abstract_group*>(node); target->child_groups.splice(group_target_iterator, node_parent->child_groups, group_list::s_iterator_to(*node_as_group)); } node->parent_ = target; } target->child_nodes.splice(target_iterator, node_parent->child_nodes, node_iterator); } template <node_position Relation> static void move_before_or_after(server_node* node, server_node* target) { assert((Relation == before) || (Relation == after)); abstract_group* target_parent = node->get_parent(); if (Relation == after && target->next_node() == nullptr) { // for the sake of simplicity, move the node to the tail of the target's parent group move_to_head_or_tail<tail>(node, target_parent); return; } server_node* node_behind = (Relation == before) ? target : target->next_node(); assert(node_behind); server_node_list::const_iterator target_iterator = server_node_list::s_iterator_to(*node_behind); server_node_list::const_iterator node_iterator = server_node_list::s_iterator_to(*node); abstract_group* node_parent = node->get_parent(); if (node_parent != target_parent) { if (node->is_synth()) { node_parent->child_synth_count -= 1; target_parent->child_synth_count += 1; } else { node_parent->child_group_count -= 1; target_parent->child_group_count += 1; group_list::const_iterator group_target_iterator = group_list::s_iterator_to(*static_cast<abstract_group*>(node)); target_parent->child_groups.splice(target_parent->child_groups.end(), node_parent->child_groups, group_target_iterator); } node->parent_ = target_parent; } target_parent->child_nodes.splice(target_iterator, node_parent->child_nodes, node_iterator); } friend class node_graph; std::size_t child_synth_count = 0, child_group_count = 0; }; inline void server_node::clear_parent(void) { if (is_synth()) --parent_->child_synth_count; else { --parent_->child_group_count; static_cast<abstract_group*>(this)->unregister_as_child(); } parent_ = nullptr; release(); } inline void server_node::set_parent(abstract_group* parent) { add_ref(); assert(parent_ == 0); parent_ = parent; if (is_synth()) ++parent->child_synth_count; else { ++parent->child_group_count; static_cast<abstract_group*>(this)->register_as_child(); } } inline server_node* server_node::previous_node(void) { return parent_->previous_node(this); } inline server_node* server_node::next_node(void) { return parent_->next_node(this); } inline const server_node* server_node::previous_node(void) const { return const_cast<server_node*>(this)->previous_node(); } inline const server_node* server_node::next_node(void) const { return const_cast<server_node*>(this)->next_node(); } class group : public abstract_group { public: group(int node_id): abstract_group(node_id, false) {} const server_node* head_node(void) const { return &*child_nodes.begin(); } const server_node* tail_node(void) const { return &*child_nodes.rbegin(); } private: void add_child(server_node* node, node_position_constraint const& constraint) override; void add_child(server_node* node, node_position) override; friend class dependency_graph_generator; virtual int tail_nodes(void) const override { if (empty()) return 0; for (server_node_list::const_reverse_iterator it = child_nodes.rbegin(); it != child_nodes.rend(); ++it) { const server_node* tail = &*it; if (tail->is_synth()) return 1; const abstract_group* tail_group = static_cast<const abstract_group*>(tail); if (!tail_group->empty()) return tail_group->tail_nodes(); } return 0; } }; class parallel_group : public abstract_group { public: parallel_group(int node_id): abstract_group(node_id, true) {} private: void add_child(server_node* node, node_position_constraint const& constraint) override; void add_child(server_node* node, node_position) override; virtual int tail_nodes(void) const override; friend class dependency_graph_generator; }; } /* namespace nova */
12,095
C++
.h
261
38.662835
120
0.639782
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,187
server_scheduler.hpp
supercollider_supercollider/server/supernova/server/server_scheduler.hpp
// server scheduler // Copyright (C) 2008, 2010 Tim Blechmann // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. #pragma once #include <mutex> #include "dsp_thread_queue/dsp_thread.hpp" #include "group.hpp" #include "memory_pool.hpp" #include "utilities/branch_hints.hpp" #include "utilities/callback_system.hpp" #include "utilities/static_pooled_class.hpp" namespace nova { /** audio-thread synchronization callback * * callback for non-rt to rt thread synchronization. since it is using * a locked internal memory pool, instances should not be allocated * from the real-time thread * * */ struct audio_sync_callback : public static_pooled_class<audio_sync_callback, 1 << 20 /* 1mb pool of realtime memory */, true, 16> { virtual ~audio_sync_callback() = default; virtual void run(void) = 0; }; /** scheduler class of the nova server * * - provides a callback system to place callbacks in the scheduler * - manages dsp threads, which themselves manage the dsp queue interpreter * * scheduler_hook: functor to be called when after callbacks have been executed * and before the threads are executed * * thread_init_functor: helper thread initialization functor * * */ template <class thread_init_functor = nop_thread_init> class scheduler { typedef nova::dsp_thread_pool<queue_node, thread_init_functor, rt_pool_allocator<void*>> dsp_thread_pool; typedef typename dsp_thread_pool::dsp_thread_queue_ptr dsp_thread_queue_ptr; typedef typename dsp_thread_pool::thread_count_t thread_count_t; struct reset_queue_cb : public audio_sync_callback { public: reset_queue_cb(scheduler* sched, dsp_thread_queue_ptr& qptr): sched(sched), qptr(qptr) {} void run(void) override { sched->reset_queue_sync(qptr); /** todo: later free the queue in a helper thread */ } private: scheduler* sched; dsp_thread_queue_ptr qptr; }; protected: /* called from the driver callback */ void reset_queue_sync(dsp_thread_queue_ptr&& qptr) { threads.reset_queue(std::move(qptr)); } public: /* start thread_count - 1 scheduler threads */ scheduler(thread_count_t thread_count = 1, bool realtime = false, bool pin_threads = false): threads(thread_count, !realtime, thread_init_functor(realtime, pin_threads)) {} void start_dsp_threads(void) { threads.start_threads(); } void terminate() { cbs.run_callbacks(); // audio backend must be closed by now threads.terminate_threads(); } void add_sync_callback(audio_sync_callback* cb) { /* we need to guard, because it can be called from the main (system) thread and the network receiver thread */ std::lock_guard<std::mutex> lock(sync_mutex); cbs.add_callback(cb); } /* called from the audio driver */ void run_callbacks() { cbs.run_callbacks(); } void compute_audio() { threads.run(); } /* schedule to set a new queue */ void reset_queue(dsp_thread_queue_ptr& qptr) { add_sync_callback(new reset_queue_cb(this, qptr)); } private: callback_system<audio_sync_callback, false> cbs; dsp_thread_pool threads; std::mutex sync_mutex; }; } /* namespace nova */
3,950
C++
.h
92
39.152174
118
0.708181
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
34,188
server.hpp
supercollider_supercollider/server/supernova/server/server.hpp
// nova server // Copyright (C) 2008, 2009, 2010 Tim Blechmann // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. #pragma once #include <atomic> #include "buffer_manager.hpp" #include "memory_pool.hpp" #include "node_graph.hpp" #include "../sc/sc_osc_handler.hpp" #include "server_args.hpp" #include "server_scheduler.hpp" #include "synth_factory.hpp" #include "../sc/sc_ugen_factory.hpp" #include "../utilities/callback_interpreter.hpp" #include "../utilities/static_pooled_class.hpp" #include "../utilities/asynchronous_log.hpp" #include "../../common/server_shm.hpp" #ifdef PORTAUDIO_BACKEND # include "audio_backend/portaudio_backend.hpp" #elif defined(JACK_BACKEND) # include "audio_backend/jack_backend.hpp" #endif #include "../../scsynth/SC_TimeDLL.hpp" #include "../../scsynth/SC_Time.hpp" namespace nova { struct realtime_engine_functor { static inline void sync_clock(void); static void init_thread(void); static inline void run_tick(void); static void log_(const char*); static void log_printf_(const char*, ...); }; extern class nova_server* instance; /** callback class for audio-thread to system-thread communcation * * the system_callback uses an internal memory pool for real-time safe * memory management. objects are only allowed to be allocated from * the real-time thread. * */ class system_callback : public static_pooled_class<system_callback, 1 << 20, /* 1mb pool of realtime memory */ false, 5> { public: virtual ~system_callback(void) = default; virtual void run(void) = 0; }; /** system_callback to delete object in the system thread. useful to avoid hitting the memory allocator * from within the real-time threads */ template <typename T> class delete_callback : public system_callback { public: delete_callback(T* ptr): ptr_(ptr) {} private: virtual void run(void) override { delete ptr_; } const T* const ptr_; }; /** dsp thread init functor * * for the real-time use, it should acquire real-time scheduling and pin the thread to a certain CPU * * */ struct thread_init_functor { thread_init_functor(bool real_time, bool pin_threads): rt(real_time), pin(pin_threads) {} void operator()(int thread_index); private: const bool rt; const bool pin; }; struct io_thread_init_functor { void operator()() const; }; namespace detail { #if defined(PORTAUDIO_BACKEND) typedef portaudio_backend<realtime_engine_functor, float, false> audio_backend; #elif defined(JACK_BACKEND) typedef jack_backend<realtime_engine_functor, float, false> audio_backend; #else # error "no audio backend selected" #endif } // detail class nova_server : public asynchronous_log_thread, public node_graph, public server_shared_memory_creator, public scheduler<thread_init_functor>, public detail::audio_backend, public synth_factory, public buffer_manager, public sc_osc_handler { public: SC_TimeDLL mDLL; bool use_system_clock; bool non_rt; bool pin_threads; double smooth_samplerate; typedef detail::audio_backend audio_backend; /* main nova_server function */ nova_server(server_arguments const& args); ~nova_server(void); void prepare_backend(void); /* @{ */ /** io interpreter */ void add_io_callback(system_callback* cb) { io_interpreter.add_callback(cb); } /* @} */ /* @{ */ /** system interpreter * \note: should only be called from the main audio thread */ void add_system_callback(system_callback* cb) { system_interpreter.add_callback(cb); } void run(void) { start_dsp_threads(); system_interpreter.run(); } void prepare_to_terminate() { server_shared_memory_creator::disconnect(); } void terminate(void) { system_interpreter.terminate(); quit_requested_ = true; } /* @} */ /** non-rt synthesis */ void run_nonrt_synthesis(server_arguments const& arguments); public: /* @{ */ /** node control */ abstract_synth* add_synth(const char* name, int id, node_position_constraint const& constraints); group* add_group(int id, node_position_constraint const& constraints); parallel_group* add_parallel_group(int id, node_position_constraint const& constraints); void free_node(server_node* node); void group_free_all(abstract_group* group); void group_free_deep(abstract_group* group); void node_pause(server_node* node) { node->pause(); notification_node_turned_off(node); } void node_resume(server_node* node) { node->resume(); notification_node_turned_on(node); } void set_node_slot(int node_id, slot_index_t slot, float value); void set_node_slot(int node_id, const char* slot, float value); /* @} */ void cpu_load(float& peak, float& average) const { audio_backend::get_cpuload(peak, average); } void increment_logical_time(void) { sc_osc_handler::increment_logical_time(time_per_tick); } void set_last_now(time_tag const& lasts, time_tag const& nows) { sc_osc_handler::set_last_now(lasts, nows); } void compensate_latency(void) { sc_osc_handler::add_last_now( time_tag::from_samples(audio_backend::get_latency(), audio_backend::get_samplerate())); } public: HOT void tick() { sc_factory->apply_done_actions(); run_callbacks(); execute_scheduled_bundles(); if (unlikely(dsp_queue_dirty)) rebuild_dsp_queue(); compute_audio(); } void rebuild_dsp_queue(void); void request_dsp_queue_update(void) { dsp_queue_dirty = true; } bool quit_requested() { return quit_requested_.load(); } private: void perform_node_add(server_node* node, node_position_constraint const& constraints, bool update_dsp_queue); void finalize_node(server_node& node); std::atomic<bool> quit_requested_ = { false }; bool dsp_queue_dirty = false; callback_interpreter<system_callback, false> system_interpreter; // rt to system thread threaded_callback_interpreter<system_callback, io_thread_init_functor> io_interpreter; // for network IO }; inline void run_scheduler_tick(void) { const int blocksize = sc_factory->world.mBufLength; // FIXME/TODO // server may have fewer input channels than sc_factory const int input_channels = instance->audio_backend::get_input_count(); const int output_channels = sc_factory->world.mNumOutputs; const int buf_counter = ++sc_factory->world.mBufCounter; /* touch all input buffers */ for (int channel = 0; channel != input_channels; ++channel) sc_factory->world.mAudioBusTouched[output_channels + channel] = buf_counter; instance->tick(); /* wipe all untouched output buffers */ for (int channel = 0; channel != output_channels; ++channel) { if (sc_factory->world.mAudioBusTouched[channel] != buf_counter) zerovec(sc_factory->world.mAudioBus + blocksize * channel, blocksize); } } inline void realtime_engine_functor::sync_clock(void) { if (instance->use_system_clock) { double nows = (uint64)(OSCTime(std::chrono::system_clock::now())) * kOSCtoSecs; instance->mDLL.Reset(sc_factory->world.mSampleRate, sc_factory->world.mBufLength, SC_TIME_DLL_BW, nows); time_tag oscTime = time_tag((uint64)((instance->mDLL.PeriodTime()) * kSecondsToOSCunits + .5)); time_tag oscInc = time_tag((uint64)((instance->mDLL.Period()) * kSecondsToOSCunits + .5)); instance->smooth_samplerate = instance->mDLL.SampleRate(); instance->set_last_now(oscTime, oscTime + oscInc); } else instance->update_time_from_system(); instance->compensate_latency(); } inline void realtime_engine_functor::run_tick(void) { /* // debug timedll static int count = 0; if(count >= 44100/64){ count = 0; log_printf("DLL: t %.6f p %.9f sr %.6f e %.9f avg(e) %.9f \n", instance->mDLL.PeriodTime(), instance->mDLL.Period(), instance->mDLL.SampleRate(), instance->mDLL.Error(), instance->mDLL.AvgError()); } count++; */ run_scheduler_tick(); if (instance->use_system_clock) { // time_tag nows = // time_tag::from_ptime(boost::date_time::microsec_clock<boost::posix_time::ptime>::universal_time()); double nows = (uint64)(OSCTime(std::chrono::system_clock::now())) * kOSCtoSecs; instance->mDLL.Update(nows); time_tag oscTime = time_tag((uint64)((instance->mDLL.PeriodTime()) * kSecondsToOSCunits + .5)); time_tag oscInc = time_tag((uint64)((instance->mDLL.Period()) * kSecondsToOSCunits + .5)); instance->smooth_samplerate = instance->mDLL.SampleRate(); instance->set_last_now(oscTime, oscTime + oscInc); } else instance->increment_logical_time(); } inline bool log(const char* string) { if (instance->get_error_posting()) return instance->log(string); return true; } inline bool log(const char* string, size_t length) { if (instance->get_error_posting()) return instance->log(string, length); return true; } inline bool log_printf(const char* fmt, ...) { if (instance->get_error_posting()) { va_list vargs; va_start(vargs, fmt); auto result = instance->log_printf(fmt, vargs); va_end(vargs); return result; } return true; } inline bool log_printf(const char* fmt, va_list vargs) { if (instance->get_error_posting()) { return instance->log_printf(fmt, vargs); } return true; } } /* namespace nova */
10,489
C++
.h
260
35.080769
113
0.675027
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
34,189
node_graph.hpp
supercollider_supercollider/server/supernova/server/node_graph.hpp
// node graph // Copyright (C) 2008, 2009, 2010 Tim Blechmann // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. #pragma once #include <memory> #include <tuple> #include "dsp_thread_queue_node.hpp" #include "group.hpp" #include "node_types.hpp" #include "dsp_thread_queue/dsp_thread_queue.hpp" namespace nova { class node_graph { private: group root_group_ = { 0 }; friend class dependency_graph_generator; static const std::size_t node_set_bucket_count = 4096; public: typedef thread_queue_item dsp_thread_queue_item; typedef thread_queue dsp_thread_queue; /** \brief ctor * * - initialize root node */ node_graph(void): node_set(node_set_type::bucket_traits(node_buckets, node_set_bucket_count)) { node_set.insert(root_group_); root_group_.add_ref(); } ~node_graph() { assert(root_group_.child_count() == 0); } uint32_t synth_count(void) const { return synth_count_; } uint32_t group_count(void) const { return group_count_; } template <typename Functor> void add_node(server_node* node, node_position_constraint const& constraint, Functor const& doOnFree) { server_node* reference_node = constraint.first; node_position position = constraint.second; std::pair<node_set_type::iterator, bool> inserted = node_set.insert(*node); node->add_ref(); assert(inserted.second == true); /* node id already present (should be checked earlier)! */ switch (position) { case before: case after: { abstract_group* parent = reference_node->parent_; parent->add_child(node, constraint); break; } case head: case tail: { abstract_group* group = static_cast<abstract_group*>(reference_node); group->add_child(node, position); break; } case insert: { abstract_group* group = static_cast<abstract_group*>(reference_node); group->add_child(node); break; } case replace: { const bool reference_node_is_group = reference_node->is_group(); if (reference_node_is_group) { abstract_group* reference_group = static_cast<abstract_group*>(reference_node); reference_group->apply_deep_on_children([&](server_node& node) { doOnFree(node); }); } doOnFree(*reference_node); abstract_group* node_parent = reference_node->parent_; node_parent->replace_child(node, reference_node); if (reference_node_is_group) group_count_ -= 1; else synth_count_ -= 1; break; } default: assert(false); /* this point should not be reached! */ } if (node->is_synth()) synth_count_ += 1; else group_count_ += 1; } void add_node(server_node* node, node_position_constraint const& constraint); void add_node(server_node* s); void remove_node(server_node* n) { remove_node(n, [](server_node&) {}); } template <typename Functor> void remove_node(server_node* node, Functor const& doOnFree) { if (!node->is_synth()) group_free_all(static_cast<abstract_group*>(node), doOnFree); /** \todo recursively remove nodes from node_set * for now this is done by the auto-unlink hook * */ doOnFree(*node); abstract_group* parent = node->parent_; parent->remove_child(node); if (node->is_synth()) synth_count_ -= 1; else group_count_ -= 1; release_node_id(node); } void dump(std::string const& filename); group* root_group(void) { return &root_group_; } typedef std::unique_ptr<dsp_thread_queue> dsp_thread_queue_ptr; dsp_thread_queue_ptr generate_dsp_queue(void); server_node* find_node(int32_t node_id) { node_set_type::iterator it = node_set.find(node_id, hash_node(), equal_node()); if (it == node_set.end()) return nullptr; return &(*it); } bool node_id_available(int32_t node_id) { node_set_type::iterator it = node_set.find(node_id, hash_node(), equal_node()); return (it == node_set.end()); } void synth_reassign_id(int32_t node_id); /** generate new hidden (negative) node id */ int32_t generate_node_id(void); private: int32_t generated_id = -2; public: abstract_group* find_group(int32_t node_id) { server_node* node = find_node(node_id); if (!node || node->is_synth()) return nullptr; else return static_cast<abstract_group*>(node); } abstract_synth* find_synth(int32_t node_id) { server_node* node = find_node(node_id); if (node && node->is_synth()) return static_cast<abstract_synth*>(node); else return nullptr; } void group_free_all(abstract_group* group) { group_free_all(group, [](server_node&) {}); } void group_free_deep(abstract_group* group) { group_free_deep(group, [](server_node&) {}); } template <typename Functor> void group_free_all(abstract_group* group, Functor const& doOnFree) { size_t synths = 0, groups = 0; group->apply_deep_on_children([&](server_node& node) { release_node_id(&node); if (node.is_synth()) synths += 1; else groups += 1; doOnFree(node); }); group->free_children(); synth_count_ -= synths; group_count_ -= groups; } template <typename Functor> void group_free_deep(abstract_group* group, Functor const& doOnFree) { size_t synths = 0; group->apply_deep_on_children([&](server_node& node) { if (node.is_synth()) { release_node_id(&node); synths += 1; } doOnFree(node); }); group->free_synths_deep(); synth_count_ -= synths; } void release_node_id(server_node* node) { node_set.erase(*node); node->release(); } private: struct equal_node { bool operator()(server_node const& lhs, int32_t const& rhs) const { return lhs.node_id == rhs; } bool operator()(int32_t const& lhs, server_node const& rhs) const { return lhs == rhs.node_id; } }; struct hash_node { std::size_t operator()(int32_t value) { return server_node::hash(value); } }; typedef boost::intrusive::unordered_set<server_node, boost::intrusive::constant_time_size<false>, boost::intrusive::power_2_buckets<true>> node_set_type; uint32_t synth_count_ = 0, group_count_ = 1; node_set_type::bucket_type node_buckets[node_set_bucket_count]; node_set_type node_set; }; } /* namespace nova */
7,731
C++
.h
197
31.182741
107
0.60476
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,190
synth_definition.hpp
supercollider_supercollider/server/supernova/server/synth_definition.hpp
// synth prototype // Copyright (C) 2008 Tim Blechmann // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. #pragma once #include <cassert> #include <cstdint> #include <boost/checked_delete.hpp> #include <boost/intrusive/unordered_set.hpp> #include "utilities/aligned_class.hpp" #include "utilities/named_hash_entry.hpp" #include "utilities/utils.hpp" namespace nova { typedef std::int32_t slot_index_t; typedef symbol slot_identifier_type; namespace detail { /** class to resolve alphanumeric string to slot id */ class slot_resolver { protected: struct map_type : public named_hash_entry { map_type(slot_identifier_type const& name, slot_index_t index, int number_of_values): named_hash_entry(name), index(index), number_of_values(number_of_values) {} const slot_index_t index; const int number_of_values; }; private: struct hash_value { hash_value(std::size_t v): value(v) {} std::size_t operator()(const char*) const { return value; } const std::size_t value; }; bool exists(const char* str) const { return slot_resolver_map.find(str, named_hash_hash(), named_hash_equal()) != slot_resolver_map.end(); } protected: slot_resolver(void): slot_resolver_map(slot_resolver_map_t::bucket_traits(buckets, resolver_map_bucket_count)) {} ~slot_resolver(void) { slot_resolver_map.clear_and_dispose(boost::checked_deleter<map_type>()); } void register_slot(symbol const& str, slot_index_t i, int number_of_values) { assert(!exists(str.c_str())); map_type* elem = new map_type(str, i, number_of_values); bool success = slot_resolver_map.insert(*elem).second; assert(success); if (size_t(i) >= slot_names.size()) slot_names.resize(i + 1, nullptr); slot_names[i] = elem->name(); } public: /*@{*/ /** resolve slot by symbolic name * * \return nonnegative index of slot * -1, if symbolic name cannot be resolved */ slot_index_t resolve_slot(const char* str) const { return resolve_slot(str, string_hash(str)); } slot_index_t resolve_slot_with_size(const char* str, int& number_of_values) const { return resolve_slot_with_size(str, string_hash(str), number_of_values); } slot_index_t resolve_slot(const char* str, std::size_t hashed_value) const { auto it = slot_resolver_map.find(str, hash_value(hashed_value), named_hash_equal()); if (it == slot_resolver_map.end()) return -1; else return it->index; } slot_index_t resolve_slot_with_size(const char* str, std::size_t hashed_value, int& number_of_values) const { auto it = slot_resolver_map.find(str, hash_value(hashed_value), named_hash_equal()); if (it == slot_resolver_map.end()) return -1; number_of_values = it->number_of_values; return it->index; } /*@}*/ size_t number_of_slots() const { return slot_names.size(); } const char* name_of_slot(size_t slot_index) const { assert(slot_index < slot_names.size()); return slot_names[slot_index]; } private: static const int resolver_map_bucket_count = 512; typedef boost::intrusive::unordered_set<map_type, boost::intrusive::power_2_buckets<true>> slot_resolver_map_t; slot_resolver_map_t::bucket_type buckets[resolver_map_bucket_count]; slot_resolver_map_t slot_resolver_map; std::vector<const char*> slot_names; }; } /* namespace detail */ class abstract_synth; struct synth_definition_deleter { template <typename T> void operator()(T* ptr) { dispose(static_cast<class synth_definition*>(ptr)); } void dispose(class synth_definition*); }; /** prototype of a synth * * - works as a synth factory * * */ class synth_definition : public aligned_class, public named_hash_entry, public intrusive_refcountable<>, public detail::slot_resolver { public: explicit synth_definition(symbol const& name): named_hash_entry(name) {} virtual ~synth_definition(void) = default; virtual abstract_synth* create_instance(int node_id) = 0; template <typename synth_t> static inline synth_t* allocate(void); }; typedef boost::intrusive_ptr<synth_definition> synth_definition_ptr; } /* namespace nova */
5,127
C++
.h
122
36.598361
117
0.674517
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,191
nrt_synthesis.hpp
supercollider_supercollider/server/supernova/server/nrt_synthesis.hpp
// Copyright (C) 2010-2013 Tim Blechmann // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. #pragma once #include <cstdio> #include <chrono> #include <fstream> #include <string> #include <boost/endian/arithmetic.hpp> #include <boost/format.hpp> #include "server_args.hpp" #include "server.hpp" #include "audio_backend/sndfile_backend.hpp" #include "sc/sc_plugin_interface.hpp" #include "../../common/SC_SndFileHelpers.hpp" #include "../../include/plugin_interface/SC_InlineUnaryOp.h" namespace nova { struct non_rt_functor { static inline void init_thread(void) { realtime_engine_functor::init_thread(); } static inline void run_tick(void) { run_scheduler_tick(); instance->increment_logical_time(); } }; struct non_realtime_synthesis_engine { typedef std::string string; non_realtime_synthesis_engine(server_arguments const& args) { int format = headerFormatFromString(args.header_format.c_str()) | sampleFormatFromString(args.sample_format.c_str()); string input_file = args.input_file; if (input_file == string("_")) input_file.clear(); backend.open_client(input_file, args.output_file, args.samplerate, format, args.output_channels, args.blocksize); command_stream.open(args.command_file.c_str(), std::fstream::in | std::fstream::binary); if (!command_stream) { throw std::runtime_error("cannot open OSC command file"); } has_inputs = !input_file.empty(); samples_per_block = args.blocksize; prepare_backend(args.blocksize, args.input_channels, args.output_channels); } void prepare_backend(int blocksize, int input_channels, int output_channels) { std::vector<sample*> inputs, outputs; for (int channel = 0; channel != input_channels; ++channel) inputs.push_back(sc_factory->world.mAudioBus + (blocksize * (output_channels + channel))); backend.input_mapping(inputs.begin(), inputs.end()); for (int channel = 0; channel != output_channels; ++channel) outputs.push_back(sc_factory->world.mAudioBus + blocksize * channel); backend.output_mapping(outputs.begin(), outputs.end()); } void run(void) { using namespace std; using namespace std::chrono; const int reserved_packet_size = 16384; std::vector<char> packet_vector(reserved_packet_size, 0); log_printf("\nPerforming non-rt synthesis:\n"); backend.activate_audio(); auto start_time = steady_clock::now(); for (;;) { boost::endian::big_int32_t packet_size; if (!command_stream.read((char*)&packet_size, sizeof(packet_size))) break; // done assert(packet_size > 0); if (packet_size > (int32_t)packet_vector.size()) { packet_vector.resize(packet_size); } if (!command_stream.read(packet_vector.data(), packet_size)) { log_printf("ERROR: missing bundle data\n"); break; } time_tag bundle_time = instance->handle_bundle_nrt(packet_vector.data(), packet_size); size_t seconds = bundle_time.get_secs(); size_t nano_seconds = bundle_time.get_nanoseconds(); log_printf(" Next OSC bundle: %zu.%09zu\n", seconds, nano_seconds); while (instance->next_time() < bundle_time) { if (instance->quit_requested()) goto done; if (has_inputs) backend.audio_fn(samples_per_block); else backend.audio_fn_noinput(samples_per_block); } } done: backend.deactivate_audio(); auto end_time = steady_clock::now(); std::string elapsed_string = format_duration(end_time - start_time); log_printf("\nNon-rt synthesis finished in %s\n", elapsed_string.c_str()); auto peaks = backend.get_peaks(); log_printf("Peak summary:\n"); for (size_t channel = 0; channel != peaks.size(); ++channel) { auto amplitude = peaks[channel]; log_printf(" Channel %zu: %gdB\n", channel, sc_ampdb(amplitude)); } } template <typename Duration> static std::string format_duration(Duration const& duration) { using namespace boost; using namespace std::chrono; auto elapsed_hours = duration_cast<hours>(duration); auto remain = duration - elapsed_hours; auto elapsed_minutes = duration_cast<minutes>(remain); remain -= elapsed_minutes; auto elapsed_nanoseconds = duration_cast<nanoseconds>(remain); double seconds = elapsed_nanoseconds.count() * 1e-9; if (elapsed_hours.count()) return str(format("%|d|h %|d|m %|0.3f|s") % elapsed_hours.count() % elapsed_minutes.count() % seconds); if (elapsed_minutes.count()) return str(format("%|d|m %|.3f|s") % elapsed_minutes.count() % seconds); else return str(format("%|.3f|s") % seconds); } private: sndfile_backend<non_rt_functor, float, true> backend; std::fstream command_stream; int samples_per_block; bool has_inputs; }; } // namespace nova
6,036
C++
.h
132
37.590909
116
0.636038
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,192
synth.hpp
supercollider_supercollider/server/supernova/server/synth.hpp
// synth // Copyright (C) 2008, 2009, 2010 Tim Blechmann // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. #pragma once #include <cassert> #include <iostream> #include <cstdint> #include "node_types.hpp" #include "synth_definition.hpp" #include "utilities/time_tag.hpp" namespace nova { namespace detail { /** wrapper class implementing the functionality of synth, that accesses its prototype */ class synth_definition_instance { public: synth_definition_instance(synth_definition_ptr const& ptr): class_ptr(ptr) {} slot_index_t resolve_slot(const char* str) { return class_ptr->resolve_slot(str); } slot_index_t resolve_slot_with_size(const char* str, int& size_of_slot) { return class_ptr->resolve_slot_with_size(str, size_of_slot); } slot_index_t resolve_slot(const char* str, std::size_t hashed_str) { return class_ptr->resolve_slot(str, hashed_str); } slot_index_t resolve_slot_with_size(const char* str, std::size_t hashed_str, int& size_of_slot) { return class_ptr->resolve_slot_with_size(str, hashed_str, size_of_slot); } const char* definition_name(void) const { return class_ptr->name(); } size_t number_of_slots() const { return class_ptr->number_of_slots(); } const char* name_of_slot(size_t index) const { return class_ptr->name_of_slot(index); } protected: synth_definition_ptr class_ptr; }; } /* namespace detail */ class abstract_synth : public server_node, public detail::synth_definition_instance { public: typedef float sample; typedef std::uint_fast16_t samplecount_t; typedef detail::synth_definition_instance definition_instance; protected: abstract_synth(int node_id, synth_definition_ptr const& definition): server_node(node_id, true), definition_instance(definition) {} public: virtual void run(void) = 0; virtual float get(slot_index_t slot_id) const = 0; /** returns true (and writes characters to *str) if the control at slot_id is indeed mapped, otherwise returns false */ virtual bool getMappedSymbol(slot_index_t slot_id, char* str) const = 0; /** set a slot */ /* @{ */ virtual void set(slot_index_t slot_id, float val) override = 0; void set(const char* slot_str, sample val) override { set(slot_str, string_hash(slot_str), val); } void set(const char* slot_str, size_t hashed_str, sample val) override { slot_index_t slot_id = definition_instance::resolve_slot(slot_str, hashed_str); if (likely(slot_id >= 0)) this->set(slot_id, val); } void set_control_array(const char* slot_str, size_t count, sample* val) override { set_control_array(slot_str, string_hash(slot_str), count, val); } void set_control_array(const char* slot_str, size_t hashed_str, size_t count, sample* val) override { int size_of_parameter; slot_index_t slot_id = definition_instance::resolve_slot_with_size(slot_str, hashed_str, size_of_parameter); count = std::min(size_t(size_of_parameter), count); if (likely(slot_id >= 0)) for (size_t i = 0; i != count; ++i) this->set(slot_id + i, val[i]); } virtual void set_control_array(slot_index_t slot_id, size_t n, float* values) override = 0; virtual void set_control_array_element(slot_index_t slot_id, size_t index, float val) override { this->set(slot_id + index, val); } void set_control_array_element(const char* slot_str, size_t index, sample val) override { set_control_array_element(slot_str, string_hash(slot_str), index, val); } void set_control_array_element(const char* slot_str, size_t hashed_str, size_t index, sample val) override { int size_of_parameter; slot_index_t slot_id = definition_instance::resolve_slot_with_size(slot_str, hashed_str, size_of_parameter); if (likely((slot_id >= 0) && (index < size_of_parameter))) this->set(slot_id + index, val); } /* @} */ }; } /* namespace nova */
4,743
C++
.h
98
43.561224
120
0.689423
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,193
sync_commands.hpp
supercollider_supercollider/server/supernova/server/sync_commands.hpp
// osc responder classes for the nova server // Copyright (C) 2008 Tim Blechmann // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. #pragma once #include "server_scheduler.hpp" namespace nova { class set_cmd_index : public audio_sync_callback { public: set_cmd_index(int node_id, slot_index_t const& slot_id, float value): node_id(node_id), slot_id(slot_id), value(value) {} private: virtual void run(void) override { instance->set_node_slot(node_id, slot_id, value); } const int node_id; const slot_index_t slot_id; const float value; }; class set_cmd_str : public audio_sync_callback { public: set_cmd_str(int node_id, const char* name, float value): node_id(node_id), value(value) { slot_id = (char*)allocate(strlen(name) * sizeof(char)); strcpy(slot_id, name); } ~set_cmd_str(void) { deallocate(slot_id); } private: virtual void run(void) override { instance->set_node_slot(node_id, slot_id, value); } const int node_id; char* slot_id; const float value; }; }
1,769
C++
.h
46
35.304348
93
0.706776
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,194
node_types.hpp
supercollider_supercollider/server/supernova/server/node_types.hpp
// node types // Copyright (C) 2008, 2009, 2010 Tim Blechmann // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. #pragma once #include <boost/detail/atomic_count.hpp> #include <boost/intrusive/list.hpp> #include <boost/intrusive/unordered_set.hpp> #include "memory_pool.hpp" #include "synth_definition.hpp" #include "utilities/static_pool.hpp" namespace nova { class server_node; class abstract_group; class group; namespace bi = boost::intrusive; typedef boost::intrusive::list<class server_node, boost::intrusive::constant_time_size<false>> server_node_list; class server_node : public bi::list_base_hook<bi::link_mode<bi::auto_unlink>>, /* group member */ public bi::unordered_set_base_hook<bi::link_mode<bi::auto_unlink>> /* for node_id mapping */ { protected: server_node(int32_t node_id, bool type): node_id(node_id), node_is_synth(type), use_count_(0) {} virtual ~server_node(void) { assert(parent_ == 0); } /* @{ */ /** node id handling */ void reset_id(int32_t new_id) { node_id = new_id; } public: int32_t node_id; int32_t id(void) const { return node_id; } /* @} */ typedef bi::list_base_hook<bi::link_mode<bi::auto_unlink>> parent_hook; /* @{ */ /** node_id mapping */ friend std::size_t hash_value(server_node const& that) { return hash(that.id()); } static int32_t hash(int32_t id) { return id * 2654435761U; // knuth hash, 32bit should be enough } friend bool operator<(server_node const& lhs, server_node const& rhs) { return lhs.node_id < rhs.node_id; } friend bool operator==(server_node const& lhs, server_node const& rhs) { return lhs.node_id == rhs.node_id; } /* @} */ bool is_synth(void) const { return node_is_synth; } bool is_group(void) const { return !node_is_synth; } /* @{ */ /* set a scalar slot */ virtual void set(slot_index_t slot_id, float val) = 0; virtual void set(const char* slot_str, float val) = 0; virtual void set(const char* slot_str, size_t hashed_str, float val) = 0; /* @} */ /* @{ */ /* set an arrayed slot from array */ virtual void set_control_array(slot_index_t slot_str, size_t n, float* values) = 0; virtual void set_control_array(const char* slot_str, size_t n, float* values) = 0; virtual void set_control_array(const char* slot_str, size_t hashed_str, size_t n, float* values) = 0; /* @} */ /* @{ */ /* set an element of an arrayed slot */ virtual void set_control_array_element(slot_index_t slot_str, size_t n, float values) = 0; virtual void set_control_array_element(const char* slot_str, size_t n, float values) = 0; virtual void set_control_array_element(const char* slot_str, size_t hashed_str, size_t n, float values) = 0; /* @} */ /* @{ */ /** group traversing */ inline const server_node* previous_node(void) const; inline server_node* previous_node(void); inline const server_node* next_node(void) const; inline server_node* next_node(void); /* @} */ private: const bool node_is_synth; /** support for pausing node */ /* @{ */ bool running_ = true; public: virtual void pause(void) { running_ = false; } virtual void resume(void) { running_ = true; } bool is_running(void) const { return running_; } /* @} */ private: friend class node_graph; friend class abstract_group; friend class group; friend class parallel_group; public: /* @{ */ /** parent group handling */ const abstract_group* get_parent(void) const { return parent_; } abstract_group* get_parent(void) { return parent_; } inline void set_parent(abstract_group* parent); inline void clear_parent(void); /* @} */ private: abstract_group* parent_ = nullptr; public: /* memory management for server_nodes */ /* @{ */ inline void* operator new(std::size_t size) { return rt_pool.malloc(size); } inline void operator delete(void* p) { rt_pool.free(p); } /* @} */ public: /* refcountable */ /* @{ */ void add_ref(void) { ++use_count_; } void release(void) { if (unlikely(--use_count_ == 0)) delete this; } private: boost::detail::atomic_count use_count_; /* @} */ }; inline void intrusive_ptr_add_ref(server_node* p) { p->add_ref(); } inline void intrusive_ptr_release(server_node* p) { p->release(); } enum node_position { head = 0, tail = 1, before = 2, after = 3, replace = 4, insert = 5 /* for pgroups */ }; typedef std::pair<server_node*, node_position> node_position_constraint; } /* namespace nova */
5,356
C++
.h
135
35.548148
113
0.66087
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,195
buffer_manager.hpp
supercollider_supercollider/server/supernova/server/buffer_manager.hpp
// nova server, buffer manager class // Copyright (C) 2009 Tim Blechmann // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. #pragma once #include <algorithm> #include <cassert> #include <exception> #include <stdexcept> #include <string> #include <vector> #include "nova-simd/simd_memory.hpp" #include "malloc_aligned.hpp" namespace nova { struct buffer_wrapper { typedef std::size_t size_t; typedef float sample_t; typedef uint32_t uint; buffer_wrapper(void) = default; ~buffer_wrapper(void) { if (data) free_aligned(data); } void allocate(size_t frames, unsigned int channels); void free(void) { if (data) { free_aligned(data); data = nullptr; frames_ = 0; channels_ = 0; } } void zero(void) { assert(data); zerovec(data, frames_); } /** set sample for specific indices */ template <typename float_type> void set_samples(unsigned int count, const size_t* indices, const float_type* values) { for (unsigned int i = 0; i != count; ++i) { size_t index = indices[i]; if (index < frames_) { sample_t value = values[i]; data[index] = value; } } } /** set continuous samples starting at position */ template <typename float_type> void set_samples(size_t position, unsigned int count, const float_type* values) { sample_t* base = data + position; size_t avail = frames_ - position; count = std::min(size_t(count), avail); std::copy_n(base, count, values); } /** set continuous samples starting at position to a single value */ template <typename float_type> void fill_samples(size_t position, unsigned int count, const float_type value) { sample_t* base = data + position; size_t avail = frames_ - position; count = std::min(size_t(count), avail); std::fill_n(base, count, sample_t(value)); } /* @{ */ void read_file(std::string const& file, size_t start_frame, size_t frames) { read_file(file.c_str(), start_frame, frames); } void read_file(const char* file, size_t start_frame, size_t frames); void read_file_channels(std::string const& file, size_t start_frame, size_t frames, unsigned int channel_count, unsigned int* channels) { read_file_channels(file.c_str(), start_frame, frames, channel_count, channels); } void read_file_channels(const char* file, size_t start_frame, size_t frames, unsigned int channel_count, unsigned int* channels); /* @} */ void write_file(const char* file, const char* header_format, const char* sample_format, size_t start_frame, size_t frames); sample_t* data = nullptr; size_t frames_ = 0; unsigned int channels_ = 0; int sample_rate_ = 0; }; class buffer_manager { public: buffer_manager(unsigned int max_buffers): buffers(max_buffers, buffer_wrapper()) {} void check_buffer_unused(int index) { if (buffers[index].data != nullptr) throw std::runtime_error("buffer already in use"); } void check_buffer_in_use(int index) { if (buffers[index].data == nullptr) throw std::runtime_error("buffer is not in use"); } void allocate_buffer(int index, unsigned int frames, unsigned int channels) { check_buffer_unused(index); buffers[index].allocate(frames, channels); } void read_buffer_allocate(int index, const char* file, size_t start_frame, size_t frames) { check_buffer_unused(index); buffers[index].read_file(file, start_frame, frames); } void read_buffer_channels_allocate(int index, const char* file, size_t start_frame, size_t frames, unsigned int channel_count, unsigned int* channels) { check_buffer_unused(index); buffers[index].read_file_channels(file, start_frame, frames, channel_count, channels); } void free_buffer(int index) { check_buffer_in_use(index); buffers[index].free(); } void zero_buffer(int index) { check_buffer_in_use(index); buffers[index].zero(); } buffer_wrapper& get_buffer(int index) { check_buffer_in_use(index); return buffers[index]; } template <typename float_type> void set_samples(int index, unsigned int count, const size_t* indices, const float_type* values) { check_buffer_in_use(index); buffers[index].set_samples(count, indices, values); } template <typename float_type> void set_samples(int index, size_t position, unsigned int count, const float_type* values) { check_buffer_in_use(index); buffers[index].set_samples(count, position, count, values); } template <typename float_type> void fill_samples(int index, size_t position, unsigned int count, float_type value) { check_buffer_in_use(index); buffers[index].fill_samples(position, count, value); } void write_buffer(int index, const char* file, const char* header_format, const char* sample_format, size_t start_frame, size_t frames) { check_buffer_in_use(index); buffers[index].write_file(file, header_format, sample_format, start_frame, frames); } private: std::vector<buffer_wrapper> buffers; }; } /* namespace nova */
6,236
C++
.h
152
34.197368
120
0.647263
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,196
dependency_graph_generator.hpp
supercollider_supercollider/server/supernova/server/dependency_graph_generator.hpp
// dependency graph generator // Copyright (C) 2010 Tim Blechmann // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. #pragma once #include "node_graph.hpp" #include "function_attributes.h" namespace nova { class dependency_graph_generator { typedef node_graph::dsp_thread_queue dsp_thread_queue; typedef thread_queue_item::successor_list successor_container; typedef std::vector<server_node*, rt_pool_allocator<server_node*>> sequential_child_list; public: dsp_thread_queue* operator()(node_graph* graph) { bool has_parallelism = graph->root_group()->has_parallel_group_children(); /* pessimize: reserve enough memory for the worst case */ q = new node_graph::dsp_thread_queue(graph->synth_count_, has_parallelism); fill_queue(*graph->root_group()); // LATER: we could optimize the case when we do not have any paralleism return q; } private: dsp_thread_queue* q; void fill_queue(group& root_group) { if (root_group.has_synth_children()) fill_queue_recursive(root_group, successor_container(0), 0); } template <typename reverse_iterator> HOT static inline int get_previous_activation_count(reverse_iterator it, reverse_iterator end, int previous_activation_limit) { reverse_iterator prev = it; for (;;) { ++prev; if (prev == end) return previous_activation_limit; // we are the first item, so we use the previous activiation limit server_node& node = *prev; if (node.is_synth()) return 1; else { abstract_group& grp = static_cast<abstract_group&>(node); int tail_nodes = grp.tail_nodes(); if (tail_nodes != 0) /* use tail nodes of previous group */ return tail_nodes; else /* skip empty groups */ continue; } } } successor_container fill_queue_recursive(abstract_group& grp, successor_container const& successors, size_t activation_limit) { if (grp.is_parallel()) return fill_queue_recursive(static_cast<parallel_group&>(grp), successors, activation_limit); else return fill_queue_recursive(static_cast<group&>(grp), successors, activation_limit); } HOT successor_container fill_queue_recursive(group& g, successor_container const& successors_from_parent, size_t previous_activation_limit) { assert(g.has_synth_children()); typedef server_node_list::reverse_iterator r_iterator; successor_container successors(successors_from_parent); size_t children = g.child_count(); sequential_child_list sequential_children; sequential_children.reserve(g.child_synth_count); for (r_iterator it = g.child_nodes.rbegin(); it != g.child_nodes.rend(); ++it) { server_node& node = *it; if (node.is_synth()) { r_iterator end_of_node = it; --end_of_node; // one element behind the last std::size_t node_count = 1; // we fill the child nodes in reverse order to an array for (;;) { sequential_children.push_back(&*it); ++it; if (it == g.child_nodes.rend()) break; // we found the beginning of this group if (!it->is_synth()) break; // we hit a child group, later we may want to add it's nodes, too? ++node_count; } --it; // we iterated one element too far, so we need to go back to the previous element assert(sequential_children.size() == node_count); auto seq_it = sequential_children.rbegin(); int activation_limit = get_previous_activation_count(it, g.child_nodes.rend(), previous_activation_limit); thread_queue_item* q_item = q->allocate_queue_item( queue_node(queue_node_data(static_cast<abstract_synth*>(*seq_it++)), node_count), successors, activation_limit); queue_node& q_node = q_item->get_job(); // now we can add all nodes sequentially for (; seq_it != sequential_children.rend(); ++seq_it) q_node.add_node(static_cast<abstract_synth*>(*seq_it)); sequential_children.clear(); assert(q_node.size() == node_count); /* advance successor list */ successors = successor_container(1); successors[0] = q_item; if (activation_limit == 0) q->add_initially_runnable(q_item); children -= node_count; } else { abstract_group& grp = static_cast<abstract_group&>(node); if (grp.has_synth_children()) { int activation_limit = get_previous_activation_count(it, g.child_nodes.rend(), previous_activation_limit); successors = fill_queue_recursive(grp, successors, activation_limit); } children -= 1; } } assert(children == 0); return successors; } HOT successor_container fill_queue_recursive(parallel_group& g, successor_container const& successors_from_parent, size_t previous_activation_limit) { assert(g.has_synth_children()); std::vector<thread_queue_item*, rt_pool_allocator<thread_queue_item*>> collected_nodes; collected_nodes.reserve(g.child_synth_count + g.child_group_count * 16); // pessimize for (auto& node : g.child_nodes) { if (node.is_synth()) { thread_queue_item* q_item = q->allocate_queue_item(queue_node(queue_node_data(static_cast<abstract_synth*>(&node))), successors_from_parent, previous_activation_limit); if (previous_activation_limit == 0) q->add_initially_runnable(q_item); collected_nodes.push_back(q_item); } else { abstract_group& grp = static_cast<abstract_group&>(node); if (grp.has_synth_children()) { successor_container group_successors = fill_queue_recursive(grp, successors_from_parent, previous_activation_limit); for (unsigned int i = 0; i != group_successors.size(); ++i) collected_nodes.push_back(group_successors[i]); } } } successor_container ret(collected_nodes.size()); memcpy(ret.data->content, collected_nodes.data(), collected_nodes.size() * sizeof(thread_queue_item*)); return ret; } }; } /* namespacen nova */
7,893
C++
.h
153
38.503268
118
0.579447
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,197
synth_factory.hpp
supercollider_supercollider/server/supernova/server/synth_factory.hpp
// synth factory // Copyright (C) 2008, 2009, 2010 Tim Blechmann // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. #pragma once #include <map> #include <string> #include "synth.hpp" #include "synth_definition.hpp" namespace nova { class synth_factory { public: void register_definition(synth_definition_ptr&& prototype) { prototype_map_type::iterator it = definition_map.find(prototype->name(), named_hash_hash(), named_hash_equal()); if (it != definition_map.end()) { definition_map.erase(it); it->release(); } synth_definition_ptr ptr(std::forward<synth_definition_ptr>(prototype)); ptr->add_ref(); definition_map.insert(*ptr.get()); } abstract_synth* create_instance(const char* name, int node_id) { prototype_map_type::iterator it = definition_map.find(name, named_hash_hash(), named_hash_equal()); if (it == definition_map.end()) return nullptr; return it->create_instance(node_id); } void remove_definition(const char* name) { prototype_map_type::iterator it = definition_map.find(name, named_hash_hash(), named_hash_equal()); if (it == definition_map.end()) return; definition_map.erase(it); it->release(); } std::size_t definition_count(void) const { return definition_map.size(); } synth_factory(void): definition_map(prototype_map_type::bucket_traits(buckets, bucket_count)) {} ~synth_factory(void) { while (definition_map.begin() != definition_map.end()) { prototype_map_type::iterator it = definition_map.begin(); definition_map.erase(it); it->release(); } } private: static const int bucket_count = 2048; typedef boost::intrusive::unordered_set<synth_definition, boost::intrusive::power_2_buckets<true>> prototype_map_type; prototype_map_type::bucket_type buckets[bucket_count]; prototype_map_type definition_map; }; } /* namespace nova */
2,745
C++
.h
65
36.846154
120
0.677431
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,198
dsp_thread_queue_node.hpp
supercollider_supercollider/server/supernova/server/dsp_thread_queue_node.hpp
// dsp thread queue nodes // Copyright (C) 2008-2015 Tim Blechmann // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. #pragma once #include <cstdint> #include <memory> #include <vector> #include "server/synth.hpp" #include "../sc/sc_synth.hpp" #include "function_attributes.h" namespace nova { /* optimized for sc_synth, since we don't support other types of synths for now */ class queue_node_data { typedef std::uint_fast8_t thread_count_type; public: explicit queue_node_data(abstract_synth* node): node(static_cast<sc_synth*>(node)) {} explicit queue_node_data(queue_node_data const& rhs) = default; explicit queue_node_data(queue_node_data&& rhs) = default; void operator()(thread_count_type index) { if (unlikely(!node->is_running())) return; node->perform(); } private: intrusive_ptr<sc_synth> node; template <typename Alloc> friend class dsp_queue_node; }; /* implements runnable concept */ template <typename Alloc = std::allocator<queue_node_data>> class dsp_queue_node { typedef std::vector<queue_node_data, typename Alloc::template rebind<queue_node_data>::other> node_container; typedef std::uint_fast16_t node_count_type; typedef std::uint_fast8_t thread_count_type; public: explicit dsp_queue_node(queue_node_data&& node): first(std::move(node)) {} dsp_queue_node(queue_node_data&& node, std::size_t container_size): first(std::move(node)) { nodes.reserve(container_size - 1); } HOT void operator()(thread_count_type thread_index) { first(thread_index); int remaining = node_count; if (remaining == 0) return; // fast-path queue_node_data* __restrict__ data = nodes.data(); if (remaining & 1) { (*data)(thread_index); if (remaining == 1) return; remaining -= 1; data += 1; } if (remaining & 2) { (*data)(thread_index); (*(data + 1))(thread_index); if (remaining == 2) return; remaining -= 2; data += 2; } if (remaining & 4) { (*data)(thread_index); (*(data + 1))(thread_index); (*(data + 2))(thread_index); (*(data + 3))(thread_index); if (remaining == 4) return; remaining -= 4; data += 4; } assert(remaining >= 8); assert((remaining % 8) == 0); for (;;) { (*data)(thread_index); (*(data + 1))(thread_index); (*(data + 2))(thread_index); (*(data + 3))(thread_index); (*(data + 4))(thread_index); (*(data + 5))(thread_index); (*(data + 6))(thread_index); (*(data + 7))(thread_index); if (remaining == 8) return; remaining -= 8; data += 8; } } void add_node(abstract_synth* node) { nodes.emplace_back(std::move(queue_node_data(node))); ++node_count; } node_count_type size(void) const { return node_count + 1; } private: queue_node_data first; node_container nodes; node_count_type node_count = 0; }; } /* namespace nova */
4,026
C++
.h
110
29.4
113
0.598559
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,199
audio_backend_common.hpp
supercollider_supercollider/server/supernova/audio_backend/audio_backend_common.hpp
// audio backend helpers // Copyright (C) 2010-2015 Tim Blechmann // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. #pragma once #include <vector> #include <boost/mpl/if.hpp> #include <boost/align/aligned_allocator.hpp> #include "nova-simd/simd_memory.hpp" #include "nova-tt/dummy_mutex.hpp" #include "nova-tt/spin_lock.hpp" #include "malloc_aligned.hpp" namespace nova { namespace detail { template <typename sample_type, typename io_sample_type, bool blocking, bool managed_memory = true> class audio_backend_base : boost::mpl::if_c<blocking, spin_lock, dummy_mutex>::type { typedef typename boost::mpl::if_c<blocking, spin_lock, dummy_mutex>::type lock_t; typedef std::size_t size_t; public: /* @{ */ /** buffers can be directly mapped to the io regions of the host application */ template <typename Iterator> void input_mapping(Iterator const& buffer_begin, Iterator const& buffer_end) { static_assert(!managed_memory, "audio_backend_common: managed_memory == true"); size_t input_count = buffer_end - buffer_begin; input_samples.resize(input_count); std::copy(buffer_begin, buffer_end, input_samples.begin()); } template <typename Iterator> void output_mapping(Iterator const& buffer_begin, Iterator const& buffer_end) { static_assert(!managed_memory, "audio_backend_common: managed_memory == true"); size_t output_count = buffer_end - buffer_begin; output_samples.resize(output_count); std::copy(buffer_begin, buffer_end, output_samples.begin()); } /* @} */ protected: void clear_inputs(size_t frames_per_tick) { for (uint16_t channel = 0; channel != input_samples.size(); ++channel) zerovec_simd(input_samples[channel].get(), frames_per_tick); } void clear_outputs(size_t frames_per_tick) { for (uint16_t channel = 0; channel != output_samples.size(); ++channel) zerovec_simd(output_samples[channel].get(), frames_per_tick); } void prepare_helper_buffers(size_t input_channels, size_t output_channels, size_t frames) { static_assert(managed_memory, "audio_backend_common: managed_memory == false"); input_samples.resize(input_channels); output_samples.resize(output_channels); std::generate(input_samples.begin(), input_samples.end(), std::bind(calloc_aligned<sample_type>, frames)); std::generate(output_samples.begin(), output_samples.end(), std::bind(calloc_aligned<sample_type>, frames)); } void fetch_inputs(const float** inputs, size_t frames, int input_channels) { if (is_multiple_of_vectorsize(frames)) { for (uint16_t i = 0; i != input_channels; ++i) { if (is_aligned(inputs[i])) nova::copyvec_simd(input_samples[i].get(), inputs[i], frames); else nova::copyvec(input_samples[i].get(), inputs[i], frames); inputs[i] += frames; } } else { for (uint16_t i = 0; i != input_channels; ++i) { nova::copyvec(input_samples[i].get(), inputs[i], frames); inputs[i] += frames; } } } void deliver_outputs(float** outputs, size_t frames, int output_channels) { if (is_multiple_of_vectorsize(frames)) { for (uint16_t i = 0; i != output_channels; ++i) { if (is_aligned(outputs[i])) nova::copyvec_simd(outputs[i], output_samples[i].get(), frames); else nova::copyvec(outputs[i], output_samples[i].get(), frames); outputs[i] += frames; } } else { for (uint16_t i = 0; i != output_channels; ++i) { nova::copyvec(outputs[i], output_samples[i].get(), frames); outputs[i] += frames; } } } static bool is_aligned(const void* arg) { size_t mask = sizeof(vec<float>::size) * sizeof(float) * 8 - 1; return !((size_t)arg & mask); } static bool is_multiple_of_vectorsize(size_t count) { return !(count & (vec<float>::objects_per_cacheline - 1)); } std::vector<aligned_storage_ptr<sample_type, managed_memory>, boost::alignment::aligned_allocator<aligned_storage_ptr<sample_type, managed_memory>, 64>> input_samples, output_samples; }; class audio_settings_basic { protected: float samplerate_ = 0.f; uint16_t input_channels = 0; uint16_t output_channels = 0; public: audio_settings_basic(void) {} float get_samplerate(void) const { return samplerate_; } uint16_t get_input_count(void) const { return input_channels; } uint16_t get_output_count(void) const { return output_channels; } }; } /* namespace detail */ } /* namespace nova */
5,547
C++
.h
115
41.008696
118
0.645078
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,200
jack_backend.hpp
supercollider_supercollider/server/supernova/audio_backend/jack_backend.hpp
// native jack backend // Copyright (C) 2009-2015 Tim Blechmann // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. #pragma once #include <iostream> #include <string> #include <vector> #include <jack/jack.h> #include <jack/thread.h> #ifdef SC_JACK_USE_METADATA_API # include <jack/metadata.h> # include <jack/uuid.h> # include <jackey.h> #endif #include "utilities/branch_hints.hpp" #include "audio_backend_common.hpp" #include "cpu_time_info.hpp" namespace nova { /** jack backend * * the jack callback thread is pinned to the first cpu of the system * * \todo later it may be interesting to directly map the io busses to the jack port regions * \todo rethink the use of output port lock */ template <typename engine_functor, typename sample_type = float, bool blocking = false> class jack_backend : public detail::audio_backend_base<sample_type, jack_default_audio_sample_t, blocking, false>, public detail::audio_settings_basic, protected engine_functor { typedef detail::audio_backend_base<sample_type, jack_default_audio_sample_t, blocking, false> super; public: jack_backend(void) = default; ~jack_backend(void) { if (audio_is_active()) deactivate_audio(); close_client(); } void initialize(void) {} uint32_t get_audio_blocksize(void) const { return blocksize_; } uint32_t get_latency(void) const { return latency_; } public: void open_client(std::string const& server_name, std::string const& name, uint32_t input_port_count, uint32_t output_port_count, uint32_t blocksize) { blocksize_ = blocksize; /* open client */ client = server_name.empty() ? jack_client_open(name.c_str(), JackNoStartServer, &status) : jack_client_open(name.c_str(), jack_options_t(JackNoStartServer | JackServerName), &status, server_name.c_str()); std::atomic_thread_fence(std::memory_order_release); // ensure visibility on other threads if (status & JackServerFailed) throw std::runtime_error("Unable to connect to JACK server"); if (status & JackNameNotUnique) { const char* client_name = jack_get_client_name(client); std::cout << "unique client name: " << client_name << std::endl; } /* initialize callbacks */ jack_set_thread_init_callback(client, jack_thread_init_callback, this); jack_set_process_callback(client, jack_process_callback, this); jack_set_xrun_callback(client, jack_xrun_callback, this); jack_set_graph_order_callback(client, jack_graph_order_callback, this); jack_on_info_shutdown(client, (JackInfoShutdownCallback)jack_on_info_shutdown_callback, nullptr); /* register ports */ input_ports.clear(); for (uint32_t i = 0; i != input_port_count; ++i) { std::string portname("input_"); portname += std::to_string(i + 1); jack_port_t* port = jack_port_register(client, portname.c_str(), JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0); input_ports.push_back(port); #ifdef SC_JACK_USE_METADATA_API jack_uuid_t uuid = jack_port_uuid(port); if (!jack_uuid_empty(uuid)) { std::string prettyname("Input "); prettyname += std::to_string(i + 1); jack_set_property(client, uuid, JACK_METADATA_PRETTY_NAME, prettyname.c_str(), "text/plain"); std::string order(""); order += std::to_string(i); jack_set_property(client, uuid, JACKEY_ORDER, order.c_str(), "http://www.w3.org/2001/XMLSchema#integer"); } #endif } input_channels = input_port_count; super::input_samples.resize(input_port_count); output_ports.clear(); for (uint32_t i = 0; i != output_port_count; ++i) { std::string portname("output_"); portname += std::to_string(i + 1); jack_port_t* port = jack_port_register(client, portname.c_str(), JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0); output_ports.push_back(port); #ifdef SC_JACK_USE_METADATA_API jack_uuid_t uuid = jack_port_uuid(port); if (!jack_uuid_empty(uuid)) { std::string prettyname("Output "); prettyname += std::to_string(i + 1); jack_set_property(client, uuid, JACK_METADATA_PRETTY_NAME, prettyname.c_str(), "text/plain"); std::string order(""); order += std::to_string(input_port_count + i); jack_set_property(client, uuid, JACKEY_ORDER, order.c_str(), "http://www.w3.org/2001/XMLSchema#integer"); } #endif } output_channels = output_port_count; super::output_samples.resize(output_port_count); samplerate_ = jack_get_sample_rate(client); jack_frames = jack_get_buffer_size(client); if (jack_frames % blocksize_) throw std::runtime_error("Jack buffer size is not a multiple of blocksize"); cpu_time_accumulator.resize(samplerate_, jack_frames, 1); } void close_client(void) { if (client) { jack_client_close(client); client = nullptr; } } bool audio_is_opened(void) { return client != nullptr; } bool audio_is_active(void) { return is_active; } void activate_audio(void) { is_active = true; jack_activate(client); } void deactivate_audio(void) { if (is_active) { jack_deactivate(client); is_active = false; } } void get_cpuload(float& peak, float& average) const { cpu_time_accumulator.get(peak, average); } int connect_input(size_t channel, const char* portname) { if (channel >= input_ports.size()) return -1; return jack_connect(client, portname, jack_port_name(input_ports[channel])); } int connect_output(size_t channel, const char* portname) { if (channel >= output_ports.size()) return -1; return jack_connect(client, jack_port_name(output_ports[channel]), portname); } int connect_all_inputs(const char* client_name) { const char** ports = jack_get_ports(client, client_name, nullptr, JackPortIsOutput); if (!ports) return -1; std::size_t i = 0; while (ports[i]) { if (i == input_ports.size()) break; int err = jack_connect(client, ports[i], jack_port_name(input_ports[i])); if (err) return err; ++i; } free(ports); return 0; } int connect_all_outputs(const char* client_name) { const char** ports = jack_get_ports(client, client_name, nullptr, JackPortIsInput); if (!ports) return -1; std::size_t i = 0; while (ports[i]) { if (i == output_ports.size()) break; int err = jack_connect(client, jack_port_name(output_ports[i]), ports[i]); if (err) return err; ++i; } free(ports); return 0; } int max_realtime_priority(void) const { return jack_client_max_real_time_priority(client); } int realtime_priority(void) const { return jack_client_real_time_priority(client); } private: static void jack_thread_init_callback(void* arg) { std::atomic_thread_fence(std::memory_order_acquire); jack_backend* self = static_cast<jack_backend*>(arg); if (jack_client_thread_id(self->client) == pthread_self()) engine_functor::init_thread(); else name_thread("Jack Helper"); } static int jack_process_callback(jack_nframes_t frames, void* arg) { return static_cast<jack_backend*>(arg)->perform(frames); } static int jack_on_info_shutdown_callback(jack_status_t code, const char* reason, void* arg) { std::cerr << "Jack server was shut down: " << reason << std::endl; std::cerr << "Exiting ..." << std::endl; exit(0); // TODO: later we may want to call a function } static int jack_xrun_callback(void* arg) { return static_cast<jack_backend*>(arg)->handle_xrun(); } static int jack_graph_order_callback(void* arg) { return static_cast<jack_backend*>(arg)->graph_order_changed(); } int handle_xrun(void) { time_is_synced = false; engine_functor::log_("Jack: xrun detected - resyncing clock\n"); return 0; } int graph_order_changed() { time_is_synced = false; jack_nframes_t lat = 0; for (auto const& port : output_ports) { jack_latency_range_t range; jack_port_get_latency_range(port, JackPlaybackLatency, &range); jack_nframes_t portLat = range.max; if (portLat > lat) lat = portLat; } uint32_t latency = (uint32_t)lat; if (latency != latency_) { latency_ = latency; double latms = lat / samplerate_ * 1e3; engine_functor::log_printf_("JackDriver: max output latency %.1f ms\n", latms); } return true; } int perform(jack_nframes_t frames) { if (unlikely(!time_is_synced)) { engine_functor::sync_clock(); time_is_synced = true; } /* get port regions */ jack_default_audio_sample_t** inputs = (jack_default_audio_sample_t**)alloca(input_channels * sizeof(jack_default_audio_sample_t*)); jack_default_audio_sample_t** outputs = (jack_default_audio_sample_t**)alloca(output_channels * sizeof(jack_default_audio_sample_t*)); for (uint16_t i = 0; i != input_channels; ++i) inputs[i] = (jack_default_audio_sample_t*)jack_port_get_buffer(input_ports[i], frames); for (uint16_t i = 0; i != output_channels; ++i) outputs[i] = (jack_default_audio_sample_t*)jack_port_get_buffer(output_ports[i], frames); jack_nframes_t processed = 0; while (processed != frames) { super::fetch_inputs((const float**)inputs, blocksize_, input_channels); engine_functor::run_tick(); super::deliver_outputs(outputs, blocksize_, output_channels); processed += blocksize_; } cpu_time_accumulator.update(jack_cpu_load(client)); return 0; } static int jack_buffersize_callback(jack_nframes_t frames, void* arg) { return static_cast<jack_backend*>(arg)->buffer_size_callback(frames); } int buffer_size_callback(jack_nframes_t frames) { jack_frames = frames; if (jack_frames % blocksize_) /* we need a multiple of the blocksize */ return 1; return 0; } jack_client_t* client = nullptr; jack_status_t status; bool is_active = false; bool time_is_synced = false; uint32_t blocksize_; std::vector<jack_port_t*> input_ports, output_ports; jack_nframes_t jack_frames; cpu_time_info cpu_time_accumulator; uint32_t latency_; }; } /* namespace nova */
12,096
C++
.h
277
34.830325
118
0.610402
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,201
portaudio_backend.hpp
supercollider_supercollider/server/supernova/audio_backend/portaudio_backend.hpp
// portaudio backend // Copyright (C) 2006 - 2013 Tim Blechmann // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. #pragma once #include <cstdio> #include <string> #include <algorithm> #include "portaudio.h" #ifdef HAVE_PORTAUDIO_CONFIG_H # include "portaudio/portaudio_config.h" #endif /* HAVE_PORTAUDIO_CONFIG_H */ #include "audio_backend_common.hpp" #include "utilities/branch_hints.hpp" #include "cpu_time_info.hpp" #include "SC_PaUtils.hpp" #include "simd_binary_arithmetic.hpp" namespace nova { /** \brief portaudio backend for supernova * * */ template <typename engine_functor, typename sample_type = float, bool blocking = false> class portaudio_backend : public detail::audio_backend_base<sample_type, float, blocking, false>, public detail::audio_settings_basic, protected engine_functor { typedef detail::audio_backend_base<sample_type, float, blocking, false> super; public: portaudio_backend(void) = default; ~portaudio_backend(void) { if (audio_is_active()) deactivate_audio(); close_stream(); int err = Pa_Terminate(); report_error(err); } void initialize(void) { int err = Pa_Initialize(); report_error(err, true); list_devices(); #ifdef PA_HAVE_JACK PaJack_SetClientName("SuperNova"); #endif } uint32_t get_audio_blocksize(void) const { return blocksize_; } uint32_t get_latency(void) const { return latency_; } private: // this will be clipped to the number of available hardware outs uint16_t m_hwOutputChannels = 0; private: static void report_error(int err, bool throw_exception = false) { if (err < 0) { engine_functor::log_printf_("PortAudio error: %s\n", Pa_GetErrorText(err)); if (throw_exception) throw std::runtime_error("PortAudio error"); } } public: static void list_devices(void) { int device_number = Pa_GetDeviceCount(); if (device_number < 0) report_error(device_number); printf("Available Audio Devices:\n"); for (int i = 0; i < device_number; i++) { const PaDeviceInfo* pdi = Pa_GetDeviceInfo(i); printf("%d: %s (%d ins, %d outs)\n", i, GetPaDeviceName(i).c_str(), pdi->maxInputChannels, pdi->maxOutputChannels); } printf("\n"); } void report_latency() { const PaStreamInfo* psi = Pa_GetStreamInfo(stream); if (psi) { fprintf(stdout, " Sample rate: %.3f\n", psi->sampleRate); fprintf(stdout, " Latency (in/out): %.3f / %.3f sec\n", psi->inputLatency, psi->outputLatency); } } // open PA stream // input_device and output_device are names of requested audio devices // if empty, default system device(s) will be used // inchans and outchans are numbers of requested hardware input/output channels // setting inchans/outchans to 0 disables input/output respctively bool open_stream(std::string const& input_device, unsigned int inchans, std::string const& output_device, unsigned int outchans, unsigned int samplerate, unsigned int pa_blocksize, int h_blocksize, float safety_clip_threshold) { int input_device_index, output_device_index; input_device_index = GetPaDeviceFromName(input_device.c_str(), true); output_device_index = GetPaDeviceFromName(output_device.c_str(), false); // check device selection, select defaults if needed std::cout << std::endl; PaError checked = TryGetDefaultPaDevices(&input_device_index, &output_device_index, inchans, outchans, samplerate); std::cout << std::endl; std::cout << "Opening audio devices:" << std::endl; if (inchans) std::cout << " In: " << GetPaDeviceName(input_device_index) << std::endl; if (outchans) std::cout << " Out: " << GetPaDeviceName(output_device_index) << std::endl; // if we got an error from CheckPaDevices, stop here if (checked != paNoError) { report_error(checked); return false; } PaStreamParameters in_parameters, out_parameters; PaTime suggestedLatencyIn, suggestedLatencyOut; if (!samplerate) { if (outchans) samplerate = Pa_GetDeviceInfo(output_device_index)->defaultSampleRate; else if (inchans) samplerate = Pa_GetDeviceInfo(input_device_index)->defaultSampleRate; // use 44100 as a last resort if (samplerate == 0) samplerate = 44100; } if (h_blocksize == 0) { if (inchans) suggestedLatencyIn = Pa_GetDeviceInfo(input_device_index)->defaultHighInputLatency; if (outchans) suggestedLatencyOut = Pa_GetDeviceInfo(output_device_index)->defaultHighOutputLatency; } else { if (h_blocksize < 0) { if (inchans) suggestedLatencyIn = Pa_GetDeviceInfo(input_device_index)->defaultLowInputLatency; if (outchans) suggestedLatencyOut = Pa_GetDeviceInfo(output_device_index)->defaultLowOutputLatency; } else suggestedLatencyIn = suggestedLatencyOut = (double)h_blocksize / (double)samplerate; } if (inchans) { const PaDeviceInfo* device_info = Pa_GetDeviceInfo(input_device_index); inchans = std::min(inchans, (unsigned int)device_info->maxInputChannels); in_parameters = MakePaStreamParameters(input_device_index, inchans, suggestedLatencyIn); } if (outchans) { const PaDeviceInfo* device_info = Pa_GetDeviceInfo(output_device_index); m_hwOutputChannels = std::min(outchans, (unsigned int)device_info->maxOutputChannels); out_parameters = MakePaStreamParameters(output_device_index, m_hwOutputChannels, suggestedLatencyOut); } PaStreamParameters* in_stream_parameters = inchans ? &in_parameters : nullptr; PaStreamParameters* out_stream_parameters = outchans ? &out_parameters : nullptr; PaError supported = Pa_IsFormatSupported(in_stream_parameters, out_stream_parameters, samplerate); if (supported != paNoError) { report_error(supported); return false; } engine_initialized = false; blocksize_ = pa_blocksize; safety_clip_threshold_ = safety_clip_threshold; auto process_func = (safety_clip_threshold > 0 && safety_clip_threshold < INFINITY) ? &portaudio_backend::pa_process<true> : &portaudio_backend::pa_process<false>; PaError opened = Pa_OpenStream(&stream, in_stream_parameters, out_stream_parameters, samplerate, pa_blocksize, paNoFlag, process_func, this); report_error(opened); if (opened != paNoError) return false; else { const PaStreamInfo* psi = Pa_GetStreamInfo(stream); if (psi) latency_ = (uint32_t)(psi->outputLatency * psi->sampleRate); } // input_channels is clipped to the number of available audio inputs // output_channels is equal to the requested number of outputs (not clipped) input_channels = inchans; super::input_samples.resize(inchans); output_channels = outchans; super::output_samples.resize(m_hwOutputChannels); samplerate_ = samplerate; cpu_time_accumulator.resize(samplerate_, blocksize_, 1); return true; } void close_stream(void) { if (stream == nullptr) return; deactivate_audio(); int err = Pa_CloseStream(stream); report_error(err); stream = nullptr; } void activate_audio() { assert(stream); int err = Pa_StartStream(stream); report_error(err); } bool audio_is_active(void) { if (stream == nullptr) return false; int is_active = Pa_IsStreamActive(stream); if (is_active == 1) return true; if (is_active == 0) return false; report_error(is_active); return false; } void deactivate_audio() { if (audio_is_active()) { PaError err = Pa_StopStream(stream); report_error(err); } } bool audiostream_ready(void) { return stream; } void get_cpuload(float& peak, float& average) const { cpu_time_accumulator.get(peak, average); } private: template <bool IsClipping> int perform(const void* inputBuffer, void* outputBuffer, unsigned long frames, const PaStreamCallbackTimeInfo* timeInfo, PaStreamCallbackFlags statusFlags) { if (unlikely(!engine_initialized)) { engine_functor::init_thread(); engine_functor::sync_clock(); engine_initialized = true; } if (statusFlags & (paInputOverflow | paInputUnderflow | paOutputOverflow | paOutputUnderflow)) engine_functor::sync_clock(); auto** inputs = static_cast<const float**>(alloca(sizeof(float*) * input_channels)); float* const* in = static_cast<float* const*>(inputBuffer); for (uint16_t i = 0; i != input_channels; ++i) inputs[i] = in[i]; auto** outputs = static_cast<float**>(alloca(sizeof(float*) * m_hwOutputChannels)); float** out = static_cast<float**>(outputBuffer); for (uint16_t i = 0; i != m_hwOutputChannels; ++i) outputs[i] = out[i]; unsigned long processed = 0; while (processed != frames) { super::fetch_inputs(inputs, blocksize_, input_channels); engine_functor::run_tick(); super::deliver_outputs(outputs, blocksize_, m_hwOutputChannels); if (IsClipping) for (uint16_t i = 0; i != m_hwOutputChannels; ++i) if (super::is_aligned(out[i])) clip2_vec_simd(out[i], out[i], safety_clip_threshold_, blocksize_); else clip2_vec(out[i], out[i], safety_clip_threshold_, blocksize_); processed += blocksize_; } cpu_time_accumulator.update(Pa_GetStreamCpuLoad(stream) * 100.0); return paContinue; } template <bool IsClipping> static int pa_process(const void* input, void* output, unsigned long frame_count, const PaStreamCallbackTimeInfo* time_info, PaStreamCallbackFlags status_flags, void* user_data) { portaudio_backend* self = static_cast<portaudio_backend*>(user_data); return self->perform<IsClipping>(input, output, frame_count, time_info, status_flags); } PaStream* stream = nullptr; uint32_t blocksize_ = 0; bool engine_initialized = false; cpu_time_info cpu_time_accumulator; uint32_t latency_ = 0; float safety_clip_threshold_ = 0; }; } /* namespace nova */
11,932
C++
.h
265
35.845283
118
0.628653
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,202
sndfile_backend.hpp
supercollider_supercollider/server/supernova/audio_backend/sndfile_backend.hpp
// file-based backend (via libsndfile) // Copyright (C) 2010-2013 Tim Blechmann // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. #pragma once #include <atomic> #include <chrono> #include <cmath> #include <deque> #include <string> #include <thread> #include <vector> #include <boost/align/aligned_allocator.hpp> #include <boost/lockfree/spsc_queue.hpp> #include <boost/sync/semaphore.hpp> #include "SC_SndFileHelpers.hpp" #include "nova-tt/name_thread.hpp" #include "utilities/branch_hints.hpp" #include "audio_backend_common.hpp" namespace nova { /** sndfile backend * * audio backend, reading/writing sound files via libsndfile * */ template <typename engine_functor, typename sample_type = float, bool blocking = false> class sndfile_backend : public detail::audio_backend_base<sample_type, float, blocking, false>, public detail::audio_settings_basic, private engine_functor { typedef detail::audio_backend_base<sample_type, float, blocking, false> super; typedef std::size_t size_t; static const size_t queue_size = 10 * 1024 * 1024; // 30 MB public: sndfile_backend(void): read_frames(queue_size), write_frames(queue_size) {} size_t get_audio_blocksize(void) const { return block_size_; } std::vector<sample_type> const& get_peaks() const { return max_peaks; } public: void open_client(std::string const& input_file_name, std::string const& output_file_name, float samplerate, int format, uint32_t output_channel_count, size_t block_size) { output_channels = output_channel_count; max_peaks.assign(output_channels, 0); samplerate_ = samplerate = std::floor(samplerate); block_size_ = block_size; if (!input_file_name.empty()) { input_file = makeSndfileHandle(input_file_name.c_str(), SFM_READ); if (input_file.rawHandle() == nullptr) throw std::runtime_error(std::string("input file: ") + input_file.strError()); if (input_file.samplerate() != samplerate) throw std::runtime_error("input file: samplerate mismatch"); input_channels = input_file.channels(); super::input_samples.resize(input_channels); } else input_channels = 0; read_position = 0; output_file = makeSndfileHandle(output_file_name.c_str(), SFM_WRITE, format, output_channel_count, samplerate); if (output_file.rawHandle() == nullptr) throw std::runtime_error(std::string("output file: ") + output_file.strError()); output_file.command(SFC_SET_CLIPPING, nullptr, SF_TRUE); super::output_samples.resize(output_channel_count); temp_buffer.reset(calloc_aligned<float>(std::max(input_channels, output_channels) * block_size)); } void close_client(void) { output_file.writeSync(); input_file = output_file = SndfileHandle(); } bool audio_is_opened(void) { return output_file; } bool audio_is_active(void) { return running.load(std::memory_order_acquire); } void activate_audio(void) { running.store(true); if (input_file) { reader_running.store(true); reader_thread = std::thread(std::bind(&sndfile_backend::sndfile_read_thread, this)); } writer_running.store(true); writer_thread = std::thread(std::bind(&sndfile_backend::sndfile_write_thread, this)); } void deactivate_audio(void) { running.store(false); if (input_file) { reader_running.store(false); reader_thread.join(); } writer_running.store(false); write_semaphore.post(); writer_thread.join(); } private: /* read input fifo from the rt context */ void read_input_buffers(size_t frames_per_tick) { if (reader_running.load(std::memory_order_acquire)) { const size_t total_samples = input_channels * frames_per_tick; size_t remaining = total_samples; read_semaphore.wait(); do { remaining -= read_frames.pop(temp_buffer.get(), remaining); if (unlikely(read_frames.empty() && !reader_running.load(std::memory_order_acquire))) { /* at the end, we are not able to read a full sample block, clear the final parts */ const size_t last_frame = (total_samples - remaining) / input_channels; const size_t remaining_per_channel = remaining / input_channels; assert(remaining % input_channels == 0); assert(remaining_per_channel % input_channels == 0); for (uint16_t channel = 0; channel != input_channels; ++channel) zerovec(super::input_samples[channel].get() + last_frame, remaining_per_channel); break; } } while (remaining); const size_t frames = (total_samples - remaining) / input_channels; for (size_t frame = 0; frame != frames; ++frame) { for (uint16_t channel = 0; channel != input_channels; ++channel) super::input_samples[channel].get()[frame] = temp_buffer.get()[frame * input_channels + channel]; } } else super::clear_inputs(frames_per_tick); } void sndfile_read_thread(void) { nova::name_thread("sndfile reader"); assert(input_file); const size_t frames_per_tick = get_audio_blocksize(); // something like autobuffer might be good std::vector<sample_type, boost::alignment::aligned_allocator<sample_type, 64>> data_to_read( input_channels * frames_per_tick, 0.f); for (;;) { if (unlikely(reader_running.load(std::memory_order_acquire) == false)) return; if (read_position < (size_t)input_file.frames()) { size_t frames = input_file.frames() - read_position; if (frames > frames_per_tick) frames = frames_per_tick; input_file.readf(data_to_read.data(), frames); read_position += frames; const size_t item_to_enqueue = input_channels * frames; size_t remaining = item_to_enqueue; do { remaining -= read_frames.push(data_to_read.data(), remaining); } while (remaining); read_semaphore.post(); } else reader_running.store(false, std::memory_order_release); } } /* write output fifo from rt context */ void write_output_buffers(size_t frames_per_tick) { for (size_t frame = 0; frame != frames_per_tick; ++frame) { for (uint16_t channel = 0; channel != output_channels; ++channel) temp_buffer.get()[frame * output_channels + channel] = super::output_samples[channel].get()[frame]; } const size_t total_samples = output_channels * frames_per_tick; sample_type* buffer = temp_buffer.get(); size_t count = total_samples; do { size_t consumed = write_frames.push(buffer, count); count -= consumed; buffer += consumed; write_semaphore.post(); if (!consumed) std::this_thread::sleep_for(std::chrono::milliseconds(50)); } while (count); } void sndfile_write_thread(void) { nova::name_thread("sndfile writer"); const size_t frames_per_tick = get_audio_blocksize(); const size_t deque_per_tick = output_channels * frames_per_tick * 64; aligned_storage_ptr<sample_type> data_to_write(deque_per_tick); size_t pending_samples = 0; for (;;) { write_semaphore.wait(); poll_writer_queue(data_to_write.get(), deque_per_tick, pending_samples); if (unlikely(writer_running.load(std::memory_order_acquire) == false)) break; } while (poll_writer_queue(data_to_write.get(), deque_per_tick, pending_samples)) {} } bool poll_writer_queue(sample_type* data_to_write, const size_t buffer_samples, size_t& pending_samples) { bool consumed_item = false; for (;;) { const size_t available_samples = write_frames.read_available(); const size_t available_frames = available_samples / output_channels; if (available_frames == 0) return consumed_item; const size_t buffer_frames = buffer_samples / output_channels; const size_t frames_to_read = std::min(available_frames, buffer_frames); const size_t samples_to_read = frames_to_read * output_channels; const size_t dequeued = write_frames.pop(data_to_write, samples_to_read); assert(dequeued == samples_to_read); consumed_item = true; const sf_count_t written_frames = output_file.writef(data_to_write, frames_to_read); assert(frames_to_read == written_frames); if (written_frames == -1) throw std::runtime_error(std::string("sndfile write failed: ") + output_file.strError()); for (size_t frame = 0; frame != frames_to_read; ++frame) { for (size_t channel = 0; channel != output_channels; ++channel) { const sample_type current_sample = data_to_write[frame * output_channels + channel]; sample_type current_peak = max_peaks[channel]; max_peaks[channel] = std::max(current_peak, std::abs(current_sample)); } } } return consumed_item; } public: void audio_fn_noinput(size_t frames_per_tick) { engine_functor::run_tick(); write_output_buffers(frames_per_tick); } void audio_fn(size_t frames_per_tick) { super::clear_outputs(frames_per_tick); read_input_buffers(frames_per_tick); engine_functor::run_tick(); write_output_buffers(frames_per_tick); } private: SndfileHandle input_file, output_file; std::size_t read_position; int block_size_; aligned_storage_ptr<sample_type> temp_buffer; std::thread reader_thread, writer_thread; boost::lockfree::spsc_queue<sample_type> read_frames, write_frames; boost::sync::semaphore read_semaphore, write_semaphore; std::atomic<bool> running = { false }, reader_running = { false }, writer_running = { false }; std::vector<sample_type> max_peaks; }; } /* namespace nova */
11,368
C++
.h
235
38.817021
119
0.619904
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,203
cpu_time_info.hpp
supercollider_supercollider/server/supernova/audio_backend/cpu_time_info.hpp
// cpu time info // Copyright (C) 2011-2015 Tim Blechmann // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. #pragma once #include <vector> #include <boost/align/aligned_allocator.hpp> #include "nova-simd/simd_horizontal_functions.hpp" namespace nova { class cpu_time_info { typedef std::vector<float, boost::alignment::aligned_allocator<float, 64>> ringbuffer; public: cpu_time_info() {} void resize(int sampleRate, int blockSize, int seconds = 1) { const size_t blocks = sampleRate * seconds / blockSize; size = std::max(size_t(1), blocks); buffer.resize(size, 0.f); index = size - 1; } void update(float f) { ++index; if (index == size) index = 0; buffer[index] = f; } void get(float& peak, float& average) const { const float average_factor = 1.f / size; float sum; horizontal_maxsum_vec_simd(peak, sum, buffer.data(), size); average = sum * average_factor; } private: std::size_t size = 0; std::size_t index = 0; ringbuffer buffer; }; }
1,805
C++
.h
50
31.96
90
0.680253
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,204
ML.h
supercollider_supercollider/server/plugins/ML.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "SC_PlugIn.h" // global data // helpful constants //#define PI 3.1415926535898f //#define TWOPI 6.28318530717952646f extern InterfaceTable* ft; // shared data extern int eqlbandbins[43]; extern int eqlbandsizes[42]; extern float contours[42][11]; extern double phons[11]; //#include "KeyTrack.h" #include "BeatTrack.h" //#include "Loudness.h" #include "Onsets.h" //#include "MFCC.h" #include "BeatTrack2.h" struct Loudness : Unit { // FFT data int m_numbands; float* m_ERBbands; // float m_phontotal; // final output float m_sones; }; struct KeyTrack : Unit { // FFT data float* m_FFTBuf; // coping with different sampling rates float m_srate; // use as a flag to check sample rate is correct float* m_weights; // will point to the sample rate specific data int* m_bins; float m_frameperiod; // counter // uint32 m_frame; // experimental transient avoidance // float m_prevphase[720]; //60*12 // float m_leaknote[60]; float m_chroma[12]; float m_key[24]; float m_histogram[24]; // key histogram // float m_keyleak; //fade parameter for histogram // int m_triggerid; int m_currentKey; }; struct MFCC : Unit { // MFCC int m_numcoefficients; float* m_mfcc; // ERB int m_numbands; float* m_bands; // sampling rate specific data float m_srate; int* m_startbin; int* m_endbin; int* m_cumulindex; float* m_bandweights; }; ////////////////////////////////////////////////////////////////////////////////////////////////// struct FFTAnalyser_Unit : Unit { float outval; // Not always used: multipliers which convert from bin indices to freq vals, and vice versa. // See also the macros for deriving these. float m_bintofreq /* , m_freqtobin */; float m_halfnyq_over_numbinsp2; }; struct FFTAnalyser_OutOfPlace : FFTAnalyser_Unit { int m_numbins; float* m_tempbuf; }; struct SpecFlatness : FFTAnalyser_Unit { double m_oneovern; }; struct SpecPcile : FFTAnalyser_OutOfPlace { bool m_interpolate; bool m_binout; }; struct SpecCentroid : FFTAnalyser_Unit {}; extern "C" { // required interface functions void Loudness_next(Loudness* unit, int wrongNumSamples); void Loudness_Ctor(Loudness* unit); void Loudness_Dtor(Loudness* unit); void KeyTrack_next(KeyTrack* unit, int wrongNumSamples); void KeyTrack_Ctor(KeyTrack* unit); void KeyTrack_Dtor(KeyTrack* unit); void MFCC_next(MFCC* unit, int wrongNumSamples); void MFCC_Ctor(MFCC* unit); void MFCC_Dtor(MFCC* unit); void SpecFlatness_Ctor(SpecFlatness* unit); void SpecFlatness_next(SpecFlatness* unit, int inNumSamples); // void SpecPcile_Ctor(SpecPcile* unit); void SpecPcile_next(SpecPcile* unit, int inNumSamples); void SpecPcile_Dtor(SpecPcile* unit); // void SpecCentroid_Ctor(SpecCentroid* unit); void SpecCentroid_next(SpecCentroid* unit, int inNumSamples); }
3,791
C++
.h
116
29.422414
98
0.712991
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,205
SIMD_Unit.hpp
supercollider_supercollider/server/plugins/SIMD_Unit.hpp
/* * SuperCollider real time audio synthesis system * Copyright (c) 2002 James McCartney. All rights reserved. * Copyright (c) 2011 Tim Blechmann. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include "SC_PlugIn.hpp" #include "simd_memory.hpp" #include "simd_binary_arithmetic.hpp" #include "simd_ternary_arithmetic.hpp" #include "simd_mix.hpp" using nova::slope_argument; #if defined(__GNUC__) && !defined(__clang__) # define inline_functions __attribute__((flatten)) #else # define inline_functions #endif struct SIMD_Unit : SCUnit { enum { scalar, unrolled, unrolled_64 }; bool canUseSIMD(void) const { return (mBufLength & (nova::vec<float>::objects_per_cacheline - 1)) == 0; } template <int index> struct ControlRateInput { float value; void init(const SIMD_Unit* parent) { value = parent->in0(index); } bool changed(const SIMD_Unit* parent) const { return value != parent->in0(index); } #if __cplusplus <= 199711L nova::detail::scalar_ramp_argument<float> slope(const SIMD_Unit* parent) #else decltype(nova::slope_argument(0.f, 0.f)) slope(const SIMD_Unit* parent) #endif { float next = parent->in0(index); float current = value; float slope = parent->calcSlope(next, current); value = next; return slope_argument(current, slope); } operator float(void) { return value; } }; template <typename UnitType, void (UnitType::*UnrolledCalcFunc)(int), void (UnitType::*VectorCalcFunc)(int), void (UnitType::*ScalarCalcFunc)(int)> void set_unrolled_calc_function(void) { if (bufferSize() == 64) SCUnit::set_vector_calc_function<UnitType, UnrolledCalcFunc, ScalarCalcFunc>(); else set_vector_calc_function<UnitType, VectorCalcFunc, ScalarCalcFunc>(); } template <typename UnitType, void (UnitType::*VectorCalcFunc)(int), void (UnitType::*ScalarCalcFunc)(int)> void set_vector_calc_function(void) { if (canUseSIMD()) SCUnit::set_vector_calc_function<UnitType, VectorCalcFunc, ScalarCalcFunc>(); else SCUnit::set_calc_function<UnitType, ScalarCalcFunc>(); } template <int type, typename Arg1, typename Arg2, typename Arg3> static void muladd(float* out, Arg1 const& arg1, Arg2 const& arg2, Arg3 const& arg3, int inNumSamples) { if (type == scalar) nova::muladd_vec(out, arg1, arg2, arg3, inNumSamples); if (type == unrolled) nova::muladd_vec_simd(out, arg1, arg2, arg3, inNumSamples); if (type == unrolled_64) nova::muladd_vec_simd<64>(out, arg1, arg2, arg3); } template <int type, typename Arg1, typename Arg2> static void plus_vec(float* out, Arg1 const& arg1, Arg2 const& arg2, int inNumSamples) { if (type == scalar) nova::plus_vec(out, arg1, arg2, inNumSamples); if (type == unrolled) nova::plus_vec_simd(out, arg1, arg2, inNumSamples); if (type == unrolled_64) nova::plus_vec_simd<64>(out, arg1, arg2); } template <int type, typename Arg1, typename Arg2> static void times_vec(float* out, Arg1 const& arg1, Arg2 const& arg2, int inNumSamples) { if (type == scalar) nova::times_vec(out, arg1, arg2, inNumSamples); if (type == unrolled) nova::times_vec_simd(out, arg1, arg2, inNumSamples); if (type == unrolled_64) nova::times_vec_simd<64>(out, arg1, arg2); } template <int type, typename Arg1, typename Arg2> static void slope_vec(float* out, Arg1 const& base, Arg2 const& slope, int inNumSamples) { if (type == scalar) nova::set_slope_vec(out, base, slope, inNumSamples); else nova::set_slope_vec_simd(out, base, slope, inNumSamples); } template <int type, typename Arg1> static void slope_vec(float* out, Arg1 const& slope, int inNumSamples) { if (type == scalar) nova::set_slope_vec(out, slope.data, slope.slope_, inNumSamples); else nova::set_slope_vec_simd(out, slope.data, slope.slope_, inNumSamples); } template <int type> static void copy_vec(float* out, const float* in, int inNumSamples) { if (in == out) return; if (type == scalar) nova::copyvec(out, in, inNumSamples); if (type == unrolled) nova::copyvec_simd(out, in, inNumSamples); if (type == unrolled_64) nova::copyvec_simd<64>(out, in); } template <int type> static void set_vec(float* out, float value, int inNumSamples) { if (type == scalar) nova::setvec(out, value, inNumSamples); if (type == unrolled) nova::setvec_simd(out, value, inNumSamples); if (type == unrolled_64) nova::setvec_simd<64>(out, value); } template <int type> static void zero_vec(float* out, int inNumSamples) { if (type == scalar) nova::zerovec(out, inNumSamples); if (type == unrolled) nova::zerovec_simd(out, inNumSamples); if (type == unrolled_64) nova::zerovec_simd<64>(out); } };
5,991
C++
.h
134
37.447761
112
0.639356
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,206
Onsets.h
supercollider_supercollider/server/plugins/Onsets.h
/* Onset detector for SuperCollider Copyright (c) 2007 Dan Stowell. All rights reserved. http://onsetsds.sourceforge.net Now part of: SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "onsetsds.h" struct Onsets : Unit { float outval; float* m_odsdata; OnsetsDS* m_ods; bool m_needsinit; }; extern "C" { void Onsets_Ctor(Onsets* unit); void Onsets_next(Onsets* unit, int inNumSamples); void Onsets_next_rawodf(Onsets* unit, int inNumSamples); void Onsets_Dtor(Onsets* unit); }
1,343
C++
.h
33
36.757576
81
0.749424
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,207
onsetsds.h
supercollider_supercollider/server/plugins/onsetsds.h
/* OnsetsDS - real time musical onset detection library. Copyright (c) 2007 Dan Stowell. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** \file */ #pragma once #ifdef __cplusplus extern "C" { #endif #include <stdio.h> #include <string.h> #include <stdbool.h> #include <math.h> //////////////////////////////////////////////////////////////////////////////// // Macros and consts // log(0.1) #define ods_log1 -2.30258509 #define PI 3.1415926535898f #define MINUSPI -3.1415926535898f #define TWOPI 6.28318530717952646f #define INV_TWOPI 0.1591549430919f #define ods_abs(a) ((a) < 0 ? -(a) : (a)) #define ods_max(a, b) (((a) > (b)) ? (a) : (b)) #define ods_min(a, b) (((a) < (b)) ? (a) : (b)) #define ODS_LOG_LOWER_LIMIT 2e-42 #define ODS_LOGOF_LOG_LOWER_LIMIT -96.0154267 #define ODS_ABSINVOF_LOGOF_LOG_LOWER_LIMIT 0.010414993 //////////////////////////////////////////////////////////////////////////////// // Constants /** * Types of incoming FFT data format. OnsetsDS needs to know where the FFT * data comes from in order to interpret it correctly. */ enum onsetsds_fft_types { ODS_FFT_SC3_COMPLEX, ///< SuperCollider, cartesian co-ords ("SCComplexBuf") - NB it's more efficient to provide ///< polar data from SC ODS_FFT_SC3_POLAR, ///< SuperCollider, polar co-ords ("SCPolarBuf") ODS_FFT_FFTW3_HC, ///< FFTW <a ///< href="http://www.fftw.org/fftw3_doc/The-Halfcomplex_002dformat-DFT.html">"halfcomplex"</a> ///< format ODS_FFT_FFTW3_R2C ///< FFTW regular format, typically produced using <a ///< href="http://www.fftw.org/fftw3_doc/One_002dDimensional-DFTs-of-Real-Data.html#One_002dDimensional-DFTs-of-Real-Data">real-to-complex</a> ///< transform }; /** * Types of onset detection function */ enum onsetsds_odf_types { ODS_ODF_POWER, ///< Power ODS_ODF_MAGSUM, ///< Sum of magnitudes ODS_ODF_COMPLEX, ///< Complex-domain deviation ODS_ODF_RCOMPLEX, ///< Complex-domain deviation, rectified (only increases counted) ODS_ODF_PHASE, ///< Phase deviation ODS_ODF_WPHASE, ///< Weighted phase deviation ODS_ODF_MKL ///< Modified Kullback-Liebler deviation }; /** * Types of whitening - may not all be implemented yet. */ enum onsetsds_wh_types { ODS_WH_NONE, ///< No whitening - onsetsds_whiten() becomes a no-op ODS_WH_ADAPT_MAX1, ///< Adaptive whitening - tracks recent-peak-magnitude in each bin, normalises that to 1 ODS_WH_NORMMAX, ///< Simple normalisation - each frame is normalised (independent of others) so largest magnitude ///< becomes 1. Not implemented. ODS_WH_NORMMEAN ///< Simple normalisation - each frame is normalised (independent of others) so mean magnitude ///< becomes 1. Not implemented. }; //////////////////////////////////////////////////////////////////////////////// // Structs typedef struct OdsPolarBin { float mag, phase; } OdsPolarBin; typedef struct OdsPolarBuf { float dc, nyq; OdsPolarBin bin[1]; } OdsPolarBuf; /// The main data structure for the onset detection routine typedef struct OnsetsDS { /// "data" is a pointer to the memory that must be EXTERNALLY allocated. /// Other pointers will point to locations within this memory. float *data, *psp, ///< Peak Spectral Profile - size is numbins+2, data is stored in order dc through to nyquist *odfvals, // odfvals[0] will be the current val, odfvals[1] prev, etc *sortbuf, // Used to calculate the median *other; // Typically stores data about the previous frame OdsPolarBuf* curr; // Current FFT frame, as polar float srate, ///< The sampling rate of the input audio. Set by onsetsds_init() // Adaptive whitening params relaxtime, ///< Do NOT set this directly. Use onsetsds_setrelax() which will also update relaxcoef. relaxcoef, ///< Relaxation coefficient (memory coefficient). See also onsetsds_setrelax() floor, ///< floor - the lowest value that a PSP magnitude can take. /// A parameter for the ODF. For most this is a magnitude threshold for a single bin to be considered; /// but for #ODS_ODF_MKL it is the "epsilon" parameter. odfparam, /// Value used internally to scale ODF value according to the FFT frame size. Automatically set by /// onsetsds_init() normfactor, // ODF val after median processing odfvalpost, // Previous val is needed for threshold-crossing detection odfvalpostprev, /// Threshold (of ODF value, after median processing) for detection. /// Values between 0 and 1 are expected, but outside this range may /// sometimes be appropriate too. thresh; int odftype, ///< Choose from #onsetsds_odf_types whtype, ///< Choose from #onsetsds_wh_types fftformat; ///< Choose from #onsetsds_fft_types bool whiten, ///< Whether to apply whitening - onsetsds_init() decides this on your behalf detected, ///< Output val - true if onset detected in curr frame /** NOT YET USED: Whether to convert magnitudes to log domain before processing. This is done as follows: Magnitudes below a log-lower-limit threshold (ODS_LOG_LOWER_LIMIT) are pushed up to that threshold (to avoid log(0) infinity problems), then the log is taken. The values are re-scaled to a similar range as the linear-domain values (assumed to lie between zero and approximately one) by subtracting log(ODS_LOG_LOWER_LIMIT) and then dividing by abs(log(ODS_LOG_LOWER_LIMIT)). */ logmags, med_odd; ///< Whether median span is odd or not (used internally) unsigned int /// Number of frames used in median calculation medspan, /// Size of enforced gap between detections, measured in FFT frames. mingap, gapleft; size_t fftsize, numbins; // numbins is the count not including DC/nyq } OnsetsDS; //////////////////////////////////////////////////////////////////////////////// // Function prototypes /** * \defgroup MainUserFuncs Main user functions */ //@{ /** * Determine how many bytes of memory must be allocated (e.g. using malloc) to * accompany the OnsetsDS struct, operating using the specified settings (used to * store part-processed FFT data etc). The user must * call this, and then allocate the memory, BEFORE calling onsetsds_init(). * @param odftype Which onset detection function (ODF) you'll be using, chosen from #onsetsds_odf_types * @param fftsize Size of FFT: 512 is recommended. * @param medspan The number of past frames that will be used for median calculation during triggering */ size_t onsetsds_memneeded(int odftype, size_t fftsize, unsigned int medspan); /** * Initialise the OnsetsDS struct and its associated memory, ready to detect * onsets using the specified settings. Must be called before any call to * onsetsds_process(). * * Note: you can change the onset detection function type in mid-operation * by calling onsetsds_init() again, but because memory will be reset this * will behave as if starting from scratch (rather than being aware of the past * few frames of sound). Do not attempt to change the * onset detection function in a more hacky way (e.g. fiddling with the struct) * because memory is set up differently for each of the different ODFs. * @param ods An instance of the OnsetsDS struct * @param odsdata A pointer to the memory allocated, size given by onsetsds_memneeded(). * @param fftformat Which format of FFT data is to be expected, chosen from #onsetsds_fft_types * @param odftype Which onset detection function (ODF) you'll be using, chosen from #onsetsds_odf_types * @param fftsize Size of FFT: 512 or 1024 is recommended. * @param medspan The number of past frames that will be used for median calculation during triggering * @param srate The sampling rate of the input audio */ void onsetsds_init(OnsetsDS* ods, float* odsdata, int fftformat, int odftype, size_t fftsize, unsigned int medspan, float srate); /** * Process a single FFT data frame in the audio signal. Note that processing * assumes that each call to onsetsds_process() is on a subsequent frame in * the same audio stream - to handle multiple streams you must use separate * OnsetsDS structs and memory! * * This function's main purpose is to call some of the library's other functions, * in the expected sequence. */ bool onsetsds_process(OnsetsDS* ods, float* fftbuf); //@} //////////////////////////////////////////////////////////////////////////////// // Function prototypes less commonly called by users /** * \defgroup LessCommonFuncs Other useful functions */ //@{ /** * Set the "memory coefficient" indirectly via the time for the * memory to decay by 60 dB. * @param ods The OnsetsDS * @param time The time in seconds * @param hopsize The FFT frame hopsize (typically this will be half the FFT frame size) */ void onsetsds_setrelax(OnsetsDS* ods, float time, size_t hopsize); //@} //////////////////////////////////////////////////////////////////////////////// // Function prototypes not typically called by users /** * \defgroup OtherFuncs Other functions, not typically called by users */ //@{ /** * Load the current frame of FFT data into the OnsetsDS struct. * * Not typically called directly by users since onsetsds_process() calls this. */ void onsetsds_loadframe(OnsetsDS* ods, float* fftbuf); /** * Apply adaptive whitening to the FFT data in the OnsetsDS struct. * * Not typically called directly by users since onsetsds_process() calls this. */ void onsetsds_whiten(OnsetsDS* ods); /** * Calculate the Onset Detection Function (includes scaling ODF outputs to * similar range) * * Not typically called directly by users since onsetsds_process() calls this. */ void onsetsds_odf(OnsetsDS* ods); /** * Detects salient peaks in Onset Detection Function by removing the median, * then thresholding. Afterwards, the member ods.detected will indicate whether * or not an onset was detected. * * Not typically called directly by users since onsetsds_process() calls this. */ void onsetsds_detect(OnsetsDS* ods); //@} //////////////////////////////////////////////////////////////////////////////// #ifdef __cplusplus } #endif
11,154
C++
.h
238
42.668067
164
0.676968
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,208
BeatTrack.h
supercollider_supercollider/server/plugins/BeatTrack.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #define DFFRAMELENGTH 512 #define DFSTORE 700 // store last 700 to avoid problems during amortisation #define LAGS 128 struct BeatTrack : Unit { // corrections for different sampling rates: support 44100 as native, and 48000, 88200, 96000 by frequency domain // down sampling assumes 1024 FFT for first two, 2048 for second two float m_srate; float m_srateconversion; float m_frameperiod; // FFT data // int m_bufWritePos; // float * m_prepareFFTBuf; float* m_FFTBuf; // fftwf_plan planTime2FFT; float* m_prevmag; float* m_prevphase; float* m_predict; // vDSP // unsigned long m_vlog2n; // COMPLEX_SPLIT m_vA; // FFTSetup m_vsetup; // time positions long m_frame; // df float m_df[DFSTORE]; int m_dfcounter; // for peak pick scorer int m_dfmemorycounter; float m_dfmemory[15]; // autocorrelation results on df float m_acf[DFFRAMELENGTH]; // float* m_M; float m_mg[LAGS]; float m_besttorsum; int m_bestcolumn; float m_phaseweights[LAGS]; float m_tor; int m_torround; float m_periodp; float m_periodg; int m_flagstep; float m_prevperiodp[3]; // amortisation search for best phase from 0 to m_torround-1 float m_bestphasescore; int m_bestphase; // tempo float m_currtempo; // phase float m_currphase; // phasor, trigger beat and modulo when >1.0 float m_phase, m_phaseperblock; // phasor output separate so can have it lock and keep going when don't want to track float m_outputphase, m_outputtempo, m_outputphaseperblock; int halftrig; int q1trig; int q2trig; // amortization - more complex structure to support different rates of work int m_amortisationstate; int m_amortcount; int m_amortlength; int m_amortisationsteps; // model states int m_stateflag; int m_timesig; int m_storedfcounter; int m_storedfcounterend; }; extern "C" { // required interface functions void BeatTrack_next(BeatTrack* unit, int wrongNumSamples); void BeatTrack_Ctor(BeatTrack* unit); void BeatTrack_Dtor(BeatTrack* unit); }
3,053
C++
.h
90
29.166667
117
0.71492
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,209
BeatTrack2.h
supercollider_supercollider/server/plugins/BeatTrack2.h
/* SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ // N feature stream inputs, cross correlation with template on each channel // templates- search 120 tempi * 2 groove types (really just /2 and /3 subdivision) and no metrical discernment * a // different numbers of phases depending on tempo // assume 4 features * 120 tempi * 2 groove * 20 phase = 19200 per calculation time; say you calculate each 0.5 sec, // amortise over (44100/64*0.5 >344.5) control blocks; calculate over 240 blocks #include "SC_PlugIn.h" struct BeatTrack2 : Unit { // adjust for any sampling rate by calculating factors; runs off of k rate inputs float m_srate; float m_phaseaccuracy; // probably 8 control blocks! int m_numtempi; //= 120; // float * m_tempi; int* m_numphases; // float ** m_phases; int m_numfeatures; float* m_features; // pointer to control bus, assumes contiguous busnum for each consecutive feature // float m_temporalwindowsize; // typically small, 2 seconds for fast reactions compared to 6 secs for BeatTrack float m_fullwindowsize; float m_krlength; int m_buffersize; // in control blocks float** m_pastfeatures; // for each feature, a trail of last m_workingmemorysize values int m_counter, m_startcounter; // time positions float m_calculationschedule; float m_calculationperiod; // tempo float m_period; int m_groove; float m_currtempo; // phase float m_currphase; // phasor, trigger beat and modulo when >1.0 float m_phase, m_phaseperblock; // phasor output separate so can have it lock and keep going when don't want to track float m_outputphase, m_outputtempo, m_outputgroove, m_outputphaseperblock; float m_predictphase, m_predictperiod; // amortization - more complex structure to support different rates of work int m_amortisationstate; int m_amortcount; int m_amortlength; int m_amortisationsteps; // efficiency trick float* m_scores; // tracking best results for each feature // also storing second best and previous best and second best? // thus keep best from previous round too for additional vote/consistency check float* bestscore; int* bestphase; int* besttempo; int* bestgroove; // or store all scores and resolve later? int halftrig; int q1trig; int q2trig; SndBuf* m_tempoweights; int m_weightingscheme; }; extern "C" { // required interface functions void BeatTrack2_next(BeatTrack2* unit, int wrongNumSamples); void BeatTrack2_Ctor(BeatTrack2* unit); void BeatTrack2_Dtor(BeatTrack2* unit); }
3,462
C++
.h
80
38.7375
116
0.734724
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
34,211
test_synth.hpp
supercollider_supercollider/testsuite/server/supernova/test_synth.hpp
#include "../server/supernova/server/synth.hpp" namespace nova { class test_synth : public abstract_synth { public: test_synth(int node_id, synth_definition_ptr const& prototype): abstract_synth(node_id, prototype) {} void run(void) {} virtual float get(slot_index_t slot_id) const { return 0.f; } virtual bool getMappedSymbol(slot_index_t slot_id, char* str) const { return false; } virtual void set(slot_index_t slot_id, sample val) {} virtual void set_control_array(slot_index_t slot_id, size_t count, sample* val) {} }; }
557
C++
.h
12
42.833333
105
0.717472
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,212
localsocket_utils.hpp
supercollider_supercollider/editors/sc-ide/primitives/localsocket_utils.hpp
#pragma once #include <QByteArray> #include <QLocalSocket> #include <QDataStream> // Aux functions for LocalSocket data handling // Make template so that it supports QVariantLists and QStringList, which are te data types that we send in sc_process // and main QByteArray IntToArray(qint32 source); qint32 ArrayToInt(QByteArray source); template <typename T> void sendSelectorAndData(QLocalSocket* socket, const QString& selector, const T& data) { QByteArray baToStream; QDataStream stream(&baToStream, QIODevice::WriteOnly); stream.setVersion(QDataStream::Qt_4_6); stream << selector; stream << data; // Write the length so that we know how long it is on the other end int len = baToStream.length(); QByteArray baLen = IntToArray(len); socket->write(baLen); socket->write(baToStream); socket->flush(); }
851
C++
.h
22
35.545455
118
0.755448
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,213
sc_ipc_client.hpp
supercollider_supercollider/editors/sc-ide/primitives/sc_ipc_client.hpp
/* SuperCollider Qt IDE Copyright (c) 2012, 2013 Jakob Leben, Tim Blechmann, and Scott Wilson http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include <QObject> #include <QLocalSocket> #include <QMutex> #include <QHash> #include <QVariantList> class SCIpcClient : public QObject { Q_OBJECT public: SCIpcClient(const char* ideName); void send(const char* data, size_t length); ~SCIpcClient(); QLocalSocket* mSocket; QString getTextMirrorForDocument(QByteArray& id, int pos = 0, int range = -1); QPair<int, int> getSelectionMirrorForDocument(QByteArray& id); void setTextMirrorForDocument(QByteArray& id, const QString& text, int pos = 0, int range = -1); void setSelectionMirrorForDocument(QByteArray& id, int start = 0, int range = 0); private Q_SLOTS: void readIDEData(); private: void onResponse(const QString& selector, const QVariantList& argList); void updateDocText(const QVariantList& argList); void updateDocSelection(const QVariantList& argList); int mReadSize = 0; QByteArray mIpcData; QHash<QByteArray, QString> mDocumentTextMirrors; QHash<QByteArray, QPair<int, int>> mDocumentSelectionMirrors; QMutex mTextMirrorHashMutex; QMutex mSelMirrorHashMutex; };
1,945
C++
.h
46
38.978261
100
0.771762
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
34,214
sc_lexer.hpp
supercollider_supercollider/editors/sc-ide/core/sc_lexer.hpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include "../widgets/code_editor/tokens.hpp" #include <QVector> #include <QRegularExpression> #include <QString> namespace ScIDE { class ScLexer { public: enum State { InCode = 0, InString = 1, InSymbol = 2, InComment = 100 // NOTE: Values higher than InComment are reserved for multi line comments, // and indicate the comment nesting level! }; static void initLexicalRules(); private: struct LexicalRule { LexicalRule(): type(Token::Unknown) {} LexicalRule(Token::Type t, const QString& s): type(t), expr(s) {} Token::Type type; QRegularExpression expr; }; static void initKeywordsRules(); static void initBuiltinsRules(); static QVector<LexicalRule> mLexicalRules; public: ScLexer(const QString& text, int offset = 0, int state = InCode): mText(text), mOffset(offset), mState(state) {} const QString& text() const { return mText; } int state() const { return mState; } void setState(int state) { mState = state; } int offset() const { return mOffset; } void setOffset(int offset) { mOffset = offset; } Token::Type nextToken(int& length); private: Token::Type nextTokenInCode(int& length); Token::Type nextTokenInString(int& length); Token::Type nextTokenInSymbol(int& length); Token::Type nextTokenInComment(int& length); const QString& mText; int mOffset; int mState; }; }
2,313
C++
.h
61
32.901639
116
0.70641
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
34,215
sc_process.hpp
supercollider_supercollider/editors/sc-ide/core/sc_process.hpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include "sc_introspection.hpp" #include <QAction> #include <QByteArray> #include <QDateTime> #include <QDebug> #include <QProcess> #include <QThread> #include <QUuid> #include <QtNetwork/QLocalSocket> #include <QtNetwork/QLocalServer> namespace ScIDE { namespace Settings { class Manager; } class ScIntrospectionParser; class ScProcess : public QProcess { Q_OBJECT public: ScProcess(Settings::Manager*, QObject* parent); enum ActionRole { ToggleRunning = 0, Start, Stop, Restart, RecompileClassLibrary, StopMain, ShowQuarks, ActionCount }; const ScLanguage::Introspection& introspection() { return mIntrospection; } void sendRequest(const QString& id, const QString& command, const QString& data) { QString cmd = QStringLiteral("ScIDE.request(\"%1\",'%2',\"%3\")").arg(id).arg(command).arg(data); evaluateCode(cmd, true); } QAction* action(ActionRole role) { return mActions[role]; } bool compiled() { return mCompiled; } void post(QString& text) { scPost(text); } void updateTextMirrorForDocument(class Document* doc, int position, int charsRemoved, int charsAdded); void updateSelectionMirrorForDocument(class Document* doc, int start, int range); public slots: void toggleRunning(); void startLanguage(void); void stopLanguage(void); void restartLanguage(void); void recompileClassLibrary(void); void stopMain(void); void showQuarks(void); void evaluateCode(QString const& commandString, bool silent = false); signals: void scPost(QString const&); void statusMessage(const QString&); void response(const QString& selector, const QString& data); void classLibraryRecompiled(); void introspectionChanged(); private slots: void onNewIpcConnection(); void onIpcData(); void finalizeConnection(); void onProcessStateChanged(QProcess::ProcessState state); void onReadyRead(void); void updateToggleRunningAction(); private: void onStart(); void onResponse(const QString& selector, const QString& data); void prepareActions(Settings::Manager* settings); void postQuitNotification(); QAction* mActions[ActionCount]; ScLanguage::Introspection mIntrospection; ScIntrospectionParser* mIntrospectionParser; QLocalServer* mIpcServer; QLocalSocket* mIpcSocket; QString mIpcServerName; QByteArray mIpcData; int mReadSize = 0; bool mTerminationRequested; QDateTime mTerminationRequestTime; bool mCompiled; }; class ScRequest : public QObject { Q_OBJECT public: ScRequest(ScProcess* sc, QObject* parent = 0): QObject(parent), mSc(sc) { connect(mSc, SIGNAL(response(QString, QString)), this, SLOT(onResponse(QString, QString))); connect(mSc, SIGNAL(classLibraryRecompiled()), this, SLOT(cancel())); } void send(const QString& command, const QString& data) { mId = QUuid::createUuid(); mCommand = command; mSc->sendRequest(mId.toString(), command, data); } public slots: void cancel() { mId = QUuid(); emit cancelled(); } signals: void response(const QString& command, const QString& data); void cancelled(); private slots: void onResponse(const QString& responseId, const QString& responseData) { if (responseId == mId.toString()) emit response(mCommand, responseData); } private: QString mCommand; QUuid mId; ScProcess* mSc; }; }
4,392
C++
.h
126
30.007937
106
0.720765
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,216
main.hpp
supercollider_supercollider/editors/sc-ide/core/main.hpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include <QAbstractNativeEventFilter> #include <QAction> #include <QObject> #include <QtNetwork/QLocalSocket> #include <QtNetwork/QLocalServer> #include "sc_process.hpp" #include "sc_server.hpp" #include "doc_manager.hpp" #include "settings/manager.hpp" #include "../widgets/style/style.hpp" namespace ScIDE { class SessionManager; // scide instances have a LocalServer. when called with an argument, it will try to reconnect // to the instance with the lowest number. class SingleInstanceGuard : public QObject { Q_OBJECT public: SingleInstanceGuard(): mReadSize(0) {}; bool tryConnect(QStringList const& arguments); public Q_SLOTS: void onNewIpcConnection() { mIpcSocket = mIpcServer->nextPendingConnection(); connect(mIpcSocket, SIGNAL(disconnected()), mIpcSocket, SLOT(deleteLater())); connect(mIpcSocket, SIGNAL(readyRead()), this, SLOT(onIpcData())); } void onIpcData(); private: QLocalServer* mIpcServer; QLocalSocket* mIpcSocket; int mReadSize; QByteArray mIpcData; }; class Main : public QObject, public QAbstractNativeEventFilter { Q_OBJECT public: static Main* instance(void) { static Main* singleton = new Main; return singleton; } static ScProcess* scProcess() { return instance()->mScProcess; } static ScServer* scServer() { return instance()->mScServer; } static SessionManager* sessionManager() { return instance()->mSessionManager; } static DocumentManager* documentManager() { return instance()->mDocManager; } static Settings::Manager* settings() { return instance()->mSettings; } static void evaluateCode(QString const& text, bool silent = false) { instance()->scProcess()->evaluateCode(text, silent); } static void evaluateCodeIfCompiled(QString const& text, bool silent = false) { if (instance()->scProcess()->compiled()) evaluateCode(text, silent); } static bool openDocumentation(const QString& string); static bool openDocumentationForMethod(const QString& className, const QString& methodName); static void openDefinition(const QString& string, QWidget* parent); static void openCommandLine(const QString& string); static void findReferences(const QString& string, QWidget* parent); public Q_SLOTS: void storeSettings() { Q_EMIT(storeSettingsRequest(mSettings)); mSettings->sync(); } void applySettings() { Q_EMIT(applySettingsRequest(mSettings)); setAppPaletteFromSettings(); qApp->setStyle(qApp->style()); } void quit(); void setAppPaletteFromSettings(); Q_SIGNALS: void storeSettingsRequest(Settings::Manager*); void applySettingsRequest(Settings::Manager*); private: Main(void); bool eventFilter(QObject* obj, QEvent* event); #if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) bool nativeEventFilter(const QByteArray&, void* message, long*); #else bool nativeEventFilter(const QByteArray&, void* message, qintptr*); #endif Settings::Manager* mSettings; ScProcess* mScProcess; ScServer* mScServer; DocumentManager* mDocManager; SessionManager* mSessionManager; }; }
4,047
C++
.h
103
34.728155
96
0.733214
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
34,217
session_manager.hpp
supercollider_supercollider/editors/sc-ide/core/session_manager.hpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include <QObject> #include <QDir> #include <QStringList> #include <QSettings> namespace ScIDE { class DocumentManager; struct Session : public QSettings { Session(const QString& file, const QString& name, Format format, QObject* parent = 0): QSettings(file, format, parent), mName(name) {} const QString& name() const { return mName; } private: QString mName; }; class SessionManager : public QObject { Q_OBJECT public: SessionManager(DocumentManager*, QObject* parent = 0); QDir sessionsDir(); QStringList availableSessions(); QString lastSession(); void newSession(); void saveSession(); Session* saveSessionAs(const QString& name); Session* openSession(const QString& name); void removeSession(const QString& name); void renameSession(const QString& oldName, const QString& newName); Session* currentSession() { return mCurrentSession; } signals: void saveSessionRequest(Session* session); void switchSessionRequest(Session* session); void currentSessionNameChanged(); private: bool closeSession(); bool saveLastSession(const QDir& dir, const QString& file); DocumentManager* mDocMng; Session* mCurrentSession; }; } // namespace ScIDE
2,107
C++
.h
56
33.464286
90
0.744346
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,218
sc_server.hpp
supercollider_supercollider/editors/sc-ide/core/sc_server.hpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include <QObject> #include <QtNetwork/QUdpSocket> #include <QAction> #include <QProcess> #include <QTimer> #include <boost/chrono/system_clocks.hpp> #include <osc/OscReceivedElements.h> namespace ScIDE { class ScProcess; class VolumeWidget; namespace Settings { class Manager; } class ScServer : public QObject { Q_OBJECT public: enum ActionRole { ToggleRunning, Boot, Quit, KillAll, Reboot, ShowMeters, ShowScope, ShowFreqScope, DumpNodeTree, DumpNodeTreeWithControls, PlotTree, DumpOSC, Mute, Volume, VolumeUp, VolumeDown, VolumeRestore, Record, PauseRecord, ActionCount }; ScServer(ScProcess* scLang, Settings::Manager* settings, QObject* parent); bool isRunning() { return mPort != 0; } QAction* action(ActionRole role) { return mActions[role]; } Q_PROPERTY(float volume READ volume WRITE setVolume NOTIFY volumeChanged) float volume() const; void setVolume(float volume); void setVolumeRange(float min, float max); bool isMuted() const; void setMuted(bool muted); bool isDumpingOSC() const; void setDumpingOSC(bool dumping); bool isRecording() const; bool isPaused() const; int recordingTime() const; public slots: void boot(); void reboot(); void quit(); void killAll(); void toggleRunning(); void showMeters(); void showScope(); void showFreqScope(); void dumpNodeTree(); void dumpNodeTreeWithControls(); void plotTree(); void queryAllNodes(bool dumpControls); void increaseVolume(); void decreaseVolume(); void changeVolume(float); void restoreVolume(); void mute() { setMuted(true); } void unmute() { setMuted(false); } void sendRecording(bool active); void setRecording(bool active); void pauseRecording(bool flag); signals: void runningStateChanged(bool running, QString const& hostName, int port, bool unresponsive); void updateServerStatus(int ugenCount, int synthCount, int groupCount, int defCount, float avgCPU, float peakCPU); void volumeChanged(float volume); void volumeRangeChanged(float min, float max); void mutedChanged(bool muted); void recordingChanged(bool recording); void pauseChanged(bool paused); private slots: void onScLangStateChanged(QProcess::ProcessState); void onScLangReponse(const QString& selector, const QString& data); void onServerDataArrived(); void updateToggleRunningAction(); void updateRecordingAction(); void updateEnabledActions(); void sendMuted(bool muted); void sendVolume(float volume); void sendDumpingOSC(bool dumping); protected: virtual void timerEvent(QTimerEvent* event); private: void createActions(Settings::Manager*); void handleRuningStateChangedMsg(const QString& data); void onRunningStateChanged(bool running, QString const& hostName, int port); void processServerStatusMessage(const osc::ReceivedMessage&); void processOscMessage(const osc::ReceivedMessage&); void processOscPacket(const osc::ReceivedPacket& packet) { if (packet.IsMessage()) processOscMessage(osc::ReceivedMessage(packet)); else processOscBundle(osc::ReceivedBundle(packet)); } void processOscBundle(const osc::ReceivedBundle& bundle) { for (auto iter = bundle.ElementsBegin(); iter != bundle.ElementsEnd(); ++iter) { const osc::ReceivedBundleElement& element = *iter; if (element.IsMessage()) processOscMessage(osc::ReceivedMessage(element)); else processOscBundle(osc::ReceivedBundle(element)); } } ScProcess* mLang; QUdpSocket* mUdpSocket; QHostAddress mServerAddress; int mPort; QAction* mActions[ActionCount]; float mVolume = 0, mVolumeMin = -90, mVolumeMax = 6; VolumeWidget* mVolumeWidget; int mRecordingSeconds; bool mIsRecording; bool mIsRecordingPaused; }; }
4,968
C++
.h
144
28.840278
118
0.711213
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,219
sig_mux.hpp
supercollider_supercollider/editors/sc-ide/core/sig_mux.hpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include <QObject> #include <QPointer> #include <QList> namespace ScIDE { class SignalMultiplexer : public QObject { Q_OBJECT public: enum ConnectionMode { ConnectionNecessary = 0, ConnectionOptional = 1 }; SignalMultiplexer(QObject* parent = 0); void connect(QObject* sender, const char* signal, const char* slot, ConnectionMode = ConnectionNecessary); bool disconnect(QObject* sender, const char* signal, const char* slot); void connect(const char* signal, QObject* receiver, const char* slot, ConnectionMode = ConnectionNecessary); bool disconnect(const char* signal, QObject* receiver, const char* slot); bool disconnect(QObject* sender); QObject* currentObject() const { return mObject; } public slots: void setCurrentObject(QObject* newObject); private: struct Connection { QPointer<QObject> sender; QPointer<QObject> receiver; const char* signal; const char* slot; ConnectionMode mode; }; void connect(const Connection& conn); void disconnect(const Connection& conn); QPointer<QObject> mObject; QList<Connection> mConnections; }; } // namespace ScIDE
2,025
C++
.h
48
37.520833
112
0.740948
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,220
doc_manager.hpp
supercollider_supercollider/editors/sc-ide/core/doc_manager.hpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include "../widgets/code_editor/editor.hpp" #include <QDateTime> #include <QFileSystemWatcher> #include <QHash> #include <QList> #include <QMetaType> #include <QObject> #include <QStringList> #include <QTextDocument> #include <QPlainTextDocumentLayout> #include <QUuid> #include <QTimer> #include <QStandardItemModel> #include <QApplication> #include <QStyle> #define RESTORE_COAL 100 #define RESTORE_COAL_MSECS 60000 namespace ScIDE { namespace Settings { class Manager; } class SyntaxHighlighter; class Main; class DocumentManager; class Document : public QObject { Q_OBJECT friend class DocumentManager; public: Document(bool isPlainText, const QByteArray& id = QByteArray(), const QString& title = QString(), const QString& text = QString()); QTextDocument* textDocument() { return mDoc; } const QByteArray& id() { return mId; } const QString& filePath() { return mFilePath; } const QString& title() { return mTitle; } void setTitle(QString& newTitle) { mTitle = newTitle; mModelItem->setText(mTitle); } QFont defaultFont() const { return mDoc->defaultFont(); } void setDefaultFont(const QFont& font); int indentWidth() const { return mIndentWidth; } void setIndentWidth(int numSpaces); void deleteTrailingSpaces(); bool isPlainText() const { return mHighlighter == NULL; } bool isModified() const { return mDoc->isModified(); } QStandardItem* modelItem() { return mModelItem; } QString textAsSCArrayOfCharCodes(int start, int range); QString titleAsSCArrayOfCharCodes(); QString pathAsSCArrayOfCharCodes(); QString bytesToSCArrayOfCharCodes(QByteArray stringBytes); void setTextInRange(const QString text, int start, int range); bool keyDownActionEnabled() { return mKeyDownActionEnabled; } bool keyUpActionEnabled() { return mKeyUpActionEnabled; } bool mouseDownActionEnabled() { return mMouseDownActionEnabled; } bool mouseUpActionEnabled() { return mMouseUpActionEnabled; } bool textChangedActionEnabled() { return mTextChangedActionEnabled; } GenericCodeEditor* lastActiveEditor() { return mLastActiveEditor; } int initialSelectionStart() { return mInitialSelectionStart; } int initialSelectionRange() { return mInitialSelectionRange; } bool editable() { return mEditable; } bool promptsToSave() { return mPromptsToSave; } void setKeyDownActionEnabled(bool enabled) { mKeyDownActionEnabled = enabled; } void setKeyUpActionEnabled(bool enabled) { mKeyUpActionEnabled = enabled; } void setMouseDownActionEnabled(bool enabled) { mMouseDownActionEnabled = enabled; } void setMouseUpActionEnabled(bool enabled) { mMouseUpActionEnabled = enabled; } void setTextChangedActionEnabled(bool enabled) { mTextChangedActionEnabled = enabled; } void setLastActiveEditor(GenericCodeEditor* lastActive) { mLastActiveEditor = lastActive; } void setInitialSelection(int start, int range) { mInitialSelectionStart = start; mInitialSelectionRange = range; } void setEditable(bool editable) { mEditable = editable; } void setPromptsToSave(bool prompts) { mPromptsToSave = prompts; } void removeTmpFile(); public slots: void applySettings(Settings::Manager*); void resetDefaultFont(); void storeTmpFile(); void onTmpCoalUsecs(); void onModificationChanged(bool changed) { if (changed) { mModelItem->setIcon(QApplication::style()->standardIcon(QStyle::SP_DialogSaveButton)); } else { mModelItem->setIcon(QIcon()); } } signals: void defaultFontChanged(); private: void setPlainText(bool flag); QByteArray mId; QTextDocument* mDoc; QString mFilePath; QString mTitle; QString mTmpFilePath; int mTmpCoalCount; QTimer mTmpCoalTimer; QDateTime mSaveTime; int mIndentWidth; SyntaxHighlighter* mHighlighter; bool mKeyDownActionEnabled; bool mKeyUpActionEnabled; bool mMouseDownActionEnabled; bool mMouseUpActionEnabled; bool mTextChangedActionEnabled; GenericCodeEditor* mLastActiveEditor; int mInitialSelectionStart, mInitialSelectionRange; bool mEditable; bool mPromptsToSave; QStandardItem* mModelItem; }; class DocumentManager : public QObject { Q_OBJECT public: typedef QList<Document*> DocumentList; DocumentManager(Main*, Settings::Manager*); QList<Document*> documents() { return mDocHash.values(); } QList<QByteArray> documentIDs() { return mDocHash.keys(); } void create(); void close(Document*); bool save(Document*); bool saveAs(Document*, const QString& path); bool reload(Document*); bool needRestore(); void restore(); void deleteRestore(); const QStringList& recents() const { return mRecent; } Document* documentForId(const QByteArray id); bool textMirrorEnabled() { return mTextMirrorEnabled; } void setActiveDocument(class Document*); void sendActiveDocument(); Document* activeDocument() { return mCurrentDocument; } bool globalKeyDownActionEnabled() { return mGlobalKeyDownEnabled; } bool globalKeyUpActionEnabled() { return mGlobalKeyUpEnabled; } QStandardItemModel* docModel() { return mDocumentModel; } public slots: // initialCursorPosition -1 means "don't change position if already open" Document* open(const QString& path, int initialCursorPosition = -1, int selectionLength = 0, bool addToRecent = true, const QByteArray& id = QByteArray(), bool syncLang = true); void clearRecents(); void storeSettings(Settings::Manager*); void handleScLangMessage(const QString& selector, const QString& data); Q_SIGNALS: void opened(Document*, int cursorPosition, int selectionLength); void closed(Document*); void saved(Document*); void showRequest(Document*, int pos = -1, int selectionLength = 0); void changedExternally(Document*); void recentsChanged(); void titleChanged(Document*); private slots: void onFileChanged(const QString& path); void updateCurrentDocContents(int position, int charsRemoved, int charsAdded); private: Document* createDocument(bool isPlainText = false, const QByteArray& id = QByteArray(), const QString& title = QString(), const QString& text = QString()); bool doSaveAs(Document*, const QString& path); void addToRecent(Document*); void loadRecentDocuments(Settings::Manager*); QStringList tmpFiles(); void closeSingleUntitledIfUnmodified(); QString decodeDocument(QByteArray const&); void handleDocListScRequest(); void handleNewDocScRequest(const QString& data); void handleOpenFileScRequest(const QString& data); void handleGetDocTextScRequest(const QString& data); void handleSetDocTextScRequest(const QString& data); void handleSetDocSelectionScRequest(const QString& data); void handleSetDocEditableScRequest(const QString& data); void handleSetDocPromptsToSaveScRequest(const QString& data); void handleSetCurrentDocScRequest(const QString& data); void handleRemoveDocUndoScRequest(const QString& data); void handleCloseDocScRequest(const QString& data); void handleSaveDocScRequest(const QString& data); void handleSetDocTitleScRequest(const QString& data); bool parseActionEnabledRequest(const QString& data, std::string* idString, bool* en); void handleEnableKeyDownScRequest(const QString& data); void handleEnableKeyUpScRequest(const QString& data); void handleEnableGlobalKeyDownScRequest(const QString& data); void handleEnableGlobalKeyUpScRequest(const QString& data); void handleEnableMouseDownScRequest(const QString& data); void handleEnableMouseUpScRequest(const QString& data); void handleEnableTextChangedScRequest(const QString& data); void handleEnableTextMirrorScRequest(const QString& data); void syncLangDocument(Document*); typedef QHash<QByteArray, Document*>::iterator DocIterator; QHash<QByteArray, Document*> mDocHash; QFileSystemWatcher mFsWatcher; QStringList mRecent; static const int mMaxRecent = 10; bool mTextMirrorEnabled; QString mCurrentDocumentPath; class Document* mCurrentDocument; bool mGlobalKeyDownEnabled, mGlobalKeyUpEnabled; QStandardItemModel* mDocumentModel; }; } // namespace ScIDE Q_DECLARE_METATYPE(ScIDE::Document*)
9,318
C++
.h
215
38.488372
103
0.753863
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
34,221
sc_introspection.hpp
supercollider_supercollider/editors/sc-ide/core/sc_introspection.hpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include <QHash> #include <QList> #include <QMap> #include <QMetaType> #include <QSharedPointer> #include <QString> #include <QVector> #include <string> #include <map> #include <boost/flyweight.hpp> static inline std::size_t hash_value(QString const& b) { return qHash(b); } namespace ScIDE { namespace ScLanguage { typedef boost::flyweight<QString> FlyweightString; typedef std::map<QString, QSharedPointer<struct Class>> ClassMap; typedef std::multimap<QString, QSharedPointer<struct Method>> MethodMap; typedef QVector<struct Argument> ArgumentVector; typedef QVector<struct Method*> MethodVector; struct Argument { FlyweightString name; FlyweightString defaultValue; }; struct Class { FlyweightString name; Class* metaClass; Class* superClass; MethodVector methods; struct { FlyweightString path; int position; } definition; bool isSubclassOf(const Class* parentClass) const { if (superClass == parentClass) return true; if (superClass == NULL) return false; return superClass->isSubclassOf(parentClass); } }; struct Method { enum SignatureStyle { SignatureWithoutArguments, SignatureWithArguments, SignatureWithArgumentsAndDefaultValues }; QString signature(SignatureStyle style) const; bool matches(const QString& toMatch) const; Class* ownerClass; FlyweightString name; ArgumentVector arguments; struct { FlyweightString path; int position; } definition; }; static inline QString makeFullMethodName(QString const& className, QString const& methodName) { QString ret(className); if (ret.startsWith("Meta_")) { ret.remove(0, 5); ret.append("-*"); } else ret.append("-"); ret.append(methodName); return ret; } class Introspection { public: Introspection(); Introspection(Introspection const& rhs) = default; explicit Introspection(QString const& yamlString); Introspection& operator=(Introspection const& rhs) = default; Introspection& operator=(Introspection&& rhs); typedef QMap<QString, QList<Method*>> ClassMethodMap; // maps Path to List of Methods const ClassMap& classMap() const { return mClassMap; } const MethodMap& methodMap() const { return mMethodMap; } const Class* findClass(const QString& className) const; const Class* findClassOrWarn(const QString& className) const; std::vector<const Class*> findClassPartial(const QString& partialClassName) const; std::vector<const Method*> findMethodPartial(const QString& partialMethodName) const; QString const& classLibraryPath() const { return mClassLibraryPath; } // remove class library path, userExtensionDir and systemExtensionDir QString compactLibraryPath(QString const& path) const; bool isClassMethod(const Method* method) const { return (method->ownerClass->name.get().startsWith("Meta_")); } bool introspectionAvailable() const { return !mClassMap.empty(); } private: void initPaths(); bool parse(const QString& yamlString); void inferClassLibraryPath(); bool ensureIntrospectionData() const; void clear() { mClassMap.clear(); mMethodMap.clear(); mClassLibraryPath.clear(); } ClassMap mClassMap; MethodMap mMethodMap; QString mClassLibraryPath; QString mUserExtensionDir; QString mSystemExtensionDir; }; } // namespace ScLanguage } // namespace ScIDE Q_DECLARE_METATYPE(ScIDE::ScLanguage::Class*) Q_DECLARE_METATYPE(const ScIDE::ScLanguage::Method*)
4,438
C++
.h
116
33.603448
118
0.739617
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,222
HelpBrowserWebSocketServices.hpp
supercollider_supercollider/editors/sc-ide/core/util/HelpBrowserWebSocketServices.hpp
#pragma once #ifdef SC_USE_QTWEBENGINE # include <QWebChannel> # include "../../widgets/util/WebSocketClientWrapper.hpp" # include "../../widgets/util/WebSocketTransport.hpp" # include "../../widgets/util/IDEWebChannelWrapper.hpp" namespace ScIDE { /** RAII class to encapsulate websocket services needed by the help browser. */ class HelpBrowserWebSocketServices { public: HelpBrowserWebSocketServices(HelpBrowser* browser) { m_server = new QWebSocketServer("SCIDE HelpBrowser Server", QWebSocketServer::NonSecureMode); if (m_server->listen(QHostAddress::LocalHost)) { browser->setServerPort(m_server->serverPort()); // setup comm channel m_clientWrapper = new WebSocketClientWrapper(m_server); m_channel = new QWebChannel(); QObject::connect(m_clientWrapper, &WebSocketClientWrapper::clientConnected, m_channel, &QWebChannel::connectTo); // publish IDE interface m_ideWrapper = new IDEWebChannelWrapper(browser); m_channel->registerObject("IDE", m_ideWrapper); } else { qWarning("Failed to set up help browser web socket."); // [don't take up heap space with a useless object] delete m_server; m_server = nullptr; } } ~HelpBrowserWebSocketServices() { delete m_server; delete m_clientWrapper; delete m_channel; delete m_ideWrapper; } private: QWebSocketServer* m_server; // non-null only if server listens successfully WebSocketClientWrapper* m_clientWrapper; QWebChannel* m_channel; IDEWebChannelWrapper* m_ideWrapper; }; } // namespace ScIDE #endif // SC_USE_QTWEBENGINE
1,766
C++
.h
44
32.795455
101
0.668418
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,223
standard_dirs.hpp
supercollider_supercollider/editors/sc-ide/core/util/standard_dirs.hpp
/* SuperCollider Qt IDE Copyright (c) 2013 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include <QString> namespace ScIDE { enum StandardDirectory { ScResourceDir, ScAppDataSystemDir, ScAppDataUserDir, ScExtensionSystemDir, ScExtensionUserDir, ScConfigUserDir }; QString standardDirectory(StandardDirectory type); } // namespace ScIDE
1,131
C++
.h
29
34.827586
81
0.766055
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,224
color.hpp
supercollider_supercollider/editors/sc-ide/core/util/color.hpp
/* SuperCollider Qt IDE Copyright (c) 2018 SuperCollider Team https://supercollider.github.io/ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include <QColor> namespace ScIDE { namespace color { QColor lighten(const QColor& color, int amount); QColor darken(const QColor& color, int amount); QColor interpolate(const QColor& color_1, const QColor& color_2, float amount); QColor setValue(const QColor& color, int value); } // namespace color } // namespace ScIDE
1,175
C++
.h
25
43.44
81
0.763573
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,225
overriding_action.hpp
supercollider_supercollider/editors/sc-ide/core/util/overriding_action.hpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include <QAction> #include <QWidget> #include <QKeyEvent> #include <QKeySequence> namespace ScIDE { class OverridingAction : public QAction { public: OverridingAction(QObject* parent): QAction(parent) { setShortcutContext(Qt::WidgetWithChildrenShortcut); } OverridingAction(const QString& text, QObject* parent): QAction(text, parent) { setShortcutContext(Qt::WidgetWithChildrenShortcut); } OverridingAction(const QIcon& icon, const QString& text, QObject* parent): QAction(icon, text, parent) { setShortcutContext(Qt::WidgetWithChildrenShortcut); } void addToWidget(QWidget* widget) { widget->addAction(this); widget->installEventFilter(this); } static QKeySequence keySequence(QKeyEvent* event) { if (event->key() >= Qt::Key_Shift && event->key() <= Qt::Key_Alt) return QKeySequence(); return QKeySequence(event->modifiers() | event->key()); } protected: virtual bool eventFilter(QObject* object, QEvent* event) { Q_UNUSED(object); switch (event->type()) { case QEvent::ShortcutOverride: { QKeySequence sequence = keySequence(static_cast<QKeyEvent*>(event)); if (sequence.isEmpty()) break; foreach (const QKeySequence& shortcut, shortcuts()) { if (shortcut == sequence) { event->accept(); return true; } } break; } case QEvent::KeyPress: { QKeySequence sequence = keySequence(static_cast<QKeyEvent*>(event)); if (sequence.isEmpty()) break; foreach (const QKeySequence& shortcut, shortcuts()) { if (shortcut == sequence) { event->accept(); activate(QAction::Trigger); return true; } } break; } default: break; } return QAction::eventFilter(object, event); } }; } // namespace ScIDE
2,950
C++
.h
76
30.25
110
0.633788
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,226
serialization.hpp
supercollider_supercollider/editors/sc-ide/core/settings/serialization.hpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include <QSettings> #include <QTextCharFormat> #include <QVariant> namespace ScIDE { namespace Settings { QSettings::Format serializationFormat(); }} // namespace ScIDE::Settings Q_DECLARE_METATYPE(QTextCharFormat)
1,072
C++
.h
24
40.958333
81
0.768046
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,227
manager.hpp
supercollider_supercollider/editors/sc-ide/core/settings/manager.hpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include "serialization.hpp" // to forward meta type declarations #include <QObject> #include <QKeySequence> #include <QList> #include <QAction> #include <QTextCharFormat> namespace ScIDE { namespace Settings { class Theme; class Manager : public QObject { Q_OBJECT public: explicit Manager(const QString& filename, QObject* parent = 0); // forwarded void beginGroup(const QString& prefix) { mSettings->beginGroup(prefix); } void endGroup() { mSettings->endGroup(); } QString group() const { return mSettings->group(); } QStringList childGroups() const { return mSettings->childGroups(); } QStringList childKeys() const { return mSettings->childKeys(); } QStringList allKeys() const { return mSettings->allKeys(); } void sync() { mSettings->sync(); } void remove(const QString& key) { mSettings->remove(key); } // extended bool contains(const QString& key) const; bool isOverridden(const QString& key) const { return mSettings->contains(key); } QVariant value(const QString& key) const; QVariant defaultValue(const QString& key) const { return mDefaults.value(resolvedKey(key)); } void setValue(const QString& key, const QVariant& value); QKeySequence shortcut(const QString& key); const QList<QAction*>& actions() { return mActions; } void addAction(QAction* action, const QString& key, const QString& category = QString()); QString keyForAction(QAction* action); QFont codeFont(); int defaultCursorFlashTime() const { return mDefaultCursorFlashTime; } void setThemeVal(QString key, const QTextCharFormat& val); const QTextCharFormat& getThemeVal(QString key); void updateTheme(); private: void setDefault(const QString& key, const QVariant& value) { mDefaults.insert(resolvedKey(key), value); } typedef QSettings::SettingsMap SettingsMap; QString resolvedKey(const QString& key) const { QString fullKey = mSettings->group(); if (!fullKey.isEmpty()) fullKey.append("/"); fullKey.append(key); return fullKey; } void initDefaults(); void initHighlightingDefaults(); QSettings* mSettings; SettingsMap mDefaults; QList<QAction*> mActions; const int mDefaultCursorFlashTime; Theme* mTheme; }; struct ActionData { QString category; QString key; }; }} // namespace ScIDE::Settings Q_DECLARE_METATYPE(ScIDE::Settings::ActionData);
3,300
C++
.h
77
38.155844
109
0.729493
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,228
theme.hpp
supercollider_supercollider/editors/sc-ide/core/settings/theme.hpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include <QMap> #include <QList> #include <QString> #include <QTextCharFormat> namespace ScIDE { namespace Settings { class Manager; int legacyTheme(Manager* settings); class Theme { public: Theme(const QString& _name, Manager* settings = NULL); Theme(const QString& _name, const QString& _source, Manager* settings = NULL); ~Theme(); void setFormat(const QString& key, const QTextCharFormat& format); const QTextCharFormat& format(const QString& key); QString& name(); bool locked(); QList<QString> availableThemes(); void save(); void remove(); private: void fillUser(const QString& theme, const Manager* settings); void fillDefault(); void fillClassic(); void fillDark(); void fillDracula(); void fillSolarizedLight(); void fillSolarizedDark(); void add(const char* key, const QColor& fg, const QColor& bg = QColor(Qt::transparent), bool bold = false, bool italic = false); bool mLocked; QMap<QString, QTextCharFormat*> mFormats; QString mName; Manager* mSettings; }; }} // namespace ScIDE:Settings
1,965
C++
.h
52
33.480769
110
0.727608
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,229
post_window.hpp
supercollider_supercollider/editors/sc-ide/widgets/post_window.hpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include "util/docklet.hpp" #include <QAction> #include <QPlainTextEdit> namespace ScIDE { namespace Settings { class Manager; } class PostDocklet; class PostWindow : public QPlainTextEdit { Q_OBJECT public: enum ActionRole { Copy, Clear, DocClose, ZoomIn, ZoomOut, ResetZoom, LineWrap, AutoScroll, ActionCount }; explicit PostWindow(QWidget* parent = 0); void applySettings(Settings::Manager*); void storeSettings(Settings::Manager*); QAction* action(ActionRole role) const { return mActions[role]; } QSize sizeHint() const { return mSizeHint; } QSize minimumSizeHint() const { return QSize(50, 50); } QString symbolUnderCursor(); signals: void scrollToBottomRequest(); public slots: void post(const QString& text); void scrollToBottom(); void zoomIn(int steps = 1); void zoomOut(int steps = 1); void resetZoom(); void closeDocument(); bool openDocumentation(); void openDefinition(); void openCommandLine(); void findReferences(); protected: virtual bool event(QEvent*); virtual void wheelEvent(QWheelEvent*); virtual void focusOutEvent(QFocusEvent* e); virtual void mouseDoubleClickEvent(QMouseEvent* e); virtual QMimeData* createMimeDataFromSelection() const; private slots: void onAutoScrollTriggered(bool); void setLineWrap(bool on); private: friend class PostDocklet; void createActions(Settings::Manager*); void updateActionShortcuts(Settings::Manager*); void zoomFont(int steps); QTextCharFormat formatForPostLine(QString line); QAction* mActions[ActionCount]; /* QAction * mAutoScrollAction; QAction * mClearAction; QAction * mLineWrapAction;*/ QSize mSizeHint; QChar previousChar; QTextCharFormat currentFormat; }; class PostDocklet : public Docklet { Q_OBJECT public: PostDocklet(QWidget* parent = 0); private slots: void onFloatingChanged(bool floating); public: PostWindow* mPostWindow; }; } // namespace ScIDE
2,952
C++
.h
93
27.129032
81
0.729424
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
34,230
tool_box.hpp
supercollider_supercollider/editors/sc-ide/widgets/tool_box.hpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include <QtCollider/layouts/stack_layout.hpp> #include <QWidget> #include <QToolButton> #include <QHBoxLayout> #include <QStyle> namespace ScIDE { class ToolBox : public QWidget { Q_OBJECT public: ToolBox(QWidget* parent = 0): QWidget(parent) { mCloseBtn = new QToolButton; mCloseBtn->setIcon(style()->standardIcon(QStyle::SP_TitleBarCloseButton)); mCloseBtn->setText("X"); mCloseBtn->setAutoRaise(true); mStack = new QtCollider::StackLayout; QHBoxLayout* layout = new QHBoxLayout; layout->setContentsMargins(2, 2, 2, 2); layout->addWidget(mCloseBtn, 0, Qt::AlignTop | Qt::AlignLeft); layout->addLayout(mStack); setLayout(layout); } QAbstractButton* closeButton() { return mCloseBtn; } void addWidget(QWidget* w) { mStack->addWidget(w); } int currentIndex() const { return mStack->currentIndex(); } QWidget* currentWidget() const { return mStack->currentWidget(); } void setCurrentWidget(QWidget* w) { mStack->setCurrentWidget(w); } void setCurrentIndex(int i) { mStack->setCurrentIndex(i); } private: QtCollider::StackLayout* mStack; QToolButton* mCloseBtn; }; } // namespace ScIDE
2,075
C++
.h
49
37.265306
82
0.720837
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,231
doc_list.hpp
supercollider_supercollider/editors/sc-ide/widgets/doc_list.hpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include "util/docklet.hpp" #include "../core/doc_manager.hpp" #include <QListWidget> namespace ScIDE { class DocumentManager; class Document; class DocumentListWidget : public QListWidget { Q_OBJECT public: DocumentListWidget(DocumentManager*, QWidget* parent = 0); public Q_SLOTS: void setCurrent(Document*); void updateDockletOrder(int, int); Q_SIGNALS: void clicked(Document*); void updateTabsOrder(QList<Document*>); private Q_SLOTS: void onOpen(Document*, int, int); void onClose(Document*); void onSaved(Document*); void onModificationChanged(Document*); void onItemClicked(QListWidgetItem*); protected: virtual QSize sizeHint() const { return QSize(200, 200); } private: struct Item : public QListWidgetItem { Item(Document* doc, QListWidget* parent = 0): QListWidgetItem(parent, QListWidgetItem::UserType), mDoc(doc) { setText(doc->title()); } Document* mDoc; }; virtual void dropEvent(QDropEvent*); QList<Document*> listDocuments(); Item* addItemFor(Document*); Item* itemFor(Document*); Item* itemFor(QListWidgetItem*); QIcon mDocModifiedIcon; QList<Document*> dockletOrder; }; class DocumentsDocklet : public Docklet { Q_OBJECT public: DocumentsDocklet(DocumentManager* manager, QWidget* parent = 0); DocumentListWidget* list() { return mDocList; } private: DocumentListWidget* mDocList; }; } // namespace ScIDE
2,332
C++
.h
65
31.538462
117
0.735504
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,232
session_switch_dialog.hpp
supercollider_supercollider/editors/sc-ide/widgets/session_switch_dialog.hpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include <QDialog> #include <QListWidget> namespace ScIDE { class SessionSwitchDialog : public QDialog { Q_OBJECT public: explicit SessionSwitchDialog(QWidget* parent = NULL); QString activeElement() { return mSessions->currentItem()->text(); } public Q_SLOTS: void onItemActivated(QListWidgetItem*); private: QListWidget* mSessions; }; }
1,218
C++
.h
31
35.451613
81
0.757447
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,233
multi_editor.hpp
supercollider_supercollider/editors/sc-ide/widgets/multi_editor.hpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include <QWidget> #include <QTabBar> #include <QAction> #include <QPushButton> #include <QToolButton> #include <QLineEdit> #include <QCheckBox> #include <QLabel> #include <QGridLayout> #include <QTextDocument> #include <QSplitter> #include "../doc_manager.hpp" namespace ScIDE { class CodeEditorBox; class Document; class DocumentManager; class GenericCodeEditor; class Main; class MultiSplitter; struct Session; class SignalMultiplexer; namespace Settings { class Manager; } class EditorTabBar : public QTabBar { Q_OBJECT public: explicit EditorTabBar(QWidget* parent = nullptr); private slots: void onCloseTab(); void onCloseOtherTabs(); void onCloseTabsToTheRight(); private: void mousePressEvent(QMouseEvent* event) override final; void mouseDoubleClickEvent(QMouseEvent* event) override final; void showContextMenu(QMouseEvent* event); int mTabUnderCursor; }; class MultiEditor : public QWidget { Q_OBJECT public: enum ActionRole { // Edit Undo, Redo, Cut, Copy, Paste, IndentLineOrRegion, TriggerAutoCompletion, TriggerMethodCallAid, ToggleComment, ToggleOverwriteMode, CopyLineUp, CopyLineDown, MoveLineUp, MoveLineDown, DeleteWord, GotoPreviousBlock, GotoNextBlock, SelectEnclosingBlock, GotoPreviousRegion, GotoNextRegion, GotoPreviousEmptyLine, GotoNextEmptyLine, SelectRegion, // View DocClose, EnlargeFont, ShrinkFont, ResetFontSize, ShowWhitespace, ShowLinenumber, IndentWithSpaces, ShowAutocompleteHelp, NextDocument, PreviousDocument, SwitchDocument, SplitHorizontally, SplitVertically, RemoveCurrentSplit, RemoveAllSplits, // Language EvaluateCurrentDocument, EvaluateRegion, EvaluateLine, ActionRoleCount }; MultiEditor(Main*, QWidget* parent = 0); int tabCount() { return mTabs->count(); } Document* documentForTab(int index); int tabForDocument(Document* doc); GenericCodeEditor* currentEditor(); CodeEditorBox* currentBox() { return mCurrentEditorBox; } void split(Qt::Orientation direction); QAction* action(ActionRole role) { return mActions[role]; } void saveSession(Session*); void switchSession(Session*); signals: void currentDocumentChanged(Document*); void splitViewActivated(); void splitViewDeactivated(); void updateDockletOrder(int, int); public slots: void setCurrent(Document*); void showNextDocument(); void showPreviousDocument(); void switchDocument(); void splitHorizontally() { split(Qt::Horizontal); } void splitVertically() { split(Qt::Vertical); } void removeCurrentSplit(); void removeAllSplits(); void setShowWhitespace(bool on); void setShowLinenumber(bool on); void setShowAutocompleteHelp(bool on); void updateTabsOrder(QList<Document*>); private slots: void applySettings(Settings::Manager*); void onOpen(Document*, int initialCursorPosition, int selectionLength); void onClose(Document*); void show(Document*, int cursorPosition = -1, int selectionLenght = 0); void update(Document*); void onCloseRequest(int index); void onCurrentTabChanged(int index); void onCurrentEditorChanged(GenericCodeEditor*); void onBoxActivated(CodeEditorBox*); void onDocModified(Document*); void updateDocOrder(int, int); private: void makeSignalConnections(); void breakSignalConnections(); void createActions(); void updateActions(); /** * Put a new doc into the editor. If `doc` is already opened, this simply returns its current index. * * @param doc The doc to insert. * @param insertIndex Index at which to insert. If negative, the doc is inserted after the current tab. * @return The index of the tab. */ int insertTab(Document* doc, int insertIndex = -1); CodeEditorBox* newBox(MultiSplitter*); void setCurrentBox(CodeEditorBox*); void setCurrentEditor(GenericCodeEditor*); void loadBoxState(CodeEditorBox* box, const QVariantList& data, const QList<Document*>& documentList); void loadSplitterState(MultiSplitter*, const QVariantMap& data, const QList<Document*>& documentList); void showEditorTabs(bool); void activateComboBoxWhenSplitting(); void setMainComboBoxOption(); QAction* mActions[ActionRoleCount]; SignalMultiplexer* mEditorSigMux; SignalMultiplexer* mBoxSigMux; // gui QTabBar* mTabs; CodeEditorBox* mCurrentEditorBox; MultiSplitter* mSplitter; QIcon mDocModifiedIcon; QVBoxLayout* multiEditorLayout; }; } // namespace ScIDE
5,748
C++
.h
177
27.067797
107
0.721086
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
34,234
popup_text_input.hpp
supercollider_supercollider/editors/sc-ide/widgets/popup_text_input.hpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include <QInputDialog> #include <QKeyEvent> #include <QPainter> namespace ScIDE { class PopupTextInput : public QInputDialog { Q_OBJECT public: PopupTextInput(QString const& labelText, QWidget* parent): QInputDialog(parent, Qt::Dialog | Qt::FramelessWindowHint) { setOption(QInputDialog::NoButtons); setInputMode(QInputDialog::TextInput); setLabelText(labelText); if (parent) { QRect position = rect(); position.moveCenter(parent->rect().center()); resize(position.size()); move(parent->mapToGlobal(position.topLeft())); } this->show(); } private: void paintEvent(QPaintEvent*) { QPainter painter(this); painter.setBrush(Qt::NoBrush); painter.setPen(palette().color(QPalette::Dark)); painter.drawRect(rect().adjusted(0, 0, -1, -1)); } virtual void keyPressEvent(QKeyEvent* event) { switch (event->key()) { case Qt::Key_Enter: case Qt::Key_Return: accept(); event->accept(); return; default:; } QInputDialog::keyPressEvent(event); } }; }
2,047
C++
.h
57
29.333333
81
0.670547
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,235
sessions_dialog.hpp
supercollider_supercollider/editors/sc-ide/widgets/sessions_dialog.hpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include "../core/session_manager.hpp" #include <QDialog> #include <QListWidget> #include <QPushButton> #include <QDialogButtonBox> #include <QHBoxLayout> #include <QVBoxLayout> #include <QInputDialog> #include <QMessageBox> namespace ScIDE { class SessionsDialog : public QDialog { Q_OBJECT public: SessionsDialog(SessionManager* mng, QWidget* parent = 0): QDialog(parent), mSessionManager(mng) { setWindowTitle("Sessions"); mList = new QListWidget; QPushButton* removeBtn = new QPushButton(tr("Delete")); QPushButton* renameBtn = new QPushButton(tr("Rename...")); QDialogButtonBox* dialogBtns = new QDialogButtonBox(QDialogButtonBox::Ok); QHBoxLayout* contentBox = new QHBoxLayout; QVBoxLayout* btnBox = new QVBoxLayout; btnBox->addWidget(renameBtn); btnBox->addWidget(removeBtn); btnBox->addStretch(); contentBox->addWidget(mList); contentBox->addLayout(btnBox); QVBoxLayout* layout = new QVBoxLayout; layout->addLayout(contentBox); layout->addWidget(dialogBtns); setLayout(layout); connect(removeBtn, SIGNAL(clicked()), this, SLOT(removeCurrent())); connect(renameBtn, SIGNAL(clicked()), this, SLOT(renameCurrent())); connect(dialogBtns, SIGNAL(accepted()), this, SLOT(accept())); updateSessions(); } private slots: void removeCurrent() { QListWidgetItem* item = mList->currentItem(); if (!item) return; QString name = item->text(); if (QMessageBox::warning(this, tr("Delete Session"), tr("Are you sure you want to delete session '%1'?").arg(name), QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes) == QMessageBox::Yes) { mSessionManager->removeSession(name); updateSessions(); } } void renameCurrent() { QListWidgetItem* item = mList->currentItem(); if (!item) return; QString oldName = item->text(); QString newName = QInputDialog::getText(this, tr("Rename Session"), tr("Enter a new name for the session:"), QLineEdit::Normal, oldName); if (newName.isEmpty() || newName == oldName) return; mSessionManager->renameSession(oldName, newName); updateSessions(); } private: void updateSessions() { mList->clear(); QStringList sessions = mSessionManager->availableSessions(); mList->addItems(sessions); const Session* currentSession = mSessionManager->currentSession(); if (!currentSession) return; const int currentSessionIndex = sessions.indexOf(currentSession->name()); if (currentSessionIndex != -1) mList->setCurrentRow(currentSessionIndex); } QListWidget* mList; SessionManager* mSessionManager; }; } // namespace ScIDE
3,873
C++
.h
94
33.276596
116
0.660533
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,236
lang_status_box.hpp
supercollider_supercollider/editors/sc-ide/widgets/lang_status_box.hpp
/* SuperCollider Qt IDE Copyright (c) 2012 - 2013 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include "util/status_box.hpp" #include <QProcess> namespace ScIDE { class ScProcess; class LangStatusBox : public StatusBox { Q_OBJECT public: LangStatusBox(ScProcess*, QWidget* parent = 0); private slots: void onInterpreterStateChanged(QProcess::ProcessState); private: StatusLabel* mLabel; }; } // namespace ScIDE
1,197
C++
.h
31
34.967742
81
0.759516
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,237
editor_box.hpp
supercollider_supercollider/editors/sc-ide/widgets/editor_box.hpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include <QWidget> #include <QStackedLayout> #include <QPointer> #include <QComboBox> #include <QBoxLayout> #include <QStandardItemModel> #include <QSortFilterProxyModel> #include "../core/doc_manager.hpp" #include "../core/main.hpp" #include "util/multi_splitter.hpp" namespace ScIDE { class Document; class GenericCodeEditor; class MultiSplitter; /* A CodeEditorBox represents an IDE document split view: it contains a stack (history) of documents displayed in that split, and an editor widget for each of those documents. Using the document tabs, or the "Switch Document" action one is effectively changing which of those editors is displayed, and thus reordering the viewing history of the CodeEditorBox (the last displayed always moves on top of the stack). A CodeEditorBox becomes "active" when any of its editors receives focus, but it does *not* become inactive when its editors loose focus: it only becomes inactive when another EditorBox becomes active. That allows a CodeEditorBox to be active even if no editor widget in the IDE has focus. The purpose of the "active" CodeEditorBox is for the IDE to direct certain actions to it: e.g. it is the one where newly created and opened documents will be displayed. */ class CodeEditorBox : public QWidget { Q_OBJECT public: typedef QList<GenericCodeEditor*> History; CodeEditorBox(MultiSplitter* splitter, QWidget* parent = 0); void setDocument(Document*, int pos = -1, int selectionLength = 0); GenericCodeEditor* currentEditor(); Document* currentDocument(); const History& history() { return mHistory; } void setActive() { if (isActive()) return; CodeEditorBox* lastActiveBox = gActiveBox; gActiveBox = this; if (lastActiveBox) lastActiveBox->update(); update(); if (lastActiveBox) emit lastActiveBox->activeChanged(false); emit activated(this); emit activeChanged(true); } bool isActive() { return gActiveBox == this; } QSize minimumSizeHint() const { return QSize(100, 100); } QSize sizeHint() const { return QSize(100, 100); } void showComboBox(bool); signals: void currentChanged(GenericCodeEditor*); void activated(CodeEditorBox* me); void activeChanged(bool active); public slots: void applySettings(Settings::Manager*); void comboBoxWhenSplitting(); void tabsWhenRemovingSplits(); private slots: void onDocumentClosed(Document*); void onDocumentSaved(Document*); void onComboSelectionChanged(int index); private: int historyIndexOf(Document*); GenericCodeEditor* editorForDocument(Document*); bool eventFilter(QObject*, QEvent*); void focusInEvent(QFocusEvent*); void paintEvent(QPaintEvent*); QStackedLayout* mLayout; History mHistory; static QPointer<CodeEditorBox> gActiveBox; QBoxLayout* mTopLayout; QComboBox* mDocComboBox; MultiSplitter* mSplitter; QSortFilterProxyModel* mProxyModel; }; } // namespace ScIDE
3,896
C++
.h
99
35.080808
81
0.750598
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,238
lookup_dialog.hpp
supercollider_supercollider/editors/sc-ide/widgets/lookup_dialog.hpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include <QDialog> #include <QLineEdit> #include <QStandardItemModel> #include <QTreeWidget> #include "../core/sc_process.hpp" #include "code_editor/sc_editor.hpp" namespace ScIDE { class GenericLookupDialog : public QDialog { Q_OBJECT public: static const int PathRole = Qt::UserRole + 1; static const int CharPosRole = Qt::UserRole + 2; static const int IsClassRole = Qt::UserRole + 3; static const int ClassNameRole = Qt::UserRole + 4; static const int MethodNameRole = Qt::UserRole + 5; explicit GenericLookupDialog(QWidget* parent = 0); void query(const QString& query) { mQueryEdit->setText(query); this->performQuery(); } void clearQuery() { mQueryEdit->clear(); } void setModel(QStandardItemModel*); public Q_SLOTS: bool openDocumentation(); protected Q_SLOTS: virtual void onAccepted(QModelIndex); void currentChanged(const QModelIndex&, const QModelIndex&); private Q_SLOTS: virtual void performQuery() = 0; protected: QStandardItem* firstItemInLine(QModelIndex); virtual bool event(QEvent*); bool eventFilter(QObject*, QEvent*); void focusResults(); static QList<QStandardItem*> makeDialogItem(QString const& displayString, QString const& displayPath, QString const& path, int position, QString const& className, QString const& methodName, bool isClassItem); QTreeView* mResult; QLineEdit* mQueryEdit; Document* mPreviewDocument; ScCodeEditor* mPreviewEditor; }; class LookupDialog : public GenericLookupDialog { Q_OBJECT public: explicit LookupDialog(QWidget* parent = 0); private slots: void performQuery(); void onAccepted(QModelIndex); private: QStandardItemModel* modelForClass(const QString& className, const QString& methodName = QString()); QStandardItemModel* modelForMethod(const QString& methodName); QStandardItemModel* modelForPartialQuery(const QString& queryString); bool performClassQuery(const QString& className); bool performMethodQuery(const QString& methodName); bool performPartialQuery(const QString& queryString); bool mIsPartialQuery; }; // LATER: cache symbol references to avoid duplicate lookup class SymbolReferenceRequest : public ScRequest { Q_OBJECT public: SymbolReferenceRequest(ScProcess* process, QObject* parent = NULL): ScRequest(process, parent) {} void sendRequest(QString const& symbol) { send("findReferencesToSymbol", symbol); } }; class ReferencesDialog : public LookupDialog { Q_OBJECT public: explicit ReferencesDialog(QWidget* parent = NULL); private slots: void requestCancelled(); void performQuery(); void onResposeFromLanguage(const QString& command, const QString& responseData); QStandardItemModel* parse(QString const& responseData); private: SymbolReferenceRequest* mRequest; }; } // namespace ScIDE
3,834
C++
.h
95
35.389474
108
0.740162
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,239
cmd_line.hpp
supercollider_supercollider/editors/sc-ide/widgets/cmd_line.hpp
/* SuperCollider Qt IDE Copyright (c) 2010-2012 Jakob Leben Copyright (c) 2012 Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include <QLineEdit> #include <QString> #include <QWidget> namespace ScIDE { namespace Settings { class Manager; } class CmdLineEdit : public QLineEdit { Q_OBJECT public: explicit CmdLineEdit(QWidget* parent = NULL): QLineEdit(parent) {} public Q_SLOTS: bool openDocumentation(); void openDefinition(); void openCommandLine(); void findReferences(); private: QString symbolUnderCursor(); }; class CmdLine : public QWidget { Q_OBJECT public: CmdLine(const QString& text, int maxHistory = 30); void applySettings(Settings::Manager*); void setText(const QString& text); signals: void invoked(const QString&, bool silent); private: bool eventFilter(QObject*, QEvent*); CmdLineEdit* expr; QStringList history; int curHistory; int maxHistory; }; } // namespace ScIDE
1,719
C++
.h
53
28.698113
81
0.7453
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,240
documents_dialog.hpp
supercollider_supercollider/editors/sc-ide/widgets/documents_dialog.hpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include "../core/doc_manager.hpp" #include <QDialog> #include <QTreeWidget> #include <QLabel> namespace ScIDE { class Document; class DocumentsDialog : public QDialog { Q_OBJECT public: enum Mode { ExternalChange, Quit }; DocumentsDialog(Mode, QWidget* parent = 0); DocumentsDialog(const QList<Document*>& docs, Mode, QWidget* parent = 0); void setText(const QString& text) { mLabel->setText(text); } void addDocument(Document*); int count() { return mDocTree->topLevelItemCount(); } public slots: void selectAll(); void selectNone(); private slots: void saveSelected(); void reloadSelected(); void ignoreSelected(); void closeSelected(); void onDocumentChangedExternally(Document*); private: class Item : public QTreeWidgetItem { public: Item(Document* doc); Document* document() const { return mDoc; } bool isChecked() const { return checkState(0) == Qt::Checked; } void setChecked(bool checked) { setCheckState(0, checked ? Qt::Checked : Qt::Unchecked); } void update(); private: void setTitle(const QString& title) { setText(0, title); } void setPath(const QString& path) { setText(1, path); } void setStatus(const QString& status) { setText(2, status); } Document* mDoc; }; void init(Mode mode, const QList<Document*>& = QList<Document*>()); Item* item(int idx) { return static_cast<Item*>(mDocTree->topLevelItem(idx)); } Mode mMode; QLabel* mLabel; QTreeWidget* mDocTree; }; } // namespace ScIDE
2,432
C++
.h
62
34.387097
98
0.705357
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,241
goto_line_tool.hpp
supercollider_supercollider/editors/sc-ide/widgets/goto_line_tool.hpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include "code_editor/editor.hpp" #include "../core/doc_manager.hpp" #include <QWidget> #include <QSpinBox> #include <QToolButton> #include <QHBoxLayout> #include <QKeyEvent> #include <QPointer> #include <QLabel> #include <QTextBlock> namespace ScIDE { class GoToLineTool : public QWidget { Q_OBJECT public: GoToLineTool(QWidget* parent = 0): QWidget(parent), mEditor(0) { mSpinBox = new QSpinBox; mSpinBox->setMinimum(0); mSpinBox->setMaximum(0); QToolButton* goBtn = new QToolButton; goBtn->setText(tr("Go")); goBtn->setAutoRaise(true); QLabel* label = new QLabel(tr("Line:")); QHBoxLayout* layout = new QHBoxLayout; layout->setContentsMargins(0, 0, 0, 0); layout->addWidget(label); layout->addWidget(mSpinBox); layout->addWidget(goBtn); layout->addStretch(); setLayout(layout); setFocusProxy(mSpinBox); connect(goBtn, SIGNAL(clicked()), this, SLOT(go())); connect(mSpinBox, SIGNAL(editingFinished()), this, SLOT(onEditingFinished())); } void setEditor(GenericCodeEditor* editor) { if (mEditor) mEditor->disconnect(this, SLOT(setMaximum(int))); mEditor = editor; if (mEditor) { connect(mEditor, SIGNAL(blockCountChanged(int)), this, SLOT(setMaximum(int))); setMaximum(mEditor->blockCount()); } else setMaximum(0); } void setValue(int value) { mSpinBox->setValue(value); } public slots: void setMaximum(int max) { if (max > 0) mSpinBox->setRange(1, max); else mSpinBox->setRange(0, 0); } void setFocus() { mSpinBox->setFocus(Qt::OtherFocusReason); mSpinBox->selectAll(); } signals: void activated(int lineNumber); private slots: void go() { int lineNumber = mSpinBox->value(); if (mEditor) { QTextDocument* doc = mEditor->textDocument(); QTextBlock block(doc->findBlockByNumber(lineNumber - 1)); if (!block.isValid()) return; QTextCursor cursor(doc); cursor.setPosition(block.position()); mEditor->setTextCursor(cursor); } emit activated(lineNumber); } void onEditingFinished() { if (mSpinBox->hasFocus()) go(); } private: QSpinBox* mSpinBox; QPointer<GenericCodeEditor> mEditor; }; } // namespace ScIDE
3,364
C++
.h
97
27.824742
90
0.653478
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,242
audio_status_box.hpp
supercollider_supercollider/editors/sc-ide/widgets/audio_status_box.hpp
/* SuperCollider Qt IDE Copyright (c) 2012 - 2013 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include "util/status_box.hpp" namespace ScIDE { class ScServer; class AudioStatusBox : public StatusBox { Q_OBJECT public: AudioStatusBox(ScServer*, QWidget* parent = 0); private slots: void onServerRunningChanged(bool running, QString const& hostName, int port, bool unresponsive); void updateStatistics(int ugens, int synths, int groups, int synthDefs, float avgCPU, float peakCPU); void updateVolumeLabel(float volume); void updateMuteLabel(bool muted); void updateRecordLabel(bool recording); signals: void increaseVolume(); void decreaseVolume(); private: void wheelEvent(QWheelEvent*); StatusLabel* mStatisticsLabel; StatusLabel* mVolumeLabel; StatusLabel* mMuteLabel; StatusLabel* mRecordLabel; }; } // namespace ScIDE
1,652
C++
.h
41
36.195122
105
0.760652
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,243
find_replace_tool.hpp
supercollider_supercollider/editors/sc-ide/widgets/find_replace_tool.hpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include <QWidget> #include <QPushButton> #include <QLabel> #include <QLineEdit> #include <QGridLayout> #include <QTextDocument> #include <QAction> #include <QMenu> #include <QToolButton> #include <QRegularExpression> namespace ScIDE { class GenericCodeEditor; class TextFindReplacePanel : public QWidget { Q_OBJECT public: enum Mode { Find = 1, Replace }; enum ActionRole { FindNext, FindPrevious, ActionCount }; public: TextFindReplacePanel(QWidget* parent = 0); void setEditor(GenericCodeEditor* editor) { mEditor = editor; } Mode mode() const { return mMode; } void setMode(Mode); void initiate(); QString findString() const { return mFindField->text(); } QString replaceString() const { return mReplaceField->text(); } bool matchCase() const { return mMatchCaseAction->isChecked(); } bool asRegExp() const { return mRegExpAction->isChecked(); } bool wholeWords() const { return mWholeWordAction->isChecked(); } QRegularExpression regexp(); QTextDocument::FindFlags flags(); QAction* action(ActionRole role) { return mActions[role]; } public Q_SLOTS: void findNext(); void findPrevious(); void findAll(); void replace(); void replaceAll(); private Q_SLOTS: void onFindFieldReturn(); void onFindFieldTextChanged(); private: void find(bool backwards); bool eventFilter(QObject*, QEvent*); static void reportFoundOccurrencies(int count); static void reportReplacedOccurrencies(int count); QLineEdit* mFindField; QLabel* mFindLabel; QLineEdit* mReplaceField; QLabel* mReplaceLabel; QToolButton* mNextBtn; QToolButton* mPrevBtn; QToolButton* mReplaceBtn; QToolButton* mReplaceAllBtn; QToolButton* mOptionsBtn; QAction* mMatchCaseAction; QAction* mRegExpAction; QAction* mWholeWordAction; QAction* mActions[ActionCount]; QGridLayout* mGrid; Mode mMode; GenericCodeEditor* mEditor; int mSearchPosition; }; } // namespace ScIDE
2,899
C++
.h
85
29.764706
81
0.734767
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
34,244
help_browser.hpp
supercollider_supercollider/editors/sc-ide/widgets/help_browser.hpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include "util/docklet.hpp" #include "QtCollider/widgets/web_page.hpp" #include "QtCollider/widgets/QcWebView.h" #include <QWebEngineView> #include <QLabel> #include <QLineEdit> #include <QBasicTimer> #include <QTimerEvent> #include <QList> #include <QKeySequence> namespace ScIDE { namespace Settings { class Manager; } class HelpBrowserDocklet; class HelpBrowserFindBox; class HelpBrowser; class LoadProgressIndicator : public QLabel { Q_OBJECT public slots: void start(const QString& msg = tr("Loading")) { mMsg = msg; mDotCount = 0; mUpdateTimer.start(200, this); } void stop() { mUpdateTimer.stop(); clear(); } protected: virtual void timerEvent(QTimerEvent* event) { if (event->timerId() != mUpdateTimer.timerId()) return; ++mDotCount; if (mDotCount > 6) mDotCount = 1; QString string(mDotCount, '.'); string.prepend(mMsg); setText(string); } private: QBasicTimer mUpdateTimer; QString mMsg; int mDotCount; }; class HelpBrowser : public QWidget { Q_OBJECT public: enum ActionRole { GoHome, DocClose, ZoomIn, ZoomOut, ResetZoom, Evaluate, EvaluateRegion, ActionCount }; HelpBrowser(QWidget* parent = 0); QSize sizeHint() const { return mSizeHint; } QSize minimumSizeHint() const { return QSize(50, 50); } void gotoHelpFor(const QString&); void gotoHelpForMethod(const QString& className, const QString& methodName); QWidget* loadProgressIndicator() { return mLoadProgressIndicator; } QUrl url() const { return mWebView->url(); } bool helpBrowserHasFocus() const; void setServerPort(int serverPort) { mServerPort = serverPort; }; public slots: void applySettings(Settings::Manager*); void goHome(); void closeDocument(); void zoomIn(); void zoomOut(); void resetZoom(); void evaluateSelection(bool region = false); void findText(const QString& text, bool backwards = false); bool openDocumentation(); void openDefinition(); void openCommandLine(); void findReferences(); void onLinkClicked(const QUrl&, QWebEnginePage::NavigationType type, bool isMainFrame); void onPageLoad(); signals: void urlChanged(); private slots: void onContextMenuRequest(const QPoint& pos); void onReload(); void onScResponse(const QString& command, const QString& data); void onJsConsoleMsg(const QString&, int, const QString&); private: friend class HelpBrowserDocklet; void createActions(); bool eventFilter(QObject* object, QEvent* event); void sendRequest(const QString& code); QString symbolUnderCursor(); QtCollider::WebView* mWebView; LoadProgressIndicator* mLoadProgressIndicator; QSize mSizeHint; QAction* mActions[ActionCount]; int mServerPort = 0; // if 0, server is not running }; class HelpBrowserFindBox : public QLineEdit { Q_OBJECT public: HelpBrowserFindBox(QWidget* parent = 0); signals: void query(const QString& text, bool backwards = false); protected: virtual bool event(QEvent* event); }; class HelpBrowserDocklet : public Docklet { Q_OBJECT public: explicit HelpBrowserDocklet(QWidget* parent = 0); HelpBrowser* browser() { return mHelpBrowser; } private slots: void onInterpreterStart() { if (isVisible() && mHelpBrowser->url().isEmpty()) mHelpBrowser->goHome(); } private: HelpBrowser* mHelpBrowser; HelpBrowserFindBox* mFindBox; }; } // namespace ScIDE
4,495
C++
.h
142
26.830986
91
0.710905
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,245
main_window.hpp
supercollider_supercollider/editors/sc-ide/widgets/main_window.hpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include <QLabel> #include <QMainWindow> #include <QProcess> #include <QStatusBar> #include "util/status_box.hpp" namespace ScIDE { class Main; class MultiEditor; class ToolBox; class TextFindReplacePanel; class GoToLineTool; class PostDocklet; class DocumentsDocklet; class HelpBrowserDocklet; class CmdLine; class Document; class DocumentsDialog; struct Session; class ClockStatusBox; class ScServer; class ScProcess; class GenericCodeEditor; namespace Settings { class Manager; } class MainWindow : public QMainWindow { Q_OBJECT public: enum ActionRole { // File Quit = 0, DocNew, DocOpen, DocOpenStartup, DocOpenSupportDir, DocSave, DocSaveAs, DocSaveAsExtension, DocSaveAll, DocCloseAll, DocReload, ClearRecentDocs, // Sessions NewSession, SaveSessionAs, ManageSessions, OpenSessionSwitchDialog, // Edit Find, Replace, // View ShowCmdLine, CmdLineForCursor, ShowGoToLineTool, CloseToolBox, ShowFullScreen, FocusPostWindow, // Settings ShowSettings, // Language LookupImplementation, LookupImplementationForCursor, LookupReferences, LookupReferencesForCursor, // Help Help, HelpAboutIDE, ReportABug, #ifdef SC_USE_QTWEBENGINE // These QtWebEngine-only actions are branched at the preprocessor // level so that accidental invocations of these actions in other code // are caught at compile time. LookupDocumentationForCursor, LookupDocumentation, #endif // SC_USE_QTWEBENGINE ShowAbout, ShowAboutQT, ActionCount }; explicit MainWindow(Main*); QAction* action(ActionRole); bool quit(); void saveWindowState(); void restoreWindowState(); void focusCodeEditor(); bool promptSaveDocs(); #ifdef SC_USE_QTWEBENGINE HelpBrowserDocklet* helpBrowserDocklet() { return mHelpBrowserDocklet; } #endif PostDocklet* postDocklet() { return mPostDocklet; } static MainWindow* instance() { return mInstance; } Settings::Manager* setting(); static bool close(Document*); static bool save(Document*, bool forceChoose = false, bool saveInExtensionFolder = false); static bool reload(Document*); void restoreDocuments(); public Q_SLOTS: void newSession(); void saveCurrentSessionAs(); void openSessionsDialog(); void newDocument(); void openDocument(); void saveDocument(); void saveDocumentAs(); void saveDocumentAsExtension(); void saveAllDocuments(); void reloadDocument(); void closeDocument(); void closeAllDocuments(); void showCmdLine(); void showCmdLine(const QString&); void showFindTool(); void showReplaceTool(); void showGoToLineTool(); void hideToolBox(); void showSettings(); signals: void evaluateCode(const QString&, bool silent = true); public Q_SLOTS: void showStatusMessage(QString const& string); private Q_SLOTS: void openStartupFile(); void openUserSupportDirectory(); void switchSession(Session* session); void saveSession(Session* session); void onInterpreterStateChanged(QProcess::ProcessState); void onQuit(); void onCurrentDocumentChanged(Document*); void onDocumentChangedExternally(Document*); void onDocDialogFinished(); void updateRecentDocsMenu(); void onOpenRecentDocument(QAction*); void onOpenSessionAction(QAction*); void updateWindowTitle(); void toggleFullScreen(); void lookupImplementation(); void lookupImplementationForCursor(); void lookupReferences(); void lookupReferencesForCursor(); void openHelp(); void openHelpAboutIDE(); void doBugReport(); void lookupDocumentationForCursor(); void lookupDocumentation(); void applySettings(Settings::Manager*); void storeSettings(Settings::Manager*); void showSwitchSessionDialog(); void showAbout(); void showAboutQT(); void cmdLineForCursor(); protected: virtual void closeEvent(QCloseEvent* event); virtual void dragEnterEvent(QDragEnterEvent*); virtual void dropEvent(QDropEvent*); virtual bool eventFilter(QObject*, QEvent*); private: void createActions(); void createMenus(); template <class T> void saveWindowState(T* settings); template <class T> void restoreWindowState(T* settings); void updateSessionsMenu(); void updateClockWidget(bool isFullScreen); void openSession(QString const& sessionName); bool checkFileExtension(const QString& fpath); void toggleInterpreterActions(bool enabled); void applyCursorBlinkingSettings(Settings::Manager*); QString documentOpenPath() const; QString documentSavePath(Document*) const; Main* mMain; QAction* mActions[ActionCount]; QMenu* mRecentDocsMenu; QMenu* mSessionsMenu; MultiEditor* mEditors; // Tools ToolBox* mToolBox; CmdLine* mCmdLine; GoToLineTool* mGoToLineTool; TextFindReplacePanel* mFindReplaceTool; // Status bar QStatusBar* mStatusBar; StatusBox* mLangStatus; StatusBox* mServerStatus; ClockStatusBox* mClockLabel; // Docks PostDocklet* mPostDocklet; DocumentsDocklet* mDocumentsDocklet; #ifdef SC_USE_QTWEBENGINE HelpBrowserDocklet* mHelpBrowserDocklet; #endif DocumentsDialog* mDocDialog; QString mLastDocumentSavePath; static MainWindow* mInstance; }; class ClockStatusBox : public StatusLabel { public: ClockStatusBox(QWidget* parent = 0); ~ClockStatusBox(); private: void timerEvent(QTimerEvent*); void updateTime(); int mTimerId; }; } // namespace ScIDE
6,708
C++
.h
220
25.286364
94
0.724336
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,247
path_chooser_widget.hpp
supercollider_supercollider/editors/sc-ide/widgets/util/path_chooser_widget.hpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include <QLineEdit> #include <QPushButton> #include <QFileDialog> #include <QHBoxLayout> #include <QPointer> namespace ScIDE { class PathChooserWidget : public QWidget { Q_OBJECT public: PathChooserWidget(QWidget* parent = 0, QFileDialog::FileMode mode = QFileDialog::ExistingFile): QWidget(parent), mMode(mode), dialog(0) { mTextField = new QLineEdit; mButton = new QPushButton; mButton->setIcon(QIcon::fromTheme("folder")); mButton->setFixedWidth(30); mButton->setFlat(true); // setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); QHBoxLayout* box = new QHBoxLayout(this); box->addWidget(mTextField); box->addWidget(mButton); box->setContentsMargins(0, 0, 0, 0); box->setSpacing(1); connect(mButton, SIGNAL(clicked()), this, SLOT(execDialog()), Qt::QueuedConnection); } QString text() const { return mTextField->text(); } void setText(const QString& text) { mTextField->setText(text); } void setFileMode(QFileDialog::FileMode mode) { mMode = mode; } public Q_SLOTS: void execDialog() { if (!dialog) { QWidget* parent = parentWidget(); dialog = new QFileDialog(parent ? parent : this); } dialog->setFileMode(mMode); dialog->selectFile(mTextField->text()); QPointer<QLineEdit> textField = mTextField; int result = dialog->exec(); if (result == QDialog::Accepted && textField) { QStringList paths = dialog->selectedFiles(); textField->setText(paths.count() ? paths[0] : ""); } } Q_SIGNALS: void textChanged(const QString&); private: QLineEdit* mTextField; QPushButton* mButton; QFileDialog::FileMode mMode; QFileDialog* dialog; }; } // namespace ScIDE
2,705
C++
.h
70
32.514286
99
0.681575
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,248
text_format_list_widget.hpp
supercollider_supercollider/editors/sc-ide/widgets/util/text_format_list_widget.hpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include <QTreeView> #include <QStyledItemDelegate> #include <QTextCharFormat> #include <QStandardItemModel> namespace ScIDE { class TextFormatListWidget : public QTreeView { Q_OBJECT public: class ItemDelegate : public QStyledItemDelegate { public: ItemDelegate(QObject* parent); virtual QSize sizeHint(const QStyleOptionViewItem&, const QModelIndex&) const; virtual void paint(QPainter*, const QStyleOptionViewItem&, const QModelIndex&) const; }; public: TextFormatListWidget(QWidget* parent); void addFormat(const QString& name, const QTextCharFormat& format); void setFormat(int index, const QTextCharFormat& format); inline void removeFormat(int index) { standardModel()->removeRow(index); } int currentIndex() { QModelIndex index(QAbstractItemView::currentIndex()); if (index.isValid()) return index.row(); else return -1; } QString name(int index); QTextCharFormat format(int index); inline int count() { return standardModel()->rowCount(); } Q_SIGNALS: void clicked(int index); private Q_SLOTS: void onDoubleClicked(const QModelIndex&); private: QStandardItem* makeBrushItem(const QBrush& brush); QStandardItem* makeBoolItem(bool b); inline QStandardItemModel* standardModel() { return qobject_cast<QStandardItemModel*>(model()); } }; } // namespace ScIDE
2,279
C++
.h
56
35.696429
101
0.738063
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,249
WebSocketClientWrapper.hpp
supercollider_supercollider/editors/sc-ide/widgets/util/WebSocketClientWrapper.hpp
/* SuperCollider Qt IDE http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Adapted from Qt example, which is BSD-licensed: https://doc.qt.io/qt-5/qtwebchannel-standalone-example.html BSD License 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 The Qt Company Ltd 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. */ #pragma once #include <QWebSocketServer> #include <QObject> #include "WebSocketTransport.hpp" namespace ScIDE { class WebSocketClientWrapper : public QObject { Q_OBJECT public: WebSocketClientWrapper(QWebSocketServer* server, QObject* parent = nullptr): QObject(parent), m_server(server) { connect(server, &QWebSocketServer::newConnection, this, &WebSocketClientWrapper::handleNewConnection); } signals: void clientConnected(WebSocketTransport* client); private slots: void handleNewConnection() { emit clientConnected(new WebSocketTransport(m_server->nextPendingConnection())); } private: QWebSocketServer* m_server; }; } // namespace ScIDE
3,145
C++
.h
60
47.516667
116
0.767677
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,250
IDEWebChannelWrapper.hpp
supercollider_supercollider/editors/sc-ide/widgets/util/IDEWebChannelWrapper.hpp
/* SuperCollider Qt IDE http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include "../help_browser.hpp" #include <QObject> namespace ScIDE { /// Exposes IDE functionality to JS in help browser widget via WebChannel class IDEWebChannelWrapper : public QObject { Q_OBJECT public: IDEWebChannelWrapper(HelpBrowser* browser): m_browser { browser } {} public slots: void evaluateLine() { m_browser->evaluateSelection(false); } private: HelpBrowser* const m_browser; }; } // namespace ScIDE
1,236
C++
.h
30
37.533333
81
0.757956
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,251
status_box.hpp
supercollider_supercollider/editors/sc-ide/widgets/util/status_box.hpp
/* SuperCollider Qt IDE Copyright (c) 2012 - 2013 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include <QLabel> #include <QMenu> namespace ScIDE { class StatusBoxMenu : public QMenu { public: StatusBoxMenu(QWidget* parent = 0): QMenu(parent) {} protected: virtual void mouseReleaseEvent(QMouseEvent* e) { QAction* action = activeAction(); if (action && action->isEnabled() && !action->menu() && action->property("keep_menu_open").toBool()) { action->setEnabled(false); QMenu::mouseReleaseEvent(e); action->setEnabled(true); action->trigger(); return; } QMenu::mouseReleaseEvent(e); } }; class StatusLabel : public QLabel { public: StatusLabel(QWidget* parent = 0); void setBackground(const QBrush&); void setTextColor(const QColor&); }; class StatusBox : public QWidget { public: StatusBox(QWidget* parent = 0); protected: void addActionSeparator(); void showContextMenu(); virtual void mousePressEvent(QMouseEvent*); StatusBoxMenu* mMenu; }; } // namespace ScIDE
1,873
C++
.h
52
31.076923
110
0.706305
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,252
key_sequence_edit.hpp
supercollider_supercollider/editors/sc-ide/widgets/util/key_sequence_edit.hpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include <QLineEdit> #include <QKeyEvent> #include <QBasicTimer> namespace ScIDE { class KeySequenceEdit : public QLineEdit { Q_OBJECT private: QBasicTimer mEditingTimer; public: KeySequenceEdit(QWidget* parent = 0): QLineEdit(parent), k1(0), k2(0), k3(0), k4(0), mEditing(false) { setReadOnly(true); } QKeySequence sequence() { return QKeySequence(k1, k2, k3, k4); } void setSequence(const QKeySequence& seq) { k1 = seq[0]; k2 = seq[1]; k3 = seq[2]; k4 = seq[3]; if (mEditing) finishEditing(); else updateText(); } public slots: void reset() { k1 = k2 = k3 = k4 = 0; if (mEditing) finishEditing(); else updateText(); } void finishEditing() { if (mEditing) { mEditing = false; mEditingTimer.stop(); updateText(); emit editingFinished(); } } signals: void editingStarted(); protected: //#if 0 void updateText() { QKeySequence seq = sequence(); if (seq.isEmpty()) clear(); else { QString text = sequence().toString(QKeySequence::NativeText); if (mEditing) text.append(", ..."); setText(text); } } bool event(QEvent* e) { if (e->type() != QEvent::KeyPress) return QLineEdit::event(e); e->accept(); QKeyEvent* ke = static_cast<QKeyEvent*>(e); int key = ke->key(); if (isModifier(key)) return true; int* k; if (!mEditing) { k1 = k2 = k3 = k4 = 0; mEditing = true; k = &k1; } else { if (k1 == 0) k = &k1; else if (k2 == 0) k = &k2; else if (k3 == 0) k = &k3; else k = &k4; } *k = key | ke->modifiers(); if (k == &k4) finishEditing(); else { mEditingTimer.start(800, this); updateText(); if (k == &k1) emit editingStarted(); } return true; } virtual void timerEvent(QTimerEvent* e) { if (e->timerId() == mEditingTimer.timerId()) finishEditing(); } void focusOutEvent(QFocusEvent* e) { finishEditing(); } //#endif private: bool isModifier(int key) { switch (key) { case Qt::Key_Shift: case Qt::Key_Control: case Qt::Key_Meta: case Qt::Key_Alt: case Qt::Key_AltGr: return true; default: return false; } } int k1, k2, k3, k4; bool mEditing; }; } // namespace ScIDE
3,676
C++
.h
128
20.453125
106
0.549744
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,253
icon_list_widget.hpp
supercollider_supercollider/editors/sc-ide/widgets/util/icon_list_widget.hpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include <QListWidget> #include <QStyledItemDelegate> #include <QPainter> #include <QListWidget> namespace ScIDE { class IconListWidget : public QListWidget { public: class ItemDelegate : public QStyledItemDelegate { public: ItemDelegate(QObject* parent): QStyledItemDelegate(parent) {} virtual QSize sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const { QIcon icon(index.data(Qt::DecorationRole).value<QIcon>()); QSize iconSize = icon.actualSize(option.decorationSize); QString text = index.data(Qt::DisplayRole).toString(); QFontMetrics fm(option.font); int fontWidth = fm.horizontalAdvance(text); QSize requiredSize(qMax(fontWidth, iconSize.width()), fm.height() + iconSize.height()); return requiredSize + QSize(5, 5); } virtual void paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const { painter->save(); QStyle* style = QApplication::style(); style->drawPrimitive(QStyle::PE_PanelItemViewItem, &option, painter); QRect r(option.rect.adjusted(0, 5, 0, -5)); QIcon icon(index.data(Qt::DecorationRole).value<QIcon>()); if (!icon.isNull()) style->drawItemPixmap(painter, r, Qt::AlignTop | Qt::AlignHCenter, icon.pixmap(option.decorationSize)); QString text = index.data(Qt::DisplayRole).toString(); if (!text.isEmpty()) { int alignment = !icon.isNull() ? Qt::AlignBottom | Qt::AlignHCenter : Qt::AlignCenter; painter->setFont(option.font); style->drawItemText(painter, r, alignment, option.palette, true, text); } painter->restore(); } }; public: IconListWidget(QWidget* parent = 0): QListWidget(parent) { setItemDelegate(new ItemDelegate(this)); } virtual QStyleOptionViewItem viewOptions() const { #if (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)) QStyleOptionViewItem opt(QListWidget::viewOptions()); #else QStyleOptionViewItem opt; QListWidget::initViewItemOption(&opt); #endif opt.displayAlignment = Qt::AlignCenter; opt.decorationAlignment = Qt::AlignCenter; opt.decorationPosition = QStyleOptionViewItem::Top; opt.font.setBold(true); return opt; } }; } // namespace ScIDE
3,306
C++
.h
70
39.457143
119
0.681394
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
34,254
popup_widget.hpp
supercollider_supercollider/editors/sc-ide/widgets/util/popup_widget.hpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include <QWidget> #include <QEventLoop> #include <QPointer> namespace ScIDE { class PopUpWidget : public QWidget { Q_OBJECT public: enum Result { Rejected = 0, Accepted }; public: explicit PopUpWidget(QWidget* parent = 0); virtual ~PopUpWidget(); int exec(const QRect& targetRect); void popup(const QRect& targetRect); void setTargetRect(const QRect& targetRect) { mTargetRect = targetRect; } public slots: void accept() { done(Accepted); } void reject() { done(Rejected); } void done(int result) { mResult = result; hide(); quit(); } signals: void finished(int result); private: void quit() { if (mEventLoop) { mEventLoop->exit(); mEventLoop = 0; } } protected: virtual void hideEvent(QHideEvent* e) { quit(); emit finished(mResult); } virtual void keyPressEvent(QKeyEvent* ke); virtual void showEvent(QShowEvent*); private: QEventLoop* mEventLoop; int mResult; QRect mTargetRect; }; } // namespace ScIDE
1,937
C++
.h
61
26.836066
81
0.697361
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,255
color_widget.hpp
supercollider_supercollider/editors/sc-ide/widgets/util/color_widget.hpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include <QLabel> #include <QColorDialog> #include <QPainter> namespace ScIDE { class ColorWidget : public QLabel { Q_OBJECT public: ColorWidget(QWidget* parent = 0): QLabel(parent) { setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); } void setColor(const QColor& color) { mBrush.setColor(color); mBrush.setStyle(Qt::SolidPattern); update(); emit colorChanged(mBrush.color()); emit brushChanged(mBrush); } void setBrush(const QBrush& brush) { mBrush = brush; update(); emit colorChanged(mBrush.color()); emit brushChanged(mBrush); } QColor color() const { return mBrush.color(); } QBrush brush() const { return mBrush; } public slots: void clear() { setBrush(QBrush()); } signals: void colorChanged(const QColor&); void brushChanged(const QBrush&); void colorPicked(const QColor&); protected: virtual void mouseReleaseEvent(QMouseEvent*) { QColor c = QColorDialog::getColor(color(), this); if (c.isValid()) { setColor(c); emit colorPicked(c); } } virtual void paintEvent(QPaintEvent*) { QBrush brush = mBrush; if (brush.style() == Qt::NoBrush) { brush.setColor(palette().color(QPalette::WindowText)); brush.setStyle(Qt::BDiagPattern); } QPainter painter(this); painter.setBrush(brush); painter.setPen(palette().color(QPalette::WindowText)); painter.drawRect(rect().adjusted(0, 0, -1, -1)); } private: QBrush mBrush; }; } // namespace ScIDE
2,488
C++
.h
69
30.072464
119
0.67945
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,256
multi_splitter.hpp
supercollider_supercollider/editors/sc-ide/widgets/util/multi_splitter.hpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include <QSplitter> #include "../multi_editor.hpp" namespace ScIDE { class MultiEditor; class MultiSplitter : public QSplitter { public: explicit MultiSplitter(MultiEditor* editor, QWidget* parent = 0): QSplitter(parent), mEditor(editor) { setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); } MultiEditor* editor() { return mEditor; } void insertWidget(QWidget* widget, QWidget* neighbour, Qt::Orientation direction) { if (!neighbour || !widgetIsChild(neighbour)) { qWarning("MultiSplitter: neighbour widget invalid"); return; } QSplitter* parentSplitter = parentSplitterOf(neighbour); Q_ASSERT(parentSplitter); int posInParent = parentSplitter->indexOf(neighbour); Q_ASSERT(posInParent != -1); if (parentSplitter->orientation() == direction) { parentSplitter->insertWidget(posInParent + 1, widget); } else if (parentSplitter->count() < 2) { parentSplitter->setOrientation(direction); parentSplitter->addWidget(widget); } else { // store parent's current distribution: QList<int> parentsSizes = parentSplitter->sizes(); QSplitter* splitter = new QSplitter(direction); // move the neighbour to the new splitter, and add the new widget: splitter->addWidget(neighbour); splitter->addWidget(widget); // insert the new splitter at the neighbour's old position: parentSplitter->insertWidget(posInParent, splitter); // restore parent's old distribution, affected by operations above: parentSplitter->setSizes(parentsSizes); // change the parent to the new splitter, for operations below: parentSplitter = splitter; } setEqualSizes(parentSplitter); } void removeWidget(QWidget* widget) { if (!widget || !widgetIsChild(widget)) { qWarning("MultiSplitter: widget invalid"); return; } QSplitter* parent = parentSplitterOf(widget); if (parent == this && parent->count() < 2) { qWarning("MultiSplitter: can not remove last widget"); return; } delete widget; Q_ASSERT(parent->count()); if (parent->count() == 1) { QWidget* neighbour = parent->widget(0); if (parent != this) { // replace parent splitter with it's only child QSplitter* grandParent = parentSplitterOf(parent); QList<int> grandParentsSizes = grandParent->sizes(); int posInParent = grandParent->indexOf(parent); Q_ASSERT(posInParent != -1); grandParent->insertWidget(posInParent, neighbour); delete parent; grandParent->setSizes(grandParentsSizes); } else { // replace child splitter with it's own children QSplitter* splitter = qobject_cast<QSplitter*>(neighbour); if (splitter) { QList<int> childSizes = splitter->sizes(); Qt::Orientation childOrientation = splitter->orientation(); int childCount = splitter->count(); while (childCount--) parent->addWidget(splitter->widget(0)); // 0 is always another widget delete splitter; parent->setOrientation(childOrientation); parent->setSizes(childSizes); } } } } template <typename T> T* findChild() { return MultiSplitter::findChild<T>(this); } private: template <typename T> static T* findChild(QSplitter* splitter) { int childCount = splitter->count(); for (int idx = 0; idx < childCount; ++idx) { QWidget* child = splitter->widget(idx); T* typedChild = qobject_cast<T*>(child); if (typedChild) return typedChild; QSplitter* childSplitter = qobject_cast<QSplitter*>(child); if (childSplitter) { typedChild = findChild<T>(childSplitter); if (typedChild) return typedChild; } } return 0; } QSplitter* parentSplitterOf(QWidget* widget) { return qobject_cast<QSplitter*>(widget->parent()); } void setEqualSizes(QSplitter* splitter) { int widgetCount = splitter->count(); int splitterSize = splitter->orientation() == Qt::Horizontal ? splitter->size().width() : splitter->size().height(); QList<int> newWidgetSizes; int singleWidgetSize = splitterSize / widgetCount; for (int idx = 0; idx < widgetCount; ++idx) newWidgetSizes << singleWidgetSize; splitter->setSizes(newWidgetSizes); } bool widgetIsChild(QWidget* widget) { QObject* object = widget->parent(); while (object) { if (object == this) return true; object = object->parent(); } return false; } MultiEditor* mEditor; }; } // namespace ScIDE
6,083
C++
.h
137
34.021898
109
0.615099
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,257
docklet.hpp
supercollider_supercollider/editors/sc-ide/widgets/util/docklet.hpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include <QAction> #include <QDockWidget> #include <QMouseEvent> #include <QToolButton> #include <QWidget> namespace ScIDE { class DockletToolButton : public QToolButton { Q_OBJECT public: explicit DockletToolButton(QWidget* parent = nullptr); private: // overrides to hide unwanted effects void mouseDoubleClickEvent(QMouseEvent* event) override final; void mousePressEvent(QMouseEvent* event) override final; }; class DockletToolBar : public QWidget { Q_OBJECT public: DockletToolBar(const QString& title); void addAction(QAction* action); void addWidget(QWidget* widget, int stretch = 0); QMenu* optionsMenu() { return mOptionsMenu; } protected: virtual void paintEvent(QPaintEvent* event); QMenu* mOptionsMenu; }; class Docklet : public QObject { Q_OBJECT public: Docklet(const QString& title, QWidget* parent = 0); QDockWidget* dockWidget() { return mDockWidget; } QWidget* window() { return mWindow; } QWidget* widget() { return mWidget; } DockletToolBar* toolBar() { return mToolBar; } QAction* toggleViewAction() { return mVisibilityAction; } bool isDetached() const { return const_cast<Docklet*>(this)->currentContainer() != mDockWidget; } void setDetachedAndVisible(bool detached, bool visible); bool isVisible() const { return const_cast<Docklet*>(this)->currentContainer()->isVisible(); } void setWidget(QWidget* widget) { mWidget = widget; if (!isDetached()) mDockWidget->setWidget(widget); } void setAllowedAreas(Qt::DockWidgetAreas areas) { mDockWidget->setAllowedAreas(areas); } void setFeatures(QDockWidget::DockWidgetFeatures features) { mDockWidget->setFeatures(features); } void setObjectName(const QString& name) { QObject::setObjectName(name); mDockWidget->setObjectName(name); } QByteArray saveDetachedState() const; void restoreDetachedState(const QByteArray&); public slots: void toggleFloating(); void toggleDetached(); void setVisible(bool visible) { QWidget* container = currentContainer(); container->setVisible(visible); if (visible) container->raise(); } void show() { setVisible(true); } void hide() { setVisible(false); } void close() { hide(); } void raise() { currentContainer()->raise(); } void focus() { show(); raise(); mWidget->setFocus(); mWidget->activateWindow(); } private slots: void onFeaturesChanged(QDockWidget::DockWidgetFeatures features); void updateDockAction(); protected: virtual bool eventFilter(QObject* object, QEvent* event); private: enum ContainerType { DockableContainer, WindowContainer }; QWidget* currentContainer() { return mToolBar->parentWidget(); } void setCurrentContainer(ContainerType); QDockWidget* mDockWidget; QWidget* mWindow; QWidget* mWidget; DockletToolBar* mToolBar; QAction* mDockAction; QAction* mDetachAction; QAction* mVisibilityAction; QRect mUndockedGeom; }; } // namespace ScIDE
3,971
C++
.h
106
32.537736
102
0.721367
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,258
gui_utilities.hpp
supercollider_supercollider/editors/sc-ide/widgets/util/gui_utilities.hpp
/* SuperCollider Qt IDE Copyright (c) 2012-2013 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include <QPlainTextEdit> #include <QRegularExpression> #include <QTextBlock> namespace ScIDE { // match words, environment variable and symbols inline QString tokenInStringAt(int position, const QString& source) { const QRegularExpression wordRegexp("(~?|\\\\?)\\w+"); int offset = 0; while (offset <= position) { QRegularExpressionMatch match = wordRegexp.match(source, offset); if (!match.hasMatch()) break; int index = match.capturedStart(); int len = match.capturedLength(); if (index <= position && index + len >= position) return match.captured(0); offset = index + len; } return QString(); } inline void extendSelectionForEnvVar(QPlainTextEdit* textEdit, QTextCursor selection) { if (selection.hasSelection()) { if (selection.selectedText() == QStringLiteral("~")) { QTextCursor wordAfter(selection); wordAfter.movePosition(QTextCursor::NextCharacter); wordAfter.select(QTextCursor::WordUnderCursor); if (wordAfter.hasSelection() && (selection.block() == wordAfter.block())) { selection.setPosition(selection.selectionStart()); selection.setPosition(wordAfter.selectionEnd(), QTextCursor::KeepAnchor); textEdit->setTextCursor(selection); } } else { int positionBeforeSelection = selection.selectionStart() - 1; if (positionBeforeSelection >= 0) { QChar charBeforeSelection = textEdit->document()->characterAt(positionBeforeSelection); if (charBeforeSelection == QChar('~')) { QTextCursor extendedSelection = textEdit->textCursor(); extendedSelection.setPosition(positionBeforeSelection); extendedSelection.setPosition(selection.selectionEnd(), QTextCursor::KeepAnchor); textEdit->setTextCursor(extendedSelection); } } } } } QRect fittedToScreen(const QRect& rect, QWidget* referenceWidget); } // namespace ScIDE
2,983
C++
.h
64
38.3125
103
0.67562
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
34,259
volume_widget.hpp
supercollider_supercollider/editors/sc-ide/widgets/util/volume_widget.hpp
/* SuperCollider Qt IDE Copyright (c) 2013 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include <QWidget> class QLabel; class QSlider; namespace ScIDE { class VolumeWidget : public QWidget { Q_OBJECT public: explicit VolumeWidget(QWidget* parent = 0); public slots: void setVolumeRange(float min, float max); void setVolume(float volume); signals: void volumeChangeRequested(float volume); private slots: void onVolumeSliderAction(); private: int volumeToSlider(float volume); float volumeFromSlider(int slider); bool eventFilter(QObject*, QEvent*); QLabel* mVolumeLabel; QSlider* mVolumeSlider; float mVolumeMin = -10000, mVolumeMax = 10000; }; } // namespace ScIDE
1,490
C++
.h
41
32.439024
81
0.75523
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,260
line_indicator.hpp
supercollider_supercollider/editors/sc-ide/widgets/code_editor/line_indicator.hpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include <QWidget> namespace ScIDE { class LineIndicator : public QWidget { Q_OBJECT public: LineIndicator(class GenericCodeEditor* editor); void setHideLineIndicator(bool hide); Q_SIGNALS: void widthChanged(); public Q_SLOTS: void setLineCount(int); protected: virtual void paintEvent(QPaintEvent* e); virtual void mousePressEvent(QMouseEvent*); virtual void mouseMoveEvent(QMouseEvent*); virtual void mouseDoubleClickEvent(QMouseEvent*); virtual void changeEvent(QEvent*); private: int widthForLineCount(int lineCount); class GenericCodeEditor* mEditor; int mLineCount; int mLastCursorPos; bool hideLineIndicator; }; }
1,540
C++
.h
42
32.619048
81
0.761777
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,261
editor.hpp
supercollider_supercollider/editors/sc-ide/widgets/code_editor/editor.hpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include <QPlainTextEdit> #include <QGraphicsScene> #include <QList> #include <QRegularExpression> namespace ScIDE { namespace Settings { class Manager; } class Document; class OverlayAnimator; class GenericCodeEditor : public QPlainTextEdit { Q_OBJECT friend class LineIndicator; friend class OverlayAnimator; public: GenericCodeEditor(Document*, QWidget* parent = NULL); ~GenericCodeEditor(); // Rule of 5 -- with an explicit dtor, make sure that copy ctor/assign and move // ctor/assign are deleted. // If these must be implemented in the future, make sure they take care of // mDoc->lastActiveEditor() appropriately. See source of dtor method. GenericCodeEditor(const GenericCodeEditor& other) = delete; GenericCodeEditor& operator=(const GenericCodeEditor& other) = delete; GenericCodeEditor(GenericCodeEditor&& other) = delete; GenericCodeEditor& operator=(GenericCodeEditor&& other) = delete; Document* document() { return mDoc; } QTextDocument* textDocument() { return QPlainTextEdit::document(); } bool showWhitespace(); bool showLinenumber(); bool find(const QRegularExpression& expr, QTextDocument::FindFlags options); bool replace(const QRegularExpression& expr, const QString& replacement, QTextDocument::FindFlags options); int findAll(const QRegularExpression& expr, QTextDocument::FindFlags options); int replaceAll(const QRegularExpression& expr, const QString& replacement, QTextDocument::FindFlags options); void showPosition(int charPosition, int selectionLength = 0); QString symbolUnderCursor(); int inactiveFadeAlpha() { return mInactiveFadeAlpha; } protected: virtual bool event(QEvent*); virtual void keyPressEvent(QKeyEvent*); virtual void keyReleaseEvent(QKeyEvent*); void doKeyAction(QKeyEvent*); virtual void mousePressEvent(QMouseEvent*); virtual void mouseDoubleClickEvent(QMouseEvent*); virtual void mouseReleaseEvent(QMouseEvent*); virtual void wheelEvent(QWheelEvent*); virtual void dragEnterEvent(QDragEnterEvent*); virtual void focusInEvent(QFocusEvent*); virtual void focusOutEvent(QFocusEvent*); void hideMouseCursor(QKeyEvent*); virtual QMimeData* createMimeDataFromSelection() const; public slots: void applySettings(Settings::Manager*); void closeDocument(); void zoomIn(int steps = 1); void zoomOut(int steps = 1); void resetFontSize(); void setShowWhitespace(bool); void setShowLinenumber(bool); void clearSearchHighlighting(); void toggleOverwriteMode(); void copyLineUp(); void copyLineDown(); void moveLineUp(); void moveLineDown(); void deleteWord(); void gotoPreviousEmptyLine(); void gotoNextEmptyLine(); void setActiveAppearance(bool active); void updateDocLastSelection(); protected slots: void updateLayout(); void updateLineIndicator(QRect, int); void onDocumentFontChanged(); void onCursorPositionChanged(); protected: void resizeEvent(QResizeEvent*); void paintLineIndicator(QPaintEvent*); virtual void paintEvent(QPaintEvent*); virtual void updateExtraSelections(); void updateCurrentLineHighlighting(); virtual void indentCurrentRegion() {} void zoomFont(int steps); void copyUpDown(bool up); void moveLineUpDown(bool up); void gotoEmptyLineUpDown(bool up); void hideMouseCursor(); void updateFocusRect(); class LineIndicator* mLineIndicator; QGraphicsScene* mOverlay; QWidget* mOverlayWidget; OverlayAnimator* mOverlayAnimator; // If this "const" is removed in the future, make sure to handle mDoc->lastActiveEditor() // correctly (see source of dtor method for this class). Document* const mDoc; bool mHighlightCurrentLine; bool mEditorBoxIsActive; int mLastCursorBlock; QTextCharFormat mCurrentLineTextFormat; QTextCharFormat mSearchResultTextFormat; QList<QTextEdit::ExtraSelection> mSearchSelections; QGraphicsRectItem* mFocusRect = 0; int mInactiveFadeAlpha = 0; private: void handleKeyDown(QKeyEvent* event, QTextCursor& textCursor); void handleKeyUp(QKeyEvent* event, QTextCursor& textCursor); void handleKeyDelete(QKeyEvent* event, QTextCursor& textCursor); void handleKeyRightParentheses(QKeyEvent* event, QTextCursor& textCursor); void handleKeyBackspace(QKeyEvent* event, QTextCursor& textCursor, bool& updateCursor); }; } // namespace ScIDE
5,353
C++
.h
127
37.598425
113
0.762656
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
34,262
autocompleter.hpp
supercollider_supercollider/editors/sc-ide/widgets/code_editor/autocompleter.hpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include <QObject> #include <QTextDocument> #include <QStack> #include <QKeyEvent> #include <QStringList> #include <QPointer> #include "tokens.hpp" #include "completion_menu.hpp" #include "SCDoc/SCDoc.h" namespace ScIDE { class ScCodeEditor; class TokenIterator; class MethodCallWidget; namespace ScLanguage { struct Method; struct Class; } class AutoCompleter : public QObject { Q_OBJECT public: AutoCompleter(ScCodeEditor*); void keyPress(QKeyEvent*); void documentChanged(QTextDocument*); // NOTE: default 'force' to true in the following methods // for the purpose of argument-less QAction::triggered() signal: void triggerCompletion(bool forceShow = true); void triggerMethodCallAid(bool explicitly = true); private slots: void onContentsChange(int pos, int removed, int added); void onCursorChanged(); void onCompletionMenuFinished(int result); void updateCompletionMenuInfo(); void clearMethodCallStack(); void hideWidgets(); void gotoHelp(QString symbol); private: friend class MethodCallWidget; struct MethodCall { MethodCall(): position(0), method(0), functionalNotation(false), suppressed(false) {} int position; const ScLanguage::Method* method; bool functionalNotation; bool suppressed; }; enum CompletionType { ClassCompletion, ClassMethodCompletion, MethodCompletion, InvalidCompletion }; struct CompletionDescription { bool on; CompletionType type; int pos; int len; int contextPos; QString base; QString text; QPointer<CompletionMenu> menu; Token::Type tokenType; }; struct MethodCallContext { QStack<MethodCall> stack; QPointer<CompletionMenu> menu; QPointer<MethodCallWidget> widget; }; typedef QStack<MethodCall>::iterator MethodCallIterator; bool eventFilter(QObject*, QEvent*); QTextDocument* document(); // completion void quitCompletion(const QString& reason = QString()); void showCompletionMenu(bool forceShow); void updateCompletionMenu(bool forceShow); // method call aid const ScLanguage::Method* disambiguateMethod(const QString& methodName, int cursorPos); void updateMethodCall(int cursorPos); void pushMethodCall(const MethodCall& call); void showMethodCall(const MethodCall& call, int arg = 0); void hideMethodCall(); bool trySwitchMethodCallArgument(bool backwards = false); bool testMethodCall(const MethodCall&, int cursorPos, int& argNum, TokenIterator& argNameToken, bool strict = false); static CompletionMenu* menuForClassCompletion(CompletionDescription const& completion, ScCodeEditor* editor); static CompletionMenu* menuForClassMethodCompletion(CompletionDescription const& completion, ScCodeEditor* editor); static CompletionMenu* menuForMethodCompletion(CompletionDescription const& completion, ScCodeEditor* editor); static const ScLanguage::Class* classForToken(Token::Type type, const QString& string); // utilities QString tokenText(TokenIterator& it); QRect globalCursorRect(int cursorPosition); static QString findHelpClass(QString klass); static DocNode* parseHelpClass(QString file); static QString parseClassElement(DocNode* node, QString element); static void parseClassNode(DocNode* node, QString* str); // data ScCodeEditor* mEditor; CompletionDescription mCompletion; MethodCallContext mMethodCall; }; } // namespace ScIDE
4,435
C++
.h
111
34.801802
119
0.747378
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,263
sc_editor.hpp
supercollider_supercollider/editors/sc-ide/widgets/code_editor/sc_editor.hpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include "editor.hpp" #include "tokens.hpp" #include "../core/settings/theme.hpp" #include <QTextBlock> #include <utility> namespace ScIDE { typedef std::pair<TokenIterator, TokenIterator> BracketPair; class ScCodeEditor : public GenericCodeEditor { Q_OBJECT public: /** \brief Used to indicate whether an edit action should start a new edit * block, which affects undo/redo operation grouping. */ enum EditBlockMode { NewEditBlock, ///< Start a new edit block. JoinEditBlock ///< Join this edit to the previous one. }; public: static TokenIterator previousOpeningBracket(TokenIterator it); static TokenIterator nextClosingBracket(TokenIterator it); static void matchBracket(const TokenIterator& bracket, BracketPair& match); static void nextBracketPair(const TokenIterator& startIt, BracketPair& bracketPair); public: ScCodeEditor(Document*, QWidget* parent = 0); QTextCursor currentRegion(); void blinkCode(const QTextCursor& c); bool spaceIndent() { return mSpaceIndent; } public slots: void applySettings(Settings::Manager*); void setSpaceIndent(bool on) { mSpaceIndent = on; } /// Indents the currently-selected text. void indent(EditBlockMode = NewEditBlock); void triggerAutoCompletion(); void triggerMethodCallAid(); void toggleComment(); void gotoPreviousBlock(); void gotoNextBlock(); void selectBlockAroundCursor(); void selectCurrentRegion(); void gotoNextRegion(); void gotoPreviousRegion(); bool openDocumentation(); void openDefinition(); void openCommandLine(); void findReferences(); void evaluateLine(); void evaluateRegion(); void evaluateDocument(); protected: virtual bool event(QEvent*); virtual void keyPressEvent(QKeyEvent*); virtual void mouseReleaseEvent(QMouseEvent*); virtual void mouseDoubleClickEvent(QMouseEvent*); virtual void mouseMoveEvent(QMouseEvent*); virtual void dragEnterEvent(QDragEnterEvent*); virtual bool canInsertFromMimeData(const QMimeData* data) const; virtual void insertFromMimeData(const QMimeData* data); private slots: void matchBrackets(); private: QTextCursor cursorAt(const TokenIterator, int offset = 0); QTextCursor selectionForPosition(int position); QTextCursor regionAroundCursor(const QTextCursor&); QTextCursor blockAroundCursor(const QTextCursor&); void moveToNextToken(QTextCursor&, QTextCursor::MoveMode); void moveToPreviousToken(QTextCursor&, QTextCursor::MoveMode); void updateExtraSelections(); void indentCurrentRegion(); void toggleCommentSingleLine(QTextCursor); void toggleCommentSingleLine(); void toggleCommentSelection(); void addSingleLineComment(QTextCursor, int indentationLevel); void removeSingleLineComment(QTextCursor); /** \brief Returns the index of the first non-whitespace character in * \c block, or <tt>block.text().size()</tt> if the block is all whitespace. */ int indentedStartOfLine(const QTextBlock& block); /// Indents the text in \c selection according to editor preferences. void indent(const QTextCursor& selection, EditBlockMode = NewEditBlock); /** \brief Indents a line to a chosen level of indentation. * * \param block The line to indent. * \param level The level of indentation. * \return A new \c QTextBlock indented to the requested level. */ QTextBlock indent(const QTextBlock& block, int level); /** \brief Creates a string of indentation characters acccording to * editor preferences. * * \param level The indentation level. */ QString makeIndentationString(int level); /** \brief Get the indentation level for the cursor's selection start. * * \param cursor A cursor in the document. * \return The number of levels of indentation there should be for * the line where the \c cursor's selection starts, or -1 on failure. */ int indentationLevel(const QTextCursor& cursor); /** \brief Inserts enough whitespace at \c cursor to reach the next * tab stop according to editor preferences. */ void insertSpaceToNextTabStop(QTextCursor& cursor); bool insertMatchingTokens(const QString& token); bool removeMatchingTokens(); // Data members /// If \c true, use spaces to indent. bool mSpaceIndent; bool mStepForwardEvaluation; int mBlinkDuration; bool mInsertMatchingTokens; QTextCharFormat mBracketHighlight; QTextCharFormat mBracketMismatchFormat; bool mHighlightBracketContents; QList<QTextEdit::ExtraSelection> mBracketSelections; bool mMouseBracketMatch; class AutoCompleter* mAutoCompleter; }; } // namespace ScIDE
5,639
C++
.h
136
36.602941
88
0.746435
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,264
overlay.hpp
supercollider_supercollider/editors/sc-ide/widgets/code_editor/overlay.hpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include <QGraphicsPixmapItem> #include <QPropertyAnimation> namespace ScIDE { class GenericCodeEditor; class OverlayAnimator : public QObject { Q_OBJECT Q_PROPERTY(QColor backgroundColor READ backgroundColor WRITE setBackgroundColor); QColor backgroundColor() const; void setBackgroundColor(const QColor& color); public: OverlayAnimator(GenericCodeEditor* editor, QObject* parent = 0); void setActiveAppearance(bool active); private: GenericCodeEditor* mEditor; QPropertyAnimation mBackgroundAnimation; }; class CodeFragmentOverlay : public QObject, public QGraphicsPixmapItem { Q_OBJECT Q_PROPERTY(qreal opacity READ opacity WRITE setOpacity) Q_PROPERTY(qreal scale READ scale WRITE setScale) }; } // namespace ScIDE
1,622
C++
.h
39
37.717949
85
0.777212
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
34,265
highlighter.hpp
supercollider_supercollider/editors/sc-ide/widgets/code_editor/highlighter.hpp
/* SuperCollider Qt IDE Copyright (c) 2012 Jakob Leben & Tim Blechmann http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #pragma once #include "../../core/sc_lexer.hpp" #include <QSyntaxHighlighter> #include <QVector> namespace ScIDE { namespace Settings { class Manager; class Theme; } class Main; enum SyntaxFormat { WhitespaceFormat, PlainFormat, ClassFormat, KeywordFormat, BuiltinFormat, PrimitiveFormat, SymbolFormat, StringFormat, CharFormat, NumberFormat, EnvVarFormat, CommentFormat, FormatCount }; class SyntaxHighlighterGlobals : public QObject { Q_OBJECT public: SyntaxHighlighterGlobals(Main*, Settings::Manager* settings); inline const QTextCharFormat* formats() const { return mFormats; } inline const QTextCharFormat& format(SyntaxFormat type) const { return mFormats[type]; } inline static const SyntaxHighlighterGlobals* instance() { Q_ASSERT(mInstance); return mInstance; } public Q_SLOTS: void applySettings(Settings::Manager*); Q_SIGNALS: void syntaxFormatsChanged(); private: friend class SyntaxHighlighter; void applySettings(Settings::Manager* s, const QString& key, SyntaxFormat); QTextCharFormat mFormats[FormatCount]; static SyntaxHighlighterGlobals* mInstance; }; class SyntaxHighlighter : public QSyntaxHighlighter { Q_OBJECT public: SyntaxHighlighter(QTextDocument* parent = 0); private: void highlightBlock(const QString& text) override; void highlightBlockInCode(ScLexer& lexer); void highlightBlockInString(ScLexer& lexer); void highlightBlockInSymbol(ScLexer& lexer); void highlightBlockInComment(ScLexer& lexer); const SyntaxHighlighterGlobals* mGlobals; }; }
2,483
C++
.h
74
29.432432
92
0.760705
supercollider/supercollider
5,424
745
915
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false