#!/usr/bin/python3 -I
"""NewWorld's native settings panel for the i386 Xfce desktop."""
import os
import re
import shutil
import subprocess
from pathlib import Path

import gi
gi.require_version("Gtk", "3.0")
gi.require_version("GdkPixbuf", "2.0")
from gi.repository import GdkPixbuf, GLib, Gtk, Pango


# Each route uses a native manager shipped by the edition or a fixed local action.
# Labels are English first and Hebrew second.
PAGES = {
    "system": (("System", "מערכת"), "computer", [
        ("Displays", "תצוגה ומסכים", "xfce4-display-settings"),
        ("Sound and recording", "צליל והקלטה", "pavucontrol"),
        ("Power and battery", "חשמל וסוללה", "xfce4-power-manager-settings"),
        ("Notifications", "התראות", "xfce4-notifyd-config"),
        ("Hardware information", "מידע על החומרה", "@cpu")]),
    "devices": (("Devices", "מכשירים"), "input-mouse", [
        ("Mouse and touchpad", "עכבר ומשטח מגע", "xfce4-mouse-settings"),
        ("Bluetooth devices", "מכשירי Bluetooth", "blueman-manager"),
        ("Printers", "מדפסות", "system-config-printer"),
        ("Webcam preview", "תצוגה מקדימה של מצלמת הרשת", "guvcview"),
        ("Connected USB devices", "מכשירים המחוברים ב־USB", "@usb")]),
    "mobile": (("Mobile devices", "מכשירים ניידים"), "phone", [
        ("Pair a phone with KDE Connect", "צימוד טלפון באמצעות KDE Connect", "kdeconnect-app"),
        ("Browse connected phone files", "עיון בקבצים של טלפון מחובר", "thunar", "computer:///")]),
    "network": (("Network and internet", "רשת ואינטרנט"), "network-workgroup", [
        ("Wi-Fi, Ethernet and VPN profiles", "פרופילי Wi-Fi, רשת קווית ו־VPN", "nm-connection-editor"),
        ("Airplane mode", "מצב טיסה", "@airplane")]),
    "personal": (("Personalization", "התאמה אישית"), "preferences-desktop-wallpaper", [
        ("Wallpapers, rotation and your pictures", "רקעים, החלפה אוטומטית ותמונות אישיות", "/usr/bin/newworld-backgrounds"),
        ("Colors, fonts and icons", "צבעים, גופנים וסמלים", "xfce4-appearance-settings"),
        ("Window themes", "ערכות נושא לחלונות", "xfwm4-settings"),
        ("Taskbar and panels", "שורת משימות ולוחות", "xfce4-panel", "--preferences"),
        ("Display sleep and locking", "השהיית המסך ונעילה", "xfce4-power-manager-settings")]),
    "apps": (("Applications", "יישומים"), "applications-other", [
        ("Open installed applications", "פתיחת היישומים המותקנים", "/usr/bin/newworld-applications"),
        ("Default applications and file types", "יישומי ברירת מחדל וסוגי קבצים", "xfce4-mime-settings"),
        ("Install or remove software", "התקנה והסרה של תוכנות", "synaptic-pkexec"),
        ("Startup applications", "יישומים המופעלים בכניסה", "xfce4-session-settings")]),
    "accounts": (("Accounts", "חשבונות"), "system-users", [
        ("Local users and groups", "משתמשים וקבוצות מקומיים", "users-admin"),
        ("Change my password", "שינוי הסיסמה שלי", "xfce4-terminal", "--execute", "passwd")]),
    "time": (("Time and language", "זמן ושפה"), "preferences-desktop-locale", [
        ("Date, time and time zone", "תאריך, שעה ואזור זמן", "time-admin"),
        ("Desktop language at next sign-in", "שפת שולחן העבודה בכניסה הבאה", "/usr/bin/compact-language"),
        ("Keyboard layouts and shortcuts", "פריסות מקלדת וקיצורי דרך", "xfce4-keyboard-settings")]),
    "gaming": (("Gaming", "משחקים"), "input-gaming", [
        ("Test and calibrate controllers", "בדיקה וכיול של בקרי משחק", "jstest-gtk"),
        ("Window effects and compositor", "אפקטים בחלונות והרכבת התצוגה", "xfwm4-tweaks-settings"),
        ("Record game or desktop video", "הקלטת וידאו של משחק או של שולחן העבודה", "simplescreenrecorder"),
        ("Capture a screenshot", "צילום המסך", "xfce4-screenshooter")]),
    "access": (("Accessibility", "נגישות"), "preferences-desktop-accessibility", [
        ("Keyboard and mouse accessibility", "נגישות המקלדת והעכבר", "xfce4-accessibility-settings"),
        ("On-screen keyboard", "מקלדת על המסך", "onboard"),
        ("Screen reader preferences", "העדפות קורא המסך", "orca", "--setup"),
        ("Fonts, contrast and themes", "גופנים, ניגודיות וערכות נושא", "xfce4-appearance-settings")]),
    "search": (("Search", "חיפוש"), "system-search", [
        ("Search files by name or content", "חיפוש קבצים לפי שם או תוכן", "catfish"),
        ("Search installed applications", "חיפוש ביישומים המותקנים", "xfce4-appfinder")]),
    "privacy": (("Privacy", "פרטיות"), "changes-prevent", [
        ("Default microphone access", "גישה למיקרופון ברירת המחדל", "@microphone"),
        ("Camera, location and site permissions in Firefox", "מצלמה, מיקום והרשאות אתרים ב־Firefox", "firefox-esr", "about:preferences#privacy"),
        ("Recent file history", "היסטוריית קבצים אחרונים", "@recent")]),
    "updates": (("Updates and security", "עדכונים ואבטחה"), "system-software-update", [
        ("Review system updates", "בדיקת עדכוני מערכת", "synaptic-pkexec"),
        ("Back up or restore files", "גיבוי ושחזור קבצים", "deja-dup"),
        ("Lock this session", "נעילת ההפעלה הנוכחית", "xflock4")]),
    "xr": (("Mixed reality", "מציאות משולבת"), "video-display", [
        ("Inspect connected USB hardware", "בדיקת חומרת USB מחוברת", "@usb"),
        ("Configure a headset display", "הגדרת התצוגה של המשקפיים", "xfce4-display-settings"),
        ("Choose headset audio", "בחירת התקן השמע במשקפיים", "pavucontrol")]),
}
NOTES = {
    "mobile": ("For wireless pairing, install KDE Connect on a supported phone and join the same network. For USB, unlock the phone and allow file access.",
               "לצימוד אלחוטי יש להתקין KDE Connect בטלפון נתמך ולהתחבר לאותה רשת. בחיבור USB יש לבטל את נעילת הטלפון ולאשר גישה לקבצים."),
    "updates": ("In Synaptic, reload the package list, mark upgrades, then review and apply the changes.",
                "במנהל החבילות יש לרענן את רשימת החבילות, לסמן שדרוגים, לעיין בשינויים ולאשר אותם."),
    "xr": ("Some headsets expose a standard display or audio device. This 32-bit edition has no immersive tracking runtime.",
           "משקפיים מסוימים מזוהים כמסך או כהתקן שמע רגיל. מהדורת 32 סיביות זו אינה כוללת סביבת מעקב תנועה למציאות מדומה."),
    "privacy": ("The microphone control affects the default audio source. Firefox permissions apply to websites in that browser. Recent file history applies to GTK applications that use it.",
                "בקרת המיקרופון חלה על מקור השמע המוגדר כברירת מחדל. הרשאות Firefox חלות על האתרים בדפדפן זה. היסטוריית הקבצים חלה על יישומי GTK המשתמשים בה."),
}
LOGO = Path("/usr/share/newworld/newworld-logo.png")
WORDS = r"[A-Za-z0-9]+(?:[./_:+%\-][A-Za-z0-9]+)*"
ASCII = re.compile(WORDS + r"(?: " + WORDS + r")*")
INTERNAL = {"@usb": "lsusb", "@cpu": "lscpu", "@airplane": "/usr/sbin/rfkill",
            "@microphone": "pactl", "@recent": "xfconf-query"}
