summaryrefslogtreecommitdiff
path: root/utils.c
blob: 489c7944cbc4ab984baa0bf474c2c4f230f8f5d8 (plain)
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
/* Camicro - Microscope camera viewer.
 *
 * Copyright (C) 2019 Nicolas Schodet
 *
 * 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.
 *
 * Contact :
 *        Web: http://ni.fr.eu.org/
 *      Email: <nico at ni.fr.eu.org>
 */
#define _GNU_SOURCE
#include <errno.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#include "utils.h"

void
utils_fatal(const char *fmt, ...)
{
    va_list ap;
    fprintf(stderr, "%s: ", program_invocation_short_name);
    va_start(ap, fmt);
    vfprintf(stderr, fmt, ap);
    va_end(ap);
    fputc('\n', stderr);
    exit(EXIT_FAILURE);
}

void
utils_info(const char *fmt, ...)
{
    va_list ap;
    fprintf(stderr, "%s: ", program_invocation_short_name);
    va_start(ap, fmt);
    vfprintf(stderr, fmt, ap);
    va_end(ap);
    fputc('\n', stderr);
}

void *
utils_malloc(size_t size)
{
    void *m = malloc(size);
    if (!m)
	utils_fatal("memory exhausted");
    return m;
}

void
utils_delay_us(int us)
{
    struct timespec delay, remaining;
    delay.tv_sec = us / 1000000;
    delay.tv_nsec = us % 1000000 * 1000;
    while (nanosleep(&delay, &remaining) == -1) {
	if (errno == EINTR)
	    delay = remaining;
	else
	    utils_fatal("can not sleep: %m");
    }
}

void
utils_dialog_error(GtkWindow *parent, const char *fmt, ...)
{
    va_list ap;
    char *msg;
    va_start(ap, fmt);
    if (vasprintf(&msg, fmt, ap) == -1)
	utils_fatal("memory exhausted");
    va_end(ap);
    GtkWidget *dialog = gtk_message_dialog_new(parent, GTK_DIALOG_MODAL,
	    GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE, "%s", msg);
    gtk_dialog_run(GTK_DIALOG(dialog));
    gtk_widget_destroy(dialog);
    free(msg);
}