summaryrefslogtreecommitdiff
blob: 728effd58edce594b002306c4e9d9a783df8079e (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
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
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
/* Copyright (C) 2001-2020 Artifex Software, Inc.
   All Rights Reserved.

   This software is provided AS-IS with no warranty, either express or
   implied.

   This software is distributed under license and may not be copied,
   modified or distributed except as expressly authorized under the terms
   of the license contained in the file LICENSE in this distribution.

   Refer to licensing information at http://www.artifex.com or contact
   Artifex Software, Inc.,  1305 Grant Avenue - Suite 200, Novato,
   CA 94945, U.S.A., +1(415)492-9861, for further information.
*/


/* dxmain.c */
/*
 * Ghostscript frontend which provides a graphical window
 * using Gtk+.  Load time linking to libgs.so
 * Compile using
 *    gcc `gtk-config --cflags` -o gs dxmain.c -lgs `gtk-config --libs`
 *
 * The ghostscript library needs to be compiled with
 *  gcc -fPIC -g -c -Wall file.c
 *  gcc -shared -Wl,-soname,libgs.so.6 -o libgs.so.6.60 file.o -lc
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <locale.h>
#include <gtk/gtk.h>
#define __PROTOTYPES__
#include "ierrors.h"
#include "iapi.h"
#include "gdevdsp.h"

const char start_string[] = "systemdict /start get exec\n";

static gboolean read_stdin_handler(GIOChannel *channel, GIOCondition condition,
        gpointer data);
static int gsdll_stdin(void *instance, char *buf, int len);
static int gsdll_stdout(void *instance, const char *str, int len);
static int gsdll_stdout(void *instance, const char *str, int len);
static int display_open(void *handle, void *device);
static int display_preclose(void *handle, void *device);
static int display_close(void *handle, void *device);
static int display_presize(void *handle, void *device, int width, int height,
        int raster, unsigned int format);
static int display_size(void *handle, void *device, int width, int height,
        int raster, unsigned int format, unsigned char *pimage);
static int display_sync(void *handle, void *device);
static int display_page(void *handle, void *device, int copies, int flush);
static int display_update(void *handle, void *device, int x, int y,
        int w, int h);

#ifndef min
#define min(a,b) ((a) < (b) ? (a) : (b))
#endif

/*********************************************************************/
/* stdio functions */

struct stdin_buf {
   char *buf;
   int len;	/* length of buffer */
   int count;	/* number of characters returned */
};

/* handler for reading non-blocking stdin */
static gboolean
read_stdin_handler(GIOChannel *channel, GIOCondition condition, gpointer data)
{
    struct stdin_buf *input = (struct stdin_buf *)data;
    GError *error = NULL;
    gsize c;

    if (condition & (G_IO_PRI)) {
        g_print("input exception");
        input->count = 0;	/* EOF */
    }
    else if (condition & (G_IO_IN)) {
        g_io_channel_read_chars(channel, input->buf, input->len, &c, &error);
        input->count = (int)c;
        if (error) {
            g_print("%s\n", error->message);
            g_error_free(error);
        }
    }
    else {
        g_print("input condition unknown");
        input->count = 0;	/* EOF */
    }
    return TRUE;
}

/* callback for reading stdin */
static int
gsdll_stdin(void *instance, char *buf, int len)
{
    struct stdin_buf input;
    gint input_tag;
    GIOChannel *channel;
    GError *error = NULL;

    input.len = len;
    input.buf = buf;
    input.count = -1;

    channel = g_io_channel_unix_new(fileno(stdin));
    g_io_channel_set_encoding(channel, NULL, &error);
    g_io_channel_set_buffered(channel, FALSE);
    if (error) {
        g_print("%s\n", error->message);
        g_error_free(error);
    }
    input_tag = g_io_add_watch(channel,
        (G_IO_IN | G_IO_PRI | G_IO_ERR | G_IO_HUP),
        read_stdin_handler, &input);
    while (input.count < 0)
        gtk_main_iteration_do(TRUE);
    g_source_remove(input_tag);
    g_io_channel_unref(channel);

    return input.count;
}

static int
gsdll_stdout(void *instance, const char *str, int len)
{
    gtk_main_iteration_do(FALSE);
    fwrite(str, 1, len, stdout);
    fflush(stdout);
    return len;
}

static int
gsdll_stderr(void *instance, const char *str, int len)
{
    gtk_main_iteration_do(FALSE);
    fwrite(str, 1, len, stderr);
    fflush(stderr);
    return len;
}


/*********************************************************************/
/* dll display device */

typedef struct IMAGE_DEVICEN_S IMAGE_DEVICEN;
struct IMAGE_DEVICEN_S {
    int used;		/* non-zero if in use */
    int visible;	/* show on window */
    char name[64];
    int cyan;
    int magenta;
    int yellow;
    int black;
    int menu;		/* non-zero if menu item added to system menu */
};
#define IMAGE_DEVICEN_MAX 8

typedef struct IMAGE_S IMAGE;
struct IMAGE_S {
    void *handle;
    void *device;
    GtkWidget *window;
    GtkWidget *vbox;
    GtkWidget *cmyk_bar;
    GtkWidget *separation[IMAGE_DEVICEN_MAX];
    GtkWidget *show_as_gray;
    GtkWidget *scroll;
    GtkWidget *darea;
    guchar *buf;
    gint width;
    gint height;
    gint rowstride;
    unsigned int format;
    int devicen_gray;	/* true if a single separation should be shown gray */
    IMAGE_DEVICEN devicen[IMAGE_DEVICEN_MAX];
    guchar *rgbbuf;	/* used when we need to convert raster format */
    IMAGE *next;
};

IMAGE *first_image;
static IMAGE *image_find(void *handle, void *device);
static void window_destroy(GtkWidget *w, gpointer data);
static void window_create(IMAGE *img);
static void window_resize(IMAGE *img);
#if !GTK_CHECK_VERSION(3, 0, 0)
static gboolean window_draw(GtkWidget *widget, GdkEventExpose *event, gpointer user_data);
#else
static gboolean window_draw(GtkWidget *widget, cairo_t *cr, gpointer user_data);
#endif

static IMAGE *
image_find(void *handle, void *device)
{
    IMAGE *img;
    for (img = first_image; img!=0; img=img->next) {
        if ((img->handle == handle) && (img->device == device))
            return img;
    }
    return NULL;
}

static gboolean
#if !GTK_CHECK_VERSION(3, 0, 0)
window_draw(GtkWidget *widget, GdkEventExpose *event, gpointer user_data)
#else
window_draw(GtkWidget *widget, cairo_t *cr, gpointer user_data)
#endif
{
    IMAGE *img = (IMAGE *)user_data;
    if (img && img->window && img->buf) {
        GdkPixbuf *pixbuf = NULL;
        int color = img->format & DISPLAY_COLORS_MASK;
        int depth = img->format & DISPLAY_DEPTH_MASK;
#if GTK_CHECK_VERSION(3, 0, 0)
        guint width, height;
#endif

#if !GTK_CHECK_VERSION(3, 0, 0)
        cairo_t *cr = gdk_cairo_create(gtk_widget_get_window(widget));
        gdk_cairo_region(cr, event->region);
        cairo_clip(cr);
#endif
#if GTK_CHECK_VERSION(3, 0, 0)
        width = gtk_widget_get_allocated_width (widget);
        height = gtk_widget_get_allocated_height (widget);
        gtk_render_background(gtk_widget_get_style_context(widget), cr, 0, 0, width, height);
#else
        gdk_cairo_set_source_color(cr, &gtk_widget_get_style(widget)->bg[GTK_STATE_NORMAL]);
#endif
        cairo_paint(cr);
            switch (color) {
                case DISPLAY_COLORS_NATIVE:
                    if (depth == DISPLAY_DEPTH_8 && img->rgbbuf)
                        pixbuf = gdk_pixbuf_new_from_data(img->rgbbuf,
                            GDK_COLORSPACE_RGB, FALSE, 8,
                            img->width, img->height, img->width*3,
                            NULL, NULL);
                    else if ((depth == DISPLAY_DEPTH_16) && img->rgbbuf)
                        pixbuf = gdk_pixbuf_new_from_data(img->rgbbuf,
                            GDK_COLORSPACE_RGB, FALSE, 8,
                            img->width, img->height, img->width*3,
                            NULL, NULL);
                    break;
                case DISPLAY_COLORS_GRAY:
                    if (depth == DISPLAY_DEPTH_8 && img->rgbbuf)
                        pixbuf = gdk_pixbuf_new_from_data(img->rgbbuf,
                            GDK_COLORSPACE_RGB, FALSE, 8,
                            img->width, img->height, img->width*3,
                            NULL, NULL);
                    break;
                case DISPLAY_COLORS_RGB:
                    if (depth == DISPLAY_DEPTH_8) {
                        if (img->rgbbuf)
                            pixbuf = gdk_pixbuf_new_from_data(img->rgbbuf,
                                GDK_COLORSPACE_RGB, FALSE, 8,
                                img->width, img->height, img->width*3,
                                NULL, NULL);
                        else
                            pixbuf = gdk_pixbuf_new_from_data(img->buf,
                                GDK_COLORSPACE_RGB, FALSE, 8,
                                img->width, img->height, img->rowstride,
                                NULL, NULL);
                    }
                    break;
                case DISPLAY_COLORS_CMYK:
                    if (((depth == DISPLAY_DEPTH_1) ||
                        (depth == DISPLAY_DEPTH_8)) && img->rgbbuf)
                        pixbuf = gdk_pixbuf_new_from_data(img->rgbbuf,
                            GDK_COLORSPACE_RGB, FALSE, 8,
                            img->width, img->height, img->width*3,
                            NULL, NULL);
                    break;
                case DISPLAY_COLORS_SEPARATION:
                    if ((depth == DISPLAY_DEPTH_8) && img->rgbbuf)
                        pixbuf = gdk_pixbuf_new_from_data(img->rgbbuf,
                            GDK_COLORSPACE_RGB, FALSE, 8,
                            img->width, img->height, img->width*3,
                            NULL, NULL);
                    break;
            }
            if (pixbuf) gdk_cairo_set_source_pixbuf(cr, pixbuf, 0, 0);
            cairo_paint(cr);
#if !GTK_CHECK_VERSION(3, 0, 0)
            cairo_destroy(cr);
#endif
            if (pixbuf) g_object_unref(pixbuf);
    }
    return TRUE;
}

static void window_destroy(GtkWidget *w, gpointer data)
{
    IMAGE *img = (IMAGE *)data;
    img->window = NULL;
    img->scroll = NULL;
    img->darea = NULL;
}

static void window_create(IMAGE *img)
{
    /* Create a gtk window */
    img->window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    gtk_window_set_title(GTK_WINDOW(img->window), "gs");
#if !GTK_CHECK_VERSION(3, 0, 0)
    img->vbox = gtk_vbox_new(FALSE, 0);
#else
    img->vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
    gtk_box_set_homogeneous(GTK_BOX (img->vbox), FALSE);
#endif
    gtk_container_add(GTK_CONTAINER(img->window), img->vbox);
    gtk_widget_show(img->vbox);

    img->darea = gtk_drawing_area_new();
    gtk_widget_show(img->darea);
    img->scroll = gtk_scrolled_window_new(NULL, NULL);
    gtk_widget_show(img->scroll);
    gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(img->scroll),
        GTK_POLICY_ALWAYS, GTK_POLICY_ALWAYS);

    gtk_container_add(GTK_CONTAINER(img->scroll), img->darea);

    gtk_box_pack_start(GTK_BOX(img->vbox), img->scroll, TRUE, TRUE, 0);
#if !GTK_CHECK_VERSION(3, 0, 0)
    g_signal_connect(G_OBJECT (img->darea), "expose-event",
#else
    g_signal_connect(G_OBJECT (img->darea), "draw",
#endif
                        G_CALLBACK (window_draw), img);
    g_signal_connect(G_OBJECT (img->window), "destroy",
                        G_CALLBACK (window_destroy), img);
    g_signal_connect(G_OBJECT (img->window), "delete-event",
                        G_CALLBACK (gtk_widget_hide_on_delete), NULL);
    /* do not show img->window until we know the image size */
}

static void window_resize(IMAGE *img)
{
    gboolean visible;
    gtk_widget_set_size_request(GTK_WIDGET (img->darea),
        img->width, img->height);

#if !GTK_CHECK_VERSION(3, 0, 0)
    visible = (GTK_WIDGET_FLAGS(img->window) & GTK_VISIBLE);
#else
    visible = gtk_widget_get_visible(img->window);
#endif

    if (!visible) {
        /* We haven't yet shown the window, so set a default size
         * which is smaller than the desktop to allow room for
         * desktop toolbars, and if possible a little larger than
         * the image to allow room for the scroll bars.
         * We don't know the width of the scroll bars, so just guess. */
#if !GTK_CHECK_VERSION(3, 0, 0)
        gtk_window_set_default_size(GTK_WINDOW(img->window),
            min(gdk_screen_width()-96, img->width+24),
            min(gdk_screen_height()-96, img->height+24));
#else
        guint width, height;
        width = gtk_widget_get_allocated_width (img->window) - 96;
        height = gtk_widget_get_allocated_height (img->window) - 96;
        gtk_window_set_default_size(GTK_WINDOW(img->window),
            min(width, img->width+24),
            min(height, img->height+24));
#endif
    }
}

static void window_separation(IMAGE *img, int sep)
{
    img->devicen[sep].visible = !img->devicen[sep].visible;
    display_sync(img->handle, img->device);
}

static void signal_sep0(GtkWidget *w, gpointer data)
{
    window_separation((IMAGE *)data, 0);
}

static void signal_sep1(GtkWidget *w, gpointer data)
{
    window_separation((IMAGE *)data, 1);
}

static void signal_sep2(GtkWidget *w, gpointer data)
{
    window_separation((IMAGE *)data, 2);
}

static void signal_sep3(GtkWidget *w, gpointer data)
{
    window_separation((IMAGE *)data, 3);
}

static void signal_sep4(GtkWidget *w, gpointer data)
{
    window_separation((IMAGE *)data, 4);
}

static void signal_sep5(GtkWidget *w, gpointer data)
{
    window_separation((IMAGE *)data, 5);
}

static void signal_sep6(GtkWidget *w, gpointer data)
{
    window_separation((IMAGE *)data, 6);
}

static void signal_sep7(GtkWidget *w, gpointer data)
{
    window_separation((IMAGE *)data, 7);
}

GCallback signal_separation[IMAGE_DEVICEN_MAX] = {
    (GCallback)signal_sep0,
    (GCallback)signal_sep1,
    (GCallback)signal_sep2,
    (GCallback)signal_sep3,
    (GCallback)signal_sep4,
    (GCallback)signal_sep5,
    (GCallback)signal_sep6,
    (GCallback)signal_sep7
};

static GtkWidget *
window_add_button(IMAGE *img, const char *label, GCallback fn)
{
    GtkWidget *w;
    w = gtk_check_button_new_with_label(label);
    gtk_box_pack_start(GTK_BOX(img->cmyk_bar), w, FALSE, FALSE, 5);
    gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(w), TRUE);
    g_signal_connect(G_OBJECT(w), "clicked", fn, img);
    gtk_widget_show(w);
    return w;
}

