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