diff --git a/initialcon/__init__.py b/initialcon/__init__.py index 1a20f0a..fc33025 100644 --- a/initialcon/__init__.py +++ b/initialcon/__init__.py @@ -1,6 +1,7 @@ import hashlib import StringIO -from os.path import abspath, dirname, join +from os.path import abspath, dirname, join, isfile +from sys import platform import PIL from PIL import ImageFont @@ -12,20 +13,45 @@ from django.conf.urls import patterns, url from django.conf import settings -# A font is required -fonts = getattr(settings, 'INITIALCON_FONTS', None) -if fonts is None: - raise LookupError( - """ - INITIALCON_FONTS must be configured in your settings.py - INITIALCON_FONTS = { - 'default': '', - 'special': '' - } - """) - -size_default = getattr(settings, 'INITIALCON_SIZE', 100) -size_max = getattr(settings, 'INITIALCON_SIZE_MAX', 200) + +def get_font(font_name): + # Check if setting is path to font already + if '/' in font_name: + return font_name + + # Get system font dirs + if platform == 'linux': + # Default dirs from https://wiki.ubuntu.com/Fonts#Manually + font_dirs = ['/usr/share/fonts', '/usr/local/share/fonts', '~/.fonts'] + elif platform == 'darwin': + # Defaults dirs from http://support.apple.com/en-nz/HT201722 + font_dirs = ['/Library/Fonts', '/System/Library/Fonts', '~/Library/Fonts'] + + # Find font file + ttf_font_name = '%s.ttf' % font_name + for font_dir in font_dirs: + candidate = join(font_dir, ttf_font_name) + if isfile(candidate): + return candidate + + # Failing that, just return the name + return font_name + + +# Default settings +DEFAULT_SETTINGS = { + 'INITIALCON_SIZE': 100, + 'INITIALCON_SIZE_MAX': 200, + 'INITIALCON_FONTS': { + 'default': 'Times New Roman', + 'special': 'Arial Bold', + } +} + + +fonts = getattr(settings, 'INITIALCON_FONTS', DEFAULT_SETTINGS['INITIALCON_FONTS']) +size_default = getattr(settings, 'INITIALCON_SIZE', DEFAULT_SETTINGS['INITIALCON_SIZE']) +size_max = getattr(settings, 'INITIALCON_SIZE_MAX', DEFAULT_SETTINGS['INITIALCON_SIZE_MAX']) # Metro colors = getattr(settings, 'INITIALCON_COLORS', [ @@ -59,9 +85,9 @@ def generate(request, name): # Custom font font = request.GET.get('font', False) if font and font in fonts: - font = fonts[font] + font = get_font(fonts[font]) else: - font = fonts.values()[0] + font = get_font(fonts.values()[0]) # Consistent color based on name encoded = hashlib.md5(name)