#!/usr/bin/python3 -IS
"""Oturum açılırken masaüstü görünmesin diye ekranı siyah perdeyle kaplar.

Pardus oturumu (Xsession) başlarken, masaüstü çizilmeden önce çalışır. Kilit programı kendi siyah
açılış ekranını gösterince "hazır" işaretini bırakır; perde o an kalkar ve geçiş siyahtan siyaha olur.
Kilit programı gelmezse perde en geç PERDE_SURE saniyede kendiliğinden kalkar; tahta siyah kalmaz.
Yalnız standart kütüphane ve libX11 kullanır; birkaç milisaniyede açılır.
"""
import ctypes
import os
import time

PERDE_SURE = 45.0
ARALIK = 0.05


def hazir_dosyasi() -> str:
    klasor = os.environ.get("XDG_RUNTIME_DIR") or "/tmp"
    return os.path.join(klasor, f"okulzen-hazir-{os.getuid()}")


class Ozellikler(ctypes.Structure):  # XSetWindowAttributes
    _fields_ = [("background_pixmap", ctypes.c_ulong), ("background_pixel", ctypes.c_ulong),
                ("border_pixmap", ctypes.c_ulong), ("border_pixel", ctypes.c_ulong),
                ("bit_gravity", ctypes.c_int), ("win_gravity", ctypes.c_int), ("backing_store", ctypes.c_int),
                ("backing_planes", ctypes.c_ulong), ("backing_pixel", ctypes.c_ulong),
                ("save_under", ctypes.c_int), ("event_mask", ctypes.c_long),
                ("do_not_propagate_mask", ctypes.c_long), ("override_redirect", ctypes.c_int),
                ("colormap", ctypes.c_ulong), ("cursor", ctypes.c_ulong)]


CW_BACK_PIXEL = 1 << 1
CW_OVERRIDE_REDIRECT = 1 << 9
CW_CURSOR = 1 << 14


def main() -> int:
    isaret = hazir_dosyasi()
    try:
        os.unlink(isaret)  # Önceki oturumdan kalan işaret perdeyi hemen kaldırmasın.
    except OSError:
        pass
    try:
        x = ctypes.CDLL("libX11.so.6")
    except OSError:
        return 0
    x.XOpenDisplay.restype = ctypes.c_void_p
    x.XOpenDisplay.argtypes = [ctypes.c_char_p]
    ekran = x.XOpenDisplay(None)
    if not ekran:
        return 0
    for ad, donus, argumanlar in (
            ("XDefaultScreen", ctypes.c_int, [ctypes.c_void_p]),
            ("XRootWindow", ctypes.c_ulong, [ctypes.c_void_p, ctypes.c_int]),
            ("XBlackPixel", ctypes.c_ulong, [ctypes.c_void_p, ctypes.c_int]),
            ("XCreateWindow", ctypes.c_ulong, [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_int, ctypes.c_int,
                                               ctypes.c_uint, ctypes.c_uint, ctypes.c_uint, ctypes.c_int,
                                               ctypes.c_uint, ctypes.c_void_p, ctypes.c_ulong,
                                               ctypes.POINTER(Ozellikler)]),
            ("XCreatePixmap", ctypes.c_ulong, [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_uint, ctypes.c_uint,
                                               ctypes.c_uint]),
            ("XCreatePixmapCursor", ctypes.c_ulong, [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_ulong,
                                                     ctypes.c_void_p, ctypes.c_void_p, ctypes.c_uint,
                                                     ctypes.c_uint]),
            ("XGetGeometry", ctypes.c_int, [ctypes.c_void_p, ctypes.c_ulong, ctypes.POINTER(ctypes.c_ulong),
                                            ctypes.POINTER(ctypes.c_int), ctypes.POINTER(ctypes.c_int),
                                            ctypes.POINTER(ctypes.c_uint), ctypes.POINTER(ctypes.c_uint),
                                            ctypes.POINTER(ctypes.c_uint), ctypes.POINTER(ctypes.c_uint)]),
            ("XMoveResizeWindow", ctypes.c_int, [ctypes.c_void_p, ctypes.c_ulong, ctypes.c_int, ctypes.c_int,
                                                 ctypes.c_uint, ctypes.c_uint]),
            ("XMapRaised", ctypes.c_int, [ctypes.c_void_p, ctypes.c_ulong]),
            ("XRaiseWindow", ctypes.c_int, [ctypes.c_void_p, ctypes.c_ulong]),
            ("XFlush", ctypes.c_int, [ctypes.c_void_p]),
            ("XCloseDisplay", ctypes.c_int, [ctypes.c_void_p])):
        getattr(x, ad).restype = donus
        getattr(x, ad).argtypes = argumanlar
    numara = x.XDefaultScreen(ekran)
    kok = x.XRootWindow(ekran, numara)
    ozellik = Ozellikler()
    ozellik.background_pixel = x.XBlackPixel(ekran, numara)
    ozellik.override_redirect = 1  # Pencere yöneticisi dokunmaz; masaüstü ve panelin üstünde durur.
    maske = CW_BACK_PIXEL | CW_OVERRIDE_REDIRECT
    bos = x.XCreatePixmap(ekran, kok, 1, 1, 1)
    if bos:
        renk = (ctypes.c_ubyte * 16)()  # Sıfırlanmış XColor (16 bayt); tek bitlik boş imleç.
        ozellik.cursor = x.XCreatePixmapCursor(ekran, bos, bos, ctypes.byref(renk), ctypes.byref(renk), 0, 0)
        if ozellik.cursor:
            maske |= CW_CURSOR
    def boyut() -> tuple[int, int]:
        kok_, xx, yy = ctypes.c_ulong(), ctypes.c_int(), ctypes.c_int()
        en, boy, kenar, derinlik = ctypes.c_uint(), ctypes.c_uint(), ctypes.c_uint(), ctypes.c_uint()
        if not x.XGetGeometry(ekran, kok, ctypes.byref(kok_), ctypes.byref(xx), ctypes.byref(yy), ctypes.byref(en),
                              ctypes.byref(boy), ctypes.byref(kenar), ctypes.byref(derinlik)):
            return 1920, 1080
        return max(1, en.value), max(1, boy.value)

    # Pencere ekran kadar açılır: aşırı büyük pencere masaüstü birleştiricisini (Cinnamon) çökertir.
    # Oturum başında çözünürlük değişirse perde de büyür/küçülür.
    en, boy = boyut()
    pencere = x.XCreateWindow(ekran, kok, 0, 0, en, boy, 0, 0, 1, None, maske, ctypes.byref(ozellik))
    x.XMapRaised(ekran, pencere)
    x.XFlush(ekran)
    bitis = time.monotonic() + PERDE_SURE
    while time.monotonic() < bitis and not os.path.exists(isaret):
        time.sleep(ARALIK)
        yeni = boyut()
        if yeni != (en, boy):
            en, boy = yeni
            x.XMoveResizeWindow(ekran, pencere, 0, 0, en, boy)
        x.XRaiseWindow(ekran, pencere)
        x.XFlush(ekran)
    x.XCloseDisplay(ekran)  # Pencere bağlantıyla birlikte kalkar.
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
