Merge remote-tracking branch 'remotes/xtensa/tags/20140526-xtensa' into staging
[sdk/emulator/qemu.git] / ui / console.c
1 /*
2  * QEMU graphical console
3  *
4  * Copyright (c) 2004 Fabrice Bellard
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24 #include "qemu-common.h"
25 #include "ui/console.h"
26 #include "hw/qdev-core.h"
27 #include "qemu/timer.h"
28 #include "qmp-commands.h"
29 #include "sysemu/char.h"
30 #include "trace.h"
31
32 #define DEFAULT_BACKSCROLL 512
33 #define MAX_CONSOLES 12
34 #define CONSOLE_CURSOR_PERIOD 500
35
36 typedef struct TextAttributes {
37     uint8_t fgcol:4;
38     uint8_t bgcol:4;
39     uint8_t bold:1;
40     uint8_t uline:1;
41     uint8_t blink:1;
42     uint8_t invers:1;
43     uint8_t unvisible:1;
44 } TextAttributes;
45
46 typedef struct TextCell {
47     uint8_t ch;
48     TextAttributes t_attrib;
49 } TextCell;
50
51 #define MAX_ESC_PARAMS 3
52
53 enum TTYState {
54     TTY_STATE_NORM,
55     TTY_STATE_ESC,
56     TTY_STATE_CSI,
57 };
58
59 typedef struct QEMUFIFO {
60     uint8_t *buf;
61     int buf_size;
62     int count, wptr, rptr;
63 } QEMUFIFO;
64
65 static int qemu_fifo_write(QEMUFIFO *f, const uint8_t *buf, int len1)
66 {
67     int l, len;
68
69     l = f->buf_size - f->count;
70     if (len1 > l)
71         len1 = l;
72     len = len1;
73     while (len > 0) {
74         l = f->buf_size - f->wptr;
75         if (l > len)
76             l = len;
77         memcpy(f->buf + f->wptr, buf, l);
78         f->wptr += l;
79         if (f->wptr >= f->buf_size)
80             f->wptr = 0;
81         buf += l;
82         len -= l;
83     }
84     f->count += len1;
85     return len1;
86 }
87
88 static int qemu_fifo_read(QEMUFIFO *f, uint8_t *buf, int len1)
89 {
90     int l, len;
91
92     if (len1 > f->count)
93         len1 = f->count;
94     len = len1;
95     while (len > 0) {
96         l = f->buf_size - f->rptr;
97         if (l > len)
98             l = len;
99         memcpy(buf, f->buf + f->rptr, l);
100         f->rptr += l;
101         if (f->rptr >= f->buf_size)
102             f->rptr = 0;
103         buf += l;
104         len -= l;
105     }
106     f->count -= len1;
107     return len1;
108 }
109
110 typedef enum {
111     GRAPHIC_CONSOLE,
112     TEXT_CONSOLE,
113     TEXT_CONSOLE_FIXED_SIZE
114 } console_type_t;
115
116 struct QemuConsole {
117     Object parent;
118
119     int index;
120     console_type_t console_type;
121     DisplayState *ds;
122     DisplaySurface *surface;
123     int dcls;
124
125     /* Graphic console state.  */
126     Object *device;
127     uint32_t head;
128     QemuUIInfo ui_info;
129     const GraphicHwOps *hw_ops;
130     void *hw;
131
132     /* Text console state */
133     int width;
134     int height;
135     int total_height;
136     int backscroll_height;
137     int x, y;
138     int x_saved, y_saved;
139     int y_displayed;
140     int y_base;
141     TextAttributes t_attrib_default; /* default text attributes */
142     TextAttributes t_attrib; /* currently active text attributes */
143     TextCell *cells;
144     int text_x[2], text_y[2], cursor_invalidate;
145     int echo;
146
147     int update_x0;
148     int update_y0;
149     int update_x1;
150     int update_y1;
151
152     enum TTYState state;
153     int esc_params[MAX_ESC_PARAMS];
154     int nb_esc_params;
155
156     CharDriverState *chr;
157     /* fifo for key pressed */
158     QEMUFIFO out_fifo;
159     uint8_t out_fifo_buf[16];
160     QEMUTimer *kbd_timer;
161 };
162
163 struct DisplayState {
164     QEMUTimer *gui_timer;
165     uint64_t last_update;
166     uint64_t update_interval;
167     bool refreshing;
168     bool have_gfx;
169     bool have_text;
170
171     QLIST_HEAD(, DisplayChangeListener) listeners;
172 };
173
174 static DisplayState *display_state;
175 static QemuConsole *active_console;
176 static QemuConsole *consoles[MAX_CONSOLES];
177 static int nb_consoles = 0;
178 static bool cursor_visible_phase;
179 static QEMUTimer *cursor_timer;
180
181 static void text_console_do_init(CharDriverState *chr, DisplayState *ds);
182 static void dpy_refresh(DisplayState *s);
183 static DisplayState *get_alloc_displaystate(void);
184 static void text_console_update_cursor_timer(void);
185 static void text_console_update_cursor(void *opaque);
186
187 static void gui_update(void *opaque)
188 {
189     uint64_t interval = GUI_REFRESH_INTERVAL_IDLE;
190     uint64_t dcl_interval;
191     DisplayState *ds = opaque;
192     DisplayChangeListener *dcl;
193     int i;
194
195     ds->refreshing = true;
196     dpy_refresh(ds);
197     ds->refreshing = false;
198
199     QLIST_FOREACH(dcl, &ds->listeners, next) {
200         dcl_interval = dcl->update_interval ?
201             dcl->update_interval : GUI_REFRESH_INTERVAL_DEFAULT;
202         if (interval > dcl_interval) {
203             interval = dcl_interval;
204         }
205     }
206     if (ds->update_interval != interval) {
207         ds->update_interval = interval;
208         for (i = 0; i < nb_consoles; i++) {
209             if (consoles[i]->hw_ops->update_interval) {
210                 consoles[i]->hw_ops->update_interval(consoles[i]->hw, interval);
211             }
212         }
213         trace_console_refresh(interval);
214     }
215     ds->last_update = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
216     timer_mod(ds->gui_timer, ds->last_update + interval);
217 }
218
219 static void gui_setup_refresh(DisplayState *ds)
220 {
221     DisplayChangeListener *dcl;
222     bool need_timer = false;
223     bool have_gfx = false;
224     bool have_text = false;
225
226     QLIST_FOREACH(dcl, &ds->listeners, next) {
227         if (dcl->ops->dpy_refresh != NULL) {
228             need_timer = true;
229         }
230         if (dcl->ops->dpy_gfx_update != NULL) {
231             have_gfx = true;
232         }
233         if (dcl->ops->dpy_text_update != NULL) {
234             have_text = true;
235         }
236     }
237
238     if (need_timer && ds->gui_timer == NULL) {
239         ds->gui_timer = timer_new_ms(QEMU_CLOCK_REALTIME, gui_update, ds);
240         timer_mod(ds->gui_timer, qemu_clock_get_ms(QEMU_CLOCK_REALTIME));
241     }
242     if (!need_timer && ds->gui_timer != NULL) {
243         timer_del(ds->gui_timer);
244         timer_free(ds->gui_timer);
245         ds->gui_timer = NULL;
246     }
247
248     ds->have_gfx = have_gfx;
249     ds->have_text = have_text;
250 }
251
252 void graphic_hw_update(QemuConsole *con)
253 {
254     if (!con) {
255         con = active_console;
256     }
257     if (con && con->hw_ops->gfx_update) {
258         con->hw_ops->gfx_update(con->hw);
259     }
260 }
261
262 void graphic_hw_invalidate(QemuConsole *con)
263 {
264     if (!con) {
265         con = active_console;
266     }
267     if (con && con->hw_ops->invalidate) {
268         con->hw_ops->invalidate(con->hw);
269     }
270 }
271
272 static void ppm_save(const char *filename, struct DisplaySurface *ds,
273                      Error **errp)
274 {
275     int width = pixman_image_get_width(ds->image);
276     int height = pixman_image_get_height(ds->image);
277     int fd;
278     FILE *f;
279     int y;
280     int ret;
281     pixman_image_t *linebuf;
282
283     trace_ppm_save(filename, ds);
284     fd = qemu_open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0666);
285     if (fd == -1) {
286         error_setg(errp, "failed to open file '%s': %s", filename,
287                    strerror(errno));
288         return;
289     }
290     f = fdopen(fd, "wb");
291     ret = fprintf(f, "P6\n%d %d\n%d\n", width, height, 255);
292     if (ret < 0) {
293         linebuf = NULL;
294         goto write_err;
295     }
296     linebuf = qemu_pixman_linebuf_create(PIXMAN_BE_r8g8b8, width);
297     for (y = 0; y < height; y++) {
298         qemu_pixman_linebuf_fill(linebuf, ds->image, width, 0, y);
299         clearerr(f);
300         ret = fwrite(pixman_image_get_data(linebuf), 1,
301                      pixman_image_get_stride(linebuf), f);
302         (void)ret;
303         if (ferror(f)) {
304             goto write_err;
305         }
306     }
307
308 out:
309     qemu_pixman_image_unref(linebuf);
310     fclose(f);
311     return;
312
313 write_err:
314     error_setg(errp, "failed to write to file '%s': %s", filename,
315                strerror(errno));
316     unlink(filename);
317     goto out;
318 }
319
320 void qmp_screendump(const char *filename, Error **errp)
321 {
322     QemuConsole *con = qemu_console_lookup_by_index(0);
323     DisplaySurface *surface;
324
325     if (con == NULL) {
326         error_setg(errp, "There is no QemuConsole I can screendump from.");
327         return;
328     }
329
330     graphic_hw_update(con);
331     surface = qemu_console_surface(con);
332     ppm_save(filename, surface, errp);
333 }
334
335 void graphic_hw_text_update(QemuConsole *con, console_ch_t *chardata)
336 {
337     if (!con) {
338         con = active_console;
339     }
340     if (con && con->hw_ops->text_update) {
341         con->hw_ops->text_update(con->hw, chardata);
342     }
343 }
344
345 static void vga_fill_rect(QemuConsole *con,
346                           int posx, int posy, int width, int height,
347                           pixman_color_t color)
348 {
349     DisplaySurface *surface = qemu_console_surface(con);
350     pixman_rectangle16_t rect = {
351         .x = posx, .y = posy, .width = width, .height = height
352     };
353
354     pixman_image_fill_rectangles(PIXMAN_OP_SRC, surface->image,
355                                  &color, 1, &rect);
356 }
357
358 /* copy from (xs, ys) to (xd, yd) a rectangle of size (w, h) */
359 static void vga_bitblt(QemuConsole *con,
360                        int xs, int ys, int xd, int yd, int w, int h)
361 {
362     DisplaySurface *surface = qemu_console_surface(con);
363
364     pixman_image_composite(PIXMAN_OP_SRC,
365                            surface->image, NULL, surface->image,
366                            xs, ys, 0, 0, xd, yd, w, h);
367 }
368
369 /***********************************************************/
370 /* basic char display */
371
372 #define FONT_HEIGHT 16
373 #define FONT_WIDTH 8
374
375 #include "vgafont.h"
376
377 #ifndef CONFIG_CURSES
378 enum color_names {
379     COLOR_BLACK   = 0,
380     COLOR_RED     = 1,
381     COLOR_GREEN   = 2,
382     COLOR_YELLOW  = 3,
383     COLOR_BLUE    = 4,
384     COLOR_MAGENTA = 5,
385     COLOR_CYAN    = 6,
386     COLOR_WHITE   = 7
387 };
388 #endif
389
390 #define QEMU_RGB(r, g, b)                                               \
391     { .red = r << 8, .green = g << 8, .blue = b << 8, .alpha = 0xffff }
392
393 static const pixman_color_t color_table_rgb[2][8] = {
394     {   /* dark */
395         QEMU_RGB(0x00, 0x00, 0x00),  /* black */
396         QEMU_RGB(0xaa, 0x00, 0x00),  /* red */
397         QEMU_RGB(0x00, 0xaa, 0x00),  /* green */
398         QEMU_RGB(0xaa, 0xaa, 0x00),  /* yellow */
399         QEMU_RGB(0x00, 0x00, 0xaa),  /* blue */
400         QEMU_RGB(0xaa, 0x00, 0xaa),  /* magenta */
401         QEMU_RGB(0x00, 0xaa, 0xaa),  /* cyan */
402         QEMU_RGB(0xaa, 0xaa, 0xaa),  /* white */
403     },
404     {   /* bright */
405         QEMU_RGB(0x00, 0x00, 0x00),  /* black */
406         QEMU_RGB(0xff, 0x00, 0x00),  /* red */
407         QEMU_RGB(0x00, 0xff, 0x00),  /* green */
408         QEMU_RGB(0xff, 0xff, 0x00),  /* yellow */
409         QEMU_RGB(0x00, 0x00, 0xff),  /* blue */
410         QEMU_RGB(0xff, 0x00, 0xff),  /* magenta */
411         QEMU_RGB(0x00, 0xff, 0xff),  /* cyan */
412         QEMU_RGB(0xff, 0xff, 0xff),  /* white */
413     }
414 };
415
416 static void vga_putcharxy(QemuConsole *s, int x, int y, int ch,
417                           TextAttributes *t_attrib)
418 {
419     static pixman_image_t *glyphs[256];
420     DisplaySurface *surface = qemu_console_surface(s);
421     pixman_color_t fgcol, bgcol;
422
423     if (t_attrib->invers) {
424         bgcol = color_table_rgb[t_attrib->bold][t_attrib->fgcol];
425         fgcol = color_table_rgb[t_attrib->bold][t_attrib->bgcol];
426     } else {
427         fgcol = color_table_rgb[t_attrib->bold][t_attrib->fgcol];
428         bgcol = color_table_rgb[t_attrib->bold][t_attrib->bgcol];
429     }
430
431     if (!glyphs[ch]) {
432         glyphs[ch] = qemu_pixman_glyph_from_vgafont(FONT_HEIGHT, vgafont16, ch);
433     }
434     qemu_pixman_glyph_render(glyphs[ch], surface->image,
435                              &fgcol, &bgcol, x, y, FONT_WIDTH, FONT_HEIGHT);
436 }
437
438 static void text_console_resize(QemuConsole *s)
439 {
440     TextCell *cells, *c, *c1;
441     int w1, x, y, last_width;
442
443     last_width = s->width;
444     s->width = surface_width(s->surface) / FONT_WIDTH;
445     s->height = surface_height(s->surface) / FONT_HEIGHT;
446
447     w1 = last_width;
448     if (s->width < w1)
449         w1 = s->width;
450
451     cells = g_malloc(s->width * s->total_height * sizeof(TextCell));
452     for(y = 0; y < s->total_height; y++) {
453         c = &cells[y * s->width];
454         if (w1 > 0) {
455             c1 = &s->cells[y * last_width];
456             for(x = 0; x < w1; x++) {
457                 *c++ = *c1++;
458             }
459         }
460         for(x = w1; x < s->width; x++) {
461             c->ch = ' ';
462             c->t_attrib = s->t_attrib_default;
463             c++;
464         }
465     }
466     g_free(s->cells);
467     s->cells = cells;
468 }
469
470 static inline void text_update_xy(QemuConsole *s, int x, int y)
471 {
472     s->text_x[0] = MIN(s->text_x[0], x);
473     s->text_x[1] = MAX(s->text_x[1], x);
474     s->text_y[0] = MIN(s->text_y[0], y);
475     s->text_y[1] = MAX(s->text_y[1], y);
476 }
477
478 static void invalidate_xy(QemuConsole *s, int x, int y)
479 {
480     if (!qemu_console_is_visible(s)) {
481         return;
482     }
483     if (s->update_x0 > x * FONT_WIDTH)
484         s->update_x0 = x * FONT_WIDTH;
485     if (s->update_y0 > y * FONT_HEIGHT)
486         s->update_y0 = y * FONT_HEIGHT;
487     if (s->update_x1 < (x + 1) * FONT_WIDTH)
488         s->update_x1 = (x + 1) * FONT_WIDTH;
489     if (s->update_y1 < (y + 1) * FONT_HEIGHT)
490         s->update_y1 = (y + 1) * FONT_HEIGHT;
491 }
492
493 static void update_xy(QemuConsole *s, int x, int y)
494 {
495     TextCell *c;
496     int y1, y2;
497
498     if (s->ds->have_text) {
499         text_update_xy(s, x, y);
500     }
501
502     y1 = (s->y_base + y) % s->total_height;
503     y2 = y1 - s->y_displayed;
504     if (y2 < 0) {
505         y2 += s->total_height;
506     }
507     if (y2 < s->height) {
508         c = &s->cells[y1 * s->width + x];
509         vga_putcharxy(s, x, y2, c->ch,
510                       &(c->t_attrib));
511         invalidate_xy(s, x, y2);
512     }
513 }
514
515 static void console_show_cursor(QemuConsole *s, int show)
516 {
517     TextCell *c;
518     int y, y1;
519     int x = s->x;
520
521     if (s->ds->have_text) {
522         s->cursor_invalidate = 1;
523     }
524
525     if (x >= s->width) {
526         x = s->width - 1;
527     }
528     y1 = (s->y_base + s->y) % s->total_height;
529     y = y1 - s->y_displayed;
530     if (y < 0) {
531         y += s->total_height;
532     }
533     if (y < s->height) {
534         c = &s->cells[y1 * s->width + x];
535         if (show && cursor_visible_phase) {
536             TextAttributes t_attrib = s->t_attrib_default;
537             t_attrib.invers = !(t_attrib.invers); /* invert fg and bg */
538             vga_putcharxy(s, x, y, c->ch, &t_attrib);
539         } else {
540             vga_putcharxy(s, x, y, c->ch, &(c->t_attrib));
541         }
542         invalidate_xy(s, x, y);
543     }
544 }
545
546 static void console_refresh(QemuConsole *s)
547 {
548     DisplaySurface *surface = qemu_console_surface(s);
549     TextCell *c;
550     int x, y, y1;
551
552     if (s->ds->have_text) {
553         s->text_x[0] = 0;
554         s->text_y[0] = 0;
555         s->text_x[1] = s->width - 1;
556         s->text_y[1] = s->height - 1;
557         s->cursor_invalidate = 1;
558     }
559
560     vga_fill_rect(s, 0, 0, surface_width(surface), surface_height(surface),
561                   color_table_rgb[0][COLOR_BLACK]);
562     y1 = s->y_displayed;
563     for (y = 0; y < s->height; y++) {
564         c = s->cells + y1 * s->width;
565         for (x = 0; x < s->width; x++) {
566             vga_putcharxy(s, x, y, c->ch,
567                           &(c->t_attrib));
568             c++;
569         }
570         if (++y1 == s->total_height) {
571             y1 = 0;
572         }
573     }
574     console_show_cursor(s, 1);
575     dpy_gfx_update(s, 0, 0,
576                    surface_width(surface), surface_height(surface));
577 }
578
579 static void console_scroll(QemuConsole *s, int ydelta)
580 {
581     int i, y1;
582
583     if (ydelta > 0) {
584         for(i = 0; i < ydelta; i++) {
585             if (s->y_displayed == s->y_base)
586                 break;
587             if (++s->y_displayed == s->total_height)
588                 s->y_displayed = 0;
589         }
590     } else {
591         ydelta = -ydelta;
592         i = s->backscroll_height;
593         if (i > s->total_height - s->height)
594             i = s->total_height - s->height;
595         y1 = s->y_base - i;
596         if (y1 < 0)
597             y1 += s->total_height;
598         for(i = 0; i < ydelta; i++) {
599             if (s->y_displayed == y1)
600                 break;
601             if (--s->y_displayed < 0)
602                 s->y_displayed = s->total_height - 1;
603         }
604     }
605     console_refresh(s);
606 }
607
608 static void console_put_lf(QemuConsole *s)
609 {
610     TextCell *c;
611     int x, y1;
612
613     s->y++;
614     if (s->y >= s->height) {
615         s->y = s->height - 1;
616
617         if (s->y_displayed == s->y_base) {
618             if (++s->y_displayed == s->total_height)
619                 s->y_displayed = 0;
620         }
621         if (++s->y_base == s->total_height)
622             s->y_base = 0;
623         if (s->backscroll_height < s->total_height)
624             s->backscroll_height++;
625         y1 = (s->y_base + s->height - 1) % s->total_height;
626         c = &s->cells[y1 * s->width];
627         for(x = 0; x < s->width; x++) {
628             c->ch = ' ';
629             c->t_attrib = s->t_attrib_default;
630             c++;
631         }
632         if (s->y_displayed == s->y_base) {
633             if (s->ds->have_text) {
634                 s->text_x[0] = 0;
635                 s->text_y[0] = 0;
636                 s->text_x[1] = s->width - 1;
637                 s->text_y[1] = s->height - 1;
638             }
639
640             vga_bitblt(s, 0, FONT_HEIGHT, 0, 0,
641                        s->width * FONT_WIDTH,
642                        (s->height - 1) * FONT_HEIGHT);
643             vga_fill_rect(s, 0, (s->height - 1) * FONT_HEIGHT,
644                           s->width * FONT_WIDTH, FONT_HEIGHT,
645                           color_table_rgb[0][s->t_attrib_default.bgcol]);
646             s->update_x0 = 0;
647             s->update_y0 = 0;
648             s->update_x1 = s->width * FONT_WIDTH;
649             s->update_y1 = s->height * FONT_HEIGHT;
650         }
651     }
652 }
653
654 /* Set console attributes depending on the current escape codes.
655  * NOTE: I know this code is not very efficient (checking every color for it
656  * self) but it is more readable and better maintainable.
657  */
658 static void console_handle_escape(QemuConsole *s)
659 {
660     int i;
661
662     for (i=0; i<s->nb_esc_params; i++) {
663         switch (s->esc_params[i]) {
664             case 0: /* reset all console attributes to default */
665                 s->t_attrib = s->t_attrib_default;
666                 break;
667             case 1:
668                 s->t_attrib.bold = 1;
669                 break;
670             case 4:
671                 s->t_attrib.uline = 1;
672                 break;
673             case 5:
674                 s->t_attrib.blink = 1;
675                 break;
676             case 7:
677                 s->t_attrib.invers = 1;
678                 break;
679             case 8:
680                 s->t_attrib.unvisible = 1;
681                 break;
682             case 22:
683                 s->t_attrib.bold = 0;
684                 break;
685             case 24:
686                 s->t_attrib.uline = 0;
687                 break;
688             case 25:
689                 s->t_attrib.blink = 0;
690                 break;
691             case 27:
692                 s->t_attrib.invers = 0;
693                 break;
694             case 28:
695                 s->t_attrib.unvisible = 0;
696                 break;
697             /* set foreground color */
698             case 30:
699                 s->t_attrib.fgcol=COLOR_BLACK;
700                 break;
701             case 31:
702                 s->t_attrib.fgcol=COLOR_RED;
703                 break;
704             case 32:
705                 s->t_attrib.fgcol=COLOR_GREEN;
706                 break;
707             case 33:
708                 s->t_attrib.fgcol=COLOR_YELLOW;
709                 break;
710             case 34:
711                 s->t_attrib.fgcol=COLOR_BLUE;
712                 break;
713             case 35:
714                 s->t_attrib.fgcol=COLOR_MAGENTA;
715                 break;
716             case 36:
717                 s->t_attrib.fgcol=COLOR_CYAN;
718                 break;
719             case 37:
720                 s->t_attrib.fgcol=COLOR_WHITE;
721                 break;
722             /* set background color */
723             case 40:
724                 s->t_attrib.bgcol=COLOR_BLACK;
725                 break;
726             case 41:
727                 s->t_attrib.bgcol=COLOR_RED;
728                 break;
729             case 42:
730                 s->t_attrib.bgcol=COLOR_GREEN;
731                 break;
732             case 43:
733                 s->t_attrib.bgcol=COLOR_YELLOW;
734                 break;
735             case 44:
736                 s->t_attrib.bgcol=COLOR_BLUE;
737                 break;
738             case 45:
739                 s->t_attrib.bgcol=COLOR_MAGENTA;
740                 break;
741             case 46:
742                 s->t_attrib.bgcol=COLOR_CYAN;
743                 break;
744             case 47:
745                 s->t_attrib.bgcol=COLOR_WHITE;
746                 break;
747         }
748     }
749 }
750
751 static void console_clear_xy(QemuConsole *s, int x, int y)
752 {
753     int y1 = (s->y_base + y) % s->total_height;
754     TextCell *c = &s->cells[y1 * s->width + x];
755     c->ch = ' ';
756     c->t_attrib = s->t_attrib_default;
757     update_xy(s, x, y);
758 }
759
760 /* set cursor, checking bounds */
761 static void set_cursor(QemuConsole *s, int x, int y)
762 {
763     if (x < 0) {
764         x = 0;
765     }
766     if (y < 0) {
767         y = 0;
768     }
769     if (y >= s->height) {
770         y = s->height - 1;
771     }
772     if (x >= s->width) {
773         x = s->width - 1;
774     }
775
776     s->x = x;
777     s->y = y;
778 }
779
780 static void console_putchar(QemuConsole *s, int ch)
781 {
782     TextCell *c;
783     int y1, i;
784     int x, y;
785
786     switch(s->state) {
787     case TTY_STATE_NORM:
788         switch(ch) {
789         case '\r':  /* carriage return */
790             s->x = 0;
791             break;
792         case '\n':  /* newline */
793             console_put_lf(s);
794             break;
795         case '\b':  /* backspace */
796             if (s->x > 0)
797                 s->x--;
798             break;
799         case '\t':  /* tabspace */
800             if (s->x + (8 - (s->x % 8)) > s->width) {
801                 s->x = 0;
802                 console_put_lf(s);
803             } else {
804                 s->x = s->x + (8 - (s->x % 8));
805             }
806             break;
807         case '\a':  /* alert aka. bell */
808             /* TODO: has to be implemented */
809             break;
810         case 14:
811             /* SI (shift in), character set 0 (ignored) */
812             break;
813         case 15:
814             /* SO (shift out), character set 1 (ignored) */
815             break;
816         case 27:    /* esc (introducing an escape sequence) */
817             s->state = TTY_STATE_ESC;
818             break;
819         default:
820             if (s->x >= s->width) {
821                 /* line wrap */
822                 s->x = 0;
823                 console_put_lf(s);
824             }
825             y1 = (s->y_base + s->y) % s->total_height;
826             c = &s->cells[y1 * s->width + s->x];
827             c->ch = ch;
828             c->t_attrib = s->t_attrib;
829             update_xy(s, s->x, s->y);
830             s->x++;
831             break;
832         }
833         break;
834     case TTY_STATE_ESC: /* check if it is a terminal escape sequence */
835         if (ch == '[') {
836             for(i=0;i<MAX_ESC_PARAMS;i++)
837                 s->esc_params[i] = 0;
838             s->nb_esc_params = 0;
839             s->state = TTY_STATE_CSI;
840         } else {
841             s->state = TTY_STATE_NORM;
842         }
843         break;
844     case TTY_STATE_CSI: /* handle escape sequence parameters */
845         if (ch >= '0' && ch <= '9') {
846             if (s->nb_esc_params < MAX_ESC_PARAMS) {
847                 int *param = &s->esc_params[s->nb_esc_params];
848                 int digit = (ch - '0');
849
850                 *param = (*param <= (INT_MAX - digit) / 10) ?
851                          *param * 10 + digit : INT_MAX;
852             }
853         } else {
854             if (s->nb_esc_params < MAX_ESC_PARAMS)
855                 s->nb_esc_params++;
856             if (ch == ';')
857                 break;
858             trace_console_putchar_csi(s->esc_params[0], s->esc_params[1],
859                                       ch, s->nb_esc_params);
860             s->state = TTY_STATE_NORM;
861             switch(ch) {
862             case 'A':
863                 /* move cursor up */
864                 if (s->esc_params[0] == 0) {
865                     s->esc_params[0] = 1;
866                 }
867                 set_cursor(s, s->x, s->y - s->esc_params[0]);
868                 break;
869             case 'B':
870                 /* move cursor down */
871                 if (s->esc_params[0] == 0) {
872                     s->esc_params[0] = 1;
873                 }
874                 set_cursor(s, s->x, s->y + s->esc_params[0]);
875                 break;
876             case 'C':
877                 /* move cursor right */
878                 if (s->esc_params[0] == 0) {
879                     s->esc_params[0] = 1;
880                 }
881                 set_cursor(s, s->x + s->esc_params[0], s->y);
882                 break;
883             case 'D':
884                 /* move cursor left */
885                 if (s->esc_params[0] == 0) {
886                     s->esc_params[0] = 1;
887                 }
888                 set_cursor(s, s->x - s->esc_params[0], s->y);
889                 break;
890             case 'G':
891                 /* move cursor to column */
892                 set_cursor(s, s->esc_params[0] - 1, s->y);
893                 break;
894             case 'f':
895             case 'H':
896                 /* move cursor to row, column */
897                 set_cursor(s, s->esc_params[1] - 1, s->esc_params[0] - 1);
898                 break;
899             case 'J':
900                 switch (s->esc_params[0]) {
901                 case 0:
902                     /* clear to end of screen */
903                     for (y = s->y; y < s->height; y++) {
904                         for (x = 0; x < s->width; x++) {
905                             if (y == s->y && x < s->x) {
906                                 continue;
907                             }
908                             console_clear_xy(s, x, y);
909                         }
910                     }
911                     break;
912                 case 1:
913                     /* clear from beginning of screen */
914                     for (y = 0; y <= s->y; y++) {
915                         for (x = 0; x < s->width; x++) {
916                             if (y == s->y && x > s->x) {
917                                 break;
918                             }
919                             console_clear_xy(s, x, y);
920                         }
921                     }
922                     break;
923                 case 2:
924                     /* clear entire screen */
925                     for (y = 0; y <= s->height; y++) {
926                         for (x = 0; x < s->width; x++) {
927                             console_clear_xy(s, x, y);
928                         }
929                     }
930                     break;
931                 }
932                 break;
933             case 'K':
934                 switch (s->esc_params[0]) {
935                 case 0:
936                     /* clear to eol */
937                     for(x = s->x; x < s->width; x++) {
938                         console_clear_xy(s, x, s->y);
939                     }
940                     break;
941                 case 1:
942                     /* clear from beginning of line */
943                     for (x = 0; x <= s->x; x++) {
944                         console_clear_xy(s, x, s->y);
945                     }
946                     break;
947                 case 2:
948                     /* clear entire line */
949                     for(x = 0; x < s->width; x++) {
950                         console_clear_xy(s, x, s->y);
951                     }
952                     break;
953                 }
954                 break;
955             case 'm':
956                 console_handle_escape(s);
957                 break;
958             case 'n':
959                 /* report cursor position */
960                 /* TODO: send ESC[row;colR */
961                 break;
962             case 's':
963                 /* save cursor position */
964                 s->x_saved = s->x;
965                 s->y_saved = s->y;
966                 break;
967             case 'u':
968                 /* restore cursor position */
969                 s->x = s->x_saved;
970                 s->y = s->y_saved;
971                 break;
972             default:
973                 trace_console_putchar_unhandled(ch);
974                 break;
975             }
976             break;
977         }
978     }
979 }
980
981 void console_select(unsigned int index)
982 {
983     DisplayChangeListener *dcl;
984     QemuConsole *s;
985
986     if (index >= MAX_CONSOLES)
987         return;
988
989     trace_console_select(index);
990     s = qemu_console_lookup_by_index(index);
991     if (s) {
992         DisplayState *ds = s->ds;
993
994         active_console = s;
995         if (ds->have_gfx) {
996             QLIST_FOREACH(dcl, &ds->listeners, next) {
997                 if (dcl->con != NULL) {
998                     continue;
999                 }
1000                 if (dcl->ops->dpy_gfx_switch) {
1001                     dcl->ops->dpy_gfx_switch(dcl, s->surface);
1002                 }
1003             }
1004             dpy_gfx_update(s, 0, 0, surface_width(s->surface),
1005                            surface_height(s->surface));
1006         }
1007         if (ds->have_text) {
1008             dpy_text_resize(s, s->width, s->height);
1009         }
1010         text_console_update_cursor(NULL);
1011     }
1012 }
1013
1014 static int console_puts(CharDriverState *chr, const uint8_t *buf, int len)
1015 {
1016     QemuConsole *s = chr->opaque;
1017     int i;
1018
1019     s->update_x0 = s->width * FONT_WIDTH;
1020     s->update_y0 = s->height * FONT_HEIGHT;
1021     s->update_x1 = 0;
1022     s->update_y1 = 0;
1023     console_show_cursor(s, 0);
1024     for(i = 0; i < len; i++) {
1025         console_putchar(s, buf[i]);
1026     }
1027     console_show_cursor(s, 1);
1028     if (s->ds->have_gfx && s->update_x0 < s->update_x1) {
1029         dpy_gfx_update(s, s->update_x0, s->update_y0,
1030                        s->update_x1 - s->update_x0,
1031                        s->update_y1 - s->update_y0);
1032     }
1033     return len;
1034 }
1035
1036 static void kbd_send_chars(void *opaque)
1037 {
1038     QemuConsole *s = opaque;
1039     int len;
1040     uint8_t buf[16];
1041
1042     len = qemu_chr_be_can_write(s->chr);
1043     if (len > s->out_fifo.count)
1044         len = s->out_fifo.count;
1045     if (len > 0) {
1046         if (len > sizeof(buf))
1047             len = sizeof(buf);
1048         qemu_fifo_read(&s->out_fifo, buf, len);
1049         qemu_chr_be_write(s->chr, buf, len);
1050     }
1051     /* characters are pending: we send them a bit later (XXX:
1052        horrible, should change char device API) */
1053     if (s->out_fifo.count > 0) {
1054         timer_mod(s->kbd_timer, qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + 1);
1055     }
1056 }
1057
1058 /* called when an ascii key is pressed */
1059 void kbd_put_keysym_console(QemuConsole *s, int keysym)
1060 {
1061     uint8_t buf[16], *q;
1062     int c;
1063
1064     if (!s || (s->console_type == GRAPHIC_CONSOLE))
1065         return;
1066
1067     switch(keysym) {
1068     case QEMU_KEY_CTRL_UP:
1069         console_scroll(s, -1);
1070         break;
1071     case QEMU_KEY_CTRL_DOWN:
1072         console_scroll(s, 1);
1073         break;
1074     case QEMU_KEY_CTRL_PAGEUP:
1075         console_scroll(s, -10);
1076         break;
1077     case QEMU_KEY_CTRL_PAGEDOWN:
1078         console_scroll(s, 10);
1079         break;
1080     default:
1081         /* convert the QEMU keysym to VT100 key string */
1082         q = buf;
1083         if (keysym >= 0xe100 && keysym <= 0xe11f) {
1084             *q++ = '\033';
1085             *q++ = '[';
1086             c = keysym - 0xe100;
1087             if (c >= 10)
1088                 *q++ = '0' + (c / 10);
1089             *q++ = '0' + (c % 10);
1090             *q++ = '~';
1091         } else if (keysym >= 0xe120 && keysym <= 0xe17f) {
1092             *q++ = '\033';
1093             *q++ = '[';
1094             *q++ = keysym & 0xff;
1095         } else if (s->echo && (keysym == '\r' || keysym == '\n')) {
1096             console_puts(s->chr, (const uint8_t *) "\r", 1);
1097             *q++ = '\n';
1098         } else {
1099             *q++ = keysym;
1100         }
1101         if (s->echo) {
1102             console_puts(s->chr, buf, q - buf);
1103         }
1104         if (s->chr->chr_read) {
1105             qemu_fifo_write(&s->out_fifo, buf, q - buf);
1106             kbd_send_chars(s);
1107         }
1108         break;
1109     }
1110 }
1111
1112 void kbd_put_keysym(int keysym)
1113 {
1114     kbd_put_keysym_console(active_console, keysym);
1115 }
1116
1117 static void text_console_invalidate(void *opaque)
1118 {
1119     QemuConsole *s = (QemuConsole *) opaque;
1120
1121     if (s->ds->have_text && s->console_type == TEXT_CONSOLE) {
1122         text_console_resize(s);
1123     }
1124     console_refresh(s);
1125 }
1126
1127 static void text_console_update(void *opaque, console_ch_t *chardata)
1128 {
1129     QemuConsole *s = (QemuConsole *) opaque;
1130     int i, j, src;
1131
1132     if (s->text_x[0] <= s->text_x[1]) {
1133         src = (s->y_base + s->text_y[0]) * s->width;
1134         chardata += s->text_y[0] * s->width;
1135         for (i = s->text_y[0]; i <= s->text_y[1]; i ++)
1136             for (j = 0; j < s->width; j ++, src ++)
1137                 console_write_ch(chardata ++, s->cells[src].ch |
1138                                 (s->cells[src].t_attrib.fgcol << 12) |
1139                                 (s->cells[src].t_attrib.bgcol << 8) |
1140                                 (s->cells[src].t_attrib.bold << 21));
1141         dpy_text_update(s, s->text_x[0], s->text_y[0],
1142                         s->text_x[1] - s->text_x[0], i - s->text_y[0]);
1143         s->text_x[0] = s->width;
1144         s->text_y[0] = s->height;
1145         s->text_x[1] = 0;
1146         s->text_y[1] = 0;
1147     }
1148     if (s->cursor_invalidate) {
1149         dpy_text_cursor(s, s->x, s->y);
1150         s->cursor_invalidate = 0;
1151     }
1152 }
1153
1154 static QemuConsole *new_console(DisplayState *ds, console_type_t console_type,
1155                                 uint32_t head)
1156 {
1157     Object *obj;
1158     QemuConsole *s;
1159     int i;
1160
1161     if (nb_consoles >= MAX_CONSOLES)
1162         return NULL;
1163
1164     obj = object_new(TYPE_QEMU_CONSOLE);
1165     s = QEMU_CONSOLE(obj);
1166     s->head = head;
1167     object_property_add_link(obj, "device", TYPE_DEVICE,
1168                              (Object **)&s->device,
1169                              object_property_allow_set_link,
1170                              OBJ_PROP_LINK_UNREF_ON_RELEASE,
1171                              &error_abort);
1172     object_property_add_uint32_ptr(obj, "head",
1173                                    &s->head, &error_abort);
1174
1175     if (!active_console || ((active_console->console_type != GRAPHIC_CONSOLE) &&
1176         (console_type == GRAPHIC_CONSOLE))) {
1177         active_console = s;
1178     }
1179     s->ds = ds;
1180     s->console_type = console_type;
1181     if (console_type != GRAPHIC_CONSOLE) {
1182         s->index = nb_consoles;
1183         consoles[nb_consoles++] = s;
1184     } else {
1185         /* HACK: Put graphical consoles before text consoles.  */
1186         for (i = nb_consoles; i > 0; i--) {
1187             if (consoles[i - 1]->console_type == GRAPHIC_CONSOLE)
1188                 break;
1189             consoles[i] = consoles[i - 1];
1190             consoles[i]->index = i;
1191         }
1192         s->index = i;
1193         consoles[i] = s;
1194         nb_consoles++;
1195     }
1196     return s;
1197 }
1198
1199 static void qemu_alloc_display(DisplaySurface *surface, int width, int height,
1200                                int linesize, PixelFormat pf, int newflags)
1201 {
1202     surface->pf = pf;
1203
1204     qemu_pixman_image_unref(surface->image);
1205     surface->image = NULL;
1206
1207     surface->format = qemu_pixman_get_format(&pf);
1208     assert(surface->format != 0);
1209     surface->image = pixman_image_create_bits(surface->format,
1210                                               width, height,
1211                                               NULL, linesize);
1212     assert(surface->image != NULL);
1213
1214     surface->flags = newflags | QEMU_ALLOCATED_FLAG;
1215 #ifdef HOST_WORDS_BIGENDIAN
1216     surface->flags |= QEMU_BIG_ENDIAN_FLAG;
1217 #endif
1218 }
1219
1220 DisplaySurface *qemu_create_displaysurface(int width, int height)
1221 {
1222     DisplaySurface *surface = g_new0(DisplaySurface, 1);
1223     int linesize = width * 4;
1224
1225     trace_displaysurface_create(surface, width, height);
1226     qemu_alloc_display(surface, width, height, linesize,
1227                        qemu_default_pixelformat(32), 0);
1228     return surface;
1229 }
1230
1231 DisplaySurface *qemu_create_displaysurface_from(int width, int height, int bpp,
1232                                                 int linesize, uint8_t *data,
1233                                                 bool byteswap)
1234 {
1235     DisplaySurface *surface = g_new0(DisplaySurface, 1);
1236
1237     trace_displaysurface_create_from(surface, width, height, bpp, byteswap);
1238     if (byteswap) {
1239         surface->pf = qemu_different_endianness_pixelformat(bpp);
1240     } else {
1241         surface->pf = qemu_default_pixelformat(bpp);
1242     }
1243
1244     surface->format = qemu_pixman_get_format(&surface->pf);
1245     assert(surface->format != 0);
1246     surface->image = pixman_image_create_bits(surface->format,
1247                                               width, height,
1248                                               (void *)data, linesize);
1249     assert(surface->image != NULL);
1250
1251 #ifdef HOST_WORDS_BIGENDIAN
1252     surface->flags = QEMU_BIG_ENDIAN_FLAG;
1253 #endif
1254
1255     return surface;
1256 }
1257
1258 static DisplaySurface *qemu_create_message_surface(int w, int h,
1259                                                    const char *msg)
1260 {
1261     DisplaySurface *surface = qemu_create_displaysurface(w, h);
1262     pixman_color_t bg = color_table_rgb[0][COLOR_BLACK];
1263     pixman_color_t fg = color_table_rgb[0][COLOR_WHITE];
1264     pixman_image_t *glyph;
1265     int len, x, y, i;
1266
1267     len = strlen(msg);
1268     x = (w / FONT_WIDTH  - len) / 2;
1269     y = (h / FONT_HEIGHT - 1)   / 2;
1270     for (i = 0; i < len; i++) {
1271         glyph = qemu_pixman_glyph_from_vgafont(FONT_HEIGHT, vgafont16, msg[i]);
1272         qemu_pixman_glyph_render(glyph, surface->image, &fg, &bg,
1273                                  x+i, y, FONT_WIDTH, FONT_HEIGHT);
1274         qemu_pixman_image_unref(glyph);
1275     }
1276     return surface;
1277 }
1278
1279 void qemu_free_displaysurface(DisplaySurface *surface)
1280 {
1281     if (surface == NULL) {
1282         return;
1283     }
1284     trace_displaysurface_free(surface);
1285     qemu_pixman_image_unref(surface->image);
1286     g_free(surface);
1287 }
1288
1289 void register_displaychangelistener(DisplayChangeListener *dcl)
1290 {
1291     static const char nodev[] =
1292         "This VM has no graphic display device.";
1293     static DisplaySurface *dummy;
1294     QemuConsole *con;
1295
1296     trace_displaychangelistener_register(dcl, dcl->ops->dpy_name);
1297     dcl->ds = get_alloc_displaystate();
1298     QLIST_INSERT_HEAD(&dcl->ds->listeners, dcl, next);
1299     gui_setup_refresh(dcl->ds);
1300     if (dcl->con) {
1301         dcl->con->dcls++;
1302         con = dcl->con;
1303     } else {
1304         con = active_console;
1305     }
1306     if (dcl->ops->dpy_gfx_switch) {
1307         if (con) {
1308             dcl->ops->dpy_gfx_switch(dcl, con->surface);
1309         } else {
1310             if (!dummy) {
1311                 dummy = qemu_create_message_surface(640, 480, nodev);
1312             }
1313             dcl->ops->dpy_gfx_switch(dcl, dummy);
1314         }
1315     }
1316     text_console_update_cursor(NULL);
1317 }
1318
1319 void update_displaychangelistener(DisplayChangeListener *dcl,
1320                                   uint64_t interval)
1321 {
1322     DisplayState *ds = dcl->ds;
1323
1324     dcl->update_interval = interval;
1325     if (!ds->refreshing && ds->update_interval > interval) {
1326         timer_mod(ds->gui_timer, ds->last_update + interval);
1327     }
1328 }
1329
1330 void unregister_displaychangelistener(DisplayChangeListener *dcl)
1331 {
1332     DisplayState *ds = dcl->ds;
1333     trace_displaychangelistener_unregister(dcl, dcl->ops->dpy_name);
1334     if (dcl->con) {
1335         dcl->con->dcls--;
1336     }
1337     QLIST_REMOVE(dcl, next);
1338     gui_setup_refresh(ds);
1339 }
1340
1341 int dpy_set_ui_info(QemuConsole *con, QemuUIInfo *info)
1342 {
1343     assert(con != NULL);
1344     con->ui_info = *info;
1345     if (con->hw_ops->ui_info) {
1346         return con->hw_ops->ui_info(con->hw, con->head, info);
1347     }
1348     return -1;
1349 }
1350
1351 void dpy_gfx_update(QemuConsole *con, int x, int y, int w, int h)
1352 {
1353     DisplayState *s = con->ds;
1354     DisplayChangeListener *dcl;
1355     int width = surface_width(con->surface);
1356     int height = surface_height(con->surface);
1357
1358     x = MAX(x, 0);
1359     y = MAX(y, 0);
1360     x = MIN(x, width);
1361     y = MIN(y, height);
1362     w = MIN(w, width - x);
1363     h = MIN(h, height - y);
1364
1365     if (!qemu_console_is_visible(con)) {
1366         return;
1367     }
1368     QLIST_FOREACH(dcl, &s->listeners, next) {
1369         if (con != (dcl->con ? dcl->con : active_console)) {
1370             continue;
1371         }
1372         if (dcl->ops->dpy_gfx_update) {
1373             dcl->ops->dpy_gfx_update(dcl, x, y, w, h);
1374         }
1375     }
1376 }
1377
1378 void dpy_gfx_replace_surface(QemuConsole *con,
1379                              DisplaySurface *surface)
1380 {
1381     DisplayState *s = con->ds;
1382     DisplaySurface *old_surface = con->surface;
1383     DisplayChangeListener *dcl;
1384
1385     con->surface = surface;
1386     QLIST_FOREACH(dcl, &s->listeners, next) {
1387         if (con != (dcl->con ? dcl->con : active_console)) {
1388             continue;
1389         }
1390         if (dcl->ops->dpy_gfx_switch) {
1391             dcl->ops->dpy_gfx_switch(dcl, surface);
1392         }
1393     }
1394     qemu_free_displaysurface(old_surface);
1395 }
1396
1397 static void dpy_refresh(DisplayState *s)
1398 {
1399     DisplayChangeListener *dcl;
1400
1401     QLIST_FOREACH(dcl, &s->listeners, next) {
1402         if (dcl->ops->dpy_refresh) {
1403             dcl->ops->dpy_refresh(dcl);
1404         }
1405     }
1406 }
1407
1408 void dpy_gfx_copy(QemuConsole *con, int src_x, int src_y,
1409                   int dst_x, int dst_y, int w, int h)
1410 {
1411     DisplayState *s = con->ds;
1412     DisplayChangeListener *dcl;
1413
1414     if (!qemu_console_is_visible(con)) {
1415         return;
1416     }
1417     QLIST_FOREACH(dcl, &s->listeners, next) {
1418         if (con != (dcl->con ? dcl->con : active_console)) {
1419             continue;
1420         }
1421         if (dcl->ops->dpy_gfx_copy) {
1422             dcl->ops->dpy_gfx_copy(dcl, src_x, src_y, dst_x, dst_y, w, h);
1423         } else { /* TODO */
1424             dcl->ops->dpy_gfx_update(dcl, dst_x, dst_y, w, h);
1425         }
1426     }
1427 }
1428
1429 void dpy_text_cursor(QemuConsole *con, int x, int y)
1430 {
1431     DisplayState *s = con->ds;
1432     DisplayChangeListener *dcl;
1433
1434     if (!qemu_console_is_visible(con)) {
1435         return;
1436     }
1437     QLIST_FOREACH(dcl, &s->listeners, next) {
1438         if (con != (dcl->con ? dcl->con : active_console)) {
1439             continue;
1440         }
1441         if (dcl->ops->dpy_text_cursor) {
1442             dcl->ops->dpy_text_cursor(dcl, x, y);
1443         }
1444     }
1445 }
1446
1447 void dpy_text_update(QemuConsole *con, int x, int y, int w, int h)
1448 {
1449     DisplayState *s = con->ds;
1450     DisplayChangeListener *dcl;
1451
1452     if (!qemu_console_is_visible(con)) {
1453         return;
1454     }
1455     QLIST_FOREACH(dcl, &s->listeners, next) {
1456         if (con != (dcl->con ? dcl->con : active_console)) {
1457             continue;
1458         }
1459         if (dcl->ops->dpy_text_update) {
1460             dcl->ops->dpy_text_update(dcl, x, y, w, h);
1461         }
1462     }
1463 }
1464
1465 void dpy_text_resize(QemuConsole *con, int w, int h)
1466 {
1467     DisplayState *s = con->ds;
1468     struct DisplayChangeListener *dcl;
1469
1470     if (!qemu_console_is_visible(con)) {
1471         return;
1472     }
1473     QLIST_FOREACH(dcl, &s->listeners, next) {
1474         if (con != (dcl->con ? dcl->con : active_console)) {
1475             continue;
1476         }
1477         if (dcl->ops->dpy_text_resize) {
1478             dcl->ops->dpy_text_resize(dcl, w, h);
1479         }
1480     }
1481 }
1482
1483 void dpy_mouse_set(QemuConsole *con, int x, int y, int on)
1484 {
1485     DisplayState *s = con->ds;
1486     DisplayChangeListener *dcl;
1487
1488     if (!qemu_console_is_visible(con)) {
1489         return;
1490     }
1491     QLIST_FOREACH(dcl, &s->listeners, next) {
1492         if (con != (dcl->con ? dcl->con : active_console)) {
1493             continue;
1494         }
1495         if (dcl->ops->dpy_mouse_set) {
1496             dcl->ops->dpy_mouse_set(dcl, x, y, on);
1497         }
1498     }
1499 }
1500
1501 void dpy_cursor_define(QemuConsole *con, QEMUCursor *cursor)
1502 {
1503     DisplayState *s = con->ds;
1504     DisplayChangeListener *dcl;
1505
1506     if (!qemu_console_is_visible(con)) {
1507         return;
1508     }
1509     QLIST_FOREACH(dcl, &s->listeners, next) {
1510         if (con != (dcl->con ? dcl->con : active_console)) {
1511             continue;
1512         }
1513         if (dcl->ops->dpy_cursor_define) {
1514             dcl->ops->dpy_cursor_define(dcl, cursor);
1515         }
1516     }
1517 }
1518
1519 bool dpy_cursor_define_supported(QemuConsole *con)
1520 {
1521     DisplayState *s = con->ds;
1522     DisplayChangeListener *dcl;
1523
1524     QLIST_FOREACH(dcl, &s->listeners, next) {
1525         if (dcl->ops->dpy_cursor_define) {
1526             return true;
1527         }
1528     }
1529     return false;
1530 }
1531
1532 /***********************************************************/
1533 /* register display */
1534
1535 /* console.c internal use only */
1536 static DisplayState *get_alloc_displaystate(void)
1537 {
1538     if (!display_state) {
1539         display_state = g_new0(DisplayState, 1);
1540         cursor_timer = timer_new_ms(QEMU_CLOCK_REALTIME,
1541                                     text_console_update_cursor, NULL);
1542     }
1543     return display_state;
1544 }
1545
1546 /*
1547  * Called by main(), after creating QemuConsoles
1548  * and before initializing ui (sdl/vnc/...).
1549  */
1550 DisplayState *init_displaystate(void)
1551 {
1552     gchar *name;
1553     int i;
1554
1555     if (!display_state) {
1556         display_state = g_new0(DisplayState, 1);
1557     }
1558
1559     for (i = 0; i < nb_consoles; i++) {
1560         if (consoles[i]->console_type != GRAPHIC_CONSOLE &&
1561             consoles[i]->ds == NULL) {
1562             text_console_do_init(consoles[i]->chr, display_state);
1563         }
1564
1565         /* Hook up into the qom tree here (not in new_console()), once
1566          * all QemuConsoles are created and the order / numbering
1567          * doesn't change any more */
1568         name = g_strdup_printf("console[%d]", i);
1569         object_property_add_child(container_get(object_get_root(), "/backend"),
1570                                   name, OBJECT(consoles[i]), &error_abort);
1571         g_free(name);
1572     }
1573
1574     return display_state;
1575 }
1576
1577 QemuConsole *graphic_console_init(DeviceState *dev, uint32_t head,
1578                                   const GraphicHwOps *hw_ops,
1579                                   void *opaque)
1580 {
1581     static const char noinit[] =
1582         "Guest has not initialized the display (yet).";
1583     int width = 640;
1584     int height = 480;
1585     QemuConsole *s;
1586     DisplayState *ds;
1587
1588     ds = get_alloc_displaystate();
1589     trace_console_gfx_new();
1590     s = new_console(ds, GRAPHIC_CONSOLE, head);
1591     s->hw_ops = hw_ops;
1592     s->hw = opaque;
1593     if (dev) {
1594         object_property_set_link(OBJECT(s), OBJECT(dev), "device",
1595                                  &error_abort);
1596     }
1597
1598     s->surface = qemu_create_message_surface(width, height, noinit);
1599     return s;
1600 }
1601
1602 QemuConsole *qemu_console_lookup_by_index(unsigned int index)
1603 {
1604     if (index >= MAX_CONSOLES) {
1605         return NULL;
1606     }
1607     return consoles[index];
1608 }
1609
1610 QemuConsole *qemu_console_lookup_by_device(DeviceState *dev, uint32_t head)
1611 {
1612     Object *obj;
1613     uint32_t h;
1614     int i;
1615
1616     for (i = 0; i < nb_consoles; i++) {
1617         if (!consoles[i]) {
1618             continue;
1619         }
1620         obj = object_property_get_link(OBJECT(consoles[i]),
1621                                        "device", &error_abort);
1622         if (DEVICE(obj) != dev) {
1623             continue;
1624         }
1625         h = object_property_get_int(OBJECT(consoles[i]),
1626                                     "head", &error_abort);
1627         if (h != head) {
1628             continue;
1629         }
1630         return consoles[i];
1631     }
1632     return NULL;
1633 }
1634
1635 bool qemu_console_is_visible(QemuConsole *con)
1636 {
1637     return (con == active_console) || (con->dcls > 0);
1638 }
1639
1640 bool qemu_console_is_graphic(QemuConsole *con)
1641 {
1642     if (con == NULL) {
1643         con = active_console;
1644     }
1645     return con && (con->console_type == GRAPHIC_CONSOLE);
1646 }
1647
1648 bool qemu_console_is_fixedsize(QemuConsole *con)
1649 {
1650     if (con == NULL) {
1651         con = active_console;
1652     }
1653     return con && (con->console_type != TEXT_CONSOLE);
1654 }
1655
1656 int qemu_console_get_index(QemuConsole *con)
1657 {
1658     if (con == NULL) {
1659         con = active_console;
1660     }
1661     return con ? con->index : -1;
1662 }
1663
1664 uint32_t qemu_console_get_head(QemuConsole *con)
1665 {
1666     if (con == NULL) {
1667         con = active_console;
1668     }
1669     return con ? con->head : -1;
1670 }
1671
1672 QemuUIInfo *qemu_console_get_ui_info(QemuConsole *con)
1673 {
1674     assert(con != NULL);
1675     return &con->ui_info;
1676 }
1677
1678 int qemu_console_get_width(QemuConsole *con, int fallback)
1679 {
1680     if (con == NULL) {
1681         con = active_console;
1682     }
1683     return con ? surface_width(con->surface) : fallback;
1684 }
1685
1686 int qemu_console_get_height(QemuConsole *con, int fallback)
1687 {
1688     if (con == NULL) {
1689         con = active_console;
1690     }
1691     return con ? surface_height(con->surface) : fallback;
1692 }
1693
1694 static void text_console_set_echo(CharDriverState *chr, bool echo)
1695 {
1696     QemuConsole *s = chr->opaque;
1697
1698     s->echo = echo;
1699 }
1700
1701 static void text_console_update_cursor_timer(void)
1702 {
1703     timer_mod(cursor_timer, qemu_clock_get_ms(QEMU_CLOCK_REALTIME)
1704               + CONSOLE_CURSOR_PERIOD / 2);
1705 }
1706
1707 static void text_console_update_cursor(void *opaque)
1708 {
1709     QemuConsole *s;
1710     int i, count = 0;
1711
1712     cursor_visible_phase = !cursor_visible_phase;
1713
1714     for (i = 0; i < nb_consoles; i++) {
1715         s = consoles[i];
1716         if (qemu_console_is_graphic(s) ||
1717             !qemu_console_is_visible(s)) {
1718             continue;
1719         }
1720         count++;
1721         graphic_hw_invalidate(s);
1722     }
1723
1724     if (count) {
1725         text_console_update_cursor_timer();
1726     }
1727 }
1728
1729 static const GraphicHwOps text_console_ops = {
1730     .invalidate  = text_console_invalidate,
1731     .text_update = text_console_update,
1732 };
1733
1734 static void text_console_do_init(CharDriverState *chr, DisplayState *ds)
1735 {
1736     QemuConsole *s;
1737     int g_width = 80 * FONT_WIDTH;
1738     int g_height = 24 * FONT_HEIGHT;
1739
1740     s = chr->opaque;
1741
1742     chr->chr_write = console_puts;
1743
1744     s->out_fifo.buf = s->out_fifo_buf;
1745     s->out_fifo.buf_size = sizeof(s->out_fifo_buf);
1746     s->kbd_timer = timer_new_ms(QEMU_CLOCK_REALTIME, kbd_send_chars, s);
1747     s->ds = ds;
1748
1749     s->y_displayed = 0;
1750     s->y_base = 0;
1751     s->total_height = DEFAULT_BACKSCROLL;
1752     s->x = 0;
1753     s->y = 0;
1754     if (!s->surface) {
1755         if (active_console && active_console->surface) {
1756             g_width = surface_width(active_console->surface);
1757             g_height = surface_height(active_console->surface);
1758         }
1759         s->surface = qemu_create_displaysurface(g_width, g_height);
1760     }
1761
1762     s->hw_ops = &text_console_ops;
1763     s->hw = s;
1764
1765     /* Set text attribute defaults */
1766     s->t_attrib_default.bold = 0;
1767     s->t_attrib_default.uline = 0;
1768     s->t_attrib_default.blink = 0;
1769     s->t_attrib_default.invers = 0;
1770     s->t_attrib_default.unvisible = 0;
1771     s->t_attrib_default.fgcol = COLOR_WHITE;
1772     s->t_attrib_default.bgcol = COLOR_BLACK;
1773     /* set current text attributes to default */
1774     s->t_attrib = s->t_attrib_default;
1775     text_console_resize(s);
1776
1777     if (chr->label) {
1778         char msg[128];
1779         int len;
1780
1781         s->t_attrib.bgcol = COLOR_BLUE;
1782         len = snprintf(msg, sizeof(msg), "%s console\r\n", chr->label);
1783         console_puts(chr, (uint8_t*)msg, len);
1784         s->t_attrib = s->t_attrib_default;
1785     }
1786
1787     qemu_chr_be_generic_open(chr);
1788     if (chr->init)
1789         chr->init(chr);
1790 }
1791
1792 static CharDriverState *text_console_init(ChardevVC *vc)
1793 {
1794     CharDriverState *chr;
1795     QemuConsole *s;
1796     unsigned width = 0;
1797     unsigned height = 0;
1798
1799     chr = g_malloc0(sizeof(CharDriverState));
1800
1801     if (vc->has_width) {
1802         width = vc->width;
1803     } else if (vc->has_cols) {
1804         width = vc->cols * FONT_WIDTH;
1805     }
1806
1807     if (vc->has_height) {
1808         height = vc->height;
1809     } else if (vc->has_rows) {
1810         height = vc->rows * FONT_HEIGHT;
1811     }
1812
1813     trace_console_txt_new(width, height);
1814     if (width == 0 || height == 0) {
1815         s = new_console(NULL, TEXT_CONSOLE, 0);
1816     } else {
1817         s = new_console(NULL, TEXT_CONSOLE_FIXED_SIZE, 0);
1818         s->surface = qemu_create_displaysurface(width, height);
1819     }
1820
1821     if (!s) {
1822         g_free(chr);
1823         return NULL;
1824     }
1825
1826     s->chr = chr;
1827     chr->opaque = s;
1828     chr->chr_set_echo = text_console_set_echo;
1829     /* console/chardev init sometimes completes elsewhere in a 2nd
1830      * stage, so defer OPENED events until they are fully initialized
1831      */
1832     chr->explicit_be_open = true;
1833
1834     if (display_state) {
1835         text_console_do_init(chr, display_state);
1836     }
1837     return chr;
1838 }
1839
1840 static VcHandler *vc_handler = text_console_init;
1841
1842 CharDriverState *vc_init(ChardevVC *vc)
1843 {
1844     return vc_handler(vc);
1845 }
1846
1847 void register_vc_handler(VcHandler *handler)
1848 {
1849     vc_handler = handler;
1850 }
1851
1852 void qemu_console_resize(QemuConsole *s, int width, int height)
1853 {
1854     DisplaySurface *surface;
1855
1856     assert(s->console_type == GRAPHIC_CONSOLE);
1857     surface = qemu_create_displaysurface(width, height);
1858     dpy_gfx_replace_surface(s, surface);
1859 }
1860
1861 void qemu_console_copy(QemuConsole *con, int src_x, int src_y,
1862                        int dst_x, int dst_y, int w, int h)
1863 {
1864     assert(con->console_type == GRAPHIC_CONSOLE);
1865     dpy_gfx_copy(con, src_x, src_y, dst_x, dst_y, w, h);
1866 }
1867
1868 DisplaySurface *qemu_console_surface(QemuConsole *console)
1869 {
1870     return console->surface;
1871 }
1872
1873 DisplayState *qemu_console_displaystate(QemuConsole *console)
1874 {
1875     return console->ds;
1876 }
1877
1878 PixelFormat qemu_different_endianness_pixelformat(int bpp)
1879 {
1880     PixelFormat pf;
1881
1882     memset(&pf, 0x00, sizeof(PixelFormat));
1883
1884     pf.bits_per_pixel = bpp;
1885     pf.bytes_per_pixel = DIV_ROUND_UP(bpp, 8);
1886     pf.depth = bpp == 32 ? 24 : bpp;
1887
1888     switch (bpp) {
1889         case 24:
1890             pf.rmask = 0x000000FF;
1891             pf.gmask = 0x0000FF00;
1892             pf.bmask = 0x00FF0000;
1893             pf.rmax = 255;
1894             pf.gmax = 255;
1895             pf.bmax = 255;
1896             pf.rshift = 0;
1897             pf.gshift = 8;
1898             pf.bshift = 16;
1899             pf.rbits = 8;
1900             pf.gbits = 8;
1901             pf.bbits = 8;
1902             break;
1903         case 32:
1904             pf.rmask = 0x0000FF00;
1905             pf.gmask = 0x00FF0000;
1906             pf.bmask = 0xFF000000;
1907             pf.amask = 0x00000000;
1908             pf.amax = 255;
1909             pf.rmax = 255;
1910             pf.gmax = 255;
1911             pf.bmax = 255;
1912             pf.ashift = 0;
1913             pf.rshift = 8;
1914             pf.gshift = 16;
1915             pf.bshift = 24;
1916             pf.rbits = 8;
1917             pf.gbits = 8;
1918             pf.bbits = 8;
1919             pf.abits = 8;
1920             break;
1921         default:
1922             break;
1923     }
1924     return pf;
1925 }
1926
1927 PixelFormat qemu_default_pixelformat(int bpp)
1928 {
1929     PixelFormat pf;
1930
1931     memset(&pf, 0x00, sizeof(PixelFormat));
1932
1933     pf.bits_per_pixel = bpp;
1934     pf.bytes_per_pixel = DIV_ROUND_UP(bpp, 8);
1935     pf.depth = bpp == 32 ? 24 : bpp;
1936
1937     switch (bpp) {
1938         case 15:
1939             pf.bits_per_pixel = 16;
1940             pf.rmask = 0x00007c00;
1941             pf.gmask = 0x000003E0;
1942             pf.bmask = 0x0000001F;
1943             pf.rmax = 31;
1944             pf.gmax = 31;
1945             pf.bmax = 31;
1946             pf.rshift = 10;
1947             pf.gshift = 5;
1948             pf.bshift = 0;
1949             pf.rbits = 5;
1950             pf.gbits = 5;
1951             pf.bbits = 5;
1952             break;
1953         case 16:
1954             pf.rmask = 0x0000F800;
1955             pf.gmask = 0x000007E0;
1956             pf.bmask = 0x0000001F;
1957             pf.rmax = 31;
1958             pf.gmax = 63;
1959             pf.bmax = 31;
1960             pf.rshift = 11;
1961             pf.gshift = 5;
1962             pf.bshift = 0;
1963             pf.rbits = 5;
1964             pf.gbits = 6;
1965             pf.bbits = 5;
1966             break;
1967         case 24:
1968             pf.rmask = 0x00FF0000;
1969             pf.gmask = 0x0000FF00;
1970             pf.bmask = 0x000000FF;
1971             pf.rmax = 255;
1972             pf.gmax = 255;
1973             pf.bmax = 255;
1974             pf.rshift = 16;
1975             pf.gshift = 8;
1976             pf.bshift = 0;
1977             pf.rbits = 8;
1978             pf.gbits = 8;
1979             pf.bbits = 8;
1980             break;
1981         case 32:
1982             pf.rmask = 0x00FF0000;
1983             pf.gmask = 0x0000FF00;
1984             pf.bmask = 0x000000FF;
1985             pf.rmax = 255;
1986             pf.gmax = 255;
1987             pf.bmax = 255;
1988             pf.rshift = 16;
1989             pf.gshift = 8;
1990             pf.bshift = 0;
1991             pf.rbits = 8;
1992             pf.gbits = 8;
1993             pf.bbits = 8;
1994             break;
1995         default:
1996             break;
1997     }
1998     return pf;
1999 }
2000
2001 static void qemu_chr_parse_vc(QemuOpts *opts, ChardevBackend *backend,
2002                               Error **errp)
2003 {
2004     int val;
2005
2006     backend->vc = g_new0(ChardevVC, 1);
2007
2008     val = qemu_opt_get_number(opts, "width", 0);
2009     if (val != 0) {
2010         backend->vc->has_width = true;
2011         backend->vc->width = val;
2012     }
2013
2014     val = qemu_opt_get_number(opts, "height", 0);
2015     if (val != 0) {
2016         backend->vc->has_height = true;
2017         backend->vc->height = val;
2018     }
2019
2020     val = qemu_opt_get_number(opts, "cols", 0);
2021     if (val != 0) {
2022         backend->vc->has_cols = true;
2023         backend->vc->cols = val;
2024     }
2025
2026     val = qemu_opt_get_number(opts, "rows", 0);
2027     if (val != 0) {
2028         backend->vc->has_rows = true;
2029         backend->vc->rows = val;
2030     }
2031 }
2032
2033 static const TypeInfo qemu_console_info = {
2034     .name = TYPE_QEMU_CONSOLE,
2035     .parent = TYPE_OBJECT,
2036     .instance_size = sizeof(QemuConsole),
2037     .class_size = sizeof(QemuConsoleClass),
2038 };
2039
2040
2041 static void register_types(void)
2042 {
2043     type_register_static(&qemu_console_info);
2044     register_char_driver_qapi("vc", CHARDEV_BACKEND_KIND_VC,
2045                               qemu_chr_parse_vc);
2046 }
2047
2048 type_init(register_types);