#!/bin/sh
#	$NetBSD: ctwm_font_size,v 1.1 2020/10/12 11:07:24 nia Exp $
#
# Copyright (c) 2020 The NetBSD Foundation, Inc.
# All rights reserved.
#
# This code is derived from software contributed to The NetBSD Foundation
# by Nia Alarie.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
# ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#

width=$(xwininfo -root | awk '/Width:/{ print $2; }')
height=$(xwininfo -root | awk '/Height:/{ print $2; }')
dpi=$(xdpyinfo | awk '/resolution:/{ split($2, res, "x"); print res[1]; }' | head -1)

# Attempt to select a reasonably sized font for the reported DPI.
#
# If the DPI is greater than 100, chances are it's specified and
# not just a default.
if [ "$dpi" -gt 100 ]; then
	for size in 16 24 32 64; do
		mm=$(printf '%d / (%d / 25)\n' "$size" "$dpi" | bc)
		if [ "$mm" -ge 3 ]; then
			printf '%d\n' "$size"
			exit 0
		fi
	done
fi

# In case the reported DPI is lower than the actual DPI, allow at least 2x2
# 80x24 xterms to be displayed in a grid.
if [ "$width" -gt 6088 -a "$height" -gt 3656 ]; then
	printf '64\n'
elif [ "$width" -gt 3048 -a "$height" -gt 1832 ]; then
	printf '32\n'
elif [ "$width" -gt 2248 -a "$height" -gt 1400 ]; then
	printf '24\n'
elif [ "$width" -gt 640 -a "$height" -gt 480 ]; then
	printf '16\n'
else
	# One 80x24 xterm with 16 pixel fonts does not fit into 640x480...
	printf '12\n'
fi
