import subprocess
import time
import math
import json
import pathlib
import sys
import os
config_file = pathlib.Path(__file__).parent / "mouse.json"
lock_file = pathlib.Path(__file__).parent / "mouse.lock"
def pixels_to_meters(pixels, pixels_per_inch=100):
"""
Convert pixels to meters based on display pixel density.
Args:
pixels (float): Total pixels traveled.
pixels_per_inch (float): Pixels per inch of the display. Default is 100.
Returns:
float: Distance in meters.
"""
inches_per_meter_x270_laptop = 39.37
pixels_per_meter = pixels_per_inch * inches_per_meter_x270_laptop
meters = pixels / pixels_per_meter
return meters
def get_data():
try:
with open(config_file,"r") as f:
return json.load(f)
except:
return {}
def set_data(**kwargs):
with open(config_file,"w") as f:
json.dump(kwargs,f)
def get_mouse_position():
result = subprocess.run(['xdotool', 'getmouselocation', '--shell'], capture_output=True, text=True)
output = result.stdout
x = y = 0
for line in output.splitlines():
if line.startswith('X='):
x = int(line.split('=')[1])
elif line.startswith('Y='):
y = int(line.split('=')[1])
return x, y
positions = []
total_distance = get_data().get("total_distance", 0)
sampling_interval = get_data().get("sampling_interval", 0.1)
import sys
import os
if len(sys.argv) > 1:
print("Total traveled in pixels: " + str(total_distance))
print("Total traveled in meters: " + str(pixels_to_meters(total_distance)))
exit()
if lock_file.exists():
sys.exit(0)
lock_file.touch()
try:
print("Tracking mouse movement. Press Ctrl+C to stop.")
while True:
x, y = get_mouse_position()
positions.append((x, y))
if len(positions) > 1:
x1, y1 = positions[-2]
x2, y2 = positions[-1]
dist = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
total_distance += dist
if len(positions) > 10:
positions.pop(0)
print("\rDistance traveled: {:.2f} pixels".format(total_distance), end="")
time.sleep(sampling_interval)
set_data(total_distance=total_distance,sampling_interval=sampling_interval)
except KeyboardInterrupt:
print(f"\nTotal distance traveled: {total_distance:.2f} pixels")
finally:
if lock_file.exists():
lock_file.unlink()