repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
avinash-palleti/libigb
igb_internal.h
/****************************************************************************** Copyright (c) 2001-2016, Intel Corporation All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the Intel Corporation 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. ******************************************************************************/ /*$FreeBSD$*/ #ifndef _IGB_INTERNAL_H_DEFINED_ #define _IGB_INTERNAL_H_DEFINED_ #include "igb.h" /* * Micellaneous constants */ #define IGB_VENDOR_ID 0x8086 #define IGB_DEFAULT_PBA 0x00000030 #define PCI_ANY_ID (~0U) #define ETHER_ALIGN 2 #define IGB_TX_BUFFER_SIZE ((uint32_t) 1514) #define IGB_RX_PTHRESH 8 #define IGB_RX_HTHRESH 8 #define IGB_RX_WTHRESH 4 #define IGB_TX_PTHRESH 8 #define IGB_TX_HTHRESH 1 #define IGB_TX_WTHRESH 16 /* * TDBA/RDBA should be aligned on 16 byte boundary. But TDLEN/RDLEN should be * multiple of 128 bytes. So we align TDBA/RDBA on 128 byte boundary. This will * also optimize cache line size effect. H/W supports up to cache line size 128. */ #define IGB_DBA_ALIGN 128 #define SPEED_MODE_BIT (1<<21) /* On PCI-E MACs only */ #define IGB_MAX_SCATTER 64 #define IGB_VFTA_SIZE 128 #define IGB_BR_SIZE 4096 /* ring buf size */ #define IGB_TSO_SIZE (65535 + sizeof(struct ether_vlan_header)) #define IGB_TSO_SEG_SIZE 4096 /* Max dma segment size */ #define IGB_HDR_BUF 128 #define IGB_PKTTYPE_MASK 0x0000FFF0 #define ETH_ZLEN 60 #define ETH_ADDR_LEN 6 /* Queue bit defines */ #define IGB_QUEUE_IDLE 1 #define IGB_QUEUE_WORKING 2 #define IGB_QUEUE_HUNG 4 #define IGB_QUEUE_DEPLETED 8 /* * This parameter controls when the driver calls the routine to reclaim * transmit descriptors. Cleaning earlier seems a win. **/ #define IGB_TX_CLEANUP_THRESHOLD (adapter->num_tx_desc / 2) #define IGB_QUEUE_THRESHOLD (2) /* Precision Time Sync (IEEE 1588) defines */ #define ETHERTYPE_IEEE1588 0x88F7 #define PICOSECS_PER_TICK 20833 #define TSYNC_PORT 319 /* UDP port for the protocol */ struct igb_tx_buffer { int next_eop; /* Index of the desc to watch */ struct igb_packet *packet; /* app-relevant handle */ }; /* * Transmit ring: one per queue */ struct tx_ring { struct adapter *adapter; u32 me; struct resource txdma; struct e1000_tx_desc *tx_base; struct igb_tx_buffer *tx_buffers; u32 next_avail_desc; u32 next_to_clean; u16 tx_avail; u32 bytes; u32 packets; int tdt; int tdh; u64 no_desc_avail; u64 tx_packets; int queue_status; }; struct igb_rx_buffer { int next_eop; /* Index of the desc to watch */ struct igb_packet *packet; /* app-relevant handle */ }; /* * Receive ring: one per queue */ struct rx_ring { struct adapter *adapter; u32 me; struct resource rxdma; union e1000_adv_rx_desc *rx_base; bool hdr_split; u32 next_to_refresh; u32 next_to_check; struct igb_rx_buffer *rx_buffers; u32 bytes; u32 packets; int rdt; int rdh; /* Soft stats */ u64 rx_split_packets; u64 rx_discarded; u64 rx_packets; u64 rx_bytes; sem_t lock; }; struct adapter { struct e1000_hw hw; pthread_mutex_t *memlock; int ldev; /* file descriptor to igb */ struct resource csr; int max_frame_size; int min_frame_size; int igb_insert_vlan_header; u16 num_queues; /* Interface queues */ struct igb_queue *queues; /* * rings */ struct tx_ring *tx_rings; u16 num_tx_desc; struct rx_ring *rx_rings; u16 num_rx_desc; #ifdef IGB_IEEE1588 /* IEEE 1588 precision time support */ struct cyclecounter cycles; struct nettimer clock; struct nettime_compare compare; struct hwtstamp_ctrl hwtstamp; #endif int active; }; /* * vendor_info_array * * This array contains the list of Subvendor/Subdevice IDs on which the driver * should load. * */ typedef struct _igb_vendor_info_t { unsigned int vendor_id; unsigned int device_id; unsigned int subvendor_id; unsigned int subdevice_id; unsigned int index; } igb_vendor_info_t; /* external API requirements */ #define IGB_BIND _IOW('E', 200, int) #define IGB_UNBIND _IOW('E', 201, int) #define IGB_MAPRING _IOW('E', 202, int) #define IGB_MAP_TX_RING IGB_MAPRING #define IGB_UNMAPRING _IOW('E', 203, int) #define IGB_UNMAP_TX_RING IGB_UNMAPRING #define IGB_MAPBUF _IOW('E', 204, int) #define IGB_UNMAPBUF _IOW('E', 205, int) #define IGB_LINKSPEED _IOW('E', 206, int) #define IGB_MAP_RX_RING _IOW('E', 207, int) #define IGB_UNMAP_RX_RING _IOW('E', 208, int) /*set of newly defined ioctl calls - new libigb compatibility each of them is an equivalent of the old ioctl changed numberiong convention: new_ioctl = old_ioctl + 100*/ #define IGB_IOCTL_MAPRING _IOW('E', 302, int) #define IGB_IOCTL_MAP_TX_RING IGB_IOCTL_MAPRING #define IGB_IOCTL_UNMAPRING _IOW('E', 303, int) #define IGB_IOCTL_UNMAP_TX_RING IGB_IOCTL_UNMAPRING #define IGB_IOCTL_MAPBUF _IOW('E', 304, int) #define IGB_IOCTL_UNMAPBUF _IOW('E', 305, int) #define IGB_IOCTL_MAP_RX_RING _IOW('E', 307, int) #define IGB_IOCTL_UNMAP_RX_RING _IOW('E', 308, int) /*END*/ #define IGB_BIND_NAMESZ 24 struct igb_bind_cmd { char iface[IGB_BIND_NAMESZ]; unsigned mmap_size; }; struct igb_buf_cmd { u_int64_t physaddr; /* dma_addr_t is 64-bit */ unsigned int queue; unsigned int mmap_size; u_int64_t pa; }; struct igb_link_cmd { u_int32_t up; /* dma_addr_t is 64-bit */ u_int32_t speed; u_int32_t duplex; }; #endif /* _IGB_H_DEFINED_ */
avinash-palleti/libigb
igb.h
/****************************************************************************** Copyright (c) 2001-2016, Intel Corporation All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the Intel Corporation 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. ******************************************************************************/ /*$FreeBSD$*/ #ifndef _IGB_H_DEFINED_ #define _IGB_H_DEFINED_ #include <sys/types.h> struct resource { u_int64_t paddr; u_int32_t mmap_size; }; /* datastructure used to transmit a timed packet */ #define IGB_PACKET_LAUNCHTIME 1 /* control when packet transmitted */ #define IGB_PACKET_LATCHTIME 2 /* grab a timestamp of transmission */ struct igb_packet { struct resource map; /* bus_dma map for packet */ unsigned int offset; /* offset into physical page */ void *vaddr; u_int32_t len; u_int32_t flags; u_int64_t attime; /* launchtime */ u_int64_t dmatime; /* when dma tx desc wb*/ struct igb_packet *next; /* used in the clean routine */ }; typedef struct _device_t { void *private_data; u_int16_t pci_vendor_id; u_int16_t pci_device_id; u_int16_t domain; u_int8_t bus; u_int8_t dev; u_int8_t func; } device_t; /* * Bus dma allocation structure used by * e1000_dma_malloc_page and e1000_dma_free_page. */ struct igb_dma_alloc { u_int64_t dma_paddr; void *dma_vaddr; unsigned int mmap_size; }; int igb_probe(device_t *dev); int igb_attach(char *dev_path, device_t *pdev); int igb_attach_rx(device_t *pdev); int igb_attach_tx(device_t *pdev); int igb_detach(device_t *dev); int igb_suspend(device_t *dev); int igb_resume(device_t *dev); int igb_init(device_t *dev); int igb_dma_malloc_page(device_t *dev, struct igb_dma_alloc *page); void igb_dma_free_page(device_t *dev, struct igb_dma_alloc *page); int igb_xmit(device_t *dev, unsigned int queue_index, struct igb_packet *packet); int igb_refresh_buffers(device_t *dev, u_int32_t idx, struct igb_packet **rxbuf_packets, u_int32_t num_bufs); int igb_receive(device_t *dev, unsigned int queue_index, struct igb_packet **received_packets, u_int32_t *count); void igb_clean(device_t *dev, struct igb_packet **cleaned_packets); int igb_get_wallclock(device_t *dev, u_int64_t *curtime, u_int64_t *rdtsc); int igb_gettime(device_t *dev, clockid_t clk_id, u_int64_t *curtime, struct timespec *system_time); int igb_set_class_bandwidth(device_t *dev, u_int32_t class_a, u_int32_t class_b, u_int32_t tpktsz_a, u_int32_t tpktsz_b); int igb_set_class_bandwidth2(device_t *dev, u_int32_t class_a_bytes_per_second, u_int32_t class_b_bytes_per_second); int igb_setup_flex_filter(device_t *dev, unsigned int queue_id, unsigned int filter_id, unsigned int filter_len, u_int8_t *filter, u_int8_t *mask); int igb_clear_flex_filter(device_t *dev, unsigned int filter_id); void igb_trigger(device_t *dev, u_int32_t data); void igb_readreg(device_t *dev, u_int32_t reg, u_int32_t *data); void igb_writereg(device_t *dev, u_int32_t reg, u_int32_t data); int igb_lock(device_t *dev); int igb_unlock(device_t *dev); int igb_get_mac_addr(device_t *dev, u_int8_t mac_addr[6]); #endif /* _IGB_H_DEFINED_ */
geekyUtkarsh99/Lost_Space
app/src/main/java/com/example/lostspace/apple.h
// // Created by WINDOWS10 on 25-May-20. // #ifndef LOST_SPACE_APPLE_H #define LOST_SPACE_APPLE_H class apple { private : void a(){ cout<< "gba"; } }; void main (){ cout<< "hello"; apple a; a.a; } #endif //LOST_SPACE_APPLE_H
Kumassy/wireshark-dissector-rs
dissector/plugins/dummy/packet-dummy.h
<gh_stars>10-100 /* packet-dummy.h * Definitions for fake dummy protocol * By <NAME> <<EMAIL>> * Part of github.com/sevagh/wireshark-dissector-rs */
Kumassy/wireshark-dissector-rs
epan-rs/wrapper.h
<gh_stars>10-100 #include <config.h> #include <epan/dissectors/packet-tcp.h> #include <epan/dissectors/packet-udp.h> #include <epan/packet.h> #include <epan/tvbuff-int.h> #include <epan/tvbuff.h> #include <wiretap/wtap.h> #include <glib.h>
Kumassy/wireshark-dissector-rs
dissector/plugins/dummy/packet-dummy.c
<filename>dissector/plugins/dummy/packet-dummy.c #include "config.h" #include <epan/dissectors/packet-tcp.h> #include <epan/packet.h> #include <epan/tvbuff-int.h> #include <epan/tvbuff.h> #include <wiretap/wtap.h> #include <glib.h> #include <stdint.h> #include <stdio.h> #include "./packet-dummy.h" #define DUMMY_PORT 8888 static int proto_dummy = -1; static gint ett_dummy = -1; static int hf_dummy_version = -1; static int hf_dummy_body = -1; static int dissect_dummy(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data); extern int32_t dissect_dummy_rs(const void *data); void proto_register_dummy(void); void proto_reg_handoff_dummy(void); static int dissect_dummy(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void *data) { ((void)data); // suppress compile warning. col_set_str(pinfo->cinfo, COL_PROTOCOL, "DUMMY"); col_clear(pinfo->cinfo, COL_INFO); dissect_dummy_rs(tvb->real_data); gint offset = 0; if (tree) { proto_item *ti; ti = proto_tree_add_item(tree, proto_dummy, tvb, 0, -1, FALSE); tree = proto_item_add_subtree(ti, ett_dummy); proto_tree_add_item(tree, hf_dummy_version, tvb, offset, 8, FT_STRING); offset += 8; proto_tree_add_item(tree, hf_dummy_body, tvb, offset, 8, FT_STRING); } return tvb_captured_length(tvb); } void proto_register_dummy(void) { static int *ett[] = {&ett_dummy}; proto_dummy = proto_register_protocol("Dummy Protocol", /* name */ "DUMMY", /* short name */ "dummy" /* abbrev */ ); static hf_register_info hf[] = { {&hf_dummy_version, {"Version", "dummy.version", FT_STRING, BASE_NONE, NULL, 0x0, NULL, HFILL}}, {&hf_dummy_body, {"Body", "dummy.body", FT_STRING, BASE_NONE, NULL, 0x0, NULL, HFILL}}, }; proto_register_field_array(proto_dummy, hf, array_length(hf)); proto_register_subtree_array(ett, array_length(ett)); } void proto_reg_handoff_dummy(void) { static dissector_handle_t dummy_handle; dummy_handle = create_dissector_handle(dissect_dummy, proto_dummy); dissector_add_uint_with_preference("tcp.port", DUMMY_PORT, dummy_handle); }
SashaBorisov/CppWinApi
iface/Utils/CountOf.h
<gh_stars>0 #pragma once // // Copyright © 2021, <NAME>, https://github.com/SashaBorisov/CppWinApi // #include <compare> #include <type_traits> #include <iterator> namespace Utils { template<typename T> struct CountOf; template<typename T> struct DiffOf { using Type = T; constexpr DiffOf() noexcept = default; constexpr DiffOf(const DiffOf&) noexcept = default; constexpr DiffOf& operator = (const DiffOf&) noexcept = default; constexpr auto operator <=> (const DiffOf& other) const noexcept = default; explicit constexpr operator ptrdiff_t () const noexcept { return value; } constexpr DiffOf operator - () const noexcept { return DiffOf{-value}; } constexpr DiffOf operator - (const DiffOf other) const noexcept { return DiffOf{value - other.value}; } constexpr DiffOf& operator -= (const DiffOf other) noexcept { value -= other.value; return *this; } constexpr DiffOf operator + (const DiffOf other) const noexcept { return DiffOf{value + other.value}; } constexpr DiffOf& operator += (const DiffOf other) noexcept { value += other.value; return *this; } template<typename N> requires std::is_arithmetic_v<N> constexpr DiffOf operator * (const N number) const noexcept { return DiffOf{value * number}; } template<typename N> requires std::is_arithmetic_v<N> constexpr DiffOf& operator *= (const N number) noexcept { value *= number; return *this; } template<typename N> requires std::is_arithmetic_v<N> constexpr DiffOf operator / (const N number) const noexcept { return DiffOf{value / number}; } template<typename N> requires std::is_arithmetic_v<N> constexpr DiffOf& operator /= (const N number) noexcept { value /= number; return *this; } template<typename N> requires std::is_integral_v<N> constexpr DiffOf operator % (const N number) const noexcept { return DiffOf{value % number}; } template<typename N> requires std::is_integral_v<N> constexpr DiffOf& operator %= (const N number) noexcept { value %= number; return *this; } private: friend struct CountOf<T>; template<typename T> friend constexpr DiffOf<std::byte> offsetOf(const DiffOf<T> offset) noexcept; constexpr DiffOf(const ptrdiff_t v) noexcept: value{v} {} ptrdiff_t value = 0; }; template<typename T> struct CountOf { using Type = T; constexpr CountOf() noexcept = default; constexpr CountOf(const CountOf&) noexcept = default; constexpr CountOf& operator = (const CountOf&) noexcept = default; constexpr auto operator <=> (const CountOf& other) const noexcept = default; explicit constexpr operator size_t () const noexcept { return value; } constexpr DiffOf<T> operator - (const CountOf other) const noexcept { return DiffOf<T>{static_cast<ptrdiff_t>(value) - static_cast<ptrdiff_t>(other.value)}; } constexpr CountOf operator - (const DiffOf<T> diff) const noexcept { return CountOf{static_cast<size_t>(static_cast<ptrdiff_t>(value) - diff.value)}; } constexpr CountOf& operator -= (const DiffOf<T> diff) noexcept { value = static_cast<size_t>(static_cast<ptrdiff_t>(value) - diff.value); return *this; } constexpr CountOf operator + (const DiffOf<T> diff) const noexcept { return CountOf{value + diff.value}; } constexpr CountOf& operator += (const DiffOf<T> diff) noexcept { value = static_cast<size_t>(static_cast<ptrdiff_t>(value) + diff.value); return *this; } // constexpr CountOf operator + (const CountOf other) const noexcept // { // return CountOf{value + other.value}; // } // constexpr CountOf& operator += (const CountOf other) noexcept // { // value += other.value; // return *this; // } template<typename N> requires std::is_arithmetic_v<N> constexpr CountOf operator * (const N number) const noexcept { return DiffOf{value * number}; } template<typename N> requires std::is_arithmetic_v<N> constexpr CountOf operator / (const N number) const noexcept { return DiffOf{value / number}; } private: template<typename T> friend constexpr CountOf<std::byte> sizeOf() noexcept; template <typename C> friend constexpr CountOf<typename C::value_type> countOf(const C& container); template <typename T, size_t value> friend constexpr CountOf<T> countOf(const T (&)[value]) noexcept; template<typename T> friend constexpr CountOf<std::byte> sizeOf(const CountOf<T> count) noexcept; template <typename I> friend constexpr CountOf<typename std::iterator_traits<I>::value_type> countOf(const I& begin, const I& end); template <typename T> friend constexpr CountOf<T> countOf(const CountOf<std::byte> size) noexcept; constexpr CountOf(const size_t v) noexcept : value{v}{} size_t value = 0; }; // struct CountOf using OffsetOfBytes = DiffOf<std::byte>; using CountOfBytes = CountOf<std::byte>; template<typename T> constexpr CountOfBytes sizeOf() noexcept { return CountOfBytes{sizeof(T)}; } template<typename T> constexpr CountOfBytes sizeOf(T&) noexcept { return sizeOf<T>(); } constexpr auto OneByte = Utils::sizeOf<std::byte>() - CountOfBytes{}; template<typename T> constexpr OffsetOfBytes offsetOf(const DiffOf<T> offset) noexcept { return OffsetOfBytes{static_cast<ptrdiff_t>(sizeof(T)) * offset.value}; } template<typename T> constexpr CountOfBytes sizeOf(const CountOf<T> count) noexcept { return CountOfBytes{sizeof(T) * count.value}; } template <typename C> constexpr CountOf<typename C::value_type> countOf(const C& container) { return CountOf<typename C::value_type>{container.size()}; } template <typename T, size_t value> constexpr CountOf<T> countOf(const T (&)[value]) noexcept { return CountOf<T>{value}; } template <typename I> constexpr CountOf<typename std::iterator_traits<I>::value_type> countOf(const I& begin, const I& end) { const auto value = static_cast<size_t>(std::distance(begin, end)); return CountOf<typename std::iterator_traits<I>::value_type>{value}; } template <typename T> constexpr CountOf<T> countOf(const CountOfBytes size) noexcept { return CountOf<T>{size.value / sizeof(T)}; } template <typename T> constexpr CountOfBytes tailOf(const CountOf<T> count) noexcept { return CountOfBytes{sizeOf(count).value % sizeof(T)}; } }
SashaBorisov/CppWinApi
iface/WinApi/IO/File.h
#pragma once // // Copyright © 2021, <NAME>, https://github.com/SashaBorisov/CppWinApi // #include <type_traits> #include <filesystem> #include <optional> #include <WinApi/Handle.h> #include <Utils/Mask.h> #include <Utils/CountOf.h> namespace WinApi::IO { using Utils::Flag; using Utils::Mask; using Utils::DiffOf; using Utils::CountOf; using Utils::OffsetOfBytes; using Utils::CountOfBytes; using Utils::OneByte; // // FILE_GENERIC_READ; enum class DesiredAccess: DWORD { GenericAll = GENERIC_ALL , GenericExecute = GENERIC_EXECUTE , GenericRead = GENERIC_READ , GenericWrite = GENERIC_WRITE , GenericReadWrite = GENERIC_READ | GENERIC_WRITE }; struct ShareFlag { using Type = DWORD; static constexpr auto None = Flag<0, ShareFlag>{}; static constexpr auto Delete = Flag<FILE_SHARE_DELETE, ShareFlag>{}; static constexpr auto Read = Flag<FILE_SHARE_READ , ShareFlag>{}; static constexpr auto Write = Flag<FILE_SHARE_WRITE , ShareFlag>{}; }; using ShareMask = Utils::Mask<ShareFlag>; enum class CreateMode: DWORD { CreateAlways = CREATE_ALWAYS , CreateNew = CREATE_NEW , OpenAlways = OPEN_ALWAYS , OpenExisting = OPEN_EXISTING , TruncateExisting = TRUNCATE_EXISTING }; struct FileFlag { using Type = DWORD; static constexpr auto Archive = Flag<FILE_ATTRIBUTE_ARCHIVE , FileFlag>{}; static constexpr auto Encripted = Flag<FILE_ATTRIBUTE_ENCRYPTED, FileFlag>{}; static constexpr auto Hidden = Flag<FILE_ATTRIBUTE_HIDDEN , FileFlag>{}; static constexpr auto Normal = Flag<FILE_ATTRIBUTE_NORMAL , FileFlag>{}; static constexpr auto Offline = Flag<FILE_ATTRIBUTE_OFFLINE , FileFlag>{}; static constexpr auto ReadOnly = Flag<FILE_ATTRIBUTE_READONLY , FileFlag>{}; static constexpr auto System = Flag<FILE_ATTRIBUTE_SYSTEM , FileFlag>{}; static constexpr auto Temporary = Flag<FILE_ATTRIBUTE_TEMPORARY, FileFlag>{}; static constexpr auto BackupSematics = Flag<FILE_FLAG_BACKUP_SEMANTICS , FileFlag>{}; static constexpr auto DeleteOnClose = Flag<FILE_FLAG_DELETE_ON_CLOSE , FileFlag>{}; static constexpr auto NoBuffering = Flag<FILE_FLAG_NO_BUFFERING , FileFlag>{}; static constexpr auto OpenNoRecall = Flag<FILE_FLAG_OPEN_NO_RECALL , FileFlag>{}; static constexpr auto OpenReparsePoint = Flag<FILE_FLAG_OPEN_REPARSE_POINT, FileFlag>{}; static constexpr auto Overllaped = Flag<FILE_FLAG_OVERLAPPED , FileFlag>{}; static constexpr auto PosixSematics = Flag<FILE_FLAG_POSIX_SEMANTICS , FileFlag>{}; static constexpr auto RandomAccess = Flag<FILE_FLAG_RANDOM_ACCESS , FileFlag>{}; static constexpr auto SessionName = Flag<FILE_FLAG_SESSION_AWARE , FileFlag>{}; static constexpr auto SequentalScan = Flag<FILE_FLAG_SEQUENTIAL_SCAN , FileFlag>{}; static constexpr auto WriteThrough = Flag<FILE_FLAG_WRITE_THROUGH , FileFlag>{}; }; using FileMask = Mask<FileFlag>; template<DesiredAccess desiredAccess> auto createFile( const std::filesystem::path & path , const ShareMask shareMode , const CreateMode creationDisposition , const FileMask flags ) { const HANDLE handle = ::CreateFileW ( path.c_str() , static_cast<DWORD>(desiredAccess) , static_cast<DWORD>(shareMode) , NULL //securityAttributes , static_cast<DWORD>(creationDisposition) , static_cast<DWORD>(flags) , NULL //templateFile ); auto close = [](const HANDLE handle) { ::CloseHandle(handle); }; using FileHandle = Handle<decltype(close)>; if(handle == INVALID_HANDLE_VALUE) { return Maybe<FileHandle>{OccurredError{}}; } return Maybe<FileHandle>{FileHandle{handle, std::move(close)}}; } template<DesiredAccess desiredAccess> using MaybeFile = decltype(createFile<desiredAccess>( std::filesystem::path{} , ShareFlag::None , CreateMode::CreateAlways , FileFlag::Normal )); template<DesiredAccess desiredAccess> using File = typename MaybeFile<desiredAccess>::Type; using FileAccessAll = File<DesiredAccess::GenericAll>; using FileAccessExecute = File<DesiredAccess::GenericExecute>; using FileAccessRead = File<DesiredAccess::GenericRead>; using FileAccessWrite = File<DesiredAccess::GenericWrite>; using FileAccessReadWrite = File<DesiredAccess::GenericReadWrite>; template<typename File> concept IsItFile = std::is_same_v<File, FileAccessAll> || std::is_same_v<File, FileAccessExecute> || std::is_same_v<File, FileAccessRead> || std::is_same_v<File, FileAccessWrite> || std::is_same_v<File, FileAccessReadWrite>; template<typename File> concept IsFileAllowRead = std::is_same_v<File, FileAccessAll> || std::is_same_v<File, FileAccessRead> || std::is_same_v<File, FileAccessReadWrite>; template<typename File> concept IsFileAllowWrite = std::is_same_v<File, FileAccessAll> || std::is_same_v<File, FileAccessWrite> || std::is_same_v<File, FileAccessReadWrite>; template<typename File> concept IsFileAllowReadWrite = std::is_same_v<File, FileAccessAll> || std::is_same_v<File, FileAccessRead> || std::is_same_v<File, FileAccessWrite> || std::is_same_v<File, FileAccessReadWrite>; template<typename File> constexpr DesiredAccess fileAccess() noexcept { if constexpr (std::is_same_v<File, FileAccessAll>) { return DesiredAccess::GenericAll; } else if constexpr (std::is_same_v<File, FileAccessRead>) { return DesiredAccess::GenericRead; } else if constexpr (std::is_same_v<File, FileAccessWrite>) { return DesiredAccess::GenericWrite; } else if constexpr (std::is_same_v<File, FileAccessReadWrite>) { return DesiredAccess::GenericReadWrite; } else if constexpr (true) { static_assert(false, ""); } } template<typename F> constexpr DesiredAccess fileAccess(const F&) noexcept { return fileAccess<F>(); } template<typename F> void closeFile(F& file) requires IsItFile<F> { file = nullptr; } enum class FilePointerFrom: DWORD { Begin = FILE_BEGIN , Current = FILE_CURRENT , End = FILE_END }; template<typename F, typename I> requires IsFileAllowReadWrite<F> Maybe<CountOf<I>> setFilePointer( const F& file , const DiffOf<I> offset , const FilePointerFrom from = FilePointerFrom::Begin ) { const LARGE_INTEGER distance{.QuadPart = static_cast<ptrdiff_t>(Utils::offsetOf(offset))}; LARGE_INTEGER newPointer{}; const bool succeed = FALSE != ::SetFilePointerEx ( file.get() , distance , &newPointer , static_cast<DWORD>(from) ); if(!succeed) { return OccurredError{}; } const CountOfBytes position = CountOfBytes{} + OneByte * newPointer.QuadPart; return Utils::countOf<I>(position); } template<typename F> Maybe<CountOfBytes> getFilePointer(const F& file) { return setFilePointer(file, OffsetOfBytes{}, FilePointerFrom::Current); } template<typename F> requires IsFileAllowReadWrite<F> Maybe<void> setFilePointerToBegin(const F& file) { return setFilePointer(file, OffsetOfBytes{}, FilePointerFrom::Begin); } template<typename F> Maybe<void> setFilePointerToEnd(const F& file) { return static_cast<bool>(setFilePointer(file, OffsetOfBytes{}, FilePointerFrom::End)); } template<typename Handle, typename I> requires IsFileAllowRead<Handle> && std::is_trivially_copyable_v<I> CountOf<I> fileRead(const Handle& file, I * const buffer_begin, const I * const buffer_end) { CountOfBytes totalBytes{}; const auto begin = reinterpret_cast<std::byte * >(buffer_begin); const auto end = reinterpret_cast<const std::byte * >(buffer_end); for(std::byte * position = begin; position < end;) { DWORD actuallyRead = 0u; const BOOL succedded = ::ReadFile ( file.get() , reinterpret_cast<void * >(position) , static_cast<DWORD>(end - position) , &actuallyRead , nullptr ); if(succedded && 0u == actuallyRead) { break; // end of file } position += actuallyRead; totalBytes += OneByte * actuallyRead; if(!succedded) { break; } } return Utils::countOf<I>(totalBytes); } template<typename Handle, typename V> requires IsFileAllowRead<Handle> && std::is_trivially_copyable_v<V> CountOf<V> fileReadValue(const Handle& file, V& value) { DWORD actuallyRead = 0u; ::ReadFile ( file.get() , reinterpret_cast<void*>(&value) , static_cast<DWORD>(sizeof(value)) , &actuallyRead , nullptr ); return Utils::countOf<V>(CountOfBytes{} + OneByte * actuallyRead); } template<typename Handle, typename C> auto fileReadData(const Handle& file, C& container) { const auto begin = std::data(container); const auto end = begin + std::size(container); return fileRead(file, begin, end); } template<typename F, typename I> requires IsFileAllowWrite<F> && std::is_trivially_copyable_v<I> CountOf<I> fileWrite(const F& file, const I * const buffer_begin, const I * const buffer_end) { CountOfBytes totalBytes; const auto begin = reinterpret_cast<const std::byte * >(buffer_begin); const auto end = reinterpret_cast<const std::byte * >(buffer_end); for(const std::byte * position = begin; position < end;) { DWORD written = 0u; const BOOL succedded = ::WriteFile ( file.get() , reinterpret_cast<const void * >(position) , static_cast<DWORD>(end - position) , &written , nullptr ); position += written; totalBytes += OneByte * written; if(!succedded) { break; } } return Utils::countOf<I>(totalBytes); } template<typename F, typename V> requires IsFileAllowWrite<F> && std::is_trivially_copyable_v<V> CountOf<V> fileWriteValue(const F& file, const V& value) { DWORD written = 0u; ::WriteFile ( file.get() , reinterpret_cast<const void *>(value) , static_cast<DWORD>(sizeof(value)) , &written , nullptr ); return Utils::countOf<V>(CountOfBytes{} + OneByte * written); } template<typename Handle, typename C> auto fileWriteData(const Handle& file, const C& container) { const auto begin = std::data(container); const auto end = begin + std::size(container); return fileWrite(file, begin, end); } }
SashaBorisov/CppWinApi
iface/WinApi/Heap.h
<reponame>SashaBorisov/CppWinApi<gh_stars>0 #pragma once // // Copyright © 2021, <NAME>, https://github.com/SashaBorisov/CppWinApi // #include <WinApi/Common.h> #include <WinApi/Handle.h> #include <heapapi.h> #include <Utils/CountOf.h> namespace WinApi { using Utils::DiffOf; using Utils::CountOf; using Utils::OffsetOfBytes; using Utils::CountOfBytes; using Utils::OneByte; struct HeapFlags { static constexpr DWORD EnableExecute = HEAP_CREATE_ENABLE_EXECUTE; static constexpr DWORD GenerateExceptions = HEAP_GENERATE_EXCEPTIONS; static constexpr DWORD NoSerialize = HEAP_NO_SERIALIZE; template<DWORD Flags> static constexpr bool valid() noexcept { return Flags == (Flags & (EnableExecute | GenerateExceptions | NoSerialize)); } }; template<DWORD Flags> concept IsValidHeapFlags = Flags == (Flags & ( HeapFlags::EnableExecute | HeapFlags::GenerateExceptions | HeapFlags::NoSerialize)); template<DWORD F, typename U, typename C> struct Heap //: public Handle<C> { // using Base = typename Handle<C>; static constexpr DWORD Flags = F; using Type = U; Handle<C> handle; }; template<DWORD Flags, typename T = std::byte> requires IsValidHeapFlags<Flags> auto createHeap( const CountOf<T> initialCount = CountOf<T>{} , const CountOf<T> maxCount = CountOf<T>{}) { const CountOfBytes initialSize = Utils::sizeOf(initialCount); const CountOfBytes maxSize = Utils::sizeOf(maxCount); const HANDLE handle = ::HeapCreate ( Flags , static_cast<size_t>(initialSize) , static_cast<size_t>(maxSize) ); auto destroy = [](const HANDLE handle) { if(handle) { ::HeapDestroy(handle); } }; using ResultHeap = Heap<Flags, T, decltype(destroy)>; if(!handle) { return Maybe<ResultHeap>{OccurredError{}}; } return Maybe<ResultHeap>{ResultHeap{{handle, std::move(destroy)}}}; } template<DWORD Flags, typename T> using MaybeHeap = decltype(createHeap<Flags, T>()); template<DWORD Flags, typename T> using HeapTag = typename MaybeHeap<Flags, T>::Type::deleter_type; template<DWORD Flags, typename T, typename C, typename ...A> requires IsValidHeapFlags<Flags> auto heapEmplace(const Heap<Flags, T, C>& heap, A&&... args) { const auto size = Utils::sizeOf<T>(); auto destructor = [heap = heap.handle.get()](T* const instance) { instance->~T(); ::HeapFree(heap, 0, instance); }; using Instance = std::unique_ptr<T, decltype(destructor)>; const auto pointer = ::HeapAlloc(heap.handle.get(), 0, static_cast<size_t>(size)); if constexpr(Flags & HeapFlags::GenerateExceptions) { auto holder = makeHandle(pointer, [heap = heap.handle.get()](void* const pointer) { ::HeapFree(heap, pointer); }); T* const instance = new(pointer) T{std::move(args)...}; holder.detach(); return Instance{instance, std::move(destructor)}; } else { if(!pointer) { return Maybe<Instance>{OccurredError{}}; } auto holder = safeHandle(pointer, [heap = heap.handle.get()](void* const pointer) { ::HeapFree(heap, 0, pointer); }); T* const instance = new(pointer) T{std::move(args)...}; holder.release(); return Maybe<Instance>{Instance{instance, std::move(destructor)}}; } } } // namespace WinApi
SashaBorisov/CppWinApi
iface/WinApi/Handle.h
#pragma once // // Copyright © 2021, <NAME>, https://github.com/SashaBorisov/CppWinApi // #include <WinApi/Common.h> #include <winnt.h> #include <memory> #include <Utils/Flag.h> namespace WinApi { template<typename C> using Handle = std::unique_ptr<void, C>; template<typename C> Handle<C> safeHandle(const HANDLE asset, C&& close) noexcept { return Handle<C>(asset, std::move(close)); } using AlertableFlag = Utils::Flag<true, UNIQUE_TAG>; constexpr auto Alertable = AlertableFlag{}; enum class WaitStatus: DWORD { Abandoned = WAIT_ABANDONED , IoCompletion = WAIT_IO_COMPLETION , Object0 = WAIT_OBJECT_0 , Timeout = WAIT_TIMEOUT }; template<typename C> Maybe<WaitStatus> waitFor( const Handle<C>& handle , const Milliseconds timeout = Infinite , const AlertableFlag alertable = !Alertable ) { const DWORD status = ::WaitForSingleObjectEx ( handle.get() , timeout.count() , alertable == Alertable ? TRUE : FALSE ); if(status == WAIT_FAILED) { return OccurredError{}; } return static_cast<WaitStatus>(status); } }
SashaBorisov/CppWinApi
iface/Utils/Flag.h
<reponame>SashaBorisov/CppWinApi<filename>iface/Utils/Flag.h<gh_stars>0 #pragma once // // Copyright © 2021, <NAME>, https://github.com/SashaBorisov/CppWinApi // namespace Utils { #define UNIQUE_TAG decltype([](){}) template<auto V, typename Tag> struct Flag { using Type = decltype(V); constexpr Flag() noexcept = default; constexpr Flag(const Flag&) noexcept = default; constexpr Flag& operator = (const Flag&) noexcept = default; constexpr bool operator == (const Flag other) const noexcept { return value == other.value; } constexpr bool operator != (const Flag other) const noexcept { return value != other.value; } constexpr Flag operator ~ () const noexcept { static_assert(!std::is_same_v<bool, Type>); return Flag{~value}; } constexpr Flag operator ! () const noexcept { static_assert(std::is_same_v<bool, Type>); return Flag{!value}; } private: template<typename E> friend class Mask; constexpr Flag(const Type v): value{v} {} Type value = V; }; }
SashaBorisov/CppWinApi
iface/WinApi/Sync/Event.h
#pragma once // // Copyright © 2021, <NAME>, https://github.com/SashaBorisov/CppWinApi // #include <WinApi/Common.h> #include <WinApi/Handle.h> #include <Utils/Flag.h> #include <synchapi.h> namespace WinApi::Sync { enum class EventReset: BOOL { Manual = TRUE , Auto = FALSE }; constexpr EventReset operator ! (const EventReset mode) noexcept { return mode == EventReset::Manual ? EventReset::Auto : EventReset::Manual; } using EventState = Utils::Flag<true, UNIQUE_TAG>; static constexpr auto EventSignaled = EventState{}; template<EventReset Mode> auto createEvent( const EventState initial = !EventSignaled , const StringView& name = {} ) { const HANDLE handle = ::CreateEvent ( nullptr , Mode == EventReset::Manual , initial == EventSignaled ? TRUE : FALSE , name.data() ); auto event = safeHandle(handle, [](const HANDLE handle) { if(handle) { ::CloseHandle(handle); } }); using Result = decltype(event); if(!event) { return Maybe<Result>{OccurredError{}}; } return Maybe<Result>{std::move(event)}; } template<EventReset mode> using MaybeEvent = decltype(createEvent<mode>(EventSignaled, StringView{})); template<EventReset mode> using Event = typename MaybeEvent<mode>::Type; using ManualEvent = Event<EventReset::Manual>; using AutoEvent = Event<EventReset::Auto>; template<typename E> concept IsItEvent = std::is_same_v<E, ManualEvent> || std::is_same_v<E, AutoEvent>; static Maybe<ManualEvent> createManualEvent( const EventState initial = !EventSignaled , const StringView& name = {}) { return createEvent<EventReset::Manual>(initial, name); } static Maybe<AutoEvent> createAutoEvent( const EventState initial = !EventSignaled , const StringView& name = {}) { return createEvent<EventReset::Auto>(initial, name); } template<typename E> requires IsItEvent<E> Maybe<void> setEvent(const E& event) { if(FALSE != ::SetEvent(event.get())) { return {}; } return OccurredError{}; } template<typename E> requires IsItEvent<E> Maybe<void> resetEvent(const E& event) { if(FALSE != ::ResetEvent(event.get())) { return {}; } return OccurredError{}; } } // namespace WinApi
SashaBorisov/CppWinApi
iface/WinApi/Common.h
<gh_stars>0 #pragma once // // Copyright © 2021, <NAME>, https://github.com/SashaBorisov/CppWinApi // #include <windows.h> #include <tchar.h> #include <string> #include <string_view> #include <chrono> #include <format> #include <system_error> namespace WinApi { using String = std::basic_string<TCHAR>; using StringView = std::basic_string_view<TCHAR>; using Milliseconds = std::chrono::duration<DWORD, std::milli>; static constexpr auto Infinite = Milliseconds{INFINITE}; static std::error_code lastErrorCode() { const DWORD code = ::GetLastError(); return std::error_code{static_cast<int>(code), std::system_category()}; } static std::string lastErrorMessage() { const DWORD code = ::GetLastError(); return std::system_category().message(static_cast<int>(code)); } struct OccurredError { OccurredError() noexcept = default; constexpr OccurredError(const OccurredError&) noexcept = default; constexpr OccurredError& operator = (const OccurredError&) noexcept = default; constexpr bool operator == (const OccurredError other) const noexcept { return value == other.value; } std::error_code code() const noexcept { return std::error_code{static_cast<int>(value), std::system_category()}; } std::string message() const { return std::system_category().message(static_cast<int>(value)); } private: template<typename T> friend struct Maybe; struct Empty{}; constexpr OccurredError(Empty) noexcept : value{0u} {} DWORD value = ::GetLastError(); }; // struct OccurredError template<typename T> struct Maybe { using Type = T; constexpr Maybe() = delete; constexpr Maybe(const Maybe&) = delete; constexpr Maybe(Maybe&&) noexcept(std::is_nothrow_move_constructible_v<T>) = default; constexpr Maybe(const OccurredError lastError) noexcept(noexcept(std::is_nothrow_default_constructible<T>)) : error{lastError} {} constexpr Maybe(T&& value) noexcept(std::is_nothrow_move_constructible_v<T>) : asset{std::move(value)} {} constexpr OccurredError code() const noexcept { return error; } std::string message() const { return error.message(); } constexpr bool okay() const noexcept { return NoError == error; } template<typename ...A> const T& unWrap(A&&... args) const & { throwIfWrong(std::move(args)...); return asset; } template<typename ...A> T&& unWrap(A&&... args) && { throwIfWrong(std::move(args)...); return std::move(asset); } const T& value() const & { throwIfWrong(); return asset; } T& value() & { throwIfWrong(); return asset; } T&& value() && { throwIfWrong(); return std::move(asset); } private: template<typename ...A> void throwIfWrong(A&&... args) const { if(!okay()) { std::string message = std::format(std::move(args)...); throw std::system_error{error.code(), std::move(message)}; } } void throwIfWrong() const { if(!okay()) { throw std::system_error{error.code()}; } } static constexpr auto NoError = OccurredError{OccurredError::Empty{}}; OccurredError error = NoError; T asset; }; // struct Maybe template<> struct Maybe<void> { using Type = void; constexpr Maybe() noexcept = default; constexpr Maybe(Maybe&&) noexcept = default; constexpr Maybe(const OccurredError lastError) noexcept : error{lastError} {} template<typename U> constexpr Maybe(Maybe<U>&& copy) noexcept : Maybe{copy.code()} {} constexpr OccurredError code() const noexcept { return error; } std::string message() const { return error.message(); } constexpr bool okay() const noexcept { return NoError == error; } template<typename ...A> void unWrap(A&&... args) const { throwIfWrong(std::move(args)...); } void value() const { throwIfWrong(); } private: template<typename ...A> void throwIfWrong(A&&... args) const { if(!okay()) { std::string message = std::format(std::move(args)...); throw std::system_error{error.code(), std::move(message)}; } } void throwIfWrong() const { if(!okay()) { throw std::system_error{error.code()}; } } static constexpr auto NoError = OccurredError{OccurredError::Empty{}}; OccurredError error = NoError; }; // struct Maybe<void> } // namespace WinApi
SashaBorisov/CppWinApi
iface/Utils/Mask.h
<gh_stars>0 #pragma once // // Copyright © 2021, <NAME>, https://github.com/SashaBorisov/CppWinApi // #include <type_traits> #include <Utils/Flag.h> namespace Utils { template<typename E> class Mask { public: using Enum = E; using Type = typename Enum::Type; template<auto V> constexpr Mask(const Flag<V,Enum> flag) noexcept : value{cast(flag)} {} constexpr Mask() noexcept = delete; constexpr Mask(const Mask& other) noexcept = default; constexpr Mask& operator = (const Mask& other) noexcept = default; constexpr bool operator == (const Mask other) const noexcept { return value == other.value; } constexpr bool operator != (const Mask other) const noexcept { return value != other.value; } explicit constexpr operator Type() const noexcept { return value; } private: constexpr Mask(Type v) noexcept : value{v} {} template<auto V> static constexpr Type cast(const Flag<V,Enum> flag) noexcept { return static_cast<Type>(flag.value); } Type value; public: constexpr inline Mask& operator &= (Mask other) noexcept { value &= other.value; return *this; } constexpr inline Mask& operator |= (Mask other) noexcept { value |= other.value; return *this; } constexpr inline Mask& operator ^= (Mask other) noexcept { value ^= other.value; return *this; } template<auto V> constexpr inline Mask& operator &= (Flag<V,Enum> other) noexcept { value &= cast(other); return *this; } template<auto V> constexpr inline Mask& operator |= (Flag<V,Enum> other) noexcept { value |= cast(other); return *this; } template<auto V> constexpr inline Mask& operator ^= (Flag<V,Enum> other) noexcept { value ^= cast(other); return *this; } constexpr inline Mask operator | (Mask other) const noexcept { return {value | other.value}; } constexpr inline Mask operator ^ (Mask other) const noexcept { return {value ^ other.value}; } constexpr inline Mask operator & (Mask other) const noexcept { return {value & other.value}; } template<auto V> constexpr inline Mask operator ^ (Flag<V,Enum> other) const noexcept { return {value ^ cast(other)}; } template<auto V> constexpr inline Mask operator | (Flag<V,Enum> other) const noexcept { return {value | cast(other)}; } template<auto V> constexpr inline Mask operator & (Flag<V,Enum> other) const noexcept { return {value & cast(other)}; } constexpr inline Mask operator ~ () const noexcept { return {~value}; } constexpr inline void operator + (Mask other) const noexcept = delete; constexpr inline void operator + (Enum other) const noexcept = delete; constexpr inline void operator - (Mask other) const noexcept = delete; constexpr inline void operator - (Enum other) const noexcept = delete; }; template<typename E, auto L> constexpr Mask<E> operator & (const Flag<L,E> left, const Mask<E> right) noexcept { return Utils::Mask<E>{left} & right; } template<typename E, auto L> constexpr Mask<E> operator ^ (const Flag<L,E> left, const Mask<E> right) noexcept { return Utils::Mask<E>{left} ^ right; } template<typename E, auto L> constexpr Mask<E> operator | (const Flag<L,E> left, const Mask<E> right) noexcept { return Mask<E>{left} | right; } template<typename E, auto L, auto R> constexpr Mask<E> operator & (const Flag<L,E> left, const Flag<R,E> right) noexcept { return Mask<E>{left} & Mask<E>{right}; } template<typename E, auto L, auto R> constexpr Mask<E> operator ^ (const Flag<L,E> left, const Flag<R,E> right) noexcept { return Utils::Mask<E>{left} ^ Mask<E>{right}; } template<typename E, auto L, auto R> constexpr Mask<E> operator | (const Flag<L,E> left, const Flag<R,E> right) noexcept { return Mask<E>{left} | Mask<E>{right}; } } // namespace Utils
Aft3rmathpwnz/TimelyDemo
TimelyDemo/TimelyDemo/Views/TDSeparatorTableView.h
<gh_stars>0 // // TDSeparatorTableView.h // TimelyDemo // // Created by <NAME> on 16/01/2019. // Copyright © 2019 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN /** UITableView subclass bringing dotted separators for empty table space. */ @interface TDSeparatorTableView : UITableView @end NS_ASSUME_NONNULL_END
Aft3rmathpwnz/TimelyDemo
TimelyDemo/TimelyDemo/Views/Time Entry/TimeEntryTableViewCell.h
// // TimeEntryTableViewCell.h // TimelyDemo // // Created by <NAME> on 08/01/2019. // Copyright © 2019 <NAME>. All rights reserved. // @import UIKit; @class TimeEntryView; NS_ASSUME_NONNULL_BEGIN @interface TimeEntryTableViewCell : UITableViewCell /** Displays time entry view. @param timeEntryView View containing representations of total hours and earnings. */ - (void)setupTimeEntryView:(TimeEntryView *)timeEntryView; @end NS_ASSUME_NONNULL_END
Aft3rmathpwnz/TimelyDemo
TimelyDemo/TimelyDemo/Views/Time Entry/TimeEntryEditableView.h
<gh_stars>0 // // TimeEntryEditableView.h // TimelyDemo // // Created by <NAME> on 13/01/2019. // Copyright © 2019 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> @class TimeEntryViewData; NS_ASSUME_NONNULL_BEGIN @interface TimeEntryEditableView : UIView @property (assign, readonly, nonatomic) TimeEntryViewData *data; - (instancetype)initWithCoder:(NSCoder *)aDecoder __attribute((unavailable("Please use +entryWithData: instead."))); - (instancetype)initWithFrame:(CGRect)frame __attribute((unavailable("Please use +entryWithData: instead."))); - (instancetype)init __attribute((unavailable("Please use +entryWithData: instead."))); /** Creates view containing mutable time entry info. @param data Time entry view data containing info. @return Mutable time entry view filled with given data. */ + (instancetype)entryWithData:(TimeEntryViewData *)data; @end NS_ASSUME_NONNULL_END
Aft3rmathpwnz/TimelyDemo
TimelyDemo/TimelyDemo/Models/Time Entry/TimeEntryViewData.h
// // TimeEntryViewData.h // TimelyDemo // // Created by <NAME> on 08/01/2019. // Copyright © 2019 <NAME>. All rights reserved. // @import UIKit; @class TimeEntry; NS_ASSUME_NONNULL_BEGIN // In real project there may be a protocol to support modularity of data visual representation logic. @interface TimeEntryViewData : NSObject @property (copy, readonly, nonatomic) NSString *projectTitle; @property (copy, readonly, nonatomic) NSAttributedString *billedTimeAttributedString; @property (nullable, copy, readonly, nonatomic) NSString *plannedHoursString; @property (assign, readonly, nonatomic) float billedHours; @property (assign, readonly, nonatomic) float plannedHours; /** Maximum of billed and planned hours for time entry */ @property (assign, readonly, nonatomic) float maximumHours; @property (assign, readonly, nonatomic) NSString *spentTimeString; @property (assign, readonly, nonatomic) TimeEntry *timeEntry; - (instancetype)init __attribute((unavailable("Use -initWithTimeEntry: instead"))); - (instancetype)initWithTimeEntry:(TimeEntry *)timeEntry; - (instancetype)initWithProjectTitle:(nullable NSString *)projectTitle billedHoursAttributedString:(NSAttributedString *)billedHoursAttributedString; @end NS_ASSUME_NONNULL_END
Aft3rmathpwnz/TimelyDemo
TimelyDemo/TimelyDemo/Models/DayMenuViewData.h
<filename>TimelyDemo/TimelyDemo/Models/DayMenuViewData.h<gh_stars>0 // // DayMenuViewData.h // TimelyDemo // // Created by <NAME> on 12/01/2019. // Copyright © 2019 <NAME>. All rights reserved. // #import <Foundation/Foundation.h> @class TimeEntry; NS_ASSUME_NONNULL_BEGIN @interface DayMenuViewData : NSObject @property (copy, readonly, nonatomic) NSAttributedString *dateEarningsAttributedString; @property (copy, readonly, nonatomic) NSString *totalHoursString; - (instancetype)init __attribute((unavailable("Use -initWithTimeEntries: instead"))); /** Initializes model for day menu view that contains string representations of total hours and earnings. Should be used this one. @param timeEntries Time entries for one day. @return Day menu view model with calculated hours and earnings. */ - (instancetype)initWithTimeEntries:(nullable NSArray<TimeEntry *> *)timeEntries NS_DESIGNATED_INITIALIZER; @end NS_ASSUME_NONNULL_END
Aft3rmathpwnz/TimelyDemo
TimelyDemo/TimelyDemo/Helpers/XibView.h
// // XibView.h // TimelyDemo // // Created by <NAME> on 08/01/2019. // Copyright © 2019 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN /** Superclass for views with xib file. Their views must be connected to this class's view property. */ @interface XibView : UIView @end NS_ASSUME_NONNULL_END
Aft3rmathpwnz/TimelyDemo
TimelyDemo/TimelyDemo/Controllers/HoursViewController.h
<filename>TimelyDemo/TimelyDemo/Controllers/HoursViewController.h // // HoursViewController.h // TimelyDemo // // Created by <NAME> on 08/01/2019. // Copyright © 2019 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface HoursViewController : UIViewController @end NS_ASSUME_NONNULL_END
Aft3rmathpwnz/TimelyDemo
TimelyDemo/TimelyDemo/Services/PhotoCaptureService.h
<reponame>Aft3rmathpwnz/TimelyDemo // // PhotoCaptureService.h // TimelyDemo // // Created by Aft3rmath on 18/01/2019. // Copyright © 2019 <NAME>. All rights reserved. // @import Foundation; @import AVFoundation; NS_ASSUME_NONNULL_BEGIN @protocol PhotoCaptureServiceDelegate <NSObject> /** Called when camera captured image after -startImageCapturing: call. @param image Captured UIImage. */ - (void)didCaptureImage:(UIImage *)image; @end @interface PhotoCaptureService : NSObject @property (weak, nonatomic) id<PhotoCaptureServiceDelegate> delegate; @property (assign, nonatomic, readonly) BOOL isPermissionGranted; /** Starts camera capturing frames that are rendering on preview layer. @return Preview layer that displays current camera input. */ - (nullable AVCaptureVideoPreviewLayer *)startCamera; /** Stops camera from capturing frames. */ - (void)stopCamera; /** Captures image from camera frames asynchronously. Use -didCaptureImage: method of PhotoCaptureServiceDelegate to handle captured image. */ - (void)captureImage; @end NS_ASSUME_NONNULL_END
Aft3rmathpwnz/TimelyDemo
TimelyDemo/TimelyDemo/Views/DayMenuView.h
<filename>TimelyDemo/TimelyDemo/Views/DayMenuView.h // // DayMenuView.h // TimelyDemo // // Created by <NAME> on 12/01/2019. // Copyright © 2019 <NAME>. All rights reserved. // @import UIKit; #import "XibView.h" @class DayMenuViewData; NS_ASSUME_NONNULL_BEGIN @protocol DayMenuViewDelegate <NSObject> /** Called when the add button has been tapped. */ - (void)didTapAdd; @end @interface DayMenuView : XibView @property (weak, nonatomic, nullable) id<DayMenuViewDelegate> delegate; /** Displays current day's total hours, earnings and date. @param data Data containing string representations of total hours and earnings. */ - (void)setupWithData:(DayMenuViewData *)data; @end NS_ASSUME_NONNULL_END
Aft3rmathpwnz/TimelyDemo
TimelyDemo/TimelyDemo/Services/Network (Simulation)/TimeEntriesService.h
// // TimeEntriesService.h // TimelyDemo // // Created by <NAME> on 15/01/2019. // Copyright © 2019 <NAME>. All rights reserved. // #import <Foundation/Foundation.h> @class TimeEntry; NS_ASSUME_NONNULL_BEGIN /** Mock for network service, that would perform CRUD operations with TimeEntry entity using APIClient if there was one. */ @interface TimeEntriesService : NSObject - (void)asyncGetTimeEntriesWithCompletion:(nullable void (^)(NSArray<TimeEntry *> * _Nullable timeEntries, NSError * _Nullable error))completion; @end NS_ASSUME_NONNULL_END
Aft3rmathpwnz/TimelyDemo
TimelyDemo/TimelyDemo/Helpers/UIColor+Utils.h
// // UIColor+Hex.h // // Created by Aft3rmath on 09.05.17. // Copyright © 2017 aft3rmath. All rights reserved. // #import <UIKit/UIKit.h> @interface UIColor (Hex) + (UIColor *)colorwithHexString:(NSString *)hexStr; + (UIColor *)colorwithHexString:(NSString *)hexStr alpha:(CGFloat)alpha; @end @interface UIColor (LightAndDark) - (UIColor *)lighterColorByFactor:(CGFloat)factor; - (UIColor *)darkerColorByFactor:(CGFloat)factor; @end
Aft3rmathpwnz/TimelyDemo
TimelyDemo/TimelyDemo/Views/Time Entry/TimeEntryViewLayoutProtocol.h
// // TimeEntryViewLayoutProtocol.h // TimelyDemo // // Created by Aft3rmath on 18/01/2019. // Copyright © 2019 <NAME>. All rights reserved. // #import <Foundation/Foundation.h> NS_ASSUME_NONNULL_BEGIN @protocol TimeEntryViewLayoutProtocol <NSObject> /** Sets project and billed hours labels up for default state */ - (void)setupInitially; /** Sets project and billed hours labels constraints up for default state */ - (void)setupInitialConstraints; @optional /** Sets planned hours label related constraints up */ - (void)setupPlannedHoursConstraints; @end NS_ASSUME_NONNULL_END
Aft3rmathpwnz/TimelyDemo
TimelyDemo/TimelyDemo/Controllers/TimeEntriesViewController.h
<reponame>Aft3rmathpwnz/TimelyDemo<filename>TimelyDemo/TimelyDemo/Controllers/TimeEntriesViewController.h // // TimeEntriesViewController.h // TimelyDemo // // Created by <NAME> on 08/01/2019. // Copyright © 2019 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> @class TimeEntry; NS_ASSUME_NONNULL_BEGIN @interface TimeEntriesViewController : UIViewController /** Displays time entries' data. @param timeEntries Time entries that must be presented. */ - (void)setupWithTimeEntries:(nullable NSArray<TimeEntry *> *)timeEntries; @end NS_ASSUME_NONNULL_END
Aft3rmathpwnz/TimelyDemo
TimelyDemo/TimelyDemo/Controllers/DayMenuViewController.h
// // DayMenuViewController.h // TimelyDemo // // Created by <NAME> on 12/01/2019. // Copyright © 2019 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> @class TimeEntry; NS_ASSUME_NONNULL_BEGIN @interface DayMenuViewController : UIViewController /** Calculates and displays day's total hours & earnings. @param timeEntries Time entries to be calculated. */ - (void)setupWithTimeEntries:(nullable NSArray<TimeEntry *> *)timeEntries; @end NS_ASSUME_NONNULL_END
Aft3rmathpwnz/TimelyDemo
TimelyDemo/TimelyDemo/Services/TimeEntryRecognitionService.h
<reponame>Aft3rmathpwnz/TimelyDemo // // TimeEntryRecognitionService.h // TimelyDemo // // Created by <NAME> on 18/01/2019. // Copyright © 2019 <NAME>. All rights reserved. // @import UIKit; @class TimeEntry; NS_ASSUME_NONNULL_BEGIN typedef void (^TimeEntryRecognitionCallback)(TimeEntry *_Nullable timeEntry, NSError *_Nullable error); @interface TimeEntryRecognitionService : NSObject /** Recognizes project name and/or hours and minutes from the image and constructs time entry from it. For demo project recignizes only images captured in portrait mode; image orientation to be investigated. @param image UIImage to recognize on. @param completion Callback with time entry if recognized succesfully, or error if any otherwise. */ - (void)recognizeTextFromImage:(UIImage *)image completion:(TimeEntryRecognitionCallback)completion; @end NS_ASSUME_NONNULL_END
Aft3rmathpwnz/TimelyDemo
TimelyDemo/TimelyDemo/Controllers/AddTimeEntryViewController.h
<filename>TimelyDemo/TimelyDemo/Controllers/AddTimeEntryViewController.h // // AddTimeEntryViewController.h // TimelyDemo // // Created by <NAME> on 13/01/2019. // Copyright © 2019 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> @class TimeEntry; NS_ASSUME_NONNULL_BEGIN @interface AddTimeEntryViewController : UIViewController @end NS_ASSUME_NONNULL_END
Aft3rmathpwnz/TimelyDemo
TimelyDemo/TimelyDemo/AppDelegate.h
// // AppDelegate.h // TimelyDemo // // Created by <NAME> on 08/01/2019. // Copyright © 2019 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> @interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
Aft3rmathpwnz/TimelyDemo
TimelyDemo/TimelyDemo/Helpers/UIImage+Utils.h
// // UIImage+Utils.h // TimelyDemo // // Created by <NAME> on 13/01/2019. // Copyright © 2019 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> NS_ASSUME_NONNULL_BEGIN @interface UIImage (Utils) /** Fixes image orientation for capturing in portraint orientation. Temporary fix for demo. @return Transformed image that can be recognized further. */ - (UIImage *)imageWithFixedOrientation; @end NS_ASSUME_NONNULL_END
Aft3rmathpwnz/TimelyDemo
TimelyDemo/TimelyDemo/External/CBZSplashView/CBZSplashView.h
<gh_stars>100-1000 // // CBZSplashView.h // MicroMessage // // Created by <NAME> on 22/07/2014. // Copyright (c) 2014 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> #import <CoreGraphics/CoreGraphics.h> /** * The abstract class that provides the common interface between all splash view implementations. */ @interface CBZSplashView : UIView /** * This initializer takes a raster image that will be used in the animation. * * The animation is first scales the image down a bit, then, simultanuously scales it all the way up and fades the view out. * * @param icon The icon image in the centre * @param backgroundColor the background color of the entire view * * @return The Splash view */ + (instancetype)splashViewWithIcon:(UIImage *)icon backgroundColor:(UIColor *)backgroundColor; + (instancetype)splashViewWithBezierPath:(UIBezierPath *)bezier backgroundColor:(UIColor *)backgroundColor; /** * Call to start the animation. */ - (void)startAnimation; /** * Call to start the animation with completion handler. */ - (void)startAnimationWithCompletionHandler:(void(^)(void))completionHandler; /** * The starting size of the centred icon. */ @property (nonatomic, assign) CGSize iconStartSize; /** * total length of animation. */ @property (nonatomic, assign) CGFloat animationDuration; /** * The animation applied to the icon */ @property (nonatomic, strong) CAAnimation *iconAnimation; /** * the color of the icon */ @property (nonatomic, strong) UIColor *iconColor; @end
Aft3rmathpwnz/TimelyDemo
TimelyDemo/TimelyDemo/Views/Time Entry/TimeEntryView.h
<reponame>Aft3rmathpwnz/TimelyDemo // // TimeEntryView.h // TimelyDemo // // Created by <NAME> on 08/01/2019. // Copyright © 2019 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> @class TimeEntryViewData; NS_ASSUME_NONNULL_BEGIN @interface TimeEntryView: UIView - (instancetype)initWithCoder:(NSCoder *)aDecoder __attribute((unavailable("Please use +entryWithData: instead."))); - (instancetype)initWithFrame:(CGRect)frame __attribute((unavailable("Please use +entryWithData: instead."))); - (instancetype)init __attribute((unavailable("Please use +entryWithData: instead."))); /** Creates view containing immutable time entry info. @param data Time entry view data containing info. @return Time entry view filled with given data. */ + (instancetype)entryWithData:(TimeEntryViewData *)data; @end NS_ASSUME_NONNULL_END
Aft3rmathpwnz/TimelyDemo
TimelyDemo/TimelyDemo/Helpers/TDHelper.h
<filename>TimelyDemo/TimelyDemo/Helpers/TDHelper.h // // TDConstants.h // TimelyDemo // // Created by <NAME> on 08/01/2019. // Copyright © 2019 <NAME>. All rights reserved. // @import UIKit; extern NSString *const TDTimeEntryAddedNotificationName; extern NSString *const TDTimeEntryKey; @interface UIColor (TimelyDemo) + (UIColor *)td_darkColor; + (UIColor *)td_whiteColor; + (UIColor *)td_fadingWhiteColor; + (UIColor *)td_grayColor; + (UIColor *)td_projectColor; @end @interface UIFont (TimelyDemo) + (UIFont *)td_projectTitleFont; + (UIFont *)td_billedTimeEntrySubtitleFont; + (UIFont *)td_plannedTimeEntrySubtitleFont; @end @interface TDConstans: NSObject + (CGFloat)minimalMargin; + (CGFloat)mediumMargin; + (CGFloat)maximalMargin; + (CGFloat)outerMargin; + (CGFloat)oneHourHeight; + (NSUInteger)hourlyRate; @end @interface TDHelperFunctions : NSObject /** Extracting integer hours and minutes components from time interval in seconds. @param hours Reference to integer hours variable that will be filled with extracted hours. @param minutes Reference to integer minutes variable that will be filled with extracted hours. @param timeInterval Time interval in seconds. */ + (void)extractHours:(NSUInteger *)hours minutes:(NSUInteger *)minutes fromTimeInterval:(NSTimeInterval)timeInterval; @end
Aft3rmathpwnz/TimelyDemo
TimelyDemo/TimelyDemo/Models/Time Entry/TimeEntry.h
<reponame>Aft3rmathpwnz/TimelyDemo // // TimeEntry.h // TimelyDemo // // Created by <NAME> on 08/01/2019. // Copyright © 2019 <NAME>. All rights reserved. // @import UIKit; NS_ASSUME_NONNULL_BEGIN /** PONSO for time entry entity (must be implementing NSCoding & NSCopying to be serializable) */ @interface TimeEntry : NSObject @property (copy, nonatomic) NSString *projectName; @property (assign, nonatomic) NSTimeInterval billedTimeInterval; @property (assign, nonatomic) NSTimeInterval plannedTimeInterval; @end NS_ASSUME_NONNULL_END
Aft3rmathpwnz/TimelyDemo
TimelyDemo/TimelyDemo/External/CBZSplashView/CBZVectorSplashView.h
<gh_stars>100-1000 // // CBZVectorSplashView.h // Telly // // Created by <NAME> on 8/7/14. // Copyright (c) 2014 Telly, Inc. All rights reserved. // #import "CBZSplashView.h" /** * VectorSplash uses a UIBezierPath to carve a mask in the middle that expands while revealing the content behind it. */ @interface CBZVectorSplashView : CBZSplashView - (instancetype)initWithBezierPath:(UIBezierPath *)bezier backgroundColor:(UIColor *)backgroundColor; @end
WEEP-WORKS/WEEP-ENGINE
Weep Engine/DebugScene.h
#pragma once #include "Module.h" #include "Globals.h" #include "imgui.h" #include "glew/glew.h" #include "ComponentUIImage.h" #define MAX_SNAKE 2 #define LIB_NUM 11 struct hardware_info { const char* gpu_vendor = 0; const char* gpu_device = 0; int vram_mb_available = 0; int vram_mb_dedicated = 0; int vram_mb_current = 0; int vram_mb_evicted = 0; }; class DebugScene : public Module { public: DebugScene(bool start_enabled = true); ~DebugScene(); bool Awake(); bool Start(); void init2d(); bool PreUpdate(float dt); bool Update(float dt); bool ButtonEvent(const UIButtonType type) override; bool CheckBoxEvent(const UICheckBoxType type, const bool is_clicked) override; bool PostUpdate(float dt); void Tools(); bool CleanUp(); void Configuration(); void OnConfiguration(); void SetFpsMax(); void ConsoleLog(const char * text); public: bool show_hierarchy = true; bool frame_passed = false; bool window_hvr = false; bool about_hvr = false; bool config_hvr = false; bool menubar_hvr = false; bool tools_hvr = false; bool mathgeo_hvr = false; bool random_hvr = false; bool resource_hvr = false; private: bool show_inspector = true; bool show_app_about = false; bool show_demo_window = false; bool show_geometry_math_test = false; bool show_random_generator = false; bool show_debug_console = true; bool show_resources = true; bool to_save = false; bool to_load = false; bool show_app_configuration = false; //MathGeo bool contact = false; float vec3a[3] = { 0.0f, 0.0f, 0.0f }; float dist = 0; bool contact_sphere_sphere = false; bool contact_sphere_capsules = false; bool contact_aabb_aabb = false; bool contact_obb_obb = false; bool contact_aabb_ray = false; //Random Number float2 range_demo; // for the random generation demo float2 range_demo1; int quantity_demo = 1; // number of random generations of the demo SDL_version compiled_version; char name_input_buffer[255]; char organization_input_buffer[255]; char version_input_buffer[255]; int max_fps_slider = 0; ImGuiTextBuffer debug_console_buff; ComponentUIImage* bg_img = nullptr; ComponentUIImage* wndw_img = nullptr; ComponentUIImage* crsshair_img = nullptr; bool wndw_menu = false; private: void PrintResourceList(const char * path); void Panels(); void MenuBar(bool &ret); void Plane(); void AppAbout(); void DebugConsole(); void AppInfo(); void LoadStyle(const char * name); //HardWare void HardwareInfo(); std::string GetHardwareInfo(); hardware_info info1; //void UpdateVRAMInfo(); void UpdateVRAMInfo1(); //Random Number void RandomGenerator(); void GenerateRandomNumbers(float2 range, float2 range1, int quantity); float GetFloatRandomValue(float range_f1, float range_f2); int GetIntRandomValue(float range_f1, float range_f2); //MathGeo void MathGeoTest(); };
WEEP-WORKS/WEEP-ENGINE
Weep Engine/QuadtreeNode.h
<filename>Weep Engine/QuadtreeNode.h #ifndef __QUADTREENODE_H__ #define __QUADTREENODE_H__ #include "MathGeoLib/include/Geometry/AABB.h" #include <vector> #include "Globals.h" class GameObject; class QuadtreeNode { public: enum class CollisionType { INTERSERCT_BORDER, FULLY_CONTAINED, NONE_COLLISION }; QuadtreeNode(const float3& min_point_AABB, const float3& max_point_AABB, QuadtreeNode* parent = nullptr); void Draw(); void Clear(); void DeleteGOFromEntities(GameObject*); void Divide(); const bool IsSubdivided() const; CollisionType OnCollision(AABB&); AABB box; CollisionType InsertGOInThis(GameObject* go); bool IsThisInsideFrustrum(Frustum& frustrum); QuadtreeNode* parent = nullptr; const std::vector<GameObject*>* GetEntities() const; std::vector<QuadtreeNode*> subdivisions; std::vector<GameObject*> entities; private: QuadtreeNode* CreateDivision(const float3& min_point_AABB, const float3& max_point_AABB, QuadtreeNode* parent = nullptr); }; #endif // !__QUADTREENODE_H__
WEEP-WORKS/WEEP-ENGINE
Weep Engine/App.h
<filename>Weep Engine/App.h #pragma once #include "Globals.h" #include "Profiler.h" #include "Module.h" #include "MathGeoLib/include/MathBuildConfig.h" #include "MathGeoLib/include/MathGeoLib.h" #include "MathGeoLib/include/Algorithm/Random/LCG.h" class Profiler; class ModuleWindow; class ModuleInput; class ModuleRenderer3D; class ModuleCamera3D; class ModuleImporter; class DebugScene; class GameObjectManager; class SceneManager; class ModuleTexture; class ModuleQuadtree; class ResourceManagment; class JsonHelper; class ModuleFileSystem; class Application { public: Application(int argc, char* args[]); ~Application(); bool Awake(); bool Start(); bool Update(); bool CleanUp(); void CloseApp(); int GetArgc() const; const char* GetArgv(int index) const; float GetDT(); void SetMaxFps(int set); int GetMaxFps(); void LoadFile(const char * filepath); std::string GetFilePath(const char * file_path); std::string GetFileName(const char * file_path); std::string GetFileNameWithoutExtension(const char * file_path); string GetFileExtension(const char * file_name); string ToLowerCase(std::string str); std::string GetStringByLength(const char* string, uint lenght_desire); void OpenWeb(string web); const char* GetBasePath(); void OpenFolder(const char* folder); void WantToSave(); void WantToLoad(); private: void AddModule(Module* mod); void PrepareUpdate(); void FinishUpdate(); void SaveAll(); void LoadAll(); public: //Modules ModuleWindow* window = nullptr; ModuleInput* input = nullptr; ModuleRenderer3D* renderer3D = nullptr; ModuleCamera3D* camera = nullptr; DebugScene* debug_scene = nullptr; GameObjectManager* game_object_manager = nullptr; ModuleImporter* importer = nullptr; ModuleTexture* texture = nullptr; ModuleFileSystem* file_system = nullptr; ModuleQuadtree* quadtree = nullptr; SceneManager* scene_manager = nullptr; ResourceManagment* resource_managment = nullptr; Profiler* profiler = nullptr; LCG* random = nullptr; JsonHelper* json_helper = nullptr; std::list<Module*> modules; private: int argc; char** args; bool close_app = false; bool want_to_save = false; bool want_to_load = false; }; extern Application* App;
WEEP-WORKS/WEEP-ENGINE
Weep Engine/ComponentTransform.h
#ifndef __COMPONENTTRANSFORM_H__ #define __COMPONENTTRANSFORM_H__ #include "Component.h" #include "MathGeoLib/include/MathGeoLib.h" class ComponentTransform : public Component { public: ComponentTransform(); void Save(Json::Value&) const override; void Load(const Json::Value&) override; void InspectorDraw(); float4x4 GetGlobalTransform() const; void SetGlobalTransform(const float4x4& global); float4x4 GetLocalTransform() const; const void Translate(const float3 & pos); const void Rotate(const float3 & rotate); const void Scale(const float3 & scale); const void SetPosition(const float3& pos); const void SetRotation(const float3& rotation); const void SetRotationQuat(const Quat& quater); const void SetScale(const float3& scale); const float3 GetPosition() const; const float3 GetRotationEuler() const; const float3 GetScale() const; private: void RecalculateLocalTransform(); private: float4x4 local_transform; float3 local_position; float3 local_rotation_euler; Quat local_rotation_quat; float3 local_scale; float4x4 global_transform; }; #endif // !__COMPONENTTRANSFORM_H__
WEEP-WORKS/WEEP-ENGINE
Weep Engine/ModuleWindow.h
<filename>Weep Engine/ModuleWindow.h #ifndef __ModuleWindow_H__ #define __ModuleWindow_H__ #include "Module.h" #include "SDL/include/SDL.h" #include "imgui.h" #include "glmath.h" class Application; class ModuleWindow : public Module { public: ModuleWindow(bool start_enabled = true); // Destructor virtual ~ModuleWindow(); bool Awake(); bool CleanUp(); void OnConfiguration(); void Save(Json::Value&) const override; void Load(const Json::Value&) override; void SetTitle(const char* title); string GetTitle() const; int GetWidth() const; int GetHeight() const; float GetSize() const; string GetTitleWithVersion() const; void SetAppName(string name); void SetAppOrganization(const char* name); const char* GetAppOrganization(); void SetVersion(const char * set); const Rect GetWindowRect() const; string GetVersion() const; void GetWindowSize(int & width, int & height); const vec2 GetWindowSizeVec(); void SetWindowSize(int width, int height); void SetBrightness(float set); void SetFullscreen(bool set); void SetResizable(bool set); void SetBorderless(bool set); void SetFullDekstop(bool set); public: //The window we'll be rendering to SDL_Window* window; //The surface contained by the window SDL_Surface* screen_surface; ImGuiIO io; private: string title; string version; string organization; SDL_GLContext gl_context; int width = 0u; int height = 0u; float brightness = 1.0f; float size = 0.0f; bool fullscreen = false; bool resizable = false; bool borderless = false; bool full_dekstop = false; }; #endif // __ModuleWindow_H__
WEEP-WORKS/WEEP-ENGINE
Weep Engine/ComponentMesh.h
<gh_stars>1-10 #ifndef __COMPONENTMESH_H__ #define __COMPONENTMESH_H__ #include "Globals.h" #include "Component.h" #include "Color.h" #include "MathGeoLib/include/Math/float3.h" #include "MathGeoLib/include\MathGeoLib.h" class ResourceMesh; class ComponentTexture; class ComponentMesh : public Component { public: Color color; private: ComponentTexture* texture = nullptr; bool activate_face_normals = false; bool activate_vertex_normals = false; UID resource_id = 0u; public: ComponentMesh(); void PostUpdate(); void CleanUp() override; void OnGetBoundingBox(AABB & box); void SetTexture(ComponentTexture*); void InspectorDraw(); void Save(Json::Value&) const override; void Load(const Json::Value&) override; const ResourceMesh* GetResource() const; ResourceMesh* GetResource(); const UID GetResourceID() const; void SetResourceID(UID); ComponentTexture* GetTexture() const; private: void Render(); void RenderModel(); void RenderVertexNormals(); void RenderFaceNormals(); }; #endif //__COMPONENTMESH_H__
WEEP-WORKS/WEEP-ENGINE
Weep Engine/ModuleImporter.h
#ifndef __MODULEIMPORTER_H__ #define __MODULEIMPORTER_H__ #include "Module.h" #include "Globals.h" struct aiMesh; class ComponentMesh; class ResourceMesh; class ComponentTexture; struct aiScene; class GameObject; template<class my_node> class Node { public: my_node* current_node; Node<my_node>* parent = nullptr; GameObject* current_go = nullptr; public: Node(my_node* current, Node<my_node>* parent, GameObject* go = nullptr) { current_node = current; this->parent = parent; this->current_go = go; } }; class ModuleImporter : public Module { public: ModuleImporter(bool start_enabled = true); virtual ~ModuleImporter() {}; bool Start() override; bool CleanUp() override; void OnLoadFile(const char* file_path, const char* file_name, const char* file_extension); bool LoadFBX(const char* path); void LoadAllMeshes(const aiScene * scene); void LoadMaterials(const aiScene * scene, aiMesh * mesh, ComponentTexture * model); void LoadUVs(ResourceMesh * model, aiMesh * mesh); void LoadNormals(ResourceMesh * model, aiMesh * mesh); void LoadVertices(ResourceMesh * model, aiMesh * mesh); void LoadIndexs(ResourceMesh * model, aiMesh * mesh); void CreateOwnFile(const ResourceMesh* mesh, const string name_to_file); void LoadOwnFile(string name_file, ComponentMesh* mesh); const char* GetPath() const; void LoadPath(char* path); private: char* path = ""; }; #endif // !__MODULEIMPORTER_H__
WEEP-WORKS/WEEP-ENGINE
Weep Engine/ModuleTexture.h
#ifndef __MODULETEXTURE_H__ #define __MODULETEXTURE_H__ #include "Module.h" #include "Globals.h" #define checkImageWidth 64 #define checkImageHeight 64 class ComponentTexture; class ModuleTexture : public Module { public: struct TextureInfo { uint resource_id = 0; }; ModuleTexture(bool start_enabled = true); ~ModuleTexture() {}; bool Start() override; bool CleanUp() override; void OnLoadFile(const char* file_path, const char* file_name, const char* file_extension); void LoadTexture(const char* path, ComponentTexture*); // path without directory. void Load(const char * path, ComponentTexture * component_texture); ComponentTexture* GetCheckersTexture() const; std::string GetPathTexture(); public: int Width; int Height; private: ComponentTexture* checkersTexture = 0u; std::vector<TextureInfo*> textures_paths; private: void LoadCheckersTexture(); }; #endif // !__MODULETEXTURE_H__
WEEP-WORKS/WEEP-ENGINE
Weep Engine/Timer.h
<reponame>WEEP-WORKS/WEEP-ENGINE<filename>Weep Engine/Timer.h<gh_stars>1-10 #ifndef __j1TIMER_H__ #define __j1TIMER_H__ class Timer { public: Timer(); ~Timer(); void Start(); int Read() const; float ReadSec() const; void SubstractTimeFromStart(float sec); void Stop(); void PauseOn(); void PauseOff(); bool IsActive(); private: int started_at; bool paused = false; int paused_at = 0; bool active = false; }; #endif //__j1TIMER_H__
WEEP-WORKS/WEEP-ENGINE
Weep Engine/ComponentTexture.h
#ifndef __COMPONENTTEXTURE_H__ #define __COMPONENTTEXTURE_H__ #include "Component.h" #include <string> class ResourceTexture; class ComponentTexture : public Component { public: ComponentTexture() {}; void ActivateThisTexture(); bool IsTextureActive() const; void DesactivateTexture(); void InspectorDraw(); void SetCheckersToGOSelected(); void Update() override; void Save(Json::Value&) const override; void Load(const Json::Value&) override; const ResourceTexture* GetResource(UID id) const; ResourceTexture* GetResource(UID id) ; const UID GetResourceID() const; void SetResourceID(UID); public: bool has_texture = false; //erase private: bool texture_active = false; bool activate_checkers = false; UID resource_id = 0u; }; #endif // !__COMPONENTTEXTURE_H__
WEEP-WORKS/WEEP-ENGINE
Weep Engine/ComponentUIObjectBase.h
<reponame>WEEP-WORKS/WEEP-ENGINE #ifndef __COMPONENTUIOBJECTBASE_H__ #define __COMPONENTUIOBJECTBASE_H__ #include "Component.h" #include <list> #include "MathGeoLib/include/Math/Rect.h" #include "ResourceMesh.h" enum class UIType { NONE = -1, IMAGE, BUTTON, CHECKBOX }; class ComponentUIObjectBase : public Component { public: ComponentUIObjectBase(float2 pos, Rect rect_spritesheet_original, bool draggable, ComponentUIObjectBase* parent); void SetBufferVertexPos(); virtual void PreUpdate() override; virtual void Update() override; virtual void CleanUp() override; virtual void PostUpdate() override; const bool MouseInRect(); const bool GetVisible() const; void SetAllVisible(const bool visible); void SetPos(float2 mouse_move); private: void SetVisible(const bool visible); public: std::list<ComponentUIObjectBase*> childrens; ComponentUIObjectBase* parent; bool dragging = false; bool draggable = false; UIType type = UIType::NONE; float2 local_pos; float2 world_pos; Rect rect_world; BuffersData<float> vertexs_quad; BuffersData<float> uv_quad; protected: bool visible = true; }; #endif // !__COMPONENTUIOBJECTBASE_H__
WEEP-WORKS/WEEP-ENGINE
Weep Engine/ComponentUIImage.h
#ifndef __COMPONENTUIIMAGE_H__ #define __COMPONENTUIIMAGE_H__ #include "ComponentUIObjectBase.h" #include "GameObject.h" class ComponentUIImage : public ComponentUIObjectBase { public: ComponentUIImage(UIType _type, float2 local_pos, Rect rect_spritesheet_original, bool draggable, ComponentUIObjectBase* parent) : ComponentUIObjectBase(local_pos, rect_spritesheet_original, draggable, parent) { type = _type; } void InspectorDraw() { if (ImGui::CollapsingHeader("UIImage", ImGuiTreeNodeFlags_DefaultOpen)) { if (parent != nullptr) { ImGui::Text("Parent: %s ", parent->object->GetName()); ImGui::Text("Has Parent, be careful when drag"); } else ImGui::Text("Don't have parent"); ImGui::Separator(); float2 position = local_pos; if (ImGui::DragFloat2("Position", (float*)&position, 0.1f)) SetPos(position - local_pos); } } }; #endif // !__COMPONENTUIIMAGE_H__
WEEP-WORKS/WEEP-ENGINE
Weep Engine/Module.h
<filename>Weep Engine/Module.h #pragma once class Application; enum class UIButtonType; enum class UICheckBoxType; using namespace std; #include <string> #include <list> #include <queue> #include <iostream> #include <functional> #include "SDL\include\SDL.h" #include "jsoncpp/json/json.h" class Module { public: Module(bool start_enabled = true) : enabled(start_enabled) {} virtual ~Module() {} virtual bool Awake() { return true; } virtual bool Start() { return true; } virtual bool PreUpdate(float dt) { return true; } virtual bool Update(float dt) { return true; } virtual bool PostUpdate(float dt) { return true; } virtual bool CleanUp() { return true; } virtual void Save(Json::Value&) const {} virtual void Load(const Json::Value&) {} virtual void OnConfiguration() { } virtual bool ButtonEvent(const UIButtonType type) { return true; } virtual bool CheckBoxEvent(const UICheckBoxType type, const bool is_clicked) { return true; } void SetName(const char* set_name) { name = set_name; } const string GetName() const { return name; } bool GetEnabled() const { return enabled; }; void SetEnabled(bool set) { enabled = set; }; virtual void OnLoadFile(const char* file_path, const char* file_name, const char* file_extension) {}; const char * name = ""; bool configuration = false; private: bool enabled = false; };
WEEP-WORKS/WEEP-ENGINE
Weep Engine/ComponentRender2D.h
<filename>Weep Engine/ComponentRender2D.h<gh_stars>1-10 #ifndef __COMPONENTRENDER2D_H__ #define __COMPONENTRENDER2D_H__ #include "Globals.h" #include "Component.h" #include "Color.h" #include "ResourceMesh.h" class ComponentTexture; class ComponentRender2D : public Component { public: ComponentRender2D(); void PostUpdate(); void CleanUp() override; void InspectorDraw(); void SetTexture(ComponentTexture* texture); ComponentTexture* GetTexture() const; void Render(BuffersData<float>& vertexs, BuffersData<float>& uvs, uint texture_id); private: void Draw(float * vertices, uint num_indices, uint * indices, float * uvs, uint texture_id); private: ComponentTexture* texture = nullptr; //BuffersData<float> uvs; }; #endif //__COMPONENTRENDER_H__
WEEP-WORKS/WEEP-ENGINE
Weep Engine/ComponentUICheckBox.h
#ifndef __COMPONENTUICHECKBOX_H__ #define __COMPONENTUICHECKBOX_H__ #include "ComponentUIObjectBase.h" class Module; enum class UICheckBoxType { TEST, VSYNC }; class ComponentUICheckBox : public ComponentUIObjectBase { enum class UICheckBoxState { NONE, CLICKED, }; public: ComponentUICheckBox(UIType _type, float2 local_pos, Rect rect_spritesheet_original, bool draggable, ComponentUIObjectBase* parent); void PreUpdate() override; void PostUpdate() override; void CleanUp() override; void InspectorDraw() override; const bool IsClicked() const; public: Module* listener = nullptr; UICheckBoxType check_box_type; UICheckBoxState state = UICheckBoxState::NONE; uint texture_id_background; uint texture_id_clicked; uint current_texture_id; }; #endif // !__COMPONENTUICHECKBOX_H__
WEEP-WORKS/WEEP-ENGINE
Weep Engine/JsonHelper.h
#ifndef __JSONHELPER_H__ #define __JSONHELPER_H__ #include "jsoncpp/json/json.h" #include "MathGeoLib/include/MathGeoLib.h" class JsonHelper { public: JsonHelper() {}; void Fill(Json::Value&, const float3&) const; void Fill(float3&, const Json::Value&) const; }; #endif // !__JSONHELPER_H__
WEEP-WORKS/WEEP-ENGINE
Weep Engine/ModuleInput.h
#pragma once #include "Module.h" #include "Globals.h" #include "imgui.h" #define MAX_MOUSE_BUTTONS 5 enum KEY_STATE { KEY_IDLE = 0, KEY_DOWN, KEY_REPEAT, KEY_UP }; enum EventWindow { WE_QUIT = 0, WE_HIDE = 1, WE_SHOW = 2, WE_COUNT }; class ModuleInput : public Module { public: ModuleInput(bool start_enabled = true); ~ModuleInput(); bool Awake(); bool PreUpdate(float dt); bool CleanUp(); void OnConfiguration(); KEY_STATE GetKey(int id) const { return keyboard[id]; } KEY_STATE GetMouseButton(int id) const { return mouse_buttons[id]; } bool GetWindowEvent(EventWindow ev); float2 GetMouse(); void BufferInput(int key, KEY_STATE state, bool mouse); int GetMouseX() const { return mouse_x; } int GetMouseY() const { return mouse_y; } int GetMouseZ() const { return mouse_z; } int GetMouseXMotion() const { return mouse_x_motion; } int GetMouseYMotion() const { return mouse_y_motion; } private: bool windowEvents[WE_COUNT]; KEY_STATE* keyboard; KEY_STATE mouse_buttons[MAX_MOUSE_BUTTONS]; int mouse_x; int mouse_y; int mouse_z; int mouse_x_motion; int mouse_y_motion; //int mouse_z_motion; ImGuiTextBuffer input_buff; };
WEEP-WORKS/WEEP-ENGINE
Weep Engine/GameObject.h
<filename>Weep Engine/GameObject.h<gh_stars>1-10 #ifndef __GAMEOBJECT_H__ #define __GAMEOBJECT_H__ #include <vector> #include <functional> #include "Globals.h" #include "ComponentTransform.h" #include "MathGeoLib/include\MathGeoLib.h" #include "ComponentUIObjectBase.h" #include "jsoncpp/json/json.h" class Component; class ComponentTexture; class ComponentMesh; class ComponentCamera; class ComponentRender2D; class ComponentUIImage; class ComponentUIButton; class ComponentUICheckBox; class Module; enum class ComponentType; enum class UIButtonType; enum class UICheckBoxType; class GameObject { public: GameObject(std::string name, GameObject* parent, bool is_static = true); GameObject(bool is_static = true); void PreUpdate(); void Update(); //this is not from the module class. This function will be called from objectManager and will call Components update or something... I don't know yet. void PostUpdate(); void CleanUp(); void Save(Json::Value&) const ; void Load(const Json::Value&); Component* AddComponent(const ComponentType&); ComponentUIImage* AddComponentUIImage(float2 local_pos, Rect rect_spritesheet_original, bool draggable = false, ComponentUIObjectBase* parent = nullptr); ComponentUIButton* AddComponentUIButton(float2 local_pos, Rect rect_spritesheet_original, UIButtonType type, Module* listener, bool draggable = false, ComponentUIObjectBase* parent = nullptr); ComponentUICheckBox* AddComponentUICheckBox(float2 local_pos, Rect rect_spritesheet_original, UICheckBoxType type, Module* listener, bool draggable = false, ComponentUIObjectBase* parent = nullptr); void AddToComponentList(Component * ret); void SetSelected(const bool & set); void SetName(const std::string& set); const char * GetName() const; const bool GetSelected() const; const bool IsActive() const; void SetActive(const bool &to_active); void SetActiveFalse(); void SetActiveTrue(); ComponentTexture* GetTextureActivated() const; std::vector<ComponentTexture*> GetTextures() const; ComponentMesh* GetMesh() const; ComponentCamera * GetCam() const; ComponentRender2D* GetRender2D() const; ComponentTransform* GetTransform() const; const ComponentTransform* ConstGetTransform() const; const bool IsStatic()const; int DoForAllChildrens(std::function<void(GameObject*)>); void DoForAllChildrens(std::function<void(GameObject*, float&, GameObject*&)>, float&, GameObject*&); GameObject* DoForAllChildrens(std::function<const bool(const GameObject*, const uint& id)>, const uint& id); int DoForAllChildrens(std::function<void(GameObject*, Json::Value&)>, Json::Value&); int DoForAllSelected(std::function<bool(GameObject*, GameObject*)>); void SelectThis(); void CalculateNumberOfChildrens()const {} const bool IsMyBrother(const GameObject* object) const; const bool HasChildrens() const; const bool SetAsNewChildren(GameObject* new_children); void SetGoSelectedAsChildrenFromThis(); void CalcGlobalTransform(); void CalcBBox(); bool AddAABB(AABB&); const bool IsParentOfMyParents(const GameObject* possible_parent) const; const bool IsThisGOId(const uint& id) const ; void TestRay(float& distance, GameObject*& closest);//const LineSegment & segment, GameObject *& closest, float & dist private: ComponentUIObjectBase* AddComponentUI(const UIType& type, float2 local_pos, Rect rect_spritesheet_original, bool draggable, ComponentUIObjectBase* parent); public: bool parametric = false; bool hierarchy_opnened = false; GameObject* parent = nullptr; std::vector<GameObject*> childrens; //should be private std::vector<Component*> components; AABB local_bbox; bool isInsideFrustum = false; private: int id = 0; bool selected = false; std::string name = ""; bool active = true; bool is_static = true; }; #endif //__GAMEOBJECT_H__
WEEP-WORKS/WEEP-ENGINE
Weep Engine/Profiler.h
<gh_stars>1-10 #ifndef __PROFILER_H__ #define __PROFILER_H__ #include "SDL\include\SDL.h" #include <vector> #include <iostream> #define MAX_FRAMES_GRAPH 25 #define MAX_MEMORY_GRAPH 25 struct Profile { const char* name; float frame_start = 0.0f; float last_frame_ms = 0.0f; float total_frames_ms = 0.0f; }; class Profiler { public: Profiler(); ~Profiler(); void CleanUp(); void AwakeTime(); void StartTime(); void UpdateFinish(); float GetAwakeTime(); //? float GetStartTime(); //? float GetFrameTime(); int GetFPS(); float GetAvgFPS(); //? int GetFramesSinceStartup(); //? int GetTimeSinceStartup(); //? void StartProfile(const char* name); void FinishProfile(); Profile* GetProfile(const char* name); //? std::vector<float> GetFramesVector(); std::vector<float> GetMillisecondsVector(); std::vector<float> GetMemoryVector(); float GetGameTime() const; float GetGameTimeScale() const; float GetGameDT(); void SetGameTime(float gamedt); void SetGameTimeScale(float gameDTScale); void AddGameTime(float gamedt); public: int capped_ms = -1; int max_fps = 0; private: float create_time = 0.0f; float awake_Ttime = 0.0f; float start_Ttime = 0.0f; float update_start_time = 0.0f; float update_time_from_create = 0.0f; int frames_since_create = 0; float frame_ms = 0.0f; float avg_fps = 0.0f; std::vector<float> frames; std::vector<float> milliseconds; std::vector<float> memory; int frame_counter = 0; float frame_counter_ms = 0.0f; int last_second_frames = 0; Profile* current_profile = nullptr; std::vector<Profile*> profiles; float game_time = 0; float game_time_scale = 0; float game_dt = 0; }; #endif //__PROFILER_H__
WEEP-WORKS/WEEP-ENGINE
Weep Engine/ResourceManagment.h
#ifndef __RESOURCEMANAGMENT_H__ #define __RESOURCEMANAGMENT_H__ #include "Module.h" //typedef unsigned long long UID; #include "Globals.h" #include "Resource.h" #include "ResourceMesh.h" //class Resource { public: enum class Type; }; class ResourceManagment : public Module { public: ResourceManagment(); //UID Find(const char* file_in_assets) const; //UID ImportFile(const char* new_file_in_assets, bool force = false); UID GenerateNewUID(); const Resource* GetByID(UID uid) const; Resource* GetByID(UID uid); UID GetByNameMesh(const char* name) const; const std::vector<ResourceMesh*> GetAllMeshes() const; UID CreateNewResource(Resource::Type type); private: std::map<UID, Resource*> resources; UID last_uid = 0u; }; #endif // !__RESOURCEMANAGMENT_H__
WEEP-WORKS/WEEP-ENGINE
Weep Engine/ModuleFonts.h
<reponame>WEEP-WORKS/WEEP-ENGINE #ifndef _MODULE_FONTS_ #define _MODULE_FONTS_ #include <vector> #include <functional> #include "stb_truetype.h" #include "Globals.h" class UIFont { public: UIFont(); UIFont(const char* filepath, const char* name, unsigned char* bitmap, uint butmap_size, int width, int height, int line_height, stbtt_fontinfo info); ~UIFont(); void CleanUp(); const char* GetName(); unsigned char* GetBitmap(); uint GetBitmapSize(); int GetWidth(); int GetHeight(); int GetLineHeight(); stbtt_fontinfo GetInfo(); const char* GetFilePath(); private: const char* name = nullptr; unsigned char* bitmap = nullptr; uint bitmap_size = 0; int width = 0; int height = 0; int line_height = 0; stbtt_fontinfo info; const char* filepath = nullptr; }; class UIFontsSystem { public: UIFontsSystem(); ~UIFontsSystem(); void CleanUp(); void LoadFont(const char* filepath, const char* set_name); void UnloadFont(const char* name); UIFont* GetFont(const char* name); //Texture LoadText(const char* text, UIFont* font, uint size); void UnloadText(uint id); std::function<uint(unsigned char * buffer, uint buffer_size, uint width, uint height)> LoadTexture; std::function<void(uint)> UnloadTexture; private: //UIMain* ui_main = nullptr; std::vector<UIFont*> fonts; }; #endif
WEEP-WORKS/WEEP-ENGINE
Weep Engine/ModuleQuadtree.h
<gh_stars>1-10 #ifndef __MODULEQUADTREE_H__ #define __MODULEQUADTREE_H__ #include "Module.h" #include "Globals.h" #include"QuadtreeNode.h" #include <functional> #include <vector> #include "MathGeoLib/include/Geometry/Frustum.h" class GameObject; class ModuleQuadtree : public Module { public: ModuleQuadtree(); bool PreUpdate(float dt) override; bool PostUpdate(float dt) override; bool CleanUp() override; void Insert(GameObject* go); void RecalculateAllQuadtree(); void Draw(); void Clear(); void DeleteQuadTreeNode(QuadtreeNode* to_delete); void DeleteGOFromQuadtree(GameObject*); bool IsRootReset() const; void ResetRoot(); const uint GetMaxEntities() const; std::vector<GameObject*> GetAllGameObjectsinsideFrustrum(Frustum& frustrum); QuadtreeNode* GetQuadtreeNodeWithThisGO(GameObject*); void DoForAllQuadtreeNodes(std::function<QuadtreeNode::CollisionType(QuadtreeNode*, GameObject*)> funct, GameObject* go); void DoForAllQuadtreeNodes(std::function<void(QuadtreeNode*)> funct); std::vector<GameObject*> GetAllGameObjects(); QuadtreeNode* root_quadtree; bool to_recalculate = false; bool quadtree_dynamic = false; private: uint max_entities = 2; }; #endif // !__MODULEQUADTREE_H__
WEEP-WORKS/WEEP-ENGINE
Weep Engine/ModuleCamera3D.h
#pragma once #include "GameObject.h" #include "Module.h" #include "Globals.h" #include "glmath.h" #include "MathGeoLib/include/MathGeoLib.h" class Camera3D { public: Camera3D(); Frustum GetFrustum(); void SetPosition(const float3& pos); const float3 GetPosition(); void SetZDir(const float3 & front); void SetYDir(const float3 & front); void GetCorners(float3* corners); void SetNearPlaneDistance(const float& set); void SetFarPlaneDistance(const float& set); void SetFOV(const float& set); void SetAspectRatio(const float& set); const float GetNearPlaneDistance() const; const float GetFarPlaneDistance() const; const float GetVerticalFOV() const; const float4x4 GetViewMatrix() const; const float4x4 GetOpenGLViewMatrix() const; const float4x4 GetOpenGLProjectionMatrix() const; void MoveFront(const float& speed); void MoveBack(const float& speed); void MoveRight(const float& speed); void MoveLeft(const float& speed); void MoveUp(const float& speed); void MoveDown(const float& speed); void Orbit(const float3& rotate_center, const float& motion_x, const float& motion_y); void Rotate(const float& motion_x, const float& motion_y); void Focus(const float3& focus_center, const float& distance); void Look(const float3& look_pos); bool CheckInsideFrustum(const AABB& box); void SetFrustumCulling(bool set); bool GetFrustumCulling(); private: Frustum frustum; float aspect_ratio = 0.0f; float vertical_fov = 0.0f; bool frustum_culling = true; }; class ModuleCamera3D : public Module { public: ModuleCamera3D(bool start_enabled = true); ~ModuleCamera3D(); bool Awake(); bool Start(); bool Update(float dt); bool CleanUp(); Camera3D* GetEditorCamera() const; Camera3D* GetCurrentCamera() const; const float* GetViewMatrix() const; Camera3D* CreateCamera(); void DestroyCamera(Camera3D* cam); void DestroyAllCameras(); private: Camera3D* editor_camera = nullptr; Camera3D* current_camera = nullptr; vector<Camera3D*> cameras; };
WEEP-WORKS/WEEP-ENGINE
Weep Engine/ResourceTexture.h
#ifndef __RESOURCETEXTURE_H__ #define __RESOURCETEXTURE_H__ #include "Resource.h" class ResourceTexture : public Resource { public: ResourceTexture(UID uid, Resource::Type type) : Resource(uid, type) {}; //virtual ~ResourceTexture(); //bool LoadInMemory() override; //void Save(Config& config) const override; //void Load(const Config& config) override; public: //uint width = 0; //uint height = 0; //uint depth = 0; //uint mips = 0; //uint bytes = 0; //uint gpu_id = 0; //Format format = unknown; uint id_texture = 0; std::string texture_path = ""; int texture_width = 0; int texture_height = 0; }; #endif // !__RESOURCETEXTURE_H__
WEEP-WORKS/WEEP-ENGINE
Weep Engine/Component.h
#ifndef __COMPONENT_H__ #define __COMPONENT_H__ #include "Globals.h" #include "imgui.h" #include "MathGeoLib/include/MathGeoLib.h" #include "jsoncpp/json/json.h" class GameObject; enum class ComponentType { NONE = -1, TRANSFORM, MESH, TEXTURE, CAMERA, RENDER2D }; class Component { public: ComponentType type = ComponentType::NONE; GameObject* object = nullptr; public: virtual void PreUpdate() {}; virtual void Update() {}; virtual void PostUpdate() {}; virtual void CleanUp() {}; virtual void InspectorDraw() {}; virtual void Save(Json::Value&) const {}; virtual void Load(const Json::Value&) {}; const bool Component::IsActive() const { return is_active; }; void Component::SetActive(bool to_active) { is_active = to_active; }; virtual void OnGetBoundingBox(AABB &bbox) {}; private: bool is_active = true; }; #endif //__COMPONENT_H__
WEEP-WORKS/WEEP-ENGINE
Weep Engine/Resource.h
#ifndef __RESOURCE_H__ #define __RESOURCE_H__ typedef unsigned long long UID; class Resource { public: enum class Type { TEXTURE, MESH, SCENE, UNKNOWN }; Resource(UID uid, Resource::Type type) : uid(uid), type(type) {}; //virtual ~Resource(); const Resource::Type GetType() const; const UID GetResourceID() const { return uid; }; //const char* GetFile() const; //const char* GetImportedFile() const; //bool IsLoadedToMemory() const; //bool LoadToMemory(); // uint CountReferences() const; //virtual void Save(Json::Value& config) const; //virtual void Load(const Json::Value& config); //virtual bool LoadInMemory() = 0; protected: UID uid = 0u; Type type = Type::UNKNOWN; // std::string name; //std::string imported_file; //uint loaded = 0; }; #endif // !__RESOURCE_H__
WEEP-WORKS/WEEP-ENGINE
Weep Engine/ComponentUIButton.h
<reponame>WEEP-WORKS/WEEP-ENGINE<gh_stars>1-10 #ifndef __COMPONENTUIBUTTON_H__ #define __COMPONENTUIBUTTON_H__ #include "ComponentUIObjectBase.h" class Module; enum class UIButtonType { TEST, PLAY }; class ComponentUIButton : public ComponentUIObjectBase { enum class UIButtonState { NONE, HOVER, CLICKED, }; public: ComponentUIButton(UIType _type, float2 local_pos, Rect rect_spritesheet_original, bool draggable, ComponentUIObjectBase* parent); void PreUpdate() override; void PostUpdate() override; void CleanUp() override; void InspectorDraw() override; public: Module* listener = nullptr; UIButtonType button_type; UIButtonState state = UIButtonState::NONE; uint texture_id_background; uint texture_id_hover; uint texture_id_clicked; uint current_texture_id; }; #endif // !__COMPONENTUIBUTTON_H__
WEEP-WORKS/WEEP-ENGINE
Weep Engine/PerfTimer.h
#ifndef __PERFTIMER_H__ #define __PERFTIMER_H__ class PerfTimer { public: // Constructor PerfTimer(); void Start(); double ReadMs() const; int ReadTicks() const; private: int started_at; static int frequency; }; #endif //__PERFTIMER_H__
WEEP-WORKS/WEEP-ENGINE
Weep Engine/Functions.h
<reponame>WEEP-WORKS/WEEP-ENGINE #ifndef __FUNCTIONS_H__ #define __FUNCTIONS_H__ #include <list> #include <string> // ----------------------------------------- // ----------------------------------------- // USEFULL FUNCTIONS // // ----------------------------------------- // ----------------------------------------- // Returns the angle between two points in degrees float AngleFromTwoPoints(float x1, float y1, float x2, float y2); // Returns the distance from two points(can be a negative distance) float DistanceFromTwoPoints(float x1, float y1, float x2, float y2); // Compares two char*, true if success bool TextCmp(const char* text1, const char* text2); //Separate a string into tokens using the indicated iterator void Tokenize(std::string string, const char separator, std::list<std::string>& tokens); //Puts al chars to lower case void ToLowerCase(std::string str); // Returns a random int given a range; int GetRandomValue(int range_1, int range_2); #endif //__FUNCTIONS_H__
WEEP-WORKS/WEEP-ENGINE
Weep Engine/ComponentCamera.h
#ifndef __COMPONENT_CAMERA_H__ #define __COMPONENT_CAMERA_H__ #include "Component.h" #include "MathGeoLib/include/MathGeoLib.h" class GameObject; class Camera3D; class ComponentCamera : public Component { public: ComponentCamera(); void Update(); void CleanUp() override; Camera3D * GetCamera() const; void InspectorDraw(); void Save(Json::Value&) const override; void Load(const Json::Value&) override; private: Camera3D* camera = nullptr; }; #endif
WEEP-WORKS/WEEP-ENGINE
Weep Engine/ModuleGameObjectManager.h
#ifndef __MODULEGAMEOBJECTMANAGER_H__ #define __MODULEGAMEOBJECTMANAGER_H__ #include "Module.h" #include "Globals.h" #include<typeinfo> #include "ImGuizmo.h" #include "MathGeoLib/include/MathGeoLib.h" class GameObject; class ResourceMesh; typedef struct par_shapes_mesh_s par_shapes_mesh; class GameObjectManager : public Module { public: GameObjectManager(bool start_enabled = true); virtual ~GameObjectManager() {}; bool Awake() override; bool PreUpdate(float dt) override; bool Update(float dt) override; bool PostUpdate(float dt) override; bool CleanUp() override; void Save(Json::Value&) const override; void Load(const Json::Value&) override; void SetGuizmoOperation(ImGuizmo::OPERATION op); //GameObject* CreateGeometryShape(int sides); void CreateCube(); void CreateSphere(); void LoadGeometryShapeInfo(ResourceMesh * cmesh, par_shapes_mesh * mesh) const; void AddGameObjectToSelected(GameObject * go) const; void ReleaseGameObject(GameObject* object); void Destroy(GameObject * go); void ClearSelection(); void Hierarchy(); // vector<GameObject*> GetSelectedGameObjects() const int DoForAllChildrens(std::function<void(GameObjectManager*, GameObject*)>, GameObject* start = nullptr); int DoForAllChildrensVertical(std::function<void(GameObjectManager*, GameObject*)>); void DoForFirstChildrens(std::function<void(GameObjectManager*, GameObject*)>, GameObject* start = nullptr); const uint GetAllGameObjectNumber() const; GameObject* GetGOById(const uint& id) const; public: bool create_cube = false; bool create_sphere = false; bool create_go_empty = false; bool window_hvr = false; GameObject* root; //should be private //std::list<GameObject*> objects; //Vector or list? vector<GameObject*> selected; list<GameObject*> printed_hierarchy; list<GameObject*> to_delete; private: //std::list<GameObject*> objects; //Vector or list? void PrintGoList(GameObject * object); void AddGameObjectsSelectedToDestroy(); void AddGameObjectToDestroy(GameObject* go); void DrawBBox(const GameObject * object) const; void MousePick(); ImGuizmo::OPERATION current_gizmo_operation = ImGuizmo::OPERATION::TRANSLATE; float3 last_moved_transformation = float3::zero; }; #endif // !__MODULEGAMEOBJECTMANAGER_H__
WEEP-WORKS/WEEP-ENGINE
Weep Engine/SceneManager.h
<filename>Weep Engine/SceneManager.h #ifndef __SCENE_MANAGER_H__ #define __SCENE_MANAGER_H__ #include "Module.h" class GameObject; enum SCENE_STATE { EDIT, PLAY }; class SceneManager : public Module { public: SceneManager(bool start_enabled = true); virtual ~SceneManager(); bool Start(); bool CleanUp(); void SaveTmpScene(); void LoadTmpScene(); void Save(Json::Value&) const override; void Load(const Json::Value&) override; SCENE_STATE GetState(); bool GetPause(); bool GetStep(); void Edit(); void Play(); void Pause(); void Step(); bool pause = false; private: SCENE_STATE state; //bool pause = false; bool step = false; string current_scene; bool gamemode = false; }; #endif
WEEP-WORKS/WEEP-ENGINE
Weep Engine/ResourceMesh.h
<filename>Weep Engine/ResourceMesh.h #ifndef __RESOURCEMESH_H__ #define __RESOURCEMESH_H__ #include "Resource.h" #include "Globals.h" #include "MathGeoLib/include/Geometry/AABB.h" #include "glew/glew.h" template <typename BufferType> struct BuffersData { ~BuffersData() { RELEASE_ARRAY(buffer); } bool has_data = false; // If exist the data type. uint num = 0u; // Number of the data type. uint id_buffer = 0u; // Id of the buffer. BufferType* buffer = nullptr; // The buffer with data. uint buffer_size = 0u; // The size of the buffer. }; struct MeshData { ~MeshData() { RELEASE_ARRAY(vertexs.buffer); RELEASE_ARRAY(indexs.buffer); RELEASE_ARRAY(normals_direction.buffer); RELEASE_ARRAY(normal_vertexs.buffer); RELEASE_ARRAY(normal_faces.buffer); RELEASE_ARRAY(uvs.buffer); glDeleteBuffers(1, &vertexs.id_buffer); glDeleteBuffers(1, &indexs.id_buffer); glDeleteBuffers(1, &normals_direction.id_buffer); glDeleteBuffers(1, &normal_vertexs.id_buffer); glDeleteBuffers(1, &normal_faces.id_buffer); glDeleteBuffers(1, &uvs.id_buffer); } BuffersData<float> vertexs; BuffersData<uint> indexs; BuffersData<float> normals_direction; BuffersData<float> normal_vertexs; BuffersData<float> normal_faces; BuffersData<float> uvs; AABB aabb; }; class ResourceMesh : public Resource { public: ResourceMesh(UID uid, Resource::Type type) : Resource(uid, type) { mesh_data = new MeshData(); }; void SetBuffersWithData(); void CalculateNormals(); AABB GetBbox(); //virtual ~ResourceTexture(); //bool LoadInMemory() override; //void Save(Config& config) const override; //void Load(const Config& config) override; private: void CalculateFacesNormals(); void CalculateVertexsNormals(); public: //uint width = 0; //uint height = 0; //uint depth = 0; //uint mips = 0; //uint bytes = 0; //uint gpu_id = 0; //Format format = unknown; std::string name; std::string imported_file; uint num_faces = 0u; // Number of faces of the mesh. uint num_uvs_channels = 0u; UID texture_binded_id = 0u; MeshData* mesh_data; private: float normal_lenght = 0.5f; // Lenght of all normals. }; #endif // !__RESOURCEMESH_H__
WEEP-WORKS/WEEP-ENGINE
Weep Engine/ModuleRenderer3D.h
<reponame>WEEP-WORKS/WEEP-ENGINE #pragma once #include "Module.h" #include "Globals.h" #include "glmath.h" #include "Light.h" #include "imgui.h" #define MAX_LIGHTS 8 enum polygon_mode { gl_fill, gl_line, gl_point }; class ModuleRenderer3D : public Module { public: ModuleRenderer3D(bool start_enabled = true); ~ModuleRenderer3D(); bool Awake(); bool Start(); bool PreUpdate(float dt); bool Update(float dt); bool PostUpdate(float dt); bool CleanUp(); void OnConfiguration(); void Save(Json::Value&) const override; void Load(const Json::Value&) override; void OnResize(int width, int height); void DrawGrid(int HALF_GRID_SIZE); bool GetVsync() const; int GetRefreshRate() const; void SetVsync(bool set); private: Light lights[MAX_LIGHTS]; //SDL_GLContext context; mat3x3 NormalMatrix; mat4x4 ModelMatrix, ViewMatrix, ProjectionMatrix; ImVec4 clear_color; private: bool vsync = false; // OpenGL Options bool gl_blend = false; bool gl_depth = true; bool gl_scissor = false; bool gl_cull_face = true; bool gl_lighting = true; bool gl_color_material = true; bool gl_texture_2d = true; bool fill_mode = true; bool wireframe_mode = false; bool point_mode = false; polygon_mode poly_mode = polygon_mode::gl_fill; float point_size_slider = 1; int refresh_rate = 0; private: void SetAmbientLight(const bool & enabled, const float color[4]) const; void SetDiffuseLight(const bool & enabled, const float color[4]) const; void SetSpecularLight(const bool & enabled, const float color[4]) const; };
EdLeafe/vRunFox
classes/vrunfox.h
<reponame>EdLeafe/vRunFox<filename>classes/vrunfox.h #DEFINE TOP_SECRET "almost()"
azuwis/debian_bspwm
messages.c
/* Copyright (c) 2012, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "bspwm.h" #include "desktop.h" #include "ewmh.h" #include "history.h" #include "monitor.h" #include "pointer.h" #include "query.h" #include "rule.h" #include "restore.h" #include "settings.h" #include "tree.h" #include "window.h" #include "common.h" #include "subscribe.h" #include "messages.h" int handle_message(char *msg, int msg_len, FILE *rsp) { int cap = INIT_CAP; int num = 0; char **args = malloc(cap * sizeof(char *)); if (args == NULL) return MSG_FAILURE; for (int i = 0, j = 0; i < msg_len; i++) { if (msg[i] == 0) { args[num++] = msg + j; j = i + 1; } if (num >= cap) { cap *= 2; char **new = realloc(args, cap * sizeof(char *)); if (new == NULL) { free(args); return MSG_FAILURE; } else { args = new; } } } if (num < 1) { free(args); return MSG_SYNTAX; } char **args_orig = args; int ret = process_message(args, num, rsp); free(args_orig); return ret; } int process_message(char **args, int num, FILE *rsp) { if (streq("window", *args)) { return cmd_window(++args, --num); } else if (streq("desktop", *args)) { return cmd_desktop(++args, --num); } else if (streq("monitor", *args)) { return cmd_monitor(++args, --num); } else if (streq("query", *args)) { return cmd_query(++args, --num, rsp); } else if (streq("restore", *args)) { return cmd_restore(++args, --num); } else if (streq("control", *args)) { return cmd_control(++args, --num, rsp); } else if (streq("rule", *args)) { return cmd_rule(++args, --num, rsp); } else if (streq("pointer", *args)) { return cmd_pointer(++args, --num); } else if (streq("config", *args)) { return cmd_config(++args, --num, rsp); } else if (streq("quit", *args)) { return cmd_quit(++args, --num); } return MSG_UNKNOWN; } int cmd_window(char **args, int num) { if (num < 1) return MSG_SYNTAX; coordinates_t ref = {mon, mon->desk, mon->desk->focus}; coordinates_t trg = ref; if ((*args)[0] != OPT_CHR) { if (node_from_desc(*args, &ref, &trg)) num--, args++; else return MSG_FAILURE; } if (trg.node == NULL) return MSG_FAILURE; bool dirty = false; while (num > 0) { if (streq("-f", *args) || streq("--focus", *args)) { coordinates_t dst = trg; if (num > 1 && *(args + 1)[0] != OPT_CHR) { num--, args++; if (!node_from_desc(*args, &trg, &dst)) return MSG_FAILURE; } focus_node(dst.monitor, dst.desktop, dst.node); } else if (streq("-d", *args) || streq("--to-desktop", *args)) { num--, args++; coordinates_t dst; if (desktop_from_desc(*args, &trg, &dst)) { if (transfer_node(trg.monitor, trg.desktop, trg.node, dst.monitor, dst.desktop, dst.desktop->focus)) { trg.monitor = dst.monitor; trg.desktop = dst.desktop; } } else { return MSG_FAILURE; } } else if (streq("-m", *args) || streq("--to-monitor", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; coordinates_t dst; if (monitor_from_desc(*args, &trg, &dst)) { if (transfer_node(trg.monitor, trg.desktop, trg.node, dst.monitor, dst.monitor->desk, dst.monitor->desk->focus)) { trg.monitor = dst.monitor; trg.desktop = dst.monitor->desk; } } else { return MSG_FAILURE; } } else if (streq("-w", *args) || streq("--to-window", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; coordinates_t dst; if (node_from_desc(*args, &trg, &dst)) { if (transfer_node(trg.monitor, trg.desktop, trg.node, dst.monitor, dst.desktop, dst.node)) { trg.monitor = dst.monitor; trg.desktop = dst.desktop; } } else { return MSG_FAILURE; } } else if (streq("-s", *args) || streq("--swap", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; coordinates_t dst; if (node_from_desc(*args, &trg, &dst)) { if (swap_nodes(trg.monitor, trg.desktop, trg.node, dst.monitor, dst.desktop, dst.node)) { if (trg.desktop != dst.desktop) arrange(trg.monitor, trg.desktop); trg.monitor = dst.monitor; trg.desktop = dst.desktop; dirty = true; } } else { return MSG_FAILURE; } } else if (streq("-t", *args) || streq("--toggle", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; char *key = strtok(*args, EQL_TOK); char *val = strtok(NULL, EQL_TOK); alter_state_t a; bool b; if (val == NULL) { a = ALTER_TOGGLE; } else { if (parse_bool(val, &b)) a = ALTER_SET; else return MSG_FAILURE; } if (streq("fullscreen", key)) { set_fullscreen(trg.node, (a == ALTER_SET ? b : !trg.node->client->fullscreen)); dirty = true; } else if (streq("pseudo_tiled", key)) { set_pseudo_tiled(trg.node, (a == ALTER_SET ? b : !trg.node->client->pseudo_tiled)); dirty = true; } else if (streq("floating", key)) { set_floating(trg.node, (a == ALTER_SET ? b : !trg.node->client->floating)); dirty = true; } else if (streq("locked", key)) { set_locked(trg.monitor, trg.desktop, trg.node, (a == ALTER_SET ? b : !trg.node->client->locked)); } else if (streq("sticky", key)) { set_sticky(trg.monitor, trg.desktop, trg.node, (a == ALTER_SET ? b : !trg.node->client->sticky)); } else if (streq("private", key)) { set_private(trg.monitor, trg.desktop, trg.node, (a == ALTER_SET ? b : !trg.node->client->private)); } else { return MSG_FAILURE; } } else if (streq("-p", *args) || streq("--presel", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; if (!is_tiled(trg.node->client) || trg.desktop->layout != LAYOUT_TILED) return MSG_FAILURE; if (streq("cancel", *args)) { reset_mode(&trg); } else { direction_t dir; if (parse_direction(*args, &dir)) { double rat = trg.node->split_ratio; if (num > 1 && *(args + 1)[0] != OPT_CHR) { num--, args++; if (sscanf(*args, "%lf", &rat) != 1 || rat <= 0 || rat >= 1) return MSG_FAILURE; } if (auto_cancel && trg.node->split_mode == MODE_MANUAL && dir == trg.node->split_dir && rat == trg.node->split_ratio) { reset_mode(&trg); } else { trg.node->split_mode = MODE_MANUAL; trg.node->split_dir = dir; trg.node->split_ratio = rat; } window_draw_border(trg.node, trg.desktop->focus == trg.node, mon == trg.monitor); } else { return MSG_FAILURE; } } } else if (streq("-e", *args) || streq("--edge", *args)) { num--, args++; if (num < 2) return MSG_SYNTAX; if (!is_tiled(trg.node->client)) return MSG_FAILURE; direction_t dir; if (!parse_direction(*args, &dir)) return MSG_FAILURE; node_t *n = find_fence(trg.node, dir); if (n == NULL) return MSG_FAILURE; num--, args++; if ((*args)[0] == '+' || (*args)[0] == '-') { int pix; if (sscanf(*args, "%i", &pix) == 1) { int max = (n->split_type == TYPE_HORIZONTAL ? n->rectangle.height : n->rectangle.width); double rat = ((max * n->split_ratio) + pix) / max; if (rat > 0 && rat < 1) n->split_ratio = rat; else return MSG_FAILURE; } else { return MSG_FAILURE; } } else { double rat; if (sscanf(*args, "%lf", &rat) == 1 && rat > 0 && rat < 1) n->split_ratio = rat; else return MSG_FAILURE; } dirty = true; } else if (streq("-r", *args) || streq("--ratio", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; double rat; if (sscanf(*args, "%lf", &rat) == 1 && rat > 0 && rat < 1) { trg.node->split_ratio = rat; window_draw_border(trg.node, trg.desktop->focus == trg.node, mon == trg.monitor); } else { return MSG_FAILURE; } } else if (streq("-R", *args) || streq("--rotate", *args)) { num--, args++; if (num < 2) return MSG_SYNTAX; direction_t dir; if (!parse_direction(*args, &dir)) return MSG_FAILURE; node_t *n = find_fence(trg.node, dir); if (n == NULL) return MSG_FAILURE; num--, args++; int deg; if (parse_degree(*args, &deg)) { rotate_tree(n, deg); dirty = true; } else { return MSG_FAILURE; } } else if (streq("-c", *args) || streq("--close", *args)) { if (num > 1) return MSG_SYNTAX; window_close(trg.node); } else if (streq("-k", *args) || streq("--kill", *args)) { if (num > 1) return MSG_SYNTAX; window_kill(trg.monitor, trg.desktop, trg.node); dirty = true; } else { return MSG_SYNTAX; } num--, args++; } if (dirty) arrange(trg.monitor, trg.desktop); return MSG_SUCCESS; } int cmd_desktop(char **args, int num) { if (num < 1) return MSG_SYNTAX; coordinates_t ref = {mon, mon->desk, NULL}; coordinates_t trg = ref; if ((*args)[0] != OPT_CHR) { if (desktop_from_desc(*args, &ref, &trg)) num--, args++; else return MSG_FAILURE; } bool dirty = false; while (num > 0) { if (streq("-f", *args) || streq("--focus", *args)) { coordinates_t dst = trg; if (num > 1 && *(args + 1)[0] != OPT_CHR) { num--, args++; if (!desktop_from_desc(*args, &trg, &dst)) return MSG_FAILURE; } if (auto_alternate && dst.desktop == mon->desk) { desktop_select_t sel = {DESKTOP_STATUS_ALL, false, false}; history_find_desktop(HISTORY_OLDER, &trg, &dst, sel); } focus_node(dst.monitor, dst.desktop, dst.desktop->focus); } else if (streq("-m", *args) || streq("--to-monitor", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; if (trg.monitor->desk_head == trg.monitor->desk_tail) return MSG_FAILURE; coordinates_t dst; if (monitor_from_desc(*args, &trg, &dst)) { transfer_desktop(trg.monitor, dst.monitor, trg.desktop); trg.monitor = dst.monitor; update_current(); } else { return MSG_FAILURE; } } else if (streq("-s", *args) || streq("--swap", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; coordinates_t dst; if (desktop_from_desc(*args, &trg, &dst)) swap_desktops(trg.monitor, trg.desktop, dst.monitor, dst.desktop); else return MSG_FAILURE; } else if (streq("-b", *args) || streq("--bubble", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; cycle_dir_t cyc; if (parse_cycle_direction(*args, &cyc)) { desktop_t *d = trg.desktop; if (cyc == CYCLE_PREV) { if (d->prev == NULL) { while (d->next != NULL) { swap_desktops(trg.monitor, d, trg.monitor, d->next); } } else { swap_desktops(trg.monitor, d, trg.monitor, d->prev); } } else { if (d->next == NULL) { while (d->prev != NULL) { swap_desktops(trg.monitor, d, trg.monitor, d->prev); } } else { swap_desktops(trg.monitor, d, trg.monitor, d->next); } } } else { return MSG_FAILURE; } } else if (streq("-l", *args) || streq("--layout", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; layout_t lyt; cycle_dir_t cyc; if (parse_cycle_direction(*args, &cyc)) change_layout(trg.monitor, trg.desktop, (trg.desktop->layout + 1) % 2); else if (parse_layout(*args, &lyt)) change_layout(trg.monitor, trg.desktop, lyt); else return MSG_FAILURE; } else if (streq("-n", *args) || streq("--rename", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; put_status(SBSC_MASK_DESKTOP_RENAME, "desktop_rename %s %s %s\n", trg.monitor->name, trg.desktop->name, *args); snprintf(trg.desktop->name, sizeof(trg.desktop->name), "%s", *args); ewmh_update_desktop_names(); put_status(SBSC_MASK_REPORT); } else if (streq("-r", *args) || streq("--remove", *args)) { if (trg.desktop->root == NULL && trg.monitor->desk_head != trg.monitor->desk_tail) { remove_desktop(trg.monitor, trg.desktop); show_desktop(trg.monitor->desk); update_current(); return MSG_SUCCESS; } else { return MSG_FAILURE; } } else if (streq("-c", *args) || streq("--cancel-presel", *args)) { reset_mode(&trg); } else if (streq("-F", *args) || streq("--flip", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; flip_t flp; if (parse_flip(*args, &flp)) { flip_tree(trg.desktop->root, flp); dirty = true; } else { return MSG_FAILURE; } } else if (streq("-R", *args) || streq("--rotate", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; int deg; if (parse_degree(*args, &deg)) { rotate_tree(trg.desktop->root, deg); dirty = true; } else { return MSG_FAILURE; } } else if (streq("-E", *args) || streq("--equalize", *args)) { equalize_tree(trg.desktop->root); dirty = true; } else if (streq("-B", *args) || streq("--balance", *args)) { balance_tree(trg.desktop->root); dirty = true; } else if (streq("-C", *args) || streq("--circulate", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; circulate_dir_t cir; if (parse_circulate_direction(*args, &cir)) { circulate_leaves(trg.monitor, trg.desktop, cir); dirty = true; } else { return MSG_FAILURE; } } else if (streq("-t", *args) || streq("--toggle", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; char *key = strtok(*args, EQL_TOK); char *val = strtok(NULL, EQL_TOK); alter_state_t a; bool b; if (val == NULL) { a = ALTER_TOGGLE; } else { if (parse_bool(val, &b)) a = ALTER_SET; else return MSG_FAILURE; } if (streq("floating", key)) trg.desktop->floating = (a == ALTER_SET ? b : !trg.desktop->floating); else return MSG_FAILURE; } else { return MSG_SYNTAX; } num--, args++; } if (dirty) arrange(trg.monitor, trg.desktop); return MSG_SUCCESS; } int cmd_monitor(char **args, int num) { if (num < 1) return MSG_SYNTAX; coordinates_t ref = {mon, NULL, NULL}; coordinates_t trg = ref; if ((*args)[0] != OPT_CHR) { if (monitor_from_desc(*args, &ref, &trg)) num--, args++; else return MSG_FAILURE; } while (num > 0) { if (streq("-f", *args) || streq("--focus", *args)) { coordinates_t dst = trg; if (num > 1 && *(args + 1)[0] != OPT_CHR) { num--, args++; if (!monitor_from_desc(*args, &trg, &dst)) return MSG_FAILURE; } if (auto_alternate && dst.monitor == mon) { desktop_select_t sel = {DESKTOP_STATUS_ALL, false, false}; history_find_monitor(HISTORY_OLDER, &trg, &dst, sel); } focus_node(dst.monitor, dst.monitor->desk, dst.monitor->desk->focus); } else if (streq("-d", *args) || streq("--reset-desktops", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; desktop_t *d = trg.monitor->desk_head; while (num > 0 && d != NULL) { put_status(SBSC_MASK_DESKTOP_RENAME, "desktop_rename %s %s %s\n", trg.monitor->name, d->name, *args); snprintf(d->name, sizeof(d->name), "%s", *args); initialize_desktop(d); arrange(trg.monitor, d); d = d->next; num--, args++; } put_status(SBSC_MASK_REPORT); while (num > 0) { add_desktop(trg.monitor, make_desktop(*args)); num--, args++; } while (d != NULL) { desktop_t *next = d->next; if (d == mon->desk) focus_node(trg.monitor, d->prev, d->prev->focus); merge_desktops(trg.monitor, d, mon, mon->desk); remove_desktop(trg.monitor, d); d = next; } } else if (streq("-a", *args) || streq("--add-desktops", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; while (num > 0) { add_desktop(trg.monitor, make_desktop(*args)); num--, args++; } } else if (streq("-r", *args) || streq("--remove-desktops", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; while (num > 0) { coordinates_t dst; if (locate_desktop(*args, &dst) && dst.monitor->desk_head != dst.monitor->desk_tail && dst.desktop->root == NULL) { remove_desktop(dst.monitor, dst.desktop); show_desktop(dst.monitor->desk); } num--, args++; } } else if (streq("-o", *args) || streq("--order-desktops", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; desktop_t *d = trg.monitor->desk_head; while (d != NULL && num > 0) { desktop_t *next = d->next; coordinates_t dst; if (locate_desktop(*args, &dst) && dst.monitor == trg.monitor) { swap_desktops(trg.monitor, d, dst.monitor, dst.desktop); if (next == dst.desktop) next = d; } d = next; num--, args++; } } else if (streq("-n", *args) || streq("--rename", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; put_status(SBSC_MASK_MONITOR_RENAME, "monitor_rename %s %s\n", trg.monitor->name, *args); snprintf(trg.monitor->name, sizeof(trg.monitor->name), "%s", *args); put_status(SBSC_MASK_REPORT); } else if (streq("-s", *args) || streq("--swap", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; coordinates_t dst; if (monitor_from_desc(*args, &trg, &dst)) swap_monitors(trg.monitor, dst.monitor); else return MSG_FAILURE; } else { return MSG_SYNTAX; } num--, args++; } return MSG_SUCCESS; } int cmd_query(char **args, int num, FILE *rsp) { coordinates_t ref = {mon, mon->desk, mon->desk->focus}; coordinates_t trg = {NULL, NULL, NULL}; domain_t dom = DOMAIN_TREE; int d = 0, t = 0; while (num > 0) { if (streq("-T", *args) || streq("--tree", *args)) { dom = DOMAIN_TREE, d++; } else if (streq("-M", *args) || streq("--monitors", *args)) { dom = DOMAIN_MONITOR, d++; } else if (streq("-D", *args) || streq("--desktops", *args)) { dom = DOMAIN_DESKTOP, d++; } else if (streq("-W", *args) || streq("--windows", *args)) { dom = DOMAIN_WINDOW, d++; } else if (streq("-H", *args) || streq("--history", *args)) { dom = DOMAIN_HISTORY, d++; } else if (streq("-S", *args) || streq("--stack", *args)) { dom = DOMAIN_STACK, d++; } else if (streq("-m", *args) || streq("--monitor", *args)) { trg.monitor = ref.monitor; if (num > 1 && *(args + 1)[0] != OPT_CHR) { num--, args++; if (!monitor_from_desc(*args, &ref, &trg)) return MSG_FAILURE; } t++; } else if (streq("-d", *args) || streq("--desktop", *args)) { trg.monitor = ref.monitor; trg.desktop = ref.desktop; if (num > 1 && *(args + 1)[0] != OPT_CHR) { num--, args++; if (!desktop_from_desc(*args, &ref, &trg)) return MSG_FAILURE; } t++; } else if (streq("-w", *args) || streq("--window", *args)) { trg = ref; if (num > 1 && *(args + 1)[0] != OPT_CHR) { num--, args++; if (!node_from_desc(*args, &ref, &trg)) return MSG_FAILURE; } t++; } else { return MSG_SYNTAX; } num--, args++; } if (d != 1 || t > 1) return MSG_SYNTAX; if (dom == DOMAIN_HISTORY) query_history(trg, rsp); else if (dom == DOMAIN_STACK) query_stack(rsp); else if (dom == DOMAIN_WINDOW) query_windows(trg, rsp); else query_monitors(trg, dom, rsp); return MSG_SUCCESS; } int cmd_rule(char **args, int num, FILE *rsp) { if (num < 1) return MSG_SYNTAX; while (num > 0) { if (streq("-a", *args) || streq("--add", *args)) { num--, args++; if (num < 2) return MSG_SYNTAX; rule_t *rule = make_rule(); snprintf(rule->cause, sizeof(rule->cause), "%s", *args); num--, args++; size_t i = 0; while (num > 0) { if (streq("-o", *args) || streq("--one-shot", *args)) { rule->one_shot = true; } else { for (size_t j = 0; i < sizeof(rule->effect) && j < strlen(*args); i++, j++) rule->effect[i] = (*args)[j]; if (num > 1 && i < sizeof(rule->effect)) rule->effect[i++] = ' '; } num--, args++; } rule->effect[MIN(i, sizeof(rule->effect) - 1)] = '\0'; add_rule(rule); } else if (streq("-r", *args) || streq("--remove", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; int idx; while (num > 0) { if (parse_index(*args, &idx)) remove_rule_by_index(idx - 1); else if (streq("tail", *args)) remove_rule(rule_tail); else if (streq("head", *args)) remove_rule(rule_head); else remove_rule_by_cause(*args); num--, args++; } } else if (streq("-l", *args) || streq("--list", *args)) { num--, args++; list_rules(num > 0 ? *args : NULL, rsp); } else { return MSG_SYNTAX; } num--, args++; } return MSG_SUCCESS; } int cmd_pointer(char **args, int num) { if (num < 1) return MSG_SYNTAX; while (num > 0) { if (streq("-t", *args) || streq("--track", *args)) { num--, args++; if (num < 2) return MSG_SYNTAX; int x, y; if (sscanf(*args, "%i", &x) == 1 && sscanf(*(args + 1), "%i", &y) == 1) track_pointer(x, y); else return MSG_FAILURE; num--, args++; } else if (streq("-g", *args) || streq("--grab", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; pointer_action_t pac; if (parse_pointer_action(*args, &pac)) grab_pointer(pac); else return MSG_FAILURE; } else if (streq("-u", *args) || streq("--ungrab", *args)) { ungrab_pointer(); } else { return MSG_SYNTAX; } num--, args++; } return MSG_SUCCESS; } int cmd_restore(char **args, int num) { if (num < 1) return MSG_SYNTAX; while (num > 0) { if (streq("-T", *args) || streq("--tree", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; restore_tree(*args); } else if (streq("-H", *args) || streq("--history", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; restore_history(*args); } else if (streq("-S", *args) || streq("--stack", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; restore_stack(*args); } else { return MSG_SYNTAX; } num--, args++; } return MSG_SUCCESS; } int cmd_control(char **args, int num, FILE *rsp) { if (num < 1) return MSG_SYNTAX; while (num > 0) { if (streq("--adopt-orphans", *args)) { adopt_orphans(); } else if (streq("--toggle-visibility", *args)) { toggle_visibility(); } else if (streq("--subscribe", *args)) { num--, args++; int field = 0; if (num < 1) { field = SBSC_MASK_REPORT; } else { subscriber_mask_t mask; while (num > 0) { if (parse_subscriber_mask(*args, &mask)) { field |= mask; } else { return MSG_SYNTAX; } num--, args++; } } add_subscriber(rsp, field); return MSG_SUBSCRIBE; } else if (streq("--get-status", *args)) { print_report(rsp); } else if (streq("--record-history", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; bool b; if (parse_bool(*args, &b)) record_history = b; else return MSG_SYNTAX; } else { return MSG_SYNTAX; } num--, args++; } return MSG_SUCCESS; } int cmd_config(char **args, int num, FILE *rsp) { if (num < 1) return MSG_SYNTAX; coordinates_t ref = {mon, mon->desk, mon->desk->focus}; coordinates_t trg = {NULL, NULL, NULL}; if ((*args)[0] == OPT_CHR) { if (streq("-m", *args) || streq("--monitor", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; if (!monitor_from_desc(*args, &ref, &trg)) return MSG_FAILURE; } else if (streq("-d", *args) || streq("--desktop", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; if (!desktop_from_desc(*args, &ref, &trg)) return MSG_FAILURE; } else if (streq("-w", *args) || streq("--window", *args)) { num--, args++; if (num < 1) return MSG_SYNTAX; if (!node_from_desc(*args, &ref, &trg)) return MSG_FAILURE; } else { return MSG_SYNTAX; } num--, args++; } if (num == 2) return set_setting(trg, *args, *(args + 1)); else if (num == 1) return get_setting(trg, *args, rsp); else return MSG_SYNTAX; } int cmd_quit(char **args, int num) { if (num > 0 && sscanf(*args, "%i", &exit_status) != 1) return MSG_FAILURE; running = false; return MSG_SUCCESS; } int set_setting(coordinates_t loc, char *name, char *value) { #define DESKWINDEFSET(k, v) \ if (loc.node != NULL) \ loc.node->client->k = v; \ else if (loc.desktop != NULL) \ loc.desktop->k = v; \ else if (loc.monitor != NULL) \ for (desktop_t *d = loc.monitor->desk_head; d != NULL; d = d->next) \ d->k = v; \ else \ k = v; if (streq("border_width", name)) { unsigned int bw; if (sscanf(value, "%u", &bw) != 1) return MSG_FAILURE; DESKWINDEFSET(border_width, bw) #undef DESKWINDEFSET #define DESKDEFSET(k, v) \ if (loc.desktop != NULL) \ loc.desktop->k = v; \ else if (loc.monitor != NULL) \ return MSG_SYNTAX; \ else \ k = v; } else if (streq("window_gap", name)) { int wg; if (sscanf(value, "%i", &wg) != 1) return MSG_FAILURE; DESKDEFSET(window_gap, wg) #undef DESKDEFSET #define MONDESKSET(k, v) \ if (loc.desktop != NULL) \ loc.desktop->k = v; \ else if (loc.monitor != NULL) \ loc.monitor->k = v; \ else \ for (monitor_t *m = mon_head; m != NULL; m = m->next) \ m->k = v; } else if (streq("top_padding", name)) { int tp; if (sscanf(value, "%i", &tp) != 1) return MSG_FAILURE; MONDESKSET(top_padding, tp) } else if (streq("right_padding", name)) { int rp; if (sscanf(value, "%i", &rp) != 1) return MSG_FAILURE; MONDESKSET(right_padding, rp) } else if (streq("bottom_padding", name)) { int bp; if (sscanf(value, "%i", &bp) != 1) return MSG_FAILURE; MONDESKSET(bottom_padding, bp) } else if (streq("left_padding", name)) { int lp; if (sscanf(value, "%i", &lp) != 1) return MSG_FAILURE; MONDESKSET(left_padding, lp) #undef MONDESKSET #define SETSTR(s) \ } else if (streq(#s, name)) { \ if (snprintf(s, sizeof(s), "%s", value) < 0) \ return MSG_FAILURE; SETSTR(external_rules_command) SETSTR(status_prefix) #undef SETSTR } else if (streq("split_ratio", name)) { double r; if (sscanf(value, "%lf", &r) == 1 && r > 0 && r < 1) split_ratio = r; else return MSG_FAILURE; return MSG_SUCCESS; #define SETCOLOR(s) \ } else if (streq(#s, name)) { \ snprintf(s, sizeof(s), "%s", value); SETCOLOR(focused_border_color) SETCOLOR(active_border_color) SETCOLOR(normal_border_color) SETCOLOR(presel_border_color) SETCOLOR(focused_locked_border_color) SETCOLOR(active_locked_border_color) SETCOLOR(normal_locked_border_color) SETCOLOR(focused_sticky_border_color) SETCOLOR(active_sticky_border_color) SETCOLOR(normal_sticky_border_color) SETCOLOR(focused_private_border_color) SETCOLOR(active_private_border_color) SETCOLOR(normal_private_border_color) SETCOLOR(urgent_border_color) #undef SETCOLOR } else if (streq("initial_polarity", name)) { child_polarity_t p; if (parse_child_polarity(value, &p)) { initial_polarity = p; } else { return MSG_FAILURE; } } else if (streq("focus_follows_pointer", name)) { bool b; if (parse_bool(value, &b) && b != focus_follows_pointer) { focus_follows_pointer = b; uint32_t values[] = {CLIENT_EVENT_MASK | (focus_follows_pointer ? XCB_EVENT_MASK_ENTER_WINDOW : 0)}; for (monitor_t *m = mon_head; m != NULL; m = m->next) { for (desktop_t *d = m->desk_head; d != NULL; d = d->next) { for (node_t *n = first_extrema(d->root); n != NULL; n = next_leaf(n, d->root)) { xcb_change_window_attributes(dpy, n->client->window, XCB_CW_EVENT_MASK, values); } } } if (focus_follows_pointer) { for (monitor_t *m = mon_head; m != NULL; m = m->next) { window_show(m->root); } } else { for (monitor_t *m = mon_head; m != NULL; m = m->next) { window_hide(m->root); } disable_motion_recorder(); } return MSG_SUCCESS; } else { return MSG_FAILURE; } #define SETBOOL(s) \ } else if (streq(#s, name)) { \ if (!parse_bool(value, &s)) \ return MSG_FAILURE; SETBOOL(borderless_monocle) SETBOOL(gapless_monocle) SETBOOL(leaf_monocle) SETBOOL(pointer_follows_focus) SETBOOL(pointer_follows_monitor) SETBOOL(apply_floating_atom) SETBOOL(auto_alternate) SETBOOL(auto_cancel) SETBOOL(history_aware_focus) SETBOOL(focus_by_distance) SETBOOL(ignore_ewmh_focus) SETBOOL(center_pseudo_tiled) #undef SETBOOL #define SETMONBOOL(s) \ } else if (streq(#s, name)) { \ if (!parse_bool(value, &s)) \ return MSG_FAILURE; \ if (s) \ update_monitors(); SETMONBOOL(remove_disabled_monitors) SETMONBOOL(remove_unplugged_monitors) SETMONBOOL(merge_overlapping_monitors) #undef SETMONBOOL } else { return MSG_FAILURE; } for (monitor_t *m = mon_head; m != NULL; m = m->next) for (desktop_t *d = m->desk_head; d != NULL; d = d->next) arrange(m, d); return MSG_SUCCESS; } int get_setting(coordinates_t loc, char *name, FILE* rsp) { if (streq("split_ratio", name)) fprintf(rsp, "%lf", split_ratio); else if (streq("window_gap", name)) if (loc.desktop != NULL) fprintf(rsp, "%i", loc.desktop->window_gap); else if (loc.monitor != NULL) return MSG_SYNTAX; else fprintf(rsp, "%i", window_gap); else if (streq("border_width", name)) if (loc.node != NULL) fprintf(rsp, "%u", loc.node->client->border_width); else if (loc.desktop != NULL) fprintf(rsp, "%u", loc.desktop->border_width); else fprintf(rsp, "%u", border_width); else if (streq("external_rules_command", name)) fprintf(rsp, "%s", external_rules_command); else if (streq("status_prefix", name)) fprintf(rsp, "%s", status_prefix); else if (streq("initial_polarity", name)) fprintf(rsp, "%s", initial_polarity == FIRST_CHILD ? "first_child" : "second_child"); #define MONDESKGET(k) \ else if (streq(#k, name)) \ if (loc.desktop != NULL) \ fprintf(rsp, "%i", loc.desktop->k); \ else if (loc.monitor != NULL) \ fprintf(rsp, "%i", loc.monitor->k); \ else \ return MSG_FAILURE; MONDESKGET(top_padding) MONDESKGET(right_padding) MONDESKGET(bottom_padding) MONDESKGET(left_padding) #undef DESKGET #define GETCOLOR(s) \ else if (streq(#s, name)) \ fprintf(rsp, "%s", s); GETCOLOR(focused_border_color) GETCOLOR(active_border_color) GETCOLOR(normal_border_color) GETCOLOR(presel_border_color) GETCOLOR(focused_locked_border_color) GETCOLOR(active_locked_border_color) GETCOLOR(normal_locked_border_color) GETCOLOR(focused_sticky_border_color) GETCOLOR(active_sticky_border_color) GETCOLOR(normal_sticky_border_color) GETCOLOR(urgent_border_color) #undef GETCOLOR #define GETBOOL(s) \ else if (streq(#s, name)) \ fprintf(rsp, "%s", BOOLSTR(s)); GETBOOL(borderless_monocle) GETBOOL(gapless_monocle) GETBOOL(leaf_monocle) GETBOOL(focus_follows_pointer) GETBOOL(pointer_follows_focus) GETBOOL(pointer_follows_monitor) GETBOOL(apply_floating_atom) GETBOOL(auto_alternate) GETBOOL(auto_cancel) GETBOOL(history_aware_focus) GETBOOL(focus_by_distance) GETBOOL(ignore_ewmh_focus) GETBOOL(center_pseudo_tiled) GETBOOL(remove_disabled_monitors) GETBOOL(remove_unplugged_monitors) GETBOOL(merge_overlapping_monitors) #undef GETBOOL else return MSG_FAILURE; fprintf(rsp, "\n"); return MSG_SUCCESS; } bool parse_subscriber_mask(char *s, subscriber_mask_t *mask) { if (streq("all", s)) { *mask = SBSC_MASK_ALL; } else if (streq("window", s)) { *mask = SBSC_MASK_WINDOW; } else if (streq("desktop", s)) { *mask = SBSC_MASK_DESKTOP; } else if (streq("monitor", s)) { *mask = SBSC_MASK_MONITOR; } else if (streq("window_manage", s)) { *mask = SBSC_MASK_WINDOW_MANAGE; } else if (streq("window_unmanage", s)) { *mask = SBSC_MASK_WINDOW_UNMANAGE; } else if (streq("window_swap", s)) { *mask = SBSC_MASK_WINDOW_SWAP; } else if (streq("window_transfer", s)) { *mask = SBSC_MASK_WINDOW_TRANSFER; } else if (streq("window_focus", s)) { *mask = SBSC_MASK_WINDOW_FOCUS; } else if (streq("window_resize", s)) { *mask = SBSC_MASK_WINDOW_RESIZE; } else if (streq("window_move", s)) { *mask = SBSC_MASK_WINDOW_MOVE; } else if (streq("window_state", s)) { *mask = SBSC_MASK_WINDOW_STATE; } else if (streq("desktop_add", s)) { *mask = SBSC_MASK_DESKTOP_ADD; } else if (streq("desktop_rename", s)) { *mask = SBSC_MASK_DESKTOP_RENAME; } else if (streq("desktop_remove", s)) { *mask = SBSC_MASK_DESKTOP_REMOVE; } else if (streq("desktop_swap", s)) { *mask = SBSC_MASK_DESKTOP_SWAP; } else if (streq("desktop_transfer", s)) { *mask = SBSC_MASK_DESKTOP_TRANSFER; } else if (streq("desktop_focus", s)) { *mask = SBSC_MASK_DESKTOP_FOCUS; } else if (streq("desktop_layout", s)) { *mask = SBSC_MASK_DESKTOP_LAYOUT; } else if (streq("desktop_state", s)) { *mask = SBSC_MASK_DESKTOP_STATE; } else if (streq("monitor_add", s)) { *mask = SBSC_MASK_MONITOR_ADD; } else if (streq("monitor_rename", s)) { *mask = SBSC_MASK_MONITOR_RENAME; } else if (streq("monitor_remove", s)) { *mask = SBSC_MASK_MONITOR_REMOVE; } else if (streq("monitor_focus", s)) { *mask = SBSC_MASK_MONITOR_FOCUS; } else if (streq("monitor_resize", s)) { *mask = SBSC_MASK_MONITOR_RESIZE; } else if (streq("report", s)) { *mask = SBSC_MASK_REPORT; } else { return false; } return true; } bool parse_bool(char *value, bool *b) { if (streq("true", value) || streq("on", value)) { *b = true; return true; } else if (streq("false", value) || streq("off", value)) { *b = false; return true; } return false; } bool parse_layout(char *s, layout_t *l) { if (streq("monocle", s)) { *l = LAYOUT_MONOCLE; return true; } else if (streq("tiled", s)) { *l = LAYOUT_TILED; return true; } return false; } bool parse_direction(char *s, direction_t *d) { if (streq("right", s)) { *d = DIR_RIGHT; return true; } else if (streq("down", s)) { *d = DIR_DOWN; return true; } else if (streq("left", s)) { *d = DIR_LEFT; return true; } else if (streq("up", s)) { *d = DIR_UP; return true; } return false; } bool parse_cycle_direction(char *s, cycle_dir_t *d) { if (streq("next", s)) { *d = CYCLE_NEXT; return true; } else if (streq("prev", s)) { *d = CYCLE_PREV; return true; } return false; } bool parse_circulate_direction(char *s, circulate_dir_t *d) { if (streq("forward", s)) { *d = CIRCULATE_FORWARD; return true; } else if (streq("backward", s)) { *d = CIRCULATE_BACKWARD; return true; } return false; } bool parse_history_direction(char *s, history_dir_t *d) { if (streq("older", s)) { *d = HISTORY_OLDER; return true; } else if (streq("newer", s)) { *d = HISTORY_NEWER; return true; } return false; } bool parse_flip(char *s, flip_t *f) { if (streq("horizontal", s)) { *f = FLIP_HORIZONTAL; return true; } else if (streq("vertical", s)) { *f = FLIP_VERTICAL; return true; } return false; } bool parse_pointer_action(char *s, pointer_action_t *a) { if (streq("move", s)) { *a = ACTION_MOVE; return true; } else if (streq("resize_corner", s)) { *a = ACTION_RESIZE_CORNER; return true; } else if (streq("resize_side", s)) { *a = ACTION_RESIZE_SIDE; return true; } else if (streq("focus", s)) { *a = ACTION_FOCUS; return true; } return false; } bool parse_child_polarity(char *s, child_polarity_t *p) { if (streq("first_child", s)) { *p = FIRST_CHILD; return true; } else if (streq("second_child", s)) { *p = SECOND_CHILD; return true; } return false; } bool parse_degree(char *s, int *d) { int i = atoi(s); while (i < 0) i += 360; while (i > 359) i -= 360; if ((i % 90) != 0) { return false; } else { *d = i; return true; } } bool parse_window_id(char *s, long int *i) { char *end; errno = 0; long int ret = strtol(s, &end, 0); if (errno != 0 || *end != '\0') return false; else *i = ret; return true; } bool parse_bool_declaration(char *s, char **key, bool *value, alter_state_t *state) { *key = strtok(s, EQL_TOK); char *v = strtok(NULL, EQL_TOK); if (v == NULL) { *state = ALTER_TOGGLE; return true; } else { if (parse_bool(v, value)) { *state = ALTER_SET; return true; } else { return false; } } return false; } bool parse_index(char *s, int *i) { int idx; if (sscanf(s, "^%i", &idx) != 1 || idx < 1) return false; *i = idx; return true; }
azuwis/debian_bspwm
query.h
<reponame>azuwis/debian_bspwm /* Copyright (c) 2012, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 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. */ #ifndef BSPWM_QUERY_H #define BSPWM_QUERY_H typedef enum { DOMAIN_MONITOR, DOMAIN_DESKTOP, DOMAIN_WINDOW, DOMAIN_TREE, DOMAIN_HISTORY, DOMAIN_STACK } domain_t; void query_monitors(coordinates_t loc, domain_t dom, FILE *rsp); void query_desktops(monitor_t *m, domain_t dom, coordinates_t loc, unsigned int depth, FILE *rsp); void query_tree(desktop_t *d, node_t *n, FILE *rsp, unsigned int depth); void query_history(coordinates_t loc, FILE *rsp); void query_stack(FILE *rsp); void query_windows(coordinates_t loc, FILE *rsp); bool node_from_desc(char *desc, coordinates_t *ref, coordinates_t *dst); bool desktop_from_desc(char *desc, coordinates_t *ref, coordinates_t *dst); bool monitor_from_desc(char *desc, coordinates_t *ref, coordinates_t *dst); bool locate_window(xcb_window_t win, coordinates_t *loc); bool locate_desktop(char *name, coordinates_t *loc); bool locate_monitor(char *name, coordinates_t *loc); bool desktop_from_index(int i, coordinates_t *loc, monitor_t *mm); bool monitor_from_index(int i, coordinates_t *loc); bool node_matches(coordinates_t *loc, coordinates_t *ref, client_select_t sel); bool desktop_matches(coordinates_t *loc, coordinates_t *ref, desktop_select_t sel); #endif
azuwis/debian_bspwm
tree.c
/* Copyright (c) 2012, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <float.h> #include <limits.h> #include "bspwm.h" #include "desktop.h" #include "ewmh.h" #include "history.h" #include "monitor.h" #include "query.h" #include "subscribe.h" #include "settings.h" #include "stack.h" #include "window.h" #include "tree.h" void arrange(monitor_t *m, desktop_t *d) { if (d->root == NULL) return; PRINTF("arrange %s %s\n", m->name, d->name); layout_t set_layout = d->layout; if (leaf_monocle && tiled_count(d) == 1) { d->layout = LAYOUT_MONOCLE; } xcb_rectangle_t rect = m->rectangle; int wg = (gapless_monocle && d->layout == LAYOUT_MONOCLE ? 0 : d->window_gap); rect.x += m->left_padding + d->left_padding + wg; rect.y += m->top_padding + d->top_padding + wg; rect.width -= m->left_padding + d->left_padding + d->right_padding + m->right_padding + wg; rect.height -= m->top_padding + d->top_padding + d->bottom_padding + m->bottom_padding + wg; apply_layout(m, d, d->root, rect, rect); d->layout = set_layout; } void apply_layout(monitor_t *m, desktop_t *d, node_t *n, xcb_rectangle_t rect, xcb_rectangle_t root_rect) { if (n == NULL) return; n->rectangle = rect; if (is_leaf(n)) { unsigned int bw; if ((borderless_monocle && is_tiled(n->client) && !n->client->pseudo_tiled && d->layout == LAYOUT_MONOCLE) || n->client->fullscreen) bw = 0; else bw = n->client->border_width; xcb_rectangle_t r; if (!n->client->fullscreen) { if (!n->client->floating) { int wg = (gapless_monocle && d->layout == LAYOUT_MONOCLE ? 0 : d->window_gap); if (n->client->pseudo_tiled) { /* pseudo-tiled clients */ r = n->client->floating_rectangle; if (center_pseudo_tiled) { r.x = rect.x - bw + (rect.width - wg - r.width) / 2; r.y = rect.y - bw + (rect.height - wg - r.height) / 2; } else { r.x = rect.x; r.y = rect.y; } } else { /* tiled clients */ r = rect; int bleed = wg + 2 * bw; r.width = (bleed < r.width ? r.width - bleed : 1); r.height = (bleed < r.height ? r.height - bleed : 1); } n->client->tiled_rectangle = r; } else { /* floating clients */ r = n->client->floating_rectangle; } } else { /* fullscreen clients */ r = m->rectangle; } window_move_resize(n->client->window, r.x, r.y, r.width, r.height); window_border_width(n->client->window, bw); window_draw_border(n, d->focus == n, m == mon); if (pointer_follows_focus && mon->desk->focus == n && frozen_pointer->action == ACTION_NONE) { center_pointer(r); } } else { xcb_rectangle_t first_rect; xcb_rectangle_t second_rect; if (d->layout == LAYOUT_MONOCLE || n->first_child->vacant || n->second_child->vacant) { first_rect = second_rect = rect; } else { unsigned int fence; if (n->split_type == TYPE_VERTICAL) { fence = rect.width * n->split_ratio; first_rect = (xcb_rectangle_t) {rect.x, rect.y, fence, rect.height}; second_rect = (xcb_rectangle_t) {rect.x + fence, rect.y, rect.width - fence, rect.height}; } else { fence = rect.height * n->split_ratio; first_rect = (xcb_rectangle_t) {rect.x, rect.y, rect.width, fence}; second_rect = (xcb_rectangle_t) {rect.x, rect.y + fence, rect.width, rect.height - fence}; } } apply_layout(m, d, n->first_child, first_rect, root_rect); apply_layout(m, d, n->second_child, second_rect, root_rect); } } void insert_node(monitor_t *m, desktop_t *d, node_t *n, node_t *f) { if (d == NULL || n == NULL) return; PRINTF("insert node %X\n", n->client->window); /* n: new leaf node */ /* c: new container node */ /* f: focus or insertion anchor */ /* p: parent of focus */ /* g: grand parent of focus */ if (f == NULL) f = d->root; if (f == NULL) { d->root = n; } else { node_t *c = make_node(); node_t *p = f->parent; if ((f->client->private || (p != NULL && p->privacy_level > 0)) && f->split_mode == MODE_AUTOMATIC) { node_t *closest = NULL; node_t *public = NULL; closest_public(d, f, &closest, &public); if (public != NULL) { f = public; p = f->parent; } else { if (closest != NULL) { f = closest; p = f->parent; } f->split_mode = MODE_MANUAL; xcb_rectangle_t rect = f->client->tiled_rectangle; f->split_dir = (rect.width >= rect.height ? DIR_LEFT : DIR_UP); if (f->client->private) { get_opposite(f->split_dir, &f->split_dir); update_privacy_level(f, false); } } } if (p != NULL && f->split_mode == MODE_AUTOMATIC && (p->first_child->vacant || p->second_child->vacant)) { f = p; p = f->parent; } n->parent = c; c->birth_rotation = f->birth_rotation; switch (f->split_mode) { case MODE_AUTOMATIC: if (p == NULL) { if (initial_polarity == FIRST_CHILD) { c->first_child = n; c->second_child = f; } else { c->first_child = f; c->second_child = n; } if (m->rectangle.width > m->rectangle.height) c->split_type = TYPE_VERTICAL; else c->split_type = TYPE_HORIZONTAL; f->parent = c; d->root = c; } else { node_t *g = p->parent; c->parent = g; if (g != NULL) { if (is_first_child(p)) g->first_child = c; else g->second_child = c; } else { d->root = c; } c->split_type = p->split_type; c->split_ratio = p->split_ratio; p->parent = c; int rot; if (is_first_child(f)) { c->first_child = n; c->second_child = p; rot = 90; } else { c->first_child = p; c->second_child = n; rot = 270; } if (!is_floating(n->client)) rotate_tree(p, rot); n->birth_rotation = rot; } break; case MODE_MANUAL: if (p != NULL) { if (is_first_child(f)) p->first_child = c; else p->second_child = c; } c->split_ratio = f->split_ratio; c->parent = p; f->parent = c; f->birth_rotation = 0; switch (f->split_dir) { case DIR_LEFT: c->split_type = TYPE_VERTICAL; c->first_child = n; c->second_child = f; break; case DIR_RIGHT: c->split_type = TYPE_VERTICAL; c->first_child = f; c->second_child = n; break; case DIR_UP: c->split_type = TYPE_HORIZONTAL; c->first_child = n; c->second_child = f; break; case DIR_DOWN: c->split_type = TYPE_HORIZONTAL; c->first_child = f; c->second_child = n; break; } if (d->root == f) d->root = c; f->split_mode = MODE_AUTOMATIC; break; } if (f->vacant) update_vacant_state(f->parent); if (f->client != NULL && f->client->private) update_privacy_level(f, true); } if (n->client->private) update_privacy_level(n, true); if (d->focus == NULL) d->focus = n; if (n->client->sticky) m->num_sticky++; put_status(SBSC_MASK_REPORT); } void pseudo_focus(monitor_t *m, desktop_t *d, node_t *n) { if (n != NULL) { stack(n, STACK_ABOVE); if (d->focus != n) { window_draw_border(d->focus, false, m == mon); window_draw_border(n, true, m == mon); } } d->focus = n; } void focus_node(monitor_t *m, desktop_t *d, node_t *n) { if (mon->desk != d || n == NULL) clear_input_focus(); if (m->num_sticky > 0 && d != m->desk) { node_t *a = first_extrema(m->desk->root); sticky_still = false; while (a != NULL) { node_t *b = next_leaf(a, m->desk->root); if (a->client->sticky) transfer_node(m, m->desk, a, m, d, d->focus); a = b; } sticky_still = true; if (n == NULL && d->focus != NULL) n = d->focus; } if (n != NULL) { if (d->focus != NULL && n != d->focus && d->focus->client->fullscreen) { set_fullscreen(d->focus, false); arrange(m, d); } if (n->client->urgent) { n->client->urgent = false; put_status(SBSC_MASK_REPORT); } } if (mon != m) { for (desktop_t *cd = mon->desk_head; cd != NULL; cd = cd->next) window_draw_border(cd->focus, true, false); for (desktop_t *cd = m->desk_head; cd != NULL; cd = cd->next) if (cd != d) window_draw_border(cd->focus, true, true); if (d->focus == n) window_draw_border(n, true, true); } if (d->focus != n) { window_draw_border(d->focus, false, true); window_draw_border(n, true, true); } focus_desktop(m, d); d->focus = n; if (n == NULL) { history_add(m, d, NULL); ewmh_update_active_window(); return; } else { stack(n, STACK_ABOVE); } PRINTF("focus node %X\n", n->client->window); put_status(SBSC_MASK_WINDOW_FOCUS, "window_focus 0x%X\n", n->client->window); history_add(m, d, n); set_input_focus(n); if (focus_follows_pointer) { xcb_window_t win = XCB_NONE; query_pointer(&win, NULL); if (win != n->client->window) { enable_motion_recorder(); } else { disable_motion_recorder(); } } if (pointer_follows_focus) { center_pointer(get_rectangle(n->client)); } ewmh_update_active_window(); } void update_current(void) { focus_node(mon, mon->desk, mon->desk->focus); } node_t *make_node(void) { node_t *n = malloc(sizeof(node_t)); n->parent = n->first_child = n->second_child = NULL; n->split_ratio = split_ratio; n->split_mode = MODE_AUTOMATIC; n->split_type = TYPE_VERTICAL; n->birth_rotation = 0; n->privacy_level = 0; n->client = NULL; n->vacant = false; return n; } client_t *make_client(xcb_window_t win, unsigned int border_width) { client_t *c = malloc(sizeof(client_t)); c->window = win; snprintf(c->class_name, sizeof(c->class_name), "%s", MISSING_VALUE); snprintf(c->instance_name, sizeof(c->instance_name), "%s", MISSING_VALUE); c->border_width = border_width; c->pseudo_tiled = c->floating = c->fullscreen = false; c->locked = c->sticky = c->urgent = c->private = c->icccm_focus = false; xcb_icccm_get_wm_protocols_reply_t protocols; if (xcb_icccm_get_wm_protocols_reply(dpy, xcb_icccm_get_wm_protocols(dpy, win, ewmh->WM_PROTOCOLS), &protocols, NULL) == 1) { if (has_proto(WM_TAKE_FOCUS, &protocols)) c->icccm_focus = true; xcb_icccm_get_wm_protocols_reply_wipe(&protocols); } c->num_states = 0; xcb_ewmh_get_atoms_reply_t wm_state; if (xcb_ewmh_get_wm_state_reply(ewmh, xcb_ewmh_get_wm_state(ewmh, win), &wm_state, NULL) == 1) { for (unsigned int i = 0; i < wm_state.atoms_len && i < MAX_STATE; i++) ewmh_wm_state_add(c, wm_state.atoms[i]); xcb_ewmh_get_atoms_reply_wipe(&wm_state); } return c; } bool is_leaf(node_t *n) { return (n != NULL && n->first_child == NULL && n->second_child == NULL); } bool is_tiled(client_t *c) { if (c == NULL) return false; return (!c->floating && !c->fullscreen); } bool is_floating(client_t *c) { if (c == NULL) return false; return (c->floating && !c->fullscreen); } bool is_first_child(node_t *n) { return (n != NULL && n->parent != NULL && n->parent->first_child == n); } bool is_second_child(node_t *n) { return (n != NULL && n->parent != NULL && n->parent->second_child == n); } void reset_mode(coordinates_t *loc) { if (loc->node != NULL) { loc->node->split_mode = MODE_AUTOMATIC; window_draw_border(loc->node, loc->desktop->focus == loc->node, mon == loc->monitor); } else if (loc->desktop != NULL) { for (node_t *a = first_extrema(loc->desktop->root); a != NULL; a = next_leaf(a, loc->desktop->root)) { a->split_mode = MODE_AUTOMATIC; window_draw_border(a, loc->desktop->focus == a, mon == loc->monitor); } } } node_t *brother_tree(node_t *n) { if (n == NULL || n->parent == NULL) return NULL; if (is_first_child(n)) return n->parent->second_child; else return n->parent->first_child; } void closest_public(desktop_t *d, node_t *n, node_t **closest, node_t **public) { if (n == NULL) return; node_t *prev = prev_leaf(n, d->root); node_t *next = next_leaf(n, d->root); while (prev != NULL || next != NULL) { #define TESTLOOP(n) \ if (n != NULL) { \ if (is_tiled(n->client)) { \ if (n->privacy_level == 0) { \ if (n->parent == NULL || n->parent->privacy_level == 0) { \ *public = n; \ return; \ } else if (*closest == NULL) { \ *closest = n; \ } \ } \ } \ n = n##_leaf(n, d->root); \ } TESTLOOP(prev) TESTLOOP(next) #undef TESTLOOP } } node_t *first_extrema(node_t *n) { if (n == NULL) return NULL; else if (n->first_child == NULL) return n; else return first_extrema(n->first_child); } node_t *second_extrema(node_t *n) { if (n == NULL) return NULL; else if (n->second_child == NULL) return n; else return second_extrema(n->second_child); } node_t *next_leaf(node_t *n, node_t *r) { if (n == NULL) return NULL; node_t *p = n; while (is_second_child(p) && p != r) p = p->parent; if (p == r) return NULL; return first_extrema(p->parent->second_child); } node_t *prev_leaf(node_t *n, node_t *r) { if (n == NULL) return NULL; node_t *p = n; while (is_first_child(p) && p != r) p = p->parent; if (p == r) return NULL; return second_extrema(p->parent->first_child); } node_t *next_tiled_leaf(desktop_t *d, node_t *n, node_t *r) { node_t *next = next_leaf(n, r); if (next == NULL || is_tiled(next->client)) return next; else return next_tiled_leaf(d, next, r); } node_t *prev_tiled_leaf(desktop_t *d, node_t *n, node_t *r) { node_t *prev = prev_leaf(n, r); if (prev == NULL || is_tiled(prev->client)) return prev; else return prev_tiled_leaf(d, prev, r); } /* bool is_adjacent(node_t *a, node_t *r) */ /* { */ /* node_t *f = r->parent; */ /* node_t *p = a; */ /* bool first_child = is_first_child(r); */ /* while (p != r) { */ /* if (p->parent->split_type == f->split_type && is_first_child(p) == first_child) */ /* return false; */ /* p = p->parent; */ /* } */ /* return true; */ /* } */ /* Returns true if *b* is adjacent to *a* in the direction *dir* */ bool is_adjacent(node_t *a, node_t *b, direction_t dir) { switch (dir) { case DIR_RIGHT: return (a->rectangle.x + a->rectangle.width) == b->rectangle.x; break; case DIR_DOWN: return (a->rectangle.y + a->rectangle.height) == b->rectangle.y; break; case DIR_LEFT: return (b->rectangle.x + b->rectangle.width) == a->rectangle.x; break; case DIR_UP: return (b->rectangle.y + b->rectangle.height) == a->rectangle.y; break; } return false; } node_t *find_fence(node_t *n, direction_t dir) { node_t *p; if (n == NULL) return NULL; p = n->parent; while (p != NULL) { if ((dir == DIR_UP && p->split_type == TYPE_HORIZONTAL && p->rectangle.y < n->rectangle.y) || (dir == DIR_LEFT && p->split_type == TYPE_VERTICAL && p->rectangle.x < n->rectangle.x) || (dir == DIR_DOWN && p->split_type == TYPE_HORIZONTAL && (p->rectangle.y + p->rectangle.height) > (n->rectangle.y + n->rectangle.height)) || (dir == DIR_RIGHT && p->split_type == TYPE_VERTICAL && (p->rectangle.x + p->rectangle.width) > (n->rectangle.x + n->rectangle.width))) return p; p = p->parent; } return NULL; } node_t *nearest_neighbor(monitor_t *m, desktop_t *d, node_t *n, direction_t dir, client_select_t sel) { if (n == NULL || n->client->fullscreen || (d->layout == LAYOUT_MONOCLE && is_tiled(n->client))) return NULL; node_t *nearest = NULL; if (history_aware_focus) nearest = nearest_from_history(m, d, n, dir, sel); if (nearest == NULL) { if (focus_by_distance) { nearest = nearest_from_distance(m, d, n, dir, sel); } else { nearest = nearest_from_tree(m, d, n, dir, sel); } } return nearest; } node_t *nearest_from_tree(monitor_t *m, desktop_t *d, node_t *n, direction_t dir, client_select_t sel) { if (n == NULL) return NULL; node_t *fence = find_fence(n, dir); if (fence == NULL) return NULL; node_t *nearest = NULL; if (dir == DIR_UP || dir == DIR_LEFT) nearest = second_extrema(fence->first_child); else if (dir == DIR_DOWN || dir == DIR_RIGHT) nearest = first_extrema(fence->second_child); coordinates_t ref = {m, d, n}; coordinates_t loc = {m, d, nearest}; if (node_matches(&loc, &ref, sel)) return nearest; else return NULL; } node_t *nearest_from_history(monitor_t *m, desktop_t *d, node_t *n, direction_t dir, client_select_t sel) { if (n == NULL || !is_tiled(n->client)) return NULL; node_t *target = find_fence(n, dir); if (target == NULL) return NULL; if (dir == DIR_UP || dir == DIR_LEFT) target = target->first_child; else if (dir == DIR_DOWN || dir == DIR_RIGHT) target = target->second_child; node_t *nearest = NULL; int min_rank = INT_MAX; coordinates_t ref = {m, d, n}; for (node_t *a = first_extrema(target); a != NULL; a = next_leaf(a, target)) { if (a->vacant || !is_adjacent(n, a, dir) || a == n) continue; coordinates_t loc = {m, d, a}; if (!node_matches(&loc, &ref, sel)) continue; int rank = history_rank(d, a); if (rank >= 0 && rank < min_rank) { nearest = a; min_rank = rank; } } return nearest; } node_t *nearest_from_distance(monitor_t *m, desktop_t *d, node_t *n, direction_t dir, client_select_t sel) { if (n == NULL) return NULL; node_t *target = NULL; if (is_tiled(n->client)) { target = find_fence(n, dir); if (target == NULL) return NULL; if (dir == DIR_UP || dir == DIR_LEFT) target = target->first_child; else if (dir == DIR_DOWN || dir == DIR_RIGHT) target = target->second_child; } else { target = d->root; } node_t *nearest = NULL; direction_t dir2; xcb_point_t pt; xcb_point_t pt2; get_side_handle(n->client, dir, &pt); get_opposite(dir, &dir2); double ds = DBL_MAX; coordinates_t ref = {m, d, n}; for (node_t *a = first_extrema(target); a != NULL; a = next_leaf(a, target)) { coordinates_t loc = {m, d, a}; if (a == n || !node_matches(&loc, &ref, sel) || is_tiled(a->client) != is_tiled(n->client) || (is_tiled(a->client) && !is_adjacent(n, a, dir))) continue; get_side_handle(a->client, dir2, &pt2); double ds2 = distance(pt, pt2); if (ds2 < ds) { ds = ds2; nearest = a; } } return nearest; } void get_opposite(direction_t src, direction_t *dst) { switch (src) { case DIR_RIGHT: *dst = DIR_LEFT; break; case DIR_DOWN: *dst = DIR_UP; break; case DIR_LEFT: *dst = DIR_RIGHT; break; case DIR_UP: *dst = DIR_DOWN; break; } } int tiled_area(node_t *n) { if (n == NULL) return -1; xcb_rectangle_t rect = n->client->tiled_rectangle; return rect.width * rect.height; } int tiled_count(desktop_t *d) { int cnt = 0; for (node_t *f = first_extrema(d->root); f != NULL; f = next_leaf(f, d->root)) { if (is_tiled(f->client)) { cnt++; } } return cnt; } node_t *find_biggest(monitor_t *m, desktop_t *d, node_t *n, client_select_t sel) { if (d == NULL) return NULL; node_t *r = NULL; int r_area = tiled_area(r); coordinates_t ref = {m, d, n}; for (node_t *f = first_extrema(d->root); f != NULL; f = next_leaf(f, d->root)) { coordinates_t loc = {m, d, f}; if (!is_tiled(f->client) || !node_matches(&loc, &ref, sel)) continue; int f_area = tiled_area(f); if (r == NULL) { r = f; r_area = f_area; } else if (f_area > r_area) { r = f; r_area = f_area; } } return r; } void rotate_tree(node_t *n, int deg) { if (n == NULL || is_leaf(n) || deg == 0) return; node_t *tmp; if ((deg == 90 && n->split_type == TYPE_HORIZONTAL) || (deg == 270 && n->split_type == TYPE_VERTICAL) || deg == 180) { tmp = n->first_child; n->first_child = n->second_child; n->second_child = tmp; n->split_ratio = 1.0 - n->split_ratio; } if (deg != 180) { if (n->split_type == TYPE_HORIZONTAL) n->split_type = TYPE_VERTICAL; else if (n->split_type == TYPE_VERTICAL) n->split_type = TYPE_HORIZONTAL; } rotate_tree(n->first_child, deg); rotate_tree(n->second_child, deg); } void rotate_brother(node_t *n) { rotate_tree(brother_tree(n), n->birth_rotation); } void unrotate_tree(node_t *n, int rot) { if (rot == 0) return; rotate_tree(n, 360 - rot); } void unrotate_brother(node_t *n) { unrotate_tree(brother_tree(n), n->birth_rotation); } void flip_tree(node_t *n, flip_t flp) { if (n == NULL || is_leaf(n)) return; node_t *tmp; if ((flp == FLIP_HORIZONTAL && n->split_type == TYPE_HORIZONTAL) || (flp == FLIP_VERTICAL && n->split_type == TYPE_VERTICAL)) { tmp = n->first_child; n->first_child = n->second_child; n->second_child = tmp; n->split_ratio = 1.0 - n->split_ratio; } flip_tree(n->first_child, flp); flip_tree(n->second_child, flp); } void equalize_tree(node_t *n) { if (n == NULL || n->vacant) { return; } else { n->split_ratio = split_ratio; equalize_tree(n->first_child); equalize_tree(n->second_child); } } int balance_tree(node_t *n) { if (n == NULL || n->vacant) { return 0; } else if (is_leaf(n)) { return 1; } else { int b1 = balance_tree(n->first_child); int b2 = balance_tree(n->second_child); int b = b1 + b2; if (b1 > 0 && b2 > 0) n->split_ratio = (double) b1 / b; return b; } } void unlink_node(monitor_t *m, desktop_t *d, node_t *n) { if (d == NULL || n == NULL) return; PRINTF("unlink node %X\n", n->client->window); node_t *p = n->parent; if (p == NULL) { d->root = NULL; d->focus = NULL; } else { if (n->client->private) update_privacy_level(n, false); node_t *b; node_t *g = p->parent; if (is_first_child(n)) { b = p->second_child; if (!n->vacant) unrotate_tree(b, n->birth_rotation); } else { b = p->first_child; if (!n->vacant) unrotate_tree(b, n->birth_rotation); } b->parent = g; if (g != NULL) { if (is_first_child(p)) g->first_child = b; else g->second_child = b; } else { d->root = b; } b->birth_rotation = p->birth_rotation; n->parent = NULL; free(p); update_vacant_state(b->parent); if (n == d->focus) { d->focus = history_get_node(d, n); // fallback to the first extrema (`n` is not reachable) if (d->focus == NULL) d->focus = first_extrema(d->root); } } if (n->client->sticky) m->num_sticky--; put_status(SBSC_MASK_REPORT); } void remove_node(monitor_t *m, desktop_t *d, node_t *n) { if (n == NULL) return; PRINTF("remove node %X\n", n->client->window); bool focused = (n == mon->desk->focus); unlink_node(m, d, n); history_remove(d, n); remove_stack_node(n); free(n->client); free(n); num_clients--; ewmh_update_client_list(); if (focused) update_current(); } void destroy_tree(node_t *n) { if (n == NULL) return; node_t *first_tree = n->first_child; node_t *second_tree = n->second_child; if (n->client != NULL) { free(n->client); num_clients--; } free(n); destroy_tree(first_tree); destroy_tree(second_tree); } bool swap_nodes(monitor_t *m1, desktop_t *d1, node_t *n1, monitor_t *m2, desktop_t *d2, node_t *n2) { if (n1 == NULL || n2 == NULL ||n1 == n2 || (d1 != d2 && (n1->client->sticky || n2->client->sticky))) return false; PRINTF("swap nodes %X %X\n", n1->client->window, n2->client->window); node_t *pn1 = n1->parent; node_t *pn2 = n2->parent; bool n1_first_child = is_first_child(n1); bool n2_first_child = is_first_child(n2); int br1 = n1->birth_rotation; int br2 = n2->birth_rotation; int pl1 = n1->privacy_level; int pl2 = n2->privacy_level; if (pn1 != NULL) { if (n1_first_child) pn1->first_child = n2; else pn1->second_child = n2; } if (pn2 != NULL) { if (n2_first_child) pn2->first_child = n1; else pn2->second_child = n1; } n1->parent = pn2; n2->parent = pn1; n1->birth_rotation = br2; n2->birth_rotation = br1; n1->privacy_level = pl2; n2->privacy_level = pl1; if (n1->vacant != n2->vacant) { update_vacant_state(n1->parent); update_vacant_state(n2->parent); } if (n1->client->private != n2->client->private) { n1->client->private = !n1->client->private; n2->client->private = !n2->client->private; } if (d1 != d2) { if (d1->root == n1) d1->root = n2; if (d1->focus == n1) d1->focus = n2; if (d2->root == n2) d2->root = n1; if (d2->focus == n2) d2->focus = n1; if (m1 != m2) { translate_client(m2, m1, n2->client); translate_client(m1, m2, n1->client); } ewmh_set_wm_desktop(n1, d2); ewmh_set_wm_desktop(n2, d1); history_swap_nodes(m1, d1, n1, m2, d2, n2); if (m1->desk != d1 && m2->desk == d2) { window_show(n1->client->window); window_hide(n2->client->window); } else if (m1->desk == d1 && m2->desk != d2) { window_hide(n1->client->window); window_show(n2->client->window); } update_input_focus(); } return true; } bool transfer_node(monitor_t *ms, desktop_t *ds, node_t *ns, monitor_t *md, desktop_t *dd, node_t *nd) { if (ns == NULL || ns == nd || (sticky_still && ns->client->sticky)) return false; PRINTF("transfer node %X\n", ns->client->window); put_status(SBSC_MASK_WINDOW_TRANSFER, "window_transfer %s %s 0x%X %s %s 0x%X\n", ms->name, ds->name, ns->client->window, md->name, dd->name, nd!=NULL?nd->client->window:0); bool focused = (ns == mon->desk->focus); bool active = (ns == ds->focus); if (focused) clear_input_focus(); unlink_node(ms, ds, ns); insert_node(md, dd, ns, nd); if (md != ms) translate_client(ms, md, ns->client); if (ds != dd) { ewmh_set_wm_desktop(ns, dd); if (!ns->client->sticky) { if (ds == ms->desk && dd != md->desk) window_hide(ns->client->window); else if (ds != ms->desk && dd == md->desk) window_show(ns->client->window); } if (ns->client->fullscreen && dd->focus != ns) set_fullscreen(ns, false); } history_transfer_node(md, dd, ns); stack(ns, STACK_BELOW); if (ds == dd) { if (focused) focus_node(md, dd, ns); else if (active) pseudo_focus(md, dd, ns); } else { if (focused) update_current(); else if (ns == mon->desk->focus) update_input_focus(); } arrange(ms, ds); if (ds != dd) arrange(md, dd); return true; } node_t *closest_node(monitor_t *m, desktop_t *d, node_t *n, cycle_dir_t dir, client_select_t sel) { if (n == NULL) return NULL; node_t *f = (dir == CYCLE_PREV ? prev_leaf(n, d->root) : next_leaf(n, d->root)); if (f == NULL) f = (dir == CYCLE_PREV ? second_extrema(d->root) : first_extrema(d->root)); coordinates_t ref = {m, d, n}; while (f != n) { coordinates_t loc = {m, d, f}; if (node_matches(&loc, &ref, sel)) return f; f = (dir == CYCLE_PREV ? prev_leaf(f, d->root) : next_leaf(f, d->root)); if (f == NULL) f = (dir == CYCLE_PREV ? second_extrema(d->root) : first_extrema(d->root)); } return NULL; } void circulate_leaves(monitor_t *m, desktop_t *d, circulate_dir_t dir) { if (d == NULL || d->root == NULL || d->focus == NULL || is_leaf(d->root)) return; node_t *p = d->focus->parent; bool focus_first_child = is_first_child(d->focus); if (dir == CIRCULATE_FORWARD) for (node_t *s = second_extrema(d->root), *f = prev_tiled_leaf(d, s, d->root); f != NULL; s = prev_tiled_leaf(d, f, d->root), f = prev_tiled_leaf(d, s, d->root)) swap_nodes(m, d, f, m, d, s); else for (node_t *f = first_extrema(d->root), *s = next_tiled_leaf(d, f, d->root); s != NULL; f = next_tiled_leaf(d, s, d->root), s = next_tiled_leaf(d, f, d->root)) swap_nodes(m, d, f, m, d, s); if (focus_first_child) focus_node(m, d, p->first_child); else focus_node(m, d, p->second_child); } void update_vacant_state(node_t *n) { if (n == NULL) return; PUTS("update vacant state"); /* n is not a leaf */ node_t *p = n; while (p != NULL) { p->vacant = (p->first_child->vacant && p->second_child->vacant); p = p->parent; } } void update_privacy_level(node_t *n, bool value) { int v = (value ? 1 : -1); for (node_t *p = n; p != NULL; p = p->parent) p->privacy_level += v; }
azuwis/debian_bspwm
types.h
<reponame>azuwis/debian_bspwm /* Copyright (c) 2012, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 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. */ #ifndef BSPWM_TYPES_H #define BSPWM_TYPES_H #include <stdbool.h> #include <xcb/xcb.h> #include <xcb/randr.h> #include <xcb/xcb_event.h> #include "helpers.h" #define MISSING_VALUE "N/A" #define MAX_STATE 4 typedef enum { TYPE_HORIZONTAL, TYPE_VERTICAL } split_type_t; typedef enum { MODE_AUTOMATIC, MODE_MANUAL } split_mode_t; typedef enum { CLIENT_TYPE_ALL, CLIENT_TYPE_FLOATING, CLIENT_TYPE_TILED } client_type_t; typedef enum { CLIENT_CLASS_ALL, CLIENT_CLASS_EQUAL, CLIENT_CLASS_DIFFER } client_class_t; typedef enum { CLIENT_MODE_ALL, CLIENT_MODE_AUTOMATIC, CLIENT_MODE_MANUAL } client_mode_t; typedef struct { client_type_t type; client_class_t class; client_mode_t mode; bool urgent; bool local; bool unfocused; } client_select_t; typedef enum { ALTER_TOGGLE, ALTER_SET } alter_state_t; typedef enum { CYCLE_NEXT, CYCLE_PREV } cycle_dir_t; typedef enum { CIRCULATE_FORWARD, CIRCULATE_BACKWARD } circulate_dir_t; typedef enum { HISTORY_OLDER, HISTORY_NEWER } history_dir_t; typedef enum { DIR_RIGHT, DIR_DOWN, DIR_LEFT, DIR_UP } direction_t; typedef enum { CORNER_TOP_LEFT, CORNER_TOP_RIGHT, CORNER_BOTTOM_RIGHT, CORNER_BOTTOM_LEFT } corner_t; typedef enum { SIDE_LEFT, SIDE_TOP, SIDE_RIGHT, SIDE_BOTTOM } side_t; typedef enum { ACTION_NONE, ACTION_FOCUS, ACTION_MOVE, ACTION_RESIZE_SIDE, ACTION_RESIZE_CORNER } pointer_action_t; typedef enum { LAYOUT_TILED, LAYOUT_MONOCLE } layout_t; typedef enum { FLIP_HORIZONTAL, FLIP_VERTICAL } flip_t; typedef enum { DESKTOP_STATUS_ALL, DESKTOP_STATUS_FREE, DESKTOP_STATUS_OCCUPIED } desktop_status_t; typedef enum { DESKTOP_URGENCY_ALL, DESKTOP_URGENCY_ON, DESKTOP_URGENCY_OFF } desktop_urgency_t; typedef enum { FIRST_CHILD, SECOND_CHILD } child_polarity_t; typedef struct { desktop_status_t status; bool urgent; bool local; } desktop_select_t; typedef struct { xcb_window_t window; char class_name[3 * SMALEN / 2]; char instance_name[3 * SMALEN / 2]; unsigned int border_width; bool pseudo_tiled; bool floating; bool fullscreen; bool locked; /* protects window from being closed */ bool sticky; bool urgent; bool private; bool icccm_focus; xcb_rectangle_t floating_rectangle; xcb_rectangle_t tiled_rectangle; uint16_t min_width; uint16_t max_width; uint16_t min_height; uint16_t max_height; xcb_atom_t wm_state[MAX_STATE]; int num_states; } client_t; typedef struct node_t node_t; struct node_t { split_type_t split_type; double split_ratio; split_mode_t split_mode; direction_t split_dir; int birth_rotation; xcb_rectangle_t rectangle; bool vacant; /* vacant nodes only hold floating clients */ int privacy_level; node_t *first_child; node_t *second_child; node_t *parent; client_t *client; /* NULL except for leaves */ }; typedef struct desktop_t desktop_t; struct desktop_t { char name[SMALEN]; layout_t layout; node_t *root; node_t *focus; desktop_t *prev; desktop_t *next; int top_padding; int right_padding; int bottom_padding; int left_padding; int window_gap; unsigned int border_width; bool floating; }; typedef struct monitor_t monitor_t; struct monitor_t { char name[SMALEN]; xcb_randr_output_t id; xcb_rectangle_t rectangle; xcb_window_t root; bool wired; int top_padding; int right_padding; int bottom_padding; int left_padding; desktop_t *desk; desktop_t *desk_head; desktop_t *desk_tail; monitor_t *prev; monitor_t *next; int num_sticky; }; typedef struct { monitor_t *monitor; desktop_t *desktop; node_t *node; } coordinates_t; typedef struct history_t history_t; struct history_t { coordinates_t loc; bool latest; history_t *prev; history_t *next; }; typedef struct stacking_list_t stacking_list_t; struct stacking_list_t { node_t *node; stacking_list_t *prev; stacking_list_t *next; }; typedef struct subscriber_list_t subscriber_list_t; struct subscriber_list_t { int fd; FILE *stream; int field; subscriber_list_t *prev; subscriber_list_t *next; }; typedef struct rule_t rule_t; struct rule_t { char cause[MAXLEN]; char effect[MAXLEN]; bool one_shot; rule_t *prev; rule_t *next; }; typedef struct { char class_name[3 * SMALEN / 2]; char instance_name[3 * SMALEN / 2]; char monitor_desc[MAXLEN]; char desktop_desc[MAXLEN]; char node_desc[MAXLEN]; char split_dir[SMALEN]; double split_ratio; uint16_t min_width; uint16_t max_width; uint16_t min_height; uint16_t max_height; bool pseudo_tiled; bool floating; bool fullscreen; bool locked; bool sticky; bool private; bool center; bool follow; bool manage; bool focus; bool border; } rule_consequence_t; typedef struct pending_rule_t pending_rule_t; struct pending_rule_t { int fd; xcb_window_t win; rule_consequence_t *csq; pending_rule_t *prev; pending_rule_t *next; }; typedef struct { xcb_point_t position; pointer_action_t action; xcb_rectangle_t rectangle; node_t *vertical_fence; node_t *horizontal_fence; monitor_t *monitor; desktop_t *desktop; node_t *node; client_t *client; xcb_window_t window; bool is_tiled; double vertical_ratio; double horizontal_ratio; corner_t corner; side_t side; } pointer_state_t; typedef struct { node_t *fence; unsigned int distance; } fence_distance_t; #endif
azuwis/debian_bspwm
window.c
/* Copyright (c) 2012, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdlib.h> #include <string.h> #include "bspwm.h" #include "ewmh.h" #include "monitor.h" #include "query.h" #include "rule.h" #include "settings.h" #include "stack.h" #include "tree.h" #include "subscribe.h" #include "messages.h" #include "window.h" void schedule_window(xcb_window_t win) { coordinates_t loc; uint8_t override_redirect = 0; xcb_get_window_attributes_reply_t *wa = xcb_get_window_attributes_reply(dpy, xcb_get_window_attributes(dpy, win), NULL); if (wa != NULL) { override_redirect = wa->override_redirect; free(wa); } if (override_redirect || locate_window(win, &loc)) return; /* ignore pending windows */ for (pending_rule_t *pr = pending_rule_head; pr != NULL; pr = pr->next) if (pr->win == win) return; rule_consequence_t *csq = make_rule_conquence(); apply_rules(win, csq); if (!schedule_rules(win, csq)) { manage_window(win, csq, -1); free(csq); } } void manage_window(xcb_window_t win, rule_consequence_t *csq, int fd) { monitor_t *m = mon; desktop_t *d = mon->desk; node_t *f = mon->desk->focus; parse_rule_consequence(fd, csq); if (!csq->manage) { disable_floating_atom(win); window_show(win); return; } PRINTF("manage %X\n", win); if (csq->node_desc[0] != '\0') { coordinates_t ref = {m, d, f}; coordinates_t trg = {NULL, NULL, NULL}; if (node_from_desc(csq->node_desc, &ref, &trg)) { m = trg.monitor; d = trg.desktop; f = trg.node; } } else if (csq->desktop_desc[0] != '\0') { coordinates_t ref = {m, d, NULL}; coordinates_t trg = {NULL, NULL, NULL}; if (desktop_from_desc(csq->desktop_desc, &ref, &trg)) { m = trg.monitor; d = trg.desktop; f = trg.desktop->focus; } } else if (csq->monitor_desc[0] != '\0') { coordinates_t ref = {m, NULL, NULL}; coordinates_t trg = {NULL, NULL, NULL}; if (monitor_from_desc(csq->monitor_desc, &ref, &trg)) { m = trg.monitor; d = trg.monitor->desk; f = trg.monitor->desk->focus; } } if (csq->sticky) { m = mon; d = mon->desk; f = mon->desk->focus; } if (csq->split_dir[0] != '\0' && f != NULL) { direction_t dir; if (parse_direction(csq->split_dir, &dir)) { f->split_mode = MODE_MANUAL; f->split_dir = dir; } } if (csq->split_ratio != 0 && f != NULL) { f->split_ratio = csq->split_ratio; } client_t *c = make_client(win, csq->border ? d->border_width : 0); update_floating_rectangle(c); if (c->floating_rectangle.x == 0 && c->floating_rectangle.y == 0) csq->center = true; c->min_width = csq->min_width; c->max_width = csq->max_width; c->min_height = csq->min_height; c->max_height = csq->max_height; monitor_t *mm = monitor_from_client(c); embrace_client(mm, c); translate_client(mm, m, c); if (csq->center) window_center(m, c); snprintf(c->class_name, sizeof(c->class_name), "%s", csq->class_name); snprintf(c->instance_name, sizeof(c->instance_name), "%s", csq->instance_name); csq->floating = csq->floating || d->floating; node_t *n = make_node(); n->client = c; put_status(SBSC_MASK_WINDOW_MANAGE, "window_manage %s %s 0x%X 0x%X\n", m->name, d->name, f!=NULL?f->client->window:0, win); insert_node(m, d, n, f); disable_floating_atom(c->window); set_pseudo_tiled(n, csq->pseudo_tiled); set_floating(n, csq->floating); set_locked(m, d, n, csq->locked); set_sticky(m, d, n, csq->sticky); set_private(m, d, n, csq->private); if (d->focus != NULL && d->focus->client->fullscreen) set_fullscreen(d->focus, false); set_fullscreen(n, csq->fullscreen); arrange(m, d); bool give_focus = (csq->focus && (d == mon->desk || csq->follow)); if (give_focus) focus_node(m, d, n); else if (csq->focus) pseudo_focus(m, d, n); else stack(n, STACK_ABOVE); uint32_t values[] = {CLIENT_EVENT_MASK | (focus_follows_pointer ? XCB_EVENT_MASK_ENTER_WINDOW : 0)}; xcb_change_window_attributes(dpy, c->window, XCB_CW_EVENT_MASK, values); if (visible) { if (d == m->desk) window_show(n->client->window); else window_hide(n->client->window); } /* the same function is already called in `focus_node` but has no effects on unmapped windows */ if (give_focus) xcb_set_input_focus(dpy, XCB_INPUT_FOCUS_POINTER_ROOT, win, XCB_CURRENT_TIME); num_clients++; ewmh_set_wm_desktop(n, d); ewmh_update_client_list(); } void unmanage_window(xcb_window_t win) { coordinates_t loc; if (locate_window(win, &loc)) { PRINTF("unmanage %X\n", win); put_status(SBSC_MASK_WINDOW_UNMANAGE, "window_unmanage 0x%X\n", win); remove_node(loc.monitor, loc.desktop, loc.node); if (frozen_pointer->window == win) frozen_pointer->action = ACTION_NONE; arrange(loc.monitor, loc.desktop); } else { for (pending_rule_t *pr = pending_rule_head; pr != NULL; pr = pr->next) { if (pr->win == win) { remove_pending_rule(pr); return; } } } } void window_draw_border(node_t *n, bool focused_window, bool focused_monitor) { if (n == NULL || n->client->border_width < 1) { return; } xcb_window_t win = n->client->window; uint32_t border_color_pxl = get_border_color(n->client, focused_window, focused_monitor); if (n->split_mode == MODE_AUTOMATIC) { xcb_change_window_attributes(dpy, win, XCB_CW_BORDER_PIXEL, &border_color_pxl); } else { unsigned int border_width = n->client->border_width; uint32_t presel_border_color_pxl; get_color(presel_border_color, win, &presel_border_color_pxl); xcb_rectangle_t actual_rectangle = get_rectangle(n->client); uint16_t width = actual_rectangle.width; uint16_t height = actual_rectangle.height; uint16_t full_width = width + 2 * border_width; uint16_t full_height = height + 2 * border_width; xcb_rectangle_t border_rectangles[] = { { width, 0, 2 * border_width, height + 2 * border_width }, { 0, height, width + 2 * border_width, 2 * border_width } }; xcb_rectangle_t *presel_rectangles; uint8_t win_depth = root_depth; xcb_get_geometry_reply_t *geo = xcb_get_geometry_reply(dpy, xcb_get_geometry(dpy, win), NULL); if (geo != NULL) win_depth = geo->depth; free(geo); xcb_pixmap_t pixmap = xcb_generate_id(dpy); xcb_create_pixmap(dpy, win_depth, pixmap, win, full_width, full_height); xcb_gcontext_t gc = xcb_generate_id(dpy); xcb_create_gc(dpy, gc, pixmap, 0, NULL); xcb_change_gc(dpy, gc, XCB_GC_FOREGROUND, &border_color_pxl); xcb_poly_fill_rectangle(dpy, pixmap, gc, LENGTH(border_rectangles), border_rectangles); uint16_t fence = (int16_t) (n->split_ratio * ((n->split_dir == DIR_UP || n->split_dir == DIR_DOWN) ? height : width)); presel_rectangles = malloc(2 * sizeof(xcb_rectangle_t)); switch (n->split_dir) { case DIR_UP: presel_rectangles[0] = (xcb_rectangle_t) {width, 0, 2 * border_width, fence}; presel_rectangles[1] = (xcb_rectangle_t) {0, height + border_width, full_width, border_width}; break; case DIR_DOWN: presel_rectangles[0] = (xcb_rectangle_t) {width, fence + 1, 2 * border_width, height + border_width - (fence + 1)}; presel_rectangles[1] = (xcb_rectangle_t) {0, height, full_width, border_width}; break; case DIR_LEFT: presel_rectangles[0] = (xcb_rectangle_t) {0, height, fence, 2 * border_width}; presel_rectangles[1] = (xcb_rectangle_t) {width + border_width, 0, border_width, full_height}; break; case DIR_RIGHT: presel_rectangles[0] = (xcb_rectangle_t) {fence + 1, height, width + border_width - (fence + 1), 2 * border_width}; presel_rectangles[1] = (xcb_rectangle_t) {width, 0, border_width, full_height}; break; } xcb_change_gc(dpy, gc, XCB_GC_FOREGROUND, &presel_border_color_pxl); xcb_poly_fill_rectangle(dpy, pixmap, gc, 2, presel_rectangles); xcb_change_window_attributes(dpy, win, XCB_CW_BORDER_PIXMAP, &pixmap); free(presel_rectangles); xcb_free_gc(dpy, gc); xcb_free_pixmap(dpy, pixmap); } } pointer_state_t *make_pointer_state(void) { pointer_state_t *p = malloc(sizeof(pointer_state_t)); p->monitor = NULL; p->desktop = NULL; p->node = p->vertical_fence = p->horizontal_fence = NULL; p->client = NULL; p->window = XCB_NONE; p->action = ACTION_NONE; return p; } /* Returns true if a contains b */ bool contains(xcb_rectangle_t a, xcb_rectangle_t b) { return (a.x <= b.x && (a.x + a.width) >= (b.x + b.width) && a.y <= b.y && (a.y + a.height) >= (b.y + b.height)); } xcb_rectangle_t get_rectangle(client_t *c) { if (is_tiled(c)) return c->tiled_rectangle; else return c->floating_rectangle; } void get_side_handle(client_t *c, direction_t dir, xcb_point_t *pt) { xcb_rectangle_t rect = get_rectangle(c); switch (dir) { case DIR_RIGHT: pt->x = rect.x + rect.width; pt->y = rect.y + (rect.height / 2); break; case DIR_DOWN: pt->x = rect.x + (rect.width / 2); pt->y = rect.y + rect.height; break; case DIR_LEFT: pt->x = rect.x; pt->y = rect.y + (rect.height / 2); break; case DIR_UP: pt->x = rect.x + (rect.width / 2); pt->y = rect.y; break; } } void adopt_orphans(void) { xcb_query_tree_reply_t *qtr = xcb_query_tree_reply(dpy, xcb_query_tree(dpy, root), NULL); if (qtr == NULL) return; PUTS("adopt orphans"); int len = xcb_query_tree_children_length(qtr); xcb_window_t *wins = xcb_query_tree_children(qtr); for (int i = 0; i < len; i++) { uint32_t idx; xcb_window_t win = wins[i]; if (xcb_ewmh_get_wm_desktop_reply(ewmh, xcb_ewmh_get_wm_desktop(ewmh, win), &idx, NULL) == 1) schedule_window(win); } free(qtr); } void window_close(node_t *n) { if (n == NULL || n->client->locked) return; PRINTF("close window %X\n", n->client->window); send_client_message(n->client->window, ewmh->WM_PROTOCOLS, WM_DELETE_WINDOW); } void window_kill(monitor_t *m, desktop_t *d, node_t *n) { if (n == NULL) return; xcb_window_t win = n->client->window; PRINTF("kill window %X\n", win); xcb_kill_client(dpy, win); remove_node(m, d, n); } void set_fullscreen(node_t *n, bool value) { if (n == NULL || n->client->fullscreen == value) return; client_t *c = n->client; PRINTF("fullscreen %X: %s\n", c->window, BOOLSTR(value)); put_status(SBSC_MASK_WINDOW_STATE, "window_state fullscreen %s 0x%X\n", ONOFFSTR(value), c->window); c->fullscreen = value; if (value) ewmh_wm_state_add(c, ewmh->_NET_WM_STATE_FULLSCREEN); else ewmh_wm_state_remove(c, ewmh->_NET_WM_STATE_FULLSCREEN); stack(n, STACK_ABOVE); } void set_pseudo_tiled(node_t *n, bool value) { if (n == NULL || n->client->pseudo_tiled == value) return; client_t *c = n->client; PRINTF("pseudo-tiled %X: %s\n", c->window, BOOLSTR(value)); put_status(SBSC_MASK_WINDOW_STATE, "window_state pseudo_tiled %s 0x%X\n", ONOFFSTR(value), c->window); c->pseudo_tiled = value; } void set_floating(node_t *n, bool value) { if (n == NULL || n->client->fullscreen || n->client->floating == value) return; client_t *c = n->client; PRINTF("floating %X: %s\n", c->window, BOOLSTR(value)); put_status(SBSC_MASK_WINDOW_STATE, "window_state floating %s 0x%X\n", ONOFFSTR(value), c->window); n->split_mode = MODE_AUTOMATIC; c->floating = n->vacant = value; update_vacant_state(n->parent); if (value) { enable_floating_atom(c->window); unrotate_brother(n); } else { disable_floating_atom(c->window); rotate_brother(n); } stack(n, STACK_ABOVE); } void set_locked(monitor_t *m, desktop_t *d, node_t *n, bool value) { if (n == NULL || n->client->locked == value) return; client_t *c = n->client; PRINTF("set locked %X: %s\n", c->window, BOOLSTR(value)); put_status(SBSC_MASK_WINDOW_STATE, "window_state locked %s 0x%X\n", ONOFFSTR(value), c->window); c->locked = value; window_draw_border(n, d->focus == n, m == mon); } void set_sticky(monitor_t *m, desktop_t *d, node_t *n, bool value) { if (n == NULL || n->client->sticky == value) return; client_t *c = n->client; PRINTF("set sticky %X: %s\n", c->window, BOOLSTR(value)); put_status(SBSC_MASK_WINDOW_STATE, "window_state sticky %s 0x%X\n", ONOFFSTR(value), c->window); if (d != m->desk) transfer_node(m, d, n, m, m->desk, m->desk->focus); c->sticky = value; if (value) { ewmh_wm_state_add(c, ewmh->_NET_WM_STATE_STICKY); m->num_sticky++; } else { ewmh_wm_state_remove(c, ewmh->_NET_WM_STATE_STICKY); m->num_sticky--; } window_draw_border(n, d->focus == n, m == mon); } void set_private(monitor_t *m, desktop_t *d, node_t *n, bool value) { if (n == NULL || n->client->private == value) return; client_t *c = n->client; PRINTF("set private %X: %s\n", c->window, BOOLSTR(value)); put_status(SBSC_MASK_WINDOW_STATE, "window_state private %s 0x%X\n", ONOFFSTR(value), c->window); c->private = value; update_privacy_level(n, value); window_draw_border(n, d->focus == n, m == mon); } void set_urgency(monitor_t *m, desktop_t *d, node_t *n, bool value) { if (value && mon->desk->focus == n) return; n->client->urgent = value; window_draw_border(n, d->focus == n, m == mon); put_status(SBSC_MASK_WINDOW_STATE, "window_state urgent %s 0x%X\n", ONOFFSTR(value), n->client->window); put_status(SBSC_MASK_REPORT); } void set_floating_atom(xcb_window_t win, uint32_t value) { if (!apply_floating_atom) return; set_atom(win, _BSPWM_FLOATING_WINDOW, value); } void enable_floating_atom(xcb_window_t win) { set_floating_atom(win, 1); } void disable_floating_atom(xcb_window_t win) { set_floating_atom(win, 0); } uint32_t get_border_color(client_t *c, bool focused_window, bool focused_monitor) { if (c == NULL) return 0; uint32_t pxl = 0; if (focused_monitor && focused_window) { if (c->locked) get_color(focused_locked_border_color, c->window, &pxl); else if (c->sticky) get_color(focused_sticky_border_color, c->window, &pxl); else if (c->private) get_color(focused_private_border_color, c->window, &pxl); else get_color(focused_border_color, c->window, &pxl); } else if (focused_window) { if (c->urgent) get_color(urgent_border_color, c->window, &pxl); else if (c->locked) get_color(active_locked_border_color, c->window, &pxl); else if (c->sticky) get_color(active_sticky_border_color, c->window, &pxl); else if (c->private) get_color(active_private_border_color, c->window, &pxl); else get_color(active_border_color, c->window, &pxl); } else { if (c->urgent) get_color(urgent_border_color, c->window, &pxl); else if (c->locked) get_color(normal_locked_border_color, c->window, &pxl); else if (c->sticky) get_color(normal_sticky_border_color, c->window, &pxl); else if (c->private) get_color(normal_private_border_color, c->window, &pxl); else get_color(normal_border_color, c->window, &pxl); } return pxl; } void update_floating_rectangle(client_t *c) { xcb_get_geometry_reply_t *geo = xcb_get_geometry_reply(dpy, xcb_get_geometry(dpy, c->window), NULL); if (geo != NULL) c->floating_rectangle = (xcb_rectangle_t) {geo->x, geo->y, geo->width, geo->height}; free(geo); } void restrain_floating_width(client_t *c, int *width) { if (*width < 1) *width = 1; if (c->min_width > 0 && *width < c->min_width) *width = c->min_width; else if (c->max_width > 0 && *width > c->max_width) *width = c->max_width; } void restrain_floating_height(client_t *c, int *height) { if (*height < 1) *height = 1; if (c->min_height > 0 && *height < c->min_height) *height = c->min_height; else if (c->max_height > 0 && *height > c->max_height) *height = c->max_height; } void restrain_floating_size(client_t *c, int *width, int *height) { restrain_floating_width(c, width); restrain_floating_height(c, height); } void query_pointer(xcb_window_t *win, xcb_point_t *pt) { window_lower(motion_recorder); xcb_query_pointer_reply_t *qpr = xcb_query_pointer_reply(dpy, xcb_query_pointer(dpy, root), NULL); if (qpr != NULL) { if (win != NULL) *win = qpr->child; if (pt != NULL) *pt = (xcb_point_t) {qpr->root_x, qpr->root_y}; free(qpr); } window_raise(motion_recorder); } void window_border_width(xcb_window_t win, uint32_t bw) { uint32_t values[] = {bw}; xcb_configure_window(dpy, win, XCB_CONFIG_WINDOW_BORDER_WIDTH, values); } void window_move(xcb_window_t win, int16_t x, int16_t y) { uint32_t values[] = {x, y}; xcb_configure_window(dpy, win, XCB_CONFIG_WINDOW_X_Y, values); } void window_resize(xcb_window_t win, uint16_t w, uint16_t h) { uint32_t values[] = {w, h}; xcb_configure_window(dpy, win, XCB_CONFIG_WINDOW_WIDTH_HEIGHT, values); } void window_move_resize(xcb_window_t win, int16_t x, int16_t y, uint16_t w, uint16_t h) { uint32_t values[] = {x, y, w, h}; xcb_configure_window(dpy, win, XCB_CONFIG_WINDOW_X_Y_WIDTH_HEIGHT, values); } void window_raise(xcb_window_t win) { uint32_t values[] = {XCB_STACK_MODE_ABOVE}; xcb_configure_window(dpy, win, XCB_CONFIG_WINDOW_STACK_MODE, values); } void window_center(monitor_t *m, client_t *c) { xcb_rectangle_t *r = &c->floating_rectangle; xcb_rectangle_t a = m->rectangle; if (r->width >= a.width) r->x = a.x; else r->x = a.x + (a.width - r->width) / 2; if (r->height >= a.height) r->y = a.y; else r->y = a.y + (a.height - r->height) / 2; r->x -= c->border_width; r->y -= c->border_width; } void window_stack(xcb_window_t w1, xcb_window_t w2, uint32_t mode) { if (w2 == XCB_NONE) return; uint16_t mask = XCB_CONFIG_WINDOW_SIBLING | XCB_CONFIG_WINDOW_STACK_MODE; uint32_t values[] = {w2, mode}; xcb_configure_window(dpy, w1, mask, values); } void window_above(xcb_window_t w1, xcb_window_t w2) { window_stack(w1, w2, XCB_STACK_MODE_ABOVE); } void window_below(xcb_window_t w1, xcb_window_t w2) { window_stack(w1, w2, XCB_STACK_MODE_BELOW); } void window_lower(xcb_window_t win) { uint32_t values[] = {XCB_STACK_MODE_BELOW}; xcb_configure_window(dpy, win, XCB_CONFIG_WINDOW_STACK_MODE, values); } void window_set_visibility(xcb_window_t win, bool visible) { uint32_t values_off[] = {ROOT_EVENT_MASK & ~XCB_EVENT_MASK_SUBSTRUCTURE_NOTIFY}; uint32_t values_on[] = {ROOT_EVENT_MASK}; xcb_change_window_attributes(dpy, root, XCB_CW_EVENT_MASK, values_off); if (visible) xcb_map_window(dpy, win); else xcb_unmap_window(dpy, win); xcb_change_window_attributes(dpy, root, XCB_CW_EVENT_MASK, values_on); } void window_hide(xcb_window_t win) { PRINTF("window hide %X\n", win); window_set_visibility(win, false); } void window_show(xcb_window_t win) { PRINTF("window show %X\n", win); window_set_visibility(win, true); } void toggle_visibility(void) { visible = !visible; if (!visible) clear_input_focus(); for (monitor_t *m = mon_head; m != NULL; m = m->next) for (node_t *n = first_extrema(m->desk->root); n != NULL; n = next_leaf(n, m->desk->root)) window_set_visibility(n->client->window, visible); if (visible) update_input_focus(); } void enable_motion_recorder(void) { PUTS("motion recorder on"); window_raise(motion_recorder); window_show(motion_recorder); } void disable_motion_recorder(void) { PUTS("motion recorder off"); window_hide(motion_recorder); } void update_motion_recorder(void) { xcb_get_geometry_reply_t *geo = xcb_get_geometry_reply(dpy, xcb_get_geometry(dpy, root), NULL); if (geo != NULL) { window_resize(motion_recorder, geo->width, geo->height); PRINTF("update motion recorder size: %ux%u\n", geo->width, geo->height); } free(geo); } void update_input_focus(void) { set_input_focus(mon->desk->focus); } void set_input_focus(node_t *n) { if (n == NULL) { clear_input_focus(); } else { if (n->client->icccm_focus) send_client_message(n->client->window, ewmh->WM_PROTOCOLS, WM_TAKE_FOCUS); xcb_set_input_focus(dpy, XCB_INPUT_FOCUS_POINTER_ROOT, n->client->window, XCB_CURRENT_TIME); } } void clear_input_focus(void) { xcb_set_input_focus(dpy, XCB_INPUT_FOCUS_POINTER_ROOT, root, XCB_CURRENT_TIME); } void center_pointer(xcb_rectangle_t r) { int16_t cx = r.x + r.width / 2; int16_t cy = r.y + r.height / 2; window_lower(motion_recorder); xcb_warp_pointer(dpy, XCB_NONE, root, 0, 0, 0, 0, cx, cy); window_raise(motion_recorder); } void get_atom(char *name, xcb_atom_t *atom) { xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(dpy, xcb_intern_atom(dpy, 0, strlen(name), name), NULL); if (reply != NULL) *atom = reply->atom; else *atom = XCB_NONE; free(reply); } void set_atom(xcb_window_t win, xcb_atom_t atom, uint32_t value) { xcb_change_property(dpy, XCB_PROP_MODE_REPLACE, win, atom, XCB_ATOM_CARDINAL, 32, 1, &value); } bool has_proto(xcb_atom_t atom, xcb_icccm_get_wm_protocols_reply_t *protocols) { for (uint32_t i = 0; i < protocols->atoms_len; i++) if (protocols->atoms[i] == atom) return true; return false; } void send_client_message(xcb_window_t win, xcb_atom_t property, xcb_atom_t value) { xcb_client_message_event_t e; e.response_type = XCB_CLIENT_MESSAGE; e.window = win; e.format = 32; e.sequence = 0; e.type = property; e.data.data32[0] = value; e.data.data32[1] = XCB_CURRENT_TIME; xcb_send_event(dpy, false, win, XCB_EVENT_MASK_NO_EVENT, (char *) &e); }
azuwis/debian_bspwm
helpers.c
/* Copyright (c) 2012, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdlib.h> #include <string.h> #include <math.h> #include "bspwm.h" void warn(char *fmt, ...) { va_list ap; va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); } __attribute__((noreturn)) void err(char *fmt, ...) { va_list ap; va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); exit(EXIT_FAILURE); } bool get_color(char *col, xcb_window_t win, uint32_t *pxl) { xcb_colormap_t map = screen->default_colormap; xcb_get_window_attributes_reply_t *reply = xcb_get_window_attributes_reply(dpy, xcb_get_window_attributes(dpy, win), NULL); if (reply != NULL) map = reply->colormap; free(reply); if (col[0] == '#') { unsigned int red, green, blue; if (sscanf(col + 1, "%02x%02x%02x", &red, &green, &blue) == 3) { /* 2**16 - 1 == 0xffff and 0x101 * 0xij == 0xijij */ red *= 0x101; green *= 0x101; blue *= 0x101; xcb_alloc_color_reply_t *reply = xcb_alloc_color_reply(dpy, xcb_alloc_color(dpy, map, red, green, blue), NULL); if (reply != NULL) { *pxl = reply->pixel; free(reply); return true; } } } else { xcb_alloc_named_color_reply_t *reply = xcb_alloc_named_color_reply(dpy, xcb_alloc_named_color(dpy, map, strlen(col), col), NULL); if (reply != NULL) { *pxl = reply->pixel; free(reply); return true; } } *pxl = 0; return false; } double distance(xcb_point_t a, xcb_point_t b) { return hypot(a.x - b.x, a.y - b.y); }
azuwis/debian_bspwm
messages.h
<gh_stars>1-10 /* Copyright (c) 2012, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 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. */ #ifndef BSPWM_MESSAGES_H #define BSPWM_MESSAGES_H #include "types.h" #include "subscribe.h" #define OPT_CHR '-' #define CAT_CHR '.' #define EQL_TOK "=" int handle_message(char *msg, int msg_len, FILE *rsp); int process_message(char **args, int num, FILE *rsp); int cmd_window(char **args, int num); int cmd_desktop(char **args, int num); int cmd_monitor(char **args, int num); int cmd_query(char **args, int num, FILE *rsp); int cmd_rule(char **args, int num, FILE *rsp); int cmd_pointer(char **args, int num); int cmd_restore(char **args, int num); int cmd_control(char **args, int num, FILE *rsp); int cmd_config(char **args, int num, FILE *rsp); int cmd_quit(char **args, int num); int set_setting(coordinates_t loc, char *name, char *value); int get_setting(coordinates_t loc, char *name, FILE* rsp); bool parse_subscriber_mask(char *s, subscriber_mask_t *mask); bool parse_bool(char *value, bool *b); bool parse_layout(char *s, layout_t *l); bool parse_direction(char *s, direction_t *d); bool parse_cycle_direction(char *s, cycle_dir_t *d); bool parse_circulate_direction(char *s, circulate_dir_t *d); bool parse_history_direction(char *s, history_dir_t *d); bool parse_flip(char *s, flip_t *f); bool parse_pointer_action(char *s, pointer_action_t *a); bool parse_child_polarity(char *s, child_polarity_t *p); bool parse_degree(char *s, int *d); bool parse_window_id(char *s, long int *i); bool parse_bool_declaration(char *s, char **key, bool *value, alter_state_t *state); bool parse_index(char *s, int *i); #endif
azuwis/debian_bspwm
stack.c
/* Copyright (c) 2012, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdlib.h> #include "bspwm.h" #include "window.h" #include "stack.h" stacking_list_t *make_stack(node_t *n) { stacking_list_t *s = malloc(sizeof(stacking_list_t)); s->node = n; s->prev = s->next = NULL; return s; } void stack_insert_after(stacking_list_t *a, node_t *n) { stacking_list_t *s = make_stack(n); if (a == NULL) { stack_head = stack_tail = s; } else { if (a->node == n) return; remove_stack_node(n); stacking_list_t *b = a->next; if (b != NULL) b->prev = s; s->next = b; s->prev = a; a->next = s; if (stack_tail == a) stack_tail = s; } } void stack_insert_before(stacking_list_t *a, node_t *n) { stacking_list_t *s = make_stack(n); if (a == NULL) { stack_head = stack_tail = s; } else { if (a->node == n) return; remove_stack_node(n); stacking_list_t *b = a->prev; if (b != NULL) b->next = s; s->prev = b; s->next = a; a->prev = s; if (stack_head == a) stack_head = s; } } void remove_stack(stacking_list_t *s) { if (s == NULL) return; stacking_list_t *a = s->prev; stacking_list_t *b = s->next; if (a != NULL) a->next = b; if (b != NULL) b->prev = a; if (s == stack_head) stack_head = b; if (s == stack_tail) stack_tail = a; free(s); } void remove_stack_node(node_t *n) { for (stacking_list_t *s = stack_head; s != NULL; s = s->next) if (s->node == n) { remove_stack(s); return; } } void stack(node_t *n, stack_flavor_t f) { PRINTF("stack %X\n", n->client->window); if (stack_head == NULL) { stack_insert_after(NULL, n); } else if (n->client->fullscreen) { if (f == STACK_ABOVE) { stack_insert_after(stack_tail, n); window_raise(n->client->window); } } else { if (f == STACK_ABOVE && n->client->floating && !auto_raise) return; stacking_list_t *latest_tiled = NULL; stacking_list_t *oldest_floating = NULL; stacking_list_t *oldest_fullscreen = NULL; for (stacking_list_t *s = (f == STACK_ABOVE ? stack_tail : stack_head); s != NULL; s = (f == STACK_ABOVE ? s->prev : s->next)) { if (s->node != n) { if (s->node->client->fullscreen) { if (oldest_fullscreen == NULL) oldest_fullscreen = s; continue; } if (s->node->client->floating == n->client->floating) { if (f == STACK_ABOVE) { stack_insert_after(s, n); window_above(n->client->window, s->node->client->window); } else { stack_insert_before(s, n); window_below(n->client->window, s->node->client->window); } return; } else if ((f != STACK_ABOVE || latest_tiled == NULL) && !s->node->client->floating) { latest_tiled = s; } else if ((f == STACK_ABOVE || oldest_floating == NULL) && s->node->client->floating) { oldest_floating = s; } } } if (latest_tiled == NULL && oldest_floating == NULL && oldest_fullscreen == NULL) return; if (n->client->floating) { if (latest_tiled != NULL) { window_above(n->client->window, latest_tiled->node->client->window); stack_insert_after(latest_tiled, n); } else if (oldest_fullscreen != NULL) { window_below(n->client->window, oldest_fullscreen->node->client->window); stack_insert_before(oldest_fullscreen, n); } } else { if (oldest_floating != NULL) { window_below(n->client->window, oldest_floating->node->client->window); stack_insert_before(oldest_floating, n); } else if (oldest_fullscreen != NULL) { window_below(n->client->window, oldest_fullscreen->node->client->window); stack_insert_before(oldest_fullscreen, n); } } } }
azuwis/debian_bspwm
helpers.h
<gh_stars>1-10 /* Copyright (c) 2012, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 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. */ #ifndef BSPWM_HELPERS_H #define BSPWM_HELPERS_H #include <xcb/xcb.h> #include <stdarg.h> #include <stdio.h> #include <stdbool.h> #include <stdint.h> #define LENGTH(x) (sizeof(x) / sizeof(*x)) #define MAX(A, B) ((A) > (B) ? (A) : (B)) #define MIN(A, B) ((A) < (B) ? (A) : (B)) #define BOOLSTR(A) ((A) ? "true" : "false") #define ONOFFSTR(A) ((A) ? "on" : "off") #define XCB_CONFIG_WINDOW_X_Y XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y #define XCB_CONFIG_WINDOW_WIDTH_HEIGHT XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT #define XCB_CONFIG_WINDOW_X_Y_WIDTH_HEIGHT XCB_CONFIG_WINDOW_X | XCB_CONFIG_WINDOW_Y | XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT #define MAXLEN 256 #define SMALEN 32 #define INIT_CAP 8 #define streq(s1, s2) (strcmp((s1), (s2)) == 0) #ifdef DEBUG # define PUTS(x) puts(x) # define PRINTF(x,...) printf(x, __VA_ARGS__) #else # define PUTS(x) ((void)0) # define PRINTF(x,...) ((void)0) #endif void warn(char *fmt, ...); void err(char *fmt, ...); bool get_color(char *col, xcb_window_t win, uint32_t *pxl); double distance(xcb_point_t a, xcb_point_t b); #endif
azuwis/debian_bspwm
settings.h
/* Copyright (c) 2012, <NAME> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 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. */ #ifndef BSPWM_SETTINGS_H #define BSPWM_SETTINGS_H #include "types.h" #define WM_NAME "bspwm" #define CONFIG_NAME WM_NAME "rc" #define CONFIG_HOME_ENV "XDG_CONFIG_HOME" #define EXTERNAL_RULES_COMMAND "" #define STATUS_PREFIX "W" #define FOCUSED_BORDER_COLOR "#7E7F89" #define ACTIVE_BORDER_COLOR "#545350" #define NORMAL_BORDER_COLOR "#3F3E3B" #define PRESEL_BORDER_COLOR "#E8E8F4" #define FOCUSED_LOCKED_BORDER_COLOR "#C7B579" #define ACTIVE_LOCKED_BORDER_COLOR "#545350" #define NORMAL_LOCKED_BORDER_COLOR "#3F3E3B" #define FOCUSED_STICKY_BORDER_COLOR "#E3A5DA" #define ACTIVE_STICKY_BORDER_COLOR "#545350" #define NORMAL_STICKY_BORDER_COLOR "#3F3E3B" #define FOCUSED_PRIVATE_BORDER_COLOR "#42CAD9" #define ACTIVE_PRIVATE_BORDER_COLOR "#5C5955" #define NORMAL_PRIVATE_BORDER_COLOR "#34322E" #define URGENT_BORDER_COLOR "#EFA29A" #define SPLIT_RATIO 0.5 #define WINDOW_GAP 6 #define BORDER_WIDTH 1 #define HISTORY_AWARE_FOCUS false #define FOCUS_BY_DISTANCE false #define BORDERLESS_MONOCLE false #define GAPLESS_MONOCLE false #define LEAF_MONOCLE false #define FOCUS_FOLLOWS_POINTER false #define POINTER_FOLLOWS_FOCUS false #define POINTER_FOLLOWS_MONITOR false #define AUTO_ALTERNATE false #define AUTO_CANCEL false #define APPLY_FLOATING_ATOM false #define IGNORE_EWMH_FOCUS false #define CENTER_PSEUDO_TILED true #define REMOVE_DISABLED_MONITORS false #define REMOVE_UNPLUGGED_MONITORS false #define MERGE_OVERLAPPING_MONITORS false char external_rules_command[MAXLEN]; char status_prefix[MAXLEN]; char focused_border_color[MAXLEN]; char active_border_color[MAXLEN]; char normal_border_color[MAXLEN]; char presel_border_color[MAXLEN]; char focused_locked_border_color[MAXLEN]; char active_locked_border_color[MAXLEN]; char normal_locked_border_color[MAXLEN]; char focused_sticky_border_color[MAXLEN]; char active_sticky_border_color[MAXLEN]; char normal_sticky_border_color[MAXLEN]; char focused_private_border_color[MAXLEN]; char active_private_border_color[MAXLEN]; char normal_private_border_color[MAXLEN]; char urgent_border_color[MAXLEN]; double split_ratio; int window_gap; unsigned int border_width; child_polarity_t initial_polarity; bool borderless_monocle; bool gapless_monocle; bool leaf_monocle; bool focus_follows_pointer; bool pointer_follows_focus; bool pointer_follows_monitor; bool apply_floating_atom; bool auto_alternate; bool auto_cancel; bool history_aware_focus; bool focus_by_distance; bool ignore_ewmh_focus; bool center_pseudo_tiled; bool remove_disabled_monitors; bool remove_unplugged_monitors; bool merge_overlapping_monitors; void run_config(void); void load_settings(void); #endif
vnm-interactive/Grove
src/Grove.h
<gh_stars>1-10 /* Copyright (c) 2015 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once //#define RES_CAPPING //#define DEBUG_OUTPUT #include "cinder/app/App.h" #include "cinder/app/RendererGl.h" #include "cinder/gl/Batch.h" #include "cinder/gl/Texture.h" #include "cinder/gl/Shader.h" #include "cinder/gl/Fbo.h" #include "cinder/Camera.h" #include "cinder/CameraUI.h" #include "Terrain.h" #include "UserInterface.h" #include "GestureManager.h" class Grove : public ci::app::App { public: // initialization Grove(); void setupUi(); void setupRendering(); void setupFbo(); void setupCamera(); // update & draw void update() override; void draw() override; void resize() override; // interactions void edit( const Touch &touch ); void editTrees(); void editTerrain(); void randomizeSunColor(); void randomizeFogColor(); void randomizeScatteringColor(); // gestures void tap( const Touch &touch ); void doubleTap( const Touch &touch ); void pan( const Touch &touch ); void panBegan( const Touch &touch ); void panEnded( const Touch &touch ); // picking and pixel data methods ci::vec4 getPixelData( const ci::vec2 &position, const ci::CameraPersp &cam ); Touch::Type getPixelDataType( const ci::vec4 &data ); // ui void createMenuModal( const std::string &name, ci::Rectf *rectangle, ci::vec2 *offset, const WidgetRef &menu = nullptr, const std::function<void()> &cancel = nullptr, const std::function<void()> &confirm = nullptr, bool adaptBackgroundColor = true ); // camera ci::CameraPersp mCamera; ci::CameraUi mCameraUi; ci::CameraPersp mCameraUiCam; ci::vec3 mCameraInitialViewDir; float mCameraSplinePos; float mCameraSplineDestination; ci::vec3 mCameraDestination; ci::quat mCameraOrientation; ci::quat mGyroInitialOrientation; // rendering ci::gl::FboRef mFbo; ci::gl::Texture2dRef mFboColorAtt; ci::gl::Texture2dRef mFboDepthAtt; ci::gl::GlslProgRef mPostProcessing; // frame time float mLastTime; float mCurrentTime; float mFrameTime; // terrain TerrainRef mTerrain; float mElevation; ci::vec3 mSunDirection; float mFogDensity; ci::Color mFogColor; ci::Color mSunColor; ci::vec3 mSunScatteringCoeffs; float mSunDispertion; float mSunIntensity; float mRandomSeed; bool mEditingTerrain; // touches, gestures and gyro GestureManagerRef mGestureManager; bool mGyroEnabled; // ui related stuffs WidgetRef mWidget, mOpenMenuButton, mMenu, mDebugMenu; ci::gl::Texture2dRef mIntroTexture[4], mInfoTexture, mTwitterTexture, mWallpaperTexture, mCompassTexture[2]; ci::vec2 mInfoOffset, mTwitterOffset, mWallpaperOffset, mCompassOffset; ci::Rectf mIntroRect[4], mInfoRect, mTwitterRect, mWallpaperRect, mCompassRect; float mIntroOpacity[4]; bool mIntro, mModal; bool mCopySurfaceToTwitter, mCopySurfaceToWallpaper; };
vnm-interactive/Grove
src/GestureManager.h
/* Copyright (c) 2015 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #include "cinder/app/App.h" #include "cinder/gl/Fbo.h" #include "cinder/Vector.h" #include "cinder/Signals.h" struct Touch { enum Type { TOUCH_TERRAIN, TOUCH_ROAD, TOUCH_TREE, TOUCH_SKY, TOUCH_SUN, TOUCH_UNDEFINED }; Touch(); uint32_t mId; Type mType; double mTimeOfBirth; double mTimeOfDeath; float mDistanceTraveled; ci::vec2 mPos2d, mPrevPos2d, mInitialPos2d; ci::vec3 mPos3d; bool mIsPan, mIsDoubleTap; }; typedef std::shared_ptr<class GestureManager> GestureManagerRef; class GestureManager { public: static GestureManagerRef create( const ci::app::WindowRef &window ); GestureManager( const ci::app::WindowRef &window ); typedef ci::signals::Signal<void(const Touch&)> GestureSignal; GestureSignal& getTapSignal() { return mTapSignal; } GestureSignal& getDoubleTapSignal() { return mDoubleTapSignal; } GestureSignal& getPanSignal() { return mPanSignal; } GestureSignal& getPanBeganSignal() { return mPanBeganSignal; } GestureSignal& getPanEndedSignal() { return mPanEndedSignal; } bool isPanning() const { return mIsPanning; } protected: void update(); void touchesBegan( ci::app::TouchEvent &event ); void touchesMoved( ci::app::TouchEvent &event ); void touchesEnded( ci::app::TouchEvent &event ); GestureSignal mTapSignal; GestureSignal mDoubleTapSignal; GestureSignal mPanSignal; GestureSignal mPanBeganSignal; GestureSignal mPanEndedSignal; std::map<uint32_t, Touch> mTouches; bool mIsPanning; };
vnm-interactive/Grove
src/Terrain.h
<gh_stars>1-10 /* Copyright (c) 2015 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #include "cinder/gl/Texture.h" #include "cinder/gl/Shader.h" #include "cinder/gl/GlslProg.h" #include "cinder/gl/Batch.h" #include "cinder/BSpline.h" #include "cinder/Channel.h" #include "cinder/ConcurrentCircularBuffer.h" #include "cinder/Signals.h" #include "cinder/TriMesh.h" #include "cinder/Timeline.h" //#define HIGH_QUALITY_ANIMATIONS //#define WIP typedef std::shared_ptr<class Terrain> TerrainRef; class Terrain : public std::enable_shared_from_this<Terrain>{ public: struct Format { Format() : mSize( 850 ), mElevation( 120.0f ), mNoiseOctaves( 8 ), mNoiseScale( 5.0f ), mNoiseSeed( 1 ), mRoadBlurIterations( 4 ), mBlurIterations( 15 ), mSobelBlurIterations( 5 ), mNumTilesPerRow( 5 ), mNumWorkingThreads( 8 ) {} //! specifies the size and resolution of the terrain Format& size( const ci::vec2 &size ) { mSize = size; return *this; } //! specifies the terrain elevation Format& elevation( const float &aElevation ) { mElevation = aElevation; return *this; } //! specifies the number of octaves to be used in the noise sum generation Format& noiseOctaves( int octaves ) { mNoiseOctaves = octaves; return *this; } //! specifies the scale to be used in the noise sum generation Format& noiseScale( float scale ) { mNoiseScale = scale; return *this; } //! specifies the random seed to be used in the noise sum generation Format& noiseSeed( float seed ) { mNoiseSeed = seed; return *this; } //! specifies the number of working threads for the triangulation, mesh and object distribution Format& workingThreads( size_t threads ) { mNumWorkingThreads = threads; return *this; } //! specifies the number of tiles per row, impacts both the performances and the threading efficiency Format& tilesPerRow( size_t tiles ) { mNumTilesPerRow = tiles; return *this; } //! specifies the number of times the road has to be blurred before being integrated in the heightmap Format& roadBlurIterations( int iterations ) { mRoadBlurIterations = iterations; return *this; } //! specifies the random seed to be used in the noise sum generation Format& blurIterations( int iterations ) { mBlurIterations = iterations; return *this; } //! specifies the random seed to be used in the noise sum generation Format& sobelBlurIterations( int iterations ) { mSobelBlurIterations = iterations; return *this; } //! returns the size and resolution of the terrain ci::vec2 getSize() const { return mSize; } //! returns the terrain elevation float getElevation() const { return mElevation * 1.3333f; } //! returns the number of octaves to be used in the noise sum generation int getNoiseOctaves() const { return mNoiseOctaves; } //! returns the scale to be used in the noise sum generation float getNoiseScale() const { return mNoiseScale; } //! returns the random seed to be used in the noise sum generation float getNoiseSeed() const { return mNoiseSeed; } //! returns the number of working threads for the triangulation, mesh and object distribution size_t getNumWorkingThreads() const { return mNumWorkingThreads; } //! returns the number of tiles per row, impacts both the performances and the threading efficiency size_t getNumTilesPerRow() const { return mNumTilesPerRow; } //! returns the random seed to be used in the noise sum generation int getRoadBlurIterations() const { return mRoadBlurIterations; } //! returns the random seed to be used in the noise sum generation int getBlurIterations() const { return mBlurIterations; } //! returns the random seed to be used in the noise sum generation int getSobelBlurIterations() const { return mSobelBlurIterations; } protected: size_t mNumTilesPerRow; size_t mNumWorkingThreads; ci::vec2 mSize; float mElevation; int mNoiseOctaves; float mNoiseScale; float mNoiseSeed; int mRoadBlurIterations; int mBlurIterations; int mSobelBlurIterations; }; //! constructs and returns a new terrain static TerrainRef create( const Format &format = Format() ); //! renders the terrain from the camera point of view void render( const ci::CameraPersp &camera ); //! starts the generation process void start(); //! regenerate the population content of each tiles void generateTilesPopulation(); //! removes the population content of each tiles void removeTilesPopulation(); //! removes the old population and regenerate with new population for of each tiles void regenerateTilesPopulation(); void createTiles(); void generateHeightMap(); void generateTriangleHeightMap(); //! sets the terrain elevation void setElevation( float elevation ); //! sets the fog density void setFogDensity( float density ); //! sets the fog color void setFogColor( const ci::Color &color ); //! sets the dispertion of the color of the sun void setSunDispertion( float dispertion ); //! sets the intensity of the sun void setSunIntensity( float intensity ); //! sets the sun color void setSunColor( const ci::Color &color ); //! sets the sun position in the sky void setSunDirection( const ci::vec3 &direction ); //! sets the atmospheric scattering coefficients void setSunScatteringCoeffs( const ci::vec3 &coeffs ); //! returns the size and resolution of the terrain ci::vec2 getSize() const { return mSize; } //! returns the terrain elevation float getElevation() const { return mElevation; } //! returns the fog density float getFogDensity() const; //! returns the fog color ci::Color getFogColor() const; //! returns the dispertion of the color of the sun float getSunDispertion() const; //! returns the intensity of the sun float getSunIntensity() const; //! returns the sun color ci::Color getSunColor() const; //! returns the sun position in the sky ci::vec3 getSunDirection() const; //! return the atmospheric scattering coefficients ci::vec3 getSunScatteringCoeffs() const; //! returns the height map texture ci::gl::Texture2dRef getHeightMap() const { return mHeightMap[mHeightMapCurrent]; } //! downloads and returns the cpu version of the height map texture ci::Channel32fRef getHeightChannel(); //! returns the mesh density texture ci::gl::Texture2dRef getMeshDensityMap() const { return mMeshDensityMap; } //! downloads and returns the cpu version of the mesh density texture ci::Channel32fRef getMeshDensityChannel(); //! returns the tree distribution map ci::gl::Texture2dRef getFloraDensityMap() const { return mFloraDensityMap; } //! downloads and returns the cpu version of the tree distribution map ci::Channel32fRef getFloraDensityChannel(); //! returns the actual triangle height map ci::gl::Texture2dRef getTrianglesHeightMap() const { return mTrianglesHeightMap[mHeightMapCurrent]; } //! downloads and returns the cpu version of the actual triangle height map ci::Channel32fRef getTrianglesHeightChannel(); //! returns the 2d b-spline representing the road ci::BSpline2f getRoadSpline2d() const { return mRoadSpline2d; } //! returns the 3d b-spline representing the road ci::BSpline3f getRoadSpline3d( int spline = -1 ) const { return mRoadSpline3d[spline == -1 ? mHeightMapCurrent : spline ]; } //! returns the 3d b-spline total length float getRoadSpline3dLength() const { return mRoadSpline3dLength; } //! returns the number of working threads for the triangulation, mesh and object distribution size_t getNumWorkingThreads() const { return mNumWorkingThreads; } //! returns the number of tiles per row, impacts both the performances and the threading efficiency size_t getNumTilesPerRow() const { return mNumTilesPerRow; } //! represents a single tile of the terrain class Tile { public: static std::shared_ptr<Terrain::Tile> create( size_t tileId, const ci::Area &tileArea, const ci::Area &fullArea, float contentScale, float randomSeed, const ci::Channel32fRef &heightMap, const ci::Channel32fRef &densityMap, const ci::BSpline2f &spline, size_t tilesPerRow, float elevation ); size_t getTileId() const { return mTileId; } ci::gl::BatchRef getBatch() const { return mBatch; } ci::gl::BatchRef getPopulationBatch() const { return mPopulation[mPopulationCurrent]; } ci::Area getArea() const { return mArea; } ci::vec2 getSize() const { return mSize; } ci::AxisAlignedBox getBounds( float elevation = 1.0f, float interpolation = 1.0f ) const; //! returns whether this tile has been occluded for a certain amount of frames bool isOccluded( size_t numFrames = 5 ); Tile( size_t tileId, const ci::Area &tileArea, const ci::Area &fullArea, float contentScale, float randomSeed, const ci::Channel32fRef &heightMap, const ci::Channel32fRef &densityMap, const ci::BSpline2f &spline, size_t tilesPerRow, float elevation ); ~Tile(); void clear(); void clearPopulation(); void updateBounds( const std::vector<ci::vec2> &samples, const ci::Channel32fRef &heightMap, const ci::Area &fullArea ); void swapBounds(); protected: void buildMeshes( const ci::gl::GlslProgRef &shader ); void buildOcclusionMesh(); void buildPopulationMeshes( const ci::TriMeshRef &triMesh, const ci::AxisAlignedBox &bounds, const ci::gl::GlslProgRef &shader ); void resetOccludedFrameCount(); void checkOcclusion(); void queryOcclusionResults(); size_t mTileId; ci::AxisAlignedBox mBounds[2]; ci::vec2 mHeightRange[2]; ci::gl::BatchRef mBatch; ci::gl::BatchRef mPopulation[2]; size_t mPopulationCurrent, mPopulationTemp; ci::gl::BatchRef mOccluderBatch; ci::vec3 mPosition; struct OcclusionQuery { OcclusionQuery() : mId(0), mUsed(false) {} GLuint mId; bool mUsed; }; std::vector<OcclusionQuery> mOcclusionQueries; float mTerrainCompletion; float mPopulationCompletion[2]; size_t mNumFramesOccluded; ci::Area mArea; ci::vec2 mSize; ci::TriMesh mTriMesh; int numTrees = 0; friend class Terrain; }; typedef std::shared_ptr<Tile> TileRef; void setTileExplosionCenter( const ci::vec3 &center ) { mTileExplosionCenter = center; } ci::vec3& getTileExplosionCenter() { return mTileExplosionCenter; } void setTilePopulationExplosionCenter( const ci::vec3 &center ) { mTilePopulationExplosionCenter = center; } ci::vec3& getTilePopulationExplosionCenter() { return mTilePopulationExplosionCenter; } float& getTileExplosionSize() { return mTileExplosionSize; } float& getTilePopulationExplosionSize() { return mTilePopulationExplosionSize; } float getTilePopulationBalance() const { return mTilePopulationBalance; } void setTilePopulationBalance( float balance ) { mTilePopulationBalance = balance; } //! returns the terrain's tiles const std::vector<TileRef>& getTiles() const { return mTiles; } //! returns the shader that takes care of rendering the actual terrain ci::gl::GlslProgRef getTileShader() const { return mTileShader; } //! returns the shader that takes care of rendering the tiles instanced content ci::gl::GlslProgRef getTileContentShader() const { return mTileContentShader; } //! returns the percentage of tiles that have been built already (between 0 and 1) float getTilesThreadsCompletion(); //! TODO: Comment float getHeightMapProgression() const { return mHeightMapProgression; } //! sets the number of octaves to be used in the noise sum generation void setNumNoiseOctaves( int octaves ) { mNoiseOctaves = octaves; } //! sets the scale to be used in the noise sum generation void setNoiseScale( float scale ) { mNoiseScale = scale; } //! sets the random seed to be used in the noise sum generation void setNoiseSeed( float seed ) { mNoiseSeed = seed; } //! sets the number of times the road has to be blurred before being integrated in the heightmap void setNumRoadBlurIterations( int iterations ) { mRoadBlurIterations = iterations; } //! sets the random seed to be used in the noise sum generation void setNumBlurIterations( int iterations ) { mBlurIterations = iterations; } //! sets the random seed to be used in the noise sum generation void setNumSobelBlurIterations( int iterations ) { mSobelBlurIterations = iterations; } //! returns whether the occlusion culling pass is enabled or not bool isOcclusionCullingEnabled() const { return mOcclusionCullingEnabled; } //! sets whether the occlusion culling pass is enabled or not void setOcclusionCullingEnabled( bool enabled = true ) { mOcclusionCullingEnabled = enabled; } //! returns the total number of instances rendered in the last frame for debug size_t getNumRenderedInstances() const { return mNumRenderedInstanced; } // keep the constructor public but make it unacessible // solves the private constructor std::make_shared issue protected: struct LeaveMeAlone {}; public: Terrain( const Format &format, LeaveMeAlone access ); ~Terrain(); //protected: void updateTiles(); void buildTilesThreaded( size_t start, size_t end, size_t numTilesPerRow, const ci::vec2 &tileSize, const ci::Area &area, float scale, const ci::Channel32fRef &heightMap, const ci::Channel32fRef &densityMap ); void populateTiles(); void updateTilePopulating(); void populateTilesThreaded( size_t start, size_t end, size_t numTilesPerRow, const ci::vec2 &tileSize, const ci::Area &area, const ci::Channel32fRef &floraMap ); void updateTilesBounds(); struct PopulationData { size_t mTileId; ci::TriMeshRef mTriMesh; ci::AxisAlignedBox mBounds; }; typedef std::shared_ptr<PopulationData> PopulationDataRef; // a few useful type aliases using CircularTileBuffer = ci::ConcurrentCircularBuffer<TileRef>; using CircularTileBufferRef = std::unique_ptr<CircularTileBuffer>; using TileWorkThreads = std::vector<std::unique_ptr<std::thread>>; using CircularPopulationBuffer = ci::ConcurrentCircularBuffer<PopulationDataRef>; using CircularPopulationBufferRef = std::unique_ptr<CircularPopulationBuffer>; ci::Area mArea; ci::vec2 mSize; float mElevation; int mNoiseOctaves; float mNoiseScale; float mNoiseSeed; int mRoadBlurIterations; int mBlurIterations; int mSobelBlurIterations; float mFogDensity; ci::Color mFogColor; float mSunDispertion; float mSunIntensity; ci::Color mSunColor; ci::vec3 mSunDirection; ci::vec3 mSunScatteringCoeffs; size_t mNumTilesPerRow; size_t mNumTilePopulated; size_t mNumWorkingThreads; CircularTileBufferRef mTilesBuffer; CircularPopulationBufferRef mTilesPopulationBuffer; TileWorkThreads mWorkThreads; ci::signals::Connection mUpdateTilesConnection; std::vector<TileRef> mTiles; ci::BSpline2f mRoadSpline2d; ci::BSpline3f mRoadSpline3d[2]; float mRoadSpline3dLength; ci::gl::Texture2dRef mHeightMap[2]; ci::gl::Texture2dRef mTrianglesHeightMap[2]; size_t mHeightMapCurrent; size_t mHeightMapTemp; float mHeightMapProgression; ci::gl::Texture2dRef mMeshDensityMap; ci::gl::Texture2dRef mFloraDensityMap; ci::gl::Texture2dRef mNoiseLookupTable; ci::gl::GlslProgRef mTileShader; ci::gl::GlslProgRef mTileContentShader; ci::gl::GlslProgRef mSkyShader; //ci::gl::GlslProgRef mClearingObjectsShader; ci::gl::BatchRef mSkyBatch; std::vector<ci::TriMesh> mPopulationMeshes; #ifdef WIP //std::vector<ci::vec3> mClearings; //std::vector<ci::gl::BatchRef> mClearingsBatches; #endif ci::TimelineRef mTimeline; bool mBuildingTiles; bool mPopulatingTiles; ci::vec3 mTileExplosionCenter; ci::vec3 mTilePopulationExplosionCenter; float mTileExplosionSize; float mTilePopulationExplosionSize; float mTilePopulationBalance; bool mOcclusionCullingEnabled; size_t mNumRenderedInstanced; };
vnm-interactive/Grove
src/UserInterface.h
<filename>src/UserInterface.h /* Copyright (c) 2015 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #include <memory> #include "cinder/Rect.h" #include "cinder/Vector.h" #include "cinder/Signals.h" #include "cinder/app/App.h" #include "cinder/gl/Texture.h" typedef std::shared_ptr<class WidgetItem> WidgetItemRef; typedef std::shared_ptr<class Widget> WidgetRef; typedef std::function<void(const class WidgetEvent &event)> WidgetCallback; class WidgetEvent { public: WidgetEvent( const ci::vec2 &pos, const WidgetRef &widget, const WidgetItemRef &item ) : mPos( pos ), mWidget( widget ), mItem( item ) {} ci::vec2 getPos() const { return mPos; } WidgetItemRef getItem() const { return mItem; } WidgetRef getWidget() const { return mWidget; } protected: ci::vec2 mPos; WidgetItemRef mItem; WidgetRef mWidget; }; class WidgetItem : public std::enable_shared_from_this<WidgetItem> { public: static WidgetItemRef create( const WidgetRef &parent, const std::string &name, const ci::vec2 &position, float delay = 0.0f, const WidgetCallback &callback = WidgetCallback() ); WidgetItem( const WidgetRef &parent, const std::string &name, const ci::vec2 &position, float delay, const WidgetCallback &callback ); void draw(); ci::Rectf getBounds() const; void setPosition( const ci::vec2 &position ) { mPosition = position; } void pressed( const WidgetEvent &event ); void released( const WidgetEvent &event ); void moved( const WidgetEvent &event ); void setParent( const WidgetRef &parent ) { mParent = parent; } WidgetRef getParent() const { return mParent; } void onReleased( const WidgetCallback &callback ) { mOnReleased = callback; } void onPressed( const WidgetCallback &callback ) { mOnPressed = callback; } void onMoved( const WidgetCallback &callback ) { mOnMoved = callback; } void setOpacity( float opacity ); const WidgetCallback& getOnReleased() const { return mOnReleased; } const WidgetCallback& getOnPressed() const { return mOnPressed; } const WidgetCallback& getOnMoved() const { return mOnMoved; } bool isPressed() const { return mIsPressed; } ci::vec2 getDownPosition() const { return mDownPosition; } ci::vec2 getPressPosition() const { return mPressPosition; } void open( float delay ); void close( float delay ); protected: WidgetCallback mOnReleased; WidgetCallback mOnPressed; WidgetCallback mOnMoved; bool mIsPressed; ci::vec2 mDownPosition; ci::vec2 mPressPosition; WidgetRef mParent; ci::vec2 mPosition; ci::vec2 mSize; float mOpacity; ci::vec2 mOriginalSize; ci::gl::Texture2dRef mTexture; }; class Widget : public std::enable_shared_from_this<Widget> { public: struct Format { Format() : mWindow( ci::app::getWindow() ), mSignalPriority( -1 ), mPosition( 0.0f ), mSize( 128.0f ), mPadding( 10.0f ), mDirection( -1.0f, 0.0f ), mAutoClose( true ) {} Format& position( const ci::vec2 &position ) { mPosition = position; return *this; } Format& size( const ci::vec2 &size ) { mSize = size; return *this; } Format& padding( const ci::vec2 &padding ) { mPadding = padding; return *this; } Format& direction( const ci::vec2 &dir ) { mDirection = dir; return *this; } Format& items( const std::vector<std::string> &items ) { mItems = items; return *this; } Format& window( const ci::app::WindowRef &window ) { mWindow = window; return *this; } Format& signalPriority( int priority ) { mSignalPriority = priority; return *this; } Format& onReleased( const WidgetCallback& callback ) { mOnReleased = callback; return *this; } Format& onPressed( const WidgetCallback& callback ) { mOnPressed = callback; return *this; } Format& onMoved( const WidgetCallback& callback ) { mOnMoved = callback; return *this; } Format& autoClose( bool autoClose ) { mAutoClose = autoClose; return *this; } ci::vec2 getPosition() const { return mPosition; } ci::vec2 getSize() const { return mSize; } ci::vec2 getPadding() const { return mPadding; } ci::vec2 getDirection() const { return mDirection; } std::vector<std::string> getItems() const { return mItems; } ci::app::WindowRef getWindow() const { return mWindow; } int getSignalPriority() const { return mSignalPriority; } const WidgetCallback& getOnReleased() const { return mOnReleased; } const WidgetCallback& getOnPressed() const { return mOnPressed; } const WidgetCallback& getOnMoved() const { return mOnMoved; } bool getAutoCloseEnabled() const { return mAutoClose; } protected: bool mAutoClose; int mSignalPriority; ci::app::WindowRef mWindow; ci::vec2 mPosition, mSize, mPadding, mDirection; std::vector<std::string> mItems; WidgetCallback mOnReleased, mOnPressed, mOnMoved; }; static WidgetRef create( const Format &format = Format() ); Widget( const Format &format ); ~Widget(); struct Close { void operator()( const WidgetEvent &event ); }; void draw(); void open(); void close( bool animate = true, const WidgetItemRef &item = nullptr ); bool isOpen() const { return mOpen; } void add( const WidgetItemRef &item ); void mouseDown( ci::app::MouseEvent &event ); void mouseUp( ci::app::MouseEvent &event ); void mouseDrag( ci::app::MouseEvent &event ); void touchesBegan( ci::app::TouchEvent &event ); void touchesMoved( ci::app::TouchEvent &event ); void touchesEnded( ci::app::TouchEvent &event ); void onReleased( const std::string &name, const WidgetCallback& callback ); void onPressed( const std::string &name, const WidgetCallback& callback ); void onMoved( const std::string &name, const WidgetCallback& callback ); void onClose( const WidgetCallback& callback ); void onCloseEnded( const WidgetCallback& callback ); void setPosition( const ci::vec2 &position ) { mPosition = position; } ci::vec2 getPosition() const { return mPosition; } const std::vector<WidgetItemRef>& getItems() const { return mItems; } WidgetItemRef getItem( const std::string &name ); protected: std::vector<WidgetItemRef> mItems; std::map<std::string,WidgetItemRef> mItemsMap; ci::signals::Connection mMouseDown; ci::signals::Connection mMouseUp; ci::signals::Connection mMouseDrag; ci::signals::Connection mTouchesBegan; ci::signals::Connection mTouchesEnded; ci::signals::Connection mTouchesMoved; ci::vec2 mPosition; WidgetCallback mCloseCallback; WidgetCallback mCloseEndedCallback; bool mOpen; bool mAutoClose; };
vnm-interactive/Grove
src/Triangulation/Triangulation.h
/* Copyright (c) 2015 <NAME> This code uses a class extracted and adapted from the OpenCV library for use with the Cinder C++ library, http://libcinder.org and all the relevant portion of code is tied to OpenCV license that can be found in Triangulation.cpp file Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #include "cinder/Rect.h" #include "cinder/Vector.h" namespace Delaunay { //! triangulates the list of points and returns a list of triangles indices std::vector<uint32_t> getTriangleIndices( const ci::Rectf &rect, const std::vector<ci::vec2> &points = std::vector<ci::vec2>() ); };
vnm-interactive/Grove
src/PoissonDiskDistribution/PoissonDiskDistribution.h
<gh_stars>1-10 /* Copyright (c) 2015 <NAME> Algorithm from Fast Poisson Disk Sampling in Arbitrary Dimensions by <NAME> http://www.cs.ubc.ca/~rbridson/docs/bridson-siggraph07-poissondisk.pdf as explained in this article: http://devmag.org.za/2009/05/03/poisson-disk-sampling/ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #include <vector> #include "cinder/AxisAlignedBox.h" #include "cinder/Rect.h" #include "cinder/Vector.h" // 2D Poisson Disk Distribution //! returns a set of poisson disk samples inside a rectangular \a area, with a minimum \a separation and with a packing determined by how high \a k is. The higher \a k is the higher the algorithm will be slow. If no \a initialSet of points is provided the area center will be used as the initial point. std::vector<glm::vec2> poissonDiskDistribution( float separation, const ci::Rectf &area, const std::vector<glm::vec2> &initialSet = std::vector<glm::vec2>(), int k = 30 ); //! returns a set of poisson disk samples inside a rectangular \a area, with a minimum separation defined by what \a distFunction returns and with a packing determined by how high \a k is. The higher \a k is the higher the algorithm will be slow. If no \a initialSet of points is provided the area center will be used as the initial point. std::vector<glm::vec2> poissonDiskDistribution( const std::function<float(const glm::vec2&)> &distFunction, const ci::Rectf &area, const std::vector<glm::vec2> &initialSet = std::vector<glm::vec2>(), int k = 30 ); //! returns a set of poisson disk samples within bounds defined by both \a boundsFunction and a rectangular \a area, with a minimum separation defined by what \a distFunction returns and with a packing determined by how high \a k is. The higher \a k is the higher the algorithm will be slow. If no \a initialSet of points is provided the area center will be used as the initial point. //TODO: remove Rectf area arguments and compute bounds inside the function std::vector<glm::vec2> poissonDiskDistribution( const std::function<float(const glm::vec2&)> &distFunction, const std::function<bool(const glm::vec2&)> &boundsFunction, const ci::Rectf &area, const std::vector<glm::vec2> &initialSet = std::vector<glm::vec2>(), int k = 30 ); //TODO: implement 3d distribution // 3D Poisson Disk Distribution //! returns a set of poisson disk samples within cubic \a bounds, with a minimum \a separation and with a packing determined by how high \a k is. The higher \a k is the higher the algorithm will be slow. If no \a initialSet of points is provided the area center will be use as the first point. std::vector<glm::vec3> poissonDiskDistribution( float separation, const ci::AxisAlignedBox &bounds, const std::vector<glm::vec3> &initialSet = std::vector<glm::vec3>(), int k = 30 );
songwut/FlashCard
flash/ExternalLibs/CHTStickerView/CHTStickerView.h
<filename>flash/ExternalLibs/CHTStickerView/CHTStickerView.h // // CHTStickerView.h // Sample // // Created by <NAME> on 2013/10/31. // Copyright (c) 2013年 <NAME>. All rights reserved. // #import <UIKit/UIKit.h> typedef NS_ENUM (NSInteger, CHTStickerViewHandler) { CHTStickerViewHandlerClose, CHTStickerViewHandlerRotate, CHTStickerViewHandlerFlip, CHTStickerViewHandlerNone }; typedef NS_ENUM (NSInteger, CHTStickerViewPosition) { CHTStickerViewPositionTopLeft, CHTStickerViewPositionTopRight, CHTStickerViewPositionBottomLeft, CHTStickerViewPositionBottomRight }; @class CHTStickerView; @protocol CHTStickerViewDelegate <NSObject> @optional - (void)stickerViewDidBeginMoving:(CHTStickerView *)stickerView; - (void)stickerViewDidChangeMoving:(CHTStickerView *)stickerView; - (void)stickerViewDidEndMoving:(CHTStickerView *)stickerView; - (void)stickerViewDidBeginRotating:(CHTStickerView *)stickerView; - (void)stickerViewDidChangeRotating:(CHTStickerView *)stickerView; - (void)stickerViewDidEndRotating:(CHTStickerView *)stickerView; - (void)stickerViewDidClose:(CHTStickerView *)stickerView; - (void)stickerViewDidTap:(CHTStickerView *)stickerView; @end @interface CHTStickerView : UIView @property (nonatomic, weak) id <CHTStickerViewDelegate> delegate; /// The contentView inside the sticker view. @property (nonatomic, strong, readonly) UIView *contentView; /// Enable the close handler or not. Default value is YES. @property (nonatomic, assign) BOOL enableClose; @property (nonatomic, assign) BOOL enableNone; /// Enable the rotate/resize handler or not. Default value is YES. @property (nonatomic, assign) BOOL enableRotate; /// Enable the flip handler or not. Default value is YES. @property (nonatomic, assign) BOOL enableFlip; /// Show close and rotate/resize handlers or not. Default value is YES. @property (nonatomic, assign) BOOL showEditingHandlers; /// Minimum value for the shorter side while resizing. Default value will be used if not set. @property (nonatomic, assign) NSInteger minimumSize; /// Color of the outline border. Default: brown color. @property (nonatomic, strong) UIColor *outlineBorderColor; /// A convenient property for you to store extra information. @property (nonatomic, strong) NSDictionary *userInfo; @property (nonatomic, strong) UIImageView *noneImageView; @property (nonatomic, strong) UIImageView *flipImageView; @property (nonatomic, strong) UIImageView *closeImageView; @property (nonatomic, strong) UIImageView *rotateImageView; @property (nonatomic, assign) CGFloat angle; @property (nonatomic, assign) CGFloat hardScale; @property (nonatomic, assign) NSInteger defaultInset; @property (nonatomic, assign) NSInteger defaultMinimumSize; /** * Initialize a sticker view. This is the designated initializer. * * @param contentView The contentView inside the sticker view. * You can access it via the `contentView` property. * * @return The sticker view. */ - (id)initWithContentView:(UIView *)contentView; /** * Use image to customize each editing handler. * It is your responsibility to set image for every editing handler. * * @param image The image to be used. * @param handler The editing handler. */ - (void)setImage:(UIImage *)image forHandler:(CHTStickerViewHandler)handler; /** * Customize each editing handler's position. * If not set, default position will be used. * @note It is your responsibility not to set duplicated position. * * @param position The position for the handler. * @param handler The editing handler. */ - (void)setPosition:(CHTStickerViewPosition)position forHandler:(CHTStickerViewHandler)handler; /** * Customize handler's size * * @param size Handler's size */ - (void)setHandlerSize:(NSInteger)size; @end
songwut/FlashCard
flash/Header.h
<gh_stars>0 // // Header.h // flash // // Created by <NAME> on 18/9/2564 BE. // #ifndef Header_h #define Header_h #import "CHTStickerView.h" #import "TTGTagCollectionView.h" #endif /* Header_h */
darknessnerd/piapf
include/base64.h
#ifndef BASE64_H #define BASE64_H #include <string> #if __cplusplus >= 201703L #include <string_view> #endif // __cplusplus >= 201703L namespace base64 { std::string base64_encode (std::string const& s, bool url = false); std::string base64_encode_pem (std::string const& s); std::string base64_encode_mime(std::string const& s); std::string base64_decode(std::string const& s, bool remove_linebreaks = false); std::string base64_encode(unsigned char const*, size_t len, bool url = false); #if __cplusplus >= 201703L std::string base64_encode (std::string_view s, bool url = false); std::string base64_encode_pem (std::string_view s); std::string base64_encode_mime(std::string_view s); std::string base64_decode(std::string_view s, bool remove_linebreaks = false); #endif // __cplusplus >= 201703L } #endif /* BASE64_H */
darknessnerd/piapf
include/pia_client.h
#ifndef PIA_CLIENT_H #define PIA_CLIENT_H #include <string> #include <cpprest/http_client.h> #include <functional> #include <cpprest/json.h> #include <pplx/pplxtasks.h> class PiaClient { public: PiaClient(); virtual ~PiaClient(); std::string get_public_ip(); bool auth(const std::string &username, const std::string &password); bool generate_signature(); bool bind_port(); int get_port() const; bool isExpired(); std::string currentISO8601TimeUTC(); long stringToTimestamp(const std::string &time); protected: private: web::http::client::http_client_config config; // private access internet host std::string pia_host; std::string token; std::string signature; std::string payload; std::string pia_request_uri; void process_request(const pplx::task<web::http::http_response> &task,std::function<void(const web::json::value &jsonObject)> handler_func); }; #endif // PIA_CLIENT_H
darknessnerd/piapf
include/uuid.h
<reponame>darknessnerd/piapf #ifndef UUID_H #define UUID_H #include <string> namespace UUID { std::string generate_uuid(); } #endif // UUID_H
darknessnerd/piapf
include/configuration.h
<reponame>darknessnerd/piapf #ifndef CONFIGURATION_H #define CONFIGURATION_H #include <string> #include <boost/program_options.hpp> class Configuration { public: Configuration(); virtual ~Configuration(); int parse(int argc, char *argv[]); std::string get_default_config_path() const; std::string get_vpn_iface() const; std::string get_pia_username() const; std::string get_pia_password() const; std::string get_deulged_host() const; std::string get_deluged_username() const; std::string get_deluged_password() const; int get_deluged_port() const; int get_check_frequency() const; protected: private: std::string default_config_path; boost::program_options::variables_map vm; boost::program_options::options_description fileOptions; }; #endif // CONFIGURATION_H
darknessnerd/piapf
include/subprocess.h
#ifndef SUBPROCESS_H #define SUBPROCESS_H #include <string> #include <future> #include <vector> // For fork and wait #include <sys/types.h> #include <sys/wait.h> namespace shell{ /** A simple class to start and read from a subprocess */ class subprocess{ enum{OUT_READ, OUT_WRITE, IN_READ, IN_WRITE}; int pipes[4]; pid_t pid_; std::string output; std::future<int> exit_status_; public: // Construct with a list of parameters, the program being the first // @note: uses execvp and passes arg[0] as first and second arg) subprocess(std::vector<std::string> args); inline subprocess(std::initializer_list<std::string> args) : subprocess(std::vector<std::string>(args)) {} inline int stdout(){ return pipes[OUT_READ];} inline int stdin(){ return pipes[IN_WRITE];} inline int pid(){ return pid_; } std::string getline(); std::string read(int n); void write(std::string); // i.e. Kill -9 void kill(); ~subprocess(); }; /** Read from stdout of the process, until EOF. NOTE: If you want partial output, read from subprocess::stdout(). */ std::ostream& operator<<(std::ostream&,subprocess&); class SubprocessException : public std::runtime_error { using runtime_error::runtime_error; }; } #endif // SUBPROCESS_H
darknessnerd/piapf
include/net_tools.h
#ifndef NET_TOOLS_H #define NET_TOOLS_H #include <string> #include <vector> namespace net_tools { std::string get_ip_address(const std::string &iface); std::vector<std::string> dns_lookup(const std::string &host_name, int ipv=4); } #endif // NET_TOOLS_H
darknessnerd/piapf
include/shell.h
#ifndef SHELL_H #define SHELL_H #include <string> #include <stdexcept> namespace shell { class cmd { int exit_code_; std::string command_; std::string output_; FILE* pipe_{nullptr}; public: cmd(std::string command, bool throws = true); ~cmd(); bool ok(); std::string str(); friend std::ostream& operator<<(std::ostream&,cmd); }; std::ostream& operator<<(std::ostream&,cmd); class cmdException : public std::runtime_error { int exit_code_; public: cmdException(std::string command, std::string output, int exit); cmdException(std::string output, int exit); int exit_code(); }; } #endif // SHELL_H
kiwiroy/libtickit
t/20mockterm.c
<gh_stars>10-100 #include "tickit.h" #include "tickit-mockterm.h" #include "taplib.h" #include "taplib-mockterm.h" #include <string.h> #define streq(a,b) (!strcmp(a,b)) #define RECT(t,l,li,co) (TickitRect){ .top = t, .left = l, .lines = li, .cols = co } static TickitTerm *tt; static void is_display_text(char *name, ...) { va_list args; va_start(args, name); int lines, cols; tickit_term_get_size(tt, &lines, &cols); for(int line = 0; line < lines; line++) { const char *expect = va_arg(args, char *); size_t len = tickit_mockterm_get_display_text((TickitMockTerm *)tt, NULL, 0, line, 0, cols); char *got = malloc(len + 1); tickit_mockterm_get_display_text((TickitMockTerm *)tt, got, len, line, 0, cols); if(streq(expect, got)) { free(got); continue; } fail(name); diag("Got line % 2d |%s|", line, got); diag("Expected |%s|", expect); free(got); va_end(args); return; } va_end(args); pass(name); } static void fillterm(TickitTerm *tt) { tickit_term_goto(tt, 0, 0); tickit_term_print(tt, "0000000000"); tickit_term_goto(tt, 1, 0); tickit_term_print(tt, "1111111111"); tickit_term_goto(tt, 2, 0); tickit_term_print(tt, "2222222222"); } int on_key_event_get_type(TickitTerm *tt, TickitEventFlags flags, void *_info, void *data) { *((int *)data) = ((TickitKeyEventInfo *)_info)->type; return 0; } int on_mouse_event_get_type(TickitTerm *tt, TickitEventFlags flags, void *_info, void *data) { *((int *)data) = ((TickitMouseEventInfo *)_info)->type; return 0; } int main(int argc, char *argv[]) { tt = make_term(3, 10); is_termlog("Termlog initially", NULL); is_display_text("Display initially", " ", " ", " "); tickit_term_goto(tt, 1, 5); is_termlog("Termlog after goto", GOTO(1,5), NULL); tickit_term_print(tt, "foo"); is_termlog("Termlog after print", PRINT("foo"), NULL); is_display_text("Display after print", " ", " foo ", " "); char c = 'l'; tickit_term_printn(tt, &c, 1); is_termlog("Termlog after printn 1", PRINT("l"), NULL); is_display_text("Display after printn 1", " ", " fool ", " "); tickit_term_goto(tt, 2, 0); tickit_term_print(tt, "Ĉu vi?"); is_termlog("Termlog after print UTF-8", GOTO(2,0), PRINT("Ĉu vi?"), NULL); is_display_text("Display after print UTF-8", " ", " fool ", "Ĉu vi? "); // U+FF10 = Fullwidth digit zero = EF BC 90 tickit_term_print(tt, "\xef\xbc\x90"); is_termlog("Termlog after print UTF-8 fullwidth", PRINT("0"), NULL); is_display_text("Display after print UTF-8 fullwidth", " ", " fool ", "Ĉu vi?0 "); tickit_term_clear(tt); is_termlog("Termlog after clear", CLEAR(), NULL); is_display_text("Display after clear", " ", " ", " "); TickitPen *fg_pen = tickit_pen_new_attrs(TICKIT_PEN_FG, 3, 0); tickit_term_setpen(tt, fg_pen); is_termlog("Termlog after setpen", SETPEN(.fg=3), NULL); TickitPen *bg_pen = tickit_pen_new_attrs(TICKIT_PEN_BG, 6, 0); tickit_term_chpen(tt, bg_pen); is_termlog("Termlog after chpen", SETPEN(.fg=3, .bg=6), NULL); // Now some test content for scrolling fillterm(tt); tickit_mockterm_clearlog((TickitMockTerm *)tt); is_display_text("Display after scroll fill", "0000000000", "1111111111", "2222222222"); ok(tickit_term_scrollrect(tt, RECT(0,0,3,10), +1,0), "Scrollrect down OK"); is_termlog("Termlog after scroll 1 down", SCROLLRECT(0,0,3,10, +1,0), NULL); is_display_text("Display after scroll 1 down", "1111111111", "2222222222", " "); ok(tickit_term_scrollrect(tt, RECT(0,0,3,10), -1,0), "Scrollrect up OK"); is_termlog("Termlog after scroll 1 up", SCROLLRECT(0,0,3,10, -1,0), NULL); is_display_text("Display after scroll 1 up", " ", "1111111111", "2222222222"); fillterm(tt); tickit_mockterm_clearlog((TickitMockTerm *)tt); tickit_term_scrollrect(tt, RECT(0,0,2,10), +1,0); is_termlog("Termlog after scroll partial 1 down", SCROLLRECT(0,0,2,10, +1,0), NULL); is_display_text("Display after scroll partial 1 down", "1111111111", " ", "2222222222"); tickit_term_scrollrect(tt, RECT(0,0,2,10), -1,0); is_termlog("Termlog after scroll partial 1 up", SCROLLRECT(0,0,2,10, -1,0), NULL); is_display_text("Display after scroll partial 1 up", " ", "1111111111", "2222222222"); for(int line = 0; line < 3; line++) tickit_term_goto(tt, line, 0), tickit_term_print(tt, "ABCDEFGHIJ"); tickit_mockterm_clearlog((TickitMockTerm *)tt); tickit_term_scrollrect(tt, RECT(0,5,1,5), 0,2); is_termlog("Termlog after scroll right", SCROLLRECT(0,5,1,5, 0,+2), NULL); is_display_text("Display after scroll right", "ABCDEHIJ ", "ABCDEFGHIJ", "ABCDEFGHIJ"); tickit_term_scrollrect(tt, RECT(1,5,1,5), 0,-3); is_termlog("Termlog after scroll left", SCROLLRECT(1,5,1,5, 0,-3), NULL); is_display_text("Display after scroll left", "ABCDEHIJ ", "ABCDE FG", "ABCDEFGHIJ"); tickit_term_goto(tt, 2, 3); tickit_term_erasech(tt, 5, -1); is_termlog("Termlog after erasech", GOTO(2,3), ERASECH(5, -1), NULL); is_display_text("Display after erasech", "ABCDEHIJ ", "ABCDE FG", "ABC IJ"); { int type = 0; int key_bind_id = tickit_term_bind_event(tt, TICKIT_TERM_ON_KEY, 0, &on_key_event_get_type, &type); int mouse_bind_id = tickit_term_bind_event(tt, TICKIT_TERM_ON_MOUSE, 0, &on_mouse_event_get_type, &type); press_key(TICKIT_KEYEV_TEXT, "A", 0); is_int(type, TICKIT_KEYEV_TEXT, "type is TICKIT_KEYEV_TEXT after press_key()"); type = 0; press_mouse(TICKIT_MOUSEEV_PRESS, 1, 2, 3, 0); is_int(type, TICKIT_MOUSEEV_PRESS, "type is TICKIT_MOUSEEV_PRESS after press_mouse()"); tickit_term_unbind_event_id(tt, key_bind_id); tickit_term_unbind_event_id(tt, mouse_bind_id); } tickit_pen_unref(fg_pen); tickit_pen_unref(bg_pen); tickit_term_unref(tt); return exit_status(); }
kiwiroy/libtickit
t/34renderbuffer-save.c
#include "tickit.h" #include "taplib.h" #include "taplib-mockterm.h" int main(int argc, char *argv[]) { TickitTerm *tt = make_term(25, 80); TickitRenderBuffer *rb; rb = tickit_renderbuffer_new(10, 20); // Position { int line, col; tickit_renderbuffer_goto(rb, 2, 2); { tickit_renderbuffer_save(rb); tickit_renderbuffer_goto(rb, 4, 4); tickit_renderbuffer_get_cursorpos(rb, &line, &col); is_int(line, 4, "line before restore"); is_int(col, 4, "col before restore"); tickit_renderbuffer_restore(rb); } tickit_renderbuffer_get_cursorpos(rb, &line, &col); is_int(line, 2, "line after restore"); is_int(col, 2, "col after restore"); tickit_renderbuffer_text(rb, "some text"); tickit_renderbuffer_flush_to_term(rb, tt); is_termlog("Stack saves/restores virtual cursor position", GOTO(2,2), SETPEN(), PRINT("some text"), NULL); } // Clipping { tickit_renderbuffer_text_at(rb, 0, 0, "0000000000"); { tickit_renderbuffer_save(rb); tickit_renderbuffer_clip(rb, &(TickitRect){.top = 0, .left = 2, .lines = 10, .cols = 16}); tickit_renderbuffer_text_at(rb, 1, 0, "1111111111"); tickit_renderbuffer_restore(rb); } tickit_renderbuffer_text_at(rb, 2, 0, "2222222222"); tickit_renderbuffer_flush_to_term(rb, tt); is_termlog("Stack saves/restores clipping region", GOTO(0,0), SETPEN(), PRINT("0000000000"), GOTO(1,2), SETPEN(), PRINT("11111111"), GOTO(2,0), SETPEN(), PRINT("2222222222"), NULL); } // Pen { TickitPen *pen; tickit_renderbuffer_goto(rb, 3, 0); tickit_renderbuffer_setpen(rb, pen = tickit_pen_new_attrs(TICKIT_PEN_BG, 1, 0)); tickit_pen_unref(pen); tickit_renderbuffer_text(rb, "123"); { tickit_renderbuffer_savepen(rb); tickit_renderbuffer_setpen(rb, pen = tickit_pen_new_attrs(TICKIT_PEN_FG, 4, 0)); tickit_pen_unref(pen); tickit_renderbuffer_text(rb, "456"); tickit_renderbuffer_setpen(rb, pen = tickit_pen_new_attrs(TICKIT_PEN_BG, -1, 0)); tickit_pen_unref(pen); tickit_renderbuffer_text(rb, "789"); tickit_renderbuffer_restore(rb); } tickit_renderbuffer_text(rb, "ABC"); tickit_renderbuffer_flush_to_term(rb, tt); is_termlog("Stack saves/restores render pen", GOTO(3,0), SETPEN(.bg=1), PRINT("123"), SETPEN(.bg=1,.fg=4), PRINT("456"), SETPEN(), PRINT("789"), SETPEN(.bg=1), PRINT("ABC"), NULL); tickit_renderbuffer_goto(rb, 4, 0); tickit_renderbuffer_setpen(rb, pen = tickit_pen_new_attrs(TICKIT_PEN_REVERSE, 1, 0)); tickit_pen_unref(pen); tickit_renderbuffer_text(rb, "123"); { tickit_renderbuffer_savepen(rb); tickit_renderbuffer_setpen(rb, pen = tickit_pen_new_attrs(TICKIT_PEN_REVERSE, 0, 0)); tickit_pen_unref(pen); tickit_renderbuffer_text(rb, "456"); tickit_renderbuffer_restore(rb); } tickit_renderbuffer_text(rb, "789"); tickit_renderbuffer_flush_to_term(rb, tt); is_termlog("Stack saves/restores allow zeroing pen attributes", GOTO(4,0), SETPEN(.rv=1), PRINT("123"), SETPEN(), PRINT("456"), SETPEN(.rv=1), PRINT("789"), NULL); } // Translation { tickit_renderbuffer_text_at(rb, 0, 0, "A"); tickit_renderbuffer_save(rb); { tickit_renderbuffer_translate(rb, 2, 2); tickit_renderbuffer_text_at(rb, 1, 1, "B"); } tickit_renderbuffer_restore(rb); tickit_renderbuffer_text_at(rb, 2, 2, "C"); tickit_renderbuffer_flush_to_term(rb, tt); is_termlog("Stack saves/restores translation offset", GOTO(0,0), SETPEN(), PRINT("A"), GOTO(2,2), SETPEN(), PRINT("C"), GOTO(3,3), SETPEN(), PRINT("B"), NULL); } tickit_renderbuffer_unref(rb); tickit_term_unref(tt); return exit_status(); }
kiwiroy/libtickit
include/tickit-termdrv.h
<reponame>kiwiroy/libtickit #ifdef __cplusplus extern "C" { #endif #ifndef __TICKIT_TERMDRV_H__ #define __TICKIT_TERMDRV_H__ /* * The contents of this file should be considered entirely experimental, and * subject to any change at any time. We make no API or ABI stability * guarantees at this time. */ #include "tickit.h" #include <termkey.h> typedef struct { void (*attach)(TickitTermDriver *ttd, TickitTerm *tt); /* optional */ void (*destroy)(TickitTermDriver *ttd); void (*start)(TickitTermDriver *ttd); /* optional */ bool (*started)(TickitTermDriver *ttd); /* optional */ void (*stop)(TickitTermDriver *ttd); /* optional */ void (*pause)(TickitTermDriver *ttd); /* optional */ void (*resume)(TickitTermDriver *ttd); /* optional */ bool (*print)(TickitTermDriver *ttd, const char *str, size_t len); bool (*goto_abs)(TickitTermDriver *ttd, int line, int col); bool (*move_rel)(TickitTermDriver *ttd, int downward, int rightward); bool (*scrollrect)(TickitTermDriver *ttd, const TickitRect *rect, int downward, int rightward); bool (*erasech)(TickitTermDriver *ttd, int count, TickitMaybeBool moveend); bool (*clear)(TickitTermDriver *ttd); bool (*chpen)(TickitTermDriver *ttd, const TickitPen *delta, const TickitPen *final); bool (*getctl_int)(TickitTermDriver *ttd, TickitTermCtl ctl, int *value); bool (*setctl_int)(TickitTermDriver *ttd, TickitTermCtl ctl, int value); bool (*setctl_str)(TickitTermDriver *ttd, TickitTermCtl ctl, const char *value); int (*gotkey)(TickitTermDriver *ttd, TermKey *tk, const TermKeyKey *key); /* optional */ } TickitTermDriverVTable; struct TickitTermDriver { TickitTerm *tt; TickitTermDriverVTable *vtable; }; void *tickit_termdrv_get_tmpbuffer(TickitTermDriver *ttd, size_t len); void tickit_termdrv_write_str(TickitTermDriver *ttd, const char *str, size_t len); void tickit_termdrv_write_strf(TickitTermDriver *ttd, const char *fmt, ...); TickitPen *tickit_termdrv_current_pen(TickitTermDriver *ttd); /* * Function to construct a new TickitTerm directly from a TickitTermDriver */ TickitTerm *tickit_term_new_for_driver(TickitTermDriver *ttd); /* * Intended for "subclass" terminal methods, to obtain their custom driver * when given a TT instance */ TickitTermDriver *tickit_term_get_driver(TickitTerm *tt); #endif #ifdef __cplusplus } #endif