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