|
| 1 | +#include "c_helpers.hpp" |
| 2 | +#include <cstddef> |
| 3 | +#include <cstdio> |
| 4 | +#include <cstring> |
| 5 | +#include <utility> |
| 6 | + |
| 7 | +#include <qdebug.h> |
| 8 | +#include <qlogging.h> |
| 9 | +#include <sys/mman.h> |
| 10 | +#include <sys/shm.h> |
| 11 | +#include <unistd.h> |
| 12 | + |
| 13 | +namespace qs::wayland::input_method::impl { |
| 14 | + |
| 15 | +void FreeDeleter::operator()(const char* p) const { |
| 16 | + std::free(const_cast<std::remove_const_t<char>*>(p)); // NOLINT |
| 17 | +} |
| 18 | + |
| 19 | +SharedMemory::SharedMemory(const char* shmName, int oFlag, size_t size) |
| 20 | + : mShmName(shmName) |
| 21 | + , mSize(size) |
| 22 | + , fd(shm_open(this->mShmName, oFlag, 0)) |
| 23 | + , map(nullptr) { |
| 24 | + if (this->fd == -1) { |
| 25 | + perror(""); |
| 26 | + qDebug() << "Virtual keyboard failed to open shared memory"; |
| 27 | + return; |
| 28 | + } |
| 29 | + if (ftruncate(this->fd, static_cast<int>(size)) == -1) { |
| 30 | + this->fd = -1; |
| 31 | + perror(""); |
| 32 | + qDebug() << "Virtual keyboard failed to resize shared memory to" << size; |
| 33 | + return; |
| 34 | + } |
| 35 | + this->map = static_cast<char*>(mmap(nullptr, this->mSize, PROT_WRITE, MAP_SHARED, this->fd, 0)); |
| 36 | + if (this->map == MAP_FAILED) { |
| 37 | + perror(""); |
| 38 | + qDebug() << "Virtual keyboard failed to open shared memory"; |
| 39 | + return; |
| 40 | + } |
| 41 | +} |
| 42 | +SharedMemory::~SharedMemory() { |
| 43 | + if (this->fd != -1) { |
| 44 | + close(this->fd); |
| 45 | + shm_unlink(this->mShmName); |
| 46 | + } |
| 47 | + if (this->map != nullptr) { |
| 48 | + munmap(this->map, this->mSize); |
| 49 | + } |
| 50 | +} |
| 51 | +SharedMemory::SharedMemory(SharedMemory&& other) noexcept |
| 52 | + : mShmName(std::exchange(other.mShmName, nullptr)) |
| 53 | + , mSize(std::exchange(other.mSize, 0)) |
| 54 | + , fd(std::exchange(other.fd, -1)) |
| 55 | + , map(std::exchange(other.map, nullptr)) {} |
| 56 | +SharedMemory& SharedMemory::operator=(SharedMemory&& other) noexcept { |
| 57 | + this->mShmName = std::exchange(other.mShmName, nullptr); |
| 58 | + this->mSize = std::exchange(other.mSize, 0); |
| 59 | + this->fd = std::exchange(other.fd, -1); |
| 60 | + this->map = std::exchange(other.map, nullptr); |
| 61 | + return *this; |
| 62 | +} |
| 63 | + |
| 64 | +SharedMemory::operator bool() const { return fd != -1 && map != MAP_FAILED; } |
| 65 | +[[nodiscard]] int SharedMemory::get() const { return fd; } |
| 66 | + |
| 67 | +void SharedMemory::write(const char* string) { |
| 68 | + if (!this->map) return; |
| 69 | + strcpy(this->map, string); |
| 70 | +} |
| 71 | + |
| 72 | +} // namespace qs::wayland::input_method::impl |
0 commit comments