widgets.rs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. use crate::window::Size;
  2. use pango::LayoutExt;
  3. #[derive(Debug,Clone,Copy)]
  4. pub enum Located {
  5. FromLeft(i32),
  6. FromRight(i32),
  7. }
  8. pub struct Config<'r> {
  9. pub left: Vec<&'r Widget>,
  10. pub right: Vec<&'r Widget>,
  11. }
  12. impl<'r> Config<'r> {
  13. pub fn draw(&self, d: &Drawing) {
  14. let mut offset = 10;
  15. for w in self.left.iter() {
  16. offset += 10 + w.draw(d, Located::FromLeft(offset));
  17. }
  18. offset = 10;
  19. for w in self.right.iter() {
  20. offset += 10 + w.draw(d, Located::FromRight(offset));
  21. }
  22. }
  23. }
  24. impl Located {
  25. fn draw_text(&self, d: &Drawing, msg: &str) -> i32 {
  26. d.lyt.set_text(msg);
  27. let (w, _) = d.lyt.get_size();
  28. d.ctx.move_to(self.target_x(d, w / pango::SCALE), 4.0);
  29. pangocairo::functions::show_layout(d.ctx, d.lyt);
  30. w / pango::SCALE
  31. }
  32. fn target_x(&self, d: &Drawing, w: i32) -> f64 {
  33. match self {
  34. Located::FromLeft(x) => *x as f64,
  35. Located::FromRight(x) => (d.size.wd - (x + w)) as f64,
  36. }
  37. }
  38. }
  39. pub struct Drawing<'t> {
  40. pub ctx: &'t cairo::Context,
  41. pub lyt: &'t pango::Layout,
  42. pub size: Size,
  43. }
  44. pub trait Widget {
  45. fn draw(&self, d: &Drawing, loc: Located) -> i32;
  46. }
  47. #[derive(Debug)]
  48. pub struct Time {
  49. fmt: String,
  50. }
  51. impl Time {
  52. pub fn new() -> Time {
  53. Time {
  54. fmt: format!("%a %b %d %H:%M")
  55. }
  56. }
  57. }
  58. impl Widget for Time {
  59. fn draw(&self, d: &Drawing, loc: Located) -> i32 {
  60. let now = time::now();
  61. loc.draw_text(d, &time::strftime(&self.fmt, &now).unwrap())
  62. }
  63. }
  64. #[derive(Debug)]
  65. pub struct Text<'t> {
  66. text: &'t str,
  67. }
  68. impl<'t> Text<'t> {
  69. pub fn new(text: &str) -> Text {
  70. Text { text }
  71. }
  72. }
  73. impl<'t> Widget for Text<'t> {
  74. fn draw(&self, d: &Drawing, loc: Located) -> i32 {
  75. loc.draw_text(d, &self.text)
  76. }
  77. }
  78. pub struct SmallBox;
  79. impl Widget for SmallBox {
  80. fn draw(&self, d: &Drawing, loc: Located) -> i32 {
  81. let sz = d.size.ht - 8;
  82. let x = loc.target_x(d, sz);
  83. d.ctx.rectangle(x, 4.0, sz as f64, sz as f64);
  84. d.ctx.fill();
  85. sz
  86. }
  87. }