summaryrefslogtreecommitdiffstats
path: root/plug-ins/screenshot/screenshot-win32.c
blob: ff8cbc475251aac0d5b4e6296fa0d1296e8f7ea0 (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
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
/* GIMP - The GNU Image Manipulation Program
 * Copyright (C) 1995 Spencer Kimball and Peter Mattis
 *
 * Screenshot plug-in
 * Copyright 1998-2007 Sven Neumann <sven@gimp.org>
 * Copyright 2003      Henrik Brix Andersen <brix@gimp.org>
 * Copyright 2012      Simone Karin Lehmann - OS X patches
 * Copyright 2018      Gil Eliyahu <gileli121@gmail.com>
 *
 * 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 3 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, see <https://www.gnu.org/licenses/>.
 */

#include "config.h"

#include <glib.h>

#ifdef G_OS_WIN32

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* Necessary in order to have SetProcessDPIAware() defined.
 * This value of _WIN32_WINNT corresponds to Windows 7, which is our
 * minimum supported platform.
 */
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0601
#include <windows.h>

#include <libgimp/gimp.h>
#include <libgimp/gimpui.h>

#include "screenshot.h"
#include "screenshot-win32.h"
#include "screenshot-win32-resource.h"

#include "libgimp/stdplugins-intl.h"
#include "screenshot-win32-magnification-api.h"
#include "screenshot-win32-dwm-api.h"

/*
 * Application definitions
 */
#define SELECT_FRAME    0
#define SELECT_CLIENT   1
#define SELECT_WINDOW   2

#define SHOW_WINDOW     FALSE
#define APP_NAME        "plug_in_screenshot_win"
#define WM_DOCAPTURE    (WM_USER + 100)

/* Prototypes */
void setCaptureType  (int       capType);
BOOL InitApplication (HINSTANCE hInstance);
BOOL InitInstance    (HINSTANCE hInstance,
                      int       nCmdShow);
int  winsnapWinMain  (void);

/* File variables */
static int             captureType;
static char            buffer[512];
static guchar         *capBytes = NULL;
static HWND            mainHwnd = NULL;
static HINSTANCE       hInst = NULL;
static HCURSOR         selectCursor = 0;
static ICONINFO        iconInfo;
static MAGIMAGEHEADER  returnedSrcheader;
static int             rectScreensCount = 0;

static gint32         *image_id;
static gboolean        capturePointer = FALSE;

static void sendBMPToGimp                      (HBITMAP         hBMP,
                                                HDC             hDC,
                                                RECT            rect);
static int      doWindowCapture                    (void);
static gboolean doCapture                          (HWND            selectedHwnd);
static BOOL     isWindowIsAboveCaptureRegion       (HWND            hwndWindow,
                                                    RECT            rectCapture);
static gboolean doCaptureMagnificationAPI          (HWND            selectedHwnd,
                                                    RECT            rect);
static void     doCaptureMagnificationAPI_callback (HWND            hwnd,
                                                    void           *srcdata,
                                                    MAGIMAGEHEADER  srcheader,
                                                    void           *destdata,
                                                    MAGIMAGEHEADER  destheader,
                                                    RECT            unclipped,
                                                    RECT            clipped,
                                                    HRGN            dirty);
static gboolean doCaptureBitBlt                    (HWND            selectedHwnd,
                                                    RECT            rect);

BOOL CALLBACK dialogProc (HWND, UINT, WPARAM, LPARAM);
LRESULT CALLBACK WndProc (HWND, UINT, WPARAM, LPARAM);

gboolean isDwmCompositionEnabled (void);

/* Data structure holding data between runs */
typedef struct {
  gint root;
  guint delay;
  gint decor;
} WinSnapValues;

/* Default WinSnap values */
static WinSnapValues winsnapvals =
{
  FALSE,
  0,
  TRUE,
};

/* The dialog information */
typedef struct {
#ifdef CAN_SET_DECOR
  GtkWidget *decor_button;
#endif
  GtkWidget *single_button;
  GtkWidget *root_button;
  GtkWidget *delay_spinner;
} WinSnapInterface;

/* We create a DIB section to hold the grabbed area. The scanlines in
 * DIB sections are aligned on a LONG (four byte) boundary. Its pixel
 * data is in RGB (BGR actually) format, three bytes per pixel.
 *
 * GIMP uses no alignment for its pixel regions. The GIMP image we
 * create is of type RGB, i.e. three bytes per pixel, too. Thus in
 * order to be able to quickly transfer all of the image at a time, we
 * must use a DIB section and pixel region the scanline width in
 * bytes of which is evenly divisible with both 3 and 4. I.e. it must
 * be a multiple of 12 bytes, or in pixels, a multiple of four pixels.
 */

#define ROUND4(width) (((width-1)/4+1)*4)


gboolean
screenshot_win32_available (void)
{
  return TRUE;
}

ScreenshotCapabilities
screenshot_win32_get_capabilities (void)
{
  return (SCREENSHOT_CAN_SHOOT_DECORATIONS |
          SCREENSHOT_CAN_SHOOT_WINDOW      |
          SCREENSHOT_CAN_SHOOT_POINTER);
}

GimpPDBStatusType
screenshot_win32_shoot (ScreenshotValues  *shootvals,
                        GdkScreen         *screen,
                        gint32            *image_ID,
                        GError           **error)
{
  GimpPDBStatusType status = GIMP_PDB_EXECUTION_ERROR;

  /* leave "shootvals->monitor" alone until somebody patches the code
   * to be able to get a monitor's color profile
   */

  image_id = image_ID;

  winsnapvals.delay = shootvals->screenshot_delay;
  capturePointer = shootvals->show_cursor;

  if (shootvals->shoot_type == SHOOT_ROOT)
    {
      doCapture (0);

      status = GIMP_PDB_SUCCESS;
    }
  else if (shootvals->shoot_type == SHOOT_WINDOW)
    {
      status = 0 == doWindowCapture () ? GIMP_PDB_CANCEL : GIMP_PDB_SUCCESS;
    }
  else if (shootvals->shoot_type == SHOOT_REGION)
    {
      /* FIXME */
    }

  if (status == GIMP_PDB_SUCCESS)
    {
      GimpColorProfile *profile;

      /* XXX No idea if the "monitor" value is right at all, especially
       * considering above comment. Just make so that it at least
       * compiles!
       */
      profile = gimp_screen_get_color_profile (screen, shootvals->monitor);

      if (profile)
        {
          gimp_image_set_color_profile (*image_ID, profile);
          g_object_unref (profile);
        }
    }

  return status;
}





/******************************************************************
 * GIMP format and transfer functions
 ******************************************************************/

/*
 * flipRedAndBlueBytes
 *
 * Microsoft has chosen to provide us a very nice (not!)
 * interface for retrieving bitmap bits.  DIBSections have
 * RGB information as BGR instead.  So, we have to swap
 * the silly red and blue bytes before sending to the
 * GIMP.
 */
static void
flipRedAndBlueBytes (int width,
                     int height)
{
  int      i, j;
  guchar  *bufp;
  guchar   temp;

  j = 0;
  while (j < height) {
    i = width;
    bufp = capBytes + j*ROUND4(width)*3;
    while (i--) {
      temp = bufp[2];
      bufp[2] = bufp[0];
      bufp[0] = temp;
      bufp += 3;
    }
    j++;
  }
}

/*
 * rgbaToRgbBytes
 *
 * Convert rgba array to rgb array
 */
static void
rgbaToRgbBytes (guchar *rgbBufp,
                guchar *rgbaBufp,
                int     rgbaBufSize)
{
  int rgbPoint = 0, rgbaPoint;

  for (rgbaPoint = 0; rgbaPoint < rgbaBufSize; rgbaPoint += 4)
    {
      rgbBufp[rgbPoint++] = rgbaBufp[rgbaPoint];
      rgbBufp[rgbPoint++] = rgbaBufp[rgbaPoint + 1];
      rgbBufp[rgbPoint++] = rgbaBufp[rgbaPoint + 2];
    }
}

/*
 * sendBMPToGIMP
 *
 * Take the captured data and send it across
 * to GIMP.
 */
static void
sendBMPToGimp (HBITMAP hBMP,
               HDC     hDC,
               RECT    rect)
{
  int            width, height;
  int            imageType, layerType;
  gint32         new_image_id;
  gint32         layer_id;
  GeglBuffer    *buffer;
  GeglRectangle *rectangle;

  /* Our width and height */
  width = (rect.right - rect.left);
  height = (rect.bottom - rect.top);

  /* Check that we got the memory */
  if (!capBytes)
    {
      g_message (_("No data captured"));
      return;
    }

  /* Flip the red and blue bytes */
  flipRedAndBlueBytes (width, height);

  /* Set up the image and layer types */
  imageType = GIMP_RGB;
  layerType = GIMP_RGB_IMAGE;

  /* Create the GIMP image and layers */
  new_image_id = gimp_image_new (width, height, imageType);
  layer_id = gimp_layer_new (new_image_id, _("Background"),
                             ROUND4 (width), height,
                             layerType,
                             100,
                             gimp_image_get_default_new_layer_mode (new_image_id));
  gimp_image_insert_layer (new_image_id, layer_id, -1, 0);

  /* make rectangle */
  rectangle = g_new (GeglRectangle, 1);
  rectangle->x = 0;
  rectangle->y = 0;
  rectangle->width = ROUND4(width);
  rectangle->height = height;

  /* get the buffer */
  buffer = gimp_drawable_get_buffer (layer_id);

  /* fill the buffer */
  gegl_buffer_set (buffer, rectangle, 0, NULL, (guchar *) capBytes,
                   GEGL_AUTO_ROWSTRIDE);

  /* flushing data */
  gegl_buffer_flush (buffer);

  /* Now resize the layer down to the correct size if necessary. */
  if (width != ROUND4 (width))
    {
      gimp_layer_resize (layer_id, width, height, 0, 0);
      gimp_image_resize (new_image_id, width, height, 0, 0);
    }

  *image_id = new_image_id;

  return;
}

/*
 * doNonRootWindowCapture
 *
 * Capture a selected window.
 * ENTRY POINT FOR WINSNAP NONROOT
 *
 */
static int
doWindowCapture (void)
{
  /* Start up a standard Win32
   * message handling loop for
   * selection of the window
   * to be captured
   */
  return winsnapWinMain ();
}

/******************************************************************
 * Debug stuff
 ******************************************************************/

/*
 * formatWindowsError
 *
 * Format the latest Windows error message into
 * a readable string.  Store in the provided
 * buffer.
 */
static void
formatWindowsError (char *buffer,
                    int   buf_size)
{
  LPVOID lpMsgBuf;

  /* Format the message */
  FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
    FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
    NULL, GetLastError(),
    MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
    (LPTSTR) &lpMsgBuf, 0, NULL );

  /* Copy to the buffer */
  strncpy(buffer, lpMsgBuf, buf_size - 1);

  LocalFree(lpMsgBuf);
}

