about summary refs log tree commit diff
path: root/src/main.rs
blob: bf0dfda7c5fdfa62a4417cd609e11ebd9a915157 (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
#![allow(linker_messages)]
use crate::error::*;
use crate::geometry::*;
use crate::modules::*;
use crate::x::*;

use std::num::NonZero;
use std::process::ExitCode;
use std::sync::Arc;
use std::sync::Mutex;
use std::time::Duration;

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

mod error;
mod geometry;
mod modules;
mod x;


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


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

struct Dock {
  configuration: DockConfiguration,
  window: Window,
  bounds: Arc<Rectangle<u16>>,
  font: Arc<Font>,
  baseline_position: i16,
  time_module: Arc<Mutex<TimeModule>>,
}

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)?;

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

  /*   Recall that Dock is non-Send, because it holds pointers to xft
   * state, which are opaque from our perspective. Thus, we have to do
   * this on the primary thread.
   *
   *   Or we could Mutex-ify everything, but this is simpler.
   */
  redraw_loop(dock, redraw_sender, redraw_receiver).await;

  event_task.cancel();

  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,
      side: Side::Bottom,
      background, foreground,
      use_rounded_inside_corners: false,
      use_rounded_outside_corners: true,
    })
  }
}


impl Dock {
  fn new(display: Arc<Display>, configuration: DockConfiguration)
    -> Result<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::BUTTON_PRESS),
      ],
    })?;

    let font = Font::new(Arc::clone(&display),
        "FantasqueSansM Nerd Font Mono:style=Regular:size=18")?;

    let font_height = font.ascent() + font.descent();
    let vertical_padding = (dock_bounds.height - font_height) / 2;
    let baseline_position = font.ascent() as i16
                            + vertical_padding as i16
                            + configuration.baseline_offset as i16;

    let time_module = TimeModule::new();

    let dock = Dock {
      window, configuration,
      bounds: Arc::new(dock_bounds),
      font,
      baseline_position,
      time_module,
    };

    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(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)?;

    let foo = self.erase_all()?;
    println!("{:?}", foo);

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

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

    let time = self.time_module.lock()?.format();
    self.draw_text(&time, Alignment::Right)?;

    let mut shortest_duration = None;

    let next_duration = self.time_module.lock()?.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 {
      // TODO load-bearing...
      exposures: true,
      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, alignment: Alignment) -> Result<()> {
    let context = FontGraphicContext::new(self.window())?;
    let color = &self.configuration.foreground;
    let text = self.font.text_span(text)?;

    let mut location = Point::<i32>::zero();
    location.x += text.draw_offset().x as i32;
    location.y += self.baseline_position as i32;

    match alignment {
      Alignment::Left => {
        location.x += self.configuration.edge_inset as i32;
      }
      Alignment::Right => {
        location.x += self.bounds.width as i32 - text.draw_size().width as i32;
        location.x -= self.configuration.edge_inset as i32;
      }
    }

    text.draw(&context, color, location)?;

    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>, sender: Sender<()>) {
  loop {
    println!("waiting for event");
    match display.wait_for_event() {
      result@Err(_) => log_and_ignore_errors(result),

      Ok(xcb::Event::X(xcb::x::Event::Expose(_event))) => {
        log_and_ignore_errors(sender.send(()).await);
      }

      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 redraw_loop(dock: Dock,
                     redraw_sender: Sender<()>,
                     redraw_receiver: Receiver<()>)
{
  loop {
    println!("awaiting redraw notification");
    if let Ok(()) = redraw_receiver.recv().await {
      match dock.redraw().await {
        Ok(Some(duration)) => {
          if let Err(error) = dock.connection().flush() {
	    Into::<Error>::into(error).log();
	  }
          println!("sleeping");
          std::thread::sleep(duration);
	  // TODO
          //redraw_sender.send(()).await;
        }
        Ok(None) => { }
        result@Err(_) => log_and_ignore_errors(result)
      }
    } else { break }
  }
}



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 }
}