Skip to content

Commit

Permalink
ruff format . --config "line-length=95"
Browse files Browse the repository at this point in the history
  • Loading branch information
simpleapps-public committed Dec 7, 2024
1 parent 9c0a87f commit e13c8f0
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 37 deletions.
55 changes: 29 additions & 26 deletions ping-menubar.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,34 +22,35 @@
NSTimer,
)
from ServiceManagement import (
SMAppService,
SMAppService,
SMAppServiceStatusEnabled,
)

# Configuration
PING_HOST = "1.1.1.1"
PING_INTERVAL = 2.0 # seconds
PING_SAMPLES = 16 # number of readings to show
PING_WAIT = 1000 # ping -W value in ms
PING_SAMPLES = 16 # number of readings to show
PING_WAIT = 1000 # ping -W value in ms

# Ping time ranges and colors (RGB)
TIERS = [
{"limit": 0, "color": NSColor.colorWithRed_green_blue_alpha_(0, 0, 0, 1.0)},
{"limit": 70, "color": NSColor.colorWithRed_green_blue_alpha_(13/255, 215/255, 33/255, 1.0)},
{"limit": 150, "color": NSColor.colorWithRed_green_blue_alpha_(209/255, 214/255, 39/255, 1.0)},
{"limit": 300, "color": NSColor.colorWithRed_green_blue_alpha_(209/255, 15/255, 29/255, 1.0)},
{"limit": 70, "color": NSColor.colorWithRed_green_blue_alpha_(0.051, 0.843, 0.129, 1.0)},
{"limit": 150, "color": NSColor.colorWithRed_green_blue_alpha_(0.820, 0.839, 0.153, 1.0)},
{"limit": 300, "color": NSColor.colorWithRed_green_blue_alpha_(0.820, 0.059, 0.114, 1.0)},
]

BAR_WIDTH = 3
BAR_HEIGHT = 18


class PingMonitor(NSObject):
def init(self):
self.times = deque([0] * PING_SAMPLES, maxlen=PING_SAMPLES)
self.width = PING_SAMPLES * BAR_WIDTH
self.statusbar = NSStatusBar.systemStatusBar()
self.statusitem = self.statusbar.statusItemWithLength_(self.width)

# Add menu items
self.menu = NSMenu.new()
self.statusitem.setMenu_(self.menu)
Expand All @@ -71,15 +72,15 @@ def init(self):
)
self.menu.addItem_(NSMenuItem.separatorItem())
self.menu.addItem_(self.quit_item)

# Add image
self.image = NSImage.alloc().initWithSize_((self.width, BAR_HEIGHT))
self.statusitem.setImage_(self.image)

# ServiceManagement app instance, for Login Items
self.service = SMAppService.mainAppService()
self.updateStartupItemState()

# Schedule update to run immediately.
self.schedule_next_update(PING_INTERVAL)
return self
Expand All @@ -88,7 +89,7 @@ def schedule_next_update(self, processing_time):
"""Schedule next update cycle"""
interval = max(0.1, PING_INTERVAL - processing_time)
self.timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(
interval, self, 'update:', None, False
interval, self, "update:", None, False
)
runLoop = NSRunLoop.currentRunLoop()
runLoop.addTimer_forMode_(self.timer, "NSEventTrackingRunLoopMode")
Expand All @@ -106,16 +107,16 @@ def run_ping(self) -> Optional[float]:
"""Subprocess call to ping"""
try:
result = subprocess.run(
['ping', '-W', str(PING_WAIT), '-c', '1', PING_HOST],
["ping", "-W", str(PING_WAIT), "-c", "1", PING_HOST],
capture_output=True,
text=True,
timeout=PING_INTERVAL,
)
if result.returncode == 0:
if match := re.search(r'time=(\d+\.?\d*)\s*ms', result.stdout):
if match := re.search(r"time=(\d+\.?\d*)\s*ms", result.stdout):
return float(match.group(1))
except:
pass
pass
return None

def update_last_ping_texts(self):
Expand All @@ -129,20 +130,18 @@ def update_last_ping_texts(self):

def update_graph(self):
self.image.lockFocus()