/******************************************************************
 * Bitmap capture and handling
 ******************************************************************/

/*
 * primDoWindowCapture
 *
 * The primitive window capture functionality.  Accepts
 * the two device contexts and the rectangle to be
 * captured.
 */
static HBITMAP
primDoWindowCapture (HDC  hdcWindow,
                     HDC  hdcCompat,
                     RECT rect)
{
  HBITMAP hbmCopy;
  HGDIOBJ oldObject;
  BITMAPINFO  bmi;

  int width = (rect.right - rect.left);
  int height = (rect.bottom - rect.top);

  /* Create the bitmap info header */
  bmi.bmiHeader.biSize = sizeof (BITMAPINFOHEADER);
  bmi.bmiHeader.biWidth = ROUND4(width);
  bmi.bmiHeader.biHeight = -height;
  bmi.bmiHeader.biPlanes = 1;
  bmi.bmiHeader.biBitCount = 24;
  bmi.bmiHeader.biCompression = BI_RGB;
  bmi.bmiHeader.biSizeImage = 0;
  bmi.bmiHeader.biXPelsPerMeter =
  bmi.bmiHeader.biYPelsPerMeter = 0;
  bmi.bmiHeader.biClrUsed = 0;
  bmi.bmiHeader.biClrImportant = 0;

  /* Create the bitmap storage space */
  hbmCopy = CreateDIBSection (hdcCompat,
                              (BITMAPINFO *) &bmi,
                              DIB_RGB_COLORS,
                              (void **)&capBytes, NULL, 0);
  if (!hbmCopy)
    {
      formatWindowsError(buffer, sizeof buffer);
      g_error("Error creating DIB section: %s", buffer);
      return NULL;
    }

  /* Select the bitmap into the compatible DC. */
  oldObject = SelectObject (hdcCompat, hbmCopy);
  if (!oldObject)
    {
      formatWindowsError (buffer, sizeof buffer);
      g_error ("Error selecting object: %s", buffer);
      return NULL;
    }

  /* Copy the data from the application to the bitmap.  Even if we did
   * round up the width, BitBlt only the actual data.
   */
  if (!BitBlt(hdcCompat, 0,0,
              width, height,
              hdcWindow, rect.left, rect.top,
              SRCCOPY))
    {
      formatWindowsError (buffer, sizeof buffer);
      g_error ("Error copying bitmap: %s", buffer);
      return NULL;
    }

  /* Draw mouse pointer over screenshot if option was selected */
  if (capturePointer)
    {
      CURSORINFO pointer = { sizeof (pointer) };
      GetCursorInfo (&pointer);
      DrawIcon (hdcCompat, pointer.ptScreenPos.x, pointer.ptScreenPos.y, GetCursor());
    }

  /* Restore the original object */
  SelectObject (hdcCompat, oldObject);

  return hbmCopy;
}

