about summary refs log tree commit diff
path: root/src/main.rs
blob: 9223a0bdbdd8a35947dc4c3c4c5e5295e9242ff9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
#![allow(linker_messages)]
#![deny(unused_imports)]
use crate::error::{ log_and_ignore_errors, Error, Result };
use crate::facility::{ FacilityMap, FacilityType };
use crate::geometry::{ Alignment, Corner, Rectangle, Side };
use crate::layout::Parcel;
use crate::module::{
  Module, CreatableModule,
  BatteryModule, I3ModeModule, TimeModule,
};
use crate::x::{
  Color,
  Connection, HasConnection, ConnectionExt,
  Display, HasDisplay, DisplayExt, DisplayColorExt,
  GraphicContext, GraphicContextExt,
  Window, HasWindow, WindowExt,
  X_CLOCKWISE_RIGHT_ANGLE,
};
use crate::x::geometry::{ RectangleExt, SideExt };
use crate::x::text::{ FontGraphicContext, FontList, Line };

use std::borrow::BorrowMut;
use std::process::ExitCode;
use std::sync::Arc;
use std::time::Duration;

use async_channel::{ Sender, Receiver };
use async_executor::StaticExecutor;
use async_lock::Mutex;
use futures_lite::future;
use xcb::{ Xid };
use xcb::x::{
  ClearArea,
  ClientMessageData,
  Gc, ChangeGc,
  Cw, CreateWindow,
  Drawable,
  EventMask,
  PolyFillArc, PolyFillRectangle,
  Screen,
  Visibility,
  WindowClass
};

mod error;
mod facility;
mod geometry;
mod layout;
mod module;
mod property_list;
mod unix;
mod x;
mod xdg;


static EXECUTOR: StaticExecutor = StaticExecutor::new();


struct DockConfiguration {
  thickness: u16,
  baseline_offset: i8,
  edge_inset: i8,
  intermodule_padding: i8,
  side: Side,
  background: Color,
  foreground: Color,
  use_rounded_inside_corners: bool,
  use_rounded_outside_corners: bool,
}

struct Dock {
  configuration: DockConfiguration,
  window: Window,
  is_visible: bool,
  bounds: Arc<Rectangle<u16>>,
  fonts: Arc<Mutex<FontList>>,
  baseline_position: i16,
  facilities: Arc<Mutex<FacilityMap>>,
  modules: Vec<(Arc<Mutex<Box<dyn Module>>>, ModuleFraming)>,
}

struct ModuleFraming {
  alignment: Alignment,
}

unsafe impl Send for Dock { }

impl HasWindow for Dock {
  fn window(&self) -> &Window { &self.window }
}


fn main() -> ExitCode {
  let (shutdown_sender, shutdown_receiver) = async_channel::unbounded();

  let n_extra_threads = std::thread::available_parallelism()
                            .map(|i| i.into()).unwrap_or(1);
  for _ in 0 .. n_extra_threads {
    let child_receiver = Receiver::clone(&shutdown_receiver);

    let _ = std::thread::spawn(move || {
      log_and_ignore_errors(future::block_on(
          EXECUTOR.run(child_receiver.recv())));
    });
  }

  future::block_on(async {
    if let Err(error) = async_main(shutdown_sender).await {
      error.log();
      println!("That means... we are released from our task. Fare well.");
      ExitCode::FAILURE
    } else { ExitCode::SUCCESS }
  })
}


async fn async_main(_shutdown_sender: Sender<()>) -> Result<()> {
  let display = Arc::new(Display::new()?);
  let configuration = DockConfiguration::new(&display)?;
  let dock = Dock::new(Arc::clone(&display), configuration).await?;

  let (redraw_sender, redraw_receiver) = async_channel::unbounded();
  let event_task = EXECUTOR.spawn(
          event_loop(display, Arc::clone(&dock),
                     Sender::clone(&redraw_sender)));

  let (sleep_sender, sleep_receiver) = async_channel::unbounded();
  let sleep_task = EXECUTOR.spawn(sleep_loop(sleep_receiver, redraw_sender));

  /*   Since we declared Dock as Send, we could do this on another
   * thread, but it's easier to do it on the primary one.
   */
  redraw_loop(dock, redraw_receiver, sleep_sender).await?;

  event_task.cancel().await;
  sleep_task.cancel().await;

  Ok(())
}


impl DockConfiguration {
  fn new(display: &Arc<Display>) -> Result<DockConfiguration> {
    // #d4ffcc
    let background = display.allocate_color(54484, 65535, 52428)?;

    // #5c01be
    let foreground = display.allocate_color(23644, 257, 48830)?;

    Ok(DockConfiguration {
      thickness: 34,
      baseline_offset: 2,
      edge_inset: 12,
      intermodule_padding: 24,
      side: Side::Bottom,
      background, foreground,
      use_rounded_inside_corners: false,
      use_rounded_outside_corners: true,
    })
  }
}


