comparison src/platform/linux/xlib.nim @ 466:1dd9e2393a9e

add: structure code for crossplatform, add some input handling + bugfixes
author Sam <sam@basx.dev>
date Thu, 22 Dec 2022 00:06:40 +0700
parents
children
comparison
equal deleted inserted replaced
465:2fcb9268072b 466:1dd9e2393a9e
1 import
2 x11/xlib,
3 x11/xutil,
4 x11/keysym
5 import x11/x
6
7 import ../../events
8
9 import ./symkey_map
10
11 export keysym
12
13 var deleteMessage*: Atom
14
15 type
16 NativeWindow* = object
17 display*: PDisplay
18 window*: Window
19
20 template checkXlibResult*(call: untyped) =
21 let value = call
22 if value == 0:
23 raise newException(Exception, "Xlib error: " & astToStr(call) & " returned " & $value)
24
25 proc createWindow*(title: string): NativeWindow =
26 checkXlibResult XInitThreads()
27 let display = XOpenDisplay(nil)
28 if display == nil:
29 quit "Failed to open display"
30
31 let
32 screen = XDefaultScreen(display)
33 rootWindow = XRootWindow(display, screen)
34 foregroundColor = XBlackPixel(display, screen)
35 backgroundColor = XWhitePixel(display, screen)
36
37 let window = XCreateSimpleWindow(display, rootWindow, -1, -1, 800, 600, 0, foregroundColor, backgroundColor)
38 checkXlibResult XSetStandardProperties(display, window, title, "window", 0, nil, 0, nil)
39 checkXlibResult XSelectInput(display, window, ButtonPressMask or KeyPressMask or ExposureMask)
40 checkXlibResult XMapWindow(display, window)
41
42 deleteMessage = XInternAtom(display, "WM_DELETE_WINDOW", XBool(false))
43 checkXlibResult XSetWMProtocols(display, window, addr(deleteMessage), 1)
44
45 return NativeWindow(display: display, window: window)
46
47 proc trash*(window: NativeWindow) =
48 checkXlibResult window.display.XDestroyWindow(window.window)
49 discard window.display.XCloseDisplay() # always returns 0
50
51 proc size*(window: NativeWindow): (int, int) =
52 var attribs: XWindowAttributes
53 checkXlibResult XGetWindowAttributes(window.display, window.window, addr(attribs))
54 return (int(attribs.width), int(attribs.height))
55
56 proc pendingEvents*(window: NativeWindow): seq[Event] =
57 var event: XEvent
58 while window.display.XPending() > 0:
59 discard window.display.XNextEvent(addr(event))
60 case event.theType
61 of ClientMessage:
62 if cast[Atom](event.xclient.data.l[0]) == deleteMessage:
63 result.add(Event(eventType: Quit))
64 of KeyPress:
65 let xkey: KeySym = XLookupKeysym(cast[PXKeyEvent](addr(event)), 0)
66 result.add(Event(eventType: KeyDown, key: KeyTypeMap.getOrDefault(xkey, UNKNOWN)))
67 of KeyRelease:
68 let xkey: KeySym = XLookupKeysym(cast[PXKeyEvent](addr(event)), 0)
69 result.add(Event(eventType: KeyUp, key: KeyTypeMap.getOrDefault(xkey, UNKNOWN)))
70 of ConfigureNotify:
71 result.add(Event(eventType: ResizedWindow))
72 else:
73 discard