static BOOL CALLBACK
GetAccurateWindowRect_MonitorEnumProc (HMONITOR hMonitor,
                                       HDC      hdcMonitor,
                                       LPRECT   lprcMonitor,
                                       LPARAM   dwData)
{
  RECT **rectScreens = (RECT**) dwData;

  if (!lprcMonitor) return FALSE;

  if (! (*rectScreens))
    *rectScreens = (RECT*) g_malloc (sizeof (RECT)*(rectScreensCount+1));
  else
    *rectScreens = (RECT*) g_realloc (*rectScreens,
                                      sizeof (RECT)*(rectScreensCount+1));

  if (*rectScreens == NULL)
    {
      rectScreensCount = 0;
      return FALSE;
    }

  (*rectScreens)[rectScreensCount] = *lprcMonitor;

  rectScreensCount++;

  return TRUE;
}

static BOOL
GetAccurateWindowRect (HWND hwndTarget,
                       RECT *outRect)
{
  HRESULT dwmResult;
  WINDOWPLACEMENT windowplacment;

  ZeroMemory (outRect, sizeof (RECT));

  /* First we try to get the rect using the dwm api. it will also avoid us from doing more ugly fixes when the window is maximized */
  if (LoadRequiredDwmFunctions ())
    {
      dwmResult = DwmGetWindowAttribute (hwndTarget, DWMWA_EXTENDED_FRAME_BOUNDS, (PVOID) outRect, sizeof (RECT));
      UnloadRequiredDwmFunctions ();
      if (dwmResult == S_OK) return TRUE;
    }

  /* In this case, we did not got the rect from the dwm api so we try to get the rect with the normal function */
  if (GetWindowRect (hwndTarget, outRect))
    {
      /* If the window is maximized then we need and can fix the rect variable
       * (we need to do this if the rect isn't coming from dwm api)
       */
      ZeroMemory (&windowplacment, sizeof (WINDOWPLACEMENT));
      if (GetWindowPlacement (hwndTarget, &windowplacment) && windowplacment.showCmd == SW_SHOWMAXIMIZED)
        {
          RECT *rectScreens = NULL;
          int   xCenter;
          int   yCenter;
          int   i;

          /* If this is not the first time we call this function for some
           * reason then we reset the rectScreens count
           */
          if (rectScreensCount)
            rectScreensCount = 0;

          /* Get the screens rects */
          EnumDisplayMonitors (NULL, NULL, GetAccurateWindowRect_MonitorEnumProc,
                               (LPARAM) &rectScreens);

          /* If for some reason the array size is 0 then we fill it with the desktop rect */
          if (! rectScreensCount)
            {
              rectScreens = (RECT*) g_malloc (sizeof (RECT));
              if (! GetWindowRect (GetDesktopWindow (), rectScreens))
                {
                  /* error: could not get rect screens */
                  g_free (rectScreens);
                  return FALSE;
                }

              rectScreensCount = 1;
            }

          xCenter = outRect->left + (outRect->right - outRect->left) / 2;
          yCenter = outRect->top + (outRect->bottom - outRect->top) / 2;

          /* find on which screen the window exist */
          for (i = 0; i < rectScreensCount; i++)
            if (xCenter > rectScreens[i].left && xCenter < rectScreens[i].right &&
                yCenter > rectScreens[i].top && yCenter < rectScreens[i].bottom)
              break;

          if (i == rectScreensCount)
            /* Error: did not found on which screen the window exist */
            return FALSE;

          if (rectScreens[i].left > outRect->left) outRect->left = rectScreens[i].left;
          if (rectScreens[i].right < outRect->right) outRect->right = rectScreens[i].right;
          if (rectScreens[i].top > outRect->top) outRect->top = rectScreens[i].top;
          if (rectScreens[i].bottom < outRect->bottom) outRect->bottom = rectScreens[i].bottom;

          g_free (rectScreens);
        }

      return TRUE;
    }

  return FALSE;
}

