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