static void signal_show_as_gray(GtkWidget *w, gpointer data)
{
    IMAGE *img= (IMAGE *)data;
    img->devicen_gray= !img->devicen_gray;
    display_sync(img->handle, img->device);
}

/* New device has been opened */
static int display_open(void *handle, void *device)
{

    IMAGE *img = (IMAGE *)malloc(sizeof(IMAGE));
    if (img == NULL)
        return -1;
    memset(img, 0, sizeof(IMAGE));

    /* add to list */
    if (first_image)
        img->next = first_image;
    first_image = img;

    /* remember device and handle */
    img->handle = handle;
    img->device = device;

    /* create window */
    window_create(img);

    gtk_main_iteration_do(FALSE);
    return 0;
}

static int display_preclose(void *handle, void *device)
{
    IMAGE *img = image_find(handle, device);
    if (img == NULL)
        return -1;

    gtk_main_iteration_do(FALSE);

    img->buf = NULL;
    img->width = 0;
    img->height = 0;
    img->rowstride = 0;
    img->format = 0;

    gtk_widget_destroy(img->window);
    img->window = NULL;
    img->scroll = NULL;
    img->darea = NULL;
    if (img->rgbbuf)
        free(img->rgbbuf);
    img->rgbbuf = NULL;

    gtk_main_iteration_do(FALSE);

    return 0;
}

