hyprshell-windows-lib 4.10.0

A modern GTK4-based window switcher and application launcher for Hyprland
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
use core_lib::Direction;
use core_lib::{
    Active, ClientData, ClientId, GetFirstOrLast, HyprlandData, RevIf, WorkspaceData, WorkspaceId,
};
use std::cmp::{max, min};
use tracing::{debug, instrument, trace, trace_span, warn};

pub fn find_next_workspace(
    direction: &Direction,
    wrap: bool,
    hypr_data: &HyprlandData,
    active: Active,
    workspaces_per_row: u8,
) -> Active {
    let _span = trace_span!("find_next_workspace", direction = ?direction, wrap = wrap, active = ?active, workspaces_per_row = workspaces_per_row).entered();

    if hypr_data.workspaces.is_empty() {
        debug!("No workspaces available, returning None");
        return active;
    }
    let filtered = hypr_data
        .workspaces
        .iter()
        .filter(|(_, data)| data.any_client_enabled)
        .collect::<Vec<_>>();
    if filtered.len() == 1 {
        trace!("Only one workspaces available, returning current workspaces");
        let workspaces = &hypr_data.workspaces[0];
        return Active {
            client: None,
            workspace: workspaces.0,
            monitor: workspaces.1.monitor,
        };
    }
    let current = filtered
        .iter()
        .position(|(id, _)| *id == active.workspace)
        .unwrap_or_else(|| {
            warn!("Active workspace not found in workspaces, returning first workspace");
            0
        });

    let index = find_next_grid(direction, wrap, filtered.len(), current, workspaces_per_row);
    #[allow(clippy::map_unwrap_or)]
    let next_active = filtered
        .get(index)
        .map(|(id, data)| Active {
            client: None,
            workspace: *id,
            monitor: data.monitor,
        })
        .unwrap_or_else(|| {
            warn!("Unable to find next workspace, returning current workspace");
            active
        });
    // .expect("unable to find next workspace!");
    trace!("Next active: {next_active:?}");
    next_active
}

#[instrument(
    level = "trace",
    skip_all,
    ret,
    fields(direction = ?direction, wrap = wrap, active = ?active, clients_per_row = clients_per_row)
)]
pub fn find_next_client(
    direction: &Direction,
    wrap: bool,
    hypr_data: &HyprlandData,
    active: Active,
    clients_per_row: u8,
) -> Active {
    if hypr_data.clients.is_empty() {
        debug!("No clients available, returning None");
        return active;
    }

    #[allow(clippy::option_if_let_else)]
    let next_active = match active.client {
        None => find_first_client(direction, &hypr_data.clients, &hypr_data.workspaces, active),
        Some(client_id) => {
            let filtered = hypr_data
                .clients
                .iter()
                .filter(|(_, data)| data.enabled)
                .collect::<Vec<_>>();
            if filtered.len() == 1 {
                trace!("Only one client available, returning current client");
                let client = &hypr_data.clients[0];
                return Active {
                    client: Some(client.0),
                    workspace: client.1.workspace,
                    monitor: client.1.monitor,
                };
            }
            let current = filtered
                .iter()
                .position(|(id, _)| *id == client_id)
                .unwrap_or(0);
            let index = find_next_grid(direction, wrap, filtered.len(), current, clients_per_row);
            #[allow(clippy::map_unwrap_or)]
            filtered
                .get(index)
                .map(|(id, data)| Active {
                    client: Some(*id),
                    workspace: data.workspace,
                    monitor: data.monitor,
                })
                .unwrap_or_else(|| {
                    warn!("Unable to find next client, returning current client");
                    active
                })
        }
    };

    trace!("Next active: {next_active:?}");
    next_active
}