gboolean isDwmCompositionEnabled (void)
{
  HRESULT err;
  BOOL    result;

  if (LoadRequiredDwmFunctions ())
    {
      err = DwmIsCompositionEnabled (&result);
      if (err != S_OK)
        {
          return FALSE;
        }
      return result;
    }

  return FALSE;
}

/*
 * doCapture
 *
 * Do the capture.  Accepts the window
 * handle to be captured or the NULL value
 * to specify the root window.
 */
static gboolean
doCapture (HWND selectedHwnd)
{
  RECT rect;

  /* Try and get everything out of the way before the
   * capture.
   */
  Sleep (500 + winsnapvals.delay * 1000);

  /* Are we capturing a window or the whole screen */
  if (selectedHwnd)
    {
      gboolean compositionEnabled;

      if (! GetAccurateWindowRect (selectedHwnd, &rect))
      /* For some reason it works only if we return here TRUE. strange... */
          return TRUE;

      /* First try to capture the window with the magnification api.
      *  This will solve the bug https://bugzilla.gnome.org/show_bug.cgi?id=793722/
      */
      compositionEnabled = isDwmCompositionEnabled ();

      if (! (compositionEnabled && doCaptureMagnificationAPI (selectedHwnd, rect)))
        {
          /* If for some reason this capture method failed then
          *  capture the window with the normal method:
          */
          HWND     previousHwnd = GetForegroundWindow ();
          gboolean success;

          SetForegroundWindow (selectedHwnd);
          BringWindowToTop (selectedHwnd);

          success = doCaptureBitBlt (selectedHwnd, rect);

          if (previousHwnd)
            SetForegroundWindow (previousHwnd);

          return success;
        }

      return TRUE;

    }
  else
    {
      /* Get the screen's rectangle */
      rect.top    = GetSystemMetrics (SM_YVIRTUALSCREEN);
      rect.bottom = GetSystemMetrics (SM_YVIRTUALSCREEN) + GetSystemMetrics (SM_CYVIRTUALSCREEN);
      rect.left   = GetSystemMetrics (SM_XVIRTUALSCREEN);
      rect.right  = GetSystemMetrics (SM_XVIRTUALSCREEN) + GetSystemMetrics (SM_CXVIRTUALSCREEN);

      return doCaptureBitBlt (selectedHwnd, rect);

    }

  return FALSE; /* we should never get here... */
}

