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