]> git.tdb.fi Git - libs/gui.git/blob - source/gbase/drawcontext.cpp
d3ac4856324811d04059dbf94c919e207ce48f13
[libs/gui.git] / source / gbase / drawcontext.cpp
1 /* $Id$
2
3 This file is part of libmspgbase
4 Copyright © 2007 Mikko Rasa, Mikkosoft Productions
5 Distributed under the LGPL
6 */
7
8 #ifndef WIN32
9 #include <sys/ipc.h>
10 #include <sys/shm.h>
11 #include <X11/Xutil.h>
12 #endif
13 #include <msp/core/except.h>
14 #include "display.h"
15 #include "drawcontext.h"
16 #include "window.h"
17
18 namespace Msp {
19 namespace Graphics {
20
21 DrawContext::DrawContext(Window &w):
22         display(w.get_display()),
23         window(w),
24         image(0)
25 {
26 #ifndef WIN32
27         ::Display *dpy=display.get_display();
28
29         use_shm=XShmQueryExtension(dpy);
30
31         XWindowAttributes wa;
32         XGetWindowAttributes(dpy, window.get_handle(), &wa);
33
34         if(use_shm)
35         {
36                 image=XShmCreateImage(dpy, wa.visual, wa.depth, ZPixmap, 0, &shminfo, wa.width, wa.height);
37                 if(!image)
38                         throw Exception("Could not create shared memory XImage");
39
40                 shminfo.shmid=shmget(IPC_PRIVATE, image->bytes_per_line*image->height, IPC_CREAT|0666);
41                 shminfo.shmaddr=image->data=reinterpret_cast<char *>(shmat(shminfo.shmid, 0, 0));
42                 shminfo.readOnly=false;
43
44                 XShmAttach(dpy, &shminfo);
45
46                 XSync(dpy, false);
47                 display.check_error();
48         }
49         else
50         {
51                 image=XCreateImage(dpy, wa.visual, wa.depth, ZPixmap, 0, 0, wa.width, wa.height, 8, 0);
52                 if(!image)
53                         throw Exception("Could not create XImage");
54                 image->data=new char[image->bytes_per_line*image->height];
55         }
56 #endif
57 }
58
59 DrawContext::~DrawContext()
60 {
61 #ifndef WIN32
62         if(use_shm)
63         {
64                 XShmDetach(display.get_display(), &shminfo);
65                 shmdt(shminfo.shmaddr);
66                 shmctl(shminfo.shmid, IPC_RMID, 0);
67         }
68
69         XDestroyImage(image);
70 #endif
71 }
72
73 void DrawContext::update()
74 {
75 #ifndef WIN32
76         ::Display *dpy=display.get_display();
77
78         GC gc=XCreateGC(dpy, window.get_handle(), 0, 0);
79
80         if(use_shm)
81                 XShmPutImage(dpy, window.get_handle(), gc, image, 0, 0, 0, 0, image->width, image->height, false);
82         else
83                 XPutImage(dpy, window.get_handle(), gc, image, 0, 0, 0, 0, image->width, image->height);
84
85         XFreeGC(dpy, gc);
86 #endif
87 }
88
89 } // namespace Graphics
90 } // namespace Msp