static int display_close(void *handle, void *device)
{
    IMAGE *img = image_find(handle, device);
    if (img == NULL)
        return -1;

    /* remove from list */
    if (img == first_image) {
        first_image = img->next;
    }
    else {
        IMAGE *tmp;
        for (tmp = first_image; tmp!=0; tmp=tmp->next) {
            if (img == tmp->next)
                tmp->next = img->next;
        }
    }

    return 0;
}

static int display_presize(void *handle, void *device, int width, int height,
        int raster, unsigned int format)
{
    /* Assume everything is OK.
     * It would be better to return gs_error_rangecheck if we can't
     * support the format.
     */
    return 0;
}

static int display_size(void *handle, void *device, int width, int height,
        int raster, unsigned int format, unsigned char *pimage)
{
    IMAGE *img = image_find(handle, device);
    int color;
    int depth;
    int i;
    gboolean visible;

    if (img == NULL)
        return -1;

    if (img->rgbbuf)
        free(img->rgbbuf);
    img->rgbbuf = NULL;

    img->width = width;
    img->height = height;
    img->rowstride = raster;
    img->buf = pimage;
    img->format = format;

    /* Reset separations */
    for (i=0; i<IMAGE_DEVICEN_MAX; i++) {
        img->devicen[i].used = 0;
        img->devicen[i].visible = 1;
        memset(img->devicen[i].name, 0, sizeof(img->devicen[i].name));
        img->devicen[i].cyan = 0;
        img->devicen[i].magenta = 0;
        img->devicen[i].yellow = 0;
        img->devicen[i].black = 0;
    }

    color = img->format & DISPLAY_COLORS_MASK;
    depth = img->format & DISPLAY_DEPTH_MASK;
    switch (color) {
        case DISPLAY_COLORS_NATIVE:
            if (depth == DISPLAY_DEPTH_8) {
                img->rgbbuf = (guchar *)malloc(width * height * 3);
                if (img->rgbbuf == NULL)
                    return -1;
                break;
            }
            else if (depth == DISPLAY_DEPTH_16) {
                /* need to convert to 24RGB */
                img->rgbbuf = (guchar *)malloc(width * height * 3);
                if (img->rgbbuf == NULL)
                    return -1;
            }
            else
                return gs_error_rangecheck;	/* not supported */
        case DISPLAY_COLORS_GRAY:
            if (depth == DISPLAY_DEPTH_8) {
                img->rgbbuf = (guchar *)malloc(width * height * 3);
                if (img->rgbbuf == NULL)
                    return -1;
                break;
            }
            else
                return -1;	/* not supported */
        case DISPLAY_COLORS_RGB:
            if (depth == DISPLAY_DEPTH_8) {
                if (((img->format & DISPLAY_ALPHA_MASK) == DISPLAY_ALPHA_NONE)
                    && ((img->format & DISPLAY_ENDIAN_MASK)
                        == DISPLAY_BIGENDIAN))
                    break;
                else {
                    /* need to convert to 24RGB */
                    img->rgbbuf = (guchar *)malloc(width * height * 3);
                    if (img->rgbbuf == NULL)
                        return -1;
                }
            }
            else
                return -1;	/* not supported */
            break;
        case DISPLAY_COLORS_CMYK:
            if ((depth == DISPLAY_DEPTH_1) || (depth == DISPLAY_DEPTH_8)) {
                /* need to convert to 24RGB */
                img->rgbbuf = (guchar *)malloc(width * height * 3);
                if (img->rgbbuf == NULL)
                    return -1;
                /* We already know about the CMYK components */
                img->devicen[0].used = 1;
                img->devicen[0].cyan = 65535;
                strncpy(img->devicen[0].name, "Cyan",
                    sizeof(img->devicen[0].name));
                img->devicen[1].used = 1;
                img->devicen[1].magenta = 65535;
                strncpy(img->devicen[1].name, "Magenta",
                    sizeof(img->devicen[1].name));
                img->devicen[2].used = 1;
                img->devicen[2].yellow = 65535;
                strncpy(img->devicen[2].name, "Yellow",
                    sizeof(img->devicen[2].name));
                img->devicen[3].used = 1;
                img->devicen[3].black = 65535;
                strncpy(img->devicen[3].name, "Black",
                    sizeof(img->devicen[3].name));
            }
            else
                return -1;	/* not supported */
            break;
        case DISPLAY_COLORS_SEPARATION:
            /* we can't display this natively */
            /* we will convert it just before displaying */
            if (depth != DISPLAY_DEPTH_8)
                return -1;	/* not supported */
            img->rgbbuf = (guchar *)malloc(width * height * 3);
            if (img->rgbbuf == NULL)
                return -1;
            break;
    }

    if ((color == DISPLAY_COLORS_CMYK) ||
        (color == DISPLAY_COLORS_SEPARATION)) {
        if (!GTK_IS_WIDGET(img->cmyk_bar)) {
            /* add bar to select separation */
#if !GTK_CHECK_VERSION(3, 0, 0)
            img->cmyk_bar = gtk_hbox_new(FALSE, 0);
#else
            img->cmyk_bar = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0);
            gtk_box_set_homogeneous(GTK_BOX(img->cmyk_bar), FALSE);
#endif
            gtk_box_pack_start(GTK_BOX(img->vbox), img->cmyk_bar,
                FALSE, FALSE, 0);
            for (i=0; i<IMAGE_DEVICEN_MAX; i++) {
               img->separation[i] =
                window_add_button(img, img->devicen[i].name,
                   signal_separation[i]);
            }
            img->show_as_gray = gtk_check_button_new_with_label("Show as Gray");
            gtk_box_pack_end(GTK_BOX(img->cmyk_bar), img->show_as_gray,
                FALSE, FALSE, 5);
            gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(img->show_as_gray),
                FALSE);
            g_signal_connect(G_OBJECT(img->show_as_gray), "clicked",
                G_CALLBACK(signal_show_as_gray), img);
            gtk_widget_show(img->show_as_gray);
        }
        gtk_widget_show(img->cmyk_bar);
    }
    else {
        if (GTK_IS_WIDGET(img->cmyk_bar))
            gtk_widget_hide(img->cmyk_bar);
    }

    window_resize(img);

