-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmonitorfunctions.py
More file actions
executable file
·1701 lines (1502 loc) · 65 KB
/
Copy pathmonitorfunctions.py
File metadata and controls
executable file
·1701 lines (1502 loc) · 65 KB
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
"""gives the monitor information of all the monitors
and provide functions for moving a (top level) window to a position on
the current or on a different monitor.
The start of this module was taken from O'Reilly, and has been enhanced for use
with NatLink speech recognition commands, see http://qh.antenna.nl and
http://qh.antenna.nl/unimacro. Quintijn Hoogenboom, february 2010.
The basic information is collected in
-MONITOR_INFO, a dictionary with keys the handles of the monitor
These keys are converted to int, and for 2 monitors probably 65537 and
65539, and put in global variable MONITOR_HNDLES (a list)
Each item of MONITOR_INFO is again a dictionary with for example my second monitor info:
{'Device': '\\\\.\\DISPLAY2',
'Flags': 0,
'Monitor': (1680, 0, 2704, 768),
'Work': (1787, 0, 2704, 768),
'offsetx': 107,
'offsety': 0}
Thus holding the Monitor info and the Work info. As a extra offsetx and offsety are calculated,
which give the width/height of task bar and possibly other "bars". In this example I have the task bar
vertically placed at the left side of this second monitor, and it has a width of 107 pixels.
-MONITOR_HNDLES: a list of the available monitors (the handles are int, see above)
-VIRTUAL_SCREEN: a 4 tuple giving the (left, top, right, bottom) of the complete (virtual) screen
-BORDERX, BORDERY: the border width of windows. With this a window can be size a little
MA, WA, RA
Each area (MA: Monitor, WA: Work, RA: restore area of a window) is a 4 length tuple
giving (left, top, right, bottom).
Biggest puzzle of the calculations is changing the restore_area (from GetWindowPlacement) to the Work area of
a new monitor. Important is the offsetx and offsety (difference between Monitor coordinates and Work area
coordinates). The RA (restore_area) is relative to the Work area of the monitor it is on, so the offsetx and offsety
must be subtracted from the calculated coordinates. (something like that)
This module provides functions for getting:
--all the info: monitor_info(force=None): giving the above mentioned data
--which is the nearest monitor, using API functions:
get_nearest_monitor_window(winHndle)
get_nearest_monitor_point(point)
(could also make get_nearest_monitor_rect, but was not needed here)
--further info:
get_other_monitors(mon): give a list of the other monitor hndles (after collecting the current monitor)
-- for individual points (used by natlinkutilsqh.py in Unimacro (NatLink, speech recognition)
is_inside_monitor(point): returns True if the point is inside one of the monitors (monitor area)
get_closest_position(point) returns a point that is closest to an outside point on one of the monitors
-- for user calls:
maximize_window(winHndle): just maximize
minimize_window(winHndle): just minimize
move_to_monitor(winHndle, newMonitor, oldMonitor, resize): move to another monitor
preserving position of restore_area as much as possible.
resize: 0 if window is (assumed to be) fixed in size, can be found with:
window_can_be_resized(winHndle):
return 1 if a window can be resized (like Komodo etc). Not eg calc.
restore_window(winHndle, monitor, ...): placing in various spots and widths/heights
see at definition for parameters
-- helper functions:
"""
import win32api, math, win32gui, win32con
import time, pprint, types, math
import messagefunctions # only for taskbar position (left, bottom etc)
MONITOR_INFO = None
MONITOR_HNDLES = None
BORDERX = BORDERY = None
VIRTUAL_SCREEN = None
NMON = None
def monitor_info():
"""collecting all the essential information
"""
global MONITOR_INFO
global MONITOR_HNDLES
global BORDERX, BORDERY
global VIRTUAL_SCREEN
global NMON # number of monitors
NMON = win32api.GetSystemMetrics(win32con.SM_CMONITORS) # 80
if NMON < 1:
raise ValueError("monitor_info: system should have at least one monitor, strange result: %s"% NMON)
MONITOR_INFO = {}
ALL_MONITOR_INFO = [item for item in win32api.EnumDisplayMonitors(None, None)]
for hndle, dummy, monitorRect in ALL_MONITOR_INFO:
hndle = int(hndle)
MONITOR_INFO[hndle] = win32api.GetMonitorInfo(hndle)
m = MONITOR_INFO[hndle]
m['offsetx'] = m['Work'][0] - m['Monitor'][0]
m['offsety'] = m['Work'][1] - m['Monitor'][1]
MONITOR_HNDLES = MONITOR_INFO.keys()
BORDERX = win32api.GetSystemMetrics(win32con.SM_CXBORDER) # 5
BORDERY = win32api.GetSystemMetrics(win32con.SM_CYBORDER) # 6
VIRTUAL_SCREEN = []
VIRTUAL_SCREEN.append(win32api.GetSystemMetrics(win32con.SM_XVIRTUALSCREEN)) # 76
VIRTUAL_SCREEN.append(win32api.GetSystemMetrics(win32con.SM_YVIRTUALSCREEN)) # 77
VIRTUAL_SCREEN.append(VIRTUAL_SCREEN[0] + win32api.GetSystemMetrics(win32con.SM_CXVIRTUALSCREEN)) # 78
VIRTUAL_SCREEN.append(VIRTUAL_SCREEN[1] + win32api.GetSystemMetrics(win32con.SM_CYVIRTUALSCREEN)) # 79
def getScreenRectData():
"""return width, height, xmin, ymin, xmax, ymax for complete screen
"""
monitor_info()
vs = VIRTUAL_SCREEN
return vs[2]-vs[0], vs[3]-vs[1], vs[0], vs[1], vs[2], vs[3]
def fake_monitor_info_for_testing(nmon, virtual_screen):
"""test if changed monitor data come through in calling program
"""
global NMON, VIRTUAL_SCREEN
NMON = nmon
VIRTUAL_SCREEN = virtual_screen
print 'fake_monitor_info_for_testing, set NMON to %s and VIRTUAL_SCREEN to %s'% (nmon, virtual_screen)
###########################################
# three wrapper functions around api calls:
# -MonitorFromPoint
# -MonitorFromRect
# -MonitorFromWindow
# using constant: MONITOR_DEFAULTTONEAREST
def get_nearest_monitor_window(winHndle):
"""give monitor number of the monitor which is nearest to the window
input the handle of the window, most often got by:
winHndle = win32gui.GetForegroundWindow()
output: the monitor handle as an integer (65537, 65539 often on a 2 monitor configuration)
"""
mon = win32api.MonitorFromWindow(winHndle, win32con.MONITOR_DEFAULTTONEAREST)
return int(mon)
def get_nearest_monitor_point( point ):
"""give monitor number of the monitor which is nearest to the point
point is a tuple (x, y) of coordinates
"""
mon = win32api.MonitorFromPoint(point , win32con.MONITOR_DEFAULTTONEAREST)
return int(mon)
def get_other_monitors(mon):
"""give list of other monitors
"""
mon = int(mon)
if MONITOR_HNDLES is None:
monitor_info()
if MONITOR_HNDLES is None:
raise ValueError("no monitor handles found")
#print 'mon: %s, int(mon): %s'% (mon, int(mon))
return [hndle for hndle in MONITOR_HNDLES if hndle != mon]
#other = [hndle for ]
def window_can_be_resized(windowHndle):
"""returns 1 if the window can be resized (has a maximize button)
"""
wstyle = win32api.GetWindowLong(windowHndle, win32con.GWL_STYLE)
canBeResized = (wstyle & win32con.WS_MAXIMIZEBOX == win32con.WS_MAXIMIZEBOX)
#print 'wstyle: %x, maximizebox: %x, '
return canBeResized
def get_taskbar_position():
"""return left, top, right or bottom
"""
monitor_info()
m = MONITOR_INFO
hApp = messagefunctions.findTopWindow(wantedClass='Shell_TrayWnd')
if not hApp:
print 'no taskbar (system tray) found'
return
info = list( win32gui.GetWindowPlacement(hApp) )
RA = list(info[4])
mon = get_nearest_monitor_window(hApp)
work = list(MONITOR_INFO[mon]['Work'])
#print 'RA: %s'% RA
#print 'work: %s'% work
# bottom 3
# right 2
# top 1
# left 0
if RA[2] <= work[0] + 2*BORDERX:
return 'left' # right pos of RA == left pos of work area
elif RA[1] >= work[3] - 2*BORDERY:
return 'bottom' # top of RA == bottom of work area
elif RA[0] >= work[2] - 2*BORDERX:
return 'right' # left of RA == right of work area (account for Dragon bar)
elif RA[3] <= work[1] + 2*BORDERY:
return 'top'
#======================== on same monitor: ==========================================
def restore_window(winHndle, monitor=None, xwidth=None, ywidth=None,
xpos=None, ypos=None, keepinside=None):
"""move window inside same monitor, restore format
(for moving an amount of pixels or across the monitor border use move_window
for resizing an amount of pixels, to an edge or across the monitor border use
stretch_window or shrink_window)
if no parameters are passed, the window is restored, but inside its
working area if it fits. If it does not fit, the left top is shown.
winHndle: hndle of the program
monitor: hndle of the monitor (from which the monitor_info is got)
xwidth, ywidth: passed to width in _get_new_coordinates_same_monitor, see there
xpos, ypos: passed to position in _get_new_coordinates_same_monitor, see there
keepinside: should normally be the same as the window_can_be_resized value,
default taken from this function
"""
monitor_info()
if not monitor:
monitor = get_nearest_monitor_window(winHndle)
toRestore = win32con.SW_RESTORE
info = list( win32gui.GetWindowPlacement(winHndle) )
MI = MONITOR_INFO[monitor]
RA = list(info[4])
maximized = ( info[1] == win32con.SW_SHOWMAXIMIZED)
if keepinside is None:
keepinside = not window_can_be_resized(winHndle)
# for non resizable windows:
if not window_can_be_resized(winHndle):
print 'no resize window, setting xwidth and ywidth to 0(width was: %s, %s'%\
(xwidth, ywidth)
## center in correct way:
#if xwidth:
# xpos = 0.5
#if not ywidth:
# ypos = 0.5
# set width to non resize:
xwidth = ywidth = 0
#print 'maximized: %s'% maximized
#print 'previous RA: %s'% RA
newRA = _change_restore_area(RA, monitor_info=MI,
xpos=xpos, ypos=ypos,
xwidth=xwidth, ywidth=ywidth,
keepinside=keepinside)
info[1] = toRestore
info[4] = tuple(newRA)
win32gui.SetWindowPlacement(winHndle, tuple(info) )
def move_window(winHndle, direction, amount, units='pixels',
keepinside=None, keepinsideall=1, monitor=None):
"""moves a window, can go across monitor borders and out of the total area
winHndle: hndle of the program
monitor: hdnle of the monitor (is collected if not passed)
direction: a string, left, right, up, down or
a direction in degrees (0 = up, 90 = right, 180 = down, 270 = left)
amount: number of pixels (for moving to left edge, use restore_window)
keepinside: keep inside the work area of the monitor
keepinsideall: keep inside the virtual area of all monitors.
"""
monitor_info()
if not monitor:
monitor = get_nearest_monitor_window(winHndle)
toRestore = win32con.SW_RESTORE
info = list( win32gui.GetWindowPlacement(winHndle) )
MI = MONITOR_INFO[monitor]
RA = list(info[4])
resize = 0
newRA = _move_resize_restore_area(RA, resize, direction, amount, units=units,
keepinside=keepinside, keepinsideall=keepinsideall,
monitor_info=MI)
info[1] = toRestore
info[4] = tuple(newRA)
win32gui.SetWindowPlacement(winHndle, tuple(info) )
def stretch_window(winHndle, direction, amount, units='pixels',
keepinside=None, keepinsideall=1, monitor=None):
"""resize a window, making it larger, can go across monitor borders and out of the total area
winHndle: hndle of the program
monitor: hdnle of the monitor (is collected if not passed)
direction: a string, left, right, up, down or
a direction in degrees (0 = up, 90 = right, 180 = down, 270 = left)
amount: number of pixels (for moving to left edge, use restore_window)
keepinside: keep inside the work area of the monitor
keepinsideall: keep inside the virtual area of all monitors.
"""
monitor_info()
if not monitor:
monitor = get_nearest_monitor_window(winHndle)
toRestore = win32con.SW_RESTORE
info = list( win32gui.GetWindowPlacement(winHndle) )
MI = MONITOR_INFO[monitor]
RA = list(info[4])
resize = 1
newRA = _move_resize_restore_area(RA, resize, direction, amount, units=units,
keepinside=keepinside, keepinsideall=keepinsideall,
monitor_info=MI)
info[1] = toRestore
info[4] = tuple(newRA)
win32gui.SetWindowPlacement(winHndle, tuple(info) )
def shrink_window(winHndle, direction, amount, units='pixels',
keepinside=None, keepinsideall=1, monitor=None):
"""resize a window, making it smaller, can go across monitor borders and out of the total area
winHndle: hndle of the program
monitor: hdnle of the monitor (is collected if not passed)
direction: a string, left, right, up, down or
a direction in degrees (0 = up, 90 = right, 180 = down, 270 = left)
amount: number of pixels (for moving to left edge, use restore_window)
when shrink relative, take size of the window rather than distance to edge or corner
keepinside: keep inside the work area of the monitor
keepinsideall: keep inside the virtual area of all monitors.
"""
monitor_info()
if not monitor:
monitor = get_nearest_monitor_window(winHndle)
toRestore = win32con.SW_RESTORE
info = list( win32gui.GetWindowPlacement(winHndle) )
MI = MONITOR_INFO[monitor]
RA = list(info[4])
resize = -1
newRA = _move_resize_restore_area(RA, resize, direction, amount, units=units,
keepinside=keepinside, keepinsideall=keepinsideall,
monitor_info=MI)
info[1] = toRestore
info[4] = tuple(newRA)
win32gui.SetWindowPlacement(winHndle, tuple(info) )
def maximize_window(winHndle):
"""maximize to the monitor (it is on at the moment)"""
monitor_info()
toMaximize = win32con.SW_SHOWMAXIMIZED
info = list( win32gui.GetWindowPlacement(winHndle) )
info[1] = toMaximize
win32gui.SetWindowPlacement(winHndle, tuple(info) )
def minimize_window(winHndle):
"""minimize the window"""
monitor_info()
toMinimize = win32con.SW_SHOWMINIMIZED
info = list( win32gui.GetWindowPlacement(winHndle) )
info[1] = toMinimize
win32gui.SetWindowPlacement(winHndle, tuple(info) )
def _move_resize_restore_area(RestoreArea, resize, direction, amount, units,
keepinside, keepinsideall, monitor_info, min_size= (100, 70) ):
"""change the coordinates of the RA according to direction and amount
the amount in combination with direction provides numerous, confusing possibilities
RA: the restore area
resize: 0 = move, 1 = resize in the target direction
-1 = resize away from target direction (making smaller)
direction: left|right|up|down|lefttop|righttop|leftbottom|rightbottom or
a number of degrees (0=up, 90=right, 180=down, 270=left)
units: relative (amount between 0 and 1)|pixels|percent (of screen size)
amount: 0 < amount <= 1: for units == relative
>= 1 (int): an absolute number of pixels|percent of screen size
keepinside: whether to check for the window being inside after the move/resize
keepinsideall: whether to check for the window being inside the virtual screen (all monitors)
monitor_info: the info (dict) of the current monitor
"""
RA = RestoreArea[:]
raWidth = RA[2] - RA[0]
raHeight = RA[3] - RA[1]
WA = monitor_info['Work']
MA = monitor_info['Monitor']
#offsetx = monitor_info['offsetx']
#offsety = monitor_info['offsety']
# norm to 0 oriented
RA[0] -= MA[0]
RA[1] -= MA[1]
RA[2] -= MA[0]
RA[3] -= MA[1]
WAWidth = WA[2] - WA[0]
WAHeight = WA[3] - WA[1]
boundingbox = [0, 0, WAWidth, WAHeight]
alpha, distance = None, None
if direction == 'lefttop':
alpha, distance = _get_angle_distance_side_corners(RA, boundingbox, 0, 0)
elif direction == 'righttop':
alpha, distance = _get_angle_distance_side_corners(RA, boundingbox, 1, 0)
elif direction == 'leftbottom':
alpha, distance = _get_angle_distance_side_corners(RA, boundingbox, 0, 1)
elif direction == 'rightbottom':
alpha, distance = _get_angle_distance_side_corners(RA, boundingbox, 1, 1)
elif direction == 'right':
alpha, distance = 90, boundingbox[2] - RA[2]
elif direction in ('down','bottom'):
alpha, distance = 180, boundingbox[3] - RA[3]
elif direction == 'left':
alpha, distance = 270, RA[0] - boundingbox[0]
elif direction in ('top', 'up'):
alpha, distance = 0, RA[1] - boundingbox[1]
elif type(direction
) in (types.FloatType, types.IntType):
alpha = direction
# setting reverse (for making smaller)
if resize == -1:
reverse = resize
else:
reverse = 1
if units == 'pixels':
if alpha is None:
raise ValueError('alpha unknown, do not know where to move to')
deltax, deltay = _get_deltax_deltay_from_angle_distance(alpha, amount)
amountx = _round_float(deltax * reverse)
amounty = _round_float(deltay * reverse)
elif units == 'relative':
if alpha is None:
raise ValueError('alpha unknown, do not know where to move to')
distance = _get_distance_in_direction(RA, boundingbox, alpha) #if distance is None:
# nearest_corner, distance =
deltax, deltay = _get_deltax_deltay_from_angle_distance(alpha, distance)
amountx = _round_float(deltax * reverse * amount)
amounty = _round_float(deltay * reverse * amount)
else:
raise ValueError("_move_resize_restore_area: units should be 'relative' or 'pixels', not '%s'"% units)
side_corner = None
if direction == 'up':
side_corner = 'top'
elif direction == 'down':
side_corner = 'bottom'
elif type(side_corner) == types.StringType:
side_corner = direction
RA = _adjust_coordinates_side_corners(RA, amountx, amounty, resize, side_corner=side_corner, min_size=min_size)
if keepinside:
fixed_width = not resize
RA[0], RA[2] = keepinside_restore_area(RA[0], RA[2], WAWidth, fixed_width=fixed_width, margin=1)
RA[1], RA[3] = keepinside_restore_area(RA[1], RA[3], WAHeight, fixed_width=fixed_width, margin=1)
# correct for WA again:
RA[0] += MA[0]
RA[1] += MA[1]
RA[2] += MA[0]
RA[3] += MA[1]
if keepinsideall:
fixed_width = not resize # if it is a move
RA[0], RA[2] = keepinside_all_screens(RA[0], RA[2], VIRTUAL_SCREEN[0], VIRTUAL_SCREEN[2], fixed_width)
RA[1], RA[3] = keepinside_all_screens(RA[1], RA[3], VIRTUAL_SCREEN[0], VIRTUAL_SCREEN[2], fixed_width)
return RA
def _get_distance_in_direction(RestoreArea, boundingbox, angle):
"""calculate the distance from window (restore area) to the bounding box
alpha is direction to appropriate cornerpoint
return distance (0 if direction fails, distance to cornerpoint maximum)
"""
RA = RestoreArea[:]
angle = angle % 360
if 0 <= angle < 90:
alpha, distance = _get_angle_distance_side_corners(RA, boundingbox, 1, 0)
if not 0 <= alpha < 90: return 0 # not same direction
angle, alpha = 90 - angle, 90 - alpha # for easier goniometry
elif 90 <= angle < 180:
alpha, distance = _get_angle_distance_side_corners(RA, boundingbox, 1, 1)
if not 90 <= alpha < 180: return 0
angle, alpha = angle - 90, alpha -90
elif 180 <= angle < 270:
alpha, distance = _get_angle_distance_side_corners(RA, boundingbox, 0, 1)
if not 180 <= alpha < 270: return 0
angle, alpha = 270 - angle, 270 - alpha
elif 270 <= angle <= 360:
alpha, distance = _get_angle_distance_side_corners(RA, boundingbox, 0, 0)
if not 270 <= alpha < 360: return 0 # not same direction
angle, alpha = angle - 270, alpha - 270 # for easier goniometry
if angle == alpha:
return distance
elif angle < alpha:
return distance * math.cos(math.radians(alpha))/math.cos(math.radians(angle))
else:
return distance * math.sin(math.radians(alpha))/math.sin(math.radians(angle))
def _round_float(f):
"""round to integer
>>> _round_float(0)
0
>>> _round_float(0.4)
0
>>> _round_float(0.5)
1
>>> _round_float(-0.5)
-1
>>> _round_float(-1.9)
-2
>>> _round_float(1.9999999999999999)
2
"""
if f > 0:
return int(f + 0.5)
elif f < 0:
return int(f - 0.5)
else:
return 0
def _get_angle_distance_side_corners(RA, boundingbox, xindex, yindex):
"""return angle and distance of RA point and WA point
give RA and WA and:
xindex: 0 left, 1 right
yindex: 0 top, 1 bottom
return (alpha (in degrees), distance (in pixels))
"""
bb = boundingbox ##(should be [0, 0, widhtofWA, heightofWA])
if xindex == 0 and yindex == 0:
return _get_angle_distance( RA[0], RA[1], bb[0], bb[1])
elif xindex == 0 and yindex == 1:
return _get_angle_distance( RA[0], RA[3], bb[0], bb[3])
elif xindex == 1 and yindex == 0:
return _get_angle_distance( RA[2], RA[1], bb[2], bb[1])
elif xindex == 1 and yindex == 1:
return _get_angle_distance( RA[2], RA[3], bb[2], bb[3])
else:
raise ValueError("_get_angle_distance_side_corners: invalid parameters xindex (%s), yindex (%s) (should be 0 or 1)"%
(xindex, yindex))
def _get_angle_distance(px, py, qx, qy):
"""calculate angle and distance of two points
px, py: (pixel) coordinates of first point (corner of window)
qx, qy: (pixel) coordinates of second point (corner of monitor)
return: (angle, dist)
angle (in degrees) up = 0, right = 90 etc, viewed from p to q
dist: pixels () (rounded to int)
(see unittestMonitorfunctions for more tests)
#>>> _get_angle_distance(20, 100, 0, 0)# fourth quadrant
#(348.69, 101.98)
#>>> _get_angle_distance(0, 100, 0, 0)# point up
#(0, 100.0)
#>>> _get_angle_distance(300, 600, 1000, 600)# point right
#(90, 700.0)
"""
dx, dy = qx-px, qy-py
dist = math.sqrt(dx*dx + dy*dy)
if dx == 0:
if dy == 0:
return (0, 0)
elif dy > 0:
return (180, dist)
else:
return (0, dist)
elif dy == 0:
if dx > 0:
return (90, dist)
else:
# dx < 0
return (270, dist)
else:
alpha = math.degrees(math.atan(math.fabs(1.0*dy/dx)))
if dx > 0 and dy < 0: # first quadrant
alpha = 90 - alpha
elif dx > 0 and dy > 0:
# second quadrant
alpha = 90 + alpha
elif dx < 0 and dy > 0:
# third quadrant
alpha = 270 - alpha
elif dx < 0 and dy < 0:
# fourth quadrant
alpha = 270 + alpha
else:
raise ValueError("impossible to come here")
return alpha, dist
def _get_deltax_deltay_from_angle_distance(angle, distance):
"""calculates "back" the px - py and qx - qy from _get_angle_distance
#>>> angle, distance = _get_angle_distance(20, 100, 0, 0)# fourth quadrant
#>>> angle, distance
#(348.69, 101.98)
#>>> _get_deltax_deltay_from_angle_distance(angle, distance)
#(-20, 99.99999)
#
#>>> angle, distance = _get_angle_distance(300, 600, 1000, 600)# point right
#>>> angle, distance
#(90, 700.0)
#>>> _get_deltax_deltay_from_angle_distance(angle, distance)
#(700.0, 0)
test with unittestMonitorfunctions)
"""
alpha = angle
deltax = distance * math.sin(math.radians(alpha))
deltay = - distance * math.cos(math.radians(alpha))
return deltax, deltay
def _adjust_coordinates_side_corners(RestoreArea, amountx, amounty, resize, side_corner=None, min_size=(100,70)):
"""adjust RestoreArea in the wanted direction
give RA
amountx and amounty (can be negative)
eg amountx = -5 means go left 5, resize == 1 doing on left side (larger)
resize == -1 doing on right side (smaller)
(resize false: does not matter where)
resize (include the other point)
resize = 0(None): move, also change the opposite point
resize = 1: make larger (see note below)
resize = -1: make smaller (only relevant if side_corner is NOT given)
side_corner in lefttop, righttop leftbottom rightbottom or
left right up down or center or None
(note: if side_corner is given, a resize (if given) is always into the
direction with respect to side_corner, so smaller/larger is not controlled by
resize)
(assume amount points in correct direction)
resize: 0 = cannot resize (move)
min_size (in case of resize, minimum size of width/height)
returns adjusted RA
(see unittestMonitorfunctions for tests)
"""
RA = RestoreArea[:]
validvaluesside_corner = ('rightbottom', 'righttop', 'leftbottom', 'lefttop',
'left', 'right', 'top', 'bottom',
'leftcenter', 'rightcenter', 'center',
'centertop', 'centerbottom')
if side_corner is None:
if resize == -1:
reverse = resize
else:
reverse = 1
if amountx == 0:
if amounty == 0:
return RA # no changes to be expected
elif amounty * reverse > 0:
side_corner = 'bottom'
else:
# amounty < 0:
side_corner = 'top'
elif amountx * reverse > 0:
if amounty == 0:
side_corner = 'right'
elif amounty * reverse > 0:
side_corner = 'rightbottom'
else:
# amounty < 0:
side_corner = 'righttop'
else:
# amountx * reverse negative
if amounty == 0:
side_corner = 'left'
elif amounty * reverse > 0:
side_corner = 'leftbottom'
else:
# amounty < 0:
side_corner = 'lefttop'
if side_corner not in validvaluesside_corner:
raise ValueError("side_corner ('%s') should be one of the valid values: %s"%
(side_corner, validvaluesside_corner))
if resize and resize not in (-1, 1, True):
raise ValueError("resize ('%s') should be false, or True, 1 (larger) or -1 (smaller)"% resize)
if amountx:
if side_corner in ('lefttop', 'leftbottom', 'left'):
RA[0] += amountx
if resize:
# allow for minimum size of result:
RA[0] = min(RA[0], RA[2]-min_size[0])
else:
RA[2] += amountx
elif side_corner in ('centertop', 'centerbottom', 'center'):
# resize not relevant
left = int(amountx/2)
right = amountx - left
RA[0] -= left
RA[2] += right
else:
RA[2] += amountx
if resize:
RA[2] = max(RA[0]+min_size[0], RA[2])
else:
RA[0] += amountx
if amounty:
if side_corner in ('lefttop', 'righttop', 'top'):
# doing y upwards:
RA[1] += amounty
if resize:
RA[1] = min(RA[1], RA[3]-min_size[1])
else:
RA[3] += amounty
elif side_corner in ('leftcenter', 'rightcenter', 'center'):
# resize not relevant
up = int(amounty/2)
down = amounty - right
RA[1] -= up
RA[3] += down
else:
# doing y downwards
RA[3] += amounty
if resize:
RA[3] = max(RA[1]+min_size[1], RA[3])
else:
RA[1] += amounty
return RA
def _change_restore_area(RA, monitor_info, xwidth, ywidth,
xpos, ypos, keepinside):
"""change the placing or the RA in the same monitor
for parameters, see restore_window above and
_get_new_coordinates_same_monitor below
"""
raWidth = RA[2] - RA[0]
raHeight = RA[3] - RA[1]
WA = monitor_info['Work']
MA = monitor_info['Monitor']
#offsetx = monitor_info['offsetx']
#offsety = monitor_info['offsety']
# norm to 0 oriented
RA[0] -= MA[0]
RA[1] -= MA[1]
RA[2] -= MA[0]
RA[3] -= MA[1]
WAWidth = WA[2] - WA[0]
WAHeight = WA[3] - WA[1]
RA[0], RA[2] = _get_new_coordinates_same_monitor(begin=RA[0], end=RA[2], size=WAWidth,
width=xwidth, positioning=xpos)
RA[1], RA[3] = _get_new_coordinates_same_monitor(begin=RA[1], end=RA[3], size=WAHeight,
width=ywidth, positioning=ypos)
fixed_width = not keepinside
RA[0], RA[2] = keepinside_restore_area(RA[0], RA[2], WAWidth, fixed_width=fixed_width, margin=1)
RA[1], RA[3] = keepinside_restore_area(RA[1], RA[3], WAHeight, fixed_width=fixed_width, margin=1)
# correct for WA again:
RA[0] += MA[0]
RA[1] += MA[1]
RA[2] += MA[0]
RA[3] += MA[1]
return RA
def _get_new_coordinates_same_monitor(begin, end, size, width, positioning, minWidth=10):
"""sqeeze or make larger the coordinates of the window in either direction
think in width here:
begin, end, actual coordinates with respect to left or top of
actual monitor
size: allowed size of the work area (width of height)
width: if false (None or 0) the same width is taken
if 1: size is taken
if < 1 (and > 0, assumed) this part of the size is taken
positioning: give the wanted position on the monitor:
None: do nothing, leave begin
'left', 'up': move to begin
'right', 'down': move to end
'center': center on the size
'relative': take the same spacing left and right as before the width change
a number between 0 and 1 (inclusive): calculate the left and right spacing
according to this number
"""
oldwidth = end - begin
if not width:
width = end - begin
elif width == 1:
# take size of monitor, positioning parameter irrelevant:
return 0, size
elif 0 < width <= 1:
width = int(size * width) # 0.5 takes half the screen
else:
raise ValueError('get_new_coordinates_same_monitor, illogical value for width: %s'% width)
width = max(width, minWidth)
if positioning is None:
return begin, begin + width
if type(positioning) == types.StringType:
if positioning in ('left', 'up'):
positioning = 0
elif positioning in ('right', 'down'):
positioning = 1
elif positioning in ('center',):
positioning = 0.5
elif positioning in ('relative',):
# relative to old spacing
oldspacing = size - oldwidth
newspacing = max(size - width, 0)
if oldspacing > 0:
positioning = 1.0 * begin / oldspacing
else:
positioning = 0.5
else:
raise ValueError("_get_new_coordinates_same_monitor: invalid positioning option: %s"% positioning)
if positioning < 0 or positioning > 1:
raise ValueError("get_new_coordinates_same_monitor: positioning number, should be between 0 and 1 (inclusive), not: %s"% positioning)
spacing = max((size - width), 0)
left = int(spacing * positioning)
return left, left + width
def keepinside_all_screens(left, right, virtL, virtR, fixed_width, border=1):
"""keep inside the virtual screen, allow for border
(horizontal and vertical called separate
"""
if left < virtL - border:
if fixed_width:
right += virtL - left - 1
if right > virtR + border:
right = virtR + border
left = virtL - border
if right > virtR + border:
if fixed_width:
left -= right - virtR - 1
if left < virtL - border:
left = virtL - border
right = virtR + border
return left, right
def keepinside_restore_area(left, right, size, fixed_width=1, margin=1):
"""adjust (restore)
"""
span = right - left
if -margin < left < right < size + 1:
return left, right
if fixed_width:
if left < -margin or span > size + margin*2:
left = -margin
right = span - margin
elif right > size + margin:
right = size + margin
left = right - span
else:
# width may alter, adjust to possibilities of monitor
if left < -margin or span > size + margin*2:
left = -margin
right = min(left+span, size+margin)
elif right > size + margin:
right = size + margin
left = max(right-span, -margin)
return left, right
def keepinside_restore_area(left, right, size, fixed_width=1, margin=1):
"""adjust (restore)
"""
span = right - left
if -margin < left < right < size + 1:
return left, right
if fixed_width:
if left < -margin or span > size + margin*2:
left = -margin
right = span - margin
elif right > size + margin:
right = size + margin
left = right - span
else:
# width may alter, adjust to possibilities of monitor
if left < -margin or span > size + margin*2:
left = -margin
right = min(left+span, size+margin)
elif right > size + margin:
right = size + margin
left = max(right-span, -margin)
return left, right
#===================== more monitors: ===============================================
def move_to_monitor(hndle, monitor, currentMon, resize=0):
"""move window with hndle to monitor with hndle monitor
"""
monitor_info()
toMin = win32con.SW_SHOWMINIMIZED
toMax = win32con.SW_SHOWMAXIMIZED
toRestore = win32con.SW_RESTORE
info = list( win32gui.GetWindowPlacement(hndle) )
MInew = MONITOR_INFO[monitor]
MIcur = MONITOR_INFO[currentMon]
RA = list(info[4])
maximized = ( info[1] == win32con.SW_SHOWMAXIMIZED)
newRA = correct_restore_area(RA, monitor_info_new=MInew,
monitor_info_old=MIcur,
resize=resize,
keepinside=resize)
info[1] = toRestore
if maximized:
offsetx = MInew['offsetx']
offsety = MInew['offsety']
work = MInew['Work']
# set RA temp to place where maximized window will come as well:
info[4] = (work[0]-offsetx-BORDERX, work[1]-offsety-BORDERY, work[2]-offsetx+BORDERX, work[3]-offsety+BORDERY)
info[1] = toRestore
# set to restore in new maximized coordinates:
win32gui.SetWindowPlacement(hndle, tuple(info) )
info[1] = toMax
info[4] = tuple(newRA)
# set to max, with new calculated restore parameters:
win32gui.SetWindowPlacement(hndle, tuple(info) )
else:
info[4] = tuple(newRA)
win32gui.SetWindowPlacement(hndle, tuple(info) )
def correct_restore_area(RA, monitor_info_new, monitor_info_old,
resize=None, keepinside=None):
"""place RA inside the newWA, preserving relative position as much as possible (other monitor)
input: restore_area (RA) in 'Work' coordinates
info of monitor_info_new and monitor_info_old
resize: resize relative to previous if true, keep size if false.
keepinside: keep the window inside the work area of the monitor (normally when resize = true)
"""
#print 'old RA: %s'% RA
raWidth = RA[2] - RA[0]
raHeight = RA[3] - RA[1]
oldWA = monitor_info_old['Work']
newWA = monitor_info_new['Work']
oldMA = monitor_info_old['Monitor']
newMA = monitor_info_new['Monitor']
#offsetx_new = monitor_info_new['offsetx']
#offsety_new = monitor_info_new['offsety']
#offsetx_old = monitor_info_old['offsetx']
#offsety_old = monitor_info_old['offsety']
# norm to 0 oriented
RA[0] -= oldMA[0]
RA[1] -= oldMA[1]
RA[2] -= oldMA[0]
RA[3] -= oldMA[1]
#print 'old calc area: %s'% RA
newWAWidth = newWA[2] - newWA[0]
newWAHeight = newWA[3] - newWA[1]
oldWAWidth = oldWA[2] - oldWA[0]
oldWAHeight = oldWA[3] - oldWA[1]
if resize:
RA[0], RA[2] = _get_new_coordinates_resize_other_monitor(begin=RA[0], end=RA[2], oldSize=oldWAWidth,
newSize=newWAWidth)
RA[1], RA[3] = _get_new_coordinates_resize_other_monitor(begin=RA[1], end=RA[3], oldSize=oldWAHeight,
newSize=newWAHeight)
else:
# no resize, keep width, height:
RA[0], RA[2] = _get_new_coordinates_fixed_other_monitor(begin=RA[0], end=RA[2], oldSize=oldWAWidth,
newSize=newWAWidth)
RA[1], RA[3] = _get_new_coordinates_fixed_other_monitor(begin=RA[1], end=RA[3], oldSize=oldWAHeight,
newSize=newWAHeight)
fixed_width = not resize
RA[0], RA[2] = keepinside_restore_area(RA[0], RA[2], newWAWidth, fixed_width=fixed_width, margin=1)
RA[1], RA[3] = keepinside_restore_area(RA[1], RA[3], newWAHeight, fixed_width=fixed_width, margin=1)
# correct for new WA:
RA[0] += newMA[0]
RA[1] += newMA[1]
RA[2] += newMA[0]
RA[3] += newMA[1]
#print 'new RA: %s'% RA
return RA
def _get_new_coordinates_resize_other_monitor(begin, end, oldSize, newSize):
"""sqeeze or make larger the coordinates of the window in either direction
"""
newBegin = int(begin * newSize / oldSize + 0.5)
newEnd = int(end * newSize / oldSize + 0.5)
return newBegin, newEnd
def _get_new_coordinates_fixed_other_monitor(begin, end, oldSize, newSize):
"""get the coordinates for the window in the new monitor, position at same relative place
"""