This repository was archived by the owner on Nov 7, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwindow.cc
94 lines (79 loc) · 2.48 KB
/
window.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// Copyright (c) 2016 Kai Luo. All rights reserved.
// Use of this source code is governed by the BSD license that can be found in
// the LICENSE file.
#include "window.h"
#include <chrono>
#include <thread>
namespace zLi {
const float Window::FPSLimit = 120;
Window::Window(int w, int h)
: width_(w), height_(h), disp_(nullptr), should_close_(false) {}
Window::~Window() {
if (disp_) {
XDestroyWindow(disp_, window_);
XCloseDisplay(disp_);
}
}
std::string Window::ToXColorName(const RGBColor &rgb) {
char buf[512];
std::snprintf(buf, sizeof(buf), "RGBi:%f/%f/%f", rgb.r, rgb.g, rgb.b);
return std::string(buf);
}
std::string Window::ToXColorName(const xyYColor &xyY) {
char buf[512];
std::snprintf(buf, sizeof(buf), "CIExyY:%f/%f/%f", xyY.x, xyY.y, xyY.Y);
return std::string(buf);
}
void Window::Flush() { XFlush(disp_); }
kl::Result<void> Window::Init() {
disp_ = XOpenDisplay(nullptr);
if (!disp_) {
return kl::Err("Can't open display");
}
screen_ = DefaultScreen(disp_);
window_ = XCreateSimpleWindow(disp_, RootWindow(disp_, screen_), 0, 0, width_,
height_, 0, BlackPixel(disp_, screen_),
BlackPixel(disp_, screen_));
Atom deleteWindow = XInternAtom(disp_, "WM_DELETE_WINDOW", false);
XSetWMProtocols(disp_, window_, &deleteWindow, 1);
XSelectInput(disp_, window_, ExposureMask | KeyPressMask);
// XGCValues values;
// unsigned long valuemask = GCCapStyle | GCJoinStyle;
gc_ = DefaultGC(disp_, screen_);
XMapWindow(disp_, window_);
return kl::Ok();
}
void Window::PollEvents() {
int count = XPending(disp_);
while (count--) {
XEvent ev;
XNextEvent(disp_, &ev);
// ESC pressed
if (ev.type == KeyPress && ev.xkey.keycode == 9) {
should_close_ = true;
}
if (ev.type == ClientMessage) {
should_close_ = true;
}
}
}
void Window::Loop(std::function<void()> &&display,
std::function<void()> &&atExitLoop) {
float time_slice = 1 / FPSLimit;
auto start = std::chrono::high_resolution_clock::now();
while (!should_close_) {
PollEvents();
display();
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<float> diff = end - start;
if (diff.count() < time_slice) {
std::this_thread::sleep_for(
std::chrono::duration<float>(time_slice - diff.count()));
}
start = std::chrono::high_resolution_clock::now();
}
if (atExitLoop) {
atExitLoop();
}
}
} // namespace zLi