#!/bin/sh

: 'PeterG 20241222

# Copyright (C) 2022 PeterG. This program is free software: you
# can redistribute it and/or modify it under the terms of the
# GNU General Public License as published by the Free Software
# Foundation, either version 2 of the License, or (at your
# option) any later version. This program is distributed in the
# hope that it will be useful, but WITHOUT ANY WARRANTY; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE.
'

export XFTDPI

case "$1" in ?*)	XFTDPI="$1";; esac
case "$XFTDPI" in '')	XFTDPI='120';; esac

SCALEDPI="`expr $XFTDPI / 100`.`expr $XFTDPI % 100`"
U1024DPI="`expr $XFTDPI \* 1024`"

# -Dsun.java2d.uiScale=2.0
# https://wiki.archlinux.org/title/HiDPI
# https://raw.githubusercontent.com/kaueraal/run_scaled/master/run_scaled

export KDEHOME XDG_CONFIG_HOME

case "$KDEHOME" in '')		KDEHOME="$HOME/.kde";; esac
case "$XDG_CONFIG_HOME" in '')	XDG_CONFIG_HOME="$HOME/.config";; esac

xrandr --dpi "$XFTDPI"

export GDK_SCALE GDK_TEXT_SCALE

GDK_SCALE="$SCALEDPI"
GDK_TEXT_SCALE="$SCALEDPI"

if test -n "$XDG_CONFIG_HOME" -a -d "$XDG_CONFIG_HOME/xfce4/xfconf"
then
  : 'https://codeberg.org/derat/xsettingsd says it is in DPI*1024'
  : 'But I checked on 4.16 and both are just DPI'
  xfconf-query -c xsettings -n -t int -p /Xft/DPI -s "$XFTDPI"
  xfconf-query -c xsettings -n -t int -p /Xfce/LastCustomDPI -s "$XFTDPI"
fi

if test -e /usr/bin/gsettings
then
  gsettings set org.gnome.mutter \
    experimental-features "['x11-randr-fractional-scaling','scale-monitor-framebuffer']"

  gsettings set org.gnome.settings-daemon.plugins.xsettings \
    overrides "{'Xft/DPI': <$U1024DPI>}"
fi

if test -n "$XDG_CONFIG_HOME" -a -d "$XDG_CONFIG_HOME/dconf"
then
  dconf write /org/gnome/font_rendering/dpi			"$XFTDPI"
  dconf write /org/mate/desktop/interface/font-rendering/dpi	"$XFTDPI"

  dconf write /org/gnome/desktop/interface/scaling-factor	"$SCALEDPI"
  dconf write /org/gnome/desktop/interface/text-scaling-factor	"$SCALEDPI"
fi

if test -n "$KDEHOME" -a -d "$KDEHOME/share/config"
then
  case "`which kwriteconfig5`" in ?*)
    kwriteconfig5 --file kcmfonts --group "General" \
      --key "forceFontDPI" "$XFTDPI";;
  esac
fi

echo 'Xft.dpi: '"$XFTDPI" | xrdb -override
