Codebase list virt-viewer / 3af6f66f-fcac-40b9-ae97-df7de2bc0c33/main src / virt-viewer-util.c
3af6f66f-fcac-40b9-ae97-df7de2bc0c33/main

Tree @3af6f66f-fcac-40b9-ae97-df7de2bc0c33/main (Download .tar.gz)

virt-viewer-util.c @3af6f66f-fcac-40b9-ae97-df7de2bc0c33/mainraw · history · blame

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
/*
 * Virt Viewer: A virtual machine console viewer
 *
 * Copyright (C) 2007-2015 Red Hat, Inc.
 * Copyright (C) 2009-2012 Daniel P. Berrange
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * Author: Daniel P. Berrange <berrange@redhat.com>
 */

#include <config.h>

#include <glib.h>
#include <glib/gi18n.h>
#include <locale.h>

#ifdef G_OS_WIN32
#include <windows.h>
#include <io.h>
#endif

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <libxml/xpath.h>
#include <libxml/uri.h>

#include "virt-viewer-util.h"

GQuark
virt_viewer_error_quark(void)
{
  return g_quark_from_static_string ("virt-viewer-error-quark");
}

GtkBuilder *virt_viewer_util_load_ui(const char *name)
{
    GtkBuilder *builder;
    gchar *resource = g_strdup_printf("%s/ui/%s",
                                      VIRT_VIEWER_RESOURCE_PREFIX,
                                      name);

    builder = gtk_builder_new_from_resource(resource);

    g_free(resource);
    return builder;
}

int
virt_viewer_util_extract_host(const char *uristr,
                              char **scheme,
                              char **host,
                              char **transport,
                              char **user,
                              int *port)
{
    xmlURIPtr uri;
    char *offset = NULL;

    if (uristr == NULL ||
        !g_ascii_strcasecmp(uristr, "xen"))
        uristr = "xen:///";

    uri = xmlParseURI(uristr);
    g_return_val_if_fail(uri != NULL, 1);

    if (host) {
        if (!uri->server) {
            *host = g_strdup("localhost");
        } else {
            if (uri->server[0] == '[') {
                gchar *tmp;
                *host = g_strdup(uri->server + 1);
                if ((tmp = strchr(*host, ']')))
                    *tmp = '\0';
            } else {
                *host = g_strdup(uri->server);
            }
        }
    }

    if (user) {
        if (uri->user)
            *user = g_strdup(uri->user);
        else
            *user = NULL;
    }

    if (port)
        *port = uri->port;

    if (uri->scheme)
        offset = strchr(uri->scheme, '+');

    if (transport) {
        if (offset)
            *transport = g_strdup(offset + 1);
        else
            *transport = NULL;
    }

    if (scheme && uri->scheme) {
        if (offset)
            *scheme = g_strndup(uri->scheme, offset - uri->scheme);
        else
            *scheme = g_strdup(uri->scheme);
    }

    xmlFreeURI(uri);
    return 0;
}

typedef struct {
    GObject *instance;
    GObject *observer;
    GClosure *closure;
    gulong handler_id;
} WeakHandlerCtx;

static WeakHandlerCtx *
whc_new(GObject *instance,
        GObject *observer)
{
    WeakHandlerCtx *ctx = g_new0(WeakHandlerCtx, 1);

    ctx->instance = instance;
    ctx->observer = observer;

    return ctx;
}

static void
whc_free(WeakHandlerCtx *ctx)
{
    g_free(ctx);
}

static void observer_destroyed_cb(gpointer, GObject *);
static void closure_invalidated_cb(gpointer, GClosure *);

/*
 * If signal handlers are removed before the object is destroyed, this
 * callback will never get triggered.
 */
static void
instance_destroyed_cb(gpointer ctx_,
                      GObject *where_the_instance_was G_GNUC_UNUSED)
{
    WeakHandlerCtx *ctx = ctx_;

    /* No need to disconnect the signal here, the instance has gone away. */
    g_object_weak_unref(ctx->observer, observer_destroyed_cb, ctx);
    g_closure_remove_invalidate_notifier(ctx->closure, ctx,
                                         closure_invalidated_cb);
    whc_free(ctx);
}

