-
Notifications
You must be signed in to change notification settings - Fork 51
/
scrot.c
976 lines (824 loc) · 27.9 KB
/
scrot.c
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
/* scrot.c
Copyright 1999-2000 Tom Gilbert <tom@linuxbrit.co.uk,
gilbertt@linuxbrit.co.uk,
scrot_sucks@linuxbrit.co.uk>
Copyright 2009 James Cameron <quozl@us.netrek.org>
Copyright 2010 Ibragimov Rinat <ibragimovrinat@mail.ru>
Copyright 2017 Stoney Sauce <stoneysauce@gmail.com>
Copyright 2019-2023 Daniel T. Borelli <danieltborelli@gmail.com>
Copyright 2019 Jade Auer <jade@trashwitch.dev>
Copyright 2020 blockparole
Copyright 2020 Cungsten Tarbide <ctarbide@tuta.io>
Copyright 2020 Hinigatsu <hinigatsu@protonmail.com>
Copyright 2020 nothub
Copyright 2020 Sean Brennan <zettix1@gmail.com>
Copyright 2021 c0dev0id <sh+github@codevoid.de>
Copyright 2021 Christopher R. Nelson <christopher.nelson@languidnights.com>
Copyright 2021-2023 Guilherme Janczak <guilherme.janczak@yandex.com>
Copyright 2021 IFo Hancroft <contact@ifohancroft.com>
Copyright 2021 Peter Wu <peterwu@hotmail.com>
Copyright 2022-2023 NRK <nrk@disroot.org>
Copyright 2022 Zev Weiss <zev@bewilderbeest.net>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies of the Software and its documentation and acknowledgment shall be
given in the documentation and software packages that this Software was
used.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <sys/stat.h>
#include <sys/wait.h>
#include <assert.h>
#include <err.h>
#include <errno.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <Imlib2.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/extensions/Xcomposite.h>
#include <X11/extensions/Xfixes.h>
#include <X11/extensions/Xinerama.h>
#include "imlib.h"
#include "note.h"
#include "options.h"
#include "scrot.h"
#include "slist.h"
#include "util.h"
static void uninitXAndImlib(void);
static size_t scrotHaveFileExtension(const char *, char **);
static Imlib_Image scrotGrabFocused(void);
static void applyFilterIfRequired(void);
static Bool scrotXEventVisibility(Display *, XEvent *, XPointer);
static Imlib_Image scrotGrabAutoselect(void);
static Imlib_Image scrotGrabShotMulti(void);
static Imlib_Image scrotGrabShotMonitor(void);
static Imlib_Image scrotGrabStackWindows(void);
static Imlib_Image scrotGrabShot(void);
static void scrotCheckIfOverwriteFile(char **);
static void scrotExecApp(Imlib_Image, struct tm *, char *, char *);
static char *imPrintf(const char *, struct tm *, const char *, const char *,
Imlib_Image);
static char *scrotGetWindowName(Window);
static Window scrotGetClientWindow(Display *, Window);
static Window scrotFindWindowByProperty(Display *, const Window,
const Atom);
static Imlib_Image stalkImageConcat(ScrotList *, const enum Direction);
static int findWindowManagerFrame(Window *const, int *const);
static Imlib_Image scrotGrabWindowById(Window const window);
int main(int argc, char *argv[])
{
Imlib_Image image;
Imlib_Image thumbnail;
Imlib_Load_Error imErr;
char *filenameIM = NULL;
char *filenameThumb = NULL;
char *haveExtension = NULL;
time_t t;
struct tm *tm;
atexit(uninitXAndImlib);
optionsParse(argc, argv);
initXAndImlib(opt.display, 0);
if (opt.selection.mode & SELECTION_MODE_ANY)
image = scrotSelectionSelectMode();
else {
scrotDoDelay();
if (opt.focused)
image = scrotGrabFocused();
else if (opt.multidisp)
image = scrotGrabShotMulti();
else if (opt.stack)
image = scrotGrabStackWindows();
else if (opt.monitor != -1)
image = scrotGrabShotMonitor();
else if (opt.autoselect)
image = scrotGrabAutoselect();
else if (opt.windowId != None)
image = scrotGrabWindowById(opt.windowId);
else
image = scrotGrabShot();
}
if (!image)
errx(EXIT_FAILURE, "no image grabbed");
if (opt.note)
scrotNoteDraw(image);
time(&t); /* Get the time directly after the screenshot */
tm = localtime(&t);
imlib_context_set_image(image);
if (opt.format) {
imlib_image_set_format(opt.format);
} else {
scrotHaveFileExtension(opt.outputFile, &haveExtension);
if (!haveExtension)
imlib_image_set_format("png");
}
imlib_image_attach_data_value("quality", NULL, opt.quality, NULL);
filenameIM = imPrintf(opt.outputFile, tm, NULL, NULL, image);
scrotCheckIfOverwriteFile(&filenameIM);
applyFilterIfRequired();
imlib_save_image_with_error_return(filenameIM, &imErr);
if (imErr)
errx(EXIT_FAILURE, "Saving to file %s failed", filenameIM);
if (opt.thumb != THUMB_DISABLED) {
int cwidth, cheight;
int twidth, theight;
cwidth = imlib_image_get_width();
cheight = imlib_image_get_height();
if (opt.thumb == THUMB_RES) {
twidth = opt.thumbW;
theight = opt.thumbH;
if (twidth == 0)
twidth = cwidth * opt.thumbH / cheight;
else if (theight == 0)
theight = cheight * opt.thumbW / cwidth;
} else {
twidth = cwidth * opt.thumbPercent / 100;
theight = cheight * opt.thumbPercent / 100;
}
/* twidth and theight could be rounded to 0 for extremely small sizes,
* fix them up.
*/
if (twidth == 0)
twidth = 1;
if (theight == 0)
theight = 1;
imlib_context_set_anti_alias(1);
thumbnail = imlib_create_cropped_scaled_image(0, 0, cwidth, cheight,
twidth, theight);
if (!thumbnail) {
errx(EXIT_FAILURE, "unable to create thumbnail");
} else {
imlib_context_set_image(thumbnail);
if (opt.format)
imlib_image_set_format(opt.format);
else if (!haveExtension)
imlib_image_set_format("png");
filenameThumb = imPrintf(opt.thumbFile, tm, NULL, NULL, thumbnail);
scrotCheckIfOverwriteFile(&filenameThumb);
imlib_save_image_with_error_return(filenameThumb, &imErr);
imlib_free_image_and_decache();
if (imErr)
errx(EXIT_FAILURE, "Saving thumbnail %s failed", filenameThumb);
}
}
if (opt.exec)
scrotExecApp(image, tm, filenameIM, filenameThumb);
imlib_context_set_image(image);
imlib_free_image_and_decache();
free(filenameIM);
free(filenameThumb);
return 0;
}
/* atexit register func. */
static void uninitXAndImlib(void)
{
if (opt.note) {
scrotNoteFree();
free(opt.note);
}
if (disp) {
XCloseDisplay(disp);
disp = NULL;
}
}
static size_t scrotHaveFileExtension(const char *filename, char **ext)
{
char *s = strrchr(filename, '.');
if (s && s[1] != '\0') {
*ext = s;
return strlen(s);
}
return 0;
}
static Imlib_Image scrotGrabWindowById(Window const window)
{
Imlib_Image im = NULL;
int rx = 0, ry = 0, rw = 0, rh = 0;
if (!scrotGetGeometry(window, &rx, &ry, &rw, &rh))
return NULL;
scrotNiceClip(&rx, &ry, &rw, &rh);
im = imlib_create_image_from_drawable(0, rx, ry, rw, rh, 1);
if (opt.pointer)
scrotGrabMousePointer(im, rx, ry);
clientWindow = window;
return im;
}
static Imlib_Image scrotGrabFocused(void)
{
Window target = None;
XGetInputFocus(disp, &target, &(int){0});
return scrotGrabWindowById(target);
}
static Imlib_Image scrotGrabAutoselect(void)
{
Imlib_Image im = NULL;
int rx = opt.autoselectX, ry = opt.autoselectY, rw = opt.autoselectW,
rh = opt.autoselectH;
scrotNiceClip(&rx, &ry, &rw, &rh);
im = imlib_create_image_from_drawable(0, rx, ry, rw, rh, 1);
if (opt.pointer)
scrotGrabMousePointer(im, rx, ry);
return im;
}
/* similar to sleep, but deals with EINTR.
* ideally, we'd want to sleep against an absolute time to prevent any drift
* but clock_nanosleep doesn't seem to be widely implemented.
*/
static void scrotSleep(int sec)
{
assert(sec > 0);
struct timespec delay = { .tv_sec = sec };
while (nanosleep(&delay, &delay) < 0 && errno == EINTR);
}
void scrotDoDelay(void)
{
if (opt.delay) {
if (opt.countdown) {
int i;
dprintf(STDERR_FILENO, "Taking shot in %d.. ", opt.delay);
scrotSleep(1);
for (i = opt.delay - 1; i > 0; i--) {
dprintf(STDERR_FILENO, "%d.. ", i);
scrotSleep(1);
}
dprintf(STDERR_FILENO, "0.\n");
} else
scrotSleep(opt.delay);
}
}
/* Clip rectangle nicely */
void scrotNiceClip(int *rx, int *ry, int *rw, int *rh)
{
if (*rx < 0) {
*rw += *rx;
*rx = 0;
}
if (*ry < 0) {
*rh += *ry;
*ry = 0;
}
if ((*rx + *rw) > scr->width)
*rw = scr->width - *rx;
if ((*ry + *rh) > scr->height)
*rh = scr->height - *ry;
}
static int findWindowManagerFrame(Window *const target, int *const frames)
{
int x, status;
unsigned int d;
Window rt, *children, parent;
status = XGetGeometry(disp, *target, &root, &x, &x, &d, &d, &d, &d);
if (!status)
return 0;
for (;;) {
status = XQueryTree(disp, *target, &rt, &parent, &children, &d);
if (status && (children != None))
XFree(children);
if (!status || (parent == None) || (parent == rt))
break;
*target = parent;
++*frames;
}
return 1;
}
/* Get geometry of window and use that */
int scrotGetGeometry(Window target, int *rx, int *ry, int *rw, int *rh)
{
Window child;
XWindowAttributes attr;
int stat, frames = 0;
/* Get windowmanager frame of window */
if (target != root) {
if (findWindowManagerFrame(&target, &frames)) {
/* Get client window. */
if (!opt.border)
target = scrotGetClientWindow(disp, target);
XRaiseWindow(disp, target);
/* Give the WM time to update the hidden area of the window.
* Some windows never send the event, a time limit is placed.
*/
XSelectInput(disp, target, FocusChangeMask);
struct timespec delay = {0, 10000000L}; // 10ms
for (short i = 0; i < 30; ++i) {
if (XCheckIfEvent(disp, &(XEvent){0}, &scrotXEventVisibility, (XPointer)&target))
break;
nanosleep(&delay, NULL);
}
}
}
stat = XGetWindowAttributes(disp, target, &attr);
if (!stat || (attr.map_state != IsViewable))
return 0;
*rw = attr.width;
*rh = attr.height;
XTranslateCoordinates(disp, target, root, 0, 0, rx, ry, &child);
/* Special case when the TWM emulates the border directly on the window. */
if (opt.border == 1 && frames < 2 && attr.border_width > 0) {
*rw += attr.border_width * 2;
*rh += attr.border_width * 2;
*rx -= attr.border_width;
*ry -= attr.border_width;
}
return 1;
}
Window scrotGetWindow(Display *display, Window window, int x, int y)
{
Window source, target;
int status, xOffset, yOffset;
source = root;
target = window;
if (window == None)
window = root;
while (1) {
status = XTranslateCoordinates(display, source, window, x, y, &xOffset,
&yOffset, &target);
if (!status)
break;
if (target == None)
break;
source = window;
window = target;
x = xOffset;
y = yOffset;
}
if (target == None)
target = window;
return target;
}
void scrotGrabMousePointer(const Imlib_Image image, const int xOffset,
const int yOffset)
{
XFixesCursorImage *xcim = NULL;
uint32_t *pixels = NULL;
/* Get the X cursor and the information we want. */
if ((xcim = XFixesGetCursorImage(disp)) == NULL) {
warnx("Can't get the cursor from X");
goto end;
}
const unsigned short width = xcim->width;
const unsigned short height = xcim->height;
const size_t pixcnt = (size_t)width*height;
/* xcim->pixels wouldn't be valid if sizeof(*pixels)*pixcnt wrapped around.
*/
if ((pixels = malloc(sizeof(*pixels)*pixcnt)) == NULL) {
warn("malloc()");
goto end;
}
/* XFixesCursorImage returns pixels as `unsigned long`, which is typically
* 64bits, but imlib2 expects 32bit packed integers. */
for (size_t i = 0; i < pixcnt; i++)
pixels[i] = xcim->pixels[i];
Imlib_Image imcursor = imlib_create_image_using_data(width, height, pixels);
if (!imcursor) {
warnx("Can't create cursor image");
goto end;
}
/* Overlay the cursor into `image`. */
const int x = (xcim->x - xcim->xhot) - xOffset;
const int y = (xcim->y - xcim->yhot) - yOffset;
imlib_context_set_image(imcursor);
imlib_image_set_has_alpha(1);
imlib_context_set_image(image);
imlib_blend_image_onto_image(imcursor, 0, 0, 0, width, height, x, y, width,
height);
imlib_context_set_image(imcursor);
imlib_free_image();
end:
free(pixels);
XFree(xcim);
}
// It assumes that the local variable 'scrot.c:Imlib_Image image' is in context
static void applyFilterIfRequired(void)
{
if (opt.script)
imlib_apply_filter(opt.script);
}
static void scrotCheckIfOverwriteFile(char **filename)
{
if (opt.overwrite)
return;
if (access(*filename, F_OK) == -1)
return;
const size_t maxCounter = 999;
size_t counter = 0;
char *ext = NULL;
size_t extLength = 0;
const size_t slen = strlen(*filename);
size_t nalloc = slen + 4 + 1; // _000 + NUL byte
char fmt[5];
char *newName = NULL;
extLength = scrotHaveFileExtension(*filename, &ext);
if (ext)
nalloc += extLength; // .ext
newName = ecalloc(nalloc, sizeof(*newName));
memcpy(newName, *filename, slen);
do {
char *ptr = newName + slen;
snprintf(fmt, sizeof(fmt), "_%03zu", counter++);
if (ext) {
ptr -= extLength;
memcpy(ptr, fmt, sizeof(fmt));
memcpy(ptr + sizeof(fmt) - 1, ext, extLength);
} else
memcpy(ptr, fmt, sizeof(fmt));
} while ((counter < maxCounter) && !access(newName, F_OK));
assert(newName[nalloc - 1] == '\0');
free(*filename);
*filename = newName;
if (counter == maxCounter) {
errx(EXIT_FAILURE, "scrot can no longer generate new file names.\n"
"The last attempt is %s", newName);
}
}
static int scrotMatchWindowClassName(Window target)
{
assert(disp != NULL);
if (!opt.windowClassName)
return 1; /* Match any if the user hasn't requested a specific class. */
XClassHint clsHint;
int match = 0;
if (XGetClassHint(disp, target, &clsHint) != BadWindow) {
match = strcmp(clsHint.res_class, opt.windowClassName) == 0;
XFree(clsHint.res_name);
XFree(clsHint.res_class);
}
return match;
}
static Imlib_Image scrotGrabShot(void)
{
Imlib_Image im;
if (!opt.silent)
XBell(disp, 0);
im = imlib_create_image_from_drawable(0, 0, 0, scr->width,
scr->height, 1);
if (opt.pointer)
scrotGrabMousePointer(im, 0, 0);
return im;
}
static void scrotExecApp(Imlib_Image image, struct tm *tm, char *filenameIM,
char *filenameThumb)
{
char *execStr;
int ret;
execStr = imPrintf(opt.exec, tm, filenameIM, filenameThumb, image);
errno = 0;
ret = system(execStr);
if (ret == -1)
warn("The child process could not be created");
else if (WEXITSTATUS(ret) == 127)
warnx("scrot could not execute the command: %s", execStr);
exit(0);
}
static Bool scrotXEventVisibility(Display *dpy, XEvent *ev, XPointer arg)
{
(void)dpy; // unused
Window *win = (Window *)arg;
return (ev->xvisibility.window == *win);
}
static char *imPrintf(const char *str, struct tm *tm, const char *filenameIM,
const char *filenameThumb, Imlib_Image im)
{
char buf[20];
Stream ret = {0};
long hostNameMax = 0;
char strf[4096];
char *tmp;
struct stat st;
const size_t strfLen = strftime(strf, sizeof(strf), str, tm);
if (strfLen == 0)
errx(EXIT_FAILURE, "strftime returned 0");
imlib_context_set_image(im);
for (const char *c = strf, *end = strf + strfLen; c < end; ++c) {
if (*c == '$' && (c + 1) < end) {
c++;
switch (*c) {
case 'a':
/* freebsd and macos don't have HOST_NAME_MAX defined.
* instead sysconf is recommended by freebsd. */
if (hostNameMax == 0)
hostNameMax = sysconf(_SC_HOST_NAME_MAX) + 1; /* +1 for nul-terminator */
streamReserve(&ret, hostNameMax);
char *target = ret.buf + ret.off;
gethostname(target, hostNameMax);
ret.off += strlen(target);
assert(ret.buf[ret.off] == '\0');
break;
case 'f':
if (filenameIM)
streamStr(&ret, filenameIM);
break;
case 'm': /* t was already taken, so m as in mini */
if (filenameThumb)
streamStr(&ret, filenameThumb);
break;
case 'n':
if (filenameIM) {
tmp = strrchr(filenameIM, '/');
if (tmp)
streamStr(&ret, tmp + 1);
else
streamStr(&ret, filenameIM);
}
break;
case 'w':
snprintf(buf, sizeof(buf), "%d", imlib_image_get_width());
streamStr(&ret, buf);
break;
case 'h':
snprintf(buf, sizeof(buf), "%d", imlib_image_get_height());
streamStr(&ret, buf);
break;
case 's':
if (filenameIM) {
if (!stat(filenameIM, &st)) {
int size;
size = st.st_size;
snprintf(buf, sizeof(buf), "%d", size);
streamStr(&ret, buf);
} else
streamStr(&ret, "[err]");
}
break;
case 'p':
snprintf(buf, sizeof(buf), "%d",
imlib_image_get_width() * imlib_image_get_height());
streamStr(&ret, buf);
break;
case 't':
tmp = imlib_image_format();
if (tmp)
streamStr(&ret, tmp);
break;
case '$':
streamChar(&ret, '$');
break;
case 'W':
if (clientWindow) {
if (!(tmp = scrotGetWindowName(clientWindow)))
break;
streamStr(&ret, tmp);
free(tmp);
}
break;
default:
streamChar(&ret, *c);
break;
}
} else if (*c == '\\' && (c + 1) < end) {
c++;
switch (*c) {
case 'n':
if (filenameIM)
streamChar(&ret, '\n');
break;
default:
streamChar(&ret, *c);
break;
}
} else {
streamChar(&ret, *c);
}
}
streamChar(&ret, '\0');
return ret.buf;
}
static char *scrotGetWindowName(Window window)
{
assert(disp != NULL);
assert(window != None);
if (window == root)
return NULL;
if (!findWindowManagerFrame(&window, &(int){0}))
return NULL;
XClassHint clsHint;
char *windowName = NULL;
const Status status = XGetClassHint(disp,
scrotGetClientWindow(disp, window),
&clsHint);
if (status != 0) {
windowName = estrdup(clsHint.res_class);
XFree(clsHint.res_name);
XFree(clsHint.res_class);
}
return windowName;
}
static Window scrotGetClientWindow(Display *display, Window target)
{
Atom state;
Atom type = None;
int format, status;
unsigned char *data = NULL;
unsigned long after, items;
Window client;
state = XInternAtom(display, "WM_STATE", True);
if (state == None)
return target;
status = XGetWindowProperty(display, target, state, 0L, 0L, False,
AnyPropertyType, &type, &format, &items, &after,
&data);
XFree(data);
if ((status == Success) && (type != None))
return target;
client = scrotFindWindowByProperty(display, target, state);
if (!client)
return target;
return client;
}
static Window scrotFindWindowByProperty(Display *display, const Window window,
const Atom property)
{
Atom type = None;
int format, status;
unsigned char *data = NULL;
unsigned int i, numberChildren;
unsigned long after, numberItems;
Window child = None, *children, parent, rootReturn;
status = XQueryTree(display, window, &rootReturn, &parent, &children,
&numberChildren);
if (!status)
return None;
for (i = 0; (i < numberChildren) && (child == None); i++) {
status = XGetWindowProperty(display, children[i], property, 0L, 0L, False,
AnyPropertyType, &type, &format,
&numberItems, &after, &data);
XFree(data);
if ((status == Success) && type)
child = children[i];
}
for (i = 0; (i < numberChildren) && (child == None); i++)
child = scrotFindWindowByProperty(display, children[i], property);
if (children != None)
XFree(children);
return (child);
}
static Imlib_Image scrotGrabStackWindows(void)
{
if (XGetSelectionOwner(disp, XInternAtom(disp, "_NET_WM_CM_S0", False))
== None) {
errx(EXIT_FAILURE, "option --stack: Composite Manager is not running,"
" required to use this option.");
}
unsigned long numberItemsReturn;
unsigned long bytesAfterReturn;
unsigned char *propReturn;
long offset = 0L;
long length = ~0L;
Bool delete = False;
int actualFormatReturn;
Atom actualTypeReturn;
Imlib_Image im = NULL;
XImage *ximage = NULL;
XWindowAttributes attr;
unsigned long i = 0;
#define EWMH_CLIENT_LIST "_NET_CLIENT_LIST" // spec EWMH
Atom atomProp = XInternAtom(disp, EWMH_CLIENT_LIST, False);
Atom atomType = AnyPropertyType;
int result = XGetWindowProperty(disp, root, atomProp, offset, length,
delete, atomType, &actualTypeReturn, &actualFormatReturn,
&numberItemsReturn, &bytesAfterReturn, &propReturn);
if (result != Success || numberItemsReturn == 0) {
errx(EXIT_FAILURE, "option --stack: Failed XGetWindowProperty: %s",
EWMH_CLIENT_LIST);
}
initializeScrotList(images);
XCompositeRedirectSubwindows(disp, root, CompositeRedirectAutomatic);
for (i = 0; i < numberItemsReturn; i++) {
Window win = *((Window *)propReturn + i);
if (!XGetWindowAttributes(disp, win, &attr))
errx(EXIT_FAILURE, "option --stack: Failed XGetWindowAttributes");
/* Only visible windows */
if (attr.map_state != IsViewable)
continue;
if (!scrotMatchWindowClassName(win))
continue;
ximage = XGetImage(disp, win, 0, 0, attr.width, attr.height, AllPlanes,
ZPixmap);
if (!ximage) {
errx(EXIT_FAILURE,
"option --stack: Failed XGetImage: Window id 0x%lx", win);
}
im = imlib_create_image_from_ximage(ximage, NULL, attr.x, attr.y,
attr.width, attr.height, 1);
XFree(ximage);
appendToScrotList(images, im);
}
return stalkImageConcat(&images, opt.stackDirection);
}
static Imlib_Image scrotGrabShotMulti(void)
{
int screens = ScreenCount(disp);
if (screens < 2)
return scrotGrabShot();
int i;
char *dispStr;
char *subDisp;
char newDisp[255];
Imlib_Image ret = NULL;
initializeScrotList(images);
subDisp = estrdup(DisplayString(disp));
for (i = 0; i < screens; i++) {
dispStr = strchr(subDisp, ':');
if (dispStr) {
dispStr = strchr(dispStr, '.');
if (dispStr)
*dispStr = '\0';
}
snprintf(newDisp, sizeof(newDisp), "%s.%d", subDisp, i);
initXAndImlib(newDisp, i);
ret = imlib_create_image_from_drawable(0, 0, 0, scr->width,
scr->height, 1);
appendToScrotList(images, ret);
}
free(subDisp);
return stalkImageConcat(&images, HORIZONTAL);
}
static Imlib_Image scrotGrabShotMonitor(void)
{
int eventBase, errBase;
if (!XineramaQueryExtension(disp, &eventBase, &errBase))
errx(EXIT_FAILURE, "Xinerama extension not found");
int numScreens = 0;
XineramaScreenInfo *screens = XineramaQueryScreens(disp, &numScreens);
if (!screens && !numScreens)
errx(EXIT_FAILURE, "Xinerama not active");
if (!numScreens)
errx(EXIT_FAILURE, "Xinerama active but did not find any output device");
if (opt.monitor >= numScreens)
errx(EXIT_FAILURE, "monitor %d not found", opt.monitor);
XineramaScreenInfo *mon = &screens[opt.monitor];
/* Hack: pretend we were invoked in autoselect mode */
opt.autoselectX = mon->x_org;
opt.autoselectY = mon->y_org;
opt.autoselectW = mon->width;
opt.autoselectH = mon->height;
XFree(screens);
return scrotGrabAutoselect();
}
static Imlib_Image stalkImageConcat(ScrotList *images, const enum Direction dir)
{
if (isEmptyScrotList(images))
return NULL;
int total = 0, max = 0;
int x = 0, y = 0, w , h;
Imlib_Image ret, im;
ScrotListNode *image = NULL;
const bool vertical = (dir == VERTICAL) ? true : false;
forEachScrotList(images, image) {
im = (Imlib_Image) image->data;
imlib_context_set_image(im);
h = imlib_image_get_height();
w = imlib_image_get_width();
if (!vertical) {
if (h > max)
max = h;
total += w;
} else {
if (w > max)
max = w;
total += h;
}
}
if (!vertical) {
w = total;
h = max;
} else {
w = max;
h = total;
}
ret = imlib_create_image(w, h);
imlib_context_set_image(ret);
imlib_context_set_color(0, 0, 0, 255);
imlib_image_fill_rectangle(0, 0, w, h);
image = firstScrotList(images);
while (image) {
im = (Imlib_Image) image->data;
imlib_context_set_image(im);
h = imlib_image_get_height();
w = imlib_image_get_width();
imlib_context_set_image(ret);
imlib_context_set_anti_alias(0);
imlib_context_set_dither(1);
imlib_context_set_blend(0);
imlib_context_set_angle(0);
imlib_blend_image_onto_image(im, 0, 0, 0, w, h, x, y, w, h);
(!vertical) ? (x += w) : (y += h);
imlib_context_set_image(im);
imlib_free_image_and_decache();
nextAndFreeScrotList(image);
}
return ret;
}