/* * Clock * ----- * Digital clock program written using GraphApp. * * This is a complex example which demonstrates the use of * timer functions, fonts, and windows. It also uses some * standard C time functions. */ #include #include #include window the_window; font the_font; int state = 0; /* 0 = show the time, 1 = show the date */ int hour = -1, minute = -1; int day = -1, month = -1; char *month_name[] = { "", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; void draw_clock(window w, rect r) { int width, height; char the_string[80]; if (state == 0) sprintf(the_string, "%d:%2.2d", hour, minute); else sprintf(the_string, "%d %3.3s", day, month_name[month]); setfont(the_font); width = strwidth(the_font, the_string); height = getascent(the_font); /* numbers are upper-case */ drawstr(pt((r.width-width)/2, (r.height-height)/2-2), the_string); } void update_clock(void *w) { struct tm *the_time; time_t seconds; int newhour, newminute, newday, newmonth; tzset(); time(&seconds); the_time = localtime(&seconds); newhour = the_time->tm_hour; if (newhour > 12) newhour -= 12; newminute = the_time->tm_min; newday = the_time->tm_mday; newmonth = the_time->tm_mon + 1; if ((hour != newhour) || (minute != newminute) || (day != newday) || (month != newmonth)) { hour = newhour; minute = newminute; day = newday; month = newmonth; redraw(the_window); } } void handle_mouse(window w, int buttons, point xy) { if (buttons && !state) { state = 1; redraw(the_window); } else if (!buttons && state) { state = 0; redraw(the_window); } } void handle_keys(window w, int key) { if ((key == ESC) || (key == DEL) || (key == 'q') || (key == 'Q')) exitapp(); } void main(void) { the_font = newfont("Helvetica", SansSerif + Bold, 22); the_window = newwindow("Clock", rect(50,0,strwidth(the_font,"HH:MM."),16), Floating | TrackMouse); setredraw(the_window, draw_clock); setbackground(the_window, LightGrey); setmouseup(the_window, handle_mouse); setmousedown(the_window, handle_mouse); setkeydown(the_window, handle_keys); setkeyaction(the_window, handle_keys); update_clock(the_window); show(the_window); settimerfn(update_clock, the_window); settimer(15000); /* 15 second timer */ mainloop(); }