RECENT = ("xfconf-query", "-c", "xsettings", "-p", "/Gtk/RecentFilesEnabled")


def translate(pair, hebrew):
    text = pair[int(hebrew)]
    return ASCII.sub(lambda match: "\u2066" + match[0] + "\u2069", text) if hebrew else text


def available(route):
    return bool(shutil.which(INTERNAL.get(route[0], route[0])))


def command(args, check=True):
    return subprocess.run(args, check=check, text=True, errors="replace", capture_output=True,
                          timeout=8, env=dict(os.environ, LC_ALL="C"))


def scroll(widget):
    box = Gtk.ScrolledWindow()
    box.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
    box.add(widget)
    return box


class Window(Gtk.Window):
    def __init__(self, hebrew=None):
        super().__init__()
        language = os.environ.get("LANGUAGE", "").split(":")[0] or os.environ.get("LANG", "")
        self.hebrew = language.startswith("he") if hebrew is None else hebrew
        self.current = "system"
        self.set_default_size(800, 510)
        self.set_icon_name("preferences-desktop")
        self.build()

    def tr(self, en, he):
        return translate((en, he), self.hebrew)

    def label(self, text):
        label = Gtk.Label(label=text, xalign=1 if self.hebrew else 0)
        label.set_line_wrap(True)
        label.set_line_wrap_mode(Pango.WrapMode.WORD_CHAR)
        return label

    def build(self):
        child = self.get_child()
        if child:
            child.destroy()
        direction = Gtk.TextDirection.RTL if self.hebrew else Gtk.TextDirection.LTR
        Gtk.Widget.set_default_direction(direction)
        self.set_direction(direction)
        self.set_title(self.tr("NewWorld Settings", "הגדרות NewWorld"))
        layout = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=0)
        self.add(layout)
        self.header = Gtk.Box(spacing=12)
        self.header.set_direction(Gtk.TextDirection.LTR)
        self.header.set_border_width(9)
        try:
            logo = Gtk.Image.new_from_pixbuf(GdkPixbuf.Pixbuf.new_from_file_at_scale(str(LOGO), 64, 42, True))
        except GLib.Error:
            logo = Gtk.Image.new_from_icon_name("preferences-desktop", Gtk.IconSize.LARGE_TOOLBAR)
        self.header.pack_start(logo, False, False, 0)
        self.header.pack_start(self.label(self.get_title()), False, False, 0)
        switch = Gtk.Button.new_with_label("English" if self.hebrew else "עברית")
        switch.connect("clicked", self.switch_language)
        self.header.pack_end(switch, False, False, 0)
        layout.pack_start(self.header, False, False, 0)
        layout.pack_start(Gtk.Separator(), False, False, 0)
        self.columns = Gtk.Box(spacing=0)
        self.columns.set_direction(self.get_direction())
        layout.pack_start(self.columns, True, True, 0)
        self.sidebar = Gtk.ListBox()
        self.sidebar.set_selection_mode(Gtk.SelectionMode.SINGLE)
        self.sidebar.set_activate_on_single_click(True)
        side = scroll(self.sidebar)
        side.set_size_request(185, -1)
        self.columns.pack_start(side, False, False, 0)
        self.columns.pack_start(Gtk.Separator(orientation=Gtk.Orientation.VERTICAL), False, False, 0)
        self.content = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=8)
        self.content.set_border_width(16)
        self.columns.pack_start(scroll(self.content), True, True, 0)
        for key, (title, icon, _actions) in PAGES.items():
            row = Gtk.ListBoxRow()
            row.key = key
            items = Gtk.Box(spacing=8)
            items.set_border_width(7)
            items.set_direction(self.get_direction())
            items.pack_start(Gtk.Image.new_from_icon_name(icon, Gtk.IconSize.MENU), False, False, 0)
            items.pack_start(self.label(translate(title, self.hebrew)), True, True, 0)
            row.add(items)
            self.sidebar.add(row)
        self.sidebar.connect("row-selected", self.select)
        selected = next(row for row in self.sidebar if row.key == self.current)
        self.sidebar.select_row(selected)
        self.show_all()

    def switch_language(self, *_):
        self.hebrew = not self.hebrew
        self.build()

    def select(self, _box, row):
        if row is None:
            return
        self.current = row.key
        for old in self.content.get_children():
            old.destroy()
        title, _, actions = PAGES[self.current]
        heading = self.label(translate(title, self.hebrew))
        heading.set_markup("<big><b>" + GLib.markup_escape_text(heading.get_text()) + "</b></big>")
        self.content.pack_start(heading, False, False, 4)
        if self.current in NOTES:
            self.content.pack_start(self.label(translate(NOTES[self.current], self.hebrew)), False, False, 6)
        for en, he, *argv in actions:
            name = self.tr(en, he)
            button = Gtk.Button()
            button.add(self.label(name))
            button.get_accessible().set_name(name)
            if not available(argv):
                extra = self.tr("Unavailable on this installation", "לא זמין בהתקנה זו")
                button.get_child().set_text(name + " · " + extra)
                button.set_sensitive(False)
            else:
                button.connect("clicked", self.activate, name, argv)
            self.content.pack_start(button, False, False, 0)
        self.content.show_all()

    def dialog(self, title):
        dlg = Gtk.Dialog(title=title, transient_for=self, modal=True)
        dlg.set_direction(self.get_direction())
        dlg.get_content_area().set_border_width(12)
        dlg.get_content_area().set_spacing(10)
        dlg.add_button(self.tr("Close", "סגירה"), Gtk.ResponseType.CLOSE)
        return dlg

    def show_text(self, title, value, technical=False):
        dlg = self.dialog(title)
        if technical:
            view = Gtk.TextView(editable=False, cursor_visible=False, monospace=True)
            view.set_direction(Gtk.TextDirection.LTR)
            view.get_buffer().set_text(value)
            frame = scroll(view)
            frame.set_size_request(410, 210)
            dlg.get_content_area().add(frame)
        else:
            dlg.get_content_area().add(self.label(value))
        dlg.show_all()
        dlg.run()
        dlg.destroy()

    def choose(self, title, current, choices):
        dlg = self.dialog(title)
        dlg.get_content_area().add(self.label(current))
        for i, text in enumerate(choices, 1):
            dlg.add_button(text, i)
        dlg.show_all()
        reply = dlg.run()
        dlg.destroy()
        return reply

    def privacy_recent(self, title):
        state = command(RECENT, check=False)
        # A missing XSettings override leaves GTK's setting in effect.
        enabled = (state.stdout.strip() == "true" if state.returncode == 0 else
                   bool(Gtk.Settings.get_default().get_property("gtk-recent-files-enabled")))
        label = self.tr("History is enabled.", "שמירת ההיסטוריה מופעלת.") if enabled else self.tr("History is disabled.", "שמירת ההיסטוריה מושבתת.")
        action = self.choose(title, label, [self.tr("Disable" if enabled else "Enable", "השבתה" if enabled else "הפעלה"), self.tr("Clear history…", "ניקוי ההיסטוריה…")])
        if action == 1:
            args = list(RECENT)
            if state.returncode:
                args += ["--create", "-t", "bool"]
            command(args + ["-s", "false" if enabled else "true"])
        if action == 2 and self.choose(title, self.tr("Remove all entries from this account’s recent file history?", "למחוק את כל הרשומות מהיסטוריית הקבצים האחרונים בחשבון זה?"), [self.tr("Clear history", "ניקוי ההיסטוריה")]) == 1:
            Gtk.RecentManager.get_default().purge_items()

    def activate(self, _button, name, args):
        try:
            action = args[0]
            if action in ("@cpu", "@usb"):
                report = command([INTERNAL[action]]).stdout.strip()
                self.show_text(name, report or self.tr("No devices detected.", "לא זוהו מכשירים."), technical=True)
            elif action == "@microphone":
                status = command(["pactl", "get-source-mute", "@DEFAULT_SOURCE@"]).stdout.strip()
                muted = status.endswith("yes")
                message = self.tr("The default microphone is muted.", "מיקרופון ברירת המחדל מושתק.") if muted else self.tr("The default microphone is active.", "מיקרופון ברירת המחדל פעיל.")
                choice = self.tr("Unmute", "ביטול השתקה") if muted else self.tr("Mute", "השתקה")
                if self.choose(name, message, [choice]) == 1:
                    command(["pactl", "set-source-mute", "@DEFAULT_SOURCE@", "0" if muted else "1"])
            elif action == "@airplane":
                radios = command([INTERNAL[action], "--output", "TYPE,SOFT,HARD"]).stdout.strip()
                message = self.tr("Block or unblock all wireless radios. A hardware switch can keep a radio blocked.", "אפשר לחסום או לשחרר את כל המשדרים האלחוטיים. מתג חומרה עשוי להשאיר משדר חסום.")
                reply = self.choose(name, message + "\n\n\u2066" + radios + "\u2069", [self.tr("Block radios", "חסימת משדרים"), self.tr("Unblock radios", "שחרור משדרים")])
                if reply in (1, 2):
                    subprocess.Popen(["pkexec", INTERNAL[action], "block" if reply == 1 else "unblock", "all"])
            elif action == "@recent":
                self.privacy_recent(name)
            else:
                subprocess.Popen(args)
        except (OSError, GLib.Error, subprocess.SubprocessError) as error:
            detail = getattr(error, "stderr", None) or str(error)
            self.show_text(name, self.tr("The operation could not finish.", "לא ניתן להשלים את הפעולה.") + "\n\n" + detail.strip())


if __name__ == "__main__":
    window = Window()
    window.connect("destroy", Gtk.main_quit)
    Gtk.main()
