Files
bananarchy/src/dwm-plugins/camera_plugin.cpp
T

989 lines
31 KiB
C++

#include "phone_data.h"
#include "media_utils.h"
#include "../sxmo-dwm/dwm_plugin.h"
#include <X11/Xatom.h>
#include <X11/Xft/Xft.h>
#include <X11/Xutil.h>
#include <linux/videodev2.h>
#include <pango/pangoxft.h>
#include <poll.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <atomic>
#include <clocale>
#include <mutex>
#include <thread>
namespace {
using namespace bananarchy;
volatile sig_atomic_t gRunning = 1;
void handleSignal(int) {
gRunning = 0;
}
enum class ViewMode {
Viewfinder = 0,
Gallery = 1,
ConfirmDelete = 2,
};
constexpr int kCamW = 800;
constexpr int kCamH = 600;
constexpr size_t kCamFrameBytes = kCamW * kCamH * 3;
constexpr int kVfW = 240;
constexpr int kVfH = 180;
const char* getTorchBrightnessPath() {
if (::access("/sys/class/leds/white:torch/brightness", R_OK) == 0) {
return "/sys/class/leds/white:torch/brightness";
}
if (::access("/sys/class/leds/white:flash/brightness", R_OK) == 0) {
return "/sys/class/leds/white:flash/brightness";
}
return nullptr;
}
bool getTorchState() {
const char* p = getTorchBrightnessPath();
if (!p) return false;
return readIntFile(p, 0) > 0;
}
void setTorchState(bool on) {
const char* p = getTorchBrightnessPath();
if (!p) return;
writeIntFile(p, on ? 1 : 0);
}
std::string getPicturesDir() {
const char* xdg = std::getenv("XDG_PICTURES_DIR");
if (xdg && xdg[0]) {
::mkdir(xdg, 0755);
return xdg;
}
const char* home = std::getenv("HOME");
std::string dir = std::string(home && home[0] ? home : "/home/user") + "/Pictures";
::mkdir(dir.c_str(), 0755);
return dir;
}
struct PhotoEntry {
std::string name;
std::string fullPath;
off_t size = 0;
time_t mtime = 0;
};
std::vector<PhotoEntry> listSavedPhotos() {
std::vector<PhotoEntry> out;
std::string dir = getPicturesDir();
DIR* d = ::opendir(dir.c_str());
if (!d) return out;
struct dirent* ent;
while ((ent = ::readdir(d)) != nullptr) {
std::string name = ent->d_name;
if (name.empty() || name[0] == '.') continue;
std::string low = toLowerStr(name);
bool isImg = (low.size() > 4 &&
(low.substr(low.size() - 4) == ".jpg" ||
low.substr(low.size() - 4) == ".png")) ||
(low.size() > 5 && low.substr(low.size() - 5) == ".jpeg");
if (!isImg) continue;
PhotoEntry pe;
pe.name = name;
pe.fullPath = dir + "/" + name;
struct stat st {};
if (::stat(pe.fullPath.c_str(), &st) == 0 && S_ISREG(st.st_mode)) {
pe.size = st.st_size;
pe.mtime = st.st_mtim.tv_sec;
out.push_back(pe);
}
}
::closedir(d);
std::sort(out.begin(), out.end(),
[](const PhotoEntry& a, const PhotoEntry& b) {
if (a.mtime != b.mtime) return a.mtime > b.mtime;
return a.name > b.name;
});
return out;
}
void saveZoomedRgb24AsJpeg(const std::string& path,
const uint8_t* src800x600,
int zoomFactor) {
// Rotate 90 degrees clockwise from raw 800x600 sensor into upright 600x800
constexpr int kOutW = kCamH; // 600
constexpr int kOutH = kCamW; // 800
zoomFactor = std::clamp(zoomFactor, 1, 4);
int cropRotW = kOutW / zoomFactor;
int cropRotH = kOutH / zoomFactor;
int startRotX = (kOutW - cropRotW) / 2;
int startRotY = (kOutH - cropRotH) / 2;
std::vector<uint8_t> rotated(kCamFrameBytes);
for (int dy = 0; dy < kOutH; ++dy) {
int rotY = std::clamp(startRotY + (dy * cropRotH) / kOutH, 0, kCamW - 1);
int sx = rotY;
uint8_t* drow = rotated.data() + static_cast<size_t>(dy) * kOutW * 3;
for (int dx = 0; dx < kOutW; ++dx) {
int rotX = std::clamp(startRotX + (dx * cropRotW) / kOutW, 0, kCamH - 1);
int sy = (kCamH - 1) - rotX;
const uint8_t* px =
src800x600 + (static_cast<size_t>(sy) * kCamW + sx) * 3;
drow[dx * 3 + 0] = px[0];
drow[dx * 3 + 1] = px[1];
drow[dx * 3 + 2] = px[2];
}
}
saveRgb24AsJpeg(path, rotated.data(), kOutW, kOutH, 92);
}
int runCameraApp(int argc, char** argv) {
gRunning = 1;
std::setlocale(LC_ALL, "");
XSetLocaleModifiers("");
bool isPreload = false;
std::string initArg;
for (int i = 1; i < argc; ++i) {
if (!argv[i]) continue;
if (std::strcmp(argv[i], "--preload") == 0) {
isPreload = true;
} else if (std::strcmp(argv[i], "gallery") == 0) {
initArg = "gallery";
}
}
std::string daemonPidPath = getPluginDaemonPidPath("camera");
std::string activePidPath = getRuntimeFile("xcamera.pid");
if (isPluginDaemonAlive("camera")) {
if (!isPreload) {
sendPluginCommand("camera",
initArg.empty() ? "OPEN" : ("OPEN " + initArg));
}
return 0;
}
writeIntFile(daemonPidPath, static_cast<int>(::getpid()));
int fifoFd = setupPluginDaemonFifo("camera");
int vfPipe[2] = {-1, -1};
if (::pipe(vfPipe) == 0) {
::fcntl(vfPipe[0], F_SETFL, O_NONBLOCK | O_CLOEXEC);
::fcntl(vfPipe[1], F_SETFL, O_NONBLOCK | O_CLOEXEC);
}
struct sigaction sa {};
sa.sa_handler = handleSignal;
sigemptyset(&sa.sa_mask);
sigaction(SIGINT, &sa, nullptr);
sigaction(SIGTERM, &sa, nullptr);
NeoWindow neo;
if (!neo.create("xcamera", "XCamera", "Camera")) {
if (fifoFd >= 0) ::close(fifoFd);
if (vfPipe[0] >= 0) ::close(vfPipe[0]);
if (vfPipe[1] >= 0) ::close(vfPipe[1]);
::unlink(daemonPidPath.c_str());
return 1;
}
Display* dpy = neo.dpy;
int screen = neo.screen;
Visual* visual = neo.visual;
Window win = neo.win;
Pixmap pix = neo.pix;
GC gc = neo.gc;
PluginTheme& pt = neo.theme;
auto& layoutMain = pt.layoutMain;
auto& layoutSmall = pt.layoutSmall;
auto& layoutIcon = pt.layoutIcon;
auto& colWhite = pt.colWhite;
auto& colLight = pt.colLight;
auto& colMuted = pt.colMuted;
auto& colYellow = pt.colYellow;
auto& colGreen = pt.colGreen;
auto& colBlue = pt.colBlue;
auto& colRed = pt.colRed;
std::vector<uint32_t> vfFront(kVfW * kVfH, 0x101010);
std::vector<uint32_t> vfBack(kVfW * kVfH, 0x101010);
XImage* xImgVf = XCreateImage(
dpy, visual, DefaultDepth(dpy, screen), ZPixmap, 0,
reinterpret_cast<char*>(vfFront.data()), kVfW, kVfH, 32, kVfW * 4);
std::mutex frameMutex;
std::atomic<bool> vfThreadRunning {false};
std::atomic<bool> vfShouldStop {false};
std::atomic<int> zoomFactor {1};
std::atomic<bool> flashAuto {false};
std::atomic<bool> snapRequested {false};
std::thread vfThread;
bool cameraReady = false;
std::string cameraStatus = "Initializing camera...";
std::string statusBanner;
int64_t statusBannerUntilMs = 0;
int64_t shutterFlashUntilMs = 0;
bool timerEnabled = false;
bool countdownActive = false;
int64_t countdownTargetMs = 0;
bool torchOn = false;
bool torchRestoredOnClose = false;
ViewMode mode = ViewMode::Viewfinder;
std::vector<PhotoEntry> photos;
int selectedPhoto = 0;
int confirmSelected = 0;
int galleryImgW = 0;
int galleryImgH = 0;
bool visible = false;
int64_t openStartMs = 0;
int64_t startupIgnoreUntilMs = 0;
bool initialSoftkeysReleased = true;
int softkeyPending = 0;
int64_t softkeyDeadlineMs = 0;
auto stopViewfinderThread = [&]() {
vfShouldStop = true;
if (vfThread.joinable()) {
vfThread.join();
}
vfThreadRunning = false;
};
auto startViewfinderThread = [&]() {
stopViewfinderThread();
vfShouldStop = false;
vfThreadRunning = true;
{
std::lock_guard<std::mutex> lk(frameMutex);
cameraReady = false;
cameraStatus = "Starting /dev/video0...";
}
int writePipe = vfPipe[1];
vfThread = std::thread([&, writePipe]() {
int fd = ::open("/dev/video0", O_RDWR | O_CLOEXEC);
if (fd < 0) {
std::lock_guard<std::mutex> lk(frameMutex);
cameraReady = false;
cameraStatus = "/dev/video0 not available";
if (writePipe >= 0) {
char c = 'E';
(void)::write(writePipe, &c, 1);
}
vfThreadRunning = false;
return;
}
struct v4l2_format fmt {};
fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
fmt.fmt.pix.width = kCamW;
fmt.fmt.pix.height = kCamH;
fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_RGB24;
fmt.fmt.pix.field = V4L2_FIELD_NONE;
(void)::ioctl(fd, VIDIOC_S_FMT, &fmt);
bool useMmap = false;
void* mmapPtr = MAP_FAILED;
size_t mmapLen = 0;
struct v4l2_requestbuffers req {};
req.count = 1;
req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
req.memory = V4L2_MEMORY_MMAP;
if (::ioctl(fd, VIDIOC_REQBUFS, &req) == 0 && req.count >= 1) {
struct v4l2_buffer buf {};
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
buf.index = 0;
if (::ioctl(fd, VIDIOC_QUERYBUF, &buf) == 0) {
mmapLen = buf.length;
mmapPtr = ::mmap(nullptr, mmapLen, PROT_READ | PROT_WRITE, MAP_SHARED,
fd, buf.m.offset);
if (mmapPtr != MAP_FAILED) {
enum v4l2_buf_type type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
if (::ioctl(fd, VIDIOC_STREAMON, &type) == 0) {
useMmap = true;
}
}
}
}
std::vector<uint8_t> localRgb;
if (!useMmap) {
localRgb.resize(kCamFrameBytes);
}
while (!vfShouldStop && gRunning) {
bool doSnap = snapRequested.exchange(false);
bool usedTempFlash = false;
if (doSnap && flashAuto.load() && !getTorchState()) {
setTorchState(true);
usedTempFlash = true;
struct timespec ts {0, 120 * 1000 * 1000};
nanosleep(&ts, nullptr);
}
const uint8_t* framePtr = nullptr;
if (useMmap) {
struct v4l2_buffer buf {};
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
buf.index = 0;
if (::ioctl(fd, VIDIOC_QBUF, &buf) == 0 &&
::ioctl(fd, VIDIOC_DQBUF, &buf) == 0) {
framePtr = static_cast<const uint8_t*>(mmapPtr);
}
} else {
::lseek(fd, 0, SEEK_SET);
ssize_t r = ::read(fd, localRgb.data(), kCamFrameBytes);
if (r == static_cast<ssize_t>(kCamFrameBytes)) {
framePtr = localRgb.data();
}
}
if (usedTempFlash) {
setTorchState(false);
}
if (framePtr) {
int zf = zoomFactor.load();
downscaleViewfinder800x600To240x180(framePtr, vfBack.data(), zf);
std::string savedName;
if (doSnap) {
time_t nowSec = std::time(nullptr);
struct tm tmNow {};
localtime_r(&nowSec, &tmNow);
char nameBuf[64];
std::strftime(nameBuf, sizeof(nameBuf), "photo-%Y%m%d-%H%M%S.jpg",
&tmNow);
savedName = nameBuf;
std::string fullPath = getPicturesDir() + "/" + savedName;
saveZoomedRgb24AsJpeg(fullPath, framePtr, zf);
}
{
std::lock_guard<std::mutex> lk(frameMutex);
vfFront.swap(vfBack);
xImgVf->data = reinterpret_cast<char*>(vfFront.data());
cameraReady = true;
cameraStatus.clear();
if (!savedName.empty()) {
statusBanner = "Saved " + savedName;
statusBannerUntilMs = nowMs() + 2200;
shutterFlashUntilMs = nowMs() + 140;
}
}
if (writePipe >= 0) {
char c = 'F';
(void)::write(writePipe, &c, 1);
}
for (int s = 0; s < 5 && !vfShouldStop && gRunning && !snapRequested.load(); ++s) {
struct timespec ts {0, 20 * 1000 * 1000};
nanosleep(&ts, nullptr);
}
} else {
struct timespec ts {0, 50 * 1000 * 1000};
nanosleep(&ts, nullptr);
}
}
if (useMmap) {
enum v4l2_buf_type type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
(void)::ioctl(fd, VIDIOC_STREAMOFF, &type);
}
if (mmapPtr != MAP_FAILED) {
::munmap(mmapPtr, mmapLen);
}
::close(fd);
vfThreadRunning = false;
});
};
auto loadGalleryPhoto = [&]() {
if (photos.empty()) {
std::fill(vfFront.begin(), vfFront.end(), 0x101010);
galleryImgW = 0;
galleryImgH = 0;
return;
}
selectedPhoto = std::clamp(selectedPhoto, 0,
static_cast<int>(photos.size()) - 1);
std::vector<uint8_t> rgb;
if (loadImageRgb24(photos[selectedPhoto].fullPath, &rgb, &galleryImgW,
&galleryImgH)) {
scaleRgb24ToBgrxCanvas(rgb.data(), galleryImgW, galleryImgH,
vfFront.data(), kVfW, kVfH, 0x101010);
} else {
std::fill(vfFront.begin(), vfFront.end(), 0x101010);
galleryImgW = 0;
galleryImgH = 0;
}
};
auto enterGalleryMode = [&]() {
stopViewfinderThread();
photos = listSavedPhotos();
selectedPhoto = 0;
loadGalleryPhoto();
mode = ViewMode::Gallery;
};
auto enterViewfinderMode = [&]() {
mode = ViewMode::Viewfinder;
photos = listSavedPhotos();
if (visible) {
startViewfinderThread();
}
};
auto triggerShutter = [&]() {
if (timerEnabled && !countdownActive) {
countdownActive = true;
countdownTargetMs = nowMs() + 3000;
return;
}
countdownActive = false;
snapRequested = true;
};
auto drawPango = [&](PangoLayout* layout, XftColor* color, int x, int y, int h,
const std::string& text, int maxW = -1) {
return neo.drawPango(layout, color, x, y, h, text, maxW);
};
auto drawSoftkeyBar = [&](const std::string& leftLabel,
const std::string& centerLabel,
const std::string& rightLabel) {
neo.drawSoftbar(leftLabel, centerLabel, rightLabel, &colWhite);
};
auto drawUI = [&]() {
if (!visible) return;
pt.checkAndReload();
int64_t tNow = nowMs();
XSetForeground(dpy, gc, pt.spec.bgMain);
XFillRectangle(dpy, pix, gc, 0, 0, kWinWidth, kWinHeight);
if (mode == ViewMode::Viewfinder) {
// Top status bar (28px)
XSetForeground(dpy, gc, pt.spec.bgHeader);
XFillRectangle(dpy, pix, gc, 0, 0, kWinWidth, 28);
drawPango(layoutIcon, &colGreen, 6, 0, 28, kIconCamera);
drawPango(layoutMain, &colWhite, 28, 0, 28, "800x600", 85);
int zf = zoomFactor.load();
std::string zStr = std::to_string(zf) + ".0x";
drawPango(layoutMain, zf > 1 ? &colYellow : &colBlue, 114, 0, 28, zStr);
bool fl = flashAuto.load();
std::string flBadge = torchOn ? "TORCH" : (fl ? "FLASH" : "NO-FL");
pango_layout_set_width(layoutSmall, -1);
pango_layout_set_text(layoutSmall, flBadge.c_str(),
static_cast<int>(flBadge.size()));
int fw = 0, fhh = 0;
pango_layout_get_pixel_size(layoutSmall, &fw, &fhh);
drawPango(layoutSmall, (torchOn || fl) ? &colYellow : &colMuted,
kWinWidth - fw - 6, 0, 28, flBadge);
// Viewfinder canvas (240x180 at y = 28..208)
const int vfY = 28;
bool isReady = false;
std::string errMsg;
{
std::lock_guard<std::mutex> lk(frameMutex);
isReady = cameraReady;
errMsg = cameraStatus;
XPutImage(dpy, pix, gc, xImgVf, 0, 0, 0, vfY, kVfW, kVfH);
}
if (!isReady && !errMsg.empty()) {
drawPango(layoutSmall, &colLight, 16, vfY + 78, 24, errMsg, 208);
} else {
// Subtle framing reticle in center of viewfinder
XSetForeground(dpy, gc, pt.spec.accentAlt);
int cx = kWinWidth / 2;
int cy = vfY + kVfH / 2;
XDrawLine(dpy, pix, gc, cx - 10, cy, cx - 3, cy);
XDrawLine(dpy, pix, gc, cx + 3, cy, cx + 10, cy);
XDrawLine(dpy, pix, gc, cx, cy - 10, cx, cy - 3);
XDrawLine(dpy, pix, gc, cx, cy + 3, cx, cy + 10);
}
if (tNow < shutterFlashUntilMs) {
XSetForeground(dpy, gc, pt.spec.fgBright);
XDrawRectangle(dpy, pix, gc, 0, vfY, kVfW - 1, kVfH - 1);
XDrawRectangle(dpy, pix, gc, 1, vfY + 1, kVfW - 3, kVfH - 3);
}
if (countdownActive) {
int remSec = std::max(1, static_cast<int>((countdownTargetMs - tNow + 999) / 1000));
XSetForeground(dpy, gc, pt.spec.selBg);
XFillRectangle(dpy, pix, gc, 78, vfY + 66, 84, 44);
drawPango(layoutMain, &colWhite, 92, vfY + 66, 44,
"Timer: " + std::to_string(remSec));
}
// Camera control strip (y = 208..270, 62px)
const int ctlY = 208;
XSetForeground(dpy, gc, pt.spec.bgAltOdd);
XFillRectangle(dpy, pix, gc, 0, ctlY, kWinWidth, 62);
XSetForeground(dpy, gc, pt.spec.border);
XDrawLine(dpy, pix, gc, 0, ctlY, kWinWidth, ctlY);
// Pill 1: Flash (* or 1)
XSetForeground(dpy, gc, fl ? pt.spec.bgInputFocus : pt.spec.bgButton);
XFillRectangle(dpy, pix, gc, 6, ctlY + 5, 110, 24);
drawPango(layoutSmall, fl ? &colYellow : &colLight, 10, ctlY + 5, 24,
std::string("[*] Flash:") + (fl ? "ON" : "OFF"), 102);
// Pill 2: Torch (0 or 2)
XSetForeground(dpy, gc,
torchOn ? pt.spec.bgInputFocus : pt.spec.bgButton);
XFillRectangle(dpy, pix, gc, 124, ctlY + 5, 110, 24);
drawPango(layoutSmall, torchOn ? &colYellow : &colLight, 128, ctlY + 5,
24, std::string("[0] Torch:") + (torchOn ? "ON" : "OFF"), 102);
// Pill 3: Zoom (Up/Dn)
XSetForeground(dpy, gc,
zf > 1 ? pt.spec.bgInputFocus : pt.spec.bgButton);
XFillRectangle(dpy, pix, gc, 6, ctlY + 33, 110, 24);
drawPango(layoutSmall, &colBlue, 10, ctlY + 33, 24,
"[U/D] Zoom:" + std::to_string(zf) + "x", 102);
// Pill 4: Timer (# or 3)
XSetForeground(dpy, gc,
timerEnabled ? pt.spec.bgInputFocus : pt.spec.bgButton);
XFillRectangle(dpy, pix, gc, 124, ctlY + 33, 110, 24);
drawPango(layoutSmall, timerEnabled ? &colYellow : &colLight, 128,
ctlY + 33, 24,
std::string("[#] Timer:") + (timerEnabled ? "3s" : "OFF"), 102);
drawSoftkeyBar("Gallery", "SNAP", "Close");
} else if (mode == ViewMode::Gallery) {
XSetForeground(dpy, gc, pt.spec.bgHeader);
XFillRectangle(dpy, pix, gc, 0, 0, kWinWidth, 28);
drawPango(layoutIcon, &colBlue, 6, 0, 28, kIconImage);
drawPango(layoutMain, &colWhite, 28, 0, 28, "Gallery", 110);
std::string idxStr =
photos.empty() ? "0/0"
: (std::to_string(selectedPhoto + 1) + "/" +
std::to_string(photos.size()));
pango_layout_set_width(layoutSmall, -1);
pango_layout_set_text(layoutSmall, idxStr.c_str(),
static_cast<int>(idxStr.size()));
int iw = 0, ihh = 0;
pango_layout_get_pixel_size(layoutSmall, &iw, &ihh);
drawPango(layoutSmall, &colMuted, kWinWidth - iw - 6, 0, 28, idxStr);
const int vfY = 28;
if (photos.empty()) {
drawPango(layoutMain, &colMuted, 24, vfY + 75, 26, "No saved photos",
192);
} else {
XPutImage(dpy, pix, gc, xImgVf, 0, 0, 0, vfY, kVfW, kVfH);
const auto& pe = photos[selectedPhoto];
drawPango(layoutMain, &colWhite, 6, 212, 26, pe.name, 228);
std::string meta = std::to_string(galleryImgW) + "x" +
std::to_string(galleryImgH) + " " +
formatFileSize(pe.size) + " (L/R: Prev/Next)";
drawPango(layoutSmall, &colMuted, 6, 240, 22, meta, 228);
}
drawSoftkeyBar(photos.empty() ? "Camera" : "Delete",
photos.empty() ? "Camera" : "Full",
"Camera");
} else if (mode == ViewMode::ConfirmDelete && !photos.empty()) {
const auto& pe = photos[selectedPhoto];
XSetForeground(dpy, gc, pt.spec.bgHeader);
XFillRectangle(dpy, pix, gc, 0, 0, kWinWidth, 36);
drawPango(layoutIcon, &colRed, 8, 0, 36, kIconTrash);
drawPango(layoutMain, &colWhite, 30, 0, 36, "Delete Photo?", 200);
drawPango(layoutMain, &colWhite, 14, 70, 26, pe.name, 212);
drawPango(layoutSmall, &colMuted, 14, 100, 22,
"Remove this photo from ~/Pictures?", 212);
for (int i = 0; i < 2; ++i) {
int ry = 156 + i * 40;
bool isSel = (confirmSelected == i);
XSetForeground(
dpy, gc,
isSel ? (i == 1 ? pt.spec.dangerBg : pt.spec.selBg)
: pt.spec.bgButton);
XFillRectangle(dpy, pix, gc, 16, ry, kWinWidth - 32, 34);
drawPango(layoutMain, &colWhite, 28, ry, 34,
i == 0 ? "No, Keep Photo" : "Yes, Delete Photo", 184);
}
drawSoftkeyBar("Select", "Confirm", "Cancel");
}
{
std::lock_guard<std::mutex> lk(frameMutex);
if (!statusBanner.empty() && tNow < statusBannerUntilMs) {
XSetForeground(dpy, gc, pt.spec.bgToast);
XFillRectangle(dpy, pix, gc, 8, 174, kWinWidth - 16, 28);
XSetForeground(dpy, gc, pt.spec.success);
XDrawRectangle(dpy, pix, gc, 8, 174, kWinWidth - 17, 27);
drawPango(layoutSmall, &colWhite, 14, 174, 28, statusBanner,
kWinWidth - 28);
}
}
XCopyArea(dpy, pix, win, gc, 0, 0, kWinWidth, kWinHeight, 0, 0);
XFlush(dpy);
};
auto showWindow = [&](const std::string& argStr) {
writeIntFile(activePidPath, static_cast<int>(::getpid()));
closeOtherPlugins("camera");
countdownActive = false;
torchOn = getTorchState();
torchRestoredOnClose = !torchOn;
if (!visible) {
visible = true;
XMapRaised(dpy, win);
} else {
XRaiseWindow(dpy, win);
}
grabPluginKeyboard(dpy, win);
openStartMs = nowMs();
startupIgnoreUntilMs = openStartMs + 180;
initialSoftkeysReleased = (querySoftkeysDown(dpy) == 0);
softkeyPending = 0;
if (argStr == "gallery") {
enterGalleryMode();
} else {
enterViewfinderMode();
}
drawUI();
};
auto hideWindow = [&]() {
if (!visible) return;
countdownActive = false;
stopViewfinderThread();
if (torchOn && torchRestoredOnClose) {
setTorchState(false);
torchOn = false;
}
writeSoftkeySuppress(nowMs() + 450);
XUngrabKeyboard(dpy, CurrentTime);
XUnmapWindow(dpy, win);
XFlush(dpy);
visible = false;
::unlink(activePidPath.c_str());
};
auto handleSoftkeyAction = [&](bool isLeft) {
if (mode == ViewMode::Viewfinder) {
if (isLeft) {
enterGalleryMode();
} else {
hideWindow();
return;
}
} else if (mode == ViewMode::Gallery) {
if (isLeft) {
if (photos.empty()) {
enterViewfinderMode();
} else {
confirmSelected = 0;
mode = ViewMode::ConfirmDelete;
}
} else {
enterViewfinderMode();
}
} else if (mode == ViewMode::ConfirmDelete) {
if (isLeft) {
if (confirmSelected == 1 && !photos.empty()) {
::unlink(photos[selectedPhoto].fullPath.c_str());
photos = listSavedPhotos();
loadGalleryPhoto();
}
mode = ViewMode::Gallery;
} else {
mode = ViewMode::Gallery;
}
}
drawUI();
};
if (!isPreload) {
showWindow(initArg);
}
int xfd = ConnectionNumber(dpy);
while (gRunning) {
for (const auto& cmd : readFifoLines(fifoFd)) {
if (cmd == "NOP") {
continue;
} else if (cmd == "RELOAD_THEME") {
pt.reload();
if (visible) drawUI();
} else if (cmd == "CLOSE") {
hideWindow();
} else if (cmd == "OPEN") {
showWindow("");
} else if (cmd.rfind("OPEN ", 0) == 0) {
showWindow(trimStr(cmd.substr(5)));
}
}
while (XPending(dpy) > 0) {
XEvent ev;
XNextEvent(dpy, &ev);
if (!visible) continue;
if (ev.type == Expose && ev.xexpose.count == 0) {
drawUI();
} else if (ev.type == VisibilityNotify &&
ev.xvisibility.state != VisibilityUnobscured) {
if (isAnotherPluginActive("camera")) {
hideWindow();
} else {
XRaiseWindow(dpy, win);
grabPluginKeyboard(dpy, win);
drawUI();
}
} else if (ev.type == KeyPress) {
int64_t tNow = nowMs();
unsigned int kc = ev.xkey.keycode;
KeySym sym = XLookupKeysym(&ev.xkey, 0);
bool isLeftSk =
(kc == 135 || sym == XK_Menu || sym == XF86XK_KbdLcdMenu1 ||
sym == _EVDEVK(0x246) || sym == XK_F1);
bool isRightSk =
(kc == 166 || sym == XF86XK_Back || sym == XF86XK_KbdLcdMenu2 ||
sym == _EVDEVK(0x247) || sym == XK_F2);
if (!initialSoftkeysReleased) {
if (querySoftkeysDown(dpy) == 0) {
initialSoftkeysReleased = true;
} else if (isLeftSk || isRightSk) {
continue;
}
}
if (tNow < startupIgnoreUntilMs && (isLeftSk || isRightSk)) {
continue;
}
if (isLeftSk || isRightSk) {
int bit = isLeftSk ? 1 : 2;
softkeyPending |= bit;
if (softkeyPending == 3 || querySoftkeysDown(dpy) == 3) {
softkeyPending = 0;
sendPluginCommand("xdrawer", "TOGGLE");
continue;
}
softkeyDeadlineMs = tNow + 35;
continue;
}
if (sym == XK_Escape || kc == 124 || sym == XF86XK_PowerOff) {
hideWindow();
continue;
}
if (sym == XK_BackSpace || sym == XK_Delete) {
handleSoftkeyAction(false);
continue;
}
bool isCallKey =
(kc == 177 || sym == XF86XK_PickupPhone || sym == XF86XK_Phone ||
sym == _EVDEVK(0x1bd) || sym == _EVDEVK(0x0a9));
if (mode == ViewMode::Viewfinder) {
if (sym == XK_Return || sym == XK_KP_Enter || sym == XK_space ||
isCallKey) {
triggerShutter();
drawUI();
} else if (sym == XK_Up || sym == XK_KP_Up) {
int curZ = zoomFactor.load();
zoomFactor = (curZ == 1) ? 2 : (curZ == 2 ? 4 : 4);
drawUI();
} else if (sym == XK_Down || sym == XK_KP_Down) {
int curZ = zoomFactor.load();
zoomFactor = (curZ == 4) ? 2 : 1;
drawUI();
} else {
char d = mapDialKey(sym, kc, ev.xkey.state);
if (d == '5') {
triggerShutter();
drawUI();
} else if (d == '1' || d == '*') {
flashAuto = !flashAuto.load();
drawUI();
} else if (d == '2' || d == '0') {
torchOn = !torchOn;
setTorchState(torchOn);
drawUI();
} else if (d == '3' || d == '#') {
timerEnabled = !timerEnabled;
countdownActive = false;
drawUI();
}
}
} else if (mode == ViewMode::Gallery) {
if (sym == XK_Left || sym == XK_KP_Left || sym == XK_Up ||
sym == XK_KP_Up) {
if (!photos.empty()) {
selectedPhoto =
(selectedPhoto - 1 + static_cast<int>(photos.size())) %
static_cast<int>(photos.size());
loadGalleryPhoto();
drawUI();
}
} else if (sym == XK_Right || sym == XK_KP_Right || sym == XK_Down ||
sym == XK_KP_Down) {
if (!photos.empty()) {
selectedPhoto =
(selectedPhoto + 1) % static_cast<int>(photos.size());
loadGalleryPhoto();
drawUI();
}
} else if (sym == XK_Return || sym == XK_KP_Enter) {
if (photos.empty()) {
enterViewfinderMode();
drawUI();
} else {
std::string path = photos[selectedPhoto].fullPath;
hideWindow();
runAsyncArgv("feh", path.c_str());
}
}
} else if (mode == ViewMode::ConfirmDelete) {
if (sym == XK_Up || sym == XK_Down || sym == XK_KP_Up ||
sym == XK_KP_Down) {
confirmSelected = 1 - confirmSelected;
drawUI();
} else if (sym == XK_Return || sym == XK_KP_Enter) {
handleSoftkeyAction(true);
}
}
}
}
int64_t tNow = nowMs();
if (visible && softkeyPending != 0 && tNow >= softkeyDeadlineMs) {
if (querySoftkeysDown(dpy) == 3) {
softkeyPending = 0;
sendPluginCommand("xdrawer", "TOGGLE");
} else {
bool isLeft = (softkeyPending == 1);
softkeyPending = 0;
handleSoftkeyAction(isLeft);
}
}
if (visible && countdownActive && tNow >= countdownTargetMs) {
countdownActive = false;
snapRequested = true;
drawUI();
}
int timeoutMs = -1;
if (visible) {
if (softkeyPending != 0) {
timeoutMs = std::max(1, static_cast<int>(softkeyDeadlineMs - tNow));
} else if (countdownActive) {
timeoutMs = 150;
}
}
struct pollfd pfds[3];
int nfds = 0;
pfds[nfds++] = {xfd, POLLIN, 0};
int fifoIdx = -1;
if (fifoFd >= 0) {
fifoIdx = nfds;
pfds[nfds++] = {fifoFd, POLLIN, 0};
}
int vfIdx = -1;
if (vfPipe[0] >= 0) {
vfIdx = nfds;
pfds[nfds++] = {vfPipe[0], POLLIN, 0};
}
int pr = ::poll(pfds, nfds, timeoutMs);
if (pr > 0) {
if (fifoIdx >= 0 && (pfds[fifoIdx].revents & POLLIN)) {
for (const auto& cmd : readFifoLines(fifoFd)) {
if (cmd == "RELOAD_THEME") {
pt.reload();
if (visible) drawUI();
} else if (cmd == "CLOSE") {
hideWindow();
} else if (cmd == "OPEN") {
showWindow("");
} else if (cmd.rfind("OPEN ", 0) == 0) {
showWindow(trimStr(cmd.substr(5)));
}
}
}
if (vfIdx >= 0 && (pfds[vfIdx].revents & POLLIN)) {
char drain[64];
while (::read(vfPipe[0], drain, sizeof(drain)) > 0) {
}
if (visible && mode == ViewMode::Viewfinder) {
drawUI();
}
}
} else if (pr == 0 && visible && countdownActive) {
drawUI();
}
}
hideWindow();
if (xImgVf) {
xImgVf->data = nullptr;
XDestroyImage(xImgVf);
}
if (fifoFd >= 0) ::close(fifoFd);
if (vfPipe[0] >= 0) ::close(vfPipe[0]);
if (vfPipe[1] >= 0) ::close(vfPipe[1]);
::unlink(daemonPidPath.c_str());
return 0;
}
int camera_plugin_init(const DwmHostApi* host) {
if (host && host->spawn_plugin) {
host->spawn_plugin("camera", "--preload");
}
return 0;
}
} // namespace
extern "C" __attribute__((visibility("default"))) const DwmPlugin dwm_plugin_entry = {
DWM_PLUGIN_API_VERSION,
"camera",
"Camera app with live V4L2 viewfinder, flash/torch, zoom, and photo gallery",
camera_plugin_init,
nullptr,
nullptr,
nullptr,
nullptr,
runCameraApp
};