# coding: utf-8
# python 2 only

# Copyright (c) 2026 TormachTips.com. All rights reserved.
# Licensed under the TormachTips Personal Use License.
# Permission is granted only for private personal use and private personal modification.
# No sharing, publication, distribution, resale, sublicensing, screenshots, code excerpts,
# benchmarks, or videos are permitted without prior written permission.
# Requests:         tormach.1100m@gmail.com
# Information page: https://tormachtips.com/plugins.htm

#############################################
##                                         ##
##      ALT + TAB Icon Patcher v0.97       ##
##          www.tormachtips.com            ##
##                                         ##
#############################################

# 0.97 - Restores executable permissions after atomic write to tormach_mill_ui.py. - 5/03/2026
# 0.96 - Added shared file lock, chronological backups, atomic writes, syntax validation, and verbose patch debug logging. - 5/02/2026
# 0.95 - Public release. - 4/2/26

import os
import re
import time
import fcntl
import shutil
import stat
import gtk
import glib
import constants
from ui_hooks import plugin, version_list

CURRENT_VER                  = "0.97"
SCRIPT_NAME                  = "ALT TAB Icon Patcher"
DESCRIPTION                  = "Gives you a custom icon when ALT TABBING. Only works if PathPilot is run from a terminal."
ENABLED                      = 1
DEV_MACHINE                  = 0
DEV_MACHINE_FLAG             = "/home/operator/gcode/python/dev_machine.txt"
ICON                         = "tab_icon_patcher_plugin.png"
TARGET_FILE                  = os.path.join("python", "tormach_mill_ui.py")
DEST_ICON_FILE               = os.path.join("python", "images", ICON)
MARKER                       = "# BEAGLE: ALT TAB ICON PATCH INSTALLED"
PATCH_START                  = "# BEAGLE: ALT TAB ICON PATCH START"
PATCH_END                    = "# BEAGLE: ALT TAB ICON PATCH END"
PATCH_LOCK_PATH              = "/tmp/tt_pathpilot_file_patch.lock"
PATCH_LOCK_TIMEOUT_SECONDS   = 10