impl Dock {
  async fn new(display: Arc<Display>, configuration: DockConfiguration)
    -> Result<Arc<Mutex<Dock>>>
  {
    let screen = display.screen();

    let dock_bounds = Dock::compute_bounds(&screen, &configuration);

    let window = Window::new(Arc::clone(&display), &mut CreateWindow {
      depth: xcb::x::COPY_FROM_PARENT as u8,
      wid: xcb::x::Window::none(),
      parent: screen.root(),
      x: dock_bounds.left as i16,
      y: dock_bounds.top as i16,
      width: dock_bounds.width,
      height: dock_bounds.height,
      border_width: 0,
      class: WindowClass::InputOutput,
      visual: screen.root_visual(),
      value_list: &[
        Cw::BackPixel(configuration.background.as_pixel()),
        Cw::EventMask(EventMask::EXPOSURE
                      | EventMask::VISIBILITY_CHANGE
                      | EventMask::BUTTON_PRESS),
      ],
    })?;

    let fonts = Arc::new(Mutex::new(FontList::new(Arc::clone(&display))?));
    fonts.lock().await.append(
        "FantasqueSansM Nerd Font Mono:style=Regular:size=18")?;
    fonts.lock().await.append("Symbola:size=18")?;
    fonts.lock().await.append("Sazanami Mincho:size=18")?;

    let primary_font = fonts.lock().await.primary_font()?;
    let font_height = primary_font.ascent() + primary_font.descent();
    let vertical_padding = (dock_bounds.height - font_height) / 2;
    let baseline_position = primary_font.ascent() as i16
                            + vertical_padding as i16
                            + configuration.baseline_offset as i16;

    let mut required_facilities = FacilityType::empty();
    required_facilities |= I3ModeModule::REQUIRED_FACILITIES;
    required_facilities |= BatteryModule::REQUIRED_FACILITIES;
    required_facilities |= TimeModule::REQUIRED_FACILITIES;

    let facilities = Arc::new(Mutex::new(FacilityMap::new()));
    for facility_type in required_facilities.iter() {
      facilities.lock().await.insert(facility_type.clone(),
                                facility_type.new(&EXECUTOR).await?);
    }

    let mut modules = Vec::new();
    {
      let mut facilities = facilities.lock().await;

      modules.push((Arc::new(Mutex::new(TimeModule::new(
                        facilities.borrow_mut())?.as_box())),
                    ModuleFraming
      {
        alignment: Alignment::Right,
      }));

      modules.push((Arc::new(Mutex::new(BatteryModule::new(
                        facilities.borrow_mut())?.as_box())),
                    ModuleFraming
      {
        alignment: Alignment::Right,
      }));

      modules.push((Arc::new(Mutex::new(I3ModeModule::new(
                        facilities.borrow_mut())?.as_box())),
                    ModuleFraming
      {
        alignment: Alignment::Left,
      }));
    }

    /*   We start is_visible at false. Since redraw events set it to true, this
     * won't make us miss any drawing.
     */
    let dock = Dock {
      window, configuration,
      is_visible: false,
      bounds: Arc::new(dock_bounds),
      fonts,
      baseline_position,
      facilities,
      modules,
    };

    dock.set_string_property(&xcb::x::ATOM_WM_NAME, b"sandbar")?;

    dock.set_atom_property(&dock.atoms().wm_protocols,
                           &[dock.atoms().wm_delete_window])?;

    dock.set_atom_property(&dock.atoms().wm_type,
                           &[dock.atoms().wm_type_dock])?;

    dock.set_strut_properties(&screen)?;

    dock.map_window()?;

    Ok(Arc::new(Mutex::new(dock)))
  }


  fn set_strut_properties(&self, screen: &Screen) -> Result<()> {
    let atoms = self.atoms();

    let thickness = self.configuration.thickness as u32;

    let strut_values = match self.configuration.side {
      Side::Left => &[thickness, 0 as u32, 0 as u32, 0 as u32],
      Side::Right => &[0 as u32, thickness, 0 as u32, 0 as u32],
      Side::Top => &[0 as u32, 0 as u32, thickness, 0 as u32],
      Side::Bottom => &[0 as u32, 0 as u32, 0 as u32, thickness],
    };
    self.set_cardinal_property(&atoms.wm_strut, strut_values)?;

    let strut_partial_values = &[
      strut_values[0],
      strut_values[1],
      strut_values[2],
      strut_values[3],

      0 as u32,
      if self.configuration.side == Side::Left {
        screen.height_in_pixels() as u32
      } else { 0 as u32 },

      0 as u32,
      if self.configuration.side == Side::Right {
        screen.height_in_pixels() as u32
      } else { 0 as u32 },

      0 as u32,
      if self.configuration.side == Side::Top {
        screen.width_in_pixels() as u32
      } else { 0 as u32 },

      0 as u32,
      if self.configuration.side == Side::Bottom {
        screen.width_in_pixels() as u32
      } else { 0 as u32 },
    ];

    self.set_cardinal_property(&atoms.wm_strut_partial,
                               strut_partial_values)?;

    Ok(())
  }