static gboolean
doCaptureBitBlt (HWND selectedHwnd,
                 RECT rect)
{

  HDC     hdcSrc;
  HDC     hdcCompat;
  HBITMAP hbm;

  /* Get the device context for the whole screen
   * even if we just want to capture a window.
   * this will allow to capture applications that
   * don't render to their main window's device
   * context (e.g. browsers).
  */
  hdcSrc = CreateDC (TEXT("DISPLAY"), NULL, NULL, NULL);

  if (!hdcSrc)
    {
      formatWindowsError(buffer, sizeof buffer);
      g_error ("Error getting device context: %s", buffer);
      return FALSE;
    }
  hdcCompat = CreateCompatibleDC (hdcSrc);
  if (!hdcCompat)
    {
      formatWindowsError (buffer, sizeof buffer);
      g_error ("Error getting compat device context: %s", buffer);
      return FALSE;
    }

  /* Do the window capture */
  hbm = primDoWindowCapture (hdcSrc, hdcCompat, rect);
  if (!hbm)
    return FALSE;

  /* Release the device context */
  ReleaseDC(selectedHwnd, hdcSrc);

  if (hbm == NULL) return FALSE;

  sendBMPToGimp (hbm, hdcCompat, rect);

  return TRUE;

}

static void
doCaptureMagnificationAPI_callback (HWND            hwnd,
                                    void           *srcdata,
                                    MAGIMAGEHEADER  srcheader,
                                    void           *destdata,
                                    MAGIMAGEHEADER  destheader,
                                    RECT            unclipped,
                                    RECT            clipped,
                                    HRGN            dirty)
{
  if (!srcdata) return;
  capBytes = (guchar*) malloc (sizeof (guchar)*srcheader.cbSize);
  rgbaToRgbBytes (capBytes, srcdata, srcheader.cbSize);
  returnedSrcheader = srcheader;
}

static BOOL
isWindowIsAboveCaptureRegion (HWND hwndWindow,
                              RECT rectCapture)
{
  RECT rectWindow;
  ZeroMemory (&rectWindow, sizeof (RECT));
  if (!GetWindowRect (hwndWindow, &rectWindow)) return FALSE;
  if (
      (
       (rectWindow.left >= rectCapture.left && rectWindow.left < rectCapture.right)
       ||
       (rectWindow.right <= rectCapture.right && rectWindow.right > rectCapture.left)
       ||
       (rectWindow.left <= rectCapture.left && rectWindow.right >= rectCapture.right)
      )
      &&
      (
       (rectWindow.top >= rectCapture.top && rectWindow.top < rectCapture.bottom)
       ||
       (rectWindow.bottom <= rectCapture.bottom && rectWindow.bottom > rectCapture.top)
       ||
       (rectWindow.top <= rectCapture.top && rectWindow.bottom >= rectCapture.bottom)
      )
  )
    return TRUE;
  else
    return FALSE;
}