/* Triggered when the observer is destroyed. */
static void
observer_destroyed_cb(gpointer ctx_,
                      GObject *where_the_observer_was G_GNUC_UNUSED)
{
    WeakHandlerCtx *ctx = ctx_;

    g_closure_remove_invalidate_notifier(ctx->closure, ctx,
                                         closure_invalidated_cb);
    g_signal_handler_disconnect(ctx->instance, ctx->handler_id);
    g_object_weak_unref(ctx->instance, instance_destroyed_cb, ctx);
    whc_free(ctx);
}

/* Triggered when either object is destroyed or the handler is disconnected. */
static void
closure_invalidated_cb(gpointer ctx_,
                       GClosure *where_the_closure_was G_GNUC_UNUSED)
{
    WeakHandlerCtx *ctx = ctx_;

    g_object_weak_unref(ctx->instance, instance_destroyed_cb, ctx);
    g_object_weak_unref(ctx->observer, observer_destroyed_cb, ctx);
    whc_free(ctx);
}

/* Copied from tp_g_signal_connect_object. */
/**
  * virt_viewer_signal_connect_object: (skip)
  * @instance: the instance to connect to.
  * @detailed_signal: a string of the form "signal-name::detail".
  * @c_handler: the #GCallback to connect.
  * @gobject: the object to pass as data to @c_handler.
  * @connect_flags: a combination of #GConnectFlags.
  *
  * Similar to g_signal_connect_object() but will delete connection
  * when any of the objects is destroyed.
  *
  * Returns: the handler id.
  */
gulong virt_viewer_signal_connect_object(gpointer instance,
                                         const gchar *detailed_signal,
                                         GCallback c_handler,
                                         gpointer gobject,
                                         GConnectFlags connect_flags)
{
    GObject *instance_obj = G_OBJECT(instance);
    WeakHandlerCtx *ctx = whc_new(instance_obj, gobject);

    g_return_val_if_fail(G_TYPE_CHECK_INSTANCE (instance), 0);
    g_return_val_if_fail(detailed_signal != NULL, 0);
    g_return_val_if_fail(c_handler != NULL, 0);
    g_return_val_if_fail(G_IS_OBJECT (gobject), 0);
    g_return_val_if_fail((connect_flags & ~(G_CONNECT_AFTER|G_CONNECT_SWAPPED)) == 0, 0);

    if (connect_flags & G_CONNECT_SWAPPED)
        ctx->closure = g_cclosure_new_object_swap(c_handler, gobject);
    else
        ctx->closure = g_cclosure_new_object(c_handler, gobject);

    ctx->handler_id = g_signal_connect_closure(instance, detailed_signal,
                                               ctx->closure, (connect_flags & G_CONNECT_AFTER) ? TRUE : FALSE);

    g_object_weak_ref(instance_obj, instance_destroyed_cb, ctx);
    g_object_weak_ref(gobject, observer_destroyed_cb, ctx);
    g_closure_add_invalidate_notifier(ctx->closure, ctx,
                                      closure_invalidated_cb);

    return ctx->handler_id;
}

static void log_handler(const gchar *log_domain,
                        GLogLevelFlags log_level,
                        const gchar *message,
                        gpointer unused_data)
{
    if (glib_check_version(2, 32, 0) != NULL)
        if (log_level >= G_LOG_LEVEL_DEBUG && !doDebug)
            return;

    g_log_default_handler(log_domain, log_level, message, unused_data);
}

#ifdef G_OS_WIN32
static BOOL is_handle_valid(HANDLE h)
{
    if (h == INVALID_HANDLE_VALUE || h == NULL)
        return FALSE;

    DWORD flags;
    return GetHandleInformation(h, &flags);
}
#endif