  fn compute_bounds(screen: &Screen, configuration: &DockConfiguration)
    -> Rectangle<u16>
  {
    if configuration.side == Side::Top
       || configuration.side == Side::Bottom
    {
      let left = 0;
      let width = screen.width_in_pixels();
      let height = configuration.thickness;

      let top = if configuration.side == Side::Bottom {
        screen.height_in_pixels() - height
      } else { 0 };

      Rectangle { left, top, width, height }
    } else {
      let top = 0;
      let height = screen.height_in_pixels();
      let width = configuration.thickness;

      let left = if configuration.side == Side::Right {
        screen.width_in_pixels() - width
      } else { 0 };

      Rectangle { left, top, width, height }
    }
  }


  async fn redraw(&self) -> Result<Option<Duration>> {
    let drawable = Drawable::Window(self.window_id());
    let context = GraphicContext::new(
                      Arc::clone(self.display()), drawable)?;

    self.erase_all()?;

    if self.configuration.use_rounded_inside_corners
       || self.configuration.use_rounded_outside_corners
    {
      self.draw_corners(drawable, &context)?;
    }

    let mut open_parcel = Parcel {
      left: self.bounds.left as u32
            + self.configuration.edge_inset as u32,
      right: (self.bounds.left + self.bounds.width) as u32
             - self.configuration.edge_inset as u32,
    };

    self.draw_text("playful cool fic tech nonfic",
                   &mut open_parcel, Alignment::Left)?;

    {
      let mut facilities = self.facilities.lock().await;

      /*   Before we handle any modules, we update all the facilities. This is
       * the easy way to make sure each facility gets updated exactly once per
       * frame; making it the modules' responsibility would be more
       * bookkeeping, to no purpose.
       */
      for facility in facilities.iter_mut() {
        facility.update()?;
      }

      for (module, framing) in &self.modules {
        let text = {
          let mut module = module.lock().await;

          let text = module.format(facilities.borrow_mut())?;

          /*   We do this after calling format(), rather than before, to give
           * the module a chance to decide whether it's shy. Thus, for example,
           * hot-plugging the only battery will make the Battery module appear
           * or disappear on the very next redraw, which will likely exceed the
           * user's expectation of slickness.
           */
          if !module.is_visible() { continue; }

          text
        };

        self.draw_text(&text, &mut open_parcel, framing.alignment)?;
      }
    }

    let mut shortest_duration = None;
    for (module, _) in &self.modules {
      let next_duration = module.lock().await.sleep_duration();
      shortest_duration = shorter_duration(shortest_duration, next_duration);
    }

    Ok(shortest_duration)
  }


  fn erase_all(&self) -> Result<()> {
    let cookie = self.send_request_checked(&ClearArea {
      exposures: false,
      window: self.window().window_id(),
      x: 0,
      y: 0,
      width: self.bounds.width,
      height: self.bounds.height,
    });
    self.check_request(cookie)?;

    Ok(())
  }


  fn draw_corners(&self, drawable: Drawable, context: &GraphicContext)
    -> Result<()>
  {
    let black_pixel = self.screen().black_pixel();

    let mut corner_squares = Vec::new();
    let mut corner_arcs = Vec::new();
    if self.configuration.use_rounded_outside_corners {
      for corner in self.configuration.side.corners_on_side() {
        let (corner_square, corner_arc) = self.compute_corner_regions(*corner);

        corner_squares.push(corner_square);
        corner_arcs.push(corner_arc);
      }
    }
    if self.configuration.use_rounded_inside_corners {
      for corner in self.configuration.side.opposite().corners_on_side() {
        let (corner_square, corner_arc) = self.compute_corner_regions(*corner);

        corner_squares.push(corner_square);
        corner_arcs.push(corner_arc);
      }
    }

    let cookie = self.send_request_checked(&ChangeGc {
      gc: context.graphic_context_id(),
      value_list: &[
        Gc::Foreground(black_pixel),
      ],
    });
    self.check_request(cookie)?;

    let cookie = self.send_request_checked(&PolyFillRectangle {
      drawable: drawable,
      gc: context.graphic_context_id(),
      rectangles: &corner_squares,
    });
    self.check_request(cookie)?;

    let cookie = self.send_request_checked(&ChangeGc {
      gc: context.graphic_context_id(),
      value_list: &[
        Gc::Foreground(self.configuration.background.as_pixel()),
      ],
    });
    self.check_request(cookie)?;

    let cookie = self.send_request_checked(&PolyFillArc {
      drawable: drawable,
      gc: context.graphic_context_id(),
      arcs: &corner_arcs,
    });
    self.check_request(cookie)?;

    Ok(())
  }