#if !GTK_CHECK_VERSION(3, 0, 0)
    visible = (GTK_WIDGET_FLAGS(img->window) & GTK_VISIBLE);
#else
    visible = gtk_widget_get_visible(img->window);
#endif

    if (!visible) gtk_widget_show_all(img->window);

    gtk_main_iteration_do(FALSE);
    return 0;
}

static int display_sync(void *handle, void *device)
{
    IMAGE *img = image_find(handle, device);
    int color;
    int depth;
    int endian;
    int native555;
    int alpha;
    gboolean visible;

    if (img == NULL)
        return -1;

    color = img->format & DISPLAY_COLORS_MASK;
    depth = img->format & DISPLAY_DEPTH_MASK;
    endian = img->format & DISPLAY_ENDIAN_MASK;
    native555 = img->format & DISPLAY_555_MASK;
    alpha = img->format & DISPLAY_ALPHA_MASK;

    if ((color == DISPLAY_COLORS_CMYK) ||
        (color == DISPLAY_COLORS_SEPARATION)) {
        /* check if separations have changed */
        int i;
        const gchar *str;
        for (i=0; i<IMAGE_DEVICEN_MAX; i++) {
            str = gtk_label_get_text(
                GTK_LABEL(gtk_bin_get_child(GTK_BIN(img->separation[i]))));
            if (!img->devicen[i].used)
                gtk_widget_hide(img->separation[i]);
            else if (strcmp(img->devicen[i].name, str) != 0) {
                /* text has changed, update it */
                gtk_label_set_text(
                    GTK_LABEL(gtk_bin_get_child(GTK_BIN(img->separation[i]))),
                    img->devicen[i].name);
                gtk_widget_show(img->separation[i]);
            }
        }
    }

    /* some formats need to be converted for use by GdkRgb */
    switch (color) {
        case DISPLAY_COLORS_NATIVE:
            if (depth == DISPLAY_DEPTH_16) {
              if (endian == DISPLAY_LITTLEENDIAN) {
                if (native555 == DISPLAY_NATIVE_555) {
                    /* BGR555 */
                    int x, y;
                    unsigned short w;
                    unsigned char value;
                    unsigned char *s, *d;
                    for (y = 0; y<img->height; y++) {
                        s = img->buf + y * img->rowstride;
                        d = img->rgbbuf + y * img->width * 3;
                        for (x=0; x<img->width; x++) {
                            w = s[0] + (s[1] << 8);
                            value = (w >> 10) & 0x1f;	/* red */
                            *d++ = (value << 3) + (value >> 2);
                            value = (w >> 5) & 0x1f;	/* green */
                            *d++ = (value << 3) + (value >> 2);
                            value = w & 0x1f;		/* blue */
                            *d++ = (value << 3) + (value >> 2);
                            s += 2;
                        }
                    }
                }
                else {
                    /* BGR565 */
                    int x, y;
                    unsigned short w;
                    unsigned char value;
                    unsigned char *s, *d;
                    for (y = 0; y<img->height; y++) {
                        s = img->buf + y * img->rowstride;
                        d = img->rgbbuf + y * img->width * 3;
                        for (x=0; x<img->width; x++) {
                            w = s[0] + (s[1] << 8);
                            value = (w >> 11) & 0x1f;	/* red */
                            *d++ = (value << 3) + (value >> 2);
                            value = (w >> 5) & 0x3f;	/* green */
                            *d++ = (value << 2) + (value >> 4);
                            value = w & 0x1f;		/* blue */
                            *d++ = (value << 3) + (value >> 2);
                            s += 2;
                        }
                    }
                }
              }
              else {
                if (native555 == DISPLAY_NATIVE_555) {
                    /* RGB555 */
                    int x, y;
                    unsigned short w;
                    unsigned char value;
                    unsigned char *s, *d;
                    for (y = 0; y<img->height; y++) {
                        s = img->buf + y * img->rowstride;
                        d = img->rgbbuf + y * img->width * 3;
                        for (x=0; x<img->width; x++) {
                            w = s[1] + (s[0] << 8);
                            value = (w >> 10) & 0x1f;	/* red */
                            *d++ = (value << 3) + (value >> 2);
                            value = (w >> 5) & 0x1f;	/* green */
                            *d++ = (value << 3) + (value >> 2);
                            value = w & 0x1f;		/* blue */
                            *d++ = (value << 3) + (value >> 2);
                            s += 2;
                        }
                    }
                }
                else {
                    /* RGB565 */
                    int x, y;
                    unsigned short w;
                    unsigned char value;
                    unsigned char *s, *d;
                    for (y = 0; y<img->height; y++) {
                        s = img->buf + y * img->rowstride;
                        d = img->rgbbuf + y * img->width * 3;
                        for (x=0; x<img->width; x++) {
                            w = s[1] + (s[0] << 8);
                            value = (w >> 11) & 0x1f;	/* red */
                            *d++ = (value << 3) + (value >> 2);
                            value = (w >> 5) & 0x3f;	/* green */
                            *d++ = (value << 2) + (value >> 4);
                            value = w & 0x1f;		/* blue */
                            *d++ = (value << 3) + (value >> 2);
                            s += 2;
                        }
                    }
                }
              }
            }
            if (depth == DISPLAY_DEPTH_8) {
                /* palette of 96 colors */
                guchar color[96][3];
                int i;
                int one = 255 / 3;
                int x, y;
                unsigned char *s, *d;

                for (i=0; i<96; i++) {
                    /* 0->63 = 00RRGGBB, 64->95 = 010YYYYY */
                    if (i < 64) {
                        color[i][0] =
                            ((i & 0x30) >> 4) * one; /* r */
                        color[i][1] =
                            ((i & 0x0c) >> 2) * one; /* g */
                        color[i][2] =
                            (i & 0x03) * one; /* b */
                    }
                    else {
                        int val = i & 0x1f;
                        val = (val << 3) + (val >> 2);
                        color[i][0] = color[i][1] = color[i][2] = val;
                    }
                }

                for (y = 0; y<img->height; y++) {
                    s = img->buf + y * img->rowstride;
                    d = img->rgbbuf + y * img->width * 3;
                    for (x=0; x<img->width; x++) {
                            *d++ = color[*s][0];	/* r */
                            *d++ = color[*s][1];	/* g */
                            *d++ = color[*s][2];	/* b */
                            s++;
                    }
                }
            }
            break;
        case DISPLAY_COLORS_GRAY:
            if (depth == DISPLAY_DEPTH_8) {
                int x, y;
                unsigned char *s, *d;
                for (y = 0; y<img->height; y++) {
                    s = img->buf + y * img->rowstride;
                    d = img->rgbbuf + y * img->width * 3;
                    for (x=0; x<img->width; x++) {
                            *d++ = *s;	/* r */
                            *d++ = *s;	/* g */
                            *d++ = *s;	/* b */
                            s++;
                    }
                }
            }
            break;
        case DISPLAY_COLORS_RGB:
            if ( (depth == DISPLAY_DEPTH_8) &&
                 ((alpha == DISPLAY_ALPHA_FIRST) ||
                  (alpha == DISPLAY_UNUSED_FIRST)) &&
                 (endian == DISPLAY_BIGENDIAN) ) {
                /* Mac format */
                int x, y;
                unsigned char *s, *d;
                for (y = 0; y<img->height; y++) {
                    s = img->buf + y * img->rowstride;
                    d = img->rgbbuf + y * img->width * 3;
                    for (x=0; x<img->width; x++) {
                        s++;		/* x = filler */
                        *d++ = *s++;	/* r */
                        *d++ = *s++;	/* g */
                        *d++ = *s++;	/* b */
                    }
                }
            }
            else if ( (depth == DISPLAY_DEPTH_8) &&
                      (endian == DISPLAY_LITTLEENDIAN) ) {
                if ((alpha == DISPLAY_UNUSED_LAST) ||
                    (alpha == DISPLAY_ALPHA_LAST)) {
                    /* Windows format + alpha = BGRx */
                    int x, y;
                    unsigned char *s, *d;
                    for (y = 0; y<img->height; y++) {
                        s = img->buf + y * img->rowstride;
                        d = img->rgbbuf + y * img->width * 3;
                        for (x=0; x<img->width; x++) {
                            *d++ = s[2];	/* r */
                            *d++ = s[1];	/* g */
                            *d++ = s[0];	/* b */
                            s += 4;
                        }
                    }
                }
                else if ((alpha == DISPLAY_UNUSED_FIRST) ||
                    (alpha == DISPLAY_ALPHA_FIRST)) {
                    /* xBGR */
                    int x, y;
                    unsigned char *s, *d;
                    for (y = 0; y<img->height; y++) {
                        s = img->buf + y * img->rowstride;
                        d = img->rgbbuf + y * img->width * 3;
                        for (x=0; x<img->width; x++) {
                            *d++ = s[3];	/* r */
                            *d++ = s[2];	/* g */
                            *d++ = s[1];	/* b */
                            s += 4;
                        }
                    }
                }
                else {
                    /* Windows BGR24 */
                    int x, y;
                    unsigned char *s, *d;
                    for (y = 0; y<img->height; y++) {
                        s = img->buf + y * img->rowstride;
                        d = img->rgbbuf + y * img->width * 3;
                        for (x=0; x<img->width; x++) {
                            *d++ = s[2];	/* r */
                            *d++ = s[1];	/* g */
                            *d++ = s[0];	/* b */
                            s += 3;
                        }
                    }
                }
            }
            break;
        case DISPLAY_COLORS_CMYK:
            if (depth == DISPLAY_DEPTH_8) {
                /* Separations */
                int x, y;
                int cyan, magenta, yellow, black;
                unsigned char *s, *d;
                int vc = img->devicen[0].visible;
                int vm = img->devicen[1].visible;
                int vy = img->devicen[2].visible;
                int vk = img->devicen[3].visible;
                int vall = vc && vm && vy && vk;
                int show_gray = (vc + vm + vy + vk == 1) && img->devicen_gray;
                for (y = 0; y<img->height; y++) {
                    s = img->buf + y * img->rowstride;
                    d = img->rgbbuf + y * img->width * 3;
                    for (x=0; x<img->width; x++) {
                        cyan = *s++;
                        magenta = *s++;
                        yellow = *s++;
                        black = *s++;
                        if (!vall) {
                            if (!vc)
                                cyan = 0;
                            if (!vm)
                                magenta = 0;
                            if (!vy)
                                yellow = 0;
                            if (!vk)
                                black = 0;
                            if (show_gray) {
                                black += cyan + magenta + yellow;
                                cyan = magenta = yellow = 0;
                            }
                        }
                        *d++ = (255-cyan)    * (255-black) / 255; /* r */
                        *d++ = (255-magenta) * (255-black) / 255; /* g */
                        *d++ = (255-yellow)  * (255-black) / 255; /* b */
                    }
                }
            }
            else if (depth == DISPLAY_DEPTH_1) {
                /* Separations */
                int x, y;
                int cyan, magenta, yellow, black;
                unsigned char *s, *d;
                int vc = img->devicen[0].visible;
                int vm = img->devicen[1].visible;
                int vy = img->devicen[2].visible;
                int vk = img->devicen[3].visible;
                int vall = vc && vm && vy && vk;
                int show_gray = (vc + vm + vy + vk == 1) && img->devicen_gray;
                int value;
                for (y = 0; y<img->height; y++) {
                    s = img->buf + y * img->rowstride;
                    d = img->rgbbuf + y * img->width * 3;
                    for (x=0; x<img->width; x++) {
                        value = s[x/2];
                        if (x & 0)
                            value >>= 4;
                        cyan = ((value >> 3) & 1) * 255;
                        magenta = ((value >> 2) & 1) * 255;
                        yellow = ((value >> 1) & 1) * 255;
                        black = (value & 1) * 255;
                        if (!vall) {
                            if (!vc)
                                cyan = 0;
                            if (!vm)
                                magenta = 0;
                            if (!vy)
                                yellow = 0;
                            if (!vk)
                                black = 0;
                            if (show_gray) {
                                black += cyan + magenta + yellow;
                                cyan = magenta = yellow = 0;
                            }
                        }
                        *d++ = (255-cyan)    * (255-black) / 255; /* r */
                        *d++ = (255-magenta) * (255-black) / 255; /* g */
                        *d++ = (255-yellow)  * (255-black) / 255; /* b */
                    }
                }
            }
            break;
        case DISPLAY_COLORS_SEPARATION:
            if (depth == DISPLAY_DEPTH_8) {
                int j;
                int x, y;
                unsigned char *s, *d;
                int cyan, magenta, yellow, black;
                int num_comp = 0;
                int value;
                int num_visible = 0;
                int show_gray = 0;
                IMAGE_DEVICEN *devicen = img->devicen;
                for (j=0; j<IMAGE_DEVICEN_MAX; j++) {
                    if (img->devicen[j].used) {
                       num_comp = j+1;
                       if (img->devicen[j].visible)
                            num_visible++;
                    }
                }
                if ((num_visible == 1) && img->devicen_gray)
                    show_gray = 1;

                for (y = 0; y<img->height; y++) {
                    s = img->buf + y * img->rowstride;
                    d = img->rgbbuf + y * img->width * 3;
                    for (x=0; x<img->width; x++) {
                        cyan = magenta = yellow = black = 0;
                        if (show_gray) {
                            for (j=0; j<num_comp; j++) {
                                devicen = &img->devicen[j];
                                if (devicen->visible && devicen->used)
                                    black += s[j];
                            }
                        }
                        else {
                            for (j=0; j<num_comp; j++) {
                                devicen = &img->devicen[j];
                                if (devicen->visible && devicen->used) {
                                    value = s[j];
                                    cyan    += value*devicen->cyan   /65535;
                                    magenta += value*devicen->magenta/65535;
                                    yellow  += value*devicen->yellow /65535;
                                    black   += value*devicen->black  /65535;
                                }
                            }
                        }
                        if (cyan > 255)
                           cyan = 255;
                        if (magenta > 255)
                           magenta = 255;
                        if (yellow > 255)
                           yellow = 255;
                        if (black > 255)
                           black = 255;
                        *d++ = (255-cyan)    * (255-black) / 255; /* r */
                        *d++ = (255-magenta) * (255-black) / 255; /* g */
                        *d++ = (255-yellow)  * (255-black) / 255; /* b */
                        s += 8;
                    }
                }
            }
            break;
    }

    if (!GTK_IS_WIDGET(img->window)) {
        window_create(img);
        window_resize(img);
    }
#if !GTK_CHECK_VERSION(3, 0, 0)
    visible = (GTK_WIDGET_FLAGS(img->window) & GTK_VISIBLE);
#else
    visible = gtk_widget_get_visible(img->window);
#endif

    if (!visible) gtk_widget_show_all(img->window);

    gtk_widget_queue_draw(img->darea);
    gtk_main_iteration_do(FALSE);
    return 0;
}