void virt_viewer_util_init(const char *appname)
{
#ifdef G_OS_WIN32
    /*
     * This named mutex will be kept around by Windows until the
     * process terminates. This allows other instances to check if it
     * already exists, indicating already running instances. It is
     * used to warn the user that installer can't proceed in this
     * case.
     */
    CreateMutexA(0, 0, "VirtViewerMutex");

    /* Get redirection from parent */
    BOOL out_valid = is_handle_valid(GetStdHandle(STD_OUTPUT_HANDLE));
    BOOL err_valid = is_handle_valid(GetStdHandle(STD_ERROR_HANDLE));

    /*
     * If not all output are redirected try to redirect to parent console.
     * If parent has no console (for instance as launched from GUI) just
     * rely on default (no output).
     */
    if ((!out_valid || !err_valid) && AttachConsole(ATTACH_PARENT_PROCESS)) {
        if (!out_valid) {
            freopen("CONOUT$", "w", stdout);
            dup2(fileno(stdout), STDOUT_FILENO);
        }
        if (!err_valid) {
            freopen("CONOUT$", "w", stderr);
            dup2(fileno(stderr), STDERR_FILENO);
        }
    }
#endif

    setlocale(LC_ALL, "");

#ifdef G_OS_WIN32
    gchar *base_path = g_win32_get_package_installation_directory_of_module(NULL);
    gchar *utf8_locale_dir = g_build_filename(base_path, "share", "locale", NULL);
    /* bindtextdomain's 2nd argument is not UTF-8 aware */
    gchar *locale_dir = g_win32_locale_filename_from_utf8 (utf8_locale_dir);

    g_warn_if_fail(locale_dir != NULL);
    bindtextdomain(GETTEXT_PACKAGE, locale_dir);

    g_free(base_path);
    g_free(utf8_locale_dir);
    g_free(locale_dir);
#else
    bindtextdomain(GETTEXT_PACKAGE, LOCALE_DIR);
#endif
    bind_textdomain_codeset(GETTEXT_PACKAGE, "UTF-8");
    textdomain(GETTEXT_PACKAGE);

    g_set_application_name(appname);

    g_log_set_handler(G_LOG_DOMAIN, G_LOG_LEVEL_MASK, log_handler, NULL);
}

static gchar *
ctrl_key_to_gtk_key(const gchar *key)
{
    guint i;

    static const struct {
        const char *ctrl;
        const char *gtk;
    } keys[] = {
        /* FIXME: right alt, right ctrl, right shift, cmds */
        { "alt", "<Alt>" },
        { "ralt", "<Alt>" },
        { "rightalt", "<Alt>" },
        { "right-alt", "<Alt>" },
        { "lalt", "<Alt>" },
        { "leftalt", "<Alt>" },
        { "left-alt", "<Alt>" },

        { "ctrl", "<Ctrl>" },
        { "rctrl", "<Ctrl>" },
        { "rightctrl", "<Ctrl>" },
        { "right-ctrl", "<Ctrl>" },
        { "lctrl", "<Ctrl>" },
        { "leftctrl", "<Ctrl>" },
        { "left-ctrl", "<Ctrl>" },

        { "shift", "<Shift>" },
        { "rshift", "<Shift>" },
        { "rightshift", "<Shift>" },
        { "right-shift", "<Shift>" },
        { "lshift", "<Shift>" },
        { "leftshift", "<Shift>" },
        { "left-shift", "<Shift>" },

        { "cmd", "<Ctrl>" },
        { "rcmd", "<Ctrl>" },
        { "rightcmd", "<Ctrl>" },
        { "right-cmd", "<Ctrl>" },
        { "lcmd", "<Ctrl>" },
        { "leftcmd", "<Ctrl>" },
        { "left-cmd", "<Ctrl>" },

        { "win", "<Super>" },
        { "rwin", "<Super>" },
        { "rightwin", "<Super>" },
        { "right-win", "<Super>" },
        { "lwin", "<Super>" },
        { "leftwin", "<Super>" },
        { "left-win", "<Super>" },

        { "esc", "Escape" },
        /* { "escape", "Escape" }, */

        { "ins", "Insert" },
        /* { "insert", "Insert" }, */

        { "del", "Delete" },
        /* { "delete", "Delete" }, */

        { "pgup", "Page_Up" },
        { "pageup", "Page_Up" },
        { "pgdn", "Page_Down" },
        { "pagedown", "Page_Down" },

        /* { "home", "home" }, */
        { "end", "End" },
        /* { "space", "space" }, */

        { "enter", "Return" },

        /* { "tab", "tab" }, */
        /* { "f1", "F1" }, */
        /* { "f2", "F2" }, */
        /* { "f3", "F3" }, */
        /* { "f4", "F4" }, */
        /* { "f5", "F5" }, */
        /* { "f6", "F6" }, */
        /* { "f7", "F7" }, */
        /* { "f8", "F8" }, */
        /* { "f9", "F9" }, */
        /* { "f10", "F10" }, */
        /* { "f11", "F11" }, */
        /* { "f12", "F12" } */
    };

    for (i = 0; i < G_N_ELEMENTS(keys); ++i) {
        if (g_ascii_strcasecmp(keys[i].ctrl, key) == 0)
            return g_strdup(keys[i].gtk);
    }

    return g_ascii_strup(key, -1);
}

