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