# 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

#######################################
##                                   ##
##     Ajustable Tab Widths 0.95     ##
##    https://www.tormachtips.com    ##
##                                   ##
#######################################

# 0.95 - Public Beta - 4/17/26

import os
import glib
import gtk
import singletons
import constants
from ui_hooks import plugin

CURRENT_VER        = "0.95"
DESCRIPTION        = "Adjusts PathPilot main notebook tab widths."
SCRIPT_NAME        = "Adjustable Tab Widths"
ENABLED            = 1
DEV_MACHINE        = 1
DEV_MACHINE_FLAG   = "/home/operator/gcode/python/dev_machine.txt"
START_DELAY_MS     = 2500
RETRY_DELAY_MS     = 1000
MAX_RETRIES        = 10
DEFAULT_TAB_WIDTH  = 92
DEFAULT_TAB_HEIGHT = -1
TAB_WIDTHS         = {
    "notebook_main_fixed":                  92,
    "notebook_file_util_wrapping_eventbox": 92,
    "notebook_settings_fixed":              92,
    "notebook_offsets_fixed":               92,
    "conversational_fixed":                 92,
    "atc_fixed":                            92,
    "rack_tool_changer_fixed":              92,
    "probe_fixed":                          92,
    "scanner_fixed":                        92,
    "injector_fixed":                       92,
    "alarms_fixed":                         92,
    "my_custom_tab_fixed":                  92,
    "load_meter_fixed":                     92,}

class UserPlugin(plugin):
    def __init__(self):
        plugin.__init__(self, SCRIPT_NAME)
        self._page_added_handler_id = None
        self._switch_page_handler_id = None
        self._retries_left = MAX_RETRIES
        self._last_width_map = {}
        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(START_DELAY_MS, self.start_process)
            return
        else:
            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, open script, find ENABLED = 0 and change to ENABLED = 1" % SCRIPT_NAME, constants.ALARM_LEVEL_QUIET)
            return
    
    def start_process(self):
        ui = singletons.g_Machine
        if ui:
            pass
        else:
            self._retries_left -= 1
            if self._retries_left > 0:
                self.error_handler.write("[%s] UI not ready yet, retrying." % SCRIPT_NAME, constants.ALARM_LEVEL_DEBUG)
                glib.timeout_add(RETRY_DELAY_MS, self.start_process)
            else:
                self.error_handler.write("[%s] UI never became ready." % SCRIPT_NAME, constants.ALARM_LEVEL_LOW)
            return False
        try:
            self.install_tab_width_hooks(ui)
            self.apply_tab_widths(ui)
            self.error_handler.write("[%s] Tab width plugin initialized." % SCRIPT_NAME, constants.ALARM_LEVEL_MEDIUM)
        except Exception as e:
            self.error_handler.write("[%s] Startup error: %s" % (SCRIPT_NAME, str(e)), constants.ALARM_LEVEL_LOW)
        return False
    
    def install_tab_width_hooks(self, ui):
        notebook = getattr(ui, "notebook", None)
        if notebook:
            pass
        else:
            self.error_handler.write("[%s] UI notebook not found." % SCRIPT_NAME, constants.ALARM_LEVEL_LOW)
            return
        if self._page_added_handler_id is None:
            self._page_added_handler_id = notebook.connect("page-added", self.on_notebook_page_added, ui)
        if self._switch_page_handler_id is None:
            self._switch_page_handler_id = notebook.connect("switch-page", self.on_notebook_switch_page, ui)
    
    def on_notebook_page_added(self, notebook, child, page_num, ui):
        glib.idle_add(self.apply_tab_widths, ui)
    
    def on_notebook_switch_page(self, notebook, page, page_num, ui):
        glib.idle_add(self.apply_tab_widths, ui)
        return False
    
    def get_page_id(self, page):
        try:
            return gtk.Buildable.get_name(page)
        except Exception:
            return ""
    
    def get_target_width_for_page_id(self, page_id):
        if page_id in TAB_WIDTHS:
            return TAB_WIDTHS[page_id]
        return DEFAULT_TAB_WIDTH
    
    def apply_tab_widths(self, ui):
        notebook = getattr(ui, "notebook", None)
        if notebook:
            pass
        else:
            return False
        changed_any = False
        for index in range(notebook.get_n_pages()):
            page = notebook.get_nth_page(index)
            if page:
                pass
            else:
                continue
            page_id = self.get_page_id(page)
            if page_id:
                pass
            else:
                continue
            tab_label = notebook.get_tab_label(page)
            if tab_label:
                pass
            else:
                continue
            target_width = self.get_target_width_for_page_id(page_id)
            cache_key = page_id
            old_width = self._last_width_map.get(cache_key)
            if old_width == target_width:
                continue
            try:
                tab_label.set_size_request(target_width, DEFAULT_TAB_HEIGHT)
                tab_label.show()
                self._last_width_map[cache_key] = target_width
                changed_any = True
            except Exception as e:
                self.error_handler.write("[%s] Failed setting width for %s: %s" % (SCRIPT_NAME, page_id, str(e)),constants.ALARM_LEVEL_DEBUG)
        if changed_any:
            try:
                notebook.queue_resize()
                notebook.queue_draw()
            except Exception:
                pass
        return False

DESCRIPTION_LONG = """Change the width of all your tabs. Individual 
    widths are in the plugin itself. Enjoy.</font></p>
    <p><a href="images/plenty.not.jpg">
    <img border="2" src="images/plenty.not_small.jpg" xthumbnail-orig-image="images/plenty.not.jpg" width="200" height="150"></a>
    <a href="images/plenty.jpg">
    <img border="2" src="images/plenty_small.jpg" xthumbnail-orig-image="images/plenty.jpg" width="200" height="150"></a><br>
    <font face="Verdana" size="1">Before &amp; After</font></p>"""