gchar*
spice_hotkey_to_gtk_accelerator(const gchar *key)
{
    gchar *accel, **k, **keyv;

    keyv = g_strsplit(key, "+", -1);
    g_return_val_if_fail(keyv != NULL, NULL);

    for (k = keyv; *k != NULL; k++) {
        gchar *tmp = *k;
        *k = ctrl_key_to_gtk_key(tmp);
        g_free(tmp);
    }

    accel = g_strjoinv(NULL, keyv);
    g_strfreev(keyv);

    return accel;
}

static gboolean str_is_empty(const gchar *str)
{
  return ((str == NULL) || (str[0] == '\0'));
}

static gint
virt_viewer_compare_version(const gchar *s1, const gchar *s2)
{
    gint i, retval = 0;
    gchar **v1, **v2;

    if (str_is_empty(s1) && str_is_empty(s2)) {
      return 0;
    } else if (str_is_empty(s1)) {
      return -1;
    } else if (str_is_empty(s2)) {
      return 1;
    }

    v1 = g_strsplit(s1, ".", -1);
    v2 = g_strsplit(s2, ".", -1);

    for (i = 0; v1[i] && v2[i]; ++i) {
        gchar *e1 = NULL, *e2 = NULL;
        guint64 m1 = g_ascii_strtoull(v1[i], &e1, 10);
        guint64 m2 = g_ascii_strtoull(v2[i], &e2, 10);

        retval = m1 - m2;
        if (retval != 0)
            goto end;

        g_return_val_if_fail(e1 && e2, 0);
        if (*e1 || *e2) {
            g_warning("the version string contains a suffix");
            goto end;
        }
    }

    if (v1[i])
        retval = 1;
    else if (v2[i])
        retval = -1;

end:
    g_strfreev(v1);
    g_strfreev(v2);
    return retval;
}

/**
 * virt_viewer_compare_buildid:
 * @s1: a version-like string
 * @s2: a version-like string
 *
 * Compare two buildid strings: 1.1-1 > 1.0-1, 1.0-2 > 1.0-1, 1.10 > 1.7...
 *
 * String suffix (1.0rc1 etc) are not accepted, and will return 0.
 *
 * Returns: negative value if s1 < s2; zero if s1 = s2; positive value if s1 > s2.
 **/
gint
virt_viewer_compare_buildid(const gchar *s1, const gchar *s2)
{
    int ret = 0;
    GStrv split1 = NULL;
    GStrv split2 = NULL;

    split1 = g_strsplit(s1, "-", 2);
    split2 = g_strsplit(s2, "-", 2);
    if ((split1 == NULL) || (split2 == NULL)) {
      goto end;
    }
    /* Compare versions */
    ret = virt_viewer_compare_version(split1[0], split2[0]);
    if (ret != 0) {
        goto end;
    }
    if ((split1[0] == NULL) || (split2[0] == NULL)) {
      goto end;
    }

    /* Compare -release */
    ret = virt_viewer_compare_version(split1[1], split2[1]);

end:
    g_strfreev(split1);
    g_strfreev(split2);

    return ret;
}