static int display_page(void *handle, void *device, int copies, int flush)
{
    display_sync(handle, device);
    return 0;
}

static int display_update(void *handle, void *device,
    int x, int y, int w, int h)
{
    /* not implemented - eventually this will be used for progressive update */
    return 0;
}

static int
display_separation(void *handle, void *device,
    int comp_num, const char *name,
    unsigned short c, unsigned short m,
    unsigned short y, unsigned short k)
{
    IMAGE *img = image_find(handle, device);
    if (img == NULL)
        return -1;
    if ((comp_num < 0) || (comp_num > IMAGE_DEVICEN_MAX))
        return -1;
    img->devicen[comp_num].used = 1;
    strncpy(img->devicen[comp_num].name, name,
        sizeof(img->devicen[comp_num].name)-1);
    img->devicen[comp_num].cyan    = c;
    img->devicen[comp_num].magenta = m;
    img->devicen[comp_num].yellow  = y;
    img->devicen[comp_num].black   = k;
    return 0;
}

/* callback structure for "display" device */
display_callback display = {
    sizeof(display_callback),
    DISPLAY_VERSION_MAJOR,
    DISPLAY_VERSION_MINOR,
    display_open,
    display_preclose,
    display_close,
    display_presize,
    display_size,
    display_sync,
    display_page,
    display_update,
    NULL,	/* memalloc */
    NULL,	/* memfree */
    display_separation
};

