diff --git a/inkycal/custom/functions.py b/inkycal/custom/functions.py index 8bab85d..4efaac3 100644 --- a/inkycal/custom/functions.py +++ b/inkycal/custom/functions.py @@ -12,18 +12,6 @@ import os import time -##from glob import glob -##import importlib -##import subprocess as subp -##import numpy -##import arrow -##from pytz import timezone - - - -##"""Set some display parameters""" -##driver = importlib.import_module('drivers.'+model) - # Get the path to the Inky-Calendar folder top_level = os.path.dirname( os.path.abspath(os.path.dirname(__file__))).split('/inkycal')[0] @@ -123,7 +111,7 @@ def write(image, xy, box_size, text, font=None, **kwargs): while (text_width, text_height) > (box_width, box_height): text=text[0:-1] text_width, text_height = font.getsize(text)[0], font.getsize('hg')[1] - logging.debug('truncated text:', text) + logging.debug(('truncated text:', text)) # Align text to desired position if alignment == "center" or None: diff --git a/inkycal/modules/ical_parser.py b/inkycal/modules/ical_parser.py index 92eb82e..9c3ff1d 100644 --- a/inkycal/modules/ical_parser.py +++ b/inkycal/modules/ical_parser.py @@ -116,7 +116,8 @@ class icalendar: t_end <= arrow.get(events.get('dtend').dt) <= t_start ] #TODO: timezone-awareness? - if events: parsed_events += events + # if any recurring events were found, add them to parsed_events + if events: self.parsed_events += events # Recurring events time-span has to be in this format: # "%Y%m%dT%H%M%SZ" (python strftime) @@ -132,20 +133,27 @@ class icalendar: 'end':arrow.get(events.get("DTEND").dt) } for ical in recurring_events for events in ical] + # if any recurring events were found, add them to parsed_events if re_events: self.parsed_events += re_events - def sort_dates(event): ##required? - return event['begin'] - self.parsed_events.sort(key=sort_dates) + # Sort events by their beginning date + self.sort() + return self.parsed_events def sort(self): """Sort all parsed events""" + if not self.parsed_events: + logging.debug('no events found to be sorted') + else: + by_date = lambda event: event['begin'] + self.parsed_events.sort(key=by_date) - def sort_dates(event): - return event['begin'] + def clear_events(self): + """clear previously parsed events""" + + self.parsed_events = [] - self.parsed_events = self.parsed_events.sort(key=sort_dates) def show_events(self, fmt='DD MMM YY HH:mm'): """print all parsed events in a more readable way @@ -153,18 +161,25 @@ class icalendar: see https://arrow.readthedocs.io/en/latest/#supported-tokens for more info tokens """ + if not self.parsed_events: logging.debug('no events found to be shown') else: +## line_width = line_width = max(len(_['title']) for _ in self.parsed_events) +## for events in self.parsed_events: +## title = events['title'], +## begin, end = events['begin'].format(fmt), events['end'].format(fmt) +## print('{0} {1} | {2} | {3}'.format( +## title, ' ' * (line_width - len(title)), begin, end)) for events in self.parsed_events: title = events['title'] begin, end = events['begin'].format(fmt), events['end'].format(fmt) print('start: {}, end : {}, title: {}'.format(begin,end,title)) -""" Sample usage... + +""" a = icalendar() a.load_url(urls) a.get_events(arrow.now(), arrow.now().shift(weeks=4)) -a.show_events() """ diff --git a/inkycal/modules/inkycal_agenda.py b/inkycal/modules/inkycal_agenda.py new file mode 100644 index 0000000..7980cee --- /dev/null +++ b/inkycal/modules/inkycal_agenda.py @@ -0,0 +1,225 @@ +#!/usr/bin/python3 +# -*- coding: utf-8 -*- +""" +Agenda module for Inky-Calendar Project +Copyright by aceisace +""" + +from inkycal.custom import * +import calendar as cal +import arrow +from ical_parser import icalendar + +size = (400, 520) +config = {'week_starts_on': 'Monday', 'ical_urls': ['https://calendar.google.com/calendar/ical/en.usa%23holiday%40group.v.calendar.google.com/public/basic.ics']} + + +class agenda: + """Agenda class + Create agenda and show events from given icalendars + """ + logger = logging.getLogger(__name__) + logging.basicConfig(level=logging.DEBUG) + + def __init__(self, section_size, section_config): + """Initialize inkycal_agenda module""" + self.name = os.path.basename(__file__).split('.py')[0] + self.config = section_config + self.width, self.height = section_size + self.background_colour = 'white' + self.font_colour = 'black' + self.fontsize = 12 + self.font = ImageFont.truetype( + fonts['NotoSans-SemiCondensed'], size = self.fontsize) + self.padding_x = 0.02 #rename to margin? + self.padding_y = 0.05 + + # Section specific config + # Format for formatting dates + self.date_format = 'D MMM' + # Fromat for formatting event timings + self.event_format = "HH:mm" #use auto for 24/12 hour format? + self.language = 'en' # Grab from settings file? + self.timezone = get_system_tz() + # urls of icalendars + self.ical_urls = config['ical_urls'] + # filepaths of icalendar files + self.ical_files = [] + print('{0} loaded'.format(self.name)) + + def set(self, **kwargs): + """Manually set some parameters of this module""" + + for key, value in kwargs.items(): + if key in self.__dict__: + setattr(self, key, value) + else: + print('{0} does not exist'.format(key)) + pass + + def get(self, **kwargs): + """Manually get some parameters of this module""" + + for key, value in kwargs.items(): + if key in self.__dict__: + getattr(self, key, value) + else: + print('{0} does not exist'.format(key)) + pass + + def get_options(self): + """Get all options which can be changed""" + + return self.__dict__ + + def generate_image(self): + """Generate image for this module""" + + # Define new image size with respect to padding + im_width = int(self.width - (self.width * 2 * self.padding_x)) + im_height = int(self.height - (self.height * 2 * self.padding_y)) + im_size = im_width, im_height + + logging.info('Image size: {0}'.format(im_size)) + + # Create an image for black pixels and one for coloured pixels + im_black = Image.new('RGB', size = im_size, color = self.background_colour) + im_colour = Image.new('RGB', size = im_size, color = 'white') + + # Calculate the max number of lines that can fit on the image + line_spacing = 1 + line_height = int(self.font.getsize('hg')[1]) + line_spacing + line_width = im_width + max_lines = im_height // line_height + logging.debug(('max lines:',max_lines)) + + # Create timeline for agenda + now = arrow.now() + today = now.floor('day') + + # Create a list of dates for the next days + agenda_events = [ + {'begin':today.shift(days=+_), + 'title': today.shift(days=+_).format( + self.date_format,locale=self.language)} + for _ in range(max_lines)] + + # Load icalendar from config + parser = icalendar() + if self.ical_urls: + parser.load_url(self.ical_urls) + if self.ical_files: + parser.load_from_file(self.ical_files) + + # Load events from all icalendar in timerange + upcoming_events = parser.get_events(today, agenda_events[-1]['begin']) + + # Sort events by beginning time + parser.sort() + # parser.show_events() + + # Set the width for date, time and event titles + date_width = int(max([self.font.getsize( + dates['begin'].format(self.date_format, locale=self.language))[0] + for dates in agenda_events]) * 1.05) + logging.debug(('date_width:', date_width)) + + # Check if any events were filtered + if upcoming_events: + + # Find out how much space the event times take + time_width = int(max([self.font.getsize( + events['begin'].format(self.event_format, locale=self.language))[0] + for events in upcoming_events]) * 1.05) + logging.debug(('time_width:', time_width)) + + # Calculate x-pos for time + x_time = date_width + logging.debug(('x-time:', x_time)) + + # Find out how much space is left for event titles + event_width = im_width - time_width - date_width + logging.debug(('width for events:', event_width)) + + # Calculate x-pos for event titles + x_event = date_width + time_width + logging.debug(('x-event:', x_event)) + + # Calculate positions for each line + line_pos = [(0, int(line * line_height)) for line in range(max_lines)] + logging.debug(('line_pos:', line_pos)) + + # Merge list of dates and list of events + agenda_events += upcoming_events + + # Sort the combined list in chronological order of dates + by_date = lambda event: event['begin'] + agenda_events.sort(key = by_date) + + # Delete more entries than can be displayed (max lines) + del agenda_events[max_lines:] + + #print(agenda_events) + + cursor = 0 + for _ in agenda_events: + title = _['title'] + + # Check if item is a date + if not 'end' in _: + ImageDraw.Draw(im_colour).line( + (0, line_pos[cursor][1], im_width, line_pos[cursor][1]), + fill = 'black') + + write(im_black, line_pos[cursor], (date_width, line_height), + title, font = self.font, alignment='left') + + cursor += 1 + + # Check if item is an event + if 'end' in _: + time = _['begin'].format(self.event_format) + + # ad-hoc! Don't display event begin time if all day + # TODO: modifiy ical-parser to somehow tell if event is all day + # Maybe event.duration = arrow(end-start).days? + if time != '00:00': + write(im_black, (x_time, line_pos[cursor][1]), + (time_width, line_height), time, + font = self.font, alignment='left') + + write(im_black, (x_event, line_pos[cursor][1]), + (event_width, line_height), + '• '+title, font = self.font, alignment='left') + cursor += 1 + +############################################################################ +# Exception handling +############################################################################ + + else: + cursor = 0 + for _ in agenda_events: + title = _['title'] + ImageDraw.Draw(im_colour).line( + (0, line_pos[cursor][1], im_width, line_pos[cursor][1]), + fill = 'black') + + write(im_black, line_pos[cursor], (date_width, line_height), + title, font = self.font, alignment='left') + + cursor += 1 + + logging.info('no events found') + + + # Save image of black and colour channel in image-folder + im_black.save(images+self.name+'.png') + im_colour.save(images+self.name+'_colour.png') + +if __name__ == '__main__': + print('running {0} in standalone mode'.format( + os.path.basename(__file__).split('.py')[0])) + + # remove below line later! + a = agenda(size, config).generate_image() diff --git a/inkycal/modules/inkycal_calendar.py b/inkycal/modules/inkycal_calendar.py new file mode 100644 index 0000000..6254cc0 --- /dev/null +++ b/inkycal/modules/inkycal_calendar.py @@ -0,0 +1,307 @@ +#!/usr/bin/python3 +# -*- coding: utf-8 -*- +""" +Calendar module for Inky-Calendar Project +Copyright by aceisace +""" + +from inkycal.custom import * +import calendar as cal +import arrow + +size = (400, 520) +config = {'week_starts_on': 'Monday', 'ical_urls': ['https://calendar.google.com/calendar/ical/en.usa%23holiday%40group.v.calendar.google.com/public/basic.ics']} + + +class calendar: + """Calendar class + Create monthly calendar and show events from given icalendars + """ + logger = logging.getLogger(__name__) + logging.basicConfig(level=logging.DEBUG) + + def __init__(self, section_size, section_config): + """Initialize inkycal_calendar module""" + + self.name = os.path.basename(__file__).split('.py')[0] + self.config = section_config + self.width, self.height = section_size + + self.background_colour = 'white' + self.font_colour = 'black' + self.fontsize = 12 + self.font = ImageFont.truetype( + fonts['NotoSans-SemiCondensed'], size = self.fontsize) + self.padding_x = 0.02 + self.padding_y = 0.05 + + self.weekstart = 'Monday' + self.show_events = True + self.event_format = "D MMM HH:mm" + self.language = 'en' # Grab from settings file? + + self.timezone = get_system_tz() + # urls of icalendars + self.ical_urls = config['ical_urls'] + # filepaths of icalendar files + self.ical_files = [] + print('{0} loaded'.format(self.name)) + + def set(self, **kwargs): + """Manually set some parameters of this module""" + + for key, value in kwargs.items(): + if key in self.__dict__: + setattr(self, key, value) + else: + print('{0} does not exist'.format(key)) + pass + + def get(self, **kwargs): + """Manually get some parameters of this module""" + + for key, value in kwargs.items(): + if key in self.__dict__: + getattr(self, key, value) + else: + print('{0} does not exist'.format(key)) + pass + + def get_options(self): + """Get all options which can be changed""" + + return self.__dict__ + + def generate_image(self): + """Generate image for this module""" + + # Define new image size with respect to padding + im_width = int(self.width - (self.width * 2 * self.padding_x)) + im_height = int(self.height - (self.height * 2 * self.padding_y)) + im_size = im_width, im_height + + logging.info('Image size: {0}'.format(im_size)) + + # Create an image for black pixels and one for coloured pixels + im_black = Image.new('RGB', size = im_size, color = self.background_colour) + im_colour = Image.new('RGB', size = im_size, color = 'white') + + # Allocate space for month-names, weekdays etc. + month_name_height = int(self.height*0.1) + weekdays_height = int(self.height*0.05) + + if self.show_events == True: + calendar_height = int(self.height*0.6) + events_height = int(self.height*0.25) + logging.debug('calendar-section size: {0} x {1} px'.format( + im_width, calendar_height)) + logging.debug('events-section size: {0} x {1} px'.format( + im_width, events_height)) + else: + calendar_height = self.height - month_name_height - weekday_height + logging.debug('calendar-section size: {0} x {1} px'.format( + im_width, calendar_height)) + + # Create grid and calculate icon sizes + calendar_rows, calendar_cols = 6, 7 + icon_width = self.width // calendar_cols + icon_height = calendar_height // calendar_rows + + # Calculate spacings for calendar area + x_spacing_calendar = int((self.width % icon_width) / 2) + y_spacing_calendar = int((self.height % calendar_rows) / 2) + + # Calculate positions for days of month + grid_start_y = (month_name_height + weekdays_height + y_spacing_calendar) + grid_start_x = x_spacing_calendar + + grid = [(grid_start_x + icon_width*x, grid_start_y + icon_height*y) + for y in range(calendar_rows) for x in range(calendar_cols)] + + weekday_pos = [(grid_start_x + icon_width*_, month_name_height) for _ in + range(calendar_cols)] + + + now = arrow.now(tz = self.timezone) + + # Set weekstart of calendar to specified weekstart + if self.weekstart == "Monday": + cal.setfirstweekday(cal.MONDAY) + weekstart = now.shift(days = - now.weekday()) + else: + cal.setfirstweekday(cal.SUNDAY) + weekstart = now.shift(days = - now.isoweekday()) + + # Write the name of current month + write( + im_black, + (x_spacing_calendar,0), + (self.width, month_name_height), + str(now.format('MMMM',locale=self.language)), + font = self.font, + autofit = True) + + # Set up weeknames in local language and add to main section + weekday_names = [weekstart.shift(days=+_).format('ddd',locale=self.language) + for _ in range(7)] + logging.debug('weekday names: {}'.format(weekday_names)) + + for _ in range(len(weekday_pos)): + write( + im_black, + weekday_pos[_], + (icon_width, weekdays_height), + weekday_names[_], + font = self.font, + autofit = True + ) + + # Create a calendar template and flatten (remove nestings) + flatten = lambda z: [x for y in z for x in y] + calendar_flat = flatten(cal.monthcalendar(now.year, now.month)) + + # Add the numbers on the correct positions + for i in range(len(calendar_flat)): + if calendar_flat[i] not in (0, int(now.day)): + write( + im_black, + grid[i], + (icon_width,icon_height), + str(calendar_flat[i]), + font = self.font, + ) + + # Draw a red/black circle with the current day of month in white + icon = Image.new('RGBA', (icon_width, icon_height)) + current_day_pos = grid[calendar_flat.index(now.day)] + x_circle,y_circle = int(icon_width/2), int(icon_height/2) + radius = int(icon_width * 0.25) + text_width, text_height = self.font.getsize(str(now.day)) + x_text = int((icon_width / 2) - (text_width / 2)) + y_text = int((icon_height / 2) - (text_height / 1.7)) + ImageDraw.Draw(icon).ellipse((x_circle-radius, y_circle-radius, + x_circle+radius, y_circle+radius), fill= 'black', outline=None) + ImageDraw.Draw(icon).text((x_text, y_text), str(now.day), fill='white', + font=self.font) + im_colour.paste(icon, current_day_pos, icon) + + # If events should be loaded and shown... + if self.show_events == True: + + # import the ical-parser + from ical_parser import icalendar + + # find out how many lines can fit at max in the event section + line_spacing = 0 + max_event_lines = events_height // (self.font.getsize('hg')[1] + + line_spacing) + + # generate list of coordinates for each line + event_lines = [(0, grid[-1][1] + int(events_height/max_event_lines*_)) + for _ in range(max_event_lines)] + + # timeline for filtering events within this month + month_start = arrow.get(now.floor('month')) + month_end = arrow.get(now.ceil('month')) + + # fetch events from given icalendars + parser = icalendar() + if self.ical_urls: + parser.load_url(self.ical_urls) + if self.ical_files: + parser.load_from_file(self.ical_files) + + # Filter events for full month (even past ones) for drawing event icons + month_events = parser.get_events(month_start, month_end) + parser.sort() + # parser.show_events() # uncomment to show events + + # find out on which days of this month events are taking place + days_with_events = [int(events['begin'].format('D')) for events in + month_events] + + # remove duplicates (more than one event in a single day) + list(set(days_with_events)).sort() + print('days with events:', days_with_events) + +## # calculate sizes for event-markers +## square_size = int(icon_width * 0.6) +## center_x = int((icon_width - square_size) / 2) +## center_y = int((icon_height - square_size) / 2) + + # Draw a border with specified parameters around days with events + for days in days_with_events: + draw_border( + im_colour, + grid[calendar_flat.index(days)], + (icon_width, icon_height), + radius = 4, + thickness= 1, + shrinkage = (0.4, 0.4) + ) + +## +## draw_square((int(grid[calendar_flat.index(days)][0]+center_x), +## int(grid[calendar_flat.index(days)][1] + center_y )), +## 8, square_size , square_size, colour='black') + + + + + # Filter upcoming events until 4 weeks in the future + parser.clear_events() + upcoming_events = parser.get_events(now, now.shift(weeks=4)) + parser.show_events() + + # delete events which won't be able to fit (more events than lines) + upcoming_events[max_event_lines:] + + + # Check if any events were found in the given timerange + if upcoming_events: + + # Find out how much space (width) the date format requires + fmt = self.event_format + lang = self.language + + date_width = int(max([self.font.getsize( + events['begin'].format(fmt,locale=lang))[0] + for events in upcoming_events]) * 1.05) + + line_height = self.font.getsize('hg')[1] + line_spacing + event_width = im_width - date_width + + # Display upcoming events below calendar + tomorrow = now.shift(days=1).floor('day') + in_two_days = now.shift(days=2).floor('day') + + # Write events and dates below calendar + # TODO: check if events all-day and then don't display time + + cursor = 0 + for event in upcoming_events: + name, date = event['title'], event['begin'].format(fmt, locale=lang) + print(date) + if now < event['end']: + write(im_colour, event_lines[cursor], (date_width, line_height), + date, font=self.font, alignment = 'left') + write(im_black, (date_width,event_lines[cursor][1]), + (event_width, line_height), name, font=self.font, + alignment = 'left') + cursor += 1 + else: + #leave section empty? or display ----- (dotted line) + pass + + +################################################################### +## Exception handling +################################################################# + + # Save image of black and colour channel in image-folder + im_black.save(images+self.name+'.png') + im_colour.save(images+self.name+'_colour.png') + +if __name__ == '__main__': + print('running {0} in standalone mode'.format( + os.path.basename(__file__).split('.py')[0])) diff --git a/inkycal/modules/inkycal_rss.py b/inkycal/modules/inkycal_rss.py index 13339a9..bc000d1 100644 --- a/inkycal/modules/inkycal_rss.py +++ b/inkycal/modules/inkycal_rss.py @@ -30,6 +30,7 @@ class rss: def __init__(self, section_size, section_config): """Initialize inkycal_rss module""" + self.name = os.path.basename(__file__).split('.py')[0] self.config = section_config self.width, self.height = section_size