xref: /qemu/ui/console.c (revision e3a6e0da)
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 
25 #include "qemu/osdep.h"
26 #include "ui/console.h"
27 #include "hw/qdev-core.h"
28 #include "qapi/error.h"
29 #include "qapi/qapi-commands-ui.h"
30 #include "qemu/module.h"
31 #include "qemu/option.h"
32 #include "qemu/timer.h"
33 #include "chardev/char-fe.h"
34 #include "trace.h"
35 #include "exec/memory.h"
36 #include "io/channel-file.h"
37 #include "qom/object.h"
38 
39 #define DEFAULT_BACKSCROLL 512
40 #define CONSOLE_CURSOR_PERIOD 500
41 
42 typedef struct TextAttributes {
43     uint8_t fgcol:4;
44     uint8_t bgcol:4;
45     uint8_t bold:1;
46     uint8_t uline:1;
47     uint8_t blink:1;
48     uint8_t invers:1;
49     uint8_t unvisible:1;
50 } TextAttributes;
51 
52 typedef struct TextCell {
53     uint8_t ch;
54     TextAttributes t_attrib;
55 } TextCell;
56 
57 #define MAX_ESC_PARAMS 3
58 
59 enum TTYState {
60     TTY_STATE_NORM,
61     TTY_STATE_ESC,
62     TTY_STATE_CSI,
63 };
64 
65 typedef struct QEMUFIFO {
66     uint8_t *buf;
67     int buf_size;
68     int count, wptr, rptr;
69 } QEMUFIFO;
70 
71 static int qemu_fifo_write(QEMUFIFO *f, const uint8_t *buf, int len1)
72 {
73     int l, len;
74 
75     l = f->buf_size - f->count;
76     if (len1 > l)
77         len1 = l;
78     len = len1;
79     while (len > 0) {
80         l = f->buf_size - f->wptr;
81         if (l > len)
82             l = len;
83         memcpy(f->buf + f->wptr, buf, l);
84         f->wptr += l;
85         if (f->wptr >= f->buf_size)
86             f->wptr = 0;
87         buf += l;
88         len -= l;
89     }
90     f->count += len1;
91     return len1;
92 }
93 
94 static int qemu_fifo_read(QEMUFIFO *f, uint8_t *buf, int len1)
95 {
96     int l, len;
97 
98     if (len1 > f->count)
99         len1 = f->count;
100     len = len1;
101     while (len > 0) {
102         l = f->buf_size - f->rptr;
103         if (l > len)
104             l = len;
105         memcpy(buf, f->buf + f->rptr, l);
106         f->rptr += l;
107         if (f->rptr >= f->buf_size)
108             f->rptr = 0;
109         buf += l;
110         len -= l;
111     }
112     f->count -= len1;
113     return len1;
114 }
115 
116 typedef enum {
117     GRAPHIC_CONSOLE,
118     TEXT_CONSOLE,
119     TEXT_CONSOLE_FIXED_SIZE
120 } console_type_t;
121 
122 struct QemuConsole {
123     Object parent;
124 
125     int index;
126     console_type_t console_type;
127     DisplayState *ds;
128     DisplaySurface *surface;
129     int dcls;
130     DisplayChangeListener *gl;
131     bool gl_block;
132     int window_id;
133 
134     /* Graphic console state.  */
135     Object *device;
136     uint32_t head;
137     QemuUIInfo ui_info;
138     QEMUTimer *ui_timer;
139     const GraphicHwOps *hw_ops;
140     void *hw;
141 
142     /* Text console state */
143     int width;
144     int height;
145     int total_height;
146     int backscroll_height;
147     int x, y;
148     int x_saved, y_saved;
149     int y_displayed;
150     int y_base;
151     TextAttributes t_attrib_default; /* default text attributes */
152     TextAttributes t_attrib; /* currently active text attributes */
153     TextCell *cells;
154     int text_x[2], text_y[2], cursor_invalidate;
155     int echo;
156 
157     int update_x0;
158     int update_y0;
159     int update_x1;
160     int update_y1;
161 
162     enum TTYState state;
163     int esc_params[MAX_ESC_PARAMS];
164     int nb_esc_params;
165 
166     Chardev *chr;
167     /* fifo for key pressed */
168     QEMUFIFO out_fifo;
169     uint8_t out_fifo_buf[16];
170     QEMUTimer *kbd_timer;
171 
172     QTAILQ_ENTRY(QemuConsole) next;
173 };
174 
175 struct DisplayState {
176     QEMUTimer *gui_timer;
177     uint64_t last_update;
178     uint64_t update_interval;
179     bool refreshing;
180     bool have_gfx;
181     bool have_text;
182 
183     QLIST_HEAD(, DisplayChangeListener) listeners;
184 };
185 
186 static DisplayState *display_state;
187 static QemuConsole *active_console;
188 static QTAILQ_HEAD(, QemuConsole) consoles =
189     QTAILQ_HEAD_INITIALIZER(consoles);
190 static bool cursor_visible_phase;
191 static QEMUTimer *cursor_timer;
192 
193 static void text_console_do_init(Chardev *chr, DisplayState *ds);
194 static void dpy_refresh(DisplayState *s);
195 static DisplayState *get_alloc_displaystate(void);
196 static void text_console_update_cursor_timer(void);
197 static void text_console_update_cursor(void *opaque);
198 static bool ppm_save(int fd, DisplaySurface *ds, Error **errp);
199 
200 static void gui_update(void *opaque)
201 {
202     uint64_t interval = GUI_REFRESH_INTERVAL_IDLE;
203     uint64_t dcl_interval;
204     DisplayState *ds = opaque;
205     DisplayChangeListener *dcl;
206     QemuConsole *con;
207 
208     ds->refreshing = true;
209     dpy_refresh(ds);
210     ds->refreshing = false;
211 
212     QLIST_FOREACH(dcl, &ds->listeners, next) {
213         dcl_interval = dcl->update_interval ?
214             dcl->update_interval : GUI_REFRESH_INTERVAL_DEFAULT;
215         if (interval > dcl_interval) {
216             interval = dcl_interval;
217         }
218     }
219     if (ds->update_interval != interval) {
220         ds->update_interval = interval;
221         QTAILQ_FOREACH(con, &consoles, next) {
222             if (con->hw_ops->update_interval) {
223                 con->hw_ops->update_interval(con->hw, interval);
224             }
225         }
226         trace_console_refresh(interval);
227     }
228     ds->last_update = qemu_clock_get_ms(QEMU_CLOCK_REALTIME);
229     timer_mod(ds->gui_timer, ds->last_update + interval);
230 }
231 
232 static void gui_setup_refresh(DisplayState *ds)
233 {
234     DisplayChangeListener *dcl;
235     bool need_timer = false;
236     bool have_gfx = false;
237     bool have_text = false;
238 
239     QLIST_FOREACH(dcl, &ds->listeners, next) {
240         if (dcl->ops->dpy_refresh != NULL) {
241             need_timer = true;
242         }
243         if (dcl->ops->dpy_gfx_update != NULL) {
244             have_gfx = true;
245         }
246         if (dcl->ops->dpy_text_update != NULL) {
247             have_text = true;
248         }
249     }
250 
251     if (need_timer && ds->gui_timer == NULL) {
252         ds->gui_timer = timer_new_ms(QEMU_CLOCK_REALTIME, gui_update, ds);
253         timer_mod(ds->gui_timer, qemu_clock_get_ms(QEMU_CLOCK_REALTIME));
254     }
255     if (!need_timer && ds->gui_timer != NULL) {
256         timer_del(ds->gui_timer);
257         timer_free(ds->gui_timer);
258         ds->gui_timer = NULL;
259     }
260 
261     ds->have_gfx = have_gfx;
262     ds->have_text = have_text;
263 }
264 
265 void graphic_hw_update_done(QemuConsole *con)
266 {
267 }
268 
269 void graphic_hw_update(QemuConsole *con)
270 {
271     bool async = false;
272     if (!con) {
273         con = active_console;
274     }
275     if (con && con->hw_ops->gfx_update) {
276         con->hw_ops->gfx_update(con->hw);
277         async = con->hw_ops->gfx_update_async;
278     }
279     if (!async) {
280         graphic_hw_update_done(con);
281     }
282 }
283 
284 void graphic_hw_gl_block(QemuConsole *con, bool block)
285 {
286     assert(con != NULL);
287 
288     con->gl_block = block;
289     if (con->hw_ops->gl_block) {
290         con->hw_ops->gl_block(con->hw, block);
291     }
292 }
293 
294 int qemu_console_get_window_id(QemuConsole *con)
295 {
296     return con->window_id;
297 }
298 
299 void qemu_console_set_window_id(QemuConsole *con, int window_id)
300 {
301     con->window_id = window_id;
302 }
303 
304 void graphic_hw_invalidate(QemuConsole *con)
305 {
306     if (!con) {
307         con = active_console;
308     }
309     if (con && con->hw_ops->invalidate) {
310         con->hw_ops->invalidate(con->hw);
311     }
312 }
313 
314 static bool ppm_save(int fd, DisplaySurface *ds, Error **errp)
315 {
316     int width = pixman_image_get_width(ds->image);
317     int height = pixman_image_get_height(ds->image);
318     g_autoptr(Object) ioc = OBJECT(qio_channel_file_new_fd(fd));
319     g_autofree char *header = NULL;
320     g_autoptr(pixman_image_t) linebuf = NULL;
321     int y;
322 
323     trace_ppm_save(fd, ds);
324 
325     header = g_strdup_printf("P6\n%d %d\n%d\n", width, height, 255);
326     if (qio_channel_write_all(QIO_CHANNEL(ioc),
327                               header, strlen(header), errp) < 0) {
328         return false;
329     }
330 
331     linebuf = qemu_pixman_linebuf_create(PIXMAN_BE_r8g8b8, width);
332     for (y = 0; y < height; y++) {
333         qemu_pixman_linebuf_fill(linebuf, ds->image, width, 0, y);
334         if (qio_channel_write_all(QIO_CHANNEL(ioc),
335                                   (char *)pixman_image_get_data(linebuf),
336                                   pixman_image_get_stride(linebuf), errp) < 0) {
337             return false;
338         }
339     }
340 
341     return true;
342 }
343 
344 void qmp_screendump(const char *filename, bool has_device, const char *device,
345                     bool has_head, int64_t head, Error **errp)
346 {
347     QemuConsole *con;
348     DisplaySurface *surface;
349     int fd;
350 
351     if (has_device) {
352         con = qemu_console_lookup_by_device_name(device, has_head ? head : 0,
353                                                  errp);
354         if (!con) {
355             return;
356         }
357     } else {
358         if (has_head) {
359             error_setg(errp, "'head' must be specified together with 'device'");
360             return;
361         }
362         con = qemu_console_lookup_by_index(0);
363         if (!con) {
364             error_setg(errp, "There is no console to take a screendump from");
365             return;
366         }
367     }
368 
369     graphic_hw_update(con);
370     surface = qemu_console_surface(con);
371     if (!surface) {
372         error_setg(errp, "no surface");
373         return;
374     }
375 
376     fd = qemu_open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0666);
377     if (fd == -1) {
378         error_setg(errp, "failed to open file '%s': %s", filename,
379                    strerror(errno));
380         return;
381     }
382 
383     if (!ppm_save(fd, surface, errp)) {
384         qemu_unlink(filename);
385     }
386 }
387 
388 void graphic_hw_text_update(QemuConsole *con, console_ch_t *chardata)
389 {
390     if (!con) {
391         con = active_console;
392     }
393     if (con && con->hw_ops->text_update) {
394         con->hw_ops->text_update(con->hw, chardata);
395     }
396 }
397 
398 static void vga_fill_rect(QemuConsole *con,
399                           int posx, int posy, int width, int height,
400                           pixman_color_t color)
401 {
402     DisplaySurface *surface = qemu_console_surface(con);
403     pixman_rectangle16_t rect = {
404         .x = posx, .y = posy, .width = width, .height = height
405     };
406 
407     pixman_image_fill_rectangles(PIXMAN_OP_SRC, surface->image,
408                                  &color, 1, &rect);
409 }
410 
411 /* copy from (xs, ys) to (xd, yd) a rectangle of size (w, h) */
412 static void vga_bitblt(QemuConsole *con,
413                        int xs, int ys, int xd, int yd, int w, int h)
414 {
415     DisplaySurface *surface = qemu_console_surface(con);
416 
417     pixman_image_composite(PIXMAN_OP_SRC,
418                            surface->image, NULL, surface->image,
419                            xs, ys, 0, 0, xd, yd, w, h);
420 }
421 
422 /***********************************************************/
423 /* basic char display */
424 
425 #define FONT_HEIGHT 16
426 #define FONT_WIDTH 8
427 
428 #include "vgafont.h"
429 
430 #define QEMU_RGB(r, g, b)                                               \
431     { .red = r << 8, .green = g << 8, .blue = b << 8, .alpha = 0xffff }
432 
433 static const pixman_color_t color_table_rgb[2][8] = {
434     {   /* dark */
435         [QEMU_COLOR_BLACK]   = QEMU_RGB(0x00, 0x00, 0x00),  /* black */
436         [QEMU_COLOR_BLUE]    = QEMU_RGB(0x00, 0x00, 0xaa),  /* blue */
437         [QEMU_COLOR_GREEN]   = QEMU_RGB(0x00, 0xaa, 0x00),  /* green */
438         [QEMU_COLOR_CYAN]    = QEMU_RGB(0x00, 0xaa, 0xaa),  /* cyan */
439         [QEMU_COLOR_RED]     = QEMU_RGB(0xaa, 0x00, 0x00),  /* red */
440         [QEMU_COLOR_MAGENTA] = QEMU_RGB(0xaa, 0x00, 0xaa),  /* magenta */
441         [QEMU_COLOR_YELLOW]  = QEMU_RGB(0xaa, 0xaa, 0x00),  /* yellow */
442         [QEMU_COLOR_WHITE]   = QEMU_RGB(0xaa, 0xaa, 0xaa),  /* white */
443     },
444     {   /* bright */
445         [QEMU_COLOR_BLACK]   = QEMU_RGB(0x00, 0x00, 0x00),  /* black */
446         [QEMU_COLOR_BLUE]    = QEMU_RGB(0x00, 0x00, 0xff),  /* blue */
447         [QEMU_COLOR_GREEN]   = QEMU_RGB(0x00, 0xff, 0x00),  /* green */
448         [QEMU_COLOR_CYAN]    = QEMU_RGB(0x00, 0xff, 0xff),  /* cyan */
449         [QEMU_COLOR_RED]     = QEMU_RGB(0xff, 0x00, 0x00),  /* red */
450         [QEMU_COLOR_MAGENTA] = QEMU_RGB(0xff, 0x00, 0xff),  /* magenta */
451         [QEMU_COLOR_YELLOW]  = QEMU_RGB(0xff, 0xff, 0x00),  /* yellow */
452         [QEMU_COLOR_WHITE]   = QEMU_RGB(0xff, 0xff, 0xff),  /* white */
453     }
454 };
455 
456 static void vga_putcharxy(QemuConsole *s, int x, int y, int ch,
457                           TextAttributes *t_attrib)
458 {
459     static pixman_image_t *glyphs[256];
460     DisplaySurface *surface = qemu_console_surface(s);
461     pixman_color_t fgcol, bgcol;
462 
463     if (t_attrib->invers) {
464         bgcol = color_table_rgb[t_attrib->bold][t_attrib->fgcol];
465         fgcol = color_table_rgb[t_attrib->bold][t_attrib->bgcol];
466     } else {
467         fgcol = color_table_rgb[t_attrib->bold][t_attrib->fgcol];
468         bgcol = color_table_rgb[t_attrib->bold][t_attrib->bgcol];
469     }
470 
471     if (!glyphs[ch]) {
472         glyphs[ch] = qemu_pixman_glyph_from_vgafont(FONT_HEIGHT, vgafont16, ch);
473     }
474     qemu_pixman_glyph_render(glyphs[ch], surface->image,
475                              &fgcol, &bgcol, x, y, FONT_WIDTH, FONT_HEIGHT);
476 }
477 
478 static void text_console_resize(QemuConsole *s)
479 {
480     TextCell *cells, *c, *c1;
481     int w1, x, y, last_width;
482 
483     last_width = s->width;
484     s->width = surface_width(s->surface) / FONT_WIDTH;
485     s->height = surface_height(s->surface) / FONT_HEIGHT;
486 
487     w1 = last_width;
488     if (s->width < w1)
489         w1 = s->width;
490 
491     cells = g_new(TextCell, s->width * s->total_height + 1);
492     for(y = 0; y < s->total_height; y++) {
493         c = &cells[y * s->width];
494         if (w1 > 0) {
495             c1 = &s->cells[y * last_width];
496             for(x = 0; x < w1; x++) {
497                 *c++ = *c1++;
498             }
499         }
500         for(x = w1; x < s->width; x++) {
501             c->ch = ' ';
502             c->t_attrib = s->t_attrib_default;
503             c++;
504         }
505     }
506     g_free(s->cells);
507     s->cells = cells;
508 }
509 
510 static inline void text_update_xy(QemuConsole *s, int x, int y)
511 {
512     s->text_x[0] = MIN(s->text_x[0], x);
513     s->text_x[1] = MAX(s->text_x[1], x);
514     s->text_y[0] = MIN(s->text_y[0], y);
515     s->text_y[1] = MAX(s->text_y[1], y);
516 }
517 
518 static void invalidate_xy(QemuConsole *s, int x, int y)
519 {
520     if (!qemu_console_is_visible(s)) {
521         return;
522     }
523     if (s->update_x0 > x * FONT_WIDTH)
524         s->update_x0 = x * FONT_WIDTH;
525     if (s->update_y0 > y * FONT_HEIGHT)
526         s->update_y0 = y * FONT_HEIGHT;
527     if (s->update_x1 < (x + 1) * FONT_WIDTH)
528         s->update_x1 = (x + 1) * FONT_WIDTH;
529     if (s->update_y1 < (y + 1) * FONT_HEIGHT)
530         s->update_y1 = (y + 1) * FONT_HEIGHT;
531 }
532 
533 static void update_xy(QemuConsole *s, int x, int y)
534 {
535     TextCell *c;
536     int y1, y2;
537 
538     if (s->ds->have_text) {
539         text_update_xy(s, x, y);
540     }
541 
542     y1 = (s->y_base + y) % s->total_height;
543     y2 = y1 - s->y_displayed;
544     if (y2 < 0) {
545         y2 += s->total_height;
546     }
547     if (y2 < s->height) {
548         if (x >= s->width) {
549             x = s->width - 1;
550         }
551         c = &s->cells[y1 * s->width + x];
552         vga_putcharxy(s, x, y2, c->ch,
553                       &(c->t_attrib));
554         invalidate_xy(s, x, y2);
555     }
556 }
557 
558 static void console_show_cursor(QemuConsole *s, int show)
559 {
560     TextCell *c;
561     int y, y1;
562     int x = s->x;
563 
564     if (s->ds->have_text) {
565         s->cursor_invalidate = 1;
566     }
567 
568     if (x >= s->width) {
569         x = s->width - 1;
570     }
571     y1 = (s->y_base + s->y) % s->total_height;
572     y = y1 - s->y_displayed;
573     if (y < 0) {
574         y += s->total_height;
575     }
576     if (y < s->height) {
577         c = &s->cells[y1 * s->width + x];
578         if (show && cursor_visible_phase) {
579             TextAttributes t_attrib = s->t_attrib_default;
580             t_attrib.invers = !(t_attrib.invers); /* invert fg and bg */
581             vga_putcharxy(s, x, y, c->ch, &t_attrib);
582         } else {
583             vga_putcharxy(s, x, y, c->ch, &(c->t_attrib));
584         }
585         invalidate_xy(s, x, y);
586     }
587 }
588 
589 static void console_refresh(QemuConsole *s)
590 {
591     DisplaySurface *surface = qemu_console_surface(s);
592     TextCell *c;
593     int x, y, y1;
594 
595     if (s->ds->have_text) {
596         s->text_x[0] = 0;
597         s->text_y[0] = 0;
598         s->text_x[1] = s->width - 1;
599         s->text_y[1] = s->height - 1;
600         s->cursor_invalidate = 1;
601     }
602 
603     vga_fill_rect(s, 0, 0, surface_width(surface), surface_height(surface),
604                   color_table_rgb[0][QEMU_COLOR_BLACK]);
605     y1 = s->y_displayed;
606     for (y = 0; y < s->height; y++) {
607         c = s->cells + y1 * s->width;
608         for (x = 0; x < s->width; x++) {
609             vga_putcharxy(s, x, y, c->ch,
610                           &(c->t_attrib));
611             c++;
612         }
613         if (++y1 == s->total_height) {
614             y1 = 0;
615         }
616     }
617     console_show_cursor(s, 1);
618     dpy_gfx_update(s, 0, 0,
619                    surface_width(surface), surface_height(surface));
620 }
621 
622 static void console_scroll(QemuConsole *s, int ydelta)
623 {
624     int i, y1;
625 
626     if (ydelta > 0) {
627         for(i = 0; i < ydelta; i++) {
628             if (s->y_displayed == s->y_base)
629                 break;
630             if (++s->y_displayed == s->total_height)
631                 s->y_displayed = 0;
632         }
633     } else {
634         ydelta = -ydelta;
635         i = s->backscroll_height;
636         if (i > s->total_height - s->height)
637             i = s->total_height - s->height;
638         y1 = s->y_base - i;
639         if (y1 < 0)
640             y1 += s->total_height;
641         for(i = 0; i < ydelta; i++) {
642             if (s->y_displayed == y1)
643                 break;
644             if (--s->y_displayed < 0)
645                 s->y_displayed = s->total_height - 1;
646         }
647     }
648     console_refresh(s);
649 }
650 
651 static void console_put_lf(QemuConsole *s)
652 {
653     TextCell *c;
654     int x, y1;
655 
656     s->y++;
657     if (s->y >= s->height) {
658         s->y = s->height - 1;
659 
660         if (s->y_displayed == s->y_base) {
661             if (++s->y_displayed == s->total_height)
662                 s->y_displayed = 0;
663         }
664         if (++s->y_base == s->total_height)
665             s->y_base = 0;
666         if (s->backscroll_height < s->total_height)
667             s->backscroll_height++;
668         y1 = (s->y_base + s->height - 1) % s->total_height;
669         c = &s->cells[y1 * s->width];
670         for(x = 0; x < s->width; x++) {
671             c->ch = ' ';
672             c->t_attrib = s->t_attrib_default;
673             c++;
674         }
675         if (s->y_displayed == s->y_base) {
676             if (s->ds->have_text) {
677                 s->text_x[0] = 0;
678                 s->text_y[0] = 0;
679                 s->text_x[1] = s->width - 1;
680                 s->text_y[1] = s->height - 1;
681             }
682 
683             vga_bitblt(s, 0, FONT_HEIGHT, 0, 0,
684                        s->width * FONT_WIDTH,
685                        (s->height - 1) * FONT_HEIGHT);
686             vga_fill_rect(s, 0, (s->height - 1) * FONT_HEIGHT,
687                           s->width * FONT_WIDTH, FONT_HEIGHT,
688                           color_table_rgb[0][s->t_attrib_default.bgcol]);
689             s->update_x0 = 0;
690             s->update_y0 = 0;
691             s->update_x1 = s->width * FONT_WIDTH;
692             s->update_y1 = s->height * FONT_HEIGHT;
693         }
694     }
695 }
696 
697 /* Set console attributes depending on the current escape codes.
698  * NOTE: I know this code is not very efficient (checking every color for it
699  * self) but it is more readable and better maintainable.
700  */
701 static void console_handle_escape(QemuConsole *s)
702 {
703     int i;
704 
705     for (i=0; i<s->nb_esc_params; i++) {
706         switch (s->esc_params[i]) {
707             case 0: /* reset all console attributes to default */
708                 s->t_attrib = s->t_attrib_default;
709                 break;
710             case 1:
711                 s->t_attrib.bold = 1;
712                 break;
713             case 4:
714                 s->t_attrib.uline = 1;
715                 break;
716             case 5:
717                 s->t_attrib.blink = 1;
718                 break;
719             case 7:
720                 s->t_attrib.invers = 1;
721                 break;
722             case 8:
723                 s->t_attrib.unvisible = 1;
724                 break;
725             case 22:
726                 s->t_attrib.bold = 0;
727                 break;
728             case 24:
729                 s->t_attrib.uline = 0;
730                 break;
731             case 25:
732                 s->t_attrib.blink = 0;
733                 break;
734             case 27:
735                 s->t_attrib.invers = 0;
736                 break;
737             case 28:
738                 s->t_attrib.unvisible = 0;
739                 break;
740             /* set foreground color */
741             case 30:
742                 s->t_attrib.fgcol = QEMU_COLOR_BLACK;
743                 break;
744             case 31:
745                 s->t_attrib.fgcol = QEMU_COLOR_RED;
746                 break;
747             case 32:
748                 s->t_attrib.fgcol = QEMU_COLOR_GREEN;
749                 break;
750             case 33:
751                 s->t_attrib.fgcol = QEMU_COLOR_YELLOW;
752                 break;
753             case 34:
754                 s->t_attrib.fgcol = QEMU_COLOR_BLUE;
755                 break;
756             case 35:
757                 s->t_attrib.fgcol = QEMU_COLOR_MAGENTA;
758                 break;
759             case 36:
760                 s->t_attrib.fgcol = QEMU_COLOR_CYAN;
761                 break;
762             case 37:
763                 s->t_attrib.fgcol = QEMU_COLOR_WHITE;
764                 break;
765             /* set background color */
766             case 40:
767                 s->t_attrib.bgcol = QEMU_COLOR_BLACK;
768                 break;
769             case 41:
770                 s->t_attrib.bgcol = QEMU_COLOR_RED;
771                 break;
772             case 42:
773                 s->t_attrib.bgcol = QEMU_COLOR_GREEN;
774                 break;
775             case 43:
776                 s->t_attrib.bgcol = QEMU_COLOR_YELLOW;
777                 break;
778             case 44:
779                 s->t_attrib.bgcol = QEMU_COLOR_BLUE;
780                 break;
781             case 45:
782                 s->t_attrib.bgcol = QEMU_COLOR_MAGENTA;
783                 break;
784             case 46:
785                 s->t_attrib.bgcol = QEMU_COLOR_CYAN;
786                 break;
787             case 47:
788                 s->t_attrib.bgcol = QEMU_COLOR_WHITE;
789                 break;
790         }
791     }
792 }
793 
794 static void console_clear_xy(QemuConsole *s, int x, int y)
795 {
796     int y1 = (s->y_base + y) % s->total_height;
797     if (x >= s->width) {
798         x = s->width - 1;
799     }
800     TextCell *c = &s->cells[y1 * s->width + x];
801     c->ch = ' ';
802     c->t_attrib = s->t_attrib_default;
803     update_xy(s, x, y);
804 }
805 
806 static void console_put_one(QemuConsole *s, int ch)
807 {
808     TextCell *c;
809     int y1;
810     if (s->x >= s->width) {
811         /* line wrap */
812         s->x = 0;
813         console_put_lf(s);
814     }
815     y1 = (s->y_base + s->y) % s->total_height;
816     c = &s->cells[y1 * s->width + s->x];
817     c->ch = ch;
818     c->t_attrib = s->t_attrib;
819     update_xy(s, s->x, s->y);
820     s->x++;
821 }
822 
823 static void console_respond_str(QemuConsole *s, const char *buf)
824 {
825     while (*buf) {
826         console_put_one(s, *buf);
827         buf++;
828     }
829 }
830 
831 /* set cursor, checking bounds */
832 static void set_cursor(QemuConsole *s, int x, int y)
833 {
834     if (x < 0) {
835         x = 0;
836     }
837     if (y < 0) {
838         y = 0;
839     }
840     if (y >= s->height) {
841         y = s->height - 1;
842     }
843     if (x >= s->width) {
844         x = s->width - 1;
845     }
846 
847     s->x = x;
848     s->y = y;
849 }
850 
851 static void console_putchar(QemuConsole *s, int ch)
852 {
853     int i;
854     int x, y;
855     char response[40];
856 
857     switch(s->state) {
858     case TTY_STATE_NORM:
859         switch(ch) {
860         case '\r':  /* carriage return */
861             s->x = 0;
862             break;
863         case '\n':  /* newline */
864             console_put_lf(s);
865             break;
866         case '\b':  /* backspace */
867             if (s->x > 0)
868                 s->x--;
869             break;
870         case '\t':  /* tabspace */
871             if (s->x + (8 - (s->x % 8)) > s->width) {
872                 s->x = 0;
873                 console_put_lf(s);
874             } else {
875                 s->x = s->x + (8 - (s->x % 8));
876             }
877             break;
878         case '\a':  /* alert aka. bell */
879             /* TODO: has to be implemented */
880             break;
881         case 14:
882             /* SI (shift in), character set 0 (ignored) */
883             break;
884         case 15:
885             /* SO (shift out), character set 1 (ignored) */
886             break;
887         case 27:    /* esc (introducing an escape sequence) */
888             s->state = TTY_STATE_ESC;
889             break;
890         default:
891             console_put_one(s, ch);
892             break;
893         }
894         break;
895     case TTY_STATE_ESC: /* check if it is a terminal escape sequence */
896         if (ch == '[') {
897             for(i=0;i<MAX_ESC_PARAMS;i++)
898                 s->esc_params[i] = 0;
899             s->nb_esc_params = 0;
900             s->state = TTY_STATE_CSI;
901         } else {
902             s->state = TTY_STATE_NORM;
903         }
904         break;
905     case TTY_STATE_CSI: /* handle escape sequence parameters */
906         if (ch >= '0' && ch <= '9') {
907             if (s->nb_esc_params < MAX_ESC_PARAMS) {
908                 int *param = &s->esc_params[s->nb_esc_params];
909                 int digit = (ch - '0');
910 
911                 *param = (*param <= (INT_MAX - digit) / 10) ?
912                          *param * 10 + digit : INT_MAX;
913             }
914         } else {
915             if (s->nb_esc_params < MAX_ESC_PARAMS)
916                 s->nb_esc_params++;
917             if (ch == ';' || ch == '?') {
918                 break;
919             }
920             trace_console_putchar_csi(s->esc_params[0], s->esc_params[1],
921                                       ch, s->nb_esc_params);
922             s->state = TTY_STATE_NORM;
923             switch(ch) {
924             case 'A':
925                 /* move cursor up */
926                 if (s->esc_params[0] == 0) {
927                     s->esc_params[0] = 1;
928                 }
929                 set_cursor(s, s->x, s->y - s->esc_params[0]);
930                 break;
931             case 'B':
932                 /* move cursor down */
933                 if (s->esc_params[0] == 0) {
934                     s->esc_params[0] = 1;
935                 }
936                 set_cursor(s, s->x, s->y + s->esc_params[0]);
937                 break;
938             case 'C':
939                 /* move cursor right */
940                 if (s->esc_params[0] == 0) {
941                     s->esc_params[0] = 1;
942                 }
943                 set_cursor(s, s->x + s->esc_params[0], s->y);
944                 break;
945             case 'D':
946                 /* move cursor left */
947                 if (s->esc_params[0] == 0) {
948                     s->esc_params[0] = 1;
949                 }
950                 set_cursor(s, s->x - s->esc_params[0], s->y);
951                 break;
952             case 'G':
953                 /* move cursor to column */
954                 set_cursor(s, s->esc_params[0] - 1, s->y);
955                 break;
956             case 'f':
957             case 'H':
958                 /* move cursor to row, column */
959                 set_cursor(s, s->esc_params[1] - 1, s->esc_params[0] - 1);
960                 break;
961             case 'J':
962                 switch (s->esc_params[0]) {
963                 case 0:
964                     /* clear to end of screen */
965                     for (y = s->y; y < s->height; y++) {
966                         for (x = 0; x < s->width; x++) {
967                             if (y == s->y && x < s->x) {
968                                 continue;
969                             }
970                             console_clear_xy(s, x, y);
971                         }
972                     }
973                     break;
974                 case 1:
975                     /* clear from beginning of screen */
976                     for (y = 0; y <= s->y; y++) {
977                         for (x = 0; x < s->width; x++) {
978                             if (y == s->y && x > s->x) {
979                                 break;
980                             }
981                             console_clear_xy(s, x, y);
982                         }
983                     }
984                     break;
985                 case 2:
986                     /* clear entire screen */
987                     for (y = 0; y <= s->height; y++) {
988                         for (x = 0; x < s->width; x++) {
989                             console_clear_xy(s, x, y);
990                         }
991                     }
992                     break;
993                 }
994                 break;
995             case 'K':
996                 switch (s->esc_params[0]) {
997                 case 0:
998                     /* clear to eol */
999                     for(x = s->x; x < s->width; x++) {
1000                         console_clear_xy(s, x, s->y);
1001                     }
1002                     break;
1003                 case 1:
1004                     /* clear from beginning of line */
1005                     for (x = 0; x <= s->x && x < s->width; x++) {
1006                         console_clear_xy(s, x, s->y);
1007                     }
1008                     break;
1009                 case 2:
1010                     /* clear entire line */
1011                     for(x = 0; x < s->width; x++) {
1012                         console_clear_xy(s, x, s->y);
1013                     }
1014                     break;
1015                 }
1016                 break;
1017             case 'm':
1018                 console_handle_escape(s);
1019                 break;
1020             case 'n':
1021                 switch (s->esc_params[0]) {
1022                 case 5:
1023                     /* report console status (always succeed)*/
1024                     console_respond_str(s, "\033[0n");
1025                     break;
1026                 case 6:
1027                     /* report cursor position */
1028                     sprintf(response, "\033[%d;%dR",
1029                            (s->y_base + s->y) % s->total_height + 1,
1030                             s->x + 1);
1031                     console_respond_str(s, response);
1032                     break;
1033                 }
1034                 break;
1035             case 's':
1036                 /* save cursor position */
1037                 s->x_saved = s->x;
1038                 s->y_saved = s->y;
1039                 break;
1040             case 'u':
1041                 /* restore cursor position */
1042                 s->x = s->x_saved;
1043                 s->y = s->y_saved;
1044                 break;
1045             default:
1046                 trace_console_putchar_unhandled(ch);
1047                 break;
1048             }
1049             break;
1050         }
1051     }
1052 }
1053 
1054 void console_select(unsigned int index)
1055 {
1056     DisplayChangeListener *dcl;
1057     QemuConsole *s;
1058 
1059     trace_console_select(index);
1060     s = qemu_console_lookup_by_index(index);
1061     if (s) {
1062         DisplayState *ds = s->ds;
1063 
1064         active_console = s;
1065         if (ds->have_gfx) {
1066             QLIST_FOREACH(dcl, &ds->listeners, next) {
1067                 if (dcl->con != NULL) {
1068                     continue;
1069                 }
1070                 if (dcl->ops->dpy_gfx_switch) {
1071                     dcl->ops->dpy_gfx_switch(dcl, s->surface);
1072                 }
1073             }
1074             if (s->surface) {
1075                 dpy_gfx_update(s, 0, 0, surface_width(s->surface),
1076                                surface_height(s->surface));
1077             }
1078         }
1079         if (ds->have_text) {
1080             dpy_text_resize(s, s->width, s->height);
1081         }
1082         text_console_update_cursor(NULL);
1083     }
1084 }
1085 
1086 struct VCChardev {
1087     Chardev parent;
1088     QemuConsole *console;
1089 };
1090 typedef struct VCChardev VCChardev;
1091 
1092 #define TYPE_CHARDEV_VC "chardev-vc"
1093 DECLARE_INSTANCE_CHECKER(VCChardev, VC_CHARDEV,
1094                          TYPE_CHARDEV_VC)
1095 
1096 static int vc_chr_write(Chardev *chr, const uint8_t *buf, int len)
1097 {
1098     VCChardev *drv = VC_CHARDEV(chr);
1099     QemuConsole *s = drv->console;
1100     int i;
1101 
1102     if (!s->ds) {
1103         return 0;
1104     }
1105 
1106     s->update_x0 = s->width * FONT_WIDTH;
1107     s->update_y0 = s->height * FONT_HEIGHT;
1108     s->update_x1 = 0;
1109     s->update_y1 = 0;
1110     console_show_cursor(s, 0);
1111     for(i = 0; i < len; i++) {
1112         console_putchar(s, buf[i]);
1113     }
1114     console_show_cursor(s, 1);
1115     if (s->ds->have_gfx && s->update_x0 < s->update_x1) {
1116         dpy_gfx_update(s, s->update_x0, s->update_y0,
1117                        s->update_x1 - s->update_x0,
1118                        s->update_y1 - s->update_y0);
1119     }
1120     return len;
1121 }
1122 
1123 static void kbd_send_chars(void *opaque)
1124 {
1125     QemuConsole *s = opaque;
1126     int len;
1127     uint8_t buf[16];
1128 
1129     len = qemu_chr_be_can_write(s->chr);
1130     if (len > s->out_fifo.count)
1131         len = s->out_fifo.count;
1132     if (len > 0) {
1133         if (len > sizeof(buf))
1134             len = sizeof(buf);
1135         qemu_fifo_read(&s->out_fifo, buf, len);
1136         qemu_chr_be_write(s->chr, buf, len);
1137     }
1138     /* characters are pending: we send them a bit later (XXX:
1139        horrible, should change char device API) */
1140     if (s->out_fifo.count > 0) {
1141         timer_mod(s->kbd_timer, qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + 1);
1142     }
1143 }
1144 
1145 /* called when an ascii key is pressed */
1146 void kbd_put_keysym_console(QemuConsole *s, int keysym)
1147 {
1148     uint8_t buf[16], *q;
1149     CharBackend *be;
1150     int c;
1151 
1152     if (!s || (s->console_type == GRAPHIC_CONSOLE))
1153         return;
1154 
1155     switch(keysym) {
1156     case QEMU_KEY_CTRL_UP:
1157         console_scroll(s, -1);
1158         break;
1159     case QEMU_KEY_CTRL_DOWN:
1160         console_scroll(s, 1);
1161         break;
1162     case QEMU_KEY_CTRL_PAGEUP:
1163         console_scroll(s, -10);
1164         break;
1165     case QEMU_KEY_CTRL_PAGEDOWN:
1166         console_scroll(s, 10);
1167         break;
1168     default:
1169         /* convert the QEMU keysym to VT100 key string */
1170         q = buf;
1171         if (keysym >= 0xe100 && keysym <= 0xe11f) {
1172             *q++ = '\033';
1173             *q++ = '[';
1174             c = keysym - 0xe100;
1175             if (c >= 10)
1176                 *q++ = '0' + (c / 10);
1177             *q++ = '0' + (c % 10);
1178             *q++ = '~';
1179         } else if (keysym >= 0xe120 && keysym <= 0xe17f) {
1180             *q++ = '\033';
1181             *q++ = '[';
1182             *q++ = keysym & 0xff;
1183         } else if (s->echo && (keysym == '\r' || keysym == '\n')) {
1184             vc_chr_write(s->chr, (const uint8_t *) "\r", 1);
1185             *q++ = '\n';
1186         } else {
1187             *q++ = keysym;
1188         }
1189         if (s->echo) {
1190             vc_chr_write(s->chr, buf, q - buf);
1191         }
1192         be = s->chr->be;
1193         if (be && be->chr_read) {
1194             qemu_fifo_write(&s->out_fifo, buf, q - buf);
1195             kbd_send_chars(s);
1196         }
1197         break;
1198     }
1199 }
1200 
1201 static const int qcode_to_keysym[Q_KEY_CODE__MAX] = {
1202     [Q_KEY_CODE_UP]     = QEMU_KEY_UP,
1203     [Q_KEY_CODE_DOWN]   = QEMU_KEY_DOWN,
1204     [Q_KEY_CODE_RIGHT]  = QEMU_KEY_RIGHT,
1205     [Q_KEY_CODE_LEFT]   = QEMU_KEY_LEFT,
1206     [Q_KEY_CODE_HOME]   = QEMU_KEY_HOME,
1207     [Q_KEY_CODE_END]    = QEMU_KEY_END,
1208     [Q_KEY_CODE_PGUP]   = QEMU_KEY_PAGEUP,
1209     [Q_KEY_CODE_PGDN]   = QEMU_KEY_PAGEDOWN,
1210     [Q_KEY_CODE_DELETE] = QEMU_KEY_DELETE,
1211     [Q_KEY_CODE_BACKSPACE] = QEMU_KEY_BACKSPACE,
1212 };
1213 
1214 static const int ctrl_qcode_to_keysym[Q_KEY_CODE__MAX] = {
1215     [Q_KEY_CODE_UP]     = QEMU_KEY_CTRL_UP,
1216     [Q_KEY_CODE_DOWN]   = QEMU_KEY_CTRL_DOWN,
1217     [Q_KEY_CODE_RIGHT]  = QEMU_KEY_CTRL_RIGHT,
1218     [Q_KEY_CODE_LEFT]   = QEMU_KEY_CTRL_LEFT,
1219     [Q_KEY_CODE_HOME]   = QEMU_KEY_CTRL_HOME,
1220     [Q_KEY_CODE_END]    = QEMU_KEY_CTRL_END,
1221     [Q_KEY_CODE_PGUP]   = QEMU_KEY_CTRL_PAGEUP,
1222     [Q_KEY_CODE_PGDN]   = QEMU_KEY_CTRL_PAGEDOWN,
1223 };
1224 
1225 bool kbd_put_qcode_console(QemuConsole *s, int qcode, bool ctrl)
1226 {
1227     int keysym;
1228 
1229     keysym = ctrl ? ctrl_qcode_to_keysym[qcode] : qcode_to_keysym[qcode];
1230     if (keysym == 0) {
1231         return false;
1232     }
1233     kbd_put_keysym_console(s, keysym);
1234     return true;
1235 }
1236 
1237 void kbd_put_string_console(QemuConsole *s, const char *str, int len)
1238 {
1239     int i;
1240 
1241     for (i = 0; i < len && str[i]; i++) {
1242         kbd_put_keysym_console(s, str[i]);
1243     }
1244 }
1245 
1246 void kbd_put_keysym(int keysym)
1247 {
1248     kbd_put_keysym_console(active_console, keysym);
1249 }
1250 
1251 static void text_console_invalidate(void *opaque)
1252 {
1253     QemuConsole *s = (QemuConsole *) opaque;
1254 
1255     if (s->ds->have_text && s->console_type == TEXT_CONSOLE) {
1256         text_console_resize(s);
1257     }
1258     console_refresh(s);
1259 }
1260 
1261 static void text_console_update(void *opaque, console_ch_t *chardata)
1262 {
1263     QemuConsole *s = (QemuConsole *) opaque;
1264     int i, j, src;
1265 
1266     if (s->text_x[0] <= s->text_x[1]) {
1267         src = (s->y_base + s->text_y[0]) * s->width;
1268         chardata += s->text_y[0] * s->width;
1269         for (i = s->text_y[0]; i <= s->text_y[1]; i ++)
1270             for (j = 0; j < s->width; j++, src++) {
1271                 console_write_ch(chardata ++,
1272                                  ATTR2CHTYPE(s->cells[src].ch,
1273                                              s->cells[src].t_attrib.fgcol,
1274                                              s->cells[src].t_attrib.bgcol,
1275                                              s->cells[src].t_attrib.bold));
1276             }
1277         dpy_text_update(s, s->text_x[0], s->text_y[0],
1278                         s->text_x[1] - s->text_x[0], i - s->text_y[0]);
1279         s->text_x[0] = s->width;
1280         s->text_y[0] = s->height;
1281         s->text_x[1] = 0;
1282         s->text_y[1] = 0;
1283     }
1284     if (s->cursor_invalidate) {
1285         dpy_text_cursor(s, s->x, s->y);
1286         s->cursor_invalidate = 0;
1287     }
1288 }
1289 
1290 static QemuConsole *new_console(DisplayState *ds, console_type_t console_type,
1291                                 uint32_t head)
1292 {
1293     Object *obj;
1294     QemuConsole *s;
1295     int i;
1296 
1297     obj = object_new(TYPE_QEMU_CONSOLE);
1298     s = QEMU_CONSOLE(obj);
1299     s->head = head;
1300     object_property_add_link(obj, "device", TYPE_DEVICE,
1301                              (Object **)&s->device,
1302                              object_property_allow_set_link,
1303                              OBJ_PROP_LINK_STRONG);
1304     object_property_add_uint32_ptr(obj, "head", &s->head,
1305                                    OBJ_PROP_FLAG_READ);
1306 
1307     if (!active_console || ((active_console->console_type != GRAPHIC_CONSOLE) &&
1308         (console_type == GRAPHIC_CONSOLE))) {
1309         active_console = s;
1310     }
1311     s->ds = ds;
1312     s->console_type = console_type;
1313 
1314     if (QTAILQ_EMPTY(&consoles)) {
1315         s->index = 0;
1316         QTAILQ_INSERT_TAIL(&consoles, s, next);
1317     } else if (console_type != GRAPHIC_CONSOLE || qdev_hotplug) {
1318         QemuConsole *last = QTAILQ_LAST(&consoles);
1319         s->index = last->index + 1;
1320         QTAILQ_INSERT_TAIL(&consoles, s, next);
1321     } else {
1322         /*
1323          * HACK: Put graphical consoles before text consoles.
1324          *
1325          * Only do that for coldplugged devices.  After initial device
1326          * initialization we will not renumber the consoles any more.
1327          */
1328         QemuConsole *c = QTAILQ_FIRST(&consoles);
1329 
1330         while (QTAILQ_NEXT(c, next) != NULL &&
1331                c->console_type == GRAPHIC_CONSOLE) {
1332             c = QTAILQ_NEXT(c, next);
1333         }
1334         if (c->console_type == GRAPHIC_CONSOLE) {
1335             /* have no text consoles */
1336             s->index = c->index + 1;
1337             QTAILQ_INSERT_AFTER(&consoles, c, s, next);
1338         } else {
1339             s->index = c->index;
1340             QTAILQ_INSERT_BEFORE(c, s, next);
1341             /* renumber text consoles */
1342             for (i = s->index + 1; c != NULL; c = QTAILQ_NEXT(c, next), i++) {
1343                 c->index = i;
1344             }
1345         }
1346     }
1347     return s;
1348 }
1349 
1350 static void qemu_alloc_display(DisplaySurface *surface, int width, int height)
1351 {
1352     qemu_pixman_image_unref(surface->image);
1353     surface->image = NULL;
1354 
1355     surface->format = PIXMAN_x8r8g8b8;
1356     surface->image = pixman_image_create_bits(surface->format,
1357                                               width, height,
1358                                               NULL, width * 4);
1359     assert(surface->image != NULL);
1360 
1361     surface->flags = QEMU_ALLOCATED_FLAG;
1362 }
1363 
1364 DisplaySurface *qemu_create_displaysurface(int width, int height)
1365 {
1366     DisplaySurface *surface = g_new0(DisplaySurface, 1);
1367 
1368     trace_displaysurface_create(surface, width, height);
1369     qemu_alloc_display(surface, width, height);
1370     return surface;
1371 }
1372 
1373 DisplaySurface *qemu_create_displaysurface_from(int width, int height,
1374                                                 pixman_format_code_t format,
1375                                                 int linesize, uint8_t *data)
1376 {
1377     DisplaySurface *surface = g_new0(DisplaySurface, 1);
1378 
1379     trace_displaysurface_create_from(surface, width, height, format);
1380     surface->format = format;
1381     surface->image = pixman_image_create_bits(surface->format,
1382                                               width, height,
1383                                               (void *)data, linesize);
1384     assert(surface->image != NULL);
1385 
1386     return surface;
1387 }
1388 
1389 DisplaySurface *qemu_create_displaysurface_pixman(pixman_image_t *image)
1390 {
1391     DisplaySurface *surface = g_new0(DisplaySurface, 1);
1392 
1393     trace_displaysurface_create_pixman(surface);
1394     surface->format = pixman_image_get_format(image);
1395     surface->image = pixman_image_ref(image);
1396 
1397     return surface;
1398 }
1399 
1400 DisplaySurface *qemu_create_message_surface(int w, int h,
1401                                             const char *msg)
1402 {
1403     DisplaySurface *surface = qemu_create_displaysurface(w, h);
1404     pixman_color_t bg = color_table_rgb[0][QEMU_COLOR_BLACK];
1405     pixman_color_t fg = color_table_rgb[0][QEMU_COLOR_WHITE];
1406     pixman_image_t *glyph;
1407     int len, x, y, i;
1408 
1409     len = strlen(msg);
1410     x = (w / FONT_WIDTH  - len) / 2;
1411     y = (h / FONT_HEIGHT - 1)   / 2;
1412     for (i = 0; i < len; i++) {
1413         glyph = qemu_pixman_glyph_from_vgafont(FONT_HEIGHT, vgafont16, msg[i]);
1414         qemu_pixman_glyph_render(glyph, surface->image, &fg, &bg,
1415                                  x+i, y, FONT_WIDTH, FONT_HEIGHT);
1416         qemu_pixman_image_unref(glyph);
1417     }
1418     return surface;
1419 }
1420 
1421 void qemu_free_displaysurface(DisplaySurface *surface)
1422 {
1423     if (surface == NULL) {
1424         return;
1425     }
1426     trace_displaysurface_free(surface);
1427     qemu_pixman_image_unref(surface->image);
1428     g_free(surface);
1429 }
1430 
1431 bool console_has_gl(QemuConsole *con)
1432 {
1433     return con->gl != NULL;
1434 }
1435 
1436 bool console_has_gl_dmabuf(QemuConsole *con)
1437 {
1438     return con->gl != NULL && con->gl->ops->dpy_gl_scanout_dmabuf != NULL;
1439 }
1440 
1441 void register_displaychangelistener(DisplayChangeListener *dcl)
1442 {
1443     static const char nodev[] =
1444         "This VM has no graphic display device.";
1445     static DisplaySurface *dummy;
1446     QemuConsole *con;
1447 
1448     assert(!dcl->ds);
1449 
1450     if (dcl->ops->dpy_gl_ctx_create) {
1451         /* display has opengl support */
1452         assert(dcl->con);
1453         if (dcl->con->gl) {
1454             fprintf(stderr, "can't register two opengl displays (%s, %s)\n",
1455                     dcl->ops->dpy_name, dcl->con->gl->ops->dpy_name);
1456             exit(1);
1457         }
1458         dcl->con->gl = dcl;
1459     }
1460 
1461     trace_displaychangelistener_register(dcl, dcl->ops->dpy_name);
1462     dcl->ds = get_alloc_displaystate();
1463     QLIST_INSERT_HEAD(&dcl->ds->listeners, dcl, next);
1464     gui_setup_refresh(dcl->ds);
1465     if (dcl->con) {
1466         dcl->con->dcls++;
1467         con = dcl->con;
1468     } else {
1469         con = active_console;
1470     }
1471     if (dcl->ops->dpy_gfx_switch) {
1472         if (con) {
1473             dcl->ops->dpy_gfx_switch(dcl, con->surface);
1474         } else {
1475             if (!dummy) {
1476                 dummy = qemu_create_message_surface(640, 480, nodev);
1477             }
1478             dcl->ops->dpy_gfx_switch(dcl, dummy);
1479         }
1480     }
1481     text_console_update_cursor(NULL);
1482 }
1483 
1484 void update_displaychangelistener(DisplayChangeListener *dcl,
1485                                   uint64_t interval)
1486 {
1487     DisplayState *ds = dcl->ds;
1488 
1489     dcl->update_interval = interval;
1490     if (!ds->refreshing && ds->update_interval > interval) {
1491         timer_mod(ds->gui_timer, ds->last_update + interval);
1492     }
1493 }
1494 
1495 void unregister_displaychangelistener(DisplayChangeListener *dcl)
1496 {
1497     DisplayState *ds = dcl->ds;
1498     trace_displaychangelistener_unregister(dcl, dcl->ops->dpy_name);
1499     if (dcl->con) {
1500         dcl->con->dcls--;
1501     }
1502     QLIST_REMOVE(dcl, next);
1503     dcl->ds = NULL;
1504     gui_setup_refresh(ds);
1505 }
1506 
1507 static void dpy_set_ui_info_timer(void *opaque)
1508 {
1509     QemuConsole *con = opaque;
1510 
1511     con->hw_ops->ui_info(con->hw, con->head, &con->ui_info);
1512 }
1513 
1514 bool dpy_ui_info_supported(QemuConsole *con)
1515 {
1516     return con->hw_ops->ui_info != NULL;
1517 }
1518 
1519 int dpy_set_ui_info(QemuConsole *con, QemuUIInfo *info)
1520 {
1521     assert(con != NULL);
1522 
1523     if (!dpy_ui_info_supported(con)) {
1524         return -1;
1525     }
1526     if (memcmp(&con->ui_info, info, sizeof(con->ui_info)) == 0) {
1527         /* nothing changed -- ignore */
1528         return 0;
1529     }
1530 
1531     /*
1532      * Typically we get a flood of these as the user resizes the window.
1533      * Wait until the dust has settled (one second without updates), then
1534      * go notify the guest.
1535      */
1536     con->ui_info = *info;
1537     timer_mod(con->ui_timer, qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + 1000);
1538     return 0;
1539 }
1540 
1541 void dpy_gfx_update(QemuConsole *con, int x, int y, int w, int h)
1542 {
1543     DisplayState *s = con->ds;
1544     DisplayChangeListener *dcl;
1545     int width = w;
1546     int height = h;
1547 
1548     if (con->surface) {
1549         width = surface_width(con->surface);
1550         height = surface_height(con->surface);
1551     }
1552     x = MAX(x, 0);
1553     y = MAX(y, 0);
1554     x = MIN(x, width);
1555     y = MIN(y, height);
1556     w = MIN(w, width - x);
1557     h = MIN(h, height - y);
1558 
1559     if (!qemu_console_is_visible(con)) {
1560         return;
1561     }
1562     QLIST_FOREACH(dcl, &s->listeners, next) {
1563         if (con != (dcl->con ? dcl->con : active_console)) {
1564             continue;
1565         }
1566         if (dcl->ops->dpy_gfx_update) {
1567             dcl->ops->dpy_gfx_update(dcl, x, y, w, h);
1568         }
1569     }
1570 }
1571 
1572 void dpy_gfx_update_full(QemuConsole *con)
1573 {
1574     if (!con->surface) {
1575         return;
1576     }
1577     dpy_gfx_update(con, 0, 0,
1578                    surface_width(con->surface),
1579                    surface_height(con->surface));
1580 }
1581 
1582 void dpy_gfx_replace_surface(QemuConsole *con,
1583                              DisplaySurface *surface)
1584 {
1585     DisplayState *s = con->ds;
1586     DisplaySurface *old_surface = con->surface;
1587     DisplayChangeListener *dcl;
1588 
1589     assert(old_surface != surface || surface == NULL);
1590 
1591     con->surface = surface;
1592     QLIST_FOREACH(dcl, &s->listeners, next) {
1593         if (con != (dcl->con ? dcl->con : active_console)) {
1594             continue;
1595         }
1596         if (dcl->ops->dpy_gfx_switch) {
1597             dcl->ops->dpy_gfx_switch(dcl, surface);
1598         }
1599     }
1600     qemu_free_displaysurface(old_surface);
1601 }
1602 
1603 bool dpy_gfx_check_format(QemuConsole *con,
1604                           pixman_format_code_t format)
1605 {
1606     DisplayChangeListener *dcl;
1607     DisplayState *s = con->ds;
1608 
1609     QLIST_FOREACH(dcl, &s->listeners, next) {
1610         if (dcl->con && dcl->con != con) {
1611             /* dcl bound to another console -> skip */
1612             continue;
1613         }
1614         if (dcl->ops->dpy_gfx_check_format) {
1615             if (!dcl->ops->dpy_gfx_check_format(dcl, format)) {
1616                 return false;
1617             }
1618         } else {
1619             /* default is to whitelist native 32 bpp only */
1620             if (format != qemu_default_pixman_format(32, true)) {
1621                 return false;
1622             }
1623         }
1624     }
1625     return true;
1626 }
1627 
1628 static void dpy_refresh(DisplayState *s)
1629 {
1630     DisplayChangeListener *dcl;
1631 
1632     QLIST_FOREACH(dcl, &s->listeners, next) {
1633         if (dcl->ops->dpy_refresh) {
1634             dcl->ops->dpy_refresh(dcl);
1635         }
1636     }
1637 }
1638 
1639 void dpy_text_cursor(QemuConsole *con, int x, int y)
1640 {
1641     DisplayState *s = con->ds;
1642     DisplayChangeListener *dcl;
1643 
1644     if (!qemu_console_is_visible(con)) {
1645         return;
1646     }
1647     QLIST_FOREACH(dcl, &s->listeners, next) {
1648         if (con != (dcl->con ? dcl->con : active_console)) {
1649             continue;
1650         }
1651         if (dcl->ops->dpy_text_cursor) {
1652             dcl->ops->dpy_text_cursor(dcl, x, y);
1653         }
1654     }
1655 }
1656 
1657 void dpy_text_update(QemuConsole *con, int x, int y, int w, int h)
1658 {
1659     DisplayState *s = con->ds;
1660     DisplayChangeListener *dcl;
1661 
1662     if (!qemu_console_is_visible(con)) {
1663         return;
1664     }
1665     QLIST_FOREACH(dcl, &s->listeners, next) {
1666         if (con != (dcl->con ? dcl->con : active_console)) {
1667             continue;
1668         }
1669         if (dcl->ops->dpy_text_update) {
1670             dcl->ops->dpy_text_update(dcl, x, y, w, h);
1671         }
1672     }
1673 }
1674 
1675 void dpy_text_resize(QemuConsole *con, int w, int h)
1676 {
1677     DisplayState *s = con->ds;
1678     DisplayChangeListener *dcl;
1679 
1680     if (!qemu_console_is_visible(con)) {
1681         return;
1682     }
1683     QLIST_FOREACH(dcl, &s->listeners, next) {
1684         if (con != (dcl->con ? dcl->con : active_console)) {
1685             continue;
1686         }
1687         if (dcl->ops->dpy_text_resize) {
1688             dcl->ops->dpy_text_resize(dcl, w, h);
1689         }
1690     }
1691 }
1692 
1693 void dpy_mouse_set(QemuConsole *con, int x, int y, int on)
1694 {
1695     DisplayState *s = con->ds;
1696     DisplayChangeListener *dcl;
1697 
1698     if (!qemu_console_is_visible(con)) {
1699         return;
1700     }
1701     QLIST_FOREACH(dcl, &s->listeners, next) {
1702         if (con != (dcl->con ? dcl->con : active_console)) {
1703             continue;
1704         }
1705         if (dcl->ops->dpy_mouse_set) {
1706             dcl->ops->dpy_mouse_set(dcl, x, y, on);
1707         }
1708     }
1709 }
1710 
1711 void dpy_cursor_define(QemuConsole *con, QEMUCursor *cursor)
1712 {
1713     DisplayState *s = con->ds;
1714     DisplayChangeListener *dcl;
1715 
1716     if (!qemu_console_is_visible(con)) {
1717         return;
1718     }
1719     QLIST_FOREACH(dcl, &s->listeners, next) {
1720         if (con != (dcl->con ? dcl->con : active_console)) {
1721             continue;
1722         }
1723         if (dcl->ops->dpy_cursor_define) {
1724             dcl->ops->dpy_cursor_define(dcl, cursor);
1725         }
1726     }
1727 }
1728 
1729 bool dpy_cursor_define_supported(QemuConsole *con)
1730 {
1731     DisplayState *s = con->ds;
1732     DisplayChangeListener *dcl;
1733 
1734     QLIST_FOREACH(dcl, &s->listeners, next) {
1735         if (dcl->ops->dpy_cursor_define) {
1736             return true;
1737         }
1738     }
1739     return false;
1740 }
1741 
1742 QEMUGLContext dpy_gl_ctx_create(QemuConsole *con,
1743                                 struct QEMUGLParams *qparams)
1744 {
1745     assert(con->gl);
1746     return con->gl->ops->dpy_gl_ctx_create(con->gl, qparams);
1747 }
1748 
1749 void dpy_gl_ctx_destroy(QemuConsole *con, QEMUGLContext ctx)
1750 {
1751     assert(con->gl);
1752     con->gl->ops->dpy_gl_ctx_destroy(con->gl, ctx);
1753 }
1754 
1755 int dpy_gl_ctx_make_current(QemuConsole *con, QEMUGLContext ctx)
1756 {
1757     assert(con->gl);
1758     return con->gl->ops->dpy_gl_ctx_make_current(con->gl, ctx);
1759 }
1760 
1761 QEMUGLContext dpy_gl_ctx_get_current(QemuConsole *con)
1762 {
1763     assert(con->gl);
1764     return con->gl->ops->dpy_gl_ctx_get_current(con->gl);
1765 }
1766 
1767 void dpy_gl_scanout_disable(QemuConsole *con)
1768 {
1769     assert(con->gl);
1770     if (con->gl->ops->dpy_gl_scanout_disable) {
1771         con->gl->ops->dpy_gl_scanout_disable(con->gl);
1772     } else {
1773         con->gl->ops->dpy_gl_scanout_texture(con->gl, 0, false, 0, 0,
1774                                              0, 0, 0, 0);
1775     }
1776 }
1777 
1778 void dpy_gl_scanout_texture(QemuConsole *con,
1779                             uint32_t backing_id,
1780                             bool backing_y_0_top,
1781                             uint32_t backing_width,
1782                             uint32_t backing_height,
1783                             uint32_t x, uint32_t y,
1784                             uint32_t width, uint32_t height)
1785 {
1786     assert(con->gl);
1787     con->gl->ops->dpy_gl_scanout_texture(con->gl, backing_id,
1788                                          backing_y_0_top,
1789                                          backing_width, backing_height,
1790                                          x, y, width, height);
1791 }
1792 
1793 void dpy_gl_scanout_dmabuf(QemuConsole *con,
1794                            QemuDmaBuf *dmabuf)
1795 {
1796     assert(con->gl);
1797     con->gl->ops->dpy_gl_scanout_dmabuf(con->gl, dmabuf);
1798 }
1799 
1800 void dpy_gl_cursor_dmabuf(QemuConsole *con, QemuDmaBuf *dmabuf,
1801                           bool have_hot, uint32_t hot_x, uint32_t hot_y)
1802 {
1803     assert(con->gl);
1804 
1805     if (con->gl->ops->dpy_gl_cursor_dmabuf) {
1806         con->gl->ops->dpy_gl_cursor_dmabuf(con->gl, dmabuf,
1807                                            have_hot, hot_x, hot_y);
1808     }
1809 }
1810 
1811 void dpy_gl_cursor_position(QemuConsole *con,
1812                             uint32_t pos_x, uint32_t pos_y)
1813 {
1814     assert(con->gl);
1815 
1816     if (con->gl->ops->dpy_gl_cursor_position) {
1817         con->gl->ops->dpy_gl_cursor_position(con->gl, pos_x, pos_y);
1818     }
1819 }
1820 
1821 void dpy_gl_release_dmabuf(QemuConsole *con,
1822                           QemuDmaBuf *dmabuf)
1823 {
1824     assert(con->gl);
1825 
1826     if (con->gl->ops->dpy_gl_release_dmabuf) {
1827         con->gl->ops->dpy_gl_release_dmabuf(con->gl, dmabuf);
1828     }
1829 }
1830 
1831 void dpy_gl_update(QemuConsole *con,
1832                    uint32_t x, uint32_t y, uint32_t w, uint32_t h)
1833 {
1834     assert(con->gl);
1835     con->gl->ops->dpy_gl_update(con->gl, x, y, w, h);
1836 }
1837 
1838 /***********************************************************/
1839 /* register display */
1840 
1841 /* console.c internal use only */
1842 static DisplayState *get_alloc_displaystate(void)
1843 {
1844     if (!display_state) {
1845         display_state = g_new0(DisplayState, 1);
1846         cursor_timer = timer_new_ms(QEMU_CLOCK_REALTIME,
1847                                     text_console_update_cursor, NULL);
1848     }
1849     return display_state;
1850 }
1851 
1852 /*
1853  * Called by main(), after creating QemuConsoles
1854  * and before initializing ui (sdl/vnc/...).
1855  */
1856 DisplayState *init_displaystate(void)
1857 {
1858     gchar *name;
1859     QemuConsole *con;
1860 
1861     get_alloc_displaystate();
1862     QTAILQ_FOREACH(con, &consoles, next) {
1863         if (con->console_type != GRAPHIC_CONSOLE &&
1864             con->ds == NULL) {
1865             text_console_do_init(con->chr, display_state);
1866         }
1867 
1868         /* Hook up into the qom tree here (not in new_console()), once
1869          * all QemuConsoles are created and the order / numbering
1870          * doesn't change any more */
1871         name = g_strdup_printf("console[%d]", con->index);
1872         object_property_add_child(container_get(object_get_root(), "/backend"),
1873                                   name, OBJECT(con));
1874         g_free(name);
1875     }
1876 
1877     return display_state;
1878 }
1879 
1880 void graphic_console_set_hwops(QemuConsole *con,
1881                                const GraphicHwOps *hw_ops,
1882                                void *opaque)
1883 {
1884     con->hw_ops = hw_ops;
1885     con->hw = opaque;
1886 }
1887 
1888 QemuConsole *graphic_console_init(DeviceState *dev, uint32_t head,
1889                                   const GraphicHwOps *hw_ops,
1890                                   void *opaque)
1891 {
1892     static const char noinit[] =
1893         "Guest has not initialized the display (yet).";
1894     int width = 640;
1895     int height = 480;
1896     QemuConsole *s;
1897     DisplayState *ds;
1898     DisplaySurface *surface;
1899 
1900     ds = get_alloc_displaystate();
1901     s = qemu_console_lookup_unused();
1902     if (s) {
1903         trace_console_gfx_reuse(s->index);
1904         if (s->surface) {
1905             width = surface_width(s->surface);
1906             height = surface_height(s->surface);
1907         }
1908     } else {
1909         trace_console_gfx_new();
1910         s = new_console(ds, GRAPHIC_CONSOLE, head);
1911         s->ui_timer = timer_new_ms(QEMU_CLOCK_REALTIME,
1912                                    dpy_set_ui_info_timer, s);
1913     }
1914     graphic_console_set_hwops(s, hw_ops, opaque);
1915     if (dev) {
1916         object_property_set_link(OBJECT(s), "device", OBJECT(dev),
1917                                  &error_abort);
1918     }
1919 
1920     surface = qemu_create_message_surface(width, height, noinit);
1921     dpy_gfx_replace_surface(s, surface);
1922     return s;
1923 }
1924 
1925 static const GraphicHwOps unused_ops = {
1926     /* no callbacks */
1927 };
1928 
1929 void graphic_console_close(QemuConsole *con)
1930 {
1931     static const char unplugged[] =
1932         "Guest display has been unplugged";
1933     DisplaySurface *surface;
1934     int width = 640;
1935     int height = 480;
1936 
1937     if (con->surface) {
1938         width = surface_width(con->surface);
1939         height = surface_height(con->surface);
1940     }
1941 
1942     trace_console_gfx_close(con->index);
1943     object_property_set_link(OBJECT(con), "device", NULL, &error_abort);
1944     graphic_console_set_hwops(con, &unused_ops, NULL);
1945 
1946     if (con->gl) {
1947         dpy_gl_scanout_disable(con);
1948     }
1949     surface = qemu_create_message_surface(width, height, unplugged);
1950     dpy_gfx_replace_surface(con, surface);
1951 }
1952 
1953 QemuConsole *qemu_console_lookup_by_index(unsigned int index)
1954 {
1955     QemuConsole *con;
1956 
1957     QTAILQ_FOREACH(con, &consoles, next) {
1958         if (con->index == index) {
1959             return con;
1960         }
1961     }
1962     return NULL;
1963 }
1964 
1965 QemuConsole *qemu_console_lookup_by_device(DeviceState *dev, uint32_t head)
1966 {
1967     QemuConsole *con;
1968     Object *obj;
1969     uint32_t h;
1970 
1971     QTAILQ_FOREACH(con, &consoles, next) {
1972         obj = object_property_get_link(OBJECT(con),
1973                                        "device", &error_abort);
1974         if (DEVICE(obj) != dev) {
1975             continue;
1976         }
1977         h = object_property_get_uint(OBJECT(con),
1978                                      "head", &error_abort);
1979         if (h != head) {
1980             continue;
1981         }
1982         return con;
1983     }
1984     return NULL;
1985 }
1986 
1987 QemuConsole *qemu_console_lookup_by_device_name(const char *device_id,
1988                                                 uint32_t head, Error **errp)
1989 {
1990     DeviceState *dev;
1991     QemuConsole *con;
1992 
1993     dev = qdev_find_recursive(sysbus_get_default(), device_id);
1994     if (dev == NULL) {
1995         error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,
1996                   "Device '%s' not found", device_id);
1997         return NULL;
1998     }
1999 
2000     con = qemu_console_lookup_by_device(dev, head);
2001     if (con == NULL) {
2002         error_setg(errp, "Device %s (head %d) is not bound to a QemuConsole",
2003                    device_id, head);
2004         return NULL;
2005     }
2006 
2007     return con;
2008 }
2009 
2010 QemuConsole *qemu_console_lookup_unused(void)
2011 {
2012     QemuConsole *con;
2013     Object *obj;
2014 
2015     QTAILQ_FOREACH(con, &consoles, next) {
2016         if (con->hw_ops != &unused_ops) {
2017             continue;
2018         }
2019         obj = object_property_get_link(OBJECT(con),
2020                                        "device", &error_abort);
2021         if (obj != NULL) {
2022             continue;
2023         }
2024         return con;
2025     }
2026     return NULL;
2027 }
2028 
2029 bool qemu_console_is_visible(QemuConsole *con)
2030 {
2031     return (con == active_console) || (con->dcls > 0);
2032 }
2033 
2034 bool qemu_console_is_graphic(QemuConsole *con)
2035 {
2036     if (con == NULL) {
2037         con = active_console;
2038     }
2039     return con && (con->console_type == GRAPHIC_CONSOLE);
2040 }
2041 
2042 bool qemu_console_is_fixedsize(QemuConsole *con)
2043 {
2044     if (con == NULL) {
2045         con = active_console;
2046     }
2047     return con && (con->console_type != TEXT_CONSOLE);
2048 }
2049 
2050 bool qemu_console_is_gl_blocked(QemuConsole *con)
2051 {
2052     assert(con != NULL);
2053     return con->gl_block;
2054 }
2055 
2056 char *qemu_console_get_label(QemuConsole *con)
2057 {
2058     if (con->console_type == GRAPHIC_CONSOLE) {
2059         if (con->device) {
2060             return g_strdup(object_get_typename(con->device));
2061         }
2062         return g_strdup("VGA");
2063     } else {
2064         if (con->chr && con->chr->label) {
2065             return g_strdup(con->chr->label);
2066         }
2067         return g_strdup_printf("vc%d", con->index);
2068     }
2069 }
2070 
2071 int qemu_console_get_index(QemuConsole *con)
2072 {
2073     if (con == NULL) {
2074         con = active_console;
2075     }
2076     return con ? con->index : -1;
2077 }
2078 
2079 uint32_t qemu_console_get_head(QemuConsole *con)
2080 {
2081     if (con == NULL) {
2082         con = active_console;
2083     }
2084     return con ? con->head : -1;
2085 }
2086 
2087 QemuUIInfo *qemu_console_get_ui_info(QemuConsole *con)
2088 {
2089     assert(con != NULL);
2090     return &con->ui_info;
2091 }
2092 
2093 int qemu_console_get_width(QemuConsole *con, int fallback)
2094 {
2095     if (con == NULL) {
2096         con = active_console;
2097     }
2098     return con ? surface_width(con->surface) : fallback;
2099 }
2100 
2101 int qemu_console_get_height(QemuConsole *con, int fallback)
2102 {
2103     if (con == NULL) {
2104         con = active_console;
2105     }
2106     return con ? surface_height(con->surface) : fallback;
2107 }
2108 
2109 static void vc_chr_set_echo(Chardev *chr, bool echo)
2110 {
2111     VCChardev *drv = VC_CHARDEV(chr);
2112     QemuConsole *s = drv->console;
2113 
2114     s->echo = echo;
2115 }
2116 
2117 static void text_console_update_cursor_timer(void)
2118 {
2119     timer_mod(cursor_timer, qemu_clock_get_ms(QEMU_CLOCK_REALTIME)
2120               + CONSOLE_CURSOR_PERIOD / 2);
2121 }
2122 
2123 static void text_console_update_cursor(void *opaque)
2124 {
2125     QemuConsole *s;
2126     int count = 0;
2127 
2128     cursor_visible_phase = !cursor_visible_phase;
2129 
2130     QTAILQ_FOREACH(s, &consoles, next) {
2131         if (qemu_console_is_graphic(s) ||
2132             !qemu_console_is_visible(s)) {
2133             continue;
2134         }
2135         count++;
2136         graphic_hw_invalidate(s);
2137     }
2138 
2139     if (count) {
2140         text_console_update_cursor_timer();
2141     }
2142 }
2143 
2144 static const GraphicHwOps text_console_ops = {
2145     .invalidate  = text_console_invalidate,
2146     .text_update = text_console_update,
2147 };
2148 
2149 static void text_console_do_init(Chardev *chr, DisplayState *ds)
2150 {
2151     VCChardev *drv = VC_CHARDEV(chr);
2152     QemuConsole *s = drv->console;
2153     int g_width = 80 * FONT_WIDTH;
2154     int g_height = 24 * FONT_HEIGHT;
2155 
2156     s->out_fifo.buf = s->out_fifo_buf;
2157     s->out_fifo.buf_size = sizeof(s->out_fifo_buf);
2158     s->kbd_timer = timer_new_ms(QEMU_CLOCK_REALTIME, kbd_send_chars, s);
2159     s->ds = ds;
2160 
2161     s->y_displayed = 0;
2162     s->y_base = 0;
2163     s->total_height = DEFAULT_BACKSCROLL;
2164     s->x = 0;
2165     s->y = 0;
2166     if (!s->surface) {
2167         if (active_console && active_console->surface) {
2168             g_width = surface_width(active_console->surface);
2169             g_height = surface_height(active_console->surface);
2170         }
2171         s->surface = qemu_create_displaysurface(g_width, g_height);
2172     }
2173 
2174     s->hw_ops = &text_console_ops;
2175     s->hw = s;
2176 
2177     /* Set text attribute defaults */
2178     s->t_attrib_default.bold = 0;
2179     s->t_attrib_default.uline = 0;
2180     s->t_attrib_default.blink = 0;
2181     s->t_attrib_default.invers = 0;
2182     s->t_attrib_default.unvisible = 0;
2183     s->t_attrib_default.fgcol = QEMU_COLOR_WHITE;
2184     s->t_attrib_default.bgcol = QEMU_COLOR_BLACK;
2185     /* set current text attributes to default */
2186     s->t_attrib = s->t_attrib_default;
2187     text_console_resize(s);
2188 
2189     if (chr->label) {
2190         char *msg;
2191 
2192         s->t_attrib.bgcol = QEMU_COLOR_BLUE;
2193         msg = g_strdup_printf("%s console\r\n", chr->label);
2194         vc_chr_write(chr, (uint8_t *)msg, strlen(msg));
2195         g_free(msg);
2196         s->t_attrib = s->t_attrib_default;
2197     }
2198 
2199     qemu_chr_be_event(chr, CHR_EVENT_OPENED);
2200 }
2201 
2202 static void vc_chr_open(Chardev *chr,
2203                         ChardevBackend *backend,
2204                         bool *be_opened,
2205                         Error **errp)
2206 {
2207     ChardevVC *vc = backend->u.vc.data;
2208     VCChardev *drv = VC_CHARDEV(chr);
2209     QemuConsole *s;
2210     unsigned width = 0;
2211     unsigned height = 0;
2212 
2213     if (vc->has_width) {
2214         width = vc->width;
2215     } else if (vc->has_cols) {
2216         width = vc->cols * FONT_WIDTH;
2217     }
2218 
2219     if (vc->has_height) {
2220         height = vc->height;
2221     } else if (vc->has_rows) {
2222         height = vc->rows * FONT_HEIGHT;
2223     }
2224 
2225     trace_console_txt_new(width, height);
2226     if (width == 0 || height == 0) {
2227         s = new_console(NULL, TEXT_CONSOLE, 0);
2228     } else {
2229         s = new_console(NULL, TEXT_CONSOLE_FIXED_SIZE, 0);
2230         s->surface = qemu_create_displaysurface(width, height);
2231     }
2232 
2233     if (!s) {
2234         error_setg(errp, "cannot create text console");
2235         return;
2236     }
2237 
2238     s->chr = chr;
2239     drv->console = s;
2240 
2241     if (display_state) {
2242         text_console_do_init(chr, display_state);
2243     }
2244 
2245     /* console/chardev init sometimes completes elsewhere in a 2nd
2246      * stage, so defer OPENED events until they are fully initialized
2247      */
2248     *be_opened = false;
2249 }
2250 
2251 void qemu_console_resize(QemuConsole *s, int width, int height)
2252 {
2253     DisplaySurface *surface;
2254 
2255     assert(s->console_type == GRAPHIC_CONSOLE);
2256 
2257     if (s->surface && (s->surface->flags & QEMU_ALLOCATED_FLAG) &&
2258         pixman_image_get_width(s->surface->image) == width &&
2259         pixman_image_get_height(s->surface->image) == height) {
2260         return;
2261     }
2262 
2263     surface = qemu_create_displaysurface(width, height);
2264     dpy_gfx_replace_surface(s, surface);
2265 }
2266 
2267 DisplaySurface *qemu_console_surface(QemuConsole *console)
2268 {
2269     return console->surface;
2270 }
2271 
2272 PixelFormat qemu_default_pixelformat(int bpp)
2273 {
2274     pixman_format_code_t fmt = qemu_default_pixman_format(bpp, true);
2275     PixelFormat pf = qemu_pixelformat_from_pixman(fmt);
2276     return pf;
2277 }
2278 
2279 static QemuDisplay *dpys[DISPLAY_TYPE__MAX];
2280 
2281 void qemu_display_register(QemuDisplay *ui)
2282 {
2283     assert(ui->type < DISPLAY_TYPE__MAX);
2284     dpys[ui->type] = ui;
2285 }
2286 
2287 bool qemu_display_find_default(DisplayOptions *opts)
2288 {
2289     static DisplayType prio[] = {
2290         DISPLAY_TYPE_GTK,
2291         DISPLAY_TYPE_SDL,
2292         DISPLAY_TYPE_COCOA
2293     };
2294     int i;
2295 
2296     for (i = 0; i < ARRAY_SIZE(prio); i++) {
2297         if (dpys[prio[i]] == NULL) {
2298             ui_module_load_one(DisplayType_str(prio[i]));
2299         }
2300         if (dpys[prio[i]] == NULL) {
2301             continue;
2302         }
2303         opts->type = prio[i];
2304         return true;
2305     }
2306     return false;
2307 }
2308 
2309 void qemu_display_early_init(DisplayOptions *opts)
2310 {
2311     assert(opts->type < DISPLAY_TYPE__MAX);
2312     if (opts->type == DISPLAY_TYPE_NONE) {
2313         return;
2314     }
2315     if (dpys[opts->type] == NULL) {
2316         ui_module_load_one(DisplayType_str(opts->type));
2317     }
2318     if (dpys[opts->type] == NULL) {
2319         error_report("Display '%s' is not available.",
2320                      DisplayType_str(opts->type));
2321         exit(1);
2322     }
2323     if (dpys[opts->type]->early_init) {
2324         dpys[opts->type]->early_init(opts);
2325     }
2326 }
2327 
2328 void qemu_display_init(DisplayState *ds, DisplayOptions *opts)
2329 {
2330     assert(opts->type < DISPLAY_TYPE__MAX);
2331     if (opts->type == DISPLAY_TYPE_NONE) {
2332         return;
2333     }
2334     assert(dpys[opts->type] != NULL);
2335     dpys[opts->type]->init(ds, opts);
2336 }
2337 
2338 void qemu_display_help(void)
2339 {
2340     int idx;
2341 
2342     printf("Available display backend types:\n");
2343     printf("none\n");
2344     for (idx = DISPLAY_TYPE_NONE; idx < DISPLAY_TYPE__MAX; idx++) {
2345         if (!dpys[idx]) {
2346             ui_module_load_one(DisplayType_str(idx));
2347         }
2348         if (dpys[idx]) {
2349             printf("%s\n",  DisplayType_str(dpys[idx]->type));
2350         }
2351     }
2352 }
2353 
2354 void qemu_chr_parse_vc(QemuOpts *opts, ChardevBackend *backend, Error **errp)
2355 {
2356     int val;
2357     ChardevVC *vc;
2358 
2359     backend->type = CHARDEV_BACKEND_KIND_VC;
2360     vc = backend->u.vc.data = g_new0(ChardevVC, 1);
2361     qemu_chr_parse_common(opts, qapi_ChardevVC_base(vc));
2362 
2363     val = qemu_opt_get_number(opts, "width", 0);
2364     if (val != 0) {
2365         vc->has_width = true;
2366         vc->width = val;
2367     }
2368 
2369     val = qemu_opt_get_number(opts, "height", 0);
2370     if (val != 0) {
2371         vc->has_height = true;
2372         vc->height = val;
2373     }
2374 
2375     val = qemu_opt_get_number(opts, "cols", 0);
2376     if (val != 0) {
2377         vc->has_cols = true;
2378         vc->cols = val;
2379     }
2380 
2381     val = qemu_opt_get_number(opts, "rows", 0);
2382     if (val != 0) {
2383         vc->has_rows = true;
2384         vc->rows = val;
2385     }
2386 }
2387 
2388 static const TypeInfo qemu_console_info = {
2389     .name = TYPE_QEMU_CONSOLE,
2390     .parent = TYPE_OBJECT,
2391     .instance_size = sizeof(QemuConsole),
2392     .class_size = sizeof(QemuConsoleClass),
2393 };
2394 
2395 static void char_vc_class_init(ObjectClass *oc, void *data)
2396 {
2397     ChardevClass *cc = CHARDEV_CLASS(oc);
2398 
2399     cc->parse = qemu_chr_parse_vc;
2400     cc->open = vc_chr_open;
2401     cc->chr_write = vc_chr_write;
2402     cc->chr_set_echo = vc_chr_set_echo;
2403 }
2404 
2405 static const TypeInfo char_vc_type_info = {
2406     .name = TYPE_CHARDEV_VC,
2407     .parent = TYPE_CHARDEV,
2408     .instance_size = sizeof(VCChardev),
2409     .class_init = char_vc_class_init,
2410 };
2411 
2412 void qemu_console_early_init(void)
2413 {
2414     /* set the default vc driver */
2415     if (!object_class_by_name(TYPE_CHARDEV_VC)) {
2416         type_register(&char_vc_type_info);
2417     }
2418 }
2419 
2420 static void register_types(void)
2421 {
2422     type_register_static(&qemu_console_info);
2423 }
2424 
2425 type_init(register_types);
2426