#[allow(clippy::cast_possible_wrap)] // wrapping wont happen here, number of workspaces or clients are way lower than isize::MAX
// #[instrument(level = "trace", skip_all, ret, fields(len = filtered_len, current = current))]
fn find_next_grid(
    direction: &Direction,
    wrap: bool,
    filtered_len: usize,
    current: usize,
    items_per_row: u8,
) -> usize {
    let _span = trace_span!("find_next_grid", len = filtered_len, current = current).entered();

    let i_per_row = isize::from(items_per_row);
    let items_per_row = usize::from(items_per_row);
    let offset = match direction {
        Direction::Right => 1,
        Direction::Left => -1,
        Direction::Up => -i_per_row,
        Direction::Down => i_per_row,
    };
    trace!("Finding next workspace with offset: {}", offset);
    let index = if wrap {
        let mut index = current as isize + offset;
        if index >= filtered_len as isize {
            trace!("Index out of bounds, wrapping around {index}");
            // subtract all rows / move to the beginning
            index -= (items_per_row * usize::div_ceil(filtered_len - 1, items_per_row)) as isize;
            if index < 0 {
                match direction {
                    Direction::Right => index = 0,
                    Direction::Down => {
                        index += i_per_row;
                    }
                    _ => unreachable!(),
                }
            }
        } else if index < 0 {
            trace!("Index out of bounds, wrapping around {index}");
            // add all rows / move to end
            index += (items_per_row * usize::div_ceil(filtered_len - 1, items_per_row)) as isize;
            if index >= filtered_len as isize {
                match direction {
                    Direction::Left => {
                        index = filtered_len as isize - 1;
                    }
                    Direction::Up => {
                        index -= i_per_row;
                    }
                    _ => unreachable!(),
                }
            }
        }
        #[allow(clippy::cast_sign_loss)] // index always positive, see if else above
        {
            index as usize
        }
    } else {
        #[allow(clippy::cast_sign_loss)]
        // max(current as isize + offset, 0) always positive (max function)
        {
            min(max(current as isize + offset, 0) as usize, filtered_len - 1)
        }
    };
    trace!("Next index: {index}");
    index
}

