clock.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. #include <u.h>
  2. #include <libc.h>
  3. #include <draw.h>
  4. #include <event.h>
  5. Image *hrhand, *minhand;
  6. Image *dots, *back;
  7. Point
  8. circlept(Point c, int r, int degrees)
  9. {
  10. double rad;
  11. rad = (double) degrees * PI/180.0;
  12. c.x += cos(rad)*r;
  13. c.y -= sin(rad)*r;
  14. return c;
  15. }
  16. void
  17. redraw(Image *screen)
  18. {
  19. static int tm, ntm;
  20. static Rectangle r;
  21. static Point c;
  22. static int rad;
  23. static Image *im;
  24. int i;
  25. int anghr, angmin;
  26. static Tm tms;
  27. static Tm ntms;
  28. ntm = time(0);
  29. if(ntm == tm && eqrect(screen->r, r))
  30. return;
  31. ntms = *localtime(ntm);
  32. anghr = 90-(ntms.hour*5 + ntms.min/12)*6;
  33. angmin = 90-ntms.min*6;
  34. tm = ntm;
  35. tms = ntms;
  36. r = screen->r;
  37. c = divpt(addpt(r.min, r.max), 2);
  38. rad = Dx(r) < Dy(r) ? Dx(r) : Dy(r);
  39. rad /= 2;
  40. rad -= 8;
  41. draw(screen, screen->r, back, nil, ZP);
  42. for(i=0; i<12; i++)
  43. fillellipse(screen, circlept(c, rad, i*(360/12)), 2, 2, dots, ZP);
  44. line(screen, c, circlept(c, (rad*3)/4, angmin), 0, 0, 1, minhand, ZP);
  45. line(screen, c, circlept(c, rad/2, anghr), 0, 0, 1, hrhand, ZP);
  46. flushimage(display, 1);
  47. }
  48. void
  49. eresized(int new)
  50. {
  51. if(new && getwindow(display, Refnone) < 0)
  52. fprint(2,"can't reattach to window");
  53. redraw(screen);
  54. }
  55. void
  56. main(int, char**)
  57. {
  58. Event e;
  59. Mouse m;
  60. Menu menu;
  61. char *mstr[] = {"exit", 0};
  62. int key, timer;
  63. int t;
  64. if (initdraw(0, 0, "clock") < 0)
  65. sysfatal("initdraw failed");
  66. back = allocimagemix(display, DPalebluegreen, DWhite);
  67. hrhand = allocimage(display, Rect(0,0,1,1), CMAP8, 1, DDarkblue);
  68. minhand = allocimage(display, Rect(0,0,1,1), CMAP8, 1, DPaleblue);
  69. dots = allocimage(display, Rect(0,0,1,1), CMAP8, 1, DBlue);
  70. redraw(screen);
  71. einit(Emouse);
  72. t = (30*1000);
  73. timer = etimer(0, t);
  74. menu.item = mstr;
  75. menu.lasthit = 0;
  76. for(;;) {
  77. key = event(&e);
  78. if(key == Emouse) {
  79. m = e.mouse;
  80. if(m.buttons & 4) {
  81. if(emenuhit(3, &m, &menu) == 0)
  82. exits(0);
  83. }
  84. } else if(key == timer) {
  85. redraw(screen);
  86. }
  87. }
  88. }