suwako / UnixWallpaper アーカイブ

このリポジトリはアーカイブされています。読むだけで、プッシュやイシューの変更は出来ません。

master
ブランチ master
UnixWallpaper / src / uw / image.cc
2.2 KB、78行 生 Blame 履歴
1#include <X11/Xlib.h>
2#include <string>
3#define STB_IMAGE_IMPLEMENTATION
4#include "../dep/stb_image.hh"
5
6#include <stdexcept>
7
8#include "image.hh"
9
10namespace uw {
11 Image::Image(Screen &screen, const std::string imgPath) : uwScreen{ screen } {
12 if (imgPath.empty()) throw std::runtime_error("画像パスが空です。");
13
14 data = stbi_load(imgPath.c_str(), &width, &height, &chan, 4);
15 if (!data) throw std::runtime_error("画像の読み込みに失敗: " + imgPath);
16
17 imageExtent.width = width;
18 imageExtent.height = height;
19 imagePath = imgPath;
20
21 v = DefaultVisual(screen.getDisplay(), screen.getScreen());
22
23 createDepth();
24 createPixmap();
25 createImage();
26 createGC();
27 }
28
29 Image::~Image() {
30 if (gc) XFreeGC(uwScreen.getDisplay(), gc);
31 if (pm) XFreePixmap(uwScreen.getDisplay(), pm);
32 if (image) XFree(image);
33 if (data) stbi_image_free(data);
34 }
35
36 void Image::createDepth() {
37 depth = DefaultDepth(uwScreen.getDisplay(), uwScreen.getScreen());
38
39 if (depth != 24 && depth != 32) {
40 throw std::runtime_error(
41 "「" + std::to_string(depth) + "」の様な視覚の深さは未対応です。");
42 }
43
44 imageExtent.depth = depth;
45 }
46
47 void Image::createPixmap() {
48 pm = XCreatePixmap(uwScreen.getDisplay(), uwScreen.getWindow(), width, height,
49 depth);
50 }
51
52 void Image::createImage() {
53 if (depth == 24) {
54 std::vector<uchar> cd(data, data + (width * height * 4));
55 cdata = cd;
56
57 for (int i = 0; i < width * height; i++) {
58 cdata[i * 4 + 0] = data[i * 4 + 2];
59 cdata[i * 4 + 1] = data[i * 4 + 1];
60 cdata[i * 4 + 2] = data[i * 4 + 0];
61 cdata[i * 4 + 3] = data[i * 4 + 3];
62 }
63
64 image = XCreateImage(uwScreen.getDisplay(), v, depth, ZPixmap, 0,
65 (char *)cdata.data(), width, height, 32, 0);
66 } else {
67 image = XCreateImage(uwScreen.getDisplay(), v, depth, ZPixmap, 0,
68 (char *)data, width, height, 32, 0);
69 }
70
71 if (!image) throw std::runtime_error("XImageの作成に失敗。");
72 }
73
74 void Image::createGC() {
75 gc = XCreateGC(uwScreen.getDisplay(), pm, 0, nullptr);
76 if (!gc) throw std::runtime_error("GCの作成に失敗。");
77 }
78}