compositor: Parse config file in main(), only keep weston config object
[profile/ivi/weston-ivi-shell.git] / src / compositor-rdp.c
1 /*
2  * Copyright © 2013 Hardening <rdp.effort@gmail.com>
3  *
4  * Permission to use, copy, modify, distribute, and sell this software and
5  * its documentation for any purpose is hereby granted without fee, provided
6  * that the above copyright notice appear in all copies and that both that
7  * copyright notice and this permission notice appear in supporting
8  * documentation, and that the name of the copyright holders not be used in
9  * advertising or publicity pertaining to distribution of the software
10  * without specific, written prior permission.  The copyright holders make
11  * no representations about the suitability of this software for any
12  * purpose.  It is provided "as is" without express or implied warranty.
13  *
14  * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS
15  * SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
16  * FITNESS, IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
17  * SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
18  * RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
19  * CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
20  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
21  */
22
23 #ifdef HAVE_CONFIG_H
24 #include <config.h>
25 #endif
26
27 #include <stdlib.h>
28 #include <string.h>
29 #include <errno.h>
30 #include <linux/input.h>
31
32 #include <freerdp/freerdp.h>
33 #include <freerdp/listener.h>
34 #include <freerdp/update.h>
35 #include <freerdp/input.h>
36 #include <freerdp/codec/color.h>
37 #include <freerdp/codec/rfx.h>
38 #include <freerdp/codec/nsc.h>
39 #include <winpr/input.h>
40
41 #include "compositor.h"
42 #include "pixman-renderer.h"
43
44 #define MAX_FREERDP_FDS 32
45
46 struct rdp_compositor_config {
47         int width;
48         int height;
49         char *bind_address;
50         int port;
51         char *rdp_key;
52         char *server_cert;
53         char *server_key;
54         char *extra_modes;
55         int env_socket;
56 };
57
58 struct rdp_output;
59
60 struct rdp_compositor {
61         struct weston_compositor base;
62
63         freerdp_listener *listener;
64         struct wl_event_source *listener_events[MAX_FREERDP_FDS];
65         struct rdp_output *output;
66
67         char *server_cert;
68         char *server_key;
69         char *rdp_key;
70         int tls_enabled;
71 };
72
73 enum peer_item_flags {
74         RDP_PEER_ACTIVATED      = (1 << 0),
75         RDP_PEER_OUTPUT_ENABLED = (1 << 1),
76 };
77
78 struct rdp_peers_item {
79         int flags;
80         freerdp_peer *peer;
81         struct weston_seat seat;
82
83         struct wl_list link;
84 };
85
86 struct rdp_output {
87         struct weston_output base;
88         struct wl_event_source *finish_frame_timer;
89         pixman_image_t *shadow_surface;
90
91         struct wl_list peers;
92 };
93
94 struct rdp_peer_context {
95         rdpContext _p;
96
97         struct rdp_compositor *rdpCompositor;
98         struct wl_event_source *events[MAX_FREERDP_FDS];
99         RFX_CONTEXT *rfx_context;
100         wStream *encode_stream;
101         RFX_RECT *rfx_rects;
102         NSC_CONTEXT *nsc_context;
103
104         struct rdp_peers_item item;
105 };
106 typedef struct rdp_peer_context RdpPeerContext;
107
108 static void
109 rdp_compositor_config_init(struct rdp_compositor_config *config) {
110         config->width = 640;
111         config->height = 480;
112         config->bind_address = NULL;
113         config->port = 3389;
114         config->rdp_key = NULL;
115         config->server_cert = NULL;
116         config->server_key = NULL;
117         config->extra_modes = NULL;
118         config->env_socket = 0;
119 }
120
121 static void
122 rdp_peer_refresh_rfx(pixman_region32_t *damage, pixman_image_t *image, freerdp_peer *peer)
123 {
124         int width, height, nrects, i;
125         pixman_box32_t *region, *rects;
126         uint32_t *ptr;
127         RFX_RECT *rfxRect;
128         rdpUpdate *update = peer->update;
129         SURFACE_BITS_COMMAND *cmd = &update->surface_bits_command;
130         RdpPeerContext *context = (RdpPeerContext *)peer->context;
131
132         Stream_Clear(context->encode_stream);
133         Stream_SetPosition(context->encode_stream, 0);
134
135         width = (damage->extents.x2 - damage->extents.x1);
136         height = (damage->extents.y2 - damage->extents.y1);
137
138         cmd->destLeft = damage->extents.x1;
139         cmd->destTop = damage->extents.y1;
140         cmd->destRight = damage->extents.x2;
141         cmd->destBottom = damage->extents.y2;
142         cmd->bpp = 32;
143         cmd->codecID = peer->settings->RemoteFxCodecId;
144         cmd->width = width;
145         cmd->height = height;
146
147         ptr = pixman_image_get_data(image) + damage->extents.x1 +
148                                 damage->extents.y1 * (pixman_image_get_stride(image) / sizeof(uint32_t));
149
150         rects = pixman_region32_rectangles(damage, &nrects);
151         context->rfx_rects = realloc(context->rfx_rects, nrects * sizeof *rfxRect);
152
153         for (i = 0; i < nrects; i++) {
154                 region = &rects[i];
155                 rfxRect = &context->rfx_rects[i];
156
157                 rfxRect->x = (region->x1 - damage->extents.x1);
158                 rfxRect->y = (region->y1 - damage->extents.y1);
159                 rfxRect->width = (region->x2 - region->x1);
160                 rfxRect->height = (region->y2 - region->y1);
161         }
162
163         rfx_compose_message(context->rfx_context, context->encode_stream, context->rfx_rects, nrects,
164                         (BYTE *)ptr, width, height,
165                         pixman_image_get_stride(image)
166         );
167
168         cmd->bitmapDataLength = Stream_GetPosition(context->encode_stream);
169         cmd->bitmapData = Stream_Buffer(context->encode_stream);
170
171         update->SurfaceBits(update->context, cmd);
172 }
173
174
175 static void
176 rdp_peer_refresh_nsc(pixman_region32_t *damage, pixman_image_t *image, freerdp_peer *peer)
177 {
178         int width, height;
179         uint32_t *ptr;
180         rdpUpdate *update = peer->update;
181         SURFACE_BITS_COMMAND *cmd = &update->surface_bits_command;
182         RdpPeerContext *context = (RdpPeerContext *)peer->context;
183
184         Stream_Clear(context->encode_stream);
185         Stream_SetPosition(context->encode_stream, 0);
186
187         width = (damage->extents.x2 - damage->extents.x1);
188         height = (damage->extents.y2 - damage->extents.y1);
189
190         cmd->destLeft = damage->extents.x1;
191         cmd->destTop = damage->extents.y1;
192         cmd->destRight = damage->extents.x2;
193         cmd->destBottom = damage->extents.y2;
194         cmd->bpp = 32;
195         cmd->codecID = peer->settings->NSCodecId;
196         cmd->width = width;
197         cmd->height = height;
198
199         ptr = pixman_image_get_data(image) + damage->extents.x1 +
200                                 damage->extents.y1 * (pixman_image_get_stride(image) / sizeof(uint32_t));
201
202         nsc_compose_message(context->nsc_context, context->encode_stream, (BYTE *)ptr,
203                         cmd->width,     cmd->height,
204                         pixman_image_get_stride(image));
205         cmd->bitmapDataLength = Stream_GetPosition(context->encode_stream);
206         cmd->bitmapData = Stream_Buffer(context->encode_stream);
207         update->SurfaceBits(update->context, cmd);
208 }
209
210 static void
211 pixman_image_flipped_subrect(const pixman_box32_t *rect, pixman_image_t *img, BYTE *dest) {
212         int stride = pixman_image_get_stride(img);
213         int h;
214         int toCopy = (rect->x2 - rect->x1) * 4;
215         int height = (rect->y2 - rect->y1);
216         const BYTE *src = (const BYTE *)pixman_image_get_data(img);
217         src += ((rect->y2-1) * stride) + (rect->x1 * 4);
218
219         for (h = 0; h < height; h++, src -= stride, dest += toCopy)
220                    memcpy(dest, src, toCopy);
221 }
222
223 static void
224 rdp_peer_refresh_raw(pixman_region32_t *region, pixman_image_t *image, freerdp_peer *peer)
225 {
226         rdpUpdate *update = peer->update;
227         SURFACE_BITS_COMMAND *cmd = &update->surface_bits_command;
228         SURFACE_FRAME_MARKER *marker = &update->surface_frame_marker;
229         pixman_box32_t *rect, subrect;
230         int nrects, i;
231         int heightIncrement, remainingHeight, top;
232
233         rect = pixman_region32_rectangles(region, &nrects);
234         if (!nrects)
235                 return;
236
237         marker->frameId++;
238         marker->frameAction = SURFACECMD_FRAMEACTION_BEGIN;
239         update->SurfaceFrameMarker(peer->context, marker);
240
241         cmd->bpp = 32;
242         cmd->codecID = 0;
243
244         for (i = 0; i < nrects; i++, rect++) {
245                 /*weston_log("rect(%d,%d, %d,%d)\n", rect->x1, rect->y1, rect->x2, rect->y2);*/
246                 cmd->destLeft = rect->x1;
247                 cmd->destRight = rect->x2;
248                 cmd->width = rect->x2 - rect->x1;
249
250                 heightIncrement = peer->settings->MultifragMaxRequestSize / (16 + cmd->width * 4);
251                 remainingHeight = rect->y2 - rect->y1;
252                 top = rect->y1;
253
254                 subrect.x1 = rect->x1;
255                 subrect.x2 = rect->x2;
256
257                 while (remainingHeight) {
258                            cmd->height = (remainingHeight > heightIncrement) ? heightIncrement : remainingHeight;
259                            cmd->destTop = top;
260                            cmd->destBottom = top + cmd->height;
261                            cmd->bitmapDataLength = cmd->width * cmd->height * 4;
262                            cmd->bitmapData = (BYTE *)realloc(cmd->bitmapData, cmd->bitmapDataLength);
263
264                            subrect.y1 = top;
265                            subrect.y2 = top + cmd->height;
266                            pixman_image_flipped_subrect(&subrect, image, cmd->bitmapData);
267
268                            /*weston_log("*  sending (%d,%d, %d,%d)\n", subrect.x1, subrect.y1, subrect.x2, subrect.y2); */
269                            update->SurfaceBits(peer->context, cmd);
270
271                            remainingHeight -= cmd->height;
272                            top += cmd->height;
273                 }
274         }
275
276         marker->frameAction = SURFACECMD_FRAMEACTION_END;
277         update->SurfaceFrameMarker(peer->context, marker);
278 }
279
280 static void
281 rdp_peer_refresh_region(pixman_region32_t *region, freerdp_peer *peer)
282 {
283         RdpPeerContext *context = (RdpPeerContext *)peer->context;
284         struct rdp_output *output = context->rdpCompositor->output;
285         rdpSettings *settings = peer->settings;
286
287         if (settings->RemoteFxCodec)
288                 rdp_peer_refresh_rfx(region, output->shadow_surface, peer);
289         else if (settings->NSCodec)
290                 rdp_peer_refresh_nsc(region, output->shadow_surface, peer);
291         else
292                 rdp_peer_refresh_raw(region, output->shadow_surface, peer);
293 }
294
295 static void
296 rdp_output_start_repaint_loop(struct weston_output *output)
297 {
298         uint32_t msec;
299         struct timeval tv;
300
301         gettimeofday(&tv, NULL);
302         msec = tv.tv_sec * 1000 + tv.tv_usec / 1000;
303         weston_output_finish_frame(output, msec);
304 }
305
306 static void
307 rdp_output_repaint(struct weston_output *output_base, pixman_region32_t *damage)
308 {
309         struct rdp_output *output = container_of(output_base, struct rdp_output, base);
310         struct weston_compositor *ec = output->base.compositor;
311         struct rdp_peers_item *outputPeer;
312
313         pixman_renderer_output_set_buffer(output_base, output->shadow_surface);
314         ec->renderer->repaint_output(&output->base, damage);
315
316         wl_list_for_each(outputPeer, &output->peers, link) {
317                 if ((outputPeer->flags & RDP_PEER_ACTIVATED) &&
318                                 (outputPeer->flags & RDP_PEER_OUTPUT_ENABLED))
319                 {
320                         rdp_peer_refresh_region(damage, outputPeer->peer);
321                 }
322         }
323
324         pixman_region32_subtract(&ec->primary_plane.damage,
325                                  &ec->primary_plane.damage, damage);
326
327         wl_event_source_timer_update(output->finish_frame_timer, 16);
328 }
329
330 static void
331 rdp_output_destroy(struct weston_output *output_base)
332 {
333         struct rdp_output *output = (struct rdp_output *)output_base;
334
335         wl_event_source_remove(output->finish_frame_timer);
336         free(output);
337 }
338
339 static int
340 finish_frame_handler(void *data)
341 {
342         rdp_output_start_repaint_loop(data);
343
344         return 1;
345 }
346
347
348 static struct weston_mode *
349 find_matching_mode(struct weston_output *output, struct weston_mode *target) {
350         struct weston_mode *local;
351
352         wl_list_for_each(local, &output->mode_list, link) {
353                 if((local->width == target->width) && (local->height == target->height))
354                         return local;
355         }
356         return 0;
357 }
358
359 static int
360 rdp_switch_mode(struct weston_output *output, struct weston_mode *target_mode) {
361         struct rdp_output *rdpOutput = container_of(output, struct rdp_output, base);
362         struct rdp_peers_item *rdpPeer;
363         rdpSettings *settings;
364         pixman_image_t *new_shadow_buffer;
365         struct weston_mode *local_mode;
366
367         local_mode = find_matching_mode(output, target_mode);
368         if(!local_mode) {
369                 weston_log("mode %dx%d not available\n", target_mode->width, target_mode->height);
370                 return -ENOENT;
371         }
372
373         if(local_mode == output->current)
374                 return 0;
375
376         output->current->flags = 0;
377         output->current = local_mode;
378         output->current->flags = WL_OUTPUT_MODE_CURRENT | WL_OUTPUT_MODE_PREFERRED;
379
380         pixman_renderer_output_destroy(output);
381         pixman_renderer_output_create(output);
382
383         new_shadow_buffer = pixman_image_create_bits(PIXMAN_x8r8g8b8, target_mode->width,
384                         target_mode->height, 0, target_mode->width * 4);
385         pixman_image_composite32(PIXMAN_OP_SRC, rdpOutput->shadow_surface, 0, new_shadow_buffer,
386                         0, 0, 0, 0, 0, 0, target_mode->width, target_mode->height);
387         pixman_image_unref(rdpOutput->shadow_surface);
388         rdpOutput->shadow_surface = new_shadow_buffer;
389
390         wl_list_for_each(rdpPeer, &rdpOutput->peers, link) {
391                 settings = rdpPeer->peer->settings;
392                 if(!settings->DesktopResize) {
393                         /* too bad this peer does not support desktop resize */
394                         rdpPeer->peer->Close(rdpPeer->peer);
395                 } else {
396                         settings->DesktopWidth = target_mode->width;
397                         settings->DesktopHeight = target_mode->height;
398                         rdpPeer->peer->update->DesktopResize(rdpPeer->peer->context);
399                 }
400         }
401         return 0;
402 }
403
404 static int
405 parse_extra_modes(const char *modes_str, struct rdp_output *output) {
406         const char *startAt = modes_str;
407         const char *nextPos;
408         int w, h;
409         struct weston_mode *mode;
410
411         while(startAt && *startAt) {
412                 nextPos = strchr(startAt, 'x');
413                 if(!nextPos)
414                         return -1;
415
416                 w = strtoul(startAt, NULL, 0);
417                 startAt = nextPos + 1;
418                 if(!*startAt)
419                         return -1;
420
421                 h = strtoul(startAt, NULL, 0);
422
423                 if(!w || (w > 3000) || !h || (h > 3000))
424                         return -1;
425                 mode = malloc(sizeof *mode);
426                 if(!mode)
427                         return -1;
428
429                 mode->width = w;
430                 mode->height = h;
431                 mode->refresh = 5;
432                 mode->flags = 0;
433                 wl_list_insert(&output->base.mode_list, &mode->link);
434
435                 startAt = strchr(startAt, ',');
436                 if(startAt && *startAt == ',')
437                         startAt++;
438         }
439         return 0;
440 }
441 static int
442 rdp_compositor_create_output(struct rdp_compositor *c, int width, int height,
443                 const char *extraModes)
444 {
445         struct rdp_output *output;
446         struct wl_event_loop *loop;
447         struct weston_mode *currentMode, *next;
448
449         output = malloc(sizeof *output);
450         if (output == NULL)
451                 return -1;
452         memset(output, 0, sizeof *output);
453
454         wl_list_init(&output->peers);
455         wl_list_init(&output->base.mode_list);
456
457         currentMode = malloc(sizeof *currentMode);
458         if(!currentMode)
459                 goto out_free_output;
460         currentMode->flags = WL_OUTPUT_MODE_CURRENT | WL_OUTPUT_MODE_PREFERRED;
461         currentMode->width = width;
462         currentMode->height = height;
463         currentMode->refresh = 5;
464         wl_list_insert(&output->base.mode_list, &currentMode->link);
465
466         if(parse_extra_modes(extraModes, output) < 0) {
467                 weston_log("invalid extra modes\n");
468                 goto out_free_output_and_modes;
469         }
470
471         output->base.current = currentMode;
472         weston_output_init(&output->base, &c->base, 0, 0, width, height,
473                            WL_OUTPUT_TRANSFORM_NORMAL, 1);
474
475         output->base.make = "weston";
476         output->base.model = "rdp";
477         output->shadow_surface = pixman_image_create_bits(PIXMAN_x8r8g8b8,
478                         width, height,
479                     NULL,
480                     width * 4);
481         if (output->shadow_surface == NULL) {
482                 weston_log("Failed to create surface for frame buffer.\n");
483                 goto out_output;
484         }
485
486         if (pixman_renderer_output_create(&output->base) < 0)
487                 goto out_shadow_surface;
488
489         weston_output_move(&output->base, 0, 0);
490
491         loop = wl_display_get_event_loop(c->base.wl_display);
492         output->finish_frame_timer = wl_event_loop_add_timer(loop, finish_frame_handler, output);
493
494         output->base.origin = output->base.current;
495         output->base.start_repaint_loop = rdp_output_start_repaint_loop;
496         output->base.repaint = rdp_output_repaint;
497         output->base.destroy = rdp_output_destroy;
498         output->base.assign_planes = NULL;
499         output->base.set_backlight = NULL;
500         output->base.set_dpms = NULL;
501         output->base.switch_mode = rdp_switch_mode;
502         c->output = output;
503
504         wl_list_insert(c->base.output_list.prev, &output->base.link);
505         return 0;
506
507 out_shadow_surface:
508         pixman_image_unref(output->shadow_surface);
509 out_output:
510         weston_output_destroy(&output->base);
511 out_free_output_and_modes:
512         wl_list_for_each_safe(currentMode, next, &output->base.mode_list, link)
513                 free(currentMode);
514 out_free_output:
515         free(output);
516         return -1;
517 }
518
519 static void
520 rdp_restore(struct weston_compositor *ec)
521 {
522 }
523
524 static void
525 rdp_destroy(struct weston_compositor *ec)
526 {
527         ec->renderer->destroy(ec);
528         weston_compositor_shutdown(ec);
529
530         free(ec);
531 }
532
533 static
534 int rdp_listener_activity(int fd, uint32_t mask, void *data) {
535         freerdp_listener* instance = (freerdp_listener *)data;
536
537         if (!(mask & WL_EVENT_READABLE))
538                 return 0;
539         if (!instance->CheckFileDescriptor(instance))
540         {
541                 weston_log("failed to check FreeRDP file descriptor\n");
542                 return -1;
543         }
544         return 0;
545 }
546
547 static
548 int rdp_implant_listener(struct rdp_compositor *c, freerdp_listener* instance) {
549         int i, fd;
550         int rcount = 0;
551         void* rfds[MAX_FREERDP_FDS];
552         struct wl_event_loop *loop;
553
554         if (!instance->GetFileDescriptor(instance, rfds, &rcount)) {
555                 weston_log("Failed to get FreeRDP file descriptor\n");
556                 return -1;
557         }
558
559         loop = wl_display_get_event_loop(c->base.wl_display);
560         for (i = 0; i < rcount; i++) {
561                 fd = (int)(long)(rfds[i]);
562                 c->listener_events[i] = wl_event_loop_add_fd(loop, fd, WL_EVENT_READABLE,
563                                 rdp_listener_activity, instance);
564         }
565
566         for( ; i < MAX_FREERDP_FDS; i++)
567                 c->listener_events[i] = 0;
568         return 0;
569 }
570
571
572 static void
573 rdp_peer_context_new(freerdp_peer* client, RdpPeerContext* context)
574 {
575         context->item.peer = client;
576         context->item.flags = 0;
577
578         context->rfx_context = rfx_context_new();
579         context->rfx_context->mode = RLGR3;
580         context->rfx_context->width = client->settings->DesktopWidth;
581         context->rfx_context->height = client->settings->DesktopHeight;
582         rfx_context_set_pixel_format(context->rfx_context, RDP_PIXEL_FORMAT_B8G8R8A8);
583
584         context->nsc_context = nsc_context_new();
585         nsc_context_set_pixel_format(context->nsc_context, RDP_PIXEL_FORMAT_B8G8R8A8);
586
587         context->encode_stream = Stream_New(NULL, 65536);
588 }
589
590 static void
591 rdp_peer_context_free(freerdp_peer* client, RdpPeerContext* context)
592 {
593         int i;
594         if(!context)
595                 return;
596
597         wl_list_remove(&context->item.link);
598         for(i = 0; i < MAX_FREERDP_FDS; i++) {
599                 if (context->events[i])
600                         wl_event_source_remove(context->events[i]);
601         }
602
603         if(context->item.flags & RDP_PEER_ACTIVATED)
604                 weston_seat_release(&context->item.seat);
605         Stream_Free(context->encode_stream, TRUE);
606         nsc_context_free(context->nsc_context);
607         rfx_context_free(context->rfx_context);
608         free(context->rfx_rects);
609 }
610
611
612 static int
613 rdp_client_activity(int fd, uint32_t mask, void *data) {
614         freerdp_peer* client = (freerdp_peer *)data;
615
616         if (!client->CheckFileDescriptor(client)) {
617                 weston_log("unable to checkDescriptor for %p\n", client);
618                 goto out_clean;
619         }
620         return 0;
621
622 out_clean:
623         freerdp_peer_context_free(client);
624         freerdp_peer_free(client);
625         return 0;
626 }
627
628 static BOOL
629 xf_peer_capabilities(freerdp_peer* client)
630 {
631         return TRUE;
632 }
633
634
635 struct rdp_to_xkb_keyboard_layout {
636         UINT32 rdpLayoutCode;
637         char *xkbLayout;
638 };
639
640 /* picked from http://technet.microsoft.com/en-us/library/cc766503(WS.10).aspx */
641 static struct rdp_to_xkb_keyboard_layout rdp_keyboards[] = {
642         {0x00000406, "dk"},
643         {0x00000407, "de"},
644         {0x00000409, "us"},
645         {0x0000040c, "fr"},
646         {0x00000410, "it"},
647         {0x00000813, "be"},
648         {0x00000000, 0},
649 };
650
651 /* taken from 2.2.7.1.6 Input Capability Set (TS_INPUT_CAPABILITYSET) */
652 static char *rdp_keyboard_types[] = {
653         "",     /* 0: unused */
654         "", /* 1: IBM PC/XT or compatible (83-key) keyboard */
655         "", /* 2: Olivetti "ICO" (102-key) keyboard */
656         "", /* 3: IBM PC/AT (84-key) or similar keyboard */
657         "pc102",/* 4: IBM enhanced (101- or 102-key) keyboard */
658         "", /* 5: Nokia 1050 and similar keyboards */
659         "",     /* 6: Nokia 9140 and similar keyboards */
660         ""      /* 7: Japanese keyboard */
661 };
662
663 static BOOL
664 xf_peer_post_connect(freerdp_peer* client)
665 {
666         RdpPeerContext *peerCtx;
667         struct rdp_compositor *c;
668         struct rdp_output *output;
669         rdpSettings *settings;
670         rdpPointerUpdate *pointer;
671         struct xkb_context *xkbContext;
672         struct xkb_rule_names xkbRuleNames;
673         struct xkb_keymap *keymap;
674         int i;
675         pixman_box32_t box;
676         pixman_region32_t damage;
677
678
679         peerCtx = (RdpPeerContext *)client->context;
680         c = peerCtx->rdpCompositor;
681         output = c->output;
682         settings = client->settings;
683
684         if(!settings->SurfaceCommandsEnabled) {
685                 weston_log("client doesn't support required SurfaceCommands\n");
686                 return FALSE;
687         }
688
689         if(output->base.width != (int)settings->DesktopWidth ||
690                         output->base.height != (int)settings->DesktopHeight)
691         {
692                 if(!settings->DesktopResize) {
693                         weston_log("client don't support desktopResize()\n");
694                         return FALSE;
695                 }
696
697                 /* force the client size */
698                 settings->DesktopWidth = output->base.width;
699                 settings->DesktopHeight = output->base.height;
700                 client->update->DesktopResize(client->context);
701         }
702
703         weston_log("kbd_layout:%x kbd_type:%x kbd_subType:%x kbd_functionKeys:%x\n",
704                         settings->KeyboardLayout, settings->KeyboardType, settings->KeyboardSubType,
705                         settings->KeyboardFunctionKey);
706
707         memset(&xkbRuleNames, 0, sizeof(xkbRuleNames));
708         if(settings->KeyboardType <= 7)
709                 xkbRuleNames.model = rdp_keyboard_types[settings->KeyboardType];
710         for(i = 0; rdp_keyboards[i].xkbLayout; i++) {
711                 if(rdp_keyboards[i].rdpLayoutCode == settings->KeyboardLayout) {
712                         xkbRuleNames.layout = rdp_keyboards[i].xkbLayout;
713                         break;
714                 }
715         }
716
717         keymap = NULL;
718         if(xkbRuleNames.layout) {
719                 xkbContext = xkb_context_new(0);
720                 if(!xkbContext) {
721                         weston_log("unable to create a xkb_context\n");
722                         return FALSE;
723                 }
724
725                 keymap = xkb_keymap_new_from_names(xkbContext, &xkbRuleNames, 0);
726         }
727         weston_seat_init_keyboard(&peerCtx->item.seat, keymap);
728         weston_seat_init_pointer(&peerCtx->item.seat);
729
730         peerCtx->item.flags |= RDP_PEER_ACTIVATED;
731
732         /* disable pointer on the client side */
733         pointer = client->update->pointer;
734         pointer->pointer_system.type = SYSPTR_NULL;
735         pointer->PointerSystem(client->context, &pointer->pointer_system);
736
737         /* sends a full refresh */
738         box.x1 = 0;
739         box.y1 = 0;
740         box.x2 = output->base.width;
741         box.y2 = output->base.height;
742         pixman_region32_init_with_extents(&damage, &box);
743
744         rdp_peer_refresh_region(&damage, client);
745
746         pixman_region32_fini(&damage);
747
748         return TRUE;
749 }
750
751 static BOOL
752 xf_peer_activate(freerdp_peer *client)
753 {
754         RdpPeerContext *context = (RdpPeerContext *)client->context;
755         rfx_context_reset(context->rfx_context);
756         return TRUE;
757 }
758
759 static void
760 xf_mouseEvent(rdpInput *input, UINT16 flags, UINT16 x, UINT16 y) {
761         wl_fixed_t wl_x, wl_y;
762         RdpPeerContext *peerContext = (RdpPeerContext *)input->context;
763         struct rdp_output *output;
764         uint32_t button = 0;
765
766         if (flags & PTR_FLAGS_MOVE) {
767                 output = peerContext->rdpCompositor->output;
768                 if(x < output->base.width && y < output->base.height) {
769                         wl_x = wl_fixed_from_int((int)x);
770                         wl_y = wl_fixed_from_int((int)y);
771                         notify_motion_absolute(&peerContext->item.seat, weston_compositor_get_time(),
772                                         wl_x, wl_y);
773                 }
774         }
775
776         if (flags & PTR_FLAGS_BUTTON1)
777                 button = BTN_LEFT;
778         else if (flags & PTR_FLAGS_BUTTON2)
779                 button = BTN_RIGHT;
780         else if (flags & PTR_FLAGS_BUTTON3)
781                 button = BTN_MIDDLE;
782
783         if(button) {
784                 notify_button(&peerContext->item.seat, weston_compositor_get_time(), button,
785                         (flags & PTR_FLAGS_DOWN) ? WL_POINTER_BUTTON_STATE_PRESSED : WL_POINTER_BUTTON_STATE_RELEASED
786                 );
787         }
788 }
789
790 static void
791 xf_extendedMouseEvent(rdpInput *input, UINT16 flags, UINT16 x, UINT16 y) {
792         wl_fixed_t wl_x, wl_y;
793         RdpPeerContext *peerContext = (RdpPeerContext *)input->context;
794         struct rdp_output *output;
795
796         output = peerContext->rdpCompositor->output;
797         if(x < output->base.width && y < output->base.height) {
798                 wl_x = wl_fixed_from_int((int)x);
799                 wl_y = wl_fixed_from_int((int)y);
800                 notify_motion_absolute(&peerContext->item.seat, weston_compositor_get_time(),
801                                 wl_x, wl_y);
802         }
803 }
804
805
806 static void
807 xf_input_synchronize_event(rdpInput *input, UINT32 flags)
808 {
809         freerdp_peer *client = input->context->peer;
810         RdpPeerContext *peerCtx = (RdpPeerContext *)input->context;
811         struct rdp_output *output = peerCtx->rdpCompositor->output;
812         pixman_box32_t box;
813         pixman_region32_t damage;
814
815         /* sends a full refresh */
816         box.x1 = 0;
817         box.y1 = 0;
818         box.x2 = output->base.width;
819         box.y2 = output->base.height;
820         pixman_region32_init_with_extents(&damage, &box);
821
822         rdp_peer_refresh_region(&damage, client);
823
824         pixman_region32_fini(&damage);
825 }
826
827 extern DWORD KEYCODE_TO_VKCODE_EVDEV[];
828 static uint32_t vk_to_keycode[256];
829 static void
830 init_vk_translator(void)
831 {
832         int i;
833
834         memset(vk_to_keycode, 0, sizeof(vk_to_keycode));
835         for(i = 0; i < 256; i++)
836                 vk_to_keycode[KEYCODE_TO_VKCODE_EVDEV[i] & 0xff] = i-8;
837 }
838
839 static void
840 xf_input_keyboard_event(rdpInput *input, UINT16 flags, UINT16 code)
841 {
842         uint32_t scan_code, vk_code, full_code;
843         enum wl_keyboard_key_state keyState;
844         RdpPeerContext *peerContext = (RdpPeerContext *)input->context;
845         int notify = 0;
846
847         if (flags & KBD_FLAGS_DOWN) {
848                 keyState = WL_KEYBOARD_KEY_STATE_PRESSED;
849                 notify = 1;
850         } else if (flags & KBD_FLAGS_RELEASE) {
851                 keyState = WL_KEYBOARD_KEY_STATE_RELEASED;
852                 notify = 1;
853         }
854
855         if(notify) {
856                 full_code = code;
857                 if(flags & KBD_FLAGS_EXTENDED)
858                         full_code |= KBD_FLAGS_EXTENDED;
859
860                 vk_code = GetVirtualKeyCodeFromVirtualScanCode(full_code, 4);
861                 if(vk_code > 0xff) {
862                         weston_log("invalid vk_code %x", vk_code);
863                         return;
864                 }
865                 scan_code = vk_to_keycode[vk_code];
866
867
868                 /*weston_log("code=%x ext=%d vk_code=%x scan_code=%x\n", code, (flags & KBD_FLAGS_EXTENDED) ? 1 : 0,
869                                 vk_code, scan_code);*/
870                 notify_key(&peerContext->item.seat, weston_compositor_get_time(),
871                                         scan_code, keyState, STATE_UPDATE_AUTOMATIC);
872         }
873 }
874
875 static void
876 xf_input_unicode_keyboard_event(rdpInput *input, UINT16 flags, UINT16 code)
877 {
878         weston_log("Client sent a unicode keyboard event (flags:0x%X code:0x%X)\n", flags, code);
879 }
880
881
882 static void
883 xf_suppress_output(rdpContext *context, BYTE allow, RECTANGLE_16 *area) {
884         RdpPeerContext *peerContext = (RdpPeerContext *)context;
885         if(allow)
886                 peerContext->item.flags |= RDP_PEER_OUTPUT_ENABLED;
887         else
888                 peerContext->item.flags &= (~RDP_PEER_OUTPUT_ENABLED);
889 }
890
891 static int
892 rdp_peer_init(freerdp_peer *client, struct rdp_compositor *c)
893 {
894         int rcount = 0;
895         void *rfds[MAX_FREERDP_FDS];
896         int i, fd;
897         struct wl_event_loop *loop;
898         rdpSettings     *settings;
899         rdpInput *input;
900         RdpPeerContext *peerCtx;
901
902         client->context_size = sizeof(RdpPeerContext);
903         client->ContextNew = (psPeerContextNew)rdp_peer_context_new;
904         client->ContextFree = (psPeerContextFree)rdp_peer_context_free;
905         freerdp_peer_context_new(client);
906
907         peerCtx = (RdpPeerContext *) client->context;
908         peerCtx->rdpCompositor = c;
909
910         settings = client->settings;
911         settings->RdpKeyFile = c->rdp_key;
912         if(c->tls_enabled) {
913                 settings->CertificateFile = c->server_cert;
914                 settings->PrivateKeyFile = c->server_key;
915         } else {
916                 settings->TlsSecurity = FALSE;
917         }
918
919         settings->NlaSecurity = FALSE;
920
921         client->Capabilities = xf_peer_capabilities;
922         client->PostConnect = xf_peer_post_connect;
923         client->Activate = xf_peer_activate;
924
925         client->update->SuppressOutput = xf_suppress_output;
926
927         input = client->input;
928         input->SynchronizeEvent = xf_input_synchronize_event;
929         input->MouseEvent = xf_mouseEvent;
930         input->ExtendedMouseEvent = xf_extendedMouseEvent;
931         input->KeyboardEvent = xf_input_keyboard_event;
932         input->UnicodeKeyboardEvent = xf_input_unicode_keyboard_event;
933         weston_seat_init(&peerCtx->item.seat, &c->base);
934
935         client->Initialize(client);
936
937         if (!client->GetFileDescriptor(client, rfds, &rcount)) {
938                 weston_log("unable to retrieve client fds\n");
939                 return -1;
940         }
941
942         loop = wl_display_get_event_loop(c->base.wl_display);
943         for(i = 0; i < rcount; i++) {
944                 fd = (int)(long)(rfds[i]);
945
946                 peerCtx->events[i] = wl_event_loop_add_fd(loop, fd, WL_EVENT_READABLE,
947                                 rdp_client_activity, client);
948         }
949         for ( ; i < MAX_FREERDP_FDS; i++)
950                 peerCtx->events[i] = 0;
951
952         wl_list_insert(&c->output->peers, &peerCtx->item.link);
953         return 0;
954 }
955
956
957 static void
958 rdp_incoming_peer(freerdp_listener *instance, freerdp_peer *client)
959 {
960         struct rdp_compositor *c = (struct rdp_compositor *)instance->param4;
961         if (rdp_peer_init(client, c) < 0)
962                 return;
963 }
964
965 static struct weston_compositor *
966 rdp_compositor_create(struct wl_display *display,
967                 struct rdp_compositor_config *config,
968                 int *argc, char *argv[], struct weston_config *config)
969 {
970         struct rdp_compositor *c;
971         char *fd_str;
972         int fd;
973
974         c = malloc(sizeof *c);
975         if (c == NULL)
976                 return NULL;
977
978         memset(c, 0, sizeof *c);
979
980         if (weston_compositor_init(&c->base, display, argc, argv, config) < 0)
981                 goto err_free;
982
983         c->base.destroy = rdp_destroy;
984         c->base.restore = rdp_restore;
985         c->rdp_key = config->rdp_key ? strdup(config->rdp_key) : NULL;
986
987         /* activate TLS only if certificate/key are available */
988         if(config->server_cert && config->server_key) {
989                 weston_log("TLS support activated\n");
990                 c->server_cert = strdup(config->server_cert);
991                 c->server_key = strdup(config->server_key);
992                 if(!c->server_cert || !c->server_key)
993                         goto err_free_strings;
994                 c->tls_enabled = 1;
995         }
996
997         if (pixman_renderer_init(&c->base) < 0)
998                 goto err_compositor;
999
1000         if (rdp_compositor_create_output(c, config->width, config->height, config->extra_modes) < 0)
1001                 goto err_compositor;
1002
1003         if(!config->env_socket) {
1004                 c->listener = freerdp_listener_new();
1005                 c->listener->PeerAccepted = rdp_incoming_peer;
1006                 c->listener->param4 = c;
1007                 if(!c->listener->Open(c->listener, config->bind_address, config->port)) {
1008                         weston_log("unable to bind rdp socket\n");
1009                         goto err_listener;
1010                 }
1011
1012                 if (rdp_implant_listener(c, c->listener) < 0)
1013                         goto err_compositor;
1014         } else {
1015                 /* get the socket from RDP_FD var */
1016                 fd_str = getenv("RDP_FD");
1017                 if(!fd_str) {
1018                         weston_log("RDP_FD env variable not set");
1019                         goto err_output;
1020                 }
1021
1022                 fd = strtoul(fd_str, NULL, 10);
1023                 if(rdp_peer_init(freerdp_peer_new(fd), c))
1024                         goto err_output;
1025         }
1026
1027         return &c->base;
1028
1029 err_listener:
1030         freerdp_listener_free(c->listener);
1031 err_output:
1032         weston_output_destroy(&c->output->base);
1033 err_compositor:
1034         weston_compositor_shutdown(&c->base);
1035 err_free_strings:
1036         if(c->rdp_key)
1037                 free(c->rdp_key);
1038         if(c->server_cert)
1039                 free(c->server_cert);
1040         if(c->server_key)
1041                 free(c->server_key);
1042 err_free:
1043         free(c);
1044         return NULL;
1045 }
1046
1047 WL_EXPORT struct weston_compositor *
1048 backend_init(struct wl_display *display, int *argc, char *argv[],
1049              struct weston_config *config)
1050 {
1051         struct rdp_compositor_config config;
1052         rdp_compositor_config_init(&config);
1053         int major, minor, revision;
1054
1055         freerdp_get_version(&major, &minor, &revision);
1056         weston_log("using FreeRDP version %d.%d.%d\n", major, minor, revision);
1057         init_vk_translator();
1058
1059         const struct weston_option rdp_options[] = {
1060                 { WESTON_OPTION_BOOLEAN, "env-socket", 0, &config.env_socket },
1061                 { WESTON_OPTION_INTEGER, "width", 0, &config.width },
1062                 { WESTON_OPTION_INTEGER, "height", 0, &config.height },
1063                 { WESTON_OPTION_STRING,  "extra-modes", 0, &config.extra_modes },
1064                 { WESTON_OPTION_STRING,  "address", 0, &config.bind_address },
1065                 { WESTON_OPTION_INTEGER, "port", 0, &config.port },
1066                 { WESTON_OPTION_STRING,  "rdp4-key", 0, &config.rdp_key },
1067                 { WESTON_OPTION_STRING,  "rdp-tls-cert", 0, &config.server_cert },
1068                 { WESTON_OPTION_STRING,  "rdp-tls-key", 0, &config.server_key }
1069         };
1070
1071         parse_options(rdp_options, ARRAY_LENGTH(rdp_options), argc, argv);
1072         return rdp_compositor_create(display, &config, argc, argv, config);
1073 }