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