static gboolean
doCaptureMagnificationAPI (HWND selectedHwnd,
                           RECT rect)
{
  HWND            hwndMag;
  HWND            hwndHost;
  HWND            nextWindow;
  HWND            excludeWins[24];
  RECT            round4Rect;
  int             excludeWinsCount = 0;
  int             magStyles;

  if (!LoadMagnificationLibrary ()) return FALSE;

  if (!MagInitialize ()) return FALSE;

  round4Rect = rect;
  round4Rect.right = round4Rect.left + ROUND4(round4Rect.right - round4Rect.left);

  /* Create the host window that will store the mag child window */
  hwndHost = CreateWindowEx (0x08000000 | 0x080000 | 0x80 | 0x20, APP_NAME, NULL, 0x80000000,
                             0, 0, 0, 0, NULL, NULL, GetModuleHandle (NULL), NULL);

  if (!hwndHost)
    {
      MagUninitialize ();
      return FALSE;
    }

  SetLayeredWindowAttributes (hwndHost, (COLORREF)0, (BYTE)255, (DWORD)0x02);

  magStyles = WS_CHILD;
  if (capturePointer)
    magStyles |= MS_SHOWMAGNIFIEDCURSOR;

  /* Create the mag child window inside the host window */
  hwndMag = CreateWindow (WC_MAGNIFIER, TEXT ("MagnifierWindow"),
                          magStyles,
                          0, 0, round4Rect.right - round4Rect.left, round4Rect.bottom - round4Rect.top,
                          hwndHost, NULL, GetModuleHandle (NULL), NULL);

  /* Set the callback function that will be called by the api to get the pixels */
  if (!MagSetImageScalingCallback (hwndMag, (MagImageScalingCallback)doCaptureMagnificationAPI_callback))
    {
      DestroyWindow (hwndHost);
      MagUninitialize ();
      return FALSE;
    }

  /* Add only windows that above the target window */
  for (nextWindow = GetNextWindow (selectedHwnd, GW_HWNDPREV); nextWindow != NULL; nextWindow = GetNextWindow (nextWindow, GW_HWNDPREV))
    if (isWindowIsAboveCaptureRegion (nextWindow, rect))
    {
      excludeWins[excludeWinsCount++] = nextWindow;
      /* This api can't work with more than 24 windows. we stop on the 24 window */
      if (excludeWinsCount >= 24) break;
    }

  if (excludeWinsCount)
    MagSetWindowFilterList (hwndMag, MW_FILTERMODE_EXCLUDE, excludeWinsCount, excludeWins);

  /* Call the api to capture the window */
  capBytes = NULL;

  if (!MagSetWindowSource (hwndMag, round4Rect) || !capBytes)
    {
      DestroyWindow (hwndHost);
      MagUninitialize ();
      return FALSE;
    }

  /* Send it to Gimp */
  sendBMPToGimp (NULL, NULL, rect);

  DestroyWindow (hwndHost);
  MagUninitialize ();

  return TRUE;
}

/******************************************************************
 * Win32 entry point and setup...
 ******************************************************************/

#define DINV 3

/*
 * highlightWindowFrame
 *
 * Highlight (or unhighlight) the specified
 * window handle's frame.
 */
static void
highlightWindowFrame (HWND hWnd)
{
  HDC  hdc;
  RECT rc;

  if (!IsWindow (hWnd))
    return;

  hdc = GetWindowDC (hWnd);
  GetWindowRect (hWnd, &rc);
  OffsetRect (&rc, -rc.left, -rc.top);

  if (!IsRectEmpty (&rc))
    {
      PatBlt (hdc, rc.left, rc.top, rc.right-rc.left, DINV, DSTINVERT);
      PatBlt (hdc, rc.left, rc.bottom-DINV, DINV, -(rc.bottom-rc.top-2*DINV),
              DSTINVERT);
      PatBlt (hdc, rc.right-DINV, rc.top+DINV, DINV, rc.bottom-rc.top-2*DINV,
              DSTINVERT);
      PatBlt (hdc, rc.right, rc.bottom-DINV, -(rc.right-rc.left), DINV,
              DSTINVERT);
    }

  ReleaseDC (hWnd, hdc);
  UpdateWindow (hWnd);
}

/*
 * setCaptureType
 *
 * Set the capture type.  Should be one of:
 * SELECT_FRAME
 * SELECT_CLIENT
 * SELECT_WINDOW
 */
void
setCaptureType (int capType)
{
  captureType = capType;
}

/*
 * myWindowFromPoint
 *
 * Map to the appropriate window from the
 * specified point.  The chosen window is
 * based on the current capture type.
 */
static HWND
myWindowFromPoint (POINT pt)
{
  HWND myHwnd;
  HWND nextHwnd;

  switch (captureType)
    {
    case SELECT_FRAME:
    case SELECT_CLIENT:
      nextHwnd = WindowFromPoint (pt);

      do {
          myHwnd = nextHwnd;
          nextHwnd = GetParent (myHwnd);
      } while (nextHwnd);

      return myHwnd;
      break;

    case SELECT_WINDOW:
      return WindowFromPoint (pt);
      break;
    }

  return WindowFromPoint (pt);
}

/*
 * dialogProc
 *
 * The window procedure for the window
 * selection dialog box.
 */