# Shift image left
source_rect = NSMakeRect(BAR_WIDTH, 0, self.width - BAR_WIDTH, BAR_HEIGHT)
self.image.compositeToPoint_fromRect_operation_(
NSPoint(0, 0),
source_rect,
NSCompositingOperationSourceOver
NSPoint(0, 0), source_rect, NSCompositingOperationSourceOver
)

# Draw new bar at rightmost position
NSColor.clearColor().set()
NSBezierPath.fillRect_(NSMakeRect(self.width - BAR_WIDTH, 0, BAR_WIDTH, BAR_HEIGHT))
self.draw_bar(self.times[-1], self.width - BAR_WIDTH)

self.image.unlockFocus()
self.statusitem.button().setNeedsDisplay_(True)

Expand All @@ -151,7 +150,7 @@ def draw_bar(self, value: float, x: int):
self.draw_time_bar(value, x)
else:
self.draw_error_bar(x)

def draw_time_bar(self, value: float, x: int):
# Select tier and draw
prev_tier = TIERS[0]
Expand All @@ -164,11 +163,11 @@ def draw_time_bar(self, value: float, x: int):

bar_range = curr_tier["limit"] - prev_tier["limit"]
bar_height = int((value - prev_tier["limit"]) / bar_range * BAR_HEIGHT)

# Current tier bar
curr_tier["color"].set()
NSBezierPath.fillRect_(NSMakeRect(x, 0, BAR_WIDTH, bar_height))

# Background tier bar
prev_tier["color"].set()
NSBezierPath.fillRect_(NSMakeRect(x, bar_height, BAR_WIDTH, BAR_HEIGHT - bar_height))
Expand All @@ -177,20 +176,22 @@ def draw_error_bar(self, x: int):
background_color = TIERS[0]["color"]
background_color.set()
NSBezierPath.fillRect_(NSMakeRect(x, 0, BAR_WIDTH, BAR_HEIGHT))

error_color = TIERS[-1]["color"]
error_color.set()
lower_bar_height = int(BAR_HEIGHT * 0.63)
gap_end = int(BAR_HEIGHT * 0.85)
NSBezierPath.fillRect_(NSMakeRect(x + 1, BAR_HEIGHT - lower_bar_height, 1, lower_bar_height))
NSBezierPath.fillRect_(
NSMakeRect(x + 1, BAR_HEIGHT - lower_bar_height, 1, lower_bar_height)
)
NSBezierPath.fillRect_(NSMakeRect(x + 1, 0, 1, BAR_HEIGHT - gap_end))
return

def updateStartupItemState(self):
"""Update the menu item's state based on whether the app is registered as a login item"""
is_registered = self.service.status() == SMAppServiceStatusEnabled
self.startup_item.setState_(1 if is_registered else 0)

def toggleStartup_(self, sender):
"""Toggle login item registration"""
try:
Expand All @@ -202,10 +203,12 @@ def toggleStartup_(self, sender):
except Exception as e:
print(f"Error toggling startup status: {e}")


def main():
app = NSApplication.sharedApplication()
PingMonitor.alloc().init()
app.run()


if __name__ == "__main__":
main()
main()
22 changes: 11 additions & 11 deletions setup.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
from setuptools import setup

APP = ['ping-menubar.py']
APP = ["ping-menubar.py"]
OPTIONS = {
'argv_emulation': False,
'plist': {
'LSUIElement': True,
'LSBackgroundOnly': True,
'CFBundleIdentifier': 'com.example.ping-menubar',
'CFBundleShortVersionString': '1.1.0',
'CFBundleVersion': '1.1.0',
"argv_emulation": False,
"plist": {
"LSUIElement": True,
"LSBackgroundOnly": True,
"CFBundleIdentifier": "com.example.ping-menubar",
"CFBundleShortVersionString": "1.1.0",
"CFBundleVersion": "1.1.0",
},
'packages': ['Foundation', 'AppKit'],
"packages": ["Foundation", "AppKit"],
}

setup(
app=APP,
setup_requires=['py2app'],
options={'py2app': OPTIONS},
setup_requires=["py2app"],
options={"py2app": OPTIONS},
)

0 comments on commit e13c8f0

Please sign in to comment.