/* simple sorting of monitors. Primary sort left-to-right, secondary sort from
 * top-to-bottom, finally by monitor id */
static int
displays_cmp(const void *p1, const void *p2, gpointer user_data)
{
    guint diff;
    GHashTable *displays = user_data;
    guint i = *(guint*)p1;
    guint j = *(guint*)p2;
    GdkRectangle *m1 = g_hash_table_lookup(displays, GINT_TO_POINTER(i));
    GdkRectangle *m2 = g_hash_table_lookup(displays, GINT_TO_POINTER(j));
    g_return_val_if_fail(m1 != NULL && m2 != NULL, 0);
    diff = m1->x - m2->x;
    if (diff == 0)
        diff = m1->y - m2->y;
    if (diff == 0)
        diff = i - j;

    return diff;
}

static void find_max_id(gpointer key,
                        gpointer value G_GNUC_UNUSED,
                        gpointer user_data)
{
    guint *max_id = user_data;
    guint id = GPOINTER_TO_INT(key);
    *max_id = MAX(*max_id, id);
}

void
virt_viewer_align_monitors_linear(GHashTable *displays)
{
    guint i;
    gint x = 0;
    guint *sorted_displays;
    guint max_id = 0;
    guint ndisplays = 0;
    GHashTableIter iter;
    gpointer key;

    g_return_if_fail(displays != NULL);

    if (g_hash_table_size(displays) == 0)
        return;

    g_hash_table_foreach(displays, find_max_id, &max_id);
    ndisplays = max_id + 1;

    sorted_displays = g_new0(guint, ndisplays);

    g_hash_table_iter_init(&iter, displays);
    while (g_hash_table_iter_next(&iter, &key, NULL))
        sorted_displays[GPOINTER_TO_INT(key)] = GPOINTER_TO_INT(key);

    g_qsort_with_data(sorted_displays, ndisplays, sizeof(guint), displays_cmp, displays);

    /* adjust monitor positions so that there's no gaps or overlap between
     * monitors */
    for (i = 0; i < ndisplays; i++) {
        guint nth = sorted_displays[i];
        g_assert(nth < ndisplays);
        GdkRectangle *rect = g_hash_table_lookup(displays, GINT_TO_POINTER(nth));
        g_return_if_fail(rect != NULL);
        rect->x = x;
        rect->y = 0;
        x += rect->width;
    }
    g_free(sorted_displays);
}

/* Shift all displays so that the monitor origin is at (0,0). This reduces the
 * size of the screen that will be required on the guest when all client
 * monitors are fullscreen but do not begin at the origin. For example, instead
 * of sending down the following configuration:
 *   1280x1024+4240+0
 * (which implies that the guest screen must be at least 5520x1024), we'd send
 *   1280x1024+0+0
 * (which implies the guest screen only needs to be 1280x1024). The first
 * version might fail if the guest video memory is not large enough to handle a
 * screen of that size.
 */
void
virt_viewer_shift_monitors_to_origin(GHashTable *displays)
{
    gint xmin = G_MAXINT;
    gint ymin = G_MAXINT;
    GHashTableIter iter;
    gpointer value;

    if (g_hash_table_size(displays) == 0)
        return;

    g_hash_table_iter_init(&iter, displays);
    while (g_hash_table_iter_next(&iter, NULL, &value)) {
        GdkRectangle *display = value;
        g_return_if_fail(display != NULL);
        if (display->width > 0 && display->height > 0) {
            xmin = MIN(xmin, display->x);
            ymin = MIN(ymin, display->y);
        }
    }
    g_return_if_fail(xmin < G_MAXINT && ymin < G_MAXINT);

    if (xmin > 0 || ymin > 0) {
        g_debug("%s: Shifting all monitors by (%i, %i)", G_STRFUNC, xmin, ymin);
        g_hash_table_iter_init(&iter, displays);
        while (g_hash_table_iter_next(&iter, NULL, &value)) {
            GdkRectangle *display = value;
            if (display->width > 0 && display->height > 0) {
                display->x -= xmin;
                display->y -= ymin;
            }
        }
    }
}