static int
write_stderr(const char *str)
{
    fwrite(str, 1, strlen(str), stderr);

    return fflush(stderr);
}


/* Note the space! It makes the string merging simpler */
#define OUR_DEFAULT_DEV_STR "display "

/*********************************************************************/

int main(int argc, char *argv[])
{
    int exit_status;
    int code = 1, code1;
    void *instance = NULL;
    int nargc;
    char **nargv;
    char dformat[64];
    int exit_code;
    gboolean use_gui;
    char *default_devs = NULL;
    char *our_default_devs = NULL;
    int len;

    /* Gtk initialisation */
    setlocale(LC_ALL, "");
    use_gui = gtk_init_check(&argc, &argv);

    /* insert display device parameters as first arguments */
    sprintf(dformat, "-dDisplayFormat=%d",
            DISPLAY_COLORS_RGB | DISPLAY_ALPHA_NONE | DISPLAY_DEPTH_8 |
            DISPLAY_BIGENDIAN | DISPLAY_TOPFIRST);
    nargc = argc + 1;
    nargv = (char **)malloc(nargc * sizeof(char *));
    nargv[0] = argv[0];
    nargv[1] = dformat;
    memcpy(&nargv[2], &argv[1], (argc-1) * sizeof(char *));

    /* run Ghostscript */
    if ((code = gsapi_new_instance(&instance, NULL)) == 0) {
        gsapi_set_stdio(instance, gsdll_stdin, gsdll_stdout, gsdll_stderr);
        if (use_gui) {
            gsapi_set_display_callback(instance, &display);

            code = gsapi_get_default_device_list(instance, &default_devs, &len);
            if (code >= 0) {
                our_default_devs = malloc(len + strlen(OUR_DEFAULT_DEV_STR) + 1);
                if (our_default_devs) {
                    memcpy(our_default_devs, OUR_DEFAULT_DEV_STR, strlen(OUR_DEFAULT_DEV_STR));
                    memcpy(our_default_devs + strlen(OUR_DEFAULT_DEV_STR), default_devs, len);
                    our_default_devs[len + strlen(OUR_DEFAULT_DEV_STR)] = '\0';
                    code = gsapi_set_default_device_list(instance, our_default_devs, strlen(default_devs));
                    free(our_default_devs);
                }
                else {
                    code = -1;
                }
            }
            if (code < 0) {
                write_stderr("Could not set default devices, continuing with existing defaults\n");
                code = 0;
            }
        }
        
        if (code == 0)
            code = gsapi_init_with_args(instance, nargc, nargv);

        if (code == 0)
            code = gsapi_run_string(instance, start_string, 0, &exit_code);
        code1 = gsapi_exit(instance);
        if (code == 0 || code == gs_error_Quit)
            code = code1;
        if (code == gs_error_Quit)
            code = 0;	/* user executed 'quit' */

        gsapi_delete_instance(instance);
    }

    exit_status = 0;
    switch (code) {
        case 0:
        case gs_error_Info:
        case gs_error_Quit:
            break;
        case gs_error_Fatal:
            exit_status = 1;
            break;
        default:
            exit_status = 255;
    }

    return exit_status;
}