class TTFilePatchLock(object):
    def __init__(self, owner, error_handler, lock_path, timeout_seconds):
        self.owner = owner
        self.error_handler = error_handler
        self.lock_path = lock_path
        self.timeout_seconds = timeout_seconds
        self.fp = None

    def write(self, message):
        try:
            self.error_handler.write("[%s] %s" % (self.owner, message), constants.ALARM_LEVEL_QUIET)
        except:
            pass

    def __enter__(self):
        start_time = time.time()
        self.write("Opening patch lock file: %s" % self.lock_path)
        self.fp = open(self.lock_path, "a+")
        self.write("Waiting for patch lock: %s" % self.lock_path)
        while True:
            try:
                fcntl.flock(self.fp.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
                self.write("Patch lock acquired: %s" % self.lock_path)
                return self
            except IOError:
                elapsed = time.time() - start_time
                if elapsed >= self.timeout_seconds:
                    self.write("Patch lock timeout after %.1f seconds: %s" % (elapsed, self.lock_path))
                    raise RuntimeError("Timed out waiting for patch lock: %s" % self.lock_path)
                time.sleep(0.1)

    def __exit__(self, exc_type, exc_value, traceback_obj):
        try:
            if self.fp:
                self.write("Releasing patch lock: %s" % self.lock_path)
                fcntl.flock(self.fp.fileno(), fcntl.LOCK_UN)
                self.write("Patch lock released: %s" % self.lock_path)
        finally:
            try:
                if self.fp:
                    self.fp.close()
                    self.write("Closed patch lock file: %s" % self.lock_path)
            except:
                pass
        return False

class UserPlugin(plugin):
    def __init__(self):
        plugin.__init__(self, '%s %s' % (SCRIPT_NAME, CURRENT_VER))
        dev_machine_found = os.path.exists(DEV_MACHINE_FLAG)
        if dev_machine_found:
            plugin_enabled = DEV_MACHINE
        else:
            plugin_enabled = ENABLED
        if plugin_enabled:
            glib.timeout_add(3000, self.try_patch)
            return
        if dev_machine_found:
            self.error_handler.write("[%s] Dev machine found. Plugin loaded, but disabled by DEV_MACHINE." % SCRIPT_NAME, constants.ALARM_LEVEL_QUIET)
        else:
            self.error_handler.write("[%s] Plugin loaded, but disabled." % SCRIPT_NAME, constants.ALARM_LEVEL_QUIET)
            self.error_handler.write("[%s] To enable it, open the script, find ENABLED = 0, and change it to ENABLED = 1." % SCRIPT_NAME, constants.ALARM_LEVEL_QUIET)

    def debug(self, message):
        self.error_handler.write("[%s] %s" % (SCRIPT_NAME, message), constants.ALARM_LEVEL_QUIET)

    def show_nonblocking_dialog(self):
        dialog = gtk.MessageDialog(
            None,
            gtk.DIALOG_DESTROY_WITH_PARENT,
            gtk.MESSAGE_INFO,
            gtk.BUTTONS_OK,
            "Alt-Tab icon patch applied.\n\nPlease reboot PathPilot/Linux for the change to take effect.")
        dialog.set_title(SCRIPT_NAME)
        dialog.set_keep_above(True)
        dialog.set_modal(False)

        def on_response(widget, response_id):
            widget.destroy()
        dialog.connect("response", on_response)
        dialog.show_all()

    def safe_script_name(self):
        safe_name = SCRIPT_NAME.lower()
        safe_name = safe_name.replace(" ", "_")
        safe_name = re.sub(r"[^a-z0-9_]+", "_", safe_name)
        return safe_name

    def get_paths(self):
        version_path = "v%d.%d.%d" % (version_list[0], version_list[1], version_list[2])
        version_root = os.path.join("/home/operator", version_path)
        plugin_dir = os.path.dirname(os.path.abspath(__file__))
        return {
            "version_root": version_root,
            "target": os.path.join(version_root, TARGET_FILE),
            "dest_icon": os.path.join(version_root, DEST_ICON_FILE),
            "source_icon": os.path.join(plugin_dir, ICON),
            "images_dir": os.path.dirname(os.path.join(version_root, DEST_ICON_FILE))}

    def read_file(self, path):
        self.debug("Reading file: %s" % path)
        with open(path, "r") as f:
            content = f.read()
        self.debug("Read %d bytes from file: %s" % (len(content), path))
        return content

    def make_chronological_backup(self, target_path):
        timestamp = time.strftime("%Y%m%d_%H%M%S")
        safe_name = self.safe_script_name()
        backup_path = "%s.%s.%s.bak" % (target_path, timestamp, safe_name)
        counter = 1
        final_path = backup_path
        while os.path.exists(final_path):
            final_path = "%s.%03d" % (backup_path, counter)
            counter += 1
        self.debug("Creating chronological backup.")
        self.debug("Backup source: %s" % target_path)
        self.debug("Backup target: %s" % final_path)
        shutil.copy2(target_path, final_path)
        self.debug("Backup complete: %s" % final_path)
        return final_path

    def chmod_executable(self, target_path):
        current_mode = os.stat(target_path).st_mode
        executable_mode = current_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH
        self.debug("Restoring executable bit.")
        self.debug("chmod target: %s" % target_path)
        self.debug("chmod mode before: %o" % current_mode)
        self.debug("chmod mode after: %o" % executable_mode)
        os.chmod(target_path, executable_mode)
        if not os.access(target_path, os.X_OK):
            raise RuntimeError("File is not executable after chmod: %s" % target_path)
        self.debug("Executable permission confirmed: %s" % target_path)

    def atomic_write_file(self, target_path, content):
        original_stat = os.stat(target_path)
        temp_path = "%s.%s.%d.tmp" % (
            target_path,
            self.safe_script_name(),
            os.getpid())
        self.debug("Writing temporary patched file: %s" % temp_path)
        with open(temp_path, "w") as f:
            f.write(content)
        self.debug("Temporary patched file written: %s" % temp_path)
        try:
            os.chmod(temp_path, original_stat.st_mode)
            self.debug("Copied original file mode to temporary file: %o" % original_stat.st_mode)
        except Exception as e:
            self.debug("Could not copy original mode to temporary file: %s" % str(e))
        try:
            os.chown(temp_path, original_stat.st_uid, original_stat.st_gid)
            self.debug("Copied original owner/group to temporary file.")
        except Exception as e:
            self.debug("Could not copy original owner/group to temporary file: %s" % str(e))
        self.debug("Renaming temporary file over target.")
        self.debug("Rename source: %s" % temp_path)
        self.debug("Rename target: %s" % target_path)
        os.rename(temp_path, target_path)
        self.debug("Atomic rename complete: %s" % target_path)
        self.chmod_executable(target_path)

    def validate_python_content(self, target_path, content):
        try:
            compile(content, target_path, "exec")
            self.debug("Python syntax validation passed: %s" % target_path)
        except Exception as e:
            raise RuntimeError("Patched file failed Python syntax validation: %s" % str(e))

    def copy_icon_asset(self, source_icon_path, dest_icon_path, images_dir):
        if not os.path.isfile(source_icon_path):
            raise RuntimeError("Icon file not found: %s" % source_icon_path)
        if not os.path.isdir(images_dir):
            self.debug("Creating images directory: %s" % images_dir)
            os.makedirs(images_dir)
        self.debug("Copying icon asset.")
        self.debug("Icon source: %s" % source_icon_path)
        self.debug("Icon target: %s" % dest_icon_path)
        shutil.copy2(source_icon_path, dest_icon_path)
        self.debug("Icon asset copied: %s" % dest_icon_path)

    def patch_content(self, content, dest_icon_path):
        if MARKER in content:
            self.debug("Patch marker already present.")
            return content, False
        original_content = content
        init_pattern = re.compile(
            r'^(?P<indent>[ \t]*)TormachUIBase\.__init__\(self,\s*gladefile,\s*self\.ini_file_name\)[ \t]*$',
            re.MULTILINE)

        def inject_icon_block(match):
            indent = match.group('indent')
            return (
                match.group(0) + "\n\n" +
                indent + MARKER + "\n" +
                indent + PATCH_START + "\n" +
                indent + "icon_path = %r\n" % dest_icon_path +
                indent + "try:\n" +
                indent + "    self.window.set_icon_from_file(icon_path)\n" +
                indent + "except Exception:\n" +
                indent + "    pass\n" +
                indent + PATCH_END)
        
        self.debug("Searching for TormachUIBase init block.")
        patched_content, count = init_pattern.subn(inject_icon_block, content, count=1)
        self.debug("Alt-Tab icon replacement count: %d" % count)
        if count < 1:
            raise RuntimeError("Injection point not found. Patch skipped.")
        if patched_content == original_content:
            raise RuntimeError("Patch produced no content changes.")
        return patched_content, True

    def try_patch(self):
        backup_path = ""
        try:
            paths = self.get_paths()
            self.debug("Target file: %s" % paths["target"])
            self.debug("Source icon: %s" % paths["source_icon"])
            self.debug("Destination icon: %s" % paths["dest_icon"])
            self.debug("Patch marker: %s" % MARKER)
            with TTFilePatchLock(SCRIPT_NAME, self.error_handler, PATCH_LOCK_PATH, PATCH_LOCK_TIMEOUT_SECONDS):
                self.debug("Inside locked patch section.")
                if not os.path.exists(paths["target"]):
                    self.error_handler.write("[%s] File not found: %s" % (SCRIPT_NAME, paths["target"]), constants.ALARM_LEVEL_LOW)
                    return False
                if not os.path.exists(paths["source_icon"]):
                    self.error_handler.write("[%s] Icon file not found: %s" % (SCRIPT_NAME, paths["source_icon"]), constants.ALARM_LEVEL_LOW)
                    return False
                content = self.read_file(paths["target"])
                patched_content, changed = self.patch_content(content, paths["dest_icon"])
                if not changed:
                    self.error_handler.write("[%s] Already patched. No changes made." % SCRIPT_NAME, constants.ALARM_LEVEL_QUIET)
                    if not os.path.isfile(paths["dest_icon"]):
                        self.copy_icon_asset(paths["source_icon"], paths["dest_icon"], paths["images_dir"])
                        self.error_handler.write("[%s] Patch was already installed, but icon was missing and has been copied." % SCRIPT_NAME, constants.ALARM_LEVEL_MEDIUM)
                    if not os.access(paths["target"], os.X_OK):
                        self.debug("Patch marker exists, but file is not executable. Restoring executable bit.")
                        self.chmod_executable(paths["target"])
                    self.debug("Marker found; exiting without backup or write.")
                    return False
                self.validate_python_content(paths["target"], patched_content)
                self.debug("Patch content generated.")
                self.debug("Original byte count: %d" % len(content))
                self.debug("Patched byte count: %d" % len(patched_content))
                backup_path = self.make_chronological_backup(paths["target"])
                self.copy_icon_asset(paths["source_icon"], paths["dest_icon"], paths["images_dir"])
                self.atomic_write_file(paths["target"], patched_content)
                self.debug("Leaving locked patch section after successful write.")
            self.error_handler.write(" ", constants.ALARM_LEVEL_QUIET)
            self.error_handler.write("[%s] Patch applied to: %s" % (SCRIPT_NAME, paths["target"]), constants.ALARM_LEVEL_MEDIUM)
            self.error_handler.write("[%s] Backup created: %s" % (SCRIPT_NAME, backup_path), constants.ALARM_LEVEL_MEDIUM)
            self.error_handler.write("[%s] Icon copied to: %s" % (SCRIPT_NAME, paths["dest_icon"]), constants.ALARM_LEVEL_MEDIUM)
            self.error_handler.write("[%s] Executable permission confirmed on patched file." % SCRIPT_NAME, constants.ALARM_LEVEL_MEDIUM)
            self.error_handler.write("[%s] Reboot PathPilot/Linux to take effect." % SCRIPT_NAME, constants.ALARM_LEVEL_MEDIUM)
            self.error_handler.write(" ", constants.ALARM_LEVEL_QUIET)
            glib.idle_add(self.show_nonblocking_dialog)
        except Exception as e:
            self.error_handler.write("[%s] Error: %s" % (SCRIPT_NAME, str(e)), constants.ALARM_LEVEL_LOW)
        return False

DESCRIPTION_LONG = """Provides&nbsp; better icon when ALT + 
    TABBING, like on Windows. I created a professional Tormach logo icon. 
    Requires PathPilot to be run in a terminal.</font></p>
    <p>
    <a href="images/tabber.png">
    <img border="2" src="images/tabber_small.png" xthumbnail-orig-image="images/tabber.png" width="200" height="150"></a></p>
        <p><font face="Verdana" size="2"><a href="plugins/output.htm">Plugin is 
        available on this regularly-updated page.</a></font><p>
    <font face="Verdana" size="2">Also needed (or DIY):</font><p>
    <b><font face="Verdana" size="2">
    <a href="plugins/tab_icon_patcher_plugin.png">Icon Image</a></B>"""