/**
 * virt_viewer_parse_monitor_mappings:
 * @mappings: (array zero-terminated=1) values for the "monitor-mapping" key
 * @nmappings: the size of @mappings
 * @nmonitors: the count of client's monitors
 *
 * Parses and validates monitor mappings values to return a hash table
 * containing the mapping from guest display ids to client monitors ids.
 *
 * Returns: (transfer full) a #GHashTable containing mapping from guest display
 *  ids to client monitor ids or %NULL if the mapping is invalid.
 */
GHashTable*
virt_viewer_parse_monitor_mappings(gchar **mappings, const gsize nmappings, const gint nmonitors)
{
    GHashTable *displaymap;
    GHashTable *monitormap;
    guint i, max_display_id = 0;
    gchar **tokens = NULL;

    g_return_val_if_fail(nmonitors != 0, NULL);
    displaymap = g_hash_table_new(g_direct_hash, g_direct_equal);
    monitormap = g_hash_table_new(g_direct_hash, g_direct_equal);
    if (nmappings == 0) {
        g_warning("Empty monitor-mapping configuration");
        goto configerror;
    }

    for (i = 0; i < nmappings; i++) {
        gchar *endptr = NULL;
        gint display = 0, monitor = 0;

        tokens = g_strsplit(mappings[i], ":", 2);
        if (g_strv_length(tokens) != 2) {
            g_warning("Invalid monitor-mapping configuration: '%s'. "
                      "Expected format is '<DISPLAY-ID>:<MONITOR-ID>'",
                      mappings[i]);
            g_strfreev(tokens);
            goto configerror;
        }

        display = strtol(tokens[0], &endptr, 10);
        if ((endptr && *endptr != '\0') || display < 1) {
            g_warning("Invalid monitor-mapping configuration: display id is invalid: %s %p='%s'", tokens[0], endptr, endptr);
            g_strfreev(tokens);
            goto configerror;
        }
        monitor = strtol(tokens[1], &endptr, 10);
        if ((endptr && *endptr != '\0') || monitor < 1) {
            g_warning("Invalid monitor-mapping configuration: monitor id '%s' is invalid", tokens[1]);
            g_strfreev(tokens);
            goto configerror;
        }
        g_strfreev(tokens);

        if (monitor > nmonitors) {
            g_warning("Invalid monitor-mapping configuration: monitor #%i for display #%i does not exist", monitor, display);
            goto configerror;
        }

        /* config file format is 1-based, not 0-based */
        display--;
        monitor--;

        if (g_hash_table_lookup_extended(displaymap, GINT_TO_POINTER(display), NULL, NULL) ||
            g_hash_table_lookup_extended(monitormap, GINT_TO_POINTER(monitor), NULL, NULL)) {
            g_warning("Invalid monitor-mapping configuration: a display or monitor id was specified twice");
            goto configerror;
        }
        g_debug("Fullscreen config: mapping guest display %i to monitor %i", display, monitor);
        g_hash_table_insert(displaymap, GINT_TO_POINTER(display), GINT_TO_POINTER(monitor));
        g_hash_table_insert(monitormap, GINT_TO_POINTER(monitor), GINT_TO_POINTER(display));
        max_display_id = MAX((guint) display, max_display_id);
    }

    for (i = 0; i < max_display_id; i++) {
        if (!g_hash_table_lookup_extended(displaymap, GINT_TO_POINTER(i), NULL, NULL)) {
            g_warning("Invalid monitor-mapping configuration: display #%d was not specified", i+1);
            goto configerror;
        }
    }

    g_hash_table_unref(monitormap);
    return displaymap;

configerror:
    g_hash_table_unref(monitormap);
    g_hash_table_unref(displaymap);
    return NULL;
}

/*
 * Local variables:
 *  c-indent-level: 4
 *  c-basic-offset: 4
 *  indent-tabs-mode: nil
 * End:
 */