BOOL CALLBACK
dialogProc (HWND   hwndDlg,
            UINT   msg,
            WPARAM wParam,
            LPARAM lParam)
{
  static int     mouseCaptured;
  static int     buttonDown;
  static HCURSOR oldCursor;
  static RECT    bitmapRect;
  static HWND    highlightedHwnd = NULL;

  switch (msg)
    {
    case WM_INITDIALOG:
        {
          int    nonclientHeight;
          HWND   hwndGroup;
          RECT   dlgRect;
          RECT   clientRect;
          RECT   groupRect;
          BITMAP bm;

          /* Set the mouse capture flag */
          buttonDown = 0;
          mouseCaptured = 0;

          /* Calculate the bitmap dimensions */
          GetObject (iconInfo.hbmMask, sizeof(BITMAP), (VOID *)&bm);

          /* Calculate the dialog window dimensions */
          GetWindowRect (hwndDlg, &dlgRect);

          /* Calculate the group box dimensions */
          hwndGroup = GetDlgItem(hwndDlg, IDC_GROUP);
          GetWindowRect (hwndGroup, &groupRect);
          OffsetRect (&groupRect, -dlgRect.left, -dlgRect.top);

          /* The client's rectangle */
          GetClientRect (hwndDlg, &clientRect);

          /* The non-client height */
          nonclientHeight = (dlgRect.bottom - dlgRect.top) -
            (clientRect.bottom - clientRect.top);

          /* Calculate the bitmap rectangle */
          bitmapRect.top = ((groupRect.top + groupRect.bottom) / 2) -
            (bm.bmHeight / 2);
          bitmapRect.top -= nonclientHeight;
          bitmapRect.bottom = bitmapRect.top + bm.bmHeight;
          bitmapRect.left = ((groupRect.left + groupRect.right) / 2) - (bm.bmWidth / 2);
          bitmapRect.right = bitmapRect.left + bm.bmWidth;
        }
      break;

    case WM_LBUTTONDOWN:
      /* Track the button down state */
      buttonDown = 1;
      break;

    case WM_LBUTTONUP:
      buttonDown = 0;

      /* If we have mouse captured
       * we do this stuff.
       */
      if (mouseCaptured)
        {
          HWND  selectedHwnd;
          POINT cursorPos;

          /* Release the capture */
          mouseCaptured = 0;
          SetCursor (oldCursor);
          ReleaseCapture ();

          /* Remove the highlight */
          if (highlightedHwnd)
            highlightWindowFrame (highlightedHwnd);
          RedrawWindow (hwndDlg, NULL, NULL, RDW_INVALIDATE);

          /* Return the selected window */
          GetCursorPos (&cursorPos);
          selectedHwnd = myWindowFromPoint (cursorPos);
          EndDialog (hwndDlg, (INT_PTR) selectedHwnd);
        }
      break;

    case WM_MOUSEMOVE:
      /* If the mouse is captured, show
       * the window which is tracking
       * under the mouse position.
       */
      if (mouseCaptured)
        {
          HWND  currentHwnd;
          POINT cursorPos;

          /* Get the window */
          GetCursorPos (&cursorPos);
          currentHwnd = myWindowFromPoint (cursorPos);

          /* Do the highlighting */
          if (highlightedHwnd != currentHwnd)
            {
              if (highlightedHwnd)
                highlightWindowFrame (highlightedHwnd);
              if (currentHwnd)
                highlightWindowFrame (currentHwnd);
              highlightedHwnd = currentHwnd;
            }
          /* If the mouse has not been captured,
           * try to figure out if we should capture
           * the mouse.
           */
      }
      else if (buttonDown)
        {
          POINT cursorPos;

          /* Get the current client position */
          GetCursorPos (&cursorPos);
          ScreenToClient (hwndDlg, &cursorPos);

          /* Check if within the rectangle formed
           * by the bitmap
           */
          if (PtInRect (&bitmapRect, cursorPos)) {
              mouseCaptured = 1;
              oldCursor = SetCursor (selectCursor);
              SetCapture (hwndDlg);
              RedrawWindow (hwndDlg, NULL, NULL, RDW_INVALIDATE | RDW_ERASE);
          }
        }

      break;

    case WM_PAINT:
        {
          HDC          hDC;
          PAINTSTRUCT  ps;

          /* If the mouse is not captured draw
           * the cursor image
           */
          if (!mouseCaptured)
            {
              hDC = BeginPaint (hwndDlg, &ps);
              DrawIconEx (hDC, bitmapRect.left, bitmapRect.top, selectCursor,
                          0, 0, 0, NULL, DI_NORMAL);
              EndPaint (hwndDlg, &ps);
            }
        }
      break;

    case WM_COMMAND:
      /* Handle the cancel button */
      switch (LOWORD (wParam))
        {
        case IDCANCEL:
          EndDialog (hwndDlg, 0);
          return TRUE;
          break;
        }

    }

  return FALSE;
}

///* Don't use the normal WinMain from gimp.h */
//#define WinMain WinMain_no_thanks
//MAIN()
//#undef WinMain

/*
 * WinMain
 *
 * The standard gimp plug-in WinMain won't quite cut it for
 * this plug-in.
 */
//int APIENTRY
//WinMain(HINSTANCE hInstance,
//  HINSTANCE hPrevInstance,
//  LPSTR     lpCmdLine,
//  int       nCmdShow)
//{
//  /*
//   * Normally, we would do all of the Windows-ish set up of
//   * the window classes and stuff here in WinMain.  But,
//   * the only time we really need the window and message
//   * queues is during the plug-in run.  So, all of that will
//   * be done during run().  This avoids all of the Windows
//   * setup stuff for the query().  Stash the instance handle now
//   * so it is available from the run() procedure.
//   */
//  hInst = hInstance;
//
//  /*
//   * Now, call gimp_main... This is what the normal WinMain()
//   * would do.
//   */
////  return gimp_main(&PLUG_IN_INFO, __argc, __argv);
//}