fn find_first_client(
    direction: &Direction,
    clients: &[(ClientId, ClientData)],
    workspaces: &[(WorkspaceId, WorkspaceData)],
    active: Active,
) -> Active {
    let get_last = matches!(direction, Direction::Left | Direction::Up);
    let (id, next) = clients
        .iter()
        .filter(|(_, c)| c.workspace == active.workspace && c.enabled)
        .get_first_or_last(get_last)
        .unwrap_or_else(|| {
            trace!("No client found in current workspace, looking for next client in workspaces");
            workspaces
                .iter()
                .reverse_if(get_last)
                .skip_while(|(id, _)| id != &active.workspace)
                .find_map(|(id, _)| {
                    trace!("Finding first client in workspace {id:?}");
                    clients
                        .iter()
                        .filter(|(_, c)| c.workspace == *id && c.enabled)
                        .get_first_or_last(get_last)
                })
                .unwrap_or_else(|| {
                    clients
                        .iter()
                        .filter(|(_, c)| c.monitor == active.monitor)
                        .get_first_or_last(get_last)
                        .unwrap_or_else(|| {
                            clients
                                .iter()
                                .get_first_or_last(get_last)
                                .expect("clients contain at least two clients")
                        })
                })
        });
    Active {
        client: Some(*id),
        workspace: next.workspace,
        monitor: next.monitor,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[allow(clippy::type_complexity)]
    fn create_test_data(
        client_count: usize,
        workspace_count: usize,
        enabled: Option<usize>,
    ) -> (
        Vec<(ClientId, ClientData)>,
        Vec<(WorkspaceId, WorkspaceData)>,
    ) {
        let clients: Vec<(ClientId, ClientData)> = (0..client_count)
            .map(|i| {
                (
                    i as ClientId,
                    ClientData {
                        x: 0,
                        y: 0,
                        width: 0,
                        height: 0,
                        class: String::new(),
                        title: String::new(),
                        #[allow(clippy::cast_possible_wrap)]
                        workspace: (i % workspace_count) as WorkspaceId,
                        monitor: 0,
                        focus_history_id: 0,
                        floating: false,
                        #[allow(clippy::map_unwrap_or)]
                        enabled: enabled.map(|s| s >= i).unwrap_or(true),
                        pid: 0,
                    },
                )
            })
            .collect();

        #[allow(clippy::cast_possible_wrap)]
        let workspaces: Vec<(WorkspaceId, WorkspaceData)> = (0..workspace_count)
            .map(|i| {
                (
                    i as WorkspaceId,
                    WorkspaceData {
                        name: String::new(),
                        width: 0,
                        height: 0,
                        monitor: 0,
                        any_client_enabled: clients
                            .iter()
                            .any(|(_, c)| c.workspace == i as WorkspaceId && c.enabled),
                    },
                )
            })
            .collect();

        (clients, workspaces)
    }

    #[test_log::test]
    #[test_log(default_log_filter = "trace")]
    fn test_find_next_workspace_0() {
        let (clients, workspaces) = create_test_data(0, 0, None);
        let hypr_data = HyprlandData {
            clients,
            workspaces,
            monitors: vec![],
        };
        let active = Active {
            client: None,
            workspace: 0,
            monitor: 0,
        };
        trace!("data: {hypr_data:?}");

        assert_eq!(
            find_next_workspace(&Direction::Right, true, &hypr_data, active, 3),
            active
        );
        assert_eq!(
            find_next_workspace(&Direction::Left, true, &hypr_data, active, 6),
            active
        );
        assert_eq!(
            find_next_workspace(&Direction::Up, false, &hypr_data, active, 200),
            active
        );
        assert_eq!(
            find_next_workspace(&Direction::Down, false, &hypr_data, active, 0),
            active
        );
    }

    #[test_log::test]
    #[test_log(default_log_filter = "trace")]
    fn test_find_next_workspace_1_filter() {
        let (clients, workspaces) = create_test_data(2, 1, Some(0));
        let hypr_data = HyprlandData {
            clients,
            workspaces,
            monitors: vec![],
        };
        let active = Active {
            client: None,
            workspace: 0,
            monitor: 0,
        };
        trace!("data: {hypr_data:?}");

        assert_eq!(
            find_next_workspace(&Direction::Right, true, &hypr_data, active, 3),
            active
        );
        assert_eq!(
            find_next_workspace(&Direction::Left, true, &hypr_data, active, 3),
            active
        );
        assert_eq!(
            find_next_workspace(&Direction::Up, true, &hypr_data, active, 3),
            active
        );
        assert_eq!(
            find_next_workspace(&Direction::Down, true, &hypr_data, active, 3),
            active
        );
        assert_eq!(
            find_next_workspace(&Direction::Right, false, &hypr_data, active, 3),
            active
        );
        assert_eq!(
            find_next_workspace(&Direction::Left, false, &hypr_data, active, 3),
            active
        );
        assert_eq!(
            find_next_workspace(&Direction::Up, false, &hypr_data, active, 3),
            active
        );
        assert_eq!(
            find_next_workspace(&Direction::Down, false, &hypr_data, active, 3),
            active
        );
    }

    #[test_log::test]
    #[test_log(default_log_filter = "trace")]
    fn test_find_next_workspace_1() {
        let (clients, workspaces) = create_test_data(1, 1, None);
        let hypr_data = HyprlandData {
            clients,
            workspaces,
            monitors: vec![],
        };
        let active = Active {
            client: None,
            workspace: 0,
            monitor: 0,
        };
        trace!("data: {hypr_data:?}");

        assert_eq!(
            find_next_workspace(&Direction::Right, true, &hypr_data, active, 3),
            active
        );
        assert_eq!(
            find_next_workspace(&Direction::Left, true, &hypr_data, active, 3),
            active
        );
        assert_eq!(
            find_next_workspace(&Direction::Up, true, &hypr_data, active, 3),
            active
        );
        assert_eq!(
            find_next_workspace(&Direction::Down, true, &hypr_data, active, 3),
            active
        );
        assert_eq!(
            find_next_workspace(&Direction::Right, false, &hypr_data, active, 3),
            active
        );
        assert_eq!(
            find_next_workspace(&Direction::Left, false, &hypr_data, active, 3),
            active
        );
        assert_eq!(
            find_next_workspace(&Direction::Up, false, &hypr_data, active, 3),
            active
        );
        assert_eq!(
            find_next_workspace(&Direction::Down, false, &hypr_data, active, 3),
            active
        );
    }
    #[test_log::test]
    #[test_log(default_log_filter = "trace")]
    fn test_find_next_workspace_2() {
        let (clients, workspaces) = create_test_data(5, 5, None);
        let hypr_data = HyprlandData {
            clients,
            workspaces,
            monitors: vec![],
        };
        let active = Active {
            client: None,
            workspace: 0,
            monitor: 0,
        };
        trace!("data: {hypr_data:?}");

        let next = find_next_workspace(&Direction::Right, true, &hypr_data, active, 3);
        assert_eq!(next.workspace, 1);
        let next = find_next_workspace(&Direction::Left, true, &hypr_data, active, 3);
        assert_eq!(next.workspace, 4);

        let next = find_next_workspace(&Direction::Up, true, &hypr_data, active, 3);
        assert_eq!(next.workspace, 3);
        let next = find_next_workspace(&Direction::Down, true, &hypr_data, active, 3);
        assert_eq!(next.workspace, 3);

        let next = find_next_workspace(&Direction::Right, false, &hypr_data, active, 3);
        assert_eq!(next.workspace, 1);
        let next = find_next_workspace(&Direction::Left, false, &hypr_data, active, 3);
        assert_eq!(next.workspace, 0);

        let next = find_next_workspace(&Direction::Up, false, &hypr_data, active, 3);
        assert_eq!(next.workspace, 0);
        let next = find_next_workspace(&Direction::Down, false, &hypr_data, active, 3);
        assert_eq!(next.workspace, 3);
    }

    #[test_log::test]
    #[test_log(default_log_filter = "trace")]
    fn test_find_next_workspace_2_filter() {
        let (clients, workspaces) = create_test_data(5, 5, Some(2));
        let hypr_data = HyprlandData {
            clients,
            workspaces,
            monitors: vec![],
        };
        let active = Active {
            client: None,
            workspace: 0,
            monitor: 0,
        };
        trace!("data: {hypr_data:?}");

        let next = find_next_workspace(&Direction::Right, true, &hypr_data, active, 3);
        assert_eq!(next.workspace, 1);
        let next = find_next_workspace(&Direction::Left, true, &hypr_data, active, 3);
        assert_eq!(next.workspace, 2);

        let next = find_next_workspace(&Direction::Up, true, &hypr_data, active, 3);
        assert_eq!(next.workspace, 0);
        let next = find_next_workspace(&Direction::Down, true, &hypr_data, active, 3);
        assert_eq!(next.workspace, 0);

        let next = find_next_workspace(&Direction::Right, false, &hypr_data, active, 3);
        assert_eq!(next.workspace, 1);
        let next = find_next_workspace(&Direction::Left, false, &hypr_data, active, 3);
        assert_eq!(next.workspace, 0);

        let next = find_next_workspace(&Direction::Up, false, &hypr_data, active, 3);
        assert_eq!(next.workspace, 0);
        let next = find_next_workspace(&Direction::Down, false, &hypr_data, active, 3);
        assert_eq!(next.workspace, 2);
    }

    #[test_log::test]
    #[test_log(default_log_filter = "trace")]
    fn test_find_next_client() {
        // Test with no clients
        let (clients, workspaces) = create_test_data(0, 1, None);
        let hypr_data = HyprlandData {
            clients,
            workspaces,
            monitors: vec![],
        };
        let active = Active {
            client: None,
            workspace: 0,
            monitor: 0,
        };
        trace!("data: {hypr_data:?}");

        assert_eq!(
            find_next_client(&Direction::Right, true, &hypr_data, active, 3),
            active
        );

        // Test with one client
        let (clients, workspaces) = create_test_data(1, 1, None);
        let hypr_data = HyprlandData {
            clients,
            workspaces,
            monitors: vec![],
        };
        trace!("data: {hypr_data:?}");

        let next = find_next_client(&Direction::Right, true, &hypr_data, active, 3);
        assert_eq!(
            next,
            Active {
                client: Some(0),
                workspace: 0,
                monitor: 0,
            }
        );

        // Test with multiple clients
        let (clients, workspaces) = create_test_data(4, 2, None);
        let hypr_data = HyprlandData {
            clients,
            workspaces,
            monitors: vec![],
        };
        trace!("data: {hypr_data:?}");

        // Test with no active client
        let next = find_next_client(&Direction::Right, true, &hypr_data, active, 3);
        assert_eq!(next.client, Some(0));

        // Test with active client
        let active = Active {
            client: Some(1),
            workspace: 1,
            monitor: 0,
        };

        // Test right direction with wrap
        let next = find_next_client(&Direction::Right, true, &hypr_data, active, 3);
        assert_eq!(next.client, Some(2));

        // Test left direction with wrap
        let next = find_next_client(&Direction::Left, true, &hypr_data, active, 3);
        assert_eq!(next.client, Some(0));

        // Test without wrap
        let next = find_next_client(&Direction::Right, false, &hypr_data, active, 3);
        assert_eq!(next.client, Some(2));
    }
}