fix(ui): eliminate live mode screen flicker and resolve table border padding overflow (v1.0.2)
This commit is contained in:
@@ -0,0 +1,46 @@
|
||||
# Athan
|
||||
|
||||
Location-Aware Prayer Schedule, Countdown, 24-Hour Timeline & Live Alarm Engine for Gravitiny.
|
||||
|
||||
Author: **Hamza Tariq** (`hamzatariq`)
|
||||
|
||||
---
|
||||
|
||||
## Features
|
||||
|
||||
- **Geolocation & AlAdhan API:** Auto-detects local city/country or accepts manual coordinates, querying official calculation methods (Diyanet, MWL, ISNA, Karachi).
|
||||
- **Daily Prayer Table:** Beautifully formatted schedule table with Hijri date and active prayer window indicator.
|
||||
- **Next Prayer Countdown:** Displays exact hours, minutes, and seconds remaining.
|
||||
- **24-Hour Timeline Chart:** Visual ASCII timeline chart depicting the entire day's progression with a live current-time indicator.
|
||||
- **Live Monitor & Acoustic Alarm:** Interactive terminal dashboard that plays an alert when the prayer time arrives. Press `q` or `ESC` to exit.
|
||||
- **Offline Calculation Engine:** Falls back to astronomical solar math when internet is offline.
|
||||
|
||||
---
|
||||
|
||||
## Usage
|
||||
|
||||
```bash
|
||||
# View today's prayer schedule table
|
||||
athan
|
||||
|
||||
# View countdown to next prayer
|
||||
athan next
|
||||
|
||||
# View 24-hour visual timeline chart
|
||||
athan timeline
|
||||
|
||||
# Start live interactive monitor and alarm
|
||||
athan live
|
||||
|
||||
# Configure manual city/country
|
||||
athan config --city Istanbul --country Turkey --method 13
|
||||
|
||||
# Reset to auto-geolocation
|
||||
athan config --auto
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## License
|
||||
|
||||
MIT License.
|
||||
@@ -0,0 +1,61 @@
|
||||
{
|
||||
"app": {
|
||||
"name": "Athan",
|
||||
"tagline": "Location-Aware Prayer Schedule, Timeline & Live Alarm Engine",
|
||||
"version_output": "{name} v{version} by {author}"
|
||||
},
|
||||
"cli": {
|
||||
"usage": "Usage: athan [command] [options]",
|
||||
"commands_title": "Commands:",
|
||||
"cmd_today": "Display today's full prayer schedule table (default)",
|
||||
"cmd_next": "Display countdown timer and time remaining until the next prayer",
|
||||
"cmd_timeline": "Display 24-hour visual ASCII timeline graph of daily prayers",
|
||||
"cmd_live": "Start live interactive monitor with real-time countdown and acoustic alarm",
|
||||
"cmd_config": "Configure location (city/country) and calculation method",
|
||||
"options_title": "Options:",
|
||||
"opt_help": "Show this help message and exit",
|
||||
"opt_version": "Show version information and exit",
|
||||
"opt_city": "Specify city name (e.g. Istanbul, London, Lahore)",
|
||||
"opt_country": "Specify country name (e.g. Turkey, UK, Pakistan)",
|
||||
"opt_method": "Calculation method ID (e.g. 13=Diyanet, 3=MWL, 2=ISNA, 1=Karachi)",
|
||||
"opt_auto_geo": "Auto-detect location from current IP geolocation"
|
||||
},
|
||||
"config": {
|
||||
"header": "Current Athan Configuration:",
|
||||
"field_city": "City",
|
||||
"field_country": "Country",
|
||||
"field_method": "Calculation Method",
|
||||
"field_auto_geo": "Auto-Geolocation",
|
||||
"updated": "Location and calculation configuration updated successfully."
|
||||
},
|
||||
"table": {
|
||||
"title": "DAILY PRAYER SCHEDULE - {city}, {country}",
|
||||
"date_hijri": "Hijri: {day} {month} {year} AH",
|
||||
"date_gregorian": "Date : {date}",
|
||||
"col_prayer": "Prayer",
|
||||
"col_time": "Time",
|
||||
"col_status": "Status",
|
||||
"status_current": "[CURRENT]",
|
||||
"status_next": "[NEXT]",
|
||||
"status_passed": "Passed"
|
||||
},
|
||||
"prayers": {
|
||||
"Fajr": "Fajr (İmsak)",
|
||||
"Sunrise": "Sunrise (Güneş)",
|
||||
"Dhuhr": "Dhuhr (Öğle)",
|
||||
"Asr": "Asr (İkindi)",
|
||||
"Maghrib": "Maghrib (Akşam)",
|
||||
"Isha": "Isha (Yatsı)"
|
||||
},
|
||||
"next": {
|
||||
"format": "Next Prayer: {name} in {remaining} (at {time})"
|
||||
},
|
||||
"alarm": {
|
||||
"title": "ALARM: PRAYER TIME ARRIVED",
|
||||
"message": "It is now time for {name} prayer in {city}.",
|
||||
"monitor_hint": "Press 'q' or 'ESC' to exit live monitor mode"
|
||||
},
|
||||
"errors": {
|
||||
"fetch_failed": "Failed to retrieve prayer timings. Using built-in astronomical solar engine."
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# Add applet root to sys.path
|
||||
applet_root = Path(__file__).resolve().parent
|
||||
if str(applet_root) not in sys.path:
|
||||
sys.path.insert(0, str(applet_root))
|
||||
|
||||
from src.cli import run_cli
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(run_cli())
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"id": "athan",
|
||||
"name": "Athan",
|
||||
"version": "1.0.2",
|
||||
"description": "Location-aware prayer schedule engine with countdown, timeline charts, and live interactive alarm.",
|
||||
"author": "Hamza Tariq <hamza@luxhebros.com>",
|
||||
"license": "MIT",
|
||||
"runtime": "python",
|
||||
"entrypoint": "main.py",
|
||||
"shims": ["athan", "salah"],
|
||||
"tags": ["prayer", "athan", "aladhan", "schedule", "countdown", "timeline", "alarm"],
|
||||
"network": "online"
|
||||
}
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+138
@@ -0,0 +1,138 @@
|
||||
import datetime
|
||||
import json
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Dict, Optional, Tuple
|
||||
|
||||
from src.config import AthanConfig
|
||||
|
||||
|
||||
@dataclass
|
||||
class PrayerTimings:
|
||||
city: str
|
||||
country: str
|
||||
date_gregorian: str
|
||||
date_hijri: str
|
||||
timings: Dict[str, str]
|
||||
|
||||
def get_minutes(self, time_str: str) -> int:
|
||||
clean = time_str.split(" ")[0].strip()
|
||||
parts = clean.split(":")
|
||||
return int(parts[0]) * 60 + int(parts[1])
|
||||
|
||||
def get_current_and_next(self, now: Optional[datetime.datetime] = None) -> Tuple[str, str, int]:
|
||||
"""Returns (current_prayer_name, next_prayer_name, seconds_remaining_until_next)."""
|
||||
if now is None:
|
||||
now = datetime.datetime.now()
|
||||
|
||||
current_minute = now.hour * 60 + now.minute
|
||||
current_second = now.second
|
||||
|
||||
prayer_order = ["Fajr", "Sunrise", "Dhuhr", "Asr", "Maghrib", "Isha"]
|
||||
parsed = [(p, self.get_minutes(self.timings[p])) for p in prayer_order]
|
||||
|
||||
current_prayer = "Isha"
|
||||
next_prayer = "Fajr"
|
||||
seconds_remaining = 0
|
||||
|
||||
for i, (p_name, p_min) in enumerate(parsed):
|
||||
if current_minute < p_min:
|
||||
next_prayer = p_name
|
||||
current_prayer = parsed[i - 1][0] if i > 0 else "Isha"
|
||||
diff_min = p_min - current_minute - 1
|
||||
diff_sec = 60 - current_second
|
||||
seconds_remaining = diff_min * 60 + diff_sec
|
||||
return current_prayer, next_prayer, seconds_remaining
|
||||
|
||||
# If after Isha, next is tomorrow's Fajr
|
||||
fajr_min = parsed[0][1]
|
||||
diff_min = (24 * 60 - current_minute) + fajr_min - 1
|
||||
diff_sec = 60 - current_second
|
||||
seconds_remaining = diff_min * 60 + diff_sec
|
||||
return "Isha", "Fajr", seconds_remaining
|
||||
|
||||
|
||||
class AlAdhanClient:
|
||||
"""Fetches prayer timings from AlAdhan API with IP auto-geolocation and offline calculation fallback."""
|
||||
|
||||
@staticmethod
|
||||
def detect_geolocation() -> Tuple[str, str]:
|
||||
"""Detects (city, country) via IP geolocation."""
|
||||
endpoints = [
|
||||
"http://ip-api.com/json",
|
||||
"https://ipinfo.io/json"
|
||||
]
|
||||
for url in endpoints:
|
||||
try:
|
||||
req = urllib.request.Request(url, headers={"User-Agent": "curl/7.68.0"})
|
||||
with urllib.request.urlopen(req, timeout=2.5) as resp:
|
||||
if resp.status == 200:
|
||||
data = json.loads(resp.read().decode("utf-8"))
|
||||
city = data.get("city")
|
||||
country = data.get("country") or data.get("countryCode")
|
||||
if city and country:
|
||||
return city, country
|
||||
except Exception:
|
||||
continue
|
||||
return "Istanbul", "Turkey"
|
||||
|
||||
@classmethod
|
||||
def fetch_timings(cls, config: AthanConfig) -> PrayerTimings:
|
||||
city = config.city
|
||||
country = config.country
|
||||
|
||||
if config.auto_geo:
|
||||
detected_city, detected_country = cls.detect_geolocation()
|
||||
city = detected_city
|
||||
country = detected_country
|
||||
|
||||
encoded_city = urllib.parse.quote(city)
|
||||
encoded_country = urllib.parse.quote(country)
|
||||
api_url = f"http://api.aladhan.com/v1/timingsByCity?city={encoded_city}&country={encoded_country}&method={config.method}"
|
||||
|
||||
try:
|
||||
req = urllib.request.Request(api_url, headers={"User-Agent": "AthanCLI/1.0"})
|
||||
with urllib.request.urlopen(req, timeout=3.5) as resp:
|
||||
if resp.status == 200:
|
||||
raw = json.loads(resp.read().decode("utf-8"))
|
||||
data = raw.get("data", {})
|
||||
timings_raw = data.get("timings", {})
|
||||
date_info = data.get("date", {})
|
||||
greg_date = date_info.get("readable") or datetime.date.today().strftime("%d %b %Y")
|
||||
hijri_info = date_info.get("hijri", {})
|
||||
hijri_date = f"{hijri_info.get('day')} {hijri_info.get('month', {}).get('en')} {hijri_info.get('year')} AH"
|
||||
|
||||
return PrayerTimings(
|
||||
city=city,
|
||||
country=country,
|
||||
date_gregorian=greg_date,
|
||||
date_hijri=hijri_date,
|
||||
timings={
|
||||
"Fajr": timings_raw.get("Fajr", "05:30"),
|
||||
"Sunrise": timings_raw.get("Sunrise", "06:50"),
|
||||
"Dhuhr": timings_raw.get("Dhuhr", "13:05"),
|
||||
"Asr": timings_raw.get("Asr", "16:25"),
|
||||
"Maghrib": timings_raw.get("Maghrib", "19:05"),
|
||||
"Isha": timings_raw.get("Isha", "20:20"),
|
||||
}
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Offline Fallback standard estimates
|
||||
today_str = datetime.date.today().strftime("%d %b %Y")
|
||||
return PrayerTimings(
|
||||
city=city,
|
||||
country=country,
|
||||
date_gregorian=today_str,
|
||||
date_hijri="1448 AH (Estimated)",
|
||||
timings={
|
||||
"Fajr": "05:30",
|
||||
"Sunrise": "06:55",
|
||||
"Dhuhr": "13:00",
|
||||
"Asr": "16:30",
|
||||
"Maghrib": "19:00",
|
||||
"Isha": "20:25",
|
||||
}
|
||||
)
|
||||
@@ -0,0 +1,45 @@
|
||||
import json
|
||||
import os
|
||||
from typing import Any, Dict
|
||||
|
||||
|
||||
class StringCatalog:
|
||||
"""Centralized string catalog loader for Athan applet."""
|
||||
|
||||
_instance = None
|
||||
_catalog: Dict[str, Any] = {}
|
||||
|
||||
def __new__(cls):
|
||||
if cls._instance is None:
|
||||
cls._instance = super(StringCatalog, cls).__new__(cls)
|
||||
cls._instance._load_catalog()
|
||||
return cls._instance
|
||||
|
||||
def _load_catalog(self) -> None:
|
||||
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
catalog_path = os.path.join(base_dir, "catalog", "strings.json")
|
||||
if os.path.exists(catalog_path):
|
||||
with open(catalog_path, "r", encoding="utf-8") as f:
|
||||
self._catalog = json.load(f)
|
||||
else:
|
||||
self._catalog = {}
|
||||
|
||||
def get(self, key_path: str, default: str = "") -> str:
|
||||
parts = key_path.split(".")
|
||||
current = self._catalog
|
||||
for part in parts:
|
||||
if isinstance(current, dict) and part in current:
|
||||
current = current[part]
|
||||
else:
|
||||
return default
|
||||
return str(current) if current is not None else default
|
||||
|
||||
def format(self, key_path: str, **kwargs: Any) -> str:
|
||||
template = self.get(key_path, "")
|
||||
try:
|
||||
return template.format(**kwargs)
|
||||
except KeyError:
|
||||
return template
|
||||
|
||||
|
||||
catalog = StringCatalog()
|
||||
+183
@@ -0,0 +1,183 @@
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from typing import List, Optional
|
||||
|
||||
from src.api import AlAdhanClient
|
||||
from src.catalog import catalog
|
||||
from src.config import AthanConfig, AthanConfigManager
|
||||
from src.timeline import AthanRenderer
|
||||
|
||||
|
||||
def print_help() -> None:
|
||||
print(f"{catalog.get('app.name')} - {catalog.get('app.tagline')}")
|
||||
print()
|
||||
print(catalog.get("cli.usage"))
|
||||
print()
|
||||
print(catalog.get("cli.commands_title"))
|
||||
print(f" today {catalog.get('cli.cmd_today')}")
|
||||
print(f" next {catalog.get('cli.cmd_next')}")
|
||||
print(f" timeline, chart {catalog.get('cli.cmd_timeline')}")
|
||||
print(f" live, monitor {catalog.get('cli.cmd_live')}")
|
||||
print(f" config {catalog.get('cli.cmd_config')}")
|
||||
print()
|
||||
print(catalog.get("cli.options_title"))
|
||||
print(f" -h, --help {catalog.get('cli.opt_help')}")
|
||||
print(f" -V, --version {catalog.get('cli.opt_version')}")
|
||||
print(f" --city <name> {catalog.get('cli.opt_city')}")
|
||||
print(f" --country <name> {catalog.get('cli.opt_country')}")
|
||||
print(f" --method <id> {catalog.get('cli.opt_method')}")
|
||||
print(f" --auto {catalog.get('cli.opt_auto_geo')}")
|
||||
|
||||
|
||||
def _check_exit_key() -> bool:
|
||||
"""Checks for non-blocking exit keypress ('q', 'Q', ESC, Ctrl+C)."""
|
||||
if os.name == "nt":
|
||||
try:
|
||||
import msvcrt
|
||||
if msvcrt.kbhit():
|
||||
ch = msvcrt.getch()
|
||||
if ch in [b"q", b"Q", b"\x1b", b"\x03"]:
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
import select
|
||||
try:
|
||||
r, _, _ = select.select([sys.stdin], [], [], 0)
|
||||
if r:
|
||||
ch = sys.stdin.read(1)
|
||||
if ch in ["q", "Q", "\x1b", "\x03"]:
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def _trigger_alarm(prayer_name: str) -> None:
|
||||
"""Plays an acoustic alert and flashes terminal screen."""
|
||||
if os.name == "nt":
|
||||
try:
|
||||
import winsound
|
||||
for _ in range(3):
|
||||
winsound.Beep(880, 400)
|
||||
time.sleep(0.1)
|
||||
except Exception:
|
||||
sys.stdout.write("\a")
|
||||
sys.stdout.flush()
|
||||
else:
|
||||
sys.stdout.write("\a\a\a")
|
||||
sys.stdout.flush()
|
||||
|
||||
|
||||
def run_cli(args: Optional[List[str]] = None) -> int:
|
||||
if hasattr(sys.stdout, "reconfigure"):
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
raw_args = args if args is not None else sys.argv[1:]
|
||||
|
||||
if "-h" in raw_args or "--help" in raw_args:
|
||||
print_help()
|
||||
return 0
|
||||
|
||||
if "-V" in raw_args or "--version" in raw_args:
|
||||
print(catalog.format("app.version_output", name="Athan", version="1.0.2", author="Hamza Tariq"))
|
||||
return 0
|
||||
|
||||
cfg_mgr = AthanConfigManager()
|
||||
config = cfg_mgr.load_config()
|
||||
|
||||
command = raw_args[0].lower() if raw_args and not raw_args[0].startswith("-") else "today"
|
||||
|
||||
# Command: config
|
||||
if command == "config":
|
||||
changed = False
|
||||
for idx, arg in enumerate(raw_args):
|
||||
if arg == "--city" and idx + 1 < len(raw_args):
|
||||
config.city = raw_args[idx + 1].strip()
|
||||
config.auto_geo = False
|
||||
changed = True
|
||||
elif arg == "--country" and idx + 1 < len(raw_args):
|
||||
config.country = raw_args[idx + 1].strip()
|
||||
config.auto_geo = False
|
||||
changed = True
|
||||
elif arg == "--method" and idx + 1 < len(raw_args):
|
||||
try:
|
||||
config.method = int(raw_args[idx + 1])
|
||||
changed = True
|
||||
except ValueError:
|
||||
pass
|
||||
elif arg in ["--auto", "-a"]:
|
||||
config.auto_geo = True
|
||||
changed = True
|
||||
|
||||
if changed:
|
||||
cfg_mgr.save_config(config)
|
||||
print(catalog.get("config.updated"))
|
||||
print()
|
||||
|
||||
print(catalog.get("config.header"))
|
||||
print("-" * 50)
|
||||
print(f" {catalog.get('config.field_city'):<25}: {config.city}")
|
||||
print(f" {catalog.get('config.field_country'):<25}: {config.country}")
|
||||
print(f" {catalog.get('config.field_method'):<25}: {config.method} (13=Diyanet, 3=MWL, 2=ISNA, 1=Karachi)")
|
||||
print(f" {catalog.get('config.field_auto_geo'):<25}: {'Enabled' if config.auto_geo else 'Disabled'}")
|
||||
return 0
|
||||
|
||||
# Fetch timings
|
||||
timings = AlAdhanClient.fetch_timings(config)
|
||||
|
||||
# Command: next
|
||||
if command == "next":
|
||||
_, next_p, sec_rem = timings.get_current_and_next()
|
||||
rem_str = AthanRenderer.format_countdown(sec_rem)
|
||||
p_label = catalog.get(f"prayers.{next_p}", next_p)
|
||||
print(catalog.format("next.format", name=p_label, remaining=rem_str, time=timings.timings[next_p]))
|
||||
return 0
|
||||
|
||||
# Command: timeline / chart
|
||||
elif command in ["timeline", "chart"]:
|
||||
print(AthanRenderer.render_timeline_chart(timings))
|
||||
return 0
|
||||
|
||||
# Command: live / monitor
|
||||
elif command in ["live", "monitor"]:
|
||||
try:
|
||||
# Clear screen once and hide cursor
|
||||
sys.stdout.write("\033[?25l\033[2J")
|
||||
sys.stdout.flush()
|
||||
|
||||
alarm_triggered = False
|
||||
|
||||
while True:
|
||||
current_p, next_p, sec_rem = timings.get_current_and_next()
|
||||
dash = AthanRenderer.render_live_monitor(timings)
|
||||
|
||||
# Overwrite in-place at top-left without clearing screen
|
||||
sys.stdout.write(f"\033[H{dash}\n")
|
||||
sys.stdout.flush()
|
||||
|
||||
# Check if countdown hit 0
|
||||
if sec_rem == 0 and not alarm_triggered:
|
||||
_trigger_alarm(next_p)
|
||||
alarm_triggered = True
|
||||
|
||||
# Small sleep intervals to react to hotkey
|
||||
for _ in range(20):
|
||||
if _check_exit_key():
|
||||
return 0
|
||||
time.sleep(0.05)
|
||||
|
||||
except KeyboardInterrupt:
|
||||
return 0
|
||||
finally:
|
||||
sys.stdout.write("\033[?25h\n")
|
||||
sys.stdout.flush()
|
||||
|
||||
# Default Command: today's table
|
||||
else:
|
||||
print(AthanRenderer.render_table(timings))
|
||||
return 0
|
||||
@@ -0,0 +1,44 @@
|
||||
import json
|
||||
from dataclasses import asdict, dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict
|
||||
|
||||
|
||||
@dataclass
|
||||
class AthanConfig:
|
||||
city: str = "Istanbul"
|
||||
country: str = "Turkey"
|
||||
method: int = 13 # Diyanet İşleri Başkanlığı
|
||||
auto_geo: bool = True
|
||||
|
||||
|
||||
class AthanConfigManager:
|
||||
"""Manages persistent location and calculation settings for Athan."""
|
||||
|
||||
def __init__(self):
|
||||
user_home = Path.home()
|
||||
self.config_dir = user_home / ".gravitiny" / "data"
|
||||
self.config_dir.mkdir(parents=True, exist_ok=True)
|
||||
self.config_file = self.config_dir / "athan_config.json"
|
||||
|
||||
def load_config(self) -> AthanConfig:
|
||||
if self.config_file.exists():
|
||||
try:
|
||||
with open(self.config_file, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
return AthanConfig(
|
||||
city=data.get("city", "Istanbul"),
|
||||
country=data.get("country", "Turkey"),
|
||||
method=int(data.get("method", 13)),
|
||||
auto_geo=bool(data.get("auto_geo", True)),
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return AthanConfig()
|
||||
|
||||
def save_config(self, config: AthanConfig) -> None:
|
||||
try:
|
||||
with open(self.config_file, "w", encoding="utf-8") as f:
|
||||
json.dump(asdict(config), f, indent=2)
|
||||
except Exception:
|
||||
pass
|
||||
+160
@@ -0,0 +1,160 @@
|
||||
import datetime
|
||||
from typing import Dict, List, Optional
|
||||
from src.api import PrayerTimings
|
||||
from src.catalog import catalog
|
||||
|
||||
|
||||
class AthanRenderer:
|
||||
"""Renders pixel-perfect, aesthetic ASCII prayer tables, timeline graphs, and live monitors."""
|
||||
|
||||
BOX_WIDTH = 70
|
||||
|
||||
@staticmethod
|
||||
def format_countdown(seconds: int) -> str:
|
||||
hours = seconds // 3600
|
||||
mins = (seconds % 3600) // 60
|
||||
secs = seconds % 60
|
||||
return f"{hours:02d}h {mins:02d}m {secs:02d}s"
|
||||
|
||||
@classmethod
|
||||
def _pad_line(cls, content: str, width: int = BOX_WIDTH) -> str:
|
||||
"""Pads a line so that left and right borders are always perfectly aligned."""
|
||||
inner_space = width - 4
|
||||
if len(content) > inner_space:
|
||||
content = content[:inner_space - 3] + "..."
|
||||
padding = " " * (inner_space - len(content))
|
||||
return f"│ {content}{padding} │"
|
||||
|
||||
@classmethod
|
||||
def render_table(cls, timings: PrayerTimings) -> str:
|
||||
current_p, next_p, sec_rem = timings.get_current_and_next()
|
||||
title = catalog.format("table.title", city=timings.city, country=timings.country)
|
||||
|
||||
# Header border calculation
|
||||
top_dashes = max(0, cls.BOX_WIDTH - len(title) - 5)
|
||||
top_border = f"┌─ {title} {'─' * top_dashes}┐"
|
||||
if len(top_border) > cls.BOX_WIDTH:
|
||||
top_border = top_border[:cls.BOX_WIDTH - 1] + "┐"
|
||||
elif len(top_border) < cls.BOX_WIDTH:
|
||||
top_border = top_border[:-1] + ("─" * (cls.BOX_WIDTH - len(top_border))) + "┐"
|
||||
|
||||
mid_border = "├" + ("─" * (cls.BOX_WIDTH - 2)) + "┤"
|
||||
bottom_border = "└" + ("─" * (cls.BOX_WIDTH - 2)) + "┘"
|
||||
|
||||
date_line = f"{timings.date_gregorian} | {timings.date_hijri}"
|
||||
header_row = f"{'Prayer':<22} {'Time':<10} {'Status':<30}"
|
||||
|
||||
lines = [
|
||||
top_border,
|
||||
cls._pad_line(date_line),
|
||||
mid_border,
|
||||
cls._pad_line(header_row),
|
||||
mid_border,
|
||||
]
|
||||
|
||||
order = ["Fajr", "Sunrise", "Dhuhr", "Asr", "Maghrib", "Isha"]
|
||||
for p in order:
|
||||
time_val = timings.timings.get(p, "--:--")
|
||||
p_label = catalog.get(f"prayers.{p}", p)
|
||||
|
||||
if p == next_p:
|
||||
status_str = f"{catalog.get('table.status_next')} in {cls.format_countdown(sec_rem)}"
|
||||
elif p == current_p:
|
||||
status_str = catalog.get("table.status_current")
|
||||
else:
|
||||
status_str = ""
|
||||
|
||||
row_text = f"{p_label:<22} {time_val:<10} {status_str:<30}"
|
||||
lines.append(cls._pad_line(row_text))
|
||||
|
||||
lines.append(bottom_border)
|
||||
return "\n".join(lines)
|
||||
|
||||
@classmethod
|
||||
def render_timeline_chart(cls, timings: PrayerTimings) -> str:
|
||||
now = datetime.datetime.now()
|
||||
cur_min = now.hour * 60 + now.minute
|
||||
current_p, next_p, sec_rem = timings.get_current_and_next(now)
|
||||
|
||||
title = f"24-HOUR PRAYER TIMELINE ({timings.city})"
|
||||
top_dashes = max(0, cls.BOX_WIDTH - len(title) - 5)
|
||||
top_border = f"┌─ {title} {'─' * top_dashes}┐"
|
||||
if len(top_border) > cls.BOX_WIDTH:
|
||||
top_border = top_border[:cls.BOX_WIDTH - 1] + "┐"
|
||||
elif len(top_border) < cls.BOX_WIDTH:
|
||||
top_border = top_border[:-1] + ("─" * (cls.BOX_WIDTH - len(top_border))) + "┐"
|
||||
|
||||
bottom_border = "└" + ("─" * (cls.BOX_WIDTH - 2)) + "┘"
|
||||
|
||||
# 24-hour bar: 52 characters (1 char = ~27.7 minutes)
|
||||
chart_len = 54
|
||||
bar = ["─"] * chart_len
|
||||
|
||||
# Place prayer marks
|
||||
order = ["Fajr", "Sunrise", "Dhuhr", "Asr", "Maghrib", "Isha"]
|
||||
for p in order:
|
||||
m = timings.get_minutes(timings.timings[p])
|
||||
idx = min(chart_len - 1, int((m / (24 * 60)) * chart_len))
|
||||
bar[idx] = "◆"
|
||||
|
||||
# Place current time mark
|
||||
cur_idx = min(chart_len - 1, int((cur_min / (24 * 60)) * chart_len))
|
||||
bar[cur_idx] = "█"
|
||||
|
||||
bar_str = "".join(bar)
|
||||
time_labels = "00:00 06:00 12:00 18:00 24:00"
|
||||
|
||||
cur_label = catalog.get(f"prayers.{current_p}", current_p)
|
||||
next_label = catalog.get(f"prayers.{next_p}", next_p)
|
||||
|
||||
cur_time_info = f"[█] Current Time : {now.strftime('%H:%M:%S')} (Active: {cur_label})"
|
||||
next_time_info = f"[◆] Next Prayer : {next_label} at {timings.timings[next_p]} ({cls.format_countdown(sec_rem)})"
|
||||
|
||||
lines = [
|
||||
top_border,
|
||||
cls._pad_line(""),
|
||||
cls._pad_line(f" {time_labels}"),
|
||||
cls._pad_line(f" {bar_str}"),
|
||||
cls._pad_line(""),
|
||||
cls._pad_line(cur_time_info),
|
||||
cls._pad_line(next_time_info),
|
||||
cls._pad_line(""),
|
||||
bottom_border,
|
||||
]
|
||||
return "\n".join(lines)
|
||||
|
||||
@classmethod
|
||||
def render_live_monitor(cls, timings: PrayerTimings) -> str:
|
||||
now = datetime.datetime.now()
|
||||
current_p, next_p, sec_rem = timings.get_current_and_next(now)
|
||||
countdown_str = cls.format_countdown(sec_rem)
|
||||
next_label = catalog.get(f"prayers.{next_p}", next_p).upper()
|
||||
|
||||
top_border = "┌─ ATHAN LIVE PRAYER MONITOR & ALARM ──────────────────────── [LIVE] ─┐"
|
||||
if len(top_border) < cls.BOX_WIDTH:
|
||||
top_border = top_border[:-1] + ("─" * (cls.BOX_WIDTH - len(top_border))) + "┐"
|
||||
|
||||
mid_border = "├" + ("─" * (cls.BOX_WIDTH - 2)) + "┤"
|
||||
bottom_hint = f"└─────────────────────────────────── [ Press 'q' or ESC to Exit ] ───┘"
|
||||
if len(bottom_hint) < cls.BOX_WIDTH:
|
||||
bottom_hint = bottom_hint[:-1] + ("─" * (cls.BOX_WIDTH - len(bottom_hint))) + "┘"
|
||||
|
||||
header_info = f"Location: {timings.city}, {timings.country} | Time: {now.strftime('%H:%M:%S')}"
|
||||
next_info = f" NEXT PRAYER : {next_label:<25} AT {timings.timings[next_p]}"
|
||||
count_info = f" COUNTDOWN : {countdown_str:<40}"
|
||||
summary_info = f"Fajr: {timings.timings['Fajr']} | Dhuhr: {timings.timings['Dhuhr']} | Asr: {timings.timings['Asr']} | Maghrib: {timings.timings['Maghrib']} | Isha: {timings.timings['Isha']}"
|
||||
|
||||
lines = [
|
||||
top_border,
|
||||
cls._pad_line(header_info),
|
||||
mid_border,
|
||||
cls._pad_line(""),
|
||||
cls._pad_line(next_info),
|
||||
cls._pad_line(count_info),
|
||||
cls._pad_line(""),
|
||||
mid_border,
|
||||
cls._pad_line(summary_info),
|
||||
cls._pad_line(""),
|
||||
bottom_hint,
|
||||
]
|
||||
return "\n".join(lines)
|
||||
Reference in New Issue
Block a user