/*
 * InitApplication
 *
 * Initialize window data and register the window class
 */
BOOL
InitApplication (HINSTANCE hInstance)
{
  WNDCLASS wc;
  BOOL     retValue;

  /* Get some resources */
#ifdef _MSC_VER
  /* For some reason this works only with MSVC */
  selectCursor = LoadCursor (hInstance, MAKEINTRESOURCE(IDC_SELECT));
#else
  selectCursor = LoadCursor (NULL, IDC_CROSS);
#endif
  GetIconInfo (selectCursor, &iconInfo);

  /*
   * Fill in window class structure with parameters to describe
   * the main window.
   */
  wc.style = CS_HREDRAW | CS_VREDRAW;
  wc.lpfnWndProc = (WNDPROC) WndProc;
  wc.cbClsExtra = 0;
  wc.cbWndExtra = 0;
  wc.hInstance = hInstance;
  wc.hIcon = LoadIcon (NULL, IDI_APPLICATION);
  wc.hCursor = LoadCursor (NULL, IDC_ARROW);
  wc.hbrBackground = (HBRUSH) (COLOR_WINDOW + 1);
  wc.lpszClassName = APP_NAME;
  wc.lpszMenuName = NULL;

  /* Register the window class and stash success/failure code. */
  retValue = RegisterClass (&wc);

  /* Log error */
  if (!retValue)
    {
      formatWindowsError (buffer, sizeof buffer);
      g_error ("Error registering class: %s", buffer);
      return retValue;
    }

  return retValue;
}

/*
 * InitInstance
 *
 * Create the main window for the application.
 */
BOOL
InitInstance (HINSTANCE hInstance,
              int       nCmdShow)
{
  HINSTANCE User32Library = LoadLibrary ("user32.dll");

  if (User32Library)
    {
      typedef BOOL (WINAPI* SET_PROC_DPI_AWARE)();
      SET_PROC_DPI_AWARE SetProcessDPIAware;

      /* This line fix bug: https://bugzilla.gnome.org/show_bug.cgi?id=796121#c4 */
      SetProcessDPIAware = (SET_PROC_DPI_AWARE) GetProcAddress (User32Library,
                                                                "SetProcessDPIAware");
      if (SetProcessDPIAware)
        SetProcessDPIAware();

      FreeLibrary (User32Library);
    }

  /* Create our window */
  mainHwnd = CreateWindow (APP_NAME, APP_NAME, WS_OVERLAPPEDWINDOW,
                           CW_USEDEFAULT, 0, CW_USEDEFAULT, 0,
                           NULL, NULL, hInstance, NULL);

  if (!mainHwnd)
    {
      return (FALSE);
    }

  ShowWindow (mainHwnd, nCmdShow);
  UpdateWindow (mainHwnd);

  return TRUE;
}

/*
 * winsnapWinMain
 *
 * This is the function that represents the code that
 * would normally reside in WinMain (see above).  This
 * function will get called during run() in order to set
 * up the windowing environment necessary for WinSnap to
 * operate.
 */
int
winsnapWinMain (void)
{
  MSG msg;

  /* Perform instance initialization */
  if (!InitApplication (hInst))
    return (FALSE);

  /* Perform application initialization */
  if (!InitInstance (hInst, SHOW_WINDOW))
    return (FALSE);

  /* Main message loop */
  while (GetMessage (&msg, NULL, 0, 0))
    {
      TranslateMessage (&msg);
      DispatchMessage (&msg);
    }

  return (msg.wParam);
}

/*
 * WndProc
 *
 * Process window message for the main window.
 */
LRESULT CALLBACK
WndProc (HWND   hwnd,
         UINT   message,
         WPARAM wParam,
         LPARAM lParam)
{
  HWND selectedHwnd;

  switch (message)
    {

    case WM_CREATE:
      /* The window is created... Send the capture message */
      PostMessage (hwnd, WM_DOCAPTURE, 0, 0);
      break;

    case WM_DOCAPTURE:
      /* Get the selected window handle */
      selectedHwnd = (HWND) DialogBox (hInst, MAKEINTRESOURCE(IDD_SELECT),
                                       hwnd, (DLGPROC) dialogProc);
      if (selectedHwnd)
        doCapture (selectedHwnd);

      PostQuitMessage (selectedHwnd != NULL);

      break;

    case WM_DESTROY:
      PostQuitMessage (0);
      break;

    default:
      return (DefWindowProc (hwnd, message, wParam, lParam));
    }

  return 0;
}

#endif /* G_OS_WIN32 */