Debian Codegraph @

src/mouseinfo/__init__.py

raw symbols SCIP
1 # MouseInfo by Al Sweigart [email protected]
2
3 # Note: how to specify where a tkintr window opens:
4 # https://stackoverflow.com/questions/14910858/how-to-specify-where-a-tkinter-window-opens
5
6 """
7 Features we should consider adding:
8 * Register a global hotkey for copying/logging info. (Should this hotkey be configurable?)
9
10 Features that have been considered and rejected:
11
12 * The Save Log/Save Screenshot buttons should open a file dialog box.
13 * The Save Log button should append text, instead of overwrite it.
14 * The log text area should prepopulate itself with the contents of the given filename.
15 * The button delay should be configurable instead of just set to 3 seconds.
16 """
17
18 __version__ = '0.1.4'
19 import pyperclip, sys, os, platform, webbrowser
20
21 #from enum import Enum
22 from ctypes import (
23 c_bool, c_int32, c_int64, c_size_t, c_uint16, c_uint32, c_void_p,
24 cdll, util,
25 )
26
27 # =========================================================================
28 # Originally, these functions were pulled in from PyAutoGUI. However, to
29 # make this module independent of PyAutoGUI, the code for these functions
30 # has been copy/pasted into the following section:
31 # NOTE: Any bug fixes for these functions in PyAutoGUI will have to be
32 # manually merged into MouseInfo.
33 #from pyautogui import position, screenshot, size
34 # =========================================================================
35 # Alternatively, this code makes this application not dependent on PyAutoGUI
36 # by copying the code for the position() and screenshot() functions into this
37 # source code file.
38 import datetime, subprocess
39
40 try:
41 from PIL import Image
42 _PILLOW_INSTALLED = True
43 except ImportError:
44 _PILLOW_INSTALLED = False
45
46 if sys.platform == 'win32':
47 import ctypes
48
49 if _PILLOW_INSTALLED:
50 from PIL import ImageGrab
51
52 # Makes this process aware of monitor scaling so the screenshots are correctly sized:
53 try:
54 ctypes.windll.user32.SetProcessDPIAware()
55 except AttributeError:
56 pass # Windows XP doesn't support this, so just do nothing.
57
58 dc = ctypes.windll.user32.GetDC(0)
59
60 class POINT(ctypes.Structure):
61 _fields_ = [('x', ctypes.c_long),
62 ('y', ctypes.c_long)]
63
64 def _winPosition():
65 cursor = POINT()
66 ctypes.windll.user32.GetCursorPos(ctypes.byref(cursor))
67 return (cursor.x, cursor.y)
68 position = _winPosition
69
70
71 def _winScreenshot(filename=None):
72 # TODO - Use the winapi to get a screenshot, and compare performance with ImageGrab.grab()
73 # https://stackoverflow.com/a/3586280/1893164
74 try:
75 im = ImageGrab.grab()
76 if filename is not None:
77 im.save(filename)
78 except NameError:
79 raise ImportError('Pillow module must be installed to use screenshot functions on Windows.')
80 return im
81 screenshot = _winScreenshot
82
83 def _winSize():
84 return (ctypes.windll.user32.GetSystemMetrics(0), ctypes.windll.user32.GetSystemMetrics(1))
85 size = _winSize
86
87 def _winGetPixel(x, y):
88 colorRef = ctypes.windll.gdi32.GetPixel(dc, x, y) # A COLORREF value as 0x00bbggrr. See https://docs.microsoft.com/en-us/windows/win32/gdi/colorref
89 red = colorRef % 256
90 colorRef //= 256
91 green = colorRef % 256
92 colorRef //= 256
93 blue = colorRef
94
95 return (red, green, blue)
96 getPixel = _winGetPixel
97
98
99 elif sys.platform == 'darwin':
100 from rubicon.objc import ObjCClass, CGPoint
101 from rubicon.objc.types import register_preferred_encoding
102
103 #####################################################################
104
105 appkit = cdll.LoadLibrary(util.find_library('AppKit'))
106
107 NSEvent = ObjCClass('NSEvent')
108 NSEvent.declare_class_property('mouseLocation')
109 # NSSystemDefined = ObjCClass('NSSystemDefined')
110
111 #####################################################################
112
113 core_graphics = cdll.LoadLibrary(util.find_library('CoreGraphics'))
114
115 CGDirectDisplayID = c_uint32
116
117 CGEventRef = c_void_p
118 register_preferred_encoding(b'^{__CGEvent=}', CGEventRef)
119
120 CGEventSourceRef = c_void_p
121 register_preferred_encoding(b'^{__CGEventSource=}', CGEventSourceRef)
122
123 CGEventTapLocation = c_uint32
124
125 CGEventType = c_uint32
126
127 CGEventField = c_uint32
128
129 CGKeyCode = c_uint16
130
131 CGMouseButton = c_uint32
132
133 CGScrollEventUnit = c_uint32
134
135 # size_t CGDisplayPixelsWide(CGDirectDisplayID display);
136 core_graphics.CGDisplayPixelsWide.argtypes = [CGDirectDisplayID]
137 core_graphics.CGDisplayPixelsWide.restype = c_size_t
138
139 # CGEventRef CGEventCreateKeyboardEvent(CGEventSourceRef source, CGKeyCode virtualKey, bool keyDown);
140 core_graphics.CGEventCreateKeyboardEvent.argtypes = [CGEventSourceRef, CGKeyCode, c_bool]
141 core_graphics.CGEventCreateKeyboardEvent.restype = CGEventRef
142
143 # CGEventRef CGEventCreateMouseEvent(
144 # CGEventSourceRef source, CGEventType mouseType, CGPoint mouseCursorPosition, CGMouseButton mouseButton);
145 core_graphics.CGEventCreateMouseEvent.argtypes = [CGEventSourceRef, CGEventType, CGPoint, CGMouseButton]
146 core_graphics.CGEventCreateMouseEvent.restype = CGEventRef
147
148 # CGEventRef CGEventCreateScrollWheelEvent(
149 # CGEventSourceRef source, CGScrollEventUnit units, uint32_t wheelCount, int32_t wheel1, ...);
150 core_graphics.CGEventCreateScrollWheelEvent.argtypes = [CGEventSourceRef, CGScrollEventUnit, c_uint32, c_int32]
151 core_graphics.CGEventCreateScrollWheelEvent.restype = CGEventRef
152
153 # void CGEventSetIntegerValueField(CGEventRef event, CGEventField field, int64_t value);
154 core_graphics.CGEventSetIntegerValueField.argtypes = [CGEventRef, CGEventField, c_int64]
155 core_graphics.CGEventSetIntegerValueField.restype = None
156
157 # void CGEventSetType(CGEventRef event, CGEventType type);
158 core_graphics.CGEventSetType.argtype = [CGEventRef, CGEventType]
159 core_graphics.CGEventSetType.restype = None
160
161 # void CGEventPost(CGEventTapLocation tap, CGEventRef event);
162 core_graphics.CGEventPost.argtypes = [CGEventTapLocation, CGEventRef]
163 core_graphics.CGEventPost.restype = None
164
165 # CGDirectDisplayID CGMainDisplayID(void);
166 core_graphics.CGMainDisplayID.argtypes = []
167 core_graphics.CGMainDisplayID.restype = CGDirectDisplayID
168
169
170
171 def _macPosition():
172 loc = NSEvent.mouseLocation
173 return int(loc.x), int(core_graphics.CGDisplayPixelsHigh(0) - loc.y)
174 position = _macPosition
175
176
177 def _macScreenshot(filename=None):
178 if filename is not None:
179 tmpFilename = filename
180 else:
181 tmpFilename = 'screenshot%s.png' % (datetime.datetime.now().strftime('%Y-%m%d_%H-%M-%S-%f'))
182 subprocess.call(['screencapture', '-x', tmpFilename])
183 im = Image.open(tmpFilename)
184
185 # force loading before unlinking, Image.open() is lazy
186 im.load()
187
188 if filename is None:
189 os.unlink(tmpFilename)
190 return im
191 screenshot = _macScreenshot
192
193 def _macSize():
194 return (
195 core_graphics.CGDisplayPixelsWide(core_graphics.CGMainDisplayID()),
196 core_graphics.CGDisplayPixelsHigh(core_graphics.CGMainDisplayID())
197 )
198 size = _macSize
199
200 def _macGetPixel(x, y):
201 rgbValue = screenshot().getpixel((x, y))
202 return rgbValue[0], rgbValue[1], rgbValue[2]
203 getPixel = _macGetPixel
204
205
206 elif platform.system() == 'Linux':
207 from Xlib.display import Display
208 import errno
209
210 scrotExists = False
211 try:
212 whichProc = subprocess.Popen(
213 ['which', 'scrot'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
214 scrotExists = whichProc.wait() == 0
215 except OSError as ex:
216 if ex.errno == errno.ENOENT:
217 # if there is no "which" program to find scrot, then assume there
218 # is no scrot.
219 pass
220 else:
221 raise
222
223 _display = Display(os.environ['DISPLAY'])
224
225 def _linuxPosition():
226 coord = _display.screen().root.query_pointer()._data
227 return coord["root_x"], coord["root_y"]
228 position = _linuxPosition
229
230 def _linuxScreenshot(filename=None):
231 if not scrotExists:
232 raise NotImplementedError('"scrot" must be installed to use screenshot functions in Linux. Run: sudo apt-get install scrot')
233
234 if filename is not None:
235 tmpFilename = filename
236 else:
237 tmpFilename = '.screenshot%s.png' % (datetime.datetime.now().strftime('%Y-%m%d_%H-%M-%S-%f'))
238
239 if scrotExists:
240 subprocess.call(['scrot', '-z', tmpFilename])
241 im = Image.open(tmpFilename)
242
243 # force loading before unlinking, Image.open() is lazy
244 im.load()
245
246 if filename is None:
247 os.unlink(tmpFilename)
248 return im
249 else:
250 raise Exception('The scrot program must be installed to take a screenshot with PyScreeze on Linux. Run: sudo apt-get install scrot')
251 screenshot = _linuxScreenshot
252
253 def _linuxSize():
254 return _display.screen().width_in_pixels, _display.screen().height_in_pixels
255 size = _linuxSize
256
257 def _linuxGetPixel(x, y):
258 rgbValue = screenshot().getpixel((x, y))
259 return rgbValue[0], rgbValue[1], rgbValue[2]
260 getPixel = _linuxGetPixel
261 # =========================================================================
262
263 RUNNING_PYTHON_2 = sys.version_info[0] == 2
264
265 if platform.system() == 'Linux':
266 if RUNNING_PYTHON_2:
267 try:
268 import Tkinter as tkinter
269 ttk = tkinter
270 from Tkinter import Event
271 except ImportError:
272 raise ImportError('You must install tkinter on Linux to use MouseInfo. For Ubuntu Linux, run the following: sudo apt-get install python-tk python-dev')
273 else:
274 # Running Python 3+:
275 try:
276 import tkinter
277 from tkinter import ttk
278 from tkinter import Event
279 except ImportError:
280 raise ImportError('You must install tkinter on Linux to use MouseInfo. For Ubuntu Linux, run the following: sudo apt-get install python3-tk python3-dev')
281 else:
282 # Running Windows or macOS:
283 if RUNNING_PYTHON_2:
284 import Tkinter as tkinter
285 ttk = tkinter
286 from Tkinter import Event
287 else:
288 # Running Python 3+:
289 import tkinter
290 from tkinter import ttk
291 from tkinter import Event
292
293 MOUSE_INFO_BUTTON_WIDTH = 16 # A standard width for the buttons in the MouseInfo window.
294
295 class MouseInfoWindow:
296 def _updateMouseInfoTextFields(self):
297 # Update the XY and RGB text fields in the MouseInfo window.
298
299 # Get the XY coordinates of the current mouse position:
300 x, y = position()
301 self.xyTextboxSV.set('%s,%s' % (x - self.xOrigin, y - self.yOrigin))
302
303 # MouseInfo currently only works on the primary monitor, and doesn't
304 # support multi-monitor setups. The color information isn't reliable
305 # when the mouse is not on the primary monitor, so display an error instead.
306 width, height = size()
307 if not _PILLOW_INSTALLED:
308 self.rgbSV.set('NA_Pillow_unsupported')
309 elif sys.platform == 'darwin':
310 # TODO - Until I can get screenshots without the mouse cursor, this feature doesn't work on mac.
311 self.rgbSV.set('NA_on_macOS')
312 elif not (0 <= x < width and 0 <= y < height):
313 self.rgbSV.set('NA_on_multimonitor_setups')
314 else:
315 # Get the RGB color value of the pixel currently under the mouse:
316 # NOTE: On Windows & Linux, Pillow's getpixel() returns a 3-integer tuple, but on macOS it returns a 4-integer tuple.
317 r, g, b = getPixel(x, y)
318 self.rgbSV.set('%s,%s,%s' % (r, g, b))
319
320 if not _PILLOW_INSTALLED:
321 self.rgbHexSV.set('NA_Pillow_unsupported')
322 elif sys.platform == 'darwin':
323 # TODO - Until I can get screenshots without the mouse cursor, this feature doesn't work on mac.
324 self.rgbHexSV.set('NA_on_macOS')
325 elif not (0 <= x < width and 0 <= y < height):
326 self.rgbHexSV.set('NA_on_multimonitor_setups')
327 else:
328 # Convert this RGB value into a hex RGB value:
329 rHex = hex(r)[2:].upper().rjust(2, '0')
330 gHex = hex(g)[2:].upper().rjust(2, '0')
331 bHex = hex(b)[2:].upper().rjust(2, '0')
332 hexColor = '#%s%s%s' % (rHex, gHex, bHex)
333 self.rgbHexSV.set(hexColor)
334
335 if (not _PILLOW_INSTALLED) or (sys.platform == 'darwin') or (not (0 <= x < width and 0 <= y < height)):
336 self.colorFrame.configure(background='black')
337 else:
338 # Update the color panel:
339 self.colorFrame.configure(background=hexColor)
340
341 # As long as the self.isRunning variable is True,
342 # schedule this function to be called again in 100 milliseconds.
343 # NOTE: Previously this if-else code was at the top of the function
344 # so that I could avoid the "invalid command name" message that
345 # was popping up (this didn't work though), but it was also causing
346 # a weird bug where the text fields weren't populated until I moved
347 # the tkinter window. I have no idea why that behavior was happening.
348 # You can reproduce it by moving this if-else code to the top of this
349 # function.
350 if self.isRunning:
351 self._updateMouseInfoJob = self.root.after(100, self._updateMouseInfoTextFields)
352 else:
353 return # MouseInfo window has been closed, so return immediately.
354
355
356 def _copyText(self, textToCopy):
357 try:
358 pyperclip.copy(textToCopy)
359 self.statusbarSV.set('Copied ' + textToCopy)
360 except pyperclip.PyperclipException as e:
361 if platform.system() == 'Linux':
362 self.statusbarSV.set('Copy failed. Run "sudo apt-get install xsel".')
363 else:
364 self.statusbarSV.set('Clipboard error: ' + str(e))
365
366
367 def _copyXyMouseInfo(self, *args):
368 # Copy the contents of the XY coordinate text field in the MouseInfo
369 # window to the clipboard.
370
371 if len(args) > 0 and isinstance(args[0], Event):
372 args = () # When the hotkey is pressed, an Event object is in args. Let's just get rid of it and let the rest of the code run as normal.
373
374 if self.delayEnabledSV.get() == 'on' and len(args) == 0:
375 # Start countdown by having after() call this function in 1 second:
376 self.root.after(1000, self._copyXyMouseInfo, 2)
377 self.xyCopyButtonSV.set('Copy in 3')
378 elif len(args) == 1 and args[0] == 2:
379 # Continue countdown by having after() call this function in 1 second:
380 self.root.after(1000, self._copyXyMouseInfo, 1)
381 self.xyCopyButtonSV.set('Copy in 2')
382 elif len(args) == 1 and args[0] == 1:
383 # Continue countdown by having after() call this function in 1 second:
384 self.root.after(1000, self._copyXyMouseInfo, 0)
385 self.xyCopyButtonSV.set('Copy in 1')
386 else:
387 # Delay disabled or countdown has finished:
388 self._copyText(self.xyTextboxSV.get())
389 self.xyCopyButtonSV.set('Copy XY')
390
391
392 def _copyRgbMouseInfo(self, *args):
393 # Copy the contents of the RGB color text field in the MouseInfo
394 # window to the clipboard.
395
396 if len(args) > 0 and isinstance(args[0], Event):
397 args = () # When the hotkey is pressed, an Event object is in args. Let's just get rid of it and let the rest of the code run as normal.
398
399 if self.delayEnabledSV.get() == 'on' and len(args) == 0:
400 # Start countdown by having after() call this function in 1 second:
401 self.root.after(1000, self._copyRgbMouseInfo, 2)
402 self.rgbCopyButtonSV.set('Copy in 3')
403 elif len(args) == 1 and args[0] == 2:
404 # Continue countdown by having after() call this function in 1 second:
405 self.root.after(1000, self._copyRgbMouseInfo, 1)
406 self.rgbCopyButtonSV.set('Copy in 2')
407 elif len(args) == 1 and args[0] == 1:
408 # Continue countdown by having after() call this function in 1 second:
409 self.root.after(1000, self._copyRgbMouseInfo, 0)
410 self.rgbCopyButtonSV.set('Copy in 1')
411 else:
412 # Delay disabled or countdown has finished:
413 self._copyText(self.rgbSV.get())
414 self.rgbCopyButtonSV.set('Copy RGB')
415
416
417 def _copyRgbHexMouseInfo(self, *args):
418 # Copy the contents of the RGB hex color text field in the MouseInfo
419 # window to the clipboard.
420
421 if len(args) > 0 and isinstance(args[0], Event):
422 args = () # When the hotkey is pressed, an Event object is in args. Let's just get rid of it and let the rest of the code run as normal.
423
424 if self.delayEnabledSV.get() == 'on' and len(args) == 0:
425 # Start countdown by having after() call this function in 1 second:
426 self.root.after(1000, self._copyRgbHexMouseInfo, 2)
427 self.rgbHexCopyButtonSV.set('Copy in 3')
428 elif len(args) == 1 and args[0] == 2:
429 # Continue countdown by having after() call this function in 1 second:
430 self.root.after(1000, self._copyRgbHexMouseInfo, 1)
431 self.rgbHexCopyButtonSV.set('Copy in 2')
432 elif len(args) == 1 and args[0] == 1:
433 # Continue countdown by having after() call this function in 1 second:
434 self.root.after(1000, self._copyRgbHexMouseInfo, 0)
435 self.rgbHexCopyButtonSV.set('Copy in 1')
436 else:
437 # Delay disabled or countdown has finished:
438 self._copyText(self.rgbHexSV.get())
439 self.rgbHexCopyButtonSV.set('Copy RGB Hex')
440
441
442 def _copyAllMouseInfo(self, *args):
443 # Copy the contents of the XY coordinate and RGB color text fields in the
444 # MouseInfo window to the log text field.
445 textFieldContents = '%s %s %s' % (self.xyTextboxSV.get(),
446 self.rgbSV.get(),
447 self.rgbHexSV.get())
448 #self._copyText(textFieldContents)
449
450 if len(args) > 0 and isinstance(args[0], Event):
451 args = () # When the hotkey is pressed, an Event object is in args. Let's just get rid of it and let the rest of the code run as normal.
452
453 if self.delayEnabledSV.get() == 'on' and len(args) == 0:
454 # Start countdown by having after() call this function in 1 second:
455 self.root.after(1000, self._copyAllMouseInfo, 2)
456 self.allCopyButtonSV.set('Copy in 3')
457 elif len(args) == 1 and args[0] == 2:
458 # Continue countdown by having after() call this function in 1 second:
459 self.root.after(1000, self._copyAllMouseInfo, 1)
460 self.allCopyButtonSV.set('Copy in 2')
461 elif len(args) == 1 and args[0] == 1:
462 # Continue countdown by having after() call this function in 1 second:
463 self.root.after(1000, self._copyAllMouseInfo, 0)
464 self.allCopyButtonSV.set('Copy in 1')
465 else:
466 # Delay disabled or countdown has finished:
467 textFieldContents = '%s %s %s' % (self.xyTextboxSV.get(),
468 self.rgbSV.get(),
469 self.rgbHexSV.get())
470 self._copyText(textFieldContents)
471 self.allCopyButtonSV.set('Copy All')
472
473
474 def _logXyMouseInfo(self, *args):
475 # Log the contents of the XY coordinate text field in the MouseInfo
476 # window to the log text field.
477
478 if len(args) > 0 and isinstance(args[0], Event):
479 args = () # When the hotkey is pressed, an Event object is in args. Let's just get rid of it and let the rest of the code run as normal.
480
481 if self.delayEnabledSV.get() == 'on' and len(args) == 0:
482 # Start countdown by having after() call this function in 1 second:
483 self.root.after(1000, self._logXyMouseInfo, 2)
484 self.xyLogButtonSV.set('Log in 3')
485 elif len(args) == 1 and args[0] == 2:
486 # Continue countdown by having after() call this function in 1 second:
487 self.root.after(1000, self._logXyMouseInfo, 1)
488 self.xyLogButtonSV.set('Log in 2')
489 elif len(args) == 1 and args[0] == 1:
490 # Continue countdown by having after() call this function in 1 second:
491 self.root.after(1000, self._logXyMouseInfo, 0)
492 self.xyLogButtonSV.set('Log in 1')
493 else:
494 # Delay disabled or countdown has finished:
495 logContents = self.logTextarea.get('1.0', 'end-1c') + '%s\n' % (self.xyTextboxSV.get()) # 'end-1c' doesn't include the final newline
496 self.logTextboxSV.set(logContents)
497 self._setLogTextAreaContents(logContents)
498 self.statusbarSV.set('Logged ' + self.xyTextboxSV.get())
499 self.xyLogButtonSV.set('Log XY')
500
501
502 def _logRgbMouseInfo(self, *args):
503 # Log the contents of the RGB color text field in the MouseInfo
504 # window to the log text field.
505
506 if len(args) > 0 and isinstance(args[0], Event):
507 args = () # When the hotkey is pressed, an Event object is in args. Let's just get rid of it and let the rest of the code run as normal.
508
509 if self.delayEnabledSV.get() == 'on' and len(args) == 0:
510 # Start countdown by having after() call this function in 1 second:
511 self.root.after(1000, self._logRgbMouseInfo, 2)
512 self.rgbLogButtonSV.set('Log in 3')
513 elif len(args) == 1 and args[0] == 2:
514 # Continue countdown by having after() call this function in 1 second:
515 self.root.after(1000, self._logRgbMouseInfo, 1)
516 self.rgbLogButtonSV.set('Log in 2')
517 elif len(args) == 1 and args[0] == 1:
518 # Continue countdown by having after() call this function in 1 second:
519 self.root.after(1000, self._logRgbMouseInfo, 0)
520 self.rgbLogButtonSV.set('Log in 1')
521 else:
522 # Delay disabled or countdown has finished:
523 logContents = self.logTextarea.get('1.0', 'end-1c') + '%s\n' % (self.rgbSV.get()) # 'end-1c' doesn't include the final newline
524 self.logTextboxSV.set(logContents)
525 self._setLogTextAreaContents(logContents)
526 self.statusbarSV.set('Logged ' + self.rgbSV.get())
527 self.rgbLogButtonSV.set('Log RGB')
528
529
530 def _logRgbHexMouseInfo(self, *args):
531 # Log the contents of the RGB hex color text field in the MouseInfo
532 # window to the log text field.
533
534 if len(args) > 0 and isinstance(args[0], Event):
535 args = () # When the hotkey is pressed, an Event object is in args. Let's just get rid of it and let the rest of the code run as normal.
536
537 if self.delayEnabledSV.get() == 'on' and len(args) == 0:
538 # Start countdown by having after() call this function in 1 second:
539 self.root.after(1000, self._logRgbHexMouseInfo, 2)
540 self.rgbHexLogButtonSV.set('Log in 3')
541 elif len(args) == 1 and args[0] == 2:
542 # Continue countdown by having after() call this function in 1 second:
543 self.root.after(1000, self._logRgbHexMouseInfo, 1)
544 self.rgbHexLogButtonSV.set('Log in 2')
545 elif len(args) == 1 and args[0] == 1:
546 # Continue countdown by having after() call this function in 1 second:
547 self.root.after(1000, self._logRgbHexMouseInfo, 0)
548 self.rgbHexLogButtonSV.set('Log in 1')
549 else:
550 # Delay disabled or countdown has finished:
551 logContents = self.logTextarea.get('1.0', 'end-1c') + '%s\n' % (self.rgbHexSV.get()) # 'end-1c' doesn't include the final newline
552 self.logTextboxSV.set(logContents)
553 self._setLogTextAreaContents(logContents)
554 self.statusbarSV.set('Logged ' + self.rgbHexSV.get())
555 self.rgbHexLogButtonSV.set('Log RGB Hex')
556
557
558 def _logAllMouseInfo(self, *args):
559 # Log the contents of the XY coordinate and RGB color text fields in the
560 # MouseInfo window to the log text field.
561
562 if len(args) > 0 and isinstance(args[0], Event):
563 args = () # When the hotkey is pressed, an Event object is in args. Let's just get rid of it and let the rest of the code run as normal.
564
565 if self.delayEnabledSV.get() == 'on' and len(args) == 0:
566 # Start countdown by having after() call this function in 1 second:
567 self.root.after(1000, self._logAllMouseInfo, 2)
568 self.allLogButtonSV.set('Log in 3')
569 elif len(args) == 1 and args[0] == 2:
570 # Continue countdown by having after() call this function in 1 second:
571 self.root.after(1000, self._logAllMouseInfo, 1)
572 self.allLogButtonSV.set('Log in 2')
573 elif len(args) == 1 and args[0] == 1:
574 # Continue countdown by having after() call this function in 1 second:
575 self.root.after(1000, self._logAllMouseInfo, 0)
576 self.allLogButtonSV.set('Log in 1')
577 else:
578 # Delay disabled or countdown has finished:
579 textFieldContents = '%s %s %s' % (self.xyTextboxSV.get(),
580 self.rgbSV.get(),
581 self.rgbHexSV.get())
582 logContents = self.logTextarea.get('1.0', 'end-1c') + '%s\n' % (textFieldContents) # 'end-1c' doesn't include the final newline
583 self.logTextboxSV.set(logContents)
584 self._setLogTextAreaContents(logContents)
585 self.statusbarSV.set('Logged ' + textFieldContents)
586 self.allLogButtonSV.set('Log All')
587
588 def _xyOriginChanged(self, sv):
589 contents = sv.get()
590 if len(contents.split(',')) != 2:
591 return # Do nothing if the text is invalid
592 x, y = contents.split(',')
593 x = x.strip()
594 y = y.strip()
595 if not x.isdecimal() or not y.isdecimal():
596 return # Do nothing.
597 self.xOrigin = int(x)
598 self.yOrigin = int(y)
599 self.statusbarSV.set('Set XY Origin to ' + str(self.xOrigin) + ', ' + str(self.yOrigin))
600
601 def _setLogTextAreaContents(self, logContents):
602 if RUNNING_PYTHON_2:
603 self.logTextarea.delete('1.0', tkinter.END)
604 self.logTextarea.insert(tkinter.END, logContents)
605 else:
606 self.logTextarea.replace('1.0', tkinter.END, logContents)
607
608 # Scroll to the bottom of the text area:
609 topOfTextArea, bottomOfTextArea = self.logTextarea.yview()
610 self.logTextarea.yview_moveto(bottomOfTextArea)
611
612
613 def _saveLogFile(self, *args):
614 # Save the current contents of the log file text field. Automatically
615 # overwrites the file if it exists. Displays an error message in the
616 # status bar if there is a problem.
617 try:
618 with open(self.logFilenameSV.get(), 'w') as fo:
619 fo.write(self.logTextboxSV.get())
620 except Exception as e:
621 self.statusbarSV.set('ERROR: ' + str(e))
622 else:
623 self.statusbarSV.set('Log file saved to ' + self.logFilenameSV.get())
624
625
626 def _saveScreenshotFile(self, *args):
627 # Saves a screenshot. Automatically overwrites the file if it exists.
628 # Displays an error message in the status bar if there is a problem.
629
630 if not _PILLOW_INSTALLED:
631 self.statusbarSV.set('ERROR: NA_Pillow_unsupported')
632 return
633
634 try:
635 screenshot(self.screenshotFilenameSV.get())
636 except Exception as e:
637 self.statusbarSV.set('ERROR: ' + str(e))
638 else:
639 self.statusbarSV.set('Screenshot file saved to ' + self.screenshotFilenameSV.get())
640
641
642 def __init__(self):
643 """Launches the MouseInfo window, which displays XY coordinate and RGB
644 color information for the mouse's current position."""
645
646 self.isRunning = True # While True, the text fields will update.
647
648 # Create the MouseInfo window:
649 self.root = tkinter.Tk()
650 self.root.title('MouseInfo ' + __version__)
651 self.root.minsize(400, 100)
652
653 # Create the main frame in the MouseInfo window:
654 if RUNNING_PYTHON_2:
655 mainframe = tkinter.Frame(self.root)
656 else:
657 mainframe = ttk.Frame(self.root, padding='3 3 12 12')
658
659 # Set up the grid for the MouseInfo window's widgets:
660 mainframe.grid(column=0, row=0, sticky=(tkinter.N, tkinter.W, tkinter.E, tkinter.S))
661 mainframe.columnconfigure(0, weight=1)
662 mainframe.rowconfigure(0, weight=1)
663
664 # WIDGETS ON ROW 1:
665 CUR_ROW = 1 # I'm using a variable because it's easier to make changes to the source code this way.
666
667 # Set up the instructional text label:
668 #ttk.Label(mainframe, text='Tab over the buttons and press Enter to\n"click" them as you move the mouse around.').grid(column=1, row=1, columnspan=2, sticky=tkinter.W)
669 self.delayEnabledSV = tkinter.StringVar()
670 self.delayEnabledSV.set('on')
671 delayCheckbox = ttk.Checkbutton(mainframe, text='3 Sec. Button Delay', variable=self.delayEnabledSV, onvalue='on', offvalue='off')
672 delayCheckbox.grid(column=1, row=CUR_ROW, columnspan=2, sticky=tkinter.W)
673
674 # Set up the button to copy the XY coordinates to the clipboard:
675 self.allCopyButtonSV = tkinter.StringVar()
676 self.allCopyButtonSV.set('Copy All (F1)')
677 self.allCopyButton = ttk.Button(mainframe, textvariable=self.allCopyButtonSV, width=MOUSE_INFO_BUTTON_WIDTH, command=self._copyAllMouseInfo)
678 self.allCopyButton.grid(column=3, row=CUR_ROW, sticky=tkinter.W)
679 self.allCopyButton.bind('<Return>', self._copyAllMouseInfo)
680
681 # Set up the button to copy the XY coordinates to the clipboard:
682 self.allLogButtonSV = tkinter.StringVar()
683 self.allLogButtonSV.set('Log All (F5)')
684 self.allLogButton = ttk.Button(mainframe, textvariable=self.allLogButtonSV, width=MOUSE_INFO_BUTTON_WIDTH, command=self._logAllMouseInfo)
685 self.allLogButton.grid(column=4, row=CUR_ROW, sticky=tkinter.W)
686 self.allLogButton.bind('<Return>', self._logAllMouseInfo)
687
688 # Set up the variables for the content of the MouseInfo window's text fields:
689 self.xyTextboxSV = tkinter.StringVar() # The str contents of the xy text field.
690 self.rgbSV = tkinter.StringVar() # The str contents of the rgb text field.
691 self.rgbHexSV = tkinter.StringVar() # The str contents of the rgb hex text field.
692 self.xyOriginSV = tkinter.StringVar() # The str contents of the xy origin field.
693 self.logTextboxSV = tkinter.StringVar() # The str contents of the log text area.
694 self.logFilenameSV = tkinter.StringVar() # The str contents of the log filename text field.
695 self.screenshotFilenameSV = tkinter.StringVar() # The str contents of the screenshot filename text field.
696 self.statusbarSV = tkinter.StringVar() # The str contents of the status bar at the bottom of the window.
697
698 # WIDGETS ON ROW 3:
699 CUR_ROW += 1
700
701 # Set up the XY coordinate text field and label:
702 self.xyInfoTextbox = ttk.Entry(mainframe, width=16, textvariable=self.xyTextboxSV)
703 self.xyInfoTextbox.grid(column=2, row=CUR_ROW, sticky=(tkinter.W, tkinter.E))
704 ttk.Label(mainframe, text='XY Position').grid(column=1, row=CUR_ROW, sticky=tkinter.W)
705
706 # Set up the button to copy the XY coordinates to the clipboard:
707 self.xyCopyButtonSV = tkinter.StringVar()
708 self.xyCopyButtonSV.set('Copy XY (F2)')
709 self.xyCopyButton = ttk.Button(mainframe, textvariable=self.xyCopyButtonSV, width=MOUSE_INFO_BUTTON_WIDTH, command=self._copyXyMouseInfo)
710 self.xyCopyButton.grid(column=3, row=CUR_ROW, sticky=tkinter.W)
711 self.xyCopyButton.bind('<Return>', self._copyXyMouseInfo)
712
713 # Set up the button to log the XY coordinates:
714 self.xyLogButtonSV = tkinter.StringVar()
715 self.xyLogButtonSV.set('Log XY (F6)')
716 self.xyLogButton = ttk.Button(mainframe, textvariable=self.xyLogButtonSV, width=MOUSE_INFO_BUTTON_WIDTH, command=self._logXyMouseInfo)
717 self.xyLogButton.grid(column=4, row=CUR_ROW, sticky=tkinter.W)
718 self.xyLogButton.bind('<Return>', self._logXyMouseInfo)
719
720 # WIDGETS ON ROW 4:
721 CUR_ROW += 1
722
723 # Set up the RGB color text field and label:
724 self.rgbSV_entry = ttk.Entry(mainframe, width=16, textvariable=self.rgbSV)
725 self.rgbSV_entry.grid(column=2, row=CUR_ROW, sticky=(tkinter.W, tkinter.E))
726 ttk.Label(mainframe, text='RGB Color').grid(column=1, row=CUR_ROW, sticky=tkinter.W)
727
728 # Set up the button to copy the RGB color to the clipboard:
729 self.rgbCopyButtonSV = tkinter.StringVar()
730 self.rgbCopyButtonSV.set('Copy RGB (F3)')
731 self.rgbCopyButton = ttk.Button(mainframe, textvariable=self.rgbCopyButtonSV, width=MOUSE_INFO_BUTTON_WIDTH, command=self._copyRgbMouseInfo)
732 self.rgbCopyButton.grid(column=3, row=CUR_ROW, sticky=tkinter.W)
733 self.rgbCopyButton.bind('<Return>', self._copyRgbMouseInfo)
734
735 # Set up the button to log the XY coordinates:
736 self.rgbLogButtonSV = tkinter.StringVar()
737 self.rgbLogButtonSV.set('Log RGB (F7)')
738 self.rgbLogButton = ttk.Button(mainframe, textvariable=self.rgbLogButtonSV, width=MOUSE_INFO_BUTTON_WIDTH, command=self._logRgbMouseInfo)
739 self.rgbLogButton.grid(column=4, row=CUR_ROW, sticky=tkinter.W)
740 self.rgbLogButton.bind('<Return>', self._logRgbMouseInfo)
741
742 # WIDGETS ON ROW 5:
743 CUR_ROW += 1
744
745 # Set up the RGB hex color text field and label:
746 self.rgbHexSV_entry = ttk.Entry(mainframe, width=16, textvariable=self.rgbHexSV)
747 self.rgbHexSV_entry.grid(column=2, row=CUR_ROW, sticky=(tkinter.W, tkinter.E))
748 ttk.Label(mainframe, text='RGB as Hex').grid(column=1, row=CUR_ROW, sticky=tkinter.W)
749
750 # Set up the button to copy the RGB hex color to the clipboard:
751 self.rgbHexCopyButtonSV = tkinter.StringVar()
752 self.rgbHexCopyButtonSV.set('Copy RGB Hex (F4)')
753 self.rgbHexCopyButton = ttk.Button(mainframe, textvariable=self.rgbHexCopyButtonSV, width=MOUSE_INFO_BUTTON_WIDTH, command=self._copyRgbHexMouseInfo)
754 self.rgbHexCopyButton.grid(column=3, row=CUR_ROW, sticky=tkinter.W)
755 self.rgbHexCopyButton.bind('<Return>', self._copyRgbHexMouseInfo)
756
757 # Set up the button to log the XY coordinates:
758 self.rgbHexLogButtonSV = tkinter.StringVar()
759 self.rgbHexLogButtonSV.set('Log RGB Hex (F8)')
760 self.rgbHexLogButton = ttk.Button(mainframe, textvariable=self.rgbHexLogButtonSV, width=MOUSE_INFO_BUTTON_WIDTH, command=self._logRgbHexMouseInfo)
761 self.rgbHexLogButton.grid(column=4, row=CUR_ROW, sticky=tkinter.W)
762 self.rgbHexLogButton.bind('<Return>', self._logRgbHexMouseInfo)
763
764 # WIDGETS ON ROW 6:
765 CUR_ROW += 1
766
767 # Set up the frame that displays the color of the pixel currently under the mouse cursor:
768 self.colorFrame = tkinter.Frame(mainframe, width=50, height=50)
769 self.colorFrame.grid(column=2, row=CUR_ROW, sticky=(tkinter.W, tkinter.E))
770 ttk.Label(mainframe, text='Color').grid(column=1, row=CUR_ROW, sticky=tkinter.W)
771
772 # WIDGETS ON ROW 7:
773 CUR_ROW += 1
774
775 # Set up the XY origin text field and label:
776 self.xOrigin = 0
777 self.yOrigin = 0
778 self.xyOriginSV.set('0, 0')
779 ttk.Label(mainframe, text='XY Origin').grid(column=1, row=CUR_ROW, sticky=tkinter.W)
780 self.xyOriginSV.trace("w", lambda name, index, mode, sv=self.xyOriginSV: self._xyOriginChanged(sv))
781 self.xyOriginSV_entry = ttk.Entry(mainframe, width=16, textvariable=self.xyOriginSV)
782 self.xyOriginSV_entry.grid(column=2, row=CUR_ROW, sticky=(tkinter.W, tkinter.E))
783
784 # WIDGETS ON ROW 8:
785 CUR_ROW += 1
786
787 # Set up the multiline text widget where the log info appears:
788 self.logTextarea = tkinter.Text(mainframe, width=20, height=6)
789 self.logTextarea.grid(column=1, row=CUR_ROW, columnspan=4, sticky=(tkinter.W, tkinter.E, tkinter.N, tkinter.S))
790 self.logTextareaScrollbar = ttk.Scrollbar(mainframe, orient=tkinter.VERTICAL, command=self.logTextarea.yview)
791 self.logTextareaScrollbar.grid(column=5, row=CUR_ROW, sticky=(tkinter.N, tkinter.S))
792 self.logTextarea['yscrollcommand'] = self.logTextareaScrollbar.set
793
794 # WIDGETS ON ROW 9:
795 CUR_ROW += 1
796
797 self.logFilenameTextbox = ttk.Entry(mainframe, width=16, textvariable=self.logFilenameSV)
798 self.logFilenameTextbox.grid(column=1, row=CUR_ROW, columnspan=3, sticky=(tkinter.W, tkinter.E))
799 self.saveLogButton = ttk.Button(mainframe, text='Save Log', width=MOUSE_INFO_BUTTON_WIDTH, command=self._saveLogFile)
800 self.saveLogButton.grid(column=4, row=CUR_ROW, sticky=tkinter.W)
801 self.saveLogButton.bind('<Return>', self._saveLogFile)
802 self.logFilenameSV.set(os.path.join(os.getcwd(), 'mouseInfoLog.txt'))
803
804 # WIDGETS ON ROW 10:
805 CUR_ROW += 1
806
807 G_MOUSE_INFO_SCREENSHOT_FILENAME_entry = ttk.Entry(mainframe, width=16, textvariable=self.screenshotFilenameSV)
808 G_MOUSE_INFO_SCREENSHOT_FILENAME_entry.grid(column=1, row=CUR_ROW, columnspan=3, sticky=(tkinter.W, tkinter.E))
809 self.saveScreenshotButton = ttk.Button(mainframe, text='Save Screenshot', width=MOUSE_INFO_BUTTON_WIDTH, command=self._saveScreenshotFile)
810 self.saveScreenshotButton.grid(column=4, row=CUR_ROW, sticky=tkinter.W)
811 self.saveScreenshotButton.bind('<Return>', self._saveScreenshotFile)
812 self.screenshotFilenameSV.set(os.path.join(os.getcwd(), 'mouseInfoScreenshot.png'))
813
814 # WIDGETS ON ROW 11:
815 CUR_ROW += 1
816
817 statusbar = ttk.Label(mainframe, relief=tkinter.SUNKEN, textvariable=self.statusbarSV)
818 statusbar.grid(column=1, row=CUR_ROW, columnspan=5, sticky=(tkinter.W, tkinter.E))
819
820 # Add padding to all of the widgets:
821 for child in mainframe.winfo_children():
822 # Ensure the scrollbar and text area don't have padding in between them:
823 if child == self.logTextareaScrollbar:
824 child.grid_configure(padx=0, pady=3)
825 elif child == self.logTextarea:
826 child.grid_configure(padx=(3, 0), pady=3)
827 elif child == statusbar:
828 child.grid_configure(padx=0, pady=(3, 0))
829 else:
830 # All other widgets have a standard padding of 3:
831 child.grid_configure(padx=3, pady=3)
832
833 # Add keyboard hotkeys for the Copy/Log buttons:
834 self.root.option_add('*tearOff', tkinter.FALSE) # Disable tkinter's ugly tear-off menus which are enabled by default.
835
836 menu = tkinter.Menu(self.root)
837 self.root.config(menu=menu)
838
839 copyMenu = tkinter.Menu(menu)
840 copyMenu.add_command(label='Copy All', command=self._copyAllMouseInfo, accelerator='F1', underline=5)
841 copyMenu.add_command(label='Copy XY', command=self._copyXyMouseInfo, accelerator='F2', underline=5)
842 copyMenu.add_command(label='Copy RGB', command=self._copyRgbMouseInfo, accelerator='F3', underline=5)
843 copyMenu.add_command(label='Copy RGB as Hex', command=self._copyRgbHexMouseInfo, accelerator='F4', underline=12)
844 menu.add_cascade(label='Copy', menu=copyMenu, underline=0)
845
846 logMenu = tkinter.Menu(menu)
847 logMenu.add_command(label='Log All', command=self._logAllMouseInfo, accelerator='F5', underline=4)
848 logMenu.add_command(label='Log XY', command=self._logXyMouseInfo, accelerator='F6', underline=4)
849 logMenu.add_command(label='Log RGB', command=self._logRgbMouseInfo, accelerator='F7', underline=4)
850 logMenu.add_command(label='Log RGB as Hex', command=self._logRgbHexMouseInfo, accelerator='F8', underline=11)
851 menu.add_cascade(label='Log', menu=logMenu, underline=0)
852
853 helpMenu = tkinter.Menu(menu)
854 helpMenu.add_command(label='Online Documentation', command=lambda: webbrowser.open('https://mouseinfo.readthedocs.io'), underline=6)
855 menu.add_cascade(label='Help', menu=helpMenu, underline=0)
856
857 self.root.bind_all('<F1>', self._copyAllMouseInfo)
858 self.root.bind_all('<F2>', self._copyXyMouseInfo)
859 self.root.bind_all('<F3>', self._copyRgbMouseInfo)
860 self.root.bind_all('<F4>', self._copyRgbHexMouseInfo)
861 self.root.bind_all('<F5>', self._logAllMouseInfo)
862 self.root.bind_all('<F6>', self._logXyMouseInfo)
863 self.root.bind_all('<F7>', self._logRgbMouseInfo)
864 self.root.bind_all('<F8>', self._logRgbHexMouseInfo)
865
866
867 self.root.resizable(False, False) # Prevent the window from being resized.
868
869 self.xyInfoTextbox.focus() # Put the focus on the XY coordinate text field to start.
870
871 self._updateMouseInfoJob = self.root.after(100, self._updateMouseInfoTextFields) # Begin updating the text fields.
872
873 # Make the mouse info window "always on top".
874 self.root.attributes('-topmost', True)
875 self.root.update()
876
877 # Start the application:
878 self.root.mainloop()
879
880 # Application has closed, set isRunning to False and cancel any "after" commands already queued:
881 self.root.after_cancel(self._updateMouseInfoJob)
882 self.isRunning = False
883
884 # Destroy the tkinter root widget:
885 try:
886 self.root.destroy()
887 except tkinter.TclError:
888 pass
889
890 def mouseInfo():
891 """
892 Launch the MouseInfo application in a new window.
893
894 This exists as a shortcut instead of running MouseInfoWindow() because
895 PyAutoGUI (which imports mouseinfo) is set up with a simple mouseInfo()
896 function and I'd like to keep this consistent with that.
897 """
898 MouseInfoWindow()
899
900 if __name__ == '__main__':
901 MouseInfoWindow()