Unix domain socket support for VNC, by Anthony Liguori.
[qemu] / vnc.c
1 /*
2  * QEMU VNC display driver
3  * 
4  * Copyright (C) 2006 Anthony Liguori <anthony@codemonkey.ws>
5  * Copyright (C) 2006 Fabrice Bellard
6  * 
7  * Permission is hereby granted, free of charge, to any person obtaining a copy
8  * of this software and associated documentation files (the "Software"), to deal
9  * in the Software without restriction, including without limitation the rights
10  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11  * copies of the Software, and to permit persons to whom the Software is
12  * furnished to do so, subject to the following conditions:
13  *
14  * The above copyright notice and this permission notice shall be included in
15  * all copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23  * THE SOFTWARE.
24  */
25
26 #include "vl.h"
27 #include "qemu_socket.h"
28
29 #define VNC_REFRESH_INTERVAL (1000 / 30)
30
31 #include "vnc_keysym.h"
32 #include "keymaps.c"
33
34 typedef struct Buffer
35 {
36     size_t capacity;
37     size_t offset;
38     char *buffer;
39 } Buffer;
40
41 typedef struct VncState VncState;
42
43 typedef int VncReadEvent(VncState *vs, char *data, size_t len);
44
45 typedef void VncWritePixels(VncState *vs, void *data, int size);
46
47 typedef void VncSendHextileTile(VncState *vs,
48                                 int x, int y, int w, int h,
49                                 uint32_t *last_bg, 
50                                 uint32_t *last_fg,
51                                 int *has_bg, int *has_fg);
52
53 #define VNC_MAX_WIDTH 2048
54 #define VNC_MAX_HEIGHT 2048
55 #define VNC_DIRTY_WORDS (VNC_MAX_WIDTH / (16 * 32))
56
57 struct VncState
58 {
59     QEMUTimer *timer;
60     int lsock;
61     int csock;
62     DisplayState *ds;
63     int need_update;
64     int width;
65     int height;
66     uint32_t dirty_row[VNC_MAX_HEIGHT][VNC_DIRTY_WORDS];
67     char *old_data;
68     int depth; /* internal VNC frame buffer byte per pixel */
69     int has_resize;
70     int has_hextile;
71     Buffer output;
72     Buffer input;
73     kbd_layout_t *kbd_layout;
74     /* current output mode information */
75     VncWritePixels *write_pixels;
76     VncSendHextileTile *send_hextile_tile;
77     int pix_bpp, pix_big_endian;
78     int red_shift, red_max, red_shift1;
79     int green_shift, green_max, green_shift1;
80     int blue_shift, blue_max, blue_shift1;
81
82     VncReadEvent *read_handler;
83     size_t read_handler_expect;
84     /* input */
85     uint8_t modifiers_state[256];
86 };
87
88 /* TODO
89    1) Get the queue working for IO.
90    2) there is some weirdness when using the -S option (the screen is grey
91       and not totally invalidated
92    3) resolutions > 1024
93 */
94
95 static void vnc_write(VncState *vs, const void *data, size_t len);
96 static void vnc_write_u32(VncState *vs, uint32_t value);
97 static void vnc_write_s32(VncState *vs, int32_t value);
98 static void vnc_write_u16(VncState *vs, uint16_t value);
99 static void vnc_write_u8(VncState *vs, uint8_t value);
100 static void vnc_flush(VncState *vs);
101 static void vnc_update_client(void *opaque);
102 static void vnc_client_read(void *opaque);
103
104 static inline void vnc_set_bit(uint32_t *d, int k)
105 {
106     d[k >> 5] |= 1 << (k & 0x1f);
107 }
108
109 static inline void vnc_clear_bit(uint32_t *d, int k)
110 {
111     d[k >> 5] &= ~(1 << (k & 0x1f));
112 }
113
114 static inline void vnc_set_bits(uint32_t *d, int n, int nb_words)
115 {
116     int j;
117
118     j = 0;
119     while (n >= 32) {
120         d[j++] = -1;
121         n -= 32;
122     }
123     if (n > 0) 
124         d[j++] = (1 << n) - 1;
125     while (j < nb_words)
126         d[j++] = 0;
127 }
128
129 static inline int vnc_get_bit(const uint32_t *d, int k)
130 {
131     return (d[k >> 5] >> (k & 0x1f)) & 1;
132 }
133
134 static inline int vnc_and_bits(const uint32_t *d1, const uint32_t *d2, 
135                                int nb_words)
136 {
137     int i;
138     for(i = 0; i < nb_words; i++) {
139         if ((d1[i] & d2[i]) != 0)
140             return 1;
141     }
142     return 0;
143 }
144
145 static void vnc_dpy_update(DisplayState *ds, int x, int y, int w, int h)
146 {
147     VncState *vs = ds->opaque;
148     int i;
149
150     h += y;
151
152     for (; y < h; y++)
153         for (i = 0; i < w; i += 16)
154             vnc_set_bit(vs->dirty_row[y], (x + i) / 16);
155 }
156
157 static void vnc_framebuffer_update(VncState *vs, int x, int y, int w, int h,
158                                    int32_t encoding)
159 {
160     vnc_write_u16(vs, x);
161     vnc_write_u16(vs, y);
162     vnc_write_u16(vs, w);
163     vnc_write_u16(vs, h);
164
165     vnc_write_s32(vs, encoding);
166 }
167
168 static void vnc_dpy_resize(DisplayState *ds, int w, int h)
169 {
170     int size_changed;
171     VncState *vs = ds->opaque;
172
173     ds->data = realloc(ds->data, w * h * vs->depth);
174     vs->old_data = realloc(vs->old_data, w * h * vs->depth);
175
176     if (ds->data == NULL || vs->old_data == NULL) {
177         fprintf(stderr, "vnc: memory allocation failed\n");
178         exit(1);
179     }
180
181     ds->depth = vs->depth * 8;
182     size_changed = ds->width != w || ds->height != h;
183     ds->width = w;
184     ds->height = h;
185     ds->linesize = w * vs->depth;
186     if (vs->csock != -1 && vs->has_resize && size_changed) {
187         vnc_write_u8(vs, 0);  /* msg id */
188         vnc_write_u8(vs, 0);
189         vnc_write_u16(vs, 1); /* number of rects */
190         vnc_framebuffer_update(vs, 0, 0, ds->width, ds->height, -223);
191         vnc_flush(vs);
192         vs->width = ds->width;
193         vs->height = ds->height;
194     }
195 }
196
197 /* fastest code */
198 static void vnc_write_pixels_copy(VncState *vs, void *pixels, int size)
199 {
200     vnc_write(vs, pixels, size);
201 }
202
203 /* slowest but generic code. */
204 static void vnc_convert_pixel(VncState *vs, uint8_t *buf, uint32_t v)
205 {
206     unsigned int r, g, b;
207
208     r = (v >> vs->red_shift1) & vs->red_max;
209     g = (v >> vs->green_shift1) & vs->green_max;
210     b = (v >> vs->blue_shift1) & vs->blue_max;
211     v = (r << vs->red_shift) | 
212         (g << vs->green_shift) | 
213         (b << vs->blue_shift);
214     switch(vs->pix_bpp) {
215     case 1:
216         buf[0] = v;
217         break;
218     case 2:
219         if (vs->pix_big_endian) {
220             buf[0] = v >> 8;
221             buf[1] = v;
222         } else {
223             buf[1] = v >> 8;
224             buf[0] = v;
225         }
226         break;
227     default:
228     case 4:
229         if (vs->pix_big_endian) {
230             buf[0] = v >> 24;
231             buf[1] = v >> 16;
232             buf[2] = v >> 8;
233             buf[3] = v;
234         } else {
235             buf[3] = v >> 24;
236             buf[2] = v >> 16;
237             buf[1] = v >> 8;
238             buf[0] = v;
239         }
240         break;
241     }
242 }
243
244 static void vnc_write_pixels_generic(VncState *vs, void *pixels1, int size)
245 {
246     uint32_t *pixels = pixels1;
247     uint8_t buf[4];
248     int n, i;
249
250     n = size >> 2;
251     for(i = 0; i < n; i++) {
252         vnc_convert_pixel(vs, buf, pixels[i]);
253         vnc_write(vs, buf, vs->pix_bpp);
254     }
255 }
256
257 static void send_framebuffer_update_raw(VncState *vs, int x, int y, int w, int h)
258 {
259     int i;
260     char *row;
261
262     vnc_framebuffer_update(vs, x, y, w, h, 0);
263
264     row = vs->ds->data + y * vs->ds->linesize + x * vs->depth;
265     for (i = 0; i < h; i++) {
266         vs->write_pixels(vs, row, w * vs->depth);
267         row += vs->ds->linesize;
268     }
269 }
270
271 static void hextile_enc_cord(uint8_t *ptr, int x, int y, int w, int h)
272 {
273     ptr[0] = ((x & 0x0F) << 4) | (y & 0x0F);
274     ptr[1] = (((w - 1) & 0x0F) << 4) | ((h - 1) & 0x0F);
275 }
276
277 #define BPP 8
278 #include "vnchextile.h"
279 #undef BPP
280
281 #define BPP 16
282 #include "vnchextile.h"
283 #undef BPP
284
285 #define BPP 32
286 #include "vnchextile.h"
287 #undef BPP
288
289 #define GENERIC
290 #define BPP 32
291 #include "vnchextile.h"
292 #undef BPP
293 #undef GENERIC
294
295 static void send_framebuffer_update_hextile(VncState *vs, int x, int y, int w, int h)
296 {
297     int i, j;
298     int has_fg, has_bg;
299     uint32_t last_fg32, last_bg32;
300
301     vnc_framebuffer_update(vs, x, y, w, h, 5);
302
303     has_fg = has_bg = 0;
304     for (j = y; j < (y + h); j += 16) {
305         for (i = x; i < (x + w); i += 16) {
306             vs->send_hextile_tile(vs, i, j, 
307                                   MIN(16, x + w - i), MIN(16, y + h - j),
308                                   &last_bg32, &last_fg32, &has_bg, &has_fg);
309         }
310     }
311 }
312
313 static void send_framebuffer_update(VncState *vs, int x, int y, int w, int h)
314 {
315         if (vs->has_hextile)
316             send_framebuffer_update_hextile(vs, x, y, w, h);
317         else
318             send_framebuffer_update_raw(vs, x, y, w, h);
319 }
320
321 static void vnc_copy(DisplayState *ds, int src_x, int src_y, int dst_x, int dst_y, int w, int h)
322 {
323     int src, dst;
324     char *src_row;
325     char *dst_row;
326     char *old_row;
327     int y = 0;
328     int pitch = ds->linesize;
329     VncState *vs = ds->opaque;
330
331     vnc_update_client(vs);
332
333     if (dst_y > src_y) {
334         y = h - 1;
335         pitch = -pitch;
336     }
337
338     src = (ds->linesize * (src_y + y) + vs->depth * src_x);
339     dst = (ds->linesize * (dst_y + y) + vs->depth * dst_x);
340
341     src_row = ds->data + src;
342     dst_row = ds->data + dst;
343     old_row = vs->old_data + dst;
344
345     for (y = 0; y < h; y++) {
346         memmove(old_row, src_row, w * vs->depth);
347         memmove(dst_row, src_row, w * vs->depth);
348         src_row += pitch;
349         dst_row += pitch;
350         old_row += pitch;
351     }
352
353     vnc_write_u8(vs, 0);  /* msg id */
354     vnc_write_u8(vs, 0);
355     vnc_write_u16(vs, 1); /* number of rects */
356     vnc_framebuffer_update(vs, dst_x, dst_y, w, h, 1);
357     vnc_write_u16(vs, src_x);
358     vnc_write_u16(vs, src_y);
359     vnc_flush(vs);
360 }
361
362 static int find_dirty_height(VncState *vs, int y, int last_x, int x)
363 {
364     int h;
365
366     for (h = 1; h < (vs->height - y); h++) {
367         int tmp_x;
368         if (!vnc_get_bit(vs->dirty_row[y + h], last_x))
369             break;
370         for (tmp_x = last_x; tmp_x < x; tmp_x++)
371             vnc_clear_bit(vs->dirty_row[y + h], tmp_x);
372     }
373
374     return h;
375 }
376
377 static void vnc_update_client(void *opaque)
378 {
379     VncState *vs = opaque;
380
381     if (vs->need_update && vs->csock != -1) {
382         int y;
383         char *row;
384         char *old_row;
385         uint32_t width_mask[VNC_DIRTY_WORDS];
386         int n_rectangles;
387         int saved_offset;
388         int has_dirty = 0;
389
390         vnc_set_bits(width_mask, (vs->width / 16), VNC_DIRTY_WORDS);
391
392         /* Walk through the dirty map and eliminate tiles that
393            really aren't dirty */
394         row = vs->ds->data;
395         old_row = vs->old_data;
396
397         for (y = 0; y < vs->height; y++) {
398             if (vnc_and_bits(vs->dirty_row[y], width_mask, VNC_DIRTY_WORDS)) {
399                 int x;
400                 char *ptr, *old_ptr;
401
402                 ptr = row;
403                 old_ptr = old_row;
404
405                 for (x = 0; x < vs->ds->width; x += 16) {
406                     if (memcmp(old_ptr, ptr, 16 * vs->depth) == 0) {
407                         vnc_clear_bit(vs->dirty_row[y], (x / 16));
408                     } else {
409                         has_dirty = 1;
410                         memcpy(old_ptr, ptr, 16 * vs->depth);
411                     }
412
413                     ptr += 16 * vs->depth;
414                     old_ptr += 16 * vs->depth;
415                 }
416             }
417
418             row += vs->ds->linesize;
419             old_row += vs->ds->linesize;
420         }
421
422         if (!has_dirty) {
423             qemu_mod_timer(vs->timer, qemu_get_clock(rt_clock) + VNC_REFRESH_INTERVAL);
424             return;
425         }
426
427         /* Count rectangles */
428         n_rectangles = 0;
429         vnc_write_u8(vs, 0);  /* msg id */
430         vnc_write_u8(vs, 0);
431         saved_offset = vs->output.offset;
432         vnc_write_u16(vs, 0);
433
434         for (y = 0; y < vs->height; y++) {
435             int x;
436             int last_x = -1;
437             for (x = 0; x < vs->width / 16; x++) {
438                 if (vnc_get_bit(vs->dirty_row[y], x)) {
439                     if (last_x == -1) {
440                         last_x = x;
441                     }
442                     vnc_clear_bit(vs->dirty_row[y], x);
443                 } else {
444                     if (last_x != -1) {
445                         int h = find_dirty_height(vs, y, last_x, x);
446                         send_framebuffer_update(vs, last_x * 16, y, (x - last_x) * 16, h);
447                         n_rectangles++;
448                     }
449                     last_x = -1;
450                 }
451             }
452             if (last_x != -1) {
453                 int h = find_dirty_height(vs, y, last_x, x);
454                 send_framebuffer_update(vs, last_x * 16, y, (x - last_x) * 16, h);
455                 n_rectangles++;
456             }
457         }
458         vs->output.buffer[saved_offset] = (n_rectangles >> 8) & 0xFF;
459         vs->output.buffer[saved_offset + 1] = n_rectangles & 0xFF;
460         vnc_flush(vs);
461
462     }
463     qemu_mod_timer(vs->timer, qemu_get_clock(rt_clock) + VNC_REFRESH_INTERVAL);
464 }
465
466 static void vnc_timer_init(VncState *vs)
467 {
468     if (vs->timer == NULL) {
469         vs->timer = qemu_new_timer(rt_clock, vnc_update_client, vs);
470         qemu_mod_timer(vs->timer, qemu_get_clock(rt_clock));
471     }
472 }
473
474 static void vnc_dpy_refresh(DisplayState *ds)
475 {
476     VncState *vs = ds->opaque;
477     vnc_timer_init(vs);
478     vga_hw_update();
479 }
480
481 static int vnc_listen_poll(void *opaque)
482 {
483     VncState *vs = opaque;
484     if (vs->csock == -1)
485         return 1;
486     return 0;
487 }
488
489 static void buffer_reserve(Buffer *buffer, size_t len)
490 {
491     if ((buffer->capacity - buffer->offset) < len) {
492         buffer->capacity += (len + 1024);
493         buffer->buffer = realloc(buffer->buffer, buffer->capacity);
494         if (buffer->buffer == NULL) {
495             fprintf(stderr, "vnc: out of memory\n");
496             exit(1);
497         }
498     }
499 }
500
501 static int buffer_empty(Buffer *buffer)
502 {
503     return buffer->offset == 0;
504 }
505
506 static char *buffer_end(Buffer *buffer)
507 {
508     return buffer->buffer + buffer->offset;
509 }
510
511 static void buffer_reset(Buffer *buffer)
512 {
513         buffer->offset = 0;
514 }
515
516 static void buffer_append(Buffer *buffer, const void *data, size_t len)
517 {
518     memcpy(buffer->buffer + buffer->offset, data, len);
519     buffer->offset += len;
520 }
521
522 static int vnc_client_io_error(VncState *vs, int ret, int last_errno)
523 {
524     if (ret == 0 || ret == -1) {
525         if (ret == -1 && (last_errno == EINTR || last_errno == EAGAIN))
526             return 0;
527
528         qemu_set_fd_handler2(vs->csock, NULL, NULL, NULL, NULL);
529         closesocket(vs->csock);
530         vs->csock = -1;
531         buffer_reset(&vs->input);
532         buffer_reset(&vs->output);
533         vs->need_update = 0;
534         return 0;
535     }
536     return ret;
537 }
538
539 static void vnc_client_error(VncState *vs)
540 {
541     vnc_client_io_error(vs, -1, EINVAL);
542 }
543
544 static void vnc_client_write(void *opaque)
545 {
546     long ret;
547     VncState *vs = opaque;
548
549     ret = send(vs->csock, vs->output.buffer, vs->output.offset, 0);
550     ret = vnc_client_io_error(vs, ret, socket_error());
551     if (!ret)
552         return;
553
554     memmove(vs->output.buffer, vs->output.buffer + ret, (vs->output.offset - ret));
555     vs->output.offset -= ret;
556
557     if (vs->output.offset == 0) {
558         qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);
559     }
560 }
561
562 static void vnc_read_when(VncState *vs, VncReadEvent *func, size_t expecting)
563 {
564     vs->read_handler = func;
565     vs->read_handler_expect = expecting;
566 }
567
568 static void vnc_client_read(void *opaque)
569 {
570     VncState *vs = opaque;
571     long ret;
572
573     buffer_reserve(&vs->input, 4096);
574
575     ret = recv(vs->csock, buffer_end(&vs->input), 4096, 0);
576     ret = vnc_client_io_error(vs, ret, socket_error());
577     if (!ret)
578         return;
579
580     vs->input.offset += ret;
581
582     while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {
583         size_t len = vs->read_handler_expect;
584         int ret;
585
586         ret = vs->read_handler(vs, vs->input.buffer, len);
587         if (vs->csock == -1)
588             return;
589
590         if (!ret) {
591             memmove(vs->input.buffer, vs->input.buffer + len, (vs->input.offset - len));
592             vs->input.offset -= len;
593         } else {
594             vs->read_handler_expect = ret;
595         }
596     }
597 }
598
599 static void vnc_write(VncState *vs, const void *data, size_t len)
600 {
601     buffer_reserve(&vs->output, len);
602
603     if (buffer_empty(&vs->output)) {
604         qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, vnc_client_write, vs);
605     }
606
607     buffer_append(&vs->output, data, len);
608 }
609
610 static void vnc_write_s32(VncState *vs, int32_t value)
611 {
612     vnc_write_u32(vs, *(uint32_t *)&value);
613 }
614
615 static void vnc_write_u32(VncState *vs, uint32_t value)
616 {
617     uint8_t buf[4];
618
619     buf[0] = (value >> 24) & 0xFF;
620     buf[1] = (value >> 16) & 0xFF;
621     buf[2] = (value >>  8) & 0xFF;
622     buf[3] = value & 0xFF;
623
624     vnc_write(vs, buf, 4);
625 }
626
627 static void vnc_write_u16(VncState *vs, uint16_t value)
628 {
629     uint8_t buf[2];
630
631     buf[0] = (value >> 8) & 0xFF;
632     buf[1] = value & 0xFF;
633
634     vnc_write(vs, buf, 2);
635 }
636
637 static void vnc_write_u8(VncState *vs, uint8_t value)
638 {
639     vnc_write(vs, (char *)&value, 1);
640 }
641
642 static void vnc_flush(VncState *vs)
643 {
644     if (vs->output.offset)
645         vnc_client_write(vs);
646 }
647
648 static uint8_t read_u8(uint8_t *data, size_t offset)
649 {
650     return data[offset];
651 }
652
653 static uint16_t read_u16(uint8_t *data, size_t offset)
654 {
655     return ((data[offset] & 0xFF) << 8) | (data[offset + 1] & 0xFF);
656 }
657
658 static int32_t read_s32(uint8_t *data, size_t offset)
659 {
660     return (int32_t)((data[offset] << 24) | (data[offset + 1] << 16) |
661                      (data[offset + 2] << 8) | data[offset + 3]);
662 }
663
664 static uint32_t read_u32(uint8_t *data, size_t offset)
665 {
666     return ((data[offset] << 24) | (data[offset + 1] << 16) |
667             (data[offset + 2] << 8) | data[offset + 3]);
668 }
669
670 static void client_cut_text(VncState *vs, size_t len, char *text)
671 {
672 }
673
674 static void pointer_event(VncState *vs, int button_mask, int x, int y)
675 {
676     int buttons = 0;
677     int dz = 0;
678
679     if (button_mask & 0x01)
680         buttons |= MOUSE_EVENT_LBUTTON;
681     if (button_mask & 0x02)
682         buttons |= MOUSE_EVENT_MBUTTON;
683     if (button_mask & 0x04)
684         buttons |= MOUSE_EVENT_RBUTTON;
685     if (button_mask & 0x08)
686         dz = -1;
687     if (button_mask & 0x10)
688         dz = 1;
689             
690     if (kbd_mouse_is_absolute()) {
691         kbd_mouse_event(x * 0x7FFF / vs->ds->width,
692                         y * 0x7FFF / vs->ds->height,
693                         dz, buttons);
694     } else {
695         static int last_x = -1;
696         static int last_y = -1;
697
698         if (last_x != -1)
699             kbd_mouse_event(x - last_x, y - last_y, dz, buttons);
700
701         last_x = x;
702         last_y = y;
703     }
704 }
705
706 static void reset_keys(VncState *vs)
707 {
708     int i;
709     for(i = 0; i < 256; i++) {
710         if (vs->modifiers_state[i]) {
711             if (i & 0x80)
712                 kbd_put_keycode(0xe0);
713             kbd_put_keycode(i | 0x80);
714             vs->modifiers_state[i] = 0;
715         }
716     }
717 }
718
719 static void do_key_event(VncState *vs, int down, uint32_t sym)
720 {
721     int keycode;
722
723     keycode = keysym2scancode(vs->kbd_layout, sym & 0xFFFF);
724     
725     /* QEMU console switch */
726     switch(keycode) {
727     case 0x2a:                          /* Left Shift */
728     case 0x36:                          /* Right Shift */
729     case 0x1d:                          /* Left CTRL */
730     case 0x9d:                          /* Right CTRL */
731     case 0x38:                          /* Left ALT */
732     case 0xb8:                          /* Right ALT */
733         if (down)
734             vs->modifiers_state[keycode] = 1;
735         else
736             vs->modifiers_state[keycode] = 0;
737         break;
738     case 0x02 ... 0x0a: /* '1' to '9' keys */ 
739         if (down && vs->modifiers_state[0x1d] && vs->modifiers_state[0x38]) {
740             /* Reset the modifiers sent to the current console */
741             reset_keys(vs);
742             console_select(keycode - 0x02);
743             return;
744         }
745         break;
746     }
747
748     if (is_graphic_console()) {
749         if (keycode & 0x80)
750             kbd_put_keycode(0xe0);
751         if (down)
752             kbd_put_keycode(keycode & 0x7f);
753         else
754             kbd_put_keycode(keycode | 0x80);
755     } else {
756         /* QEMU console emulation */
757         if (down) {
758             switch (keycode) {
759             case 0x2a:                          /* Left Shift */
760             case 0x36:                          /* Right Shift */
761             case 0x1d:                          /* Left CTRL */
762             case 0x9d:                          /* Right CTRL */
763             case 0x38:                          /* Left ALT */
764             case 0xb8:                          /* Right ALT */
765                 break;
766             case 0xc8:
767                 kbd_put_keysym(QEMU_KEY_UP);
768                 break;
769             case 0xd0:
770                 kbd_put_keysym(QEMU_KEY_DOWN);
771                 break;
772             case 0xcb:
773                 kbd_put_keysym(QEMU_KEY_LEFT);
774                 break;
775             case 0xcd:
776                 kbd_put_keysym(QEMU_KEY_RIGHT);
777                 break;
778             case 0xd3:
779                 kbd_put_keysym(QEMU_KEY_DELETE);
780                 break;
781             case 0xc7:
782                 kbd_put_keysym(QEMU_KEY_HOME);
783                 break;
784             case 0xcf:
785                 kbd_put_keysym(QEMU_KEY_END);
786                 break;
787             case 0xc9:
788                 kbd_put_keysym(QEMU_KEY_PAGEUP);
789                 break;
790             case 0xd1:
791                 kbd_put_keysym(QEMU_KEY_PAGEDOWN);
792                 break;
793             default:
794                 kbd_put_keysym(sym);
795                 break;
796             }
797         }
798     }
799 }
800
801 static void key_event(VncState *vs, int down, uint32_t sym)
802 {
803     if (sym >= 'A' && sym <= 'Z')
804         sym = sym - 'A' + 'a';
805     do_key_event(vs, down, sym);
806 }
807
808 static void framebuffer_update_request(VncState *vs, int incremental,
809                                        int x_position, int y_position,
810                                        int w, int h)
811 {
812     int i;
813     vs->need_update = 1;
814     if (!incremental) {
815         char *old_row = vs->old_data + y_position * vs->ds->linesize;
816
817         for (i = 0; i < h; i++) {
818             vnc_set_bits(vs->dirty_row[y_position + i], 
819                          (vs->ds->width / 16), VNC_DIRTY_WORDS);
820             memset(old_row, 42, vs->ds->width * vs->depth);
821             old_row += vs->ds->linesize;
822         }
823     }
824 }
825
826 static void set_encodings(VncState *vs, int32_t *encodings, size_t n_encodings)
827 {
828     int i;
829
830     vs->has_hextile = 0;
831     vs->has_resize = 0;
832     vs->ds->dpy_copy = NULL;
833
834     for (i = n_encodings - 1; i >= 0; i--) {
835         switch (encodings[i]) {
836         case 0: /* Raw */
837             vs->has_hextile = 0;
838             break;
839         case 1: /* CopyRect */
840             vs->ds->dpy_copy = vnc_copy;
841             break;
842         case 5: /* Hextile */
843             vs->has_hextile = 1;
844             break;
845         case -223: /* DesktopResize */
846             vs->has_resize = 1;
847             break;
848         default:
849             break;
850         }
851     }
852 }
853
854 static int compute_nbits(unsigned int val)
855 {
856     int n;
857     n = 0;
858     while (val != 0) {
859         n++;
860         val >>= 1;
861     }
862     return n;
863 }
864
865 static void set_pixel_format(VncState *vs,
866                              int bits_per_pixel, int depth,
867                              int big_endian_flag, int true_color_flag,
868                              int red_max, int green_max, int blue_max,
869                              int red_shift, int green_shift, int blue_shift)
870 {
871     int host_big_endian_flag;
872
873 #ifdef WORDS_BIGENDIAN
874     host_big_endian_flag = 1;
875 #else
876     host_big_endian_flag = 0;
877 #endif
878     if (!true_color_flag) {
879     fail:
880         vnc_client_error(vs);
881         return;
882     }
883     if (bits_per_pixel == 32 && 
884         host_big_endian_flag == big_endian_flag &&
885         red_max == 0xff && green_max == 0xff && blue_max == 0xff &&
886         red_shift == 16 && green_shift == 8 && blue_shift == 0) {
887         vs->depth = 4;
888         vs->write_pixels = vnc_write_pixels_copy;
889         vs->send_hextile_tile = send_hextile_tile_32;
890     } else 
891     if (bits_per_pixel == 16 && 
892         host_big_endian_flag == big_endian_flag &&
893         red_max == 31 && green_max == 63 && blue_max == 31 &&
894         red_shift == 11 && green_shift == 5 && blue_shift == 0) {
895         vs->depth = 2;
896         vs->write_pixels = vnc_write_pixels_copy;
897         vs->send_hextile_tile = send_hextile_tile_16;
898     } else 
899     if (bits_per_pixel == 8 && 
900         red_max == 7 && green_max == 7 && blue_max == 3 &&
901         red_shift == 5 && green_shift == 2 && blue_shift == 0) {
902         vs->depth = 1;
903         vs->write_pixels = vnc_write_pixels_copy;
904         vs->send_hextile_tile = send_hextile_tile_8;
905     } else 
906     {
907         /* generic and slower case */
908         if (bits_per_pixel != 8 &&
909             bits_per_pixel != 16 &&
910             bits_per_pixel != 32)
911             goto fail;
912         vs->depth = 4;
913         vs->red_shift = red_shift;
914         vs->red_max = red_max;
915         vs->red_shift1 = 24 - compute_nbits(red_max);
916         vs->green_shift = green_shift;
917         vs->green_max = green_max;
918         vs->green_shift1 = 16 - compute_nbits(green_max);
919         vs->blue_shift = blue_shift;
920         vs->blue_max = blue_max;
921         vs->blue_shift1 = 8 - compute_nbits(blue_max);
922         vs->pix_bpp = bits_per_pixel / 8;
923         vs->pix_big_endian = big_endian_flag;
924         vs->write_pixels = vnc_write_pixels_generic;
925         vs->send_hextile_tile = send_hextile_tile_generic;
926     }
927
928     vnc_dpy_resize(vs->ds, vs->ds->width, vs->ds->height);
929     memset(vs->dirty_row, 0xFF, sizeof(vs->dirty_row));
930     memset(vs->old_data, 42, vs->ds->linesize * vs->ds->height);
931
932     vga_hw_invalidate();
933     vga_hw_update();
934 }
935
936 static int protocol_client_msg(VncState *vs, char *data, size_t len)
937 {
938     int i;
939     uint16_t limit;
940
941     switch (data[0]) {
942     case 0:
943         if (len == 1)
944             return 20;
945
946         set_pixel_format(vs, read_u8(data, 4), read_u8(data, 5),
947                          read_u8(data, 6), read_u8(data, 7),
948                          read_u16(data, 8), read_u16(data, 10),
949                          read_u16(data, 12), read_u8(data, 14),
950                          read_u8(data, 15), read_u8(data, 16));
951         break;
952     case 2:
953         if (len == 1)
954             return 4;
955
956         if (len == 4)
957             return 4 + (read_u16(data, 2) * 4);
958
959         limit = read_u16(data, 2);
960         for (i = 0; i < limit; i++) {
961             int32_t val = read_s32(data, 4 + (i * 4));
962             memcpy(data + 4 + (i * 4), &val, sizeof(val));
963         }
964
965         set_encodings(vs, (int32_t *)(data + 4), limit);
966         break;
967     case 3:
968         if (len == 1)
969             return 10;
970
971         framebuffer_update_request(vs,
972                                    read_u8(data, 1), read_u16(data, 2), read_u16(data, 4),
973                                    read_u16(data, 6), read_u16(data, 8));
974         break;
975     case 4:
976         if (len == 1)
977             return 8;
978
979         key_event(vs, read_u8(data, 1), read_u32(data, 4));
980         break;
981     case 5:
982         if (len == 1)
983             return 6;
984
985         pointer_event(vs, read_u8(data, 1), read_u16(data, 2), read_u16(data, 4));
986         break;
987     case 6:
988         if (len == 1)
989             return 8;
990
991         if (len == 8)
992             return 8 + read_u32(data, 4);
993
994         client_cut_text(vs, read_u32(data, 4), data + 8);
995         break;
996     default:
997         printf("Msg: %d\n", data[0]);
998         vnc_client_error(vs);
999         break;
1000     }
1001         
1002     vnc_read_when(vs, protocol_client_msg, 1);
1003     return 0;
1004 }
1005
1006 static int protocol_client_init(VncState *vs, char *data, size_t len)
1007 {
1008     char pad[3] = { 0, 0, 0 };
1009
1010     vs->width = vs->ds->width;
1011     vs->height = vs->ds->height;
1012     vnc_write_u16(vs, vs->ds->width);
1013     vnc_write_u16(vs, vs->ds->height);
1014
1015     vnc_write_u8(vs, vs->depth * 8); /* bits-per-pixel */
1016     vnc_write_u8(vs, vs->depth * 8); /* depth */
1017 #ifdef WORDS_BIGENDIAN
1018     vnc_write_u8(vs, 1);             /* big-endian-flag */
1019 #else
1020     vnc_write_u8(vs, 0);             /* big-endian-flag */
1021 #endif
1022     vnc_write_u8(vs, 1);             /* true-color-flag */
1023     if (vs->depth == 4) {
1024         vnc_write_u16(vs, 0xFF);     /* red-max */
1025         vnc_write_u16(vs, 0xFF);     /* green-max */
1026         vnc_write_u16(vs, 0xFF);     /* blue-max */
1027         vnc_write_u8(vs, 16);        /* red-shift */
1028         vnc_write_u8(vs, 8);         /* green-shift */
1029         vnc_write_u8(vs, 0);         /* blue-shift */
1030         vs->send_hextile_tile = send_hextile_tile_32;
1031     } else if (vs->depth == 2) {
1032         vnc_write_u16(vs, 31);       /* red-max */
1033         vnc_write_u16(vs, 63);       /* green-max */
1034         vnc_write_u16(vs, 31);       /* blue-max */
1035         vnc_write_u8(vs, 11);        /* red-shift */
1036         vnc_write_u8(vs, 5);         /* green-shift */
1037         vnc_write_u8(vs, 0);         /* blue-shift */
1038         vs->send_hextile_tile = send_hextile_tile_16;
1039     } else if (vs->depth == 1) {
1040         /* XXX: change QEMU pixel 8 bit pixel format to match the VNC one ? */
1041         vnc_write_u16(vs, 7);        /* red-max */
1042         vnc_write_u16(vs, 7);        /* green-max */
1043         vnc_write_u16(vs, 3);        /* blue-max */
1044         vnc_write_u8(vs, 5);         /* red-shift */
1045         vnc_write_u8(vs, 2);         /* green-shift */
1046         vnc_write_u8(vs, 0);         /* blue-shift */
1047         vs->send_hextile_tile = send_hextile_tile_8;
1048     }
1049     vs->write_pixels = vnc_write_pixels_copy;
1050         
1051     vnc_write(vs, pad, 3);           /* padding */
1052
1053     vnc_write_u32(vs, 4);        
1054     vnc_write(vs, "QEMU", 4);
1055     vnc_flush(vs);
1056
1057     vnc_read_when(vs, protocol_client_msg, 1);
1058
1059     return 0;
1060 }
1061
1062 static int protocol_version(VncState *vs, char *version, size_t len)
1063 {
1064     char local[13];
1065     int maj, min;
1066
1067     memcpy(local, version, 12);
1068     local[12] = 0;
1069
1070     if (sscanf(local, "RFB %03d.%03d\n", &maj, &min) != 2) {
1071         vnc_client_error(vs);
1072         return 0;
1073     }
1074
1075     vnc_write_u32(vs, 1); /* None */
1076     vnc_flush(vs);
1077
1078     vnc_read_when(vs, protocol_client_init, 1);
1079
1080     return 0;
1081 }
1082
1083 static void vnc_listen_read(void *opaque)
1084 {
1085     VncState *vs = opaque;
1086     struct sockaddr_in addr;
1087     socklen_t addrlen = sizeof(addr);
1088
1089     vs->csock = accept(vs->lsock, (struct sockaddr *)&addr, &addrlen);
1090     if (vs->csock != -1) {
1091         socket_set_nonblock(vs->csock);
1092         qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, opaque);
1093         vnc_write(vs, "RFB 003.003\n", 12);
1094         vnc_flush(vs);
1095         vnc_read_when(vs, protocol_version, 12);
1096         memset(vs->old_data, 0, vs->ds->linesize * vs->ds->height);
1097         memset(vs->dirty_row, 0xFF, sizeof(vs->dirty_row));
1098         vs->has_resize = 0;
1099         vs->has_hextile = 0;
1100         vs->ds->dpy_copy = NULL;
1101     }
1102 }
1103
1104 extern int parse_host_port(struct sockaddr_in *saddr, const char *str);
1105
1106 void vnc_display_init(DisplayState *ds, const char *arg)
1107 {
1108     struct sockaddr *addr;
1109     struct sockaddr_in iaddr;
1110 #ifndef _WIN32
1111     struct sockaddr_un uaddr;
1112 #endif
1113     int reuse_addr, ret;
1114     socklen_t addrlen;
1115     const char *p;
1116     VncState *vs;
1117
1118     vs = qemu_mallocz(sizeof(VncState));
1119     if (!vs)
1120         exit(1);
1121
1122     ds->opaque = vs;
1123
1124     vs->lsock = -1;
1125     vs->csock = -1;
1126     vs->depth = 4;
1127
1128     vs->ds = ds;
1129
1130     if (!keyboard_layout)
1131         keyboard_layout = "en-us";
1132
1133     vs->kbd_layout = init_keyboard_layout(keyboard_layout);
1134     if (!vs->kbd_layout)
1135         exit(1);
1136
1137     vs->ds->data = NULL;
1138     vs->ds->dpy_update = vnc_dpy_update;
1139     vs->ds->dpy_resize = vnc_dpy_resize;
1140     vs->ds->dpy_refresh = vnc_dpy_refresh;
1141
1142     memset(vs->dirty_row, 0xFF, sizeof(vs->dirty_row));
1143
1144     vnc_dpy_resize(vs->ds, 640, 400);
1145
1146 #ifndef _WIN32
1147     if (strstart(arg, "unix:", &p)) {
1148         addr = (struct sockaddr *)&uaddr;
1149         addrlen = sizeof(uaddr);
1150
1151         vs->lsock = socket(PF_UNIX, SOCK_STREAM, 0);
1152         if (vs->lsock == -1) {
1153             fprintf(stderr, "Could not create socket\n");
1154             exit(1);
1155         }
1156
1157         uaddr.sun_family = AF_UNIX;
1158         memset(uaddr.sun_path, 0, 108);
1159         snprintf(uaddr.sun_path, 108, "%s", p);
1160
1161         unlink(uaddr.sun_path);
1162     } else
1163 #endif
1164     {
1165         addr = (struct sockaddr *)&iaddr;
1166         addrlen = sizeof(iaddr);
1167
1168         vs->lsock = socket(PF_INET, SOCK_STREAM, 0);
1169         if (vs->lsock == -1) {
1170             fprintf(stderr, "Could not create socket\n");
1171             exit(1);
1172         }
1173
1174         if (parse_host_port(&iaddr, arg) < 0) {
1175             fprintf(stderr, "Could not parse VNC address\n");
1176             exit(1);
1177         }
1178             
1179         iaddr.sin_port = htons(ntohs(iaddr.sin_port) + 5900);
1180
1181         reuse_addr = 1;
1182         ret = setsockopt(vs->lsock, SOL_SOCKET, SO_REUSEADDR,
1183                          (const char *)&reuse_addr, sizeof(reuse_addr));
1184         if (ret == -1) {
1185             fprintf(stderr, "setsockopt() failed\n");
1186             exit(1);
1187         }
1188     }
1189
1190     if (bind(vs->lsock, addr, addrlen) == -1) {
1191         fprintf(stderr, "bind() failed\n");
1192         exit(1);
1193     }
1194
1195     if (listen(vs->lsock, 1) == -1) {
1196         fprintf(stderr, "listen() failed\n");
1197         exit(1);
1198     }
1199
1200     ret = qemu_set_fd_handler2(vs->lsock, vnc_listen_poll, vnc_listen_read, NULL, vs);
1201     if (ret == -1) {
1202         exit(1);
1203     }
1204 }