  fn compute_corner_regions(&self, corner: Corner)
    -> (xcb::x::Rectangle, xcb::x::Arc)
  {
    let radius = self.configuration.thickness / 2;
    let diameter = self.configuration.thickness;

    let bounds = &self.bounds;

    let corner_square = bounds.corner_square(corner, radius)
                              .to_x_rectangle();

    let angle1 = corner.first_clockwise_side().to_x_angle();
    let corner_arc = bounds.corner_square(corner, diameter)
                           .to_x_arc(angle1, X_CLOCKWISE_RIGHT_ANGLE);

    (corner_square, corner_arc)
  }


  fn draw_text(&self, text: &str,
               open_parcel: &mut Parcel, alignment: Alignment)
    -> Result<()>
  {
    let context = FontGraphicContext::new(self.window())?;
    let color = &self.configuration.foreground;

    let mut line = Line::new(Arc::clone(&self.fonts))?;
    line.append_text(text)?;

    line.layout_and_draw(open_parcel, alignment, &context, color,
                         self.baseline_position)?;

    match alignment {
      Alignment::Left => {
        open_parcel.left += self.configuration.intermodule_padding as u32;
      }
      Alignment::Right => {
        open_parcel.right -= self.configuration.intermodule_padding as u32;
      }
    }

    Ok(())
  }
}

impl HasDisplay for Dock {
  fn display(&self) -> &Arc<Display> { self.window.display() }
}

impl HasConnection for Dock {
  fn connection(&self) -> &Connection { self.window.connection() }
}


async fn event_loop(display: Arc<Display>,
                    dock: Arc<Mutex<Dock>>,
                    redraw_sender: Sender<()>)
{
  loop {
    match display.wait_for_event() {
      result@Err(_) => log_and_ignore_errors(result),

      Ok(xcb::Event::X(xcb::x::Event::Expose(_event))) => {
        dock.lock().await.is_visible = true;

        log_and_ignore_errors(redraw_sender.send(()).await);
      }

      Ok(xcb::Event::X(xcb::x::Event::VisibilityNotify(event))) => {
        let mut dock = dock.lock().await;

        if event.window() == dock.window.window_id() {
          dock.is_visible = event.state() != Visibility::FullyObscured;

          /*   We don't initiate a redraw here, instead waiting for the
           * redraw event.
           */
        }
      }

      Ok(xcb::Event::X(xcb::x::Event::ButtonPress(event))) => {
        println!("click {:?}", event);
      }

      Ok(xcb::Event::X(xcb::x::Event::ClientMessage(event))) => {
        if let ClientMessageData::Data32([atom, ..]) = event.data() {
          if atom == display.atoms().wm_delete_window.resource_id() {
            break;
          }
        }
      }

      Ok(event) => { println!("unknown event {:?}", event); }
    }
  }
}


async fn sleep_loop(sleep_receiver: Receiver<Duration>,
                    redraw_sender: Sender<()>)
{
  loop {
    if let Ok(duration) = sleep_receiver.recv().await {
      std::thread::sleep(duration);

      /*   If it's not visible, the redraw loop will skip the actual redraw, so
       * we don't need to worry at this end.
       */
      log_and_ignore_errors(redraw_sender.send(()).await);
    } else { break }
  }
}


async fn redraw_loop(dock: Arc<Mutex<Dock>>,
                     redraw_receiver: Receiver<()>,
                     sleep_sender: Sender<Duration>)
  -> Result<()>
{
  loop {
    if let Ok(()) = redraw_receiver.recv().await {
      let duration = {
        let dock = dock.lock().await;

        if !dock.is_visible { continue }

        match dock.redraw().await {
          Ok(Some(duration)) => {
            if let Err(error) = dock.connection().flush() {
              Into::<Error>::into(error).log();
            }

            Some(duration)
          }
          Ok(None) => None,
          result@Err(_) => {
            log_and_ignore_errors(result);
            None
          }
        }
      };

      if let Some(duration) = duration {
        log_and_ignore_errors(sleep_sender.send(duration).await);
      }
    } else { break }
  }

  Ok(())
}



fn shorter_duration(a: Option<Duration>, b: Option<Duration>)
  -> Option<Duration>
{
  if let Some(a_value) = a {
    if let Some(b_value) = b
       && b_value < a_value
    { b } else { a }
  } else { b }
}